// SF2 writing (browser and Node: Uint8Array only) and the layout of the instrument: which notes and // velocities are rendered, how the rendered notes are processed into samples, and the zones. // // Layout: notes firstNote, firstNote + step, ... (count of them); each sample plays from its own // root key over the keys nearest to it (the lowest down to key 0, the highest up to 127, pitch // shifted there). Three velocity layers. Samples are 16-bit mono, unlooped, with a short fade at // the end; their levels keep the physical dynamics between the layers, and a partial loudness // equalisation between the notes (sf2.levelEqualize). A gentle velocity curve shades the // velocities within a layer, and a release envelope stands for the hand damping the string. import type { Params } from "./params.ts"; export interface SampleJob { note: number; velocity: number; layer: number; /** seconds of sound */ length: number; } const NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]; export const noteName = (n: number) => `${NAMES[n % 12]}${Math.floor(n / 12) - 1}`; export function sampleNotes(p: Params): number[] { return Array.from({ length: p.sf2.count }, (_, i) => p.sf2.firstNote + i * p.sf2.step); } export function sampleJobs(p: Params): SampleJob[] { const notes = sampleNotes(p); const jobs: SampleJob[] = []; const n0 = notes[0], n1 = notes[notes.length - 1]; notes.forEach((note) => { const t = n1 > n0 ? (note - n0) / (n1 - n0) : 0; const length = p.sf2.lengthLow * Math.pow(p.sf2.lengthHigh / p.sf2.lengthLow, t); p.sf2.velocities.forEach((velocity, layer) => jobs.push({ note, velocity, layer, length })); }); return jobs; } /** DC removal (15 Hz one-pole high-pass) and an end fade. */ export function processSample(x: Float32Array, fs: number, fade: number): Float64Array { const a = Math.exp((-2 * Math.PI * 15) / fs); const y = new Float64Array(x.length); let px = 0, py = 0; for (let i = 0; i < x.length; i++) { py = a * (py + x[i] - px); px = x[i]; y[i] = py; } const nf = Math.min(y.length, Math.round(fade * fs)); for (let i = 0; i < nf; i++) y[y.length - 1 - i] *= 0.5 - 0.5 * Math.cos((Math.PI * i) / nf); return y; } const rmsOf = (x: Float64Array, n: number) => { let s = 0; const m = Math.min(n, x.length); for (let i = 0; i < m; i++) s += x[i] * x[i]; return Math.sqrt(s / Math.max(1, m)); }; /** * Level the processed samples: the hard layer of each note is brought toward a common loudness * (RMS over the first 0.5 s) by the fraction levelEqualize (in dB), and the other layers of that * note get the same gain, keeping their physical level relative to it. Then one global gain puts * the loudest peak at -1 dBFS. Returns 16-bit data. */ export function levelSamples(p: Params, jobs: SampleJob[], data: Float64Array[], fs: number): Int16Array[] { const eq = p.sf2.levelEqualize; const top = p.sf2.velocities.length - 1; const hardRms = new Map(); jobs.forEach((j, i) => { if (j.layer === top) hardRms.set(j.note, rmsOf(data[i], Math.round(0.5 * fs))); }); const logs = [...hardRms.values()].map((v) => Math.log(v)); const meanLog = logs.reduce((a, b) => a + b, 0) / Math.max(1, logs.length); const gains = jobs.map((j) => Math.exp(eq * (meanLog - Math.log(hardRms.get(j.note) ?? Math.exp(meanLog))))); let peak = 0; data.forEach((d, i) => { for (const v of d) peak = Math.max(peak, Math.abs(v * gains[i])); }); const g = 0.89 / Math.max(peak, 1e-30); return data.map((d, i) => Int16Array.from(d, (v) => Math.round(Math.max(-1, Math.min(1, v * gains[i] * g)) * 32767))); } // ---------------------------------------------------------------- RIFF / SF2 writer class Bytes { parts: Uint8Array[] = []; len = 0; push(b: Uint8Array) { this.parts.push(b); this.len += b.length; } concat(): Uint8Array { const out = new Uint8Array(this.len); let o = 0; for (const p of this.parts) { out.set(p, o); o += p.length; } return out; } } const ascii = (s: string) => Uint8Array.from(s, (c) => c.charCodeAt(0) & 0x7f); function chunk(id: string, data: Uint8Array): Uint8Array { const out = new Uint8Array(8 + data.length + (data.length & 1)); out.set(ascii(id), 0); new DataView(out.buffer).setUint32(4, data.length, true); out.set(data, 8); return out; } function list(type: string, parts: Uint8Array[]): Uint8Array { const b = new Bytes(); b.push(ascii(type)); parts.forEach((p) => b.push(p)); return chunk("LIST", b.concat()); } function zstr(s: string): Uint8Array { const n = s.length + 1; const out = new Uint8Array(n + (n & 1)); out.set(ascii(s)); return out; } function name20(v: Uint8Array, o: number, s: string) { v.fill(0, o, o + 20); v.set(ascii(s.slice(0, 19)), o); } export const GEN = { chorusEffectsSend: 15, reverbEffectsSend: 16, releaseVolEnv: 38, keyRange: 43, velRange: 44, initialAttenuation: 48, instrument: 41, sampleID: 53, sampleModes: 54, scaleTuning: 56, overridingRootKey: 58, fineTune: 52, } as const; type Gen = [number, number] | [number, [number, number]]; interface Mod { src: number; dst: number; amt: number; amtSrc?: number; trans?: number } export interface Sf2Sample { name: string; data: Int16Array; rate: number; root: number } export interface Sf2Zone { gens: Gen[]; mods?: Mod[] } export interface Sf2Spec { bankName: string; comment: string; software: string; presetName: string; instrumentName: string; bank: number; program: number; samples: Sf2Sample[]; /** the instrument's zones; the first may be a global zone (no sampleID) */ zones: Sf2Zone[]; } export function writeSf2(spec: Sf2Spec): Uint8Array { const ver = new Uint8Array(4); new DataView(ver.buffer).setUint16(0, 2, true); new DataView(ver.buffer).setUint16(2, 1, true); const info = list("INFO", [chunk("ifil", ver), chunk("isng", zstr("EMU8000")), chunk("INAM", zstr(spec.bankName)), chunk("ICMT", zstr(spec.comment)), chunk("ISFT", zstr(spec.software))]); // sample data: back to back, each followed by 46 zero samples const starts: number[] = []; let total = 0; for (const s of spec.samples) { starts.push(total); total += s.data.length + 46; } const smpl = new Uint8Array(2 * total); const sv = new DataView(smpl.buffer); spec.samples.forEach((s, i) => { for (let j = 0; j < s.data.length; j++) sv.setInt16(2 * (starts[i] + j), s.data[j], true); }); const sdta = list("sdta", [chunk("smpl", smpl)]); const genRec = ([op, v]: Gen) => { const b = new Uint8Array(4), d = new DataView(b.buffer); d.setUint16(0, op, true); if (Array.isArray(v)) { b[2] = v[0]; b[3] = v[1]; } else d.setInt16(2, v, true); return b; }; const modRec = (m: Mod) => { const b = new Uint8Array(10), d = new DataView(b.buffer); d.setUint16(0, m.src, true); d.setUint16(2, m.dst, true); d.setInt16(4, m.amt, true); d.setUint16(6, m.amtSrc ?? 0, true); d.setUint16(8, m.trans ?? 0, true); return b; }; const bagRec = (g: number, m: number) => { const b = new Uint8Array(4), d = new DataView(b.buffer); d.setUint16(0, g, true); d.setUint16(2, m, true); return b; }; // instrument const ibag = new Bytes(), igen = new Bytes(), imod = new Bytes(); let ng = 0, nm = 0; for (const z of spec.zones) { ibag.push(bagRec(ng, nm)); // keyRange must be first, velRange second, sampleID last const order = (g: Gen) => (g[0] === GEN.keyRange ? 0 : g[0] === GEN.velRange ? 1 : g[0] === GEN.sampleID ? 3 : 2); for (const g of [...z.gens].sort((a, b) => order(a) - order(b))) { igen.push(genRec(g)); ng++; } for (const m of z.mods ?? []) { imod.push(modRec(m)); nm++; } } ibag.push(bagRec(ng, nm)); igen.push(new Uint8Array(4)); imod.push(new Uint8Array(10)); const inst = new Uint8Array(44), iv = new DataView(inst.buffer); name20(inst, 0, spec.instrumentName); iv.setUint16(20, 0, true); name20(inst, 22, "EOI"); iv.setUint16(42, spec.zones.length, true); // preset: one zone, the instrument const phdr = new Uint8Array(76), pv = new DataView(phdr.buffer); name20(phdr, 0, spec.presetName); pv.setUint16(20, spec.program, true); pv.setUint16(22, spec.bank, true); pv.setUint16(24, 0, true); name20(phdr, 38, "EOP"); pv.setUint16(38 + 24, 1, true); const pbag = new Bytes(); pbag.push(bagRec(0, 0)); pbag.push(bagRec(1, 0)); const pgen = new Bytes(); pgen.push(genRec([GEN.instrument, 0])); pgen.push(new Uint8Array(4)); const shdr = new Uint8Array(46 * (spec.samples.length + 1)), hv = new DataView(shdr.buffer); spec.samples.forEach((s, i) => { const o = 46 * i, start = starts[i], end = start + s.data.length; name20(shdr, o, s.name); hv.setUint32(o + 20, start, true); hv.setUint32(o + 24, end, true); hv.setUint32(o + 28, start, true); hv.setUint32(o + 32, end, true); hv.setUint32(o + 36, s.rate, true); shdr[o + 40] = s.root; hv.setInt8(o + 41, 0); hv.setUint16(o + 42, 0, true); hv.setUint16(o + 44, 1, true); }); name20(shdr, 46 * spec.samples.length, "EOS"); const pdta = list("pdta", [ chunk("phdr", phdr), chunk("pbag", pbag.concat()), chunk("pmod", new Uint8Array(10)), chunk("pgen", pgen.concat()), chunk("inst", inst), chunk("ibag", ibag.concat()), chunk("imod", imod.concat()), chunk("igen", igen.concat()), chunk("shdr", shdr), ]); const body = new Bytes(); body.push(ascii("sfbk")); body.push(info); body.push(sdta); body.push(pdta); return chunk("RIFF", body.concat()); } /** Assemble the SF2 from rendered (raw, unprocessed) notes in the order of sampleJobs(p). */ export function buildSf2(p: Params, jobs: SampleJob[], rendered: Float32Array[], fs: number, comment: string): { sf2: Uint8Array; samples: Int16Array[] } { const processed = rendered.map((x) => processSample(x, fs, p.sf2.fade)); const pcm = levelSamples(p, jobs, processed, fs); const notes = sampleNotes(p); const keyLo = (i: number) => (i === 0 ? 0 : notes[i] - Math.floor(p.sf2.step / 2)); const keyHi = (i: number) => (i === notes.length - 1 ? 127 : keyLo(i + 1) - 1); const layers = p.sf2.velocities.length; const velLo = (l: number) => (l === 0 ? 1 : p.sf2.layerTop[l - 1] + 1); const velHi = (l: number) => (l === layers - 1 ? 127 : p.sf2.layerTop[l]); const samples: Sf2Sample[] = jobs.map((j, i) => ({ name: `AB ${noteName(j.note)} v${j.velocity}`, data: pcm[i], rate: fs, root: j.note })); const timecents = (s: number) => Math.round(1200 * Math.log2(Math.max(s, 0.001))); const zones: Sf2Zone[] = [ { gens: [[GEN.sampleModes, 0], [GEN.releaseVolEnv, timecents(p.sf2.release)], [GEN.reverbEffectsSend, Math.round(p.sf2.reverbSend)], [GEN.chorusEffectsSend, 0]], mods: [ // velocity -> attenuation: a gentle curve within a layer (replaces the default 960 cB) { src: 0x0502, dst: GEN.initialAttenuation, amt: Math.round(p.sf2.velAtten) }, // velocity -> filter cutoff: off (the layers carry the brightness physically) { src: 0x0502, dst: 8, amt: 0 }, ], }, ]; jobs.forEach((j, i) => { const ni = notes.indexOf(j.note); zones.push({ gens: [[GEN.keyRange, [keyLo(ni), keyHi(ni)]], [GEN.velRange, [velLo(j.layer), velHi(j.layer)]], [GEN.overridingRootKey, j.note], [GEN.sampleID, i]] }); }); const sf2 = writeSf2({ bankName: "Simulated Acoustic Bass", comment, software: "acoustic-base", presetName: p.sf2.presetName, instrumentName: "Acoustic Bass sim", bank: p.sf2.bank, program: p.sf2.program, samples, zones, }); return { sf2, samples: pcm }; }