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