CallActivity.java 121 KB

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