-
Notifications
You must be signed in to change notification settings - Fork 477
/
DefaultAudioVideoController.ts
1710 lines (1556 loc) · 72.8 KB
/
DefaultAudioVideoController.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
import { MeetingSessionCredentials, ReceiveRemoteVideoPauseResumeTask } from '..';
import ActiveSpeakerDetector from '../activespeakerdetector/ActiveSpeakerDetector';
import DefaultActiveSpeakerDetector from '../activespeakerdetector/DefaultActiveSpeakerDetector';
import AudioMixController from '../audiomixcontroller/AudioMixController';
import DefaultAudioMixController from '../audiomixcontroller/DefaultAudioMixController';
import AudioProfile from '../audioprofile/AudioProfile';
import AudioVideoController from '../audiovideocontroller/AudioVideoController';
import AudioVideoObserver from '../audiovideoobserver/AudioVideoObserver';
import DefaultBrowserBehavior from '../browserbehavior/DefaultBrowserBehavior';
import ConnectionHealthData from '../connectionhealthpolicy/ConnectionHealthData';
import SignalingAndMetricsConnectionMonitor from '../connectionmonitor/SignalingAndMetricsConnectionMonitor';
import Destroyable from '../destroyable/Destroyable';
import VideoQualitySettings from '../devicecontroller/VideoQualitySettings';
import AudioVideoEventAttributes from '../eventcontroller/AudioVideoEventAttributes';
import EventController from '../eventcontroller/EventController';
import Logger from '../logger/Logger';
import MediaStreamBroker from '../mediastreambroker/MediaStreamBroker';
import MediaStreamBrokerObserver from '../mediastreambrokerobserver/MediaStreamBrokerObserver';
import MeetingSessionConfiguration from '../meetingsession/MeetingSessionConfiguration';
import MeetingSessionStatus from '../meetingsession/MeetingSessionStatus';
import MeetingSessionStatusCode from '../meetingsession/MeetingSessionStatusCode';
import MeetingSessionVideoAvailability from '../meetingsession/MeetingSessionVideoAvailability';
import DefaultModality from '../modality/DefaultModality';
import DefaultPingPong from '../pingpong/DefaultPingPong';
import DefaultRealtimeController from '../realtimecontroller/DefaultRealtimeController';
import RealtimeController from '../realtimecontroller/RealtimeController';
import ReconnectController from '../reconnectcontroller/ReconnectController';
import AsyncScheduler from '../scheduler/AsyncScheduler';
import VideoCodecCapability from '../sdp/VideoCodecCapability';
import DefaultSessionStateController from '../sessionstatecontroller/DefaultSessionStateController';
import SessionStateController from '../sessionstatecontroller/SessionStateController';
import SessionStateControllerAction from '../sessionstatecontroller/SessionStateControllerAction';
import SessionStateControllerState from '../sessionstatecontroller/SessionStateControllerState';
import SessionStateControllerTransitionResult from '../sessionstatecontroller/SessionStateControllerTransitionResult';
import DefaultSignalingClient from '../signalingclient/DefaultSignalingClient';
import ServerSideNetworkAdaption, {
serverSideNetworkAdaptionIsNoneOrDefault,
} from '../signalingclient/ServerSideNetworkAdaption';
import SignalingClientEvent from '../signalingclient/SignalingClientEvent';
import SignalingClientEventType from '../signalingclient/SignalingClientEventType';
import SignalingClientVideoSubscriptionConfiguration from '../signalingclient/SignalingClientVideoSubscriptionConfiguration';
import SignalingClientObserver from '../signalingclientobserver/SignalingClientObserver';
import { SdkStreamServiceType } from '../signalingprotocol/SignalingProtocol.js';
import SimulcastLayers from '../simulcastlayers/SimulcastLayers';
import StatsCollector from '../statscollector/StatsCollector';
import AttachMediaInputTask from '../task/AttachMediaInputTask';
import CleanRestartedSessionTask from '../task/CleanRestartedSessionTask';
import CleanStoppedSessionTask from '../task/CleanStoppedSessionTask';
import CreatePeerConnectionTask from '../task/CreatePeerConnectionTask';
import CreateSDPTask from '../task/CreateSDPTask';
import FinishGatheringICECandidatesTask from '../task/FinishGatheringICECandidatesTask';
import JoinAndReceiveIndexTask from '../task/JoinAndReceiveIndexTask';
import LeaveAndReceiveLeaveAckTask from '../task/LeaveAndReceiveLeaveAckTask';
import ListenForVolumeIndicatorsTask from '../task/ListenForVolumeIndicatorsTask';
import MonitorTask from '../task/MonitorTask';
import OpenSignalingConnectionTask from '../task/OpenSignalingConnectionTask';
import ParallelGroupTask from '../task/ParallelGroupTask';
import PromoteToPrimaryMeetingTask from '../task/PromoteToPrimaryMeetingTask';
import ReceiveAudioInputTask from '../task/ReceiveAudioInputTask';
import ReceiveRemoteVideoPauseResume from '../task/ReceiveRemoteVideoPauseResumeTask';
import ReceiveVideoInputTask from '../task/ReceiveVideoInputTask';
import ReceiveVideoStreamIndexTask from '../task/ReceiveVideoStreamIndexTask';
import SendAndReceiveDataMessagesTask from '../task/SendAndReceiveDataMessagesTask';
import SerialGroupTask from '../task/SerialGroupTask';
import SetLocalDescriptionTask from '../task/SetLocalDescriptionTask';
import SetRemoteDescriptionTask from '../task/SetRemoteDescriptionTask';
import SubscribeAndReceiveSubscribeAckTask from '../task/SubscribeAndReceiveSubscribeAckTask';
import Task from '../task/Task';
import TimeoutTask from '../task/TimeoutTask';
import WaitForAttendeePresenceTask from '../task/WaitForAttendeePresenceTask';
import DefaultTransceiverController from '../transceivercontroller/DefaultTransceiverController';
import SimulcastContentShareTransceiverController from '../transceivercontroller/SimulcastContentShareTransceiverController';
import SimulcastTransceiverController from '../transceivercontroller/SimulcastTransceiverController';
import VideoOnlyTransceiverController from '../transceivercontroller/VideoOnlyTransceiverController';
import { Maybe } from '../utils/Types';
import DefaultVideoCaptureAndEncodeParameter from '../videocaptureandencodeparameter/DefaultVideoCaptureAndEncodeParameter';
import AllHighestVideoBandwidthPolicy from '../videodownlinkbandwidthpolicy/AllHighestVideoBandwidthPolicy';
import VideoAdaptiveProbePolicy from '../videodownlinkbandwidthpolicy/VideoAdaptiveProbePolicy';
import { convertVideoPreferencesToSignalingClientVideoSubscriptionConfiguration } from '../videodownlinkbandwidthpolicy/VideoPreferences';
import VideoSource from '../videosource/VideoSource';
import DefaultVideoStreamIdSet from '../videostreamidset/DefaultVideoStreamIdSet';
import DefaultVideoStreamIndex from '../videostreamindex/DefaultVideoStreamIndex';
import SimulcastVideoStreamIndex from '../videostreamindex/SimulcastVideoStreamIndex';
import DefaultVideoTileController from '../videotilecontroller/DefaultVideoTileController';
import VideoTileController from '../videotilecontroller/VideoTileController';
import DefaultVideoTileFactory from '../videotilefactory/DefaultVideoTileFactory';
import DefaultSimulcastUplinkPolicy from '../videouplinkbandwidthpolicy/DefaultSimulcastUplinkPolicy';
import NScaleVideoUplinkBandwidthPolicy from '../videouplinkbandwidthpolicy/NScaleVideoUplinkBandwidthPolicy';
import SimulcastUplinkObserver from '../videouplinkbandwidthpolicy/SimulcastUplinkObserver';
import SimulcastUplinkPolicy from '../videouplinkbandwidthpolicy/SimulcastUplinkPolicy';
import DefaultVolumeIndicatorAdapter from '../volumeindicatoradapter/DefaultVolumeIndicatorAdapter';
import WebSocketAdapter from '../websocketadapter/WebSocketAdapter';
import AudioVideoControllerState from './AudioVideoControllerState';
export default class DefaultAudioVideoController
implements AudioVideoController, SimulcastUplinkObserver, MediaStreamBrokerObserver, Destroyable {
private _logger: Logger;
private _configuration: MeetingSessionConfiguration;
private _webSocketAdapter: WebSocketAdapter;
private _realtimeController: RealtimeController;
private _activeSpeakerDetector: ActiveSpeakerDetector;
private _videoTileController: VideoTileController;
private _mediaStreamBroker: MediaStreamBroker;
private _reconnectController: ReconnectController;
private _audioMixController: DefaultAudioMixController;
private _eventController: EventController;
private _audioProfile: AudioProfile = new AudioProfile();
private connectionHealthData = new ConnectionHealthData();
private observerQueue: Set<AudioVideoObserver> = new Set<AudioVideoObserver>();
private meetingSessionContext = new AudioVideoControllerState();
private sessionStateController: SessionStateController;
private static MIN_VOLUME_DECIBELS = -42;
private static MAX_VOLUME_DECIBELS = -14;
private static PING_PONG_INTERVAL_MS = 10000;
private enableSimulcast: boolean = false;
private enableSVC: boolean = false;
private useUpdateTransceiverControllerForUplink: boolean = false;
private totalRetryCount = 0;
private startAudioVideoTimestamp: number = 0;
private signalingTask: Task;
private preStartObserver: SignalingClientObserver | undefined;
private mayNeedRenegotiationForSimulcastLayerChange: boolean = false;
private maxUplinkBandwidthKbps: number;
private videoSendCodecPreferences: VideoCodecCapability[];
// Stored solely to trigger demotion callback on disconnection (expected behavior).
//
// We otherwise intentionally do not use this for any other behavior to avoid the complexity
// of the added state.
private promotedToPrimaryMeeting: boolean = false;
private hasGetRTCPeerConnectionStatsDeprecationMessageBeenSent: boolean = false;
// `connectWithPromises`, and `actionUpdateWithRenegotiation` all
// contains a significant portion of asynchronous tasks, so we need to explicitly defer
// any task operation which may be performed on the event queue that may modify
// mutable state in `MeetingSessionContext`, as this mutable state needs to be consistent over the course of the update.
//
// Currently this includes
// * `ReceiveVideoStreamIndexTask` which updates `videosToReceive` and `videoCaptureAndEncodeParameter`
// * `MonitorTask` which updates `videosToReceive`
private receiveIndexTask: ReceiveVideoStreamIndexTask | undefined = undefined;
private monitorTask: MonitorTask | undefined = undefined;
private receiveRemotePauseResumeTask: ReceiveRemoteVideoPauseResumeTask | undefined = undefined;
destroyed = false;
constructor(
configuration: MeetingSessionConfiguration,
logger: Logger,
webSocketAdapter: WebSocketAdapter,
mediaStreamBroker: MediaStreamBroker,
reconnectController: ReconnectController,
eventController?: EventController
) {
this._logger = logger;
this.sessionStateController = new DefaultSessionStateController(this._logger);
this._configuration = configuration;
this._webSocketAdapter = webSocketAdapter;
this._realtimeController = new DefaultRealtimeController(mediaStreamBroker);
this._realtimeController.realtimeSetLocalAttendeeId(
configuration.credentials.attendeeId,
configuration.credentials.externalUserId
);
this._mediaStreamBroker = mediaStreamBroker;
this._reconnectController = reconnectController;
this._videoTileController = new DefaultVideoTileController(
new DefaultVideoTileFactory(),
this,
this._logger
);
this._audioMixController = new DefaultAudioMixController(this._logger);
this._mediaStreamBroker.addMediaStreamBrokerObserver(this._audioMixController);
this.meetingSessionContext.logger = this._logger;
this._eventController = eventController;
}
async destroy(): Promise<void> {
this.observerQueue.clear();
this._mediaStreamBroker.removeMediaStreamBrokerObserver(this._audioMixController);
this.destroyed = true;
}
get configuration(): MeetingSessionConfiguration {
return this._configuration;
}
get realtimeController(): RealtimeController {
return this._realtimeController;
}
get activeSpeakerDetector(): ActiveSpeakerDetector {
// Lazy init.
if (!this._activeSpeakerDetector) {
this._activeSpeakerDetector = new DefaultActiveSpeakerDetector(
this._realtimeController,
this._configuration.credentials.attendeeId,
this.handleHasBandwidthPriority.bind(this)
);
}
return this._activeSpeakerDetector;
}
get videoTileController(): VideoTileController {
return this._videoTileController;
}
get audioMixController(): AudioMixController {
return this._audioMixController;
}
get logger(): Logger {
return this._logger;
}
get rtcPeerConnection(): RTCPeerConnection | null {
return (this.meetingSessionContext && this.meetingSessionContext.peer) || null;
}
get mediaStreamBroker(): MediaStreamBroker {
return this._mediaStreamBroker;
}
get eventController(): EventController | undefined {
return this._eventController;
}
/**
* This API will be deprecated in favor of `ClientMetricReport.getRTCStatsReport()`.
*
* It makes an additional call to the `getStats` API and therefore may cause slight performance degradation.
*
* Please subscribe to `metricsDidReceive(clientMetricReport: ClientMetricReport)` callback,
* and get the raw `RTCStatsReport` via `clientMetricReport.getRTCStatsReport()`.
*/
getRTCPeerConnectionStats(selector?: MediaStreamTrack): Promise<RTCStatsReport> {
/* istanbul ignore else */
if (!this.hasGetRTCPeerConnectionStatsDeprecationMessageBeenSent) {
this.logger.warn(
'The `getRTCPeerConnectionStats()` is on its way to be deprecated. It makes an additional call to the `getStats` API and therefore may cause slight performance degradation. Please use the new API `clientMetricReport.getRTCStatsReport()` returned by `metricsDidReceive(clientMetricReport)` callback instead.'
);
this.hasGetRTCPeerConnectionStatsDeprecationMessageBeenSent = true;
}
if (!this.rtcPeerConnection) {
return null;
}
return this.rtcPeerConnection.getStats(selector);
}
setAudioProfile(audioProfile: AudioProfile): void {
this._audioProfile = audioProfile;
}
addObserver(observer: AudioVideoObserver): void {
this.logger.info('adding meeting observer');
this.observerQueue.add(observer);
}
removeObserver(observer: AudioVideoObserver): void {
this.logger.info('removing meeting observer');
this.observerQueue.delete(observer);
}
forEachObserver(observerFunc: (observer: AudioVideoObserver) => void): void {
for (const observer of this.observerQueue) {
AsyncScheduler.nextTick(() => {
if (this.observerQueue.has(observer)) {
observerFunc(observer);
}
});
}
}
private initSignalingClient(): void {
this.connectionHealthData.reset();
if (this.meetingSessionContext.signalingClient) {
return;
}
this.meetingSessionContext = new AudioVideoControllerState();
this.meetingSessionContext.logger = this.logger;
this.meetingSessionContext.eventController = this.eventController;
this.meetingSessionContext.browserBehavior = new DefaultBrowserBehavior();
this.meetingSessionContext.videoSendCodecPreferences = this.videoSendCodecPreferences;
this.meetingSessionContext.audioProfile = this._audioProfile;
this.meetingSessionContext.meetingSessionConfiguration = this.configuration;
this.meetingSessionContext.signalingClient = new DefaultSignalingClient(
this._webSocketAdapter,
this.logger
);
}
private uninstallPreStartObserver(): void {
this.meetingSessionContext.signalingClient.removeObserver(this.preStartObserver);
this.preStartObserver = undefined;
}
private prestart(): Promise<void> {
this.logger.info('Pre-connecting signaling connection.');
return this.createOrReuseSignalingTask()
.run()
.then(() => {
const handleClosed = async (): Promise<void> => {
this.logger.info('Early connection closed; discarding signaling task.');
this.signalingTask = undefined;
this.uninstallPreStartObserver();
};
this.preStartObserver = {
handleSignalingClientEvent(event: SignalingClientEvent): void {
if (event.type === SignalingClientEventType.WebSocketClosed) {
handleClosed();
}
},
};
this.meetingSessionContext.signalingClient.registerObserver(this.preStartObserver);
})
.catch(e => {
this.logger.error(`Signaling task pre-start failed: ${e}`);
// Clean up just in case a subsequent attempt will succeed.
this.signalingTask = undefined;
});
}
start(options?: { signalingOnly?: boolean }): void {
this.startReturningPromise(options)
.then(() => {
this.logger.info('start completed');
})
// Just-in-case error handling.
.catch(
/* istanbul ignore next */
e => {
this.logger.error(`start failed: ${e}`);
}
);
}
// This is public (albeit marked internal) for tests only.
/* @internal */
startReturningPromise(options?: { signalingOnly?: boolean }): Promise<void> {
if (options?.signalingOnly === true) {
return this.prestart();
}
// For side-effects: lazy getter.
this.activeSpeakerDetector;
return new Promise((resolve, reject) => {
this.sessionStateController.perform(SessionStateControllerAction.Connect, () => {
this.actionConnect(false).then(resolve).catch(reject);
});
});
}
// @ts-ignore
private connectWithPromises(needsToWaitForAttendeePresence: boolean): Task {
const context = this.meetingSessionContext;
// Syntactic sugar.
const timeout = (timeoutMs: number, task: Task): TimeoutTask => {
return new TimeoutTask(this.logger, task, timeoutMs);
};
// First layer.
this.monitorTask = new MonitorTask(
context,
this.configuration.connectionHealthPolicyConfiguration,
this.connectionHealthData
);
const monitor = this.monitorTask.once();
// Second layer.
const receiveAudioInput = new ReceiveAudioInputTask(context).once();
this.receiveIndexTask = new ReceiveVideoStreamIndexTask(context);
// See declaration (unpaused in actionFinishConnecting)
this.monitorTask.pauseResubscribeCheck();
this.receiveIndexTask.pauseIngestion();
const signaling = new SerialGroupTask(this.logger, 'Signaling', [
// If pre-connecting, this will be an existing task that has already been run.
this.createOrReuseSignalingTask(),
new ListenForVolumeIndicatorsTask(context),
new SendAndReceiveDataMessagesTask(context),
new JoinAndReceiveIndexTask(context),
this.receiveIndexTask,
]).once();
// Third layer.
const createPeerConnection = new CreatePeerConnectionTask(context).once(signaling);
const attachMediaInput = new AttachMediaInputTask(context).once(
createPeerConnection,
receiveAudioInput
);
// Mostly serial section -- kept as promises to allow for finer-grained breakdown.
const createSDP = new CreateSDPTask(context).once(attachMediaInput);
const setLocalDescription = new SetLocalDescriptionTask(context).once(createSDP);
const ice = new FinishGatheringICECandidatesTask(context).once(setLocalDescription);
const subscribeAck = new SubscribeAndReceiveSubscribeAckTask(context).once(ice);
this.receiveRemotePauseResumeTask = new ReceiveRemoteVideoPauseResume(context);
this.receiveRemotePauseResumeTask.once(subscribeAck);
// The ending is a delicate time: we need the connection as a whole to have a timeout,
// and for the attendee presence timer to not start ticking until after the subscribe/ack.
return new SerialGroupTask(this.logger, this.wrapTaskName('AudioVideoStart'), [
monitor,
timeout(
this.configuration.connectionTimeoutMs,
new SerialGroupTask(this.logger, 'Peer', [
// The order of these two matters. If canceled, the first one that's still running
// will contribute any special rejection, and we don't want that to be "attendee not found"!
subscribeAck,
this.receiveRemotePauseResumeTask,
needsToWaitForAttendeePresence
? new TimeoutTask(
this.logger,
new ParallelGroupTask(this.logger, 'FinalizeConnection', [
new WaitForAttendeePresenceTask(context),
new SetRemoteDescriptionTask(context),
]),
this.meetingSessionContext.meetingSessionConfiguration.attendeePresenceTimeoutMs
)
: /* istanbul ignore next */ new SetRemoteDescriptionTask(context),
])
),
]);
}
private async actionConnect(reconnecting: boolean): Promise<void> {
this.initSignalingClient();
// We no longer need to watch for the early connection dropping; we're back where
// we otherwise would have been had we not pre-started.
this.uninstallPreStartObserver();
// Note that some of the assignments in this function exist to clean up previous connections.
// All future 'clean up' assignments should go in `AudioVideoControllerState.resetConnectionSpecificState`
// for consolidation purposes.
this.meetingSessionContext.mediaStreamBroker = this._mediaStreamBroker;
this.meetingSessionContext.realtimeController = this._realtimeController;
this.meetingSessionContext.audioMixController = this._audioMixController;
this.meetingSessionContext.audioVideoController = this;
this.enableSimulcast =
this.configuration.enableSimulcastForUnifiedPlanChromiumBasedBrowsers &&
new DefaultBrowserBehavior().hasChromiumWebRTC();
if (this.enableSimulcast && this.configuration.enableSVC) {
this.logger.warn(
'SVC cannot be enabled at the same time as simulcast. Disabling SVC, using simulcast.'
);
}
this.enableSVC =
!this.enableSimulcast &&
this.configuration.enableSVC &&
new DefaultBrowserBehavior().supportsScalableVideoCoding();
const useAudioConnection: boolean = !!this.configuration.urls.audioHostURL;
if (!useAudioConnection) {
this.logger.info(`Using video only transceiver controller`);
this.meetingSessionContext.transceiverController = new VideoOnlyTransceiverController(
this.logger,
this.meetingSessionContext.browserBehavior,
this.meetingSessionContext
);
} else if (this.enableSimulcast) {
this.logger.info(`Using transceiver controller with simulcast support`);
if (
new DefaultModality(this.configuration.credentials.attendeeId).hasModality(
DefaultModality.MODALITY_CONTENT
)
) {
this.meetingSessionContext.transceiverController = new SimulcastContentShareTransceiverController(
this.logger,
this.meetingSessionContext.browserBehavior,
this.meetingSessionContext
);
} else {
this.meetingSessionContext.transceiverController = new SimulcastTransceiverController(
this.logger,
this.meetingSessionContext.browserBehavior,
this.meetingSessionContext
);
}
} else {
this.logger.info(`Using default transceiver controller`);
this.meetingSessionContext.transceiverController = new DefaultTransceiverController(
this.logger,
this.meetingSessionContext.browserBehavior,
this.meetingSessionContext
);
}
this.meetingSessionContext.volumeIndicatorAdapter = new DefaultVolumeIndicatorAdapter(
this.logger,
this._realtimeController,
DefaultAudioVideoController.MIN_VOLUME_DECIBELS,
DefaultAudioVideoController.MAX_VOLUME_DECIBELS,
this.configuration.credentials.attendeeId
);
this.meetingSessionContext.videoTileController = this._videoTileController;
this.meetingSessionContext.videoDownlinkBandwidthPolicy = this.configuration.videoDownlinkBandwidthPolicy;
this.meetingSessionContext.videoUplinkBandwidthPolicy = this.configuration.videoUplinkBandwidthPolicy;
this.meetingSessionContext.enableSimulcast = this.enableSimulcast;
this.meetingSessionContext.enableSVC = this.enableSVC;
if (this.enableSimulcast) {
let simulcastPolicy = this.meetingSessionContext
.videoUplinkBandwidthPolicy as SimulcastUplinkPolicy;
if (!simulcastPolicy) {
simulcastPolicy = new DefaultSimulcastUplinkPolicy(
this.configuration.credentials.attendeeId,
this.meetingSessionContext.logger
);
this.meetingSessionContext.videoUplinkBandwidthPolicy = simulcastPolicy;
}
simulcastPolicy.addObserver(this);
if (!this.meetingSessionContext.videoDownlinkBandwidthPolicy) {
this.meetingSessionContext.videoDownlinkBandwidthPolicy = new VideoAdaptiveProbePolicy(
this.meetingSessionContext.logger
);
}
this.meetingSessionContext.videoStreamIndex = new SimulcastVideoStreamIndex(this.logger);
} else {
this.meetingSessionContext.enableSimulcast = false;
this.meetingSessionContext.videoStreamIndex = new DefaultVideoStreamIndex(this.logger);
if (!this.meetingSessionContext.videoUplinkBandwidthPolicy) {
this.meetingSessionContext.videoUplinkBandwidthPolicy = new NScaleVideoUplinkBandwidthPolicy(
this.configuration.credentials.attendeeId,
!this.meetingSessionContext.browserBehavior.disableResolutionScaleDown(),
this.meetingSessionContext.logger,
this.meetingSessionContext.browserBehavior
);
this.meetingSessionContext.videoUplinkBandwidthPolicy.setSVCEnabled(this.enableSVC);
}
if (!this.meetingSessionContext.videoDownlinkBandwidthPolicy) {
this.meetingSessionContext.videoDownlinkBandwidthPolicy = new AllHighestVideoBandwidthPolicy(
this.configuration.credentials.attendeeId
);
}
if (
this.meetingSessionContext.videoUplinkBandwidthPolicy.setTransceiverController &&
this.meetingSessionContext.videoUplinkBandwidthPolicy.updateTransceiverController
) {
this.useUpdateTransceiverControllerForUplink = true;
this.meetingSessionContext.videoUplinkBandwidthPolicy.setTransceiverController(
this.meetingSessionContext.transceiverController
);
}
this.meetingSessionContext.audioProfile = this._audioProfile;
}
if (
new DefaultModality(this.configuration.credentials.attendeeId).hasModality(
DefaultModality.MODALITY_CONTENT
)
) {
const enableUhdContent =
this.configuration.meetingFeatures.contentMaxResolution ===
VideoQualitySettings.VideoResolutionUHD;
if (enableUhdContent) {
// Increase default bandwidth for content share since this is not yet configuration that can be exposed
// without using simulcast
this.setVideoMaxBandwidthKbps(2500);
}
this.meetingSessionContext.videoUplinkBandwidthPolicy.setHighResolutionFeatureEnabled(
enableUhdContent
);
} else {
const enableFhdVideo =
this.configuration.meetingFeatures.videoMaxResolution ===
VideoQualitySettings.VideoResolutionFHD;
this.meetingSessionContext.videoUplinkBandwidthPolicy.setHighResolutionFeatureEnabled(
enableFhdVideo
);
}
if (this.meetingSessionContext.videoUplinkBandwidthPolicy && this.maxUplinkBandwidthKbps) {
this.meetingSessionContext.videoUplinkBandwidthPolicy.setIdealMaxBandwidthKbps(
this.maxUplinkBandwidthKbps
);
}
if (this.meetingSessionContext.videoDownlinkBandwidthPolicy.bindToTileController) {
this.meetingSessionContext.videoDownlinkBandwidthPolicy.bindToTileController(
this._videoTileController
);
}
if (this.meetingSessionContext.videoDownlinkBandwidthPolicy.setWantsResubscribeObserver) {
this.meetingSessionContext.videoDownlinkBandwidthPolicy.setWantsResubscribeObserver(() =>
this.update({ needsRenegotiation: false })
);
}
this.meetingSessionContext.lastKnownVideoAvailability = new MeetingSessionVideoAvailability();
this.meetingSessionContext.videoCaptureAndEncodeParameter = new DefaultVideoCaptureAndEncodeParameter(
0,
0,
0,
0,
false
);
this.meetingSessionContext.videosToReceive = new DefaultVideoStreamIdSet();
this.meetingSessionContext.videosPaused = new DefaultVideoStreamIdSet();
this.meetingSessionContext.statsCollector = new StatsCollector(this, this.logger);
this.meetingSessionContext.connectionMonitor = new SignalingAndMetricsConnectionMonitor(
this,
this._realtimeController,
this.connectionHealthData,
new DefaultPingPong(
this.meetingSessionContext.signalingClient,
DefaultAudioVideoController.PING_PONG_INTERVAL_MS,
this.logger
),
this.meetingSessionContext.statsCollector
);
this.meetingSessionContext.reconnectController = this._reconnectController;
this.meetingSessionContext.videoDeviceInformation = {};
if (!reconnecting) {
this.totalRetryCount = 0;
this._reconnectController.reset();
this.startAudioVideoTimestamp = Date.now();
this.forEachObserver(observer => {
Maybe.of(observer.audioVideoDidStartConnecting).map(f => f.bind(observer)(false));
});
this.eventController?.publishEvent('meetingStartRequested');
}
this.meetingSessionContext.startAudioVideoTimestamp = this.startAudioVideoTimestamp;
if (this._reconnectController.hasStartedConnectionAttempt()) {
// This does not reset the reconnect deadline, but declare it's not the first connection.
this._reconnectController.startedConnectionAttempt(false);
} else {
this._reconnectController.startedConnectionAttempt(true);
}
// No attendee presence event will be triggered if there is no audio connection.
// Waiting for attendee presence is explicitly executed
// if `attendeePresenceTimeoutMs` is configured to larger than 0.
const needsToWaitForAttendeePresence =
useAudioConnection &&
this.meetingSessionContext.meetingSessionConfiguration.attendeePresenceTimeoutMs > 0;
this.logger.info('Needs to wait for attendee presence? ' + needsToWaitForAttendeePresence);
const connect = this.connectWithPromises(needsToWaitForAttendeePresence);
// The rest.
try {
await connect.run();
this.connectionHealthData.setConnectionStartTime();
this._mediaStreamBroker.addMediaStreamBrokerObserver(this);
this.sessionStateController.perform(SessionStateControllerAction.FinishConnecting, () => {
/* istanbul ignore else */
if (this.eventController) {
this.meetingSessionContext.meetingStartDurationMs =
Date.now() - this.startAudioVideoTimestamp;
this.eventController.publishEvent('meetingStartSucceeded', {
maxVideoTileCount: this.meetingSessionContext.maxVideoTileCount,
poorConnectionCount: this.meetingSessionContext.poorConnectionCount,
retryCount: this.totalRetryCount,
signalingOpenDurationMs: this.meetingSessionContext.signalingOpenDurationMs,
iceGatheringDurationMs: this.meetingSessionContext.iceGatheringDurationMs,
meetingStartDurationMs: this.meetingSessionContext.meetingStartDurationMs,
});
}
this.meetingSessionContext.startTimeMs = Date.now();
this.actionFinishConnecting();
});
} catch (error) {
this.signalingTask = undefined;
const status = new MeetingSessionStatus(
this.getMeetingStatusCode(error) || MeetingSessionStatusCode.TaskFailed
);
this.logger.info(`Start failed: ${status} due to error ${error}.`);
// I am not able to successfully reach this state in the test suite with mock
// websockets -- it always ends up in 'Disconnecting' instead. As such, this
// has to be marked for Istanbul.
/* istanbul ignore if */
if (this.sessionStateController.state() === SessionStateControllerState.NotConnected) {
// There's no point trying to 'disconnect', because we're not connected.
// The session state controller will bail.
this.logger.info('Start failed and not connected. Not cleaning up.');
return;
}
this.sessionStateController.perform(SessionStateControllerAction.Fail, async () => {
await this.actionDisconnect(status, true, error);
if (!this.handleMeetingSessionStatus(status, error)) {
this.notifyStop(status, error);
}
});
}
}
private createOrReuseSignalingTask(): Task {
if (!this.signalingTask) {
this.initSignalingClient();
this.signalingTask = new TimeoutTask(
this.logger,
new OpenSignalingConnectionTask(this.meetingSessionContext),
this.configuration.connectionTimeoutMs
).once();
}
return this.signalingTask;
}
private actionFinishConnecting(): void {
this.signalingTask = undefined;
this.meetingSessionContext.videoDuplexMode = SdkStreamServiceType.RX;
if (!this.meetingSessionContext.enableSimulcast) {
if (this.useUpdateTransceiverControllerForUplink) {
this.meetingSessionContext.videoUplinkBandwidthPolicy.updateTransceiverController();
} else {
this.enforceBandwidthLimitationForSender(
this.meetingSessionContext.videoCaptureAndEncodeParameter.encodeBitrates()[0]
);
}
}
this.forEachObserver(observer => {
Maybe.of(observer.audioVideoDidStart).map(f => f.bind(observer)());
});
this._reconnectController.reset();
// `receiveIndexTask` needs to be resumed first so it can set `remoteStreamDescriptions`
this.receiveIndexTask.resumeIngestion();
this.monitorTask.resumeResubscribeCheck();
}
/* @internal */
stopReturningPromise(): Promise<void> {
// In order to avoid breaking backward compatibility, when only the
// signaling connection is established we appear to not be connected.
// We handle this by simply disconnecting the websocket directly.
if (this.sessionStateController.state() === SessionStateControllerState.NotConnected) {
// Unfortunately, this does not return a promise.
this.meetingSessionContext.signalingClient?.closeConnection();
this.cleanUpMediaStreamsAfterStop();
return Promise.resolve();
}
/*
Stops the current audio video meeting session.
The stop method execution is deferred and executed after
the current reconnection attempt completes.
It disables any further reconnection attempts.
Upon completion, AudioVideoObserver's `audioVideoDidStop`
callback function is called with `MeetingSessionStatusCode.Left`.
*/
return new Promise((resolve, reject) => {
this.sessionStateController.perform(SessionStateControllerAction.Disconnect, () => {
this._reconnectController.disableReconnect();
this.logger.info('attendee left meeting, session will not be reconnected');
this.actionDisconnect(new MeetingSessionStatus(MeetingSessionStatusCode.Left), false, null)
.then(resolve)
.catch(reject);
});
});
}
stop(): void {
this.stopReturningPromise();
}
private async actionDisconnect(
status: MeetingSessionStatus,
reconnecting: boolean,
error: Error | null
): Promise<void> {
try {
await new SerialGroupTask(this.logger, this.wrapTaskName('AudioVideoStop'), [
new TimeoutTask(
this.logger,
new LeaveAndReceiveLeaveAckTask(this.meetingSessionContext),
this.configuration.connectionTimeoutMs
),
]).run();
} catch (stopError) {
this.logger.info('fail to stop');
}
try {
const subtasks: Task[] = [
new TimeoutTask(
this.logger,
new CleanStoppedSessionTask(this.meetingSessionContext),
this.configuration.connectionTimeoutMs
),
];
this.cleanUpMediaStreamsAfterStop();
await new SerialGroupTask(this.logger, this.wrapTaskName('AudioVideoClean'), subtasks).run();
} catch (cleanError) {
/* istanbul ignore next */
this.logger.info('fail to clean');
}
this.sessionStateController.perform(SessionStateControllerAction.FinishDisconnecting, () => {
if (!reconnecting) {
this.notifyStop(status, error);
}
});
}
update(options: { needsRenegotiation: boolean } = { needsRenegotiation: true }): boolean {
let needsRenegotiation = options.needsRenegotiation;
// Check in case this function has been called before peer connection is set up
// since that is necessary to try to update remote videos without the full resubscribe path
needsRenegotiation ||= this.meetingSessionContext.peer === undefined;
needsRenegotiation ||= !this.updateRemoteVideosFromPolicy();
needsRenegotiation ||= !this.updateLocalVideoFromPolicy();
// `MeetingSessionContext.lastVideosToReceive` needs to be updated regardless
this.meetingSessionContext.lastVideosToReceive = this.meetingSessionContext.videosToReceive;
if (!needsRenegotiation) {
this.logger.info('Update request does not require resubscribe');
// Call `actionFinishUpdating` to apply the new encoding parameters that may have been set in `updateLocalVideoFromPolicy`.
this.actionFinishUpdating();
return true; // Skip the subscribe!
}
this.logger.info('Update request requires resubscribe');
const result = this.sessionStateController.perform(SessionStateControllerAction.Update, () => {
this.actionUpdateWithRenegotiation(true);
});
return (
result === SessionStateControllerTransitionResult.Transitioned ||
result === SessionStateControllerTransitionResult.DeferredTransition
);
}
// Depending on if using server-side bandwidth probing and if using server-side quality adaption,
// decide if needs to send necessary updates, and if send through full renegotiaton.
// It returns true if downlink policy took care of everything and no renegotiation needed.
private updateRemoteVideosFromPolicy(): boolean {
if (
this.meetingSessionContext.videoDownlinkBandwidthPolicy &&
this.meetingSessionContext.videoDownlinkBandwidthPolicy.getVideoPreferences !== undefined &&
this.meetingSessionContext.videoDownlinkBandwidthPolicy.getServerSideNetworkAdaption !==
undefined &&
!serverSideNetworkAdaptionIsNoneOrDefault(
this.meetingSessionContext.videoDownlinkBandwidthPolicy.getServerSideNetworkAdaption()
)
) {
// Send up-to-date video preferences to server. This is fine if it includes remote sources/MIDs we need a full renegotiation for (i.e.
// ones that were added or removed). We will re-include these updates in the subscribe.
/* istanbul ignore if: Extremely unlikely that `videosToReceive` is null */
if (!this.sendRemoteVideoUpdate()) {
return false;
}
if (
this.meetingSessionContext.videoDownlinkBandwidthPolicy.getServerSideNetworkAdaption() ===
ServerSideNetworkAdaption.BandwidthProbingAndRemoteVideoQualityAdaption
) {
// If using server side remote video quality adaption (i.e. server is picking the encoding to send), we don't need
// to do anything after sending the update, as long as we are not adding or removing streams, in which case
// we need to complete a full renegotiation.
return this.isNotAddingOrRemovingStreams();
}
}
// If using client-side network adaptation, try skipping renegotitaiton if only simulcast stream swicth.
return this.updateRemoteVideosIfNotAddingOrRemovingStreams();
}
// When `ServerSideNetworkAdaption.BandwidthProbingAndRemoteVideoQualityAdaption` has been signalled,
// trigger server side video quality adaption logic through `SignalingClient.remoteVideoUpdate` and skip full subscribe.
//
// This function also tries to use the diff between `this.meetingSessionContext.lastVideosToReceive`
// and `this.meetingSessionContext.videosToReceive` to determine if update is only simulcast stream switch,
// which is accomplished through `SignalingClient.remoteVideoUpdate` rather than the full subscribe.
//
// It requires the caller to manage `this.meetingSessionContext.lastVideosToReceive`
// and `this.meetingSessionContext.videosToReceive` so that `this.meetingSessionContext.lastVideosToReceive`
// contains the stream IDs from either last time a subscribe was set, or last time this function was set.
//
// It will return true if successful, if false the caller must fall back to a full renegotiation
private updateRemoteVideosIfNotAddingOrRemovingStreams(): boolean {
const streamChanges = this.detectChangesInVideosToReceive();
/* istanbul ignore if: Extremely unlikely that `videosToReceive` is null or missing requisite functions and made it this far */
if (streamChanges === undefined) {
return false;
}
const added: number[] = streamChanges.added;
const simulcastStreamUpdates: Map<number, number> = streamChanges.simulcastStreamUpdates;
const removed: number[] = streamChanges.removed;
const context = this.meetingSessionContext;
const updatedVideoSubscriptionConfigurations: SignalingClientVideoSubscriptionConfiguration[] = [];
for (const [previousId, currentId] of simulcastStreamUpdates.entries()) {
const updatedConfig = new SignalingClientVideoSubscriptionConfiguration();
updatedConfig.streamId = currentId;
updatedConfig.attendeeId = context.videoStreamIndex.attendeeIdForStreamId(currentId);
updatedConfig.mid = context.transceiverController.getMidForStreamId(previousId);
if (updatedConfig.mid === undefined) {
this.logger.info(
`No MID found for stream ID ${previousId}, cannot update stream without renegotiation`
);
return false;
}
updatedVideoSubscriptionConfigurations.push(updatedConfig);
// We need to override some other components dependent on the subscribe paths for certain functionality
context.transceiverController.setStreamIdForMid(updatedConfig.mid, currentId);
context.videoStreamIndex.overrideStreamIdMappings(previousId, currentId);
if (context.videoTileController.haveVideoTileForAttendeeId(updatedConfig.attendeeId)) {
const tile = context.videoTileController.getVideoTileForAttendeeId(
updatedConfig.attendeeId
);
if (!tile.setStreamId) {
// Required function
return false;
}
tile.setStreamId(currentId);
}
}
// accomplish simulcast stream switches by sending removeVideoUpdate signaling frame instead of full renegotiation
if (updatedVideoSubscriptionConfigurations.length !== 0) {
context.signalingClient.remoteVideoUpdate(updatedVideoSubscriptionConfigurations, []);
}
// but cannot skip renegotiation if there are more changes than simulcast stream switch (i.e. add/remove/source switches)
if (added.length !== 0 || removed.length !== 0) {
return false;
}
// We use `remoteVideoUpdateSent` to cache the previous index so that we are able to do switches (not add/removes)
// for simulcast stream layer changes. See `subscribeFrameSent` for more details.
context.videoStreamIndex.remoteVideoUpdateSent();
return true;
}
private detectChangesInVideosToReceive():
| {
added: number[];
removed: number[];
simulcastStreamUpdates: Map<number, number>;
}
| undefined {
const context = this.meetingSessionContext;
/* istanbul ignore next: Extremely unlikely that `videosToReceive` is null */
if (context.videosToReceive === null) {
return undefined;
}
// Check existence of all required dependencies and requisite functions
if (
!context.transceiverController ||
!context.transceiverController.getMidForStreamId ||
!context.transceiverController.setStreamIdForMid ||
!context.videosToReceive.forEach ||
!context.signalingClient.remoteVideoUpdate ||
!context.videoStreamIndex.overrideStreamIdMappings
) {
return undefined;
}
let added: number[] = [];
const simulcastStreamUpdates: Map<number, number> = new Map();
let removed: number[] = [];
if (context.lastVideosToReceive === null) {
added = context.videosToReceive.array();
} else {
const index = context.videoStreamIndex;
context.videosToReceive.forEach((currentId: number) => {
if (context.lastVideosToReceive.contain(currentId)) {
return;
}
// Check if group ID exists in previous set (i.e. simulcast stream switch)
let foundUpdatedPreviousStreamId = false;
context.lastVideosToReceive.forEach((previousId: number) => {
if (foundUpdatedPreviousStreamId) {
return; // Short circuit since we have already found it
}
if (index.StreamIdsInSameGroup(previousId, currentId)) {
simulcastStreamUpdates.set(previousId, currentId);
foundUpdatedPreviousStreamId = true;
}