CallActivity.java 120 KB

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