Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

revert(insertions): remove the added-word machinery, keep the gesture

EtienneLescot913deb8e90a4
diff --git a/crates/compositor-view-napi/src/lib.rs b/crates/compositor-view-napi/src/lib.rs
index 95700a6cb..69476ffc2 100644
--- a/crates/compositor-view-napi/src/lib.rs
+++ b/crates/compositor-view-napi/src/lib.rs
@@ -364,10 +364,6 @@ pub struct ClipInput {
pub webcam_offset_sec: f64,
/// `false` évite une ouverture ffmpeg vouée à échouer et réserve du silence à ce clip.
pub has_audio: bool,
- /// Secondes de sortie pendant lesquelles ce clip TIENT sa dernière image, en silence.
- /// Une pause achetée par un mot ajouté (issue #560) : le ruler et la preview la
- /// respectaient déjà, l'export l'ignorait, faute d'une fenêtre source non vide.
- pub hold_sec: f64,
}
/// Taille/cadence/codec de sortie voulus par l'app (modale d'export). Tous optionnels :
@@ -504,7 +500,6 @@ pub fn export_multi(
source_end_sec: c.source_end_sec,
webcam_offset_sec: c.webcam_offset_sec,
has_audio: c.has_audio,
- hold_sec: c.hold_sec,
})
.collect();
Ok(AsyncTask::new(ExportMultiTask {
@@ -662,7 +657,6 @@ pub fn export_gif(
source_end_sec: c.source_end_sec,
webcam_offset_sec: c.webcam_offset_sec,
has_audio: c.has_audio,
- hold_sec: c.hold_sec,
})
.collect();
let gif_params = params
diff --git a/crates/compositor/src/pipeline_linux.rs b/crates/compositor/src/pipeline_linux.rs
index 5e8ae3970..bc54c3843 100644
--- a/crates/compositor/src/pipeline_linux.rs
+++ b/crates/compositor/src/pipeline_linux.rs
@@ -54,8 +54,6 @@ pub struct ClipSource {
pub source_end_sec: f64,
pub webcam_offset_sec: f64,
pub has_audio: bool,
- /// Secondes de sortie tenues sur la dernière image, en silence (issue #560).
- pub hold_sec: f64,
}
/// Codec cible. Memes variantes que `pipeline_macos::ExportCodec`.
diff --git a/crates/compositor/src/pipeline_macos.rs b/crates/compositor/src/pipeline_macos.rs
index 1adeb8816..1b3f75798 100644
--- a/crates/compositor/src/pipeline_macos.rs
+++ b/crates/compositor/src/pipeline_macos.rs
@@ -614,8 +614,6 @@ pub struct ClipSource {
pub source_end_sec: f64,
pub webcam_offset_sec: f64,
pub has_audio: bool,
- /// Secondes de sortie tenues sur la dernière image, en silence (issue #560).
- pub hold_sec: f64,
}
/// Codec cible pour l'export. Identique à `pipeline_windows::ExportCodec`.
diff --git a/crates/compositor/src/pipeline_windows.rs b/crates/compositor/src/pipeline_windows.rs
index 49eabf806..43e6fc826 100644
--- a/crates/compositor/src/pipeline_windows.rs
+++ b/crates/compositor/src/pipeline_windows.rs
@@ -976,8 +976,6 @@ pub struct ClipSource {
pub source_end_sec: f64,
pub webcam_offset_sec: f64,
pub has_audio: bool,
- /// Secondes de sortie tenues sur la dernière image, en silence (issue #560).
- pub hold_sec: f64,
}
/// Export **multiclip** : rend la timeline (clips ordonnés, avec trims) en un seul MP4.
diff --git a/crates/compositor/src/scene.rs b/crates/compositor/src/scene.rs
index a53aba3cf..a42241672 100644
--- a/crates/compositor/src/scene.rs
+++ b/crates/compositor/src/scene.rs
@@ -19,11 +19,6 @@ pub struct SceneClip {
/// Une source sans piste audio décodable garde sa durée via du silence natif.
#[serde(default)]
pub has_audio: bool,
- /// Secondes de sortie pendant lesquelles ce clip TIENT sa dernière image, en silence.
- /// `#[serde(default)]` comme `has_audio` juste au-dessus, et pour la même raison : un
- /// document écrit avant ce champ se charge sans lui, à 0.0.
- #[serde(default)]
- pub hold_sec: f64,
}
#[derive(Debug, Clone, Copy, Deserialize)]
@@ -618,26 +613,9 @@ impl Scene {
mod tests {
use super::*;
- /// Un document écrit avant `holdSec` doit se charger, à 0.0 — comme `hasAudio` avant
/// lui. Sans ce défaut, ouvrir un projet fait par une version antérieure échouerait au
/// parse au lieu de simplement ne rien tenir (issue #560).
- #[test]
- fn a_clip_without_hold_sec_deserializes_to_zero() {
- let json = r##"{"screenPath":"/s.mp4","webcamPath":"/w.mp4","sourceStartSec":0,"sourceEndSec":4,"webcamOffsetSec":0,"hasAudio":true}"##;
- let clip: SceneClip = serde_json::from_str(json).expect("clip sans holdSec");
- assert_eq!(clip.hold_sec, 0.0);
- }
-
- #[test]
- fn a_clip_carries_its_hold_when_the_document_states_one() {
- let json = r##"{"screenPath":"/s.mp4","webcamPath":"/w.mp4","sourceStartSec":2,"sourceEndSec":2,"webcamOffsetSec":0,"hasAudio":true,"holdSec":1.5}"##;
- let clip: SceneClip = serde_json::from_str(json).expect("clip tenu");
- assert_eq!(clip.hold_sec, 1.5);
- // Fenêtre source vide ET pause positive : c'est exactement la forme que la marche
- // laisse désormais passer.
- assert!(clip.source_end_sec <= clip.source_start_sec);
- }
-
+
#[test]
fn parses_a_minimal_scene_json() {
let json = r##"{
diff --git a/crates/compositor/src/timeline_walk.rs b/crates/compositor/src/timeline_walk.rs
index 4a0cab4ef..fe3a2e795 100644
--- a/crates/compositor/src/timeline_walk.rs
+++ b/crates/compositor/src/timeline_walk.rs
@@ -248,11 +248,7 @@ pub(crate) unsafe fn walk_composited_timeline(
clip.webcam,
);
}
- // Une fenêtre source vide ne veut plus dire « rien à faire » : un segment TENU
- // (issue #560) n'a par construction aucune source à décoder et n'existe que pour
- // ses images tenues. Sans cette porte, une pause achetée par un mot ajouté était
- // honorée par le ruler et par la preview et n'exportait rien du tout.
- if source_end_sec <= clip.source_start_sec && clip.hold_sec <= 0.0 {
+ if source_end_sec <= clip.source_start_sec {
continue;
}
@@ -306,10 +302,6 @@ pub(crate) unsafe fn walk_composited_timeline(
}
let frames_before_clip = frames;
- // La dernière paire composée, gardée hors de la boucle : `'clip_frames` peut casser,
- // et un clip qui n'existe QUE pour tenir une image n'entre jamais dedans — il faut
- // pourtant une image à tenir dans les deux cas.
- let mut last_pair: Option<(*mut AVFrame, *mut AVFrame)> = None;
'clip_frames: for segment in &speed_segments {
for segment_frame in 0..segment.frame_count {
let target_source_time =
@@ -340,53 +332,12 @@ pub(crate) unsafe fn walk_composited_timeline(
let _p = crate::export_probe::scope(crate::export_probe::Stage::Compose);
comp.compose_frame(sf, wf, frames as f32, cfg)?;
}
- last_pair = Some((sf, wf));
on_frame(frames)?;
frames += 1;
}
}
- // Les images tenues, APRÈS les segments de vitesse et volontairement en dehors
- // d'eux. Dedans, `stretch_pcm_to_length` étirerait le vrai son du clip à travers le
- // gel (WSOLA sur une voix, audible). Dehors, le créneau audio est plus long que le
- // PCM et `min(source.len())` laisse des zéros : le silence est gratuit.
- //
- // `ceil`, pas `round` : arrondir perd jusqu'à une demi-image, prise sur la fin de la
- // narration même que la pause existe pour loger.
- if clip.hold_sec > 0.0 {
- if last_pair.is_none() {
- // Clip tenu seul : rien n'a été composé, alors on va chercher une image une
- // fois. Un seek qui échoue laisse `last_pair` vide et on n'émet rien plutôt
- // que de composer du vide.
- if advance_decoder_to(sdec, clip.source_start_sec, 0.0)?
- && advance_decoder_to(wdec, clip.source_start_sec, clip.webcam_offset_sec)?
- {
- let sf = sdec.cur_frame();
- let wf = wdec.cur_frame();
- if !sf.is_null() && !wf.is_null() {
- last_pair = Some((sf, wf));
- }
- }
- }
- match last_pair {
- Some((sf, wf)) => {
- let held = ((clip.hold_sec * out_fps as f64).ceil()) as u64;
- // Le temps timeline est ÉPINGLÉ sur l'instant tenu : c'est ce qui fige
- // aussi les modificateurs (zoom, curseur) au lieu de les laisser courir.
- comp.set_timeline_time(Some(clip.source_start_sec as f32));
- for _ in 0..held {
- comp.compose_frame(sf, wf, frames as f32, cfg)?;
- on_frame(frames)?;
- frames += 1;
- }
- }
- None => eprintln!(
- "[pipeline] warning: clip #{}: pause de {:.3}s ignorée, aucune image à tenir (screen=\"{}\")",
- clip_index, clip.hold_sec, clip.screen,
- ),
- }
- }
on_clip_end(
clip_index,
source_end_sec,
diff --git a/crates/compositor/tests/compose_linux.rs b/crates/compositor/tests/compose_linux.rs
index 22ea8bc3f..62361572d 100644
--- a/crates/compositor/tests/compose_linux.rs
+++ b/crates/compositor/tests/compose_linux.rs
@@ -792,7 +792,6 @@ fn export_linux_mp4() {
source_end_sec: 1.0,
webcam_offset_sec: 0.0,
has_audio: true,
- hold_sec: 0.0,
}];
let params = ExportParams {
width: 640,
diff --git a/crates/compositor/tests/export_timing.rs b/crates/compositor/tests/export_timing.rs
index 11a100626..f0070794b 100644
--- a/crates/compositor/tests/export_timing.rs
+++ b/crates/compositor/tests/export_timing.rs
@@ -117,7 +117,6 @@ fn whole_clip(dir: &PathBuf) -> ClipSource {
source_end_sec: SOURCE_SEC,
webcam_offset_sec: 0.0,
has_audio: false,
- hold_sec: 0.0,
}
}
diff --git a/electron/ai-edition/document-service.ts b/electron/ai-edition/document-service.ts
index d3eaa01d3..9c9b958b9 100644
--- a/electron/ai-edition/document-service.ts
+++ b/electron/ai-edition/document-service.ts
@@ -13,7 +13,6 @@
import fs, { type FileHandle } from "node:fs/promises";
import path from "node:path";
import { createId } from "../../src/lib/ai-edition/document/ids";
-import { parseStoredDocument, reconcileInsertions } from "../../src/lib/ai-edition/document/load";
import { removeClip } from "../../src/lib/ai-edition/document/timeline";
import {
type AxcutAsset,
@@ -123,7 +122,7 @@ function safeProjectId(raw: string): string {
// `getProject` spells the same two steps out inline because it relinks moved
// media between them; keep the order (upgrade, then validate) in step.
function parseLoadedDocument(raw: string): AxcutDocument {
- return parseStoredDocument(JSON.parse(raw));
+ return documentSchema.parse(migrateRawDocumentToCurrent(JSON.parse(raw)));
}
/**
@@ -274,9 +273,7 @@ export class DocumentService {
// back, and it is not persisted from here: the renderer saves the document
// it was given, as it does for any other load-time repair.
const migrated = migrateRawDocumentToCurrent(JSON.parse(raw));
- return reconcileInsertions(
- documentSchema.parse(await relinkProjectMedia(migrated, this.mediaRegistryDir)),
- );
+ return documentSchema.parse(await relinkProjectMedia(migrated, this.mediaRegistryDir));
}
async createProject(title: string): Promise<AxcutDocument> {
diff --git a/src/cli/CliExportRunner.tsx b/src/cli/CliExportRunner.tsx
index 5da415596..9a7f1b590 100644
--- a/src/cli/CliExportRunner.tsx
+++ b/src/cli/CliExportRunner.tsx
@@ -95,7 +95,6 @@ function buildNativeClipList(axcutDocument: AxcutDocument): CompositorClipInput[
sourceEndSec,
webcamOffsetSec: camera.offsetSec,
hasAudio: true,
- holdSec: clip.heldSec ?? 0,
},
];
});
diff --git a/src/components/ai-edition/EditorEmptyState.test.tsx b/src/components/ai-edition/EditorEmptyState.test.tsx
index 0756bc0dd..be7f130b7 100644
--- a/src/components/ai-edition/EditorEmptyState.test.tsx
+++ b/src/components/ai-edition/EditorEmptyState.test.tsx
@@ -47,7 +47,6 @@ const sampleDoc = vi.hoisted(
clips: [],
gaps: [],
trimRanges: [],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/src/components/ai-edition/EditorEmptyState.tsx b/src/components/ai-edition/EditorEmptyState.tsx
index 18101e699..226171dca 100644
--- a/src/components/ai-edition/EditorEmptyState.tsx
+++ b/src/components/ai-edition/EditorEmptyState.tsx
@@ -14,8 +14,11 @@ import { AlertCircle, Film, FolderOpen, Upload, X } from "lucide-react";
import { useCallback, useRef, useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { useScopedT } from "@/contexts/I18nContext";
-import { parseStoredDocument } from "@/lib/ai-edition/document/load";
-import { migrateProjectDataToAxcutDocument } from "@/lib/ai-edition/document/migrate";
+import {
+ migrateProjectDataToAxcutDocument,
+ migrateRawDocumentToCurrent,
+} from "@/lib/ai-edition/document/migrate";
+import { documentSchema } from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { nativeBridgeClient } from "@/native";
import styles from "./NewEditorShell.module.css";
@@ -79,7 +82,7 @@ export function EditorEmptyState({
const isAxcutDocument =
typeof raw === "object" && raw !== null && "schemaVersion" in raw && "timeline" in raw;
const doc = isAxcutDocument
- ? parseStoredDocument(raw) // disk-load: upgrade, validate, reconcile clip geometry
+ ? documentSchema.parse(migrateRawDocumentToCurrent(raw)) // disk-load: upgrade v3/v4 → v5, then validate
: migrateProjectDataToAxcutDocument(raw as never);
const saved = await nativeBridgeClient.aiEdition.save(doc);
if (!saved.success || !saved.document) return false;
diff --git a/src/components/ai-edition/ExportDialog.showInFolder.test.tsx b/src/components/ai-edition/ExportDialog.showInFolder.test.tsx
index d2ec1adbd..52eb7b2ad 100644
--- a/src/components/ai-edition/ExportDialog.showInFolder.test.tsx
+++ b/src/components/ai-edition/ExportDialog.showInFolder.test.tsx
@@ -71,7 +71,6 @@ const DOC: AxcutDocument = {
],
gaps: [],
trimRanges: [],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/src/components/ai-edition/ExportDialog.test.ts b/src/components/ai-edition/ExportDialog.test.ts
index 1fb005750..ed2f1ab1a 100644
--- a/src/components/ai-edition/ExportDialog.test.ts
+++ b/src/components/ai-edition/ExportDialog.test.ts
@@ -51,7 +51,6 @@ function doc(assets: AxcutAsset[], clips: AxcutClip[]): AxcutDocument {
clips,
gaps: [],
trimRanges: [],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/src/components/ai-edition/ExportDialog.tsx b/src/components/ai-edition/ExportDialog.tsx
index 6a581c1ec..5dff50acf 100644
--- a/src/components/ai-edition/ExportDialog.tsx
+++ b/src/components/ai-edition/ExportDialog.tsx
@@ -103,7 +103,6 @@ function buildNativeClipList(document: AxcutDocument): CompositorClipInput[] {
sourceEndSec,
webcamOffsetSec: camera.offsetSec,
hasAudio: true,
- holdSec: clip.heldSec ?? 0,
},
];
});
diff --git a/src/components/ai-edition/NativeCompositorOverlay.tsx b/src/components/ai-edition/NativeCompositorOverlay.tsx
index 18b63f72e..e4af64102 100644
--- a/src/components/ai-edition/NativeCompositorOverlay.tsx
+++ b/src/components/ai-edition/NativeCompositorOverlay.tsx
@@ -74,13 +74,7 @@ export function NativeCompositorOverlay() {
return resolveVisibleClips(document);
}, [document]);
const activePosition = useMemo(
- () =>
- resolveNativePosition(
- currentTimeSec,
- nativeClips,
- document?.timeline.clips ?? [],
- document?.timeline.insertRanges ?? [],
- ),
+ () => resolveNativePosition(currentTimeSec, nativeClips, document?.timeline.clips ?? []),
[nativeClips, currentTimeSec, document],
);
const activeClip = activePosition?.clip ?? null;
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index fbf7a2a2e..2d24ed32e 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -6,8 +6,10 @@ import { useEditorDialogActions } from "@/contexts/EditorDialogsContext";
import { useScopedT } from "@/contexts/I18nContext";
import { useShortcuts } from "@/contexts/ShortcutsContext";
import { createId } from "@/lib/ai-edition/document/ids";
-import { parseStoredDocument } from "@/lib/ai-edition/document/load";
-import { migrateProjectDataToAxcutDocument } from "@/lib/ai-edition/document/migrate";
+import {
+ migrateProjectDataToAxcutDocument,
+ migrateRawDocumentToCurrent,
+} from "@/lib/ai-edition/document/migrate";
import {
applyProbedDuration,
replaceTimeline as replaceTimelineOp,
@@ -19,11 +21,7 @@ import {
setDocumentWordText,
} from "@/lib/ai-edition/document/transcript";
import { isModalOpen } from "@/lib/ai-edition/modalGuard";
-import {
- type AxcutAudioTrack,
- type AxcutClip,
- type AxcutInsertRange,
-} from "@/lib/ai-edition/schema";
+import { type AxcutAudioTrack, type AxcutClip, documentSchema } from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import {
useAssetTranscriptions,
@@ -94,17 +92,15 @@ const NO_AUDIO_TRACKS: AxcutAudioTrack[] = [];
function NativePlaybackSync({
visibleClips,
clips,
- insertRanges,
}: {
visibleClips: AxcutClip[];
clips: AxcutClip[];
- insertRanges: readonly AxcutInsertRange[];
}) {
const playing = useProjectStore((s) => s.playing);
const currentTimeSec = useProjectStore((s) => s.currentTimeSec);
// visibleClips = trim-compressed native stream; `clips` = RAW layout currentTimeSec
// is measured against. resolveNativePosition needs both (see timelineMap).
- useNativePlaybackSync(playing, currentTimeSec, visibleClips, clips, insertRanges);
+ useNativePlaybackSync(playing, currentTimeSec, visibleClips, clips);
return null;
}
@@ -587,7 +583,7 @@ export function NewEditorShell() {
const isAxcutDocument =
typeof raw === "object" && raw !== null && "schemaVersion" in raw && "timeline" in raw;
const doc = isAxcutDocument
- ? parseStoredDocument(raw) // disk-load: upgrade, validate, reconcile clip geometry
+ ? documentSchema.parse(migrateRawDocumentToCurrent(raw)) // disk-load: upgrade v3/v4 → v5, then validate
: migrateProjectDataToAxcutDocument(raw as EditorProjectData);
const saved = await nativeBridgeClient.aiEdition.save(doc);
if (saved.success && saved.document) {
@@ -666,12 +662,7 @@ export function NewEditorShell() {
void enqueueTimelineWrite(async () => {
const doc = useProjectStore.getState().document;
if (!doc) return;
- const next = dropTrimPillsByIds(
- doc.timeline.trimRanges,
- doc.timeline.clips,
- trimIds,
- doc.timeline.insertRanges ?? [],
- );
+ const next = dropTrimPillsByIds(doc.timeline.trimRanges, doc.timeline.clips, trimIds);
if (next.length === doc.timeline.trimRanges.length) return;
await saveDocument(
{ ...doc, timeline: { ...doc.timeline, trimRanges: next } },
@@ -1090,7 +1081,7 @@ export function NewEditorShell() {
// (properties kept, position taken from the playhead).
if (sel.kind === "trim") {
const { coalescedTrimGroups } = await import("@/lib/ai-edition/timeline/trim-mapping");
- const group = coalescedTrimGroups(tl.trimRanges, tl.clips, tl.insertRanges ?? []).find((g) =>
+ const group = coalescedTrimGroups(tl.trimRanges, tl.clips).find((g) =>
g.ids.includes(sel.id),
);
if (!group) return;
@@ -1352,7 +1343,6 @@ export function NewEditorShell() {
isMac,
togglePlay,
handleSeek,
- openVoiceoverFlow,
]);
const showTimeline = mode !== "rec";
@@ -1438,11 +1428,7 @@ export function NewEditorShell() {
className={v4.app}
style={{ gridTemplateRows: `58px 1fr ${showTimeline ? timelineRow : "0px"}` }}
>
- <NativePlaybackSync
- visibleClips={visibleClips}
- clips={clips}
- insertRanges={document?.timeline.insertRanges ?? []}
- />
+ <NativePlaybackSync visibleClips={visibleClips} clips={clips} />
<EditorTopBar
mode={mode}
onModeChange={setMode}
@@ -1527,7 +1513,6 @@ export function NewEditorShell() {
speedRegions={tl.speedRegions}
cameraFullscreenRegions={tl.cameraFullscreenRegions}
trimRanges={tl.trimRanges}
- insertRanges={document?.timeline?.insertRanges ?? []}
selectedZoomRegionId={tl.selection?.kind === "zoom" ? tl.selection.id : null}
onZoomFocusChange={tl.updateZoomFocusLive}
onZoomFocusCommit={() => void tl.commitZoomFocus()}
diff --git a/src/components/ai-edition/Preview.tsx b/src/components/ai-edition/Preview.tsx
index 2753f9635..cd6868e75 100644
--- a/src/components/ai-edition/Preview.tsx
+++ b/src/components/ai-edition/Preview.tsx
@@ -5,7 +5,6 @@ import type {
AxcutAnnotationRegion,
AxcutAudioTrack,
AxcutClip,
- AxcutInsertRange,
AxcutTrimRange,
AxcutZoomRegion,
} from "@/lib/ai-edition/schema";
@@ -34,7 +33,6 @@ interface PreviewProps {
speedRegions?: SpeedRegion[];
cameraFullscreenRegions?: CameraFullscreenRegion[];
trimRanges?: AxcutTrimRange[];
- insertRanges?: AxcutInsertRange[];
selectedZoomRegionId?: string | null;
onZoomFocusChange?: (id: string, focus: ZoomFocus) => void;
onZoomFocusCommit?: () => void;
@@ -68,7 +66,6 @@ export function Preview({
speedRegions,
cameraFullscreenRegions,
trimRanges,
- insertRanges,
selectedZoomRegionId,
onZoomFocusChange,
onZoomFocusCommit,
@@ -197,7 +194,6 @@ export function Preview({
speedRegions={speedRegions}
cameraFullscreenRegions={cameraFullscreenRegions}
trimRanges={trimRanges}
- insertRanges={insertRanges}
selectedZoomRegionId={selectedZoomRegionId}
onZoomFocusChange={onZoomFocusChange}
onZoomFocusCommit={onZoomFocusCommit}
diff --git a/src/components/ai-edition/PreviewCanvas.tsx b/src/components/ai-edition/PreviewCanvas.tsx
index 07a526f45..150012b95 100644
--- a/src/components/ai-edition/PreviewCanvas.tsx
+++ b/src/components/ai-edition/PreviewCanvas.tsx
@@ -36,7 +36,6 @@ import type {
AxcutAnnotationRegion,
AxcutAudioTrack,
AxcutClip,
- AxcutInsertRange,
AxcutTrimRange,
AxcutZoomRegion,
} from "@/lib/ai-edition/schema";
@@ -63,9 +62,6 @@ import { type VideoSource, VirtualPreview } from "./VirtualPreview";
import { WebcamOverlay } from "./WebcamOverlay";
import { ZoomFocusOverlay } from "./ZoomFocusOverlay";
-/** Stable identity, so the memos are not invalidated every render by a fresh `[]`. */
-const EMPTY_INSERT_RANGES: readonly AxcutInsertRange[] = [];
-
type BlurData = NonNullable<AxcutAnnotationRegion["blurData"]>;
interface PreviewCanvasProps {
@@ -79,7 +75,6 @@ interface PreviewCanvasProps {
speedRegions?: SpeedRegion[];
cameraFullscreenRegions?: CameraFullscreenRegion[];
trimRanges?: AxcutTrimRange[];
- insertRanges?: AxcutInsertRange[];
selectedZoomRegionId?: string | null;
onZoomFocusChange?: (id: string, focus: ZoomFocus) => void;
onZoomFocusCommit?: () => void;
@@ -224,18 +219,17 @@ export function PreviewCanvas(props: PreviewCanvasProps) {
// clip the playhead is currently inside, the same lookup VirtualPreview
// itself uses to map playback position back to a clip. `undefined` (no
// crop stored) normalises to the identity region.
- const previewInserts = props.insertRanges ?? EMPTY_INSERT_RANGES;
const activeClip = useMemo(
- () => locateVirtualPosition(props.clips, props.currentTimeSec, previewInserts)?.clip ?? null,
- [props.clips, props.currentTimeSec, previewInserts],
+ () => locateVirtualPosition(props.clips, props.currentTimeSec)?.clip ?? null,
+ [props.clips, props.currentTimeSec],
);
const cropRegion: CropRegion = activeClip?.cropRegion ?? DEFAULT_CROP_REGION;
// P4 — the layout preset is global (one panel for the whole timeline) but the camera
// is per clip, so the layout has to be resolved against the clip under the playhead.
const activeCameraTrack = useMemo(
- () => resolveActiveCameraTrack(assets, props.clips, props.currentTimeSec, previewInserts),
- [assets, props.clips, props.currentTimeSec, previewInserts],
+ () => resolveActiveCameraTrack(assets, props.clips, props.currentTimeSec),
+ [assets, props.clips, props.currentTimeSec],
);
const activeClipHasCamera = Boolean(activeCameraTrack?.visible && activeCameraTrack.sourcePath);
diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsx
index 83927970d..79f9f2e00 100644
--- a/src/components/ai-edition/RightPanes.tsx
+++ b/src/components/ai-edition/RightPanes.tsx
@@ -51,7 +51,6 @@ import type {
AxcutAsset,
AxcutAudioTrack,
AxcutClip,
- AxcutInsertRange,
AxcutTranscript,
AxcutTrimRange,
AxcutWord,
@@ -79,7 +78,6 @@ import {
} from "@/lib/ai-edition/timeline/aggregated-transcript";
import { hasAnyClipWithCamera } from "@/lib/ai-edition/timeline/camera";
import { formatMs } from "@/lib/ai-edition/timeline/format";
-import { takeInserts } from "@/lib/ai-edition/timeline/insert-mapping";
import { removedRawSpans } from "@/lib/ai-edition/timeline/programme-time";
import type {
AssetTranscriptionView,
@@ -112,9 +110,6 @@ import styles from "./NewEditorShell.module.css";
import { useTranscriptionLabel } from "./TranscriptionStatus";
import { transcriptionBusyLabel } from "./transcriptionBusyLabel";
-/** Stable identity, so the memos below are not invalidated every render by a fresh `[]`. */
-const EMPTY_INSERT_RANGES: readonly AxcutInsertRange[] = [];
-
interface PaneProps {
title: string;
icon: ReactNode;
@@ -888,20 +883,11 @@ export function TranscriptPane({
// From the RECORDING clips and the whole trim set, never from `placements`: the
// programme is one thing, and the voiceover lane is asking whether the film still
// contains a moment — not whether some trim happens to name an audio fragment.
- const insertRanges = document?.timeline.insertRanges ?? EMPTY_INSERT_RANGES;
- const removed = useMemo(
- () => removedRawSpans(clips, trimRanges, insertRanges),
- [clips, trimRanges, insertRanges],
- );
+ const removed = useMemo(() => removedRawSpans(clips, trimRanges), [clips, trimRanges]);
// The take's placements are fed the cuts AND its own insertions, so a word after a pause
- // is struck through — and highlighted — at the moment it is actually heard (issue #560).
- const insertsFor = useCallback(
- (groupId: string) => (document ? takeInserts(document, groupId) : []),
- [document],
- );
const voiceover = useMemo(
- () => voiceoverPlacements(audioTracks, removed, insertsFor),
- [audioTracks, removed, insertsFor],
+ () => voiceoverPlacements(audioTracks, removed),
+ [audioTracks, removed],
);
const activeLane = resolveCaptionLane(document, captionSettings);
const setLane = useCallback(
@@ -913,8 +899,8 @@ export function TranscriptPane({
const placements = activeLane === "voiceover" ? voiceover : clips;
const sections = useMemo(
- () => buildAggregatedSections(placements, transcripts, assets, removed, insertRanges),
- [placements, transcripts, assets, removed, insertRanges],
+ () => buildAggregatedSections(placements, transcripts, assets, removed),
+ [placements, transcripts, assets, removed],
);
// `currentTimeSec` is the RAW/document timeline (same referential as the ruler, see
@@ -923,8 +909,8 @@ export function TranscriptPane({
// id is something only the recording lane has — so the voiceover lane never
// highlighted. Raw seconds are the coordinate both lanes share.
const cueWordId = useMemo(
- () => findCueWordId(sections, currentTimeSec, insertRanges),
- [sections, currentTimeSec, insertRanges],
+ () => findCueWordId(sections, currentTimeSec),
+ [sections, currentTimeSec],
);
const laneSwitch =
@@ -1035,7 +1021,6 @@ export function TranscriptPane({
undefined
}
cueWordId={cueWordId}
- insertRanges={insertRanges}
onSeek={onSeek}
onTrimTimelineSpan={onTrimTimelineSpan}
onRemoveTrimRanges={onRemoveTrimRanges}
@@ -1067,7 +1052,6 @@ const TranscriptClipBlock = memo(function TranscriptClipBlock({
busyLabel,
lane,
cueWordId,
- insertRanges,
onSeek,
onTrimTimelineSpan,
onRemoveTrimRanges,
@@ -1083,10 +1067,6 @@ const TranscriptClipBlock = memo(function TranscriptClipBlock({
* CLIP frame, and a voiceover placement has no clip to hold. */
lane: TranscriptLane;
cueWordId: string | null;
- /** The insertions this placement carries: the block maps its words' SOURCE spans onto
- * the ruler to author a cut, and a clip carrying insertions is longer than its source
- * window (issue #560). */
- insertRanges: readonly AxcutInsertRange[];
onSeek: (sec: number) => void;
onTrimTimelineSpan: (startSec: number, endSec: number, reason: string) => void;
onRemoveTrimRanges: (trimIds: string[]) => void;
@@ -1106,14 +1086,13 @@ const TranscriptClipBlock = memo(function TranscriptClipBlock({
// to do with the word the user deleted.
const toRawSpan = useCallback(
(startSec: number, endSec: number): [number, number] => {
- const extent = placementRawExtent(clip, insertRanges);
+ const extent = placementRawExtent(clip);
const lo = extent?.startSec ?? clip.timelineStartSec;
const hi = extent?.endSec ?? Number.POSITIVE_INFINITY;
- const clamp = (sec: number) =>
- Math.min(Math.max(placementRawSec(clip, sec, insertRanges), lo), hi);
+ const clamp = (sec: number) => Math.min(Math.max(placementRawSec(clip, sec), lo), hi);
return [clamp(startSec), clamp(endSec)];
},
- [clip, insertRanges],
+ [clip],
);
const filename = asset?.label ?? clip.assetId;
const sourceRangeLabel =
@@ -1281,6 +1260,13 @@ const TranscriptClipBlock = memo(function TranscriptClipBlock({
// timeline time (the pause gesture) it is a silent freeze frame. Drop this gate
// when TTS lands.
if (!import.meta.env.DEV) return;
+ // Not on the voiceover lane. `insertRangeSchema` has no `clipId`, and the pause an
+ // a voiceover placement has no clip to hold. Refused with a reason rather than
+ // left to write a record nothing can read.
+ if (lane === "voiceover") {
+ toast.error(ts("transcript.insertRecordingOnly"));
+ return;
+ }
if (busy || !seed.trim()) return;
const editor = editorRef.current;
const selection = globalThis.getSelection();
diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsx
index 143051b85..feb174ff8 100644
--- a/src/components/ai-edition/VirtualPreview.tsx
+++ b/src/components/ai-edition/VirtualPreview.tsx
@@ -16,19 +16,16 @@ import {
import type {
AxcutAudioTrack,
AxcutClip,
- AxcutInsertRange,
AxcutTrimRange,
AxcutZoomRegion,
} from "@/lib/ai-edition/schema";
import { audioGainScalar } from "@/lib/ai-edition/store/editorSettings";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
-import { insertionEnteredBetween, rulerInserts } from "@/lib/ai-edition/timeline/inserted-time";
import type { PlaybackClockRef } from "@/lib/ai-edition/timeline/playback-clock";
import { removedRawSpans } from "@/lib/ai-edition/timeline/programme-time";
import { findActiveSpeedRegion, type SpeedRegion } from "@/lib/ai-edition/timeline/speed";
import {
consumedSourceSec,
- type TakeInsert,
type TakePiece,
takePlaybackAt,
takeProgramme,
@@ -215,8 +212,6 @@ interface VirtualPreviewProps {
zoomRegions?: AxcutZoomRegion[];
speedRegions?: SpeedRegion[];
trimRanges?: AxcutTrimRange[];
- /** The media added words inserted — it lengthens playback, it does not cut it. */
- insertRanges?: AxcutInsertRange[];
seekTarget?: { timeSec: number; isSource?: boolean; requestId: number } | null;
onTimeChange?: (timeSec: number) => void;
onLoadedMetadata?: (
@@ -263,7 +258,6 @@ export function VirtualPreview({
zoomRegions = [],
speedRegions = [],
trimRanges = [],
- insertRanges = [],
seekTarget,
onTimeChange,
onLoadedMetadata,
@@ -562,76 +556,26 @@ export function VirtualPreview({
trimRangesRef.current = trimRanges;
// What the film no longer contains, recomputed only when the cuts move — the rAF asks
// it once per voiceover per frame, and walking every trim there would be wasteful.
- // The film's insertions, placed on the raw ruler once. The projection needs them or every
- // track after one lands D seconds early — the bug this argument exists to close.
- /** The insertion currently playing, if any.
- *
- * An added word inserts MEDIA inside the clip (issue #560). There is no generator for it
- * yet, so the stand-in is a fixed frame and silence — but it is a piece of media on the
- * timeline like any other, and playback runs THROUGH it rather than around it.
- *
- * The `<video>` cannot supply those seconds: they are not in the file. So it is PARKED
- * for the insertion's duration — paused, which holds the frame the insertion stands for
- * and silences the recording under it — and a wall clock runs the insertion out.
- *
- * Parked, not re-seeked: writing `currentTime` every frame to a still-playing element
- * is a seek storm the decoder never settles out of, and that is what "playback stops at
- * the insertion" actually was. The cost is that `<video>.paused` stops answering "is the
- * film stopped?" — see `filmPlaying` in the tick. */
- const insertionRef = useRef<{ rawSec: number; durationSec: number; startedAtMs: number } | null>(
- null,
- );
- /** How far into the insertion the wall clock has run, in seconds. Read by
- * `updateVirtualTime` so the RULER position it publishes crosses the insertion while the
- * RAW second it publishes alongside stands still at the insertion's own moment. */
- const insertionElapsedRef = useRef(0);
- // The ranges themselves for anything that maps through a clip; their timeline positions
- // for the one thing that asks "did this frame run into one".
- const insertRangesRef = useRef(insertRanges);
- insertRangesRef.current = insertRanges;
- const filmInsertsRef = useRef(rulerInserts(insertRanges, clips));
- filmInsertsRef.current = useMemo(() => rulerInserts(insertRanges, clips), [insertRanges, clips]);
+ // The film's pauses, placed on the raw ruler once. The projection needs them or every
+ // track after a pause lands D seconds early — the bug this argument exists to close.
// One walk per take, recomputed only when the cuts or the insertions move. The rAF asks
// it every frame per track, and walking on each would be wasteful.
- // The take's own insertions, resolved from the ranges this component already receives.
- // `resolveInsertPlacement` needs assets to tell the lanes apart, and the preview has
- // none — but a range naming an AUDIO asset is exactly one whose asset is not a clip's,
- // which is the same test, available here.
- const clipAssetIds = useMemo(() => new Set(clips.map((c) => c.assetId)), [clips]);
- const takeInsertsByGroup = useCallback(
- (groupId: string): TakeInsert[] => {
- const pill = collapseTracksToPills(audioTracks).find((t) => trackGroupId(t) === groupId);
- if (!pill) return [];
- return insertRanges
- .filter((range) => range.assetId === pill.assetId && !clipAssetIds.has(range.assetId))
- .map((range) => ({
- id: range.id,
- wordId: range.wordId,
- atSourceSec: range.atSec,
- durationSec: range.durationSec,
- }));
- },
- [audioTracks, insertRanges, clipAssetIds],
- );
const takePiecesRef = useRef<Map<string, TakePiece[]>>(new Map());
const takeHeadsRef = useRef<Map<string, string>>(new Map());
- const removedRef = useRef(removedRawSpans(clips, trimRanges, insertRanges));
- removedRef.current = useMemo(
- () => removedRawSpans(clips, trimRanges, insertRanges),
- [clips, trimRanges, insertRanges],
- );
+ const removedRef = useRef(removedRawSpans(clips, trimRanges));
+ removedRef.current = useMemo(() => removedRawSpans(clips, trimRanges), [clips, trimRanges]);
const takeWalks = useMemo(() => {
const pieces = new Map<string, TakePiece[]>();
const heads = new Map<string, string>();
- const removed = removedRawSpans(clips, trimRanges, insertRanges);
+ const removed = removedRawSpans(clips, trimRanges);
for (const pill of collapseTracksToPills(audioTracks)) {
if (pill.kind !== "voiceover" || pill.loop) continue;
const groupId = trackGroupId(pill);
heads.set(groupId, pill.id);
- pieces.set(groupId, takeProgramme(pill, removed, takeInsertsByGroup(groupId)));
+ pieces.set(groupId, takeProgramme(pill, removed));
}
return { pieces, heads };
- }, [audioTracks, clips, trimRanges, takeInsertsByGroup, insertRanges]);
+ }, [audioTracks, clips, trimRanges]);
takePiecesRef.current = takeWalks.pieces;
takeHeadsRef.current = takeWalks.heads;
// Trim-narrowed (`resolvePlaybackSegments`) — used ONLY to detect "has the <video>'s own
@@ -645,8 +589,8 @@ export function VirtualPreview({
// source time to a RAW virtual time that jumps discontinuously by exactly the trim's
// width the moment the video itself jumps — matching the marker's own pixel span.
const playbackClips = useMemo(
- () => resolvePlaybackSegments(clips, trimRanges, insertRanges),
- [clips, trimRanges, insertRanges],
+ () => resolvePlaybackSegments(clips, trimRanges),
+ [clips, trimRanges],
);
const playbackClipsRef = useRef(playbackClips);
playbackClipsRef.current = playbackClips;
@@ -695,25 +639,6 @@ export function VirtualPreview({
if (!v || !Number.isFinite(v.currentTime)) {
return;
}
- // Run the insertion out FIRST: everything below is positioned against a clock that
- // crosses it — the imported tracks especially, which sit on the programme clock
- // exactly as they do in the render's output stream.
- const insertion = insertionRef.current;
- if (insertion) {
- const elapsedSec = (performance.now() - insertion.startedAtMs) / 1000;
- // `!v.paused` means something un-parked the element under us — the transport.
- if (elapsedSec >= insertion.durationSec || !v.paused) {
- insertionRef.current = null;
- insertionElapsedRef.current = 0;
- if (v.paused) void v.play().catch(() => undefined);
- } else {
- insertionElapsedRef.current = elapsedSec;
- }
- }
- // A PARKED element is not a stopped film, and this is the question every gate
- // below actually means: the picture is held on the insertion's frame on purpose
- // while the programme keeps running over it.
- const filmPlaying = !v.paused || insertionRef.current !== null;
for (const audio of [primaryAudioRef.current, supplementalAudioRef.current]) {
if (!audio) continue;
const target = resolveAudioTrackPlayback(v.currentTime, audio.duration);
@@ -750,20 +675,12 @@ export function VirtualPreview({
// was never given a faster `playbackRate`, but seeking it twice as fast
// amounts to the same thing. Dividing raw time by the rate turns that
// back into 1x wall-clock, which is what the render does too.
- // `+ insertionElapsedSec`, and only here: the RAW playhead stands still at the
- // insertion's moment for its whole duration — none of those seconds come from the
- // recording — and the projection of that moment is where the insertion OPENS
- // (`expandRawSec` and this walk both give the last recorded frame its own instant).
- // Adding the elapsed walks the programme through the inserted media, which is what
- // the mixer downstream is doing over the same seconds.
- const outputTimeSec =
- projectRawTimelineSecToPlayback(
- clipsRef.current,
- trimRangesRef.current,
- virtualTimeSecRef.current,
- insertRangesRef.current,
- speedRegionsRef.current,
- ) + insertionElapsedRef.current;
+ const outputTimeSec = projectRawTimelineSecToPlayback(
+ clipsRef.current,
+ trimRangesRef.current,
+ virtualTimeSecRef.current,
+ speedRegionsRef.current,
+ );
for (const track of audioTracksRef.current) {
const el = audioTrackElsRef.current.get(track.id);
if (!el) continue;
@@ -771,7 +688,6 @@ export function VirtualPreview({
clipsRef.current,
trimRangesRef.current,
track.startMs / 1000,
- insertRangesRef.current,
speedRegionsRef.current,
);
// Length is measured WITHOUT speed, position WITH it. A trim REMOVES
@@ -786,13 +702,11 @@ export function VirtualPreview({
clipsRef.current,
trimRangesRef.current,
track.endMs / 1000,
- insertRangesRef.current,
) -
projectRawTimelineSecToPlayback(
clipsRef.current,
trimRangesRef.current,
track.startMs / 1000,
- insertRangesRef.current,
),
);
// A voiceover follows the cuts AND its own insertions, through one walk over
@@ -855,7 +769,7 @@ export function VirtualPreview({
// media metadata not ready yet
}
}
- if (filmPlaying && trackTarget.shouldPlay && el.paused) {
+ if (!v.paused && trackTarget.shouldPlay && el.paused) {
// Resume a context suspended by autoplay policy, exactly as the primary
// loop does above — otherwise a track that starts while the primary
// element is silent (its span is over, or a recording with no separate
@@ -865,7 +779,7 @@ export function VirtualPreview({
}
const playback = el.play();
if (playback) void playback.catch(() => undefined);
- } else if ((!filmPlaying || !trackTarget.shouldPlay) && !el.paused) {
+ } else if ((v.paused || !trackTarget.shouldPlay) && !el.paused) {
el.pause();
}
}
@@ -874,7 +788,7 @@ export function VirtualPreview({
// bypasses React state entirely.
if (clockRef) {
clockRef.current.sourceTimeSec = v.currentTime;
- clockRef.current.isPlaying = filmPlaying;
+ clockRef.current.isPlaying = !v.paused;
clockRef.current.playbackRate = v.playbackRate;
clockRef.current.virtualTimeSec = virtualTimeSecRef.current;
}
@@ -919,7 +833,6 @@ export function VirtualPreview({
activeSourceId,
v.currentTime,
activeClipIdRef.current ?? undefined,
- insertRangesRef.current,
);
if (nextKeptSegment) {
// `findRawClipForSegment` is the ONE definition of the segment-id
@@ -930,11 +843,7 @@ export function VirtualPreview({
if (rawClip) {
activeClipIdRef.current = rawClip.id;
}
- const rawTargetTime = getRawVirtualStartTime(
- nextKeptSegment,
- clipsRef.current,
- insertRangesRef.current,
- );
+ const rawTargetTime = getRawVirtualStartTime(nextKeptSegment, clipsRef.current);
seekToVirtualTimeRef.current?.(rawTargetTime, true);
return;
}
@@ -970,7 +879,7 @@ export function VirtualPreview({
// `clockRef` et `setSourceTimeSec` ci-dessus continuent d'être publiés : la webcam
// et le calque curseur ont besoin du temps source même à l'arrêt. Seule la
// position de la TIMELINE cesse d'être dictée par le média.
- if (!filmPlaying) {
+ if (v.paused) {
return;
}
if (clipsRef.current.length === 0) {
@@ -991,7 +900,6 @@ export function VirtualPreview({
activeSourceId,
0.05,
activeClipIdRef.current ?? undefined,
- insertRangesRef.current,
);
if (pos) {
activeClipIdRef.current = pos.clip.id;
@@ -1005,7 +913,6 @@ export function VirtualPreview({
activeSourceId,
0.05,
activeClipIdRef.current ?? undefined,
- insertRangesRef.current,
);
if (!position) {
// ponytail: fall back to timeline order so cross-asset / reordered
@@ -1041,32 +948,7 @@ export function VirtualPreview({
seekToVirtualTimeRef.current?.(nextClip.timelineStartSec, true);
return;
}
- const nextRawTime = clampVirtualTime(clipsRef.current, position.virtualTimeSec);
- // The first insertion this frame ran into — the rule, and why it is half-open,
- // lives with the other ruler arithmetic.
- const entering = insertionRef.current
- ? undefined
- : insertionEnteredBetween(virtualTimeSecRef.current, nextRawTime, filmInsertsRef.current);
- if (entering) {
- insertionRef.current = {
- rawSec: entering.atRawSec,
- durationSec: entering.durationSec,
- startedAtMs: performance.now(),
- };
- insertionElapsedRef.current = 0;
- // Parks the picture on the frame the insertion stands for, and silences the
- // recording under it. Both are what the insertion IS.
- v.pause();
- // The insertion's own moment, not the frame we happened to land on: the
- // transcript cue, the caption lookup and the audio mix all read this, and
- // through the insertion the RECORDING really is at that one instant.
- updateVirtualTime(entering.atRawSec);
- return;
- }
- // While an insertion plays the element is parked, so the position it reports stands
- // still at where the insertion opens. Its own wall clock is what carries the
- // playhead across it — nothing else is moving. Zero the rest of the time.
- updateVirtualTime(nextRawTime + insertionElapsedRef.current);
+ updateVirtualTime(clampVirtualTime(clipsRef.current, position.virtualTimeSec));
};
raf = window.requestAnimationFrame(tick);
return () => window.cancelAnimationFrame(raf);
@@ -1165,12 +1047,7 @@ export function VirtualPreview({
const seekToVirtualTime = useCallback(
(nextVirtualTimeSec: number, preservePlayback = false, forceResume = false) => {
- // A seek ends the insertion that was playing: the playhead is somewhere else now,
- // so the frame it parked on is not the frame any more. The rAF's own seeks (clip
- // advance, trim skip) are gated on `!v.paused` and so never land here mid-insertion.
- insertionRef.current = null;
- insertionElapsedRef.current = 0;
- const position = locateVirtualPosition(clips, nextVirtualTimeSec, insertRanges);
+ const position = locateVirtualPosition(clips, nextVirtualTimeSec);
if (!position) {
videoRef.current?.pause();
updateVirtualTime(0);
@@ -1238,7 +1115,7 @@ export function VirtualPreview({
});
}
},
- [applySourceTime, clips, videoSources, sourceIndex, updateVirtualTime, insertRanges],
+ [applySourceTime, clips, videoSources, sourceIndex, updateVirtualTime],
);
const seekToSourceTime = useCallback(
@@ -1277,11 +1154,7 @@ export function VirtualPreview({
// the one that has to come back. An asset switch queued in the
// meantime is newer intent still, so it wins outright.
if (!pendingSeekRef.current) {
- const position = locateVirtualPosition(
- clipsRef.current,
- virtualTimeSecRef.current,
- insertRangesRef.current,
- );
+ const position = locateVirtualPosition(clipsRef.current, virtualTimeSecRef.current);
// `locateVirtualPosition` answers for whatever clip the playhead
// is on, which after a boundary advance can belong to a DIFFERENT
// asset — its source time would be a meaningless offset into the
diff --git a/src/components/ai-edition/WebcamOverlay.test.tsx b/src/components/ai-edition/WebcamOverlay.test.tsx
index ffd13f30a..0e5575b6a 100644
--- a/src/components/ai-edition/WebcamOverlay.test.tsx
+++ b/src/components/ai-edition/WebcamOverlay.test.tsx
@@ -68,7 +68,6 @@ function makeDocument(): AxcutDocument {
clips: [CLIP_WITH_CAMERA, CLIP_WITHOUT_CAMERA],
gaps: [],
trimRanges: [],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/src/components/ai-edition/WebcamOverlay.tsx b/src/components/ai-edition/WebcamOverlay.tsx
index 9a9dad3dd..d9b256149 100644
--- a/src/components/ai-edition/WebcamOverlay.tsx
+++ b/src/components/ai-edition/WebcamOverlay.tsx
@@ -17,7 +17,7 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { toFileUrl } from "@/components/video-editor/projectPersistence";
import type { WebcamLayoutPreset, WebcamMaskShape } from "@/components/video-editor/types";
-import type { AxcutClip, AxcutInsertRange } from "@/lib/ai-edition/schema";
+import type { AxcutClip } from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
import { resolveActiveCameraTrack } from "@/lib/ai-edition/timeline/camera";
@@ -31,14 +31,8 @@ import { getCssClipPath } from "@/lib/webcamMaskShapes";
import { setWebcamNativeSize } from "@/native/webcamSizeCache";
import styles from "./NewEditorShell.module.css";
-/** Stable identity, so the memos are not invalidated every render by a fresh `[]`. */
-const EMPTY_INSERT_RANGES: readonly AxcutInsertRange[] = [];
-
interface WebcamOverlayProps {
clips: AxcutClip[];
- /** The insertions those clips carry — the camera follows the clip under the playhead,
- * and which clip that is cannot be answered without them (issue #560). */
- insertRanges?: readonly AxcutInsertRange[];
currentTimeSec: number;
onTimeChange: (sec: number) => void;
isPlaying: boolean;
@@ -67,15 +61,14 @@ export function WebcamOverlay(props: WebcamOverlayProps) {
// Fallback (pre-clockRef / first paint) position from props, used only for
// the initial correction on loadedmetadata before the rAF loop below has
// had a chance to run.
- const overlayInserts = props.insertRanges ?? EMPTY_INSERT_RANGES;
const position = useMemo(
- () => locateVirtualPosition(props.clips, props.currentTimeSec, overlayInserts),
- [props.clips, props.currentTimeSec, overlayInserts],
+ () => locateVirtualPosition(props.clips, props.currentTimeSec),
+ [props.clips, props.currentTimeSec],
);
const cameraTrack = useMemo(
- () => resolveActiveCameraTrack(assets ?? [], props.clips, props.currentTimeSec, overlayInserts),
- [assets, props.clips, props.currentTimeSec, overlayInserts],
+ () => resolveActiveCameraTrack(assets ?? [], props.clips, props.currentTimeSec),
+ [assets, props.clips, props.currentTimeSec],
);
const cameraTime = useMemo(() => {
@@ -88,8 +81,6 @@ export function WebcamOverlay(props: WebcamOverlayProps) {
// re-creating the loop on every document mutation.
const clipsRef = useRef(props.clips);
clipsRef.current = props.clips;
- const insertsRef = useRef(overlayInserts);
- insertsRef.current = overlayInserts;
const assetsRef = useRef(assets);
assetsRef.current = assets;
@@ -106,12 +97,11 @@ export function WebcamOverlay(props: WebcamOverlayProps) {
raf = window.requestAnimationFrame(tick);
const clock = clockRef.current;
const clipsNow = clipsRef.current;
- const positionNow = locateVirtualPosition(clipsNow, clock.virtualTimeSec, insertsRef.current);
+ const positionNow = locateVirtualPosition(clipsNow, clock.virtualTimeSec);
const trackNow = resolveActiveCameraTrack(
assetsRef.current ?? [],
clipsNow,
clock.virtualTimeSec,
- insertsRef.current,
);
const target = resolveCameraSyncTarget(
clock,
diff --git a/src/components/ai-edition/v4/FloatingInspector.tsx b/src/components/ai-edition/v4/FloatingInspector.tsx
index 2700087af..254da35f2 100644
--- a/src/components/ai-edition/v4/FloatingInspector.tsx
+++ b/src/components/ai-edition/v4/FloatingInspector.tsx
@@ -990,7 +990,7 @@ function SelectionPane({ tl, onClose }: { tl: TimelineApi; onClose: () => void }
// the group's, not the clicked row's. Deleting no longer needs the same expansion here:
// `removeRegion` drops the whole pill for every kind (`dropTrimPillsByIds`), which is
// what this pane used to have to arrange for itself.
- const trimGroup = coalescedTrimGroups(tl.trimRanges, tl.clips, tl.insertRanges ?? []).find((g) =>
+ const trimGroup = coalescedTrimGroups(tl.trimRanges, tl.clips).find((g) =>
g.ids.includes(selection.id),
);
if (!trimGroup) return null;
diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsx
index 1a3b97fab..81b79d80b 100644
--- a/src/components/ai-edition/v4/V4Timeline.tsx
+++ b/src/components/ai-edition/v4/V4Timeline.tsx
@@ -41,7 +41,7 @@ import {
} from "@/lib/ai-edition/document/audioTracks";
import { createId } from "@/lib/ai-edition/document/ids";
import { setUiProbeScrubbing } from "@/lib/ai-edition/perf/uiFrameProbe";
-import type { AxcutAudioTrack, AxcutClip } from "@/lib/ai-edition/schema";
+import type { AxcutAudioTrack, AxcutClip, AxcutWord } from "@/lib/ai-edition/schema";
import { audioGainScalar } from "@/lib/ai-edition/store/editorSettings";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { useTimelineTranscriptGate } from "@/lib/ai-edition/store/transcriptionStore";
@@ -50,18 +50,11 @@ import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
import type { useTimeline } from "@/lib/ai-edition/store/useTimeline";
import { hasAnyClipWithCamera } from "@/lib/ai-edition/timeline/camera";
import { formatSec } from "@/lib/ai-edition/timeline/format";
-import {
- type InsertedWordMark,
- insertedWordMarks,
- rulerInserts,
-} from "@/lib/ai-edition/timeline/inserted-time";
import {
newRegionDurationSec,
setTimelineScale,
} from "@/lib/ai-edition/timeline/newRegionDuration";
-import { removedRawSpans } from "@/lib/ai-edition/timeline/programme-time";
import { ventilateSpanAcrossClips } from "@/lib/ai-edition/timeline/region-ventilation";
-import { type TakePiece, takeProgramme } from "@/lib/ai-edition/timeline/take-programme";
import { coalesceRegionsForRuler } from "@/lib/ai-edition/timeline/timelineMap";
import {
coalescedTrimGroups,
@@ -226,7 +219,7 @@ interface RulerTick {
interface PlayheadOverlayProps {
/** Full timeline length in seconds — the denominator for the playhead's percentage. */
totalSec: number;
- /** Live scrub position in RAW seconds, when a drag is in flight. */
+ /** Live scrub position, when a drag is in flight. Takes precedence over the store. */
overrideTimeSec: number | null;
canvasStyle: React.CSSProperties;
onPointerDown: (e: ReactPointerEvent) => void;
@@ -257,7 +250,7 @@ const PlayheadOverlay = memo(function PlayheadOverlay({
playheadRef,
}: PlayheadOverlayProps) {
const storeTimeSec = useProjectStore((s) => s.currentTimeSec);
- const pct = (((overrideTimeSec ?? storeTimeSec) / totalSec) * 100) as number;
+ const pct = ((overrideTimeSec ?? storeTimeSec) / totalSec) * 100;
return (
<div className={styles.tlPlayheadLayer} aria-hidden>
<div className={styles.tlCanvas} style={canvasStyle}>
@@ -391,7 +384,6 @@ const AudioLanePill = memo(function AudioLanePill({
slipArmed,
outputGain,
ghost,
- pieces,
}: {
track: AxcutAudioTrack;
url: string | undefined;
@@ -432,18 +424,8 @@ const AudioLanePill = memo(function AudioLanePill({
sourceStartSec: number;
sourceEndSec: number;
} | null;
- /** The take's own walk, when it has one. Absent for music, for a looping take, and for
- * a take with no insertion — all of which draw one unbroken waveform, exactly as
- * before. */
- pieces?: readonly TakePiece[] | null;
}) {
const duration = assetDurationSec ?? track.durationSec;
- // Only a take that actually holds somewhere is drawn in pieces. Everything else keeps
- // the single waveform it has always had, so the common pill is untouched.
- const notched = pieces?.some((piece) => piece.kind === "hold") ? pieces : null;
- const pillRawStart = track.startMs / 1000;
- const pillRawSpan = Math.max(1e-6, track.endMs / 1000 - pillRawStart);
- const atPctOfPill = (rawSec: number) => ((rawSec - pillRawStart) / pillRawSpan) * 100;
return (
<>
{/* The rest of the tape, dimmed and unclickable, behind the pill — so the pill
@@ -498,50 +480,15 @@ const AudioLanePill = memo(function AudioLanePill({
style={{ left: 0 }}
onPointerDown={(e) => onStartDrag(e, track, "l")}
/>
- {notched ? (
- // A notch cut out of the fill, inside ONE outline. The take is still one
- // take — one draggable, slippable object — and the eye should read "the
- // voice stops here", not "two takes". The opposite polarity of the clip
- // lane's band, which means "the picture freezes here" (issue #560).
- notched.map((piece) => {
- const left = atPctOfPill(piece.rawStartSec);
- const width = atPctOfPill(piece.rawEndSec) - left;
- return piece.kind === "hold" ? (
- <span
- key={piece.holdId}
- aria-hidden
- data-testid="audio-insert-notch"
- className={styles.laneAudioNotch}
- style={{ left: `${left}%`, width: `${width}%` }}
- />
- ) : (
- <span
- key={`piece-${piece.rawStartSec}`}
- aria-hidden
- className={styles.laneAudioPiece}
- style={{ left: `${left}%`, width: `${width}%` }}
- >
- <ClipWaveform
- videoUrl={url}
- assetDurationSec={duration}
- sourceStartSec={piece.sourceStartSec}
- sourceEndSec={piece.sourceEndSec}
- gain={audioGainScalar(track.gainDb) * outputGain}
- />
- </span>
- );
- })
- ) : (
- <ClipWaveform
- videoUrl={url}
- assetDurationSec={duration}
- sourceStartSec={sourceStartSec}
- sourceEndSec={sourceEndSec}
- // Track gain AND the project output gain — `finish_audio` applies both and
- // clamps, so scaling by the track gain alone under-read a boosted output.
- gain={audioGainScalar(track.gainDb) * outputGain}
- />
- )}
+ <ClipWaveform
+ videoUrl={url}
+ assetDurationSec={duration}
+ sourceStartSec={sourceStartSec}
+ sourceEndSec={sourceEndSec}
+ // Track gain AND the project output gain — `finish_audio` applies both and
+ // clamps, so scaling by the track gain alone under-read a boosted output.
+ gain={audioGainScalar(track.gainDb) * outputGain}
+ />
{/* Where the file starts over, so a looping bed reads as one deliberate
repeat rather than a mystery. Only drawn when the pill actually
outruns its source — otherwise there is nothing to repeat. */}
@@ -684,15 +631,9 @@ export function V4Timeline({
// clicked instead of looking like it worked. Same question, same helper as the Layout
// pane: is a camera attached anywhere on this timeline?
const hasAnyCamera = useMemo(() => hasAnyClipWithCamera(tl.assets, clips), [tl.assets, clips]);
- // The media added words inserted, placed on the ruler. Everything below measures the
- // EXPANDED ruler — stored clip geometry plus the time those insertions add — because that
+ // The pauses added words created, placed on the ruler. Everything below measures the
+ // EXPANDED ruler — stored clip geometry plus the time those pauses add — because that
// is the film's real length and the one the playhead runs along. Stored geometry is
- // never rewritten for this: only what is drawn moves.
- // `?? []` because the key is additive: a document written before it has no insertions.
- const inserts = useMemo(
- () => rulerInserts(tl.insertRanges ?? [], clips),
- [tl.insertRanges, clips],
- );
const total = useMemo(
() =>
Math.max(
@@ -702,6 +643,8 @@ export function V4Timeline({
[clips],
);
const pctOf = useCallback((sec: number) => (sec / total) * 100, [total]);
+ /** Stored raw seconds → a percentage of the expanded ruler. */
+ const pctAt = pctOf;
const showLanes = variant === "edit";
// The visible fraction of the timeline, and what one second is worth on screen
@@ -769,11 +712,22 @@ export function V4Timeline({
// clip because each mark is positioned inside its clip's own box — it then travels with
// the clip through a reorder for free, with no ruler arithmetic of its own.
const insertedWordsByClip = useMemo(() => {
- const out = new Map<string, InsertedWordMark[]>();
- for (const mark of insertedWordMarks(tl.transcripts, clips, tl.insertRanges ?? [])) {
- const list = out.get(mark.clipId);
- if (list) list.push(mark);
- else out.set(mark.clipId, [mark]);
+ const byAsset = new Map<string, AxcutWord[]>();
+ for (const transcript of tl.transcripts) {
+ const added = transcript.words.filter((word) => word.source === "synth");
+ if (added.length > 0) byAsset.set(transcript.assetId, added);
+ }
+ if (byAsset.size === 0) return new Map<string, Array<{ word: AxcutWord; atPct: number }>>();
+ const out = new Map<string, Array<{ word: AxcutWord; atPct: number }>>();
+ for (const clip of clips) {
+ const words = byAsset.get(clip.assetId);
+ const sourceEnd = clip.sourceEndSec ?? clip.sourceStartSec;
+ const span = sourceEnd - clip.sourceStartSec;
+ if (!words || span <= 0) continue;
+ const marks = words
+ .filter((word) => word.startSec >= clip.sourceStartSec && word.startSec <= sourceEnd)
+ .map((word) => ({ word, atPct: ((word.startSec - clip.sourceStartSec) / span) * 100 }));
+ if (marks.length > 0) out.set(clip.id, marks);
}
return out;
}, [tl.transcripts, clips]);
@@ -783,11 +737,7 @@ export function V4Timeline({
// coalesced into one pill. This is what makes growing a trim across a
// junction look like one continuously-growing pill instead of visibly
// splitting, aligning trims with how zoom/speed/annotation already behave.
- const trimPills: LanePill[] = coalescedTrimGroups(
- tl.trimRanges,
- clips,
- tl.insertRanges ?? [],
- ).map((g) => ({
+ const trimPills: LanePill[] = coalescedTrimGroups(tl.trimRanges, clips).map((g) => ({
id: g.ids[0],
kind: "trim",
start: g.start,
@@ -840,13 +790,6 @@ export function V4Timeline({
if (!el) return;
const r = el.getBoundingClientRect();
const pct = Math.min(1, Math.max(0, (clientX - r.left) / r.width));
- // `total` is the EXPANDED ruler, so `pct * total` is a ruler second — and
- // `setCurrentTime` is read as a RAW one by every consumer: the preview seek, the
- // caption lookup, the transcript cue, the audio mix. Writing the ruler value
- // straight in put the playhead one accumulated insertion AHEAD of everything it was
- // supposed to be pointing at, which is what showed as the wrong subtitle under a
- // correctly-placed playhead (issue #560).
- //
const targetTime = pct * total;
// Direct DOM playhead update (0ms latency, zero React re-render overhead)
@@ -1013,7 +956,7 @@ export function V4Timeline({
let ranges = ventilateTimelineSpanToTrims(s, en, clips);
if (ranges.length === 0) {
// Span sits in a gap / past the end: fall back to the nearest clip.
- const resolved = resolveTimelineSpanToTrim(s, en, clips, tl.insertRanges ?? []);
+ const resolved = resolveTimelineSpanToTrim(s, en, clips);
if (!resolved) return;
ranges = [resolved];
}
@@ -1095,30 +1038,6 @@ export function V4Timeline({
// it keeps a document written before that rule legible instead of stacking its pills on
// top of each other. A kind with no tracks takes no row, so the common single-bed
// project stays exactly as tall as it was.
- // One walk per take, for the lane to draw. Same inputs the preview and the export use,
- // so a notch cannot appear where the voice does not actually stop.
- const takePieces = useMemo(() => {
- const clipAssetIds = new Set(clips.map((c) => c.assetId));
- const removed = removedRawSpans(clips, tl.trimRanges, tl.insertRanges ?? []);
- const out = new Map<string, TakePiece[]>();
- for (const pill of audioPills) {
- if (pill.kind !== "voiceover" || pill.loop) continue;
- // A range naming an asset that is no clip's is a take's — the same test
- // `resolveInsertPlacement` makes, available here without a document.
- const inserts = (tl.insertRanges ?? [])
- .filter((range) => range.assetId === pill.assetId && !clipAssetIds.has(range.assetId))
- .map((range) => ({
- id: range.id,
- wordId: range.wordId,
- atSourceSec: range.atSec,
- durationSec: range.durationSec,
- }));
- if (inserts.length === 0) continue;
- out.set(pill.id, takeProgramme(pill, removed, inserts));
- }
- return out;
- }, [audioPills, clips, tl.trimRanges, tl.insertRanges]);
-
const audioRows = useMemo(() => {
const voice = audioPills.filter((p) => p.kind === "voiceover");
const music = audioPills.filter((p) => p.kind !== "voiceover");
@@ -1698,9 +1617,9 @@ export function V4Timeline({
compact ? ` ${styles.lanePillCompact}` : ""
}${seg.interactive && isPillSelected(p.id) ? ` ${styles.lanePillSel}` : ""}`}
style={{
- left: `${pctOf(seg.segStart)}%`,
- // Measured on the expanded ruler at BOTH ends: a region straddling an insertion
- // covers it, so its box has to grow by that insertion and not merely slide.
+ left: `${pctAt(seg.segStart)}%`,
+ // Measured on the expanded ruler at BOTH ends: a region straddling a pause
+ // covers it, so its box has to grow by that pause and not merely slide.
width: `${pctOf(seg.segEnd - seg.segStart)}%`,
transform: seg.shiftPx ? `translateX(${seg.shiftPx}px)` : undefined,
transition: !clipDrag
@@ -2112,7 +2031,7 @@ export function V4Timeline({
<div
key={tick.sec}
className={`${styles.tlTick}${tick.major ? ` ${styles.tlTickMajor}` : ""}`}
- style={{ left: `${pctOf(tick.sec)}%` }}
+ style={{ left: `${pctAt(tick.sec)}%` }}
>
{tick.major ? (
<span className={styles.tlTickLabel}>{fmtTick(tick.sec, rulerTicks.step)}</span>
@@ -2198,10 +2117,6 @@ export function V4Timeline({
track={track}
url={asset ? toFileUrl(asset.originalPath) : undefined}
assetDurationSec={duration}
- // `pctAt`, not `pctOf`: the clip boxes are drawn on the EXPANDED
- // ruler and the audio pills were drawn on the stored one, so any
- // insertion in the film slid the two lanes apart. The take keeps its
- // own length — only its head follows the ruler.
leftPct={pctOf(start)}
widthPct={pctOf(widthSec)}
row={audioRows.rowOf.get(track.id) ?? 0}
@@ -2219,7 +2134,6 @@ export function V4Timeline({
slipHint={ts("audioTrack.slipHint")}
slipArmed={slipArmed}
outputGain={audioGainScalar(settings.audioGainDb)}
- pieces={takePieces.get(track.id) ?? null}
ghost={((g) =>
g
? {
@@ -2264,7 +2178,7 @@ export function V4Timeline({
>
{clips.map((c, i) => {
const dur = c.timelineEndSec - c.timelineStartSec;
- // On the expanded ruler the box also carries whatever insertions fall
+ // On the expanded ruler the box also carries whatever pauses fall
// inside it — the film really does stay on this clip's frame for
// them, so they belong to its box rather than between boxes.
const boxStart = c.timelineStartSec;
@@ -2345,39 +2259,29 @@ export function V4Timeline({
{tl.assets.find((a) => a.id === c.assetId)?.label ?? c.assetId}
</span>
</div>
- {(insertedWordsByClip.get(c.id) ?? []).map(({ wordId, text, atRawSec }) => {
- // A word whose insertion the film plays gets a BAND as wide as the time
- // it adds — that width IS the added time, drawn. One that fitted in
- // silence already there adds nothing and stays a hairline.
- //
- // Both ends on ONE clock. The mark used to place a paused word on
- // the expanded ruler and an unpaused one at a fraction of the clip's
- // SOURCE span, in the same ternary — two clocks, one of which the
- // box is not drawn in.
- const inserted = inserts.find((ins) => ins.wordId === wordId);
- const left = ((atRawSec - boxStart) / boxLen) * 100;
- const width = inserted ? (inserted.durationSec / boxLen) * 100 : 0;
+ {(insertedWordsByClip.get(c.id) ?? []).map(({ word, atPct }) => {
+ const left = atPct;
+ const width = 0;
return (
<button
- key={wordId}
+ key={word.id}
type="button"
data-no-clip-drag
- data-inserted-word={wordId}
- data-inserted-sec={inserted?.durationSec ?? 0}
+ data-inserted-word={word.id}
className={styles.tlClipInsert}
style={
width > 0
? { left: `${left}%`, width: `${width}%`, marginLeft: 0 }
: { left: `${left}%` }
}
- title={t("toolbar.addedWord", { word: text })}
- aria-label={t("toolbar.addedWord", { word: text })}
+ title={t("toolbar.addedWord", { word: word.text })}
+ aria-label={t("toolbar.addedWord", { word: word.text })}
onPointerDown={(e) => e.stopPropagation()}
onClick={(e) => {
// Jump to the moment the added text sits on. The clip box
// underneath would otherwise take this as a selection.
e.stopPropagation();
- setCurrentTime(atRawSec);
+ setCurrentTime(c.timelineStartSec + (word.startSec - c.sourceStartSec));
}}
/>
);
diff --git a/src/lib/ai-edition/captions/captionLane.test.ts b/src/lib/ai-edition/captions/captionLane.test.ts
index 016f95f18..dfc3f5d88 100644
--- a/src/lib/ai-edition/captions/captionLane.test.ts
+++ b/src/lib/ai-edition/captions/captionLane.test.ts
@@ -141,34 +141,4 @@ describe("captionLane", () => {
});
expect(texts(corrected, "voiceover")).toContain("Kubernetes words");
});
-
- it("leaves a take's cues alone when the FILM gains an insertion", () => {
- // An insertion is media inside the clip that carries it, and it lengthens that clip.
- // A take laid over the film keeps its own position on the timeline — the picture
- // slides underneath it — so its cues do not move either. Measured per placement,
- // through the asset the placement actually plays.
- const paused = doc({
- timeline: {
- ...doc().timeline,
- insertRanges: [
- {
- id: "i1",
- assetId: "rec",
- atSec: 1,
- durationSec: 1,
- wordId: "x",
- reason: "",
- origin: "user",
- },
- // biome-ignore lint/suspicious/noExplicitAny: fixture, not a schema exercise
- ] as any,
- },
- });
- const before = deriveCaptionCues(doc(), on("voiceover"), {});
- const after = deriveCaptionCues(paused, on("voiceover"), {});
- // The insertion names the RECORDING's asset. The take is a different asset laid at
- // its own timeline position, so nothing about this cue changes.
- expect(after[0].startMs).toBe(before[0].startMs);
- expect(after[0].endMs).toBe(before[0].endMs);
- });
});
diff --git a/src/lib/ai-edition/captions/captions.test.ts b/src/lib/ai-edition/captions/captions.test.ts
index 46b04de83..ce3d4a961 100644
--- a/src/lib/ai-edition/captions/captions.test.ts
+++ b/src/lib/ai-edition/captions/captions.test.ts
@@ -650,167 +650,3 @@ describe("translated caption layout", () => {
);
});
});
-
-// ─── Captions across an added word's pause ───────────────────────
-// The pause lengthens the ruler, so every line after it slides — and the line the pause
-// exists FOR has to stay on screen through it rather than going dark over the one moment
-// an added word is there for.
-
-describe("captions and a pause", () => {
- function withPause(): AxcutDocument {
- const base = doc();
- return {
- ...base,
- timeline: {
- ...base.timeline,
- insertRanges: [
- {
- id: "ins_1",
- assetId: "asset-1",
- // Inside "hello there friend" (0–2s), so the line covers it.
- atSec: 1.2,
- durationSec: 0.5,
- wordId: "synth_1",
- reason: "",
- origin: "user" as const,
- },
- ],
- },
- };
- }
-
- it("keeps the covering line up through the pause instead of cutting it short", () => {
- const before = deriveCaptionCues(doc(), ON, {});
- const after = deriveCaptionCues(withPause(), ON, {});
- const line = (cues: typeof before) => cues.find((cue) => cue.text.includes("hello"));
- expect(line(after)?.startMs).toBe(line(before)?.startMs);
- // Half a second longer: exactly the pause it now spans.
- expect((line(after)?.endMs ?? 0) - (line(before)?.endMs ?? 0)).toBe(500);
- });
-
- it("slides everything after the pause along by it", () => {
- const before = deriveCaptionCues(doc(), ON, {});
- const after = deriveCaptionCues(withPause(), ON, {});
- const later = (cues: typeof before) => cues.find((cue) => cue.text.includes("goodbye"));
- expect((later(after)?.startMs ?? 0) - (later(before)?.startMs ?? 0)).toBe(500);
- });
-
- it("is unchanged when the project has no pauses", () => {
- expect(deriveCaptionCues(doc(), ON, {})).toEqual(deriveCaptionCues(doc(), ON, {}));
- });
-});
-
-// ─── An added word is spoken over the media it inserted ─────────────────────
-// Lines are grouped by word count and by silences, in SOURCE time. An added word barely
-// takes up source time — the seconds it is spoken in are the INSERTION that follows it —
-// so it was swallowed into the line of the words before it and inherited their start. On
-// screen the added words appeared while the recorded picture was still playing, a whole
-// insertion early (issue #560).
-
-describe("a caption line never mixes recorded words with added ones", () => {
- function docWithAddedWord(): AxcutDocument {
- const t = transcript();
- // "really" typed in after "friend", which ends at source 2. An added word takes up NO
- // source time — the seconds it is spoken in are the insertion it buys, which is how
- // the real documents store it — so its span is degenerate at the moment it follows.
- // The next recorded word begins at the added word's own second — the shape every
- // real document has, because an added word is anchored at the END of the word it
- // follows and the transcript's next word starts there.
- t.words = [
- ...t.words.slice(0, 3),
- {
- id: "synth_1",
- segmentId: "seg_1",
- startSec: 2,
- endSec: 2,
- text: "really",
- source: "synth",
- // biome-ignore lint/suspicious/noExplicitAny: fixture, not a schema exercise
- } as any,
- // Begins at the added word's own second — that adjacency is the whole defect.
- ...t.words.slice(3).map((w) => ({ ...w, startSec: w.startSec - 2, endSec: w.endSec - 2 })),
- ];
- const base = doc();
- return {
- ...base,
- transcripts: [t],
- timeline: {
- ...base.timeline,
- clips: [{ ...base.timeline.clips[0], timelineEndSec: 12 }],
- insertRanges: [
- {
- id: "i1",
- assetId: "asset-1",
- atSec: 2,
- durationSec: 2,
- wordId: "synth_1",
- reason: "",
- origin: "user",
- },
- // biome-ignore lint/suspicious/noExplicitAny: fixture, not a schema exercise
- ] as any,
- },
- };
- }
-
- const settings: CaptionSettings = { ...DEFAULT_CAPTION_SETTINGS, enabled: true };
-
- it("gives the added word its own cue, starting where the recorded words stop", () => {
- const cues = deriveCaptionCues(docWithAddedWord(), settings, {});
- const added = cues.filter((c) => c.text.includes("really"));
- expect(added).toHaveLength(1);
- // It must not carry the recorded words with it — that is the whole defect.
- expect(added[0].text.toLowerCase()).not.toContain("hello");
- // And it opens at the recorded words' end, not at their start.
- expect(added[0].startMs).toBeGreaterThanOrEqual(2000);
- });
-
- it("lays the three lines out end to end across the insertion", () => {
- // The whole rule in one assertion set: the recorded line stops where the added one
- // begins, the added one spans the media it bought, and what follows is pushed along
- // by exactly that length.
- const cues = deriveCaptionCues(docWithAddedWord(), settings, {});
- const recorded = cues.find((c) => c.text.toLowerCase().includes("hello"));
- const added = cues.find((c) => c.text.includes("really"));
- const after = cues.find((c) => c.text.includes("goodbye"));
- expect(recorded).toBeDefined();
- expect(added).toBeDefined();
- expect(after).toBeDefined();
- // The insertion opens at ruler 2000 and runs 2000ms. Three consecutive facts:
- // the recorded line STOPS there, the added line COVERS it, and what follows is
- // pushed along by exactly its length.
- expect(recorded?.endMs).toBe(2000);
- expect(added?.startMs).toBe(2000);
- expect(added?.endMs).toBe(4000);
- expect(after?.startMs).toBe(4000);
- });
-
- it("leaves the recorded line ending before the added one begins", () => {
- const cues = deriveCaptionCues(docWithAddedWord(), settings, {});
- const recorded = cues.find((c) => c.text.toLowerCase().includes("hello"));
- const added = cues.find((c) => c.text.includes("really"));
- expect(recorded).toBeDefined();
- expect(added).toBeDefined();
- expect(recorded?.text).not.toContain("really");
- expect(added?.startMs ?? 0).toBeGreaterThanOrEqual((recorded?.startMs ?? 0) + 1);
- });
-
- it("never prints two cues at once", () => {
- // The symptom this whole rule exists for: the recorded line that follows an added
- // word begins at the added word's own source second, so mapped before the insertion
- // it landed inside it and the two were drawn on top of each other.
- const cues = [...deriveCaptionCues(docWithAddedWord(), settings, {})].sort(
- (a, b) => a.startMs - b.startMs,
- );
- expect(cues.length).toBeGreaterThan(1);
- for (const [i, cue] of cues.slice(0, -1).entries()) {
- expect(cue.endMs).toBeLessThanOrEqual(cues[i + 1].startMs);
- }
- });
-
- it("changes nothing when the transcript has no added words", () => {
- const before = deriveCaptionCues(doc(), settings, {});
- expect(before.some((c) => c.text.toLowerCase().includes("hello"))).toBe(true);
- expect(before.every((c) => !c.text.includes("really"))).toBe(true);
- });
-});
diff --git a/src/lib/ai-edition/captions/cues.ts b/src/lib/ai-edition/captions/cues.ts
index 87e9e3f1b..4d7395063 100644
--- a/src/lib/ai-edition/captions/cues.ts
+++ b/src/lib/ai-edition/captions/cues.ts
@@ -22,10 +22,8 @@ import {
splitMergedCaptionsByWordBounds,
} from "@/lib/captioning/annotationsFromCaptions";
import type { CaptionSegment } from "@/lib/captioning/transcribe";
-import type { AxcutDocument, AxcutInsertRange, AxcutTranscript } from "../schema";
+import type { AxcutDocument, AxcutTranscript } from "../schema";
import { lanePlacements, type TranscriptPlacement } from "../timeline/aggregated-transcript";
-import { takeInserts } from "../timeline/insert-mapping";
-import { sourceToTimelineSec } from "../timeline/inserted-time";
import { removedRawSpans } from "../timeline/programme-time";
import {
type CaptionAnchorV,
@@ -100,7 +98,7 @@ export function captionLinesForAsset(
transcript: AxcutTranscript,
settings: CaptionSettings,
translations: CaptionTranslations,
-): CaptionLine[] {
+): CaptionSegment[] {
const minWords = settings.minWordsPerLine;
const maxWords = settings.maxWordsPerLine;
@@ -117,76 +115,7 @@ export function captionLinesForAsset(
: translatedWordStream(transcript, translations, settings.language);
if (stream.length === 0) return [];
- // Grouped per RUN, never across one. A run is a maximal stretch of words that are all
- // recorded or all added: the two are spoken over different media — the recording, and the
- // insertion that added word bought — so a line holding both would have to be in two places
- // at once, and resolved as one it lands on the recording, an insertion too early.
- const added = addedWordSpans(transcript);
- // Polished per RUN, so the flag survives and so the finaliser's neighbours are all the
- // same kind. Across a run boundary the two lines share a source second and the finaliser
- // cannot tell them apart; `deoverlapCues` settles that on the ruler instead, where the
- // insertion has a width.
- return captionRuns(stream, added).flatMap((run) => {
- const isAdded = run.length > 0 && overlapsAdded(run[0], added);
- return polish(groupTimedCaptionWordsIntoLines(run, minWords, maxWords)).map((line) => ({
- ...line,
- added: isAdded,
- }));
- });
-}
-
-function overlapsAdded(
- word: CaptionSegment,
- added: Array<{ startSec: number; endSec: number }>,
-): boolean {
- return added.some(
- (span) =>
- (word.startSec < span.endSec && word.endSec > span.startSec) ||
- // An added word's source span is DEGENERATE — the seconds it is spoken in are the
- // insertion, not the recording — so a strict overlap never matches it.
- (word.startSec >= span.startSec && word.endSec <= span.endSec),
- );
-}
-
-/** A caption line, and whether it is spoken over inserted media rather than the recording.
- * Only the grouping pass knows which is which, and every edge below depends on it. */
-export type CaptionLine = CaptionSegment & { added: boolean };
-
-/** Where the transcript's ADDED words sit, in source time. */
-function addedWordSpans(transcript: AxcutTranscript): Array<{ startSec: number; endSec: number }> {
- return transcript.words
- .filter((word) => word.source === "synth" && word.text.trim().length > 0)
- .map((word) => ({ startSec: word.startSec, endSec: word.endSec }))
- .sort((a, b) => a.startSec - b.startSec);
-}
-
-/**
- * The stream cut into maximal all-recorded / all-added runs.
- *
- * Membership is decided by OVERLAP with an added word's source span rather than by identity,
- * because a translated stream is rebuilt as pseudo-words and no longer carries the original
- * ids — the spans are the one thing both streams keep.
- */
-function captionRuns(
- stream: CaptionSegment[],
- added: Array<{ startSec: number; endSec: number }>,
-): CaptionSegment[][] {
- if (added.length === 0) return [stream];
- const isAdded = (word: CaptionSegment) => overlapsAdded(word, added);
- const runs: CaptionSegment[][] = [];
- let current: CaptionSegment[] = [];
- let currentIsAdded: boolean | null = null;
- for (const word of stream) {
- const flag = isAdded(word);
- if (currentIsAdded !== null && flag !== currentIsAdded) {
- runs.push(current);
- current = [];
- }
- currentIsAdded = flag;
- current.push(word);
- }
- if (current.length > 0) runs.push(current);
- return runs;
+ return polish(groupTimedCaptionWordsIntoLines(stream, minWords, maxWords));
}
function originalWordStream(transcript: AxcutTranscript): CaptionSegment[] {
@@ -234,10 +163,6 @@ export function sourceSpanToTimelineSpans(
* window and the ruler head, which both providers carry (issue #560). `AxcutClip`
* stays structurally assignable, so every existing caller is unaffected. */
clips: TranscriptPlacement[],
- inserts: readonly AxcutInsertRange[] = [],
- /** True for a span spoken over INSERTED media rather than the recording. The two occupy
- * opposite sides of the same source second, so every edge flips with it. */
- overInsertedMedia = false,
): Array<{ startSec: number; endSec: number }> {
const out: Array<{ startSec: number; endSec: number }> = [];
for (const clip of clips) {
@@ -247,17 +172,11 @@ export function sourceSpanToTimelineSpans(
const e = Math.min(endSec, clipSourceEnd);
if (e <= s) continue;
out.push({
- // An ADDED span IS the insertion: it opens before the inserted media and closes
- // after it, which is exactly the stretch of ruler that media occupies. A RECORDED
- // span lives BETWEEN insertions, so both its edges are the other way round — and
- // its START is the one that matters, because an added word is anchored at the END
- // of the word it follows and the next recorded word begins at that very second.
- // Mapped with the opening edge, that line landed inside the insertion, printed on
- // top of the added one.
- startSec: sourceToTimelineSec(clip, s, inserts, overInsertedMedia ? "opens" : "closes"),
- endSec: sourceToTimelineSec(clip, e, inserts, overInsertedMedia ? "closes" : "opens"),
+ startSec: clip.timelineStartSec + (s - clip.sourceStartSec),
+ endSec: clip.timelineStartSec + (e - clip.sourceStartSec),
});
}
+ // Onto the ruler the viewer actually sees. Expanding BOTH ends does the whole job:
return out;
}
@@ -281,12 +200,7 @@ export function deriveCaptionCues(
// `?? []` for the same reason `insertRanges` has one: the key is additive, so a
// document written before it — or hand-built, never through the schema — has none.
document.audioTracks ?? [],
- removedRawSpans(
- document.timeline.clips,
- document.timeline.trimRanges,
- document.timeline.insertRanges ?? [],
- ),
- (groupId) => takeInserts(document, groupId),
+ removedRawSpans(document.timeline.clips, document.timeline.trimRanges),
);
if (placements.length === 0) return [];
@@ -299,7 +213,7 @@ export function deriveCaptionCues(
// every voiceover cue early.
// A transcript is only projected once per asset even when several clips draw
// from it (line grouping is the expensive part, clipping is cheap).
- const linesByAsset = new Map<string, CaptionLine[]>();
+ const linesByAsset = new Map<string, CaptionSegment[]>();
const cues: CaptionCue[] = [];
let n = 0;
@@ -318,8 +232,6 @@ export function deriveCaptionCues(
line.startSec,
line.endSec,
placements,
- document.timeline.insertRanges ?? [],
- line.added,
)) {
const startMs = Math.round(span.startSec * 1000);
const endMs = Math.max(Math.round(span.endSec * 1000), startMs + 1);
diff --git a/src/lib/ai-edition/document/load.test.ts b/src/lib/ai-edition/document/load.test.ts
deleted file mode 100644
index e6f8b3b2f..000000000
--- a/src/lib/ai-edition/document/load.test.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-// A document written before insertions took up time on the timeline.
-//
-// Nothing else reconciles it: `withInsertRangesForWords` only runs when a transcript word is
-// written, so a project the user merely OPENS keeps its old geometry while all the code
-// around it assumes the new — the film's ruler stops short, the insertion pills are drawn at
-// their source position, and the subtitles slide further out of step with every insertion
-// passed (issue #560).
-
-import { describe, expect, it } from "vitest";
-import type { AxcutClip, AxcutDocument, AxcutInsertRange } from "../schema";
-import { reconcileClipsWithInserts, reconcileInsertions } from "./load";
-
-function clip(over: Partial<AxcutClip> & { id: string }): AxcutClip {
- return {
- assetId: "a1",
- sourceStartSec: 0,
- sourceEndSec: 10,
- timelineStartSec: 0,
- timelineEndSec: 10,
- wordRefs: [],
- origin: "user",
- reason: "",
- ...over,
- };
-}
-
-const insert = (over: Partial<AxcutInsertRange> & { id: string }): AxcutInsertRange => ({
- assetId: "a1",
- atSec: 5,
- durationSec: 1,
- wordId: "w1",
- reason: "",
- origin: "user",
- ...over,
-});
-
-function doc(clips: AxcutClip[], insertRanges: AxcutInsertRange[]): AxcutDocument {
- return { timeline: { clips, insertRanges } } as unknown as AxcutDocument;
-}
-
-describe("reconcileClipsWithInserts", () => {
- it("gives a short clip back the time its insertions take", () => {
- const before = doc([clip({ id: "c1" })], [insert({ id: "i1" })]);
- const [after] = reconcileClipsWithInserts(before).timeline.clips;
- expect(after.timelineEndSec - after.timelineStartSec).toBeCloseTo(11, 6);
- // The recording is untouched: no frame was added to or taken from the file.
- expect(after.sourceStartSec).toBe(0);
- expect(after.sourceEndSec).toBe(10);
- });
-
- it("pushes every later clip along by what the one before it gained", () => {
- const before = doc(
- [clip({ id: "c1" }), clip({ id: "c2", timelineStartSec: 10, timelineEndSec: 20 })],
- [insert({ id: "i1" })],
- );
- const [, second] = reconcileClipsWithInserts(before).timeline.clips;
- expect(second.timelineStartSec).toBeCloseTo(11, 6);
- expect(second.timelineEndSec).toBeCloseTo(21, 6);
- });
-
- it("is idempotent, so it can run on every load", () => {
- const before = doc([clip({ id: "c1" })], [insert({ id: "i1" })]);
- const once = reconcileClipsWithInserts(before);
- const twice = reconcileClipsWithInserts(once);
- expect(twice.timeline.clips).toEqual(once.timeline.clips);
- // And a document already in step is returned as-is, not rebuilt.
- expect(twice).toBe(once);
- });
-
- it("leaves a document with no insertions completely alone", () => {
- const before = doc([clip({ id: "c1" })], []);
- expect(reconcileClipsWithInserts(before)).toBe(before);
- });
-
- it("counts several insertions in one clip, and only that clip's", () => {
- const before = doc(
- [
- clip({ id: "c1" }),
- clip({ id: "c2", assetId: "a2", timelineStartSec: 10, timelineEndSec: 20 }),
- ],
- [insert({ id: "i1", atSec: 3 }), insert({ id: "i2", atSec: 7, durationSec: 0.5 })],
- );
- const [first, second] = reconcileClipsWithInserts(before).timeline.clips;
- expect(first.timelineEndSec).toBeCloseTo(11.5, 6);
- expect(second.timelineEndSec - second.timelineStartSec).toBeCloseTo(10, 6);
- });
-});
-
-// ─── An added word nobody marked ────────────────────────────────────────────
-// `source: "synth"` is how the whole pipeline recognises a word the user typed: it decides
-// whether the word gets an insertion, whether the film makes room for it, and whether the
-// caption line breaks around it. A row minted before that field existed answers no to all
-// three — its text plays over the recording and everything after it drifts. Found in the
-// live project: `synth_1`, zero-width at source 9.15, with no insertion at all (issue #560).
-
-describe("reconcileInsertions", () => {
- function docWithUnmarkedWord(): AxcutDocument {
- return {
- assets: [{ id: "a1", kind: "video" }],
- transcripts: [
- {
- assetId: "a1",
- language: "en",
- segments: [{ id: "s1", kind: "speech", startSec: 0, endSec: 6, text: "x", wordIds: [] }],
- words: [
- { id: "w1", segmentId: "s1", startSec: 0, endSec: 1, text: "hello" },
- // Minted as an added word — the id says so — but never marked.
- { id: "synth_1", segmentId: "s1", startSec: 1, endSec: 1, text: "a much longer thing" },
- ],
- },
- ],
- timeline: { clips: [clip({ id: "c1" })], insertRanges: [] },
- } as unknown as AxcutDocument;
- }
-
- it("marks it, gives it an insertion, and makes room for it", () => {
- const out = reconcileInsertions(docWithUnmarkedWord());
- const word = out.transcripts[0].words.find((w) => w.id === "synth_1");
- expect(word?.source).toBe("synth");
- const range = out.timeline.insertRanges?.find((r) => r.wordId === "synth_1");
- expect(range).toBeDefined();
- expect(range?.durationSec ?? 0).toBeGreaterThan(0);
- const [c] = out.timeline.clips;
- expect(c.timelineEndSec - c.timelineStartSec).toBeCloseTo(10 + (range?.durationSec ?? 0), 6);
- });
-
- it("leaves a word that was never added alone", () => {
- const out = reconcileInsertions(docWithUnmarkedWord());
- expect(out.transcripts[0].words.find((w) => w.id === "w1")?.source).toBeUndefined();
- });
-
- it("is idempotent", () => {
- const once = reconcileInsertions(docWithUnmarkedWord());
- const twice = reconcileInsertions(once);
- expect(twice.timeline.clips).toEqual(once.timeline.clips);
- expect(twice.timeline.insertRanges).toEqual(once.timeline.insertRanges);
- });
-});
diff --git a/src/lib/ai-edition/document/load.ts b/src/lib/ai-edition/document/load.ts
deleted file mode 100644
index a71b81e95..000000000
--- a/src/lib/ai-edition/document/load.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-// The one way to turn a document on disk into a document in memory.
-//
-// Three steps, in this order, and no caller may do two of them and skip the third:
-//
-// 1. UPGRADE — `migrateRawDocumentToCurrent` walks the vN → vN+1 chain.
-// 2. VALIDATE — `documentSchema.parse` is a pure current-version shape check.
-// 3. RECONCILE — clip geometry is brought back in line with the insert ranges.
-//
-// Step 3 is the one that is easy to forget and impossible to notice. An insertion is MEDIA
-// inside a clip (issue #560), so a clip carrying one is longer than its source window by
-// exactly that much — every reader downstream depends on it, and a document written before
-// that was true carries SHORT clips. Nothing else reconciles them: `withInsertRangesForWords`
-// only runs when a transcript word is written, so a project the user merely OPENS keeps its
-// old geometry while all the code around it assumes the new. The visible result is a film
-// whose ruler stops short, insertion pills drawn at their source position instead of their
-// timeline one, and subtitles sliding further out of step with every insertion passed.
-//
-// `reflowClipsForInserts` is absolute rather than incremental, so this is idempotent: a
-// document already in step is returned unchanged, and running it on every load costs nothing
-// while also repairing anything that writes clip geometry without allowing for insertions.
-
-import type { AxcutDocument } from "../schema";
-import { documentSchema, migrateRawDocumentToCurrent } from "../schema";
-import { reflowClipsForInserts } from "./timeline";
-import { withInsertRangesForAllWords, withMarkedAddedWords } from "./transcript";
-
-/**
- * The whole insertion invariant, in dependency order.
- *
- * A word is ADDED, an added word has an INSERTION, and a clip carrying insertions is
- * LONGER. Each step feeds the next, and reconciling only the last one left a document
- * carrying an unmarked added word looking perfectly consistent while playing its text over
- * the recording. Every step is idempotent, so this runs on every load and changes nothing
- * for a document already in step.
- */
-export function reconcileInsertions(document: AxcutDocument): AxcutDocument {
- return reconcileClipsWithInserts(withInsertRangesForAllWords(withMarkedAddedWords(document)));
-}
-
-/** Clip geometry brought back in line with the document's insert ranges. Idempotent. */
-export function reconcileClipsWithInserts(document: AxcutDocument): AxcutDocument {
- const insertRanges = document.timeline.insertRanges ?? [];
- if (insertRanges.length === 0) return document;
- const clips = reflowClipsForInserts(document.timeline.clips, insertRanges);
- const unchanged =
- clips.length === document.timeline.clips.length &&
- clips.every((clip, i) => {
- const was = document.timeline.clips[i];
- return (
- Math.abs(clip.timelineStartSec - was.timelineStartSec) < 1e-9 &&
- Math.abs(clip.timelineEndSec - was.timelineEndSec) < 1e-9
- );
- });
- return unchanged ? document : { ...document, timeline: { ...document.timeline, clips } };
-}
-
-/** Raw JSON (any stored version) → a validated, reconciled document. */
-export function parseStoredDocument(raw: unknown): AxcutDocument {
- return reconcileInsertions(documentSchema.parse(migrateRawDocumentToCurrent(raw)));
-}
diff --git a/src/lib/ai-edition/document/migrate.ts b/src/lib/ai-edition/document/migrate.ts
index 8d06f6b85..9315eb8c7 100644
--- a/src/lib/ai-edition/document/migrate.ts
+++ b/src/lib/ai-edition/document/migrate.ts
@@ -28,9 +28,10 @@ import {
type AxcutLegacyEditor,
type AxcutTrimRange,
type AxcutZoomRegion,
+ documentSchema,
+ migrateRawDocumentToCurrent,
} from "../schema";
import { createId } from "./ids";
-import { parseStoredDocument } from "./load";
const MS_TO_SEC = 1 / 1000;
const SEC_TO_MS = 1000;
@@ -249,7 +250,7 @@ export function migrateProjectDataToAxcutDocument(
legacyEditor,
};
- return parseStoredDocument(draft);
+ return documentSchema.parse(migrateRawDocumentToCurrent(draft));
}
/**
diff --git a/src/lib/ai-edition/document/outputFormat.test.ts b/src/lib/ai-edition/document/outputFormat.test.ts
index 2a614edd0..c7e75ab40 100644
--- a/src/lib/ai-edition/document/outputFormat.test.ts
+++ b/src/lib/ai-edition/document/outputFormat.test.ts
@@ -61,7 +61,6 @@ function doc(assets: AxcutAsset[], clips: AxcutClip[]): AxcutDocument {
clips,
gaps: [],
trimRanges: [],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/src/lib/ai-edition/document/timeline.test.ts b/src/lib/ai-edition/document/timeline.test.ts
index eabccabd8..9cbdbc5ec 100644
--- a/src/lib/ai-edition/document/timeline.test.ts
+++ b/src/lib/ai-edition/document/timeline.test.ts
@@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest";
import {
type AxcutClip,
type AxcutDocument,
- type AxcutInsertRange,
type AxcutTrimRange,
axcutSchemaVersion,
} from "../schema";
@@ -53,7 +52,6 @@ function makeDoc(overrides: Partial<AxcutDocument> = {}): AxcutDocument {
clips: [],
gaps: [],
trimRanges: [],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
@@ -214,7 +212,6 @@ describe("timeline pure functions", () => {
],
gaps: [],
trimRanges: [makeTrim({ id: "trim_1", startSec: 12, endSec: 17 })],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
@@ -312,7 +309,6 @@ describe("timeline pure functions", () => {
clips: [],
gaps: [],
trimRanges: [makeTrim({ id: "trim_other", assetId: "asset_2", startSec: 1, endSec: 2 })],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
@@ -414,7 +410,6 @@ describe("timeline pure functions", () => {
],
gaps: [],
trimRanges: [],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
@@ -540,7 +535,6 @@ describe("timeline pure functions", () => {
],
gaps: [],
trimRanges: [makeTrim({ id: "trim_1", startSec: 12, endSec: 17 })],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
@@ -617,7 +611,6 @@ describe("timeline pure functions", () => {
trimRanges: [
{ id: "s1", assetId: "asset_1", startSec: 10, endSec: 20, origin: "user", reason: "" },
],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
@@ -655,7 +648,6 @@ describe("timeline pure functions", () => {
],
gaps: [],
trimRanges: [],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
@@ -861,22 +853,22 @@ describe("projectRawTimelineSecToPlayback (issue #350 audio-track/trim sync)", (
const trim = makeTrim({ startSec: 2, endSec: 4 });
it("is the identity when there are no trims", () => {
- expect(projectRawTimelineSecToPlayback([clip], [], 6, [])).toBeCloseTo(6, 6);
+ expect(projectRawTimelineSecToPlayback([clip], [], 6)).toBeCloseTo(6, 6);
});
it("pulls a raw position after a cut earlier by the removed duration", () => {
// Raw 6 sits 2s past the 2s cut → output 4. This is the exact bug: the track was
// landing at 6 (delayed by the trim) instead of 4.
- expect(projectRawTimelineSecToPlayback([clip], [trim], 6, [])).toBeCloseTo(4, 6);
+ expect(projectRawTimelineSecToPlayback([clip], [trim], 6)).toBeCloseTo(4, 6);
});
it("is unaffected for a position before the cut", () => {
- expect(projectRawTimelineSecToPlayback([clip], [trim], 1, [])).toBeCloseTo(1, 6);
+ expect(projectRawTimelineSecToPlayback([clip], [trim], 1)).toBeCloseTo(1, 6);
});
it("collapses a position inside the trimmed gap to the end of the kept content before it", () => {
// Raw 3 is inside the removed 2..4 span → the next audible sample is at output 2.
- expect(projectRawTimelineSecToPlayback([clip], [trim], 3, [])).toBeCloseTo(2, 6);
+ expect(projectRawTimelineSecToPlayback([clip], [trim], 3)).toBeCloseTo(2, 6);
});
it("counts overlapping trims once (union, not sum)", () => {
@@ -886,7 +878,7 @@ describe("projectRawTimelineSecToPlayback (issue #350 audio-track/trim sync)", (
makeTrim({ id: "t1", startSec: 2, endSec: 5 }),
makeTrim({ id: "t2", startSec: 3, endSec: 4 }),
];
- expect(projectRawTimelineSecToPlayback([clip], trims, 6, [])).toBeCloseTo(3, 6);
+ expect(projectRawTimelineSecToPlayback([clip], trims, 6)).toBeCloseTo(3, 6);
});
it("removes a raw gap between clips (concatenated, like the programme)", () => {
@@ -906,7 +898,7 @@ describe("projectRawTimelineSecToPlayback (issue #350 audio-track/trim sync)", (
timelineStartSec: 15,
timelineEndSec: 25,
});
- expect(projectRawTimelineSecToPlayback([clipA, clipB], [], 20, [])).toBeCloseTo(15, 6);
+ expect(projectRawTimelineSecToPlayback([clipA, clipB], [], 20)).toBeCloseTo(15, 6);
});
it("sums cuts across multiple clips", () => {
@@ -930,7 +922,7 @@ describe("projectRawTimelineSecToPlayback (issue #350 audio-track/trim sync)", (
makeTrim({ id: "t2", startSec: 12, endSec: 14 }),
];
// Raw 18 is past both cuts (3s removed) → output 15.
- expect(projectRawTimelineSecToPlayback([clipA, clipB], trims, 18, [])).toBeCloseTo(15, 6);
+ expect(projectRawTimelineSecToPlayback([clipA, clipB], trims, 18)).toBeCloseTo(15, 6);
});
});
@@ -971,7 +963,6 @@ describe("duplicateClip / moveClip", () => {
...makeDoc().timeline,
clips: [makeClip({ id: "clip_a", sourceStartSec: 0, sourceEndSec: 10 })],
trimRanges: [makeTrim({ id: "t1", clipId: "clip_a", startSec: 2, endSec: 4 })],
- insertRanges: [],
},
});
const next = duplicateClip(doc, "clip_a");
@@ -1325,7 +1316,6 @@ describe("removeRegion — the one shared region-delete mutator", () => {
timeline: {
...makeDoc().timeline,
trimRanges: [makeTrim({ id: "trim_1" }), makeTrim({ id: "trim_2" })],
- insertRanges: [],
},
});
const next = removeRegion(doc, "trim", "trim_1");
@@ -1714,16 +1704,16 @@ describe("projectRawTimelineSecToPlayback with speed regions", () => {
it("halves the time a 2x stretch takes to play", () => {
// Raw 4..8 at 2x plays in 2s, so raw 8 lands at output 6.
const speed = [{ startMs: 4000, endMs: 8000, speed: 2 }];
- expect(projectRawTimelineSecToPlayback([clip], [], 4, [], speed)).toBeCloseTo(4, 6);
- expect(projectRawTimelineSecToPlayback([clip], [], 6, [], speed)).toBeCloseTo(5, 6);
- expect(projectRawTimelineSecToPlayback([clip], [], 8, [], speed)).toBeCloseTo(6, 6);
+ expect(projectRawTimelineSecToPlayback([clip], [], 4, speed)).toBeCloseTo(4, 6);
+ expect(projectRawTimelineSecToPlayback([clip], [], 6, speed)).toBeCloseTo(5, 6);
+ expect(projectRawTimelineSecToPlayback([clip], [], 8, speed)).toBeCloseTo(6, 6);
// Everything after carries the compression with it.
- expect(projectRawTimelineSecToPlayback([clip], [], 12, [], speed)).toBeCloseTo(10, 6);
+ expect(projectRawTimelineSecToPlayback([clip], [], 12, speed)).toBeCloseTo(10, 6);
});
it("stretches a slow-motion region instead", () => {
const speed = [{ startMs: 0, endMs: 4000, speed: 0.5 }];
- expect(projectRawTimelineSecToPlayback([clip], [], 4, [], speed)).toBeCloseTo(8, 6);
+ expect(projectRawTimelineSecToPlayback([clip], [], 4, speed)).toBeCloseTo(8, 6);
});
it("composes with trims", () => {
@@ -1738,97 +1728,15 @@ describe("projectRawTimelineSecToPlayback with speed regions", () => {
reason: "",
};
const speed = [{ startMs: 6000, endMs: 10_000, speed: 2 }];
- expect(projectRawTimelineSecToPlayback([clip], [trim], 12, [], speed)).toBeCloseTo(8, 6);
+ expect(projectRawTimelineSecToPlayback([clip], [trim], 12, speed)).toBeCloseTo(8, 6);
});
it("ignores a nonsense rate rather than dividing by it", () => {
const speed = [{ startMs: 0, endMs: 4000, speed: 0 }];
- expect(projectRawTimelineSecToPlayback([clip], [], 4, [], speed)).toBeCloseTo(4, 6);
+ expect(projectRawTimelineSecToPlayback([clip], [], 4, speed)).toBeCloseTo(4, 6);
});
});
// ─── The pause an added word bought ──────────────────────────────
// Created time only exists once playback honours it. These pin the one thing the record
// is for: the stream really does stay on the held frame, and the film really is longer.
-
-describe("resolvePlaybackSegments with insert ranges", () => {
- const CLIPS: AxcutClip[] = [
- {
- id: "c1",
- assetId: "a1",
- sourceStartSec: 0,
- sourceEndSec: 10,
- timelineStartSec: 0,
- timelineEndSec: 10,
- wordRefs: [],
- origin: "user",
- reason: "",
- },
- ];
- const insert = (overrides: Partial<AxcutInsertRange> = {}): AxcutInsertRange => ({
- id: "ins_1",
- assetId: "a1",
- atSec: 10,
- durationSec: 0.5,
- wordId: "synth_1",
- reason: "held",
- origin: "user",
- ...overrides,
- });
-
- it("holds the frame where the pause sits, and lengthens the stream by it", () => {
- const segments = resolvePlaybackSegments(CLIPS, [], [insert()]);
- expect(segments).toHaveLength(2);
- expect(segments[1]).toMatchObject({
- sourceStartSec: 10,
- sourceEndSec: 10,
- heldSec: 0.5,
- timelineStartSec: 10,
- timelineEndSec: 10.5,
- });
- });
-
- it("changes nothing when there is no pause", () => {
- expect(resolvePlaybackSegments(CLIPS, [], [])).toHaveLength(1);
- });
-
- // The usual case, and the one the first cut of this missed: a pause sits at the end of
- // the word it follows, which is almost never a boundary a trim happened to leave.
- it("cuts the clip open where a pause falls in the MIDDLE of it", () => {
- const segments = resolvePlaybackSegments(CLIPS, [], [insert({ atSec: 2.5 })]);
- expect(segments.map((s) => [s.sourceStartSec, s.sourceEndSec, s.heldSec])).toEqual([
- [0, 2.5, undefined],
- [2.5, 2.5, 0.5],
- [2.5, 10, undefined],
- ]);
- // 10s of film plus half a second of held frame.
- expect(segments[2].timelineEndSec).toBeCloseTo(10.5, 5);
- });
-
- // The moment the pause holds is not in the film any more, so neither is the pause.
- it("drops a pause whose moment a trim removed", () => {
- const trims: AxcutTrimRange[] = [
- { id: "t1", assetId: "a1", startSec: 4, endSec: 10, origin: "user", reason: "" },
- ];
- const segments = resolvePlaybackSegments(CLIPS, trims, [insert()]);
- expect(segments.some((s) => s.heldSec !== undefined)).toBe(false);
- });
-
- it("places a pause inside a clip between the halves a trim left", () => {
- const trims: AxcutTrimRange[] = [
- { id: "t1", assetId: "a1", startSec: 4, endSec: 6, origin: "user", reason: "" },
- ];
- const segments = resolvePlaybackSegments(CLIPS, trims, [insert({ atSec: 4 })]);
- expect(segments.map((s) => s.heldSec)).toEqual([undefined, 0.5, undefined]);
- // The stream is the kept film plus the pause: 4s + 0.5s + 4s.
- expect(segments[segments.length - 1].timelineEndSec).toBeCloseTo(8.5, 5);
- });
-
- it("never writes the held flag onto a stored clip", () => {
- // The field lives on the derived segment only; that is the whole difference from
- // the attempt that made clips for it.
- const segments = resolvePlaybackSegments(CLIPS, [], [insert()]);
- expect(CLIPS[0]).not.toHaveProperty("heldSec");
- expect(segments[0]).not.toHaveProperty("heldSec");
- });
-});
diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.ts
index c52ae3b6f..ae26d7fb7 100644
--- a/src/lib/ai-edition/document/timeline.ts
+++ b/src/lib/ai-edition/document/timeline.ts
@@ -3,25 +3,18 @@
// (store, exporter, agent) feeds an AxcutDocument and gets back intervals
// or a new document with updated clips.
-import type {
- AxcutClip,
- AxcutDocument,
- AxcutInsertRange,
- AxcutTranscript,
- AxcutTrimRange,
-} from "../schema";
+import type { AxcutClip, AxcutDocument, AxcutTranscript, AxcutTrimRange } from "../schema";
/**
* What `resolvePlaybackSegments` returns: a clip-shaped slice of playable film, plus the
- * one thing a stored clip can never carry — `heldSec`, the media an added word inserted.
+ * one thing a stored clip can never carry — `heldSec`, the pause an added word created.
*
* A held segment's source window is the single frame it shows; its LENGTH is `heldSec`.
* The field lives only on this derived shape, never on `clipSchema`, so nothing can write
* one to disk — which is the whole difference from the attempt that made clips for it.
*/
-export type PlaybackSegment = AxcutClip & { heldSec?: number };
+export type PlaybackSegment = AxcutClip;
-import { assignInsertsToClips } from "../timeline/inserted-time";
import { type Interval, subtractInterval } from "../timeline/intervals";
import { keptRawSpans } from "../timeline/programme-time";
import {
@@ -136,41 +129,6 @@ function collectWordRefs(
// after any structural change (insert / move / remove / trim) so the timeline
// never has gaps or overlaps between clips. Shared by useTimeline (UI) and
// the agent tool executor (main process) so both enforce the same invariant.
-/**
- * Clip geometry that accounts for the media inserted inside each clip (issue #560).
- *
- * An added word inserts media — a fixed frame and silence, until there is a generator for
- * it — and a clip carrying it is that much longer, exactly as it would be if the media had
- * come from a file. This is the ONE place that says so; every reader downstream then works
- * in a single coordinate, which is what makes the playhead, the native decoder and the
- * export agree without any of them converting between two rulers.
- *
- * Absolute rather than incremental, so it is idempotent: a stored clip's length is always
- * its source length (every writer above builds it that way), and re-running this on an
- * already-reflowed document changes nothing. That is what lets it also serve as the
- * migration for documents written before insertions existed.
- */
-export function reflowClipsForInserts(
- clips: AxcutClip[],
- insertRanges: readonly AxcutInsertRange[],
-): AxcutClip[] {
- // Through `assignInsertsToClips`, so the length a clip gains and the pills drawn inside it
- // come from the same assignment. They used to be computed separately, and with two clips
- // over one recording the film grew twice for an insertion drawn once.
- const byClip = assignInsertsToClips(clips, insertRanges);
- return resequenceClips(
- clips.map((clip) => {
- const sourceLen = (clip.sourceEndSec ?? clip.sourceStartSec) - clip.sourceStartSec;
- if (sourceLen <= 0) return clip; // duration not probed yet; leave it to the prober
- const owed = (byClip.get(clip.id) ?? []).reduce((sum, r) => sum + r.durationSec, 0);
- return {
- ...clip,
- timelineEndSec: clip.timelineStartSec + sourceLen + owed,
- };
- }),
- );
-}
-
export function resequenceClips(clips: AxcutClip[]): AxcutClip[] {
let cursor = 0;
return clips.map((c) => {
@@ -202,32 +160,10 @@ export function resequenceClips(clips: AxcutClip[]): AxcutClip[] {
export function resolvePlaybackSegments(
clips: AxcutClip[],
trimRanges: AxcutTrimRange[],
- insertRanges: readonly AxcutInsertRange[] = [],
): PlaybackSegment[] {
const ordered = [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec);
const result: PlaybackSegment[] = [];
let timelineCursor = 0;
- // The media added words insert, in the order they will be met. Consumed as the walk
- // passes each one's moment, so an insertion inside a span a trim removed is never reached —
- // which is right: the moment it holds is not in the film any more.
- const pending = [...insertRanges].sort((a, b) => a.atSec - b.atSec);
- const holdAt = (clip: AxcutClip, atSec: number): PlaybackSegment | null => {
- const insert = pending.find(
- (range) => range.assetId === clip.assetId && Math.abs(range.atSec - atSec) < 1e-6,
- );
- if (!insert) return null;
- pending.splice(pending.indexOf(insert), 1);
- return {
- ...clip,
- id: `${clip.id}__hold_${insert.id}`,
- sourceStartSec: atSec,
- sourceEndSec: atSec,
- timelineStartSec: 0,
- timelineEndSec: 0,
- heldSec: insert.durationSec,
- reason: insert.reason,
- };
- };
for (const clip of ordered) {
const sourceEnd = clip.sourceEndSec ?? clip.sourceStartSec;
if (sourceEnd <= clip.sourceStartSec) {
@@ -246,30 +182,7 @@ export function resolvePlaybackSegments(
if (!trimAppliesToClip(trim, clip)) continue;
kept = subtractInterval(kept, { startSec: trim.startSec, endSec: trim.endSec });
}
- // An insertion sits at the END of the word it follows, which is almost never a boundary a
- // trim happened to leave. So each kept span is cut at the moments it holds, and the
- // held frame goes between the halves: the stream plays up to that frame, stays on it
- // for the insertion, then carries on — which is what makes the film longer.
- const pieces: Array<{ startSec: number; endSec: number; holdAtEnd: boolean }> = [];
- for (const iv of kept) {
- const moments = pending
- .filter(
- (range) =>
- range.assetId === clip.assetId &&
- range.atSec > iv.startSec + 1e-6 &&
- range.atSec <= iv.endSec + 1e-6,
- )
- .map((range) => range.atSec)
- .sort((a, b) => a - b);
- let from = iv.startSec;
- for (const at of moments) {
- pieces.push({ startSec: from, endSec: Math.min(at, iv.endSec), holdAtEnd: true });
- from = Math.min(at, iv.endSec);
- }
- if (iv.endSec - from > 1e-6 || pieces.length === 0) {
- pieces.push({ startSec: from, endSec: iv.endSec, holdAtEnd: false });
- }
- }
+ const pieces = kept.map((iv) => ({ startSec: iv.startSec, endSec: iv.endSec }));
pieces.forEach((piece, i) => {
const dur = piece.endSec - piece.startSec;
if (dur > 0) {
@@ -283,15 +196,6 @@ export function resolvePlaybackSegments(
});
timelineCursor += dur;
}
- if (!piece.holdAtEnd) return;
- const hold = holdAt(clip, piece.endSec);
- if (!hold) return;
- result.push({
- ...hold,
- timelineStartSec: timelineCursor,
- timelineEndSec: timelineCursor + (hold.heldSec ?? 0),
- });
- timelineCursor += hold.heldSec ?? 0;
});
}
return result;
@@ -362,58 +266,10 @@ function outputDurationOfRawSpan(
return out;
}
-/**
- * The raw span that plays for `outSec` OUTPUT seconds starting at `fromRawSec` — the
- * inverse of {@link outputDurationOfRawSpan}, and the identity when nothing is sped up.
- *
- * A voice-over plays at 1x in the mix, so an insertion for a spoken word is D seconds of the
- * take's own clock. Under a 2x region that is 2 raw seconds, not 1, and getting it wrong
- * puts the resumed narration half an insertion out of step with the picture.
- */
-export function rawSpanForOutDuration(
- fromRawSec: number,
- outSec: number,
- speedRegions: PlaybackSpeedRegion[] = [],
-): number {
- if (!(outSec > 0)) return 0;
- if (speedRegions.length === 0) return outSec;
- // Walk the regions from the head, spending output budget piecewise.
- const edges = [
- ...new Set(
- speedRegions
- .flatMap((r) => [r.startMs / 1000, r.endMs / 1000])
- .filter((edge) => edge > fromRawSec),
- ),
- ].sort((a, b) => a - b);
- let raw = fromRawSec;
- let left = outSec;
- for (const edge of [...edges, Number.POSITIVE_INFINITY]) {
- const mid = raw + Math.min(1e-6, (edge - raw) / 2);
- const region = speedRegions.find(
- (r) => mid >= r.startMs / 1000 && mid < r.endMs / 1000 && r.speed > 0,
- );
- const speed = region?.speed ?? 1;
- const rawAvailable = edge - raw;
- const outAvailable = rawAvailable / speed;
- if (outAvailable >= left) return raw + left * speed - fromRawSec;
- raw = edge;
- left -= outAvailable;
- }
- return raw - fromRawSec;
-}
-
export function projectRawTimelineSecToPlayback(
clips: AxcutClip[],
trimRanges: AxcutTrimRange[],
rawSec: number,
- /**
- * The insertions, so the kept spans below can carry them.
- *
- * REQUIRED, not optional: an optional parameter would silently keep the early-audio bug
- * alive at every site not yet touched — the one that shows up as "the music starts a
- * beat early" months later.
- */
- insertRanges: readonly AxcutInsertRange[],
/**
* Speed regions on the raw ruler. Supplied by the AUDIO paths, which overlay
* a 1x track onto the finished programme and so need its real, speed-adjusted
@@ -429,22 +285,17 @@ export function projectRawTimelineSecToPlayback(
// The kept stretches come from `keptRawSpans`, which is this walk — it was lifted out of
// here so the transcript lanes and the audio mix could ask the same question and get the
- // same answer (issue #560). It carries the insertions too: they are timeline seconds like
- // any other, which is exactly what one clock buys — this walk used to interleave them
- // itself, and every reader that forgot to had audio landing early.
- //
- // Trims only REMOVE, so a kept span's length is what survives; how long it takes to PLAY
- // is a separate question `outputDurationOfRawSpan` answers, because a speed region scales
- // it.
- for (const seg of keptRawSpans(ordered, trimRanges, insertRanges)) {
- const from = seg.startSec;
+ // same answer (issue #560). Trims only REMOVE, so a kept span's RAW length is what
+ // survives; how long it takes to PLAY is a separate question `outputDurationOfRawSpan`
+ // answers, because a speed region scales it.
+ for (const seg of keptRawSpans(ordered, trimRanges)) {
if (landed === null && rawSec < seg.endSec) {
// `rawSec` is inside this segment, or before it in a trimmed/gap region (then
// the span clamps to nothing → the output edge just before the gap).
- const within = Math.min(Math.max(rawSec, from), seg.endSec);
- landed = outCursor + outputDurationOfRawSpan(from, within, speedRegions);
+ const within = Math.min(Math.max(rawSec, seg.startSec), seg.endSec);
+ landed = outCursor + outputDurationOfRawSpan(seg.startSec, within, speedRegions);
}
- outCursor += outputDurationOfRawSpan(from, seg.endSec, speedRegions);
+ outCursor += outputDurationOfRawSpan(seg.startSec, seg.endSec, speedRegions);
lastRawEnd = seg.endSec;
}
// Past every kept frame: programme end plus whatever raw time hangs off the end (identity when
@@ -1161,12 +1012,9 @@ export function removeRegion(document: AxcutDocument, kind: RegionKind, id: stri
...document,
timeline: {
...document.timeline,
- trimRanges: dropTrimPillsByIds(
- document.timeline.trimRanges,
- document.timeline.clips,
- [id],
- document.timeline.insertRanges ?? [],
- ),
+ trimRanges: dropTrimPillsByIds(document.timeline.trimRanges, document.timeline.clips, [
+ id,
+ ]),
},
};
case "speed": {
diff --git a/src/lib/ai-edition/document/transcribe.test.ts b/src/lib/ai-edition/document/transcribe.test.ts
index 6a0656c23..0ca221a8c 100644
--- a/src/lib/ai-edition/document/transcribe.test.ts
+++ b/src/lib/ai-edition/document/transcribe.test.ts
@@ -51,7 +51,6 @@ function makeDoc(): AxcutDocument {
clips: [],
gaps: [],
trimRanges: [],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/src/lib/ai-edition/document/transcript.test.ts b/src/lib/ai-edition/document/transcript.test.ts
index fdc3909d1..1bc1f5451 100644
--- a/src/lib/ai-edition/document/transcript.test.ts
+++ b/src/lib/ai-edition/document/transcript.test.ts
@@ -1,16 +1,6 @@
import { describe, expect, it } from "vitest";
-import { type AxcutTranscript, createEmptyDocument, documentSchema } from "../schema";
-import {
- carryOverWordEdits,
- insertDocumentWord,
- insertRangesMatchWords,
- insertWord,
- removeDocumentWords,
- removeWord,
- setDocumentWordText,
- setWordText,
- withTranscript,
-} from "./transcript";
+import { type AxcutTranscript, createEmptyDocument } from "../schema";
+import { carryOverWordEdits, setDocumentWordText, setWordText, withTranscript } from "./transcript";
function fixture(language = "en"): AxcutTranscript {
return {
@@ -493,329 +483,3 @@ describe("carryOverWordEdits", () => {
expect(carryOverWordEdits(null, next).transcript).toBe(next);
});
});
-
-// ─── Inserting a word nobody said ────────────────────────────────
-// The word carries no audio, so what it may occupy is the silence around it and nothing
-// else. These pin that boundary: never over a spoken word, never a duration invented out
-// of nothing when there is no pause to take.
-
-describe("insertWord", () => {
- // "I"(1–2) "use"(2–3) "OpenScreen"(3–4), then a gap, then segment 2 at 5.
- it("takes the silence after the word it follows, up to what its text needs", () => {
- const result = insertWord(fixture(), "word_3", "after", "everywhere");
- const inserted = result.words.find((w) => w.source === "synth");
- expect(inserted?.startSec).toBe(4);
- // 10 characters at 15/s = 0.67s, and the next word is a full second away.
- expect(inserted?.endSec).toBeCloseTo(4 + 10 / 15, 5);
- });
-
- it("never runs over the word that comes next", () => {
- // "use" ends at 3 and "OpenScreen" starts there: a long word gets no room at all.
- const inserted = insertWord(fixture(), "word_2", "after", "a very long addition").words.find(
- (w) => w.source === "synth",
- );
- expect(inserted).toMatchObject({ startSec: 3, endSec: 3 });
- });
-
- it("borrows backwards when it goes before the first word", () => {
- const inserted = insertWord(fixture(), "word_1", "before", "Well").words.find(
- (w) => w.source === "synth",
- );
- // "word_1" starts at 1, and nothing precedes it — the floor is the media's own start.
- expect(inserted?.endSec).toBe(1);
- expect(inserted?.startSec).toBeCloseTo(1 - 0.4, 5);
- });
-
- it("marks it synthesized, with an id no transcription run can reuse", () => {
- const inserted = insertWord(fixture(), "word_3", "after", "indeed").words.find(
- (w) => w.source === "synth",
- );
- expect(inserted).toMatchObject({ text: "indeed", source: "synth", segmentId: "segment_1" });
- expect(inserted?.id).toMatch(/^synth_\d+$/);
- expect(inserted).not.toHaveProperty("originalText");
- });
-
- it("numbers past the inserts already there", () => {
- const once = insertWord(fixture(), "word_3", "after", "one");
- const twice = insertWord(once, "word_3", "after", "two");
- const ids = twice.words.filter((w) => w.source === "synth").map((w) => w.id);
- expect(new Set(ids).size).toBe(2);
- expect(ids).toContain("synth_2");
- });
-
- it("lands in the segment's reading order, and rebuilds its text", () => {
- const transcript = fixture();
- const result = insertWord(transcript, "word_2", "after", "really");
- const segment = result.segments.find((seg) => seg.id === "segment_1");
- expect(segment?.wordIds).toEqual(["word_1", "word_2", "synth_1", "word_3"]);
- expect(segment?.text).toBe("I use really OpenScreen");
- // The segment the insert did not land in is carried over untouched, not rebuilt.
- expect(result.segments[1]).toBe(transcript.segments[1]);
- });
-
- it("sits beside its anchor in the words array, which is what orders a zero-length insert", () => {
- const result = insertWord(fixture(), "word_2", "after", "really");
- const ids = result.words.map((w) => w.id);
- expect(ids.indexOf("synth_1")).toBe(ids.indexOf("word_2") + 1);
- });
-
- it("refuses empty text and unknown anchors", () => {
- expect(() => insertWord(fixture(), "word_2", "after", " ")).toThrow(/empty/);
- expect(() => insertWord(fixture(), "nope", "after", "x")).toThrow(/missing/);
- });
-
- it("keeps the input transcript untouched", () => {
- const transcript = fixture();
- const before = JSON.stringify(transcript);
- insertWord(transcript, "word_2", "after", "really");
- expect(JSON.stringify(transcript)).toBe(before);
- });
-});
-
-describe("removeWord", () => {
- const withInsert = () => insertWord(fixture(), "word_2", "after", "really");
-
- it("takes the word out of the array, the segment, and its text", () => {
- const result = removeWord(withInsert(), "synth_1");
- expect(result.words.some((w) => w.id === "synth_1")).toBe(false);
- const segment = result.segments.find((seg) => seg.id === "segment_1");
- expect(segment?.wordIds).toEqual(["word_1", "word_2", "word_3"]);
- expect(segment?.text).toBe("I use OpenScreen");
- });
-
- // Deleting a transcribed word would leave the film saying something the transcript
- // denies. The operation for making a spoken word go away is a trim.
- it("refuses a word that was actually spoken", () => {
- expect(() => removeWord(fixture(), "word_2")).toThrow(/Refusing to remove transcribed word/);
- });
-
- it("refuses a word that is not there", () => {
- expect(() => removeWord(fixture(), "nope")).toThrow(/missing/);
- });
-});
-
-describe("insertDocumentWord / removeDocumentWords", () => {
- it("writes both the per-asset transcript and the legacy mirror", () => {
- const result = insertDocumentWord(makeDoc(), "asset_1", "word_2", "after", "really");
- expect(result.transcript?.words.some((w) => w.id === "synth_1")).toBe(true);
- expect(result.transcript).toBe(result.transcripts.find((t) => t.assetId === "asset_1"));
- });
-
- // One save for the whole set: a Backspace over three inserted words must be one Ctrl+Z.
- it("removes several inserted words in a single document", () => {
- let doc = insertDocumentWord(makeDoc(), "asset_1", "word_2", "after", "one");
- doc = insertDocumentWord(doc, "asset_1", "word_3", "after", "two");
- const result = removeDocumentWords(doc, "asset_1", ["synth_1", "synth_2"]);
- expect(result.transcripts[0].words.some((w) => w.source === "synth")).toBe(false);
- });
-
- it("rejects an asset with no transcript", () => {
- expect(() => insertDocumentWord(makeDoc(), "nope", "word_2", "after", "x")).toThrow(
- /no transcript/,
- );
- });
-});
-
-describe("carryOverWordEdits with inserted words", () => {
- const withInsert = () => insertWord(fixture(), "word_2", "after", "really");
-
- it("puts an insert back after whatever the new run now ends last before it", () => {
- // The insert sits at 3s. The new transcript says "I"(1–2) "used"(2–3) "it"(3.5–4).
- const next = retranscribed([
- ["n1", "I", 1, 2],
- ["n2", "used", 2, 3],
- ["n3", "it", 3.5, 4],
- ]);
- const result = carryOverWordEdits(withInsert(), next);
- expect(result).toMatchObject({ carried: 1, dropped: 0 });
- const ids = result.transcript.words.map((w) => w.id);
- expect(ids.indexOf("synth_1")).toBe(ids.indexOf("n2") + 1);
- expect(result.transcript.words.find((w) => w.id === "synth_1")).toMatchObject({
- text: "really",
- source: "synth",
- });
- });
-
- it("puts it at the head when the new run has nothing before it", () => {
- const carried = carryOverWordEdits(
- insertWord(fixture(), "word_1", "before", "Well"),
- retranscribed([["n1", "I", 1, 2]]),
- );
- expect(carried.carried).toBe(1);
- expect(carried.transcript.words[0].text).toBe("Well");
- });
-
- it("counts an insert it could not place, rather than losing it quietly", () => {
- const empty: AxcutTranscript = { assetId: "asset_1", language: "en", segments: [], words: [] };
- expect(carryOverWordEdits(withInsert(), empty)).toMatchObject({ carried: 0, dropped: 1 });
- });
-
- it("carries corrections and inserts together", () => {
- const both = insertWord(
- setWordText(fixture(), "word_3", "OpenScreenApp"),
- "word_2",
- "after",
- "really",
- );
- const next = retranscribed([
- ["n1", "I", 1, 2],
- ["n2", "use", 2, 3],
- ["n3", "OpenScreen", 3, 4],
- ]);
- const result = carryOverWordEdits(both, next);
- expect(result).toMatchObject({ carried: 2, dropped: 0 });
- expect(result.transcript.words.find((w) => w.id === "n3")?.text).toBe("OpenScreenApp");
- expect(result.transcript.words.some((w) => w.text === "really")).toBe(true);
- });
-});
-
-// ─── The pause an added word needs ───────────────────────────────
-// Created time is STORED, as a region beside the trims. Something has to keep those
-// records true against the words they belong to, and `withInsertRangesForWords` is the one
-// writer — these hold it to the invariant it maintains. The first attempt at this made
-// CLIPS instead, and every other writer of `timeline.clips` disagreed with them.
-
-describe("insert ranges", () => {
- function docWithClip() {
- const doc = makeDoc();
- return {
- ...doc,
- timeline: {
- ...doc.timeline,
- clips: [
- {
- id: "clip_1",
- assetId: "asset_1",
- sourceStartSec: 0,
- sourceEndSec: 10,
- timelineStartSec: 0,
- timelineEndSec: 10,
- wordRefs: [],
- origin: "user" as const,
- reason: "",
- },
- ],
- },
- };
- }
-
- it("stores a pause when the free silence does not cover the word", () => {
- // "really" after word_2: word_3 starts exactly where word_2 ends, so the word
- // borrows nothing and needs its whole reading time — max(0.4, 6/15) = 0.4s.
- const result = insertDocumentWord(docWithClip(), "asset_1", "word_2", "after", "really");
- expect(result.timeline.insertRanges).toHaveLength(1);
- expect(result.timeline.insertRanges[0]).toMatchObject({
- assetId: "asset_1",
- wordId: "synth_1",
- atSec: 3,
- durationSec: 0.4,
- origin: "user",
- });
- expect(insertRangesMatchWords(result)).toBe(true);
- });
-
- // The reason is user-visible on the region, and the two lanes do not hold the same
- // thing: the film holds a FRAME, a take holds silence and no picture is involved
- // (issue #560). The keying above is lane-agnostic and stays that way — one row per
- // word per asset, whichever lane the asset is on.
- it("names what is actually held, per lane", () => {
- const film = insertDocumentWord(docWithClip(), "asset_1", "word_2", "after", "really");
- expect(film.timeline.insertRanges[0].reason).toContain("Held frame");
-
- // `createEmptyDocument` carries no assets, so the lane has to be given one to read.
- const base = docWithClip();
- const take = insertDocumentWord(
- {
- ...base,
- assets: [
- {
- id: "asset_1",
- kind: "audio" as const,
- label: "take.mp3",
- originalPath: "/take.mp3",
- durationSec: 30,
- cameraTrack: null,
- },
- ],
- },
- "asset_1",
- "word_2",
- "after",
- "really",
- );
- expect(take.timeline.insertRanges[0].reason).toContain("Silence");
- expect(take.timeline.insertRanges[0].reason).not.toContain("frame");
- // Same row otherwise, and the invariant still holds on an audio asset.
- expect(take.timeline.insertRanges[0]).toMatchObject({ atSec: 3, durationSec: 0.4 });
- expect(insertRangesMatchWords(take)).toBe(true);
- });
-
- // An insertion is MEDIA inside the clip, so the clip carrying it is exactly that much
- // longer — the one fact every reader downstream depends on, and the reason none of them
- // needs a second ruler to convert to. Its source window is untouched: no frame of the
- // recording was added or removed.
- it("lengthens the clip that carries the insertion, by the insertion", () => {
- const before = docWithClip();
- const result = insertDocumentWord(before, "asset_1", "word_2", "after", "really");
- const [range] = result.timeline.insertRanges;
- const was = before.timeline.clips[0];
- const now = result.timeline.clips[0];
- expect(now.timelineEndSec - now.timelineStartSec).toBeCloseTo(
- was.timelineEndSec - was.timelineStartSec + range.durationSec,
- 5,
- );
- expect(now.sourceStartSec).toBe(was.sourceStartSec);
- expect(now.sourceEndSec).toBe(was.sourceEndSec);
- });
-
- it("gives the length back when the word goes", () => {
- const before = docWithClip();
- const added = insertDocumentWord(before, "asset_1", "word_2", "after", "really");
- const removed = removeDocumentWords(added, "asset_1", ["synth_1"]);
- expect(removed.timeline.clips).toEqual(before.timeline.clips);
- });
-
- it("stores nothing when the word fits in silence that is already there", () => {
- // word_3 ends at 4 and word_4 starts at 5: a full second, more than "really" needs.
- const result = insertDocumentWord(docWithClip(), "asset_1", "word_3", "after", "really");
- expect(result.timeline.insertRanges).toEqual([]);
- expect(insertRangesMatchWords(result)).toBe(true);
- });
-
- it("resizes the pause when the word is rewritten longer", () => {
- const added = insertDocumentWord(docWithClip(), "asset_1", "word_2", "after", "really");
- const longer = setDocumentWordText(added, "asset_1", "synth_1", "really quite genuinely so");
- const [range] = longer.timeline.insertRanges;
- expect(range.durationSec).toBeCloseTo(25 / 15, 5);
- expect(range.id).toBe(added.timeline.insertRanges[0].id);
- expect(insertRangesMatchWords(longer)).toBe(true);
- });
-
- it("drops the pause with the word", () => {
- const added = insertDocumentWord(docWithClip(), "asset_1", "word_2", "after", "really");
- const gone = removeDocumentWords(added, "asset_1", ["synth_1"]);
- expect(gone.timeline.insertRanges).toEqual([]);
- expect(insertRangesMatchWords(gone)).toBe(true);
- });
-
- it("keeps one pause per added word, and no more", () => {
- let doc = insertDocumentWord(docWithClip(), "asset_1", "word_2", "after", "really");
- doc = insertDocumentWord(doc, "asset_1", "word_1", "after", "personally");
- expect(doc.timeline.insertRanges).toHaveLength(2);
- expect(new Set(doc.timeline.insertRanges.map((r) => r.wordId)).size).toBe(2);
- expect(insertRangesMatchWords(doc)).toBe(true);
- });
-
- // Correcting a SPOKEN word must not invent a pause: it has audio behind it already.
- it("stores nothing for an ordinary correction", () => {
- const result = setDocumentWordText(docWithClip(), "asset_1", "word_3", "OpenScreenApp");
- expect(result.timeline.insertRanges).toEqual([]);
- });
-
- it("survives the document schema", () => {
- const added = insertDocumentWord(docWithClip(), "asset_1", "word_2", "after", "really");
- const parsed = documentSchema.parse(JSON.parse(JSON.stringify(added)));
- expect(parsed.timeline.insertRanges).toHaveLength(1);
- expect(insertRangesMatchWords(parsed)).toBe(true);
- });
-});
diff --git a/src/lib/ai-edition/document/transcript.ts b/src/lib/ai-edition/document/transcript.ts
index 82df1928d..dec291474 100644
--- a/src/lib/ai-edition/document/transcript.ts
+++ b/src/lib/ai-edition/document/transcript.ts
@@ -1,6 +1,4 @@
-import type { AxcutDocument, AxcutInsertRange, AxcutTranscript, AxcutWord } from "../schema";
-import { createId } from "./ids";
-import { reflowClipsForInserts } from "./timeline";
+import type { AxcutDocument, AxcutTranscript, AxcutWord } from "../schema";
const CJK_EDGE = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u;
const CLOSING_PUNCTUATION = /^[,.;:!?%。,、;:!?…))\]}>》」』】〕]/u;
@@ -146,12 +144,7 @@ export function setDocumentWordText(
if (!transcript) {
throw new Error(`Cannot edit a word of asset "${assetId}": it has no transcript`);
}
- // Rewriting an added word changes how long it takes to read, so its pause is resized
- // here too — the one writer, whatever the edit was.
- return withInsertRangesForWords(
- withTranscript(document, setWordText(transcript, wordId, text)),
- assetId,
- );
+ return withTranscript(document, setWordText(transcript, wordId, text));
}
/** Where a new word goes relative to the word the caret was resting on. */
@@ -308,171 +301,8 @@ export function removeWord(transcript: AxcutTranscript, wordId: string): AxcutTr
};
}
-/**
- * How much created time an added word still needs, on top of the silence it borrowed.
- *
- * Zero when the pause it landed in was already long enough — an added word between two
- * sentences costs the film nothing.
- */
-function pauseDeficitSec(word: AxcutWord): number {
- const borrowed = word.endSec - word.startSec;
- return Math.max(0, readingSeconds(word.text) - borrowed);
-}
-
-/** Below this, a pause is not worth a record — a few milliseconds of held frame is a
- * stutter, not a slot to speak in. */
-const MIN_PAUSE_SEC = 0.05;
-
-/**
- * Bring the document's insert ranges back in line with its words.
- *
- * The ranges are STORED, so something has to keep them true; this is that something, and
- * it is the only writer. Called after every word write, it adds the pause an added word
- * needs, resizes one whose text changed length, and drops the ones whose word is gone —
- * so no caller has to remember any of the three. `insertRangesMatchWords` is the same rule
- * read back, for a test to hold this to.
- */
-/** `synth_N` — the id every added word has been minted with, and the one thing a row
- * written before the `source` field carries to say what it is. */
-const SYNTH_WORD_ID = /^synth_\d+$/;
-
-/**
- * Added words that never got marked as such, marked.
- *
- * `source: "synth"` is how the whole pipeline recognises a word the user typed: it decides
- * whether the word gets an insertion, whether the film makes room for it, and whether the
- * caption line breaks around it. A row minted before that field existed answers no to all
- * three, so its text plays over the recording and everything after it drifts. The id is the
- * evidence — `nextSynthWordId` has always minted exactly this shape, and the numbering scan
- * already reads it back with the same pattern.
- */
-export function withMarkedAddedWords(document: AxcutDocument): AxcutDocument {
- let touched = false;
- const transcripts = document.transcripts.map((transcript) => {
- let changed = false;
- const words = transcript.words.map((word) => {
- if (word.source !== undefined || !SYNTH_WORD_ID.test(word.id)) return word;
- changed = true;
- return { ...word, source: "synth" as const };
- });
- if (!changed) return transcript;
- touched = true;
- return { ...transcript, words };
- });
- return touched ? { ...document, transcripts } : document;
-}
-
-/**
- * Every asset's insert ranges brought back in line with its words.
- *
- * The per-asset reconciler applied to the whole document, so a load can enforce the
- * invariant it maintains rather than waiting for the next word write to notice.
- */
-export function withInsertRangesForAllWords(document: AxcutDocument): AxcutDocument {
- return document.transcripts.reduce(
- (doc, transcript) => withInsertRangesForWords(doc, transcript.assetId),
- document,
- );
-}
-
-function withInsertRangesForWords(document: AxcutDocument, assetId: string): AxcutDocument {
- // The reason is user-visible on the region, and it is not the same fact on both lanes:
- // the film holds a FRAME, a take holds nothing but silence — no picture is involved
- // (issue #560). Keying, below, stays lane-agnostic: one row per word per asset.
- const isTake = document.assets.find((a) => a.id === assetId)?.kind === "audio";
- const transcript = document.transcripts.find((t) => t.assetId === assetId);
- const words = transcript?.words ?? [];
- const wanted = new Map<string, number>();
- for (const word of words) {
- if (word.source !== "synth") continue;
- const deficit = pauseDeficitSec(word);
- if (deficit >= MIN_PAUSE_SEC) wanted.set(word.id, deficit);
- }
-
- const existing = document.timeline.insertRanges;
- const kept: AxcutInsertRange[] = [];
- const seen = new Set<string>();
- for (const range of existing) {
- // Ranges for OTHER assets are none of this call's business.
- if (range.assetId !== assetId) {
- kept.push(range);
- continue;
- }
- const durationSec = wanted.get(range.wordId);
- if (durationSec === undefined) continue; // its word is gone, or needs no pause now
- seen.add(range.wordId);
- const word = words.find((w) => w.id === range.wordId);
- const atSec = word?.endSec ?? range.atSec;
- kept.push(
- durationSec === range.durationSec && atSec === range.atSec
- ? range
- : { ...range, atSec, durationSec },
- );
- }
- for (const [wordId, durationSec] of wanted) {
- if (seen.has(wordId)) continue;
- const word = words.find((w) => w.id === wordId);
- if (!word) continue;
- kept.push({
- id: createId("insert"),
- assetId,
- atSec: word.endSec,
- durationSec,
- wordId,
- reason: isTake
- ? `Silence for the added word "${word.text}".`
- : `Held frame for the added word "${word.text}".`,
- origin: "user",
- });
- }
-
- if (kept.length === existing.length && kept.every((range, i) => range === existing[i])) {
- return document;
- }
- // The clips grow with them. An insertion is media inside the clip, so the clip is that
- // much longer — the single fact every downstream reader needs, written once, here, where
- // the ranges themselves are written.
- return {
- ...document,
- timeline: {
- ...document.timeline,
- insertRanges: kept,
- clips: reflowClipsForInserts(document.timeline.clips, kept),
- },
- };
-}
-
-/**
- * The invariant {@link withInsertRangesForWords} maintains, read back: every stored pause
- * belongs to an added word that still needs one, sits where that word ends, and lasts what
- * its text needs. Exported for the test that holds the writer to it.
- */
-export function insertRangesMatchWords(document: AxcutDocument): boolean {
- const byAsset = new Map(document.transcripts.map((t) => [t.assetId, t]));
- const expected = new Set<string>();
- for (const transcript of document.transcripts) {
- for (const word of transcript.words) {
- if (word.source === "synth" && pauseDeficitSec(word) >= MIN_PAUSE_SEC) {
- expected.add(`${transcript.assetId}::${word.id}`);
- }
- }
- }
- const seen = new Set<string>();
- for (const range of document.timeline.insertRanges) {
- const key = `${range.assetId}::${range.wordId}`;
- if (!expected.has(key) || seen.has(key)) return false;
- seen.add(key);
- const word = byAsset.get(range.assetId)?.words.find((w) => w.id === range.wordId);
- if (!word) return false;
- if (range.atSec !== word.endSec) return false;
- if (Math.abs(range.durationSec - pauseDeficitSec(word)) > 1e-9) return false;
- }
- return seen.size === expected.size;
-}
-
/** {@link insertWord}, addressed by asset. Goes through `withTranscript` for the same
- * reason {@link setDocumentWordText} does, and leaves behind the pause the new word
- * needs — see {@link withInsertRangesForWords}. */
+ * reason {@link setDocumentWordText} does. */
export function insertDocumentWord(
document: AxcutDocument,
assetId: string,
@@ -484,10 +314,7 @@ export function insertDocumentWord(
if (!transcript) {
throw new Error(`Cannot insert a word into asset "${assetId}": it has no transcript`);
}
- return withInsertRangesForWords(
- withTranscript(document, insertWord(transcript, anchorWordId, side, text)),
- assetId,
- );
+ return withTranscript(document, insertWord(transcript, anchorWordId, side, text));
}
/** {@link removeWord}, addressed by asset and taking the whole set at once: a Backspace
@@ -502,12 +329,9 @@ export function removeDocumentWords(
if (!transcript) {
throw new Error(`Cannot remove a word from asset "${assetId}": it has no transcript`);
}
- return withInsertRangesForWords(
- withTranscript(
- document,
- wordIds.reduce((acc, wordId) => removeWord(acc, wordId), transcript),
- ),
- assetId,
+ return withTranscript(
+ document,
+ wordIds.reduce((acc, wordId) => removeWord(acc, wordId), transcript),
);
}
diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.ts
index 8a715ab0e..d37f500b3 100644
--- a/src/lib/ai-edition/schema/index.ts
+++ b/src/lib/ai-edition/schema/index.ts
@@ -274,34 +274,6 @@ export const trimRangeSchema = endGteStart(
"startSec",
);
-/**
- * Time the film does NOT have: the pause an added word needs so a synthesized voice will
- * have somewhere to speak. The film holds the frame at `atSec` for `durationSec`, screen
- * and webcam together, and everything after it shifts.
- *
- * The exact inverse of a trim, and stored the same way and for the same reason. The first
- * attempt created CLIPS for this; every other writer of `timeline.clips` — the duration
- * probe, the recording import, resequencing — is entitled to disagree with a clip it did
- * not make, and they did: a project came back split twice, both pauses gone, and the words
- * they belonged to with them. A region is the shape this timeline already carries safely.
- *
- * `wordId` is what makes it derived-in-spirit while stored in fact: `document/transcript.ts`
- * is the only writer, it creates the range with the word and drops it with the word, and
- * `insertRangesMatchWords` is the invariant a test holds it to. Nothing else may write one.
- */
-export const insertRangeSchema = z.object({
- id: z.string().min(1),
- assetId: z.string().min(1),
- /** Source moment the film holds on. */
- atSec: z.number().nonnegative(),
- /** Timeline time created. Always positive — a pause of zero is simply not stored. */
- durationSec: z.number().positive(),
- /** The transcript word this pause exists for. */
- wordId: z.string().min(1),
- reason: z.string().default(""),
- origin: z.enum(["system", "agent", "user"]),
-});
-
export const timelineSchema = z.preprocess(
// Back-compat: the field was renamed skipRanges → trimRanges. Old persisted
// documents (disk + browser-shim localStorage) still carry `skipRanges`;
@@ -322,7 +294,6 @@ export const timelineSchema = z.preprocess(
// Additive, like every optional field before it: absent on every document written
// before this, so no schema bump — an older build simply drops the key on save, and
// the words it belonged to keep their text and lose only their pause.
- insertRanges: z.array(insertRangeSchema).default([]),
muteRanges: z.array(rangeSchema).default([]),
speedRanges: z.array(rangeSchema).default([]),
captionRanges: z.array(rangeSchema).default([]),
@@ -618,7 +589,6 @@ const documentSchemaShape = z.object({
clips: [],
gaps: [],
trimRanges: [],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
@@ -1116,7 +1086,6 @@ export type AxcutClip = z.infer<typeof clipSchema>;
export type AxcutClipCropRegion = z.infer<typeof clipCropRegionSchema>;
export type AxcutGap = z.infer<typeof gapSchema>;
export type AxcutTrimRange = z.infer<typeof trimRangeSchema>;
-export type AxcutInsertRange = z.infer<typeof insertRangeSchema>;
export type AxcutTimeline = z.infer<typeof timelineSchema>;
export type AxcutTimelineOperation = z.infer<typeof timelineOperationSchema>;
export type AxcutAnnotationRegion = z.infer<typeof annotationRegionSchema>;
diff --git a/src/lib/ai-edition/store/editorSettings.test.ts b/src/lib/ai-edition/store/editorSettings.test.ts
index 1e8cc43de..ec37d7176 100644
--- a/src/lib/ai-edition/store/editorSettings.test.ts
+++ b/src/lib/ai-edition/store/editorSettings.test.ts
@@ -23,7 +23,6 @@ const baseDoc: AxcutDocument = {
clips: [],
gaps: [],
trimRanges: [],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/src/lib/ai-edition/store/projectStore.test.ts b/src/lib/ai-edition/store/projectStore.test.ts
index 18df17063..2b75f0a04 100644
--- a/src/lib/ai-edition/store/projectStore.test.ts
+++ b/src/lib/ai-edition/store/projectStore.test.ts
@@ -67,7 +67,6 @@ const sampleDoc = {
clips: [],
gaps: [],
trimRanges: [],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/src/lib/ai-edition/store/projectStore.ts b/src/lib/ai-edition/store/projectStore.ts
index 4af906cd4..fd47da9cc 100644
--- a/src/lib/ai-edition/store/projectStore.ts
+++ b/src/lib/ai-edition/store/projectStore.ts
@@ -5,7 +5,6 @@ import { toastText } from "@/i18n/toastText";
import { nativeBridgeClient } from "@/native/client";
import { placeAudioTrackInDocument } from "../document/audioTracks";
import { createId } from "../document/ids";
-import { reconcileInsertions } from "../document/load";
import { type Interval, replaceTimeline as replaceTimelineOp } from "../document/timeline";
import { type AxcutAsset, type AxcutDocument, createAudioTrack, documentSchema } from "../schema";
import { probeAudioDuration, probeVideoDimensions } from "../timeline/duration";
@@ -159,10 +158,7 @@ export interface ProjectState {
}
function parseDocument(value: unknown): AxcutDocument {
- // Reconciled here too, not only in the main process: this is the renderer's own gate on
- // every document it accepts, and it is idempotent, so a document that arrived correct
- // passes through untouched.
- return reconcileInsertions(documentSchema.parse(value));
+ return documentSchema.parse(value);
}
/**
diff --git a/src/lib/ai-edition/store/undo.modalGuard.test.tsx b/src/lib/ai-edition/store/undo.modalGuard.test.tsx
index 834103e60..46e083b0b 100644
--- a/src/lib/ai-edition/store/undo.modalGuard.test.tsx
+++ b/src/lib/ai-edition/store/undo.modalGuard.test.tsx
@@ -29,7 +29,6 @@ function doc(title: string): AxcutDocument {
clips: [],
gaps: [],
trimRanges: [],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/src/lib/ai-edition/store/useCaptions.test.ts b/src/lib/ai-edition/store/useCaptions.test.ts
index 84694923c..0cd641328 100644
--- a/src/lib/ai-edition/store/useCaptions.test.ts
+++ b/src/lib/ai-edition/store/useCaptions.test.ts
@@ -65,7 +65,6 @@ const docA: AxcutDocument = {
clips: [],
gaps: [],
trimRanges: [],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/src/lib/ai-edition/store/useEditorSettings.test.ts b/src/lib/ai-edition/store/useEditorSettings.test.ts
index fe433f070..4122c05bf 100644
--- a/src/lib/ai-edition/store/useEditorSettings.test.ts
+++ b/src/lib/ai-edition/store/useEditorSettings.test.ts
@@ -68,7 +68,6 @@ const docA: AxcutDocument = {
clips: [],
gaps: [],
trimRanges: [],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/src/lib/ai-edition/store/useTimeline.test.ts b/src/lib/ai-edition/store/useTimeline.test.ts
index ecb5dced9..7b77e9c46 100644
--- a/src/lib/ai-edition/store/useTimeline.test.ts
+++ b/src/lib/ai-edition/store/useTimeline.test.ts
@@ -106,7 +106,6 @@ const sampleDoc: AxcutDocument = {
],
gaps: [],
trimRanges: [],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.ts
index 79e4340f6..06a4e6b90 100644
--- a/src/lib/ai-edition/store/useTimeline.ts
+++ b/src/lib/ai-edition/store/useTimeline.ts
@@ -371,12 +371,7 @@ export function useTimeline() {
// the trim at the wrong source position.
const playhead = playheadSec();
const end = playhead + durationSec;
- const resolved = resolveTimelineSpanToTrim(
- playhead,
- end,
- document.timeline.clips,
- document.timeline.insertRanges ?? [],
- );
+ const resolved = resolveTimelineSpanToTrim(playhead, end, document.timeline.clips);
const asset =
document.assets.find((a) => a.id === document.project.primaryAssetId) ?? document.assets[0];
if (!resolved && !asset) return;
@@ -957,7 +952,6 @@ export function useTimeline() {
document.timeline.trimRanges,
document.timeline.clips,
trimIds,
- document.timeline.insertRanges ?? [],
),
},
legacyEditor:
@@ -1460,7 +1454,6 @@ export function useTimeline() {
audioTracks: document?.audioTracks ?? [],
// The pauses added words created. The ruler counts them; nothing else in the
// timeline store writes them (see `document/transcript.ts`).
- insertRanges: document?.timeline.insertRanges ?? [],
annotationRegions: (document?.annotations ?? []) as unknown as AnnotationRegion[],
speedRegions,
cameraFullscreenRegions,
diff --git a/src/lib/ai-edition/timeline/aggregated-transcript.lanes.test.ts b/src/lib/ai-edition/timeline/aggregated-transcript.lanes.test.ts
index d4aa314e5..9cfebde27 100644
--- a/src/lib/ai-edition/timeline/aggregated-transcript.lanes.test.ts
+++ b/src/lib/ai-edition/timeline/aggregated-transcript.lanes.test.ts
@@ -88,20 +88,6 @@ describe("voiceoverPlacements", () => {
[4, 4, 6],
]);
});
-
- it("maps the words after an insertion to the moment they actually occupy", () => {
- // The reason this stopped being per-fragment. Source 4 is heard at ruler 5, because
- // the pause before it took a second of the take's span.
- const placements = voiceoverPlacements(
- [track({ id: "f1", trackId: "T", startMs: 0, endMs: 6000, offsetMs: 0 })],
- [],
- () => [{ id: "i1", wordId: "w1", atSourceSec: 4, durationSec: 1 }],
- );
- expect(placements.map((p) => [p.timelineStartSec, p.sourceStartSec, p.sourceEndSec])).toEqual([
- [0, 0, 4],
- [5, 4, 5],
- ]);
- });
});
describe("lanePlacements", () => {
@@ -143,7 +129,6 @@ describe("lanePlacements", () => {
[transcript as any],
[],
[],
- [],
);
expect(sections).toHaveLength(1);
expect(sections[0].words.filter((w) => !w.word.id.startsWith("silence_"))).toHaveLength(2);
@@ -216,7 +201,7 @@ describe("one programme, two lanes", () => {
const VO = track({ id: "vo_1", startMs: 0, endMs: 12000, offsetMs: 0, durationSec: 12 });
function lanes(trims: (typeof TRIM)[]) {
- const removed = removedRawSpans(CLIPS_2, trims, []);
+ const removed = removedRawSpans(CLIPS_2, trims);
const transcripts = [secondsTranscript("asset_rec", 12), secondsTranscript("asset_vo", 12)];
const build = (lane: "recording" | "voiceover") =>
buildAggregatedSections(
@@ -225,7 +210,6 @@ describe("one programme, two lanes", () => {
transcripts as any,
[],
removed,
- [],
);
return { recording: build("recording"), voiceover: build("voiceover") };
}
@@ -258,14 +242,13 @@ describe("one programme, two lanes", () => {
it("removes a word over an inter-clip gap, with nothing to restore", () => {
const gapped = [CLIPS_2[0], { ...CLIPS_2[1], timelineStartSec: 8, timelineEndSec: 14 }];
- const removed = removedRawSpans(gapped, [], []);
+ const removed = removedRawSpans(gapped, []);
const sections = buildAggregatedSections(
voiceoverPlacements([track({ id: "vo_1", startMs: 0, endMs: 14000, durationSec: 14 })]),
// biome-ignore lint/suspicious/noExplicitAny: fixture, not a schema exercise
[secondsTranscript("asset_vo", 14)] as any,
[],
removed,
- [],
);
const w6 = sections.flatMap((s) => s.words).find((w) => w.word.id === "w6"); // raw 6..7
expect(w6?.kept).toBe(false);
@@ -283,8 +266,7 @@ describe("one programme, two lanes", () => {
// biome-ignore lint/suspicious/noExplicitAny: fixture, not a schema exercise
[secondsTranscript("asset_vo", 20)] as any,
[],
- removedRawSpans(CLIPS_2, [], []),
- [],
+ removedRawSpans(CLIPS_2, []),
);
const w15 = sections.flatMap((s) => s.words).find((w) => w.word.id === "w15");
expect(w15?.kept).toBe(true);
@@ -294,14 +276,14 @@ describe("one programme, two lanes", () => {
// The cue used to be resolved into a clip id, which only the recording lane has —
// so this returned null for every moment of every voiceover.
const { voiceover } = lanes([]);
- expect(findCueWordId(voiceover, 4.5, [])).toBe("vo_1:w4");
- expect(findCueWordId(voiceover, 0.5, [])).toBe("vo_1:w0");
+ expect(findCueWordId(voiceover, 4.5)).toBe("vo_1:w4");
+ expect(findCueWordId(voiceover, 0.5)).toBe("vo_1:w0");
});
it("reads a word's raw moment through its own placement", () => {
// A take starting 3s along the ruler, 5s into its file: its source 6 is raw 4.
const placement = { id: "p", assetId: "a", sourceStartSec: 5, timelineStartSec: 3 };
- expect(placementRawSec(placement, 6, [])).toBe(4);
+ expect(placementRawSec(placement, 6)).toBe(4);
});
it("contributes no placement for a looping take", () => {
@@ -315,53 +297,3 @@ describe("one programme, two lanes", () => {
// ─── The cue, after an insertion ─────────────────────────────────────────────
// `findCueWordId` carries its own inverse of the affine map — the fourth copy in the tree.
// It needs no insertion term of its own PROVIDED each placement is affine, which is exactly
-// what walking the take by play pieces buys. Asserted rather than assumed.
-
-describe("the karaoke highlight after a pause", () => {
- const TAKE = track({ id: "vo", startMs: 0, endMs: 6000, offsetMs: 0, durationSec: 6 });
- const WORDS = {
- assetId: "asset_vo",
- language: "en",
- segments: [],
- words: [0, 1, 2, 3, 4, 5].map((i) => ({
- id: `w${i}`,
- segmentId: "s",
- text: `w${i}`,
- startSec: i + 0.1,
- endSec: i + 0.9,
- })),
- };
-
- const sectionsWith = (
- inserts: Array<{ id: string; wordId: string; atSourceSec: number; durationSec: number }>,
- ) =>
- buildAggregatedSections(
- // biome-ignore lint/suspicious/noExplicitAny: fixture, not a schema exercise
- voiceoverPlacements([TAKE as any], [], () => inserts),
- // biome-ignore lint/suspicious/noExplicitAny: fixture, not a schema exercise
- [WORDS as any],
- [],
- [],
- [],
- );
-
- it("tracks the voice with no insertion", () => {
- expect(findCueWordId(sectionsWith([]), 4.5, [])).toBe("vo:w4");
- });
-
- it("follows the word D later once a pause has pushed it there", () => {
- // A one-second pause at source 3: source 4 is now heard at ruler 5.
- const inserts = [{ id: "i1", wordId: "w3", atSourceSec: 3, durationSec: 1 }];
- const sections = sectionsWith(inserts);
- expect(findCueWordId(sections, 5.5, [])).toBe("vo#1:w4");
- // And it is NOT still answering with the pre-pause mapping.
- expect(findCueWordId(sections, 4.5, [])).not.toBe("vo:w4");
- });
-
- it("highlights nothing while the voice is parked", () => {
- // No word is being said during the pause, so the karaoke goes quiet rather than
- // leaving a word lit that has already been spoken.
- const inserts = [{ id: "i1", wordId: "w3", atSourceSec: 3, durationSec: 1 }];
- expect(findCueWordId(sectionsWith(inserts), 3.5, [])).toBeNull();
- });
-});
diff --git a/src/lib/ai-edition/timeline/aggregated-transcript.test.ts b/src/lib/ai-edition/timeline/aggregated-transcript.test.ts
index 085435091..1a62d7e4c 100644
--- a/src/lib/ai-edition/timeline/aggregated-transcript.test.ts
+++ b/src/lib/ai-edition/timeline/aggregated-transcript.test.ts
@@ -63,7 +63,7 @@ describe("buildClipSection", () => {
{ id: "w3", segmentId: "s1", startSec: 2, endSec: 3, text: "friend" },
]);
- const section = buildClipSection(clip, transcript, makeAsset(), [], []);
+ const section = buildClipSection(clip, transcript, makeAsset(), []);
expect(section.words.map((cw) => cw.kept)).toEqual([true, true, true]);
expect(section.trimRuns).toEqual([]);
});
@@ -83,8 +83,7 @@ describe("buildClipSection", () => {
clip,
transcript,
makeAsset(),
- removedRawSpans([clip], [trim], []),
- [],
+ removedRawSpans([clip], [trim]),
);
expect(section.words.map((cw) => cw.kept)).toEqual([true, false, false, false, true]);
expect(section.words.map((cw) => cw.trimIds)).toEqual([
@@ -118,13 +117,7 @@ describe("buildClipSection", () => {
makeTrim({ id: "trim_b", startSec: 3, endSec: 4 }),
];
- const section = buildClipSection(
- clip,
- transcript,
- makeAsset(),
- removedRawSpans([clip], trims, []),
- [],
- );
+ const section = buildClipSection(clip, transcript, makeAsset(), removedRawSpans([clip], trims));
expect(section.trimRuns).toHaveLength(2);
expect(section.trimRuns[0]).toMatchObject({
trimIds: ["trim_a"],
@@ -164,8 +157,7 @@ describe("buildClipSection", () => {
clips,
[makeTranscript(words())],
[makeAsset()],
- removedRawSpans(clips, [trim], []),
- [],
+ removedRawSpans(clips, [trim]),
);
expect(sections[0].words.map((cw) => cw.kept)).toEqual([true, true, true]);
@@ -184,8 +176,7 @@ describe("buildClipSection", () => {
clips,
[makeTranscript(words())],
[makeAsset()],
- removedRawSpans(clips, [trim], []),
- [],
+ removedRawSpans(clips, [trim]),
);
expect(sections[0].trimRuns).toHaveLength(1);
expect(sections[1].trimRuns).toHaveLength(1);
@@ -204,8 +195,7 @@ describe("buildClipSection", () => {
clip,
transcript,
makeAsset(),
- removedRawSpans([clip], [trim], []),
- [],
+ removedRawSpans([clip], [trim]),
);
// Trailing gap 2s→3s is a silence — the different-asset trim doesn't
// cover any of the three entries, so all stay kept.
@@ -220,7 +210,7 @@ describe("buildClipSection", () => {
{ id: "w3", segmentId: "s1", startSec: 2, endSec: 3, text: "Um," },
]);
- const section = buildClipSection(clip, transcript, makeAsset(), [], []);
+ const section = buildClipSection(clip, transcript, makeAsset(), []);
// ponytail: the LLM (not the renderer) decides what is a filler. Every
// word renders as plain text in the right pane.
expect(section.words.map((cw) => cw.kept)).toEqual([true, true, true]);
@@ -229,7 +219,7 @@ describe("buildClipSection", () => {
it("returns an empty words list when the clip has no matching transcript", () => {
const clip = makeClip({ sourceStartSec: 0, sourceEndSec: 5 });
- const section = buildClipSection(clip, null, makeAsset(), [], []);
+ const section = buildClipSection(clip, null, makeAsset(), []);
expect(section.words).toEqual([]);
expect(section.trimRuns).toEqual([]);
@@ -244,7 +234,7 @@ describe("buildClipSection", () => {
{ id: "w_after", segmentId: "s1", startSec: 5, endSec: 6, text: "trim" },
]);
- const section = buildClipSection(clip, transcript, makeAsset(), [], []);
+ const section = buildClipSection(clip, transcript, makeAsset(), []);
// Leading (2s→2.5s) and trailing (3.5s→4s) gaps are both silences.
expect(section.words.map((cw) => cw.word.id)).toEqual(["silence_1", "w_mid", "silence_2"]);
});
@@ -258,7 +248,7 @@ describe("silence gaps", () => {
{ id: "w2", segmentId: "s1", startSec: 1.3, endSec: 2, text: "there" },
]);
- const section = buildClipSection(clip, transcript, makeAsset(), [], []);
+ const section = buildClipSection(clip, transcript, makeAsset(), []);
const ids = section.words.map((cw) => cw.word.id);
expect(ids).toEqual(["w1", "silence_1", "w2", "silence_2"]);
expect(section.words.filter((cw) => isSilenceWord(cw.word))).toHaveLength(2);
@@ -272,7 +262,7 @@ describe("silence gaps", () => {
{ id: "w2", segmentId: "s1", startSec: 1.1, endSec: 2, text: "there" },
]);
- const section = buildClipSection(clip, transcript, makeAsset(), [], []);
+ const section = buildClipSection(clip, transcript, makeAsset(), []);
expect(section.words.map((cw) => cw.word.id)).toEqual(["w1", "w2"]);
});
@@ -288,8 +278,7 @@ describe("silence gaps", () => {
clip,
transcript,
makeAsset(),
- removedRawSpans([clip], [trim], []),
- [],
+ removedRawSpans([clip], [trim]),
);
const silence = section.words.find((cw) => isSilenceWord(cw.word));
expect(silence?.kept).toBe(false);
@@ -330,7 +319,7 @@ describe("buildAggregatedSections", () => {
makeAsset({ id: "asset_2", label: "second.mp4" }),
];
- const sections = buildAggregatedSections(clips, transcripts, assets, [], []);
+ const sections = buildAggregatedSections(clips, transcripts, assets, []);
expect(sections).toHaveLength(2);
expect(sections[0]?.clip.id).toBe("c1");
expect(sections[1]?.clip.id).toBe("c2");
@@ -343,7 +332,7 @@ describe("buildAggregatedSections", () => {
const transcripts = [makeTranscript([])];
const assets = [makeAsset(), makeAsset({ id: "asset_2" })];
- const sections = buildAggregatedSections(clips, transcripts, assets, [], []);
+ const sections = buildAggregatedSections(clips, transcripts, assets, []);
expect(sections).toHaveLength(2);
expect(sections[0]?.transcript).toBeTruthy();
expect(sections[1]?.transcript).toBeNull();
@@ -387,7 +376,7 @@ describe("findCueWordId", () => {
it("returns null when there is no playhead", () => {
const section = makeSection("c1", "asset_1", [["w1", 0, 1]]);
- expect(findCueWordId([section], null, [])).toBeNull();
+ expect(findCueWordId([section], null)).toBeNull();
});
it("returns null when the head is before every section", () => {
@@ -395,7 +384,7 @@ describe("findCueWordId", () => {
timelineStartSec: 10,
timelineEndSec: 110,
});
- expect(findCueWordId([section], 2, [])).toBeNull();
+ expect(findCueWordId([section], 2)).toBeNull();
});
it("returns the word containing the head", () => {
@@ -404,7 +393,7 @@ describe("findCueWordId", () => {
["w2", 1, 2],
["w3", 2, 3],
]);
- expect(findCueWordId([section], 1.5, [])).toBe("c1:w2");
+ expect(findCueWordId([section], 1.5)).toBe("c1:w2");
});
it("returns the previous word when the head is between two words", () => {
@@ -412,7 +401,7 @@ describe("findCueWordId", () => {
["w1", 0, 1],
["w2", 2, 3],
]);
- expect(findCueWordId([section], 1.5, [])).toBe("c1:w1");
+ expect(findCueWordId([section], 1.5)).toBe("c1:w1");
});
it("returns null when the head is before the first word", () => {
@@ -420,7 +409,7 @@ describe("findCueWordId", () => {
["w1", 5, 6],
["w2", 7, 8],
]);
- expect(findCueWordId([section], 0.5, [])).toBeNull();
+ expect(findCueWordId([section], 0.5)).toBeNull();
});
it("returns the last word when the head is past the last word", () => {
@@ -428,7 +417,7 @@ describe("findCueWordId", () => {
["w1", 0, 1],
["w2", 1, 2],
]);
- expect(findCueWordId([section], 99, [])).toBe("c1:w2");
+ expect(findCueWordId([section], 99)).toBe("c1:w2");
});
it("reads the head through the section's own source clock", () => {
@@ -439,8 +428,8 @@ describe("findCueWordId", () => {
timelineStartSec: 20,
timelineEndSec: 30,
});
- expect(findCueWordId([section], 22, [])).toBe("c1:w1");
- expect(findCueWordId([section], 2, [])).toBeNull();
+ expect(findCueWordId([section], 22)).toBe("c1:w1");
+ expect(findCueWordId([section], 2)).toBeNull();
});
// Two clips over the same media project the SAME transcript words twice, so the cue
@@ -469,12 +458,12 @@ describe("findCueWordId", () => {
it("resolves the head against the clip that is playing", () => {
// Source 1.5 in both, but raw 4.5 is only inside c2.
- expect(findCueWordId(sections(), 4.5, [])).toBe("c2:w2");
- expect(findCueWordId(sections(), 1.5, [])).toBe("c1:w2");
+ expect(findCueWordId(sections(), 4.5)).toBe("c2:w2");
+ expect(findCueWordId(sections(), 1.5)).toBe("c1:w2");
});
it("returns an id that cannot match the other clip's copy of the same word", () => {
- const cue = findCueWordId(sections(), 4.5, []);
+ const cue = findCueWordId(sections(), 4.5);
// The whole point: `word.id` is "w2" in BOTH sections, so a bare word id lit up
// both blocks. Exactly one rendered word may claim the cue.
const claiming = sections().flatMap((s) => s.words.filter((cw) => cw.id === cue));
@@ -491,7 +480,7 @@ describe("findCueWordId", () => {
}),
];
// c2 has no words, and borrowing c1's would point at the wrong text.
- expect(findCueWordId(withEmptyC2, 4.5, [])).toBeNull();
+ expect(findCueWordId(withEmptyC2, 4.5)).toBeNull();
});
it("runs an open-ended placement up to the next one", () => {
@@ -508,8 +497,8 @@ describe("findCueWordId", () => {
timelineEndSec: 6,
}),
];
- expect(findCueWordId(open, 2, [])).toBe("c1:w1");
- expect(findCueWordId(open, 3.5, [])).toBe("c2:w1");
+ expect(findCueWordId(open, 2)).toBe("c1:w1");
+ expect(findCueWordId(open, 3.5)).toBe("c2:w1");
});
});
});
@@ -545,7 +534,6 @@ describe("clipWordId", () => {
[transcript],
[makeAsset()],
[],
- [],
);
const rawIds = sections.flatMap((s) => s.words.map((cw) => cw.word.id));
const scopedIds = sections.flatMap((s) => s.words.map((cw) => cw.id));
@@ -554,60 +542,3 @@ describe("clipWordId", () => {
expect(new Set(scopedIds).size).toBe(scopedIds.length);
});
});
-
-// ─── The word an insertion is spoken over ───────────────────────────────────
-// The pane mapped source → ruler and back with two hand-written shifts that ignored the
-// media inserted inside the clip. Past an insertion the highlight ran ahead of the voice by
-// exactly the inserted time — it sat on the word AFTER the one being spoken — and the added
-// word itself was never highlighted at all, because the only seconds it is spoken in are the
-// insertion, and no source second exists inside one (issue #560).
-
-describe("the cue word across an insertion", () => {
- // "b" is typed in after "a". It fits in 0.1s of existing silence and buys 2s of media.
- const words = () => [
- { id: "w_a", segmentId: "s1", startSec: 0, endSec: 1, text: "a" },
- { id: "w_b", segmentId: "s1", startSec: 1, endSec: 1.1, text: "b", source: "synth" as const },
- { id: "w_c", segmentId: "s1", startSec: 2, endSec: 3, text: "c" },
- ];
- // The clip carries the insertion, so it runs 0..12 for 10s of recording.
- const clips = () => [makeClip({ sourceStartSec: 0, sourceEndSec: 10, timelineEndSec: 12 })];
- const inserted = [
- {
- id: "i1",
- assetId: "asset_1",
- atSec: 1.1,
- durationSec: 2,
- wordId: "w_b",
- reason: "",
- origin: "user" as const,
- },
- ];
- const sections = () =>
- buildAggregatedSections(
- clips(),
- [makeTranscript(words())],
- [makeAsset()],
- removedRawSpans(clips(), [], inserted),
- inserted,
- );
-
- it("highlights the added word for the whole stretch its insertion occupies", () => {
- // The insertion opens at ruler 1.1 and closes at 3.1.
- for (const at of [1.2, 2, 3.0]) {
- expect(findCueWordId(sections(), at, inserted)).toBe(clipWordId("clip_1", "w_b"));
- }
- });
-
- it("does not run ahead of the voice after the insertion", () => {
- // Source 2..3 is "c", which the insertion has pushed to ruler 4..5.
- expect(findCueWordId(sections(), 4.5, inserted)).toBe(clipWordId("clip_1", "w_c"));
- // Without the shift this same moment resolved to source 4.5 — past "c" entirely.
- expect(findCueWordId(sections(), 0.5, inserted)).toBe(clipWordId("clip_1", "w_a"));
- });
-
- it("still finds a word at the very end of the clip", () => {
- // The extent used to stop at the source length, so the last 2s belonged to no
- // section and the highlight simply went out.
- expect(findCueWordId(sections(), 11.5, inserted)).not.toBeNull();
- });
-});
diff --git a/src/lib/ai-edition/timeline/aggregated-transcript.ts b/src/lib/ai-edition/timeline/aggregated-transcript.ts
index 27dcbb5cd..309e3c6aa 100644
--- a/src/lib/ai-edition/timeline/aggregated-transcript.ts
+++ b/src/lib/ai-edition/timeline/aggregated-transcript.ts
@@ -14,18 +14,10 @@
// names a word a filler. The transcript view shows plain text for every
// kept word; the user or the LLM decides what to mark as skipped.
-import { collapseTracksToPills, trackGroupId } from "../document/audioTracks";
-import type {
- AxcutAsset,
- AxcutAudioTrack,
- AxcutClip,
- AxcutInsertRange,
- AxcutTranscript,
- AxcutWord,
-} from "../schema";
-import { sourceToTimelineSec, timelineToSourceSec } from "./inserted-time";
+import { collapseTracksToPills } from "../document/audioTracks";
+import type { AxcutAsset, AxcutAudioTrack, AxcutClip, AxcutTranscript, AxcutWord } from "../schema";
import { type RawSpan, type RemovedRawSpan, removalAt } from "./programme-time";
-import { type TakeInsert, takeProgramme } from "./take-programme";
+import { takeProgramme } from "./take-programme";
/**
* The unit the aggregation actually runs over: one stretch of ONE asset's source
@@ -63,28 +55,16 @@ export type TranscriptLane = "recording" | "voiceover";
* whether two things coincide; raw time can, which is why kept-or-removed is asked here
* and not in source time (issue #560).
*/
-export function placementRawSec(
- placement: TranscriptPlacement,
- sourceSec: number,
- insertRanges: readonly AxcutInsertRange[],
- edge: "opens" | "closes" = "opens",
-): number {
- return sourceToTimelineSec(placement, sourceSec, insertRanges, edge);
+export function placementRawSec(placement: TranscriptPlacement, sourceSec: number): number {
+ return placement.timelineStartSec + (sourceSec - placement.sourceStartSec);
}
/** The placement's own stretch of raw ruler, or null when it runs open-ended. */
-export function placementRawExtent(
- placement: TranscriptPlacement,
- insertRanges: readonly AxcutInsertRange[],
-): RawSpan | null {
+export function placementRawExtent(placement: TranscriptPlacement): RawSpan | null {
if (placement.sourceEndSec === undefined) return null;
return {
startSec: placement.timelineStartSec,
- // `"closes"` on the end: the media inserted inside this placement is part of its
- // stretch of ruler, so the extent has to reach past the last one. Ending short left
- // the final seconds of every such clip belonging to no section at all, and the
- // highlight simply went out there.
- endSec: placementRawSec(placement, placement.sourceEndSec, insertRanges, "closes"),
+ endSec: placementRawSec(placement, placement.sourceEndSec),
};
}
@@ -234,7 +214,6 @@ export function buildClipSection(
transcript: AxcutTranscript | null,
asset: AxcutAsset | null,
removed: RemovedRawSpan[],
- insertRanges: readonly AxcutInsertRange[],
): ClipSection {
const words = transcript
? withSilenceGaps(
@@ -246,10 +225,7 @@ export function buildClipSection(
const tagged: ClipWord[] = words.map((word) => {
// The word's CENTRE, mirroring the rule the identity filter used, so the recording
// lane's tagging does not shift under this change.
- const covering = removalAt(
- removed,
- placementRawSec(clip, (word.startSec + word.endSec) / 2, insertRanges),
- );
+ const covering = removalAt(removed, placementRawSec(clip, (word.startSec + word.endSec) / 2));
return {
id: clipWordId(clip.id, word.id),
word,
@@ -315,7 +291,6 @@ export function buildAggregatedSections(
transcripts: AxcutTranscript[],
assets: AxcutAsset[],
removed: RemovedRawSpan[],
- insertRanges: readonly AxcutInsertRange[],
): ClipSection[] {
const transcriptById = new Map(transcripts.map((t) => [t.assetId, t]));
const assetById = new Map(assets.map((a) => [a.id, a]));
@@ -325,7 +300,6 @@ export function buildAggregatedSections(
transcriptById.get(clip.assetId) ?? null,
assetById.get(clip.assetId) ?? null,
removed,
- insertRanges,
),
);
}
@@ -353,13 +327,12 @@ export function voiceoverPlacements(
* insertions the walk yields one piece per take, which is what this always produced. */
removed: readonly RemovedRawSpan[] = [],
/** This take's own insertions, by group id. */
- insertsFor: (groupId: string) => readonly TakeInsert[] = () => [],
): TranscriptPlacement[] {
return collapseTracksToPills(audioTracks)
.filter((pill) => pill.kind === "voiceover" && !pill.loop)
.sort((a, b) => a.startMs - b.startMs || a.id.localeCompare(b.id))
.flatMap((pill) =>
- takeProgramme(pill, removed, insertsFor(trackGroupId(pill)))
+ takeProgramme(pill, removed)
.filter((piece) => piece.kind === "play")
.map((piece, i) => ({
// Namespaced by piece so two stretches of one take never collide on a word id.
@@ -378,9 +351,8 @@ export function lanePlacements(
clips: AxcutClip[],
audioTracks: AxcutAudioTrack[],
removed: readonly RemovedRawSpan[] = [],
- insertsFor: (groupId: string) => readonly TakeInsert[] = () => [],
): TranscriptPlacement[] {
- return lane === "voiceover" ? voiceoverPlacements(audioTracks, removed, insertsFor) : clips;
+ return lane === "voiceover" ? voiceoverPlacements(audioTracks, removed) : clips;
}
/**
@@ -405,11 +377,7 @@ export function lanePlacements(
* clip whose media has not been probed) has no extent of its own and runs to the next
* section's head, then to the end of time.
*/
-export function findCueWordId(
- sections: ClipSection[],
- rawSec: number | null,
- insertRanges: readonly AxcutInsertRange[],
-): string | null {
+export function findCueWordId(sections: ClipSection[], rawSec: number | null): string | null {
if (rawSec === null || !Number.isFinite(rawSec)) return null;
// No fallback to a neighbouring section: a placement with no transcript simply has no
// cue word, and borrowing another's would point at the wrong text.
@@ -420,7 +388,7 @@ export function findCueWordId(
let match: ClipSection | null = null;
for (const [i, section] of withWords.entries()) {
if (rawSec < section.clip.timelineStartSec) break;
- const extent = placementRawExtent(section.clip, insertRanges);
+ const extent = placementRawExtent(section.clip);
const endSec =
extent?.endSec ?? withWords[i + 1]?.clip.timelineStartSec ?? Number.POSITIVE_INFINITY;
if (rawSec < endSec) {
@@ -431,14 +399,7 @@ export function findCueWordId(
if (!match) return null;
// Back to the placement's own source clock, which is what the words are stamped in.
- const { sourceSec: t, insideInsert } = timelineToSourceSec(match.clip, rawSec, insertRanges);
- // Inside an insertion, the word being spoken is the one that bought it — those seconds
- // exist for no other reason. There is no source second in there to find it by, which is
- // why the added word could never be highlighted before.
- if (insideInsert) {
- const own = match.words.find((cw) => cw.word.id === insideInsert.wordId);
- if (own) return own.id;
- }
+ const t = match.clip.sourceStartSec + (rawSec - match.clip.timelineStartSec);
let previous: string | null = null;
for (const cw of match.words) {
if (isSilenceWord(cw.word)) continue;
diff --git a/src/lib/ai-edition/timeline/camera.test.ts b/src/lib/ai-edition/timeline/camera.test.ts
index e1caa03a5..1f7fea91b 100644
--- a/src/lib/ai-edition/timeline/camera.test.ts
+++ b/src/lib/ai-edition/timeline/camera.test.ts
@@ -56,7 +56,6 @@ describe("resolveActiveCameraTrack", () => {
[assetWithCamera, assetWithoutCamera],
[clipWithCamera, clipWithoutCamera],
2,
- [],
);
expect(track?.sourcePath).toBe("/cam-1.mp4");
});
@@ -66,18 +65,17 @@ describe("resolveActiveCameraTrack", () => {
[assetWithCamera, assetWithoutCamera],
[clipWithCamera, clipWithoutCamera],
7,
- [],
);
expect(track).toBeNull();
});
it("returns null when there are no clips", () => {
- expect(resolveActiveCameraTrack([assetWithCamera], [], 0, [])).toBeNull();
+ expect(resolveActiveCameraTrack([assetWithCamera], [], 0)).toBeNull();
});
it("returns null when the active clip references an unknown asset", () => {
const orphanClip: AxcutClip = { ...clipWithCamera, assetId: "missing" };
- expect(resolveActiveCameraTrack([assetWithCamera], [orphanClip], 2, [])).toBeNull();
+ expect(resolveActiveCameraTrack([assetWithCamera], [orphanClip], 2)).toBeNull();
});
});
diff --git a/src/lib/ai-edition/timeline/camera.ts b/src/lib/ai-edition/timeline/camera.ts
index 0f11ed0ce..4fc576952 100644
--- a/src/lib/ai-edition/timeline/camera.ts
+++ b/src/lib/ai-edition/timeline/camera.ts
@@ -4,18 +4,15 @@
// timeline, and whether the timeline has ANY camera at all — used to gate
// camera-only preview chrome and settings controls.
-import type { AxcutAsset, AxcutCameraTrack, AxcutClip, AxcutInsertRange } from "../schema";
+import type { AxcutAsset, AxcutCameraTrack, AxcutClip } from "../schema";
import { locateVirtualPosition } from "./virtual-preview";
export function resolveActiveCameraTrack(
assets: AxcutAsset[],
clips: AxcutClip[],
currentTimeSec: number,
- /** REQUIRED: a clip carrying insertions is longer than its source window, so which clip
- * a timeline second falls on cannot be answered without them (issue #560). */
- insertRanges: readonly AxcutInsertRange[],
): AxcutCameraTrack | null {
- const position = locateVirtualPosition(clips, currentTimeSec, insertRanges);
+ const position = locateVirtualPosition(clips, currentTimeSec);
if (!position) return null;
const activeAsset = assets.find((a) => a.id === position.clip.assetId);
return activeAsset?.cameraTrack ?? null;
diff --git a/src/lib/ai-edition/timeline/cursor-track.ts b/src/lib/ai-edition/timeline/cursor-track.ts
index f190828d6..aec4324a4 100644
--- a/src/lib/ai-edition/timeline/cursor-track.ts
+++ b/src/lib/ai-edition/timeline/cursor-track.ts
@@ -16,7 +16,7 @@
// sample, nothing is summarised, and every pointer-shape change survives the
// reduction because a shape change is an observed event, not a verdict about it.
-import type { AxcutClip, AxcutInsertRange, AxcutTrimRange } from "../schema";
+import type { AxcutClip, AxcutTrimRange } from "../schema";
import { locateSourcePosition } from "./virtual-preview";
/**
@@ -158,9 +158,6 @@ export interface CursorTrackOptions {
durationSec: number;
clips: AxcutClip[];
trimRanges?: AxcutTrimRange[];
- /** The insertions those clips carry: a clip carrying one is longer than its source
- * window, so a capture timestamp's place on the timeline moves with them (issue #560). */
- insertRanges?: readonly AxcutInsertRange[];
hz?: number;
maxPoints?: number;
/** Movement threshold in frame fractions; see DEFAULT_TRACK_EPSILON. */
@@ -172,7 +169,6 @@ export interface CursorTrackOptions {
export function buildCursorTrack(options: CursorTrackOptions): CursorTrack {
const { assetId, samples, durationSec, clips } = options;
const trimRanges = options.trimRanges ?? [];
- const insertRanges = options.insertRanges ?? [];
const maxPoints = options.maxPoints ?? DEFAULT_MAX_TRACK_POINTS;
const ceilingMs = Math.max(0, durationSec) * 1000 || Number.POSITIVE_INFINITY;
@@ -298,7 +294,7 @@ export function buildCursorTrack(options: CursorTrackOptions): CursorTrack {
// not told twice.
const shifted = keep.some((s) => {
const atSec = s.timeMs / 1000;
- const position = locateSourcePosition(clips, atSec, assetId, 0.05, undefined, insertRanges);
+ const position = locateSourcePosition(clips, atSec, assetId);
return !position || Math.abs(position.virtualTimeSec - atSec) > 0.005;
});
@@ -307,7 +303,7 @@ export function buildCursorTrack(options: CursorTrackOptions): CursorTrack {
// `locateSourcePosition` is the existing source→virtual mapping, exact here
// because trims do NOT compact the document's virtual axis — a trim is a hole
// in playback, not a shortening of the ruler (see timeline/trim-mapping.ts).
- const position = locateSourcePosition(clips, atSec, assetId, 0.05, undefined, insertRanges);
+ const position = locateSourcePosition(clips, atSec, assetId);
const point: CursorTrackPoint = {
atSec: round2(atSec),
cx: round3(s.cx),
diff --git a/src/lib/ai-edition/timeline/insert-mapping.test.ts b/src/lib/ai-edition/timeline/insert-mapping.test.ts
deleted file mode 100644
index 8e75b2d11..000000000
--- a/src/lib/ai-edition/timeline/insert-mapping.test.ts
+++ /dev/null
@@ -1,192 +0,0 @@
-// Issue #560. An insertion made from the recording transcript buys the FILM time; one made
-// from a voiceover transcript buys the TAKE silence and leaves the picture alone. The row
-// looks identical either way — only the asset it names says which lane it is on.
-//
-// These also lock the inertness that is true today by ACCIDENT: a voiceover row reaches
-// `rulerInserts` and `resolvePlaybackSegments` and is ignored by both, purely because they
-// match on `clip.assetId`. That accident is the only reason writing one is harmless right
-// now, so it becomes a rule with a test before anything starts writing them.
-
-import { describe, expect, it } from "vitest";
-import { resolvePlaybackSegments } from "../document/timeline";
-import type { AxcutAudioTrack, AxcutClip, AxcutDocument, AxcutInsertRange } from "../schema";
-import { resolveInsertPlacement, takeInserts } from "./insert-mapping";
-import { rulerInserts } from "./inserted-time";
-
-const CLIPS: AxcutClip[] = [
- {
- id: "c1",
- assetId: "rec",
- sourceStartSec: 0,
- sourceEndSec: 6,
- timelineStartSec: 0,
- timelineEndSec: 6,
- wordRefs: [],
- origin: "user",
- reason: "",
- },
- {
- id: "c2",
- assetId: "rec",
- sourceStartSec: 20,
- sourceEndSec: 26,
- timelineStartSec: 6,
- timelineEndSec: 12,
- wordRefs: [],
- origin: "user",
- reason: "",
- },
-];
-
-const TAKE = {
- id: "vo_frag",
- trackId: "vo",
- assetId: "aud",
- kind: "voiceover",
- startMs: 2000,
- endMs: 10_000,
- durationSec: 30,
- offsetMs: 1000,
- gainDb: 0,
- loop: false,
- fadeInMs: 0,
- fadeOutMs: 0,
- muted: false,
- label: "",
- origin: "user",
-} as unknown as AxcutAudioTrack;
-
-function insert(over: Partial<AxcutInsertRange> & { id: string }): AxcutInsertRange {
- return {
- assetId: "rec",
- atSec: 3,
- durationSec: 0.5,
- wordId: `w_${over.id}`,
- reason: "",
- origin: "user",
- ...over,
- } as AxcutInsertRange;
-}
-
-function doc(inserts: AxcutInsertRange[], over: Partial<AxcutDocument> = {}): AxcutDocument {
- return {
- schemaVersion: 7,
- project: { id: "p", title: "T", createdAt: "", updatedAt: "" },
- assets: [
- {
- id: "rec",
- kind: "video",
- label: "r",
- originalPath: "/r.mp4",
- durationSec: 30,
- cameraTrack: null,
- },
- {
- id: "aud",
- kind: "audio",
- label: "a",
- originalPath: "/a.mp3",
- durationSec: 30,
- cameraTrack: null,
- },
- ],
- transcript: null,
- transcripts: [],
- timeline: {
- clips: CLIPS,
- gaps: [],
- trimRanges: [],
- muteRanges: [],
- speedRanges: [],
- captionRanges: [],
- insertRanges: inserts,
- },
- annotations: [],
- zoomRanges: [],
- audioTracks: [TAKE],
- legacyEditor: null,
- ...over,
- } as unknown as AxcutDocument;
-}
-
-describe("resolveInsertPlacement", () => {
- it("leaves a recording insert to `rulerInserts`, the one place that places one", () => {
- // It used to answer with a raw second of its own, from a plain shift the clip's own
- // insertions made wrong — a second, contradictory answer that nothing read.
- const row = insert({ id: "i1", atSec: 3 });
- expect(resolveInsertPlacement(row, doc([row]))).toBeNull();
- });
-
- it("leaves a voiceover insert UNPROJECTED, naming the take and a source second", () => {
- // Deliberately not a raw moment: where it lands depends on the insertions before it
- // inside the same take and on the cuts under it, and only the take's walk knows.
- const row = insert({ id: "i1", assetId: "aud", atSec: 4 });
- expect(resolveInsertPlacement(row, doc([row]))).toEqual({
- lane: "voiceover",
- trackGroupId: "vo",
- atSourceSec: 4,
- });
- });
-
- it("returns null when nothing carries the moment any more", () => {
- // Past every clip's source window...
- expect(resolveInsertPlacement(insert({ id: "i1", atSec: 40 }), doc([]))).toBeNull();
- // ...outside the take's own window (offset 1s, span 8s → source 1..9)...
- expect(
- resolveInsertPlacement(insert({ id: "i2", assetId: "aud", atSec: 12 }), doc([])),
- ).toBeNull();
- // ...and when the take has been deleted outright.
- expect(
- resolveInsertPlacement(
- insert({ id: "i3", assetId: "aud", atSec: 4 }),
- doc([], { audioTracks: [] }),
- ),
- ).toBeNull();
- });
-
- it("names the take by its GROUP, so a split take resolves to one thing", () => {
- const split = doc([], {
- audioTracks: [
- { ...TAKE, id: "f1", trackId: "vo", startMs: 2000, endMs: 6000, offsetMs: 1000 },
- { ...TAKE, id: "f2", trackId: "vo", startMs: 6000, endMs: 10_000, offsetMs: 5000 },
- ],
- });
- const row = insert({ id: "i1", assetId: "aud", atSec: 2 });
- expect(resolveInsertPlacement(row, split)).toMatchObject({ trackGroupId: "vo" });
- });
-});
-
-describe("takeInserts", () => {
- it("collects one take's insertions in its own source order", () => {
- const rows = [
- insert({ id: "b", assetId: "aud", atSec: 6 }),
- insert({ id: "a", assetId: "aud", atSec: 2 }),
- insert({ id: "film", assetId: "rec", atSec: 3 }),
- ];
- expect(takeInserts(doc(rows), "vo").map((i) => [i.id, i.atSourceSec])).toEqual([
- ["a", 2],
- ["b", 6],
- ]);
- });
-
- it("returns nothing for a take that has none", () => {
- expect(takeInserts(doc([insert({ id: "film" })]), "vo")).toEqual([]);
- });
-});
-
-describe("a voiceover insert is inert on the film, deliberately", () => {
- const row = insert({ id: "i1", assetId: "aud", atSec: 4 });
-
- it("produces no ruler insert, so the film's length does not move", () => {
- expect(rulerInserts([row], CLIPS)).toEqual([]);
- // And the recording's own row still does.
- expect(rulerInserts([insert({ id: "i2", atSec: 3 })], CLIPS)).toHaveLength(1);
- });
-
- it("produces no held segment, so no clip freezes for it", () => {
- const held = (rows: AxcutInsertRange[]) =>
- resolvePlaybackSegments(CLIPS, [], rows).filter((s) => s.heldSec !== undefined);
- expect(held([row])).toEqual([]);
- expect(held([insert({ id: "i2", atSec: 3 })])).toHaveLength(1);
- });
-});
diff --git a/src/lib/ai-edition/timeline/insert-mapping.ts b/src/lib/ai-edition/timeline/insert-mapping.ts
deleted file mode 100644
index 66f2fdf0c..000000000
--- a/src/lib/ai-edition/timeline/insert-mapping.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-// Where an insertion lives, resolved rather than stored (issue #560).
-//
-// An added word buys itself time. On the RECORDING lane that time is film: the clip holds
-// a frame and the ruler grows. On the VOICEOVER lane it is a silence inside the take: the
-// picture is not touched at all, and the narration that follows lands later against the
-// same image.
-//
-// The record says which by naming an asset, and the asset's `kind` says which lane it is
-// on. Nothing stores a container id, and that is deliberate: every candidate is ephemeral.
-// A voiceover fragment id is re-minted by `reanchorAudioTracks` on the first clip drag; a
-// clip id does not survive a split, which in this repo is `duplicateClip` plus two
-// `setClipSourceRange` calls that move `atSec` out of the half that was named. An
-// un-anchored region reaching every placement of its asset is the working state here — see
-// `duplicateClip`'s own comment about trims.
-//
-// The two lanes come back in DIFFERENT shapes on purpose. A recording insert can be given
-// its raw moment immediately, through the clip that plays that source second. A voiceover
-// insert cannot: its ruler position depends on the insertions before it inside the same
-// take AND on the cuts under it, and only the take's own walk can resolve that. Handing
-// back an unprojected result is what stops a caller from inventing a projection that would
-// disagree with the walk.
-
-import { trackGroupId } from "../document/audioTracks";
-import type { AxcutDocument, AxcutInsertRange } from "../schema";
-
-/** A silence inside a take: no picture of its own. */
-export interface VoiceoverInsertPlacement {
- lane: "voiceover";
- /** The user-visible take, not one of its stored fragments. */
- trackGroupId: string;
- /** Deliberately in the take's SOURCE seconds — see the note above. */
- atSourceSec: number;
-}
-
-export type InsertPlacement = VoiceoverInsertPlacement;
-
-/**
- * Which TAKE carries this insertion, or null — a recording's insertion, or a take that has
- * been deleted. Only takes need answering here: an insertion in the film is placed by
- * `rulerInserts`, which is the one definition of where an insertion sits on the timeline.
- *
- * The lane is read from the ASSET, never from the row: `kind: "audio"` is the only thing
- * that distinguishes a take's transcript from the film's, and it is already the
- * discriminator `lanePlacements` uses for the transcript tab.
- */
-export function resolveInsertPlacement(
- insert: AxcutInsertRange,
- document: AxcutDocument,
-): InsertPlacement | null {
- const asset = document.assets.find((a) => a.id === insert.assetId);
- if (asset?.kind !== "audio") return null;
- // The first take drawing on this asset whose source window contains the moment.
- // Inclusive at both edges, matching `rulerInserts`: an insertion sits at the END of the
- // word it follows, which is routinely a window's own boundary.
- for (const track of document.audioTracks ?? []) {
- if (track.kind !== "voiceover" || track.assetId !== insert.assetId) continue;
- const startSec = track.offsetMs / 1000;
- const endSec = startSec + Math.max(0, track.endMs - track.startMs) / 1000;
- if (insert.atSec < startSec || insert.atSec > endSec) continue;
- return { lane: "voiceover", trackGroupId: trackGroupId(track), atSourceSec: insert.atSec };
- }
- return null;
-}
-
-/** The insertions belonging to one take, in the take's own source order. */
-export function takeInserts(
- document: AxcutDocument,
- groupId: string,
-): Array<{ id: string; wordId: string; atSourceSec: number; durationSec: number }> {
- const out: Array<{ id: string; wordId: string; atSourceSec: number; durationSec: number }> = [];
- for (const insert of document.timeline.insertRanges ?? []) {
- const placement = resolveInsertPlacement(insert, document);
- if (placement?.lane !== "voiceover" || placement.trackGroupId !== groupId) continue;
- out.push({
- id: insert.id,
- wordId: insert.wordId,
- atSourceSec: placement.atSourceSec,
- durationSec: insert.durationSec,
- });
- }
- return out.sort((a, b) => a.atSourceSec - b.atSourceSec || a.id.localeCompare(b.id));
-}
diff --git a/src/lib/ai-edition/timeline/inserted-time.test.ts b/src/lib/ai-edition/timeline/inserted-time.test.ts
deleted file mode 100644
index b1037f94c..000000000
--- a/src/lib/ai-edition/timeline/inserted-time.test.ts
+++ /dev/null
@@ -1,281 +0,0 @@
-// The ruler arithmetic behind an added word's pause.
-//
-// The one thing these have to pin: stored raw seconds and the seconds the user scrubs stop
-// being the same number the moment a pause exists, and every reader that confuses the two
-// puts a region, a playhead or a caption in the wrong place. The pair is an inverse
-// everywhere except inside a pause — which is not a gap in the model, it is the pause.
-
-import { describe, expect, it } from "vitest";
-import type { AxcutClip, AxcutInsertRange, AxcutWord } from "../schema";
-import {
- insertedWordMarks,
- insertionEnteredBetween,
- type RulerInsert,
- rulerInserts,
- sourceToTimelineSec,
- timelineToSourceSec,
-} from "./inserted-time";
-
-function clipFixture(overrides: Partial<AxcutClip> & Pick<AxcutClip, "id">): AxcutClip {
- return {
- assetId: "a1",
- sourceStartSec: 0,
- sourceEndSec: 10,
- timelineStartSec: 0,
- timelineEndSec: 10,
- wordRefs: [],
- origin: "user",
- reason: "",
- ...overrides,
- };
-}
-
-function insert(overrides: Partial<AxcutInsertRange> = {}): AxcutInsertRange {
- return {
- id: "ins_1",
- assetId: "a1",
- atSec: 4,
- durationSec: 0.5,
- wordId: "synth_1",
- reason: "",
- origin: "user",
- ...overrides,
- };
-}
-
-describe("rulerInserts", () => {
- it("projects a pause through the clip that plays its moment", () => {
- // The clip plays source 4–10 starting at ruler 20, so source 6 is ruler 22.
- const clips = [
- clipFixture({ id: "c1", sourceStartSec: 4, timelineStartSec: 20, timelineEndSec: 26 }),
- ];
- expect(rulerInserts([insert({ atSec: 6 })], clips)).toEqual([
- { id: "ins_1", wordId: "synth_1", atRawSec: 22, durationSec: 0.5 },
- ]);
- });
-
- // The word is not on the timeline, so its pause has no place on the ruler and adds
- // nothing — the same rule a caption line follows when no clip covers it.
- it("drops a pause no clip plays", () => {
- const clips = [
- clipFixture({ id: "c1", sourceStartSec: 0, sourceEndSec: 3, timelineEndSec: 3 }),
- ];
- expect(rulerInserts([insert({ atSec: 6 })], clips)).toEqual([]);
- });
-
- it("counts a pause sitting exactly on a clip's edge", () => {
- // A pause sits at the END of the word it follows, which is routinely the boundary.
- const clips = [
- clipFixture({ id: "c1", sourceStartSec: 0, sourceEndSec: 4, timelineEndSec: 4 }),
- ];
- expect(rulerInserts([insert({ atSec: 4 })], clips)).toHaveLength(1);
- });
-
- it("returns them in ruler order, whatever order they were stored in", () => {
- const clips = [clipFixture({ id: "c1" })];
- const placed = rulerInserts(
- [insert({ id: "b", atSec: 8 }), insert({ id: "a", atSec: 2 })],
- clips,
- );
- expect(placed.map((p) => p.id)).toEqual(["a", "b"]);
- });
-
- it("places a pause only once when two clips could play its moment", () => {
- const clips = [
- clipFixture({ id: "c1" }),
- clipFixture({ id: "c2", timelineStartSec: 10, timelineEndSec: 20 }),
- ];
- expect(rulerInserts([insert()], clips)).toHaveLength(1);
- });
-});
-
-// ─── Where an added word's mark goes ─────────────────────────────────────────
-// Issue #560. Two defects lived in one ternary in V4Timeline: a word WITH a pause was
-// placed on the expanded ruler and one WITHOUT at a fraction of the clip's SOURCE span —
-// two clocks, and the clip box is drawn in neither of them consistently. And both edges
-// were inclusive, so a word whose pause sits on a split boundary painted twice.
-
-function markClip(over: Partial<AxcutClip> & { id: string }): AxcutClip {
- return {
- assetId: "a1",
- sourceStartSec: 0,
- sourceEndSec: 5,
- timelineStartSec: 0,
- timelineEndSec: 5,
- wordRefs: [],
- origin: "user",
- reason: "",
- ...over,
- } as AxcutClip;
-}
-
-const synth = (id: string, startSec: number): AxcutWord =>
- ({ id, segmentId: "s", text: id, startSec, endSec: startSec, source: "synth" }) as AxcutWord;
-
-describe("insertedWordMarks", () => {
- const split = [
- markClip({
- id: "c1",
- sourceStartSec: 0,
- sourceEndSec: 5,
- timelineStartSec: 0,
- timelineEndSec: 5,
- }),
- markClip({
- id: "c2",
- sourceStartSec: 5,
- sourceEndSec: 10,
- timelineStartSec: 5,
- timelineEndSec: 10,
- }),
- ];
-
- it("paints a word on a split boundary exactly once", () => {
- const marks = insertedWordMarks([{ assetId: "a1", words: [synth("w_edge", 5)] }], split, []);
- expect(marks).toHaveLength(1);
- expect(marks[0]).toMatchObject({ clipId: "c2", atRawSec: 5 });
- });
-
- it("places every mark in RAW seconds through its own clip", () => {
- const marks = insertedWordMarks(
- [{ assetId: "a1", words: [synth("early", 2), synth("late", 7)] }],
- split,
- [],
- );
- expect(marks.map((m) => [m.clipId, m.atRawSec])).toEqual([
- ["c1", 2],
- ["c2", 7],
- ]);
- });
-
- it("keeps a word at the very end of the last clip", () => {
- // Half-open everywhere but the tail, or the final word of a project vanishes.
- const marks = insertedWordMarks([{ assetId: "a1", words: [synth("w_end", 10)] }], split, []);
- expect(marks.map((m) => m.wordId)).toEqual(["w_end"]);
- });
-
- it("ignores words nobody added", () => {
- const spoken = { id: "w1", segmentId: "s", text: "w1", startSec: 2, endSec: 3 } as AxcutWord;
- expect(insertedWordMarks([{ assetId: "a1", words: [spoken] }], split, [])).toEqual([]);
- });
-
- it("ignores a transcript no clip draws on", () => {
- expect(insertedWordMarks([{ assetId: "other", words: [synth("w1", 2)] }], split, [])).toEqual(
- [],
- );
- });
-});
-
-// ─── Source ↔ timeline, inside one clip ─────────────────────────────────────
-// The whole consequence of an insertion being MEDIA: the clip is longer than its source
-// window, so a moment past an insertion sits that much further along the timeline. Every
-// place that used to convert between a "raw" and an "expanded" ruler is asking this, of
-// one clip — and getting it wrong put a caption, a playhead or a decoder in the wrong
-// place (issue #560).
-
-describe("source ↔ timeline through a clip that carries insertions", () => {
- // Ten seconds of recording laid at timeline 0, with 0.5s inserted at source 2 and 1s
- // at source 6 — so the clip is 11.5s long and its source window is untouched.
- const clip = clipFixture({
- id: "c1",
- sourceStartSec: 0,
- sourceEndSec: 10,
- timelineStartSec: 0,
- timelineEndSec: 11.5,
- });
- const ranges: AxcutInsertRange[] = [
- {
- id: "a",
- assetId: "a1",
- atSec: 2,
- durationSec: 0.5,
- wordId: "w_a",
- reason: "",
- origin: "user",
- },
- {
- id: "b",
- assetId: "a1",
- atSec: 6,
- durationSec: 1,
- wordId: "w_b",
- reason: "",
- origin: "user",
- },
- ];
-
- it("leaves everything before the first insertion where it was", () => {
- expect(sourceToTimelineSec(clip, 0, ranges)).toBeCloseTo(0, 6);
- expect(sourceToTimelineSec(clip, 1.9, ranges)).toBeCloseTo(1.9, 6);
- });
-
- it("counts every insertion before the moment, and only those", () => {
- expect(sourceToTimelineSec(clip, 4, ranges)).toBeCloseTo(4.5, 6);
- expect(sourceToTimelineSec(clip, 10, ranges)).toBeCloseTo(11.5, 6);
- });
-
- it("puts the insertion's own moment where it opens, or where it closes", () => {
- // The choice is real: a position and a span's START go before the inserted media,
- // a span's END goes after it, so a caption running up to an added word covers it.
- expect(sourceToTimelineSec(clip, 2, ranges, "opens")).toBeCloseTo(2, 6);
- expect(sourceToTimelineSec(clip, 2, ranges, "closes")).toBeCloseTo(2.5, 6);
- });
-
- it("comes back to the source moment it started from", () => {
- for (const source of [0, 1.9, 2, 3, 5.5, 6, 9.99]) {
- const back = timelineToSourceSec(clip, sourceToTimelineSec(clip, source, ranges), ranges);
- expect(back.sourceSec).toBeCloseTo(source, 6);
- }
- });
-
- it("has no source moment inside an insertion, and says which one", () => {
- // There is nothing else it could answer: none of those seconds come from the file.
- const inside = timelineToSourceSec(clip, 2.25, ranges);
- expect(inside.sourceSec).toBeCloseTo(2, 6);
- expect(inside.insideInsert?.id).toBe("a");
- expect(timelineToSourceSec(clip, 2.5, ranges).insideInsert).toBeNull();
- });
-
- it("is the plain shift when the clip carries nothing", () => {
- expect(sourceToTimelineSec(clip, 4, [])).toBeCloseTo(4, 6);
- expect(timelineToSourceSec(clip, 4, []).sourceSec).toBeCloseTo(4, 6);
- });
-
- it("ignores insertions belonging to another recording", () => {
- const other = [{ ...ranges[0], assetId: "a2" }];
- expect(sourceToTimelineSec(clip, 4, other)).toBeCloseTo(4, 6);
- });
-});
-
-// ─── Running into an insertion ──────────────────────────────────────────────
-// An added word inserts MEDIA inside the clip — a fixed frame and silence, until there is
-// a generator for it. Playback runs THROUGH that media, and the half-open rule below is
-// what keeps it from running through the same insertion forever.
-
-describe("the insertion a frame runs into", () => {
- const marks: RulerInsert[] = [
- { id: "i1", wordId: "w1", atRawSec: 4, durationSec: 2 },
- { id: "i2", wordId: "w2", atRawSec: 9, durationSec: 1 },
- ];
-
- it("is found when the frame crosses it", () => {
- expect(insertionEnteredBetween(3.98, 4.02, marks)?.id).toBe("i1");
- expect(insertionEnteredBetween(8.9, 9.1, marks)?.id).toBe("i2");
- });
-
- it("is not found again from the moment it occupies", () => {
- // While the insertion plays, the raw playhead stands still at exactly 4. Coming out,
- // the next frames must not re-enter — otherwise the film never gets past it.
- expect(insertionEnteredBetween(4, 4.02, marks)).toBeUndefined();
- expect(insertionEnteredBetween(4, 4.5, marks)).toBeUndefined();
- });
-
- it("takes the earliest of several in one frame, and none outside", () => {
- expect(insertionEnteredBetween(0, 20, marks)?.id).toBe("i1");
- expect(insertionEnteredBetween(5, 8, marks)).toBeUndefined();
- });
-
- it("plays an insertion landing exactly on the frame boundary", () => {
- expect(insertionEnteredBetween(3.9, 4, marks)?.id).toBe("i1");
- });
-});
diff --git a/src/lib/ai-edition/timeline/inserted-time.ts b/src/lib/ai-edition/timeline/inserted-time.ts
deleted file mode 100644
index 8b3e7950e..000000000
--- a/src/lib/ai-edition/timeline/inserted-time.ts
+++ /dev/null
@@ -1,237 +0,0 @@
-// Time the film does not have.
-//
-// An added word needs somewhere to be spoken. Where the transcript has free silence it
-// borrows it; where it does not, the film holds its frame and everything after it moves
-// along the ruler. That created time is stored as an `AxcutInsertRange` — the inverse of a
-// trim, and deliberately the same shape, because a region is what this timeline already
-// carries safely from end to end. (An earlier attempt made CLIPS for it; see the schema's
-// note on `insertRangeSchema` for how that ended.)
-//
-// This module is the arithmetic, and nothing else: pure, no document, no React. It answers
-// two questions.
-//
-// • Where does an insertion land on the RULER? A range is anchored in SOURCE time, so it has
-// to be projected through whichever clip plays that moment — `rulerInserts`.
-// • What does the ruler look like once the insertions are counted? Stored raw seconds and
-// the seconds the user actually scrubs are no longer the same number, and
-// `expandRawSec` / `collapseRawSec` are the one place that difference is resolved.
-//
-// The two are inverses everywhere except INSIDE an insertion, where they cannot be: a stretch
-// of ruler maps to the single source moment being held. `collapseRawSec` returns that
-// moment, which is exactly what a decoder parked on a held frame should be told.
-
-import type { AxcutClip, AxcutInsertRange, AxcutWord } from "../schema";
-
-/** An insertion placed on the raw ruler, ready to be counted. */
-export interface RulerInsert {
- id: string;
- wordId: string;
- /** Where the insertion begins, in STORED raw seconds — before any insertion is counted. */
- atRawSec: number;
- durationSec: number;
-}
-
-/**
- * Project each insert onto the ruler through the clip that owns it.
- *
- * A range whose moment no clip plays yields nothing: the insertion exists for a word that is
- * not on the timeline, so there is no ruler position for it and nothing to add. Same rule
- * the captions follow for a line no clip covers.
- *
- * Ordered by ruler position, which is what lets the accumulation below be a single pass.
- */
-/**
- * Which clip owns each insertion.
- *
- * ONE definition, because the geometry and the drawing must not answer this differently.
- * An insertion is anchored to an ASSET and a source moment, not to a clip, so two clips over
- * the same recording could both claim it — and when they did, the film grew twice while the
- * pill was drawn once. It is claimed by the FIRST clip that plays its moment, in timeline
- * order: the insertion is stored once and the word exists once, so it happens once.
- */
-export function assignInsertsToClips(
- clips: readonly AxcutClip[],
- inserts: readonly AxcutInsertRange[],
-): Map<string, AxcutInsertRange[]> {
- const byClip = new Map<string, AxcutInsertRange[]>();
- const claimed = new Set<string>();
- for (const clip of [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec)) {
- const sourceEnd = clip.sourceEndSec ?? Number.POSITIVE_INFINITY;
- const mine = inserts
- // Inclusive at both edges: an insertion sits at the END of the word it follows,
- // which is routinely a clip's own boundary.
- .filter(
- (insert) =>
- insert.assetId === clip.assetId &&
- !claimed.has(insert.id) &&
- insert.atSec >= clip.sourceStartSec &&
- insert.atSec <= sourceEnd,
- )
- .sort((a, b) => a.atSec - b.atSec);
- for (const insert of mine) claimed.add(insert.id);
- if (mine.length > 0) byClip.set(clip.id, mine);
- }
- return byClip;
-}
-
-export function rulerInserts(
- inserts: readonly AxcutInsertRange[],
- clips: readonly AxcutClip[],
-): RulerInsert[] {
- const byClip = assignInsertsToClips(clips, inserts);
- const placed: RulerInsert[] = [];
- for (const clip of clips) {
- // Each insertion opens after the ones before it in the same clip: the clip's length
- // already carries all of them, so a plain source-shift would stack them all at the
- // first one's position.
- let carriedSec = 0;
- for (const insert of byClip.get(clip.id) ?? []) {
- placed.push({
- id: insert.id,
- wordId: insert.wordId,
- atRawSec: clip.timelineStartSec + (insert.atSec - clip.sourceStartSec) + carriedSec,
- durationSec: insert.durationSec,
- });
- carriedSec += insert.durationSec;
- }
- }
- return placed.sort((a, b) => a.atRawSec - b.atRawSec);
-}
-
-/**
- * A clip's own source moment → where it lands on the timeline.
- *
- * Not a plain shift, and this is the whole consequence of an insertion being MEDIA: the
- * clip is longer than its source window by everything inserted inside it, so a moment past
- * an insertion sits that much further along. Every place that used to convert between a
- * "raw" and an "expanded" ruler is really asking this, of one clip.
- *
- * `edge` decides what happens AT an insertion's own moment, which is a real choice and not
- * a rounding detail. `"opens"` puts the moment before the inserted media — right for a
- * position, and for the START of a span, so the span does not swallow the insertion that
- * precedes it. `"closes"` puts it after — right for the END of a span, so a stretch running
- * up to an insertion covers it rather than stopping short and leaving it orphaned.
- */
-export function sourceToTimelineSec(
- /** Only the three fields that locate a clip — so a voiceover placement, which carries
- * the same three, maps through this too (issue #560). */
- clip: Pick<AxcutClip, "assetId" | "sourceStartSec" | "timelineStartSec">,
- sourceSec: number,
- inserts: readonly AxcutInsertRange[],
- edge: "opens" | "closes" = "opens",
-): number {
- let added = 0;
- for (const insert of inserts) {
- if (insert.assetId !== clip.assetId) continue;
- if (insert.atSec <= clip.sourceStartSec) continue;
- if (edge === "opens" ? insert.atSec < sourceSec : insert.atSec <= sourceSec + 1e-6) {
- added += insert.durationSec;
- }
- }
- return clip.timelineStartSec + (sourceSec - clip.sourceStartSec) + added;
-}
-
-/**
- * The inverse: a timeline second → the source moment the clip is showing there.
- *
- * Inside an insertion there is no source moment — that is what makes it an insertion — so
- * it answers with the moment the inserted media follows, and names the insertion. A caller
- * driving a decoder needs both: where to park, and the fact that it should stay parked.
- */
-export function timelineToSourceSec(
- /** The same three fields `sourceToTimelineSec` needs, so a voiceover placement maps
- * through this too. */
- clip: Pick<AxcutClip, "assetId" | "sourceStartSec" | "timelineStartSec">,
- timelineSec: number,
- inserts: readonly AxcutInsertRange[],
-): { sourceSec: number; insideInsert: AxcutInsertRange | null } {
- const mine = inserts
- .filter((insert) => insert.assetId === clip.assetId && insert.atSec > clip.sourceStartSec)
- .sort((a, b) => a.atSec - b.atSec);
- let added = 0;
- for (const insert of mine) {
- const opensAt = clip.timelineStartSec + (insert.atSec - clip.sourceStartSec) + added;
- if (timelineSec < opensAt) break;
- if (timelineSec < opensAt + insert.durationSec) {
- return { sourceSec: insert.atSec, insideInsert: insert };
- }
- added += insert.durationSec;
- }
- return {
- sourceSec: clip.sourceStartSec + (timelineSec - clip.timelineStartSec) - added,
- insideInsert: null,
- };
-}
-
-/**
- * The insertion a frame of playback ran into, if it ran into one.
- *
- * Half-open on the LEFT, and that is the whole point: a player parks on the insertion's
- * frame and pins its clock to exactly `atRawSec` for the first frame of it, so `>` is what
- * refuses that same moment on the way in a second time. Closed on the right (with the frame
- * epsilon) so an insertion landing precisely on a frame boundary is played, not skipped.
- */
-export function insertionEnteredBetween(
- prevSec: number,
- nextSec: number,
- inserts: readonly RulerInsert[],
- epsilonSec = 1e-6,
-): RulerInsert | undefined {
- return inserts.find(
- (insert) => insert.atRawSec > prevSec && insert.atRawSec <= nextSec + epsilonSec,
- );
-}
-
-/** An added word, placed on the raw ruler through the clip that carries it. */
-export interface InsertedWordMark {
- clipId: string;
- wordId: string;
- text: string;
- atRawSec: number;
-}
-
-/**
- * Where each added word's mark belongs, one per word.
- *
- * Claimed once, and half-open at a clip's far edge except for the last: an insertion sits at the
- * END of the word it follows, which is routinely a split boundary, and testing both edges
- * inclusively painted the same word in BOTH halves (issue #560).
- *
- * Returns RAW seconds. The caller expands them; it used to mix a raw-then-expanded position
- * for a word with an insertion and a fraction of the clip's SOURCE span for one without, in the
- * same ternary — two clocks, and the clip box is not drawn in the second.
- */
-export function insertedWordMarks(
- transcripts: ReadonlyArray<{ assetId: string; words: ReadonlyArray<AxcutWord> }>,
- clips: readonly AxcutClip[],
- insertRanges: readonly AxcutInsertRange[],
-): InsertedWordMark[] {
- const byAsset = new Map<string, ReadonlyArray<AxcutWord>>();
- for (const transcript of transcripts) {
- const added = transcript.words.filter((word) => word.source === "synth");
- if (added.length > 0) byAsset.set(transcript.assetId, added);
- }
- if (byAsset.size === 0) return [];
-
- const marks: InsertedWordMark[] = [];
- const claimed = new Set<string>();
- clips.forEach((clip, index) => {
- const words = byAsset.get(clip.assetId);
- const sourceEnd = clip.sourceEndSec ?? clip.sourceStartSec;
- if (!words || sourceEnd <= clip.sourceStartSec) return;
- const isLast = index === clips.length - 1;
- for (const word of words) {
- if (claimed.has(word.id)) continue;
- if (word.startSec < clip.sourceStartSec) continue;
- if (word.startSec > sourceEnd || (!isLast && word.startSec === sourceEnd)) continue;
- claimed.add(word.id);
- marks.push({
- clipId: clip.id,
- wordId: word.id,
- text: word.text,
- atRawSec: sourceToTimelineSec(clip, word.startSec, insertRanges),
- });
- }
- });
- return marks;
-}
diff --git a/src/lib/ai-edition/timeline/programme-time.test.ts b/src/lib/ai-edition/timeline/programme-time.test.ts
index e302703dd..5d6faa4ef 100644
--- a/src/lib/ai-edition/timeline/programme-time.test.ts
+++ b/src/lib/ai-edition/timeline/programme-time.test.ts
@@ -7,7 +7,7 @@
import { describe, expect, it } from "vitest";
import { projectRawTimelineSecToPlayback, resolvePlaybackSegments } from "../document/timeline";
-import type { AxcutClip, AxcutInsertRange, AxcutTrimRange } from "../schema";
+import type { AxcutClip, AxcutTrimRange } from "../schema";
import { keptRawSpans, removalAt, removedRawSpans, subtractRemoved } from "./programme-time";
function clip(over: Partial<AxcutClip> & { id: string }): AxcutClip {
@@ -114,7 +114,7 @@ describe("keptRawSpans agrees with playback", () => {
(sum, seg) => sum + ((seg.sourceEndSec ?? seg.sourceStartSec) - seg.sourceStartSec),
0,
);
- const kept = keptRawSpans(clips, trims, []);
+ const kept = keptRawSpans(clips, trims);
expect(total(kept), `seed ${seed} total`).toBeCloseTo(played, 6);
// The sum alone is blind to ORDER, and order is the whole reason this walk was
@@ -125,7 +125,7 @@ describe("keptRawSpans agrees with playback", () => {
let before = 0;
for (const [i, span] of kept.entries()) {
expect(
- projectRawTimelineSecToPlayback(clips, trims, span.startSec, []),
+ projectRawTimelineSecToPlayback(clips, trims, span.startSec),
`seed ${seed} span ${i}`,
).toBeCloseTo(before, 6);
before += span.endSec - span.startSec;
@@ -153,7 +153,7 @@ describe("keptRawSpans agrees with playback", () => {
timelineEndSec: 6,
}),
];
- expect(keptRawSpans(clips, [], []).map((s) => s.startSec)).toEqual([0, 6]);
+ expect(keptRawSpans(clips, []).map((s) => s.startSec)).toEqual([0, 6]);
});
it("leaves the projection identical to what it produced before the lift", () => {
@@ -161,13 +161,13 @@ describe("keptRawSpans agrees with playback", () => {
const trims = [trim({ id: "t1", clipId: "c1", startSec: 2, endSec: 4 })];
// Raw 2..4 is gone, so everything after it plays 2s earlier; inside the cut the
// playhead lands on the output edge just before it.
- expect(projectRawTimelineSecToPlayback(clips, trims, 1, [])).toBeCloseTo(1, 6);
- expect(projectRawTimelineSecToPlayback(clips, trims, 3, [])).toBeCloseTo(2, 6);
- expect(projectRawTimelineSecToPlayback(clips, trims, 6, [])).toBeCloseTo(4, 6);
- expect(projectRawTimelineSecToPlayback(clips, trims, 20, [])).toBeCloseTo(18, 6);
+ expect(projectRawTimelineSecToPlayback(clips, trims, 1)).toBeCloseTo(1, 6);
+ expect(projectRawTimelineSecToPlayback(clips, trims, 3)).toBeCloseTo(2, 6);
+ expect(projectRawTimelineSecToPlayback(clips, trims, 6)).toBeCloseTo(4, 6);
+ expect(projectRawTimelineSecToPlayback(clips, trims, 20)).toBeCloseTo(18, 6);
// Past the programme the projection is the identity, which is what lets a voiceover
// hang off the end and keep playing.
- expect(projectRawTimelineSecToPlayback(clips, trims, 25, [])).toBeCloseTo(23, 6);
+ expect(projectRawTimelineSecToPlayback(clips, trims, 25)).toBeCloseTo(23, 6);
});
});
@@ -178,8 +178,8 @@ describe("removedRawSpans", () => {
trim({ id: "t1", clipId: "c1", startSec: 2, endSec: 4 }),
trim({ id: "t2", clipId: "c2", startSec: 15, endSec: 16 }),
];
- const kept = [...keptRawSpans(clips, trims, [])].sort((a, b) => a.startSec - b.startSec);
- const removed = removedRawSpans(clips, trims, []);
+ const kept = [...keptRawSpans(clips, trims)].sort((a, b) => a.startSec - b.startSec);
+ const removed = removedRawSpans(clips, trims);
const all = [...kept, ...removed].sort((a, b) => a.startSec - b.startSec);
let cursor = 0;
@@ -201,7 +201,7 @@ describe("removedRawSpans", () => {
timelineEndSec: 23,
}),
];
- const gap = removedRawSpans(clips, [], []).find((s) => s.startSec === 10);
+ const gap = removedRawSpans(clips, []).find((s) => s.startSec === 10);
expect(gap).toMatchObject({ startSec: 10, endSec: 13 });
// No trim took it, so the pane must not offer a restore.
expect(gap?.trimIds).toEqual([]);
@@ -210,7 +210,7 @@ describe("removedRawSpans", () => {
it("removes a trimmed tail of the last clip but never the time past it", () => {
const clips = [twoClips()[0]];
const trims = [trim({ id: "t1", clipId: "c1", startSec: 8, endSec: 10 })];
- const removed = removedRawSpans(clips, trims, []);
+ const removed = removedRawSpans(clips, trims);
expect(removed).toEqual([{ startSec: 8, endSec: 10, trimIds: ["t1"] }]);
// Raw 12 is unfilmed, not removed — the distinction a voiceover overhanging the
// programme depends on.
@@ -225,7 +225,7 @@ describe("removedRawSpans", () => {
// playback walk cuts on overlap, per clip, and this must match it.
const clips = twoClips();
const trims = [trim({ id: "t1", startSec: 5, endSec: 15 })]; // no clipId
- const removed = removedRawSpans(clips, trims, []);
+ const removed = removedRawSpans(clips, trims);
expect(removalAt(removed, 6)).toMatchObject({ trimIds: ["t1"] }); // inside c1
expect(removalAt(removed, 12)).toMatchObject({ trimIds: ["t1"] }); // inside c2
expect(removalAt(removed, 2)).toBeNull();
@@ -240,24 +240,22 @@ describe("removedRawSpans", () => {
];
// `subtractInterval` merges the two into one hole; both ids come with it, so
// restoring from the pane can drop the whole pill.
- expect(removedRawSpans(clips, trims, [])).toEqual([
+ expect(removedRawSpans(clips, trims)).toEqual([
{ startSec: 2, endSec: 7, trimIds: ["t1", "t2"] },
]);
});
it("returns nothing for a document with no clips", () => {
- expect(removedRawSpans([], [trim({ id: "t1" })], [])).toEqual([]);
+ expect(removedRawSpans([], [trim({ id: "t1" })])).toEqual([]);
});
});
describe("subtractRemoved", () => {
it("splits a span that crosses a cut into the pieces that survive", () => {
const clips = twoClips();
- const removed = removedRawSpans(
- clips,
- [trim({ id: "t1", clipId: "c1", startSec: 3, endSec: 5 })],
- [],
- );
+ const removed = removedRawSpans(clips, [
+ trim({ id: "t1", clipId: "c1", startSec: 3, endSec: 5 }),
+ ]);
// A voiceover from raw 1 to raw 8 plays as two pieces, not as one take cut short.
expect(subtractRemoved(1, 8, removed)).toEqual([
{ startSec: 1, endSec: 3 },
@@ -267,141 +265,12 @@ describe("subtractRemoved", () => {
it("yields nothing for a span buried inside a cut, and the whole span when untouched", () => {
const clips = twoClips();
- const removed = removedRawSpans(
- clips,
- [trim({ id: "t1", clipId: "c1", startSec: 3, endSec: 8 })],
- [],
- );
+ const removed = removedRawSpans(clips, [
+ trim({ id: "t1", clipId: "c1", startSec: 3, endSec: 8 }),
+ ]);
expect(subtractRemoved(4, 6, removed)).toEqual([]);
expect(subtractRemoved(10, 14, removed)).toEqual([{ startSec: 10, endSec: 14 }]);
// Past the programme is not removed, so an overhanging take keeps its tail.
expect(subtractRemoved(18, 25, removed)).toEqual([{ startSec: 18, endSec: 25 }]);
});
});
-
-// ─── The insertion the projection has to walk over ──────────────────────────
-// An insertion is media INSIDE a clip, so the clip carrying it is that much longer and the
-// insertion's seconds are timeline seconds like any other. The projection's job is unchanged
-// by that — timeline in, output out — but it has to be TOLD, because it walks each clip's
-// kept SOURCE stretches and those are shorter than the clip.
-
-describe("projectRawTimelineSecToPlayback across an insertion", () => {
- // One second inserted at source 5 of the first clip, so that clip runs 0..11 and the
- // second one starts at 11.
- const inserted: AxcutInsertRange[] = [
- {
- id: "i1",
- assetId: "a1",
- atSec: 5,
- durationSec: 1,
- wordId: "w1",
- reason: "",
- origin: "user",
- },
- ];
- const clips = [
- clip({
- id: "c1",
- sourceStartSec: 0,
- sourceEndSec: 10,
- timelineStartSec: 0,
- timelineEndSec: 11,
- }),
- clip({
- id: "c2",
- sourceStartSec: 0,
- sourceEndSec: 10,
- timelineStartSec: 11,
- timelineEndSec: 21,
- }),
- ];
-
- it("is the identity when nothing is cut — the insertion is already in the film", () => {
- // This is what one clock buys. Under two, the walk had to re-add the insertion here
- // and every reader that forgot to had its audio landing a second early.
- expect(projectRawTimelineSecToPlayback(clips, [], 3, inserted)).toBeCloseTo(3, 6);
- expect(projectRawTimelineSecToPlayback(clips, [], 8, inserted)).toBeCloseTo(8, 6);
- expect(projectRawTimelineSecToPlayback(clips, [], 15, inserted)).toBeCloseTo(15, 6);
- });
-
- it("keeps the insertion's own seconds when a trim takes the film around it", () => {
- // Cutting source 0..2 of the first clip removes two seconds of RECORDING. The second
- // the added word bought is not recording, so it survives.
- const trims = [trim({ id: "t1", clipId: "c1", startSec: 0, endSec: 2 })];
- expect(projectRawTimelineSecToPlayback(clips, trims, 8, inserted)).toBeCloseTo(6, 6);
- });
-
- it("loses an insertion whose own moment a trim removed", () => {
- // The moment it follows is not in the film any more, so neither is it — the same
- // rule `resolvePlaybackSegments` follows.
- const trims = [trim({ id: "t1", clipId: "c1", startSec: 4, endSec: 6 })];
- const out = projectRawTimelineSecToPlayback(clips, trims, 11, inserted);
- // 10s of recording, less the 2s cut, and the insertion gone with it.
- expect(out).toBeCloseTo(8, 6);
- });
-
- it("compresses the film around an insertion, and the insertion with it", () => {
- // A 2x region halves whatever timeline it covers. The insertion is timeline, so it
- // is halved too — the film is one thing, and speed is a property of the film.
- const speed = [{ startMs: 0, endMs: 21_000, speed: 2 }];
- expect(projectRawTimelineSecToPlayback(clips, [], 8, inserted, speed)).toBeCloseTo(4, 6);
- });
-});
-
-// ─── The hole an insertion is not ────────────────────────────────────────────
-// `clipRawExtent` measured a clip by its SOURCE window, so a clip carrying insertions
-// ended short by exactly the inserted time — and `removedRawSpans`, walking clip to clip,
-// reported the difference as a gap nothing had removed. Everything that cuts on removed
-// spans then cut there: a voiceover crossing it went silent for the insertion's length, in
-// the preview and in the exported mix, and its words were struck through in the transcript
-// pane. The user heard the voice drop out exactly where they added a word (issue #560).
-
-describe("an insertion is not a hole in the programme", () => {
- const inserted: AxcutInsertRange[] = [
- {
- id: "i1",
- assetId: "a1",
- atSec: 5,
- durationSec: 1,
- wordId: "w1",
- reason: "",
- origin: "user",
- },
- ];
- const clips = [
- clip({
- id: "c1",
- sourceStartSec: 0,
- sourceEndSec: 10,
- timelineStartSec: 0,
- timelineEndSec: 11,
- }),
- clip({
- id: "c2",
- sourceStartSec: 0,
- sourceEndSec: 10,
- timelineStartSec: 11,
- timelineEndSec: 21,
- }),
- ];
-
- it("reports nothing removed when nothing was trimmed", () => {
- expect(removedRawSpans(clips, [], inserted)).toEqual([]);
- });
-
- it("covers the insertion's own seconds as kept programme", () => {
- const spans = keptRawSpans(clips, [], inserted);
- const covers = (sec: number) => spans.some((s) => sec >= s.startSec && sec < s.endSec);
- // 5.5 is inside the inserted media, 10.5 is the first clip's last second.
- expect(covers(5.5)).toBe(true);
- expect(covers(10.5)).toBe(true);
- });
-
- it("still reports a real gap between two clips", () => {
- const apart = [clips[0], clip({ ...clips[1], timelineStartSec: 13, timelineEndSec: 23 })];
- const removed = removedRawSpans(apart, [], inserted);
- expect(removed).toHaveLength(1);
- expect(removed[0].startSec).toBeCloseTo(11, 6);
- expect(removed[0].endSec).toBeCloseTo(13, 6);
- });
-});
diff --git a/src/lib/ai-edition/timeline/programme-time.ts b/src/lib/ai-edition/timeline/programme-time.ts
index d9bfd77a7..60c23f032 100644
--- a/src/lib/ai-edition/timeline/programme-time.ts
+++ b/src/lib/ai-edition/timeline/programme-time.ts
@@ -18,8 +18,7 @@
// Storage does not change: a trim stays source-time anchored to a clip. This is the
// derived READING of those rows, computed on demand and never written back.
-import type { AxcutClip, AxcutInsertRange, AxcutTrimRange } from "../schema";
-import { assignInsertsToClips, sourceToTimelineSec } from "./inserted-time";
+import type { AxcutClip, AxcutTrimRange } from "../schema";
import { type Interval, subtractInterval } from "./intervals";
import { trimAppliesToClip } from "./trim-mapping";
@@ -48,39 +47,22 @@ export interface RemovedRawSpan extends RawSpan {
* source length to measure, and falls back to the ruler geometry it was given — matching
* the pass-through branch `resolvePlaybackSegments` takes for the same clips.
*/
-/** A clip's whole stretch of timeline — its source window PLUS the media inserted inside it.
- *
- * Computed, not read off `timelineEndSec`: derived the same way `reflowClipsForInserts`
- * writes it, so a clip whose stored geometry is stale or half-written cannot make this lie.
- * Leaving the insertions out was its own bug — the extent then ended short by exactly the
- * inserted time, and `removedRawSpans` reported a phantom hole at the tail of every clip
- * carrying one, which the audio paths cut as if a trim had taken it. */
-function clipRawExtent(clip: AxcutClip, ownInserts: readonly AxcutInsertRange[]): RawSpan {
+function clipRawExtent(clip: AxcutClip): RawSpan {
const sourceEnd = clip.sourceEndSec ?? clip.sourceStartSec;
if (sourceEnd <= clip.sourceStartSec) {
return { startSec: clip.timelineStartSec, endSec: clip.timelineEndSec };
}
- const owed = ownInserts.reduce((sum, insert) => sum + insert.durationSec, 0);
return {
startSec: clip.timelineStartSec,
- endSec: clip.timelineStartSec + (sourceEnd - clip.sourceStartSec) + owed,
+ endSec: clip.timelineStartSec + (sourceEnd - clip.sourceStartSec),
};
}
-/** Source interval → timeline, through the clip that carries it.
- *
- * `"closes"` on the end is what makes an insertion INSIDE a kept stretch part of it: the
- * film plays those seconds, so they belong to the span. An insertion at the stretch's own
- * start belongs to whatever came before — and if a trim took that, it is gone with it,
- * which is right: the moment it follows is not in the film any more. */
-function sourceToRaw(
- clip: AxcutClip,
- interval: Interval,
- insertRanges: readonly AxcutInsertRange[],
-): RawSpan {
+/** Source interval → raw, through the clip that carries it. */
+function sourceToRaw(clip: AxcutClip, interval: Interval): RawSpan {
return {
- startSec: sourceToTimelineSec(clip, interval.startSec, insertRanges, "opens"),
- endSec: sourceToTimelineSec(clip, interval.endSec, insertRanges, "closes"),
+ startSec: clip.timelineStartSec + (interval.startSec - clip.sourceStartSec),
+ endSec: clip.timelineStartSec + (interval.endSec - clip.sourceStartSec),
};
}
@@ -107,27 +89,19 @@ function keptSourceIntervals(clip: AxcutClip, trimRanges: AxcutTrimRange[]): Int
*
* Zero-length spans are dropped, so a caller can trust `endSec > startSec`.
*/
-export function keptRawSpans(
- clips: AxcutClip[],
- trimRanges: AxcutTrimRange[],
- /** REQUIRED, not defaulted. A clip carrying insertions is longer than its source window,
- * so a caller that omits these gets an answer that is plausible and wrong by exactly the
- * inserted time, with nothing to catch it (issue #560). */
- insertRanges: readonly AxcutInsertRange[],
-): RawSpan[] {
+export function keptRawSpans(clips: AxcutClip[], trimRanges: AxcutTrimRange[]): RawSpan[] {
const ordered = [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec);
- const owners = assignInsertsToClips(ordered, insertRanges);
const spans: RawSpan[] = [];
for (const clip of ordered) {
const sourceEnd = clip.sourceEndSec ?? clip.sourceStartSec;
if (sourceEnd <= clip.sourceStartSec) {
// Duration not probed yet — the whole raw clip passes through unnarrowed.
- const extent = clipRawExtent(clip, owners.get(clip.id) ?? []);
+ const extent = clipRawExtent(clip);
if (extent.endSec > extent.startSec) spans.push(extent);
continue;
}
for (const iv of keptSourceIntervals(clip, trimRanges)) {
- const span = sourceToRaw(clip, iv, insertRanges);
+ const span = sourceToRaw(clip, iv);
if (span.endSec > span.startSec) spans.push(span);
}
}
@@ -152,20 +126,15 @@ export function keptRawSpans(
export function removedRawSpans(
clips: AxcutClip[],
trimRanges: AxcutTrimRange[],
- /** REQUIRED, not defaulted. A clip carrying insertions is longer than its source window,
- * so a caller that omits these gets an answer that is plausible and wrong by exactly the
- * inserted time, with nothing to catch it (issue #560). */
- insertRanges: readonly AxcutInsertRange[],
): RemovedRawSpan[] {
const ordered = [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec);
if (ordered.length === 0) return [];
- const owners = assignInsertsToClips(ordered, insertRanges);
const removed: RemovedRawSpan[] = [];
let cursor = 0; // raw end of the programme walked so far
for (const clip of ordered) {
- const extent = clipRawExtent(clip, owners.get(clip.id) ?? []);
+ const extent = clipRawExtent(clip);
// The unfilmed stretch before this clip. `max` rather than a bare subtraction so
// two clips overlapping on the ruler contribute no negative gap.
if (extent.startSec > cursor) {
@@ -185,12 +154,12 @@ export function removedRawSpans(
.filter((trim) => trimAppliesToClip(trim, clip))
.map((trim) => ({
id: trim.id,
- ...sourceToRaw(clip, { startSec: trim.startSec, endSec: trim.endSec }, insertRanges),
+ ...sourceToRaw(clip, { startSec: trim.startSec, endSec: trim.endSec }),
}));
let holeStart = extent.startSec;
for (const iv of kept) {
- const span = sourceToRaw(clip, iv, insertRanges);
+ const span = sourceToRaw(clip, iv);
if (span.startSec > holeStart) {
removed.push(taggedHole(holeStart, span.startSec, applicable));
}
diff --git a/src/lib/ai-edition/timeline/sharedMediaTrim.test.ts b/src/lib/ai-edition/timeline/sharedMediaTrim.test.ts
index 4edd43902..5bbe7ac44 100644
--- a/src/lib/ai-edition/timeline/sharedMediaTrim.test.ts
+++ b/src/lib/ai-edition/timeline/sharedMediaTrim.test.ts
@@ -74,8 +74,7 @@ describe("repro: trim on clip 2 of two clips sharing one media", () => {
next.timeline.clips,
next.transcripts,
next.assets,
- removedRawSpans(next.timeline.clips, next.timeline.trimRanges, []),
- [],
+ removedRawSpans(next.timeline.clips, next.timeline.trimRanges),
);
expect(sections[0].trimRuns).toHaveLength(0);
expect(sections[1].trimRuns).toHaveLength(1);
@@ -85,7 +84,7 @@ describe("repro: trim on clip 2 of two clips sharing one media", () => {
]);
// 2. Ruler — one pill, over clip 2 (timeline 11.8 + 8.4 = 20.2 … 22.2).
- const pills = coalescedTrimGroups(next.timeline.trimRanges, next.timeline.clips, []);
+ const pills = coalescedTrimGroups(next.timeline.trimRanges, next.timeline.clips);
expect(pills).toHaveLength(1);
expect(pills[0].start).toBeCloseTo(20.2, 6);
expect(pills[0].end).toBeCloseTo(22.2, 6);
diff --git a/src/lib/ai-edition/timeline/take-programme.test.ts b/src/lib/ai-edition/timeline/take-programme.test.ts
index 7cf3cce0c..def48cc48 100644
--- a/src/lib/ai-edition/timeline/take-programme.test.ts
+++ b/src/lib/ai-edition/timeline/take-programme.test.ts
@@ -7,10 +7,9 @@
// their answers must not move.
import { describe, expect, it } from "vitest";
-import { rawSpanForOutDuration } from "../document/timeline";
import type { AxcutAudioTrack, AxcutClip, AxcutTrimRange } from "../schema";
import { removedRawSpans, subtractRemoved } from "./programme-time";
-import { consumedSourceSec, takePlaybackAt, takeProgramme } from "./take-programme";
+import { takePlaybackAt, takeProgramme } from "./take-programme";
const CLIPS: AxcutClip[] = [
{
@@ -43,16 +42,6 @@ const TAKE = { startMs: 0, endMs: 10_000, offsetMs: 0 } as Pick<
"startMs" | "endMs" | "offsetMs"
>;
-const ins = (atSourceSec: number, durationSec: number, id = "i1") => ({
- id,
- wordId: `w_${id}`,
- atSourceSec,
- durationSec,
-});
-
-const shape = (pieces: ReturnType<typeof takeProgramme>) =>
- pieces.map((p) => [p.kind, p.rawStartSec, p.rawEndSec, p.sourceStartSec, p.sourceEndSec]);
-
describe("takeProgramme", () => {
it("is exactly subtractRemoved when nothing is inserted", () => {
// The demotion. Every fixture the export and the preview already agree on has to
@@ -64,120 +53,23 @@ describe("takeProgramme", () => {
[trim(8, 12)],
[trim(2, 3), trim(6, 7, "t2")],
]) {
- const removed = removedRawSpans(CLIPS, cuts, []);
- const played = takeProgramme(TAKE, removed, [])
+ const removed = removedRawSpans(CLIPS, cuts);
+ const played = takeProgramme(TAKE, removed)
.filter((p) => p.kind === "play")
.map((p) => [p.rawStartSec, p.rawEndSec]);
const expected = subtractRemoved(0, 10, removed).map((s) => [s.startSec, s.endSec]);
expect(played).toEqual(expected);
}
});
-
- it("parks the voice for an insertion and resumes on the same word", () => {
- const pieces = takeProgramme(TAKE, [], [ins(4, 1)]);
- expect(shape(pieces)).toEqual([
- ["play", 0, 4, 0, 4],
- ["hold", 4, 5, 4, 4],
- ["play", 5, 10, 4, 9],
- ]);
- // The take consumed 9 seconds of its file, not 10: the second the pause took is
- // pushed off the end and lost, which is the accepted cost of the clips deciding
- // the length.
- expect(consumedSourceSec(pieces)).toBeCloseTo(9, 6);
- });
-
- it("resolves the second insertion AFTER the first one's hold, not before it", () => {
- // The case a two-pass design gets wrong: mapped up front, source 6 would be raw 6,
- // which is inside the first hold.
- const pieces = takeProgramme(TAKE, [], [ins(4, 1, "a"), ins(6, 1, "b")]);
- expect(shape(pieces)).toEqual([
- ["play", 0, 4, 0, 4],
- ["hold", 4, 5, 4, 4],
- ["play", 5, 7, 4, 6],
- ["hold", 7, 8, 6, 6],
- ["play", 8, 10, 6, 8],
- ]);
- });
-
- it("makes two insertions at one moment two adjacent holds, with no empty play between", () => {
- const pieces = takeProgramme(TAKE, [], [ins(4, 1, "a"), ins(4, 0.5, "b")]);
- expect(pieces.map((p) => p.kind)).toEqual(["play", "hold", "hold", "play"]);
- expect(pieces.filter((p) => p.kind === "hold").map((p) => p.holdId)).toEqual(["a", "b"]);
- expect(pieces.some((p) => p.rawEndSec === p.rawStartSec)).toBe(false);
- });
-
- it("gives nothing to an insertion a cut swallowed", () => {
- const removed = removedRawSpans(CLIPS, [trim(3, 6)], []);
- const withIt = takeProgramme(TAKE, removed, [ins(4, 1)]);
- const without = takeProgramme(TAKE, removed, []);
- // The moment it holds is not in the film any more, so it buys no time.
- expect(withIt.some((p) => p.kind === "hold")).toBe(false);
- expect(shape(withIt)).toEqual(shape(without));
- });
-
- it("keeps an insertion on a cut's far edge, which is what follows the cut", () => {
- const removed = removedRawSpans(CLIPS, [trim(3, 6)], []);
- const pieces = takeProgramme(TAKE, removed, [ins(6, 1)]);
- expect(pieces.map((p) => p.kind)).toEqual(["play", "removed", "hold", "play"]);
- });
-
- it("drops an insertion at or past the take's last moment", () => {
- expect(takeProgramme(TAKE, [], [ins(10, 1)]).some((p) => p.kind === "hold")).toBe(false);
- expect(takeProgramme(TAKE, [], [ins(30, 1)]).some((p) => p.kind === "hold")).toBe(false);
- });
-
- it("ignores an insertion of no duration", () => {
- expect(takeProgramme(TAKE, [], [ins(4, 0)]).map((p) => p.kind)).toEqual(["play"]);
- });
-
- it("spends a pause on the take's own clock under a speed region", () => {
- // A voice plays at 1x in the mix. Under a 2x region a one-second pause has to eat
- // TWO raw seconds to last one second of programme.
- const speed = [{ startMs: 0, endMs: 20_000, speed: 2 }];
- const pieces = takeProgramme(TAKE, [], [ins(4, 1)], speed);
- const hold = pieces.find((p) => p.kind === "hold");
- expect(hold && hold.rawEndSec - hold.rawStartSec).toBeCloseTo(2, 6);
- });
-});
-
-describe("rawSpanForOutDuration", () => {
- it("is the identity with no regions", () => {
- expect(rawSpanForOutDuration(3, 2)).toBe(2);
- });
-
- it("inverts outputDurationOfRawSpan across a boundary", () => {
- const speed = [{ startMs: 4000, endMs: 8000, speed: 2 }];
- // From raw 3: one output second buys 1 raw second before the region, then the rest
- // at 2x. Two output seconds = 1 + 2 = 3 raw seconds.
- expect(rawSpanForOutDuration(3, 2, speed)).toBeCloseTo(3, 6);
- });
-
- it("returns zero for a non-positive duration", () => {
- expect(rawSpanForOutDuration(0, 0)).toBe(0);
- expect(rawSpanForOutDuration(0, -1)).toBe(0);
- });
});
describe("takePlaybackAt", () => {
- const pieces = takeProgramme(TAKE, removedRawSpans(CLIPS, [trim(7, 8)], []), [ins(4, 1)]);
+ const pieces = takeProgramme(TAKE, removedRawSpans(CLIPS, [trim(7, 8)]));
it("plays the file where the file plays", () => {
expect(takePlaybackAt(pieces, 2)).toMatchObject({ targetTimeSec: 2, shouldPlay: true });
});
- it("parks on one moment inside the pause rather than tracking a moving target", () => {
- expect(takePlaybackAt(pieces, 4.5)).toMatchObject({
- targetTimeSec: 4,
- shouldPlay: false,
- heldBy: "i1",
- });
- });
-
- it("keeps the clock running through a cut, silently", () => {
- // Raw 7.5 is one second past the pause, so the file is at 6.5 — and muted.
- expect(takePlaybackAt(pieces, 7.5)).toMatchObject({ targetTimeSec: 6.5, shouldPlay: false });
- });
-
it("has nothing to say outside the take", () => {
expect(takePlaybackAt(pieces, 12)).toBeNull();
});
@@ -187,88 +79,3 @@ describe("takePlaybackAt", () => {
// They read the same walk now, but "the same walk" is a claim about wiring. This walks the
// take frame by frame the way the rAF does and asserts the runs of source time it would
// play are the entries the export emits, piece for piece.
-
-describe("preview and export agree over a take with a cut and a pause", () => {
- const removed = removedRawSpans(CLIPS, [trim(7, 8)], []);
- const pieces = takeProgramme(TAKE, removed, [ins(4, 1)]);
-
- it("plays exactly the play pieces, and nothing between them", () => {
- const runs: Array<{ from: number; to: number }> = [];
- // A run breaks on SILENCE, not on a jump in source time. Across a pause the source
- // is deliberately continuous — the voice resumes on the word it stopped on — so a
- // detector watching only the source would merge the two halves and see one run.
- let wasPlaying = false;
- for (let raw = 0; raw < 10; raw += 0.05) {
- const at = takePlaybackAt(pieces, raw);
- if (!at?.shouldPlay) {
- wasPlaying = false;
- continue;
- }
- const last = runs.at(-1);
- if (wasPlaying && last && Math.abs(at.targetTimeSec - last.to) < 0.06) {
- last.to = at.targetTimeSec;
- } else {
- runs.push({ from: at.targetTimeSec, to: at.targetTimeSec });
- }
- wasPlaying = true;
- }
- const entries = pieces
- .filter((p) => p.kind === "play")
- .map((p) => [p.sourceStartSec, p.sourceEndSec]);
- expect(runs).toHaveLength(entries.length);
- runs.forEach((run, i) => {
- expect(run.from).toBeCloseTo(entries[i][0], 1);
- expect(run.to).toBeCloseTo(entries[i][1], 1);
- });
- });
-
- it("never re-seeks while the voice is parked", () => {
- // One value for the whole pause: a target that drifted would re-seek a paused
- // element every frame, and resuming would restart on the wrong word.
- const inside = [4.1, 4.3, 4.5, 4.7, 4.9].map((raw) => takePlaybackAt(pieces, raw));
- expect(inside.every((at) => at?.shouldPlay === false)).toBe(true);
- expect(new Set(inside.map((at) => at?.targetTimeSec)).size).toBe(1);
- });
-
- it("resumes on the second it stopped on", () => {
- const parked = takePlaybackAt(pieces, 4.5)?.targetTimeSec;
- const resumed = takePlaybackAt(pieces, 5.01)?.targetTimeSec;
- expect(resumed).toBeCloseTo(parked ?? -1, 1);
- });
-});
-
-// ─── What the lane has to draw ──────────────────────────────────────────────
-// The notch is positioned from the walk, as a fraction of the PILL's own raw span. These
-// pin the arithmetic the drawing does, so a notch cannot appear where the voice does not
-// actually stop.
-
-describe("the pieces a pill draws", () => {
- const pctOfPill = (pieces: ReturnType<typeof takeProgramme>, rawSec: number) =>
- ((rawSec - TAKE.startMs / 1000) / (TAKE.endMs / 1000 - TAKE.startMs / 1000)) * 100;
-
- it("cuts one notch, in the middle, at the width of the time it took", () => {
- const pieces = takeProgramme(TAKE, [], [ins(4, 1)]);
- const hold = pieces.find((p) => p.kind === "hold");
- expect(hold).toBeDefined();
- if (!hold) return;
- expect(pctOfPill(pieces, hold.rawStartSec)).toBeCloseTo(40, 6);
- expect(pctOfPill(pieces, hold.rawEndSec) - pctOfPill(pieces, hold.rawStartSec)).toBeCloseTo(
- 10,
- 6,
- );
- });
-
- it("leaves a take with no insertion in one piece, so the pill draws as it always did", () => {
- expect(takeProgramme(TAKE, [], []).some((p) => p.kind === "hold")).toBe(false);
- });
-
- it("covers the pill end to end, with no overlap and no hole", () => {
- const pieces = takeProgramme(TAKE, removedRawSpans(CLIPS, [trim(7, 8)], []), [ins(4, 1)]);
- let cursor = TAKE.startMs / 1000;
- for (const piece of pieces) {
- expect(piece.rawStartSec).toBeCloseTo(cursor, 6);
- cursor = piece.rawEndSec;
- }
- expect(cursor).toBeCloseTo(TAKE.endMs / 1000, 6);
- });
-});
diff --git a/src/lib/ai-edition/timeline/take-programme.ts b/src/lib/ai-edition/timeline/take-programme.ts
index 828055f03..8ea999428 100644
--- a/src/lib/ai-edition/timeline/take-programme.ts
+++ b/src/lib/ai-edition/timeline/take-programme.ts
@@ -24,40 +24,22 @@
// playing on top of itself. `anchorAudioTrackFragments` is untouched and stays correct for
// the music and loop paths that still read it.
-import type { PlaybackSpeedRegion } from "../document/timeline";
-import { rawSpanForOutDuration } from "../document/timeline";
import type { AxcutAudioTrack } from "../schema";
import type { RemovedRawSpan } from "./programme-time";
/** One stretch of a take, in playback order. */
export interface TakePiece {
/**
- * `play` — the file is heard. `hold` — the voice is parked on one source moment while
- * the timeline runs on (an insertion). `removed` — the film lost this stretch, so the
- * take is silent through it, its own clock still running underneath.
+ * `play` — the file is heard. `removed` — the film lost this stretch, so the take is
+ * silent through it, its own clock still running underneath.
*/
- kind: "play" | "hold" | "removed";
- /** Stored RAW ruler seconds. Insertions occupy raw time here because they consume it
- * from the take's own span — they do not create programme time. */
+ kind: "play" | "removed";
+ /** Stored RAW ruler seconds. */
rawStartSec: number;
rawEndSec: number;
- /** The take's own file. Equal on a `hold`: the moment the voice is parked on. */
+ /** The take's own file. */
sourceStartSec: number;
sourceEndSec: number;
- /** The insertion that produced a `hold`. */
- holdId?: string;
- /** The word that insertion exists for. */
- wordId?: string;
-}
-
-/** An insertion inside one take, in the take's own source seconds. */
-export interface TakeInsert {
- id: string;
- wordId: string;
- atSourceSec: number;
- /** OUTPUT seconds. A voice plays at 1x in the mix, so a pause for a spoken word is
- * measured on the take's own clock, not on a raw ruler a speed region compresses. */
- durationSec: number;
}
const EPSILON_SEC = 1e-9;
@@ -76,8 +58,6 @@ const EPSILON_SEC = 1e-9;
export function takeProgramme(
pill: Pick<AxcutAudioTrack, "startMs" | "endMs" | "offsetMs">,
removed: readonly RemovedRawSpan[],
- inserts: readonly TakeInsert[],
- speedRegions: PlaybackSpeedRegion[] = [],
): TakePiece[] {
const rawStart = pill.startMs / 1000;
const rawEnd = Math.max(rawStart, pill.endMs / 1000);
@@ -86,9 +66,6 @@ export function takeProgramme(
// Every boundary the walk has to stop at, on the RAW ruler, resolved sequentially:
// an insertion's raw moment depends on the holds before it, so it cannot be mapped in
// one pass up front.
- const pending = [...inserts]
- .filter((ins) => ins.durationSec > 0)
- .sort((a, b) => a.atSourceSec - b.atSourceSec || a.id.localeCompare(b.id));
const cuts = [...removed]
.filter((span) => span.endSec > rawStart && span.startSec < rawEnd)
@@ -97,10 +74,9 @@ export function takeProgramme(
const pieces: TakePiece[] = [];
let raw = rawStart;
let source = sourceStart;
- let nextInsert = 0;
let nextCut = 0;
- const push = (kind: TakePiece["kind"], rawTo: number, sourceTo: number, ins?: TakeInsert) => {
+ const push = (kind: TakePiece["kind"], rawTo: number, sourceTo: number) => {
if (rawTo - raw <= EPSILON_SEC) return;
pieces.push({
kind,
@@ -108,7 +84,6 @@ export function takeProgramme(
rawEndSec: rawTo,
sourceStartSec: source,
sourceEndSec: sourceTo,
- ...(ins ? { holdId: ins.id, wordId: ins.wordId } : {}),
});
raw = rawTo;
source = sourceTo;
@@ -121,43 +96,14 @@ export function takeProgramme(
// so the bound is enforced. Counting passes rather than watching `raw` on purpose: a
// pass that consumes a zero-length insertion makes real progress without moving `raw`,
// and a no-progress test would cut the walk short on a legitimate document.
- const maxPasses = 4 * (removed.length + inserts.length + 2);
+ const maxPasses = 4 * (removed.length + 2);
let passes = 0;
while (raw < rawEnd - EPSILON_SEC) {
if (passes++ > maxPasses) break;
- // Skip cuts and insertions the walk has already passed.
+ // Skip cuts the walk has already passed.
while (nextCut < cuts.length && cuts[nextCut].endSec <= raw + EPSILON_SEC) nextCut++;
- while (nextInsert < pending.length && pending[nextInsert].atSourceSec <= source - EPSILON_SEC) {
- // Its moment is behind the source cursor: a cut swallowed it, or two inserts
- // share a moment and the first already consumed it. Either way it buys nothing.
- nextInsert++;
- }
const cut = cuts[nextCut];
- const insert = pending[nextInsert];
-
- // Sitting exactly on an insertion's moment: hold before anything else, so two
- // inserts at one moment become two adjacent holds rather than one merged stretch.
- if (insert && insert.atSourceSec <= source + EPSILON_SEC) {
- const held = Math.min(
- rawSpanForOutDuration(raw, insert.durationSec, speedRegions),
- rawEnd - raw,
- );
- nextInsert++;
- if (held > EPSILON_SEC) {
- pieces.push({
- kind: "hold",
- rawStartSec: raw,
- rawEndSec: raw + held,
- sourceStartSec: source,
- sourceEndSec: source,
- holdId: insert.id,
- wordId: insert.wordId,
- });
- raw += held;
- }
- continue;
- }
// Inside a cut: silent to the cut's end, both cursors running.
if (cut && cut.startSec <= raw + EPSILON_SEC) {
@@ -169,7 +115,6 @@ export function takeProgramme(
// Otherwise play up to whichever boundary comes first.
let to = rawEnd;
if (cut) to = Math.min(to, cut.startSec);
- if (insert) to = Math.min(to, raw + (insert.atSourceSec - source));
push("play", Math.max(raw, to), source + (Math.max(raw, to) - raw));
}
@@ -200,16 +145,11 @@ export function consumedSourceSec(pieces: readonly TakePiece[]): number {
export function takePlaybackAt(
pieces: readonly TakePiece[],
rawSec: number,
-): { targetTimeSec: number; shouldPlay: boolean; heldBy?: string } | null {
+): { targetTimeSec: number; shouldPlay: boolean } | null {
for (const piece of pieces) {
if (rawSec < piece.rawStartSec) break;
if (rawSec >= piece.rawEndSec) continue;
- if (piece.kind === "hold") {
- // Parked on ONE source moment, not clamped to a moving target: resuming from the
- // post-insert source would restart the narration on the wrong word, and a target
- // that drifts every frame would re-seek a paused element every frame.
- return { targetTimeSec: piece.sourceStartSec, shouldPlay: false, heldBy: piece.holdId };
- }
+
const target = piece.sourceStartSec + (rawSec - piece.rawStartSec);
return { targetTimeSec: target, shouldPlay: piece.kind === "play" };
}
diff --git a/src/lib/ai-edition/timeline/timelineMap.test.ts b/src/lib/ai-edition/timeline/timelineMap.test.ts
index 608350a49..ea3f6c61b 100644
--- a/src/lib/ai-edition/timeline/timelineMap.test.ts
+++ b/src/lib/ai-edition/timeline/timelineMap.test.ts
@@ -5,7 +5,7 @@
import { describe, expect, it } from "vitest";
import { resolvePlaybackSegments } from "../document/timeline";
-import type { AxcutClip, AxcutInsertRange, AxcutTrimRange } from "../schema";
+import type { AxcutClip, AxcutTrimRange } from "../schema";
import {
anchorRawRegionsToClips,
anchorRegionsWithDerivedMs,
@@ -48,7 +48,7 @@ const region = (id: string, startSec: number, endSec: number, payload?: string):
describe("projectRegionsToSource", () => {
it("passes a region through unchanged (no clipIndex) when there are no segments", () => {
- const out = projectRegionsToSource([region("r", 1.5, 4.25)], [], [], () => "x", []);
+ const out = projectRegionsToSource([region("r", 1.5, 4.25)], [], [], () => "x");
expect(out).toEqual([{ id: "r", startMs: 1500, endMs: 4250 }]);
});
@@ -60,7 +60,7 @@ describe("projectRegionsToSource", () => {
sourceEndSec: 10,
timelineEndSec: 10,
});
- const out = projectRegionsToSource([region("r", 3, 5)], [c], [c], () => "x", []);
+ const out = projectRegionsToSource([region("r", 3, 5)], [c], [c], () => "x");
expect(out).toEqual([{ id: "r", startMs: 3000, endMs: 5000, clipIndex: 0 }]);
});
@@ -75,7 +75,7 @@ describe("projectRegionsToSource", () => {
timelineEndSec: 10,
});
const segments = resolvePlaybackSegments([c], [trim("a", 2, 4)]);
- const out = projectRegionsToSource([region("r", 6, 8)], segments, [c], () => "x", []);
+ const out = projectRegionsToSource([region("r", 6, 8)], segments, [c], () => "x");
expect(out).toEqual([{ id: "r", startMs: 6000, endMs: 8000, clipIndex: 1 }]);
});
@@ -96,13 +96,7 @@ describe("projectRegionsToSource", () => {
timelineStartSec: 5,
timelineEndSec: 10,
});
- const out = projectRegionsToSource(
- [region("r", 3, 7, "keep")],
- [c1, c2],
- [c1, c2],
- () => "r2",
- [],
- );
+ const out = projectRegionsToSource([region("r", 3, 7, "keep")], [c1, c2], [c1, c2], () => "r2");
expect(out).toEqual([
{ id: "r", startMs: 103000, endMs: 105000, clipIndex: 0, payload: "keep" },
{ id: "r2", startMs: 200000, endMs: 202000, clipIndex: 1, payload: "keep" },
@@ -120,7 +114,7 @@ describe("projectRegionsToSource", () => {
timelineEndSec: 10,
});
const segments = resolvePlaybackSegments([c], [trim("a", 4, 6)]);
- const out = projectRegionsToSource([region("r", 3, 8)], segments, [c], () => "r2", []);
+ const out = projectRegionsToSource([region("r", 3, 8)], segments, [c], () => "r2");
expect(out).toEqual([
{ id: "r", startMs: 3000, endMs: 4000, clipIndex: 0 },
{ id: "r2", startMs: 6000, endMs: 8000, clipIndex: 1 },
@@ -155,7 +149,7 @@ describe("projectRegionsToSource", () => {
const segments = resolvePlaybackSegments([c1, c2], [trim("a", 2, 8)]);
// segments: c1[0,2] (0), c1[8,10] (1), c2[0,10] (2).
const anchored = { ...region("r", 3, 5), clipId: "c1", sourceStartSec: 3, sourceEndSec: 5 };
- expect(projectRegionsToSource([anchored], segments, [c1, c2], () => "x", [])).toEqual([
+ expect(projectRegionsToSource([anchored], segments, [c1, c2], () => "x")).toEqual([
{ ...anchored, startMs: 3000, endMs: 5000, clipIndex: 0, underTrim: true },
]);
});
@@ -181,7 +175,7 @@ describe("projectRegionsToSource", () => {
});
const segments = resolvePlaybackSegments([c1, c2], [trim("a", 0, 10)]);
const anchored = { ...region("r", 3, 5), clipId: "c1", sourceStartSec: 3, sourceEndSec: 5 };
- expect(projectRegionsToSource([anchored], segments, [c1, c2], () => "x", [])).toEqual([]);
+ expect(projectRegionsToSource([anchored], segments, [c1, c2], () => "x")).toEqual([]);
});
it("keeps an unanchored region a trim removes entirely, mapped through its raw clip", () => {
@@ -197,7 +191,7 @@ describe("projectRegionsToSource", () => {
timelineEndSec: 10,
});
const segments = resolvePlaybackSegments([c], [trim("a", 4, 6)]);
- expect(projectRegionsToSource([region("r", 4.5, 5.5)], segments, [c], () => "x", [])).toEqual([
+ expect(projectRegionsToSource([region("r", 4.5, 5.5)], segments, [c], () => "x")).toEqual([
{ id: "r", startMs: 4500, endMs: 5500, clipIndex: 0, underTrim: true },
]);
});
@@ -214,7 +208,7 @@ describe("projectRegionsToSource", () => {
});
const segments = resolvePlaybackSegments([c], [trim("a", 0, 3)]);
const anchored = { ...region("r", 1, 2), clipId: "c1", sourceStartSec: 1, sourceEndSec: 2 };
- expect(projectRegionsToSource([anchored], segments, [c], () => "x", [])).toEqual([
+ expect(projectRegionsToSource([anchored], segments, [c], () => "x")).toEqual([
{ ...anchored, startMs: 1000, endMs: 2000, clipIndex: 0, underTrim: true },
]);
});
@@ -240,9 +234,9 @@ describe("projectRegionsToSource", () => {
});
const segments = resolvePlaybackSegments([c1, c2], [trim("a", 6, 10)]);
const anchored = { ...region("r", 7, 9), clipId: "c1", sourceStartSec: 7, sourceEndSec: 9 };
- const [projected] = projectRegionsToSource([anchored], segments, [c1, c2], () => "x", []);
+ const [projected] = projectRegionsToSource([anchored], segments, [c1, c2], () => "x");
// raw 8 is inside c1's removed tail; the region covering source [7,9] is that same cut.
- expect(resolveNativePosition(8, segments, [c1, c2], [])?.clipIndex).toBe(projected.clipIndex);
+ expect(resolveNativePosition(8, segments, [c1, c2])?.clipIndex).toBe(projected.clipIndex);
});
// --- anchored path: the anchor is the SSOT, `startMs`/`endMs` are not consulted ---
@@ -264,7 +258,7 @@ describe("projectRegionsToSource", () => {
sourceStartSec: 6,
sourceEndSec: 8,
};
- const out = projectRegionsToSource([stale], [c], [c], () => "x", []);
+ const out = projectRegionsToSource([stale], [c], [c], () => "x");
expect(out).toEqual([{ ...stale, startMs: 6000, endMs: 8000, clipIndex: 0 }]);
});
@@ -284,7 +278,7 @@ describe("projectRegionsToSource", () => {
sourceStartSec: 3,
sourceEndSec: 8,
};
- const out = projectRegionsToSource([anchored], segments, [c], () => "r2", []);
+ const out = projectRegionsToSource([anchored], segments, [c], () => "r2");
expect(out).toEqual([
{ ...anchored, id: "r", startMs: 3000, endMs: 4000, clipIndex: 0 },
{ ...anchored, id: "r2", startMs: 6000, endMs: 8000, clipIndex: 1 },
@@ -316,7 +310,7 @@ describe("projectRegionsToSource", () => {
sourceStartSec: 1,
sourceEndSec: 2,
};
- const out = projectRegionsToSource([anchored], [c1, c2], [c1, c2], () => "x", []);
+ const out = projectRegionsToSource([anchored], [c1, c2], [c1, c2], () => "x");
expect(out).toEqual([{ ...anchored, startMs: 1000, endMs: 2000, clipIndex: 1 }]);
});
@@ -331,7 +325,7 @@ describe("projectRegionsToSource", () => {
timelineEndSec: 10,
});
const partial = { ...region("r", 3, 5), clipId: "c1" }; // no source span
- const out = projectRegionsToSource([partial], [c], [c], () => "x", []);
+ const out = projectRegionsToSource([partial], [c], [c], () => "x");
expect(out).toEqual([{ ...partial, startMs: 3000, endMs: 5000, clipIndex: 0 }]);
});
});
@@ -357,12 +351,12 @@ describe("resolveNativePosition", () => {
timelineEndSec: 12,
}),
];
- expect(resolveNativePosition(6.5, clips, clips, [])).toMatchObject({
+ expect(resolveNativePosition(6.5, clips, clips)).toMatchObject({
clip: { id: "c2" },
clipIndex: 1,
sourceTimeSec: 22.5,
});
- expect(resolveNativePosition(10, clips, clips, [])).toMatchObject({
+ expect(resolveNativePosition(10, clips, clips)).toMatchObject({
clip: { id: "c3" },
clipIndex: 2,
sourceTimeSec: 42,
@@ -389,12 +383,12 @@ describe("resolveNativePosition", () => {
timelineEndSec: 12,
}),
];
- expect(resolveNativePosition(7.25, clips, clips, [])).toMatchObject({
+ expect(resolveNativePosition(7.25, clips, clips)).toMatchObject({
clip: { assetId: "asset-b" },
clipIndex: 1,
sourceTimeSec: 103.25,
});
- expect(resolveNativePosition(11, clips, clips, [])).toMatchObject({
+ expect(resolveNativePosition(11, clips, clips)).toMatchObject({
clip: { assetId: "asset-c" },
clipIndex: 2,
sourceTimeSec: 14,
@@ -411,11 +405,11 @@ describe("resolveNativePosition", () => {
});
const segments = resolvePlaybackSegments([c], [trim("a", 2, 4)]);
// raw 1 → source 1 on seg1; raw 6 → source 6 on seg2 (NOT 8).
- expect(resolveNativePosition(1, segments, [c], [])).toMatchObject({
+ expect(resolveNativePosition(1, segments, [c])).toMatchObject({
clipIndex: 0,
sourceTimeSec: 1,
});
- expect(resolveNativePosition(6, segments, [c], [])).toMatchObject({
+ expect(resolveNativePosition(6, segments, [c])).toMatchObject({
clipIndex: 1,
sourceTimeSec: 6,
});
@@ -436,7 +430,7 @@ describe("resolveNativePosition", () => {
// points at, and would incrust any modifier under the cut on someone else's image (#216).
// The segment it borrows is the one the cut interrupts (seg1), so a modifier under that
// cut — addressed the same way — survives `belongs()`.
- expect(resolveNativePosition(3, segments, [c], [])).toMatchObject({
+ expect(resolveNativePosition(3, segments, [c])).toMatchObject({
clipIndex: 0,
sourceTimeSec: 3,
});
@@ -451,7 +445,7 @@ describe("resolveNativePosition", () => {
timelineEndSec: 10,
});
const segments = resolvePlaybackSegments([c], [trim("a", 0, 3)]);
- expect(resolveNativePosition(1, segments, [c], [])).toMatchObject({
+ expect(resolveNativePosition(1, segments, [c])).toMatchObject({
clipIndex: 0,
sourceTimeSec: 1,
});
@@ -467,11 +461,11 @@ describe("resolveNativePosition", () => {
});
const segments = resolvePlaybackSegments([c], [trim("a", 2, 4)]);
// No raw clip owns raw 99 — nothing to present, so the historical clamp stands.
- expect(resolveNativePosition(99, segments, [c], [])).toMatchObject({ clipIndex: 1 });
+ expect(resolveNativePosition(99, segments, [c])).toMatchObject({ clipIndex: 1 });
});
it("returns null when there are no segments", () => {
- expect(resolveNativePosition(1, [], [], [])).toBeNull();
+ expect(resolveNativePosition(1, [], [])).toBeNull();
});
});
@@ -811,65 +805,3 @@ describe("legacy groupId must never affect identity (regression: test 1)", () =>
expect(out[0]).not.toHaveProperty("groupId");
});
});
-
-// ─── Placing an unanchored region past an insertion ─────────────────────────
-// A caption cue is built fresh on every derive and carries no clip anchor, so it is placed
-// by intersecting its TIMELINE span with each segment's extent. A clip carrying insertions
-// is longer than its source window, so the segment that resumes after one starts that much
-// further along — and a projection blind to that put every caption after an insertion on
-// the wrong stretch of source. That is what "the subtitles are out of sync" was (#560).
-
-describe("projectRegionsToSource past an insertion", () => {
- const raw = clip({
- id: "c1",
- assetId: "a1",
- sourceStartSec: 0,
- sourceEndSec: 10,
- timelineStartSec: 0,
- timelineEndSec: 11, // 10s of recording + 1s inserted at source 5
- });
- const inserts: AxcutInsertRange[] = [
- {
- id: "i1",
- assetId: "a1",
- atSec: 5,
- durationSec: 1,
- wordId: "w1",
- reason: "",
- origin: "user",
- },
- ];
- // What `resolvePlaybackSegments` produces: the clip split at the insertion, with the
- // inserted media between the halves.
- const segments = [
- clip({ id: "c1_seg1", assetId: "a1", sourceStartSec: 0, sourceEndSec: 5 }),
- clip({ id: "c1_seg2", assetId: "a1", sourceStartSec: 5, sourceEndSec: 10 }),
- ];
-
- it("lands a region on the source it actually names", () => {
- // Timeline 7..9 is one second past the insertion, so it is source 6..8.
- const [out] = projectRegionsToSource(
- [region("cue", 7, 9)],
- segments,
- [raw],
- () => "x",
- inserts,
- );
- expect(out.startMs).toBe(6000);
- expect(out.endMs).toBe(8000);
- expect(out.clipIndex).toBe(1);
- });
-
- it("leaves a region before the insertion where it was", () => {
- const [out] = projectRegionsToSource(
- [region("cue", 1, 3)],
- segments,
- [raw],
- () => "x",
- inserts,
- );
- expect(out.startMs).toBe(1000);
- expect(out.endMs).toBe(3000);
- expect(out.clipIndex).toBe(0);
- });
-});
diff --git a/src/lib/ai-edition/timeline/timelineMap.ts b/src/lib/ai-edition/timeline/timelineMap.ts
index e344c2398..b98601a03 100644
--- a/src/lib/ai-edition/timeline/timelineMap.ts
+++ b/src/lib/ai-edition/timeline/timelineMap.ts
@@ -17,8 +17,7 @@
// against the COMPRESSED segment layout, which slips every region after a trim
// forward by the trimmed duration.
-import type { PlaybackSegment } from "../document/timeline";
-import type { AxcutClip, AxcutInsertRange } from "../schema";
+import type { AxcutClip } from "../schema";
import { ventilateSpanAcrossClips } from "./region-ventilation";
import { findRawClipForSegment, getRawVirtualStartTime } from "./virtual-preview";
@@ -96,11 +95,6 @@ export function anchoredToRawSpanSec(
): { startSec: number; endSec: number } | null {
const clip = clips.find((c) => c.id === fragment.clipId);
if (!clip) return null;
- // ponytail: plain shift, wrong by the clip's own insertions for a region anchored past
- // one — the pill is drawn early while `projectRegionsToSource` exports it on the right
- // frames. Route through `sourceToTimelineSec` when zoom/annotation pills need to agree
- // with the effect; it means threading the ranges through `anchorRegionsWithDerivedMs`
- // and its 15 callers, which is its own change.
return {
startSec: clip.timelineStartSec + (fragment.sourceStartSec - clip.sourceStartSec),
endSec: clip.timelineStartSec + (fragment.sourceEndSec - clip.sourceStartSec),
@@ -405,19 +399,11 @@ export function anchorRegionsWithDerivedMs<
* the gap.
*/
export function segmentRawSpanSec(
- segment: PlaybackSegment,
+ segment: AxcutClip,
rawClips: AxcutClip[],
- /** REQUIRED, not defaulted. A clip carrying insertions is longer than its source window,
- * so a caller that omits these gets an answer that is plausible and wrong by exactly the
- * inserted time, with nothing to catch it (issue #560). */
- insertRanges: readonly AxcutInsertRange[],
): { startSec: number; endSec: number } {
- const startSec = getRawVirtualStartTime(segment, rawClips, insertRanges);
- // A held segment's source window is the single frame it shows, so its source length
- // is zero — its RAW span is the pause it carries. Without this the playhead could
- // never be inside it and would step straight over the pause.
- const lenSec =
- segment.heldSec ?? (segment.sourceEndSec ?? segment.sourceStartSec) - segment.sourceStartSec;
+ const startSec = getRawVirtualStartTime(segment, rawClips);
+ const lenSec = (segment.sourceEndSec ?? segment.sourceStartSec) - segment.sourceStartSec;
return { startSec, endSec: startSec + lenSec };
}
@@ -573,21 +559,14 @@ export function projectRegionsToSource<
T extends { id: string; startMs: number; endMs: number } & RegionClipAnchor,
>(
regions: T[],
- visibleSegments: PlaybackSegment[],
+ visibleSegments: AxcutClip[],
rawClips: AxcutClip[],
makeId: () => string,
- /** The insertions the clips carry. A segment after one starts that much further along
- * the timeline, and an UNANCHORED region — a caption cue, which is built fresh each
- * time and has no clip anchor — is placed by intersecting with exactly that extent.
- * Without them the caption landed on the wrong stretch of source (issue #560).
- *
- * REQUIRED for the same reason as its neighbours: omitting it is silently wrong. */
- insertRanges: readonly AxcutInsertRange[],
): (T & { clipIndex?: number; underTrim?: boolean })[] {
// RAW extents + owning raw clip per visible segment. Both are only consulted by the
// path that needs them (raw fallback / anchor match), but resolving them once keeps
// the per-region loop free of repeated lookups.
- const spans = visibleSegments.map((seg) => segmentRawSpanSec(seg, rawClips, insertRanges));
+ const spans = visibleSegments.map((seg) => segmentRawSpanSec(seg, rawClips));
const segmentRawClipIds = visibleSegments.map((seg) => findRawClipForSegment(seg, rawClips)?.id);
const out: (T & { clipIndex?: number; underTrim?: boolean })[] = [];
for (const region of regions) {
@@ -660,7 +639,7 @@ export function projectRegionsToSource<
export interface NativePosition {
/** The trim-narrowed playback segment (from `visibleSegments`) that is active. */
- clip: PlaybackSegment;
+ clip: AxcutClip;
/** Its index in `visibleSegments`, matching `SceneDescription.clips` / native `clip_index`. */
clipIndex: number;
/** Screen-source seconds the native decoder should present for this segment. */
@@ -696,31 +675,20 @@ const NATIVE_EOF_MARGIN_SEC = 0.033;
*/
export function resolveNativePosition(
rawSec: number,
- visibleSegments: PlaybackSegment[],
+ visibleSegments: AxcutClip[],
rawClips: AxcutClip[],
- /** REQUIRED, not defaulted. A clip carrying insertions is longer than its source window,
- * so a caller that omits these gets an answer that is plausible and wrong by exactly the
- * inserted time, with nothing to catch it (issue #560). */
- insertRanges: readonly AxcutInsertRange[],
): NativePosition | null {
if (!Number.isFinite(rawSec) || visibleSegments.length === 0) return null;
- const spans = visibleSegments.map((seg) => segmentRawSpanSec(seg, rawClips, insertRanges));
+ const spans = visibleSegments.map((seg) => segmentRawSpanSec(seg, rawClips));
// Segment whose RAW extent contains the playhead (last segment's end inclusive).
const index = spans.findIndex((s, i) => {
const isLast = i === spans.length - 1;
return rawSec >= s.startSec && (rawSec < s.endSec || (isLast && rawSec <= s.endSec));
});
- if (index < 0) return positionUnderCut(rawSec, visibleSegments, rawClips, insertRanges);
+ if (index < 0) return positionUnderCut(rawSec, visibleSegments, rawClips);
const seg = visibleSegments[index];
- // Inside a pause the source clock does not advance: the whole point of the segment
- // is created time over one held frame. Clamping here is what stops the raw-playhead
- // delta — which DOES advance through the pause — from pushing the decoder past the
- // held frame into the content that belongs after it.
- if (seg.heldSec !== undefined) {
- return { clip: seg, clipIndex: index, sourceTimeSec: seg.sourceStartSec };
- }
const segSourceEnd = seg.sourceEndSec ?? seg.sourceStartSec;
const unclamped = seg.sourceStartSec + (rawSec - spans[index].startSec);
const maxSource = Math.max(seg.sourceStartSec, segSourceEnd - NATIVE_EOF_MARGIN_SEC);
@@ -746,7 +714,6 @@ function positionUnderCut(
rawSec: number,
visibleSegments: AxcutClip[],
rawClips: AxcutClip[],
- insertRanges: readonly AxcutInsertRange[],
): NativePosition {
const rawClip = rawClipAt(rawSec, rawClips);
if (rawClip) {
@@ -771,7 +738,7 @@ function positionUnderCut(
}
}
- const spans = visibleSegments.map((seg) => segmentRawSpanSec(seg, rawClips, insertRanges));
+ const spans = visibleSegments.map((seg) => segmentRawSpanSec(seg, rawClips));
const next = spans.findIndex((s) => s.startSec >= rawSec);
const index = next >= 0 ? next : visibleSegments.length - 1;
const seg = visibleSegments[index];
diff --git a/src/lib/ai-edition/timeline/trim-mapping.test.ts b/src/lib/ai-edition/timeline/trim-mapping.test.ts
index 0e003351e..3ac5cba00 100644
--- a/src/lib/ai-edition/timeline/trim-mapping.test.ts
+++ b/src/lib/ai-edition/timeline/trim-mapping.test.ts
@@ -38,7 +38,7 @@ describe("trimToTimelineSpan", () => {
timelineEndSec: 42,
}),
];
- expect(trimToTimelineSpan({ assetId: "a", startSec: 5, endSec: 7 }, clips, [])).toEqual({
+ expect(trimToTimelineSpan({ assetId: "a", startSec: 5, endSec: 7 }, clips)).toEqual({
start: 5,
end: 7,
});
@@ -65,7 +65,7 @@ describe("trimToTimelineSpan", () => {
}),
];
// A trim at source 20..22 lives in c2 → timeline 14 + (20-16) = 18..20.
- expect(trimToTimelineSpan({ assetId: "a", startSec: 20, endSec: 22 }, clips, [])).toEqual({
+ expect(trimToTimelineSpan({ assetId: "a", startSec: 20, endSec: 22 }, clips)).toEqual({
start: 18,
end: 20,
});
@@ -73,8 +73,8 @@ describe("trimToTimelineSpan", () => {
it("returns null when no clip carries the trim's source region", () => {
const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })];
- expect(trimToTimelineSpan({ assetId: "a", startSec: 40, endSec: 42 }, clips, [])).toBeNull();
- expect(trimToTimelineSpan({ assetId: "b", startSec: 2, endSec: 4 }, clips, [])).toBeNull();
+ expect(trimToTimelineSpan({ assetId: "a", startSec: 40, endSec: 42 }, clips)).toBeNull();
+ expect(trimToTimelineSpan({ assetId: "b", startSec: 2, endSec: 4 }, clips)).toBeNull();
});
});
@@ -99,7 +99,7 @@ describe("resolveTimelineSpanToTrim", () => {
}),
];
// Timeline 18..20 falls in c2 (asset b) → source 16 + (18-14)=20 .. 22.
- expect(resolveTimelineSpanToTrim(18, 20, clips, [])).toEqual({
+ expect(resolveTimelineSpanToTrim(18, 20, clips)).toEqual({
assetId: "b",
clipId: "c2",
sourceStartSec: 20,
@@ -127,8 +127,8 @@ describe("resolveTimelineSpanToTrim", () => {
}),
];
// Start in c1 → asset a, start in c2 → asset b.
- expect(resolveTimelineSpanToTrim(2, 4, clips, [])?.assetId).toBe("a");
- expect(resolveTimelineSpanToTrim(20, 22, clips, [])?.assetId).toBe("b");
+ expect(resolveTimelineSpanToTrim(2, 4, clips)?.assetId).toBe("a");
+ expect(resolveTimelineSpanToTrim(20, 22, clips)?.assetId).toBe("b");
});
it("clamps the span to the carrier clip's extent (no straddling)", () => {
@@ -151,7 +151,7 @@ describe("resolveTimelineSpanToTrim", () => {
}),
];
// Span 10..20 starts in c1; end clamps to c1's end (timeline 14 → source 14).
- expect(resolveTimelineSpanToTrim(10, 20, clips, [])).toEqual({
+ expect(resolveTimelineSpanToTrim(10, 20, clips)).toEqual({
assetId: "a",
clipId: "c1",
sourceStartSec: 10,
@@ -178,7 +178,7 @@ describe("resolveTimelineSpanToTrim", () => {
timelineEndSec: 28,
}),
];
- const resolved = resolveTimelineSpanToTrim(18, 21, clips, []);
+ const resolved = resolveTimelineSpanToTrim(18, 21, clips);
expect(resolved).not.toBeNull();
if (!resolved) return;
const back = trimToTimelineSpan(
@@ -188,13 +188,12 @@ describe("resolveTimelineSpanToTrim", () => {
endSec: resolved.sourceEndSec,
},
clips,
- [],
);
expect(back).toEqual({ start: 18, end: 21 });
});
it("returns null with no clips", () => {
- expect(resolveTimelineSpanToTrim(1, 2, [], [])).toBeNull();
+ expect(resolveTimelineSpanToTrim(1, 2, [])).toBeNull();
});
});
@@ -271,9 +270,7 @@ describe("coalescedTrimGroups", () => {
trim({ id: "t1", assetId: "a", startSec: 8, endSec: 14 }), // -> timeline 8..14
trim({ id: "t2", assetId: "a", startSec: 16, endSec: 22 }), // -> timeline 14..20
];
- expect(coalescedTrimGroups(trims, clips, [])).toEqual([
- { ids: ["t1", "t2"], start: 8, end: 20 },
- ]);
+ expect(coalescedTrimGroups(trims, clips)).toEqual([{ ids: ["t1", "t2"], start: 8, end: 20 }]);
});
it("groups two independently-created trims snapped to touching clip boundaries", () => {
@@ -302,9 +299,7 @@ describe("coalescedTrimGroups", () => {
trim({ id: "t1", assetId: "a", startSec: 7, endSec: 10 }), // -> timeline 7..10
trim({ id: "t2", assetId: "b", startSec: 0, endSec: 2 }), // -> timeline 10..12
];
- expect(coalescedTrimGroups(trims, clips, [])).toEqual([
- { ids: ["t1", "t2"], start: 7, end: 12 },
- ]);
+ expect(coalescedTrimGroups(trims, clips)).toEqual([{ ids: ["t1", "t2"], start: 7, end: 12 }]);
});
it("keeps a trim separated by a real gap in its own group", () => {
@@ -322,7 +317,7 @@ describe("coalescedTrimGroups", () => {
trim({ id: "t1", assetId: "a", startSec: 2, endSec: 4 }),
trim({ id: "t2", assetId: "a", startSec: 10, endSec: 12 }),
];
- expect(coalescedTrimGroups(trims, clips, [])).toEqual([
+ expect(coalescedTrimGroups(trims, clips)).toEqual([
{ ids: ["t1"], start: 2, end: 4 },
{ ids: ["t2"], start: 10, end: 12 },
]);
@@ -343,7 +338,7 @@ describe("coalescedTrimGroups", () => {
trim({ id: "gone", assetId: "b", startSec: 0, endSec: 2 }), // no clip carries asset b
trim({ id: "t1", assetId: "a", startSec: 3, endSec: 5 }),
];
- expect(coalescedTrimGroups(trims, clips, [])).toEqual([{ ids: ["t1"], start: 3, end: 5 }]);
+ expect(coalescedTrimGroups(trims, clips)).toEqual([{ ids: ["t1"], start: 3, end: 5 }]);
});
});
@@ -375,17 +370,15 @@ describe("two clips sharing one asset over the same source window", () => {
// Without the anchor this returned {3,5} — the first clip — because the loop
// stopped at the first clip whose asset and source window matched.
expect(
- trimToTimelineSpan({ assetId: "a", clipId: "c2", startSec: 3, endSec: 5 }, sharedClips(), []),
+ trimToTimelineSpan({ assetId: "a", clipId: "c2", startSec: 3, endSec: 5 }, sharedClips()),
).toEqual({ start: 15, end: 17 });
});
it("keeps mapping an un-anchored trim to the first matching clip (pre-v7 behaviour)", () => {
- expect(trimToTimelineSpan({ assetId: "a", startSec: 3, endSec: 5 }, sharedClips(), [])).toEqual(
- {
- start: 3,
- end: 5,
- },
- );
+ expect(trimToTimelineSpan({ assetId: "a", startSec: 3, endSec: 5 }, sharedClips())).toEqual({
+ start: 3,
+ end: 5,
+ });
});
it("draws one pill per clip when each clip carries its own trim", () => {
@@ -394,7 +387,7 @@ describe("two clips sharing one asset over the same source window", () => {
trim({ id: "t2", assetId: "a", clipId: "c2", startSec: 3, endSec: 5 }),
];
// Two pills, 12s apart — not one merged pill, and not two stacked on c1.
- expect(coalescedTrimGroups(trims, sharedClips(), [])).toEqual([
+ expect(coalescedTrimGroups(trims, sharedClips())).toEqual([
{ ids: ["t1"], start: 3, end: 5 },
{ ids: ["t2"], start: 15, end: 17 },
]);
@@ -404,7 +397,7 @@ describe("two clips sharing one asset over the same source window", () => {
// The twin still uses the same asset over the same source range, so an asset-only
// match would resurrect the cut on it.
const trims = [trim({ id: "orphan", assetId: "a", clipId: "c2", startSec: 3, endSec: 5 })];
- expect(coalescedTrimGroups(trims, [sharedClips()[0]], [])).toEqual([]);
+ expect(coalescedTrimGroups(trims, [sharedClips()[0]])).toEqual([]);
});
it("still shows a pill when the anchor clip was re-cut past the trim's start", () => {
@@ -421,7 +414,7 @@ describe("two clips sharing one asset over the same source window", () => {
}),
];
expect(
- trimToTimelineSpan({ assetId: "a", clipId: "c2", startSec: 3, endSec: 5 }, clips, []),
+ trimToTimelineSpan({ assetId: "a", clipId: "c2", startSec: 3, endSec: 5 }, clips),
).toEqual({ start: 0, end: 1 });
});
});
diff --git a/src/lib/ai-edition/timeline/trim-mapping.ts b/src/lib/ai-edition/timeline/trim-mapping.ts
index 701b575d0..0dee56d7d 100644
--- a/src/lib/ai-edition/timeline/trim-mapping.ts
+++ b/src/lib/ai-edition/timeline/trim-mapping.ts
@@ -14,8 +14,7 @@
// clip) share a coordinate space: without the anchor, "which clip is this cut on?"
// had no answer and each caller invented its own. See `trimAppliesToClip`.
-import type { AxcutClip, AxcutInsertRange, AxcutTrimRange } from "../schema";
-import { sourceToTimelineSec, timelineToSourceSec } from "./inserted-time";
+import type { AxcutClip, AxcutTrimRange } from "../schema";
import { type CoalescedSpan, ventilateSpanAcrossClips } from "./region-ventilation";
import { coalesceByIdentity, regionIdentityKey } from "./timelineMap";
@@ -69,9 +68,6 @@ export function trimAppliesToClip(
export function trimToTimelineSpan(
trim: TrimAnchor,
clips: AxcutClip[],
- /** REQUIRED: a clip carrying insertions is longer than its source window, so this is not
- * a plain shift (issue #560). */
- insertRanges: readonly AxcutInsertRange[],
): { start: number; end: number } | null {
for (const c of clips) {
if (!trimAppliesToClip(trim, c)) continue;
@@ -82,7 +78,7 @@ export function trimToTimelineSpan(
: trim.startSec >= c.sourceStartSec && trim.startSec <= srcEnd;
if (carries) {
const map = (s: number) =>
- sourceToTimelineSec(c, Math.min(Math.max(s, c.sourceStartSec), srcEnd), insertRanges);
+ c.timelineStartSec + (Math.min(Math.max(s, c.sourceStartSec), srcEnd) - c.sourceStartSec);
return { start: map(trim.startSec), end: map(trim.endSec) };
}
}
@@ -144,12 +140,11 @@ export function ventilateTimelineSpanToTrims(
export function coalescedTrimGroups(
trimRanges: AxcutTrimRange[],
clips: AxcutClip[],
- insertRanges: readonly AxcutInsertRange[],
epsilonSec?: number,
): CoalescedSpan[] {
const spans = trimRanges
.map((t) => {
- const mapped = trimToTimelineSpan(t, clips, insertRanges);
+ const mapped = trimToTimelineSpan(t, clips);
return mapped
? {
id: t.id,
@@ -188,12 +183,10 @@ export function resolveTrimPillIds(
trimRanges: AxcutTrimRange[],
clips: AxcutClip[],
id: string,
- insertRanges: readonly AxcutInsertRange[],
epsilonSec?: number,
): string[] {
return (
- coalescedTrimGroups(trimRanges, clips, insertRanges, epsilonSec).find((g) => g.ids.includes(id))
- ?.ids ?? [id]
+ coalescedTrimGroups(trimRanges, clips, epsilonSec).find((g) => g.ids.includes(id))?.ids ?? [id]
);
}
@@ -208,14 +201,11 @@ export function dropTrimPillsByIds(
trimRanges: AxcutTrimRange[],
clips: AxcutClip[],
ids: Iterable<string>,
- insertRanges: readonly AxcutInsertRange[],
epsilonSec?: number,
): AxcutTrimRange[] {
const under = new Set<string>();
for (const id of ids) {
- for (const member of resolveTrimPillIds(trimRanges, clips, id, insertRanges, epsilonSec)) {
- under.add(member);
- }
+ for (const member of resolveTrimPillIds(trimRanges, clips, id, epsilonSec)) under.add(member);
}
if (under.size === 0) return trimRanges;
return trimRanges.filter((t) => !under.has(t.id));
@@ -235,9 +225,6 @@ export function resolveTimelineSpanToTrim(
startSec: number,
endSec: number,
clips: AxcutClip[],
- /** REQUIRED: a clip carrying insertions is longer than its source window, so this is not
- * a plain shift (issue #560). */
- insertRanges: readonly AxcutInsertRange[],
): TrimSourceRange | null {
if (clips.length === 0) return null;
const lo = Math.min(startSec, endSec);
@@ -259,7 +246,7 @@ export function resolveTimelineSpanToTrim(
Math.min(lo, carrier.timelineStartSec + srcLen),
);
const tEnd = Math.max(tStart, Math.min(hi, carrier.timelineStartSec + srcLen));
- const toSrc = (t: number) => timelineToSourceSec(carrier, t, insertRanges).sourceSec;
+ const toSrc = (t: number) => carrier.sourceStartSec + (t - carrier.timelineStartSec);
return {
assetId: carrier.assetId,
clipId: carrier.id,
diff --git a/src/lib/ai-edition/timeline/virtual-preview.test.ts b/src/lib/ai-edition/timeline/virtual-preview.test.ts
index 37bac870b..f3dd64888 100644
--- a/src/lib/ai-edition/timeline/virtual-preview.test.ts
+++ b/src/lib/ai-edition/timeline/virtual-preview.test.ts
@@ -51,24 +51,24 @@ describe("virtual-preview pure functions", () => {
});
it("locateVirtualPosition maps virtual time to source time", () => {
- const pos = locateVirtualPosition(clips, 12, []);
+ const pos = locateVirtualPosition(clips, 12);
expect(pos).not.toBeNull();
expect(pos?.clipIndex).toBe(1);
expect(pos?.sourceTimeSec).toBe(22);
});
it("locateVirtualPosition returns null for empty clips", () => {
- expect(locateVirtualPosition([], 0, [])).toBeNull();
+ expect(locateVirtualPosition([], 0)).toBeNull();
});
it("locateSourcePosition maps source time back to virtual time", () => {
- const pos = locateSourcePosition(clips, 25, undefined, 0.05, undefined, []);
+ const pos = locateSourcePosition(clips, 25);
expect(pos).not.toBeNull();
expect(pos?.virtualTimeSec).toBe(15);
});
it("locateSourcePosition returns null for source time in a cut", () => {
- expect(locateSourcePosition(clips, 15, undefined, 0.05, undefined, [])).toBeNull();
+ expect(locateSourcePosition(clips, 15)).toBeNull();
});
it("keptWordIdSet flattens wordRefs from all clips", () => {
@@ -106,13 +106,13 @@ describe("virtual-preview pure functions", () => {
reason: "",
},
];
- const pos1 = locateSourcePosition(multiClips, 5, "a1", 0.05, undefined, []);
+ const pos1 = locateSourcePosition(multiClips, 5, "a1");
expect(pos1?.clip.id).toBe("clip_1");
- const pos2 = locateSourcePosition(multiClips, 5, "a2", 0.05, undefined, []);
+ const pos2 = locateSourcePosition(multiClips, 5, "a2");
expect(pos2?.clip.id).toBe("clip_2");
- const posNone = locateSourcePosition(multiClips, 5, "a3", 0.05, undefined, []);
+ const posNone = locateSourcePosition(multiClips, 5, "a3");
expect(posNone).toBeNull();
});
@@ -148,19 +148,19 @@ describe("virtual-preview pure functions", () => {
// the earliest matching clip — this is the bug: playing back the
// second clip's segment would still report position/identity for the
// first.
- const ambiguous = locateSourcePosition(duplicateClips, 5, "a1", 0.05, undefined, []);
+ const ambiguous = locateSourcePosition(duplicateClips, 5, "a1");
expect(ambiguous?.clip.id).toBe("clip_1");
// With the currently-active clip id passed through, it's preferred
// even though clip_1 also matches (assetId, sourceTime).
- const disambiguated = locateSourcePosition(duplicateClips, 5, "a1", 0.05, "clip_2", []);
+ const disambiguated = locateSourcePosition(duplicateClips, 5, "a1", 0.05, "clip_2");
expect(disambiguated?.clip.id).toBe("clip_2");
expect(disambiguated?.virtualTimeSec).toBe(15);
// A preferred clip id that no longer applies (source time moved
// outside its range) falls back to the ambiguous scan rather than
// forcing a stale match.
- const outOfRange = locateSourcePosition(duplicateClips, 5, "a1", 0.05, "clip_3", []);
+ const outOfRange = locateSourcePosition(duplicateClips, 5, "a1", 0.05, "clip_3");
expect(outOfRange?.clip.id).toBe("clip_1");
});
@@ -213,7 +213,6 @@ describe("virtual-preview pure functions", () => {
playingClip.assetId,
0.05,
playingClip.id,
- [],
);
expect(pos?.clip.id).toBe(playing);
expect(pos?.virtualTimeSec).toBeCloseTo(playingClip.timelineStartSec + sourceTimeSec, 6);
@@ -223,8 +222,8 @@ describe("virtual-preview pure functions", () => {
// The scan cannot know which twin is playing — but its answer must at least not
// depend on which twin happens to sit last in the array, which is what
// `index === clips.length - 1` made it do.
- const forward = locateSourcePosition(twins([a1, a2]), 9.96, "a1", 0.05, undefined, []);
- const reversed = locateSourcePosition(twins([a2, a1]), 9.96, "a1", 0.05, undefined, []);
+ const forward = locateSourcePosition(twins([a1, a2]), 9.96, "a1");
+ const reversed = locateSourcePosition(twins([a2, a1]), 9.96, "a1");
expect(forward?.clip.id).toBe("clip_a1");
expect(reversed?.clip.id).toBe("clip_a2");
// i.e. both resolve to the FIRST clip of the asset — the documented behaviour of
@@ -247,17 +246,17 @@ describe("virtual-preview pure functions", () => {
timelineEndSec: 20,
},
];
- expect(locateSourcePosition(split, 10, "a1", 0.05, undefined, [])?.clip.id).toBe("clip_a2");
- expect(locateSourcePosition(split, 9.9, "a1", 0.05, undefined, [])?.clip.id).toBe("clip_a1");
+ expect(locateSourcePosition(split, 10, "a1")?.clip.id).toBe("clip_a2");
+ expect(locateSourcePosition(split, 9.9, "a1")?.clip.id).toBe("clip_a1");
// …and the very end of the timeline still resolves rather than falling off it.
- expect(locateSourcePosition(split, 20, "a1", 0.05, undefined, [])?.clip.id).toBe("clip_a2");
+ expect(locateSourcePosition(split, 20, "a1")?.clip.id).toBe("clip_a2");
});
it("ignores a named clip whose asset is not the one playing", () => {
// A stale id during an asset swap must fall through to the scan rather than
// mapping the time through media that is not on screen.
const clips = twins([a1, c3]);
- const pos = locateSourcePosition(clips, 5, "a1", 0.05, "clip_c3", []);
+ const pos = locateSourcePosition(clips, 5, "a1", 0.05, "clip_c3");
expect(pos?.clip.id).toBe("clip_a1");
});
});
@@ -368,8 +367,8 @@ describe("virtual-preview pure functions", () => {
timelineEndSec: 13.8,
};
- expect(getRawVirtualStartTime(segClip1Part2, rawClips, [])).toBe(6);
- expect(getRawVirtualStartTime(segClip2Part1, rawClips, [])).toBe(13.2);
+ expect(getRawVirtualStartTime(segClip1Part2, rawClips)).toBe(6);
+ expect(getRawVirtualStartTime(segClip2Part1, rawClips)).toBe(13.2);
});
it("findNextKeptSegment finds next kept segment across multi-clip trim boundary", () => {
@@ -422,11 +421,11 @@ describe("virtual-preview pure functions", () => {
];
// At current raw virtual time 2.5s (end of seg 0), next kept segment is seg 1 (clip_2)
- const nextSeg = findNextKeptSegment(playbackClips, rawClips, 2.5, "a1", 2.5, undefined, []);
+ const nextSeg = findNextKeptSegment(playbackClips, rawClips, 2.5, "a1", 2.5);
expect(nextSeg).toBeDefined();
expect(nextSeg?.id).toBe("clip_2");
expect(nextSeg?.assetId).toBe("a2");
- expect(getRawVirtualStartTime(nextSeg!, rawClips, [])).toBe(10.7);
+ expect(getRawVirtualStartTime(nextSeg!, rawClips)).toBe(10.7);
});
describe("findNextKeptSegment never goes backwards", () => {
@@ -474,9 +473,9 @@ describe("virtual-preview pure functions", () => {
// clip_1 starts at source 30, which IS "later in source time", and its raw start
// is 0: answering it sent playback back to the beginning, straight into the same
// cut again, forever.
- const next = findNextKeptSegment(playbackClips, rawClips, 17, "a1", 7, "clip_2", []);
+ const next = findNextKeptSegment(playbackClips, rawClips, 17, "a1", 7, "clip_2");
expect(next).toBeDefined();
- expect(getRawVirtualStartTime(next!, rawClips, [])).toBe(20);
+ expect(getRawVirtualStartTime(next!, rawClips)).toBe(20);
expect(next?.sourceStartSec).toBe(10);
});
@@ -484,7 +483,7 @@ describe("virtual-preview pure functions", () => {
// Same moment, but the raw position has not caught up (still reads 10, the start
// of clip_2). The ruler test alone would answer clip_2's FIRST kept segment —
// the stretch already played. The clip-scoped source test carries it past the cut.
- const next = findNextKeptSegment(playbackClips, rawClips, 10, "a1", 7, "clip_2", []);
+ const next = findNextKeptSegment(playbackClips, rawClips, 10, "a1", 7, "clip_2");
expect(next?.sourceStartSec).toBe(10);
});
});
diff --git a/src/lib/ai-edition/timeline/virtual-preview.ts b/src/lib/ai-edition/timeline/virtual-preview.ts
index ba27e8cfb..1cdc5d2f6 100644
--- a/src/lib/ai-edition/timeline/virtual-preview.ts
+++ b/src/lib/ai-edition/timeline/virtual-preview.ts
@@ -1,8 +1,7 @@
// Ported from axcut/apps/web/src/lib/virtual-preview.ts — pure time-mapping
// functions shared by the VirtualPreview component and the timeline math.
-import type { AxcutClip, AxcutInsertRange } from "../schema";
-import { sourceToTimelineSec, timelineToSourceSec } from "./inserted-time";
+import type { AxcutClip } from "../schema";
export type VirtualPosition = {
clip: AxcutClip;
@@ -23,10 +22,6 @@ export function clampVirtualTime(clips: AxcutClip[], value: number): number {
export function locateVirtualPosition(
clips: AxcutClip[],
virtualTimeSec: number,
- /** REQUIRED, not defaulted. A clip carrying insertions is longer than its source window,
- * so a caller that omits these gets an answer that is plausible and wrong by exactly the
- * inserted time, with nothing to catch it (issue #560). */
- insertRanges: readonly AxcutInsertRange[],
): VirtualPosition | null {
if (clips.length === 0) return null;
const clamped = clampVirtualTime(clips, virtualTimeSec);
@@ -37,11 +32,7 @@ export function locateVirtualPosition(
const resolvedIndex = clipIndex >= 0 ? clipIndex : clips.length - 1;
const clip = clips[resolvedIndex];
const clipDuration = (clip.sourceEndSec ?? 0) - clip.sourceStartSec;
- // Inside an insertion there is no source moment — none of those seconds came from the
- // file — so this answers with the one the inserted media follows, which is the frame a
- // decoder should be parked on.
- const { sourceSec } = timelineToSourceSec(clip, clamped, insertRanges);
- const clipOffset = Math.max(0, Math.min(clipDuration, sourceSec - clip.sourceStartSec));
+ const clipOffset = Math.max(0, Math.min(clipDuration, clamped - clip.timelineStartSec));
return {
clip,
clipIndex: resolvedIndex,
@@ -81,22 +72,10 @@ export function findRawClipForSegment(
* Maps a kept segment (`AxcutClip` from `resolvePlaybackSegments`) back to its
* exact start position on the raw (untrimmed) document timeline.
*/
-export function getRawVirtualStartTime(
- segment: AxcutClip,
- rawClips: AxcutClip[],
- /** REQUIRED, not defaulted. A clip carrying insertions is longer than its source window,
- * so a caller that omits these gets an answer that is plausible and wrong by exactly the
- * inserted time, with nothing to catch it (issue #560). */
- insertRanges: readonly AxcutInsertRange[],
-): number {
+export function getRawVirtualStartTime(segment: AxcutClip, rawClips: AxcutClip[]): number {
const rawClip = findRawClipForSegment(segment, rawClips);
if (!rawClip) return segment.timelineStartSec;
- // A HELD segment is the inserted media itself, so it starts where the insertion opens.
- // Every other segment starting at that same source moment is the film RESUMING, so it
- // starts where the insertion closes. Same source second, two different places on the
- // timeline — which is the whole reason an insertion is media and not a marker.
- const edge = (segment as { heldSec?: number }).heldSec !== undefined ? "opens" : "closes";
- return sourceToTimelineSec(rawClip, segment.sourceStartSec, insertRanges, edge);
+ return rawClip.timelineStartSec + (segment.sourceStartSec - rawClip.sourceStartSec);
}
/**
@@ -120,13 +99,12 @@ export function findNextKeptSegment(
playbackClips: AxcutClip[],
rawClips: AxcutClip[],
currentRawTime: number,
- activeSourceId: string | undefined,
- currentSourceTime: number | undefined,
- activeClipId: string | undefined,
- insertRanges: readonly AxcutInsertRange[],
+ activeSourceId?: string,
+ currentSourceTime?: number,
+ activeClipId?: string,
): AxcutClip | undefined {
for (const seg of playbackClips) {
- const segRawStart = getRawVirtualStartTime(seg, rawClips, insertRanges);
+ const segRawStart = getRawVirtualStartTime(seg, rawClips);
if (segRawStart > currentRawTime + 0.001) {
return seg;
}
@@ -148,7 +126,6 @@ function toPositionAt(
clips: AxcutClip[],
clipIndex: number,
sourceTimeSec: number,
- insertRanges: readonly AxcutInsertRange[] = [],
): VirtualPosition {
const clip = clips[clipIndex];
const sourceOffset = Math.max(
@@ -158,9 +135,7 @@ function toPositionAt(
return {
clip,
clipIndex,
- // Not `timelineStartSec + offset`: a clip carrying insertions is longer than its
- // source window, so a moment past one sits that much further along (issue #560).
- virtualTimeSec: sourceToTimelineSec(clip, clip.sourceStartSec + sourceOffset, insertRanges),
+ virtualTimeSec: clip.timelineStartSec + sourceOffset,
sourceTimeSec,
};
}
@@ -195,8 +170,8 @@ function isWithinClipBounds(
export function locateSourcePosition(
clips: AxcutClip[],
sourceTimeSec: number,
- assetId: string | undefined,
- epsilon: number,
+ assetId?: string,
+ epsilon = 0.05,
// When two clips share the same source asset (and possibly overlapping
// source ranges — a duplicated clip, or simply not trimmed yet), scanning
// by (assetId, sourceTime) alone is ambiguous and always resolves to the
@@ -205,11 +180,7 @@ export function locateSourcePosition(
// which clip they're tracking (VirtualPreview, mid-playback) should pass
// its id here so it's preferred whenever the source time still falls
// inside it, before falling back to the ambiguous asset-wide scan.
- preferredClipId: string | undefined,
- /** REQUIRED, not defaulted. A clip carrying insertions is longer than its source window,
- * so a caller that omits these gets an answer that is plausible and wrong by exactly the
- * inserted time, with nothing to catch it (issue #560). */
- insertRanges: readonly AxcutInsertRange[],
+ preferredClipId?: string,
): VirtualPosition | null {
if (preferredClipId) {
const preferredIndex = clips.findIndex((clip) => clip.id === preferredClipId);
@@ -227,7 +198,7 @@ export function locateSourcePosition(
(!assetId || clips[preferredIndex].assetId === assetId) &&
isWithinClipBounds(clips[preferredIndex], sourceTimeSec, epsilon, "inclusive")
) {
- return toPositionAt(clips, preferredIndex, sourceTimeSec, insertRanges);
+ return toPositionAt(clips, preferredIndex, sourceTimeSec);
}
}
const scan = (closingEdge: ClosingEdge) =>
@@ -248,7 +219,7 @@ export function locateSourcePosition(
const strict = scan("exclusive");
const clipIndex = strict >= 0 ? strict : scan("inclusive");
if (clipIndex < 0) return null;
- return toPositionAt(clips, clipIndex, sourceTimeSec, insertRanges);
+ return toPositionAt(clips, clipIndex, sourceTimeSec);
}
/**
@@ -276,12 +247,8 @@ export function locateKeptSegment(
const ownSegments = activeClipId
? playbackClips.filter((seg) => findRawClipForSegment(seg, rawClips)?.id === activeClipId)
: [];
- // The SEGMENTS are already split at every insertion, so within one of them source → its
- // own start is a plain shift again. `[]` here is the honest answer, not a forgotten
- // argument: there is no insertion inside a segment to account for.
- if (ownSegments.length > 0)
- return locateSourcePosition(ownSegments, sourceTimeSec, assetId, 0.05, undefined, []);
- return locateSourcePosition(playbackClips, sourceTimeSec, assetId, 0.05, undefined, []);
+ if (ownSegments.length > 0) return locateSourcePosition(ownSegments, sourceTimeSec, assetId);
+ return locateSourcePosition(playbackClips, sourceTimeSec, assetId);
}
export function keptWordIdSet(clips: AxcutClip[]): Set<string> {
diff --git a/src/lib/ai-edition/timeline/voiceoverCut.test.ts b/src/lib/ai-edition/timeline/voiceoverCut.test.ts
index 701b403ef..7e121be61 100644
--- a/src/lib/ai-edition/timeline/voiceoverCut.test.ts
+++ b/src/lib/ai-edition/timeline/voiceoverCut.test.ts
@@ -84,7 +84,7 @@ describe("a cut authored from the voiceover lane", () => {
// wrote `clipId: "vo"` here and removed nothing at all.
// biome-ignore lint/suspicious/noExplicitAny: fixture, not a schema exercise
const [placement] = voiceoverPlacements([VOICE as any]);
- const rows = cut(placementRawSec(placement, 2, []), placementRawSec(placement, 3, []));
+ const rows = cut(placementRawSec(placement, 2), placementRawSec(placement, 3));
expect(rows).toHaveLength(1);
expect(CLIPS.map((c) => c.id)).toContain(rows[0].clipId);
expect(filmSec([])).toBeCloseTo(12, 6);
@@ -101,7 +101,7 @@ describe("a cut authored from the voiceover lane", () => {
[5, 6],
[20, 21],
]);
- expect(coalescedTrimGroups(rows, CLIPS, [])).toHaveLength(1);
+ expect(coalescedTrimGroups(rows, CLIPS)).toHaveLength(1);
expect(filmSec(rows)).toBeCloseTo(10, 6);
});
@@ -109,7 +109,7 @@ describe("a cut authored from the voiceover lane", () => {
const rows = cut(5, 7);
// Restoring must not leave half the cut behind, with the word still gone and
// nothing on the ruler to click.
- expect(dropTrimPillsByIds(rows, CLIPS, [rows[0].id], [])).toEqual([]);
+ expect(dropTrimPillsByIds(rows, CLIPS, [rows[0].id])).toEqual([]);
});
it("writes nothing where there is no film", () => {
diff --git a/src/lib/ai-edition/transcription/status.test.ts b/src/lib/ai-edition/transcription/status.test.ts
index b37b71ece..d453936bf 100644
--- a/src/lib/ai-edition/transcription/status.test.ts
+++ b/src/lib/ai-edition/transcription/status.test.ts
@@ -274,7 +274,6 @@ function doc(assetIds: string[], clipAssetIds: string[]): AxcutDocument {
})),
gaps: [],
trimRanges: [],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
diff --git a/src/native/contracts.ts b/src/native/contracts.ts
index c2d290387..54c1cc775 100644
--- a/src/native/contracts.ts
+++ b/src/native/contracts.ts
@@ -170,16 +170,6 @@ export interface CompositorClipInput {
* convention). Populated by `buildSceneDescription` and `buildNativeClipList`;
* see the comment on the producer side for the exact rule. */
hasAudio: boolean;
- /** Extra OUTPUT seconds this clip holds its last frame for, silently.
- *
- * A word added to the recording transcript needs somewhere to be spoken, so the film
- * holds a frame and everything after it moves along the ruler (issue #560). The ruler
- * and the preview have honoured that for a while; the EXPORT did not, because a held
- * segment has an empty source window and `walk_composited_timeline` skips those. It is
- * a separate clip carrying this field rather than an adjustment to its predecessor:
- * scene regions are keyed by clip INDEX, so removing an entry from the list would point
- * every region after it at the wrong clip. */
- holdSec: number;
}
/** Bilan d'un export natif (mesure enveloppante §10 : frames, durée, fps). */
diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts
index cda53e559..346c1af3c 100644
--- a/src/native/sceneDescription.test.ts
+++ b/src/native/sceneDescription.test.ts
@@ -84,7 +84,6 @@ function makeDoc(
clips,
gaps: [],
trimRanges: [],
- insertRanges: [],
muteRanges: [],
speedRanges: [],
captionRanges: [],
@@ -1994,72 +1993,6 @@ describe("buildSceneDescription.captions", () => {
});
// --- imported audio tracks (issue #350) ------------------------------------
-// ─── The pause that exported as nothing ─────────────────────────────────────
-// A held segment has an empty source window, and `walk_composited_timeline` skipped every
-// clip shaped like that — so a word added to the recording lengthened the ruler and the
-// preview and produced no frames at all in the exported file (issue #560). The segment now
-// reaches the compositor as its OWN clip carrying `holdSec`, keeping its index so the scene
-// regions after it still point at the right clip.
-
-describe("buildSceneDescription.holdSec", () => {
- it("sends a pause to the compositor as a clip that holds", () => {
- const doc = makeDoc({
- assets: [makeAsset({ id: "scr", kind: "video", originalPath: "/s.mp4", durationSec: 10 })],
- clips: [
- makeClip({
- id: "c1",
- assetId: "scr",
- sourceStartSec: 0,
- sourceEndSec: 10,
- timelineStartSec: 0,
- timelineEndSec: 10,
- }),
- ],
- timeline: {
- insertRanges: [
- {
- id: "i1",
- assetId: "scr",
- atSec: 4,
- durationSec: 1,
- wordId: "w1",
- reason: "",
- origin: "user",
- },
- // biome-ignore lint/suspicious/noExplicitAny: fixture, not a schema exercise
- ] as any,
- },
- });
- const clips = buildSceneDescription(doc).clips;
- const held = clips.filter((c) => c.holdSec > 0);
- expect(held).toHaveLength(1);
- expect(held[0].holdSec).toBeCloseTo(1, 6);
- // Its own entry, in place — not folded onto its predecessor, which would shift every
- // clip index after it and point the scene's per-clip regions at the wrong clip.
- expect(clips).toHaveLength(3);
- expect(clips[1]).toBe(held[0]);
- // An empty source window: it decodes nothing and exists only for its held frames.
- expect(held[0].sourceEndSec).toBeCloseTo(held[0].sourceStartSec, 6);
- });
-
- it("holds nothing on an ordinary clip", () => {
- const doc = makeDoc({
- assets: [makeAsset({ id: "scr", kind: "video", originalPath: "/s.mp4", durationSec: 10 })],
- clips: [
- makeClip({
- id: "c1",
- assetId: "scr",
- sourceStartSec: 0,
- sourceEndSec: 10,
- timelineStartSec: 0,
- timelineEndSec: 10,
- }),
- ],
- });
- expect(buildSceneDescription(doc).clips.every((c) => c.holdSec === 0)).toBe(true);
- });
-});
-
describe("buildSceneDescription.audioTracks", () => {
const audioAsset = makeAsset({
id: "aud",
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index 6ede99478..ce22db0ed 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -41,7 +41,6 @@ import type { AxcutClip, AxcutDocument } from "@/lib/ai-edition/schema";
import { getEditorSettings } from "@/lib/ai-edition/store/editorSettings";
import { assetCameraSource } from "@/lib/ai-edition/timeline/camera";
import { resolveClipSourceEndSec } from "@/lib/ai-edition/timeline/clipDuration";
-import { takeInserts } from "@/lib/ai-edition/timeline/insert-mapping";
import { removedRawSpans } from "@/lib/ai-edition/timeline/programme-time";
import { takeProgramme } from "@/lib/ai-edition/timeline/take-programme";
import { projectRegionsToSource } from "@/lib/ai-edition/timeline/timelineMap";
@@ -520,15 +519,10 @@ function clipAssetIsResolvable(
/**
* Returns `PlaybackSegment[]`, not `AxcutClip[]`: a held segment carries `heldSec`, and
* widening it away here is what kept the pause from ever reaching the compositor. Every
- * caller maps it to `holdSec` on the clip input (issue #560).
*/
export function resolveVisibleClips(document: AxcutDocument): PlaybackSegment[] {
const assetById = new Map(document.assets.map((a) => [a.id, a]));
- return resolvePlaybackSegments(
- document.timeline.clips,
- document.timeline.trimRanges,
- document.timeline.insertRanges,
- )
+ return resolvePlaybackSegments(document.timeline.clips, document.timeline.trimRanges)
.sort((a, b) => a.timelineStartSec - b.timelineStartSec)
.filter((clip) => clipAssetIsResolvable(clip, assetById));
}
@@ -573,9 +567,7 @@ export function buildSceneDescription(
// The one removed set, hoisted out of the map: every voiceover asks it the same
// question, and it does not depend on the track.
// Placed once: the projection below counts them, so a track after a pause lands where
- // the ruler says rather than D seconds early.
- const filmInserts = document.timeline.insertRanges ?? [];
- const removed = removedRawSpans(projectedClips, document.timeline.trimRanges, filmInserts);
+ const removed = removedRawSpans(projectedClips, document.timeline.trimRanges);
// The take's pills, keyed by group. A voiceover is walked ONCE per pill and never per
// stored fragment: the document keeps one fragment per clip a take covers, so walking
// them separately would emit overlapping entries and `overlay_track_pcm` sums with `+=`
@@ -595,7 +587,6 @@ export function buildSceneDescription(
projectedClips,
document.timeline.trimRanges,
track.startMs / 1000,
- filmInserts,
rawSpeedRegions,
);
// Length is measured WITHOUT speed, position WITH it — the two do different
@@ -612,13 +603,11 @@ export function buildSceneDescription(
projectedClips,
document.timeline.trimRanges,
track.endMs / 1000,
- filmInserts,
) -
projectRawTimelineSecToPlayback(
projectedClips,
document.timeline.trimRanges,
track.startMs / 1000,
- filmInserts,
);
const spanSec = trimmedSpanSec;
if (spanSec <= 0) return [];
@@ -654,10 +643,7 @@ export function buildSceneDescription(
// file the take covers, which is the honest fallback once the cuts are taken out.
const voWindowSec =
sourceDurationSec > 0 ? Math.max(0, sourceDurationSec - offsetSec) : rawSpanSec;
- // One walk: the cuts take time away, the take's own insertions add it, and the
- // walk resolves them together so a second insertion lands after the first one's
- // hold rather than inside it.
- const kept = takeProgramme(pill, removed, takeInserts(document, groupId), rawSpeedRegions)
+ const kept = takeProgramme(pill, removed)
.filter((piece) => piece.kind === "play")
.map((piece) => ({
...base,
@@ -665,7 +651,6 @@ export function buildSceneDescription(
projectedClips,
document.timeline.trimRanges,
piece.rawStartSec,
- filmInserts,
rawSpeedRegions,
),
trimStartSec: piece.sourceStartSec,
@@ -731,7 +716,6 @@ export function buildSceneDescription(
hasAudio: true,
// A held segment has an empty source window and exists only for the frames it
// holds; every other clip holds nothing.
- holdSec: clip.heldSec ?? 0,
},
];
});
@@ -777,7 +761,6 @@ export function buildSceneDescription(
visibleClips,
document.timeline.clips,
() => createId("zoom"),
- document.timeline.insertRanges ?? [],
);
// Same raw→source projection as the zoom regions above, for the same reason: annotations are
// authored in RAW document time and the compositor matches each frame's SOURCE time.
@@ -814,7 +797,6 @@ export function buildSceneDescription(
visibleClips,
document.timeline.clips,
() => createId("ann"),
- document.timeline.insertRanges ?? [],
);
const projectedCameraFullscreenRegions = projectRegionsToSource(
((document.legacyEditor as Record<string, unknown> | null)?.cameraFullscreenRegions as
@@ -823,7 +805,6 @@ export function buildSceneDescription(
visibleClips,
document.timeline.clips,
() => createId("camfull"),
- document.timeline.insertRanges ?? [],
);
// Speed regions carry an extra `speed` field the standard `rangeSchema` does not, so we
// can't read from `document.timeline.speedRanges` today (see SceneDescription.speedRegions
@@ -838,7 +819,6 @@ export function buildSceneDescription(
visibleClips,
document.timeline.clips,
() => createId("speed"),
- document.timeline.insertRanges ?? [],
);
// Webcam rect, single source of truth between preview & native :
diff --git a/src/native/useNativePlaybackSync.ts b/src/native/useNativePlaybackSync.ts
index 7263d14a0..64e877b63 100644
--- a/src/native/useNativePlaybackSync.ts
+++ b/src/native/useNativePlaybackSync.ts
@@ -18,7 +18,7 @@
* re-aligns them.
*/
import { useEffect, useMemo, useRef, useSyncExternalStore } from "react";
-import type { AxcutClip, AxcutInsertRange } from "@/lib/ai-edition/schema";
+import type { AxcutClip } from "@/lib/ai-edition/schema";
import { resolveNativePosition } from "@/lib/ai-edition/timeline/timelineMap";
import {
getCurrentNativeViewId,
@@ -34,22 +34,13 @@ export function useNativePlaybackSync(
visibleSegments: readonly AxcutClip[],
/** RAW clip layout (`document.timeline.clips`) `currentTimeSec` is expressed against. */
rawClips: readonly AxcutClip[],
- /** The insertions those clips carry — a clip is longer than its source window by them,
- * so a segment's place on the timeline cannot be found without them (issue #560). */
- insertRanges: readonly AxcutInsertRange[],
): void {
const activePosition = useMemo(
- () => resolveNativePosition(currentTimeSec, [...visibleSegments], [...rawClips], insertRanges),
- [visibleSegments, rawClips, currentTimeSec, insertRanges],
+ () => resolveNativePosition(currentTimeSec, [...visibleSegments], [...rawClips]),
+ [visibleSegments, rawClips, currentTimeSec],
);
const activeClipId = activePosition?.clip.id ?? null;
const sourceTimeSec = activePosition?.sourceTimeSec ?? null;
- // A pause holds ONE frame for its whole length. Free-running the decoder through it
- // would play what comes after instead, and the app clock — which does traverse the
- // pause — would then re-seek on the drift and stutter. Pausing the decoder is what
- // makes the pause a pause; the webcam holds with the screen because both derive
- // from the one asset source clock the pause stops advancing.
- const held = activePosition?.clip.heldSec !== undefined;
// Reactive "is a native view active?" so activation mid-session re-pushes the
// current transport/playhead (time & playing aren't memoised in the store).
@@ -63,8 +54,8 @@ export function useNativePlaybackSync(
if (!active) {
return;
}
- setNativePlaying(playing && !held);
- }, [active, playing, held]);
+ setNativePlaying(playing);
+ }, [active, playing]);
// Scrub/step while paused OR periodic resync during playback when drift > 100ms
const lastSyncedSourceTimeRef = useRef<number | null>(null);
@@ -77,16 +68,6 @@ export function useNativePlaybackSync(
}
const now = performance.now();
- // Inside a pause while playing: the decoder is parked on the held frame (see the
- // transport effect). Refresh the drift refs every run so the check never reads a
- // correctly-frozen source clock as divergence and fights itself with seeks.
- if (playing && held) {
- setNativeTime(sourceTimeSec);
- lastSyncedSourceTimeRef.current = sourceTimeSec;
- lastSyncedWallTimeRef.current = now;
- return;
- }
-
// When clip changes, let setActiveClip handle the atomic clip-switch-and-seek.
if (lastActiveClipIdRef.current !== activeClipId) {
lastActiveClipIdRef.current = activeClipId;
@@ -114,5 +95,5 @@ export function useNativePlaybackSync(
lastSyncedSourceTimeRef.current = sourceTimeSec;
lastSyncedWallTimeRef.current = now;
}
- }, [active, playing, held, activeClipId, sourceTimeSec]);
+ }, [active, playing, activeClipId, sourceTimeSec]);
}