@xromdev/apu 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"render.js","sourceRoot":"","sources":["../src/render.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,GAAG,EAAuC,MAAM,WAAW,CAAC;AACrE,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAiElF;;;;;;GAMG;AACH,MAAM,UAAU,YAAY,CAC1B,MAAgC,EAChC,QAAgB,EAChB,UAAyB,EAAE;IAE3B,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,IAAI,KAAK,CAAC;IAC/C,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,IAAI,CAAC,CAAC,CAAC,CAAC;IACpE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,GAAG,CAAC;IACjC,MAAM,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IACnC,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,KAAK,KAAK,CAAC;IAC3C,MAAM,IAAI,GAAG,UAAU,GAAG,UAAU,CAAC;IACrC,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,OAAO,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC;IAEpF,MAAM,OAAO,GAAG,MAAM;SACnB,GAAG,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,EA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AAE,IAAI,GAAG,IAAI,CAAC;IACjD,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AACzF,CAAC;AAED,+EAA+E;AAC/E,MAAM,aAAa,GAAG,CAAC,OAAe,EAAE,EAAE,CACxC,CAAC,OAAO,IAAI,MAAM,IAAI,OAAO,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,IAAI,MAAM,IAAI,OAAO,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,IAAI,MAAM,IAAI,OAAO,IAAI,MAAM,CAAC,CAAC","sourcesContent":["/**\n * Register writes in, a finished buffer of samples out.\n *\n * Offline rather than scheduled live: a whole track is a few hundred\n * milliseconds of arithmetic, and a finished buffer is trivially in sync with\n * anything drawn over it — the playing position is one number both read.\n */\n\nimport { Apu, type ApuMemory, type ChannelBuffers } from './chip.js';\nimport { mixApu, OutputFilters, PULSE_MIX, PULSE_TRIANGLE_MIX } from './mixer.js';\n\n/** One CPU write to an APU register, at a moment in seconds from the start. */\nexport interface RegisterWrite {\n time: number;\n address: number;\n value: number;\n}\n\n/** A metronome click: ours, not the chip's, so it is mixed after the console's filters. */\nexport interface Click {\n time: number;\n /** The downbeat: higher and louder. */\n strong: boolean;\n}\n\nexport interface RenderOptions {\n sampleRate?: number;\n /**\n * Run the chip at this multiple of the sample rate and average down. A square\n * wave has infinite harmonics, so at 44.1 kHz the high notes alias into\n * inharmonic tones; 2× costs twice the arithmetic and takes most of it away.\n */\n oversample?: number;\n /** Master level. Default 2.2 — the high-passes centre the signal and cost level. */\n gain?: number;\n /**\n * A fader per channel, `[pulse1, pulse2, triangle, noise, dmc]`, 0..1. Default all 1.\n *\n * Applied to each channel's level BEFORE the non-linear mixer, the only place\n * a per-channel level can go: the mixer's whole point is that the channels\n * are not independent. The console has no such control — the triangle has no\n * volume at all — so this is a desk in front of the chip, for hearing one\n * voice on its own.\n */\n voiceLevels?: readonly number[];\n /**\n * Expansion chips to emulate (`'FDS'`, `'N163'`, `'VRC6'`). Left out, they are inferred from the\n * writes: one to `$4040`–`$408A` means an FDS, one to `$F800`/`$4800` an N163, one to\n * `$9000`–`$9003`/`$A000`–`$A002`/`$B000`–`$B002` a VRC6.\n */\n expansion?: readonly string[];\n /** Skip the output filters. For tests that want the raw mixer. */\n filters?: boolean;\n /** Add the console's second high-pass at 440 Hz — see `OutputFilters`. */\n consoleBass?: boolean;\n /** Honour the length counters. Default true. */\n lengthCounter?: boolean;\n /** Cartridge memory the DMC reads its samples from — see `ApuMemory`. */\n memory?: ApuMemory;\n /** Metronome clicks to mix in after the filters. */\n clicks?: readonly Click[];\n /** Seconds rendered past `duration` so the filters can ring out. Default 0.05. */\n tail?: number;\n}\n\nexport interface Render {\n samples: Float32Array;\n sampleRate: number;\n /** Length of the whole buffer, tail included, in seconds. */\n duration: number;\n /** Loudest absolute sample, before clamping. A value over 1 means the buffer was clamped. */\n peak: number;\n}\n\n/**\n * Play `writes` through the chip for `duration` seconds.\n *\n * Writes may come in any order; ones at the same moment are applied in the\n * order given, which matters — `$4015` has to enable a channel before the\n * write that loads its length counter.\n */\nexport function renderWrites(\n writes: readonly RegisterWrite[],\n duration: number,\n options: RenderOptions = {}\n): Render {\n const sampleRate = options.sampleRate ?? 44100;\n const oversample = Math.max(1, Math.round(options.oversample ?? 2));\n const gain = options.gain ?? 2.2;\n const faders = options.voiceLevels;\n const filtered = options.filters !== false;\n const rate = sampleRate * oversample;\n const total = Math.ceil(duration * rate) + Math.ceil(rate * (options.tail ?? 0.05));\n\n const ordered = writes\n .map((write, index) => ({ at: Math.max(0, Math.round(write.time * rate)), index, write }))\n .sort((a, b) => a.at - b.at || a.index - b.index);\n\n const expansion = options.expansion ?? expansionOf(writes);\n const chip = new Apu(rate, { lengthCounter: options.lengthCounter, memory: options.memory, expansion });\n const filters = new OutputFilters(rate, options.consoleBass ?? false);\n const out = new Float32Array(Math.ceil(total / oversample));\n\n const clicks = [...(options.clicks ?? [])]\n .map((click) => ({ at: Math.round(click.time * rate), strong: click.strong }))\n .sort((a, b) => a.at - b.at);\n const clickLength = Math.round(rate * 0.03);\n let clickCursor = 0;\n\n // Work in blocks: the chip fills a run of samples per channel, then one tight\n // loop mixes, filters and decimates it. A block ends early at the next write,\n // which has to land on its own sample.\n const BLOCK = 1024;\n const buffers: ChannelBuffers = {\n pulse1: new Uint8Array(BLOCK),\n pulse2: new Uint8Array(BLOCK),\n triangle: new Uint8Array(BLOCK),\n noise: new Float64Array(BLOCK),\n dmc: new Uint8Array(BLOCK),\n };\n const { pulse1: p1, pulse2: p2, triangle: tri, noise, dmc } = buffers;\n /*\n * The expansion voices, each in a buffer of its own so a fader reaches it: the FDS at voice 5,\n * the N163's channels at 6.. — its always-on slot 7 first, then 6, 5… as more are switched on —\n * and the VRC6's pulse 1, pulse 2 and saw at 14, 15, 16.\n */\n const fdsOut = chip.fds ? new Float64Array(BLOCK) : null;\n const n163Out = chip.n163 ? Array.from({ length: 8 }, () => new Float64Array(BLOCK)) : null;\n if (fdsOut) buffers.fds = fdsOut;\n if (n163Out) buffers.n163 = n163Out;\n const vrc6Out = chip.vrc6 ? Array.from({ length: 3 }, () => new Float64Array(BLOCK)) : null;\n if (vrc6Out) buffers.vrc6 = vrc6Out;\n const fVrc6 = [14, 15, 16].map((voice) => (faders ? (faders[voice] ?? 1) : 1));\n const fFds = faders ? (faders[5] ?? 1) : 1;\n const fN163 = Array.from({ length: 8 }, (_, slot) => (faders ? (faders[6 + 7 - slot] ?? 1) : 1));\n const hasClicks = clicks.length > 0;\n const f0 = faders ? (faders[0] ?? 1) : 1;\n const f1 = faders ? (faders[1] ?? 1) : 1;\n const f2 = faders ? (faders[2] ?? 1) : 1;\n const f3 = faders ? (faders[3] ?? 1) : 1;\n const f4 = faders ? (faders[4] ?? 1) : 1;\n\n let next = 0;\n let peak = 0;\n let accumulator = 0;\n let written = 0;\n let phase = 0;\n\n for (let sample = 0; sample < total; ) {\n while (next < ordered.length && ordered[next].at <= sample) {\n const { write } = ordered[next++];\n chip.write(write.address, write.value);\n }\n const until = next < ordered.length ? ordered[next].at : total;\n const count = Math.min(BLOCK, total - sample, until - sample);\n chip.render(count, buffers);\n\n for (let k = 0; k < count; k++, sample++) {\n let mixed: number;\n if (faders) {\n mixed = mixApu(p1[k] * f0, p2[k] * f1, tri[k] * f2, noise[k] * f3, dmc[k] * f4);\n } else if (noise[k] === 0 && dmc[k] === 0) {\n // The common case, from tables built with the mixer's own expressions.\n mixed = PULSE_TRIANGLE_MIX[((p1[k] + p2[k]) << 4) | tri[k]];\n } else {\n const tnd = tri[k] / 8227 + noise[k] / 12241 + dmc[k] / 22638;\n mixed = PULSE_MIX[p1[k] + p2[k]] + (tnd === 0 ? 0 : 159.79 / (1 / tnd + 100));\n }\n if (fdsOut) mixed += fdsOut[k] * fFds;\n if (n163Out) for (let slot = 0; slot < 8; slot++) mixed += n163Out[slot][k] * fN163[slot];\n if (vrc6Out) mixed += vrc6Out[0][k] * fVrc6[0] + vrc6Out[1][k] * fVrc6[1] + vrc6Out[2][k] * fVrc6[2];\n // Filtered at the oversampled rate: the low-pass then doubles as the\n // anti-aliasing filter the decimation needs.\n let value = filtered ? filters.step(mixed) : mixed;\n\n if (hasClicks) {\n while (clickCursor < clicks.length && sample >= clicks[clickCursor].at + clickLength) {\n clickCursor++;\n }\n const click = clicks[clickCursor];\n if (click && sample >= click.at) {\n // A decaying sine, added AFTER the console's filters: running it\n // through them would colour it as if it came out of the cartridge.\n const into = (sample - click.at) / clickLength;\n const hz = click.strong ? 1600 : 1050;\n value +=\n Math.sin((2 * Math.PI * hz * (sample - click.at)) / rate) *\n Math.pow(1 - into, 3) *\n (click.strong ? 0.22 : 0.14);\n }\n }\n\n accumulator += value;\n\n if (++phase === oversample) {\n phase = 0;\n // Clamped, not scaled: the filters can overshoot a little on a hard\n // transient. `peak` reports what it was BEFORE the clamp.\n const averaged = (accumulator / oversample) * gain;\n accumulator = 0;\n const magnitude = averaged < 0 ? -averaged : averaged;\n if (magnitude > peak) peak = magnitude;\n if (written < out.length) out[written++] = averaged > 1 ? 1 : averaged < -1 ? -1 : averaged;\n }\n }\n }\n\n return { samples: out, sampleRate, duration: out.length / sampleRate, peak };\n}\n\n/** The expansion chips a list of writes talks to — see `RenderOptions.expansion`. */\nexport function expansionOf(writes: readonly RegisterWrite[]): string[] {\n let fds = false;\n let n163 = false;\n let vrc6 = false;\n for (const w of writes) {\n if (w.address >= 0x4040 && w.address <= 0x408a) fds = true;\n else if ((w.address >= 0xf800 && w.address <= 0xffff) || (w.address >= 0x4800 && w.address <= 0x4fff)) n163 = true;\n else if (isVrc6Address(w.address)) vrc6 = true;\n }\n return [...(fds ? ['FDS'] : []), ...(n163 ? ['N163'] : []), ...(vrc6 ? ['VRC6'] : [])];\n}\n\n/** `$9000`–`$9003`, `$A000`–`$A002`, `$B000`–`$B002`: the VRC6's registers. */\nconst isVrc6Address = (address: number) =>\n (address >= 0x9000 && address <= 0x9003) || (address >= 0xa000 && address <= 0xa002) || (address >= 0xb000 && address <= 0xb002);\n"]}
1
+ {"version":3,"file":"render.js","sourceRoot":"","sources":["../src/render.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,GAAG,EAAuC,MAAM,WAAW,CAAC;AACrE,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAkElF;;;;;;GAMG;AACH,MAAM,UAAU,YAAY,CAC1B,MAAgC,EAChC,QAAgB,EAChB,UAAyB,EAAE;IAE3B,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,IAAI,KAAK,CA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;aAC5D,IAAI,CAAC,CAAC,OAAO,KAAK,MAAM,IAAI,CAAC,CAAC,OAAO,KAAK,MAAM;YAAE,IAAI,GAAG,IAAI,CAAC;IACrE,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAC/I,CAAC;AAED,+EAA+E;AAC/E,MAAM,aAAa,GAAG,CAAC,OAAe,EAAE,EAAE,CACxC,CAAC,OAAO,IAAI,MAAM,IAAI,OAAO,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,IAAI,MAAM,IAAI,OAAO,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,IAAI,MAAM,IAAI,OAAO,IAAI,MAAM,CAAC,CAAC","sourcesContent":["/**\n * Register writes in, a finished buffer of samples out.\n *\n * Offline rather than scheduled live: a whole track is a few hundred\n * milliseconds of arithmetic, and a finished buffer is trivially in sync with\n * anything drawn over it — the playing position is one number both read.\n */\n\nimport { Apu, type ApuMemory, type ChannelBuffers } from './chip.js';\nimport { mixApu, OutputFilters, PULSE_MIX, PULSE_TRIANGLE_MIX } from './mixer.js';\n\n/** One CPU write to an APU register, at a moment in seconds from the start. */\nexport interface RegisterWrite {\n time: number;\n address: number;\n value: number;\n}\n\n/** A metronome click: ours, not the chip's, so it is mixed after the console's filters. */\nexport interface Click {\n time: number;\n /** The downbeat: higher and louder. */\n strong: boolean;\n}\n\nexport interface RenderOptions {\n sampleRate?: number;\n /**\n * Run the chip at this multiple of the sample rate and average down. A square\n * wave has infinite harmonics, so at 44.1 kHz the high notes alias into\n * inharmonic tones; 2× costs twice the arithmetic and takes most of it away.\n */\n oversample?: number;\n /** Master level. Default 2.2 — the high-passes centre the signal and cost level. */\n gain?: number;\n /**\n * A fader per channel, `[pulse1, pulse2, triangle, noise, dmc]`, 0..1. Default all 1.\n *\n * Applied to each channel's level BEFORE the non-linear mixer, the only place\n * a per-channel level can go: the mixer's whole point is that the channels\n * are not independent. The console has no such control — the triangle has no\n * volume at all — so this is a desk in front of the chip, for hearing one\n * voice on its own.\n */\n voiceLevels?: readonly number[];\n /**\n * Expansion chips to emulate (`'FDS'`, `'N163'`, `'VRC6'`, `'MMC5'`, `'VRC7'`). Left out, they are inferred from the\n * writes: one to `$4040`–`$408A` means an FDS, one to `$F800`/`$4800` an N163, one to\n * `$9000`–`$9003`/`$A000`–`$A002`/`$B000`–`$B002` a VRC6, one to `$5000`–`$5015` an MMC5,\n * one to `$9010`/`$9030` a VRC7.\n */\n expansion?: readonly string[];\n /** Skip the output filters. For tests that want the raw mixer. */\n filters?: boolean;\n /** Add the console's second high-pass at 440 Hz — see `OutputFilters`. */\n consoleBass?: boolean;\n /** Honour the length counters. Default true. */\n lengthCounter?: boolean;\n /** Cartridge memory the DMC reads its samples from — see `ApuMemory`. */\n memory?: ApuMemory;\n /** Metronome clicks to mix in after the filters. */\n clicks?: readonly Click[];\n /** Seconds rendered past `duration` so the filters can ring out. Default 0.05. */\n tail?: number;\n}\n\nexport interface Render {\n samples: Float32Array;\n sampleRate: number;\n /** Length of the whole buffer, tail included, in seconds. */\n duration: number;\n /** Loudest absolute sample, before clamping. A value over 1 means the buffer was clamped. */\n peak: number;\n}\n\n/**\n * Play `writes` through the chip for `duration` seconds.\n *\n * Writes may come in any order; ones at the same moment are applied in the\n * order given, which matters — `$4015` has to enable a channel before the\n * write that loads its length counter.\n */\nexport function renderWrites(\n writes: readonly RegisterWrite[],\n duration: number,\n options: RenderOptions = {}\n): Render {\n const sampleRate = options.sampleRate ?? 44100;\n const oversample = Math.max(1, Math.round(options.oversample ?? 2));\n const gain = options.gain ?? 2.2;\n const faders = options.voiceLevels;\n const filtered = options.filters !== false;\n const rate = sampleRate * oversample;\n const total = Math.ceil(duration * rate) + Math.ceil(rate * (options.tail ?? 0.05));\n\n const ordered = writes\n .map((write, index) => ({ at: Math.max(0, Math.round(write.time * rate)), index, write }))\n .sort((a, b) => a.at - b.at || a.index - b.index);\n\n const expansion = options.expansion ?? expansionOf(writes);\n const chip = new Apu(rate, { lengthCounter: options.lengthCounter, memory: options.memory, expansion });\n const filters = new OutputFilters(rate, options.consoleBass ?? false);\n const out = new Float32Array(Math.ceil(total / oversample));\n\n const clicks = [...(options.clicks ?? [])]\n .map((click) => ({ at: Math.round(click.time * rate), strong: click.strong }))\n .sort((a, b) => a.at - b.at);\n const clickLength = Math.round(rate * 0.03);\n let clickCursor = 0;\n\n // Work in blocks: the chip fills a run of samples per channel, then one tight\n // loop mixes, filters and decimates it. A block ends early at the next write,\n // which has to land on its own sample.\n const BLOCK = 1024;\n const buffers: ChannelBuffers = {\n pulse1: new Uint8Array(BLOCK),\n pulse2: new Uint8Array(BLOCK),\n triangle: new Uint8Array(BLOCK),\n noise: new Float64Array(BLOCK),\n dmc: new Uint8Array(BLOCK),\n };\n const { pulse1: p1, pulse2: p2, triangle: tri, noise, dmc } = buffers;\n /*\n * The expansion voices, each in a buffer of its own so a fader reaches it: the FDS at voice 5,\n * the N163's channels at 6.. — its always-on slot 7 first, then 6, 5… as more are switched on —\n * the VRC6's pulse 1, pulse 2 and saw at 14, 15, 16, and the MMC5's pulse 1, pulse 2 and PCM at\n * 17, 18, 19, and the VRC7's six FM channels at 20..25.\n */\n const fdsOut = chip.fds ? new Float64Array(BLOCK) : null;\n const n163Out = chip.n163 ? Array.from({ length: 8 }, () => new Float64Array(BLOCK)) : null;\n if (fdsOut) buffers.fds = fdsOut;\n if (n163Out) buffers.n163 = n163Out;\n const vrc6Out = chip.vrc6 ? Array.from({ length: 3 }, () => new Float64Array(BLOCK)) : null;\n if (vrc6Out) buffers.vrc6 = vrc6Out;\n const fVrc6 = [14, 15, 16].map((voice) => (faders ? (faders[voice] ?? 1) : 1));\n const mmc5Out = chip.mmc5 ? Array.from({ length: 3 }, () => new Float64Array(BLOCK)) : null;\n if (mmc5Out) buffers.mmc5 = mmc5Out;\n const fMmc5 = [17, 18, 19].map((voice) => (faders ? (faders[voice] ?? 1) : 1));\n const vrc7Out = chip.vrc7 ? Array.from({ length: 6 }, () => new Float64Array(BLOCK)) : null;\n if (vrc7Out) buffers.vrc7 = vrc7Out;\n const fVrc7 = [20, 21, 22, 23, 24, 25].map((voice) => (faders ? (faders[voice] ?? 1) : 1));\n const fFds = faders ? (faders[5] ?? 1) : 1;\n const fN163 = Array.from({ length: 8 }, (_, slot) => (faders ? (faders[6 + 7 - slot] ?? 1) : 1));\n const hasClicks = clicks.length > 0;\n const f0 = faders ? (faders[0] ?? 1) : 1;\n const f1 = faders ? (faders[1] ?? 1) : 1;\n const f2 = faders ? (faders[2] ?? 1) : 1;\n const f3 = faders ? (faders[3] ?? 1) : 1;\n const f4 = faders ? (faders[4] ?? 1) : 1;\n\n let next = 0;\n let peak = 0;\n let accumulator = 0;\n let written = 0;\n let phase = 0;\n\n for (let sample = 0; sample < total; ) {\n while (next < ordered.length && ordered[next].at <= sample) {\n const { write } = ordered[next++];\n chip.write(write.address, write.value);\n }\n const until = next < ordered.length ? ordered[next].at : total;\n const count = Math.min(BLOCK, total - sample, until - sample);\n chip.render(count, buffers);\n\n for (let k = 0; k < count; k++, sample++) {\n let mixed: number;\n if (faders) {\n mixed = mixApu(p1[k] * f0, p2[k] * f1, tri[k] * f2, noise[k] * f3, dmc[k] * f4);\n } else if (noise[k] === 0 && dmc[k] === 0) {\n // The common case, from tables built with the mixer's own expressions.\n mixed = PULSE_TRIANGLE_MIX[((p1[k] + p2[k]) << 4) | tri[k]];\n } else {\n const tnd = tri[k] / 8227 + noise[k] / 12241 + dmc[k] / 22638;\n mixed = PULSE_MIX[p1[k] + p2[k]] + (tnd === 0 ? 0 : 159.79 / (1 / tnd + 100));\n }\n if (fdsOut) mixed += fdsOut[k] * fFds;\n if (n163Out) for (let slot = 0; slot < 8; slot++) mixed += n163Out[slot][k] * fN163[slot];\n if (vrc6Out) mixed += vrc6Out[0][k] * fVrc6[0] + vrc6Out[1][k] * fVrc6[1] + vrc6Out[2][k] * fVrc6[2];\n if (mmc5Out) mixed += mmc5Out[0][k] * fMmc5[0] + mmc5Out[1][k] * fMmc5[1] + mmc5Out[2][k] * fMmc5[2];\n if (vrc7Out) for (let c = 0; c < 6; c++) mixed += vrc7Out[c][k] * fVrc7[c];\n // Filtered at the oversampled rate: the low-pass then doubles as the\n // anti-aliasing filter the decimation needs.\n let value = filtered ? filters.step(mixed) : mixed;\n\n if (hasClicks) {\n while (clickCursor < clicks.length && sample >= clicks[clickCursor].at + clickLength) {\n clickCursor++;\n }\n const click = clicks[clickCursor];\n if (click && sample >= click.at) {\n // A decaying sine, added AFTER the console's filters: running it\n // through them would colour it as if it came out of the cartridge.\n const into = (sample - click.at) / clickLength;\n const hz = click.strong ? 1600 : 1050;\n value +=\n Math.sin((2 * Math.PI * hz * (sample - click.at)) / rate) *\n Math.pow(1 - into, 3) *\n (click.strong ? 0.22 : 0.14);\n }\n }\n\n accumulator += value;\n\n if (++phase === oversample) {\n phase = 0;\n // Clamped, not scaled: the filters can overshoot a little on a hard\n // transient. `peak` reports what it was BEFORE the clamp.\n const averaged = (accumulator / oversample) * gain;\n accumulator = 0;\n const magnitude = averaged < 0 ? -averaged : averaged;\n if (magnitude > peak) peak = magnitude;\n if (written < out.length) out[written++] = averaged > 1 ? 1 : averaged < -1 ? -1 : averaged;\n }\n }\n }\n\n return { samples: out, sampleRate, duration: out.length / sampleRate, peak };\n}\n\n/** The expansion chips a list of writes talks to — see `RenderOptions.expansion`. */\nexport function expansionOf(writes: readonly RegisterWrite[]): string[] {\n let fds = false;\n let n163 = false;\n let vrc6 = false;\n let mmc5 = false;\n let vrc7 = false;\n for (const w of writes) {\n if (w.address >= 0x4040 && w.address <= 0x408a) fds = true;\n else if ((w.address >= 0xf800 && w.address <= 0xffff) || (w.address >= 0x4800 && w.address <= 0x4fff)) n163 = true;\n else if (isVrc6Address(w.address)) vrc6 = true;\n else if (w.address >= 0x5000 && w.address <= 0x5015) mmc5 = true;\n else if (w.address === 0x9010 || w.address === 0x9030) vrc7 = true;\n }\n return [...(fds ? ['FDS'] : []), ...(n163 ? ['N163'] : []), ...(vrc6 ? ['VRC6'] : []), ...(mmc5 ? ['MMC5'] : []), ...(vrc7 ? ['VRC7'] : [])];\n}\n\n/** `$9000`–`$9003`, `$A000`–`$A002`, `$B000`–`$B002`: the VRC6's registers. */\nconst isVrc6Address = (address: number) =>\n (address >= 0x9000 && address <= 0x9003) || (address >= 0xa000 && address <= 0xa002) || (address >= 0xb000 && address <= 0xb002);\n"]}
package/dist/vrc7.d.ts ADDED
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Konami's VRC7: six channels of two-operator FM, a cut-down Yamaha YM2413 (OPLL), beside the 2A03
3
+ * — on one Famicom game, Lagrange Point, whose whole score is on it.
4
+ *
5
+ * A model of the chip from its documented behaviour, not a port of any emulator: each channel is a
6
+ * modulator and a carrier, sine (or half-sine) operators with an ADSR envelope in decibels, the
7
+ * modulator's self-feedback and the carrier's phase moved by the modulator. The fifteen built-in
8
+ * instruments are the chip's ROM as dumped (NESdev wiki, "VRC7 audio"); instrument 0 is the one a
9
+ * driver writes into `$00`–`$07`. It runs at the chip's own rate — 3.58 MHz / 72, 49716 Hz a
10
+ * channel — and is resampled to the output rate linearly.
11
+ *
12
+ * Registers through the NSF format's two ports: `$9010` picks a register, `$9030` writes it.
13
+ * `$E000` bit 6 holds the sound in reset (silent).
14
+ */
15
+ /** The chip's update rate: its 3.579545 MHz clock over the 72 cycles it takes to update all channels. */
16
+ export declare const VRC7_RATE: number;
17
+ /**
18
+ * The built-in instruments 1..15, bytes `$00`–`$07` each (modulator, carrier): TVSK MMMM ×2,
19
+ * KKOO OOOO, KK-Q WFFF, AAAA DDDD ×2, SSSS RRRR ×2.
20
+ */
21
+ export declare const VRC7_INSTRUMENTS: readonly (readonly number[])[];
22
+ /** Hz of a channel's 9-bit frequency and 3-bit octave: 49716 · f / 2^(19 − octave). */
23
+ export declare const vrc7Hz: (fnum: number, block: number) => number;
24
+ /** One VRC7 channel as a decoder reads it. */
25
+ export interface Vrc7ChannelSnapshot {
26
+ fnum: number;
27
+ block: number;
28
+ /** Bit 4 of `$2x`: keyed on. */
29
+ key: boolean;
30
+ /** Bit 5 of `$2x`: the slow release after key-off. */
31
+ sustain: boolean;
32
+ /** 0 is the driver's own (`$00`–`$07`), 1..15 the chip's. */
33
+ instrument: number;
34
+ /** 0 (loudest) .. 15. */
35
+ volume: number;
36
+ /** The carrier still sounding (keyed, or in its release above the floor). */
37
+ sounding: boolean;
38
+ }
39
+ export interface Vrc7Snapshot {
40
+ channels: Vrc7ChannelSnapshot[];
41
+ /** `$00`–`$07`: the instrument a driver writes itself. */
42
+ custom: number[];
43
+ /** `$E000` bit 6: the sound held in reset. */
44
+ silenced: boolean;
45
+ }
46
+ export declare class Vrc7Chip {
47
+ private readonly ratio;
48
+ /** Chip-rate steps owed to the next output sample, fractional. */
49
+ private clock;
50
+ private address;
51
+ private readonly registers;
52
+ private readonly channels;
53
+ private silenced;
54
+ /** The tremolo's and vibrato's phases, in cycles. */
55
+ private amPhase;
56
+ private vibPhase;
57
+ constructor(sampleRate: number);
58
+ /** A write to `$9010`, `$9030` or `$E000`. Returns false for any other address. */
59
+ write(address: number, value: number): boolean;
60
+ private writeRegister;
61
+ private keyOn;
62
+ private keyOff;
63
+ /** The channel's instrument: the chip's, or `$00`–`$07` (the register file's first eight bytes). */
64
+ private patchOf;
65
+ /** The effective envelope rate (0..63) of a 4-bit rate field, with key rate scaling. */
66
+ private static rate;
67
+ /** One chip-rate step of an operator's envelope. */
68
+ private static envelope;
69
+ /** One chip-rate output of channel `c`, −1..1. */
70
+ private step;
71
+ /**
72
+ * Advance `count` samples, ADDING each channel's output to `outs[0..5]` — or, for a channel
73
+ * without a buffer of its own, to `outs[6]` if given — from `offset`.
74
+ */
75
+ render(count: number, outs: readonly (Float64Array | undefined)[], offset?: number): void;
76
+ snapshot(): Vrc7Snapshot;
77
+ }
package/dist/vrc7.js ADDED
@@ -0,0 +1,303 @@
1
+ /**
2
+ * Konami's VRC7: six channels of two-operator FM, a cut-down Yamaha YM2413 (OPLL), beside the 2A03
3
+ * — on one Famicom game, Lagrange Point, whose whole score is on it.
4
+ *
5
+ * A model of the chip from its documented behaviour, not a port of any emulator: each channel is a
6
+ * modulator and a carrier, sine (or half-sine) operators with an ADSR envelope in decibels, the
7
+ * modulator's self-feedback and the carrier's phase moved by the modulator. The fifteen built-in
8
+ * instruments are the chip's ROM as dumped (NESdev wiki, "VRC7 audio"); instrument 0 is the one a
9
+ * driver writes into `$00`–`$07`. It runs at the chip's own rate — 3.58 MHz / 72, 49716 Hz a
10
+ * channel — and is resampled to the output rate linearly.
11
+ *
12
+ * Registers through the NSF format's two ports: `$9010` picks a register, `$9030` writes it.
13
+ * `$E000` bit 6 holds the sound in reset (silent).
14
+ */
15
+ /** The chip's update rate: its 3.579545 MHz clock over the 72 cycles it takes to update all channels. */
16
+ export const VRC7_RATE = 3579545 / 72;
17
+ /**
18
+ * The built-in instruments 1..15, bytes `$00`–`$07` each (modulator, carrier): TVSK MMMM ×2,
19
+ * KKOO OOOO, KK-Q WFFF, AAAA DDDD ×2, SSSS RRRR ×2.
20
+ */
21
+ export const VRC7_INSTRUMENTS = [
22
+ [0x03, 0x21, 0x05, 0x06, 0xe8, 0x81, 0x42, 0x27], // 1 Buzzy Bell
23
+ [0x13, 0x41, 0x14, 0x0d, 0xd8, 0xf6, 0x23, 0x12], // 2 Guitar
24
+ [0x11, 0x11, 0x08, 0x08, 0xfa, 0xb2, 0x20, 0x12], // 3 Wurly
25
+ [0x31, 0x61, 0x0c, 0x07, 0xa8, 0x64, 0x61, 0x27], // 4 Flute
26
+ [0x32, 0x21, 0x1e, 0x06, 0xe1, 0x76, 0x01, 0x28], // 5 Clarinet
27
+ [0x02, 0x01, 0x06, 0x00, 0xa3, 0xe2, 0xf4, 0xf4], // 6 Synth
28
+ [0x21, 0x61, 0x1d, 0x07, 0x82, 0x81, 0x11, 0x07], // 7 Trumpet
29
+ [0x23, 0x21, 0x22, 0x17, 0xa2, 0x72, 0x01, 0x17], // 8 Organ
30
+ [0x35, 0x11, 0x25, 0x00, 0x40, 0x73, 0x72, 0x01], // 9 Bells
31
+ [0xb5, 0x01, 0x0f, 0x0f, 0xa8, 0xa5, 0x51, 0x02], // A Vibes
32
+ [0x17, 0xc1, 0x24, 0x07, 0xf8, 0xf8, 0x22, 0x12], // B Vibraphone
33
+ [0x71, 0x23, 0x11, 0x06, 0x65, 0x74, 0x18, 0x16], // C Tutti
34
+ [0x01, 0x02, 0xd3, 0x05, 0xc9, 0x95, 0x03, 0x02], // D Fretless
35
+ [0x61, 0x63, 0x0c, 0x00, 0x94, 0xc0, 0x33, 0xf6], // E Synth Bass
36
+ [0x21, 0x72, 0x0d, 0x00, 0xc1, 0xd5, 0x56, 0x06], // F Sweep
37
+ ];
38
+ /** Hz of a channel's 9-bit frequency and 3-bit octave: 49716 · f / 2^(19 − octave). */
39
+ export const vrc7Hz = (fnum, block) => (VRC7_RATE * fnum) / Math.pow(2, 19 - block);
40
+ /**
41
+ * Peak output of one channel at full level (carrier at 0 dB), in `mixApu` units: about as loud as
42
+ * a 2A03 pulse at 15 swings, so the six channels sit in the mix as the reference players put them.
43
+ */
44
+ const VRC7_FULL = 0.12;
45
+ /** The multiplier field: ×½, ×1 … ×15, with 10/12/15 doubled up as on the chip. */
46
+ const MULTIPLIER = [0.5, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 12, 12, 15, 15];
47
+ /** Key level scaling at octave 7 by the frequency's top four bits, in dB, before the per-octave fall. */
48
+ const KSL_BASE = [0, 9, 12, 13.875, 15, 16.125, 16.875, 17.625, 18, 18.75, 19.125, 19.5, 19.875, 20.25, 20.625, 21];
49
+ /** The KSL field → the share of `KSL_BASE` taken: none, 1.5, 3 and 6 dB an octave. */
50
+ const KSL_SHIFT = [0, 0.5, 1, 2];
51
+ /** Below this attenuation the envelope is silent. */
52
+ const SILENT_DB = 48;
53
+ const SINE = Float64Array.from({ length: 1024 }, (_, i) => Math.sin((2 * Math.PI * i) / 1024));
54
+ /** Tremolo: 3.7 Hz, 4.8 dB deep. Vibrato: 6.4 Hz, ±14 cents. */
55
+ const AM_HZ = 3.7;
56
+ const AM_DB = 4.8;
57
+ const VIB_HZ = 6.4;
58
+ const VIB_CENTS = 14;
59
+ const VIB_DEPTH = (VIB_CENTS / 1200) * Math.LN2;
60
+ const newOperator = () => ({ phase: 0, stage: 'off', db: SILENT_DB, out1: 0, out2: 0 });
61
+ /**
62
+ * Per chip step, by effective rate 0..63: the share of `(dB + 3)` an attack takes off (silence to
63
+ * full in 2.826 s at rate 4, the OPL's table, twice as fast every 4), and the dB a decay adds (96 dB
64
+ * over 39.28 s at rate 4).
65
+ */
66
+ const ATTACK_STEP = Float64Array.from({ length: 64 }, (_, rate) => Math.log(17) / (2.826 * Math.pow(2, -(rate - 4) / 4)) / VRC7_RATE);
67
+ const DECAY_STEP = Float64Array.from({ length: 64 }, (_, rate) => 96 / (39.28 * Math.pow(2, -(rate - 4) / 4)) / VRC7_RATE);
68
+ /** 10^(−dB/20) at 1/64 dB steps, 0..128 dB. */
69
+ const DB_STEPS = 64;
70
+ const AMPLITUDE = Float64Array.from({ length: 128 * DB_STEPS + 1 }, (_, i) => Math.pow(10, -i / DB_STEPS / 20));
71
+ const amplitudeOf = (db) => (db >= 128 ? 0 : AMPLITUDE[(db * DB_STEPS) | 0]);
72
+ export class Vrc7Chip {
73
+ constructor(sampleRate) {
74
+ /** Chip-rate steps owed to the next output sample, fractional. */
75
+ this.clock = 0;
76
+ this.address = 0;
77
+ this.registers = new Uint8Array(0x40);
78
+ this.channels = Array.from({ length: 6 }, () => ({
79
+ fnum: 0,
80
+ block: 0,
81
+ key: false,
82
+ sustain: false,
83
+ instrument: 0,
84
+ volume: 0,
85
+ mod: newOperator(),
86
+ car: newOperator(),
87
+ previous: 0,
88
+ current: 0,
89
+ }));
90
+ this.silenced = false;
91
+ /** The tremolo's and vibrato's phases, in cycles. */
92
+ this.amPhase = 0;
93
+ this.vibPhase = 0;
94
+ this.ratio = VRC7_RATE / sampleRate;
95
+ }
96
+ /** A write to `$9010`, `$9030` or `$E000`. Returns false for any other address. */
97
+ write(address, value) {
98
+ const v = value & 0xff;
99
+ if (address === 0x9010) {
100
+ this.address = v & 0x3f;
101
+ return true;
102
+ }
103
+ if (address === 0x9030) {
104
+ this.writeRegister(this.address, v);
105
+ return true;
106
+ }
107
+ if (address === 0xe000) {
108
+ this.silenced = (v & 0x40) !== 0;
109
+ // Shared with the mapper's mirroring bits: not ours to claim.
110
+ return false;
111
+ }
112
+ return false;
113
+ }
114
+ writeRegister(register, v) {
115
+ this.registers[register] = v;
116
+ const k = register & 0x0f;
117
+ if (k > 5)
118
+ return;
119
+ const c = this.channels[k];
120
+ switch (register & 0xf0) {
121
+ case 0x10:
122
+ c.fnum = (c.fnum & 0x100) | v;
123
+ break;
124
+ case 0x20: {
125
+ c.fnum = (c.fnum & 0xff) | ((v & 1) << 8);
126
+ c.block = (v >> 1) & 7;
127
+ c.sustain = (v & 0x20) !== 0;
128
+ const key = (v & 0x10) !== 0;
129
+ if (key && !c.key)
130
+ this.keyOn(c);
131
+ else if (!key && c.key)
132
+ this.keyOff(c);
133
+ c.key = key;
134
+ break;
135
+ }
136
+ case 0x30:
137
+ c.instrument = v >> 4;
138
+ c.volume = v & 0x0f;
139
+ break;
140
+ }
141
+ }
142
+ keyOn(c) {
143
+ for (const op of [c.mod, c.car]) {
144
+ op.phase = 0;
145
+ op.stage = 'attack';
146
+ }
147
+ c.mod.out1 = c.mod.out2 = 0;
148
+ }
149
+ keyOff(c) {
150
+ for (const op of [c.mod, c.car])
151
+ if (op.stage !== 'off')
152
+ op.stage = 'release';
153
+ }
154
+ /** The channel's instrument: the chip's, or `$00`–`$07` (the register file's first eight bytes). */
155
+ patchOf(c) {
156
+ return c.instrument === 0 ? this.registers : VRC7_INSTRUMENTS[c.instrument - 1];
157
+ }
158
+ /** The effective envelope rate (0..63) of a 4-bit rate field, with key rate scaling. */
159
+ static rate(field, c, ksr) {
160
+ if (field === 0)
161
+ return 0;
162
+ const keyCode = (c.block << 1) | (c.fnum >> 8);
163
+ return Math.min(63, field * 4 + (ksr ? keyCode : keyCode >> 2));
164
+ }
165
+ /** One chip-rate step of an operator's envelope. */
166
+ static envelope(op, c, flags, ad, sr, carrier) {
167
+ const ksr = (flags & 0x10) !== 0;
168
+ const sustained = (flags & 0x20) !== 0;
169
+ switch (op.stage) {
170
+ case 'attack': {
171
+ const rate = Vrc7Chip.rate(ad >> 4, c, ksr);
172
+ if (rate === 0)
173
+ break;
174
+ if (rate >= 60)
175
+ op.db = 0;
176
+ else
177
+ op.db -= (op.db + 3) * ATTACK_STEP[rate];
178
+ if (op.db <= 0.05) {
179
+ op.db = 0;
180
+ op.stage = 'decay';
181
+ }
182
+ break;
183
+ }
184
+ case 'decay': {
185
+ const level = (sr >> 4) * 3;
186
+ const rate = Vrc7Chip.rate(ad & 0x0f, c, ksr);
187
+ if (rate)
188
+ op.db += DECAY_STEP[rate];
189
+ if (op.db >= level) {
190
+ op.db = level;
191
+ op.stage = 'sustain';
192
+ }
193
+ break;
194
+ }
195
+ case 'sustain':
196
+ // A sustained voice holds; a percussive one goes on falling at its release rate.
197
+ if (!sustained && sr & 0x0f)
198
+ op.db += DECAY_STEP[Vrc7Chip.rate(sr & 0x0f, c, ksr)];
199
+ break;
200
+ case 'release': {
201
+ // The modulator releases with the carrier; the sustain bit slows a released note to rate 5.
202
+ const field = carrier && c.sustain ? 5 : sr & 0x0f;
203
+ if (field)
204
+ op.db += DECAY_STEP[Vrc7Chip.rate(field, c, ksr)];
205
+ break;
206
+ }
207
+ case 'off':
208
+ break;
209
+ }
210
+ if (op.db >= SILENT_DB) {
211
+ op.db = SILENT_DB;
212
+ if (op.stage !== 'attack')
213
+ op.stage = op.stage === 'sustain' && sustained ? 'sustain' : 'off';
214
+ }
215
+ }
216
+ /** One chip-rate output of channel `c`, −1..1. */
217
+ step(c, am, vib) {
218
+ const patch = this.patchOf(c);
219
+ const mFlags = patch[0], cFlags = patch[1], mLevel = patch[2], cLevel = patch[3];
220
+ const mAd = patch[4], cAd = patch[5], mSr = patch[6], cSr = patch[7];
221
+ Vrc7Chip.envelope(c.mod, c, mFlags, mAd, mSr, false);
222
+ Vrc7Chip.envelope(c.car, c, cFlags, cAd, cSr, true);
223
+ const base = (c.fnum << c.block) / 524288;
224
+ const kslDb = Math.max(0, KSL_BASE[c.fnum >> 5] - (7 - c.block) * 6);
225
+ // Modulator: self-feedback of its last two outputs, 0, π/16 … 4π.
226
+ const fb = cLevel & 7;
227
+ const mod = c.mod;
228
+ const mInc = base * MULTIPLIER[mFlags & 0x0f] * (mFlags & 0x40 ? vib : 1);
229
+ mod.phase = (mod.phase + mInc) % 1;
230
+ const mDb = mod.db + (mLevel & 0x3f) * 0.75 + kslDb * KSL_SHIFT[mLevel >> 6] + (mFlags & 0x80 ? am : 0);
231
+ let mOut = 0;
232
+ if (mod.stage !== 'off' && mDb < SILENT_DB + 30) {
233
+ const feedback = fb ? (mod.out1 + mod.out2) * Math.pow(2, fb - 7) : 0;
234
+ let s = SINE[(((mod.phase + feedback) * 1024) | 0) & 1023];
235
+ if (cLevel & 0x08 && s < 0)
236
+ s = 0;
237
+ mOut = s * amplitudeOf(mDb);
238
+ }
239
+ mod.out2 = mod.out1;
240
+ mod.out1 = mOut;
241
+ // Carrier: its phase moved by the modulator's output, ±4π at full.
242
+ const car = c.car;
243
+ const cInc = base * MULTIPLIER[cFlags & 0x0f] * (cFlags & 0x40 ? vib : 1);
244
+ car.phase = (car.phase + cInc) % 1;
245
+ if (car.stage === 'off')
246
+ return 0;
247
+ const cDb = car.db + c.volume * 3 + kslDb * KSL_SHIFT[cLevel >> 6] + (cFlags & 0x80 ? am : 0);
248
+ if (cDb >= SILENT_DB)
249
+ return 0;
250
+ let s = SINE[(((car.phase + mOut * 2) * 1024) | 0) & 1023];
251
+ if (cLevel & 0x10 && s < 0)
252
+ s = 0;
253
+ return s * amplitudeOf(cDb);
254
+ }
255
+ /**
256
+ * Advance `count` samples, ADDING each channel's output to `outs[0..5]` — or, for a channel
257
+ * without a buffer of its own, to `outs[6]` if given — from `offset`.
258
+ */
259
+ render(count, outs, offset = 0) {
260
+ for (let k = 0; k < count; k++) {
261
+ this.clock += this.ratio;
262
+ while (this.clock >= 1) {
263
+ this.clock -= 1;
264
+ this.amPhase = (this.amPhase + AM_HZ / VRC7_RATE) % 1;
265
+ this.vibPhase = (this.vibPhase + VIB_HZ / VRC7_RATE) % 1;
266
+ // Tremolo 0..AM_DB down; vibrato ±VIB_CENTS, near enough linear at that size.
267
+ const am = AM_DB * 0.5 * (1 + SINE[(this.amPhase * 1024) | 0]);
268
+ const vib = 1 + VIB_DEPTH * SINE[(this.vibPhase * 1024) | 0];
269
+ for (const c of this.channels) {
270
+ c.previous = c.current;
271
+ c.current = this.silenced ? 0 : this.step(c, am, vib);
272
+ }
273
+ }
274
+ // Between the chip's last two outputs, by how far the next one is.
275
+ const t = this.clock;
276
+ for (let ch = 0; ch < 6; ch++) {
277
+ const out = outs[ch] ?? outs[6];
278
+ if (!out)
279
+ continue;
280
+ const c = this.channels[ch];
281
+ const value = c.previous + (c.current - c.previous) * t;
282
+ if (value !== 0)
283
+ out[offset + k] += value * VRC7_FULL;
284
+ }
285
+ }
286
+ }
287
+ snapshot() {
288
+ return {
289
+ channels: this.channels.map((c) => ({
290
+ fnum: c.fnum,
291
+ block: c.block,
292
+ key: c.key,
293
+ sustain: c.sustain,
294
+ instrument: c.instrument,
295
+ volume: c.volume,
296
+ sounding: c.car.stage !== 'off' && c.car.db < SILENT_DB,
297
+ })),
298
+ custom: Array.from(this.registers.subarray(0, 8)),
299
+ silenced: this.silenced,
300
+ };
301
+ }
302
+ }
303
+ //# sourceMappingURL=vrc7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vrc7.js","sourceRoot":"","sources":["../src/vrc7.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,yGAAyG;AACzG,MAAM,CAAC,MAAM,SAAS,GAAG,OAAO,GAAG,EAAE,CAAC;AAEtC;;;GAGG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAmC;IAC9D,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,eAAe;IACjE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,WAAW;IAC7D,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,UAAU;IAC5D,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,UAAU;IAC5D,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,aAAa;IAC/D,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,UAAU;IAC5D,CAAC,IAAI,EAAE,IA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AC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;gBAClC,IAAI,EAAE,CAAC,CAAC,IAAI;gBACZ,KAAK,EAAE,CAAC,CAAC,KAAK;gBACd,GAAG,EAAE,CAAC,CAAC,GAAG;gBACV,OAAO,EAAE,CAAC,CAAC,OAAO;gBAClB,UAAU,EAAE,CAAC,CAAC,UAAU;gBACxB,MAAM,EAAE,CAAC,CAAC,MAAM;gBAChB,QAAQ,EAAE,CAAC,CAAC,GAAG,CAAC,KAAK,KAAK,KAAK,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,GAAG,SAAS;aACxD,CAAC,CAAC;YACH,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;YACjD,QAAQ,EAAE,IAAI,CAAC,QAAQ;SACxB,CAAC;IACJ,CAAC;CACF","sourcesContent":["/**\n * Konami's VRC7: six channels of two-operator FM, a cut-down Yamaha YM2413 (OPLL), beside the 2A03\n * — on one Famicom game, Lagrange Point, whose whole score is on it.\n *\n * A model of the chip from its documented behaviour, not a port of any emulator: each channel is a\n * modulator and a carrier, sine (or half-sine) operators with an ADSR envelope in decibels, the\n * modulator's self-feedback and the carrier's phase moved by the modulator. The fifteen built-in\n * instruments are the chip's ROM as dumped (NESdev wiki, \"VRC7 audio\"); instrument 0 is the one a\n * driver writes into `$00`–`$07`. It runs at the chip's own rate — 3.58 MHz / 72, 49716 Hz a\n * channel — and is resampled to the output rate linearly.\n *\n * Registers through the NSF format's two ports: `$9010` picks a register, `$9030` writes it.\n * `$E000` bit 6 holds the sound in reset (silent).\n */\n\n/** The chip's update rate: its 3.579545 MHz clock over the 72 cycles it takes to update all channels. */\nexport const VRC7_RATE = 3579545 / 72;\n\n/**\n * The built-in instruments 1..15, bytes `$00`–`$07` each (modulator, carrier): TVSK MMMM ×2,\n * KKOO OOOO, KK-Q WFFF, AAAA DDDD ×2, SSSS RRRR ×2.\n */\nexport const VRC7_INSTRUMENTS: readonly (readonly number[])[] = [\n [0x03, 0x21, 0x05, 0x06, 0xe8, 0x81, 0x42, 0x27], // 1 Buzzy Bell\n [0x13, 0x41, 0x14, 0x0d, 0xd8, 0xf6, 0x23, 0x12], // 2 Guitar\n [0x11, 0x11, 0x08, 0x08, 0xfa, 0xb2, 0x20, 0x12], // 3 Wurly\n [0x31, 0x61, 0x0c, 0x07, 0xa8, 0x64, 0x61, 0x27], // 4 Flute\n [0x32, 0x21, 0x1e, 0x06, 0xe1, 0x76, 0x01, 0x28], // 5 Clarinet\n [0x02, 0x01, 0x06, 0x00, 0xa3, 0xe2, 0xf4, 0xf4], // 6 Synth\n [0x21, 0x61, 0x1d, 0x07, 0x82, 0x81, 0x11, 0x07], // 7 Trumpet\n [0x23, 0x21, 0x22, 0x17, 0xa2, 0x72, 0x01, 0x17], // 8 Organ\n [0x35, 0x11, 0x25, 0x00, 0x40, 0x73, 0x72, 0x01], // 9 Bells\n [0xb5, 0x01, 0x0f, 0x0f, 0xa8, 0xa5, 0x51, 0x02], // A Vibes\n [0x17, 0xc1, 0x24, 0x07, 0xf8, 0xf8, 0x22, 0x12], // B Vibraphone\n [0x71, 0x23, 0x11, 0x06, 0x65, 0x74, 0x18, 0x16], // C Tutti\n [0x01, 0x02, 0xd3, 0x05, 0xc9, 0x95, 0x03, 0x02], // D Fretless\n [0x61, 0x63, 0x0c, 0x00, 0x94, 0xc0, 0x33, 0xf6], // E Synth Bass\n [0x21, 0x72, 0x0d, 0x00, 0xc1, 0xd5, 0x56, 0x06], // F Sweep\n];\n\n/** Hz of a channel's 9-bit frequency and 3-bit octave: 49716 · f / 2^(19 − octave). */\nexport const vrc7Hz = (fnum: number, block: number) => (VRC7_RATE * fnum) / Math.pow(2, 19 - block);\n\n/**\n * Peak output of one channel at full level (carrier at 0 dB), in `mixApu` units: about as loud as\n * a 2A03 pulse at 15 swings, so the six channels sit in the mix as the reference players put them.\n */\nconst VRC7_FULL = 0.12;\n\n/** The multiplier field: ×½, ×1 … ×15, with 10/12/15 doubled up as on the chip. */\nconst MULTIPLIER = [0.5, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 12, 12, 15, 15];\n/** Key level scaling at octave 7 by the frequency's top four bits, in dB, before the per-octave fall. */\nconst KSL_BASE = [0, 9, 12, 13.875, 15, 16.125, 16.875, 17.625, 18, 18.75, 19.125, 19.5, 19.875, 20.25, 20.625, 21];\n/** The KSL field → the share of `KSL_BASE` taken: none, 1.5, 3 and 6 dB an octave. */\nconst KSL_SHIFT = [0, 0.5, 1, 2];\n/** Below this attenuation the envelope is silent. */\nconst SILENT_DB = 48;\nconst SINE = Float64Array.from({ length: 1024 }, (_, i) => Math.sin((2 * Math.PI * i) / 1024));\n/** Tremolo: 3.7 Hz, 4.8 dB deep. Vibrato: 6.4 Hz, ±14 cents. */\nconst AM_HZ = 3.7;\nconst AM_DB = 4.8;\nconst VIB_HZ = 6.4;\nconst VIB_CENTS = 14;\nconst VIB_DEPTH = (VIB_CENTS / 1200) * Math.LN2;\n\ntype Stage = 'attack' | 'decay' | 'sustain' | 'release' | 'off';\n\ninterface Operator {\n /** Phase in cycles, 0..1. */\n phase: number;\n stage: Stage;\n /** Envelope attenuation in dB, 0 (loudest) .. 48 (silent). */\n db: number;\n /** The last two outputs (the modulator's feedback), −1..1. */\n out1: number;\n out2: number;\n}\n\ninterface Channel {\n fnum: number;\n block: number;\n key: boolean;\n sustain: boolean;\n instrument: number;\n /** 0 (loudest) .. 15, in 3 dB steps. */\n volume: number;\n mod: Operator;\n car: Operator;\n /** The channel's last two chip-rate outputs, for the resampler. */\n previous: number;\n current: number;\n}\n\n/** One VRC7 channel as a decoder reads it. */\nexport interface Vrc7ChannelSnapshot {\n fnum: number;\n block: number;\n /** Bit 4 of `$2x`: keyed on. */\n key: boolean;\n /** Bit 5 of `$2x`: the slow release after key-off. */\n sustain: boolean;\n /** 0 is the driver's own (`$00`–`$07`), 1..15 the chip's. */\n instrument: number;\n /** 0 (loudest) .. 15. */\n volume: number;\n /** The carrier still sounding (keyed, or in its release above the floor). */\n sounding: boolean;\n}\n\nexport interface Vrc7Snapshot {\n channels: Vrc7ChannelSnapshot[];\n /** `$00`–`$07`: the instrument a driver writes itself. */\n custom: number[];\n /** `$E000` bit 6: the sound held in reset. */\n silenced: boolean;\n}\n\nconst newOperator = (): Operator => ({ phase: 0, stage: 'off', db: SILENT_DB, out1: 0, out2: 0 });\n\n/**\n * Per chip step, by effective rate 0..63: the share of `(dB + 3)` an attack takes off (silence to\n * full in 2.826 s at rate 4, the OPL's table, twice as fast every 4), and the dB a decay adds (96 dB\n * over 39.28 s at rate 4).\n */\nconst ATTACK_STEP = Float64Array.from({ length: 64 }, (_, rate) =>\n Math.log(17) / (2.826 * Math.pow(2, -(rate - 4) / 4)) / VRC7_RATE\n);\nconst DECAY_STEP = Float64Array.from({ length: 64 }, (_, rate) => 96 / (39.28 * Math.pow(2, -(rate - 4) / 4)) / VRC7_RATE);\n/** 10^(−dB/20) at 1/64 dB steps, 0..128 dB. */\nconst DB_STEPS = 64;\nconst AMPLITUDE = Float64Array.from({ length: 128 * DB_STEPS + 1 }, (_, i) => Math.pow(10, -i / DB_STEPS / 20));\nconst amplitudeOf = (db: number) => (db >= 128 ? 0 : AMPLITUDE[(db * DB_STEPS) | 0]);\n\nexport class Vrc7Chip {\n private readonly ratio: number;\n /** Chip-rate steps owed to the next output sample, fractional. */\n private clock = 0;\n private address = 0;\n private readonly registers = new Uint8Array(0x40);\n private readonly channels: Channel[] = Array.from({ length: 6 }, () => ({\n fnum: 0,\n block: 0,\n key: false,\n sustain: false,\n instrument: 0,\n volume: 0,\n mod: newOperator(),\n car: newOperator(),\n previous: 0,\n current: 0,\n }));\n private silenced = false;\n /** The tremolo's and vibrato's phases, in cycles. */\n private amPhase = 0;\n private vibPhase = 0;\n\n constructor(sampleRate: number) {\n this.ratio = VRC7_RATE / sampleRate;\n }\n\n /** A write to `$9010`, `$9030` or `$E000`. Returns false for any other address. */\n write(address: number, value: number): boolean {\n const v = value & 0xff;\n if (address === 0x9010) {\n this.address = v & 0x3f;\n return true;\n }\n if (address === 0x9030) {\n this.writeRegister(this.address, v);\n return true;\n }\n if (address === 0xe000) {\n this.silenced = (v & 0x40) !== 0;\n // Shared with the mapper's mirroring bits: not ours to claim.\n return false;\n }\n return false;\n }\n\n private writeRegister(register: number, v: number) {\n this.registers[register] = v;\n const k = register & 0x0f;\n if (k > 5) return;\n const c = this.channels[k];\n switch (register & 0xf0) {\n case 0x10:\n c.fnum = (c.fnum & 0x100) | v;\n break;\n case 0x20: {\n c.fnum = (c.fnum & 0xff) | ((v & 1) << 8);\n c.block = (v >> 1) & 7;\n c.sustain = (v & 0x20) !== 0;\n const key = (v & 0x10) !== 0;\n if (key && !c.key) this.keyOn(c);\n else if (!key && c.key) this.keyOff(c);\n c.key = key;\n break;\n }\n case 0x30:\n c.instrument = v >> 4;\n c.volume = v & 0x0f;\n break;\n }\n }\n\n private keyOn(c: Channel) {\n for (const op of [c.mod, c.car]) {\n op.phase = 0;\n op.stage = 'attack';\n }\n c.mod.out1 = c.mod.out2 = 0;\n }\n\n private keyOff(c: Channel) {\n for (const op of [c.mod, c.car]) if (op.stage !== 'off') op.stage = 'release';\n }\n\n /** The channel's instrument: the chip's, or `$00`–`$07` (the register file's first eight bytes). */\n private patchOf(c: Channel): ArrayLike<number> {\n return c.instrument === 0 ? this.registers : VRC7_INSTRUMENTS[c.instrument - 1];\n }\n\n /** The effective envelope rate (0..63) of a 4-bit rate field, with key rate scaling. */\n private static rate(field: number, c: Channel, ksr: boolean) {\n if (field === 0) return 0;\n const keyCode = (c.block << 1) | (c.fnum >> 8);\n return Math.min(63, field * 4 + (ksr ? keyCode : keyCode >> 2));\n }\n\n /** One chip-rate step of an operator's envelope. */\n private static envelope(op: Operator, c: Channel, flags: number, ad: number, sr: number, carrier: boolean) {\n const ksr = (flags & 0x10) !== 0;\n const sustained = (flags & 0x20) !== 0;\n switch (op.stage) {\n case 'attack': {\n const rate = Vrc7Chip.rate(ad >> 4, c, ksr);\n if (rate === 0) break;\n if (rate >= 60) op.db = 0;\n else op.db -= (op.db + 3) * ATTACK_STEP[rate];\n if (op.db <= 0.05) {\n op.db = 0;\n op.stage = 'decay';\n }\n break;\n }\n case 'decay': {\n const level = (sr >> 4) * 3;\n const rate = Vrc7Chip.rate(ad & 0x0f, c, ksr);\n if (rate) op.db += DECAY_STEP[rate];\n if (op.db >= level) {\n op.db = level;\n op.stage = 'sustain';\n }\n break;\n }\n case 'sustain':\n // A sustained voice holds; a percussive one goes on falling at its release rate.\n if (!sustained && sr & 0x0f) op.db += DECAY_STEP[Vrc7Chip.rate(sr & 0x0f, c, ksr)];\n break;\n case 'release': {\n // The modulator releases with the carrier; the sustain bit slows a released note to rate 5.\n const field = carrier && c.sustain ? 5 : sr & 0x0f;\n if (field) op.db += DECAY_STEP[Vrc7Chip.rate(field, c, ksr)];\n break;\n }\n case 'off':\n break;\n }\n if (op.db >= SILENT_DB) {\n op.db = SILENT_DB;\n if (op.stage !== 'attack') op.stage = op.stage === 'sustain' && sustained ? 'sustain' : 'off';\n }\n }\n\n /** One chip-rate output of channel `c`, −1..1. */\n private step(c: Channel, am: number, vib: number): number {\n const patch = this.patchOf(c);\n const mFlags = patch[0], cFlags = patch[1], mLevel = patch[2], cLevel = patch[3];\n const mAd = patch[4], cAd = patch[5], mSr = patch[6], cSr = patch[7];\n Vrc7Chip.envelope(c.mod, c, mFlags, mAd, mSr, false);\n Vrc7Chip.envelope(c.car, c, cFlags, cAd, cSr, true);\n const base = (c.fnum << c.block) / 524288;\n const kslDb = Math.max(0, KSL_BASE[c.fnum >> 5] - (7 - c.block) * 6);\n\n // Modulator: self-feedback of its last two outputs, 0, π/16 … 4π.\n const fb = cLevel & 7;\n const mod = c.mod;\n const mInc = base * MULTIPLIER[mFlags & 0x0f] * (mFlags & 0x40 ? vib : 1);\n mod.phase = (mod.phase + mInc) % 1;\n const mDb = mod.db + (mLevel & 0x3f) * 0.75 + kslDb * KSL_SHIFT[mLevel >> 6] + (mFlags & 0x80 ? am : 0);\n let mOut = 0;\n if (mod.stage !== 'off' && mDb < SILENT_DB + 30) {\n const feedback = fb ? (mod.out1 + mod.out2) * Math.pow(2, fb - 7) : 0;\n let s = SINE[(((mod.phase + feedback) * 1024) | 0) & 1023];\n if (cLevel & 0x08 && s < 0) s = 0;\n mOut = s * amplitudeOf(mDb);\n }\n mod.out2 = mod.out1;\n mod.out1 = mOut;\n\n // Carrier: its phase moved by the modulator's output, ±4π at full.\n const car = c.car;\n const cInc = base * MULTIPLIER[cFlags & 0x0f] * (cFlags & 0x40 ? vib : 1);\n car.phase = (car.phase + cInc) % 1;\n if (car.stage === 'off') return 0;\n const cDb = car.db + c.volume * 3 + kslDb * KSL_SHIFT[cLevel >> 6] + (cFlags & 0x80 ? am : 0);\n if (cDb >= SILENT_DB) return 0;\n let s = SINE[(((car.phase + mOut * 2) * 1024) | 0) & 1023];\n if (cLevel & 0x10 && s < 0) s = 0;\n return s * amplitudeOf(cDb);\n }\n\n /**\n * Advance `count` samples, ADDING each channel's output to `outs[0..5]` — or, for a channel\n * without a buffer of its own, to `outs[6]` if given — from `offset`.\n */\n render(count: number, outs: readonly (Float64Array | undefined)[], offset = 0) {\n for (let k = 0; k < count; k++) {\n this.clock += this.ratio;\n while (this.clock >= 1) {\n this.clock -= 1;\n this.amPhase = (this.amPhase + AM_HZ / VRC7_RATE) % 1;\n this.vibPhase = (this.vibPhase + VIB_HZ / VRC7_RATE) % 1;\n // Tremolo 0..AM_DB down; vibrato ±VIB_CENTS, near enough linear at that size.\n const am = AM_DB * 0.5 * (1 + SINE[(this.amPhase * 1024) | 0]);\n const vib = 1 + VIB_DEPTH * SINE[(this.vibPhase * 1024) | 0];\n for (const c of this.channels) {\n c.previous = c.current;\n c.current = this.silenced ? 0 : this.step(c, am, vib);\n }\n }\n // Between the chip's last two outputs, by how far the next one is.\n const t = this.clock;\n for (let ch = 0; ch < 6; ch++) {\n const out = outs[ch] ?? outs[6];\n if (!out) continue;\n const c = this.channels[ch];\n const value = c.previous + (c.current - c.previous) * t;\n if (value !== 0) out[offset + k] += value * VRC7_FULL;\n }\n }\n }\n\n snapshot(): Vrc7Snapshot {\n return {\n channels: this.channels.map((c) => ({\n fnum: c.fnum,\n block: c.block,\n key: c.key,\n sustain: c.sustain,\n instrument: c.instrument,\n volume: c.volume,\n sounding: c.car.stage !== 'off' && c.car.db < SILENT_DB,\n })),\n custom: Array.from(this.registers.subarray(0, 8)),\n silenced: this.silenced,\n };\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xromdev/apu",
3
- "version": "0.5.2",
3
+ "version": "0.6.0",
4
4
  "description": "The NES sound chip (2A03 APU) in TypeScript: register writes in, samples out.",
5
5
  "license": "MIT",
6
6
  "type": "module",