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            final List<VideoTrack> videoTracks = mediaStream.videoTracks;
140            if (videoTracks.size() > 0) {
141                remoteVideoTrack = videoTracks.get(0);
142                Log.d(Config.LOGTAG, "remote video track enabled?=" + remoteVideoTrack.enabled());
143            } else {
144                Log.d(Config.LOGTAG, "no remote video tracks found");
145            }
146        }
147
148        @Override
149        public void onRemoveStream(MediaStream mediaStream) {
150
151        }
152
153        @Override
154        public void onDataChannel(DataChannel dataChannel) {
155
156        }
157
158        @Override
159        public void onRenegotiationNeeded() {
160
161        }
162
163        @Override
164        public void onAddTrack(RtpReceiver rtpReceiver, MediaStream[] mediaStreams) {
165            final MediaStreamTrack track = rtpReceiver.track();
166            Log.d(EXTENDED_LOGGING_TAG, "onAddTrack(kind=" + (track == null ? "null" : track.kind()) + ",numMediaStreams=" + mediaStreams.length + ")");
167        }
168
169        @Override
170        public void onTrack(RtpTransceiver transceiver) {
171            Log.d(EXTENDED_LOGGING_TAG, "onTrack(mid=" + transceiver.getMid() + ",media=" + transceiver.getMediaType() + ")");
172        }
173    };
174    @Nullable
175    private PeerConnection peerConnection = null;
176    private AudioTrack localAudioTrack = null;
177    private AppRTCAudioManager appRTCAudioManager = null;
178    private ToneManager toneManager = null;
179    private Context context = null;
180    private EglBase eglBase = null;
181    private CapturerChoice capturerChoice;
182
183    WebRTCWrapper(final EventCallback eventCallback) {
184        this.eventCallback = eventCallback;
185    }
186
187    private static void dispose(final PeerConnection peerConnection) {
188        try {
189            peerConnection.dispose();
190        } catch (final IllegalStateException e) {
191            Log.e(Config.LOGTAG, "unable to dispose of peer connection", e);
192        }
193    }
194
195    @Nullable
196    private static CapturerChoice of(CameraEnumerator enumerator, final String deviceName, Set<String> availableCameras) {
197        final CameraVideoCapturer capturer = enumerator.createCapturer(deviceName, null);
198        if (capturer == null) {
199            return null;
200        }
201        final ArrayList<CameraEnumerationAndroid.CaptureFormat> choices = new ArrayList<>(enumerator.getSupportedFormats(deviceName));
202        Collections.sort(choices, (a, b) -> b.width - a.width);
203        for (final CameraEnumerationAndroid.CaptureFormat captureFormat : choices) {
204            if (captureFormat.width <= CAPTURING_RESOLUTION) {
205                return new CapturerChoice(capturer, captureFormat, availableCameras);
206            }
207        }
208        return null;
209    }
210
211    public void setup(final XmppConnectionService service, final AppRTCAudioManager.SpeakerPhonePreference speakerPhonePreference) throws InitializationException {
212        try {
213            PeerConnectionFactory.initialize(
214                    PeerConnectionFactory.InitializationOptions.builder(service).createInitializationOptions()
215            );
216        } catch (final UnsatisfiedLinkError e) {
217            throw new InitializationException("Unable to initialize PeerConnectionFactory", e);
218        }
219        try {
220            this.eglBase = EglBase.create();
221        } catch (final RuntimeException e) {
222            throw new InitializationException("Unable to create EGL base", e);
223        }
224        this.context = service;
225        this.toneManager = service.getJingleConnectionManager().toneManager;
226        mainHandler.post(() -> {
227            appRTCAudioManager = AppRTCAudioManager.create(service, speakerPhonePreference);
228            toneManager.setAppRtcAudioManagerHasControl(true);
229            appRTCAudioManager.start(audioManagerEvents);
230            eventCallback.onAudioDeviceChanged(appRTCAudioManager.getSelectedAudioDevice(), appRTCAudioManager.getAudioDevices());
231        });
232    }
233
234    synchronized void initializePeerConnection(final Set<Media> media, final List<PeerConnection.IceServer> iceServers) throws InitializationException {
235        Preconditions.checkState(this.eglBase != null);
236        Preconditions.checkNotNull(media);
237        Preconditions.checkArgument(media.size() > 0, "media can not be empty when initializing peer connection");
238        final boolean setUseHardwareAcousticEchoCanceler = WebRtcAudioEffects.canUseAcousticEchoCanceler() && !HARDWARE_AEC_BLACKLIST.contains(Build.MODEL);
239        Log.d(Config.LOGTAG, String.format("setUseHardwareAcousticEchoCanceler(%s) model=%s", setUseHardwareAcousticEchoCanceler, Build.MODEL));
240        PeerConnectionFactory peerConnectionFactory = PeerConnectionFactory.builder()
241                .setVideoDecoderFactory(new DefaultVideoDecoderFactory(eglBase.getEglBaseContext()))
242                .setVideoEncoderFactory(new DefaultVideoEncoderFactory(eglBase.getEglBaseContext(), true, true))
243                .setAudioDeviceModule(JavaAudioDeviceModule.builder(context)
244                        .setUseHardwareAcousticEchoCanceler(setUseHardwareAcousticEchoCanceler)
245                        .createAudioDeviceModule()
246                )
247                .createPeerConnectionFactory();
248
249
250        final MediaStream stream = peerConnectionFactory.createLocalMediaStream("my-media-stream");
251
252        final Optional<CapturerChoice> optionalCapturerChoice = media.contains(Media.VIDEO) ? getVideoCapturer() : Optional.absent();
253
254        if (optionalCapturerChoice.isPresent()) {
255            this.capturerChoice = optionalCapturerChoice.get();
256            final CameraVideoCapturer capturer = this.capturerChoice.cameraVideoCapturer;
257            final VideoSource videoSource = peerConnectionFactory.createVideoSource(false);
258            SurfaceTextureHelper surfaceTextureHelper = SurfaceTextureHelper.create("webrtc", eglBase.getEglBaseContext());
259            capturer.initialize(surfaceTextureHelper, requireContext(), videoSource.getCapturerObserver());
260            Log.d(Config.LOGTAG, String.format("start capturing at %dx%d@%d", capturerChoice.captureFormat.width, capturerChoice.captureFormat.height, capturerChoice.getFrameRate()));
261            capturer.startCapture(capturerChoice.captureFormat.width, capturerChoice.captureFormat.height, capturerChoice.getFrameRate());
262
263            this.localVideoTrack = peerConnectionFactory.createVideoTrack("my-video-track", videoSource);
264
265            stream.addTrack(this.localVideoTrack);
266        }
267
268
269        if (media.contains(Media.AUDIO)) {
270            //set up audio track
271            final AudioSource audioSource = peerConnectionFactory.createAudioSource(new MediaConstraints());
272            this.localAudioTrack = peerConnectionFactory.createAudioTrack("my-audio-track", audioSource);
273            stream.addTrack(this.localAudioTrack);
274        }
275
276
277        final PeerConnection.RTCConfiguration rtcConfig = new PeerConnection.RTCConfiguration(iceServers);
278        rtcConfig.tcpCandidatePolicy = PeerConnection.TcpCandidatePolicy.DISABLED; //XEP-0176 doesn't support tcp
279        rtcConfig.continualGatheringPolicy = PeerConnection.ContinualGatheringPolicy.GATHER_CONTINUALLY;
280        final PeerConnection peerConnection = peerConnectionFactory.createPeerConnection(rtcConfig, peerConnectionObserver);
281        if (peerConnection == null) {
282            throw new InitializationException("Unable to create PeerConnection");
283        }
284        peerConnection.addStream(stream);
285        peerConnection.setAudioPlayout(true);
286        peerConnection.setAudioRecording(true);
287        this.peerConnection = peerConnection;
288    }
289
290    synchronized void close() {
291        final PeerConnection peerConnection = this.peerConnection;
292        final CapturerChoice capturerChoice = this.capturerChoice;
293        final AppRTCAudioManager audioManager = this.appRTCAudioManager;
294        final EglBase eglBase = this.eglBase;
295        if (peerConnection != null) {
296            dispose(peerConnection);
297            this.peerConnection = null;
298        }
299        if (audioManager != null) {
300            toneManager.setAppRtcAudioManagerHasControl(false);
301            mainHandler.post(audioManager::stop);
302        }
303        this.localVideoTrack = null;
304        this.remoteVideoTrack = null;
305        if (capturerChoice != null) {
306            try {
307                capturerChoice.cameraVideoCapturer.stopCapture();
308            } catch (InterruptedException e) {
309                Log.e(Config.LOGTAG, "unable to stop capturing");
310            }
311        }
312        if (eglBase != null) {
313            eglBase.release();
314            this.eglBase = null;
315        }
316    }
317
318    synchronized void verifyClosed() {
319        if (this.peerConnection != null
320                || this.eglBase != null
321                || this.localVideoTrack != null
322                || this.remoteVideoTrack != null) {
323            final IllegalStateException e = new IllegalStateException("WebRTCWrapper hasn't been closed properly");
324            Log.e(Config.LOGTAG, "verifyClosed() failed. Going to throw", e);
325            throw e;
326        }
327    }
328
329    boolean isCameraSwitchable() {
330        final CapturerChoice capturerChoice = this.capturerChoice;
331        return capturerChoice != null && capturerChoice.availableCameras.size() > 1;
332    }
333
334    boolean isFrontCamera() {
335        final CapturerChoice capturerChoice = this.capturerChoice;
336        return capturerChoice == null || capturerChoice.isFrontCamera;
337    }
338
339    ListenableFuture<Boolean> switchCamera() {
340        final CapturerChoice capturerChoice = this.capturerChoice;
341        if (capturerChoice == null) {
342            return Futures.immediateFailedFuture(new IllegalStateException("CameraCapturer has not been initialized"));
343        }
344        final SettableFuture<Boolean> future = SettableFuture.create();
345        capturerChoice.cameraVideoCapturer.switchCamera(new CameraVideoCapturer.CameraSwitchHandler() {
346            @Override
347            public void onCameraSwitchDone(boolean isFrontCamera) {
348                capturerChoice.isFrontCamera = isFrontCamera;
349                future.set(isFrontCamera);
350            }
351
352            @Override
353            public void onCameraSwitchError(final String message) {
354                future.setException(new IllegalStateException(String.format("Unable to switch camera %s", message)));
355            }
356        });
357        return future;
358    }
359
360    boolean isMicrophoneEnabled() {
361        final AudioTrack audioTrack = this.localAudioTrack;
362        if (audioTrack == null) {
363            throw new IllegalStateException("Local audio track does not exist (yet)");
364        }
365        try {
366            return audioTrack.enabled();
367        } catch (final IllegalStateException e) {
368            //sometimes UI might still be rendering the buttons when a background thread has already ended the call
369            return false;
370        }
371    }
372
373    boolean setMicrophoneEnabled(final boolean enabled) {
374        final AudioTrack audioTrack = this.localAudioTrack;
375        if (audioTrack == null) {
376            throw new IllegalStateException("Local audio track does not exist (yet)");
377        }
378        try {
379            audioTrack.setEnabled(enabled);
380            return true;
381        } catch (final IllegalStateException e) {
382            Log.d(Config.LOGTAG, "unable to toggle microphone", e);
383            //ignoring race condition in case MediaStreamTrack has been disposed
384            return false;
385        }
386    }
387
388    boolean isVideoEnabled() {
389        final VideoTrack videoTrack = this.localVideoTrack;
390        if (videoTrack == null) {
391            throw new IllegalStateException("Local video track does not exist");
392        }
393        return videoTrack.enabled();
394    }
395
396    void setVideoEnabled(final boolean enabled) {
397        final VideoTrack videoTrack = this.localVideoTrack;
398        if (videoTrack == null) {
399            throw new IllegalStateException("Local video track does not exist");
400        }
401        videoTrack.setEnabled(enabled);
402    }
403
404    ListenableFuture<SessionDescription> createOffer() {
405        return Futures.transformAsync(getPeerConnectionFuture(), peerConnection -> {
406            final SettableFuture<SessionDescription> future = SettableFuture.create();
407            peerConnection.createOffer(new CreateSdpObserver() {
408                @Override
409                public void onCreateSuccess(SessionDescription sessionDescription) {
410                    future.set(sessionDescription);
411                }
412
413                @Override
414                public void onCreateFailure(String s) {
415                    future.setException(new IllegalStateException("Unable to create offer: " + s));
416                }
417            }, new MediaConstraints());
418            return future;
419        }, MoreExecutors.directExecutor());
420    }
421
422    ListenableFuture<SessionDescription> createAnswer() {
423        return Futures.transformAsync(getPeerConnectionFuture(), peerConnection -> {
424            final SettableFuture<SessionDescription> future = SettableFuture.create();
425            peerConnection.createAnswer(new CreateSdpObserver() {
426                @Override
427                public void onCreateSuccess(SessionDescription sessionDescription) {
428                    future.set(sessionDescription);
429                }
430
431                @Override
432                public void onCreateFailure(String s) {
433                    future.setException(new IllegalStateException("Unable to create answer: " + s));
434                }
435            }, new MediaConstraints());
436            return future;
437        }, MoreExecutors.directExecutor());
438    }
439
440    ListenableFuture<Void> setLocalDescription(final SessionDescription sessionDescription) {
441        Log.d(EXTENDED_LOGGING_TAG, "setting local description:");
442        for (final String line : sessionDescription.description.split(eu.siacs.conversations.xmpp.jingle.SessionDescription.LINE_DIVIDER)) {
443            Log.d(EXTENDED_LOGGING_TAG, line);
444        }
445        return Futures.transformAsync(getPeerConnectionFuture(), peerConnection -> {
446            final SettableFuture<Void> future = SettableFuture.create();
447            peerConnection.setLocalDescription(new SetSdpObserver() {
448                @Override
449                public void onSetSuccess() {
450                    future.set(null);
451                }
452
453                @Override
454                public void onSetFailure(final String s) {
455                    future.setException(new IllegalArgumentException("unable to set local session description: " + s));
456
457                }
458            }, sessionDescription);
459            return future;
460        }, MoreExecutors.directExecutor());
461    }
462
463    ListenableFuture<Void> setRemoteDescription(final SessionDescription sessionDescription) {
464        Log.d(EXTENDED_LOGGING_TAG, "setting remote description:");
465        for (final String line : sessionDescription.description.split(eu.siacs.conversations.xmpp.jingle.SessionDescription.LINE_DIVIDER)) {
466            Log.d(EXTENDED_LOGGING_TAG, line);
467        }
468        return Futures.transformAsync(getPeerConnectionFuture(), peerConnection -> {
469            final SettableFuture<Void> future = SettableFuture.create();
470            peerConnection.setRemoteDescription(new SetSdpObserver() {
471                @Override
472                public void onSetSuccess() {
473                    future.set(null);
474                }
475
476                @Override
477                public void onSetFailure(String s) {
478                    future.setException(new IllegalArgumentException("unable to set remote session description: " + s));
479
480                }
481            }, sessionDescription);
482            return future;
483        }, MoreExecutors.directExecutor());
484    }
485
486    @Nonnull
487    private ListenableFuture<PeerConnection> getPeerConnectionFuture() {
488        final PeerConnection peerConnection = this.peerConnection;
489        if (peerConnection == null) {
490            return Futures.immediateFailedFuture(new IllegalStateException("initialize PeerConnection first"));
491        } else {
492            return Futures.immediateFuture(peerConnection);
493        }
494    }
495
496    void addIceCandidate(IceCandidate iceCandidate) {
497        requirePeerConnection().addIceCandidate(iceCandidate);
498    }
499
500    private CameraEnumerator getCameraEnumerator() {
501        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
502            return new Camera2Enumerator(requireContext());
503        } else {
504            return new Camera1Enumerator();
505        }
506    }
507
508    private Optional<CapturerChoice> getVideoCapturer() {
509        final CameraEnumerator enumerator = getCameraEnumerator();
510        final Set<String> deviceNames = ImmutableSet.copyOf(enumerator.getDeviceNames());
511        for (final String deviceName : deviceNames) {
512            if (isFrontFacing(enumerator, deviceName)) {
513                final CapturerChoice capturerChoice = of(enumerator, deviceName, deviceNames);
514                if (capturerChoice == null) {
515                    return Optional.absent();
516                }
517                capturerChoice.isFrontCamera = true;
518                return Optional.of(capturerChoice);
519            }
520        }
521        if (deviceNames.size() == 0) {
522            return Optional.absent();
523        } else {
524            return Optional.fromNullable(of(enumerator, Iterables.get(deviceNames, 0), deviceNames));
525        }
526    }
527
528    private static boolean isFrontFacing(final CameraEnumerator cameraEnumerator, final String deviceName) {
529        try {
530            return cameraEnumerator.isFrontFacing(deviceName);
531        } catch (final NullPointerException e) {
532            return false;
533        }
534    }
535
536    public PeerConnection.PeerConnectionState getState() {
537        return requirePeerConnection().connectionState();
538    }
539
540    EglBase.Context getEglBaseContext() {
541        return this.eglBase.getEglBaseContext();
542    }
543
544    Optional<VideoTrack> getLocalVideoTrack() {
545        return Optional.fromNullable(this.localVideoTrack);
546    }
547
548    Optional<VideoTrack> getRemoteVideoTrack() {
549        return Optional.fromNullable(this.remoteVideoTrack);
550    }
551
552    private PeerConnection requirePeerConnection() {
553        final PeerConnection peerConnection = this.peerConnection;
554        if (peerConnection == null) {
555            throw new IllegalStateException("initialize PeerConnection first");
556        }
557        return peerConnection;
558    }
559
560    private Context requireContext() {
561        final Context context = this.context;
562        if (context == null) {
563            throw new IllegalStateException("call setup first");
564        }
565        return context;
566    }
567
568    AppRTCAudioManager getAudioManager() {
569        return appRTCAudioManager;
570    }
571
572    public interface EventCallback {
573        void onIceCandidate(IceCandidate iceCandidate);
574
575        void onConnectionChange(PeerConnection.PeerConnectionState newState);
576
577        void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices);
578    }
579
580    private static abstract class SetSdpObserver implements SdpObserver {
581
582        @Override
583        public void onCreateSuccess(org.webrtc.SessionDescription sessionDescription) {
584            throw new IllegalStateException("Not able to use SetSdpObserver");
585        }
586
587        @Override
588        public void onCreateFailure(String s) {
589            throw new IllegalStateException("Not able to use SetSdpObserver");
590        }
591
592    }
593
594    private static abstract class CreateSdpObserver implements SdpObserver {
595
596
597        @Override
598        public void onSetSuccess() {
599            throw new IllegalStateException("Not able to use CreateSdpObserver");
600        }
601
602
603        @Override
604        public void onSetFailure(String s) {
605            throw new IllegalStateException("Not able to use CreateSdpObserver");
606        }
607    }
608
609    static class InitializationException extends Exception {
610
611        private InitializationException(final String message, final Throwable throwable) {
612            super(message, throwable);
613        }
614
615        private InitializationException(final String message) {
616            super(message);
617        }
618    }
619
620    private static class CapturerChoice {
621        private final CameraVideoCapturer cameraVideoCapturer;
622        private final CameraEnumerationAndroid.CaptureFormat captureFormat;
623        private final Set<String> availableCameras;
624        private boolean isFrontCamera = false;
625
626        CapturerChoice(CameraVideoCapturer cameraVideoCapturer, CameraEnumerationAndroid.CaptureFormat captureFormat, Set<String> cameras) {
627            this.cameraVideoCapturer = cameraVideoCapturer;
628            this.captureFormat = captureFormat;
629            this.availableCameras = cameras;
630        }
631
632        int getFrameRate() {
633            return Math.max(captureFormat.framerate.min, Math.min(CAPTURING_MAX_FRAME_RATE, captureFormat.framerate.max));
634        }
635    }
636}