CallActivity.java 135 KB

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