summaryrefslogtreecommitdiff
path: root/apps/web/src/timeline/components/audio-waveform.tsx
blob: 7777bc0995c88ed0c597418bee449183bb51c2fa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
"use client";

import { useCallback, useEffect, useLayoutEffect, useRef } from "react";
import { useResizeObserver } from "@/hooks/use-resize-observer";
import { TIMELINE_AUDIO_WAVEFORM_COLOR } from "./theme";
import {
	buildWaveformSampleBuckets,
	sampleSourceWaveformSummary,
	type SourceWaveformSummary,
} from "@/media/waveform-summary";
import type { RetimeConfig } from "@/timeline";
import { getBarFractionFromOutputAmplitude } from "@/timeline/audio-display";
import { waveformCache } from "@/services/waveform-cache/service";
import { findScrollParent } from "@/utils/browser";
import { cn } from "@/utils/ui";

const BAR_WIDTH = 1;
const BAR_GAP = 1;
const BAR_STEP = BAR_WIDTH + BAR_GAP;
const WAVEFORM_BURN_COLOR = "rgba(255, 110, 20, 0.9)";
export const WAVEFORM_GAIN_SAMPLE_COUNT = 200;

function sampleGainAtClipTime({
	samples,
	clipTimeSec,
	clipDurationSec,
}: {
	samples: number[];
	clipTimeSec: number;
	clipDurationSec: number;
}): number {
	if (samples.length === 0 || clipDurationSec <= 0) {
		return 1;
	}

	const progress = Math.max(0, Math.min(1, clipTimeSec / clipDurationSec));
	const rawIndex = progress * (samples.length - 1);
	const lo = Math.floor(rawIndex);
	const hi = Math.min(samples.length - 1, lo + 1);
	return samples[lo] + (samples[hi] - samples[lo]) * (rawIndex - lo);
}

interface AudioWaveformProps {
	sourceKey: string;
	sourceFile?: File;
	audioUrl?: string;
	audioBuffer?: AudioBuffer;
	gainSamples?: number[];
	pixelsPerSecond: number;
	clipDurationSec: number;
	retime?: RetimeConfig;
	sourceStartSec: number;
	color?: string;
	burnColor?: string;
	className?: string;
}

