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