RtpSessionActivity.java

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