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