WebRTCWrapper.java

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