File size: 2,764 Bytes
26e7ebe | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | // Audio encoders for mono or stereo PCM:
// - WAV: 24-bit PCM at the model sample rate.
// - MP3: CBR encoding from 16-bit PCM with optional TPDF dither.
import { Mp3Encoder } from "@breezystack/lamejs";
import { NormalStream } from "./prng.js";
export function encodeWav24(wave, sampleRate, right = null) {
const channels = right ? [wave, right] : [wave];
const n = wave.length, blockAlign = channels.length * 3, dataBytes = n * blockAlign;
const buf = new ArrayBuffer(44 + dataBytes), dv = new DataView(buf);
const str = (o, s) => [...s].forEach((c, i) => dv.setUint8(o + i, c.charCodeAt(0)));
str(0, "RIFF"); dv.setUint32(4, 36 + dataBytes, true); str(8, "WAVE");
str(12, "fmt "); dv.setUint32(16, 16, true); dv.setUint16(20, 1, true); dv.setUint16(22, channels.length, true);
dv.setUint32(24, sampleRate, true); dv.setUint32(28, sampleRate * blockAlign, true); dv.setUint16(32, blockAlign, true); dv.setUint16(34, 24, true);
str(36, "data"); dv.setUint32(40, dataBytes, true);
let o = 44;
for (let i = 0; i < n; i++) {
for (const channel of channels) {
const v = Math.max(-8388608, Math.min(8388607, Math.round(channel[i] * 8388608)));
dv.setUint8(o, v & 0xff); dv.setUint8(o + 1, (v >> 8) & 0xff); dv.setUint8(o + 2, (v >> 16) & 0xff);
o += 3;
}
}
return new Uint8Array(buf);
}
/** MP3 bytes; `seed` makes the dither reproducible. Returns { bytes, clipped }. */
export function encodeMp3(wave, { right = null, sampleRate, kbps, dither, seed, onProgress = () => {} }) {
const channels = right ? [wave, right] : [wave];
const enc = new Mp3Encoder(channels.length, sampleRate, kbps);
const rng = dither ? new NormalStream(seed, 7) : null;
const block = 1152 * 64, parts = [];
let clipped = 0;
for (let p = 0; p < wave.length; p += block) {
const m = Math.min(block, wave.length - p);
const pcm = channels.map((channel) => {
const samples = new Int16Array(m);
for (let i = 0; i < m; i++) {
let s = channel[p + i] * 32768.0;
if (rng) s += rng.uniform() - rng.uniform();
let r = Math.round(s);
if (Math.abs(s - Math.trunc(s)) === 0.5) r = 2 * Math.round(s / 2); // np.rint: round half to even
if (r > 32767 || r < -32768) clipped++;
samples[i] = Math.max(-32768, Math.min(32767, r));
}
return samples;
});
const out = enc.encodeBuffer(...pcm);
if (out.length) parts.push(new Uint8Array(out));
onProgress(Math.min(1, (p + m) / wave.length));
}
const tail = enc.flush();
if (tail.length) parts.push(new Uint8Array(tail));
const bytes = new Uint8Array(parts.reduce((a, b) => a + b.length, 0));
let o = 0;
for (const b of parts) { bytes.set(b, o); o += b.length; }
return { bytes, clipped };
}
|