Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion src/components/canvas/players/audio-player.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand All @@ -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;

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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;
Expand All @@ -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;
}
Expand Down
112 changes: 112 additions & 0 deletions src/core/audio/duck-levels.ts
Original file line number Diff line number Diff line change
@@ -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<string, Float64Array | null>();
private readonly requested = new Set<string>();
private readonly batches = new Set<Promise<void>>();
private plans: Array<[clipId: string, measurements: DuckMeasurement[]]> = [];
private levels = new Map<string, ReadonlyMap<string, number>>();
private levelsKey = "[]";
private disposed = false;

constructor(
private readonly events: EventEmitter<InternalEventMap>,
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<void> = Promise.all(decodes).then(() => {
this.batches.delete(batch);
this.update();
});
this.batches.add(batch);
}
this.update();
}

public levelsFor(clipId: string): ReadonlyMap<string, number> | 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<void> {
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<string, number> {
const levels = new Map<string, number>();
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;
}
}
20 changes: 20 additions & 0 deletions src/core/edit-session.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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();

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions src/core/events/edit-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -217,6 +220,7 @@ export type InternalEventMap = {

// Resolution
[InternalEvent.Resolved]: { edit: ResolvedEdit };
[InternalEvent.DuckLevelsChanged]: Record<string, never>;

// Edit → Canvas visual sync
[InternalEvent.PlayerAddedToTrack]: { player: Player; trackIndex: number };
Expand Down
10 changes: 7 additions & 3 deletions src/core/export/audio-processor.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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,
Expand All @@ -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
};
}
Expand Down
16 changes: 16 additions & 0 deletions src/core/export/export-coordinator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,20 @@ function waitForLoads(edit: Pick<Edit, "whenSettled" | "getLoadingClipIds">, 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<Edit, "getDuckLevels">, signal?: AbortSignal): Promise<void> {
let timer: ReturnType<typeof setTimeout> | undefined;
const timedOut = new Promise<void>(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;
Expand Down Expand Up @@ -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;
Expand Down
6 changes: 5 additions & 1 deletion src/core/export/export-timing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading
Loading