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