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