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