@xromdev/apu 0.4.2 → 0.5.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/expansion.js CHANGED
@@ -1,9 +1,9 @@
1
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.
2
+ * The expansion sound chips the Famicom's own games carried most: the Disk
3
+ * System's wavetable voice (FDS), Namco's 163 (N163) and Konami's VRC6. Each
4
+ * adds channels the 2A03 does not have — a waveform drawn in RAM played back at
5
+ * a pitch, or two more pulses and a sawtooth — and games that use them put
6
+ * their melody there, so without them a soundtrack is its bass and drums.
7
7
  *
8
8
  * Like the APU here they run at the sample rate, not per CPU cycle: each sample
9
9
  * advances the chip by `CPU_HZ / sampleRate` cycles' worth of its counters.
@@ -12,7 +12,9 @@
12
12
  * renderer adds it to the mix. The levels relative to the 2A03 follow the
13
13
  * common reference players: FDS at full gain about as loud as both pulses at
14
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.
15
+ * the number of channels it time-shares its one output with, as the chip does —
16
+ * and a VRC6 pulse at full volume one and a half times a 2A03 pulse, as Mesen2
17
+ * mixes it (`VRC6_STEP`).
16
18
  */
17
19
  import { CPU_HZ } from './constants.js';
18
20
  /** Full-scale output of the FDS (wave 63 × gain 32 at master volume 1), in `mixApu` units. */
@@ -23,6 +25,13 @@ const N163_FULL = 0.16;
23
25
  const FDS_MASTER = [1, 2 / 3, 1 / 2, 2 / 5];
24
26
  /** Mod table entries → how far each moves the mod counter; 4 resets it. */
25
27
  const MOD_STEP = [0, 1, 2, 4, 0, -4, -2, -1];
