-
Notifications
You must be signed in to change notification settings - Fork 412
/
Copy pathCustomTwilioVideoView.java
1072 lines (906 loc) · 43.3 KB
/
CustomTwilioVideoView.java
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
/**
* Component to orchestrate the Twilio Video connection and the various video
* views.
* <p>
* Authors:
* Ralph Pina <[email protected]>
* Jonathan Chang <[email protected]>
*/
package com.twiliorn.library;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.annotation.StringDef;
import android.util.Log;
import android.view.View;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import com.twilio.video.AudioTrackPublication;
import com.twilio.video.BaseTrackStats;
import com.twilio.video.CameraCapturer;
import com.twilio.video.ConnectOptions;
import com.twilio.video.LocalAudioTrack;
import com.twilio.video.LocalAudioTrackStats;
import com.twilio.video.LocalParticipant;
import com.twilio.video.LocalTrackStats;
import com.twilio.video.LocalVideoTrack;
import com.twilio.video.LocalVideoTrackStats;
import com.twilio.video.Participant;
import com.twilio.video.RemoteAudioTrack;
import com.twilio.video.RemoteAudioTrackPublication;
import com.twilio.video.RemoteAudioTrackStats;
import com.twilio.video.LocalDataTrack;
import com.twilio.video.RemoteDataTrack;
import com.twilio.video.RemoteDataTrackPublication;
import com.twilio.video.RemoteParticipant;
import com.twilio.video.RemoteTrackStats;
import com.twilio.video.RemoteVideoTrack;
import com.twilio.video.RemoteVideoTrackPublication;
import com.twilio.video.RemoteVideoTrackStats;
import com.twilio.video.Room;
import com.twilio.video.Room.State;
import com.twilio.video.StatsListener;
import com.twilio.video.StatsReport;
import com.twilio.video.TrackPublication;
import com.twilio.video.TwilioException;
import com.twilio.video.Video;
import com.twilio.video.VideoConstraints;
import com.twilio.video.VideoDimensions;
import org.webrtc.voiceengine.WebRtcAudioManager;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collections;
import java.util.List;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_AUDIO_CHANGED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_CAMERA_SWITCHED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_CONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_CONNECT_FAILURE;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_DISCONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_DATATRACK_MESSAGE_RECEIVED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ADDED_DATA_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ADDED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ADDED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_CONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_DISABLED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_DISABLED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_DISCONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ENABLED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ENABLED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_REMOVED_DATA_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_REMOVED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_REMOVED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_STATS_RECEIVED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_VIDEO_CHANGED;
public class CustomTwilioVideoView extends View implements LifecycleEventListener, AudioManager.OnAudioFocusChangeListener {
private static final String TAG = "CustomTwilioVideoView";
private static final String DATA_TRACK_MESSAGE_THREAD_NAME = "DataTrackMessages";
private boolean enableRemoteAudio = false;
@Retention(RetentionPolicy.SOURCE)
@StringDef({Events.ON_CAMERA_SWITCHED,
Events.ON_VIDEO_CHANGED,
Events.ON_AUDIO_CHANGED,
Events.ON_CONNECTED,
Events.ON_CONNECT_FAILURE,
Events.ON_DISCONNECTED,
Events.ON_PARTICIPANT_CONNECTED,
Events.ON_PARTICIPANT_DISCONNECTED,
Events.ON_PARTICIPANT_ADDED_VIDEO_TRACK,
Events.ON_DATATRACK_MESSAGE_RECEIVED,
Events.ON_PARTICIPANT_ADDED_DATA_TRACK,
Events.ON_PARTICIPANT_REMOVED_DATA_TRACK,
Events.ON_PARTICIPANT_REMOVED_VIDEO_TRACK,
Events.ON_PARTICIPANT_ADDED_AUDIO_TRACK,
Events.ON_PARTICIPANT_REMOVED_AUDIO_TRACK,
Events.ON_PARTICIPANT_ENABLED_VIDEO_TRACK,
Events.ON_PARTICIPANT_DISABLED_VIDEO_TRACK,
Events.ON_PARTICIPANT_ENABLED_AUDIO_TRACK,
Events.ON_PARTICIPANT_DISABLED_AUDIO_TRACK,
Events.ON_STATS_RECEIVED})
public @interface Events {
String ON_CAMERA_SWITCHED = "onCameraSwitched";
String ON_VIDEO_CHANGED = "onVideoChanged";
String ON_AUDIO_CHANGED = "onAudioChanged";
String ON_CONNECTED = "onRoomDidConnect";
String ON_CONNECT_FAILURE = "onRoomDidFailToConnect";
String ON_DISCONNECTED = "onRoomDidDisconnect";
String ON_PARTICIPANT_CONNECTED = "onRoomParticipantDidConnect";
String ON_PARTICIPANT_DISCONNECTED = "onRoomParticipantDidDisconnect";
String ON_DATATRACK_MESSAGE_RECEIVED = "onDataTrackMessageReceived";
String ON_PARTICIPANT_ADDED_DATA_TRACK = "onParticipantAddedDataTrack";
String ON_PARTICIPANT_REMOVED_DATA_TRACK = "onParticipantRemovedDataTrack";
String ON_PARTICIPANT_ADDED_VIDEO_TRACK = "onParticipantAddedVideoTrack";
String ON_PARTICIPANT_REMOVED_VIDEO_TRACK = "onParticipantRemovedVideoTrack";
String ON_PARTICIPANT_ADDED_AUDIO_TRACK = "onParticipantAddedAudioTrack";
String ON_PARTICIPANT_REMOVED_AUDIO_TRACK = "onParticipantRemovedAudioTrack";
String ON_PARTICIPANT_ENABLED_VIDEO_TRACK = "onParticipantEnabledVideoTrack";
String ON_PARTICIPANT_DISABLED_VIDEO_TRACK = "onParticipantDisabledVideoTrack";
String ON_PARTICIPANT_ENABLED_AUDIO_TRACK = "onParticipantEnabledAudioTrack";
String ON_PARTICIPANT_DISABLED_AUDIO_TRACK = "onParticipantDisabledAudioTrack";
String ON_STATS_RECEIVED = "onStatsReceived";
}
private final ThemedReactContext themedReactContext;
private final RCTEventEmitter eventEmitter;
private AudioFocusRequest audioFocusRequest;
private AudioAttributes playbackAttributes;
private Handler handler = new Handler();
/*
* A Room represents communication between the client and one or more participants.
*/
private static Room room;
private String roomName = null;
private String accessToken = null;
private LocalParticipant localParticipant;
/*
* A VideoView receives frames from a local or remote video track and renders them
* to an associated view.
*/
private static PatchedVideoView thumbnailVideoView;
private static LocalVideoTrack localVideoTrack;
private boolean isLocalVideoPublished = false;
private static CameraCapturer cameraCapturer;
private LocalAudioTrack localAudioTrack;
private AudioManager audioManager;
private int previousAudioMode;
private boolean disconnectedFromOnDestroy;
private IntentFilter intentFilter;
private BecomingNoisyReceiver myNoisyAudioStreamReceiver;
// Dedicated thread and handler for messages received from a RemoteDataTrack
private final HandlerThread dataTrackMessageThread =
new HandlerThread(DATA_TRACK_MESSAGE_THREAD_NAME);
private Handler dataTrackMessageThreadHandler;
private LocalDataTrack localDataTrack;
// Map used to map remote data tracks to remote participants
private final Map<RemoteDataTrack, RemoteParticipant> dataTrackRemoteParticipantMap =
new HashMap<>();
public CustomTwilioVideoView(ThemedReactContext context) {
super(context);
this.themedReactContext = context;
this.eventEmitter = themedReactContext.getJSModule(RCTEventEmitter.class);
// add lifecycle for onResume and on onPause
themedReactContext.addLifecycleEventListener(this);
/*
* Enable changing the volume using the up/down keys during a conversation
*/
if (themedReactContext.getCurrentActivity() != null) {
themedReactContext.getCurrentActivity().setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
}
/*
* Needed for setting/abandoning audio focus during call
*/
audioManager = (AudioManager) themedReactContext.getSystemService(Context.AUDIO_SERVICE);
myNoisyAudioStreamReceiver = new BecomingNoisyReceiver();
intentFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
// Create the local data track
// localDataTrack = LocalDataTrack.create(this);
localDataTrack = LocalDataTrack.create(getContext());
// Start the thread where data messages are received
dataTrackMessageThread.start();
dataTrackMessageThreadHandler = new Handler(dataTrackMessageThread.getLooper());
}
// ===== SETUP =================================================================================
private VideoConstraints buildVideoConstraints() {
return new VideoConstraints.Builder()
.minVideoDimensions(VideoDimensions.CIF_VIDEO_DIMENSIONS)
.maxVideoDimensions(VideoDimensions.CIF_VIDEO_DIMENSIONS)
.minFps(5)
.maxFps(15)
.build();
}
private CameraCapturer createCameraCaputer(Context context, CameraCapturer.CameraSource cameraSource) {
CameraCapturer newCameraCapturer = null;
try {
newCameraCapturer = new CameraCapturer(
context,
cameraSource,
new CameraCapturer.Listener() {
@Override
public void onFirstFrameAvailable() {
}
@Override
public void onCameraSwitched() {
setThumbnailMirror();
}
@Override
public void onError(int i) {
Log.i("CustomTwilioVideoView", "Error getting camera");
}
}
);
return newCameraCapturer;
} catch (Exception e) {
return null;
}
}
private boolean createLocalVideo(boolean enableVideo) {
// Share your camera
cameraCapturer = this.createCameraCaputer(getContext(), CameraCapturer.CameraSource.FRONT_CAMERA);
if (cameraCapturer == null){
cameraCapturer = this.createCameraCaputer(getContext(), CameraCapturer.CameraSource.BACK_CAMERA);
}
if (cameraCapturer == null){
WritableMap event = new WritableNativeMap();
event.putString("error", "No camera is supported on this device");
pushEvent(CustomTwilioVideoView.this, ON_CONNECT_FAILURE, event);
return false;
}
if (cameraCapturer.getSupportedFormats().size() > 0) {
localVideoTrack = LocalVideoTrack.create(getContext(), enableVideo, cameraCapturer, buildVideoConstraints());
if (thumbnailVideoView != null && localVideoTrack != null) {
localVideoTrack.addRenderer(thumbnailVideoView);
}
setThumbnailMirror();
}
return true;
}
// ===== LIFECYCLE EVENTS ======================================================================
@Override
public void onHostResume() {
/*
* In case it wasn't set.
*/
if (themedReactContext.getCurrentActivity() != null) {
/*
* If the local video track was released when the app was put in the background, recreate.
*/
if (cameraCapturer != null && localVideoTrack == null) {
localVideoTrack = LocalVideoTrack.create(getContext(), true, cameraCapturer, buildVideoConstraints());
}
if (localVideoTrack != null) {
if (thumbnailVideoView != null) {
localVideoTrack.addRenderer(thumbnailVideoView);
}
/*
* If connected to a Room then share the local video track.
*/
if (localParticipant != null && isLocalVideoPublished) {
localParticipant.publishTrack(localVideoTrack);
}
}
themedReactContext.getCurrentActivity().setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
}
}
@Override
public void onHostPause() {
/*
* Release the local video track before going in the background. This ensures that the
* camera can be used by other applications while this app is in the background.
*/
if (localVideoTrack != null) {
/*
* If this local video track is being shared in a Room, remove from local
* participant before releasing the video track. Participants will be notified that
* the track has been removed.
*/
if (localParticipant != null) {
localParticipant.unpublishTrack(localVideoTrack);
}
localVideoTrack.release();
localVideoTrack = null;
}
}
@Override
public void onHostDestroy() {
/*
* Always disconnect from the room before leaving the Activity to
* ensure any memory allocated to the Room resource is freed.
*/
if (room != null && room.getState() != Room.State.DISCONNECTED) {
room.disconnect();
disconnectedFromOnDestroy = true;
}
/*
* Release the local media ensuring any memory allocated to audio or video is freed.
*/
if (localVideoTrack != null) {
localVideoTrack.release();
localVideoTrack = null;
}
if (localAudioTrack != null) {
localAudioTrack.release();
localAudioTrack = null;
}
// Quit the data track message thread
dataTrackMessageThread.quit();
}
public void releaseResource() {
themedReactContext.removeLifecycleEventListener(this);
room = null;
localVideoTrack = null;
thumbnailVideoView = null;
cameraCapturer = null;
}
// ====== CONNECTING ===========================================================================
public void connectToRoomWrapper(
String roomName, String accessToken, boolean enableAudio, boolean enableVideo, boolean enableRemoteAudio) {
this.roomName = roomName;
this.accessToken = accessToken;
this.enableRemoteAudio = enableAudio;
// Share your microphone
localAudioTrack = LocalAudioTrack.create(getContext(), enableAudio);
if (cameraCapturer == null) {
boolean createVideoStatus = createLocalVideo(enableVideo);
if (!createVideoStatus) {
// No need to connect to room if video creation failed
return;
}
}
connectToRoom(enableAudio);
}
public void connectToRoom(boolean enableAudio) {
/*
* Create a VideoClient allowing you to connect to a Room
*/
setAudioFocus(enableAudio);
ConnectOptions.Builder connectOptionsBuilder = new ConnectOptions.Builder(this.accessToken);
if (this.roomName != null) {
connectOptionsBuilder.roomName(this.roomName);
}
if (localAudioTrack != null) {
connectOptionsBuilder.audioTracks(Collections.singletonList(localAudioTrack));
}
if (localVideoTrack != null) {
connectOptionsBuilder.videoTracks(Collections.singletonList(localVideoTrack));
}
//LocalDataTrack localDataTrack = LocalDataTrack.create(getContext());
if (localDataTrack != null) {
connectOptionsBuilder.dataTracks(Collections.singletonList(localDataTrack));
}
room = Video.connect(getContext(), connectOptionsBuilder.build(), roomListener());
}
private void setAudioFocus(boolean focus) {
if (focus) {
previousAudioMode = audioManager.getMode();
// Request audio focus before making any device switch.
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
audioManager.requestAudioFocus(this,
AudioManager.STREAM_VOICE_CALL,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
} else {
playbackAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build();
audioFocusRequest = new AudioFocusRequest
.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
.setAudioAttributes(playbackAttributes)
.setAcceptsDelayedFocusGain(true)
.setOnAudioFocusChangeListener(this, handler)
.build();
audioManager.requestAudioFocus(audioFocusRequest);
}
/*
* Use MODE_IN_COMMUNICATION as the default audio mode. It is required
* to be in this mode when playout and/or recording starts for the best
* possible VoIP performance. Some devices have difficulties with
* speaker mode if this is not set.
*/
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(!audioManager.isWiredHeadsetOn());
getContext().registerReceiver(myNoisyAudioStreamReceiver, intentFilter);
} else {
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
audioManager.abandonAudioFocus(this);
} else if (audioFocusRequest != null) {
audioManager.abandonAudioFocusRequest(audioFocusRequest);
}
audioManager.setSpeakerphoneOn(false);
audioManager.setMode(previousAudioMode);
try {
if (myNoisyAudioStreamReceiver != null) {
getContext().unregisterReceiver(myNoisyAudioStreamReceiver);
}
myNoisyAudioStreamReceiver = null;
} catch (Exception e) {
// already registered
e.printStackTrace();
}
}
}
private class BecomingNoisyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// audioManager.setSpeakerphoneOn(true);
if (Intent.ACTION_HEADSET_PLUG.equals(intent.getAction())) {
audioManager.setSpeakerphoneOn(!audioManager.isWiredHeadsetOn());
}
}
}
@Override
public void onAudioFocusChange(int focusChange) {
Log.e(TAG, "onAudioFocusChange: focuschange: " + focusChange);
}
// ====== DISCONNECTING ========================================================================
public void disconnect() {
if (room != null) {
room.disconnect();
}
if (localAudioTrack != null) {
localAudioTrack.release();
localAudioTrack = null;
}
if (localVideoTrack != null) {
localVideoTrack.release();
localVideoTrack = null;
}
setAudioFocus(false);
if (cameraCapturer != null) {
cameraCapturer.stopCapture();
cameraCapturer = null;
}
}
// ===== SEND STRING ON DATA TRACK ======================================================================
public void sendString(String message) {
if (localDataTrack != null) {
localDataTrack.send(message);
}
}
// ===== BUTTON LISTENERS ======================================================================
private static void setThumbnailMirror() {
if (cameraCapturer != null) {
CameraCapturer.CameraSource cameraSource = cameraCapturer.getCameraSource();
final boolean isBackCamera = (cameraSource == CameraCapturer.CameraSource.BACK_CAMERA);
if (thumbnailVideoView != null && thumbnailVideoView.getVisibility() == View.VISIBLE) {
thumbnailVideoView.setMirror(!isBackCamera);
}
}
}
public void switchCamera() {
if (cameraCapturer != null) {
cameraCapturer.switchCamera();
CameraCapturer.CameraSource cameraSource = cameraCapturer.getCameraSource();
final boolean isBackCamera = cameraSource == CameraCapturer.CameraSource.BACK_CAMERA;
WritableMap event = new WritableNativeMap();
event.putBoolean("isBackCamera", isBackCamera);
pushEvent(CustomTwilioVideoView.this, ON_CAMERA_SWITCHED, event);
}
}
public void toggleVideo(boolean enabled) {
if (localVideoTrack != null) {
localVideoTrack.enable(enabled);
WritableMap event = new WritableNativeMap();
event.putBoolean("videoEnabled", enabled);
pushEvent(CustomTwilioVideoView.this, ON_VIDEO_CHANGED, event);
}
}
public void toggleSoundSetup(boolean speaker){
AudioManager audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
if(speaker){
audioManager.setSpeakerphoneOn(true);
} else {
audioManager.setSpeakerphoneOn(false);
}
}
public void toggleAudio(boolean enabled) {
if (localAudioTrack != null) {
localAudioTrack.enable(enabled);
WritableMap event = new WritableNativeMap();
event.putBoolean("audioEnabled", enabled);
pushEvent(CustomTwilioVideoView.this, ON_AUDIO_CHANGED, event);
}
}
public void toggleBluetoothHeadset(boolean enabled) {
AudioManager audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
if(enabled){
audioManager.startBluetoothSco();
} else {
audioManager.stopBluetoothSco();
}
}
public void toggleRemoteAudio(boolean enabled) {
if (room != null) {
for (RemoteParticipant rp : room.getRemoteParticipants()) {
for(AudioTrackPublication at : rp.getAudioTracks()) {
if(at.getAudioTrack() != null) {
((RemoteAudioTrack)at.getAudioTrack()).enablePlayback(enabled);
}
}
}
}
}
public void publishLocalVideo(boolean enabled) {
if (localParticipant != null && localVideoTrack != null) {
isLocalVideoPublished = enabled;
if (enabled) {
localParticipant.publishTrack(localVideoTrack);
} else {
localParticipant.unpublishTrack(localVideoTrack);
}
}
}
public void publishLocalAudio(boolean enabled) {
if (localParticipant != null && localAudioTrack != null) {
if (enabled) {
localParticipant.publishTrack(localAudioTrack);
} else {
localParticipant.unpublishTrack(localAudioTrack);
}
}
}
private void convertBaseTrackStats(BaseTrackStats bs, WritableMap result) {
result.putString("codec", bs.codec);
result.putInt("packetsLost", bs.packetsLost);
result.putString("ssrc", bs.ssrc);
result.putDouble("timestamp", bs.timestamp);
result.putString("trackSid", bs.trackSid);
}
private void convertLocalTrackStats(LocalTrackStats ts, WritableMap result) {
result.putDouble("bytesSent", ts.bytesSent);
result.putInt("packetsSent", ts.packetsSent);
result.putDouble("roundTripTime", ts.roundTripTime);
}
private void convertRemoteTrackStats(RemoteTrackStats ts, WritableMap result) {
result.putDouble("bytesReceived", ts.bytesReceived);
result.putInt("packetsReceived", ts.packetsReceived);
}
private WritableMap convertAudioTrackStats(RemoteAudioTrackStats as) {
WritableMap result = new WritableNativeMap();
result.putInt("audioLevel", as.audioLevel);
result.putInt("jitter", as.jitter);
convertBaseTrackStats(as, result);
convertRemoteTrackStats(as, result);
return result;
}
private WritableMap convertLocalAudioTrackStats(LocalAudioTrackStats as) {
WritableMap result = new WritableNativeMap();
result.putInt("audioLevel", as.audioLevel);
result.putInt("jitter", as.jitter);
convertBaseTrackStats(as, result);
convertLocalTrackStats(as, result);
return result;
}
private WritableMap convertVideoTrackStats(RemoteVideoTrackStats vs) {
WritableMap result = new WritableNativeMap();
WritableMap dimensions = new WritableNativeMap();
dimensions.putInt("height", vs.dimensions.height);
dimensions.putInt("width", vs.dimensions.width);
result.putMap("dimensions", dimensions);
result.putInt("frameRate", vs.frameRate);
convertBaseTrackStats(vs, result);
convertRemoteTrackStats(vs, result);
return result;
}
private WritableMap convertLocalVideoTrackStats(LocalVideoTrackStats vs) {
WritableMap result = new WritableNativeMap();
WritableMap dimensions = new WritableNativeMap();
dimensions.putInt("height", vs.dimensions.height);
dimensions.putInt("width", vs.dimensions.width);
result.putMap("dimensions", dimensions);
result.putInt("frameRate", vs.frameRate);
convertBaseTrackStats(vs, result);
convertLocalTrackStats(vs, result);
return result;
}
public void getStats() {
if (room != null) {
room.getStats(new StatsListener() {
@Override
public void onStats(List<StatsReport> statsReports) {
WritableMap event = new WritableNativeMap();
for (StatsReport sr : statsReports) {
WritableMap connectionStats = new WritableNativeMap();
WritableArray as = new WritableNativeArray();
for (RemoteAudioTrackStats s : sr.getRemoteAudioTrackStats()) {
as.pushMap(convertAudioTrackStats(s));
}
connectionStats.putArray("remoteAudioTrackStats", as);
WritableArray vs = new WritableNativeArray();
for (RemoteVideoTrackStats s : sr.getRemoteVideoTrackStats()) {
vs.pushMap(convertVideoTrackStats(s));
}
connectionStats.putArray("remoteVideoTrackStats", vs);
WritableArray las = new WritableNativeArray();
for (LocalAudioTrackStats s : sr.getLocalAudioTrackStats()) {
las.pushMap(convertLocalAudioTrackStats(s));
}
connectionStats.putArray("localAudioTrackStats", las);
WritableArray lvs = new WritableNativeArray();
for (LocalVideoTrackStats s : sr.getLocalVideoTrackStats()) {
lvs.pushMap(convertLocalVideoTrackStats(s));
}
connectionStats.putArray("localVideoTrackStats", lvs);
event.putMap(sr.getPeerConnectionId(), connectionStats);
}
pushEvent(CustomTwilioVideoView.this, ON_STATS_RECEIVED, event);
}
});
}
}
public void disableOpenSLES() {
WebRtcAudioManager.setBlacklistDeviceForOpenSLESUsage(true);
}
// ====== ROOM LISTENER ========================================================================
/*
* Room events listener
*/
private Room.Listener roomListener() {
return new Room.Listener() {
@Override
public void onConnected(Room room) {
localParticipant = room.getLocalParticipant();
WritableMap event = new WritableNativeMap();
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
List<RemoteParticipant> participants = room.getRemoteParticipants();
WritableArray participantsArray = new WritableNativeArray();
for (RemoteParticipant participant : participants) {
participantsArray.pushMap(buildParticipant(participant));
}
participantsArray.pushMap(buildParticipant(localParticipant));
event.putArray("participants", participantsArray);
pushEvent(CustomTwilioVideoView.this, ON_CONNECTED, event);
//There is not .publish it's publishTrack
localParticipant.publishTrack(localDataTrack);
for (RemoteParticipant participant : participants) {
addParticipant(room, participant);
}
}
@Override
public void onConnectFailure(Room room, TwilioException e) {
WritableMap event = new WritableNativeMap();
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
event.putString("error", e.getMessage());
pushEvent(CustomTwilioVideoView.this, ON_CONNECT_FAILURE, event);
}
@Override
public void onReconnecting(@NonNull Room room, @NonNull TwilioException twilioException) {
}
@Override
public void onReconnected(@NonNull Room room) {
}
@Override
public void onDisconnected(Room room, TwilioException e) {
WritableMap event = new WritableNativeMap();
if (localParticipant != null) {
event.putString("participant", localParticipant.getIdentity());
}
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
if (e != null) {
event.putString("error", e.getMessage());
}
pushEvent(CustomTwilioVideoView.this, ON_DISCONNECTED, event);
localParticipant = null;
roomName = null;
accessToken = null;
CustomTwilioVideoView.room = null;
// Only reinitialize the UI if disconnect was not called from onDestroy()
if (!disconnectedFromOnDestroy) {
setAudioFocus(false);
}
}
@Override
public void onParticipantConnected(Room room, RemoteParticipant participant) {
addParticipant(room, participant);
}
@Override
public void onParticipantDisconnected(Room room, RemoteParticipant participant) {
removeParticipant(room, participant);
}
@Override
public void onRecordingStarted(Room room) {
}
@Override
public void onRecordingStopped(Room room) {
}
};
}
/*
* Called when participant joins the room
*/
private void addParticipant(Room room, RemoteParticipant remoteParticipant) {
WritableMap event = new WritableNativeMap();
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
event.putMap("participant", buildParticipant(remoteParticipant));
pushEvent(this, ON_PARTICIPANT_CONNECTED, event);
/*
* Start listening for participant media events
*/
remoteParticipant.setListener(mediaListener());
for (final RemoteDataTrackPublication remoteDataTrackPublication :
remoteParticipant.getRemoteDataTracks()) {
/*
* Data track messages are received on the thread that calls setListener. Post the
* invocation of setting the listener onto our dedicated data track message thread.
*/
if (remoteDataTrackPublication.isTrackSubscribed()) {
dataTrackMessageThreadHandler.post(() -> addRemoteDataTrack(remoteParticipant,
remoteDataTrackPublication.getRemoteDataTrack()));
}
}
}
/*
* Called when participant leaves the room
*/
private void removeParticipant(Room room, RemoteParticipant participant) {
WritableMap event = new WritableNativeMap();
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
event.putMap("participant", buildParticipant(participant));
pushEvent(this, ON_PARTICIPANT_DISCONNECTED, event);
//something about this breaking.
//participant.setListener(null);
}
private void addRemoteDataTrack(RemoteParticipant remoteParticipant, RemoteDataTrack remoteDataTrack) {
dataTrackRemoteParticipantMap.put(remoteDataTrack, remoteParticipant);
remoteDataTrack.setListener(remoteDataTrackListener());
}
// ====== MEDIA LISTENER =======================================================================
private RemoteParticipant.Listener mediaListener() {
return new RemoteParticipant.Listener() {
@Override
public void onAudioTrackSubscribed(RemoteParticipant participant, RemoteAudioTrackPublication publication, RemoteAudioTrack audioTrack) {
audioTrack.enablePlayback(enableRemoteAudio);
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_ADDED_AUDIO_TRACK, event);
}
@Override
public void onAudioTrackUnsubscribed(RemoteParticipant participant, RemoteAudioTrackPublication publication, RemoteAudioTrack audioTrack) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_REMOVED_AUDIO_TRACK, event);
}
@Override
public void onAudioTrackSubscriptionFailed(RemoteParticipant participant, RemoteAudioTrackPublication publication, TwilioException twilioException) {
}
@Override
public void onAudioTrackPublished(RemoteParticipant participant, RemoteAudioTrackPublication publication) {
}
@Override
public void onAudioTrackUnpublished(RemoteParticipant participant, RemoteAudioTrackPublication publication) {
}
@Override
public void onDataTrackSubscribed(RemoteParticipant remoteParticipant, RemoteDataTrackPublication remoteDataTrackPublication, RemoteDataTrack remoteDataTrack) {
WritableMap event = buildParticipantDataEvent(remoteParticipant);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_ADDED_DATA_TRACK, event);
dataTrackMessageThreadHandler.post(() -> addRemoteDataTrack(remoteParticipant, remoteDataTrack));
}
@Override
public void onDataTrackUnsubscribed(RemoteParticipant remoteParticipant, RemoteDataTrackPublication publication, RemoteDataTrack remoteDataTrack) {
WritableMap event = buildParticipantDataEvent(remoteParticipant);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_REMOVED_DATA_TRACK, event);
}
@Override
public void onDataTrackSubscriptionFailed(RemoteParticipant participant, RemoteDataTrackPublication publication, TwilioException twilioException) {
}
@Override
public void onDataTrackPublished(RemoteParticipant participant, RemoteDataTrackPublication publication) {
}
@Override
public void onDataTrackUnpublished(RemoteParticipant participant, RemoteDataTrackPublication publication) {
}
@Override
public void onVideoTrackSubscribed(RemoteParticipant participant, RemoteVideoTrackPublication publication, RemoteVideoTrack videoTrack) {
addParticipantVideo(participant, publication);
}
@Override
public void onVideoTrackUnsubscribed(RemoteParticipant participant, RemoteVideoTrackPublication publication, RemoteVideoTrack videoTrack) {
removeParticipantVideo(participant, publication);
}
@Override
public void onVideoTrackSubscriptionFailed(RemoteParticipant participant, RemoteVideoTrackPublication publication, TwilioException twilioException) {
}
@Override
public void onVideoTrackPublished(RemoteParticipant participant, RemoteVideoTrackPublication publication) {
}
@Override
public void onVideoTrackUnpublished(RemoteParticipant participant, RemoteVideoTrackPublication publication) {
}
@Override
public void onAudioTrackEnabled(RemoteParticipant participant, RemoteAudioTrackPublication publication) {// Log.i(TAG, "onAudioTrackEnabled");
// publication.getRemoteAudioTrack().enablePlayback(false);
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_ENABLED_AUDIO_TRACK, event);
}
@Override
public void onAudioTrackDisabled(RemoteParticipant participant, RemoteAudioTrackPublication publication) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_DISABLED_AUDIO_TRACK, event);
}
@Override
public void onVideoTrackEnabled(RemoteParticipant participant, RemoteVideoTrackPublication publication) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_ENABLED_VIDEO_TRACK, event);
}
@Override
public void onVideoTrackDisabled(RemoteParticipant participant, RemoteVideoTrackPublication publication) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_DISABLED_VIDEO_TRACK, event);
}
};
}
private WritableMap buildParticipant(Participant participant) {
WritableMap participantMap = new WritableNativeMap();
participantMap.putString("identity", participant.getIdentity());
participantMap.putString("sid", participant.getSid());
return participantMap;
}
private WritableMap buildParticipantDataEvent(Participant participant) {
WritableMap participantMap = buildParticipant(participant);
WritableMap participantMap2 = buildParticipant(participant);
WritableMap event = new WritableNativeMap();
event.putMap("participant", participantMap);
event.putMap("track", participantMap2);
return event;
}
private WritableMap buildParticipantVideoEvent(Participant participant, TrackPublication publication) {
WritableMap participantMap = buildParticipant(participant);
WritableMap trackMap = new WritableNativeMap();
trackMap.putString("trackSid", publication.getTrackSid());
trackMap.putString("trackName", publication.getTrackName());
trackMap.putBoolean("enabled", publication.isTrackEnabled());