-
Notifications
You must be signed in to change notification settings - Fork 308
/
sfuClient.js
3523 lines (3506 loc) · 121 KB
/
sfuClient.js
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
/** @file automatically generated, do not edit it. */
/* eslint-disable max-len, indent */
/******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ // The require scope
/******/ var __webpack_require__ = {};
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (exports, definition) => {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"S": () => (/* binding */ ConnState)
});
// UNUSED EXPORTS: CallJoinPermission, ScreenShareType, SfuClient, SpeakerState
;// CONCATENATED MODULE: ../shared/termCodes.ts
var TermCode;
(function (TermCode) {
// Normal conditions
TermCode[TermCode["kFlagError"] = 128] = "kFlagError";
TermCode[TermCode["kFlagDisconn"] = 64] = "kFlagDisconn";
TermCode[TermCode["kUserHangup"] = 0] = "kUserHangup";
TermCode[TermCode["kTooManyParticipants"] = 1] = "kTooManyParticipants";
TermCode[TermCode["kLeavingRoom"] = 2] = "kLeavingRoom";
TermCode[TermCode["kCallEndedByModerator"] = 3] = "kCallEndedByModerator";
TermCode[TermCode["kCallEndedByApi"] = 4] = "kCallEndedByApi";
TermCode[TermCode["kPeerJoinTimeout"] = 5] = "kPeerJoinTimeout";
TermCode[TermCode["kPushedToWaitingRoom"] = 6] = "kPushedToWaitingRoom";
TermCode[TermCode["kKickedFromWaitingRoom"] = 7] = "kKickedFromWaitingRoom";
// Disconnects
TermCode[TermCode["kRtcDisconn"] = 64] = "kRtcDisconn";
TermCode[TermCode["kSigDisconn"] = 65] = "kSigDisconn";
TermCode[TermCode["kSfuShuttingDown"] = 66] = "kSfuShuttingDown";
TermCode[TermCode["kChatDisconn"] = 67] = "kChatDisconn";
TermCode[TermCode["kNoMediaPath"] = 68] = "kNoMediaPath";
// Errors (abnormal conditions)
TermCode[TermCode["kErrSignaling"] = 128] = "kErrSignaling";
TermCode[TermCode["kErrNoCall"] = 129] = "kErrNoCall";
TermCode[TermCode["kErrAuth"] = 130] = "kErrAuth";
TermCode[TermCode["kErrApiTimeout"] = 131] = "kErrApiTimeout";
TermCode[TermCode["kErrSdp"] = 132] = "kErrSdp";
TermCode[TermCode["kErrTooManyClients"] = 133] = "kErrTooManyClients";
TermCode[TermCode["kErrClientGeneral"] = 190] = "kErrClientGeneral";
TermCode[TermCode["kErrSfuGeneral"] = 191] = "kErrSfuGeneral";
})(TermCode || (TermCode = {}));
;
/* harmony default export */ const termCodes = (TermCode);
;// CONCATENATED MODULE: ../shared/av.ts
class Av {
static hasCamAndScreen(av) {
return ((av & Av.Camera) && (av & Av.Screen));
}
static toString(av) {
let result = (av & Av.onHold) ? "H" : "";
if (av & Av.Audio) {
result += "a";
}
if (av & Av.CameraHiRes) {
result += "C";
}
if (av & Av.CameraLowRes) {
result += "c";
}
if (av & Av.ScreenHiRes) {
result += "S";
}
if (av & Av.ScreenLowRes) {
result += "s";
}
return result;
}
}
Av.Audio = 1;
Av.CameraLowRes = 2;
Av.CameraHiRes = 4;
Av.Camera = 6;
Av.ScreenLowRes = 8;
Av.ScreenHiRes = 16;
Av.Screen = 24;
Av.LowResVideo = 10;
Av.HiResVideo = 20;
Av.Video = 30;
Av.onHold = 128;
;// CONCATENATED MODULE: ../shared/sdpCompress.ts
const endl = "\r\n";
class Ssrc {
constructor(id) {
this.id = id;
}
}
class Track {
constructor(type) {
this.t = type;
}
static uncompress(track, template) {
let sdp = template;
if (track.sdp) {
sdp += track.sdp + "\r\n";
}
sdp += "a=mid:" + track.mid + endl;
sdp += "a=" + track.dir + endl;
if (track.id) { // recvonly tracks don't have it
sdp += "a=msid:" + track.sid + " " + track.id + endl;
}
if (track.ssrcs) {
for (let ssrc of track.ssrcs) {
let id = ssrc.id;
sdp += "a=ssrc:" + id + " cname:" + (ssrc.cname ? ssrc.cname : track.sid) + endl;
sdp += "a=ssrc:" + id + " msid:" + track.sid + " " + track.id + endl;
// sdp += "a=ssrc:" + id + " mslabel:" + track.sid + endl;
// sdp += "a=ssrc:" + id + " label:" + track.id + endl;
}
if (track.ssrcg) {
for (let grp of track.ssrcg) {
sdp += "a=ssrc-group:" + grp + endl;
}
}
}
return sdp;
}
}
class CompressedSdp {
constructor(sdp) {
if (sdp instanceof Object) {
this.data = sdp;
return;
}
let data = this.data = {
cmn: "",
atpl: "",
vtpl: "",
tracks: []
};
let lines = sdp.split(/\r\n/);
let i = 0;
for (; i < lines.length; i++) {
let line = lines[i];
if (line.substr(0, 2) === "m=") {
break;
}
data.cmn += line + endl;
}
while (i < lines.length) {
let line = lines[i];
let type = line.substr(2, 5);
if (type === "audio" && !data.atpl) {
i = this._createTemplate("atpl", lines, i);
if (data.vtpl) {
break;
}
}
else if (type === "video" && !data.vtpl) {
i = this._createTemplate("vtpl", lines, i);
if (data.atpl) {
break;
}
}
else {
i = nextMline(lines, i + 1);
}
}
for (i = nextMline(lines, 0); i < lines.length;) {
i = this._addTrack(lines, i);
}
}
_createTemplate(tname, lines, i) {
let template = lines[i++] + endl;
for (; i < lines.length; i++) {
let line = lines[i];
let ltype = line.charAt(0);
if (ltype === 'm') {
break;
}
if (ltype !== 'a') {
template += line + endl;
continue;
}
let name = nextWord(line, 2)[0];
if (name === "recvonly") { // we don't want to make a template from a recvonly description
// consume lines till next m-line
return nextMline(lines, i);
}
switch (name) {
case "sendrecv":
case "sendonly":
case "ssrc-group":
case "ssrc":
case "mid":
case "msid":
continue;
default:
template += line + endl;
}
}
this.data[tname] = template;
return i;
}
_addTrack(lines, i) {
let type = lines[i++].substr(2, 5);
if (type === "audio") {
type = "a";
}
else if (type === "video") {
type = "v";
}
;
let track = new Track(type);
let ssrcIds = new Set;
for (; i < lines.length; i++) {
let line = lines[i];
let ltype = line.charAt(0);
if (ltype === 'm') {
break;
}
if (ltype !== 'a') {
continue;
}
let name = nextWord(line, 2)[0];
switch (name) {
case "sendrecv":
case "recvonly":
case "sendonly": {
track.dir = name;
break;
}
case "mid": {
track.mid = parseInt(line.substr(6));
break;
}
case "msid": {
let parts = line.substr(7).split(' ');
track.sid = parts[0];
track.id = parts[1];
break;
}
case "ssrc-group": {
if (!track.ssrcg) {
track.ssrcg = [];
}
track.ssrcg.push(line.substr(13));
break;
}
case "ssrc": {
let ret = nextWord(line, 7);
let id = parseInt(ret[0]);
if (ssrcIds.has(id)) {
break;
}
ssrcIds.add(id);
ret = nextWord(line, ret[1] + 1);
let cname = nextWord(line, ret[1] + 1)[0];
let ssrc = new Ssrc(id);
if (cname !== track.sid) {
ssrc.cname = cname;
}
if (!track.ssrcs) {
track.ssrcs = [ssrc];
}
else {
track.ssrcs.push(ssrc);
}
break;
}
}
}
this.data.tracks.push(track);
return i;
}
uncompress() {
let sdp = this.data.cmn;
for (let track of this.data.tracks) {
if (track.t === "a") {
sdp += Track.uncompress(track, this.data.atpl);
}
else if (track.t === "v") {
sdp += Track.uncompress(track, this.data.vtpl);
}
}
return sdp;
}
}
function nextWord(line, start) {
let i;
for (i = start; i < line.length; i++) {
let ch = line.charCodeAt(i);
if ((ch >= 97 && ch <= 122) || // a - z
(ch >= 65 && ch <= 90) || // A - Z
(ch >= 48 && ch <= 57) || // 0 - 9
(ch === 45) || (ch === 43) || (ch === 47) || (ch === 95)) { // - + /
continue;
}
break;
}
return [line.substr(start, i - start), i];
}
function nextMline(lines, i) {
for (; i < lines.length; i++) {
if (lines[i].charAt(0) === "m") {
return i;
}
}
return i;
}
function sdpCompress(sdp) {
/*
console.log("original:\n", sdp);
let csdp = (new CompressedSdp(sdp)).uncompress();
console.log("compressed:\n", csdp);
*/
// return sdp;
return (new CompressedSdp(sdp)).data;
}
function sdpUncompress(sdp) {
// return sdp;
return (new CompressedSdp(sdp)).uncompress();
}
function trackSummary(tracks) {
let summary = "";
if (tracks.tx) {
summary += tracks.tx + " send";
}
else {
summary += tracks.rx + " recv";
}
if (tracks.txrx) {
summary += ", " + tracks.txrx + " sendrecv";
}
return summary;
}
function compressedSdpToString(sdp) {
let video = { rx: 0, tx: 0, txrx: 0, svc: 0 };
let audio = { rx: 0, tx: 0, txrx: 0 };
for (let track of sdp.tracks) {
let type = track.t;
let dir = track.dir;
let info;
if (type === "v") {
info = video;
if (track.ssrcg) {
for (let ssrcg of track.ssrcg) {
if (ssrcg.substr(0, 3) === "SIM") {
video.svc++;
}
}
}
}
else {
info = audio;
}
if (dir === "recvonly") {
info.rx++;
}
else if (dir === "sendrecv") {
info.txrx++;
}
else if (dir === "sendonly") {
info.tx++;
}
}
let summary = "<vtracks: " + trackSummary(video);
if (video.svc) {
summary += ", " + video.svc + " SVC";
}
summary += "; atracks: " + trackSummary(audio) + ">";
return summary;
}
;// CONCATENATED MODULE: ./adaptation.ts
class SvcDriver {
constructor(client) {
this.currRxQuality = 4; // start at half resolution, full fps
this.currTxQuality = 2;
// rtt window
this.lowestRttSeen = 10000; // force recalculation on first stat sample
this.rxqSwitchSeqNo = 0;
this.rxqUpSwitchHistory = new Array(SvcDriver.kMaxRxQualityIndex + 1);
this.hasBadNetwork = false;
this.client = client;
}
async onStats() {
const stats = this.client.rtcStats;
let { pl: plost, rtt } = stats;
if (isNaN(rtt)) {
return;
}
if (isNaN(plost)) {
plost = stats.pl = 0;
}
const plostCapped = (plost > SvcDriver.kPlostCap) ? SvcDriver.kPlostCap : plost;
if (isNaN(this.maRtt)) {
this.maRtt = rtt;
this.smaPlost = plostCapped;
this.fmaPlost = plost;
return; // intentionally skip first sample for lower/upper range calculation
}
rtt = this.maRtt = (this.maRtt * 2 + rtt) / 3;
if (rtt < this.lowestRttSeen) {
this.setRttWindow(rtt);
}
this.smaPlost = (this.smaPlost * 29 + plostCapped) / 30;
this.setPlostWindow(this.smaPlost);
plost = this.fmaPlost = (this.fmaPlost * 2 + plost) / 3;
/*
console.log("rtt:", rtt.toFixed(1), "rttLower:", this.rttLower.toFixed(1), "rttUpper:", this.rttUpper.toFixed(1),
"plost:", plost.toFixed(1), "fmaPlost:", this.fmaPlost.toFixed(1),
"plostLower", this.plostLower.toFixed(1), "plostUpper:", this.plostUpper.toFixed(1));
*/
const tsNow = Date.now();
if (!this.tsNoSwitchUntil) {
this.tsNoSwitchUntil = tsNow;
return;
}
let maTxKbps;
const adaptScrnTx = stats._vtxIsHiRes && this.client.isSendingScreenHiRes();
if (adaptScrnTx) { // calculate tx average kbps
const txBwidth = (stats.txBwe > 0) ? stats.txBwe : stats._vtxkbps;
if (this.maTxKbps == null) {
maTxKbps = this.maTxKbps = txBwidth;
}
else {
maTxKbps = this.maTxKbps = (this.maTxKbps * 5 + txBwidth) / 6;
}
// console.log("scrshare: maTxKbps:", maTxKbps, "mom:", txBwidth);
}
if (tsNow < this.tsNoSwitchUntil) {
return; // too early
}
if (plost > this.plostUpper) {
if (window.d) {
console.warn("Decreasing rxQ due to PACKET LOSS of", plost.toFixed(1));
}
this.decRxQuality(plost > SvcDriver.kPlostCritical);
}
else if (rtt > this.rttUpper) { // rtt or packet loss increased above thresholds
this.decRxQualityDueToRtt(stats);
}
else if (rtt < this.rttLower && plost < this.plostLower) {
this.incRxQuality();
}
const txQs = SvcDriver.TxQuality;
if (adaptScrnTx) {
const currTxQ = SvcDriver.TxQuality[this.currTxQuality];
if (maTxKbps < currTxQ.minKbps) {
let q = this.currTxQuality;
while (maTxKbps < txQs[q].minKbps) {
q--;
if (q < 0) {
q = 0;
break;
}
}
const delta = q - this.currTxQuality;
if (delta < 0) {
this.switchTxQuality(delta, "scr");
}
}
else if (stats.vtxdly > 2500) {
if (window.d) {
console.warn(`scrnshare: Tx delay ${stats.vtxdly} ms too large, decreasing quality...`);
}
this.switchTxQuality(-1, "scr");
}
else if (stats.vtxdly > 0 && stats.vtxdly < 1400) {
let q = this.currTxQuality;
while (maTxKbps > txQs[q].maxKbps) {
q++;
if (q >= txQs.length) {
q--;
break;
}
}
const delta = q - this.currTxQuality;
if (delta > 0) {
this.switchTxQuality(delta, "scr");
}
}
}
// handle "bad network" notification
let txBad = !isNaN(stats.vtxdly) && (stats.vtxdly > 1500);
if (adaptScrnTx) {
txBad = txBad || this.currTxQuality < 1;
}
else if (stats._vtxIsHiRes && stats.vtxh) {
this.maVideoTxHeight = !isNaN(this.maVideoTxHeight) ? (this.maVideoTxHeight * 3 + stats.vtxh) / 4 : stats.vtxh;
txBad = txBad || (this.maVideoTxHeight < 200);
}
const rxBad = rtt > 1500 || plost > 20;
if (txBad || rxBad) {
if (!this.hasBadNetwork) {
this.hasBadNetwork = true;
this.client._fire("onBadNetwork", true);
}
}
else if (this.hasBadNetwork) {
this.hasBadNetwork = false;
this.client._fire("onBadNetwork", false);
}
}
setRttWindow(rtt) {
this.lowestRttSeen = rtt;
this.rttLower = rtt + SvcDriver.kRttLowerHeadroom;
this.rttUpper = rtt + SvcDriver.kRttUpperHeadroom;
if (window.d) {
console.warn("Rtt floor set to", rtt.toFixed(2));
}
}
setPlostWindow(plost) {
this.plostLower = plost + SvcDriver.kPlostLowerHeadroom;
this.plostUpper = plost + SvcDriver.kPlostUpperHeadroom;
}
decRxQuality(critical) {
if (this.currRxQuality <= 0) {
return false;
}
const newQ = this.currRxQuality - 1;
const hist = this.rxqUpSwitchHistory[newQ];
const now = Date.now();
if (hist) {
const timeMatch = now <= hist.tsMonitorTill;
if ((hist.hiArea === this.rxTotalArea()) && (critical || timeMatch)) {
let span = SvcDriver.kRxUpFailDur;
if (hist.upFails) {
if (critical && timeMatch) {
span += SvcDriver.kRxUpFailMaxExtendPeriod; // critical decreases get maximum validity time
}
else {
// extend the validity based on how recent the last fail was and how many total fails occurred
let decay = hist.tsMonitorTill + SvcDriver.kRxUpFailMaxExtendPeriod - now;
if (decay > 0) {
decay = decay * hist.upFails * SvcDriver.kRxUpFailDurDecayMult;
if (decay > SvcDriver.kRxUpFailMaxExtendPeriod) {
decay = SvcDriver.kRxUpFailMaxExtendPeriod;
}
}
span += decay;
}
}
hist.upFails++;
hist.tsValidTill = now + span;
if (window.d) {
console.warn(`decRxQuality[${this.currRxQuality} -> ${newQ}]: Marking rx quality switch up attempt as failed: critcal: ${!!critical}, for period: ${span}`);
}
}
else {
if (window.d) {
console.warn(`decRxQuality[${this.currRxQuality} -> ${newQ}]: not marking as failed: areaMatch: ${hist.hiArea === this.rxTotalArea()}, timeMatch: ${Date.now() - hist.tsMonitorTill}`);
}
}
}
this.setRxQuality(newQ, SvcDriver.kQualityDecreaseSettleTime);
return true;
}
incRxQuality() {
delete this.rxRttDowngr;
if (this.currRxQuality >= SvcDriver.kMaxRxQualityIndex) {
return false;
}
const now = Date.now();
const stats = this.client.rtcStats;
let hist = this.rxqUpSwitchHistory[this.currRxQuality];
let histMatch;
if (hist) {
// positive matching is the conservative stragegy - by matching we block the rx quality increase
const kbpsMatch = stats.rx <= hist.kbps * 1.5;
const rttMatch = this.maRtt > hist.rtt - 50;
histMatch = hist.upFails && kbpsMatch && rttMatch && hist.lowArea <= this.rxTotalArea();
if (histMatch && (hist.tsValidTill - now) >= 0) {
if (window.d) {
console.warn(`incRxQuality[${this.currRxQuality} -> ${this.currRxQuality + 1}]: Not increasing rxQ, have failed recently`);
}
return;
}
else {
if (window.d) {
console.warn(`incRxQuality[${this.currRxQuality} -> ${this.currRxQuality + 1}]: not failed(recently): upFails:${hist.upFails}, timeMatch: ${(hist.tsValidTill - now)}, kbpsMatch: ${kbpsMatch} (hist: ${hist.kbps}, curr: ${stats.rx}), rttMatch: ${rttMatch} (hist: ${hist.rtt.toFixed()}, curr: ${this.maRtt.toFixed()}), areaDiff: ${this.rxTotalArea() - hist.lowArea}`);
}
}
}
if (histMatch) {
hist.tsMonitorTill = now + SvcDriver.kRxUpFailMonitorDur;
hist.kbps = stats.rx;
hist.rtt = stats.rtt;
if (window.d) {
console.warn(`incRxQuality[${this.currRxQuality} -> ${this.currRxQuality + 1}]: Same up-fail parameters, preserving fail descriptor`);
}
}
else {
hist = this.rxqUpSwitchHistory[this.currRxQuality] = {
upFails: 0, tsValidTill: 0,
tsMonitorTill: now + SvcDriver.kRxUpFailMonitorDur,
kbps: stats.rx, rtt: this.maRtt, lowArea: this.rxTotalArea()
};
if (window.d) {
console.warn(`incRxQuality[${this.currRxQuality} -> ${this.currRxQuality + 1}]: Created new up-fail descriptor`);
}
}
// we can't know the area after quality increasing before the actual quality switch takes place, so we do it
// with a delay
this.setRxQuality(this.currRxQuality + 1, SvcDriver.kQualityIncreaseSettleTime);
setTimeout(() => {
if (this.client.connState === ConnState.kCallJoined) {
hist.hiArea = this.rxTotalArea();
}
}, SvcDriver.kQualityIncreaseSettleTime - 1000);
return true;
}
setRxQuality(newQ, deadTime) {
const params = SvcDriver.RxQuality[newQ];
assert(params);
this.tsNoSwitchUntil = Date.now() + deadTime;
this.rxqSwitchSeqNo++;
if (window.d) {
console.warn(`Switching rx SVC quality from ${this.currRxQuality} to ${newQ}: %o`, params);
}
this.currRxQuality = newQ;
this.client.requestSvcLayers(params[0], params[1], params[2]);
}
decRxQualityDueToRtt(stats) {
if (!this.rxRttDowngr) {
if (this.currRxQuality > 0) {
if (window.d) {
console.warn(`Decreasing rxQ due to HIGH RTT of ${this.maRtt.toFixed()}, saving checkpoint`);
}
this.rxRttDowngr = { startQ: this.currRxQuality, lastRtt: stats.rtt, lastPlost: stats.pl };
this.decRxQuality();
}
return;
}
// we have rxRttDowngr, see if the downgrade is affecting rtt
const nSteps = this.rxRttDowngr.startQ - this.currRxQuality;
if (nSteps > 0) {
// we have stepped down at least once:
// If rtt did not really decrease, is not too big (to be influenced by our q step down), and there is no extraordinary
// packet loss, then assume the high rtt is not due to network congestion
if ((this.fmaPlost <= this.plostLower) && (stats.rtt < 1000) && (Math.abs(stats.rtt - this.rxRttDowngr.lastRtt) < 16)) {
// rtt did not change
if (window.d) {
console.warn(`Decreased rxQ by ${nSteps} steps: rtt didn't change much (${stats.rtt - this.rxRttDowngr.lastRtt}), is not over 1000 and there is no extra packet loss. Updating rtt floor`);
}
this.setRttWindow(this.maRtt);
// reset the checkpoint as well - otherwise we may ignore a future rtt decrease
// on top of the current increase
this.rxRttDowngr = { startQ: this.currRxQuality, lastRtt: stats.rtt, lastPlost: stats.pl };
return; // dont decrease quality
}
else if (this.currRxQuality > 0) {
// rtt changed - could be decreasing from the quality downgrade, or still rising
// because of network conditions. Either way, we should further downgrade quality
if (window.d) {
console.warn(`Decreased rxQ by ${nSteps} steps: rtt ${stats.rtt} changed by ${Math.round(stats.rtt - this.rxRttDowngr.lastRtt)}, plost: ${this.fmaPlost.toFixed(1)}. Keeping current rtt floor of ${this.lowestRttSeen.toFixed(2)}`);
}
this.rxRttDowngr = { startQ: this.currRxQuality, lastRtt: stats.rtt, lastPlost: stats.pl };
}
}
this.decRxQuality();
}
switchTxQuality(delta, mode) {
let newQ = this.currTxQuality + delta;
if (newQ < 0) {
newQ = 0;
}
else if (newQ > SvcDriver.kMaxTxQualityIndex) {
newQ = SvcDriver.kMaxTxQualityIndex;
}
if (newQ === this.currTxQuality) {
return false;
}
return this.setTxQuality(newQ, mode);
}
setTxQuality(newQ, mode) {
const track = this.client.outVSpeakerTrack.sentTrack;
if (!track) {
return false;
}
const info = SvcDriver.TxQuality[newQ];
assert(info);
this.tsNoSwitchUntil = Date.now() + SvcDriver.kQualityIncreaseSettleTime;
const params = info[mode];
let ar = this.client.screenAspectRatio;
if (!ar) {
const res = track.getSettings();
if (res.width && res.height) {
ar = this.client.screenAspectRatio = res.width / res.height;
if (window.d) {
console.warn(`Screen capture res: ${res.width}x${res.height} (aspect ratio: ${Math.round(ar * 1000) / 1000})`);
}
}
else {
ar = 1.78;
if (window.d) {
console.warn("setTxQuality: Could not obtain screen track's resolution, assuming AR of", ar);
}
}
}
params.width = Math.round(params.height * ar);
if (window.d) {
console.warn(`Switching TX quality from ${this.currTxQuality} to ${newQ}: %o (AR: ${this.client.screenAspectRatio ? this.client.screenAspectRatio.toFixed(3) : "unknown"})`, params);
}
this.currTxQuality = newQ;
track.applyConstraints(params);
return true;
}
rxTotalArea() {
let area = 0;
for (const peer of this.client.peers.values()) {
if ((peer.av & Av.onHold)) {
continue;
}
const player = peer.hiResPlayer;
if (player && player.slot) {
const props = player.slot.inTrack.getSettings();
area += props.width * props.height;
}
}
return area;
}
initTx() {
if (this.client.isSendingScreenHiRes()) {
// need small delay to have the track started
setTimeout(this.setTxQuality.bind(this, this.currTxQuality, "scr"), 100);
}
}
}
SvcDriver.kRttLowerHeadroom = 20;
SvcDriver.kRttUpperHeadroom = 100;
SvcDriver.kPlostUpperHeadroom = 3;
SvcDriver.kPlostLowerHeadroom = 0.01;
SvcDriver.kPlostCap = 3; // cap on adaptive continuous packet loss reference
SvcDriver.kPlostCritical = 10;
SvcDriver.kQualityDecreaseSettleTime = 6000;
SvcDriver.kQualityIncreaseSettleTime = 4000;
SvcDriver.kRxUpFailMonitorDur = 40000;
SvcDriver.kRxUpFailDur = 40000;
SvcDriver.kRxUpFailMaxExtendPeriod = 140000;
SvcDriver.kRxUpFailDurDecayMult = 0.5;
// (427)x240 - sends only one spatial layer, i.e. receiver can't get lower resolution than 240
// (640)x360 - 2 spatial layers: receiver can get x180 or x360
// (852)x480 - 2 spatial layers: 240 and 480
// (960)x540 - 3 spatial layers: 136, 270 and 540. This is the camera capture resolution
// anything above x540 is only for screen sharing, where there are no spatial layers
// (1028)x578 - screen sharing
// Array(spatial, temporal, screen-temporal)
SvcDriver.RxQuality = [
[0, 0, 0],
[0, 1, 0],
[0, 2, 0],
[1, 1, 1],
[1, 2, 1],
[2, 1, 2],
[2, 2, 2],
];
SvcDriver.kMaxRxQualityIndex = SvcDriver.RxQuality.length - 1;
// minKbps, maxKbps, scr: constraints for applyConstraints() on sent screen track
SvcDriver.TxQuality = [
{ minKbps: 0, maxKbps: 300, scr: { height: 540, frameRate: 4 } },
{ minKbps: 280, maxKbps: 700, scr: { height: 720, frameRate: 4 } },
{ minKbps: 680, maxKbps: 1000, scr: { height: 840, frameRate: 4 } },
{ minKbps: 900, maxKbps: 1600, scr: { height: 1080, frameRate: 4 } },
{ minKbps: 1500, maxKbps: 1800, scr: { height: 1080, frameRate: 8 } },
{ minKbps: 1700, maxKbps: 2000, scr: { height: 1200, frameRate: 8 } },
{ minKbps: 1900, maxKbps: 4000, scr: { height: 1440, frameRate: 8 } } // 6
];
SvcDriver.kMaxTxQualityIndex = SvcDriver.TxQuality.length - 1;
;// CONCATENATED MODULE: ../shared/commitId.ts
const COMMIT_ID = '360250a8c2';
/* harmony default export */ const commitId = (COMMIT_ID);
;// CONCATENATED MODULE: ./client.ts
/* Mega SFU Client library */
function client_assert(cond) {
if (!cond) {
throw new Error("Assertion failed");
}
}
var SpeakerState;
(function (SpeakerState) {
SpeakerState[SpeakerState["kNoSpeaker"] = 0] = "kNoSpeaker";
SpeakerState[SpeakerState["kPending"] = 1] = "kPending";
SpeakerState[SpeakerState["kActive"] = 2] = "kActive";
})(SpeakerState || (SpeakerState = {}));
var ConnState;
(function (ConnState) {
ConnState[ConnState["kDisconnected"] = 0] = "kDisconnected";
ConnState[ConnState["kDisconnectedRetrying"] = 1] = "kDisconnectedRetrying";
ConnState[ConnState["kConnecting"] = 2] = "kConnecting";
ConnState[ConnState["kInWaitingRoom"] = 3] = "kInWaitingRoom";
ConnState[ConnState["kCallJoining"] = 4] = "kCallJoining";
ConnState[ConnState["kCallJoined"] = 5] = "kCallJoined";
})(ConnState || (ConnState = {}));
var ScreenShareType;
(function (ScreenShareType) {
ScreenShareType[ScreenShareType["kInvalid"] = 0] = "kInvalid";
ScreenShareType[ScreenShareType["kWholeScreen"] = 1] = "kWholeScreen";
ScreenShareType[ScreenShareType["kWindow"] = 2] = "kWindow";
ScreenShareType[ScreenShareType["kBrowserTab"] = 3] = "kBrowserTab";
})(ScreenShareType || (ScreenShareType = {}));
var CallJoinPermission;
(function (CallJoinPermission) {
CallJoinPermission[CallJoinPermission["kUnknown"] = 0] = "kUnknown";
CallJoinPermission[CallJoinPermission["kAllow"] = 1] = "kAllow";
CallJoinPermission[CallJoinPermission["kDeny"] = 2] = "kDeny";
})(CallJoinPermission || (CallJoinPermission = {}));
;
class SfuClient {
constructor(userId, app, callKey, options, url) {
this.peers = new Map();
this._isSharingScreen = false;
this._muteCamera = false;
this._muteAudio = false;
this._sendVthumb = false;
this._sendHires = false;
this._cameraTrack = null;
this._screenTrack = null;
this._audioTrack = null;
this._availAv = 0;
this._sentAv = 0;
this._joinRetries = 0;
this._forcedDisconnect = false;
this._tsCallJoin = 0;
this._tsCallStart = 0;
this.joinToffs = 0;
this.statCtx = {};
this.hasConnStats = false;
this.maxPeers = 0;
this.micAudioLevel = 0;
this.tsMicAudioLevel = 0;
if (!SfuClient.platformHasSupport()) {
throw new Error("This browser does not support insertable streams");
}
client_assert(options);
this.userId = userId;
this.app = app;
this._reqBarrier = new RequestBarrier;
this._speakerState = SpeakerState.kNoSpeaker;
this._connState = ConnState.kDisconnected;
this.options = options;
if (callKey) {
this.setCallKey(callKey);
}
this.url = url;
this.cryptoWorker = new Worker(SfuClient.kWorkerUrl);
this.cryptoWorker.addEventListener("message", this.onCryptoWorkerEvent.bind(this));
this._svcDriver = new SvcDriver(this);
this._speakerDetector = new SpeakerDetector(this);
this._statsRecorder = new StatsRecorder(this);
this.micMuteMonitor = new MicMuteMonitor(this);
}
get micInputSeen() { return this.micMuteMonitor.micInputSeen; }
static platformHasSupport() {
return window.RTCRtpSender &&
!!RTCRtpSender.prototype.createEncodedStreams;
}
logError(...args) {
console.error.apply(console, args);
let msg = args.join(' ');
let url = `${SfuClient.kStatServerUrl}/msglog?userid=${this.userId}&t=e`;
if (this.callId) {
url += `&callid=${this.callId}`;
}
fetch(url, { method: "POST", body: msg });
}
onCryptoWorkerEvent(event) {
let msg = event.data;
console.debug("Message from crypto worker:", msg);
if ((msg.op === "keyset") && (this.keySetPromise && msg.keyId === this.keySetPromise.keyId)) {
this.keySetPromise.resolve();
delete this.keySetPromise;
}
}
isModerator() {
return this.moderators ? this.moderators.has(this.userId) : true;
}
isJoining() {
return this._connState < ConnState.kCallJoined;
}
isLeavingCall() {
return !isNaN(this.termCode);
}
get connState() {
return this._connState;
}
get callJoinPermission() {
return this._callJoinPermission;
}
willReconnect() {
if (this._forcedDisconnect) {
return false;
}
return SfuClient.isTermCodeRetriable(this.termCode);
}
static isTermCodeRetriable(termCode) {
return termCode === termCodes.kRtcDisconn ||
termCode === termCodes.kSigDisconn; // || termCode === TermCode.kSfuShuttingDown;
// TODO: handle SFU shutdown gracefully and reconnect
}
async onWsClose(event) {
if (event && event.target !== this.conn) {
console.warn("onWsClose: ignoring stale event for a previous websocket instance");
return;
}
console.warn("SfuClient: Signaling connection closed");
delete this.conn;
this.leaveCall(termCodes.kSigDisconn); // sets this.termCode
const willReconnect = this.willReconnect(); // decides based on this.termCode
if (willReconnect) {
this._setConnState(ConnState.kDisconnectedRetrying);
this.scheduleReconnect();
}
else {
this._setConnState(ConnState.kDisconnected);
this._stopLocalTracks();
}
this._fire("onDisconnect", this.termCode, willReconnect);
}
leaveCall(termCode) {
if (this.termCode == null) {
this.termCode = termCode;
}
if (this.statTimer) {
clearTimeout(this.statTimer);
}
this.disableStats();
if (this._connState === ConnState.kCallJoined) {
this._statsRecorder.submit(this.termCode);
}
this._closeMediaConnection();
this._destroyAllPeers(this.termCode);
}
async scheduleReconnect() {
let delay = this._joinRetries++ * 500;
if (delay > 2000) {
delay = 2000;
}
console.warn("Reconnecting in", delay, "ms....");
await msDelay(delay);
if (!this._forcedDisconnect) {
this.connect();
}
}
_closeMediaConnection() {
if (this.rtcConn) {
this.rtcConn.close();
delete this.rtcConn;
}
}
_destroyAllPeers(reason) {
for (let peer of this.peers.values()) {
peer.destroy(reason);
}
this.peers.clear();
}
_fire(evName, ...args) {
let method = this.app[evName];
if (!method) {
console.warn(`Unhandled event: ${evName}(${args.join(",")})`);
return;
}
console.log(`fire [${evName}](${args.join(',')})`);
try {
method.call(this.app, ...args);
}
catch (ex) {
this.logError("Event handler for", evName, "threw exception:", ex.stack);
}
}
async generateKey() {
let keyObj = await window.crypto.subtle.generateKey({ name: "AES-GCM", length: 128 }, true, ["encrypt", "decrypt"]);
let tsStart = Date.now();
let key = await crypto.subtle.exportKey("raw", keyObj);
console.warn(`exportKey completed in ${Date.now() - tsStart} ms`);