forked from Lab-Lab-Lab/CPR-Music
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAudioProcessor.js
More file actions
621 lines (525 loc) Β· 22 KB
/
AudioProcessor.js
File metadata and controls
621 lines (525 loc) Β· 22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
// components/audio/DAW/Multitrack/AudioProcessor.js
'use client';
import { decodeAudioFromURL } from './AudioEngine';
import { debugLog, debugWarn, debugError, debugGroup, debugGroupEnd, DebugTimer } from '../../../../lib/debug';
// Audio processing constants
const AUDIO_CONSTANTS = {
/** Default sample rate for audio processing (CD quality) */
DEFAULT_SAMPLE_RATE: 44100,
/** Default samples per pixel for waveform peak generation */
DEFAULT_SAMPLES_PER_PIXEL: 256,
/** Worker processing timeout in milliseconds */
WORKER_TIMEOUT_MS: 30000,
/** Bytes per sample for Float32 audio data */
BYTES_PER_SAMPLE: 4,
/** Conversion factor for bytes to kilobytes */
BYTES_TO_KB: 1024,
};
/**
* Hybrid Audio Processor - Uses Web Workers when available, falls back to main thread
* Provides consistent API regardless of implementation method
*/
class AudioProcessor {
constructor() {
this.worker = null;
this.workerSupported = this.checkWorkerSupport();
this.processingQueue = new Map(); // clipId -> { resolve, reject, onProgress }
this.stats = { workerJobs: 0, mainThreadJobs: 0, errors: 0, fallbacks: 0, workerRestarts: 0 };
// Worker recovery configuration
this.workerRecovery = {
maxRetries: 3, // Maximum worker restart attempts
currentRetries: 0, // Current retry count
cooldownMs: 5000, // Initial cooldown before retry (5 seconds)
maxCooldownMs: 60000, // Maximum cooldown (1 minute)
recoveryScheduled: false, // Whether recovery is scheduled
lastFailureTime: null, // Last failure timestamp
consecutiveFailures: 0, // Consecutive failures without success
};
debugLog('AudioProcessor', 'ποΈ Initializing hybrid audio processing system');
debugLog('AudioProcessor', `π Worker Support: ${this.workerSupported ? 'β
Available' : 'β Not available'}`);
if (this.workerSupported) {
this.initializeWorker();
} else {
debugLog('AudioProcessor', 'π Will use main thread fallback for all audio processing');
}
}
/**
* Check if Web Workers are supported and available
*/
checkWorkerSupport() {
try {
return typeof Worker !== 'undefined' &&
typeof OfflineAudioContext !== 'undefined' &&
typeof window !== 'undefined';
} catch (e) {
debugWarn('AudioProcessor', 'π Web Workers not supported, using fallback method');
return false;
}
}
/**
* Initialize Web Worker if supported
*/
initializeWorker() {
try {
// Create worker from inline script to avoid external file dependencies
const workerCode = this.getWorkerCode();
const blob = new Blob([workerCode], { type: 'application/javascript' });
const workerUrl = URL.createObjectURL(blob);
this.worker = new Worker(workerUrl);
this.worker.onmessage = this.handleWorkerMessage.bind(this);
this.worker.onerror = this.handleWorkerError.bind(this);
debugLog('AudioProcessor', 'π Web Worker initialized successfully');
// Clean up blob URL
setTimeout(() => URL.revokeObjectURL(workerUrl), 1000);
} catch (e) {
debugWarn('AudioProcessor', 'π Failed to initialize Web Worker, using fallback:', e);
this.workerSupported = false;
this.worker = null;
}
}
/**
* Handle messages from Web Worker
*/
handleWorkerMessage(event) {
const { type, clipId, ...data } = event.data;
const processing = this.processingQueue.get(clipId);
if (!processing) return;
switch (type) {
case 'progress':
processing.onProgress?.(data.stage, data.progress);
break;
case 'success':
processing.resolve({
duration: data.duration,
peaks: data.peaks,
method: 'worker'
});
this.processingQueue.delete(clipId);
break;
case 'error':
processing.reject(new Error(data.error));
this.processingQueue.delete(clipId);
break;
case 'decode-failed':
// Worker fetched audio but couldn't decode (Firefox/Safari lack
// OfflineAudioContext in workers). Decode on main thread using
// the already-fetched data to avoid a second network request.
debugLog('AudioProcessor', `π Main-thread decode for ${clipId} (worker transferred data)`);
processing.onProgress?.('decoding', 70);
{
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
audioCtx.decodeAudioData(data.arrayBuffer)
.then(audioBuffer => {
const peaks = this.generateSimplePeaks(audioBuffer);
processing.resolve({ duration: audioBuffer.duration, peaks, method: 'worker-fetch-main-decode' });
})
.catch(err => {
processing.reject(new Error('Main-thread decode failed: ' + err.message));
})
.finally(() => {
this.processingQueue.delete(clipId);
});
}
break;
}
}
/**
* Handle Web Worker errors with recovery mechanism
*/
handleWorkerError(error) {
debugError('AudioProcessor', 'π₯ Web Worker error:', error);
// Track failure
this.workerRecovery.lastFailureTime = Date.now();
this.workerRecovery.consecutiveFailures++;
// Fallback all pending operations to main thread
const pendingOps = Array.from(this.processingQueue.entries());
this.processingQueue.clear();
this.stats.fallbacks += pendingOps.length;
debugLog('AudioProcessor', `π Falling back ${pendingOps.length} pending operations to main thread`);
for (const [clipId, { resolve, reject, onProgress, audioUrl }] of pendingOps) {
debugLog('AudioProcessor', `π Fallback processing: ${clipId}`);
this.processOnMainThread(audioUrl, clipId, onProgress)
.then(resolve)
.catch(reject);
}
// Terminate failed worker
if (this.worker) {
this.worker.terminate();
this.worker = null;
}
// Determine if we should attempt recovery
const canRecover = this.workerRecovery.currentRetries < this.workerRecovery.maxRetries;
if (canRecover && !this.workerRecovery.recoveryScheduled) {
this.scheduleWorkerRecovery();
} else if (!canRecover) {
// Permanently disable worker after max retries
this.workerSupported = false;
debugWarn('AudioProcessor', `β οΈ Web Worker permanently disabled after ${this.workerRecovery.maxRetries} failed recovery attempts`);
}
}
/**
* Schedule worker recovery with exponential backoff
*/
scheduleWorkerRecovery() {
if (this.workerRecovery.recoveryScheduled) return;
this.workerRecovery.recoveryScheduled = true;
this.workerRecovery.currentRetries++;
// Calculate cooldown with exponential backoff
const backoffMultiplier = Math.pow(2, this.workerRecovery.currentRetries - 1);
const cooldownMs = Math.min(
this.workerRecovery.cooldownMs * backoffMultiplier,
this.workerRecovery.maxCooldownMs
);
debugLog('AudioProcessor', `π Scheduling worker recovery attempt ${this.workerRecovery.currentRetries}/${this.workerRecovery.maxRetries} in ${cooldownMs / 1000}s`);
setTimeout(() => {
this.attemptWorkerRecovery();
}, cooldownMs);
}
/**
* Attempt to recover the Web Worker
*/
attemptWorkerRecovery() {
this.workerRecovery.recoveryScheduled = false;
if (!this.workerSupported) {
debugLog('AudioProcessor', 'π Recovery skipped - worker support disabled');
return;
}
debugLog('AudioProcessor', `π Attempting worker recovery (attempt ${this.workerRecovery.currentRetries}/${this.workerRecovery.maxRetries})`);
try {
this.initializeWorker();
if (this.worker) {
this.stats.workerRestarts++;
debugLog('AudioProcessor', 'β
Worker recovery successful!');
// Reset consecutive failures on successful recovery
this.workerRecovery.consecutiveFailures = 0;
} else {
debugWarn('AudioProcessor', 'β Worker recovery failed - worker initialization returned null');
// Schedule another recovery if we have retries left
if (this.workerRecovery.currentRetries < this.workerRecovery.maxRetries) {
this.scheduleWorkerRecovery();
} else {
this.workerSupported = false;
debugWarn('AudioProcessor', 'β οΈ Web Worker permanently disabled after exhausting recovery attempts');
}
}
} catch (e) {
debugError('AudioProcessor', 'β Worker recovery threw error:', e);
// Schedule another recovery if we have retries left
if (this.workerRecovery.currentRetries < this.workerRecovery.maxRetries) {
this.scheduleWorkerRecovery();
} else {
this.workerSupported = false;
debugWarn('AudioProcessor', 'β οΈ Web Worker permanently disabled after exhausting recovery attempts');
}
}
}
/**
* Reset worker recovery state (call after sustained successful operations)
*/
resetRecoveryState() {
if (this.workerRecovery.consecutiveFailures === 0 &&
this.workerRecovery.currentRetries > 0 &&
this.stats.workerJobs > 5) {
debugLog('AudioProcessor', 'β
Resetting worker recovery state after sustained success');
this.workerRecovery.currentRetries = 0;
}
}
/**
* Main API: Process audio file with automatic worker/fallback selection
*/
async processAudioFile(audioUrl, clipId, onProgress = () => {}) {
const timer = new DebugTimer('AudioProcessor', `Processing ${clipId}`);
debugLog('AudioProcessor', `π΅ Starting processing for ${clipId}`);
debugLog('AudioProcessor', `π File URL: ${audioUrl.substring(0, 50)}...`);
try {
let result;
if (this.workerSupported && this.worker) {
debugLog('AudioProcessor', `π Using Web Worker for ${clipId}`);
this.stats.workerJobs++;
result = await this.processWithWorker(audioUrl, clipId, onProgress);
// Reset recovery state after successful worker operations
this.resetRecoveryState();
} else {
debugLog('AudioProcessor', `π Using main thread fallback for ${clipId}`);
this.stats.mainThreadJobs++;
result = await this.processOnMainThread(audioUrl, clipId, onProgress);
}
timer.end();
debugLog('AudioProcessor', `π Duration: ${result.duration?.toFixed(2)}s, Peaks: ${result.peaks?.length || 0} samples`);
debugLog('AudioProcessor', `π Stats: Worker=${this.stats.workerJobs}, MainThread=${this.stats.mainThreadJobs}, Errors=${this.stats.errors}, Fallbacks=${this.stats.fallbacks}, Restarts=${this.stats.workerRestarts}`);
return result;
} catch (error) {
this.stats.errors++;
timer.end();
debugError('AudioProcessor', `β Failed ${clipId}:`, error);
debugLog('AudioProcessor', `π Stats: Worker=${this.stats.workerJobs}, MainThread=${this.stats.mainThreadJobs}, Errors=${this.stats.errors}, Fallbacks=${this.stats.fallbacks}`);
throw error;
}
}
/**
* Process using Web Worker (true non-blocking)
*/
processWithWorker(audioUrl, clipId, onProgress) {
return new Promise((resolve, reject) => {
// Store processing context
this.processingQueue.set(clipId, {
resolve,
reject,
onProgress,
audioUrl,
method: 'worker'
});
// Send work to worker
this.worker.postMessage({
type: 'process',
clipId,
audioUrl
});
// Timeout safety net
setTimeout(() => {
if (this.processingQueue.has(clipId)) {
this.processingQueue.delete(clipId);
reject(new Error('Worker processing timeout'));
}
}, AUDIO_CONSTANTS.WORKER_TIMEOUT_MS);
});
}
/**
* Fallback: Process on main thread (progressive loading approach)
*/
async processOnMainThread(audioUrl, clipId, onProgress) {
const timer = new DebugTimer('AudioProcessor', `Main Thread - ${clipId}`);
debugLog('AudioProcessor', `π Main Thread: Starting ${clipId}`);
try {
onProgress('reading', 10);
debugLog('AudioProcessor', `π Main Thread: Reading file for ${clipId}`);
// Still show progress updates even though it's blocking
await this.delay(50); // Allow UI to update
onProgress('reading', 30);
await this.delay(50);
onProgress('decoding', 50);
debugLog('AudioProcessor', `π§ Main Thread: Starting audio decode for ${clipId} (THIS MAY BLOCK UI)`);
timer.checkpoint('decode-start');
// This is the blocking operation
const audioBuffer = await decodeAudioFromURL(audioUrl);
const duration = audioBuffer ? audioBuffer.duration : 0;
timer.checkpoint(`decode-complete (${duration?.toFixed(2)}s)`);
onProgress('generating-peaks', 80);
await this.delay(50);
debugLog('AudioProcessor', `π Main Thread: Generating peaks for ${clipId}`);
// Generate simple peaks (could be optimized further)
const peaks = this.generateSimplePeaks(audioBuffer);
timer.checkpoint(`peaks-generated (${peaks.length} samples)`);
onProgress('complete', 100);
timer.end();
return {
duration,
peaks,
method: 'main-thread'
};
} catch (error) {
timer.end();
debugError('AudioProcessor', `β Main Thread: Failed ${clipId}:`, error);
onProgress('error', 100);
throw error;
}
}
/**
* Generate simple peaks on main thread
* Optimized to pre-allocate array and avoid repeated object creation in hot loop
*/
generateSimplePeaks(audioBuffer, samplesPerPixel = AUDIO_CONSTANTS.DEFAULT_SAMPLES_PER_PIXEL) {
if (!audioBuffer) return [];
const ch = 0; // use first channel
const data = audioBuffer.getChannelData(ch);
const total = data.length;
const step = Math.max(1, Math.floor(total / Math.max(1, Math.floor(total / samplesPerPixel))));
// Pre-calculate array size and allocate upfront to avoid repeated reallocation
const peakCount = Math.ceil(total / step);
const peaks = new Array(peakCount);
let peakIndex = 0;
for (let i = 0; i < total; i += step) {
let min = 1.0;
let max = -1.0;
const end = Math.min(i + step, total);
for (let j = i; j < end; j++) {
const v = data[j];
if (v < min) min = v;
if (v > max) max = v;
}
peaks[peakIndex++] = [min, max];
}
// Trim if we over-allocated (shouldn't happen but defensive)
if (peakIndex < peakCount) {
peaks.length = peakIndex;
}
return peaks;
}
/**
* Utility: Non-blocking delay
*/
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* Web Worker code as string (to avoid external file dependencies)
*/
getWorkerCode() {
return `
// Audio processing worker constants
const WORKER_CONSTANTS = {
DEFAULT_SAMPLE_RATE: 44100,
DEFAULT_SAMPLES_PER_PIXEL: 256,
BYTES_TO_KB: 1024,
};
// Audio processing worker
console.log('π Worker: Audio processing worker initialized');
self.onmessage = async function(event) {
const { type, clipId, audioUrl } = event.data;
if (type === 'process') {
const startTime = performance.now();
console.log('π Worker: Starting processing for', clipId);
console.log('π Worker: File URL:', audioUrl.substring(0, 50) + '...');
try {
// Report progress
self.postMessage({ type: 'progress', clipId, stage: 'reading', progress: 20 });
console.log('π Worker: Reading file for', clipId);
const fetchStart = performance.now();
const response = await fetch(audioUrl);
if (!response.ok) throw new Error('Failed to fetch audio');
const fetchTime = Math.round(performance.now() - fetchStart);
console.log('π Worker: File fetched in', fetchTime + 'ms for', clipId);
self.postMessage({ type: 'progress', clipId, stage: 'reading', progress: 40 });
const bufferStart = performance.now();
const arrayBuffer = await response.arrayBuffer();
const bufferTime = Math.round(performance.now() - bufferStart);
console.log('π Worker: ArrayBuffer created in', bufferTime + 'ms for', clipId, '(' + Math.round(arrayBuffer.byteLength / WORKER_CONSTANTS.BYTES_TO_KB) + 'KB)');
self.postMessage({ type: 'progress', clipId, stage: 'decoding', progress: 60 });
console.log('π§ Worker: Starting audio decode for', clipId);
// OfflineAudioContext is not available in Web Workers on Firefox/Safari.
// If decode fails, transfer the fetched data back so the main thread
// can decode without re-fetching.
try {
const decodeStart = performance.now();
const sampleRate = WORKER_CONSTANTS.DEFAULT_SAMPLE_RATE;
const offlineCtx = new OfflineAudioContext(2, sampleRate, sampleRate);
const audioBuffer = await offlineCtx.decodeAudioData(arrayBuffer);
const decodeTime = Math.round(performance.now() - decodeStart);
console.log('π§ Worker: Decode completed in', decodeTime + 'ms for', clipId, '(duration:', audioBuffer.duration.toFixed(2) + 's)');
self.postMessage({ type: 'progress', clipId, stage: 'generating-peaks', progress: 85 });
console.log('π Worker: Generating peaks for', clipId);
const peaksStart = performance.now();
const peaks = generatePeaks(audioBuffer, WORKER_CONSTANTS.DEFAULT_SAMPLES_PER_PIXEL);
const peaksTime = Math.round(performance.now() - peaksStart);
console.log('π Worker: Peaks generated in', peaksTime + 'ms for', clipId, '(' + peaks.length + ' samples)');
const totalTime = Math.round(performance.now() - startTime);
console.log('β
Worker: Completed', clipId, 'in', totalTime + 'ms total');
self.postMessage({
type: 'success',
clipId,
duration: audioBuffer.duration,
peaks
});
} catch (decodeError) {
console.warn('β οΈ Worker: Decode failed for', clipId, '- transferring data to main thread:', decodeError.message);
self.postMessage({
type: 'decode-failed',
clipId,
arrayBuffer: arrayBuffer
}, [arrayBuffer]);
}
} catch (error) {
const totalTime = Math.round(performance.now() - startTime);
console.error('β Worker: Failed', clipId, 'after', totalTime + 'ms:', error);
self.postMessage({
type: 'error',
clipId,
error: error.message
});
}
}
};
function generatePeaks(audioBuffer, samplesPerPixel = WORKER_CONSTANTS.DEFAULT_SAMPLES_PER_PIXEL) {
const ch = 0;
const data = audioBuffer.getChannelData(ch);
const total = data.length;
const step = Math.max(1, Math.floor(total / Math.max(1, Math.floor(total / samplesPerPixel))));
const peaks = [];
for (let i = 0; i < total; i += step) {
let min = 1.0;
let max = -1.0;
for (let j = 0; j < step && i + j < total; j++) {
const v = data[i + j];
if (v < min) min = v;
if (v > max) max = v;
}
peaks.push([min, max]);
}
return peaks;
}
`;
}
/**
* Get processing statistics
*/
getStats() {
return {
...this.stats,
workerSupported: this.workerSupported,
workerActive: !!(this.workerSupported && this.worker),
pendingJobs: this.processingQueue.size,
recovery: {
retriesUsed: this.workerRecovery.currentRetries,
maxRetries: this.workerRecovery.maxRetries,
consecutiveFailures: this.workerRecovery.consecutiveFailures,
recoveryPending: this.workerRecovery.recoveryScheduled,
lastFailure: this.workerRecovery.lastFailureTime,
}
};
}
/**
* Print comprehensive stats to console
*/
printStats() {
const stats = this.getStats();
debugGroup('AudioProcessor', 'π Performance Stats');
debugLog('AudioProcessor', `π Web Worker Jobs: ${stats.workerJobs}`);
debugLog('AudioProcessor', `π Main Thread Jobs: ${stats.mainThreadJobs}`);
debugLog('AudioProcessor', `β Failed Jobs: ${stats.errors}`);
debugLog('AudioProcessor', `π Fallback Operations: ${stats.fallbacks}`);
debugLog('AudioProcessor', `π Worker Restarts: ${stats.workerRestarts}`);
debugLog('AudioProcessor', `β‘ Worker Support: ${stats.workerSupported ? 'β
' : 'β'}`);
debugLog('AudioProcessor', `π§ Worker Active: ${stats.workerActive ? 'β
' : 'β'}`);
debugLog('AudioProcessor', `β³ Pending Jobs: ${stats.pendingJobs}`);
debugLog('AudioProcessor', `π Total Jobs: ${stats.workerJobs + stats.mainThreadJobs}`);
debugLog('AudioProcessor', `πͺ Worker Usage: ${stats.workerJobs + stats.mainThreadJobs > 0 ? Math.round((stats.workerJobs / (stats.workerJobs + stats.mainThreadJobs)) * 100) : 0}%`);
debugLog('AudioProcessor', `π Recovery: ${stats.recovery.retriesUsed}/${stats.recovery.maxRetries} retries used, ${stats.recovery.consecutiveFailures} consecutive failures`);
debugGroupEnd();
}
/**
* Cleanup resources
*/
dispose() {
debugLog('AudioProcessor', 'π§Ή Cleaning up resources...');
this.printStats();
if (this.worker) {
debugLog('AudioProcessor', 'π Terminating Web Worker...');
this.worker.terminate();
this.worker = null;
}
if (this.processingQueue.size > 0) {
debugWarn('AudioProcessor', `β οΈ Disposing with ${this.processingQueue.size} pending operations`);
}
this.processingQueue.clear();
debugLog('AudioProcessor', 'β
Cleanup complete');
}
}
// Create singleton instance
let audioProcessor = null;
export function getAudioProcessor() {
if (!audioProcessor) {
audioProcessor = new AudioProcessor();
}
return audioProcessor;
}
export default AudioProcessor;