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