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 finish();
650 return true;
651 }
652 final Set<Media> media = getMedia();
653 if (currentState == RtpEndUserState.INCOMING_CALL) {
654 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
655 }
656 if (JingleRtpConnection.STATES_SHOWING_ONGOING_CALL.contains(
657 requireRtpConnection().getState())) {
658 putScreenInCallMode();
659 }
660 binding.with.setText(getWith().getDisplayName());
661 updateVideoViews(currentState);
662 updateStateDisplay(currentState, media);
663 updateVerifiedShield(verified && STATES_SHOWING_SWITCH_TO_CHAT.contains(currentState));
664 updateButtonConfiguration(currentState, media);
665 updateProfilePicture(currentState);
666 invalidateOptionsMenu();
667 return false;
668 }
669
670 private void initializeWithTerminatedSessionState(
671 final Account account,
672 final Jid with,
673 final JingleConnectionManager.TerminatedRtpSession terminatedRtpSession) {
674 Log.d(Config.LOGTAG, "initializeWithTerminatedSessionState()");
675 if (terminatedRtpSession.state == RtpEndUserState.ENDED) {
676 finish();
677 return;
678 }
679 RtpEndUserState state = terminatedRtpSession.state;
680 resetIntent(account, with, terminatedRtpSession.state, terminatedRtpSession.media);
681 updateButtonConfiguration(state);
682 updateStateDisplay(state);
683 updateProfilePicture(state);
684 updateCallDuration();
685 updateVerifiedShield(false);
686 invalidateOptionsMenu();
687 binding.with.setText(account.getRoster().getContact(with).getDisplayName());
688 }
689
690 private void reInitializeActivityWithRunningRtpSession(
691 final Account account, Jid with, String sessionId) {
692 runOnUiThread(() -> initializeActivityWithRunningRtpSession(account, with, sessionId));
693 resetIntent(account, with, sessionId);
694 }
695
696 private void resetIntent(final Account account, final Jid with, final String sessionId) {
697 final Intent intent = new Intent(Intent.ACTION_VIEW);
698 intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
699 intent.putExtra(EXTRA_WITH, with.toEscapedString());
700 intent.putExtra(EXTRA_SESSION_ID, sessionId);
701 setIntent(intent);
702 }
703
704 private void ensureSurfaceViewRendererIsSetup(final SurfaceViewRenderer surfaceViewRenderer) {
705 surfaceViewRenderer.setVisibility(View.VISIBLE);
706 try {
707 surfaceViewRenderer.init(requireRtpConnection().getEglBaseContext(), null);
708 } catch (final IllegalStateException e) {
709 // Log.d(Config.LOGTAG, "SurfaceViewRenderer was already initialized");
710 }
711 surfaceViewRenderer.setEnableHardwareScaler(true);
712 }
713
714 private void updateStateDisplay(final RtpEndUserState state) {
715 updateStateDisplay(state, Collections.emptySet());
716 }
717
718 private void updateStateDisplay(final RtpEndUserState state, final Set<Media> media) {
719 switch (state) {
720 case INCOMING_CALL:
721 Preconditions.checkArgument(media.size() > 0, "Media must not be empty");
722 if (media.contains(Media.VIDEO)) {
723 setTitle(R.string.rtp_state_incoming_video_call);
724 } else {
725 setTitle(R.string.rtp_state_incoming_call);
726 }
727 break;
728 case CONNECTING:
729 setTitle(R.string.rtp_state_connecting);
730 break;
731 case CONNECTED:
732 setTitle(R.string.rtp_state_connected);
733 break;
734 case RECONNECTING:
735 setTitle(R.string.rtp_state_reconnecting);
736 break;
737 case ACCEPTING_CALL:
738 setTitle(R.string.rtp_state_accepting_call);
739 break;
740 case ENDING_CALL:
741 setTitle(R.string.rtp_state_ending_call);
742 break;
743 case FINDING_DEVICE:
744 setTitle(R.string.rtp_state_finding_device);
745 break;
746 case RINGING:
747 setTitle(R.string.rtp_state_ringing);
748 break;
749 case DECLINED_OR_BUSY:
750 setTitle(R.string.rtp_state_declined_or_busy);
751 break;
752 case CONNECTIVITY_ERROR:
753 setTitle(R.string.rtp_state_connectivity_error);
754 break;
755 case CONNECTIVITY_LOST_ERROR:
756 setTitle(R.string.rtp_state_connectivity_lost_error);
757 break;
758 case RETRACTED:
759 setTitle(R.string.rtp_state_retracted);
760 break;
761 case APPLICATION_ERROR:
762 setTitle(R.string.rtp_state_application_failure);
763 break;
764 case SECURITY_ERROR:
765 setTitle(R.string.rtp_state_security_error);
766 break;
767 case ENDED:
768 throw new IllegalStateException(
769 "Activity should have called finishAndReleaseWakeLock();");
770 default:
771 throw new IllegalStateException(
772 String.format("State %s has not been handled in UI", state));
773 }
774 }
775
776 private void updateVerifiedShield(final boolean verified) {
777 if (isPictureInPicture()) {
778 this.binding.verified.setVisibility(View.GONE);
779 return;
780 }
781 this.binding.verified.setVisibility(verified ? View.VISIBLE : View.GONE);
782 }
783
784 private void updateProfilePicture(final RtpEndUserState state) {
785 updateProfilePicture(state, null);
786 }
787
788 private void updateProfilePicture(final RtpEndUserState state, final Contact contact) {
789 if (state == RtpEndUserState.INCOMING_CALL || state == RtpEndUserState.ACCEPTING_CALL) {
790 final boolean show = getResources().getBoolean(R.bool.show_avatar_incoming_call);
791 if (show) {
792 binding.contactPhoto.setVisibility(View.VISIBLE);
793 if (contact == null) {
794 AvatarWorkerTask.loadAvatar(
795 getWith(), binding.contactPhoto, R.dimen.publish_avatar_size);
796 } else {
797 AvatarWorkerTask.loadAvatar(
798 contact, binding.contactPhoto, R.dimen.publish_avatar_size);
799 }
800 } else {
801 binding.contactPhoto.setVisibility(View.GONE);
802 }
803 } else {
804 binding.contactPhoto.setVisibility(View.GONE);
805 }
806 }
807
808 private Set<Media> getMedia() {
809 return requireRtpConnection().getMedia();
810 }
811
812 private void updateButtonConfiguration(final RtpEndUserState state) {
813 updateButtonConfiguration(state, Collections.emptySet());
814 }
815
816 @SuppressLint("RestrictedApi")
817 private void updateButtonConfiguration(final RtpEndUserState state, final Set<Media> media) {
818 if (state == RtpEndUserState.ENDING_CALL || isPictureInPicture()) {
819 this.binding.rejectCall.setVisibility(View.INVISIBLE);
820 this.binding.endCall.setVisibility(View.INVISIBLE);
821 this.binding.acceptCall.setVisibility(View.INVISIBLE);
822 } else if (state == RtpEndUserState.INCOMING_CALL) {
823 this.binding.rejectCall.setContentDescription(getString(R.string.dismiss_call));
824 this.binding.rejectCall.setOnClickListener(this::rejectCall);
825 this.binding.rejectCall.setImageResource(R.drawable.ic_call_end_white_48dp);
826 this.binding.rejectCall.setVisibility(View.VISIBLE);
827 this.binding.endCall.setVisibility(View.INVISIBLE);
828 this.binding.acceptCall.setContentDescription(getString(R.string.answer_call));
829 this.binding.acceptCall.setOnClickListener(this::acceptCall);
830 this.binding.acceptCall.setImageResource(R.drawable.ic_call_white_48dp);
831 this.binding.acceptCall.setVisibility(View.VISIBLE);
832 } else if (state == RtpEndUserState.DECLINED_OR_BUSY) {
833 this.binding.rejectCall.setContentDescription(getString(R.string.exit));
834 this.binding.rejectCall.setOnClickListener(this::exit);
835 this.binding.rejectCall.setImageResource(R.drawable.ic_clear_white_48dp);
836 this.binding.rejectCall.setVisibility(View.VISIBLE);
837 this.binding.endCall.setVisibility(View.INVISIBLE);
838 this.binding.acceptCall.setContentDescription(getString(R.string.record_voice_mail));
839 this.binding.acceptCall.setOnClickListener(this::recordVoiceMail);
840 this.binding.acceptCall.setImageResource(R.drawable.ic_voicemail_white_24dp);
841 this.binding.acceptCall.setVisibility(View.VISIBLE);
842 } else if (asList(
843 RtpEndUserState.CONNECTIVITY_ERROR,
844 RtpEndUserState.CONNECTIVITY_LOST_ERROR,
845 RtpEndUserState.APPLICATION_ERROR,
846 RtpEndUserState.RETRACTED,
847 RtpEndUserState.SECURITY_ERROR)
848 .contains(state)) {
849 this.binding.rejectCall.setContentDescription(getString(R.string.exit));
850 this.binding.rejectCall.setOnClickListener(this::exit);
851 this.binding.rejectCall.setImageResource(R.drawable.ic_clear_white_48dp);
852 this.binding.rejectCall.setVisibility(View.VISIBLE);
853 this.binding.endCall.setVisibility(View.INVISIBLE);
854 this.binding.acceptCall.setContentDescription(getString(R.string.try_again));
855 this.binding.acceptCall.setOnClickListener(this::retry);
856 this.binding.acceptCall.setImageResource(R.drawable.ic_replay_white_48dp);
857 this.binding.acceptCall.setVisibility(View.VISIBLE);
858 } else {
859 this.binding.rejectCall.setVisibility(View.INVISIBLE);
860 this.binding.endCall.setContentDescription(getString(R.string.hang_up));
861 this.binding.endCall.setOnClickListener(this::endCall);
862 this.binding.endCall.setImageResource(R.drawable.ic_call_end_white_48dp);
863 this.binding.endCall.setVisibility(View.VISIBLE);
864 this.binding.acceptCall.setVisibility(View.INVISIBLE);
865 }
866 updateInCallButtonConfiguration(state, media);
867 }
868
869 private boolean isPictureInPicture() {
870 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
871 return isInPictureInPictureMode();
872 } else {
873 return false;
874 }
875 }
876
877 private void updateInCallButtonConfiguration() {
878 updateInCallButtonConfiguration(
879 requireRtpConnection().getEndUserState(), requireRtpConnection().getMedia());
880 }
881
882 @SuppressLint("RestrictedApi")
883 private void updateInCallButtonConfiguration(
884 final RtpEndUserState state, final Set<Media> media) {
885 if (STATES_CONSIDERED_CONNECTED.contains(state) && !isPictureInPicture()) {
886 Preconditions.checkArgument(media.size() > 0, "Media must not be empty");
887 if (media.contains(Media.VIDEO)) {
888 final JingleRtpConnection rtpConnection = requireRtpConnection();
889 updateInCallButtonConfigurationVideo(
890 rtpConnection.isVideoEnabled(), rtpConnection.isCameraSwitchable());
891 } else {
892 final AppRTCAudioManager audioManager = requireRtpConnection().getAudioManager();
893 updateInCallButtonConfigurationSpeaker(
894 audioManager.getSelectedAudioDevice(),
895 audioManager.getAudioDevices().size());
896 this.binding.inCallActionFarRight.setVisibility(View.GONE);
897 }
898 if (media.contains(Media.AUDIO)) {
899 updateInCallButtonConfigurationMicrophone(
900 requireRtpConnection().isMicrophoneEnabled());
901 } else {
902 this.binding.inCallActionLeft.setVisibility(View.GONE);
903 }
904 } else {
905 this.binding.inCallActionLeft.setVisibility(View.GONE);
906 this.binding.inCallActionRight.setVisibility(View.GONE);
907 this.binding.inCallActionFarRight.setVisibility(View.GONE);
908 }
909 }
910
911 @SuppressLint("RestrictedApi")
912 private void updateInCallButtonConfigurationSpeaker(
913 final AppRTCAudioManager.AudioDevice selectedAudioDevice, final int numberOfChoices) {
914 switch (selectedAudioDevice) {
915 case EARPIECE:
916 this.binding.inCallActionRight.setImageResource(
917 R.drawable.ic_volume_off_black_24dp);
918 if (numberOfChoices >= 2) {
919 this.binding.inCallActionRight.setOnClickListener(this::switchToSpeaker);
920 } else {
921 this.binding.inCallActionRight.setOnClickListener(null);
922 this.binding.inCallActionRight.setClickable(false);
923 }
924 break;
925 case WIRED_HEADSET:
926 this.binding.inCallActionRight.setImageResource(R.drawable.ic_headset_black_24dp);
927 this.binding.inCallActionRight.setOnClickListener(null);
928 this.binding.inCallActionRight.setClickable(false);
929 break;
930 case SPEAKER_PHONE:
931 this.binding.inCallActionRight.setImageResource(R.drawable.ic_volume_up_black_24dp);
932 if (numberOfChoices >= 2) {
933 this.binding.inCallActionRight.setOnClickListener(this::switchToEarpiece);
934 } else {
935 this.binding.inCallActionRight.setOnClickListener(null);
936 this.binding.inCallActionRight.setClickable(false);
937 }
938 break;
939 case BLUETOOTH:
940 this.binding.inCallActionRight.setImageResource(
941 R.drawable.ic_bluetooth_audio_black_24dp);
942 this.binding.inCallActionRight.setOnClickListener(null);
943 this.binding.inCallActionRight.setClickable(false);
944 break;
945 }
946 this.binding.inCallActionRight.setVisibility(View.VISIBLE);
947 }
948
949 @SuppressLint("RestrictedApi")
950 private void updateInCallButtonConfigurationVideo(
951 final boolean videoEnabled, final boolean isCameraSwitchable) {
952 this.binding.inCallActionRight.setVisibility(View.VISIBLE);
953 if (isCameraSwitchable) {
954 this.binding.inCallActionFarRight.setImageResource(
955 R.drawable.ic_flip_camera_android_black_24dp);
956 this.binding.inCallActionFarRight.setVisibility(View.VISIBLE);
957 this.binding.inCallActionFarRight.setOnClickListener(this::switchCamera);
958 } else {
959 this.binding.inCallActionFarRight.setVisibility(View.GONE);
960 }
961 if (videoEnabled) {
962 this.binding.inCallActionRight.setImageResource(R.drawable.ic_videocam_black_24dp);
963 this.binding.inCallActionRight.setOnClickListener(this::disableVideo);
964 } else {
965 this.binding.inCallActionRight.setImageResource(R.drawable.ic_videocam_off_black_24dp);
966 this.binding.inCallActionRight.setOnClickListener(this::enableVideo);
967 }
968 }
969
970 private void switchCamera(final View view) {
971 Futures.addCallback(
972 requireRtpConnection().switchCamera(),
973 new FutureCallback<Boolean>() {
974 @Override
975 public void onSuccess(@NullableDecl Boolean isFrontCamera) {
976 binding.localVideo.setMirror(isFrontCamera);
977 }
978
979 @Override
980 public void onFailure(@NonNull final Throwable throwable) {
981 Log.d(
982 Config.LOGTAG,
983 "could not switch camera",
984 Throwables.getRootCause(throwable));
985 Toast.makeText(
986 RtpSessionActivity.this,
987 R.string.could_not_switch_camera,
988 Toast.LENGTH_LONG)
989 .show();
990 }
991 },
992 MainThreadExecutor.getInstance());
993 }
994
995 private void enableVideo(View view) {
996 try {
997 requireRtpConnection().setVideoEnabled(true);
998 } catch (final IllegalStateException e) {
999 Toast.makeText(this, R.string.unable_to_enable_video, Toast.LENGTH_SHORT).show();
1000 return;
1001 }
1002 updateInCallButtonConfigurationVideo(true, requireRtpConnection().isCameraSwitchable());
1003 }
1004
1005 private void disableVideo(View view) {
1006 requireRtpConnection().setVideoEnabled(false);
1007 updateInCallButtonConfigurationVideo(false, requireRtpConnection().isCameraSwitchable());
1008 }
1009
1010 @SuppressLint("RestrictedApi")
1011 private void updateInCallButtonConfigurationMicrophone(final boolean microphoneEnabled) {
1012 if (microphoneEnabled) {
1013 this.binding.inCallActionLeft.setImageResource(R.drawable.ic_mic_black_24dp);
1014 this.binding.inCallActionLeft.setOnClickListener(this::disableMicrophone);
1015 } else {
1016 this.binding.inCallActionLeft.setImageResource(R.drawable.ic_mic_off_black_24dp);
1017 this.binding.inCallActionLeft.setOnClickListener(this::enableMicrophone);
1018 }
1019 this.binding.inCallActionLeft.setVisibility(View.VISIBLE);
1020 }
1021
1022 private void updateCallDuration() {
1023 final JingleRtpConnection connection =
1024 this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1025 if (connection == null || connection.getMedia().contains(Media.VIDEO)) {
1026 this.binding.duration.setVisibility(View.GONE);
1027 return;
1028 }
1029 if (connection.zeroDuration()) {
1030 this.binding.duration.setVisibility(View.GONE);
1031 } else {
1032 this.binding.duration.setText(
1033 TimeFrameUtils.formatElapsedTime(connection.getCallDuration(), false));
1034 this.binding.duration.setVisibility(View.VISIBLE);
1035 }
1036 }
1037
1038 private void updateVideoViews(final RtpEndUserState state) {
1039 if (END_CARD.contains(state) || state == RtpEndUserState.ENDING_CALL) {
1040 binding.localVideo.setVisibility(View.GONE);
1041 binding.localVideo.release();
1042 binding.remoteVideoWrapper.setVisibility(View.GONE);
1043 binding.remoteVideo.release();
1044 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1045 if (isPictureInPicture()) {
1046 binding.appBarLayout.setVisibility(View.GONE);
1047 binding.pipPlaceholder.setVisibility(View.VISIBLE);
1048 if (Arrays.asList(
1049 RtpEndUserState.APPLICATION_ERROR,
1050 RtpEndUserState.CONNECTIVITY_ERROR,
1051 RtpEndUserState.SECURITY_ERROR)
1052 .contains(state)) {
1053 binding.pipWarning.setVisibility(View.VISIBLE);
1054 binding.pipWaiting.setVisibility(View.GONE);
1055 } else {
1056 binding.pipWarning.setVisibility(View.GONE);
1057 binding.pipWaiting.setVisibility(View.GONE);
1058 }
1059 } else {
1060 binding.appBarLayout.setVisibility(View.VISIBLE);
1061 binding.pipPlaceholder.setVisibility(View.GONE);
1062 }
1063 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1064 return;
1065 }
1066 if (isPictureInPicture() && STATES_SHOWING_PIP_PLACEHOLDER.contains(state)) {
1067 binding.localVideo.setVisibility(View.GONE);
1068 binding.remoteVideoWrapper.setVisibility(View.GONE);
1069 binding.appBarLayout.setVisibility(View.GONE);
1070 binding.pipPlaceholder.setVisibility(View.VISIBLE);
1071 binding.pipWarning.setVisibility(View.GONE);
1072 binding.pipWaiting.setVisibility(View.VISIBLE);
1073 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1074 return;
1075 }
1076 final Optional<VideoTrack> localVideoTrack = getLocalVideoTrack();
1077 if (localVideoTrack.isPresent() && !isPictureInPicture()) {
1078 ensureSurfaceViewRendererIsSetup(binding.localVideo);
1079 // paint local view over remote view
1080 binding.localVideo.setZOrderMediaOverlay(true);
1081 binding.localVideo.setMirror(requireRtpConnection().isFrontCamera());
1082 addSink(localVideoTrack.get(), binding.localVideo);
1083 } else {
1084 binding.localVideo.setVisibility(View.GONE);
1085 }
1086 final Optional<VideoTrack> remoteVideoTrack = getRemoteVideoTrack();
1087 if (remoteVideoTrack.isPresent()) {
1088 ensureSurfaceViewRendererIsSetup(binding.remoteVideo);
1089 addSink(remoteVideoTrack.get(), binding.remoteVideo);
1090 binding.remoteVideo.setScalingType(
1091 RendererCommon.ScalingType.SCALE_ASPECT_FILL,
1092 RendererCommon.ScalingType.SCALE_ASPECT_FIT);
1093 if (state == RtpEndUserState.CONNECTED) {
1094 binding.appBarLayout.setVisibility(View.GONE);
1095 getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1096 binding.remoteVideoWrapper.setVisibility(View.VISIBLE);
1097 } else {
1098 binding.appBarLayout.setVisibility(View.VISIBLE);
1099 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1100 binding.remoteVideoWrapper.setVisibility(View.GONE);
1101 }
1102 if (isPictureInPicture() && !requireRtpConnection().isMicrophoneEnabled()) {
1103 binding.pipLocalMicOffIndicator.setVisibility(View.VISIBLE);
1104 } else {
1105 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1106 }
1107 } else {
1108 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1109 binding.remoteVideoWrapper.setVisibility(View.GONE);
1110 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1111 }
1112 }
1113
1114 private Optional<VideoTrack> getLocalVideoTrack() {
1115 final JingleRtpConnection connection =
1116 this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1117 if (connection == null) {
1118 return Optional.absent();
1119 }
1120 return connection.getLocalVideoTrack();
1121 }
1122
1123 private Optional<VideoTrack> getRemoteVideoTrack() {
1124 final JingleRtpConnection connection =
1125 this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1126 if (connection == null) {
1127 return Optional.absent();
1128 }
1129 return connection.getRemoteVideoTrack();
1130 }
1131
1132 private void disableMicrophone(View view) {
1133 final JingleRtpConnection rtpConnection = requireRtpConnection();
1134 if (rtpConnection.setMicrophoneEnabled(false)) {
1135 updateInCallButtonConfiguration();
1136 }
1137 }
1138
1139 private void enableMicrophone(View view) {
1140 final JingleRtpConnection rtpConnection = requireRtpConnection();
1141 if (rtpConnection.setMicrophoneEnabled(true)) {
1142 updateInCallButtonConfiguration();
1143 }
1144 }
1145
1146 private void switchToEarpiece(View view) {
1147 requireRtpConnection()
1148 .getAudioManager()
1149 .setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.EARPIECE);
1150 acquireProximityWakeLock();
1151 }
1152
1153 private void switchToSpeaker(View view) {
1154 requireRtpConnection()
1155 .getAudioManager()
1156 .setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.SPEAKER_PHONE);
1157 releaseProximityWakeLock();
1158 }
1159
1160 private void retry(View view) {
1161 final Intent intent = getIntent();
1162 final Account account = extractAccount(intent);
1163 final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
1164 final String lastAction = intent.getStringExtra(EXTRA_LAST_ACTION);
1165 final String action = intent.getAction();
1166 final Set<Media> media = actionToMedia(lastAction == null ? action : lastAction);
1167 this.rtpConnectionReference = null;
1168 Log.d(Config.LOGTAG, "attempting retry with " + with.toEscapedString());
1169 proposeJingleRtpSession(account, with, media);
1170 }
1171
1172 private void exit(final View view) {
1173 finish();
1174 }
1175
1176 private void recordVoiceMail(final View view) {
1177 final Intent intent = getIntent();
1178 final Account account = extractAccount(intent);
1179 final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
1180 final Conversation conversation =
1181 xmppConnectionService.findOrCreateConversation(account, with, false, true);
1182 final Intent launchIntent = new Intent(this, ConversationsActivity.class);
1183 launchIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
1184 launchIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
1185 launchIntent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
1186 launchIntent.putExtra(
1187 ConversationsActivity.EXTRA_POST_INIT_ACTION,
1188 ConversationsActivity.POST_ACTION_RECORD_VOICE);
1189 startActivity(launchIntent);
1190 finish();
1191 }
1192
1193 private Contact getWith() {
1194 final AbstractJingleConnection.Id id = requireRtpConnection().getId();
1195 final Account account = id.account;
1196 return account.getRoster().getContact(id.with);
1197 }
1198
1199 private JingleRtpConnection requireRtpConnection() {
1200 final JingleRtpConnection connection =
1201 this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1202 if (connection == null) {
1203 throw new IllegalStateException("No RTP connection found");
1204 }
1205 return connection;
1206 }
1207
1208 @Override
1209 public void onJingleRtpConnectionUpdate(
1210 Account account, Jid with, final String sessionId, RtpEndUserState state) {
1211 Log.d(Config.LOGTAG, "onJingleRtpConnectionUpdate(" + state + ")");
1212 if (END_CARD.contains(state)) {
1213 Log.d(Config.LOGTAG, "end card reached");
1214 releaseProximityWakeLock();
1215 runOnUiThread(
1216 () -> getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON));
1217 }
1218 if (with.isBareJid()) {
1219 updateRtpSessionProposalState(account, with, state);
1220 return;
1221 }
1222 if (emptyReference(this.rtpConnectionReference)) {
1223 if (END_CARD.contains(state)) {
1224 Log.d(Config.LOGTAG, "not reinitializing session");
1225 return;
1226 }
1227 // this happens when going from proposed session to actual session
1228 reInitializeActivityWithRunningRtpSession(account, with, sessionId);
1229 return;
1230 }
1231 final AbstractJingleConnection.Id id = requireRtpConnection().getId();
1232 final boolean verified = requireRtpConnection().isVerified();
1233 final Set<Media> media = getMedia();
1234 final Contact contact = getWith();
1235 if (account == id.account && id.with.equals(with) && id.sessionId.equals(sessionId)) {
1236 if (state == RtpEndUserState.ENDED) {
1237 finish();
1238 return;
1239 }
1240 runOnUiThread(
1241 () -> {
1242 updateStateDisplay(state, media);
1243 updateVerifiedShield(
1244 verified && STATES_SHOWING_SWITCH_TO_CHAT.contains(state));
1245 updateButtonConfiguration(state, media);
1246 updateVideoViews(state);
1247 updateProfilePicture(state, contact);
1248 invalidateOptionsMenu();
1249 });
1250 if (END_CARD.contains(state)) {
1251 final JingleRtpConnection rtpConnection = requireRtpConnection();
1252 resetIntent(account, with, state, rtpConnection.getMedia());
1253 releaseVideoTracks(rtpConnection);
1254 this.rtpConnectionReference = null;
1255 }
1256 } else {
1257 Log.d(Config.LOGTAG, "received update for other rtp session");
1258 }
1259 }
1260
1261 @Override
1262 public void onAudioDeviceChanged(
1263 AppRTCAudioManager.AudioDevice selectedAudioDevice,
1264 Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
1265 Log.d(
1266 Config.LOGTAG,
1267 "onAudioDeviceChanged in activity: selected:"
1268 + selectedAudioDevice
1269 + ", available:"
1270 + availableAudioDevices);
1271 try {
1272 if (getMedia().contains(Media.VIDEO)) {
1273 Log.d(Config.LOGTAG, "nothing to do; in video mode");
1274 return;
1275 }
1276 final RtpEndUserState endUserState = requireRtpConnection().getEndUserState();
1277 if (endUserState == RtpEndUserState.CONNECTED) {
1278 final AppRTCAudioManager audioManager = requireRtpConnection().getAudioManager();
1279 updateInCallButtonConfigurationSpeaker(
1280 audioManager.getSelectedAudioDevice(),
1281 audioManager.getAudioDevices().size());
1282 } else if (END_CARD.contains(endUserState)) {
1283 Log.d(
1284 Config.LOGTAG,
1285 "onAudioDeviceChanged() nothing to do because end card has been reached");
1286 } else {
1287 putProximityWakeLockInProperState(selectedAudioDevice);
1288 }
1289 } catch (IllegalStateException e) {
1290 Log.d(Config.LOGTAG, "RTP connection was not available when audio device changed");
1291 }
1292 }
1293
1294 private void updateRtpSessionProposalState(
1295 final Account account, final Jid with, final RtpEndUserState state) {
1296 final Intent currentIntent = getIntent();
1297 final String withExtra =
1298 currentIntent == null ? null : currentIntent.getStringExtra(EXTRA_WITH);
1299 if (withExtra == null) {
1300 return;
1301 }
1302 if (Jid.ofEscaped(withExtra).asBareJid().equals(with)) {
1303 runOnUiThread(
1304 () -> {
1305 updateVerifiedShield(false);
1306 updateStateDisplay(state);
1307 updateButtonConfiguration(state);
1308 updateProfilePicture(state);
1309 invalidateOptionsMenu();
1310 });
1311 resetIntent(account, with, state, actionToMedia(currentIntent.getAction()));
1312 }
1313 }
1314
1315 private void resetIntent(final Bundle extras) {
1316 final Intent intent = new Intent(Intent.ACTION_VIEW);
1317 intent.putExtras(extras);
1318 setIntent(intent);
1319 }
1320
1321 private void resetIntent(
1322 final Account account, Jid with, final RtpEndUserState state, final Set<Media> media) {
1323 final Intent intent = new Intent(Intent.ACTION_VIEW);
1324 intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
1325 if (account.getRoster()
1326 .getContact(with)
1327 .getPresences()
1328 .anySupport(Namespace.JINGLE_MESSAGE)) {
1329 intent.putExtra(EXTRA_WITH, with.asBareJid().toEscapedString());
1330 } else {
1331 intent.putExtra(EXTRA_WITH, with.toEscapedString());
1332 }
1333 intent.putExtra(EXTRA_LAST_REPORTED_STATE, state.toString());
1334 intent.putExtra(
1335 EXTRA_LAST_ACTION,
1336 media.contains(Media.VIDEO) ? ACTION_MAKE_VIDEO_CALL : ACTION_MAKE_VOICE_CALL);
1337 setIntent(intent);
1338 }
1339
1340 private static boolean emptyReference(final WeakReference<?> weakReference) {
1341 return weakReference == null || weakReference.get() == null;
1342 }
1343}