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