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        while (ready && iceCandidates.peek() != null) {
460            eventCallback.onIceCandidate(iceCandidates.poll());
461        }
462    }
463
464    synchronized void close() {
465        final PeerConnection peerConnection = this.peerConnection;
466        final PeerConnectionFactory peerConnectionFactory = this.peerConnectionFactory;
467        final VideoSourceWrapper videoSourceWrapper = this.videoSourceWrapper;
468        final AppRTCAudioManager audioManager = this.appRTCAudioManager;
469        final EglBase eglBase = this.eglBase;
470        if (peerConnection != null) {
471            this.peerConnection = null;
472            dispose(peerConnection);
473        }
474        if (audioManager != null) {
475            toneManager.setAppRtcAudioManagerHasControl(false);
476            mainHandler.post(audioManager::stop);
477        }
478        this.localVideoTrack = null;
479        this.remoteVideoTrack = null;
480        if (videoSourceWrapper != null) {
481            try {
482                videoSourceWrapper.stopCapture();
483            } catch (final InterruptedException e) {
484                Log.e(Config.LOGTAG, "unable to stop capturing");
485            }
486            videoSourceWrapper.dispose();
487        }
488        if (eglBase != null) {
489            eglBase.release();
490            this.eglBase = null;
491        }
492        if (peerConnectionFactory != null) {
493            this.peerConnectionFactory = null;
494            peerConnectionFactory.dispose();
495        }
496    }
497
498    synchronized void verifyClosed() {
499        if (this.peerConnection != null
500                || this.eglBase != null
501                || this.localVideoTrack != null
502                || this.remoteVideoTrack != null) {
503            final IllegalStateException e =
504                    new IllegalStateException("WebRTCWrapper hasn't been closed properly");
505            Log.e(Config.LOGTAG, "verifyClosed() failed. Going to throw", e);
506            throw e;
507        }
508    }
509
510    boolean isCameraSwitchable() {
511        final VideoSourceWrapper videoSourceWrapper = this.videoSourceWrapper;
512        return videoSourceWrapper != null && videoSourceWrapper.isCameraSwitchable();
513    }
514
515    boolean isFrontCamera() {
516        final VideoSourceWrapper videoSourceWrapper = this.videoSourceWrapper;
517        return videoSourceWrapper == null || videoSourceWrapper.isFrontCamera();
518    }
519
520    ListenableFuture<Boolean> switchCamera() {
521        final VideoSourceWrapper videoSourceWrapper = this.videoSourceWrapper;
522        if (videoSourceWrapper == null) {
523            return Futures.immediateFailedFuture(
524                    new IllegalStateException("VideoSourceWrapper has not been initialized"));
525        }
526        return videoSourceWrapper.switchCamera();
527    }
528
529    boolean isMicrophoneEnabled() {
530        final Optional<AudioTrack> audioTrack =
531                TrackWrapper.get(peerConnection, this.localAudioTrack);
532        if (audioTrack.isPresent()) {
533            try {
534                return audioTrack.get().enabled();
535            } catch (final IllegalStateException e) {
536                // sometimes UI might still be rendering the buttons when a background thread has
537                // already ended the call
538                return false;
539            }
540        } else {
541            throw new IllegalStateException("Local audio track does not exist (yet)");
542        }
543    }
544
545    boolean setMicrophoneEnabled(final boolean enabled) {
546        final Optional<AudioTrack> audioTrack =
547                TrackWrapper.get(peerConnection, this.localAudioTrack);
548        if (audioTrack.isPresent()) {
549            try {
550                audioTrack.get().setEnabled(enabled);
551                return true;
552            } catch (final IllegalStateException e) {
553                Log.d(Config.LOGTAG, "unable to toggle microphone", e);
554                // ignoring race condition in case MediaStreamTrack has been disposed
555                return false;
556            }
557        } else {
558            throw new IllegalStateException("Local audio track does not exist (yet)");
559        }
560    }
561
562    boolean isVideoEnabled() {
563        final Optional<VideoTrack> videoTrack =
564                TrackWrapper.get(peerConnection, this.localVideoTrack);
565        if (videoTrack.isPresent()) {
566            return videoTrack.get().enabled();
567        }
568        return false;
569    }
570
571    void setVideoEnabled(final boolean enabled) {
572        final Optional<VideoTrack> videoTrack =
573                TrackWrapper.get(peerConnection, this.localVideoTrack);
574        if (videoTrack.isPresent()) {
575            videoTrack.get().setEnabled(enabled);
576            return;
577        }
578        throw new IllegalStateException("Local video track does not exist");
579    }
580
581    synchronized ListenableFuture<SessionDescription> setLocalDescription() {
582        return Futures.transformAsync(
583                getPeerConnectionFuture(),
584                peerConnection -> {
585                    if (peerConnection == null) {
586                        return Futures.immediateFailedFuture(
587                                new IllegalStateException("PeerConnection was null"));
588                    }
589                    final SettableFuture<SessionDescription> future = SettableFuture.create();
590                    peerConnection.setLocalDescription(
591                            new SetSdpObserver() {
592                                @Override
593                                public void onSetSuccess() {
594                                    final SessionDescription description =
595                                            peerConnection.getLocalDescription();
596                                    Log.d(EXTENDED_LOGGING_TAG, "set local description:");
597                                    logDescription(description);
598                                    future.set(description);
599                                }
600
601                                @Override
602                                public void onSetFailure(final String message) {
603                                    future.setException(
604                                            new FailureToSetDescriptionException(message));
605                                }
606                            });
607                    return future;
608                },
609                MoreExecutors.directExecutor());
610    }
611
612    public static void logDescription(final SessionDescription sessionDescription) {
613        for (final String line :
614                sessionDescription.description.split(
615                        eu.siacs.conversations.xmpp.jingle.SessionDescription.LINE_DIVIDER)) {
616            Log.d(EXTENDED_LOGGING_TAG, line);
617        }
618    }
619
620    synchronized ListenableFuture<Void> setRemoteDescription(
621            final SessionDescription sessionDescription) {
622        Log.d(EXTENDED_LOGGING_TAG, "setting remote description:");
623        logDescription(sessionDescription);
624        return Futures.transformAsync(
625                getPeerConnectionFuture(),
626                peerConnection -> {
627                    if (peerConnection == null) {
628                        return Futures.immediateFailedFuture(
629                                new IllegalStateException("PeerConnection was null"));
630                    }
631                    final SettableFuture<Void> future = SettableFuture.create();
632                    peerConnection.setRemoteDescription(
633                            new SetSdpObserver() {
634                                @Override
635                                public void onSetSuccess() {
636                                    future.set(null);
637                                }
638
639                                @Override
640                                public void onSetFailure(final String message) {
641                                    future.setException(
642                                            new FailureToSetDescriptionException(message));
643                                }
644                            },
645                            sessionDescription);
646                    return future;
647                },
648                MoreExecutors.directExecutor());
649    }
650
651    @Nonnull
652    private ListenableFuture<PeerConnection> getPeerConnectionFuture() {
653        final PeerConnection peerConnection = this.peerConnection;
654        if (peerConnection == null) {
655            return Futures.immediateFailedFuture(new PeerConnectionNotInitialized());
656        } else {
657            return Futures.immediateFuture(peerConnection);
658        }
659    }
660
661    @Nonnull
662    private PeerConnection requirePeerConnection() {
663        final PeerConnection peerConnection = this.peerConnection;
664        if (peerConnection == null) {
665            throw new PeerConnectionNotInitialized();
666        }
667        return peerConnection;
668    }
669
670    public boolean applyDtmfTone(String tone) {
671        if (toneManager == null || peerConnection == null || peerConnection.getSenders().isEmpty()) {
672            return false;
673        }
674        peerConnection.getSenders().get(0).dtmf().insertDtmf(tone, TONE_DURATION, 100);
675        toneManager.startTone(TONE_CODES.get(tone), TONE_DURATION);
676        return true;
677    }
678
679    @Nonnull
680    private PeerConnectionFactory requirePeerConnectionFactory() {
681        final PeerConnectionFactory peerConnectionFactory = this.peerConnectionFactory;
682        if (peerConnectionFactory == null) {
683            throw new IllegalStateException("Make sure PeerConnectionFactory is initialized");
684        }
685        return peerConnectionFactory;
686    }
687
688    void addIceCandidate(IceCandidate iceCandidate) {
689        requirePeerConnection().addIceCandidate(iceCandidate);
690    }
691
692    PeerConnection.PeerConnectionState getState() {
693        return requirePeerConnection().connectionState();
694    }
695
696    public PeerConnection.SignalingState getSignalingState() {
697        return requirePeerConnection().signalingState();
698    }
699
700    EglBase.Context getEglBaseContext() {
701        return this.eglBase.getEglBaseContext();
702    }
703
704    Optional<VideoTrack> getLocalVideoTrack() {
705        return TrackWrapper.get(peerConnection, this.localVideoTrack);
706    }
707
708    Optional<VideoTrack> getRemoteVideoTrack() {
709        return Optional.fromNullable(this.remoteVideoTrack);
710    }
711
712    private Context requireContext() {
713        final Context context = this.context;
714        if (context == null) {
715            throw new IllegalStateException("call setup first");
716        }
717        return context;
718    }
719
720    AppRTCAudioManager getAudioManager() {
721        return appRTCAudioManager;
722    }
723
724    void execute(final Runnable command) {
725        executorService.execute(command);
726    }
727
728    public void switchSpeakerPhonePreference(AppRTCAudioManager.SpeakerPhonePreference preference) {
729        mainHandler.post(() -> appRTCAudioManager.switchSpeakerPhonePreference(preference));
730    }
731
732    public interface EventCallback {
733        void onIceCandidate(IceCandidate iceCandidate);
734
735        void onConnectionChange(PeerConnection.PeerConnectionState newState);
736
737        void onAudioDeviceChanged(
738                AppRTCAudioManager.AudioDevice selectedAudioDevice,
739                Set<AppRTCAudioManager.AudioDevice> availableAudioDevices);
740
741        void onRenegotiationNeeded();
742    }
743
744    private abstract static class SetSdpObserver implements SdpObserver {
745
746        @Override
747        public void onCreateSuccess(org.webrtc.SessionDescription sessionDescription) {
748            throw new IllegalStateException("Not able to use SetSdpObserver");
749        }
750
751        @Override
752        public void onCreateFailure(String s) {
753            throw new IllegalStateException("Not able to use SetSdpObserver");
754        }
755    }
756
757    static class InitializationException extends Exception {
758
759        private InitializationException(final String message, final Throwable throwable) {
760            super(message, throwable);
761        }
762
763        private InitializationException(final String message) {
764            super(message);
765        }
766    }
767
768    public static class PeerConnectionNotInitialized extends IllegalStateException {
769
770        private PeerConnectionNotInitialized() {
771            super("initialize PeerConnection first");
772        }
773    }
774
775    private static class FailureToSetDescriptionException extends IllegalArgumentException {
776        public FailureToSetDescriptionException(String message) {
777            super(message);
778        }
779    }
780}