/ music / acoustic-base
Sign in
music / acoustic-base
acoustic-base / src / core / sf2.ts
227 lines · 11.2 KBCodeBlameHistory
087c169Physically simulated pizzicato double bass and an SF2 built from itJeremy Magland 1// SF2 writing (browser and Node: Uint8Array only) and the layout of the instrument: which notes and
2// velocities are rendered, how the rendered notes are processed into samples, and the zones.
3//
4// Layout: notes firstNote, firstNote + step, ... (count of them); each sample plays from its own
5// root key over the keys nearest to it (the lowest down to key 0, the highest up to 127, pitch
6// shifted there). Three velocity layers. Samples are 16-bit mono, unlooped, with a short fade at
7// the end; their levels keep the physical dynamics between the layers, and a partial loudness
8// equalisation between the notes (sf2.levelEqualize). A gentle velocity curve shades the
9// velocities within a layer, and a release envelope stands for the hand damping the string.
11import type { Params } from "./params.ts";
13export interface SampleJob {
14 note: number;
15 velocity: number;
16 layer: number;
17 /** seconds of sound */
18 length: number;
21const NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
22export const noteName = (n: number) => `${NAMES[n % 12]}${Math.floor(n / 12) - 1}`;
24export function sampleNotes(p: Params): number[] {
25 return Array.from({ length: p.sf2.count }, (_, i) => p.sf2.firstNote + i * p.sf2.step);
28export function sampleJobs(p: Params): SampleJob[] {
29 const notes = sampleNotes(p);
30 const jobs: SampleJob[] = [];
31 const n0 = notes[0], n1 = notes[notes.length - 1];
32 notes.forEach((note) => {
33 const t = n1 > n0 ? (note - n0) / (n1 - n0) : 0;
34 const length = p.sf2.lengthLow * Math.pow(p.sf2.lengthHigh / p.sf2.lengthLow, t);
35 p.sf2.velocities.forEach((velocity, layer) => jobs.push({ note, velocity, layer, length }));
36 });
37 return jobs;
40/** DC removal (15 Hz one-pole high-pass) and an end fade. */
41export function processSample(x: Float32Array, fs: number, fade: number): Float64Array {
42 const a = Math.exp((-2 * Math.PI * 15) / fs);
43 const y = new Float64Array(x.length);
44 let px = 0, py = 0;
45 for (let i = 0; i < x.length; i++) { py = a * (py + x[i] - px); px = x[i]; y[i] = py; }
46 const nf = Math.min(y.length, Math.round(fade * fs));
47 for (let i = 0; i < nf; i++) y[y.length - 1 - i] *= 0.5 - 0.5 * Math.cos((Math.PI * i) / nf);
48 return y;
51const 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)); };
53/**
54 * Level the processed samples: the hard layer of each note is brought toward a common loudness
55 * (RMS over the first 0.5 s) by the fraction levelEqualize (in dB), and the other layers of that
56 * note get the same gain, keeping their physical level relative to it. Then one global gain puts
57 * the loudest peak at -1 dBFS. Returns 16-bit data.
58 */
59export function levelSamples(p: Params, jobs: SampleJob[], data: Float64Array[], fs: number): Int16Array[] {
60 const eq = p.sf2.levelEqualize;
61 const top = p.sf2.velocities.length - 1;
62 const hardRms = new Map<number, number>();
63 jobs.forEach((j, i) => { if (j.layer === top) hardRms.set(j.note, rmsOf(data[i], Math.round(0.5 * fs))); });
64 const logs = [...hardRms.values()].map((v) => Math.log(v));
65 const meanLog = logs.reduce((a, b) => a + b, 0) / Math.max(1, logs.length);
66 const gains = jobs.map((j) => Math.exp(eq * (meanLog - Math.log(hardRms.get(j.note) ?? Math.exp(meanLog)))));
67 let peak = 0;
68 data.forEach((d, i) => { for (const v of d) peak = Math.max(peak, Math.abs(v * gains[i])); });
69 const g = 0.89 / Math.max(peak, 1e-30);
70 return data.map((d, i) => Int16Array.from(d, (v) => Math.round(Math.max(-1, Math.min(1, v * gains[i] * g)) * 32767)));
73// ---------------------------------------------------------------- RIFF / SF2 writer
75class Bytes {
76 parts: Uint8Array[] = [];
77 len = 0;
78 push(b: Uint8Array) { this.parts.push(b); this.len += b.length; }
79 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; }
81const ascii = (s: string) => Uint8Array.from(s, (c) => c.charCodeAt(0) & 0x7f);
82function chunk(id: string, data: Uint8Array): Uint8Array {
83 const out = new Uint8Array(8 + data.length + (data.length & 1));
84 out.set(ascii(id), 0);
85 new DataView(out.buffer).setUint32(4, data.length, true);
86 out.set(data, 8);
87 return out;
89function list(type: string, parts: Uint8Array[]): Uint8Array {
90 const b = new Bytes(); b.push(ascii(type)); parts.forEach((p) => b.push(p));
91 return chunk("LIST", b.concat());
93function zstr(s: string): Uint8Array { const n = s.length + 1; const out = new Uint8Array(n + (n & 1)); out.set(ascii(s)); return out; }
94function name20(v: Uint8Array, o: number, s: string) { v.fill(0, o, o + 20); v.set(ascii(s.slice(0, 19)), o); }
96export const GEN = {
97 chorusEffectsSend: 15, reverbEffectsSend: 16, releaseVolEnv: 38, keyRange: 43, velRange: 44,
98 initialAttenuation: 48, instrument: 41, sampleID: 53, sampleModes: 54, scaleTuning: 56, overridingRootKey: 58, fineTune: 52,
99} as const;
100type Gen = [number, number] | [number, [number, number]];
101interface Mod { src: number; dst: number; amt: number; amtSrc?: number; trans?: number }
103export interface Sf2Sample { name: string; data: Int16Array; rate: number; root: number }
104export interface Sf2Zone { gens: Gen[]; mods?: Mod[] }
105export interface Sf2Spec {
106 bankName: string;
107 comment: string;
108 software: string;
109 presetName: string;
110 instrumentName: string;
111 bank: number;
112 program: number;
113 samples: Sf2Sample[];
114 /** the instrument's zones; the first may be a global zone (no sampleID) */
115 zones: Sf2Zone[];
118export function writeSf2(spec: Sf2Spec): Uint8Array {
119 const ver = new Uint8Array(4); new DataView(ver.buffer).setUint16(0, 2, true); new DataView(ver.buffer).setUint16(2, 1, true);
120 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))]);
122 // sample data: back to back, each followed by 46 zero samples
123 const starts: number[] = [];
124 let total = 0;
125 for (const s of spec.samples) { starts.push(total); total += s.data.length + 46; }
126 const smpl = new Uint8Array(2 * total);
127 const sv = new DataView(smpl.buffer);
128 spec.samples.forEach((s, i) => { for (let j = 0; j < s.data.length; j++) sv.setInt16(2 * (starts[i] + j), s.data[j], true); });
129 const sdta = list("sdta", [chunk("smpl", smpl)]);
131 const genRec = ([op, v]: Gen) => {
132 const b = new Uint8Array(4), d = new DataView(b.buffer);
133 d.setUint16(0, op, true);
134 if (Array.isArray(v)) { b[2] = v[0]; b[3] = v[1]; } else d.setInt16(2, v, true);
135 return b;
136 };
137 const modRec = (m: Mod) => {
138 const b = new Uint8Array(10), d = new DataView(b.buffer);
139 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);
140 return b;
141 };
142 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; };
144 // instrument
145 const ibag = new Bytes(), igen = new Bytes(), imod = new Bytes();
146 let ng = 0, nm = 0;
147 for (const z of spec.zones) {
148 ibag.push(bagRec(ng, nm));
149 // keyRange must be first, velRange second, sampleID last
150 const order = (g: Gen) => (g[0] === GEN.keyRange ? 0 : g[0] === GEN.velRange ? 1 : g[0] === GEN.sampleID ? 3 : 2);
151 for (const g of [...z.gens].sort((a, b) => order(a) - order(b))) { igen.push(genRec(g)); ng++; }
152 for (const m of z.mods ?? []) { imod.push(modRec(m)); nm++; }
153 }
154 ibag.push(bagRec(ng, nm));
155 igen.push(new Uint8Array(4));
156 imod.push(new Uint8Array(10));
157 const inst = new Uint8Array(44), iv = new DataView(inst.buffer);
158 name20(inst, 0, spec.instrumentName); iv.setUint16(20, 0, true);
159 name20(inst, 22, "EOI"); iv.setUint16(42, spec.zones.length, true);
161 // preset: one zone, the instrument
162 const phdr = new Uint8Array(76), pv = new DataView(phdr.buffer);
163 name20(phdr, 0, spec.presetName); pv.setUint16(20, spec.program, true); pv.setUint16(22, spec.bank, true); pv.setUint16(24, 0, true);
164 name20(phdr, 38, "EOP"); pv.setUint16(38 + 24, 1, true);
165 const pbag = new Bytes(); pbag.push(bagRec(0, 0)); pbag.push(bagRec(1, 0));
166 const pgen = new Bytes(); pgen.push(genRec([GEN.instrument, 0])); pgen.push(new Uint8Array(4));
168 const shdr = new Uint8Array(46 * (spec.samples.length + 1)), hv = new DataView(shdr.buffer);
169 spec.samples.forEach((s, i) => {
170 const o = 46 * i, start = starts[i], end = start + s.data.length;
171 name20(shdr, o, s.name);
172 hv.setUint32(o + 20, start, true); hv.setUint32(o + 24, end, true);
173 hv.setUint32(o + 28, start, true); hv.setUint32(o + 32, end, true);
174 hv.setUint32(o + 36, s.rate, true); shdr[o + 40] = s.root; hv.setInt8(o + 41, 0);
175 hv.setUint16(o + 42, 0, true); hv.setUint16(o + 44, 1, true);
176 });
177 name20(shdr, 46 * spec.samples.length, "EOS");
179 const pdta = list("pdta", [
180 chunk("phdr", phdr), chunk("pbag", pbag.concat()), chunk("pmod", new Uint8Array(10)), chunk("pgen", pgen.concat()),
181 chunk("inst", inst), chunk("ibag", ibag.concat()), chunk("imod", imod.concat()), chunk("igen", igen.concat()),
182 chunk("shdr", shdr),
183 ]);
184 const body = new Bytes(); body.push(ascii("sfbk")); body.push(info); body.push(sdta); body.push(pdta);
185 return chunk("RIFF", body.concat());
188/** Assemble the SF2 from rendered (raw, unprocessed) notes in the order of sampleJobs(p). */
189export function buildSf2(p: Params, jobs: SampleJob[], rendered: Float32Array[], fs: number, comment: string): { sf2: Uint8Array; samples: Int16Array[] } {
190 const processed = rendered.map((x) => processSample(x, fs, p.sf2.fade));
191 const pcm = levelSamples(p, jobs, processed, fs);
192 const notes = sampleNotes(p);
193 const keyLo = (i: number) => (i === 0 ? 0 : notes[i] - Math.floor(p.sf2.step / 2));
194 const keyHi = (i: number) => (i === notes.length - 1 ? 127 : keyLo(i + 1) - 1);
195 const layers = p.sf2.velocities.length;
196 const velLo = (l: number) => (l === 0 ? 1 : p.sf2.layerTop[l - 1] + 1);
197 const velHi = (l: number) => (l === layers - 1 ? 127 : p.sf2.layerTop[l]);
198 const samples: Sf2Sample[] = jobs.map((j, i) => ({ name: `AB ${noteName(j.note)} v${j.velocity}`, data: pcm[i], rate: fs, root: j.note }));
199 const timecents = (s: number) => Math.round(1200 * Math.log2(Math.max(s, 0.001)));
200 const zones: Sf2Zone[] = [
201 {
202 gens: [[GEN.sampleModes, 0], [GEN.releaseVolEnv, timecents(p.sf2.release)], [GEN.reverbEffectsSend, Math.round(p.sf2.reverbSend)], [GEN.chorusEffectsSend, 0]],
203 mods: [
204 // velocity -> attenuation: a gentle curve within a layer (replaces the default 960 cB)
205 { src: 0x0502, dst: GEN.initialAttenuation, amt: Math.round(p.sf2.velAtten) },
206 // velocity -> filter cutoff: off (the layers carry the brightness physically)
207 { src: 0x0502, dst: 8, amt: 0 },
208 ],
209 },
210 ];
211 jobs.forEach((j, i) => {
212 const ni = notes.indexOf(j.note);
213 zones.push({ gens: [[GEN.keyRange, [keyLo(ni), keyHi(ni)]], [GEN.velRange, [velLo(j.layer), velHi(j.layer)]], [GEN.overridingRootKey, j.note], [GEN.sampleID, i]] });
214 });
215 const sf2 = writeSf2({
216 bankName: "Simulated Acoustic Bass",
217 comment,
218 software: "acoustic-base",
219 presetName: p.sf2.presetName,
220 instrumentName: "Acoustic Bass sim",
221 bank: p.sf2.bank,
222 program: p.sf2.program,
223 samples,
224 zones,
225 });
226 return { sf2, samples: pcm };
↑↓ move↵openescclose