1package eu.siacs.conversations.xmpp.jingle;
2
3import android.content.Context;
4import android.media.ToneGenerator;
5import android.os.Build;
6import android.os.Handler;
7import android.os.Looper;
8import android.util.Log;
9
10import com.google.common.base.Optional;
11import com.google.common.base.Preconditions;
12import com.google.common.collect.ImmutableMap;
13import com.google.common.collect.ImmutableSet;
14import com.google.common.util.concurrent.Futures;
15import com.google.common.util.concurrent.ListenableFuture;
16import com.google.common.util.concurrent.MoreExecutors;
17import com.google.common.util.concurrent.SettableFuture;
18
19import org.webrtc.AudioSource;
20import org.webrtc.AudioTrack;
21import org.webrtc.CandidatePairChangeEvent;
22import org.webrtc.DataChannel;
23import org.webrtc.DefaultVideoDecoderFactory;
24import org.webrtc.DefaultVideoEncoderFactory;
25import org.webrtc.DtmfSender;
26import org.webrtc.EglBase;
27import org.webrtc.IceCandidate;
28import org.webrtc.MediaConstraints;
29import org.webrtc.MediaStream;
30import org.webrtc.MediaStreamTrack;
31import org.webrtc.PeerConnection;
32import org.webrtc.PeerConnectionFactory;
33import org.webrtc.RtpReceiver;
34import org.webrtc.RtpTransceiver;
35import org.webrtc.SdpObserver;
36import org.webrtc.SessionDescription;
37import org.webrtc.VideoTrack;
38import org.webrtc.audio.JavaAudioDeviceModule;
39import org.webrtc.voiceengine.WebRtcAudioEffects;
40
41import java.util.LinkedList;
42import java.util.List;
43import java.util.Queue;
44import java.util.Map;
45import java.util.Set;
46import java.util.concurrent.ExecutorService;
47import java.util.concurrent.Executors;
48import java.util.concurrent.atomic.AtomicBoolean;
49
50import javax.annotation.Nonnull;
51import javax.annotation.Nullable;
52
53import eu.siacs.conversations.Config;
54import eu.siacs.conversations.services.AppRTCAudioManager;
55import eu.siacs.conversations.services.XmppConnectionService;
56
57@SuppressWarnings("UnstableApiUsage")
58public class WebRTCWrapper {
59
60 private static final String EXTENDED_LOGGING_TAG = WebRTCWrapper.class.getSimpleName();
61
62 private final ExecutorService executorService = Executors.newSingleThreadExecutor();
63
64 private static final int TONE_DURATION = 500;
65 private static final Map<String,Integer> TONE_CODES;
66 static {
67 ImmutableMap.Builder<String,Integer> builder = new ImmutableMap.Builder<>();
68 builder.put("0", ToneGenerator.TONE_DTMF_0);
69 builder.put("1", ToneGenerator.TONE_DTMF_1);
70 builder.put("2", ToneGenerator.TONE_DTMF_2);
71 builder.put("3", ToneGenerator.TONE_DTMF_3);
72 builder.put("4", ToneGenerator.TONE_DTMF_4);
73 builder.put("5", ToneGenerator.TONE_DTMF_5);
74 builder.put("6", ToneGenerator.TONE_DTMF_6);
75 builder.put("7", ToneGenerator.TONE_DTMF_7);
76 builder.put("8", ToneGenerator.TONE_DTMF_8);
77 builder.put("9", ToneGenerator.TONE_DTMF_9);
78 builder.put("*", ToneGenerator.TONE_DTMF_S);
79 builder.put("#", ToneGenerator.TONE_DTMF_P);
80 TONE_CODES = builder.build();
81 }
82
83 private static final Set<String> HARDWARE_AEC_BLACKLIST =
84 new ImmutableSet.Builder<String>()
85 .add("Pixel")
86 .add("Pixel XL")
87 .add("Moto G5")
88 .add("Moto G (5S) Plus")
89 .add("Moto G4")
90 .add("TA-1053")
91 .add("Mi A1")
92 .add("Mi A2")
93 .add("E5823") // Sony z5 compact
94 .add("Redmi Note 5")
95 .add("FP2") // Fairphone FP2
96 .add("MI 5")
97 .add("GT-I9515") // Samsung Galaxy S4 Value Edition (jfvelte)
98 .add("GT-I9515L") // Samsung Galaxy S4 Value Edition (jfvelte)
99 .add("GT-I9505") // Samsung Galaxy S4 (jfltexx)
100 .build();
101
102 private final EventCallback eventCallback;
103 private final AtomicBoolean readyToReceivedIceCandidates = new AtomicBoolean(false);
104 private final Queue<IceCandidate> iceCandidates = new LinkedList<>();
105 private final AppRTCAudioManager.AudioManagerEvents audioManagerEvents =
106 new AppRTCAudioManager.AudioManagerEvents() {
107 @Override
108 public void onAudioDeviceChanged(
109 AppRTCAudioManager.AudioDevice selectedAudioDevice,
110 Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
111 eventCallback.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
112 }
113 };
114 private final Handler mainHandler = new Handler(Looper.getMainLooper());
115 private TrackWrapper<AudioTrack> localAudioTrack = null;
116 private TrackWrapper<VideoTrack> localVideoTrack = null;
117 private VideoTrack remoteVideoTrack = null;
118 private final PeerConnection.Observer peerConnectionObserver =
119 new PeerConnection.Observer() {
120 @Override
121 public void onSignalingChange(PeerConnection.SignalingState signalingState) {
122 Log.d(EXTENDED_LOGGING_TAG, "onSignalingChange(" + signalingState + ")");
123 // this is called after removeTrack or addTrack
124 // and should then trigger a content-add or content-remove or something
125 // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/removeTrack
126 }
127
128 @Override
129 public void onConnectionChange(final PeerConnection.PeerConnectionState newState) {
130 eventCallback.onConnectionChange(newState);
131 }
132
133 @Override
134 public void onIceConnectionChange(
135 PeerConnection.IceConnectionState iceConnectionState) {
136 Log.d(
137 EXTENDED_LOGGING_TAG,
138 "onIceConnectionChange(" + iceConnectionState + ")");
139 }
140
141 @Override
142 public void onSelectedCandidatePairChanged(CandidatePairChangeEvent event) {
143 Log.d(Config.LOGTAG, "remote candidate selected: " + event.remote);
144 Log.d(Config.LOGTAG, "local candidate selected: " + event.local);
145 }
146
147 @Override
148 public void onIceConnectionReceivingChange(boolean b) {}
149
150 @Override
151 public void onIceGatheringChange(
152 PeerConnection.IceGatheringState iceGatheringState) {
153 Log.d(EXTENDED_LOGGING_TAG, "onIceGatheringChange(" + iceGatheringState + ")");
154 }
155
156 @Override
157 public void onIceCandidate(IceCandidate iceCandidate) {
158 if (readyToReceivedIceCandidates.get()) {
159 eventCallback.onIceCandidate(iceCandidate);
160 } else {
161 iceCandidates.add(iceCandidate);
162 }
163 }
164
165 @Override
166 public void onIceCandidatesRemoved(IceCandidate[] iceCandidates) {}
167
168 @Override
169 public void onAddStream(MediaStream mediaStream) {
170 Log.d(
171 EXTENDED_LOGGING_TAG,
172 "onAddStream(numAudioTracks="
173 + mediaStream.audioTracks.size()
174 + ",numVideoTracks="
175 + mediaStream.videoTracks.size()
176 + ")");
177 }
178
179 @Override
180 public void onRemoveStream(MediaStream mediaStream) {}
181
182 @Override
183 public void onDataChannel(DataChannel dataChannel) {}
184
185 @Override
186 public void onRenegotiationNeeded() {
187 Log.d(EXTENDED_LOGGING_TAG, "onRenegotiationNeeded()");
188 final PeerConnection.PeerConnectionState currentState =
189 peerConnection == null ? null : peerConnection.connectionState();
190 if (currentState != null
191 && currentState != PeerConnection.PeerConnectionState.NEW) {
192 eventCallback.onRenegotiationNeeded();
193 }
194 }
195
196 @Override
197 public void onAddTrack(RtpReceiver rtpReceiver, MediaStream[] mediaStreams) {
198 final MediaStreamTrack track = rtpReceiver.track();
199 Log.d(
200 EXTENDED_LOGGING_TAG,
201 "onAddTrack(kind="
202 + (track == null ? "null" : track.kind())
203 + ",numMediaStreams="
204 + mediaStreams.length
205 + ")");
206 if (track instanceof VideoTrack) {
207 remoteVideoTrack = (VideoTrack) track;
208 }
209 }
210
211 @Override
212 public void onTrack(final RtpTransceiver transceiver) {
213 Log.d(
214 EXTENDED_LOGGING_TAG,
215 "onTrack(mid="
216 + transceiver.getMid()
217 + ",media="
218 + transceiver.getMediaType()
219 + ",direction="
220 + transceiver.getDirection()
221 + ")");
222 }
223
224 @Override
225 public void onRemoveTrack(final RtpReceiver receiver) {
226 Log.d(EXTENDED_LOGGING_TAG, "onRemoveTrack(" + receiver.id() + ")");
227 }
228 };
229 @Nullable private PeerConnectionFactory peerConnectionFactory = null;
230 @Nullable private PeerConnection peerConnection = null;
231 private AppRTCAudioManager appRTCAudioManager = null;
232 private ToneManager toneManager = null;
233 private Context context = null;
234 private EglBase eglBase = null;
235 private VideoSourceWrapper videoSourceWrapper;
236
237 WebRTCWrapper(final EventCallback eventCallback) {
238 this.eventCallback = eventCallback;
239 }
240
241 private static void dispose(final PeerConnection peerConnection) {
242 try {
243 peerConnection.dispose();
244 } catch (final IllegalStateException e) {
245 Log.e(Config.LOGTAG, "unable to dispose of peer connection", e);
246 }
247 }
248
249 public void setup(
250 final XmppConnectionService service,
251 @Nonnull final AppRTCAudioManager.SpeakerPhonePreference speakerPhonePreference)
252 throws InitializationException {
253 try {
254 PeerConnectionFactory.initialize(
255 PeerConnectionFactory.InitializationOptions.builder(service)
256 .setFieldTrials("WebRTC-BindUsingInterfaceName/Enabled/")
257 .createInitializationOptions());
258 } catch (final UnsatisfiedLinkError e) {
259 throw new InitializationException("Unable to initialize PeerConnectionFactory", e);
260 }
261 try {
262 this.eglBase = EglBase.create();
263 } catch (final RuntimeException e) {
264 throw new InitializationException("Unable to create EGL base", e);
265 }
266 this.context = service;
267 this.toneManager = service.getJingleConnectionManager().toneManager;
268 mainHandler.post(
269 () -> {
270 appRTCAudioManager = AppRTCAudioManager.create(service, speakerPhonePreference);
271 toneManager.setAppRtcAudioManagerHasControl(true);
272 appRTCAudioManager.start(audioManagerEvents);
273 eventCallback.onAudioDeviceChanged(
274 appRTCAudioManager.getSelectedAudioDevice(),
275 appRTCAudioManager.getAudioDevices());
276 });
277 }
278
279 synchronized void initializePeerConnection(
280 final Set<Media> media, final List<PeerConnection.IceServer> iceServers)
281 throws InitializationException {
282 Preconditions.checkState(this.eglBase != null);
283 Preconditions.checkNotNull(media);
284 Preconditions.checkArgument(
285 media.size() > 0, "media can not be empty when initializing peer connection");
286 final boolean setUseHardwareAcousticEchoCanceler =
287 WebRtcAudioEffects.canUseAcousticEchoCanceler()
288 && !HARDWARE_AEC_BLACKLIST.contains(Build.MODEL);
289 Log.d(
290 Config.LOGTAG,
291 String.format(
292 "setUseHardwareAcousticEchoCanceler(%s) model=%s",
293 setUseHardwareAcousticEchoCanceler, Build.MODEL));
294 this.peerConnectionFactory =
295 PeerConnectionFactory.builder()
296 .setVideoDecoderFactory(
297 new DefaultVideoDecoderFactory(eglBase.getEglBaseContext()))
298 .setVideoEncoderFactory(
299 new DefaultVideoEncoderFactory(
300 eglBase.getEglBaseContext(), true, true))
301 .setAudioDeviceModule(
302 JavaAudioDeviceModule.builder(requireContext())
303 .setUseHardwareAcousticEchoCanceler(
304 setUseHardwareAcousticEchoCanceler)
305 .createAudioDeviceModule())
306 .createPeerConnectionFactory();
307
308 final PeerConnection.RTCConfiguration rtcConfig = buildConfiguration(iceServers);
309 final PeerConnection peerConnection =
310 requirePeerConnectionFactory()
311 .createPeerConnection(rtcConfig, peerConnectionObserver);
312 if (peerConnection == null) {
313 throw new InitializationException("Unable to create PeerConnection");
314 }
315
316 if (media.contains(Media.VIDEO)) {
317 addVideoTrack(peerConnection);
318 }
319
320 if (media.contains(Media.AUDIO)) {
321 addAudioTrack(peerConnection);
322 }
323 peerConnection.setAudioPlayout(true);
324 peerConnection.setAudioRecording(true);
325
326 this.peerConnection = peerConnection;
327 }
328
329 private VideoSourceWrapper initializeVideoSourceWrapper() {
330 final VideoSourceWrapper existingVideoSourceWrapper = this.videoSourceWrapper;
331 if (existingVideoSourceWrapper != null) {
332 existingVideoSourceWrapper.startCapture();
333 return existingVideoSourceWrapper;
334 }
335 final VideoSourceWrapper videoSourceWrapper =
336 new VideoSourceWrapper.Factory(requireContext()).create();
337 if (videoSourceWrapper == null) {
338 throw new IllegalStateException("Could not instantiate VideoSourceWrapper");
339 }
340 videoSourceWrapper.initialize(
341 requirePeerConnectionFactory(), requireContext(), eglBase.getEglBaseContext());
342 videoSourceWrapper.startCapture();
343 this.videoSourceWrapper = videoSourceWrapper;
344 return videoSourceWrapper;
345 }
346
347 public synchronized boolean addTrack(final Media media) {
348 if (media == Media.VIDEO) {
349 return addVideoTrack(requirePeerConnection());
350 } else if (media == Media.AUDIO) {
351 return addAudioTrack(requirePeerConnection());
352 }
353 throw new IllegalStateException(String.format("Could not add track for %s", media));
354 }
355
356 public synchronized void removeTrack(final Media media) {
357 if (media == Media.VIDEO) {
358 removeVideoTrack(requirePeerConnection());
359 }
360 }
361
362 private boolean addAudioTrack(final PeerConnection peerConnection) {
363 final AudioSource audioSource =
364 requirePeerConnectionFactory().createAudioSource(new MediaConstraints());
365 final AudioTrack audioTrack =
366 requirePeerConnectionFactory()
367 .createAudioTrack(TrackWrapper.id(AudioTrack.class), audioSource);
368 this.localAudioTrack = TrackWrapper.addTrack(peerConnection, audioTrack);
369 return true;
370 }
371
372 private boolean addVideoTrack(final PeerConnection peerConnection) {
373 final TrackWrapper<VideoTrack> existing = this.localVideoTrack;
374 if (existing != null) {
375 final RtpTransceiver transceiver =
376 TrackWrapper.getTransceiver(peerConnection, existing);
377 if (transceiver == null) {
378 Log.w(EXTENDED_LOGGING_TAG, "unable to restart video transceiver");
379 return false;
380 }
381 transceiver.setDirection(RtpTransceiver.RtpTransceiverDirection.SEND_RECV);
382 this.videoSourceWrapper.startCapture();
383 return true;
384 }
385 final VideoSourceWrapper videoSourceWrapper;
386 try {
387 videoSourceWrapper = initializeVideoSourceWrapper();
388 } catch (final IllegalStateException e) {
389 Log.d(Config.LOGTAG, "could not add video track", e);
390 return false;
391 }
392 final VideoTrack videoTrack =
393 requirePeerConnectionFactory()
394 .createVideoTrack(
395 TrackWrapper.id(VideoTrack.class),
396 videoSourceWrapper.getVideoSource());
397 this.localVideoTrack = TrackWrapper.addTrack(peerConnection, videoTrack);
398 return true;
399 }
400
401 private void removeVideoTrack(final PeerConnection peerConnection) {
402 final TrackWrapper<VideoTrack> localVideoTrack = this.localVideoTrack;
403 if (localVideoTrack != null) {
404
405 final RtpTransceiver exactTransceiver =
406 TrackWrapper.getTransceiver(peerConnection, localVideoTrack);
407 if (exactTransceiver == null) {
408 throw new IllegalStateException();
409 }
410 exactTransceiver.setDirection(RtpTransceiver.RtpTransceiverDirection.INACTIVE);
411 }
412 final VideoSourceWrapper videoSourceWrapper = this.videoSourceWrapper;
413 if (videoSourceWrapper != null) {
414 try {
415 videoSourceWrapper.stopCapture();
416 } catch (InterruptedException e) {
417 e.printStackTrace();
418 }
419 }
420 }
421
422 private static PeerConnection.RTCConfiguration buildConfiguration(
423 final List<PeerConnection.IceServer> iceServers) {
424 final PeerConnection.RTCConfiguration rtcConfig =
425 new PeerConnection.RTCConfiguration(iceServers);
426 rtcConfig.tcpCandidatePolicy =
427 PeerConnection.TcpCandidatePolicy.DISABLED; // XEP-0176 doesn't support tcp
428 rtcConfig.continualGatheringPolicy =
429 PeerConnection.ContinualGatheringPolicy.GATHER_CONTINUALLY;
430 rtcConfig.sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN;
431 rtcConfig.rtcpMuxPolicy = PeerConnection.RtcpMuxPolicy.NEGOTIATE;
432 rtcConfig.enableImplicitRollback = true;
433 return rtcConfig;
434 }
435
436 void reconfigurePeerConnection(final List<PeerConnection.IceServer> iceServers) {
437 requirePeerConnection().setConfiguration(buildConfiguration(iceServers));
438 }
439
440 void restartIce() {
441 executorService.execute(
442 () -> {
443 final PeerConnection peerConnection;
444 try {
445 peerConnection = requirePeerConnection();
446 } catch (final PeerConnectionNotInitialized e) {
447 Log.w(
448 EXTENDED_LOGGING_TAG,
449 "PeerConnection vanished before we could execute restart");
450 return;
451 }
452 setIsReadyToReceiveIceCandidates(false);
453 peerConnection.restartIce();
454 });
455 }
456
457 public void setIsReadyToReceiveIceCandidates(final boolean ready) {
458 readyToReceivedIceCandidates.set(ready);
459 final int was = iceCandidates.size();
460 while (ready && iceCandidates.peek() != null) {
461 eventCallback.onIceCandidate(iceCandidates.poll());
462 }
463 final int is = iceCandidates.size();
464 Log.d(
465 EXTENDED_LOGGING_TAG,
466 "setIsReadyToReceiveCandidates(" + ready + ") was=" + was + " is=" + is);
467 }
468
469 synchronized void close() {
470 final PeerConnection peerConnection = this.peerConnection;
471 final PeerConnectionFactory peerConnectionFactory = this.peerConnectionFactory;
472 final VideoSourceWrapper videoSourceWrapper = this.videoSourceWrapper;
473 final AppRTCAudioManager audioManager = this.appRTCAudioManager;
474 final EglBase eglBase = this.eglBase;
475 if (peerConnection != null) {
476 this.peerConnection = null;
477 dispose(peerConnection);
478 }
479 if (audioManager != null) {
480 toneManager.setAppRtcAudioManagerHasControl(false);
481 mainHandler.post(audioManager::stop);
482 }
483 this.localVideoTrack = null;
484 this.remoteVideoTrack = null;
485 if (videoSourceWrapper != null) {
486 this.videoSourceWrapper = null;
487 try {
488 videoSourceWrapper.stopCapture();
489 } catch (final InterruptedException e) {
490 Log.e(Config.LOGTAG, "unable to stop capturing");
491 }
492 videoSourceWrapper.dispose();
493 }
494 if (eglBase != null) {
495 eglBase.release();
496 this.eglBase = null;
497 }
498 if (peerConnectionFactory != null) {
499 this.peerConnectionFactory = null;
500 peerConnectionFactory.dispose();
501 }
502 }
503
504 synchronized void verifyClosed() {
505 if (this.peerConnection != null
506 || this.eglBase != null
507 || this.localVideoTrack != null
508 || this.remoteVideoTrack != null) {
509 final IllegalStateException e =
510 new IllegalStateException("WebRTCWrapper hasn't been closed properly");
511 Log.e(Config.LOGTAG, "verifyClosed() failed. Going to throw", e);
512 throw e;
513 }
514 }
515
516 boolean isCameraSwitchable() {
517 final VideoSourceWrapper videoSourceWrapper = this.videoSourceWrapper;
518 return videoSourceWrapper != null && videoSourceWrapper.isCameraSwitchable();
519 }
520
521 boolean isFrontCamera() {
522 final VideoSourceWrapper videoSourceWrapper = this.videoSourceWrapper;
523 return videoSourceWrapper == null || videoSourceWrapper.isFrontCamera();
524 }
525
526 ListenableFuture<Boolean> switchCamera() {
527 final VideoSourceWrapper videoSourceWrapper = this.videoSourceWrapper;
528 if (videoSourceWrapper == null) {
529 return Futures.immediateFailedFuture(
530 new IllegalStateException("VideoSourceWrapper has not been initialized"));
531 }
532 return videoSourceWrapper.switchCamera();
533 }
534
535 boolean isMicrophoneEnabled() {
536 Optional<AudioTrack> audioTrack = null;
537 try {
538 audioTrack = TrackWrapper.get(peerConnection, this.localAudioTrack);
539 } catch (final IllegalStateException e) {
540 Log.d(Config.LOGTAG, "unable to check microphone", e);
541 // ignoring race condition in case sender has been disposed
542 return false;
543 }
544 if (audioTrack.isPresent()) {
545 try {
546 return audioTrack.get().enabled();
547 } catch (final IllegalStateException e) {
548 // sometimes UI might still be rendering the buttons when a background thread has
549 // already ended the call
550 return false;
551 }
552 } else {
553 throw new IllegalStateException("Local audio track does not exist (yet)");
554 }
555 }
556
557 boolean setMicrophoneEnabled(final boolean enabled) {
558 Optional<AudioTrack> audioTrack = null;
559 try {
560 audioTrack = TrackWrapper.get(peerConnection, this.localAudioTrack);
561 } catch (final IllegalStateException e) {
562 Log.d(Config.LOGTAG, "unable to toggle microphone", e);
563 // ignoring race condition in case sender has been disposed
564 return false;
565 }
566 if (audioTrack.isPresent()) {
567 try {
568 audioTrack.get().setEnabled(enabled);
569 return true;
570 } catch (final IllegalStateException e) {
571 Log.d(Config.LOGTAG, "unable to toggle microphone", e);
572 // ignoring race condition in case MediaStreamTrack has been disposed
573 return false;
574 }
575 } else {
576 throw new IllegalStateException("Local audio track does not exist (yet)");
577 }
578 }
579
580 boolean isVideoEnabled() {
581 final Optional<VideoTrack> videoTrack =
582 TrackWrapper.get(peerConnection, this.localVideoTrack);
583 if (videoTrack.isPresent()) {
584 return videoTrack.get().enabled();
585 }
586 return false;
587 }
588
589 void setVideoEnabled(final boolean enabled) {
590 final Optional<VideoTrack> videoTrack =
591 TrackWrapper.get(peerConnection, this.localVideoTrack);
592 if (videoTrack.isPresent()) {
593 videoTrack.get().setEnabled(enabled);
594 return;
595 }
596 throw new IllegalStateException("Local video track does not exist");
597 }
598
599 synchronized ListenableFuture<SessionDescription> setLocalDescription() {
600 return Futures.transformAsync(
601 getPeerConnectionFuture(),
602 peerConnection -> {
603 if (peerConnection == null) {
604 return Futures.immediateFailedFuture(
605 new IllegalStateException("PeerConnection was null"));
606 }
607 final SettableFuture<SessionDescription> future = SettableFuture.create();
608 peerConnection.setLocalDescription(
609 new SetSdpObserver() {
610 @Override
611 public void onSetSuccess() {
612 final SessionDescription description =
613 peerConnection.getLocalDescription();
614 Log.d(EXTENDED_LOGGING_TAG, "set local description:");
615 logDescription(description);
616 future.set(description);
617 }
618
619 @Override
620 public void onSetFailure(final String message) {
621 future.setException(
622 new FailureToSetDescriptionException(message));
623 }
624 });
625 return future;
626 },
627 MoreExecutors.directExecutor());
628 }
629
630 public static void logDescription(final SessionDescription sessionDescription) {
631 for (final String line :
632 sessionDescription.description.split(
633 eu.siacs.conversations.xmpp.jingle.SessionDescription.LINE_DIVIDER)) {
634 Log.d(EXTENDED_LOGGING_TAG, line);
635 }
636 }
637
638 synchronized ListenableFuture<Void> setRemoteDescription(
639 final SessionDescription sessionDescription) {
640 Log.d(EXTENDED_LOGGING_TAG, "setting remote description:");
641 logDescription(sessionDescription);
642 return Futures.transformAsync(
643 getPeerConnectionFuture(),
644 peerConnection -> {
645 if (peerConnection == null) {
646 return Futures.immediateFailedFuture(
647 new IllegalStateException("PeerConnection was null"));
648 }
649 final SettableFuture<Void> future = SettableFuture.create();
650 peerConnection.setRemoteDescription(
651 new SetSdpObserver() {
652 @Override
653 public void onSetSuccess() {
654 future.set(null);
655 }
656
657 @Override
658 public void onSetFailure(final String message) {
659 future.setException(
660 new FailureToSetDescriptionException(message));
661 }
662 },
663 sessionDescription);
664 return future;
665 },
666 MoreExecutors.directExecutor());
667 }
668
669 @Nonnull
670 private ListenableFuture<PeerConnection> getPeerConnectionFuture() {
671 final PeerConnection peerConnection = this.peerConnection;
672 if (peerConnection == null) {
673 return Futures.immediateFailedFuture(new PeerConnectionNotInitialized());
674 } else {
675 return Futures.immediateFuture(peerConnection);
676 }
677 }
678
679 @Nonnull
680 private PeerConnection requirePeerConnection() {
681 final PeerConnection peerConnection = this.peerConnection;
682 if (peerConnection == null) {
683 throw new PeerConnectionNotInitialized();
684 }
685 return peerConnection;
686 }
687
688 public boolean applyDtmfTone(String tone) {
689 if (toneManager == null || peerConnection == null || peerConnection.getSenders().isEmpty()) {
690 return false;
691 }
692 peerConnection.getSenders().get(0).dtmf().insertDtmf(tone, TONE_DURATION, 100);
693 toneManager.startTone(TONE_CODES.get(tone), TONE_DURATION);
694 return true;
695 }
696
697 @Nonnull
698 private PeerConnectionFactory requirePeerConnectionFactory() {
699 final PeerConnectionFactory peerConnectionFactory = this.peerConnectionFactory;
700 if (peerConnectionFactory == null) {
701 throw new IllegalStateException("Make sure PeerConnectionFactory is initialized");
702 }
703 return peerConnectionFactory;
704 }
705
706 void addIceCandidate(IceCandidate iceCandidate) {
707 requirePeerConnection().addIceCandidate(iceCandidate);
708 }
709
710 PeerConnection.PeerConnectionState getState() {
711 return requirePeerConnection().connectionState();
712 }
713
714 public PeerConnection.SignalingState getSignalingState() {
715 try {
716 return requirePeerConnection().signalingState();
717 } catch (final IllegalStateException e) {
718 return PeerConnection.SignalingState.CLOSED;
719 }
720 }
721
722 EglBase.Context getEglBaseContext() {
723 return this.eglBase.getEglBaseContext();
724 }
725
726 Optional<VideoTrack> getLocalVideoTrack() {
727 return TrackWrapper.get(peerConnection, this.localVideoTrack);
728 }
729
730 Optional<VideoTrack> getRemoteVideoTrack() {
731 return Optional.fromNullable(this.remoteVideoTrack);
732 }
733
734 private Context requireContext() {
735 final Context context = this.context;
736 if (context == null) {
737 throw new IllegalStateException("call setup first");
738 }
739 return context;
740 }
741
742 AppRTCAudioManager getAudioManager() {
743 return appRTCAudioManager;
744 }
745
746 void execute(final Runnable command) {
747 executorService.execute(command);
748 }
749
750 public void switchSpeakerPhonePreference(AppRTCAudioManager.SpeakerPhonePreference preference) {
751 mainHandler.post(() -> appRTCAudioManager.switchSpeakerPhonePreference(preference));
752 }
753
754 public interface EventCallback {
755 void onIceCandidate(IceCandidate iceCandidate);
756
757 void onConnectionChange(PeerConnection.PeerConnectionState newState);
758
759 void onAudioDeviceChanged(
760 AppRTCAudioManager.AudioDevice selectedAudioDevice,
761 Set<AppRTCAudioManager.AudioDevice> availableAudioDevices);
762
763 void onRenegotiationNeeded();
764 }
765
766 private abstract static class SetSdpObserver implements SdpObserver {
767
768 @Override
769 public void onCreateSuccess(org.webrtc.SessionDescription sessionDescription) {
770 throw new IllegalStateException("Not able to use SetSdpObserver");
771 }
772
773 @Override
774 public void onCreateFailure(String s) {
775 throw new IllegalStateException("Not able to use SetSdpObserver");
776 }
777 }
778
779 static class InitializationException extends Exception {
780
781 private InitializationException(final String message, final Throwable throwable) {
782 super(message, throwable);
783 }
784
785 private InitializationException(final String message) {
786 super(message);
787 }
788 }
789
790 public static class PeerConnectionNotInitialized extends IllegalStateException {
791
792 private PeerConnectionNotInitialized() {
793 super("initialize PeerConnection first");
794 }
795 }
796
797 private static class FailureToSetDescriptionException extends IllegalArgumentException {
798 public FailureToSetDescriptionException(String message) {
799 super(message);
800 }
801 }
802}