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