CallActivity.java 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683
  1. /*
  2. * Nextcloud Talk application
  3. *
  4. * @author Mario Danic
  5. * Copyright (C) 2017-2018 Mario Danic <mario@lovelyhq.com>
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. package com.nextcloud.talk.activities;
  21. import android.Manifest;
  22. import android.animation.Animator;
  23. import android.animation.AnimatorListenerAdapter;
  24. import android.annotation.SuppressLint;
  25. import android.app.PendingIntent;
  26. import android.app.RemoteAction;
  27. import android.content.BroadcastReceiver;
  28. import android.content.Context;
  29. import android.content.Intent;
  30. import android.content.IntentFilter;
  31. import android.content.pm.PackageManager;
  32. import android.content.res.Configuration;
  33. import android.graphics.Color;
  34. import android.graphics.drawable.Icon;
  35. import android.media.AudioAttributes;
  36. import android.media.MediaPlayer;
  37. import android.net.Uri;
  38. import android.os.Build;
  39. import android.os.Bundle;
  40. import android.os.Handler;
  41. import android.os.Looper;
  42. import android.text.TextUtils;
  43. import android.util.DisplayMetrics;
  44. import android.util.Log;
  45. import android.view.MotionEvent;
  46. import android.view.View;
  47. import android.view.ViewGroup;
  48. import android.view.ViewTreeObserver;
  49. import android.widget.FrameLayout;
  50. import android.widget.RelativeLayout;
  51. import android.widget.Toast;
  52. import com.bluelinelabs.logansquare.LoganSquare;
  53. import com.nextcloud.talk.R;
  54. import com.nextcloud.talk.adapters.ParticipantDisplayItem;
  55. import com.nextcloud.talk.adapters.ParticipantsAdapter;
  56. import com.nextcloud.talk.api.NcApi;
  57. import com.nextcloud.talk.application.NextcloudTalkApplication;
  58. import com.nextcloud.talk.data.user.model.User;
  59. import com.nextcloud.talk.databinding.CallActivityBinding;
  60. import com.nextcloud.talk.events.ConfigurationChangeEvent;
  61. import com.nextcloud.talk.events.MediaStreamEvent;
  62. import com.nextcloud.talk.events.NetworkEvent;
  63. import com.nextcloud.talk.events.PeerConnectionEvent;
  64. import com.nextcloud.talk.events.SessionDescriptionSendEvent;
  65. import com.nextcloud.talk.events.WebSocketCommunicationEvent;
  66. import com.nextcloud.talk.models.ExternalSignalingServer;
  67. import com.nextcloud.talk.models.json.capabilities.CapabilitiesOverall;
  68. import com.nextcloud.talk.models.json.conversations.Conversation;
  69. import com.nextcloud.talk.models.json.conversations.RoomOverall;
  70. import com.nextcloud.talk.models.json.conversations.RoomsOverall;
  71. import com.nextcloud.talk.models.json.generic.GenericOverall;
  72. import com.nextcloud.talk.models.json.participants.Participant;
  73. import com.nextcloud.talk.models.json.participants.ParticipantsOverall;
  74. import com.nextcloud.talk.models.json.signaling.DataChannelMessage;
  75. import com.nextcloud.talk.models.json.signaling.DataChannelMessageNick;
  76. import com.nextcloud.talk.models.json.signaling.NCIceCandidate;
  77. import com.nextcloud.talk.models.json.signaling.NCMessagePayload;
  78. import com.nextcloud.talk.models.json.signaling.NCMessageWrapper;
  79. import com.nextcloud.talk.models.json.signaling.NCSignalingMessage;
  80. import com.nextcloud.talk.models.json.signaling.Signaling;
  81. import com.nextcloud.talk.models.json.signaling.SignalingOverall;
  82. import com.nextcloud.talk.models.json.signaling.settings.IceServer;
  83. import com.nextcloud.talk.models.json.signaling.settings.SignalingSettingsOverall;
  84. import com.nextcloud.talk.ui.dialog.AudioOutputDialog;
  85. import com.nextcloud.talk.users.UserManager;
  86. import com.nextcloud.talk.utils.ApiUtils;
  87. import com.nextcloud.talk.utils.DisplayUtils;
  88. import com.nextcloud.talk.utils.NotificationUtils;
  89. import com.nextcloud.talk.utils.animations.PulseAnimation;
  90. import com.nextcloud.talk.utils.bundle.BundleKeys;
  91. import com.nextcloud.talk.utils.permissions.PlatformPermissionUtil;
  92. import com.nextcloud.talk.utils.power.PowerManagerUtils;
  93. import com.nextcloud.talk.utils.preferences.AppPreferences;
  94. import com.nextcloud.talk.utils.singletons.ApplicationWideCurrentRoomHolder;
  95. import com.nextcloud.talk.webrtc.MagicWebRTCUtils;
  96. import com.nextcloud.talk.webrtc.MagicWebSocketInstance;
  97. import com.nextcloud.talk.webrtc.PeerConnectionWrapper;
  98. import com.nextcloud.talk.webrtc.WebRtcAudioManager;
  99. import com.nextcloud.talk.webrtc.WebSocketConnectionHelper;
  100. import com.wooplr.spotlight.SpotlightView;
  101. import org.apache.commons.lang3.StringEscapeUtils;
  102. import org.greenrobot.eventbus.EventBus;
  103. import org.greenrobot.eventbus.Subscribe;
  104. import org.greenrobot.eventbus.ThreadMode;
  105. import org.webrtc.AudioSource;
  106. import org.webrtc.AudioTrack;
  107. import org.webrtc.Camera1Enumerator;
  108. import org.webrtc.Camera2Enumerator;
  109. import org.webrtc.CameraEnumerator;
  110. import org.webrtc.CameraVideoCapturer;
  111. import org.webrtc.DefaultVideoDecoderFactory;
  112. import org.webrtc.DefaultVideoEncoderFactory;
  113. import org.webrtc.EglBase;
  114. import org.webrtc.IceCandidate;
  115. import org.webrtc.Logging;
  116. import org.webrtc.MediaConstraints;
  117. import org.webrtc.MediaStream;
  118. import org.webrtc.PeerConnection;
  119. import org.webrtc.PeerConnectionFactory;
  120. import org.webrtc.RendererCommon;
  121. import org.webrtc.SessionDescription;
  122. import org.webrtc.SurfaceTextureHelper;
  123. import org.webrtc.VideoCapturer;
  124. import org.webrtc.VideoSource;
  125. import org.webrtc.VideoTrack;
  126. import java.io.IOException;
  127. import java.util.ArrayList;
  128. import java.util.HashMap;
  129. import java.util.HashSet;
  130. import java.util.List;
  131. import java.util.Map;
  132. import java.util.Objects;
  133. import java.util.Set;
  134. import java.util.concurrent.TimeUnit;
  135. import javax.inject.Inject;
  136. import androidx.activity.result.ActivityResultLauncher;
  137. import androidx.activity.result.contract.ActivityResultContracts;
  138. import androidx.annotation.DrawableRes;
  139. import androidx.annotation.NonNull;
  140. import androidx.annotation.Nullable;
  141. import androidx.annotation.RequiresApi;
  142. import androidx.appcompat.app.AppCompatActivity;
  143. import androidx.appcompat.content.res.AppCompatResources;
  144. import androidx.core.content.ContextCompat;
  145. import androidx.core.graphics.drawable.DrawableCompat;
  146. import autodagger.AutoInjector;
  147. import io.reactivex.Observable;
  148. import io.reactivex.Observer;
  149. import io.reactivex.android.schedulers.AndroidSchedulers;
  150. import io.reactivex.disposables.Disposable;
  151. import io.reactivex.schedulers.Schedulers;
  152. import me.zhanghai.android.effortlesspermissions.AfterPermissionDenied;
  153. import me.zhanghai.android.effortlesspermissions.EffortlessPermissions;
  154. import me.zhanghai.android.effortlesspermissions.OpenAppDetailsDialogFragment;
  155. import okhttp3.Cache;
  156. import pub.devrel.easypermissions.AfterPermissionGranted;
  157. import static android.app.PendingIntent.FLAG_IMMUTABLE;
  158. import static com.nextcloud.talk.webrtc.Globals.JOB_ID;
  159. import static com.nextcloud.talk.webrtc.Globals.PARTICIPANTS_UPDATE;
  160. import static com.nextcloud.talk.webrtc.Globals.ROOM_TOKEN;
  161. import static com.nextcloud.talk.webrtc.Globals.UPDATE_ALL;
  162. import static com.nextcloud.talk.webrtc.Globals.UPDATE_IN_CALL;
  163. @AutoInjector(NextcloudTalkApplication.class)
  164. public class CallActivity extends CallBaseActivity {
  165. public static final String VIDEO_STREAM_TYPE_SCREEN = "screen";
  166. public static final String VIDEO_STREAM_TYPE_VIDEO = "video";
  167. @Inject
  168. NcApi ncApi;
  169. @Inject
  170. EventBus eventBus;
  171. @Inject
  172. UserManager userManager;
  173. @Inject
  174. AppPreferences appPreferences;
  175. @Inject
  176. Cache cache;
  177. @Inject
  178. PlatformPermissionUtil permissionUtil;
  179. public static final String TAG = "CallActivity";
  180. public WebRtcAudioManager audioManager;
  181. private static final String[] PERMISSIONS_CALL = {
  182. Manifest.permission.CAMERA,
  183. Manifest.permission.RECORD_AUDIO
  184. };
  185. private static final String[] PERMISSIONS_CAMERA = {
  186. Manifest.permission.CAMERA
  187. };
  188. private static final String[] PERMISSIONS_MICROPHONE = {
  189. Manifest.permission.RECORD_AUDIO
  190. };
  191. private static final String MICROPHONE_PIP_INTENT_NAME = "microphone_pip_intent";
  192. private static final String MICROPHONE_PIP_INTENT_EXTRA_ACTION = "microphone_pip_action";
  193. private static final int MICROPHONE_PIP_REQUEST_MUTE = 1;
  194. private static final int MICROPHONE_PIP_REQUEST_UNMUTE = 2;
  195. private BroadcastReceiver mReceiver;
  196. private PeerConnectionFactory peerConnectionFactory;
  197. private MediaConstraints audioConstraints;
  198. private MediaConstraints videoConstraints;
  199. private MediaConstraints sdpConstraints;
  200. private MediaConstraints sdpConstraintsForMCU;
  201. private VideoSource videoSource;
  202. private VideoTrack localVideoTrack;
  203. private AudioSource audioSource;
  204. private AudioTrack localAudioTrack;
  205. private VideoCapturer videoCapturer;
  206. private EglBase rootEglBase;
  207. private Disposable signalingDisposable;
  208. private List<PeerConnection.IceServer> iceServers;
  209. private CameraEnumerator cameraEnumerator;
  210. private String roomToken;
  211. private User conversationUser;
  212. private String conversationName;
  213. private String callSession;
  214. private MediaStream localStream;
  215. private String credentials;
  216. private List<PeerConnectionWrapper> peerConnectionWrapperList = new ArrayList<>();
  217. private Map<String, Participant> participantMap = new HashMap<>();
  218. private boolean videoOn = false;
  219. private boolean microphoneOn = false;
  220. private boolean isVoiceOnlyCall;
  221. private boolean isCallWithoutNotification;
  222. private boolean isIncomingCallFromNotification;
  223. private Handler callControlHandler = new Handler();
  224. private Handler callInfosHandler = new Handler();
  225. private Handler cameraSwitchHandler = new Handler();
  226. // push to talk
  227. private boolean isPTTActive = false;
  228. private PulseAnimation pulseAnimation;
  229. private String baseUrl;
  230. private String roomId;
  231. private SpotlightView spotlightView;
  232. private ExternalSignalingServer externalSignalingServer;
  233. private MagicWebSocketInstance webSocketClient;
  234. private WebSocketConnectionHelper webSocketConnectionHelper;
  235. private boolean hasMCU;
  236. private boolean hasExternalSignalingServer;
  237. private String conversationPassword;
  238. private PowerManagerUtils powerManagerUtils;
  239. private Handler handler;
  240. private CallStatus currentCallStatus;
  241. private MediaPlayer mediaPlayer;
  242. private Map<String, ParticipantDisplayItem> participantDisplayItems;
  243. private ParticipantsAdapter participantsAdapter;
  244. private CallActivityBinding binding;
  245. private AudioOutputDialog audioOutputDialog;
  246. private final ActivityResultLauncher<String> requestBluetoothPermissionLauncher =
  247. registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
  248. if (isGranted) {
  249. enableBluetoothManager();
  250. }
  251. });
  252. @SuppressLint("ClickableViewAccessibility")
  253. @Override
  254. public void onCreate(Bundle savedInstanceState) {
  255. Log.d(TAG, "onCreate");
  256. super.onCreate(savedInstanceState);
  257. NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
  258. binding = CallActivityBinding.inflate(getLayoutInflater());
  259. setContentView(binding.getRoot());
  260. hideNavigationIfNoPipAvailable();
  261. Bundle extras = getIntent().getExtras();
  262. roomId = extras.getString(BundleKeys.INSTANCE.getKEY_ROOM_ID(), "");
  263. roomToken = extras.getString(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(), "");
  264. conversationUser = extras.getParcelable(BundleKeys.INSTANCE.getKEY_USER_ENTITY());
  265. conversationPassword = extras.getString(BundleKeys.INSTANCE.getKEY_CONVERSATION_PASSWORD(), "");
  266. conversationName = extras.getString(BundleKeys.INSTANCE.getKEY_CONVERSATION_NAME(), "");
  267. isVoiceOnlyCall = extras.getBoolean(BundleKeys.INSTANCE.getKEY_CALL_VOICE_ONLY(), false);
  268. isCallWithoutNotification = extras.getBoolean(BundleKeys.INSTANCE.getKEY_CALL_WITHOUT_NOTIFICATION(), false);
  269. if (extras.containsKey(BundleKeys.INSTANCE.getKEY_FROM_NOTIFICATION_START_CALL())) {
  270. isIncomingCallFromNotification = extras.getBoolean(BundleKeys.INSTANCE.getKEY_FROM_NOTIFICATION_START_CALL());
  271. }
  272. credentials = ApiUtils.getCredentials(conversationUser.getUsername(), conversationUser.getToken());
  273. baseUrl = extras.getString(BundleKeys.INSTANCE.getKEY_MODIFIED_BASE_URL(), "");
  274. if (TextUtils.isEmpty(baseUrl)) {
  275. baseUrl = conversationUser.getBaseUrl();
  276. }
  277. powerManagerUtils = new PowerManagerUtils();
  278. if (extras.getString("state", "").equalsIgnoreCase("resume")) {
  279. setCallState(CallStatus.IN_CONVERSATION);
  280. } else {
  281. setCallState(CallStatus.CONNECTING);
  282. }
  283. initClickListeners();
  284. binding.microphoneButton.setOnTouchListener(new MicrophoneButtonTouchListener());
  285. pulseAnimation = PulseAnimation.create().with(binding.microphoneButton)
  286. .setDuration(310)
  287. .setRepeatCount(PulseAnimation.INFINITE)
  288. .setRepeatMode(PulseAnimation.REVERSE);
  289. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
  290. requestBluetoothPermission();
  291. }
  292. basicInitialization();
  293. participantDisplayItems = new HashMap<>();
  294. initViews();
  295. if (!isConnectionEstablished()) {
  296. initiateCall();
  297. }
  298. updateSelfVideoViewPosition();
  299. }
  300. @RequiresApi(api = Build.VERSION_CODES.S)
  301. private void requestBluetoothPermission() {
  302. if (ContextCompat.checkSelfPermission(
  303. getContext(), Manifest.permission.BLUETOOTH_CONNECT) ==
  304. PackageManager.PERMISSION_DENIED) {
  305. requestBluetoothPermissionLauncher.launch(Manifest.permission.BLUETOOTH_CONNECT);
  306. }
  307. }
  308. private void enableBluetoothManager() {
  309. if (audioManager != null) {
  310. audioManager.startBluetoothManager();
  311. }
  312. }
  313. @Override
  314. public void onStart() {
  315. super.onStart();
  316. try {
  317. cache.evictAll();
  318. } catch (IOException e) {
  319. Log.e(TAG, "Failed to evict cache");
  320. }
  321. }
  322. private void initClickListeners() {
  323. binding.pictureInPictureButton.setOnClickListener(l -> enterPipMode());
  324. binding.audioOutputButton.setOnClickListener(v -> {
  325. audioOutputDialog = new AudioOutputDialog(this);
  326. audioOutputDialog.show();
  327. });
  328. binding.microphoneButton.setOnClickListener(l -> onMicrophoneClick());
  329. binding.microphoneButton.setOnLongClickListener(l -> {
  330. if (!microphoneOn) {
  331. callControlHandler.removeCallbacksAndMessages(null);
  332. callInfosHandler.removeCallbacksAndMessages(null);
  333. cameraSwitchHandler.removeCallbacksAndMessages(null);
  334. isPTTActive = true;
  335. binding.callControls.setVisibility(View.VISIBLE);
  336. if (!isVoiceOnlyCall) {
  337. binding.switchSelfVideoButton.setVisibility(View.VISIBLE);
  338. }
  339. }
  340. onMicrophoneClick();
  341. return true;
  342. });
  343. binding.cameraButton.setOnClickListener(l -> onCameraClick());
  344. binding.hangupButton.setOnClickListener(l -> {
  345. setCallState(CallStatus.LEAVING);
  346. hangup(true);
  347. });
  348. binding.switchSelfVideoButton.setOnClickListener(l -> switchCamera());
  349. binding.gridview.setOnItemClickListener((parent, view, position, id) -> animateCallControls(true, 0));
  350. binding.callStates.callStateRelativeLayout.setOnClickListener(l -> {
  351. if (currentCallStatus.equals(CallStatus.CALLING_TIMEOUT)) {
  352. setCallState(CallStatus.RECONNECTING);
  353. hangupNetworkCalls(false);
  354. }
  355. });
  356. }
  357. private void createCameraEnumerator() {
  358. boolean camera2EnumeratorIsSupported = false;
  359. try {
  360. camera2EnumeratorIsSupported = Camera2Enumerator.isSupported(this);
  361. } catch (final Throwable t) {
  362. Log.w(TAG, "Camera2Enumerator threw an error", t);
  363. }
  364. if (camera2EnumeratorIsSupported) {
  365. cameraEnumerator = new Camera2Enumerator(this);
  366. } else {
  367. cameraEnumerator = new Camera1Enumerator(MagicWebRTCUtils.shouldEnableVideoHardwareAcceleration());
  368. }
  369. }
  370. private void basicInitialization() {
  371. rootEglBase = EglBase.create();
  372. createCameraEnumerator();
  373. //Create a new PeerConnectionFactory instance.
  374. PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
  375. DefaultVideoEncoderFactory defaultVideoEncoderFactory = new DefaultVideoEncoderFactory(
  376. rootEglBase.getEglBaseContext(), true, true);
  377. DefaultVideoDecoderFactory defaultVideoDecoderFactory = new DefaultVideoDecoderFactory(
  378. rootEglBase.getEglBaseContext());
  379. peerConnectionFactory = PeerConnectionFactory.builder()
  380. .setOptions(options)
  381. .setVideoEncoderFactory(defaultVideoEncoderFactory)
  382. .setVideoDecoderFactory(defaultVideoDecoderFactory)
  383. .createPeerConnectionFactory();
  384. //Create MediaConstraints - Will be useful for specifying video and audio constraints.
  385. audioConstraints = new MediaConstraints();
  386. videoConstraints = new MediaConstraints();
  387. localStream = peerConnectionFactory.createLocalMediaStream("NCMS");
  388. // Create and audio manager that will take care of audio routing,
  389. // audio modes, audio device enumeration etc.
  390. audioManager = WebRtcAudioManager.create(getApplicationContext(), isVoiceOnlyCall);
  391. // Store existing audio settings and change audio mode to
  392. // MODE_IN_COMMUNICATION for best possible VoIP performance.
  393. Log.d(TAG, "Starting the audio manager...");
  394. audioManager.start(this::onAudioManagerDevicesChanged);
  395. if (isVoiceOnlyCall) {
  396. setAudioOutputChannel(WebRtcAudioManager.AudioDevice.EARPIECE);
  397. } else {
  398. setAudioOutputChannel(WebRtcAudioManager.AudioDevice.SPEAKER_PHONE);
  399. }
  400. iceServers = new ArrayList<>();
  401. //create sdpConstraints
  402. sdpConstraints = new MediaConstraints();
  403. sdpConstraintsForMCU = new MediaConstraints();
  404. sdpConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"));
  405. String offerToReceiveVideoString = "true";
  406. if (isVoiceOnlyCall) {
  407. offerToReceiveVideoString = "false";
  408. }
  409. sdpConstraints.mandatory.add(
  410. new MediaConstraints.KeyValuePair("OfferToReceiveVideo", offerToReceiveVideoString));
  411. sdpConstraintsForMCU.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "false"));
  412. sdpConstraintsForMCU.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false"));
  413. sdpConstraintsForMCU.optional.add(new MediaConstraints.KeyValuePair("internalSctpDataChannels", "true"));
  414. sdpConstraintsForMCU.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));
  415. sdpConstraints.optional.add(new MediaConstraints.KeyValuePair("internalSctpDataChannels", "true"));
  416. sdpConstraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));
  417. if (!isVoiceOnlyCall) {
  418. cameraInitialization();
  419. }
  420. microphoneInitialization();
  421. }
  422. public void setAudioOutputChannel(WebRtcAudioManager.AudioDevice selectedAudioDevice) {
  423. if (audioManager != null) {
  424. audioManager.selectAudioDevice(selectedAudioDevice);
  425. updateAudioOutputButton(audioManager.getCurrentAudioDevice());
  426. }
  427. }
  428. private void updateAudioOutputButton(WebRtcAudioManager.AudioDevice activeAudioDevice) {
  429. switch (activeAudioDevice) {
  430. case BLUETOOTH:
  431. binding.audioOutputButton.getHierarchy().setPlaceholderImage(
  432. AppCompatResources.getDrawable(context, R.drawable.ic_baseline_bluetooth_audio_24));
  433. break;
  434. case SPEAKER_PHONE:
  435. binding.audioOutputButton.getHierarchy().setPlaceholderImage(
  436. AppCompatResources.getDrawable(context, R.drawable.ic_volume_up_white_24dp));
  437. break;
  438. case EARPIECE:
  439. binding.audioOutputButton.getHierarchy().setPlaceholderImage(
  440. AppCompatResources.getDrawable(context, R.drawable.ic_baseline_phone_in_talk_24));
  441. break;
  442. case WIRED_HEADSET:
  443. binding.audioOutputButton.getHierarchy().setPlaceholderImage(
  444. AppCompatResources.getDrawable(context, R.drawable.ic_baseline_headset_mic_24));
  445. break;
  446. default:
  447. Log.e(TAG, "Icon for audio output not available");
  448. break;
  449. }
  450. DrawableCompat.setTint(binding.audioOutputButton.getDrawable(), Color.WHITE);
  451. }
  452. private void handleFromNotification() {
  453. int apiVersion = ApiUtils.getConversationApiVersion(conversationUser, new int[]{ApiUtils.APIv4, 1});
  454. ncApi.getRooms(credentials, ApiUtils.getUrlForRooms(apiVersion, baseUrl))
  455. .retry(3)
  456. .subscribeOn(Schedulers.io())
  457. .observeOn(AndroidSchedulers.mainThread())
  458. .subscribe(new Observer<RoomsOverall>() {
  459. @Override
  460. public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
  461. // unused atm
  462. }
  463. @Override
  464. public void onNext(@io.reactivex.annotations.NonNull RoomsOverall roomsOverall) {
  465. for (Conversation conversation : roomsOverall.getOcs().getData()) {
  466. if (roomId.equals(conversation.getRoomId())) {
  467. roomToken = conversation.getToken();
  468. break;
  469. }
  470. }
  471. checkPermissions();
  472. }
  473. @Override
  474. public void onError(@io.reactivex.annotations.NonNull Throwable e) {
  475. // unused atm
  476. }
  477. @Override
  478. public void onComplete() {
  479. // unused atm
  480. }
  481. });
  482. }
  483. @SuppressLint("ClickableViewAccessibility")
  484. private void initViews() {
  485. Log.d(TAG, "initViews");
  486. binding.callInfosLinearLayout.setVisibility(View.VISIBLE);
  487. binding.selfVideoViewWrapper.setVisibility(View.VISIBLE);
  488. if (!isPipModePossible()) {
  489. binding.pictureInPictureButton.setVisibility(View.GONE);
  490. }
  491. if (isVoiceOnlyCall) {
  492. binding.switchSelfVideoButton.setVisibility(View.GONE);
  493. binding.cameraButton.setVisibility(View.GONE);
  494. binding.selfVideoRenderer.setVisibility(View.GONE);
  495. RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
  496. ViewGroup.LayoutParams.WRAP_CONTENT);
  497. params.addRule(RelativeLayout.BELOW, R.id.callInfosLinearLayout);
  498. int callControlsHeight = Math.round(getApplicationContext().getResources().getDimension(R.dimen.call_controls_height));
  499. params.setMargins(0, 0, 0, callControlsHeight);
  500. binding.gridview.setLayoutParams(params);
  501. } else {
  502. RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
  503. ViewGroup.LayoutParams.WRAP_CONTENT);
  504. params.setMargins(0, 0, 0, 0);
  505. binding.gridview.setLayoutParams(params);
  506. if (cameraEnumerator.getDeviceNames().length < 2) {
  507. binding.switchSelfVideoButton.setVisibility(View.GONE);
  508. }
  509. initSelfVideoView();
  510. }
  511. binding.gridview.setOnTouchListener(new View.OnTouchListener() {
  512. public boolean onTouch(View v, MotionEvent me) {
  513. int action = me.getActionMasked();
  514. if (action == MotionEvent.ACTION_DOWN) {
  515. animateCallControls(true, 0);
  516. }
  517. return false;
  518. }
  519. });
  520. binding.conversationRelativeLayout.setOnTouchListener(new View.OnTouchListener() {
  521. public boolean onTouch(View v, MotionEvent me) {
  522. int action = me.getActionMasked();
  523. if (action == MotionEvent.ACTION_DOWN) {
  524. animateCallControls(true, 0);
  525. }
  526. return false;
  527. }
  528. });
  529. animateCallControls(true, 0);
  530. initGridAdapter();
  531. }
  532. @SuppressLint("ClickableViewAccessibility")
  533. private void initSelfVideoView() {
  534. try {
  535. binding.selfVideoRenderer.init(rootEglBase.getEglBaseContext(), null);
  536. } catch (IllegalStateException e) {
  537. Log.d(TAG, "selfVideoRenderer already initialized", e);
  538. }
  539. binding.selfVideoRenderer.setZOrderMediaOverlay(true);
  540. // disabled because it causes some devices to crash
  541. binding.selfVideoRenderer.setEnableHardwareScaler(false);
  542. binding.selfVideoRenderer.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT);
  543. binding.selfVideoRenderer.setOnTouchListener(new SelfVideoTouchListener());
  544. }
  545. private void initGridAdapter() {
  546. Log.d(TAG, "initGridAdapter");
  547. int columns;
  548. int participantsInGrid = participantDisplayItems.size();
  549. if (getResources() != null
  550. && getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
  551. if (participantsInGrid > 2) {
  552. columns = 2;
  553. } else {
  554. columns = 1;
  555. }
  556. } else {
  557. if (participantsInGrid > 2) {
  558. columns = 3;
  559. } else if (participantsInGrid > 1) {
  560. columns = 2;
  561. } else {
  562. columns = 1;
  563. }
  564. }
  565. binding.gridview.setNumColumns(columns);
  566. binding.conversationRelativeLayout
  567. .getViewTreeObserver()
  568. .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
  569. @Override
  570. public void onGlobalLayout() {
  571. binding.conversationRelativeLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
  572. int height = binding.conversationRelativeLayout.getMeasuredHeight();
  573. binding.gridview.setMinimumHeight(height);
  574. }
  575. });
  576. binding
  577. .callInfosLinearLayout
  578. .getViewTreeObserver()
  579. .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
  580. @Override
  581. public void onGlobalLayout() {
  582. binding.callInfosLinearLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
  583. }
  584. });
  585. participantsAdapter = new ParticipantsAdapter(
  586. this,
  587. participantDisplayItems,
  588. binding.conversationRelativeLayout,
  589. binding.callInfosLinearLayout,
  590. columns,
  591. isVoiceOnlyCall);
  592. binding.gridview.setAdapter(participantsAdapter);
  593. if (isInPipMode) {
  594. updateUiForPipMode();
  595. }
  596. }
  597. private void checkPermissions() {
  598. if (isVoiceOnlyCall) {
  599. onMicrophoneClick();
  600. } else {
  601. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  602. requestPermissions(PERMISSIONS_CALL, 100);
  603. } else {
  604. onRequestPermissionsResult(100, PERMISSIONS_CALL, new int[]{1, 1});
  605. }
  606. }
  607. }
  608. private boolean isConnectionEstablished() {
  609. return (currentCallStatus.equals(CallStatus.JOINED) || currentCallStatus.equals(CallStatus.IN_CONVERSATION));
  610. }
  611. @AfterPermissionGranted(100)
  612. private void onPermissionsGranted() {
  613. if (EffortlessPermissions.hasPermissions(this, PERMISSIONS_CALL)) {
  614. if (!videoOn && !isVoiceOnlyCall) {
  615. onCameraClick();
  616. }
  617. if (!microphoneOn) {
  618. onMicrophoneClick();
  619. }
  620. if (!isVoiceOnlyCall) {
  621. if (cameraEnumerator.getDeviceNames().length == 0) {
  622. binding.cameraButton.setVisibility(View.GONE);
  623. }
  624. if (cameraEnumerator.getDeviceNames().length > 1) {
  625. binding.switchSelfVideoButton.setVisibility(View.VISIBLE);
  626. }
  627. }
  628. if (!isConnectionEstablished()) {
  629. fetchSignalingSettings();
  630. }
  631. } else if (EffortlessPermissions.somePermissionPermanentlyDenied(this, PERMISSIONS_CALL)) {
  632. checkIfSomeAreApproved();
  633. }
  634. }
  635. private void checkIfSomeAreApproved() {
  636. if (!isVoiceOnlyCall) {
  637. if (cameraEnumerator.getDeviceNames().length == 0) {
  638. binding.cameraButton.setVisibility(View.GONE);
  639. }
  640. if (cameraEnumerator.getDeviceNames().length > 1) {
  641. binding.switchSelfVideoButton.setVisibility(View.VISIBLE);
  642. }
  643. if (EffortlessPermissions.hasPermissions(this, PERMISSIONS_CAMERA)) {
  644. if (!videoOn) {
  645. onCameraClick();
  646. }
  647. } else {
  648. binding.cameraButton.getHierarchy().setPlaceholderImage(R.drawable.ic_videocam_off_white_24px);
  649. binding.cameraButton.setAlpha(0.7f);
  650. binding.switchSelfVideoButton.setVisibility(View.GONE);
  651. }
  652. }
  653. if (EffortlessPermissions.hasPermissions(this, PERMISSIONS_MICROPHONE)) {
  654. if (!microphoneOn) {
  655. onMicrophoneClick();
  656. }
  657. } else {
  658. binding.microphoneButton.getHierarchy().setPlaceholderImage(R.drawable.ic_mic_off_white_24px);
  659. }
  660. if (!isConnectionEstablished()) {
  661. fetchSignalingSettings();
  662. }
  663. }
  664. @AfterPermissionDenied(100)
  665. private void onPermissionsDenied() {
  666. if (!isVoiceOnlyCall) {
  667. if (cameraEnumerator.getDeviceNames().length == 0) {
  668. binding.cameraButton.setVisibility(View.GONE);
  669. } else if (cameraEnumerator.getDeviceNames().length == 1) {
  670. binding.switchSelfVideoButton.setVisibility(View.GONE);
  671. }
  672. }
  673. if ((EffortlessPermissions.hasPermissions(this, PERMISSIONS_CAMERA) ||
  674. EffortlessPermissions.hasPermissions(this, PERMISSIONS_MICROPHONE))) {
  675. checkIfSomeAreApproved();
  676. } else if (!isConnectionEstablished()) {
  677. fetchSignalingSettings();
  678. }
  679. }
  680. private void onAudioManagerDevicesChanged(
  681. final WebRtcAudioManager.AudioDevice currentDevice,
  682. final Set<WebRtcAudioManager.AudioDevice> availableDevices) {
  683. Log.d(TAG, "onAudioManagerDevicesChanged: " + availableDevices + ", "
  684. + "currentDevice: " + currentDevice);
  685. final boolean shouldDisableProximityLock = (currentDevice.equals(WebRtcAudioManager.AudioDevice.WIRED_HEADSET)
  686. || currentDevice.equals(WebRtcAudioManager.AudioDevice.SPEAKER_PHONE)
  687. || currentDevice.equals(WebRtcAudioManager.AudioDevice.BLUETOOTH));
  688. if (shouldDisableProximityLock) {
  689. powerManagerUtils.updatePhoneState(PowerManagerUtils.PhoneState.WITHOUT_PROXIMITY_SENSOR_LOCK);
  690. } else {
  691. powerManagerUtils.updatePhoneState(PowerManagerUtils.PhoneState.WITH_PROXIMITY_SENSOR_LOCK);
  692. }
  693. if (audioOutputDialog != null) {
  694. audioOutputDialog.updateOutputDeviceList();
  695. }
  696. updateAudioOutputButton(currentDevice);
  697. }
  698. private void cameraInitialization() {
  699. videoCapturer = createCameraCapturer(cameraEnumerator);
  700. //Create a VideoSource instance
  701. if (videoCapturer != null) {
  702. SurfaceTextureHelper surfaceTextureHelper = SurfaceTextureHelper.create("CaptureThread",
  703. rootEglBase.getEglBaseContext());
  704. videoSource = peerConnectionFactory.createVideoSource(false);
  705. videoCapturer.initialize(surfaceTextureHelper, getApplicationContext(), videoSource.getCapturerObserver());
  706. }
  707. localVideoTrack = peerConnectionFactory.createVideoTrack("NCv0", videoSource);
  708. localStream.addTrack(localVideoTrack);
  709. localVideoTrack.setEnabled(false);
  710. localVideoTrack.addSink(binding.selfVideoRenderer);
  711. }
  712. private void microphoneInitialization() {
  713. //create an AudioSource instance
  714. audioSource = peerConnectionFactory.createAudioSource(audioConstraints);
  715. localAudioTrack = peerConnectionFactory.createAudioTrack("NCa0", audioSource);
  716. localAudioTrack.setEnabled(false);
  717. localStream.addTrack(localAudioTrack);
  718. }
  719. private VideoCapturer createCameraCapturer(CameraEnumerator enumerator) {
  720. final String[] deviceNames = enumerator.getDeviceNames();
  721. // First, try to find front facing camera
  722. Logging.d(TAG, "Looking for front facing cameras.");
  723. for (String deviceName : deviceNames) {
  724. if (enumerator.isFrontFacing(deviceName)) {
  725. Logging.d(TAG, "Creating front facing camera capturer.");
  726. VideoCapturer videoCapturer = enumerator.createCapturer(deviceName, null);
  727. if (videoCapturer != null) {
  728. binding.selfVideoRenderer.setMirror(true);
  729. return videoCapturer;
  730. }
  731. }
  732. }
  733. // Front facing camera not found, try something else
  734. Logging.d(TAG, "Looking for other cameras.");
  735. for (String deviceName : deviceNames) {
  736. if (!enumerator.isFrontFacing(deviceName)) {
  737. Logging.d(TAG, "Creating other camera capturer.");
  738. VideoCapturer videoCapturer = enumerator.createCapturer(deviceName, null);
  739. if (videoCapturer != null) {
  740. binding.selfVideoRenderer.setMirror(false);
  741. return videoCapturer;
  742. }
  743. }
  744. }
  745. return null;
  746. }
  747. public void onMicrophoneClick() {
  748. if (EffortlessPermissions.hasPermissions(this, PERMISSIONS_MICROPHONE)) {
  749. if (!appPreferences.getPushToTalkIntroShown()) {
  750. int primary = viewThemeUtils.getScheme(binding.audioOutputButton.getContext()).getPrimary();
  751. spotlightView = new SpotlightView.Builder(this)
  752. .introAnimationDuration(300)
  753. .enableRevealAnimation(true)
  754. .performClick(false)
  755. .fadeinTextDuration(400)
  756. .headingTvColor(primary)
  757. .headingTvSize(20)
  758. .headingTvText(getResources().getString(R.string.nc_push_to_talk))
  759. .subHeadingTvColor(getResources().getColor(R.color.bg_default))
  760. .subHeadingTvSize(16)
  761. .subHeadingTvText(getResources().getString(R.string.nc_push_to_talk_desc))
  762. .maskColor(Color.parseColor("#dc000000"))
  763. .target(binding.microphoneButton)
  764. .lineAnimDuration(400)
  765. .lineAndArcColor(primary)
  766. .enableDismissAfterShown(true)
  767. .dismissOnBackPress(true)
  768. .usageId("pushToTalk")
  769. .show();
  770. appPreferences.setPushToTalkIntroShown(true);
  771. }
  772. if (!isPTTActive) {
  773. microphoneOn = !microphoneOn;
  774. if (microphoneOn) {
  775. binding.microphoneButton.getHierarchy().setPlaceholderImage(R.drawable.ic_mic_white_24px);
  776. updatePictureInPictureActions(R.drawable.ic_mic_white_24px,
  777. getResources().getString(R.string.nc_pip_microphone_mute),
  778. MICROPHONE_PIP_REQUEST_MUTE);
  779. } else {
  780. binding.microphoneButton.getHierarchy().setPlaceholderImage(R.drawable.ic_mic_off_white_24px);
  781. updatePictureInPictureActions(R.drawable.ic_mic_off_white_24px,
  782. getResources().getString(R.string.nc_pip_microphone_unmute),
  783. MICROPHONE_PIP_REQUEST_UNMUTE);
  784. }
  785. toggleMedia(microphoneOn, false);
  786. } else {
  787. binding.microphoneButton.getHierarchy().setPlaceholderImage(R.drawable.ic_mic_white_24px);
  788. pulseAnimation.start();
  789. toggleMedia(true, false);
  790. }
  791. if (isVoiceOnlyCall && !isConnectionEstablished()) {
  792. fetchSignalingSettings();
  793. }
  794. } else if (EffortlessPermissions.somePermissionPermanentlyDenied(this, PERMISSIONS_MICROPHONE)) {
  795. // Microphone permission is permanently denied so we cannot request it normally.
  796. OpenAppDetailsDialogFragment.show(
  797. R.string.nc_microphone_permission_permanently_denied,
  798. R.string.nc_permissions_settings, (AppCompatActivity) this);
  799. } else {
  800. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  801. requestPermissions(PERMISSIONS_MICROPHONE, 100);
  802. } else {
  803. onRequestPermissionsResult(100, PERMISSIONS_MICROPHONE, new int[]{1});
  804. }
  805. }
  806. }
  807. public void onCameraClick() {
  808. if (EffortlessPermissions.hasPermissions(this, PERMISSIONS_CAMERA)) {
  809. videoOn = !videoOn;
  810. if (videoOn) {
  811. binding.cameraButton.getHierarchy().setPlaceholderImage(R.drawable.ic_videocam_white_24px);
  812. if (cameraEnumerator.getDeviceNames().length > 1) {
  813. binding.switchSelfVideoButton.setVisibility(View.VISIBLE);
  814. }
  815. } else {
  816. binding.cameraButton.getHierarchy().setPlaceholderImage(R.drawable.ic_videocam_off_white_24px);
  817. binding.switchSelfVideoButton.setVisibility(View.GONE);
  818. }
  819. toggleMedia(videoOn, true);
  820. } else if (EffortlessPermissions.somePermissionPermanentlyDenied(this, PERMISSIONS_CAMERA)) {
  821. // Camera permission is permanently denied so we cannot request it normally.
  822. OpenAppDetailsDialogFragment.show(
  823. R.string.nc_camera_permission_permanently_denied,
  824. R.string.nc_permissions_settings, (AppCompatActivity) this);
  825. } else {
  826. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  827. requestPermissions(PERMISSIONS_CAMERA, 100);
  828. } else {
  829. onRequestPermissionsResult(100, PERMISSIONS_CAMERA, new int[]{1});
  830. }
  831. }
  832. }
  833. public void switchCamera() {
  834. CameraVideoCapturer cameraVideoCapturer = (CameraVideoCapturer) videoCapturer;
  835. if (cameraVideoCapturer != null) {
  836. cameraVideoCapturer.switchCamera(new CameraVideoCapturer.CameraSwitchHandler() {
  837. @Override
  838. public void onCameraSwitchDone(boolean currentCameraIsFront) {
  839. binding.selfVideoRenderer.setMirror(currentCameraIsFront);
  840. }
  841. @Override
  842. public void onCameraSwitchError(String s) {
  843. }
  844. });
  845. }
  846. }
  847. private void toggleMedia(boolean enable, boolean video) {
  848. String message;
  849. if (video) {
  850. message = "videoOff";
  851. if (enable) {
  852. binding.cameraButton.setAlpha(1.0f);
  853. message = "videoOn";
  854. startVideoCapture();
  855. } else {
  856. binding.cameraButton.setAlpha(0.7f);
  857. if (videoCapturer != null) {
  858. try {
  859. videoCapturer.stopCapture();
  860. } catch (InterruptedException e) {
  861. Log.d(TAG, "Failed to stop capturing video while sensor is near the ear");
  862. }
  863. }
  864. }
  865. if (localStream != null && localStream.videoTracks.size() > 0) {
  866. localStream.videoTracks.get(0).setEnabled(enable);
  867. }
  868. if (enable) {
  869. binding.selfVideoRenderer.setVisibility(View.VISIBLE);
  870. } else {
  871. binding.selfVideoRenderer.setVisibility(View.INVISIBLE);
  872. }
  873. } else {
  874. message = "audioOff";
  875. if (enable) {
  876. message = "audioOn";
  877. binding.microphoneButton.setAlpha(1.0f);
  878. } else {
  879. binding.microphoneButton.setAlpha(0.7f);
  880. }
  881. if (localStream != null && localStream.audioTracks.size() > 0) {
  882. localStream.audioTracks.get(0).setEnabled(enable);
  883. }
  884. }
  885. if (isConnectionEstablished() && peerConnectionWrapperList != null) {
  886. if (!hasMCU) {
  887. for (PeerConnectionWrapper peerConnectionWrapper : peerConnectionWrapperList) {
  888. peerConnectionWrapper.sendChannelData(new DataChannelMessage(message));
  889. }
  890. } else {
  891. for (PeerConnectionWrapper peerConnectionWrapper : peerConnectionWrapperList) {
  892. if (peerConnectionWrapper.getSessionId().equals(webSocketClient.getSessionId())) {
  893. peerConnectionWrapper.sendChannelData(new DataChannelMessage(message));
  894. break;
  895. }
  896. }
  897. }
  898. }
  899. }
  900. private void animateCallControls(boolean show, long startDelay) {
  901. if (isVoiceOnlyCall) {
  902. if (spotlightView != null && spotlightView.getVisibility() != View.GONE) {
  903. spotlightView.setVisibility(View.GONE);
  904. }
  905. } else if (!isPTTActive) {
  906. float alpha;
  907. long duration;
  908. if (show) {
  909. callControlHandler.removeCallbacksAndMessages(null);
  910. callInfosHandler.removeCallbacksAndMessages(null);
  911. cameraSwitchHandler.removeCallbacksAndMessages(null);
  912. alpha = 1.0f;
  913. duration = 1000;
  914. if (binding.callControls.getVisibility() != View.VISIBLE) {
  915. binding.callControls.setAlpha(0.0f);
  916. binding.callControls.setVisibility(View.VISIBLE);
  917. binding.callInfosLinearLayout.setAlpha(0.0f);
  918. binding.callInfosLinearLayout.setVisibility(View.VISIBLE);
  919. binding.switchSelfVideoButton.setAlpha(0.0f);
  920. if (videoOn) {
  921. binding.switchSelfVideoButton.setVisibility(View.VISIBLE);
  922. }
  923. } else {
  924. callControlHandler.postDelayed(() -> animateCallControls(false, 0), 5000);
  925. return;
  926. }
  927. } else {
  928. alpha = 0.0f;
  929. duration = 1000;
  930. }
  931. binding.callControls.setEnabled(false);
  932. binding.callControls.animate()
  933. .translationY(0)
  934. .alpha(alpha)
  935. .setDuration(duration)
  936. .setStartDelay(startDelay)
  937. .setListener(new AnimatorListenerAdapter() {
  938. @Override
  939. public void onAnimationEnd(Animator animation) {
  940. super.onAnimationEnd(animation);
  941. if (!show) {
  942. binding.callControls.setVisibility(View.GONE);
  943. if (spotlightView != null && spotlightView.getVisibility() != View.GONE) {
  944. spotlightView.setVisibility(View.GONE);
  945. }
  946. } else {
  947. callControlHandler.postDelayed(new Runnable() {
  948. @Override
  949. public void run() {
  950. if (!isPTTActive) {
  951. animateCallControls(false, 0);
  952. }
  953. }
  954. }, 7500);
  955. }
  956. binding.callControls.setEnabled(true);
  957. }
  958. });
  959. binding.callInfosLinearLayout.setEnabled(false);
  960. binding.callInfosLinearLayout.animate()
  961. .translationY(0)
  962. .alpha(alpha)
  963. .setDuration(duration)
  964. .setStartDelay(startDelay)
  965. .setListener(new AnimatorListenerAdapter() {
  966. @Override
  967. public void onAnimationEnd(Animator animation) {
  968. super.onAnimationEnd(animation);
  969. if (!show) {
  970. binding.callInfosLinearLayout.setVisibility(View.GONE);
  971. } else {
  972. callInfosHandler.postDelayed(new Runnable() {
  973. @Override
  974. public void run() {
  975. if (!isPTTActive) {
  976. animateCallControls(false, 0);
  977. }
  978. }
  979. }, 7500);
  980. }
  981. binding.callInfosLinearLayout.setEnabled(true);
  982. }
  983. });
  984. binding.switchSelfVideoButton.setEnabled(false);
  985. binding.switchSelfVideoButton.animate()
  986. .translationY(0)
  987. .alpha(alpha)
  988. .setDuration(duration)
  989. .setStartDelay(startDelay)
  990. .setListener(new AnimatorListenerAdapter() {
  991. @Override
  992. public void onAnimationEnd(Animator animation) {
  993. super.onAnimationEnd(animation);
  994. if (!show) {
  995. binding.switchSelfVideoButton.setVisibility(View.GONE);
  996. }
  997. binding.switchSelfVideoButton.setEnabled(true);
  998. }
  999. });
  1000. }
  1001. }
  1002. @Override
  1003. public void onDestroy() {
  1004. if (!currentCallStatus.equals(CallStatus.LEAVING)) {
  1005. setCallState(CallStatus.LEAVING);
  1006. hangup(true);
  1007. }
  1008. powerManagerUtils.updatePhoneState(PowerManagerUtils.PhoneState.IDLE);
  1009. super.onDestroy();
  1010. }
  1011. private void fetchSignalingSettings() {
  1012. Log.d(TAG, "fetchSignalingSettings");
  1013. int apiVersion = ApiUtils.getSignalingApiVersion(conversationUser, new int[]{ApiUtils.APIv3, 2, 1});
  1014. ncApi.getSignalingSettings(credentials, ApiUtils.getUrlForSignalingSettings(apiVersion, baseUrl))
  1015. .subscribeOn(Schedulers.io())
  1016. .retry(3)
  1017. .observeOn(AndroidSchedulers.mainThread())
  1018. .subscribe(new Observer<SignalingSettingsOverall>() {
  1019. @Override
  1020. public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
  1021. // unused atm
  1022. }
  1023. @Override
  1024. public void onNext(@io.reactivex.annotations.NonNull SignalingSettingsOverall signalingSettingsOverall) {
  1025. if (signalingSettingsOverall.getOcs() != null
  1026. && signalingSettingsOverall.getOcs().getSettings() != null) {
  1027. externalSignalingServer = new ExternalSignalingServer();
  1028. if (!TextUtils.isEmpty(
  1029. signalingSettingsOverall.getOcs().getSettings().getExternalSignalingServer()) &&
  1030. !TextUtils.isEmpty(
  1031. signalingSettingsOverall.getOcs().getSettings().getExternalSignalingTicket())) {
  1032. externalSignalingServer = new ExternalSignalingServer();
  1033. externalSignalingServer.setExternalSignalingServer(
  1034. signalingSettingsOverall.getOcs().getSettings().getExternalSignalingServer());
  1035. externalSignalingServer.setExternalSignalingTicket(
  1036. signalingSettingsOverall.getOcs().getSettings().getExternalSignalingTicket());
  1037. hasExternalSignalingServer = true;
  1038. } else {
  1039. hasExternalSignalingServer = false;
  1040. }
  1041. Log.d(TAG, " hasExternalSignalingServer: " + hasExternalSignalingServer);
  1042. if (!"?".equals(conversationUser.getUserId()) && conversationUser.getId() != null) {
  1043. Log.d(TAG, "Update externalSignalingServer for: " + conversationUser.getId() +
  1044. " / " + conversationUser.getUserId());
  1045. userManager.updateExternalSignalingServer(conversationUser.getId(), externalSignalingServer)
  1046. .subscribeOn(Schedulers.io())
  1047. .subscribe();
  1048. } else {
  1049. conversationUser.setExternalSignalingServer(externalSignalingServer);
  1050. }
  1051. if (signalingSettingsOverall.getOcs().getSettings().getStunServers() != null) {
  1052. List<IceServer> stunServers =
  1053. signalingSettingsOverall.getOcs().getSettings().getStunServers();
  1054. if (apiVersion == ApiUtils.APIv3) {
  1055. for (IceServer stunServer : stunServers) {
  1056. if (stunServer.getUrls() != null) {
  1057. for (String url : stunServer.getUrls()) {
  1058. Log.d(TAG, " STUN server url: " + url);
  1059. iceServers.add(new PeerConnection.IceServer(url));
  1060. }
  1061. }
  1062. }
  1063. } else {
  1064. if (signalingSettingsOverall.getOcs().getSettings().getStunServers() != null) {
  1065. for (IceServer stunServer : stunServers) {
  1066. Log.d(TAG, " STUN server url: " + stunServer.getUrl());
  1067. iceServers.add(new PeerConnection.IceServer(stunServer.getUrl()));
  1068. }
  1069. }
  1070. }
  1071. }
  1072. if (signalingSettingsOverall.getOcs().getSettings().getTurnServers() != null) {
  1073. List<IceServer> turnServers =
  1074. signalingSettingsOverall.getOcs().getSettings().getTurnServers();
  1075. for (IceServer turnServer : turnServers) {
  1076. if (turnServer.getUrls() != null) {
  1077. for (String url : turnServer.getUrls()) {
  1078. Log.d(TAG, " TURN server url: " + url);
  1079. iceServers.add(new PeerConnection.IceServer(
  1080. url, turnServer.getUsername(), turnServer.getCredential()
  1081. ));
  1082. }
  1083. }
  1084. }
  1085. }
  1086. }
  1087. checkCapabilities();
  1088. }
  1089. @Override
  1090. public void onError(@io.reactivex.annotations.NonNull Throwable e) {
  1091. Log.e(TAG, e.getMessage(), e);
  1092. }
  1093. @Override
  1094. public void onComplete() {
  1095. // unused atm
  1096. }
  1097. });
  1098. }
  1099. private void checkCapabilities() {
  1100. ncApi.getCapabilities(credentials, ApiUtils.getUrlForCapabilities(baseUrl))
  1101. .retry(3)
  1102. .subscribeOn(Schedulers.io())
  1103. .observeOn(AndroidSchedulers.mainThread())
  1104. .subscribe(new Observer<CapabilitiesOverall>() {
  1105. @Override
  1106. public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
  1107. // unused atm
  1108. }
  1109. @Override
  1110. public void onNext(@io.reactivex.annotations.NonNull CapabilitiesOverall capabilitiesOverall) {
  1111. // FIXME check for compatible Call API version
  1112. if (hasExternalSignalingServer) {
  1113. setupAndInitiateWebSocketsConnection();
  1114. } else {
  1115. joinRoomAndCall();
  1116. }
  1117. }
  1118. @Override
  1119. public void onError(@io.reactivex.annotations.NonNull Throwable e) {
  1120. // unused atm
  1121. }
  1122. @Override
  1123. public void onComplete() {
  1124. // unused atm
  1125. }
  1126. });
  1127. }
  1128. private void joinRoomAndCall() {
  1129. callSession = ApplicationWideCurrentRoomHolder.getInstance().getSession();
  1130. int apiVersion = ApiUtils.getConversationApiVersion(conversationUser, new int[]{ApiUtils.APIv4, 1});
  1131. Log.d(TAG, "joinRoomAndCall");
  1132. Log.d(TAG, " baseUrl= " + baseUrl);
  1133. Log.d(TAG, " roomToken= " + roomToken);
  1134. Log.d(TAG, " callSession= " + callSession);
  1135. String url = ApiUtils.getUrlForParticipantsActive(apiVersion, baseUrl, roomToken);
  1136. Log.d(TAG, " url= " + url);
  1137. if (TextUtils.isEmpty(callSession)) {
  1138. ncApi.joinRoom(credentials, url, conversationPassword)
  1139. .subscribeOn(Schedulers.io())
  1140. .observeOn(AndroidSchedulers.mainThread())
  1141. .retry(3)
  1142. .subscribe(new Observer<RoomOverall>() {
  1143. @Override
  1144. public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
  1145. // unused atm
  1146. }
  1147. @Override
  1148. public void onNext(@io.reactivex.annotations.NonNull RoomOverall roomOverall) {
  1149. callSession = roomOverall.getOcs().getData().getSessionId();
  1150. Log.d(TAG, " new callSession by joinRoom= " + callSession);
  1151. ApplicationWideCurrentRoomHolder.getInstance().setSession(callSession);
  1152. ApplicationWideCurrentRoomHolder.getInstance().setCurrentRoomId(roomId);
  1153. ApplicationWideCurrentRoomHolder.getInstance().setCurrentRoomToken(roomToken);
  1154. ApplicationWideCurrentRoomHolder.getInstance().setUserInRoom(conversationUser);
  1155. callOrJoinRoomViaWebSocket();
  1156. }
  1157. @Override
  1158. public void onError(@io.reactivex.annotations.NonNull Throwable e) {
  1159. Log.e(TAG, "joinRoom onError", e);
  1160. }
  1161. @Override
  1162. public void onComplete() {
  1163. Log.d(TAG, "joinRoom onComplete");
  1164. }
  1165. });
  1166. } else {
  1167. // we are in a room and start a call -> same session needs to be used
  1168. callOrJoinRoomViaWebSocket();
  1169. }
  1170. }
  1171. private void callOrJoinRoomViaWebSocket() {
  1172. if (hasExternalSignalingServer) {
  1173. webSocketClient.joinRoomWithRoomTokenAndSession(roomToken, callSession);
  1174. } else {
  1175. performCall();
  1176. }
  1177. }
  1178. private void performCall() {
  1179. int inCallFlag;
  1180. if (isVoiceOnlyCall) {
  1181. inCallFlag = Participant.InCallFlags.IN_CALL + Participant.InCallFlags.WITH_AUDIO;
  1182. } else {
  1183. inCallFlag =
  1184. Participant.InCallFlags.IN_CALL + Participant.InCallFlags.WITH_AUDIO + Participant.InCallFlags.WITH_VIDEO;
  1185. }
  1186. int apiVersion = ApiUtils.getCallApiVersion(conversationUser, new int[]{ApiUtils.APIv4, 1});
  1187. ncApi.joinCall(
  1188. credentials,
  1189. ApiUtils.getUrlForCall(apiVersion, baseUrl, roomToken),
  1190. inCallFlag,
  1191. isCallWithoutNotification)
  1192. .subscribeOn(Schedulers.io())
  1193. .retry(3)
  1194. .observeOn(AndroidSchedulers.mainThread())
  1195. .subscribe(new Observer<GenericOverall>() {
  1196. @Override
  1197. public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
  1198. // unused atm
  1199. }
  1200. @Override
  1201. public void onNext(@io.reactivex.annotations.NonNull GenericOverall genericOverall) {
  1202. if (!currentCallStatus.equals(CallStatus.LEAVING)) {
  1203. setCallState(CallStatus.JOINED);
  1204. ApplicationWideCurrentRoomHolder.getInstance().setInCall(true);
  1205. ApplicationWideCurrentRoomHolder.getInstance().setDialing(false);
  1206. if (!TextUtils.isEmpty(roomToken)) {
  1207. NotificationUtils.INSTANCE.cancelExistingNotificationsForRoom(getApplicationContext(),
  1208. conversationUser,
  1209. roomToken);
  1210. }
  1211. if (!hasExternalSignalingServer) {
  1212. int apiVersion = ApiUtils.getSignalingApiVersion(conversationUser,
  1213. new int[]{ApiUtils.APIv3, 2, 1});
  1214. ncApi.pullSignalingMessages(credentials,
  1215. ApiUtils.getUrlForSignaling(apiVersion,
  1216. baseUrl,
  1217. roomToken))
  1218. .subscribeOn(Schedulers.io())
  1219. .observeOn(AndroidSchedulers.mainThread())
  1220. .repeatWhen(observable -> observable)
  1221. .takeWhile(observable -> isConnectionEstablished())
  1222. .retry(3, observable -> isConnectionEstablished())
  1223. .subscribe(new Observer<SignalingOverall>() {
  1224. @Override
  1225. public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
  1226. signalingDisposable = d;
  1227. }
  1228. @Override
  1229. public void onNext(
  1230. @io.reactivex.annotations.NonNull
  1231. SignalingOverall signalingOverall) {
  1232. receivedSignalingMessages(signalingOverall.getOcs().getSignalings());
  1233. }
  1234. @Override
  1235. public void onError(@io.reactivex.annotations.NonNull Throwable e) {
  1236. dispose(signalingDisposable);
  1237. }
  1238. @Override
  1239. public void onComplete() {
  1240. dispose(signalingDisposable);
  1241. }
  1242. });
  1243. }
  1244. }
  1245. }
  1246. @Override
  1247. public void onError(@io.reactivex.annotations.NonNull Throwable e) {
  1248. // unused atm
  1249. }
  1250. @Override
  1251. public void onComplete() {
  1252. // unused atm
  1253. }
  1254. });
  1255. }
  1256. private void setupAndInitiateWebSocketsConnection() {
  1257. if (webSocketConnectionHelper == null) {
  1258. webSocketConnectionHelper = new WebSocketConnectionHelper();
  1259. }
  1260. if (webSocketClient == null) {
  1261. webSocketClient = WebSocketConnectionHelper.getExternalSignalingInstanceForServer(
  1262. externalSignalingServer.getExternalSignalingServer(),
  1263. conversationUser, externalSignalingServer.getExternalSignalingTicket(),
  1264. TextUtils.isEmpty(credentials));
  1265. } else {
  1266. if (webSocketClient.isConnected() && currentCallStatus.equals(CallStatus.PUBLISHER_FAILED)) {
  1267. webSocketClient.restartWebSocket();
  1268. }
  1269. }
  1270. joinRoomAndCall();
  1271. }
  1272. private void initiateCall() {
  1273. if (!TextUtils.isEmpty(roomToken)) {
  1274. checkPermissions();
  1275. } else {
  1276. handleFromNotification();
  1277. }
  1278. }
  1279. @Subscribe(threadMode = ThreadMode.BACKGROUND)
  1280. public void onMessageEvent(WebSocketCommunicationEvent webSocketCommunicationEvent) {
  1281. switch (webSocketCommunicationEvent.getType()) {
  1282. case "hello":
  1283. Log.d(TAG, "onMessageEvent 'hello'");
  1284. if (!webSocketCommunicationEvent.getHashMap().containsKey("oldResumeId")) {
  1285. if (currentCallStatus.equals(CallStatus.RECONNECTING)) {
  1286. hangup(false);
  1287. } else {
  1288. initiateCall();
  1289. }
  1290. }
  1291. break;
  1292. case "roomJoined":
  1293. Log.d(TAG, "onMessageEvent 'roomJoined'");
  1294. startSendingNick();
  1295. if (webSocketCommunicationEvent.getHashMap().get("roomToken").equals(roomToken)) {
  1296. performCall();
  1297. }
  1298. break;
  1299. case PARTICIPANTS_UPDATE:
  1300. Log.d(TAG, "onMessageEvent 'participantsUpdate'");
  1301. // See MagicWebSocketInstance#onMessage in case "participants" how the 'updateParameters' are created
  1302. Map<String, String> updateParameters = webSocketCommunicationEvent.getHashMap();
  1303. if (updateParameters == null) {
  1304. break;
  1305. }
  1306. String updateRoomToken = updateParameters.get(ROOM_TOKEN);
  1307. String updateAll = updateParameters.get(UPDATE_ALL);
  1308. String updateInCall = updateParameters.get(UPDATE_IN_CALL);
  1309. String jobId = updateParameters.get(JOB_ID);
  1310. if (roomToken.equals(updateRoomToken)) {
  1311. if (updateAll != null && Boolean.parseBoolean(updateAll)) {
  1312. if ("0".equals(updateInCall)) {
  1313. Log.d(TAG, "Most probably a moderator ended the call for all.");
  1314. hangup(true);
  1315. }
  1316. } else if (jobId != null) {
  1317. // In that case a list of users for the room is passed.
  1318. processUsersInRoom(
  1319. (List<HashMap<String, Object>>) webSocketClient
  1320. .getJobWithId(
  1321. Integer.valueOf(jobId)));
  1322. }
  1323. }
  1324. break;
  1325. case "signalingMessage":
  1326. Log.d(TAG, "onMessageEvent 'signalingMessage'");
  1327. processMessage((NCSignalingMessage) webSocketClient.getJobWithId(
  1328. Integer.valueOf(webSocketCommunicationEvent.getHashMap().get("jobId"))));
  1329. break;
  1330. case "peerReadyForRequestingOffer":
  1331. Log.d(TAG, "onMessageEvent 'peerReadyForRequestingOffer'");
  1332. webSocketClient.requestOfferForSessionIdWithType(
  1333. webSocketCommunicationEvent.getHashMap().get("sessionId"), "video");
  1334. break;
  1335. }
  1336. }
  1337. private void dispose(@Nullable Disposable disposable) {
  1338. if (disposable != null && !disposable.isDisposed()) {
  1339. disposable.dispose();
  1340. } else if (disposable == null) {
  1341. if (signalingDisposable != null && !signalingDisposable.isDisposed()) {
  1342. signalingDisposable.dispose();
  1343. signalingDisposable = null;
  1344. }
  1345. }
  1346. }
  1347. private void receivedSignalingMessages(@Nullable List<Signaling> signalingList) {
  1348. if (signalingList != null) {
  1349. for (Signaling signaling : signalingList) {
  1350. try {
  1351. receivedSignalingMessage(signaling);
  1352. } catch (IOException e) {
  1353. Log.e(TAG, "Failed to process received signaling message", e);
  1354. }
  1355. }
  1356. }
  1357. }
  1358. private void receivedSignalingMessage(Signaling signaling) throws IOException {
  1359. String messageType = signaling.getType();
  1360. if (!isConnectionEstablished() && !currentCallStatus.equals(CallStatus.CONNECTING)) {
  1361. return;
  1362. }
  1363. if ("usersInRoom".equals(messageType)) {
  1364. processUsersInRoom((List<HashMap<String, Object>>) signaling.getMessageWrapper());
  1365. } else if ("message".equals(messageType)) {
  1366. NCSignalingMessage ncSignalingMessage = LoganSquare.parse(signaling.getMessageWrapper().toString(),
  1367. NCSignalingMessage.class);
  1368. processMessage(ncSignalingMessage);
  1369. } else {
  1370. Log.e(TAG, "unexpected message type when receiving signaling message");
  1371. }
  1372. }
  1373. private void processMessage(NCSignalingMessage ncSignalingMessage) {
  1374. if (ncSignalingMessage.getRoomType().equals("video") || ncSignalingMessage.getRoomType().equals("screen")) {
  1375. String type = null;
  1376. if (ncSignalingMessage.getPayload() != null && ncSignalingMessage.getPayload().getType() != null) {
  1377. type = ncSignalingMessage.getPayload().getType();
  1378. } else if (ncSignalingMessage.getType() != null) {
  1379. type = ncSignalingMessage.getType();
  1380. }
  1381. PeerConnectionWrapper peerConnectionWrapper = null;
  1382. if ("offer".equals(type)) {
  1383. peerConnectionWrapper =
  1384. getOrCreatePeerConnectionWrapperForSessionIdAndType(ncSignalingMessage.getFrom(),
  1385. ncSignalingMessage.getRoomType(), false);
  1386. } else {
  1387. peerConnectionWrapper =
  1388. getPeerConnectionWrapperForSessionIdAndType(ncSignalingMessage.getFrom(),
  1389. ncSignalingMessage.getRoomType());
  1390. }
  1391. if ("unshareScreen".equals(type) ||
  1392. (("offer".equals(type) ||
  1393. "answer".equals(type) ||
  1394. "candidate".equals(type) ||
  1395. "endOfCandidates".equals(type)) &&
  1396. peerConnectionWrapper != null)) {
  1397. switch (type) {
  1398. case "unshareScreen":
  1399. endPeerConnection(ncSignalingMessage.getFrom(), true);
  1400. break;
  1401. case "offer":
  1402. case "answer":
  1403. peerConnectionWrapper.setNick(ncSignalingMessage.getPayload().getNick());
  1404. SessionDescription sessionDescriptionWithPreferredCodec;
  1405. String sessionDescriptionStringWithPreferredCodec = MagicWebRTCUtils.preferCodec
  1406. (ncSignalingMessage.getPayload().getSdp(),
  1407. "H264", false);
  1408. sessionDescriptionWithPreferredCodec = new SessionDescription(
  1409. SessionDescription.Type.fromCanonicalForm(type),
  1410. sessionDescriptionStringWithPreferredCodec);
  1411. if (peerConnectionWrapper.getPeerConnection() != null) {
  1412. peerConnectionWrapper.getPeerConnection().setRemoteDescription(
  1413. peerConnectionWrapper.getMagicSdpObserver(),
  1414. sessionDescriptionWithPreferredCodec);
  1415. }
  1416. break;
  1417. case "candidate":
  1418. NCIceCandidate ncIceCandidate = ncSignalingMessage.getPayload().getIceCandidate();
  1419. IceCandidate iceCandidate = new IceCandidate(ncIceCandidate.getSdpMid(),
  1420. ncIceCandidate.getSdpMLineIndex(),
  1421. ncIceCandidate.getCandidate());
  1422. peerConnectionWrapper.addCandidate(iceCandidate);
  1423. break;
  1424. case "endOfCandidates":
  1425. peerConnectionWrapper.drainIceCandidates();
  1426. break;
  1427. default:
  1428. break;
  1429. }
  1430. }
  1431. } else {
  1432. Log.e(TAG, "unexpected RoomType while processing NCSignalingMessage");
  1433. }
  1434. }
  1435. private void hangup(boolean shutDownView) {
  1436. Log.d(TAG, "hangup! shutDownView=" + shutDownView);
  1437. stopCallingSound();
  1438. dispose(null);
  1439. if (shutDownView) {
  1440. if (videoCapturer != null) {
  1441. try {
  1442. videoCapturer.stopCapture();
  1443. } catch (InterruptedException e) {
  1444. Log.e(TAG, "Failed to stop capturing while hanging up");
  1445. }
  1446. videoCapturer.dispose();
  1447. videoCapturer = null;
  1448. }
  1449. binding.selfVideoRenderer.release();
  1450. if (audioSource != null) {
  1451. audioSource.dispose();
  1452. audioSource = null;
  1453. }
  1454. runOnUiThread(() -> {
  1455. if (audioManager != null) {
  1456. audioManager.stop();
  1457. audioManager = null;
  1458. }
  1459. });
  1460. if (videoSource != null) {
  1461. videoSource = null;
  1462. }
  1463. if (peerConnectionFactory != null) {
  1464. peerConnectionFactory = null;
  1465. }
  1466. localAudioTrack = null;
  1467. localVideoTrack = null;
  1468. if (TextUtils.isEmpty(credentials) && hasExternalSignalingServer) {
  1469. WebSocketConnectionHelper.deleteExternalSignalingInstanceForUserEntity(-1);
  1470. }
  1471. }
  1472. for (PeerConnectionWrapper wrapper : peerConnectionWrapperList) {
  1473. endPeerConnection(wrapper.getSessionId(), false);
  1474. }
  1475. if (localStream != null) {
  1476. localStream.dispose();
  1477. localStream = null;
  1478. Log.d(TAG, "Disposed localStream");
  1479. } else {
  1480. Log.d(TAG, "localStream is null");
  1481. }
  1482. hangupNetworkCalls(shutDownView);
  1483. ApplicationWideCurrentRoomHolder.getInstance().setInCall(false);
  1484. }
  1485. private void hangupNetworkCalls(boolean shutDownView) {
  1486. Log.d(TAG, "hangupNetworkCalls. shutDownView=" + shutDownView);
  1487. int apiVersion = ApiUtils.getCallApiVersion(conversationUser, new int[]{ApiUtils.APIv4, 1});
  1488. ncApi.leaveCall(credentials, ApiUtils.getUrlForCall(apiVersion, baseUrl, roomToken))
  1489. .subscribeOn(Schedulers.io())
  1490. .observeOn(AndroidSchedulers.mainThread())
  1491. .subscribe(new Observer<GenericOverall>() {
  1492. @Override
  1493. public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
  1494. // unused atm
  1495. }
  1496. @Override
  1497. public void onNext(@io.reactivex.annotations.NonNull GenericOverall genericOverall) {
  1498. if (shutDownView) {
  1499. finish();
  1500. } else if (currentCallStatus == CallStatus.RECONNECTING
  1501. || currentCallStatus == CallStatus.PUBLISHER_FAILED) {
  1502. initiateCall();
  1503. }
  1504. }
  1505. @Override
  1506. public void onError(@io.reactivex.annotations.NonNull Throwable e) {
  1507. // unused atm
  1508. }
  1509. @Override
  1510. public void onComplete() {
  1511. // unused atm
  1512. }
  1513. });
  1514. }
  1515. private void startVideoCapture() {
  1516. if (videoCapturer != null) {
  1517. videoCapturer.startCapture(1280, 720, 30);
  1518. }
  1519. }
  1520. private void processUsersInRoom(List<HashMap<String, Object>> users) {
  1521. Log.d(TAG, "processUsersInRoom");
  1522. List<String> newSessions = new ArrayList<>();
  1523. Set<String> oldSessions = new HashSet<>();
  1524. hasMCU = hasExternalSignalingServer && webSocketClient != null && webSocketClient.hasMCU();
  1525. Log.d(TAG, " hasMCU is " + hasMCU);
  1526. // The signaling session is the same as the Nextcloud session only when the MCU is not used.
  1527. String currentSessionId = callSession;
  1528. if (hasMCU) {
  1529. currentSessionId = webSocketClient.getSessionId();
  1530. }
  1531. Log.d(TAG, " currentSessionId is " + currentSessionId);
  1532. for (HashMap<String, Object> participant : users) {
  1533. long inCallFlag = (long) participant.get("inCall");
  1534. if (!participant.get("sessionId").equals(currentSessionId)) {
  1535. boolean isNewSession;
  1536. Log.d(TAG, " inCallFlag of participant "
  1537. + participant.get("sessionId").toString().substring(0, 4)
  1538. + " : "
  1539. + inCallFlag);
  1540. isNewSession = inCallFlag != 0;
  1541. if (isNewSession) {
  1542. newSessions.add(participant.get("sessionId").toString());
  1543. } else {
  1544. oldSessions.add(participant.get("sessionId").toString());
  1545. }
  1546. } else {
  1547. Log.d(TAG, " inCallFlag of currentSessionId: " + inCallFlag);
  1548. if (inCallFlag == 0) {
  1549. Log.d(TAG, "Most probably a moderator ended the call for all.");
  1550. hangup(true);
  1551. }
  1552. }
  1553. }
  1554. for (PeerConnectionWrapper peerConnectionWrapper : peerConnectionWrapperList) {
  1555. if (!peerConnectionWrapper.isMCUPublisher()) {
  1556. oldSessions.add(peerConnectionWrapper.getSessionId());
  1557. }
  1558. }
  1559. // Calculate sessions that left the call
  1560. oldSessions.removeAll(newSessions);
  1561. // Calculate sessions that join the call
  1562. newSessions.removeAll(oldSessions);
  1563. if (!isConnectionEstablished() && !currentCallStatus.equals(CallStatus.CONNECTING)) {
  1564. return;
  1565. }
  1566. if (newSessions.size() > 0 && !hasMCU) {
  1567. getPeersForCall();
  1568. }
  1569. if (hasMCU) {
  1570. // Ensure that own publishing peer is set up.
  1571. getOrCreatePeerConnectionWrapperForSessionIdAndType(webSocketClient.getSessionId(), VIDEO_STREAM_TYPE_VIDEO, true);
  1572. }
  1573. for (String sessionId : newSessions) {
  1574. Log.d(TAG, " newSession joined: " + sessionId);
  1575. getOrCreatePeerConnectionWrapperForSessionIdAndType(sessionId, VIDEO_STREAM_TYPE_VIDEO, false);
  1576. }
  1577. if (newSessions.size() > 0 && !currentCallStatus.equals(CallStatus.IN_CONVERSATION)) {
  1578. setCallState(CallStatus.IN_CONVERSATION);
  1579. }
  1580. for (String sessionId : oldSessions) {
  1581. Log.d(TAG, " oldSession that will be removed is: " + sessionId);
  1582. endPeerConnection(sessionId, false);
  1583. }
  1584. }
  1585. private void getPeersForCall() {
  1586. Log.d(TAG, "getPeersForCall");
  1587. int apiVersion = ApiUtils.getCallApiVersion(conversationUser, new int[]{ApiUtils.APIv4, 1});
  1588. ncApi.getPeersForCall(
  1589. credentials,
  1590. ApiUtils.getUrlForCall(
  1591. apiVersion,
  1592. baseUrl,
  1593. roomToken))
  1594. .subscribeOn(Schedulers.io())
  1595. .subscribe(new Observer<ParticipantsOverall>() {
  1596. @Override
  1597. public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
  1598. // unused atm
  1599. }
  1600. @Override
  1601. public void onNext(@io.reactivex.annotations.NonNull ParticipantsOverall participantsOverall) {
  1602. participantMap = new HashMap<>();
  1603. for (Participant participant : participantsOverall.getOcs().getData()) {
  1604. participantMap.put(participant.getSessionId(), participant);
  1605. }
  1606. }
  1607. @Override
  1608. public void onError(@io.reactivex.annotations.NonNull Throwable e) {
  1609. Log.e(TAG, "error while executing getPeersForCall", e);
  1610. }
  1611. @Override
  1612. public void onComplete() {
  1613. // unused atm
  1614. }
  1615. });
  1616. }
  1617. private void deletePeerConnection(PeerConnectionWrapper peerConnectionWrapper) {
  1618. peerConnectionWrapper.removePeerConnection();
  1619. peerConnectionWrapperList.remove(peerConnectionWrapper);
  1620. }
  1621. private PeerConnectionWrapper getPeerConnectionWrapperForSessionIdAndType(String sessionId, String type) {
  1622. for (PeerConnectionWrapper wrapper : peerConnectionWrapperList) {
  1623. if (wrapper.getSessionId().equals(sessionId)
  1624. && wrapper.getVideoStreamType().equals(type)) {
  1625. return wrapper;
  1626. }
  1627. }
  1628. return null;
  1629. }
  1630. private PeerConnectionWrapper getOrCreatePeerConnectionWrapperForSessionIdAndType(String sessionId,
  1631. String type,
  1632. boolean publisher) {
  1633. PeerConnectionWrapper peerConnectionWrapper;
  1634. if ((peerConnectionWrapper = getPeerConnectionWrapperForSessionIdAndType(sessionId, type)) != null) {
  1635. return peerConnectionWrapper;
  1636. } else {
  1637. if (peerConnectionFactory == null) {
  1638. Log.e(TAG, "peerConnectionFactory was null in getOrCreatePeerConnectionWrapperForSessionIdAndType.");
  1639. Toast.makeText(context, context.getResources().getString(R.string.nc_common_error_sorry),
  1640. Toast.LENGTH_LONG).show();
  1641. hangup(true);
  1642. return null;
  1643. }
  1644. if (hasMCU && publisher) {
  1645. peerConnectionWrapper = new PeerConnectionWrapper(peerConnectionFactory,
  1646. iceServers,
  1647. sdpConstraintsForMCU,
  1648. sessionId,
  1649. callSession,
  1650. localStream,
  1651. true,
  1652. true,
  1653. type);
  1654. } else if (hasMCU) {
  1655. peerConnectionWrapper = new PeerConnectionWrapper(peerConnectionFactory,
  1656. iceServers,
  1657. sdpConstraints,
  1658. sessionId,
  1659. callSession,
  1660. null,
  1661. false,
  1662. true,
  1663. type);
  1664. } else {
  1665. if (!"screen".equals(type)) {
  1666. peerConnectionWrapper = new PeerConnectionWrapper(peerConnectionFactory,
  1667. iceServers,
  1668. sdpConstraints,
  1669. sessionId,
  1670. callSession,
  1671. localStream,
  1672. false,
  1673. false,
  1674. type);
  1675. } else {
  1676. peerConnectionWrapper = new PeerConnectionWrapper(peerConnectionFactory,
  1677. iceServers,
  1678. sdpConstraints,
  1679. sessionId,
  1680. callSession,
  1681. null,
  1682. false,
  1683. false,
  1684. type);
  1685. }
  1686. }
  1687. peerConnectionWrapperList.add(peerConnectionWrapper);
  1688. if (publisher) {
  1689. startSendingNick();
  1690. }
  1691. return peerConnectionWrapper;
  1692. }
  1693. }
  1694. private List<PeerConnectionWrapper> getPeerConnectionWrapperListForSessionId(String sessionId) {
  1695. List<PeerConnectionWrapper> internalList = new ArrayList<>();
  1696. for (PeerConnectionWrapper peerConnectionWrapper : peerConnectionWrapperList) {
  1697. if (peerConnectionWrapper.getSessionId().equals(sessionId)) {
  1698. internalList.add(peerConnectionWrapper);
  1699. }
  1700. }
  1701. return internalList;
  1702. }
  1703. private void endPeerConnection(String sessionId, boolean justScreen) {
  1704. List<PeerConnectionWrapper> peerConnectionWrappers;
  1705. if (!(peerConnectionWrappers = getPeerConnectionWrapperListForSessionId(sessionId)).isEmpty()) {
  1706. for (PeerConnectionWrapper peerConnectionWrapper : peerConnectionWrappers) {
  1707. if (peerConnectionWrapper.getSessionId().equals(sessionId)) {
  1708. if (VIDEO_STREAM_TYPE_SCREEN.equals(peerConnectionWrapper.getVideoStreamType()) || !justScreen) {
  1709. runOnUiThread(() -> removeMediaStream(sessionId));
  1710. deletePeerConnection(peerConnectionWrapper);
  1711. }
  1712. }
  1713. }
  1714. }
  1715. }
  1716. private void removeMediaStream(String sessionId) {
  1717. Log.d(TAG, "removeMediaStream");
  1718. participantDisplayItems.remove(sessionId);
  1719. if (!isDestroyed()) {
  1720. initGridAdapter();
  1721. }
  1722. }
  1723. @Subscribe(threadMode = ThreadMode.MAIN)
  1724. public void onMessageEvent(ConfigurationChangeEvent configurationChangeEvent) {
  1725. powerManagerUtils.setOrientation(Objects.requireNonNull(getResources()).getConfiguration().orientation);
  1726. initGridAdapter();
  1727. updateSelfVideoViewPosition();
  1728. }
  1729. private void updateSelfVideoViewPosition() {
  1730. Log.d(TAG, "updateSelfVideoViewPosition");
  1731. if (!isInPipMode) {
  1732. FrameLayout.LayoutParams layoutParams =
  1733. (FrameLayout.LayoutParams) binding.selfVideoRenderer.getLayoutParams();
  1734. DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
  1735. int screenWidthPx = displayMetrics.widthPixels;
  1736. int screenWidthDp = (int) DisplayUtils.convertPixelToDp(screenWidthPx, getApplicationContext());
  1737. float newXafterRotate = 0;
  1738. float newYafterRotate;
  1739. if (binding.callInfosLinearLayout.getVisibility() == View.VISIBLE) {
  1740. newYafterRotate = 250;
  1741. } else {
  1742. newYafterRotate = 20;
  1743. }
  1744. if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
  1745. layoutParams.height = (int) getResources().getDimension(R.dimen.large_preview_dimension);
  1746. layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT;
  1747. newXafterRotate = (float) (screenWidthDp - getResources().getDimension(R.dimen.large_preview_dimension) * 0.8);
  1748. } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
  1749. layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT;
  1750. layoutParams.width = (int) getResources().getDimension(R.dimen.large_preview_dimension);
  1751. newXafterRotate = (float) (screenWidthDp - getResources().getDimension(R.dimen.large_preview_dimension) * 0.5);
  1752. }
  1753. binding.selfVideoRenderer.setLayoutParams(layoutParams);
  1754. int newXafterRotatePx = (int) DisplayUtils.convertDpToPixel(newXafterRotate, getApplicationContext());
  1755. binding.selfVideoViewWrapper.setY(newYafterRotate);
  1756. binding.selfVideoViewWrapper.setX(newXafterRotatePx);
  1757. }
  1758. }
  1759. @Subscribe(threadMode = ThreadMode.MAIN)
  1760. public void onMessageEvent(PeerConnectionEvent peerConnectionEvent) {
  1761. String sessionId = peerConnectionEvent.getSessionId();
  1762. if (peerConnectionEvent.getPeerConnectionEventType() ==
  1763. PeerConnectionEvent.PeerConnectionEventType.PEER_CLOSED) {
  1764. endPeerConnection(sessionId, VIDEO_STREAM_TYPE_SCREEN.equals(peerConnectionEvent.getVideoStreamType()));
  1765. } else if (peerConnectionEvent.getPeerConnectionEventType() ==
  1766. PeerConnectionEvent.PeerConnectionEventType.SENSOR_FAR ||
  1767. peerConnectionEvent.getPeerConnectionEventType() ==
  1768. PeerConnectionEvent.PeerConnectionEventType.SENSOR_NEAR) {
  1769. if (!isVoiceOnlyCall) {
  1770. boolean enableVideo = peerConnectionEvent.getPeerConnectionEventType() ==
  1771. PeerConnectionEvent.PeerConnectionEventType.SENSOR_FAR && videoOn;
  1772. if (EffortlessPermissions.hasPermissions(this, PERMISSIONS_CAMERA) &&
  1773. (currentCallStatus.equals(CallStatus.CONNECTING) || isConnectionEstablished()) && videoOn
  1774. && enableVideo != localVideoTrack.enabled()) {
  1775. toggleMedia(enableVideo, true);
  1776. }
  1777. }
  1778. } else if (peerConnectionEvent.getPeerConnectionEventType() ==
  1779. PeerConnectionEvent.PeerConnectionEventType.NICK_CHANGE) {
  1780. if (participantDisplayItems.get(sessionId) != null) {
  1781. participantDisplayItems.get(sessionId).setNick(peerConnectionEvent.getNick());
  1782. }
  1783. participantsAdapter.notifyDataSetChanged();
  1784. } else if (peerConnectionEvent.getPeerConnectionEventType() ==
  1785. PeerConnectionEvent.PeerConnectionEventType.VIDEO_CHANGE && !isVoiceOnlyCall) {
  1786. if (participantDisplayItems.get(sessionId) != null) {
  1787. participantDisplayItems.get(sessionId).setStreamEnabled(peerConnectionEvent.getChangeValue());
  1788. }
  1789. participantsAdapter.notifyDataSetChanged();
  1790. } else if (peerConnectionEvent.getPeerConnectionEventType() ==
  1791. PeerConnectionEvent.PeerConnectionEventType.AUDIO_CHANGE) {
  1792. if (participantDisplayItems.get(sessionId) != null) {
  1793. participantDisplayItems.get(sessionId).setAudioEnabled(peerConnectionEvent.getChangeValue());
  1794. }
  1795. participantsAdapter.notifyDataSetChanged();
  1796. } else if (peerConnectionEvent.getPeerConnectionEventType() ==
  1797. PeerConnectionEvent.PeerConnectionEventType.PUBLISHER_FAILED) {
  1798. currentCallStatus = CallStatus.PUBLISHER_FAILED;
  1799. webSocketClient.clearResumeId();
  1800. hangup(false);
  1801. }
  1802. }
  1803. private void startSendingNick() {
  1804. DataChannelMessageNick dataChannelMessage = new DataChannelMessageNick();
  1805. dataChannelMessage.setType("nickChanged");
  1806. HashMap<String, String> nickChangedPayload = new HashMap<>();
  1807. nickChangedPayload.put("userid", conversationUser.getUserId());
  1808. nickChangedPayload.put("name", conversationUser.getDisplayName());
  1809. dataChannelMessage.setPayload(nickChangedPayload);
  1810. for (PeerConnectionWrapper peerConnectionWrapper : peerConnectionWrapperList) {
  1811. if (peerConnectionWrapper.isMCUPublisher()) {
  1812. Observable
  1813. .interval(1, TimeUnit.SECONDS)
  1814. .repeatUntil(() -> (!isConnectionEstablished() || isDestroyed()))
  1815. .observeOn(Schedulers.io())
  1816. .subscribe(new Observer<Long>() {
  1817. @Override
  1818. public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
  1819. // unused atm
  1820. }
  1821. @Override
  1822. public void onNext(@io.reactivex.annotations.NonNull Long aLong) {
  1823. peerConnectionWrapper.sendNickChannelData(dataChannelMessage);
  1824. }
  1825. @Override
  1826. public void onError(@io.reactivex.annotations.NonNull Throwable e) {
  1827. // unused atm
  1828. }
  1829. @Override
  1830. public void onComplete() {
  1831. // unused atm
  1832. }
  1833. });
  1834. break;
  1835. }
  1836. }
  1837. }
  1838. @Subscribe(threadMode = ThreadMode.MAIN)
  1839. public void onMessageEvent(MediaStreamEvent mediaStreamEvent) {
  1840. if (mediaStreamEvent.getMediaStream() != null) {
  1841. boolean hasAtLeastOneVideoStream = mediaStreamEvent.getMediaStream().videoTracks != null
  1842. && mediaStreamEvent.getMediaStream().videoTracks.size() > 0;
  1843. setupVideoStreamForLayout(
  1844. mediaStreamEvent.getMediaStream(),
  1845. mediaStreamEvent.getSession(),
  1846. hasAtLeastOneVideoStream,
  1847. mediaStreamEvent.getVideoStreamType());
  1848. } else {
  1849. setupVideoStreamForLayout(
  1850. null,
  1851. mediaStreamEvent.getSession(),
  1852. false,
  1853. mediaStreamEvent.getVideoStreamType());
  1854. }
  1855. }
  1856. @Subscribe(threadMode = ThreadMode.BACKGROUND)
  1857. public void onMessageEvent(SessionDescriptionSendEvent sessionDescriptionSend) throws IOException {
  1858. NCMessageWrapper ncMessageWrapper = new NCMessageWrapper();
  1859. ncMessageWrapper.setEv("message");
  1860. ncMessageWrapper.setSessionId(callSession);
  1861. NCSignalingMessage ncSignalingMessage = new NCSignalingMessage();
  1862. ncSignalingMessage.setTo(sessionDescriptionSend.getPeerId());
  1863. ncSignalingMessage.setRoomType(sessionDescriptionSend.getVideoStreamType());
  1864. ncSignalingMessage.setType(sessionDescriptionSend.getType());
  1865. NCMessagePayload ncMessagePayload = new NCMessagePayload();
  1866. ncMessagePayload.setType(sessionDescriptionSend.getType());
  1867. if (!"candidate".equals(sessionDescriptionSend.getType())) {
  1868. ncMessagePayload.setSdp(sessionDescriptionSend.getSessionDescription().description);
  1869. ncMessagePayload.setNick(conversationUser.getDisplayName());
  1870. } else {
  1871. ncMessagePayload.setIceCandidate(sessionDescriptionSend.getNcIceCandidate());
  1872. }
  1873. // Set all we need
  1874. ncSignalingMessage.setPayload(ncMessagePayload);
  1875. ncMessageWrapper.setSignalingMessage(ncSignalingMessage);
  1876. if (!hasExternalSignalingServer) {
  1877. StringBuilder stringBuilder = new StringBuilder();
  1878. stringBuilder.append("{")
  1879. .append("\"fn\":\"")
  1880. .append(StringEscapeUtils.escapeJson(LoganSquare.serialize(ncMessageWrapper.getSignalingMessage())))
  1881. .append("\"")
  1882. .append(",")
  1883. .append("\"sessionId\":")
  1884. .append("\"").append(StringEscapeUtils.escapeJson(callSession)).append("\"")
  1885. .append(",")
  1886. .append("\"ev\":\"message\"")
  1887. .append("}");
  1888. List<String> strings = new ArrayList<>();
  1889. String stringToSend = stringBuilder.toString();
  1890. strings.add(stringToSend);
  1891. int apiVersion = ApiUtils.getSignalingApiVersion(conversationUser, new int[]{ApiUtils.APIv3, 2, 1});
  1892. ncApi.sendSignalingMessages(credentials, ApiUtils.getUrlForSignaling(apiVersion, baseUrl, roomToken),
  1893. strings.toString())
  1894. .retry(3)
  1895. .subscribeOn(Schedulers.io())
  1896. .subscribe(new Observer<SignalingOverall>() {
  1897. @Override
  1898. public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
  1899. // unused atm
  1900. }
  1901. @Override
  1902. public void onNext(@io.reactivex.annotations.NonNull SignalingOverall signalingOverall) {
  1903. receivedSignalingMessages(signalingOverall.getOcs().getSignalings());
  1904. }
  1905. @Override
  1906. public void onError(@io.reactivex.annotations.NonNull Throwable e) {
  1907. Log.e(TAG, "", e);
  1908. }
  1909. @Override
  1910. public void onComplete() {
  1911. // unused atm
  1912. }
  1913. });
  1914. } else {
  1915. webSocketClient.sendCallMessage(ncMessageWrapper);
  1916. }
  1917. }
  1918. @Override
  1919. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
  1920. @NonNull int[] grantResults) {
  1921. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  1922. EffortlessPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults,
  1923. this);
  1924. }
  1925. private void setupVideoStreamForLayout(@Nullable MediaStream mediaStream,
  1926. String session,
  1927. boolean videoStreamEnabled,
  1928. String videoStreamType) {
  1929. String nick;
  1930. if (hasExternalSignalingServer) {
  1931. nick = webSocketClient.getDisplayNameForSession(session);
  1932. } else {
  1933. PeerConnectionWrapper peerConnectionWrapper = getPeerConnectionWrapperForSessionIdAndType(session,
  1934. videoStreamType);
  1935. nick = peerConnectionWrapper != null ? peerConnectionWrapper.getNick() : "";
  1936. }
  1937. String userId = "";
  1938. if (hasMCU) {
  1939. userId = webSocketClient.getUserIdForSession(session);
  1940. } else if (participantMap.get(session).getCalculatedActorType() == Participant.ActorType.USERS) {
  1941. userId = participantMap.get(session).getCalculatedActorId();
  1942. }
  1943. String urlForAvatar;
  1944. if (!TextUtils.isEmpty(userId)) {
  1945. urlForAvatar = ApiUtils.getUrlForAvatar(baseUrl,
  1946. userId,
  1947. true);
  1948. } else {
  1949. urlForAvatar = ApiUtils.getUrlForGuestAvatar(baseUrl,
  1950. nick,
  1951. true);
  1952. }
  1953. ParticipantDisplayItem participantDisplayItem = new ParticipantDisplayItem(userId,
  1954. session,
  1955. nick,
  1956. urlForAvatar,
  1957. mediaStream,
  1958. videoStreamType,
  1959. videoStreamEnabled,
  1960. rootEglBase);
  1961. participantDisplayItems.put(session, participantDisplayItem);
  1962. initGridAdapter();
  1963. }
  1964. private void setCallState(CallStatus callState) {
  1965. if (currentCallStatus == null || !currentCallStatus.equals(callState)) {
  1966. currentCallStatus = callState;
  1967. if (handler == null) {
  1968. handler = new Handler(Looper.getMainLooper());
  1969. } else {
  1970. handler.removeCallbacksAndMessages(null);
  1971. }
  1972. switch (callState) {
  1973. case CONNECTING:
  1974. handler.post(() -> {
  1975. playCallingSound();
  1976. if (isIncomingCallFromNotification) {
  1977. binding.callStates.callStateTextView.setText(R.string.nc_call_incoming);
  1978. } else {
  1979. binding.callStates.callStateTextView.setText(R.string.nc_call_ringing);
  1980. }
  1981. binding.callConversationNameTextView.setText(conversationName);
  1982. binding.callModeTextView.setText(getDescriptionForCallType());
  1983. if (binding.callStates.callStateRelativeLayout.getVisibility() != View.VISIBLE) {
  1984. binding.callStates.callStateRelativeLayout.setVisibility(View.VISIBLE);
  1985. }
  1986. if (binding.gridview.getVisibility() != View.INVISIBLE) {
  1987. binding.gridview.setVisibility(View.INVISIBLE);
  1988. }
  1989. if (binding.callStates.callStateProgressBar.getVisibility() != View.VISIBLE) {
  1990. binding.callStates.callStateProgressBar.setVisibility(View.VISIBLE);
  1991. }
  1992. if (binding.callStates.errorImageView.getVisibility() != View.GONE) {
  1993. binding.callStates.errorImageView.setVisibility(View.GONE);
  1994. }
  1995. });
  1996. break;
  1997. case CALLING_TIMEOUT:
  1998. handler.post(() -> {
  1999. hangup(false);
  2000. binding.callStates.callStateTextView.setText(R.string.nc_call_timeout);
  2001. binding.callModeTextView.setText(getDescriptionForCallType());
  2002. if (binding.callStates.callStateRelativeLayout.getVisibility() != View.VISIBLE) {
  2003. binding.callStates.callStateRelativeLayout.setVisibility(View.VISIBLE);
  2004. }
  2005. if (binding.callStates.callStateProgressBar.getVisibility() != View.GONE) {
  2006. binding.callStates.callStateProgressBar.setVisibility(View.GONE);
  2007. }
  2008. if (binding.gridview.getVisibility() != View.INVISIBLE) {
  2009. binding.gridview.setVisibility(View.INVISIBLE);
  2010. }
  2011. binding.callStates.errorImageView.setImageResource(R.drawable.ic_av_timer_timer_24dp);
  2012. if (binding.callStates.errorImageView.getVisibility() != View.VISIBLE) {
  2013. binding.callStates.errorImageView.setVisibility(View.VISIBLE);
  2014. }
  2015. });
  2016. break;
  2017. case RECONNECTING:
  2018. handler.post(() -> {
  2019. playCallingSound();
  2020. binding.callStates.callStateTextView.setText(R.string.nc_call_reconnecting);
  2021. binding.callModeTextView.setText(getDescriptionForCallType());
  2022. if (binding.callStates.callStateRelativeLayout.getVisibility() != View.VISIBLE) {
  2023. binding.callStates.callStateRelativeLayout.setVisibility(View.VISIBLE);
  2024. }
  2025. if (binding.gridview.getVisibility() != View.INVISIBLE) {
  2026. binding.gridview.setVisibility(View.INVISIBLE);
  2027. }
  2028. if (binding.callStates.callStateProgressBar.getVisibility() != View.VISIBLE) {
  2029. binding.callStates.callStateProgressBar.setVisibility(View.VISIBLE);
  2030. }
  2031. if (binding.callStates.errorImageView.getVisibility() != View.GONE) {
  2032. binding.callStates.errorImageView.setVisibility(View.GONE);
  2033. }
  2034. });
  2035. break;
  2036. case JOINED:
  2037. handler.postDelayed(() -> setCallState(CallStatus.CALLING_TIMEOUT), 45000);
  2038. handler.post(() -> {
  2039. binding.callModeTextView.setText(getDescriptionForCallType());
  2040. if (isIncomingCallFromNotification) {
  2041. binding.callStates.callStateTextView.setText(R.string.nc_call_incoming);
  2042. } else {
  2043. binding.callStates.callStateTextView.setText(R.string.nc_call_ringing);
  2044. }
  2045. if (binding.callStates.callStateRelativeLayout.getVisibility() != View.VISIBLE) {
  2046. binding.callStates.callStateRelativeLayout.setVisibility(View.VISIBLE);
  2047. }
  2048. if (binding.callStates.callStateProgressBar.getVisibility() != View.VISIBLE) {
  2049. binding.callStates.callStateProgressBar.setVisibility(View.VISIBLE);
  2050. }
  2051. if (binding.gridview.getVisibility() != View.INVISIBLE) {
  2052. binding.gridview.setVisibility(View.INVISIBLE);
  2053. }
  2054. if (binding.callStates.errorImageView.getVisibility() != View.GONE) {
  2055. binding.callStates.errorImageView.setVisibility(View.GONE);
  2056. }
  2057. });
  2058. break;
  2059. case IN_CONVERSATION:
  2060. handler.post(() -> {
  2061. stopCallingSound();
  2062. binding.callModeTextView.setText(getDescriptionForCallType());
  2063. if (!isVoiceOnlyCall) {
  2064. binding.callInfosLinearLayout.setVisibility(View.GONE);
  2065. }
  2066. if (!isPTTActive) {
  2067. animateCallControls(false, 5000);
  2068. }
  2069. if (binding.callStates.callStateRelativeLayout.getVisibility() != View.INVISIBLE) {
  2070. binding.callStates.callStateRelativeLayout.setVisibility(View.INVISIBLE);
  2071. }
  2072. if (binding.callStates.callStateProgressBar.getVisibility() != View.GONE) {
  2073. binding.callStates.callStateProgressBar.setVisibility(View.GONE);
  2074. }
  2075. if (binding.gridview.getVisibility() != View.VISIBLE) {
  2076. binding.gridview.setVisibility(View.VISIBLE);
  2077. }
  2078. if (binding.callStates.errorImageView.getVisibility() != View.GONE) {
  2079. binding.callStates.errorImageView.setVisibility(View.GONE);
  2080. }
  2081. });
  2082. break;
  2083. case OFFLINE:
  2084. handler.post(() -> {
  2085. stopCallingSound();
  2086. binding.callStates.callStateTextView.setText(R.string.nc_offline);
  2087. if (binding.callStates.callStateRelativeLayout.getVisibility() != View.VISIBLE) {
  2088. binding.callStates.callStateRelativeLayout.setVisibility(View.VISIBLE);
  2089. }
  2090. if (binding.gridview.getVisibility() != View.INVISIBLE) {
  2091. binding.gridview.setVisibility(View.INVISIBLE);
  2092. }
  2093. if (binding.callStates.callStateProgressBar.getVisibility() != View.GONE) {
  2094. binding.callStates.callStateProgressBar.setVisibility(View.GONE);
  2095. }
  2096. binding.callStates.errorImageView.setImageResource(R.drawable.ic_signal_wifi_off_white_24dp);
  2097. if (binding.callStates.errorImageView.getVisibility() != View.VISIBLE) {
  2098. binding.callStates.errorImageView.setVisibility(View.VISIBLE);
  2099. }
  2100. });
  2101. break;
  2102. case LEAVING:
  2103. handler.post(() -> {
  2104. if (!isDestroyed()) {
  2105. stopCallingSound();
  2106. binding.callModeTextView.setText(getDescriptionForCallType());
  2107. binding.callStates.callStateTextView.setText(R.string.nc_leaving_call);
  2108. binding.callStates.callStateRelativeLayout.setVisibility(View.VISIBLE);
  2109. binding.gridview.setVisibility(View.INVISIBLE);
  2110. binding.callStates.callStateProgressBar.setVisibility(View.VISIBLE);
  2111. binding.callStates.errorImageView.setVisibility(View.GONE);
  2112. }
  2113. });
  2114. break;
  2115. default:
  2116. }
  2117. }
  2118. }
  2119. private String getDescriptionForCallType() {
  2120. String appName = getResources().getString(R.string.nc_app_product_name);
  2121. if (isVoiceOnlyCall) {
  2122. return String.format(getResources().getString(R.string.nc_call_voice), appName);
  2123. } else {
  2124. return String.format(getResources().getString(R.string.nc_call_video), appName);
  2125. }
  2126. }
  2127. private void playCallingSound() {
  2128. stopCallingSound();
  2129. Uri ringtoneUri;
  2130. if (isIncomingCallFromNotification) {
  2131. ringtoneUri = NotificationUtils.INSTANCE.getCallRingtoneUri(getApplicationContext(), appPreferences);
  2132. } else {
  2133. ringtoneUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/raw" +
  2134. "/tr110_1_kap8_3_freiton1");
  2135. }
  2136. mediaPlayer = new MediaPlayer();
  2137. try {
  2138. mediaPlayer.setDataSource(this, ringtoneUri);
  2139. mediaPlayer.setLooping(true);
  2140. AudioAttributes audioAttributes = new AudioAttributes.Builder().setContentType(
  2141. AudioAttributes.CONTENT_TYPE_SONIFICATION)
  2142. .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
  2143. .build();
  2144. mediaPlayer.setAudioAttributes(audioAttributes);
  2145. mediaPlayer.setOnPreparedListener(mp -> mediaPlayer.start());
  2146. mediaPlayer.prepareAsync();
  2147. } catch (IOException e) {
  2148. Log.e(TAG, "Failed to play sound");
  2149. }
  2150. }
  2151. private void stopCallingSound() {
  2152. if (mediaPlayer != null) {
  2153. if (mediaPlayer.isPlaying()) {
  2154. mediaPlayer.stop();
  2155. }
  2156. mediaPlayer.release();
  2157. mediaPlayer = null;
  2158. }
  2159. }
  2160. private class MicrophoneButtonTouchListener implements View.OnTouchListener {
  2161. @SuppressLint("ClickableViewAccessibility")
  2162. @Override
  2163. public boolean onTouch(View v, MotionEvent event) {
  2164. v.onTouchEvent(event);
  2165. if (event.getAction() == MotionEvent.ACTION_UP && isPTTActive) {
  2166. isPTTActive = false;
  2167. binding.microphoneButton.getHierarchy().setPlaceholderImage(R.drawable.ic_mic_off_white_24px);
  2168. pulseAnimation.stop();
  2169. toggleMedia(false, false);
  2170. animateCallControls(false, 5000);
  2171. }
  2172. return true;
  2173. }
  2174. }
  2175. @Subscribe(threadMode = ThreadMode.BACKGROUND)
  2176. public void onMessageEvent(NetworkEvent networkEvent) {
  2177. if (networkEvent.getNetworkConnectionEvent() == NetworkEvent.NetworkConnectionEvent.NETWORK_CONNECTED) {
  2178. if (handler != null) {
  2179. handler.removeCallbacksAndMessages(null);
  2180. }
  2181. } else if (networkEvent.getNetworkConnectionEvent() ==
  2182. NetworkEvent.NetworkConnectionEvent.NETWORK_DISCONNECTED) {
  2183. if (handler != null) {
  2184. handler.removeCallbacksAndMessages(null);
  2185. }
  2186. }
  2187. }
  2188. @RequiresApi(api = Build.VERSION_CODES.O)
  2189. @Override
  2190. public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode, Configuration newConfig) {
  2191. super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
  2192. Log.d(TAG, "onPictureInPictureModeChanged");
  2193. Log.d(TAG, "isInPictureInPictureMode= " + isInPictureInPictureMode);
  2194. isInPipMode = isInPictureInPictureMode;
  2195. if (isInPictureInPictureMode) {
  2196. mReceiver =
  2197. new BroadcastReceiver() {
  2198. @Override
  2199. public void onReceive(Context context, Intent intent) {
  2200. if (intent == null || !MICROPHONE_PIP_INTENT_NAME.equals(intent.getAction())) {
  2201. return;
  2202. }
  2203. final int action = intent.getIntExtra(MICROPHONE_PIP_INTENT_EXTRA_ACTION, 0);
  2204. switch (action) {
  2205. case MICROPHONE_PIP_REQUEST_MUTE:
  2206. case MICROPHONE_PIP_REQUEST_UNMUTE:
  2207. onMicrophoneClick();
  2208. break;
  2209. }
  2210. }
  2211. };
  2212. registerReceiver(mReceiver,
  2213. new IntentFilter(MICROPHONE_PIP_INTENT_NAME),
  2214. permissionUtil.getPrivateBroadcastPermission(),
  2215. null);
  2216. updateUiForPipMode();
  2217. } else {
  2218. unregisterReceiver(mReceiver);
  2219. mReceiver = null;
  2220. updateUiForNormalMode();
  2221. }
  2222. }
  2223. void updatePictureInPictureActions(
  2224. @DrawableRes int iconId,
  2225. String title,
  2226. int requestCode) {
  2227. if (isGreaterEqualOreo() && isPipModePossible()) {
  2228. final ArrayList<RemoteAction> actions = new ArrayList<>();
  2229. final Icon icon = Icon.createWithResource(this, iconId);
  2230. int intentFlag;
  2231. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
  2232. intentFlag = FLAG_IMMUTABLE;
  2233. } else {
  2234. intentFlag = 0;
  2235. }
  2236. final PendingIntent intent =
  2237. PendingIntent.getBroadcast(
  2238. this,
  2239. requestCode,
  2240. new Intent(MICROPHONE_PIP_INTENT_NAME).putExtra(MICROPHONE_PIP_INTENT_EXTRA_ACTION, requestCode),
  2241. intentFlag);
  2242. actions.add(new RemoteAction(icon, title, title, intent));
  2243. mPictureInPictureParamsBuilder.setActions(actions);
  2244. setPictureInPictureParams(mPictureInPictureParamsBuilder.build());
  2245. }
  2246. }
  2247. public void updateUiForPipMode() {
  2248. Log.d(TAG, "updateUiForPipMode");
  2249. RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
  2250. ViewGroup.LayoutParams.WRAP_CONTENT);
  2251. params.setMargins(0, 0, 0, 0);
  2252. binding.gridview.setLayoutParams(params);
  2253. binding.callControls.setVisibility(View.GONE);
  2254. binding.callInfosLinearLayout.setVisibility(View.GONE);
  2255. binding.selfVideoViewWrapper.setVisibility(View.GONE);
  2256. binding.callStates.callStateRelativeLayout.setVisibility(View.GONE);
  2257. if (participantDisplayItems.size() > 1) {
  2258. binding.pipCallConversationNameTextView.setText(conversationName);
  2259. binding.pipGroupCallOverlay.setVisibility(View.VISIBLE);
  2260. } else {
  2261. binding.pipGroupCallOverlay.setVisibility(View.GONE);
  2262. }
  2263. binding.selfVideoRenderer.release();
  2264. }
  2265. public void updateUiForNormalMode() {
  2266. Log.d(TAG, "updateUiForNormalMode");
  2267. if (isVoiceOnlyCall) {
  2268. binding.callControls.setVisibility(View.VISIBLE);
  2269. } else {
  2270. // animateCallControls needs this to be invisible for a check.
  2271. binding.callControls.setVisibility(View.INVISIBLE);
  2272. }
  2273. initViews();
  2274. binding.callInfosLinearLayout.setVisibility(View.VISIBLE);
  2275. binding.selfVideoViewWrapper.setVisibility(View.VISIBLE);
  2276. binding.pipGroupCallOverlay.setVisibility(View.GONE);
  2277. }
  2278. @Override
  2279. void suppressFitsSystemWindows() {
  2280. binding.controllerCallLayout.setFitsSystemWindows(false);
  2281. }
  2282. public void onConfigurationChanged(Configuration newConfig) {
  2283. super.onConfigurationChanged(newConfig);
  2284. eventBus.post(new ConfigurationChangeEvent());
  2285. }
  2286. private class SelfVideoTouchListener implements View.OnTouchListener {
  2287. @SuppressLint("ClickableViewAccessibility")
  2288. @Override
  2289. public boolean onTouch(View view, MotionEvent event) {
  2290. long duration = event.getEventTime() - event.getDownTime();
  2291. if (event.getActionMasked() == MotionEvent.ACTION_MOVE) {
  2292. float newY = event.getRawY() - binding.selfVideoViewWrapper.getHeight() / (float) 2;
  2293. float newX = event.getRawX() - binding.selfVideoViewWrapper.getWidth() / (float) 2;
  2294. binding.selfVideoViewWrapper.setY(newY);
  2295. binding.selfVideoViewWrapper.setX(newX);
  2296. } else if (event.getActionMasked() == MotionEvent.ACTION_UP && duration < 100) {
  2297. switchCamera();
  2298. }
  2299. return true;
  2300. }
  2301. }
  2302. }