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