CallActivity.java 122 KB

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