-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathRtcSession.cs
More file actions
2515 lines (2082 loc) · 99.7 KB
/
RtcSession.cs
File metadata and controls
2515 lines (2082 loc) · 99.7 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
#if UNITY_ANDROID && !UNITY_EDITOR
#define STREAM_NATIVE_AUDIO //Defined in multiple files
#endif
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using StreamVideo.v1.Sfu.Events;
using StreamVideo.v1.Sfu.Models;
using StreamVideo.v1.Sfu.Signal;
using StreamVideo.Core.Configs;
using StreamVideo.Core.DeviceManagers;
using StreamVideo.Core.Exceptions;
using StreamVideo.Core.InternalDTO.Requests;
using StreamVideo.Core.LowLevelClient.WebSockets;
using StreamVideo.Core.Models;
using StreamVideo.Core.Models.Sfu;
using StreamVideo.Core.State.Caches;
using StreamVideo.Core.StatefulModels;
using StreamVideo.Core.StatefulModels.Tracks;
using StreamVideo.Core.Utils;
using StreamVideo.Libs.Logs;
using StreamVideo.Libs.Serialization;
using StreamVideo.Libs.Time;
using StreamVideo.Libs.Utils;
using Unity.WebRTC;
using UnityEngine;
using SfuError = StreamVideo.v1.Sfu.Events.Error;
using SfuICETrickle = StreamVideo.v1.Sfu.Models.ICETrickle;
using TrackType = StreamVideo.Core.Models.Sfu.TrackType;
using SfuTrackType = StreamVideo.v1.Sfu.Models.TrackType;
using StreamVideo.Core.Sfu;
using StreamVideo.Core.Stats;
using StreamVideo.Core.Trace;
using StreamVideo.Libs.NetworkMonitors;
namespace StreamVideo.Core.LowLevelClient
{
public delegate void ParticipantTrackChangedHandler(IStreamVideoCallParticipant participant, IStreamTrack track);
public delegate void ParticipantJoinedHandler(IStreamVideoCallParticipant participant);
public delegate void ParticipantLeftHandler(string sessionId, string userId);
public delegate void CallingStateChangedHandler(CallingState previousState, CallingState currentState);
//StreamTodo: Implement GeneratedApi.UpdateMuteStates
//StreamTodo: Implement GeneratedApi.RestartIce
//StreamTodo: Rename GeneratedAPI to SfuRpcApi
//StreamTodo: reconnect flow needs to send `UpdateSubscription` https://getstream.slack.com/archives/C022N8JNQGZ/p1691139853890859?thread_ts=1691139571.281779&cid=C022N8JNQGZ
//StreamTodo: decide lifetime, if the obj persists across session maybe it should be named differently and only return struct handle to a session
internal class RtcSession : IMediaInputProvider, ISfuClient, IDisposable
{
// Static session counter to track the number of sessions created
private static int _sessionCounter = 0;
// StreamTodo: control this via compiler flag
public const bool LogWebRTCStats = false;
// Some sources claim the 48kHz is the most optimal sample rate for WebRTC, other cause internal resampling
public const int AudioInputSampleRate = 48_000;
// Some sources claim the 48kHz is the most optimal sample rate for WebRTC, other cause internal resampling
public const int AudioOutputSampleRate = 48_000;
public const int AudioOutputChannels = 2;
#if STREAM_NATIVE_AUDIO
public const bool UseNativeAudioBindings = true;
#else
public const bool UseNativeAudioBindings = false;
#endif
public const int MaxParticipantsForVideoAutoSubscription = 5;
public event Action<bool> PublisherAudioTrackIsEnabledChanged;
public event Action<bool> PublisherVideoTrackIsEnabledChanged;
public event Action PublisherAudioTrackChanged;
public event Action PublisherVideoTrackChanged;
public event Action PeerConnectionDisconnectedDuringSession;
/// <summary>
/// Fired when the SFU WebSocket disconnects unexpectedly.
/// This is NOT fired when the disconnect is intentional (e.g., leaving a call).
/// </summary>
public event Action SfuDisconnected;
public event CallingStateChangedHandler CallStateChanged;
public bool PublisherAudioTrackIsEnabled
{
get => _publisherAudioTrackIsEnabled;
private set
{
if (_publisherAudioTrackIsEnabled == value)
{
return;
}
_publisherAudioTrackIsEnabled = value;
InternalExecuteSetPublisherAudioTrackEnabled(value);
PublisherAudioTrackIsEnabledChanged?.Invoke(value);
}
}
public bool PublisherVideoTrackIsEnabled
{
get => _publisherVideoTrackIsEnabled;
private set
{
if (_publisherVideoTrackIsEnabled == value)
{
return;
}
_publisherVideoTrackIsEnabled = value;
InternalExecuteSetPublisherVideoTrackEnabled(value);
PublisherVideoTrackIsEnabledChanged?.Invoke(value);
}
}
public CallingState CallState
{
get => _callState;
internal set
{
if (_callState == value)
{
return;
}
var prevState = _callState;
_callState = value;
_logs.Info($"Call state changed from: `{prevState}` to: `{value}`");
CallStateChanged?.Invoke(prevState, value);
}
}
public StreamCall ActiveCall { get; internal set; }
public SubscriberPeerConnection Subscriber { get; private set; }
public PublisherPeerConnection Publisher { get; private set; }
#region IInputProvider
public event Action<AudioSource> AudioInputChanged;
public event Action<WebCamTexture> VideoInputChanged;
public event Action<Camera> VideoSceneInputChanged;
//StreamTodo: move IInputProvider elsewhere. it's for easy testing only
public AudioSource AudioInput
{
get => _audioInput;
set
{
if (value == null)
{
throw new ArgumentNullException();
}
if (value == _audioInput)
{
return;
}
var prev = _audioInput;
_audioInput = value;
if (prev != _audioInput)
{
AudioInputChanged?.Invoke(value);
}
}
}
public WebCamTexture VideoInput
{
get => _videoInput;
set
{
if (value == null)
{
throw new ArgumentNullException();
}
if (value == _videoInput)
{
return;
}
var prev = _videoInput;
_videoInput = value;
if (prev != _videoInput)
{
VideoInputChanged?.Invoke(value);
}
}
}
public Camera VideoSceneInput
{
get => _videoSceneInput;
set
{
var prev = _videoSceneInput;
_videoSceneInput = value;
if (prev != _videoSceneInput)
{
VideoSceneInputChanged?.Invoke(value);
}
}
}
#endregion
public SessionID SessionId { get; } = new SessionID();
/// <summary>
/// Current session version. Increments when session ID is regenerated (e.g., during rejoin).
/// Used to invalidate stale operations like pending ICE restarts.
/// </summary>
public int SessionVersion => SessionId.Version;
public RtcSession(ISfuWebSocketFactory sfuWebSocketFactory, Func<IStreamCall, HttpClient> httpClientFactory,
ILogs logs, ISerializer serializer, ITimeService timeService, StreamVideoLowLevelClient lowLevelClient,
IStreamClientConfig config, INetworkMonitor networkMonitor)
{
_httpClientFactory = httpClientFactory;
_logs = logs;
_serializer = serializer;
_timeService = timeService;
_lowLevelClient = lowLevelClient;
_config = config;
_networkMonitor = networkMonitor;
_sfuWebSocketFactory = sfuWebSocketFactory ?? throw new ArgumentNullException(nameof(sfuWebSocketFactory));
var statsCollector = new UnityWebRtcStatsCollector(this, _serializer, _tracerManager);
_statsSender = new WebRtcStatsSender(this, statsCollector, _timeService, _logs);
//StreamTodo: enable this only if a special mode e.g. compiler flag
#if STREAM_AUDIO_BENCHMARK_ENABLED
_logs.Warning($"Audio benchmark enabled. Waiting for a special video stream to measure audio-video sync. Check {nameof(VideoAudioSyncBenchmark)} summary for more details.");
_videoAudioSyncBenchmark = new VideoAudioSyncBenchmark(_timeService, _logs);
#endif
_networkMonitor.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged;
_mainThreadId = Thread.CurrentThread.ManagedThreadId;
}
public void Dispose()
{
StopAsync("Video Client is being disposed").LogIfFailed();
DisposeSfuWebSocket();
DisposeSubscriber();
DisposePublisher();
_tracerManager?.Clear();
_networkMonitor.NetworkAvailabilityChanged -= OnNetworkAvailabilityChanged;
}
//StreamTodo: to make updates more explicit we could make an UpdateService, that we could tell such dependency by constructor and component would self-register for updates
public void Update()
{
_networkMonitor.Update();
_sfuWebSocket?.Update();
Publisher?.Update();
_statsSender.Update();
_videoAudioSyncBenchmark?.Update();
//StreamTodo: we could remove this if we'd maintain a collection of tracks and update them directly
if (ActiveCall != null && ActiveCall.Participants != null)
{
foreach (StreamVideoCallParticipant p in ActiveCall.Participants)
{
p.Update();
}
}
TryExecuteSubscribeToTracks();
TryExecutePendingReconnectRequest();
}
public async Task SendWebRtcStats(SendStatsRequest request, CancellationToken cancellationToken)
{
var response = await RpcCallAsync(request, GeneratedAPI.SendStats,
nameof(GeneratedAPI.SendStats), cancellationToken, response => response.Error,
postLog: LogWebRTCStats);
if (ActiveCall == null)
{
//Ignore if call ended during this request
#if STREAM_DEBUG_ENABLED
_logs.Warning("Sending webRTC stats aborted: call ended during the request");
#endif
return;
}
if (response.Error != null)
{
// StreamTodo: perhaps failure on stats sending should be silent? This can return "call not found" if call ended before `call.ended` event was received
// Maybe we can wait 1-2s before displaying the error to cover this case
_logs.Warning("Sending webRTC stats failed: " + response.Error.Message);
_logs.ErrorIfDebug("Sending webRTC stats failed: " + response.Error.Message);
}
}
//StreamTodo: solve this dependency better
public void SetCache(ICache cache) => _cache = cache;
private void ValidateCallCredentialsOrThrow(IStreamCall call)
{
if (call.Credentials == null)
{
throw new ArgumentNullException(nameof(call.Credentials));
}
if (call.Credentials.Server == null)
{
throw new ArgumentNullException(nameof(call.Credentials.Server));
}
if (string.IsNullOrEmpty(call.Credentials.Server.Url))
{
throw new ArgumentNullException(nameof(call.Credentials.Server.Url));
}
if (string.IsNullOrEmpty(call.Credentials.Token))
{
throw new ArgumentNullException(nameof(call.Credentials.Token));
}
if (call.Credentials.IceServers == null)
{
throw new ArgumentNullException(nameof(call.Credentials.IceServers));
}
if (call.Credentials.IceServers.Count == 0)
{
throw new ArgumentException("At least one ICE server must be provided in call credentials.");
}
}
public async Task Join(JoinCallData joinCallData, CancellationToken cancellationToken)
{
if (CallState == CallingState.Leaving)
{
_logs.WarningIfDebug($"{nameof(Join)} called while call is leaving. Waiting for leave to complete...");
await StopAsync();
}
if (CallState == CallingState.Joined)
{
throw new InvalidOperationException(
$"Call is already joined. Please leave the current call before joining a new one.");
}
if (CallState == CallingState.Joining)
{
throw new InvalidOperationException(
$"Joining a `{_joinCallData.Id}` call is in progress. Please cancel the current join operation before joining a new one.");
}
// we will count the number of join failures per SFU.
// once the number of failures reaches 2, we will piggyback on the `migrating_from`
// field to force the coordinator to provide us another SFU
var joinFailsPerSfu = new Dictionary<string, int>();
for (int attempt = 0; attempt < CallJoinMaxRetries; attempt++)
{
try
{
_lastJoinCallCredentials = null;
await DoJoin(joinCallData, cancellationToken);
return;
//TODO: joinData.ClearMigrationData
}
catch (Exception)
{
_logs.Warning($"Failed to join call `{joinCallData.Id}`, attempt: {attempt}");
//TODO: check if error is no recoverable
//if (err instanceof ErrorFromResponse && err.unrecoverable)
var sfuId = _lastJoinCallCredentials?.Server.EdgeName ?? string.Empty;
var sfuFails = joinFailsPerSfu.GetValueOrDefault(sfuId) + 1;
if (sfuFails > 2)
{
joinCallData = joinCallData.CloneWithMigratingFromSfu(sfuId);
}
if (attempt == CallJoinMaxRetries - 1)
{
throw;
}
//StreamTODO: randomize a bit
await Task.Delay(500, cancellationToken);
}
}
}
//StreamTODO: cancellation token
public async Task DoJoin(JoinCallData joinCallData, CancellationToken cancellationToken)
{
if (CallState == CallingState.Joining)
{
_logs.Error($"{nameof(DoJoin)} called while already joining.");
throw new NotSupportedException("Already joining");
}
var prevCallState = CallState;
_joinCallData = joinCallData;
CallState = CallingState.Joining;
if (_joinCallCts != null)
{
_logs.ErrorIfDebug("Previous join call CTS was not cleaned up properly. Cancelling it now.");
_joinCallCts.Cancel();
_joinCallCts.Dispose();
_joinCallCts = null;
}
if (_activeCallCts != null)
{
_logs.ErrorIfDebug("Previous active call CTS was not cleaned up properly. Cancelling it now.");
_activeCallCts.Cancel();
_activeCallCts.Dispose();
_activeCallCts = null;
}
_joinCallCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_pendingIceTrickleRequests.Clear();
try
{
var isMigration = _reconnectStrategy == WebsocketReconnectStrategy.Migrate;
var isRejoin = _reconnectStrategy == WebsocketReconnectStrategy.Rejoin;
var isFast = _reconnectStrategy == WebsocketReconnectStrategy.Fast;
var callCid = joinCallData.Type + ":" + joinCallData.Id;
// Call can exist without credentials because it can be added via call.created event
var callCredentialsExists = _cache.Calls.TryGet(callCid, out var call) && call.Credentials != null;
if (!callCredentialsExists || isRejoin || isMigration)
{
try
{
_logs.WarningIfDebug($"{nameof(DoJoin)} - Execute join call API request.");
call = await ExecuteJoinRequest(joinCallData, cancellationToken);
_lastJoinCallCredentials = call.Credentials;
}
catch (Exception e)
{
_logs.ExceptionIfDebug(e);
if (CallState != CallingState.Offline)
{
CallState = prevCallState;
}
throw;
}
}
else
{
_logs.WarningIfDebug(
$"{nameof(DoJoin)} - Skipped join call request: callExists: {callCredentialsExists}, isRejoin: {isRejoin}, isMigration: {isMigration}");
}
ActiveCall = call ?? throw new NullReferenceException(nameof(call));
if (ActiveCall.Credentials == null || string.IsNullOrEmpty(ActiveCall.Credentials.Token))
{
_logs.ErrorIfDebug($"{nameof(DoJoin)} - Missing credentials!");
}
_httpClient = _httpClientFactory(ActiveCall);
var previousSfuWebSocket = _sfuWebSocket;
var isWsHealthy = previousSfuWebSocket?.IsHealthy ?? false;
var startNewSfuWsSession = isRejoin || isMigration || !isWsHealthy;
// Following JS: Publisher/Subscriber are only recreated for REJOIN/MIGRATE.
// For FAST reconnect (even with unhealthy WS), we keep existing pub/sub.
// Also create new ones if they don't exist (initial join).
var startNewPeerConnections = isRejoin || isMigration || Publisher == null || !Publisher.IsHealthy ||
Subscriber == null || !Subscriber.IsHealthy;
string previousSessionId = SessionId.ToString();
// a new session_id is necessary for the REJOIN strategy.
// we use the previous session_id if available
if (isRejoin || SessionId.IsEmpty)
{
_logs.WarningIfDebug($"{nameof(DoJoin)} - Regenerate session ID. {nameof(isRejoin)}:{isRejoin}, SessionID is empty: {SessionId.IsEmpty}");
SessionId.Regenerate();
}
if (startNewSfuWsSession)
{
_logs.WarningIfDebug($"{nameof(DoJoin)} - Create new SFU Session");
CreateNewSfuWebSocket(out previousSfuWebSocket);
var sfuUrl = call.Credentials.Server.Url;
var sfuToken = call.Credentials.Token;
var iceServers = call.Credentials.IceServers;
// Initialize tracers with the correct ID format - separate tracers for SFU, Publisher, and Subscriber
var sfuUrlForId = sfuUrl.Replace("https://", "").Replace("/twirp", "");
var sessionNumber = _sessionCounter + 1;
_sfuTracer = _tracerManager.GetTracer($"{sessionNumber}-{sfuUrlForId}");
_publisherTracer = _tracerManager.GetTracer($"{sessionNumber}-pub");
_subscriberTracer = _tracerManager.GetTracer($"{sessionNumber}-sub");
_sessionCounter++;
if (startNewPeerConnections)
{
_logs.WarningIfDebug($"{nameof(DoJoin)} - Create new Publisher and Subscriber");
// REJOIN/MIGRATE: Create new Publisher/Subscriber
CreatePublisher(call.Credentials.IceServers);
CreateSubscriber(call.Credentials.IceServers);
}
else
{
_logs.WarningIfDebug($"{nameof(DoJoin)} - Don't create new Publisher and Subscriber. Both exist: {(Subscriber != null)}, {(Publisher != null)}");
}
// else: FAST with unhealthy WS - keep existing Publisher/Subscriber.
// No need to update SfuClient reference because Publisher/Subscriber hold a reference to RtcSession
// (which implements ISfuClient), and RtcSession internally manages the _sfuWebSocket.
// We don't set initial offer as local. Later on we set generated answer as a local
var subscriberOffer = await Subscriber.CreateOfferAsync(_joinCallCts.Token);
var publisherOffer = await Publisher.CreateOfferAsync(_joinCallCts.Token);
_sfuWebSocket.InitNewSession(SessionId.ToString(), sfuUrl, sfuToken, subscriberOffer.sdp, publisherOffer.sdp);
var reconnectDetails = new ReconnectDetails
{
Strategy = _reconnectStrategy,
ReconnectAttempt = (uint)_reconnectAttempts,
FromSfuId = joinCallData.MigratingFromSfu,
PreviousSessionId = previousSessionId,
Reason = _reconnectReason ?? string.Empty,
};
var announcedTracks = Publisher.GetAnnouncedTracksForReconnect();
if (announcedTracks?.Any() ?? false)
{
#if STREAM_DEBUG_ENABLED
_logs.WarningIfDebug("DoJoin - announcedTracks " + string.Join(", ", announcedTracks.Select(t => t.TrackType.ToString())));
#endif
reconnectDetails.AnnouncedTracks.AddRange(announcedTracks);
}
var desiredTracks = GetDesiredTracksDetails();
if (desiredTracks.Any())
{
reconnectDetails.Subscriptions.AddRange(desiredTracks);
}
var joinRequest = new SfuConnectRequest
{
ReconnectDetails = reconnectDetails
};
_logs.WarningIfDebug($"{nameof(DoJoin)} - SFU Sending join request");
var joinResponse = await _sfuWebSocket.ConnectAsync(joinRequest, cancellationToken);
//StreamTODO: if we try to rejoin a call with no other participants we'll get error from SFU not call FOUND
// What should we do then?
ActiveCall.UpdateFromSfu(joinResponse);
_logs.WarningIfDebug($"{nameof(DoJoin)} - SFU Sending join response received. startNewPeerConnections: {startNewPeerConnections}");
_fastReconnectDeadlineSeconds = joinResponse.FastReconnectDeadlineSeconds;
if (startNewPeerConnections)
{
_logs.WarningIfDebug($"{nameof(DoJoin)} - startNewPeerConnections, _publisherAudioTrackIsEnabled: {_publisherAudioTrackIsEnabled}, _publisherVideoTrackIsEnabled: {_publisherVideoTrackIsEnabled}");
// Only init publisher tracks for new Publisher
await Publisher.InitPublisherTracksAsync();
await NotifyCurrentMuteStatesAsync();
// Handle tracks subscriptions for already present participants
foreach (var participant in ActiveCall.Participants)
{
if (!participant.IsLocalParticipant)
{
NotifyParticipantJoined(participant.SessionId);
}
}
QueueTracksSubscriptionRequest();
}
}
else
{
_logs.WarningIfDebug($"{nameof(DoJoin)} - Reuse SFU Session");
}
if (!isMigration)
{
// in MIGRATION, `JOINED` state is set in `this.reconnectMigrate()`
CallState = CallingState.Joined;
}
// Following JS: For FAST reconnect, always call RestartIce (after updating SfuClient if needed).
// The SFU automatically issues an ICE restart on the subscriber, we don't have to do it ourselves.
if (isFast)
{
_logs.WarningIfDebug($"{nameof(DoJoin)} - Restart ICE");
await Publisher.RestartIce(); //StreamTODO: cancellation token
}
if (!isRejoin && !isFast && !isMigration)
{
// TODO: send sendConnectionTime
}
if (previousSfuWebSocket != null && previousSfuWebSocket != _sfuWebSocket)
{
var closeReason = isRejoin
? "Closing WS after rejoin"
: "Closing unhealthy WS after reconnect";
_logs.WarningIfDebug($"{nameof(DoJoin)} - Close previous SFU WS - " + closeReason);
ClosePreviousSfuWebSocketAsync(previousSfuWebSocket, closeReason).LogIfFailed();
}
//StreamTODO: JS client deletes here ring and notify data because these are one-time actions
//delete this.joinCallData?.ring;
//delete this.joinCallData?.notify;
_reconnectStrategy = WebsocketReconnectStrategy.Unspecified;
_reconnectReason = string.Empty;
if (UseNativeAudioBindings)
{
//StreamTODO: Either use UseNativeAudioBindings const or STREAM_NATIVE_AUDIO flag but not both. Once we replace the webRTC package we could remove STREAM_NATIVE_AUDIO
#if STREAM_NATIVE_AUDIO
WebRTC.StartAudioPlayback(AudioOutputSampleRate, AudioOutputChannels);
#endif
}
_logs.Info($"{nameof(DoJoin)} - Joined call: {call.Cid}, Call State: {CallState}");
}
catch (Exception e)
{
_logs.Error($"{nameof(DoJoin)} failed with exception: {e.Message}");
_logs.Exception(e);
if (CallState != CallingState.Offline)
{
CallState = prevCallState;
}
throw;
}
finally
{
if (_joinCallCts != null)
{
_joinCallCts.Dispose();
_joinCallCts = null;
}
}
}
//StreamTODO: move
private async Task<StreamCall> ExecuteJoinRequest(JoinCallData data, CancellationToken cancellationToken)
{
// StreamTodo: check state if we don't have an active session already
var locationHint = await _lowLevelClient.GetLocationHintAsync(cancellationToken);
//StreamTodo: move this logic to call.Join, this way user can create call object and join later on
// StreamTodo: expose params
var joinCallRequest = new JoinCallRequestInternalDTO
{
Create = data.Create,
Data = new CallRequestInternalDTO
{
Custom = null,
Members = null,
SettingsOverride = null,
//StreamTODO: check this, if we're just joining another call perhaps we shouldn't set this?
StartsAt = DateTimeOffset.Now,
Team = null
},
Location = locationHint,
MembersLimit = 0,
MigratingFrom = null,
Notify = data.Notify,
Ring = data.Ring
};
var joinCallResponse
= await _lowLevelClient.InternalVideoClientApi.JoinCallAsync(data.Type, data.Id, joinCallRequest);
var streamCall = _cache.TryCreateOrUpdate(joinCallResponse);
//StreamTODO: add ring accept logic. Check JS doJoinRequest
return streamCall;
}
public Task StopAsync(string reason = "")
{
if (UseNativeAudioBindings)
{
#if STREAM_NATIVE_AUDIO
WebRTC.StopAudioPlayback();
#endif
}
if (CallState == CallingState.Leaving || CallState == CallingState.Left)
{
_logs.WarningIfDebug($"{nameof(StopAsync)} ignored because call is in state: " + CallState);
return _ongoingStopTask ?? Task.CompletedTask;
}
//StreamTODO: revise this. Right now StopAsync is always called on disconnect, perhaps we can leave it this way
// if (CallState != CallingState.Joined && CallState != CallingState.Joining)
// {
// throw new InvalidOperationException(
// "Tried to leave call that is not joined or joining. Current state: " + CallState);
// }
CallState = CallingState.Leaving;
_logs.InfoIfDebug("Leaving the call - cleanup session");
_ongoingStopTask = StopInternalAsync(reason);
return _ongoingStopTask;
}
private async Task StopInternalAsync(string reason)
{
try
{
if (_joinCallCts != null)
{
_joinCallCts.Cancel();
}
if (_activeCallCts != null)
{
_activeCallCts.Cancel();
}
if (ActiveCall != null)
{
_logs.Info("Leaving active call with Cid: " + ActiveCall.Cid);
try
{
// Trace leave call before leaving the call. Otherwise, stats are not send because SFU WS disconnects
_sfuTracer?.Trace(PeerConnectionTraceKey.LeaveCall, new { SessionId = SessionId.ToString(), Reason = reason });
if (_statsSender != null) // This was null in tests
{
var sendStatsCancellationToken = new CancellationTokenSource();
sendStatsCancellationToken.CancelAfter(800);
using (new TimeLogScope("Sending final stats on leave", _logs.Info))
{
await _statsSender.SendFinalStatsAsync(sendStatsCancellationToken.Token);
}
}
}
catch (HttpRequestException httpEx)
{
_logs.Info($"Network unavailable during final stats send: {httpEx.Message}");
}
catch (OperationCanceledException)
{
_logs.Info("Final stats send timed out.");
}
catch (Exception e)
{
_logs.Warning($"Failed to send final stats on leave: {e.Message}");
}
}
await ClearSessionAsync();
if (_sfuWebSocket != null)
{
using (new TimeLogScope("Sending leave call request & disconnect", _logs.Info))
{
await _sfuWebSocket.DisconnectAsync(WebSocketCloseStatus.NormalClosure, reason);
}
}
#if STREAM_DEBUG_ENABLED
_videoAudioSyncBenchmark?.Finish();
#endif
}
finally
{
// Set Left before clearing ActiveCall so that CallStateChanged subscribers
// can still access the call reference
CallState = CallingState.Left;
ActiveCall = null;
}
}
public void UpdateRequestedVideoResolution(string participantSessionId, VideoResolution videoResolution)
{
_videoResolutionByParticipantSessionId[participantSessionId] = videoResolution;
QueueTracksSubscriptionRequest();
}
public void UpdateIncomingVideoRequested(string participantSessionId, bool isRequested)
{
_incomingVideoRequestedByParticipantSessionId[participantSessionId] = isRequested;
QueueTracksSubscriptionRequest();
}
public void UpdateIncomingAudioRequested(string participantSessionId, bool isRequested)
{
_incomingAudioRequestedByParticipantSessionId[participantSessionId] = isRequested;
QueueTracksSubscriptionRequest();
}
// Let's request video for the first 10 participants that join
public void NotifyParticipantJoined(string participantSessionId)
{
if (ActiveCall == null)
{
return;
}
var participantCount = ActiveCall.Participants?.Count ?? 0;
var requestVideo = participantCount <= MaxParticipantsForVideoAutoSubscription;
var requestAudio = true; // No limit by default
_incomingVideoRequestedByParticipantSessionId.TryAdd(participantSessionId, requestVideo);
_incomingAudioRequestedByParticipantSessionId.TryAdd(participantSessionId, requestAudio);
}
public void NotifyParticipantLeft(string participantSessionId)
{
_videoResolutionByParticipantSessionId.Remove(participantSessionId);
_incomingVideoRequestedByParticipantSessionId.Remove(participantSessionId);
_incomingAudioRequestedByParticipantSessionId.Remove(participantSessionId);
QueueTracksSubscriptionRequest();
}
public void SetAudioRecordingDevice(MicrophoneDeviceInfo device)
{
_logs.WarningIfDebug("RtcSession.SetAudioRecordingDevice device: " + device);
_activeAudioRecordingDevice = device;
UpdateAudioRecording();
}
/// <summary>
/// Set Publisher Audio track enabled/disabled, if track is available, or store the preference for when track becomes available
/// </summary>
public void TrySetPublisherAudioTrackEnabled(bool isEnabled) => PublisherAudioTrackIsEnabled = isEnabled;
public void TryRestartAudioRecording() => UpdateAudioRecording();
public void TryRestartAudioPlayback()
{
if (!UseNativeAudioBindings)
{
return;
}
#if STREAM_NATIVE_AUDIO
WebRTC.StopAudioPlayback();
WebRTC.StartAudioPlayback(AudioOutputSampleRate, AudioOutputChannels);
#endif
}
//StreamTODO: temp solution to allow stopping the audio when app is minimized. User tried disabling the AudioSource but the audio is handled natively so it has no effect
public void PauseAndroidAudioPlayback()
{
#if STREAM_NATIVE_AUDIO
WebRTC.MuteAndroidAudioPlayback();
_logs.Warning("Audio Playback is paused. This stops all audio coming from StreamVideo SDK on Android platform.");
#else
throw new NotSupportedException(
$"{nameof(PauseAndroidAudioPlayback)} is only supported on Android platform.");
#endif
}
//StreamTODO: temp solution to allow stopping the audio when app is minimized. User tried disabling the AudioSource but the audio is handled natively so it has no effect
public void ResumeAndroidAudioPlayback()
{
#if STREAM_NATIVE_AUDIO
WebRTC.UnmuteAndroidAudioPlayback();
_logs.Warning("Audio Playback is resumed. This resumes audio coming from StreamVideo SDK on Android platform.");
#else
throw new NotSupportedException(
$"{nameof(ResumeAndroidAudioPlayback)} is only supported on Android platform.");
#endif
}
/// <summary>
/// Set Publisher Video track enabled/disabled, if track is available, or store the preference for when track becomes available
/// </summary>
public void TrySetPublisherVideoTrackEnabled(bool isEnabled) => PublisherVideoTrackIsEnabled = isEnabled;
protected virtual bool ArePeerConnectionsHealthy()
=> (Publisher?.IsHealthy ?? false) && (Subscriber?.IsHealthy ?? false);
protected virtual bool IsOfflineTimeWithinFastReconnectDeadline()
{
var offlineTime = _timeService.UtcNow - _lastTimeOffline;
return offlineTime.TotalSeconds <= _fastReconnectDeadlineSeconds;
}
//StreamTODO: add triggering from SFU WS closed.
// In JS -> Call.ts -> onSignalClose -> handleSfuSignalClose -> reconnect
//StreamTODO: add triggering from network changed -> js Call.ts "network.changed"
protected virtual async Task Reconnect(WebsocketReconnectStrategy strategy, string reason)
{
if (!AssertMainThread())
{
_pendingReconnectRequest = new ValueTuple<WebsocketReconnectStrategy, string>(strategy, reason);
return;
}
if (!_reconnectGuard.TryBeginReconnection(CallState))
{
_logs.WarningIfDebug($"[Reconnect] Ignoring reconnect request. CallState: {CallState}, IsReconnecting: {_reconnectGuard.IsReconnecting}");
return;
}
_logs.WarningIfDebug($"--------- Reconnection FLOW TRIGGERED ---------- strategy: {strategy}, reason: {reason}");
try
{
_reconnectStrategy = strategy;
_reconnectReason = reason;
var finishedStates = new[] { CallingState.Joined, CallingState.ReconnectingFailed, CallingState.Left, CallingState.Offline };
var attempt = 0;
var reconnectStartTime = _timeService.UtcNow;
//StreamTODO: we should handle cancellation token between each await
do
{
// StreamTODO: consider give up timeout. JS has it
// Only increment attempts if the strategy is not FAST
if (_reconnectStrategy != WebsocketReconnectStrategy.Fast)
{
_reconnectAttempts++;
}
try
{
_logs.Info("Reconnect with strategy: " + _reconnectStrategy);
switch (_reconnectStrategy)
{
case WebsocketReconnectStrategy.Unspecified:
case WebsocketReconnectStrategy.Disconnect:
// Log warning
break;
case WebsocketReconnectStrategy.Fast:
await ReconnectFast();
break;
case WebsocketReconnectStrategy.Rejoin:
await ReconnectRejoin();
break;
case WebsocketReconnectStrategy.Migrate:
await ReconnectMigrate();
break;
default:
throw new ArgumentOutOfRangeException();
}
}
catch (Exception e)
{