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.PictureInPictureParams;
   9import android.content.ActivityNotFoundException;
  10import android.content.Context;
  11import android.content.Intent;
  12import android.content.pm.PackageManager;
  13import android.os.Build;
  14import android.os.Bundle;
  15import android.os.Handler;
  16import android.os.PowerManager;
  17import android.os.SystemClock;
  18import android.util.Log;
  19import android.util.Rational;
  20import android.view.KeyEvent;
  21import android.view.Menu;
  22import android.view.MenuItem;
  23import android.view.View;
  24import android.view.WindowManager;
  25import android.widget.Toast;
  26
  27import androidx.annotation.NonNull;
  28import androidx.annotation.RequiresApi;
  29import androidx.annotation.StringRes;
  30import androidx.databinding.DataBindingUtil;
  31
  32import com.google.common.base.Optional;
  33import com.google.common.base.Preconditions;
  34import com.google.common.base.Throwables;
  35import com.google.common.collect.ImmutableList;
  36import com.google.common.collect.ImmutableSet;
  37import com.google.common.util.concurrent.FutureCallback;
  38import com.google.common.util.concurrent.Futures;
  39
  40import org.checkerframework.checker.nullness.compatqual.NullableDecl;
  41import org.jetbrains.annotations.NotNull;
  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.widget.DialpadView;
  61import eu.siacs.conversations.ui.util.AvatarWorkerTask;
  62import eu.siacs.conversations.ui.util.MainThreadExecutor;
  63import eu.siacs.conversations.ui.util.Rationals;
  64import eu.siacs.conversations.utils.PermissionUtils;
  65import eu.siacs.conversations.utils.TimeFrameUtils;
  66import eu.siacs.conversations.xml.Namespace;
  67import eu.siacs.conversations.xmpp.Jid;
  68import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
  69import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
  70import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
  71import eu.siacs.conversations.xmpp.jingle.Media;
  72import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
  73
  74public class RtpSessionActivity extends XmppActivity
  75        implements XmppConnectionService.OnJingleRtpConnectionUpdate,
  76                eu.siacs.conversations.ui.widget.SurfaceViewRenderer.OnAspectRatioChanged {
  77
  78    public static final String EXTRA_WITH = "with";
  79    public static final String EXTRA_SESSION_ID = "session_id";
  80    public static final String EXTRA_LAST_REPORTED_STATE = "last_reported_state";
  81    public static final String EXTRA_LAST_ACTION = "last_action";
  82    public static final String ACTION_ACCEPT_CALL = "action_accept_call";
  83    public static final String ACTION_MAKE_VOICE_CALL = "action_make_voice_call";
  84    public static final String ACTION_MAKE_VIDEO_CALL = "action_make_video_call";
  85
  86    private static final int CALL_DURATION_UPDATE_INTERVAL = 333;
  87
  88    public static final List<RtpEndUserState> END_CARD =
  89            Arrays.asList(
  90                    RtpEndUserState.APPLICATION_ERROR,
  91                    RtpEndUserState.SECURITY_ERROR,
  92                    RtpEndUserState.DECLINED_OR_BUSY,
  93                    RtpEndUserState.CONNECTIVITY_ERROR,
  94                    RtpEndUserState.CONNECTIVITY_LOST_ERROR,
  95                    RtpEndUserState.RETRACTED);
  96    private static final List<RtpEndUserState> STATES_SHOWING_HELP_BUTTON =
  97            Arrays.asList(
  98                    RtpEndUserState.APPLICATION_ERROR,
  99                    RtpEndUserState.CONNECTIVITY_ERROR,
 100                    RtpEndUserState.SECURITY_ERROR);
 101    private static final List<RtpEndUserState> STATES_SHOWING_SWITCH_TO_CHAT =
 102            Arrays.asList(
 103                    RtpEndUserState.CONNECTING,
 104                    RtpEndUserState.CONNECTED,
 105                    RtpEndUserState.RECONNECTING);
 106    private static final List<RtpEndUserState> STATES_CONSIDERED_CONNECTED =
 107            Arrays.asList(RtpEndUserState.CONNECTED, RtpEndUserState.RECONNECTING);
 108    private static final List<RtpEndUserState> STATES_SHOWING_PIP_PLACEHOLDER =
 109            Arrays.asList(
 110                    RtpEndUserState.ACCEPTING_CALL,
 111                    RtpEndUserState.CONNECTING,
 112                    RtpEndUserState.RECONNECTING);
 113    private static final String PROXIMITY_WAKE_LOCK_TAG = "conversations:in-rtp-session";
 114    private static final int REQUEST_ACCEPT_CALL = 0x1111;
 115    private WeakReference<JingleRtpConnection> rtpConnectionReference;
 116
 117    private ActivityRtpSessionBinding binding;
 118    private PowerManager.WakeLock mProximityWakeLock;
 119
 120    private final Handler mHandler = new Handler();
 121    private final Runnable mTickExecutor =
 122            new Runnable() {
 123                @Override
 124                public void run() {
 125                    updateCallDuration();
 126                    mHandler.postDelayed(mTickExecutor, CALL_DURATION_UPDATE_INTERVAL);
 127                }
 128            };
 129
 130    private static Set<Media> actionToMedia(final String action) {
 131        if (ACTION_MAKE_VIDEO_CALL.equals(action)) {
 132            return ImmutableSet.of(Media.AUDIO, Media.VIDEO);
 133        } else {
 134            return ImmutableSet.of(Media.AUDIO);
 135        }
 136    }
 137
 138    private static void addSink(
 139            final VideoTrack videoTrack, final SurfaceViewRenderer surfaceViewRenderer) {
 140        try {
 141            videoTrack.addSink(surfaceViewRenderer);
 142        } catch (final IllegalStateException e) {
 143            Log.e(
 144                    Config.LOGTAG,
 145                    "possible race condition on trying to display video track. ignoring",
 146                    e);
 147        }
 148    }
 149
 150    @Override
 151    public void onCreate(Bundle savedInstanceState) {
 152        super.onCreate(savedInstanceState);
 153        getWindow()
 154                .addFlags(
 155                        WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
 156                                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
 157                                | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
 158                                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
 159        this.binding = DataBindingUtil.setContentView(this, R.layout.activity_rtp_session);
 160        setSupportActionBar(binding.toolbar);
 161
 162        binding.dialpad.setClickConsumer(tag -> {
 163            requireRtpConnection().applyDtmfTone(tag);
 164        });
 165
 166        if (savedInstanceState != null) {
 167            boolean dialpadVisible = savedInstanceState.getBoolean("dialpad_visible");
 168            binding.dialpad.setVisibility(dialpadVisible ? View.VISIBLE : View.GONE);
 169        }
 170    }
 171
 172    @Override
 173    public boolean onCreateOptionsMenu(final Menu menu) {
 174        getMenuInflater().inflate(R.menu.activity_rtp_session, menu);
 175        final MenuItem help = menu.findItem(R.id.action_help);
 176        final MenuItem gotoChat = menu.findItem(R.id.action_goto_chat);
 177        final MenuItem dialpad = menu.findItem(R.id.action_dialpad);
 178        help.setVisible(isHelpButtonVisible());
 179        gotoChat.setVisible(isSwitchToConversationVisible());
 180        dialpad.setVisible(isAudioOnlyConversation());
 181        return super.onCreateOptionsMenu(menu);
 182    }
 183
 184    @Override
 185    public boolean onKeyDown(final int keyCode, final KeyEvent event) {
 186        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
 187            if (xmppConnectionService != null) {
 188                if (xmppConnectionService.getNotificationService().stopSoundAndVibration()) {
 189                    return true;
 190                }
 191            }
 192        }
 193        return super.onKeyDown(keyCode, event);
 194    }
 195
 196    private boolean isHelpButtonVisible() {
 197        try {
 198            return STATES_SHOWING_HELP_BUTTON.contains(requireRtpConnection().getEndUserState());
 199        } catch (IllegalStateException e) {
 200            final Intent intent = getIntent();
 201            final String state =
 202                    intent != null ? intent.getStringExtra(EXTRA_LAST_REPORTED_STATE) : null;
 203            if (state != null) {
 204                return STATES_SHOWING_HELP_BUTTON.contains(RtpEndUserState.valueOf(state));
 205            } else {
 206                return false;
 207            }
 208        }
 209    }
 210
 211    private boolean isSwitchToConversationVisible() {
 212        final JingleRtpConnection connection =
 213                this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
 214        return connection != null
 215                && STATES_SHOWING_SWITCH_TO_CHAT.contains(connection.getEndUserState());
 216    }
 217
 218    private boolean isAudioOnlyConversation() {
 219        final JingleRtpConnection connection =
 220                this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
 221
 222        return connection != null && !connection.getMedia().contains(Media.VIDEO);
 223    }
 224
 225    private void switchToConversation() {
 226        final Contact contact = getWith();
 227        final Conversation conversation =
 228                xmppConnectionService.findOrCreateConversation(
 229                        contact.getAccount(), contact.getJid(), false, true);
 230        switchToConversation(conversation);
 231    }
 232
 233    private void toggleDialpadVisibility() {
 234        if (binding.dialpad.getVisibility() == View.VISIBLE) {
 235            binding.dialpad.setVisibility(View.GONE);
 236        }
 237        else {
 238            binding.dialpad.setVisibility(View.VISIBLE);
 239        }
 240    }
 241
 242    public boolean onOptionsItemSelected(final MenuItem item) {
 243        switch (item.getItemId()) {
 244            case R.id.action_help:
 245                launchHelpInBrowser();
 246                break;
 247            case R.id.action_goto_chat:
 248                switchToConversation();
 249                break;
 250            case R.id.action_dialpad:
 251                toggleDialpadVisibility();
 252                break;
 253        }
 254        return super.onOptionsItemSelected(item);
 255    }
 256
 257    private void launchHelpInBrowser() {
 258        final Intent intent = new Intent(Intent.ACTION_VIEW, Config.HELP);
 259        try {
 260            startActivity(intent);
 261        } catch (final ActivityNotFoundException e) {
 262            Toast.makeText(this, R.string.no_application_found_to_open_link, Toast.LENGTH_LONG)
 263                    .show();
 264        }
 265    }
 266
 267    private void endCall(View view) {
 268        endCall();
 269    }
 270
 271    private void endCall() {
 272        if (this.rtpConnectionReference == null) {
 273            retractSessionProposal();
 274            finish();
 275        } else {
 276            requireRtpConnection().endCall();
 277        }
 278    }
 279
 280    private void retractSessionProposal() {
 281        final Intent intent = getIntent();
 282        final String action = intent.getAction();
 283        final Account account = extractAccount(intent);
 284        final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
 285        final String state = intent.getStringExtra(EXTRA_LAST_REPORTED_STATE);
 286        if (!Intent.ACTION_VIEW.equals(action)
 287                || state == null
 288                || !END_CARD.contains(RtpEndUserState.valueOf(state))) {
 289            resetIntent(
 290                    account, with, RtpEndUserState.RETRACTED, actionToMedia(intent.getAction()));
 291        }
 292        xmppConnectionService
 293                .getJingleConnectionManager()
 294                .retractSessionProposal(account, with.asBareJid());
 295    }
 296
 297    private void rejectCall(View view) {
 298        requireRtpConnection().rejectCall();
 299        finish();
 300    }
 301
 302    private void acceptCall(View view) {
 303        requestPermissionsAndAcceptCall();
 304    }
 305
 306    private void requestPermissionsAndAcceptCall() {
 307        final List<String> permissions;
 308        if (getMedia().contains(Media.VIDEO)) {
 309            permissions =
 310                    ImmutableList.of(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO);
 311        } else {
 312            permissions = ImmutableList.of(Manifest.permission.RECORD_AUDIO);
 313        }
 314        if (PermissionUtils.hasPermission(this, permissions, REQUEST_ACCEPT_CALL)) {
 315            putScreenInCallMode();
 316            checkRecorderAndAcceptCall();
 317        }
 318    }
 319
 320    private void checkRecorderAndAcceptCall() {
 321        checkMicrophoneAvailabilityAsync();
 322        try {
 323            requireRtpConnection().acceptCall();
 324        } catch (final IllegalStateException e) {
 325            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
 326        }
 327    }
 328
 329    private void checkMicrophoneAvailabilityAsync() {
 330        new Thread(this::checkMicrophoneAvailability).start();
 331    }
 332
 333    private void checkMicrophoneAvailability() {
 334        final long start = SystemClock.elapsedRealtime();
 335        final boolean isMicrophoneAvailable = AppRTCAudioManager.isMicrophoneAvailable();
 336        final long stop = SystemClock.elapsedRealtime();
 337        Log.d(Config.LOGTAG, "checking microphone availability took " + (stop - start) + "ms");
 338        if (isMicrophoneAvailable) {
 339            return;
 340        }
 341        runOnUiThread(
 342                () ->
 343                        Toast.makeText(this, R.string.microphone_unavailable, Toast.LENGTH_LONG)
 344                                .show());
 345    }
 346
 347    private void putScreenInCallMode() {
 348        putScreenInCallMode(requireRtpConnection().getMedia());
 349    }
 350
 351    private void putScreenInCallMode(final Set<Media> media) {
 352        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
 353        if (!media.contains(Media.VIDEO)) {
 354            final JingleRtpConnection rtpConnection =
 355                    rtpConnectionReference != null ? rtpConnectionReference.get() : null;
 356            final AppRTCAudioManager audioManager =
 357                    rtpConnection == null ? null : rtpConnection.getAudioManager();
 358            if (audioManager == null
 359                    || audioManager.getSelectedAudioDevice()
 360                            == AppRTCAudioManager.AudioDevice.EARPIECE) {
 361                acquireProximityWakeLock();
 362            }
 363        }
 364    }
 365
 366    @SuppressLint("WakelockTimeout")
 367    private void acquireProximityWakeLock() {
 368        final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
 369        if (powerManager == null) {
 370            Log.e(Config.LOGTAG, "power manager not available");
 371            return;
 372        }
 373        if (isFinishing()) {
 374            Log.e(Config.LOGTAG, "do not acquire wakelock. activity is finishing");
 375            return;
 376        }
 377        if (this.mProximityWakeLock == null) {
 378            this.mProximityWakeLock =
 379                    powerManager.newWakeLock(
 380                            PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, PROXIMITY_WAKE_LOCK_TAG);
 381        }
 382        if (!this.mProximityWakeLock.isHeld()) {
 383            Log.d(Config.LOGTAG, "acquiring proximity wake lock");
 384            this.mProximityWakeLock.acquire();
 385        }
 386    }
 387
 388    private void releaseProximityWakeLock() {
 389        if (this.mProximityWakeLock != null && mProximityWakeLock.isHeld()) {
 390            Log.d(Config.LOGTAG, "releasing proximity wake lock");
 391            this.mProximityWakeLock.release(PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY);
 392            this.mProximityWakeLock = null;
 393        }
 394    }
 395
 396    private void putProximityWakeLockInProperState(
 397            final AppRTCAudioManager.AudioDevice audioDevice) {
 398        if (audioDevice == AppRTCAudioManager.AudioDevice.EARPIECE) {
 399            acquireProximityWakeLock();
 400        } else {
 401            releaseProximityWakeLock();
 402        }
 403    }
 404
 405    @Override
 406    protected void refreshUiReal() {}
 407
 408    @Override
 409    public void onNewIntent(final Intent intent) {
 410        Log.d(Config.LOGTAG, this.getClass().getName() + ".onNewIntent()");
 411        super.onNewIntent(intent);
 412        setIntent(intent);
 413        if (xmppConnectionService == null) {
 414            Log.d(
 415                    Config.LOGTAG,
 416                    "RtpSessionActivity: background service wasn't bound in onNewIntent()");
 417            return;
 418        }
 419        final Account account = extractAccount(intent);
 420        final String action = intent.getAction();
 421        final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
 422        final String sessionId = intent.getStringExtra(EXTRA_SESSION_ID);
 423        if (sessionId != null) {
 424            Log.d(Config.LOGTAG, "reinitializing from onNewIntent()");
 425            if (initializeActivityWithRunningRtpSession(account, with, sessionId)) {
 426                return;
 427            }
 428            if (ACTION_ACCEPT_CALL.equals(intent.getAction())) {
 429                Log.d(Config.LOGTAG, "accepting call from onNewIntent()");
 430                requestPermissionsAndAcceptCall();
 431                resetIntent(intent.getExtras());
 432            }
 433        } else if (asList(ACTION_MAKE_VIDEO_CALL, ACTION_MAKE_VOICE_CALL).contains(action)) {
 434            proposeJingleRtpSession(account, with, actionToMedia(action));
 435            setWith(account.getRoster().getContact(with));
 436        } else {
 437            throw new IllegalStateException("received onNewIntent without sessionId");
 438        }
 439    }
 440
 441    @Override
 442    void onBackendConnected() {
 443        final Intent intent = getIntent();
 444        final String action = intent.getAction();
 445        final Account account = extractAccount(intent);
 446        final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
 447        final String sessionId = intent.getStringExtra(EXTRA_SESSION_ID);
 448        if (sessionId != null) {
 449            if (initializeActivityWithRunningRtpSession(account, with, sessionId)) {
 450                return;
 451            }
 452            if (ACTION_ACCEPT_CALL.equals(intent.getAction())) {
 453                Log.d(Config.LOGTAG, "intent action was accept");
 454                requestPermissionsAndAcceptCall();
 455                resetIntent(intent.getExtras());
 456            }
 457        } else if (asList(ACTION_MAKE_VIDEO_CALL, ACTION_MAKE_VOICE_CALL).contains(action)) {
 458            proposeJingleRtpSession(account, with, actionToMedia(action));
 459            setWith(account.getRoster().getContact(with));
 460        } else if (Intent.ACTION_VIEW.equals(action)) {
 461            final String extraLastState = intent.getStringExtra(EXTRA_LAST_REPORTED_STATE);
 462            final RtpEndUserState state =
 463                    extraLastState == null ? null : RtpEndUserState.valueOf(extraLastState);
 464            if (state != null) {
 465                Log.d(Config.LOGTAG, "restored last state from intent extra");
 466                updateButtonConfiguration(state);
 467                updateVerifiedShield(false);
 468                updateStateDisplay(state);
 469                updateIncomingCallScreen(state);
 470                invalidateOptionsMenu();
 471            }
 472            setWith(account.getRoster().getContact(with));
 473            if (xmppConnectionService
 474                    .getJingleConnectionManager()
 475                    .fireJingleRtpConnectionStateUpdates()) {
 476                return;
 477            }
 478            if (END_CARD.contains(state)
 479                    || xmppConnectionService
 480                            .getJingleConnectionManager()
 481                            .hasMatchingProposal(account, with)) {
 482                return;
 483            }
 484            Log.d(Config.LOGTAG, "restored state (" + state + ") was not an end card. finishing");
 485            finish();
 486        }
 487    }
 488
 489    private void setWith() {
 490        setWith(getWith());
 491    }
 492
 493    private void setWith(final Contact contact) {
 494        binding.with.setText(contact.getDisplayName());
 495        binding.withJid.setText(contact.getJid().asBareJid().toEscapedString());
 496    }
 497
 498    private void proposeJingleRtpSession(
 499            final Account account, final Jid with, final Set<Media> media) {
 500        checkMicrophoneAvailabilityAsync();
 501        if (with.isBareJid()) {
 502            xmppConnectionService
 503                    .getJingleConnectionManager()
 504                    .proposeJingleRtpSession(account, with, media);
 505        } else {
 506            final String sessionId =
 507                    xmppConnectionService
 508                            .getJingleConnectionManager()
 509                            .initializeRtpSession(account, with, media);
 510            initializeActivityWithRunningRtpSession(account, with, sessionId);
 511            resetIntent(account, with, sessionId);
 512        }
 513        putScreenInCallMode(media);
 514    }
 515
 516    @Override
 517    public void onRequestPermissionsResult(
 518            int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
 519        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
 520        if (PermissionUtils.allGranted(grantResults)) {
 521            if (requestCode == REQUEST_ACCEPT_CALL) {
 522                checkRecorderAndAcceptCall();
 523            }
 524        } else {
 525            @StringRes int res;
 526            final String firstDenied = getFirstDenied(grantResults, permissions);
 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        setWith();
 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        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));
 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(@NullableDecl 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    @Override
1343    protected void onSaveInstanceState(@NonNull @NotNull Bundle outState) {
1344        super.onSaveInstanceState(outState);
1345        outState.putBoolean("dialpad_visible", binding.dialpad.getVisibility() == View.VISIBLE);
1346    }
1347
1348    private void updateRtpSessionProposalState(
1349            final Account account, final Jid with, final RtpEndUserState state) {
1350        final Intent currentIntent = getIntent();
1351        final String withExtra =
1352                currentIntent == null ? null : currentIntent.getStringExtra(EXTRA_WITH);
1353        if (withExtra == null) {
1354            return;
1355        }
1356        if (Jid.ofEscaped(withExtra).asBareJid().equals(with)) {
1357            runOnUiThread(
1358                    () -> {
1359                        updateVerifiedShield(false);
1360                        updateStateDisplay(state);
1361                        updateButtonConfiguration(state);
1362                        updateIncomingCallScreen(state);
1363                        invalidateOptionsMenu();
1364                    });
1365            resetIntent(account, with, state, actionToMedia(currentIntent.getAction()));
1366        }
1367    }
1368
1369    private void resetIntent(final Bundle extras) {
1370        final Intent intent = new Intent(Intent.ACTION_VIEW);
1371        intent.putExtras(extras);
1372        setIntent(intent);
1373    }
1374
1375    private void resetIntent(
1376            final Account account, Jid with, final RtpEndUserState state, final Set<Media> media) {
1377        final Intent intent = new Intent(Intent.ACTION_VIEW);
1378        intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
1379        if (account.getRoster()
1380                .getContact(with)
1381                .getPresences()
1382                .anySupport(Namespace.JINGLE_MESSAGE)) {
1383            intent.putExtra(EXTRA_WITH, with.asBareJid().toEscapedString());
1384        } else {
1385            intent.putExtra(EXTRA_WITH, with.toEscapedString());
1386        }
1387        intent.putExtra(EXTRA_LAST_REPORTED_STATE, state.toString());
1388        intent.putExtra(
1389                EXTRA_LAST_ACTION,
1390                media.contains(Media.VIDEO) ? ACTION_MAKE_VIDEO_CALL : ACTION_MAKE_VOICE_CALL);
1391        setIntent(intent);
1392    }
1393
1394    private static boolean emptyReference(final WeakReference<?> weakReference) {
1395        return weakReference == null || weakReference.get() == null;
1396    }
1397}