RtpSessionActivity.java

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