RtpSessionActivity.java

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