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