RtpSessionActivity.java

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