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