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