@dsebastien/music-notation 0.25.0 → 0.26.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.
@@ -3,6 +3,7 @@ import type { Hand } from '../render/layout.js';
3
3
  import { type NotePlayer, type PlayKind, type Sound } from './player.js';
4
4
  import { type Engine } from './engine.js';
5
5
  import { type GuitarTone } from './guitar-tone.js';
6
+ import { type AmpOptions, type PlayEffects } from './effects.js';
6
7
  export interface PlayOptions {
7
8
  /**
8
9
  * The language of the bars' texts and of the diagrams they redraw (#136): `'en'` or `'fr'`.
@@ -33,6 +34,27 @@ export interface PlayOptions {
33
34
  * changed in the app is heard at the next Play. A block's `guitar:` line comes first.
34
35
  */
35
36
  guitar?: GuitarTone | (() => GuitarTone | null | undefined);
37
+ /**
38
+ * The room's level (#103), 0 (none) to 1: every block plays in a small room, light by default
39
+ * (0.125, the room 18 dB under the notes). A function is read at each play, so a setting changed in the app is heard at the
40
+ * next Play. The level is the page's: the last play sets it for everything that sounds.
41
+ */
42
+ reverb?: number | (() => number | null | undefined);
43
+ /**
44
+ * How long the room rings (#103), in seconds, 0.2 (a small room) to 3 (a hall); 1.2 by
45
+ * default. A function is read at each play. Like the level, it is the page's.
46
+ */
47
+ room?: number | (() => number | null | undefined);
48
+ /**
49
+ * No room and no ceiling (#103): the notes go straight to the output, as they did before the
50
+ * room, for a host that adds its own effects. A function is read at each play.
51
+ */
52
+ dry?: boolean | (() => boolean | null | undefined);
53
+ /**
54
+ * An amplifier for the electric guitars (`clean`, `overdrive`): `drive` 0 to 1, `cabinet` a
55
+ * speaker's sound. None by default. A function is read at each play.
56
+ */
57
+ amp?: AmpOptions | (() => AmpOptions | null | undefined);
36
58
  /**
37
59
  * 0 to 1, 0.8 by default. The bars have no volume (#58): it is the app's setting. A function
38
60
  * is read at each play (and each pass of a loop), so a setting changed in the app applies at
@@ -112,6 +134,12 @@ export declare function playerFor(win: Window, options: PlayOptions, el?: Elemen
112
134
  * guitar, so an app that names none gets exactly the player it gave.
113
135
  */
114
136
  export declare function toned(player: NotePlayer, options: PlayOptions, el?: Element | null): NotePlayer;
137
+ /**
138
+ * The effects a host asks for (#103): its room level (to the thousandth: the default is 0.125)
139
+ * and length, `dry`, an amplifier; null when it names none, so the players use their defaults and
140
+ * an app that names nothing gets its own player.
141
+ */
142
+ export declare function effectsOf(options: PlayOptions): PlayEffects | null;
115
143
  /**
116
144
  * The guitar that plays for an element: the one its reader chose in a bar's Sound menu, else its
117
145
  * block's `guitar:` line, else the app's or page's.
@@ -0,0 +1,142 @@
1
+ /**
2
+ * What comes after the instruments (#103): a small room and a ceiling on the way to the speakers,
3
+ * and for the electric guitars an optional amplifier (a drive and a speaker cabinet). Built from
4
+ * Web Audio nodes and a generated impulse response: no file, a few KB of code.
5
+ *
6
+ * One chain per audio context: every play of that context goes through the same room, so a page
7
+ * sounds like one place. A host that adds its own effects asks for `dry` and gets the output as
8
+ * it was.
9
+ */
10
+ /** The effects of a play: the app's or the page's choice (`PlayOptions`), given to the players. */
11
+ export interface PlayEffects {
12
+ /** The room's level, 0 (none) to 1; the light room by default. */
13
+ reverb?: number;
14
+ /** How long the room rings, in seconds (0.2 to 3): a small room to a hall. */
15
+ room?: number;
16
+ /** No room and no ceiling: the notes go straight to the output, for hosts with their own. */
17
+ dry?: boolean;
18
+ /** An amplifier for the electric guitars (clean, overdrive); none by default. */
19
+ amp?: AmpOptions;
20
+ }
21
+ /** The amplifier of an electric guitar. */
22
+ export interface AmpOptions {
23
+ /** How hard the amplifier is driven, 0 (clean) to 1. */
24
+ drive?: number;
25
+ /** A speaker cabinet's sound: less deep bass and less fizz, more mids. */
26
+ cabinet?: boolean;
27
+ }
28
+ /**
29
+ * The room's level when nothing says another: a light room, 18 dB under the notes. The level is
30
+ * how loud the room is against what plays in it, where a guitar sounds (`ROOM_BAND`): 0.125 is
31
+ * 18 dB under, 0.35 is 9 dB under, 1 as loud as the notes.
32
+ */
33
+ export declare const DEFAULT_REVERB = 0.125;
34
+ /**
35
+ * How long the room rings (seconds to fall by 60 dB). A guitar's notes ring for seconds
36
+ * themselves: a room shorter than about a second hides under them and is not heard.
37
+ */
38
+ export declare const ROOM_SECONDS = 1.2;
39
+ /** The shortest and the longest room (seconds). */
40
+ export declare const ROOM_RANGE: readonly [0.2, 3];
41
+ /** A room's length from an option: within the range, the default when it isn't a number. */
42
+ export declare function roomSeconds(value: unknown): number;
43
+ /** A room level from an option: 0 to 1, the default when it isn't a number. */
44
+ export declare function reverbLevel(value: unknown): number;
45
+ /**
46
+ * A page's effects (`play: { reverb, room, dry, amp }` in `window.musicNotationOptions`): `reverb`
47
+ * a number from 0 to 1, `room` its length in seconds, `dry: true`, `amp: { drive, cabinet }`. A
48
+ * function in place of a value is called. Null when the page names none.
49
+ */
50
+ export declare function pageEffects(options: unknown): PlayEffects | null;
51
+ /** What a room sounds like, besides its length. */
52
+ export interface RoomShape {
53
+ /** Where the tail's highs end when it starts (Hz). */
54
+ bright: number;
55
+ /** Where they end when it has rung out (Hz). */
56
+ dark: number;
57
+ /** How long the tail takes to come up (seconds). */
58
+ rise: number;
59
+ /** 0: the same on both sides (in the middle, with the notes); 1: nothing in common. */
60
+ width: number;
61
+ }
62
+ /**
63
+ * The library's room.
64
+ *
65
+ * Brightness: a room is darker than what plays in it. As bright as the guitar (9 kHz, a gentle
66
+ * slope), the tail was heard as noise: every attack came back as a hiss until the next strum.
67
+ *
68
+ * Rise: a real room starts with a few echoes and gets dense later; a tail of noise at full level
69
+ * from its first instant put a burst of noise right after each attack. Not long: at 50 ms the
70
+ * tail's loudest moment came 60 ms after the note, a small echo.
71
+ *
72
+ * Width: with nothing in common between the two sides, the room was a cloud of noise around the
73
+ * head, apart from the guitar in the middle (and the hardest sound there is for the codec of
74
+ * wireless headphones). Half in common: the room is around the guitar.
75
+ */
76
+ export declare const ROOM_SHAPE: Readonly<RoomShape>;
77
+ /**
78
+ * Where a guitar sounds (Hz): the room is as loud there as what goes into it. With an energy of 1
79
+ * over all frequencies, a dark room had all of it in this band: 11 dB more than its number said
80
+ * (the default was 8.6 dB under a recorded strum, not the 18 dB meant).
81
+ */
82
+ export declare const ROOM_BAND: readonly [300, 3000];
83
+ /** Under this (Hz) the two sides are the same: lows that differ between the ears feel wrong. */
84
+ export declare const ROOM_WIDE_FROM = 400;
85
+ /**
86
+ * The impulse response of a room, left and right: after 12 ms (the notes themselves come first),
87
+ * a diffuse tail that comes up, falls by 60 dB in `seconds` and gets darker as it falls (walls
88
+ * take the highs first; the brightness is in Hz, so the room sounds the same at every sample
89
+ * rate). `shape` changes the library's room (`ROOM_SHAPE`), for a host that tunes its own. The
90
+ * two sides differ above `ROOM_WIDE_FROM`, so the room has width. A sound of the guitar's band
91
+ * (`ROOM_BAND`) through it comes out as loud as it went in: the level is the gain after it.
92
+ */
93
+ export declare function roomImpulse(sampleRate: number, seconds?: number, shape?: Partial<RoomShape>): [Float32Array, Float32Array];
94
+ /** Where the ceiling starts to bend, and the highest level its curve is drawn for. */
95
+ export declare const CEILING: {
96
+ readonly knee: 0.9;
97
+ readonly range: 2;
98
+ };
99
+ /**
100
+ * The ceiling, the last thing before the speakers: a level under the knee comes out as it is, a
101
+ * higher one bends toward 1 and never passes it. An accented six-string strum of the recorded
102
+ * guitars peaks at 1.115 and was cut flat by the speakers; plays that add up go higher. It is
103
+ * not late and has no memory: nothing to pump. (A browser's compressor was here first, as a
104
+ * limiter. It is 6 ms late, starts turned down, cannot give up its make-up gain, and its gain
105
+ * moved by 1 to 5 dB for a quarter to half of the time when a loud room pushed it: it is gone.)
106
+ * The curve is for an input divided by `CEILING.range` (a wave shaper reads -1 to 1).
107
+ */
108
+ export declare function ceilingCurve(points?: number): Float32Array;
109
+ /** The room's sound below this (Hz) is left out: a room's low end is mud under a guitar. */
110
+ export declare const ROOM_LOW_CUT = 180;
111
+ /**
112
+ * Where a player sends its notes: the context's chain (the room at the level asked, then the
113
+ * ceiling), or the output itself for `dry` and for a context that can't build the chain. The
114
+ * room's level and length are the context's: the last play that names them sets them for what
115
+ * sounds. `speakers` is the context's output, for a caller that keeps it under another name
116
+ * (alphaTab's context, see `src/tab/room.ts`).
117
+ */
118
+ export declare function outputFor(ctx: BaseAudioContext, effects?: PlayEffects, speakers?: AudioNode): AudioNode;
119
+ /** How hard the amplifier's curve bends at a drive of 0 to 1. */
120
+ export declare const driveAmount: (drive: number) => number;
121
+ /** The curve of a driven amplifier: a soft ceiling, steeper with more drive. */
122
+ export declare function driveCurve(drive: number, points?: number): Float32Array;
123
+ /** The level of a strummed guitar the drive is matched for (a wave's peak). */
124
+ export declare const DRIVE_REFERENCE = 0.2;
125
+ /**
126
+ * The gain after the drive that keeps a strum as loud as it went in: a wave at the reference
127
+ * level through the curve, its level in over its level out. The curve raises quiet sound by its
128
+ * slope (up to 15 times): a fixed gain made a driven strum 10 to 12 dB louder.
129
+ */
130
+ export declare function driveLevel(drive: number, reference?: number): number;
131
+ /** The cabinet's filters raise a guitar's level by about this (dB): taken back after them. */
132
+ export declare const CABINET_TRIM_DB = -2;
133
+ /**
134
+ * An electric guitar's amplifier between a play and the chain: a drive (the deep bass left out,
135
+ * then a wave shaper, level matched so more drive is not simply louder) and a cabinet (no deep
136
+ * bass, a peak in the mids, no fizz, level matched too). Null when the options ask for neither,
137
+ * or the context can't build it.
138
+ */
139
+ export declare function ampFor(ctx: BaseAudioContext, amp: AmpOptions | undefined): {
140
+ input: AudioNode;
141
+ output: AudioNode;
142
+ } | null;
@@ -4,6 +4,7 @@
4
4
  * Apps can pass another NotePlayer (a soundfont one) for realistic sound.
5
5
  */
6
6
  import { type GuitarTone } from './guitar-tone.js';
7
+ import { type PlayEffects } from './effects.js';
7
8
  export type Sound = 'guitar' | 'piano';
8
9
  export interface NoteEvent {
9
10
  midi: number;
@@ -41,6 +42,11 @@ export interface NotePlayer {
41
42
  * that doesn't know it plays its own guitar.
42
43
  */
43
44
  guitar?: GuitarTone;
45
+ /**
46
+ * The room, the ceiling and the amplifier after the notes (#103): the light room by
47
+ * default. A player that doesn't know them plays as it always did.
48
+ */
49
+ effects?: PlayEffects;
44
50
  }): PlayHandle;
45
51
  /**
46
52
  * True when `play` calls `onStart`: the bar then waits for it before it lights notes.
@@ -133,6 +139,14 @@ export declare function contextFor(win: Window & {
133
139
  export declare const RELEASE: Readonly<Record<Sound, number>>;
134
140
  /** The release of a note of `duration` seconds. */
135
141
  export declare const releaseOf: (sound: Sound, duration: number) => number;
142
+ /**
143
+ * Sends a play's notes on (#103): through an electric guitar's amplifier when one is asked for
144
+ * (`clean` and `overdrive` only), then to the context's room and ceiling, or straight to the
145
+ * output for `dry`. Returns what lets the play go once its sound is over: its node leaves the
146
+ * chain, and its amplifier too (an amplifier left connected stayed in the chain for good, one
147
+ * more with each play).
148
+ */
149
+ export declare function sendOut(ctx: BaseAudioContext, from: AudioNode, guitar: GuitarTone | null, effects: PlayEffects | undefined): () => void;
136
150
  /**
137
151
  * The light synthesizer: computed sound, a few KB, no download. No two notes sound quite the
138
152
  * same: each guitar note takes one of a few plucks of its string (brightness, pick position,
@@ -95,7 +95,11 @@ function withoutParentheses(suffix) {
95
95
  return null;
96
96
  return suffix.replace(/[(),\s]/g, "");
97
97
  }
98
+ var leadSheetSuffix = (suffix) => suffix.replace(/^(?:mi|MI|min|MIN)(?![A-Za-z])/, "m").replace(/^(?:ma|MA)(?![A-Za-z])/, "maj");
98
99
  function canonicalSuffix(suffix) {
100
+ const lead = leadSheetSuffix(suffix);
101
+ if (lead !== suffix)
102
+ return canonicalSuffix(lead);
99
103
  const direct = CANONICAL.get(suffix);
100
104
  if (direct !== undefined)
101
105
  return direct;
@@ -1523,9 +1527,10 @@ function parseChord(symbol) {
1523
1527
  return null;
1524
1528
  const trimmed = symbol.trim();
1525
1529
  const { root, bass } = parts;
1526
- const suffix = withoutParentheses(parts.suffix);
1530
+ const lead = leadSheetSuffix(parts.suffix);
1531
+ const suffix = withoutParentheses(lead);
1527
1532
  let quality = null;
1528
- for (const written of suffix === null || suffix === parts.suffix ? [parts.suffix] : [parts.suffix, suffix]) {
1533
+ for (const written of suffix === null || suffix === lead ? [lead] : [lead, suffix]) {
1529
1534
  for (const [re, label] of QUALITY_SUFFIXES) {
1530
1535
  const hit = re.exec(written);
1531
1536
  if (hit) {
@@ -5579,6 +5584,289 @@ function pageGuitar(options) {
5579
5584
  return guitarToneOf(play.guitar) ?? undefined;
5580
5585
  }
5581
5586
 
5587
+ // src/playback/effects.ts
5588
+ var DEFAULT_REVERB = 0.125;
5589
+ var ROOM_SECONDS = 1.2;
5590
+ var ROOM_RANGE = [0.2, 3];
5591
+ function roomSeconds(value) {
5592
+ return typeof value === "number" && Number.isFinite(value) ? Math.min(ROOM_RANGE[1], Math.max(ROOM_RANGE[0], value)) : ROOM_SECONDS;
5593
+ }
5594
+ function reverbLevel(value) {
5595
+ return typeof value === "number" && Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : DEFAULT_REVERB;
5596
+ }
5597
+ function pageEffects(options) {
5598
+ if (!options || typeof options !== "object" || !("play" in options))
5599
+ return null;
5600
+ const play = options.play;
5601
+ if (!play || typeof play !== "object")
5602
+ return null;
5603
+ const read = (key) => {
5604
+ const value = play[key];
5605
+ if (typeof value !== "function")
5606
+ return value;
5607
+ try {
5608
+ return value();
5609
+ } catch {
5610
+ return;
5611
+ }
5612
+ };
5613
+ const reverb = read("reverb");
5614
+ const room = read("room");
5615
+ const amp = read("amp");
5616
+ const drive = amp && typeof amp === "object" ? amp["drive"] : null;
5617
+ const cabinet = amp && typeof amp === "object" && amp["cabinet"];
5618
+ const effects = {
5619
+ ...typeof reverb === "number" && Number.isFinite(reverb) ? { reverb: Math.min(1, Math.max(0, reverb)) } : {},
5620
+ ...typeof room === "number" && Number.isFinite(room) ? { room: roomSeconds(room) } : {},
5621
+ ...read("dry") === true ? { dry: true } : {},
5622
+ ...cabinet === true || typeof drive === "number" && Number.isFinite(drive) ? {
5623
+ amp: {
5624
+ ...typeof drive === "number" && Number.isFinite(drive) ? { drive: Math.min(1, Math.max(0, drive)) } : {},
5625
+ ...cabinet === true ? { cabinet: true } : {}
5626
+ }
5627
+ } : {}
5628
+ };
5629
+ return Object.keys(effects).length ? effects : null;
5630
+ }
5631
+ function seeded(seed) {
5632
+ let a = seed >>> 0;
5633
+ return () => {
5634
+ a = a + 1831565813 >>> 0;
5635
+ let t = a;
5636
+ t = Math.imul(t ^ t >>> 15, t | 1);
5637
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
5638
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
5639
+ };
5640
+ }
5641
+ var ROOM_SHAPE = { bright: 4000, dark: 800, rise: 0.02, width: 0.5 };
5642
+ var ROOM_BAND = [300, 3000];
5643
+ var ROOM_WIDE_FROM = 400;
5644
+ var ROOM_SLOPE = 3;
5645
+ function roomImpulse(sampleRate, seconds = ROOM_SECONDS, shape = {}) {
5646
+ const { bright, dark, rise: riseSeconds, width } = { ...ROOM_SHAPE, ...shape };
5647
+ const length = Math.max(1, Math.round(sampleRate * seconds));
5648
+ const start = Math.min(length, Math.round(sampleRate * 0.012));
5649
+ const fade = Math.max(1, Math.round(length * 0.1));
5650
+ const fall = Math.pow(10, -3 / (sampleRate * seconds));
5651
+ const darker = Math.pow(dark / bright, 1 / (sampleRate * seconds));
5652
+ const rise = Math.max(1, Math.round(sampleRate * Math.max(0, riseSeconds)));
5653
+ const keepAt = (cutoff) => Math.exp(-2 * Math.PI * Math.min(cutoff, sampleRate * 0.45) / sampleRate);
5654
+ const shapeAt = (i) => (i - start < rise ? (i - start) / rise : 1) * (i > length - fade ? (length - i) / fade : 1);
5655
+ const make = (seed) => {
5656
+ const random = seeded(seed);
5657
+ const data = new Float32Array(length);
5658
+ let level = Math.pow(fall, start);
5659
+ let cutoff = bright * Math.pow(darker, start);
5660
+ let keep = 0;
5661
+ const lows = new Float64Array(ROOM_SLOPE);
5662
+ for (let i = start;i < length; i++) {
5663
+ if ((i - start) % 64 === 0)
5664
+ keep = keepAt(cutoff);
5665
+ let value = random() * 2 - 1;
5666
+ for (let pole = 0;pole < ROOM_SLOPE; pole++) {
5667
+ value = keep * lows[pole] + (1 - keep) * value;
5668
+ lows[pole] = value;
5669
+ }
5670
+ data[i] = value * level * shapeAt(i);
5671
+ level *= fall;
5672
+ cutoff *= darker;
5673
+ }
5674
+ return data;
5675
+ };
5676
+ let power = 0;
5677
+ const pitches = 8;
5678
+ for (let p = 0;p < pitches; p++) {
5679
+ const hz = ROOM_BAND[0] * Math.pow(ROOM_BAND[1] / ROOM_BAND[0], (p + 0.5) / pitches);
5680
+ const cos = Math.cos(2 * Math.PI * hz / sampleRate);
5681
+ let level = Math.pow(fall, start);
5682
+ let cutoff = bright * Math.pow(darker, start);
5683
+ const step = Math.pow(fall, 64);
5684
+ const darkerStep = Math.pow(darker, 64);
5685
+ for (let i = start;i < length; i += 64) {
5686
+ const keep = keepAt(cutoff);
5687
+ const pole = (1 - keep) * (1 - keep) / (1 - 2 * keep * cos + keep * keep);
5688
+ const size = Math.min(64, length - i);
5689
+ const here = level * shapeAt(i + (size >> 1));
5690
+ power += size * here * here * Math.pow(pole, ROOM_SLOPE) / 3;
5691
+ level *= step;
5692
+ cutoff *= darkerStep;
5693
+ }
5694
+ }
5695
+ const scale = power > 0 ? 1 / Math.sqrt(power / pitches) : 0;
5696
+ const middle = make(625341585);
5697
+ const apart = make(1374496523);
5698
+ const pass = Math.exp(-2 * Math.PI * ROOM_WIDE_FROM / sampleRate);
5699
+ for (let turn = 0;turn < 2; turn++) {
5700
+ let low = 0;
5701
+ for (let i = 0;i < length; i++) {
5702
+ low = pass * low + (1 - pass) * apart[i];
5703
+ apart[i] = apart[i] - low;
5704
+ }
5705
+ }
5706
+ const angle = Math.min(1, Math.max(0, width)) * Math.PI / 4;
5707
+ const left = new Float32Array(length);
5708
+ const right = new Float32Array(length);
5709
+ for (let i = 0;i < length; i++) {
5710
+ const m = middle[i] * Math.cos(angle) * scale;
5711
+ const a = apart[i] * Math.sin(angle) * scale;
5712
+ left[i] = m + a;
5713
+ right[i] = m - a;
5714
+ }
5715
+ return [left, right];
5716
+ }
5717
+ var CEILING = { knee: 0.9, range: 2 };
5718
+ function ceilingCurve(points = 4097) {
5719
+ const { knee, range } = CEILING;
5720
+ const curve = new Float32Array(points);
5721
+ for (let i = 0;i < points; i++) {
5722
+ const level = (i / (points - 1) * 2 - 1) * range;
5723
+ const size = Math.abs(level);
5724
+ curve[i] = Math.sign(level) * (size <= knee ? size : knee + (1 - knee) * Math.tanh((size - knee) / (1 - knee)));
5725
+ }
5726
+ return curve;
5727
+ }
5728
+ var ROOM_LOW_CUT = 180;
5729
+ var chains = new WeakMap;
5730
+ var canBuild = (ctx) => typeof ctx.createConvolver === "function" && typeof ctx.createBuffer === "function";
5731
+ var rooms = new Map;
5732
+ function roomBuffer(ctx, seconds) {
5733
+ const key = `${ctx.sampleRate}:${seconds}`;
5734
+ let sides = rooms.get(key);
5735
+ if (!sides) {
5736
+ sides = roomImpulse(ctx.sampleRate, seconds);
5737
+ if (rooms.size >= 3)
5738
+ rooms.delete(rooms.keys().next().value);
5739
+ rooms.set(key, sides);
5740
+ }
5741
+ const [left, right] = sides;
5742
+ const impulse = ctx.createBuffer(2, left.length, ctx.sampleRate);
5743
+ impulse.getChannelData(0).set(left);
5744
+ impulse.getChannelData(1).set(right);
5745
+ return impulse;
5746
+ }
5747
+ function build(ctx, speakers, seconds) {
5748
+ const input = ctx.createGain();
5749
+ const wet = ctx.createGain();
5750
+ wet.gain.value = 0;
5751
+ const room = ctx.createConvolver();
5752
+ room.normalize = false;
5753
+ room.buffer = roomBuffer(ctx, seconds);
5754
+ const sum = ctx.createGain();
5755
+ input.connect(sum);
5756
+ input.connect(room);
5757
+ if (typeof ctx.createBiquadFilter === "function") {
5758
+ const lowCut = ctx.createBiquadFilter();
5759
+ lowCut.type = "highpass";
5760
+ lowCut.frequency.value = ROOM_LOW_CUT;
5761
+ lowCut.Q.value = 0.7;
5762
+ room.connect(lowCut);
5763
+ lowCut.connect(wet);
5764
+ } else
5765
+ room.connect(wet);
5766
+ wet.connect(sum);
5767
+ if (typeof ctx.createWaveShaper === "function") {
5768
+ const ceiling = ctx.createWaveShaper();
5769
+ ceiling.curve = ceilingCurve();
5770
+ sum.gain.value = 1 / CEILING.range;
5771
+ sum.connect(ceiling);
5772
+ ceiling.connect(speakers);
5773
+ } else
5774
+ sum.connect(speakers);
5775
+ return { input, wet, room, seconds };
5776
+ }
5777
+ function outputFor(ctx, effects, speakers = ctx.destination) {
5778
+ if (effects?.dry || !canBuild(ctx))
5779
+ return speakers;
5780
+ const seconds = roomSeconds(effects?.room);
5781
+ let chain = chains.get(ctx);
5782
+ if (!chain) {
5783
+ try {
5784
+ chain = build(ctx, speakers, seconds);
5785
+ } catch {
5786
+ return speakers;
5787
+ }
5788
+ chains.set(ctx, chain);
5789
+ } else if (chain.seconds !== seconds) {
5790
+ try {
5791
+ chain.room.buffer = roomBuffer(ctx, seconds);
5792
+ chain.seconds = seconds;
5793
+ } catch {}
5794
+ }
5795
+ const level = reverbLevel(effects?.reverb);
5796
+ if (typeof chain.wet.gain.setTargetAtTime === "function")
5797
+ chain.wet.gain.setTargetAtTime(level, ctx.currentTime, 0.02);
5798
+ else
5799
+ chain.wet.gain.value = level;
5800
+ return chain.input;
5801
+ }
5802
+ var driveAmount = (drive) => 1 + 14 * Math.min(1, Math.max(0, drive));
5803
+ function driveCurve(drive, points = 2048) {
5804
+ const amount = driveAmount(drive);
5805
+ const curve = new Float32Array(points);
5806
+ const ceiling = Math.tanh(amount);
5807
+ for (let i = 0;i < points; i++) {
5808
+ const x = i / (points - 1) * 2 - 1;
5809
+ curve[i] = Math.tanh(amount * x) / ceiling;
5810
+ }
5811
+ return curve;
5812
+ }
5813
+ var DRIVE_REFERENCE = 0.2;
5814
+ function driveLevel(drive, reference = DRIVE_REFERENCE) {
5815
+ const amount = driveAmount(drive);
5816
+ const ceiling = Math.tanh(amount);
5817
+ let before = 0;
5818
+ let after = 0;
5819
+ for (let i = 0;i < 256; i++) {
5820
+ const x = reference * Math.sin(2 * Math.PI * i / 256);
5821
+ const y = Math.tanh(amount * x) / ceiling;
5822
+ before += x * x;
5823
+ after += y * y;
5824
+ }
5825
+ return after > 0 ? Math.sqrt(before / after) : 1;
5826
+ }
5827
+ var CABINET_TRIM_DB = -2;
5828
+ function ampFor(ctx, amp) {
5829
+ const drive = typeof amp?.drive === "number" ? Math.min(1, Math.max(0, amp.drive)) : 0;
5830
+ const cabinet = amp?.cabinet === true;
5831
+ if (!drive && !cabinet)
5832
+ return null;
5833
+ if (typeof ctx.createWaveShaper !== "function" || typeof ctx.createBiquadFilter !== "function")
5834
+ return null;
5835
+ const input = ctx.createGain();
5836
+ let last = input;
5837
+ const filter = (type, frequency, q, gain = 0) => {
5838
+ const node = ctx.createBiquadFilter();
5839
+ node.type = type;
5840
+ node.frequency.value = frequency;
5841
+ node.Q.value = q;
5842
+ node.gain.value = gain;
5843
+ last.connect(node);
5844
+ last = node;
5845
+ };
5846
+ if (drive) {
5847
+ filter("highpass", 120, 0.7);
5848
+ const shaper = ctx.createWaveShaper();
5849
+ shaper.curve = driveCurve(drive);
5850
+ shaper.oversample = "4x";
5851
+ const level = ctx.createGain();
5852
+ level.gain.value = driveLevel(drive);
5853
+ last.connect(shaper);
5854
+ shaper.connect(level);
5855
+ last = level;
5856
+ }
5857
+ if (cabinet) {
5858
+ filter("highpass", 90, 0.7);
5859
+ filter("peaking", 2200, 1, 4);
5860
+ filter("lowpass", 4800, 0.7);
5861
+ filter("lowpass", 6500, 0.7);
5862
+ const level = ctx.createGain();
5863
+ level.gain.value = Math.pow(10, CABINET_TRIM_DB / 20);
5864
+ last.connect(level);
5865
+ last = level;
5866
+ }
5867
+ return { input, output: last };
5868
+ }
5869
+
5582
5870
  // src/playback/player.ts
5583
5871
  var DEFAULT_SEQUENCE = { bpm: 90, strum: 12 };
5584
5872
  var DEFAULT_STRUM = { guitar: 12, piano: 0 };
@@ -5768,6 +6056,25 @@ var PLUCKS = 4;
5768
6056
  var RELEASE = { guitar: 0.15, piano: 0.3 };
5769
6057
  var releaseOf = (sound, duration) => Math.min(RELEASE[sound], Math.max(0.03, duration / 2));
5770
6058
  var pianoDecay = (midi) => Math.min(2.5, Math.max(0.35, Math.pow(2, (60 - midi) / 24)));
6059
+ function sendOut(ctx, from, guitar, effects) {
6060
+ const out = outputFor(ctx, effects);
6061
+ const amp = !effects?.dry && (guitar === "clean" || guitar === "overdrive") ? ampFor(ctx, effects?.amp) : null;
6062
+ const cut = (node) => {
6063
+ try {
6064
+ node.disconnect();
6065
+ } catch {}
6066
+ };
6067
+ if (!amp) {
6068
+ from.connect(out);
6069
+ return () => cut(from);
6070
+ }
6071
+ from.connect(amp.input);
6072
+ amp.output.connect(out);
6073
+ return () => {
6074
+ cut(from);
6075
+ cut(amp.output);
6076
+ };
6077
+ }
5771
6078
  function lightPlayer(win, random = Math.random) {
5772
6079
  const strings = new Map;
5773
6080
  const waves = new WeakMap;
@@ -5800,7 +6107,7 @@ function lightPlayer(win, random = Math.random) {
5800
6107
  };
5801
6108
  return {
5802
6109
  reportsStart: true,
5803
- play(events, { sound, volume, onEnd, onStart, guitar }) {
6110
+ play(events, { sound, volume, onEnd, onStart, guitar, effects }) {
5804
6111
  const ctx = contextFor(win);
5805
6112
  if (!ctx || !events.length)
5806
6113
  return { stop() {} };
@@ -5821,7 +6128,7 @@ function lightPlayer(win, random = Math.random) {
5821
6128
  });
5822
6129
  const gain = ctx.createGain();
5823
6130
  gain.gain.value = Number.isFinite(volume) ? Math.min(1, Math.max(0, volume)) : 0.8;
5824
- gain.connect(ctx.destination);
6131
+ const letGo = sendOut(ctx, gain, sound === "guitar" ? tone : null, effects);
5825
6132
  const start = ctx.currentTime + 0.05;
5826
6133
  const sources = events.map((e, i) => {
5827
6134
  if (e.kind)
@@ -5857,7 +6164,7 @@ function lightPlayer(win, random = Math.random) {
5857
6164
  source.stop(Math.max(at + 0.006, end) + release);
5858
6165
  return source;
5859
6166
  });
5860
- const finish = () => gain.disconnect();
6167
+ const finish = () => letGo();
5861
6168
  let stopped = false;
5862
6169
  let heard;
5863
6170
  const announce = () => {
@@ -9296,7 +9603,32 @@ function playerFor(win, options, el) {
9296
9603
  }
9297
9604
  function toned(player, options, el) {
9298
9605
  const tone = guitarFor(options, el);
9299
- return tone ? withGuitar(player, tone) : player;
9606
+ const effects = effectsOf(options);
9607
+ return tone || effects ? withPlay(player, tone, effects) : player;
9608
+ }
9609
+ function effectsOf(options) {
9610
+ const read = (value) => {
9611
+ try {
9612
+ return (typeof value === "function" ? value() : value) ?? null;
9613
+ } catch {
9614
+ return null;
9615
+ }
9616
+ };
9617
+ const reverb = read(options.reverb);
9618
+ const room = read(options.room);
9619
+ const amp = read(options.amp);
9620
+ const effects = {
9621
+ ...typeof reverb === "number" && Number.isFinite(reverb) ? { reverb: Math.round(Math.min(1, Math.max(0, reverb)) * 1000) / 1000 } : {},
9622
+ ...typeof room === "number" && Number.isFinite(room) ? { room: Math.round(roomSeconds(room) * 100) / 100 } : {},
9623
+ ...read(options.dry) === true ? { dry: true } : {},
9624
+ ...amp && typeof amp === "object" && (amp.cabinet === true || typeof amp.drive === "number") ? {
9625
+ amp: {
9626
+ ...amp.cabinet === true ? { cabinet: true } : {},
9627
+ ...typeof amp.drive === "number" && Number.isFinite(amp.drive) ? { drive: Math.round(Math.min(1, Math.max(0, amp.drive)) * 100) / 100 } : {}
9628
+ }
9629
+ } : {}
9630
+ };
9631
+ return Object.keys(effects).length ? effects : null;
9300
9632
  }
9301
9633
  function guitarFor(options, el) {
9302
9634
  const wish = guitarChoice(el) ?? guitarWish(el);
@@ -9308,22 +9640,30 @@ function guitarFor(options, el) {
9308
9640
  return null;
9309
9641
  }
9310
9642
  }
9311
- var guitarPlayers = new WeakMap;
9312
- function withGuitar(player, guitar) {
9313
- let twins = guitarPlayers.get(player);
9643
+ var twinPlayers = new WeakMap;
9644
+ var TWINS_KEPT = 32;
9645
+ function withPlay(player, guitar, effects) {
9646
+ let twins = twinPlayers.get(player);
9314
9647
  if (!twins) {
9315
9648
  twins = new Map;
9316
- guitarPlayers.set(player, twins);
9649
+ twinPlayers.set(player, twins);
9317
9650
  }
9318
- let twin = twins.get(guitar);
9651
+ const key = `${guitar ?? ""}|${effects ? JSON.stringify(effects) : ""}`;
9652
+ let twin = twins.get(key);
9319
9653
  if (!twin) {
9320
9654
  twin = {
9321
9655
  get reportsStart() {
9322
9656
  return player.reportsStart;
9323
9657
  },
9324
- play: (events, options) => player.play(events, options.guitar ? options : { ...options, guitar })
9658
+ play: (events, options) => player.play(events, {
9659
+ ...options,
9660
+ ...guitar && !options.guitar ? { guitar } : {},
9661
+ ...effects && !options.effects ? { effects } : {}
9662
+ })
9325
9663
  };
9326
- twins.set(guitar, twin);
9664
+ if (twins.size >= TWINS_KEPT)
9665
+ twins.delete(twins.keys().next().value);
9666
+ twins.set(key, twin);
9327
9667
  }
9328
9668
  return twin;
9329
9669
  }
@@ -15605,5 +15945,5 @@ export {
15605
15945
  renderAll
15606
15946
  };
15607
15947
 
15608
- //# debugId=054081EECF4A18AD64756E2164756E21
15948
+ //# debugId=29E2BBD4A54230B564756E2164756E21
15609
15949
  //# sourceMappingURL=index.js.map