@libraz/libsonare 1.0.4 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,3670 @@
1
+ /**
2
+ * sonare - Audio Analysis Library
3
+ *
4
+ * @example
5
+ * ```typescript
6
+ * import { init, detectBpm, detectKey, analyze } from '@libraz/sonare';
7
+ *
8
+ * await init();
9
+ *
10
+ * // Detect BPM from audio samples
11
+ * const bpm = detectBpm(samples, sampleRate);
12
+ *
13
+ * // Detect musical key
14
+ * const key = detectKey(samples, sampleRate);
15
+ *
16
+ * // Full analysis
17
+ * const result = analyze(samples, sampleRate);
18
+ * ```
19
+ */
20
+
21
+ import type {
22
+ AcousticResult,
23
+ AnalysisResult,
24
+ AutomationCurve,
25
+ ChordAnalysisResult,
26
+ ChordDetectionOptions,
27
+ ChordQuality,
28
+ ChromaResult,
29
+ CqtResult,
30
+ EqBand,
31
+ EqMatchOptions,
32
+ EqSpectrumSnapshot,
33
+ GoniometerPoint,
34
+ HpssResult,
35
+ Key,
36
+ KeyCandidate,
37
+ KeyDetectionOptions,
38
+ KeyProfileName,
39
+ LufsResult,
40
+ MasteringChainConfig,
41
+ MasteringChainResult,
42
+ MasteringPreset,
43
+ MasteringProcessorParams,
44
+ MasteringResult,
45
+ MasteringStereoChainResult,
46
+ MasteringStereoResult,
47
+ MelodyResult,
48
+ MelPowerResult,
49
+ MelSpectrogramResult,
50
+ MeterTap,
51
+ MfccResult,
52
+ MixerProcessResult,
53
+ MixMeterSnapshot,
54
+ MixOptions,
55
+ MixResult,
56
+ PairAnalysis,
57
+ PairProcessor,
58
+ PanLaw,
59
+ PitchResult,
60
+ Section,
61
+ SectionType,
62
+ SendTiming,
63
+ SoloProcessor,
64
+ StereoAnalysis,
65
+ StftPowerResult,
66
+ StftResult,
67
+ StreamingEqualizerConfig,
68
+ StreamingPlatform,
69
+ TempogramMode,
70
+ } from './public_types';
71
+ import { KeyProfile as KeyProfileValues, Mode, PitchClass } from './public_types';
72
+ import type {
73
+ AnalyzerStats,
74
+ FrameBuffer,
75
+ StreamConfig,
76
+ StreamFramesI16,
77
+ StreamFramesU8,
78
+ } from './stream_types';
79
+ import type {
80
+ ProgressCallback,
81
+ SonareModule,
82
+ WasmAcousticResult,
83
+ WasmAnalysisResult,
84
+ WasmChordAnalysisResult,
85
+ WasmCyclicTempogramResult,
86
+ WasmEngineAutomationPoint,
87
+ WasmEngineBounceOptions,
88
+ WasmEngineBounceResult,
89
+ WasmEngineCaptureStatus,
90
+ WasmEngineClip,
91
+ WasmEngineFreezeOptions,
92
+ WasmEngineFreezeResult,
93
+ WasmEngineGraphSpec,
94
+ WasmEngineMarker,
95
+ WasmEngineMeterTelemetry,
96
+ WasmEngineMetronomeConfig,
97
+ WasmEngineParameterInfo,
98
+ WasmEngineProcessWithMonitorResult,
99
+ WasmEngineTelemetry,
100
+ WasmEngineTransportState,
101
+ WasmFourierTempogramResult,
102
+ WasmFrameResult,
103
+ WasmKeyCandidateResult,
104
+ WasmNnlsChromaResult,
105
+ WasmRealtimeEngine,
106
+ WasmStreamAnalyzer,
107
+ WasmTempogramResult,
108
+ WasmTrimResult,
109
+ } from './wasm_types';
110
+
111
+ export type {
112
+ AcousticResult,
113
+ AnalysisResult,
114
+ AutomationCurve,
115
+ Beat,
116
+ Chord,
117
+ ChordAnalysisResult,
118
+ ChordDetectionOptions,
119
+ ChromaResult,
120
+ CqtResult,
121
+ Dynamics,
122
+ EqBand,
123
+ EqBandPhase,
124
+ EqBandType,
125
+ EqCoeffMode,
126
+ EqMatchOptions,
127
+ EqSpectrumSnapshot,
128
+ EqStereoPlacement,
129
+ GoniometerPoint,
130
+ HpssResult,
131
+ Key,
132
+ KeyCandidate,
133
+ KeyDetectionOptions,
134
+ KeyProfileName,
135
+ LufsResult,
136
+ MasteringChainConfig,
137
+ MasteringChainResult,
138
+ MasteringPreset,
139
+ MasteringProcessorParams,
140
+ MasteringResult,
141
+ MasteringStereoChainResult,
142
+ MasteringStereoResult,
143
+ MelodyPoint,
144
+ MelodyResult,
145
+ MelSpectrogramResult,
146
+ MeterTap,
147
+ MfccResult,
148
+ MixerProcessResult,
149
+ MixMeterSnapshot,
150
+ MixOptions,
151
+ MixResult,
152
+ PairAnalysis,
153
+ PairProcessor,
154
+ PanLaw,
155
+ PanMode,
156
+ PitchResult,
157
+ RhythmFeatures,
158
+ Section,
159
+ SendTiming,
160
+ SoloProcessor,
161
+ StereoAnalysis,
162
+ StftResult,
163
+ StreamingEqualizerConfig,
164
+ StreamingPlatform,
165
+ Timbre,
166
+ TimeSignature,
167
+ } from './public_types';
168
+ export {
169
+ ChordQuality,
170
+ KeyProfile,
171
+ Mode,
172
+ PitchClass,
173
+ SectionType,
174
+ } from './public_types';
175
+ export type {
176
+ AnalyzerStats,
177
+ BarChord,
178
+ ChordChange,
179
+ FrameBuffer,
180
+ PatternScore,
181
+ ProgressiveEstimate,
182
+ StreamConfig,
183
+ StreamFramesI16,
184
+ StreamFramesU8,
185
+ } from './stream_types';
186
+ export type { ProgressCallback } from './wasm_types';
187
+
188
+ export type EngineClip = WasmEngineClip;
189
+ export type EngineParameterInfo = WasmEngineParameterInfo;
190
+ export type EngineAutomationPoint = WasmEngineAutomationPoint;
191
+ export type EngineMarker = WasmEngineMarker;
192
+ export type EngineMetronomeConfig = WasmEngineMetronomeConfig;
193
+ export type EngineGraphSpec = WasmEngineGraphSpec;
194
+ export type EngineCaptureStatus = WasmEngineCaptureStatus;
195
+ export type EngineBounceOptions = WasmEngineBounceOptions;
196
+ export type EngineBounceResult = WasmEngineBounceResult;
197
+ export type EngineFreezeOptions = WasmEngineFreezeOptions;
198
+ export type EngineFreezeResult = WasmEngineFreezeResult;
199
+ export type EngineTelemetry = WasmEngineTelemetry;
200
+ export type EngineMeterTelemetry = WasmEngineMeterTelemetry;
201
+ export type EngineTransportState = WasmEngineTransportState;
202
+
203
+ export const EXPECTED_ENGINE_ABI_VERSION = 2;
204
+
205
+ export interface EngineCapabilities {
206
+ engineAbiVersion: number;
207
+ expectedEngineAbiVersion: number;
208
+ abiCompatible: boolean;
209
+ sharedArrayBuffer: boolean;
210
+ atomics: boolean;
211
+ audioWorklet: boolean;
212
+ mode: 'sab' | 'postMessage';
213
+ }
214
+
215
+ export interface MixerRealtimeBuffer {
216
+ leftInputs: Float32Array[];
217
+ rightInputs: Float32Array[];
218
+ outLeft: Float32Array;
219
+ outRight: Float32Array;
220
+ process: (numSamples?: number) => void;
221
+ }
222
+
223
+ function automationCurveCode(curve: AutomationCurve): number {
224
+ switch (curve) {
225
+ case 'linear':
226
+ return 0;
227
+ case 'exponential':
228
+ return 1;
229
+ case 'hold':
230
+ return 2;
231
+ case 's-curve':
232
+ return 3;
233
+ default:
234
+ throw new Error(`Invalid automation curve: ${curve}`);
235
+ }
236
+ }
237
+
238
+ function panLawCode(panLaw: PanLaw | number): number {
239
+ if (typeof panLaw === 'number') {
240
+ return panLaw;
241
+ }
242
+ switch (panLaw) {
243
+ case 'const4.5dB':
244
+ return 1;
245
+ case 'const6dB':
246
+ return 2;
247
+ case 'linear0dB':
248
+ return 3;
249
+ default:
250
+ return 0;
251
+ }
252
+ }
253
+
254
+ function meterTapCode(tap: MeterTap | number): number {
255
+ return tap === 'preFader' || tap === 0 ? 0 : 1;
256
+ }
257
+
258
+ function sendTimingCode(timing: SendTiming | number): number {
259
+ return timing === 'preFader' || timing === 0 ? 0 : 1;
260
+ }
261
+
262
+ // ============================================================================
263
+ // Module State
264
+ // ============================================================================
265
+
266
+ let module: SonareModule | null = null;
267
+ let initPromise: Promise<void> | null = null;
268
+
269
+ // ============================================================================
270
+ // Initialization
271
+ // ============================================================================
272
+
273
+ /**
274
+ * Initialize the WASM module.
275
+ * Must be called before using any analysis functions.
276
+ *
277
+ * @param options - Optional module configuration
278
+ * @returns Promise that resolves when initialization is complete
279
+ */
280
+ export async function init(options?: {
281
+ locateFile?: (path: string, prefix: string) => string;
282
+ }): Promise<void> {
283
+ if (module) {
284
+ return;
285
+ }
286
+
287
+ if (initPromise) {
288
+ return initPromise;
289
+ }
290
+
291
+ initPromise = (async () => {
292
+ try {
293
+ const createModule = (await import('./sonare.js')).default;
294
+ module = await createModule(options);
295
+ } catch (error) {
296
+ initPromise = null;
297
+ throw error;
298
+ }
299
+ })();
300
+
301
+ return initPromise;
302
+ }
303
+
304
+ /**
305
+ * Check if the module is initialized.
306
+ */
307
+ export function isInitialized(): boolean {
308
+ return module !== null;
309
+ }
310
+
311
+ /**
312
+ * Get the library version.
313
+ */
314
+ export function version(): string {
315
+ if (!module) {
316
+ throw new Error('Module not initialized. Call init() first.');
317
+ }
318
+ return module.version();
319
+ }
320
+
321
+ export function engineAbiVersion(): number {
322
+ if (!module) {
323
+ throw new Error('Module not initialized. Call init() first.');
324
+ }
325
+ return module.engineAbiVersion();
326
+ }
327
+
328
+ export function engineCapabilities(): EngineCapabilities {
329
+ const abiVersion = engineAbiVersion();
330
+ const sharedArrayBuffer = typeof globalThis.SharedArrayBuffer === 'function';
331
+ const atomics = typeof globalThis.Atomics === 'object';
332
+ const audioWorklet =
333
+ typeof AudioWorkletNode !== 'undefined' ||
334
+ typeof (globalThis as typeof globalThis & { AudioWorkletProcessor?: unknown })
335
+ .AudioWorkletProcessor !== 'undefined';
336
+ return {
337
+ engineAbiVersion: abiVersion,
338
+ expectedEngineAbiVersion: EXPECTED_ENGINE_ABI_VERSION,
339
+ abiCompatible: abiVersion === EXPECTED_ENGINE_ABI_VERSION,
340
+ sharedArrayBuffer,
341
+ atomics,
342
+ audioWorklet,
343
+ mode: sharedArrayBuffer && atomics ? 'sab' : 'postMessage',
344
+ };
345
+ }
346
+
347
+ export class RealtimeEngine {
348
+ private native: WasmRealtimeEngine;
349
+
350
+ constructor(
351
+ sampleRate = 48000,
352
+ maxBlockSize = 128,
353
+ commandCapacity = 1024,
354
+ telemetryCapacity = 1024,
355
+ ) {
356
+ if (!module) {
357
+ throw new Error('Module not initialized. Call init() first.');
358
+ }
359
+ const capabilities = engineCapabilities();
360
+ if (!capabilities.abiCompatible) {
361
+ throw new Error(
362
+ `Engine ABI mismatch: wasm=${capabilities.engineAbiVersion}, expected=${capabilities.expectedEngineAbiVersion}`,
363
+ );
364
+ }
365
+ this.native = new module.RealtimeEngine(
366
+ sampleRate,
367
+ maxBlockSize,
368
+ commandCapacity,
369
+ telemetryCapacity,
370
+ );
371
+ }
372
+
373
+ prepare(
374
+ sampleRate: number,
375
+ maxBlockSize: number,
376
+ commandCapacity = 1024,
377
+ telemetryCapacity = 1024,
378
+ ): void {
379
+ this.native.prepare(sampleRate, maxBlockSize, commandCapacity, telemetryCapacity);
380
+ }
381
+
382
+ /** Queue a sample-accurate parameter change (engine kSetParam). */
383
+ setParameter(paramId: number, value: number, renderFrame = -1): void {
384
+ this.native.setParameter(paramId, value, renderFrame);
385
+ }
386
+
387
+ /** Queue a smoothed parameter change (engine kSetParamSmoothed). */
388
+ setParameterSmoothed(paramId: number, value: number, renderFrame = -1): void {
389
+ this.native.setParameterSmoothed(paramId, value, renderFrame);
390
+ }
391
+
392
+ /** Read back the current transport state snapshot. */
393
+ getTransportState(): EngineTransportState {
394
+ return this.native.getTransportState();
395
+ }
396
+
397
+ play(renderFrame = -1): void {
398
+ this.native.play(renderFrame);
399
+ }
400
+
401
+ stop(renderFrame = -1): void {
402
+ this.native.stop(renderFrame);
403
+ }
404
+
405
+ seekSample(timelineSample: number, renderFrame = -1): void {
406
+ this.native.seekSample(timelineSample, renderFrame);
407
+ }
408
+
409
+ seekPpq(ppq: number, renderFrame = -1): void {
410
+ this.native.seekPpq(ppq, renderFrame);
411
+ }
412
+
413
+ setTempo(bpm: number): void {
414
+ this.native.setTempo(bpm);
415
+ }
416
+
417
+ setTimeSignature(numerator: number, denominator: number): void {
418
+ this.native.setTimeSignature(numerator, denominator);
419
+ }
420
+
421
+ setLoop(startPpq: number, endPpq: number, enabled = true): void {
422
+ this.native.setLoop(startPpq, endPpq, enabled);
423
+ }
424
+
425
+ addParameter(info: EngineParameterInfo): void {
426
+ this.native.addParameter(info);
427
+ }
428
+
429
+ parameterCount(): number {
430
+ return this.native.parameterCount();
431
+ }
432
+
433
+ parameterInfoByIndex(index: number): EngineParameterInfo {
434
+ return this.native.parameterInfoByIndex(index);
435
+ }
436
+
437
+ parameterInfo(id: number): EngineParameterInfo {
438
+ return this.native.parameterInfo(id);
439
+ }
440
+
441
+ setAutomationLane(paramId: number, points: EngineAutomationPoint[]): void {
442
+ this.native.setAutomationLane(paramId, points);
443
+ }
444
+
445
+ automationLaneCount(): number {
446
+ return this.native.automationLaneCount();
447
+ }
448
+
449
+ setMarkers(markers: EngineMarker[]): void {
450
+ this.native.setMarkers(markers);
451
+ }
452
+
453
+ markerCount(): number {
454
+ return this.native.markerCount();
455
+ }
456
+
457
+ markerByIndex(index: number): EngineMarker {
458
+ return this.native.markerByIndex(index);
459
+ }
460
+
461
+ marker(id: number): EngineMarker {
462
+ return this.native.marker(id);
463
+ }
464
+
465
+ seekMarker(markerId: number, renderFrame = -1): void {
466
+ this.native.seekMarker(markerId, renderFrame);
467
+ }
468
+
469
+ setLoopFromMarkers(startMarkerId: number, endMarkerId: number): void {
470
+ this.native.setLoopFromMarkers(startMarkerId, endMarkerId);
471
+ }
472
+
473
+ setMetronome(config: EngineMetronomeConfig): void {
474
+ this.native.setMetronome(config);
475
+ }
476
+
477
+ metronome(): Required<EngineMetronomeConfig> {
478
+ return this.native.metronome();
479
+ }
480
+
481
+ countInEndSample(startSample: number, bars: number): number {
482
+ return Number(this.native.countInEndSample(startSample, bars));
483
+ }
484
+
485
+ setGraph(spec: EngineGraphSpec): void {
486
+ this.native.setGraph(spec);
487
+ }
488
+
489
+ graphNodeCount(): number {
490
+ return this.native.graphNodeCount();
491
+ }
492
+
493
+ graphConnectionCount(): number {
494
+ return this.native.graphConnectionCount();
495
+ }
496
+
497
+ setClips(clips: EngineClip[]): void {
498
+ this.native.setClips(clips);
499
+ }
500
+
501
+ clipCount(): number {
502
+ return this.native.clipCount();
503
+ }
504
+
505
+ setCaptureBuffer(numChannels: number, capacityFrames: number): void {
506
+ this.native.setCaptureBuffer(numChannels, capacityFrames);
507
+ }
508
+
509
+ armCapture(armed = true): void {
510
+ this.native.armCapture(armed);
511
+ }
512
+
513
+ setCapturePunch(startSample: number, endSample: number, enabled = true): void {
514
+ this.native.setCapturePunch(startSample, endSample, enabled);
515
+ }
516
+
517
+ resetCapture(): void {
518
+ this.native.resetCapture();
519
+ }
520
+
521
+ captureStatus(): EngineCaptureStatus {
522
+ return this.native.captureStatus();
523
+ }
524
+
525
+ capturedAudio(): Float32Array[] {
526
+ return this.native.capturedAudio();
527
+ }
528
+
529
+ process(channels: Float32Array[]): Float32Array[] {
530
+ return this.native.process(channels);
531
+ }
532
+
533
+ processWithMonitor(channels: Float32Array[]): WasmEngineProcessWithMonitorResult {
534
+ return this.native.processWithMonitor(channels);
535
+ }
536
+
537
+ renderOffline(channels: Float32Array[], blockSize = 128): Float32Array[] {
538
+ return this.native.renderOffline(channels, blockSize);
539
+ }
540
+
541
+ bounceOffline(options: EngineBounceOptions): EngineBounceResult {
542
+ return this.native.bounceOffline(options);
543
+ }
544
+
545
+ freezeOffline(options: EngineFreezeOptions): EngineFreezeResult {
546
+ return this.native.freezeOffline(options);
547
+ }
548
+
549
+ drainTelemetry(maxRecords = 1024): EngineTelemetry[] {
550
+ return this.native.drainTelemetry(maxRecords);
551
+ }
552
+
553
+ drainMeterTelemetry(maxRecords = 1024): EngineMeterTelemetry[] {
554
+ return this.native.drainMeterTelemetry(maxRecords);
555
+ }
556
+
557
+ destroy(): void {
558
+ this.native.delete();
559
+ }
560
+ }
561
+
562
+ // ============================================================================
563
+ // Quick API (High-level Analysis)
564
+ // ============================================================================
565
+
566
+ /**
567
+ * Detect BPM from audio samples.
568
+ *
569
+ * @param samples - Audio samples (mono, float32)
570
+ * @param sampleRate - Sample rate in Hz
571
+ * @returns Detected BPM
572
+ */
573
+ export function detectBpm(samples: Float32Array, sampleRate: number): number {
574
+ if (!module) {
575
+ throw new Error('Module not initialized. Call init() first.');
576
+ }
577
+ return module.detectBpm(samples, sampleRate);
578
+ }
579
+
580
+ /**
581
+ * Detect musical key from audio samples.
582
+ *
583
+ * @param samples - Audio samples (mono, float32)
584
+ * @param sampleRate - Sample rate in Hz
585
+ * @returns Detected key
586
+ */
587
+ export function detectKey(
588
+ samples: Float32Array,
589
+ sampleRate: number,
590
+ options: KeyDetectionOptions = {},
591
+ ): Key {
592
+ if (!module) {
593
+ throw new Error('Module not initialized. Call init() first.');
594
+ }
595
+ const result = module._detectKeyWithOptions(
596
+ samples,
597
+ sampleRate,
598
+ options.nFft ?? 4096,
599
+ options.hopLength ?? 512,
600
+ options.useHpss ?? false,
601
+ options.loudnessWeighted ?? false,
602
+ options.highPassHz ?? 0,
603
+ keyModeValues(options.modes),
604
+ keyProfileValue(options.profile),
605
+ options.genreHint ?? '',
606
+ );
607
+ return {
608
+ root: result.root as PitchClass,
609
+ mode: result.mode as Mode,
610
+ confidence: result.confidence,
611
+ name: result.name,
612
+ shortName: result.shortName,
613
+ };
614
+ }
615
+
616
+ function convertKeyCandidate(wasm: WasmKeyCandidateResult): KeyCandidate {
617
+ return {
618
+ key: {
619
+ root: wasm.key.root as PitchClass,
620
+ mode: wasm.key.mode as Mode,
621
+ confidence: wasm.key.confidence,
622
+ name: wasm.key.name,
623
+ shortName: wasm.key.shortName,
624
+ },
625
+ correlation: wasm.correlation,
626
+ };
627
+ }
628
+
629
+ function keyModeValues(modes: KeyDetectionOptions['modes'] | undefined): number[] {
630
+ if (!modes) {
631
+ return [];
632
+ }
633
+ if (modes === 'major-minor') {
634
+ return [Mode.Major, Mode.Minor];
635
+ }
636
+ if (modes === 'all' || modes === 'modal') {
637
+ return [
638
+ Mode.Major,
639
+ Mode.Minor,
640
+ Mode.Dorian,
641
+ Mode.Phrygian,
642
+ Mode.Lydian,
643
+ Mode.Mixolydian,
644
+ Mode.Locrian,
645
+ ];
646
+ }
647
+ const names = {
648
+ major: Mode.Major,
649
+ minor: Mode.Minor,
650
+ dorian: Mode.Dorian,
651
+ phrygian: Mode.Phrygian,
652
+ lydian: Mode.Lydian,
653
+ mixolydian: Mode.Mixolydian,
654
+ locrian: Mode.Locrian,
655
+ } as const;
656
+ return modes.map((mode) => (typeof mode === 'number' ? mode : names[mode]));
657
+ }
658
+
659
+ function keyProfileValue(profile: KeyDetectionOptions['profile'] | undefined): number {
660
+ if (profile === undefined) {
661
+ return -1;
662
+ }
663
+ if (typeof profile === 'number') {
664
+ return profile;
665
+ }
666
+ const names: Record<KeyProfileName, number> = {
667
+ ks: KeyProfileValues.KrumhanslSchmuckler,
668
+ krumhansl: KeyProfileValues.KrumhanslSchmuckler,
669
+ temperley: KeyProfileValues.Temperley,
670
+ shaath: KeyProfileValues.Shaath,
671
+ keyfinder: KeyProfileValues.Shaath,
672
+ 'faraldo-edmt': KeyProfileValues.FaraldoEDMT,
673
+ edmt: KeyProfileValues.FaraldoEDMT,
674
+ 'faraldo-edma': KeyProfileValues.FaraldoEDMA,
675
+ edma: KeyProfileValues.FaraldoEDMA,
676
+ 'faraldo-edmm': KeyProfileValues.FaraldoEDMM,
677
+ edmm: KeyProfileValues.FaraldoEDMM,
678
+ 'bellman-budge': KeyProfileValues.BellmanBudge,
679
+ bellman: KeyProfileValues.BellmanBudge,
680
+ };
681
+ return names[profile];
682
+ }
683
+
684
+ export function detectKeyCandidates(
685
+ samples: Float32Array,
686
+ sampleRate: number,
687
+ options: KeyDetectionOptions = {},
688
+ ): KeyCandidate[] {
689
+ if (!module) {
690
+ throw new Error('Module not initialized. Call init() first.');
691
+ }
692
+ return module
693
+ ._detectKeyCandidates(
694
+ samples,
695
+ sampleRate,
696
+ options.nFft ?? 4096,
697
+ options.hopLength ?? 512,
698
+ options.useHpss ?? false,
699
+ options.loudnessWeighted ?? false,
700
+ options.highPassHz ?? 0,
701
+ keyModeValues(options.modes),
702
+ keyProfileValue(options.profile),
703
+ options.genreHint ?? '',
704
+ )
705
+ .map(convertKeyCandidate);
706
+ }
707
+
708
+ /**
709
+ * Detect onset times from audio samples.
710
+ *
711
+ * @param samples - Audio samples (mono, float32)
712
+ * @param sampleRate - Sample rate in Hz
713
+ * @returns Array of onset times in seconds
714
+ */
715
+ export function detectOnsets(samples: Float32Array, sampleRate: number): Float32Array {
716
+ if (!module) {
717
+ throw new Error('Module not initialized. Call init() first.');
718
+ }
719
+ return module.detectOnsets(samples, sampleRate);
720
+ }
721
+
722
+ /**
723
+ * Detect beat times from audio samples.
724
+ *
725
+ * @param samples - Audio samples (mono, float32)
726
+ * @param sampleRate - Sample rate in Hz
727
+ * @returns Array of beat times in seconds
728
+ */
729
+ export function detectBeats(samples: Float32Array, sampleRate: number): Float32Array {
730
+ if (!module) {
731
+ throw new Error('Module not initialized. Call init() first.');
732
+ }
733
+ return module.detectBeats(samples, sampleRate);
734
+ }
735
+
736
+ /**
737
+ * Detect downbeat times from audio samples.
738
+ *
739
+ * @param samples - Audio samples (mono, float32)
740
+ * @param sampleRate - Sample rate in Hz
741
+ * @returns Array of downbeat times in seconds
742
+ */
743
+ export function detectDownbeats(samples: Float32Array, sampleRate: number): Float32Array {
744
+ if (!module) {
745
+ throw new Error('Module not initialized. Call init() first.');
746
+ }
747
+ return module.detectDownbeats(samples, sampleRate);
748
+ }
749
+
750
+ function convertChordAnalysisResult(wasm: WasmChordAnalysisResult): ChordAnalysisResult {
751
+ return {
752
+ chords: wasm.chords.map((c) => ({
753
+ root: c.root as PitchClass,
754
+ bass: c.bass as PitchClass,
755
+ quality: c.quality as ChordQuality,
756
+ start: c.start,
757
+ end: c.end,
758
+ confidence: c.confidence,
759
+ name: c.name,
760
+ })),
761
+ };
762
+ }
763
+
764
+ /**
765
+ * Detect chords from audio samples.
766
+ *
767
+ * @param samples - Audio samples (mono, float32)
768
+ * @param sampleRate - Sample rate in Hz
769
+ * @param options - Optional chord detection settings
770
+ * @returns Detected chord segments
771
+ */
772
+ export function detectChords(
773
+ samples: Float32Array,
774
+ sampleRate: number,
775
+ options: ChordDetectionOptions = {},
776
+ ): ChordAnalysisResult {
777
+ if (!module) {
778
+ throw new Error('Module not initialized. Call init() first.');
779
+ }
780
+ const result = module.detectChords(
781
+ samples,
782
+ sampleRate,
783
+ options.minDuration ?? 0.3,
784
+ options.smoothingWindow ?? 2.0,
785
+ options.threshold ?? 0.5,
786
+ options.useTriadsOnly ?? false,
787
+ options.nFft ?? 2048,
788
+ options.hopLength ?? 512,
789
+ options.useBeatSync ?? true,
790
+ options.useHmm ?? false,
791
+ options.hmmBeamWidth ?? 24,
792
+ options.useKeyContext ?? false,
793
+ options.keyRoot ?? PitchClass.C,
794
+ options.keyMode ?? Mode.Major,
795
+ options.detectInversions ?? false,
796
+ chordChromaMethodValue(options.chromaMethod ?? 'stft'),
797
+ );
798
+ return convertChordAnalysisResult(result);
799
+ }
800
+
801
+ function chordChromaMethodValue(method: 'stft' | 'nnls'): number {
802
+ if (method === 'stft') {
803
+ return 0;
804
+ }
805
+ if (method === 'nnls') {
806
+ return 1;
807
+ }
808
+ throw new Error(`Invalid chord chroma method: ${method}`);
809
+ }
810
+
811
+ // Helper to convert WASM result to typed result
812
+ function convertAnalysisResult(wasm: WasmAnalysisResult): AnalysisResult {
813
+ const beatTimes = new Float32Array(wasm.beats.length);
814
+ for (let i = 0; i < wasm.beats.length; i++) {
815
+ beatTimes[i] = wasm.beats[i].time;
816
+ }
817
+ return {
818
+ bpm: wasm.bpm,
819
+ bpmConfidence: wasm.bpmConfidence,
820
+ key: {
821
+ root: wasm.key.root as PitchClass,
822
+ mode: wasm.key.mode as Mode,
823
+ confidence: wasm.key.confidence,
824
+ name: wasm.key.name,
825
+ shortName: wasm.key.shortName,
826
+ },
827
+ timeSignature: wasm.timeSignature,
828
+ beatTimes,
829
+ beats: wasm.beats,
830
+ chords: wasm.chords.map((c) => ({
831
+ root: c.root as PitchClass,
832
+ bass: c.bass as PitchClass,
833
+ quality: c.quality as ChordQuality,
834
+ start: c.start,
835
+ end: c.end,
836
+ confidence: c.confidence,
837
+ name: c.name,
838
+ })),
839
+ sections: wasm.sections.map((s) => ({
840
+ type: s.type as SectionType,
841
+ start: s.start,
842
+ end: s.end,
843
+ energyLevel: s.energyLevel,
844
+ confidence: s.confidence,
845
+ name: s.name,
846
+ })),
847
+ timbre: wasm.timbre,
848
+ dynamics: wasm.dynamics,
849
+ rhythm: wasm.rhythm,
850
+ form: wasm.form,
851
+ };
852
+ }
853
+
854
+ /**
855
+ * Perform complete music analysis.
856
+ *
857
+ * @param samples - Audio samples (mono, float32)
858
+ * @param sampleRate - Sample rate in Hz
859
+ * @returns Complete analysis result
860
+ */
861
+ export function analyze(samples: Float32Array, sampleRate: number): AnalysisResult {
862
+ if (!module) {
863
+ throw new Error('Module not initialized. Call init() first.');
864
+ }
865
+ const result = module.analyze(samples, sampleRate);
866
+ return convertAnalysisResult(result);
867
+ }
868
+
869
+ export function analyzeImpulseResponse(
870
+ samples: Float32Array,
871
+ sampleRate: number,
872
+ nOctaveBands = 6,
873
+ ): AcousticResult {
874
+ if (!module) {
875
+ throw new Error('Module not initialized. Call init() first.');
876
+ }
877
+ const result: WasmAcousticResult = module.analyzeImpulseResponse(
878
+ samples,
879
+ sampleRate,
880
+ nOctaveBands,
881
+ );
882
+ return result;
883
+ }
884
+
885
+ export function detectAcoustic(
886
+ samples: Float32Array,
887
+ sampleRate: number,
888
+ nOctaveBands = 6,
889
+ nThirdOctaveSubbands = 24,
890
+ minDecayDb = 30.0,
891
+ noiseFloorMarginDb = 10.0,
892
+ ): AcousticResult {
893
+ if (!module) {
894
+ throw new Error('Module not initialized. Call init() first.');
895
+ }
896
+ const result: WasmAcousticResult = module.detectAcoustic(
897
+ samples,
898
+ sampleRate,
899
+ nOctaveBands,
900
+ nThirdOctaveSubbands,
901
+ minDecayDb,
902
+ noiseFloorMarginDb,
903
+ );
904
+ return result;
905
+ }
906
+
907
+ /**
908
+ * Perform complete music analysis with progress reporting.
909
+ *
910
+ * @param samples - Audio samples (mono, float32)
911
+ * @param sampleRate - Sample rate in Hz
912
+ * @param onProgress - Progress callback (progress: 0-1, stage: string)
913
+ * @returns Complete analysis result
914
+ */
915
+ export function analyzeWithProgress(
916
+ samples: Float32Array,
917
+ sampleRate: number,
918
+ onProgress: ProgressCallback,
919
+ ): AnalysisResult {
920
+ if (!module) {
921
+ throw new Error('Module not initialized. Call init() first.');
922
+ }
923
+ const result = module.analyzeWithProgress(samples, sampleRate, onProgress);
924
+ return convertAnalysisResult(result);
925
+ }
926
+
927
+ // ============================================================================
928
+ // Effects
929
+ // ============================================================================
930
+
931
+ /**
932
+ * Perform Harmonic-Percussive Source Separation (HPSS).
933
+ *
934
+ * @param samples - Audio samples (mono, float32)
935
+ * @param sampleRate - Sample rate in Hz
936
+ * @param kernelHarmonic - Horizontal median filter size for harmonic (default: 31)
937
+ * @param kernelPercussive - Vertical median filter size for percussive (default: 31)
938
+ * @returns Separated harmonic and percussive components
939
+ */
940
+ export function hpss(
941
+ samples: Float32Array,
942
+ sampleRate: number,
943
+ kernelHarmonic = 31,
944
+ kernelPercussive = 31,
945
+ ): HpssResult {
946
+ if (!module) {
947
+ throw new Error('Module not initialized. Call init() first.');
948
+ }
949
+ return module.hpss(samples, sampleRate, kernelHarmonic, kernelPercussive);
950
+ }
951
+
952
+ /**
953
+ * Extract harmonic component from audio.
954
+ *
955
+ * @param samples - Audio samples (mono, float32)
956
+ * @param sampleRate - Sample rate in Hz
957
+ * @returns Harmonic component
958
+ */
959
+ export function harmonic(samples: Float32Array, sampleRate: number): Float32Array {
960
+ if (!module) {
961
+ throw new Error('Module not initialized. Call init() first.');
962
+ }
963
+ return module.harmonic(samples, sampleRate);
964
+ }
965
+
966
+ /**
967
+ * Extract percussive component from audio.
968
+ *
969
+ * @param samples - Audio samples (mono, float32)
970
+ * @param sampleRate - Sample rate in Hz
971
+ * @returns Percussive component
972
+ */
973
+ export function percussive(samples: Float32Array, sampleRate: number): Float32Array {
974
+ if (!module) {
975
+ throw new Error('Module not initialized. Call init() first.');
976
+ }
977
+ return module.percussive(samples, sampleRate);
978
+ }
979
+
980
+ /**
981
+ * Time-stretch audio without changing pitch.
982
+ *
983
+ * @param samples - Audio samples (mono, float32)
984
+ * @param sampleRate - Sample rate in Hz
985
+ * @param rate - Time stretch rate (0.5 = double duration, 2.0 = half duration)
986
+ * @returns Time-stretched audio
987
+ */
988
+ export function timeStretch(samples: Float32Array, sampleRate: number, rate: number): Float32Array {
989
+ if (!module) {
990
+ throw new Error('Module not initialized. Call init() first.');
991
+ }
992
+ return module.timeStretch(samples, sampleRate, rate);
993
+ }
994
+
995
+ /**
996
+ * Pitch-shift audio without changing duration.
997
+ *
998
+ * @param samples - Audio samples (mono, float32)
999
+ * @param sampleRate - Sample rate in Hz
1000
+ * @param semitones - Pitch shift in semitones (+12 = one octave up, -12 = one octave down)
1001
+ * @returns Pitch-shifted audio
1002
+ */
1003
+ export function pitchShift(
1004
+ samples: Float32Array,
1005
+ sampleRate: number,
1006
+ semitones: number,
1007
+ ): Float32Array {
1008
+ if (!module) {
1009
+ throw new Error('Module not initialized. Call init() first.');
1010
+ }
1011
+ return module.pitchShift(samples, sampleRate, semitones);
1012
+ }
1013
+
1014
+ /**
1015
+ * Pitch-correct audio from a current MIDI note to a target MIDI note.
1016
+ *
1017
+ * @param samples - Audio samples (mono, float32)
1018
+ * @param sampleRate - Sample rate in Hz
1019
+ * @param currentMidi - Detected/current MIDI note number
1020
+ * @param targetMidi - Desired MIDI note number
1021
+ * @returns Pitch-corrected audio
1022
+ */
1023
+ export function pitchCorrectToMidi(
1024
+ samples: Float32Array,
1025
+ sampleRate: number,
1026
+ currentMidi: number,
1027
+ targetMidi: number,
1028
+ ): Float32Array {
1029
+ if (!module) {
1030
+ throw new Error('Module not initialized. Call init() first.');
1031
+ }
1032
+ return module.pitchCorrectToMidi(samples, sampleRate, currentMidi, targetMidi);
1033
+ }
1034
+
1035
+ /**
1036
+ * Time-stretch a note region between two sample offsets without changing pitch.
1037
+ *
1038
+ * @param samples - Audio samples (mono, float32)
1039
+ * @param sampleRate - Sample rate in Hz
1040
+ * @param onsetSample - Note onset position in samples
1041
+ * @param offsetSample - Note offset position in samples
1042
+ * @param stretchRatio - Stretch ratio (0.5 = double duration, 2.0 = half duration)
1043
+ * @returns Audio with the note region stretched
1044
+ */
1045
+ export function noteStretch(
1046
+ samples: Float32Array,
1047
+ sampleRate: number,
1048
+ onsetSample: number,
1049
+ offsetSample: number,
1050
+ stretchRatio: number,
1051
+ ): Float32Array {
1052
+ if (!module) {
1053
+ throw new Error('Module not initialized. Call init() first.');
1054
+ }
1055
+ return module.noteStretch(samples, sampleRate, onsetSample, offsetSample, stretchRatio);
1056
+ }
1057
+
1058
+ /**
1059
+ * Apply a voice change by shifting pitch and formants independently.
1060
+ *
1061
+ * @param samples - Audio samples (mono, float32)
1062
+ * @param sampleRate - Sample rate in Hz
1063
+ * @param pitchSemitones - Pitch shift in semitones
1064
+ * @param formantFactor - Formant scaling factor (1.0 = unchanged)
1065
+ * @returns Voice-changed audio
1066
+ */
1067
+ export function voiceChange(
1068
+ samples: Float32Array,
1069
+ sampleRate: number,
1070
+ pitchSemitones: number,
1071
+ formantFactor: number,
1072
+ ): Float32Array {
1073
+ if (!module) {
1074
+ throw new Error('Module not initialized. Call init() first.');
1075
+ }
1076
+ return module.voiceChange(samples, sampleRate, pitchSemitones, formantFactor);
1077
+ }
1078
+
1079
+ /**
1080
+ * Normalize audio to target peak level.
1081
+ *
1082
+ * @param samples - Audio samples (mono, float32)
1083
+ * @param sampleRate - Sample rate in Hz
1084
+ * @param targetDb - Target peak level in dB (default: 0 dB = full scale)
1085
+ * @returns Normalized audio
1086
+ */
1087
+ export function normalize(samples: Float32Array, sampleRate: number, targetDb = 0.0): Float32Array {
1088
+ if (!module) {
1089
+ throw new Error('Module not initialized. Call init() first.');
1090
+ }
1091
+ return module.normalize(samples, sampleRate, targetDb);
1092
+ }
1093
+
1094
+ /**
1095
+ * Apply mastering loudness normalization with a true-peak ceiling.
1096
+ *
1097
+ * @param samples - Audio samples (mono, float32)
1098
+ * @param sampleRate - Sample rate in Hz
1099
+ * @param targetLufs - Target integrated LUFS (default: -14)
1100
+ * @param ceilingDb - True/sample peak ceiling in dBFS (default: -1)
1101
+ * @param truePeakOversample - Oversampling factor used for peak estimation
1102
+ * @returns Processed audio and loudness metadata
1103
+ */
1104
+ export function mastering(
1105
+ samples: Float32Array,
1106
+ sampleRate: number,
1107
+ targetLufs = -14.0,
1108
+ ceilingDb = -1.0,
1109
+ truePeakOversample = 4,
1110
+ ): MasteringResult {
1111
+ if (!module) {
1112
+ throw new Error('Module not initialized. Call init() first.');
1113
+ }
1114
+ return module.mastering(samples, sampleRate, targetLufs, ceilingDb, truePeakOversample);
1115
+ }
1116
+
1117
+ export function masteringProcessorNames(): SoloProcessor[] {
1118
+ if (!module) {
1119
+ throw new Error('Module not initialized. Call init() first.');
1120
+ }
1121
+ return module.masteringProcessorNames() as SoloProcessor[];
1122
+ }
1123
+
1124
+ export function masteringPairProcessorNames(): PairProcessor[] {
1125
+ if (!module) {
1126
+ throw new Error('Module not initialized. Call init() first.');
1127
+ }
1128
+ return module.masteringPairProcessorNames() as PairProcessor[];
1129
+ }
1130
+
1131
+ export function masteringPairAnalysisNames(): PairAnalysis[] {
1132
+ if (!module) {
1133
+ throw new Error('Module not initialized. Call init() first.');
1134
+ }
1135
+ return module.masteringPairAnalysisNames() as PairAnalysis[];
1136
+ }
1137
+
1138
+ export function masteringStereoAnalysisNames(): StereoAnalysis[] {
1139
+ if (!module) {
1140
+ throw new Error('Module not initialized. Call init() first.');
1141
+ }
1142
+ return module.masteringStereoAnalysisNames() as StereoAnalysis[];
1143
+ }
1144
+
1145
+ export function masteringProcess(
1146
+ processorName: SoloProcessor,
1147
+ samples: Float32Array,
1148
+ sampleRate: number,
1149
+ params: MasteringProcessorParams = {},
1150
+ ): MasteringResult {
1151
+ if (!module) {
1152
+ throw new Error('Module not initialized. Call init() first.');
1153
+ }
1154
+ return module.masteringProcess(processorName, samples, sampleRate, params);
1155
+ }
1156
+
1157
+ export function masteringProcessStereo(
1158
+ processorName: SoloProcessor,
1159
+ left: Float32Array,
1160
+ right: Float32Array,
1161
+ sampleRate: number,
1162
+ params: MasteringProcessorParams = {},
1163
+ ): MasteringStereoResult {
1164
+ if (!module) {
1165
+ throw new Error('Module not initialized. Call init() first.');
1166
+ }
1167
+ if (left.length !== right.length) {
1168
+ throw new Error('Stereo channel lengths must match.');
1169
+ }
1170
+ return module.masteringProcessStereo(processorName, left, right, sampleRate, params);
1171
+ }
1172
+
1173
+ export function masteringPairProcess(
1174
+ processorName: PairProcessor,
1175
+ source: Float32Array,
1176
+ reference: Float32Array,
1177
+ sampleRate: number,
1178
+ params: MasteringProcessorParams = {},
1179
+ ): MasteringResult {
1180
+ if (!module) {
1181
+ throw new Error('Module not initialized. Call init() first.');
1182
+ }
1183
+ return module.masteringPairProcess(processorName, source, reference, sampleRate, params);
1184
+ }
1185
+
1186
+ export function masteringPairAnalyze(
1187
+ analysisName: PairAnalysis,
1188
+ source: Float32Array,
1189
+ reference: Float32Array,
1190
+ sampleRate: number,
1191
+ params: MasteringProcessorParams = {},
1192
+ ): string {
1193
+ if (!module) {
1194
+ throw new Error('Module not initialized. Call init() first.');
1195
+ }
1196
+ return module.masteringPairAnalyze(analysisName, source, reference, sampleRate, params);
1197
+ }
1198
+
1199
+ export function masteringStereoAnalyze(
1200
+ analysisName: StereoAnalysis,
1201
+ left: Float32Array,
1202
+ right: Float32Array,
1203
+ sampleRate: number,
1204
+ params: MasteringProcessorParams = {},
1205
+ ): string {
1206
+ if (!module) {
1207
+ throw new Error('Module not initialized. Call init() first.');
1208
+ }
1209
+ return module.masteringStereoAnalyze(analysisName, left, right, sampleRate, params);
1210
+ }
1211
+
1212
+ export function masteringAssistantSuggest(
1213
+ samples: Float32Array,
1214
+ sampleRate: number,
1215
+ params: MasteringProcessorParams = {},
1216
+ ): string {
1217
+ if (!module) {
1218
+ throw new Error('Module not initialized. Call init() first.');
1219
+ }
1220
+ return module.masteringAssistantSuggest(samples, sampleRate, params);
1221
+ }
1222
+
1223
+ export function masteringAudioProfile(
1224
+ samples: Float32Array,
1225
+ sampleRate: number,
1226
+ params: MasteringProcessorParams = {},
1227
+ ): string {
1228
+ if (!module) {
1229
+ throw new Error('Module not initialized. Call init() first.');
1230
+ }
1231
+ return module.masteringAudioProfile(samples, sampleRate, params);
1232
+ }
1233
+
1234
+ export function masteringStreamingPreview(
1235
+ samples: Float32Array,
1236
+ sampleRate: number,
1237
+ platforms: StreamingPlatform[] = [],
1238
+ ): string {
1239
+ if (!module) {
1240
+ throw new Error('Module not initialized. Call init() first.');
1241
+ }
1242
+ return module.masteringStreamingPreview(samples, sampleRate, platforms);
1243
+ }
1244
+
1245
+ /**
1246
+ * Apply a configurable mastering chain in WASM.
1247
+ *
1248
+ * @param samples - Audio samples (mono, float32)
1249
+ * @param sampleRate - Sample rate in Hz
1250
+ * @param config - Chain stage configuration
1251
+ * @returns Processed audio, loudness metadata, and applied stage names
1252
+ */
1253
+ export function masteringChain(
1254
+ samples: Float32Array,
1255
+ sampleRate: number,
1256
+ config: MasteringChainConfig,
1257
+ ): MasteringChainResult {
1258
+ if (!module) {
1259
+ throw new Error('Module not initialized. Call init() first.');
1260
+ }
1261
+ return module.masteringChain(samples, sampleRate, config as Record<string, unknown>);
1262
+ }
1263
+
1264
+ /**
1265
+ * Apply a configurable stereo mastering chain in WASM.
1266
+ *
1267
+ * @param left - Left channel samples
1268
+ * @param right - Right channel samples
1269
+ * @param sampleRate - Sample rate in Hz
1270
+ * @param config - Chain stage configuration
1271
+ * @returns Processed stereo audio, loudness metadata, and applied stage names
1272
+ */
1273
+ export function masteringChainStereo(
1274
+ left: Float32Array,
1275
+ right: Float32Array,
1276
+ sampleRate: number,
1277
+ config: MasteringChainConfig,
1278
+ ): MasteringStereoChainResult {
1279
+ if (!module) {
1280
+ throw new Error('Module not initialized. Call init() first.');
1281
+ }
1282
+ if (left.length !== right.length) {
1283
+ throw new Error('Stereo channel lengths must match.');
1284
+ }
1285
+ return module.masteringChainStereo(left, right, sampleRate, config as Record<string, unknown>);
1286
+ }
1287
+
1288
+ /**
1289
+ * Apply a configurable mastering chain in WASM with progress reporting.
1290
+ *
1291
+ * @param samples - Audio samples (mono, float32)
1292
+ * @param sampleRate - Sample rate in Hz
1293
+ * @param config - Chain stage configuration
1294
+ * @param onProgress - Progress callback (progress: 0-1, stage: string)
1295
+ * @returns Processed audio, loudness metadata, and applied stage names
1296
+ */
1297
+ export function masteringChainWithProgress(
1298
+ samples: Float32Array,
1299
+ sampleRate: number,
1300
+ config: MasteringChainConfig,
1301
+ onProgress: ProgressCallback,
1302
+ ): MasteringChainResult {
1303
+ if (!module) {
1304
+ throw new Error('Module not initialized. Call init() first.');
1305
+ }
1306
+ return module.masteringChainWithProgress(
1307
+ samples,
1308
+ sampleRate,
1309
+ config as Record<string, unknown>,
1310
+ onProgress,
1311
+ );
1312
+ }
1313
+
1314
+ /**
1315
+ * Apply a configurable stereo mastering chain in WASM with progress reporting.
1316
+ *
1317
+ * @param left - Left channel samples
1318
+ * @param right - Right channel samples
1319
+ * @param sampleRate - Sample rate in Hz
1320
+ * @param config - Chain stage configuration
1321
+ * @param onProgress - Progress callback (progress: 0-1, stage: string)
1322
+ * @returns Processed stereo audio, loudness metadata, and applied stage names
1323
+ */
1324
+ export function masteringChainStereoWithProgress(
1325
+ left: Float32Array,
1326
+ right: Float32Array,
1327
+ sampleRate: number,
1328
+ config: MasteringChainConfig,
1329
+ onProgress: ProgressCallback,
1330
+ ): MasteringStereoChainResult {
1331
+ if (!module) {
1332
+ throw new Error('Module not initialized. Call init() first.');
1333
+ }
1334
+ if (left.length !== right.length) {
1335
+ throw new Error('Stereo channel lengths must match.');
1336
+ }
1337
+ return module.masteringChainStereoWithProgress(
1338
+ left,
1339
+ right,
1340
+ sampleRate,
1341
+ config as Record<string, unknown>,
1342
+ onProgress,
1343
+ );
1344
+ }
1345
+
1346
+ /**
1347
+ * List built-in mastering preset identifiers.
1348
+ *
1349
+ * @returns Preset names in display order (e.g. "pop", "edm", "aiMusic")
1350
+ */
1351
+ export function masteringPresetNames(): MasteringPreset[] {
1352
+ if (!module) {
1353
+ throw new Error('Module not initialized. Call init() first.');
1354
+ }
1355
+ return module.masteringPresetNames() as MasteringPreset[];
1356
+ }
1357
+
1358
+ /**
1359
+ * Apply a named mastering preset chain to mono audio.
1360
+ *
1361
+ * @param samples - Audio samples (mono, float32)
1362
+ * @param sampleRate - Sample rate in Hz
1363
+ * @param presetName - Preset identifier from {@link masteringPresetNames}
1364
+ * @param overrides - Optional flat overrides (dot-notation, e.g. `'loudness.targetLufs'`) applied on top of the preset. Pass `null` for preset defaults.
1365
+ * @returns Processed audio, loudness metadata, and applied stage names
1366
+ */
1367
+ export function masterAudio(
1368
+ samples: Float32Array,
1369
+ sampleRate: number,
1370
+ presetName: MasteringPreset,
1371
+ overrides: Record<string, number | boolean> | null = null,
1372
+ ): MasteringChainResult {
1373
+ if (!module) {
1374
+ throw new Error('Module not initialized. Call init() first.');
1375
+ }
1376
+ return module.masterAudio(presetName, samples, sampleRate, overrides);
1377
+ }
1378
+
1379
+ /**
1380
+ * Apply a named mastering preset chain to stereo audio.
1381
+ *
1382
+ * @param left - Left channel samples
1383
+ * @param right - Right channel samples
1384
+ * @param sampleRate - Sample rate in Hz
1385
+ * @param presetName - Preset identifier from {@link masteringPresetNames}
1386
+ * @param overrides - Optional flat overrides (dot-notation, e.g. `'loudness.targetLufs'`) applied on top of the preset. Pass `null` for preset defaults.
1387
+ * @returns Processed stereo audio, loudness metadata, and applied stage names
1388
+ */
1389
+ export function masterAudioStereo(
1390
+ left: Float32Array,
1391
+ right: Float32Array,
1392
+ sampleRate: number,
1393
+ presetName: MasteringPreset,
1394
+ overrides: Record<string, number | boolean> | null = null,
1395
+ ): MasteringStereoChainResult {
1396
+ if (!module) {
1397
+ throw new Error('Module not initialized. Call init() first.');
1398
+ }
1399
+ if (left.length !== right.length) {
1400
+ throw new Error('Stereo channel lengths must match.');
1401
+ }
1402
+ return module.masterAudioStereo(presetName, left, right, sampleRate, overrides);
1403
+ }
1404
+
1405
+ export function mixingScenePresetNames(): string[] {
1406
+ if (!module) {
1407
+ throw new Error('Module not initialized. Call init() first.');
1408
+ }
1409
+ return module.mixingScenePresetNames();
1410
+ }
1411
+
1412
+ /**
1413
+ * Get a built-in mixing scene preset serialized as JSON. This is the canonical
1414
+ * name shared with the Node and Python bindings; the returned JSON loads
1415
+ * directly into a {@link Mixer} via {@link Mixer.fromSceneJson}.
1416
+ *
1417
+ * @param preset - Preset name (see {@link mixingScenePresetNames})
1418
+ * @returns Scene JSON string
1419
+ */
1420
+ export function mixingScenePresetJson(preset: string): string {
1421
+ if (!module) {
1422
+ throw new Error('Module not initialized. Call init() first.');
1423
+ }
1424
+ return module.mixingScenePresetJson(preset);
1425
+ }
1426
+
1427
+ export function mixStereo(
1428
+ leftChannels: Float32Array[],
1429
+ rightChannels: Float32Array[],
1430
+ sampleRate = 48000,
1431
+ options: MixOptions = {},
1432
+ ): MixResult {
1433
+ if (!module) {
1434
+ throw new Error('Module not initialized. Call init() first.');
1435
+ }
1436
+ if (leftChannels.length === 0 || leftChannels.length !== rightChannels.length) {
1437
+ throw new Error('leftChannels and rightChannels must have the same non-zero length.');
1438
+ }
1439
+ return module.mixStereo(
1440
+ leftChannels,
1441
+ rightChannels,
1442
+ sampleRate,
1443
+ options as Record<string, unknown>,
1444
+ );
1445
+ }
1446
+
1447
+ // ============================================================================
1448
+ // StreamingMasteringChain Class
1449
+ // ============================================================================
1450
+
1451
+ /**
1452
+ * Block-by-block streaming variant of {@link masteringChain}.
1453
+ *
1454
+ * Maintains processor state across {@link processMono}/{@link processStereo}
1455
+ * calls. Only ProcessorBase-backed stages are supported. Configurations that
1456
+ * enable `repair.denoise` or `loudness` throw at construction.
1457
+ *
1458
+ * Call {@link delete} (or use a `try/finally`) to release the underlying WASM
1459
+ * object — the embind handle is not garbage-collected automatically.
1460
+ *
1461
+ * @example
1462
+ * ```typescript
1463
+ * const chain = new StreamingMasteringChain({ eq: { tiltDb: 1.0 } });
1464
+ * try {
1465
+ * chain.prepare(44100, 512, 1);
1466
+ * const out = chain.processMono(blockSamples);
1467
+ * } finally {
1468
+ * chain.delete();
1469
+ * }
1470
+ * ```
1471
+ */
1472
+ export class StreamingMasteringChain {
1473
+ private chain: import('./wasm_types').WasmStreamingMasteringChain;
1474
+
1475
+ constructor(config: MasteringChainConfig) {
1476
+ if (!module) {
1477
+ throw new Error('Module not initialized. Call init() first.');
1478
+ }
1479
+ this.chain = module.createStreamingMasteringChain(config as Record<string, unknown>);
1480
+ }
1481
+
1482
+ /**
1483
+ * Initialize processors for the given sample rate and block layout.
1484
+ *
1485
+ * @param sampleRate - Sample rate in Hz
1486
+ * @param maxBlockSize - Maximum block size per process call
1487
+ * @param numChannels - 1 (mono) or 2 (stereo)
1488
+ */
1489
+ prepare(sampleRate: number, maxBlockSize: number, numChannels: number): void {
1490
+ this.chain.prepare(sampleRate, maxBlockSize, numChannels);
1491
+ }
1492
+
1493
+ /**
1494
+ * Process one mono block, returning the processed samples (same length).
1495
+ */
1496
+ processMono(samples: Float32Array): Float32Array {
1497
+ return this.chain.processMono(samples);
1498
+ }
1499
+
1500
+ /**
1501
+ * Process one stereo block, returning the processed channels.
1502
+ */
1503
+ processStereo(
1504
+ left: Float32Array,
1505
+ right: Float32Array,
1506
+ ): { left: Float32Array; right: Float32Array } {
1507
+ if (left.length !== right.length) {
1508
+ throw new Error('Stereo channel lengths must match.');
1509
+ }
1510
+ return this.chain.processStereo(left, right);
1511
+ }
1512
+
1513
+ /** Reset all processor state without rebuilding. */
1514
+ reset(): void {
1515
+ this.chain.reset();
1516
+ }
1517
+
1518
+ /** Total reported latency in samples across all active processors. */
1519
+ latencySamples(): number {
1520
+ return this.chain.latencySamples();
1521
+ }
1522
+
1523
+ /** Ordered stage names that will run (e.g. `"eq.tilt"`). */
1524
+ stageNames(): string[] {
1525
+ return this.chain.stageNames();
1526
+ }
1527
+
1528
+ /** Release the underlying WASM object. Safe to call only once. */
1529
+ delete(): void {
1530
+ this.chain.delete();
1531
+ }
1532
+ }
1533
+
1534
+ // ============================================================================
1535
+ // StreamingEqualizer Class
1536
+ // ============================================================================
1537
+
1538
+ /**
1539
+ * Block-by-block streaming equalizer wrapping the unified C++
1540
+ * `EqualizerProcessor` (up to 24 bands, RBJ/Vicanek biquads, dynamic EQ,
1541
+ * linear-phase FIR, mid/side processing, and auto-gain).
1542
+ *
1543
+ * State is maintained across {@link processMono}/{@link processStereo} calls.
1544
+ * Call {@link delete} (or use `try/finally`) to release the underlying WASM
1545
+ * object — the embind handle is not garbage-collected automatically.
1546
+ *
1547
+ * @example
1548
+ * ```typescript
1549
+ * const eq = new StreamingEqualizer({ sampleRate: 48000, maxBlockSize: 512 });
1550
+ * try {
1551
+ * eq.setBand(0, { type: 'HighShelf', frequencyHz: 8000, gainDb: 6, enabled: true });
1552
+ * const out = eq.processStereo(left, right);
1553
+ * const snapshot = eq.spectrum();
1554
+ * } finally {
1555
+ * eq.delete();
1556
+ * }
1557
+ * ```
1558
+ */
1559
+ export class StreamingEqualizer {
1560
+ private eq: import('./wasm_types').WasmStreamingEqualizer;
1561
+
1562
+ constructor(config: StreamingEqualizerConfig = {}) {
1563
+ if (!module) {
1564
+ throw new Error('Module not initialized. Call init() first.');
1565
+ }
1566
+ this.eq = module.createEqualizer(config as Record<string, unknown>);
1567
+ }
1568
+
1569
+ /**
1570
+ * Configure the band at `index` (0..23). Omitted fields use C++ defaults.
1571
+ */
1572
+ setBand(index: number, band: EqBand): void {
1573
+ this.eq.setBand(index, band as Record<string, unknown>);
1574
+ }
1575
+
1576
+ /** Disable and reset every band. */
1577
+ clear(): void {
1578
+ this.eq.clear();
1579
+ }
1580
+
1581
+ /**
1582
+ * Set the global phase mode: 1=ZeroLatency, 2=NaturalPhase, 3=LinearPhase.
1583
+ */
1584
+ setPhaseMode(mode: number): void {
1585
+ this.eq.setPhaseMode(mode);
1586
+ }
1587
+
1588
+ /** Enable or disable output auto-gain compensation. */
1589
+ setAutoGain(enabled: boolean): void {
1590
+ this.eq.setAutoGain(enabled);
1591
+ }
1592
+
1593
+ /** Set all-band EQ gain scale as a 0.0..2.0 multiplier. */
1594
+ setGainScale(scale: number): void {
1595
+ this.eq.setGainScale(scale);
1596
+ }
1597
+
1598
+ /** Set post-EQ output gain in dB. */
1599
+ setOutputGainDb(gainDb: number): void {
1600
+ this.eq.setOutputGainDb(gainDb);
1601
+ }
1602
+
1603
+ /** Set post-EQ stereo balance in -1.0..1.0; mono input ignores pan. */
1604
+ setOutputPan(pan: number): void {
1605
+ this.eq.setOutputPan(pan);
1606
+ }
1607
+
1608
+ /**
1609
+ * Provide a mono external sidechain key for dynamic bands that opt into
1610
+ * `external_sidechain`. The samples are copied into an owned buffer.
1611
+ */
1612
+ setSidechainMono(samples: Float32Array): void {
1613
+ this.eq.setSidechainMono(samples);
1614
+ }
1615
+
1616
+ /**
1617
+ * Provide a stereo external sidechain key. Both channels must match length.
1618
+ */
1619
+ setSidechainStereo(left: Float32Array, right: Float32Array): void {
1620
+ if (left.length !== right.length) {
1621
+ throw new Error('Sidechain channel lengths must match.');
1622
+ }
1623
+ this.eq.setSidechainStereo(left, right);
1624
+ }
1625
+
1626
+ /** Release any borrowed external sidechain buffers. */
1627
+ clearSidechain(): void {
1628
+ this.eq.clearSidechain();
1629
+ }
1630
+
1631
+ /** Auto-gain applied on the most recent block, in dB. */
1632
+ lastAutoGainDb(): number {
1633
+ return this.eq.lastAutoGainDb();
1634
+ }
1635
+
1636
+ /** Reported processing latency in samples (non-zero for linear-phase bands). */
1637
+ latencySamples(): number {
1638
+ return this.eq.latencySamples();
1639
+ }
1640
+
1641
+ /**
1642
+ * Process one mono block, returning the equalized samples (same length).
1643
+ */
1644
+ processMono(samples: Float32Array): Float32Array {
1645
+ return this.eq.processMono(samples);
1646
+ }
1647
+
1648
+ /**
1649
+ * Process one stereo block, returning the equalized channels.
1650
+ */
1651
+ processStereo(
1652
+ left: Float32Array,
1653
+ right: Float32Array,
1654
+ ): { left: Float32Array; right: Float32Array } {
1655
+ if (left.length !== right.length) {
1656
+ throw new Error('Stereo channel lengths must match.');
1657
+ }
1658
+ return this.eq.processStereo(left, right);
1659
+ }
1660
+
1661
+ /**
1662
+ * Read the latest pre/post spectrum snapshot for metering. `seq` increments
1663
+ * each time a new snapshot is published.
1664
+ */
1665
+ spectrum(): EqSpectrumSnapshot {
1666
+ return this.eq.spectrum();
1667
+ }
1668
+
1669
+ /**
1670
+ * Configure bands so the source spectrum matches the reference spectrum.
1671
+ *
1672
+ * @param source - Source audio (mono samples)
1673
+ * @param reference - Reference audio (mono samples)
1674
+ * @param options - `sampleRate` (default 48000) and `maxBands` (default 8)
1675
+ */
1676
+ match(source: Float32Array, reference: Float32Array, options: EqMatchOptions = {}): void {
1677
+ this.eq.match(source, reference, options as Record<string, unknown>);
1678
+ }
1679
+
1680
+ /** Release the underlying WASM object. Safe to call only once. */
1681
+ delete(): void {
1682
+ this.eq.delete();
1683
+ }
1684
+ }
1685
+
1686
+ // ============================================================================
1687
+ // Mixer Class (scene-based persistent mixer)
1688
+ // ============================================================================
1689
+
1690
+ /**
1691
+ * Get a built-in mixing scene preset serialized as JSON, normalized through the
1692
+ * C mixer API (the same path {@link Mixer.fromSceneJson} uses to load it).
1693
+ *
1694
+ * @deprecated Use {@link mixingScenePresetJson}, the canonical name shared with
1695
+ * the Node and Python bindings. This alias is retained for backwards
1696
+ * compatibility and may be removed in a future release. Both functions return a
1697
+ * scene JSON string that loads cleanly into a {@link Mixer}.
1698
+ *
1699
+ * @param preset - Preset name (see {@link mixingScenePresetNames})
1700
+ * @returns Scene JSON string
1701
+ */
1702
+ export function mixerScenePresetJson(preset: string): string {
1703
+ if (!module) {
1704
+ throw new Error('Module not initialized. Call init() first.');
1705
+ }
1706
+ return module.mixerPresetJson(preset);
1707
+ }
1708
+
1709
+ /**
1710
+ * Persistent, scene-based stereo mixer.
1711
+ *
1712
+ * Build one from a scene JSON string (e.g. {@link mixerScenePresetJson} or a
1713
+ * hand-authored scene), then feed per-strip stereo blocks through
1714
+ * {@link processStereo} to get the routed stereo master. Strips, sends, buses,
1715
+ * and inserts are described entirely by the scene; the routing graph is
1716
+ * compiled lazily on the first {@link processStereo} call (or eagerly via
1717
+ * {@link compile}).
1718
+ *
1719
+ * Call {@link delete} (or use a `try/finally`) to release the underlying WASM
1720
+ * object — the embind handle is not garbage-collected automatically.
1721
+ *
1722
+ * @example
1723
+ * ```typescript
1724
+ * const mixer = Mixer.fromSceneJson(mixerScenePresetJson('basicStereo'), 48000, 512);
1725
+ * try {
1726
+ * const out = mixer.processStereo([stripL], [stripR]);
1727
+ * } finally {
1728
+ * mixer.delete();
1729
+ * }
1730
+ * ```
1731
+ */
1732
+ export class Mixer {
1733
+ private mixer: import('./wasm_types').WasmMixer;
1734
+
1735
+ private constructor(mixer: import('./wasm_types').WasmMixer) {
1736
+ this.mixer = mixer;
1737
+ }
1738
+
1739
+ /**
1740
+ * Build a mixer from a scene JSON string.
1741
+ *
1742
+ * @param json - Scene JSON (strips, buses, sends, connections, inserts)
1743
+ * @param sampleRate - Sample rate in Hz (default: 48000)
1744
+ * @param blockSize - Maximum block size per {@link processStereo} call (default: 512)
1745
+ */
1746
+ static fromSceneJson(json: string, sampleRate = 48000, blockSize = 512): Mixer {
1747
+ if (!module) {
1748
+ throw new Error('Module not initialized. Call init() first.');
1749
+ }
1750
+ return new Mixer(module.createMixerFromSceneJson(json, sampleRate, blockSize));
1751
+ }
1752
+
1753
+ /** Rebuild and compile the routing graph from the current scene topology. */
1754
+ compile(): void {
1755
+ this.mixer.compile();
1756
+ }
1757
+
1758
+ /**
1759
+ * Mix one block of per-strip stereo audio into the stereo master.
1760
+ *
1761
+ * @param leftChannels - `leftChannels[i]` is the left channel of strip `i`
1762
+ * @param rightChannels - `rightChannels[i]` is the right channel of strip `i`
1763
+ * @returns Mixed stereo master (`left`, `right`, `sampleRate`)
1764
+ */
1765
+ processStereo(leftChannels: Float32Array[], rightChannels: Float32Array[]): MixerProcessResult {
1766
+ if (leftChannels.length !== rightChannels.length) {
1767
+ throw new Error('leftChannels and rightChannels must have the same length.');
1768
+ }
1769
+ return this.mixer.processStereo(leftChannels, rightChannels);
1770
+ }
1771
+
1772
+ /**
1773
+ * Mix one block into caller-owned output arrays.
1774
+ *
1775
+ * This avoids allocating the result object and result `Float32Array`s. It is
1776
+ * intended for realtime bridges such as AudioWorklet; the input channel count
1777
+ * must match the scene strip count and all arrays must have the same length.
1778
+ */
1779
+ processStereoInto(
1780
+ leftChannels: Float32Array[],
1781
+ rightChannels: Float32Array[],
1782
+ outLeft: Float32Array,
1783
+ outRight: Float32Array,
1784
+ ): void {
1785
+ if (leftChannels.length !== rightChannels.length) {
1786
+ throw new Error('leftChannels and rightChannels must have the same length.');
1787
+ }
1788
+ if (outLeft.length !== outRight.length) {
1789
+ throw new Error('outLeft and outRight must have the same length.');
1790
+ }
1791
+ this.mixer.processStereoInto(leftChannels, rightChannels, outLeft, outRight);
1792
+ }
1793
+
1794
+ /**
1795
+ * Create reusable WASM-heap input/output views for realtime-style processing.
1796
+ *
1797
+ * Fill `leftInputs[i]` / `rightInputs[i]`, call `process()`, then read
1798
+ * `outLeft` / `outRight`. The views are owned by this mixer and become invalid
1799
+ * after {@link delete}.
1800
+ */
1801
+ createRealtimeBuffer(): MixerRealtimeBuffer {
1802
+ const stripCount = this.stripCount();
1803
+ const leftInputs: Float32Array[] = [];
1804
+ const rightInputs: Float32Array[] = [];
1805
+ for (let index = 0; index < stripCount; index++) {
1806
+ leftInputs.push(this.mixer.inputLeftView(index));
1807
+ rightInputs.push(this.mixer.inputRightView(index));
1808
+ }
1809
+ const outLeft = this.mixer.outputLeftView();
1810
+ const outRight = this.mixer.outputRightView();
1811
+ return {
1812
+ leftInputs,
1813
+ rightInputs,
1814
+ outLeft,
1815
+ outRight,
1816
+ process: (numSamples = outLeft.length) => this.mixer.processPreparedStereo(numSamples),
1817
+ };
1818
+ }
1819
+
1820
+ /** Number of strips in the mixer (e.g. strips loaded from the scene). */
1821
+ stripCount(): number {
1822
+ return this.mixer.stripCount();
1823
+ }
1824
+
1825
+ /**
1826
+ * Schedule sample-accurate insert-parameter automation on a strip's insert.
1827
+ *
1828
+ * @param stripIndex - Strip index in `[0, stripCount())`
1829
+ * @param insertIndex - Index into the strip's combined insert sequence
1830
+ * (`[pre-inserts... post-inserts...]`)
1831
+ * @param paramId - Processor-specific parameter id
1832
+ * @param samplePos - Absolute samples from the start of processing (the mixer
1833
+ * advances an internal position from 0 on the first {@link processStereo}
1834
+ * call; recompiling resets it to 0)
1835
+ * @param value - Target parameter value
1836
+ * @param curve - Interpolation curve (default: `'linear'`)
1837
+ * @throws If the strip index is out of range or the schedule call fails
1838
+ * (unknown curve, out-of-range insert index, or full event lane)
1839
+ */
1840
+ scheduleInsertAutomation(
1841
+ stripIndex: number,
1842
+ insertIndex: number,
1843
+ paramId: number,
1844
+ samplePos: number,
1845
+ value: number,
1846
+ curve: AutomationCurve = 'linear',
1847
+ ): void {
1848
+ this.mixer.scheduleInsertAutomation(
1849
+ stripIndex,
1850
+ insertIndex,
1851
+ paramId,
1852
+ samplePos,
1853
+ value,
1854
+ automationCurveCode(curve),
1855
+ );
1856
+ }
1857
+
1858
+ /**
1859
+ * Resolve a strip's index in `[0, stripCount())` from its scene id, or `null`
1860
+ * when no strip with that id exists (matches the Node binding's `number | null`).
1861
+ */
1862
+ stripById(id: string): number | null {
1863
+ const index = this.mixer.stripById(id);
1864
+ return index < 0 ? null : index;
1865
+ }
1866
+
1867
+ /**
1868
+ * Add a bus to the mixer topology. `role` is one of `'master'`, `'aux'`, or
1869
+ * `'submix'` (defaults to `'aux'`). Marks the routing graph dirty; call
1870
+ * {@link compile} (or {@link processStereo}) to rebuild.
1871
+ */
1872
+ addBus(id: string, role = 'aux'): void {
1873
+ this.mixer.addBus(id, role);
1874
+ }
1875
+
1876
+ /** Remove a bus by id. Marks the routing graph dirty. */
1877
+ removeBus(id: string): void {
1878
+ this.mixer.removeBus(id);
1879
+ }
1880
+
1881
+ /** Number of buses in the mixer topology. */
1882
+ busCount(): number {
1883
+ return this.mixer.busCount();
1884
+ }
1885
+
1886
+ /**
1887
+ * Add a VCA group with the given gain offset (dB). `members` is a list of
1888
+ * strip ids governed by the group (may be empty).
1889
+ */
1890
+ addVcaGroup(id: string, gainDb = 0.0, members: string[] = []): void {
1891
+ this.mixer.addVcaGroup(id, gainDb, members);
1892
+ }
1893
+
1894
+ /** Remove a VCA group by id. */
1895
+ removeVcaGroup(id: string): void {
1896
+ this.mixer.removeVcaGroup(id);
1897
+ }
1898
+
1899
+ /** Number of VCA groups in the mixer topology. */
1900
+ vcaGroupCount(): number {
1901
+ return this.mixer.vcaGroupCount();
1902
+ }
1903
+
1904
+ /**
1905
+ * Set a strip's solo state. Takes effect on the next process without a
1906
+ * graph recompile.
1907
+ */
1908
+ setSoloed(stripIndex: number, soloed: boolean): void {
1909
+ this.mixer.setSoloed(stripIndex, soloed);
1910
+ }
1911
+
1912
+ /**
1913
+ * Mark a strip solo-safe so it is never implied-muted by another strip's
1914
+ * solo. Takes effect on the next process without a graph recompile.
1915
+ */
1916
+ setSoloSafe(stripIndex: number, soloSafe: boolean): void {
1917
+ this.mixer.setSoloSafe(stripIndex, soloSafe);
1918
+ }
1919
+
1920
+ /** Invert the polarity of the left and/or right channel of a strip. */
1921
+ setPolarityInvert(stripIndex: number, invertLeft: boolean, invertRight: boolean): void {
1922
+ this.mixer.setPolarityInvert(stripIndex, invertLeft, invertRight);
1923
+ }
1924
+
1925
+ /** Set the strip's pan law. */
1926
+ setPanLaw(stripIndex: number, panLaw: PanLaw | number): void {
1927
+ this.mixer.setPanLaw(stripIndex, panLawCode(panLaw));
1928
+ }
1929
+
1930
+ /**
1931
+ * Set a per-strip channel delay in samples. This changes the strip's reported
1932
+ * latency; recompile to re-run latency compensation.
1933
+ */
1934
+ setChannelDelaySamples(stripIndex: number, delaySamples: number): void {
1935
+ this.mixer.setChannelDelaySamples(stripIndex, delaySamples);
1936
+ }
1937
+
1938
+ /** Set the strip's live VCA gain offset in dB (not persisted to the scene). */
1939
+ setVcaOffsetDb(stripIndex: number, offsetDb: number): void {
1940
+ this.mixer.setVcaOffsetDb(stripIndex, offsetDb);
1941
+ }
1942
+
1943
+ /** Set independent left/right pan positions (dual-pan mode). */
1944
+ setDualPan(stripIndex: number, leftPan: number, rightPan: number): void {
1945
+ this.mixer.setDualPan(stripIndex, leftPan, rightPan);
1946
+ }
1947
+
1948
+ /**
1949
+ * Add a send to a strip after construction.
1950
+ *
1951
+ * @param stripIndex - Strip index in `[0, stripCount())`
1952
+ * @param id - Send id
1953
+ * @param destinationBusId - Destination bus id
1954
+ * @param sendDb - Initial send level in dB
1955
+ * @param timing - `'preFader'` or `'postFader'` (default: `'postFader'`)
1956
+ * @returns The new send's index
1957
+ */
1958
+ addSend(
1959
+ stripIndex: number,
1960
+ id: string,
1961
+ destinationBusId: string,
1962
+ sendDb: number,
1963
+ timing: SendTiming | number = 'postFader',
1964
+ ): number {
1965
+ return this.mixer.addSend(stripIndex, id, destinationBusId, sendDb, sendTimingCode(timing));
1966
+ }
1967
+
1968
+ /** Set the send level (in dB) for an existing send by index. */
1969
+ setSendDb(stripIndex: number, sendIndex: number, sendDb: number): void {
1970
+ this.mixer.setSendDb(stripIndex, sendIndex, sendDb);
1971
+ }
1972
+
1973
+ /**
1974
+ * Read a strip's meter snapshot at the given tap point.
1975
+ *
1976
+ * @param stripIndex - Strip index in `[0, stripCount())`
1977
+ * @param tap - `'preFader'` or `'postFader'` (default: `'postFader'`)
1978
+ */
1979
+ meterTap(stripIndex: number, tap: MeterTap = 'postFader'): MixMeterSnapshot {
1980
+ return this.mixer.meterTap(stripIndex, meterTapCode(tap));
1981
+ }
1982
+
1983
+ /**
1984
+ * Read a strip's meter snapshot. Alias of {@link meterTap}, provided for
1985
+ * cross-binding (Node/Python) parity.
1986
+ *
1987
+ * @param stripIndex - Strip index in `[0, stripCount())`
1988
+ * @param tap - `'preFader'` or `'postFader'` (default: `'postFader'`)
1989
+ */
1990
+ stripMeter(stripIndex: number, tap: MeterTap = 'postFader'): MixMeterSnapshot {
1991
+ return this.mixer.stripMeter(stripIndex, meterTapCode(tap));
1992
+ }
1993
+
1994
+ /**
1995
+ * Schedule sample-accurate fader automation on a strip.
1996
+ *
1997
+ * @param stripIndex - Strip index in `[0, stripCount())`
1998
+ * @param samplePos - Absolute samples from the start of processing
1999
+ * @param faderDb - Target fader level in dB
2000
+ * @param curve - Interpolation curve (default: `'linear'`)
2001
+ */
2002
+ scheduleFaderAutomation(
2003
+ stripIndex: number,
2004
+ samplePos: number,
2005
+ faderDb: number,
2006
+ curve: AutomationCurve = 'linear',
2007
+ ): void {
2008
+ this.mixer.scheduleFaderAutomation(stripIndex, samplePos, faderDb, automationCurveCode(curve));
2009
+ }
2010
+
2011
+ /**
2012
+ * Schedule sample-accurate pan automation on a strip.
2013
+ *
2014
+ * @param stripIndex - Strip index in `[0, stripCount())`
2015
+ * @param samplePos - Absolute samples from the start of processing
2016
+ * @param pan - Target pan position
2017
+ * @param curve - Interpolation curve (default: `'linear'`)
2018
+ */
2019
+ schedulePanAutomation(
2020
+ stripIndex: number,
2021
+ samplePos: number,
2022
+ pan: number,
2023
+ curve: AutomationCurve = 'linear',
2024
+ ): void {
2025
+ this.mixer.schedulePanAutomation(stripIndex, samplePos, pan, automationCurveCode(curve));
2026
+ }
2027
+
2028
+ /**
2029
+ * Schedule sample-accurate width automation on a strip.
2030
+ *
2031
+ * @param stripIndex - Strip index in `[0, stripCount())`
2032
+ * @param samplePos - Absolute samples from the start of processing
2033
+ * @param width - Target stereo width
2034
+ * @param curve - Interpolation curve (default: `'linear'`)
2035
+ */
2036
+ scheduleWidthAutomation(
2037
+ stripIndex: number,
2038
+ samplePos: number,
2039
+ width: number,
2040
+ curve: AutomationCurve = 'linear',
2041
+ ): void {
2042
+ this.mixer.scheduleWidthAutomation(stripIndex, samplePos, width, automationCurveCode(curve));
2043
+ }
2044
+
2045
+ /**
2046
+ * Schedule sample-accurate send-level automation on a strip's send.
2047
+ *
2048
+ * @param stripIndex - Strip index in `[0, stripCount())`
2049
+ * @param sendIndex - Send index in the strip's add order
2050
+ * @param samplePos - Absolute samples from the start of processing
2051
+ * @param db - Target send level in dB
2052
+ * @param curve - Interpolation curve (default: `'linear'`)
2053
+ */
2054
+ scheduleSendAutomation(
2055
+ stripIndex: number,
2056
+ sendIndex: number,
2057
+ samplePos: number,
2058
+ db: number,
2059
+ curve: AutomationCurve = 'linear',
2060
+ ): void {
2061
+ this.mixer.scheduleSendAutomation(
2062
+ stripIndex,
2063
+ sendIndex,
2064
+ samplePos,
2065
+ db,
2066
+ automationCurveCode(curve),
2067
+ );
2068
+ }
2069
+
2070
+ /**
2071
+ * Read up to `maxPoints` of a strip's most recent goniometer samples
2072
+ * (oldest to newest).
2073
+ */
2074
+ readGoniometerLatest(stripIndex: number, maxPoints: number): GoniometerPoint[] {
2075
+ return this.mixer.readGoniometerLatest(stripIndex, maxPoints);
2076
+ }
2077
+
2078
+ /** Serialize the current scene (strips, buses, sends, connections) to JSON. */
2079
+ toSceneJson(): string {
2080
+ return this.mixer.toSceneJson();
2081
+ }
2082
+
2083
+ /** Release the underlying WASM object. Safe to call only once. */
2084
+ delete(): void {
2085
+ this.mixer.delete();
2086
+ }
2087
+
2088
+ /** Alias for {@link delete}, provided for cross-binding (Node) compatibility. */
2089
+ destroy(): void {
2090
+ this.delete();
2091
+ }
2092
+ }
2093
+
2094
+ /**
2095
+ * Trim silence from beginning and end of audio.
2096
+ *
2097
+ * @param samples - Audio samples (mono, float32)
2098
+ * @param sampleRate - Sample rate in Hz
2099
+ * @param thresholdDb - Silence threshold in dB (default: -60 dB)
2100
+ * @returns Trimmed audio
2101
+ */
2102
+ export function trim(samples: Float32Array, sampleRate: number, thresholdDb = -60.0): Float32Array {
2103
+ if (!module) {
2104
+ throw new Error('Module not initialized. Call init() first.');
2105
+ }
2106
+ return module.trim(samples, sampleRate, thresholdDb);
2107
+ }
2108
+
2109
+ // ============================================================================
2110
+ // Features - Spectrogram
2111
+ // ============================================================================
2112
+
2113
+ /**
2114
+ * Compute Short-Time Fourier Transform (STFT).
2115
+ *
2116
+ * @param samples - Audio samples (mono, float32)
2117
+ * @param sampleRate - Sample rate in Hz
2118
+ * @param nFft - FFT size (default: 2048)
2119
+ * @param hopLength - Hop length (default: 512)
2120
+ * @returns STFT result with magnitude and power spectrograms
2121
+ */
2122
+ export function stft(
2123
+ samples: Float32Array,
2124
+ sampleRate: number,
2125
+ nFft = 2048,
2126
+ hopLength = 512,
2127
+ ): StftResult {
2128
+ if (!module) {
2129
+ throw new Error('Module not initialized. Call init() first.');
2130
+ }
2131
+ return module.stft(samples, sampleRate, nFft, hopLength);
2132
+ }
2133
+
2134
+ /**
2135
+ * Compute STFT and return magnitude in decibels.
2136
+ *
2137
+ * @param samples - Audio samples (mono, float32)
2138
+ * @param sampleRate - Sample rate in Hz
2139
+ * @param nFft - FFT size (default: 2048)
2140
+ * @param hopLength - Hop length (default: 512)
2141
+ * @returns STFT result with dB values
2142
+ */
2143
+ export function stftDb(
2144
+ samples: Float32Array,
2145
+ sampleRate: number,
2146
+ nFft = 2048,
2147
+ hopLength = 512,
2148
+ ): { nBins: number; nFrames: number; db: Float32Array } {
2149
+ if (!module) {
2150
+ throw new Error('Module not initialized. Call init() first.');
2151
+ }
2152
+ return module.stftDb(samples, sampleRate, nFft, hopLength);
2153
+ }
2154
+
2155
+ // ============================================================================
2156
+ // Features - Mel Spectrogram
2157
+ // ============================================================================
2158
+
2159
+ /**
2160
+ * Compute Mel spectrogram.
2161
+ *
2162
+ * @param samples - Audio samples (mono, float32)
2163
+ * @param sampleRate - Sample rate in Hz
2164
+ * @param nFft - FFT size (default: 2048)
2165
+ * @param hopLength - Hop length (default: 512)
2166
+ * @param nMels - Number of Mel bands (default: 128)
2167
+ * @returns Mel spectrogram result
2168
+ */
2169
+ export function melSpectrogram(
2170
+ samples: Float32Array,
2171
+ sampleRate: number,
2172
+ nFft = 2048,
2173
+ hopLength = 512,
2174
+ nMels = 128,
2175
+ ): MelSpectrogramResult {
2176
+ if (!module) {
2177
+ throw new Error('Module not initialized. Call init() first.');
2178
+ }
2179
+ return module.melSpectrogram(samples, sampleRate, nFft, hopLength, nMels);
2180
+ }
2181
+
2182
+ /**
2183
+ * Compute MFCC (Mel-Frequency Cepstral Coefficients).
2184
+ *
2185
+ * @param samples - Audio samples (mono, float32)
2186
+ * @param sampleRate - Sample rate in Hz
2187
+ * @param nFft - FFT size (default: 2048)
2188
+ * @param hopLength - Hop length (default: 512)
2189
+ * @param nMels - Number of Mel bands (default: 128)
2190
+ * @param nMfcc - Number of MFCC coefficients (default: 13)
2191
+ * @returns MFCC result
2192
+ */
2193
+ export function mfcc(
2194
+ samples: Float32Array,
2195
+ sampleRate: number,
2196
+ nFft = 2048,
2197
+ hopLength = 512,
2198
+ nMels = 128,
2199
+ nMfcc = 13,
2200
+ ): MfccResult {
2201
+ if (!module) {
2202
+ throw new Error('Module not initialized. Call init() first.');
2203
+ }
2204
+ return module.mfcc(samples, sampleRate, nFft, hopLength, nMels, nMfcc);
2205
+ }
2206
+
2207
+ // ============================================================================
2208
+ // Features - Inverse reconstruction
2209
+ // ============================================================================
2210
+
2211
+ /**
2212
+ * Approximate inverse of a Mel filterbank: Mel power spectrogram -> STFT power
2213
+ * spectrogram. Mirrors `feature::mel_to_stft`.
2214
+ *
2215
+ * @param melPower - Mel power spectrogram [nMels x nFrames] row-major
2216
+ * @param nMels - Number of Mel bands
2217
+ * @param nFrames - Number of time frames
2218
+ * @param sampleRate - Sample rate in Hz
2219
+ * @param nFft - FFT size (default: 2048)
2220
+ * @param hopLength - Hop length (default: 512)
2221
+ * @returns STFT power spectrogram result
2222
+ */
2223
+ export function melToStft(
2224
+ melPower: Float32Array,
2225
+ nMels: number,
2226
+ nFrames: number,
2227
+ sampleRate: number,
2228
+ nFft = 2048,
2229
+ hopLength = 512,
2230
+ fmin = 0,
2231
+ fmax = 0,
2232
+ ): StftPowerResult {
2233
+ if (!module) {
2234
+ throw new Error('Module not initialized. Call init() first.');
2235
+ }
2236
+ return module.melToStft(melPower, nMels, nFrames, sampleRate, nFft, hopLength, fmin, fmax);
2237
+ }
2238
+
2239
+ /**
2240
+ * Reconstruct audio from a Mel power spectrogram via Griffin-Lim. Mirrors
2241
+ * `feature::mel_to_audio`.
2242
+ *
2243
+ * @param melPower - Mel power spectrogram [nMels x nFrames] row-major
2244
+ * @param nMels - Number of Mel bands
2245
+ * @param nFrames - Number of time frames
2246
+ * @param sampleRate - Sample rate in Hz
2247
+ * @param nFft - FFT size (default: 2048)
2248
+ * @param hopLength - Hop length (default: 512)
2249
+ * @param nIter - Griffin-Lim iterations (default: 32)
2250
+ * @returns Reconstructed audio samples (mono, float32)
2251
+ */
2252
+ export function melToAudio(
2253
+ melPower: Float32Array,
2254
+ nMels: number,
2255
+ nFrames: number,
2256
+ sampleRate: number,
2257
+ nFft = 2048,
2258
+ hopLength = 512,
2259
+ nIter = 32,
2260
+ fmin = 0,
2261
+ fmax = 0,
2262
+ ): Float32Array {
2263
+ if (!module) {
2264
+ throw new Error('Module not initialized. Call init() first.');
2265
+ }
2266
+ return module.melToAudio(
2267
+ melPower,
2268
+ nMels,
2269
+ nFrames,
2270
+ sampleRate,
2271
+ nFft,
2272
+ hopLength,
2273
+ nIter,
2274
+ fmin,
2275
+ fmax,
2276
+ );
2277
+ }
2278
+
2279
+ /**
2280
+ * Invert MFCC coefficients back to a Mel power spectrogram. Mirrors
2281
+ * `feature::mfcc_to_mel`.
2282
+ *
2283
+ * @param mfccCoefficients - MFCC matrix [nMfcc x nFrames] row-major
2284
+ * @param nMfcc - Number of MFCC coefficients
2285
+ * @param nFrames - Number of time frames
2286
+ * @param nMels - Number of Mel bins to reconstruct (default: 128)
2287
+ * @returns Mel power spectrogram result
2288
+ */
2289
+ export function mfccToMel(
2290
+ mfccCoefficients: Float32Array,
2291
+ nMfcc: number,
2292
+ nFrames: number,
2293
+ nMels = 128,
2294
+ ): MelPowerResult {
2295
+ if (!module) {
2296
+ throw new Error('Module not initialized. Call init() first.');
2297
+ }
2298
+ return module.mfccToMel(mfccCoefficients, nMfcc, nFrames, nMels);
2299
+ }
2300
+
2301
+ /**
2302
+ * Reconstruct audio directly from MFCC coefficients via Griffin-Lim. Mirrors
2303
+ * `feature::mfcc_to_audio`.
2304
+ *
2305
+ * @param mfccCoefficients - MFCC matrix [nMfcc x nFrames] row-major
2306
+ * @param nMfcc - Number of MFCC coefficients
2307
+ * @param nFrames - Number of time frames
2308
+ * @param nMels - Number of Mel bins (default: 128)
2309
+ * @param sampleRate - Sample rate in Hz
2310
+ * @param nFft - FFT size (default: 2048)
2311
+ * @param hopLength - Hop length (default: 512)
2312
+ * @param nIter - Griffin-Lim iterations (default: 32)
2313
+ * @returns Reconstructed audio samples (mono, float32)
2314
+ */
2315
+ export function mfccToAudio(
2316
+ mfccCoefficients: Float32Array,
2317
+ nMfcc: number,
2318
+ nFrames: number,
2319
+ nMels: number,
2320
+ sampleRate: number,
2321
+ nFft = 2048,
2322
+ hopLength = 512,
2323
+ nIter = 32,
2324
+ fmin = 0,
2325
+ fmax = 0,
2326
+ ): Float32Array {
2327
+ if (!module) {
2328
+ throw new Error('Module not initialized. Call init() first.');
2329
+ }
2330
+ return module.mfccToAudio(
2331
+ mfccCoefficients,
2332
+ nMfcc,
2333
+ nFrames,
2334
+ nMels,
2335
+ sampleRate,
2336
+ nFft,
2337
+ hopLength,
2338
+ nIter,
2339
+ fmin,
2340
+ fmax,
2341
+ );
2342
+ }
2343
+
2344
+ // ============================================================================
2345
+ // Features - Chroma
2346
+ // ============================================================================
2347
+
2348
+ /**
2349
+ * Compute chromagram (pitch class distribution).
2350
+ *
2351
+ * @param samples - Audio samples (mono, float32)
2352
+ * @param sampleRate - Sample rate in Hz
2353
+ * @param nFft - FFT size (default: 2048)
2354
+ * @param hopLength - Hop length (default: 512)
2355
+ * @returns Chroma features result
2356
+ */
2357
+ export function chroma(
2358
+ samples: Float32Array,
2359
+ sampleRate: number,
2360
+ nFft = 2048,
2361
+ hopLength = 512,
2362
+ ): ChromaResult {
2363
+ if (!module) {
2364
+ throw new Error('Module not initialized. Call init() first.');
2365
+ }
2366
+ return module.chroma(samples, sampleRate, nFft, hopLength);
2367
+ }
2368
+
2369
+ // ============================================================================
2370
+ // Features - Spectral
2371
+ // ============================================================================
2372
+
2373
+ /**
2374
+ * Compute spectral centroid (center of mass of spectrum).
2375
+ *
2376
+ * @param samples - Audio samples (mono, float32)
2377
+ * @param sampleRate - Sample rate in Hz
2378
+ * @param nFft - FFT size (default: 2048)
2379
+ * @param hopLength - Hop length (default: 512)
2380
+ * @returns Spectral centroid in Hz for each frame
2381
+ */
2382
+ export function spectralCentroid(
2383
+ samples: Float32Array,
2384
+ sampleRate: number,
2385
+ nFft = 2048,
2386
+ hopLength = 512,
2387
+ ): Float32Array {
2388
+ if (!module) {
2389
+ throw new Error('Module not initialized. Call init() first.');
2390
+ }
2391
+ return module.spectralCentroid(samples, sampleRate, nFft, hopLength);
2392
+ }
2393
+
2394
+ /**
2395
+ * Compute spectral bandwidth.
2396
+ *
2397
+ * @param samples - Audio samples (mono, float32)
2398
+ * @param sampleRate - Sample rate in Hz
2399
+ * @param nFft - FFT size (default: 2048)
2400
+ * @param hopLength - Hop length (default: 512)
2401
+ * @returns Spectral bandwidth in Hz for each frame
2402
+ */
2403
+ export function spectralBandwidth(
2404
+ samples: Float32Array,
2405
+ sampleRate: number,
2406
+ nFft = 2048,
2407
+ hopLength = 512,
2408
+ ): Float32Array {
2409
+ if (!module) {
2410
+ throw new Error('Module not initialized. Call init() first.');
2411
+ }
2412
+ return module.spectralBandwidth(samples, sampleRate, nFft, hopLength);
2413
+ }
2414
+
2415
+ /**
2416
+ * Compute spectral rolloff frequency.
2417
+ *
2418
+ * @param samples - Audio samples (mono, float32)
2419
+ * @param sampleRate - Sample rate in Hz
2420
+ * @param nFft - FFT size (default: 2048)
2421
+ * @param hopLength - Hop length (default: 512)
2422
+ * @param rollPercent - Percentage threshold (default: 0.85)
2423
+ * @returns Rolloff frequency in Hz for each frame
2424
+ */
2425
+ export function spectralRolloff(
2426
+ samples: Float32Array,
2427
+ sampleRate: number,
2428
+ nFft = 2048,
2429
+ hopLength = 512,
2430
+ rollPercent = 0.85,
2431
+ ): Float32Array {
2432
+ if (!module) {
2433
+ throw new Error('Module not initialized. Call init() first.');
2434
+ }
2435
+ return module.spectralRolloff(samples, sampleRate, nFft, hopLength, rollPercent);
2436
+ }
2437
+
2438
+ /**
2439
+ * Compute spectral flatness.
2440
+ *
2441
+ * @param samples - Audio samples (mono, float32)
2442
+ * @param sampleRate - Sample rate in Hz
2443
+ * @param nFft - FFT size (default: 2048)
2444
+ * @param hopLength - Hop length (default: 512)
2445
+ * @returns Spectral flatness for each frame (0 = tonal, 1 = noise-like)
2446
+ */
2447
+ export function spectralFlatness(
2448
+ samples: Float32Array,
2449
+ sampleRate: number,
2450
+ nFft = 2048,
2451
+ hopLength = 512,
2452
+ ): Float32Array {
2453
+ if (!module) {
2454
+ throw new Error('Module not initialized. Call init() first.');
2455
+ }
2456
+ return module.spectralFlatness(samples, sampleRate, nFft, hopLength);
2457
+ }
2458
+
2459
+ /**
2460
+ * Compute zero crossing rate.
2461
+ *
2462
+ * @param samples - Audio samples (mono, float32)
2463
+ * @param sampleRate - Sample rate in Hz
2464
+ * @param frameLength - Frame length (default: 2048)
2465
+ * @param hopLength - Hop length (default: 512)
2466
+ * @returns Zero crossing rate for each frame
2467
+ */
2468
+ export function zeroCrossingRate(
2469
+ samples: Float32Array,
2470
+ sampleRate: number,
2471
+ frameLength = 2048,
2472
+ hopLength = 512,
2473
+ ): Float32Array {
2474
+ if (!module) {
2475
+ throw new Error('Module not initialized. Call init() first.');
2476
+ }
2477
+ return module.zeroCrossingRate(samples, sampleRate, frameLength, hopLength);
2478
+ }
2479
+
2480
+ /**
2481
+ * Compute RMS energy.
2482
+ *
2483
+ * @param samples - Audio samples (mono, float32)
2484
+ * @param sampleRate - Sample rate in Hz
2485
+ * @param frameLength - Frame length (default: 2048)
2486
+ * @param hopLength - Hop length (default: 512)
2487
+ * @returns RMS energy for each frame
2488
+ */
2489
+ export function rmsEnergy(
2490
+ samples: Float32Array,
2491
+ sampleRate: number,
2492
+ frameLength = 2048,
2493
+ hopLength = 512,
2494
+ ): Float32Array {
2495
+ if (!module) {
2496
+ throw new Error('Module not initialized. Call init() first.');
2497
+ }
2498
+ return module.rmsEnergy(samples, sampleRate, frameLength, hopLength);
2499
+ }
2500
+
2501
+ // ============================================================================
2502
+ // Features - Pitch
2503
+ // ============================================================================
2504
+
2505
+ /**
2506
+ * Detect pitch using YIN algorithm.
2507
+ *
2508
+ * @param samples - Audio samples (mono, float32)
2509
+ * @param sampleRate - Sample rate in Hz
2510
+ * @param frameLength - Frame length (default: 2048)
2511
+ * @param hopLength - Hop length (default: 512)
2512
+ * @param fmin - Minimum frequency in Hz (default: 65)
2513
+ * @param fmax - Maximum frequency in Hz (default: 2093)
2514
+ * @param threshold - YIN threshold (default: 0.3)
2515
+ * @returns Pitch detection result
2516
+ */
2517
+ export function pitchYin(
2518
+ samples: Float32Array,
2519
+ sampleRate: number,
2520
+ frameLength = 2048,
2521
+ hopLength = 512,
2522
+ fmin = 65.0,
2523
+ fmax = 2093.0,
2524
+ threshold = 0.3,
2525
+ ): PitchResult {
2526
+ if (!module) {
2527
+ throw new Error('Module not initialized. Call init() first.');
2528
+ }
2529
+ return module.pitchYin(samples, sampleRate, frameLength, hopLength, fmin, fmax, threshold);
2530
+ }
2531
+
2532
+ /**
2533
+ * Detect pitch using pYIN algorithm (probabilistic YIN with HMM smoothing).
2534
+ *
2535
+ * @param samples - Audio samples (mono, float32)
2536
+ * @param sampleRate - Sample rate in Hz
2537
+ * @param frameLength - Frame length (default: 2048)
2538
+ * @param hopLength - Hop length (default: 512)
2539
+ * @param fmin - Minimum frequency in Hz (default: 65)
2540
+ * @param fmax - Maximum frequency in Hz (default: 2093)
2541
+ * @param threshold - YIN threshold (default: 0.3)
2542
+ * @returns Pitch detection result
2543
+ */
2544
+ export function pitchPyin(
2545
+ samples: Float32Array,
2546
+ sampleRate: number,
2547
+ frameLength = 2048,
2548
+ hopLength = 512,
2549
+ fmin = 65.0,
2550
+ fmax = 2093.0,
2551
+ threshold = 0.3,
2552
+ ): PitchResult {
2553
+ if (!module) {
2554
+ throw new Error('Module not initialized. Call init() first.');
2555
+ }
2556
+ return module.pitchPyin(samples, sampleRate, frameLength, hopLength, fmin, fmax, threshold);
2557
+ }
2558
+
2559
+ // ============================================================================
2560
+ // Core - Unit Conversion
2561
+ // ============================================================================
2562
+
2563
+ /**
2564
+ * Convert frequency in Hz to Mel scale.
2565
+ *
2566
+ * @param hz - Frequency in Hz
2567
+ * @returns Mel frequency
2568
+ */
2569
+ export function hzToMel(hz: number): number {
2570
+ if (!module) {
2571
+ throw new Error('Module not initialized. Call init() first.');
2572
+ }
2573
+ return module.hzToMel(hz);
2574
+ }
2575
+
2576
+ /**
2577
+ * Convert Mel scale to frequency in Hz.
2578
+ *
2579
+ * @param mel - Mel frequency
2580
+ * @returns Frequency in Hz
2581
+ */
2582
+ export function melToHz(mel: number): number {
2583
+ if (!module) {
2584
+ throw new Error('Module not initialized. Call init() first.');
2585
+ }
2586
+ return module.melToHz(mel);
2587
+ }
2588
+
2589
+ /**
2590
+ * Convert frequency in Hz to MIDI note number.
2591
+ *
2592
+ * @param hz - Frequency in Hz
2593
+ * @returns MIDI note number (A4 = 440 Hz = 69)
2594
+ */
2595
+ export function hzToMidi(hz: number): number {
2596
+ if (!module) {
2597
+ throw new Error('Module not initialized. Call init() first.');
2598
+ }
2599
+ return module.hzToMidi(hz);
2600
+ }
2601
+
2602
+ /**
2603
+ * Convert MIDI note number to frequency in Hz.
2604
+ *
2605
+ * @param midi - MIDI note number
2606
+ * @returns Frequency in Hz
2607
+ */
2608
+ export function midiToHz(midi: number): number {
2609
+ if (!module) {
2610
+ throw new Error('Module not initialized. Call init() first.');
2611
+ }
2612
+ return module.midiToHz(midi);
2613
+ }
2614
+
2615
+ /**
2616
+ * Convert frequency in Hz to note name.
2617
+ *
2618
+ * @param hz - Frequency in Hz
2619
+ * @returns Note name (e.g., "A4", "C#5")
2620
+ */
2621
+ export function hzToNote(hz: number): string {
2622
+ if (!module) {
2623
+ throw new Error('Module not initialized. Call init() first.');
2624
+ }
2625
+ return module.hzToNote(hz);
2626
+ }
2627
+
2628
+ /**
2629
+ * Convert note name to frequency in Hz.
2630
+ *
2631
+ * @param note - Note name (e.g., "A4", "C#5")
2632
+ * @returns Frequency in Hz
2633
+ */
2634
+ export function noteToHz(note: string): number {
2635
+ if (!module) {
2636
+ throw new Error('Module not initialized. Call init() first.');
2637
+ }
2638
+ return module.noteToHz(note);
2639
+ }
2640
+
2641
+ /**
2642
+ * Convert frame index to time in seconds.
2643
+ *
2644
+ * @param frames - Frame index
2645
+ * @param sr - Sample rate in Hz
2646
+ * @param hopLength - Hop length in samples
2647
+ * @returns Time in seconds
2648
+ */
2649
+ export function framesToTime(frames: number, sr: number, hopLength: number): number {
2650
+ if (!module) {
2651
+ throw new Error('Module not initialized. Call init() first.');
2652
+ }
2653
+ return module.framesToTime(frames, sr, hopLength);
2654
+ }
2655
+
2656
+ /**
2657
+ * Convert time in seconds to frame index.
2658
+ *
2659
+ * @param time - Time in seconds
2660
+ * @param sr - Sample rate in Hz
2661
+ * @param hopLength - Hop length in samples
2662
+ * @returns Frame index
2663
+ */
2664
+ export function timeToFrames(time: number, sr: number, hopLength: number): number {
2665
+ if (!module) {
2666
+ throw new Error('Module not initialized. Call init() first.');
2667
+ }
2668
+ return module.timeToFrames(time, sr, hopLength);
2669
+ }
2670
+
2671
+ export function framesToSamples(frames: number, hopLength = 512, nFft = 0): number {
2672
+ if (!module) {
2673
+ throw new Error('Module not initialized. Call init() first.');
2674
+ }
2675
+ return module.framesToSamples(frames, hopLength, nFft);
2676
+ }
2677
+
2678
+ export function samplesToFrames(samples: number, hopLength = 512, nFft = 0): number {
2679
+ if (!module) {
2680
+ throw new Error('Module not initialized. Call init() first.');
2681
+ }
2682
+ return module.samplesToFrames(samples, hopLength, nFft);
2683
+ }
2684
+
2685
+ export function powerToDb(
2686
+ values: Float32Array,
2687
+ ref = 1.0,
2688
+ amin = 1e-10,
2689
+ topDb = 80.0,
2690
+ ): Float32Array {
2691
+ if (!module) {
2692
+ throw new Error('Module not initialized. Call init() first.');
2693
+ }
2694
+ return module.powerToDb(values, ref, amin, topDb);
2695
+ }
2696
+
2697
+ export function amplitudeToDb(
2698
+ values: Float32Array,
2699
+ ref = 1.0,
2700
+ amin = 1e-5,
2701
+ topDb = 80.0,
2702
+ ): Float32Array {
2703
+ if (!module) {
2704
+ throw new Error('Module not initialized. Call init() first.');
2705
+ }
2706
+ return module.amplitudeToDb(values, ref, amin, topDb);
2707
+ }
2708
+
2709
+ export function dbToPower(values: Float32Array, ref = 1.0): Float32Array {
2710
+ if (!module) {
2711
+ throw new Error('Module not initialized. Call init() first.');
2712
+ }
2713
+ return module.dbToPower(values, ref);
2714
+ }
2715
+
2716
+ export function dbToAmplitude(values: Float32Array, ref = 1.0): Float32Array {
2717
+ if (!module) {
2718
+ throw new Error('Module not initialized. Call init() first.');
2719
+ }
2720
+ return module.dbToAmplitude(values, ref);
2721
+ }
2722
+
2723
+ export function preemphasis(samples: Float32Array, coef = 0.97, zi?: number): Float32Array {
2724
+ if (!module) {
2725
+ throw new Error('Module not initialized. Call init() first.');
2726
+ }
2727
+ return module.preemphasis(samples, coef, zi ?? null);
2728
+ }
2729
+
2730
+ export function deemphasis(samples: Float32Array, coef = 0.97, zi?: number): Float32Array {
2731
+ if (!module) {
2732
+ throw new Error('Module not initialized. Call init() first.');
2733
+ }
2734
+ return module.deemphasis(samples, coef, zi ?? null);
2735
+ }
2736
+
2737
+ export function trimSilence(
2738
+ samples: Float32Array,
2739
+ topDb = 60.0,
2740
+ frameLength = 2048,
2741
+ hopLength = 512,
2742
+ ): WasmTrimResult {
2743
+ if (!module) {
2744
+ throw new Error('Module not initialized. Call init() first.');
2745
+ }
2746
+ return module.trimSilence(samples, topDb, frameLength, hopLength);
2747
+ }
2748
+
2749
+ export function splitSilence(
2750
+ samples: Float32Array,
2751
+ topDb = 60.0,
2752
+ frameLength = 2048,
2753
+ hopLength = 512,
2754
+ ): Int32Array {
2755
+ if (!module) {
2756
+ throw new Error('Module not initialized. Call init() first.');
2757
+ }
2758
+ return module.splitSilence(samples, topDb, frameLength, hopLength);
2759
+ }
2760
+
2761
+ export function frameSignal(
2762
+ samples: Float32Array,
2763
+ frameLength: number,
2764
+ hopLength: number,
2765
+ ): WasmFrameResult {
2766
+ if (!module) {
2767
+ throw new Error('Module not initialized. Call init() first.');
2768
+ }
2769
+ return module.frameSignal(samples, frameLength, hopLength);
2770
+ }
2771
+
2772
+ export function padCenter(values: Float32Array, size: number, padValue = 0.0): Float32Array {
2773
+ if (!module) {
2774
+ throw new Error('Module not initialized. Call init() first.');
2775
+ }
2776
+ return module.padCenter(values, size, padValue);
2777
+ }
2778
+
2779
+ export function fixLength(values: Float32Array, size: number, padValue = 0.0): Float32Array {
2780
+ if (!module) {
2781
+ throw new Error('Module not initialized. Call init() first.');
2782
+ }
2783
+ return module.fixLength(values, size, padValue);
2784
+ }
2785
+
2786
+ export function fixFrames(frames: Int32Array, xMin = 0, xMax = -1, pad = true): Int32Array {
2787
+ if (!module) {
2788
+ throw new Error('Module not initialized. Call init() first.');
2789
+ }
2790
+ return module.fixFrames(frames, xMin, xMax, pad);
2791
+ }
2792
+
2793
+ export function peakPick(
2794
+ values: Float32Array,
2795
+ preMax: number,
2796
+ postMax: number,
2797
+ preAvg: number,
2798
+ postAvg: number,
2799
+ delta: number,
2800
+ wait: number,
2801
+ ): Int32Array {
2802
+ if (!module) {
2803
+ throw new Error('Module not initialized. Call init() first.');
2804
+ }
2805
+ return module.peakPick(values, preMax, postMax, preAvg, postAvg, delta, wait);
2806
+ }
2807
+
2808
+ export function vectorNormalize(
2809
+ values: Float32Array,
2810
+ normType = 0,
2811
+ threshold = 1e-12,
2812
+ ): Float32Array {
2813
+ if (!module) {
2814
+ throw new Error('Module not initialized. Call init() first.');
2815
+ }
2816
+ return module.vectorNormalize(values, normType, threshold);
2817
+ }
2818
+
2819
+ export function pcen(
2820
+ values: Float32Array,
2821
+ nBins: number,
2822
+ nFrames: number,
2823
+ options: Record<string, number> = {},
2824
+ ): Float32Array {
2825
+ if (!module) {
2826
+ throw new Error('Module not initialized. Call init() first.');
2827
+ }
2828
+ return module.pcen(values, nBins, nFrames, options);
2829
+ }
2830
+
2831
+ export function tonnetz(chromagram: Float32Array, nChroma: number, nFrames: number): Float32Array {
2832
+ if (!module) {
2833
+ throw new Error('Module not initialized. Call init() first.');
2834
+ }
2835
+ return module.tonnetz(chromagram, nChroma, nFrames);
2836
+ }
2837
+
2838
+ export function tempogram(
2839
+ onsetEnvelope: Float32Array,
2840
+ sampleRate: number,
2841
+ hopLength = 512,
2842
+ winLength = 384,
2843
+ mode: TempogramMode = 'autocorrelation',
2844
+ ): WasmTempogramResult {
2845
+ if (!module) {
2846
+ throw new Error('Module not initialized. Call init() first.');
2847
+ }
2848
+ return module.tempogram(onsetEnvelope, sampleRate, hopLength, winLength, mode);
2849
+ }
2850
+
2851
+ export function cyclicTempogram(
2852
+ onsetEnvelope: Float32Array,
2853
+ sampleRate: number,
2854
+ hopLength = 512,
2855
+ winLength = 384,
2856
+ bpmMin = 60.0,
2857
+ nBins = 60,
2858
+ ): WasmCyclicTempogramResult {
2859
+ if (!module) {
2860
+ throw new Error('Module not initialized. Call init() first.');
2861
+ }
2862
+ return module.cyclicTempogram(onsetEnvelope, sampleRate, hopLength, winLength, bpmMin, nBins);
2863
+ }
2864
+
2865
+ export function plp(
2866
+ onsetEnvelope: Float32Array,
2867
+ sampleRate: number,
2868
+ hopLength = 512,
2869
+ tempoMin = 30.0,
2870
+ tempoMax = 300.0,
2871
+ winLength = 384,
2872
+ ): Float32Array {
2873
+ if (!module) {
2874
+ throw new Error('Module not initialized. Call init() first.');
2875
+ }
2876
+ return module.plp(onsetEnvelope, sampleRate, hopLength, tempoMin, tempoMax, winLength);
2877
+ }
2878
+
2879
+ /**
2880
+ * Compute NNLS (non-negative least squares) chromagram.
2881
+ *
2882
+ * @param samples - Audio samples (mono, float32)
2883
+ * @param sampleRate - Sample rate in Hz (default: 22050)
2884
+ * @returns NNLS chroma result
2885
+ */
2886
+ export function nnlsChroma(samples: Float32Array, sampleRate = 22050): WasmNnlsChromaResult {
2887
+ if (!module) {
2888
+ throw new Error('Module not initialized. Call init() first.');
2889
+ }
2890
+ return module.nnlsChroma(samples, sampleRate);
2891
+ }
2892
+
2893
+ /**
2894
+ * Compute the Constant-Q Transform magnitude.
2895
+ *
2896
+ * @param samples - Audio samples (mono, float32)
2897
+ * @param sampleRate - Sample rate in Hz (default: 22050)
2898
+ * @param hopLength - Hop length (default: 512)
2899
+ * @param fmin - Minimum frequency in Hz (default: 32.70319566257483, C1)
2900
+ * @param nBins - Number of frequency bins (default: 84)
2901
+ * @param binsPerOctave - Bins per octave (default: 12)
2902
+ * @returns CQT magnitude result
2903
+ */
2904
+ export function cqt(
2905
+ samples: Float32Array,
2906
+ sampleRate = 22050,
2907
+ hopLength = 512,
2908
+ fmin = 32.70319566257483,
2909
+ nBins = 84,
2910
+ binsPerOctave = 12,
2911
+ ): CqtResult {
2912
+ if (!module) {
2913
+ throw new Error('Module not initialized. Call init() first.');
2914
+ }
2915
+ return module.cqt(samples, sampleRate, hopLength, fmin, nBins, binsPerOctave);
2916
+ }
2917
+
2918
+ /**
2919
+ * Compute the Variable-Q Transform magnitude (gamma controls Q).
2920
+ *
2921
+ * @param samples - Audio samples (mono, float32)
2922
+ * @param sampleRate - Sample rate in Hz (default: 22050)
2923
+ * @param hopLength - Hop length (default: 512)
2924
+ * @param fmin - Minimum frequency in Hz (default: 32.70319566257483, C1)
2925
+ * @param nBins - Number of frequency bins (default: 84)
2926
+ * @param binsPerOctave - Bins per octave (default: 12)
2927
+ * @param gamma - Bandwidth offset; 0 is equivalent to CQT (default: 0)
2928
+ * @returns VQT magnitude result (same shape as CQT)
2929
+ */
2930
+ export function vqt(
2931
+ samples: Float32Array,
2932
+ sampleRate = 22050,
2933
+ hopLength = 512,
2934
+ fmin = 32.70319566257483,
2935
+ nBins = 84,
2936
+ binsPerOctave = 12,
2937
+ gamma = 0,
2938
+ ): CqtResult {
2939
+ if (!module) {
2940
+ throw new Error('Module not initialized. Call init() first.');
2941
+ }
2942
+ return module.vqt(samples, sampleRate, hopLength, fmin, nBins, binsPerOctave, gamma);
2943
+ }
2944
+
2945
+ /**
2946
+ * Detect song-structure sections (intro/verse/chorus/...).
2947
+ *
2948
+ * @param samples - Audio samples (mono, float32)
2949
+ * @param sampleRate - Sample rate in Hz (default: 22050)
2950
+ * @param nFft - FFT size (default: 2048)
2951
+ * @param hopLength - Hop length (default: 512)
2952
+ * @param minSectionSec - Minimum section duration in seconds (default: 8.0)
2953
+ * @returns Array of detected sections
2954
+ */
2955
+ export function analyzeSections(
2956
+ samples: Float32Array,
2957
+ sampleRate = 22050,
2958
+ nFft = 2048,
2959
+ hopLength = 512,
2960
+ minSectionSec = 8.0,
2961
+ ): Section[] {
2962
+ if (!module) {
2963
+ throw new Error('Module not initialized. Call init() first.');
2964
+ }
2965
+ return module
2966
+ .analyzeSections(samples, sampleRate, nFft, hopLength, minSectionSec)
2967
+ .map((s) => ({ ...s, type: s.type as SectionType }));
2968
+ }
2969
+
2970
+ /**
2971
+ * Extract the melody contour from monophonic audio via YIN.
2972
+ *
2973
+ * @param samples - Audio samples (mono, float32)
2974
+ * @param sampleRate - Sample rate in Hz (default: 22050)
2975
+ * @param fmin - Minimum frequency in Hz (default: 65.0)
2976
+ * @param fmax - Maximum frequency in Hz (default: 2093.0)
2977
+ * @param frameLength - Frame length in samples (default: 2048)
2978
+ * @param hopLength - Hop length (default: 512)
2979
+ * @param threshold - YIN threshold; lower is stricter (default: 0.1)
2980
+ * @returns Melody contour with per-frame pitch points and summary stats
2981
+ */
2982
+ export function analyzeMelody(
2983
+ samples: Float32Array,
2984
+ sampleRate = 22050,
2985
+ fmin = 65.0,
2986
+ fmax = 2093.0,
2987
+ frameLength = 2048,
2988
+ hopLength = 512,
2989
+ threshold = 0.1,
2990
+ ): MelodyResult {
2991
+ if (!module) {
2992
+ throw new Error('Module not initialized. Call init() first.');
2993
+ }
2994
+ return module.analyzeMelody(samples, sampleRate, fmin, fmax, frameLength, hopLength, threshold);
2995
+ }
2996
+
2997
+ /**
2998
+ * Compute the onset strength envelope.
2999
+ *
3000
+ * @param samples - Audio samples (mono, float32)
3001
+ * @param sampleRate - Sample rate in Hz (default: 22050)
3002
+ * @param nFft - FFT size (default: 2048)
3003
+ * @param hopLength - Hop length (default: 512)
3004
+ * @param nMels - Number of Mel bands (default: 128)
3005
+ * @returns Onset envelope for each frame
3006
+ */
3007
+ export function onsetEnvelope(
3008
+ samples: Float32Array,
3009
+ sampleRate = 22050,
3010
+ nFft = 2048,
3011
+ hopLength = 512,
3012
+ nMels = 128,
3013
+ ): Float32Array {
3014
+ if (!module) {
3015
+ throw new Error('Module not initialized. Call init() first.');
3016
+ }
3017
+ return module.onsetEnvelope(samples, sampleRate, nFft, hopLength, nMels);
3018
+ }
3019
+
3020
+ /**
3021
+ * Compute the Fourier tempogram from an onset envelope.
3022
+ *
3023
+ * @param onsetEnvelope - Onset strength envelope (float32)
3024
+ * @param sampleRate - Sample rate in Hz (default: 22050)
3025
+ * @param hopLength - Hop length (default: 512)
3026
+ * @param winLength - Window length in frames (default: 384)
3027
+ * @returns Fourier tempogram result
3028
+ */
3029
+ export function fourierTempogram(
3030
+ onsetEnvelope: Float32Array,
3031
+ sampleRate = 22050,
3032
+ hopLength = 512,
3033
+ winLength = 384,
3034
+ ): WasmFourierTempogramResult {
3035
+ if (!module) {
3036
+ throw new Error('Module not initialized. Call init() first.');
3037
+ }
3038
+ return module.fourierTempogram(onsetEnvelope, sampleRate, hopLength, winLength);
3039
+ }
3040
+
3041
+ /**
3042
+ * Compute tempogram ratio features.
3043
+ *
3044
+ * @param tempogramData - Tempogram data (float32)
3045
+ * @param winLength - Window length in frames (default: 384)
3046
+ * @param sampleRate - Sample rate in Hz (default: 22050)
3047
+ * @param hopLength - Hop length (default: 512)
3048
+ * @returns Tempogram ratio features
3049
+ */
3050
+ export function tempogramRatio(
3051
+ tempogramData: Float32Array,
3052
+ winLength = 384,
3053
+ sampleRate = 22050,
3054
+ hopLength = 512,
3055
+ ): Float32Array {
3056
+ if (!module) {
3057
+ throw new Error('Module not initialized. Call init() first.');
3058
+ }
3059
+ return module.tempogramRatio(tempogramData, winLength, sampleRate, hopLength);
3060
+ }
3061
+
3062
+ /**
3063
+ * Measure loudness (EBU R128 / ITU-R BS.1770).
3064
+ *
3065
+ * @param samples - Audio samples (mono, float32)
3066
+ * @param sampleRate - Sample rate in Hz (default: 22050)
3067
+ * @returns Loudness measurement result
3068
+ */
3069
+ export function lufs(samples: Float32Array, sampleRate = 22050): LufsResult {
3070
+ if (!module) {
3071
+ throw new Error('Module not initialized. Call init() first.');
3072
+ }
3073
+ return module.lufs(samples, sampleRate);
3074
+ }
3075
+
3076
+ /**
3077
+ * Compute the momentary loudness (LUFS) over time.
3078
+ *
3079
+ * @param samples - Audio samples (mono, float32)
3080
+ * @param sampleRate - Sample rate in Hz (default: 22050)
3081
+ * @returns Momentary LUFS values over time
3082
+ */
3083
+ export function momentaryLufs(samples: Float32Array, sampleRate = 22050): Float32Array {
3084
+ if (!module) {
3085
+ throw new Error('Module not initialized. Call init() first.');
3086
+ }
3087
+ return module.momentaryLufs(samples, sampleRate);
3088
+ }
3089
+
3090
+ /**
3091
+ * Compute the short-term loudness (LUFS) over time.
3092
+ *
3093
+ * @param samples - Audio samples (mono, float32)
3094
+ * @param sampleRate - Sample rate in Hz (default: 22050)
3095
+ * @returns Short-term LUFS values over time
3096
+ */
3097
+ export function shortTermLufs(samples: Float32Array, sampleRate = 22050): Float32Array {
3098
+ if (!module) {
3099
+ throw new Error('Module not initialized. Call init() first.');
3100
+ }
3101
+ return module.shortTermLufs(samples, sampleRate);
3102
+ }
3103
+
3104
+ // ============================================================================
3105
+ // Core - Resample
3106
+ // ============================================================================
3107
+
3108
+ /**
3109
+ * Resample audio to a different sample rate.
3110
+ *
3111
+ * @param samples - Audio samples (mono, float32)
3112
+ * @param srcSr - Source sample rate in Hz
3113
+ * @param targetSr - Target sample rate in Hz
3114
+ * @returns Resampled audio
3115
+ */
3116
+ export function resample(samples: Float32Array, srcSr: number, targetSr: number): Float32Array {
3117
+ if (!module) {
3118
+ throw new Error('Module not initialized. Call init() first.');
3119
+ }
3120
+ return module.resample(samples, srcSr, targetSr);
3121
+ }
3122
+
3123
+ // ============================================================================
3124
+ // Audio Class
3125
+ // ============================================================================
3126
+
3127
+ /**
3128
+ * Wrapper around audio data that exposes all analysis and feature functions as instance methods.
3129
+ *
3130
+ * @example
3131
+ * ```typescript
3132
+ * import { init, Audio } from '@libraz/sonare';
3133
+ *
3134
+ * await init();
3135
+ *
3136
+ * const audio = Audio.fromBuffer(samples, 44100);
3137
+ * console.log('BPM:', audio.detectBpm());
3138
+ * console.log('Key:', audio.detectKey().name);
3139
+ *
3140
+ * const mel = audio.melSpectrogram();
3141
+ * ```
3142
+ */
3143
+ export class Audio {
3144
+ private _samples: Float32Array;
3145
+ private _sampleRate: number;
3146
+
3147
+ private constructor(samples: Float32Array, sampleRate: number) {
3148
+ this._samples = samples;
3149
+ this._sampleRate = sampleRate;
3150
+ }
3151
+
3152
+ /** Create an Audio instance from raw sample data. */
3153
+ static fromBuffer(samples: Float32Array, sampleRate: number): Audio {
3154
+ return new Audio(samples, sampleRate);
3155
+ }
3156
+
3157
+ /** The raw audio samples. */
3158
+ get data(): Float32Array {
3159
+ return this._samples;
3160
+ }
3161
+
3162
+ /** Number of samples. */
3163
+ get length(): number {
3164
+ return this._samples.length;
3165
+ }
3166
+
3167
+ /** Sample rate in Hz. */
3168
+ get sampleRate(): number {
3169
+ return this._sampleRate;
3170
+ }
3171
+
3172
+ /** Duration in seconds. */
3173
+ get duration(): number {
3174
+ return this._samples.length / this._sampleRate;
3175
+ }
3176
+
3177
+ // -- Analysis --
3178
+
3179
+ detectBpm(): number {
3180
+ return detectBpm(this._samples, this._sampleRate);
3181
+ }
3182
+
3183
+ detectKey(options: KeyDetectionOptions = {}): Key {
3184
+ return detectKey(this._samples, this._sampleRate, options);
3185
+ }
3186
+
3187
+ detectKeyCandidates(options: KeyDetectionOptions = {}): KeyCandidate[] {
3188
+ return detectKeyCandidates(this._samples, this._sampleRate, options);
3189
+ }
3190
+
3191
+ detectOnsets(): Float32Array {
3192
+ return detectOnsets(this._samples, this._sampleRate);
3193
+ }
3194
+
3195
+ detectBeats(): Float32Array {
3196
+ return detectBeats(this._samples, this._sampleRate);
3197
+ }
3198
+
3199
+ detectDownbeats(): Float32Array {
3200
+ return detectDownbeats(this._samples, this._sampleRate);
3201
+ }
3202
+
3203
+ detectChords(options: ChordDetectionOptions = {}): ChordAnalysisResult {
3204
+ return detectChords(this._samples, this._sampleRate, options);
3205
+ }
3206
+
3207
+ analyze(): AnalysisResult {
3208
+ return analyze(this._samples, this._sampleRate);
3209
+ }
3210
+
3211
+ analyzeWithProgress(onProgress: ProgressCallback): AnalysisResult {
3212
+ return analyzeWithProgress(this._samples, this._sampleRate, onProgress);
3213
+ }
3214
+
3215
+ // -- Effects --
3216
+
3217
+ hpss(kernelHarmonic = 31, kernelPercussive = 31): HpssResult {
3218
+ return hpss(this._samples, this._sampleRate, kernelHarmonic, kernelPercussive);
3219
+ }
3220
+
3221
+ harmonic(): Float32Array {
3222
+ return harmonic(this._samples, this._sampleRate);
3223
+ }
3224
+
3225
+ percussive(): Float32Array {
3226
+ return percussive(this._samples, this._sampleRate);
3227
+ }
3228
+
3229
+ timeStretch(rate: number): Float32Array {
3230
+ return timeStretch(this._samples, this._sampleRate, rate);
3231
+ }
3232
+
3233
+ pitchShift(semitones: number): Float32Array {
3234
+ return pitchShift(this._samples, this._sampleRate, semitones);
3235
+ }
3236
+
3237
+ pitchCorrectToMidi(currentMidi: number, targetMidi: number): Float32Array {
3238
+ return pitchCorrectToMidi(this._samples, this._sampleRate, currentMidi, targetMidi);
3239
+ }
3240
+
3241
+ noteStretch(onsetSample: number, offsetSample: number, stretchRatio: number): Float32Array {
3242
+ return noteStretch(this._samples, this._sampleRate, onsetSample, offsetSample, stretchRatio);
3243
+ }
3244
+
3245
+ voiceChange(pitchSemitones: number, formantFactor: number): Float32Array {
3246
+ return voiceChange(this._samples, this._sampleRate, pitchSemitones, formantFactor);
3247
+ }
3248
+
3249
+ normalize(targetDb = 0.0): Float32Array {
3250
+ return normalize(this._samples, this._sampleRate, targetDb);
3251
+ }
3252
+
3253
+ mastering(targetLufs = -14.0, ceilingDb = -1.0, truePeakOversample = 4): MasteringResult {
3254
+ return mastering(this._samples, this._sampleRate, targetLufs, ceilingDb, truePeakOversample);
3255
+ }
3256
+
3257
+ masteringChain(config: MasteringChainConfig): MasteringChainResult {
3258
+ return masteringChain(this._samples, this._sampleRate, config);
3259
+ }
3260
+
3261
+ masterAudio(
3262
+ presetName: MasteringPreset,
3263
+ overrides: Record<string, number | boolean> | null = null,
3264
+ ): MasteringChainResult {
3265
+ return masterAudio(this._samples, this._sampleRate, presetName, overrides);
3266
+ }
3267
+
3268
+ masteringProcess(
3269
+ processorName: SoloProcessor,
3270
+ params: MasteringProcessorParams = {},
3271
+ ): MasteringResult {
3272
+ return masteringProcess(processorName, this._samples, this._sampleRate, params);
3273
+ }
3274
+
3275
+ trim(thresholdDb = -60.0): Float32Array {
3276
+ return trim(this._samples, this._sampleRate, thresholdDb);
3277
+ }
3278
+
3279
+ // -- Features --
3280
+
3281
+ stft(nFft = 2048, hopLength = 512): StftResult {
3282
+ return stft(this._samples, this._sampleRate, nFft, hopLength);
3283
+ }
3284
+
3285
+ stftDb(nFft = 2048, hopLength = 512): { nBins: number; nFrames: number; db: Float32Array } {
3286
+ return stftDb(this._samples, this._sampleRate, nFft, hopLength);
3287
+ }
3288
+
3289
+ melSpectrogram(nFft = 2048, hopLength = 512, nMels = 128): MelSpectrogramResult {
3290
+ return melSpectrogram(this._samples, this._sampleRate, nFft, hopLength, nMels);
3291
+ }
3292
+
3293
+ mfcc(nFft = 2048, hopLength = 512, nMels = 128, nMfcc = 13): MfccResult {
3294
+ return mfcc(this._samples, this._sampleRate, nFft, hopLength, nMels, nMfcc);
3295
+ }
3296
+
3297
+ chroma(nFft = 2048, hopLength = 512): ChromaResult {
3298
+ return chroma(this._samples, this._sampleRate, nFft, hopLength);
3299
+ }
3300
+
3301
+ nnlsChroma(): WasmNnlsChromaResult {
3302
+ return nnlsChroma(this._samples, this._sampleRate);
3303
+ }
3304
+
3305
+ onsetEnvelope(nFft = 2048, hopLength = 512, nMels = 128): Float32Array {
3306
+ return onsetEnvelope(this._samples, this._sampleRate, nFft, hopLength, nMels);
3307
+ }
3308
+
3309
+ lufs(): LufsResult {
3310
+ return lufs(this._samples, this._sampleRate);
3311
+ }
3312
+
3313
+ momentaryLufs(): Float32Array {
3314
+ return momentaryLufs(this._samples, this._sampleRate);
3315
+ }
3316
+
3317
+ shortTermLufs(): Float32Array {
3318
+ return shortTermLufs(this._samples, this._sampleRate);
3319
+ }
3320
+
3321
+ spectralCentroid(nFft = 2048, hopLength = 512): Float32Array {
3322
+ return spectralCentroid(this._samples, this._sampleRate, nFft, hopLength);
3323
+ }
3324
+
3325
+ spectralBandwidth(nFft = 2048, hopLength = 512): Float32Array {
3326
+ return spectralBandwidth(this._samples, this._sampleRate, nFft, hopLength);
3327
+ }
3328
+
3329
+ spectralRolloff(nFft = 2048, hopLength = 512, rollPercent = 0.85): Float32Array {
3330
+ return spectralRolloff(this._samples, this._sampleRate, nFft, hopLength, rollPercent);
3331
+ }
3332
+
3333
+ spectralFlatness(nFft = 2048, hopLength = 512): Float32Array {
3334
+ return spectralFlatness(this._samples, this._sampleRate, nFft, hopLength);
3335
+ }
3336
+
3337
+ zeroCrossingRate(frameLength = 2048, hopLength = 512): Float32Array {
3338
+ return zeroCrossingRate(this._samples, this._sampleRate, frameLength, hopLength);
3339
+ }
3340
+
3341
+ rmsEnergy(frameLength = 2048, hopLength = 512): Float32Array {
3342
+ return rmsEnergy(this._samples, this._sampleRate, frameLength, hopLength);
3343
+ }
3344
+
3345
+ pitchYin(
3346
+ frameLength = 2048,
3347
+ hopLength = 512,
3348
+ fmin = 65.0,
3349
+ fmax = 2093.0,
3350
+ threshold = 0.3,
3351
+ ): PitchResult {
3352
+ return pitchYin(this._samples, this._sampleRate, frameLength, hopLength, fmin, fmax, threshold);
3353
+ }
3354
+
3355
+ pitchPyin(
3356
+ frameLength = 2048,
3357
+ hopLength = 512,
3358
+ fmin = 65.0,
3359
+ fmax = 2093.0,
3360
+ threshold = 0.3,
3361
+ ): PitchResult {
3362
+ return pitchPyin(
3363
+ this._samples,
3364
+ this._sampleRate,
3365
+ frameLength,
3366
+ hopLength,
3367
+ fmin,
3368
+ fmax,
3369
+ threshold,
3370
+ );
3371
+ }
3372
+
3373
+ resample(targetSr: number): Float32Array {
3374
+ return resample(this._samples, this._sampleRate, targetSr);
3375
+ }
3376
+ }
3377
+
3378
+ // ============================================================================
3379
+ // StreamAnalyzer Class
3380
+ // ============================================================================
3381
+
3382
+ /**
3383
+ * Real-time streaming audio analyzer.
3384
+ *
3385
+ * @example
3386
+ * ```typescript
3387
+ * import { init, StreamAnalyzer } from '@libraz/sonare';
3388
+ *
3389
+ * await init();
3390
+ *
3391
+ * const analyzer = new StreamAnalyzer({ sampleRate: 44100 });
3392
+ *
3393
+ * // In audio processing callback
3394
+ * analyzer.process(samples);
3395
+ *
3396
+ * // Get current analysis state
3397
+ * const stats = analyzer.stats();
3398
+ * console.log('BPM:', stats.estimate.bpm);
3399
+ * console.log('Key:', stats.estimate.key);
3400
+ * console.log('Chord progression:', stats.estimate.chordProgression);
3401
+ * ```
3402
+ */
3403
+ export class StreamAnalyzer {
3404
+ private analyzer: WasmStreamAnalyzer;
3405
+
3406
+ /**
3407
+ * Create a new StreamAnalyzer.
3408
+ *
3409
+ * @param config - Configuration options
3410
+ */
3411
+ constructor(config: StreamConfig) {
3412
+ if (!module) {
3413
+ throw new Error('Module not initialized. Call init() first.');
3414
+ }
3415
+ const wasmModule = module;
3416
+ const args = [
3417
+ config.sampleRate,
3418
+ config.nFft ?? 2048,
3419
+ config.hopLength ?? 512,
3420
+ config.nMels ?? 128,
3421
+ config.fmin ?? 0,
3422
+ config.fmax ?? 0,
3423
+ config.tuningRefHz ?? 440,
3424
+ config.computeMagnitude ?? true,
3425
+ config.computeMel ?? true,
3426
+ config.computeChroma ?? true,
3427
+ config.computeOnset ?? true,
3428
+ config.computeSpectral ?? true,
3429
+ config.emitEveryNFrames ?? 1,
3430
+ config.magnitudeDownsample ?? 1,
3431
+ config.keyUpdateIntervalSec ?? 5,
3432
+ config.bpmUpdateIntervalSec ?? 10,
3433
+ config.window ?? 0,
3434
+ config.outputFormat ?? 0,
3435
+ ] as const;
3436
+ const isArityError = (error: unknown): boolean => {
3437
+ const message = String((error as { message?: unknown } | null)?.message ?? error);
3438
+ return message.includes('invalid number of parameters');
3439
+ };
3440
+ const createLegacy = (): WasmStreamAnalyzer => {
3441
+ const LegacyStreamAnalyzer = wasmModule.StreamAnalyzer as unknown as new (
3442
+ sampleRate: number,
3443
+ nFft: number,
3444
+ hopLength: number,
3445
+ nMels: number,
3446
+ computeMel: boolean,
3447
+ computeChroma: boolean,
3448
+ computeOnset: boolean,
3449
+ emitEveryNFrames: number,
3450
+ ) => WasmStreamAnalyzer;
3451
+ return new LegacyStreamAnalyzer(
3452
+ args[0],
3453
+ args[1],
3454
+ args[2],
3455
+ args[3],
3456
+ args[8],
3457
+ args[9],
3458
+ args[10],
3459
+ args[12],
3460
+ );
3461
+ };
3462
+ const hasExtendedConfig =
3463
+ config.fmin !== undefined ||
3464
+ config.fmax !== undefined ||
3465
+ config.tuningRefHz !== undefined ||
3466
+ config.computeMagnitude !== undefined ||
3467
+ config.computeSpectral !== undefined ||
3468
+ config.magnitudeDownsample !== undefined ||
3469
+ config.keyUpdateIntervalSec !== undefined ||
3470
+ config.bpmUpdateIntervalSec !== undefined ||
3471
+ config.window !== undefined ||
3472
+ config.outputFormat !== undefined;
3473
+ if (hasExtendedConfig) {
3474
+ try {
3475
+ this.analyzer = new wasmModule.StreamAnalyzer(...args);
3476
+ } catch (error) {
3477
+ if (!isArityError(error)) {
3478
+ throw error;
3479
+ }
3480
+ this.analyzer = createLegacy();
3481
+ }
3482
+ } else {
3483
+ try {
3484
+ this.analyzer = createLegacy();
3485
+ } catch (error) {
3486
+ if (!isArityError(error)) {
3487
+ throw error;
3488
+ }
3489
+ this.analyzer = new wasmModule.StreamAnalyzer(...args);
3490
+ }
3491
+ }
3492
+ }
3493
+
3494
+ /**
3495
+ * Process audio samples.
3496
+ *
3497
+ * @param samples - Audio samples (mono, float32)
3498
+ */
3499
+ process(samples: Float32Array): void {
3500
+ this.analyzer.process(samples);
3501
+ }
3502
+
3503
+ /**
3504
+ * Process audio samples with explicit sample offset.
3505
+ *
3506
+ * @param samples - Audio samples (mono, float32)
3507
+ * @param sampleOffset - Cumulative sample count at start of this chunk
3508
+ */
3509
+ processWithOffset(samples: Float32Array, sampleOffset: number): void {
3510
+ this.analyzer.processWithOffset(samples, sampleOffset);
3511
+ }
3512
+
3513
+ /**
3514
+ * Get the number of frames available to read.
3515
+ */
3516
+ availableFrames(): number {
3517
+ return this.analyzer.availableFrames();
3518
+ }
3519
+
3520
+ /**
3521
+ * Read processed frames as Structure of Arrays.
3522
+ *
3523
+ * @param maxFrames - Maximum number of frames to read
3524
+ * @returns Frame buffer with analysis results
3525
+ */
3526
+ readFrames(maxFrames: number): FrameBuffer {
3527
+ return this.analyzer.readFramesSoa(maxFrames);
3528
+ }
3529
+
3530
+ readFramesU8(maxFrames: number): StreamFramesU8 {
3531
+ return this.analyzer.readFramesU8(maxFrames) as StreamFramesU8;
3532
+ }
3533
+
3534
+ readFramesI16(maxFrames: number): StreamFramesI16 {
3535
+ return this.analyzer.readFramesI16(maxFrames) as StreamFramesI16;
3536
+ }
3537
+
3538
+ /**
3539
+ * Reset the analyzer state.
3540
+ *
3541
+ * @param baseSampleOffset - Starting sample offset (default 0)
3542
+ */
3543
+ reset(baseSampleOffset = 0): void {
3544
+ this.analyzer.reset(baseSampleOffset);
3545
+ }
3546
+
3547
+ /**
3548
+ * Get current statistics and progressive estimates.
3549
+ *
3550
+ * @returns Analyzer statistics including BPM, key, and chord progression
3551
+ */
3552
+ stats(): AnalyzerStats {
3553
+ const s = this.analyzer.stats();
3554
+ return {
3555
+ totalFrames: s.totalFrames,
3556
+ totalSamples: s.totalSamples,
3557
+ durationSeconds: s.durationSeconds,
3558
+ estimate: {
3559
+ bpm: s.estimate.bpm,
3560
+ bpmConfidence: s.estimate.bpmConfidence,
3561
+ bpmCandidateCount: s.estimate.bpmCandidateCount,
3562
+ key: s.estimate.key as PitchClass,
3563
+ keyMinor: s.estimate.keyMinor,
3564
+ keyConfidence: s.estimate.keyConfidence,
3565
+ chordRoot: s.estimate.chordRoot as PitchClass,
3566
+ chordQuality: s.estimate.chordQuality as ChordQuality,
3567
+ chordConfidence: s.estimate.chordConfidence,
3568
+ chordStartTime: s.estimate.chordStartTime,
3569
+ chordProgression: s.estimate.chordProgression.map((c) => ({
3570
+ root: c.root as PitchClass,
3571
+ quality: c.quality as ChordQuality,
3572
+ startTime: c.startTime,
3573
+ confidence: c.confidence,
3574
+ })),
3575
+ barChordProgression: s.estimate.barChordProgression.map((c) => ({
3576
+ barIndex: c.barIndex,
3577
+ root: c.root as PitchClass,
3578
+ quality: c.quality as ChordQuality,
3579
+ startTime: c.startTime,
3580
+ confidence: c.confidence,
3581
+ })),
3582
+ currentBar: s.estimate.currentBar,
3583
+ barDuration: s.estimate.barDuration,
3584
+ votedPattern: (s.estimate.votedPattern || []).map((c) => ({
3585
+ barIndex: c.barIndex,
3586
+ root: c.root as PitchClass,
3587
+ quality: c.quality as ChordQuality,
3588
+ startTime: c.startTime,
3589
+ confidence: c.confidence,
3590
+ })),
3591
+ patternLength: s.estimate.patternLength,
3592
+ detectedPatternName: s.estimate.detectedPatternName || '',
3593
+ detectedPatternScore: s.estimate.detectedPatternScore || 0,
3594
+ allPatternScores: (s.estimate.allPatternScores || []).map((p) => ({
3595
+ name: p.name,
3596
+ score: p.score,
3597
+ })),
3598
+ accumulatedSeconds: s.estimate.accumulatedSeconds,
3599
+ usedFrames: s.estimate.usedFrames,
3600
+ updated: s.estimate.updated,
3601
+ },
3602
+ };
3603
+ }
3604
+
3605
+ /**
3606
+ * Get total frames processed.
3607
+ */
3608
+ frameCount(): number {
3609
+ return this.analyzer.frameCount();
3610
+ }
3611
+
3612
+ /**
3613
+ * Get current time position in seconds.
3614
+ */
3615
+ currentTime(): number {
3616
+ return this.analyzer.currentTime();
3617
+ }
3618
+
3619
+ /**
3620
+ * Get the sample rate.
3621
+ */
3622
+ sampleRate(): number {
3623
+ return this.analyzer.sampleRate();
3624
+ }
3625
+
3626
+ /**
3627
+ * Set the expected total duration for pattern lock timing.
3628
+ *
3629
+ * @param durationSeconds - Total duration in seconds
3630
+ */
3631
+ setExpectedDuration(durationSeconds: number): void {
3632
+ this.analyzer.setExpectedDuration(durationSeconds);
3633
+ }
3634
+
3635
+ /**
3636
+ * Set normalization gain for loud/compressed audio.
3637
+ *
3638
+ * @param gain - Gain factor to apply (e.g., 0.5 for -6dB reduction)
3639
+ */
3640
+ setNormalizationGain(gain: number): void {
3641
+ this.analyzer.setNormalizationGain(gain);
3642
+ }
3643
+
3644
+ /**
3645
+ * Set tuning reference frequency for non-standard tuning.
3646
+ *
3647
+ * @param refHz - Reference frequency for A4 (default 440 Hz)
3648
+ * @example
3649
+ * // If audio is 1 semitone sharp (A4 = 466.16 Hz)
3650
+ * analyzer.setTuningRefHz(466.16);
3651
+ * // If audio is 1 semitone flat (A4 = 415.30 Hz)
3652
+ * analyzer.setTuningRefHz(415.30);
3653
+ */
3654
+ setTuningRefHz(refHz: number): void {
3655
+ this.analyzer.setTuningRefHz(refHz);
3656
+ }
3657
+
3658
+ /**
3659
+ * Release resources. Call when done using the analyzer.
3660
+ */
3661
+ dispose(): void {
3662
+ this.analyzer.delete();
3663
+ }
3664
+ }
3665
+
3666
+ // ============================================================================
3667
+ // Re-exports
3668
+ // ============================================================================
3669
+
3670
+ export { PitchClass as Pitch } from './public_types';