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