CallActivity.java 121 KB

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