WebRTCWrapper.java

  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        final Optional<AudioTrack> audioTrack =
537                TrackWrapper.get(peerConnection, this.localAudioTrack);
538        if (audioTrack.isPresent()) {
539            try {
540                return audioTrack.get().enabled();
541            } catch (final IllegalStateException e) {
542                // sometimes UI might still be rendering the buttons when a background thread has
543                // already ended the call
544                return false;
545            }
546        } else {
547            throw new IllegalStateException("Local audio track does not exist (yet)");
548        }
549    }
550
551    boolean setMicrophoneEnabled(final boolean enabled) {
552        final Optional<AudioTrack> audioTrack =
553                TrackWrapper.get(peerConnection, this.localAudioTrack);
554        if (audioTrack.isPresent()) {
555            try {
556                audioTrack.get().setEnabled(enabled);
557                return true;
558            } catch (final IllegalStateException e) {
559                Log.d(Config.LOGTAG, "unable to toggle microphone", e);
560                // ignoring race condition in case MediaStreamTrack has been disposed
561                return false;
562            }
563        } else {
564            throw new IllegalStateException("Local audio track does not exist (yet)");
565        }
566    }
567
568    boolean isVideoEnabled() {
569        final Optional<VideoTrack> videoTrack =
570                TrackWrapper.get(peerConnection, this.localVideoTrack);
571        if (videoTrack.isPresent()) {
572            return videoTrack.get().enabled();
573        }
574        return false;
575    }
576
577    void setVideoEnabled(final boolean enabled) {
578        final Optional<VideoTrack> videoTrack =
579                TrackWrapper.get(peerConnection, this.localVideoTrack);
580        if (videoTrack.isPresent()) {
581            videoTrack.get().setEnabled(enabled);
582            return;
583        }
584        throw new IllegalStateException("Local video track does not exist");
585    }
586
587    synchronized ListenableFuture<SessionDescription> setLocalDescription() {
588        return Futures.transformAsync(
589                getPeerConnectionFuture(),
590                peerConnection -> {
591                    if (peerConnection == null) {
592                        return Futures.immediateFailedFuture(
593                                new IllegalStateException("PeerConnection was null"));
594                    }
595                    final SettableFuture<SessionDescription> future = SettableFuture.create();
596                    peerConnection.setLocalDescription(
597                            new SetSdpObserver() {
598                                @Override
599                                public void onSetSuccess() {
600                                    final SessionDescription description =
601                                            peerConnection.getLocalDescription();
602                                    Log.d(EXTENDED_LOGGING_TAG, "set local description:");
603                                    logDescription(description);
604                                    future.set(description);
605                                }
606
607                                @Override
608                                public void onSetFailure(final String message) {
609                                    future.setException(
610                                            new FailureToSetDescriptionException(message));
611                                }
612                            });
613                    return future;
614                },
615                MoreExecutors.directExecutor());
616    }
617
618    public static void logDescription(final SessionDescription sessionDescription) {
619        for (final String line :
620                sessionDescription.description.split(
621                        eu.siacs.conversations.xmpp.jingle.SessionDescription.LINE_DIVIDER)) {
622            Log.d(EXTENDED_LOGGING_TAG, line);
623        }
624    }
625
626    synchronized ListenableFuture<Void> setRemoteDescription(
627            final SessionDescription sessionDescription) {
628        Log.d(EXTENDED_LOGGING_TAG, "setting remote description:");
629        logDescription(sessionDescription);
630        return Futures.transformAsync(
631                getPeerConnectionFuture(),
632                peerConnection -> {
633                    if (peerConnection == null) {
634                        return Futures.immediateFailedFuture(
635                                new IllegalStateException("PeerConnection was null"));
636                    }
637                    final SettableFuture<Void> future = SettableFuture.create();
638                    peerConnection.setRemoteDescription(
639                            new SetSdpObserver() {
640                                @Override
641                                public void onSetSuccess() {
642                                    future.set(null);
643                                }
644
645                                @Override
646                                public void onSetFailure(final String message) {
647                                    future.setException(
648                                            new FailureToSetDescriptionException(message));
649                                }
650                            },
651                            sessionDescription);
652                    return future;
653                },
654                MoreExecutors.directExecutor());
655    }
656
657    @Nonnull
658    private ListenableFuture<PeerConnection> getPeerConnectionFuture() {
659        final PeerConnection peerConnection = this.peerConnection;
660        if (peerConnection == null) {
661            return Futures.immediateFailedFuture(new PeerConnectionNotInitialized());
662        } else {
663            return Futures.immediateFuture(peerConnection);
664        }
665    }
666
667    @Nonnull
668    private PeerConnection requirePeerConnection() {
669        final PeerConnection peerConnection = this.peerConnection;
670        if (peerConnection == null) {
671            throw new PeerConnectionNotInitialized();
672        }
673        return peerConnection;
674    }
675
676    public boolean applyDtmfTone(String tone) {
677        if (toneManager == null || peerConnection == null || peerConnection.getSenders().isEmpty()) {
678            return false;
679        }
680        peerConnection.getSenders().get(0).dtmf().insertDtmf(tone, TONE_DURATION, 100);
681        toneManager.startTone(TONE_CODES.get(tone), TONE_DURATION);
682        return true;
683    }
684
685    @Nonnull
686    private PeerConnectionFactory requirePeerConnectionFactory() {
687        final PeerConnectionFactory peerConnectionFactory = this.peerConnectionFactory;
688        if (peerConnectionFactory == null) {
689            throw new IllegalStateException("Make sure PeerConnectionFactory is initialized");
690        }
691        return peerConnectionFactory;
692    }
693
694    void addIceCandidate(IceCandidate iceCandidate) {
695        requirePeerConnection().addIceCandidate(iceCandidate);
696    }
697
698    PeerConnection.PeerConnectionState getState() {
699        return requirePeerConnection().connectionState();
700    }
701
702    public PeerConnection.SignalingState getSignalingState() {
703        try {
704            return requirePeerConnection().signalingState();
705        } catch (final IllegalStateException e) {
706            return PeerConnection.SignalingState.CLOSED;
707        }
708    }
709
710    EglBase.Context getEglBaseContext() {
711        return this.eglBase.getEglBaseContext();
712    }
713
714    Optional<VideoTrack> getLocalVideoTrack() {
715        return TrackWrapper.get(peerConnection, this.localVideoTrack);
716    }
717
718    Optional<VideoTrack> getRemoteVideoTrack() {
719        return Optional.fromNullable(this.remoteVideoTrack);
720    }
721
722    private Context requireContext() {
723        final Context context = this.context;
724        if (context == null) {
725            throw new IllegalStateException("call setup first");
726        }
727        return context;
728    }
729
730    AppRTCAudioManager getAudioManager() {
731        return appRTCAudioManager;
732    }
733
734    void execute(final Runnable command) {
735        executorService.execute(command);
736    }
737
738    public void switchSpeakerPhonePreference(AppRTCAudioManager.SpeakerPhonePreference preference) {
739        mainHandler.post(() -> appRTCAudioManager.switchSpeakerPhonePreference(preference));
740    }
741
742    public interface EventCallback {
743        void onIceCandidate(IceCandidate iceCandidate);
744
745        void onConnectionChange(PeerConnection.PeerConnectionState newState);
746
747        void onAudioDeviceChanged(
748                AppRTCAudioManager.AudioDevice selectedAudioDevice,
749                Set<AppRTCAudioManager.AudioDevice> availableAudioDevices);
750
751        void onRenegotiationNeeded();
752    }
753
754    private abstract static class SetSdpObserver implements SdpObserver {
755
756        @Override
757        public void onCreateSuccess(org.webrtc.SessionDescription sessionDescription) {
758            throw new IllegalStateException("Not able to use SetSdpObserver");
759        }
760
761        @Override
762        public void onCreateFailure(String s) {
763            throw new IllegalStateException("Not able to use SetSdpObserver");
764        }
765    }
766
767    static class InitializationException extends Exception {
768
769        private InitializationException(final String message, final Throwable throwable) {
770            super(message, throwable);
771        }
772
773        private InitializationException(final String message) {
774            super(message);
775        }
776    }
777
778    public static class PeerConnectionNotInitialized extends IllegalStateException {
779
780        private PeerConnectionNotInitialized() {
781            super("initialize PeerConnection first");
782        }
783    }
784
785    private static class FailureToSetDescriptionException extends IllegalArgumentException {
786        public FailureToSetDescriptionException(String message) {
787            super(message);
788        }
789    }
790}