diff --git a/drizzle/0002_mature_mephistopheles.sql b/drizzle/0002_mature_mephistopheles.sql new file mode 100644 index 00000000..dc807fd7 --- /dev/null +++ b/drizzle/0002_mature_mephistopheles.sql @@ -0,0 +1,10 @@ +CREATE TABLE `transcripts` ( + `segment_id` text PRIMARY KEY NOT NULL, + `source_file` text NOT NULL, + `status` text DEFAULT 'processing' NOT NULL, + `language` text, + `text` text, + `lines` text, + `created_at` integer DEFAULT (unixepoch('subsec') * 1000) NOT NULL, + FOREIGN KEY (`segment_id`) REFERENCES `segments`(`id`) ON UPDATE no action ON DELETE cascade +); diff --git a/drizzle/0003_fair_baron_zemo.sql b/drizzle/0003_fair_baron_zemo.sql new file mode 100644 index 00000000..ab72b932 --- /dev/null +++ b/drizzle/0003_fair_baron_zemo.sql @@ -0,0 +1,6 @@ +CREATE TABLE `settings` ( + `key` text PRIMARY KEY NOT NULL, + `value` text +); +--> statement-breakpoint +ALTER TABLE `transcripts` ADD `model` text; \ No newline at end of file diff --git a/drizzle/meta/0002_snapshot.json b/drizzle/meta/0002_snapshot.json new file mode 100644 index 00000000..550a4cfc --- /dev/null +++ b/drizzle/meta/0002_snapshot.json @@ -0,0 +1,256 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "a4403da4-3590-4c0f-ae0c-68fd450e1351", + "prevId": "68650116-7c34-4ab1-80c9-97209df7cbb8", + "tables": { + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'camera'" + }, + "thumbnail": { + "name": "thumbnail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "upload_server": { + "name": "upload_server", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "upload_token": { + "name": "upload_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + }, + "last_modified": { + "name": "last_modified", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "segments": { + "name": "segments", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "original_filename": { + "name": "original_filename", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "edited_filename": { + "name": "edited_filename", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "edited_duration_ms": { + "name": "edited_duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "trim_start_ms": { + "name": "trim_start_ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "trim_end_ms": { + "name": "trim_end_ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "thumbnail": { + "name": "thumbnail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "segments_project_id_projects_id_fk": { + "name": "segments_project_id_projects_id_fk", + "tableFrom": "segments", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "transcripts": { + "name": "transcripts", + "columns": { + "segment_id": { + "name": "segment_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "source_file": { + "name": "source_file", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'processing'" + }, + "language": { + "name": "language", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lines": { + "name": "lines", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": {}, + "foreignKeys": { + "transcripts_segment_id_segments_id_fk": { + "name": "transcripts_segment_id_segments_id_fk", + "tableFrom": "transcripts", + "tableTo": "segments", + "columnsFrom": [ + "segment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/0003_snapshot.json b/drizzle/meta/0003_snapshot.json new file mode 100644 index 00000000..f409d00f --- /dev/null +++ b/drizzle/meta/0003_snapshot.json @@ -0,0 +1,287 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "b66d4db3-d6b3-4ce1-aaf8-e1151eb03372", + "prevId": "a4403da4-3590-4c0f-ae0c-68fd450e1351", + "tables": { + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'camera'" + }, + "thumbnail": { + "name": "thumbnail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "upload_server": { + "name": "upload_server", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "upload_token": { + "name": "upload_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + }, + "last_modified": { + "name": "last_modified", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "segments": { + "name": "segments", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "original_filename": { + "name": "original_filename", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "edited_filename": { + "name": "edited_filename", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "edited_duration_ms": { + "name": "edited_duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "trim_start_ms": { + "name": "trim_start_ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "trim_end_ms": { + "name": "trim_end_ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "thumbnail": { + "name": "thumbnail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "segments_project_id_projects_id_fk": { + "name": "segments_project_id_projects_id_fk", + "tableFrom": "segments", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "transcripts": { + "name": "transcripts", + "columns": { + "segment_id": { + "name": "segment_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "source_file": { + "name": "source_file", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'processing'" + }, + "language": { + "name": "language", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lines": { + "name": "lines", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch('subsec') * 1000)" + } + }, + "indexes": {}, + "foreignKeys": { + "transcripts_segment_id_segments_id_fk": { + "name": "transcripts_segment_id_segments_id_fk", + "tableFrom": "transcripts", + "tableTo": "segments", + "columnsFrom": [ + "segment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 752d4b98..778c07e1 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -15,6 +15,20 @@ "when": 1781146305067, "tag": "0001_gifted_quentin_quire", "breakpoints": true + }, + { + "idx": 2, + "version": "6", + "when": 1781385753195, + "tag": "0002_mature_mephistopheles", + "breakpoints": true + }, + { + "idx": 3, + "version": "6", + "when": 1781387303622, + "tag": "0003_fair_baron_zemo", + "breakpoints": true } ] } \ No newline at end of file diff --git a/drizzle/migrations.js b/drizzle/migrations.js index d84a0080..754455b1 100644 --- a/drizzle/migrations.js +++ b/drizzle/migrations.js @@ -3,12 +3,16 @@ import journal from './meta/_journal.json'; import m0000 from './0000_rainy_hex.sql'; import m0001 from './0001_gifted_quentin_quire.sql'; +import m0002 from './0002_mature_mephistopheles.sql'; +import m0003 from './0003_fair_baron_zemo.sql'; export default { journal, migrations: { m0000, -m0001 +m0001, +m0002, +m0003 } } \ No newline at end of file diff --git a/jest.config.js b/jest.config.js new file mode 100644 index 00000000..1004209a --- /dev/null +++ b/jest.config.js @@ -0,0 +1,9 @@ +// Lightweight unit-test runner for the project's PURE logic (timeline math, transcription +// decisions, model catalog) — no React/React Native rendering. Files are transformed with the +// project's Babel config, and the `@/` path alias is mapped to `src/`. +module.exports = { + testEnvironment: 'node', + transform: { '^.+\\.[jt]sx?$': 'babel-jest' }, + moduleNameMapper: { '^@/(.*)$': '/src/$1' }, + testMatch: ['/src/**/*.test.ts'], +}; diff --git a/package-lock.json b/package-lock.json index 596978b1..c0a5f399 100644 --- a/package-lock.json +++ b/package-lock.json @@ -41,15 +41,19 @@ "react-native-svg": "15.15.4", "react-native-video-trim": "file:modules/react-native-video-trim", "react-native-web": "~0.21.0", - "react-native-worklets": "0.8.3" + "react-native-worklets": "0.8.3", + "whisper.rn": "0.6.0" }, "devDependencies": { + "@jest/globals": "^29.7.0", "@types/react": "~19.2.2", + "babel-jest": "^29.7.0", "babel-plugin-inline-import": "^3.0.0", "drizzle-kit": "^0.31.10", "eslint": "^9.0.0", "eslint-config-expo": "~56.0.4", "eslint-config-prettier": "^10.1.8", + "jest": "^29.7.0", "prettier": "^3.8.3", "typescript": "~6.0.3" } @@ -25192,6 +25196,22 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/whisper.rn": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/whisper.rn/-/whisper.rn-0.6.0.tgz", + "integrity": "sha512-zuwIdiZzUYZDZSrGRBrM7kNknWWYCPT6BcGgmhTlZ5Z8k0QTtHRV/RxhmqrXZ8PAgh8FtUyrH3aQJptrsOHDDA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "^5.2.1" + }, + "engines": { + "node": ">=20.19.4" + }, + "peerDependencies": { + "react": "*", + "react-native": "*" + } + }, "node_modules/widest-line": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-5.0.0.tgz", diff --git a/package.json b/package.json index d3719fa6..56d7e4e2 100644 --- a/package.json +++ b/package.json @@ -36,15 +36,19 @@ "react-native-svg": "15.15.4", "react-native-video-trim": "file:modules/react-native-video-trim", "react-native-web": "~0.21.0", - "react-native-worklets": "0.8.3" + "react-native-worklets": "0.8.3", + "whisper.rn": "0.6.0" }, "devDependencies": { + "@jest/globals": "^29.7.0", "@types/react": "~19.2.2", + "babel-jest": "^29.7.0", "babel-plugin-inline-import": "^3.0.0", "drizzle-kit": "^0.31.10", "eslint": "^9.0.0", "eslint-config-expo": "~56.0.4", "eslint-config-prettier": "^10.1.8", + "jest": "^29.7.0", "prettier": "^3.8.3", "typescript": "~6.0.3" }, @@ -55,6 +59,7 @@ "ios": "expo run:ios", "web": "expo start --web", "lint": "expo lint", + "test": "jest", "format": "prettier --write .", "format:check": "prettier --check ." }, diff --git a/src/app/_layout.tsx b/src/app/_layout.tsx index b07fc8ee..0609db58 100644 --- a/src/app/_layout.tsx +++ b/src/app/_layout.tsx @@ -4,6 +4,7 @@ import { GestureHandlerRootView } from 'react-native-gesture-handler'; import { SafeAreaProvider } from 'react-native-safe-area-context'; import { MigrationGate } from '@/db/migrate'; +import { TranscriptionProvider } from '@/features/transcription/transcription-provider'; import { useColorScheme } from '@/hooks/use-color-scheme'; export default function RootLayout() { @@ -14,10 +15,12 @@ export default function RootLayout() { - - - - + + + + + + diff --git a/src/app/export.tsx b/src/app/export.tsx index 25717597..e8c16662 100644 --- a/src/app/export.tsx +++ b/src/app/export.tsx @@ -3,7 +3,7 @@ import { useLiveQuery } from 'drizzle-orm/expo-sqlite'; import { useLocalSearchParams } from 'expo-router'; import { SymbolView } from 'expo-symbols'; import { useVideoPlayer, VideoView } from 'expo-video'; -import { useState } from 'react'; +import { useEffect, useState } from 'react'; import { ActivityIndicator, Alert, Pressable, StyleSheet, View } from 'react-native'; import { shareAsync } from 'expo-sharing'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; @@ -18,6 +18,7 @@ import { useExport } from '@/features/export/use-export'; import { MergeProgressRing } from '@/features/export/merge-progress-ring'; import { useSaveToDocuments } from '@/features/export/use-save-to-documents'; import { useSaveToPhotos } from '@/features/export/use-save-to-photos'; +import { setActiveDraft } from '@/features/transcription/active-draft'; import { formatClipCount, formatDuration } from '@/utils/format'; import { effMs } from '@/utils/segment-window'; @@ -29,6 +30,11 @@ export default function ExportScreen() { const { draftId } = useLocalSearchParams<{ draftId?: string }>(); const { data: segments } = useLiveQuery(segmentsForDraft(draftId ?? ''), [draftId]); + // Tell the engine which draft is on screen so any missing captions for it are generated first. + useEffect(() => { + setActiveDraft(draftId ?? null); + return () => setActiveDraft(null); + }, [draftId]); // Zero-length clips (failed native reads) can't be concatenated — drop them before merging. const clips = segments.filter((s) => effMs(s) > 0); const { state, retry } = useExport(clips); diff --git a/src/app/index.tsx b/src/app/index.tsx index 5e29fc29..7ee39d07 100644 --- a/src/app/index.tsx +++ b/src/app/index.tsx @@ -10,10 +10,18 @@ import { ThemedText } from '@/components/themed-text'; import { ThemedView } from '@/components/themed-view'; import { Spacing } from '@/constants/theme'; import { deleteDraft, draftListQuery, renameDraft } from '@/db/drafts'; -import { clearDrafts, seedDraft, seedSpeedMixed, seedSpeedUniform } from '@/dev/seed'; +import { selectedModelQuery } from '@/db/settings'; import { DraftCard } from '@/features/home/draft-card'; +import { ModelSwitcherModal } from '@/features/transcription/model-switcher-modal'; +import { getModel } from '@/features/transcription/models'; import { useTheme } from '@/hooks/use-theme'; +// Dev-only seeding controls, behind a `__DEV__`-guarded require so the component and `@/dev/seed` +// (with its perf fixtures) are dead-code-eliminated from the production bundle, not just hidden. +const DevSeedRow = __DEV__ + ? (require('@/dev/dev-seed-row') as typeof import('@/dev/dev-seed-row')).DevSeedRow + : null; + type DraftRef = { id: string; name: string | null; anchor: Anchor }; export default function HomeScreen() { @@ -30,6 +38,13 @@ export default function HomeScreen() { // Rows hidden optimistically while their delete is in flight. const [deletingIds, setDeletingIds] = useState>(new Set()); + // On-device AI: the globally-selected model (persisted) that powers captions today and more + // on-device features later. Download + library-wide work runs in the background engine + // (TranscriptionProvider); here we just open the panel and reflect whether a model is active. + const { data: modelRow } = useLiveQuery(selectedModelQuery, []); + const selectedModel = getModel(modelRow[0]?.value); + const [pickerOpen, setPickerOpen] = useState(false); + if ( pendingRename && drafts.some((d) => d.id === pendingRename.id && d.name === pendingRename.name) @@ -112,32 +127,30 @@ export default function HomeScreen() { Pulse - {__DEV__ && ( - - void seedDraft()} hitSlop={8}> - - + seed - - - void seedSpeedUniform()} hitSlop={8}> - - + s2 - - - void seedSpeedMixed()} hitSlop={8}> - - + s3 - - - void clearDrafts()} hitSlop={8}> - - clear - - - - )} + setPickerOpen(true)} + hitSlop={12} + accessibilityRole="button" + accessibilityLabel="On-device AI" + style={styles.aiButton}> + + + AI + + + {/* Dev-only seeding controls live on their own line so they never crowd the AI action. */} + {DevSeedRow && ( + + + + )} + {visibleDrafts.length === 0 ? ( @@ -193,6 +206,8 @@ export default function HomeScreen() { ]}> + + setPickerOpen(false)} /> ); } @@ -203,14 +218,15 @@ const styles = StyleSheet.create({ }, header: { flexDirection: 'row', - alignItems: 'flex-end', + alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: Spacing.four, paddingBottom: Spacing.two, }, - devRow: { - flexDirection: 'row', - gap: Spacing.three, + aiButton: { flexDirection: 'row', alignItems: 'center', gap: Spacing.one }, + devRowWrap: { + alignItems: 'flex-end', + paddingHorizontal: Spacing.four, paddingBottom: Spacing.two, }, list: { diff --git a/src/app/recorder.tsx b/src/app/recorder.tsx index 2d68c5d8..f27b269c 100644 --- a/src/app/recorder.tsx +++ b/src/app/recorder.tsx @@ -22,6 +22,9 @@ import { useRecorderGestures } from '@/features/recorder/use-recorder-gestures'; import { useRecorderPermissions } from '@/features/recorder/use-recorder-permissions'; import { useRecordingTimer } from '@/features/recorder/use-recording-timer'; import { useVideoTrim } from '@/features/recorder/use-video-trim'; +import { setActiveDraft } from '@/features/transcription/active-draft'; +import { setRecordingActive } from '@/features/transcription/recording-signal'; +import { useDraftTranscripts } from '@/features/transcription/use-draft-transcripts'; import { formatDurationPadded } from '@/utils/format'; export default function RecorderScreen() { @@ -64,6 +67,21 @@ export default function RecorderScreen() { const preview = usePreview(segments, previewId); const previewing = previewId != null; + // Captions for this draft (read-only) — generation happens in the global background engine + // (TranscriptionProvider). Mirror the recording state into the engine's signal so Whisper yields + // while the camera is capturing. + const transcripts = useDraftTranscripts(draftId); + useEffect(() => { + setRecordingActive(isRecording); + }, [isRecording]); + useEffect(() => () => setRecordingActive(false), []); + + // Tell the engine which draft is on screen so its clips are captioned first. + useEffect(() => { + setActiveDraft(draftId); + return () => setActiveDraft(null); + }, [draftId]); + // Top running timer: always the live draft total — saved clips plus wall-clock while // recording. During preview the playhead position is shown inside the preview card instead. const totalMs = useRecordingTimer(segments, recordStartedAt); @@ -165,6 +183,8 @@ export default function RecorderScreen() { isPlaying={preview.isPlaying} positionMs={preview.globalMs} totalMs={preview.totalMs} + captionMs={preview.positionMs} + transcript={preview.activeId ? transcripts.get(preview.activeId) : undefined} onTogglePlay={preview.togglePlay} onClose={() => setPreviewId(null)} onTrim={() => { diff --git a/src/db/drafts.ts b/src/db/drafts.ts index 1828669a..1a4b35df 100644 --- a/src/db/drafts.ts +++ b/src/db/drafts.ts @@ -43,6 +43,9 @@ export function segmentsForDraft(projectId: string) { .orderBy(asc(segments.order)); } +/** Every segment in the library — drives the global background transcription engine. */ +export const allSegmentsQuery = db.select().from(segments); + // Mutations — each is a single-row write that autosaves the draft (§3). export async function createDraft(): Promise { diff --git a/src/db/schema.ts b/src/db/schema.ts index d19a050e..bdab38c4 100644 --- a/src/db/schema.ts +++ b/src/db/schema.ts @@ -46,5 +46,35 @@ export const segments = sqliteTable('segments', { thumbnail: text('thumbnail'), }); +/** + * On-device speech-to-text for a clip's audio (whisper.rn). One row per segment, keyed by the + * EFFECTIVE file it was produced from (`sourceFile`); a destructive edit changes the effective + * file, which invalidates the stored transcript and triggers a re-run. `lines` is JSON of + * `Array<{ text, t0, t1 }>` where t0/t1 are centiseconds relative to the clip's audio start. + */ +export const transcripts = sqliteTable('transcripts', { + segmentId: text('segment_id') + .primaryKey() + .references(() => segments.id, { onDelete: 'cascade' }), + sourceFile: text('source_file').notNull(), + // The Whisper model id that produced (or is producing) this transcript. When the user switches + // models, rows whose `model` no longer matches the selection are re-transcribed. + model: text('model'), + status: text('status', { enum: ['processing', 'done', 'error'] }) + .notNull() + .default('processing'), + language: text('language'), + text: text('text'), + lines: text('lines'), + createdAt: integer('created_at').notNull().default(now), +}); + +/** App-wide key/value settings (e.g. the selected transcription model). */ +export const settings = sqliteTable('settings', { + key: text('key').primaryKey(), + value: text('value'), +}); + export type Project = typeof projects.$inferSelect; export type Segment = typeof segments.$inferSelect; +export type Transcript = typeof transcripts.$inferSelect; diff --git a/src/db/settings.ts b/src/db/settings.ts new file mode 100644 index 00000000..28d8293d --- /dev/null +++ b/src/db/settings.ts @@ -0,0 +1,24 @@ +import { eq } from 'drizzle-orm'; + +import { db } from './client'; +import { settings } from './schema'; + +const SELECTED_MODEL_KEY = 'transcription.model'; + +/** Live-queryable: the selected transcription model id (a single settings row). */ +export const selectedModelQuery = db + .select({ value: settings.value }) + .from(settings) + .where(eq(settings.key, SELECTED_MODEL_KEY)); + +/** Set (or clear, with `null`) the selected transcription model id. */ +export async function setSelectedModel(id: string | null): Promise { + if (id === null) { + await db.delete(settings).where(eq(settings.key, SELECTED_MODEL_KEY)); + return; + } + await db + .insert(settings) + .values({ key: SELECTED_MODEL_KEY, value: id }) + .onConflictDoUpdate({ target: settings.key, set: { value: id } }); +} diff --git a/src/db/transcripts.ts b/src/db/transcripts.ts new file mode 100644 index 00000000..281a18f6 --- /dev/null +++ b/src/db/transcripts.ts @@ -0,0 +1,84 @@ +import { eq } from 'drizzle-orm'; + +import type { TranscriptResult } from '@/features/transcription/whisper'; +import { db } from './client'; +import { segments, transcripts } from './schema'; + +/** Live-queryable: all transcript rows for a draft's segments (joined via the segment FK). */ +export function transcriptsForDraft(projectId: string) { + return db + .select({ + segmentId: transcripts.segmentId, + sourceFile: transcripts.sourceFile, + model: transcripts.model, + status: transcripts.status, + language: transcripts.language, + text: transcripts.text, + lines: transcripts.lines, + }) + .from(transcripts) + .innerJoin(segments, eq(segments.id, transcripts.segmentId)) + .where(eq(segments.projectId, projectId)); +} + +/** Live-queryable: every transcript row (status/model/file) — the engine's needs-check source. */ +export const allTranscriptsQuery = db + .select({ + segmentId: transcripts.segmentId, + sourceFile: transcripts.sourceFile, + model: transcripts.model, + status: transcripts.status, + }) + .from(transcripts); + +/** Drop every transcript (e.g. on a model switch, so captions regenerate from scratch). */ +export async function clearAllTranscripts(): Promise { + await db.delete(transcripts); +} + +/** Mark a segment's transcript in-progress for a given effective file + model (insert or replace). */ +export async function markTranscribing( + segmentId: string, + sourceFile: string, + model: string, +): Promise { + await db + .insert(transcripts) + .values({ segmentId, sourceFile, model, status: 'processing' }) + .onConflictDoUpdate({ + target: transcripts.segmentId, + set: { sourceFile, model, status: 'processing', text: null, lines: null, language: null }, + }); +} + +/** Persist a completed transcription result. */ +export async function saveTranscript( + segmentId: string, + sourceFile: string, + model: string, + result: TranscriptResult, +): Promise { + await db + .update(transcripts) + .set({ + sourceFile, + model, + status: 'done', + language: result.language, + text: result.text, + lines: JSON.stringify(result.lines), + }) + .where(eq(transcripts.segmentId, segmentId)); +} + +/** Mark a segment's transcription as failed for a given effective file + model. */ +export async function markTranscriptError( + segmentId: string, + sourceFile: string, + model: string, +): Promise { + await db + .update(transcripts) + .set({ sourceFile, model, status: 'error', text: null, lines: null }) + .where(eq(transcripts.segmentId, segmentId)); +} diff --git a/src/dev/dev-seed-row.tsx b/src/dev/dev-seed-row.tsx new file mode 100644 index 00000000..41727b60 --- /dev/null +++ b/src/dev/dev-seed-row.tsx @@ -0,0 +1,45 @@ +import { Pressable, StyleSheet, View } from 'react-native'; + +import { ThemedText } from '@/components/themed-text'; +import { Spacing } from '@/constants/theme'; +import { clearDrafts, seedDraft, seedSpeedMixed, seedSpeedUniform } from '@/dev/seed'; + +/** + * Dev-only seeding controls for the home header. Lives in its own module so it can be loaded behind + * a `__DEV__`-guarded `require` (see HomeScreen) — that keeps this component AND `@/dev/seed` (with + * its perf-test fixtures) out of the production bundle entirely, not just hidden at runtime. + */ +export function DevSeedRow() { + return ( + + void seedDraft()} hitSlop={8}> + + + seed + + + void seedSpeedUniform()} hitSlop={8}> + + + s2 + + + void seedSpeedMixed()} hitSlop={8}> + + + s3 + + + void clearDrafts()} hitSlop={8}> + + clear + + + + ); +} + +const styles = StyleSheet.create({ + devRow: { + flexDirection: 'row', + alignItems: 'center', + gap: Spacing.three, + }, +}); diff --git a/src/features/recorder/preview-modal.tsx b/src/features/recorder/preview-modal.tsx index de1ecc77..c5637e43 100644 --- a/src/features/recorder/preview-modal.tsx +++ b/src/features/recorder/preview-modal.tsx @@ -3,6 +3,7 @@ import { VideoView, type VideoPlayer } from 'expo-video'; import { Pressable, StyleSheet, Text, View } from 'react-native'; import { Spacing } from '@/constants/theme'; +import type { SegmentTranscript } from '@/features/transcription/use-draft-transcripts'; import { formatDurationPadded } from '@/utils/format'; type Props = { @@ -11,12 +12,22 @@ type Props = { // Draft-global playhead position and total, for the time readout pill. positionMs: number; totalMs: number; + // Playback position WITHIN the active clip (ms), used to sync the caption line. + captionMs: number; + // The active clip's transcript (undefined until transcription has run for it). + transcript?: SegmentTranscript; onTogglePlay: () => void; onClose: () => void; onTrim: () => void; onDelete: () => void; }; +/** The caption line covering the current playback position (whisper t0/t1 are centiseconds). */ +function activeLine(transcript: SegmentTranscript | undefined, captionMs: number) { + if (transcript?.status !== 'done') return undefined; + return transcript.lines.find((l) => captionMs >= l.t0 * 10 && captionMs <= l.t1 * 10); +} + /** * Floating preview card over the recorder — the camera UI, record button, and segment bar * all stay visible around it. Plays the draft through one shared player; tap toggles play, @@ -28,11 +39,14 @@ export function PreviewModal({ isPlaying, positionMs, totalMs, + captionMs, + transcript, onTogglePlay, onClose, onTrim, onDelete, }: Props) { + const line = activeLine(transcript, captionMs); return ( @@ -78,6 +92,26 @@ export function PreviewModal({ + + {transcript?.status === 'processing' && ( + + Transcribing… + + )} + {transcript?.status === 'error' && ( + + Transcription unavailable + + )} + {line && ( + + + {line.text.trim()} + + + )} + + @@ -137,6 +171,33 @@ const styles = StyleSheet.create({ trim: { right: Spacing.two + 28 + Spacing.two, }, + // Sits just above the time pill; captions are centered and wrap up to 3 lines. + captionRow: { + position: 'absolute', + left: Spacing.two, + right: Spacing.two, + bottom: Spacing.two + 28, + alignItems: 'center', + }, + captionPill: { + paddingHorizontal: Spacing.two, + paddingVertical: Spacing.one, + borderRadius: 10, + backgroundColor: 'rgba(0,0,0,0.6)', + }, + captionText: { + color: '#fff', + fontSize: 14, + lineHeight: 19, + fontWeight: '600', + textAlign: 'center', + }, + captionMuted: { + color: 'rgba(255,255,255,0.75)', + fontSize: 12, + fontWeight: '600', + fontStyle: 'italic', + }, timeRow: { position: 'absolute', left: 0, diff --git a/src/features/transcription/active-draft.ts b/src/features/transcription/active-draft.ts new file mode 100644 index 00000000..d0277804 --- /dev/null +++ b/src/features/transcription/active-draft.ts @@ -0,0 +1,13 @@ +// A module-level pointer to the draft the user is currently looking at (recorder/export). The +// background transcription engine reads it to caption that draft's clips *first*, so captions for +// what's on screen appear quickly instead of waiting behind the rest of the library. It's a plain +// signal (not React state) — the engine reads it when it builds each work batch; no render churn. +let activeDraftId: string | null = null; + +export function setActiveDraft(id: string | null): void { + activeDraftId = id; +} + +export function getActiveDraft(): string | null { + return activeDraftId; +} diff --git a/src/features/transcription/model-switcher-modal.tsx b/src/features/transcription/model-switcher-modal.tsx new file mode 100644 index 00000000..5772f55c --- /dev/null +++ b/src/features/transcription/model-switcher-modal.tsx @@ -0,0 +1,218 @@ +import { useLiveQuery } from 'drizzle-orm/expo-sqlite'; +import { SymbolView } from 'expo-symbols'; +import { + ActivityIndicator, + Alert, + Modal, + Pressable, + ScrollView, + StyleSheet, + View, +} from 'react-native'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; + +import { ThemedText } from '@/components/themed-text'; +import { Spacing } from '@/constants/theme'; +import { selectedModelQuery, setSelectedModel } from '@/db/settings'; +import { useTheme } from '@/hooks/use-theme'; +import { isModelReady } from './model'; +import { getModel, LARGE_MODEL_BYTES, MODELS } from './models'; +import { useTranscriptionStatus } from './transcription-provider'; + +const sizeMb = (bytes: number) => `${(bytes / (1024 * 1024)).toFixed(0)} MB`; + +function statusLine(status: ReturnType): string | null { + switch (status.kind) { + case 'deleting': + return 'Removing previous model…'; + case 'downloading': { + const pct = + status.totalBytes > 0 ? Math.round((status.bytesWritten / status.totalBytes) * 100) : 0; + return `Downloading model… ${pct}%`; + } + case 'transcribing': + return `Generating captions… ${status.done}/${status.total}`; + default: + return null; + } +} + +/** + * The on-device AI panel. Today it holds a single section — Captions — but it's structured so + * future on-device features can slot in as additional sections. Selecting a model persists the + * choice, which the global background engine picks up (delete-old → download-new → regenerate + * captions across the library). The panel only records intent and shows live progress; closing + * without selecting downloads nothing. The active model can be removed here to free disk. + */ +export function ModelSwitcherModal({ + visible, + onClose, +}: { + visible: boolean; + onClose: () => void; +}) { + const theme = useTheme(); + const insets = useSafeAreaInsets(); + const { data } = useLiveQuery(selectedModelQuery, []); + const selectedId = data[0]?.value ?? null; + const status = useTranscriptionStatus(); + const busy = statusLine(status); + + const select = (id: string) => { + void setSelectedModel(id); + onClose(); + }; + + const choose = (id: string) => { + if (id === selectedId) { + onClose(); + return; + } + // Warn before kicking off a large download that isn't already on disk (cellular/data cost). + const model = getModel(id); + if (model && model.approxBytes >= LARGE_MODEL_BYTES && !isModelReady(model)) { + Alert.alert( + 'Large download', + `${model.label} is about ${sizeMb(model.approxBytes)}. Download it now? Connect to Wi-Fi to avoid cellular data charges.`, + [ + { text: 'Cancel', style: 'cancel' }, + { text: 'Download', onPress: () => select(id) }, + ], + ); + return; + } + select(id); + }; + + return ( + + + + + + + On-device AI + + Runs entirely on your device — nothing leaves your phone. Powers captions today, with + more features coming. + + + + + + + + {busy && ( + + + + {busy} + + + )} + + {/* First (and currently only) feature. Future on-device features slot in as new sections. */} + + + + Captions + + Auto-transcribe clips with a speech model. Only the selected model is kept on disk. + + + + + + {MODELS.map((m) => { + const active = m.id === selectedId; + return ( + choose(m.id)} + style={[ + styles.row, + { borderColor: theme.border, backgroundColor: theme.backgroundElement }, + active && { borderColor: theme.accent }, + ]}> + + {m.label} + + {m.note} · {sizeMb(m.approxBytes)} + + + {active && ( + + )} + + ); + })} + + + {selectedId && ( + { + void setSelectedModel(null); + onClose(); + }} + hitSlop={8} + accessibilityRole="button" + style={styles.delete}> + + + Remove model & free up space + + + )} + + + + ); +} + +const styles = StyleSheet.create({ + backdrop: { flex: 1, justifyContent: 'flex-end', backgroundColor: 'rgba(0,0,0,0.5)' }, + sheet: { + borderTopLeftRadius: 20, + borderTopRightRadius: 20, + paddingTop: Spacing.four, + paddingHorizontal: Spacing.four, + gap: Spacing.three, + }, + header: { flexDirection: 'row', alignItems: 'flex-start', gap: Spacing.three }, + headerText: { flex: 1, gap: Spacing.one }, + section: { flexDirection: 'row', alignItems: 'flex-start', gap: Spacing.two }, + sectionText: { flex: 1, gap: 2 }, + status: { + flexDirection: 'row', + alignItems: 'center', + gap: Spacing.two, + padding: Spacing.three, + borderRadius: 12, + }, + list: { maxHeight: 360 }, + listContent: { gap: Spacing.two }, + row: { + flexDirection: 'row', + alignItems: 'center', + gap: Spacing.three, + padding: Spacing.three, + borderRadius: 12, + borderWidth: 1, + }, + rowText: { flex: 1, gap: 2 }, + delete: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'center', + gap: Spacing.two, + }, + deleteText: { fontWeight: '700' }, +}); diff --git a/src/features/transcription/model.ts b/src/features/transcription/model.ts new file mode 100644 index 00000000..36478379 --- /dev/null +++ b/src/features/transcription/model.ts @@ -0,0 +1,102 @@ +import { Directory, File, Paths } from 'expo-file-system'; + +import { modelUrl, type WhisperModel } from './models'; + +// On-device Whisper model files live under the document directory (so they survive launches) and +// are downloaded on demand. Only the currently-selected model is kept on disk — switching deletes +// the others — so the app never holds more than one set of weights at a time. +// +// models/ggml-.bin +// +// A partial/interrupted download is shorter than the real file; we treat anything well under the +// model's approximate size as incomplete. +const COMPLETE_FRACTION = 0.7; + +function modelsDir(): Directory { + return new Directory(Paths.document, 'models'); +} + +function modelFile(m: WhisperModel): File { + return new File(Paths.document, 'models', m.filename); +} + +/** Whether the given model is fully downloaded. */ +export function isModelReady(m: WhisperModel): boolean { + const file = modelFile(m); + return file.exists && (file.size ?? 0) >= m.approxBytes * COMPLETE_FRACTION; +} + +/** Absolute file URI of the model's weights (only valid once downloaded). */ +export function modelFileUri(m: WhisperModel): string { + return modelFile(m).uri; +} + +export type ModelProgress = { bytesWritten: number; totalBytes: number }; + +// In-flight downloads keyed by filename, so concurrent callers (e.g. the global lifecycle on Home +// and a transcribe fallback in the recorder) share one download instead of racing on the same file. +// We keep the DownloadTask alongside the promise so a model switch can cancel a now-stale download +// (e.g. abandoning a 574 MB pull) instead of letting it run to completion only to be deleted. +type InFlight = { promise: Promise; task: { cancel: () => void } }; +const inFlight = new Map(); + +/** + * Ensure the given model is on disk, downloading it if missing. Idempotent and safe to call + * concurrently. `onProgress` (from the first caller of an in-flight download) reports byte + * progress. Returns the model's absolute file URI. + */ +export function ensureModel( + m: WhisperModel, + onProgress?: (p: ModelProgress) => void, +): Promise { + const file = modelFile(m); + if (isModelReady(m)) return Promise.resolve(file.uri); + + const existing = inFlight.get(m.filename); + if (existing) return existing.promise; + + if (file.exists) file.delete(); // clear a partial/corrupt prior attempt + modelsDir().create({ intermediates: true, idempotent: true }); + + const task = File.createDownloadTask(modelUrl(m), file, { + onProgress: ({ bytesWritten, totalBytes }) => onProgress?.({ bytesWritten, totalBytes }), + }); + + const promise = (async () => { + await task.downloadAsync(); + if (!isModelReady(m)) { + if (file.exists) file.delete(); + throw new Error('Whisper model download failed or is incomplete'); + } + return file.uri; + })(); + + inFlight.set(m.filename, { promise, task }); + return promise.finally(() => inFlight.delete(m.filename)); +} + +/** + * Cancel any in-flight model download other than `keep` (pass `null` to cancel all). Called on a + * model switch so an abandoned download stops immediately instead of finishing just to be deleted. + * A cancelled download rejects its `ensureModel` promise, which the engine treats like a failed + * download and retries on next selection. + */ +export function cancelModelDownloadsExcept(keep: WhisperModel | null): void { + for (const [filename, entry] of inFlight) { + if (filename !== keep?.filename) entry.task.cancel(); + } +} + +/** + * Delete every downloaded model file except `keep` (pass `null` to delete all). Used when + * switching models so only one set of weights occupies disk at a time. + */ +export function deleteModelsExcept(keep: WhisperModel | null): void { + const dir = modelsDir(); + if (!dir.exists) return; + for (const entry of dir.list()) { + if (entry instanceof File && entry.name.endsWith('.bin') && entry.name !== keep?.filename) { + entry.delete(); + } + } +} diff --git a/src/features/transcription/models.test.ts b/src/features/transcription/models.test.ts new file mode 100644 index 00000000..6681c1d1 --- /dev/null +++ b/src/features/transcription/models.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from '@jest/globals'; + +import { getModel, LARGE_MODEL_BYTES, MODELS, modelUrl } from './models'; + +describe('model catalog', () => { + it('resolves a known id and rejects unknown / nullish ids', () => { + expect(getModel('tiny.en')?.id).toBe('tiny.en'); + expect(getModel('nope')).toBeNull(); + expect(getModel(null)).toBeNull(); + expect(getModel(undefined)).toBeNull(); + }); + + it('builds the Hugging Face GGML url from the filename', () => { + const m = getModel('base.en')!; + expect(modelUrl(m)).toBe( + 'https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-base.en.bin', + ); + }); + + it('pins English-only models to "en" and the multilingual model to "auto"', () => { + // Regression: the multilingual model must NOT be silently forced to English. + for (const m of MODELS) { + const expected = m.id.includes('.en') ? 'en' : 'auto'; + expect(m.lang).toBe(expected); + } + expect(getModel('large-v3-turbo-q5_0')!.lang).toBe('auto'); + }); + + it('only the large model crosses the confirm-before-download threshold', () => { + const large = MODELS.filter((m) => m.approxBytes >= LARGE_MODEL_BYTES); + expect(large.map((m) => m.id)).toEqual(['large-v3-turbo-q5_0']); + }); +}); diff --git a/src/features/transcription/models.ts b/src/features/transcription/models.ts new file mode 100644 index 00000000..d01fcd98 --- /dev/null +++ b/src/features/transcription/models.ts @@ -0,0 +1,64 @@ +// Catalog of on-device Whisper models the user can choose between. All are hosted on the +// whisper.cpp GGML repo. `approxBytes` is only for an initial progress estimate / a completeness +// floor — the real content length comes from the download task. English-only models (`.en`) are +// smaller/faster; large-v3-turbo is multilingual. +const BASE_URL = 'https://huggingface.co/ggerganov/whisper.cpp/resolve/main/'; + +export type WhisperModel = { + id: string; + label: string; + filename: string; + /** Approximate on-disk size, for the size label and a download-completeness floor. */ + approxBytes: number; + /** Short tradeoff note shown in the picker. */ + note: string; + /** + * Decode language passed to Whisper. The `.en` models are English-only, so we pin `'en'`; + * the multilingual model uses `'auto'` so it actually detects the spoken language instead of + * being silently forced to English. + */ + lang: 'en' | 'auto'; +}; + +export const MODELS: WhisperModel[] = [ + { + id: 'tiny.en', + label: 'Tiny (English)', + filename: 'ggml-tiny.en.bin', + approxBytes: 78 * 1024 * 1024, + note: 'Fastest · lowest accuracy', + lang: 'en', + }, + { + id: 'base.en', + label: 'Base (English)', + filename: 'ggml-base.en.bin', + approxBytes: 148 * 1024 * 1024, + note: 'Balanced', + lang: 'en', + }, + { + id: 'small.en-q5_1', + label: 'Small (English)', + filename: 'ggml-small.en-q5_1.bin', + approxBytes: 190 * 1024 * 1024, + note: 'Better accuracy · a bit slower', + lang: 'en', + }, + { + id: 'large-v3-turbo-q5_0', + label: 'Large Turbo', + filename: 'ggml-large-v3-turbo-q5_0.bin', + approxBytes: 574 * 1024 * 1024, + note: 'Best · multilingual · large download', + lang: 'auto', + }, +]; + +/** Models at/above this on-disk size prompt for confirmation before downloading (cellular/data). */ +export const LARGE_MODEL_BYTES = 300 * 1024 * 1024; + +export const getModel = (id: string | null | undefined): WhisperModel | null => + MODELS.find((m) => m.id === id) ?? null; + +export const modelUrl = (m: WhisperModel): string => BASE_URL + m.filename; diff --git a/src/features/transcription/needs-transcription.test.ts b/src/features/transcription/needs-transcription.test.ts new file mode 100644 index 00000000..65518109 --- /dev/null +++ b/src/features/transcription/needs-transcription.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from '@jest/globals'; + +import { needsTranscription, type TranscriptState } from './needs-transcription'; + +const MAX = 2; +const done = (over: Partial = {}): TranscriptState => ({ + model: 'tiny.en', + sourceFile: 'a.mp4', + status: 'done', + ...over, +}); + +describe('needsTranscription', () => { + it('runs when there is no row yet', () => { + expect(needsTranscription('a.mp4', 'tiny.en', undefined, 0, MAX)).toBe(true); + }); + + it('skips a matching, completed row', () => { + expect(needsTranscription('a.mp4', 'tiny.en', done(), 0, MAX)).toBe(false); + }); + + it('re-runs when the effective file changed (destructive edit)', () => { + expect(needsTranscription('edited.mp4', 'tiny.en', done(), 0, MAX)).toBe(true); + }); + + it('re-runs when the model changed', () => { + expect(needsTranscription('a.mp4', 'base.en', done(), 0, MAX)).toBe(true); + }); + + it('resumes a row stranded in processing', () => { + expect(needsTranscription('a.mp4', 'tiny.en', done({ status: 'processing' }), 0, MAX)).toBe(true); + }); + + it('retries an errored row while under the attempt budget', () => { + const row = done({ status: 'error' }); + expect(needsTranscription('a.mp4', 'tiny.en', row, 0, MAX)).toBe(true); + expect(needsTranscription('a.mp4', 'tiny.en', row, 1, MAX)).toBe(true); + }); + + it('gives up on an errored row once the budget is spent', () => { + const row = done({ status: 'error' }); + expect(needsTranscription('a.mp4', 'tiny.en', row, MAX, MAX)).toBe(false); + }); + + it('a file change overrides a spent error budget (fresh file, fresh start)', () => { + const row = done({ status: 'error', sourceFile: 'old.mp4' }); + expect(needsTranscription('new.mp4', 'tiny.en', row, MAX, MAX)).toBe(true); + }); +}); diff --git a/src/features/transcription/needs-transcription.ts b/src/features/transcription/needs-transcription.ts new file mode 100644 index 00000000..67eb34b2 --- /dev/null +++ b/src/features/transcription/needs-transcription.ts @@ -0,0 +1,34 @@ +/** The persisted transcript facts the engine decides from (a subset of the `transcripts` row). */ +export type TranscriptState = { + model: string | null; + sourceFile: string; + status: 'processing' | 'done' | 'error'; +}; + +/** + * Pure decision: does the clip identified by (`effectiveFile`, `modelId`) need (re)transcription, + * given its current DB row and how many times it has already failed this session? + * + * - No row yet → yes. + * - Row was produced from a different file (a destructive edit changed the effective file) → yes. + * - Row was produced by a different model → yes. + * - Done → no. + * - Errored → retry only while under the attempt budget. + * - Processing → yes (stranded by a killed app; resume). + * + * The caller separately skips keys already settled this session; this function is the DB-driven part. + */ +export function needsTranscription( + effectiveFile: string, + modelId: string, + row: TranscriptState | undefined, + errorAttempts: number, + maxAttempts: number, +): boolean { + if (!row) return true; + if (row.sourceFile !== effectiveFile) return true; + if (row.model !== modelId) return true; + if (row.status === 'done') return false; + if (row.status === 'error') return errorAttempts < maxAttempts; + return true; // 'processing' — resume +} diff --git a/src/features/transcription/recording-signal.ts b/src/features/transcription/recording-signal.ts new file mode 100644 index 00000000..56e9cb2b --- /dev/null +++ b/src/features/transcription/recording-signal.ts @@ -0,0 +1,21 @@ +// A tiny module-level flag the recorder sets while the camera is actively recording. The global +// transcription engine checks it between clips and yields, so Whisper inference never competes with +// capture. It's a plain signal (not React state) so updating it from the recorder doesn't trigger +// renders; the engine re-checks it on its own cadence and the recorder pokes it to resume. +let recording = false; +let onResume: (() => void) | null = null; + +export function setRecordingActive(active: boolean): void { + const was = recording; + recording = active; + if (was && !active) onResume?.(); // recording just stopped — let the engine resume +} + +export function isRecordingActive(): boolean { + return recording; +} + +/** The engine registers a callback to be poked when recording stops. */ +export function setResumeHandler(fn: (() => void) | null): void { + onResume = fn; +} diff --git a/src/features/transcription/transcription-provider.tsx b/src/features/transcription/transcription-provider.tsx new file mode 100644 index 00000000..4e5a5c96 --- /dev/null +++ b/src/features/transcription/transcription-provider.tsx @@ -0,0 +1,18 @@ +import { createContext, useContext } from 'react'; + +import { useLibraryTranscription, type TranscriptionStatus } from './use-library-transcription'; + +const StatusContext = createContext({ kind: 'idle' }); + +/** + * Mounts the single global transcription engine for the app's lifetime and exposes its coarse + * status via context. Place once near the root, above all screens, so captions are generated in + * the background regardless of which screen is open. + */ +export function TranscriptionProvider({ children }: { children: React.ReactNode }) { + const status = useLibraryTranscription(); + return {children}; +} + +/** Current background transcription status (idle / deleting / downloading / transcribing). */ +export const useTranscriptionStatus = () => useContext(StatusContext); diff --git a/src/features/transcription/use-draft-transcripts.ts b/src/features/transcription/use-draft-transcripts.ts new file mode 100644 index 00000000..254200a6 --- /dev/null +++ b/src/features/transcription/use-draft-transcripts.ts @@ -0,0 +1,31 @@ +import { useLiveQuery } from 'drizzle-orm/expo-sqlite'; +import { useMemo } from 'react'; + +import { transcriptsForDraft } from '@/db/transcripts'; +import type { TranscriptLine } from './whisper'; + +/** Parsed transcript for one segment, ready for display. */ +export type SegmentTranscript = { + status: 'processing' | 'done' | 'error'; + text: string | null; + lines: TranscriptLine[]; +}; + +/** + * Read-only: the transcripts for a draft's segments, keyed by segment id, for rendering captions. + * Writes are owned by the global background engine (`useLibraryTranscription`); this just observes. + */ +export function useDraftTranscripts(draftId: string | null): Map { + const { data } = useLiveQuery(transcriptsForDraft(draftId ?? ''), [draftId]); + return useMemo(() => { + const map = new Map(); + for (const r of data) { + map.set(r.segmentId, { + status: r.status, + text: r.text, + lines: r.lines ? (JSON.parse(r.lines) as TranscriptLine[]) : [], + }); + } + return map; + }, [data]); +} diff --git a/src/features/transcription/use-library-transcription.ts b/src/features/transcription/use-library-transcription.ts new file mode 100644 index 00000000..cd98a9a4 --- /dev/null +++ b/src/features/transcription/use-library-transcription.ts @@ -0,0 +1,227 @@ +import { useLiveQuery } from 'drizzle-orm/expo-sqlite'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; + +import { allSegmentsQuery } from '@/db/drafts'; +import type { Segment } from '@/db/schema'; +import { selectedModelQuery } from '@/db/settings'; +import { + allTranscriptsQuery, + clearAllTranscripts, + markTranscribing, + markTranscriptError, + saveTranscript, +} from '@/db/transcripts'; +import { absolutize } from '@/utils/file-store'; +import { effFile } from '@/utils/segment-window'; +import { getActiveDraft } from './active-draft'; +import { cancelModelDownloadsExcept, deleteModelsExcept, ensureModel, isModelReady } from './model'; +import { getModel, type WhisperModel } from './models'; +import { needsTranscription } from './needs-transcription'; +import { isRecordingActive, setResumeHandler } from './recording-signal'; +import { releaseVad } from './vad'; +import { releaseWhisper, transcribeVideo } from './whisper'; + +// How many times a clip that errors out is retried within a session before it's given up on. A +// fresh launch resets the count, so a transient failure (device busy, momentary OOM) gets another +// chance next time the app opens, while a genuinely broken clip can't spin forever. +const MAX_TRANSCRIBE_ATTEMPTS = 2; + +/** Global transcription status — drives the picker's status line. */ +export type TranscriptionStatus = + | { kind: 'idle' } + | { kind: 'deleting' } + | { kind: 'downloading'; bytesWritten: number; totalBytes: number } + | { kind: 'transcribing'; done: number; total: number }; + +type Row = { model: string | null; sourceFile: string; status: 'processing' | 'done' | 'error' }; + +/** + * The single, app-wide background transcription engine. Mounted once (see TranscriptionProvider). + * + * Driven by the persisted model selection, it keeps every clip in the library captioned: + * - Selecting a model downloads it (deleting any other), then transcribes the whole library. + * - Switching models **clears all transcripts** (captions vanish everywhere) and regenerates them + * per-segment with the new model — each caption reappears as its clip finishes. + * - Clearing the model releases the context and deletes the weights. + * - New clips (recorded/imported anywhere) are picked up automatically. + * + * All work is background; Whisper yields between clips while the camera is recording. Returns a + * coarse `status` for the picker. + */ +export function useLibraryTranscription(): TranscriptionStatus { + const { data: modelRow, updatedAt } = useLiveQuery(selectedModelQuery, []); + const ready = updatedAt != null; + const model = getModel(modelRow[0]?.value); + + const { data: segments } = useLiveQuery(allSegmentsQuery, []); + const { data: transcriptRows } = useLiveQuery(allTranscriptsQuery, []); + + const [status, setStatus] = useState({ kind: 'idle' }); + + const rowById = useMemo(() => { + const map = new Map(); + for (const r of transcriptRows) { + map.set(r.segmentId, { model: r.model, sourceFile: r.sourceFile, status: r.status }); + } + return map; + }, [transcriptRows]); + + // Live values read inside the long-running async pipeline (writing refs during render is + // disallowed by the React-Compiler lint, so sync them in an effect). + const segmentsRef = useRef(segments); + const rowByIdRef = useRef(rowById); + const modelRef = useRef(model); + useEffect(() => { + segmentsRef.current = segments; + rowByIdRef.current = rowById; + modelRef.current = model; + }); + + // Keys (`id:file:model`) that are settled for this session — transcribed successfully or given up + // on after MAX_TRANSCRIBE_ATTEMPTS — so `needs()` skips them without re-reading the DB. + const processedRef = useRef>(new Set()); + // Per-key failed-attempt counts, so a clip is retried a bounded number of times before being + // abandoned for the session (a relaunch resets this and gives transient failures another go). + const errorAttemptsRef = useRef>(new Map()); + const runningRef = useRef(false); + const dirtyRef = useRef(false); + // Latest `sync` reference, so the lost-wakeup re-check can re-invoke it without making `sync` + // depend on itself (ref assignment happens in an effect — never during render). + const syncRef = useRef<() => Promise>(undefined); + // Tracks the previously-seen model id to detect a genuine switch (vs. the initial load) so we + // only clear existing captions on an actual change, never on app launch. + const prevModelIdRef = useRef(undefined); + + const needs = useCallback((s: Segment, m: WhisperModel): boolean => { + const file = effFile(s); + const key = `${s.id}:${file}:${m.id}`; + if (processedRef.current.has(key)) return false; // settled this session + return needsTranscription( + file, + m.id, + rowByIdRef.current.get(s.id), + errorAttemptsRef.current.get(key) ?? 0, + MAX_TRANSCRIBE_ATTEMPTS, + ); + }, []); + + const sync = useCallback(async () => { + if (runningRef.current) { + dirtyRef.current = true; + return; + } + runningRef.current = true; + try { + do { + dirtyRef.current = false; + const m = modelRef.current; + const curId = m?.id ?? null; + + // Detect a real model change. First resolved value is adopted without clearing (don't wipe + // captions on launch); any later change clears all transcripts so they regenerate. + if (prevModelIdRef.current === undefined) { + prevModelIdRef.current = curId; + } else if (prevModelIdRef.current !== curId) { + prevModelIdRef.current = curId; + processedRef.current.clear(); + await clearAllTranscripts(); + } + + if (!m) { + await releaseWhisper(); + await releaseVad(); + deleteModelsExcept(null); + continue; + } + + // Ensure the selected model is the only one on disk. + if (!isModelReady(m)) { + setStatus({ kind: 'deleting' }); + await releaseWhisper(); + deleteModelsExcept(m); + setStatus({ kind: 'downloading', bytesWritten: 0, totalBytes: m.approxBytes }); + try { + await ensureModel(m, (p) => { + if (modelRef.current?.id === m.id) setStatus({ kind: 'downloading', ...p }); + }); + } catch { + break; // download failed (offline) — user can reselect to retry + } + } + + // Transcribe everything that needs it, yielding while recording. The draft currently on + // screen is captioned first so its captions appear quickly, ahead of the rest of the library. + const pending = segmentsRef.current.filter((s) => needs(s, m)); + const activeDraft = getActiveDraft(); + const todo = activeDraft + ? [ + ...pending.filter((s) => s.projectId === activeDraft), + ...pending.filter((s) => s.projectId !== activeDraft), + ] + : pending; + if (todo.length > 0) { + let done = 0; + setStatus({ kind: 'transcribing', done, total: todo.length }); + for (const s of todo) { + if (modelRef.current?.id !== m.id) { + dirtyRef.current = true; // switched mid-run — restart with the new model + break; + } + if (isRecordingActive()) { + dirtyRef.current = true; // defer; the resume handler re-runs when recording stops + break; + } + const file = effFile(s); + const key = `${s.id}:${file}:${m.id}`; + try { + await markTranscribing(s.id, file, m.id); + const result = await transcribeVideo(absolutize(file), m); + await saveTranscript(s.id, file, m.id, result); + processedRef.current.add(key); // done — settled for the session + } catch { + await markTranscriptError(s.id, file, m.id).catch(() => {}); + const attempts = (errorAttemptsRef.current.get(key) ?? 0) + 1; + errorAttemptsRef.current.set(key, attempts); + if (attempts >= MAX_TRANSCRIBE_ATTEMPTS) + processedRef.current.add(key); // give up for this session + else dirtyRef.current = true; // schedule another pass to retry + } + done += 1; + setStatus({ kind: 'transcribing', done, total: todo.length }); + } + } + } while (dirtyRef.current && !isRecordingActive()); + } finally { + runningRef.current = false; + setStatus({ kind: 'idle' }); + } + // Close the lost-wakeup gap: if a resume/model/library change set `dirty` during the teardown + // above — after the loop exited but before `running` was cleared — re-run now that the lock is + // released, so deferred work isn't stranded until the next unrelated change. + if (dirtyRef.current && !isRecordingActive()) void syncRef.current?.(); + }, [needs]); + + // Keep the self-reference fresh for the lost-wakeup re-check (never assign refs during render). + useEffect(() => { + syncRef.current = sync; + }, [sync]); + + // On a model switch, cancel any in-flight download for a now-unselected model so an abandoned + // (possibly large) pull stops immediately instead of finishing only to be deleted. + useEffect(() => { + cancelModelDownloadsExcept(model); + }, [model]); + + // Re-sync on model change and as the library's clips change. + useEffect(() => { + if (ready) void sync(); + }, [ready, model?.id, segments, sync]); + + // Resume deferred work the moment recording stops. + useEffect(() => { + setResumeHandler(() => void sync()); + return () => setResumeHandler(null); + }, [sync]); + + return status; +} diff --git a/src/features/transcription/vad.ts b/src/features/transcription/vad.ts new file mode 100644 index 00000000..bdb7cdbc --- /dev/null +++ b/src/features/transcription/vad.ts @@ -0,0 +1,122 @@ +import { Directory, File, Paths } from 'expo-file-system'; +import { initWhisperVad, type WhisperVadContext } from 'whisper.rn'; + +/** + * Voice-activity-detection pre-gate for transcription. + * + * Whisper hallucinates on clips with no real speech: the multilingual model especially emits + * Chinese on noise (auto language-detection falls back to its training prior) or canned subtitle + * credits on silence ("Thank you for watching", "Gracias por ver"). whisper.rn 0.6.0 doesn't + * expose the whisper.cpp no-speech / logprob / entropy thresholds that would suppress this, so we + * run a Silero VAD pass first and skip Whisper entirely on clips with no detected speech. + * + * The VAD model is a tiny (~1.5 MB) Silero GGML build from the same whisper.cpp repo as the speech + * models. It lives under `vad/` — NOT `models/` — so the single-speech-model-on-disk cleanup + * (`deleteModelsExcept`) never wipes it on a model switch. + */ +const VAD_URL = + 'https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-silero-v5.1.2.bin'; +const VAD_FILENAME = 'ggml-silero-v5.1.2.bin'; +// Completeness floor for a partial/interrupted download (the real file is ~1.5 MB). +const VAD_MIN_BYTES = 1024 * 1024; + +function vadDir(): Directory { + return new Directory(Paths.document, 'vad'); +} + +function vadFile(): File { + return new File(Paths.document, 'vad', VAD_FILENAME); +} + +function isVadModelReady(): boolean { + const file = vadFile(); + return file.exists && (file.size ?? 0) >= VAD_MIN_BYTES; +} + +/** Ensure the Silero VAD model is on disk, downloading it on first use. Returns its file URI. */ +async function ensureVadModel(): Promise { + const file = vadFile(); + if (isVadModelReady()) return file.uri; + + if (file.exists) file.delete(); // clear a partial/corrupt prior attempt + vadDir().create({ intermediates: true, idempotent: true }); + + const task = File.createDownloadTask(VAD_URL, file); + await task.downloadAsync(); + if (!isVadModelReady()) { + if (file.exists) file.delete(); + throw new Error('VAD model download failed or is incomplete'); + } + return file.uri; +} + +// The VAD context is independent of which speech model is selected, so we hold a single instance +// across model switches (it's cheap and tiny) and only release it when on-device AI is turned off. +let ctx: WhisperVadContext | null = null; +let loadPromise: Promise | null = null; +// Sticky flag set when VAD init fails even on the CPU fallback — the device genuinely can't run the +// VAD, so we stop re-attempting it on every clip (callers fail open and let Whisper run). A model +// download failure (offline) is NOT cached here: it's transient and retried on the next clip. +// Cleared by releaseVad so a later toggle can try again. +let unavailable = false; + +/** + * Build a VAD context, preferring the Metal GPU and falling back to CPU. GPU init throws on + * simulators / older devices without a usable GPU (mirrors the speech-context init in whisper.ts), + * so we retry on CPU rather than letting the gate fail open — keeping hallucination suppression + * active wherever the VAD can run at all. + */ +async function initVadContext(filePath: string): Promise { + try { + return await initWhisperVad({ filePath, useGpu: true }); + } catch { + return initWhisperVad({ filePath }); + } +} + +async function loadVad(): Promise { + if (ctx) return ctx; + if (unavailable) throw new Error('VAD unavailable on this device'); + if (loadPromise) return loadPromise; + loadPromise = (async () => { + await ensureVadModel(); // transient (offline) failures throw here and are intentionally not cached + let c: WhisperVadContext; + try { + c = await initVadContext(vadFile().uri); + } catch (e) { + unavailable = true; // failed even on CPU — don't retry this on every clip + throw e; + } + ctx = c; + return c; + })(); + try { + return await loadPromise; + } finally { + loadPromise = null; + } +} + +/** Free the VAD context (e.g. when the model is cleared). Re-loads lazily on next use. */ +export async function releaseVad(): Promise { + loadPromise = null; + unavailable = false; // allow a fresh attempt after a model toggle + const c = ctx; + ctx = null; + await c?.release(); +} + +/** + * Whether the WAV at `wavPath` contains any detected speech. Throws if the VAD model isn't yet + * available (e.g. offline before its first download) — callers should treat that as "unknown" and + * fail open (transcribe anyway) rather than dropping captions. + * + * NOTE: `detectSpeech` segments' `t0`/`t1` are in **seconds** — unlike Whisper's transcript lines, + * whose `t0`/`t1` are centiseconds. We only count segments here, but if you ever read these + * timestamps, do NOT apply the centisecond (`*10` / `/100`) conversion used for caption lines. + */ +export async function hasSpeech(wavPath: string): Promise { + const c = await loadVad(); + const segments = await c.detectSpeech(wavPath); + return segments.length > 0; +} diff --git a/src/features/transcription/whisper.ts b/src/features/transcription/whisper.ts new file mode 100644 index 00000000..7ba78879 --- /dev/null +++ b/src/features/transcription/whisper.ts @@ -0,0 +1,133 @@ +import { deleteFile, extractAudio } from 'react-native-video-trim'; +import { initWhisper, type WhisperContext } from 'whisper.rn'; + +import { ensureModel, modelFileUri } from './model'; +import type { WhisperModel } from './models'; +import { hasSpeech } from './vad'; + +/** + * One transcribed line. `t0`/`t1` are whisper.cpp timestamps in **centiseconds** (1/100s) + * relative to the clip's audio start — divide by 100 for seconds when rendering. + */ +export type TranscriptLine = { text: string; t0: number; t1: number }; + +export type TranscriptResult = { + language: string; + text: string; + lines: TranscriptLine[]; +}; + +/** A clip with no detected speech: a settled, empty transcript (no captions, never re-run). */ +const EMPTY_TRANSCRIPT: TranscriptResult = { language: '', text: '', lines: [] }; + +/** + * Whether the clip has no speech worth transcribing. Runs the VAD pre-gate; if the VAD itself is + * unavailable (e.g. its model hasn't downloaded yet offline) we fail **open** — assume speech and + * let Whisper run — so a VAD hiccup never silently drops real captions. + */ +async function isSilent(wavPath: string): Promise { + try { + return !(await hasSpeech(wavPath)); + } catch { + return false; + } +} + +// A Whisper context is expensive to create (loads the weights into memory) and is reusable across +// clips, so we hold a single instance, tagged with the model it was built from. Switching models +// releases the old context before loading the new one. +let current: { id: string; ctx: WhisperContext } | null = null; +let loadPromise: Promise | null = null; + +// Cap on a single caption line's length (characters). Whisper emits whole utterances as one +// segment; splitting to caption-sized chunks (requires token timestamps) gives short, readable +// lines that sync tightly with playback instead of one long paragraph. +const CAPTION_MAX_LEN = 42; + +/** + * Build a Whisper context, preferring on-device acceleration. `useGpu` runs inference on the + * Metal GPU (iOS) — several times faster and far lighter on battery than the CPU path — with + * Flash Attention on top. Older devices / simulators without a usable GPU throw on init, so we + * fall back to the plain CPU context rather than failing transcription outright. + */ +async function initContext(filePath: string): Promise { + try { + return await initWhisper({ filePath, useGpu: true, useFlashAttn: true }); + } catch { + return initWhisper({ filePath }); + } +} + +/** Free the active Whisper context (e.g. on model switch / delete). Re-loads lazily on next use. */ +export async function releaseWhisper(): Promise { + loadPromise = null; + const ctx = current?.ctx ?? null; + current = null; + await ctx?.release(); +} + +/** + * Get a Whisper context for `model`, loading (and downloading, if needed) on first use and + * swapping the context when the selected model changes. Idempotent for the already-loaded model. + */ +async function loadContext(model: WhisperModel): Promise { + if (current?.id === model.id) return current.ctx; + if (loadPromise) await loadPromise.catch(() => {}); + if (current?.id === model.id) return current.ctx; + + loadPromise = (async () => { + await releaseWhisper(); + await ensureModel(model); // no-op if already on disk + const ctx = await initContext(modelFileUri(model)); + current = { id: model.id, ctx }; + return ctx; + })(); + try { + return await loadPromise; + } finally { + loadPromise = null; + } +} + +/** + * Transcribe a single video clip's audio on-device with the given model. + * + * Pipeline: extract the audio track to a 16-bit PCM WAV via react-native-video-trim (FFmpegKit's + * default WAV codec is pcm_s16le, exactly what whisper.cpp wants), then run Whisper — which + * auto-resamples to 16kHz and downmixes to mono. The temp WAV is removed afterwards. The model + * is expected to be downloaded already (the manager handles the download phase); if not, it is + * fetched here as a fallback. + * + * @param videoUri absolute file URI to the clip (the effective edited-or-original file). + */ +export async function transcribeVideo( + videoUri: string, + model: WhisperModel, + onProgress?: (progress: number) => void, +): Promise { + const { outputPath: wavPath } = await extractAudio(videoUri, { outputExt: 'wav' }); + try { + // Pre-gate on voice activity: silent/noise-only clips make Whisper hallucinate (the + // multilingual model emits Chinese on noise, or canned subtitle credits on silence). Skip + // Whisper entirely and store an empty transcript so the clip settles instead of re-running. + if (await isSilent(wavPath)) return EMPTY_TRANSCRIPT; + + const ctx = await loadContext(model); + // `tokenTimestamps` is what lets `maxLen` split a long utterance into caption-sized lines. + // `language` honors the model: 'en' for the English-only models, 'auto' for the multilingual one. + const { promise } = ctx.transcribe(wavPath, { + language: model.lang, + maxLen: CAPTION_MAX_LEN, + tokenTimestamps: true, + onProgress, + }); + const result = await promise; + return { + language: result.language, + text: result.result.trim(), + lines: result.segments.map((s) => ({ text: s.text, t0: s.t0, t1: s.t1 })), + }; + } finally { + await deleteFile(wavPath).catch(() => {}); + } +} diff --git a/src/utils/segment-window.test.ts b/src/utils/segment-window.test.ts new file mode 100644 index 00000000..3ba8eef3 --- /dev/null +++ b/src/utils/segment-window.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from '@jest/globals'; + +import type { Segment } from '@/db/schema'; +import { effFile, effMs, indexAtGlobalMs, segmentOffsets } from './segment-window'; + +// Minimal Segment factory — only the fields the timeline math reads. +const seg = (over: Partial): Segment => + ({ + id: 'x', + originalFilename: 'orig.mp4', + editedFilename: null, + durationMs: 1000, + editedDurationMs: null, + ...over, + }) as Segment; + +describe('effFile / effMs', () => { + it('uses the edited file and duration when present, else the original', () => { + expect(effFile(seg({ editedFilename: 'edit.mp4' }))).toBe('edit.mp4'); + expect(effFile(seg({ editedFilename: null }))).toBe('orig.mp4'); + expect(effMs(seg({ durationMs: 1000, editedDurationMs: 400 }))).toBe(400); + expect(effMs(seg({ durationMs: 1000, editedDurationMs: null }))).toBe(1000); + }); + + it('never reports a negative contribution', () => { + expect(effMs(seg({ durationMs: -50, editedDurationMs: null }))).toBe(0); + }); +}); + +describe('segmentOffsets', () => { + it('produces prefix sums of effective durations', () => { + const segs = [seg({ durationMs: 1000 }), seg({ durationMs: 500 }), seg({ durationMs: 2000 })]; + expect(segmentOffsets(segs)).toEqual([0, 1000, 1500]); + }); +}); + +describe('indexAtGlobalMs', () => { + const segs = [seg({ durationMs: 1000 }), seg({ durationMs: 500 }), seg({ durationMs: 2000 })]; + const offsets = segmentOffsets(segs); // [0, 1000, 1500] + + it('maps a global position to the containing clip', () => { + expect(indexAtGlobalMs(segs, offsets, 0)).toBe(0); + expect(indexAtGlobalMs(segs, offsets, 999)).toBe(0); + expect(indexAtGlobalMs(segs, offsets, 1000)).toBe(1); + expect(indexAtGlobalMs(segs, offsets, 1600)).toBe(2); + }); + + it('skips zero-length clips and never lands on them', () => { + const withZero = [seg({ durationMs: 1000 }), seg({ durationMs: 0 }), seg({ durationMs: 2000 })]; + const offs = segmentOffsets(withZero); // [0, 1000, 1000] + expect(indexAtGlobalMs(withZero, offs, 1000)).toBe(2); + }); +}); diff --git a/tsconfig.json b/tsconfig.json index 812502ee..c8a6932b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,7 +4,11 @@ "strict": true, "paths": { "@/*": ["./src/*"], - "@/assets/*": ["./assets/*"] + "@/assets/*": ["./assets/*"], + // whisper.rn's package.json `exports` map omits a "." root entry, so bundler-mode + // resolution can't find the bare import's types. Metro resolves it at runtime via the + // `main` fallback; this points TS at the published declarations. + "whisper.rn": ["./node_modules/whisper.rn/lib/typescript/index"] } }, "include": ["**/*.ts", "**/*.tsx", ".expo/types/**/*.ts", "expo-env.d.ts"],