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
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 peerConnection = peerConnectionFactory.createPeerConnection(iceServers, peerConnectionObserver);
216 if (peerConnection == null) {
217 throw new InitializationException("Unable to create PeerConnection");
218 }
219 peerConnection.addStream(stream);
220 peerConnection.setAudioPlayout(true);
221 peerConnection.setAudioRecording(true);
222 this.peerConnection = peerConnection;
223 }
224
225 public void close() {
226 final PeerConnection peerConnection = this.peerConnection;
227 final CapturerChoice capturerChoice = this.capturerChoice;
228 final AppRTCAudioManager audioManager = this.appRTCAudioManager;
229 final EglBase eglBase = this.eglBase;
230 if (peerConnection != null) {
231 peerConnection.dispose();
232 this.peerConnection = null;
233 }
234 if (audioManager != null) {
235 mainHandler.post(audioManager::stop);
236 }
237 this.localVideoTrack = null;
238 this.remoteVideoTrack = null;
239 if (capturerChoice != null) {
240 try {
241 capturerChoice.cameraVideoCapturer.stopCapture();
242 } catch (InterruptedException e) {
243 Log.e(Config.LOGTAG, "unable to stop capturing");
244 }
245 }
246 if (eglBase != null) {
247 eglBase.release();
248 this.eglBase = null;
249 }
250 }
251
252 void verifyClosed() {
253 if (this.peerConnection != null
254 || this.eglBase != null
255 || this.localVideoTrack != null
256 || this.remoteVideoTrack != null) {
257 throw new IllegalStateException("WebRTCWrapper hasn't been closed properly");
258 }
259 }
260
261 boolean isMicrophoneEnabled() {
262 final AudioTrack audioTrack = this.localAudioTrack;
263 if (audioTrack == null) {
264 throw new IllegalStateException("Local audio track does not exist (yet)");
265 }
266 return audioTrack.enabled();
267 }
268
269 void setMicrophoneEnabled(final boolean enabled) {
270 final AudioTrack audioTrack = this.localAudioTrack;
271 if (audioTrack == null) {
272 throw new IllegalStateException("Local audio track does not exist (yet)");
273 }
274 audioTrack.setEnabled(enabled);
275 }
276
277 public boolean isVideoEnabled() {
278 final VideoTrack videoTrack = this.localVideoTrack;
279 if (videoTrack == null) {
280 throw new IllegalStateException("Local video track does not exist");
281 }
282 return videoTrack.enabled();
283 }
284
285 public void setVideoEnabled(final boolean enabled) {
286 final VideoTrack videoTrack = this.localVideoTrack;
287 if (videoTrack == null) {
288 throw new IllegalStateException("Local video track does not exist");
289 }
290 videoTrack.setEnabled(enabled);
291 }
292
293 public ListenableFuture<SessionDescription> createOffer() {
294 return Futures.transformAsync(getPeerConnectionFuture(), peerConnection -> {
295 final SettableFuture<SessionDescription> future = SettableFuture.create();
296 peerConnection.createOffer(new CreateSdpObserver() {
297 @Override
298 public void onCreateSuccess(SessionDescription sessionDescription) {
299 future.set(sessionDescription);
300 }
301
302 @Override
303 public void onCreateFailure(String s) {
304 Log.d(Config.LOGTAG, "create failure" + s);
305 future.setException(new IllegalStateException("Unable to create offer: " + s));
306 }
307 }, new MediaConstraints());
308 return future;
309 }, MoreExecutors.directExecutor());
310 }
311
312 public ListenableFuture<SessionDescription> createAnswer() {
313 return Futures.transformAsync(getPeerConnectionFuture(), peerConnection -> {
314 final SettableFuture<SessionDescription> future = SettableFuture.create();
315 peerConnection.createAnswer(new CreateSdpObserver() {
316 @Override
317 public void onCreateSuccess(SessionDescription sessionDescription) {
318 future.set(sessionDescription);
319 }
320
321 @Override
322 public void onCreateFailure(String s) {
323 future.setException(new IllegalStateException("Unable to create answer: " + s));
324 }
325 }, new MediaConstraints());
326 return future;
327 }, MoreExecutors.directExecutor());
328 }
329
330 public ListenableFuture<Void> setLocalDescription(final SessionDescription sessionDescription) {
331 Log.d(EXTENDED_LOGGING_TAG, "setting local description:");
332 for (final String line : sessionDescription.description.split(eu.siacs.conversations.xmpp.jingle.SessionDescription.LINE_DIVIDER)) {
333 Log.d(EXTENDED_LOGGING_TAG, line);
334 }
335 return Futures.transformAsync(getPeerConnectionFuture(), peerConnection -> {
336 final SettableFuture<Void> future = SettableFuture.create();
337 peerConnection.setLocalDescription(new SetSdpObserver() {
338 @Override
339 public void onSetSuccess() {
340 future.set(null);
341 }
342
343 @Override
344 public void onSetFailure(String s) {
345 Log.d(Config.LOGTAG, "unable to set local " + s);
346 future.setException(new IllegalArgumentException("unable to set local session description: " + s));
347
348 }
349 }, sessionDescription);
350 return future;
351 }, MoreExecutors.directExecutor());
352 }
353
354 public ListenableFuture<Void> setRemoteDescription(final SessionDescription sessionDescription) {
355 Log.d(EXTENDED_LOGGING_TAG, "setting remote description:");
356 for (final String line : sessionDescription.description.split(eu.siacs.conversations.xmpp.jingle.SessionDescription.LINE_DIVIDER)) {
357 Log.d(EXTENDED_LOGGING_TAG, line);
358 }
359 return Futures.transformAsync(getPeerConnectionFuture(), peerConnection -> {
360 final SettableFuture<Void> future = SettableFuture.create();
361 peerConnection.setRemoteDescription(new SetSdpObserver() {
362 @Override
363 public void onSetSuccess() {
364 future.set(null);
365 }
366
367 @Override
368 public void onSetFailure(String s) {
369 future.setException(new IllegalArgumentException("unable to set remote session description: " + s));
370
371 }
372 }, sessionDescription);
373 return future;
374 }, MoreExecutors.directExecutor());
375 }
376
377 @Nonnull
378 private ListenableFuture<PeerConnection> getPeerConnectionFuture() {
379 final PeerConnection peerConnection = this.peerConnection;
380 if (peerConnection == null) {
381 return Futures.immediateFailedFuture(new IllegalStateException("initialize PeerConnection first"));
382 } else {
383 return Futures.immediateFuture(peerConnection);
384 }
385 }
386
387 public void addIceCandidate(IceCandidate iceCandidate) {
388 requirePeerConnection().addIceCandidate(iceCandidate);
389 }
390
391 private CameraEnumerator getCameraEnumerator() {
392 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
393 return new Camera2Enumerator(requireContext());
394 } else {
395 return new Camera1Enumerator();
396 }
397 }
398
399 private Optional<CapturerChoice> getVideoCapturer() {
400 final CameraEnumerator enumerator = getCameraEnumerator();
401 final String[] deviceNames = enumerator.getDeviceNames();
402 for (final String deviceName : deviceNames) {
403 if (enumerator.isFrontFacing(deviceName)) {
404 return Optional.fromNullable(of(enumerator, deviceName));
405 }
406 }
407 if (deviceNames.length == 0) {
408 return Optional.absent();
409 } else {
410 return Optional.fromNullable(of(enumerator, deviceNames[0]));
411 }
412 }
413
414 @Nullable
415 private static CapturerChoice of(CameraEnumerator enumerator, final String deviceName) {
416 final CameraVideoCapturer capturer = enumerator.createCapturer(deviceName, null);
417 if (capturer == null) {
418 return null;
419 }
420 final ArrayList<CameraEnumerationAndroid.CaptureFormat> choices = new ArrayList<>(enumerator.getSupportedFormats(deviceName));
421 Collections.sort(choices, (a, b) -> b.width - a.width);
422 for (final CameraEnumerationAndroid.CaptureFormat captureFormat : choices) {
423 if (captureFormat.width <= CAPTURING_RESOLUTION) {
424 return new CapturerChoice(capturer, captureFormat);
425 }
426 }
427 return null;
428 }
429
430 public PeerConnection.PeerConnectionState getState() {
431 return requirePeerConnection().connectionState();
432 }
433
434 EglBase.Context getEglBaseContext() {
435 return this.eglBase.getEglBaseContext();
436 }
437
438 public Optional<VideoTrack> getLocalVideoTrack() {
439 return Optional.fromNullable(this.localVideoTrack);
440 }
441
442 public Optional<VideoTrack> getRemoteVideoTrack() {
443 return Optional.fromNullable(this.remoteVideoTrack);
444 }
445
446 private PeerConnection requirePeerConnection() {
447 final PeerConnection peerConnection = this.peerConnection;
448 if (peerConnection == null) {
449 throw new IllegalStateException("initialize PeerConnection first");
450 }
451 return peerConnection;
452 }
453
454 private Context requireContext() {
455 final Context context = this.context;
456 if (context == null) {
457 throw new IllegalStateException("call setup first");
458 }
459 return context;
460 }
461
462 public AppRTCAudioManager getAudioManager() {
463 return appRTCAudioManager;
464 }
465
466 public interface EventCallback {
467 void onIceCandidate(IceCandidate iceCandidate);
468
469 void onConnectionChange(PeerConnection.PeerConnectionState newState);
470
471 void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices);
472 }
473
474 private static abstract class SetSdpObserver implements SdpObserver {
475
476 @Override
477 public void onCreateSuccess(org.webrtc.SessionDescription sessionDescription) {
478 throw new IllegalStateException("Not able to use SetSdpObserver");
479 }
480
481 @Override
482 public void onCreateFailure(String s) {
483 throw new IllegalStateException("Not able to use SetSdpObserver");
484 }
485
486 }
487
488 private static abstract class CreateSdpObserver implements SdpObserver {
489
490
491 @Override
492 public void onSetSuccess() {
493 throw new IllegalStateException("Not able to use CreateSdpObserver");
494 }
495
496
497 @Override
498 public void onSetFailure(String s) {
499 throw new IllegalStateException("Not able to use CreateSdpObserver");
500 }
501 }
502
503 public static class InitializationException extends Exception {
504
505 private InitializationException(String message) {
506 super(message);
507 }
508 }
509
510 private static class CapturerChoice {
511 private final CameraVideoCapturer cameraVideoCapturer;
512 private final CameraEnumerationAndroid.CaptureFormat captureFormat;
513
514 public CapturerChoice(CameraVideoCapturer cameraVideoCapturer, CameraEnumerationAndroid.CaptureFormat captureFormat) {
515 this.cameraVideoCapturer = cameraVideoCapturer;
516 this.captureFormat = captureFormat;
517 }
518
519 public int getFrameRate() {
520 return Math.max(captureFormat.framerate.min, Math.min(CAPTURING_MAX_FRAME_RATE, captureFormat.framerate.max));
521 }
522 }
523}