CallActivity.java 114 KB

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