audiora 1.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/src/Audiora.ts ADDED
@@ -0,0 +1,293 @@
1
+ import { State } from "./core/State";
2
+ import { AudioEngine } from "./core/AudioEngine";
3
+ import { Synthesizer } from "./core/Synthesizer";
4
+ import { Scheduler } from "./core/Scheduler";
5
+ import { Sequencer } from "./core/Scanner";
6
+ import { ImageProcessor, BlockGrid } from "./core/ImageProcessor";
7
+ import { audioBufferToWavBlob } from "./core/wav";
8
+ import { PresetData } from "./core/types";
9
+ import { KEY, SCALES } from "./core/constants";
10
+ import { Tweener, TweenTickHandler } from "./ui/Tweener";
11
+ import { Renderer } from "./ui/Renderer";
12
+
13
+ export type ImageSource = string | File | Blob | HTMLImageElement;
14
+
15
+ export interface RenderOptions {
16
+ image?: ImageSource;
17
+ params?: Partial<PresetData>;
18
+ duration?: number;
19
+ sampleRate?: number;
20
+ }
21
+
22
+ export interface LiveOptions {
23
+ waveCanvas?: HTMLCanvasElement;
24
+ mapCanvas?: HTMLCanvasElement;
25
+ onTweenTick?: TweenTickHandler;
26
+ }
27
+
28
+ const DEFAULT_DURATION_SECONDS = 10;
29
+ const DEFAULT_SAMPLE_RATE = 44100;
30
+ const OUTPUT_CHANNELS = 2;
31
+
32
+ export class Audiora {
33
+ private readonly state = new State();
34
+ private readonly engine = new AudioEngine();
35
+ private readonly imageProcessor = new ImageProcessor();
36
+ private readonly grid = new BlockGrid();
37
+ private readonly seq: Sequencer;
38
+ private readonly synth: Synthesizer;
39
+ private readonly scheduler: Scheduler;
40
+ private readonly tweener: Tweener;
41
+ private renderer: Renderer | null = null;
42
+ private reverbDebounce: ReturnType<typeof setTimeout> | null = null;
43
+ private loadedImage: HTMLImageElement | null = null;
44
+
45
+ constructor(options: LiveOptions = {}) {
46
+ this.seq = new Sequencer(this.grid);
47
+ this.synth = new Synthesizer(this.engine, this.state);
48
+ this.scheduler = new Scheduler(
49
+ this.state,
50
+ this.engine,
51
+ this.synth,
52
+ this.seq,
53
+ this.grid,
54
+ );
55
+ this.tweener = new Tweener(this.state, this.engine, options.onTweenTick);
56
+
57
+ if (options.waveCanvas && options.mapCanvas) {
58
+ this.attachVisuals(options.waveCanvas, options.mapCanvas);
59
+ }
60
+ }
61
+
62
+ public get playing(): boolean {
63
+ return this.state.playing;
64
+ }
65
+
66
+ public attachVisuals(
67
+ waveCanvas: HTMLCanvasElement,
68
+ mapCanvas: HTMLCanvasElement,
69
+ ): void {
70
+ this.renderer?.stop();
71
+ this.renderer = new Renderer(
72
+ waveCanvas,
73
+ mapCanvas,
74
+ this.engine,
75
+ this.imageProcessor,
76
+ this.grid,
77
+ this.seq,
78
+ );
79
+ this.renderer.start();
80
+ }
81
+
82
+ public resizeVisuals(): void {
83
+ this.renderer?.resizeCanvases();
84
+ }
85
+
86
+ public async loadImage(image: ImageSource): Promise<void> {
87
+ const img = await resolveImageElement(image);
88
+ this.loadedImage = img;
89
+ this.imageProcessor.processImage(img);
90
+ this.rebuildGrid();
91
+ }
92
+
93
+ public async play(): Promise<void> {
94
+ this.engine.ensure(this.state);
95
+ if (!this.engine.ctx || this.state.playing) return;
96
+ await this.engine.resume();
97
+ this.state.playing = true;
98
+ this.scheduler.start();
99
+ }
100
+
101
+ public stop(): void {
102
+ this.state.playing = false;
103
+ this.seq.nextTime = 0;
104
+ this.seq.active = false;
105
+ this.seq.activateAt = 0;
106
+ this.scheduler.stop();
107
+ this.engine.suspend();
108
+ }
109
+
110
+ public async warmUp(): Promise<void> {
111
+ await this.engine.warmUp(this.state);
112
+ }
113
+
114
+ public getParam(key: keyof PresetData): string | number {
115
+ const value = (this.state as unknown as Record<string, unknown>)[key];
116
+ return value as string | number;
117
+ }
118
+
119
+ public setParam(key: keyof PresetData, value: string | number): void {
120
+ if (typeof value === "number") this.state.setNumeric(key, value);
121
+ else this.state.setString(key, value);
122
+ this.applyParamSideEffects(key);
123
+ }
124
+
125
+ public applyParams(
126
+ patch: Partial<PresetData>,
127
+ options: { tween?: boolean } = {},
128
+ ): void {
129
+ const { tween = true } = options;
130
+
131
+ if (tween) {
132
+ this.state.applyPatch(patch);
133
+ this.rebuildGrid();
134
+ this.tweener.tweenTo(patch);
135
+ } else {
136
+ this.tweener.cancel();
137
+ this.state.applyAll(patch);
138
+ this.rebuildGrid();
139
+ this.syncLiveAudioFromState();
140
+ }
141
+
142
+ if (patch.scan_mode) {
143
+ this.seq.resetPosition(this.state);
144
+ this.scheduler.resync();
145
+ }
146
+ }
147
+
148
+ public captureParams(): Partial<PresetData> {
149
+ return this.state.capture();
150
+ }
151
+
152
+ public async toAudioBuffer(options: RenderOptions = {}): Promise<AudioBuffer> {
153
+ const {
154
+ duration = DEFAULT_DURATION_SECONDS,
155
+ sampleRate = DEFAULT_SAMPLE_RATE,
156
+ } = options;
157
+
158
+ const state = new State();
159
+ state.applyAll(options.params ?? this.state.capture());
160
+
161
+ const imageProcessor = new ImageProcessor();
162
+ const grid = new BlockGrid();
163
+ const img = options.image
164
+ ? await resolveImageElement(options.image)
165
+ : this.loadedImage;
166
+
167
+ if (!img) throw new Error("No image loaded. Pass `image` or call loadImage first.");
168
+
169
+ imageProcessor.processImage(img);
170
+ grid.build(imageProcessor, state);
171
+
172
+ const seq = new Sequencer(grid);
173
+ seq.resetPosition(state);
174
+
175
+ const ctx = new OfflineAudioContext({
176
+ numberOfChannels: OUTPUT_CHANNELS,
177
+ length: Math.max(1, Math.ceil(duration * sampleRate)),
178
+ sampleRate,
179
+ });
180
+
181
+ const engine = new AudioEngine();
182
+ engine.ensureOffline(ctx, state);
183
+
184
+ const synth = new Synthesizer(engine, state);
185
+ const scheduler = new Scheduler(state, engine, synth, seq, grid);
186
+ scheduler.renderRange(0, duration);
187
+
188
+ return ctx.startRendering();
189
+ }
190
+
191
+ public async toBlob(options: RenderOptions = {}): Promise<Blob> {
192
+ const buffer = await this.toAudioBuffer(options);
193
+ return audioBufferToWavBlob(buffer);
194
+ }
195
+
196
+ private rebuildGrid(): void {
197
+ this.grid.build(this.imageProcessor, this.state);
198
+ this.seq.clampToGrid();
199
+ this.scheduler.resync();
200
+ }
201
+
202
+ private applyParamSideEffects(key: keyof PresetData): void {
203
+ switch (key) {
204
+ case KEY.volume:
205
+ if (this.engine.master) {
206
+ this.engine.smooth(
207
+ this.engine.master.gain,
208
+ Math.pow(this.state.volume, 2),
209
+ );
210
+ }
211
+ break;
212
+ case KEY.bpm:
213
+ case KEY.speed:
214
+ case KEY.note_mult:
215
+ this.scheduler.resync();
216
+ break;
217
+ case KEY.reverb_mix:
218
+ if (this.engine.wet && this.engine.dry) {
219
+ this.engine.smooth(this.engine.wet.gain, this.state.reverb_mix);
220
+ this.engine.smooth(
221
+ this.engine.dry.gain,
222
+ this.engine.dryVal(this.state.reverb_mix),
223
+ );
224
+ }
225
+ break;
226
+ case KEY.reverb_time:
227
+ if (!this.engine.ctx || !this.engine.conv) return;
228
+ if (this.reverbDebounce) clearTimeout(this.reverbDebounce);
229
+ this.reverbDebounce = setTimeout(
230
+ () => this.engine.updateReverbBuffer(this.state),
231
+ 120,
232
+ );
233
+ break;
234
+ case KEY.block_w:
235
+ case KEY.block_h:
236
+ this.rebuildGrid();
237
+ break;
238
+ case KEY.scale_name:
239
+ this.state.scale =
240
+ SCALES.find((s) => s.name === this.state.scale_name) ?? SCALES[0];
241
+ this.rebuildGrid();
242
+ break;
243
+ case KEY.scan_mode:
244
+ this.seq.resetPosition(this.state);
245
+ this.scheduler.resync();
246
+ break;
247
+ }
248
+ }
249
+
250
+ private syncLiveAudioFromState(): void {
251
+ if (this.engine.master) {
252
+ this.engine.master.gain.value = Math.pow(this.state.volume, 2);
253
+ }
254
+ if (this.engine.wet && this.engine.dry) {
255
+ this.engine.wet.gain.value = this.state.reverb_mix;
256
+ this.engine.dry.gain.value = this.engine.dryVal(this.state.reverb_mix);
257
+ }
258
+ this.engine.updateReverbBuffer(this.state);
259
+ }
260
+ }
261
+
262
+ async function resolveImageElement(image: ImageSource): Promise<HTMLImageElement> {
263
+ if (image instanceof HTMLImageElement) return waitForImage(image);
264
+
265
+ const isBlobSource = image instanceof Blob;
266
+ const src = isBlobSource ? URL.createObjectURL(image) : image;
267
+ const img = new Image();
268
+ if (!isBlobSource) img.crossOrigin = "anonymous";
269
+
270
+ return new Promise((resolve, reject) => {
271
+ img.onload = () => {
272
+ if (isBlobSource) URL.revokeObjectURL(src);
273
+ resolve(img);
274
+ };
275
+ img.onerror = () => {
276
+ if (isBlobSource) URL.revokeObjectURL(src);
277
+ reject(new Error(`Failed to load image: ${isBlobSource ? "blob" : src}`));
278
+ };
279
+ img.src = src;
280
+ });
281
+ }
282
+
283
+ function waitForImage(img: HTMLImageElement): Promise<HTMLImageElement> {
284
+ if (img.complete && img.naturalWidth > 0) return Promise.resolve(img);
285
+ return new Promise((resolve, reject) => {
286
+ img.addEventListener("load", () => resolve(img), { once: true });
287
+ img.addEventListener(
288
+ "error",
289
+ () => reject(new Error("Failed to load image")),
290
+ { once: true },
291
+ );
292
+ });
293
+ }
@@ -0,0 +1,108 @@
1
+ import { State } from "./State";
2
+ import { clamp } from "./utils";
3
+
4
+ export class AudioEngine {
5
+ private _ctx: BaseAudioContext | null = null;
6
+ private _master: GainNode | null = null;
7
+ private _analyser: AnalyserNode | null = null;
8
+ private _conv: ConvolverNode | null = null;
9
+ private _wet: GainNode | null = null;
10
+ private _dry: GainNode | null = null;
11
+
12
+ public get ctx(): BaseAudioContext | null { return this._ctx; }
13
+ public get master(): GainNode | null { return this._master; }
14
+ public get analyser(): AnalyserNode | null { return this._analyser; }
15
+ public get conv(): ConvolverNode | null { return this._conv; }
16
+ public get wet(): GainNode | null { return this._wet; }
17
+ public get dry(): GainNode | null { return this._dry; }
18
+
19
+ public ensure(state: State): void {
20
+ if (this._ctx) return;
21
+ const Ctx = window.AudioContext ?? (window as any).webkitAudioContext;
22
+ if (!Ctx) return;
23
+ this.buildGraph(new Ctx(), state);
24
+ }
25
+
26
+ public ensureOffline(ctx: OfflineAudioContext, state: State): void {
27
+ this.buildGraph(ctx, state);
28
+ }
29
+
30
+ private buildGraph(ctx: BaseAudioContext, state: State): void {
31
+ const master = ctx.createGain();
32
+ const analyser = ctx.createAnalyser();
33
+ const dry = ctx.createGain();
34
+ const wet = ctx.createGain();
35
+ const conv = ctx.createConvolver();
36
+
37
+ master.gain.value = Math.pow(state.volume ?? 0.8, 2);
38
+ analyser.fftSize = 1024;
39
+ analyser.smoothingTimeConstant = 0.88;
40
+ conv.buffer = this.makeImpulse(ctx, state.reverb_time, 3);
41
+ wet.gain.value = state.reverb_mix;
42
+ dry.gain.value = this.dryVal(state.reverb_mix);
43
+
44
+ conv.connect(wet);
45
+ dry.connect(analyser);
46
+ wet.connect(analyser);
47
+ analyser.connect(master);
48
+ master.connect(ctx.destination);
49
+
50
+ this._ctx = ctx;
51
+ this._master = master;
52
+ this._analyser = analyser;
53
+ this._conv = conv;
54
+ this._wet = wet;
55
+ this._dry = dry;
56
+ }
57
+
58
+ public makeImpulse(ctx: BaseAudioContext, dur: number, decay: number): AudioBuffer {
59
+ const len = Math.max(1, Math.floor(ctx.sampleRate * dur));
60
+ const buf = ctx.createBuffer(2, len, ctx.sampleRate);
61
+ for (let ch = 0; ch < 2; ch++) {
62
+ const d = buf.getChannelData(ch);
63
+ for (let i = 0; i < len; i++) {
64
+ d[i] = (Math.random() * 2 - 1) * Math.pow(1 - i / len, decay);
65
+ }
66
+ }
67
+ return buf;
68
+ }
69
+
70
+ public dryVal(mix: number): number {
71
+ return mix >= 0.99 ? 0 : 1 - mix;
72
+ }
73
+
74
+ public smooth(param: AudioParam, value: number, tau: number = 0.02): void {
75
+ if (!this._ctx || !isFinite(value)) return;
76
+ param.setTargetAtTime(value, this._ctx.currentTime, tau);
77
+ }
78
+
79
+ public async resume(): Promise<void> {
80
+ if (this._ctx instanceof AudioContext && this._ctx.state === "suspended") {
81
+ await this._ctx.resume();
82
+ }
83
+ }
84
+
85
+ public suspend(): void {
86
+ if (this._ctx instanceof AudioContext && this._ctx.state === "running") {
87
+ this._ctx.suspend().catch(() => {});
88
+ }
89
+ }
90
+
91
+ public async warmUp(state: State): Promise<void> {
92
+ this.ensure(state);
93
+ if (!(this._ctx instanceof AudioContext)) return;
94
+ await this.resume();
95
+
96
+ const osc = this._ctx.createOscillator();
97
+ const g = this._ctx.createGain();
98
+ g.gain.value = 0.00001;
99
+ osc.connect(g).connect(this._master!);
100
+ osc.start();
101
+ osc.stop(this._ctx.currentTime + 0.15);
102
+ }
103
+
104
+ public updateReverbBuffer(state: State): void {
105
+ if (!this._ctx || !this._conv) return;
106
+ this._conv.buffer = this.makeImpulse(this._ctx, state.reverb_time, 3);
107
+ }
108
+ }
@@ -0,0 +1,180 @@
1
+ import { BlockData, Point, ScaleDefinition } from "./types";
2
+ import { clamp, rgbToHsl } from "./utils";
3
+ import { SCALES } from "./constants";
4
+ import { State } from "./State";
5
+
6
+ export class ImageProcessor {
7
+ private _canvas: HTMLCanvasElement | null = null;
8
+ private _pixels: Uint8ClampedArray | null = null;
9
+ private _w: number = 0;
10
+ private _h: number = 0;
11
+
12
+ public get canvas(): HTMLCanvasElement | null {
13
+ return this._canvas;
14
+ }
15
+ public get pixels(): Uint8ClampedArray | null {
16
+ return this._pixels;
17
+ }
18
+ public get width(): number {
19
+ return this._w;
20
+ }
21
+ public get height(): number {
22
+ return this._h;
23
+ }
24
+
25
+ public processImage(img: HTMLImageElement): void {
26
+ const maxD = 2048;
27
+ const ds = Math.min(maxD / img.naturalWidth, maxD / img.naturalHeight, 1);
28
+ const dw = Math.max(1, Math.floor(img.naturalWidth * ds));
29
+ const dh = Math.max(1, Math.floor(img.naturalHeight * ds));
30
+ const cv = document.createElement("canvas");
31
+ cv.width = dw;
32
+ cv.height = dh;
33
+ const cx = cv.getContext("2d")!;
34
+ cx.imageSmoothingEnabled = true;
35
+ cx.drawImage(img, 0, 0, dw, dh);
36
+ this._canvas = cv;
37
+
38
+ const maxA = 512;
39
+ const as = Math.min(maxA / img.naturalWidth, maxA / img.naturalHeight, 1);
40
+ const aw = Math.max(1, Math.floor(img.naturalWidth * as));
41
+ const ah = Math.max(1, Math.floor(img.naturalHeight * as));
42
+ const av = document.createElement("canvas");
43
+ av.width = aw;
44
+ av.height = ah;
45
+ const ax = av.getContext("2d", { willReadFrequently: true })!;
46
+ ax.imageSmoothingEnabled = true;
47
+ ax.drawImage(img, 0, 0, aw, ah);
48
+
49
+ const px = ax.getImageData(0, 0, aw, ah);
50
+ this._pixels = px.data;
51
+ this._w = aw;
52
+ this._h = ah;
53
+ }
54
+
55
+ public loadDefault(src: string, onLoad: (img: HTMLImageElement) => void): void {
56
+ const img = new Image();
57
+ img.onload = () => onLoad(img);
58
+ img.onerror = () => {};
59
+ img.src = src;
60
+ }
61
+ }
62
+
63
+ export class BlockGrid {
64
+ private _list: BlockData[] = [];
65
+ private _cols: number = 0;
66
+ private _rows: number = 0;
67
+ private _spiralPath: Point[] = [];
68
+
69
+ public get list(): BlockData[] {
70
+ return this._list;
71
+ }
72
+ public get cols(): number {
73
+ return this._cols;
74
+ }
75
+ public get rows(): number {
76
+ return this._rows;
77
+ }
78
+ public get spiralPath(): Point[] {
79
+ return this._spiralPath;
80
+ }
81
+
82
+ public build(imageProcessor: ImageProcessor, state: State): void {
83
+ this._list = [];
84
+ this._cols = 0;
85
+ this._rows = 0;
86
+
87
+ if (!imageProcessor.pixels) return;
88
+
89
+ const sc: ScaleDefinition = state.scale ?? SCALES[0];
90
+ const bw = Math.max(1, Math.floor(state.block_w));
91
+ const bh = Math.max(1, Math.floor(state.block_h));
92
+ const cols = Math.max(1, Math.floor(imageProcessor.width / bw));
93
+ const rows = Math.max(1, Math.floor(imageProcessor.height / bh));
94
+ this._cols = cols;
95
+ this._rows = rows;
96
+
97
+ const nDeg = sc.intervals.length - 1;
98
+ const pixels = imageProcessor.pixels;
99
+ const imgW = imageProcessor.width;
100
+
101
+ for (let ry = 0; ry < rows; ry++) {
102
+ for (let rx = 0; rx < cols; rx++) {
103
+ const x0 = rx * bw;
104
+ const y0 = ry * bh;
105
+ const x1 = Math.min(x0 + bw, imageProcessor.width);
106
+ const y1 = Math.min(y0 + bh, imageProcessor.height);
107
+ let rs = 0,
108
+ gs = 0,
109
+ bs = 0,
110
+ n = 0;
111
+
112
+ for (let y = y0; y < y1; y++) {
113
+ for (let x = x0; x < x1; x++) {
114
+ const i = (y * imgW + x) * 4;
115
+ rs += pixels[i];
116
+ gs += pixels[i + 1];
117
+ bs += pixels[i + 2];
118
+ n++;
119
+ }
120
+ }
121
+
122
+ if (n === 0) continue;
123
+
124
+ const { h, s_hsv, l } = rgbToHsl(rs / n, gs / n, bs / n);
125
+ const safeH = isFinite(h) ? h : 0;
126
+ const degree = clamp(
127
+ Math.floor(Math.sqrt(safeH / 360) * nDeg),
128
+ 0,
129
+ nDeg,
130
+ );
131
+ const oct = Math.floor((l / 100) * 3) - 1;
132
+ const vel = clamp(0.2 + (l / 100) * 0.5 + s_hsv * 0.3, 0.1, 1);
133
+ const pan = (safeH / 360) * 2 - 1;
134
+ this._list.push({ degree, oct, vel, l, pan });
135
+ }
136
+ }
137
+
138
+ this._spiralPath = this.buildSpiralPath(cols, rows);
139
+ }
140
+
141
+ private buildSpiralPath(cols: number, rows: number): Point[] {
142
+ const cx = Math.floor(cols / 2);
143
+ const cy = Math.floor(rows / 2);
144
+ const path: Point[] = [];
145
+ const visited = new Set<string>();
146
+ let x = cx,
147
+ y = cy;
148
+ let step = 1,
149
+ dir = 0;
150
+ const ddx = [1, 0, -1, 0];
151
+ const ddy = [0, 1, 0, -1];
152
+
153
+ while (path.length < cols * rows) {
154
+ for (let leg = 0; leg < 2; leg++) {
155
+ for (let i = 0; i < step; i++) {
156
+ const key = `${x},${y}`;
157
+ if (x >= 0 && x < cols && y >= 0 && y < rows && !visited.has(key)) {
158
+ path.push({ x, y });
159
+ visited.add(key);
160
+ }
161
+ x += ddx[dir];
162
+ y += ddy[dir];
163
+ }
164
+ dir = (dir + 1) % 4;
165
+ }
166
+ step++;
167
+ if (path.length >= cols * rows) break;
168
+ }
169
+
170
+ if (path.length < cols * rows) {
171
+ for (let fy = 0; fy < rows; fy++) {
172
+ for (let fx = 0; fx < cols; fx++) {
173
+ if (!visited.has(`${fx},${fy}`)) path.push({ x: fx, y: fy });
174
+ }
175
+ }
176
+ }
177
+
178
+ return path;
179
+ }
180
+ }