|
| 1 | +// Run the shared beat detection (@hyperframes/core/beats) in a headless Chrome |
| 2 | +// so results match the Studio exactly — same Web Audio decode + same |
| 3 | +// bpm-detective. Used by the `beats` CLI command to write the beat file before |
| 4 | +// the Studio is ever opened. |
| 5 | + |
| 6 | +import { existsSync, readFileSync } from "node:fs"; |
| 7 | +import { createRequire } from "node:module"; |
| 8 | +import { dirname, join } from "node:path"; |
| 9 | +import { fileURLToPath } from "node:url"; |
| 10 | +import type { Browser, Page } from "puppeteer-core"; |
| 11 | + |
| 12 | +const require = createRequire(import.meta.url); |
| 13 | + |
| 14 | +// The detection is browser code. We need it as an IIFE that exposes |
| 15 | +// analyzeMusicFromBuffer on the page. Prefer the artifact prebuilt at CLI build |
| 16 | +// time (shipped in dist); fall back to bundling from core source at runtime |
| 17 | +// (dev/monorepo, where core's src is on disk). |
| 18 | +let bundlePromise: Promise<string> | null = null; |
| 19 | + |
| 20 | +function findPrebuiltBundle(): string | null { |
| 21 | + const here = dirname(fileURLToPath(import.meta.url)); |
| 22 | + const candidates = [ |
| 23 | + join(here, "beat-analyzer.global.js"), // dist root (tsup-bundled cli) |
| 24 | + join(here, "../beat-analyzer.global.js"), // dist/beats → dist |
| 25 | + join(here, "../dist/beat-analyzer.global.js"), |
| 26 | + ]; |
| 27 | + for (const p of candidates) { |
| 28 | + if (existsSync(p)) return p; |
| 29 | + } |
| 30 | + return null; |
| 31 | +} |
| 32 | + |
| 33 | +async function buildFromCoreSource(): Promise<string> { |
| 34 | + const esbuild = await import("esbuild"); |
| 35 | + const coreRoot = dirname(require.resolve("@hyperframes/core/package.json")); |
| 36 | + const entry = join(coreRoot, "src/beats/beatDetection.ts"); |
| 37 | + const result = await esbuild.build({ |
| 38 | + stdin: { |
| 39 | + contents: |
| 40 | + `import { analyzeMusicFromBuffer } from ${JSON.stringify(entry)};\n` + |
| 41 | + `globalThis.__hfAnalyze = analyzeMusicFromBuffer;`, |
| 42 | + resolveDir: coreRoot, |
| 43 | + loader: "ts", |
| 44 | + }, |
| 45 | + bundle: true, |
| 46 | + format: "iife", |
| 47 | + platform: "browser", |
| 48 | + target: "es2020", |
| 49 | + write: false, |
| 50 | + }); |
| 51 | + const out = result.outputFiles?.[0]; |
| 52 | + if (!out) throw new Error("Failed to bundle beat analyzer"); |
| 53 | + return out.text; |
| 54 | +} |
| 55 | + |
| 56 | +function buildAnalyzerBundle(): Promise<string> { |
| 57 | + if (bundlePromise) return bundlePromise; |
| 58 | + bundlePromise = (async () => { |
| 59 | + const prebuilt = findPrebuiltBundle(); |
| 60 | + if (prebuilt) return readFileSync(prebuilt, "utf8"); |
| 61 | + return buildFromCoreSource(); |
| 62 | + })().catch((err) => { |
| 63 | + bundlePromise = null; // don't poison the process with a cached rejection |
| 64 | + throw err; |
| 65 | + }); |
| 66 | + return bundlePromise; |
| 67 | +} |
| 68 | + |
| 69 | +export interface HeadlessBeatResult { |
| 70 | + beatTimes: number[]; |
| 71 | + beatStrengths: number[]; |
| 72 | + bpm: number | null; |
| 73 | + bpmConfidence: string; |
| 74 | +} |
| 75 | + |
| 76 | +// Guard against pathological inputs that would blow CDP message limits when |
| 77 | +// transferred to the page as base64 (≈ +33% over the raw bytes). |
| 78 | +const MAX_AUDIO_BYTES = 80 * 1024 * 1024; |
| 79 | + |
| 80 | +// Runs inside the headless page: decode the base64 audio and analyze it. |
| 81 | +function inPageAnalyze(data: string) { |
| 82 | + const bin = atob(data); |
| 83 | + const bytes = new Uint8Array(bin.length); |
| 84 | + for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i); |
| 85 | + const win = window as unknown as { |
| 86 | + AudioContext: typeof AudioContext; |
| 87 | + webkitAudioContext?: typeof AudioContext; |
| 88 | + __hfAnalyze?: (buffer: AudioBuffer) => Promise<HeadlessBeatResult>; |
| 89 | + }; |
| 90 | + if (typeof win.__hfAnalyze !== "function") throw new Error("beat analyzer not loaded"); |
| 91 | + const ctx = new (win.AudioContext || win.webkitAudioContext!)(); |
| 92 | + return ( |
| 93 | + ctx |
| 94 | + .decodeAudioData(bytes.buffer) |
| 95 | + .then((buf) => win.__hfAnalyze!(buf)) |
| 96 | + // analyzeMusicFromBuffer also returns the decoded PCM (channelData) + sampleRate; |
| 97 | + // project to only the fields we need so page.evaluate doesn't serialize an |
| 98 | + // ~8-million-element Float32Array back across the CDP boundary. |
| 99 | + .then((r) => ({ |
| 100 | + beatTimes: r.beatTimes, |
| 101 | + beatStrengths: r.beatStrengths, |
| 102 | + bpm: r.bpm, |
| 103 | + bpmConfidence: r.bpmConfidence, |
| 104 | + })) |
| 105 | + .finally(() => ctx.close()) |
| 106 | + ); |
| 107 | +} |
| 108 | + |
| 109 | +// Load the analyzer bundle into the page, run analysis, and surface in-page |
| 110 | +// errors (decode/codec failures, missing global) instead of an opaque rejection. |
| 111 | +async function detectOnPage(page: Page, bundle: string, b64: string): Promise<HeadlessBeatResult> { |
| 112 | + const pageErrors: string[] = []; |
| 113 | + page.on("pageerror", (e) => { |
| 114 | + pageErrors.push((e as Error).message); |
| 115 | + }); |
| 116 | + page.on("console", (m) => { |
| 117 | + if (m.type() === "error") pageErrors.push(m.text()); |
| 118 | + }); |
| 119 | + await page.setContent("<!doctype html><html><body></body></html>"); |
| 120 | + await page.addScriptTag({ content: bundle }); |
| 121 | + try { |
| 122 | + return (await page.evaluate(inPageAnalyze, b64)) as HeadlessBeatResult; |
| 123 | + } catch (err) { |
| 124 | + const detail = pageErrors.length ? ` (${pageErrors.join("; ")})` : ""; |
| 125 | + throw new Error(`${err instanceof Error ? err.message : String(err)}${detail}`); |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +/** Decode + analyze the given audio bytes in headless Chrome. */ |
| 130 | +export async function analyzeBeatsHeadless(audioBytes: Buffer): Promise<HeadlessBeatResult> { |
| 131 | + if (audioBytes.length > MAX_AUDIO_BYTES) { |
| 132 | + const mb = Math.round(audioBytes.length / 1e6); |
| 133 | + throw new Error( |
| 134 | + `Audio file too large for headless analysis (${mb}MB > ${MAX_AUDIO_BYTES / 1e6}MB).`, |
| 135 | + ); |
| 136 | + } |
| 137 | + const bundle = await buildAnalyzerBundle(); |
| 138 | + const { ensureBrowser } = await import("../browser/manager.js"); |
| 139 | + const puppeteer = await import("puppeteer-core"); |
| 140 | + const browser = await ensureBrowser(); |
| 141 | + const chrome: Browser = await puppeteer.default.launch({ |
| 142 | + headless: true, |
| 143 | + executablePath: browser.executablePath, |
| 144 | + args: ["--no-sandbox", "--disable-dev-shm-usage", "--autoplay-policy=no-user-gesture-required"], |
| 145 | + }); |
| 146 | + try { |
| 147 | + const page = await chrome.newPage(); |
| 148 | + return await detectOnPage(page, bundle, audioBytes.toString("base64")); |
| 149 | + } finally { |
| 150 | + await chrome.close(); |
| 151 | + } |
| 152 | +} |
0 commit comments