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
40 changes: 37 additions & 3 deletions src/core/ui/media-toolbar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import type { Edit } from "@core/edit-session";
import { EditEvent } from "@core/events/edit-events";
import { validateAssetUrl } from "@core/shared/utils";
import { ShotstackEdit } from "@core/shotstack-edit";
import type { ResolvedClip } from "@schemas";
import type { AudioAsset, Duck, ResolvedClip } from "@schemas";
import { injectShotstackStyles } from "@styles/inject";

import { BaseToolbar } from "./base-toolbar";
Expand Down Expand Up @@ -905,6 +905,7 @@ export class MediaToolbar extends BaseToolbar {
this.volumeBtn.title = volumeKeyframed ? "Keyframed volume cannot be edited with this control" : "";
}
this.syncOpacityState(clip);
this.syncDuckState(clip);
}
}

Expand Down Expand Up @@ -1020,6 +1021,12 @@ export class MediaToolbar extends BaseToolbar {

const final = this.captureClipState();
if (final) {
const duck = controlId === "volume" ? MediaToolbar.autoDuckAt(final.clip.asset as Record<string, unknown>) : null;
if (duck) {
final.clip.asset = { ...final.clip.asset, duck } as ResolvedClip["asset"];
this.edit.updateClipInDocument(session.clipId, { asset: final.clip.asset });
this.edit.resolveClip(session.clipId);
}
this.edit.commitClipUpdate(session.clipId, session.initialState, final.clip);
}
if (controlId === "opacity") this.opacityDragTime = null;
Expand Down Expand Up @@ -1186,7 +1193,10 @@ export class MediaToolbar extends BaseToolbar {
this.syncState();
return;
}
const updates = { asset: { ...asset, volume: value / 100 } as typeof clip.asset };
const next = { ...asset, volume: value / 100 };
// Drag ticks only preview; endSliderDrag settles the level when the drag commits.
const duck = this.dragManager.isDragging("volume") ? null : MediaToolbar.autoDuckAt(next);
const updates = { asset: (duck ? { ...next, duck } : next) as typeof clip.asset };

if (this.dragManager.isDragging("volume")) {
this.edit.updateClipInDocument(clipId, updates);
Expand Down Expand Up @@ -1224,6 +1234,13 @@ export class MediaToolbar extends BaseToolbar {
const clipId = this.edit.getClipId(this.selectedTrackIdx, this.selectedClipIdx);
if (!clip || !clipId) return;

// Ducking needs normal speed, and a popup opened before duck was set outlives the Speed button's lock.
const docClip = this.edit.getDocumentClip(this.selectedTrackIdx, this.selectedClipIdx);
if ((docClip?.asset as { duck?: unknown } | undefined)?.duck) {
this.syncState();
return;
}

const asset = clip.asset as Record<string, unknown>;
const newAsset: Record<string, unknown> = { ...asset, speed: this.currentSpeed === 1 ? undefined : this.currentSpeed };
const updates: Record<string, unknown> = { asset: newAsset };
Expand All @@ -1233,7 +1250,6 @@ export class MediaToolbar extends BaseToolbar {
const oldSpeed = typeof asset["speed"] === "number" ? (asset["speed"] as number) : 1;
if (oldSpeed > 0 && oldSpeed !== this.currentSpeed) {
const ratio = oldSpeed / this.currentSpeed;
const docClip = this.edit.getDocumentClip(this.selectedTrackIdx, this.selectedClipIdx);
if (typeof docClip?.length === "number") {
updates["length"] = Math.max(0.1, docClip.length * ratio);
}
Expand Down Expand Up @@ -1351,6 +1367,24 @@ export class MediaToolbar extends BaseToolbar {
}
}

// ─── Duck ────────────────────────────────────────────────────────────────────

/** `duck` without its Custom level once the asset's volume has reached it, since a dip must stay below the volume; otherwise null. */
private static autoDuckAt(asset: Record<string, unknown>): Duck | null {
const { volume, duck } = asset as { volume?: unknown; duck?: Duck };
if (typeof duck?.volume !== "number" || typeof volume !== "number" || volume > duck.volume) return null;
return { ...duck, volume: undefined };
}

private syncDuckState(clip: ResolvedClip): void {
const audio = this.assetType === "audio";
const ducking = audio && Boolean((clip.asset as AudioAsset).duck);
if (this.speedBtn) {
this.speedBtn.disabled = ducking;
this.speedBtn.title = ducking ? "Turn off ducking to change speed" : "";
}
}

private applyClipUpdate(updates: Record<string, unknown>): void {
if (this.selectedTrackIdx >= 0 && this.selectedClipIdx >= 0) {
this.edit.updateClip(this.selectedTrackIdx, this.selectedClipIdx, updates);
Expand Down
187 changes: 187 additions & 0 deletions tests/media-toolbar-duck.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
/**
* @jest-environment jsdom
*/
import type { Edit } from "@core/edit-session";
import { deepMerge } from "@core/shared/utils";
import { MediaToolbar } from "@core/ui/media-toolbar";

jest.mock("pixi.js", () => ({}));
jest.mock("../src/components/canvas/players/player", () => ({ Player: class MockPlayer {}, PlayerType: {} }));
jest.mock("../src/core/shotstack-edit", () => ({}));
jest.mock("../src/core/edit-session", () => ({}));
jest.mock("@styles/inject", () => ({ injectShotstackStyles: jest.fn() }));

// jsdom has no structuredClone, and the toolbar's slider drags call it.
if (typeof structuredClone === "undefined") {
global.structuredClone = (obj: unknown) => JSON.parse(JSON.stringify(obj));
}

type TestClip = Record<string, unknown> & { id: string; start: number; length: number; asset: Record<string, unknown> };

const MUSIC = 0;

/** Music on track 0 is the selected clip; everything else is a candidate to duck under. */
function createTracks(music: Record<string, unknown> = {}, narration: Record<string, unknown> = { alias: "narration" }): TestClip[][] {
return [
[{ id: "clip-music-a1b2c3d4", start: 0, length: 20, asset: { type: "audio", src: "https://example.com/music.mp3", volume: 0.8, ...music } }],
[
{ id: "clip-voice-0000beef", alias: "voice", start: 2, length: 5, asset: { type: "audio", src: "https://example.com/voice.mp3" } },
{ id: "clip-outro-0000cafe", alias: "outro", start: 30, length: 5, asset: { type: "audio", src: "https://example.com/outro.mp3" } }
],
[
{
id: "clip-speech-3f9a2c10",
start: 8,
length: 4,
...narration,
asset: { type: "text-to-speech", text: "Welcome to the show", voice: "Matthew", src: "https://example.com/narration.mp3" }
}
],
[{ id: "clip-video-00c0ffee", alias: "broll", start: 0, length: 20, asset: { type: "video", src: "https://example.com/broll.mp4" } }]
];
}

function createEdit(tracks: TestClip[][]) {
const listeners = new Map<string, Array<(payload: unknown) => void>>();
const clipAt = (t: number, c: number) => tracks[t]?.[c] ?? null;

const edit = {
getClipId: jest.fn((t: number, c: number) => clipAt(t, c)?.id ?? null),
getResolvedClip: jest.fn(clipAt),
getDocumentClip: jest.fn(clipAt),
// Applied a tick later, like the command queue, so writes land after the handler that made them.
updateClip: jest.fn((t: number, c: number, updates: Record<string, unknown>) =>
Promise.resolve().then(() => {
Object.assign(tracks[t][c], deepMerge(tracks[t][c], updates));
listeners.get("edit:changed")?.forEach(listener => listener({ source: "setUpdatedClip" }));
return { status: "success" };
})
),
updateClipInDocument: jest.fn((clipId: string, updates: Record<string, unknown>) => {
const clip = tracks.flat().find(({ id }) => id === clipId);
if (clip) Object.assign(clip, structuredClone(updates));
}),
resolveClip: jest.fn(),
commitClipUpdate: jest.fn(),
deleteClip: jest.fn(),
canDeleteClip: jest.fn(() => true),
playbackTime: 0,
isPlaying: false,
pause: jest.fn(),
getOutputFps: jest.fn(() => 30),
seek: jest.fn(),
events: {
on: jest.fn((event: string, listener: (payload: unknown) => void) => listeners.set(event, [...(listeners.get(event) ?? []), listener])),
off: jest.fn()
},
size: { width: 1920, height: 1080 }
};

return { edit };
}

const flush = () =>
new Promise(resolve => {
setTimeout(resolve, 0);
});

function drag(slider: HTMLInputElement, values: string[]): void {
slider.dispatchEvent(new Event("pointerdown"));
values.forEach(value => {
Object.assign(slider, { value });
slider.dispatchEvent(new Event("input"));
});
slider.dispatchEvent(new Event("change"));
}

function mount(tracks: TestClip[][], selected: [number, number] = [MUSIC, 0]) {
const mocked = createEdit(tracks);
const toolbar = new MediaToolbar(mocked.edit as unknown as Edit);
const parent = document.createElement("div");
document.body.appendChild(parent);
toolbar.mount(parent);
toolbar.show(...selected);

const q = <T extends HTMLElement = HTMLElement>(selector: string) => parent.querySelector(selector) as T;
const music = () => tracks[MUSIC][0];
return { ...mocked, toolbar, parent, q, music };
}

describe("MediaToolbar on a ducked clip", () => {
afterEach(() => {
document.body.innerHTML = "";
jest.clearAllMocks();
});

it("disables the speed section while duck is set", () => {
const ducking = mount(createTracks({ duck: { under: ["alias://voice"] } }));
const speed = ducking.q<HTMLButtonElement>('[data-action="speed"]');
expect(speed.disabled).toBe(true);
expect(speed.title).toBe("Turn off ducking to change speed");
ducking.toolbar.dispose();

const plain = mount(createTracks());
expect(plain.q<HTMLButtonElement>('[data-action="speed"]').disabled).toBe(false);
plain.toolbar.dispose();
});

it("writes no speed while duck is set, from a preset, the slider or the typed value", async () => {
const { edit, toolbar, q } = mount(createTracks({ duck: { under: ["alias://voice"] } }));
q('[data-speed-preset="2"]').click();
const slider = q<HTMLInputElement>("[data-speed-slider]");
slider.value = "450";
slider.dispatchEvent(new Event("change"));
const input = q<HTMLInputElement>("[data-speed-display]");
input.value = "2×";
input.dispatchEvent(new Event("blur"));
await flush();

expect(edit.updateClip).not.toHaveBeenCalled();
expect(q("[data-speed-value]").textContent).toBe("1×");
toolbar.dispose();
});

describe("lowering the volume to or below a Custom level", () => {
it("writes the typed volume and removes duck.volume in one updateClip", async () => {
const { edit, toolbar, q, music } = mount(createTracks({ duck: { under: ["alias://voice"], volume: 0.3 } }));
const input = q<HTMLInputElement>("[data-volume-display]");
input.value = "30%";
input.dispatchEvent(new Event("blur"));
await flush();

expect(edit.updateClip).toHaveBeenCalledTimes(1);
expect(music().asset["volume"]).toBe(0.3);
expect(music().asset["duck"]).toEqual({ under: ["alias://voice"] });
expect((music().asset["duck"] as { volume?: number }).volume).toBeUndefined();
toolbar.dispose();
});

it("commits a slider drag with the volume and the Auto level as one undo entry", () => {
const { edit, toolbar, q } = mount(createTracks({ duck: { under: ["alias://voice"], volume: 0.3 } }));
drag(q<HTMLInputElement>("[data-volume-slider]"), ["40", "20", "10"]);

// Ticks preview the volume only; the level changes with the commit.
expect(edit.updateClipInDocument.mock.calls[2][1]["asset"]).toEqual(
expect.objectContaining({ volume: 0.1, duck: { under: ["alias://voice"], volume: 0.3 } })
);
expect(edit.updateClip).not.toHaveBeenCalled();
expect(edit.commitClipUpdate).toHaveBeenCalledTimes(1);
const [, initial, final] = edit.commitClipUpdate.mock.calls[0];
expect(initial.asset).toEqual(expect.objectContaining({ volume: 0.8, duck: { under: ["alias://voice"], volume: 0.3 } }));
expect(final.asset.volume).toBe(0.1);
expect(final.asset.duck.volume).toBeUndefined();
toolbar.dispose();
});

it("keeps a Custom level that stays below the new volume", async () => {
const { toolbar, q, music } = mount(createTracks({ duck: { under: ["alias://voice"], volume: 0.3 } }));
const input = q<HTMLInputElement>("[data-volume-display]");
input.value = "50%";
input.dispatchEvent(new Event("blur"));
await flush();

expect(music().asset["duck"]).toEqual({ under: ["alias://voice"], volume: 0.3 });
toolbar.dispose();
});
});
});
Loading