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