@xromdev/apu 0.1.1 → 0.2.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.
package/README.md CHANGED
@@ -73,6 +73,12 @@ const melody: PitchedRow[] = [
73
73
  const render = renderNotes({ pitched: melody, drums: [], secondsPerTick: 0.1, totalTicks: 8 });
74
74
  ```
75
75
 
76
+ A driver with a tempo command has ticks of more than one length: give the
77
+ changes as `tempo: [{ tick, secondsPerTick }]` — from `tick` on, a tick lasts
78
+ that long — and notes, loop points and the metronome follow them.
79
+ `tickToSeconds(input, tick)` and `secondsToTick` convert for anything drawn
80
+ alongside.
81
+
76
82
  `notesToWrites` gives you the writes on their own, if you want to see them.
77
83
 
78
84
  ### Live
@@ -219,6 +225,7 @@ test suite checks the fast paths against the plain ones bit for bit.
219
225
  |---|---|
220
226
  | `renderWrites(writes, seconds, options?)` | Register writes → `{ samples, sampleRate, duration, peak }`. |
221
227
  | `renderNotes(input, options?)` / `notesToWrites(input)` | Decoded notes → samples, or → the writes a driver would make. |
228
+ | `tickToSeconds(input, tick)` / `secondsToTick(input, s)` | Ticks ↔ seconds through the input's `tempo` changes. |
222
229
  | `new Apu(sampleRate, { memory?, lengthCounter? })` | The chip itself: `write(address, value)`, `render(count, buffers)`, `levels()`, `snapshot()`. |
223
230
  | `mixApu(p1, p2, tri, noise, dmc?)`, `OutputFilters` | The non-linear mixer and the console's analogue stage, for use with `Apu`. |
224
231
  | `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, } from './notes.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';
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, } from './notes.js';
19
+ export { bendAt, notesToWrites, renderNotes, 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,GAOZ,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 notesToWrites,\n renderNotes,\n type ApuInput,\n type ApuOptions,\n type ApuRender,\n type BendCurve,\n type DrumRow,\n type PitchedRow,\n} from './notes.js';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,MAAM,EACN,WAAW,EACX,cAAc,EACd,QAAQ,EACR,YAAY,EACZ,aAAa,EACb,gBAAgB,EAChB,cAAc,GACf,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,GAAG,GAKJ,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EACL,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,EAOX,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 notesToWrites,\n renderNotes,\n type ApuInput,\n type ApuOptions,\n type ApuRender,\n type BendCurve,\n type DrumRow,\n type PitchedRow,\n secondsToTick,\n tickToSeconds,\n type TempoChange,\n} from './notes.js';\n"]}
package/dist/notes.d.ts CHANGED
@@ -68,7 +68,26 @@ export interface ApuInput {
68
68
  * intro every time round. Absent means the piece does not loop.
69
69
  */
70
70
  loopStart?: number;
71
+ /**
72
+ * Changes of tempo, as `{ tick, secondsPerTick }` in tick order: from `tick`
73
+ * on, a tick lasts `secondsPerTick`. Before the first change it is the
74
+ * input's own `secondsPerTick`. For drivers with a tempo command — Battletoads
75
+ * speeds its opening up this way — whose ticks are not all the same length.
76
+ */
77
+ tempo?: readonly TempoChange[];
78
+ }
79
+ export interface TempoChange {
80
+ tick: number;
81
+ secondsPerTick: number;
71
82
  }
