@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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Oleksandr Maksymov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,241 @@
1
+ # @xromdev/apu
2
+
3
+ [![npm](https://img.shields.io/npm/v/@xromdev/apu)](https://www.npmjs.com/package/@xromdev/apu) [![test](https://github.com/DeepNESReverse/xrom-apu/actions/workflows/test.yml/badge.svg)](https://github.com/DeepNESReverse/xrom-apu/actions/workflows/test.yml) ![size](https://img.shields.io/bundlephobia/minzip/@xromdev/apu)
4
+
5
+ The NES sound chip — the 2A03's APU — in TypeScript. **Register writes in, samples out.**
6
+
7
+ Every NES game's music reaches the speaker the same way: a sound driver in the
8
+ cartridge writes to the registers `$4000`–`$4017`, sixty times a second. This
9
+ library is those registers. Give it the writes and it gives you back the sound,
10
+ whatever game they came from.
11
+
12
+ It was written to play Battletoads note for note from its decoded cartridge,
13
+ and is the synth for the music chapters of [xrom.dev](https://xrom.dev) as
14
+ they come out. **Try it live in the browser:
15
+ [xrom.dev/utils/apu](https://xrom.dev/utils/apu).**
16
+
17
+ - All five channels: two pulses, the triangle, noise and the DMC (samples).
18
+ - No dependencies, ~6 KB gzipped, runs anywhere JavaScript does (browser, worker, Node).
19
+ - Pure and deterministic: the same writes always give the same samples, so it
20
+ can be tested by measuring rather than by ear.
21
+ - Hardware-faithful where it is audible: the real duty sequences, the noise
22
+ shift register, the length and linear counters, envelopes, the sweep unit
23
+ (including the mute rules that catch people out), the non-linear mixer, and
24
+ the console's output filters.
25
+
26
+ ## Install
27
+
28
+ ```sh
29
+ npm install @xromdev/apu
30
+ ```
31
+
32
+ ## Three ways in
33
+
34
+ ### Register writes
35
+
36
+ What a driver writes, with a time in seconds:
37
+
38
+ ```ts
39
+ import { renderWrites } from '@xromdev/apu';
40
+
41
+ const { samples, sampleRate } = renderWrites(
42
+ [
43
+ { time: 0, address: 0x4015, value: 0x01 }, // enable pulse 1
44
+ { time: 0, address: 0x4000, value: 0xbf }, // duty 50%, constant volume 15
45
+ { time: 0, address: 0x4001, value: 0x08 }, // sweep off (see below)
46
+ { time: 0, address: 0x4002, value: 0xfd }, // period low byte
47
+ { time: 0, address: 0x4003, value: 0x00 }, // period high bits: 253 → 440 Hz
48
+ { time: 1, address: 0x4015, value: 0x00 }, // stop after a second
49
+ ],
50
+ 1 // seconds
51
+ );
52
+ // samples: Float32Array, -1..1, mono, 44.1 kHz by default
53
+ ```
54
+
55
+ This is the layer to use with an emulator trace, or with a driver you are
56
+ running yourself — any game, decoded or not.
57
+
58
+ ### Notes
59
+
60
+ If the music is already decoded into notes, `renderNotes` plays the driver's
61
+ part — it writes what a driver would have written to sound them, and renders
62
+ that:
63
+
64
+ ```ts
65
+ import { renderNotes, type PitchedRow } from '@xromdev/apu';
66
+
67
+ // [midi, startTick, ticks, channel, volume, period, duty, volumeEnd, lengthTicks, bendIndex]
68
+ const melody: PitchedRow[] = [
69
+ [69, 0, 4, 0, 12, 253, 2, 12, 0, -1],
70
+ [72, 4, 4, 0, 12, 212, 2, 4, 0, -1], // fades from 12 to 4 across the note
71
+ ];
72
+
73
+ const render = renderNotes({ pitched: melody, drums: [], secondsPerTick: 0.1, totalTicks: 8 });
74
+ ```
75
+
76
+ `notesToWrites` gives you the writes on their own, if you want to see them.
77
+
78
+ ### Live
79
+
80
+ `Apu` is the chip on its own, for a live source such as a running emulator.
81
+ Write to it as the CPU does, and pull a block of samples whenever the audio
82
+ side wants one:
83
+
84
+ ```ts
85
+ import { Apu, mixApu, OutputFilters, type ChannelBuffers } from '@xromdev/apu';
86
+
87
+ const rate = 48000;
88
+ const chip = new Apu(rate);
89
+ const filters = new OutputFilters(rate, false);
90
+ const n = 128;
91
+ const levels: ChannelBuffers = {
92
+ pulse1: new Uint8Array(n), pulse2: new Uint8Array(n), triangle: new Uint8Array(n),
93
+ noise: new Float64Array(n), dmc: new Uint8Array(n),
94
+ };
95
+
96
+ chip.write(0x4015, 0x01); // …whenever the CPU writes
97
+
98
+ function nextBlock(out: Float32Array) {
99
+ chip.render(out.length, levels);
100
+ const { pulse1, pulse2, triangle, noise, dmc } = levels;
101
+ for (let i = 0; i < out.length; i++) {
102
+ out[i] = 2.2 * filters.step(mixApu(pulse1[i], pulse2[i], triangle[i], noise[i], dmc[i]));
103
+ }
104
+ }
105
+ ```
106
+
107
+ That is the whole of an AudioWorklet processor: the playground at
108
+ [xrom.dev/utils/apu](https://xrom.dev/utils/apu) runs exactly this. The
109
+ per-channel levels are also what to draw an oscilloscope from, and
110
+ `chip.snapshot()` gives the chip's own counters — length, envelope, linear
111
+ counter, sweep mute — for showing what it is doing.
112
+
113
+ `chip.levels()` does the same one sample at a time; `render` gives identical
114
+ numbers several times faster.
115
+
116
+ ### Samples: the DMC
117
+
118
+ The fifth channel plays 1-bit delta samples from cartridge memory. Hand the
119
+ chip that memory — the bytes of `$8000`–`$FFFF`, or a function that reads any
120
+ address — and start a sample the way a game does:
121
+
122
+ ```ts
123
+ const cartridge = new Uint8Array(0x8000); // $8000–$FFFF
124
+ cartridge.set(sampleBytes, 0x4000); // a sample at $C000
125
+
126
+ renderWrites(
127
+ [
128
+ { time: 0, address: 0x4010, value: 0x0f }, // rate 15 (33 kHz), no loop
129
+ { time: 0, address: 0x4012, value: 0x00 }, // start at $C000 + 0 × 64
130
+ { time: 0, address: 0x4013, value: 0x20 }, // 0x20 × 16 + 1 = 513 bytes
131
+ { time: 0, address: 0x4015, value: 0x10 }, // go
132
+ ],
133
+ 1,
134
+ { memory: cartridge }
135
+ );
136
+ ```
137
+
138
+ `$4011` sets the output level directly — which is also how games play raw PCM,
139
+ one write per sample, without the DMC's reader at all.
140
+
141
+ ## Playing it in a browser
142
+
143
+ ```ts
144
+ const context = new AudioContext();
145
+ const buffer = context.createBuffer(1, samples.length, sampleRate);
146
+ buffer.copyToChannel(samples, 0);
147
+ const source = context.createBufferSource();
148
+ source.buffer = buffer;
149
+ source.connect(context.destination);
150
+ source.start();
151
+ ```
152
+
153
+ Rendering takes about 0.2 s for 100 s of music (see below); for long pieces,
154
+ do it in a Worker so the page never stalls.
155
+
156
+ ## Size and speed
157
+
158
+ - **~14 KB minified, ~6 KB gzipped**, no dependencies.
159
+ - **About 500× faster than real time** at the default 2× oversampling: all 20
160
+ Battletoads tracks — 16 minutes of music, 110 000 register writes — render in
161
+ under 2 s on a laptop; the longest, 108 s, in 0.2 s (0.11 s without
162
+ oversampling). The output buffer is 176 KB per second of sound.
163
+
164
+ How: anything that only changes when a register is written — each channel's
165
+ step per sample, whether the sweep unit mutes it — is worked out at the write,
166
+ not every sample; the chip fills runs of samples a channel at a time between
167
+ events; the noise register's whole 32 767-state cycle is a table, so N shifts
168
+ are one lookup; the mixer's common cases are tables built with its own formula;
169
+ the filters allocate nothing per sample. None of it changes a sample: the
170
+ test suite checks the fast paths against the plain ones bit for bit.
171
+
172
+ ## Options
173
+
174
+ `renderWrites(writes, seconds, options)` and `renderNotes(input, options)` take:
175
+
176
+ | option | default | |
177
+ |---|---|---|
178
+ | `sampleRate` | 44100 | |
179
+ | `oversample` | 2 | Run the chip at 2× and average down. Square waves alias badly at 44.1 kHz without it. |
180
+ | `gain` | 2.2 | Master level. |
181
+ | `voiceLevels` | `[1,1,1,1,1]` | A fader per channel — pulse 1, pulse 2, triangle, noise, DMC — applied before the mixer. Not on the console (the triangle has no volume at all), but it is how you hear one voice alone. |
182
+ | `filters` | true | The console's analogue stage. Off gives the raw mixer. |
183
+ | `consoleBass` | false | Add the console's 440 Hz high-pass. Real, but it takes 18 dB off a bass line at 82 Hz; on a television that was the sound, in headphones it is just thin. |
184
+ | `lengthCounter` | true | Off to hear what the length counters are doing. |
185
+ | `memory` | — | Cartridge memory for the DMC: a `Uint8Array` of `$8000`–`$FFFF`, or `(address) => byte`. |
186
+
187
+ `renderNotes` also takes `lead` (seconds of silence first) and `metronome`
188
+ (a click every N ticks, mixed after the filters so it never sounds like the chip).
189
+
190
+ ## Things the hardware does that you might not expect
191
+
192
+ - **`$4001` at its power-on value mutes low notes.** The sweep unit computes a
193
+ target period whether or not it is enabled, and at shift 0 in add mode that
194
+ target is double the period — past `$7FF` for every period from `$400` up,
195
+ which silences the channel. Drivers write `$08` for this reason, and so should you.
196
+ - **Writing `$4003`/`$4007` restarts the note.** It reloads the length counter,
197
+ restarts the envelope and resets the duty sequencer. A vibrato that rewrites
198
+ the high byte every frame clicks on the console too.
199
+ - **The triangle never rests at zero.** When it is stopped it holds whatever
200
+ step it was on, and its level still counts in the mixer — a triangle held
201
+ high takes level from the noise channel beside it.
202
+ - **Pulse 1 and pulse 2 sweep differently by one.** Pulse 1 negates with one's
203
+ complement, pulse 2 with two's.
204
+ - **The DMC's level sticks.** A sample steps the output up or down by 2 per bit
205
+ and it stays wherever the sample left it — and, like the triangle, a high DMC
206
+ level makes the triangle and noise quieter through the shared mixer.
207
+
208
+ ## Not modelled
209
+
210
+ - The DMC's and the frame counter's IRQs, and the CPU cycles the DMC steals
211
+ for its memory reads.
212
+ - The handful of races between a write and a clock landing on the same CPU
213
+ cycle.
214
+ - PAL timings. Everything is NTSC.
215
+
216
+ ## API at a glance
217
+
218
+ | | |
219
+ |---|---|
220
+ | `renderWrites(writes, seconds, options?)` | Register writes → `{ samples, sampleRate, duration, peak }`. |
221
+ | `renderNotes(input, options?)` / `notesToWrites(input)` | Decoded notes → samples, or → the writes a driver would make. |
222
+ | `new Apu(sampleRate, { memory?, lengthCounter? })` | The chip itself: `write(address, value)`, `render(count, buffers)`, `levels()`, `snapshot()`. |
223
+ | `mixApu(p1, p2, tri, noise, dmc?)`, `OutputFilters` | The non-linear mixer and the console's analogue stage, for use with `Apu`. |
224
+ | `sweepTrace(period, sweep, channel, halfFrames)` | The period the sweep unit plays, half-frame by half-frame — for drawing a swept sound. |
225
+ | `CPU_HZ`, `FRAME_HZ`, `LENGTH_TABLE`, `NOISE_PERIODS`, `DMC_PERIODS`, `DUTY_SEQUENCES` | The hardware's numbers. |
226
+
227
+ ## Development
228
+
229
+ ```sh
230
+ npm install
231
+ npm test # vitest
232
+ npm run build # dist/
233
+ ```
234
+
235
+ The tests measure the output — frequencies by counting zero crossings, silence
236
+ by peak level — rather than comparing against recordings, so each one states a
237
+ fact about the hardware in a form that can fail.
238
+
239
+ ## License
240
+
241
+ MIT © Oleksandr Maksymov
package/dist/chip.d.ts ADDED
@@ -0,0 +1,155 @@
1
+ /**
2
+ * The 2A03's sound half, register by register.
3
+ *
4
+ * `Apu` holds what the chip holds — timers, sequencer positions, length and
5
+ * linear counters, envelopes, sweep units, the frame counter — and changes it
6
+ * only the ways the chip does: through a write to `$4000`–`$4017`, or through
7
+ * its own clocks. Nothing here knows what a note is. That is the point: every
8
+ * NES game's music, whatever its driver, reaches the speaker as writes to
9
+ * these registers, so a synth that takes writes plays any of them.
10
+ *
11
+ * It runs at a fixed sample rate rather than per CPU cycle: `render()` advances
12
+ * the chip a run of samples and reports each channel's output level — 0..15 for
13
+ * the pulses, triangle and noise, 0..127 for the DMC — at every one of them. The
14
+ * mixer and the analogue stage are separate (`mixer.ts`), because a caller that
15
+ * wants to hear one channel alone has to get at the levels before they are mixed.
16
+ *
17
+ * The DMC reads its samples from the cartridge, `$8000`–`$FFFF`; give it that
18
+ * memory as `options.memory` (without it, it reads zeros — a sample that only
19
+ * ever steps down).
20
+ *
21
+ * Not modelled: the DMC's and the frame counter's IRQs, the CPU stall of the
22
+ * DMC's memory reads, and the handful of cycle-exact write/clock races. Periods
23
+ * and levels are the hardware's; timing is exact to the sample.
24
+ *
25
+ * **Speed.** `levels()` runs once per sample — 88 200 times a second of music at
26
+ * the default oversampling — so anything that only changes when a register is
27
+ * written (a channel's step per sample, whether the sweep unit mutes it) is
28
+ * worked out at the write and kept, not recomputed here. The expressions are the
29
+ * same ones, evaluated at a different moment, so the output is bit for bit what
30
+ * recomputing them every sample gives.
31
+ */
32
+ /** Where every channel's output levels go, sample by sample. */
33
+ export interface ChannelBuffers {
34
+ pulse1: Uint8Array;
35
+ pulse2: Uint8Array;
36
+ triangle: Uint8Array;
37
+ /** Fractional: the gate is averaged over the shifts in a sample. */
38
+ noise: Float64Array;
39
+ dmc: Uint8Array;
40
+ }
41
+ /** Cartridge memory for the DMC: the bytes of `$8000`–`$FFFF`, or a reader for any address. */
42
+ export type ApuMemory = Uint8Array | ((address: number) => number);
43
+ export interface ApuSnapshot {
44
+ pulse: {
45
+ period: number;
46
+ duty: number;
47
+ /** Length counter, in half-frames; 0 is silent. */
48
+ length: number;
49
+ /** Level the channel outputs when high: the written volume, or the envelope's decay. */
50
+ level: number;
51
+ constant: boolean;
52
+ /** The sweep unit is muting the channel (period < 8, or target past $7FF). */
53
+ muted: boolean;
54
+ enabled: boolean;
55
+ }[];
56
+ triangle: {
57
+ period: number;
58
+ length: number;
59
+ /** Linear counter, in quarter-frames; 0 is silent. */
60
+ linear: number;
61
+ /** The step the staircase is on — held while silent. */
62
+ step: number;
63
+ enabled: boolean;
64
+ };
65
+ noise: {
66
+ periodIndex: number;
67
+ shortMode: boolean;
68
+ length: number;
69
+ level: number;
70
+ constant: boolean;
71
+ enabled: boolean;
72
+ };
73
+ dmc: {
74
+ /** Output level, 0..127. */
75
+ level: number;
76
+ rateIndex: number;
77
+ loop: boolean;
78
+ /** Bytes of the sample still to read; above 0 means it is playing. */
79
+ remaining: number;
80
+ /** Where the memory reader is. */
81
+ address: number;
82
+ enabled: boolean;
83
+ };
84
+ }
85
+ export interface ApuChipOptions {
86
+ /**
87
+ * Honour the length counters. Default true — it is hardware, and without it
88
+ * a drum hit written with a short counter runs on as a wash. Off exists to
89
+ * hear the difference.
90
+ */
91
+ lengthCounter?: boolean;
92
+ /** Where the DMC reads its samples from — see `ApuMemory`. Reads 0 when absent. */
93
+ memory?: ApuMemory;
94
+ }
95
+ export declare class Apu {
96
+ readonly sampleRate: number;
97
+ private readonly lengthCounter;
98
+ private readonly pulses;
99
+ private readonly triangle;
100
+ private readonly noise;
101
+ private readonly dmc;
102
+ private readonly read;
103
+ /** Frame counter: 5-step mode, which step is next, samples until it. */
104
+ private fiveStep;
105
+ private frameStep;
106
+ private frameCountdown;
107
+ private readonly samplesPerQuarterFrame;
108
+ private readonly out;
109
+ constructor(sampleRate: number, options?: ApuChipOptions);
110
+ /** A CPU write to one of the APU's registers. Anything outside `$4000`–`$4017` is ignored. */
111
+ write(address: number, value: number): void;
112
+ /** Scratch buffers for `levels()`, one sample long. */
113
+ private readonly one;
114
+ /**
115
+ * Advance one sample and return the five channel levels, `[pulse1, pulse2,
116
+ * triangle, noise, dmc]` (see `render`). The array is reused between calls.
117
+ * For more than a sample at a time, `render` is several times faster and
118
+ * gives the same numbers.
119
+ */
120
+ levels(): readonly number[];
121
+ /**
122
+ * Advance `count` samples, writing each channel's level into its buffer from
123
+ * `offset` on: the pulses, triangle and DMC as whole numbers (0..15, 0..127),
124
+ * the noise fractional (its gate is averaged over the shifts in a sample). No
125
+ * register writes happen inside — a caller with writes due splits the run at
126
+ * them.
127
+ *
128
+ * The frame counter is the only thing that changes a channel's parameters
129
+ * between writes, so the run is cut at its clocks and each piece is filled a
130
+ * channel at a time (`fill`). Every sum is the one `levels()` would do, in the
131
+ * same order — the buffers come out bit for bit the same as `count` calls.
132
+ */
133
+ render(count: number, buffers: ChannelBuffers, offset?: number): void;
134
+ /** `count` samples with every channel's parameters fixed — tight loops on locals. */
135
+ private fill;
136
+ /**
137
+ * The DMC over `[at, end)`. At most a bit or two per sample even at its
138
+ * fastest rate, so it is clocked bit by bit; a channel with nothing to play
139
+ * only has its output-cycle count moved on, which is all that changes.
140
+ */
141
+ private fillDmc;
142
+ /** One DMC timer clock: step the output by the next bit, and start a new byte after eight. */
143
+ private clockDmc;
144
+ /** The memory reader: refill the empty buffer from the cartridge, looping or stopping at the end. */
145
+ private fetchDmc;
146
+ private retuneDmc;
147
+ /** A copy of the channels' internal counters and levels — see `ApuSnapshot`. */
148
+ snapshot(): ApuSnapshot;
149
+ private retunePulse;
150
+ private retuneTriangle;
151
+ private retuneNoise;
152
+ private clockFrameCounter;
153
+ private clockQuarterFrame;
154
+ private clockHalfFrame;
155
+ }