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