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