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