1package eu.siacs.conversations.ui;
2
3import android.Manifest;
4import android.annotation.SuppressLint;
5import android.app.PictureInPictureParams;
6import android.content.Context;
7import android.content.Intent;
8import android.content.pm.PackageManager;
9import android.databinding.DataBindingUtil;
10import android.os.Build;
11import android.os.Bundle;
12import android.os.PowerManager;
13import android.os.SystemClock;
14import android.support.annotation.NonNull;
15import android.support.annotation.RequiresApi;
16import android.support.annotation.StringRes;
17import android.util.Log;
18import android.util.Rational;
19import android.view.View;
20import android.view.WindowManager;
21import android.widget.Toast;
22
23import com.google.common.base.Optional;
24import com.google.common.base.Preconditions;
25import com.google.common.base.Throwables;
26import com.google.common.collect.ImmutableList;
27import com.google.common.collect.ImmutableSet;
28import com.google.common.util.concurrent.FutureCallback;
29import com.google.common.util.concurrent.Futures;
30import com.google.common.util.concurrent.ListenableFuture;
31
32import org.checkerframework.checker.nullness.compatqual.NullableDecl;
33import org.webrtc.SurfaceViewRenderer;
34import org.webrtc.VideoTrack;
35
36import java.lang.ref.WeakReference;
37import java.util.Arrays;
38import java.util.Collections;
39import java.util.List;
40import java.util.Set;
41
42import eu.siacs.conversations.Config;
43import eu.siacs.conversations.R;
44import eu.siacs.conversations.databinding.ActivityRtpSessionBinding;
45import eu.siacs.conversations.entities.Account;
46import eu.siacs.conversations.entities.Contact;
47import eu.siacs.conversations.services.AppRTCAudioManager;
48import eu.siacs.conversations.services.XmppConnectionService;
49import eu.siacs.conversations.ui.util.AvatarWorkerTask;
50import eu.siacs.conversations.ui.util.MainThreadExecutor;
51import eu.siacs.conversations.utils.PermissionUtils;
52import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
53import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
54import eu.siacs.conversations.xmpp.jingle.Media;
55import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
56import rocks.xmpp.addr.Jid;
57
58import static eu.siacs.conversations.utils.PermissionUtils.getFirstDenied;
59import static java.util.Arrays.asList;
60
61public class RtpSessionActivity extends XmppActivity implements XmppConnectionService.OnJingleRtpConnectionUpdate {
62
63 public static final String EXTRA_WITH = "with";
64 public static final String EXTRA_SESSION_ID = "session_id";
65 public static final String EXTRA_LAST_REPORTED_STATE = "last_reported_state";
66 public static final String EXTRA_LAST_ACTION = "last_action";
67 public static final String ACTION_ACCEPT_CALL = "action_accept_call";
68 public static final String ACTION_MAKE_VOICE_CALL = "action_make_voice_call";
69 public static final String ACTION_MAKE_VIDEO_CALL = "action_make_video_call";
70 private static final List<RtpEndUserState> END_CARD = Arrays.asList(
71 RtpEndUserState.APPLICATION_ERROR,
72 RtpEndUserState.DECLINED_OR_BUSY,
73 RtpEndUserState.CONNECTIVITY_ERROR
74 );
75 private static final String PROXIMITY_WAKE_LOCK_TAG = "conversations:in-rtp-session";
76 private static final int REQUEST_ACCEPT_CALL = 0x1111;
77 private WeakReference<JingleRtpConnection> rtpConnectionReference;
78
79 private ActivityRtpSessionBinding binding;
80 private PowerManager.WakeLock mProximityWakeLock;
81
82 private static Set<Media> actionToMedia(final String action) {
83 if (ACTION_MAKE_VIDEO_CALL.equals(action)) {
84 return ImmutableSet.of(Media.AUDIO, Media.VIDEO);
85 } else {
86 return ImmutableSet.of(Media.AUDIO);
87 }
88 }
89
90 @Override
91 public void onCreate(Bundle savedInstanceState) {
92 super.onCreate(savedInstanceState);
93 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
94 | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
95 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
96 | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
97 this.binding = DataBindingUtil.setContentView(this, R.layout.activity_rtp_session);
98 setSupportActionBar(binding.toolbar);
99 }
100
101 private void endCall(View view) {
102 endCall();
103 }
104
105 private void endCall() {
106 if (this.rtpConnectionReference == null) {
107 retractSessionProposal();
108 finish();
109 } else {
110 requireRtpConnection().endCall();
111 }
112 }
113
114 private void retractSessionProposal() {
115 final Intent intent = getIntent();
116 final String action = intent.getAction();
117 final Account account = extractAccount(intent);
118 final Jid with = Jid.of(intent.getStringExtra(EXTRA_WITH));
119 final String state = intent.getStringExtra(EXTRA_LAST_REPORTED_STATE);
120 if (!Intent.ACTION_VIEW.equals(action) || state == null || !END_CARD.contains(RtpEndUserState.valueOf(state))) {
121 resetIntent(account, with, RtpEndUserState.RETRACTED, actionToMedia(intent.getAction()));
122 }
123 xmppConnectionService.getJingleConnectionManager().retractSessionProposal(account, with.asBareJid());
124 }
125
126 private void rejectCall(View view) {
127 requireRtpConnection().rejectCall();
128 finish();
129 }
130
131 private void acceptCall(View view) {
132 requestPermissionsAndAcceptCall();
133 }
134
135 private void requestPermissionsAndAcceptCall() {
136 final List<String> permissions;
137 if (getMedia().contains(Media.VIDEO)) {
138 permissions = ImmutableList.of(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO);
139 } else {
140 permissions = ImmutableList.of(Manifest.permission.RECORD_AUDIO);
141 }
142 if (PermissionUtils.hasPermission(this, permissions, REQUEST_ACCEPT_CALL)) {
143 putScreenInCallMode();
144 checkRecorderAndAcceptCall();
145 }
146 }
147
148 private void checkRecorderAndAcceptCall() {
149 checkMicrophoneAvailability();
150 requireRtpConnection().acceptCall();
151 }
152
153 private void checkMicrophoneAvailability() {
154 new Thread(() -> {
155 final long start = SystemClock.elapsedRealtime();
156 final boolean isMicrophoneAvailable = AppRTCAudioManager.isMicrophoneAvailable();
157 final long stop = SystemClock.elapsedRealtime();
158 Log.d(Config.LOGTAG, "checking microphone availability took " + (stop - start) + "ms");
159 if (isMicrophoneAvailable) {
160 return;
161 }
162 runOnUiThread(() -> Toast.makeText(this, R.string.microphone_unavailable, Toast.LENGTH_LONG).show());
163 }
164 ).start();
165 }
166
167 private void putScreenInCallMode() {
168 putScreenInCallMode(requireRtpConnection().getMedia());
169 }
170
171 private void putScreenInCallMode(final Set<Media> media) {
172 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
173 if (!media.contains(Media.VIDEO)) {
174 final JingleRtpConnection rtpConnection = rtpConnectionReference != null ? rtpConnectionReference.get() : null;
175 final AppRTCAudioManager audioManager = rtpConnection == null ? null : rtpConnection.getAudioManager();
176 if (audioManager == null || audioManager.getSelectedAudioDevice() == AppRTCAudioManager.AudioDevice.EARPIECE) {
177 acquireProximityWakeLock();
178 }
179 }
180 }
181
182 @SuppressLint("WakelockTimeout")
183 private void acquireProximityWakeLock() {
184 final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
185 if (powerManager == null) {
186 Log.e(Config.LOGTAG, "power manager not available");
187 return;
188 }
189 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
190 if (this.mProximityWakeLock == null) {
191 this.mProximityWakeLock = powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, PROXIMITY_WAKE_LOCK_TAG);
192 }
193 if (!this.mProximityWakeLock.isHeld()) {
194 Log.d(Config.LOGTAG, "acquiring proximity wake lock");
195 this.mProximityWakeLock.acquire();
196 }
197 }
198 }
199
200 private void releaseProximityWakeLock() {
201 if (this.mProximityWakeLock != null && mProximityWakeLock.isHeld()) {
202 Log.d(Config.LOGTAG, "releasing proximity wake lock");
203 this.mProximityWakeLock.release();
204 this.mProximityWakeLock = null;
205 }
206 }
207
208 private void putProximityWakeLockInProperState() {
209 if (requireRtpConnection().getAudioManager().getSelectedAudioDevice() == AppRTCAudioManager.AudioDevice.EARPIECE) {
210 acquireProximityWakeLock();
211 } else {
212 releaseProximityWakeLock();
213 }
214 }
215
216 @Override
217 protected void refreshUiReal() {
218
219 }
220
221 @Override
222 public void onNewIntent(final Intent intent) {
223 Log.d(Config.LOGTAG, this.getClass().getName() + ".onNewIntent()");
224 super.onNewIntent(intent);
225 setIntent(intent);
226 if (xmppConnectionService == null) {
227 Log.d(Config.LOGTAG, "RtpSessionActivity: background service wasn't bound in onNewIntent()");
228 return;
229 }
230 final Account account = extractAccount(intent);
231 final Jid with = Jid.of(intent.getStringExtra(EXTRA_WITH));
232 final String sessionId = intent.getStringExtra(EXTRA_SESSION_ID);
233 if (sessionId != null) {
234 Log.d(Config.LOGTAG, "reinitializing from onNewIntent()");
235 if (initializeActivityWithRunningRtpSession(account, with, sessionId)) {
236 return;
237 }
238 if (ACTION_ACCEPT_CALL.equals(intent.getAction())) {
239 Log.d(Config.LOGTAG, "accepting call from onNewIntent()");
240 requestPermissionsAndAcceptCall();
241 resetIntent(intent.getExtras());
242 }
243 } else {
244 throw new IllegalStateException("received onNewIntent without sessionId");
245 }
246 }
247
248 @Override
249 void onBackendConnected() {
250 final Intent intent = getIntent();
251 final String action = intent.getAction();
252 final Account account = extractAccount(intent);
253 final Jid with = Jid.of(intent.getStringExtra(EXTRA_WITH));
254 final String sessionId = intent.getStringExtra(EXTRA_SESSION_ID);
255 if (sessionId != null) {
256 if (initializeActivityWithRunningRtpSession(account, with, sessionId)) {
257 return;
258 }
259 if (ACTION_ACCEPT_CALL.equals(intent.getAction())) {
260 Log.d(Config.LOGTAG, "intent action was accept");
261 requestPermissionsAndAcceptCall();
262 resetIntent(intent.getExtras());
263 }
264 } else if (asList(ACTION_MAKE_VIDEO_CALL, ACTION_MAKE_VOICE_CALL).contains(action)) {
265 proposeJingleRtpSession(account, with, actionToMedia(action));
266 binding.with.setText(account.getRoster().getContact(with).getDisplayName());
267 } else if (Intent.ACTION_VIEW.equals(action)) {
268 final String extraLastState = intent.getStringExtra(EXTRA_LAST_REPORTED_STATE);
269 if (extraLastState != null) {
270 Log.d(Config.LOGTAG, "restored last state from intent extra");
271 RtpEndUserState state = RtpEndUserState.valueOf(extraLastState);
272 updateButtonConfiguration(state);
273 updateStateDisplay(state);
274 updateProfilePicture(state);
275 }
276 binding.with.setText(account.getRoster().getContact(with).getDisplayName());
277 }
278 }
279
280 private void proposeJingleRtpSession(final Account account, final Jid with, final Set<Media> media) {
281 checkMicrophoneAvailability();
282 xmppConnectionService.getJingleConnectionManager().proposeJingleRtpSession(account, with, media);
283 putScreenInCallMode(media);
284 }
285
286 @Override
287 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
288 super.onRequestPermissionsResult(requestCode, permissions, grantResults);
289 if (PermissionUtils.allGranted(grantResults)) {
290 if (requestCode == REQUEST_ACCEPT_CALL) {
291 checkRecorderAndAcceptCall();
292 }
293 } else {
294 @StringRes int res;
295 final String firstDenied = getFirstDenied(grantResults, permissions);
296 if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
297 res = R.string.no_microphone_permission;
298 } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
299 res = R.string.no_camera_permission;
300 } else {
301 throw new IllegalStateException("Invalid permission result request");
302 }
303 Toast.makeText(this, res, Toast.LENGTH_SHORT).show();
304 }
305 }
306
307 @Override
308 public void onStop() {
309 binding.remoteVideo.release();
310 binding.localVideo.release();
311 final WeakReference<JingleRtpConnection> weakReference = this.rtpConnectionReference;
312 final JingleRtpConnection jingleRtpConnection = weakReference == null ? null : weakReference.get();
313 if (jingleRtpConnection != null) {
314 releaseVideoTracks(jingleRtpConnection);
315 } else if (!isChangingConfigurations()) {
316 if (xmppConnectionService != null) {
317 retractSessionProposal();
318 }
319 }
320 releaseProximityWakeLock();
321 super.onStop();
322 }
323
324 private void releaseVideoTracks(final JingleRtpConnection jingleRtpConnection) {
325 final Optional<VideoTrack> remoteVideo = jingleRtpConnection.getRemoteVideoTrack();
326 if (remoteVideo.isPresent()) {
327 remoteVideo.get().removeSink(binding.remoteVideo);
328 }
329 final Optional<VideoTrack> localVideo = jingleRtpConnection.getLocalVideoTrack();
330 if (localVideo.isPresent()) {
331 localVideo.get().removeSink(binding.localVideo);
332 }
333 }
334
335 @Override
336 public void onBackPressed() {
337 endCall();
338 super.onBackPressed();
339 }
340
341 @Override
342 public void onUserLeaveHint() {
343 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && deviceSupportsPictureInPicture()) {
344 if (shouldBePictureInPicture()) {
345 startPictureInPicture();
346 }
347 }
348 }
349
350
351 @RequiresApi(api = Build.VERSION_CODES.O)
352 private void startPictureInPicture() {
353 try {
354 enterPictureInPictureMode(
355 new PictureInPictureParams.Builder()
356 .setAspectRatio(new Rational(10, 16))
357 .build()
358 );
359 } catch (IllegalStateException e) {
360 //this sometimes happens on Samsung phones (possibly when Knox is enabled)
361 Log.w(Config.LOGTAG, "unable to enter picture in picture mode", e);
362 }
363 }
364
365 private boolean deviceSupportsPictureInPicture() {
366 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
367 return getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE);
368 } else {
369 return false;
370 }
371 }
372
373 private boolean shouldBePictureInPicture() {
374 try {
375 final JingleRtpConnection rtpConnection = requireRtpConnection();
376 return rtpConnection.getMedia().contains(Media.VIDEO) && Arrays.asList(
377 RtpEndUserState.ACCEPTING_CALL,
378 RtpEndUserState.CONNECTING,
379 RtpEndUserState.CONNECTED
380 ).contains(rtpConnection.getEndUserState());
381 } catch (IllegalStateException e) {
382 return false;
383 }
384 }
385
386 private boolean initializeActivityWithRunningRtpSession(final Account account, Jid with, String sessionId) {
387 final WeakReference<JingleRtpConnection> reference = xmppConnectionService.getJingleConnectionManager()
388 .findJingleRtpConnection(account, with, sessionId);
389 if (reference == null || reference.get() == null) {
390 finish();
391 return true;
392 }
393 this.rtpConnectionReference = reference;
394 final RtpEndUserState currentState = requireRtpConnection().getEndUserState();
395 if (currentState == RtpEndUserState.ENDED) {
396 finish();
397 return true;
398 }
399 final Set<Media> media = getMedia();
400 if (currentState == RtpEndUserState.INCOMING_CALL) {
401 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
402 }
403 if (JingleRtpConnection.STATES_SHOWING_ONGOING_CALL.contains(requireRtpConnection().getState())) {
404 putScreenInCallMode();
405 }
406 binding.with.setText(getWith().getDisplayName());
407 updateVideoViews(currentState);
408 updateStateDisplay(currentState, media);
409 updateButtonConfiguration(currentState, media);
410 updateProfilePicture(currentState);
411 return false;
412 }
413
414 private void reInitializeActivityWithRunningRapSession(final Account account, Jid with, String sessionId) {
415 runOnUiThread(() -> initializeActivityWithRunningRtpSession(account, with, sessionId));
416 final Intent intent = new Intent(Intent.ACTION_VIEW);
417 intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
418 intent.putExtra(EXTRA_WITH, with.toEscapedString());
419 intent.putExtra(EXTRA_SESSION_ID, sessionId);
420 setIntent(intent);
421 }
422
423 private void ensureSurfaceViewRendererIsSetup(final SurfaceViewRenderer surfaceViewRenderer) {
424 surfaceViewRenderer.setVisibility(View.VISIBLE);
425 try {
426 surfaceViewRenderer.init(requireRtpConnection().getEglBaseContext(), null);
427 } catch (IllegalStateException e) {
428 Log.d(Config.LOGTAG, "SurfaceViewRenderer was already initialized");
429 }
430 surfaceViewRenderer.setEnableHardwareScaler(true);
431 }
432
433 private void updateStateDisplay(final RtpEndUserState state) {
434 updateStateDisplay(state, Collections.emptySet());
435 }
436
437 private void updateStateDisplay(final RtpEndUserState state, final Set<Media> media) {
438 switch (state) {
439 case INCOMING_CALL:
440 Preconditions.checkArgument(media.size() > 0, "Media must not be empty");
441 if (media.contains(Media.VIDEO)) {
442 setTitle(R.string.rtp_state_incoming_video_call);
443 } else {
444 setTitle(R.string.rtp_state_incoming_call);
445 }
446 break;
447 case CONNECTING:
448 setTitle(R.string.rtp_state_connecting);
449 break;
450 case CONNECTED:
451 setTitle(R.string.rtp_state_connected);
452 break;
453 case ACCEPTING_CALL:
454 setTitle(R.string.rtp_state_accepting_call);
455 break;
456 case ENDING_CALL:
457 setTitle(R.string.rtp_state_ending_call);
458 break;
459 case FINDING_DEVICE:
460 setTitle(R.string.rtp_state_finding_device);
461 break;
462 case RINGING:
463 setTitle(R.string.rtp_state_ringing);
464 break;
465 case DECLINED_OR_BUSY:
466 setTitle(R.string.rtp_state_declined_or_busy);
467 break;
468 case CONNECTIVITY_ERROR:
469 setTitle(R.string.rtp_state_connectivity_error);
470 break;
471 case RETRACTED:
472 setTitle(R.string.rtp_state_retracted);
473 break;
474 case APPLICATION_ERROR:
475 setTitle(R.string.rtp_state_application_failure);
476 break;
477 case ENDED:
478 throw new IllegalStateException("Activity should have called finishAndReleaseWakeLock();");
479 default:
480 throw new IllegalStateException(String.format("State %s has not been handled in UI", state));
481 }
482 }
483
484 private void updateProfilePicture(final RtpEndUserState state) {
485 updateProfilePicture(state, null);
486 }
487
488 private void updateProfilePicture(final RtpEndUserState state, final Contact contact) {
489 if (state == RtpEndUserState.INCOMING_CALL || state == RtpEndUserState.ACCEPTING_CALL) {
490 final boolean show = getResources().getBoolean(R.bool.show_avatar_incoming_call);
491 if (show) {
492 binding.contactPhoto.setVisibility(View.VISIBLE);
493 if (contact == null) {
494 AvatarWorkerTask.loadAvatar(getWith(), binding.contactPhoto, R.dimen.publish_avatar_size);
495 } else {
496 AvatarWorkerTask.loadAvatar(contact, binding.contactPhoto, R.dimen.publish_avatar_size);
497 }
498 } else {
499 binding.contactPhoto.setVisibility(View.GONE);
500 }
501 } else {
502 binding.contactPhoto.setVisibility(View.GONE);
503 }
504 }
505
506 private Set<Media> getMedia() {
507 return requireRtpConnection().getMedia();
508 }
509
510 private void updateButtonConfiguration(final RtpEndUserState state) {
511 updateButtonConfiguration(state, Collections.emptySet());
512 }
513
514 @SuppressLint("RestrictedApi")
515 private void updateButtonConfiguration(final RtpEndUserState state, final Set<Media> media) {
516 if (state == RtpEndUserState.ENDING_CALL || isPictureInPicture()) {
517 this.binding.rejectCall.setVisibility(View.INVISIBLE);
518 this.binding.endCall.setVisibility(View.INVISIBLE);
519 this.binding.acceptCall.setVisibility(View.INVISIBLE);
520 } else if (state == RtpEndUserState.INCOMING_CALL) {
521 this.binding.rejectCall.setOnClickListener(this::rejectCall);
522 this.binding.rejectCall.setImageResource(R.drawable.ic_call_end_white_48dp);
523 this.binding.rejectCall.setVisibility(View.VISIBLE);
524 this.binding.endCall.setVisibility(View.INVISIBLE);
525 this.binding.acceptCall.setOnClickListener(this::acceptCall);
526 this.binding.acceptCall.setImageResource(R.drawable.ic_call_white_48dp);
527 this.binding.acceptCall.setVisibility(View.VISIBLE);
528 } else if (state == RtpEndUserState.DECLINED_OR_BUSY) {
529 this.binding.rejectCall.setVisibility(View.INVISIBLE);
530 this.binding.endCall.setOnClickListener(this::exit);
531 this.binding.endCall.setImageResource(R.drawable.ic_clear_white_48dp);
532 this.binding.endCall.setVisibility(View.VISIBLE);
533 this.binding.acceptCall.setVisibility(View.INVISIBLE);
534 } else if (asList(RtpEndUserState.CONNECTIVITY_ERROR, RtpEndUserState.APPLICATION_ERROR, RtpEndUserState.RETRACTED).contains(state)) {
535 this.binding.rejectCall.setOnClickListener(this::exit);
536 this.binding.rejectCall.setImageResource(R.drawable.ic_clear_white_48dp);
537 this.binding.rejectCall.setVisibility(View.VISIBLE);
538 this.binding.endCall.setVisibility(View.INVISIBLE);
539 this.binding.acceptCall.setOnClickListener(this::retry);
540 this.binding.acceptCall.setImageResource(R.drawable.ic_replay_white_48dp);
541 this.binding.acceptCall.setVisibility(View.VISIBLE);
542 } else {
543 this.binding.rejectCall.setVisibility(View.INVISIBLE);
544 this.binding.endCall.setOnClickListener(this::endCall);
545 this.binding.endCall.setImageResource(R.drawable.ic_call_end_white_48dp);
546 this.binding.endCall.setVisibility(View.VISIBLE);
547 this.binding.acceptCall.setVisibility(View.INVISIBLE);
548 }
549 updateInCallButtonConfiguration(state, media);
550 }
551
552 private boolean isPictureInPicture() {
553 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
554 return isInPictureInPictureMode();
555 } else {
556 return false;
557 }
558 }
559
560 private void updateInCallButtonConfiguration() {
561 updateInCallButtonConfiguration(requireRtpConnection().getEndUserState(), requireRtpConnection().getMedia());
562 }
563
564 @SuppressLint("RestrictedApi")
565 private void updateInCallButtonConfiguration(final RtpEndUserState state, final Set<Media> media) {
566 if (state == RtpEndUserState.CONNECTED && !isPictureInPicture()) {
567 Preconditions.checkArgument(media.size() > 0, "Media must not be empty");
568 if (media.contains(Media.VIDEO)) {
569 final JingleRtpConnection rtpConnection = requireRtpConnection();
570 updateInCallButtonConfigurationVideo(rtpConnection.isVideoEnabled(), rtpConnection.isCameraSwitchable());
571 } else {
572 final AppRTCAudioManager audioManager = requireRtpConnection().getAudioManager();
573 updateInCallButtonConfigurationSpeaker(
574 audioManager.getSelectedAudioDevice(),
575 audioManager.getAudioDevices().size()
576 );
577 this.binding.inCallActionFarRight.setVisibility(View.GONE);
578 }
579 updateInCallButtonConfigurationMicrophone(requireRtpConnection().isMicrophoneEnabled());
580 } else {
581 this.binding.inCallActionLeft.setVisibility(View.GONE);
582 this.binding.inCallActionRight.setVisibility(View.GONE);
583 this.binding.inCallActionFarRight.setVisibility(View.GONE);
584 }
585 }
586
587 @SuppressLint("RestrictedApi")
588 private void updateInCallButtonConfigurationSpeaker(final AppRTCAudioManager.AudioDevice selectedAudioDevice, final int numberOfChoices) {
589 switch (selectedAudioDevice) {
590 case EARPIECE:
591 this.binding.inCallActionRight.setImageResource(R.drawable.ic_volume_off_black_24dp);
592 if (numberOfChoices >= 2) {
593 this.binding.inCallActionRight.setOnClickListener(this::switchToSpeaker);
594 } else {
595 this.binding.inCallActionRight.setOnClickListener(null);
596 this.binding.inCallActionRight.setClickable(false);
597 }
598 break;
599 case WIRED_HEADSET:
600 this.binding.inCallActionRight.setImageResource(R.drawable.ic_headset_black_24dp);
601 this.binding.inCallActionRight.setOnClickListener(null);
602 this.binding.inCallActionRight.setClickable(false);
603 break;
604 case SPEAKER_PHONE:
605 this.binding.inCallActionRight.setImageResource(R.drawable.ic_volume_up_black_24dp);
606 if (numberOfChoices >= 2) {
607 this.binding.inCallActionRight.setOnClickListener(this::switchToEarpiece);
608 } else {
609 this.binding.inCallActionRight.setOnClickListener(null);
610 this.binding.inCallActionRight.setClickable(false);
611 }
612 break;
613 case BLUETOOTH:
614 this.binding.inCallActionRight.setImageResource(R.drawable.ic_bluetooth_audio_black_24dp);
615 this.binding.inCallActionRight.setOnClickListener(null);
616 this.binding.inCallActionRight.setClickable(false);
617 break;
618 }
619 this.binding.inCallActionRight.setVisibility(View.VISIBLE);
620 }
621
622 @SuppressLint("RestrictedApi")
623 private void updateInCallButtonConfigurationVideo(final boolean videoEnabled, final boolean isCameraSwitchable) {
624 this.binding.inCallActionRight.setVisibility(View.VISIBLE);
625 if (isCameraSwitchable) {
626 this.binding.inCallActionFarRight.setImageResource(R.drawable.ic_flip_camera_android_black_24dp);
627 this.binding.inCallActionFarRight.setVisibility(View.VISIBLE);
628 this.binding.inCallActionFarRight.setOnClickListener(this::switchCamera);
629 } else {
630 this.binding.inCallActionFarRight.setVisibility(View.GONE);
631 }
632 if (videoEnabled) {
633 this.binding.inCallActionRight.setImageResource(R.drawable.ic_videocam_black_24dp);
634 this.binding.inCallActionRight.setOnClickListener(this::disableVideo);
635 } else {
636 this.binding.inCallActionRight.setImageResource(R.drawable.ic_videocam_off_black_24dp);
637 this.binding.inCallActionRight.setOnClickListener(this::enableVideo);
638 }
639 }
640
641 private void switchCamera(final View view) {
642 Futures.addCallback(requireRtpConnection().switchCamera(), new FutureCallback<Boolean>() {
643 @Override
644 public void onSuccess(@NullableDecl Boolean isFrontCamera) {
645 binding.localVideo.setMirror(isFrontCamera);
646 }
647
648 @Override
649 public void onFailure(@NonNull final Throwable throwable) {
650 Log.d(Config.LOGTAG,"could not switch camera", Throwables.getRootCause(throwable));
651 Toast.makeText(RtpSessionActivity.this, R.string.could_not_switch_camera, Toast.LENGTH_LONG).show();
652 }
653 }, MainThreadExecutor.getInstance());
654 }
655
656 private void enableVideo(View view) {
657 requireRtpConnection().setVideoEnabled(true);
658 updateInCallButtonConfigurationVideo(true, requireRtpConnection().isCameraSwitchable());
659 }
660
661 private void disableVideo(View view) {
662 requireRtpConnection().setVideoEnabled(false);
663 updateInCallButtonConfigurationVideo(false, requireRtpConnection().isCameraSwitchable());
664
665 }
666
667 @SuppressLint("RestrictedApi")
668 private void updateInCallButtonConfigurationMicrophone(final boolean microphoneEnabled) {
669 if (microphoneEnabled) {
670 this.binding.inCallActionLeft.setImageResource(R.drawable.ic_mic_black_24dp);
671 this.binding.inCallActionLeft.setOnClickListener(this::disableMicrophone);
672 } else {
673 this.binding.inCallActionLeft.setImageResource(R.drawable.ic_mic_off_black_24dp);
674 this.binding.inCallActionLeft.setOnClickListener(this::enableMicrophone);
675 }
676 this.binding.inCallActionLeft.setVisibility(View.VISIBLE);
677 }
678
679 private void updateVideoViews(final RtpEndUserState state) {
680 if (END_CARD.contains(state) || state == RtpEndUserState.ENDING_CALL) {
681 binding.localVideo.setVisibility(View.GONE);
682 binding.localVideo.release();
683 binding.remoteVideo.setVisibility(View.GONE);
684 binding.remoteVideo.release();
685 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
686 if (isPictureInPicture()) {
687 binding.appBarLayout.setVisibility(View.GONE);
688 binding.pipPlaceholder.setVisibility(View.VISIBLE);
689 if (state == RtpEndUserState.APPLICATION_ERROR || state == RtpEndUserState.CONNECTIVITY_ERROR) {
690 binding.pipWarning.setVisibility(View.VISIBLE);
691 binding.pipWaiting.setVisibility(View.GONE);
692 } else {
693 binding.pipWarning.setVisibility(View.GONE);
694 binding.pipWaiting.setVisibility(View.GONE);
695 }
696 } else {
697 binding.appBarLayout.setVisibility(View.VISIBLE);
698 binding.pipPlaceholder.setVisibility(View.GONE);
699 }
700 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
701 return;
702 }
703 if (isPictureInPicture() && (state == RtpEndUserState.CONNECTING || state == RtpEndUserState.ACCEPTING_CALL)) {
704 binding.localVideo.setVisibility(View.GONE);
705 binding.remoteVideo.setVisibility(View.GONE);
706 binding.appBarLayout.setVisibility(View.GONE);
707 binding.pipPlaceholder.setVisibility(View.VISIBLE);
708 binding.pipWarning.setVisibility(View.GONE);
709 binding.pipWaiting.setVisibility(View.VISIBLE);
710 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
711 return;
712 }
713 final Optional<VideoTrack> localVideoTrack = getLocalVideoTrack();
714 if (localVideoTrack.isPresent() && !isPictureInPicture()) {
715 ensureSurfaceViewRendererIsSetup(binding.localVideo);
716 //paint local view over remote view
717 binding.localVideo.setZOrderMediaOverlay(true);
718 binding.localVideo.setMirror(requireRtpConnection().isFrontCamera());
719 localVideoTrack.get().addSink(binding.localVideo);
720 } else {
721 binding.localVideo.setVisibility(View.GONE);
722 }
723 final Optional<VideoTrack> remoteVideoTrack = getRemoteVideoTrack();
724 if (remoteVideoTrack.isPresent()) {
725 ensureSurfaceViewRendererIsSetup(binding.remoteVideo);
726 remoteVideoTrack.get().addSink(binding.remoteVideo);
727 if (state == RtpEndUserState.CONNECTED) {
728 binding.appBarLayout.setVisibility(View.GONE);
729 getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
730 } else {
731 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
732 binding.remoteVideo.setVisibility(View.GONE);
733 }
734 if (isPictureInPicture() && !requireRtpConnection().isMicrophoneEnabled()) {
735 binding.pipLocalMicOffIndicator.setVisibility(View.VISIBLE);
736 } else {
737 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
738 }
739 } else {
740 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
741 binding.remoteVideo.setVisibility(View.GONE);
742 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
743 }
744 }
745
746 private Optional<VideoTrack> getLocalVideoTrack() {
747 final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
748 if (connection == null) {
749 return Optional.absent();
750 }
751 return connection.getLocalVideoTrack();
752 }
753
754 private Optional<VideoTrack> getRemoteVideoTrack() {
755 final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
756 if (connection == null) {
757 return Optional.absent();
758 }
759 return connection.getRemoteVideoTrack();
760 }
761
762 private void disableMicrophone(View view) {
763 JingleRtpConnection rtpConnection = requireRtpConnection();
764 rtpConnection.setMicrophoneEnabled(false);
765 updateInCallButtonConfiguration();
766 }
767
768 private void enableMicrophone(View view) {
769 JingleRtpConnection rtpConnection = requireRtpConnection();
770 rtpConnection.setMicrophoneEnabled(true);
771 updateInCallButtonConfiguration();
772 }
773
774 private void switchToEarpiece(View view) {
775 requireRtpConnection().getAudioManager().setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.EARPIECE);
776 acquireProximityWakeLock();
777 }
778
779 private void switchToSpeaker(View view) {
780 requireRtpConnection().getAudioManager().setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.SPEAKER_PHONE);
781 releaseProximityWakeLock();
782 }
783
784 private void retry(View view) {
785 Log.d(Config.LOGTAG, "attempting retry");
786 final Intent intent = getIntent();
787 final Account account = extractAccount(intent);
788 final Jid with = Jid.of(intent.getStringExtra(EXTRA_WITH));
789 final String lastAction = intent.getStringExtra(EXTRA_LAST_ACTION);
790 final String action = intent.getAction();
791 final Set<Media> media = actionToMedia(lastAction == null ? action : lastAction);
792 this.rtpConnectionReference = null;
793 proposeJingleRtpSession(account, with, media);
794 }
795
796 private void exit(View view) {
797 finish();
798 }
799
800 private Contact getWith() {
801 final AbstractJingleConnection.Id id = requireRtpConnection().getId();
802 final Account account = id.account;
803 return account.getRoster().getContact(id.with);
804 }
805
806 private JingleRtpConnection requireRtpConnection() {
807 final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
808 if (connection == null) {
809 throw new IllegalStateException("No RTP connection found");
810 }
811 return connection;
812 }
813
814 @Override
815 public void onJingleRtpConnectionUpdate(Account account, Jid with, final String sessionId, RtpEndUserState state) {
816 Log.d(Config.LOGTAG, "onJingleRtpConnectionUpdate(" + state + ")");
817 if (END_CARD.contains(state)) {
818 Log.d(Config.LOGTAG, "end card reached");
819 releaseProximityWakeLock();
820 runOnUiThread(() -> getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON));
821 }
822 if (with.isBareJid()) {
823 updateRtpSessionProposalState(account, with, state);
824 return;
825 }
826 if (this.rtpConnectionReference == null) {
827 if (END_CARD.contains(state)) {
828 Log.d(Config.LOGTAG, "not reinitializing session");
829 return;
830 }
831 //this happens when going from proposed session to actual session
832 reInitializeActivityWithRunningRapSession(account, with, sessionId);
833 return;
834 }
835 final AbstractJingleConnection.Id id = requireRtpConnection().getId();
836 final Set<Media> media = getMedia();
837 final Contact contact = getWith();
838 if (account == id.account && id.with.equals(with) && id.sessionId.equals(sessionId)) {
839 if (state == RtpEndUserState.ENDED) {
840 finish();
841 return;
842 }
843 runOnUiThread(() -> {
844 updateStateDisplay(state, media);
845 updateButtonConfiguration(state, media);
846 updateVideoViews(state);
847 updateProfilePicture(state, contact);
848 });
849 if (END_CARD.contains(state)) {
850 final JingleRtpConnection rtpConnection = requireRtpConnection();
851 resetIntent(account, with, state, rtpConnection.getMedia());
852 releaseVideoTracks(rtpConnection);
853 this.rtpConnectionReference = null;
854 }
855 } else {
856 Log.d(Config.LOGTAG, "received update for other rtp session");
857 }
858 }
859
860 @Override
861 public void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
862 Log.d(Config.LOGTAG, "onAudioDeviceChanged in activity: selected:" + selectedAudioDevice + ", available:" + availableAudioDevices);
863 try {
864 if (getMedia().contains(Media.VIDEO)) {
865 Log.d(Config.LOGTAG, "nothing to do; in video mode");
866 return;
867 }
868 final RtpEndUserState endUserState = requireRtpConnection().getEndUserState();
869 if (endUserState == RtpEndUserState.CONNECTED) {
870 final AppRTCAudioManager audioManager = requireRtpConnection().getAudioManager();
871 updateInCallButtonConfigurationSpeaker(
872 audioManager.getSelectedAudioDevice(),
873 audioManager.getAudioDevices().size()
874 );
875 } else if (END_CARD.contains(endUserState)) {
876 Log.d(Config.LOGTAG, "onAudioDeviceChanged() nothing to do because end card has been reached");
877 } else {
878 putProximityWakeLockInProperState();
879 }
880 } catch (IllegalStateException e) {
881 Log.d(Config.LOGTAG, "RTP connection was not available when audio device changed");
882 }
883 }
884
885 private void updateRtpSessionProposalState(final Account account, final Jid with, final RtpEndUserState state) {
886 final Intent currentIntent = getIntent();
887 final String withExtra = currentIntent == null ? null : currentIntent.getStringExtra(EXTRA_WITH);
888 if (withExtra == null) {
889 return;
890 }
891 if (Jid.ofEscaped(withExtra).asBareJid().equals(with)) {
892 runOnUiThread(() -> {
893 updateStateDisplay(state);
894 updateButtonConfiguration(state);
895 updateProfilePicture(state);
896 });
897 resetIntent(account, with, state, actionToMedia(currentIntent.getAction()));
898 }
899 }
900
901 private void resetIntent(final Bundle extras) {
902 final Intent intent = new Intent(Intent.ACTION_VIEW);
903 intent.putExtras(extras);
904 setIntent(intent);
905 }
906
907 private void resetIntent(final Account account, Jid with, final RtpEndUserState state, final Set<Media> media) {
908 final Intent intent = new Intent(Intent.ACTION_VIEW);
909 intent.putExtra(EXTRA_WITH, with.asBareJid().toEscapedString());
910 intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
911 intent.putExtra(EXTRA_LAST_REPORTED_STATE, state.toString());
912 intent.putExtra(EXTRA_LAST_ACTION, media.contains(Media.VIDEO) ? ACTION_MAKE_VIDEO_CALL : ACTION_MAKE_VOICE_CALL);
913 setIntent(intent);
914 }
915}