RtpSessionActivity.java

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