Skip to content

🎥 Make videos programmatically with React

3.4 KB
Raw Blame
import {spawn} from 'child_process';
import {existsSync, writeFileSync} from 'fs';
import path from 'path';
import {fileURLToPath} from 'url';

const sampleCount = 2000;

type SfxExport = {
	readonly name: string;
	readonly fileName: string;
	readonly url: string;
};

const docsRoot = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.join(docsRoot, '..', '..');
const sfxIndex = path.join(repoRoot, 'packages', 'sfx', 'src', 'index.ts');
const mediaRoot = path.join(repoRoot, 'packages', 'remotion-media');
const outputFile = path.join(
	docsRoot,
	'components',
	'sfx-demos',
	'sfx-waveforms.ts',
);

const source = await Bun.file(sfxIndex).text();

const sfxExports: SfxExport[] = Array.from(
	source.matchAll(
		/export const\s+([a-zA-Z0-9_]+)\s*=\s*'https:\/\/remotion\.media\/([^']+\.wav)'/g,
	),
	(match) => {
		const fileName = decodeURIComponent(match[2]);
		return {
			name: match[1],
			fileName,
			url: `https://remotion.media/${match[2]}`,
		};
	},
);

if (sfxExports.length === 0) {
	throw new Error(`No @remotion/sfx exports found in ${sfxIndex}`);
}

const readPcm = (file: string): Promise<Buffer> => {
	return new Promise((resolve, reject) => {
		const child = spawn(
			'ffmpeg',
			['-v', 'error', '-i', file, '-ac', '1', '-f', 'f32le', '-'],
			{
				stdio: ['ignore', 'pipe', 'pipe'],
			},
		);

		const stdout: Buffer[] = [];
		const stderr: Buffer[] = [];

		child.stdout.on('data', (chunk) => stdout.push(chunk));
		child.stderr.on('data', (chunk) => stderr.push(chunk));

		child.on('error', reject);
		child.on('close', (code) => {
			if (code === 0) {
				resolve(Buffer.concat(stdout));
				return;
			}

			reject(
				new Error(
					`ffmpeg failed for ${file}: ${Buffer.concat(stderr).toString('utf8')}`,
				),
			);
		});
	});
};

const sampleWaveform = async (file: string): Promise<Buffer> => {
	const pcm = await readPcm(file);
	const floatCount = Math.floor(
		pcm.byteLength / Float32Array.BYTES_PER_ELEMENT,
	);
	if (floatCount === 0) {
		throw new Error(`No samples found in ${file}`);
	}

	const view = new DataView(pcm.buffer, pcm.byteOffset, pcm.byteLength);
	const peaks: number[] = [];
	for (let sample = 0; sample < sampleCount; sample++) {
		const start = Math.floor((sample / sampleCount) * floatCount);
		const end = Math.max(
			start + 1,
			Math.floor(((sample + 1) / sampleCount) * floatCount),
		);

		let peak = 0;
		for (let index = start; index < end; index++) {
			peak = Math.max(
				peak,
				Math.abs(view.getFloat32(index * Float32Array.BYTES_PER_ELEMENT, true)),
			);
		}

		peaks.push(peak);
	}

	const maxPeak = Math.max(...peaks);
	return Buffer.from(
		peaks.map((peak) => {
			if (maxPeak === 0) {
				return 0;
			}

			return Math.round((peak / maxPeak) * 255);
		}),
	);
};

const entries: string[] = [];
for (const sfx of sfxExports) {
	const file = path.join(mediaRoot, sfx.fileName);
	if (!existsSync(file)) {
		throw new Error(`Missing local sound file for ${sfx.name}: ${file}`);
	}

	const sampled = await sampleWaveform(file);
	entries.push(`\t'${sfx.url}': '${sampled.toString('base64')}',`);
	console.log(`Sampled ${sfx.fileName}`);
}

const output = `// Generated by packages/docs/generate-sfx-waveforms.ts
// Do not edit by hand.

export const SFX_WAVEFORM_SAMPLE_COUNT = ${sampleCount};

export const sfxWaveforms: Record<string, string> = {
${entries.join('\n')}
};
`;

writeFileSync(outputFile, output);
console.log(`Wrote ${outputFile}`);