@xromdev/apu 0.3.1 → 0.4.1
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/README.md +5 -0
- package/dist/chip.d.ts +24 -1
- package/dist/chip.js +28 -1
- package/dist/chip.js.map +1 -1
- package/dist/expansion.d.ts +123 -0
- package/dist/expansion.js +337 -0
- package/dist/expansion.js.map +1 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/notes.d.ts +18 -1
- package/dist/notes.js +176 -0
- package/dist/notes.js.map +1 -1
- package/dist/render.d.ts +7 -0
- package/dist/render.js +31 -1
- package/dist/render.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -15,6 +15,11 @@ they come out. **Try it live in the browser:
|
|
|
15
15
|
[xrom.dev/utils/apu](https://xrom.dev/utils/apu).**
|
|
16
16
|
|
|
17
17
|
- All five channels: two pulses, the triangle, noise and the DMC (samples).
|
|
18
|
+
- Two Famicom expansion chips, when a game has them: the Disk System's wavetable
|
|
19
|
+
voice (FDS, `$4040`–`$408A`) and Namco's 163 (up to eight wavetable channels,
|
|
20
|
+
through its ports at `$F800`/`$4800`). `renderWrites` turns them on when the
|
|
21
|
+
writes talk to them; `renderNotes` plays notes on them from `waves`
|
|
22
|
+
(`EXPANSION_CHANNELS`: FDS is channel 5, the N163's 6–13).
|
|
18
23
|
- No dependencies, ~6 KB gzipped, runs anywhere JavaScript does (browser, worker, Node).
|
|
19
24
|
- Pure and deterministic: the same writes always give the same samples, so it
|
|
20
25
|
can be tested by measuring rather than by ear.
|
package/dist/chip.d.ts
CHANGED
|
@@ -29,6 +29,7 @@
|
|
|
29
29
|
* same ones, evaluated at a different moment, so the output is bit for bit what
|
|
30
30
|
* recomputing them every sample gives.
|
|
31
31
|
*/
|
|
32
|
+
import { FdsChip, N163Chip, type FdsSnapshot, type N163Snapshot } from './expansion.js';
|
|
32
33
|
/** Where every channel's output levels go, sample by sample. */
|
|
33
34
|
export interface ChannelBuffers {
|
|
34
35
|
pulse1: Uint8Array;
|
|
@@ -37,6 +38,13 @@ export interface ChannelBuffers {
|
|
|
37
38
|
/** Fractional: the gate is averaged over the shifts in a sample. */
|
|
38
39
|
noise: Float64Array;
|
|
39
40
|
dmc: Uint8Array;
|
|
41
|
+
/** The FDS wave channel, in `mixApu` units (added to, not overwritten) — when the chip has one. */
|
|
42
|
+
fds?: Float64Array;
|
|
43
|
+
/**
|
|
44
|
+
* The N163's channels by register slot 0..7 (slot 7, `$78`, is the one always on), in `mixApu`
|
|
45
|
+
* units; index 8, if given, takes every slot without a buffer of its own.
|
|
46
|
+
*/
|
|
47
|
+
n163?: (Float64Array | undefined)[];
|
|
40
48
|
}
|
|
41
49
|
/** Cartridge memory for the DMC: the bytes of `$8000`–`$FFFF`, or a reader for any address. */
|
|
42
50
|
export type ApuMemory = Uint8Array | ((address: number) => number);
|
|
@@ -70,6 +78,9 @@ export interface ApuSnapshot {
|
|
|
70
78
|
constant: boolean;
|
|
71
79
|
enabled: boolean;
|
|
72
80
|
};
|
|
81
|
+
/** The expansion chips' state, when the chip has them (`ApuChipOptions.expansion`). */
|
|
82
|
+
fds?: FdsSnapshot;
|
|
83
|
+
n163?: N163Snapshot;
|
|
73
84
|
dmc: {
|
|
74
85
|
/** Output level, 0..127. */
|
|
75
86
|
level: number;
|
|
@@ -91,9 +102,18 @@ export interface ApuChipOptions {
|
|
|
91
102
|
lengthCounter?: boolean;
|
|
92
103
|
/** Where the DMC reads its samples from — see `ApuMemory`. Reads 0 when absent. */
|
|
93
104
|
memory?: ApuMemory;
|
|
105
|
+
/**
|
|
106
|
+
* Expansion sound on the cartridge: `'FDS'` takes `$4040`–`$408A`, `'N163'` its address port
|
|
107
|
+
* (`$F800`), data port (`$4800`) and `$E000`. Their output goes to `ChannelBuffers.fds`/`n163`.
|
|
108
|
+
*/
|
|
109
|
+
expansion?: readonly string[];
|
|
94
110
|
}
|
|
95
111
|
export declare class Apu {
|
|
96
112
|
readonly sampleRate: number;
|
|
113
|
+
/** The Disk System's wave channel, when `expansion` has `'FDS'`. */
|
|
114
|
+
readonly fds: FdsChip | null;
|
|
115
|
+
/** Namco's 163, when `expansion` has `'N163'`. */
|
|
116
|
+
readonly n163: N163Chip | null;
|
|
97
117
|
private readonly lengthCounter;
|
|
98
118
|
private readonly pulses;
|
|
99
119
|
private readonly triangle;
|
|
@@ -107,7 +127,10 @@ export declare class Apu {
|
|
|
107
127
|
private readonly samplesPerQuarterFrame;
|
|
108
128
|
private readonly out;
|
|
109
129
|
constructor(sampleRate: number, options?: ApuChipOptions);
|
|
110
|
-
/**
|
|
130
|
+
/**
|
|
131
|
+
* A CPU write to one of the APU's registers — or an expansion chip's, when there is one.
|
|
132
|
+
* Anything else is ignored.
|
|
133
|
+
*/
|
|
111
134
|
write(address: number, value: number): void;
|
|
112
135
|
/** Scratch buffers for `levels()`, one sample long. */
|
|
113
136
|
private readonly one;
|
package/dist/chip.js
CHANGED
|
@@ -32,6 +32,7 @@
|
|
|
32
32
|
import { CPU_HZ, DMC_PERIODS, DUTY_SEQUENCES, LENGTH_TABLE, NOISE_PERIODS, QUARTER_FRAME_HZ, TRIANGLE_STEPS, } from './constants.js';
|
|
33
33
|
import { LONG_CYCLE, LONG_HIGH_BEFORE, LONG_INDEX, LONG_STATES } from './lfsr.js';
|
|
34
34
|
import { decodeSweep, sweepMutes, sweepTarget } from './sweep.js';
|
|
35
|
+
import { FdsChip, N163Chip } from './expansion.js';
|
|
35
36
|
/** The four duty sequences flattened, `duty * 8 + step`. */
|
|
36
37
|
const DUTY_FLAT = Uint8Array.from(DUTY_SEQUENCES.flat());
|
|
37
38
|
const TRIANGLE_FLAT = Uint8Array.from(TRIANGLE_STEPS);
|
|
@@ -133,6 +134,8 @@ export class Apu {
|
|
|
133
134
|
};
|
|
134
135
|
this.sampleRate = sampleRate;
|
|
135
136
|
this.lengthCounter = options.lengthCounter !== false;
|
|
137
|
+
this.fds = options.expansion?.includes('FDS') ? new FdsChip(sampleRate) : null;
|
|
138
|
+
this.n163 = options.expansion?.includes('N163') ? new N163Chip(sampleRate) : null;
|
|
136
139
|
this.samplesPerQuarterFrame = sampleRate / QUARTER_FRAME_HZ;
|
|
137
140
|
this.frameCountdown = this.samplesPerQuarterFrame;
|
|
138
141
|
for (const p of this.pulses)
|
|
@@ -148,8 +151,17 @@ export class Apu {
|
|
|
148
151
|
? (address) => memory[(address - 0x8000) % memory.length]
|
|
149
152
|
: () => 0;
|
|
150
153
|
}
|
|
151
|
-
/**
|
|
154
|
+
/**
|
|
155
|
+
* A CPU write to one of the APU's registers — or an expansion chip's, when there is one.
|
|
156
|
+
* Anything else is ignored.
|
|
157
|
+
*/
|
|
152
158
|
write(address, value) {
|
|
159
|
+
if (address > 0x4017) {
|
|
160
|
+
if (this.fds?.write(address, value))
|
|
161
|
+
return;
|
|
162
|
+
this.n163?.write(address, value);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
153
165
|
const v = value & 0xff;
|
|
154
166
|
switch (address) {
|
|
155
167
|
case 0x4000:
|
|
@@ -313,6 +325,19 @@ export class Apu {
|
|
|
313
325
|
* same order — the buffers come out bit for bit the same as `count` calls.
|
|
314
326
|
*/
|
|
315
327
|
render(count, buffers, offset = 0) {
|
|
328
|
+
if (this.fds && buffers.fds) {
|
|
329
|
+
buffers.fds.fill(0, offset, offset + count);
|
|
330
|
+
this.fds.render(count, buffers.fds, offset);
|
|
331
|
+
}
|
|
332
|
+
if (this.n163 && buffers.n163) {
|
|
333
|
+
const cleared = new Set();
|
|
334
|
+
for (const out of buffers.n163)
|
|
335
|
+
if (out && !cleared.has(out)) {
|
|
336
|
+
out.fill(0, offset, offset + count);
|
|
337
|
+
cleared.add(out);
|
|
338
|
+
}
|
|
339
|
+
this.n163.render(count, buffers.n163, offset);
|
|
340
|
+
}
|
|
316
341
|
let done = 0;
|
|
317
342
|
while (done < count) {
|
|
318
343
|
// Samples before the one on which the counter reaches zero. Subtracting
|
|
@@ -556,6 +581,8 @@ export class Apu {
|
|
|
556
581
|
constant: n.constant,
|
|
557
582
|
enabled: n.enabled,
|
|
558
583
|
},
|
|
584
|
+
...(this.fds ? { fds: this.fds.snapshot() } : {}),
|
|
585
|
+
...(this.n163 ? { n163: this.n163.snapshot() } : {}),
|
|
559
586
|
dmc: {
|
|
560
587
|
level: this.dmc.level,
|
|
561
588
|
rateIndex: this.dmc.rateIndex,
|
package/dist/chip.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chip.js","sourceRoot":"","sources":["../src/chip.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,EACL,MAAM,EACN,WAAW,EACX,cAAc,EACd,YAAY,EACZ,aAAa,EACb,gBAAgB,EAChB,cAAc,GACf,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAClF,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,WAAW,EAAoB,MAAM,YAAY,CAAC;AAEpF,4DAA4D;AAC5D,MAAM,SAAS,GAAG,UAAU,CAAC,IAAI,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC,CAAC;AACzD,MAAM,aAAa,GAAG,UAAU,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;AAmKtD,MAAM,WAAW,GAAG,GAAa,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;AAE7E,MAAM,QAAQ,GAAG,CAAC,MAAe,EAAS,EAAE,CAAC,CAAC;IAC5C,MAAM;IACN,IAAI,EAAE,CAAC;IACP,IAAI,EAAE,KAAK;IACX,QAAQ,EAAE,KAAK;IACf,MAAM,EAAE,CAAC;IACT,GAAG,EAAE,WAAW,EAAE;IAClB,KAAK,EAAE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gBACvD,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;YACtB,CAAC;YACD,IAAI,CAAC,CAAC,YAAY,KAAK,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC;gBAC1C,CAAC,CAAC,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,aAAa,CAAC;gBACvC,CAAC,CAAC,WAAW,GAAG,KAAK,CAAC;YACxB,CAAC;iBAAM,CAAC;gBACN,CAAC,CAAC,YAAY,IAAI,CAAC,CAAC;YACtB,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * The 2A03's sound half, register by register.\n *\n * `Apu` holds what the chip holds — timers, sequencer positions, length and\n * linear counters, envelopes, sweep units, the frame counter — and changes it\n * only the ways the chip does: through a write to `$4000`–`$4017`, or through\n * its own clocks. Nothing here knows what a note is. That is the point: every\n * NES game's music, whatever its driver, reaches the speaker as writes to\n * these registers, so a synth that takes writes plays any of them.\n *\n * It runs at a fixed sample rate rather than per CPU cycle: `render()` advances\n * the chip a run of samples and reports each channel's output level — 0..15 for\n * the pulses, triangle and noise, 0..127 for the DMC — at every one of them. The\n * mixer and the analogue stage are separate (`mixer.ts`), because a caller that\n * wants to hear one channel alone has to get at the levels before they are mixed.\n *\n * The DMC reads its samples from the cartridge, `$8000`–`$FFFF`; give it that\n * memory as `options.memory` (without it, it reads zeros — a sample that only\n * ever steps down).\n *\n * Not modelled: the DMC's and the frame counter's IRQs, the CPU stall of the\n * DMC's memory reads, and the handful of cycle-exact write/clock races. Periods\n * and levels are the hardware's; timing is exact to the sample.\n *\n * **Speed.** `levels()` runs once per sample — 88 200 times a second of music at\n * the default oversampling — so anything that only changes when a register is\n * written (a channel's step per sample, whether the sweep unit mutes it) is\n * worked out at the write and kept, not recomputed here. The expressions are the\n * same ones, evaluated at a different moment, so the output is bit for bit what\n * recomputing them every sample gives.\n */\n\nimport {\n CPU_HZ,\n DMC_PERIODS,\n DUTY_SEQUENCES,\n LENGTH_TABLE,\n NOISE_PERIODS,\n QUARTER_FRAME_HZ,\n TRIANGLE_STEPS,\n} from './constants.js';\nimport { LONG_CYCLE, LONG_HIGH_BEFORE, LONG_INDEX, LONG_STATES } from './lfsr.js';\nimport { decodeSweep, sweepMutes, sweepTarget, type SweepConfig } from './sweep.js';\n\n/** The four duty sequences flattened, `duty * 8 + step`. */\nconst DUTY_FLAT = Uint8Array.from(DUTY_SEQUENCES.flat());\nconst TRIANGLE_FLAT = Uint8Array.from(TRIANGLE_STEPS);\n\ninterface Envelope {\n start: boolean;\n divider: number;\n decay: number;\n}\n\ninterface Pulse {\n pulse1: boolean;\n duty: number;\n /** Bit 5 of `$4000`: halts the length counter AND loops the envelope — one bit, two jobs. */\n halt: boolean;\n constant: boolean;\n /** Bits 0..3 of `$4000`: the level when `constant`, the envelope's divider period when not. */\n volume: number;\n env: Envelope;\n sweep: SweepConfig;\n sweepDivider: number;\n sweepReload: boolean;\n /** The 11-bit timer period. */\n period: number;\n length: number;\n enabled: boolean;\n /** Position in the 8-step duty sequence, fractional. */\n phase: number;\n /** Steps of the sequence per sample, from `period` — kept, see \"Speed\". */\n step: number;\n /** Whether the sweep unit mutes the channel at this period — kept, see \"Speed\". */\n muted: boolean;\n}\n\ninterface Triangle {\n /** Bit 7 of `$4008`: halts the length counter and keeps reloading the linear counter. */\n control: boolean;\n linearReload: number;\n linearReloadFlag: boolean;\n linear: number;\n period: number;\n length: number;\n enabled: boolean;\n phase: number;\n step: number;\n}\n\ninterface Noise {\n halt: boolean;\n constant: boolean;\n volume: number;\n env: Envelope;\n /** Bit 7 of `$400E`: feedback from bit 6 instead of bit 1 — the short, metallic 93-step loop. */\n shortMode: boolean;\n periodIndex: number;\n length: number;\n enabled: boolean;\n /**\n * The register. In normal mode it is held as a position in the precomputed\n * cycle (`lfsrIndex`) and `lfsr` is stale; in short mode `lfsr` is the state.\n * A mode switch converts one into the other.\n */\n lfsr: number;\n lfsrIndex: number;\n /** Fractional timer position: how many register shifts are owed. */\n phase: number;\n step: number;\n}\n\n/**\n * What the chip is doing right now, channel by channel — for showing it, not\n * for driving it. Every field is a number the hardware itself holds.\n */\n/**\n * The delta modulation channel: 1-bit samples read from cartridge memory, each\n * bit stepping a 7-bit output up or down by 2.\n */\ninterface Dmc {\n loop: boolean;\n rateIndex: number;\n /** Output level, 0..127. `$4011` sets it directly. */\n level: number;\n /** `$4012`/`$4013` as addresses and byte counts. */\n startAddress: number;\n startLength: number;\n /** The memory reader: where it reads next, and how many bytes are left. */\n address: number;\n remaining: number;\n /** The one-byte sample buffer, or -1 when empty. */\n buffer: number;\n /** The output unit: its shift register, bits left in it, and whether it is silent. */\n shift: number;\n bits: number;\n silence: boolean;\n phase: number;\n step: number;\n}\n\n/** Where every channel's output levels go, sample by sample. */\nexport interface ChannelBuffers {\n pulse1: Uint8Array;\n pulse2: Uint8Array;\n triangle: Uint8Array;\n /** Fractional: the gate is averaged over the shifts in a sample. */\n noise: Float64Array;\n dmc: Uint8Array;\n}\n\n/** Cartridge memory for the DMC: the bytes of `$8000`–`$FFFF`, or a reader for any address. */\nexport type ApuMemory = Uint8Array | ((address: number) => number);\n\nexport interface ApuSnapshot {\n pulse: {\n period: number;\n duty: number;\n /** Length counter, in half-frames; 0 is silent. */\n length: number;\n /** Level the channel outputs when high: the written volume, or the envelope's decay. */\n level: number;\n constant: boolean;\n /** The sweep unit is muting the channel (period < 8, or target past $7FF). */\n muted: boolean;\n enabled: boolean;\n }[];\n triangle: {\n period: number;\n length: number;\n /** Linear counter, in quarter-frames; 0 is silent. */\n linear: number;\n /** The step the staircase is on — held while silent. */\n step: number;\n enabled: boolean;\n };\n noise: {\n periodIndex: number;\n shortMode: boolean;\n length: number;\n level: number;\n constant: boolean;\n enabled: boolean;\n };\n dmc: {\n /** Output level, 0..127. */\n level: number;\n rateIndex: number;\n loop: boolean;\n /** Bytes of the sample still to read; above 0 means it is playing. */\n remaining: number;\n /** Where the memory reader is. */\n address: number;\n enabled: boolean;\n };\n}\n\nexport interface ApuChipOptions {\n /**\n * Honour the length counters. Default true — it is hardware, and without it\n * a drum hit written with a short counter runs on as a wash. Off exists to\n * hear the difference.\n */\n lengthCounter?: boolean;\n /** Where the DMC reads its samples from — see `ApuMemory`. Reads 0 when absent. */\n memory?: ApuMemory;\n}\n\nconst newEnvelope = (): Envelope => ({ start: false, divider: 0, decay: 0 });\n\nconst newPulse = (pulse1: boolean): Pulse => ({\n pulse1,\n duty: 0,\n halt: false,\n constant: false,\n volume: 0,\n env: newEnvelope(),\n sweep: decodeSweep(0, pulse1),\n sweepDivider: 0,\n sweepReload: false,\n period: 0,\n length: 0,\n enabled: false,\n phase: 0,\n step: 0,\n muted: true,\n});\n\n/** One quarter-frame of an envelope, in the hardware's order. */\nfunction clockEnvelope(env: Envelope, period: number, loop: boolean) {\n if (env.start) {\n env.start = false;\n env.decay = 15;\n env.divider = period;\n } else if (env.divider === 0) {\n env.divider = period;\n if (env.decay > 0) env.decay -= 1;\n else if (loop) env.decay = 15;\n } else {\n env.divider -= 1;\n }\n}\n\nexport class Apu {\n readonly sampleRate: number;\n private readonly lengthCounter: boolean;\n\n private readonly pulses: [Pulse, Pulse] = [newPulse(true), newPulse(false)];\n private readonly triangle: Triangle = {\n control: false,\n linearReload: 0,\n linearReloadFlag: false,\n linear: 0,\n period: 0,\n length: 0,\n enabled: false,\n // Start on a zero step, so a chip that has not been written to is silent\n // rather than holding the top of the staircase as DC. The triangle's\n // position only moves while it sounds, so this is where it rests until the\n // first note — the part of power-on a listener would otherwise hear as a\n // thump.\n phase: 16,\n step: 0,\n };\n private readonly noise: Noise = {\n halt: false,\n constant: false,\n volume: 0,\n env: newEnvelope(),\n shortMode: false,\n periodIndex: 0,\n length: 0,\n enabled: false,\n lfsr: 1, // the chip powers up with bit 0 set\n lfsrIndex: LONG_INDEX[1],\n phase: 0,\n step: 0,\n };\n\n private readonly dmc: Dmc = {\n loop: false,\n rateIndex: 0,\n level: 0,\n startAddress: 0xc000,\n startLength: 1,\n address: 0xc000,\n remaining: 0,\n buffer: -1,\n shift: 0,\n bits: 8,\n silence: true,\n phase: 0,\n step: 0,\n };\n private readonly read: (address: number) => number;\n\n /** Frame counter: 5-step mode, which step is next, samples until it. */\n private fiveStep = false;\n private frameStep = 0;\n private frameCountdown: number;\n private readonly samplesPerQuarterFrame: number;\n\n private readonly out = [0, 0, 0, 0, 0];\n\n constructor(sampleRate: number, options: ApuChipOptions = {}) {\n this.sampleRate = sampleRate;\n this.lengthCounter = options.lengthCounter !== false;\n this.samplesPerQuarterFrame = sampleRate / QUARTER_FRAME_HZ;\n this.frameCountdown = this.samplesPerQuarterFrame;\n for (const p of this.pulses) this.retunePulse(p);\n this.retuneTriangle();\n this.retuneNoise();\n this.retuneDmc();\n const memory = options.memory;\n this.read =\n typeof memory === 'function'\n ? (address) => memory(address) & 0xff\n : memory && memory.length > 0\n ? (address) => memory[(address - 0x8000) % memory.length]\n : () => 0;\n }\n\n /** A CPU write to one of the APU's registers. Anything outside `$4000`–`$4017` is ignored. */\n write(address: number, value: number) {\n const v = value & 0xff;\n switch (address) {\n case 0x4000:\n case 0x4004: {\n const p = this.pulses[address === 0x4000 ? 0 : 1];\n p.duty = v >> 6;\n p.halt = (v & 0x20) !== 0;\n p.constant = (v & 0x10) !== 0;\n p.volume = v & 0x0f;\n return;\n }\n case 0x4001:\n case 0x4005: {\n const p = this.pulses[address === 0x4001 ? 0 : 1];\n p.sweep = decodeSweep(v, p.pulse1);\n p.sweepReload = true;\n p.muted = sweepMutes(p.period, p.sweep);\n return;\n }\n case 0x4002:\n case 0x4006: {\n const p = this.pulses[address === 0x4002 ? 0 : 1];\n p.period = (p.period & 0x700) | v;\n this.retunePulse(p);\n return;\n }\n case 0x4003:\n case 0x4007: {\n // The high byte does three things at once, and all three are audible:\n // it reloads the length counter, restarts the envelope, and puts the\n // duty sequencer back to its first step — which is why a driver that\n // rewrites it every frame for a vibrato makes the vibrato click.\n const p = this.pulses[address === 0x4003 ? 0 : 1];\n p.period = (p.period & 0xff) | ((v & 7) << 8);\n if (p.enabled) p.length = LENGTH_TABLE[v >> 3];\n p.env.start = true;\n p.phase = 0;\n this.retunePulse(p);\n return;\n }\n case 0x4008:\n this.triangle.control = (v & 0x80) !== 0;\n this.triangle.linearReload = v & 0x7f;\n return;\n case 0x400a:\n this.triangle.period = (this.triangle.period & 0x700) | v;\n this.retuneTriangle();\n return;\n case 0x400b:\n // No phase reset here: the triangle's sequencer is never restarted, so\n // a new note picks up the staircase wherever the last one left it.\n this.triangle.period = (this.triangle.period & 0xff) | ((v & 7) << 8);\n if (this.triangle.enabled) this.triangle.length = LENGTH_TABLE[v >> 3];\n this.triangle.linearReloadFlag = true;\n this.retuneTriangle();\n return;\n case 0x400c:\n this.noise.halt = (v & 0x20) !== 0;\n this.noise.constant = (v & 0x10) !== 0;\n this.noise.volume = v & 0x0f;\n return;\n case 0x400e: {\n const n = this.noise;\n const shortMode = (v & 0x80) !== 0;\n // Hand the register between its two representations: a position in the\n // precomputed cycle for normal mode, the raw state for short mode.\n if (shortMode && !n.shortMode) n.lfsr = LONG_STATES[n.lfsrIndex];\n if (!shortMode && n.shortMode) n.lfsrIndex = LONG_INDEX[n.lfsr];\n n.shortMode = shortMode;\n n.periodIndex = v & 0x0f;\n this.retuneNoise();\n return;\n }\n case 0x400f:\n if (this.noise.enabled) this.noise.length = LENGTH_TABLE[v >> 3];\n this.noise.env.start = true;\n return;\n case 0x4010:\n this.dmc.loop = (v & 0x40) !== 0;\n this.dmc.rateIndex = v & 0x0f;\n this.retuneDmc();\n return;\n case 0x4011:\n // Straight to the output — the way games play PCM without the DMC's\n // own memory reader, one write per sample.\n this.dmc.level = v & 0x7f;\n return;\n case 0x4012:\n this.dmc.startAddress = 0xc000 + v * 64;\n return;\n case 0x4013:\n this.dmc.startLength = v * 16 + 1;\n return;\n case 0x4015: {\n // Clearing a channel's bit empties its length counter at once — the\n // one way to silence a channel on the spot rather than at the next clock.\n const channels = [this.pulses[0], this.pulses[1], this.triangle, this.noise];\n channels.forEach((channel, i) => {\n channel.enabled = (v & (1 << i)) !== 0;\n if (!channel.enabled) channel.length = 0;\n });\n // Bit 4 is the DMC's: clear stops the sample (what is already in the\n // buffer still plays out); set starts it again if it had finished.\n const d = this.dmc;\n if ((v & 0x10) === 0) d.remaining = 0;\n else if (d.remaining === 0) {\n d.address = d.startAddress;\n d.remaining = d.startLength;\n this.fetchDmc();\n }\n return;\n }\n case 0x4017:\n this.fiveStep = (v & 0x80) !== 0;\n this.frameStep = 0;\n this.frameCountdown = this.samplesPerQuarterFrame;\n // Selecting 5-step mode clocks everything once, immediately.\n if (this.fiveStep) {\n this.clockQuarterFrame();\n this.clockHalfFrame();\n }\n return;\n default:\n return;\n }\n }\n\n /** Scratch buffers for `levels()`, one sample long. */\n private readonly one: ChannelBuffers = {\n pulse1: new Uint8Array(1),\n pulse2: new Uint8Array(1),\n triangle: new Uint8Array(1),\n noise: new Float64Array(1),\n dmc: new Uint8Array(1),\n };\n\n /**\n * Advance one sample and return the five channel levels, `[pulse1, pulse2,\n * triangle, noise, dmc]` (see `render`). The array is reused between calls.\n * For more than a sample at a time, `render` is several times faster and\n * gives the same numbers.\n */\n levels(): readonly number[] {\n const one = this.one;\n this.render(1, one);\n const out = this.out;\n out[0] = one.pulse1[0];\n out[1] = one.pulse2[0];\n out[2] = one.triangle[0];\n out[3] = one.noise[0];\n out[4] = one.dmc[0];\n return out;\n }\n\n /**\n * Advance `count` samples, writing each channel's level into its buffer from\n * `offset` on: the pulses, triangle and DMC as whole numbers (0..15, 0..127),\n * the noise fractional (its gate is averaged over the shifts in a sample). No\n * register writes happen inside — a caller with writes due splits the run at\n * them.\n *\n * The frame counter is the only thing that changes a channel's parameters\n * between writes, so the run is cut at its clocks and each piece is filled a\n * channel at a time (`fill`). Every sum is the one `levels()` would do, in the\n * same order — the buffers come out bit for bit the same as `count` calls.\n */\n render(count: number, buffers: ChannelBuffers, offset = 0) {\n let done = 0;\n while (done < count) {\n // Samples before the one on which the counter reaches zero. Subtracting\n // them in one go is exact: the counter holds a value whose fractional\n // bits are all representable after taking off a whole number.\n const free = Math.ceil(this.frameCountdown) - 1;\n if (free <= 0) {\n this.frameCountdown -= 1;\n while (this.frameCountdown <= 0) {\n this.frameCountdown += this.samplesPerQuarterFrame;\n this.clockFrameCounter();\n }\n this.fill(1, buffers, offset + done);\n done += 1;\n } else {\n const run = Math.min(free, count - done);\n this.frameCountdown -= run;\n this.fill(run, buffers, offset + done);\n done += run;\n }\n }\n }\n\n /** `count` samples with every channel's parameters fixed — tight loops on locals. */\n private fill(count: number, buffers: ChannelBuffers, at: number) {\n const end = at + count;\n const { pulse1, pulse2, triangle, noise } = buffers;\n\n for (let i = 0; i < 2; i++) {\n const p = this.pulses[i];\n const out = i === 0 ? pulse1 : pulse2;\n // A pulse steps through 8 entries per cycle and each entry takes\n // 2 × (period + 1) CPU cycles: CPU / (16 × (period + 1)) per cycle.\n const step = p.step;\n let phase = p.phase;\n if (p.length === 0 || p.muted) {\n for (let k = at; k < end; k++) {\n phase += step;\n if (phase >= 8) phase %= 8;\n out[k] = 0;\n }\n } else {\n const level = p.constant ? p.volume : p.env.decay;\n const base = p.duty * 8;\n for (let k = at; k < end; k++) {\n phase += step;\n if (phase >= 8) phase %= 8;\n out[k] = DUTY_FLAT[base + ((phase | 0) & 7)] * level;\n }\n }\n p.phase = phase;\n }\n\n const t = this.triangle;\n // The staircase only moves while both counters are non-zero. When either\n // runs out the sequencer STOPS where it is and the output holds that step:\n // the triangle is never \"at zero\" between notes, it is wherever it paused.\n if (t.length > 0 && t.linear > 0) {\n const step = t.step;\n let phase = t.phase;\n for (let k = at; k < end; k++) {\n phase += step;\n if (phase >= 32) phase %= 32;\n triangle[k] = TRIANGLE_FLAT[(phase | 0) & 31];\n }\n t.phase = phase;\n } else {\n triangle.fill(TRIANGLE_FLAT[(t.phase | 0) & 31], at, end);\n }\n\n // AVERAGE the register's output across the shifts each sample is worth,\n // rather than sampling wherever it lands. At the short periods the LFSR\n // runs well past the sample rate, and keeping only the last shift folds the\n // rest back as alias tones — drums like a broken speaker. The channel is\n // silenced while bit 0 is set: the register gates it.\n const n = this.noise;\n const level = n.length === 0 ? 0 : n.constant ? n.volume : n.env.decay;\n const step = n.step;\n let phase = n.phase;\n if (!n.shortMode) {\n let index = n.lfsrIndex;\n if (level === 0) {\n // Silent, but the register keeps shifting: advance it, output nothing.\n for (let k = at; k < end; k++) {\n phase += step;\n // A few shifts per sample at most, so one conditional subtraction\n // wraps the index — no division. (Math.floor, not `| 0`: the phase is\n // a double, and a round trip through int32 measured 20% slower.)\n const shifts = Math.floor(phase);\n phase -= shifts;\n index += shifts;\n if (index >= LONG_CYCLE) index -= LONG_CYCLE;\n }\n noise.fill(0, at, end);\n } else {\n for (let k = at; k < end; k++) {\n phase += step;\n const shifts = Math.floor(phase);\n phase -= shifts;\n let gate: number;\n if (shifts > 0) {\n gate = (LONG_HIGH_BEFORE[index + shifts] - LONG_HIGH_BEFORE[index]) / shifts;\n index += shifts;\n if (index >= LONG_CYCLE) index -= LONG_CYCLE;\n } else {\n gate = (LONG_STATES[index] & 1) === 0 ? 1 : 0;\n }\n noise[k] = gate * level;\n }\n }\n n.lfsrIndex = index;\n } else {\n let lfsr = n.lfsr;\n for (let k = at; k < end; k++) {\n phase += step;\n const shifts = Math.floor(phase);\n phase -= shifts;\n let high = 0;\n for (let s = 0; s < shifts; s++) {\n if ((lfsr & 1) === 0) high++;\n const feedback = (lfsr & 1) ^ ((lfsr >> 6) & 1);\n lfsr = (lfsr >> 1) | (feedback << 14);\n }\n const gate = shifts > 0 ? high / shifts : (lfsr & 1) === 0 ? 1 : 0;\n noise[k] = level === 0 ? 0 : gate * level;\n }\n n.lfsr = lfsr;\n }\n n.phase = phase;\n\n this.fillDmc(buffers.dmc, at, end);\n }\n\n /**\n * The DMC over `[at, end)`. At most a bit or two per sample even at its\n * fastest rate, so it is clocked bit by bit; a channel with nothing to play\n * only has its output-cycle count moved on, which is all that changes.\n */\n private fillDmc(out: Uint8Array, at: number, end: number) {\n const d = this.dmc;\n if (d.silence && d.remaining === 0 && d.buffer < 0) {\n // Nothing to play: the output holds, and only the timer and the bit count\n // move on. Worked out for the whole run at once — nothing audible depends\n // on the timer's exact fraction until a sample starts, and starting one\n // takes a register write, which ends the run.\n const total = d.phase + d.step * (end - at);\n const clocks = Math.floor(total);\n d.phase = total - clocks;\n // Each clock uses up a bit; an emptied cycle starts another, silent,\n // since there is nothing to load.\n d.bits -= clocks % 8;\n if (d.bits <= 0) d.bits += 8;\n out.fill(d.level, at, end);\n return;\n }\n for (let k = at; k < end; k++) {\n d.phase += d.step;\n while (d.phase >= 1) {\n d.phase -= 1;\n this.clockDmc();\n }\n out[k] = d.level;\n }\n }\n\n /** One DMC timer clock: step the output by the next bit, and start a new byte after eight. */\n private clockDmc() {\n const d = this.dmc;\n if (!d.silence) {\n if (d.shift & 1) {\n if (d.level <= 125) d.level += 2;\n } else if (d.level >= 2) {\n d.level -= 2;\n }\n }\n d.shift >>= 1;\n d.bits -= 1;\n if (d.bits === 0) {\n d.bits = 8;\n if (d.buffer < 0) {\n d.silence = true;\n } else {\n d.silence = false;\n d.shift = d.buffer;\n d.buffer = -1;\n this.fetchDmc();\n }\n }\n }\n\n /** The memory reader: refill the empty buffer from the cartridge, looping or stopping at the end. */\n private fetchDmc() {\n const d = this.dmc;\n if (d.buffer >= 0 || d.remaining === 0) return;\n d.buffer = this.read(d.address);\n d.address = d.address === 0xffff ? 0x8000 : d.address + 1;\n d.remaining -= 1;\n if (d.remaining === 0 && d.loop) {\n d.address = d.startAddress;\n d.remaining = d.startLength;\n }\n }\n\n private retuneDmc() {\n this.dmc.step = CPU_HZ / DMC_PERIODS[this.dmc.rateIndex] / this.sampleRate;\n }\n\n /** A copy of the channels' internal counters and levels — see `ApuSnapshot`. */\n snapshot(): ApuSnapshot {\n const t = this.triangle;\n const n = this.noise;\n return {\n pulse: this.pulses.map((p) => ({\n period: p.period,\n duty: p.duty,\n length: p.length,\n level: p.constant ? p.volume : p.env.decay,\n constant: p.constant,\n muted: p.muted,\n enabled: p.enabled,\n })),\n triangle: {\n period: t.period,\n length: t.length,\n linear: t.linear,\n step: TRIANGLE_FLAT[(t.phase | 0) & 31],\n enabled: t.enabled,\n },\n noise: {\n periodIndex: n.periodIndex,\n shortMode: n.shortMode,\n length: n.length,\n level: n.constant ? n.volume : n.env.decay,\n constant: n.constant,\n enabled: n.enabled,\n },\n dmc: {\n level: this.dmc.level,\n rateIndex: this.dmc.rateIndex,\n loop: this.dmc.loop,\n remaining: this.dmc.remaining,\n address: this.dmc.address,\n enabled: this.dmc.remaining > 0,\n },\n };\n }\n\n private retunePulse(p: Pulse) {\n p.step = CPU_HZ / (2 * (p.period + 1)) / this.sampleRate;\n p.muted = sweepMutes(p.period, p.sweep);\n }\n\n private retuneTriangle() {\n this.triangle.step = CPU_HZ / (this.triangle.period + 1) / this.sampleRate;\n }\n\n private retuneNoise() {\n this.noise.step = CPU_HZ / NOISE_PERIODS[this.noise.periodIndex] / this.sampleRate;\n }\n\n private clockFrameCounter() {\n // 4-step: quarter frames on every step, half frames on steps 2 and 4.\n // 5-step: quarter frames on 1, 2, 3 and 5, half frames on 2 and 5.\n const step = this.frameStep;\n if (this.fiveStep) {\n this.frameStep = (step + 1) % 5;\n if (step !== 3) this.clockQuarterFrame();\n if (step === 1 || step === 4) this.clockHalfFrame();\n } else {\n this.frameStep = (step + 1) % 4;\n this.clockQuarterFrame();\n if (step === 1 || step === 3) this.clockHalfFrame();\n }\n }\n\n private clockQuarterFrame() {\n for (const p of this.pulses) clockEnvelope(p.env, p.volume, p.halt);\n clockEnvelope(this.noise.env, this.noise.volume, this.noise.halt);\n\n const t = this.triangle;\n if (t.linearReloadFlag) t.linear = t.linearReload;\n else if (t.linear > 0) t.linear -= 1;\n if (!t.control) t.linearReloadFlag = false;\n }\n\n private clockHalfFrame() {\n if (this.lengthCounter) {\n for (const p of this.pulses) if (!p.halt && p.length > 0) p.length -= 1;\n if (!this.triangle.control && this.triangle.length > 0) this.triangle.length -= 1;\n if (!this.noise.halt && this.noise.length > 0) this.noise.length -= 1;\n }\n\n for (const p of this.pulses) {\n // The hardware's order: adjust first, then reload or count down.\n if (p.sweepDivider === 0 && p.sweep.enabled && p.sweep.shift > 0 && !p.muted) {\n p.period = Math.max(0, sweepTarget(p.period, p.sweep));\n this.retunePulse(p);\n }\n if (p.sweepDivider === 0 || p.sweepReload) {\n p.sweepDivider = p.sweep.dividerPeriod;\n p.sweepReload = false;\n } else {\n p.sweepDivider -= 1;\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"chip.js","sourceRoot":"","sources":["../src/chip.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,EACL,MAAM,EACN,WAAW,EACX,cAAc,EACd,YAAY,EACZ,aAAa,EACb,gBAAgB,EAChB,cAAc,GACf,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAClF,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,WAAW,EAAoB,MAAM,YAAY,CAAC;AACpF,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAuC,MAAM,gBAAgB,CAAC;AAExF,4DAA4D;AAC5D,MAAM,SAAS,GAAG,UAAU,CAAC,IAAI,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC,CAAC;AACzD,MAAM,aAAa,GAAG,UAAU,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;AAkLtD,MAAM,WAAW,GAAG,GAAa,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;AAE7E,MAAM,QAAQ,GAAG,CAAC,MAAe,EAAS,EAAE,CAAC,CAAC;IAC5C,MAAM;IACN,IAAI,EAAE,CAAC;IACP,IAAI,EAAE,KAAK;IACX,QAAQ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BAAE,IAAI,CAAC,KAAK,CAAC,MAAM,IAAI,CAAC,CAAC;QACxE,CAAC;QAED,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAC5B,iEAAiE;YACjE,IAAI,CAAC,CAAC,YAAY,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,OAAO,IAAI,CAAC,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;gBAC7E,CAAC,CAAC,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,WAAW,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;gBACvD,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;YACtB,CAAC;YACD,IAAI,CAAC,CAAC,YAAY,KAAK,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC;gBAC1C,CAAC,CAAC,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,aAAa,CAAC;gBACvC,CAAC,CAAC,WAAW,GAAG,KAAK,CAAC;YACxB,CAAC;iBAAM,CAAC;gBACN,CAAC,CAAC,YAAY,IAAI,CAAC,CAAC;YACtB,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * The 2A03's sound half, register by register.\n *\n * `Apu` holds what the chip holds — timers, sequencer positions, length and\n * linear counters, envelopes, sweep units, the frame counter — and changes it\n * only the ways the chip does: through a write to `$4000`–`$4017`, or through\n * its own clocks. Nothing here knows what a note is. That is the point: every\n * NES game's music, whatever its driver, reaches the speaker as writes to\n * these registers, so a synth that takes writes plays any of them.\n *\n * It runs at a fixed sample rate rather than per CPU cycle: `render()` advances\n * the chip a run of samples and reports each channel's output level — 0..15 for\n * the pulses, triangle and noise, 0..127 for the DMC — at every one of them. The\n * mixer and the analogue stage are separate (`mixer.ts`), because a caller that\n * wants to hear one channel alone has to get at the levels before they are mixed.\n *\n * The DMC reads its samples from the cartridge, `$8000`–`$FFFF`; give it that\n * memory as `options.memory` (without it, it reads zeros — a sample that only\n * ever steps down).\n *\n * Not modelled: the DMC's and the frame counter's IRQs, the CPU stall of the\n * DMC's memory reads, and the handful of cycle-exact write/clock races. Periods\n * and levels are the hardware's; timing is exact to the sample.\n *\n * **Speed.** `levels()` runs once per sample — 88 200 times a second of music at\n * the default oversampling — so anything that only changes when a register is\n * written (a channel's step per sample, whether the sweep unit mutes it) is\n * worked out at the write and kept, not recomputed here. The expressions are the\n * same ones, evaluated at a different moment, so the output is bit for bit what\n * recomputing them every sample gives.\n */\n\nimport {\n CPU_HZ,\n DMC_PERIODS,\n DUTY_SEQUENCES,\n LENGTH_TABLE,\n NOISE_PERIODS,\n QUARTER_FRAME_HZ,\n TRIANGLE_STEPS,\n} from './constants.js';\nimport { LONG_CYCLE, LONG_HIGH_BEFORE, LONG_INDEX, LONG_STATES } from './lfsr.js';\nimport { decodeSweep, sweepMutes, sweepTarget, type SweepConfig } from './sweep.js';\nimport { FdsChip, N163Chip, type FdsSnapshot, type N163Snapshot } from './expansion.js';\n\n/** The four duty sequences flattened, `duty * 8 + step`. */\nconst DUTY_FLAT = Uint8Array.from(DUTY_SEQUENCES.flat());\nconst TRIANGLE_FLAT = Uint8Array.from(TRIANGLE_STEPS);\n\ninterface Envelope {\n start: boolean;\n divider: number;\n decay: number;\n}\n\ninterface Pulse {\n pulse1: boolean;\n duty: number;\n /** Bit 5 of `$4000`: halts the length counter AND loops the envelope — one bit, two jobs. */\n halt: boolean;\n constant: boolean;\n /** Bits 0..3 of `$4000`: the level when `constant`, the envelope's divider period when not. */\n volume: number;\n env: Envelope;\n sweep: SweepConfig;\n sweepDivider: number;\n sweepReload: boolean;\n /** The 11-bit timer period. */\n period: number;\n length: number;\n enabled: boolean;\n /** Position in the 8-step duty sequence, fractional. */\n phase: number;\n /** Steps of the sequence per sample, from `period` — kept, see \"Speed\". */\n step: number;\n /** Whether the sweep unit mutes the channel at this period — kept, see \"Speed\". */\n muted: boolean;\n}\n\ninterface Triangle {\n /** Bit 7 of `$4008`: halts the length counter and keeps reloading the linear counter. */\n control: boolean;\n linearReload: number;\n linearReloadFlag: boolean;\n linear: number;\n period: number;\n length: number;\n enabled: boolean;\n phase: number;\n step: number;\n}\n\ninterface Noise {\n halt: boolean;\n constant: boolean;\n volume: number;\n env: Envelope;\n /** Bit 7 of `$400E`: feedback from bit 6 instead of bit 1 — the short, metallic 93-step loop. */\n shortMode: boolean;\n periodIndex: number;\n length: number;\n enabled: boolean;\n /**\n * The register. In normal mode it is held as a position in the precomputed\n * cycle (`lfsrIndex`) and `lfsr` is stale; in short mode `lfsr` is the state.\n * A mode switch converts one into the other.\n */\n lfsr: number;\n lfsrIndex: number;\n /** Fractional timer position: how many register shifts are owed. */\n phase: number;\n step: number;\n}\n\n/**\n * What the chip is doing right now, channel by channel — for showing it, not\n * for driving it. Every field is a number the hardware itself holds.\n */\n/**\n * The delta modulation channel: 1-bit samples read from cartridge memory, each\n * bit stepping a 7-bit output up or down by 2.\n */\ninterface Dmc {\n loop: boolean;\n rateIndex: number;\n /** Output level, 0..127. `$4011` sets it directly. */\n level: number;\n /** `$4012`/`$4013` as addresses and byte counts. */\n startAddress: number;\n startLength: number;\n /** The memory reader: where it reads next, and how many bytes are left. */\n address: number;\n remaining: number;\n /** The one-byte sample buffer, or -1 when empty. */\n buffer: number;\n /** The output unit: its shift register, bits left in it, and whether it is silent. */\n shift: number;\n bits: number;\n silence: boolean;\n phase: number;\n step: number;\n}\n\n/** Where every channel's output levels go, sample by sample. */\nexport interface ChannelBuffers {\n pulse1: Uint8Array;\n pulse2: Uint8Array;\n triangle: Uint8Array;\n /** Fractional: the gate is averaged over the shifts in a sample. */\n noise: Float64Array;\n dmc: Uint8Array;\n /** The FDS wave channel, in `mixApu` units (added to, not overwritten) — when the chip has one. */\n fds?: Float64Array;\n /**\n * The N163's channels by register slot 0..7 (slot 7, `$78`, is the one always on), in `mixApu`\n * units; index 8, if given, takes every slot without a buffer of its own.\n */\n n163?: (Float64Array | undefined)[];\n}\n\n/** Cartridge memory for the DMC: the bytes of `$8000`–`$FFFF`, or a reader for any address. */\nexport type ApuMemory = Uint8Array | ((address: number) => number);\n\nexport interface ApuSnapshot {\n pulse: {\n period: number;\n duty: number;\n /** Length counter, in half-frames; 0 is silent. */\n length: number;\n /** Level the channel outputs when high: the written volume, or the envelope's decay. */\n level: number;\n constant: boolean;\n /** The sweep unit is muting the channel (period < 8, or target past $7FF). */\n muted: boolean;\n enabled: boolean;\n }[];\n triangle: {\n period: number;\n length: number;\n /** Linear counter, in quarter-frames; 0 is silent. */\n linear: number;\n /** The step the staircase is on — held while silent. */\n step: number;\n enabled: boolean;\n };\n noise: {\n periodIndex: number;\n shortMode: boolean;\n length: number;\n level: number;\n constant: boolean;\n enabled: boolean;\n };\n /** The expansion chips' state, when the chip has them (`ApuChipOptions.expansion`). */\n fds?: FdsSnapshot;\n n163?: N163Snapshot;\n dmc: {\n /** Output level, 0..127. */\n level: number;\n rateIndex: number;\n loop: boolean;\n /** Bytes of the sample still to read; above 0 means it is playing. */\n remaining: number;\n /** Where the memory reader is. */\n address: number;\n enabled: boolean;\n };\n}\n\nexport interface ApuChipOptions {\n /**\n * Honour the length counters. Default true — it is hardware, and without it\n * a drum hit written with a short counter runs on as a wash. Off exists to\n * hear the difference.\n */\n lengthCounter?: boolean;\n /** Where the DMC reads its samples from — see `ApuMemory`. Reads 0 when absent. */\n memory?: ApuMemory;\n /**\n * Expansion sound on the cartridge: `'FDS'` takes `$4040`–`$408A`, `'N163'` its address port\n * (`$F800`), data port (`$4800`) and `$E000`. Their output goes to `ChannelBuffers.fds`/`n163`.\n */\n expansion?: readonly string[];\n}\n\nconst newEnvelope = (): Envelope => ({ start: false, divider: 0, decay: 0 });\n\nconst newPulse = (pulse1: boolean): Pulse => ({\n pulse1,\n duty: 0,\n halt: false,\n constant: false,\n volume: 0,\n env: newEnvelope(),\n sweep: decodeSweep(0, pulse1),\n sweepDivider: 0,\n sweepReload: false,\n period: 0,\n length: 0,\n enabled: false,\n phase: 0,\n step: 0,\n muted: true,\n});\n\n/** One quarter-frame of an envelope, in the hardware's order. */\nfunction clockEnvelope(env: Envelope, period: number, loop: boolean) {\n if (env.start) {\n env.start = false;\n env.decay = 15;\n env.divider = period;\n } else if (env.divider === 0) {\n env.divider = period;\n if (env.decay > 0) env.decay -= 1;\n else if (loop) env.decay = 15;\n } else {\n env.divider -= 1;\n }\n}\n\nexport class Apu {\n readonly sampleRate: number;\n /** The Disk System's wave channel, when `expansion` has `'FDS'`. */\n readonly fds: FdsChip | null;\n /** Namco's 163, when `expansion` has `'N163'`. */\n readonly n163: N163Chip | null;\n private readonly lengthCounter: boolean;\n\n private readonly pulses: [Pulse, Pulse] = [newPulse(true), newPulse(false)];\n private readonly triangle: Triangle = {\n control: false,\n linearReload: 0,\n linearReloadFlag: false,\n linear: 0,\n period: 0,\n length: 0,\n enabled: false,\n // Start on a zero step, so a chip that has not been written to is silent\n // rather than holding the top of the staircase as DC. The triangle's\n // position only moves while it sounds, so this is where it rests until the\n // first note — the part of power-on a listener would otherwise hear as a\n // thump.\n phase: 16,\n step: 0,\n };\n private readonly noise: Noise = {\n halt: false,\n constant: false,\n volume: 0,\n env: newEnvelope(),\n shortMode: false,\n periodIndex: 0,\n length: 0,\n enabled: false,\n lfsr: 1, // the chip powers up with bit 0 set\n lfsrIndex: LONG_INDEX[1],\n phase: 0,\n step: 0,\n };\n\n private readonly dmc: Dmc = {\n loop: false,\n rateIndex: 0,\n level: 0,\n startAddress: 0xc000,\n startLength: 1,\n address: 0xc000,\n remaining: 0,\n buffer: -1,\n shift: 0,\n bits: 8,\n silence: true,\n phase: 0,\n step: 0,\n };\n private readonly read: (address: number) => number;\n\n /** Frame counter: 5-step mode, which step is next, samples until it. */\n private fiveStep = false;\n private frameStep = 0;\n private frameCountdown: number;\n private readonly samplesPerQuarterFrame: number;\n\n private readonly out = [0, 0, 0, 0, 0];\n\n constructor(sampleRate: number, options: ApuChipOptions = {}) {\n this.sampleRate = sampleRate;\n this.lengthCounter = options.lengthCounter !== false;\n this.fds = options.expansion?.includes('FDS') ? new FdsChip(sampleRate) : null;\n this.n163 = options.expansion?.includes('N163') ? new N163Chip(sampleRate) : null;\n this.samplesPerQuarterFrame = sampleRate / QUARTER_FRAME_HZ;\n this.frameCountdown = this.samplesPerQuarterFrame;\n for (const p of this.pulses) this.retunePulse(p);\n this.retuneTriangle();\n this.retuneNoise();\n this.retuneDmc();\n const memory = options.memory;\n this.read =\n typeof memory === 'function'\n ? (address) => memory(address) & 0xff\n : memory && memory.length > 0\n ? (address) => memory[(address - 0x8000) % memory.length]\n : () => 0;\n }\n\n /**\n * A CPU write to one of the APU's registers — or an expansion chip's, when there is one.\n * Anything else is ignored.\n */\n write(address: number, value: number) {\n if (address > 0x4017) {\n if (this.fds?.write(address, value)) return;\n this.n163?.write(address, value);\n return;\n }\n const v = value & 0xff;\n switch (address) {\n case 0x4000:\n case 0x4004: {\n const p = this.pulses[address === 0x4000 ? 0 : 1];\n p.duty = v >> 6;\n p.halt = (v & 0x20) !== 0;\n p.constant = (v & 0x10) !== 0;\n p.volume = v & 0x0f;\n return;\n }\n case 0x4001:\n case 0x4005: {\n const p = this.pulses[address === 0x4001 ? 0 : 1];\n p.sweep = decodeSweep(v, p.pulse1);\n p.sweepReload = true;\n p.muted = sweepMutes(p.period, p.sweep);\n return;\n }\n case 0x4002:\n case 0x4006: {\n const p = this.pulses[address === 0x4002 ? 0 : 1];\n p.period = (p.period & 0x700) | v;\n this.retunePulse(p);\n return;\n }\n case 0x4003:\n case 0x4007: {\n // The high byte does three things at once, and all three are audible:\n // it reloads the length counter, restarts the envelope, and puts the\n // duty sequencer back to its first step — which is why a driver that\n // rewrites it every frame for a vibrato makes the vibrato click.\n const p = this.pulses[address === 0x4003 ? 0 : 1];\n p.period = (p.period & 0xff) | ((v & 7) << 8);\n if (p.enabled) p.length = LENGTH_TABLE[v >> 3];\n p.env.start = true;\n p.phase = 0;\n this.retunePulse(p);\n return;\n }\n case 0x4008:\n this.triangle.control = (v & 0x80) !== 0;\n this.triangle.linearReload = v & 0x7f;\n return;\n case 0x400a:\n this.triangle.period = (this.triangle.period & 0x700) | v;\n this.retuneTriangle();\n return;\n case 0x400b:\n // No phase reset here: the triangle's sequencer is never restarted, so\n // a new note picks up the staircase wherever the last one left it.\n this.triangle.period = (this.triangle.period & 0xff) | ((v & 7) << 8);\n if (this.triangle.enabled) this.triangle.length = LENGTH_TABLE[v >> 3];\n this.triangle.linearReloadFlag = true;\n this.retuneTriangle();\n return;\n case 0x400c:\n this.noise.halt = (v & 0x20) !== 0;\n this.noise.constant = (v & 0x10) !== 0;\n this.noise.volume = v & 0x0f;\n return;\n case 0x400e: {\n const n = this.noise;\n const shortMode = (v & 0x80) !== 0;\n // Hand the register between its two representations: a position in the\n // precomputed cycle for normal mode, the raw state for short mode.\n if (shortMode && !n.shortMode) n.lfsr = LONG_STATES[n.lfsrIndex];\n if (!shortMode && n.shortMode) n.lfsrIndex = LONG_INDEX[n.lfsr];\n n.shortMode = shortMode;\n n.periodIndex = v & 0x0f;\n this.retuneNoise();\n return;\n }\n case 0x400f:\n if (this.noise.enabled) this.noise.length = LENGTH_TABLE[v >> 3];\n this.noise.env.start = true;\n return;\n case 0x4010:\n this.dmc.loop = (v & 0x40) !== 0;\n this.dmc.rateIndex = v & 0x0f;\n this.retuneDmc();\n return;\n case 0x4011:\n // Straight to the output — the way games play PCM without the DMC's\n // own memory reader, one write per sample.\n this.dmc.level = v & 0x7f;\n return;\n case 0x4012:\n this.dmc.startAddress = 0xc000 + v * 64;\n return;\n case 0x4013:\n this.dmc.startLength = v * 16 + 1;\n return;\n case 0x4015: {\n // Clearing a channel's bit empties its length counter at once — the\n // one way to silence a channel on the spot rather than at the next clock.\n const channels = [this.pulses[0], this.pulses[1], this.triangle, this.noise];\n channels.forEach((channel, i) => {\n channel.enabled = (v & (1 << i)) !== 0;\n if (!channel.enabled) channel.length = 0;\n });\n // Bit 4 is the DMC's: clear stops the sample (what is already in the\n // buffer still plays out); set starts it again if it had finished.\n const d = this.dmc;\n if ((v & 0x10) === 0) d.remaining = 0;\n else if (d.remaining === 0) {\n d.address = d.startAddress;\n d.remaining = d.startLength;\n this.fetchDmc();\n }\n return;\n }\n case 0x4017:\n this.fiveStep = (v & 0x80) !== 0;\n this.frameStep = 0;\n this.frameCountdown = this.samplesPerQuarterFrame;\n // Selecting 5-step mode clocks everything once, immediately.\n if (this.fiveStep) {\n this.clockQuarterFrame();\n this.clockHalfFrame();\n }\n return;\n default:\n return;\n }\n }\n\n /** Scratch buffers for `levels()`, one sample long. */\n private readonly one: ChannelBuffers = {\n pulse1: new Uint8Array(1),\n pulse2: new Uint8Array(1),\n triangle: new Uint8Array(1),\n noise: new Float64Array(1),\n dmc: new Uint8Array(1),\n };\n\n /**\n * Advance one sample and return the five channel levels, `[pulse1, pulse2,\n * triangle, noise, dmc]` (see `render`). The array is reused between calls.\n * For more than a sample at a time, `render` is several times faster and\n * gives the same numbers.\n */\n levels(): readonly number[] {\n const one = this.one;\n this.render(1, one);\n const out = this.out;\n out[0] = one.pulse1[0];\n out[1] = one.pulse2[0];\n out[2] = one.triangle[0];\n out[3] = one.noise[0];\n out[4] = one.dmc[0];\n return out;\n }\n\n /**\n * Advance `count` samples, writing each channel's level into its buffer from\n * `offset` on: the pulses, triangle and DMC as whole numbers (0..15, 0..127),\n * the noise fractional (its gate is averaged over the shifts in a sample). No\n * register writes happen inside — a caller with writes due splits the run at\n * them.\n *\n * The frame counter is the only thing that changes a channel's parameters\n * between writes, so the run is cut at its clocks and each piece is filled a\n * channel at a time (`fill`). Every sum is the one `levels()` would do, in the\n * same order — the buffers come out bit for bit the same as `count` calls.\n */\n render(count: number, buffers: ChannelBuffers, offset = 0) {\n if (this.fds && buffers.fds) {\n buffers.fds.fill(0, offset, offset + count);\n this.fds.render(count, buffers.fds, offset);\n }\n if (this.n163 && buffers.n163) {\n const cleared = new Set<Float64Array>();\n for (const out of buffers.n163) if (out && !cleared.has(out)) {\n out.fill(0, offset, offset + count);\n cleared.add(out);\n }\n this.n163.render(count, buffers.n163, offset);\n }\n let done = 0;\n while (done < count) {\n // Samples before the one on which the counter reaches zero. Subtracting\n // them in one go is exact: the counter holds a value whose fractional\n // bits are all representable after taking off a whole number.\n const free = Math.ceil(this.frameCountdown) - 1;\n if (free <= 0) {\n this.frameCountdown -= 1;\n while (this.frameCountdown <= 0) {\n this.frameCountdown += this.samplesPerQuarterFrame;\n this.clockFrameCounter();\n }\n this.fill(1, buffers, offset + done);\n done += 1;\n } else {\n const run = Math.min(free, count - done);\n this.frameCountdown -= run;\n this.fill(run, buffers, offset + done);\n done += run;\n }\n }\n }\n\n /** `count` samples with every channel's parameters fixed — tight loops on locals. */\n private fill(count: number, buffers: ChannelBuffers, at: number) {\n const end = at + count;\n const { pulse1, pulse2, triangle, noise } = buffers;\n\n for (let i = 0; i < 2; i++) {\n const p = this.pulses[i];\n const out = i === 0 ? pulse1 : pulse2;\n // A pulse steps through 8 entries per cycle and each entry takes\n // 2 × (period + 1) CPU cycles: CPU / (16 × (period + 1)) per cycle.\n const step = p.step;\n let phase = p.phase;\n if (p.length === 0 || p.muted) {\n for (let k = at; k < end; k++) {\n phase += step;\n if (phase >= 8) phase %= 8;\n out[k] = 0;\n }\n } else {\n const level = p.constant ? p.volume : p.env.decay;\n const base = p.duty * 8;\n for (let k = at; k < end; k++) {\n phase += step;\n if (phase >= 8) phase %= 8;\n out[k] = DUTY_FLAT[base + ((phase | 0) & 7)] * level;\n }\n }\n p.phase = phase;\n }\n\n const t = this.triangle;\n // The staircase only moves while both counters are non-zero. When either\n // runs out the sequencer STOPS where it is and the output holds that step:\n // the triangle is never \"at zero\" between notes, it is wherever it paused.\n if (t.length > 0 && t.linear > 0) {\n const step = t.step;\n let phase = t.phase;\n for (let k = at; k < end; k++) {\n phase += step;\n if (phase >= 32) phase %= 32;\n triangle[k] = TRIANGLE_FLAT[(phase | 0) & 31];\n }\n t.phase = phase;\n } else {\n triangle.fill(TRIANGLE_FLAT[(t.phase | 0) & 31], at, end);\n }\n\n // AVERAGE the register's output across the shifts each sample is worth,\n // rather than sampling wherever it lands. At the short periods the LFSR\n // runs well past the sample rate, and keeping only the last shift folds the\n // rest back as alias tones — drums like a broken speaker. The channel is\n // silenced while bit 0 is set: the register gates it.\n const n = this.noise;\n const level = n.length === 0 ? 0 : n.constant ? n.volume : n.env.decay;\n const step = n.step;\n let phase = n.phase;\n if (!n.shortMode) {\n let index = n.lfsrIndex;\n if (level === 0) {\n // Silent, but the register keeps shifting: advance it, output nothing.\n for (let k = at; k < end; k++) {\n phase += step;\n // A few shifts per sample at most, so one conditional subtraction\n // wraps the index — no division. (Math.floor, not `| 0`: the phase is\n // a double, and a round trip through int32 measured 20% slower.)\n const shifts = Math.floor(phase);\n phase -= shifts;\n index += shifts;\n if (index >= LONG_CYCLE) index -= LONG_CYCLE;\n }\n noise.fill(0, at, end);\n } else {\n for (let k = at; k < end; k++) {\n phase += step;\n const shifts = Math.floor(phase);\n phase -= shifts;\n let gate: number;\n if (shifts > 0) {\n gate = (LONG_HIGH_BEFORE[index + shifts] - LONG_HIGH_BEFORE[index]) / shifts;\n index += shifts;\n if (index >= LONG_CYCLE) index -= LONG_CYCLE;\n } else {\n gate = (LONG_STATES[index] & 1) === 0 ? 1 : 0;\n }\n noise[k] = gate * level;\n }\n }\n n.lfsrIndex = index;\n } else {\n let lfsr = n.lfsr;\n for (let k = at; k < end; k++) {\n phase += step;\n const shifts = Math.floor(phase);\n phase -= shifts;\n let high = 0;\n for (let s = 0; s < shifts; s++) {\n if ((lfsr & 1) === 0) high++;\n const feedback = (lfsr & 1) ^ ((lfsr >> 6) & 1);\n lfsr = (lfsr >> 1) | (feedback << 14);\n }\n const gate = shifts > 0 ? high / shifts : (lfsr & 1) === 0 ? 1 : 0;\n noise[k] = level === 0 ? 0 : gate * level;\n }\n n.lfsr = lfsr;\n }\n n.phase = phase;\n\n this.fillDmc(buffers.dmc, at, end);\n }\n\n /**\n * The DMC over `[at, end)`. At most a bit or two per sample even at its\n * fastest rate, so it is clocked bit by bit; a channel with nothing to play\n * only has its output-cycle count moved on, which is all that changes.\n */\n private fillDmc(out: Uint8Array, at: number, end: number) {\n const d = this.dmc;\n if (d.silence && d.remaining === 0 && d.buffer < 0) {\n // Nothing to play: the output holds, and only the timer and the bit count\n // move on. Worked out for the whole run at once — nothing audible depends\n // on the timer's exact fraction until a sample starts, and starting one\n // takes a register write, which ends the run.\n const total = d.phase + d.step * (end - at);\n const clocks = Math.floor(total);\n d.phase = total - clocks;\n // Each clock uses up a bit; an emptied cycle starts another, silent,\n // since there is nothing to load.\n d.bits -= clocks % 8;\n if (d.bits <= 0) d.bits += 8;\n out.fill(d.level, at, end);\n return;\n }\n for (let k = at; k < end; k++) {\n d.phase += d.step;\n while (d.phase >= 1) {\n d.phase -= 1;\n this.clockDmc();\n }\n out[k] = d.level;\n }\n }\n\n /** One DMC timer clock: step the output by the next bit, and start a new byte after eight. */\n private clockDmc() {\n const d = this.dmc;\n if (!d.silence) {\n if (d.shift & 1) {\n if (d.level <= 125) d.level += 2;\n } else if (d.level >= 2) {\n d.level -= 2;\n }\n }\n d.shift >>= 1;\n d.bits -= 1;\n if (d.bits === 0) {\n d.bits = 8;\n if (d.buffer < 0) {\n d.silence = true;\n } else {\n d.silence = false;\n d.shift = d.buffer;\n d.buffer = -1;\n this.fetchDmc();\n }\n }\n }\n\n /** The memory reader: refill the empty buffer from the cartridge, looping or stopping at the end. */\n private fetchDmc() {\n const d = this.dmc;\n if (d.buffer >= 0 || d.remaining === 0) return;\n d.buffer = this.read(d.address);\n d.address = d.address === 0xffff ? 0x8000 : d.address + 1;\n d.remaining -= 1;\n if (d.remaining === 0 && d.loop) {\n d.address = d.startAddress;\n d.remaining = d.startLength;\n }\n }\n\n private retuneDmc() {\n this.dmc.step = CPU_HZ / DMC_PERIODS[this.dmc.rateIndex] / this.sampleRate;\n }\n\n /** A copy of the channels' internal counters and levels — see `ApuSnapshot`. */\n snapshot(): ApuSnapshot {\n const t = this.triangle;\n const n = this.noise;\n return {\n pulse: this.pulses.map((p) => ({\n period: p.period,\n duty: p.duty,\n length: p.length,\n level: p.constant ? p.volume : p.env.decay,\n constant: p.constant,\n muted: p.muted,\n enabled: p.enabled,\n })),\n triangle: {\n period: t.period,\n length: t.length,\n linear: t.linear,\n step: TRIANGLE_FLAT[(t.phase | 0) & 31],\n enabled: t.enabled,\n },\n noise: {\n periodIndex: n.periodIndex,\n shortMode: n.shortMode,\n length: n.length,\n level: n.constant ? n.volume : n.env.decay,\n constant: n.constant,\n enabled: n.enabled,\n },\n ...(this.fds ? { fds: this.fds.snapshot() } : {}),\n ...(this.n163 ? { n163: this.n163.snapshot() } : {}),\n dmc: {\n level: this.dmc.level,\n rateIndex: this.dmc.rateIndex,\n loop: this.dmc.loop,\n remaining: this.dmc.remaining,\n address: this.dmc.address,\n enabled: this.dmc.remaining > 0,\n },\n };\n }\n\n private retunePulse(p: Pulse) {\n p.step = CPU_HZ / (2 * (p.period + 1)) / this.sampleRate;\n p.muted = sweepMutes(p.period, p.sweep);\n }\n\n private retuneTriangle() {\n this.triangle.step = CPU_HZ / (this.triangle.period + 1) / this.sampleRate;\n }\n\n private retuneNoise() {\n this.noise.step = CPU_HZ / NOISE_PERIODS[this.noise.periodIndex] / this.sampleRate;\n }\n\n private clockFrameCounter() {\n // 4-step: quarter frames on every step, half frames on steps 2 and 4.\n // 5-step: quarter frames on 1, 2, 3 and 5, half frames on 2 and 5.\n const step = this.frameStep;\n if (this.fiveStep) {\n this.frameStep = (step + 1) % 5;\n if (step !== 3) this.clockQuarterFrame();\n if (step === 1 || step === 4) this.clockHalfFrame();\n } else {\n this.frameStep = (step + 1) % 4;\n this.clockQuarterFrame();\n if (step === 1 || step === 3) this.clockHalfFrame();\n }\n }\n\n private clockQuarterFrame() {\n for (const p of this.pulses) clockEnvelope(p.env, p.volume, p.halt);\n clockEnvelope(this.noise.env, this.noise.volume, this.noise.halt);\n\n const t = this.triangle;\n if (t.linearReloadFlag) t.linear = t.linearReload;\n else if (t.linear > 0) t.linear -= 1;\n if (!t.control) t.linearReloadFlag = false;\n }\n\n private clockHalfFrame() {\n if (this.lengthCounter) {\n for (const p of this.pulses) if (!p.halt && p.length > 0) p.length -= 1;\n if (!this.triangle.control && this.triangle.length > 0) this.triangle.length -= 1;\n if (!this.noise.halt && this.noise.length > 0) this.noise.length -= 1;\n }\n\n for (const p of this.pulses) {\n // The hardware's order: adjust first, then reload or count down.\n if (p.sweepDivider === 0 && p.sweep.enabled && p.sweep.shift > 0 && !p.muted) {\n p.period = Math.max(0, sweepTarget(p.period, p.sweep));\n this.retunePulse(p);\n }\n if (p.sweepDivider === 0 || p.sweepReload) {\n p.sweepDivider = p.sweep.dividerPeriod;\n p.sweepReload = false;\n } else {\n p.sweepDivider -= 1;\n }\n }\n }\n}\n"]}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two expansion sound chips the Famicom's own games carried most: the Disk
|
|
3
|
+
* System's wavetable voice (FDS) and Namco's 163 (N163). Each is a channel the
|
|
4
|
+
* 2A03 does not have — a waveform drawn in RAM, played back at a pitch — and
|
|
5
|
+
* games that use them put their melody there, so without them a soundtrack is
|
|
6
|
+
* its bass and drums.
|
|
7
|
+
*
|
|
8
|
+
* Like the APU here they run at the sample rate, not per CPU cycle: each sample
|
|
9
|
+
* advances the chip by `CPU_HZ / sampleRate` cycles' worth of its counters.
|
|
10
|
+
*
|
|
11
|
+
* Output is in the units `mixApu` returns (0..~1 for the whole 2A03), so a
|
|
12
|
+
* renderer adds it to the mix. The levels relative to the 2A03 follow the
|
|
13
|
+
* common reference players: FDS at full gain about as loud as both pulses at
|
|
14
|
+
* full, an N163 channel at full volume about as loud as one pulse — divided by
|
|
15
|
+
* the number of channels it time-shares its one output with, as the chip does.
|
|
16
|
+
*/
|
|
17
|
+
export interface FdsSnapshot {
|
|
18
|
+
/** 12-bit wave frequency; Hz = CPU_HZ * frequency / 4194304. */
|
|
19
|
+
frequency: number;
|
|
20
|
+
/** Volume gain as the chip uses it, 0..32. */
|
|
21
|
+
gain: number;
|
|
22
|
+
/** `$4089` bits 0–1. */
|
|
23
|
+
master: number;
|
|
24
|
+
/** The 64 wave samples, 0..63. */
|
|
25
|
+
wave: number[];
|
|
26
|
+
/** Wave unit halted (`$4083` bit 7) or the wave being written (`$4089` bit 7). */
|
|
27
|
+
halted: boolean;
|
|
28
|
+
/** Modulation depth (mod gain, 0..63) and frequency: a vibrato when both are above 0. */
|
|
29
|
+
modGain: number;
|
|
30
|
+
modFrequency: number;
|
|
31
|
+
}
|
|
32
|
+
export declare class FdsChip {
|
|
33
|
+
private readonly cyclesPerSample;
|
|
34
|
+
readonly wave: Uint8Array<ArrayBuffer>;
|
|
35
|
+
private readonly modTable;
|
|
36
|
+
private modWritePos;
|
|
37
|
+
private frequency;
|
|
38
|
+
private haltWave;
|
|
39
|
+
private envelopesOff;
|
|
40
|
+
private waveWrite;
|
|
41
|
+
private master;
|
|
42
|
+
private envSpeed;
|
|
43
|
+
private volDirect;
|
|
44
|
+
private volIncrease;
|
|
45
|
+
private volSpeed;
|
|
46
|
+
private volGain;
|
|
47
|
+
private volCounter;
|
|
48
|
+
private modDirect;
|
|
49
|
+
private modIncrease;
|
|
50
|
+
private modSpeed;
|
|
51
|
+
private modGain;
|
|
52
|
+
private modCounterEnv;
|
|
53
|
+
private modFrequency;
|
|
54
|
+
private modHalt;
|
|
55
|
+
private modCounter;
|
|
56
|
+
private modPos;
|
|
57
|
+
private modAcc;
|
|
58
|
+
private waveAcc;
|
|
59
|
+
private wavePos;
|
|
60
|
+
/** Gain latched at the start of each wave cycle, as the chip does: a level change waits for the cycle. */
|
|
61
|
+
private latchedGain;
|
|
62
|
+
constructor(sampleRate: number);
|
|
63
|
+
/** A write to `$4040`–`$408A`. Returns false for any other address. */
|
|
64
|
+
write(address: number, value: number): boolean;
|
|
65
|
+
/** The pitch the wave unit runs at this moment, after modulation (the chip's own arithmetic). */
|
|
66
|
+
private modulatedFrequency;
|
|
67
|
+
/**
|
|
68
|
+
* Advance `count` samples, ADDING the output to `out` from `offset` (in `mixApu` units, centred
|
|
69
|
+
* by the renderer's filters like the rest).
|
|
70
|
+
*/
|
|
71
|
+
render(count: number, out: Float64Array, offset?: number): void;
|
|
72
|
+
snapshot(): FdsSnapshot;
|
|
73
|
+
}
|
|
74
|
+
export interface N163ChannelSnapshot {
|
|
75
|
+
/** 0..7 — the register slot, `$40 + 8·slot` in the chip's RAM; slot 7 ($78) is always on. */
|
|
76
|
+
slot: number;
|
|
77
|
+
/** 18-bit frequency; Hz = CPU_HZ * frequency / (15 · 65536 · channels · length). */
|
|
78
|
+
frequency: number;
|
|
79
|
+
/** Wave length in 4-bit samples. */
|
|
80
|
+
length: number;
|
|
81
|
+
/** Where the wave starts, in 4-bit samples. */
|
|
82
|
+
waveAddress: number;
|
|
83
|
+
volume: number;
|
|
84
|
+
/** The wave as it stands in RAM, `length` samples 0..15. */
|
|
85
|
+
wave: number[];
|
|
86
|
+
}
|
|
87
|
+
export interface N163Snapshot {
|
|
88
|
+
/** How many channels are on, 1..8 — the top ones, from slot 7 down. */
|
|
89
|
+
channels: number;
|
|
90
|
+
active: N163ChannelSnapshot[];
|
|
91
|
+
}
|
|
92
|
+
export declare class N163Chip {
|
|
93
|
+
private readonly cyclesPerSample;
|
|
94
|
+
readonly ram: Uint8Array<ArrayBuffer>;
|
|
95
|
+
private address;
|
|
96
|
+
private autoIncrement;
|
|
97
|
+
private disabled;
|
|
98
|
+
private readonly phase;
|
|
99
|
+
constructor(sampleRate: number);
|
|
100
|
+
/** A write to the address port (`$F800`), data port (`$4800`) or `$E000`. Returns false for others. */
|
|
101
|
+
write(address: number, value: number): boolean;
|
|
102
|
+
/** A read of the data port, as the CPU makes it — auto-increment included. */
|
|
103
|
+
read(): number;
|
|
104
|
+
get channels(): number;
|
|
105
|
+
/**
|
|
106
|
+
* A channel's eight bytes: frequency low, middle, and high two bits with the wave length above
|
|
107
|
+
* them; three bytes of phase; the wave's address; the volume. (Read off what Namco's own drivers
|
|
108
|
+
* write — Erika to Satoru and Mappy Kids both put `$E0`/`$F0`, a 32- or 16-sample wave, in the
|
|
109
|
+
* third byte.)
|
|
110
|
+
*/
|
|
111
|
+
private channel;
|
|
112
|
+
private sample;
|
|
113
|
+
/**
|
|
114
|
+
* Advance `count` samples, ADDING each active channel's output to `outs[slot]` (or, when a
|
|
115
|
+
* channel has no buffer of its own, to `outs[8]` if given) from `offset`.
|
|
116
|
+
*/
|
|
117
|
+
render(count: number, outs: readonly (Float64Array | undefined)[], offset?: number): void;
|
|
118
|
+
snapshot(): N163Snapshot;
|
|
119
|
+
}
|
|
120
|
+
/** Hz of an FDS frequency register value. */
|
|
121
|
+
export declare const fdsHz: (frequency: number) => number;
|
|
122
|
+
/** Hz of an N163 channel, from its frequency, wave length and the number of channels on. */
|
|
123
|
+
export declare const n163Hz: (frequency: number, length: number, channels: number) => number;
|