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