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 setWith(account.getRoster().getContact(with), null);
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 setWith(account.getRoster().getContact(with), null);
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 updateIncomingCallScreen(state);
438 invalidateOptionsMenu();
439 }
440 setWith(account.getRoster().getContact(with), state);
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 setWidth(final RtpEndUserState state) {
458 setWith(getWith(), state);
459 }
460
461 private void setWith(final Contact contact, final RtpEndUserState state) {
462 binding.with.setText(contact.getDisplayName());
463 if (Arrays.asList(RtpEndUserState.INCOMING_CALL, RtpEndUserState.ACCEPTING_CALL)
464 .contains(state)) {
465 binding.withJid.setText(contact.getJid().asBareJid().toEscapedString());
466 binding.withJid.setVisibility(View.VISIBLE);
467 } else {
468 binding.withJid.setVisibility(View.GONE);
469 }
470 }
471
472 private void proposeJingleRtpSession(
473 final Account account, final Jid with, final Set<Media> media) {
474 checkMicrophoneAvailabilityAsync();
475 if (with.isBareJid()) {
476 xmppConnectionService
477 .getJingleConnectionManager()
478 .proposeJingleRtpSession(account, with, media);
479 } else {
480 final String sessionId =
481 xmppConnectionService
482 .getJingleConnectionManager()
483 .initializeRtpSession(account, with, media);
484 initializeActivityWithRunningRtpSession(account, with, sessionId);
485 resetIntent(account, with, sessionId);
486 }
487 putScreenInCallMode(media);
488 }
489
490 @Override
491 public void onRequestPermissionsResult(
492 int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
493 super.onRequestPermissionsResult(requestCode, permissions, grantResults);
494 if (PermissionUtils.allGranted(grantResults)) {
495 if (requestCode == REQUEST_ACCEPT_CALL) {
496 checkRecorderAndAcceptCall();
497 }
498 } else {
499 @StringRes int res;
500 final String firstDenied = getFirstDenied(grantResults, permissions);
501 if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
502 res = R.string.no_microphone_permission;
503 } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
504 res = R.string.no_camera_permission;
505 } else {
506 throw new IllegalStateException("Invalid permission result request");
507 }
508 Toast.makeText(this, getString(res, getString(R.string.app_name)), Toast.LENGTH_SHORT)
509 .show();
510 }
511 }
512
513 @Override
514 public void onStart() {
515 super.onStart();
516 mHandler.postDelayed(mTickExecutor, CALL_DURATION_UPDATE_INTERVAL);
517 this.binding.remoteVideo.setOnAspectRatioChanged(this);
518 }
519
520 @Override
521 public void onStop() {
522 mHandler.removeCallbacks(mTickExecutor);
523 binding.remoteVideo.release();
524 binding.remoteVideo.setOnAspectRatioChanged(null);
525 binding.localVideo.release();
526 final WeakReference<JingleRtpConnection> weakReference = this.rtpConnectionReference;
527 final JingleRtpConnection jingleRtpConnection =
528 weakReference == null ? null : weakReference.get();
529 if (jingleRtpConnection != null) {
530 releaseVideoTracks(jingleRtpConnection);
531 }
532 releaseProximityWakeLock();
533 super.onStop();
534 }
535
536 private void releaseVideoTracks(final JingleRtpConnection jingleRtpConnection) {
537 final Optional<VideoTrack> remoteVideo = jingleRtpConnection.getRemoteVideoTrack();
538 if (remoteVideo.isPresent()) {
539 remoteVideo.get().removeSink(binding.remoteVideo);
540 }
541 final Optional<VideoTrack> localVideo = jingleRtpConnection.getLocalVideoTrack();
542 if (localVideo.isPresent()) {
543 localVideo.get().removeSink(binding.localVideo);
544 }
545 }
546
547 @Override
548 public void onBackPressed() {
549 if (isConnected()) {
550 if (switchToPictureInPicture()) {
551 return;
552 }
553 } else {
554 endCall();
555 }
556 super.onBackPressed();
557 }
558
559 @Override
560 public void onUserLeaveHint() {
561 super.onUserLeaveHint();
562 if (switchToPictureInPicture()) {
563 return;
564 }
565 // TODO apparently this method is not getting called on Android 10 when using the task
566 // switcher
567 if (emptyReference(rtpConnectionReference) && xmppConnectionService != null) {
568 retractSessionProposal();
569 }
570 }
571
572 private boolean isConnected() {
573 final JingleRtpConnection connection =
574 this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
575 return connection != null
576 && STATES_CONSIDERED_CONNECTED.contains(connection.getEndUserState());
577 }
578
579 private boolean switchToPictureInPicture() {
580 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && deviceSupportsPictureInPicture()) {
581 if (shouldBePictureInPicture()) {
582 startPictureInPicture();
583 return true;
584 }
585 }
586 return false;
587 }
588
589 @RequiresApi(api = Build.VERSION_CODES.O)
590 private void startPictureInPicture() {
591 try {
592 final Rational rational = this.binding.remoteVideo.getAspectRatio();
593 final Rational clippedRational = Rationals.clip(rational);
594 Log.d(
595 Config.LOGTAG,
596 "suggested rational " + rational + ". clipped to " + clippedRational);
597 enterPictureInPictureMode(
598 new PictureInPictureParams.Builder().setAspectRatio(clippedRational).build());
599 } catch (final IllegalStateException e) {
600 // this sometimes happens on Samsung phones (possibly when Knox is enabled)
601 Log.w(Config.LOGTAG, "unable to enter picture in picture mode", e);
602 }
603 }
604
605 @Override
606 public void onAspectRatioChanged(final Rational rational) {
607 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && isPictureInPicture()) {
608 final Rational clippedRational = Rationals.clip(rational);
609 Log.d(
610 Config.LOGTAG,
611 "suggested rational after aspect ratio change "
612 + rational
613 + ". clipped to "
614 + clippedRational);
615 setPictureInPictureParams(
616 new PictureInPictureParams.Builder().setAspectRatio(clippedRational).build());
617 }
618 }
619
620 private boolean deviceSupportsPictureInPicture() {
621 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
622 return getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE);
623 } else {
624 return false;
625 }
626 }
627
628 private boolean shouldBePictureInPicture() {
629 try {
630 final JingleRtpConnection rtpConnection = requireRtpConnection();
631 return rtpConnection.getMedia().contains(Media.VIDEO)
632 && Arrays.asList(
633 RtpEndUserState.ACCEPTING_CALL,
634 RtpEndUserState.CONNECTING,
635 RtpEndUserState.CONNECTED)
636 .contains(rtpConnection.getEndUserState());
637 } catch (final IllegalStateException e) {
638 return false;
639 }
640 }
641
642 private boolean initializeActivityWithRunningRtpSession(
643 final Account account, Jid with, String sessionId) {
644 final WeakReference<JingleRtpConnection> reference =
645 xmppConnectionService
646 .getJingleConnectionManager()
647 .findJingleRtpConnection(account, with, sessionId);
648 if (reference == null || reference.get() == null) {
649 final JingleConnectionManager.TerminatedRtpSession terminatedRtpSession =
650 xmppConnectionService
651 .getJingleConnectionManager()
652 .getTerminalSessionState(with, sessionId);
653 if (terminatedRtpSession == null) {
654 throw new IllegalStateException(
655 "failed to initialize activity with running rtp session. session not found");
656 }
657 initializeWithTerminatedSessionState(account, with, terminatedRtpSession);
658 return true;
659 }
660 this.rtpConnectionReference = reference;
661 final RtpEndUserState currentState = requireRtpConnection().getEndUserState();
662 final boolean verified = requireRtpConnection().isVerified();
663 if (currentState == RtpEndUserState.ENDED) {
664 finish();
665 return true;
666 }
667 final Set<Media> media = getMedia();
668 if (currentState == RtpEndUserState.INCOMING_CALL) {
669 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
670 }
671 if (JingleRtpConnection.STATES_SHOWING_ONGOING_CALL.contains(
672 requireRtpConnection().getState())) {
673 putScreenInCallMode();
674 }
675 setWidth(currentState);
676 updateVideoViews(currentState);
677 updateStateDisplay(currentState, media);
678 updateVerifiedShield(verified && STATES_SHOWING_SWITCH_TO_CHAT.contains(currentState));
679 updateButtonConfiguration(currentState, media);
680 updateIncomingCallScreen(currentState);
681 invalidateOptionsMenu();
682 return false;
683 }
684
685 private void initializeWithTerminatedSessionState(
686 final Account account,
687 final Jid with,
688 final JingleConnectionManager.TerminatedRtpSession terminatedRtpSession) {
689 Log.d(Config.LOGTAG, "initializeWithTerminatedSessionState()");
690 if (terminatedRtpSession.state == RtpEndUserState.ENDED) {
691 finish();
692 return;
693 }
694 final RtpEndUserState state = terminatedRtpSession.state;
695 resetIntent(account, with, terminatedRtpSession.state, terminatedRtpSession.media);
696 updateButtonConfiguration(state);
697 updateStateDisplay(state);
698 updateIncomingCallScreen(state);
699 updateCallDuration();
700 updateVerifiedShield(false);
701 invalidateOptionsMenu();
702 setWith(account.getRoster().getContact(with), state);
703 }
704
705 private void reInitializeActivityWithRunningRtpSession(
706 final Account account, Jid with, String sessionId) {
707 runOnUiThread(() -> initializeActivityWithRunningRtpSession(account, with, sessionId));
708 resetIntent(account, with, sessionId);
709 }
710
711 private void resetIntent(final Account account, final Jid with, final String sessionId) {
712 final Intent intent = new Intent(Intent.ACTION_VIEW);
713 intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
714 intent.putExtra(EXTRA_WITH, with.toEscapedString());
715 intent.putExtra(EXTRA_SESSION_ID, sessionId);
716 setIntent(intent);
717 }
718
719 private void ensureSurfaceViewRendererIsSetup(final SurfaceViewRenderer surfaceViewRenderer) {
720 surfaceViewRenderer.setVisibility(View.VISIBLE);
721 try {
722 surfaceViewRenderer.init(requireRtpConnection().getEglBaseContext(), null);
723 } catch (final IllegalStateException e) {
724 // Log.d(Config.LOGTAG, "SurfaceViewRenderer was already initialized");
725 }
726 surfaceViewRenderer.setEnableHardwareScaler(true);
727 }
728
729 private void updateStateDisplay(final RtpEndUserState state) {
730 updateStateDisplay(state, Collections.emptySet());
731 }
732
733 private void updateStateDisplay(final RtpEndUserState state, final Set<Media> media) {
734 switch (state) {
735 case INCOMING_CALL:
736 Preconditions.checkArgument(media.size() > 0, "Media must not be empty");
737 if (media.contains(Media.VIDEO)) {
738 setTitle(R.string.rtp_state_incoming_video_call);
739 } else {
740 setTitle(R.string.rtp_state_incoming_call);
741 }
742 break;
743 case CONNECTING:
744 setTitle(R.string.rtp_state_connecting);
745 break;
746 case CONNECTED:
747 setTitle(R.string.rtp_state_connected);
748 break;
749 case RECONNECTING:
750 setTitle(R.string.rtp_state_reconnecting);
751 break;
752 case ACCEPTING_CALL:
753 setTitle(R.string.rtp_state_accepting_call);
754 break;
755 case ENDING_CALL:
756 setTitle(R.string.rtp_state_ending_call);
757 break;
758 case FINDING_DEVICE:
759 setTitle(R.string.rtp_state_finding_device);
760 break;
761 case RINGING:
762 setTitle(R.string.rtp_state_ringing);
763 break;
764 case DECLINED_OR_BUSY:
765 setTitle(R.string.rtp_state_declined_or_busy);
766 break;
767 case CONNECTIVITY_ERROR:
768 setTitle(R.string.rtp_state_connectivity_error);
769 break;
770 case CONNECTIVITY_LOST_ERROR:
771 setTitle(R.string.rtp_state_connectivity_lost_error);
772 break;
773 case RETRACTED:
774 setTitle(R.string.rtp_state_retracted);
775 break;
776 case APPLICATION_ERROR:
777 setTitle(R.string.rtp_state_application_failure);
778 break;
779 case SECURITY_ERROR:
780 setTitle(R.string.rtp_state_security_error);
781 break;
782 case ENDED:
783 throw new IllegalStateException(
784 "Activity should have called finishAndReleaseWakeLock();");
785 default:
786 throw new IllegalStateException(
787 String.format("State %s has not been handled in UI", state));
788 }
789 }
790
791 private void updateVerifiedShield(final boolean verified) {
792 if (isPictureInPicture()) {
793 this.binding.verified.setVisibility(View.GONE);
794 return;
795 }
796 this.binding.verified.setVisibility(verified ? View.VISIBLE : View.GONE);
797 }
798
799 private void updateIncomingCallScreen(final RtpEndUserState state) {
800 updateIncomingCallScreen(state, null);
801 }
802
803 private void updateIncomingCallScreen(final RtpEndUserState state, final Contact contact) {
804 if (state == RtpEndUserState.INCOMING_CALL || state == RtpEndUserState.ACCEPTING_CALL) {
805 final boolean show = getResources().getBoolean(R.bool.show_avatar_incoming_call);
806 if (show) {
807 binding.contactPhoto.setVisibility(View.VISIBLE);
808 if (contact == null) {
809 AvatarWorkerTask.loadAvatar(
810 getWith(), binding.contactPhoto, R.dimen.publish_avatar_size);
811 } else {
812 AvatarWorkerTask.loadAvatar(
813 contact, binding.contactPhoto, R.dimen.publish_avatar_size);
814 }
815 } else {
816 binding.contactPhoto.setVisibility(View.GONE);
817 }
818 final Account account = contact == null ? getWith().getAccount() : contact.getAccount();
819 binding.usingAccount.setVisibility(View.VISIBLE);
820 binding.usingAccount.setText(
821 getString(
822 R.string.using_account,
823 account.getJid().asBareJid().toEscapedString()));
824 } else {
825 binding.usingAccount.setVisibility(View.GONE);
826 binding.contactPhoto.setVisibility(View.GONE);
827 }
828 }
829
830 private Set<Media> getMedia() {
831 return requireRtpConnection().getMedia();
832 }
833
834 private void updateButtonConfiguration(final RtpEndUserState state) {
835 updateButtonConfiguration(state, Collections.emptySet());
836 }
837
838 @SuppressLint("RestrictedApi")
839 private void updateButtonConfiguration(final RtpEndUserState state, final Set<Media> media) {
840 if (state == RtpEndUserState.ENDING_CALL || isPictureInPicture()) {
841 this.binding.rejectCall.setVisibility(View.INVISIBLE);
842 this.binding.endCall.setVisibility(View.INVISIBLE);
843 this.binding.acceptCall.setVisibility(View.INVISIBLE);
844 } else if (state == RtpEndUserState.INCOMING_CALL) {
845 this.binding.rejectCall.setContentDescription(getString(R.string.dismiss_call));
846 this.binding.rejectCall.setOnClickListener(this::rejectCall);
847 this.binding.rejectCall.setImageResource(R.drawable.ic_call_end_white_48dp);
848 this.binding.rejectCall.setVisibility(View.VISIBLE);
849 this.binding.endCall.setVisibility(View.INVISIBLE);
850 this.binding.acceptCall.setContentDescription(getString(R.string.answer_call));
851 this.binding.acceptCall.setOnClickListener(this::acceptCall);
852 this.binding.acceptCall.setImageResource(R.drawable.ic_call_white_48dp);
853 this.binding.acceptCall.setVisibility(View.VISIBLE);
854 } else if (state == RtpEndUserState.DECLINED_OR_BUSY) {
855 this.binding.rejectCall.setContentDescription(getString(R.string.exit));
856 this.binding.rejectCall.setOnClickListener(this::exit);
857 this.binding.rejectCall.setImageResource(R.drawable.ic_clear_white_48dp);
858 this.binding.rejectCall.setVisibility(View.VISIBLE);
859 this.binding.endCall.setVisibility(View.INVISIBLE);
860 this.binding.acceptCall.setContentDescription(getString(R.string.record_voice_mail));
861 this.binding.acceptCall.setOnClickListener(this::recordVoiceMail);
862 this.binding.acceptCall.setImageResource(R.drawable.ic_voicemail_white_24dp);
863 this.binding.acceptCall.setVisibility(View.VISIBLE);
864 } else if (asList(
865 RtpEndUserState.CONNECTIVITY_ERROR,
866 RtpEndUserState.CONNECTIVITY_LOST_ERROR,
867 RtpEndUserState.APPLICATION_ERROR,
868 RtpEndUserState.RETRACTED,
869 RtpEndUserState.SECURITY_ERROR)
870 .contains(state)) {
871 this.binding.rejectCall.setContentDescription(getString(R.string.exit));
872 this.binding.rejectCall.setOnClickListener(this::exit);
873 this.binding.rejectCall.setImageResource(R.drawable.ic_clear_white_48dp);
874 this.binding.rejectCall.setVisibility(View.VISIBLE);
875 this.binding.endCall.setVisibility(View.INVISIBLE);
876 this.binding.acceptCall.setContentDescription(getString(R.string.try_again));
877 this.binding.acceptCall.setOnClickListener(this::retry);
878 this.binding.acceptCall.setImageResource(R.drawable.ic_replay_white_48dp);
879 this.binding.acceptCall.setVisibility(View.VISIBLE);
880 } else {
881 this.binding.rejectCall.setVisibility(View.INVISIBLE);
882 this.binding.endCall.setContentDescription(getString(R.string.hang_up));
883 this.binding.endCall.setOnClickListener(this::endCall);
884 this.binding.endCall.setImageResource(R.drawable.ic_call_end_white_48dp);
885 this.binding.endCall.setVisibility(View.VISIBLE);
886 this.binding.acceptCall.setVisibility(View.INVISIBLE);
887 }
888 updateInCallButtonConfiguration(state, media);
889 }
890
891 private boolean isPictureInPicture() {
892 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
893 return isInPictureInPictureMode();
894 } else {
895 return false;
896 }
897 }
898
899 private void updateInCallButtonConfiguration() {
900 updateInCallButtonConfiguration(
901 requireRtpConnection().getEndUserState(), requireRtpConnection().getMedia());
902 }
903
904 @SuppressLint("RestrictedApi")
905 private void updateInCallButtonConfiguration(
906 final RtpEndUserState state, final Set<Media> media) {
907 if (STATES_CONSIDERED_CONNECTED.contains(state) && !isPictureInPicture()) {
908 Preconditions.checkArgument(media.size() > 0, "Media must not be empty");
909 if (media.contains(Media.VIDEO)) {
910 final JingleRtpConnection rtpConnection = requireRtpConnection();
911 updateInCallButtonConfigurationVideo(
912 rtpConnection.isVideoEnabled(), rtpConnection.isCameraSwitchable());
913 } else {
914 final AppRTCAudioManager audioManager = requireRtpConnection().getAudioManager();
915 updateInCallButtonConfigurationSpeaker(
916 audioManager.getSelectedAudioDevice(),
917 audioManager.getAudioDevices().size());
918 this.binding.inCallActionFarRight.setVisibility(View.GONE);
919 }
920 if (media.contains(Media.AUDIO)) {
921 updateInCallButtonConfigurationMicrophone(
922 requireRtpConnection().isMicrophoneEnabled());
923 } else {
924 this.binding.inCallActionLeft.setVisibility(View.GONE);
925 }
926 } else {
927 this.binding.inCallActionLeft.setVisibility(View.GONE);
928 this.binding.inCallActionRight.setVisibility(View.GONE);
929 this.binding.inCallActionFarRight.setVisibility(View.GONE);
930 }
931 }
932
933 @SuppressLint("RestrictedApi")
934 private void updateInCallButtonConfigurationSpeaker(
935 final AppRTCAudioManager.AudioDevice selectedAudioDevice, final int numberOfChoices) {
936 switch (selectedAudioDevice) {
937 case EARPIECE:
938 this.binding.inCallActionRight.setImageResource(
939 R.drawable.ic_volume_off_black_24dp);
940 if (numberOfChoices >= 2) {
941 this.binding.inCallActionRight.setOnClickListener(this::switchToSpeaker);
942 } else {
943 this.binding.inCallActionRight.setOnClickListener(null);
944 this.binding.inCallActionRight.setClickable(false);
945 }
946 break;
947 case WIRED_HEADSET:
948 this.binding.inCallActionRight.setImageResource(R.drawable.ic_headset_black_24dp);
949 this.binding.inCallActionRight.setOnClickListener(null);
950 this.binding.inCallActionRight.setClickable(false);
951 break;
952 case SPEAKER_PHONE:
953 this.binding.inCallActionRight.setImageResource(R.drawable.ic_volume_up_black_24dp);
954 if (numberOfChoices >= 2) {
955 this.binding.inCallActionRight.setOnClickListener(this::switchToEarpiece);
956 } else {
957 this.binding.inCallActionRight.setOnClickListener(null);
958 this.binding.inCallActionRight.setClickable(false);
959 }
960 break;
961 case BLUETOOTH:
962 this.binding.inCallActionRight.setImageResource(
963 R.drawable.ic_bluetooth_audio_black_24dp);
964 this.binding.inCallActionRight.setOnClickListener(null);
965 this.binding.inCallActionRight.setClickable(false);
966 break;
967 }
968 this.binding.inCallActionRight.setVisibility(View.VISIBLE);
969 }
970
971 @SuppressLint("RestrictedApi")
972 private void updateInCallButtonConfigurationVideo(
973 final boolean videoEnabled, final boolean isCameraSwitchable) {
974 this.binding.inCallActionRight.setVisibility(View.VISIBLE);
975 if (isCameraSwitchable) {
976 this.binding.inCallActionFarRight.setImageResource(
977 R.drawable.ic_flip_camera_android_black_24dp);
978 this.binding.inCallActionFarRight.setVisibility(View.VISIBLE);
979 this.binding.inCallActionFarRight.setOnClickListener(this::switchCamera);
980 } else {
981 this.binding.inCallActionFarRight.setVisibility(View.GONE);
982 }
983 if (videoEnabled) {
984 this.binding.inCallActionRight.setImageResource(R.drawable.ic_videocam_black_24dp);
985 this.binding.inCallActionRight.setOnClickListener(this::disableVideo);
986 } else {
987 this.binding.inCallActionRight.setImageResource(R.drawable.ic_videocam_off_black_24dp);
988 this.binding.inCallActionRight.setOnClickListener(this::enableVideo);
989 }
990 }
991
992 private void switchCamera(final View view) {
993 Futures.addCallback(
994 requireRtpConnection().switchCamera(),
995 new FutureCallback<Boolean>() {
996 @Override
997 public void onSuccess(@NullableDecl Boolean isFrontCamera) {
998 binding.localVideo.setMirror(isFrontCamera);
999 }
1000
1001 @Override
1002 public void onFailure(@NonNull final Throwable throwable) {
1003 Log.d(
1004 Config.LOGTAG,
1005 "could not switch camera",
1006 Throwables.getRootCause(throwable));
1007 Toast.makeText(
1008 RtpSessionActivity.this,
1009 R.string.could_not_switch_camera,
1010 Toast.LENGTH_LONG)
1011 .show();
1012 }
1013 },
1014 MainThreadExecutor.getInstance());
1015 }
1016
1017 private void enableVideo(View view) {
1018 try {
1019 requireRtpConnection().setVideoEnabled(true);
1020 } catch (final IllegalStateException e) {
1021 Toast.makeText(this, R.string.unable_to_enable_video, Toast.LENGTH_SHORT).show();
1022 return;
1023 }
1024 updateInCallButtonConfigurationVideo(true, requireRtpConnection().isCameraSwitchable());
1025 }
1026
1027 private void disableVideo(View view) {
1028 requireRtpConnection().setVideoEnabled(false);
1029 updateInCallButtonConfigurationVideo(false, requireRtpConnection().isCameraSwitchable());
1030 }
1031
1032 @SuppressLint("RestrictedApi")
1033 private void updateInCallButtonConfigurationMicrophone(final boolean microphoneEnabled) {
1034 if (microphoneEnabled) {
1035 this.binding.inCallActionLeft.setImageResource(R.drawable.ic_mic_black_24dp);
1036 this.binding.inCallActionLeft.setOnClickListener(this::disableMicrophone);
1037 } else {
1038 this.binding.inCallActionLeft.setImageResource(R.drawable.ic_mic_off_black_24dp);
1039 this.binding.inCallActionLeft.setOnClickListener(this::enableMicrophone);
1040 }
1041 this.binding.inCallActionLeft.setVisibility(View.VISIBLE);
1042 }
1043
1044 private void updateCallDuration() {
1045 final JingleRtpConnection connection =
1046 this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1047 if (connection == null || connection.getMedia().contains(Media.VIDEO)) {
1048 this.binding.duration.setVisibility(View.GONE);
1049 return;
1050 }
1051 if (connection.zeroDuration()) {
1052 this.binding.duration.setVisibility(View.GONE);
1053 } else {
1054 this.binding.duration.setText(
1055 TimeFrameUtils.formatElapsedTime(connection.getCallDuration(), false));
1056 this.binding.duration.setVisibility(View.VISIBLE);
1057 }
1058 }
1059
1060 private void updateVideoViews(final RtpEndUserState state) {
1061 if (END_CARD.contains(state) || state == RtpEndUserState.ENDING_CALL) {
1062 binding.localVideo.setVisibility(View.GONE);
1063 binding.localVideo.release();
1064 binding.remoteVideoWrapper.setVisibility(View.GONE);
1065 binding.remoteVideo.release();
1066 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1067 if (isPictureInPicture()) {
1068 binding.appBarLayout.setVisibility(View.GONE);
1069 binding.pipPlaceholder.setVisibility(View.VISIBLE);
1070 if (Arrays.asList(
1071 RtpEndUserState.APPLICATION_ERROR,
1072 RtpEndUserState.CONNECTIVITY_ERROR,
1073 RtpEndUserState.SECURITY_ERROR)
1074 .contains(state)) {
1075 binding.pipWarning.setVisibility(View.VISIBLE);
1076 binding.pipWaiting.setVisibility(View.GONE);
1077 } else {
1078 binding.pipWarning.setVisibility(View.GONE);
1079 binding.pipWaiting.setVisibility(View.GONE);
1080 }
1081 } else {
1082 binding.appBarLayout.setVisibility(View.VISIBLE);
1083 binding.pipPlaceholder.setVisibility(View.GONE);
1084 }
1085 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1086 return;
1087 }
1088 if (isPictureInPicture() && STATES_SHOWING_PIP_PLACEHOLDER.contains(state)) {
1089 binding.localVideo.setVisibility(View.GONE);
1090 binding.remoteVideoWrapper.setVisibility(View.GONE);
1091 binding.appBarLayout.setVisibility(View.GONE);
1092 binding.pipPlaceholder.setVisibility(View.VISIBLE);
1093 binding.pipWarning.setVisibility(View.GONE);
1094 binding.pipWaiting.setVisibility(View.VISIBLE);
1095 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1096 return;
1097 }
1098 final Optional<VideoTrack> localVideoTrack = getLocalVideoTrack();
1099 if (localVideoTrack.isPresent() && !isPictureInPicture()) {
1100 ensureSurfaceViewRendererIsSetup(binding.localVideo);
1101 // paint local view over remote view
1102 binding.localVideo.setZOrderMediaOverlay(true);
1103 binding.localVideo.setMirror(requireRtpConnection().isFrontCamera());
1104 addSink(localVideoTrack.get(), binding.localVideo);
1105 } else {
1106 binding.localVideo.setVisibility(View.GONE);
1107 }
1108 final Optional<VideoTrack> remoteVideoTrack = getRemoteVideoTrack();
1109 if (remoteVideoTrack.isPresent()) {
1110 ensureSurfaceViewRendererIsSetup(binding.remoteVideo);
1111 addSink(remoteVideoTrack.get(), binding.remoteVideo);
1112 binding.remoteVideo.setScalingType(
1113 RendererCommon.ScalingType.SCALE_ASPECT_FILL,
1114 RendererCommon.ScalingType.SCALE_ASPECT_FIT);
1115 if (state == RtpEndUserState.CONNECTED) {
1116 binding.appBarLayout.setVisibility(View.GONE);
1117 getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1118 binding.remoteVideoWrapper.setVisibility(View.VISIBLE);
1119 } else {
1120 binding.appBarLayout.setVisibility(View.VISIBLE);
1121 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1122 binding.remoteVideoWrapper.setVisibility(View.GONE);
1123 }
1124 if (isPictureInPicture() && !requireRtpConnection().isMicrophoneEnabled()) {
1125 binding.pipLocalMicOffIndicator.setVisibility(View.VISIBLE);
1126 } else {
1127 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1128 }
1129 } else {
1130 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1131 binding.remoteVideoWrapper.setVisibility(View.GONE);
1132 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1133 }
1134 }
1135
1136 private Optional<VideoTrack> getLocalVideoTrack() {
1137 final JingleRtpConnection connection =
1138 this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1139 if (connection == null) {
1140 return Optional.absent();
1141 }
1142 return connection.getLocalVideoTrack();
1143 }
1144
1145 private Optional<VideoTrack> getRemoteVideoTrack() {
1146 final JingleRtpConnection connection =
1147 this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1148 if (connection == null) {
1149 return Optional.absent();
1150 }
1151 return connection.getRemoteVideoTrack();
1152 }
1153
1154 private void disableMicrophone(View view) {
1155 final JingleRtpConnection rtpConnection = requireRtpConnection();
1156 if (rtpConnection.setMicrophoneEnabled(false)) {
1157 updateInCallButtonConfiguration();
1158 }
1159 }
1160
1161 private void enableMicrophone(View view) {
1162 final JingleRtpConnection rtpConnection = requireRtpConnection();
1163 if (rtpConnection.setMicrophoneEnabled(true)) {
1164 updateInCallButtonConfiguration();
1165 }
1166 }
1167
1168 private void switchToEarpiece(View view) {
1169 requireRtpConnection()
1170 .getAudioManager()
1171 .setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.EARPIECE);
1172 acquireProximityWakeLock();
1173 }
1174
1175 private void switchToSpeaker(View view) {
1176 requireRtpConnection()
1177 .getAudioManager()
1178 .setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.SPEAKER_PHONE);
1179 releaseProximityWakeLock();
1180 }
1181
1182 private void retry(View view) {
1183 final Intent intent = getIntent();
1184 final Account account = extractAccount(intent);
1185 final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
1186 final String lastAction = intent.getStringExtra(EXTRA_LAST_ACTION);
1187 final String action = intent.getAction();
1188 final Set<Media> media = actionToMedia(lastAction == null ? action : lastAction);
1189 this.rtpConnectionReference = null;
1190 Log.d(Config.LOGTAG, "attempting retry with " + with.toEscapedString());
1191 proposeJingleRtpSession(account, with, media);
1192 }
1193
1194 private void exit(final View view) {
1195 finish();
1196 }
1197
1198 private void recordVoiceMail(final View view) {
1199 final Intent intent = getIntent();
1200 final Account account = extractAccount(intent);
1201 final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
1202 final Conversation conversation =
1203 xmppConnectionService.findOrCreateConversation(account, with, false, true);
1204 final Intent launchIntent = new Intent(this, ConversationsActivity.class);
1205 launchIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
1206 launchIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
1207 launchIntent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
1208 launchIntent.putExtra(
1209 ConversationsActivity.EXTRA_POST_INIT_ACTION,
1210 ConversationsActivity.POST_ACTION_RECORD_VOICE);
1211 startActivity(launchIntent);
1212 finish();
1213 }
1214
1215 private Contact getWith() {
1216 final AbstractJingleConnection.Id id = requireRtpConnection().getId();
1217 final Account account = id.account;
1218 return account.getRoster().getContact(id.with);
1219 }
1220
1221 private JingleRtpConnection requireRtpConnection() {
1222 final JingleRtpConnection connection =
1223 this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1224 if (connection == null) {
1225 throw new IllegalStateException("No RTP connection found");
1226 }
1227 return connection;
1228 }
1229
1230 @Override
1231 public void onJingleRtpConnectionUpdate(
1232 Account account, Jid with, final String sessionId, RtpEndUserState state) {
1233 Log.d(Config.LOGTAG, "onJingleRtpConnectionUpdate(" + state + ")");
1234 if (END_CARD.contains(state)) {
1235 Log.d(Config.LOGTAG, "end card reached");
1236 releaseProximityWakeLock();
1237 runOnUiThread(
1238 () -> getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON));
1239 }
1240 if (with.isBareJid()) {
1241 updateRtpSessionProposalState(account, with, state);
1242 return;
1243 }
1244 if (emptyReference(this.rtpConnectionReference)) {
1245 if (END_CARD.contains(state)) {
1246 Log.d(Config.LOGTAG, "not reinitializing session");
1247 return;
1248 }
1249 // this happens when going from proposed session to actual session
1250 reInitializeActivityWithRunningRtpSession(account, with, sessionId);
1251 return;
1252 }
1253 final AbstractJingleConnection.Id id = requireRtpConnection().getId();
1254 final boolean verified = requireRtpConnection().isVerified();
1255 final Set<Media> media = getMedia();
1256 final Contact contact = getWith();
1257 if (account == id.account && id.with.equals(with) && id.sessionId.equals(sessionId)) {
1258 if (state == RtpEndUserState.ENDED) {
1259 finish();
1260 return;
1261 }
1262 runOnUiThread(
1263 () -> {
1264 updateStateDisplay(state, media);
1265 updateVerifiedShield(
1266 verified && STATES_SHOWING_SWITCH_TO_CHAT.contains(state));
1267 updateButtonConfiguration(state, media);
1268 updateVideoViews(state);
1269 updateIncomingCallScreen(state, contact);
1270 invalidateOptionsMenu();
1271 });
1272 if (END_CARD.contains(state)) {
1273 final JingleRtpConnection rtpConnection = requireRtpConnection();
1274 resetIntent(account, with, state, rtpConnection.getMedia());
1275 releaseVideoTracks(rtpConnection);
1276 this.rtpConnectionReference = null;
1277 }
1278 } else {
1279 Log.d(Config.LOGTAG, "received update for other rtp session");
1280 }
1281 }
1282
1283 @Override
1284 public void onAudioDeviceChanged(
1285 AppRTCAudioManager.AudioDevice selectedAudioDevice,
1286 Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
1287 Log.d(
1288 Config.LOGTAG,
1289 "onAudioDeviceChanged in activity: selected:"
1290 + selectedAudioDevice
1291 + ", available:"
1292 + availableAudioDevices);
1293 try {
1294 if (getMedia().contains(Media.VIDEO)) {
1295 Log.d(Config.LOGTAG, "nothing to do; in video mode");
1296 return;
1297 }
1298 final RtpEndUserState endUserState = requireRtpConnection().getEndUserState();
1299 if (endUserState == RtpEndUserState.CONNECTED) {
1300 final AppRTCAudioManager audioManager = requireRtpConnection().getAudioManager();
1301 updateInCallButtonConfigurationSpeaker(
1302 audioManager.getSelectedAudioDevice(),
1303 audioManager.getAudioDevices().size());
1304 } else if (END_CARD.contains(endUserState)) {
1305 Log.d(
1306 Config.LOGTAG,
1307 "onAudioDeviceChanged() nothing to do because end card has been reached");
1308 } else {
1309 putProximityWakeLockInProperState(selectedAudioDevice);
1310 }
1311 } catch (IllegalStateException e) {
1312 Log.d(Config.LOGTAG, "RTP connection was not available when audio device changed");
1313 }
1314 }
1315
1316 private void updateRtpSessionProposalState(
1317 final Account account, final Jid with, final RtpEndUserState state) {
1318 final Intent currentIntent = getIntent();
1319 final String withExtra =
1320 currentIntent == null ? null : currentIntent.getStringExtra(EXTRA_WITH);
1321 if (withExtra == null) {
1322 return;
1323 }
1324 if (Jid.ofEscaped(withExtra).asBareJid().equals(with)) {
1325 runOnUiThread(
1326 () -> {
1327 updateVerifiedShield(false);
1328 updateStateDisplay(state);
1329 updateButtonConfiguration(state);
1330 updateIncomingCallScreen(state);
1331 invalidateOptionsMenu();
1332 });
1333 resetIntent(account, with, state, actionToMedia(currentIntent.getAction()));
1334 }
1335 }
1336
1337 private void resetIntent(final Bundle extras) {
1338 final Intent intent = new Intent(Intent.ACTION_VIEW);
1339 intent.putExtras(extras);
1340 setIntent(intent);
1341 }
1342
1343 private void resetIntent(
1344 final Account account, Jid with, final RtpEndUserState state, final Set<Media> media) {
1345 final Intent intent = new Intent(Intent.ACTION_VIEW);
1346 intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
1347 if (account.getRoster()
1348 .getContact(with)
1349 .getPresences()
1350 .anySupport(Namespace.JINGLE_MESSAGE)) {
1351 intent.putExtra(EXTRA_WITH, with.asBareJid().toEscapedString());
1352 } else {
1353 intent.putExtra(EXTRA_WITH, with.toEscapedString());
1354 }
1355 intent.putExtra(EXTRA_LAST_REPORTED_STATE, state.toString());
1356 intent.putExtra(
1357 EXTRA_LAST_ACTION,
1358 media.contains(Media.VIDEO) ? ACTION_MAKE_VIDEO_CALL : ACTION_MAKE_VOICE_CALL);
1359 setIntent(intent);
1360 }
1361
1362 private static boolean emptyReference(final WeakReference<?> weakReference) {
1363 return weakReference == null || weakReference.get() == null;
1364 }
1365}