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