diff --git a/src/components/canvas/players/audio-player.ts b/src/components/canvas/players/audio-player.ts index a01df824..296cb933 100644 --- a/src/components/canvas/players/audio-player.ts +++ b/src/components/canvas/players/audio-player.ts @@ -1,8 +1,10 @@ import { KeyframeBuilder } from "@animations/keyframe-builder"; import type { Edit } from "@core/edit-session"; +import { InternalEvent } from "@core/events/edit-events"; import { type Size } from "@layouts/geometry"; import { AudioLoadParser } from "@loaders/audio-load-parser"; import { type AudioAsset, type ResolvedClip, type Keyframe } from "@schemas"; +import { duckedVolumeFor, scanDucking } from "@shotstack/shotstack-canvas/duck"; import * as howler from "howler"; import * as pixi from "pixi.js"; @@ -13,6 +15,8 @@ export class AudioPlayer extends Player { private isPlaying: boolean; private volumeKeyframeBuilder: KeyframeBuilder | undefined; + private effectiveVolume: Keyframe[] | number = 1; + private disposed = false; private syncTimer: number; @@ -51,6 +55,12 @@ export class AudioPlayer extends Player { this.audioResource.volume(this.getVolume()); this.configureKeyframes(); + + // dispose() can run during the awaits above; subscribing after it would never be undone. + if (this.disposed) return; + const events = this.edit.getInternalEvents(); + events.on(InternalEvent.Resolved, this.rebuildDuckedVolume); + events.on(InternalEvent.DuckLevelsChanged, this.rebuildDuckedVolume); } public override update(deltaTime: number, elapsed: number): void { @@ -111,6 +121,11 @@ export class AudioPlayer extends Player { } public override dispose(): void { + this.disposed = true; + const events = this.edit.getInternalEvents(); + events.off(InternalEvent.Resolved, this.rebuildDuckedVolume); + events.off(InternalEvent.DuckLevelsChanged, this.rebuildDuckedVolume); + if (this.audioResource) { this.audioResource.stop(); this.audioResource.unload(); @@ -167,6 +182,11 @@ export class AudioPlayer extends Player { return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime()); } + /** The volume the keyframes were built from, clip-local, with any fade or dips already applied. */ + public getEffectiveVolume(): Keyframe[] | number { + return this.effectiveVolume; + } + public override getSourceDuration(): number | null { const duration = this.audioResource?.duration(); return typeof duration === "number" && duration > 0 ? duration : null; @@ -183,15 +203,28 @@ export class AudioPlayer extends Player { return typeof audioAsset.volume === "number" ? audioAsset.volume : 1; } + // A clip's dips follow the clips it ducks under, which can move without this clip changing. + private readonly rebuildDuckedVolume = (): void => { + if ((this.clipConfiguration.asset as AudioAsset).duck) this.rebuildVolumeKeyframeBuilder(); + }; + private rebuildVolumeKeyframeBuilder(): void { const audioAsset = this.clipConfiguration.asset as AudioAsset; const baseVolume = this.getBaseVolume(); - this.volumeKeyframeBuilder = new KeyframeBuilder(this.createVolumeKeyframes(audioAsset, baseVolume)); + this.effectiveVolume = this.createVolumeKeyframes(audioAsset, baseVolume); + this.volumeKeyframeBuilder = new KeyframeBuilder(this.effectiveVolume); } private createVolumeKeyframes(asset: AudioAsset, baseVolume: number): Keyframe[] | number { const { effect, volume } = asset; + if (asset.duck) { + const resolved = this.edit.getResolvedEdit(); + const clip = resolved.timeline.tracks.flatMap(track => track.clips).find(({ id }) => id === this.clipId) ?? this.clipConfiguration; + // The dips already carry the asset's fade. + return duckedVolumeFor(clip, scanDucking(resolved).aliases, this.edit.getDuckLevels().levelsFor(clip.id)); + } + if (!effect || effect === "none" || Array.isArray(volume)) { return volume ?? 1; } diff --git a/src/core/audio/duck-levels.ts b/src/core/audio/duck-levels.ts new file mode 100644 index 00000000..4c03bbfb --- /dev/null +++ b/src/core/audio/duck-levels.ts @@ -0,0 +1,112 @@ +import { InternalEvent, type InternalEventMap } from "@core/events/edit-events"; +import type { EventEmitter } from "@core/events/event-emitter"; +import type { ResolvedClip, ResolvedEdit } from "@schemas"; +import { + duckLevel, + integratedLoudness, + planDuckMeasurements, + scanDucking, + type DuckMeasurement, + type LoudnessWindow +} from "@shotstack/shotstack-canvas/duck"; + +import { decodeLoudnessBlocks } from "./loudness"; + +// `URL.canParse` needs Chrome 120, Safari 17 or Firefox 115. +function isUrl(src: string): boolean { + try { + return Boolean(new URL(src)); + } catch { + return false; + } +} + +/** Each ducking clip's dip levels, measured from its files' loudness the way the server render measures them. */ +export class DuckLevelService { + // Kept for the session's lifetime, failures included, so a file is fetched at most once. + private readonly blocks = new Map(); + private readonly requested = new Set(); + private readonly batches = new Set>(); + private plans: Array<[clipId: string, measurements: DuckMeasurement[]]> = []; + private levels = new Map>(); + private levelsKey = "[]"; + private disposed = false; + + constructor( + private readonly events: EventEmitter, + private readonly decode: typeof decodeLoudnessBlocks = decodeLoudnessBlocks + ) {} + + public refresh(resolved: ResolvedEdit): void { + const { aliases, ducking } = scanDucking(resolved); + this.plans = ducking.map(({ clip }) => [(clip as ResolvedClip).id, planDuckMeasurements(clip, aliases)]); + + // A merge field still waiting for its value is not a URL yet, so there is nothing to fetch. + const sources = this.plans + .flatMap(([, measurements]) => measurements) + .filter(({ speech, bed }) => isUrl(speech.src) && isUrl(bed.src)) + .flatMap(({ speech, bed }) => [speech.src, bed.src]); + const decodes = [...new Set(sources)] + .filter(src => !this.requested.has(src)) + .map(src => { + this.requested.add(src); + // A rejection counts as unmeasurable, or its batch would never settle. + return this.decode(src) + .catch(() => null) + .then(blocks => { + this.blocks.set(src, blocks); + }); + }); + + if (decodes.length > 0) { + const batch: Promise = Promise.all(decodes).then(() => { + this.batches.delete(batch); + this.update(); + }); + this.batches.add(batch); + } + this.update(); + } + + public levelsFor(clipId: string): ReadonlyMap | undefined { + return this.levels.get(clipId); + } + + /** Resolves once every decode started so far has landed and its levels have been announced. */ + public async whenSettled(): Promise { + while (this.batches.size > 0) await Promise.all(this.batches); + } + + public dispose(): void { + this.disposed = true; + } + + private update(): void { + if (this.disposed) return; + const levels = new Map( + this.plans.map(([clipId, measurements]) => [clipId, this.levelsOf(measurements)] as const).filter(([, refs]) => refs.size > 0) + ); + const key = JSON.stringify([...levels].map(([clipId, refs]) => [clipId, [...refs]])); + if (key === this.levelsKey) return; + + this.levels = levels; + this.levelsKey = key; + this.events.emit(InternalEvent.DuckLevelsChanged, {}); + } + + // A dip whose speech or bed has no measurable loudness gets no entry, so it falls back to the default level. + private levelsOf(measurements: DuckMeasurement[]): Map { + const levels = new Map(); + for (const { ref, speech, bed, speechVolume } of measurements) { + const speechLufs = this.loudness(speech); + const bedLufs = this.loudness(bed); + if (speechLufs !== null && bedLufs !== null) levels.set(ref, duckLevel(speechLufs, speechVolume, bedLufs)); + } + return levels; + } + + private loudness({ src, start, end }: LoudnessWindow): number | null { + const blocks = this.blocks.get(src); + return blocks ? integratedLoudness(blocks, start, end) : null; + } +} diff --git a/src/core/edit-session.ts b/src/core/edit-session.ts index b4e92b7d..3d81519a 100644 --- a/src/core/edit-session.ts +++ b/src/core/edit-session.ts @@ -1,6 +1,7 @@ import { type Player, PlayerType } from "@canvas/players/player"; import { PlayerFactory } from "@canvas/players/player-factory"; import type { Canvas } from "@canvas/shotstack-canvas"; +import { DuckLevelService } from "@core/audio/duck-levels"; // TODO: Consolidate commands - many have overlapping concerns and could be unified import { tryParseClipJson, tryParseTracksJson } from "@core/clipboard/clip-json"; import { insertClipWithOverlapPolicy } from "@core/clipboard/paste-dispatcher"; @@ -122,6 +123,7 @@ export class Edit { private lumaMaskController: LumaMaskController; private playerReconciler: PlayerReconciler; private assetGenerator: AssetGenerator; + private duckLevels: DuckLevelService; /** @internal */ public generationSettings?: GenerationSettingsHandler; private outputSettings!: OutputSettingsManager; @@ -155,6 +157,8 @@ export class Edit { this.assetGenerator.abortMissing(live); }; + private readonly onResolvedForDucking = ({ edit }: { edit: ResolvedEdit }): void => this.duckLevels.refresh(edit); + // Clearing the key on deselection lets a re-selected clip announce itself again. private emitGenerationConfig = (): void => { const clipId = this.getSelectedClipInfo()?.player.clipId ?? null; @@ -228,6 +232,8 @@ export class Edit { emitStatusChanged: clipId => this.internalEvents.emit(InternalEvent.GenerationStatusChanged, { clipId }) }); this.mergeFieldService = new MergeFieldService(this.internalEvents); + this.duckLevels = new DuckLevelService(this.internalEvents); + this.internalEvents.on(InternalEvent.Resolved, this.onResolvedForDucking); this.outputSettings = new OutputSettingsManager(this); this.selectionManager = new SelectionManager(this); this.timingManager = new TimingManager(this); @@ -305,6 +311,11 @@ export class Edit { // 10. Update total duration this.updateTotalDuration(); + // Loading resolves without announcing it, so nothing else would measure this edit's dips. + this.duckLevels.refresh(this.getResolvedEdit()); + // Players built their dips at step 7, before timing resolved, and a Custom or unmeasurable dip never gets a level to rebuild on. + this.internalEvents.emit(InternalEvent.DuckLevelsChanged, {}); + // 11. Load soundtrack if present if (parsedEdit.timeline.soundtrack) { await this.loadSoundtrack(parsedEdit.timeline.soundtrack); @@ -342,8 +353,10 @@ export class Edit { this.generationSettings = undefined; this.clearClips(); this.internalEvents.off(InternalEvent.Resolved, this.onResolvedForGeneration); + this.internalEvents.off(InternalEvent.Resolved, this.onResolvedForDucking); for (const name of Edit.GenerationConfigTriggers) this.internalEvents.off(name, this.emitGenerationConfig); this.assetGenerator.abortAll(); + this.duckLevels.dispose(); this.lumaMaskController.dispose(); this.playerReconciler.dispose(); @@ -694,6 +707,11 @@ export class Edit { return this.lastResolved; } + /** @internal */ + public getDuckLevels(): DuckLevelService { + return this.duckLevels; + } + /** * Get a specific clip from the resolved edit. * @internal @@ -809,6 +827,8 @@ export class Edit { if (cachedTrack && cachedTrack.clips[result.clipIndex]) { cachedTrack.clips[result.clipIndex] = result.resolved; } + // This path skips Resolved, but a resized bed still changes the windows its dips are measured over. + this.duckLevels.refresh(this.lastResolved); } // Update the player via the reconciler's single-player update diff --git a/src/core/events/edit-events.ts b/src/core/events/edit-events.ts index 03bd0afd..444e2740 100644 --- a/src/core/events/edit-events.ts +++ b/src/core/events/edit-events.ts @@ -124,6 +124,9 @@ export const InternalEvent = { // Resolution - document to resolved edit transformation Resolved: "resolved", + // Measured duck levels landed or changed + DuckLevelsChanged: "duck:levelsChanged", + // Edit → Canvas visual sync PlayerAddedToTrack: "player:addedToTrack", PlayerMovedBetweenTracks: "player:movedBetweenTracks", @@ -217,6 +220,7 @@ export type InternalEventMap = { // Resolution [InternalEvent.Resolved]: { edit: ResolvedEdit }; + [InternalEvent.DuckLevelsChanged]: Record; // Edit → Canvas visual sync [InternalEvent.PlayerAddedToTrack]: { player: Player; trackIndex: number }; diff --git a/src/core/export/audio-processor.ts b/src/core/export/audio-processor.ts index 4b7172c2..6d279247 100644 --- a/src/core/export/audio-processor.ts +++ b/src/core/export/audio-processor.ts @@ -1,3 +1,4 @@ +import type { AudioPlayer } from "@canvas/players/audio-player"; import { PlayerType, type Player } from "@canvas/players/player"; import { createAnimatedSpeed } from "@canvas/players/video-player"; import type { VideoAsset } from "@schemas"; @@ -131,8 +132,11 @@ export class AudioProcessor { private asAudioClip(clip: Player): AudioBearingClip | null { if (!AUDIO_BEARING.has(clip.playerType)) return null; const asset = clip.clipConfiguration?.asset as - { src?: unknown; trim?: number; volume?: unknown; volumeEffect?: string; effect?: string; speed?: VideoAsset["speed"] } | undefined; + | { src?: unknown; trim?: number; volume?: unknown; volumeEffect?: string; effect?: string; speed?: VideoAsset["speed"]; duck?: unknown } + | undefined; if (typeof asset?.src !== "string" || !asset.src) return null; + // The preview's ducked volume already carries the fade, so it must not be applied again. + const ducked = Boolean(asset.duck) && clip.playerType === PlayerType.Audio; return { clipId: clip.clipId, @@ -141,8 +145,8 @@ export class AudioProcessor { start: clip.getStart(), length: clip.getLength(), trim: asset.trim ?? 0, - volume: asset.volume as number | VolumeTween[] | undefined, - effect: asset.volumeEffect ?? asset.effect, + volume: (ducked ? (clip as AudioPlayer).getEffectiveVolume() : asset.volume) as number | VolumeTween[] | undefined, + effect: ducked ? undefined : (asset.volumeEffect ?? asset.effect), speed: asset.speed }; } diff --git a/src/core/export/export-coordinator.ts b/src/core/export/export-coordinator.ts index 96fa739a..bb9800c2 100644 --- a/src/core/export/export-coordinator.ts +++ b/src/core/export/export-coordinator.ts @@ -58,6 +58,20 @@ function waitForLoads(edit: Pick, sig return untilAborted(Promise.race([edit.whenSettled(), timedOut]), signal).finally(() => clearTimeout(timer)); } +// A stalled audio fetch can keep a measurement pending indefinitely. Past the timeout the mix uses the levels announced +// so far and the default level for the rest, which is what preview plays. Levels are announced when a whole batch of +// fetches lands, so one stalled fetch also holds back levels that need only the other files in its batch. +function waitForDuckLevels(edit: Pick, signal?: AbortSignal): Promise { + let timer: ReturnType | undefined; + const timedOut = new Promise(resolve => { + timer = setTimeout(() => { + console.warn(`Export: audio levels weren't all measured within ${ASSET_SETTLE_TIMEOUT_MS / 1000} seconds; the rest duck to the default level`); + resolve(); + }, ASSET_SETTLE_TIMEOUT_MS); + }); + return untilAborted(Promise.race([edit.getDuckLevels().whenSettled(), timedOut]), signal).finally(() => clearTimeout(timer)); +} + export class ExportCoordinator { private readonly edit: Edit; private readonly app: pixi.Application; @@ -151,6 +165,8 @@ export class ExportCoordinator { output.addVideoTrack(videoSource); report(0.15, "Mixing audio..."); + // Players rebuild their ducked volume as measured levels land, and the mix reads those volumes. + if (!cfg.muted) await waitForDuckLevels(this.edit, signal); const mixedAudio = cfg.muted ? null : await untilAborted(this.audioProcessor.renderMix(this.edit.getTracks(), this.edit.totalDuration), signal); throwIfStopped(); let audioSource: AudioBufferSource | null = null; diff --git a/src/core/export/export-timing.ts b/src/core/export/export-timing.ts index d7243c6e..c3aecbe3 100644 --- a/src/core/export/export-timing.ts +++ b/src/core/export/export-timing.ts @@ -30,7 +30,11 @@ export function buildVolumeAutomation(volume: number | VolumeTween[] | undefined points.push({ time: start, value: tween.from }); points.push({ time: end, value: tween.to }); } - return points.length ? points : [{ time: 0, value: 1 }]; + if (!points.length) return [{ time: 0, value: 1 }]; + + // A GainNode sits at 1 before its first event, while the player holds the earliest tween's `from`. + const earliest = points.reduce((first, point) => (point.time < first.time ? point : first)); + return earliest.time > 0 ? [{ time: 0, value: earliest.value }, ...points] : points; } const base = typeof volume === "number" ? volume : 1; diff --git a/tests/audio-player-duck.test.ts b/tests/audio-player-duck.test.ts new file mode 100644 index 00000000..b79300d5 --- /dev/null +++ b/tests/audio-player-duck.test.ts @@ -0,0 +1,149 @@ +import { AudioPlayer } from "@canvas/players/audio-player"; +import { EditDocument } from "@core/edit-document"; +import type { Edit } from "@core/edit-session"; +import { InternalEvent, type EditEventMap, type InternalEventMap } from "@core/events/edit-events"; +import { EventEmitter } from "@core/events/event-emitter"; +import { MergeFieldService } from "@core/merge/merge-field-service"; +import { resolve } from "@core/resolver"; +import type { Edit as EditConfig, ResolvedEdit } from "@schemas"; +import { duckedVolumeFor, scanDucking } from "@shotstack/shotstack-canvas/duck"; +import * as howler from "howler"; + +jest.mock("pixi.js", () => ({ + // eslint-disable-next-line global-require, @typescript-eslint/no-require-imports -- jest.mock factories can't use imports + ...require("./helpers/pixi-mock-filters").pixiFilterStubs, + Container: jest.fn().mockImplementation(() => ({ addChild: jest.fn(), destroy: jest.fn() })) +})); + +jest.mock("howler", () => ({ + // The player checks `instanceof Howl`, so the stub has to be a class. + Howl: class { + volume = jest.fn(); + + stop = jest.fn(); + + unload = jest.fn(); + } +})); + +const MUSIC_TRACK = 1; + +function config(musicAsset: Record): EditConfig { + return { + timeline: { + tracks: [ + { + clips: [ + { asset: { type: "audio", src: "https://example.com/intro.mp3" }, start: 0, length: 2 }, + { alias: "voice", asset: { type: "audio", src: "https://example.com/voice.mp3" }, start: "auto", length: 3 } + ] + }, + { clips: [{ asset: { type: "audio", src: "https://example.com/music.mp3", ...musicAsset }, start: 0, length: 10 }] } + ] + }, + output: { format: "mp4", size: { width: 1280, height: 720 } } + } as EditConfig; +} + +/** The parts of a session a player reads, over a real document and resolver. */ +async function session(musicAsset: Record) { + const document = new EditDocument(config(musicAsset)); + const mergeFields = new MergeFieldService(new EventEmitter()); + const events = new EventEmitter(); + const levels = new Map>(); + let resolved: ResolvedEdit = resolve(document, { mergeFields }); + + const edit = { + playbackTime: 0, + isPlaying: false, + size: { width: 1280, height: 720 }, + assetLoader: { load: jest.fn(async () => new howler.Howl({ src: [""] })) }, + getInternalEvents: () => events, + getResolvedEdit: jest.fn(() => resolved), + getDuckLevels: () => ({ levelsFor: (clipId: string) => levels.get(clipId) }) + }; + + const music = resolved.timeline.tracks[MUSIC_TRACK].clips[0]; + const player = new AudioPlayer(edit as unknown as Edit, music); + player.clipId = music.id; + await player.load(); + + const reresolve = (): void => { + resolved = resolve(document, { mergeFields }); + events.emit(InternalEvent.Resolved, { edit: resolved }); + }; + const expected = () => { + const clip = resolved.timeline.tracks[MUSIC_TRACK].clips[0]; + return duckedVolumeFor(clip, scanDucking(resolved).aliases, levels.get(clip.id)); + }; + return { document, edit, events, levels, music, player, reresolve, expected }; +} + +const dipStart = (volume: unknown): number | undefined => (Array.isArray(volume) ? (volume[0] as { start: number }).start : undefined); + +describe("AudioPlayer ducking", () => { + it("getEffectiveVolume equals duckedVolumeFor with the resolved alias timings", async () => { + const { player, expected } = await session({ duck: { under: "alias://voice" } }); + + expect(player.getEffectiveVolume()).toEqual(expected()); + // The voice starts "auto" after the 2-second intro; its dip ramps down 0.3 s before that. + expect(dipStart(player.getEffectiveVolume())).toBe(1.7); + }); + + it("rebuilds on Resolved when another clip moves, and on DuckLevelsChanged", async () => { + const { document, edit, events, levels, music, player, reresolve, expected } = await session({ duck: { under: "alias://voice" } }); + + document.updateClip(0, 0, { length: 4 }); + reresolve(); + expect(dipStart(player.getEffectiveVolume())).toBe(3.7); + + levels.set(music.id, new Map([["alias://voice", 0.2]])); + events.emit(InternalEvent.DuckLevelsChanged, {}); + expect(player.getEffectiveVolume()).toEqual(expected()); + edit.playbackTime = 5; + expect(player.getVolume()).toBeCloseTo(0.2); + + player.dispose(); + edit.getResolvedEdit.mockClear(); + reresolve(); + events.emit(InternalEvent.DuckLevelsChanged, {}); + expect(edit.getResolvedEdit).not.toHaveBeenCalled(); + }); + + it("stays unsubscribed when disposed while its audio loads", async () => { + const { edit, events, music, player: loaded, reresolve } = await session({ duck: { under: "alias://voice" } }); + loaded.dispose(); + let land!: (howl: howler.Howl) => void; + const audio = new Promise(done => { + land = done; + }); + edit.assetLoader.load.mockImplementationOnce(() => audio); + + const player = new AudioPlayer(edit as unknown as Edit, music); + player.clipId = music.id; + const loading = player.load(); + player.dispose(); + land(new howler.Howl({ src: [""] })); + await loading; + + edit.getResolvedEdit.mockClear(); + reresolve(); + events.emit(InternalEvent.DuckLevelsChanged, {}); + expect(edit.getResolvedEdit).not.toHaveBeenCalled(); + }); + + it("without duck, keeps the asset's volume and fade and ignores other clips moving", async () => { + const { document, edit, player, reresolve } = await session({ volume: 0.8, effect: "fadeIn" }); + const fade = [{ from: 0, to: 0.8, start: 0, length: 2 }]; + + expect(player.getEffectiveVolume()).toEqual(fade); + edit.playbackTime = 1; + expect(player.getVolume()).toBeCloseTo(0.4); + + edit.getResolvedEdit.mockClear(); + document.updateClip(0, 0, { length: 4 }); + reresolve(); + expect(edit.getResolvedEdit).not.toHaveBeenCalled(); + expect(player.getEffectiveVolume()).toEqual(fade); + }); +}); diff --git a/tests/duck-levels.test.ts b/tests/duck-levels.test.ts new file mode 100644 index 00000000..ce43ec12 --- /dev/null +++ b/tests/duck-levels.test.ts @@ -0,0 +1,216 @@ +import { DuckLevelService } from "@core/audio/duck-levels"; +import { InternalEvent, type InternalEventMap } from "@core/events/edit-events"; +import { EventEmitter } from "@core/events/event-emitter"; +import type { ResolvedEdit } from "@schemas"; +import { duckLevel, momentaryToBlock } from "@shotstack/shotstack-canvas/duck"; + +const VOICE = "https://example.com/voice.mp3"; +const VOICE_2 = "https://example.com/voice-2.mp3"; +const MUSIC = "https://example.com/music.mp3"; + +type Blocks = Float64Array | null; + +// One block per 0.1 s hop, `lufs(end)` loud, where `end` is when the block ends. +const blocksOf = (lufs: (end: number) => number): Float64Array => Float64Array.from({ length: 200 }, (_, k) => momentaryToBlock(lufs((k + 1) * 0.1))); + +// The music is louder for its first 6 seconds, so each dip's level depends on where its voice falls. +const FILES: Record = { + [VOICE]: blocksOf(() => -20), + [VOICE_2]: blocksOf(() => -26), + [MUSIC]: blocksOf(end => (end <= 6 ? -14 : -20)) +}; + +const voice = (alias: string, src: string | undefined, start: number, volume?: number) => ({ + id: alias, + alias, + start, + length: 3, + asset: { type: "audio", ...(src === undefined ? {} : { src }), ...(volume === undefined ? {} : { volume }) } +}); + +const music = (id: string, duck: Record, start = 0) => ({ id, start, length: 20, asset: { type: "audio", src: MUSIC, duck } }); + +const edit = (...tracks: unknown[][]): ResolvedEdit => + ({ + timeline: { tracks: tracks.map(clips => ({ clips })) }, + output: { format: "mp4", size: { width: 1280, height: 720 } } + }) as unknown as ResolvedEdit; + +const flush = (): Promise => + new Promise(resolve => { + setImmediate(resolve); + }); + +function setup(decode: (src: string) => Promise = async src => FILES[src] ?? null) { + const events = new EventEmitter(); + const changed = jest.fn(); + events.on(InternalEvent.DuckLevelsChanged, changed); + const decoder = jest.fn(decode); + return { service: new DuckLevelService(events, decoder), decoder, changed, events }; +} + +/** A decoder whose files land only when a test says so. */ +function heldDecoder() { + const held = new Map void>(); + const decode = (src: string) => + new Promise(resolve => { + held.set(src, resolve); + }); + const land = (src: string, blocks: Blocks = FILES[src]) => held.get(src)?.(blocks); + return { decode, land }; +} + +describe("DuckLevelService", () => { + it("decodes each file once", async () => { + const { service, decoder } = setup(); + const resolved = edit( + [voice("voice", VOICE, 2), voice("voice2", VOICE_2, 12)], + [music("intro", { under: "alias://voice" }), music("outro", { under: "alias://voice2" }, 10)] + ); + + service.refresh(resolved); + service.refresh(resolved); + await service.whenSettled(); + service.refresh(resolved); + await service.whenSettled(); + + expect(decoder.mock.calls.map(([src]) => src).sort()).toEqual([MUSIC, VOICE, VOICE_2].sort()); + }); + + it("sets each dip to duckLevel of the speech and bed loudness under it", async () => { + const { service } = setup(); + + service.refresh( + edit([voice("voice", VOICE, 2), voice("voice2", VOICE_2, 8, 0.5)], [music("music", { under: ["alias://voice", "alias://voice2"] })]) + ); + await service.whenSettled(); + + expect(service.levelsFor("music")).toEqual( + new Map([ + ["alias://voice", duckLevel(-20, 1, -14)], + ["alias://voice2", duckLevel(-26, 0.5, -20)] + ]) + ); + }); + + it("emits DuckLevelsChanged once per batch that lands", async () => { + const { decode, land } = heldDecoder(); + const { service, changed } = setup(decode); + const one = edit([voice("voice", VOICE, 2)], [music("music", { under: "alias://voice" })]); + const two = edit([voice("voice", VOICE, 2), voice("voice2", VOICE_2, 8)], [music("music", { under: ["alias://voice", "alias://voice2"] })]); + + service.refresh(one); + land(VOICE); + await flush(); + expect(changed).not.toHaveBeenCalled(); + + land(MUSIC); + await service.whenSettled(); + expect(changed).toHaveBeenCalledTimes(1); + + service.refresh(two); + land(VOICE_2); + await service.whenSettled(); + expect(changed).toHaveBeenCalledTimes(2); + + service.refresh(two); + await service.whenSettled(); + expect(changed).toHaveBeenCalledTimes(2); + }); + + it("gives no entry to a dip with an explicit duck.volume", async () => { + const { service, decoder } = setup(); + + service.refresh(edit([voice("voice", VOICE, 2)], [music("music", { under: "alias://voice", volume: 0.2 })])); + await service.whenSettled(); + + expect(service.levelsFor("music")?.has("alias://voice") ?? false).toBe(false); + expect(decoder).not.toHaveBeenCalled(); + }); + + it("gives no entry when a file can't be decoded", async () => { + const { service, changed } = setup(async src => (src === VOICE ? null : FILES[src])); + + service.refresh(edit([voice("voice", VOICE, 2)], [music("music", { under: "alias://voice" })])); + await service.whenSettled(); + + expect(service.levelsFor("music")?.has("alias://voice") ?? false).toBe(false); + expect(changed).not.toHaveBeenCalled(); + }); + + it("no level until the source resolves", async () => { + const { service, decoder } = setup(); + const under = { under: ["alias://voice", "alias://voice2"] }; + + service.refresh(edit([voice("voice", undefined, 2), voice("voice2", "{{ VOICE }}", 8)], [music("music", under)])); + await service.whenSettled(); + expect(decoder).not.toHaveBeenCalled(); + expect(service.levelsFor("music")?.size ?? 0).toBe(0); + + service.refresh(edit([voice("voice", undefined, 2), voice("voice2", VOICE_2, 8)], [music("music", under)])); + await service.whenSettled(); + expect(decoder.mock.calls.map(([src]) => src).sort()).toEqual([MUSIC, VOICE_2].sort()); + expect([...(service.levelsFor("music")?.keys() ?? [])]).toEqual(["alias://voice2"]); + }); + + it("treats a merge field as unresolved where URL.canParse is missing", async () => { + const canParse = Object.getOwnPropertyDescriptor(URL, "canParse"); + Reflect.deleteProperty(URL, "canParse"); + try { + const { service, decoder } = setup(); + + service.refresh( + edit([voice("voice", "{{ VOICE }}", 2), voice("voice2", VOICE_2, 8)], [music("music", { under: ["alias://voice", "alias://voice2"] })]) + ); + await service.whenSettled(); + + expect(decoder.mock.calls.map(([src]) => src).sort()).toEqual([MUSIC, VOICE_2].sort()); + expect([...(service.levelsFor("music")?.keys() ?? [])]).toEqual(["alias://voice2"]); + } finally { + if (canParse) Object.defineProperty(URL, "canParse", canParse); + } + }); + + it("settles, now and later, when a decode rejects, leaving that file unmeasured", async () => { + const { service } = setup(async src => { + if (src === VOICE) throw new Error("decoder crashed"); + return FILES[src] ?? null; + }); + + service.refresh(edit([voice("voice", VOICE, 2), voice("voice2", VOICE_2, 8)], [music("music", { under: ["alias://voice", "alias://voice2"] })])); + await expect(service.whenSettled()).resolves.toBeUndefined(); + await expect(service.whenSettled()).resolves.toBeUndefined(); + + expect([...(service.levelsFor("music")?.keys() ?? [])]).toEqual(["alias://voice2"]); + }); + + it("whenSettled resolves after pending decodes", async () => { + const { decode, land } = heldDecoder(); + const { service, events } = setup(decode); + const order: string[] = []; + events.on(InternalEvent.DuckLevelsChanged, () => order.push("changed")); + + service.refresh(edit([voice("voice", VOICE, 2)], [music("music", { under: "alias://voice" })])); + const settled = service.whenSettled().then(() => order.push("settled")); + land(VOICE); + await flush(); + expect(order).toEqual([]); + + land(MUSIC); + await settled; + expect(order).toEqual(["changed", "settled"]); + }); + + it("ignores decodes that land after it is disposed", async () => { + const { decode, land } = heldDecoder(); + const { service, changed } = setup(decode); + + service.refresh(edit([voice("voice", VOICE, 2)], [music("music", { under: "alias://voice" })])); + service.dispose(); + land(VOICE); + land(MUSIC); + await service.whenSettled(); + + expect(changed).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/edit-load.test.ts b/tests/edit-load.test.ts index facddfea..d406dec4 100644 --- a/tests/edit-load.test.ts +++ b/tests/edit-load.test.ts @@ -25,7 +25,9 @@ * 17. Hide loading overlay (in finally block) */ +import { DuckLevelService } from "@core/audio/duck-levels"; import { Edit } from "@core/edit-session"; +import { InternalEvent } from "@core/events/edit-events"; import { ShotstackEdit } from "@core/shotstack-edit"; import { PlayerType } from "@canvas/players/player"; import type { EventEmitter } from "@core/events/event-emitter"; @@ -1346,3 +1348,48 @@ it("keeps same-source video failures separate for each clip", () => { expect(edit.getClipError(0, 0)).toBeNull(); expect(edit.getClipError(0, 1)).not.toBeNull(); }); + +describe("duck levels", () => { + afterEach(() => jest.restoreAllMocks()); + + it("refreshes once loaded and after every resolve, and is disposed with the session", async () => { + const refresh = jest.spyOn(DuckLevelService.prototype, "refresh"); + const dispose = jest.spyOn(DuckLevelService.prototype, "dispose"); + const edit = new Edit(createMinimalEdit()); + + await edit.load(); + expect(refresh).toHaveBeenLastCalledWith(edit.getResolvedEdit()); + + const resolved = edit.resolve(); + expect(refresh).toHaveBeenLastCalledWith(resolved); + + refresh.mockClear(); + edit.resolveClip(edit.getClipId(0, 0) ?? ""); + expect(refresh).toHaveBeenCalledWith(edit.getResolvedEdit()); + + edit.dispose(); + expect(dispose).toHaveBeenCalledTimes(1); + }); + + it("announces levels once loaded, so players rebuild their dips when nothing is measured", async () => { + const refresh = jest.spyOn(DuckLevelService.prototype, "refresh"); + const edit = new Edit( + createMinimalEdit([ + { clips: [{ alias: "voice", asset: { type: "audio", src: "https://example.com/voice.mp3" }, start: 2, length: 3 }] }, + { + clips: [ + { asset: { type: "audio", src: "https://example.com/music.mp3", duck: { under: "alias://voice", volume: 0.2 } }, start: 0, length: 10 } + ] + } + ]) + ); + const changed = jest.fn(); + edit.getInternalEvents().on(InternalEvent.DuckLevelsChanged, changed); + + await edit.load(); + + expect(changed).toHaveBeenCalledTimes(1); + expect(refresh.mock.invocationCallOrder.at(-1)).toBeLessThan(changed.mock.invocationCallOrder[0]); + edit.dispose(); + }); +}); diff --git a/tests/export-audio.test.ts b/tests/export-audio.test.ts index 20254d1d..b5b2b0cf 100644 --- a/tests/export-audio.test.ts +++ b/tests/export-audio.test.ts @@ -23,15 +23,24 @@ function createBufferSource() { return source; } -const createGain = () => ({ gain: { setValueAtTime: jest.fn(), linearRampToValueAtTime: jest.fn() }, connect: (node: unknown) => node }); +type Gain = { setValueAtTime: jest.Mock; linearRampToValueAtTime: jest.Mock }; -function mediaClip(playerType: PlayerType, asset: Record, start: number, length: number): Player { +const gains: Gain[] = []; + +function createGain() { + const gain: Gain = { setValueAtTime: jest.fn(), linearRampToValueAtTime: jest.fn() }; + gains.push(gain); + return { gain, connect: (node: unknown) => node }; +} + +function mediaClip(playerType: PlayerType, asset: Record, start: number, length: number, player: object = {}): Player { return { clipId: `${playerType}-clip`, playerType, clipConfiguration: { asset }, getStart: () => start, - getLength: () => length + getLength: () => length, + ...player } as unknown as Player; } @@ -51,6 +60,7 @@ beforeAll(() => { beforeEach(() => { scheduled.length = 0; + gains.length = 0; }); describe("AudioProcessor speed", () => { @@ -119,3 +129,58 @@ describe("AudioProcessor failures", () => { ).resolves.toBeNull(); }); }); + +describe("AudioProcessor ducking", () => { + const FADING = { type: "audio", src: "https://example.com/music.mp3", volume: 1, effect: "fadeIn" }; + const MUSIC = { ...FADING, duck: { under: "alias://voice" } }; + + it("mixes a ducked clip at its effective volume with no separate fade", async () => { + const dip = [ + { from: 1, to: 0.1, start: 1, length: 0.3 }, + { from: 0.1, to: 1, start: 3, length: 0.3 } + ]; + await new AudioProcessor().renderMix( + [ + [ + mediaClip(PlayerType.Audio, MUSIC, 2, 6, { getEffectiveVolume: () => dip }), + mediaClip(PlayerType.Audio, MUSIC, 0, 6, { getEffectiveVolume: () => 0.5 }) + ] + ], + 10 + ); + + expect(gains[0].setValueAtTime.mock.calls).toEqual([[1, 2]]); + expect(gains[0].linearRampToValueAtTime.mock.calls).toEqual([ + [1, 3], + [0.1, 3.3], + [0.1, 5], + [1, 5.3] + ]); + expect(gains[1].setValueAtTime.mock.calls).toEqual([[0.5, 0]]); + expect(gains[1].linearRampToValueAtTime).not.toHaveBeenCalled(); + }); + + it("holds a ducked bed at its volume from the clip's start until its first dip", async () => { + const dip = [ + { from: 0.5, to: 0.1, start: 4.32, length: 0.3 }, + { from: 0.1, to: 0.5, start: 7, length: 0.3 } + ]; + const bed = { type: "audio", src: "https://example.com/music.mp3", volume: 0.5, duck: { under: "alias://voice" } }; + await new AudioProcessor().renderMix([[mediaClip(PlayerType.Audio, bed, 1, 10, { getEffectiveVolume: () => dip })]], 12); + + expect(gains[0].setValueAtTime.mock.calls).toEqual([[0.5, 1]]); + const [value, time] = gains[0].linearRampToValueAtTime.mock.calls[0]; + expect(value).toBe(0.5); + expect(time).toBeCloseTo(5.32); + }); + + it("keeps the asset's volume and fade for a clip without duck", async () => { + await new AudioProcessor().renderMix([[mediaClip(PlayerType.Audio, { ...FADING, volume: 0.8 }, 0, 6, { getEffectiveVolume: () => 0.5 })]], 10); + + expect(gains[0].setValueAtTime.mock.calls).toEqual([[0, 0]]); + expect(gains[0].linearRampToValueAtTime.mock.calls).toEqual([ + [0.8, 2], + [0.8, 6] + ]); + }); +}); diff --git a/tests/export-coordinator.test.ts b/tests/export-coordinator.test.ts index d13c4edc..269eb2c0 100644 --- a/tests/export-coordinator.test.ts +++ b/tests/export-coordinator.test.ts @@ -88,6 +88,8 @@ function createHarness() { getResolvedEdit: () => ({ timeline: { tracks: [] }, output: { format: "mp4" } }), getFontUrlByFamilyAndWeight: () => null, whenSettled: jest.fn(() => Promise.resolve()), + duckLevels: { whenSettled: jest.fn(() => Promise.resolve()) }, + getDuckLevels: () => edit.duckLevels, getLoadingClipIds: jest.fn(() => [] as string[]), getTracks: () => edit.tracks, getClipError: jest.fn<{ error: string; assetType: string } | null, [number, number]>(() => null), @@ -409,6 +411,57 @@ describe("output settings", () => { exporter.dispose(); }); + it("mixes audio only once the duck levels have settled", async () => { + const { exporter, edit } = createHarness(); + const order: string[] = []; + edit.duckLevels.whenSettled.mockImplementation(async () => { + await null; + order.push("settled"); + }); + mockRenderMix.mockImplementation(async () => { + order.push("mixed"); + return null; + }); + + await exporter.exportBlob(); + + expect(order).toEqual(["settled", "mixed"]); + exporter.dispose(); + }); + + it("mixes with the levels measured so far when they haven't settled by the timeout", async () => { + jest.useFakeTimers(); + const warn = jest.spyOn(console, "warn").mockImplementation(() => undefined); + const { exporter, edit } = createHarness(); + edit.duckLevels.whenSettled.mockReturnValue(new Promise(() => {})); + + const result = exporter.exportBlob(); + await jest.advanceTimersByTimeAsync(ASSET_SETTLE_TIMEOUT_MS - 1); + expect(mockRenderMix).not.toHaveBeenCalled(); + await jest.advanceTimersByTimeAsync(1); + + await expect(result).resolves.toBeInstanceOf(Blob); + expect(mockRenderMix).toHaveBeenCalledTimes(1); + expect(warn).toHaveBeenCalledTimes(1); + warn.mockRestore(); + exporter.dispose(); + jest.useRealTimers(); + }); + + it("neither warns nor leaves a timer behind when the duck levels settle first", async () => { + jest.useFakeTimers(); + const warn = jest.spyOn(console, "warn").mockImplementation(() => undefined); + const { exporter } = createHarness(); + + await expect(exporter.exportBlob()).resolves.toBeInstanceOf(Blob); + + expect(warn).not.toHaveBeenCalled(); + expect(jest.getTimerCount()).toBe(0); + warn.mockRestore(); + exporter.dispose(); + jest.useRealTimers(); + }); + it("tags the video as limited range even when the encoder reports full range", async () => { const { exporter } = createHarness(); await exporter.exportBlob(); diff --git a/tests/export-timing.test.ts b/tests/export-timing.test.ts index 422bddbc..c46d1251 100644 --- a/tests/export-timing.test.ts +++ b/tests/export-timing.test.ts @@ -48,4 +48,23 @@ describe("buildVolumeAutomation", () => { { time: 1, value: 1 } ]); }); + + it("holds the earliest keyframe's from value until it starts", () => { + expect( + buildVolumeAutomation( + [ + { from: 0.3, to: 1, start: 2, length: 1 }, + { from: 1, to: 0.6, start: 4, length: 1 } + ], + undefined, + 6 + ) + ).toEqual([ + { time: 0, value: 0.3 }, + { time: 2, value: 0.3 }, + { time: 3, value: 1 }, + { time: 4, value: 1 }, + { time: 5, value: 0.6 } + ]); + }); });