import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterAll, describe, expect, it } from "vitest"; import type { AudioElement } from "@hyperframes/engine"; import { findFfBinary } from "@hyperframes/parsers/ff-binaries"; import { inspectAudio, type AudioCheckDependencies } from "./checkAudio.js"; import type { ProjectMedia } from "./projectMedia.js"; const RATE = 48_000; const dir = mkdtempSync(join(tmpdir(), "hf-check-audio-")); afterAll(() => rmSync(dir, { recursive: true, force: true })); /** A mono 16-bit WAV of `seconds`, each sample from `fill`; `byteRate` is the header's claim. */ function wav( name: string, seconds: number, fill: (t: number) => number, byteRate = RATE * 2, ): string { const frames = Math.round(seconds * RATE); const data = Buffer.alloc(frames * 2); for (let i = 0; i < frames; i++) data.writeInt16LE(Math.round(fill(i / RATE) * 32767), i * 2); const header = Buffer.alloc(44); header.write("RIFF", 0); header.writeUInt32LE(36 + data.length, 4); header.write("WAVEfmt ", 8); header.writeUInt32LE(16, 16); header.writeUInt16LE(1, 20); header.writeUInt16LE(1, 22); header.writeUInt32LE(RATE, 24); header.writeUInt32LE(byteRate, 28); header.writeUInt16LE(2, 32); header.writeUInt16LE(16, 34); header.write("data", 36); header.writeUInt32LE(data.length, 40); writeFileSync(join(dir, name), Buffer.concat([header, data])); return name; } const tone = (t: number) => 0.5 * Math.sin(2 * Math.PI * 440 * t); const silent = () => 0; /** Sound only after `at` seconds. */ const lateTone = (at: number) => (t: number) => (t < at ? 0 : tone(t)); function clip(src: string, overrides: Partial = {}): AudioElement { return { id: src.replace(/\W/g, "-"), src, start: 0, end: 2, mediaStart: 0, layer: 0, volume: 1, type: "audio", ...overrides, }; } function media( audios: AudioElement[], videos: ProjectMedia["videos"] = [], html = "", ): ProjectMedia { return { audios, videos, images: [], html }; } const codes = async (project: ProjectMedia) => (await inspectAudio(dir, "index.html", project)).map((f) => `${f.code}:${f.selector}`); const ffmpeg = findFfBinary("ffmpeg") && findFfBinary("ffprobe"); describe.skipIf(!ffmpeg)("inspectAudio", () => { wav("tone.wav", 3, tone); wav("silent.wav", 3, silent); wav("late.wav", 4, lateTone(2.5)); // Long enough to be sampled at spots first; sound only between the spots. wav("long-silent.wav", 20, silent); wav("long-gap.wav", 20, (t) => (t > 5 && t < 6 ? tone(t) : 0)); // Its header claims twice the real byte rate, as some speech generators write it. wav("misstated-rate.wav", 8, tone, RATE * 4); // Not audio at all: the render's audio probe rejects it and the whole mix fails. writeFileSync(join(dir, "notes.wav"), "RIFF but not really a wave file"); // A 1x1 PNG: it probes, but as a still image, so render refuses it as an