@xromdev/apu 0.4.1 → 0.4.2

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.
@@ -101,12 +101,14 @@ export declare class N163Chip {
101
101
  write(address: number, value: number): boolean;
102
102
  /** A read of the data port, as the CPU makes it — auto-increment included. */
103
103
  read(): number;
104
+ /** The address port as it stands — the next RAM byte the data port reaches, with bit 7 for auto-increment. */
105
+ get port(): number;
104
106
  get channels(): number;
105
107
  /**
106
- * A channel's eight bytes: frequency low, middle, and high two bits with the wave length above
107
- * them; three bytes of phase; the wave's address; the volume. (Read off what Namco's own drivers
108
- * write — Erika to Satoru and Mappy Kids both put `$E0`/`$F0`, a 32- or 16-sample wave, in the
109
- * third byte.)
108
+ * A channel's eight bytes, interleaved as on the chip: frequency low, phase low, frequency
109
+ * middle, phase middle, the frequency's high two bits with the wave length above them, phase
110
+ * high, the wave's address, the volume. (Namco's drivers write the frequency bytes and step over
111
+ * the phase ones by READING the data port — auto-increment counts reads too.)
110
112
  */
111
113
  private channel;
112
114
  private sample;
package/dist/expansion.js CHANGED
@@ -263,21 +263,25 @@ export class N163Chip {
263
263
  this.address = (this.address + 1) & 0x7f;
264
264
  return v;
265
265
  }
266
+ /** The address port as it stands — the next RAM byte the data port reaches, with bit 7 for auto-increment. */
267
+ get port() {
268
+ return this.address | (this.autoIncrement ? 0x80 : 0);
269
+ }
266
270
  get channels() {
267
271
  return ((this.ram[0x7f] >> 4) & 7) + 1;
268
272
  }
269
273
  /**
270
- * A channel's eight bytes: frequency low, middle, and high two bits with the wave length above
271
- * them; three bytes of phase; the wave's address; the volume. (Read off what Namco's own drivers
272
- * write — Erika to Satoru and Mappy Kids both put `$E0`/`$F0`, a 32- or 16-sample wave, in the
273
- * third byte.)
274
+ * A channel's eight bytes, interleaved as on the chip: frequency low, phase low, frequency
275
+ * middle, phase middle, the frequency's high two bits with the wave length above them, phase
276
+ * high, the wave's address, the volume. (Namco's drivers write the frequency bytes and step over
277
+ * the phase ones by READING the data port — auto-increment counts reads too.)
274
278
  */
275
279
  channel(slot) {
276
280
  const base = 0x40 + slot * 8;
277
281
  const r = this.ram;
278
282
  return {
279
- frequency: r[base] | (r[base + 1] << 8) | ((r[base + 2] & 3) << 16),
280
- length: 256 - (r[base + 2] & 0xfc),
283
+ frequency: r[base] | (r[base + 2] << 8) | ((r[base + 4] & 3) << 16),
284
+ length: 256 - (r[base + 4] & 0xfc),
281
285
  waveAddress: r[base + 6],
282
286
  volume: r[base + 7] & 0x0f,
283
287
  };
@@ -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,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,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAkB7C,MAAM,OAAO,OAAO;IAiClB,YAAY,UAAkB;QA/BrB,SAAI,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;QAClB,aAAQ,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;QACvC,gBAAW,GAAG,CAAC,CAAC;QAChB,cAAS,GAAG,CAAC,CAAC;QACd,aAAQ,GAAG,IAAI,CAAC;QAChB,iBAAY,GAAG,IAAI,CAAC;QACpB,cAAS,GAAG,KAAK,CAAC;QAClB,WAAM,GAA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AgB,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 get channels(): number {\n return ((this.ram[0x7f] >> 4) & 7) + 1;\n }\n\n /**\n * A channel's eight bytes: frequency low, middle, and high two bits with the wave length above\n * them; three bytes of phase; the wave's address; the volume. (Read off what Namco's own drivers\n * write — Erika to Satoru and Mappy Kids both put `$E0`/`$F0`, a 32- or 16-sample wave, in the\n * third byte.)\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 + 1] << 8) | ((r[base + 2] & 3) << 16),\n length: 256 - (r[base + 2] & 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;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAExC,8FAA8F;AAC9F,MAAM,QAAQ,GAAG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AC,GAAG,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"]}
package/dist/notes.js CHANGED
@@ -500,10 +500,10 @@ function expansionWrites(input, lead, voicesOf, frames, put) {
500
500
  const freqOf = (hz) => Math.min(0x3ffff, Math.max(1, Math.round((hz * 15 * 65536 * count * length) / CPU_HZ)));
501
501
  const regs = (freq, volume) => [
502
502
  freq & 0xff,
503
- (freq >> 8) & 0xff,
504
- ((256 - length) & 0xfc) | ((freq >> 16) & 3),
505
503
  0,
504
+ (freq >> 8) & 0xff,
506
505
  0,
506
+ ((256 - length) & 0xfc) | ((freq >> 16) & 3),
507
507
  0,
508
508
  start & 0xff,
509
509
  volumeByte(volume),
@@ -521,7 +521,9 @@ function expansionWrites(input, lead, voicesOf, frames, put) {
521
521
  const nowFreq = curve ? freqOf(hzOf(row) * Math.pow(2, bendAt(curve, position) / 12)) : lastFreq;
522
522
  if (nowFreq !== lastFreq) {
523
523
  // The frequency bytes alone, not the phase after them: that is the chip's running count.
524
- ramWrite(time, base, [nowFreq & 0xff, (nowFreq >> 8) & 0xff, ((256 - length) & 0xfc) | ((nowFreq >> 16) & 3)]);
524
+ ramWrite(time, base, [nowFreq & 0xff]);
525
+ ramWrite(time, base + 2, [(nowFreq >> 8) & 0xff]);
526
+ ramWrite(time, base + 4, [((256 - length) & 0xfc) | ((nowFreq >> 16) & 3)]);
525
527
  }
526
528
  if (nowLevel !== lastLevel)
527
529
  ramWrite(time, base + 7, [volumeByte(nowLevel)]);
package/dist/notes.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"notes.js","sourceRoot":"","sources":["../src/notes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC7E,OAAO,EAAE,YAAY,EAAsD,MAAM,aAAa,CAAC;AAmC/F,4EAA4E;AAC5E,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,GAAG,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAW,CAAC;AAS1F,6EAA6E;AAC7E,MAAM,UAAU,OAAO,CAAC,KAAiB,EAAE,QAAgB;IACzD,IAAI,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IAC/B,KAAK,MAAM,CAAC,EAAE,EAAE,KAAK,CAAC,IAAI,KAAK,EAAE,CAAC;QAChC,IAAI,EAAE,GAAG,QAAQ,GAAG,IAAI;YAAE,MAAM;QAChC,KAAK,GAAG,KAAK,CAAC;IAChB,CAAC;IACD,OAA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aAAa,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,IAAI,CAAC,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;QACxF,OAAO,EAAE,IAAI,GAAG,GAAG;QACnB,IAAI,EAAE,MAAM,CAAC,IAAI;KAClB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Notes in, register writes out — the adapter between a decoded score and the\n * chip.\n *\n * A music driver's job is to turn its own data into register writes, once a\n * frame. When a game's music has already been decoded into notes (start, length,\n * period, volume, duty, and how each of those moves), this plays the driver's\n * part: it writes what a driver would have written to sound those notes, and\n * `renderWrites` does the rest. So the chip never learns what a note is, and\n * anything the adapter gets wrong is visible as a register write rather than\n * hidden inside a synth.\n *\n * The note shape is the one xrom.dev exports for Battletoads, but nothing in it\n * is that game's: a tick is whatever the caller says it is in seconds.\n *\n * What it writes, per note:\n * - at the start, the channel's full register set — which on a pulse restarts\n * the duty sequencer and the envelope and reloads the length counter,\n * exactly as the driver's own `$4003` write does;\n * - once a frame after that, the level while it ramps and the period while it\n * bends, as whole numbers, because the registers hold whole numbers — so a\n * fade is a staircase at 60 Hz, as it is on the console;\n * - at the end, silence — unless the next note on the channel starts at the\n * same moment.\n */\n\nimport { CPU_HZ, DMC_PERIODS, FRAME_HZ, LENGTH_TABLE } from './constants.js';\nimport { renderWrites, type Click, type RegisterWrite, type RenderOptions } from './render.js';\n\n/**\n * `[midi, startTick, durationTicks, channel, volume, period, duty,\n * volumeEnd, lengthTicks, bendIndex, envelope, sweep, levelIndex]` — `lengthTicks` counts at\n * 120 Hz and 0 means unlimited; `bendIndex` points into `ApuInput.bends`, or is\n * -1; `envelope` is the low five bits of `$4000` when the chip's own envelope\n * runs (period, and bit 4 for loop), or -1 for constant volume; `sweep` is the\n * `$4001` byte, or -1/absent when the data has none; `levelIndex`, on a pulse, points into\n * `ApuInput.levels` for a level that does not go in a straight line from `volume` to `volumeEnd`,\n * or is -1/absent.\n *\n * Channels 0..2 are the 2A03's pulses and triangle. 5 is the Disk System's wave channel (FDS) and\n * 6..13 the N163's channels in the order the chip switches them on — see `EXPANSION_CHANNELS`. On\n * those `period` is the frequency in hundredths of a hertz (their registers depend on the wave's\n * length and the chip's channel count, which the adapter chooses itself), `volume` is 0..15, and\n * `waveIndex` (the 14th field) points into `ApuInput.waves`: the waveform the note plays.\n */\nexport type PitchedRow = readonly [\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number?,\n number?,\n number?,\n number?,\n];\n\n/** Pitched-row channels past the 2A03's: the FDS, then the N163's eight. */\nexport const EXPANSION_CHANNELS = { fds: 5, n163: [6, 7, 8, 9, 10, 11, 12, 13] } as const;\n\n\n/**\n * A level curve: `[position 0..1, level 0..15]` at each change of level, in order. The level holds\n * from one point to the next — a driver writes whole levels, a frame at a time.\n */\nexport type LevelCurve = readonly (readonly [number, number])[];\n\n/** The level a curve holds at `position`: the last point at or before it. */\nexport function levelAt(curve: LevelCurve, position: number): number {\n let level = curve[0]?.[1] ?? 0;\n for (const [at, value] of curve) {\n if (at > position + 1e-9) break;\n level = value;\n }\n return level;\n}\n\n/** A pitch curve: `[position 0..1, semitones]`, in order. */\nexport type BendCurve = readonly (readonly [number, number])[];\n\n/**\n * `[periodIndex, startTick, durationTicks, volume, volumeEnd, lengthTicks,\n * envelope, levelIndex]` — a noise-channel note. `periodIndex` is the low nibble of `$400E`;\n * `levelIndex` points into `ApuInput.levels`, as a pulse row's does, or is -1/absent.\n */\nexport type DrumRow = readonly [number, number, number, number, number, number, number?, number?];\n\n/**\n * `[sampleIndex, startTick, durationTicks, rate, loop, level]` — a sample struck\n * on the DMC: `sampleIndex` into `ApuInput.samples`, `rate` the low nibble of\n * `$4010`, `loop` 1 to repeat it until the row ends, `level` the 7-bit value a\n * driver loads into `$4011` before it (the jump is part of the sound — a kick's\n * thump), or -1/absent for none. It plays to the end of its bytes or of the\n * row, whichever comes first.\n */\nexport type SampleRow = readonly [number, number, number, number, number, number?];\n\n/**\n * A DMC sample: the 1-bit delta bytes the channel reads, and where it reads them\n * — `$C000` + 64·n, as `$4012` can point. The bytes are the cartridge's own.\n */\nexport interface DmcSample {\n address: number;\n bytes: readonly number[] | Uint8Array;\n}\n\nexport interface ApuInput {\n pitched: readonly PitchedRow[];\n drums: readonly DrumRow[];\n /** Samples struck on the DMC, pointing into `samples`. */\n hits?: readonly SampleRow[];\n /** The samples the hits play. */\n samples?: readonly DmcSample[];\n /** Pitch curves the notes point at. Shared, because the shapes repeat. */\n bends?: readonly BendCurve[];\n /** Level curves the pulse and noise notes point at — see `PitchedRow`'s `levelIndex`. Shared like `bends`. */\n levels?: readonly LevelCurve[];\n /**\n * Waveforms the expansion notes play — see `PitchedRow`'s `waveIndex`: 64 samples 0..63 for the\n * FDS, a multiple of 4 samples 0..15 for an N163 channel.\n */\n waves?: readonly (readonly number[])[];\n /** Seconds per tick. */\n secondsPerTick: number;\n /** Length of the piece in ticks. */\n totalTicks: number;\n /**\n * Where the repeat starts, in ticks. Not always 0: a driver's first ticks are\n * often one-time setup, so a track that loops on the whole buffer replays its\n * intro every time round. Absent means the piece does not loop.\n */\n loopStart?: number;\n /**\n * Changes of tempo, as `{ tick, secondsPerTick }` in tick order: from `tick`\n * on, a tick lasts `secondsPerTick`. Before the first change it is the\n * input's own `secondsPerTick`. For drivers with a tempo command — Battletoads\n * speeds its opening up this way — whose ticks are not all the same length.\n */\n tempo?: readonly TempoChange[];\n}\n\nexport interface TempoChange {\n tick: number;\n secondsPerTick: number;\n}\n\n/**\n * Seconds from the start to `tick`, through the tempo changes. With none it is\n * exactly `tick * secondsPerTick` — the same float, so a piece without changes\n * renders as it always has.\n */\nexport function tickToSeconds(input: Pick<ApuInput, 'secondsPerTick' | 'tempo'>, tick: number): number {\n const changes = input.tempo;\n if (!changes || changes.length === 0) return tick * input.secondsPerTick;\n let seconds = 0;\n let from = 0;\n let spt = input.secondsPerTick;\n for (const change of changes) {\n if (change.tick >= tick) break;\n seconds += (change.tick - from) * spt;\n from = change.tick;\n spt = change.secondsPerTick;\n }\n return seconds + (tick - from) * spt;\n}\n\n/** The tick at `seconds` — the inverse of `tickToSeconds`, fractional. */\nexport function secondsToTick(input: Pick<ApuInput, 'secondsPerTick' | 'tempo'>, seconds: number): number {\n const changes = input.tempo;\n if (!changes || changes.length === 0) return seconds / input.secondsPerTick;\n let at = 0;\n let from = 0;\n let spt = input.secondsPerTick;\n for (const change of changes) {\n const end = at + (change.tick - from) * spt;\n if (end >= seconds) break;\n at = end;\n from = change.tick;\n spt = change.secondsPerTick;\n }\n return from + (seconds - at) / spt;\n}\n\nexport interface ApuOptions extends Omit<RenderOptions, 'clicks' | 'tail'> {\n /** Seconds of silence before the first note. */\n lead?: number;\n /** Click on every `metronome` ticks, loud on every fourth. 0 is off. */\n metronome?: number;\n}\n\nexport interface ApuRender {\n samples: Float32Array;\n sampleRate: number;\n /** Seconds of silence before tick 0 — what the caller asked for as `lead`. */\n lead: number;\n /** Length of the whole buffer, tail included. */\n duration: number;\n /**\n * Where the music itself ends, in seconds — the loop point. The buffer runs a\n * little longer so the filters can ring out; looping on the buffer would play\n * that tail as a gap every time round.\n */\n loopEnd: number;\n /** Where the repeat starts, in seconds — the other end of the seam. */\n loopStart: number;\n /** Loudest absolute sample, before clamping. */\n peak: number;\n}\n\n/**\n * Semitones at `position` through a note, straight-line between the curve's own\n * points; outside it, the nearest end.\n */\nexport function bendAt(curve: BendCurve, position: number): number {\n if (curve.length === 0) return 0;\n if (position <= curve[0][0]) return curve[0][1];\n for (let i = 1; i < curve.length; i++) {\n const [x1, y1] = curve[i];\n if (position <= x1) {\n const [x0, y0] = curve[i - 1];\n const span = x1 - x0;\n return span <= 0 ? y1 : y0 + ((y1 - y0) * (position - x0)) / span;\n }\n }\n return curve[curve.length - 1][1];\n}\n\n/** Length-counter load → the index `$4003`'s top five bits must hold for it. */\nconst lengthIndex = (halfFrames: number) => {\n const index = LENGTH_TABLE.indexOf(halfFrames as (typeof LENGTH_TABLE)[number]);\n if (index < 0) throw new Error(`no length-table entry loads ${halfFrames} half-frames`);\n return index;\n};\n\n/** The longest load, 254 half-frames (2.1 s) — for a note with no counter that cannot halt it. */\nconst LONGEST = 1;\n\n/** The `$4015` value: pulses and noise always on; the triangle toggled to end its notes. */\nconst enables = (triangle: boolean) => 0x0b | (triangle ? 0x04 : 0);\n\n/** Seconds a sample of `length` bytes takes at `$4010` rate `rate`. */\nexport const sampleSeconds = (length: number, rate: number) =>\n (length * 8 * DMC_PERIODS[rate & 0x0f]) / CPU_HZ;\n\n/**\n * The bytes `$4013` makes the DMC read: 16·n + 1. A sample is stored that long;\n * one that is not is read to the next length the register can say.\n */\nconst lengthCode = (bytes: number) => Math.max(0, Math.min(255, Math.ceil((bytes - 1) / 16)));\n\n/**\n * The cartridge memory the DMC reads, from the samples a piece holds: each laid\n * at its own address, the rest zero. For `renderWrites`' `memory`.\n */\nexport function sampleMemory(samples: readonly DmcSample[]): Uint8Array {\n const memory = new Uint8Array(0x8000);\n for (const sample of samples) {\n const at = sample.address - 0x8000;\n for (let i = 0; i < sample.bytes.length && at + i < memory.length; i++) memory[at + i] = sample.bytes[i];\n }\n return memory;\n}\n\n/** A register value can only hold whole numbers; a period outside 11 bits is not one the chip has. */\nconst toPeriod = (value: number) => Math.min(0x7ff, Math.max(0, Math.round(value)));\n\ninterface Voice {\n start: number;\n end: number;\n row: PitchedRow | DrumRow;\n}\n\n/**\n * The bits `$4000`/`$400C` share, from a row's envelope and length counter.\n *\n * Bit 5 is one bit with two jobs — it halts the length counter AND loops the\n * envelope — so a note that wants its envelope to decay once cannot also have\n * an unlimited counter. The rows that ask for both (`lengthTicks` 0 with a\n * one-shot envelope) get the longest load the table has instead, which outlasts\n * any note the envelope has not already silenced.\n */\nfunction controlBits(envelope: number, lengthTicks: number) {\n if (envelope >= 0) {\n const loop = (envelope & 0x10) !== 0;\n return {\n halt: loop,\n load: lengthTicks > 0 ? lengthIndex(lengthTicks) : LONGEST,\n low: envelope & 0x0f,\n constant: false,\n };\n }\n return {\n halt: lengthTicks === 0,\n load: lengthTicks > 0 ? lengthIndex(lengthTicks) : 0,\n low: 0,\n constant: true,\n };\n}\n\n/** Frame moments inside a note, after its start: when a driver would next touch it. */\nfunction* frames(start: number, end: number) {\n for (let k = 1; ; k++) {\n const time = start + k / FRAME_HZ;\n if (time >= end) return;\n yield { time, position: (time - start) / (end - start) };\n }\n}\n\n/**\n * The writes that play `input`, as a driver would make them.\n *\n * @param lead seconds of silence before tick 0\n */\nexport function notesToWrites(input: ApuInput, lead = 0): RegisterWrite[] {\n const at = (tick: number) => tickToSeconds(input, tick);\n const bends = input.bends ?? [];\n const writes: RegisterWrite[] = [];\n const put = (time: number, address: number, value: number) =>\n writes.push({ time, address, value });\n\n // Power-on housekeeping, before any note: every channel enabled, and both\n // sweep units given `$08` (disabled, negate). That is what drivers write and\n // why: at the power-on value of 0 the sweep's target overflows for every\n // period from `$400` up, which would mute the low pulse notes of a track that\n // never mentions `$4001`.\n put(0, 0x4015, enables(true));\n put(0, 0x4001, 0x08);\n put(0, 0x4005, 0x08);\n\n const voicesOf = (rows: readonly (PitchedRow | DrumRow)[], keep: (row: never) => boolean) =>\n rows\n .filter(keep as (row: PitchedRow | DrumRow) => boolean)\n .map((row) => ({\n start: lead + at(row[1]),\n end: lead + at(row[1] + row[2]),\n row,\n }))\n .filter((voice) => voice.end > voice.start)\n .sort((a, b) => a.start - b.start);\n\n // Pulses.\n for (const channel of [0, 1]) {\n const base = 0x4000 + channel * 4;\n const voices: Voice[] = voicesOf(\n input.pitched,\n // Period 0 would be a divide by zero on the chip too; a row with none is\n // a rest, not a note.\n ((row: PitchedRow) => row[3] === channel && row[5] >= 1) as (row: never) => boolean\n );\n voices.forEach((voice, i) => {\n const [, , , , volume, period, duty, volumeEnd, lengthTicks, bendIndex, envelope, sweep, levelIndex] =\n voice.row as PitchedRow;\n const levelCurve =\n levelIndex !== undefined && levelIndex >= 0 ? (input.levels?.[levelIndex] ?? null) : null;\n const bits = controlBits(envelope ?? -1, lengthTicks);\n const reg0 = (level: number) =>\n ((duty & 3) << 6) |\n (bits.halt ? 0x20 : 0) |\n (bits.constant ? 0x10 | (level & 0x0f) : bits.low);\n const level = (at: number) =>\n levelCurve\n ? Math.min(15, Math.max(0, levelAt(levelCurve, at)))\n : Math.min(15, Math.max(0, Math.round(volume + (volumeEnd - volume) * at)));\n\n put(voice.start, base, reg0(level(0)));\n put(voice.start, base + 1, sweep !== undefined && sweep >= 0 ? sweep : 0x08);\n put(voice.start, base + 2, period & 0xff);\n put(voice.start, base + 3, (bits.load << 3) | ((period >> 8) & 7));\n\n const curve = bendIndex >= 0 ? (bends[bendIndex] ?? null) : null;\n const ramps = bits.constant && (levelCurve !== null || volume !== volumeEnd);\n if (curve || ramps) {\n let lastLevel = level(0);\n let lastPeriod = period;\n for (const { time, position } of frames(voice.start, voice.end)) {\n if (ramps) {\n const now = level(position);\n if (now !== lastLevel) put(time, base, reg0(now));\n lastLevel = now;\n }\n if (curve) {\n // A semitone is a frequency ratio; the period is a divider, so it\n // moves the other way.\n const now = toPeriod((period + 1) * Math.pow(2, -bendAt(curve, position) / 12) - 1);\n if (now !== lastPeriod) {\n put(time, base + 2, now & 0xff);\n // The high byte only when it changes, as drivers do — writing it\n // restarts the sequencer, which is an audible click.\n if (now >> 8 !== lastPeriod >> 8) put(time, base + 3, (bits.load << 3) | (now >> 8));\n }\n lastPeriod = now;\n }\n }\n }\n\n const next = voices[i + 1];\n if (!next || next.start > voice.end + 1e-9) put(voice.end, base, ((duty & 3) << 6) | 0x30);\n });\n }\n\n /*\n * The DMC's hits, worked out first: `$4015` is one register, and the triangle's\n * on/off writes to it clear the DMC's bit unless they set it — which stops a\n * sample dead. So every `$4015` write carries bit 4 while a sample is still\n * playing, and only then: set after it has ended, the bit starts it again.\n */\n const samples = input.samples ?? [];\n const hits = (input.hits ?? [])\n .map((row) => {\n const sample = samples[row[0]];\n if (!sample) return null;\n const start = lead + at(row[1]);\n const rowEnd = lead + at(row[1] + row[2]);\n const length = lengthCode(sample.bytes.length) * 16 + 1;\n const end = row[4] ? rowEnd : Math.min(rowEnd, start + sampleSeconds(length, row[3]));\n return end > start ? { row, sample, start, end, length } : null;\n })\n .filter((hit) => hit !== null)\n .sort((a, b) => a.start - b.start);\n const sampleOn = (time: number) => hits.some((hit) => hit.start <= time && time < hit.end);\n const withSample = (value: number, time: number) => (sampleOn(time) ? value | 0x10 : value);\n\n // Triangle. No volume: it is ended by switching it off in `$4015`, the one\n // way to stop it on the spot — and it then holds whatever step it stopped on.\n {\n const voices: Voice[] = voicesOf(input.pitched, ((row: PitchedRow) =>\n row[3] === 2 && row[5] >= 1) as (row: never) => boolean);\n let on = true;\n voices.forEach((voice, i) => {\n const [, , , , , period, , , lengthTicks, bendIndex] = voice.row as PitchedRow;\n // With a counter to honour, the control bit is clear and the linear\n // counter set to its longest (127 quarter-frames, 0.53 s) so the length\n // counter is the one that ends the note; with none, the control bit set\n // halts both.\n const load = lengthTicks > 0 ? lengthIndex(lengthTicks) : 0;\n if (!on) put(voice.start, 0x4015, withSample(enables(true), voice.start));\n on = true;\n put(voice.start, 0x4008, lengthTicks > 0 ? 0x7f : 0xff);\n put(voice.start, 0x400a, period & 0xff);\n put(voice.start, 0x400b, (load << 3) | ((period >> 8) & 7));\n\n const curve = bendIndex >= 0 ? (bends[bendIndex] ?? null) : null;\n if (curve) {\n let last = period;\n for (const { time, position } of frames(voice.start, voice.end)) {\n const now = toPeriod((period + 1) * Math.pow(2, -bendAt(curve, position) / 12) - 1);\n if (now !== last) {\n put(time, 0x400a, now & 0xff);\n if (now >> 8 !== last >> 8) put(time, 0x400b, (load << 3) | (now >> 8));\n }\n last = now;\n }\n }\n\n const next = voices[i + 1];\n if (!next || next.start > voice.end + 1e-9) {\n put(voice.end, 0x4015, withSample(enables(false), voice.end));\n on = false;\n }\n });\n }\n\n // Noise.\n {\n const voices: Voice[] = voicesOf(input.drums, (() => true) as (row: never) => boolean);\n voices.forEach((voice, i) => {\n const [periodIndex, , , volume, volumeEnd, lengthTicks, envelope, levelIndex] = voice.row as DrumRow;\n const bits = controlBits(envelope ?? -1, lengthTicks);\n const reg = (level: number) =>\n (bits.halt ? 0x20 : 0) | (bits.constant ? 0x10 | (level & 0x0f) : bits.low);\n // A drum struck at 8 and dropped to 2 the next frame — Darkwing Duck's — is that curve, not a line.\n const levelCurve =\n levelIndex !== undefined && levelIndex >= 0 ? (input.levels?.[levelIndex] ?? null) : null;\n const level = (at: number) =>\n levelCurve\n ? Math.min(15, Math.max(0, levelAt(levelCurve, at)))\n : Math.min(15, Math.max(0, Math.round(volume + (volumeEnd - volume) * at)));\n\n put(voice.start, 0x400c, reg(level(0)));\n put(voice.start, 0x400e, periodIndex & 0x0f);\n put(voice.start, 0x400f, bits.load << 3);\n\n if (bits.constant && (levelCurve !== null || volume !== volumeEnd)) {\n let last = level(0);\n for (const { time, position } of frames(voice.start, voice.end)) {\n const now = level(position);\n if (now !== last) put(time, 0x400c, reg(now));\n last = now;\n }\n }\n\n const next = voices[i + 1];\n if (!next || next.start > voice.end + 1e-9) put(voice.end, 0x400c, 0x30);\n });\n }\n\n // The DMC: rate and loop, where the sample is and how long, then bit 4 of\n // `$4015` to start it. A hit cut short by its row — or by the next — is\n // stopped by clearing the bit. The triangle's own `$4015` state goes with it.\n hits.forEach((hit, i) => {\n const [, , , rate, loop, level] = hit.row;\n const triangleOn = (time: number) => {\n // The last word the triangle had on `$4015` before `time`: on unless it was switched off.\n let state = true;\n for (const w of writes) if (w.address === 0x4015 && w.time <= time) state = (w.value & 0x04) !== 0;\n return state;\n };\n put(hit.start, 0x4010, (loop ? 0x40 : 0) | (rate & 0x0f));\n if (level !== undefined && level >= 0) put(hit.start, 0x4011, level & 0x7f);\n put(hit.start, 0x4012, ((hit.sample.address - 0xc000) >> 6) & 0xff);\n put(hit.start, 0x4013, lengthCode(hit.sample.bytes.length));\n // Off and on: bit 4 set while the last sample is still reading does not restart it.\n put(hit.start, 0x4015, enables(triangleOn(hit.start)));\n put(hit.start, 0x4015, enables(triangleOn(hit.start)) | 0x10);\n const next = hits[i + 1];\n const natural = hit.start + sampleSeconds(hit.length, rate);\n if (hit.end < natural - 1e-9 && (!next || next.start > hit.end + 1e-9)) {\n put(hit.end, 0x4015, enables(triangleOn(hit.end)));\n }\n });\n\n expansionWrites(input, lead, voicesOf, frames, put);\n return writes;\n}\n\nconst hzOf = (row: PitchedRow) => row[5] / 100;\n\n/**\n * The expansion channels' notes as writes: what a driver for the FDS or the N163 would write to\n * sound them — the waveform when it changes, then the frequency and level, and once a frame the\n * level while it ramps and the frequency while it bends.\n */\nfunction expansionWrites(\n input: ApuInput,\n lead: number,\n voicesOf: (rows: readonly (PitchedRow | DrumRow)[], keep: (row: never) => boolean) => Voice[],\n frames: (start: number, end: number) => Iterable<{ time: number; position: number }>,\n put: (time: number, address: number, value: number) => void\n) {\n const bends = input.bends ?? [];\n const waves = input.waves ?? [];\n const curveOf = (row: PitchedRow) => (row[9] >= 0 ? (bends[row[9]] ?? null) : null);\n const levelsOf = (row: PitchedRow) =>\n row[12] !== undefined && row[12] >= 0 ? (input.levels?.[row[12]] ?? null) : null;\n const levelAtOf = (row: PitchedRow) => {\n const curve = levelsOf(row);\n return (at: number) =>\n curve\n ? Math.min(15, Math.max(0, levelAt(curve, at)))\n : Math.min(15, Math.max(0, Math.round(row[4] + (row[7] - row[4]) * at)));\n };\n\n // FDS.\n {\n const voices = voicesOf(input.pitched, ((row: PitchedRow) =>\n row[3] === EXPANSION_CHANNELS.fds && row[5] > 0) as (row: never) => boolean);\n if (voices.length > 0) {\n put(0, 0x4087, 0x80); // modulation off: the bends carry the vibrato\n put(0, 0x408a, 0xe8);\n }\n const freqOf = (hz: number) => Math.min(0xfff, Math.max(1, Math.round((hz * 4194304) / CPU_HZ)));\n let lastWave = -1;\n voices.forEach((voice, i) => {\n const row = voice.row as PitchedRow;\n const waveIndex = row[13] ?? -1;\n if (waveIndex >= 0 && waveIndex !== lastWave && waves[waveIndex]) {\n put(voice.start, 0x4089, 0x80);\n waves[waveIndex].slice(0, 64).forEach((v, k) => put(voice.start, 0x4040 + k, v & 0x3f));\n put(voice.start, 0x4089, 0x00);\n lastWave = waveIndex;\n }\n const level = levelAtOf(row);\n const gain = (l: number) => 0x80 | Math.round((l * 32) / 15);\n const freq = freqOf(hzOf(row));\n put(voice.start, 0x4080, gain(level(0)));\n put(voice.start, 0x4082, freq & 0xff);\n put(voice.start, 0x4083, 0x40 | (freq >> 8));\n const curve = curveOf(row);\n const ramps = levelsOf(row) !== null || row[4] !== row[7];\n if (curve || ramps) {\n let lastLevel = level(0);\n let lastFreq = freq;\n for (const { time, position } of frames(voice.start, voice.end)) {\n if (ramps) {\n const now = level(position);\n if (now !== lastLevel) put(time, 0x4080, gain(now));\n lastLevel = now;\n }\n if (curve) {\n const now = freqOf(hzOf(row) * Math.pow(2, bendAt(curve, position) / 12));\n if (now !== lastFreq) {\n put(time, 0x4082, now & 0xff);\n if (now >> 8 !== lastFreq >> 8) put(time, 0x4083, 0x40 | (now >> 8));\n }\n lastFreq = now;\n }\n }\n }\n const next = voices[i + 1];\n if (!next || next.start > voice.end + 1e-9) put(voice.end, 0x4080, 0x80);\n });\n }\n\n // N163: as many channels on as the piece uses, each with its own stretch of the chip's RAM.\n const n163Voices = EXPANSION_CHANNELS.n163.map((channel) =>\n voicesOf(input.pitched, ((row: PitchedRow) => row[3] === channel && row[5] > 0) as (row: never) => boolean)\n );\n const used = n163Voices.reduce((most, voices, k) => (voices.length > 0 ? k + 1 : most), 0);\n if (used === 0) return;\n const count = used;\n // Registers take the top 8·count bytes; the rest is wave RAM, shared out evenly, in whole fours.\n const freeNibbles = (0x80 - 8 * count) * 2;\n const area = Math.max(4, Math.floor(freeNibbles / count / 4) * 4);\n const ramWrite = (time: number, address: number, bytes: readonly number[]) => {\n put(time, 0xf800, 0x80 | (address & 0x7f));\n for (const b of bytes) put(time, 0x4800, b & 0xff);\n };\n // The channel count lives in the top nibble of $7F, beside slot 7's volume.\n const countBits = (count - 1) << 4;\n ramWrite(0, 0x7f, [countBits]);\n /*\n * When every waveform the piece plays fits in the wave RAM at once, each gets a place of its own,\n * written before the first note, and a channel just points at it — as Namco's drivers do, several\n * channels reading one wave. Only when they do not fit does each channel get a stretch of its own\n * that its waves are written into as they come (and squeezed into, if longer).\n */\n const n163Waves = [...new Set(n163Voices.flat().map((voice) => (voice.row as PitchedRow)[13] ?? -1))].filter(\n (index) => index >= 0 && waves[index]\n );\n const fitted = (index: number) => Math.min(256, Math.max(4, Math.floor(waves[index].length / 4) * 4));\n const shared = new Map<number, { start: number; length: number }>();\n if (n163Waves.reduce((sum, index) => sum + fitted(index), 0) <= freeNibbles) {\n let at = 0;\n for (const index of n163Waves) {\n const length = fitted(index);\n shared.set(index, { start: at, length });\n const wave = waves[index];\n const bytes: number[] = [];\n for (let n = 0; n < length; n += 2) bytes.push((wave[n] & 0x0f) | ((wave[n + 1] ?? 0) & 0x0f) << 4);\n ramWrite(0, at >> 1, bytes);\n at += length;\n }\n }\n n163Voices.forEach((voices, k) => {\n const slot = 7 - k;\n const base = 0x40 + slot * 8;\n let start = k * area; // in nibbles\n let lastWave = -1;\n let length = area;\n const volumeByte = (v: number) => (slot === 7 ? countBits : 0) | (v & 0x0f);\n voices.forEach((voice, i) => {\n const row = voice.row as PitchedRow;\n const waveIndex = row[13] ?? -1;\n const wave = waveIndex >= 0 ? waves[waveIndex] : null;\n const place = shared.get(waveIndex);\n if (place) {\n start = place.start;\n length = place.length;\n } else if (wave && waveIndex !== lastWave) {\n start = k * area;\n // A wave longer than the stretch this channel has is resampled to fit.\n length = Math.min(area, Math.max(4, Math.floor(wave.length / 4) * 4));\n const samples = Array.from({ length }, (_, n) => wave[Math.floor((n * wave.length) / length)] & 0x0f);\n const bytes: number[] = [];\n for (let n = 0; n < length; n += 2) bytes.push(samples[n] | ((samples[n + 1] ?? 0) << 4));\n ramWrite(voice.start, start >> 1, bytes);\n lastWave = waveIndex;\n }\n const freqOf = (hz: number) =>\n Math.min(0x3ffff, Math.max(1, Math.round((hz * 15 * 65536 * count * length) / CPU_HZ)));\n const regs = (freq: number, volume: number) => [\n freq & 0xff,\n (freq >> 8) & 0xff,\n ((256 - length) & 0xfc) | ((freq >> 16) & 3),\n 0,\n 0,\n 0,\n start & 0xff,\n volumeByte(volume),\n ];\n const level = levelAtOf(row);\n const freq = freqOf(hzOf(row));\n ramWrite(voice.start, base, regs(freq, level(0)));\n const curve = curveOf(row);\n const ramps = levelsOf(row) !== null || row[4] !== row[7];\n if (curve || ramps) {\n let lastLevel = level(0);\n let lastFreq = freq;\n for (const { time, position } of frames(voice.start, voice.end)) {\n const nowLevel = ramps ? level(position) : lastLevel;\n const nowFreq = curve ? freqOf(hzOf(row) * Math.pow(2, bendAt(curve, position) / 12)) : lastFreq;\n if (nowFreq !== lastFreq) {\n // The frequency bytes alone, not the phase after them: that is the chip's running count.\n ramWrite(time, base, [nowFreq & 0xff, (nowFreq >> 8) & 0xff, ((256 - length) & 0xfc) | ((nowFreq >> 16) & 3)]);\n }\n if (nowLevel !== lastLevel) ramWrite(time, base + 7, [volumeByte(nowLevel)]);\n lastLevel = nowLevel;\n lastFreq = nowFreq;\n }\n }\n const next = voices[i + 1];\n if (!next || next.start > voice.end + 1e-9) ramWrite(voice.end, base + 7, [volumeByte(0)]);\n });\n });\n}\n\n/** Render a decoded piece: `notesToWrites` into `renderWrites`, with the tick-based extras. */\nexport function renderNotes(input: ApuInput, options: ApuOptions = {}): ApuRender {\n const lead = options.lead ?? 0;\n\n const clicks: Click[] = [];\n if (options.metronome && options.metronome > 0) {\n for (let tick = 0, beat = 0; tick < input.totalTicks; tick += options.metronome, beat++) {\n // Four beats to a bar: the downbeat is what makes a tempo readable.\n clicks.push({ time: lead + tickToSeconds(input, tick), strong: beat % 4 === 0 });\n }\n }\n\n const { lead: _lead, metronome: _metronome, ...render } = options;\n const end = tickToSeconds(input, input.totalTicks);\n const result = renderWrites(notesToWrites(input, lead), lead + end, {\n ...render,\n clicks,\n ...(input.samples?.length && !render.memory ? { memory: sampleMemory(input.samples) } : {}),\n });\n\n return {\n samples: result.samples,\n sampleRate: result.sampleRate,\n lead,\n duration: result.duration,\n loopStart: lead + tickToSeconds(input, Math.min(input.loopStart ?? 0, input.totalTicks)),\n loopEnd: lead + end,\n peak: result.peak,\n };\n}\n"]}
1
+ {"version":3,"file":"notes.js","sourceRoot":"","sources":["../src/notes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC7E,OAAO,EAAE,YAAY,EAAsD,MAAM,aAAa,CAAC;AAmC/F,4EAA4E;AAC5E,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,GAAG,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAW,CAAC;AAS1F,6EAA6E;AAC7E,MAAM,UAAU,OAAO,CAAC,KAAiB,EAAE,QAAgB;IACzD,IAAI,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IAC/B,KAAK,MAAM,CAAC,EAAE,EAAE,KAAK,CAAC,IAAI,KAAK,EAAE,CAAC;QAChC,IAAI,EAAE,GAAG,QAAQ,GAAG,IAAI;YAAE,MAAM;QAChC,KAAK,GAAG,KAAK,CAAC;IAChB,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAuED;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,KAAiD,EAAE,IAAY;IAC3F,MAAM,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC;IAC5B,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,GAAG,KAAK,CAAC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KAAK,CAAC,UAAU,CAAC,CAAC;QACxF,OAAO,EAAE,IAAI,GAAG,GAAG;QACnB,IAAI,EAAE,MAAM,CAAC,IAAI;KAClB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Notes in, register writes out — the adapter between a decoded score and the\n * chip.\n *\n * A music driver's job is to turn its own data into register writes, once a\n * frame. When a game's music has already been decoded into notes (start, length,\n * period, volume, duty, and how each of those moves), this plays the driver's\n * part: it writes what a driver would have written to sound those notes, and\n * `renderWrites` does the rest. So the chip never learns what a note is, and\n * anything the adapter gets wrong is visible as a register write rather than\n * hidden inside a synth.\n *\n * The note shape is the one xrom.dev exports for Battletoads, but nothing in it\n * is that game's: a tick is whatever the caller says it is in seconds.\n *\n * What it writes, per note:\n * - at the start, the channel's full register set — which on a pulse restarts\n * the duty sequencer and the envelope and reloads the length counter,\n * exactly as the driver's own `$4003` write does;\n * - once a frame after that, the level while it ramps and the period while it\n * bends, as whole numbers, because the registers hold whole numbers — so a\n * fade is a staircase at 60 Hz, as it is on the console;\n * - at the end, silence — unless the next note on the channel starts at the\n * same moment.\n */\n\nimport { CPU_HZ, DMC_PERIODS, FRAME_HZ, LENGTH_TABLE } from './constants.js';\nimport { renderWrites, type Click, type RegisterWrite, type RenderOptions } from './render.js';\n\n/**\n * `[midi, startTick, durationTicks, channel, volume, period, duty,\n * volumeEnd, lengthTicks, bendIndex, envelope, sweep, levelIndex]` — `lengthTicks` counts at\n * 120 Hz and 0 means unlimited; `bendIndex` points into `ApuInput.bends`, or is\n * -1; `envelope` is the low five bits of `$4000` when the chip's own envelope\n * runs (period, and bit 4 for loop), or -1 for constant volume; `sweep` is the\n * `$4001` byte, or -1/absent when the data has none; `levelIndex`, on a pulse, points into\n * `ApuInput.levels` for a level that does not go in a straight line from `volume` to `volumeEnd`,\n * or is -1/absent.\n *\n * Channels 0..2 are the 2A03's pulses and triangle. 5 is the Disk System's wave channel (FDS) and\n * 6..13 the N163's channels in the order the chip switches them on — see `EXPANSION_CHANNELS`. On\n * those `period` is the frequency in hundredths of a hertz (their registers depend on the wave's\n * length and the chip's channel count, which the adapter chooses itself), `volume` is 0..15, and\n * `waveIndex` (the 14th field) points into `ApuInput.waves`: the waveform the note plays.\n */\nexport type PitchedRow = readonly [\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number?,\n number?,\n number?,\n number?,\n];\n\n/** Pitched-row channels past the 2A03's: the FDS, then the N163's eight. */\nexport const EXPANSION_CHANNELS = { fds: 5, n163: [6, 7, 8, 9, 10, 11, 12, 13] } as const;\n\n\n/**\n * A level curve: `[position 0..1, level 0..15]` at each change of level, in order. The level holds\n * from one point to the next — a driver writes whole levels, a frame at a time.\n */\nexport type LevelCurve = readonly (readonly [number, number])[];\n\n/** The level a curve holds at `position`: the last point at or before it. */\nexport function levelAt(curve: LevelCurve, position: number): number {\n let level = curve[0]?.[1] ?? 0;\n for (const [at, value] of curve) {\n if (at > position + 1e-9) break;\n level = value;\n }\n return level;\n}\n\n/** A pitch curve: `[position 0..1, semitones]`, in order. */\nexport type BendCurve = readonly (readonly [number, number])[];\n\n/**\n * `[periodIndex, startTick, durationTicks, volume, volumeEnd, lengthTicks,\n * envelope, levelIndex]` — a noise-channel note. `periodIndex` is the low nibble of `$400E`;\n * `levelIndex` points into `ApuInput.levels`, as a pulse row's does, or is -1/absent.\n */\nexport type DrumRow = readonly [number, number, number, number, number, number, number?, number?];\n\n/**\n * `[sampleIndex, startTick, durationTicks, rate, loop, level]` — a sample struck\n * on the DMC: `sampleIndex` into `ApuInput.samples`, `rate` the low nibble of\n * `$4010`, `loop` 1 to repeat it until the row ends, `level` the 7-bit value a\n * driver loads into `$4011` before it (the jump is part of the sound — a kick's\n * thump), or -1/absent for none. It plays to the end of its bytes or of the\n * row, whichever comes first.\n */\nexport type SampleRow = readonly [number, number, number, number, number, number?];\n\n/**\n * A DMC sample: the 1-bit delta bytes the channel reads, and where it reads them\n * — `$C000` + 64·n, as `$4012` can point. The bytes are the cartridge's own.\n */\nexport interface DmcSample {\n address: number;\n bytes: readonly number[] | Uint8Array;\n}\n\nexport interface ApuInput {\n pitched: readonly PitchedRow[];\n drums: readonly DrumRow[];\n /** Samples struck on the DMC, pointing into `samples`. */\n hits?: readonly SampleRow[];\n /** The samples the hits play. */\n samples?: readonly DmcSample[];\n /** Pitch curves the notes point at. Shared, because the shapes repeat. */\n bends?: readonly BendCurve[];\n /** Level curves the pulse and noise notes point at — see `PitchedRow`'s `levelIndex`. Shared like `bends`. */\n levels?: readonly LevelCurve[];\n /**\n * Waveforms the expansion notes play — see `PitchedRow`'s `waveIndex`: 64 samples 0..63 for the\n * FDS, a multiple of 4 samples 0..15 for an N163 channel.\n */\n waves?: readonly (readonly number[])[];\n /** Seconds per tick. */\n secondsPerTick: number;\n /** Length of the piece in ticks. */\n totalTicks: number;\n /**\n * Where the repeat starts, in ticks. Not always 0: a driver's first ticks are\n * often one-time setup, so a track that loops on the whole buffer replays its\n * intro every time round. Absent means the piece does not loop.\n */\n loopStart?: number;\n /**\n * Changes of tempo, as `{ tick, secondsPerTick }` in tick order: from `tick`\n * on, a tick lasts `secondsPerTick`. Before the first change it is the\n * input's own `secondsPerTick`. For drivers with a tempo command — Battletoads\n * speeds its opening up this way — whose ticks are not all the same length.\n */\n tempo?: readonly TempoChange[];\n}\n\nexport interface TempoChange {\n tick: number;\n secondsPerTick: number;\n}\n\n/**\n * Seconds from the start to `tick`, through the tempo changes. With none it is\n * exactly `tick * secondsPerTick` — the same float, so a piece without changes\n * renders as it always has.\n */\nexport function tickToSeconds(input: Pick<ApuInput, 'secondsPerTick' | 'tempo'>, tick: number): number {\n const changes = input.tempo;\n if (!changes || changes.length === 0) return tick * input.secondsPerTick;\n let seconds = 0;\n let from = 0;\n let spt = input.secondsPerTick;\n for (const change of changes) {\n if (change.tick >= tick) break;\n seconds += (change.tick - from) * spt;\n from = change.tick;\n spt = change.secondsPerTick;\n }\n return seconds + (tick - from) * spt;\n}\n\n/** The tick at `seconds` — the inverse of `tickToSeconds`, fractional. */\nexport function secondsToTick(input: Pick<ApuInput, 'secondsPerTick' | 'tempo'>, seconds: number): number {\n const changes = input.tempo;\n if (!changes || changes.length === 0) return seconds / input.secondsPerTick;\n let at = 0;\n let from = 0;\n let spt = input.secondsPerTick;\n for (const change of changes) {\n const end = at + (change.tick - from) * spt;\n if (end >= seconds) break;\n at = end;\n from = change.tick;\n spt = change.secondsPerTick;\n }\n return from + (seconds - at) / spt;\n}\n\nexport interface ApuOptions extends Omit<RenderOptions, 'clicks' | 'tail'> {\n /** Seconds of silence before the first note. */\n lead?: number;\n /** Click on every `metronome` ticks, loud on every fourth. 0 is off. */\n metronome?: number;\n}\n\nexport interface ApuRender {\n samples: Float32Array;\n sampleRate: number;\n /** Seconds of silence before tick 0 — what the caller asked for as `lead`. */\n lead: number;\n /** Length of the whole buffer, tail included. */\n duration: number;\n /**\n * Where the music itself ends, in seconds — the loop point. The buffer runs a\n * little longer so the filters can ring out; looping on the buffer would play\n * that tail as a gap every time round.\n */\n loopEnd: number;\n /** Where the repeat starts, in seconds — the other end of the seam. */\n loopStart: number;\n /** Loudest absolute sample, before clamping. */\n peak: number;\n}\n\n/**\n * Semitones at `position` through a note, straight-line between the curve's own\n * points; outside it, the nearest end.\n */\nexport function bendAt(curve: BendCurve, position: number): number {\n if (curve.length === 0) return 0;\n if (position <= curve[0][0]) return curve[0][1];\n for (let i = 1; i < curve.length; i++) {\n const [x1, y1] = curve[i];\n if (position <= x1) {\n const [x0, y0] = curve[i - 1];\n const span = x1 - x0;\n return span <= 0 ? y1 : y0 + ((y1 - y0) * (position - x0)) / span;\n }\n }\n return curve[curve.length - 1][1];\n}\n\n/** Length-counter load → the index `$4003`'s top five bits must hold for it. */\nconst lengthIndex = (halfFrames: number) => {\n const index = LENGTH_TABLE.indexOf(halfFrames as (typeof LENGTH_TABLE)[number]);\n if (index < 0) throw new Error(`no length-table entry loads ${halfFrames} half-frames`);\n return index;\n};\n\n/** The longest load, 254 half-frames (2.1 s) — for a note with no counter that cannot halt it. */\nconst LONGEST = 1;\n\n/** The `$4015` value: pulses and noise always on; the triangle toggled to end its notes. */\nconst enables = (triangle: boolean) => 0x0b | (triangle ? 0x04 : 0);\n\n/** Seconds a sample of `length` bytes takes at `$4010` rate `rate`. */\nexport const sampleSeconds = (length: number, rate: number) =>\n (length * 8 * DMC_PERIODS[rate & 0x0f]) / CPU_HZ;\n\n/**\n * The bytes `$4013` makes the DMC read: 16·n + 1. A sample is stored that long;\n * one that is not is read to the next length the register can say.\n */\nconst lengthCode = (bytes: number) => Math.max(0, Math.min(255, Math.ceil((bytes - 1) / 16)));\n\n/**\n * The cartridge memory the DMC reads, from the samples a piece holds: each laid\n * at its own address, the rest zero. For `renderWrites`' `memory`.\n */\nexport function sampleMemory(samples: readonly DmcSample[]): Uint8Array {\n const memory = new Uint8Array(0x8000);\n for (const sample of samples) {\n const at = sample.address - 0x8000;\n for (let i = 0; i < sample.bytes.length && at + i < memory.length; i++) memory[at + i] = sample.bytes[i];\n }\n return memory;\n}\n\n/** A register value can only hold whole numbers; a period outside 11 bits is not one the chip has. */\nconst toPeriod = (value: number) => Math.min(0x7ff, Math.max(0, Math.round(value)));\n\ninterface Voice {\n start: number;\n end: number;\n row: PitchedRow | DrumRow;\n}\n\n/**\n * The bits `$4000`/`$400C` share, from a row's envelope and length counter.\n *\n * Bit 5 is one bit with two jobs — it halts the length counter AND loops the\n * envelope — so a note that wants its envelope to decay once cannot also have\n * an unlimited counter. The rows that ask for both (`lengthTicks` 0 with a\n * one-shot envelope) get the longest load the table has instead, which outlasts\n * any note the envelope has not already silenced.\n */\nfunction controlBits(envelope: number, lengthTicks: number) {\n if (envelope >= 0) {\n const loop = (envelope & 0x10) !== 0;\n return {\n halt: loop,\n load: lengthTicks > 0 ? lengthIndex(lengthTicks) : LONGEST,\n low: envelope & 0x0f,\n constant: false,\n };\n }\n return {\n halt: lengthTicks === 0,\n load: lengthTicks > 0 ? lengthIndex(lengthTicks) : 0,\n low: 0,\n constant: true,\n };\n}\n\n/** Frame moments inside a note, after its start: when a driver would next touch it. */\nfunction* frames(start: number, end: number) {\n for (let k = 1; ; k++) {\n const time = start + k / FRAME_HZ;\n if (time >= end) return;\n yield { time, position: (time - start) / (end - start) };\n }\n}\n\n/**\n * The writes that play `input`, as a driver would make them.\n *\n * @param lead seconds of silence before tick 0\n */\nexport function notesToWrites(input: ApuInput, lead = 0): RegisterWrite[] {\n const at = (tick: number) => tickToSeconds(input, tick);\n const bends = input.bends ?? [];\n const writes: RegisterWrite[] = [];\n const put = (time: number, address: number, value: number) =>\n writes.push({ time, address, value });\n\n // Power-on housekeeping, before any note: every channel enabled, and both\n // sweep units given `$08` (disabled, negate). That is what drivers write and\n // why: at the power-on value of 0 the sweep's target overflows for every\n // period from `$400` up, which would mute the low pulse notes of a track that\n // never mentions `$4001`.\n put(0, 0x4015, enables(true));\n put(0, 0x4001, 0x08);\n put(0, 0x4005, 0x08);\n\n const voicesOf = (rows: readonly (PitchedRow | DrumRow)[], keep: (row: never) => boolean) =>\n rows\n .filter(keep as (row: PitchedRow | DrumRow) => boolean)\n .map((row) => ({\n start: lead + at(row[1]),\n end: lead + at(row[1] + row[2]),\n row,\n }))\n .filter((voice) => voice.end > voice.start)\n .sort((a, b) => a.start - b.start);\n\n // Pulses.\n for (const channel of [0, 1]) {\n const base = 0x4000 + channel * 4;\n const voices: Voice[] = voicesOf(\n input.pitched,\n // Period 0 would be a divide by zero on the chip too; a row with none is\n // a rest, not a note.\n ((row: PitchedRow) => row[3] === channel && row[5] >= 1) as (row: never) => boolean\n );\n voices.forEach((voice, i) => {\n const [, , , , volume, period, duty, volumeEnd, lengthTicks, bendIndex, envelope, sweep, levelIndex] =\n voice.row as PitchedRow;\n const levelCurve =\n levelIndex !== undefined && levelIndex >= 0 ? (input.levels?.[levelIndex] ?? null) : null;\n const bits = controlBits(envelope ?? -1, lengthTicks);\n const reg0 = (level: number) =>\n ((duty & 3) << 6) |\n (bits.halt ? 0x20 : 0) |\n (bits.constant ? 0x10 | (level & 0x0f) : bits.low);\n const level = (at: number) =>\n levelCurve\n ? Math.min(15, Math.max(0, levelAt(levelCurve, at)))\n : Math.min(15, Math.max(0, Math.round(volume + (volumeEnd - volume) * at)));\n\n put(voice.start, base, reg0(level(0)));\n put(voice.start, base + 1, sweep !== undefined && sweep >= 0 ? sweep : 0x08);\n put(voice.start, base + 2, period & 0xff);\n put(voice.start, base + 3, (bits.load << 3) | ((period >> 8) & 7));\n\n const curve = bendIndex >= 0 ? (bends[bendIndex] ?? null) : null;\n const ramps = bits.constant && (levelCurve !== null || volume !== volumeEnd);\n if (curve || ramps) {\n let lastLevel = level(0);\n let lastPeriod = period;\n for (const { time, position } of frames(voice.start, voice.end)) {\n if (ramps) {\n const now = level(position);\n if (now !== lastLevel) put(time, base, reg0(now));\n lastLevel = now;\n }\n if (curve) {\n // A semitone is a frequency ratio; the period is a divider, so it\n // moves the other way.\n const now = toPeriod((period + 1) * Math.pow(2, -bendAt(curve, position) / 12) - 1);\n if (now !== lastPeriod) {\n put(time, base + 2, now & 0xff);\n // The high byte only when it changes, as drivers do — writing it\n // restarts the sequencer, which is an audible click.\n if (now >> 8 !== lastPeriod >> 8) put(time, base + 3, (bits.load << 3) | (now >> 8));\n }\n lastPeriod = now;\n }\n }\n }\n\n const next = voices[i + 1];\n if (!next || next.start > voice.end + 1e-9) put(voice.end, base, ((duty & 3) << 6) | 0x30);\n });\n }\n\n /*\n * The DMC's hits, worked out first: `$4015` is one register, and the triangle's\n * on/off writes to it clear the DMC's bit unless they set it — which stops a\n * sample dead. So every `$4015` write carries bit 4 while a sample is still\n * playing, and only then: set after it has ended, the bit starts it again.\n */\n const samples = input.samples ?? [];\n const hits = (input.hits ?? [])\n .map((row) => {\n const sample = samples[row[0]];\n if (!sample) return null;\n const start = lead + at(row[1]);\n const rowEnd = lead + at(row[1] + row[2]);\n const length = lengthCode(sample.bytes.length) * 16 + 1;\n const end = row[4] ? rowEnd : Math.min(rowEnd, start + sampleSeconds(length, row[3]));\n return end > start ? { row, sample, start, end, length } : null;\n })\n .filter((hit) => hit !== null)\n .sort((a, b) => a.start - b.start);\n const sampleOn = (time: number) => hits.some((hit) => hit.start <= time && time < hit.end);\n const withSample = (value: number, time: number) => (sampleOn(time) ? value | 0x10 : value);\n\n // Triangle. No volume: it is ended by switching it off in `$4015`, the one\n // way to stop it on the spot — and it then holds whatever step it stopped on.\n {\n const voices: Voice[] = voicesOf(input.pitched, ((row: PitchedRow) =>\n row[3] === 2 && row[5] >= 1) as (row: never) => boolean);\n let on = true;\n voices.forEach((voice, i) => {\n const [, , , , , period, , , lengthTicks, bendIndex] = voice.row as PitchedRow;\n // With a counter to honour, the control bit is clear and the linear\n // counter set to its longest (127 quarter-frames, 0.53 s) so the length\n // counter is the one that ends the note; with none, the control bit set\n // halts both.\n const load = lengthTicks > 0 ? lengthIndex(lengthTicks) : 0;\n if (!on) put(voice.start, 0x4015, withSample(enables(true), voice.start));\n on = true;\n put(voice.start, 0x4008, lengthTicks > 0 ? 0x7f : 0xff);\n put(voice.start, 0x400a, period & 0xff);\n put(voice.start, 0x400b, (load << 3) | ((period >> 8) & 7));\n\n const curve = bendIndex >= 0 ? (bends[bendIndex] ?? null) : null;\n if (curve) {\n let last = period;\n for (const { time, position } of frames(voice.start, voice.end)) {\n const now = toPeriod((period + 1) * Math.pow(2, -bendAt(curve, position) / 12) - 1);\n if (now !== last) {\n put(time, 0x400a, now & 0xff);\n if (now >> 8 !== last >> 8) put(time, 0x400b, (load << 3) | (now >> 8));\n }\n last = now;\n }\n }\n\n const next = voices[i + 1];\n if (!next || next.start > voice.end + 1e-9) {\n put(voice.end, 0x4015, withSample(enables(false), voice.end));\n on = false;\n }\n });\n }\n\n // Noise.\n {\n const voices: Voice[] = voicesOf(input.drums, (() => true) as (row: never) => boolean);\n voices.forEach((voice, i) => {\n const [periodIndex, , , volume, volumeEnd, lengthTicks, envelope, levelIndex] = voice.row as DrumRow;\n const bits = controlBits(envelope ?? -1, lengthTicks);\n const reg = (level: number) =>\n (bits.halt ? 0x20 : 0) | (bits.constant ? 0x10 | (level & 0x0f) : bits.low);\n // A drum struck at 8 and dropped to 2 the next frame — Darkwing Duck's — is that curve, not a line.\n const levelCurve =\n levelIndex !== undefined && levelIndex >= 0 ? (input.levels?.[levelIndex] ?? null) : null;\n const level = (at: number) =>\n levelCurve\n ? Math.min(15, Math.max(0, levelAt(levelCurve, at)))\n : Math.min(15, Math.max(0, Math.round(volume + (volumeEnd - volume) * at)));\n\n put(voice.start, 0x400c, reg(level(0)));\n put(voice.start, 0x400e, periodIndex & 0x0f);\n put(voice.start, 0x400f, bits.load << 3);\n\n if (bits.constant && (levelCurve !== null || volume !== volumeEnd)) {\n let last = level(0);\n for (const { time, position } of frames(voice.start, voice.end)) {\n const now = level(position);\n if (now !== last) put(time, 0x400c, reg(now));\n last = now;\n }\n }\n\n const next = voices[i + 1];\n if (!next || next.start > voice.end + 1e-9) put(voice.end, 0x400c, 0x30);\n });\n }\n\n // The DMC: rate and loop, where the sample is and how long, then bit 4 of\n // `$4015` to start it. A hit cut short by its row — or by the next — is\n // stopped by clearing the bit. The triangle's own `$4015` state goes with it.\n hits.forEach((hit, i) => {\n const [, , , rate, loop, level] = hit.row;\n const triangleOn = (time: number) => {\n // The last word the triangle had on `$4015` before `time`: on unless it was switched off.\n let state = true;\n for (const w of writes) if (w.address === 0x4015 && w.time <= time) state = (w.value & 0x04) !== 0;\n return state;\n };\n put(hit.start, 0x4010, (loop ? 0x40 : 0) | (rate & 0x0f));\n if (level !== undefined && level >= 0) put(hit.start, 0x4011, level & 0x7f);\n put(hit.start, 0x4012, ((hit.sample.address - 0xc000) >> 6) & 0xff);\n put(hit.start, 0x4013, lengthCode(hit.sample.bytes.length));\n // Off and on: bit 4 set while the last sample is still reading does not restart it.\n put(hit.start, 0x4015, enables(triangleOn(hit.start)));\n put(hit.start, 0x4015, enables(triangleOn(hit.start)) | 0x10);\n const next = hits[i + 1];\n const natural = hit.start + sampleSeconds(hit.length, rate);\n if (hit.end < natural - 1e-9 && (!next || next.start > hit.end + 1e-9)) {\n put(hit.end, 0x4015, enables(triangleOn(hit.end)));\n }\n });\n\n expansionWrites(input, lead, voicesOf, frames, put);\n return writes;\n}\n\nconst hzOf = (row: PitchedRow) => row[5] / 100;\n\n/**\n * The expansion channels' notes as writes: what a driver for the FDS or the N163 would write to\n * sound them — the waveform when it changes, then the frequency and level, and once a frame the\n * level while it ramps and the frequency while it bends.\n */\nfunction expansionWrites(\n input: ApuInput,\n lead: number,\n voicesOf: (rows: readonly (PitchedRow | DrumRow)[], keep: (row: never) => boolean) => Voice[],\n frames: (start: number, end: number) => Iterable<{ time: number; position: number }>,\n put: (time: number, address: number, value: number) => void\n) {\n const bends = input.bends ?? [];\n const waves = input.waves ?? [];\n const curveOf = (row: PitchedRow) => (row[9] >= 0 ? (bends[row[9]] ?? null) : null);\n const levelsOf = (row: PitchedRow) =>\n row[12] !== undefined && row[12] >= 0 ? (input.levels?.[row[12]] ?? null) : null;\n const levelAtOf = (row: PitchedRow) => {\n const curve = levelsOf(row);\n return (at: number) =>\n curve\n ? Math.min(15, Math.max(0, levelAt(curve, at)))\n : Math.min(15, Math.max(0, Math.round(row[4] + (row[7] - row[4]) * at)));\n };\n\n // FDS.\n {\n const voices = voicesOf(input.pitched, ((row: PitchedRow) =>\n row[3] === EXPANSION_CHANNELS.fds && row[5] > 0) as (row: never) => boolean);\n if (voices.length > 0) {\n put(0, 0x4087, 0x80); // modulation off: the bends carry the vibrato\n put(0, 0x408a, 0xe8);\n }\n const freqOf = (hz: number) => Math.min(0xfff, Math.max(1, Math.round((hz * 4194304) / CPU_HZ)));\n let lastWave = -1;\n voices.forEach((voice, i) => {\n const row = voice.row as PitchedRow;\n const waveIndex = row[13] ?? -1;\n if (waveIndex >= 0 && waveIndex !== lastWave && waves[waveIndex]) {\n put(voice.start, 0x4089, 0x80);\n waves[waveIndex].slice(0, 64).forEach((v, k) => put(voice.start, 0x4040 + k, v & 0x3f));\n put(voice.start, 0x4089, 0x00);\n lastWave = waveIndex;\n }\n const level = levelAtOf(row);\n const gain = (l: number) => 0x80 | Math.round((l * 32) / 15);\n const freq = freqOf(hzOf(row));\n put(voice.start, 0x4080, gain(level(0)));\n put(voice.start, 0x4082, freq & 0xff);\n put(voice.start, 0x4083, 0x40 | (freq >> 8));\n const curve = curveOf(row);\n const ramps = levelsOf(row) !== null || row[4] !== row[7];\n if (curve || ramps) {\n let lastLevel = level(0);\n let lastFreq = freq;\n for (const { time, position } of frames(voice.start, voice.end)) {\n if (ramps) {\n const now = level(position);\n if (now !== lastLevel) put(time, 0x4080, gain(now));\n lastLevel = now;\n }\n if (curve) {\n const now = freqOf(hzOf(row) * Math.pow(2, bendAt(curve, position) / 12));\n if (now !== lastFreq) {\n put(time, 0x4082, now & 0xff);\n if (now >> 8 !== lastFreq >> 8) put(time, 0x4083, 0x40 | (now >> 8));\n }\n lastFreq = now;\n }\n }\n }\n const next = voices[i + 1];\n if (!next || next.start > voice.end + 1e-9) put(voice.end, 0x4080, 0x80);\n });\n }\n\n // N163: as many channels on as the piece uses, each with its own stretch of the chip's RAM.\n const n163Voices = EXPANSION_CHANNELS.n163.map((channel) =>\n voicesOf(input.pitched, ((row: PitchedRow) => row[3] === channel && row[5] > 0) as (row: never) => boolean)\n );\n const used = n163Voices.reduce((most, voices, k) => (voices.length > 0 ? k + 1 : most), 0);\n if (used === 0) return;\n const count = used;\n // Registers take the top 8·count bytes; the rest is wave RAM, shared out evenly, in whole fours.\n const freeNibbles = (0x80 - 8 * count) * 2;\n const area = Math.max(4, Math.floor(freeNibbles / count / 4) * 4);\n const ramWrite = (time: number, address: number, bytes: readonly number[]) => {\n put(time, 0xf800, 0x80 | (address & 0x7f));\n for (const b of bytes) put(time, 0x4800, b & 0xff);\n };\n // The channel count lives in the top nibble of $7F, beside slot 7's volume.\n const countBits = (count - 1) << 4;\n ramWrite(0, 0x7f, [countBits]);\n /*\n * When every waveform the piece plays fits in the wave RAM at once, each gets a place of its own,\n * written before the first note, and a channel just points at it — as Namco's drivers do, several\n * channels reading one wave. Only when they do not fit does each channel get a stretch of its own\n * that its waves are written into as they come (and squeezed into, if longer).\n */\n const n163Waves = [...new Set(n163Voices.flat().map((voice) => (voice.row as PitchedRow)[13] ?? -1))].filter(\n (index) => index >= 0 && waves[index]\n );\n const fitted = (index: number) => Math.min(256, Math.max(4, Math.floor(waves[index].length / 4) * 4));\n const shared = new Map<number, { start: number; length: number }>();\n if (n163Waves.reduce((sum, index) => sum + fitted(index), 0) <= freeNibbles) {\n let at = 0;\n for (const index of n163Waves) {\n const length = fitted(index);\n shared.set(index, { start: at, length });\n const wave = waves[index];\n const bytes: number[] = [];\n for (let n = 0; n < length; n += 2) bytes.push((wave[n] & 0x0f) | ((wave[n + 1] ?? 0) & 0x0f) << 4);\n ramWrite(0, at >> 1, bytes);\n at += length;\n }\n }\n n163Voices.forEach((voices, k) => {\n const slot = 7 - k;\n const base = 0x40 + slot * 8;\n let start = k * area; // in nibbles\n let lastWave = -1;\n let length = area;\n const volumeByte = (v: number) => (slot === 7 ? countBits : 0) | (v & 0x0f);\n voices.forEach((voice, i) => {\n const row = voice.row as PitchedRow;\n const waveIndex = row[13] ?? -1;\n const wave = waveIndex >= 0 ? waves[waveIndex] : null;\n const place = shared.get(waveIndex);\n if (place) {\n start = place.start;\n length = place.length;\n } else if (wave && waveIndex !== lastWave) {\n start = k * area;\n // A wave longer than the stretch this channel has is resampled to fit.\n length = Math.min(area, Math.max(4, Math.floor(wave.length / 4) * 4));\n const samples = Array.from({ length }, (_, n) => wave[Math.floor((n * wave.length) / length)] & 0x0f);\n const bytes: number[] = [];\n for (let n = 0; n < length; n += 2) bytes.push(samples[n] | ((samples[n + 1] ?? 0) << 4));\n ramWrite(voice.start, start >> 1, bytes);\n lastWave = waveIndex;\n }\n const freqOf = (hz: number) =>\n Math.min(0x3ffff, Math.max(1, Math.round((hz * 15 * 65536 * count * length) / CPU_HZ)));\n const regs = (freq: number, volume: number) => [\n freq & 0xff,\n 0,\n (freq >> 8) & 0xff,\n 0,\n ((256 - length) & 0xfc) | ((freq >> 16) & 3),\n 0,\n start & 0xff,\n volumeByte(volume),\n ];\n const level = levelAtOf(row);\n const freq = freqOf(hzOf(row));\n ramWrite(voice.start, base, regs(freq, level(0)));\n const curve = curveOf(row);\n const ramps = levelsOf(row) !== null || row[4] !== row[7];\n if (curve || ramps) {\n let lastLevel = level(0);\n let lastFreq = freq;\n for (const { time, position } of frames(voice.start, voice.end)) {\n const nowLevel = ramps ? level(position) : lastLevel;\n const nowFreq = curve ? freqOf(hzOf(row) * Math.pow(2, bendAt(curve, position) / 12)) : lastFreq;\n if (nowFreq !== lastFreq) {\n // The frequency bytes alone, not the phase after them: that is the chip's running count.\n ramWrite(time, base, [nowFreq & 0xff]);\n ramWrite(time, base + 2, [(nowFreq >> 8) & 0xff]);\n ramWrite(time, base + 4, [((256 - length) & 0xfc) | ((nowFreq >> 16) & 3)]);\n }\n if (nowLevel !== lastLevel) ramWrite(time, base + 7, [volumeByte(nowLevel)]);\n lastLevel = nowLevel;\n lastFreq = nowFreq;\n }\n }\n const next = voices[i + 1];\n if (!next || next.start > voice.end + 1e-9) ramWrite(voice.end, base + 7, [volumeByte(0)]);\n });\n });\n}\n\n/** Render a decoded piece: `notesToWrites` into `renderWrites`, with the tick-based extras. */\nexport function renderNotes(input: ApuInput, options: ApuOptions = {}): ApuRender {\n const lead = options.lead ?? 0;\n\n const clicks: Click[] = [];\n if (options.metronome && options.metronome > 0) {\n for (let tick = 0, beat = 0; tick < input.totalTicks; tick += options.metronome, beat++) {\n // Four beats to a bar: the downbeat is what makes a tempo readable.\n clicks.push({ time: lead + tickToSeconds(input, tick), strong: beat % 4 === 0 });\n }\n }\n\n const { lead: _lead, metronome: _metronome, ...render } = options;\n const end = tickToSeconds(input, input.totalTicks);\n const result = renderWrites(notesToWrites(input, lead), lead + end, {\n ...render,\n clicks,\n ...(input.samples?.length && !render.memory ? { memory: sampleMemory(input.samples) } : {}),\n });\n\n return {\n samples: result.samples,\n sampleRate: result.sampleRate,\n lead,\n duration: result.duration,\n loopStart: lead + tickToSeconds(input, Math.min(input.loopStart ?? 0, input.totalTicks)),\n loopEnd: lead + end,\n peak: result.peak,\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xromdev/apu",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
4
4
  "description": "The NES sound chip (2A03 APU) in TypeScript: register writes in, samples out.",
5
5
  "license": "MIT",
6
6
  "type": "module",