-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathMeetingViewController.swift
More file actions
1037 lines (847 loc) · 43.9 KB
/
MeetingViewController.swift
File metadata and controls
1037 lines (847 loc) · 43.9 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
//
// ViewController.swift
// VideoSDKRTC_Example
//
// Created by Parth Asodariya on 11/01/23.
//
import UIKit
import VideoSDKRTC
import WebRTC
import AVFoundation
private let reuseIdentifier = "ParticipantViewCell"
private let addStreamOutputSegueIdentifier = "Add Livestream Outputs"
private let recordingWebhookUrl = "https://www.google.com"
private let CHAT_TOPIC = "CHAT"
private let RAISE_HAND_TOPIC = "RAISE_HAND"
class MeetingViewController: UIViewController, UNUserNotificationCenterDelegate {
@IBOutlet weak var viewRemoteMicContainer: UIView!
@IBOutlet weak var imgRemoteMicEnabled: UIImageView!
@IBOutlet weak var participantViewsContainer: UIView!
@IBOutlet weak var remoteParticipantNameContainer: UIView!
@IBOutlet weak var remoteParticipantVideoContainer: RTCMTLVideoView!
@IBOutlet weak var remoteParticipantInnerNameView: UIView!
@IBOutlet weak var lblRemoteParticipantName: UILabel!
@IBOutlet weak var localParticipantViewContainer: UIView!
@IBOutlet weak var localParticipantViewNameContainer: UIView!
@IBOutlet weak var localParticipantViewVideoContainer: RTCMTLVideoView!
@IBOutlet weak var localScreenSharedView: UIView!
@IBOutlet weak var StopPresenting: UIButton!
@IBOutlet weak var ivIsRecording: UIImageView!
@IBOutlet weak var buttonsView: UIView!
@IBOutlet weak var btnCopyMeetingId: UIButton!
@IBOutlet weak var viewCopyMeetingContainer: UIView!
@IBOutlet weak var btnRotateCamera: UIButton!
@IBOutlet weak var lblMeetingId: UILabel!
@IBAction func StopPresentingTapped(_ sender: Any) {
Task {
await self.meeting?.disableScreenShare()
}
}
// MARK: - Properties
/// View for handling meeting controls consists of Mic, Video, and End buttons
lazy var buttonControlsView: ButtonControlsView! = {
Bundle.main.loadNibNamed("ButtonControlsView", owner: self, options: nil)?[0] as! ButtonControlsView
}()
/// Meeting data - required to start
var meetingData: MeetingData!
/// current meeting reference
private var meeting: Meeting?
/// keep track of participant indexPath for reference
private var indexPaths: [String : IndexPath] = [:]
/// video participants including self to show in Grid
private var participants: [Participant] = []
/// keep track of recording
private var recordingStarted = false
/// keep track of livestream
private var liveStreamStarted = false
/// Camera position
private var cameraPosition = CameraPosition.front
private var isCameraOn = true
private var isMicToggling = false
private var isVideoToggling = false
/// Notification center for sending and authorize notification
var userNotificationCenter = UNUserNotificationCenter.current()
// MARK: - Life Cycle
override var prefersStatusBarHidden: Bool { true }
var participantIsSharingScreen: Bool = false
var valueOfVideoDevice: String?
var valueOfAudioDevice: String?
override func viewDidLoad() {
super.viewDidLoad()
Utils.loaderShow(viewControler: self)
prepareUI()
setupActions()
// addAudioChangeObserver()
// Log verbosity level
VideoSDK.setLogLevel(level: .all) // Default: .info
// config
VideoSDK.config(token: meetingData.token)
// init meeting
initializeMeeting()
// set meeting id in button text
lblMeetingId.text = "\(meetingData.meetingId)"
// setting up notification for viewcontroller to check, it going to background or not
NotificationCenter.default.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil)
// Assigning self delegate on userNotificationCenter
self.userNotificationCenter.delegate = self
// requesting authorization to send the local notification
// self.requestNotificationAuthorization()
}
// method called once app state changes to background
@objc func appMovedToBackground() {
self.sendNotification()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.isHidden = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.navigationBar.isHidden = false
NotificationCenter.default.removeObserver(self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
guard let navigationController = segue.destination as? UINavigationController,
let addStreamsController = navigationController.viewControllers.first as? AddStreamOutputiewController
else { return }
addStreamsController.onStart = { streamOutputs in
if !streamOutputs.isEmpty {
self.meeting?.startLivestream(outputs: streamOutputs)
} else {
self.showAlert(title: "Error", message: "Add stream outputs to start livestream.")
}
}
}
func prepareUI() {
buttonsView.addSubview(buttonControlsView)
buttonControlsView.frame = buttonsView.bounds
[remoteParticipantNameContainer, remoteParticipantVideoContainer, localScreenSharedView].forEach {
$0?.frame = CGRect(x: 0, y: 0, width: participantViewsContainer.frame.width, height: participantViewsContainer.frame.height)
$0?.bounds = CGRect(x: 0, y: 0, width: participantViewsContainer.frame.width, height: participantViewsContainer.frame.height)
$0?.clipsToBounds = true
}
[localParticipantViewVideoContainer, localParticipantViewNameContainer].forEach {
$0?.frame = CGRect(x: 10, y: 0, width: localParticipantViewContainer.frame.width, height: localParticipantViewContainer.frame.height)
$0?.bounds = CGRect(x: 10, y: 0, width: localParticipantViewContainer.frame.width, height: localParticipantViewContainer.frame.height)
$0?.clipsToBounds = true
}
[localParticipantViewVideoContainer, remoteParticipantVideoContainer].forEach {
$0?.videoContentMode = .scaleAspectFill
}
[participantViewsContainer, remoteParticipantNameContainer, remoteParticipantVideoContainer, remoteParticipantInnerNameView, viewRemoteMicContainer, localScreenSharedView].forEach {
$0.roundCorners(corners: [.allCorners], radius: 12.0)
}
[localParticipantViewContainer, localParticipantViewNameContainer, localParticipantViewVideoContainer, remoteParticipantInnerNameView].forEach {
$0.roundCorners(corners: [.allCorners], radius: 8.0)
}
ivIsRecording.isHidden = true
localParticipantViewVideoContainer.isHidden = false
remoteParticipantVideoContainer.isHidden = false
localScreenSharedView.isHidden = true
}
// MARK: - Meeting
func initializeMeeting() {
guard let videoDevice = meetingData?.videoDevice else { return }
let facingMode = getSelectedCameraPosition(for: videoDevice)
// Create the custom video track using the selected camera
guard let customVideoStream = try? VideoSDK.createCameraVideoTrack(
encoderConfig: .h360p_w640p,
facingMode: facingMode,
multiStream: true,
bitrateMode: .BANDWIDTH_OPTIMIZED,
maxLayer: .MAX_LAYER_2
) else {
print("Failed to create custom video stream")
return
}
// Initialize the meeting with the custom video stream
meeting = VideoSDK.initMeeting(
meetingId: meetingData.meetingId,
participantName: meetingData.name,
micEnabled: meetingData.micEnabled,
webcamEnabled: meetingData.cameraEnabled,
customCameraVideoStream: customVideoStream
)
// Add event listeners and join the meeting
meeting?.addEventListener(self)
meeting?.join()
}
private func getSelectedCameraPosition(for device: String) -> AVCaptureDevice.Position {
switch device {
case "Front Camera":
return .front
case "Back Camera":
return .back
default:
return .front
}
}
@IBAction func btnRotateCameraTapped(_ sender: Any) {
if isCameraOn {
self.meeting?.switchWebcam()
} else {
self.showToast(message: "Camera is off", font: .boldSystemFont(ofSize: 12))
}
}
@IBAction func btnCopyMeetingIdTapped(_ sender: Any) {
guard let meetingId = lblMeetingId.text, !meetingId.isEmpty else { return }
let meetingLink = "\(meetingId)"
UIPasteboard.general.string = meetingLink
self.showAlert(title: "MeetingId Copied", message: nil, autoDismiss: true)
}
func audioSetupForPrecall() {
if let audio = meetingData?.audioDevice {
meeting?.changeMic(selectedDevice: audio)
}
}
}
// MARK: - MeetingEventListener
extension MeetingViewController: MeetingEventListener {
func onQualityLimitation(type: VideoSDKRTC.QualityLimitationType, state: VideoSDKRTC.QualityLimitationState, timestamp: Int) {
}
/// Meeting started
func onMeetingJoined() {
guard let localParticipant = self.meeting?.localParticipant else { return }
if participants.count < 2 {
// add to list
participants.append(localParticipant)
setNameToView(localParticipant)
// add event listener
localParticipant.addEventListener(self)
do {
try localParticipant.setQuality(.high)
} catch {
print("Error: \(error)")
}
Task{// listen/subscribe for chat topic
await meeting?.pubsub.subscribe(topic: CHAT_TOPIC, forListener: self)
await meeting?.pubsub.subscribe(topic: RAISE_HAND_TOPIC, forListener: self)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.audioSetupForPrecall()
}
} else {
//Navigate to error screen
}
DispatchQueue.main.async {
Utils.loaderDismiss(viewControler: self)
}
}
/// Meeting ended
func onMeetingLeft() {
// remove listeners
meeting?.localParticipant.removeEventListener(self)
meeting?.removeEventListener(self)
participants.removeAll()
// dismiss controller
Utils.loaderDismiss(viewControler: self)
// Navigate back to previous view
DispatchQueue.main.async {
// If presented modally
if self.presentingViewController != nil {
self.dismiss(animated: true)
}
}
}
func onMeetingLeft(reason: LeaveReason) {
print("Meeting left with reason: \(reason.message)")
self.onMeetingLeft()
}
/// A new participant joined
func onParticipantJoined(_ participant: Participant) {
if participants.count < 2 {
// add new participant to list
participants.append(participant)
// add listener
participant.addEventListener(self)
do {
try participant.setQuality(.high)
} catch {
print("Error: \(error)")
}
self.setNameToView(participant)
} else {
//Navigate to Error Screen
}
//notification to participants via sharing participants
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "shareParticipants"), object: nil, userInfo: ["participants": participants])
}
/// A participant left from the meeting
/// - Parameter participant: participant object
func onParticipantLeft(_ participant: Participant) {
// remove listener
participant.removeEventListener(self)
// find participant
guard let index = self.participants.firstIndex(where: { $0.id == participant.id }) else {
return
}
// remove participant from list
participants.remove(at: index)
// hide from ui
removeParticipantFromGridView(participant)
//notification to participants via sharing participants
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "shareParticipants"), object: nil, userInfo: ["participants": participants])
}
func onParticipantLeft(_ participant: Participant, reason: LeaveReason) {
print("Participant \(participant.displayName) left with reason: \(reason.message)")
self.onParticipantLeft(participant)
}
/// Called after recording starts
func onRecordingStarted() {
self.recordingStarted = true
self.ivIsRecording.isHidden = false
updateMenuButton()
showAlert(title: "Recording Started", message: nil, autoDismiss: true)
}
/// Caled after recording stops
func onRecordingStopped() {
self.ivIsRecording.isHidden = true
recordingStarted = false
updateMenuButton()
}
/// Called after livestream starts
func onLivestreamStarted() {
liveStreamStarted = true
updateMenuButton()
showAlert(title: "Livestream Started", message: nil, autoDismiss: true)
}
/// Called after livestream stops
func onLivestreamStopped() {
print("livestream stopped")
liveStreamStarted = false
updateMenuButton()
}
/// Called when speaker is changed
/// - Parameter participantId: participant id of the speaker, nil when no one is speaking.
func onSpeakerChanged(participantId: String?) {
// show indication for active speaker
if let participant = participants.first(where: { $0.id == participantId }), participants.count > 1 {
showActiveSpeakerIndicator(participant.isLocal ? localParticipantViewContainer : participantViewsContainer, true)
} else if let participant = participants.first(where: { $0.id == participantId }), participant.isLocal{
showActiveSpeakerIndicator(participantViewsContainer, true)
}
// hide indication for others participants
let otherParticipants = participants.filter { $0.id != participantId }
for participant in otherParticipants {
if participants.count > 1 && participant.isLocal {
showActiveSpeakerIndicator(localParticipantViewContainer, false)
} else {
showActiveSpeakerIndicator(participantViewsContainer, false)
}
}
}
/// Called when host requests to turn on the mic/audio
func onMicRequested(participantId: String?, accept: @escaping () -> Void, reject: @escaping () -> Void) {
let requesterName = participants.first(where: { $0.id == participantId })?.displayName ?? "Meeting host"
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
reject()
}
let confirmAction = UIAlertAction(title: "Confirm", style: .default) { _ in
accept()
}
showAlert(
title: "Turn On Mic?",
message: "\(requesterName) has requested to turn on the mic.",
actions: [cancelAction, confirmAction])
}
/// Called when host requests to turn on the camera/video
func onWebcamRequested(participantId: String?, accept: @escaping () -> Void, reject: @escaping () -> Void) {
let requesterName = participants.first(where: { $0.id == participantId })?.displayName ?? "Meeting host"
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
reject()
}
let confirmAction = UIAlertAction(title: "Confirm", style: .default) { _ in
accept()
}
showAlert(
title: "Turn On Camera?",
message: "\(requesterName) has requested to turn on the camera.",
actions: [cancelAction, confirmAction])
}
func showActiveSpeakerIndicator(_ view: UIView, _ show: Bool) {
// border
view.layer.borderWidth = 4.0
view.layer.borderColor = show ? UIColor.blue.cgColor : UIColor.clear.cgColor
}
func onQualityLimitation(type: QualityLimitationType, state: QualityLimitationState, timestamp: String) {
print("type: \(type.rawValue) || state: \(state.rawValue) || timestamp: \(timestamp)")
}
}
// MARK: - ParticipantEventListener
extension MeetingViewController: ParticipantEventListener {
/// Participant has enabled mic, video or screenshare
/// - Parameters:
/// - stream: enabled stream object
/// - participant: participant object
func onStreamEnabled(_ stream: MediaStream, forParticipant participant: Participant) {
// if stream.kind == .share && participant.isLocal {
//
// showLocalScreenShareView(stream: stream)
// return
// }
// else if stream.kind == .share && !participant.isLocal {
// showRemoteScreenShare(stream: stream)
// return
// }
Utils.loaderDismiss(viewControler: self)
updateView(participant: participant, forStream: stream, enabled: true)
if participant.isLocal {
// turn on controls for local participant
self.buttonControlsView.updateButtons(forStream: stream, enabled: true)
}
//notification to participants via sharing participants
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "shareParticipants"), object: nil, userInfo: ["participants": self.participants])
}
/// Participant has disabled mic, video or screenshare
/// - Parameters:
/// - stream: disabled stream object
/// - participant: participant object
func onStreamDisabled(_ stream: MediaStream, forParticipant participant: Participant) {
// if stream.kind == .share && participant.isLocal {
// removeLocalScreenShareView(stream: stream)
// return
// }
// else if stream.kind == .share && !participant.isLocal {
// removeRemoteScreenShare(stream: stream)
// return
// }
updateView(participant: participant, forStream: stream, enabled: false)
if participant.isLocal {
// turn off controls for local participant
self.buttonControlsView.updateButtons(forStream: stream, enabled: false)
}
//notification to participants via sharing participants
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "shareParticipants"), object: nil, userInfo: ["participants": self.participants])
}
}
// MARK: - PubSubMessageListener
extension MeetingViewController: PubSubMessageListener {
func onMessageReceived(_ message: PubSubMessage) {
let localParticipantID = participants.first(where: { $0.isLocal == true })?.id
if(message.topic == RAISE_HAND_TOPIC){
self.showToast(message: "\(message.senderId == localParticipantID ? "You" : "\(message.senderName)") raised hand 🖐🏼", font: .systemFont(ofSize: 18))
} else {
if let chatViewController = navigationController?.topViewController as? ChatViewController {
chatViewController.showNewMessage(message)
} else {
if message.senderId != localParticipantID {
self.showToast(message: "\(message.senderName) says: \(message.message)", font: .systemFont(ofSize: 18))
}
}
}
}
}
// MARK: - Actions
private extension MeetingViewController {
func setupActions() {
// onMicTapped
buttonControlsView.onMicTapped = { on in
guard !self.isMicToggling else { return }
self.isMicToggling = true
Task {
if !on {
self.meeting?.unmuteMic()
} else {
self.meeting?.muteMic()
}
}
// Reset flag after delay
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
self.isMicToggling = false
}
}
// onVideoTapped
buttonControlsView.onVideoTapped = { on in
guard !self.isVideoToggling else { return }
self.isVideoToggling = true
Task {
if !on {
guard let customVideoStream = try? VideoSDK.createCameraVideoTrack(encoderConfig: .h720p_w1280p, facingMode: .front, multiStream: true) else { return }
self.meeting?.enableWebcam(customVideoStream: customVideoStream)
self.isCameraOn = true
} else {
self.meeting?.disableWebcam()
self.isCameraOn = false
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
self.isVideoToggling = false
}
}
// onEndMeetingTapped
buttonControlsView.onEndMeetingTapped = {
let menuOptions: [MenuOption] = [.leaveMeeting, .endMeeting]
self.showActionsheet(options: menuOptions, fromView: self.buttonControlsView.leaveMeetingButton) { option in
switch option {
case .leaveMeeting:
self.meeting?.leave()
case .endMeeting:
self.meeting?.end()
default:
break
}
}
}
/// Chat Button Tap
buttonControlsView.onChatButtonTapped = {
self.openChat()
}
/// Menu tap
buttonControlsView.onMenuButtonTapped = {
var menuOptions: [MenuOption] = []
menuOptions.append(.showParticipantList)
menuOptions.append(.raiseHand)
menuOptions.append(.switchAudioOutput)
menuOptions.append(!self.recordingStarted ? .startRecording : .stopRecording)
// menuOptions.append(!self.liveStreamStarted ? .startLivestream : .stopLivestream)
menuOptions.append(.startScreenShare)
menuOptions.append(.stopScreenShare)
self.showActionsheet(options: menuOptions, fromView: self.buttonControlsView.btnMoreOptions) { option in
switch option {
case .startRecording:
self.meeting?.startRecording(webhookUrl: "")
case .stopRecording:
self.meeting?.stopRecording()
// case .startLivestream:
// self.performSegue(withIdentifier: addStreamOutputSegueIdentifier, sender: nil)
//
// case .stopLivestream:
// self.stopLivestream()
case .switchAudioOutput:
self.changeAudioOutput(presenterViewController: self)
case .showParticipantList:
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let participantsViewController = storyBoard.instantiateViewController(withIdentifier: "ParticipantsViewController") as! ParticipantsViewController
participantsViewController.participants = self.participants
self.present(participantsViewController, animated: true, completion: nil)
case .raiseHand:
Task {
try await self.meeting?.pubsub.publish(topic: RAISE_HAND_TOPIC, message: "Raise Hand by Me", options: [:], payload: ["generated_by": "Application"])
}
case .startScreenShare:
Task {
await self.meeting?.enableScreenShare()
}
case .stopScreenShare:
Task {
await self.meeting?.disableScreenShare()
}
default:
break
}
}
}
}
func stopRecording() {
meeting?.stopRecording()
}
func stopLivestream() {
meeting?.stopLivestream()
}
}
// MARK: - Chat
extension MeetingViewController {
func openChat() {
let chatViewController = ChatViewController(meeting: meeting!, topic: CHAT_TOPIC)
navigationController?.pushViewController(chatViewController, animated: true)
}
}
// MARK: - Helpers
private extension MeetingViewController {
func addAudioChangeObserver() {
// change audio output to louder speaker
NotificationCenter.default.addObserver(forName: AVAudioSession.routeChangeNotification, object: nil, queue: nil) { notification in
guard let info = notification.userInfo,
let value = info[AVAudioSessionRouteChangeReasonKey] as? UInt,
let reason = AVAudioSession.RouteChangeReason(rawValue: value) else { return }
switch reason {
case .categoryChange: try? AVAudioSession.sharedInstance().overrideOutputAudioPort(.speaker)
default: break
}
}
}
func updateMenuButton() {
// show enabled when recording or livestream enabled
buttonControlsView.menuButtonEnabled = (recordingStarted || liveStreamStarted)
}
/// Set the name of the participant to name view
func setNameToView(_ participant: Participant){
let nameComponents = participant.displayName.components(separatedBy: " ")
self.lblRemoteParticipantName.text = nameComponents
.reduce("") {
($0.isEmpty ? "" : "\($0.first?.uppercased() ?? "")") +
($1.isEmpty ? "" : "\($1.first?.uppercased() ?? "")")
}
self.remoteParticipantInnerNameView.roundCorners(corners: .allCorners, radius: 20.0)
}
func updateView(participant: Participant, forStream stream: MediaStream, enabled: Bool) { // true
switch stream.kind {
case .state(value: .video):
if let videotrack = stream.track as? RTCVideoTrack {
if enabled {
showVideoView(participant: participant, stream: videotrack) // show video
} else {
hideVideoView(participant: participant, stream: videotrack) // hide video
}
}
case .state(value: .audio):
updateMic(participant: participant, enabled)
case .share:
if let shareTrack = stream.track as? RTCVideoTrack {
DispatchQueue.main.async {
UIView.animate(withDuration: 0.5){
if enabled {
if participant.isLocal {
self.localScreenSharedView.isHidden = false
}
if let videoStream = self.participants.first(where: {$0.id == participant.id})?.streams.first(where: { $1.kind == .state(value: .video) })?.value.track as? RTCVideoTrack {
videoStream.remove(self.remoteParticipantVideoContainer)
shareTrack.add(self.remoteParticipantVideoContainer)
if participant.isLocal {
self.remoteParticipantVideoContainer.isHidden = true
} else {
self.remoteParticipantVideoContainer.isHidden = false
}
self.remoteParticipantVideoContainer.videoContentMode = .scaleAspectFit
self.remoteParticipantNameContainer.isHidden = true
if let localVideoStream = self.participants.first(where: { $0.isLocal })?.streams.first(where: { $1.kind == .state(value: .video)})?.value.track as? RTCVideoTrack {
localVideoStream.remove(self.localParticipantViewVideoContainer)
// videoStream.add(self.localParticipantViewVideoContainer)
self.localParticipantViewVideoContainer.isHidden = true
self.localParticipantViewNameContainer.isHidden = true
self.localParticipantViewContainer.isHidden = true
}
} else {
shareTrack.add(self.remoteParticipantVideoContainer)
self.remoteParticipantVideoContainer.videoContentMode = .scaleAspectFit
if participant.isLocal {
self.remoteParticipantVideoContainer.isHidden = true
self.remoteParticipantNameContainer.isHidden = true
} else {
self.remoteParticipantVideoContainer.isHidden = false
self.remoteParticipantNameContainer.isHidden = false
}
// self.remoteParticipantVideoContainer.isHidden = false
if let localVideoStream = self.participants.first(where: { $0.isLocal })?.streams.first(where: { $1.kind == .state(value: .video)})?.value.track as? RTCVideoTrack {
localVideoStream.remove(self.localParticipantViewVideoContainer)
}
self.localParticipantViewVideoContainer.isHidden = true
self.localParticipantViewNameContainer.isHidden = true
self.localParticipantViewContainer.isHidden = true
}
} else {
if participant.isLocal {
self.localScreenSharedView.isHidden = true
}
if self.participants.count > 1 {
shareTrack.remove(self.remoteParticipantVideoContainer)
if let videoStream = self.participants.first(where: {!$0.isLocal})?.streams.first(where: { $1.kind == .state(value: .video) })?.value.track as? RTCVideoTrack {
// videoStream.remove(self.localParticipantViewVideoContainer)
videoStream.add(self.remoteParticipantVideoContainer)
self.remoteParticipantVideoContainer.videoContentMode = .scaleAspectFill
self.remoteParticipantVideoContainer.isHidden = false
self.remoteParticipantNameContainer.isHidden = true
} else {
self.remoteParticipantVideoContainer.isHidden = true
self.remoteParticipantNameContainer.isHidden = false
}
if let localVideoStream = self.participants.first(where: { $0.isLocal })?.streams.first(where: { $1.kind == .state(value: .video)})?.value.track as? RTCVideoTrack {
localVideoStream.add(self.localParticipantViewVideoContainer)
self.localParticipantViewContainer.isHidden = false
self.localParticipantViewVideoContainer.isHidden = false
self.localParticipantViewNameContainer.isHidden = true
}
} else {
if let localVideoStream = self.participants.first(where: { $0.isLocal })?.streams.first(where: { $1.kind == .state(value: .video)})?.value.track as? RTCVideoTrack {
localVideoStream.add(self.remoteParticipantVideoContainer)
self.remoteParticipantVideoContainer.isHidden = false
self.remoteParticipantNameContainer.isHidden = true
self.localParticipantViewVideoContainer.isHidden = true
self.localParticipantViewNameContainer.isHidden = false
}
}
//
}
}
}
}
default:
break
}
}
func showVideoView(participant: Participant, stream: RTCVideoTrack){
DispatchQueue.main.async {
UIView.animate(withDuration: 0.5){
if self.participants.count > 1 {
if let currentVideoTrack = self.participants.first(where: { $0.isLocal })?.streams.first(where: {$1.kind == .state(value: .video)})?.value.track as? RTCVideoTrack {
currentVideoTrack.remove(self.remoteParticipantVideoContainer)
currentVideoTrack.remove(self.localParticipantViewVideoContainer)
}
let hasShareStream = self.participants.first(where: { !$0.isLocal })?.streams.contains(where: {$1.kind == .share})
if hasShareStream ?? false {
if let currentVideoTrack = self.participants.first(where: { !$0.isLocal })?.streams.first(where: {$1.kind == .state(value: .video)})?.value.track as? RTCVideoTrack {
currentVideoTrack.add(self.localParticipantViewVideoContainer)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
self.localParticipantViewVideoContainer.isHidden = false
self.localParticipantViewNameContainer.isHidden = true
}
}
} else {
stream.add(participant.isLocal ? self.localParticipantViewVideoContainer : self.remoteParticipantVideoContainer)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
if participant.isLocal {
self.localParticipantViewVideoContainer.isHidden = false
self.localParticipantViewNameContainer.isHidden = true
self.localParticipantViewContainer.isHidden = false
} else {
self.remoteParticipantVideoContainer.isHidden = false
self.remoteParticipantNameContainer.isHidden = true
}
}
if let localParticipantVideoStream = self.participants.first(where: { $0.isLocal })?.streams.first(where: {$1.kind == .state(value: .video )})?.value.track as? RTCVideoTrack {
localParticipantVideoStream.add(self.localParticipantViewVideoContainer)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
self.localParticipantViewVideoContainer.isHidden = false
self.localParticipantViewNameContainer.isHidden = true
self.localParticipantViewContainer.isHidden = false
}
}
}
} else {
DispatchQueue.main.async {
stream.add(self.remoteParticipantVideoContainer)
self.remoteParticipantVideoContainer.videoContentMode = .scaleAspectFit
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
self.remoteParticipantVideoContainer.isHidden = false
self.remoteParticipantNameContainer.isHidden = true
}
}
}
}
}
}
func hideVideoView(participant: Participant, stream: RTCVideoTrack){
UIView.animate(withDuration: 0.5){
if self.participants.count > 1 {
let hasShareStream = self.participants.first(where: { !$0.isLocal })?.streams.contains(where: {$1.kind == .share})
if hasShareStream ?? false {
if !participant.isLocal {
if let currentVideoTrack = self.participants.first(where: { !$0.isLocal })?.streams.first(where: {$1.kind == .state(value: .video)})?.value.track as? RTCVideoTrack {
currentVideoTrack.remove(self.localParticipantViewVideoContainer)
self.localParticipantViewVideoContainer.isHidden = true
self.localParticipantViewNameContainer.isHidden = false
} else {
self.localParticipantViewVideoContainer.isHidden = true
self.localParticipantViewNameContainer.isHidden = false
}
}
} else {
stream.remove(participant.isLocal ? self.localParticipantViewVideoContainer : self.remoteParticipantVideoContainer)
if participant.isLocal {
self.localParticipantViewVideoContainer.videoContentMode = .scaleAspectFit
self.localParticipantViewVideoContainer.isHidden = true
self.localParticipantViewNameContainer.isHidden = false
} else {
self.remoteParticipantVideoContainer.isHidden = true
self.remoteParticipantNameContainer.isHidden = false
}
}
} else {
stream.remove(self.remoteParticipantVideoContainer)
self.remoteParticipantVideoContainer.isHidden = true
self.remoteParticipantNameContainer.isHidden = false
}
}
}
func updateMic(participant: Participant, _ enabled: Bool) {
if !participant.isLocal {
participantViewsContainer.bringSubviewToFront(viewRemoteMicContainer)
viewRemoteMicContainer.isHidden = enabled
} else if participants.count == 1 {
participantViewsContainer.bringSubviewToFront(viewRemoteMicContainer)
viewRemoteMicContainer.isHidden = enabled
}
}
func removeParticipantFromGridView(_ participant: Participant) {
UIView.animate(withDuration: 0.5){
if !participant.isLocal {
self.localParticipantViewVideoContainer.isHidden = true
self.localParticipantViewNameContainer.isHidden = true
self.localParticipantViewContainer.isHidden = true
self.remoteParticipantVideoContainer.videoContentMode = .scaleAspectFit
// other remote participant
if let remoteParticipant = self.participants.first(where: { $0.id != participant.id }) {
// find videostream of remote participant
if let videoStream = remoteParticipant.streams.first(where: { $1.kind == .state(value: .video) })?.value.track as? RTCVideoTrack {
// added remote video stream to remote participant video container
videoStream.add(self.remoteParticipantVideoContainer)
// hide remote name container
self.remoteParticipantNameContainer.isHidden = true
// set remained participant name
self.setNameToView(remoteParticipant)
// show remote video container
self.remoteParticipantVideoContainer.isHidden = false
// show remote participant main container
self.participantViewsContainer.isHidden = false
} else {
// show remote name container
self.remoteParticipantNameContainer.isHidden = false
// set remained participant name
self.setNameToView(remoteParticipant)
// hide remote video container
self.remoteParticipantVideoContainer.isHidden = true
// show remote participant main container
self.participantViewsContainer.isHidden = false
}
}
}
}
}
}
// MARK: - Notification Center Methods
extension MeetingViewController {
func requestNotificationAuthorization() {
self.userNotificationCenter.requestAuthorization(options: UNAuthorizationOptions.init(arrayLiteral: .alert, .badge, .sound)) { (success, error) in
if let error = error {
print("requestAuthorization error: ", error)
}
}
}
func sendNotification() {
let notificationContent = UNMutableNotificationContent()
notificationContent.title = "Your application is in background"
notificationContent.body = "This may cause you to leave the meeting automatically"
notificationContent.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1,
repeats: false)
let request = UNNotificationRequest(identifier: "backgroundNotification",
content: notificationContent,
trigger: trigger)