-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaudio-client.mjs
630 lines (574 loc) · 14.6 KB
/
audio-client.mjs
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
622
623
624
625
626
627
628
629
630
import {OpusAudioEncoder, OpusAudioDecoder, Mp3AudioEncoder, Mp3AudioDecoder} from './ws-codec.mjs';
import {WsMediaStreamAudioReader, FakeAudioData} from './ws-codec-util.mjs';
import {AudioOutput} from './audio-classes.mjs';
import {getEncodedAudioChunkBuffer, getAudioDataBuffer} from './audio-util.mjs';
// opus stream -> decoded output audio node
export function createOpusAudioOutputStream({
audioContext,
codecs,
}) {
if (!audioContext) {
throw new Error('missing audio context');
}
if (!codecs) {
throw new Error('missing codecs');
}
const audioWorkletNode = new AudioWorkletNode(
audioContext,
'ws-output-worklet',
);
audioWorkletNode.addEventListener('processorerror', e => {
console.log('audioWorkletNode processorerror', e);
});
audioWorkletNode.port.onmessage = e => {
// console.log('audio worklet node message', e.data);
const {
method,
} = e.data;
switch (method) {
case 'finish': {
// console.log('finish', performance.now());
audioWorkletNode.dispatchEvent(new MessageEvent('finish'));
break;
}
default: {
console.warn('opus audio stream got unknown method', method);
break;
}
}
};
const audioDecoder = new OpusAudioDecoder({
sampleRate: audioContext.sampleRate,
output: data => {
if (data) {
// console.log('decoded data', structuredClone(data?.data), performance.now());
data = getAudioDataBuffer(data);
audioWorkletNode.port.postMessage(data, [data.buffer]);
} else {
audioWorkletNode.port.postMessage(null);
}
},
});
return {
outputNode: audioWorkletNode,
audioDecoder,
write(data) {
// console.log('decode data', structuredClone(data));
audioDecoder.decode(data);
},
end() {
// console.log('decode end');
audioDecoder.decode(null);
}
// close() {
// audioWorkletNode.disconnect();
// audioDecoder.close();
// },
};
}
// media stream -> encoded opus audio output
export function createOpusMicrophoneSource({
mediaStream,
audioContext,
codecs,
}) {
if (!audioContext) {
throw new Error('missing audio context');
}
if (!mediaStream) {
throw new Error('missing media stream');
}
if (!codecs) {
throw new Error('missing codecs');
}
const output = new AudioOutput();
const muxAndSend = encodedChunk => {
if (encodedChunk.data) {
const data = getEncodedAudioChunkBuffer(encodedChunk);
output.write(data);
} else {
output.end();
}
};
function onEncoderError(err) {
console.warn('encoder error', err);
}
const audioEncoder = new OpusAudioEncoder({
sampleRate: audioContext.sampleRate,
codecs,
output: muxAndSend,
error: onEncoderError,
});
const audioReader = new WsMediaStreamAudioReader(mediaStream, {
audioContext,
});
async function readAndEncode() {
const result = await audioReader.read();
if (!result.done) {
audioEncoder.encode(result.value);
readAndEncode();
} else {
audioEncoder.encode(new FakeAudioData());
}
}
readAndEncode();
const id = crypto.randomUUID();
return {
id,
output,
mediaStream,
audioReader,
audioEncoder,
close() {
audioReader.cancel();
// note: the encoder will close itself on an end packet
// audioEncoder.close();
},
};
};
// media stream -> pcm (Float32) 48000 audio output
export function createPcmF32MicrophoneSource({
mediaStream,
audioContext,
}) {
if (!audioContext) {
throw new Error('missing audio context');
}
if (!mediaStream) {
throw new Error('missing media stream');
}
const output = new AudioOutput();
const audioReader = new WsMediaStreamAudioReader(mediaStream, {
audioContext,
sampleRate: 48000,
});
const _readLoop = async () => {
for (;;) {
const result = await audioReader.read();
if (!result.done) {
output.write(result.value.data);
} else {
output.end();
break;
}
}
};
_readLoop();
const id = crypto.randomUUID();
return {
id,
output,
mediaStream,
audioReader,
// audioEncoder,
close() {
audioReader.cancel();
// note: the encoder will close itself on an end packet
// audioEncoder.close();
},
};
};
// samples readable stream -> encoded opus audio output
export function createOpusReadableStreamSource({
readableStream,
// audioContext,
codecs,
}) {
if (!readableStream) {
throw new Error('missing readable stream');
}
if (!codecs) {
throw new Error('missing codecs');
}
const {sampleRate} = readableStream;
if (!sampleRate) {
throw new Error('createOpusReadableStreamSource: missing sample rate on readable stream');
}
// create output
const output = new AudioOutput();
// create encoder
const muxAndSend = encodedChunk => {
if (encodedChunk.data) {
const data = getEncodedAudioChunkBuffer(encodedChunk);
output.write(data);
} else {
output.end();
}
};
function onEncoderError(err) {
console.warn('encoder error', err);
}
const audioEncoder = new OpusAudioEncoder({
sampleRate,
codecs,
output: muxAndSend,
error: onEncoderError,
});
// read the stream
(async () => {
const fakeAudioData = new FakeAudioData();
const reader = readableStream.getReader();
for (;;) {
const {done, value} = await reader.read();
if (!done) {
fakeAudioData.set(value);
audioEncoder.encode(fakeAudioData);
} else {
fakeAudioData.set(null);
audioEncoder.encode(fakeAudioData);
break;
}
}
})();
// return result
const id = crypto.randomUUID();
return {
id,
output,
audioEncoder,
close() {
audioReader.cancel();
// note: the encoder will close itself on an end packet
// audioEncoder.close();
},
};
}
// samples readable stream -> encoded mp3 audio output
export function createMp3ReadableStreamSource({
readableStream,
// audioContext,
codecs,
}) {
if (!readableStream) {
throw new Error('missing readable stream');
}
if (!codecs) {
throw new Error('missing codecs');
}
const {sampleRate} = readableStream;
if (!sampleRate) {
throw new Error('createMp3ReadableStreamSource: missing sample rate on stream');
}
// create output
const output = new AudioOutput();
// create encoder
const muxAndSend = encodedChunk => {
if (encodedChunk.data) {
const data = getEncodedAudioChunkBuffer(encodedChunk);
output.write(data);
} else {
output.end();
}
};
function onEncoderError(err) {
console.warn('encoder error', err);
}
const audioEncoder = new Mp3AudioEncoder({
sampleRate,
codecs,
output: muxAndSend,
error: onEncoderError,
});
// read the stream
(async () => {
const fakeAudioData = new FakeAudioData();
const reader = readableStream.getReader();
for (;;) {
const {done, value} = await reader.read();
if (!done) {
fakeAudioData.set(value);
audioEncoder.encode(fakeAudioData);
} else {
fakeAudioData.set(null);
audioEncoder.encode(fakeAudioData);
break;
}
}
})();
// return result
const id = crypto.randomUUID();
return {
id,
output,
audioEncoder,
close() {
audioReader.cancel();
// note: the encoder will close itself on an end packet
// audioEncoder.close();
},
};
}
// media stream -> encoded mp3 audio output
export function createMp3MicrophoneSource({
mediaStream,
audioContext,
codecs,
}) {
const output = new AudioOutput();
const muxAndSend = encodedChunk => {
if (encodedChunk.data) {
const data = getEncodedAudioChunkBuffer(encodedChunk);
output.write(data);
} else {
output.end();
}
};
function onEncoderError(err) {
console.warn('mp3 encoder error', err);
}
const audioEncoder = new Mp3AudioEncoder({
sampleRate: audioContext.sampleRate,
output: muxAndSend,
error: onEncoderError,
});
const audioReader = new WsMediaStreamAudioReader(mediaStream, {
audioContext,
codecs,
});
async function readAndEncode() {
const result = await audioReader.read();
if (!result.done) {
audioEncoder.encode(result.value);
readAndEncode();
} else {
audioEncoder.encode(new FakeAudioData());
}
}
readAndEncode();
const id = crypto.randomUUID();
return {
id,
output,
mediaStream,
audioReader,
audioEncoder,
close() {
audioReader.cancel();
// note: the encoder will close itself on an end packet
// audioEncoder.close();
},
};
}
//
// DECODER STREAMS
//
export function createMp3DecodeTransformStream({
sampleRate,
format = 'f32',
transferBuffers,
codecs,
}) {
if (!sampleRate) {
throw new Error('missing sample rate');
}
if (!format) {
throw new Error('missing format');
}
if (!codecs) {
throw new Error('missing codecs');
}
let controller;
const {
promise: donePromise,
resolve: doneResolve,
reject: doneReject,
} = Promise.withResolvers();
const transformStream = new TransformStream({
start: (c) => {
controller = c;
},
transform: (chunk) => {
// console.log('decoding data', chunk);
audioDecoder.decode(chunk);
},
flush: async () => {
audioDecoder.decode(null);
await donePromise;
},
});
const muxAndSend = encodedChunk => {
// console.log('decoded data', encodedChunk);
if (encodedChunk) {
controller.enqueue(encodedChunk.data);
} else {
doneResolve();
}
};
function onDecoderError(err) {
console.warn('mp3 decoder error', err);
}
const audioDecoder = new Mp3AudioDecoder({
sampleRate,
format,
codecs,
transferBuffers,
output: muxAndSend,
error: onDecoderError,
});
transformStream.readable.sampleRate = sampleRate;
transformStream.readable.format = format;
transformStream.abort = (reason) => {
transformStream.readable.cancel(reason);
transformStream.writable.abort(reason);
audioDecoder.close();
};
return transformStream;
}
export function createOpusDecodeTransformStream({
sampleRate,
format = 'f32',
codecs,
}) {
if (!sampleRate) {
throw new Error('missing sample rate');
}
if (!format) {
throw new Error('missing format');
}
if (!codecs) {
throw new Error('missing codecs');
}
let controller;
const {
promise: donePromise,
resolve: doneResolve,
reject: doneReject,
} = Promise.withResolvers();
const transformStream = new TransformStream({
start: (c) => {
controller = c;
},
transform: (chunk) => {
// console.log('decode data 1', chunk);
audioDecoder.decode(chunk);
},
flush: async () => {
audioDecoder.decode(null);
await donePromise;
},
});
const muxAndSend = encodedChunk => {
if (encodedChunk) {
// console.log('decode data', encodedChunk.data);
controller.enqueue(encodedChunk.data);
} else {
doneResolve();
}
};
function onDecoderError(err) {
console.warn('opus decoder error', err);
}
const audioDecoder = new OpusAudioDecoder({
sampleRate,
format,
codecs,
output: muxAndSend,
error: onDecoderError,
});
transformStream.readable.sampleRate = sampleRate;
transformStream.readable.format = format;
transformStream.abort = (reason) => {
transformStream.readable.cancel(reason);
transformStream.writable.abort(reason);
audioDecoder.close();
};
return transformStream;
}
export function createPcmF32TransformStream({
sampleRate,
format = 'f32',
}) {
if (!sampleRate) {
throw new Error('missing sample rate');
}
if (!format) {
throw new Error('missing format');
}
throw new Error('not implemented');
// let controller;
const transformStream = new TransformStream({
start: c => {
controller = c;
},
transform: (chunk, controller) => {
console.log('decode pcm', chunk);
// const formatted = formatSamples(output, format, 'i16');
},
flush: async controller => {
console.log('flush pcm');
// await donePromise;
},
});
transformStream.readable.sampleRate = sampleRate;
transformStream.readable.format = format;
transformStream.abort = (reason) => {
transformStream.readable.cancel(reason);
transformStream.writable.abort(reason);
};
return transformStream;
}
//
// ENCODER STREAMS
//
export function createMp3EncodeTransformStream({
sampleRate,
transferBuffers,
codecs,
}) {
if (!sampleRate) {
throw new Error('missing sample rate');
}
if (!codecs) {
throw new Error('missing codecs');
}
let controller;
const {
promise: donePromise,
resolve: doneResolve,
reject: doneReject,
} = Promise.withResolvers();
const transformStream = new TransformStream({
start: (c) => {
controller = c;
},
transform: (chunk) => {
const audioData = new FakeAudioData();
audioData.data = new Float32Array(chunk.buffer, chunk.byteOffset, chunk.byteLength / Float32Array.BYTES_PER_ELEMENT);
audioEncoder.encode(audioData);
},
flush: async () => {
// console.log('flush');
audioEncoder.encode(new FakeAudioData());
await donePromise;
},
});
// create encoder
const muxAndSend = encodedChunk => {
// console.log('mux and send', encodedChunk);
if (encodedChunk.data) {
const data = getEncodedAudioChunkBuffer(encodedChunk);
// output.write(data);
controller.enqueue(data);
} else {
// output.end();
doneResolve();
}
};
function onEncoderError(err) {
console.warn('mp3 encoder error', err);
}
const audioEncoder = new Mp3AudioEncoder({
sampleRate,
transferBuffers,
codecs,
output: muxAndSend,
error: onEncoderError,
});
transformStream.readable.sampleRate = sampleRate;
transformStream.abort = (reason) => {
transformStream.readable.cancel(reason);
transformStream.writable.abort(reason);
audioEncoder.close();
};
return transformStream;
}