-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Expand file tree
/
Copy pathCall.ts
More file actions
1199 lines (955 loc) · 30.4 KB
/
Call.ts
File metadata and controls
1199 lines (955 loc) · 30.4 KB
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
import { Emitter } from '@rocket.chat/emitter';
import type { MediaSignalTransportWrapper } from './TransportWrapper';
import type { ClientMediaSignalError, IServiceProcessorFactoryList } from '../definition';
import type {
IClientMediaCall,
CallEvents,
CallContact,
CallRole,
CallState,
CallService,
CallHangupReason,
CallActorType,
} from '../definition/call';
import type { ClientContractState, ClientState } from '../definition/client';
import type { IMediaSignalLogger } from '../definition/logger';
import type { IWebRTCProcessor, WebRTCInternalStateMap } from '../definition/services';
import { isPendingState } from './services/states';
import { serializeError } from './utils/serializeError';
import type {
ServerMediaSignal,
ServerMediaSignalNewCall,
ServerMediaSignalNotification,
ServerMediaSignalRemoteSDP,
ServerMediaSignalRequestOffer,
} from '../definition/signals/server';
export interface IClientMediaCallConfig {
logger?: IMediaSignalLogger;
transporter: MediaSignalTransportWrapper;
processorFactories: IServiceProcessorFactoryList;
sessionId: string;
iceGatheringTimeout: number;
}
const TIMEOUT_TO_ACCEPT = 30000;
const TIMEOUT_TO_CONFIRM_ACCEPTANCE = 2000;
const TIMEOUT_TO_PROGRESS_SIGNALING = 10000;
const STATE_REPORT_DELAY = 300;
const CALLS_WITH_NO_REMOTE_DATA_REPORT_DELAY = 5000;
// if the server tells us we're the caller in a call we don't recognize, ignore it completely
const AUTO_IGNORE_UNKNOWN_OUTBOUND_CALLS = true;
type StateTimeoutHandler = {
state: ClientState;
handler: ReturnType<typeof setTimeout>;
};
export class ClientMediaCall implements IClientMediaCall {
public get callId(): string {
return this.remoteCallId ?? this.localCallId;
}
public readonly emitter: Emitter<CallEvents>;
private _role: CallRole;
public get role(): CallRole {
return this._role;
}
private _state: CallState;
public get state(): CallState {
return this._state;
}
private _ignored: boolean;
public get ignored(): boolean {
return this._ignored;
}
private _contact: CallContact | null;
public get contact(): CallContact {
return this._contact || {};
}
private _service: CallService | null;
public get service(): CallService | null {
return this._service;
}
public get signed(): boolean {
return ['signed', 'pre-signed', 'self-signed'].includes(this.contractState);
}
public get hidden(): boolean {
return this.ignored || this.contractState === 'ignored';
}
public get muted(): boolean {
if (!this.webrtcProcessor) {
return false;
}
return this.webrtcProcessor.muted;
}
/** indicates if the call is on hold */
public get held(): boolean {
if (!this.webrtcProcessor) {
return false;
}
return this.webrtcProcessor.held;
}
/** indicates the call is past the "dialing" stage and not yet over */
public get busy(): boolean {
return !this.isPendingAcceptance() && !this.isOver();
}
protected webrtcProcessor: IWebRTCProcessor | null = null;
private acceptedLocally: boolean;
private endedLocally: boolean;
private hasRemoteData: boolean;
private hasLocalDescription: boolean;
private hasRemoteDescription: boolean;
private initialized: boolean;
private acknowledged: boolean;
private earlySignals: Set<ServerMediaSignal>;
private stateTimeoutHandlers: Set<StateTimeoutHandler>;
private remoteCallId: string | null;
private oldClientState: ClientState;
private serviceStates: Map<string, string>;
private stateReporterTimeoutHandler: ReturnType<typeof setTimeout> | null;
private mayReportStates: boolean;
private contractState: ClientContractState;
private inputTrack: MediaStreamTrack | null;
/** localCallId will only be different on calls initiated by this session */
private localCallId: string;
private currentNegotiationId: string | null;
private creationTimestamp: Date;
private pendingAnswerRequest: ServerMediaSignalRemoteSDP | null;
constructor(
private readonly config: IClientMediaCallConfig,
callId: string,
{ inputTrack }: { inputTrack?: MediaStreamTrack | null } = {},
) {
this.emitter = new Emitter<CallEvents>();
this.config.transporter = config.transporter;
this.localCallId = callId;
this.remoteCallId = null;
this.acceptedLocally = false;
this.endedLocally = false;
this.hasRemoteData = false;
this.initialized = false;
this.acknowledged = false;
this.contractState = 'proposed';
this.hasLocalDescription = false;
this.hasRemoteDescription = false;
this.serviceStates = new Map();
this.stateReporterTimeoutHandler = null;
this.mayReportStates = true;
this.inputTrack = inputTrack || null;
this.creationTimestamp = new Date();
this.pendingAnswerRequest = null;
this.currentNegotiationId = null;
this.earlySignals = new Set();
this.stateTimeoutHandlers = new Set();
this._role = 'callee';
this._state = 'none';
this.oldClientState = 'none';
this._ignored = false;
this._contact = null;
this._service = null;
}
/**
* Initialize an outbound call with basic contact information until we receive the full call details from the server;
* this gets executed once for outbound calls initiated in this session.
*/
public async initializeOutboundCall(contact: CallContact): Promise<void> {
if (this.acceptedLocally) {
return;
}
this.config.logger?.debug('ClientMediaCall.initializeOutboundCall');
const wasInitialized = this.initialized;
this.initialized = true;
this.acceptedLocally = true;
if (this.hasRemoteData) {
this.changeContact(contact, { prioritizeExisting: true });
} else {
this._role = 'caller';
this._contact = contact;
}
this.addStateTimeout('pending', TIMEOUT_TO_ACCEPT);
if (!wasInitialized) {
this.emitter.emit('initialized');
}
}
/** Initialize an outbound call with the callee information and send a call request to the server */
public async requestCall(callee: { type: CallActorType; id: string }, contactInfo?: CallContact): Promise<void> {
if (this.initialized) {
return;
}
this.config.logger?.debug('ClientMediaCall.requestCall', callee);
this.config.transporter.sendToServer(this.callId, 'request-call', {
callee,
supportedServices: Object.keys(this.config.processorFactories) as CallService[],
});
return this.initializeOutboundCall({ ...contactInfo, ...callee });
}
/** initialize a call with the data received from the server on a 'new' signal; this gets executed once for every call */
public async initializeRemoteCall(signal: ServerMediaSignalNewCall, oldCall?: ClientMediaCall | null): Promise<void> {
if (this.hasRemoteData) {
return;
}
this.config.logger?.debug('ClientMediaCall.initializeRemoteCall', signal);
this.remoteCallId = signal.callId;
const wasInitialized = this.initialized;
this.initialized = true;
this.hasRemoteData = true;
this._service = signal.service;
this._role = signal.role;
this.changeContact(signal.contact);
if (this._role === 'caller' && !this.acceptedLocally) {
if (oldCall) {
this.acceptedLocally = true;
} else if (AUTO_IGNORE_UNKNOWN_OUTBOUND_CALLS) {
this.config.logger?.log('Ignoring Unknown Outbound Call');
this.ignore();
}
}
// If it's flagged as ignored even before the initialization, tell the server we're unavailable
if (this.ignored) {
return this.rejectAsUnavailable();
}
if (this._service === 'webrtc') {
try {
this.prepareWebRtcProcessor();
} catch (e) {
this.sendError({
errorType: 'service',
errorCode: 'service-initialization-failed',
critical: true,
errorDetails: serializeError(e),
});
await this.rejectAsUnavailable();
throw e;
}
}
// Send an ACK so the server knows that this session exists and is reachable
this.acknowledge();
if (this._role === 'callee' || !this.acceptedLocally) {
this.addStateTimeout('pending', TIMEOUT_TO_ACCEPT);
}
// If the call was requested by this specific session, assume we're signed already.
if (
this._role === 'caller' &&
this.acceptedLocally &&
this.contractState !== 'ignored' &&
(signal.requestedCallId === this.localCallId || Boolean(oldCall))
) {
this.contractState = 'pre-signed';
}
if (!wasInitialized) {
this.emitter.emit('initialized');
}
await this.processEarlySignals();
}
public mayNeedInputTrack(): boolean {
if (this.isOver() || this._ignored || this.hidden) {
return false;
}
return true;
}
public needsInputTrack(): boolean {
if (!this.mayNeedInputTrack()) {
return false;
}
if (this.role === 'caller') {
return this.hasRemoteData;
}
return this.busy;
}
public hasInputTrack(): boolean {
return Boolean(this.inputTrack);
}
public isMissingInputTrack(): boolean {
return !this.hasInputTrack() && this.mayNeedInputTrack();
}
public getClientState(): ClientState {
if (this.isOver()) {
return 'hangup';
}
if (this.hidden) {
return 'busy-elsewhere';
}
switch (this._state) {
case 'none':
case 'ringing':
if (this.hasRemoteData && this._role === 'callee' && this.acceptedLocally) {
return 'accepting';
}
return 'pending';
case 'accepted':
if (this.hasLocalDescription && this.hasRemoteDescription) {
return 'has-answer';
}
if (this.hasLocalDescription !== this.hasRemoteDescription) {
return 'has-offer';
}
return 'accepted';
case 'renegotiating':
if (this.hasLocalDescription && this.hasRemoteDescription) {
return 'has-new-answer';
}
if (this.hasLocalDescription !== this.hasRemoteDescription) {
return 'has-new-offer';
}
return 'renegotiating';
default:
return this._state;
}
}
public async setInputTrack(newInputTrack: MediaStreamTrack | null): Promise<void> {
this.config.logger?.debug('ClientMediaCall.setInputTrack', Boolean(newInputTrack));
if (newInputTrack && (this.isOver() || this.hidden)) {
return;
}
this.inputTrack = newInputTrack;
if (this.webrtcProcessor) {
await this.webrtcProcessor.setInputTrack(newInputTrack);
}
if (newInputTrack && this.pendingAnswerRequest) {
await this.processAnswerRequest(this.pendingAnswerRequest);
}
}
public getRemoteMediaStream(): MediaStream {
this.config.logger?.debug('ClientMediaCall.getRemoteMediaStream');
if (this.hidden) {
this.throwError('getRemoteMediaStream is not available for this call');
}
if (this.shouldIgnoreWebRTC()) {
this.throwError('getRemoteMediaStream is not available for this service');
}
this.prepareWebRtcProcessor();
return this.webrtcProcessor.getRemoteMediaStream();
}
public async processSignal(signal: ServerMediaSignal, oldCall?: ClientMediaCall | null) {
if (this.isOver()) {
return;
}
this.config.logger?.debug('ClientMediaCall.processSignal', signal);
const { type: signalType } = signal;
if (signalType === 'new') {
return this.initializeRemoteCall(signal, oldCall);
}
if (signalType === 'rejected-call-request') {
return this.flagAsEnded('remote');
}
if (!this.hasRemoteData) {
this.config.logger?.debug('Remote data missing, adding signal to queue');
this.earlySignals.add(signal);
return;
}
switch (signalType) {
case 'remote-sdp':
return this.processRemoteSDP(signal);
case 'request-offer':
return this.processOfferRequest(signal);
case 'notification':
return this.processNotification(signal);
}
}
public accept(): void {
this.config.logger?.debug('ClientMediaCall.accept');
if (!this.isPendingOurAcceptance()) {
this.throwError('call-not-pending-acceptance');
}
if (!this.hasRemoteData) {
this.throwError('missing-remote-data');
}
this.acceptedLocally = true;
this.config.transporter.answer(this.callId, 'accept');
if (this.getClientState() === 'accepting') {
this.updateStateTimeouts();
this.addStateTimeout('accepting', TIMEOUT_TO_CONFIRM_ACCEPTANCE);
this.emitter.emit('accepting');
}
}
public reject(): void {
this.config.logger?.debug('ClientMediaCall.reject');
if (!this.isPendingOurAcceptance()) {
this.throwError('call-not-pending-acceptance');
}
if (!this.hasRemoteData) {
this.throwError('missing-remote-data');
}
this.config.transporter.answer(this.callId, 'reject');
this.changeState('hangup');
}
public transfer(callee: { type: CallActorType; id: string }): void {
if (!this.busy) {
return;
}
this.config.logger?.debug('ClientMediaCall.transfer', callee);
this.config.transporter.sendToServer(this.callId, 'transfer', {
to: callee,
});
}
public hangup(reason: CallHangupReason = 'normal'): void {
this.config.logger?.debug('ClientMediaCall.hangup', reason);
if (this.endedLocally || this._state === 'hangup') {
return;
}
if (this.hidden) {
return;
}
this.endedLocally = true;
this.flagAsEnded(reason);
}
public isPendingAcceptance(): boolean {
return isPendingState(this._state);
}
public isPendingOurAcceptance(): boolean {
if (this._role !== 'callee' || this.acceptedLocally) {
return false;
}
if (this.hidden) {
return false;
}
return this.isPendingAcceptance();
}
public isOver(): boolean {
return this._state === 'hangup';
}
public isAbleToReportStates(): boolean {
return this.mayReportStates;
}
public ignore(): void {
if (this.ignored) {
return;
}
const { hidden: wasHidden } = this;
this.config.logger?.debug('ClientMediaCall.ignore');
this._ignored = true;
if (this.hidden && !wasHidden) {
this.emitter.emit('hidden');
}
this.updateClientState();
this.reportStates();
this.mayReportStates = false;
this.clearStateTimeouts();
}
public setMuted(muted: boolean): void {
if (this.isOver() || this.hidden) {
return;
}
if (!this.webrtcProcessor && !muted) {
return;
}
this.requireWebRTC();
const wasMuted = this.webrtcProcessor.muted;
this.webrtcProcessor.setMuted(muted);
if (wasMuted !== this.webrtcProcessor.muted) {
this.emitter.emit('trackStateChange');
}
}
public setHeld(held: boolean): void {
if (this.isOver() || this.hidden) {
return;
}
if (!this.webrtcProcessor && !held) {
return;
}
this.requireWebRTC();
const wasOnHold = this.webrtcProcessor.held;
this.webrtcProcessor.setHeld(held);
if (wasOnHold !== this.webrtcProcessor.held) {
this.emitter.emit('trackStateChange');
}
}
public setContractState(state: 'signed' | 'ignored') {
if (this.contractState === state) {
return;
}
this.config.logger?.debug('ClientMediaCall.setContractState', `${this.contractState} => ${state}`);
if (['pre-signed', 'self-signed'].includes(this.contractState) && state === 'signed') {
this.contractState = state;
return;
}
if (this.contractState !== 'proposed') {
this.reportStates();
}
if (this.contractState === 'signed') {
if (state === 'ignored') {
this.config.logger?.error('[Media Signal] Trying to ignore a contract that was already signed.');
}
return;
}
if (this.contractState === 'pre-signed' && state === 'ignored') {
this.config.logger?.error('[Media Signal] Our self signed contract was ignored.');
}
const { hidden: wasHidden } = this;
this.contractState = state;
if (this.hidden && !wasHidden) {
this.emitter.emit('hidden');
}
this.maybeStopWebRTC();
}
public reportStates(): void {
this.config.logger?.debug('ClientMediaCall.reportStates');
this.clearStateReporter();
if (!this.mayReportStates) {
return;
}
if (this.hasRemoteData || Date.now() > this.creationTimestamp.valueOf() + CALLS_WITH_NO_REMOTE_DATA_REPORT_DELAY) {
this.config.transporter.sendToServer(this.callId, 'local-state', {
callState: this.state,
clientState: this.getClientState(),
serviceStates: Object.fromEntries(this.serviceStates.entries()),
ignored: this.ignored,
contractState: this.contractState,
...(this.currentNegotiationId && { negotiationId: this.currentNegotiationId }),
});
}
if (this.state === 'hangup') {
this.mayReportStates = false;
}
}
public sendDTMF(dtmf: string, duration?: number): void {
if (!dtmf || !/^[0-9A-D#*,]$/.exec(dtmf)) {
throw new Error('Invalid DTMF tone.');
}
this.config.transporter.sendToServer(this.callId, 'dtmf', {
dtmf,
duration,
});
}
private changeState(newState: CallState): void {
if (newState === this._state) {
return;
}
this.config.logger?.debug('ClientMediaCall.changeState', `${this._state} => ${newState}`);
const oldState = this._state;
this._state = newState;
this.maybeStopWebRTC();
this.updateClientState();
this.emitter.emit('stateChange', oldState);
this.requestStateReport();
switch (newState) {
case 'accepted':
this.emitter.emit('accepted');
break;
case 'active':
this.emitter.emit('active');
this.reportStates();
break;
case 'hangup':
this.emitter.emit('ended');
break;
}
}
private updateClientState(): void {
const { oldClientState } = this;
const clientState = this.getClientState();
if (clientState === oldClientState) {
return;
}
this.config.logger?.debug('ClientMediaCall.updateClientState', `${oldClientState} => ${clientState}`);
this.updateStateTimeouts();
this.requestStateReport();
this.oldClientState = clientState;
this.emitter.emit('clientStateChange', oldClientState);
}
private maybeStopWebRTC(): void {
if (!this.webrtcProcessor) {
return;
}
if (this.isOver() || this.hidden) {
this.webrtcProcessor.stop();
}
}
private changeContact(contact: CallContact | null, { prioritizeExisting }: { prioritizeExisting?: boolean } = {}): void {
this.config.logger?.debug('ClientMediaCall.changeContact');
const lowPriorityContact = prioritizeExisting ? contact : this._contact;
const highPriorityContact = prioritizeExisting ? this._contact : contact;
const finalContact = highPriorityContact || lowPriorityContact;
this._contact = finalContact && { ...finalContact };
if (this._contact) {
this.emitter.emit('contactUpdate');
}
}
protected async processOfferRequest(signal: ServerMediaSignalRequestOffer) {
if (this.hidden) {
return;
}
this.config.logger?.debug('ClientMediaCall.processOfferRequest', signal);
if (!this.isSignalTargetingThisSession(signal)) {
this.config.logger?.error('Received an unsigned offer request.');
return;
}
const { negotiationId } = signal;
if (this.shouldIgnoreWebRTC()) {
this.sendError({ errorType: 'service', errorCode: 'invalid-service', negotiationId, critical: true });
return;
}
this.requireWebRTC();
const iceRestart = this.currentNegotiationId !== negotiationId;
this.currentNegotiationId = negotiationId;
if (iceRestart) {
this.hasLocalDescription = false;
}
this.hasRemoteDescription = false;
let offer: { sdp: RTCSessionDescriptionInit } | null = null;
try {
offer = await this.webrtcProcessor.createOffer({ iceRestart });
} catch (e) {
this.sendError({
errorType: 'service',
errorCode: 'failed-to-create-offer',
negotiationId,
critical: true,
errorDetails: serializeError(e),
});
throw e;
}
if (!offer) {
this.sendError({ errorType: 'service', errorCode: 'implementation-error', negotiationId, critical: true });
return;
}
await this.deliverSdp({ ...offer, negotiationId });
}
protected shouldIgnoreWebRTC(): boolean {
if (this.hasRemoteData) {
return this.service !== 'webrtc';
}
// If we called and we don't support webrtc, assume it's not gonna be a webrtc call
if (this._role === 'caller' && !this.config.processorFactories.webrtc) {
return true;
}
// With no more info, we can't safely ignore webrtc
return false;
}
protected async processAnswerRequest(signal: ServerMediaSignalRemoteSDP): Promise<void> {
this.pendingAnswerRequest = null;
if (this.hidden || this.shouldIgnoreWebRTC()) {
return;
}
this.config.logger?.debug('ClientMediaCall.processAnswerRequest', signal);
this.requireWebRTC();
const { negotiationId } = signal;
const iceRestart = this.currentNegotiationId !== negotiationId;
if (iceRestart) {
this.hasLocalDescription = false;
this.hasRemoteDescription = false;
this.webrtcProcessor.startNewNegotiation();
}
this.currentNegotiationId = negotiationId;
if (!this.hasInputTrack()) {
this.pendingAnswerRequest = signal;
this.config.logger?.debug('Delaying WebRTC Answer due to missing audio input track.');
return;
}
let answer: { sdp: RTCSessionDescriptionInit } | null = null;
try {
answer = await this.webrtcProcessor.createAnswer(signal);
} catch (e) {
this.config.logger?.error(e);
this.sendError({
errorType: 'service',
errorCode: 'failed-to-create-answer',
negotiationId,
critical: true,
errorDetails: serializeError(e),
});
throw e;
}
if (!answer) {
this.sendError({ errorType: 'service', errorCode: 'implementation-error', negotiationId, critical: true });
return;
}
this.hasRemoteDescription = true;
await this.deliverSdp({ ...answer, negotiationId });
}
protected sendError(error: Partial<ClientMediaSignalError>): void {
this.config.logger?.debug('ClientMediaCall.sendError', error);
if (this.hidden) {
return;
}
this.config.transporter.sendError(this.callId, error);
}
protected async processRemoteSDP(signal: ServerMediaSignalRemoteSDP): Promise<void> {
this.config.logger?.debug('ClientMediaCall.processRemoteSDP', signal);
if (this.hidden) {
return;
}
if (!this.isSignalTargetingThisSession(signal)) {
this.config.logger?.error('Received an offer request that is unsigned, or signed to a different session.');
return;
}
if (this.shouldIgnoreWebRTC()) {
return;
}
this.requireWebRTC();
if (signal.sdp.type === 'offer') {
return this.processAnswerRequest(signal);
}
if (signal.negotiationId !== this.currentNegotiationId) {
this.config.logger?.error('Received an answer for an unexpected negotiation.');
return;
}
await this.webrtcProcessor.setRemoteAnswer(signal);
this.hasRemoteDescription = true;
}
protected async deliverSdp(data: { sdp: RTCSessionDescriptionInit; negotiationId: string }) {
this.config.logger?.debug('ClientMediaCall.deliverSdp');
this.hasLocalDescription = true;
if (!this.hidden) {
this.config.transporter.sendToServer(this.callId, 'local-sdp', data);
}
this.updateClientState();
}
protected async rejectAsUnavailable(): Promise<void> {
this.config.logger?.debug('ClientMediaCall.rejectAsUnavailable');
// If we have already told the server we accept this call, then we need to send a hangup to get out of it
if (this.acceptedLocally) {
return this.hangup('unavailable');
}
this.config.transporter.answer(this.callId, 'unavailable');
this.changeState('hangup');
}
protected async processEarlySignals(): Promise<void> {
this.config.logger?.debug('ClientMediaCall.processEarlySignals');
const earlySignals = Array.from(this.earlySignals.values());
this.earlySignals.clear();
for await (const signal of earlySignals) {
try {
await this.processSignal(signal);
} catch (e) {
this.config.logger?.error('Error processing early signal', e);
}
}
}
protected acknowledge(): void {
if (this.acknowledged || this.hidden) {
return;
}
this.config.logger?.debug('ClientMediaCall.acknowledge');
this.acknowledged = true;
this.config.transporter.answer(this.callId, 'ack');
if (this._state === 'none') {
this.changeState('ringing');
}
}
private async processNotification(signal: ServerMediaSignalNotification) {
this.config.logger?.debug('ClientMediaCall.processNotification');
switch (signal.notification) {
case 'accepted':
return this.flagAsAccepted();
case 'active':
if (this.state === 'accepted' || this.hidden) {
this.changeState('active');
}
return;
case 'hangup':
return this.flagAsEnded('remote');
}
}
private async flagAsAccepted(): Promise<void> {
this.config.logger?.debug('ClientMediaCall.flagAsAccepted');
// If hidden, just move the state without doing anything
if (this.hidden) {
this.changeState('accepted');
return;
}
if (!this.acceptedLocally) {
this.config.transporter.sendError(this.callId, { errorType: 'signaling', errorCode: 'not-accepted', critical: true });
this.config.logger?.error('Trying to activate a call that was not yet accepted locally.');
return;
}
if (this.contractState === 'proposed') {
this.contractState = 'self-signed';
}
// Both sides of the call have accepted it, we can change the state now
this.changeState('accepted');
this.addStateTimeout('accepted', TIMEOUT_TO_PROGRESS_SIGNALING);
this.addStateTimeout('has-offer', TIMEOUT_TO_PROGRESS_SIGNALING);
}
private flagAsEnded(reason: CallHangupReason): void {
this.config.logger?.debug('ClientMediaCall.flagAsEnded', reason);
if (this._state === 'hangup') {
return;
}
if (!this.hidden && this.hasRemoteData) {
this.config.transporter.hangup(this.callId, reason);
}
this.changeState('hangup');
}
private addStateTimeout(state: ClientState, timeout: number, callback?: () => void): void {
this.config.logger?.debug('ClientMediaCall.addStateTimeout', state, `${timeout / 1000}s`);
if (this.getClientState() !== state) {
return;
}
// Do not set state timeouts if the call is not happening on this session, unless there's a callback attached to that timeout
if (this.hidden && !callback) {
return;
}
const handler = {
state,
handler: setTimeout(() => {
if (this.stateTimeoutHandlers.has(handler)) {
this.stateTimeoutHandlers.delete(handler);
}
if (state !== this.getClientState()) {
return;