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