Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(editor): add source-timed caption derivation utilities

Richie McIlroyb421fe5231cb
diff --git a/apps/desktop/src/routes/editor/captions.ts b/apps/desktop/src/routes/editor/captions.ts
index 314130146..f398ac212 100644
--- a/apps/desktop/src/routes/editor/captions.ts
+++ b/apps/desktop/src/routes/editor/captions.ts
@@ -110,12 +110,24 @@ function mapTimeRangeWithinMapping(
};
}
+const CAPTION_EDL_SEPARATOR = "::edl";
+
function mappedCaptionSegmentId(
baseId: string,
index: number,
total: number,
): string {
- return total === 1 ? baseId : `${baseId}-${index}`;
+ return total === 1 ? baseId : `${baseId}${CAPTION_EDL_SEPARATOR}${index}`;
+}
+
+/**
+ * Recovers the originating source caption id from a derived track segment id. A
+ * single source caption can be split into several track segments when it spans
+ * timeline cuts; they all share the same source id.
+ */
+export function sourceCaptionId(trackId: string): string {
+ const index = trackId.indexOf(CAPTION_EDL_SEPARATOR);
+ return index === -1 ? trackId : trackId.slice(0, index);
}
export function mapCaptionsToEditedTimeline(
@@ -221,6 +233,149 @@ export function createCaptionTrackSegments(
}));
}
+type CaptionTrackOverrides = Pick<
+ CaptionTrackSegment,
+ | "fadeDurationOverride"
+ | "lingerDurationOverride"
+ | "positionOverride"
+ | "colorOverride"
+ | "backgroundColorOverride"
+ | "fontSizeOverride"
+>;
+
+const EMPTY_CAPTION_OVERRIDES: CaptionTrackOverrides = {
+ fadeDurationOverride: null,
+ lingerDurationOverride: null,
+ positionOverride: null,
+ colorOverride: null,
+ backgroundColorOverride: null,
+ fontSizeOverride: null,
+};
+
+/**
+ * Projects the source-time caption master through the current edit list to
+ * produce the output-time render track. This is the single source of truth for
+ * `timeline.captionSegments`: deleting sections, trimming, reordering, or
+ * inserting clips keeps captions aligned 1:1 without re-transcription. Per
+ * source-caption style overrides are carried across by source id so manual
+ * styling survives re-derivation.
+ */
+export function deriveCaptionTrackSegments(
+ sourceSegments: CaptionSegment[],
+ timelineSegments: TimelineSegment[],
+ recordingSegments: SegmentRecordings[],
+ previousTrack: CaptionTrackSegment[] = [],
+): CaptionTrackSegment[] {
+ const overridesBySourceId = new Map<string, CaptionTrackOverrides>();
+ for (const segment of previousTrack) {
+ const id = sourceCaptionId(segment.id);
+ if (!overridesBySourceId.has(id)) {
+ overridesBySourceId.set(id, {
+ fadeDurationOverride: segment.fadeDurationOverride ?? null,
+ lingerDurationOverride: segment.lingerDurationOverride ?? null,
+ positionOverride: segment.positionOverride ?? null,
+ colorOverride: segment.colorOverride ?? null,
+ backgroundColorOverride: segment.backgroundColorOverride ?? null,
+ fontSizeOverride: segment.fontSizeOverride ?? null,
+ });
+ }
+ }
+
+ const mapped = mapCaptionsToEditedTimeline(
+ sourceSegments,
+ timelineSegments,
+ recordingSegments,
+ );
+
+ return mapped
+ .slice()
+ .sort((a, b) => a.start - b.start)
+ .map((segment) => ({
+ id: segment.id,
+ start: segment.start,
+ end: segment.end,
+ text: segment.text,
+ words: segment.words ?? [],
+ ...(overridesBySourceId.get(sourceCaptionId(segment.id)) ??
+ EMPTY_CAPTION_OVERRIDES),
+ }));
+}
+
+/**
+ * Maps a point in source/recording time to the first output-time position where
+ * it appears in the edited timeline (used to seek from the transcript).
+ */
+export function mapSourceTimeToEdited(
+ sourceTime: number,
+ timelineSegments: TimelineSegment[],
+ recordingSegments: SegmentRecordings[],
+): number | null {
+ const mappings = buildSourceToEditedMappings(
+ timelineSegments,
+ recordingSegments,
+ );
+ for (const mapping of mappings) {
+ if (sourceTime >= mapping.sourceStart && sourceTime <= mapping.sourceEnd) {
+ return (
+ mapping.editedStart +
+ (sourceTime - mapping.sourceStart) / mapping.timescale
+ );
+ }
+ }
+ return null;
+}
+
+/**
+ * Maps a source/recording time range to the output-time ranges it occupies in
+ * the edited timeline. A single source range can map to zero ranges (fully cut)
+ * or several (split across non-contiguous clips).
+ */
+export function mapSourceRangeToEdited(
+ sourceStart: number,
+ sourceEnd: number,
+ timelineSegments: TimelineSegment[],
+ recordingSegments: SegmentRecordings[],
+): MappedTimeRange[] {
+ const mappings = buildSourceToEditedMappings(
+ timelineSegments,
+ recordingSegments,
+ );
+ const ranges: MappedTimeRange[] = [];
+ for (const mapping of mappings) {
+ const mapped = mapTimeRangeWithinMapping(sourceStart, sourceEnd, mapping);
+ if (mapped) ranges.push(mapped);
+ }
+ return ranges;
+}
+
+/**
+ * Maps a point in output/edited time back to source/recording time (used to
+ * translate edits made against the rendered timeline onto the source caption
+ * master).
+ */
+export function mapEditedTimeToSource(
+ editedTime: number,
+ timelineSegments: TimelineSegment[],
+ recordingSegments: SegmentRecordings[],
+): number | null {
+ const mappings = buildSourceToEditedMappings(
+ timelineSegments,
+ recordingSegments,
+ );
+ for (const mapping of mappings) {
+ const editedEnd =
+ mapping.editedStart +
+ (mapping.sourceEnd - mapping.sourceStart) / mapping.timescale;
+ if (editedTime >= mapping.editedStart && editedTime <= editedEnd) {
+ return (
+ mapping.sourceStart +
+ (editedTime - mapping.editedStart) * mapping.timescale
+ );
+ }
+ }
+ return null;
+}
+
export function applyCaptionResultToProject<
T extends {
captions?:
@@ -267,14 +422,14 @@ export function applyCaptionResultToProject<
}
const timeline = currentProject.timeline;
- const mappedSegments = mapCaptionsToEditedTimeline(
+ captions.segments = rawSegments;
+ captions.sourceTimed = true;
+ timeline.captionSegments = deriveCaptionTrackSegments(
rawSegments,
timeline.segments,
recordingSegments,
+ timeline.captionSegments ?? [],
);
-
- captions.segments = mappedSegments;
- timeline.captionSegments = createCaptionTrackSegments(mappedSegments);
}
export async function getModelPath(modelName: string): Promise<string> {
@@ -452,13 +607,13 @@ if (import.meta.vitest) {
expect(result).toHaveLength(2);
expect(result[0]).toEqual({
- id: "caption-0",
+ id: "caption::edl0",
start: 0.4,
end: 0.6,
text: "hello",
words: [{ text: "hello", start: 0.4, end: 0.6 }],
});
- expect(result[1]?.id).toBe("caption-1");
+ expect(result[1]?.id).toBe("caption::edl1");
expect(result[1]?.text).toBe("world");
expect(result[1]?.start).toBeCloseTo(1.1);
expect(result[1]?.end).toBeCloseTo(1.3);
@@ -487,14 +642,14 @@ if (import.meta.vitest) {
expect(result).toEqual([
{
- id: "caption-0",
+ id: "caption::edl0",
start: 0.25,
end: 1,
text: "hello world",
words: [],
},
{
- id: "caption-1",
+ id: "caption::edl1",
start: 1,
end: 1.5,
text: "hello world",
@@ -503,4 +658,76 @@ if (import.meta.vitest) {
]);
});
});
+
+ describe("deriveCaptionTrackSegments", () => {
+ const sourceSegments: CaptionSegment[] = [
+ {
+ id: "capA",
+ start: 1,
+ end: 2,
+ text: "a",
+ words: [{ text: "a", start: 1, end: 2 }],
+ },
+ {
+ id: "capB",
+ start: 6,
+ end: 7,
+ text: "b",
+ words: [{ text: "b", start: 6, end: 7 }],
+ },
+ ];
+ const recordings = [{ display: { duration: 10 } } as SegmentRecordings];
+
+ it("follows clip reordering to keep captions on their content", () => {
+ const reordered: TimelineSegment[] = [
+ { start: 5, end: 8, timescale: 1, recordingSegment: 0 },
+ { start: 0, end: 3, timescale: 1, recordingSegment: 0 },
+ ];
+
+ const track = deriveCaptionTrackSegments(
+ sourceSegments,
+ reordered,
+ recordings,
+ );
+
+ expect(track.map((s) => s.id)).toEqual(["capB", "capA"]);
+ expect(track[0]?.start).toBeCloseTo(1);
+ expect(track[0]?.end).toBeCloseTo(2);
+ expect(track[1]?.start).toBeCloseTo(4);
+ expect(track[1]?.end).toBeCloseTo(5);
+ });
+
+ it("drops captions whose content was cut out", () => {
+ const cut: TimelineSegment[] = [
+ { start: 0, end: 3, timescale: 1, recordingSegment: 0 },
+ ];
+
+ const track = deriveCaptionTrackSegments(sourceSegments, cut, recordings);
+
+ expect(track.map((s) => s.id)).toEqual(["capA"]);
+ });
+
+ it("carries style overrides across re-derivation by source id", () => {
+ const identity: TimelineSegment[] = [
+ { start: 0, end: 10, timescale: 1, recordingSegment: 0 },
+ ];
+
+ const previous = deriveCaptionTrackSegments(
+ sourceSegments,
+ identity,
+ recordings,
+ ).map((segment) =>
+ segment.id === "capA" ? { ...segment, fontSizeOverride: 42 } : segment,
+ );
+
+ const rederived = deriveCaptionTrackSegments(
+ sourceSegments,
+ identity,
+ recordings,
+ previous,
+ );
+
+ expect(rederived.find((s) => s.id === "capA")?.fontSizeOverride).toBe(42);
+ });
+ });
}