@xromdev/apu 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +241 -0
- package/dist/chip.d.ts +155 -0
- package/dist/chip.js +629 -0
- package/dist/chip.js.map +1 -0
- package/dist/constants.d.ts +44 -0
- package/dist/constants.js +57 -0
- package/dist/constants.js.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +20 -0
- package/dist/index.js.map +1 -0
- package/dist/lfsr.d.ts +24 -0
- package/dist/lfsr.js +37 -0
- package/dist/lfsr.js.map +1 -0
- package/dist/mixer.d.ts +52 -0
- package/dist/mixer.js +85 -0
- package/dist/mixer.js.map +1 -0
- package/dist/notes.d.ts +108 -0
- package/dist/notes.js +263 -0
- package/dist/notes.js.map +1 -0
- package/dist/render.d.ts +69 -0
- package/dist/render.js +116 -0
- package/dist/render.js.map +1 -0
- package/dist/sweep.d.ts +51 -0
- package/dist/sweep.js +79 -0
- package/dist/sweep.js.map +1 -0
- package/package.json +59 -0
package/dist/notes.js
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Notes in, register writes out — the adapter between a decoded score and the
|
|
3
|
+
* chip.
|
|
4
|
+
*
|
|
5
|
+
* A music driver's job is to turn its own data into register writes, once a
|
|
6
|
+
* frame. When a game's music has already been decoded into notes (start, length,
|
|
7
|
+
* period, volume, duty, and how each of those moves), this plays the driver's
|
|
8
|
+
* part: it writes what a driver would have written to sound those notes, and
|
|
9
|
+
* `renderWrites` does the rest. So the chip never learns what a note is, and
|
|
10
|
+
* anything the adapter gets wrong is visible as a register write rather than
|
|
11
|
+
* hidden inside a synth.
|
|
12
|
+
*
|
|
13
|
+
* The note shape is the one xrom.dev exports for Battletoads, but nothing in it
|
|
14
|
+
* is that game's: a tick is whatever the caller says it is in seconds.
|
|
15
|
+
*
|
|
16
|
+
* What it writes, per note:
|
|
17
|
+
* - at the start, the channel's full register set — which on a pulse restarts
|
|
18
|
+
* the duty sequencer and the envelope and reloads the length counter,
|
|
19
|
+
* exactly as the driver's own `$4003` write does;
|
|
20
|
+
* - once a frame after that, the level while it ramps and the period while it
|
|
21
|
+
* bends, as whole numbers, because the registers hold whole numbers — so a
|
|
22
|
+
* fade is a staircase at 60 Hz, as it is on the console;
|
|
23
|
+
* - at the end, silence — unless the next note on the channel starts at the
|
|
24
|
+
* same moment.
|
|
25
|
+
*/
|
|
26
|
+
import { FRAME_HZ, LENGTH_TABLE } from './constants.js';
|
|
27
|
+
import { renderWrites } from './render.js';
|
|
28
|
+
/**
|
|
29
|
+
* Semitones at `position` through a note, straight-line between the curve's own
|
|
30
|
+
* points; outside it, the nearest end.
|
|
31
|
+
*/
|
|
32
|
+
export function bendAt(curve, position) {
|
|
33
|
+
if (curve.length === 0)
|
|
34
|
+
return 0;
|
|
35
|
+
if (position <= curve[0][0])
|
|
36
|
+
return curve[0][1];
|
|
37
|
+
for (let i = 1; i < curve.length; i++) {
|
|
38
|
+
const [x1, y1] = curve[i];
|
|
39
|
+
if (position <= x1) {
|
|
40
|
+
const [x0, y0] = curve[i - 1];
|
|
41
|
+
const span = x1 - x0;
|
|
42
|
+
return span <= 0 ? y1 : y0 + ((y1 - y0) * (position - x0)) / span;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return curve[curve.length - 1][1];
|
|
46
|
+
}
|
|
47
|
+
/** Length-counter load → the index `$4003`'s top five bits must hold for it. */
|
|
48
|
+
const lengthIndex = (halfFrames) => {
|
|
49
|
+
const index = LENGTH_TABLE.indexOf(halfFrames);
|
|
50
|
+
if (index < 0)
|
|
51
|
+
throw new Error(`no length-table entry loads ${halfFrames} half-frames`);
|
|
52
|
+
return index;
|
|
53
|
+
};
|
|
54
|
+
/** The longest load, 254 half-frames (2.1 s) — for a note with no counter that cannot halt it. */
|
|
55
|
+
const LONGEST = 1;
|
|
56
|
+
/** The `$4015` value: pulses and noise always on; the triangle toggled to end its notes. */
|
|
57
|
+
const enables = (triangle) => 0x0b | (triangle ? 0x04 : 0);
|
|
58
|
+
/** A register value can only hold whole numbers; a period outside 11 bits is not one the chip has. */
|
|
59
|
+
const toPeriod = (value) => Math.min(0x7ff, Math.max(0, Math.round(value)));
|
|
60
|
+
/**
|
|
61
|
+
* The bits `$4000`/`$400C` share, from a row's envelope and length counter.
|
|
62
|
+
*
|
|
63
|
+
* Bit 5 is one bit with two jobs — it halts the length counter AND loops the
|
|
64
|
+
* envelope — so a note that wants its envelope to decay once cannot also have
|
|
65
|
+
* an unlimited counter. The rows that ask for both (`lengthTicks` 0 with a
|
|
66
|
+
* one-shot envelope) get the longest load the table has instead, which outlasts
|
|
67
|
+
* any note the envelope has not already silenced.
|
|
68
|
+
*/
|
|
69
|
+
function controlBits(envelope, lengthTicks) {
|
|
70
|
+
if (envelope >= 0) {
|
|
71
|
+
const loop = (envelope & 0x10) !== 0;
|
|
72
|
+
return {
|
|
73
|
+
halt: loop,
|
|
74
|
+
load: lengthTicks > 0 ? lengthIndex(lengthTicks) : LONGEST,
|
|
75
|
+
low: envelope & 0x0f,
|
|
76
|
+
constant: false,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
halt: lengthTicks === 0,
|
|
81
|
+
load: lengthTicks > 0 ? lengthIndex(lengthTicks) : 0,
|
|
82
|
+
low: 0,
|
|
83
|
+
constant: true,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
/** Frame moments inside a note, after its start: when a driver would next touch it. */
|
|
87
|
+
function* frames(start, end) {
|
|
88
|
+
for (let k = 1;; k++) {
|
|
89
|
+
const time = start + k / FRAME_HZ;
|
|
90
|
+
if (time >= end)
|
|
91
|
+
return;
|
|
92
|
+
yield { time, position: (time - start) / (end - start) };
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* The writes that play `input`, as a driver would make them.
|
|
97
|
+
*
|
|
98
|
+
* @param lead seconds of silence before tick 0
|
|
99
|
+
*/
|
|
100
|
+
export function notesToWrites(input, lead = 0) {
|
|
101
|
+
const spt = input.secondsPerTick;
|
|
102
|
+
const bends = input.bends ?? [];
|
|
103
|
+
const writes = [];
|
|
104
|
+
const put = (time, address, value) => writes.push({ time, address, value });
|
|
105
|
+
// Power-on housekeeping, before any note: every channel enabled, and both
|
|
106
|
+
// sweep units given `$08` (disabled, negate). That is what drivers write and
|
|
107
|
+
// why: at the power-on value of 0 the sweep's target overflows for every
|
|
108
|
+
// period from `$400` up, which would mute the low pulse notes of a track that
|
|
109
|
+
// never mentions `$4001`.
|
|
110
|
+
put(0, 0x4015, enables(true));
|
|
111
|
+
put(0, 0x4001, 0x08);
|
|
112
|
+
put(0, 0x4005, 0x08);
|
|
113
|
+
const voicesOf = (rows, keep) => rows
|
|
114
|
+
.filter(keep)
|
|
115
|
+
.map((row) => ({
|
|
116
|
+
start: lead + row[1] * spt,
|
|
117
|
+
end: lead + (row[1] + row[2]) * spt,
|
|
118
|
+
row,
|
|
119
|
+
}))
|
|
120
|
+
.filter((voice) => voice.end > voice.start)
|
|
121
|
+
.sort((a, b) => a.start - b.start);
|
|
122
|
+
// Pulses.
|
|
123
|
+
for (const channel of [0, 1]) {
|
|
124
|
+
const base = 0x4000 + channel * 4;
|
|
125
|
+
const voices = voicesOf(input.pitched,
|
|
126
|
+
// Period 0 would be a divide by zero on the chip too; a row with none is
|
|
127
|
+
// a rest, not a note.
|
|
128
|
+
((row) => row[3] === channel && row[5] >= 1));
|
|
129
|
+
voices.forEach((voice, i) => {
|
|
130
|
+
const [, , , , volume, period, duty, volumeEnd, lengthTicks, bendIndex, envelope, sweep] = voice.row;
|
|
131
|
+
const bits = controlBits(envelope ?? -1, lengthTicks);
|
|
132
|
+
const reg0 = (level) => ((duty & 3) << 6) |
|
|
133
|
+
(bits.halt ? 0x20 : 0) |
|
|
134
|
+
(bits.constant ? 0x10 | (level & 0x0f) : bits.low);
|
|
135
|
+
const level = (at) => Math.min(15, Math.max(0, Math.round(volume + (volumeEnd - volume) * at)));
|
|
136
|
+
put(voice.start, base, reg0(level(0)));
|
|
137
|
+
put(voice.start, base + 1, sweep !== undefined && sweep >= 0 ? sweep : 0x08);
|
|
138
|
+
put(voice.start, base + 2, period & 0xff);
|
|
139
|
+
put(voice.start, base + 3, (bits.load << 3) | ((period >> 8) & 7));
|
|
140
|
+
const curve = bendIndex >= 0 ? (bends[bendIndex] ?? null) : null;
|
|
141
|
+
const ramps = bits.constant && volume !== volumeEnd;
|
|
142
|
+
if (curve || ramps) {
|
|
143
|
+
let lastLevel = level(0);
|
|
144
|
+
let lastPeriod = period;
|
|
145
|
+
for (const { time, position } of frames(voice.start, voice.end)) {
|
|
146
|
+
if (ramps) {
|
|
147
|
+
const now = level(position);
|
|
148
|
+
if (now !== lastLevel)
|
|
149
|
+
put(time, base, reg0(now));
|
|
150
|
+
lastLevel = now;
|
|
151
|
+
}
|
|
152
|
+
if (curve) {
|
|
153
|
+
// A semitone is a frequency ratio; the period is a divider, so it
|
|
154
|
+
// moves the other way.
|
|
155
|
+
const now = toPeriod((period + 1) * Math.pow(2, -bendAt(curve, position) / 12) - 1);
|
|
156
|
+
if (now !== lastPeriod) {
|
|
157
|
+
put(time, base + 2, now & 0xff);
|
|
158
|
+
// The high byte only when it changes, as drivers do — writing it
|
|
159
|
+
// restarts the sequencer, which is an audible click.
|
|
160
|
+
if (now >> 8 !== lastPeriod >> 8)
|
|
161
|
+
put(time, base + 3, (bits.load << 3) | (now >> 8));
|
|
162
|
+
}
|
|
163
|
+
lastPeriod = now;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
const next = voices[i + 1];
|
|
168
|
+
if (!next || next.start > voice.end + 1e-9)
|
|
169
|
+
put(voice.end, base, ((duty & 3) << 6) | 0x30);
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
// Triangle. No volume: it is ended by switching it off in `$4015`, the one
|
|
173
|
+
// way to stop it on the spot — and it then holds whatever step it stopped on.
|
|
174
|
+
{
|
|
175
|
+
const voices = voicesOf(input.pitched, ((row) => row[3] === 2 && row[5] >= 1));
|
|
176
|
+
let on = true;
|
|
177
|
+
voices.forEach((voice, i) => {
|
|
178
|
+
const [, , , , , period, , , lengthTicks, bendIndex] = voice.row;
|
|
179
|
+
// With a counter to honour, the control bit is clear and the linear
|
|
180
|
+
// counter set to its longest (127 quarter-frames, 0.53 s) so the length
|
|
181
|
+
// counter is the one that ends the note; with none, the control bit set
|
|
182
|
+
// halts both.
|
|
183
|
+
const load = lengthTicks > 0 ? lengthIndex(lengthTicks) : 0;
|
|
184
|
+
if (!on)
|
|
185
|
+
put(voice.start, 0x4015, enables(true));
|
|
186
|
+
on = true;
|
|
187
|
+
put(voice.start, 0x4008, lengthTicks > 0 ? 0x7f : 0xff);
|
|
188
|
+
put(voice.start, 0x400a, period & 0xff);
|
|
189
|
+
put(voice.start, 0x400b, (load << 3) | ((period >> 8) & 7));
|
|
190
|
+
const curve = bendIndex >= 0 ? (bends[bendIndex] ?? null) : null;
|
|
191
|
+
if (curve) {
|
|
192
|
+
let last = period;
|
|
193
|
+
for (const { time, position } of frames(voice.start, voice.end)) {
|
|
194
|
+
const now = toPeriod((period + 1) * Math.pow(2, -bendAt(curve, position) / 12) - 1);
|
|
195
|
+
if (now !== last) {
|
|
196
|
+
put(time, 0x400a, now & 0xff);
|
|
197
|
+
if (now >> 8 !== last >> 8)
|
|
198
|
+
put(time, 0x400b, (load << 3) | (now >> 8));
|
|
199
|
+
}
|
|
200
|
+
last = now;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
const next = voices[i + 1];
|
|
204
|
+
if (!next || next.start > voice.end + 1e-9) {
|
|
205
|
+
put(voice.end, 0x4015, enables(false));
|
|
206
|
+
on = false;
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
// Noise.
|
|
211
|
+
{
|
|
212
|
+
const voices = voicesOf(input.drums, (() => true));
|
|
213
|
+
voices.forEach((voice, i) => {
|
|
214
|
+
const [periodIndex, , , volume, volumeEnd, lengthTicks, envelope] = voice.row;
|
|
215
|
+
const bits = controlBits(envelope ?? -1, lengthTicks);
|
|
216
|
+
const reg = (level) => (bits.halt ? 0x20 : 0) | (bits.constant ? 0x10 | (level & 0x0f) : bits.low);
|
|
217
|
+
const level = (at) => Math.min(15, Math.max(0, Math.round(volume + (volumeEnd - volume) * at)));
|
|
218
|
+
put(voice.start, 0x400c, reg(level(0)));
|
|
219
|
+
put(voice.start, 0x400e, periodIndex & 0x0f);
|
|
220
|
+
put(voice.start, 0x400f, bits.load << 3);
|
|
221
|
+
if (bits.constant && volume !== volumeEnd) {
|
|
222
|
+
let last = level(0);
|
|
223
|
+
for (const { time, position } of frames(voice.start, voice.end)) {
|
|
224
|
+
const now = level(position);
|
|
225
|
+
if (now !== last)
|
|
226
|
+
put(time, 0x400c, reg(now));
|
|
227
|
+
last = now;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
const next = voices[i + 1];
|
|
231
|
+
if (!next || next.start > voice.end + 1e-9)
|
|
232
|
+
put(voice.end, 0x400c, 0x30);
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
return writes;
|
|
236
|
+
}
|
|
237
|
+
/** Render a decoded piece: `notesToWrites` into `renderWrites`, with the tick-based extras. */
|
|
238
|
+
export function renderNotes(input, options = {}) {
|
|
239
|
+
const lead = options.lead ?? 0;
|
|
240
|
+
const spt = input.secondsPerTick;
|
|
241
|
+
const clicks = [];
|
|
242
|
+
if (options.metronome && options.metronome > 0) {
|
|
243
|
+
for (let tick = 0, beat = 0; tick < input.totalTicks; tick += options.metronome, beat++) {
|
|
244
|
+
// Four beats to a bar: the downbeat is what makes a tempo readable.
|
|
245
|
+
clicks.push({ time: lead + tick * spt, strong: beat % 4 === 0 });
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
const { lead: _lead, metronome: _metronome, ...render } = options;
|
|
249
|
+
const result = renderWrites(notesToWrites(input, lead), lead + input.totalTicks * spt, {
|
|
250
|
+
...render,
|
|
251
|
+
clicks,
|
|
252
|
+
});
|
|
253
|
+
return {
|
|
254
|
+
samples: result.samples,
|
|
255
|
+
sampleRate: result.sampleRate,
|
|
256
|
+
lead,
|
|
257
|
+
duration: result.duration,
|
|
258
|
+
loopStart: lead + Math.min(input.loopStart ?? 0, input.totalTicks) * spt,
|
|
259
|
+
loopEnd: lead + input.totalTicks * spt,
|
|
260
|
+
peak: result.peak,
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
//# sourceMappingURL=notes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"notes.js","sourceRoot":"","sources":["../src/notes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,YAAY,EAAsD,MAAM,aAAa,CAAC;AA6E/F;;;GAGG;AACH,MAAM,UAAU,MAAM,CAAC,KAAgB,EAAE,QAAgB;IACvD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,CAAC,CAAC;IACjC,IAAI,QAAQ,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAAE,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAChD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACtC,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QAC1B,IAAI,QAAQ,IAAI,EAAE,EAAE,CAAC;YACnB,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;YAC9B,MAAM,IAAI,GAAG,EAAE,GAAG,EAAE,C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AAK,CAAC,UAAU,CAAC,GAAG,GAAG;QACxE,OAAO,EAAE,IAAI,GAAG,KAAK,CAAC,UAAU,GAAG,GAAG;QACtC,IAAI,EAAE,MAAM,CAAC,IAAI;KAClB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Notes in, register writes out — the adapter between a decoded score and the\n * chip.\n *\n * A music driver's job is to turn its own data into register writes, once a\n * frame. When a game's music has already been decoded into notes (start, length,\n * period, volume, duty, and how each of those moves), this plays the driver's\n * part: it writes what a driver would have written to sound those notes, and\n * `renderWrites` does the rest. So the chip never learns what a note is, and\n * anything the adapter gets wrong is visible as a register write rather than\n * hidden inside a synth.\n *\n * The note shape is the one xrom.dev exports for Battletoads, but nothing in it\n * is that game's: a tick is whatever the caller says it is in seconds.\n *\n * What it writes, per note:\n * - at the start, the channel's full register set — which on a pulse restarts\n * the duty sequencer and the envelope and reloads the length counter,\n * exactly as the driver's own `$4003` write does;\n * - once a frame after that, the level while it ramps and the period while it\n * bends, as whole numbers, because the registers hold whole numbers — so a\n * fade is a staircase at 60 Hz, as it is on the console;\n * - at the end, silence — unless the next note on the channel starts at the\n * same moment.\n */\n\nimport { FRAME_HZ, LENGTH_TABLE } from './constants.js';\nimport { renderWrites, type Click, type RegisterWrite, type RenderOptions } from './render.js';\n\n/**\n * `[midi, startTick, durationTicks, channel 0..2, volume, period, duty,\n * volumeEnd, lengthTicks, bendIndex, envelope, sweep]` — `lengthTicks` counts at\n * 120 Hz and 0 means unlimited; `bendIndex` points into `ApuInput.bends`, or is\n * -1; `envelope` is the low five bits of `$4000` when the chip's own envelope\n * runs (period, and bit 4 for loop), or -1 for constant volume; `sweep` is the\n * `$4001` byte, or -1/absent when the data has none.\n */\nexport type PitchedRow = readonly [\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number?,\n number?,\n];\n\n/** A pitch curve: `[position 0..1, semitones]`, in order. */\nexport type BendCurve = readonly (readonly [number, number])[];\n\n/**\n * `[periodIndex, startTick, durationTicks, volume, volumeEnd, lengthTicks,\n * envelope]` — a noise-channel note. `periodIndex` is the low nibble of `$400E`.\n */\nexport type DrumRow = readonly [number, number, number, number, number, number, number?];\n\nexport interface ApuInput {\n pitched: readonly PitchedRow[];\n drums: readonly DrumRow[];\n /** Pitch curves the notes point at. Shared, because the shapes repeat. */\n bends?: readonly BendCurve[];\n /** Seconds per tick. */\n secondsPerTick: number;\n /** Length of the piece in ticks. */\n totalTicks: number;\n /**\n * Where the repeat starts, in ticks. Not always 0: a driver's first ticks are\n * often one-time setup, so a track that loops on the whole buffer replays its\n * intro every time round. Absent means the piece does not loop.\n */\n loopStart?: number;\n}\n\nexport interface ApuOptions extends Omit<RenderOptions, 'clicks' | 'tail'> {\n /** Seconds of silence before the first note. */\n lead?: number;\n /** Click on every `metronome` ticks, loud on every fourth. 0 is off. */\n metronome?: number;\n}\n\nexport interface ApuRender {\n samples: Float32Array;\n sampleRate: number;\n /** Seconds of silence before tick 0 — what the caller asked for as `lead`. */\n lead: number;\n /** Length of the whole buffer, tail included. */\n duration: number;\n /**\n * Where the music itself ends, in seconds — the loop point. The buffer runs a\n * little longer so the filters can ring out; looping on the buffer would play\n * that tail as a gap every time round.\n */\n loopEnd: number;\n /** Where the repeat starts, in seconds — the other end of the seam. */\n loopStart: number;\n /** Loudest absolute sample, before clamping. */\n peak: number;\n}\n\n/**\n * Semitones at `position` through a note, straight-line between the curve's own\n * points; outside it, the nearest end.\n */\nexport function bendAt(curve: BendCurve, position: number): number {\n if (curve.length === 0) return 0;\n if (position <= curve[0][0]) return curve[0][1];\n for (let i = 1; i < curve.length; i++) {\n const [x1, y1] = curve[i];\n if (position <= x1) {\n const [x0, y0] = curve[i - 1];\n const span = x1 - x0;\n return span <= 0 ? y1 : y0 + ((y1 - y0) * (position - x0)) / span;\n }\n }\n return curve[curve.length - 1][1];\n}\n\n/** Length-counter load → the index `$4003`'s top five bits must hold for it. */\nconst lengthIndex = (halfFrames: number) => {\n const index = LENGTH_TABLE.indexOf(halfFrames as (typeof LENGTH_TABLE)[number]);\n if (index < 0) throw new Error(`no length-table entry loads ${halfFrames} half-frames`);\n return index;\n};\n\n/** The longest load, 254 half-frames (2.1 s) — for a note with no counter that cannot halt it. */\nconst LONGEST = 1;\n\n/** The `$4015` value: pulses and noise always on; the triangle toggled to end its notes. */\nconst enables = (triangle: boolean) => 0x0b | (triangle ? 0x04 : 0);\n\n/** A register value can only hold whole numbers; a period outside 11 bits is not one the chip has. */\nconst toPeriod = (value: number) => Math.min(0x7ff, Math.max(0, Math.round(value)));\n\ninterface Voice {\n start: number;\n end: number;\n row: PitchedRow | DrumRow;\n}\n\n/**\n * The bits `$4000`/`$400C` share, from a row's envelope and length counter.\n *\n * Bit 5 is one bit with two jobs — it halts the length counter AND loops the\n * envelope — so a note that wants its envelope to decay once cannot also have\n * an unlimited counter. The rows that ask for both (`lengthTicks` 0 with a\n * one-shot envelope) get the longest load the table has instead, which outlasts\n * any note the envelope has not already silenced.\n */\nfunction controlBits(envelope: number, lengthTicks: number) {\n if (envelope >= 0) {\n const loop = (envelope & 0x10) !== 0;\n return {\n halt: loop,\n load: lengthTicks > 0 ? lengthIndex(lengthTicks) : LONGEST,\n low: envelope & 0x0f,\n constant: false,\n };\n }\n return {\n halt: lengthTicks === 0,\n load: lengthTicks > 0 ? lengthIndex(lengthTicks) : 0,\n low: 0,\n constant: true,\n };\n}\n\n/** Frame moments inside a note, after its start: when a driver would next touch it. */\nfunction* frames(start: number, end: number) {\n for (let k = 1; ; k++) {\n const time = start + k / FRAME_HZ;\n if (time >= end) return;\n yield { time, position: (time - start) / (end - start) };\n }\n}\n\n/**\n * The writes that play `input`, as a driver would make them.\n *\n * @param lead seconds of silence before tick 0\n */\nexport function notesToWrites(input: ApuInput, lead = 0): RegisterWrite[] {\n const spt = input.secondsPerTick;\n const bends = input.bends ?? [];\n const writes: RegisterWrite[] = [];\n const put = (time: number, address: number, value: number) =>\n writes.push({ time, address, value });\n\n // Power-on housekeeping, before any note: every channel enabled, and both\n // sweep units given `$08` (disabled, negate). That is what drivers write and\n // why: at the power-on value of 0 the sweep's target overflows for every\n // period from `$400` up, which would mute the low pulse notes of a track that\n // never mentions `$4001`.\n put(0, 0x4015, enables(true));\n put(0, 0x4001, 0x08);\n put(0, 0x4005, 0x08);\n\n const voicesOf = (rows: readonly (PitchedRow | DrumRow)[], keep: (row: never) => boolean) =>\n rows\n .filter(keep as (row: PitchedRow | DrumRow) => boolean)\n .map((row) => ({\n start: lead + row[1] * spt,\n end: lead + (row[1] + row[2]) * spt,\n row,\n }))\n .filter((voice) => voice.end > voice.start)\n .sort((a, b) => a.start - b.start);\n\n // Pulses.\n for (const channel of [0, 1]) {\n const base = 0x4000 + channel * 4;\n const voices: Voice[] = voicesOf(\n input.pitched,\n // Period 0 would be a divide by zero on the chip too; a row with none is\n // a rest, not a note.\n ((row: PitchedRow) => row[3] === channel && row[5] >= 1) as (row: never) => boolean\n );\n voices.forEach((voice, i) => {\n const [, , , , volume, period, duty, volumeEnd, lengthTicks, bendIndex, envelope, sweep] =\n voice.row as PitchedRow;\n const bits = controlBits(envelope ?? -1, lengthTicks);\n const reg0 = (level: number) =>\n ((duty & 3) << 6) |\n (bits.halt ? 0x20 : 0) |\n (bits.constant ? 0x10 | (level & 0x0f) : bits.low);\n const level = (at: number) =>\n Math.min(15, Math.max(0, Math.round(volume + (volumeEnd - volume) * at)));\n\n put(voice.start, base, reg0(level(0)));\n put(voice.start, base + 1, sweep !== undefined && sweep >= 0 ? sweep : 0x08);\n put(voice.start, base + 2, period & 0xff);\n put(voice.start, base + 3, (bits.load << 3) | ((period >> 8) & 7));\n\n const curve = bendIndex >= 0 ? (bends[bendIndex] ?? null) : null;\n const ramps = bits.constant && volume !== volumeEnd;\n if (curve || ramps) {\n let lastLevel = level(0);\n let lastPeriod = period;\n for (const { time, position } of frames(voice.start, voice.end)) {\n if (ramps) {\n const now = level(position);\n if (now !== lastLevel) put(time, base, reg0(now));\n lastLevel = now;\n }\n if (curve) {\n // A semitone is a frequency ratio; the period is a divider, so it\n // moves the other way.\n const now = toPeriod((period + 1) * Math.pow(2, -bendAt(curve, position) / 12) - 1);\n if (now !== lastPeriod) {\n put(time, base + 2, now & 0xff);\n // The high byte only when it changes, as drivers do — writing it\n // restarts the sequencer, which is an audible click.\n if (now >> 8 !== lastPeriod >> 8) put(time, base + 3, (bits.load << 3) | (now >> 8));\n }\n lastPeriod = now;\n }\n }\n }\n\n const next = voices[i + 1];\n if (!next || next.start > voice.end + 1e-9) put(voice.end, base, ((duty & 3) << 6) | 0x30);\n });\n }\n\n // Triangle. No volume: it is ended by switching it off in `$4015`, the one\n // way to stop it on the spot — and it then holds whatever step it stopped on.\n {\n const voices: Voice[] = voicesOf(input.pitched, ((row: PitchedRow) =>\n row[3] === 2 && row[5] >= 1) as (row: never) => boolean);\n let on = true;\n voices.forEach((voice, i) => {\n const [, , , , , period, , , lengthTicks, bendIndex] = voice.row as PitchedRow;\n // With a counter to honour, the control bit is clear and the linear\n // counter set to its longest (127 quarter-frames, 0.53 s) so the length\n // counter is the one that ends the note; with none, the control bit set\n // halts both.\n const load = lengthTicks > 0 ? lengthIndex(lengthTicks) : 0;\n if (!on) put(voice.start, 0x4015, enables(true));\n on = true;\n put(voice.start, 0x4008, lengthTicks > 0 ? 0x7f : 0xff);\n put(voice.start, 0x400a, period & 0xff);\n put(voice.start, 0x400b, (load << 3) | ((period >> 8) & 7));\n\n const curve = bendIndex >= 0 ? (bends[bendIndex] ?? null) : null;\n if (curve) {\n let last = period;\n for (const { time, position } of frames(voice.start, voice.end)) {\n const now = toPeriod((period + 1) * Math.pow(2, -bendAt(curve, position) / 12) - 1);\n if (now !== last) {\n put(time, 0x400a, now & 0xff);\n if (now >> 8 !== last >> 8) put(time, 0x400b, (load << 3) | (now >> 8));\n }\n last = now;\n }\n }\n\n const next = voices[i + 1];\n if (!next || next.start > voice.end + 1e-9) {\n put(voice.end, 0x4015, enables(false));\n on = false;\n }\n });\n }\n\n // Noise.\n {\n const voices: Voice[] = voicesOf(input.drums, (() => true) as (row: never) => boolean);\n voices.forEach((voice, i) => {\n const [periodIndex, , , volume, volumeEnd, lengthTicks, envelope] = voice.row as DrumRow;\n const bits = controlBits(envelope ?? -1, lengthTicks);\n const reg = (level: number) =>\n (bits.halt ? 0x20 : 0) | (bits.constant ? 0x10 | (level & 0x0f) : bits.low);\n const level = (at: number) =>\n Math.min(15, Math.max(0, Math.round(volume + (volumeEnd - volume) * at)));\n\n put(voice.start, 0x400c, reg(level(0)));\n put(voice.start, 0x400e, periodIndex & 0x0f);\n put(voice.start, 0x400f, bits.load << 3);\n\n if (bits.constant && volume !== volumeEnd) {\n let last = level(0);\n for (const { time, position } of frames(voice.start, voice.end)) {\n const now = level(position);\n if (now !== last) put(time, 0x400c, reg(now));\n last = now;\n }\n }\n\n const next = voices[i + 1];\n if (!next || next.start > voice.end + 1e-9) put(voice.end, 0x400c, 0x30);\n });\n }\n\n return writes;\n}\n\n/** Render a decoded piece: `notesToWrites` into `renderWrites`, with the tick-based extras. */\nexport function renderNotes(input: ApuInput, options: ApuOptions = {}): ApuRender {\n const lead = options.lead ?? 0;\n const spt = input.secondsPerTick;\n\n const clicks: Click[] = [];\n if (options.metronome && options.metronome > 0) {\n for (let tick = 0, beat = 0; tick < input.totalTicks; tick += options.metronome, beat++) {\n // Four beats to a bar: the downbeat is what makes a tempo readable.\n clicks.push({ time: lead + tick * spt, strong: beat % 4 === 0 });\n }\n }\n\n const { lead: _lead, metronome: _metronome, ...render } = options;\n const result = renderWrites(notesToWrites(input, lead), lead + input.totalTicks * spt, {\n ...render,\n clicks,\n });\n\n return {\n samples: result.samples,\n sampleRate: result.sampleRate,\n lead,\n duration: result.duration,\n loopStart: lead + Math.min(input.loopStart ?? 0, input.totalTicks) * spt,\n loopEnd: lead + input.totalTicks * spt,\n peak: result.peak,\n };\n}\n"]}
|
package/dist/render.d.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Register writes in, a finished buffer of samples out.
|
|
3
|
+
*
|
|
4
|
+
* Offline rather than scheduled live: a whole track is a few hundred
|
|
5
|
+
* milliseconds of arithmetic, and a finished buffer is trivially in sync with
|
|
6
|
+
* anything drawn over it — the playing position is one number both read.
|
|
7
|
+
*/
|
|
8
|
+
import { type ApuMemory } from './chip.js';
|
|
9
|
+
/** One CPU write to an APU register, at a moment in seconds from the start. */
|
|
10
|
+
export interface RegisterWrite {
|
|
11
|
+
time: number;
|
|
12
|
+
address: number;
|
|
13
|
+
value: number;
|
|
14
|
+
}
|
|
15
|
+
/** A metronome click: ours, not the chip's, so it is mixed after the console's filters. */
|
|
16
|
+
export interface Click {
|
|
17
|
+
time: number;
|
|
18
|
+
/** The downbeat: higher and louder. */
|
|
19
|
+
strong: boolean;
|
|
20
|
+
}
|
|
21
|
+
export interface RenderOptions {
|
|
22
|
+
sampleRate?: number;
|
|
23
|
+
/**
|
|
24
|
+
* Run the chip at this multiple of the sample rate and average down. A square
|
|
25
|
+
* wave has infinite harmonics, so at 44.1 kHz the high notes alias into
|
|
26
|
+
* inharmonic tones; 2× costs twice the arithmetic and takes most of it away.
|
|
27
|
+
*/
|
|
28
|
+
oversample?: number;
|
|
29
|
+
/** Master level. Default 2.2 — the high-passes centre the signal and cost level. */
|
|
30
|
+
gain?: number;
|
|
31
|
+
/**
|
|
32
|
+
* A fader per channel, `[pulse1, pulse2, triangle, noise, dmc]`, 0..1. Default all 1.
|
|
33
|
+
*
|
|
34
|
+
* Applied to each channel's level BEFORE the non-linear mixer, the only place
|
|
35
|
+
* a per-channel level can go: the mixer's whole point is that the channels
|
|
36
|
+
* are not independent. The console has no such control — the triangle has no
|
|
37
|
+
* volume at all — so this is a desk in front of the chip, for hearing one
|
|
38
|
+
* voice on its own.
|
|
39
|
+
*/
|
|
40
|
+
voiceLevels?: readonly number[];
|
|
41
|
+
/** Skip the output filters. For tests that want the raw mixer. */
|
|
42
|
+
filters?: boolean;
|
|
43
|
+
/** Add the console's second high-pass at 440 Hz — see `OutputFilters`. */
|
|
44
|
+
consoleBass?: boolean;
|
|
45
|
+
/** Honour the length counters. Default true. */
|
|
46
|
+
lengthCounter?: boolean;
|
|
47
|
+
/** Cartridge memory the DMC reads its samples from — see `ApuMemory`. */
|
|
48
|
+
memory?: ApuMemory;
|
|
49
|
+
/** Metronome clicks to mix in after the filters. */
|
|
50
|
+
clicks?: readonly Click[];
|
|
51
|
+
/** Seconds rendered past `duration` so the filters can ring out. Default 0.05. */
|
|
52
|
+
tail?: number;
|
|
53
|
+
}
|
|
54
|
+
export interface Render {
|
|
55
|
+
samples: Float32Array;
|
|
56
|
+
sampleRate: number;
|
|
57
|
+
/** Length of the whole buffer, tail included, in seconds. */
|
|
58
|
+
duration: number;
|
|
59
|
+
/** Loudest absolute sample, before clamping. A value over 1 means the buffer was clamped. */
|
|
60
|
+
peak: number;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Play `writes` through the chip for `duration` seconds.
|
|
64
|
+
*
|
|
65
|
+
* Writes may come in any order; ones at the same moment are applied in the
|
|
66
|
+
* order given, which matters — `$4015` has to enable a channel before the
|
|
67
|
+
* write that loads its length counter.
|
|
68
|
+
*/
|
|
69
|
+
export declare function renderWrites(writes: readonly RegisterWrite[], duration: number, options?: RenderOptions): Render;
|
package/dist/render.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Register writes in, a finished buffer of samples out.
|
|
3
|
+
*
|
|
4
|
+
* Offline rather than scheduled live: a whole track is a few hundred
|
|
5
|
+
* milliseconds of arithmetic, and a finished buffer is trivially in sync with
|
|
6
|
+
* anything drawn over it — the playing position is one number both read.
|
|
7
|
+
*/
|
|
8
|
+
import { Apu } from './chip.js';
|
|
9
|
+
import { mixApu, OutputFilters, PULSE_MIX, TRIANGLE_MIX } from './mixer.js';
|
|
10
|
+
/**
|
|
11
|
+
* Play `writes` through the chip for `duration` seconds.
|
|
12
|
+
*
|
|
13
|
+
* Writes may come in any order; ones at the same moment are applied in the
|
|
14
|
+
* order given, which matters — `$4015` has to enable a channel before the
|
|
15
|
+
* write that loads its length counter.
|
|
16
|
+
*/
|
|
17
|
+
export function renderWrites(writes, duration, options = {}) {
|
|
18
|
+
const sampleRate = options.sampleRate ?? 44100;
|
|
19
|
+
const oversample = Math.max(1, Math.round(options.oversample ?? 2));
|
|
20
|
+
const gain = options.gain ?? 2.2;
|
|
21
|
+
const faders = options.voiceLevels;
|
|
22
|
+
const filtered = options.filters !== false;
|
|
23
|
+
const rate = sampleRate * oversample;
|
|
24
|
+
const total = Math.ceil(duration * rate) + Math.ceil(rate * (options.tail ?? 0.05));
|
|
25
|
+
const ordered = writes
|
|
26
|
+
.map((write, index) => ({ at: Math.max(0, Math.round(write.time * rate)), index, write }))
|
|
27
|
+
.sort((a, b) => a.at - b.at || a.index - b.index);
|
|
28
|
+
const chip = new Apu(rate, { lengthCounter: options.lengthCounter, memory: options.memory });
|
|
29
|
+
const filters = new OutputFilters(rate, options.consoleBass ?? false);
|
|
30
|
+
const out = new Float32Array(Math.ceil(total / oversample));
|
|
31
|
+
const clicks = [...(options.clicks ?? [])]
|
|
32
|
+
.map((click) => ({ at: Math.round(click.time * rate), strong: click.strong }))
|
|
33
|
+
.sort((a, b) => a.at - b.at);
|
|
34
|
+
const clickLength = Math.round(rate * 0.03);
|
|
35
|
+
let clickCursor = 0;
|
|
36
|
+
// Work in blocks: the chip fills a run of samples per channel, then one tight
|
|
37
|
+
// loop mixes, filters and decimates it. A block ends early at the next write,
|
|
38
|
+
// which has to land on its own sample.
|
|
39
|
+
const BLOCK = 1024;
|
|
40
|
+
const buffers = {
|
|
41
|
+
pulse1: new Uint8Array(BLOCK),
|
|
42
|
+
pulse2: new Uint8Array(BLOCK),
|
|
43
|
+
triangle: new Uint8Array(BLOCK),
|
|
44
|
+
noise: new Float64Array(BLOCK),
|
|
45
|
+
dmc: new Uint8Array(BLOCK),
|
|
46
|
+
};
|
|
47
|
+
const { pulse1: p1, pulse2: p2, triangle: tri, noise, dmc } = buffers;
|
|
48
|
+
const hasClicks = clicks.length > 0;
|
|
49
|
+
const f0 = faders ? (faders[0] ?? 1) : 1;
|
|
50
|
+
const f1 = faders ? (faders[1] ?? 1) : 1;
|
|
51
|
+
const f2 = faders ? (faders[2] ?? 1) : 1;
|
|
52
|
+
const f3 = faders ? (faders[3] ?? 1) : 1;
|
|
53
|
+
const f4 = faders ? (faders[4] ?? 1) : 1;
|
|
54
|
+
let next = 0;
|
|
55
|
+
let peak = 0;
|
|
56
|
+
let accumulator = 0;
|
|
57
|
+
let written = 0;
|
|
58
|
+
let phase = 0;
|
|
59
|
+
for (let sample = 0; sample < total;) {
|
|
60
|
+
while (next < ordered.length && ordered[next].at <= sample) {
|
|
61
|
+
const { write } = ordered[next++];
|
|
62
|
+
chip.write(write.address, write.value);
|
|
63
|
+
}
|
|
64
|
+
const until = next < ordered.length ? ordered[next].at : total;
|
|
65
|
+
const count = Math.min(BLOCK, total - sample, until - sample);
|
|
66
|
+
chip.render(count, buffers);
|
|
67
|
+
for (let k = 0; k < count; k++, sample++) {
|
|
68
|
+
let mixed;
|
|
69
|
+
if (faders) {
|
|
70
|
+
mixed = mixApu(p1[k] * f0, p2[k] * f1, tri[k] * f2, noise[k] * f3, dmc[k] * f4);
|
|
71
|
+
}
|
|
72
|
+
else if (noise[k] === 0 && dmc[k] === 0) {
|
|
73
|
+
// The common case, from tables built with the mixer's own expressions.
|
|
74
|
+
mixed = PULSE_MIX[p1[k] + p2[k]] + TRIANGLE_MIX[tri[k]];
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
const tnd = tri[k] / 8227 + noise[k] / 12241 + dmc[k] / 22638;
|
|
78
|
+
mixed = PULSE_MIX[p1[k] + p2[k]] + (tnd === 0 ? 0 : 159.79 / (1 / tnd + 100));
|
|
79
|
+
}
|
|
80
|
+
// Filtered at the oversampled rate: the low-pass then doubles as the
|
|
81
|
+
// anti-aliasing filter the decimation needs.
|
|
82
|
+
let value = filtered ? filters.step(mixed) : mixed;
|
|
83
|
+
if (hasClicks) {
|
|
84
|
+
while (clickCursor < clicks.length && sample >= clicks[clickCursor].at + clickLength) {
|
|
85
|
+
clickCursor++;
|
|
86
|
+
}
|
|
87
|
+
const click = clicks[clickCursor];
|
|
88
|
+
if (click && sample >= click.at) {
|
|
89
|
+
// A decaying sine, added AFTER the console's filters: running it
|
|
90
|
+
// through them would colour it as if it came out of the cartridge.
|
|
91
|
+
const into = (sample - click.at) / clickLength;
|
|
92
|
+
const hz = click.strong ? 1600 : 1050;
|
|
93
|
+
value +=
|
|
94
|
+
Math.sin((2 * Math.PI * hz * (sample - click.at)) / rate) *
|
|
95
|
+
Math.pow(1 - into, 3) *
|
|
96
|
+
(click.strong ? 0.22 : 0.14);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
accumulator += value;
|
|
100
|
+
if (++phase === oversample) {
|
|
101
|
+
phase = 0;
|
|
102
|
+
// Clamped, not scaled: the filters can overshoot a little on a hard
|
|
103
|
+
// transient. `peak` reports what it was BEFORE the clamp.
|
|
104
|
+
const averaged = (accumulator / oversample) * gain;
|
|
105
|
+
accumulator = 0;
|
|
106
|
+
const magnitude = averaged < 0 ? -averaged : averaged;
|
|
107
|
+
if (magnitude > peak)
|
|
108
|
+
peak = magnitude;
|
|
109
|
+
if (written < out.length)
|
|
110
|
+
out[written++] = averaged > 1 ? 1 : averaged < -1 ? -1 : averaged;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return { samples: out, sampleRate, duration: out.length / sampleRate, peak };
|
|
115
|
+
}
|
|
116
|
+
//# sourceMappingURL=render.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"render.js","sourceRoot":"","sources":["../src/render.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,GAAG,EAAuC,MAAM,WAAW,CAAC;AACrE,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,SAAS,E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KAAK,CAAC;YAErB,IAAI,EAAE,KAAK,KAAK,UAAU,EAAE,CAAC;gBAC3B,KAAK,GAAG,CAAC,CAAC;gBACV,oEAAoE;gBACpE,0DAA0D;gBAC1D,MAAM,QAAQ,GAAG,CAAC,WAAW,GAAG,UAAU,CAAC,GAAG,IAAI,CAAC;gBACnD,WAAW,GAAG,CAAC,CAAC;gBAChB,MAAM,SAAS,GAAG,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC;gBACtD,IAAI,SAAS,GAAG,IAAI;oBAAE,IAAI,GAAG,SAAS,CAAC;gBACvC,IAAI,OAAO,GAAG,GAAG,CAAC,MAAM;oBAAE,GAAG,CAAC,OAAO,EAAE,CAAC,GAAG,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;YAC9F,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,UAAU,EAAE,QAAQ,EAAE,GAAG,CAAC,MAAM,GAAG,UAAU,EAAE,IAAI,EAAE,CAAC;AAC/E,CAAC","sourcesContent":["/**\n * Register writes in, a finished buffer of samples out.\n *\n * Offline rather than scheduled live: a whole track is a few hundred\n * milliseconds of arithmetic, and a finished buffer is trivially in sync with\n * anything drawn over it — the playing position is one number both read.\n */\n\nimport { Apu, type ApuMemory, type ChannelBuffers } from './chip.js';\nimport { mixApu, OutputFilters, PULSE_MIX, TRIANGLE_MIX } from './mixer.js';\n\n/** One CPU write to an APU register, at a moment in seconds from the start. */\nexport interface RegisterWrite {\n time: number;\n address: number;\n value: number;\n}\n\n/** A metronome click: ours, not the chip's, so it is mixed after the console's filters. */\nexport interface Click {\n time: number;\n /** The downbeat: higher and louder. */\n strong: boolean;\n}\n\nexport interface RenderOptions {\n sampleRate?: number;\n /**\n * Run the chip at this multiple of the sample rate and average down. A square\n * wave has infinite harmonics, so at 44.1 kHz the high notes alias into\n * inharmonic tones; 2× costs twice the arithmetic and takes most of it away.\n */\n oversample?: number;\n /** Master level. Default 2.2 — the high-passes centre the signal and cost level. */\n gain?: number;\n /**\n * A fader per channel, `[pulse1, pulse2, triangle, noise, dmc]`, 0..1. Default all 1.\n *\n * Applied to each channel's level BEFORE the non-linear mixer, the only place\n * a per-channel level can go: the mixer's whole point is that the channels\n * are not independent. The console has no such control — the triangle has no\n * volume at all — so this is a desk in front of the chip, for hearing one\n * voice on its own.\n */\n voiceLevels?: readonly number[];\n /** Skip the output filters. For tests that want the raw mixer. */\n filters?: boolean;\n /** Add the console's second high-pass at 440 Hz — see `OutputFilters`. */\n consoleBass?: boolean;\n /** Honour the length counters. Default true. */\n lengthCounter?: boolean;\n /** Cartridge memory the DMC reads its samples from — see `ApuMemory`. */\n memory?: ApuMemory;\n /** Metronome clicks to mix in after the filters. */\n clicks?: readonly Click[];\n /** Seconds rendered past `duration` so the filters can ring out. Default 0.05. */\n tail?: number;\n}\n\nexport interface Render {\n samples: Float32Array;\n sampleRate: number;\n /** Length of the whole buffer, tail included, in seconds. */\n duration: number;\n /** Loudest absolute sample, before clamping. A value over 1 means the buffer was clamped. */\n peak: number;\n}\n\n/**\n * Play `writes` through the chip for `duration` seconds.\n *\n * Writes may come in any order; ones at the same moment are applied in the\n * order given, which matters — `$4015` has to enable a channel before the\n * write that loads its length counter.\n */\nexport function renderWrites(\n writes: readonly RegisterWrite[],\n duration: number,\n options: RenderOptions = {}\n): Render {\n const sampleRate = options.sampleRate ?? 44100;\n const oversample = Math.max(1, Math.round(options.oversample ?? 2));\n const gain = options.gain ?? 2.2;\n const faders = options.voiceLevels;\n const filtered = options.filters !== false;\n const rate = sampleRate * oversample;\n const total = Math.ceil(duration * rate) + Math.ceil(rate * (options.tail ?? 0.05));\n\n const ordered = writes\n .map((write, index) => ({ at: Math.max(0, Math.round(write.time * rate)), index, write }))\n .sort((a, b) => a.at - b.at || a.index - b.index);\n\n const chip = new Apu(rate, { lengthCounter: options.lengthCounter, memory: options.memory });\n const filters = new OutputFilters(rate, options.consoleBass ?? false);\n const out = new Float32Array(Math.ceil(total / oversample));\n\n const clicks = [...(options.clicks ?? [])]\n .map((click) => ({ at: Math.round(click.time * rate), strong: click.strong }))\n .sort((a, b) => a.at - b.at);\n const clickLength = Math.round(rate * 0.03);\n let clickCursor = 0;\n\n // Work in blocks: the chip fills a run of samples per channel, then one tight\n // loop mixes, filters and decimates it. A block ends early at the next write,\n // which has to land on its own sample.\n const BLOCK = 1024;\n const buffers: ChannelBuffers = {\n pulse1: new Uint8Array(BLOCK),\n pulse2: new Uint8Array(BLOCK),\n triangle: new Uint8Array(BLOCK),\n noise: new Float64Array(BLOCK),\n dmc: new Uint8Array(BLOCK),\n };\n const { pulse1: p1, pulse2: p2, triangle: tri, noise, dmc } = buffers;\n const hasClicks = clicks.length > 0;\n const f0 = faders ? (faders[0] ?? 1) : 1;\n const f1 = faders ? (faders[1] ?? 1) : 1;\n const f2 = faders ? (faders[2] ?? 1) : 1;\n const f3 = faders ? (faders[3] ?? 1) : 1;\n const f4 = faders ? (faders[4] ?? 1) : 1;\n\n let next = 0;\n let peak = 0;\n let accumulator = 0;\n let written = 0;\n let phase = 0;\n\n for (let sample = 0; sample < total; ) {\n while (next < ordered.length && ordered[next].at <= sample) {\n const { write } = ordered[next++];\n chip.write(write.address, write.value);\n }\n const until = next < ordered.length ? ordered[next].at : total;\n const count = Math.min(BLOCK, total - sample, until - sample);\n chip.render(count, buffers);\n\n for (let k = 0; k < count; k++, sample++) {\n let mixed: number;\n if (faders) {\n mixed = mixApu(p1[k] * f0, p2[k] * f1, tri[k] * f2, noise[k] * f3, dmc[k] * f4);\n } else if (noise[k] === 0 && dmc[k] === 0) {\n // The common case, from tables built with the mixer's own expressions.\n mixed = PULSE_MIX[p1[k] + p2[k]] + TRIANGLE_MIX[tri[k]];\n } else {\n const tnd = tri[k] / 8227 + noise[k] / 12241 + dmc[k] / 22638;\n mixed = PULSE_MIX[p1[k] + p2[k]] + (tnd === 0 ? 0 : 159.79 / (1 / tnd + 100));\n }\n // Filtered at the oversampled rate: the low-pass then doubles as the\n // anti-aliasing filter the decimation needs.\n let value = filtered ? filters.step(mixed) : mixed;\n\n if (hasClicks) {\n while (clickCursor < clicks.length && sample >= clicks[clickCursor].at + clickLength) {\n clickCursor++;\n }\n const click = clicks[clickCursor];\n if (click && sample >= click.at) {\n // A decaying sine, added AFTER the console's filters: running it\n // through them would colour it as if it came out of the cartridge.\n const into = (sample - click.at) / clickLength;\n const hz = click.strong ? 1600 : 1050;\n value +=\n Math.sin((2 * Math.PI * hz * (sample - click.at)) / rate) *\n Math.pow(1 - into, 3) *\n (click.strong ? 0.22 : 0.14);\n }\n }\n\n accumulator += value;\n\n if (++phase === oversample) {\n phase = 0;\n // Clamped, not scaled: the filters can overshoot a little on a hard\n // transient. `peak` reports what it was BEFORE the clamp.\n const averaged = (accumulator / oversample) * gain;\n accumulator = 0;\n const magnitude = averaged < 0 ? -averaged : averaged;\n if (magnitude > peak) peak = magnitude;\n if (written < out.length) out[written++] = averaged > 1 ? 1 : averaged < -1 ? -1 : averaged;\n }\n }\n }\n\n return { samples: out, sampleRate, duration: out.length / sampleRate, peak };\n}\n"]}
|
package/dist/sweep.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pulse channels' sweep unit (`$4001`/`$4005`), as pure functions.
|
|
3
|
+
*
|
|
4
|
+
* The chip uses these per half-frame; `sweepTrace` runs the same unit over one
|
|
5
|
+
* note so a chart of an effect's pitch can show the period the chip PLAYS rather
|
|
6
|
+
* than the one the data holds — for a swept sound those are not the same line.
|
|
7
|
+
*/
|
|
8
|
+
/** Rate the sweep unit and the length counters are clocked at — the half-frame. */
|
|
9
|
+
export declare const SWEEP_HZ = 120;
|
|
10
|
+
/**
|
|
11
|
+
* `$4001` taken apart: `EPPP NSSS`.
|
|
12
|
+
*
|
|
13
|
+
* `pulse1` is not in the register — it is which channel it belongs to — but it
|
|
14
|
+
* belongs here because the subtraction differs between the two channels by one,
|
|
15
|
+
* and that one is audible as most of a semitone at short periods.
|
|
16
|
+
*/
|
|
17
|
+
export interface SweepConfig {
|
|
18
|
+
enabled: boolean;
|
|
19
|
+
/** Reload value for the divider: the unit acts every `dividerPeriod + 1` half-frames. */
|
|
20
|
+
dividerPeriod: number;
|
|
21
|
+
negate: boolean;
|
|
22
|
+
shift: number;
|
|
23
|
+
pulse1: boolean;
|
|
24
|
+
}
|
|
25
|
+
export declare function decodeSweep(value: number, pulse1: boolean): SweepConfig;
|
|
26
|
+
/**
|
|
27
|
+
* The period the sweep unit would move to.
|
|
28
|
+
*
|
|
29
|
+
* Pulse 1 subtracts one MORE than pulse 2 — a hardware asymmetry, not a typo:
|
|
30
|
+
* pulse 1 negates with one's complement and pulse 2 with two's.
|
|
31
|
+
*/
|
|
32
|
+
export declare function sweepTarget(period: number, sweep: SweepConfig): number;
|
|
33
|
+
/**
|
|
34
|
+
* Is the channel silenced by the sweep unit?
|
|
35
|
+
*
|
|
36
|
+
* Two conditions, and both hold **whether or not the unit is enabled**: a
|
|
37
|
+
* period below 8, and a target above `$7FF`. That second one surprises people —
|
|
38
|
+
* with `$4001` at its power-on value of 0 (shift 0, add) every period from
|
|
39
|
+
* `$400` up targets past `$7FF`, so a low pulse note is mute until something
|
|
40
|
+
* writes the register. Drivers write `$08` (negate) for exactly this reason.
|
|
41
|
+
*/
|
|
42
|
+
export declare function sweepMutes(period: number, sweep: SweepConfig): boolean;
|
|
43
|
+
/**
|
|
44
|
+
* The period the sweep unit holds at each half-frame of one note.
|
|
45
|
+
*
|
|
46
|
+
* `null` in the returned array is a half-frame where the unit mutes the channel.
|
|
47
|
+
*
|
|
48
|
+
* @param sweep the `$4001` byte; -1 or undefined gives a flat trace
|
|
49
|
+
* @param channel 0 pulse 1, 1 pulse 2; anything else has no sweep unit
|
|
50
|
+
*/
|
|
51
|
+
export declare function sweepTrace(period: number, sweep: number | undefined, channel: number, halfFrames: number): (number | null)[];
|