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 binding.withJid.setText(with.asBareJid());
418 } else {
419 throw new IllegalStateException("received onNewIntent without sessionId");
420 }
421 }
422
423 @Override
424 void onBackendConnected() {
425 final Intent intent = getIntent();
426 final String action = intent.getAction();
427 final Account account = extractAccount(intent);
428 final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
429 final String sessionId = intent.getStringExtra(EXTRA_SESSION_ID);
430 if (sessionId != null) {
431 if (initializeActivityWithRunningRtpSession(account, with, sessionId)) {
432 return;
433 }
434 if (ACTION_ACCEPT_CALL.equals(intent.getAction())) {
435 Log.d(Config.LOGTAG, "intent action was accept");
436 requestPermissionsAndAcceptCall();
437 resetIntent(intent.getExtras());
438 }
439 } else if (asList(ACTION_MAKE_VIDEO_CALL, ACTION_MAKE_VOICE_CALL).contains(action)) {
440 proposeJingleRtpSession(account, with, actionToMedia(action));
441 binding.with.setText(account.getRoster().getContact(with).getDisplayName());
442 binding.withJid.setText(with.asBareJid());
443 } else if (Intent.ACTION_VIEW.equals(action)) {
444 final String extraLastState = intent.getStringExtra(EXTRA_LAST_REPORTED_STATE);
445 final RtpEndUserState state = extraLastState == null ? null : RtpEndUserState.valueOf(extraLastState);
446 if (state != null) {
447 Log.d(Config.LOGTAG, "restored last state from intent extra");
448 updateButtonConfiguration(state);
449 updateVerifiedShield(false);
450 updateStateDisplay(state);
451 updateProfilePicture(state);
452 invalidateOptionsMenu();
453 }
454 binding.with.setText(account.getRoster().getContact(with).getDisplayName());
455 binding.withJid.setText(with.asBareJid());
456 if (xmppConnectionService.getJingleConnectionManager().fireJingleRtpConnectionStateUpdates()) {
457 return;
458 }
459 if (END_CARD.contains(state) || xmppConnectionService.getJingleConnectionManager().hasMatchingProposal(account, with)) {
460 return;
461 }
462 Log.d(Config.LOGTAG, "restored state (" + state + ") was not an end card. finishing");
463 finish();
464 }
465 }
466
467 private void proposeJingleRtpSession(final Account account, final Jid with, final Set<Media> media) {
468 checkMicrophoneAvailability();
469 if (with.isBareJid()) {
470 xmppConnectionService.getJingleConnectionManager().proposeJingleRtpSession(account, with, media);
471 } else {
472 final String sessionId = xmppConnectionService.getJingleConnectionManager().initializeRtpSession(account, with, media);
473 initializeActivityWithRunningRtpSession(account, with, sessionId);
474 resetIntent(account, with, sessionId);
475 }
476 putScreenInCallMode(media);
477 }
478
479 @Override
480 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
481 super.onRequestPermissionsResult(requestCode, permissions, grantResults);
482 if (PermissionUtils.allGranted(grantResults)) {
483 if (requestCode == REQUEST_ACCEPT_CALL) {
484 checkRecorderAndAcceptCall();
485 }
486 } else {
487 @StringRes int res;
488 final String firstDenied = getFirstDenied(grantResults, permissions);
489 if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
490 res = R.string.no_microphone_permission;
491 } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
492 res = R.string.no_camera_permission;
493 } else {
494 throw new IllegalStateException("Invalid permission result request");
495 }
496 Toast.makeText(this, getString(res, getString(R.string.app_name)), Toast.LENGTH_SHORT).show();
497 }
498 }
499
500 @Override
501 public void onStart() {
502 super.onStart();
503 mHandler.postDelayed(mTickExecutor, CALL_DURATION_UPDATE_INTERVAL);
504 }
505
506 @Override
507 public void onStop() {
508 mHandler.removeCallbacks(mTickExecutor);
509 binding.remoteVideo.release();
510 binding.localVideo.release();
511 final WeakReference<JingleRtpConnection> weakReference = this.rtpConnectionReference;
512 final JingleRtpConnection jingleRtpConnection = weakReference == null ? null : weakReference.get();
513 if (jingleRtpConnection != null) {
514 releaseVideoTracks(jingleRtpConnection);
515 }
516 releaseProximityWakeLock();
517 super.onStop();
518 }
519
520 private void releaseVideoTracks(final JingleRtpConnection jingleRtpConnection) {
521 final Optional<VideoTrack> remoteVideo = jingleRtpConnection.getRemoteVideoTrack();
522 if (remoteVideo.isPresent()) {
523 remoteVideo.get().removeSink(binding.remoteVideo);
524 }
525 final Optional<VideoTrack> localVideo = jingleRtpConnection.getLocalVideoTrack();
526 if (localVideo.isPresent()) {
527 localVideo.get().removeSink(binding.localVideo);
528 }
529 }
530
531 @Override
532 public void onBackPressed() {
533 if (isConnected()) {
534 if (switchToPictureInPicture()) {
535 return;
536 }
537 } else {
538 endCall();
539 }
540 super.onBackPressed();
541 }
542
543 @Override
544 public void onUserLeaveHint() {
545 super.onUserLeaveHint();
546 if (switchToPictureInPicture()) {
547 return;
548 }
549 //TODO apparently this method is not getting called on Android 10 when using the task switcher
550 if (emptyReference(rtpConnectionReference) && xmppConnectionService != null) {
551 retractSessionProposal();
552 }
553 }
554
555 private boolean isConnected() {
556 final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
557 return connection != null && connection.getEndUserState() == RtpEndUserState.CONNECTED;
558 }
559
560 private boolean switchToPictureInPicture() {
561 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && deviceSupportsPictureInPicture()) {
562 if (shouldBePictureInPicture()) {
563 startPictureInPicture();
564 return true;
565 }
566 }
567 return false;
568 }
569
570 @RequiresApi(api = Build.VERSION_CODES.O)
571 private void startPictureInPicture() {
572 try {
573 enterPictureInPictureMode(
574 new PictureInPictureParams.Builder()
575 .setAspectRatio(new Rational(10, 16))
576 .build()
577 );
578 } catch (final IllegalStateException e) {
579 //this sometimes happens on Samsung phones (possibly when Knox is enabled)
580 Log.w(Config.LOGTAG, "unable to enter picture in picture mode", e);
581 }
582 }
583
584 private boolean deviceSupportsPictureInPicture() {
585 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
586 return getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE);
587 } else {
588 return false;
589 }
590 }
591
592 private boolean shouldBePictureInPicture() {
593 try {
594 final JingleRtpConnection rtpConnection = requireRtpConnection();
595 return rtpConnection.getMedia().contains(Media.VIDEO) && Arrays.asList(
596 RtpEndUserState.ACCEPTING_CALL,
597 RtpEndUserState.CONNECTING,
598 RtpEndUserState.CONNECTED
599 ).contains(rtpConnection.getEndUserState());
600 } catch (final IllegalStateException e) {
601 return false;
602 }
603 }
604
605 private boolean initializeActivityWithRunningRtpSession(final Account account, Jid with, String sessionId) {
606 final WeakReference<JingleRtpConnection> reference = xmppConnectionService.getJingleConnectionManager()
607 .findJingleRtpConnection(account, with, sessionId);
608 if (reference == null || reference.get() == null) {
609 final JingleConnectionManager.TerminatedRtpSession terminatedRtpSession = xmppConnectionService
610 .getJingleConnectionManager().getTerminalSessionState(with, sessionId);
611 if (terminatedRtpSession == null) {
612 throw new IllegalStateException("failed to initialize activity with running rtp session. session not found");
613 }
614 initializeWithTerminatedSessionState(account, with, terminatedRtpSession);
615 return true;
616 }
617 this.rtpConnectionReference = reference;
618 final RtpEndUserState currentState = requireRtpConnection().getEndUserState();
619 final boolean verified = requireRtpConnection().isVerified();
620 if (currentState == RtpEndUserState.ENDED) {
621 reference.get().throwStateTransitionException();
622 finish();
623 return true;
624 }
625 final Set<Media> media = getMedia();
626 if (currentState == RtpEndUserState.INCOMING_CALL) {
627 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
628 }
629 if (JingleRtpConnection.STATES_SHOWING_ONGOING_CALL.contains(requireRtpConnection().getState())) {
630 putScreenInCallMode();
631 }
632 binding.with.setText(getWith().getDisplayName());
633 binding.withJid.setText(with.asBareJid());
634 updateVideoViews(currentState);
635 updateStateDisplay(currentState, media);
636 updateVerifiedShield(verified && STATES_SHOWING_SWITCH_TO_CHAT.contains(currentState));
637 updateButtonConfiguration(currentState, media);
638 updateProfilePicture(currentState);
639 invalidateOptionsMenu();
640 return false;
641 }
642
643 private void initializeWithTerminatedSessionState(final Account account, final Jid with, final JingleConnectionManager.TerminatedRtpSession terminatedRtpSession) {
644 Log.d(Config.LOGTAG, "initializeWithTerminatedSessionState()");
645 if (terminatedRtpSession.state == RtpEndUserState.ENDED) {
646 finish();
647 return;
648 }
649 RtpEndUserState state = terminatedRtpSession.state;
650 resetIntent(account, with, terminatedRtpSession.state, terminatedRtpSession.media);
651 updateButtonConfiguration(state);
652 updateStateDisplay(state);
653 updateProfilePicture(state);
654 updateCallDuration();
655 updateVerifiedShield(false);
656 invalidateOptionsMenu();
657 binding.with.setText(account.getRoster().getContact(with).getDisplayName());
658 binding.withJid.setText(with.asBareJid());
659 }
660
661 private void reInitializeActivityWithRunningRtpSession(final Account account, Jid with, String sessionId) {
662 runOnUiThread(() -> initializeActivityWithRunningRtpSession(account, with, sessionId));
663 resetIntent(account, with, sessionId);
664 }
665
666 private void resetIntent(final Account account, final Jid with, final String sessionId) {
667 final Intent intent = new Intent(Intent.ACTION_VIEW);
668 intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
669 intent.putExtra(EXTRA_WITH, with.toEscapedString());
670 intent.putExtra(EXTRA_SESSION_ID, sessionId);
671 setIntent(intent);
672 }
673
674 private void ensureSurfaceViewRendererIsSetup(final SurfaceViewRenderer surfaceViewRenderer) {
675 surfaceViewRenderer.setVisibility(View.VISIBLE);
676 try {
677 surfaceViewRenderer.init(requireRtpConnection().getEglBaseContext(), null);
678 } catch (IllegalStateException e) {
679 Log.d(Config.LOGTAG, "SurfaceViewRenderer was already initialized");
680 }
681 surfaceViewRenderer.setEnableHardwareScaler(true);
682 }
683
684 private void updateStateDisplay(final RtpEndUserState state) {
685 updateStateDisplay(state, Collections.emptySet());
686 }
687
688 private void updateStateDisplay(final RtpEndUserState state, final Set<Media> media) {
689 switch (state) {
690 case INCOMING_CALL:
691 Preconditions.checkArgument(media.size() > 0, "Media must not be empty");
692 if (media.contains(Media.VIDEO)) {
693 setTitle(R.string.rtp_state_incoming_video_call);
694 } else {
695 setTitle(R.string.rtp_state_incoming_call);
696 }
697 break;
698 case CONNECTING:
699 setTitle(R.string.rtp_state_connecting);
700 break;
701 case CONNECTED:
702 setTitle(R.string.rtp_state_connected);
703 break;
704 case ACCEPTING_CALL:
705 setTitle(R.string.rtp_state_accepting_call);
706 break;
707 case ENDING_CALL:
708 setTitle(R.string.rtp_state_ending_call);
709 break;
710 case FINDING_DEVICE:
711 setTitle(R.string.rtp_state_finding_device);
712 break;
713 case RINGING:
714 setTitle(R.string.rtp_state_ringing);
715 break;
716 case DECLINED_OR_BUSY:
717 setTitle(R.string.rtp_state_declined_or_busy);
718 break;
719 case CONNECTIVITY_ERROR:
720 setTitle(R.string.rtp_state_connectivity_error);
721 break;
722 case CONNECTIVITY_LOST_ERROR:
723 setTitle(R.string.rtp_state_connectivity_lost_error);
724 break;
725 case RETRACTED:
726 setTitle(R.string.rtp_state_retracted);
727 break;
728 case APPLICATION_ERROR:
729 setTitle(R.string.rtp_state_application_failure);
730 break;
731 case SECURITY_ERROR:
732 setTitle(R.string.rtp_state_security_error);
733 break;
734 case ENDED:
735 throw new IllegalStateException("Activity should have called finishAndReleaseWakeLock();");
736 default:
737 throw new IllegalStateException(String.format("State %s has not been handled in UI", state));
738 }
739 }
740
741 private void updateVerifiedShield(final boolean verified) {
742 if (isPictureInPicture()) {
743 this.binding.verified.setVisibility(View.GONE);
744 return;
745 }
746 this.binding.verified.setVisibility(verified ? View.VISIBLE : View.GONE);
747 }
748
749 private void updateProfilePicture(final RtpEndUserState state) {
750 updateProfilePicture(state, null);
751 }
752
753 private void updateProfilePicture(final RtpEndUserState state, final Contact contact) {
754 if (state == RtpEndUserState.INCOMING_CALL || state == RtpEndUserState.ACCEPTING_CALL) {
755 final boolean show = getResources().getBoolean(R.bool.show_avatar_incoming_call);
756 if (show) {
757 binding.contactPhoto.setVisibility(View.VISIBLE);
758 if (contact == null) {
759 AvatarWorkerTask.loadAvatar(getWith(), binding.contactPhoto, R.dimen.publish_avatar_size);
760 } else {
761 AvatarWorkerTask.loadAvatar(contact, binding.contactPhoto, R.dimen.publish_avatar_size);
762 }
763 } else {
764 binding.contactPhoto.setVisibility(View.GONE);
765 }
766 } else {
767 binding.contactPhoto.setVisibility(View.GONE);
768 }
769 }
770
771 private Set<Media> getMedia() {
772 return requireRtpConnection().getMedia();
773 }
774
775 private void updateButtonConfiguration(final RtpEndUserState state) {
776 updateButtonConfiguration(state, Collections.emptySet());
777 }
778
779 @SuppressLint("RestrictedApi")
780 private void updateButtonConfiguration(final RtpEndUserState state, final Set<Media> media) {
781 if (state == RtpEndUserState.ENDING_CALL || isPictureInPicture()) {
782 this.binding.rejectCall.setVisibility(View.INVISIBLE);
783 this.binding.endCall.setVisibility(View.INVISIBLE);
784 this.binding.acceptCall.setVisibility(View.INVISIBLE);
785 } else if (state == RtpEndUserState.INCOMING_CALL) {
786 this.binding.rejectCall.setContentDescription(getString(R.string.dismiss_call));
787 this.binding.rejectCall.setOnClickListener(this::rejectCall);
788 this.binding.rejectCall.setImageResource(R.drawable.ic_call_end_white_48dp);
789 this.binding.rejectCall.setVisibility(View.VISIBLE);
790 this.binding.endCall.setVisibility(View.INVISIBLE);
791 this.binding.acceptCall.setContentDescription(getString(R.string.answer_call));
792 this.binding.acceptCall.setOnClickListener(this::acceptCall);
793 this.binding.acceptCall.setImageResource(R.drawable.ic_call_white_48dp);
794 this.binding.acceptCall.setVisibility(View.VISIBLE);
795 } else if (state == RtpEndUserState.DECLINED_OR_BUSY) {
796 this.binding.rejectCall.setContentDescription(getString(R.string.exit));
797 this.binding.rejectCall.setOnClickListener(this::exit);
798 this.binding.rejectCall.setImageResource(R.drawable.ic_clear_white_48dp);
799 this.binding.rejectCall.setVisibility(View.VISIBLE);
800 this.binding.endCall.setVisibility(View.INVISIBLE);
801 this.binding.acceptCall.setContentDescription(getString(R.string.record_voice_mail));
802 this.binding.acceptCall.setOnClickListener(this::recordVoiceMail);
803 this.binding.acceptCall.setImageResource(R.drawable.ic_voicemail_white_24dp);
804 this.binding.acceptCall.setVisibility(View.VISIBLE);
805 } else if (asList(
806 RtpEndUserState.CONNECTIVITY_ERROR,
807 RtpEndUserState.CONNECTIVITY_LOST_ERROR,
808 RtpEndUserState.APPLICATION_ERROR,
809 RtpEndUserState.RETRACTED,
810 RtpEndUserState.SECURITY_ERROR
811 ).contains(state)) {
812 this.binding.rejectCall.setContentDescription(getString(R.string.exit));
813 this.binding.rejectCall.setOnClickListener(this::exit);
814 this.binding.rejectCall.setImageResource(R.drawable.ic_clear_white_48dp);
815 this.binding.rejectCall.setVisibility(View.VISIBLE);
816 this.binding.endCall.setVisibility(View.INVISIBLE);
817 this.binding.acceptCall.setContentDescription(getString(R.string.try_again));
818 this.binding.acceptCall.setOnClickListener(this::retry);
819 this.binding.acceptCall.setImageResource(R.drawable.ic_replay_white_48dp);
820 this.binding.acceptCall.setVisibility(View.VISIBLE);
821 } else {
822 this.binding.rejectCall.setVisibility(View.INVISIBLE);
823 this.binding.endCall.setContentDescription(getString(R.string.hang_up));
824 this.binding.endCall.setOnClickListener(this::endCall);
825 this.binding.endCall.setImageResource(R.drawable.ic_call_end_white_48dp);
826 this.binding.endCall.setVisibility(View.VISIBLE);
827 this.binding.acceptCall.setVisibility(View.INVISIBLE);
828 }
829 updateInCallButtonConfiguration(state, media);
830 }
831
832 private boolean isPictureInPicture() {
833 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
834 return isInPictureInPictureMode();
835 } else {
836 return false;
837 }
838 }
839
840 private void updateInCallButtonConfiguration() {
841 updateInCallButtonConfiguration(requireRtpConnection().getEndUserState(), requireRtpConnection().getMedia());
842 }
843
844 @SuppressLint("RestrictedApi")
845 private void updateInCallButtonConfiguration(final RtpEndUserState state, final Set<Media> media) {
846 if (state == RtpEndUserState.CONNECTED && !isPictureInPicture()) {
847 Preconditions.checkArgument(media.size() > 0, "Media must not be empty");
848 if (media.contains(Media.VIDEO)) {
849 final JingleRtpConnection rtpConnection = requireRtpConnection();
850 updateInCallButtonConfigurationVideo(rtpConnection.isVideoEnabled(), rtpConnection.isCameraSwitchable());
851 } else {
852 final AppRTCAudioManager audioManager = requireRtpConnection().getAudioManager();
853 updateInCallButtonConfigurationSpeaker(
854 audioManager.getSelectedAudioDevice(),
855 audioManager.getAudioDevices().size()
856 );
857 this.binding.inCallActionFarRight.setVisibility(View.GONE);
858 }
859 if (media.contains(Media.AUDIO)) {
860 updateInCallButtonConfigurationMicrophone(requireRtpConnection().isMicrophoneEnabled());
861 } else {
862 this.binding.inCallActionLeft.setVisibility(View.GONE);
863 }
864 } else {
865 this.binding.inCallActionLeft.setVisibility(View.GONE);
866 this.binding.inCallActionRight.setVisibility(View.GONE);
867 this.binding.inCallActionFarRight.setVisibility(View.GONE);
868 }
869 }
870
871 @SuppressLint("RestrictedApi")
872 private void updateInCallButtonConfigurationSpeaker(final AppRTCAudioManager.AudioDevice selectedAudioDevice, final int numberOfChoices) {
873 switch (selectedAudioDevice) {
874 case EARPIECE:
875 this.binding.inCallActionRight.setImageResource(R.drawable.ic_volume_off_black_24dp);
876 if (numberOfChoices >= 2) {
877 this.binding.inCallActionRight.setOnClickListener(this::switchToSpeaker);
878 } else {
879 this.binding.inCallActionRight.setOnClickListener(null);
880 this.binding.inCallActionRight.setClickable(false);
881 }
882 break;
883 case WIRED_HEADSET:
884 this.binding.inCallActionRight.setImageResource(R.drawable.ic_headset_black_24dp);
885 this.binding.inCallActionRight.setOnClickListener(null);
886 this.binding.inCallActionRight.setClickable(false);
887 break;
888 case SPEAKER_PHONE:
889 this.binding.inCallActionRight.setImageResource(R.drawable.ic_volume_up_black_24dp);
890 if (numberOfChoices >= 2) {
891 this.binding.inCallActionRight.setOnClickListener(this::switchToEarpiece);
892 } else {
893 this.binding.inCallActionRight.setOnClickListener(null);
894 this.binding.inCallActionRight.setClickable(false);
895 }
896 break;
897 case BLUETOOTH:
898 this.binding.inCallActionRight.setImageResource(R.drawable.ic_bluetooth_audio_black_24dp);
899 this.binding.inCallActionRight.setOnClickListener(null);
900 this.binding.inCallActionRight.setClickable(false);
901 break;
902 }
903 this.binding.inCallActionRight.setVisibility(View.VISIBLE);
904 }
905
906 @SuppressLint("RestrictedApi")
907 private void updateInCallButtonConfigurationVideo(final boolean videoEnabled, final boolean isCameraSwitchable) {
908 this.binding.inCallActionRight.setVisibility(View.VISIBLE);
909 if (isCameraSwitchable) {
910 this.binding.inCallActionFarRight.setImageResource(R.drawable.ic_flip_camera_android_black_24dp);
911 this.binding.inCallActionFarRight.setVisibility(View.VISIBLE);
912 this.binding.inCallActionFarRight.setOnClickListener(this::switchCamera);
913 } else {
914 this.binding.inCallActionFarRight.setVisibility(View.GONE);
915 }
916 if (videoEnabled) {
917 this.binding.inCallActionRight.setImageResource(R.drawable.ic_videocam_black_24dp);
918 this.binding.inCallActionRight.setOnClickListener(this::disableVideo);
919 } else {
920 this.binding.inCallActionRight.setImageResource(R.drawable.ic_videocam_off_black_24dp);
921 this.binding.inCallActionRight.setOnClickListener(this::enableVideo);
922 }
923 }
924
925 private void switchCamera(final View view) {
926 Futures.addCallback(requireRtpConnection().switchCamera(), new FutureCallback<Boolean>() {
927 @Override
928 public void onSuccess(@NullableDecl Boolean isFrontCamera) {
929 binding.localVideo.setMirror(isFrontCamera);
930 }
931
932 @Override
933 public void onFailure(@NonNull final Throwable throwable) {
934 Log.d(Config.LOGTAG, "could not switch camera", Throwables.getRootCause(throwable));
935 Toast.makeText(RtpSessionActivity.this, R.string.could_not_switch_camera, Toast.LENGTH_LONG).show();
936 }
937 }, MainThreadExecutor.getInstance());
938 }
939
940 private void enableVideo(View view) {
941 try {
942 requireRtpConnection().setVideoEnabled(true);
943 } catch (final IllegalStateException e) {
944 Toast.makeText(this, R.string.unable_to_enable_video, Toast.LENGTH_SHORT).show();
945 return;
946 }
947 updateInCallButtonConfigurationVideo(true, requireRtpConnection().isCameraSwitchable());
948 }
949
950 private void disableVideo(View view) {
951 requireRtpConnection().setVideoEnabled(false);
952 updateInCallButtonConfigurationVideo(false, requireRtpConnection().isCameraSwitchable());
953
954 }
955
956 @SuppressLint("RestrictedApi")
957 private void updateInCallButtonConfigurationMicrophone(final boolean microphoneEnabled) {
958 if (microphoneEnabled) {
959 this.binding.inCallActionLeft.setImageResource(R.drawable.ic_mic_black_24dp);
960 this.binding.inCallActionLeft.setOnClickListener(this::disableMicrophone);
961 } else {
962 this.binding.inCallActionLeft.setImageResource(R.drawable.ic_mic_off_black_24dp);
963 this.binding.inCallActionLeft.setOnClickListener(this::enableMicrophone);
964 }
965 this.binding.inCallActionLeft.setVisibility(View.VISIBLE);
966 }
967
968 private void updateCallDuration() {
969 final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
970 if (connection == null || connection.getMedia().contains(Media.VIDEO)) {
971 this.binding.duration.setVisibility(View.GONE);
972 return;
973 }
974 final long rtpConnectionStarted = connection.getRtpConnectionStarted();
975 final long rtpConnectionEnded = connection.getRtpConnectionEnded();
976 if (rtpConnectionStarted != 0) {
977 final long ended = rtpConnectionEnded == 0 ? SystemClock.elapsedRealtime() : rtpConnectionEnded;
978 this.binding.duration.setText(TimeFrameUtils.formatTimePassed(rtpConnectionStarted, ended, false));
979 this.binding.duration.setVisibility(View.VISIBLE);
980 } else {
981 this.binding.duration.setVisibility(View.GONE);
982 }
983 }
984
985 private void updateVideoViews(final RtpEndUserState state) {
986 if (END_CARD.contains(state) || state == RtpEndUserState.ENDING_CALL) {
987 binding.localVideo.setVisibility(View.GONE);
988 binding.localVideo.release();
989 binding.remoteVideoWrapper.setVisibility(View.GONE);
990 binding.remoteVideo.release();
991 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
992 if (isPictureInPicture()) {
993 binding.appBarLayout.setVisibility(View.GONE);
994 binding.pipPlaceholder.setVisibility(View.VISIBLE);
995 if (Arrays.asList(
996 RtpEndUserState.APPLICATION_ERROR,
997 RtpEndUserState.CONNECTIVITY_ERROR,
998 RtpEndUserState.SECURITY_ERROR)
999 .contains(state)) {
1000 binding.pipWarning.setVisibility(View.VISIBLE);
1001 binding.pipWaiting.setVisibility(View.GONE);
1002 } else {
1003 binding.pipWarning.setVisibility(View.GONE);
1004 binding.pipWaiting.setVisibility(View.GONE);
1005 }
1006 } else {
1007 binding.appBarLayout.setVisibility(View.VISIBLE);
1008 binding.pipPlaceholder.setVisibility(View.GONE);
1009 }
1010 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1011 return;
1012 }
1013 if (isPictureInPicture() && (state == RtpEndUserState.CONNECTING || state == RtpEndUserState.ACCEPTING_CALL)) {
1014 binding.localVideo.setVisibility(View.GONE);
1015 binding.remoteVideoWrapper.setVisibility(View.GONE);
1016 binding.appBarLayout.setVisibility(View.GONE);
1017 binding.pipPlaceholder.setVisibility(View.VISIBLE);
1018 binding.pipWarning.setVisibility(View.GONE);
1019 binding.pipWaiting.setVisibility(View.VISIBLE);
1020 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1021 return;
1022 }
1023 final Optional<VideoTrack> localVideoTrack = getLocalVideoTrack();
1024 if (localVideoTrack.isPresent() && !isPictureInPicture()) {
1025 ensureSurfaceViewRendererIsSetup(binding.localVideo);
1026 //paint local view over remote view
1027 binding.localVideo.setZOrderMediaOverlay(true);
1028 binding.localVideo.setMirror(requireRtpConnection().isFrontCamera());
1029 addSink(localVideoTrack.get(), binding.localVideo);
1030 } else {
1031 binding.localVideo.setVisibility(View.GONE);
1032 }
1033 final Optional<VideoTrack> remoteVideoTrack = getRemoteVideoTrack();
1034 if (remoteVideoTrack.isPresent()) {
1035 ensureSurfaceViewRendererIsSetup(binding.remoteVideo);
1036 addSink(remoteVideoTrack.get(), binding.remoteVideo);
1037 binding.remoteVideo.setScalingType(
1038 RendererCommon.ScalingType.SCALE_ASPECT_FILL,
1039 RendererCommon.ScalingType.SCALE_ASPECT_FIT
1040 );
1041 if (state == RtpEndUserState.CONNECTED) {
1042 binding.appBarLayout.setVisibility(View.GONE);
1043 getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1044 binding.remoteVideoWrapper.setVisibility(View.VISIBLE);
1045 } else {
1046 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1047 binding.remoteVideoWrapper.setVisibility(View.GONE);
1048 }
1049 if (isPictureInPicture() && !requireRtpConnection().isMicrophoneEnabled()) {
1050 binding.pipLocalMicOffIndicator.setVisibility(View.VISIBLE);
1051 } else {
1052 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1053 }
1054 } else {
1055 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
1056 binding.remoteVideoWrapper.setVisibility(View.GONE);
1057 binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
1058 }
1059 }
1060
1061 private Optional<VideoTrack> getLocalVideoTrack() {
1062 final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1063 if (connection == null) {
1064 return Optional.absent();
1065 }
1066 return connection.getLocalVideoTrack();
1067 }
1068
1069 private Optional<VideoTrack> getRemoteVideoTrack() {
1070 final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1071 if (connection == null) {
1072 return Optional.absent();
1073 }
1074 return connection.getRemoteVideoTrack();
1075 }
1076
1077 private void disableMicrophone(View view) {
1078 final JingleRtpConnection rtpConnection = requireRtpConnection();
1079 if (rtpConnection.setMicrophoneEnabled(false)) {
1080 updateInCallButtonConfiguration();
1081 }
1082 }
1083
1084 private void enableMicrophone(View view) {
1085 final JingleRtpConnection rtpConnection = requireRtpConnection();
1086 if (rtpConnection.setMicrophoneEnabled(true)) {
1087 updateInCallButtonConfiguration();
1088 }
1089 }
1090
1091 private void switchToEarpiece(View view) {
1092 requireRtpConnection().getAudioManager().setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.EARPIECE);
1093 acquireProximityWakeLock();
1094 }
1095
1096 private void switchToSpeaker(View view) {
1097 requireRtpConnection().getAudioManager().setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.SPEAKER_PHONE);
1098 releaseProximityWakeLock();
1099 }
1100
1101 private void retry(View view) {
1102 final Intent intent = getIntent();
1103 final Account account = extractAccount(intent);
1104 final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
1105 final String lastAction = intent.getStringExtra(EXTRA_LAST_ACTION);
1106 final String action = intent.getAction();
1107 final Set<Media> media = actionToMedia(lastAction == null ? action : lastAction);
1108 this.rtpConnectionReference = null;
1109 Log.d(Config.LOGTAG, "attempting retry with " + with.toEscapedString());
1110 proposeJingleRtpSession(account, with, media);
1111 }
1112
1113 private void exit(final View view) {
1114 finish();
1115 }
1116
1117 private void recordVoiceMail(final View view) {
1118 final Intent intent = getIntent();
1119 final Account account = extractAccount(intent);
1120 final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
1121 final Conversation conversation = xmppConnectionService.findOrCreateConversation(account, with, false, true);
1122 final Intent launchIntent = new Intent(this, ConversationsActivity.class);
1123 launchIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
1124 launchIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
1125 launchIntent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
1126 launchIntent.putExtra(ConversationsActivity.EXTRA_POST_INIT_ACTION, ConversationsActivity.POST_ACTION_RECORD_VOICE);
1127 startActivity(launchIntent);
1128 finish();
1129 }
1130
1131 private Contact getWith() {
1132 final AbstractJingleConnection.Id id = requireRtpConnection().getId();
1133 final Account account = id.account;
1134 return account.getRoster().getContact(id.with);
1135 }
1136
1137 private JingleRtpConnection requireRtpConnection() {
1138 final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1139 if (connection == null) {
1140 throw new IllegalStateException("No RTP connection found");
1141 }
1142 return connection;
1143 }
1144
1145 @Override
1146 public void onJingleRtpConnectionUpdate(Account account, Jid with, final String sessionId, RtpEndUserState state) {
1147 Log.d(Config.LOGTAG, "onJingleRtpConnectionUpdate(" + state + ")");
1148 if (END_CARD.contains(state)) {
1149 Log.d(Config.LOGTAG, "end card reached");
1150 releaseProximityWakeLock();
1151 runOnUiThread(() -> getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON));
1152 }
1153 if (with.isBareJid()) {
1154 updateRtpSessionProposalState(account, with, state);
1155 return;
1156 }
1157 if (emptyReference(this.rtpConnectionReference)) {
1158 if (END_CARD.contains(state)) {
1159 Log.d(Config.LOGTAG, "not reinitializing session");
1160 return;
1161 }
1162 //this happens when going from proposed session to actual session
1163 reInitializeActivityWithRunningRtpSession(account, with, sessionId);
1164 return;
1165 }
1166 final AbstractJingleConnection.Id id = requireRtpConnection().getId();
1167 final boolean verified = requireRtpConnection().isVerified();
1168 final Set<Media> media = getMedia();
1169 final Contact contact = getWith();
1170 if (account == id.account && id.with.equals(with) && id.sessionId.equals(sessionId)) {
1171 if (state == RtpEndUserState.ENDED) {
1172 finish();
1173 return;
1174 }
1175 runOnUiThread(() -> {
1176 updateStateDisplay(state, media);
1177 updateVerifiedShield(verified && STATES_SHOWING_SWITCH_TO_CHAT.contains(state));
1178 updateButtonConfiguration(state, media);
1179 updateVideoViews(state);
1180 updateProfilePicture(state, contact);
1181 invalidateOptionsMenu();
1182 });
1183 if (END_CARD.contains(state)) {
1184 final JingleRtpConnection rtpConnection = requireRtpConnection();
1185 resetIntent(account, with, state, rtpConnection.getMedia());
1186 releaseVideoTracks(rtpConnection);
1187 this.rtpConnectionReference = null;
1188 }
1189 } else {
1190 Log.d(Config.LOGTAG, "received update for other rtp session");
1191 }
1192 }
1193
1194 @Override
1195 public void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
1196 Log.d(Config.LOGTAG, "onAudioDeviceChanged in activity: selected:" + selectedAudioDevice + ", available:" + availableAudioDevices);
1197 try {
1198 if (getMedia().contains(Media.VIDEO)) {
1199 Log.d(Config.LOGTAG, "nothing to do; in video mode");
1200 return;
1201 }
1202 final RtpEndUserState endUserState = requireRtpConnection().getEndUserState();
1203 if (endUserState == RtpEndUserState.CONNECTED) {
1204 final AppRTCAudioManager audioManager = requireRtpConnection().getAudioManager();
1205 updateInCallButtonConfigurationSpeaker(
1206 audioManager.getSelectedAudioDevice(),
1207 audioManager.getAudioDevices().size()
1208 );
1209 } else if (END_CARD.contains(endUserState)) {
1210 Log.d(Config.LOGTAG, "onAudioDeviceChanged() nothing to do because end card has been reached");
1211 } else {
1212 putProximityWakeLockInProperState(selectedAudioDevice);
1213 }
1214 } catch (IllegalStateException e) {
1215 Log.d(Config.LOGTAG, "RTP connection was not available when audio device changed");
1216 }
1217 }
1218
1219 @Override
1220 protected void onSaveInstanceState(@NonNull @NotNull Bundle outState) {
1221 super.onSaveInstanceState(outState);
1222 int visibility = findViewById(R.id.action_dialpad).getVisibility();
1223 System.out.println("visibility onSave = " + visibility);
1224 outState.putInt("dialpad_visibility", visibility);
1225 }
1226
1227 private void updateRtpSessionProposalState(final Account account, final Jid with, final RtpEndUserState state) {
1228 final Intent currentIntent = getIntent();
1229 final String withExtra = currentIntent == null ? null : currentIntent.getStringExtra(EXTRA_WITH);
1230 if (withExtra == null) {
1231 return;
1232 }
1233 if (Jid.ofEscaped(withExtra).asBareJid().equals(with)) {
1234 runOnUiThread(() -> {
1235 updateVerifiedShield(false);
1236 updateStateDisplay(state);
1237 updateButtonConfiguration(state);
1238 updateProfilePicture(state);
1239 invalidateOptionsMenu();
1240 });
1241 resetIntent(account, with, state, actionToMedia(currentIntent.getAction()));
1242 }
1243 }
1244
1245 private void resetIntent(final Bundle extras) {
1246 final Intent intent = new Intent(Intent.ACTION_VIEW);
1247 intent.putExtras(extras);
1248 setIntent(intent);
1249 }
1250
1251 private void resetIntent(final Account account, Jid with, final RtpEndUserState state, final Set<Media> media) {
1252 final Intent intent = new Intent(Intent.ACTION_VIEW);
1253 intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
1254 if (account.getRoster().getContact(with).getPresences().anySupport(Namespace.JINGLE_MESSAGE)) {
1255 intent.putExtra(EXTRA_WITH, with.asBareJid().toEscapedString());
1256 } else {
1257 intent.putExtra(EXTRA_WITH, with.toEscapedString());
1258 }
1259 intent.putExtra(EXTRA_LAST_REPORTED_STATE, state.toString());
1260 intent.putExtra(EXTRA_LAST_ACTION, media.contains(Media.VIDEO) ? ACTION_MAKE_VIDEO_CALL : ACTION_MAKE_VOICE_CALL);
1261 setIntent(intent);
1262 }
1263
1264 private static boolean emptyReference(final WeakReference<?> weakReference) {
1265 return weakReference == null || weakReference.get() == null;
1266 }
1267}