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                updateIncomingCallScreen(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        updateIncomingCallScreen(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        updateIncomingCallScreen(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 updateIncomingCallScreen(final RtpEndUserState state) {
 794        updateIncomingCallScreen(state, null);
 795    }
 796
 797    private void updateIncomingCallScreen(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            final Account account = contact == null ? getWith().getAccount() : contact.getAccount();
 813            binding.usingAccount.setVisibility(View.VISIBLE);
 814            binding.usingAccount.setText(
 815                    getString(
 816                            R.string.using_account,
 817                            account.getJid().asBareJid().toEscapedString()));
 818        } else {
 819            binding.usingAccount.setVisibility(View.GONE);
 820            binding.contactPhoto.setVisibility(View.GONE);
 821        }
 822    }
 823
 824    private Set<Media> getMedia() {
 825        return requireRtpConnection().getMedia();
 826    }
 827
 828    private void updateButtonConfiguration(final RtpEndUserState state) {
 829        updateButtonConfiguration(state, Collections.emptySet());
 830    }
 831
 832    @SuppressLint("RestrictedApi")
 833    private void updateButtonConfiguration(final RtpEndUserState state, final Set<Media> media) {
 834        if (state == RtpEndUserState.ENDING_CALL || isPictureInPicture()) {
 835            this.binding.rejectCall.setVisibility(View.INVISIBLE);
 836            this.binding.endCall.setVisibility(View.INVISIBLE);
 837            this.binding.acceptCall.setVisibility(View.INVISIBLE);
 838        } else if (state == RtpEndUserState.INCOMING_CALL) {
 839            this.binding.rejectCall.setContentDescription(getString(R.string.dismiss_call));
 840            this.binding.rejectCall.setOnClickListener(this::rejectCall);
 841            this.binding.rejectCall.setImageResource(R.drawable.ic_call_end_white_48dp);
 842            this.binding.rejectCall.setVisibility(View.VISIBLE);
 843            this.binding.endCall.setVisibility(View.INVISIBLE);
 844            this.binding.acceptCall.setContentDescription(getString(R.string.answer_call));
 845            this.binding.acceptCall.setOnClickListener(this::acceptCall);
 846            this.binding.acceptCall.setImageResource(R.drawable.ic_call_white_48dp);
 847            this.binding.acceptCall.setVisibility(View.VISIBLE);
 848        } else if (state == RtpEndUserState.DECLINED_OR_BUSY) {
 849            this.binding.rejectCall.setContentDescription(getString(R.string.exit));
 850            this.binding.rejectCall.setOnClickListener(this::exit);
 851            this.binding.rejectCall.setImageResource(R.drawable.ic_clear_white_48dp);
 852            this.binding.rejectCall.setVisibility(View.VISIBLE);
 853            this.binding.endCall.setVisibility(View.INVISIBLE);
 854            this.binding.acceptCall.setContentDescription(getString(R.string.record_voice_mail));
 855            this.binding.acceptCall.setOnClickListener(this::recordVoiceMail);
 856            this.binding.acceptCall.setImageResource(R.drawable.ic_voicemail_white_24dp);
 857            this.binding.acceptCall.setVisibility(View.VISIBLE);
 858        } else if (asList(
 859                        RtpEndUserState.CONNECTIVITY_ERROR,
 860                        RtpEndUserState.CONNECTIVITY_LOST_ERROR,
 861                        RtpEndUserState.APPLICATION_ERROR,
 862                        RtpEndUserState.RETRACTED,
 863                        RtpEndUserState.SECURITY_ERROR)
 864                .contains(state)) {
 865            this.binding.rejectCall.setContentDescription(getString(R.string.exit));
 866            this.binding.rejectCall.setOnClickListener(this::exit);
 867            this.binding.rejectCall.setImageResource(R.drawable.ic_clear_white_48dp);
 868            this.binding.rejectCall.setVisibility(View.VISIBLE);
 869            this.binding.endCall.setVisibility(View.INVISIBLE);
 870            this.binding.acceptCall.setContentDescription(getString(R.string.try_again));
 871            this.binding.acceptCall.setOnClickListener(this::retry);
 872            this.binding.acceptCall.setImageResource(R.drawable.ic_replay_white_48dp);
 873            this.binding.acceptCall.setVisibility(View.VISIBLE);
 874        } else {
 875            this.binding.rejectCall.setVisibility(View.INVISIBLE);
 876            this.binding.endCall.setContentDescription(getString(R.string.hang_up));
 877            this.binding.endCall.setOnClickListener(this::endCall);
 878            this.binding.endCall.setImageResource(R.drawable.ic_call_end_white_48dp);
 879            this.binding.endCall.setVisibility(View.VISIBLE);
 880            this.binding.acceptCall.setVisibility(View.INVISIBLE);
 881        }
 882        updateInCallButtonConfiguration(state, media);
 883    }
 884
 885    private boolean isPictureInPicture() {
 886        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
 887            return isInPictureInPictureMode();
 888        } else {
 889            return false;
 890        }
 891    }
 892
 893    private void updateInCallButtonConfiguration() {
 894        updateInCallButtonConfiguration(
 895                requireRtpConnection().getEndUserState(), requireRtpConnection().getMedia());
 896    }
 897
 898    @SuppressLint("RestrictedApi")
 899    private void updateInCallButtonConfiguration(
 900            final RtpEndUserState state, final Set<Media> media) {
 901        if (STATES_CONSIDERED_CONNECTED.contains(state) && !isPictureInPicture()) {
 902            Preconditions.checkArgument(media.size() > 0, "Media must not be empty");
 903            if (media.contains(Media.VIDEO)) {
 904                final JingleRtpConnection rtpConnection = requireRtpConnection();
 905                updateInCallButtonConfigurationVideo(
 906                        rtpConnection.isVideoEnabled(), rtpConnection.isCameraSwitchable());
 907            } else {
 908                final AppRTCAudioManager audioManager = requireRtpConnection().getAudioManager();
 909                updateInCallButtonConfigurationSpeaker(
 910                        audioManager.getSelectedAudioDevice(),
 911                        audioManager.getAudioDevices().size());
 912                this.binding.inCallActionFarRight.setVisibility(View.GONE);
 913            }
 914            if (media.contains(Media.AUDIO)) {
 915                updateInCallButtonConfigurationMicrophone(
 916                        requireRtpConnection().isMicrophoneEnabled());
 917            } else {
 918                this.binding.inCallActionLeft.setVisibility(View.GONE);
 919            }
 920        } else {
 921            this.binding.inCallActionLeft.setVisibility(View.GONE);
 922            this.binding.inCallActionRight.setVisibility(View.GONE);
 923            this.binding.inCallActionFarRight.setVisibility(View.GONE);
 924        }
 925    }
 926
 927    @SuppressLint("RestrictedApi")
 928    private void updateInCallButtonConfigurationSpeaker(
 929            final AppRTCAudioManager.AudioDevice selectedAudioDevice, final int numberOfChoices) {
 930        switch (selectedAudioDevice) {
 931            case EARPIECE:
 932                this.binding.inCallActionRight.setImageResource(
 933                        R.drawable.ic_volume_off_black_24dp);
 934                if (numberOfChoices >= 2) {
 935                    this.binding.inCallActionRight.setOnClickListener(this::switchToSpeaker);
 936                } else {
 937                    this.binding.inCallActionRight.setOnClickListener(null);
 938                    this.binding.inCallActionRight.setClickable(false);
 939                }
 940                break;
 941            case WIRED_HEADSET:
 942                this.binding.inCallActionRight.setImageResource(R.drawable.ic_headset_black_24dp);
 943                this.binding.inCallActionRight.setOnClickListener(null);
 944                this.binding.inCallActionRight.setClickable(false);
 945                break;
 946            case SPEAKER_PHONE:
 947                this.binding.inCallActionRight.setImageResource(R.drawable.ic_volume_up_black_24dp);
 948                if (numberOfChoices >= 2) {
 949                    this.binding.inCallActionRight.setOnClickListener(this::switchToEarpiece);
 950                } else {
 951                    this.binding.inCallActionRight.setOnClickListener(null);
 952                    this.binding.inCallActionRight.setClickable(false);
 953                }
 954                break;
 955            case BLUETOOTH:
 956                this.binding.inCallActionRight.setImageResource(
 957                        R.drawable.ic_bluetooth_audio_black_24dp);
 958                this.binding.inCallActionRight.setOnClickListener(null);
 959                this.binding.inCallActionRight.setClickable(false);
 960                break;
 961        }
 962        this.binding.inCallActionRight.setVisibility(View.VISIBLE);
 963    }
 964
 965    @SuppressLint("RestrictedApi")
 966    private void updateInCallButtonConfigurationVideo(
 967            final boolean videoEnabled, final boolean isCameraSwitchable) {
 968        this.binding.inCallActionRight.setVisibility(View.VISIBLE);
 969        if (isCameraSwitchable) {
 970            this.binding.inCallActionFarRight.setImageResource(
 971                    R.drawable.ic_flip_camera_android_black_24dp);
 972            this.binding.inCallActionFarRight.setVisibility(View.VISIBLE);
 973            this.binding.inCallActionFarRight.setOnClickListener(this::switchCamera);
 974        } else {
 975            this.binding.inCallActionFarRight.setVisibility(View.GONE);
 976        }
 977        if (videoEnabled) {
 978            this.binding.inCallActionRight.setImageResource(R.drawable.ic_videocam_black_24dp);
 979            this.binding.inCallActionRight.setOnClickListener(this::disableVideo);
 980        } else {
 981            this.binding.inCallActionRight.setImageResource(R.drawable.ic_videocam_off_black_24dp);
 982            this.binding.inCallActionRight.setOnClickListener(this::enableVideo);
 983        }
 984    }
 985
 986    private void switchCamera(final View view) {
 987        Futures.addCallback(
 988                requireRtpConnection().switchCamera(),
 989                new FutureCallback<Boolean>() {
 990                    @Override
 991                    public void onSuccess(@NullableDecl Boolean isFrontCamera) {
 992                        binding.localVideo.setMirror(isFrontCamera);
 993                    }
 994
 995                    @Override
 996                    public void onFailure(@NonNull final Throwable throwable) {
 997                        Log.d(
 998                                Config.LOGTAG,
 999                                "could not switch camera",
1000                                Throwables.getRootCause(throwable));
1001                        Toast.makeText(
1002                                        RtpSessionActivity.this,
1003                                        R.string.could_not_switch_camera,
1004                                        Toast.LENGTH_LONG)
1005                                .show();
1006                    }
1007                },
1008                MainThreadExecutor.getInstance());
1009    }
1010
1011    private void enableVideo(View view) {
1012        try {
1013            requireRtpConnection().setVideoEnabled(true);
1014        } catch (final IllegalStateException e) {
1015            Toast.makeText(this, R.string.unable_to_enable_video, Toast.LENGTH_SHORT).show();
1016            return;
1017        }
1018        updateInCallButtonConfigurationVideo(true, requireRtpConnection().isCameraSwitchable());
1019    }
1020
1021    private void disableVideo(View view) {
1022        requireRtpConnection().setVideoEnabled(false);
1023        updateInCallButtonConfigurationVideo(false, requireRtpConnection().isCameraSwitchable());
1024    }
1025
1026    @SuppressLint("RestrictedApi")
1027    private void updateInCallButtonConfigurationMicrophone(final boolean microphoneEnabled) {
1028        if (microphoneEnabled) {
1029            this.binding.inCallActionLeft.setImageResource(R.drawable.ic_mic_black_24dp);
1030            this.binding.inCallActionLeft.setOnClickListener(this::disableMicrophone);
1031        } else {
1032            this.binding.inCallActionLeft.setImageResource(R.drawable.ic_mic_off_black_24dp);
1033            this.binding.inCallActionLeft.setOnClickListener(this::enableMicrophone);
1034        }
1035        this.binding.inCallActionLeft.setVisibility(View.VISIBLE);
1036    }
1037
1038    private void updateCallDuration() {
1039        final JingleRtpConnection connection =
1040                this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1041        if (connection == null || connection.getMedia().contains(Media.VIDEO)) {
1042            this.binding.duration.setVisibility(View.GONE);
1043            return;
1044        }
1045        if (connection.zeroDuration()) {
1046            this.binding.duration.setVisibility(View.GONE);
1047        } else {
1048            this.binding.duration.setText(
1049                    TimeFrameUtils.formatElapsedTime(connection.getCallDuration(), false));
1050            this.binding.duration.setVisibility(View.VISIBLE);
1051        }
1052    }
1053
1054    private void updateVideoViews(final RtpEndUserState state) {
1055        if (END_CARD.contains(state) || state == RtpEndUserState.ENDING_CALL) {
1056            binding.localVideo.setVisibility(View.GONE);
1057            binding.localVideo.release();
1058            binding.remoteVideoWrapper.setVisibility(View.GONE);
1059            binding.remoteVideo.release();
1060            binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1061            if (isPictureInPicture()) {
1062                binding.appBarLayout.setVisibility(View.GONE);
1063                binding.pipPlaceholder.setVisibility(View.VISIBLE);
1064                if (Arrays.asList(
1065                                RtpEndUserState.APPLICATION_ERROR,
1066                                RtpEndUserState.CONNECTIVITY_ERROR,
1067                                RtpEndUserState.SECURITY_ERROR)
1068                        .contains(state)) {
1069                    binding.pipWarning.setVisibility(View.VISIBLE);
1070                    binding.pipWaiting.setVisibility(View.GONE);
1071                } else {
1072                    binding.pipWarning.setVisibility(View.GONE);
1073                    binding.pipWaiting.setVisibility(View.GONE);
1074                }
1075            } else {
1076                binding.appBarLayout.setVisibility(View.VISIBLE);
1077                binding.pipPlaceholder.setVisibility(View.GONE);
1078            }
1079            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1080            return;
1081        }
1082        if (isPictureInPicture() && STATES_SHOWING_PIP_PLACEHOLDER.contains(state)) {
1083            binding.localVideo.setVisibility(View.GONE);
1084            binding.remoteVideoWrapper.setVisibility(View.GONE);
1085            binding.appBarLayout.setVisibility(View.GONE);
1086            binding.pipPlaceholder.setVisibility(View.VISIBLE);
1087            binding.pipWarning.setVisibility(View.GONE);
1088            binding.pipWaiting.setVisibility(View.VISIBLE);
1089            binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1090            return;
1091        }
1092        final Optional<VideoTrack> localVideoTrack = getLocalVideoTrack();
1093        if (localVideoTrack.isPresent() && !isPictureInPicture()) {
1094            ensureSurfaceViewRendererIsSetup(binding.localVideo);
1095            // paint local view over remote view
1096            binding.localVideo.setZOrderMediaOverlay(true);
1097            binding.localVideo.setMirror(requireRtpConnection().isFrontCamera());
1098            addSink(localVideoTrack.get(), binding.localVideo);
1099        } else {
1100            binding.localVideo.setVisibility(View.GONE);
1101        }
1102        final Optional<VideoTrack> remoteVideoTrack = getRemoteVideoTrack();
1103        if (remoteVideoTrack.isPresent()) {
1104            ensureSurfaceViewRendererIsSetup(binding.remoteVideo);
1105            addSink(remoteVideoTrack.get(), binding.remoteVideo);
1106            binding.remoteVideo.setScalingType(
1107                    RendererCommon.ScalingType.SCALE_ASPECT_FILL,
1108                    RendererCommon.ScalingType.SCALE_ASPECT_FIT);
1109            if (state == RtpEndUserState.CONNECTED) {
1110                binding.appBarLayout.setVisibility(View.GONE);
1111                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1112                binding.remoteVideoWrapper.setVisibility(View.VISIBLE);
1113            } else {
1114                binding.appBarLayout.setVisibility(View.VISIBLE);
1115                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1116                binding.remoteVideoWrapper.setVisibility(View.GONE);
1117            }
1118            if (isPictureInPicture() && !requireRtpConnection().isMicrophoneEnabled()) {
1119                binding.pipLocalMicOffIndicator.setVisibility(View.VISIBLE);
1120            } else {
1121                binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1122            }
1123        } else {
1124            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1125            binding.remoteVideoWrapper.setVisibility(View.GONE);
1126            binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1127        }
1128    }
1129
1130    private Optional<VideoTrack> getLocalVideoTrack() {
1131        final JingleRtpConnection connection =
1132                this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1133        if (connection == null) {
1134            return Optional.absent();
1135        }
1136        return connection.getLocalVideoTrack();
1137    }
1138
1139    private Optional<VideoTrack> getRemoteVideoTrack() {
1140        final JingleRtpConnection connection =
1141                this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1142        if (connection == null) {
1143            return Optional.absent();
1144        }
1145        return connection.getRemoteVideoTrack();
1146    }
1147
1148    private void disableMicrophone(View view) {
1149        final JingleRtpConnection rtpConnection = requireRtpConnection();
1150        if (rtpConnection.setMicrophoneEnabled(false)) {
1151            updateInCallButtonConfiguration();
1152        }
1153    }
1154
1155    private void enableMicrophone(View view) {
1156        final JingleRtpConnection rtpConnection = requireRtpConnection();
1157        if (rtpConnection.setMicrophoneEnabled(true)) {
1158            updateInCallButtonConfiguration();
1159        }
1160    }
1161
1162    private void switchToEarpiece(View view) {
1163        requireRtpConnection()
1164                .getAudioManager()
1165                .setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.EARPIECE);
1166        acquireProximityWakeLock();
1167    }
1168
1169    private void switchToSpeaker(View view) {
1170        requireRtpConnection()
1171                .getAudioManager()
1172                .setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.SPEAKER_PHONE);
1173        releaseProximityWakeLock();
1174    }
1175
1176    private void retry(View view) {
1177        final Intent intent = getIntent();
1178        final Account account = extractAccount(intent);
1179        final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
1180        final String lastAction = intent.getStringExtra(EXTRA_LAST_ACTION);
1181        final String action = intent.getAction();
1182        final Set<Media> media = actionToMedia(lastAction == null ? action : lastAction);
1183        this.rtpConnectionReference = null;
1184        Log.d(Config.LOGTAG, "attempting retry with " + with.toEscapedString());
1185        proposeJingleRtpSession(account, with, media);
1186    }
1187
1188    private void exit(final View view) {
1189        finish();
1190    }
1191
1192    private void recordVoiceMail(final View view) {
1193        final Intent intent = getIntent();
1194        final Account account = extractAccount(intent);
1195        final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
1196        final Conversation conversation =
1197                xmppConnectionService.findOrCreateConversation(account, with, false, true);
1198        final Intent launchIntent = new Intent(this, ConversationsActivity.class);
1199        launchIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
1200        launchIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
1201        launchIntent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
1202        launchIntent.putExtra(
1203                ConversationsActivity.EXTRA_POST_INIT_ACTION,
1204                ConversationsActivity.POST_ACTION_RECORD_VOICE);
1205        startActivity(launchIntent);
1206        finish();
1207    }
1208
1209    private Contact getWith() {
1210        final AbstractJingleConnection.Id id = requireRtpConnection().getId();
1211        final Account account = id.account;
1212        return account.getRoster().getContact(id.with);
1213    }
1214
1215    private JingleRtpConnection requireRtpConnection() {
1216        final JingleRtpConnection connection =
1217                this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1218        if (connection == null) {
1219            throw new IllegalStateException("No RTP connection found");
1220        }
1221        return connection;
1222    }
1223
1224    @Override
1225    public void onJingleRtpConnectionUpdate(
1226            Account account, Jid with, final String sessionId, RtpEndUserState state) {
1227        Log.d(Config.LOGTAG, "onJingleRtpConnectionUpdate(" + state + ")");
1228        if (END_CARD.contains(state)) {
1229            Log.d(Config.LOGTAG, "end card reached");
1230            releaseProximityWakeLock();
1231            runOnUiThread(
1232                    () -> getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON));
1233        }
1234        if (with.isBareJid()) {
1235            updateRtpSessionProposalState(account, with, state);
1236            return;
1237        }
1238        if (emptyReference(this.rtpConnectionReference)) {
1239            if (END_CARD.contains(state)) {
1240                Log.d(Config.LOGTAG, "not reinitializing session");
1241                return;
1242            }
1243            // this happens when going from proposed session to actual session
1244            reInitializeActivityWithRunningRtpSession(account, with, sessionId);
1245            return;
1246        }
1247        final AbstractJingleConnection.Id id = requireRtpConnection().getId();
1248        final boolean verified = requireRtpConnection().isVerified();
1249        final Set<Media> media = getMedia();
1250        final Contact contact = getWith();
1251        if (account == id.account && id.with.equals(with) && id.sessionId.equals(sessionId)) {
1252            if (state == RtpEndUserState.ENDED) {
1253                finish();
1254                return;
1255            }
1256            runOnUiThread(
1257                    () -> {
1258                        updateStateDisplay(state, media);
1259                        updateVerifiedShield(
1260                                verified && STATES_SHOWING_SWITCH_TO_CHAT.contains(state));
1261                        updateButtonConfiguration(state, media);
1262                        updateVideoViews(state);
1263                        updateIncomingCallScreen(state, contact);
1264                        invalidateOptionsMenu();
1265                    });
1266            if (END_CARD.contains(state)) {
1267                final JingleRtpConnection rtpConnection = requireRtpConnection();
1268                resetIntent(account, with, state, rtpConnection.getMedia());
1269                releaseVideoTracks(rtpConnection);
1270                this.rtpConnectionReference = null;
1271            }
1272        } else {
1273            Log.d(Config.LOGTAG, "received update for other rtp session");
1274        }
1275    }
1276
1277    @Override
1278    public void onAudioDeviceChanged(
1279            AppRTCAudioManager.AudioDevice selectedAudioDevice,
1280            Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
1281        Log.d(
1282                Config.LOGTAG,
1283                "onAudioDeviceChanged in activity: selected:"
1284                        + selectedAudioDevice
1285                        + ", available:"
1286                        + availableAudioDevices);
1287        try {
1288            if (getMedia().contains(Media.VIDEO)) {
1289                Log.d(Config.LOGTAG, "nothing to do; in video mode");
1290                return;
1291            }
1292            final RtpEndUserState endUserState = requireRtpConnection().getEndUserState();
1293            if (endUserState == RtpEndUserState.CONNECTED) {
1294                final AppRTCAudioManager audioManager = requireRtpConnection().getAudioManager();
1295                updateInCallButtonConfigurationSpeaker(
1296                        audioManager.getSelectedAudioDevice(),
1297                        audioManager.getAudioDevices().size());
1298            } else if (END_CARD.contains(endUserState)) {
1299                Log.d(
1300                        Config.LOGTAG,
1301                        "onAudioDeviceChanged() nothing to do because end card has been reached");
1302            } else {
1303                putProximityWakeLockInProperState(selectedAudioDevice);
1304            }
1305        } catch (IllegalStateException e) {
1306            Log.d(Config.LOGTAG, "RTP connection was not available when audio device changed");
1307        }
1308    }
1309
1310    private void updateRtpSessionProposalState(
1311            final Account account, final Jid with, final RtpEndUserState state) {
1312        final Intent currentIntent = getIntent();
1313        final String withExtra =
1314                currentIntent == null ? null : currentIntent.getStringExtra(EXTRA_WITH);
1315        if (withExtra == null) {
1316            return;
1317        }
1318        if (Jid.ofEscaped(withExtra).asBareJid().equals(with)) {
1319            runOnUiThread(
1320                    () -> {
1321                        updateVerifiedShield(false);
1322                        updateStateDisplay(state);
1323                        updateButtonConfiguration(state);
1324                        updateIncomingCallScreen(state);
1325                        invalidateOptionsMenu();
1326                    });
1327            resetIntent(account, with, state, actionToMedia(currentIntent.getAction()));
1328        }
1329    }
1330
1331    private void resetIntent(final Bundle extras) {
1332        final Intent intent = new Intent(Intent.ACTION_VIEW);
1333        intent.putExtras(extras);
1334        setIntent(intent);
1335    }
1336
1337    private void resetIntent(
1338            final Account account, Jid with, final RtpEndUserState state, final Set<Media> media) {
1339        final Intent intent = new Intent(Intent.ACTION_VIEW);
1340        intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
1341        if (account.getRoster()
1342                .getContact(with)
1343                .getPresences()
1344                .anySupport(Namespace.JINGLE_MESSAGE)) {
1345            intent.putExtra(EXTRA_WITH, with.asBareJid().toEscapedString());
1346        } else {
1347            intent.putExtra(EXTRA_WITH, with.toEscapedString());
1348        }
1349        intent.putExtra(EXTRA_LAST_REPORTED_STATE, state.toString());
1350        intent.putExtra(
1351                EXTRA_LAST_ACTION,
1352                media.contains(Media.VIDEO) ? ACTION_MAKE_VIDEO_CALL : ACTION_MAKE_VOICE_CALL);
1353        setIntent(intent);
1354    }
1355
1356    private static boolean emptyReference(final WeakReference<?> weakReference) {
1357        return weakReference == null || weakReference.get() == null;
1358    }
1359}