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