CallController.java 72 KB

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