WebRTCWrapper.java

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