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