Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat(editor): show the output gain on the timeline waveform

EtienneLescotc0f98035f1be
diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsx
index d202d0084..804cfa5a5 100644
--- a/src/components/ai-edition/VirtualPreview.tsx
+++ b/src/components/ai-edition/VirtualPreview.tsx
@@ -6,6 +6,7 @@ import {
} from "@/components/video-editor/types";
import { resolvePlaybackSegments } from "@/lib/ai-edition/document/timeline";
import type { AxcutClip, AxcutTrimRange, AxcutZoomRegion } from "@/lib/ai-edition/schema";
+import { audioGainScalar } from "@/lib/ai-edition/store/editorSettings";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
import type { PlaybackClockRef } from "@/lib/ai-edition/timeline/playback-clock";
import { findActiveSpeedRegion, type SpeedRegion } from "@/lib/ai-edition/timeline/speed";
@@ -85,7 +86,7 @@ export function applyPreviewAudioSettings(
elements: Array<HTMLAudioElement | null>,
gainDb: number,
): void {
- const outputGain = 10 ** (gainDb / 20);
+ const outputGain = audioGainScalar(gainDb);
if (!graph) {
for (const element of elements) {
if (element) element.volume = Math.min(1, outputGain);
diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsx
index 1ab58ac88..0872d7f87 100644
--- a/src/components/ai-edition/v4/V4Timeline.tsx
+++ b/src/components/ai-edition/v4/V4Timeline.tsx
@@ -33,6 +33,7 @@ import { createId } from "@/lib/ai-edition/document/ids";
import { collectNativeFormats } from "@/lib/ai-edition/document/outputFormat";
import { setUiProbeScrubbing } from "@/lib/ai-edition/perf/uiFrameProbe";
import type { AxcutClip } from "@/lib/ai-edition/schema";
+import { audioGainScalar } from "@/lib/ai-edition/store/editorSettings";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { useTimelineTranscriptGate } from "@/lib/ai-edition/store/transcriptionStore";
import { useChatPromptBus } from "@/lib/ai-edition/store/useChatPromptBus";
@@ -258,11 +259,18 @@ const ClipWaveform = memo(function ClipWaveform({
assetDurationSec,
sourceStartSec,
sourceEndSec,
+ gain,
}: {
videoUrl: string | undefined;
assetDurationSec: number | undefined;
sourceStartSec: number;
sourceEndSec: number;
+ /** Linear output gain — `audioGainScalar(settings.audioGainDb)`, not the dB.
+ * Passed in rather than read from the settings store here: this component is
+ * memoised per clip, and subscribing each one to the document would re-render
+ * every waveform on any edit at all. As a prop it busts the memo on a gain
+ * change and on nothing else. */
+ gain: number;
}) {
// The duration is what tells `useAudioPeaks` whether this recording is small
// enough to decode whole — the file's byte size does not, on compressed video.
@@ -301,15 +309,31 @@ const ClipWaveform = memo(function ClipWaveform({
if (!bars) return null;
return (
<div aria-hidden className={styles.tlWave}>
- {bars.map((h, bi) => (
- <span
- key={bi}
- style={{
- height: `${Math.max(8, Math.round(h * 100))}%`,
- opacity: (0.5 + h * 0.5).toFixed(2),
- }}
- />
- ))}
+ {bars.map((h, bi) => {
+ // Gain is applied HERE and not inside the memo above, which scans the whole
+ // asset's blocks: a slider drag fires one setLive per pointer move, so this
+ // keeps a tick at `barCount` multiplies instead of re-folding the peaks.
+ //
+ // Clamped because `finish_audio` clamps: it does `(sample * trim).clamp(-1, 1)`
+ // per sample, and this bar is `max|sample|` over its bucket. Gain is positive
+ // and clamping is monotonic, so `clamp(max(|s|) * g)` IS the peak of the gained,
+ // clipped signal — the bar is exact, not an impression. Without the clamp a
+ // 0.5 peak at +12 dB computes `height: 199%` and is merely hidden by the clip's
+ // `overflow`, which draws a signal the export will never write.
+ //
+ // The 8% floor is deliberately NOT scaled: it exists so an empty clip still
+ // reads as a clip, and it is not amplitude.
+ const amplitude = Math.min(1, h * gain);
+ return (
+ <span
+ key={bi}
+ style={{
+ height: `${Math.max(8, Math.round(amplitude * 100))}%`,
+ opacity: (0.5 + amplitude * 0.5).toFixed(2),
+ }}
+ />
+ );
+ })}
</div>
);
});
@@ -1611,6 +1635,7 @@ export function V4Timeline({
assetDurationSec={asset?.durationSec}
sourceStartSec={c.sourceStartSec}
sourceEndSec={c.sourceEndSec ?? c.sourceStartSec + dur}
+ gain={audioGainScalar(settings.audioGainDb)}
/>
<div className={styles.tlClipLabel}>
<span
diff --git a/src/components/ai-edition/v4/V4Timeline.waveform.test.tsx b/src/components/ai-edition/v4/V4Timeline.waveform.test.tsx
new file mode 100644
index 000000000..b5b2d9949
--- /dev/null
+++ b/src/components/ai-edition/v4/V4Timeline.waveform.test.tsx
@@ -0,0 +1,170 @@
+// @vitest-environment jsdom
+//
+// The output-gain slider is the only audio setting this editor still has, and it survived
+// review precisely because it is exactly reproducible: the same `10 ** (dB / 20)` scalar
+// drives a GainNode in the preview and a per-sample multiply in `finish_audio`. The timeline
+// waveform is the only place that claim is VISIBLE, so these tests pin it there.
+//
+// The export's half of the same claim lives in crates/compositor/src/audio.rs
+// (`output_trim_is_the_same_scalar_the_preview_applies` and
+// `output_is_clipped_to_full_scale_and_keeps_its_length`). Together they are what makes
+// "the waveform shows what you will hear" checkable rather than asserted.
+import "@testing-library/jest-dom";
+import { render } from "@testing-library/react";
+import { beforeAll, describe, expect, it, vi } from "vitest";
+
+const VIEWPORT_PX = 900;
+const CLIP_SEC = 10;
+/** ClipWaveform's own rule: one bar per ~125ms, floored at 20 and capped at 400. */
+const BAR_COUNT = Math.min(400, Math.max(20, Math.round(CLIP_SEC * 8)));
+
+const LOUD = 0.5;
+const QUIET = 0.1;
+
+vi.mock("@/contexts/I18nContext", () => ({
+ useScopedT: () => (key: string) => key,
+}));
+vi.mock("sonner", () => ({ toast: { error: vi.fn(), info: vi.fn(), success: vi.fn() } }));
+
+// Peaks are the SOURCE file's amplitude and never carry the gain — they are disk-cached
+// under path+size+mtime, so putting gain in them would be a cache-key redesign for what is
+// a scalar multiply. The first half of the recording is loud, the second half quiet, which
+// is what lets one render distinguish "scaled" from "clamped".
+vi.mock("@/hooks/useAudioPeaks", () => ({
+ useAudioPeaks: () => {
+ const blocks = 200;
+ const peaks = new Float32Array(blocks * 2);
+ for (let b = 0; b < blocks; b++) {
+ const amp = b < blocks / 2 ? LOUD : QUIET;
+ peaks[b * 2] = -amp;
+ peaks[b * 2 + 1] = amp;
+ }
+ return peaks;
+ },
+}));
+
+let gainDb = 0;
+vi.mock("@/lib/ai-edition/store/useEditorSettings", () => ({
+ useEditorSettings: () => ({
+ settings: { audioGainDb: gainDb },
+ hasDocument: true,
+ set: vi.fn(),
+ setLive: vi.fn(),
+ commit: vi.fn(),
+ }),
+}));
+
+import type { useTimeline } from "@/lib/ai-edition/store/useTimeline";
+import { V4Timeline } from "./V4Timeline";
+
+beforeAll(() => {
+ globalThis.ResizeObserver = class {
+ observe() {
+ /* noop */
+ }
+ unobserve() {
+ /* noop */
+ }
+ disconnect() {
+ /* noop */
+ }
+ } as unknown as typeof ResizeObserver;
+ // jsdom reports 0 for every box, which would leave the timeline "unmeasured".
+ Object.defineProperty(HTMLElement.prototype, "clientWidth", {
+ configurable: true,
+ get: () => VIEWPORT_PX,
+ });
+ Object.defineProperty(HTMLElement.prototype, "getBoundingClientRect", {
+ configurable: true,
+ value: () => ({
+ x: 0,
+ y: 0,
+ left: 0,
+ top: 0,
+ right: VIEWPORT_PX,
+ bottom: 100,
+ width: VIEWPORT_PX,
+ height: 100,
+ toJSON() {
+ /* unused by the component */
+ },
+ }),
+ });
+});
+
+/** Bar heights as the DOM carries them, in document order. */
+function renderBars(atGainDb: number): string[] {
+ gainDb = atGainDb;
+ const tl = {
+ clips: [
+ {
+ id: "c0",
+ assetId: "a1",
+ timelineStartSec: 0,
+ timelineEndSec: CLIP_SEC,
+ sourceStartSec: 0,
+ sourceEndSec: CLIP_SEC,
+ },
+ ],
+ assets: [{ id: "a1", label: "rec", durationSec: CLIP_SEC }],
+ annotationRegions: [],
+ speedRegions: [],
+ cameraFullscreenRegions: [],
+ zoomRegions: [],
+ trimRanges: [],
+ selection: null,
+ multiSelection: [],
+ clipSelection: null,
+ clearSelection: vi.fn(),
+ selectRegion: vi.fn(),
+ selectClip: vi.fn(),
+ updateAnnotationSpan: vi.fn(async () => undefined),
+ addZoom: vi.fn(async () => undefined),
+ };
+ const view = render(
+ <V4Timeline
+ tl={tl as unknown as ReturnType<typeof useTimeline>}
+ videoSources={[{ id: "a1", src: "file:///tmp/rec.mp4", label: "rec" }]}
+ setCurrentTime={vi.fn()}
+ playing={false}
+ onTogglePlay={vi.fn()}
+ onPrevClip={vi.fn()}
+ onNextClip={vi.fn()}
+ onEditClip={vi.fn()}
+ />,
+ );
+ const bars = Array.from(
+ document.querySelectorAll<HTMLElement>('[class*="tlWave"] span'),
+ (span) => span.style.height,
+ );
+ view.unmount();
+ return bars;
+}
+
+describe("ClipWaveform output gain", () => {
+ it("draws the source amplitude when the gain is unity", () => {
+ const bars = renderBars(0);
+ expect(bars).toHaveLength(BAR_COUNT);
+ expect(bars[0]).toBe("50%");
+ expect(bars[BAR_COUNT - 1]).toBe("10%");
+ });
+
+ it("scales quiet bars and flattens loud ones when the gain is boosted", () => {
+ // +12 dB is x3.98. The loud half would reach 199% — the number the old code
+ // computed and merely hid behind the clip's `overflow` — and pins flat at 100%
+ // instead, because `finish_audio` clamps the samples it writes to +/-1. The quiet
+ // half is nowhere near full scale, so it just gets louder. That difference between
+ // the two halves IS clipping, drawn.
+ const bars = renderBars(12);
+ expect(bars[0]).toBe("100%");
+ expect(bars[BAR_COUNT - 1]).toBe("40%");
+ });
+
+ it("shrinks the bars when the gain is cut, down to the empty-clip floor", () => {
+ // -12 dB is x0.251. The quiet half lands at 2.5%, below the 8% floor that exists so
+ // an empty clip still reads as a clip — the floor is not amplitude and is not scaled.
+ const bars = renderBars(-12);
+ expect(bars[0]).toBe("13%");
+ expect(bars[BAR_COUNT - 1]).toBe("8%");
+ });
+});
diff --git a/src/lib/ai-edition/store/editorSettings.ts b/src/lib/ai-edition/store/editorSettings.ts
index b86bf6ba5..62b7e8348 100644
--- a/src/lib/ai-edition/store/editorSettings.ts
+++ b/src/lib/ai-edition/store/editorSettings.ts
@@ -47,6 +47,17 @@ import type { AxcutDocument } from "../schema";
* region, and near a cut the export pulls audio across the junction while the preview cannot. */
export const AUDIO_GAIN_DB_LIMIT = 12;
+/** dB to the linear scalar every side of the boundary multiplies by.
+ *
+ * Exported rather than written out three times. `finish_audio` applies
+ * `10f32.powf(gain_db / 20.0)` per sample; the preview feeds this to a `GainNode`; the
+ * timeline waveform scales its bars by it. The claim those three make together — that what
+ * you see is what you hear is what you export — only holds while they are the same number,
+ * and a hand-copied `10 ** (dB / 20)` is exactly how that stops being true. */
+export function audioGainScalar(gainDb: number): number {
+ return 10 ** (gainDb / 20);
+}
+
export interface EditorSettingsSnapshot {
wallpaper: string;
aspectRatio: AspectRatio;