CallActivity.java 114 KB

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