@xromdev/apu 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/notes.d.ts +45 -4
- package/dist/notes.js +96 -9
- package/dist/notes.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -79,6 +79,20 @@ that long — and notes, loop points and the metronome follow them.
|
|
|
79
79
|
`tickToSeconds(input, tick)` and `secondsToTick` convert for anything drawn
|
|
80
80
|
alongside.
|
|
81
81
|
|
|
82
|
+
Samples struck on the DMC — a kick, a snare, a voice — go in `hits`, each
|
|
83
|
+
`[sampleIndex, startTick, ticks, rate, loop, level]`, with the bytes they play in
|
|
84
|
+
`samples` as `{ address, bytes }`. `level` is the value the driver loads into
|
|
85
|
+
`$4011` just before the hit, or -1 for none: that jump is part of the sound, the
|
|
86
|
+
thump of a kick. The chip reads the bytes from where they sit in cartridge
|
|
87
|
+
memory; `sampleMemory(samples)` lays them out there for a `memory` option of
|
|
88
|
+
your own.
|
|
89
|
+
|
|
90
|
+
A note whose level does not go in a straight line from `volume` to `volumeEnd`
|
|
91
|
+
— a driver that steps it frame by frame — points into `levels` with its last
|
|
92
|
+
field, `levelIndex`. A curve is `[position 0..1, level 0..15]` at each change,
|
|
93
|
+
and holds from one point to the next, as a driver writes whole levels a frame at
|
|
94
|
+
a time. Pulse and noise notes take them; `levelAt(curve, position)` reads one.
|
|
95
|
+
|
|
82
96
|
`notesToWrites` gives you the writes on their own, if you want to see them.
|
|
83
97
|
|
|
84
98
|
### Live
|
|
@@ -226,6 +240,8 @@ test suite checks the fast paths against the plain ones bit for bit.
|
|
|
226
240
|
| `renderWrites(writes, seconds, options?)` | Register writes → `{ samples, sampleRate, duration, peak }`. |
|
|
227
241
|
| `renderNotes(input, options?)` / `notesToWrites(input)` | Decoded notes → samples, or → the writes a driver would make. |
|
|
228
242
|
| `tickToSeconds(input, tick)` / `secondsToTick(input, s)` | Ticks ↔ seconds through the input's `tempo` changes. |
|
|
243
|
+
| `sampleMemory(samples)` | DMC samples laid out where the chip reads them — cartridge memory for the `memory` option. |
|
|
244
|
+
| `levelAt(curve, position)` | The level a note's level curve holds at a point of the note. |
|
|
229
245
|
| `new Apu(sampleRate, { memory?, lengthCounter? })` | The chip itself: `write(address, value)`, `render(count, buffers)`, `levels()`, `snapshot()`. |
|
|
230
246
|
| `mixApu(p1, p2, tri, noise, dmc?)`, `OutputFilters` | The non-linear mixer and the console's analogue stage, for use with `Apu`. |
|
|
231
247
|
| `sweepTrace(period, sweep, channel, halfFrames)` | The period the sweep unit plays, half-frame by half-frame — for drawing a swept sound. |
|
package/dist/index.d.ts
CHANGED
|
@@ -16,4 +16,4 @@ export { Apu, type ApuChipOptions, type ApuMemory, type ApuSnapshot, type Channe
|
|
|
16
16
|
export { mixApu, OutputFilters } from './mixer.js';
|
|
17
17
|
export { SWEEP_HZ, decodeSweep, sweepMutes, sweepTarget, sweepTrace, type SweepConfig, } from './sweep.js';
|
|
18
18
|
export { renderWrites, type Click, type RegisterWrite, type Render, type RenderOptions, } from './render.js';
|
|
19
|
-
export { bendAt, notesToWrites, renderNotes, type ApuInput, type ApuOptions, type ApuRender, type BendCurve, type DrumRow, type PitchedRow, secondsToTick, tickToSeconds, type TempoChange, } from './notes.js';
|
|
19
|
+
export { bendAt, levelAt, notesToWrites, renderNotes, sampleMemory, sampleSeconds, type DmcSample, type SampleRow, type ApuInput, type ApuOptions, type ApuRender, type BendCurve, type LevelCurve, type DrumRow, type PitchedRow, secondsToTick, tickToSeconds, type TempoChange, } from './notes.js';
|
package/dist/index.js
CHANGED
|
@@ -16,5 +16,5 @@ export { Apu, } from './chip.js';
|
|
|
16
16
|
export { mixApu, OutputFilters } from './mixer.js';
|
|
17
17
|
export { SWEEP_HZ, decodeSweep, sweepMutes, sweepTarget, sweepTrace, } from './sweep.js';
|
|
18
18
|
export { renderWrites, } from './render.js';
|
|
19
|
-
export { bendAt, notesToWrites, renderNotes, secondsToTick, tickToSeconds, } from './notes.js';
|
|
19
|
+
export { bendAt, levelAt, notesToWrites, renderNotes, sampleMemory, sampleSeconds, secondsToTick, tickToSeconds, } from './notes.js';
|
|
20
20
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,MAAM,EACN,WAAW,EACX,cAAc,EACd,QAAQ,EACR,YAAY,EACZ,aAAa,EACb,gBAAgB,EAChB,cAAc,GACf,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,GAAG,GAKJ,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EACL,QAAQ,EACR,WAAW,EACX,UAAU,EACV,WAAW,EACX,UAAU,GAEX,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,YAAY,GAKb,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,MAAM,EACN,aAAa,EACb,WAAW,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,MAAM,EACN,WAAW,EACX,cAAc,EACd,QAAQ,EACR,YAAY,EACZ,aAAa,EACb,gBAAgB,EAChB,cAAc,GACf,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,GAAG,GAKJ,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EACL,QAAQ,EACR,WAAW,EACX,UAAU,EACV,WAAW,EACX,UAAU,GAEX,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,YAAY,GAKb,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,MAAM,EACN,OAAO,EACP,aAAa,EACb,WAAW,EACX,YAAY,EACZ,aAAa,EAUb,aAAa,EACb,aAAa,GAEd,MAAM,YAAY,CAAC","sourcesContent":["/**\n * @xrom/apu — the NES sound chip (2A03 APU) in TypeScript.\n *\n * Two layers, usable separately:\n *\n * - **The chip.** `renderWrites(writes, seconds)` plays a list of register\n * writes — `{ time, address: 0x4000..0x4017, value }` — and returns samples.\n * Every NES game's music reaches the speaker as writes like these, so this\n * plays any game's music once its writes are known (from an emulator trace,\n * say). `Apu` is the same chip one sample at a time, for live use.\n * - **The note adapter.** `renderNotes(input)` takes music already decoded into\n * notes and writes what a driver would have written to sound them.\n */\n\nexport {\n CPU_HZ,\n DMC_PERIODS,\n DUTY_SEQUENCES,\n FRAME_HZ,\n LENGTH_TABLE,\n NOISE_PERIODS,\n QUARTER_FRAME_HZ,\n TRIANGLE_STEPS,\n} from './constants.js';\nexport {\n Apu,\n type ApuChipOptions,\n type ApuMemory,\n type ApuSnapshot,\n type ChannelBuffers,\n} from './chip.js';\nexport { mixApu, OutputFilters } from './mixer.js';\nexport {\n SWEEP_HZ,\n decodeSweep,\n sweepMutes,\n sweepTarget,\n sweepTrace,\n type SweepConfig,\n} from './sweep.js';\nexport {\n renderWrites,\n type Click,\n type RegisterWrite,\n type Render,\n type RenderOptions,\n} from './render.js';\nexport {\n bendAt,\n levelAt,\n notesToWrites,\n renderNotes,\n sampleMemory,\n sampleSeconds,\n type DmcSample,\n type SampleRow,\n type ApuInput,\n type ApuOptions,\n type ApuRender,\n type BendCurve,\n type LevelCurve,\n type DrumRow,\n type PitchedRow,\n secondsToTick,\n tickToSeconds,\n type TempoChange,\n} from './notes.js';\n"]}
|
package/dist/notes.d.ts
CHANGED
|
@@ -26,11 +26,13 @@
|
|
|
26
26
|
import { type RegisterWrite, type RenderOptions } from './render.js';
|
|
27
27
|
/**
|
|
28
28
|
* `[midi, startTick, durationTicks, channel 0..2, volume, period, duty,
|
|
29
|
-
* volumeEnd, lengthTicks, bendIndex, envelope, sweep]` — `lengthTicks` counts at
|
|
29
|
+
* volumeEnd, lengthTicks, bendIndex, envelope, sweep, levelIndex]` — `lengthTicks` counts at
|
|
30
30
|
* 120 Hz and 0 means unlimited; `bendIndex` points into `ApuInput.bends`, or is
|
|
31
31
|
* -1; `envelope` is the low five bits of `$4000` when the chip's own envelope
|
|
32
32
|
* runs (period, and bit 4 for loop), or -1 for constant volume; `sweep` is the
|
|
33
|
-
* `$4001` byte, or -1/absent when the data has none
|
|
33
|
+
* `$4001` byte, or -1/absent when the data has none; `levelIndex`, on a pulse, points into
|
|
34
|
+
* `ApuInput.levels` for a level that does not go in a straight line from `volume` to `volumeEnd`,
|
|
35
|
+
* or is -1/absent.
|
|
34
36
|
*/
|
|
35
37
|
export type PitchedRow = readonly [
|
|
36
38
|
number,
|
|
@@ -44,20 +46,52 @@ export type PitchedRow = readonly [
|
|
|
44
46
|
number,
|
|
45
47
|
number,
|
|
46
48
|
number?,
|
|
49
|
+
number?,
|
|
47
50
|
number?
|
|
48
51
|
];
|
|
52
|
+
/**
|
|
53
|
+
* A level curve: `[position 0..1, level 0..15]` at each change of level, in order. The level holds
|
|
54
|
+
* from one point to the next — a driver writes whole levels, a frame at a time.
|
|
55
|
+
*/
|
|
56
|
+
export type LevelCurve = readonly (readonly [number, number])[];
|
|
57
|
+
/** The level a curve holds at `position`: the last point at or before it. */
|
|
58
|
+
export declare function levelAt(curve: LevelCurve, position: number): number;
|
|
49
59
|
/** A pitch curve: `[position 0..1, semitones]`, in order. */
|
|
50
60
|
export type BendCurve = readonly (readonly [number, number])[];
|
|
51
61
|
/**
|
|
52
62
|
* `[periodIndex, startTick, durationTicks, volume, volumeEnd, lengthTicks,
|
|
53
|
-
* envelope]` — a noise-channel note. `periodIndex` is the low nibble of `$400E
|
|
63
|
+
* envelope, levelIndex]` — a noise-channel note. `periodIndex` is the low nibble of `$400E`;
|
|
64
|
+
* `levelIndex` points into `ApuInput.levels`, as a pulse row's does, or is -1/absent.
|
|
65
|
+
*/
|
|
66
|
+
export type DrumRow = readonly [number, number, number, number, number, number, number?, number?];
|
|
67
|
+
/**
|
|
68
|
+
* `[sampleIndex, startTick, durationTicks, rate, loop, level]` — a sample struck
|
|
69
|
+
* on the DMC: `sampleIndex` into `ApuInput.samples`, `rate` the low nibble of
|
|
70
|
+
* `$4010`, `loop` 1 to repeat it until the row ends, `level` the 7-bit value a
|
|
71
|
+
* driver loads into `$4011` before it (the jump is part of the sound — a kick's
|
|
72
|
+
* thump), or -1/absent for none. It plays to the end of its bytes or of the
|
|
73
|
+
* row, whichever comes first.
|
|
54
74
|
*/
|
|
55
|
-
export type
|
|
75
|
+
export type SampleRow = readonly [number, number, number, number, number, number?];
|
|
76
|
+
/**
|
|
77
|
+
* A DMC sample: the 1-bit delta bytes the channel reads, and where it reads them
|
|
78
|
+
* — `$C000` + 64·n, as `$4012` can point. The bytes are the cartridge's own.
|
|
79
|
+
*/
|
|
80
|
+
export interface DmcSample {
|
|
81
|
+
address: number;
|
|
82
|
+
bytes: readonly number[] | Uint8Array;
|
|
83
|
+
}
|
|
56
84
|
export interface ApuInput {
|
|
57
85
|
pitched: readonly PitchedRow[];
|
|
58
86
|
drums: readonly DrumRow[];
|
|
87
|
+
/** Samples struck on the DMC, pointing into `samples`. */
|
|
88
|
+
hits?: readonly SampleRow[];
|
|
89
|
+
/** The samples the hits play. */
|
|
90
|
+
samples?: readonly DmcSample[];
|
|
59
91
|
/** Pitch curves the notes point at. Shared, because the shapes repeat. */
|
|
60
92
|
bends?: readonly BendCurve[];
|
|
93
|
+
/** Level curves the pulse and noise notes point at — see `PitchedRow`'s `levelIndex`. Shared like `bends`. */
|
|
94
|
+
levels?: readonly LevelCurve[];
|
|
61
95
|
/** Seconds per tick. */
|
|
62
96
|
secondsPerTick: number;
|
|
63
97
|
/** Length of the piece in ticks. */
|
|
@@ -117,6 +151,13 @@ export interface ApuRender {
|
|
|
117
151
|
* points; outside it, the nearest end.
|
|
118
152
|
*/
|
|
119
153
|
export declare function bendAt(curve: BendCurve, position: number): number;
|
|
154
|
+
/** Seconds a sample of `length` bytes takes at `$4010` rate `rate`. */
|
|
155
|
+
export declare const sampleSeconds: (length: number, rate: number) => number;
|
|
156
|
+
/**
|
|
157
|
+
* The cartridge memory the DMC reads, from the samples a piece holds: each laid
|
|
158
|
+
* at its own address, the rest zero. For `renderWrites`' `memory`.
|
|
159
|
+
*/
|
|
160
|
+
export declare function sampleMemory(samples: readonly DmcSample[]): Uint8Array;
|
|
120
161
|
/**
|
|
121
162
|
* The writes that play `input`, as a driver would make them.
|
|
122
163
|
*
|
package/dist/notes.js
CHANGED
|
@@ -23,8 +23,18 @@
|
|
|
23
23
|
* - at the end, silence — unless the next note on the channel starts at the
|
|
24
24
|
* same moment.
|
|
25
25
|
*/
|
|
26
|
-
import { FRAME_HZ, LENGTH_TABLE } from './constants.js';
|
|
26
|
+
import { CPU_HZ, DMC_PERIODS, FRAME_HZ, LENGTH_TABLE } from './constants.js';
|
|
27
27
|
import { renderWrites } from './render.js';
|
|
28
|
+
/** The level a curve holds at `position`: the last point at or before it. */
|
|
29
|
+
export function levelAt(curve, position) {
|
|
30
|
+
let level = curve[0]?.[1] ?? 0;
|
|
31
|
+
for (const [at, value] of curve) {
|
|
32
|
+
if (at > position + 1e-9)
|
|
33
|
+
break;
|
|
34
|
+
level = value;
|
|
35
|
+
}
|
|
36
|
+
return level;
|
|
37
|
+
}
|
|
28
38
|
/**
|
|
29
39
|
* Seconds from the start to `tick`, through the tempo changes. With none it is
|
|
30
40
|
* exactly `tick * secondsPerTick` — the same float, so a piece without changes
|
|
@@ -94,6 +104,26 @@ const lengthIndex = (halfFrames) => {
|
|
|
94
104
|
const LONGEST = 1;
|
|
95
105
|
/** The `$4015` value: pulses and noise always on; the triangle toggled to end its notes. */
|
|
96
106
|
const enables = (triangle) => 0x0b | (triangle ? 0x04 : 0);
|
|
107
|
+
/** Seconds a sample of `length` bytes takes at `$4010` rate `rate`. */
|
|
108
|
+
export const sampleSeconds = (length, rate) => (length * 8 * DMC_PERIODS[rate & 0x0f]) / CPU_HZ;
|
|
109
|
+
/**
|
|
110
|
+
* The bytes `$4013` makes the DMC read: 16·n + 1. A sample is stored that long;
|
|
111
|
+
* one that is not is read to the next length the register can say.
|
|
112
|
+
*/
|
|
113
|
+
const lengthCode = (bytes) => Math.max(0, Math.min(255, Math.ceil((bytes - 1) / 16)));
|
|
114
|
+
/**
|
|
115
|
+
* The cartridge memory the DMC reads, from the samples a piece holds: each laid
|
|
116
|
+
* at its own address, the rest zero. For `renderWrites`' `memory`.
|
|
117
|
+
*/
|
|
118
|
+
export function sampleMemory(samples) {
|
|
119
|
+
const memory = new Uint8Array(0x8000);
|
|
120
|
+
for (const sample of samples) {
|
|
121
|
+
const at = sample.address - 0x8000;
|
|
122
|
+
for (let i = 0; i < sample.bytes.length && at + i < memory.length; i++)
|
|
123
|
+
memory[at + i] = sample.bytes[i];
|
|
124
|
+
}
|
|
125
|
+
return memory;
|
|
126
|
+
}
|
|
97
127
|
/** A register value can only hold whole numbers; a period outside 11 bits is not one the chip has. */
|
|
98
128
|
const toPeriod = (value) => Math.min(0x7ff, Math.max(0, Math.round(value)));
|
|
99
129
|
/**
|
|
@@ -166,18 +196,21 @@ export function notesToWrites(input, lead = 0) {
|
|
|
166
196
|
// a rest, not a note.
|
|
167
197
|
((row) => row[3] === channel && row[5] >= 1));
|
|
168
198
|
voices.forEach((voice, i) => {
|
|
169
|
-
const [, , , , volume, period, duty, volumeEnd, lengthTicks, bendIndex, envelope, sweep] = voice.row;
|
|
199
|
+
const [, , , , volume, period, duty, volumeEnd, lengthTicks, bendIndex, envelope, sweep, levelIndex] = voice.row;
|
|
200
|
+
const levelCurve = levelIndex !== undefined && levelIndex >= 0 ? (input.levels?.[levelIndex] ?? null) : null;
|
|
170
201
|
const bits = controlBits(envelope ?? -1, lengthTicks);
|
|
171
202
|
const reg0 = (level) => ((duty & 3) << 6) |
|
|
172
203
|
(bits.halt ? 0x20 : 0) |
|
|
173
204
|
(bits.constant ? 0x10 | (level & 0x0f) : bits.low);
|
|
174
|
-
const level = (at) =>
|
|
205
|
+
const level = (at) => levelCurve
|
|
206
|
+
? Math.min(15, Math.max(0, levelAt(levelCurve, at)))
|
|
207
|
+
: Math.min(15, Math.max(0, Math.round(volume + (volumeEnd - volume) * at)));
|
|
175
208
|
put(voice.start, base, reg0(level(0)));
|
|
176
209
|
put(voice.start, base + 1, sweep !== undefined && sweep >= 0 ? sweep : 0x08);
|
|
177
210
|
put(voice.start, base + 2, period & 0xff);
|
|
178
211
|
put(voice.start, base + 3, (bits.load << 3) | ((period >> 8) & 7));
|
|
179
212
|
const curve = bendIndex >= 0 ? (bends[bendIndex] ?? null) : null;
|
|
180
|
-
const ramps = bits.constant && volume !== volumeEnd;
|
|
213
|
+
const ramps = bits.constant && (levelCurve !== null || volume !== volumeEnd);
|
|
181
214
|
if (curve || ramps) {
|
|
182
215
|
let lastLevel = level(0);
|
|
183
216
|
let lastPeriod = period;
|
|
@@ -208,6 +241,28 @@ export function notesToWrites(input, lead = 0) {
|
|
|
208
241
|
put(voice.end, base, ((duty & 3) << 6) | 0x30);
|
|
209
242
|
});
|
|
210
243
|
}
|
|
244
|
+
/*
|
|
245
|
+
* The DMC's hits, worked out first: `$4015` is one register, and the triangle's
|
|
246
|
+
* on/off writes to it clear the DMC's bit unless they set it — which stops a
|
|
247
|
+
* sample dead. So every `$4015` write carries bit 4 while a sample is still
|
|
248
|
+
* playing, and only then: set after it has ended, the bit starts it again.
|
|
249
|
+
*/
|
|
250
|
+
const samples = input.samples ?? [];
|
|
251
|
+
const hits = (input.hits ?? [])
|
|
252
|
+
.map((row) => {
|
|
253
|
+
const sample = samples[row[0]];
|
|
254
|
+
if (!sample)
|
|
255
|
+
return null;
|
|
256
|
+
const start = lead + at(row[1]);
|
|
257
|
+
const rowEnd = lead + at(row[1] + row[2]);
|
|
258
|
+
const length = lengthCode(sample.bytes.length) * 16 + 1;
|
|
259
|
+
const end = row[4] ? rowEnd : Math.min(rowEnd, start + sampleSeconds(length, row[3]));
|
|
260
|
+
return end > start ? { row, sample, start, end, length } : null;
|
|
261
|
+
})
|
|
262
|
+
.filter((hit) => hit !== null)
|
|
263
|
+
.sort((a, b) => a.start - b.start);
|
|
264
|
+
const sampleOn = (time) => hits.some((hit) => hit.start <= time && time < hit.end);
|
|
265
|
+
const withSample = (value, time) => (sampleOn(time) ? value | 0x10 : value);
|
|
211
266
|
// Triangle. No volume: it is ended by switching it off in `$4015`, the one
|
|
212
267
|
// way to stop it on the spot — and it then holds whatever step it stopped on.
|
|
213
268
|
{
|
|
@@ -221,7 +276,7 @@ export function notesToWrites(input, lead = 0) {
|
|
|
221
276
|
// halts both.
|
|
222
277
|
const load = lengthTicks > 0 ? lengthIndex(lengthTicks) : 0;
|
|
223
278
|
if (!on)
|
|
224
|
-
put(voice.start, 0x4015, enables(true));
|
|
279
|
+
put(voice.start, 0x4015, withSample(enables(true), voice.start));
|
|
225
280
|
on = true;
|
|
226
281
|
put(voice.start, 0x4008, lengthTicks > 0 ? 0x7f : 0xff);
|
|
227
282
|
put(voice.start, 0x400a, period & 0xff);
|
|
@@ -241,7 +296,7 @@ export function notesToWrites(input, lead = 0) {
|
|
|
241
296
|
}
|
|
242
297
|
const next = voices[i + 1];
|
|
243
298
|
if (!next || next.start > voice.end + 1e-9) {
|
|
244
|
-
put(voice.end, 0x4015, enables(false));
|
|
299
|
+
put(voice.end, 0x4015, withSample(enables(false), voice.end));
|
|
245
300
|
on = false;
|
|
246
301
|
}
|
|
247
302
|
});
|
|
@@ -250,14 +305,18 @@ export function notesToWrites(input, lead = 0) {
|
|
|
250
305
|
{
|
|
251
306
|
const voices = voicesOf(input.drums, (() => true));
|
|
252
307
|
voices.forEach((voice, i) => {
|
|
253
|
-
const [periodIndex, , , volume, volumeEnd, lengthTicks, envelope] = voice.row;
|
|
308
|
+
const [periodIndex, , , volume, volumeEnd, lengthTicks, envelope, levelIndex] = voice.row;
|
|
254
309
|
const bits = controlBits(envelope ?? -1, lengthTicks);
|
|
255
310
|
const reg = (level) => (bits.halt ? 0x20 : 0) | (bits.constant ? 0x10 | (level & 0x0f) : bits.low);
|
|
256
|
-
|
|
311
|
+
// A drum struck at 8 and dropped to 2 the next frame — Darkwing Duck's — is that curve, not a line.
|
|
312
|
+
const levelCurve = levelIndex !== undefined && levelIndex >= 0 ? (input.levels?.[levelIndex] ?? null) : null;
|
|
313
|
+
const level = (at) => levelCurve
|
|
314
|
+
? Math.min(15, Math.max(0, levelAt(levelCurve, at)))
|
|
315
|
+
: Math.min(15, Math.max(0, Math.round(volume + (volumeEnd - volume) * at)));
|
|
257
316
|
put(voice.start, 0x400c, reg(level(0)));
|
|
258
317
|
put(voice.start, 0x400e, periodIndex & 0x0f);
|
|
259
318
|
put(voice.start, 0x400f, bits.load << 3);
|
|
260
|
-
if (bits.constant && volume !== volumeEnd) {
|
|
319
|
+
if (bits.constant && (levelCurve !== null || volume !== volumeEnd)) {
|
|
261
320
|
let last = level(0);
|
|
262
321
|
for (const { time, position } of frames(voice.start, voice.end)) {
|
|
263
322
|
const now = level(position);
|
|
@@ -271,6 +330,33 @@ export function notesToWrites(input, lead = 0) {
|
|
|
271
330
|
put(voice.end, 0x400c, 0x30);
|
|
272
331
|
});
|
|
273
332
|
}
|
|
333
|
+
// The DMC: rate and loop, where the sample is and how long, then bit 4 of
|
|
334
|
+
// `$4015` to start it. A hit cut short by its row — or by the next — is
|
|
335
|
+
// stopped by clearing the bit. The triangle's own `$4015` state goes with it.
|
|
336
|
+
hits.forEach((hit, i) => {
|
|
337
|
+
const [, , , rate, loop, level] = hit.row;
|
|
338
|
+
const triangleOn = (time) => {
|
|
339
|
+
// The last word the triangle had on `$4015` before `time`: on unless it was switched off.
|
|
340
|
+
let state = true;
|
|
341
|
+
for (const w of writes)
|
|
342
|
+
if (w.address === 0x4015 && w.time <= time)
|
|
343
|
+
state = (w.value & 0x04) !== 0;
|
|
344
|
+
return state;
|
|
345
|
+
};
|
|
346
|
+
put(hit.start, 0x4010, (loop ? 0x40 : 0) | (rate & 0x0f));
|
|
347
|
+
if (level !== undefined && level >= 0)
|
|
348
|
+
put(hit.start, 0x4011, level & 0x7f);
|
|
349
|
+
put(hit.start, 0x4012, ((hit.sample.address - 0xc000) >> 6) & 0xff);
|
|
350
|
+
put(hit.start, 0x4013, lengthCode(hit.sample.bytes.length));
|
|
351
|
+
// Off and on: bit 4 set while the last sample is still reading does not restart it.
|
|
352
|
+
put(hit.start, 0x4015, enables(triangleOn(hit.start)));
|
|
353
|
+
put(hit.start, 0x4015, enables(triangleOn(hit.start)) | 0x10);
|
|
354
|
+
const next = hits[i + 1];
|
|
355
|
+
const natural = hit.start + sampleSeconds(hit.length, rate);
|
|
356
|
+
if (hit.end < natural - 1e-9 && (!next || next.start > hit.end + 1e-9)) {
|
|
357
|
+
put(hit.end, 0x4015, enables(triangleOn(hit.end)));
|
|
358
|
+
}
|
|
359
|
+
});
|
|
274
360
|
return writes;
|
|
275
361
|
}
|
|
276
362
|
/** Render a decoded piece: `notesToWrites` into `renderWrites`, with the tick-based extras. */
|
|
@@ -288,6 +374,7 @@ export function renderNotes(input, options = {}) {
|
|
|
288
374
|
const result = renderWrites(notesToWrites(input, lead), lead + end, {
|
|
289
375
|
...render,
|
|
290
376
|
clicks,
|
|
377
|
+
...(input.samples?.length && !render.memory ? { memory: sampleMemory(input.samples) } : {}),
|
|
291
378
|
});
|
|
292
379
|
return {
|
|
293
380
|
samples: result.samples,
|
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,QAAQ,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,YAAY,EAAsD,MAAM,aAAa,CAAC;AA+D/F;;;;G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AI,GAAG,CAAC,EAAE,IAAI,GAAG,CAAC,EAAE,IAAI,GAAG,KAAK,CAAC,UAAU,EAAE,IAAI,IAAI,OAAO,CAAC,SAAS,EAAE,IAAI,EAAE,EAAE,CAAC;YACxF,oEAAoE;YACpE,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,GAAG,aAAa,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACnF,CAAC;IACH,CAAC;IAED,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC;IAClE,MAAM,GAAG,GAAG,aAAa,CAAC,KAAK,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;IACnD,MAAM,MAAM,GAAG,YAAY,CAAC,aAAa,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,GAAG,EAAE;QAClE,GAAG,MAAM;QACT,MAAM;KACP,CAAC,CAAC;IAEH,OAAO;QACL,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,IAAI;QACJ,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,SAAS,EAAE,IAAI,GAAG,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 { 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 0..2, volume, period, duty,\n * volumeEnd, lengthTicks, bendIndex, envelope, sweep]` — `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.\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];\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]` — a noise-channel note. `periodIndex` is the low nibble of `$400E`.\n */\nexport type DrumRow = readonly [number, number, number, number, number, number, number?];\n\nexport interface ApuInput {\n pitched: readonly PitchedRow[];\n drums: readonly DrumRow[];\n /** Pitch curves the notes point at. Shared, because the shapes repeat. */\n bends?: readonly BendCurve[];\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/** 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] =\n voice.row as PitchedRow;\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 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 && 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 // 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, enables(true));\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, enables(false));\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] = 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 const level = (at: number) =>\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 && 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 return writes;\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 });\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;AAkC/F,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;AAkED;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,KAAiD,EAAE,IAAY;IAC3F,MAAM,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC;IAC5B,IAAI,CAAC,OAAO,IAAI,OAAO,CA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C,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 0..2, 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 */\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];\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 /** 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 return writes;\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"]}
|