Files
client/scripts/build-denoise.mjs
T

105 lines
4.5 KiB
JavaScript

#!/usr/bin/env node
// Builds the microphone noise-reduction DSP (dsp/, sonora WebRTC NS) for wasm32-unknown-unknown
// and installs it as app/renderer/assets/audio/denoise.wasm.
// node scripts/build-denoise.mjs
// Needs the Rust toolchain with the wasm32-unknown-unknown target (rustup target add
// wasm32-unknown-unknown) and dsp/Cargo.lock (cargo generate-lockfile --manifest-path dsp/Cargo.toml).
// Cargo is taken from $CARGO, else PATH, else ~/.cargo/bin. The installed asset is replaced only
// after a successful build whose output is a valid module with no imports and the full export ABI.
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import crypto from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const CRATE = path.join(ROOT, 'dsp');
const MANIFEST = path.join(CRATE, 'Cargo.toml');
const LOCKFILE = path.join(CRATE, 'Cargo.lock');
const TARGET = 'wasm32-unknown-unknown';
const TARGET_DIR = path.join(CRATE, 'target');
const ARTIFACT = path.join(TARGET_DIR, TARGET, 'release', 'teamspeach_denoise.wasm');
const ASSET = path.join(ROOT, 'app', 'renderer', 'assets', 'audio', 'denoise.wasm');
const REQUIRED_EXPORTS = {
memory: 'memory',
dsp_new: 'function',
dsp_input: 'function',
dsp_process: 'function',
dsp_reset: 'function',
dsp_free: 'function',
};
function fail(message) {
console.error(`build-denoise: ${message}`);
process.exit(1);
}
function works(cargo) {
const probe = spawnSync(cargo, ['--version'], { encoding: 'utf8' });
return probe.status === 0;
}
function findCargo() {
if (process.env.CARGO) {
if (!works(process.env.CARGO)) fail(`$CARGO=${process.env.CARGO} does not run`);
return process.env.CARGO;
}
if (works('cargo')) return 'cargo';
const installed = path.join(os.homedir(), '.cargo', 'bin', process.platform === 'win32' ? 'cargo.exe' : 'cargo');
if (fs.existsSync(installed) && works(installed)) return installed;
fail('cargo not found ($CARGO, PATH, ~/.cargo/bin); install Rust from https://rustup.rs');
}
const cargo = findCargo();
if (!fs.existsSync(LOCKFILE)) {
fail(`missing ${path.relative(ROOT, LOCKFILE)}; create it with: cargo generate-lockfile --manifest-path dsp/Cargo.toml`);
}
// Never let a previous build's output stand in for this one.
fs.rmSync(ARTIFACT, { force: true });
// A cargo found outside PATH (e.g. rustup's ~/.cargo/bin proxy) needs its directory on PATH for rustc.
const env = { ...process.env };
if (path.isAbsolute(cargo)) {
const pathKey = Object.keys(env).find((key) => key.toUpperCase() === 'PATH') ?? 'PATH';
env[pathKey] = [path.dirname(cargo), env[pathKey]].filter(Boolean).join(path.delimiter);
}
delete env.CARGO_TARGET_DIR;
delete env.CARGO_BUILD_TARGET;
const args = ['build', '--release', '--locked', '--manifest-path', MANIFEST, '--target', TARGET, '--target-dir', TARGET_DIR];
console.log(`build-denoise: ${cargo} ${args.join(' ')}`);
const build = spawnSync(cargo, args, { cwd: ROOT, env, stdio: 'inherit' });
if (build.error) fail(`could not run cargo: ${build.error.message}`);
if (build.status !== 0) fail(`cargo exited with ${build.status ?? build.signal}`);
if (!fs.existsSync(ARTIFACT)) fail(`cargo succeeded but ${path.relative(ROOT, ARTIFACT)} is missing`);
const bytes = fs.readFileSync(ARTIFACT);
const MAGIC = Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]); // "\0asm", version 1
if (bytes.length < MAGIC.length || !bytes.subarray(0, MAGIC.length).equals(MAGIC)) {
fail('build output is not a WebAssembly version-1 binary');
}
let module;
try {
module = new WebAssembly.Module(bytes);
} catch (err) {
fail(`build output does not compile: ${err.message}`);
}
const imports = WebAssembly.Module.imports(module);
if (imports.length) {
fail(`module must import nothing (the AudioWorklet instantiates it with {}), found: ${imports.map((i) => `${i.module}.${i.name}`).join(', ')}`);
}
const exports = new Map(WebAssembly.Module.exports(module).map((e) => [e.name, e.kind]));
for (const [name, kind] of Object.entries(REQUIRED_EXPORTS)) {
if (exports.get(name) !== kind) fail(`missing ${kind} export "${name}"`);
}
fs.mkdirSync(path.dirname(ASSET), { recursive: true });
const staging = `${ASSET}.tmp-${process.pid}`;
fs.writeFileSync(staging, bytes);
fs.renameSync(staging, ASSET);
const sha256 = crypto.createHash('sha256').update(bytes).digest('hex');
console.log(`build-denoise: ${path.relative(ROOT, ASSET)} ${bytes.length} bytes sha256 ${sha256}`);