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