@xromdev/apu 0.1.0 → 0.1.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/dist/chip.js +9 -3
- package/dist/chip.js.map +1 -1
- package/dist/mixer.d.ts +6 -0
- package/dist/mixer.js +6 -0
- package/dist/mixer.js.map +1 -1
- package/dist/render.js +2 -2
- package/dist/render.js.map +1 -1
- package/package.json +1 -1
package/dist/chip.js
CHANGED
|
@@ -400,10 +400,14 @@ export class Apu {
|
|
|
400
400
|
// Silent, but the register keeps shifting: advance it, output nothing.
|
|
401
401
|
for (let k = at; k < end; k++) {
|
|
402
402
|
phase += step;
|
|
403
|
+
// A few shifts per sample at most, so one conditional subtraction
|
|
404
|
+
// wraps the index — no division. (Math.floor, not `| 0`: the phase is
|
|
405
|
+
// a double, and a round trip through int32 measured 20% slower.)
|
|
403
406
|
const shifts = Math.floor(phase);
|
|
404
407
|
phase -= shifts;
|
|
405
|
-
|
|
406
|
-
|
|
408
|
+
index += shifts;
|
|
409
|
+
if (index >= LONG_CYCLE)
|
|
410
|
+
index -= LONG_CYCLE;
|
|
407
411
|
}
|
|
408
412
|
noise.fill(0, at, end);
|
|
409
413
|
}
|
|
@@ -415,7 +419,9 @@ export class Apu {
|
|
|
415
419
|
let gate;
|
|
416
420
|
if (shifts > 0) {
|
|
417
421
|
gate = (LONG_HIGH_BEFORE[index + shifts] - LONG_HIGH_BEFORE[index]) / shifts;
|
|
418
|
-
index
|
|
422
|
+
index += shifts;
|
|
423
|
+
if (index >= LONG_CYCLE)
|
|
424
|
+
index -= LONG_CYCLE;
|
|
419
425
|
}
|
|
420
426
|
else {
|
|
421
427
|
gate = (LONG_STATES[index] & 1) === 0 ? 1 : 0;
|
package/dist/chip.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chip.js","sourceRoot":"","sources":["../src/chip.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;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E,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC;YACxE,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC;gBAAE,IAAI,CAAC,QAAQ,CAAC,MAAM,IAAI,CAAC,CAAC;YAClF,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC;gBAAE,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';\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 const shifts = Math.floor(phase);\n phase -= shifts;\n if (shifts > 0) index = (index + shifts) % 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 = (index + shifts) % 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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AC,QAAQ,CAAC,MAAM,GAAG,CAAC;gBAAE,IAAI,CAAC,QAAQ,CAAC,MAAM,IAAI,CAAC,CAAC;YAClF,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC;gBAAE,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';\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"]}
|
package/dist/mixer.d.ts
CHANGED
|
@@ -50,3 +50,9 @@ export declare class OutputFilters {
|
|
|
50
50
|
constructor(rate: number, consoleBass: boolean);
|
|
51
51
|
step(input: number): number;
|
|
52
52
|
}
|
|
53
|
+
/**
|
|
54
|
+
* `PULSE_MIX[pulses] + TRIANGLE_MIX[triangle]`, added up in advance: one
|
|
55
|
+
* lookup at `(pulses << 4) | triangle` for the renderer's commonest case —
|
|
56
|
+
* the same addition, so the same floats.
|
|
57
|
+
*/
|
|
58
|
+
export declare const PULSE_TRIANGLE_MIX: Float64Array<ArrayBuffer>;
|
package/dist/mixer.js
CHANGED
|
@@ -82,4 +82,10 @@ export class OutputFilters {
|
|
|
82
82
|
return this.lowPrev;
|
|
83
83
|
}
|
|
84
84
|
}
|
|
85
|
+
/**
|
|
86
|
+
* `PULSE_MIX[pulses] + TRIANGLE_MIX[triangle]`, added up in advance: one
|
|
87
|
+
* lookup at `(pulses << 4) | triangle` for the renderer's commonest case —
|
|
88
|
+
* the same addition, so the same floats.
|
|
89
|
+
*/
|
|
90
|
+
export const PULSE_TRIANGLE_MIX = Float64Array.from({ length: 31 * 16 }, (_, i) => PULSE_MIX[i >> 4] + TRIANGLE_MIX[i & 15]);
|
|
85
91
|
//# sourceMappingURL=mixer.js.map
|
package/dist/mixer.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mixer.js","sourceRoot":"","sources":["../src/mixer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,MAAM,CACpB,MAAc,EACd,MAAc,EACd,QAAgB,EAChB,KAAa,EACb,GAAG,GAAG,CAAC;IAEP,MAAM,QAAQ,GAAG,MAAM,GAAG,MAAM,CAAC;IACjC,MAAM,QAAQ,GAAG,QAAQ,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,IAAI,GAAG,QAAQ,GAAG,GAAG,CAAC,CAAC;IACtE,MAAM,GAAG,GAAG,QAAQ,GAAG,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG,GAAG,GAAG,KAAK,CAAC;IAC1D,MAAM,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;IACxD,OAAO,QAAQ,GAAG,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AAM,OAAO,GAAG,CAAC,EAAU,EAAE,EAAE;YAC7B,MAAM,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC;YAClC,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC;QACpC,CAAC,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;QAC3B,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;IAC5B,CAAC;IAED,IAAI,CAAC,KAAa;QAChB,MAAM,CAAC,GAAG,IAAI,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;QACxD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC;QAEf,IAAI,CAAC,GAAG,CAAC,CAAC;QACV,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;YACrB,CAAC,GAAG,IAAI,CAAC,KAAK,GAAG,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;YACjD,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;YAChB,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;QAClB,CAAC;QAED,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC;QAC9C,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;CACF","sourcesContent":["/**\n * The APU's mixer, from the hardware's own measured curves.\n *\n * Non-linear on purpose: two pulses at full volume are not twice one pulse, and\n * the triangle/noise group is louder per unit than the pulses. It also means\n * the channels are not independent — a triangle held high takes level from the\n * noise beside it. Getting this wrong is what makes a naive NES synth sound thin\n * and shrill.\n *\n * Inputs are each channel's output level — 0..15, and 0..127 for the DMC; the\n * result is 0..~1 and never negative. With the DMC at 0 its term adds exactly\n * nothing, so a mix without it is bit for bit the four-channel one. Centring it on zero is the output filters' job.\n */\nexport function mixApu(\n pulse1: number,\n pulse2: number,\n triangle: number,\n noise: number,\n dmc = 0\n): number {\n const pulseSum = pulse1 + pulse2;\n const pulseOut = pulseSum === 0 ? 0 : 95.88 / (8128 / pulseSum + 100);\n const tnd = triangle / 8227 + noise / 12241 + dmc / 22638;\n const tndOut = tnd === 0 ? 0 : 159.79 / (1 / tnd + 100);\n return pulseOut + tndOut;\n}\n\n/**\n * `mixApu`'s two halves for whole-number inputs, precomputed with the same\n * expressions — so a lookup gives exactly the float the formula would.\n *\n * The pulses are always whole numbers (0..30 summed) unless a fader scales them;\n * the triangle is a whole step, and the noise is only fractional while it\n * sounds (its gate is averaged over the shifts in a sample). The renderer uses\n * these for the common cases and the formula for the rest.\n */\nexport const PULSE_MIX = Float64Array.from({ length: 31 }, (_, sum) =>\n sum === 0 ? 0 : 95.88 / (8128 / sum + 100)\n);\n\n/** Triangle alone, noise silent: `triangle / 8227 + 0 / 12241` through the curve. */\nexport const TRIANGLE_MIX = Float64Array.from({ length: 16 }, (_, level) => {\n const tnd = level / 8227 + 0 / 12241;\n return tnd === 0 ? 0 : 159.79 / (1 / tnd + 100);\n});\n\n/**\n * The analogue stage after the mixer, as the console has it.\n *\n * Two RC high-passes (90 Hz and 440 Hz) and a low-pass at 14 kHz, one pole each.\n * The 90 Hz one is what centres the signal on zero — without it every note\n * starts and ends on a step in the DC level, and each drum hit arrives as a\n * click the size of the sound itself.\n *\n * **The 440 Hz high-pass is off unless asked for.** It is real, but it costs\n * 18 dB at 82 Hz, which is where a triangle bass line lives: on a 1980s\n * television that loss was part of the sound, in headphones it just sounds\n * thin. `consoleBass` puts it back.\n */\nexport class OutputFilters {\n // Previous input and output of each stage, as plain numbers: this runs once\n // per sample, and a fresh object per sample is garbage by the megabyte.\n private hp90X = 0;\n private hp90Y = 0;\n private hp440X = 0;\n private hp440Y = 0;\n private lowPrev = 0;\n private readonly hp90: number;\n private readonly hp440: number;\n private readonly low: number;\n private readonly consoleBass: boolean;\n\n constructor(rate: number, consoleBass: boolean) {\n this.consoleBass = consoleBass;\n const highPass = (hz: number) => {\n const rc = 1 / (2 * Math.PI * hz);\n return rc / (rc + 1 / rate);\n };\n const lowPass = (hz: number) => {\n const rc = 1 / (2 * Math.PI * hz);\n return 1 / rate / (rc + 1 / rate);\n };\n this.hp90 = highPass(90);\n this.hp440 = highPass(440);\n this.low = lowPass(14000);\n }\n\n step(input: number): number {\n const a = this.hp90 * (this.hp90Y + input - this.hp90X);\n this.hp90X = input;\n this.hp90Y = a;\n\n let b = a;\n if (this.consoleBass) {\n b = this.hp440 * (this.hp440Y + a - this.hp440X);\n this.hp440X = a;\n this.hp440Y = b;\n }\n\n this.lowPrev += this.low * (b - this.lowPrev);\n return this.lowPrev;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"mixer.js","sourceRoot":"","sources":["../src/mixer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,MAAM,CACpB,MAAc,EACd,MAAc,EACd,QAAgB,EAChB,KAAa,EACb,GAAG,GAAG,CAAC;IAEP,MAAM,QAAQ,GAAG,MAAM,GAAG,MAAM,CAAC;IACjC,MAAM,QAAQ,GAAG,QAAQ,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,IAAI,GAAG,QAAQ,GAAG,GAAG,CAAC,CAAC;IACtE,MAAM,GAAG,GAAG,QAAQ,GAAG,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG,GAAG,GAAG,KAAK,CAAC;IAC1D,MAAM,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,C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M,kBAAkB,GAAG,YAAY,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,YAAY,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC","sourcesContent":["/**\n * The APU's mixer, from the hardware's own measured curves.\n *\n * Non-linear on purpose: two pulses at full volume are not twice one pulse, and\n * the triangle/noise group is louder per unit than the pulses. It also means\n * the channels are not independent — a triangle held high takes level from the\n * noise beside it. Getting this wrong is what makes a naive NES synth sound thin\n * and shrill.\n *\n * Inputs are each channel's output level — 0..15, and 0..127 for the DMC; the\n * result is 0..~1 and never negative. With the DMC at 0 its term adds exactly\n * nothing, so a mix without it is bit for bit the four-channel one. Centring it on zero is the output filters' job.\n */\nexport function mixApu(\n pulse1: number,\n pulse2: number,\n triangle: number,\n noise: number,\n dmc = 0\n): number {\n const pulseSum = pulse1 + pulse2;\n const pulseOut = pulseSum === 0 ? 0 : 95.88 / (8128 / pulseSum + 100);\n const tnd = triangle / 8227 + noise / 12241 + dmc / 22638;\n const tndOut = tnd === 0 ? 0 : 159.79 / (1 / tnd + 100);\n return pulseOut + tndOut;\n}\n\n/**\n * `mixApu`'s two halves for whole-number inputs, precomputed with the same\n * expressions — so a lookup gives exactly the float the formula would.\n *\n * The pulses are always whole numbers (0..30 summed) unless a fader scales them;\n * the triangle is a whole step, and the noise is only fractional while it\n * sounds (its gate is averaged over the shifts in a sample). The renderer uses\n * these for the common cases and the formula for the rest.\n */\nexport const PULSE_MIX = Float64Array.from({ length: 31 }, (_, sum) =>\n sum === 0 ? 0 : 95.88 / (8128 / sum + 100)\n);\n\n/** Triangle alone, noise silent: `triangle / 8227 + 0 / 12241` through the curve. */\nexport const TRIANGLE_MIX = Float64Array.from({ length: 16 }, (_, level) => {\n const tnd = level / 8227 + 0 / 12241;\n return tnd === 0 ? 0 : 159.79 / (1 / tnd + 100);\n});\n\n/**\n * The analogue stage after the mixer, as the console has it.\n *\n * Two RC high-passes (90 Hz and 440 Hz) and a low-pass at 14 kHz, one pole each.\n * The 90 Hz one is what centres the signal on zero — without it every note\n * starts and ends on a step in the DC level, and each drum hit arrives as a\n * click the size of the sound itself.\n *\n * **The 440 Hz high-pass is off unless asked for.** It is real, but it costs\n * 18 dB at 82 Hz, which is where a triangle bass line lives: on a 1980s\n * television that loss was part of the sound, in headphones it just sounds\n * thin. `consoleBass` puts it back.\n */\nexport class OutputFilters {\n // Previous input and output of each stage, as plain numbers: this runs once\n // per sample, and a fresh object per sample is garbage by the megabyte.\n private hp90X = 0;\n private hp90Y = 0;\n private hp440X = 0;\n private hp440Y = 0;\n private lowPrev = 0;\n private readonly hp90: number;\n private readonly hp440: number;\n private readonly low: number;\n private readonly consoleBass: boolean;\n\n constructor(rate: number, consoleBass: boolean) {\n this.consoleBass = consoleBass;\n const highPass = (hz: number) => {\n const rc = 1 / (2 * Math.PI * hz);\n return rc / (rc + 1 / rate);\n };\n const lowPass = (hz: number) => {\n const rc = 1 / (2 * Math.PI * hz);\n return 1 / rate / (rc + 1 / rate);\n };\n this.hp90 = highPass(90);\n this.hp440 = highPass(440);\n this.low = lowPass(14000);\n }\n\n step(input: number): number {\n const a = this.hp90 * (this.hp90Y + input - this.hp90X);\n this.hp90X = input;\n this.hp90Y = a;\n\n let b = a;\n if (this.consoleBass) {\n b = this.hp440 * (this.hp440Y + a - this.hp440X);\n this.hp440X = a;\n this.hp440Y = b;\n }\n\n this.lowPrev += this.low * (b - this.lowPrev);\n return this.lowPrev;\n }\n}\n\n/**\n * `PULSE_MIX[pulses] + TRIANGLE_MIX[triangle]`, added up in advance: one\n * lookup at `(pulses << 4) | triangle` for the renderer's commonest case —\n * the same addition, so the same floats.\n */\nexport const PULSE_TRIANGLE_MIX = Float64Array.from({ length: 31 * 16 }, (_, i) => PULSE_MIX[i >> 4] + TRIANGLE_MIX[i & 15]);\n"]}
|
package/dist/render.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* anything drawn over it — the playing position is one number both read.
|
|
7
7
|
*/
|
|
8
8
|
import { Apu } from './chip.js';
|
|
9
|
-
import { mixApu, OutputFilters, PULSE_MIX,
|
|
9
|
+
import { mixApu, OutputFilters, PULSE_MIX, PULSE_TRIANGLE_MIX } from './mixer.js';
|
|
10
10
|
/**
|
|
11
11
|
* Play `writes` through the chip for `duration` seconds.
|
|
12
12
|
*
|
|
@@ -71,7 +71,7 @@ export function renderWrites(writes, duration, options = {}) {
|
|
|
71
71
|
}
|
|
72
72
|
else if (noise[k] === 0 && dmc[k] === 0) {
|
|
73
73
|
// The common case, from tables built with the mixer's own expressions.
|
|
74
|
-
mixed =
|
|
74
|
+
mixed = PULSE_TRIANGLE_MIX[((p1[k] + p2[k]) << 4) | tri[k]];
|
|
75
75
|
}
|
|
76
76
|
else {
|
|
77
77
|
const tnd = tri[k] / 8227 + noise[k] / 12241 + dmc[k] / 22638;
|
package/dist/render.js.map
CHANGED
|
@@ -1 +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,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AA2D5E;;;;;;GAMG;AACH,MAAM,UAAU,YAAY,CAC1B,MAAgC,EAChC,QAAgB,EAChB,UAAyB,EAAE;IAE3B,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,IAAI,KAAK,CAAC;IAC/C,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,IAAI,CAAC,CAAC,CAAC,CAAC;IACpE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,GAAG,CAAC;IACj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AG,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"]}
|
|
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,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AA2DlF;;;;;;GAMG;AACH,MAAM,UAAU,YAAY,CAC1B,MAAgC,EAChC,QAAgB,EAChB,UAAyB,EAAE;IAE3B,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,IAAI,KAAK,CAAC;IAC/C,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,IAAI,CAAC,CAAC,CAAC,CAAC;IACpE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,GAAG,CAAC;IACjC,MAAM,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IACnC,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,KAAK,KAAK,CAAC;IAC3C,MAAM,IAAI,GAAG,UAAU,GAAG,UAAU,CAAC;IACrC,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,G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AC,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, PULSE_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_TRIANGLE_MIX[((p1[k] + p2[k]) << 4) | 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"]}
|