CallController.java 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780
  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.controllers;
  21. import android.Manifest;
  22. import android.animation.Animator;
  23. import android.animation.AnimatorListenerAdapter;
  24. import android.annotation.SuppressLint;
  25. import android.content.res.Configuration;
  26. import android.graphics.Color;
  27. import android.os.Build;
  28. import android.os.Bundle;
  29. import android.os.Handler;
  30. import androidx.annotation.NonNull;
  31. import androidx.annotation.Nullable;
  32. import androidx.appcompat.app.AppCompatActivity;
  33. import android.text.TextUtils;
  34. import android.util.Log;
  35. import android.view.LayoutInflater;
  36. import android.view.MotionEvent;
  37. import android.view.View;
  38. import android.view.ViewGroup;
  39. import android.widget.ImageView;
  40. import android.widget.LinearLayout;
  41. import android.widget.RelativeLayout;
  42. import android.widget.TextView;
  43. import com.bluelinelabs.logansquare.LoganSquare;
  44. import com.bumptech.glide.load.engine.DiskCacheStrategy;
  45. import com.bumptech.glide.load.resource.bitmap.CircleCrop;
  46. import com.bumptech.glide.request.RequestOptions;
  47. import com.nextcloud.talk.R;
  48. import com.nextcloud.talk.api.NcApi;
  49. import com.nextcloud.talk.application.NextcloudTalkApplication;
  50. import com.nextcloud.talk.controllers.base.BaseController;
  51. import com.nextcloud.talk.events.ConfigurationChangeEvent;
  52. import com.nextcloud.talk.events.MediaStreamEvent;
  53. import com.nextcloud.talk.events.PeerConnectionEvent;
  54. import com.nextcloud.talk.events.SessionDescriptionSendEvent;
  55. import com.nextcloud.talk.models.database.UserEntity;
  56. import com.nextcloud.talk.models.json.call.CallOverall;
  57. import com.nextcloud.talk.models.json.capabilities.CapabilitiesOverall;
  58. import com.nextcloud.talk.models.json.generic.GenericOverall;
  59. import com.nextcloud.talk.models.json.participants.Participant;
  60. import com.nextcloud.talk.models.json.participants.ParticipantsOverall;
  61. import com.nextcloud.talk.models.json.rooms.Conversation;
  62. import com.nextcloud.talk.models.json.rooms.RoomsOverall;
  63. import com.nextcloud.talk.models.json.signaling.DataChannelMessage;
  64. import com.nextcloud.talk.models.json.signaling.NCIceCandidate;
  65. import com.nextcloud.talk.models.json.signaling.NCMessagePayload;
  66. import com.nextcloud.talk.models.json.signaling.NCMessageWrapper;
  67. import com.nextcloud.talk.models.json.signaling.NCSignalingMessage;
  68. import com.nextcloud.talk.models.json.signaling.Signaling;
  69. import com.nextcloud.talk.models.json.signaling.SignalingOverall;
  70. import com.nextcloud.talk.models.json.signaling.settings.IceServer;
  71. import com.nextcloud.talk.models.json.signaling.settings.SignalingSettingsOverall;
  72. import com.nextcloud.talk.utils.ApiUtils;
  73. import com.nextcloud.talk.utils.MagicFlipView;
  74. import com.nextcloud.talk.utils.NotificationUtils;
  75. import com.nextcloud.talk.utils.animations.PulseAnimation;
  76. import com.nextcloud.talk.utils.bundle.BundleKeys;
  77. import com.nextcloud.talk.utils.database.user.UserUtils;
  78. import com.nextcloud.talk.utils.glide.GlideApp;
  79. import com.nextcloud.talk.utils.preferences.AppPreferences;
  80. import com.nextcloud.talk.utils.singletons.ApplicationWideCurrentRoomHolder;
  81. import com.nextcloud.talk.webrtc.MagicAudioManager;
  82. import com.nextcloud.talk.webrtc.MagicPeerConnectionWrapper;
  83. import com.nextcloud.talk.webrtc.MagicWebRTCUtils;
  84. import com.wooplr.spotlight.SpotlightView;
  85. import org.apache.commons.lang3.StringEscapeUtils;
  86. import org.greenrobot.eventbus.EventBus;
  87. import org.greenrobot.eventbus.Subscribe;
  88. import org.greenrobot.eventbus.ThreadMode;
  89. import org.parceler.Parcels;
  90. import org.webrtc.AudioSource;
  91. import org.webrtc.AudioTrack;
  92. import org.webrtc.Camera1Enumerator;
  93. import org.webrtc.Camera2Enumerator;
  94. import org.webrtc.CameraEnumerator;
  95. import org.webrtc.CameraVideoCapturer;
  96. import org.webrtc.EglBase;
  97. import org.webrtc.IceCandidate;
  98. import org.webrtc.Logging;
  99. import org.webrtc.MediaConstraints;
  100. import org.webrtc.MediaStream;
  101. import org.webrtc.PeerConnection;
  102. import org.webrtc.PeerConnectionFactory;
  103. import org.webrtc.RendererCommon;
  104. import org.webrtc.SessionDescription;
  105. import org.webrtc.SurfaceViewRenderer;
  106. import org.webrtc.VideoCapturer;
  107. import org.webrtc.VideoSource;
  108. import org.webrtc.VideoTrack;
  109. import java.io.IOException;
  110. import java.util.ArrayList;
  111. import java.util.HashMap;
  112. import java.util.HashSet;
  113. import java.util.List;
  114. import java.util.Map;
  115. import java.util.Set;
  116. import java.util.concurrent.TimeUnit;
  117. import javax.inject.Inject;
  118. import autodagger.AutoInjector;
  119. import butterknife.BindView;
  120. import butterknife.OnClick;
  121. import butterknife.OnLongClick;
  122. import eu.davidea.flipview.FlipView;
  123. import io.reactivex.Observer;
  124. import io.reactivex.android.schedulers.AndroidSchedulers;
  125. import io.reactivex.disposables.Disposable;
  126. import io.reactivex.schedulers.Schedulers;
  127. import me.zhanghai.android.effortlesspermissions.AfterPermissionDenied;
  128. import me.zhanghai.android.effortlesspermissions.EffortlessPermissions;
  129. import me.zhanghai.android.effortlesspermissions.OpenAppDetailsDialogFragment;
  130. import okhttp3.Cache;
  131. import pub.devrel.easypermissions.AfterPermissionGranted;
  132. @AutoInjector(NextcloudTalkApplication.class)
  133. public class CallController extends BaseController {
  134. private static final String TAG = "CallController";
  135. private static final String[] PERMISSIONS_CALL = {
  136. android.Manifest.permission.CAMERA,
  137. android.Manifest.permission.RECORD_AUDIO,
  138. };
  139. private static final String[] PERMISSIONS_CAMERA = {
  140. Manifest.permission.CAMERA
  141. };
  142. private static final String[] PERMISSIONS_MICROPHONE = {
  143. Manifest.permission.RECORD_AUDIO
  144. };
  145. @BindView(R.id.callControlEnableSpeaker)
  146. MagicFlipView callControlEnableSpeaker;
  147. @BindView(R.id.pip_video_view)
  148. SurfaceViewRenderer pipVideoView;
  149. @BindView(R.id.relative_layout)
  150. RelativeLayout relativeLayout;
  151. @BindView(R.id.remote_renderers_layout)
  152. LinearLayout remoteRenderersLayout;
  153. @BindView(R.id.callControlsLinearLayoutView)
  154. LinearLayout callControls;
  155. @BindView(R.id.call_control_microphone)
  156. FlipView microphoneControlButton;
  157. @BindView(R.id.call_control_camera)
  158. FlipView cameraControlButton;
  159. @BindView(R.id.call_control_switch_camera)
  160. FlipView cameraSwitchButton;
  161. @BindView(R.id.connectingTextView)
  162. TextView connectingTextView;
  163. @BindView(R.id.connectingRelativeLayoutView)
  164. RelativeLayout connectingView;
  165. @BindView(R.id.conversationRelativeLayoutView)
  166. RelativeLayout conversationView;
  167. @Inject
  168. NcApi ncApi;
  169. @Inject
  170. EventBus eventBus;
  171. @Inject
  172. UserUtils userUtils;
  173. @Inject
  174. AppPreferences appPreferences;
  175. @Inject
  176. Cache cache;
  177. private PeerConnectionFactory peerConnectionFactory;
  178. private MediaConstraints audioConstraints;
  179. private MediaConstraints videoConstraints;
  180. private MediaConstraints sdpConstraints;
  181. private MagicAudioManager audioManager;
  182. private VideoSource videoSource;
  183. private VideoTrack localVideoTrack;
  184. private AudioSource audioSource;
  185. private AudioTrack localAudioTrack;
  186. private VideoCapturer videoCapturer;
  187. private EglBase rootEglBase;
  188. private boolean leavingCall = false;
  189. private boolean inCall = false;
  190. private Disposable signalingDisposable;
  191. private Disposable pingDisposable;
  192. private List<PeerConnection.IceServer> iceServers;
  193. private CameraEnumerator cameraEnumerator;
  194. private String roomToken;
  195. private UserEntity conversationUser;
  196. private String callSession;
  197. private MediaStream localMediaStream;
  198. private String credentials;
  199. private List<MagicPeerConnectionWrapper> magicPeerConnectionWrapperList = new ArrayList<>();
  200. private Map<String, Participant> participantMap = new HashMap<>();
  201. private boolean videoOn = false;
  202. private boolean audioOn = false;
  203. private boolean isMultiSession = false;
  204. private boolean needsPing = true;
  205. private boolean isVoiceOnlyCall;
  206. private boolean isFromNotification;
  207. private Handler callControlHandler = new Handler();
  208. private Handler cameraSwitchHandler = new Handler();
  209. private boolean isPTTActive = false;
  210. private PulseAnimation pulseAnimation;
  211. private View.OnClickListener videoOnClickListener;
  212. private String baseUrl;
  213. private String roomId;
  214. private SpotlightView spotlightView;
  215. public CallController(Bundle args) {
  216. super(args);
  217. NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
  218. roomId = args.getString(BundleKeys.KEY_ROOM_ID, "");
  219. roomToken = args.getString(BundleKeys.KEY_ROOM_TOKEN, "");
  220. conversationUser = Parcels.unwrap(args.getParcelable(BundleKeys.KEY_USER_ENTITY));
  221. if (conversationUser == null) {
  222. conversationUser = userUtils.getCurrentUser();
  223. }
  224. callSession = args.getString(BundleKeys.KEY_CALL_SESSION, "0");
  225. credentials = ApiUtils.getCredentials(conversationUser.getUsername(), conversationUser.getToken());
  226. isVoiceOnlyCall = args.getBoolean(BundleKeys.KEY_CALL_VOICE_ONLY, false);
  227. if (conversationUser.getUserId().equals("?")) {
  228. credentials = null;
  229. }
  230. baseUrl = args.getString(BundleKeys.KEY_MODIFIED_BASE_URL, "");
  231. if (TextUtils.isEmpty(baseUrl)) {
  232. baseUrl = conversationUser.getBaseUrl();
  233. }
  234. isFromNotification = TextUtils.isEmpty(roomToken);
  235. }
  236. @Override
  237. protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
  238. return inflater.inflate(R.layout.controller_call, container, false);
  239. }
  240. private void createCameraEnumerator() {
  241. if (getActivity() != null) {
  242. boolean camera2EnumeratorIsSupported = false;
  243. try {
  244. camera2EnumeratorIsSupported = Camera2Enumerator.isSupported(getActivity());
  245. } catch (final Throwable throwable) {
  246. Log.w(TAG, "Camera2Enumator threw an error");
  247. }
  248. if (camera2EnumeratorIsSupported) {
  249. cameraEnumerator = new Camera2Enumerator(getActivity());
  250. } else {
  251. cameraEnumerator = new Camera1Enumerator(MagicWebRTCUtils.shouldEnableVideoHardwareAcceleration());
  252. }
  253. }
  254. }
  255. @Override
  256. protected void onViewBound(@NonNull View view) {
  257. super.onViewBound(view);
  258. microphoneControlButton.setOnTouchListener(new MicrophoneButtonTouchListener());
  259. videoOnClickListener = new VideoClickListener();
  260. pulseAnimation = PulseAnimation.create().with(microphoneControlButton.getFrontImageView())
  261. .setDuration(310)
  262. .setRepeatCount(PulseAnimation.INFINITE)
  263. .setRepeatMode(PulseAnimation.REVERSE);
  264. try {
  265. cache.evictAll();
  266. } catch (IOException e) {
  267. Log.e(TAG, "Failed to evict cache");
  268. }
  269. if (isVoiceOnlyCall) {
  270. callControlEnableSpeaker.setVisibility(View.VISIBLE);
  271. }
  272. callControls.setZ(100.0f);
  273. basicInitialization();
  274. if (isFromNotification) {
  275. handleFromNotification();
  276. } else {
  277. initViews();
  278. checkPermissions();
  279. }
  280. }
  281. private void basicInitialization() {
  282. rootEglBase = EglBase.create();
  283. createCameraEnumerator();
  284. //Create a new PeerConnectionFactory instance.
  285. PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
  286. peerConnectionFactory = PeerConnectionFactory.builder().createPeerConnectionFactory();
  287. peerConnectionFactory.setVideoHwAccelerationOptions(rootEglBase.getEglBaseContext(),
  288. rootEglBase.getEglBaseContext());
  289. //Create MediaConstraints - Will be useful for specifying video and audio constraints.
  290. audioConstraints = new MediaConstraints();
  291. videoConstraints = new MediaConstraints();
  292. localMediaStream = peerConnectionFactory.createLocalMediaStream("NCMS");
  293. // Create and audio manager that will take care of audio routing,
  294. // audio modes, audio device enumeration etc.
  295. audioManager = MagicAudioManager.create(getApplicationContext(), !isVoiceOnlyCall);
  296. // Store existing audio settings and change audio mode to
  297. // MODE_IN_COMMUNICATION for best possible VoIP performance.
  298. Log.d(TAG, "Starting the audio manager...");
  299. audioManager.start(this::onAudioManagerDevicesChanged);
  300. iceServers = new ArrayList<>();
  301. //create sdpConstraints
  302. sdpConstraints = new MediaConstraints();
  303. sdpConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"));
  304. String offerToReceiveVideoString = "true";
  305. if (isVoiceOnlyCall) {
  306. offerToReceiveVideoString = "false";
  307. }
  308. sdpConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo",
  309. offerToReceiveVideoString));
  310. sdpConstraints.optional.add(new MediaConstraints.KeyValuePair("internalSctpDataChannels", "true"));
  311. sdpConstraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));
  312. if (!isVoiceOnlyCall) {
  313. cameraInitialization();
  314. }
  315. microphoneInitialization();
  316. }
  317. private void handleFromNotification() {
  318. ncApi.getRooms(credentials, ApiUtils.getUrlForGetRooms(baseUrl))
  319. .retry(3)
  320. .subscribeOn(Schedulers.newThread())
  321. .observeOn(AndroidSchedulers.mainThread())
  322. .subscribe(new Observer<RoomsOverall>() {
  323. @Override
  324. public void onSubscribe(Disposable d) {
  325. }
  326. @Override
  327. public void onNext(RoomsOverall roomsOverall) {
  328. for (Conversation conversation : roomsOverall.getOcs().getData()) {
  329. if (roomId.equals(conversation.getRoomId())) {
  330. roomToken = conversation.getToken();
  331. break;
  332. }
  333. }
  334. initViews();
  335. checkPermissions();
  336. }
  337. @Override
  338. public void onError(Throwable e) {
  339. }
  340. @Override
  341. public void onComplete() {
  342. }
  343. });
  344. }
  345. private void initViews() {
  346. if (isVoiceOnlyCall) {
  347. cameraSwitchButton.setVisibility(View.GONE);
  348. cameraControlButton.setVisibility(View.GONE);
  349. pipVideoView.setVisibility(View.GONE);
  350. } else {
  351. if (cameraEnumerator.getDeviceNames().length < 2) {
  352. cameraSwitchButton.setVisibility(View.GONE);
  353. }
  354. // setting this to true because it's not shown by default
  355. pipVideoView.setMirror(false);
  356. pipVideoView.init(rootEglBase.getEglBaseContext(), null);
  357. pipVideoView.setZOrderMediaOverlay(true);
  358. // disabled because it causes some devices to crash
  359. pipVideoView.setEnableHardwareScaler(false);
  360. pipVideoView.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT);
  361. }
  362. }
  363. private void checkPermissions() {
  364. if (isVoiceOnlyCall) {
  365. onMicrophoneClick();
  366. } else if (getActivity() != null) {
  367. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  368. requestPermissions(PERMISSIONS_CALL, 100);
  369. } else {
  370. onRequestPermissionsResult(100, PERMISSIONS_CALL, new int[]{1, 1});
  371. }
  372. }
  373. }
  374. @AfterPermissionGranted(100)
  375. private void onPermissionsGranted() {
  376. if (EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_CALL)) {
  377. if (!videoOn && !isVoiceOnlyCall) {
  378. onCameraClick();
  379. }
  380. if (!audioOn) {
  381. onMicrophoneClick();
  382. }
  383. if (!isVoiceOnlyCall) {
  384. if (cameraEnumerator.getDeviceNames().length == 0) {
  385. cameraControlButton.setVisibility(View.GONE);
  386. }
  387. if (cameraEnumerator.getDeviceNames().length > 1) {
  388. cameraSwitchButton.setVisibility(View.VISIBLE);
  389. }
  390. }
  391. if (!inCall) {
  392. startCall();
  393. }
  394. } else if (getActivity() != null && EffortlessPermissions.somePermissionPermanentlyDenied(getActivity(),
  395. PERMISSIONS_CALL)) {
  396. checkIfSomeAreApproved();
  397. }
  398. }
  399. private void checkIfSomeAreApproved() {
  400. if (!isVoiceOnlyCall) {
  401. if (cameraEnumerator.getDeviceNames().length == 0) {
  402. cameraControlButton.setVisibility(View.GONE);
  403. }
  404. if (cameraEnumerator.getDeviceNames().length > 1) {
  405. cameraSwitchButton.setVisibility(View.VISIBLE);
  406. }
  407. if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_CAMERA)) {
  408. if (!videoOn) {
  409. onCameraClick();
  410. }
  411. } else {
  412. cameraControlButton.getFrontImageView().setImageResource(R.drawable.ic_videocam_off_white_24px);
  413. cameraControlButton.setAlpha(0.7f);
  414. cameraSwitchButton.setVisibility(View.GONE);
  415. }
  416. }
  417. if (EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_MICROPHONE)) {
  418. if (!audioOn) {
  419. onMicrophoneClick();
  420. }
  421. } else {
  422. microphoneControlButton.getFrontImageView().setImageResource(R.drawable.ic_mic_off_white_24px);
  423. }
  424. if (!inCall) {
  425. startCall();
  426. }
  427. }
  428. @AfterPermissionDenied(100)
  429. private void onPermissionsDenied() {
  430. if (!isVoiceOnlyCall) {
  431. if (cameraEnumerator.getDeviceNames().length == 0) {
  432. cameraControlButton.setVisibility(View.GONE);
  433. } else if (cameraEnumerator.getDeviceNames().length == 1) {
  434. cameraSwitchButton.setVisibility(View.GONE);
  435. }
  436. }
  437. if (getActivity() != null && (EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_CAMERA) ||
  438. EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_MICROPHONE))) {
  439. checkIfSomeAreApproved();
  440. } else if (!inCall) {
  441. startCall();
  442. }
  443. }
  444. private void onAudioManagerDevicesChanged(
  445. final MagicAudioManager.AudioDevice device, final Set<MagicAudioManager.AudioDevice> availableDevices) {
  446. Log.d(TAG, "onAudioManagerDevicesChanged: " + availableDevices + ", "
  447. + "selected: " + device);
  448. }
  449. private void cameraInitialization() {
  450. videoCapturer = createCameraCapturer(cameraEnumerator);
  451. //Create a VideoSource instance
  452. if (videoCapturer != null) {
  453. videoSource = peerConnectionFactory.createVideoSource(videoCapturer);
  454. localVideoTrack = peerConnectionFactory.createVideoTrack("NCv0", videoSource);
  455. localMediaStream.addTrack(localVideoTrack);
  456. localVideoTrack.setEnabled(false);
  457. localVideoTrack.addSink(pipVideoView);
  458. }
  459. }
  460. private void microphoneInitialization() {
  461. //create an AudioSource instance
  462. audioSource = peerConnectionFactory.createAudioSource(audioConstraints);
  463. localAudioTrack = peerConnectionFactory.createAudioTrack("NCa0", audioSource);
  464. localAudioTrack.setEnabled(false);
  465. localMediaStream.addTrack(localAudioTrack);
  466. }
  467. private VideoCapturer createCameraCapturer(CameraEnumerator enumerator) {
  468. final String[] deviceNames = enumerator.getDeviceNames();
  469. // First, try to find front facing camera
  470. Logging.d(TAG, "Looking for front facing cameras.");
  471. for (String deviceName : deviceNames) {
  472. if (enumerator.isFrontFacing(deviceName)) {
  473. Logging.d(TAG, "Creating front facing camera capturer.");
  474. VideoCapturer videoCapturer = enumerator.createCapturer(deviceName, null);
  475. if (videoCapturer != null) {
  476. return videoCapturer;
  477. }
  478. }
  479. }
  480. // Front facing camera not found, try something else
  481. Logging.d(TAG, "Looking for other cameras.");
  482. for (String deviceName : deviceNames) {
  483. if (!enumerator.isFrontFacing(deviceName)) {
  484. Logging.d(TAG, "Creating other camera capturer.");
  485. VideoCapturer videoCapturer = enumerator.createCapturer(deviceName, null);
  486. if (videoCapturer != null) {
  487. pipVideoView.setMirror(false);
  488. return videoCapturer;
  489. }
  490. }
  491. }
  492. return null;
  493. }
  494. @OnLongClick(R.id.call_control_microphone)
  495. public boolean onMicrophoneLongClick() {
  496. if (!audioOn) {
  497. callControlHandler.removeCallbacksAndMessages(null);
  498. cameraSwitchHandler.removeCallbacksAndMessages(null);
  499. isPTTActive = true;
  500. callControls.setVisibility(View.VISIBLE);
  501. cameraSwitchButton.setVisibility(View.VISIBLE);
  502. }
  503. onMicrophoneClick();
  504. return true;
  505. }
  506. @OnClick(R.id.callControlEnableSpeaker)
  507. public void onEnableSpeakerphoneClick() {
  508. if (audioManager != null) {
  509. audioManager.toggleUseSpeakerphone();
  510. callControlEnableSpeaker.flipSilently(!callControlEnableSpeaker.isFlipped());
  511. }
  512. }
  513. @OnClick(R.id.call_control_microphone)
  514. public void onMicrophoneClick() {
  515. if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_MICROPHONE)) {
  516. if (getActivity() != null && !appPreferences.getPushToTalkIntroShown()) {
  517. spotlightView = new SpotlightView.Builder(getActivity())
  518. .introAnimationDuration(300)
  519. .enableRevealAnimation(true)
  520. .performClick(false)
  521. .fadeinTextDuration(400)
  522. .headingTvColor(getResources().getColor(R.color.colorPrimary))
  523. .headingTvSize(20)
  524. .headingTvText(getResources().getString(R.string.nc_push_to_talk))
  525. .subHeadingTvColor(getResources().getColor(R.color.white))
  526. .subHeadingTvSize(16)
  527. .subHeadingTvText(getResources().getString(R.string.nc_push_to_talk_desc))
  528. .maskColor(Color.parseColor("#dc000000"))
  529. .target(microphoneControlButton)
  530. .lineAnimDuration(400)
  531. .lineAndArcColor(getResources().getColor(R.color.colorPrimary))
  532. .enableDismissAfterShown(true)
  533. .dismissOnBackPress(true)
  534. .usageId("pushToTalk")
  535. .show();
  536. appPreferences.setPushToTalkIntroShown(true);
  537. }
  538. if (!isPTTActive) {
  539. audioOn = !audioOn;
  540. if (audioOn) {
  541. microphoneControlButton.getFrontImageView().setImageResource(R.drawable.ic_mic_white_24px);
  542. } else {
  543. microphoneControlButton.getFrontImageView().setImageResource(R.drawable.ic_mic_off_white_24px);
  544. }
  545. toggleMedia(audioOn, false);
  546. } else {
  547. microphoneControlButton.getFrontImageView().setImageResource(R.drawable.ic_mic_white_24px);
  548. pulseAnimation.start();
  549. toggleMedia(true, false);
  550. }
  551. if (isVoiceOnlyCall && !inCall) {
  552. startCall();
  553. }
  554. } else if (getActivity() != null && EffortlessPermissions.somePermissionPermanentlyDenied(getActivity(),
  555. PERMISSIONS_MICROPHONE)) {
  556. // Microphone permission is permanently denied so we cannot request it normally.
  557. OpenAppDetailsDialogFragment.show(
  558. R.string.nc_microphone_permission_permanently_denied,
  559. R.string.nc_permissions_settings, (AppCompatActivity) getActivity());
  560. } else {
  561. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  562. requestPermissions(PERMISSIONS_MICROPHONE, 100);
  563. } else {
  564. onRequestPermissionsResult(100, PERMISSIONS_MICROPHONE, new int[]{1});
  565. }
  566. }
  567. }
  568. @OnClick(R.id.callControlHangupView)
  569. public void onHangupClick() {
  570. if (inCall) {
  571. hangup(false);
  572. } else {
  573. hangup(true);
  574. }
  575. }
  576. @OnClick(R.id.call_control_camera)
  577. public void onCameraClick() {
  578. if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_CAMERA)) {
  579. videoOn = !videoOn;
  580. if (videoOn) {
  581. cameraControlButton.getFrontImageView().setImageResource(R.drawable.ic_videocam_white_24px);
  582. if (cameraEnumerator.getDeviceNames().length > 1) {
  583. cameraSwitchButton.setVisibility(View.VISIBLE);
  584. }
  585. } else {
  586. cameraControlButton.getFrontImageView().setImageResource(R.drawable.ic_videocam_off_white_24px);
  587. cameraSwitchButton.setVisibility(View.GONE);
  588. }
  589. toggleMedia(videoOn, true);
  590. } else if (getActivity() != null && EffortlessPermissions.somePermissionPermanentlyDenied(getActivity(),
  591. PERMISSIONS_CAMERA)) {
  592. // Camera permission is permanently denied so we cannot request it normally.
  593. OpenAppDetailsDialogFragment.show(
  594. R.string.nc_camera_permission_permanently_denied,
  595. R.string.nc_permissions_settings, (AppCompatActivity) getActivity());
  596. } else {
  597. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  598. requestPermissions(PERMISSIONS_CAMERA, 100);
  599. } else {
  600. onRequestPermissionsResult(100, PERMISSIONS_CAMERA, new int[]{1});
  601. }
  602. }
  603. }
  604. @OnClick(R.id.call_control_switch_camera)
  605. public void switchCamera() {
  606. CameraVideoCapturer cameraVideoCapturer = (CameraVideoCapturer) videoCapturer;
  607. if (cameraVideoCapturer != null) {
  608. cameraVideoCapturer.switchCamera(new CameraVideoCapturer.CameraSwitchHandler() {
  609. @Override
  610. public void onCameraSwitchDone(boolean b) {
  611. pipVideoView.setMirror(false);
  612. }
  613. @Override
  614. public void onCameraSwitchError(String s) {
  615. }
  616. });
  617. }
  618. }
  619. private void toggleMedia(boolean enable, boolean video) {
  620. String message;
  621. if (video) {
  622. message = "videoOff";
  623. if (enable) {
  624. cameraControlButton.setAlpha(1.0f);
  625. message = "videoOn";
  626. startVideoCapture();
  627. } else {
  628. cameraControlButton.setAlpha(0.7f);
  629. if (videoCapturer != null) {
  630. try {
  631. videoCapturer.stopCapture();
  632. } catch (InterruptedException e) {
  633. Log.d(TAG, "Failed to stop capturing video while sensor is near the ear");
  634. }
  635. }
  636. }
  637. if (localMediaStream != null && localMediaStream.videoTracks.size() > 0) {
  638. localMediaStream.videoTracks.get(0).setEnabled(enable);
  639. }
  640. if (enable) {
  641. pipVideoView.setVisibility(View.VISIBLE);
  642. } else {
  643. pipVideoView.setVisibility(View.INVISIBLE);
  644. }
  645. } else {
  646. message = "audioOff";
  647. if (enable) {
  648. message = "audioOn";
  649. microphoneControlButton.setAlpha(1.0f);
  650. } else {
  651. microphoneControlButton.setAlpha(0.7f);
  652. }
  653. if (localMediaStream != null && localMediaStream.audioTracks.size() > 0) {
  654. localMediaStream.audioTracks.get(0).setEnabled(enable);
  655. }
  656. }
  657. if (inCall) {
  658. for (int i = 0; i < magicPeerConnectionWrapperList.size(); i++) {
  659. magicPeerConnectionWrapperList.get(i).sendChannelData(new DataChannelMessage(message));
  660. }
  661. }
  662. }
  663. private void startCall() {
  664. startPullingSignalingMessages();
  665. }
  666. private void animateCallControls(boolean show, long startDelay) {
  667. if (isVoiceOnlyCall) {
  668. if (spotlightView != null && spotlightView.getVisibility() != View.GONE) {
  669. spotlightView.setVisibility(View.GONE);
  670. }
  671. } else if (!isPTTActive) {
  672. float alpha;
  673. long duration;
  674. if (show) {
  675. callControlHandler.removeCallbacksAndMessages(null);
  676. cameraSwitchHandler.removeCallbacksAndMessages(null);
  677. alpha = 1.0f;
  678. duration = 1000;
  679. if (callControls.getVisibility() != View.VISIBLE) {
  680. callControls.setAlpha(0.0f);
  681. callControls.setVisibility(View.VISIBLE);
  682. cameraSwitchButton.setAlpha(0.0f);
  683. cameraSwitchButton.setVisibility(View.VISIBLE);
  684. } else {
  685. callControlHandler.postDelayed(() -> animateCallControls(false, 0), 5000);
  686. return;
  687. }
  688. } else {
  689. alpha = 0.0f;
  690. duration = 1000;
  691. }
  692. if (callControls != null) {
  693. callControls.setEnabled(false);
  694. callControls.animate()
  695. .translationY(0)
  696. .alpha(alpha)
  697. .setDuration(duration)
  698. .setStartDelay(startDelay)
  699. .setListener(new AnimatorListenerAdapter() {
  700. @Override
  701. public void onAnimationEnd(Animator animation) {
  702. super.onAnimationEnd(animation);
  703. if (callControls != null) {
  704. if (!show) {
  705. callControls.setVisibility(View.GONE);
  706. if (spotlightView != null && spotlightView.getVisibility() != View.GONE) {
  707. spotlightView.setVisibility(View.GONE);
  708. }
  709. } else {
  710. callControlHandler.postDelayed(new Runnable() {
  711. @Override
  712. public void run() {
  713. if (!isPTTActive) {
  714. animateCallControls(false, 0);
  715. }
  716. }
  717. }, 7500);
  718. }
  719. callControls.setEnabled(true);
  720. }
  721. }
  722. });
  723. }
  724. if (cameraSwitchButton != null) {
  725. cameraSwitchButton.setEnabled(false);
  726. cameraSwitchButton.animate()
  727. .translationY(0)
  728. .alpha(alpha)
  729. .setDuration(duration)
  730. .setStartDelay(startDelay)
  731. .setListener(new AnimatorListenerAdapter() {
  732. @Override
  733. public void onAnimationEnd(Animator animation) {
  734. super.onAnimationEnd(animation);
  735. if (cameraSwitchButton != null) {
  736. if (!show) {
  737. cameraSwitchButton.setVisibility(View.GONE);
  738. }
  739. cameraSwitchButton.setEnabled(true);
  740. }
  741. }
  742. });
  743. }
  744. }
  745. }
  746. @Override
  747. public void onDestroy() {
  748. onHangupClick();
  749. super.onDestroy();
  750. }
  751. private void startPullingSignalingMessages() {
  752. leavingCall = false;
  753. ncApi.getSignalingSettings(credentials, ApiUtils.getUrlForSignalingSettings(baseUrl))
  754. .subscribeOn(Schedulers.newThread())
  755. .retry(3)
  756. .observeOn(AndroidSchedulers.mainThread())
  757. .subscribe(new Observer<SignalingSettingsOverall>() {
  758. @Override
  759. public void onSubscribe(Disposable d) {
  760. }
  761. @Override
  762. public void onNext(SignalingSettingsOverall signalingSettingsOverall) {
  763. IceServer iceServer;
  764. if (signalingSettingsOverall != null && signalingSettingsOverall.getOcs() != null &&
  765. signalingSettingsOverall.getOcs().getSettings() != null) {
  766. if (signalingSettingsOverall.getOcs().getSettings().getStunServers() != null) {
  767. for (int i = 0; i < signalingSettingsOverall.getOcs().getSettings().getStunServers().size();
  768. i++) {
  769. iceServer = signalingSettingsOverall.getOcs().getSettings().getStunServers().get(i);
  770. if (TextUtils.isEmpty(iceServer.getUsername()) || TextUtils.isEmpty(iceServer
  771. .getCredential())) {
  772. iceServers.add(new PeerConnection.IceServer(iceServer.getUrl()));
  773. } else {
  774. iceServers.add(new PeerConnection.IceServer(iceServer.getUrl(),
  775. iceServer.getUsername(), iceServer.getCredential()));
  776. }
  777. }
  778. }
  779. if (signalingSettingsOverall.getOcs().getSettings().getTurnServers() != null) {
  780. for (int i = 0; i < signalingSettingsOverall.getOcs().getSettings().getTurnServers().size();
  781. i++) {
  782. iceServer = signalingSettingsOverall.getOcs().getSettings().getTurnServers().get(i);
  783. for (int j = 0; j < iceServer.getUrls().size(); j++) {
  784. if (TextUtils.isEmpty(iceServer.getUsername()) || TextUtils.isEmpty(iceServer
  785. .getCredential())) {
  786. iceServers.add(new PeerConnection.IceServer(iceServer.getUrls().get(j)));
  787. } else {
  788. iceServers.add(new PeerConnection.IceServer(iceServer.getUrls().get(j),
  789. iceServer.getUsername(), iceServer.getCredential()));
  790. }
  791. }
  792. }
  793. }
  794. }
  795. checkCapabilities();
  796. }
  797. @Override
  798. public void onError(Throwable e) {
  799. }
  800. @Override
  801. public void onComplete() {
  802. }
  803. });
  804. }
  805. private void checkCapabilities() {
  806. ncApi.getCapabilities(credentials, ApiUtils.getUrlForCapabilities(baseUrl))
  807. .retry(3)
  808. .subscribeOn(Schedulers.newThread())
  809. .observeOn(AndroidSchedulers.mainThread())
  810. .subscribe(new Observer<CapabilitiesOverall>() {
  811. @Override
  812. public void onSubscribe(Disposable d) {
  813. }
  814. @Override
  815. public void onNext(CapabilitiesOverall capabilitiesOverall) {
  816. isMultiSession = capabilitiesOverall.getOcs().getData()
  817. .getCapabilities() != null && capabilitiesOverall.getOcs().getData()
  818. .getCapabilities().getSpreedCapability() != null &&
  819. capabilitiesOverall.getOcs().getData()
  820. .getCapabilities().getSpreedCapability()
  821. .getFeatures() != null && capabilitiesOverall.getOcs().getData()
  822. .getCapabilities().getSpreedCapability()
  823. .getFeatures().contains("multi-room-users");
  824. needsPing = !(capabilitiesOverall.getOcs().getData()
  825. .getCapabilities() != null && capabilitiesOverall.getOcs().getData()
  826. .getCapabilities().getSpreedCapability() != null &&
  827. capabilitiesOverall.getOcs().getData()
  828. .getCapabilities().getSpreedCapability()
  829. .getFeatures() != null && capabilitiesOverall.getOcs().getData()
  830. .getCapabilities().getSpreedCapability()
  831. .getFeatures().contains("no-ping"));
  832. joinRoomAndCall();
  833. }
  834. @Override
  835. public void onError(Throwable e) {
  836. isMultiSession = false;
  837. }
  838. @Override
  839. public void onComplete() {
  840. }
  841. });
  842. }
  843. private void joinRoomAndCall() {
  844. if ("0".equals(callSession)) {
  845. ncApi.joinRoom(credentials, ApiUtils.getUrlForSettingMyselfAsActiveParticipant(baseUrl, roomToken), null)
  846. .subscribeOn(Schedulers.newThread())
  847. .observeOn(AndroidSchedulers.mainThread())
  848. .retry(3)
  849. .subscribe(new Observer<CallOverall>() {
  850. @Override
  851. public void onSubscribe(Disposable d) {
  852. }
  853. @Override
  854. public void onNext(CallOverall callOverall) {
  855. callSession = callOverall.getOcs().getData().getSessionId();
  856. performCall();
  857. }
  858. @Override
  859. public void onError(Throwable e) {
  860. }
  861. @Override
  862. public void onComplete() {
  863. }
  864. });
  865. } else {
  866. performCall();
  867. }
  868. }
  869. private void performCall() {
  870. ncApi.joinCall(credentials,
  871. ApiUtils.getUrlForCall(baseUrl, roomToken))
  872. .subscribeOn(Schedulers.newThread())
  873. .retry(3)
  874. .observeOn(AndroidSchedulers.mainThread())
  875. .subscribe(new Observer<GenericOverall>() {
  876. @Override
  877. public void onSubscribe(Disposable d) {
  878. }
  879. @Override
  880. public void onNext(GenericOverall genericOverall) {
  881. inCall = true;
  882. if (connectingView != null) {
  883. connectingView.setVisibility(View.GONE);
  884. }
  885. if (conversationView != null) {
  886. conversationView.setVisibility(View.VISIBLE);
  887. }
  888. if (!isPTTActive) {
  889. animateCallControls(false, 5000);
  890. }
  891. ApplicationWideCurrentRoomHolder.getInstance().setCurrentRoomId(roomId);
  892. ApplicationWideCurrentRoomHolder.getInstance().setCurrentRoomToken(roomToken);
  893. ApplicationWideCurrentRoomHolder.getInstance().setInCall(true);
  894. ApplicationWideCurrentRoomHolder.getInstance().setUserInRoom(conversationUser);
  895. if (needsPing) {
  896. ncApi.pingCall(credentials, ApiUtils.getUrlForCallPing(baseUrl, roomToken))
  897. .subscribeOn(Schedulers.newThread())
  898. .observeOn(AndroidSchedulers.mainThread())
  899. .repeatWhen(observable -> observable.delay(5000, TimeUnit.MILLISECONDS))
  900. .takeWhile(observable -> inCall)
  901. .retry(3, observable -> inCall)
  902. .subscribe(new Observer<GenericOverall>() {
  903. @Override
  904. public void onSubscribe(Disposable d) {
  905. pingDisposable = d;
  906. }
  907. @Override
  908. public void onNext(GenericOverall genericOverall) {
  909. }
  910. @Override
  911. public void onError(Throwable e) {
  912. dispose(pingDisposable);
  913. }
  914. @Override
  915. public void onComplete() {
  916. dispose(pingDisposable);
  917. }
  918. });
  919. }
  920. // Start pulling signaling messages
  921. String urlToken = null;
  922. if (isMultiSession) {
  923. urlToken = roomToken;
  924. }
  925. NotificationUtils.cancelExistingNotifications(getApplicationContext(), conversationUser);
  926. ncApi.pullSignalingMessages(credentials, ApiUtils.getUrlForSignaling(baseUrl, urlToken))
  927. .subscribeOn(Schedulers.newThread())
  928. .observeOn(AndroidSchedulers.mainThread())
  929. .repeatWhen(observable -> observable)
  930. .takeWhile(observable -> inCall)
  931. .retry(3, observable -> inCall)
  932. .subscribe(new Observer<SignalingOverall>() {
  933. @Override
  934. public void onSubscribe(Disposable d) {
  935. signalingDisposable = d;
  936. }
  937. @Override
  938. public void onNext(SignalingOverall signalingOverall) {
  939. if (signalingOverall.getOcs().getSignalings() != null) {
  940. for (int i = 0; i < signalingOverall.getOcs().getSignalings().size(); i++) {
  941. try {
  942. receivedSignalingMessage(signalingOverall.getOcs().getSignalings().get(i));
  943. } catch (IOException e) {
  944. Log.e(TAG, "Failed to process received signaling" +
  945. " message");
  946. }
  947. }
  948. }
  949. }
  950. @Override
  951. public void onError(Throwable e) {
  952. dispose(signalingDisposable);
  953. }
  954. @Override
  955. public void onComplete() {
  956. dispose(signalingDisposable);
  957. }
  958. });
  959. }
  960. @Override
  961. public void onError(Throwable e) {
  962. }
  963. @Override
  964. public void onComplete() {
  965. }
  966. });
  967. }
  968. @OnClick({R.id.pip_video_view, R.id.remote_renderers_layout})
  969. public void showCallControls() {
  970. animateCallControls(true, 0);
  971. }
  972. private void dispose(@Nullable Disposable disposable) {
  973. if (disposable != null && !disposable.isDisposed()) {
  974. disposable.dispose();
  975. } else if (disposable == null) {
  976. if (pingDisposable != null && !pingDisposable.isDisposed()) {
  977. pingDisposable.dispose();
  978. pingDisposable = null;
  979. }
  980. if (signalingDisposable != null && !signalingDisposable.isDisposed()) {
  981. signalingDisposable.dispose();
  982. signalingDisposable = null;
  983. }
  984. }
  985. }
  986. private void receivedSignalingMessage(Signaling signaling) throws IOException {
  987. String messageType = signaling.getType();
  988. if (leavingCall) {
  989. return;
  990. }
  991. if ("usersInRoom".equals(messageType)) {
  992. processUsersInRoom((List<HashMap<String, Object>>) signaling.getMessageWrapper());
  993. } else if ("message".equals(messageType)) {
  994. NCSignalingMessage ncSignalingMessage = LoganSquare.parse(signaling.getMessageWrapper().toString(),
  995. NCSignalingMessage.class);
  996. if (ncSignalingMessage.getRoomType().equals("video")) {
  997. MagicPeerConnectionWrapper magicPeerConnectionWrapper = alwaysGetPeerConnectionWrapperForSessionId
  998. (ncSignalingMessage.getFrom());
  999. String type = null;
  1000. if (ncSignalingMessage.getPayload() != null && ncSignalingMessage.getPayload().getType() !=
  1001. null) {
  1002. type = ncSignalingMessage.getPayload().getType();
  1003. } else if (ncSignalingMessage.getType() != null) {
  1004. type = ncSignalingMessage.getType();
  1005. }
  1006. if (type != null) {
  1007. switch (type) {
  1008. case "offer":
  1009. case "answer":
  1010. magicPeerConnectionWrapper.setNick(ncSignalingMessage.getPayload().getNick());
  1011. String sessionDescriptionStringWithPreferredCodec = MagicWebRTCUtils.preferCodec
  1012. (ncSignalingMessage.getPayload().getSdp(),
  1013. "VP8", false);
  1014. SessionDescription sessionDescriptionWithPreferredCodec = new SessionDescription(
  1015. SessionDescription.Type.fromCanonicalForm(type),
  1016. sessionDescriptionStringWithPreferredCodec);
  1017. if (magicPeerConnectionWrapper.getPeerConnection() != null) {
  1018. magicPeerConnectionWrapper.getPeerConnection().setRemoteDescription(magicPeerConnectionWrapper
  1019. .getMagicSdpObserver(), sessionDescriptionWithPreferredCodec);
  1020. }
  1021. break;
  1022. case "candidate":
  1023. NCIceCandidate ncIceCandidate = ncSignalingMessage.getPayload().getIceCandidate();
  1024. IceCandidate iceCandidate = new IceCandidate(ncIceCandidate.getSdpMid(),
  1025. ncIceCandidate.getSdpMLineIndex(), ncIceCandidate.getCandidate());
  1026. magicPeerConnectionWrapper.addCandidate(iceCandidate);
  1027. break;
  1028. case "endOfCandidates":
  1029. magicPeerConnectionWrapper.drainIceCandidates();
  1030. break;
  1031. default:
  1032. break;
  1033. }
  1034. }
  1035. } else {
  1036. Log.d(TAG, "Something went very very wrong");
  1037. }
  1038. } else {
  1039. Log.d(TAG, "Something went very very wrong");
  1040. }
  1041. }
  1042. private void hangup(boolean dueToNetworkChange) {
  1043. leavingCall = true;
  1044. inCall = false;
  1045. if (videoCapturer != null) {
  1046. try {
  1047. videoCapturer.stopCapture();
  1048. } catch (InterruptedException e) {
  1049. Log.e(TAG, "Failed to stop capturing while hanging up");
  1050. }
  1051. videoCapturer.dispose();
  1052. videoCapturer = null;
  1053. }
  1054. for (int i = 0; i < magicPeerConnectionWrapperList.size(); i++) {
  1055. endPeerConnection(magicPeerConnectionWrapperList.get(i).getSessionId());
  1056. }
  1057. if (pipVideoView != null) {
  1058. pipVideoView.release();
  1059. }
  1060. if (audioSource != null) {
  1061. audioSource.dispose();
  1062. audioSource = null;
  1063. }
  1064. if (audioManager != null) {
  1065. audioManager.stop();
  1066. audioManager = null;
  1067. }
  1068. if (videoSource != null) {
  1069. videoSource = null;
  1070. }
  1071. if (peerConnectionFactory != null) {
  1072. peerConnectionFactory = null;
  1073. }
  1074. localMediaStream = null;
  1075. localAudioTrack = null;
  1076. localVideoTrack = null;
  1077. if (!dueToNetworkChange) {
  1078. hangupNetworkCalls();
  1079. } else {
  1080. if (getActivity() != null) {
  1081. getActivity().finish();
  1082. }
  1083. }
  1084. }
  1085. private void hangupNetworkCalls() {
  1086. ncApi.leaveCall(credentials, ApiUtils.getUrlForCall(baseUrl, roomToken))
  1087. .subscribeOn(Schedulers.newThread())
  1088. .observeOn(AndroidSchedulers.mainThread())
  1089. .subscribe(new Observer<GenericOverall>() {
  1090. @Override
  1091. public void onSubscribe(Disposable d) {
  1092. }
  1093. @Override
  1094. public void onNext(GenericOverall genericOverall) {
  1095. if (isMultiSession) {
  1096. if (getActivity() != null) {
  1097. getActivity().finish();
  1098. }
  1099. } else {
  1100. leaveRoom();
  1101. }
  1102. }
  1103. @Override
  1104. public void onError(Throwable e) {
  1105. }
  1106. @Override
  1107. public void onComplete() {
  1108. }
  1109. });
  1110. }
  1111. private void leaveRoom() {
  1112. ncApi.leaveRoom(credentials, ApiUtils.getUrlForSettingMyselfAsActiveParticipant(baseUrl, roomToken))
  1113. .subscribeOn(Schedulers.newThread())
  1114. .observeOn(AndroidSchedulers.mainThread())
  1115. .subscribe(new Observer<GenericOverall>() {
  1116. @Override
  1117. public void onSubscribe(Disposable d) {
  1118. }
  1119. @Override
  1120. public void onNext(GenericOverall genericOverall) {
  1121. if (getActivity() != null) {
  1122. getActivity().finish();
  1123. }
  1124. }
  1125. @Override
  1126. public void onError(Throwable e) {
  1127. }
  1128. @Override
  1129. public void onComplete() {
  1130. }
  1131. });
  1132. }
  1133. private void startVideoCapture() {
  1134. if (videoCapturer != null) {
  1135. videoCapturer.startCapture(1280, 720, 30);
  1136. }
  1137. }
  1138. private void processUsersInRoom(List<HashMap<String, Object>> users) {
  1139. List<String> newSessions = new ArrayList<>();
  1140. Set<String> oldSesssions = new HashSet<>();
  1141. for (HashMap<String, Object> participant : users) {
  1142. if (!participant.get("sessionId").equals(callSession)) {
  1143. Object inCallObject = participant.get("inCall");
  1144. boolean isNewSession;
  1145. if (inCallObject instanceof Boolean) {
  1146. isNewSession = (boolean) inCallObject;
  1147. } else {
  1148. isNewSession = ((long) inCallObject) != 0;
  1149. }
  1150. if (isNewSession) {
  1151. newSessions.add(participant.get("sessionId").toString());
  1152. } else {
  1153. oldSesssions.add(participant.get("sessionId").toString());
  1154. }
  1155. }
  1156. }
  1157. for (MagicPeerConnectionWrapper magicPeerConnectionWrapper : magicPeerConnectionWrapperList) {
  1158. oldSesssions.add(magicPeerConnectionWrapper.getSessionId());
  1159. }
  1160. // Calculate sessions that left the call
  1161. oldSesssions.removeAll(newSessions);
  1162. // Calculate sessions that join the call
  1163. newSessions.removeAll(oldSesssions);
  1164. if (leavingCall) {
  1165. return;
  1166. }
  1167. if (newSessions.size() > 0) {
  1168. getPeersForCall();
  1169. }
  1170. for (String sessionId : newSessions) {
  1171. alwaysGetPeerConnectionWrapperForSessionId(sessionId);
  1172. }
  1173. for (String sessionId : oldSesssions) {
  1174. endPeerConnection(sessionId);
  1175. }
  1176. }
  1177. private void getPeersForCall() {
  1178. ncApi.getPeersForCall(credentials, ApiUtils.getUrlForCall(baseUrl, roomToken))
  1179. .subscribeOn(Schedulers.newThread())
  1180. .subscribe(new Observer<ParticipantsOverall>() {
  1181. @Override
  1182. public void onSubscribe(Disposable d) {
  1183. }
  1184. @Override
  1185. public void onNext(ParticipantsOverall participantsOverall) {
  1186. participantMap = new HashMap<>();
  1187. for (Participant participant : participantsOverall.getOcs().getData()) {
  1188. participantMap.put(participant.getSessionId(), participant);
  1189. if (getActivity() != null) {
  1190. getActivity().runOnUiThread(() -> setupAvatarForSession(participant.getSessionId()));
  1191. }
  1192. }
  1193. }
  1194. @Override
  1195. public void onError(Throwable e) {
  1196. }
  1197. @Override
  1198. public void onComplete() {
  1199. }
  1200. });
  1201. }
  1202. private void deleteMagicPeerConnection(MagicPeerConnectionWrapper magicPeerConnectionWrapper) {
  1203. magicPeerConnectionWrapper.removePeerConnection();
  1204. magicPeerConnectionWrapperList.remove(magicPeerConnectionWrapper);
  1205. }
  1206. private MagicPeerConnectionWrapper alwaysGetPeerConnectionWrapperForSessionId(String sessionId) {
  1207. MagicPeerConnectionWrapper magicPeerConnectionWrapper;
  1208. if ((magicPeerConnectionWrapper = getPeerConnectionWrapperForSessionId(sessionId)) != null) {
  1209. return magicPeerConnectionWrapper;
  1210. } else {
  1211. magicPeerConnectionWrapper = new MagicPeerConnectionWrapper(peerConnectionFactory,
  1212. iceServers, sdpConstraints, sessionId, callSession, localMediaStream);
  1213. magicPeerConnectionWrapperList.add(magicPeerConnectionWrapper);
  1214. return magicPeerConnectionWrapper;
  1215. }
  1216. }
  1217. private MagicPeerConnectionWrapper getPeerConnectionWrapperForSessionId(String sessionId) {
  1218. for (MagicPeerConnectionWrapper magicPeerConnectionWrapper : magicPeerConnectionWrapperList) {
  1219. if (magicPeerConnectionWrapper.getSessionId().equals(sessionId)) {
  1220. return magicPeerConnectionWrapper;
  1221. }
  1222. }
  1223. return null;
  1224. }
  1225. private void endPeerConnection(String sessionId) {
  1226. MagicPeerConnectionWrapper magicPeerConnectionWrapper;
  1227. if ((magicPeerConnectionWrapper = getPeerConnectionWrapperForSessionId(sessionId)) != null && getActivity()
  1228. != null) {
  1229. getActivity().runOnUiThread(() -> removeMediaStream(sessionId));
  1230. deleteMagicPeerConnection(magicPeerConnectionWrapper);
  1231. }
  1232. }
  1233. private void removeMediaStream(String sessionId) {
  1234. if (remoteRenderersLayout != null && remoteRenderersLayout.getChildCount() > 0) {
  1235. RelativeLayout relativeLayout = remoteRenderersLayout.findViewWithTag(sessionId);
  1236. if (relativeLayout != null) {
  1237. SurfaceViewRenderer surfaceViewRenderer = relativeLayout.findViewById(R.id.surface_view);
  1238. surfaceViewRenderer.release();
  1239. remoteRenderersLayout.removeView(relativeLayout);
  1240. remoteRenderersLayout.invalidate();
  1241. }
  1242. }
  1243. if (callControls != null) {
  1244. callControls.setZ(100.0f);
  1245. }
  1246. }
  1247. @Subscribe(threadMode = ThreadMode.MAIN)
  1248. public void onMessageEvent(ConfigurationChangeEvent configurationChangeEvent) {
  1249. if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
  1250. remoteRenderersLayout.setOrientation(LinearLayout.HORIZONTAL);
  1251. } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
  1252. remoteRenderersLayout.setOrientation(LinearLayout.VERTICAL);
  1253. }
  1254. }
  1255. @Subscribe(threadMode = ThreadMode.MAIN)
  1256. public void onMessageEvent(PeerConnectionEvent peerConnectionEvent) {
  1257. if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent.PeerConnectionEventType
  1258. .PEER_CLOSED)) {
  1259. endPeerConnection(peerConnectionEvent.getSessionId());
  1260. } else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
  1261. .PeerConnectionEventType.SENSOR_FAR) ||
  1262. peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
  1263. .PeerConnectionEventType.SENSOR_NEAR)) {
  1264. if (!isVoiceOnlyCall) {
  1265. boolean enableVideo = peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
  1266. .PeerConnectionEventType.SENSOR_FAR) && videoOn;
  1267. if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_CAMERA) &&
  1268. inCall && videoOn
  1269. && enableVideo != localVideoTrack.enabled()) {
  1270. toggleMedia(enableVideo, true);
  1271. }
  1272. }
  1273. } else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
  1274. .PeerConnectionEventType.NICK_CHANGE)) {
  1275. gotNick(peerConnectionEvent.getSessionId(), peerConnectionEvent.getNick());
  1276. } else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
  1277. .PeerConnectionEventType.VIDEO_CHANGE) && !isVoiceOnlyCall) {
  1278. gotAudioOrVideoChange(true, peerConnectionEvent.getSessionId(),
  1279. peerConnectionEvent.getChangeValue());
  1280. } else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
  1281. .PeerConnectionEventType.AUDIO_CHANGE)) {
  1282. gotAudioOrVideoChange(false, peerConnectionEvent.getSessionId(),
  1283. peerConnectionEvent.getChangeValue());
  1284. }
  1285. }
  1286. @Subscribe(threadMode = ThreadMode.MAIN)
  1287. public void onMessageEvent(MediaStreamEvent mediaStreamEvent) {
  1288. if (mediaStreamEvent.getMediaStream() != null) {
  1289. setupVideoStreamForLayout(mediaStreamEvent.getMediaStream(), mediaStreamEvent.getSession(),
  1290. mediaStreamEvent.getMediaStream().videoTracks != null
  1291. && mediaStreamEvent.getMediaStream().videoTracks.size() > 0);
  1292. } else {
  1293. setupVideoStreamForLayout(null, mediaStreamEvent.getSession(), false);
  1294. }
  1295. }
  1296. @Subscribe(threadMode = ThreadMode.BACKGROUND)
  1297. public void onMessageEvent(SessionDescriptionSendEvent sessionDescriptionSend) throws IOException {
  1298. NCMessageWrapper ncMessageWrapper = new NCMessageWrapper();
  1299. ncMessageWrapper.setEv("message");
  1300. ncMessageWrapper.setSessionId(callSession);
  1301. NCSignalingMessage ncSignalingMessage = new NCSignalingMessage();
  1302. ncSignalingMessage.setTo(sessionDescriptionSend.getPeerId());
  1303. ncSignalingMessage.setRoomType("video");
  1304. ncSignalingMessage.setType(sessionDescriptionSend.getType());
  1305. NCMessagePayload ncMessagePayload = new NCMessagePayload();
  1306. ncMessagePayload.setType(sessionDescriptionSend.getType());
  1307. if (!"candidate".equals(sessionDescriptionSend.getType())) {
  1308. ncMessagePayload.setSdp(sessionDescriptionSend.getSessionDescription().description);
  1309. ncMessagePayload.setNick(conversationUser.getDisplayName());
  1310. } else {
  1311. ncMessagePayload.setIceCandidate(sessionDescriptionSend.getNcIceCandidate());
  1312. }
  1313. // Set all we need
  1314. ncSignalingMessage.setPayload(ncMessagePayload);
  1315. ncMessageWrapper.setSignalingMessage(ncSignalingMessage);
  1316. StringBuilder stringBuilder = new StringBuilder();
  1317. stringBuilder.append("{")
  1318. .append("\"fn\":\"")
  1319. .append(StringEscapeUtils.escapeJson(LoganSquare.serialize(ncMessageWrapper.getSignalingMessage()))).append("\"")
  1320. .append(",")
  1321. .append("\"sessionId\":")
  1322. .append("\"").append(StringEscapeUtils.escapeJson(callSession)).append("\"")
  1323. .append(",")
  1324. .append("\"ev\":\"message\"")
  1325. .append("}");
  1326. List<String> strings = new ArrayList<>();
  1327. String stringToSend = stringBuilder.toString();
  1328. strings.add(stringToSend);
  1329. String urlToken = null;
  1330. if (isMultiSession) {
  1331. urlToken = roomToken;
  1332. }
  1333. ncApi.sendSignalingMessages(credentials, ApiUtils.getUrlForSignaling(baseUrl, urlToken),
  1334. strings.toString())
  1335. .retry(3)
  1336. .subscribeOn(Schedulers.newThread())
  1337. .subscribe(new Observer<SignalingOverall>() {
  1338. @Override
  1339. public void onSubscribe(Disposable d) {
  1340. }
  1341. @Override
  1342. public void onNext(SignalingOverall signalingOverall) {
  1343. if (signalingOverall.getOcs().getSignalings() != null) {
  1344. for (int i = 0; i < signalingOverall.getOcs().getSignalings().size(); i++) {
  1345. try {
  1346. receivedSignalingMessage(signalingOverall.getOcs().getSignalings().get(i));
  1347. } catch (IOException e) {
  1348. e.printStackTrace();
  1349. }
  1350. }
  1351. }
  1352. }
  1353. @Override
  1354. public void onError(Throwable e) {
  1355. }
  1356. @Override
  1357. public void onComplete() {
  1358. }
  1359. });
  1360. }
  1361. @Override
  1362. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
  1363. @NonNull int[] grantResults) {
  1364. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  1365. EffortlessPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults,
  1366. this);
  1367. }
  1368. private void setupAvatarForSession(String session) {
  1369. if (remoteRenderersLayout != null) {
  1370. RelativeLayout relativeLayout = remoteRenderersLayout.findViewWithTag(session);
  1371. if (relativeLayout != null) {
  1372. ImageView avatarImageView = relativeLayout.findViewById(R.id.avatarImageView);
  1373. if (participantMap.containsKey(session) && avatarImageView.getDrawable() == null) {
  1374. int size = Math.round(getResources().getDimension(R.dimen.avatar_size_big));
  1375. if (getActivity() != null) {
  1376. GlideApp.with(getActivity())
  1377. .asBitmap()
  1378. .diskCacheStrategy(DiskCacheStrategy.NONE)
  1379. .load(ApiUtils.getUrlForAvatarWithName(baseUrl, participantMap.get(session).getUserId(), R.dimen.avatar_size_big))
  1380. .centerInside()
  1381. .override(size, size)
  1382. .apply(RequestOptions.bitmapTransform(new CircleCrop()))
  1383. .into(avatarImageView);
  1384. }
  1385. }
  1386. }
  1387. }
  1388. }
  1389. private void setupVideoStreamForLayout(@Nullable MediaStream mediaStream, String session, boolean enable) {
  1390. boolean isInitialLayoutSetupForPeer = false;
  1391. if (remoteRenderersLayout.findViewWithTag(session) == null) {
  1392. setupNewPeerLayout(session);
  1393. isInitialLayoutSetupForPeer = true;
  1394. }
  1395. RelativeLayout relativeLayout = remoteRenderersLayout.findViewWithTag(session);
  1396. SurfaceViewRenderer surfaceViewRenderer = relativeLayout.findViewById(R.id.surface_view);
  1397. ImageView imageView = relativeLayout.findViewById(R.id.avatarImageView);
  1398. if (mediaStream != null && mediaStream.videoTracks != null && mediaStream.videoTracks.size() > 0 && enable) {
  1399. VideoTrack videoTrack = mediaStream.videoTracks.get(0);
  1400. videoTrack.addSink(surfaceViewRenderer);
  1401. imageView.setVisibility(View.INVISIBLE);
  1402. surfaceViewRenderer.setVisibility(View.VISIBLE);
  1403. } else {
  1404. imageView.setVisibility(View.VISIBLE);
  1405. surfaceViewRenderer.setVisibility(View.INVISIBLE);
  1406. if (isInitialLayoutSetupForPeer && isVoiceOnlyCall) {
  1407. gotAudioOrVideoChange(true, session, false);
  1408. }
  1409. }
  1410. callControls.setZ(100.0f);
  1411. }
  1412. private void gotAudioOrVideoChange(boolean video, String sessionId, boolean change) {
  1413. RelativeLayout relativeLayout = remoteRenderersLayout.findViewWithTag(sessionId);
  1414. if (relativeLayout != null) {
  1415. ImageView imageView;
  1416. ImageView avatarImageView = relativeLayout.findViewById(R.id.avatarImageView);
  1417. SurfaceViewRenderer surfaceViewRenderer = relativeLayout.findViewById(R.id.surface_view);
  1418. if (video) {
  1419. imageView = relativeLayout.findViewById(R.id.remote_video_off);
  1420. if (change) {
  1421. avatarImageView.setVisibility(View.INVISIBLE);
  1422. surfaceViewRenderer.setVisibility(View.VISIBLE);
  1423. } else {
  1424. avatarImageView.setVisibility(View.VISIBLE);
  1425. surfaceViewRenderer.setVisibility(View.INVISIBLE);
  1426. }
  1427. } else {
  1428. imageView = relativeLayout.findViewById(R.id.remote_audio_off);
  1429. }
  1430. if (change && imageView.getVisibility() != View.INVISIBLE) {
  1431. imageView.setVisibility(View.INVISIBLE);
  1432. } else if (!change && imageView.getVisibility() != View.VISIBLE) {
  1433. imageView.setVisibility(View.VISIBLE);
  1434. }
  1435. }
  1436. }
  1437. private void setupNewPeerLayout(String session) {
  1438. if (remoteRenderersLayout.findViewWithTag(session) == null && getActivity() != null) {
  1439. getActivity().runOnUiThread(() -> {
  1440. RelativeLayout relativeLayout = (RelativeLayout)
  1441. getActivity().getLayoutInflater().inflate(R.layout.call_item, remoteRenderersLayout,
  1442. false);
  1443. relativeLayout.setTag(session);
  1444. SurfaceViewRenderer surfaceViewRenderer = relativeLayout.findViewById(R.id
  1445. .surface_view);
  1446. surfaceViewRenderer.setMirror(false);
  1447. surfaceViewRenderer.init(rootEglBase.getEglBaseContext(), null);
  1448. surfaceViewRenderer.setZOrderMediaOverlay(false);
  1449. // disabled because it causes some devices to crash
  1450. surfaceViewRenderer.setEnableHardwareScaler(false);
  1451. surfaceViewRenderer.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT);
  1452. surfaceViewRenderer.setOnClickListener(videoOnClickListener);
  1453. remoteRenderersLayout.addView(relativeLayout);
  1454. gotNick(session, getPeerConnectionWrapperForSessionId(session).getNick());
  1455. setupAvatarForSession(session);
  1456. callControls.setZ(100.0f);
  1457. });
  1458. }
  1459. }
  1460. private void gotNick(String sessionId, String nick) {
  1461. RelativeLayout relativeLayout = remoteRenderersLayout.findViewWithTag(sessionId);
  1462. if (relativeLayout != null) {
  1463. TextView textView = relativeLayout.findViewById(R.id.peer_nick_text_view);
  1464. textView.setText(nick);
  1465. }
  1466. }
  1467. @Override
  1468. protected void onAttach(@NonNull View view) {
  1469. super.onAttach(view);
  1470. eventBus.register(this);
  1471. }
  1472. @Override
  1473. protected void onDetach(@NonNull View view) {
  1474. super.onDetach(view);
  1475. eventBus.unregister(this);
  1476. }
  1477. private class MicrophoneButtonTouchListener implements View.OnTouchListener {
  1478. @SuppressLint("ClickableViewAccessibility")
  1479. @Override
  1480. public boolean onTouch(View v, MotionEvent event) {
  1481. v.onTouchEvent(event);
  1482. if (event.getAction() == MotionEvent.ACTION_UP && isPTTActive) {
  1483. isPTTActive = false;
  1484. microphoneControlButton.getFrontImageView().setImageResource(R.drawable.ic_mic_off_white_24px);
  1485. pulseAnimation.stop();
  1486. toggleMedia(false, false);
  1487. animateCallControls(false, 5000);
  1488. }
  1489. return true;
  1490. }
  1491. }
  1492. private class VideoClickListener implements View.OnClickListener {
  1493. @Override
  1494. public void onClick(View v) {
  1495. showCallControls();
  1496. }
  1497. }
  1498. }