83
+ /**
84
+ * Seconds from the start to `tick`, through the tempo changes. With none it is
85
+ * exactly `tick * secondsPerTick` — the same float, so a piece without changes
86
+ * renders as it always has.
87
+ */
88
+ export declare function tickToSeconds(input: Pick<ApuInput, 'secondsPerTick' | 'tempo'>, tick: number): number;
89
+ /** The tick at `seconds` — the inverse of `tickToSeconds`, fractional. */
90
+ export declare function secondsToTick(input: Pick<ApuInput, 'secondsPerTick' | 'tempo'>, seconds: number): number;
72
91
  export interface ApuOptions extends Omit<RenderOptions, 'clicks' | 'tail'> {
73
92
  /** Seconds of silence before the first note. */
74
93
  lead?: number;
package/dist/notes.js CHANGED
@@ -25,6 +25,45 @@
25
25
  */
26
26
  import { FRAME_HZ, LENGTH_TABLE } from './constants.js';
27
27
  import { renderWrites } from './render.js';
28
+ /**
29
+ * Seconds from the start to `tick`, through the tempo changes. With none it is
30
+ * exactly `tick * secondsPerTick` — the same float, so a piece without changes
31
+ * renders as it always has.
32
+ */
33
+ export function tickToSeconds(input, tick) {
34
+ const changes = input.tempo;
35
+ if (!changes || changes.length === 0)
36
+ return tick * input.secondsPerTick;
37
+ let seconds = 0;
38
+ let from = 0;
39
+ let spt = input.secondsPerTick;
40
+ for (const change of changes) {
41
+ if (change.tick >= tick)
42
+ break;
43
+ seconds += (change.tick - from) * spt;
44
+ from = change.tick;
45
+ spt = change.secondsPerTick;
46
+ }
47
+ return seconds + (tick - from) * spt;
48
+ }
49
+ /** The tick at `seconds` — the inverse of `tickToSeconds`, fractional. */
50
+ export function secondsToTick(input, seconds) {
51
+ const changes = input.tempo;
52
+ if (!changes || changes.length === 0)
53
+ return seconds / input.secondsPerTick;
54
+ let at = 0;
55
+ let from = 0;
56
+ let spt = input.secondsPerTick;
57
+ for (const change of changes) {
58
+ const end = at + (change.tick - from) * spt;
59
+ if (end >= seconds)
60
+ break;
61
+ at = end;
62
+ from = change.tick;
63
+ spt = change.secondsPerTick;
64
+ }
65
+ return from + (seconds - at) / spt;
66
+ }
28
67
  /**
29
68
  * Semitones at `position` through a note, straight-line between the curve's own
30
69
  * points; outside it, the nearest end.
@@ -98,7 +137,7 @@ function* frames(start, end) {
98
137
  * @param lead seconds of silence before tick 0
99
138
  */
100
139
  export function notesToWrites(input, lead = 0) {
101
- const spt = input.secondsPerTick;
140
+ const at = (tick) => tickToSeconds(input, tick);
102
141
  const bends = input.bends ?? [];
103
142
  const writes = [];
104
143
  const put = (time, address, value) => writes.push({ time, address, value });
@@ -113,8 +152,8 @@ export function notesToWrites(input, lead = 0) {
113
152
  const voicesOf = (rows, keep) => rows
114
153
  .filter(keep)
115
154
  .map((row) => ({
116
- start: lead + row[1] * spt,
117
- end: lead + (row[1] + row[2]) * spt,
155
+ start: lead + at(row[1]),
156
+ end: lead + at(row[1] + row[2]),
118
157
  row,
119
158
  }))
120
159
  .filter((voice) => voice.end > voice.start)
@@ -237,16 +276,16 @@ export function notesToWrites(input, lead = 0) {
237
276
  /** Render a decoded piece: `notesToWrites` into `renderWrites`, with the tick-based extras. */
238
277
  export function renderNotes(input, options = {}) {
239
278
  const lead = options.lead ?? 0;
240
- const spt = input.secondsPerTick;
241
279
  const clicks = [];
242
280
  if (options.metronome && options.metronome > 0) {
243
281
  for (let tick = 0, beat = 0; tick < input.totalTicks; tick += options.metronome, beat++) {
244
282
  // Four beats to a bar: the downbeat is what makes a tempo readable.
245
- clicks.push({ time: lead + tick * spt, strong: beat % 4 === 0 });
283
+ clicks.push({ time: lead + tickToSeconds(input, tick), strong: beat % 4 === 0 });
246
284
  }
247
285
  }
248
286
  const { lead: _lead, metronome: _metronome, ...render } = options;
249
- const result = renderWrites(notesToWrites(input, lead), lead + input.totalTicks * spt, {
287
+ const end = tickToSeconds(input, input.totalTicks);
288
+ const result = renderWrites(notesToWrites(input, lead), lead + end, {
250
289
  ...render,
251
290
  clicks,
252
291
  });
@@ -255,8 +294,8 @@ export function renderNotes(input, options = {}) {
255
294
  sampleRate: result.sampleRate,
256
295
  lead,
257
296
  duration: result.duration,
258
- loopStart: lead + Math.min(input.loopStart ?? 0, input.totalTicks) * spt,
259
- loopEnd: lead + input.totalTicks * spt,
297
+ loopStart: lead + tickToSeconds(input, Math.min(input.loopStart ?? 0, input.totalTicks)),
298
+ loopEnd: lead + end,
260
299
  peak: result.peak,
261
300
  };
262
301
  }
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;AA6E/F;;;GAGG;AACH,MAAM,UAAU,MAAM,CAAC,KAAgB,EAAE,QAAgB;IACvD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,CAAC,CAAC;IACjC,IAAI,QAAQ,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAAE,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAChD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACtC,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QAC1B,IAAI,QAAQ,IAAI,EAAE,EAAE,CAAC;YACnB,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;YAC9B,MAAM,IAAI,GAAG,EAAE,GAAG,EAAE,CAAC;YACrB,OAAO,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,QAAQ,GAAG,EAAE,C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cesContent":["/**\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\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 spt = input.secondsPerTick;\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 + row[1] * spt,\n end: lead + (row[1] + row[2]) * spt,\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 const spt = input.secondsPerTick;\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 + tick * spt, strong: beat % 4 === 0 });\n }\n }\n\n const { lead: _lead, metronome: _metronome, ...render } = options;\n const result = renderWrites(notesToWrites(input, lead), lead + input.totalTicks * spt, {\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 + Math.min(input.loopStart ?? 0, input.totalTicks) * spt,\n loopEnd: lead + input.totalTicks * spt,\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,QAAQ,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,YAAY,EAAsD,MAAM,aAAa,CAAC;AA+D/F;;;;GAIG;AACH,MA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AC,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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xromdev/apu",
3
- "version": "0.1.1",
3
+ "version": "0.2.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",