-
Notifications
You must be signed in to change notification settings - Fork 477
/
RedundantAudioEncoder.ts
1500 lines (1307 loc) · 56.7 KB
/
RedundantAudioEncoder.ts
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
export default class RedundantAudioEncoder {
// Each payload must be less than 1024 bytes to fit the 10 bit block length
private readonly maxRedPacketSizeBytes = 1 << 10;
// Limit payload to 1000 bytes to handle small MTU. 1000 is chosen because in Chromium-based browsers, writing audio
// payloads larger than 1000 bytes using the WebRTC Insertable Streams API (which is used to enable dynamic audio
// redundancy) will cause an error to be thrown and cause audio flow to permanently stop. See
// https://crbug.com/1248479.
private readonly maxAudioPayloadSizeBytes = 1000;
// Each payload can encode a timestamp delta of 14 bits
private readonly maxRedTimestampOffset = 1 << 14;
// 4 byte RED header
private readonly redHeaderSizeBytes = 4;
// reduced size for last RED header
private readonly redLastHeaderSizeBytes = 1;
// P-Time for Opus 20 msec packets
// We do not support other p-times or clock rates
private readonly redPacketizationTime = 960;
// distance between redundant payloads, Opus FEC handles a distance of 1
// TODO(https://issues.amazon.com/issues/ChimeSDKAudio-55):
// Consider making this dynamic
private readonly redPacketDistance = 2;
// maximum number of redundant payloads per RTP packet
private readonly maxRedEncodings = 2;
// Maximum number of encodings that can be recovered with a single RED packet, assuming the primary and redundant
// payloads have FEC.
private readonly redMaxRecoveryDistance = this.redPacketDistance * this.maxRedEncodings + 1;
// maximum history of prior payloads to keep
// generally we will expire old entries based on timestamp
// this limit is in place just to make sure the history does not
// grow too large in the case of erroneous timestamp inputs
private readonly maxEncodingHistorySize = 10;
// Holds the RED payload type obtained from the local SDP
// This is updated when the transceiver controller sends
// a message of type RedPayloadType
private redPayloadType: number;
// Holds the RED payload type obtained from the local SDP
// This is updated when the transceiver controller sends
// a message of type RedPayloadType
private opusPayloadType: number;
// Current number of encodings we want to send
// to the remote end. This will be dynamically
// updated through the setNumEncodingsFromPacketloss API
private numRedundantEncodings: number = 0;
// Holds a history of primary payloads in order
// oldest to newest
private encodingHistory: Array<RedundantAudioEncoder.Encoding>;
// Used to enable or disable redundancy
// in response to very high packet loss events
private redundancyEnabled: boolean = true;
// This is a workaround for unit testing due to issues with mocking `self`
// which is a part of DedicatedWorker scope and is currently used to post
// messages to the main thread
static shouldLog: boolean = false;
// This is a workaround for unit testing due to issues with mocking `self`
// which is a part of DedicatedWorker scope and is currently used to post
// messages to the main thread
static shouldReportStats: boolean = false;
constructor() {
this.encodingHistory = new Array<RedundantAudioEncoder.Encoding>();
this.opusPayloadType = 0;
this.redPayloadType = 0;
this.initializePacketLogs();
}
/**
* Creates an instance of RedundantAudioEncoder and sets up callbacks.
*/
static initializeWorker(): void {
RedundantAudioEncoder.log('Initializing RedundantAudioEncoder');
const encoder = new RedundantAudioEncoder();
// RED encoding is done using WebRTC Encoded Transform
// https://github.com/w3c/webrtc-encoded-transform/blob/main/explainer.md
// Check the DedicatedWorkerGlobalScope for existence of
// RTCRtpScriptTransformer interface. If exists, then
// RTCRtpScriptTransform is supported by this browser.
// @ts-ignore
if (self.RTCRtpScriptTransformer) {
// @ts-ignore
self.onrtctransform = (event: RTCTransformEvent) => {
if (event.transformer.options.type === 'SenderTransform') {
encoder.setupSenderTransform(event.transformer.readable, event.transformer.writable);
} else if (event.transformer.options.type === 'ReceiverTransform') {
encoder.setupReceiverTransform(event.transformer.readable, event.transformer.writable);
} else if (event.transformer.options.type === 'PassthroughTransform') {
encoder.setupPassthroughTransform(event.transformer.readable, event.transformer.writable);
}
};
}
self.onmessage = (event: MessageEvent) => {
if (event.data.msgType === 'StartRedWorker') {
encoder.setupSenderTransform(event.data.send.readable, event.data.send.writable);
encoder.setupReceiverTransform(event.data.receive.readable, event.data.receive.writable);
} else if (event.data.msgType === 'PassthroughTransform') {
encoder.setupPassthroughTransform(event.data.send.readable, event.data.send.writable);
encoder.setupPassthroughTransform(event.data.receive.readable, event.data.receive.writable);
} else if (event.data.msgType === 'RedPayloadType') {
encoder.setRedPayloadType(event.data.payloadType);
} else if (event.data.msgType === 'OpusPayloadType') {
encoder.setOpusPayloadType(event.data.payloadType);
} else if (event.data.msgType === 'UpdateNumRedundantEncodings') {
encoder.setNumRedundantEncodings(event.data.numRedundantEncodings);
} else if (event.data.msgType === 'Enable') {
encoder.setRedundancyEnabled(true);
} else if (event.data.msgType === 'Disable') {
encoder.setRedundancyEnabled(false);
}
};
}
/**
* Post logs to the main thread
*/
static log(msg: string): void {
if (RedundantAudioEncoder.shouldLog) {
// @ts-ignore
self.postMessage({
type: 'REDWorkerLog',
log: `[AudioRed] ${msg}`,
});
}
}
/**
* Returns the number of encodings based on packetLoss value. This is used by `DefaultTransceiverController` to
* determine when to alert the encoder to update the number of encodings. It also determines if we need to
* turn off red in cases of very high packet loss to avoid congestion collapse.
*/
static getNumRedundantEncodingsForPacketLoss(packetLoss: number): [number, boolean] {
let recommendedRedundantEncodings = 0;
let shouldTurnOffRed = false;
if (packetLoss <= 8) {
recommendedRedundantEncodings = 0;
} else if (packetLoss <= 18) {
recommendedRedundantEncodings = 1;
} else if (packetLoss <= 75) {
recommendedRedundantEncodings = 2;
} else {
recommendedRedundantEncodings = 0;
shouldTurnOffRed = true;
}
return [recommendedRedundantEncodings, shouldTurnOffRed];
}
/**
* Sets up a passthrough (no-op) transform for the given streams.
*/
setupPassthroughTransform(readable: ReadableStream, writable: WritableStream): void {
RedundantAudioEncoder.log('Setting up passthrough transform');
readable.pipeTo(writable);
}
/**
* Sets up the transform stream and pipes the outgoing encoded audio frames through the transform function.
*/
setupSenderTransform(readable: ReadableStream, writable: WritableStream): void {
RedundantAudioEncoder.log('Setting up sender RED transform');
const transformStream = new TransformStream({
transform: this.senderTransform.bind(this),
});
readable.pipeThrough(transformStream).pipeTo(writable);
return;
}
/**
* Sets up the transform stream and pipes the received encoded audio frames through the transform function.
*/
setupReceiverTransform(readable: ReadableStream, writable: WritableStream): void {
RedundantAudioEncoder.log('Setting up receiver RED transform');
const transformStream = new TransformStream({
transform: this.receivePacketLogTransform.bind(this),
});
readable.pipeThrough(transformStream).pipeTo(writable);
return;
}
/**
* Set the RED payload type ideally obtained from local offer.
*/
setRedPayloadType(payloadType: number): void {
this.redPayloadType = payloadType;
RedundantAudioEncoder.log(`red payload type set to ${this.redPayloadType}`);
}
/**
* Set the opus payload type ideally obtained from local offer.
*/
setOpusPayloadType(payloadType: number): void {
this.opusPayloadType = payloadType;
RedundantAudioEncoder.log(`opus payload type set to ${this.opusPayloadType}`);
}
/**
* Set the number of redundant encodings
*/
setNumRedundantEncodings(numRedundantEncodings: number): void {
this.numRedundantEncodings = numRedundantEncodings;
if (this.numRedundantEncodings > this.maxRedEncodings) {
this.numRedundantEncodings = this.maxRedEncodings;
}
RedundantAudioEncoder.log(`Updated numRedundantEncodings to ${this.numRedundantEncodings}`);
}
/**
* Enable or disable redundancy in response to
* high packet loss event.
*/
setRedundancyEnabled(enabled: boolean): void {
this.redundancyEnabled = enabled;
RedundantAudioEncoder.log(`redundancy ${this.redundancyEnabled ? 'enabled' : 'disabled'}`);
}
/**
* Helper function to only enqueue audio frames if they do not exceed the audio payload byte limit imposed by
* Chromium-based browsers. Chromium will throw an error (https://crbug.com/1248479) if an audio payload larger than
* 1000 bytes is enqueued. Any controller that attempts to enqueue an audio payload larger than 1000 bytes will
* encounter this error and will permanently stop sending or receiving audio.
*/
private enqueueAudioFrameIfPayloadSizeIsValid(
// @ts-ignore
frame: RTCEncodedAudioFrame,
controller: TransformStreamDefaultController
): void {
if (frame.data.byteLength > this.maxAudioPayloadSizeBytes) return;
controller.enqueue(frame);
}
/**
* Receives encoded frames and modifies as needed before sending to transport.
*/
private senderTransform(
// @ts-ignore
frame: RTCEncodedAudioFrame,
controller: TransformStreamDefaultController
): void {
const frameMetadata = frame.getMetadata();
// @ts-ignore
if (frameMetadata.payloadType !== this.redPayloadType) {
this.enqueueAudioFrameIfPayloadSizeIsValid(frame, controller);
return;
}
const primaryPayloadBuffer = this.getPrimaryPayload(frame.timestamp, frame.data);
if (!primaryPayloadBuffer) {
this.enqueueAudioFrameIfPayloadSizeIsValid(frame, controller);
return;
}
const encodedBuffer = this.encode(frame.timestamp, primaryPayloadBuffer);
/* istanbul ignore next */
if (!encodedBuffer) {
this.enqueueAudioFrameIfPayloadSizeIsValid(frame, controller);
return;
}
frame.data = encodedBuffer;
this.enqueueAudioFrameIfPayloadSizeIsValid(frame, controller);
return;
}
/**
* Get the primary payload from encoding
*/
private getPrimaryPayload(primaryTimestamp: number, frame: ArrayBuffer): ArrayBuffer | null {
const encodings = this.splitEncodings(primaryTimestamp, frame);
if (!encodings || encodings.length < 1) return null;
return encodings[encodings.length - 1].payload;
}
/**
* Split up the encoding received into primary and redundant encodings
* These will be ordered oldest to newest which is the same ordering
* in the RTP red payload.
*/
private splitEncodings(
primaryTimestamp: number,
frame: ArrayBuffer,
getFecInfo: boolean = false,
primarySequenceNumber: number = undefined
): RedundantAudioEncoder.Encoding[] | null {
// process RED headers (according to RFC 2198)
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |F| block PT | timestamp offset | block length |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
// last header
// 0 1 2 3 4 5 6 7
// +-+-+-+-+-+-+-+-+
// |0| Block PT |
// +-+-+-+-+-+-+-+-+
const payload = new DataView(frame);
let payloadSizeBytes = payload.byteLength;
let totalPayloadSizeBytes = 0;
let totalHeaderSizeBytes = 0;
let primaryPayloadSizeBytes = 0;
let payloadOffset = 0;
let gotLastBlock = false;
const encodings = new Array<RedundantAudioEncoder.Encoding>();
const redundantEncodingBlockLengths = new Array();
const redundantEncodingTimestamps = new Array();
while (payloadSizeBytes > 0) {
gotLastBlock = (payload.getUint8(payloadOffset) & 0x80) === 0;
if (gotLastBlock) {
// Bits 1 through 7 are payload type
const payloadType = payload.getUint8(payloadOffset) & 0x7f;
// Unexpected payload type. This is a bad packet.
if (payloadType !== this.opusPayloadType) {
return null;
}
totalPayloadSizeBytes += this.redLastHeaderSizeBytes;
totalHeaderSizeBytes += this.redLastHeaderSizeBytes;
// Accumulated block lengths are equal to or larger than the buffer, which means there is no primary block. This
// is a bad packet.
if (totalPayloadSizeBytes >= payload.byteLength) {
return null;
}
primaryPayloadSizeBytes = payload.byteLength - totalPayloadSizeBytes;
break;
} else {
if (payloadSizeBytes < this.redHeaderSizeBytes) {
return null;
}
// Bits 22 through 31 are payload length
const blockLength =
((payload.getUint8(payloadOffset + 2) & 0x03) << 8) + payload.getUint8(payloadOffset + 3);
redundantEncodingBlockLengths.push(blockLength);
const timestampOffset = payload.getUint16(payloadOffset + 1) >> 2;
const timestamp = primaryTimestamp - timestampOffset;
redundantEncodingTimestamps.push(timestamp);
totalPayloadSizeBytes += blockLength + this.redHeaderSizeBytes;
totalHeaderSizeBytes += this.redHeaderSizeBytes;
payloadOffset += this.redHeaderSizeBytes;
payloadSizeBytes -= this.redHeaderSizeBytes;
}
}
// The last block was never found. This is a bad packet.
if (!gotLastBlock) {
return null;
}
let redundantPayloadOffset = totalHeaderSizeBytes;
for (let i = 0; i < redundantEncodingTimestamps.length; i++) {
const redundantPayloadBuffer = new ArrayBuffer(redundantEncodingBlockLengths[i]);
const redundantPayloadArray = new Uint8Array(redundantPayloadBuffer);
redundantPayloadArray.set(
new Uint8Array(payload.buffer, redundantPayloadOffset, redundantEncodingBlockLengths[i]),
0
);
const encoding: RedundantAudioEncoder.Encoding = {
timestamp: redundantEncodingTimestamps[i],
payload: redundantPayloadBuffer,
isRedundant: true,
};
if (getFecInfo) {
encoding.hasFec = this.opusPacketHasFec(
new DataView(redundantPayloadBuffer),
redundantPayloadBuffer.byteLength
);
}
encodings.push(encoding);
redundantPayloadOffset += redundantEncodingBlockLengths[i];
}
const primaryPayloadOffset = payload.byteLength - primaryPayloadSizeBytes;
const primaryPayloadBuffer = new ArrayBuffer(primaryPayloadSizeBytes);
const primaryArray = new Uint8Array(primaryPayloadBuffer);
primaryArray.set(
new Uint8Array(payload.buffer, primaryPayloadOffset, primaryPayloadSizeBytes),
0
);
const encoding: RedundantAudioEncoder.Encoding = {
timestamp: primaryTimestamp,
payload: primaryPayloadBuffer,
isRedundant: false,
seq: primarySequenceNumber,
};
if (getFecInfo) {
encoding.hasFec = this.opusPacketHasFec(
new DataView(primaryPayloadBuffer),
primaryPayloadBuffer.byteLength
);
}
encodings.push(encoding);
return encodings;
}
/**
* Create a new encoding with current primary payload and the older payloads of choice.
*/
private encode(primaryTimestamp: number, primaryPayload: ArrayBuffer): ArrayBuffer | null {
const primaryPayloadSize = primaryPayload.byteLength;
// Payload size needs to be valid.
if (
primaryPayloadSize === 0 ||
primaryPayloadSize >= this.maxRedPacketSizeBytes ||
primaryPayloadSize >= this.maxAudioPayloadSizeBytes
) {
return null;
}
const numRedundantEncodings = this.numRedundantEncodings;
let headerSizeBytes = this.redLastHeaderSizeBytes;
let payloadSizeBytes = primaryPayloadSize;
let bytesAvailable = this.maxAudioPayloadSizeBytes - primaryPayloadSize - headerSizeBytes;
const redundantEncodingTimestamps: Array<number> = new Array();
const redundantEncodingPayloads: Array<ArrayBuffer> = new Array();
// If redundancy is disabled then only send the primary payload
if (this.redundancyEnabled) {
// Determine how much redundancy we can fit into our packet
let redundantTimestamp = this.uint32WrapAround(
primaryTimestamp - this.redPacketizationTime * this.redPacketDistance
);
for (let i = 0; i < numRedundantEncodings; i++) {
// Do not add redundant encodings that are beyond the maximum timestamp offset.
if (
this.uint32WrapAround(primaryTimestamp - redundantTimestamp) >= this.maxRedTimestampOffset
) {
break;
}
let findTimestamp = redundantTimestamp;
let encoding = this.encodingHistory.find(e => e.timestamp === findTimestamp);
if (!encoding) {
// If not found or not important then look for the previous packet.
// The current packet may have included FEC for the previous, so just
// use the previous packet instead provided that it has voice activity.
findTimestamp = this.uint32WrapAround(redundantTimestamp - this.redPacketizationTime);
encoding = this.encodingHistory.find(e => e.timestamp === findTimestamp);
}
if (encoding) {
const redundantEncodingSizeBytes = encoding.payload.byteLength;
// Only add redundancy if there are enough bytes available.
if (bytesAvailable < this.redHeaderSizeBytes + redundantEncodingSizeBytes) break;
bytesAvailable -= this.redHeaderSizeBytes + redundantEncodingSizeBytes;
headerSizeBytes += this.redHeaderSizeBytes;
payloadSizeBytes += redundantEncodingSizeBytes;
redundantEncodingTimestamps.unshift(encoding.timestamp);
redundantEncodingPayloads.unshift(encoding.payload);
}
redundantTimestamp -= this.redPacketizationTime * this.redPacketDistance;
redundantTimestamp = this.uint32WrapAround(redundantTimestamp);
}
}
const redPayloadBuffer = new ArrayBuffer(headerSizeBytes + payloadSizeBytes);
const redPayloadView = new DataView(redPayloadBuffer);
// Add redundant encoding header(s) to new buffer
let redPayloadOffset = 0;
for (let i = 0; i < redundantEncodingTimestamps.length; i++) {
const timestampDelta = primaryTimestamp - redundantEncodingTimestamps[i];
redPayloadView.setUint8(redPayloadOffset, this.opusPayloadType | 0x80);
redPayloadView.setUint16(
redPayloadOffset + 1,
(timestampDelta << 2) | (redundantEncodingPayloads[i].byteLength >> 8)
);
redPayloadView.setUint8(redPayloadOffset + 3, redundantEncodingPayloads[i].byteLength & 0xff);
redPayloadOffset += this.redHeaderSizeBytes;
}
// Add primary encoding header to new buffer
redPayloadView.setUint8(redPayloadOffset, this.opusPayloadType);
redPayloadOffset += this.redLastHeaderSizeBytes;
// Add redundant payload(s) to new buffer
const redPayloadArray = new Uint8Array(redPayloadBuffer);
for (let i = 0; i < redundantEncodingPayloads.length; i++) {
redPayloadArray.set(new Uint8Array(redundantEncodingPayloads[i]), redPayloadOffset);
redPayloadOffset += redundantEncodingPayloads[i].byteLength;
}
// Add primary payload to new buffer
redPayloadArray.set(new Uint8Array(primaryPayload), redPayloadOffset);
redPayloadOffset += primaryPayload.byteLength;
/* istanbul ignore next */
// Sanity check that we got the expected total payload size.
if (redPayloadOffset !== headerSizeBytes + payloadSizeBytes) return null;
this.updateEncodingHistory(primaryTimestamp, primaryPayload);
return redPayloadBuffer;
}
/**
* Update the encoding history with the latest primary encoding
*/
private updateEncodingHistory(primaryTimestamp: number, primaryPayload: ArrayBuffer): void {
// Remove encodings from the history if they are too old.
for (const encoding of this.encodingHistory) {
const maxTimestampDelta = this.redPacketizationTime * this.redMaxRecoveryDistance;
if (primaryTimestamp - encoding.timestamp >= maxTimestampDelta) {
this.encodingHistory.shift();
} else {
break;
}
}
// Only add an encoding to the history if the encoding is deemed to be important. An encoding is important if it is
// a CELT-only packet or contains voice activity.
const packet = new DataView(primaryPayload);
if (
this.opusPacketIsCeltOnly(packet) ||
this.opusPacketHasVoiceActivity(packet, packet.byteLength) > 0
) {
// Check if adding an encoding will cause the length of the encoding history to exceed the maximum history size.
// This is not expected to happen but could occur if we get incorrect timestamps. We want to make sure our memory
// usage is bounded. In this case, just clear the history and start over from empty.
if (this.encodingHistory.length + 1 > this.maxEncodingHistorySize)
this.encodingHistory.length = 0;
this.encodingHistory.push({ timestamp: primaryTimestamp, payload: primaryPayload });
}
}
// Keep track of timestamps of primary packets received
// from the server
private primaryPacketLog: RedundantAudioEncoder.PacketLog;
// Keeps track of timestamps of payloads we recovered
// through redundant payloads.
private redRecoveryLog: RedundantAudioEncoder.PacketLog;
// Keeps track of timestamps of payloads we recovered
// through fec payloads.
private fecRecoveryLog: RedundantAudioEncoder.PacketLog;
// Most recent sequence number of a primary packet received
// from the server
private newestSequenceNumber: number;
// Total number of packets we expected from the server.
private totalAudioPacketsExpected: number;
// Total number of packets from the server that were lost.
private totalAudioPacketsLost: number;
// Total number of packets we recovered by consuming
// redundant payloads.
private totalAudioPacketsRecoveredRed: number;
// Total number of packets we recovered by consuming
// payloads with FEC.
private totalAudioPacketsRecoveredFec: number;
// The timestamp at which we last reported loss stats
// to the main thread.
private lastLossReportTimestamp: number;
// Loss stats are reported to the main thread every 5 seconds.
// Since timestamp differences between 2 consecutive packets
// give us the number of samples in each channel, 1 second
// is equivalent to 48000 samples:
// P-time * (1000ms/1s)
// = (960 samples/20ms) * (1000ms/1s)
// = 48000 samples/s
private readonly lossReportInterval: number = 48000 * 5;
// Maximum distance of a packet from the most recent packet timestamp
// that we will consider for recovery.
private readonly maxOutOfOrderPacketDistance = 16;
/**
* Initialize packet logs and metric values.
*/
private initializePacketLogs(): void {
// The extra space from the max RED recovery distance is to ensure that we do not incorrectly count recovery for
// packets that have already been received but are outside of the max out-of-order distance.
const packetLogSize = this.maxOutOfOrderPacketDistance + this.redMaxRecoveryDistance;
this.primaryPacketLog = {
window: new Array<number>(packetLogSize),
index: 0,
windowSize: packetLogSize,
};
this.redRecoveryLog = {
window: new Array<number>(packetLogSize),
index: 0,
windowSize: packetLogSize,
};
this.fecRecoveryLog = {
window: new Array<number>(packetLogSize),
index: 0,
windowSize: packetLogSize,
};
this.totalAudioPacketsExpected = 0;
this.totalAudioPacketsLost = 0;
this.totalAudioPacketsRecoveredRed = 0;
this.totalAudioPacketsRecoveredFec = 0;
}
/**
* Receives encoded frames from the server
* and adds the timestamps to a packet log
* to calculate an approximate recovery metric.
*/
private receivePacketLogTransform(
// @ts-ignore
frame: RTCEncodedAudioFrame,
controller: TransformStreamDefaultController
): void {
const frameMetadata = frame.getMetadata();
// @ts-ignore
if (frameMetadata.payloadType !== this.redPayloadType) {
this.enqueueAudioFrameIfPayloadSizeIsValid(frame, controller);
return;
}
// @ts-ignore
const encodings = this.splitEncodings(
frame.timestamp,
frame.data,
/*getFecInfo*/ true,
frameMetadata.sequenceNumber
);
if (!encodings) {
this.enqueueAudioFrameIfPayloadSizeIsValid(frame, controller);
return;
}
for (let i = encodings.length - 1; i >= 0; i--) {
if (this.updateLossStats(encodings[i])) {
this.updateRedStats(encodings[i]);
this.updateFecStats(encodings[i]);
}
}
this.maybeReportLossStats(
encodings[encodings.length - 1].timestamp,
frameMetadata.synchronizationSource
);
this.enqueueAudioFrameIfPayloadSizeIsValid(frame, controller);
}
/**
* Adds a timestamp to the primary packet log.
* This also updates totalAudioPacketsLost and totalAudioPacketsExpected by looking
* at the difference between timestamps.
*
* @param encoding : The encoding to be analyzed
* @returns false if sequence number was greater than max out of order distance
* true otherwise
*/
private updateLossStats(encoding: RedundantAudioEncoder.Encoding): boolean {
if (encoding.isRedundant) return true;
const timestamp = encoding.timestamp;
const seq = encoding.seq;
if (this.totalAudioPacketsExpected === 0) {
this.totalAudioPacketsExpected = 1;
this.newestSequenceNumber = seq;
this.addTimestamp(this.primaryPacketLog, timestamp);
return true;
}
const diff = this.int16(seq - this.newestSequenceNumber);
if (diff < -this.maxOutOfOrderPacketDistance) return false;
if (diff < 0) {
if (!this.hasTimestamp(this.primaryPacketLog, timestamp)) {
if (this.totalAudioPacketsLost > 0) this.totalAudioPacketsLost--;
this.addTimestamp(this.primaryPacketLog, timestamp);
this.removeFromRecoveryWindows(timestamp);
}
} else if (diff > 1) {
this.totalAudioPacketsLost += diff - 1;
}
if (diff > 0) {
this.totalAudioPacketsExpected += diff;
this.newestSequenceNumber = encoding.seq;
this.addTimestamp(this.primaryPacketLog, timestamp);
}
return true;
}
/**
* Adds a timestamp to the red recovery log if it is not present in
* the primary packet log and if it's not too old.
*
* @param encoding : The encoding to be analyzed
*/
private updateRedStats(encoding: RedundantAudioEncoder.Encoding): void {
if (!encoding.isRedundant || this.totalAudioPacketsLost === 0) return;
const timestamp = encoding.timestamp;
if (!this.hasTimestamp(this.primaryPacketLog, timestamp)) {
if (!this.hasTimestamp(this.redRecoveryLog, timestamp)) {
this.totalAudioPacketsRecoveredRed++;
this.addTimestamp(this.redRecoveryLog, timestamp);
}
if (this.removeTimestamp(this.fecRecoveryLog, timestamp)) {
/* istanbul ignore else */
if (this.totalAudioPacketsRecoveredFec > 0) this.totalAudioPacketsRecoveredFec--;
}
}
}
/**
* Adds a timestamp to the fec recovery log if it is not present in
* the primary packet log and red recovery log and if it is not too old.
*
* @param encoding : The encoding to be analyzed
*/
private updateFecStats(encoding: RedundantAudioEncoder.Encoding): void {
if (!encoding.hasFec || this.totalAudioPacketsLost === 0) return;
const fecTimestamp = encoding.timestamp - this.redPacketizationTime;
if (
this.hasTimestamp(this.primaryPacketLog, fecTimestamp) ||
this.hasTimestamp(this.redRecoveryLog, fecTimestamp) ||
this.hasTimestamp(this.fecRecoveryLog, fecTimestamp)
) {
return;
}
this.totalAudioPacketsRecoveredFec++;
this.addTimestamp(this.fecRecoveryLog, fecTimestamp);
}
/**
* Reports loss metrics to DefaultTransceiverController
*
* @param timestamp : Timestamp of most recent primary packet
*/
private maybeReportLossStats(timestamp: number, ssrc: number): void {
if (timestamp - this.lastLossReportTimestamp < this.lossReportInterval) return;
/* istanbul ignore next */
if (RedundantAudioEncoder.shouldReportStats) {
// @ts-ignore
self.postMessage({
type: 'RedundantAudioEncoderStats',
ssrc,
totalAudioPacketsLost: this.totalAudioPacketsLost,
totalAudioPacketsExpected: this.totalAudioPacketsExpected,
totalAudioPacketsRecoveredRed: this.totalAudioPacketsRecoveredRed,
totalAudioPacketsRecoveredFec: this.totalAudioPacketsRecoveredFec,
});
}
this.lastLossReportTimestamp = timestamp;
}
/**
* Adds a timestamp to a packet log
*
* @param packetLog : The packetlog to add the timestamp to
* @param timestamp : The timestamp that should be added
*/
private addTimestamp(packetLog: RedundantAudioEncoder.PacketLog, timestamp: number): void {
packetLog.window[packetLog.index] = timestamp;
packetLog.index = (packetLog.index + 1) % packetLog.windowSize;
}
/**
* Checks if a timestamp is in a packetlog
*
* @param packetLog : The packetlog to search
* @param timestamp : The timestamp to search for
* @returns true if timestamp is present, false otherwise
*/
private hasTimestamp(packetLog: RedundantAudioEncoder.PacketLog, timestamp: number): boolean {
const element = packetLog.window.find(t => t === timestamp);
return !!element;
}
/**
* Removes a timestamp from a packet log
*
* @param packetLog : The packetlog from which the timestamp should be removed
* @param timestamp : The timestamp to be removed
* @returns true if timestamp was present in the log and removed, false otherwise
*/
private removeTimestamp(packetLog: RedundantAudioEncoder.PacketLog, timestamp: number): boolean {
const index = packetLog.window.indexOf(timestamp);
if (index >= 0) {
packetLog.window[index] = undefined;
return true;
}
return false;
}
/**
* Removes a timestamp from red and fec recovery windows.
*
* @param timestamp : The timestamp to be removed
*/
private removeFromRecoveryWindows(timestamp: number): void {
let removed = this.removeTimestamp(this.redRecoveryLog, timestamp);
if (removed) {
if (this.totalAudioPacketsRecoveredRed > 0) this.totalAudioPacketsRecoveredRed--;
}
removed = this.removeTimestamp(this.fecRecoveryLog, timestamp);
if (removed) {
if (this.totalAudioPacketsRecoveredFec > 0) this.totalAudioPacketsRecoveredFec--;
}
}
/**
* Converts the supplied argument to 32-bit unsigned integer
*/
private uint32WrapAround(num: number): number {
const mod = 4294967296; // 2^32
let res: number = num;
if (num >= mod) {
res = num - mod;
} else if (num < 0) {
res = mod + num;
}
return res;
}
/**
* Converts the supplied argument to 16-bit signed integer
*/
private int16(num: number): number {
return (num << 16) >> 16;
}
/**
* Below are Opus helper methods and constants.
*/
private readonly OPUS_BAD_ARG = -1;
private readonly OPUS_INVALID_PACKET = -4;
// Max number of Opus frames in an Opus packet is 48 (https://www.rfc-editor.org/rfc/rfc6716#section-3.2.5).
private readonly OPUS_MAX_OPUS_FRAMES = 48;
// Max number of bytes that any individual Opus frame can have.
private readonly OPUS_MAX_FRAME_SIZE_BYTES = 1275;
/**
* Determines if an Opus packet is in CELT-only mode.
*
* @param packet Opus packet.
* @returns `true` if the packet is in CELT-only mode.
*/
private opusPacketIsCeltOnly(packet: DataView): boolean {
// TOC byte format (https://www.rfc-editor.org/rfc/rfc6716#section-3.1):
// 0
// 0 1 2 3 4 5 6 7
// +-+-+-+-+-+-+-+-+
// | config |s| c |
// +-+-+-+-+-+-+-+-+
// Since CELT-only packets are represented using configurations 16 to 31, the highest 'config' bit will always be 1
// for CELT-only packets.
return !!(packet.getUint8(0) & 0x80);
}
/**
* Gets the number of samples per frame from an Opus packet.
*
* @param packet Opus packet. This must contain at least one byte of data.
* @param sampleRateHz 32-bit integer sampling rate in Hz. This must be a multiple of 400 or inaccurate results will
* be returned.
* @returns Number of samples per frame.
*/
private opusPacketGetSamplesPerFrame(packet: DataView, sampleRateHz: number): number {
// Sample rate must be a 32-bit integer.
sampleRateHz = Math.round(sampleRateHz);
sampleRateHz = Math.min(Math.max(sampleRateHz, -(2 ** 32)), 2 ** 32 - 1);
// TOC byte format (https://www.rfc-editor.org/rfc/rfc6716#section-3.1):
// 0
// 0 1 2 3 4 5 6 7
// +-+-+-+-+-+-+-+-+
// | config |s| c |
// +-+-+-+-+-+-+-+-+
let numSamples: number;
let frameSizeOption: number;
// Case for CELT-only packet.
if (this.opusPacketIsCeltOnly(packet)) {
// The lower 3 'config' bits indicate the frame size option.
frameSizeOption = (packet.getUint8(0) >> 3) & 0x3;
// The frame size options 0, 1, 2, 3 correspond to frame sizes of 2.5, 5, 10, 20 ms. Notice that the frame sizes
// can be represented as (2.5 * 2^0), (2.5 * 2^1), (2.5 * 2^2), (2.5 * 2^3) ms. So, the number of samples can be
// calculated as follows:
// (sample/s) * (1s/1000ms) * (2.5ms) * 2^(frameSizeOption)
// = (sample/s) * (1s/400) * 2^(frameSizeOption)
// = (sample/s) * 2^(frameSizeOption) * (1s/400)
numSamples = (sampleRateHz << frameSizeOption) / 400;
}
// Case for Hybrid packet. Since Hybrid packets are represented using configurations 12 to 15, bits 1 and 2 in the
// above TOC byte diagram will both be 1.
else if ((packet.getUint8(0) & 0x60) === 0x60) {
// In the case of configuration 13 or 15, bit 4 in the above TOC byte diagram will be 1. Configurations 13 and 15
// correspond to a 20ms frame size, so the number of samples is calculated as follows:
// (sample/s) * (1s/1000ms) * (20ms)
// = (sample/s) * (1s/50)
//
// In the case of configuration 12 or 14, bit 4 in the above TOC byte diagram will be 0. Configurations 12 and 14
// correspond to a 10ms frame size, so the number of samples is calculated as follows:
// (sample/s) * (1s/1000ms) * (10ms)
// = (sample/s) * (1s/100)
numSamples = packet.getUint8(0) & 0x08 ? sampleRateHz / 50 : sampleRateHz / 100;
}
// Case for SILK-only packet.
else {
// The lower 3 'config' bits indicate the frame size option for SILK-only packets.
frameSizeOption = (packet.getUint8(0) >> 3) & 0x3;
if (frameSizeOption === 3) {
// Frame size option 3 corresponds to a frame size of 60ms, so the number of samples is calculated as follows:
// (sample/s) * (1s/1000ms) * (60ms)
// = (sample/s) * (60ms) * (1s/1000ms)
numSamples = (sampleRateHz * 60) / 1000;
} else {
// The frame size options 0, 1, 2 correspond to frame sizes of 10, 20, 40 ms. Notice that the frame sizes can be
// represented as (10 * 2^0), (10 * 2^1), (10 * 2^2) ms. So, the number of samples can be calculated as follows:
// (sample/s) * (1s/1000ms) * (10ms) * 2^(frameSizeOption)
// = (sample/s) * (1s/100) * 2^(frameSizeOption)
// = (sample/s) * 2^(frameSizeOption) * (1s/100)
numSamples = (sampleRateHz << frameSizeOption) / 100;
}
}
return numSamples;
}
/**
* Gets the number of SILK frames per Opus frame.
*
* @param packet Opus packet.
* @returns Number of SILK frames per Opus frame.
*/
private opusNumSilkFrames(packet: DataView): number {
// For computing the frame length in ms, the sample rate is not important since it cancels out. We use 48 kHz, but
// any valid sample rate would work.
//
// To calculate the length of a frame (with a 48kHz sample rate) in ms:
// (samples/frame) * (1s/48000 samples) * (1000ms/s)
// = (samples/frame) * (1000ms/48000 samples)
// = (samples/frame) * (1ms/48 samples)
let frameLengthMs = this.opusPacketGetSamplesPerFrame(packet, 48000) / 48;
if (frameLengthMs < 10) frameLengthMs = 10;
// The number of SILK frames per Opus frame is described in https://www.rfc-editor.org/rfc/rfc6716#section-4.2.2.
switch (frameLengthMs) {
case 10:
case 20:
return 1;
case 40:
return 2;
case 60:
return 3;
// It is not possible to reach the default case since an Opus packet can only encode sizes of 2.5, 5, 10, 20, 40,
// or 60 ms, so we ignore the default case for test coverage.
/* istanbul ignore next */
default:
return 0;
}
}
/**
* Gets the number of channels from an Opus packet.
*
* @param packet Opus packet.