export function AudioWaveform({
	sourceKey,
	sourceFile,
	audioUrl,
	audioBuffer,
	gainSamples,
	pixelsPerSecond,
	clipDurationSec,
	retime,
	sourceStartSec,
	color = TIMELINE_AUDIO_WAVEFORM_COLOR,
	burnColor = WAVEFORM_BURN_COLOR,
	className = "",
}: AudioWaveformProps) {
	const canvasRef = useRef<HTMLCanvasElement>(null);
	const containerRef = useRef<HTMLDivElement>(null);
	const summaryRef = useRef<SourceWaveformSummary | null>(null);
	const gainSamplesRef = useRef<number[] | undefined>(gainSamples);
	const pixelsPerSecondRef = useRef<number>(pixelsPerSecond);
	const clipDurationSecRef = useRef<number>(clipDurationSec);
	const retimeRef = useRef<RetimeConfig | undefined>(retime);
	const sourceStartSecRef = useRef<number>(sourceStartSec);
	const scrollParentRef = useRef<HTMLElement | null>(null);
	const heightRef = useRef<number>(0);
	const lastRenderSignatureRef = useRef<string | null>(null);

	gainSamplesRef.current = gainSamples;
	pixelsPerSecondRef.current = pixelsPerSecond;
	clipDurationSecRef.current = clipDurationSec;
	retimeRef.current = retime;
	sourceStartSecRef.current = sourceStartSec;

	const clearCanvas = useCallback(() => {
		const canvas = canvasRef.current;
		if (!canvas) {
			return;
		}

		const ctx = canvas.getContext("2d");
		if (ctx) {
			ctx.setTransform(1, 0, 0, 1, 0, 0);
			ctx.clearRect(0, 0, canvas.width, canvas.height);
		}
		lastRenderSignatureRef.current = null;
	}, []);

	const drawVisible = useCallback(() => {
		const container = containerRef.current;
		const canvas = canvasRef.current;
		const summary = summaryRef.current;
		const height = heightRef.current;

		if (!container || !canvas || !summary || height <= 0) {
			clearCanvas();
			return;
		}

		const containerRect = container.getBoundingClientRect();
		const elementWidth = containerRect.width;
		if (elementWidth <= 0) {
			clearCanvas();
			return;
		}

		const scrollParent = scrollParentRef.current;

		let clipLeft: number;
		let clipRight: number;

		if (scrollParent) {
			const parentRect = scrollParent.getBoundingClientRect();
			clipLeft = Math.max(0, parentRect.left - containerRect.left);
			clipRight = Math.min(elementWidth, parentRect.right - containerRect.left);
		} else {
			clipLeft = Math.max(0, -containerRect.left);
			clipRight = Math.min(
				elementWidth,
				window.innerWidth - containerRect.left,
			);
		}

		const visibleWidth = clipRight - clipLeft;
		if (visibleWidth <= 0) {
			clearCanvas();
			return;
		}

		const dpr = window.devicePixelRatio || 1;
		const canvasW = Math.max(1, Math.ceil(visibleWidth * dpr));
		const canvasH = Math.max(1, Math.round(height * dpr));
		const barCount = Math.max(1, Math.floor(visibleWidth / BAR_STEP));
		const pixelsPerSecondValue = pixelsPerSecondRef.current;
		const clipDurationSecValue = clipDurationSecRef.current;
		const samples = gainSamplesRef.current;
		const renderSignature = JSON.stringify({
			elementWidth,
			clipLeft,
			clipRight,
			visibleWidth,
			canvasW,
			canvasH,
			barCount,
			dpr,
			clipDurationSec: clipDurationSecValue,
			sourceStartSec: sourceStartSecRef.current,
			pixelsPerSecond: pixelsPerSecondValue,
			retime: retimeRef.current ?? null,
			summarySourceKey: summary.sourceKey,
			summarySampleRate: summary.sampleRate,
			summaryTotalSamples: summary.totalSamples,
			summaryBucketSize: summary.bucketSize,
			gainSamples: samples ?? null,
			color,
			burnColor,
		});
		if (lastRenderSignatureRef.current === renderSignature) {
			return;
		}
		lastRenderSignatureRef.current = renderSignature;

		canvas.width = canvasW;
		canvas.height = canvasH;
		canvas.style.width = `${visibleWidth}px`;
		canvas.style.height = `${height}px`;
		canvas.style.left = `${clipLeft}px`;

		const backingScaleX = dpr;
		const backingScaleY = canvasH / height;

		const sampleBuckets = buildWaveformSampleBuckets({
			clipLeftPx: clipLeft,
			clipRightPx: clipRight,
			barCount,
			pixelsPerSecond: pixelsPerSecondValue,
			clipDurationSec: clipDurationSecValue,
			sourceStartSec: sourceStartSecRef.current,
			retime: retimeRef.current,
			sampleRate: summary.sampleRate,
			maxSampleExclusive: summary.totalSamples,
			barStepPx: BAR_STEP,
		});
		const amplitudes = sampleSourceWaveformSummary({
			summary,
			buckets: sampleBuckets,
		});

		const ctx = canvas.getContext("2d");
		if (!ctx) {
			return;
		}

		ctx.setTransform(1, 0, 0, 1, 0, 0);
		ctx.clearRect(0, 0, canvasW, canvasH);

		const clipBottom = canvasH;

		for (let i = 0; i < barCount; i++) {
			const barCenterPx = clipLeft + i * BAR_STEP + BAR_WIDTH * 0.5;
			const clipCenterSec = Math.max(
				0,
				Math.min(clipDurationSecValue, barCenterPx / pixelsPerSecondValue),
			);
			const gain =
				samples != null
					? sampleGainAtClipTime({
							samples,
							clipTimeSec: clipCenterSec,
							clipDurationSec: clipDurationSecValue,
						})
					: 1;
			const amplitude = Math.max(0, amplitudes[i] ?? 0);
			const outputAmplitude = amplitude * Math.max(0, gain);
			const fraction = getBarFractionFromOutputAmplitude({ outputAmplitude });
			const barH = fraction > 0 ? Math.max(1, fraction * height) : 0;
			if (barH <= 0) {
				continue;
			}

			const barLeft = i * BAR_STEP;
			const barRight = barLeft + BAR_WIDTH;
			const deviceLeft = Math.round(barLeft * backingScaleX);
			const deviceRight = Math.max(
				deviceLeft + 1,
				Math.round(barRight * backingScaleX),
			);
			const deviceTop = Math.round((height - barH) * backingScaleY);
			const deviceHeight = Math.max(1, clipBottom - deviceTop);

			ctx.fillStyle = color;
			ctx.fillRect(
				deviceLeft,
				deviceTop,
				deviceRight - deviceLeft,
				deviceHeight,
			);

			if (outputAmplitude > 1) {
				const burnHeight = Math.max(1, Math.round(BAR_WIDTH * backingScaleY));
				ctx.fillStyle = burnColor;
				ctx.fillRect(
					deviceLeft,
					deviceTop,
					deviceRight - deviceLeft,
					burnHeight,
				);
			}
		}
	}, [burnColor, clearCanvas, color]);

	useEffect(() => {
		let isCancelled = false;
		summaryRef.current = null;
		clearCanvas();

		void waveformCache
			.getSourceSummary({
				sourceKey,
				audioBuffer,
				sourceFile,
				audioUrl,
			})
			.then((summary) => {
				if (isCancelled) {
					return;
				}
				summaryRef.current = summary;
				drawVisible();
			})
			.catch(() => {
				// Waveform loading failed (e.g. corrupt file, unsupported format).
				// Fail silently — a missing waveform is preferable to an error state.
				if (!isCancelled) {
					clearCanvas();
				}
			});

		return () => {
			isCancelled = true;
		};
	}, [audioBuffer, audioUrl, clearCanvas, drawVisible, sourceFile, sourceKey]);

	// biome-ignore lint/correctness/useExhaustiveDependencies: these props are mirrored into refs during render, but the effect must still re-run to redraw when they change.
	useLayoutEffect(() => {
		drawVisible();
	}, [
		drawVisible,
		gainSamples,
		pixelsPerSecond,
		clipDurationSec,
		retime,
		sourceStartSec,
	]);

	useEffect(() => {
		const container = containerRef.current;
		if (!container) {
			return;
		}

		scrollParentRef.current = findScrollParent({ element: container });
		const scrollParent = scrollParentRef.current;
		if (!scrollParent) {
			return;
		}

		const handleScroll = () => {
			drawVisible();
		};
		scrollParent.addEventListener("scroll", handleScroll, { passive: true });
		return () => scrollParent.removeEventListener("scroll", handleScroll);
	}, [drawVisible]);

	const onResize = useCallback(
		(entry: ResizeObserverEntry) => {
			heightRef.current = entry.contentRect.height;
			drawVisible();
		},
		[drawVisible],
	);

	useResizeObserver({ ref: containerRef, onResize });

	return (
		<div ref={containerRef} className={cn("relative size-full", className)}>
			<canvas ref={canvasRef} className="absolute bottom-0" />
		</div>
	);
}