/ music / acoustic-base
Sign in
music / acoustic-base
acoustic-base / scripts / build_sf2.ts
72 lines · 4.2 KBBlameHistoryRaw
1// Build the SoundFont from the simulation: render every sampled note and velocity (in parallel
2// worker threads), process and level them, and write the SF2, plus the processed samples as WAVs
3// (renders/sf2wav/) and the parameters used (next to the SF2, as .json).
4// node scripts/build_sf2.ts [--params presets/x.json] [--body bodies/fe_default.json] [--out acoustic-bass.sf2] [--workers 8]
5import fs from "node:fs";
6import os from "node:os";
7import path from "node:path";
8import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
9import { defaultParams, mergeParams, type Params } from "../src/core/params.ts";
10import { bodyFor } from "./fe_cache.ts";
11import { mixOutput, renderNote } from "../src/core/engine.ts";
12import { buildSf2, sampleJobs, noteName, type SampleJob } from "../src/core/sf2.ts";
13import { encodeWav } from "../src/core/dsp.ts";
14import type { BodyModel } from "../src/core/types.ts";
16const ROOT = path.join(import.meta.dirname, "..");
17const DEFAULT_OUT = path.join(ROOT, "acoustic-bass.sf2");
19if (!isMainThread) {
20 const { params, body, jobs } = workerData as { params: Params; body: BodyModel; jobs: (SampleJob & { idx: number })[] };
21 for (const j of jobs) {
22 const r = renderNote(params, body, { note: j.note, velocity: j.velocity, duration: j.length });
23 const x = mixOutput(params, r.mic, r.pickup);
24 parentPort!.postMessage({ idx: j.idx, x, elapsed: r.elapsed }, [x.buffer as ArrayBuffer]);
25 }
26} else {
27 const args = process.argv.slice(2);
28 let params = defaultParams();
29 let bodyFile = "";
30 let out = DEFAULT_OUT;
31 let nw = Math.max(1, Math.min(os.availableParallelism() - 1, 10));
32 for (let i = 0; i < args.length; i++) {
33 if (args[i] === "--params") params = mergeParams(JSON.parse(fs.readFileSync(args[++i], "utf8")));
34 else if (args[i] === "--body") bodyFile = args[++i];
35 else if (args[i] === "--out") out = path.resolve(args[++i]);
36 else if (args[i] === "--workers") nw = Number(args[++i]);
37 }
38 params.engine.oversample = params.sf2.oversample;
39 let body: BodyModel;
40 if (bodyFile) body = JSON.parse(fs.readFileSync(bodyFile, "utf8"));
41 else body = bodyFor(params);
43 const jobs = sampleJobs(params).map((j, idx) => ({ ...j, idx }));
44 console.log(`${jobs.length} renders (${params.sf2.count} notes x ${params.sf2.velocities.length} layers), ${body.modes.length} body modes (${body.source}), ${nw} workers`);
45 const results: Float32Array[] = new Array(jobs.length);
46 const t0 = Date.now();
47 let done = 0;
48 // longest first, round-robin
49 const order = [...jobs].sort((a, b) => b.length - a.length);
50 await Promise.all(Array.from({ length: nw }, (_, w) => new Promise<void>((resolve, reject) => {
51 const mine = order.filter((_, i) => i % nw === w);
52 if (!mine.length) return resolve();
53 const worker = new Worker(new URL(import.meta.url), { workerData: { params, body, jobs: mine } });
54 worker.on("message", (m: { idx: number; x: Float32Array; elapsed: number }) => {
55 results[m.idx] = m.x; done++;
56 const j = jobs[m.idx];
57 process.stdout.write(`\r ${done}/${jobs.length} ${noteName(j.note)} v${j.velocity} (${m.elapsed.toFixed(1)} s) `);
58 });
59 worker.on("error", reject);
60 worker.on("exit", () => resolve());
61 })));
62 console.log(`\nrendered in ${((Date.now() - t0) / 1000).toFixed(0)} s`);
63 const fs0 = params.engine.sampleRate;
64 const comment = `Pizzicato double bass simulated by acoustic-base: steel strings (modal ${params.engine.stringModel} string model, two polarisations, tension modulation, finger pluck), ${body.source} body (${body.modes.length} modes), mic ${params.output.micMix} + bridge pickup ${params.output.pickupMix}.`;
65 const { sf2, samples } = buildSf2(params, jobs, results, fs0, comment);
66 fs.writeFileSync(out, sf2);
67 fs.writeFileSync(out.replace(/\.sf2$/, ".json"), JSON.stringify(params, null, 2));
68 const wavDir = path.join(ROOT, "renders", "sf2wav");
69 fs.mkdirSync(wavDir, { recursive: true });
70 jobs.forEach((j, i) => fs.writeFileSync(path.join(wavDir, `${noteName(j.note).replace("#", "s")}_v${j.velocity}.wav`), encodeWav(Array.from(samples[i], (v) => v / 32768), fs0)));
71 console.log(`${path.relative(process.cwd(), out)}: ${jobs.length} samples, ${(sf2.length / 1e6).toFixed(1)} MB`);
↑↓ move↵openescclose