CallActivity.java 118 KB

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