1package eu.siacs.conversations.ui;
2
3import static eu.siacs.conversations.utils.PermissionUtils.getFirstDenied;
4
5import static java.util.Arrays.asList;
6
7import android.Manifest;
8import android.annotation.SuppressLint;
9import android.app.Activity;
10import android.app.PictureInPictureParams;
11import android.content.ActivityNotFoundException;
12import android.content.Context;
13import android.content.Intent;
14import android.content.pm.ActivityInfo;
15import android.content.pm.PackageManager;
16import android.opengl.GLException;
17import android.os.Build;
18import android.os.Bundle;
19import android.os.Handler;
20import android.os.PowerManager;
21import android.os.SystemClock;
22import android.util.Log;
23import android.util.Rational;
24import android.view.KeyEvent;
25import android.view.Menu;
26import android.view.MenuItem;
27import android.view.View;
28import android.view.WindowManager;
29import android.widget.Toast;
30
31import androidx.annotation.NonNull;
32import androidx.annotation.Nullable;
33import androidx.annotation.RequiresApi;
34import androidx.annotation.StringRes;
35import androidx.databinding.DataBindingUtil;
36
37import com.google.common.base.Optional;
38import com.google.common.base.Preconditions;
39import com.google.common.base.Throwables;
40import com.google.common.collect.ImmutableList;
41import com.google.common.collect.ImmutableSet;
42import com.google.common.util.concurrent.FutureCallback;
43import com.google.common.util.concurrent.Futures;
44
45import eu.siacs.conversations.Config;
46import eu.siacs.conversations.R;
47import eu.siacs.conversations.databinding.ActivityRtpSessionBinding;
48import eu.siacs.conversations.entities.Account;
49import eu.siacs.conversations.entities.Contact;
50import eu.siacs.conversations.entities.Conversation;
51import eu.siacs.conversations.services.AppRTCAudioManager;
52import eu.siacs.conversations.services.XmppConnectionService;
53import eu.siacs.conversations.ui.util.AvatarWorkerTask;
54import eu.siacs.conversations.ui.util.MainThreadExecutor;
55import eu.siacs.conversations.ui.util.Rationals;
56import eu.siacs.conversations.utils.PermissionUtils;
57import eu.siacs.conversations.utils.TimeFrameUtils;
58import eu.siacs.conversations.xmpp.Jid;
59import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
60import eu.siacs.conversations.xmpp.jingle.ContentAddition;
61import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
62import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
63import eu.siacs.conversations.xmpp.jingle.Media;
64import eu.siacs.conversations.xmpp.jingle.RtpCapability;
65import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
66
67import org.webrtc.RendererCommon;
68import org.webrtc.SurfaceViewRenderer;
69import org.webrtc.VideoTrack;
70
71import java.lang.ref.WeakReference;
72import java.util.Arrays;
73import java.util.Collections;
74import java.util.List;
75import java.util.Set;
76
77public class RtpSessionActivity extends XmppActivity
78 implements XmppConnectionService.OnJingleRtpConnectionUpdate,
79 eu.siacs.conversations.ui.widget.SurfaceViewRenderer.OnAspectRatioChanged {
80
81 public static final String EXTRA_WITH = "with";
82 public static final String EXTRA_SESSION_ID = "session_id";
83 public static final String EXTRA_LAST_REPORTED_STATE = "last_reported_state";
84 public static final String EXTRA_LAST_ACTION = "last_action";
85 public static final String ACTION_ACCEPT_CALL = "action_accept_call";
86 public static final String ACTION_MAKE_VOICE_CALL = "action_make_voice_call";
87 public static final String ACTION_MAKE_VIDEO_CALL = "action_make_video_call";
88
89 private static final int CALL_DURATION_UPDATE_INTERVAL = 333;
90
91 private static final List<RtpEndUserState> END_CARD =
92 Arrays.asList(
93 RtpEndUserState.APPLICATION_ERROR,
94 RtpEndUserState.SECURITY_ERROR,
95 RtpEndUserState.DECLINED_OR_BUSY,
96 RtpEndUserState.CONNECTIVITY_ERROR,
97 RtpEndUserState.CONNECTIVITY_LOST_ERROR,
98 RtpEndUserState.RETRACTED);
99 private static final List<RtpEndUserState> STATES_SHOWING_HELP_BUTTON =
100 Arrays.asList(
101 RtpEndUserState.APPLICATION_ERROR,
102 RtpEndUserState.CONNECTIVITY_ERROR,
103 RtpEndUserState.SECURITY_ERROR);
104 private static final List<RtpEndUserState> STATES_SHOWING_SWITCH_TO_CHAT =
105 Arrays.asList(
106 RtpEndUserState.CONNECTING,
107 RtpEndUserState.CONNECTED,
108 RtpEndUserState.RECONNECTING,
109 RtpEndUserState.INCOMING_CONTENT_ADD);
110 private static final List<RtpEndUserState> STATES_CONSIDERED_CONNECTED =
111 Arrays.asList(RtpEndUserState.CONNECTED, RtpEndUserState.RECONNECTING);
112 private static final List<RtpEndUserState> STATES_SHOWING_PIP_PLACEHOLDER =
113 Arrays.asList(
114 RtpEndUserState.ACCEPTING_CALL,
115 RtpEndUserState.CONNECTING,
116 RtpEndUserState.RECONNECTING);
117 private static final String PROXIMITY_WAKE_LOCK_TAG = "conversations:in-rtp-session";
118 private static final int REQUEST_ACCEPT_CALL = 0x1111;
119 private static final int REQUEST_ACCEPT_CONTENT = 0x1112;
120 private static final int REQUEST_ADD_CONTENT = 0x1113;
121 private WeakReference<JingleRtpConnection> rtpConnectionReference;
122
123 private ActivityRtpSessionBinding binding;
124 private PowerManager.WakeLock mProximityWakeLock;
125
126 private final Handler mHandler = new Handler();
127 private final Runnable mTickExecutor =
128 new Runnable() {
129 @Override
130 public void run() {
131 updateCallDuration();
132 mHandler.postDelayed(mTickExecutor, CALL_DURATION_UPDATE_INTERVAL);
133 }
134 };
135
136 private static Set<Media> actionToMedia(final String action) {
137 if (ACTION_MAKE_VIDEO_CALL.equals(action)) {
138 return ImmutableSet.of(Media.AUDIO, Media.VIDEO);
139 } else {
140 return ImmutableSet.of(Media.AUDIO);
141 }
142 }
143
144 private static void addSink(
145 final VideoTrack videoTrack, final SurfaceViewRenderer surfaceViewRenderer) {
146 try {
147 videoTrack.addSink(surfaceViewRenderer);
148 } catch (final IllegalStateException e) {
149 Log.e(
150 Config.LOGTAG,
151 "possible race condition on trying to display video track. ignoring",
152 e);
153 }
154 }
155
156 @Override
157 public void onCreate(Bundle savedInstanceState) {
158 super.onCreate(savedInstanceState);
159 getWindow()
160 .addFlags(
161 WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
162 | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
163 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
164 | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
165 this.binding = DataBindingUtil.setContentView(this, R.layout.activity_rtp_session);
166 setSupportActionBar(binding.toolbar);
167 }
168
169 @Override
170 public boolean onCreateOptionsMenu(final Menu menu) {
171 getMenuInflater().inflate(R.menu.activity_rtp_session, menu);
172 final MenuItem help = menu.findItem(R.id.action_help);
173 final MenuItem gotoChat = menu.findItem(R.id.action_goto_chat);
174 final MenuItem switchToVideo = menu.findItem(R.id.action_switch_to_video);
175 help.setVisible(Config.HELP != null && isHelpButtonVisible());
176 gotoChat.setVisible(isSwitchToConversationVisible());
177 switchToVideo.setVisible(isSwitchToVideoVisible());
178 return super.onCreateOptionsMenu(menu);
179 }
180
181 @Override
182 public boolean onKeyDown(final int keyCode, final KeyEvent event) {
183 if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
184 if (xmppConnectionService != null) {
185 if (xmppConnectionService.getNotificationService().stopSoundAndVibration()) {
186 return true;
187 }
188 }
189 }
190 return super.onKeyDown(keyCode, event);
191 }
192
193 private boolean isHelpButtonVisible() {
194 try {
195 return STATES_SHOWING_HELP_BUTTON.contains(requireRtpConnection().getEndUserState());
196 } catch (IllegalStateException e) {
197 final Intent intent = getIntent();
198 final String state =
199 intent != null ? intent.getStringExtra(EXTRA_LAST_REPORTED_STATE) : null;
200 if (state != null) {
201 return STATES_SHOWING_HELP_BUTTON.contains(RtpEndUserState.valueOf(state));
202 } else {
203 return false;
204 }
205 }
206 }
207
208 private boolean isSwitchToConversationVisible() {
209 final JingleRtpConnection connection =
210 this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
211 return connection != null
212 && STATES_SHOWING_SWITCH_TO_CHAT.contains(connection.getEndUserState());
213 }
214
215 private boolean isSwitchToVideoVisible() {
216 final JingleRtpConnection connection =
217 this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
218 if (connection == null) {
219 return false;
220 }
221 return connection.isSwitchToVideoAvailable();
222 }
223
224 private void switchToConversation() {
225 final Contact contact = getWith();
226 final Conversation conversation =
227 xmppConnectionService.findOrCreateConversation(
228 contact.getAccount(), contact.getJid(), false, true);
229 switchToConversation(conversation);
230 }
231
232 public boolean onOptionsItemSelected(final MenuItem item) {
233 final var itemItem = item.getItemId();
234 if (itemItem == R.id.action_help) {
235 launchHelpInBrowser();
236 return true;
237 } else if (itemItem == R.id.action_goto_chat) {
238 switchToConversation();
239 return true;
240 } else if (itemItem == R.id.action_switch_to_video) {
241 requestPermissionAndSwitchToVideo();
242 return true;
243 } else {
244 return super.onOptionsItemSelected(item);
245 }
246 }
247
248 private void launchHelpInBrowser() {
249 final Intent intent = new Intent(Intent.ACTION_VIEW, Config.HELP);
250 try {
251 startActivity(intent);
252 } catch (final ActivityNotFoundException e) {
253 Toast.makeText(this, R.string.no_application_found_to_open_link, Toast.LENGTH_LONG)
254 .show();
255 }
256 }
257
258 private void endCall(View view) {
259 endCall();
260 }
261
262 private void endCall() {
263 if (this.rtpConnectionReference == null) {
264 retractSessionProposal();
265 finish();
266 } else {
267 requireRtpConnection().endCall();
268 }
269 }
270
271 private void retractSessionProposal() {
272 final Intent intent = getIntent();
273 final String action = intent.getAction();
274 final Account account = extractAccount(intent);
275 final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
276 final String state = intent.getStringExtra(EXTRA_LAST_REPORTED_STATE);
277 if (!Intent.ACTION_VIEW.equals(action)
278 || state == null
279 || !END_CARD.contains(RtpEndUserState.valueOf(state))) {
280 resetIntent(
281 account, with, RtpEndUserState.RETRACTED, actionToMedia(intent.getAction()));
282 }
283 xmppConnectionService
284 .getJingleConnectionManager()
285 .retractSessionProposal(account, with.asBareJid());
286 }
287
288 private void rejectCall(View view) {
289 requireRtpConnection().rejectCall();
290 finish();
291 }
292
293 private void acceptCall(View view) {
294 requestPermissionsAndAcceptCall();
295 }
296
297 private void acceptContentAdd() {
298 try {
299 requireRtpConnection()
300 .acceptContentAdd(requireRtpConnection().getPendingContentAddition().summary);
301 } catch (final IllegalStateException e) {
302 Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
303 }
304 }
305
306 private void requestPermissionAndSwitchToVideo() {
307 final List<String> permissions = permissions(ImmutableSet.of(Media.VIDEO, Media.AUDIO));
308 if (PermissionUtils.hasPermission(this, permissions, REQUEST_ADD_CONTENT)) {
309 switchToVideo();
310 }
311 }
312
313 private void switchToVideo() {
314 try {
315 requireRtpConnection().addMedia(Media.VIDEO);
316 } catch (final IllegalStateException e) {
317 Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
318 }
319 }
320
321 private void acceptContentAdd(final ContentAddition contentAddition) {
322 if (contentAddition == null
323 || contentAddition.direction != ContentAddition.Direction.INCOMING) {
324 Log.d(Config.LOGTAG, "ignore press on content-accept button");
325 return;
326 }
327 requestPermissionAndAcceptContentAdd(contentAddition);
328 }
329
330 private void requestPermissionAndAcceptContentAdd(final ContentAddition contentAddition) {
331 final List<String> permissions = permissions(contentAddition.media());
332 if (PermissionUtils.hasPermission(this, permissions, REQUEST_ACCEPT_CONTENT)) {
333 try {
334 requireRtpConnection().acceptContentAdd(contentAddition.summary);
335 } catch (final IllegalStateException e) {
336 Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
337 }
338 }
339 }
340
341 private void rejectContentAdd(final View view) {
342 requireRtpConnection().rejectContentAdd();
343 }
344
345 private void requestPermissionsAndAcceptCall() {
346 final List<String> permissions = permissions(getMedia());
347 if (PermissionUtils.hasPermission(this, permissions, REQUEST_ACCEPT_CALL)) {
348 putScreenInCallMode();
349 checkRecorderAndAcceptCall();
350 }
351 }
352
353 private List<String> permissions(final Set<Media> media) {
354 final ImmutableList.Builder<String> permissions = ImmutableList.builder();
355 if (media.contains(Media.VIDEO)) {
356 permissions.add(Manifest.permission.CAMERA).add(Manifest.permission.RECORD_AUDIO);
357 } else {
358 permissions.add(Manifest.permission.RECORD_AUDIO);
359 }
360 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
361 permissions.add(Manifest.permission.BLUETOOTH_CONNECT);
362 }
363 return permissions.build();
364 }
365
366 private void checkRecorderAndAcceptCall() {
367 checkMicrophoneAvailabilityAsync();
368 try {
369 requireRtpConnection().acceptCall();
370 } catch (final IllegalStateException e) {
371 Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
372 }
373 }
374
375 private void checkMicrophoneAvailabilityAsync() {
376 new Thread(new MicrophoneAvailabilityCheck(this)).start();
377 }
378
379 private static class MicrophoneAvailabilityCheck implements Runnable {
380
381 private final WeakReference<Activity> activityReference;
382
383 private MicrophoneAvailabilityCheck(final Activity activity) {
384 this.activityReference = new WeakReference<>(activity);
385 }
386
387 @Override
388 public void run() {
389 final long start = SystemClock.elapsedRealtime();
390 final boolean isMicrophoneAvailable = AppRTCAudioManager.isMicrophoneAvailable();
391 final long stop = SystemClock.elapsedRealtime();
392 Log.d(Config.LOGTAG, "checking microphone availability took " + (stop - start) + "ms");
393 if (isMicrophoneAvailable) {
394 return;
395 }
396 final Activity activity = activityReference.get();
397 if (activity == null) {
398 return;
399 }
400 activity.runOnUiThread(
401 () ->
402 Toast.makeText(
403 activity,
404 R.string.microphone_unavailable,
405 Toast.LENGTH_LONG)
406 .show());
407 }
408 }
409
410 private void putScreenInCallMode() {
411 putScreenInCallMode(requireRtpConnection().getMedia());
412 }
413
414 private void putScreenInCallMode(final Set<Media> media) {
415 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
416 if (Media.audioOnly(media)) {
417 final JingleRtpConnection rtpConnection =
418 rtpConnectionReference != null ? rtpConnectionReference.get() : null;
419 final AppRTCAudioManager audioManager =
420 rtpConnection == null ? null : rtpConnection.getAudioManager();
421 if (audioManager == null
422 || audioManager.getSelectedAudioDevice()
423 == AppRTCAudioManager.AudioDevice.EARPIECE) {
424 acquireProximityWakeLock();
425 }
426 }
427 lockOrientation(media);
428 }
429
430 private void lockOrientation(final Set<Media> media) {
431 if (Media.audioOnly(media)) {
432 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
433 } else {
434 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
435 }
436 }
437
438 @SuppressLint("WakelockTimeout")
439 private void acquireProximityWakeLock() {
440 final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
441 if (powerManager == null) {
442 Log.e(Config.LOGTAG, "power manager not available");
443 return;
444 }
445 if (isFinishing()) {
446 Log.e(Config.LOGTAG, "do not acquire wakelock. activity is finishing");
447 return;
448 }
449 if (this.mProximityWakeLock == null) {
450 this.mProximityWakeLock =
451 powerManager.newWakeLock(
452 PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, PROXIMITY_WAKE_LOCK_TAG);
453 }
454 if (!this.mProximityWakeLock.isHeld()) {
455 Log.d(Config.LOGTAG, "acquiring proximity wake lock");
456 this.mProximityWakeLock.acquire();
457 }
458 }
459
460 private void releaseProximityWakeLock() {
461 if (this.mProximityWakeLock != null && mProximityWakeLock.isHeld()) {
462 Log.d(Config.LOGTAG, "releasing proximity wake lock");
463 this.mProximityWakeLock.release(PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY);
464 this.mProximityWakeLock = null;
465 }
466 }
467
468 private void putProximityWakeLockInProperState(
469 final AppRTCAudioManager.AudioDevice audioDevice) {
470 if (audioDevice == AppRTCAudioManager.AudioDevice.EARPIECE) {
471 acquireProximityWakeLock();
472 } else {
473 releaseProximityWakeLock();
474 }
475 }
476
477 @Override
478 protected void refreshUiReal() {}
479
480 @Override
481 public void onNewIntent(final Intent intent) {
482 Log.d(Config.LOGTAG, this.getClass().getName() + ".onNewIntent()");
483 super.onNewIntent(intent);
484 setIntent(intent);
485 if (xmppConnectionService == null) {
486 Log.d(
487 Config.LOGTAG,
488 "RtpSessionActivity: background service wasn't bound in onNewIntent()");
489 return;
490 }
491 final Account account = extractAccount(intent);
492 final String action = intent.getAction();
493 final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
494 final String sessionId = intent.getStringExtra(EXTRA_SESSION_ID);
495 if (sessionId != null) {
496 Log.d(Config.LOGTAG, "reinitializing from onNewIntent()");
497 if (initializeActivityWithRunningRtpSession(account, with, sessionId)) {
498 return;
499 }
500 if (ACTION_ACCEPT_CALL.equals(intent.getAction())) {
501 Log.d(Config.LOGTAG, "accepting call from onNewIntent()");
502 requestPermissionsAndAcceptCall();
503 resetIntent(intent.getExtras());
504 }
505 } else if (asList(ACTION_MAKE_VIDEO_CALL, ACTION_MAKE_VOICE_CALL).contains(action)) {
506 proposeJingleRtpSession(account, with, actionToMedia(action));
507 setWith(account.getRoster().getContact(with), null);
508 } else {
509 throw new IllegalStateException("received onNewIntent without sessionId");
510 }
511 }
512
513 @Override
514 void onBackendConnected() {
515 final Intent intent = getIntent();
516 final String action = intent.getAction();
517 final Account account = extractAccount(intent);
518 final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
519 final String sessionId = intent.getStringExtra(EXTRA_SESSION_ID);
520 if (sessionId != null) {
521 if (initializeActivityWithRunningRtpSession(account, with, sessionId)) {
522 return;
523 }
524 if (ACTION_ACCEPT_CALL.equals(intent.getAction())) {
525 Log.d(Config.LOGTAG, "intent action was accept");
526 requestPermissionsAndAcceptCall();
527 resetIntent(intent.getExtras());
528 }
529 } else if (asList(ACTION_MAKE_VIDEO_CALL, ACTION_MAKE_VOICE_CALL).contains(action)) {
530 proposeJingleRtpSession(account, with, actionToMedia(action));
531 setWith(account.getRoster().getContact(with), null);
532 } else if (Intent.ACTION_VIEW.equals(action)) {
533 final String extraLastState = intent.getStringExtra(EXTRA_LAST_REPORTED_STATE);
534 final RtpEndUserState state =
535 extraLastState == null ? null : RtpEndUserState.valueOf(extraLastState);
536 if (state != null) {
537 Log.d(Config.LOGTAG, "restored last state from intent extra");
538 updateButtonConfiguration(state);
539 updateVerifiedShield(false);
540 updateStateDisplay(state);
541 updateIncomingCallScreen(state);
542 invalidateOptionsMenu();
543 }
544 setWith(account.getRoster().getContact(with), state);
545 if (xmppConnectionService
546 .getJingleConnectionManager()
547 .fireJingleRtpConnectionStateUpdates()) {
548 return;
549 }
550 if (END_CARD.contains(state)
551 || xmppConnectionService
552 .getJingleConnectionManager()
553 .hasMatchingProposal(account, with)) {
554 return;
555 }
556 Log.d(Config.LOGTAG, "restored state (" + state + ") was not an end card. finishing");
557 finish();
558 }
559 }
560
561 private void setWidth(final RtpEndUserState state) {
562 setWith(getWith(), state);
563 }
564
565 private void setWith(final Contact contact, final RtpEndUserState state) {
566 binding.with.setText(contact.getDisplayName());
567 if (Arrays.asList(RtpEndUserState.INCOMING_CALL, RtpEndUserState.ACCEPTING_CALL)
568 .contains(state)) {
569 binding.withJid.setText(contact.getJid().asBareJid().toEscapedString());
570 binding.withJid.setVisibility(View.VISIBLE);
571 } else {
572 binding.withJid.setVisibility(View.GONE);
573 }
574 }
575
576 private void proposeJingleRtpSession(
577 final Account account, final Jid with, final Set<Media> media) {
578 checkMicrophoneAvailabilityAsync();
579 if (with.isBareJid()) {
580 xmppConnectionService
581 .getJingleConnectionManager()
582 .proposeJingleRtpSession(account, with, media);
583 } else {
584 final String sessionId =
585 xmppConnectionService
586 .getJingleConnectionManager()
587 .initializeRtpSession(account, with, media);
588 initializeActivityWithRunningRtpSession(account, with, sessionId);
589 resetIntent(account, with, sessionId);
590 }
591 putScreenInCallMode(media);
592 }
593
594 @Override
595 public void onRequestPermissionsResult(
596 int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
597 super.onRequestPermissionsResult(requestCode, permissions, grantResults);
598 final PermissionUtils.PermissionResult permissionResult =
599 PermissionUtils.removeBluetoothConnect(permissions, grantResults);
600 if (PermissionUtils.allGranted(permissionResult.grantResults)) {
601 if (requestCode == REQUEST_ACCEPT_CALL) {
602 checkRecorderAndAcceptCall();
603 } else if (requestCode == REQUEST_ACCEPT_CONTENT) {
604 acceptContentAdd();
605 } else if (requestCode == REQUEST_ADD_CONTENT) {
606 switchToVideo();
607 }
608 } else {
609 @StringRes int res;
610 final String firstDenied =
611 getFirstDenied(permissionResult.grantResults, permissionResult.permissions);
612 if (firstDenied == null) {
613 return;
614 }
615 if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
616 res = R.string.no_microphone_permission;
617 } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
618 res = R.string.no_camera_permission;
619 } else {
620 throw new IllegalStateException("Invalid permission result request");
621 }
622 Toast.makeText(this, getString(res, getString(R.string.app_name)), Toast.LENGTH_SHORT)
623 .show();
624 }
625 }
626
627 @Override
628 public void onStart() {
629 super.onStart();
630 mHandler.postDelayed(mTickExecutor, CALL_DURATION_UPDATE_INTERVAL);
631 this.binding.remoteVideo.setOnAspectRatioChanged(this);
632 }
633
634 @Override
635 public void onStop() {
636 mHandler.removeCallbacks(mTickExecutor);
637 binding.remoteVideo.release();
638 binding.remoteVideo.setOnAspectRatioChanged(null);
639 binding.localVideo.release();
640 final WeakReference<JingleRtpConnection> weakReference = this.rtpConnectionReference;
641 final JingleRtpConnection jingleRtpConnection =
642 weakReference == null ? null : weakReference.get();
643 if (jingleRtpConnection != null) {
644 releaseVideoTracks(jingleRtpConnection);
645 }
646 releaseProximityWakeLock();
647 super.onStop();
648 }
649
650 private void releaseVideoTracks(final JingleRtpConnection jingleRtpConnection) {
651 final Optional<VideoTrack> remoteVideo = jingleRtpConnection.getRemoteVideoTrack();
652 if (remoteVideo.isPresent()) {
653 remoteVideo.get().removeSink(binding.remoteVideo);
654 }
655 final Optional<VideoTrack> localVideo = jingleRtpConnection.getLocalVideoTrack();
656 if (localVideo.isPresent()) {
657 localVideo.get().removeSink(binding.localVideo);
658 }
659 }
660
661 @Override
662 public void onBackPressed() {
663 if (isConnected()) {
664 if (switchToPictureInPicture()) {
665 return;
666 }
667 } else {
668 endCall();
669 }
670 super.onBackPressed();
671 }
672
673 @Override
674 public void onUserLeaveHint() {
675 super.onUserLeaveHint();
676 if (switchToPictureInPicture()) {
677 return;
678 }
679 // TODO apparently this method is not getting called on Android 10 when using the task
680 // switcher
681 if (emptyReference(rtpConnectionReference) && xmppConnectionService != null) {
682 retractSessionProposal();
683 }
684 }
685
686 private boolean isConnected() {
687 final JingleRtpConnection connection =
688 this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
689 final RtpEndUserState endUserState =
690 connection == null ? null : connection.getEndUserState();
691 return STATES_CONSIDERED_CONNECTED.contains(endUserState)
692 || endUserState == RtpEndUserState.INCOMING_CONTENT_ADD;
693 }
694
695 private boolean switchToPictureInPicture() {
696 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && deviceSupportsPictureInPicture()) {
697 if (shouldBePictureInPicture()) {
698 startPictureInPicture();
699 return true;
700 }
701 }
702 return false;
703 }
704
705 @RequiresApi(api = Build.VERSION_CODES.O)
706 private void startPictureInPicture() {
707 try {
708 final Rational rational = this.binding.remoteVideo.getAspectRatio();
709 final Rational clippedRational = Rationals.clip(rational);
710 Log.d(
711 Config.LOGTAG,
712 "suggested rational " + rational + ". clipped to " + clippedRational);
713 enterPictureInPictureMode(
714 new PictureInPictureParams.Builder().setAspectRatio(clippedRational).build());
715 } catch (final IllegalStateException e) {
716 // this sometimes happens on Samsung phones (possibly when Knox is enabled)
717 Log.w(Config.LOGTAG, "unable to enter picture in picture mode", e);
718 }
719 }
720
721 @Override
722 public void onAspectRatioChanged(final Rational rational) {
723 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && isPictureInPicture()) {
724 final Rational clippedRational = Rationals.clip(rational);
725 Log.d(
726 Config.LOGTAG,
727 "suggested rational after aspect ratio change "
728 + rational
729 + ". clipped to "
730 + clippedRational);
731 setPictureInPictureParams(
732 new PictureInPictureParams.Builder().setAspectRatio(clippedRational).build());
733 }
734 }
735
736 private boolean deviceSupportsPictureInPicture() {
737 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
738 return getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE);
739 } else {
740 return false;
741 }
742 }
743
744 private boolean shouldBePictureInPicture() {
745 try {
746 final JingleRtpConnection rtpConnection = requireRtpConnection();
747 return rtpConnection.getMedia().contains(Media.VIDEO)
748 && Arrays.asList(
749 RtpEndUserState.ACCEPTING_CALL,
750 RtpEndUserState.CONNECTING,
751 RtpEndUserState.CONNECTED)
752 .contains(rtpConnection.getEndUserState());
753 } catch (final IllegalStateException e) {
754 return false;
755 }
756 }
757
758 private boolean initializeActivityWithRunningRtpSession(
759 final Account account, Jid with, String sessionId) {
760 final WeakReference<JingleRtpConnection> reference =
761 xmppConnectionService
762 .getJingleConnectionManager()
763 .findJingleRtpConnection(account, with, sessionId);
764 if (reference == null || reference.get() == null) {
765 final JingleConnectionManager.TerminatedRtpSession terminatedRtpSession =
766 xmppConnectionService
767 .getJingleConnectionManager()
768 .getTerminalSessionState(with, sessionId);
769 if (terminatedRtpSession == null) {
770 throw new IllegalStateException(
771 "failed to initialize activity with running rtp session. session not found");
772 }
773 initializeWithTerminatedSessionState(account, with, terminatedRtpSession);
774 return true;
775 }
776 this.rtpConnectionReference = reference;
777 final RtpEndUserState currentState = requireRtpConnection().getEndUserState();
778 final boolean verified = requireRtpConnection().isVerified();
779 if (currentState == RtpEndUserState.ENDED) {
780 finish();
781 return true;
782 }
783 final Set<Media> media = getMedia();
784 final ContentAddition contentAddition = getPendingContentAddition();
785 if (currentState == RtpEndUserState.INCOMING_CALL) {
786 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
787 }
788 if (JingleRtpConnection.STATES_SHOWING_ONGOING_CALL.contains(
789 requireRtpConnection().getState())) {
790 putScreenInCallMode();
791 }
792 setWidth(currentState);
793 updateVideoViews(currentState);
794 updateStateDisplay(currentState, media, contentAddition);
795 updateVerifiedShield(verified && STATES_SHOWING_SWITCH_TO_CHAT.contains(currentState));
796 updateButtonConfiguration(currentState, media, contentAddition);
797 updateIncomingCallScreen(currentState);
798 invalidateOptionsMenu();
799 return false;
800 }
801
802 private void initializeWithTerminatedSessionState(
803 final Account account,
804 final Jid with,
805 final JingleConnectionManager.TerminatedRtpSession terminatedRtpSession) {
806 Log.d(Config.LOGTAG, "initializeWithTerminatedSessionState()");
807 if (terminatedRtpSession.state == RtpEndUserState.ENDED) {
808 finish();
809 return;
810 }
811 final RtpEndUserState state = terminatedRtpSession.state;
812 resetIntent(account, with, terminatedRtpSession.state, terminatedRtpSession.media);
813 updateButtonConfiguration(state);
814 updateStateDisplay(state);
815 updateIncomingCallScreen(state);
816 updateCallDuration();
817 updateVerifiedShield(false);
818 invalidateOptionsMenu();
819 setWith(account.getRoster().getContact(with), state);
820 }
821
822 private void reInitializeActivityWithRunningRtpSession(
823 final Account account, Jid with, String sessionId) {
824 runOnUiThread(() -> initializeActivityWithRunningRtpSession(account, with, sessionId));
825 resetIntent(account, with, sessionId);
826 }
827
828 private void resetIntent(final Account account, final Jid with, final String sessionId) {
829 final Intent intent = new Intent(Intent.ACTION_VIEW);
830 intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
831 intent.putExtra(EXTRA_WITH, with.toEscapedString());
832 intent.putExtra(EXTRA_SESSION_ID, sessionId);
833 setIntent(intent);
834 }
835
836 private void ensureSurfaceViewRendererIsSetup(final SurfaceViewRenderer surfaceViewRenderer) {
837 surfaceViewRenderer.setVisibility(View.VISIBLE);
838 try {
839 surfaceViewRenderer.init(requireRtpConnection().getEglBaseContext(), null);
840 } catch (final IllegalStateException ignored) {
841 // SurfaceViewRenderer was already initialized
842 } catch (final RuntimeException e) {
843 if (Throwables.getRootCause(e) instanceof GLException glException) {
844 Log.w(Config.LOGTAG, "could not set up hardware renderer", glException);
845 }
846 }
847 surfaceViewRenderer.setEnableHardwareScaler(true);
848 }
849
850 private void updateStateDisplay(final RtpEndUserState state) {
851 updateStateDisplay(state, Collections.emptySet(), null);
852 }
853
854 private void updateStateDisplay(
855 final RtpEndUserState state,
856 final Set<Media> media,
857 final ContentAddition contentAddition) {
858 switch (state) {
859 case INCOMING_CALL -> {
860 Preconditions.checkArgument(media.size() > 0, "Media must not be empty");
861 if (media.contains(Media.VIDEO)) {
862 setTitle(R.string.rtp_state_incoming_video_call);
863 } else {
864 setTitle(R.string.rtp_state_incoming_call);
865 }
866 }
867 case INCOMING_CONTENT_ADD -> {
868 if (contentAddition != null && contentAddition.media().contains(Media.VIDEO)) {
869 setTitle(R.string.rtp_state_content_add_video);
870 } else {
871 setTitle(R.string.rtp_state_content_add);
872 }
873 }
874 case CONNECTING -> setTitle(R.string.rtp_state_connecting);
875 case CONNECTED -> setTitle(R.string.rtp_state_connected);
876 case RECONNECTING -> setTitle(R.string.rtp_state_reconnecting);
877 case ACCEPTING_CALL -> setTitle(R.string.rtp_state_accepting_call);
878 case ENDING_CALL -> setTitle(R.string.rtp_state_ending_call);
879 case FINDING_DEVICE -> setTitle(R.string.rtp_state_finding_device);
880 case RINGING -> setTitle(R.string.rtp_state_ringing);
881 case DECLINED_OR_BUSY -> setTitle(R.string.rtp_state_declined_or_busy);
882 case CONNECTIVITY_ERROR -> setTitle(R.string.rtp_state_connectivity_error);
883 case CONNECTIVITY_LOST_ERROR -> setTitle(R.string.rtp_state_connectivity_lost_error);
884 case RETRACTED -> setTitle(R.string.rtp_state_retracted);
885 case APPLICATION_ERROR -> setTitle(R.string.rtp_state_application_failure);
886 case SECURITY_ERROR -> setTitle(R.string.rtp_state_security_error);
887 case ENDED -> throw new IllegalStateException(
888 "Activity should have called finishAndReleaseWakeLock();");
889 default -> throw new IllegalStateException(
890 String.format("State %s has not been handled in UI", state));
891 }
892 }
893
894 private void updateVerifiedShield(final boolean verified) {
895 if (isPictureInPicture()) {
896 this.binding.verified.setVisibility(View.GONE);
897 return;
898 }
899 this.binding.verified.setVisibility(verified ? View.VISIBLE : View.GONE);
900 }
901
902 private void updateIncomingCallScreen(final RtpEndUserState state) {
903 updateIncomingCallScreen(state, null);
904 }
905
906 private void updateIncomingCallScreen(final RtpEndUserState state, final Contact contact) {
907 if (state == RtpEndUserState.INCOMING_CALL || state == RtpEndUserState.ACCEPTING_CALL) {
908 final boolean show = getResources().getBoolean(R.bool.show_avatar_incoming_call);
909 if (show) {
910 binding.contactPhoto.setVisibility(View.VISIBLE);
911 if (contact == null) {
912 AvatarWorkerTask.loadAvatar(
913 getWith(), binding.contactPhoto, R.dimen.publish_avatar_size);
914 } else {
915 AvatarWorkerTask.loadAvatar(
916 contact, binding.contactPhoto, R.dimen.publish_avatar_size);
917 }
918 } else {
919 binding.contactPhoto.setVisibility(View.GONE);
920 }
921 final Account account = contact == null ? getWith().getAccount() : contact.getAccount();
922 binding.usingAccount.setVisibility(View.VISIBLE);
923 binding.usingAccount.setText(
924 getString(
925 R.string.using_account,
926 account.getJid().asBareJid().toEscapedString()));
927 } else {
928 binding.usingAccount.setVisibility(View.GONE);
929 binding.contactPhoto.setVisibility(View.GONE);
930 }
931 }
932
933 private Set<Media> getMedia() {
934 return requireRtpConnection().getMedia();
935 }
936
937 public ContentAddition getPendingContentAddition() {
938 return requireRtpConnection().getPendingContentAddition();
939 }
940
941 private void updateButtonConfiguration(final RtpEndUserState state) {
942 updateButtonConfiguration(state, Collections.emptySet(), null);
943 }
944
945 @SuppressLint("RestrictedApi")
946 private void updateButtonConfiguration(
947 final RtpEndUserState state,
948 final Set<Media> media,
949 final ContentAddition contentAddition) {
950 if (state == RtpEndUserState.ENDING_CALL || isPictureInPicture()) {
951 this.binding.rejectCall.setVisibility(View.INVISIBLE);
952 this.binding.endCall.setVisibility(View.INVISIBLE);
953 this.binding.acceptCall.setVisibility(View.INVISIBLE);
954 } else if (state == RtpEndUserState.INCOMING_CALL) {
955 this.binding.rejectCall.setContentDescription(getString(R.string.dismiss_call));
956 this.binding.rejectCall.setOnClickListener(this::rejectCall);
957 this.binding.rejectCall.setImageResource(R.drawable.ic_call_end_white_48dp);
958 this.binding.rejectCall.setVisibility(View.VISIBLE);
959 this.binding.endCall.setVisibility(View.INVISIBLE);
960 this.binding.acceptCall.setContentDescription(getString(R.string.answer_call));
961 this.binding.acceptCall.setOnClickListener(this::acceptCall);
962 this.binding.acceptCall.setImageResource(R.drawable.ic_call_white_48dp);
963 this.binding.acceptCall.setVisibility(View.VISIBLE);
964 } else if (state == RtpEndUserState.INCOMING_CONTENT_ADD) {
965 this.binding.rejectCall.setContentDescription(
966 getString(R.string.reject_switch_to_video));
967 this.binding.rejectCall.setOnClickListener(this::rejectContentAdd);
968 this.binding.rejectCall.setImageResource(R.drawable.ic_clear_white_48dp);
969 this.binding.rejectCall.setVisibility(View.VISIBLE);
970 this.binding.endCall.setVisibility(View.INVISIBLE);
971 this.binding.acceptCall.setContentDescription(getString(R.string.accept));
972 this.binding.acceptCall.setOnClickListener((v -> acceptContentAdd(contentAddition)));
973 this.binding.acceptCall.setImageResource(R.drawable.ic_baseline_check_24);
974 this.binding.acceptCall.setVisibility(View.VISIBLE);
975 } else if (state == RtpEndUserState.DECLINED_OR_BUSY) {
976 this.binding.rejectCall.setContentDescription(getString(R.string.exit));
977 this.binding.rejectCall.setOnClickListener(this::exit);
978 this.binding.rejectCall.setImageResource(R.drawable.ic_clear_white_48dp);
979 this.binding.rejectCall.setVisibility(View.VISIBLE);
980 this.binding.endCall.setVisibility(View.INVISIBLE);
981 this.binding.acceptCall.setContentDescription(getString(R.string.record_voice_mail));
982 this.binding.acceptCall.setOnClickListener(this::recordVoiceMail);
983 this.binding.acceptCall.setImageResource(R.drawable.ic_voicemail_white_24dp);
984 this.binding.acceptCall.setVisibility(View.VISIBLE);
985 } else if (asList(
986 RtpEndUserState.CONNECTIVITY_ERROR,
987 RtpEndUserState.CONNECTIVITY_LOST_ERROR,
988 RtpEndUserState.APPLICATION_ERROR,
989 RtpEndUserState.RETRACTED,
990 RtpEndUserState.SECURITY_ERROR)
991 .contains(state)) {
992 this.binding.rejectCall.setContentDescription(getString(R.string.exit));
993 this.binding.rejectCall.setOnClickListener(this::exit);
994 this.binding.rejectCall.setImageResource(R.drawable.ic_clear_white_48dp);
995 this.binding.rejectCall.setVisibility(View.VISIBLE);
996 this.binding.endCall.setVisibility(View.INVISIBLE);
997 this.binding.acceptCall.setContentDescription(getString(R.string.try_again));
998 this.binding.acceptCall.setOnClickListener(this::retry);
999 this.binding.acceptCall.setImageResource(R.drawable.ic_replay_white_48dp);
1000 this.binding.acceptCall.setVisibility(View.VISIBLE);
1001 } else {
1002 this.binding.rejectCall.setVisibility(View.INVISIBLE);
1003 this.binding.endCall.setContentDescription(getString(R.string.hang_up));
1004 this.binding.endCall.setOnClickListener(this::endCall);
1005 this.binding.endCall.setImageResource(R.drawable.ic_call_end_white_48dp);
1006 this.binding.endCall.setVisibility(View.VISIBLE);
1007 this.binding.acceptCall.setVisibility(View.INVISIBLE);
1008 }
1009 updateInCallButtonConfiguration(state, media);
1010 }
1011
1012 private boolean isPictureInPicture() {
1013 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
1014 return isInPictureInPictureMode();
1015 } else {
1016 return false;
1017 }
1018 }
1019
1020 private void updateInCallButtonConfiguration() {
1021 updateInCallButtonConfiguration(
1022 requireRtpConnection().getEndUserState(), requireRtpConnection().getMedia());
1023 }
1024
1025 @SuppressLint("RestrictedApi")
1026 private void updateInCallButtonConfiguration(
1027 final RtpEndUserState state, final Set<Media> media) {
1028 if (STATES_CONSIDERED_CONNECTED.contains(state) && !isPictureInPicture()) {
1029 Preconditions.checkArgument(media.size() > 0, "Media must not be empty");
1030 if (media.contains(Media.VIDEO)) {
1031 final JingleRtpConnection rtpConnection = requireRtpConnection();
1032 updateInCallButtonConfigurationVideo(
1033 rtpConnection.isVideoEnabled(), rtpConnection.isCameraSwitchable());
1034 } else {
1035 final AppRTCAudioManager audioManager = requireRtpConnection().getAudioManager();
1036 updateInCallButtonConfigurationSpeaker(
1037 audioManager.getSelectedAudioDevice(),
1038 audioManager.getAudioDevices().size());
1039 this.binding.inCallActionFarRight.setVisibility(View.GONE);
1040 }
1041 if (media.contains(Media.AUDIO)) {
1042 updateInCallButtonConfigurationMicrophone(
1043 requireRtpConnection().isMicrophoneEnabled());
1044 } else {
1045 this.binding.inCallActionLeft.setVisibility(View.GONE);
1046 }
1047 } else {
1048 this.binding.inCallActionLeft.setVisibility(View.GONE);
1049 this.binding.inCallActionRight.setVisibility(View.GONE);
1050 this.binding.inCallActionFarRight.setVisibility(View.GONE);
1051 }
1052 }
1053
1054 @SuppressLint("RestrictedApi")
1055 private void updateInCallButtonConfigurationSpeaker(
1056 final AppRTCAudioManager.AudioDevice selectedAudioDevice, final int numberOfChoices) {
1057 switch (selectedAudioDevice) {
1058 case EARPIECE -> {
1059 this.binding.inCallActionRight.setImageResource(
1060 R.drawable.ic_volume_off_black_24dp);
1061 if (numberOfChoices >= 2) {
1062 this.binding.inCallActionRight.setOnClickListener(this::switchToSpeaker);
1063 } else {
1064 this.binding.inCallActionRight.setOnClickListener(null);
1065 this.binding.inCallActionRight.setClickable(false);
1066 }
1067 }
1068 case WIRED_HEADSET -> {
1069 this.binding.inCallActionRight.setImageResource(R.drawable.ic_headset_black_24dp);
1070 this.binding.inCallActionRight.setOnClickListener(null);
1071 this.binding.inCallActionRight.setClickable(false);
1072 }
1073 case SPEAKER_PHONE -> {
1074 this.binding.inCallActionRight.setImageResource(R.drawable.ic_volume_up_black_24dp);
1075 if (numberOfChoices >= 2) {
1076 this.binding.inCallActionRight.setOnClickListener(this::switchToEarpiece);
1077 } else {
1078 this.binding.inCallActionRight.setOnClickListener(null);
1079 this.binding.inCallActionRight.setClickable(false);
1080 }
1081 }
1082 case BLUETOOTH -> {
1083 this.binding.inCallActionRight.setImageResource(
1084 R.drawable.ic_bluetooth_audio_black_24dp);
1085 this.binding.inCallActionRight.setOnClickListener(null);
1086 this.binding.inCallActionRight.setClickable(false);
1087 }
1088 }
1089 this.binding.inCallActionRight.setVisibility(View.VISIBLE);
1090 }
1091
1092 @SuppressLint("RestrictedApi")
1093 private void updateInCallButtonConfigurationVideo(
1094 final boolean videoEnabled, final boolean isCameraSwitchable) {
1095 this.binding.inCallActionRight.setVisibility(View.VISIBLE);
1096 if (isCameraSwitchable) {
1097 this.binding.inCallActionFarRight.setImageResource(
1098 R.drawable.ic_flip_camera_android_black_24dp);
1099 this.binding.inCallActionFarRight.setVisibility(View.VISIBLE);
1100 this.binding.inCallActionFarRight.setOnClickListener(this::switchCamera);
1101 } else {
1102 this.binding.inCallActionFarRight.setVisibility(View.GONE);
1103 }
1104 if (videoEnabled) {
1105 this.binding.inCallActionRight.setImageResource(R.drawable.ic_videocam_black_24dp);
1106 this.binding.inCallActionRight.setOnClickListener(this::disableVideo);
1107 } else {
1108 this.binding.inCallActionRight.setImageResource(R.drawable.ic_videocam_off_black_24dp);
1109 this.binding.inCallActionRight.setOnClickListener(this::enableVideo);
1110 }
1111 }
1112
1113 private void switchCamera(final View view) {
1114 Futures.addCallback(
1115 requireRtpConnection().switchCamera(),
1116 new FutureCallback<>() {
1117 @Override
1118 public void onSuccess(@Nullable Boolean isFrontCamera) {
1119 binding.localVideo.setMirror(Boolean.TRUE.equals(isFrontCamera));
1120 }
1121
1122 @Override
1123 public void onFailure(@NonNull final Throwable throwable) {
1124 Log.d(
1125 Config.LOGTAG,
1126 "could not switch camera",
1127 Throwables.getRootCause(throwable));
1128 Toast.makeText(
1129 RtpSessionActivity.this,
1130 R.string.could_not_switch_camera,
1131 Toast.LENGTH_LONG)
1132 .show();
1133 }
1134 },
1135 MainThreadExecutor.getInstance());
1136 }
1137
1138 private void enableVideo(View view) {
1139 try {
1140 requireRtpConnection().setVideoEnabled(true);
1141 } catch (final IllegalStateException e) {
1142 Toast.makeText(this, R.string.unable_to_enable_video, Toast.LENGTH_SHORT).show();
1143 return;
1144 }
1145 updateInCallButtonConfigurationVideo(true, requireRtpConnection().isCameraSwitchable());
1146 }
1147
1148 private void disableVideo(View view) {
1149 final JingleRtpConnection rtpConnection = requireRtpConnection();
1150 final ContentAddition pending = rtpConnection.getPendingContentAddition();
1151 if (pending != null && pending.direction == ContentAddition.Direction.OUTGOING) {
1152 rtpConnection.retractContentAdd();
1153 return;
1154 }
1155 requireRtpConnection().setVideoEnabled(false);
1156 updateInCallButtonConfigurationVideo(false, requireRtpConnection().isCameraSwitchable());
1157 }
1158
1159 @SuppressLint("RestrictedApi")
1160 private void updateInCallButtonConfigurationMicrophone(final boolean microphoneEnabled) {
1161 if (microphoneEnabled) {
1162 this.binding.inCallActionLeft.setImageResource(R.drawable.ic_mic_black_24dp);
1163 this.binding.inCallActionLeft.setOnClickListener(this::disableMicrophone);
1164 } else {
1165 this.binding.inCallActionLeft.setImageResource(R.drawable.ic_mic_off_black_24dp);
1166 this.binding.inCallActionLeft.setOnClickListener(this::enableMicrophone);
1167 }
1168 this.binding.inCallActionLeft.setVisibility(View.VISIBLE);
1169 }
1170
1171 private void updateCallDuration() {
1172 final JingleRtpConnection connection =
1173 this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1174 if (connection == null || connection.getMedia().contains(Media.VIDEO)) {
1175 this.binding.duration.setVisibility(View.GONE);
1176 return;
1177 }
1178 if (connection.zeroDuration()) {
1179 this.binding.duration.setVisibility(View.GONE);
1180 } else {
1181 this.binding.duration.setText(
1182 TimeFrameUtils.formatElapsedTime(connection.getCallDuration(), false));
1183 this.binding.duration.setVisibility(View.VISIBLE);
1184 }
1185 }
1186
1187 private void updateVideoViews(final RtpEndUserState state) {
1188 if (END_CARD.contains(state) || state == RtpEndUserState.ENDING_CALL) {
1189 binding.localVideo.setVisibility(View.GONE);
1190 binding.localVideo.release();
1191 binding.remoteVideoWrapper.setVisibility(View.GONE);
1192 binding.remoteVideo.release();
1193 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1194 if (isPictureInPicture()) {
1195 binding.appBarLayout.setVisibility(View.GONE);
1196 binding.pipPlaceholder.setVisibility(View.VISIBLE);
1197 if (Arrays.asList(
1198 RtpEndUserState.APPLICATION_ERROR,
1199 RtpEndUserState.CONNECTIVITY_ERROR,
1200 RtpEndUserState.SECURITY_ERROR)
1201 .contains(state)) {
1202 binding.pipWarning.setVisibility(View.VISIBLE);
1203 binding.pipWaiting.setVisibility(View.GONE);
1204 } else {
1205 binding.pipWarning.setVisibility(View.GONE);
1206 binding.pipWaiting.setVisibility(View.GONE);
1207 }
1208 } else {
1209 binding.appBarLayout.setVisibility(View.VISIBLE);
1210 binding.pipPlaceholder.setVisibility(View.GONE);
1211 }
1212 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1213 return;
1214 }
1215 if (isPictureInPicture() && STATES_SHOWING_PIP_PLACEHOLDER.contains(state)) {
1216 binding.localVideo.setVisibility(View.GONE);
1217 binding.remoteVideoWrapper.setVisibility(View.GONE);
1218 binding.appBarLayout.setVisibility(View.GONE);
1219 binding.pipPlaceholder.setVisibility(View.VISIBLE);
1220 binding.pipWarning.setVisibility(View.GONE);
1221 binding.pipWaiting.setVisibility(View.VISIBLE);
1222 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1223 return;
1224 }
1225 final Optional<VideoTrack> localVideoTrack = getLocalVideoTrack();
1226 if (localVideoTrack.isPresent() && !isPictureInPicture()) {
1227 ensureSurfaceViewRendererIsSetup(binding.localVideo);
1228 // paint local view over remote view
1229 binding.localVideo.setZOrderMediaOverlay(true);
1230 binding.localVideo.setMirror(requireRtpConnection().isFrontCamera());
1231 addSink(localVideoTrack.get(), binding.localVideo);
1232 } else {
1233 binding.localVideo.setVisibility(View.GONE);
1234 }
1235 final Optional<VideoTrack> remoteVideoTrack = getRemoteVideoTrack();
1236 if (remoteVideoTrack.isPresent()) {
1237 ensureSurfaceViewRendererIsSetup(binding.remoteVideo);
1238 addSink(remoteVideoTrack.get(), binding.remoteVideo);
1239 binding.remoteVideo.setScalingType(
1240 RendererCommon.ScalingType.SCALE_ASPECT_FILL,
1241 RendererCommon.ScalingType.SCALE_ASPECT_FIT);
1242 if (state == RtpEndUserState.CONNECTED) {
1243 binding.appBarLayout.setVisibility(View.GONE);
1244 getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1245 binding.remoteVideoWrapper.setVisibility(View.VISIBLE);
1246 } else {
1247 binding.appBarLayout.setVisibility(View.VISIBLE);
1248 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1249 binding.remoteVideoWrapper.setVisibility(View.GONE);
1250 }
1251 if (isPictureInPicture() && !requireRtpConnection().isMicrophoneEnabled()) {
1252 binding.pipLocalMicOffIndicator.setVisibility(View.VISIBLE);
1253 } else {
1254 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1255 }
1256 } else {
1257 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1258 binding.remoteVideoWrapper.setVisibility(View.GONE);
1259 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1260 }
1261 }
1262
1263 private Optional<VideoTrack> getLocalVideoTrack() {
1264 final JingleRtpConnection connection =
1265 this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1266 if (connection == null) {
1267 return Optional.absent();
1268 }
1269 return connection.getLocalVideoTrack();
1270 }
1271
1272 private Optional<VideoTrack> getRemoteVideoTrack() {
1273 final JingleRtpConnection connection =
1274 this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1275 if (connection == null) {
1276 return Optional.absent();
1277 }
1278 return connection.getRemoteVideoTrack();
1279 }
1280
1281 private void disableMicrophone(View view) {
1282 final JingleRtpConnection rtpConnection = requireRtpConnection();
1283 if (rtpConnection.setMicrophoneEnabled(false)) {
1284 updateInCallButtonConfiguration();
1285 }
1286 }
1287
1288 private void enableMicrophone(View view) {
1289 final JingleRtpConnection rtpConnection = requireRtpConnection();
1290 if (rtpConnection.setMicrophoneEnabled(true)) {
1291 updateInCallButtonConfiguration();
1292 }
1293 }
1294
1295 private void switchToEarpiece(View view) {
1296 requireRtpConnection()
1297 .getAudioManager()
1298 .setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.EARPIECE);
1299 acquireProximityWakeLock();
1300 }
1301
1302 private void switchToSpeaker(View view) {
1303 requireRtpConnection()
1304 .getAudioManager()
1305 .setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.SPEAKER_PHONE);
1306 releaseProximityWakeLock();
1307 }
1308
1309 private void retry(View view) {
1310 final Intent intent = getIntent();
1311 final Account account = extractAccount(intent);
1312 final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
1313 final String lastAction = intent.getStringExtra(EXTRA_LAST_ACTION);
1314 final String action = intent.getAction();
1315 final Set<Media> media = actionToMedia(lastAction == null ? action : lastAction);
1316 this.rtpConnectionReference = null;
1317 Log.d(Config.LOGTAG, "attempting retry with " + with.toEscapedString());
1318 proposeJingleRtpSession(account, with, media);
1319 }
1320
1321 private void exit(final View view) {
1322 finish();
1323 }
1324
1325 private void recordVoiceMail(final View view) {
1326 final Intent intent = getIntent();
1327 final Account account = extractAccount(intent);
1328 final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
1329 final Conversation conversation =
1330 xmppConnectionService.findOrCreateConversation(account, with, false, true);
1331 final Intent launchIntent = new Intent(this, ConversationsActivity.class);
1332 launchIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
1333 launchIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
1334 launchIntent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
1335 launchIntent.putExtra(
1336 ConversationsActivity.EXTRA_POST_INIT_ACTION,
1337 ConversationsActivity.POST_ACTION_RECORD_VOICE);
1338 startActivity(launchIntent);
1339 finish();
1340 }
1341
1342 private Contact getWith() {
1343 final AbstractJingleConnection.Id id = requireRtpConnection().getId();
1344 final Account account = id.account;
1345 return account.getRoster().getContact(id.with);
1346 }
1347
1348 private JingleRtpConnection requireRtpConnection() {
1349 final JingleRtpConnection connection =
1350 this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1351 if (connection == null) {
1352 throw new IllegalStateException("No RTP connection found");
1353 }
1354 return connection;
1355 }
1356
1357 @Override
1358 public void onJingleRtpConnectionUpdate(
1359 Account account, Jid with, final String sessionId, RtpEndUserState state) {
1360 Log.d(Config.LOGTAG, "onJingleRtpConnectionUpdate(" + state + ")");
1361 if (END_CARD.contains(state)) {
1362 Log.d(Config.LOGTAG, "end card reached");
1363 releaseProximityWakeLock();
1364 runOnUiThread(
1365 () -> getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON));
1366 }
1367 if (with.isBareJid()) {
1368 updateRtpSessionProposalState(account, with, state);
1369 return;
1370 }
1371 if (emptyReference(this.rtpConnectionReference)) {
1372 if (END_CARD.contains(state)) {
1373 Log.d(Config.LOGTAG, "not reinitializing session");
1374 return;
1375 }
1376 // this happens when going from proposed session to actual session
1377 reInitializeActivityWithRunningRtpSession(account, with, sessionId);
1378 return;
1379 }
1380 final AbstractJingleConnection.Id id = requireRtpConnection().getId();
1381 final boolean verified = requireRtpConnection().isVerified();
1382 final Set<Media> media = getMedia();
1383 lockOrientation(media);
1384 final ContentAddition contentAddition = getPendingContentAddition();
1385 final Contact contact = getWith();
1386 if (account == id.account && id.with.equals(with) && id.sessionId.equals(sessionId)) {
1387 if (state == RtpEndUserState.ENDED) {
1388 finish();
1389 return;
1390 }
1391 runOnUiThread(
1392 () -> {
1393 updateStateDisplay(state, media, contentAddition);
1394 updateVerifiedShield(
1395 verified && STATES_SHOWING_SWITCH_TO_CHAT.contains(state));
1396 updateButtonConfiguration(state, media, contentAddition);
1397 updateVideoViews(state);
1398 updateIncomingCallScreen(state, contact);
1399 invalidateOptionsMenu();
1400 });
1401 if (END_CARD.contains(state)) {
1402 final JingleRtpConnection rtpConnection = requireRtpConnection();
1403 resetIntent(account, with, state, rtpConnection.getMedia());
1404 releaseVideoTracks(rtpConnection);
1405 this.rtpConnectionReference = null;
1406 }
1407 } else {
1408 Log.d(Config.LOGTAG, "received update for other rtp session");
1409 }
1410 }
1411
1412 @Override
1413 public void onAudioDeviceChanged(
1414 final AppRTCAudioManager.AudioDevice selectedAudioDevice,
1415 final Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
1416 Log.d(
1417 Config.LOGTAG,
1418 "onAudioDeviceChanged in activity: selected:"
1419 + selectedAudioDevice
1420 + ", available:"
1421 + availableAudioDevices);
1422 try {
1423 final RtpEndUserState endUserState = requireRtpConnection().getEndUserState();
1424 final Set<Media> media = getMedia();
1425 if (END_CARD.contains(endUserState)) {
1426 Log.d(
1427 Config.LOGTAG,
1428 "onAudioDeviceChanged() nothing to do because end card has been reached");
1429 } else {
1430 if (Media.audioOnly(media) && endUserState == RtpEndUserState.CONNECTED) {
1431 final AppRTCAudioManager audioManager =
1432 requireRtpConnection().getAudioManager();
1433 updateInCallButtonConfigurationSpeaker(
1434 audioManager.getSelectedAudioDevice(),
1435 audioManager.getAudioDevices().size());
1436 }
1437 Log.d(
1438 Config.LOGTAG,
1439 "put proximity wake lock into proper state after device update");
1440 putProximityWakeLockInProperState(selectedAudioDevice);
1441 }
1442 } catch (final IllegalStateException e) {
1443 Log.d(Config.LOGTAG, "RTP connection was not available when audio device changed");
1444 }
1445 }
1446
1447 private void updateRtpSessionProposalState(
1448 final Account account, final Jid with, final RtpEndUserState state) {
1449 final Intent currentIntent = getIntent();
1450 final String withExtra =
1451 currentIntent == null ? null : currentIntent.getStringExtra(EXTRA_WITH);
1452 if (withExtra == null) {
1453 return;
1454 }
1455 if (Jid.ofEscaped(withExtra).asBareJid().equals(with)) {
1456 runOnUiThread(
1457 () -> {
1458 updateVerifiedShield(false);
1459 updateStateDisplay(state);
1460 updateButtonConfiguration(state);
1461 updateIncomingCallScreen(state);
1462 invalidateOptionsMenu();
1463 });
1464 resetIntent(account, with, state, actionToMedia(currentIntent.getAction()));
1465 }
1466 }
1467
1468 private void resetIntent(final Bundle extras) {
1469 final Intent intent = new Intent(Intent.ACTION_VIEW);
1470 intent.putExtras(extras);
1471 setIntent(intent);
1472 }
1473
1474 private void resetIntent(
1475 final Account account, Jid with, final RtpEndUserState state, final Set<Media> media) {
1476 final Intent intent = new Intent(Intent.ACTION_VIEW);
1477 intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
1478 if (RtpCapability.jmiSupport(account.getRoster().getContact(with))) {
1479 intent.putExtra(EXTRA_WITH, with.asBareJid().toEscapedString());
1480 } else {
1481 intent.putExtra(EXTRA_WITH, with.toEscapedString());
1482 }
1483 intent.putExtra(EXTRA_LAST_REPORTED_STATE, state.toString());
1484 intent.putExtra(
1485 EXTRA_LAST_ACTION,
1486 media.contains(Media.VIDEO) ? ACTION_MAKE_VIDEO_CALL : ACTION_MAKE_VOICE_CALL);
1487 setIntent(intent);
1488 }
1489
1490 private static boolean emptyReference(final WeakReference<?> weakReference) {
1491 return weakReference == null || weakReference.get() == null;
1492 }
1493}