-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathAntMediaClient.swift
1630 lines (1333 loc) · 59 KB
/
AntMediaClient.swift
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
//
// WebRTCClient.swift
// AntMediaSDK
//
// Copyright © 2018 AntMedia. All rights reserved.
//
import Foundation
import AVFoundation
import Starscream
import WebRTC
let TAG: String = "AntMedia_iOS: "
public enum AntMediaClientMode: Int {
case join = 1
case play = 2
case publish = 3
//deprecated
case conference = 4;
case unspecified = 5;
func getLeaveMessage() -> String {
switch self {
case .join:
return "leave"
case .publish, .play:
return "stop"
case .conference:
return "leaveRoom"
case .unspecified:
return "unspecified";
}
}
func getName() -> String {
switch self {
case .join:
return "join"
case .play:
return "play"
case .publish:
return "publish"
case .conference:
return "conference"
case .unspecified:
return "unspecified";
}
}
}
open class AntMediaClient: NSObject, AntMediaClientProtocol {
internal static var isDebug: Bool = false
internal static var isVerbose: Bool = false
public weak var delegate: AntMediaClientDelegate?
private var wsUrl: String!
private var publisherStreamId: String? = nil;
/**
mainTrackId can also be used the roomId of the conference
*/
private var mainTrackId: String?
private var playerStreamId: String?
private var p2pStreamId: String?
private var publishToken: String?
private var playToken: String?
private var webSocket: WebSocket?
//keep it for backward compatibility
private var mode: AntMediaClientMode!
var streamsInTheRoom:[String] = [];
var audioLevelGetterTimer: Timer?;
var rtcStatsTimer: Timer?
var rtcStatsStreamIdSet = Set<String>()
//private var webRTCClient: WebRTCClient?;
private var webRTCClientMap: [String: WebRTCClient] = [:]
private var localView: RTCVideoRenderer?
private var remoteView: RTCVideoRenderer?
private var videoContentMode: UIView.ContentMode?
private static let dispatchQueue = DispatchQueue(label: "audio")
private static let rtcAudioSession = RTCAudioSession.sharedInstance()
private var localContainerBounds: CGRect?
private var remoteContainerBounds: CGRect?
private var cameraPosition: AVCaptureDevice.Position = .front
private var targetWidth: Int = 1280
private var targetHeight: Int = 720
private var maxVideoBps: NSNumber = 0;
private var videoEnable: Bool = true
private var audioEnable: Bool = true
private var enableDataChannel: Bool = true
//Screen capture of the app's screen.
private var useExternalCameraSource: Bool = false
private var isWebSocketConnected: Bool = false;
private var isWebSocketConnecting: Bool = false;
private var externalAudioEnabled: Bool = false;
// External video capture is getting frames from Broadcast Extension.
//In order to make the broadcast extension to work both captureScreenEnable and
// externalVideoCapture should be true
private var externalVideoCapture: Bool = false;
private var cameraSourceFPS: Int = 30;
/**
Degradation preference when publishing streams. By default its values is maintainResolution because when resolution changes HLS playback does not play in safari
*/
private var degradationPreference: RTCDegradationPreference = RTCDegradationPreference.maintainResolution;
var pingTimer: Timer?
var disableTrackId:String?
var reconnectIfRequiresScheduled: Bool = false;
struct HandshakeMessage:Codable {
var command:String?
var streamId:String?
var token:String?
var video:Bool?
var audio:Bool?
var mode:String?
var mainTrack:String?
var trackList:[String]
}
public override init() {
}
public func setOptions(url: String, streamId: String, token: String = "", mode: AntMediaClientMode = .join, enableDataChannel: Bool = false, useExternalCameraSource: Bool = false) {
self.wsUrl = url
self.mode = mode
if self.mode == AntMediaClientMode.publish {
self.publisherStreamId = streamId;
self.publishToken = token;
}
else if (self.mode == AntMediaClientMode.play) {
self.playerStreamId = streamId;
self.playToken = token;
}
else if self.mode == AntMediaClientMode.join {
self.p2pStreamId = streamId;
}
self.enableDataChannel = enableDataChannel
self.useExternalCameraSource = useExternalCameraSource
}
public func setWebSocketServerUrl(url: String) {
self.wsUrl = url;
}
public func setRoomId(roomId: String) {
self.mainTrackId = roomId
}
public func setEnableDataChannel(enableDataChannel: Bool) {
self.enableDataChannel = enableDataChannel;
}
public func setUseExternalCameraSource(useExternalCameraSource: Bool) {
self.useExternalCameraSource = useExternalCameraSource;
}
public func setMaxVideoBps(videoBitratePerSecond: NSNumber) {
self.maxVideoBps = videoBitratePerSecond;
self.webRTCClientMap[self.getPublisherStreamId()]?.setMaxVideoBps(maxVideoBps: videoBitratePerSecond)
}
public func setVideoEnable( enable: Bool) {
self.videoEnable = enable
}
public func getStreamId(_ streamId:String = "") -> String {
//backward compatibility
if streamId.isEmpty {
return self.publisherStreamId ?? (self.playerStreamId ?? (self.p2pStreamId ?? ""));
}
else {
return streamId;
}
}
public func getPublisherStreamId() -> String {
return self.publisherStreamId ?? (self.p2pStreamId ?? "");
}
func getHandshakeMessage(streamId: String, mode: AntMediaClientMode, token:String = "") -> String {
var trackList:[String] = [];
AntMediaClient.printf("disable track id is \(String(describing: self.disableTrackId))");
if let trackId = self.disableTrackId {
AntMediaClient.printf("appending track id to the tracklist \(String(describing: self.disableTrackId))");
trackList.append("!" + trackId);
}
else {
AntMediaClient.printf("Disable track id is not set \(String(describing: self.disableTrackId))");
}
let handShakeMesage = HandshakeMessage(command: mode.getName(), streamId: streamId, token: token, video: self.videoEnable, audio:self.audioEnable, mainTrack: self.mainTrackId, trackList: trackList)
let json = try! JSONEncoder().encode(handShakeMesage)
return String(data: json, encoding: .utf8)!
}
public func getLeaveMessage(streamId: String, mode:AntMediaClientMode) -> [String: String] {
return [COMMAND: mode.getLeaveMessage(), STREAM_ID: streamId]
}
// Force speaker
public static func speakerOn() {
dispatchQueue.async {() in
rtcAudioSession.lockForConfiguration()
do {
try rtcAudioSession.overrideOutputAudioPort(.speaker)
try rtcAudioSession.setActive(true)
} catch let error {
AntMediaClient.printf("Couldn't force audio to speaker: \(error)")
}
rtcAudioSession.unlockForConfiguration()
}
}
// Fallback to the default playing device: headphones/bluetooth/ear speaker
public static func speakerOff() {
dispatchQueue.async {() in
rtcAudioSession.lockForConfiguration()
do {
try rtcAudioSession.overrideOutputAudioPort(.none)
} catch let error {
debugPrint("Error setting AVAudioSession category: \(error)")
}
rtcAudioSession.unlockForConfiguration()
}
}
open func start() {
initPeerConnection(streamId: self.getStreamId(), mode: self.mode, token: self.publishToken ?? (self.playToken ?? ""))
if (!isWebSocketConnected) {
connectWebSocket()
}
else {
self.websocketConnected();
}
}
/**
Join P2P call
*/
public func join(streamId:String)
{
self.p2pStreamId = streamId;
resetDefaultWebRTCAudioConfiguation();
initPeerConnection(streamId: streamId, mode: AntMediaClientMode.join)
if (!isWebSocketConnected) {
connectWebSocket();
}
else {
sendJoinCommand(streamId)
}
}
/**
Leave from p2p call
*/
public func leave(streamId:String) {
if (!isWebSocketConnected) {
let leaveMessage = [
COMMAND: "leave",
STREAM_ID: streamId] as [String : Any]
webSocket?.write(string:leaveMessage.json)
}
self.webRTCClientMap.removeValue(forKey: streamId)?.disconnect();
}
public func joinRoom(roomId:String, streamId: String = "") {
self.mainTrackId = roomId;
self.publisherStreamId = streamId;
self.mode = AntMediaClientMode.conference;
if (!isWebSocketConnected) {
connectWebSocket()
}
else {
sendJoinConferenceCommand()
}
}
/**
Called when the server responds with "joined room notification" as a response to "join room" command
*/
private func joinedRoom(streamId:String, streams:[String]) {
self.publisherStreamId = streamId;
self.delegate?.streamIdToPublish(streamId: streamId);
self.streamsInTheRoom = streams;
if (self.streamsInTheRoom.count > 0) {
self.delegate?.newStreamsJoined(streams: streams);
}
reconnectIfRequires()
}
public func leaveFromRoom() {
if (isWebSocketConnected)
{
if let roomId = self.mainTrackId {
let leaveRoomMessage = [
COMMAND: "leaveFromRoom",
ROOM_ID: roomId,
STREAM_ID: self.publisherStreamId ?? "" ] as [String : Any]
webSocket?.write(string: leaveRoomMessage.json)
AntMediaClient.printf("Sending leaveRoom message \(leaveRoomMessage.json)");
}
else {
AntMediaClient.printf("Websocket is not connected to send leave from room message");
}
}
if let tmpStreamId = self.publisherStreamId {
self.webRTCClientMap.removeValue(forKey: tmpStreamId)?.disconnect();
}
if let tmpStreamId = self.playerStreamId {
self.webRTCClientMap.removeValue(forKey: tmpStreamId)?.disconnect()
}
}
//this configuration don't ask for mic permission it's useful for playback
public func dontAskMicPermissionForPlaying() {
let webRTCConfiguration = RTCAudioSessionConfiguration.init()
webRTCConfiguration.mode = AVAudioSession.Mode.moviePlayback.rawValue
webRTCConfiguration.category = AVAudioSession.Category.playback.rawValue
webRTCConfiguration.categoryOptions = AVAudioSession.CategoryOptions.duckOthers
RTCAudioSessionConfiguration.setWebRTC(webRTCConfiguration)
}
//this configuration ask mic permission and capture mic record
public func resetDefaultWebRTCAudioConfiguation() {
RTCAudioSessionConfiguration.setWebRTC(RTCAudioSessionConfiguration.init())
}
public func publish(streamId: String, token: String = "", mainTrackId: String = "") {
self.publisherStreamId = streamId;
//reset default webrtc audio configuation to capture audio and mic
resetDefaultWebRTCAudioConfiguation();
initPeerConnection(streamId: streamId, mode: AntMediaClientMode.publish, token: token)
if (!mainTrackId.isEmpty) {
self.mainTrackId = mainTrackId
}
if (!token.isEmpty) {
self.publishToken = token;
}
if (!isWebSocketConnected) {
connectWebSocket();
}
else {
sendPublishCommand(streamId)
}
}
public func play(streamId: String, token: String = "") {
self.playerStreamId = streamId;
if (!token.isEmpty) {
self.playToken = token;
}
if let streamId = self.publisherStreamId
{
if (self.webRTCClientMap[streamId] == nil)
{
//if there is not publisherStreamId, don't ask mic permission for playing
dontAskMicPermissionForPlaying();
}
}
else {
//if there is not publisherStreamId, don't ask mic permission for playing
dontAskMicPermissionForPlaying();
}
initPeerConnection(streamId: streamId, mode: AntMediaClientMode.play, token: token)
if (!isWebSocketConnected) {
connectWebSocket();
}
else {
sendPlayCommand(streamId)
}
}
/*
Connect to websocket.
*/
open func connectWebSocket()
{
AntMediaClient.dispatchQueue.async
{
AntMediaClient.printf("Connect websocket to \(self.getWsUrl())")
if (!self.isWebSocketConnected && !self.isWebSocketConnecting) { //provides backward compatibility
self.isWebSocketConnecting = true;
self.streamsInTheRoom.removeAll();
AntMediaClient.printf("Will connect to: \(self.getWsUrl()) for stream: \(self.getStreamId())")
self.webSocket = WebSocket(request: self.getRequest())
self.webSocket?.delegate = self
self.webSocket?.connect()
}
else {
if (self.isWebSocketConnected) {
AntMediaClient.printf("WebSocket is already connected to: \(self.getWsUrl())")
}
if (self.isWebSocketConnecting) {
AntMediaClient.printf("WebSocket is connecting to: \(self.getWsUrl())")
}
}
}
}
open func setCameraPosition(position: AVCaptureDevice.Position) {
self.cameraPosition = position
}
open func setTargetResolution(width: Int, height: Int) {
self.targetWidth = width
self.targetHeight = height
}
open func setTargetFps(fps: Int) {
self.cameraSourceFPS = fps;
}
/*
Get a default value to make it compatible with old version
*/
open func stop(streamId:String = "") {
AntMediaClient.rtcAudioSession.remove(self);
let tmpStreamId = getStreamId(streamId)
AntMediaClient.printf("Stop is called for \(tmpStreamId)")
if tmpStreamId == self.p2pStreamId
{
//provide backward compatibility
if tmpStreamId == streamId {
leave(streamId: tmpStreamId)
}
}
else {
//removing means that user requests to stop
unregisterStatsListener(streamId: tmpStreamId);
self.webRTCClientMap.removeValue(forKey: tmpStreamId)?.disconnect();
if (isWebSocketConnected) {
let command = [
COMMAND: "stop",
STREAM_ID: tmpStreamId] as [String : String];
webSocket?.write(string: command.json)
}
else {
AntMediaClient.printf("Websocket is not connected to stop stream:\(tmpStreamId)")
}
if (self.publisherStreamId == tmpStreamId) {
self.publisherStreamId = nil
}
else if (self.playerStreamId == tmpStreamId) {
self.playerStreamId = nil;
}
}
}
open func initPeerConnection(streamId: String = "", mode:AntMediaClientMode=AntMediaClientMode.unspecified, token: String = "") {
let id = getStreamId(streamId);
if (self.webRTCClientMap[id] == nil) {
AntMediaClient.printf("Has wsClient? (start) : \(String(describing: self.webRTCClientMap[id]))")
self.webRTCClientMap[id] = WebRTCClient.init(remoteVideoView: remoteView, localVideoView: localView, delegate: self, cameraPosition: self.cameraPosition, targetWidth: self.targetWidth, targetHeight: self.targetHeight, videoEnabled: self.videoEnable, enableDataChannel: self.enableDataChannel, useExternalCameraSource: self.useExternalCameraSource, externalAudio: self.externalAudioEnabled, externalVideoCapture: self.externalVideoCapture, cameraSourceFPS: self.cameraSourceFPS, streamId:id,
degradationPreference: self.degradationPreference);
if (self.mode != .play) {
self.webRTCClientMap[id]?.addLocalMediaStream();
}
self.webRTCClientMap[id]?.setToken(token)
AntMediaClient.rtcAudioSession.add(self);
}
else {
//it may initialized without correct token parameter because of backward compatibility
self.webRTCClientMap[id]?.setToken(token)
AntMediaClient.printf("WebRTCClient already initialized for id:\(id) and mode:\(mode.getName())")
}
}
/*
Just switches the camera. It works on the fly as well
*/
open func switchCamera() {
self.webRTCClientMap[(self.publisherStreamId ?? (self.p2pStreamId)) ?? ""]?.switchCamera()
}
/*
Send data through WebRTC Data channel.
*/
open func sendData(data: Data, binary: Bool = false, streamId: String = "") {
self.webRTCClientMap[getStreamId(streamId)]?.sendData(data: data, binary: binary)
}
open func isDataChannelActive(streamId: String = "") -> Bool {
return self.webRTCClientMap[getStreamId(streamId)]?.isDataChannelActive() ?? false
}
open func setLocalView( container: UIView, mode:UIView.ContentMode = .scaleAspectFit) {
#if arch(arm64)
let localRenderer = RTCMTLVideoView(frame: container.frame)
localRenderer.videoContentMode = mode
#else
let localRenderer = RTCEAGLVideoView(frame: container.frame)
localRenderer.delegate = self
#endif
localRenderer.frame = container.bounds
self.localView = localRenderer
self.localContainerBounds = container.bounds
AntMediaClient.embedView(localRenderer, into: container)
}
open func setRemoteView(remoteContainer: UIView, mode:UIView.ContentMode = .scaleAspectFit) {
#if arch(arm64)
let remoteRenderer = RTCMTLVideoView(frame: remoteContainer.frame)
remoteRenderer.videoContentMode = mode
#else
let remoteRenderer = RTCEAGLVideoView(frame: remoteContainer.frame)
remoteRenderer.delegate = self
#endif
remoteRenderer.frame = remoteContainer.frame
self.remoteView = remoteRenderer
self.remoteContainerBounds = remoteContainer.bounds
AntMediaClient.embedView(remoteRenderer, into: remoteContainer)
}
open func disableTrack(trackId:String) {
self.disableTrackId = trackId;
}
public static func embedView(_ view: UIView, into containerView: UIView) {
containerView.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|",
options: [],
metrics: nil,
views: ["view":view]))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|",
options: [],
metrics: nil,
views: ["view":view]))
containerView.layoutIfNeeded()
}
open func isConnected() -> Bool {
return isWebSocketConnected;
}
open func setDebug(_ value: Bool) {
AntMediaClient.isDebug = value
}
public static func setDebug(_ value: Bool) {
AntMediaClient.isDebug = value
}
/*
Toggle publisher audo
*/
open func toggleAudio() {
self.webRTCClientMap[self.publisherStreamId ?? (self.p2pStreamId ?? "")]?.toggleAudioEnabled()
if let audioEnabled = self.webRTCClientMap[self.publisherStreamId ?? (self.p2pStreamId ?? "")]?.isAudioEnabled() {
self.sendAudioTrackStatusNotification(enabled: audioEnabled)
}
}
func sendAudioTrackStatusNotification(enabled:Bool)
{
var eventType = EVENT_TYPE_MIC_MUTED;
if (enabled) {
eventType = EVENT_TYPE_MIC_UNMUTED;
}
if let streamId = self.publisherStreamId {
self.sendNotification(eventType: eventType, streamId:streamId);
}
}
/*
Set publisher audio track
*/
open func setAudioTrack(enableTrack: Bool) {
self.webRTCClientMap[self.publisherStreamId ?? (self.p2pStreamId ?? "")]?.setAudioEnabled(enabled: enableTrack);
self.sendAudioTrackStatusNotification(enabled:enableTrack);
}
open func getLocalAudioTrack() -> RTCAudioTrack? {
self.webRTCClientMap[self.publisherStreamId ?? (self.p2pStreamId ?? "")]?.getLocalAudioTrack();
}
open func getLocalVideoTrack() -> RTCVideoTrack? {
self.webRTCClientMap[self.publisherStreamId ?? (self.p2pStreamId ?? "")]?.getLocalVideoTrack();
}
func sendNotification(eventType:String, streamId: String = "") {
let notification = [
EVENT_TYPE: eventType,
STREAM_ID: self.getStreamId()].json;
if let data = notification.data(using: .utf8) {
self.webRTCClientMap[self.publisherStreamId ?? (self.p2pStreamId ?? "")]?.sendData(data: data);
}
}
open func setMicMute( mute: Bool, completionHandler:@escaping(Bool, Error?)->Void)
{
AntMediaClient.dispatchQueue.async { () in
AntMediaClient.rtcAudioSession.lockForConfiguration()
do {
var category:String;
if (mute) {
category = AVAudioSession.Category.soloAmbient.rawValue;
}
else {
category = AVAudioSession.Category.playAndRecord.rawValue;
}
try AntMediaClient.rtcAudioSession.setCategory(category);
//playAndRecord category defaults receiver to set to speaker
try AntMediaClient.rtcAudioSession.overrideOutputAudioPort(.speaker)
try AntMediaClient.rtcAudioSession.setActive(true);
self.webRTCClientMap[self.getPublisherStreamId()]?.setAudioEnabled(enabled: !mute);
self.sendNotification(eventType: mute ? EVENT_TYPE_MIC_MUTED : EVENT_TYPE_MIC_UNMUTED);
completionHandler(mute, nil);
} catch let error {
AntMediaClient.printf("Couldn't set to mic status: \(error)")
completionHandler(mute, error);
}
AntMediaClient.rtcAudioSession.unlockForConfiguration()
}
}
open func toggleVideo() {
self.webRTCClientMap[getPublisherStreamId()]?.toggleVideoEnabled()
if let videoEnabled = self.webRTCClientMap[self.publisherStreamId ?? (self.p2pStreamId ?? "")]?.isVideoEnabled() {
self.sendVideoTrackStatusNotification(enabled: videoEnabled)
}
}
func sendVideoTrackStatusNotification(enabled:Bool) {
var eventType = EVENT_TYPE_CAM_TURNED_OFF;
if (enabled) {
eventType = EVENT_TYPE_CAM_TURNED_ON;
}
if let streamId = self.publisherStreamId {
self.sendNotification(eventType: eventType, streamId:streamId);
}
}
open func setVideoTrack(enableTrack: Bool)
{
self.webRTCClientMap[getPublisherStreamId()]?.setVideoEnabled(enabled: enableTrack);
self.sendVideoTrackStatusNotification(enabled:enableTrack);
}
open func getCurrentMode() -> AntMediaClientMode {
return self.mode
}
open func getWsUrl() -> String {
return wsUrl;
}
fileprivate func sendPublishCommand(_ streamId: String) {
if isWebSocketConnected {
let jsonString = getHandshakeMessage(streamId: streamId, mode: AntMediaClientMode.publish, token:self.publishToken ?? "");
webSocket?.write(string: jsonString)
AntMediaClient.printf("Send Publish onConnection message: \(jsonString)")
//Add 3 seconds delay here and reconnectIfRequires has also 3 seconds delay
AntMediaClient.dispatchQueue.asyncAfter(deadline: .now() + 5.0) {
self.reconnectIfRequires();
};
}
else {
AntMediaClient.printf("Websocket is not connected to send Publish message for stream\(streamId)")
}
}
func sendJoinConferenceCommand()
{
if isWebSocketConnected
{
if let roomId = self.mainTrackId {
let joinRoomMessage = [
COMMAND: "joinRoom",
ROOM_ID: roomId,
MODE: "multitrack",
STREAM_ID: self.publisherStreamId ?? "" ] as [String : String]
webSocket?.write(string: joinRoomMessage.json)
}
else {
AntMediaClient.printf("mainTrackId is not specified to join the room ");
}
}
else {
AntMediaClient.printf("Websocket is not connected to send joinConferece message for room \(String(describing: self.mainTrackId))")
}
}
fileprivate func sendPlayCommand(_ streamId: String) {
if (isWebSocketConnected) {
let jsonString = getHandshakeMessage(streamId: streamId, mode: AntMediaClientMode.play, token: self.playToken ?? "");
webSocket?.write(string: jsonString)
AntMediaClient.printf("Play onConnection message: \(jsonString)")
//Add 3 seconds delay here and reconnectIfRequires has also 3 seconds delay
AntMediaClient.dispatchQueue.asyncAfter(deadline: .now() + 5.0) {
self.reconnectIfRequires();
};
}
else {
AntMediaClient.printf("Websocket is not connected to send play message for stream: \(streamId)")
}
}
fileprivate func sendJoinCommand(_ streamId: String) {
let jsonString = getHandshakeMessage(streamId: streamId, mode: AntMediaClientMode.join)
webSocket?.write(string: jsonString)
AntMediaClient.printf("P2P onConnection message: \(jsonString)")
}
private func websocketConnected() {
if (isWebSocketConnected) {
if mode == AntMediaClientMode.conference {
sendJoinConferenceCommand();
}
//multiple modes can be active at a time so they are "if" statement
if let streamId = self.publisherStreamId {
sendPublishCommand(streamId)
}
if let streamId = self.playerStreamId {
sendPlayCommand(streamId)
}
if let streamId = self.p2pStreamId {
sendJoinCommand(streamId)
}
}
// setup for audio interruption notification
self.setupAudioNotifications()
}
private func websocketDisconnected(message:String, code:UInt16) {
self.delegate?.clientDidDisconnect(message)
self.reconnectIfRequires()
}
/**
Re-connection Scenario based on Ice Connection State because No matter websocket is disconnected or webrtc is disconnected
, ice Connection states changes to disconnected and below `reconnectIfRequires` method is called when ice connection is disconnected.
`reconnectIfRequires` checks if connection is in the map because if the connection is stopped by the user, it's removed from the map, then there is nothing to do.
If it's not removed from the map and its state is closed, disconnected or failed it means that is a reconnect scenario is required.
This method is also called after joining a room to check if it requires to reconnect
*/
private func reconnectIfRequires() {
if (self.reconnectIfRequiresScheduled) {
AntMediaClient.printf("ReconnectIfRequires is already scheduled and it will work soon")
return;
}
self.reconnectIfRequiresScheduled = true;
AntMediaClient.dispatchQueue.asyncAfter(deadline: .now() + 3.0) {
self.reconnectIfRequiresScheduled = false;
if let streamId = self.publisherStreamId {
//if there is a webRTCClient in the map, it means it's disconnected due to network issue
if (self.webRTCClientMap[streamId] != nil)
{
let iceState = self.webRTCClientMap[streamId]?.getIceConnectionState();
//check the ice state if this method is triggered consequently
if ( iceState == RTCIceConnectionState.closed ||
iceState == RTCIceConnectionState.disconnected ||
iceState == RTCIceConnectionState.failed ||
iceState == RTCIceConnectionState.new
)
{
//clean the connection
self.webRTCClientMap.removeValue(forKey: streamId)?.disconnect()
AntMediaClient.printf("Reconnecting to publish the stream:\(streamId)");
self.publish(streamId:streamId)
}
else {
AntMediaClient.printf("Not trying to reconnect to publish the stream:\(streamId) because ice connection state is not disconnected");
}
}
}
if let streamId = self.playerStreamId {
//if there is a webRTCClient in the map, it means it's disconnected due to network issue
let iceState = self.webRTCClientMap[streamId]?.getIceConnectionState();
//check the ice state if this method is triggered consequently
if ( iceState == RTCIceConnectionState.closed ||
iceState == RTCIceConnectionState.disconnected ||
iceState == RTCIceConnectionState.failed ||
iceState == RTCIceConnectionState.new
)
{
//clean the connection
self.webRTCClientMap.removeValue(forKey: streamId)?.disconnect()
AntMediaClient.printf("Reconnecting to play the stream:\(streamId)");
self.play(streamId:streamId)
}
else {
AntMediaClient.printf("Not trying to reconnect to play the stream:\(streamId) because ice connection state is not disconnected");
}
}
if let streamId = self.p2pStreamId {
//if there is a webRTCClient in the map, it means it's disconnected due to network issue
if (self.webRTCClientMap[streamId] != nil) {
let iceState = self.webRTCClientMap[streamId]?.getIceConnectionState();
//check the ice state if this method is triggered consequently
if ( iceState == RTCIceConnectionState.closed ||
iceState == RTCIceConnectionState.disconnected ||
iceState == RTCIceConnectionState.failed
)
{
//clean the connection
self.webRTCClientMap.removeValue(forKey: streamId)?.disconnect()
AntMediaClient.printf("Reconnecting to join the stream:\(streamId) because ice connection state is not disconnected");
self.join(streamId:streamId)
}
}
}
}
}
private func onJoined() {
}
private func onTakeConfiguration(message: [String: Any], streamId:String) {
var rtcSessionDesc: RTCSessionDescription
let type = message["type"] as! String
let sdp = message["sdp"] as! String
if type == "offer" {
rtcSessionDesc = RTCSessionDescription.init(type: RTCSdpType.offer, sdp: sdp)
self.webRTCClientMap[streamId]?.setRemoteDescription(rtcSessionDesc, completionHandler: {
(error) in
if (error == nil) {
self.webRTCClientMap[streamId]?.sendAnswer()
}
else {
AntMediaClient.printf("Error (setRemoteDescription): " + error!.localizedDescription + " debug description: " + error.debugDescription)
}
})
} else if type == "answer" {
rtcSessionDesc = RTCSessionDescription.init(type: RTCSdpType.answer, sdp: sdp)
self.webRTCClientMap[streamId]?.setRemoteDescription(rtcSessionDesc, completionHandler: { (error ) in
})
}
}
private func onTakeCandidate(message: [String: Any], streamId:String) {
let mid = message["id"] as! String
let index = message["label"] as! Int
let sdp = message["candidate"] as! String
let candidate: RTCIceCandidate = RTCIceCandidate.init(sdp: sdp, sdpMLineIndex: Int32(index), sdpMid: mid)
self.webRTCClientMap[streamId]?.addCandidate(candidate)
}
private func onMessage(_ msg: String) {
if let message = msg.toJSON() {
guard let command = message[COMMAND] as? String else {
return
}
self.onCommand(command, message: message)
} else {
print("WebSocket message JSON parsing error: " + msg)
}
}
private func onCommand(_ command: String, message: [String: Any]) {
switch command {
case "start":
//if this is called, it's publisher or initiator in p2p
let streamId = message[STREAM_ID] as! String
self.webRTCClientMap[streamId]?.createOffer()
break
case "stop":
let streamId = message[STREAM_ID] as! String
AntMediaClient.dispatchQueue.async {
self.webRTCClientMap.removeValue(forKey: streamId)?.disconnect()
}
break
case "takeConfiguration":
let streamId = message[STREAM_ID] as! String
self.onTakeConfiguration(message: message, streamId: streamId)
break
case "takeCandidate":
let streamId = message[STREAM_ID] as! String
self.onTakeCandidate(message: message, streamId: streamId)
break
case STREAM_INFORMATION_COMMAND:
AntMediaClient.printf("stream information command")
var streamInformations: [StreamInformation] = [];
if let streamInformationArray = message["streamInfo"] as? [Any]
{
for result in streamInformationArray
{
if let resultObject = result as? [String:Any]
{
streamInformations.append(StreamInformation(json: resultObject))
}
}
}
self.delegate?.streamInformation(streamInfo: streamInformations);
break
case "notification":
guard let definition = message["definition"] as? String else {
return
}
if definition == "joined" {
AntMediaClient.printf("Joined: Let's go")
self.onJoined()
}
else if definition == "play_started" {
let streamId = message[STREAM_ID] as! String