audiora 1.1.0 → 2.0.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/dist/index.d.cts CHANGED
@@ -1,132 +1,5 @@
1
- interface PresetData {
2
- osc_type: string;
3
- scale_name: string;
4
- base_note: number;
5
- bpm: number;
6
- speed: number;
7
- note_mult: number;
8
- volume: number;
9
- vibrato_rate: number;
10
- vibrato_depth: number;
11
- tremolo_rate: number;
12
- tremolo_depth: number;
13
- fifth_lvl: number;
14
- oct_lvl: number;
15
- filter_base: number;
16
- filter_track: number;
17
- resonance: number;
18
- reverb_mix: number;
19
- reverb_time: number;
20
- bass_gain: number;
21
- block_w: number;
22
- block_h: number;
23
- scan_mode: string;
24
- pan_amount: number;
25
- timing_mode: string;
26
- timing_intensity: number;
27
- }
28
- type FormatFn = (v: number) => string;
29
-
30
- type TweenTickHandler = (key: string, value: number) => void;
31
-
32
- type ImageSource = string | File | Blob | HTMLImageElement;
33
-
34
- type AudioraEventType = "start" | "stop" | "noteplay" | "imageload" | "error";
35
- interface AudioraStartEvent extends CustomEvent<{
36
- timestamp: number;
37
- }> {
38
- readonly type: "start";
39
- }
40
- interface AudioraStopEvent extends CustomEvent<{
41
- timestamp: number;
42
- duration: number;
43
- }> {
44
- readonly type: "stop";
45
- }
46
- interface AudioraNotePlayEvent extends CustomEvent<{
47
- freq: number;
48
- vel: number;
49
- pan: number;
50
- blockIndex: number;
51
- timestamp: number;
52
- }> {
53
- readonly type: "noteplay";
54
- }
55
- interface AudioraImageLoadEvent extends CustomEvent<{
56
- width: number;
57
- height: number;
58
- blockCount: number;
59
- }> {
60
- readonly type: "imageload";
61
- }
62
- interface AudioraErrorEvent extends CustomEvent<{
63
- error: Error;
64
- context: string;
65
- }> {
66
- readonly type: "error";
67
- }
68
- interface AudioraEventMap {
69
- start: AudioraStartEvent;
70
- stop: AudioraStopEvent;
71
- noteplay: AudioraNotePlayEvent;
72
- imageload: AudioraImageLoadEvent;
73
- error: AudioraErrorEvent;
74
- }
75
- type AudioraEvent = AudioraEventMap[AudioraEventType];
76
-
77
- interface RenderOptions {
78
- image?: ImageSource;
79
- params?: Partial<PresetData>;
80
- duration?: number;
81
- sampleRate?: number;
82
- }
83
- interface LiveOptions {
84
- waveCanvas?: HTMLCanvasElement;
85
- mapCanvas?: HTMLCanvasElement;
86
- onTweenTick?: TweenTickHandler;
87
- }
88
- interface Audiora {
89
- addEventListener<K extends AudioraEventType>(type: K, listener: (this: Audiora, event: AudioraEventMap[K]) => void, options?: boolean | AddEventListenerOptions): void;
90
- addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void;
91
- removeEventListener<K extends AudioraEventType>(type: K, listener: (this: Audiora, event: AudioraEventMap[K]) => void, options?: boolean | EventListenerOptions): void;
92
- removeEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions): void;
93
- }
94
- declare class Audiora extends EventTarget {
95
- private readonly state;
96
- private readonly engine;
97
- private readonly imageProcessor;
98
- private readonly grid;
99
- private readonly seq;
100
- private readonly synth;
101
- private readonly scheduler;
102
- private readonly tweener;
103
- private renderer;
104
- private reverbDebounce;
105
- private loadedImage;
106
- private playStartTime;
107
- constructor(options?: LiveOptions);
108
- get playing(): boolean;
109
- attachVisuals(waveCanvas: HTMLCanvasElement, mapCanvas: HTMLCanvasElement): void;
110
- resizeVisuals(): void;
111
- loadImage(image: ImageSource): Promise<void>;
112
- play(): Promise<void>;
113
- stop(): void;
114
- warmUp(): Promise<void>;
115
- getParam(key: keyof PresetData): string | number;
116
- setParam(key: keyof PresetData, value: string | number): void;
117
- applyParams(patch: Partial<PresetData>, options?: {
118
- tween?: boolean;
119
- }): void;
120
- captureParams(): Partial<PresetData>;
121
- toAudioBuffer(options?: RenderOptions): Promise<AudioBuffer>;
122
- toBlob(options?: RenderOptions): Promise<Blob>;
123
- private renderOffline;
124
- private rebuildGrid;
125
- private applyParamSideEffects;
126
- private syncLiveAudioFromState;
127
- private emit;
128
- private emitError;
129
- }
1
+ import { k as PresetData, F as FormatFn, A as Audiora$1, L as LiveOptions, M as Multimodal, a as AudioraProviders } from './types-Cm-vGOKS.cjs';
2
+ export { l as AudioraErrorEvent, m as AudioraEvent, n as AudioraEventMap, o as AudioraEventType, p as AudioraImageLoadEvent, q as AudioraMode, r as AudioraNotePlayEvent, s as AudioraStartEvent, t as AudioraStopEvent, I as ImageSource, R as RenderOptions, j as VisionProviderName } from './types-Cm-vGOKS.cjs';
130
3
 
131
4
  declare const PRESETS: Record<string, PresetData>;
132
5
 
@@ -135,4 +8,15 @@ declare const RANGE_KEYS: (keyof PresetData)[];
135
8
  declare const SELECT_KEYS: (keyof PresetData)[];
136
9
  declare const DEFAULT_PRESET = "Haze";
137
10
 
138
- export { Audiora, type AudioraErrorEvent, type AudioraEvent, type AudioraEventMap, type AudioraEventType, type AudioraImageLoadEvent, type AudioraNotePlayEvent, type AudioraStartEvent, type AudioraStopEvent, DEFAULT_PRESET, FORMAT, type ImageSource, type LiveOptions, PRESETS, type PresetData, RANGE_KEYS, type RenderOptions, SELECT_KEYS };
11
+ type Audiora = Audiora$1;
12
+ declare const Audiora: {
13
+ new (options: LiveOptions & {
14
+ mode: "multimodal";
15
+ }): Audiora$1 & Multimodal;
16
+ new (options: LiveOptions & {
17
+ providers: AudioraProviders;
18
+ }): Audiora$1 & Multimodal;
19
+ new (options?: LiveOptions): Audiora$1;
20
+ };
21
+
22
+ export { Audiora, AudioraProviders, DEFAULT_PRESET, FORMAT, LiveOptions, PRESETS, PresetData, RANGE_KEYS, SELECT_KEYS };
package/dist/index.d.ts CHANGED
@@ -1,132 +1,5 @@
1
- interface PresetData {
2
- osc_type: string;
3
- scale_name: string;
4
- base_note: number;
5
- bpm: number;
6
- speed: number;
7
- note_mult: number;
8
- volume: number;
9
- vibrato_rate: number;
10
- vibrato_depth: number;
11
- tremolo_rate: number;
12
- tremolo_depth: number;
13
- fifth_lvl: number;
14
- oct_lvl: number;
15
- filter_base: number;
16
- filter_track: number;
17
- resonance: number;
18
- reverb_mix: number;
19
- reverb_time: number;
20
- bass_gain: number;
21
- block_w: number;
22
- block_h: number;
23
- scan_mode: string;
24
- pan_amount: number;
25
- timing_mode: string;
26
- timing_intensity: number;
27
- }
28
- type FormatFn = (v: number) => string;
29
-
30
- type TweenTickHandler = (key: string, value: number) => void;
31
-
32
- type ImageSource = string | File | Blob | HTMLImageElement;
33
-
34
- type AudioraEventType = "start" | "stop" | "noteplay" | "imageload" | "error";
35
- interface AudioraStartEvent extends CustomEvent<{
36
- timestamp: number;
37
- }> {
38
- readonly type: "start";
39
- }
40
- interface AudioraStopEvent extends CustomEvent<{
41
- timestamp: number;
42
- duration: number;
43
- }> {
44
- readonly type: "stop";
45
- }
46
- interface AudioraNotePlayEvent extends CustomEvent<{
47
- freq: number;
48
- vel: number;
49
- pan: number;
50
- blockIndex: number;
51
- timestamp: number;
52
- }> {
53
- readonly type: "noteplay";
54
- }
55
- interface AudioraImageLoadEvent extends CustomEvent<{
56
- width: number;
57
- height: number;
58
- blockCount: number;
59
- }> {
60
- readonly type: "imageload";
61
- }
62
- interface AudioraErrorEvent extends CustomEvent<{
63
- error: Error;
64
- context: string;
65
- }> {
66
- readonly type: "error";
67
- }
68
- interface AudioraEventMap {
69
- start: AudioraStartEvent;
70
- stop: AudioraStopEvent;
71
- noteplay: AudioraNotePlayEvent;
72
- imageload: AudioraImageLoadEvent;
73
- error: AudioraErrorEvent;
74
- }
75
- type AudioraEvent = AudioraEventMap[AudioraEventType];
76
-
77
- interface RenderOptions {
78
- image?: ImageSource;
79
- params?: Partial<PresetData>;
80
- duration?: number;
81
- sampleRate?: number;
82
- }
83
- interface LiveOptions {
84
- waveCanvas?: HTMLCanvasElement;
85
- mapCanvas?: HTMLCanvasElement;
86
- onTweenTick?: TweenTickHandler;
87
- }
88
- interface Audiora {
89
- addEventListener<K extends AudioraEventType>(type: K, listener: (this: Audiora, event: AudioraEventMap[K]) => void, options?: boolean | AddEventListenerOptions): void;
90
- addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void;
91
- removeEventListener<K extends AudioraEventType>(type: K, listener: (this: Audiora, event: AudioraEventMap[K]) => void, options?: boolean | EventListenerOptions): void;
92
- removeEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions): void;
93
- }
94
- declare class Audiora extends EventTarget {
95
- private readonly state;
96
- private readonly engine;
97
- private readonly imageProcessor;
98
- private readonly grid;
99
- private readonly seq;
100
- private readonly synth;
101
- private readonly scheduler;
102
- private readonly tweener;
103
- private renderer;
104
- private reverbDebounce;
105
- private loadedImage;
106
- private playStartTime;
107
- constructor(options?: LiveOptions);
108
- get playing(): boolean;
109
- attachVisuals(waveCanvas: HTMLCanvasElement, mapCanvas: HTMLCanvasElement): void;
110
- resizeVisuals(): void;
111
- loadImage(image: ImageSource): Promise<void>;
112
- play(): Promise<void>;
113
- stop(): void;
114
- warmUp(): Promise<void>;
115
- getParam(key: keyof PresetData): string | number;
116
- setParam(key: keyof PresetData, value: string | number): void;
117
- applyParams(patch: Partial<PresetData>, options?: {
118
- tween?: boolean;
119
- }): void;
120
- captureParams(): Partial<PresetData>;
121
- toAudioBuffer(options?: RenderOptions): Promise<AudioBuffer>;
122
- toBlob(options?: RenderOptions): Promise<Blob>;
123
- private renderOffline;
124
- private rebuildGrid;
125
- private applyParamSideEffects;
126
- private syncLiveAudioFromState;
127
- private emit;
128
- private emitError;
129
- }
1
+ import { k as PresetData, F as FormatFn, A as Audiora$1, L as LiveOptions, M as Multimodal, a as AudioraProviders } from './types-Cm-vGOKS.js';
2
+ export { l as AudioraErrorEvent, m as AudioraEvent, n as AudioraEventMap, o as AudioraEventType, p as AudioraImageLoadEvent, q as AudioraMode, r as AudioraNotePlayEvent, s as AudioraStartEvent, t as AudioraStopEvent, I as ImageSource, R as RenderOptions, j as VisionProviderName } from './types-Cm-vGOKS.js';
130
3
 
131
4
  declare const PRESETS: Record<string, PresetData>;
132
5
 
@@ -135,4 +8,15 @@ declare const RANGE_KEYS: (keyof PresetData)[];
135
8
  declare const SELECT_KEYS: (keyof PresetData)[];
136
9
  declare const DEFAULT_PRESET = "Haze";
137
10
 
