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