RtpSessionActivity.java

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