diff --git a/src/core/commands/alias-reference-utils.ts b/src/core/commands/alias-reference-utils.ts index c204302d..3044fe30 100644 --- a/src/core/commands/alias-reference-utils.ts +++ b/src/core/commands/alias-reference-utils.ts @@ -1,5 +1,6 @@ import type { EditDocument } from "@core/edit-document"; -import type { Clip, ResolvedEdit } from "@schemas"; +import { isAliasReference, parseAliasName } from "@core/timing/types"; +import type { Clip, Duck, ResolvedEdit } from "@schemas"; /** * Stores original alias reference values for a clip. @@ -7,6 +8,8 @@ import type { Clip, ResolvedEdit } from "@schemas"; export interface StoredAliasReference { start?: string; length?: string; + /** The clip's original `asset.duck`, before references to removed aliases were pruned. */ + duck?: unknown; } /** @@ -101,6 +104,76 @@ export function convertMultipleAliasReferences( return combined; } +function readDuck(asset: unknown): Duck | undefined { + const duck = (asset as { duck?: Duck } | undefined)?.duck; + return typeof duck?.under === "string" || Array.isArray(duck?.under) ? duck : undefined; +} + +/** + * `duck` without the alias refs that `drop` names, keeping the shape of `under`. + * Null when no refs remain; undefined when none were dropped. + */ +function trimDuck(duck: Duck, drop: (aliasName: string) => boolean): Duck | null | undefined { + const refs = [duck.under].flat(); + const kept = refs.filter(ref => !(isAliasReference(ref) && drop(parseAliasName(ref)))); + if (kept.length === refs.length) return undefined; + if (kept.length === 0) return null; + return { ...duck, under: typeof duck.under === "string" ? kept[0] : kept }; +} + +function withDuck(asset: object, duck: unknown): object { + const next: { duck?: unknown } = { ...asset }; + if (duck) next.duck = duck; + else delete next.duck; + return next; +} + +/** + * Remove references to deleted aliases from every clip's `asset.duck.under`, dropping + * `duck` when none remain. + * + * @param document - The edit document + * @param removedAliases - Names of the aliases being removed (e.g., "voice" for "alias://voice") + * @param stored - Map to record each pruned clip's original `duck` in, for undo + * @param skipClipIndices - Optional set of "trackIdx:clipIdx" to skip (the clips being deleted) + */ +export function pruneDuckReferences( + document: EditDocument, + removedAliases: Set, + stored: AliasReferenceMap, + skipClipIndices?: Set +): void { + for (let t = 0; t < document.getTrackCount(); t += 1) { + const clips = document.getClipsInTrack(t); + for (let c = 0; c < clips.length; c += 1) { + const clip = clips[c]; + const clipId = (clip as { id?: string }).id; + const duck = readDuck(clip.asset); + + if (clipId && duck && !skipClipIndices?.has(`${t}:${c}`)) { + const pruned = trimDuck(duck, name => removedAliases.has(name)); + if (pruned !== undefined) { + const existing = stored.get(clipId); + stored.set(clipId, { ...existing, duck: structuredClone(duck) }); + document.updateClip(t, c, { asset: withDuck(clip.asset, pruned) as Clip["asset"] }); + } + } + } + } +} + +/** + * Remove references to aliases that `knownAliases` lacks from a pasted clip's + * `asset.duck.under`, dropping `duck` when none remain. Edits `clip` in place. + */ +export function pruneMissingDuckReferences(clip: Clip, knownAliases: Set): void { + const duck = readDuck(clip.asset); + const pruned = duck ? trimDuck(duck, name => !knownAliases.has(name)) : undefined; + if (pruned === undefined) return; + + Object.assign(clip, { asset: withDuck(clip.asset, pruned) }); +} + /** * Restore original alias references after undoing deletion. * @@ -114,6 +187,7 @@ export function restoreAliasReferences(document: EditDocument, convertedReferenc const updates: Partial = {}; if (original.start) updates.start = original.start; if (original.length) updates.length = original.length; + if (original.duck) updates.asset = withDuck(clipInfo.clip.asset, original.duck) as Clip["asset"]; document.updateClip(clipInfo.trackIndex, clipInfo.clipIndex, updates); } } @@ -135,3 +209,8 @@ export function extractAliasNames(clips: Clip[]): string[] { } return aliases; } + +/** Names of every alias defined in the document. */ +export function documentAliasNames(document: EditDocument | null): Set { + return new Set(document?.getTracks().flatMap(track => extractAliasNames(track.clips))); +} diff --git a/src/core/commands/delete-clip-command.ts b/src/core/commands/delete-clip-command.ts index 1c95c971..eb293c00 100644 --- a/src/core/commands/delete-clip-command.ts +++ b/src/core/commands/delete-clip-command.ts @@ -2,7 +2,7 @@ import type { MergeFieldBinding } from "@core/edit-document"; import { EditEvent } from "@core/events/edit-events"; import type { Clip } from "@schemas"; -import { type AliasReferenceMap, convertAliasReferencesToValues, restoreAliasReferences } from "./alias-reference-utils"; +import { type AliasReferenceMap, convertAliasReferencesToValues, pruneDuckReferences, restoreAliasReferences } from "./alias-reference-utils"; import { DeleteTrackCommand } from "./delete-track-command"; import { type EditCommand, type CommandContext, type CommandResult, CommandSuccess, CommandNoop } from "./types"; @@ -55,6 +55,7 @@ export class DeleteClipCommand implements EditCommand { if (clipAlias) { const skipIndices = new Set([`${this.trackIdx}:${this.clipIdx}`]); this.convertedReferences = convertAliasReferencesToValues(document, context.getEditState(), clipAlias, skipIndices); + pruneDuckReferences(document, new Set([clipAlias]), this.convertedReferences, skipIndices); } // Clear any error associated with this clip before deletion diff --git a/src/core/commands/delete-track-command.ts b/src/core/commands/delete-track-command.ts index 35e860b9..24d7ae1e 100644 --- a/src/core/commands/delete-track-command.ts +++ b/src/core/commands/delete-track-command.ts @@ -1,7 +1,13 @@ import { EditEvent } from "@core/events/edit-events"; import type { Clip } from "@schemas"; -import { type AliasReferenceMap, convertMultipleAliasReferences, extractAliasNames, restoreAliasReferences } from "./alias-reference-utils"; +import { + type AliasReferenceMap, + convertMultipleAliasReferences, + extractAliasNames, + pruneDuckReferences, + restoreAliasReferences +} from "./alias-reference-utils"; import { type EditCommand, type CommandContext, type CommandResult, CommandSuccess, CommandNoop } from "./types"; /** @@ -39,6 +45,7 @@ export class DeleteTrackCommand implements EditCommand { skipIndices.add(`${this.trackIdx}:${c}`); } this.convertedReferences = convertMultipleAliasReferences(document, context.getEditState(), aliasNames, skipIndices); + pruneDuckReferences(document, new Set(aliasNames), this.convertedReferences, skipIndices); } // Document mutation - remove track (and all its clips) diff --git a/src/core/edit-session.ts b/src/core/edit-session.ts index 3d81519a..20bcc56c 100644 --- a/src/core/edit-session.ts +++ b/src/core/edit-session.ts @@ -10,6 +10,7 @@ import { parseSvgIntrinsicSize, sanitiseSvg } from "@core/clipboard/svg-clipboar import { AddClipCommand } from "@core/commands/add-clip-command"; import { AddTrackCommand } from "@core/commands/add-track-command"; import { AddTracksCommand } from "@core/commands/add-tracks-command"; +import { documentAliasNames, pruneMissingDuckReferences } from "@core/commands/alias-reference-utils"; import { DeleteClipCommand } from "@core/commands/delete-clip-command"; import { DeleteTrackCommand } from "@core/commands/delete-track-command"; import { MoveClipCommand } from "@core/commands/move-clip-command"; @@ -870,6 +871,7 @@ export class Edit { } remintPastedClipIdentity(parsed as { id?: string; alias?: string }); + pruneMissingDuckReferences(parsed, documentAliasNames(this.document)); const asset = parsed.asset as { type?: string; src?: string } | undefined; if (asset?.type === "svg" && typeof asset.src === "string") { @@ -910,11 +912,13 @@ export class Edit { const anchor = (opts.start ?? this.playbackTime) as number; const offset = anchor - minStart; + const knownAliases = documentAliasNames(this.document); const prepared: Track[] = tracks.map(track => ({ ...track, clips: track.clips.map(clip => { const cloned = structuredClone(clip) as Clip; remintPastedClipIdentity(cloned as { id?: string; alias?: string }); + pruneMissingDuckReferences(cloned, knownAliases); const asset = cloned.asset as { type?: string; src?: string } | undefined; if (asset?.type === "svg" && typeof asset.src === "string") { asset.src = sanitiseSvg(asset.src); diff --git a/src/core/schemas/index.ts b/src/core/schemas/index.ts index ac339e8d..f821c599 100644 --- a/src/core/schemas/index.ts +++ b/src/core/schemas/index.ts @@ -56,6 +56,7 @@ export type Font = components["schemas"]["Font"]; // Asset types export type VideoAsset = components["schemas"]["VideoAsset"]; export type AudioAsset = components["schemas"]["AudioAsset"]; +export type Duck = components["schemas"]["Duck"]; export type ImageAsset = components["schemas"]["ImageAsset"]; export type TextAsset = components["schemas"]["TextAsset"]; export type RichTextAsset = components["schemas"]["RichTextAsset"]; diff --git a/src/core/selection-manager.ts b/src/core/selection-manager.ts index 143de192..ff6ec65a 100644 --- a/src/core/selection-manager.ts +++ b/src/core/selection-manager.ts @@ -8,6 +8,7 @@ import { clipToJsonString } from "@core/clipboard/clip-json"; import { insertClipWithOverlapPolicy } from "@core/clipboard/paste-dispatcher"; import { remintPastedClipIdentity } from "@core/clipboard/remint-pasted-alias"; import { writeSystemClipboardText } from "@core/clipboard/system-clipboard"; +import { documentAliasNames, pruneMissingDuckReferences } from "@core/commands/alias-reference-utils"; import { EditEvent } from "@core/events/edit-events"; import type { ResolvedClip, Clip } from "@core/schemas"; import { stripInternalProperties } from "@core/shared/clip-utils"; @@ -153,6 +154,7 @@ export class SelectionManager { pastedClip.start = this.edit.playbackTime as Seconds; remintPastedClipIdentity(pastedClip as { id?: string; alias?: string }); + pruneMissingDuckReferences(pastedClip, documentAliasNames(this.edit.getDocument())); return insertClipWithOverlapPolicy(this.edit, this.copiedClip.trackIndex, pastedClip); } diff --git a/tests/edit-clip-operations.test.ts b/tests/edit-clip-operations.test.ts index ee0323c1..153fc9da 100644 --- a/tests/edit-clip-operations.test.ts +++ b/tests/edit-clip-operations.test.ts @@ -11,6 +11,8 @@ import { * These are the core editing operations that modify timeline content. */ +import { DuckLevelService } from "@core/audio/duck-levels"; +import { restoreAliasReferences } from "@core/commands/alias-reference-utils"; import { Edit } from "@core/edit-session"; import { ShotstackEdit } from "@core/shotstack-edit"; import { EditEvent, InternalEvent } from "@core/events/edit-events"; @@ -2072,3 +2074,232 @@ describe("Edit Clip Operations", () => { }); }); }); + +// A ducking clip's `duck.under` must only name aliases that exist. Deleting the clips it ducks under, or pasting it +// somewhere they are missing, has to prune those references, and undo has to put the original `duck` back. +describe("duck references", () => { + const VOICE = "https://example.com/voice.mp3"; + const PASTED = "https://example.com/pasted.mp3"; + + const audio = (src: string, extra: Record = {}) => ({ type: "audio" as const, src, ...extra }); + const image = (start: number): Clip => ({ asset: { type: "image", src: "https://example.com/i.jpg" }, start, length: 1 }) as Clip; + const voice = (alias: string, src = VOICE): Clip => ({ alias, asset: audio(src), start: 0, length: 5 }) as Clip; + const bed = (src: string, duck: unknown, start: number | string = 0): Clip => + ({ asset: audio(src, { volume: 0.8, duck }), start, length: 10 }) as Clip; + + let edit: Edit; + + async function load(...tracks: Clip[][]): Promise { + edit = new Edit({ + timeline: { tracks: tracks.map(clips => ({ clips })) }, + output: { size: { width: 1920, height: 1080 }, format: "mp4" } + }); + await edit.load(); + } + + /** The document's clips, which is the model the server validates. */ + const docClips = (): Clip[] => + edit + .getDocument()! + .getTimeline() + .tracks.flatMap(track => track.clips); + const byAsset = (src: string): Clip => docClips().find(clip => (clip.asset as { src?: string }).src === src)!; + const duckOf = (src: string): unknown => (byAsset(src).asset as { duck?: unknown }).duck; + + beforeEach(() => { + // The level service would try to fetch and decode the example URLs. + jest.spyOn(DuckLevelService.prototype, "refresh").mockImplementation(() => undefined); + }); + + afterEach(() => { + edit.dispose(); + jest.restoreAllMocks(); + }); + + describe("deleting clips that are ducked under", () => { + // Track 0 keeps an image so deleting the voice leaves the track, and the edit, alive. + const MUSIC_A = "https://example.com/a.mp3"; + const MUSIC_B = "https://example.com/b.mp3"; + + it("removes the deleted alias from every duck.under", async () => { + await load( + [voice("voice"), image(5)], + [bed(MUSIC_A, { under: ["alias://voice", "alias://other"] })], + [bed(MUSIC_B, { under: ["alias://other", "alias://voice"], volume: 0.2 })], + [voice("other", "https://example.com/other.mp3")] + ); + + await edit.deleteClip(0, 0); + + expect(duckOf(MUSIC_A)).toEqual({ under: ["alias://other"] }); + expect(duckOf(MUSIC_B)).toEqual({ under: ["alias://other"], volume: 0.2 }); + }); + + it("drops duck when the last reference goes", async () => { + await load([voice("voice"), image(5)], [bed(MUSIC_A, { under: "alias://voice", volume: 0.2 })]); + + await edit.deleteClip(0, 0); + + const { asset } = byAsset(MUSIC_A); + expect("duck" in asset).toBe(false); + expect(asset).toMatchObject({ type: "audio", src: MUSIC_A, volume: 0.8 }); + }); + + it("undo restores the whole duck object", async () => { + const kept = { under: ["alias://voice", "alias://other"], volume: 0.2 }; + const dropped = { under: "alias://voice", volume: 0.3 }; + await load([voice("voice"), image(5)], [bed(MUSIC_A, kept)], [bed(MUSIC_B, dropped)], [voice("other", "https://example.com/other.mp3")]); + + await edit.deleteClip(0, 0); + expect(duckOf(MUSIC_A)).toEqual({ under: ["alias://other"], volume: 0.2 }); + expect(duckOf(MUSIC_B)).toBeUndefined(); + + await edit.undo(); + + expect(duckOf(MUSIC_A)).toEqual(kept); + expect(duckOf(MUSIC_B)).toEqual(dropped); + }); + + it("undo restores a bed that starts with its voice exactly", async () => { + await load([voice("voice"), image(5)], [bed(MUSIC_A, { under: "alias://voice", volume: 0.2 }, "alias://voice")]); + const before = structuredClone(byAsset(MUSIC_A)); + + await edit.deleteClip(0, 0); + expect(byAsset(MUSIC_A).start).toBe(0); + expect(duckOf(MUSIC_A)).toBeUndefined(); + + await edit.undo(); + + expect(byAsset(MUSIC_A)).toEqual(before); + }); + + it("leaves ducking clips that do not name the deleted alias alone", async () => { + await load([voice("voice"), image(5)], [bed(MUSIC_A, { under: "alias://other" })], [voice("other", "https://example.com/other.mp3")]); + + await edit.deleteClip(0, 0); + + expect(duckOf(MUSIC_A)).toEqual({ under: "alias://other" }); + }); + }); + + describe("restoreAliasReferences", () => { + it("gives the document its own copy of the stored duck", async () => { + await load([voice("voice"), image(5)], [bed("https://example.com/a.mp3", { under: "alias://voice" })]); + const document = edit.getDocument()!; + const bedId = (document.getClip(1, 0) as { id: string }).id; + const duck = { under: ["alias://voice", "alias://other"], volume: 0.3 }; + + restoreAliasReferences(document, new Map([[bedId, { duck }]])); + + const restored = (document.getClip(1, 0)!.asset as { duck?: unknown }).duck; + expect(restored).toEqual(duck); + expect(restored).not.toBe(duck); + expect((restored as typeof duck).under).not.toBe(duck.under); + }); + }); + + describe("deleting a track", () => { + const MUSIC = "https://example.com/music.mp3"; + const OUTSIDE_BED = "https://example.com/outside.mp3"; + const OTHER_VOICE = "https://example.com/other.mp3"; + + it("removes the references to both of its referenced clips", async () => { + await load( + [voice("voice")], + [voice("narrator", OTHER_VOICE), voice("host", "https://example.com/host.mp3")], + [bed(MUSIC, { under: ["alias://voice", "alias://narrator", "alias://host"] })] + ); + + await edit.deleteTrack(1); + + expect(duckOf(MUSIC)).toEqual({ under: ["alias://voice"] }); + }); + + it("restores the references when the deletion is undone", async () => { + const duck = { under: ["alias://voice", "alias://narrator", "alias://host"], volume: 0.25 }; + await load([voice("voice")], [voice("narrator", OTHER_VOICE), voice("host", "https://example.com/host.mp3")], [bed(MUSIC, duck)]); + + await edit.deleteTrack(1); + await edit.undo(); + + expect(duckOf(MUSIC)).toEqual(duck); + }); + + it("restores both clips exactly when the track holds the voice and the bed ducking under it", async () => { + await load( + [image(0)], + [voice("voice"), bed(MUSIC, { under: "alias://voice", volume: 0.2 }, 5)], + [bed(OUTSIDE_BED, { under: "alias://voice" })] + ); + const before = structuredClone(edit.getDocument()!.getTimeline()); + + await edit.deleteTrack(1); + expect(duckOf(OUTSIDE_BED)).toBeUndefined(); + + await edit.undo(); + + expect(edit.getDocument()!.getTimeline()).toEqual(before); + }); + }); + + describe("pasting a ducking clip", () => { + const UNKNOWN = { under: ["alias://voice", "alias://gone"], volume: 0.2 }; + + it("pasteClip drops references to aliases the edit no longer has", async () => { + await load( + [voice("voice"), image(5)], + [bed(PASTED, { under: ["alias://voice", "alias://other"], volume: 0.2 })], + [voice("other", "https://example.com/o.mp3")] + ); + edit.copyClip(1, 0); + await edit.deleteClip(2, 0); + + await edit.pasteClip(); + + const pasted = docClips().filter(clip => (clip.asset as { src?: string }).src === PASTED); + expect(pasted).toHaveLength(2); + // Both the original (pruned by the delete) and the copy (pruned on paste) end up the same. + expect(pasted.map(clip => (clip.asset as { duck?: unknown }).duck)).toEqual([ + { under: ["alias://voice"], volume: 0.2 }, + { under: ["alias://voice"], volume: 0.2 } + ]); + }); + + it("pasteClip drops duck when none of its targets remain", async () => { + await load([voice("voice"), image(5)], [bed(PASTED, { under: "alias://voice" })]); + edit.copyClip(1, 0); + await edit.deleteClip(0, 0); + + await edit.pasteClip(); + + const pasted = docClips().filter(clip => (clip.asset as { src?: string }).src === PASTED); + expect(pasted).toHaveLength(2); + expect(pasted.map(clip => "duck" in clip.asset)).toEqual([false, false]); + }); + + it("addClipFromJson keeps the references whose targets exist and drops the rest", async () => { + await load([voice("voice"), image(5)]); + + await edit.addClipFromJson(bed(PASTED, UNKNOWN)); + + expect(duckOf(PASTED)).toEqual({ under: ["alias://voice"], volume: 0.2 }); + }); + + it("addClipFromJson drops duck when none of its targets exist", async () => { + await load([voice("voice"), image(5)]); + + await edit.addClipFromJson(JSON.stringify(bed(PASTED, { under: "alias://gone", volume: 0.2 }))); + + expect("duck" in byAsset(PASTED).asset).toBe(false); + }); + + it("addTracksFromJson prunes every clip in the pasted tracks", async () => { + await load([voice("voice"), image(5)]); + + await edit.addTracksFromJson([{ clips: [bed(PASTED, UNKNOWN)] }, { clips: [bed("https://example.com/b.mp3", { under: "alias://gone" })] }]); + + expect(duckOf(PASTED)).toEqual({ under: ["alias://voice"], volume: 0.2 }); + expect("duck" in byAsset("https://example.com/b.mp3").asset).toBe(false); + }); + }); +});