CallActivity.java 114 KB

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