-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompose-tracks.ts
More file actions
512 lines (468 loc) · 19.6 KB
/
Copy pathcompose-tracks.ts
File metadata and controls
512 lines (468 loc) · 19.6 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
/**
* Offline music composer — renders the v5 film tracks as produced-sounding
* stereo arrangements into public/audio/. Pure math, zero deps, deterministic.
* Re-run with `npm run synth:tracks` (transcodes to .m4a when ffmpeg exists).
*
* Each track is 29 bars @ exactly 118 BPM (≈59s), beat 0 at sample 0, so the
* film's beat grid locks to it with zero offset (see src/remotion/film/tracks.ts):
* intro(0-3) → build(4-7) → groove(8-15) → breakdown(16-19, riser + gap)
* → drop(20-27) → tail(28).
* Spectral bar vs the Zelios reference: sustained pad/chord energy through the
* mids, air above 8kHz, continuous warm low end — not just drum transients.
*/
import { execFileSync } from "child_process";
import { existsSync, mkdirSync, unlinkSync, writeFileSync } from "fs";
import path from "path";
import { mulberry32 } from "../src/remotion/film/beat";
const SR = 44100;
const BPM = 118;
const BEAT = 60 / BPM;
const BAR = 4 * BEAT;
const BARS = 29; // 28 played + 1 reverb tail
const N = Math.round(BARS * BAR * SR);
// Section boundaries in bars.
const SEC = { build: 4, groove: 8, breakdown: 16, drop: 20, tail: 28 };
const barAt = (i: number): number => i / SR / BAR;
const inRange = (b: number, from: number, to: number): boolean => b >= from && b < to;
// ---------------------------------------------------------------------------
// Infrastructure
// ---------------------------------------------------------------------------
function writeWavStereo(filePath: string, L: Float32Array, R: Float32Array): void {
const frames = L.length;
const buf = Buffer.alloc(44 + frames * 4);
buf.write("RIFF", 0);
buf.writeUInt32LE(36 + frames * 4, 4);
buf.write("WAVE", 8);
buf.write("fmt ", 12);
buf.writeUInt32LE(16, 16);
buf.writeUInt16LE(1, 20); // PCM
buf.writeUInt16LE(2, 22); // stereo
buf.writeUInt32LE(SR, 24);
buf.writeUInt32LE(SR * 4, 28);
buf.writeUInt16LE(4, 32);
buf.writeUInt16LE(16, 34);
buf.write("data", 36);
buf.writeUInt32LE(frames * 4, 40);
for (let i = 0; i < frames; i++) {
buf.writeInt16LE(Math.round(Math.max(-1, Math.min(1, L[i])) * 32767), 44 + i * 4);
buf.writeInt16LE(Math.round(Math.max(-1, Math.min(1, R[i])) * 32767), 46 + i * 4);
}
writeFileSync(filePath, buf);
}
class Biquad {
private b0 = 1; private b1 = 0; private b2 = 0; private a1 = 0; private a2 = 0;
private x1 = 0; private x2 = 0; private y1 = 0; private y2 = 0;
setLowpass(freq: number, q: number): void {
const w = (2 * Math.PI * Math.min(freq, SR / 2 - 100)) / SR;
const alpha = Math.sin(w) / (2 * q);
const cosw = Math.cos(w);
const a0 = 1 + alpha;
this.b0 = ((1 - cosw) / 2) / a0;
this.b1 = (1 - cosw) / a0;
this.b2 = ((1 - cosw) / 2) / a0;
this.a1 = (-2 * cosw) / a0;
this.a2 = (1 - alpha) / a0;
}
setHighpass(freq: number, q: number): void {
const w = (2 * Math.PI * Math.min(freq, SR / 2 - 100)) / SR;
const alpha = Math.sin(w) / (2 * q);
const cosw = Math.cos(w);
const a0 = 1 + alpha;
this.b0 = ((1 + cosw) / 2) / a0;
this.b1 = (-(1 + cosw)) / a0;
this.b2 = ((1 + cosw) / 2) / a0;
this.a1 = (-2 * cosw) / a0;
this.a2 = (1 - alpha) / a0;
}
setBandpass(freq: number, q: number): void {
const w = (2 * Math.PI * Math.min(freq, SR / 2 - 100)) / SR;
const alpha = Math.sin(w) / (2 * q);
const cosw = Math.cos(w);
const a0 = 1 + alpha;
this.b0 = alpha / a0;
this.b1 = 0;
this.b2 = -alpha / a0;
this.a1 = (-2 * cosw) / a0;
this.a2 = (1 - alpha) / a0;
}
process(x: number): number {
const y = this.b0 * x + this.b1 * this.x1 + this.b2 * this.x2 - this.a1 * this.y1 - this.a2 * this.y2;
this.x2 = this.x1; this.x1 = x;
this.y2 = this.y1; this.y1 = y;
return y;
}
}
/** One-pole smoothed time-varying lowpass for section macros (cheap, stable). */
class SweepLp {
private lp = new Biquad();
private current = 800;
process(x: number, target: number): number {
this.current += (target - this.current) * 0.0004;
this.lp.setLowpass(this.current, 0.8);
return this.lp.process(x);
}
}
/** Schroeder reverb: 4 damped combs + 2 allpasses. Detune combs per channel. */
class Reverb {
private combs: { buf: Float32Array; idx: number; fb: number; damp: number; store: number }[];
private aps: { buf: Float32Array; idx: number; g: number }[];
constructor(detune: number) {
const combLens = [1557, 1617, 1491, 1422].map((l) => l + detune);
this.combs = combLens.map((len) => ({
buf: new Float32Array(len), idx: 0, fb: 0.78, damp: 0.28, store: 0,
}));
this.aps = [225 + detune, 556 + detune].map((len) => ({
buf: new Float32Array(len), idx: 0, g: 0.5,
}));
}
process(x: number): number {
let out = 0;
for (const c of this.combs) {
const y = c.buf[c.idx];
c.store = y * (1 - c.damp) + c.store * c.damp;
c.buf[c.idx] = x + c.store * c.fb;
c.idx = (c.idx + 1) % c.buf.length;
out += y;
}
out *= 0.25;
for (const a of this.aps) {
const y = a.buf[a.idx];
const v = out + y * a.g;
a.buf[a.idx] = v;
a.idx = (a.idx + 1) % a.buf.length;
out = y - v * a.g;
}
return out;
}
}
// ---------------------------------------------------------------------------
// Musical material
// ---------------------------------------------------------------------------
type TrackSpec = {
/** Chord roots (Hz, bass octave) — one chord per bar, cycled. */
roots: number[];
/** Chord voicings as frequency lists (pad octave). */
chords: number[][];
/** Pentatonic pool for the pluck arp. */
pent: number[];
seed: number;
};
const HZ = (midi: number): number => 440 * Math.pow(2, (midi - 69) / 12);
/** Track A "Pulse" — A minor 9 lane: Am9 / Fmaj9 / Cadd9 / G6. */
const TRACK_A: TrackSpec = {
roots: [HZ(33), HZ(29), HZ(36), HZ(31)], // A1 F1 C2 G1
chords: [
[HZ(57), HZ(60), HZ(64), HZ(67), HZ(71)], // A3 C4 E4 G4 B4
[HZ(53), HZ(57), HZ(60), HZ(64), HZ(67)], // F3 A3 C4 E4 G4
[HZ(55), HZ(60), HZ(64), HZ(62), HZ(67)], // (C) G3 C4 E4 D4 G4
[HZ(55), HZ(59), HZ(62), HZ(64), HZ(69)], // G3 B3 D4 E4 A4
],
pent: [HZ(69), HZ(72), HZ(76), HZ(79), HZ(81), HZ(84)], // A4 C5 E5 G5 A5 C6
seed: 41,
};
/** Track B "Bloom" — F# minor lane: F#m9 / D / A / E, softer arp. */
const TRACK_B: TrackSpec = {
roots: [HZ(30), HZ(38), HZ(33), HZ(28)], // F#1 D2 A1 E1
chords: [
[HZ(54), HZ(57), HZ(61), HZ(64), HZ(68)], // F#3 A3 C#4 E4 G#4
[HZ(50), HZ(54), HZ(57), HZ(62), HZ(66)], // D3 F#3 A3 D4 F#4
[HZ(52), HZ(57), HZ(61), HZ(64), HZ(69)], // (A) E3 A3 C#4 E4 A4
[HZ(52), HZ(56), HZ(59), HZ(64), HZ(68)], // E3 G#3 B3 E4 G#4
],
pent: [HZ(66), HZ(69), HZ(73), HZ(76), HZ(78), HZ(81)], // F#4 A4 C#5 E5 F#5 A5
seed: 97,
};
// ---------------------------------------------------------------------------
// Renderer
// ---------------------------------------------------------------------------
function renderTrack(spec: TrackSpec): [Float32Array, Float32Array] {
const rng = mulberry32(spec.seed);
const L = new Float32Array(N);
const R = new Float32Array(N);
// Layer buses (stereo pairs), mixed at the end through the section macro LP.
const padL = new Float32Array(N), padR = new Float32Array(N);
const bassM = new Float32Array(N);
const drumM = new Float32Array(N);
const plkL = new Float32Array(N), plkR = new Float32Array(N);
const airL = new Float32Array(N), airR = new Float32Array(N);
const fxM = new Float32Array(N); // risers, crashes — bypasses macro LP
const sendL = new Float32Array(N), sendR = new Float32Array(N); // reverb send
// Sidechain envelope from kick positions (also used in sections w/o kick = 1).
const duck = new Float32Array(N).fill(1);
// --- energy plan per bar ---------------------------------------------------
const kickOn = (b: number): boolean =>
inRange(b, SEC.build, SEC.breakdown) || inRange(b, SEC.drop, SEC.tail);
const hatsOn = kickOn;
const clapOn = (b: number): boolean =>
inRange(b, SEC.groove, SEC.breakdown) || inRange(b, SEC.drop, SEC.tail);
// "The gap": last half-beat before the drop is near-silent for punch.
const gapStart = Math.round((SEC.drop * BAR - BEAT / 2) * SR);
const gapEnd = Math.round(SEC.drop * BAR * SR);
// --- kick + sidechain -------------------------------------------------------
for (let beat = 0; beat < BARS * 4; beat++) {
const bar = Math.floor(beat / 4);
if (!kickOn(bar)) continue;
const n0 = Math.round(beat * BEAT * SR);
let phase = 0;
const dur = Math.round(0.32 * SR);
for (let i = 0; i < dur && n0 + i < N; i++) {
const t = i / SR;
const f = 42 + 95 * Math.exp(-t * 30);
phase += (2 * Math.PI * f) / SR;
drumM[n0 + i] += Math.sin(phase) * Math.exp(-t * 15) * 0.95;
if (i < 55) drumM[n0 + i] += (rng() * 2 - 1) * 0.3 * (1 - i / 55);
}
const pumpLen = Math.round(0.24 * SR);
for (let i = 0; i < pumpLen && n0 + i < N; i++) {
const dip = 1 - 0.62 * Math.exp(-(i / SR) * 14);
duck[n0 + i] = Math.min(duck[n0 + i], dip);
}
}
// --- clap on 2 & 4 (three-burst noise through bandpass) ----------------------
const clapBp = new Biquad();
clapBp.setBandpass(1500, 1.1);
for (let beat = 0; beat < BARS * 4; beat++) {
if (beat % 2 !== 1) continue; // beats 2 and 4
const bar = Math.floor(beat / 4);
if (!clapOn(bar)) continue;
const n0 = Math.round(beat * BEAT * SR);
for (const off of [0, 0.012, 0.026]) {
const s0 = n0 + Math.round(off * SR);
const len = Math.round(0.14 * SR);
for (let i = 0; i < len && s0 + i < N; i++) {
const raw = (rng() * 2 - 1) * Math.exp(-(i / SR) * (off === 0.026 ? 24 : 90));
const v = clapBp.process(raw) * 0.55;
drumM[s0 + i] += v;
sendL[s0 + i] += v * 0.5;
sendR[s0 + i] += v * 0.5;
}
}
}
// --- hats: offbeat 8ths + 16th shaker + open hat every 2 bars ----------------
const hatHp = new Biquad();
hatHp.setHighpass(7500, 0.7);
const shakerHp = new Biquad();
shakerHp.setHighpass(9500, 0.7);
for (let e = 0; e < BARS * 8; e++) {
const bar = Math.floor(e / 8);
if (!hatsOn(bar)) continue;
if (e % 2 === 1) {
const n0 = Math.round(e * (BEAT / 2) * SR);
const open = e % 16 === 15;
const vel = (0.5 + rng() * 0.4) * (open ? 1.4 : 1);
const len = Math.round((open ? 0.22 : 0.05) * SR);
for (let i = 0; i < len && n0 + i < N; i++) {
drumM[n0 + i] += hatHp.process((rng() * 2 - 1) * Math.exp(-(i / SR) * (open ? 22 : 85)) * vel) * 0.16;
}
}
}
for (let s = 0; s < BARS * 16; s++) {
const bar = Math.floor(s / 16);
if (!inRange(bar, SEC.groove, SEC.breakdown) && !inRange(bar, SEC.drop, SEC.tail)) continue;
const n0 = Math.round(s * (BEAT / 4) * SR);
const vel = s % 4 === 2 ? 0.9 : 0.45;
const len = Math.round(0.03 * SR);
for (let i = 0; i < len && n0 + i < N; i++) {
drumM[n0 + i] += shakerHp.process((rng() * 2 - 1) * Math.exp(-(i / SR) * 130) * vel) * 0.055;
}
}
// --- bass: sub sine + gently saturated saw, 8th gate, follows chord roots ----
const bassLp = new Biquad();
bassLp.setLowpass(320, 0.8);
for (let e = 0; e < BARS * 8; e++) {
const bar = Math.floor(e / 8);
if (bar >= SEC.tail) continue;
const inBreak = inRange(bar, SEC.breakdown, SEC.drop);
if (bar < SEC.build && e % 8 !== 0) continue; // intro: whole-note roots only
if (inBreak && e % 4 !== 0) continue; // breakdown: half-note pulses
const f = spec.roots[bar % 4];
const n0 = Math.round(e * (BEAT / 2) * SR);
const len = Math.round(BEAT * (bar < SEC.build || inBreak ? 1.9 : 0.44) * SR);
for (let i = 0; i < len && n0 + i < N; i++) {
const t = i / SR;
const env = Math.min(1, t * 160) * Math.exp(-t * (bar < SEC.build || inBreak ? 1.2 : 5));
const sub = Math.sin(2 * Math.PI * f * t);
const saw = bassLp.process(2 * ((f * 2 * t) % 1) - 1);
bassM[n0 + i] += (sub * 0.62 + saw * 0.24) * env;
}
}
// --- supersaw pads: one chord per bar, 5 detuned saws per note --------------
// Per-voice static pan and detune; legato 40ms attack; sustained all bar.
const DETUNE = [-0.004, -0.0015, 0, 0.0018, 0.0042];
for (let bar = 0; bar < SEC.tail; bar++) {
const chord = spec.chords[bar % 4];
const n0 = Math.round(bar * BAR * SR);
const len = Math.round(BAR * 1.02 * SR); // slight overlap into next bar
// Pad presence macro: quiet intro, full from build, huge in breakdown.
const base =
bar < SEC.build ? 0.55 : inRange(bar, SEC.breakdown, SEC.drop) ? 1.15 : 0.95;
for (let ni = 0; ni < chord.length; ni++) {
const f0 = chord[ni];
const shimmer = ni === chord.length - 1 ? 0.5 : 1; // top note quieter
for (let v = 0; v < DETUNE.length; v++) {
const f = f0 * (1 + DETUNE[v]);
const pan = (v / (DETUNE.length - 1)) * 2 - 1; // -1..1
const gL = Math.SQRT1_2 * (1 - pan * 0.7);
const gR = Math.SQRT1_2 * (1 + pan * 0.7);
let phase = rng() * 2 * Math.PI; // free-running per voice — lush, still deterministic
for (let i = 0; i < len && n0 + i < N; i++) {
const t = i / SR;
const att = Math.min(1, t / 0.04);
const rel = i > len - 0.06 * SR ? (len - i) / (0.06 * SR) : 1;
phase += (2 * Math.PI * f) / SR;
const saw = 2 * ((phase / (2 * Math.PI)) % 1) - 1;
const s = saw * att * rel * base * shimmer * 0.055;
padL[n0 + i] += s * gL;
padR[n0 + i] += s * gR;
}
}
}
}
// --- pluck arp: 16th mask, dual-saw, ping-pong dotted-8th delay -------------
const mask: number[] = [];
for (let i = 0; i < 16; i++) mask.push(rng() < 0.42 ? 1 : 0);
mask[0] = 1; mask[6] = 1;
const plkLp = new Biquad();
plkLp.setLowpass(2100, 0.9);
for (let s = 0; s < BARS * 16; s++) {
const bar = Math.floor(s / 16);
if (bar >= SEC.tail) continue;
if (bar < 2) continue; // let the intro breathe for 2 bars
if (!mask[s % 16]) continue;
// Drop section: arp doubles up an octave for lift.
const lift = inRange(bar, SEC.drop, SEC.tail) && s % 2 === 0 ? 2 : 1;
const f = spec.pent[Math.floor(rng() * spec.pent.length)] * lift;
const vel = (s % 16 === 0 ? 1 : 0.6 + rng() * 0.4) * (bar < SEC.build ? 0.6 : 1);
const n0 = Math.round(s * (BEAT / 4) * SR);
const len = Math.round(0.22 * SR);
for (let i = 0; i < len && n0 + i < N; i++) {
const t = i / SR;
const saw1 = 2 * ((f * t * 0.9975) % 1) - 1;
const saw2 = 2 * ((f * t * 1.0025) % 1) - 1;
const v = (saw1 + saw2) * 0.5 * Math.exp(-t * 20) * vel;
plkL[n0 + i] += v;
plkR[n0 + i] += v;
}
}
for (let i = 0; i < N; i++) {
plkL[i] = plkLp.process(plkL[i]);
plkR[i] = plkL[i]; // filter once, split below via delay
}
// Ping-pong: L delays to R, R delays back to L (dotted 8th).
const dSam = Math.round(BEAT * 0.75 * SR);
for (let i = dSam; i < N; i++) {
plkR[i] += plkL[i - dSam] * 0.4;
if (i >= dSam * 2) plkL[i] += plkR[i - dSam] * 0.32;
}
for (let i = 0; i < N; i++) {
sendL[i] += plkL[i] * 0.3;
sendR[i] += plkR[i] * 0.3;
}
// --- air: decorrelated shimmer noise, present from build ---------------------
const airHpL = new Biquad(); airHpL.setHighpass(8200, 0.7);
const airHpR = new Biquad(); airHpR.setHighpass(8600, 0.7);
const rngR = mulberry32(spec.seed + 1);
for (let i = 0; i < N; i++) {
const bar = barAt(i);
if (bar < SEC.build - 0.5) continue;
const lfo = 0.7 + 0.3 * Math.sin((2 * Math.PI * i) / SR / (BAR * 2));
const amp = (inRange(bar, SEC.drop, SEC.tail) ? 1.25 : 1) * lfo * 0.045;
airL[i] += airHpL.process((rng() * 2 - 1)) * amp;
airR[i] += airHpR.process((rngR() * 2 - 1)) * amp;
}
// --- riser (bars 18-20) + crashes at groove and drop downbeats ---------------
const riseStart = Math.round((SEC.drop - 2) * BAR * SR);
const riseLen = gapStart - riseStart;
const riseLp = new Biquad();
for (let i = 0; i < riseLen; i++) {
const p = i / riseLen;
riseLp.setLowpass(500 * Math.pow(6800 / 500, p), 1.6);
const noise = riseLp.process(rng() * 2 - 1) * p * p * 0.5;
const gliss = Math.sin(2 * Math.PI * (220 * Math.pow(2, p)) * (i / SR)) * p * 0.12;
fxM[riseStart + i] += noise + gliss;
}
for (const crashBar of [SEC.groove, SEC.drop]) {
const n0 = Math.round(crashBar * BAR * SR);
const cHp = new Biquad();
cHp.setHighpass(5200, 0.7);
const len = Math.round(1.4 * SR);
for (let i = 0; i < len && n0 + i < N; i++) {
fxM[n0 + i] += cHp.process((rng() * 2 - 1)) * Math.exp(-(i / SR) * 3.2) * 0.4;
}
}
// --- mix: macro filter per section, sidechain, reverb, master ---------------
const macroL = new SweepLp();
const macroR = new SweepLp();
const verbL = new Reverb(0);
const verbR = new Reverb(23);
const masterHpL = new Biquad(); masterHpL.setHighpass(28, 0.7);
const masterHpR = new Biquad(); masterHpR.setHighpass(28, 0.7);
for (let i = 0; i < N; i++) {
const bar = barAt(i);
// Section macro cutoff — the "produced" arc.
const cutoff =
bar < 1 ? 900 :
bar < SEC.build ? 900 + (bar - 1) * 1100 :
bar < SEC.groove ? 4200 + (bar - SEC.build) * 800 :
bar < SEC.breakdown ? 9500 :
bar < SEC.drop - 2 ? 5200 :
bar < SEC.drop ? 5200 + (bar - (SEC.drop - 2)) * 3600 :
11000;
const dk = duck[i];
// Ducked musical bus (pads split L/R, mono layers center).
let mL = padL[i] * dk + bassM[i] * 0.62 * dk + plkL[i] * 0.3 + airL[i] * dk;
let mR = padR[i] * dk + bassM[i] * 0.62 * dk + plkR[i] * 0.3 + airR[i] * dk;
mL = macroL.process(mL, cutoff);
mR = macroR.process(mR, cutoff);
// Reverb return (send bus also carries pads a little).
const wet = 0.55;
const rvL = verbL.process((sendL[i] + padL[i] * 0.12) * dk);
const rvR = verbR.process((sendR[i] + padR[i] * 0.12) * dk);
let outL = mL + rvL * wet + drumM[i] + fxM[i];
let outR = mR + rvR * wet + drumM[i] + fxM[i];
// The gap before the drop.
if (i >= gapStart && i < gapEnd) {
const g = 0.04;
outL *= g; outR *= g;
}
// Track-end fade over the tail bar.
const tailStart = SEC.tail * BAR * SR;
if (i > tailStart) {
const g = Math.max(0, 1 - (i - tailStart) / (N - tailStart));
outL *= g; outR *= g;
}
L[i] = Math.tanh(masterHpL.process(outL) * 1.12);
R[i] = Math.tanh(masterHpR.process(outR) * 1.12);
}
// Master normalize: RMS to -14 dBFS with 0.97 peak guard.
let sum = 0, peak = 0;
for (let i = 0; i < N; i++) {
sum += L[i] * L[i] + R[i] * R[i];
peak = Math.max(peak, Math.abs(L[i]), Math.abs(R[i]));
}
const rms = Math.sqrt(sum / (2 * N)) || 1e-9;
const gain = Math.min(Math.pow(10, -14 / 20) / rms, 0.97 / (peak || 1e-9));
for (let i = 0; i < N; i++) { L[i] *= gain; R[i] *= gain; }
return [L, R];
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
const audioDir = path.join(process.cwd(), "public", "audio");
mkdirSync(audioDir, { recursive: true });
for (const [name, spec] of [["track-a", TRACK_A], ["track-b", TRACK_B]] as const) {
const [L, R] = renderTrack(spec);
const wavPath = path.join(audioDir, `${name}.wav`);
writeWavStereo(wavPath, L, R);
const m4aPath = path.join(audioDir, `${name}.m4a`);
try {
execFileSync("ffmpeg", ["-y", "-loglevel", "error", "-i", wavPath, "-c:a", "aac", "-b:a", "192k", m4aPath]);
unlinkSync(wavPath);
console.log(path.relative(process.cwd(), m4aPath), (N / SR).toFixed(2) + "s");
} catch {
console.log(path.relative(process.cwd(), wavPath), (N / SR).toFixed(2) + "s (ffmpeg missing — kept wav)");
}
}
if (existsSync(path.join(audioDir, "track-a.m4a"))) {
console.log("done: tracks composed @ " + BPM + " BPM, beat 0 at 0s");
}