Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(cli): port the export runner and captions onto the 1.8 native pipeline
PeterTakahashi9e5dd71d4acb
diff --git a/src/cli/CliCaptionsRunner.tsx b/src/cli/CliCaptionsRunner.tsxindex 32d01ca11..7bcf21391 100644--- a/src/cli/CliCaptionsRunner.tsx+++ b/src/cli/CliCaptionsRunner.tsx@@ -10,12 +10,12 @@ import {validateProjectData,} from "@/components/video-editor/projectPersistence";import type { AnnotationRegion, TrimRegion } from "@/components/video-editor/types";-import { captionSegmentsToAnnotationRegions } from "@/lib/captioning/annotationsFromCaptions";+import { captionSegmentsToAnnotationRegions } from "./vendor/captionRegions";import { extractMono16kFromVideoUrl } from "@/lib/captioning/extractMono16k";import {shiftTrimRegionsMsForCaptionBuffer,trimLeadingSilenceMono16k,-} from "@/lib/captioning/leadingSilence";+} from "./vendor/leadingSilence";import { transcribeMono16kToSegments } from "@/lib/captioning/transcribe";import type { CliCaptionsRequest, CliDoneResult } from "@/lib/cliContracts";import { nativeBridgeClient } from "@/native";diff --git a/src/cli/CliExportRunner.tsx b/src/cli/CliExportRunner.tsxindex 08e600b34..2b42da58e 100644--- a/src/cli/CliExportRunner.tsx+++ b/src/cli/CliExportRunner.tsx@@ -1,49 +1,41 @@// Hidden-window runner for `openscreen export`. Loads an .openscreen project,-// rebuilds the same exporter configuration the editor's export dialog would,-// and streams progress back to the CLI controller in the main process.+// migrates it to the AxcutDocument the native Rust compositor consumes, and+// drives exportMultiNative/exportGifNative — mirroring the v4 ExportDialog so+// CLI exports and GUI exports stay pixel-identical. The hidden window does no+// compositing itself: the render runs in the main process; this runner only+// builds the clip list + scene JSON and relays progress.import { useEffect, useRef, useState } from "react";-import {- DEFAULT_CURSOR_SETTINGS,- DEFAULT_SOURCE_DIMENSIONS,-} from "@/components/video-editor/editorDefaults";import {normalizeProjectEditor,resolveProjectMedia,toFileUrl,validateProjectData,} from "@/components/video-editor/projectPersistence";-import { buildAutoZoomSuggestions } from "@/components/video-editor/timeline/zoomSuggestionUtils";-import type { CursorTelemetryPoint, ZoomRegion } from "@/components/video-editor/types";+import type { CursorTelemetryPoint } from "@/components/video-editor/types";+import { migrateProjectDataToAxcutDocument } from "@/lib/ai-edition/document/migrate";import {- clampFocusToDepth,- DEFAULT_ZOOM_DEPTH,- ZOOM_DEPTH_SCALES,-} from "@/components/video-editor/types";+ collectEffectiveClipDims,+ type Dims,+ pickExtremeDims,+ resolveAspectRatioValue,+} from "@/lib/ai-edition/document/outputFormat";+import { applyProbedDuration } from "@/lib/ai-edition/document/timeline";+import type { AxcutDocument } from "@/lib/ai-edition/schema";+import { getEditorSettings } from "@/lib/ai-edition/store/editorSettings";+import { resolveClipSourceEndSec } from "@/lib/ai-edition/timeline/clipDuration";+import { DEFAULT_ZOOM_DEPTH, ZOOM_DEPTH_SCALES } from "@/lib/ai-edition/timeline/zoom-scale";+import { buildAutoZoomSuggestions } from "@/lib/ai-edition/timeline/zoom-suggestions";import type { CliDoneResult, CliExportRequest } from "@/lib/cliContracts";-import { hasNativeCursorRecordingData } from "@/lib/cursor/nativeCursor";-import { calculateOutputDimensions, GifExporter } from "@/lib/exporter/gifExporter";-import {- calculateEffectiveSourceDimensions,- calculateMp4ExportSettings,-} from "@/lib/exporter/mp4ExportSettings";-import type { ExportProgress } from "@/lib/exporter/types";-import { GIF_SIZE_PRESETS } from "@/lib/exporter/types";-import { VideoExporter } from "@/lib/exporter/videoExporter";+import { GIF_SIZE_PRESETS, type GifSizePreset } from "@/lib/exporter";+import { calculateMp4ExportSettings } from "@/lib/exporter/mp4ExportSettings";import { mixVoiceoverIntoVideo } from "@/lib/exporter/voiceoverMix";-import { nativeBridgeClient } from "@/native";-import type { CursorRecordingData, NativePlatform } from "@/native/contracts";-import { getAspectRatioValue, getNativeAspectRatioValue } from "@/utils/aspectRatioUtils";+import { exportGifNative, exportMultiNative, nativeBridgeClient } from "@/native";+import type { CompositorClipInput } from "@/native/contracts";+import { buildSceneDescription, resolveVisibleClips } from "@/native/sceneDescription";+import { clampZoomFocus } from "./vendor/zoomHelpers";-// Mirrors the private helper in VideoEditor.tsx.-function isClickInteractionType(interactionType: string | null | undefined) {- return (- interactionType === "click" ||- interactionType === "double-click" ||- interactionType === "right-click" ||- interactionType === "middle-click"- );-}+const MP4_EXPORT_FPS = 60;function probeVideoDimensions(url: string,@@ -77,46 +69,75 @@ function probeVideoDimensions(});}-/** Fit the composition aspect ratio into the reference preview box, mirroring- * how the editor sizes its on-screen preview container. */-function fitPreviewBox(aspectRatioValue: number, boxWidth: number, boxHeight: number) {- let width = boxWidth;- let height = boxWidth / aspectRatioValue;- if (height > boxHeight) {- height = boxHeight;- width = boxHeight * aspectRatioValue;+function replaceExtension(filePath: string, newExtension: string): string {+ return filePath.replace(/\.(openscreen|json)$/i, "") + newExtension;+}++/** Mirrors ExportDialog.buildNativeClipList: trim-narrowed visible clips mapped+ * onto the native multiclip contract. Kept in lock-step with+ * buildSceneDescription so export and scene agree on the clip stream. */+function buildNativeClipList(axcutDocument: AxcutDocument): CompositorClipInput[] {+ const assetById = new Map(axcutDocument.assets.map((asset) => [asset.id, asset]));+ return resolveVisibleClips(axcutDocument).flatMap((clip) => {+ const asset = assetById.get(clip.assetId);+ if (!asset?.originalPath) {+ return [];+ }+ const cam = asset.cameraTrack;+ const sourceEndSec = resolveClipSourceEndSec(clip, asset);+ return [+ {+ screenPath: asset.originalPath,+ webcamPath: cam?.sourcePath ?? asset.originalPath,+ sourceStartSec: clip.sourceStartSec,+ sourceEndSec,+ webcamOffsetSec: cam ? (cam.startMs + cam.offsetMs) / 1000 : 0,+ hasAudio: true,+ },+ ];+ });+}++/** Mirrors ExportDialog.gifOutputDims: cap height at the preset, keep even. */+function gifOutputDims(+ preset: GifSizePreset,+ tierDims: { width: number; height: number } | null,+): { width?: number; height?: number } {+ if (!tierDims) return {};+ const maxHeight = GIF_SIZE_PRESETS[preset].maxHeight;+ if (!Number.isFinite(maxHeight) || tierDims.height <= maxHeight) {+ return { width: tierDims.width, height: tierDims.height };}- return { width: Math.round(width), height: Math.round(height) };+ const scale = maxHeight / tierDims.height;+ const even = (n: number) => Math.max(2, Math.round(n * scale) & ~1);+ return { width: even(tierDims.width), height: even(tierDims.height) };}-/** Mirrors the editor's buildAutoZoomRegions: cursor-dwell suggestions that- * follow the cursor (focusMode "auto") and never overlap existing regions. */-function buildAutoZoomRegions(+function appendAutoZoomRanges(+ axcutDocument: AxcutDocument,cursorTelemetry: CursorTelemetryPoint[],totalMs: number,- existingRegions: ZoomRegion[],-): ZoomRegion[] {+): number {const suggestions = buildAutoZoomSuggestions({cursorTelemetry,totalMs,- existingRegions,+ existingRegions: axcutDocument.zoomRanges,defaultDurationMs: Math.max(1000, Math.round(totalMs * 0.05)),});let nextId = 1;- return suggestions.map((suggestion) => ({- id: `cli-auto-zoom-${nextId++}`,- startMs: Math.round(suggestion.span.start),- endMs: Math.round(suggestion.span.end),- depth: DEFAULT_ZOOM_DEPTH,- customScale: ZOOM_DEPTH_SCALES[DEFAULT_ZOOM_DEPTH],- focus: clampFocusToDepth(suggestion.focus, DEFAULT_ZOOM_DEPTH),- focusMode: "auto" as const,- source: "auto" as const,- }));-}--function replaceExtension(filePath: string, newExtension: string): string {- return filePath.replace(/\.(openscreen|json)$/i, "") + newExtension;+ for (const suggestion of suggestions) {+ axcutDocument.zoomRanges.push({+ id: `cli-auto-zoom-${nextId++}`,+ startMs: Math.round(suggestion.span.start),+ endMs: Math.round(suggestion.span.end),+ depth: DEFAULT_ZOOM_DEPTH,+ customScale: ZOOM_DEPTH_SCALES[DEFAULT_ZOOM_DEPTH],+ focus: clampZoomFocus(suggestion.focus),+ focusMode: "auto",+ source: "auto",+ });+ }+ return suggestions.length;}async function runExport(request: CliExportRequest): Promise<CliDoneResult> {@@ -159,210 +180,158 @@ async function runExport(request: CliExportRequest): Promise<CliDoneResult> {const gifSizePreset = request.gifSizePreset ?? editor.gifSizePreset;const outPath =request.outPath ?? replaceExtension(request.projectPath, format === "gif" ? ".gif" : ".mp4");+ if (request.previewWidth !== null || request.previewHeight !== null) {+ window.electronAPI.cliLog(+ "info",+ "--preview-size is a no-op on the native pipeline (annotation geometry is percentage-based) and kept only for CLI compatibility",+ );+ }- const videoUrl = toFileUrl(media.screenVideoPath);- const webcamVideoUrl = media.webcamVideoPath ? toFileUrl(media.webcamVideoPath) : undefined;-- // Cursor sidecar data (native recordings). Both lookups tolerate missing files.+ // Cursor telemetry: only needed to compute --auto-zoom suggestions. The+ // native compositor discovers the `<video>.cursor.json` sidecar itself.let cursorTelemetry: CursorTelemetryPoint[] = [];- let cursorRecordingData: CursorRecordingData | null = null;- try {- cursorTelemetry = await nativeBridgeClient.cursor.getTelemetry(media.screenVideoPath);- } catch {- cursorTelemetry = [];- }- try {- cursorRecordingData = await nativeBridgeClient.cursor.getRecordingData(media.screenVideoPath);- } catch {- cursorRecordingData = null;+ if (request.autoZoom) {+ try {+ cursorTelemetry = await nativeBridgeClient.cursor.getTelemetry(media.screenVideoPath);+ } catch {+ cursorTelemetry = [];+ }}- const recordingClicks =- cursorRecordingData?.samples- .filter((sample) => isClickInteractionType(sample.interactionType))- .map((sample) => sample.timeMs) ?? [];- const cursorClickTimestamps =- recordingClicks.length > 0- ? recordingClicks- : cursorTelemetry- .filter((sample) => isClickInteractionType(sample.interactionType))- .map((sample) => sample.timeMs);+ const probed = await probeVideoDimensions(toFileUrl(media.screenVideoPath));- let platform: NativePlatform | null = null;- try {- platform = await nativeBridgeClient.system.getPlatform();- } catch {- platform = null;+ // Migrate the .openscreen project onto the AxcutDocument the native+ // compositor consumes. The migration is pure and carries zooms, annotations,+ // trims and the legacy editor settings; the clip's duration is unknown until+ // probed, so applyProbedDuration must run or the export is a single frame.+ let axcutDocument = migrateProjectDataToAxcutDocument({+ ...project,+ media,+ editor,+ });+ const primaryAssetId = axcutDocument.project.primaryAssetId ?? axcutDocument.assets[0]?.id;+ if (!primaryAssetId) {+ throw new Error("Project migration produced no media asset");+ }+ if (probed.durationMs > 0) {+ axcutDocument = applyProbedDuration(axcutDocument, primaryAssetId, probed.durationMs / 1000);}- const hasEditableCursorRecording =- (media.cursorCaptureMode ?? "editable-overlay") === "editable-overlay" &&- (platform === "win32" || platform === "darwin") &&- hasNativeCursorRecordingData(cursorRecordingData);- const effectiveShowCursor = DEFAULT_CURSOR_SETTINGS.show && hasEditableCursorRecording;-- const probed = await probeVideoDimensions(videoUrl);- const sourceWidth = probed.width || DEFAULT_SOURCE_DIMENSIONS.width;- const sourceHeight = probed.height || DEFAULT_SOURCE_DIMENSIONS.height;if (request.autoZoom) {- const autoRegions = buildAutoZoomRegions(- cursorTelemetry,- probed.durationMs,- editor.zoomRegions,- );- if (autoRegions.length > 0) {- editor.zoomRegions = [...editor.zoomRegions, ...autoRegions];- }- window.electronAPI.cliLog(- "info",- `Auto-zoom: added ${autoRegions.length} region(s) from cursor telemetry`,- );+ const added = appendAutoZoomRanges(axcutDocument, cursorTelemetry, probed.durationMs);+ window.electronAPI.cliLog("info", `Auto-zoom: added ${added} region(s) from cursor telemetry`);}- const effectiveSourceDimensions = calculateEffectiveSourceDimensions(- sourceWidth,- sourceHeight,- editor.cropRegion,- );- const aspectRatioValue =- editor.aspectRatio === "native"- ? getNativeAspectRatioValue(sourceWidth, sourceHeight, editor.cropRegion)- : getAspectRatioValue(editor.aspectRatio);- const preview = fitPreviewBox(- aspectRatioValue,- request.previewWidth ?? 1280,- request.previewHeight ?? 720,+ // Output sizing mirrors the ExportDialog: crop-aware smallest clip on the+ // timeline, normalized to the document's aspect ratio.+ const probedAssetDims: Record<string, Dims> = {+ [primaryAssetId]: { width: probed.width, height: probed.height },+ };+ const smallestSource =+ pickExtremeDims(collectEffectiveClipDims(axcutDocument, probedAssetDims), "smallest") ??+ ({ width: probed.width, height: probed.height } as Dims);+ const aspectRatioValue = resolveAspectRatioValue(+ axcutDocument,+ getEditorSettings(axcutDocument).aspectRatio,);+ const outDims = calculateMp4ExportSettings({+ quality,+ sourceWidth: smallestSource.width,+ sourceHeight: smallestSource.height,+ aspectRatioValue,+ });- const onProgress = (progress: ExportProgress) => {+ const clips = buildNativeClipList(axcutDocument);+ if (clips.length === 0) {+ throw new Error("The project's timeline has no visible clips to export");+ }+ const sceneJson = JSON.stringify(buildSceneDescription(axcutDocument));++ // Progress: native pushes raw encoded-frame counts; totals and pacing are+ // computed here, mirroring the ExportDialog.+ const outFps = format === "gif" ? gifFrameRate : MP4_EXPORT_FPS;+ const totalFrames = Math.max(+ 1,+ Math.round(+ clips.reduce((sum, clip) => sum + Math.max(0, clip.sourceEndSec - clip.sourceStartSec), 0) *+ outFps,+ ),+ );+ const exportStartedAt = Date.now();+ const unsubscribeProgress = window.electronAPI.onNativeExportProgress?.((frames: number) => {+ const elapsedSec = (Date.now() - exportStartedAt) / 1000;+ const rate = frames > 0 ? frames / Math.max(elapsedSec, 0.001) : 0;window.electronAPI.cliProgress({- percentage: progress.percentage,- currentFrame: progress.currentFrame,- totalFrames: progress.totalFrames,- estimatedTimeRemaining: progress.estimatedTimeRemaining,- phase: progress.phase,+ percentage: Math.min(100, (frames / totalFrames) * 100),+ currentFrame: frames,+ totalFrames,+ estimatedTimeRemaining: rate > 0 ? Math.max(0, (totalFrames - frames) / rate) : 0,});- };-- const sharedConfig = {- videoUrl,- webcamVideoUrl,- wallpaper: editor.wallpaper,- zoomRegions: editor.zoomRegions,- cameraFullscreenRegions: editor.cameraFullscreenRegions,- trimRegions: editor.trimRegions,- speedRegions: editor.speedRegions,- showShadow: editor.shadowIntensity > 0,- shadowIntensity: editor.shadowIntensity,- showBlur: editor.showBlur,- motionBlurAmount: editor.motionBlurAmount,- borderRadius: editor.borderRadius,- padding: editor.padding,- cropRegion: editor.cropRegion,- cursorRecordingData,- cursorScale: effectiveShowCursor ? DEFAULT_CURSOR_SETTINGS.size : 0,- cursorSmoothing: DEFAULT_CURSOR_SETTINGS.smoothing,- cursorMotionBlur: DEFAULT_CURSOR_SETTINGS.motionBlur,- cursorClickBounce: DEFAULT_CURSOR_SETTINGS.clickBounce,- cursorClipToBounds: DEFAULT_CURSOR_SETTINGS.clipToBounds,- cursorTheme: editor.cursorTheme,- annotationRegions: editor.annotationRegions,- webcamLayoutPreset: editor.webcamLayoutPreset,- webcamMaskShape: editor.webcamMaskShape,- webcamMirrored: editor.webcamMirrored,- webcamReactiveZoom: editor.webcamReactiveZoom,- webcamSizePreset: editor.webcamSizePreset,- webcamPosition: editor.webcamPosition,- previewWidth: preview.width,- previewHeight: preview.height,- cursorTelemetry,- cursorClickTimestamps,- onProgress,- };-- let blob: Blob;- let warnings: string[] | undefined;- let outWidth: number;- let outHeight: number;+ });- if (format === "gif") {- const gifDimensions = calculateOutputDimensions(- effectiveSourceDimensions.width,- effectiveSourceDimensions.height,- gifSizePreset,- GIF_SIZE_PRESETS,- aspectRatioValue,- );- outWidth = gifDimensions.width;- outHeight = gifDimensions.height;- const gifExporter = new GifExporter({- ...sharedConfig,- width: gifDimensions.width,- height: gifDimensions.height,- frameRate: gifFrameRate,- loop: editor.gifLoop,- sizePreset: gifSizePreset,- videoPadding: editor.padding,- });- const result = await gifExporter.export();- if (!result.success || !result.blob) {- throw new Error(result.error ?? "GIF export failed");+ try {+ if (format === "gif") {+ const dims = gifOutputDims(gifSizePreset, outDims);+ await exportGifNative(clips, outPath, sceneJson, {+ ...dims,+ fps: gifFrameRate,+ loopCount: editor.gifLoop ? 0 : 1,+ });+ return {+ success: true,+ outputPath: outPath,+ format,+ width: dims.width,+ height: dims.height,+ };}- blob = result.blob;- warnings = result.warnings;- } else {- const mp4Settings = calculateMp4ExportSettings({- quality,- sourceWidth: effectiveSourceDimensions.width,- sourceHeight: effectiveSourceDimensions.height,- aspectRatioValue,- });- outWidth = mp4Settings.width;- outHeight = mp4Settings.height;- const exporter = new VideoExporter({- ...sharedConfig,- width: mp4Settings.width,- height: mp4Settings.height,- frameRate: 60,- bitrate: mp4Settings.bitrate,- codec: "avc1.640033",++ // MP4: native writes outPath directly. When a voiceover is requested, mix+ // it afterwards (the native pipeline has no extra-audio-track concept) and+ // overwrite the same file.+ await exportMultiNative(clips, outPath, sceneJson, {+ width: outDims.width,+ height: outDims.height,+ fps: MP4_EXPORT_FPS,+ codec: "h264",});- const result = await exporter.export();- if (!result.success || !result.blob) {- throw new Error(result.error ?? "MP4 export failed");- }- blob = result.blob;- warnings = result.warnings;- }- if (request.audioPath && format === "mp4") {- window.electronAPI.cliProgress({ percentage: 100, phase: "mixing-voiceover" });- const audioResponse = await fetch(toFileUrl(request.audioPath));- if (!audioResponse.ok) {- throw new Error(`Failed to read voiceover file: ${request.audioPath}`);+ if (request.audioPath) {+ window.electronAPI.cliProgress({ percentage: 100, phase: "mixing-voiceover" });+ const [videoResponse, audioResponse] = await Promise.all([+ fetch(toFileUrl(outPath)),+ fetch(toFileUrl(request.audioPath)),+ ]);+ if (!videoResponse.ok) {+ throw new Error(`Failed to read the exported video back for mixing: ${outPath}`);+ }+ if (!audioResponse.ok) {+ throw new Error(`Failed to read voiceover file: ${request.audioPath}`);+ }+ const mixed = await mixVoiceoverIntoVideo(await videoResponse.blob(), {+ voiceoverData: await audioResponse.arrayBuffer(),+ mode: request.audioMode,+ offsetSec: request.audioOffsetSec,+ });+ const saveResult = await window.electronAPI.writeExportToPath(+ await mixed.arrayBuffer(),+ outPath,+ );+ if (!saveResult.success) {+ throw new Error(saveResult.message ?? `Failed to write mixed output to ${outPath}`);+ }}- const voiceoverData = await audioResponse.arrayBuffer();- blob = await mixVoiceoverIntoVideo(blob, {- voiceoverData,- mode: request.audioMode,- offsetSec: request.audioOffsetSec,- });- }- const arrayBuffer = await blob.arrayBuffer();- const saveResult = await window.electronAPI.writeExportToPath(arrayBuffer, outPath);- if (!saveResult.success || !saveResult.path) {- throw new Error(saveResult.message ?? `Failed to write output to ${outPath}`);+ return {+ success: true,+ outputPath: outPath,+ format,+ width: outDims.width,+ height: outDims.height,+ };+ } finally {+ unsubscribeProgress?.();}-- return {- success: true,- outputPath: saveResult.path,- format,- width: outWidth,- height: outHeight,- warnings,- };}export function CliExportRunner() {diff --git a/src/cli/vendor/captionRegions.ts b/src/cli/vendor/captionRegions.tsnew file mode 100644index 000000000..f8ce2726d--- /dev/null+++ b/src/cli/vendor/captionRegions.ts@@ -0,0 +1,606 @@+// Vendored for the CLI: captionSegmentsToAnnotationRegions was removed from @/lib/captioning/annotationsFromCaptions in the 1.8 line (the v4 editor renders captions natively). The CLI still writes caption *annotations* into .openscreen projects, so the converter lives on here verbatim.++import type { AnnotationRegion, AnnotationTextStyle } from "@/components/video-editor/types";++import type { CaptionSegment } from "@/lib/captioning/transcribe";++/** Wide lower-third bar; `position.x` is top-left as % of container, so center with (100 - width) / 2. */+const CAPTION_WIDTH = 92;+const CAPTION_HEIGHT = 12;+const CAPTION_BOTTOM_MARGIN = 2;++const CAPTION_POSITION = {+ x: (100 - CAPTION_WIDTH) / 2,+ y: 100 - CAPTION_HEIGHT - CAPTION_BOTTOM_MARGIN,+};++const CAPTION_SIZE = { width: CAPTION_WIDTH, height: CAPTION_HEIGHT };++const CAPTION_STYLE: AnnotationTextStyle = {+ color: "#ffffff",+ backgroundColor: "rgba(255, 255, 255, 0)",+ fontSize: 24,+ fontFamily: "Inter",+ fontWeight: "normal",+ fontStyle: "normal",+ textDecoration: "none",+ textAlign: "center",+};++/** Nudge caption starts earlier (seconds); Whisper onsets run slightly late. Do not offset ends too, that pulls lines off-screen early. */+const AUTO_CAPTION_START_BIAS_SEC = 0;++/** Extra hold after Whisper's segment end (seconds); model end times run early vs trailing vowels. Separate from the start bias. */+const AUTO_CAPTION_END_HOLD_SEC = 0;++/** Inside one Whisper phrase, sub-lines can be shorter (do not steal time from neighbors). */+const WORD_SPLIT_MIN_SPAN_SEC = 0.02;++/** Brief linger after the last word in a line (seconds); trimmed if it would overlap the next line. */+const CAPTION_LINE_END_TAIL_SEC = 0;++/** A real silence between word-level timestamps should start a new caption run. */+const WORD_RUN_BREAK_GAP_SEC = 0.24;++/** Min time between consecutive caption regions (seconds); keeps a visible gap so blocks don't read as one clip. Small so short pauses survive. */+const MIN_CAPTION_TIMELINE_GAP_SEC = 0;++/** Same text again with almost no gap or overlap; common Whisper/chunk artifact. */+const DEDUPE_SAME_TEXT_MAX_GAP_SEC = 0.55;++export const SAME_CONTENT_ECHO_MAX_GAP_SEC = 1.15;++function normalizeCaptionKey(text: string): string {+ return text+ .trim()+ .replace(/\s+/g, " ")+ .replace(/[\u2018\u2019]/g, "'")+ .replace(/[\u201C\u201D]/g, '"')+ .toLowerCase()+ .replace(/[.!?,;:]+$/g, "");+}++/** Legacy echo-collapse helper kept for reference while phrase timing uses raw model spans. */+export function collapseSameContentEchoes(segments: CaptionSegment[]): CaptionSegment[] {+ const sorted = [...segments]+ .filter((s) => s.text.trim())+ .sort((a, b) => a.startSec - b.startSec || a.endSec - b.endSec);+ const out: CaptionSegment[] = [];+ const lastIndexByKey = new Map<string, number>();++ for (const seg of sorted) {+ const key = normalizeCaptionKey(seg.text);+ const hit = lastIndexByKey.get(key);+ if (hit !== undefined) {+ const prev = out[hit]!;+ if (seg.startSec < prev.endSec + SAME_CONTENT_ECHO_MAX_GAP_SEC) {+ prev.startSec = Math.min(prev.startSec, seg.startSec);+ prev.endSec = Math.max(prev.endSec, seg.endSec);+ continue;+ }+ }+ out.push({+ startSec: seg.startSec,+ endSec: seg.endSec,+ text: seg.text.trim(),+ });+ lastIndexByKey.set(key, out.length - 1);+ }+ return out;+}++/**+ * Collapse adjacent duplicate lines (overlapping or tiny gap). Does not merge the same phrase+ * repeated later in the video when separated by real silence.+ */+function dedupeAdjacentCaptionRepeats(segments: CaptionSegment[]): CaptionSegment[] {+ const sorted = [...segments]+ .filter((s) => s.text.trim())+ .sort((a, b) => a.startSec - b.startSec || a.endSec - b.endSec);+ const out: CaptionSegment[] = [];+ for (const seg of sorted) {+ const t = seg.text.trim();+ const prev = out[out.length - 1];+ if (prev && normalizeCaptionKey(prev.text) === normalizeCaptionKey(t)) {+ const overlap = prev.endSec - seg.startSec;+ const gap = seg.startSec - prev.endSec;+ if (overlap > 0.015 || gap < DEDUPE_SAME_TEXT_MAX_GAP_SEC) {+ prev.startSec = Math.min(prev.startSec, seg.startSec);+ prev.endSec = Math.max(prev.endSec, seg.endSec);+ continue;+ }+ }+ out.push({ startSec: seg.startSec, endSec: seg.endSec, text: t });+ }+ return out;+}++/** Trim only real overlaps. Avoid synthetic lead/lag so caption timing matches model output. */+function finalizeCaptionSegmentsForPlayback(segments: CaptionSegment[]): CaptionSegment[] {+ const OVERLAP_TRIM_SEC = 0.002;++ const sortedRaw = [...segments]+ .filter((s) => s.text.trim())+ .sort((a, b) => a.startSec - b.startSec || a.endSec - b.endSec);++ const a = sortedRaw.map((seg) => {+ let s = seg.startSec + AUTO_CAPTION_START_BIAS_SEC;+ let e = seg.endSec + AUTO_CAPTION_END_HOLD_SEC;+ s = Math.max(0, s);+ if (e <= s) e = s + 0.02;+ return { startSec: s, endSec: e, text: seg.text.trim() };+ });++ for (let i = 1; i < a.length; i++) {+ if (a[i].startSec < a[i - 1].endSec - OVERLAP_TRIM_SEC) {+ a[i - 1].endSec = Math.max(a[i - 1].startSec + 1e-4, a[i].startSec);+ }+ }++ return a;+}++/** Default min gap between auto-caption blocks on the timeline (ms); matches `MIN_CAPTION_TIMELINE_GAP_SEC`. */+export const DEFAULT_AUTO_CAPTION_MIN_GAP_MS = Math.round(MIN_CAPTION_TIMELINE_GAP_SEC * 1000);++/**+ * Enforce a min gap between consecutive `auto-caption` regions (by start time). Shortens the previous+ * region's end when possible, else shifts the following region later so blocks can't sit completely flush.+ */+export function reconcileAutoCaptionTimelineGaps(+ regions: AnnotationRegion[],+ minGapMs: number = DEFAULT_AUTO_CAPTION_MIN_GAP_MS,+): AnnotationRegion[] {+ const gap = Math.max(0, Math.round(minGapMs));+ if (regions.length === 0 || gap === 0) return regions;++ const autoCandidates = regions.filter((r) => r.annotationSource === "auto-caption");+ if (autoCandidates.length <= 1) return regions;++ const sorted = [...autoCandidates].sort((a, b) => a.startMs - b.startMs || a.endMs - b.endMs);+ const fixed: AnnotationRegion[] = [];+ let prev = { ...sorted[0]! };+ fixed.push(prev);++ for (let i = 1; i < sorted.length; i++) {+ let cur = { ...sorted[i]! };+ const minStart = prev.endMs + gap;++ if (cur.startMs < minStart) {+ const newPrevEnd = cur.startMs - gap;+ if (newPrevEnd >= prev.startMs + 1) {+ prev = { ...prev, endMs: newPrevEnd };+ fixed[fixed.length - 1] = prev;+ } else {+ const dur = Math.max(1, cur.endMs - cur.startMs);+ cur = { ...cur, startMs: minStart, endMs: minStart + dur };+ }+ }++ fixed.push(cur);+ prev = cur;+ }++ const fixedById = new Map(fixed.map((r) => [r.id, r]));+ return regions.map((r) => fixedById.get(r.id) ?? r);+}++/** Join phrases that are close in time so the editor does not create dozens of separate overlays. */+export function mergeAdjacentCaptionSegments(+ segments: CaptionSegment[],+ options?: { maxGapSec?: number; maxChars?: number; maxBlockDurationSec?: number },+): CaptionSegment[] {+ const maxGapSec = options?.maxGapSec ?? 1.35;+ const maxChars = options?.maxChars ?? 320;+ const maxBlockDurationSec = options?.maxBlockDurationSec ?? 12;++ const sorted = [...segments].sort((a, b) => a.startSec - b.startSec);+ const out: CaptionSegment[] = [];++ for (const seg of sorted) {+ const text = seg.text.trim();+ if (!text) continue;++ const prev = out[out.length - 1];+ if (!prev) {+ out.push({ startSec: seg.startSec, endSec: seg.endSec, text });+ continue;+ }++ const gap = seg.startSec - prev.endSec;+ const mergedText = `${prev.text} ${text}`.trim();+ const mergedEnd = Math.max(prev.endSec, seg.endSec);+ const wouldSpan = mergedEnd - prev.startSec;+ if (gap <= maxGapSec && mergedText.length <= maxChars && wouldSpan <= maxBlockDurationSec) {+ prev.endSec = mergedEnd;+ prev.text = mergedText;+ } else {+ out.push({ startSec: seg.startSec, endSec: seg.endSec, text });+ }+ }++ return out;+}++function partitionPhraseCaptionSegments(+ segments: CaptionSegment[],+ options?: { maxGapSec?: number; maxChars?: number; maxBlockDurationSec?: number },+): CaptionSegment[][] {+ const maxGapSec = options?.maxGapSec ?? 0;+ const maxChars = options?.maxChars ?? Number.POSITIVE_INFINITY;+ const maxBlockDurationSec = options?.maxBlockDurationSec ?? Number.POSITIVE_INFINITY;++ const sorted = [...segments]+ .filter((s) => s.text.trim())+ .sort((a, b) => a.startSec - b.startSec || a.endSec - b.endSec);+ if (sorted.length === 0) return [];++ const groups: CaptionSegment[][] = [];+ let current: CaptionSegment[] = [];++ for (const seg of sorted) {+ const text = seg.text.trim();+ if (!text) continue;++ if (current.length === 0) {+ current.push({ ...seg, text });+ continue;+ }++ const prev = current[current.length - 1]!;+ const groupStart = current[0]!.startSec;+ const gap = seg.startSec - prev.endSec;+ const currentChars = current.reduce((sum, item) => sum + item.text.length, 0);+ const wouldChars = currentChars + 1 + text.length;+ const wouldSpan = Math.max(prev.endSec, seg.endSec) - groupStart;++ if (gap <= maxGapSec && wouldChars <= maxChars && wouldSpan <= maxBlockDurationSec) {+ current.push({ ...seg, text });+ continue;+ }++ groups.push(current);+ current = [{ ...seg, text }];+ }++ if (current.length > 0) {+ groups.push(current);+ }++ return groups;+}++export interface CaptionSegmentLayoutOptions {+ /** Lower bound on words per on-screen caption (default 2). */+ minWordsPerCaption?: number;+ /** Upper bound on words per on-screen caption (default 7). */+ maxWordsPerCaption?: number;+ /**+ * `word`: each `CaptionSegment` is a single token with Whisper word timestamps (default).+ * `phrase`: merged phrase spans; use proportional line splitting inside each span.+ */+ timestampGranularity?: "word" | "phrase";+}++function computeCaptionLineIndexRanges(+ wordCount: number,+ minWords: number,+ maxWords: number,+): Array<{ from: number; to: number }> {+ const minW = Math.max(1, Math.min(Math.floor(minWords), Math.floor(maxWords)));+ const maxW = Math.max(minW, Math.floor(maxWords));+ const sliceRanges: Array<{ from: number; to: number }> = [];+ let i = 0;+ while (i < wordCount) {+ const remaining = wordCount - i;+ if (remaining <= maxW) {+ if (sliceRanges.length > 0 && remaining < minW) {+ sliceRanges[sliceRanges.length - 1]!.to = wordCount;+ } else {+ sliceRanges.push({ from: i, to: wordCount });+ }+ break;+ }++ let take = maxW;+ const after = remaining - take;+ if (after > 0 && after < minW) {+ take = remaining - minW;+ if (take < minW) {+ sliceRanges.push({ from: i, to: wordCount });+ break;+ }+ if (take > maxW) {+ take = maxW;+ }+ }+ sliceRanges.push({ from: i, to: i + take });+ i += take;+ }+ return sliceRanges;+}++/**+ * Groups per-word segments into on-screen lines using each token's Whisper timestamps+ * (no proportional stretching across a long phrase span).+ */+export function groupTimedCaptionWordsIntoLines(+ segments: CaptionSegment[],+ minWords: number,+ maxWords: number,+): CaptionSegment[] {+ const words = [...segments]+ .filter((s) => s.text.trim())+ .sort((a, b) => a.startSec - b.startSec || a.endSec - b.endSec);+ if (words.length === 0) return [];++ const minW = Math.max(1, Math.min(Math.floor(minWords), Math.floor(maxWords)));+ const maxW = Math.max(minW, Math.floor(maxWords));+ const out: CaptionSegment[] = [];++ let runStart = 0;+ const flushRun = (runEndExclusive: number) => {+ const run = words.slice(runStart, runEndExclusive);+ if (run.length === 0) return;+ const ranges = computeCaptionLineIndexRanges(run.length, minW, maxW);+ for (const { from, to } of ranges) {+ const slice = run.slice(from, to);+ const s = slice[0]!.startSec;+ const rawEnd = slice[slice.length - 1]!.endSec;+ const e = Math.max(s + WORD_SPLIT_MIN_SPAN_SEC, rawEnd + CAPTION_LINE_END_TAIL_SEC);+ out.push({+ startSec: s,+ endSec: e,+ text: slice.map((w) => w.text.trim()).join(" "),+ });+ }+ };++ for (let i = 1; i < words.length; i++) {+ const prev = words[i - 1]!;+ const cur = words[i]!;+ const gap = cur.startSec - prev.endSec;+ if (gap >= WORD_RUN_BREAK_GAP_SEC) {+ flushRun(i);+ runStart = i;+ }+ }+ flushRun(words.length);++ for (let i = 0; i < out.length - 1; i++) {+ if (out[i]!.endSec > out[i + 1]!.startSec + 1e-3) {+ out[i]!.endSec = Math.max(+ out[i]!.startSec + WORD_SPLIT_MIN_SPAN_SEC,+ out[i + 1]!.startSec - 1e-4,+ );+ }+ }+ return out;+}++/**+ * Splits each merged transcription span into shorter captions with about+ * `minWords`-`maxWords` words. Times are interpolated by character weight inside the span.+ */+export function splitMergedCaptionsByWordBounds(+ merged: CaptionSegment[],+ minWords: number,+ maxWords: number,+): CaptionSegment[] {+ const minW = Math.max(1, Math.min(Math.floor(minWords), Math.floor(maxWords)));+ const maxW = Math.max(minW, Math.floor(maxWords));+ const out: CaptionSegment[] = [];++ for (const seg of merged) {+ const words = seg.text.trim().split(/\s+/).filter(Boolean);+ if (words.length === 0) continue;++ if (words.length <= maxW) {+ out.push({+ startSec: seg.startSec,+ endSec: seg.endSec,+ text: words.join(" "),+ });+ continue;+ }++ out.push(...splitOneSegmentByWordBounds(seg.startSec, seg.endSec, words, minW, maxW));+ }++ return out;+}++function wrapCaptionTextByWordBounds(text: string, minWords: number, maxWords: number): string {+ const words = text.trim().split(/\s+/).filter(Boolean);+ if (words.length === 0) return "";+ const minW = Math.max(1, Math.min(Math.floor(minWords), Math.floor(maxWords)));+ const maxW = Math.max(minW, Math.floor(maxWords));+ const ranges = computeCaptionLineIndexRanges(words.length, minW, maxW);+ return ranges.map(({ from, to }) => words.slice(from, to).join(" ")).join("\n");+}++function expandPhraseSegmentToPseudoWords(segment: CaptionSegment): CaptionSegment[] {+ const words = segment.text.trim().split(/\s+/).filter(Boolean);+ if (words.length === 0) return [];+ if (words.length === 1) {+ return [+ {+ startSec: segment.startSec,+ endSec: segment.endSec,+ text: words[0]!,+ },+ ];+ }++ return splitOneSegmentByWordBounds(segment.startSec, segment.endSec, words, 1, 1);+}++export function groupPhraseCaptionSegmentsIntoLines(+ segments: CaptionSegment[],+ minWords: number,+ maxWords: number,+ options?: { maxGapSec?: number; maxChars?: number; maxBlockDurationSec?: number },+): CaptionSegment[] {+ const groups = partitionPhraseCaptionSegments(segments, options);+ const out: CaptionSegment[] = [];++ for (const group of groups) {+ if (group.length === 1) {+ const only = group[0]!;+ const wrapped = wrapCaptionTextByWordBounds(only.text, minWords, maxWords).trim();+ if (!wrapped) continue;+ const lineTexts = wrapped+ .split("\n")+ .map((t) => t.trim())+ .filter(Boolean);+ const n = lineTexts.length;+ const rawDur = only.endSec - only.startSec;+ if (n > 1 && rawDur < n * WORD_SPLIT_MIN_SPAN_SEC) {+ out.push({+ startSec: only.startSec,+ endSec: only.endSec,+ text: lineTexts.join(" "),+ });+ continue;+ }+ const dur = Math.max(rawDur, WORD_SPLIT_MIN_SPAN_SEC * n);+ if (n <= 1) {+ out.push({+ startSec: only.startSec,+ endSec: only.endSec,+ text: lineTexts[0] ?? wrapped,+ });+ continue;+ }+ for (let i = 0; i < n; i++) {+ const startSec = only.startSec + (dur * i) / n;+ const boundary = only.startSec + (dur * (i + 1)) / n;+ const endSec =+ i === n - 1 ? only.endSec : Math.max(startSec + WORD_SPLIT_MIN_SPAN_SEC, boundary);+ out.push({+ startSec,+ endSec,+ text: lineTexts[i]!,+ });+ }+ continue;+ }++ const pseudoWords = group.flatMap(expandPhraseSegmentToPseudoWords);+ out.push(...groupTimedCaptionWordsIntoLines(pseudoWords, minWords, maxWords));+ }++ return out;+}++function splitOneSegmentByWordBounds(+ startSec: number,+ endSec: number,+ words: string[],+ minWords: number,+ maxWords: number,+): CaptionSegment[] {+ const sliceRanges = computeCaptionLineIndexRanges(words.length, minWords, maxWords);++ const dur = Math.max(endSec - startSec, 0.05);+ const weights = words.map((w) => Math.max(1, w.length));+ const totalW = weights.reduce((a, b) => a + b, 0);++ const weightSum = (from: number, to: number) => {+ let s = 0;+ for (let k = from; k < to; k++) s += weights[k] ?? 0;+ return s;+ };++ const result: CaptionSegment[] = [];+ let prevEnd = startSec;+ for (const { from, to } of sliceRanges) {+ const wb = weightSum(0, from);+ const ws = weightSum(from, to);+ let s = startSec + (wb / totalW) * dur;+ let e = startSec + ((wb + ws) / totalW) * dur;+ s = Math.max(s, prevEnd);+ e = Math.max(s + WORD_SPLIT_MIN_SPAN_SEC, e);+ e = Math.min(e, endSec);+ if (e <= s) {+ e = Math.min(endSec, s + WORD_SPLIT_MIN_SPAN_SEC);+ }+ prevEnd = e;+ result.push({+ startSec: s,+ endSec: e,+ text: words.slice(from, to).join(" "),+ });+ }+ if (result.length > 0) {+ result[result.length - 1].endSec = endSec;+ for (let i = 0; i < result.length - 1; i++) {+ if (result[i].endSec > result[i + 1].startSec + 0.002) {+ result[i].endSec = Math.max(result[i].startSec + 1e-4, result[i + 1].startSec);+ }+ }+ }+ return result;+}++export function captionSegmentsToAnnotationRegions(+ segments: CaptionSegment[],+ startNumericId: number,+ startZIndex: number,+ layout?: CaptionSegmentLayoutOptions,+): { regions: AnnotationRegion[]; nextNumericId: number; nextZIndex: number } {+ // Don't echo-collapse raw word tokens before grouping: repeated words ("I … I") share a+ // normalized key and would merge spans while keeping only the first token's text.+ const minW = layout?.minWordsPerCaption ?? 2;+ const maxW = layout?.maxWordsPerCaption ?? 7;+ const granularity = layout?.timestampGranularity ?? "word";++ const grouped =+ granularity === "phrase"+ ? groupPhraseCaptionSegmentsIntoLines(segments, minW, maxW)+ : groupTimedCaptionWordsIntoLines(segments, minW, maxW);++ const dedupedOut = dedupeAdjacentCaptionRepeats(grouped);+ const finalized = finalizeCaptionSegmentsForPlayback(dedupedOut);++ let nid = startNumericId;+ let z = startZIndex;+ const regions: AnnotationRegion[] = [];++ for (const seg of finalized) {+ const startMs = Math.round(seg.startSec * 1000);+ const endMs = Math.max(Math.round(seg.endSec * 1000), startMs + 1);+ regions.push({+ id: `annotation-${nid++}`,+ startMs,+ endMs,+ type: "text",+ content: seg.text,+ annotationSource: "auto-caption",+ position: { ...CAPTION_POSITION },+ size: { ...CAPTION_SIZE },+ style: { ...CAPTION_STYLE },+ zIndex: z++,+ });+ }++ return {+ regions: reconcileAutoCaptionTimelineGaps(regions),+ nextNumericId: nid,+ nextZIndex: z,+ };+}++export function maxAnnotationNumericId(regions: AnnotationRegion[]): number {+ let max = 0;+ for (const r of regions) {+ const m = /^annotation-(\d+)$/.exec(r.id);+ if (m) max = Math.max(max, Number.parseInt(m[1], 10));+ }+ return max;+}++export function maxAnnotationZIndex(regions: AnnotationRegion[]): number {+ if (regions.length === 0) return 0;+ return Math.max(...regions.map((r) => r.zIndex));+}diff --git a/src/cli/vendor/leadingSilence.ts b/src/cli/vendor/leadingSilence.tsnew file mode 100644index 000000000..1f6b1b846--- /dev/null+++ b/src/cli/vendor/leadingSilence.ts@@ -0,0 +1,80 @@+// Vendored for the CLI: @/lib/captioning/leadingSilence was deleted in the 1.8 line. The CLI's captions command still trims leading silence before transcription, so the module lives on here verbatim.++/** Caption path is always mono 16 kHz after `extractMono16kFromVideoUrl`. */+import type { TrimRegion } from "@/components/video-editor/types";++const SAMPLE_RATE = 16_000;++/** Window length for peak detection (~50 ms). */+const WINDOW_SAMPLES = 800;++/** Coarse hop so long intros scan quickly (~50 ms steps). */+const HOP_SAMPLES = 800;++/** Max |sample| in a window below this counts as silence (float PCM ~[-1, 1]). */+const PEAK_THRESHOLD = 0.012;++/** Keep a little audio before the first peak so word onsets are not clipped. */+const PRE_ROLL_SEC = 0.12;++/** Do not scan more than this much audio for leading silence (performance + pathological files). */+const MAX_LEADING_SCAN_SEC = 15 * 60;++/**+ * Drops quiet audio at the beginning so Whisper is not fed a long silent prefix (which can skew+ * the first phrase and wastes work). Returned `trimSec` must be added back to every segment time.+ */+export function trimLeadingSilenceMono16k(samples: Float32Array): {+ samples: Float32Array;+ trimSec: number;+} {+ if (samples.length < WINDOW_SAMPLES) {+ return { samples, trimSec: 0 };+ }++ const maxIndex = Math.min(+ samples.length - WINDOW_SAMPLES,+ Math.floor(MAX_LEADING_SCAN_SEC * SAMPLE_RATE),+ );++ let firstSpeechSample = -1;+ for (let i = 0; i <= maxIndex; i += HOP_SAMPLES) {+ let peak = 0;+ for (let j = 0; j < WINDOW_SAMPLES; j++) {+ peak = Math.max(peak, Math.abs(samples[i + j]!));+ }+ if (peak > PEAK_THRESHOLD) {+ firstSpeechSample = i;+ break;+ }+ }++ if (firstSpeechSample <= 0) {+ return { samples, trimSec: 0 };+ }++ const preRollSamples = Math.round(PRE_ROLL_SEC * SAMPLE_RATE);+ const start = Math.max(0, firstSpeechSample - preRollSamples);+ return {+ samples: samples.subarray(start),+ trimSec: start / SAMPLE_RATE,+ };+}++/**+ * When audio is trimmed from the front, Whisper times are relative to the shortened buffer.+ * Shift trim regions by the same offset so `segmentOverlapsTrim` still uses consistent coordinates.+ */+export function shiftTrimRegionsMsForCaptionBuffer(+ regions: TrimRegion[],+ trimMs: number,+): TrimRegion[] {+ if (trimMs <= 0) return regions;+ return regions+ .map((r) => ({+ ...r,+ startMs: Math.max(0, r.startMs - trimMs),+ endMs: Math.max(0, r.endMs - trimMs),+ }))+ .filter((r) => r.endMs > r.startMs);+}diff --git a/src/cli/vendor/zoomHelpers.ts b/src/cli/vendor/zoomHelpers.tsnew file mode 100644index 000000000..151b080df--- /dev/null+++ b/src/cli/vendor/zoomHelpers.ts@@ -0,0 +1,30 @@+// Vendored for the CLI: clampFocusToDepth was deleted from+// @/components/video-editor/types in the 1.8 line with no successor, and+// hasNativeCursorRecordingData left with @/lib/cursor/nativeCursor. Both are+// tiny pure predicates the CLI export runner still needs.++import type { CursorRecordingData } from "@/native/contracts";++export interface ZoomFocusPoint {+ cx: number;+ cy: number;+}++function clamp(value: number, min: number, max: number): number {+ if (Number.isNaN(value)) return (min + max) / 2;+ return Math.min(max, Math.max(min, value));+}++export function clampZoomFocus(focus: ZoomFocusPoint): ZoomFocusPoint {+ return { cx: clamp(focus.cx, 0, 1), cy: clamp(focus.cy, 0, 1) };+}++export function hasNativeCursorRecordingData(+ recordingData: CursorRecordingData | null | undefined,+): recordingData is CursorRecordingData {+ return Boolean(+ recordingData &&+ recordingData.samples.length > 0 &&+ (recordingData.assets.length > 0 || recordingData.provider === "none"),+ );+}