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