138
- export { Audiora, type AudioraErrorEvent, type AudioraEvent, type AudioraEventMap, type AudioraEventType, type AudioraImageLoadEvent, type AudioraNotePlayEvent, type AudioraStartEvent, type AudioraStopEvent, DEFAULT_PRESET, FORMAT, type ImageSource, type LiveOptions, PRESETS, type PresetData, RANGE_KEYS, type RenderOptions, SELECT_KEYS };
11
+ type Audiora = Audiora$1;
12
+ declare const Audiora: {
13
+ new (options: LiveOptions & {
14
+ mode: "multimodal";
15
+ }): Audiora$1 & Multimodal;
16
+ new (options: LiveOptions & {
17
+ providers: AudioraProviders;
18
+ }): Audiora$1 & Multimodal;
19
+ new (options?: LiveOptions): Audiora$1;
20
+ };
21
+
22
+ export { Audiora, AudioraProviders, DEFAULT_PRESET, FORMAT, LiveOptions, PRESETS, PresetData, RANGE_KEYS, SELECT_KEYS };
package/dist/index.js CHANGED
@@ -1,2 +1,6 @@
1
- var f=[{name:"Major",intervals:[0,2,4,5,7,9,11,12]},{name:"Minor",intervals:[0,2,3,5,7,8,10,12]},{name:"Pentatonic",intervals:[0,2,4,7,9,12]},{name:"Blues",intervals:[0,3,5,6,7,10,12]},{name:"Chromatic",intervals:[0,1,2,3,4,5,6,7,8,9,10,11,12]},{name:"Whole Tone",intervals:[0,2,4,6,8,10,12]},{name:"Dorian",intervals:[0,2,3,5,7,9,10,12]},{name:"Phrygian",intervals:[0,1,3,5,7,8,10,12]},{name:"Lydian",intervals:[0,2,4,6,7,9,11,12]},{name:"Harmonic Minor",intervals:[0,2,3,5,7,8,11,12]},{name:"In Sen",intervals:[0,1,5,7,10,12]}],F=["osc_type","scale_name","base_note","bpm","speed","note_mult","volume","vibrato_rate","vibrato_depth","tremolo_rate","tremolo_depth","fifth_lvl","oct_lvl","filter_base","filter_track","resonance","reverb_mix","reverb_time","bass_gain","block_w","block_h","scan_mode","pan_amount","timing_mode","timing_intensity"],Z={volume:r=>`${Math.round(r*100)}%`,bpm:r=>String(Math.round(r)),speed:r=>`\xD7${r.toFixed(2)}`,note_mult:r=>`\xD7${r.toFixed(2)}`,base_note:r=>`${Math.round(r)} Hz`,fifth_lvl:r=>`${Math.round(r*100)}%`,oct_lvl:r=>`${Math.round(r*100)}%`,vibrato_rate:r=>`${r.toFixed(1)} Hz`,vibrato_depth:r=>`${Math.round(r)} \xA2`,tremolo_rate:r=>`${r.toFixed(1)} Hz`,tremolo_depth:r=>`${Math.round(r*100)}%`,filter_base:r=>`${Math.round(r)} Hz`,filter_track:r=>`${Math.round(r)} Hz`,resonance:r=>r.toFixed(2),reverb_mix:r=>`${Math.round(r*100)}%`,reverb_time:r=>`${r.toFixed(1)} s`,bass_gain:r=>`${r.toFixed(1)} dB`,block_w:r=>`${Math.round(r)} px`,block_h:r=>`${Math.round(r)} px`,pan_amount:r=>`${Math.round(r*100)}%`,timing_intensity:r=>`${Math.round(r*100)}%`},pe=Object.keys(Z),ve=F.filter(r=>!(r in Z)),u=F.reduce((r,e)=>(r[e]=e,r),{}),Q=1.2,ue=1500,be="Haze",J=[u.volume,u.base_note,u.vibrato_rate,u.vibrato_depth,u.tremolo_rate,u.tremolo_depth,u.fifth_lvl,u.oct_lvl,u.filter_base,u.filter_track,u.resonance,u.reverb_mix,u.reverb_time,u.bass_gain,u.pan_amount];var G=class{constructor(){this.playing=false;this.scale=f[0];this.osc_type="triangle";this.scale_name="Minor";this.base_note=287;this.bpm=70;this.speed=4.2;this.note_mult=.15;this.volume=.99;this.vibrato_rate=0;this.vibrato_depth=50;this.tremolo_rate=1.8;this.tremolo_depth=0;this.fifth_lvl=.37;this.oct_lvl=.63;this.filter_base=1810;this.filter_track=0;this.resonance=2.6;this.reverb_mix=1;this.reverb_time=3.6;this.bass_gain=13.5;this.block_w=23;this.block_h=13;this.scan_mode="linear";this.pan_amount=.6;this.timing_mode="expressive";this.timing_intensity=.4;}applyPatch(e){e.osc_type&&(this.osc_type=e.osc_type),e.scale_name&&(this.scale_name=e.scale_name,this.scale=f.find(t=>t.name===e.scale_name)??f[0]),e.scan_mode&&(this.scan_mode=e.scan_mode),e.timing_mode&&(this.timing_mode=e.timing_mode),typeof e.bpm=="number"&&(this.bpm=e.bpm),typeof e.speed=="number"&&(this.speed=e.speed),typeof e.note_mult=="number"&&(this.note_mult=e.note_mult),typeof e.timing_intensity=="number"&&(this.timing_intensity=e.timing_intensity),typeof e.block_w=="number"&&(this.block_w=e.block_w),typeof e.block_h=="number"&&(this.block_h=e.block_h);}applyAll(e){F.forEach(t=>{let i=e[t];if(i!==void 0){if(t==="scale_name"&&typeof i=="string"){this.scale_name=i,this.scale=f.find(a=>a.name===i)??f[0];return}this[t]=i;}});}capture(){let e={};return F.forEach(t=>{e[t]=this[t];}),e}setNumeric(e,t){this[e]=t;}getNumeric(e){return this[e]}getString(e){return this[e]}setString(e,t){this[e]=t;}};var O=class{constructor(){this._ctx=null;this._master=null;this._analyser=null;this._conv=null;this._wet=null;this._dry=null;}get ctx(){return this._ctx}get master(){return this._master}get analyser(){return this._analyser}get conv(){return this._conv}get wet(){return this._wet}get dry(){return this._dry}ensure(e){if(this._ctx)return;let t=window.AudioContext??window.webkitAudioContext;t&&this.buildGraph(new t,e);}ensureOffline(e,t){this.buildGraph(e,t);}buildGraph(e,t){let i=e.createGain(),a=e.createAnalyser(),n=e.createGain(),s=e.createGain(),o=e.createConvolver();i.gain.value=Math.pow(t.volume??.8,2),a.fftSize=1024,a.smoothingTimeConstant=.88,o.buffer=this.makeImpulse(e,t.reverb_time,3),s.gain.value=t.reverb_mix,n.gain.value=this.dryVal(t.reverb_mix),o.connect(s),n.connect(a),s.connect(a),a.connect(i),i.connect(e.destination),this._ctx=e,this._master=i,this._analyser=a,this._conv=o,this._wet=s,this._dry=n;}makeImpulse(e,t,i){let a=Math.max(1,Math.floor(e.sampleRate*t)),n=e.createBuffer(2,a,e.sampleRate);for(let s=0;s<2;s++){let o=n.getChannelData(s);for(let l=0;l<a;l++)o[l]=(Math.random()*2-1)*Math.pow(1-l/a,i);}return n}dryVal(e){return e>=.99?0:1-e}smooth(e,t,i=.02){!this._ctx||!isFinite(t)||e.setTargetAtTime(t,this._ctx.currentTime,i);}async resume(){this._ctx instanceof AudioContext&&this._ctx.state==="suspended"&&await this._ctx.resume();}suspend(){this._ctx instanceof AudioContext&&this._ctx.state==="running"&&this._ctx.suspend().catch(()=>{});}async warmUp(e){if(this.ensure(e),!(this._ctx instanceof AudioContext))return;await this.resume();let t=this._ctx.createOscillator(),i=this._ctx.createGain();i.gain.value=1e-5,t.connect(i).connect(this._master),t.start(),t.stop(this._ctx.currentTime+.15);}updateReverbBuffer(e){!this._ctx||!this._conv||(this._conv.buffer=this.makeImpulse(this._ctx,e.reverb_time,3));}};function b(r,e,t){return Math.max(e,Math.min(t,r))}function $(r){return 440*Math.pow(2,(r-69)/12)}function Y(r){return 69+12*Math.log2(r/440)}function me(r,e,t){r/=255,e/=255,t/=255;let i=Math.max(r,e,t),a=Math.min(r,e,t),n=0,s=0,o=(i+a)/2,l=i-a;if(l){switch(s=o>.5?l/(2-i-a):l/(i+a),i){case r:n=(e-t)/l+(e<t?6:0);break;case e:n=(t-r)/l+2;break;case t:n=(r-e)/l+4;break}n*=60;}let m=i===0?0:l/i;return {h:n,s_hsl:s,s_hsv:m,l:o*100}}function he(r){return r<.5?2*r*r:-1+(4-2*r)*r}var N=class{constructor(e,t){this.engine=e;this.state=t;}expressiveCurve(e){return .75+Math.pow(e/100,1.3)*.5}getIntensity(){return Math.pow(this.state.timing_intensity??1,1.5)}getStepDur(){let e=isFinite(this.state.bpm)&&this.state.bpm>0?this.state.bpm:120,t=isFinite(this.state.speed)&&this.state.speed>0?this.state.speed:1;return Math.max(.05,60/e/b(t,.5,8))}getSpeedMod(e){let t=this.expressiveCurve(e);return b(1+(t-1)*this.getIntensity()*Q*.6,.85,1.2)}scheduleNote(e,t,i,a,n){let s=this.engine.ctx,o=this.engine.dry,l=this.engine.conv;if(!s||!o||!l)return n;let m=this.state.speed>2?.003:5e-4,p=(Math.random()-.5)*m;if(n=Math.max(n+p,s.currentTime+.001),!isFinite(n))return n;let c=this.state,d=this.getStepDur(),h=this.expressiveCurve(i*100),v=b(1+(h-1)*this.getIntensity()*Q*.75,.85,1.2),_=b(isFinite(d)?d*c.note_mult*(.6+.8*t)*v:.2,.06,2),B=c.filter_track===0?c.filter_base:b(c.filter_base+i*c.filter_track,40,s.sampleRate*.45),y=s.createBiquadFilter();y.type="lowpass",y.Q.value=c.resonance,y.frequency.setValueAtTime(B,n);let g=s.createGain();g.gain.setValueAtTime(0,n);let P=s.createGain();P.gain.setValueAtTime(1-c.tremolo_depth,n);let x=s.createOscillator();x.frequency.setValueAtTime(c.tremolo_rate,n);let I=s.createGain();I.gain.setValueAtTime(c.tremolo_depth,n),x.connect(I).connect(P.gain);let k=s.createBiquadFilter();k.type="lowshelf",k.frequency.setValueAtTime(200,n),k.gain.setValueAtTime(c.bass_gain,n);let E=s.createStereoPanner();E.pan.setValueAtTime(b(a,-1,1),n),y.connect(g),g.connect(P),P.connect(k),k.connect(E),E.connect(l),E.connect(o);let q=.2+t*.6;g.gain.linearRampToValueAtTime(q,n+.01),g.gain.setTargetAtTime(q*.6,n+.03,.05),g.gain.setTargetAtTime(1e-4,n+_*.7,.1);let L=s.createGain(),T=s.createOscillator();this.applyWave(T,s),T.frequency.setValueAtTime(e,n);let S=s.createOscillator();this.applyWave(S,s),S.frequency.setValueAtTime(e*1.5,n);let A=s.createOscillator();this.applyWave(A,s),A.frequency.setValueAtTime(e*2,n);let M=s.createOscillator();M.frequency.setValueAtTime(c.vibrato_rate,n);let w=s.createGain();w.gain.setValueAtTime(e*(Math.pow(2,c.vibrato_depth/1200)-1),n),M.connect(w),w.connect(T.frequency),w.connect(S.frequency),w.connect(A.frequency);let D=s.createGain(),oe=s.createGain(),le=b(c.fifth_lvl,0,1),ce=b(c.oct_lvl,0,1);c.osc_type==="bell"&&(le*=.35,ce*=.25),D.gain.setValueAtTime(le,n),oe.gain.setValueAtTime(ce,n),T.connect(L),S.connect(D).connect(L),A.connect(oe).connect(L),L.connect(y);let W=n+_+.05;return T.start(n),T.stop(W),S.start(n),S.stop(W),A.start(n),A.stop(W),M.start(n),M.stop(W),x.start(n),x.stop(n+_+.1),n}applyWave(e,t){let i=this.state.osc_type;if(["sine","square","sawtooth","triangle"].includes(i)){e.type=i;return}if(i==="pulse"){let a=new Float32Array([0,0,0,0,0,0,0,0]),n=new Float32Array([0,1,0,.33,0,.2,0,.14]);e.setPeriodicWave(t.createPeriodicWave(a,n));return}if(i==="organ"){let a=new Float32Array([0,1,.8,.6,.45,.3,.2]),n=new Float32Array(a.length);e.setPeriodicWave(t.createPeriodicWave(a,n));return}if(i==="bell"){let a=new Float32Array([0,1,.9,.55,.32,.18,.09,.04]),n=new Float32Array(a.length);e.setPeriodicWave(t.createPeriodicWave(a,n));return}e.type="triangle";}};var C=class{},ee=class extends C{advance(e,t,i){e.x++,e.x>=t&&(e.x=0,e.y=(e.y+1)%i);}reset(e,t){e.x=0,e.y=0;}},te=class extends C{advance(e,t,i){e.y++,e.y>=i&&(e.y=0,e.x=(e.x+1)%t);}reset(e,t){e.x=0,e.y=0;}},ie=class extends C{advance(e,t,i){e.x+=e.dx,e.x>=t?(e.x=t-1,e.dx=-1,e.y=(e.y+1)%i):e.x<0&&(e.x=0,e.dx=1,e.y=(e.y+1)%i);}reset(e,t){e.x=0,e.y=0,e.dx=1;}},ne=class extends C{advance(e,t,i){let a=e.lastL??50,n=0,s=0;if(Math.random()<.05){e.x=Math.floor(Math.random()*t),e.y=Math.floor(Math.random()*i);return}a>60?n=1:a<40?n=-1:s=Math.random()<.5?1:-1,Math.random()<.15&&(n=Math.floor(Math.random()*3)-1,s=Math.floor(Math.random()*3)-1),e.x=(e.x+n+t)%t,e.y=(e.y+s+i)%i;}reset(e,t){e.x=0,e.y=0;}},re=class extends C{advance(e,t,i){let a=e.grid.spiralPath;if(!a.length)return;e.spiralIdx=(e.spiralIdx+1)%a.length;let n=a[e.spiralIdx];e.x=n.x,e.y=n.y;}reset(e,t){e.spiralIdx=0,t.spiralPath.length?(e.x=t.spiralPath[0].x,e.y=t.spiralPath[0].y):(e.x=0,e.y=0);}},H=class{static get(e){return this.strategies[e]??this.strategies.linear}};H.strategies={linear:new ee,vertical:new te,zigzag:new ie,drift:new ne,spiral:new re};var R=class{constructor(e){this.grid=e;this.x=0;this.y=0;this.dx=1;this.visX=0;this.visY=0;this.renderX=0;this.renderY=0;this.visIdx=0;this.nextTime=0;this.raf=null;this.lastL=50;this.active=false;this.spiralIdx=0;this.activateAt=0;}resetPosition(e){H.get(e.scan_mode).reset(this,this.grid),this.dx=1,this.visX=0,this.visY=0,this.renderX=0,this.renderY=0,this.visIdx=0,this.lastL=50,this.active=false,this.spiralIdx=0,this.activateAt=0;}currentBlockIdx(){let e=this.y*this.grid.cols+this.x;return isFinite(e)?b(e,0,this.grid.list.length-1):0}advance(e){let t=this.grid.cols,i=this.grid.rows;if(t<=0||i<=0)return;H.get(e.scan_mode).advance(this,t,i);}clampToGrid(){this.x=Math.min(this.x,Math.max(0,this.grid.cols-1)),this.y=Math.min(this.y,Math.max(0,this.grid.rows-1));}static mapBlockToNote(e,t,i){let a=t.intervals[e.degree%t.intervals.length]+12*e.oct,n=e.pan*5,s=$(Y(i.base_note)+a+n/100),o=e.pan*i.pan_amount;return {freq:s,vel:e.vel,brightness:e.l/100,pan:o}}};var V=class{constructor(e,t,i,a,n,s){this.state=e;this.engine=t;this.synth=i;this.seq=a;this.grid=n;this.onNotePlay=s;this.raf=null;this.tick=()=>{if(!this.state.playing||!this.engine.ctx)return;let e=this.engine.ctx.currentTime;this.seq.nextTime<e-.02&&(this.seq.nextTime=e);let t=this.synth.getStepDur(),i=b(t*2.5,.12,.3);if(this.grid.list.length&&this.grid.cols&&this.grid.rows)for(;this.seq.nextTime<e+i;)if(this.playStep(this.seq.nextTime),this.state.timing_mode==="expressive"){let a=this.synth.getSpeedMod(this.seq.lastL??50);this.seq.nextTime+=t/a;}else this.seq.nextTime+=t;this.raf=requestAnimationFrame(this.tick);};}start(){this.engine.ctx&&(this.seq.nextTime=this.engine.ctx.currentTime+.03,this.raf&&cancelAnimationFrame(this.raf),this.tick());}stop(){this.raf&&(cancelAnimationFrame(this.raf),this.raf=null);}resync(){if(!this.engine.ctx)return;let e=this.engine.ctx.currentTime;this.seq.nextTime<e-.02&&(this.seq.nextTime=e+.02);}renderRange(e,t){if(!(this.grid.list.length&&this.grid.cols&&this.grid.rows))return;let i=this.synth.getStepDur(),a=e;for(;a<t;)if(this.playStep(a),this.state.timing_mode==="expressive"){let n=this.synth.getSpeedMod(this.seq.lastL??50);a+=i/n;}else a+=i;}playStep(e){let t=this.state.scale??f[0];if(this.grid.list.length>0){let i=this.seq.currentBlockIdx(),a=this.grid.list[i];if(a){this.seq.visIdx=i,this.seq.lastL=a.l;let n=R.mapBlockToNote(a,t,this.state);this.synth.scheduleNote(n.freq,n.vel,n.brightness,n.pan,e),this.onNotePlay?.({freq:n.freq,vel:n.vel,pan:n.pan,blockIndex:i,timestamp:e});}}else {let i=Math.floor(this.seq.x%64/64*(t.intervals.length-1)),a=$(Y(this.state.base_note)+t.intervals[i]);this.seq.lastL=50,this.synth.scheduleNote(a,.6,.5,0,e),this.onNotePlay?.({freq:a,vel:.6,pan:0,blockIndex:-1,timestamp:e});}this.seq.visX=this.seq.x,this.seq.visY=this.seq.y,this.seq.activateAt===0&&(this.seq.activateAt=e),this.seq.advance(this.state);}};var U=class{constructor(){this._canvas=null;this._pixels=null;this._w=0;this._h=0;}get canvas(){return this._canvas}get pixels(){return this._pixels}get width(){return this._w}get height(){return this._h}processImage(e){let i=Math.min(2048/e.naturalWidth,2048/e.naturalHeight,1),a=Math.max(1,Math.floor(e.naturalWidth*i)),n=Math.max(1,Math.floor(e.naturalHeight*i)),s=document.createElement("canvas");s.width=a,s.height=n;let o=s.getContext("2d");o.imageSmoothingEnabled=true,o.drawImage(e,0,0,a,n),this._canvas=s;let l=512,m=Math.min(l/e.naturalWidth,l/e.naturalHeight,1),p=Math.max(1,Math.floor(e.naturalWidth*m)),c=Math.max(1,Math.floor(e.naturalHeight*m)),d=document.createElement("canvas");d.width=p,d.height=c;let h=d.getContext("2d",{willReadFrequently:true});h.imageSmoothingEnabled=true,h.drawImage(e,0,0,p,c);let v=h.getImageData(0,0,p,c);this._pixels=v.data,this._w=p,this._h=c;}loadDefault(e,t){let i=new Image;i.onload=()=>t(i),i.onerror=()=>{},i.src=e;}},z=class{constructor(){this._list=[];this._cols=0;this._rows=0;this._spiralPath=[];}get list(){return this._list}get cols(){return this._cols}get rows(){return this._rows}get spiralPath(){return this._spiralPath}build(e,t){if(this._list=[],this._cols=0,this._rows=0,!e.pixels)return;let i=t.scale??f[0],a=Math.max(1,Math.floor(t.block_w)),n=Math.max(1,Math.floor(t.block_h)),s=Math.max(1,Math.floor(e.width/a)),o=Math.max(1,Math.floor(e.height/n));this._cols=s,this._rows=o;let l=i.intervals.length-1,m=e.pixels,p=e.width;for(let c=0;c<o;c++)for(let d=0;d<s;d++){let h=d*a,v=c*n,_=Math.min(h+a,e.width),B=Math.min(v+n,e.height),y=0,g=0,P=0,x=0;for(let M=v;M<B;M++)for(let w=h;w<_;w++){let D=(M*p+w)*4;y+=m[D],g+=m[D+1],P+=m[D+2],x++;}if(x===0)continue;let{h:I,s_hsv:k,l:E}=me(y/x,g/x,P/x),q=isFinite(I)?I:0,L=b(Math.floor(Math.sqrt(q/360)*l),0,l),T=Math.floor(E/100*3)-1,S=b(.2+E/100*.5+k*.3,.1,1),A=q/360*2-1;this._list.push({degree:L,oct:T,vel:S,l:E,pan:A});}this._spiralPath=this.buildSpiralPath(s,o);}buildSpiralPath(e,t){let i=Math.floor(e/2),a=Math.floor(t/2),n=[],s=new Set,o=i,l=a,m=1,p=0,c=[1,0,-1,0],d=[0,1,0,-1];for(;n.length<e*t;){for(let h=0;h<2;h++){for(let v=0;v<m;v++){let _=`${o},${l}`;o>=0&&o<e&&l>=0&&l<t&&!s.has(_)&&(n.push({x:o,y:l}),s.add(_)),o+=c[p],l+=d[p];}p=(p+1)%4;}if(m++,n.length>=e*t)break}if(n.length<e*t)for(let h=0;h<t;h++)for(let v=0;v<e;v++)s.has(`${v},${h}`)||n.push({x:v,y:h});return n}};function de(r){let e=r.numberOfChannels,t=e*2,i=r.length*t,a=new ArrayBuffer(44+i),n=new DataView(a);return fe(n,r.sampleRate,e,t,i),ge(n,r,e),new Blob([a],{type:"audio/wav"})}function fe(r,e,t,i,a){K(r,0,"RIFF"),r.setUint32(4,36+a,true),K(r,8,"WAVE"),K(r,12,"fmt "),r.setUint32(16,16,true),r.setUint16(20,1,true),r.setUint16(22,t,true),r.setUint32(24,e,true),r.setUint32(28,e*i,true),r.setUint16(32,i,true),r.setUint16(34,16,true),K(r,36,"data"),r.setUint32(40,a,true);}function ge(r,e,t){let i=[];for(let n=0;n<t;n++)i.push(e.getChannelData(n));let a=44;for(let n=0;n<e.length;n++)for(let s=0;s<t;s++)r.setInt16(a,_e(i[s][n]),true),a+=2;}function _e(r){let e=Math.max(-1,Math.min(1,r));return e<0?e*32768:e*32767}function K(r,e,t){for(let i=0;i<t.length;i++)r.setUint8(e+i,t.charCodeAt(i));}var j=class{constructor(e,t,i){this.state=e;this.engine=t;this.onTick=i;this.raf=null;}tweenTo(e){this.raf&&(cancelAnimationFrame(this.raf),this.raf=null);let t={};J.forEach(n=>{let s=e[n];if(typeof s=="number"&&isFinite(s)){let o=this.state.getNumeric(n);t[n]=isFinite(o)?o:s;}});let i=performance.now(),a=()=>{let n=Math.min((performance.now()-i)/ue,1),s=he(n);J.forEach(o=>{if(t[o]===void 0)return;let l=e[o],m=t[o]+(l-t[o])*s;this.state.setNumeric(o,m),this.onTick?.(o,m);}),isFinite(this.state.volume)&&this.engine.master&&(this.engine.master.gain.value=Math.pow(this.state.volume,2)),isFinite(this.state.reverb_mix)&&this.engine.wet&&(this.engine.wet.gain.value=this.state.reverb_mix,this.engine.dry.gain.value=this.engine.dryVal(this.state.reverb_mix)),n<1?this.raf=requestAnimationFrame(a):t.reverb_time!==void 0&&this.engine.updateReverbBuffer(this.state);};this.raf=requestAnimationFrame(a);}cancel(){this.raf&&(cancelAnimationFrame(this.raf),this.raf=null);}};var X=class{constructor(e,t,i,a,n,s){this.engine=i;this.imageProcessor=a;this.grid=n;this.seq=s;this.waveBuf=null;this.drawT=0;this.renderRaf=null;this.renderFrame=()=>{this.renderRaf=requestAnimationFrame(this.renderFrame);let e=performance.now();if(e-this.drawT<1e3/60)return;this.drawT=e;let t=this.canvasCssSize(this.waveCanvas),i=this.canvasCssSize(this.mapCanvas);this.drawWave(t.w,t.h),this.drawMap(i.w,i.h);};this.waveCanvas=e,this.mapCanvas=t;}start(){this.resizeCanvases(),this.renderFrame();}stop(){this.renderRaf&&(cancelAnimationFrame(this.renderRaf),this.renderRaf=null);}resizeCanvases(){let e=window.devicePixelRatio||1;[this.waveCanvas,this.mapCanvas].forEach(t=>{if(!t)return;let i=t.getBoundingClientRect();t.width=Math.floor(i.width*e),t.height=Math.floor(i.height*e),t.getContext("2d").setTransform(e,0,0,e,0,0);});}canvasCssSize(e){let t=e.getBoundingClientRect();return {w:t.width,h:t.height}}drawWave(e,t){let i=this.waveCanvas.getContext("2d");i.fillStyle="#0d0d14",i.fillRect(0,0,e,t),i.strokeStyle="rgba(255,255,255,0.03)",i.lineWidth=1;for(let n=0;n<e;n+=40)i.beginPath(),i.moveTo(n+.5,0),i.lineTo(n+.5,t),i.stroke();for(let n=0;n<t;n+=40)i.beginPath(),i.moveTo(0,n+.5),i.lineTo(e,n+.5),i.stroke();this.engine.analyser&&((!this.waveBuf||this.waveBuf.length!==this.engine.analyser.fftSize)&&(this.waveBuf=new Uint8Array(this.engine.analyser.fftSize)),this.engine.analyser.getByteTimeDomainData(this.waveBuf));let a=this.waveBuf?.length??1024;i.beginPath(),i.strokeStyle="#ffffff",i.lineWidth=2;for(let n=0;n<a;n++){let s=this.waveBuf?this.waveBuf[n]/128:1,o=n/(a-1)*e;n===0?i.moveTo(o,s*t/2):i.lineTo(o,s*t/2);}i.stroke();}drawMap(e,t){let i=this.mapCanvas.getContext("2d");i.clearRect(0,0,e,t);let a=this.imageProcessor.canvas;if(!a)return;let n=Math.min(e/a.width,t/a.height),s=a.width*n,o=a.height*n,l=(e-s)/2,m=(t-o)/2;if(i.save(),i.imageSmoothingEnabled=true,i.drawImage(a,0,0,a.width,a.height,l,m,s,o),!this.seq.active&&this.seq.activateAt>0&&this.engine.ctx&&this.engine.ctx.currentTime>=this.seq.activateAt&&(this.seq.active=true),this.seq.active&&this.grid.cols>0&&this.grid.list.length>0){this.seq.renderX=this.seq.renderX+(this.seq.visX-this.seq.renderX)*1,this.seq.renderY=this.seq.renderY+(this.seq.visY-this.seq.renderY)*1;let c=s/this.grid.cols,d=o/this.grid.rows,h=Math.max(1.5,Math.min(c,d)*.06),v=l+this.seq.renderX*c,_=m+this.seq.renderY*d,B=c-1,y=d-1,g=this.seq.lastL>50;i.strokeStyle=g?"rgba(30,30,30,0.85)":"rgba(220,220,220,0.85)",i.lineWidth=h,i.strokeRect(v+.5,_+.5,B,y);}i.restore();}};async function ae(r){if(r instanceof HTMLImageElement)return ye(r);let e=r instanceof Blob,t=e?URL.createObjectURL(r):r,i=new Image;return e||(i.crossOrigin="anonymous"),new Promise((a,n)=>{i.onload=()=>{e&&URL.revokeObjectURL(t),a(i);},i.onerror=()=>{e&&URL.revokeObjectURL(t),n(new Error(`Failed to load image: ${e?"blob":t}`));},i.src=t;})}function ye(r){return r.complete&&r.naturalWidth>0?Promise.resolve(r):r.complete&&r.naturalWidth===0?Promise.reject(new Error("Failed to load image")):new Promise((e,t)=>{r.addEventListener("load",()=>e(r),{once:true}),r.addEventListener("error",()=>t(new Error("Failed to load image")),{once:true});})}var xe=10,we=44100,Ee=2,se=class extends EventTarget{constructor(t={}){super();this.state=new G;this.engine=new O;this.imageProcessor=new U;this.grid=new z;this.renderer=null;this.reverbDebounce=null;this.loadedImage=null;this.playStartTime=0;this.seq=new R(this.grid),this.synth=new N(this.engine,this.state),this.scheduler=new V(this.state,this.engine,this.synth,this.seq,this.grid,i=>this.emit("noteplay",i)),this.tweener=new j(this.state,this.engine,t.onTweenTick),t.waveCanvas&&t.mapCanvas&&this.attachVisuals(t.waveCanvas,t.mapCanvas);}get playing(){return this.state.playing}attachVisuals(t,i){this.renderer?.stop(),this.renderer=new X(t,i,this.engine,this.imageProcessor,this.grid,this.seq),this.renderer.start();}resizeVisuals(){this.renderer?.resizeCanvases();}async loadImage(t){try{let i=await ae(t);this.loadedImage=i,this.imageProcessor.processImage(i),this.rebuildGrid(),this.emit("imageload",{width:i.naturalWidth,height:i.naturalHeight,blockCount:this.grid.list.length});}catch(i){throw this.emitError(i,"loadImage")}}async play(){try{if(this.engine.ensure(this.state),!this.engine.ctx)throw new Error("Web Audio API is not available");if(this.state.playing)return;await this.engine.resume();}catch(t){throw this.emitError(t,"play")}!this.engine.ctx||this.state.playing||(this.state.playing=true,this.playStartTime=this.engine.ctx.currentTime,this.scheduler.start(),this.emit("start",{timestamp:this.engine.ctx.currentTime}));}stop(){if(!this.state.playing)return;let t=this.engine.ctx?.currentTime??0,i=t-this.playStartTime;this.state.playing=false,this.seq.nextTime=0,this.seq.active=false,this.seq.activateAt=0,this.scheduler.stop(),this.engine.suspend(),this.emit("stop",{timestamp:t,duration:i});}async warmUp(){try{await this.engine.warmUp(this.state);}catch(t){throw this.emitError(t,"warmUp")}}getParam(t){return this.state[t]}setParam(t,i){typeof i=="number"?this.state.setNumeric(t,i):this.state.setString(t,i),this.applyParamSideEffects(t);}applyParams(t,i={}){let{tween:a=true}=i;a?(this.state.applyPatch(t),this.rebuildGrid(),this.tweener.tweenTo(t)):(this.tweener.cancel(),this.state.applyAll(t),this.rebuildGrid(),this.syncLiveAudioFromState()),t.scan_mode&&(this.seq.resetPosition(this.state),this.scheduler.resync());}captureParams(){return this.state.capture()}async toAudioBuffer(t={}){try{return await this.renderOffline(t)}catch(i){throw this.emitError(i,"toAudioBuffer")}}async toBlob(t={}){let i=await this.toAudioBuffer(t);return de(i)}async renderOffline(t){let{duration:i=xe,sampleRate:a=we}=t,n=new G;n.applyAll(t.params??this.state.capture());let s=new U,o=new z,l=t.image?await ae(t.image):this.loadedImage;if(!l)throw new Error("No image loaded. Pass `image` or call loadImage first.");s.processImage(l),o.build(s,n);let m=new R(o);m.resetPosition(n);let p=new OfflineAudioContext({numberOfChannels:Ee,length:Math.max(1,Math.ceil(i*a)),sampleRate:a}),c=new O;c.ensureOffline(p,n);let d=new N(c,n);return new V(n,c,d,m,o).renderRange(0,i),p.startRendering()}rebuildGrid(){this.grid.build(this.imageProcessor,this.state),this.seq.clampToGrid(),this.scheduler.resync();}applyParamSideEffects(t){switch(t){case u.volume:this.engine.master&&this.engine.smooth(this.engine.master.gain,Math.pow(this.state.volume,2));break;case u.bpm:case u.speed:case u.note_mult:this.scheduler.resync();break;case u.reverb_mix:this.engine.wet&&this.engine.dry&&(this.engine.smooth(this.engine.wet.gain,this.state.reverb_mix),this.engine.smooth(this.engine.dry.gain,this.engine.dryVal(this.state.reverb_mix)));break;case u.reverb_time:if(!this.engine.ctx||!this.engine.conv)return;this.reverbDebounce&&clearTimeout(this.reverbDebounce),this.reverbDebounce=setTimeout(()=>this.engine.updateReverbBuffer(this.state),120);break;case u.block_w:case u.block_h:this.rebuildGrid();break;case u.scale_name:this.state.scale=f.find(i=>i.name===this.state.scale_name)??f[0],this.rebuildGrid();break;case u.scan_mode:this.seq.resetPosition(this.state),this.scheduler.resync();break}}syncLiveAudioFromState(){this.engine.master&&(this.engine.master.gain.value=Math.pow(this.state.volume,2)),this.engine.wet&&this.engine.dry&&(this.engine.wet.gain.value=this.state.reverb_mix,this.engine.dry.gain.value=this.engine.dryVal(this.state.reverb_mix)),this.engine.updateReverbBuffer(this.state);}emit(t,i){this.dispatchEvent(new CustomEvent(t,{detail:i}));}emitError(t,i){let a=t instanceof Error?t:new Error(String(t));return this.emit("error",{error:a,context:i}),a}};var Te={Haze:{osc_type:"triangle",scale_name:"Pentatonic",base_note:220,bpm:92,speed:1.7,note_mult:.55,volume:.85,vibrato_rate:3.2,vibrato_depth:14,tremolo_rate:2.2,tremolo_depth:.18,fifth_lvl:.25,oct_lvl:.2,filter_base:900,filter_track:2200,resonance:1.7,reverb_mix:.45,reverb_time:2.4,bass_gain:4,block_w:20,block_h:20,scan_mode:"zigzag",pan_amount:.65,timing_mode:"expressive",timing_intensity:.7},Leap:{osc_type:"square",scale_name:"Major",base_note:330,bpm:150,speed:5,note_mult:.28,volume:.7,vibrato_rate:6,vibrato_depth:4,tremolo_rate:12,tremolo_depth:.25,fifth_lvl:.5,oct_lvl:.2,filter_base:1200,filter_track:1500,resonance:.9,reverb_mix:.15,reverb_time:1.2,bass_gain:2,block_w:16,block_h:16,scan_mode:"zigzag",pan_amount:.8,timing_mode:"stable",timing_intensity:0},Pulse:{osc_type:"square",scale_name:"Pentatonic",base_note:220,bpm:100,speed:3,note_mult:.4,volume:.7,vibrato_rate:0,vibrato_depth:0,tremolo_rate:8,tremolo_depth:.6,fifth_lvl:.4,oct_lvl:.1,filter_base:800,filter_track:1200,resonance:1.5,reverb_mix:.25,reverb_time:1,bass_gain:3,block_w:12,block_h:12,scan_mode:"zigzag",pan_amount:.6,timing_mode:"stable",timing_intensity:0},Bite:{osc_type:"sawtooth",scale_name:"Chromatic",base_note:110,bpm:130,speed:4,note_mult:.3,volume:.7,vibrato_rate:0,vibrato_depth:0,tremolo_rate:0,tremolo_depth:0,fifth_lvl:0,oct_lvl:0,filter_base:200,filter_track:5500,resonance:8,reverb_mix:.1,reverb_time:.8,bass_gain:10,block_w:8,block_h:8,scan_mode:"linear",pan_amount:.2,timing_mode:"stable",timing_intensity:0},Spark:{osc_type:"square",scale_name:"Chromatic",base_note:523,bpm:180,speed:6,note_mult:.08,volume:.6,vibrato_rate:0,vibrato_depth:0,tremolo_rate:20,tremolo_depth:.4,fifth_lvl:0,oct_lvl:0,filter_base:3500,filter_track:5e3,resonance:3,reverb_mix:.1,reverb_time:.5,bass_gain:-6,block_w:6,block_h:6,scan_mode:"linear",pan_amount:.3,timing_mode:"stable",timing_intensity:0},Raw:{osc_type:"square",scale_name:"Major",base_note:220,bpm:110,speed:3.2,note_mult:.22,volume:.75,vibrato_rate:0,vibrato_depth:0,tremolo_rate:0,tremolo_depth:0,fifth_lvl:0,oct_lvl:0,filter_base:2400,filter_track:0,resonance:.2,reverb_mix:0,reverb_time:.8,bass_gain:0,block_w:40,block_h:40,scan_mode:"linear",pan_amount:0,timing_mode:"stable",timing_intensity:0}};export{se as Audiora,be as DEFAULT_PRESET,Z as FORMAT,Te as PRESETS,pe as RANGE_KEYS,ve as SELECT_KEYS};//# sourceMappingURL=index.js.map
1
+ var mr=Object.defineProperty;var v=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var dr=(t,e)=>{for(var r in e)mr(t,r,{get:e[r],enumerable:true});};var w,R,Oe,pr,hr,b,Ne,ft,fr,Be,T=v(()=>{"use strict";w=[{name:"Major",intervals:[0,2,4,5,7,9,11,12]},{name:"Minor",intervals:[0,2,3,5,7,8,10,12]},{name:"Pentatonic",intervals:[0,2,4,7,9,12]},{name:"Blues",intervals:[0,3,5,6,7,10,12]},{name:"Chromatic",intervals:[0,1,2,3,4,5,6,7,8,9,10,11,12]},{name:"Whole Tone",intervals:[0,2,4,6,8,10,12]},{name:"Dorian",intervals:[0,2,3,5,7,9,10,12]},{name:"Phrygian",intervals:[0,1,3,5,7,8,10,12]},{name:"Lydian",intervals:[0,2,4,6,7,9,11,12]},{name:"Harmonic Minor",intervals:[0,2,3,5,7,8,11,12]},{name:"In Sen",intervals:[0,1,5,7,10,12]}],R=["osc_type","scale_name","base_note","bpm","speed","note_mult","volume","vibrato_rate","vibrato_depth","tremolo_rate","tremolo_depth","fifth_lvl","oct_lvl","filter_base","filter_track","resonance","reverb_mix","reverb_time","bass_gain","block_w","block_h","scan_mode","pan_amount","timing_mode","timing_intensity"],Oe={volume:t=>`${Math.round(t*100)}%`,bpm:t=>String(Math.round(t)),speed:t=>`\xD7${t.toFixed(2)}`,note_mult:t=>`\xD7${t.toFixed(2)}`,base_note:t=>`${Math.round(t)} Hz`,fifth_lvl:t=>`${Math.round(t*100)}%`,oct_lvl:t=>`${Math.round(t*100)}%`,vibrato_rate:t=>`${t.toFixed(1)} Hz`,vibrato_depth:t=>`${Math.round(t)} \xA2`,tremolo_rate:t=>`${t.toFixed(1)} Hz`,tremolo_depth:t=>`${Math.round(t*100)}%`,filter_base:t=>`${Math.round(t)} Hz`,filter_track:t=>`${Math.round(t)} Hz`,resonance:t=>t.toFixed(2),reverb_mix:t=>`${Math.round(t*100)}%`,reverb_time:t=>`${t.toFixed(1)} s`,bass_gain:t=>`${t.toFixed(1)} dB`,block_w:t=>`${Math.round(t)} px`,block_h:t=>`${Math.round(t)} px`,pan_amount:t=>`${Math.round(t*100)}%`,timing_intensity:t=>`${Math.round(t*100)}%`},pr=Object.keys(Oe),hr=R.filter(t=>!(t in Oe)),b=R.reduce((t,e)=>(t[e]=e,t),{}),Ne=1.2,ft=1500,fr="Haze",Be=[b.volume,b.base_note,b.vibrato_rate,b.vibrato_depth,b.tremolo_rate,b.tremolo_depth,b.fifth_lvl,b.oct_lvl,b.filter_base,b.filter_track,b.resonance,b.reverb_mix,b.reverb_time,b.bass_gain,b.pan_amount];});function f(t,e,r){return Math.max(e,Math.min(r,t))}function he(t){return 440*Math.pow(2,(t-69)/12)}function fe(t){return 69+12*Math.log2(t/440)}function $(t,e,r){t/=255,e/=255,r/=255;let n=Math.max(t,e,r),o=Math.min(t,e,r),i=0,s=0,c=(n+o)/2,l=n-o;if(l){switch(s=c>.5?l/(2-n-o):l/(n+o),n){case t:i=(e-r)/l+(e<r?6:0);break;case e:i=(r-t)/l+2;break;case r:i=(t-e)/l+4;break}i*=60;}let a=n===0?0:l/n;return {h:i,s_hsl:s,s_hsv:a,l:c*100}}function gt(t){return t<.5?2*t*t:-1+(4-2*t)*t}var k=v(()=>{"use strict";});function yt(t){if(t.length<2||t.sampleRate<=0||t.numberOfChannels<1)throw new Error("audio-intelligence requires a buffer with samples.");let e=Array.from({length:t.numberOfChannels},(l,a)=>t.getChannelData(a)),r=_r(e),n=Ar(e),o=Sr(e),i=Er(e,t.sampleRate),s=wr(n,i),c=xr({duration:t.duration,peak:r,rms:n,zeroCrossingRate:o,spectralCentroid:i,label:s});return {duration:t.duration,sampleRate:t.sampleRate,channels:t.numberOfChannels,peak:r,rms:n,zeroCrossingRate:o,spectralCentroid:i,label:s,summary:c}}function wr(t,e){return t<.05?"sparse":e>=2500?"bright":e<800?"dark":t>=.2?"dense":"warm"}function xr(t){return [`Duration ${t.duration.toFixed(2)} s`,`peak ${t.peak.toFixed(2)}`,`RMS ${t.rms.toFixed(2)}`,`zero-crossing rate ${t.zeroCrossingRate.toFixed(2)}`,`spectral centroid ${Math.round(t.spectralCentroid)} Hz`,`Label: ${t.label}.`].join(", ")}function _r(t){let e=0;for(let r of t)for(let n=0;n<r.length;n++)e=Math.max(e,Math.abs(r[n]));return e}function Ar(t){let e=0,r=0;for(let n of t)for(let o=0;o<n.length;o++)e+=n[o]*n[o],r+=1;return r===0?0:Math.sqrt(e/r)}function Sr(t){let e=0;for(let r of t){let n=0,o=r[0]>=0?1:-1;for(let i=1;i<r.length;i++){let s=r[i]>=0?1:-1;s!==o&&(n+=1),o=s;}e+=n/(r.length-1);}return e/t.length}function Er(t,e){let r=t[0].length,n=new Float64Array(2048),o=new Float64Array(2048),i=0,s=0;for(let c of Pr(r)){for(let a=0;a<2048;a++){let u=c+a,m=0;if(u<r){for(let p of t)m+=p[u];m/=t.length;}n[a]=m*vt[a],o[a]=0;}kr(n,o);let l=Tr(n,o,e);i+=l.centroid*l.energy,s+=l.energy;}return s===0?0:i/s}function Pr(t){if(t<=2048)return [0];let e=[];for(let n=0;n+2048<=t;n+=1024)e.push(n);let r=t-2048;return e[e.length-1]!==r&&e.push(r),e}function Tr(t,e,r){let o=r/2048,i=0,s=0;for(let c=0;c<1024;c++){let l=Math.hypot(t[c],e[c]);i+=l,s+=c*o*l;}return {centroid:i===0?0:s/i,energy:i}}function kr(t,e){let r=t.length;for(let n=1,o=0;n<r;n++){let i=r>>1;for(;o&i;i>>=1)o^=i;if(o^=i,n<o){let s=t[n];t[n]=t[o],t[o]=s;let c=e[n];e[n]=e[o],e[o]=c;}}for(let n=2;n<=r;n<<=1){let o=-2*Math.PI/n,i=Math.cos(o),s=Math.sin(o);for(let c=0;c<r;c+=n){let l=1,a=0,u=n>>1;for(let m=0;m<u;m++){let p=c+m,h=p+u,d=t[h]*l-e[h]*a,g=t[h]*a+e[h]*l;t[h]=t[p]-d,e[h]=e[p]-g,t[p]+=d,e[p]+=g;let x=l*i-a*s;a=l*s+a*i,l=x;}}}}var vt,wt=v(()=>{"use strict";vt=new Float32Array(2048);for(let t=0;t<2048;t++)vt[t]=.5*(1-Math.cos(2*Math.PI*t/2047));});function ye(t){let e=Array.from({length:He},()=>({h:0,s:0,l:0,n:0})),r={h:0,s:0,l:0,n:0},n=0,o=0,i=0,s=0,c=t.pixels;for(let u=0;u<c.length;u+=4){let m=c[u],p=c[u+1],h=c[u+2];n+=m,o+=p,i+=h,s+=1;let d=$(m,p,h),g=d.s_hsv<Mr?r:e[Rr(d.h)];g.h+=d.h,g.s+=d.s_hsv,g.l+=d.l,g.n+=1;}let l=s===0?{h:0,s_hsv:0,l:0}:$(n/s,o/s,i/s),a=[...e,r].filter(u=>u.n>0).map(u=>({h:u.h/u.n,s:u.s/u.n,l:u.l/u.n,weight:s===0?0:u.n/s})).sort((u,m)=>m.weight-u.weight);return {width:t.width,height:t.height,blockCount:t.blockCount,average:{h:l.h,s:l.s_hsv,l:l.l},palette:a}}function Rr(t){let e=Math.floor(t/360*He);return Math.min(He-1,Math.max(0,e))}var He,Mr,Ge=v(()=>{"use strict";k();He=12,Mr=.08;});function xt(t){let r=globalThis.process?.env?.[t];if(typeof r!="string")return;let n=r.trim();return n.length>0?n:void 0}function Cr(){return Dr(xt("OLLAMA_HOST")??"http://127.0.0.1:11434")}function Dr(t){let e;try{e=new URL(t);}catch{throw new Error("OLLAMA_HOST must be https, or http on localhost.")}let r=e.hostname.replace(/^\[|\]$/g,""),n=r==="localhost"||r==="127.0.0.1"||r==="::1",o=e.pathname==="/"||e.pathname==="";if(!(!e.username&&!e.password&&!e.search&&!e.hash&&o&&(e.protocol==="https:"||e.protocol==="http:"&&n)))throw new Error("OLLAMA_HOST must be https, or http on localhost.");return e.origin}function A(t){if(t==="ollama")return Cr();if(!(t!=="gemini"&&t!=="openai"&&t!=="anthropic"))return xt(Ir[t])}function S(t){if(!(typeof window>"u")&&!t)throw new Error("Set providers.browserAccess to call a provider from the browser.")}function we(t){return typeof window>"u"||!t?{}:{"anthropic-dangerous-direct-browser-access":"true"}}var Ir,I=v(()=>{"use strict";Ir={gemini:"GEMINI_API_KEY",openai:"OPENAI_API_KEY",anthropic:"ANTHROPIC_API_KEY"};});function Lr(){let t=new AbortController,e=setTimeout(()=>t.abort(),1e4);return {signal:t.signal,cancel:()=>clearTimeout(e)}}function G(t){if(t>5242880)throw new Error(je)}function Ke(t){let e=Number(t.headers.get("content-length"));if(Number.isFinite(e)&&e>5242880)throw t.body?.cancel().catch(()=>{}),new Error(je)}async function B(t){let e=Lr();try{return await t(e.signal)}catch(r){throw e.signal.aborted?new Error(xe):r}finally{e.cancel();}}async function W(t,e){if(e.aborted)throw new Error(xe);Ke(t);let r=t.body?.getReader();if(!r){let l=new Uint8Array(await t.arrayBuffer());return G(l.byteLength),l}let n=[],o=0,i=()=>{r.cancel().catch(()=>{});};e.addEventListener("abort",i,{once:true});try{for(;!e.aborted;){let{done:l,value:a}=await r.read();if(l)break;if(a?.byteLength){if(o+a.byteLength>5242880)throw new Error(je);n.push(a),o+=a.byteLength;}}}catch(l){throw await r.cancel().catch(()=>{}),e.aborted?new Error(xe):l}finally{e.removeEventListener("abort",i);}if(e.aborted)throw new Error(xe);let s=new Uint8Array(o),c=0;for(let l of n)s.set(l,c),c+=l.byteLength;return s}var je,xe,J=v(()=>{"use strict";je="response exceeds 5242880 bytes.",xe="request timed out.";});function Nr(t){let e=t.trim();if(!e)throw new Error("image URL is empty.");let r=typeof document<"u"?document.baseURI:void 0,n;try{n=new URL(e,r);}catch{throw new Error("image URL must be https, or http on localhost.")}if(n.username||n.password)throw new Error("image URL must not include credentials.");let o=Or.has(n.hostname.replace(/^\[|\]$/g,""));if(!(n.protocol==="https:"||n.protocol==="blob:"||n.protocol==="http:"&&o))throw new Error("image URL must be https, or http on localhost.");return n}async function ae(t){return typeof t=="string"?Br(Nr(t)):t instanceof HTMLImageElement?qr(t):(G(t.size),_t(new Uint8Array(await t.arrayBuffer()),t.type))}async function Br(t){return B(async e=>{let r=await fetch(t.href,{credentials:"omit",redirect:"manual",signal:e});if(Fr(r))throw Ye(r),new Error("image URL must not redirect.");if(!r.ok)throw Ye(r),new Error(`Failed to read image (${r.status}).`);let n=At(r.headers.get("content-type")??"");if(!n.startsWith("image/"))throw Ye(r),new Error("image response must be an image.");let o=await W(r,e);return {base64:St(o),mimeType:n}})}function _t(t,e){G(t.byteLength);let r=At(e);if(r&&!r.startsWith("image/"))throw new Error("image response must be an image.");return {base64:St(t),mimeType:r||"image/png"}}function At(t){return t.split(";")[0]?.trim().toLowerCase()??""}function Fr(t){return t.type==="opaqueredirect"||t.status>=300&&t.status<400}function Ye(t){t.body?.cancel().catch(()=>{});}function qr(t){let e=document.createElement("canvas");e.width=t.naturalWidth,e.height=t.naturalHeight;let r=e.getContext("2d");if(!r)throw new Error("Failed to encode image.");return r.drawImage(t,0,0),new Promise((n,o)=>{e.toBlob(async i=>{try{if(!i)throw new Error("Failed to encode image.");G(i.size);let s=new Uint8Array(await i.arrayBuffer());n(_t(s,"image/png"));}catch(s){o(s instanceof Error?s:new Error("Failed to encode image."));}},"image/png");})}function St(t){let e=[];for(let n=0;n<t.length;n+=8192)e.push(String.fromCharCode(...t.subarray(n,n+8192)));return btoa(e.join(""))}var Or,We=v(()=>{"use strict";J();Or=new Set(["localhost","127.0.0.1","::1"]);});async function Et(t){if(t.provider==="anthropic")throw new Error("anthropic does not provide an embeddings endpoint.");let e=t.provider;return S(t.browserAccess),B(async r=>{let n=await Vr(e,t.credential,t.text,r);if(!n.ok)throw n.body?.cancel().catch(()=>{}),new Error(`${e} semantic request failed (${n.status}).`);let o=$r(zr(await W(n,r)));if(!o)throw new Error(`${e} semantic request returned an empty embedding.`);return o})}function Vr(t,e,r,n){switch(t){case "gemini":return fetch(`https://generativelanguage.googleapis.com/v1beta/models/${Je.gemini}:embedContent`,{method:"POST",signal:n,headers:{"content-type":"application/json","x-goog-api-key":e},body:JSON.stringify({content:{parts:[{text:r}]}})});case "openai":return fetch("https://api.openai.com/v1/embeddings",{method:"POST",signal:n,headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({model:Je.openai,input:r})});case "ollama":return fetch(`${e}/api/embed`,{method:"POST",signal:n,headers:{"content-type":"application/json"},body:JSON.stringify({model:Je.ollama,input:r})})}}function zr(t){try{return JSON.parse(new TextDecoder().decode(t))}catch{return}}function $r(t){if(!t||typeof t!="object")return;let e=t,r=e.embedding;if(r&&typeof r=="object"&&!Array.isArray(r)){let o=_e(r.values);if(o)return o}let n=_e(r);if(n)return n;if(Array.isArray(e.data)&&e.data[0]&&typeof e.data[0]=="object"){let o=_e(e.data[0].embedding);if(o)return o}if(Array.isArray(e.embeddings))return _e(e.embeddings[0])}function _e(t){if(!Array.isArray(t)||t.length===0)return;let e=[];for(let r of t){if(typeof r!="number"||!Number.isFinite(r))return;e.push(r);}return e}var Je,Pt=v(()=>{"use strict";I();J();Je={gemini:"text-embedding-004",openai:"text-embedding-3-small",ollama:"nomic-embed-text"};});async function Ae(t,e,r,n){if(Ke(t),n.aborted)throw t.body?.cancel().catch(()=>{}),new Error(Xe);if(!t.body){let d=await W(t,n);return Tt(new TextDecoder().decode(d),e,r)}let o=t.body.getReader(),i=new TextDecoder,s="",c="",l="",a=false,u=0,m=()=>{o.cancel().catch(()=>{});};n.addEventListener("abort",m,{once:true});let p=d=>{d&&(a=true,l+=d,r?.(d));};try{for(;!n.aborted;){let{done:d,value:g}=await o.read();if(d)break;if(!g?.byteLength)continue;G(u+g.byteLength),u+=g.byteLength;let x=i.decode(g,{stream:!0});c+=x,s+=x;let y=s.split(`
2
+ `);s=y.pop()??"";for(let _ of y)p(Ze(_,e));}}catch(d){throw await o.cancel().catch(()=>{}),n.aborted?new Error(Xe):d}finally{n.removeEventListener("abort",m);}if(n.aborted)throw new Error(Xe);let h=i.decode();return c+=h,s+=h,a?(p(Ze(s,e)),l):Tt(c,e,r)}function Tt(t,e,r){let n=Ze(t,e)||kt(t,e);return n&&r?.(n),n}function Ze(t,e){let r=t.trim();if(!r)return "";let n=r.startsWith("data:")?r.slice(5).trim():r;return !n||n==="[DONE]"?"":kt(n,e)}function kt(t,e){try{return e(t)}catch{return ""}}var Xe,Qe=v(()=>{"use strict";J();Xe="request timed out.";});async function ce(t){S(t.browserAccess);let e=Ur(t.instruction,t.prompt);return B(async r=>{let n=await Gr(t.provider,t.credential,t.image,e,t.browserAccess,r);if(!n.ok)throw Hr(n),new Error(`${t.provider} vision request failed (${n.status}).`);let o=await Ae(n,Rt(t.provider),t.onText,r);if(!o.trim())throw new Error(`${t.provider} vision request returned an empty ${t.purpose??"description"}.`);return o})}function Ur(t,e){let r=t?.trim()||"Describe what this image shows.",n=e?.trim();return n?`${r} ${n}`:r}function Hr(t){t.body?.cancel().catch(()=>{});}function Gr(t,e,r,n,o,i){switch(t){case "gemini":return fetch(jr(),{method:"POST",signal:i,headers:{"content-type":"application/json","x-goog-api-key":e},body:JSON.stringify({contents:[{role:"user",parts:[{text:n},{inlineData:{mimeType:r.mimeType,data:r.base64}}]}]})});case "openai":return fetch("https://api.openai.com/v1/chat/completions",{method:"POST",signal:i,headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({model:Se.openai,stream:true,messages:[{role:"user",content:[{type:"text",text:n},{type:"image_url",image_url:{url:`data:${r.mimeType};base64,${r.base64}`}}]}]})});case "anthropic":return fetch("https://api.anthropic.com/v1/messages",{method:"POST",signal:i,headers:{"content-type":"application/json","x-api-key":e,"anthropic-version":"2023-06-01",...we(o)},body:JSON.stringify({model:Se.anthropic,max_tokens:1024,stream:true,messages:[{role:"user",content:[{type:"image",source:{type:"base64",media_type:r.mimeType,data:r.base64}},{type:"text",text:n}]}]})});case "ollama":return fetch(`${e}/api/chat`,{method:"POST",signal:i,headers:{"content-type":"application/json"},body:JSON.stringify({model:Se.ollama,stream:true,messages:[{role:"user",content:n,images:[r.base64]}]})})}}function jr(){return `https://generativelanguage.googleapis.com/v1beta/models/${Se.gemini}:streamGenerateContent?alt=sse`}function Mt(t,e){return Rt(t)(e)}function Rt(t){switch(t){case "gemini":return Kr;case "openai":return Yr;case "anthropic":return Wr;case "ollama":return Jr}}function Kr(t){return (JSON.parse(t).candidates?.[0]?.content?.parts??[]).map(n=>n.text??"").join("")}function Yr(t){let r=JSON.parse(t).choices?.[0];return r?.delta?.content??r?.message?.content??""}function Wr(t){let e=JSON.parse(t);return e.type==="content_block_delta"?e.delta?.text??"":(e.content??[]).map(r=>r.text??"").join("")}function Jr(t){return JSON.parse(t).message?.content??""}var Se,Ee=v(()=>{"use strict";I();J();Qe();Se={gemini:"gemini-2.0-flash",openai:"gpt-4o-mini",anthropic:"claude-3-5-haiku-latest",ollama:"llava"};});function It(){return Xr.flatMap(t=>[Qr(t),en(t),tn(t)])}function Qr(t){return {kind:"vision",name:t,async describe({image:e,prompt:r,onText:n,browserAccess:o}){S(o);let i=et(t),s=await ae(e);return ce({provider:t,credential:i,image:s,prompt:r,onText:n,browserAccess:o})}}}function en(t){return {kind:"embeddings",name:t,embed({text:e,browserAccess:r}){return S(r),Et({provider:t,credential:et(t),text:e,browserAccess:r})}}}function tn(t){return {kind:"speech",name:t,async narrate({image:e,text:r,onText:n,browserAccess:o}){if(!e){let l=r?.trim();if(!l)throw new Error("narration requires an image.");return {text:l}}S(o);let i=et(t),s=await ae(e);return {text:await ce({provider:t,credential:i,image:s,prompt:r,instruction:Zr,onText:n,purpose:"narration",browserAccess:o})}}}}function et(t){let e=A(t);if(!e)throw new Error(`${t} provider requires credentials.`);return e}var Xr,Zr,Ct=v(()=>{"use strict";We();I();Pt();Ee();Xr=["gemini","openai","anthropic","ollama"],Zr="Narrate this image in a few spoken sentences.";});function Te(t){let e=Pe.get(nt(t,Pe,"vision"));if(!e)throw new Error(`Unknown vision provider "${t}".`);if(!(it(t)&&!A(t)))return e}function Lt(t){let e=tt.get(nt(t,tt,"embeddings"));if(!e)throw new Error(`Unknown embeddings provider "${t}".`);if(!(it(t)&&!A(t)))return e}function Ot(t){let e=rt.get(nt(t,rt,"speech"));if(!e)throw new Error(`Unknown speech provider "${t}".`);return e}function F(t){if(Bt(),it(t))return t;throw Pe.has(t)?new Error(`Vision provider "${t}" does not provide text completion.`):new Error(`Unknown vision provider "${t}".`)}function Nt(t){if("audio"in t&&t.audio instanceof ArrayBuffer)return t;let e=t.text?.trim();if(!e)throw new Error("speech provider returned an empty narration.");return e}function Bt(){if(!Dt){Dt=true;for(let t of It())rn(t);}}function rn(t){t.kind==="vision"?Pe.set(t.name,t):t.kind==="embeddings"?tt.set(t.name,t):rt.set(t.name,t);}function nt(t,e,r){if(Bt(),!e.has(t))throw new Error(`Unknown ${r} provider "${t}".`);return t}function it(t){return t==="gemini"||t==="openai"||t==="anthropic"||t==="ollama"}var Pe,tt,rt,Dt,X=v(()=>{"use strict";Ct();I();Pe=new Map,tt=new Map,rt=new Map,Dt=!1;});function ot(t){let e=0,r=0,n=0,o=0;for(let s=0;s<t.length;s+=4)e+=t[s],r+=t[s+1],n+=t[s+2],o+=1;if(o===0)return {h:0,s:0,l:0};let i=$(e/o,r/o,n/o);return {h:i.h,s:i.s_hsv,l:i.l}}function st(t,e){let r=Math.round(e.h),n=e.s.toFixed(2),o=Math.round(e.l);return `Measured image ${t.width}\xD7${t.height} px, ${t.blockCount} blocks. Average hue ${r}\xB0, saturation ${n}, lightness ${o}.`}var Ft=v(()=>{"use strict";k();});async function Ut(t,e){let r=on(t),n=sn(t),o=an(t);return {tags:r,mood:n,embedding:await cn(o,n,r,e)}}function on(t){let e=[],r=t.color;return r&&(r.average.s<Vt?e.push("neutral"):e.push(Ht(r.average.h)),r.average.l<zt?e.push("dark"):r.average.l>=$t&&e.push("bright")),t.audio&&!e.includes(t.audio.label)&&e.push(t.audio.label),e}function sn(t){if(t.audio)return t.audio.label;let e=t.color;return e?e.average.l<zt?"dark":e.average.l>=$t?"bright":e.average.s<Vt?"sparse":nn.has(Ht(e.average.h))?"warm":"dense":"neutral"}function an(t){let e=t.color,r=t.audio,n=r&&r.sampleRate>0?r.sampleRate/2:0;return un([e?f(e.average.h/360,0,1):0,e?f(e.average.s,0,1):0,e?f(e.average.l/100,0,1):0,r?f(r.rms,0,1):0,r&&n>0?f(r.spectralCentroid/n,0,1):0,ln(t.soundscape?.label)])}async function cn(t,e,r,n){let o=n?.embeddings;if(!o||o==="local")return t;let i=Lt(o);return i?i.embed({text:`mood: ${e}
3
+ tags: ${r.join(", ")}`,browserAccess:n?.browserAccess}):t}function Ht(t){let e=Math.floor((t%360+360)%360/45)%qt.length;return qt[e]}function ln(t){if(!t)return 0;let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=Math.imul(e,16777619);return (e>>>0)/4294967295}function un(t){let e=0;for(let n of t)e+=n*n;let r=Math.sqrt(e);return r===0?t.map(()=>0):t.map(n=>n/r)}var qt,Vt,zt,$t,nn,Gt=v(()=>{"use strict";k();X();qt=["red","orange","yellow","green","cyan","blue","violet","magenta"],Vt=.08,zt=35,$t=70,nn=new Set(["red","orange","yellow"]);});async function Kt(t,e){let r=e?.speech;if(r&&r!=="browser"){if(!t.image&&!t.text?.trim())throw new Error("narration requires an image.");let i=await Ot(r).narrate({image:t.image,text:t.text,onText:t.onText,browserAccess:e?.browserAccess});return Nt(i)}let n=e?.vision;if(!n)return;let o=Te(n);if(!o||!t.image){if(!t.image&&o)throw new Error("narration requires an image.");return}if(mn(n)){let i=A(n);if(!i)return;S(e?.browserAccess);let s=await ae(t.image);return ce({provider:n,credential:i,image:s,prompt:t.prompt,instruction:jt,onText:t.onText,purpose:"narration",browserAccess:e?.browserAccess})}return o.describe({image:t.image,prompt:t.prompt??jt,onText:t.onText,browserAccess:e?.browserAccess})}function Yt(t){let e=t?.trim();if(!e)return;let r=globalThis.speechSynthesis;if(!r||typeof SpeechSynthesisUtterance>"u")throw new Error("speechSynthesis is not available.");r.speak(new SpeechSynthesisUtterance(e));}function mn(t){return t==="gemini"||t==="openai"||t==="anthropic"||t==="ollama"}var jt,Wt=v(()=>{"use strict";We();I();X();Ee();jt="Narrate this image in a few spoken sentences.";});function E(t,e){if(!t||typeof t!="object"||Array.isArray(t))return {};let r={},n=r;for(let[o,i]of Object.entries(t)){if(!gn.has(o))continue;let s=o;if(s==="scale_name"){r.scale_name=vn(i,e.scale_name);continue}if(bn(s)){n[s]=yn(i,Jt[s],e[s]);continue}let c=wn(i);if(c===void 0)continue;let l=fn[s],a=l.integer?Math.round(c):c;n[s]=xn(a,l.min,l.max);}return r}function bn(t){return t in Jt}function vn(t,e){return typeof t!="string"?e:w.some(r=>r.name===t)?t:e}function yn(t,e,r){return typeof t=="string"&&e.includes(t)?t:r}function wn(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim()!==""){let e=Number(t);if(Number.isFinite(e))return e}}function xn(t,e,r){return Math.min(r,Math.max(e,t))}var dn,pn,hn,Jt,fn,gn,le=v(()=>{"use strict";T();dn=["sine","square","sawtooth","triangle","pulse","organ","bell"],pn=["linear","vertical","zigzag","drift","spiral"],hn=["expressive","stable"],Jt={osc_type:dn,scan_mode:pn,timing_mode:hn},fn={base_note:{min:20,max:2e3},bpm:{min:20,max:300,integer:!0},speed:{min:.1,max:10},note_mult:{min:.01,max:2},volume:{min:0,max:1},fifth_lvl:{min:0,max:1},oct_lvl:{min:0,max:1},reverb_mix:{min:0,max:1},tremolo_depth:{min:0,max:1},pan_amount:{min:0,max:1},timing_intensity:{min:0,max:1},vibrato_rate:{min:0,max:20},vibrato_depth:{min:0,max:100},tremolo_rate:{min:0,max:30},filter_base:{min:20,max:2e4},filter_track:{min:0,max:1e4},resonance:{min:.1,max:30},reverb_time:{min:.1,max:10},bass_gain:{min:-20,max:20},block_w:{min:4,max:200,integer:!0},block_h:{min:4,max:200,integer:!0}},gn=new Set(R);});var j,ue=v(()=>{"use strict";j={Haze:{osc_type:"triangle",scale_name:"Pentatonic",base_note:220,bpm:92,speed:1.7,note_mult:.55,volume:.85,vibrato_rate:3.2,vibrato_depth:14,tremolo_rate:2.2,tremolo_depth:.18,fifth_lvl:.25,oct_lvl:.2,filter_base:900,filter_track:2200,resonance:1.7,reverb_mix:.45,reverb_time:2.4,bass_gain:4,block_w:20,block_h:20,scan_mode:"zigzag",pan_amount:.65,timing_mode:"expressive",timing_intensity:.7},Leap:{osc_type:"square",scale_name:"Major",base_note:330,bpm:150,speed:5,note_mult:.28,volume:.7,vibrato_rate:6,vibrato_depth:4,tremolo_rate:12,tremolo_depth:.25,fifth_lvl:.5,oct_lvl:.2,filter_base:1200,filter_track:1500,resonance:.9,reverb_mix:.15,reverb_time:1.2,bass_gain:2,block_w:16,block_h:16,scan_mode:"zigzag",pan_amount:.8,timing_mode:"stable",timing_intensity:0},Pulse:{osc_type:"square",scale_name:"Pentatonic",base_note:220,bpm:100,speed:3,note_mult:.4,volume:.7,vibrato_rate:0,vibrato_depth:0,tremolo_rate:8,tremolo_depth:.6,fifth_lvl:.4,oct_lvl:.1,filter_base:800,filter_track:1200,resonance:1.5,reverb_mix:.25,reverb_time:1,bass_gain:3,block_w:12,block_h:12,scan_mode:"zigzag",pan_amount:.6,timing_mode:"stable",timing_intensity:0},Bite:{osc_type:"sawtooth",scale_name:"Chromatic",base_note:110,bpm:130,speed:4,note_mult:.3,volume:.7,vibrato_rate:0,vibrato_depth:0,tremolo_rate:0,tremolo_depth:0,fifth_lvl:0,oct_lvl:0,filter_base:200,filter_track:5500,resonance:8,reverb_mix:.1,reverb_time:.8,bass_gain:10,block_w:8,block_h:8,scan_mode:"linear",pan_amount:.2,timing_mode:"stable",timing_intensity:0},Spark:{osc_type:"square",scale_name:"Chromatic",base_note:523,bpm:180,speed:6,note_mult:.08,volume:.6,vibrato_rate:0,vibrato_depth:0,tremolo_rate:20,tremolo_depth:.4,fifth_lvl:0,oct_lvl:0,filter_base:3500,filter_track:5e3,resonance:3,reverb_mix:.1,reverb_time:.5,bass_gain:-6,block_w:6,block_h:6,scan_mode:"linear",pan_amount:.3,timing_mode:"stable",timing_intensity:0},Raw:{osc_type:"square",scale_name:"Major",base_note:220,bpm:110,speed:3.2,note_mult:.22,volume:.75,vibrato_rate:0,vibrato_depth:0,tremolo_rate:0,tremolo_depth:0,fifth_lvl:0,oct_lvl:0,filter_base:2400,filter_track:0,resonance:.2,reverb_mix:0,reverb_time:.8,bass_gain:0,block_w:40,block_h:40,scan_mode:"linear",pan_amount:0,timing_mode:"stable",timing_intensity:0}};});function Me(t){let e=Object.entries(j);if(e.length===0)throw new Error("No presets are available for sound mapping.");let r=e.map(([u,m])=>({name:u,candidate:m,lightness:_n(m),saturation:An(m)})),n=Xt(r.map(u=>u.lightness)),o=Xt(r.map(u=>u.saturation)),i=f(t.average.l/100,0,1),s=f(t.average.s,0,1),c=r[0].name,l=r[0].candidate,a=Number.POSITIVE_INFINITY;for(let u=0;u<r.length;u++){let m=r[u],p=n[u]-i,h=o[u]-s,d=p*p+h*h;(d<a||d===a&&m.name<c)&&(a=d,c=m.name,l=m.candidate);}return {source:"image",label:c,patch:{...l}}}function _n(t){let e=ke(Math.log(Math.max(t.filter_base,20)),Math.log(20),Math.log(2e4)),r=ke(t.base_note,20,2e3),n=1-ke(t.bass_gain,-20,20);return e*.5+r*.3+n*.2}function An(t){return ke(t.resonance,.1,30)*.5+f(t.tremolo_depth,0,1)*.25+f(t.fifth_lvl,0,1)*.25}function Xt(t){let e=Math.min(...t),r=Math.max(...t);return t.map(n=>r===e?.5:(n-e)/(r-e))}function ke(t,e,r){return r===e?0:f((t-e)/(r-e),0,1)}var at=v(()=>{"use strict";ue();k();});function q(t){let e={};for(let r of R){let n=t[r];if(typeof n!="number"&&typeof n!="string")throw new Error("text-mapping requires the current preset.");e[r]=n;}return e}function me(t,e){if(!(t.toLowerCase().match(/[a-z]+/g)??[]).some(o=>Sn.has(o)))return {source:"text",label:"current",patch:{...e}};let n=En(e);return n?{source:"text",label:n.name,patch:{...n.patch}}:{source:"text",label:"current",patch:{...e}}}function Re(t){let e=t.trim().match(/```(?:json)?\s*([\s\S]*?)```/i),r=e?e[1]:t,n=r.indexOf("{"),o=r.lastIndexOf("}");if(n<0||o<=n)throw new Error("text-mapping provider did not return a JSON object.");try{return JSON.parse(r.slice(n,o+1))}catch{throw new Error("text-mapping provider did not return a JSON object.")}}function En(t){let e;for(let[r,n]of Object.entries(j))n.bpm<t.bpm&&n.reverb_mix>t.reverb_mix&&(!e||Pn(n,e.patch,r,e.name))&&(e={name:r,patch:n});return e}function Pn(t,e,r,n){return t.bpm!==e.bpm?t.bpm<e.bpm:t.reverb_mix!==e.reverb_mix?t.reverb_mix>e.reverb_mix:r<n}var Sn,de=v(()=>{"use strict";T();ue();Sn=new Set(["calm","sea"]);});function Zt(t,e){function r(c,l){return e({image:c,tasks:["description"],prompt:l?.prompt,onText:l?.onText})}function n(c,l){return e({image:c,tasks:["color-analysis","sound-mapping"],prompt:l?.prompt,onText:l?.onText})}async function o(c,l){let a=await e({image:c,tasks:["description"],prompt:l?.prompt,onText:l?.onText}),u=await e({text:a.description??"",tasks:["text-mapping"],onText:l?.onText});return {description:a.description,soundscape:u.soundscape}}function i(c,l){return e({image:c,tasks:["narration"],prompt:l?.prompt,onText:l?.onText})}async function s(c){await e({image:c,tasks:["soundscape"]});let l=q(t.captureParams());return {soundscapes:Object.entries(j).map(([u,m])=>({source:"image",label:u,patch:{...l,...E(m,l)}}))}}return {describe:r,soundify:n,interpret:o,narrate:i,explore:s}}var Qt=v(()=>{"use strict";ue();le();de();});async function Ce(t){return ct({provider:t.provider,credential:t.credential,prompt:`${Tn}
4
+ Text: ${t.text}`,onText:t.onText,purpose:t.purpose??"text-mapping",browserAccess:t.browserAccess})}async function ct(t){let e=F(t.provider);return S(t.browserAccess),B(async r=>{let n=await kn(e,t.credential,t.prompt,t.browserAccess,r);if(!n.ok)throw n.body?.cancel().catch(()=>{}),new Error(`${t.provider} ${t.purpose} request failed (${n.status}).`);let o=await Ae(n,i=>Mt(e,i),t.onText,r);if(!o.trim())throw new Error(`${t.provider} ${t.purpose} request returned an empty response.`);return o})}function kn(t,e,r,n,o){switch(t){case "gemini":return fetch(`https://generativelanguage.googleapis.com/v1beta/models/${Ie.gemini}:streamGenerateContent?alt=sse`,{method:"POST",signal:o,headers:{"content-type":"application/json","x-goog-api-key":e},body:JSON.stringify({contents:[{role:"user",parts:[{text:r}]}]})});case "openai":return fetch("https://api.openai.com/v1/chat/completions",{method:"POST",signal:o,headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({model:Ie.openai,stream:true,messages:[{role:"user",content:r}]})});case "anthropic":return fetch("https://api.anthropic.com/v1/messages",{method:"POST",signal:o,headers:{"content-type":"application/json","x-api-key":e,"anthropic-version":"2023-06-01",...we(n)},body:JSON.stringify({model:Ie.anthropic,max_tokens:1024,stream:true,messages:[{role:"user",content:[{type:"text",text:r}]}]})});case "ollama":return fetch(`${e}/api/chat`,{method:"POST",signal:o,headers:{"content-type":"application/json"},body:JSON.stringify({model:Ie.ollama,stream:true,messages:[{role:"user",content:r}]})})}}var Ie,Tn,lt=v(()=>{"use strict";I();J();X();Qe();Ee();Ie={gemini:"gemini-2.0-flash",openai:"gpt-4o-mini",anthropic:"claude-3-5-haiku-latest",ollama:"llava"},Tn=["Return one JSON object of synthesizer parameters for the text.","Keys may only be preset fields. Do not include mood, tags, or embedding.","No markdown."].join(" ");});async function er(t,e,r){let n=e.prompt?.trim()??"",o=e.text?.trim()??"",i=n||o,s=n?"prompt":"text";if(!e.image&&!i)throw new Error("soundscape requires an image, text, or prompt.");let c=q(t.captureParams());if(!e.image)return Mn(i,s,c,r,e.onText);let l=t.readLoadedImage();if(!l||l.blockCount===0)throw new Error("Image loaded but the grid is empty.");let a=Me(ye(l)),u=De(c,E(a.patch,c));return i&&(u=De(u,await Rn(i,u,r,e.onText))),{source:"image",label:a.label,patch:u}}async function Mn(t,e,r,n,o){let i=n?.vision;i&&F(i);let s=i?A(i):void 0;if(!i||!s){let l=me(t,r);return {source:e,label:l.label,patch:De(r,E(l.patch,r))}}let c=await tr(t,r,i,s,o,n?.browserAccess);return {source:e,label:e,patch:De(r,c)}}async function Rn(t,e,r,n){let o=r?.vision;o&&F(o);let i=o?A(o):void 0;return !o||!i?In(t,e):tr(t,e,o,i,n,r?.browserAccess)}async function tr(t,e,r,n,o,i){let s=await Ce({provider:r,credential:n,text:t,onText:o,purpose:"soundscape",browserAccess:i});return E(Re(s),e)}function In(t,e){let r=me(t,e);return r.label==="current"?{}:E({bpm:r.patch.bpm,reverb_mix:r.patch.reverb_mix},e)}function De(t,e){return {...t,...e}}var rr=v(()=>{"use strict";Ge();I();X();le();at();de();lt();});function ir(t,e){let r=e?.providers;async function n(a){if(!a.tasks?.length)throw new Error("analyze requires at least one task.");for(let d of a.tasks)if(!Cn.has(d))throw new Error(`Unknown analysis task "${d}".`);let u=a.tasks.includes("soundscape"),m=a.tasks.some(d=>nr.has(d))||u&&!!a.image,p=a.tasks.includes("text-mapping");if(p&&!a.text?.trim())throw new Error("text-mapping requires text.");if(u&&!a.image&&!a.prompt?.trim()&&!a.text?.trim())throw new Error("soundscape requires an image, text, or prompt.");let h={};if(m){if(!a.image)throw new Error(`${a.tasks.find(y=>nr.has(y))} requires an image.`);await t.loadImage(a.image);let d=t.readLoadedImage();if(!d||d.blockCount===0)throw new Error("Image loaded but the grid is empty.");let g=a.tasks.includes("color-analysis"),x=a.tasks.includes("sound-mapping");if(g||x){let y=ye(d);g&&(h.color=y),x&&(h.soundscape=Me(y));}a.tasks.includes("description")&&(h.description=await s(a,d));}if(p&&(h.soundscape=await i(a)),u&&(h.soundscape=await er(t,a,r)),a.tasks.includes("audio-intelligence")&&(h.audio=await o(a)),a.tasks.includes("semantic")&&(h.semantic=await Ut(h,r)),a.tasks.includes("narration")){let d=await Kt(a,r);d!==void 0&&(h.narration=d);}return h}async function o(a){let u=a.buffer??await t.toAudioBuffer(),m=yt(u);r?.vision&&F(r.vision);let p=r?.vision?A(r.vision):void 0;if(!r?.vision||!p)return a.onText?.(m.summary),m;let h=await ct({provider:r.vision,credential:p,purpose:"audio-intelligence",onText:a.onText,browserAccess:r.browserAccess,prompt:`Rewrite this measurement as one short prose sentence. Keep every number unchanged.
5
+ ${m.summary}`});return {...m,summary:h.trim()}}async function i(a){let u=q(t.captureParams()),m=a.text?.trim()??"";r?.vision&&F(r.vision);let p=r?.vision?A(r.vision):void 0;if(!r?.vision||!p)return me(m,u);let h=await Ce({provider:r.vision,credential:p,text:m,onText:a.onText,browserAccess:r.browserAccess});return {source:"text",label:"text",patch:{...u,...E(Re(h),u)}}}async function s(a,u){if(!r?.vision){let p=st(u,ot(u.pixels));return a.onText?.(p),p}let m=Te(r.vision);if(!m){let p=st(u,ot(u.pixels));return a.onText?.(p),p}return m.describe({image:a.image,prompt:a.prompt,onText:a.onText,browserAccess:r.browserAccess})}function c(a){if(a&&typeof a=="object"&&"audio"in a&&a.audio instanceof ArrayBuffer)return t.playDetachedAudio(a.audio);Yt(typeof a=="string"?a:a?.text);}function l(a){return t.play(a)}return Object.assign(t,{analyze:n,playSoundscape:l,speak:c,...Zt(t,n)})}var Cn,nr,or=v(()=>{"use strict";wt();Ge();I();X();Ft();Gt();Wt();le();at();Qt();rr();de();lt();Cn=new Set(["description","color-analysis","sound-mapping","text-mapping","audio-intelligence","soundscape","semantic","narration"]),nr=new Set(["description","color-analysis","sound-mapping"]);});function sr(t,e){if(!Dn(t))throw new Error("play requires a soundscape with source, label, and patch.");return E(t.patch,q(e))}function Dn(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return (e.source==="image"||e.source==="text"||e.source==="prompt")&&typeof e.label=="string"&&!!e.patch&&typeof e.patch=="object"&&!Array.isArray(e.patch)}var ar=v(()=>{"use strict";le();de();});var cr={};dr(cr,{attachMultimodal:()=>ir,soundscapePatch:()=>sr});var lr=v(()=>{"use strict";or();ar();});T();var ee=class{constructor(){this.playing=false;this.scale=w[0];this.osc_type="triangle";this.scale_name="Minor";this.base_note=287;this.bpm=70;this.speed=4.2;this.note_mult=.15;this.volume=.99;this.vibrato_rate=0;this.vibrato_depth=50;this.tremolo_rate=1.8;this.tremolo_depth=0;this.fifth_lvl=.37;this.oct_lvl=.63;this.filter_base=1810;this.filter_track=0;this.resonance=2.6;this.reverb_mix=1;this.reverb_time=3.6;this.bass_gain=13.5;this.block_w=23;this.block_h=13;this.scan_mode="linear";this.pan_amount=.6;this.timing_mode="expressive";this.timing_intensity=.4;}applyPatch(e){e.osc_type&&(this.osc_type=e.osc_type),e.scale_name&&(this.scale_name=e.scale_name,this.scale=w.find(r=>r.name===e.scale_name)??w[0]),e.scan_mode&&(this.scan_mode=e.scan_mode),e.timing_mode&&(this.timing_mode=e.timing_mode),typeof e.bpm=="number"&&(this.bpm=e.bpm),typeof e.speed=="number"&&(this.speed=e.speed),typeof e.note_mult=="number"&&(this.note_mult=e.note_mult),typeof e.timing_intensity=="number"&&(this.timing_intensity=e.timing_intensity),typeof e.block_w=="number"&&(this.block_w=e.block_w),typeof e.block_h=="number"&&(this.block_h=e.block_h);}applyAll(e){R.forEach(r=>{let n=e[r];if(n!==void 0){if(r==="scale_name"&&typeof n=="string"){this.scale_name=n,this.scale=w.find(o=>o.name===n)??w[0];return}this[r]=n;}});}capture(){let e={};return R.forEach(r=>{e[r]=this[r];}),e}setNumeric(e,r){this[e]=r;}getNumeric(e){return this[e]}getString(e){return this[e]}setString(e,r){this[e]=r;}};var te=class{constructor(){this._ctx=null;this._master=null;this._analyser=null;this._conv=null;this._wet=null;this._dry=null;}get ctx(){return this._ctx}get master(){return this._master}get analyser(){return this._analyser}get conv(){return this._conv}get wet(){return this._wet}get dry(){return this._dry}ensure(e){if(this._ctx)return;let r=window.AudioContext??window.webkitAudioContext;r&&this.buildGraph(new r,e);}ensureOffline(e,r){this.buildGraph(e,r);}buildGraph(e,r){let n=e.createGain(),o=e.createAnalyser(),i=e.createGain(),s=e.createGain(),c=e.createConvolver();n.gain.value=Math.pow(r.volume??.8,2),o.fftSize=1024,o.smoothingTimeConstant=.88,c.buffer=this.makeImpulse(e,r.reverb_time,3),s.gain.value=r.reverb_mix,i.gain.value=this.dryVal(r.reverb_mix),c.connect(s),i.connect(o),s.connect(o),o.connect(n),n.connect(e.destination),this._ctx=e,this._master=n,this._analyser=o,this._conv=c,this._wet=s,this._dry=i;}makeImpulse(e,r,n){let o=Math.max(1,Math.floor(e.sampleRate*r)),i=e.createBuffer(2,o,e.sampleRate);for(let s=0;s<2;s++){let c=i.getChannelData(s);for(let l=0;l<o;l++)c[l]=(Math.random()*2-1)*Math.pow(1-l/o,n);}return i}dryVal(e){return e>=.99?0:1-e}smooth(e,r,n=.02){!this._ctx||!isFinite(r)||e.setTargetAtTime(r,this._ctx.currentTime,n);}async resume(){this._ctx instanceof AudioContext&&this._ctx.state==="suspended"&&await this._ctx.resume();}suspend(){this._ctx instanceof AudioContext&&this._ctx.state==="running"&&this._ctx.suspend().catch(()=>{});}async warmUp(e){if(this.ensure(e),!(this._ctx instanceof AudioContext))return;await this.resume();let r=this._ctx.createOscillator(),n=this._ctx.createGain();n.gain.value=1e-5,r.connect(n).connect(this._master),r.start(),r.stop(this._ctx.currentTime+.15);}updateReverbBuffer(e){!this._ctx||!this._conv||(this._conv.buffer=this.makeImpulse(this._ctx,e.reverb_time,3));}};k();T();var re=class{constructor(e,r){this.engine=e;this.state=r;}expressiveCurve(e){return .75+Math.pow(e/100,1.3)*.5}getIntensity(){return Math.pow(this.state.timing_intensity??1,1.5)}getStepDur(){let e=isFinite(this.state.bpm)&&this.state.bpm>0?this.state.bpm:120,r=isFinite(this.state.speed)&&this.state.speed>0?this.state.speed:1;return Math.max(.05,60/e/f(r,.5,8))}getSpeedMod(e){let r=this.expressiveCurve(e);return f(1+(r-1)*this.getIntensity()*Ne*.6,.85,1.2)}scheduleNote(e,r,n,o,i){let s=this.engine.ctx,c=this.engine.dry,l=this.engine.conv;if(!s||!c||!l)return i;let a=this.state.speed>2?.003:5e-4,u=(Math.random()-.5)*a;if(i=Math.max(i+u,s.currentTime+.001),!isFinite(i))return i;let m=this.state,p=this.getStepDur(),h=this.expressiveCurve(n*100),d=f(1+(h-1)*this.getIntensity()*Ne*.75,.85,1.2),g=f(isFinite(p)?p*m.note_mult*(.6+.8*r)*d:.2,.06,2),x=m.filter_track===0?m.filter_base:f(m.filter_base+n*m.filter_track,40,s.sampleRate*.45),y=s.createBiquadFilter();y.type="lowpass",y.Q.value=m.resonance,y.frequency.setValueAtTime(x,i);let _=s.createGain();_.gain.setValueAtTime(0,i);let V=s.createGain();V.gain.setValueAtTime(1-m.tremolo_depth,i);let P=s.createOscillator();P.frequency.setValueAtTime(m.tremolo_rate,i);let Z=s.createGain();Z.gain.setValueAtTime(m.tremolo_depth,i),P.connect(Z).connect(V.gain);let z=s.createBiquadFilter();z.type="lowshelf",z.frequency.setValueAtTime(200,i),z.gain.setValueAtTime(m.bass_gain,i);let C=s.createStereoPanner();C.pan.setValueAtTime(f(o,-1,1),i),y.connect(_),_.connect(V),V.connect(z),z.connect(C),C.connect(l),C.connect(c);let Q=.2+r*.6;_.gain.linearRampToValueAtTime(Q,i+.01),_.gain.setTargetAtTime(Q*.6,i+.03,.05),_.gain.setTargetAtTime(1e-4,i+g*.7,.1);let K=s.createGain(),D=s.createOscillator();this.applyWave(D,s),D.frequency.setValueAtTime(e,i);let L=s.createOscillator();this.applyWave(L,s),L.frequency.setValueAtTime(e*1.5,i);let O=s.createOscillator();this.applyWave(O,s),O.frequency.setValueAtTime(e*2,i);let N=s.createOscillator();N.frequency.setValueAtTime(m.vibrato_rate,i);let M=s.createGain();M.gain.setValueAtTime(e*(Math.pow(2,m.vibrato_depth/1200)-1),i),N.connect(M),M.connect(D.frequency),M.connect(L.frequency),M.connect(O.frequency);let Y=s.createGain(),dt=s.createGain(),pt=f(m.fifth_lvl,0,1),ht=f(m.oct_lvl,0,1);m.osc_type==="bell"&&(pt*=.35,ht*=.25),Y.gain.setValueAtTime(pt,i),dt.gain.setValueAtTime(ht,i),D.connect(K),L.connect(Y).connect(K),O.connect(dt).connect(K),K.connect(y);let pe=i+g+.05;return D.start(i),D.stop(pe),L.start(i),L.stop(pe),O.start(i),O.stop(pe),N.start(i),N.stop(pe),P.start(i),P.stop(i+g+.1),i}applyWave(e,r){let n=this.state.osc_type;if(["sine","square","sawtooth","triangle"].includes(n)){e.type=n;return}if(n==="pulse"){let o=new Float32Array([0,0,0,0,0,0,0,0]),i=new Float32Array([0,1,0,.33,0,.2,0,.14]);e.setPeriodicWave(r.createPeriodicWave(o,i));return}if(n==="organ"){let o=new Float32Array([0,1,.8,.6,.45,.3,.2]),i=new Float32Array(o.length);e.setPeriodicWave(r.createPeriodicWave(o,i));return}if(n==="bell"){let o=new Float32Array([0,1,.9,.55,.32,.18,.09,.04]),i=new Float32Array(o.length);e.setPeriodicWave(r.createPeriodicWave(o,i));return}e.type="triangle";}};k();var U=class{},Fe=class extends U{advance(e,r,n){e.x++,e.x>=r&&(e.x=0,e.y=(e.y+1)%n);}reset(e,r){e.x=0,e.y=0;}},qe=class extends U{advance(e,r,n){e.y++,e.y>=n&&(e.y=0,e.x=(e.x+1)%r);}reset(e,r){e.x=0,e.y=0;}},Ve=class extends U{advance(e,r,n){e.x+=e.dx,e.x>=r?(e.x=r-1,e.dx=-1,e.y=(e.y+1)%n):e.x<0&&(e.x=0,e.dx=1,e.y=(e.y+1)%n);}reset(e,r){e.x=0,e.y=0,e.dx=1;}},ze=class extends U{advance(e,r,n){let o=e.lastL??50,i=0,s=0;if(Math.random()<.05){e.x=Math.floor(Math.random()*r),e.y=Math.floor(Math.random()*n);return}o>60?i=1:o<40?i=-1:s=Math.random()<.5?1:-1,Math.random()<.15&&(i=Math.floor(Math.random()*3)-1,s=Math.floor(Math.random()*3)-1),e.x=(e.x+i+r)%r,e.y=(e.y+s+n)%n;}reset(e,r){e.x=0,e.y=0;}},$e=class extends U{advance(e,r,n){let o=e.grid.spiralPath;if(!o.length)return;e.spiralIdx=(e.spiralIdx+1)%o.length;let i=o[e.spiralIdx];e.x=i.x,e.y=i.y;}reset(e,r){e.spiralIdx=0,r.spiralPath.length?(e.x=r.spiralPath[0].x,e.y=r.spiralPath[0].y):(e.x=0,e.y=0);}},ne=class{static get(e){return this.strategies[e]??this.strategies.linear}};ne.strategies={linear:new Fe,vertical:new qe,zigzag:new Ve,drift:new ze,spiral:new $e};var H=class{constructor(e){this.grid=e;this.x=0;this.y=0;this.dx=1;this.visX=0;this.visY=0;this.renderX=0;this.renderY=0;this.visIdx=0;this.nextTime=0;this.raf=null;this.lastL=50;this.active=false;this.spiralIdx=0;this.activateAt=0;}resetPosition(e){ne.get(e.scan_mode).reset(this,this.grid),this.dx=1,this.visX=0,this.visY=0,this.renderX=0,this.renderY=0,this.visIdx=0,this.lastL=50,this.active=false,this.spiralIdx=0,this.activateAt=0;}currentBlockIdx(){let e=this.y*this.grid.cols+this.x;return isFinite(e)?f(e,0,this.grid.list.length-1):0}advance(e){let r=this.grid.cols,n=this.grid.rows;if(r<=0||n<=0)return;ne.get(e.scan_mode).advance(this,r,n);}clampToGrid(){this.x=Math.min(this.x,Math.max(0,this.grid.cols-1)),this.y=Math.min(this.y,Math.max(0,this.grid.rows-1));}static mapBlockToNote(e,r,n){let o=r.intervals[e.degree%r.intervals.length]+12*e.oct,i=e.pan*5,s=he(fe(n.base_note)+o+i/100),c=e.pan*n.pan_amount;return {freq:s,vel:e.vel,brightness:e.l/100,pan:c}}};T();k();var ie=class{constructor(e,r,n,o,i,s){this.state=e;this.engine=r;this.synth=n;this.seq=o;this.grid=i;this.onNotePlay=s;this.raf=null;this.tick=()=>{if(!this.state.playing||!this.engine.ctx)return;let e=this.engine.ctx.currentTime;this.seq.nextTime<e-.02&&(this.seq.nextTime=e);let r=this.synth.getStepDur(),n=f(r*2.5,.12,.3);if(this.grid.list.length&&this.grid.cols&&this.grid.rows)for(;this.seq.nextTime<e+n;)if(this.playStep(this.seq.nextTime),this.state.timing_mode==="expressive"){let o=this.synth.getSpeedMod(this.seq.lastL??50);this.seq.nextTime+=r/o;}else this.seq.nextTime+=r;this.raf=requestAnimationFrame(this.tick);};}start(){this.engine.ctx&&(this.seq.nextTime=this.engine.ctx.currentTime+.03,this.raf&&cancelAnimationFrame(this.raf),this.tick());}stop(){this.raf&&(cancelAnimationFrame(this.raf),this.raf=null);}resync(){if(!this.engine.ctx)return;let e=this.engine.ctx.currentTime;this.seq.nextTime<e-.02&&(this.seq.nextTime=e+.02);}renderRange(e,r){if(!(this.grid.list.length&&this.grid.cols&&this.grid.rows))return;let n=this.synth.getStepDur(),o=e;for(;o<r;)if(this.playStep(o),this.state.timing_mode==="expressive"){let i=this.synth.getSpeedMod(this.seq.lastL??50);o+=n/i;}else o+=n;}playStep(e){let r=this.state.scale??w[0];if(this.grid.list.length>0){let n=this.seq.currentBlockIdx(),o=this.grid.list[n];if(o){this.seq.visIdx=n,this.seq.lastL=o.l;let i=H.mapBlockToNote(o,r,this.state);this.synth.scheduleNote(i.freq,i.vel,i.brightness,i.pan,e),this.onNotePlay?.({freq:i.freq,vel:i.vel,pan:i.pan,blockIndex:n,timestamp:e});}}else {let n=Math.floor(this.seq.x%64/64*(r.intervals.length-1)),o=he(fe(this.state.base_note)+r.intervals[n]);this.seq.lastL=50,this.synth.scheduleNote(o,.6,.5,0,e),this.onNotePlay?.({freq:o,vel:.6,pan:0,blockIndex:-1,timestamp:e});}this.seq.visX=this.seq.x,this.seq.visY=this.seq.y,this.seq.activateAt===0&&(this.seq.activateAt=e),this.seq.advance(this.state);}};k();T();var oe=class{constructor(){this._canvas=null;this._pixels=null;this._w=0;this._h=0;}get canvas(){return this._canvas}get pixels(){return this._pixels}get width(){return this._w}get height(){return this._h}processImage(e){let n=Math.min(2048/e.naturalWidth,2048/e.naturalHeight,1),o=Math.max(1,Math.floor(e.naturalWidth*n)),i=Math.max(1,Math.floor(e.naturalHeight*n)),s=document.createElement("canvas");s.width=o,s.height=i;let c=s.getContext("2d");c.imageSmoothingEnabled=true,c.drawImage(e,0,0,o,i),this._canvas=s;let l=512,a=Math.min(l/e.naturalWidth,l/e.naturalHeight,1),u=Math.max(1,Math.floor(e.naturalWidth*a)),m=Math.max(1,Math.floor(e.naturalHeight*a)),p=document.createElement("canvas");p.width=u,p.height=m;let h=p.getContext("2d",{willReadFrequently:true});h.imageSmoothingEnabled=true,h.drawImage(e,0,0,u,m);let d=h.getImageData(0,0,u,m);this._pixels=d.data,this._w=u,this._h=m;}loadDefault(e,r){let n=new Image;n.onload=()=>r(n),n.onerror=()=>{},n.src=e;}},se=class{constructor(){this._list=[];this._cols=0;this._rows=0;this._spiralPath=[];}get list(){return this._list}get cols(){return this._cols}get rows(){return this._rows}get spiralPath(){return this._spiralPath}build(e,r){if(this._list=[],this._cols=0,this._rows=0,!e.pixels)return;let n=r.scale??w[0],o=Math.max(1,Math.floor(r.block_w)),i=Math.max(1,Math.floor(r.block_h)),s=Math.max(1,Math.floor(e.width/o)),c=Math.max(1,Math.floor(e.height/i));this._cols=s,this._rows=c;let l=n.intervals.length-1,a=e.pixels,u=e.width;for(let m=0;m<c;m++)for(let p=0;p<s;p++){let h=p*o,d=m*i,g=Math.min(h+o,e.width),x=Math.min(d+i,e.height),y=0,_=0,V=0,P=0;for(let N=d;N<x;N++)for(let M=h;M<g;M++){let Y=(N*u+M)*4;y+=a[Y],_+=a[Y+1],V+=a[Y+2],P++;}if(P===0)continue;let{h:Z,s_hsv:z,l:C}=$(y/P,_/P,V/P),Q=isFinite(Z)?Z:0,K=f(Math.floor(Math.sqrt(Q/360)*l),0,l),D=Math.floor(C/100*3)-1,L=f(.2+C/100*.5+z*.3,.1,1),O=Q/360*2-1;this._list.push({degree:K,oct:D,vel:L,l:C,pan:O});}this._spiralPath=this.buildSpiralPath(s,c);}buildSpiralPath(e,r){let n=Math.floor(e/2),o=Math.floor(r/2),i=[],s=new Set,c=n,l=o,a=1,u=0,m=[1,0,-1,0],p=[0,1,0,-1];for(;i.length<e*r;){for(let h=0;h<2;h++){for(let d=0;d<a;d++){let g=`${c},${l}`;c>=0&&c<e&&l>=0&&l<r&&!s.has(g)&&(i.push({x:c,y:l}),s.add(g)),c+=m[u],l+=p[u];}u=(u+1)%4;}if(a++,i.length>=e*r)break}if(i.length<e*r)for(let h=0;h<r;h++)for(let d=0;d<e;d++)s.has(`${d},${h}`)||i.push({x:d,y:h});return i}};function bt(t){let e=t.numberOfChannels,r=e*2,n=t.length*r,o=new ArrayBuffer(44+n),i=new DataView(o);return gr(i,t.sampleRate,e,r,n),br(i,t,e),new Blob([o],{type:"audio/wav"})}function gr(t,e,r,n,o){ge(t,0,"RIFF"),t.setUint32(4,36+o,true),ge(t,8,"WAVE"),ge(t,12,"fmt "),t.setUint32(16,16,true),t.setUint16(20,1,true),t.setUint16(22,r,true),t.setUint32(24,e,true),t.setUint32(28,e*n,true),t.setUint16(32,n,true),t.setUint16(34,16,true),ge(t,36,"data"),t.setUint32(40,o,true);}function br(t,e,r){let n=[];for(let i=0;i<r;i++)n.push(e.getChannelData(i));let o=44;for(let i=0;i<e.length;i++)for(let s=0;s<r;s++)t.setInt16(o,vr(n[s][i]),true),o+=2;}function vr(t){let e=Math.max(-1,Math.min(1,t));return e<0?e*32768:e*32767}function ge(t,e,r){for(let n=0;n<r.length;n++)t.setUint8(e+n,r.charCodeAt(n));}T();T();k();var be=class{constructor(e,r,n){this.state=e;this.engine=r;this.onTick=n;this.raf=null;}tweenTo(e){this.raf&&(cancelAnimationFrame(this.raf),this.raf=null);let r={};Be.forEach(i=>{let s=e[i];if(typeof s=="number"&&isFinite(s)){let c=this.state.getNumeric(i);r[i]=isFinite(c)?c:s;}});let n=performance.now(),o=()=>{let i=Math.min((performance.now()-n)/ft,1),s=gt(i);Be.forEach(c=>{if(r[c]===void 0)return;let l=e[c],a=r[c]+(l-r[c])*s;this.state.setNumeric(c,a),this.onTick?.(c,a);}),isFinite(this.state.volume)&&this.engine.master&&(this.engine.master.gain.value=Math.pow(this.state.volume,2)),isFinite(this.state.reverb_mix)&&this.engine.wet&&(this.engine.wet.gain.value=this.state.reverb_mix,this.engine.dry.gain.value=this.engine.dryVal(this.state.reverb_mix)),i<1?this.raf=requestAnimationFrame(o):r.reverb_time!==void 0&&this.engine.updateReverbBuffer(this.state);};this.raf=requestAnimationFrame(o);}cancel(){this.raf&&(cancelAnimationFrame(this.raf),this.raf=null);}};var ve=class{constructor(e,r,n,o,i,s){this.engine=n;this.imageProcessor=o;this.grid=i;this.seq=s;this.waveBuf=null;this.drawT=0;this.renderRaf=null;this.renderFrame=()=>{this.renderRaf=requestAnimationFrame(this.renderFrame);let e=performance.now();if(e-this.drawT<1e3/60)return;this.drawT=e;let r=this.canvasCssSize(this.waveCanvas),n=this.canvasCssSize(this.mapCanvas);this.drawWave(r.w,r.h),this.drawMap(n.w,n.h);};this.waveCanvas=e,this.mapCanvas=r;}start(){this.resizeCanvases(),this.renderFrame();}stop(){this.renderRaf&&(cancelAnimationFrame(this.renderRaf),this.renderRaf=null);}resizeCanvases(){let e=window.devicePixelRatio||1;[this.waveCanvas,this.mapCanvas].forEach(r=>{if(!r)return;let n=r.getBoundingClientRect();r.width=Math.floor(n.width*e),r.height=Math.floor(n.height*e),r.getContext("2d").setTransform(e,0,0,e,0,0);});}canvasCssSize(e){let r=e.getBoundingClientRect();return {w:r.width,h:r.height}}drawWave(e,r){let n=this.waveCanvas.getContext("2d");n.fillStyle="#0d0d14",n.fillRect(0,0,e,r),n.strokeStyle="rgba(255,255,255,0.03)",n.lineWidth=1;for(let i=0;i<e;i+=40)n.beginPath(),n.moveTo(i+.5,0),n.lineTo(i+.5,r),n.stroke();for(let i=0;i<r;i+=40)n.beginPath(),n.moveTo(0,i+.5),n.lineTo(e,i+.5),n.stroke();this.engine.analyser&&((!this.waveBuf||this.waveBuf.length!==this.engine.analyser.fftSize)&&(this.waveBuf=new Uint8Array(this.engine.analyser.fftSize)),this.engine.analyser.getByteTimeDomainData(this.waveBuf));let o=this.waveBuf?.length??1024;n.beginPath(),n.strokeStyle="#ffffff",n.lineWidth=2;for(let i=0;i<o;i++){let s=this.waveBuf?this.waveBuf[i]/128:1,c=i/(o-1)*e;i===0?n.moveTo(c,s*r/2):n.lineTo(c,s*r/2);}n.stroke();}drawMap(e,r){let n=this.mapCanvas.getContext("2d");n.clearRect(0,0,e,r);let o=this.imageProcessor.canvas;if(!o)return;let i=Math.min(e/o.width,r/o.height),s=o.width*i,c=o.height*i,l=(e-s)/2,a=(r-c)/2;if(n.save(),n.imageSmoothingEnabled=true,n.drawImage(o,0,0,o.width,o.height,l,a,s,c),!this.seq.active&&this.seq.activateAt>0&&this.engine.ctx&&this.engine.ctx.currentTime>=this.seq.activateAt&&(this.seq.active=true),this.seq.active&&this.grid.cols>0&&this.grid.list.length>0){this.seq.renderX=this.seq.renderX+(this.seq.visX-this.seq.renderX)*1,this.seq.renderY=this.seq.renderY+(this.seq.visY-this.seq.renderY)*1;let m=s/this.grid.cols,p=c/this.grid.rows,h=Math.max(1.5,Math.min(m,p)*.06),d=l+this.seq.renderX*m,g=a+this.seq.renderY*p,x=m-1,y=p-1,_=this.seq.lastL>50;n.strokeStyle=_?"rgba(30,30,30,0.85)":"rgba(220,220,220,0.85)",n.lineWidth=h,n.strokeRect(d+.5,g+.5,x,y);}n.restore();}};async function Ue(t){if(t instanceof HTMLImageElement)return yr(t);let e=t instanceof Blob,r=e?URL.createObjectURL(t):t,n=new Image;return e||(n.crossOrigin="anonymous"),new Promise((o,i)=>{n.onload=()=>{e&&URL.revokeObjectURL(r),o(n);},n.onerror=()=>{e&&URL.revokeObjectURL(r),i(new Error(`Failed to load image: ${e?"blob":r}`));},n.src=r;})}function yr(t){return t.complete&&t.naturalWidth>0?Promise.resolve(t):t.complete&&t.naturalWidth===0?Promise.reject(new Error("Failed to load image")):new Promise((e,r)=>{t.addEventListener("load",()=>e(t),{once:true}),t.addEventListener("error",()=>r(new Error("Failed to load image")),{once:true});})}var Ln=["analyze","playSoundscape","describe","soundify","interpret","narrate","explore"],ut;function mt(){return ut??(ut=Promise.resolve().then(()=>(lr(),cr))),ut}function ur(t,e){let r,n=()=>(r??(r=mt().then(({attachMultimodal:i})=>i(t,e?{providers:e}:void 0))),r),o=t;for(let i of Ln)o[i]=(...s)=>n().then(c=>c[i](...s));o.speak=(i=>n().then(s=>s.speak(i)));}var On=10,Nn=44100,Bn=2,Le=class extends EventTarget{constructor(r={}){super();this.state=new ee;this.engine=new te;this.imageProcessor=new oe;this.grid=new se;this.renderer=null;this.reverbDebounce=null;this.loadedImage=null;this.playStartTime=0;this.speechSource=null;this.seq=new H(this.grid),this.synth=new re(this.engine,this.state),this.scheduler=new ie(this.state,this.engine,this.synth,this.seq,this.grid,n=>this.emit("noteplay",n)),this.tweener=new be(this.state,this.engine,r.onTweenTick),r.waveCanvas&&r.mapCanvas&&this.attachVisuals(r.waveCanvas,r.mapCanvas),(r.mode==="multimodal"||r.providers!=null)&&ur(this,r.providers);}get playing(){return this.state.playing}attachVisuals(r,n){this.renderer?.stop(),this.renderer=new ve(r,n,this.engine,this.imageProcessor,this.grid,this.seq),this.renderer.start();}resizeVisuals(){this.renderer?.resizeCanvases();}readLoadedImage(){let r=this.imageProcessor.pixels;return !r||this.imageProcessor.width===0||this.imageProcessor.height===0?null:{pixels:r,width:this.imageProcessor.width,height:this.imageProcessor.height,blockCount:this.grid.list.length}}async loadImage(r){try{let n=await Ue(r);this.loadedImage=n,this.imageProcessor.processImage(n),this.rebuildGrid(),this.emit("imageload",{width:n.naturalWidth,height:n.naturalHeight,blockCount:this.grid.list.length});}catch(n){throw this.emitError(n,"loadImage")}}async play(r){if(r){let{soundscapePatch:n}=await mt();this.applyParams(n(r,this.captureParams()),{tween:false});}try{if(this.engine.ensure(this.state),!this.engine.ctx)throw new Error("Web Audio API is not available");if(this.state.playing)return;await this.engine.resume();}catch(n){throw this.emitError(n,"play")}!this.engine.ctx||this.state.playing||(this.state.playing=true,this.playStartTime=this.engine.ctx.currentTime,this.scheduler.start(),this.emit("start",{timestamp:this.engine.ctx.currentTime}));}stop(){if(this.stopSpeech(),!this.state.playing)return;let r=this.engine.ctx?.currentTime??0,n=r-this.playStartTime;this.state.playing=false,this.seq.nextTime=0,this.seq.active=false,this.seq.activateAt=0,this.scheduler.stop(),this.engine.suspend(),this.emit("stop",{timestamp:r,duration:n});}async warmUp(){try{await this.engine.warmUp(this.state);}catch(r){throw this.emitError(r,"warmUp")}}getParam(r){return this.state[r]}setParam(r,n){typeof n=="number"?this.state.setNumeric(r,n):this.state.setString(r,n),this.applyParamSideEffects(r);}applyParams(r,n={}){let{tween:o=true}=n;o?(this.state.applyPatch(r),this.rebuildGrid(),this.tweener.tweenTo(r)):(this.tweener.cancel(),this.state.applyAll(r),this.rebuildGrid(),this.syncLiveAudioFromState()),r.scan_mode&&(this.seq.resetPosition(this.state),this.scheduler.resync());}captureParams(){return this.state.capture()}async toAudioBuffer(r={}){try{return await this.renderOffline(r)}catch(n){throw this.emitError(n,"toAudioBuffer")}}async toBlob(r={}){let n=await this.toAudioBuffer(r);return bt(n)}async playDetachedAudio(r){this.engine.ensure(this.state);let n=this.engine.ctx,o=this.engine.master;if(!(n instanceof AudioContext)||!o)throw new Error("Web Audio API is not available");this.stopSpeech();let i=await n.decodeAudioData(r.slice(0)),s=n.createBufferSource();s.buffer=i,s.connect(o),s.onended=()=>{this.speechSource===s&&(this.speechSource=null);},this.speechSource=s,s.start();}stopSpeech(){let r=this.speechSource;if(this.speechSource=null,!!r){try{r.stop();}catch{}try{r.disconnect();}catch{}}}async renderOffline(r){let{duration:n=On,sampleRate:o=Nn}=r,i=new ee;i.applyAll(r.params??this.state.capture());let s=new oe,c=new se,l=r.image?await Ue(r.image):this.loadedImage;if(!l)throw new Error("No image loaded. Pass `image` or call loadImage first.");s.processImage(l),c.build(s,i);let a=new H(c);a.resetPosition(i);let u=new OfflineAudioContext({numberOfChannels:Bn,length:Math.max(1,Math.ceil(n*o)),sampleRate:o}),m=new te;m.ensureOffline(u,i);let p=new re(m,i);return new ie(i,m,p,a,c).renderRange(0,n),u.startRendering()}rebuildGrid(){this.grid.build(this.imageProcessor,this.state),this.seq.clampToGrid(),this.scheduler.resync();}applyParamSideEffects(r){switch(r){case b.volume:this.engine.master&&this.engine.smooth(this.engine.master.gain,Math.pow(this.state.volume,2));break;case b.bpm:case b.speed:case b.note_mult:this.scheduler.resync();break;case b.reverb_mix:this.engine.wet&&this.engine.dry&&(this.engine.smooth(this.engine.wet.gain,this.state.reverb_mix),this.engine.smooth(this.engine.dry.gain,this.engine.dryVal(this.state.reverb_mix)));break;case b.reverb_time:if(!this.engine.ctx||!this.engine.conv)return;this.reverbDebounce&&clearTimeout(this.reverbDebounce),this.reverbDebounce=setTimeout(()=>this.engine.updateReverbBuffer(this.state),120);break;case b.block_w:case b.block_h:this.rebuildGrid();break;case b.scale_name:this.state.scale=w.find(n=>n.name===this.state.scale_name)??w[0],this.rebuildGrid();break;case b.scan_mode:this.seq.resetPosition(this.state),this.scheduler.resync();break}}syncLiveAudioFromState(){this.engine.master&&(this.engine.master.gain.value=Math.pow(this.state.volume,2)),this.engine.wet&&this.engine.dry&&(this.engine.wet.gain.value=this.state.reverb_mix,this.engine.dry.gain.value=this.engine.dryVal(this.state.reverb_mix)),this.engine.updateReverbBuffer(this.state);}emit(r,n){this.dispatchEvent(new CustomEvent(r,{detail:n}));}emitError(r,n){let o=r instanceof Error?r:new Error(String(r));return this.emit("error",{error:o,context:n}),o}};ue();T();var Xo=Le;export{Xo as Audiora,fr as DEFAULT_PRESET,Oe as FORMAT,j as PRESETS,pr as RANGE_KEYS,hr as SELECT_KEYS};//# sourceMappingURL=index.js.map
2
6
  //# sourceMappingURL=index.js.map