RtpSessionActivity.java

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