-
Notifications
You must be signed in to change notification settings - Fork 0
/
qchat-app.js
4073 lines (3460 loc) · 169 KB
/
qchat-app.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
/* eslint-disable nonblock-statement-body-position */
/* global Croquet AgoraRTC */
// v4
AgoraRTC.setLogLevel(1); // 1=INFO
AgoraRTC.enableLogUpload();
const { searchParams } = new URL(window.location);
const isBackdrop = searchParams.get('backdrop') !== null;
const isSpectator = searchParams.has('spectator');
const sessionConfiguration = {
channelName: searchParams.get('channelName') || searchParams.get('c') || 'all',
nickname: searchParams.get('nickname') || searchParams.get('n') || '',
initials: searchParams.get('initials') || searchParams.get('i') || '',
viewColor: searchParams.get('viewColor') || searchParams.get('userColor') || searchParams.get('h') || `hsl(${Math.floor(Math.random() * 255)}, 40%, 40%)`,
mic: searchParams.get('mic') || searchParams.get('m') || (isBackdrop ? 'on' : 'off'),
video: searchParams.get('video') || searchParams.get('v') || (isBackdrop ? 'on' : 'off'),
innerWidth: searchParams.get('iw') || 0,
innerHeight: searchParams.get('ih') || 0,
requestName: searchParams.has('requestName'),
};
// some settings are determined by which html file was loaded to get here
const htmlConfig = window.htmlConfig || {};
const isVideoAllowed = !htmlConfig.audioOnly;
if (!isVideoAllowed) sessionConfiguration.video = 'unavailable'; // hard override
if (htmlConfig.resizeFrame) sessionConfiguration.resizeFrame = true;
if (htmlConfig.parentJoinLeave) sessionConfiguration.parentJoinLeave = true;
const cover = document.getElementById('cover'); // only in index.html, else null
const joinDialog = document.getElementById('joinDialog'); // only in audioOnly, microverse
const ui = document.getElementById('ui');
if (isSpectator) {
sessionConfiguration.mic = 'off';
sessionConfiguration.video = 'off';
ui.classList.add('spectator');
}
/*
in Agora v4, the notion of publishing and unpublishing a stream that could contain an audio and/or video track was replaced with the publishing and unpublishing of tracks separately.
with Agora v3, the client needed to publish its stream - which combined audio and video tracks - whenever it wanted to be sending either audio or video. if both audio and video were muted, it needed to ensure that its stream was unpublished. with v4, a track needs to be published once, after which it can be enabled or disabled at will (to unmute and mute). remote peers will receive a "user-published" event for any track that is published (presumably only if it is enabled at that point), and "user-unpublished" if it is later disabled or explicitly unpublished - e.g., to replace with an alternative track.
migration guide at https://docs.agora.io/en/Interactive%20Broadcast/migration_guide_web_ng?platform=Web
code examples https://github.com/AgoraIO/API-Examples-Web, especially
https://github.com/AgoraIO/API-Examples-Web/blob/main/Demo/basicVideoCall/basicVideoCall.js
*/
class StreamMixerInput {
// created for each local video source. makes a
// dedicated video element, and provides a draw()
// method for drawing to the main canvas when
// this source is online.
constructor(stream, streamMixer) {
this.stream = stream;
this.streamMixer = streamMixer;
if (stream.getVideoTracks().length) {
this.alpha = 0;
this.video = document.createElement('video');
this.video.playsInline = true;
this.video.muted = true;
this.video.autoplay = true;
this.video.onloadedmetadata = this.onloadedmetadata.bind(this);
this.video.onplay = this.updateVideoSize.bind(this);
this.video.onresize = this.onresize.bind(this);
this.video.srcObject = stream;
window.setTimeout(this.updateVideoSize.bind(this, true), 1000);
}
}
get width() { return this.video ? this.stream.getVideoTracks()[0].getSettings().width : undefined; }
get height() { return this.video ? this.stream.getVideoTracks()[0].getSettings().height : undefined; }
get aspectRatio() { return this.video ? this.width / this.height : undefined; }
onloadedmetadata() {
this.video.loadedmetadata = true;
this.updateVideoSize(true);
}
onresize() {
this.updateVideoSize();
}
updateVideoSize(updateStreamMixer = false) {
this.video.width = this.width;
this.video.height = this.height;
if (updateStreamMixer || this.alpha === 1) {
this.streamMixer.aspectRatio = this.aspectRatio;
}
}
draw(canvas) {
if (this.video && this.alpha > 0) {
const context = canvas.getContext('2d');
context.save();
context.globalAlpha = this.alpha;
context.drawImage(this.video, 0, 0, this.width, this.height, 0, 0, canvas.width, canvas.height);
context.restore();
}
}
remove() {
if (this.video) {
this.video.pause();
this.video.srcObject = null;
}
}
}
class StreamMixer {
// for selecting - and, if necessary, blending - the
// video for our local stream.
constructor(streamManager) {
this.streamManager = streamManager;
this.inputs = [];
this.canvases = [];
this.canvas = document.createElement('canvas');
this.canvas.classList.add('peerVideo');
this.canvas.width = 640;
this.canvas.height = 480;
this.canvasContext = this.canvas.getContext('2d');
this.frameRate = isBackdrop ? 30 : 12;
this.canvasStream = this.canvas.captureStream(this.frameRate);
}
get filter() { return this.canvasContext.filter; }
set filter(filter) { this.canvasContext.filter = filter; }
get videoInputs() {return this.inputs.filter(input => input.video);}
// get audioInputs() {return this.inputs.filter(input => input.audio);}
getInputByStream(stream) {return this.inputs.find(input => input.stream === stream);}
addStream(stream) {
let input = this.getInputByStream(stream);
if (!input) {
input = new StreamMixerInput(stream, this);
this.inputs.push(input);
if (input.video) {
input.video.play().catch(err => {
console.error(`video.play() failed`, err);
this.streamManager.chatManager.playBlocked(() => input.video.play());
});
}
}
return input;
}
removeStream(stream) {
const input = this.getInputByStream(stream);
if (input) {
input.remove();
this.inputs.splice(this.inputs.indexOf(input), 1);
return true;
}
return false;
}
get isDrawing() {return !!this.drawIntervalId;}
startDrawing() {
if (this.isDrawing) this.stopDrawing(false);
this.drawIntervalId = window.setInterval(this.draw.bind(this), 1000 / this.frameRate);
}
draw() {
this.updateSize();
const compositingCanvas = this.canvas;
/* eslint-disable-next-line no-self-assign */
compositingCanvas.width = compositingCanvas.width; // clear
// draw all the video inputs onto the working canvas
this.videoInputs.forEach(videoInput => videoInput.draw(compositingCanvas));
// add the waveform
this.streamManager.drawWaveform(compositingCanvas);
// copy the working canvas image to each output canvas
this.canvases.forEach(canvas => {
/* eslint-disable-next-line no-self-assign */
canvas.width = canvas.width; // clear
const context = canvas.getContext('2d');
context.drawImage(compositingCanvas, 0, 0);
});
}
stopDrawing(clearCanvas = true) {
if (this.isDrawing) {
window.clearInterval(this.drawIntervalId);
delete this.drawIntervalId;
if (clearCanvas) {
const compositingCanvas = this.canvas;
/* eslint-disable-next-line no-self-assign */
compositingCanvas.width = compositingCanvas.width; // clear
this.canvases.forEach(canvas => {
/* eslint-disable-next-line no-self-assign */
canvas.width = canvas.width; // clear
});
}
}
}
addOutputCanvas(canvas) {
if (!this.canvases.includes(canvas)) {
canvas.width = this.width;
canvas.height = this.height;
this.canvases.push(canvas);
}
}
removeOutputCanvas(canvas) {
if (this.canvases.includes(canvas))
this.canvases.splice(this.canvases.indexOf(canvas), 1);
}
get width() {return this.canvas.width;}
set width(width) {
if (this.width === width || width === 0) return;
this._width = width;
this._height = width / this.aspectRatio;
this._updateSize = true;
}
get height() {return this.canvas.height;}
set height(height) {
if (this.height === height || height === 0) return;
this._height = height;
this._width = height * this.aspectRatio;
this._updateSize = true;
}
get aspectRatio() {return this.width / this.height;}
set aspectRatio(aspectRatio) {
if (this.aspectRatio === aspectRatio || aspectRatio === 0) return;
if (aspectRatio > 1) {
this._width = this.length;
this._height = this._width / aspectRatio;
} else {
this._height = this.length;
this._width = this._height * aspectRatio;
}
this._updateSize = true;
}
get length() {return Math.max(100, Math.max(this.width, this.height));}
set length(length) {
if (this.length === length || length === 0) return;
if (this.aspectRatio > 1) {
this._width = length;
this._height = this._width / this.aspectRatio;
} else {
this._height = length;
this._width = this._height * this.aspectRatio;
}
this._updateSize = true;
}
updateSize() {
// @@ put back the isNaNs. sort it out later.
if (this._updateSize) {
/* eslint-disable-next-line no-restricted-globals */
if (!isNaN(this._width)) {
this.canvas.width = this._width;
delete this._width;
}
/* eslint-disable-next-line no-restricted-globals */
if (!isNaN(this._height)) {
this.canvas.height = this._height;
delete this._height;
}
/* eslint-enable no-restricted-globals */
this.canvases.forEach(canvas => {
canvas.width = this.width;
canvas.height = this.height;
});
this._updateSize = false;
this.canvas.dispatchEvent(new Event('resize'));
this.canvases.forEach(canvas => canvas.dispatchEvent(new Event('resize')));
}
}
setFrameRate(frameRate) {
// we could check against the settings currently found in
// the stream, rather than the constraint we requested.
// but if that constraint has resulted in a different setting,
// there might not be any point in trying to request the
// same constraint again.
if (this.frameRate === frameRate) return;
this.frameRate = frameRate;
this.canvasStream.getVideoTracks()[0].applyConstraints({frameRate});
if (this.isDrawing) this.startDrawing();
}
_fade(stream, fadeIn = true, period = 500) {
const currentAspectRatio = this.aspectRatio;
return new Promise((resolve, _reject) => {
const videoInput = this.getInputByStream(stream);
if (videoInput && !videoInput._fade) {
videoInput._fade = true;
const newAspectRatio = videoInput.aspectRatio;
const now = Date.now();
const intervalId = setInterval(() => {
let interpolation = (Date.now() - now) / period;
interpolation = Math.min(interpolation, 1);
/* eslint-disable-next-line no-restricted-globals */
if (fadeIn && !isNaN(newAspectRatio) && !isNaN(currentAspectRatio)) {
const aspectRatio = (newAspectRatio * interpolation) + (currentAspectRatio * (1 - interpolation));
this.aspectRatio = aspectRatio;
}
if (interpolation < 1) {
videoInput.alpha = fadeIn ?
interpolation :
1 - interpolation;
} else {
videoInput.alpha = fadeIn ? 1 : 0;
delete videoInput._fade;
clearInterval(intervalId);
resolve(stream);
}
}, 1000 / this.frameRate);
} else
resolve(stream);
});
}
fadeIn(stream, period) {
return this._fade(stream, true, period);
}
fadeOut(stream, period) {
return this._fade(stream, false, period);
}
close() {
this.stopDrawing();
this.inputs.forEach(input => input.remove());
this.canvasStream.getVideoTracks()[0].stop();
this.canvases.length = 0;
}
}
class AgoraPeerManager {
constructor(chatManager) {
this.chatManager = chatManager;
this.viewId = this.chatManager.viewId;
// @@ long-lived temporary hack
this.elements = this.chatManager.elements;
this.peerDict = {}; // streams and flags by viewId (including local)
// this.uidDict = {}; // {uid: viewId};
this.ensurePeerState(this.viewId); // get it over with :)
this.connectionState = 'DISCONNECTED';
this.setUpConnectionPromise();
this.appID = 'a4df6cd2da8445c393b56527eacf529a';
this.setUpClient();
}
setUpConnectionPromise() {
this.connectionP = new Promise(resolve => this.resolveConnectionPromise = resolve);
}
setUpClient() {
this.client = AgoraRTC.createClient({ mode: 'rtc', codec: 'vp8' });
// insert our own try/catch into the handlers, because otherwise
// Agora will silently swallow any error
const addHandler = (eventName, handlerName) => {
this.client.on(eventName, (...data) => {
try {
this[handlerName](...data);
} catch (e) { console.error(e); }
});
};
// CONNECTING, CONNECTED, RECONNECTING (v4), DISCONNECTING, DISCONNECTED
addHandler('connection-state-change', 'onConnectionStateChange'); // v4
addHandler('user-published', 'onUserPublished'); // v4: sent to remote clients when a client publishes a video or audio track
addHandler('user-unpublished', 'onUserUnpublished'); // v4: sent to remote clients when a client unpublishes a track
addHandler('user-left', 'onUserLeft'); // sent to remote clients when a client leaves the room
addHandler('stream-fallback', 'onStreamFallback');
addHandler('join-fallback-to-proxy', 'onJoinFallbackToProxy'); // new in v4.9
addHandler('user-info-updated', 'onUserInfoUpdated');
addHandler('network-quality', 'onNetworkQuality');
addHandler('exception', 'onException');
addHandler('volume-indicator', 'onVolumeIndicator');
}
peerState(viewId) { return this.peerDict[viewId]; }
ensurePeerState(viewId) {
let state = this.peerDict[viewId];
if (!state) {
// for remote peers, videoDisabled and audioDisabled (which are used in
// setting a peer's display style) reflect directly whether there are
// null entries in mediaTracks (as updated by user-publish
// and user-unpublish events). for the local peer, the tracks live on
// but are selectively enabled and disabled (which, once they've been
// published, will trigger their being unpublished and republished)
// under local user control.
state = this.peerDict[viewId] = {
published: false,
audioTrack: null,
audioDisabled: true,
videoTrack: null,
videoDisabled: true,
lastAnnounce: Date.now(),
left: false
};
}
return state;
}
get localPeerState() { return this.peerState(this.viewId); }
isKnownPeer(viewId) {
const state = this.peerState(viewId);
return !!(state && !state.left);
}
removePeerState(viewId) {
delete this.peerDict[viewId];
}
setPeerLastAnnounce(viewId) {
const state = this.ensurePeerState(viewId);
state.lastAnnounce = Date.now();
}
getPeerIds() { return Object.keys(this.peerDict); }
getPeerMedia(viewId, mediaType) {
// if the view hasn't been heard of yet, return null
const prop = `${mediaType}Track`;
return this.peerState(viewId)?.[prop];
}
async setLocalAudio(nativeTrack) {
const state = this.localPeerState;
const { audioTrack, audioDisabled } = state;
delete state.audioTrack;
const newAudioTrack = await AgoraRTC.createCustomAudioTrack({ mediaStreamTrack: nativeTrack });
// iff the audio has been published and is currently unmuted, replace it
if (audioTrack && !audioDisabled && audioTrack._croquetPublished) {
await this.client.unpublish(audioTrack);
await newAudioTrack.setMuted(false);
newAudioTrack._croquetPublished = true;
await this.client.publish(newAudioTrack);
this.elements.ui.classList.add('published-tracks');
}
state.audioTrack = newAudioTrack;
this.chatManager.onPeerMedia(this.viewId, 'audio', newAudioTrack);
}
async setLocalVideo(nativeTrack) {
// this embodies the assumption that the video track is never replaced
const state = this.localPeerState;
const newVideoTrack = await AgoraRTC.createCustomVideoTrack({ mediaStreamTrack: nativeTrack });
state.videoTrack = newVideoTrack;
this.chatManager.onPeerMedia(this.viewId, 'video', newVideoTrack);
}
registerPeerMedia(viewId, mediaType, track) {
const state = this.ensurePeerState(viewId);
state.published = true;
const trackProp = `${mediaType}Track`;
// if we got a new stream from the same peer, remove the old one.
const knownTrack = state[trackProp];
if (knownTrack && knownTrack !== track) this.chatManager.offPeerMedia(viewId, mediaType, knownTrack);
state[trackProp] = track;
state[`${mediaType}Disabled`] = false;
}
unregisterPeerMedia(viewId, mediaType) {
const state = this.ensurePeerState(viewId);
delete state[`${mediaType}Track`];
state[`${mediaType}Disabled`] = true;
state.published = ['audioTrack', 'videoTrack'].some(key => state[key]);
}
// LOCAL CHAT CONNECTION
connect() {
// invoked on clicking Join button when DISCONNECTED, or in chatManager.addPeer
// when this is DISCONNECTED but still in the Croquet session
if (this.connectionState === 'DISCONNECTED' && this.chatManager.numberOfPeers > 1) {
// NB: the null arg is in place of a token, which Agora
// supports for apps that need authentication of individual
// clients. i.e., we're using the "low security" approach.
// https://docs.agora.io/en/Interactive%20Broadcast/API%20Reference/web/interfaces/agorartc.client.html#join
// the channel-name arg can be up to 64 bytes. most
// punctuation is ok, but apparently not "/" or "\".
// v4 events: https://docs.agora.io/en/Interactive%20Broadcast/API%20Reference/web_ng/interfaces/iagorartcclient.html?platform=Web
this.client.join(this.appID, sessionConfiguration.channelName, null, this.viewId)
.then(_uid => {
// the connection-state change has probably already arrived
// console.log("successful client.join()");
this.resolveConnectionPromise();
}).catch((err) => console.error(err));
}
}
disconnect() {
// invoked from shutDown, or chatManager.removePeer
// if total number of peers has dropped to 1.
if (this.connectionState === 'CONNECTED' || this.connectionState === "CONNECTING") {
this.client.leave()
.then(() => console.log("left chat"))
.catch(err => console.log(`Error on leaving chat: ${err.message}`));
}
}
ensureConnected() {
if (this.connectionState !== 'CONNECTED' && this.connectionState !== 'CONNECTING') {
this.connect();
}
}
ensureDisconnected() {
if (this.connectionState !== 'DISCONNECTED' && this.connectionState !== 'DISCONNECTING') {
this.disconnect();
}
}
// v4
onConnectionStateChange(curState, revState, reason) {
// console.log(`received connection state ${curState}`);
this.connectionState = curState;
let localState;
switch (this.connectionState) {
case 'DISCONNECTED':
// v4: could at least log the reason
this.elements.ui.classList.remove('connected');
this.stopCheckingPeerState();
// if this is a shutdown, local state will have been cleared
localState = this.localPeerState;
if (localState) {
// in case we're about to reconnect, leave in place the audio/video
// status (track, disabled state) but remove the tracks' published
// flag, so that on reconnection we'll publish again.
localState.published = false;
localState.left = true;
if (localState.audioTrack) delete localState.audioTrack._croquetPublished;
if (localState.videoTrack) delete localState.videoTrack._croquetPublished;
this.setUIForPublishState(localState.published);
}
this.chatManager.onChatDisconnected();
this.setUpConnectionPromise();
break;
case 'CONNECTING':
case 'RECONNECTING':
// after join() is called, or during Agora's automatic reconnect
// attempt when connection is temporarily lost
break;
case 'CONNECTED':
this.elements.ui.classList.add('connected');
localState = this.localPeerState;
localState.left = false;
// on first connection, these will have already been called. but
// the duplication doesn't matter, and we need to call from here
// for reconnections.
if (!localState.audioDisabled) this.ensureAudioMuteState(false);
if (!localState.videoDisabled) this.ensureVideoMuteState(false);
this.startCheckingPeerState();
this.chatManager.onChatConnected();
break;
default:
break;
}
}
startCheckingPeerState() {
this.stopCheckingPeerState();
this._checkPeersIntervalId = window.setInterval(this.checkPeers.bind(this), 1000);
}
stopCheckingPeerState() {
if (this._checkPeersIntervalId) {
window.clearInterval(this._checkPeersIntervalId);
delete this._checkPeersIntervalId;
}
}
checkPeers() {
this.getPeerIds().forEach(viewId => {
// this is only to catch a peer that is not playing by
// the normal rules (typically, a remnant caused by a
// peer reloading with a different view id). any peer
// already recorded as having left, or that is currently
// published, is not under suspicion.
if (viewId === this.viewId) return;
const state = this.peerDict[viewId];
if (state.left || state.published) return;
const seconds = Math.floor((Date.now() - state.lastAnnounce) / 1000);
if (seconds >= 35) {
console.warn(`${viewId} not heard from in ${seconds}s; assuming it has left chat`);
state.left = true;
// make the rest asynchronous
Promise.resolve().then(() => {
this.cleanUpTracksForLeavingPeer(viewId);
this.chatManager.provisionallyRemovePeer(viewId);
});
}
});
}
async ensureAudioMuteState(muted) {
// used to mute/unmute our audio in the call.
// given the choice between setEnabled and setMuted, for audio we use the
// latter because (according to API docs) it switches more quickly.
// in v4, setMuted() automatically triggers publishing and unpublishing
// of the track iff it's already been published.
// wait on the connection promise to ensure the client is ready to publish.
const localState = this.localPeerState;
const { audioTrack, audioDisabled } = localState;
if (audioDisabled !== muted) {
localState.audioDisabled = muted;
await audioTrack.setMuted(muted);
}
if (!muted && !audioTrack._croquetPublished) {
await this.connectionP;
if (localState.audioDisabled || localState.audioTrack._croquetPublished) return;
audioTrack._croquetPublished = true;
await this.client.publish(audioTrack);
console.log("own audio published");
}
// if audio is muted, our published state depends on the video track
localState.published = !muted || !localState.videoDisabled;
this.setUIForPublishState(localState.published);
}
async ensureVideoMuteState(disabled) {
// used to mute/unmute our video in the call.
// given the choice between setEnabled and setMuted, we use the former
// because when enabled=false the camera light will be turned off, as
// the user would expect.
// in v4, setEnabled() automatically triggers publishing and unpublishing
// of the track iff it's already been published.
// @@ in v3 it was used on remote streams too, for temporarily suspending incoming video for peers we didn't want to display. if that's helpful for CPU usage, we might need to figure out an equivalent mechanism. see calls to ensurePeerVideoDisplayState.
const localState = this.localPeerState;
const { videoTrack, videoDisabled } = localState;
if (videoDisabled !== disabled) {
localState.videoDisabled = disabled;
await videoTrack.setEnabled(!disabled);
}
if (!disabled && !videoTrack._croquetPublished) {
await this.connectionP;
if (localState.videoDisabled || localState.videoTrack._croquetPublished) return;
videoTrack._croquetPublished = true;
await this.client.publish(videoTrack);
console.log("own video published");
}
// if video is disabled, our published state depends on the audio track
localState.published = !disabled || !localState.audioDisabled;
this.setUIForPublishState(localState.published);
}
onClientRoleChanged(event) {
console.log("onClientRoleChanged", event);
}
// REMOTE PEER STATE
async onUserPublished(user, mediaType) {
console.log("onuserpublished", user, mediaType);
const viewId = user.uid;
this.chatManager.postponePeerCheck(viewId);
const state = this.ensurePeerState(viewId);
delete state.left; // in case the peer went and came back
// make sure we don't have multiple subscribe attempts for same publish
const timerProp = `${mediaType}SubscribeTimer`;
if (state[timerProp]) {
clearTimeout(state[timerProp]);
delete state[timerProp];
}
// aug 2022 comment from Agora Support on connecting in the presence of network errors:
// "when our SDK tries to subscribe remote user stream track, if a connection issue occurs which failed the subscription, our SDK won't automatically help re-subscribe remote users. In this case, in your code, you may add logic to check if the promise of API subscribe is null. You may call it again if yes."
// practically speaking, during bad network conditions it looks like the promise
// tends to just hang around - without being resolved or rejected - until either
// the condition clears, or the client drops into automatic reconnection.
const tryToSubscribe = async () => {
let status, errMsg;
try {
status = await this.client.subscribe(user, mediaType);
} catch (e) {
errMsg = e.message;
}
if (status && !errMsg) {
// there's a narrow window in which an unpublish immediately after
// a publish will cause the client.subscribe call to (misleadingly)
// succeed. but the user object knows what's up.
const track = user[`${mediaType}Track`];
if (!track) {
console.warn(`subscribe: ${mediaType} track for ${viewId} disappeared while subscribing`);
return;
}
console.log(`subscribed to ${viewId}'s ${mediaType}`);
this.registerPeerMedia(viewId, mediaType, track);
this.chatManager.onPeerMedia(viewId, mediaType, track);
} else {
let msg = `will retry subscribe for ${viewId}'s ${mediaType}`;
if (errMsg) msg += ` following error: ${errMsg}`;
console.warn(msg);
state[timerProp] = setTimeout(() => {
if (state.left || !state[timerProp]) return; // left or unpublished while we were waiting
delete state[timerProp];
tryToSubscribe();
}, 2000);
this.chatManager.publishTrackSubscriptions(); // so remote peer realises there's a problem
}
};
tryToSubscribe();
}
async onUserUnpublished(user, mediaType) {
// a remote user has unpublished one of its tracks (perhaps the last)
console.log("onuserunpublished", user, mediaType);
const viewId = user.uid;
this.chatManager.postponePeerCheck(viewId);
const state = this.ensurePeerState(viewId);
const timerProp = `${mediaType}SubscribeTimer`;
if (state[timerProp]) {
clearTimeout(state[timerProp]);
delete state[timerProp];
}
// check that we knew of the track we'll supposedly be unsubscribing from
const track = this.getPeerMedia(viewId, mediaType);
if (!track) {
console.warn(`unsubscribe: failed to find ${mediaType} track for ${viewId}`);
this.chatManager.publishTrackSubscriptions(); // so remote peer knows the situation
return;
}
try {
await this.client.unsubscribe(user, mediaType);
console.log(`unsubscribed from ${viewId}'s ${mediaType}`);
} catch (e) {
console.error(e);
}
// first unregister the track, so we can update the .published
// state for offPeerMedia to access.
this.unregisterPeerMedia(viewId, mediaType);
this.chatManager.offPeerMedia(viewId, mediaType, track);
}
onUserLeft(user, reason) {
// sent to remote peers when a peer leaves the room,
// or its role changes from "host" to "audience".
// in the latter case, the peer is still there; we
// shouldn't remove its record.
// reason is one of "Quit", "ServerTimeOut", "BecomeAudience"
const viewId = user.uid;
console.log(`peer ${viewId} left: ${reason}`);
const state = this.peerState(viewId);
if (!state) {
console.warn(`leaving ${viewId} record not found`);
return;
}
this.cleanUpTracksForLeavingPeer(viewId);
if (reason !== "BecomeAudience") {
// no expectation that this peer will return
// - but chatManager won't throw it out unless/until
// the peer disappears from the Croquet session too.
state.left = true;
this.chatManager.provisionallyRemovePeer(viewId);
}
}
cleanUpTracksForLeavingPeer(viewId, shutdown = false) {
const state = this.peerDict[viewId];
const { audioTrack, videoTrack } = state;
if (audioTrack) this.chatManager.offPeerMedia(viewId, 'audio', audioTrack, shutdown);
if (videoTrack) this.chatManager.offPeerMedia(viewId, 'video', videoTrack, shutdown);
state.audioDisabled = state.videoDisabled = true;
state.published = false;
}
setUIForPublishState(published) {
if (published) this.elements.ui.classList.add('published-tracks');
else this.elements.ui.classList.remove('published-tracks');
}
onStreamFallback(uid, direction) { console.warn(`stream-fallback (${direction} for user ${uid}`); }
onJoinFallbackToProxy(server) { console.warn(`join-fallback-to-proxy ${server}`); }
onUserInfoUpdated(...data) {
console.log("user info updated", ...data);
}
onNetworkQuality(stats) {
/* per https://docs.agora.io/en/Video/API%20Reference/web_ng/interfaces/networkquality.html, for each of uplink and downlink the number means:
0: The quality is unknown.
1: The quality is excellent.
2: The quality is good, but the bitrate is less than optimal.
3: Users experience slightly impaired communication.
4: Users can communicate with each other, but not very smoothly.
5: The quality is so poor that users can barely communicate.
6: The network is disconnected and users cannot communicate.
*/
const { uplinkNetworkQuality, downlinkNetworkQuality } = stats;
if (uplinkNetworkQuality > 1 || downlinkNetworkQuality > 1) console.log(stats);
}
onException(event) {
console.log(`Agora exception ${event.code} (${event.msg}) for ${event.uid}`);
}
shutDown() {
this.stopCheckingPeerState();
Object.keys(this.peerDict).forEach(viewId => {
if (viewId !== this.viewId) this.cleanUpTracksForLeavingPeer(viewId);
this.removePeerState(viewId);
});
this.disconnect();
}
}
class LocalMediaManager {
constructor(chatManager) {
this.chatManager = chatManager;
// @@ something of a hack
this.elements = chatManager.elements;
this.audioContext = chatManager.audioContext;
this.userWantsAudio = chatManager.userWantsLocalAudio;
this.userWantsVideo = chatManager.userWantsLocalVideo;
this.localInputStreams = {}; // selected audio, selected video
if (this.userWantsAudio) {
// create a gain node that is always
// connected to an analyser to measure level (even if the
// stream to the call is muted), and to testAudioNode for
// listening to one's own mic.
this.gainNode = this.audioContext.createGain();
this.gainNode.gain.value = 1;
this.analyser = this.audioContext.createAnalyser();
this.analyser.fftSize = 4096; // approx 85ms at 48k
this.byteTimeDomainData = new Uint8Array(this.analyser.fftSize);
this.gainNode.connect(this.analyser);
this.testAudioNode = this.audioContext.createMediaStreamDestination();
this.elements.localAudio.srcObject = this.testAudioNode.stream;
this.gainNode.connect(this.testAudioNode);
this.elements.localAudio.muted = true;
// WAVEFORM
// currently set to take 20 samples to display 0.5s,
// requiring a sample every 25ms.
const config = this.waveformConfiguration = {
period: 0.5,
sampleCount: 20,
waveform: [],
};
config.sampleInterval = 1000 * config.period / config.sampleCount;
}
this.streamMixer = new StreamMixer(this);
}
// PEER INPUT STREAMS
chatVideoSource() { return this.streamMixer.canvasStream.getVideoTracks()[0]; }
async startMedia() {
if (this.userWantsVideo) {
this.chatVideoTrack = this.chatVideoSource(); // this never changes
this.chatManager.localVideoStarted(this.chatVideoTrack);
await this.updateVideoInputs();
}
if (this.userWantsAudio) {
await this.updateAudioInputs();
await this.setAudioInput(); // includes setting chatAudioTrack
// on Safari (at least), the audioContext doesn't start
// in 'running' state. it seems we can start it here, now
// we have the user permissions.
// when audio is not available, we still need an audioContext
// for measuring other peers' streams. this check is carried
// out in chatManager.frobPlayHooks.
const audioContext = this.audioContext;
if (audioContext.state !== 'running' && audioContext.state !== 'closed')
audioContext.resume();
this.startWaveform();
this.startTestingAudioLevel();
}
this.mediaStarted = true;
}
stopStream(stream) {
if (!stream) return;
stream.getTracks().forEach(track => track.stop());
}
stopAudioStream() {
if (this.localInputStreams.audio) {
this.stopStream(this.localInputStreams.audio);
delete this.localInputStreams.audio;
}
if (this.localInputStreams.mediaStreamSource) {
this.localInputStreams.mediaStreamSource.disconnect();
delete this.localInputStreams.mediaStreamSource;
}
}
stopVideoStream() {
if (this.localInputStreams.video) {
this.stopStream(this.localInputStreams.video);
delete this.localInputStreams.video;
}
}
onDeviceChange() {
// a device has come or gone. update the selectors.
// ...unless we're still in the process of initialising
// the media for the first time.
if (!this.mediaStarted) return;
if (this.userWantsVideo) this.updateVideoInputs();
if (this.userWantsAudio) this.updateAudioInputs();
}
// VIDEO
updateVideoInputs() {
// refresh the video-selection list with all available built-in devices
if (this._updateVideoInputsPromise) return this._updateVideoInputsPromise;
const previousSelection = this.elements.videoInputs.selectedOptions[0];
const previousLabel = (previousSelection && previousSelection.label)
|| (this.localInputStreams.video && this.localInputStreams.video._label)
|| sessionConfiguration.cameraDeviceLabel;
let lookingForPrevious = !!previousLabel;
let firstOption;
const videoInputs = this.elements.videoInputs;
videoInputs.innerHTML = '';
const videoPlaceholderOption = document.createElement('optgroup');
videoPlaceholderOption.disabled = true;
videoPlaceholderOption.selected = false;
videoPlaceholderOption.label = "Select Camera";
videoInputs.appendChild(videoPlaceholderOption);
// v4
const promise = this._updateVideoInputsPromise = AgoraRTC.getDevices()
.then(devices => {
devices.filter(device => device.kind === 'videoinput').forEach(device => {
const { deviceId, label } = device;
// re-apply any earlier selection
const selected = lookingForPrevious && previousLabel === label;
if (selected) lookingForPrevious = false;