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