28
+ /**
29
+ * One step of the VRC6's output (pulse 0..15 + pulse 0..15 + saw 0..31), in `mixApu` units. From
30
+ * Mesen2, which adds the chip's summed output × 15 (Core/NES/Mappers/Audio/Vrc6Audio.h) × 5
31
+ * (Core/NES/NesSoundMixer.cpp, GetOutputVolume) to a 2A03 mix whose `mixApu` 1.0 is 5000 there:
32
+ * 75 / 5000. A VRC6 pulse at volume 15 is so 0.225, about one and a half 2A03 pulses at 15.
33
+ */
34
+ const VRC6_STEP = 75 / 5000;
26
35
  export class FdsChip {
27
36
  constructor(sampleRate) {
28
37
  this.wave = new Uint8Array(64);
@@ -334,8 +343,191 @@ export class N163Chip {
334
343
  return { channels: this.disabled ? 0 : n, active: this.disabled ? [] : active };
335
344
  }
336
345
  }
346
+ /**
347
+ * Konami's VRC6: two pulses with eight duties and a sawtooth, beside the 2A03 (Akumajou Densetsu,
348
+ * Madara, Esper Dream 2). The registers are at the addresses the NSF format gives them —
349
+ * `$9000`–`$9003`, `$A000`–`$A002`, `$B000`–`$B002`; the cartridges themselves differ in which of
350
+ * A0/A1 they wire to the chip, which a player maps before here.
351
+ *
352
+ * Each channel counts down `(period >> shift) + 1` CPU cycles a step, as Mesen2's Vrc6Pulse/Vrc6Saw
353
+ * do. Output is the average over each sample of what the chip puts out, so a high note at a low
354
+ * sample rate keeps its level.
355
+ */
356
+ export class Vrc6Chip {
357
+ static newPulse() {
358
+ return { volume: 0, duty: 0, constant: false, period: 0, enabled: false, timer: 1, step: 0 };
359
+ }
360
+ constructor(sampleRate) {
361
+ this.pulses = [Vrc6Chip.newPulse(), Vrc6Chip.newPulse()];
362
+ this.sawRate = 0;
363
+ this.sawPeriod = 0;
364
+ this.sawEnabled = false;
365
+ this.sawTimer = 1;
366
+ this.sawStep = 0;
367
+ this.sawAccumulator = 0;
368
+ this.halted = false;
369
+ this.shift = 0;
370
+ this.cyclesPerSample = CPU_HZ / sampleRate;
371
+ }
372
+ /** A write to `$9000`–`$9003`, `$A000`–`$A002` or `$B000`–`$B002`. Returns false for any other address. */
373
+ write(address, value) {
374
+ const v = value & 0xff;
375
+ if (address === 0x9003) {
376
+ this.halted = (v & 1) !== 0;
377
+ this.shift = v & 4 ? 8 : v & 2 ? 4 : 0;
378
+ return true;
379
+ }
380
+ if ((address >= 0x9000 && address <= 0x9002) || (address >= 0xa000 && address <= 0xa002)) {
381
+ const p = this.pulses[address >> 12 === 0x9 ? 0 : 1];
382
+ switch (address & 3) {
383
+ case 0:
384
+ p.volume = v & 0x0f;
385
+ p.duty = (v >> 4) & 7;
386
+ p.constant = (v & 0x80) !== 0;
387
+ break;
388
+ case 1:
389
+ p.period = (p.period & 0xf00) | v;
390
+ break;
391
+ case 2:
392
+ p.period = (p.period & 0x0ff) | ((v & 0x0f) << 8);
393
+ p.enabled = (v & 0x80) !== 0;
394
+ // Clearing E resets the duty step; the divider runs on.
395
+ if (!p.enabled)
396
+ p.step = 0;
397
+ break;
398
+ }
399
+ return true;
400
+ }
401
+ if (address >= 0xb000 && address <= 0xb002) {
402
+ switch (address & 3) {
403
+ case 0:
404
+ this.sawRate = v & 0x3f;
405
+ break;
406
+ case 1:
407
+ this.sawPeriod = (this.sawPeriod & 0xf00) | v;
408
+ break;
409
+ case 2:
410
+ this.sawPeriod = (this.sawPeriod & 0x0ff) | ((v & 0x0f) << 8);
411
+ this.sawEnabled = (v & 0x80) !== 0;
412
+ if (!this.sawEnabled) {
413
+ this.sawStep = 0;
414
+ this.sawAccumulator = 0;
415
+ }
416
+ break;
417
+ }
418
+ return true;
419
+ }
420
+ return false;
421
+ }
422
+ static pulseLevel(p) {
423
+ if (!p.enabled)
424
+ return 0;
425
+ if (p.constant)
426
+ return p.volume;
427
+ return p.step <= p.duty ? p.volume : 0;
428
+ }
429
+ /**
430
+ * Advance `count` samples, ADDING each channel's output to `outs[0]` (pulse 1), `outs[1]` (pulse
431
+ * 2) and `outs[2]` (saw) — or, for a channel without a buffer of its own, to `outs[3]` if given —
432
+ * from `offset`.
433
+ */
434
+ render(count, outs, offset = 0) {
435
+ const cps = this.cyclesPerSample;
436
+ const scale = VRC6_STEP / cps;
437
+ const running = !this.halted;
438
+ for (let c = 0; c < 2; c++) {
439
+ const out = outs[c] ?? outs[3];
440
+ const p = this.pulses[c];
441
+ const reload = (p.period >> this.shift) + 1;
442
+ // Not stepping, or stepping makes no difference: one level for the whole run.
443
+ if (!running || !p.enabled || p.constant || p.volume === 0) {
444
+ if (out) {
445
+ const level = Vrc6Chip.pulseLevel(p) * VRC6_STEP;
446
+ if (level !== 0)
447
+ for (let k = 0; k < count; k++)
448
+ out[offset + k] += level;
449
+ }
450
+ if (running && p.enabled) {
451
+ // The duty step moves on all the same, for when the level comes back.
452
+ const cycles = count * cps;
453
+ if (cycles >= p.timer) {
454
+ const steps = 1 + Math.floor((cycles - p.timer) / reload);
455
+ p.step = (p.step + steps) & 15;
456
+ p.timer = reload - ((cycles - p.timer) % reload);
457
+ }
458
+ else
459
+ p.timer -= cycles;
460
+ }
461
+ continue;
462
+ }
463
+ for (let k = 0; k < count; k++) {
464
+ let left = cps;
465
+ let sum = 0;
466
+ while (left >= p.timer) {
467
+ sum += (p.step <= p.duty ? p.volume : 0) * p.timer;
468
+ left -= p.timer;
469
+ p.step = (p.step + 1) & 15;
470
+ p.timer = reload;
471
+ }
472
+ sum += (p.step <= p.duty ? p.volume : 0) * left;
473
+ p.timer -= left;
474
+ if (out)
475
+ out[offset + k] += sum * scale;
476
+ }
477
+ }
478
+ {
479
+ const out = outs[2] ?? outs[3];
480
+ const reload = (this.sawPeriod >> this.shift) + 1;
481
+ if (!running || !this.sawEnabled) {
482
+ const level = this.sawEnabled ? (this.sawAccumulator >> 3) * VRC6_STEP : 0;
483
+ if (out && level !== 0)
484
+ for (let k = 0; k < count; k++)
485
+ out[offset + k] += level;
486
+ return;
487
+ }
488
+ for (let k = 0; k < count; k++) {
489
+ let left = cps;
490
+ let sum = 0;
491
+ while (left >= this.sawTimer) {
492
+ sum += (this.sawAccumulator >> 3) * this.sawTimer;
493
+ left -= this.sawTimer;
494
+ this.sawTimer = reload;
495
+ // Fourteen steps a cycle: the accumulator grows on every other one and starts over on the 14th.
496
+ this.sawStep = (this.sawStep + 1) % 14;
497
+ if (this.sawStep === 0)
498
+ this.sawAccumulator = 0;
499
+ else if ((this.sawStep & 1) === 0)
500
+ this.sawAccumulator = (this.sawAccumulator + this.sawRate) & 0xff;
501
+ }
502
+ sum += (this.sawAccumulator >> 3) * left;
503
+ this.sawTimer -= left;
504
+ if (out)
505
+ out[offset + k] += sum * scale;
506
+ }
507
+ }
508
+ }
509
+ snapshot() {
510
+ const pulse = (p) => ({
511
+ period: p.period,
512
+ volume: p.volume,
513
+ duty: p.duty,
514
+ constant: p.constant,
515
+ enabled: p.enabled,
516
+ });
517
+ return {
518
+ pulse: [pulse(this.pulses[0]), pulse(this.pulses[1])],
519
+ saw: { period: this.sawPeriod, rate: this.sawRate, enabled: this.sawEnabled },
520
+ halted: this.halted,
521
+ shift: this.shift,
522
+ };
523
+ }
524
+ }
337
525
  /** Hz of an FDS frequency register value. */
338
526
  export const fdsHz = (frequency) => (CPU_HZ * frequency) / 4194304;
339
527
  /** Hz of an N163 channel, from its frequency, wave length and the number of channels on. */
340
528
  export const n163Hz = (frequency, length, channels) => (CPU_HZ * frequency) / (15 * 65536 * channels * length);
529
+ /** Hz of a VRC6 pulse period (with `$9003`'s shift, if any): 16 steps of `(period >> shift) + 1` cycles. */
530
+ export const vrc6PulseHz = (period, shift = 0) => CPU_HZ / (16 * ((period >> shift) + 1));
531
+ /** Hz of the VRC6 sawtooth's period (with `$9003`'s shift, if any): 14 steps of `(period >> shift) + 1` cycles. */
532
+ export const vrc6SawHz = (period, shift = 0) => CPU_HZ / (14 * ((period >> shift) + 1));
341
533
  //# sourceMappingURL=expansion.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"expansion.js","sourceRoot":"","sources":["../src/expansion.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAExC,8FAA8F;AAC9F,MAAM,QAAQ,GAAG,IAAI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AG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;YAC7B,MAAM,IAAI,GAAa,EAAE,CAAC;YAC1B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,CAAC,EAAE;gBAAE,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC;YAC5F,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;QACpC,CAAC;QACD,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;IAClF,CAAC;CACF;AAED,6CAA6C;AAC7C,MAAM,CAAC,MAAM,KAAK,GAAG,CAAC,SAAiB,EAAE,EAAE,CAAC,CAAC,MAAM,GAAG,SAAS,CAAC,GAAG,OAAO,CAAC;AAE3E,4FAA4F;AAC5F,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,SAAiB,EAAE,MAAc,EAAE,QAAgB,EAAE,EAAE,CAC5E,CAAC,MAAM,GAAG,SAAS,CAAC,GAAG,CAAC,EAAE,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC,CAAC","sourcesContent":["/**\n * The two expansion sound chips the Famicom's own games carried most: the Disk\n * System's wavetable voice (FDS) and Namco's 163 (N163). Each is a channel the\n * 2A03 does not have — a waveform drawn in RAM, played back at a pitch — and\n * games that use them put their melody there, so without them a soundtrack is\n * its bass and drums.\n *\n * Like the APU here they run at the sample rate, not per CPU cycle: each sample\n * advances the chip by `CPU_HZ / sampleRate` cycles' worth of its counters.\n *\n * Output is in the units `mixApu` returns (0..~1 for the whole 2A03), so a\n * renderer adds it to the mix. The levels relative to the 2A03 follow the\n * common reference players: FDS at full gain about as loud as both pulses at\n * full, an N163 channel at full volume about as loud as one pulse — divided by\n * the number of channels it time-shares its one output with, as the chip does.\n */\n\nimport { CPU_HZ } from './constants.js';\n\n/** Full-scale output of the FDS (wave 63 × gain 32 at master volume 1), in `mixApu` units. */\nconst FDS_FULL = 0.25;\n/** Full-scale output of one N163 sample step (|sample - 8| = 8 at volume 15), in `mixApu` units. */\nconst N163_FULL = 0.16;\n/** The FDS master volume, `$4089` bits 0–1: 1, 2/3, 1/2, 2/5. */\nconst FDS_MASTER = [1, 2 / 3, 1 / 2, 2 / 5];\n/** Mod table entries → how far each moves the mod counter; 4 resets it. */\nconst MOD_STEP = [0, 1, 2, 4, 0, -4, -2, -1];\n\nexport interface FdsSnapshot {\n /** 12-bit wave frequency; Hz = CPU_HZ * frequency / 4194304. */\n frequency: number;\n /** Volume gain as the chip uses it, 0..32. */\n gain: number;\n /** `$4089` bits 0–1. */\n master: number;\n /** The 64 wave samples, 0..63. */\n wave: number[];\n /** Wave unit halted (`$4083` bit 7) or the wave being written (`$4089` bit 7). */\n halted: boolean;\n /** Modulation depth (mod gain, 0..63) and frequency: a vibrato when both are above 0. */\n modGain: number;\n modFrequency: number;\n}\n\nexport class FdsChip {\n private readonly cyclesPerSample: number;\n readonly wave = new Uint8Array(64);\n private readonly modTable = new Uint8Array(64);\n private modWritePos = 0;\n private frequency = 0;\n private haltWave = true;\n private envelopesOff = true;\n private waveWrite = false;\n private master = 0;\n private envSpeed = 0xe8;\n // Volume envelope.\n private volDirect = true;\n private volIncrease = false;\n private volSpeed = 0;\n private volGain = 0;\n private volCounter = 0;\n // Mod envelope and unit.\n private modDirect = true;\n private modIncrease = false;\n private modSpeed = 0;\n private modGain = 0;\n private modCounterEnv = 0;\n private modFrequency = 0;\n private modHalt = true;\n private modCounter = 0;\n private modPos = 0;\n private modAcc = 0;\n private waveAcc = 0;\n private wavePos = 0;\n /** Gain latched at the start of each wave cycle, as the chip does: a level change waits for the cycle. */\n private latchedGain = 0;\n\n constructor(sampleRate: number) {\n this.cyclesPerSample = CPU_HZ / sampleRate;\n }\n\n /** A write to `$4040`–`$408A`. Returns false for any other address. */\n write(address: number, value: number): boolean {\n const v = value & 0xff;\n if (address >= 0x4040 && address <= 0x407f) {\n if (this.waveWrite) this.wave[address - 0x4040] = v & 0x3f;\n return true;\n }\n switch (address) {\n case 0x4080:\n this.volDirect = (v & 0x80) !== 0;\n this.volIncrease = (v & 0x40) !== 0;\n this.volSpeed = v & 0x3f;\n if (this.volDirect) this.volGain = v & 0x3f;\n this.volCounter = 0;\n return true;\n case 0x4082:\n this.frequency = (this.frequency & 0xf00) | v;\n return true;\n case 0x4083:\n this.frequency = (this.frequency & 0x0ff) | ((v & 0x0f) << 8);\n this.haltWave = (v & 0x80) !== 0;\n this.envelopesOff = (v & 0x40) !== 0;\n if (this.haltWave) {\n this.waveAcc = 0;\n this.wavePos = 0;\n }\n return true;\n case 0x4084:\n this.modDirect = (v & 0x80) !== 0;\n this.modIncrease = (v & 0x40) !== 0;\n this.modSpeed = v & 0x3f;\n if (this.modDirect) this.modGain = v & 0x3f;\n this.modCounterEnv = 0;\n return true;\n case 0x4085:\n this.modCounter = ((v & 0x7f) << 25) >> 25; // 7-bit signed\n return true;\n case 0x4086:\n this.modFrequency = (this.modFrequency & 0xf00) | v;\n return true;\n case 0x4087:\n this.modFrequency = (this.modFrequency & 0x0ff) | ((v & 0x0f) << 8);\n this.modHalt = (v & 0x80) !== 0;\n if (this.modHalt) this.modAcc = 0;\n return true;\n case 0x4088:\n // Only while the mod unit is halted; each write fills two steps.\n if (this.modHalt) {\n this.modTable[this.modWritePos] = v & 7;\n this.modTable[(this.modWritePos + 1) & 63] = v & 7;\n this.modWritePos = (this.modWritePos + 2) & 63;\n }\n return true;\n case 0x4089:\n this.waveWrite = (v & 0x80) !== 0;\n this.master = v & 3;\n return true;\n case 0x408a:\n this.envSpeed = v;\n return true;\n }\n return address >= 0x4040 && address <= 0x4097;\n }\n\n /** The pitch the wave unit runs at this moment, after modulation (the chip's own arithmetic). */\n private modulatedFrequency(): number {\n if (this.modHalt || this.modGain === 0) return this.frequency;\n let temp = this.modCounter * this.modGain;\n const rem = temp & 0x0f;\n temp >>= 4;\n if (rem > 0 && (temp & 0x80) === 0) temp += this.modCounter < 0 ? -1 : 2;\n if (temp >= 192) temp -= 256;\n else if (temp < -64) temp += 256;\n temp *= this.frequency;\n const rem2 = temp & 0x3f;\n temp >>= 6;\n if (rem2 >= 32) temp += 1;\n return Math.max(0, this.frequency + temp);\n }\n\n /**\n * Advance `count` samples, ADDING the output to `out` from `offset` (in `mixApu` units, centred\n * by the renderer's filters like the rest).\n */\n render(count: number, out: Float64Array, offset = 0) {\n const cps = this.cyclesPerSample;\n const masterScale = (FDS_MASTER[this.master] * FDS_FULL) / (63 * 32);\n for (let k = 0; k < count; k++) {\n // Envelopes: one step every 8 × envSpeed × (speed + 1) cycles.\n if (!this.envelopesOff && this.envSpeed > 0 && !this.haltWave) {\n if (!this.volDirect) {\n this.volCounter += cps;\n const period = 8 * this.envSpeed * (this.volSpeed + 1);\n while (this.volCounter >= period) {\n this.volCounter -= period;\n if (this.volIncrease) {\n if (this.volGain < 32) this.volGain++;\n } else if (this.volGain > 0) this.volGain--;\n }\n }\n if (!this.modDirect) {\n this.modCounterEnv += cps;\n const period = 8 * this.envSpeed * (this.modSpeed + 1);\n while (this.modCounterEnv >= period) {\n this.modCounterEnv -= period;\n if (this.modIncrease) {\n if (this.modGain < 32) this.modGain++;\n } else if (this.modGain > 0) this.modGain--;\n }\n }\n }\n // Mod unit: steps through its table as its accumulator overflows 16 bits.\n if (!this.modHalt && this.modFrequency > 0) {\n this.modAcc += this.modFrequency * cps;\n while (this.modAcc >= 0x10000) {\n this.modAcc -= 0x10000;\n const step = this.modTable[this.modPos];\n this.modPos = (this.modPos + 1) & 63;\n if (step === 4) this.modCounter = 0;\n else {\n this.modCounter += MOD_STEP[step];\n if (this.modCounter > 63) this.modCounter -= 128;\n else if (this.modCounter < -64) this.modCounter += 128;\n }\n }\n }\n // Wave unit: 64 steps a cycle, the accumulator 16 bits a step.\n if (!this.haltWave && !this.waveWrite) {\n this.waveAcc += this.modulatedFrequency() * cps;\n while (this.waveAcc >= 0x10000) {\n this.waveAcc -= 0x10000;\n this.wavePos = (this.wavePos + 1) & 63;\n if (this.wavePos === 0) this.latchedGain = Math.min(32, this.volGain);\n }\n if (this.latchedGain === 0 && this.volGain > 0 && this.wavePos === 0) this.latchedGain = Math.min(32, this.volGain);\n }\n const level = this.waveWrite ? 0 : this.wave[this.wavePos] * this.latchedGain;\n out[offset + k] += level * masterScale;\n }\n }\n\n snapshot(): FdsSnapshot {\n return {\n frequency: this.frequency,\n gain: Math.min(32, this.volGain),\n master: this.master,\n wave: Array.from(this.wave),\n halted: this.haltWave || this.waveWrite,\n modGain: this.modHalt ? 0 : this.modGain,\n modFrequency: this.modHalt ? 0 : this.modFrequency,\n };\n }\n}\n\nexport interface N163ChannelSnapshot {\n /** 0..7 — the register slot, `$40 + 8·slot` in the chip's RAM; slot 7 ($78) is always on. */\n slot: number;\n /** 18-bit frequency; Hz = CPU_HZ * frequency / (15 · 65536 · channels · length). */\n frequency: number;\n /** Wave length in 4-bit samples. */\n length: number;\n /** Where the wave starts, in 4-bit samples. */\n waveAddress: number;\n volume: number;\n /** The wave as it stands in RAM, `length` samples 0..15. */\n wave: number[];\n}\n\nexport interface N163Snapshot {\n /** How many channels are on, 1..8 — the top ones, from slot 7 down. */\n channels: number;\n active: N163ChannelSnapshot[];\n}\n\nexport class N163Chip {\n private readonly cyclesPerSample: number;\n readonly ram = new Uint8Array(128);\n private address = 0;\n private autoIncrement = false;\n private disabled = false;\n private readonly phase = new Float64Array(8);\n\n constructor(sampleRate: number) {\n this.cyclesPerSample = CPU_HZ / sampleRate;\n }\n\n /** A write to the address port (`$F800`), data port (`$4800`) or `$E000`. Returns false for others. */\n write(address: number, value: number): boolean {\n const v = value & 0xff;\n if (address >= 0xf800 && address <= 0xffff) {\n this.address = v & 0x7f;\n this.autoIncrement = (v & 0x80) !== 0;\n return true;\n }\n if (address >= 0x4800 && address <= 0x4fff) {\n this.ram[this.address] = v;\n if (this.autoIncrement) this.address = (this.address + 1) & 0x7f;\n return true;\n }\n if (address >= 0xe000 && address <= 0xe7ff) {\n this.disabled = (v & 0x40) !== 0;\n return true;\n }\n return false;\n }\n\n /** A read of the data port, as the CPU makes it — auto-increment included. */\n read(): number {\n const v = this.ram[this.address];\n if (this.autoIncrement) this.address = (this.address + 1) & 0x7f;\n return v;\n }\n\n /** The address port as it stands — the next RAM byte the data port reaches, with bit 7 for auto-increment. */\n get port(): number {\n return this.address | (this.autoIncrement ? 0x80 : 0);\n }\n\n get channels(): number {\n return ((this.ram[0x7f] >> 4) & 7) + 1;\n }\n\n /**\n * A channel's eight bytes, interleaved as on the chip: frequency low, phase low, frequency\n * middle, phase middle, the frequency's high two bits with the wave length above them, phase\n * high, the wave's address, the volume. (Namco's drivers write the frequency bytes and step over\n * the phase ones by READING the data port — auto-increment counts reads too.)\n */\n private channel(slot: number) {\n const base = 0x40 + slot * 8;\n const r = this.ram;\n return {\n frequency: r[base] | (r[base + 2] << 8) | ((r[base + 4] & 3) << 16),\n length: 256 - (r[base + 4] & 0xfc),\n waveAddress: r[base + 6],\n volume: r[base + 7] & 0x0f,\n };\n }\n\n private sample(index: number): number {\n const byte = this.ram[(index >> 1) & 0x7f];\n return index & 1 ? byte >> 4 : byte & 0x0f;\n }\n\n /**\n * Advance `count` samples, ADDING each active channel's output to `outs[slot]` (or, when a\n * channel has no buffer of its own, to `outs[8]` if given) from `offset`.\n */\n render(count: number, outs: readonly (Float64Array | undefined)[], offset = 0) {\n if (this.disabled) return;\n const n = this.channels;\n // Each channel is updated once every 15·n cycles, and the one DAC is shared n ways.\n const updatesPerSample = this.cyclesPerSample / (15 * n);\n const scale = N163_FULL / (8 * 15 * n);\n for (let slot = 8 - n; slot < 8; slot++) {\n const out = outs[slot] ?? outs[8];\n if (!out) continue;\n const c = this.channel(slot);\n if (c.volume === 0 || c.frequency === 0) continue;\n const step = c.frequency * updatesPerSample;\n const wrap = c.length * 0x10000;\n let phase = this.phase[slot];\n for (let k = 0; k < count; k++) {\n phase += step;\n if (phase >= wrap) phase %= wrap;\n const s = this.sample(((phase / 0x10000) | 0) + c.waveAddress);\n out[offset + k] += (s - 8) * c.volume * scale;\n }\n this.phase[slot] = phase;\n }\n }\n\n snapshot(): N163Snapshot {\n const n = this.channels;\n const active: N163ChannelSnapshot[] = [];\n for (let slot = 8 - n; slot < 8; slot++) {\n const c = this.channel(slot);\n const wave: number[] = [];\n for (let i = 0; i < Math.min(c.length, 256); i++) wave.push(this.sample(c.waveAddress + i));\n active.push({ slot, ...c, wave });\n }\n return { channels: this.disabled ? 0 : n, active: this.disabled ? [] : active };\n }\n}\n\n/** Hz of an FDS frequency register value. */\nexport const fdsHz = (frequency: number) => (CPU_HZ * frequency) / 4194304;\n\n/** Hz of an N163 channel, from its frequency, wave length and the number of channels on. */\nexport const n163Hz = (frequency: number, length: number, channels: number) =>\n (CPU_HZ * frequency) / (15 * 65536 * channels * length);\n"]}
1
+ {"version":3,"file":"expansion.js","sourceRoot":"","sources":["../src/expansion.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAExC,8FAA8F;AAC9F,MAAM,QAAQ,GAAG,IAAI,CAAC;AACtB,oGAAoG;AACpG,MAAM,SAAS,GAAG,IAAI,CAAC;AACvB,iEAAiE;AACjE,MAAM,UAAU,GAAG,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;AAC5C,2EAA2E;AAC3E,MAAM,QAAQ,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAA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AM,GAAG,SAAS,CAAC,GAAG,OAAO,CAAC;AAE3E,4FAA4F;AAC5F,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,SAAiB,EAAE,MAAc,EAAE,QAAgB,EAAE,EAAE,CAC5E,CAAC,MAAM,GAAG,SAAS,CAAC,GAAG,CAAC,EAAE,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC,CAAC;AAE1D,4GAA4G;AAC5G,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,MAAc,EAAE,KAAK,GAAG,CAAC,EAAE,EAAE,CAAC,MAAM,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AAElG,mHAAmH;AACnH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,MAAc,EAAE,KAAK,GAAG,CAAC,EAAE,EAAE,CAAC,MAAM,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC","sourcesContent":["/**\n * The expansion sound chips the Famicom's own games carried most: the Disk\n * System's wavetable voice (FDS), Namco's 163 (N163) and Konami's VRC6. Each\n * adds channels the 2A03 does not have — a waveform drawn in RAM played back at\n * a pitch, or two more pulses and a sawtooth — and games that use them put\n * their melody there, so without them a soundtrack is its bass and drums.\n *\n * Like the APU here they run at the sample rate, not per CPU cycle: each sample\n * advances the chip by `CPU_HZ / sampleRate` cycles' worth of its counters.\n *\n * Output is in the units `mixApu` returns (0..~1 for the whole 2A03), so a\n * renderer adds it to the mix. The levels relative to the 2A03 follow the\n * common reference players: FDS at full gain about as loud as both pulses at\n * full, an N163 channel at full volume about as loud as one pulse — divided by\n * the number of channels it time-shares its one output with, as the chip does —\n * and a VRC6 pulse at full volume one and a half times a 2A03 pulse, as Mesen2\n * mixes it (`VRC6_STEP`).\n */\n\nimport { CPU_HZ } from './constants.js';\n\n/** Full-scale output of the FDS (wave 63 × gain 32 at master volume 1), in `mixApu` units. */\nconst FDS_FULL = 0.25;\n/** Full-scale output of one N163 sample step (|sample - 8| = 8 at volume 15), in `mixApu` units. */\nconst N163_FULL = 0.16;\n/** The FDS master volume, `$4089` bits 0–1: 1, 2/3, 1/2, 2/5. */\nconst FDS_MASTER = [1, 2 / 3, 1 / 2, 2 / 5];\n/** Mod table entries → how far each moves the mod counter; 4 resets it. */\nconst MOD_STEP = [0, 1, 2, 4, 0, -4, -2, -1];\n/**\n * One step of the VRC6's output (pulse 0..15 + pulse 0..15 + saw 0..31), in `mixApu` units. From\n * Mesen2, which adds the chip's summed output × 15 (Core/NES/Mappers/Audio/Vrc6Audio.h) × 5\n * (Core/NES/NesSoundMixer.cpp, GetOutputVolume) to a 2A03 mix whose `mixApu` 1.0 is 5000 there:\n * 75 / 5000. A VRC6 pulse at volume 15 is so 0.225, about one and a half 2A03 pulses at 15.\n */\nconst VRC6_STEP = 75 / 5000;\n\nexport interface FdsSnapshot {\n /** 12-bit wave frequency; Hz = CPU_HZ * frequency / 4194304. */\n frequency: number;\n /** Volume gain as the chip uses it, 0..32. */\n gain: number;\n /** `$4089` bits 0–1. */\n master: number;\n /** The 64 wave samples, 0..63. */\n wave: number[];\n /** Wave unit halted (`$4083` bit 7) or the wave being written (`$4089` bit 7). */\n halted: boolean;\n /** Modulation depth (mod gain, 0..63) and frequency: a vibrato when both are above 0. */\n modGain: number;\n modFrequency: number;\n}\n\nexport class FdsChip {\n private readonly cyclesPerSample: number;\n readonly wave = new Uint8Array(64);\n private readonly modTable = new Uint8Array(64);\n private modWritePos = 0;\n private frequency = 0;\n private haltWave = true;\n private envelopesOff = true;\n private waveWrite = false;\n private master = 0;\n private envSpeed = 0xe8;\n // Volume envelope.\n private volDirect = true;\n private volIncrease = false;\n private volSpeed = 0;\n private volGain = 0;\n private volCounter = 0;\n // Mod envelope and unit.\n private modDirect = true;\n private modIncrease = false;\n private modSpeed = 0;\n private modGain = 0;\n private modCounterEnv = 0;\n private modFrequency = 0;\n private modHalt = true;\n private modCounter = 0;\n private modPos = 0;\n private modAcc = 0;\n private waveAcc = 0;\n private wavePos = 0;\n /** Gain latched at the start of each wave cycle, as the chip does: a level change waits for the cycle. */\n private latchedGain = 0;\n\n constructor(sampleRate: number) {\n this.cyclesPerSample = CPU_HZ / sampleRate;\n }\n\n /** A write to `$4040`–`$408A`. Returns false for any other address. */\n write(address: number, value: number): boolean {\n const v = value & 0xff;\n if (address >= 0x4040 && address <= 0x407f) {\n if (this.waveWrite) this.wave[address - 0x4040] = v & 0x3f;\n return true;\n }\n switch (address) {\n case 0x4080:\n this.volDirect = (v & 0x80) !== 0;\n this.volIncrease = (v & 0x40) !== 0;\n this.volSpeed = v & 0x3f;\n if (this.volDirect) this.volGain = v & 0x3f;\n this.volCounter = 0;\n return true;\n case 0x4082:\n this.frequency = (this.frequency & 0xf00) | v;\n return true;\n case 0x4083:\n this.frequency = (this.frequency & 0x0ff) | ((v & 0x0f) << 8);\n this.haltWave = (v & 0x80) !== 0;\n this.envelopesOff = (v & 0x40) !== 0;\n if (this.haltWave) {\n this.waveAcc = 0;\n this.wavePos = 0;\n }\n return true;\n case 0x4084:\n this.modDirect = (v & 0x80) !== 0;\n this.modIncrease = (v & 0x40) !== 0;\n this.modSpeed = v & 0x3f;\n if (this.modDirect) this.modGain = v & 0x3f;\n this.modCounterEnv = 0;\n return true;\n case 0x4085:\n this.modCounter = ((v & 0x7f) << 25) >> 25; // 7-bit signed\n return true;\n case 0x4086:\n this.modFrequency = (this.modFrequency & 0xf00) | v;\n return true;\n case 0x4087:\n this.modFrequency = (this.modFrequency & 0x0ff) | ((v & 0x0f) << 8);\n this.modHalt = (v & 0x80) !== 0;\n if (this.modHalt) this.modAcc = 0;\n return true;\n case 0x4088:\n // Only while the mod unit is halted; each write fills two steps.\n if (this.modHalt) {\n this.modTable[this.modWritePos] = v & 7;\n this.modTable[(this.modWritePos + 1) & 63] = v & 7;\n this.modWritePos = (this.modWritePos + 2) & 63;\n }\n return true;\n case 0x4089:\n this.waveWrite = (v & 0x80) !== 0;\n this.master = v & 3;\n return true;\n case 0x408a:\n this.envSpeed = v;\n return true;\n }\n return address >= 0x4040 && address <= 0x4097;\n }\n\n /** The pitch the wave unit runs at this moment, after modulation (the chip's own arithmetic). */\n private modulatedFrequency(): number {\n if (this.modHalt || this.modGain === 0) return this.frequency;\n let temp = this.modCounter * this.modGain;\n const rem = temp & 0x0f;\n temp >>= 4;\n if (rem > 0 && (temp & 0x80) === 0) temp += this.modCounter < 0 ? -1 : 2;\n if (temp >= 192) temp -= 256;\n else if (temp < -64) temp += 256;\n temp *= this.frequency;\n const rem2 = temp & 0x3f;\n temp >>= 6;\n if (rem2 >= 32) temp += 1;\n return Math.max(0, this.frequency + temp);\n }\n\n /**\n * Advance `count` samples, ADDING the output to `out` from `offset` (in `mixApu` units, centred\n * by the renderer's filters like the rest).\n */\n render(count: number, out: Float64Array, offset = 0) {\n const cps = this.cyclesPerSample;\n const masterScale = (FDS_MASTER[this.master] * FDS_FULL) / (63 * 32);\n for (let k = 0; k < count; k++) {\n // Envelopes: one step every 8 × envSpeed × (speed + 1) cycles.\n if (!this.envelopesOff && this.envSpeed > 0 && !this.haltWave) {\n if (!this.volDirect) {\n this.volCounter += cps;\n const period = 8 * this.envSpeed * (this.volSpeed + 1);\n while (this.volCounter >= period) {\n this.volCounter -= period;\n if (this.volIncrease) {\n if (this.volGain < 32) this.volGain++;\n } else if (this.volGain > 0) this.volGain--;\n }\n }\n if (!this.modDirect) {\n this.modCounterEnv += cps;\n const period = 8 * this.envSpeed * (this.modSpeed + 1);\n while (this.modCounterEnv >= period) {\n this.modCounterEnv -= period;\n if (this.modIncrease) {\n if (this.modGain < 32) this.modGain++;\n } else if (this.modGain > 0) this.modGain--;\n }\n }\n }\n // Mod unit: steps through its table as its accumulator overflows 16 bits.\n if (!this.modHalt && this.modFrequency > 0) {\n this.modAcc += this.modFrequency * cps;\n while (this.modAcc >= 0x10000) {\n this.modAcc -= 0x10000;\n const step = this.modTable[this.modPos];\n this.modPos = (this.modPos + 1) & 63;\n if (step === 4) this.modCounter = 0;\n else {\n this.modCounter += MOD_STEP[step];\n if (this.modCounter > 63) this.modCounter -= 128;\n else if (this.modCounter < -64) this.modCounter += 128;\n }\n }\n }\n // Wave unit: 64 steps a cycle, the accumulator 16 bits a step.\n if (!this.haltWave && !this.waveWrite) {\n this.waveAcc += this.modulatedFrequency() * cps;\n while (this.waveAcc >= 0x10000) {\n this.waveAcc -= 0x10000;\n this.wavePos = (this.wavePos + 1) & 63;\n if (this.wavePos === 0) this.latchedGain = Math.min(32, this.volGain);\n }\n if (this.latchedGain === 0 && this.volGain > 0 && this.wavePos === 0) this.latchedGain = Math.min(32, this.volGain);\n }\n const level = this.waveWrite ? 0 : this.wave[this.wavePos] * this.latchedGain;\n out[offset + k] += level * masterScale;\n }\n }\n\n snapshot(): FdsSnapshot {\n return {\n frequency: this.frequency,\n gain: Math.min(32, this.volGain),\n master: this.master,\n wave: Array.from(this.wave),\n halted: this.haltWave || this.waveWrite,\n modGain: this.modHalt ? 0 : this.modGain,\n modFrequency: this.modHalt ? 0 : this.modFrequency,\n };\n }\n}\n\nexport interface N163ChannelSnapshot {\n /** 0..7 — the register slot, `$40 + 8·slot` in the chip's RAM; slot 7 ($78) is always on. */\n slot: number;\n /** 18-bit frequency; Hz = CPU_HZ * frequency / (15 · 65536 · channels · length). */\n frequency: number;\n /** Wave length in 4-bit samples. */\n length: number;\n /** Where the wave starts, in 4-bit samples. */\n waveAddress: number;\n volume: number;\n /** The wave as it stands in RAM, `length` samples 0..15. */\n wave: number[];\n}\n\nexport interface N163Snapshot {\n /** How many channels are on, 1..8 — the top ones, from slot 7 down. */\n channels: number;\n active: N163ChannelSnapshot[];\n}\n\nexport class N163Chip {\n private readonly cyclesPerSample: number;\n readonly ram = new Uint8Array(128);\n private address = 0;\n private autoIncrement = false;\n private disabled = false;\n private readonly phase = new Float64Array(8);\n\n constructor(sampleRate: number) {\n this.cyclesPerSample = CPU_HZ / sampleRate;\n }\n\n /** A write to the address port (`$F800`), data port (`$4800`) or `$E000`. Returns false for others. */\n write(address: number, value: number): boolean {\n const v = value & 0xff;\n if (address >= 0xf800 && address <= 0xffff) {\n this.address = v & 0x7f;\n this.autoIncrement = (v & 0x80) !== 0;\n return true;\n }\n if (address >= 0x4800 && address <= 0x4fff) {\n this.ram[this.address] = v;\n if (this.autoIncrement) this.address = (this.address + 1) & 0x7f;\n return true;\n }\n if (address >= 0xe000 && address <= 0xe7ff) {\n this.disabled = (v & 0x40) !== 0;\n return true;\n }\n return false;\n }\n\n /** A read of the data port, as the CPU makes it — auto-increment included. */\n read(): number {\n const v = this.ram[this.address];\n if (this.autoIncrement) this.address = (this.address + 1) & 0x7f;\n return v;\n }\n\n /** The address port as it stands — the next RAM byte the data port reaches, with bit 7 for auto-increment. */\n get port(): number {\n return this.address | (this.autoIncrement ? 0x80 : 0);\n }\n\n get channels(): number {\n return ((this.ram[0x7f] >> 4) & 7) + 1;\n }\n\n /**\n * A channel's eight bytes, interleaved as on the chip: frequency low, phase low, frequency\n * middle, phase middle, the frequency's high two bits with the wave length above them, phase\n * high, the wave's address, the volume. (Namco's drivers write the frequency bytes and step over\n * the phase ones by READING the data port — auto-increment counts reads too.)\n */\n private channel(slot: number) {\n const base = 0x40 + slot * 8;\n const r = this.ram;\n return {\n frequency: r[base] | (r[base + 2] << 8) | ((r[base + 4] & 3) << 16),\n length: 256 - (r[base + 4] & 0xfc),\n waveAddress: r[base + 6],\n volume: r[base + 7] & 0x0f,\n };\n }\n\n private sample(index: number): number {\n const byte = this.ram[(index >> 1) & 0x7f];\n return index & 1 ? byte >> 4 : byte & 0x0f;\n }\n\n /**\n * Advance `count` samples, ADDING each active channel's output to `outs[slot]` (or, when a\n * channel has no buffer of its own, to `outs[8]` if given) from `offset`.\n */\n render(count: number, outs: readonly (Float64Array | undefined)[], offset = 0) {\n if (this.disabled) return;\n const n = this.channels;\n // Each channel is updated once every 15·n cycles, and the one DAC is shared n ways.\n const updatesPerSample = this.cyclesPerSample / (15 * n);\n const scale = N163_FULL / (8 * 15 * n);\n for (let slot = 8 - n; slot < 8; slot++) {\n const out = outs[slot] ?? outs[8];\n if (!out) continue;\n const c = this.channel(slot);\n if (c.volume === 0 || c.frequency === 0) continue;\n const step = c.frequency * updatesPerSample;\n const wrap = c.length * 0x10000;\n let phase = this.phase[slot];\n for (let k = 0; k < count; k++) {\n phase += step;\n if (phase >= wrap) phase %= wrap;\n const s = this.sample(((phase / 0x10000) | 0) + c.waveAddress);\n out[offset + k] += (s - 8) * c.volume * scale;\n }\n this.phase[slot] = phase;\n }\n }\n\n snapshot(): N163Snapshot {\n const n = this.channels;\n const active: N163ChannelSnapshot[] = [];\n for (let slot = 8 - n; slot < 8; slot++) {\n const c = this.channel(slot);\n const wave: number[] = [];\n for (let i = 0; i < Math.min(c.length, 256); i++) wave.push(this.sample(c.waveAddress + i));\n active.push({ slot, ...c, wave });\n }\n return { channels: this.disabled ? 0 : n, active: this.disabled ? [] : active };\n }\n}\n\n/** One of the VRC6's two pulses, `$9000`–`$9002` or `$A000`–`$A002`. */\nexport interface Vrc6PulseSnapshot {\n /** 12-bit period; Hz = CPU_HZ / (16 · (period + 1)) — see `vrc6PulseHz`. */\n period: number;\n volume: number;\n /** 0..7: high for duty + 1 of every 16 steps. */\n duty: number;\n /** The mode bit (`$x000` bit 7): the volume put out as it is, the duty ignored. */\n constant: boolean;\n enabled: boolean;\n}\n\nexport interface Vrc6Snapshot {\n pulse: [Vrc6PulseSnapshot, Vrc6PulseSnapshot];\n saw: {\n /** 12-bit period; Hz = CPU_HZ / (14 · (period + 1)) — see `vrc6SawHz`. */\n period: number;\n /** The accumulator rate, 0..63; past 42 the 8-bit accumulator wraps and the wave breaks up. */\n rate: number;\n enabled: boolean;\n };\n /** `$9003` bit 0: every oscillator stopped where it is. */\n halted: boolean;\n /** `$9003`: the periods shifted right by 4 (bit 1) or 8 (bit 2, which wins) — ×16 / ×256 pitch. */\n shift: number;\n}\n\ninterface Vrc6Pulse {\n volume: number;\n duty: number;\n constant: boolean;\n period: number;\n enabled: boolean;\n /** CPU cycles until the next step, fractional. */\n timer: number;\n step: number;\n}\n\n/**\n * Konami's VRC6: two pulses with eight duties and a sawtooth, beside the 2A03 (Akumajou Densetsu,\n * Madara, Esper Dream 2). The registers are at the addresses the NSF format gives them —\n * `$9000`–`$9003`, `$A000`–`$A002`, `$B000`–`$B002`; the cartridges themselves differ in which of\n * A0/A1 they wire to the chip, which a player maps before here.\n *\n * Each channel counts down `(period >> shift) + 1` CPU cycles a step, as Mesen2's Vrc6Pulse/Vrc6Saw\n * do. Output is the average over each sample of what the chip puts out, so a high note at a low\n * sample rate keeps its level.\n */\nexport class Vrc6Chip {\n private readonly cyclesPerSample: number;\n private readonly pulses: [Vrc6Pulse, Vrc6Pulse] = [Vrc6Chip.newPulse(), Vrc6Chip.newPulse()];\n private sawRate = 0;\n private sawPeriod = 0;\n private sawEnabled = false;\n private sawTimer = 1;\n private sawStep = 0;\n private sawAccumulator = 0;\n private halted = false;\n private shift = 0;\n\n private static newPulse(): Vrc6Pulse {\n return { volume: 0, duty: 0, constant: false, period: 0, enabled: false, timer: 1, step: 0 };\n }\n\n constructor(sampleRate: number) {\n this.cyclesPerSample = CPU_HZ / sampleRate;\n }\n\n /** A write to `$9000`–`$9003`, `$A000`–`$A002` or `$B000`–`$B002`. Returns false for any other address. */\n write(address: number, value: number): boolean {\n const v = value & 0xff;\n if (address === 0x9003) {\n this.halted = (v & 1) !== 0;\n this.shift = v & 4 ? 8 : v & 2 ? 4 : 0;\n return true;\n }\n if ((address >= 0x9000 && address <= 0x9002) || (address >= 0xa000 && address <= 0xa002)) {\n const p = this.pulses[address >> 12 === 0x9 ? 0 : 1];\n switch (address & 3) {\n case 0:\n p.volume = v & 0x0f;\n p.duty = (v >> 4) & 7;\n p.constant = (v & 0x80) !== 0;\n break;\n case 1:\n p.period = (p.period & 0xf00) | v;\n break;\n case 2:\n p.period = (p.period & 0x0ff) | ((v & 0x0f) << 8);\n p.enabled = (v & 0x80) !== 0;\n // Clearing E resets the duty step; the divider runs on.\n if (!p.enabled) p.step = 0;\n break;\n }\n return true;\n }\n if (address >= 0xb000 && address <= 0xb002) {\n switch (address & 3) {\n case 0:\n this.sawRate = v & 0x3f;\n break;\n case 1:\n this.sawPeriod = (this.sawPeriod & 0xf00) | v;\n break;\n case 2:\n this.sawPeriod = (this.sawPeriod & 0x0ff) | ((v & 0x0f) << 8);\n this.sawEnabled = (v & 0x80) !== 0;\n if (!this.sawEnabled) {\n this.sawStep = 0;\n this.sawAccumulator = 0;\n }\n break;\n }\n return true;\n }\n return false;\n }\n\n private static pulseLevel(p: Vrc6Pulse): number {\n if (!p.enabled) return 0;\n if (p.constant) return p.volume;\n return p.step <= p.duty ? p.volume : 0;\n }\n\n /**\n * Advance `count` samples, ADDING each channel's output to `outs[0]` (pulse 1), `outs[1]` (pulse\n * 2) and `outs[2]` (saw) — or, for a channel without a buffer of its own, to `outs[3]` if given —\n * from `offset`.\n */\n render(count: number, outs: readonly (Float64Array | undefined)[], offset = 0) {\n const cps = this.cyclesPerSample;\n const scale = VRC6_STEP / cps;\n const running = !this.halted;\n for (let c = 0; c < 2; c++) {\n const out = outs[c] ?? outs[3];\n const p = this.pulses[c];\n const reload = (p.period >> this.shift) + 1;\n // Not stepping, or stepping makes no difference: one level for the whole run.\n if (!running || !p.enabled || p.constant || p.volume === 0) {\n if (out) {\n const level = Vrc6Chip.pulseLevel(p) * VRC6_STEP;\n if (level !== 0) for (let k = 0; k < count; k++) out[offset + k] += level;\n }\n if (running && p.enabled) {\n // The duty step moves on all the same, for when the level comes back.\n const cycles = count * cps;\n if (cycles >= p.timer) {\n const steps = 1 + Math.floor((cycles - p.timer) / reload);\n p.step = (p.step + steps) & 15;\n p.timer = reload - ((cycles - p.timer) % reload);\n } else p.timer -= cycles;\n }\n continue;\n }\n for (let k = 0; k < count; k++) {\n let left = cps;\n let sum = 0;\n while (left >= p.timer) {\n sum += (p.step <= p.duty ? p.volume : 0) * p.timer;\n left -= p.timer;\n p.step = (p.step + 1) & 15;\n p.timer = reload;\n }\n sum += (p.step <= p.duty ? p.volume : 0) * left;\n p.timer -= left;\n if (out) out[offset + k] += sum * scale;\n }\n }\n {\n const out = outs[2] ?? outs[3];\n const reload = (this.sawPeriod >> this.shift) + 1;\n if (!running || !this.sawEnabled) {\n const level = this.sawEnabled ? (this.sawAccumulator >> 3) * VRC6_STEP : 0;\n if (out && level !== 0) for (let k = 0; k < count; k++) out[offset + k] += level;\n return;\n }\n for (let k = 0; k < count; k++) {\n let left = cps;\n let sum = 0;\n while (left >= this.sawTimer) {\n sum += (this.sawAccumulator >> 3) * this.sawTimer;\n left -= this.sawTimer;\n this.sawTimer = reload;\n // Fourteen steps a cycle: the accumulator grows on every other one and starts over on the 14th.\n this.sawStep = (this.sawStep + 1) % 14;\n if (this.sawStep === 0) this.sawAccumulator = 0;\n else if ((this.sawStep & 1) === 0) this.sawAccumulator = (this.sawAccumulator + this.sawRate) & 0xff;\n }\n sum += (this.sawAccumulator >> 3) * left;\n this.sawTimer -= left;\n if (out) out[offset + k] += sum * scale;\n }\n }\n }\n\n snapshot(): Vrc6Snapshot {\n const pulse = (p: Vrc6Pulse): Vrc6PulseSnapshot => ({\n period: p.period,\n volume: p.volume,\n duty: p.duty,\n constant: p.constant,\n enabled: p.enabled,\n });\n return {\n pulse: [pulse(this.pulses[0]), pulse(this.pulses[1])],\n saw: { period: this.sawPeriod, rate: this.sawRate, enabled: this.sawEnabled },\n halted: this.halted,\n shift: this.shift,\n };\n }\n}\n\n/** Hz of an FDS frequency register value. */\nexport const fdsHz = (frequency: number) => (CPU_HZ * frequency) / 4194304;\n\n/** Hz of an N163 channel, from its frequency, wave length and the number of channels on. */\nexport const n163Hz = (frequency: number, length: number, channels: number) =>\n (CPU_HZ * frequency) / (15 * 65536 * channels * length);\n\n/** Hz of a VRC6 pulse period (with `$9003`'s shift, if any): 16 steps of `(period >> shift) + 1` cycles. */\nexport const vrc6PulseHz = (period: number, shift = 0) => CPU_HZ / (16 * ((period >> shift) + 1));\n\n/** Hz of the VRC6 sawtooth's period (with `$9003`'s shift, if any): 14 steps of `(period >> shift) + 1` cycles. */\nexport const vrc6SawHz = (period: number, shift = 0) => CPU_HZ / (14 * ((period >> shift) + 1));\n"]}
package/dist/index.d.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  export { CPU_HZ, DMC_PERIODS, DUTY_SEQUENCES, FRAME_HZ, LENGTH_TABLE, NOISE_PERIODS, QUARTER_FRAME_HZ, TRIANGLE_STEPS, } from './constants.js';
15
15
  export { Apu, type ApuChipOptions, type ApuMemory, type ApuSnapshot, type ChannelBuffers, } from './chip.js';
16
16
  export { mixApu, OutputFilters } from './mixer.js';
17
- export { FdsChip, N163Chip, fdsHz, n163Hz, type FdsSnapshot, type N163ChannelSnapshot, type N163Snapshot, } from './expansion.js';
17
+ export { FdsChip, N163Chip, Vrc6Chip, fdsHz, n163Hz, vrc6PulseHz, vrc6SawHz, type FdsSnapshot, type N163ChannelSnapshot, type N163Snapshot, type Vrc6PulseSnapshot, type Vrc6Snapshot, } from './expansion.js';
18
18
  export { SWEEP_HZ, decodeSweep, sweepMutes, sweepTarget, sweepTrace, type SweepConfig, } from './sweep.js';
19
19
  export { expansionOf, renderWrites, type Click, type RegisterWrite, type Render, type RenderOptions, } from './render.js';
20
20
  export { bendAt, EXPANSION_CHANNELS, levelAt, notesToWrites, renderNotes, sampleMemory, sampleSeconds, type DmcSample, type SampleRow, type ApuInput, type ApuOptions, type ApuRender, type BendCurve, type LevelCurve, type DrumRow, type PitchedRow, secondsToTick, tickToSeconds, type TempoChange, } from './notes.js';
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@
14
14
  export { CPU_HZ, DMC_PERIODS, DUTY_SEQUENCES, FRAME_HZ, LENGTH_TABLE, NOISE_PERIODS, QUARTER_FRAME_HZ, TRIANGLE_STEPS, } from './constants.js';
15
15
  export { Apu, } from './chip.js';
16
16
  export { mixApu, OutputFilters } from './mixer.js';
17
- export { FdsChip, N163Chip, fdsHz, n163Hz, } from './expansion.js';
17
+ export { FdsChip, N163Chip, Vrc6Chip, fdsHz, n163Hz, vrc6PulseHz, vrc6SawHz, } from './expansion.js';
18
18
  export { SWEEP_HZ, decodeSweep, sweepMutes, sweepTarget, sweepTrace, } from './sweep.js';
19
19
  export { expansionOf, renderWrites, } from './render.js';
20
20
  export { bendAt, EXPANSION_CHANNELS, levelAt, notesToWrites, renderNotes, sampleMemory, sampleSeconds, secondsToTick, tickToSeconds, } from './notes.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,MAAM,EACN,WAAW,EACX,cAAc,EACd,QAAQ,EACR,YAAY,EACZ,aAAa,EACb,gBAAgB,EAChB,cAAc,GACf,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,GAAG,GAKJ,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EACL,OAAO,EACP,QAAQ,EACR,KAAK,EACL,MAAM,GAIP,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,QAAQ,EACR,WAAW,EACX,UAAU,EACV,WAAW,EACX,UAAU,GAEX,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,WAAW,EACX,YAAY,GAKb,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,MAAM,EACN,kBAAkB,EAClB,OAAO,EACP,aAAa,EACb,WAAW,EACX,YAAY,EACZ,aAAa,EAUb,aAAa,EACb,aAAa,GAEd,MAAM,YAAY,CAAC","sourcesContent":["/**\n * @xrom/apu — the NES sound chip (2A03 APU) in TypeScript.\n *\n * Two layers, usable separately:\n *\n * - **The chip.** `renderWrites(writes, seconds)` plays a list of register\n * writes — `{ time, address: 0x4000..0x4017, value }` — and returns samples.\n * Every NES game's music reaches the speaker as writes like these, so this\n * plays any game's music once its writes are known (from an emulator trace,\n * say). `Apu` is the same chip one sample at a time, for live use.\n * - **The note adapter.** `renderNotes(input)` takes music already decoded into\n * notes and writes what a driver would have written to sound them.\n */\n\nexport {\n CPU_HZ,\n DMC_PERIODS,\n DUTY_SEQUENCES,\n FRAME_HZ,\n LENGTH_TABLE,\n NOISE_PERIODS,\n QUARTER_FRAME_HZ,\n TRIANGLE_STEPS,\n} from './constants.js';\nexport {\n Apu,\n type ApuChipOptions,\n type ApuMemory,\n type ApuSnapshot,\n type ChannelBuffers,\n} from './chip.js';\nexport { mixApu, OutputFilters } from './mixer.js';\nexport {\n FdsChip,\n N163Chip,\n fdsHz,\n n163Hz,\n type FdsSnapshot,\n type N163ChannelSnapshot,\n type N163Snapshot,\n} from './expansion.js';\nexport {\n SWEEP_HZ,\n decodeSweep,\n sweepMutes,\n sweepTarget,\n sweepTrace,\n type SweepConfig,\n} from './sweep.js';\nexport {\n expansionOf,\n renderWrites,\n type Click,\n type RegisterWrite,\n type Render,\n type RenderOptions,\n} from './render.js';\nexport {\n bendAt,\n EXPANSION_CHANNELS,\n levelAt,\n notesToWrites,\n renderNotes,\n sampleMemory,\n sampleSeconds,\n type DmcSample,\n type SampleRow,\n type ApuInput,\n type ApuOptions,\n type ApuRender,\n type BendCurve,\n type LevelCurve,\n type DrumRow,\n type PitchedRow,\n secondsToTick,\n tickToSeconds,\n type TempoChange,\n} from './notes.js';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,MAAM,EACN,WAAW,EACX,cAAc,EACd,QAAQ,EACR,YAAY,EACZ,aAAa,EACb,gBAAgB,EAChB,cAAc,GACf,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,GAAG,GAKJ,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EACL,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,KAAK,EACL,MAAM,EACN,WAAW,EACX,SAAS,GAMV,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,QAAQ,EACR,WAAW,EACX,UAAU,EACV,WAAW,EACX,UAAU,GAEX,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,WAAW,EACX,YAAY,GAKb,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,MAAM,EACN,kBAAkB,EAClB,OAAO,EACP,aAAa,EACb,WAAW,EACX,YAAY,EACZ,aAAa,EAUb,aAAa,EACb,aAAa,GAEd,MAAM,YAAY,CAAC","sourcesContent":["/**\n * @xrom/apu — the NES sound chip (2A03 APU) in TypeScript.\n *\n * Two layers, usable separately:\n *\n * - **The chip.** `renderWrites(writes, seconds)` plays a list of register\n * writes — `{ time, address: 0x4000..0x4017, value }` — and returns samples.\n * Every NES game's music reaches the speaker as writes like these, so this\n * plays any game's music once its writes are known (from an emulator trace,\n * say). `Apu` is the same chip one sample at a time, for live use.\n * - **The note adapter.** `renderNotes(input)` takes music already decoded into\n * notes and writes what a driver would have written to sound them.\n */\n\nexport {\n CPU_HZ,\n DMC_PERIODS,\n DUTY_SEQUENCES,\n FRAME_HZ,\n LENGTH_TABLE,\n NOISE_PERIODS,\n QUARTER_FRAME_HZ,\n TRIANGLE_STEPS,\n} from './constants.js';\nexport {\n Apu,\n type ApuChipOptions,\n type ApuMemory,\n type ApuSnapshot,\n type ChannelBuffers,\n} from './chip.js';\nexport { mixApu, OutputFilters } from './mixer.js';\nexport {\n FdsChip,\n N163Chip,\n Vrc6Chip,\n fdsHz,\n n163Hz,\n vrc6PulseHz,\n vrc6SawHz,\n type FdsSnapshot,\n type N163ChannelSnapshot,\n type N163Snapshot,\n type Vrc6PulseSnapshot,\n type Vrc6Snapshot,\n} from './expansion.js';\nexport {\n SWEEP_HZ,\n decodeSweep,\n sweepMutes,\n sweepTarget,\n sweepTrace,\n type SweepConfig,\n} from './sweep.js';\nexport {\n expansionOf,\n renderWrites,\n type Click,\n type RegisterWrite,\n type Render,\n type RenderOptions,\n} from './render.js';\nexport {\n bendAt,\n EXPANSION_CHANNELS,\n levelAt,\n notesToWrites,\n renderNotes,\n sampleMemory,\n sampleSeconds,\n type DmcSample,\n type SampleRow,\n type ApuInput,\n type ApuOptions,\n type ApuRender,\n type BendCurve,\n type LevelCurve,\n type DrumRow,\n type PitchedRow,\n secondsToTick,\n tickToSeconds,\n type TempoChange,\n} from './notes.js';\n"]}
package/dist/notes.d.ts CHANGED
@@ -39,6 +39,11 @@ import { type RegisterWrite, type RenderOptions } from './render.js';
39
39
  * those `period` is the frequency in hundredths of a hertz (their registers depend on the wave's
40
40
  * length and the chip's channel count, which the adapter chooses itself), `volume` is 0..15, and
41
41
  * `waveIndex` (the 14th field) points into `ApuInput.waves`: the waveform the note plays.
42
+ *
43
+ * 14 and 15 are the VRC6's pulses, 16 its sawtooth. There too `period` is hundredths of a hertz
44
+ * and `volume` 0..15; on a pulse `duty` is the chip's 0..7 (high for duty + 1 of 16 steps), or 8
45
+ * for its mode bit — the volume put out flat; on the saw `volume` stands for the accumulator rate
46
+ * on a 0..15 scale, written as rate = round(volume · 42 / 15) (42 is the loudest clean saw).
42
47
  */
43
48
  export type PitchedRow = readonly [
44
49
  number,
@@ -56,10 +61,11 @@ export type PitchedRow = readonly [
56
61
  number?,
57
62
  number?
58
63
  ];
59
- /** Pitched-row channels past the 2A03's: the FDS, then the N163's eight. */
64
+ /** Pitched-row channels past the 2A03's: the FDS, the N163's eight, then the VRC6's pulse, pulse, saw. */
60
65
  export declare const EXPANSION_CHANNELS: {
61
66
  readonly fds: 5;
62
67
  readonly n163: readonly [6, 7, 8, 9, 10, 11, 12, 13];
68
+ readonly vrc6: readonly [14, 15, 16];
63
69
  };
64
70
  /**
65
71
  * A level curve: `[position 0..1, level 0..15]` at each change of level, in order. The level holds
@@ -126,6 +132,16 @@ export interface ApuInput {
126
132
  * speeds its opening up this way — whose ticks are not all the same length.
127
133
  */
128
134
  tempo?: readonly TempoChange[];
135
+ /**
136
+ * The pulses' duty sequencers left running from note to note: a note's `$4003`/`$4007` is
137
+ * written only when its high byte differs from the last one written, as drivers that write the
138
+ * high byte only on a change do (Konami's Yie Ar Kung-Fu). The write restarts the sequencer, so
139
+ * by default — every note, as Battletoads' driver writes it — a repeated note against the same
140
+ * note held on the other pulse lands at whatever phase its start gives, and in opposite phase the
141
+ * two cancel: the note goes quiet. Only where the write does nothing else: a constant level with
142
+ * the length counter halted (no envelope to restart, no length to reload).
143
+ */
144
+ keepPulsePhase?: boolean;
129
145
  }
130
146
  export interface TempoChange {
131
147
  tick: number;
package/dist/notes.js CHANGED
@@ -25,8 +25,8 @@
25
25
  */
26
26
  import { CPU_HZ, DMC_PERIODS, FRAME_HZ, LENGTH_TABLE } from './constants.js';
27
27
  import { renderWrites } from './render.js';
28
- /** Pitched-row channels past the 2A03's: the FDS, then the N163's eight. */
29
- export const EXPANSION_CHANNELS = { fds: 5, n163: [6, 7, 8, 9, 10, 11, 12, 13] };
28
+ /** Pitched-row channels past the 2A03's: the FDS, the N163's eight, then the VRC6's pulse, pulse, saw. */
29
+ export const EXPANSION_CHANNELS = { fds: 5, n163: [6, 7, 8, 9, 10, 11, 12, 13], vrc6: [14, 15, 16] };
30
30
  /** The level a curve holds at `position`: the last point at or before it. */
31
31
  export function levelAt(curve, position) {
32
32
  let level = curve[0]?.[1] ?? 0;
@@ -193,6 +193,11 @@ export function notesToWrites(input, lead = 0) {
193
193
  // Pulses.
194
194
  for (const channel of [0, 1]) {
195
195
  const base = 0x4000 + channel * 4;
196
+ /**
197
+ * The high byte last written to `$4003`/`$4007`, for `keepPulsePhase` — or -1 where the next
198
+ * note must write it anyway: before the first, or after a note whose length counter ran.
199
+ */
200
+ let lastHigh = -1;
196
201
  const voices = voicesOf(input.pitched,
197
202
  // Period 0 would be a divide by zero on the chip too; a row with none is
198
203
  // a rest, not a note.
@@ -210,7 +215,11 @@ export function notesToWrites(input, lead = 0) {
210
215
  put(voice.start, base, reg0(level(0)));
211
216
  put(voice.start, base + 1, sweep !== undefined && sweep >= 0 ? sweep : 0x08);
212
217
  put(voice.start, base + 2, period & 0xff);
213
- put(voice.start, base + 3, (bits.load << 3) | ((period >> 8) & 7));
218
+ const high = (period >> 8) & 7;
219
+ const restart = !input.keepPulsePhase || !bits.constant || !bits.halt || high !== lastHigh;
220
+ if (restart)
221
+ put(voice.start, base + 3, (bits.load << 3) | high);
222
+ lastHigh = bits.constant && bits.halt ? high : -1;
214
223
  const curve = bendIndex >= 0 ? (bends[bendIndex] ?? null) : null;
215
224
  const ramps = bits.constant && (levelCurve !== null || volume !== volumeEnd);
216
225
  if (curve || ramps) {
@@ -231,8 +240,11 @@ export function notesToWrites(input, lead = 0) {
231
240
  put(time, base + 2, now & 0xff);
232
241
  // The high byte only when it changes, as drivers do — writing it
233
242
  // restarts the sequencer, which is an audible click.
234
- if (now >> 8 !== lastPeriod >> 8)
243
+ if (now >> 8 !== lastPeriod >> 8) {
235
244
  put(time, base + 3, (bits.load << 3) | (now >> 8));
245
+ if (lastHigh >= 0)
246
+ lastHigh = now >> 8;
247
+ }
236
248
  }
237
249
  lastPeriod = now;
238
250
  }
@@ -364,7 +376,7 @@ export function notesToWrites(input, lead = 0) {
364
376
  }
365
377
  const hzOf = (row) => row[5] / 100;
366
378
  /**
367
- * The expansion channels' notes as writes: what a driver for the FDS or the N163 would write to
379
+ * The expansion channels' notes as writes: what a driver for the FDS, the VRC6 or the N163 would write to
368
380
  * sound them — the waveform when it changes, then the frequency and level, and once a frame the
369
381
  * level while it ramps and the frequency while it bends.
370
382
  */
@@ -431,6 +443,59 @@ function expansionWrites(input, lead, voicesOf, frames, put) {
431
443
  put(voice.end, 0x4080, 0x80);
432
444
  });
433
445
  }
446
+ // VRC6: two pulses and the saw, each its three registers; the period counts CPU cycles.
447
+ {
448
+ let started = false;
449
+ EXPANSION_CHANNELS.vrc6.forEach((channel, k) => {
450
+ const voices = voicesOf(input.pitched, ((row) => row[3] === channel && row[5] > 0));
451
+ if (voices.length === 0)
452
+ return;
453
+ if (!started)
454
+ put(0, 0x9003, 0x00); // running, no frequency shift
455
+ started = true;
456
+ const base = 0x9000 + k * 0x1000;
457
+ const saw = k === 2;
458
+ const periodOf = (hz) => Math.min(0xfff, Math.max(0, Math.round(CPU_HZ / ((saw ? 14 : 16) * hz)) - 1));
459
+ voices.forEach((voice, i) => {
460
+ const row = voice.row;
461
+ const level = levelAtOf(row);
462
+ const control = saw
463
+ ? (l) => Math.min(0x3f, Math.round((l * 42) / 15))
464
+ : (l) => (row[6] >= 8 ? 0x80 : (Math.max(0, row[6]) & 7) << 4) | l;
465
+ const period = periodOf(hzOf(row));
466
+ put(voice.start, base, control(level(0)));
467
+ put(voice.start, base + 1, period & 0xff);
468
+ put(voice.start, base + 2, 0x80 | (period >> 8));
469
+ const curve = curveOf(row);
470
+ const ramps = levelsOf(row) !== null || row[4] !== row[7];
471
+ if (curve || ramps) {
472
+ let lastLevel = level(0);
473
+ let lastPeriod = period;
474
+ for (const { time, position } of frames(voice.start, voice.end)) {
475
+ if (ramps) {
476
+ const now = level(position);
477
+ if (now !== lastLevel)
478
+ put(time, base, control(now));
479
+ lastLevel = now;
480
+ }
481
+ if (curve) {
482
+ const now = periodOf(hzOf(row) * Math.pow(2, bendAt(curve, position) / 12));
483
+ if (now !== lastPeriod) {
484
+ put(time, base + 1, now & 0xff);
485
+ // With E kept set: clearing it would restart the wave.
486
+ if (now >> 8 !== lastPeriod >> 8)
487
+ put(time, base + 2, 0x80 | (now >> 8));
488
+ }
489
+ lastPeriod = now;
490
+ }
491
+ }
492
+ }
493
+ const next = voices[i + 1];
494
+ if (!next || next.start > voice.end + 1e-9)
495
+ put(voice.end, base + 2, period >> 8);
496
+ });
497
+ });
498
+ }
434
499
  // N163: as many channels on as the piece uses, each with its own stretch of the chip's RAM.
435
500
  const n163Voices = EXPANSION_CHANNELS.n163.map((channel) => voicesOf(input.pitched, ((row) => row[3] === channel && row[5] > 0)));
436
501
  const used = n163Voices.reduce((most, voices, k) => (voices.length > 0 ? k + 1 : most), 0);