123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773 |
- /*
- * Nextcloud Talk application
- *
- * @author Mario Danic
- * Copyright (C) 2017-2018 Mario Danic <mario@lovelyhq.com>
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
- package com.nextcloud.talk.controllers;
- import android.Manifest;
- import android.animation.Animator;
- import android.animation.AnimatorListenerAdapter;
- import android.annotation.SuppressLint;
- import android.content.res.Configuration;
- import android.graphics.Color;
- import android.os.Build;
- import android.os.Bundle;
- import android.os.Handler;
- import android.support.annotation.NonNull;
- import android.support.annotation.Nullable;
- import android.support.v7.app.AppCompatActivity;
- import android.text.TextUtils;
- import android.util.Log;
- import android.view.LayoutInflater;
- import android.view.MotionEvent;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.ImageView;
- import android.widget.LinearLayout;
- import android.widget.RelativeLayout;
- import android.widget.TextView;
- import com.bluelinelabs.logansquare.LoganSquare;
- import com.bumptech.glide.load.engine.DiskCacheStrategy;
- import com.bumptech.glide.load.resource.bitmap.CircleCrop;
- import com.bumptech.glide.request.RequestOptions;
- import com.nextcloud.talk.R;
- import com.nextcloud.talk.api.NcApi;
- import com.nextcloud.talk.application.NextcloudTalkApplication;
- import com.nextcloud.talk.controllers.base.BaseController;
- import com.nextcloud.talk.events.ConfigurationChangeEvent;
- import com.nextcloud.talk.events.MediaStreamEvent;
- import com.nextcloud.talk.events.PeerConnectionEvent;
- import com.nextcloud.talk.events.SessionDescriptionSendEvent;
- import com.nextcloud.talk.models.database.UserEntity;
- import com.nextcloud.talk.models.json.call.CallOverall;
- import com.nextcloud.talk.models.json.capabilities.CapabilitiesOverall;
- import com.nextcloud.talk.models.json.generic.GenericOverall;
- import com.nextcloud.talk.models.json.participants.Participant;
- import com.nextcloud.talk.models.json.participants.ParticipantsOverall;
- import com.nextcloud.talk.models.json.rooms.Conversation;
- import com.nextcloud.talk.models.json.rooms.RoomsOverall;
- import com.nextcloud.talk.models.json.signaling.DataChannelMessage;
- import com.nextcloud.talk.models.json.signaling.NCIceCandidate;
- import com.nextcloud.talk.models.json.signaling.NCMessagePayload;
- import com.nextcloud.talk.models.json.signaling.NCMessageWrapper;
- import com.nextcloud.talk.models.json.signaling.NCSignalingMessage;
- import com.nextcloud.talk.models.json.signaling.Signaling;
- import com.nextcloud.talk.models.json.signaling.SignalingOverall;
- import com.nextcloud.talk.models.json.signaling.settings.IceServer;
- import com.nextcloud.talk.models.json.signaling.settings.SignalingSettingsOverall;
- import com.nextcloud.talk.utils.ApiUtils;
- import com.nextcloud.talk.utils.MagicFlipView;
- import com.nextcloud.talk.utils.NotificationUtils;
- import com.nextcloud.talk.utils.animations.PulseAnimation;
- import com.nextcloud.talk.utils.bundle.BundleKeys;
- import com.nextcloud.talk.utils.database.user.UserUtils;
- import com.nextcloud.talk.utils.glide.GlideApp;
- import com.nextcloud.talk.utils.preferences.AppPreferences;
- import com.nextcloud.talk.utils.singletons.ApplicationWideCurrentRoomHolder;
- import com.nextcloud.talk.webrtc.MagicAudioManager;
- import com.nextcloud.talk.webrtc.MagicPeerConnectionWrapper;
- import com.nextcloud.talk.webrtc.MagicWebRTCUtils;
- import com.wooplr.spotlight.SpotlightView;
- import org.apache.commons.lang3.StringEscapeUtils;
- import org.greenrobot.eventbus.EventBus;
- import org.greenrobot.eventbus.Subscribe;
- import org.greenrobot.eventbus.ThreadMode;
- import org.parceler.Parcels;
- import org.webrtc.AudioSource;
- import org.webrtc.AudioTrack;
- import org.webrtc.Camera1Enumerator;
- import org.webrtc.Camera2Enumerator;
- import org.webrtc.CameraEnumerator;
- import org.webrtc.CameraVideoCapturer;
- import org.webrtc.EglBase;
- import org.webrtc.IceCandidate;
- import org.webrtc.Logging;
- import org.webrtc.MediaConstraints;
- import org.webrtc.MediaStream;
- import org.webrtc.PeerConnection;
- import org.webrtc.PeerConnectionFactory;
- import org.webrtc.RendererCommon;
- import org.webrtc.SessionDescription;
- import org.webrtc.SurfaceViewRenderer;
- import org.webrtc.VideoCapturer;
- import org.webrtc.VideoSource;
- import org.webrtc.VideoTrack;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Map;
- import java.util.Set;
- import java.util.concurrent.TimeUnit;
- import javax.inject.Inject;
- import autodagger.AutoInjector;
- import butterknife.BindView;
- import butterknife.OnClick;
- import butterknife.OnLongClick;
- import eu.davidea.flipview.FlipView;
- import io.reactivex.Observer;
- import io.reactivex.android.schedulers.AndroidSchedulers;
- import io.reactivex.disposables.Disposable;
- import io.reactivex.schedulers.Schedulers;
- import me.zhanghai.android.effortlesspermissions.AfterPermissionDenied;
- import me.zhanghai.android.effortlesspermissions.EffortlessPermissions;
- import me.zhanghai.android.effortlesspermissions.OpenAppDetailsDialogFragment;
- import okhttp3.Cache;
- import pub.devrel.easypermissions.AfterPermissionGranted;
- @AutoInjector(NextcloudTalkApplication.class)
- public class CallController extends BaseController {
- private static final String TAG = "CallController";
- private static final String[] PERMISSIONS_CALL = {
- android.Manifest.permission.CAMERA,
- android.Manifest.permission.RECORD_AUDIO,
- };
- private static final String[] PERMISSIONS_CAMERA = {
- Manifest.permission.CAMERA
- };
- private static final String[] PERMISSIONS_MICROPHONE = {
- Manifest.permission.RECORD_AUDIO
- };
- @BindView(R.id.callControlEnableSpeaker)
- MagicFlipView callControlEnableSpeaker;
- @BindView(R.id.pip_video_view)
- SurfaceViewRenderer pipVideoView;
- @BindView(R.id.relative_layout)
- RelativeLayout relativeLayout;
- @BindView(R.id.remote_renderers_layout)
- LinearLayout remoteRenderersLayout;
- @BindView(R.id.callControlsLinearLayoutView)
- LinearLayout callControls;
- @BindView(R.id.call_control_microphone)
- FlipView microphoneControlButton;
- @BindView(R.id.call_control_camera)
- FlipView cameraControlButton;
- @BindView(R.id.call_control_switch_camera)
- FlipView cameraSwitchButton;
- @BindView(R.id.connectingTextView)
- TextView connectingTextView;
- @BindView(R.id.connectingRelativeLayoutView)
- RelativeLayout connectingView;
- @BindView(R.id.conversationRelativeLayoutView)
- RelativeLayout conversationView;
- @Inject
- NcApi ncApi;
- @Inject
- EventBus eventBus;
- @Inject
- UserUtils userUtils;
- @Inject
- AppPreferences appPreferences;
- @Inject
- Cache cache;
- private PeerConnectionFactory peerConnectionFactory;
- private MediaConstraints audioConstraints;
- private MediaConstraints videoConstraints;
- private MediaConstraints sdpConstraints;
- private MagicAudioManager audioManager;
- private VideoSource videoSource;
- private VideoTrack localVideoTrack;
- private AudioSource audioSource;
- private AudioTrack localAudioTrack;
- private VideoCapturer videoCapturer;
- private EglBase rootEglBase;
- private boolean leavingCall = false;
- private boolean inCall = false;
- private Disposable signalingDisposable;
- private Disposable pingDisposable;
- private List<PeerConnection.IceServer> iceServers;
- private CameraEnumerator cameraEnumerator;
- private String roomToken;
- private UserEntity conversationUser;
- private String callSession;
- private MediaStream localMediaStream;
- private String credentials;
- private List<MagicPeerConnectionWrapper> magicPeerConnectionWrapperList = new ArrayList<>();
- private Map<String, Participant> participantMap = new HashMap<>();
- private boolean videoOn = false;
- private boolean audioOn = false;
- private boolean isMultiSession = false;
- private boolean needsPing = true;
- private boolean isVoiceOnlyCall;
- private boolean isFromNotification;
- private Handler callControlHandler = new Handler();
- private Handler cameraSwitchHandler = new Handler();
- private boolean isPTTActive = false;
- private PulseAnimation pulseAnimation;
- private View.OnClickListener videoOnClickListener;
- private String baseUrl;
- private String roomId;
- private SpotlightView spotlightView;
- public CallController(Bundle args) {
- super(args);
- NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
- roomId = args.getString(BundleKeys.KEY_ROOM_ID, "");
- roomToken = args.getString(BundleKeys.KEY_ROOM_TOKEN, "");
- conversationUser = Parcels.unwrap(args.getParcelable(BundleKeys.KEY_USER_ENTITY));
- if (conversationUser == null) {
- conversationUser = userUtils.getCurrentUser();
- }
- callSession = args.getString(BundleKeys.KEY_CALL_SESSION, "0");
- credentials = ApiUtils.getCredentials(conversationUser.getUsername(), conversationUser.getToken());
- isVoiceOnlyCall = args.getBoolean(BundleKeys.KEY_CALL_VOICE_ONLY, false);
- if (conversationUser.getUserId().equals("?")) {
- credentials = null;
- }
- baseUrl = args.getString(BundleKeys.KEY_MODIFIED_BASE_URL, "");
- if (TextUtils.isEmpty(baseUrl)) {
- baseUrl = conversationUser.getBaseUrl();
- }
- isFromNotification = TextUtils.isEmpty(roomToken);
- }
- @Override
- protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
- return inflater.inflate(R.layout.controller_call, container, false);
- }
- private void createCameraEnumerator() {
- if (getActivity() != null) {
- boolean camera2EnumeratorIsSupported = false;
- try {
- camera2EnumeratorIsSupported = Camera2Enumerator.isSupported(getActivity());
- } catch (final Throwable throwable) {
- Log.w(TAG, "Camera2Enumator threw an error");
- }
- if (camera2EnumeratorIsSupported) {
- cameraEnumerator = new Camera2Enumerator(getActivity());
- } else {
- cameraEnumerator = new Camera1Enumerator(MagicWebRTCUtils.shouldEnableVideoHardwareAcceleration());
- }
- }
- }
- @Override
- protected void onViewBound(@NonNull View view) {
- super.onViewBound(view);
- microphoneControlButton.setOnTouchListener(new MicrophoneButtonTouchListener());
- videoOnClickListener = new VideoClickListener();
- pulseAnimation = PulseAnimation.create().with(microphoneControlButton.getFrontImageView())
- .setDuration(310)
- .setRepeatCount(PulseAnimation.INFINITE)
- .setRepeatMode(PulseAnimation.REVERSE);
- try {
- cache.evictAll();
- } catch (IOException e) {
- Log.e(TAG, "Failed to evict cache");
- }
- if (isVoiceOnlyCall) {
- callControlEnableSpeaker.setVisibility(View.VISIBLE);
- }
- callControls.setZ(100.0f);
- basicInitialization();
- if (isFromNotification) {
- handleFromNotification();
- } else {
- initViews();
- checkPermissions();
- }
- }
- private void basicInitialization() {
- rootEglBase = EglBase.create();
- createCameraEnumerator();
- //Create a new PeerConnectionFactory instance.
- PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
- peerConnectionFactory = PeerConnectionFactory.builder().createPeerConnectionFactory();
- peerConnectionFactory.setVideoHwAccelerationOptions(rootEglBase.getEglBaseContext(),
- rootEglBase.getEglBaseContext());
- //Create MediaConstraints - Will be useful for specifying video and audio constraints.
- audioConstraints = new MediaConstraints();
- videoConstraints = new MediaConstraints();
- localMediaStream = peerConnectionFactory.createLocalMediaStream("NCMS");
- // Create and audio manager that will take care of audio routing,
- // audio modes, audio device enumeration etc.
- audioManager = MagicAudioManager.create(getApplicationContext(), !isVoiceOnlyCall);
- // Store existing audio settings and change audio mode to
- // MODE_IN_COMMUNICATION for best possible VoIP performance.
- Log.d(TAG, "Starting the audio manager...");
- audioManager.start(this::onAudioManagerDevicesChanged);
- iceServers = new ArrayList<>();
- //create sdpConstraints
- sdpConstraints = new MediaConstraints();
- sdpConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"));
- String offerToReceiveVideoString = "true";
- if (isVoiceOnlyCall) {
- offerToReceiveVideoString = "false";
- }
- sdpConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo",
- offerToReceiveVideoString));
- sdpConstraints.optional.add(new MediaConstraints.KeyValuePair("internalSctpDataChannels", "true"));
- sdpConstraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));
- if (!isVoiceOnlyCall) {
- cameraInitialization();
- }
- microphoneInitialization();
- }
- private void handleFromNotification() {
- ncApi.getRooms(credentials, ApiUtils.getUrlForGetRooms(baseUrl))
- .retry(3)
- .subscribeOn(Schedulers.newThread())
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe(new Observer<RoomsOverall>() {
- @Override
- public void onSubscribe(Disposable d) {
- }
- @Override
- public void onNext(RoomsOverall roomsOverall) {
- for (Conversation conversation : roomsOverall.getOcs().getData()) {
- if (roomId.equals(conversation.getRoomId())) {
- roomToken = conversation.getToken();
- break;
- }
- }
- initViews();
- checkPermissions();
- }
- @Override
- public void onError(Throwable e) {
- }
- @Override
- public void onComplete() {
- }
- });
- }
- private void initViews() {
- if (isVoiceOnlyCall) {
- cameraSwitchButton.setVisibility(View.GONE);
- cameraControlButton.setVisibility(View.GONE);
- pipVideoView.setVisibility(View.GONE);
- } else {
- if (cameraEnumerator.getDeviceNames().length < 2) {
- cameraSwitchButton.setVisibility(View.GONE);
- }
- // setting this to true because it's not shown by default
- pipVideoView.setMirror(false);
- pipVideoView.init(rootEglBase.getEglBaseContext(), null);
- pipVideoView.setZOrderMediaOverlay(true);
- // disabled because it causes some devices to crash
- pipVideoView.setEnableHardwareScaler(false);
- pipVideoView.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT);
- }
- }
- private void checkPermissions() {
- if (isVoiceOnlyCall) {
- onMicrophoneClick();
- } else if (getActivity() != null) {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
- requestPermissions(PERMISSIONS_CALL, 100);
- } else {
- onRequestPermissionsResult(100, PERMISSIONS_CALL, new int[]{1, 1});
- }
- }
- }
- @AfterPermissionGranted(100)
- private void onPermissionsGranted() {
- if (EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_CALL)) {
- if (!videoOn && !isVoiceOnlyCall) {
- onCameraClick();
- }
- if (!audioOn) {
- onMicrophoneClick();
- }
- if (!isVoiceOnlyCall) {
- if (cameraEnumerator.getDeviceNames().length == 0) {
- cameraControlButton.setVisibility(View.GONE);
- }
- if (cameraEnumerator.getDeviceNames().length > 1) {
- cameraSwitchButton.setVisibility(View.VISIBLE);
- }
- }
- if (!inCall) {
- startCall();
- }
- } else if (getActivity() != null && EffortlessPermissions.somePermissionPermanentlyDenied(getActivity(),
- PERMISSIONS_CALL)) {
- checkIfSomeAreApproved();
- }
- }
- private void checkIfSomeAreApproved() {
- if (!isVoiceOnlyCall) {
- if (cameraEnumerator.getDeviceNames().length == 0) {
- cameraControlButton.setVisibility(View.GONE);
- }
- if (cameraEnumerator.getDeviceNames().length > 1) {
- cameraSwitchButton.setVisibility(View.VISIBLE);
- }
- if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_CAMERA)) {
- if (!videoOn) {
- onCameraClick();
- }
- } else {
- cameraControlButton.getFrontImageView().setImageResource(R.drawable.ic_videocam_off_white_24px);
- cameraControlButton.setAlpha(0.7f);
- cameraSwitchButton.setVisibility(View.GONE);
- }
- }
- if (EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_MICROPHONE)) {
- if (!audioOn) {
- onMicrophoneClick();
- }
- } else {
- microphoneControlButton.getFrontImageView().setImageResource(R.drawable.ic_mic_off_white_24px);
- }
- if (!inCall) {
- startCall();
- }
- }
- @AfterPermissionDenied(100)
- private void onPermissionsDenied() {
- if (!isVoiceOnlyCall) {
- if (cameraEnumerator.getDeviceNames().length == 0) {
- cameraControlButton.setVisibility(View.GONE);
- } else if (cameraEnumerator.getDeviceNames().length == 1) {
- cameraSwitchButton.setVisibility(View.GONE);
- }
- }
- if (getActivity() != null && (EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_CAMERA) ||
- EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_MICROPHONE))) {
- checkIfSomeAreApproved();
- } else if (!inCall) {
- startCall();
- }
- }
- private void onAudioManagerDevicesChanged(
- final MagicAudioManager.AudioDevice device, final Set<MagicAudioManager.AudioDevice> availableDevices) {
- Log.d(TAG, "onAudioManagerDevicesChanged: " + availableDevices + ", "
- + "selected: " + device);
- }
- private void cameraInitialization() {
- videoCapturer = createCameraCapturer(cameraEnumerator);
- //Create a VideoSource instance
- if (videoCapturer != null) {
- videoSource = peerConnectionFactory.createVideoSource(videoCapturer);
- localVideoTrack = peerConnectionFactory.createVideoTrack("NCv0", videoSource);
- localMediaStream.addTrack(localVideoTrack);
- localVideoTrack.setEnabled(false);
- localVideoTrack.addSink(pipVideoView);
- }
- }
- private void microphoneInitialization() {
- //create an AudioSource instance
- audioSource = peerConnectionFactory.createAudioSource(audioConstraints);
- localAudioTrack = peerConnectionFactory.createAudioTrack("NCa0", audioSource);
- localAudioTrack.setEnabled(false);
- localMediaStream.addTrack(localAudioTrack);
- }
- private VideoCapturer createCameraCapturer(CameraEnumerator enumerator) {
- final String[] deviceNames = enumerator.getDeviceNames();
- // First, try to find front facing camera
- Logging.d(TAG, "Looking for front facing cameras.");
- for (String deviceName : deviceNames) {
- if (enumerator.isFrontFacing(deviceName)) {
- Logging.d(TAG, "Creating front facing camera capturer.");
- VideoCapturer videoCapturer = enumerator.createCapturer(deviceName, null);
- if (videoCapturer != null) {
- return videoCapturer;
- }
- }
- }
- // Front facing camera not found, try something else
- Logging.d(TAG, "Looking for other cameras.");
- for (String deviceName : deviceNames) {
- if (!enumerator.isFrontFacing(deviceName)) {
- Logging.d(TAG, "Creating other camera capturer.");
- VideoCapturer videoCapturer = enumerator.createCapturer(deviceName, null);
- if (videoCapturer != null) {
- pipVideoView.setMirror(false);
- return videoCapturer;
- }
- }
- }
- return null;
- }
- @OnLongClick(R.id.call_control_microphone)
- public boolean onMicrophoneLongClick() {
- if (!audioOn) {
- callControlHandler.removeCallbacksAndMessages(null);
- cameraSwitchHandler.removeCallbacksAndMessages(null);
- isPTTActive = true;
- callControls.setVisibility(View.VISIBLE);
- cameraSwitchButton.setVisibility(View.VISIBLE);
- }
- onMicrophoneClick();
- return true;
- }
- @OnClick(R.id.callControlEnableSpeaker)
- public void onEnableSpeakerphoneClick() {
- if (audioManager != null) {
- audioManager.toggleUseSpeakerphone();
- callControlEnableSpeaker.flipSilently(!callControlEnableSpeaker.isFlipped());
- }
- }
- @OnClick(R.id.call_control_microphone)
- public void onMicrophoneClick() {
- if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_MICROPHONE)) {
- if (getActivity() != null && !appPreferences.getPushToTalkIntroShown()) {
- spotlightView = new SpotlightView.Builder(getActivity())
- .introAnimationDuration(300)
- .enableRevealAnimation(true)
- .performClick(false)
- .fadeinTextDuration(400)
- .headingTvColor(getResources().getColor(R.color.colorPrimary))
- .headingTvSize(20)
- .headingTvText(getResources().getString(R.string.nc_push_to_talk))
- .subHeadingTvColor(getResources().getColor(R.color.white))
- .subHeadingTvSize(16)
- .subHeadingTvText(getResources().getString(R.string.nc_push_to_talk_desc))
- .maskColor(Color.parseColor("#dc000000"))
- .target(microphoneControlButton)
- .lineAnimDuration(400)
- .lineAndArcColor(getResources().getColor(R.color.colorPrimary))
- .enableDismissAfterShown(true)
- .dismissOnBackPress(true)
- .usageId("pushToTalk")
- .show();
- appPreferences.setPushToTalkIntroShown(true);
- }
- if (!isPTTActive) {
- audioOn = !audioOn;
- if (audioOn) {
- microphoneControlButton.getFrontImageView().setImageResource(R.drawable.ic_mic_white_24px);
- } else {
- microphoneControlButton.getFrontImageView().setImageResource(R.drawable.ic_mic_off_white_24px);
- }
- toggleMedia(audioOn, false);
- } else {
- microphoneControlButton.getFrontImageView().setImageResource(R.drawable.ic_mic_white_24px);
- pulseAnimation.start();
- toggleMedia(true, false);
- }
- if (isVoiceOnlyCall && !inCall) {
- startCall();
- }
- } else if (getActivity() != null && EffortlessPermissions.somePermissionPermanentlyDenied(getActivity(),
- PERMISSIONS_MICROPHONE)) {
- // Microphone permission is permanently denied so we cannot request it normally.
- OpenAppDetailsDialogFragment.show(
- R.string.nc_microphone_permission_permanently_denied,
- R.string.nc_permissions_settings, (AppCompatActivity) getActivity());
- } else {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
- requestPermissions(PERMISSIONS_MICROPHONE, 100);
- } else {
- onRequestPermissionsResult(100, PERMISSIONS_MICROPHONE, new int[]{1});
- }
- }
- }
- @OnClick(R.id.callControlHangupView)
- public void onHangupClick() {
- if (inCall) {
- hangup(false);
- } else {
- hangup(true);
- }
- }
- @OnClick(R.id.call_control_camera)
- public void onCameraClick() {
- if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_CAMERA)) {
- videoOn = !videoOn;
- if (videoOn) {
- cameraControlButton.getFrontImageView().setImageResource(R.drawable.ic_videocam_white_24px);
- if (cameraEnumerator.getDeviceNames().length > 1) {
- cameraSwitchButton.setVisibility(View.VISIBLE);
- }
- } else {
- cameraControlButton.getFrontImageView().setImageResource(R.drawable.ic_videocam_off_white_24px);
- cameraSwitchButton.setVisibility(View.GONE);
- }
- toggleMedia(videoOn, true);
- } else if (getActivity() != null && EffortlessPermissions.somePermissionPermanentlyDenied(getActivity(),
- PERMISSIONS_CAMERA)) {
- // Camera permission is permanently denied so we cannot request it normally.
- OpenAppDetailsDialogFragment.show(
- R.string.nc_camera_permission_permanently_denied,
- R.string.nc_permissions_settings, (AppCompatActivity) getActivity());
- } else {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
- requestPermissions(PERMISSIONS_CAMERA, 100);
- } else {
- onRequestPermissionsResult(100, PERMISSIONS_CAMERA, new int[]{1});
- }
- }
- }
- @OnClick(R.id.call_control_switch_camera)
- public void switchCamera() {
- CameraVideoCapturer cameraVideoCapturer = (CameraVideoCapturer) videoCapturer;
- if (cameraVideoCapturer != null) {
- cameraVideoCapturer.switchCamera(new CameraVideoCapturer.CameraSwitchHandler() {
- @Override
- public void onCameraSwitchDone(boolean b) {
- pipVideoView.setMirror(false);
- }
- @Override
- public void onCameraSwitchError(String s) {
- }
- });
- }
- }
- private void toggleMedia(boolean enable, boolean video) {
- String message;
- if (video) {
- message = "videoOff";
- if (enable) {
- cameraControlButton.setAlpha(1.0f);
- message = "videoOn";
- startVideoCapture();
- } else {
- cameraControlButton.setAlpha(0.7f);
- if (videoCapturer != null) {
- try {
- videoCapturer.stopCapture();
- } catch (InterruptedException e) {
- Log.d(TAG, "Failed to stop capturing video while sensor is near the ear");
- }
- }
- }
- if (localMediaStream != null && localMediaStream.videoTracks.size() > 0) {
- localMediaStream.videoTracks.get(0).setEnabled(enable);
- }
- if (enable) {
- pipVideoView.setVisibility(View.VISIBLE);
- } else {
- pipVideoView.setVisibility(View.INVISIBLE);
- }
- } else {
- message = "audioOff";
- if (enable) {
- message = "audioOn";
- microphoneControlButton.setAlpha(1.0f);
- } else {
- microphoneControlButton.setAlpha(0.7f);
- }
- if (localMediaStream != null && localMediaStream.audioTracks.size() > 0) {
- localMediaStream.audioTracks.get(0).setEnabled(enable);
- }
- }
- if (inCall) {
- for (int i = 0; i < magicPeerConnectionWrapperList.size(); i++) {
- magicPeerConnectionWrapperList.get(i).sendChannelData(new DataChannelMessage(message));
- }
- }
- }
- private void startCall() {
- startPullingSignalingMessages();
- }
- private void animateCallControls(boolean show, long startDelay) {
- if (isVoiceOnlyCall) {
- if (spotlightView != null && spotlightView.getVisibility() != View.GONE) {
- spotlightView.setVisibility(View.GONE);
- }
- } else if (!isPTTActive) {
- float alpha;
- long duration;
- if (show) {
- callControlHandler.removeCallbacksAndMessages(null);
- cameraSwitchHandler.removeCallbacksAndMessages(null);
- alpha = 1.0f;
- duration = 1000;
- if (callControls.getVisibility() != View.VISIBLE) {
- callControls.setAlpha(0.0f);
- callControls.setVisibility(View.VISIBLE);
- cameraSwitchButton.setAlpha(0.0f);
- cameraSwitchButton.setVisibility(View.VISIBLE);
- } else {
- callControlHandler.postDelayed(() -> animateCallControls(false, 0), 5000);
- return;
- }
- } else {
- alpha = 0.0f;
- duration = 1000;
- }
- if (callControls != null) {
- callControls.setEnabled(false);
- callControls.animate()
- .translationY(0)
- .alpha(alpha)
- .setDuration(duration)
- .setStartDelay(startDelay)
- .setListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- super.onAnimationEnd(animation);
- if (callControls != null) {
- if (!show) {
- callControls.setVisibility(View.GONE);
- if (spotlightView != null && spotlightView.getVisibility() != View.GONE) {
- spotlightView.setVisibility(View.GONE);
- }
- } else {
- callControlHandler.postDelayed(new Runnable() {
- @Override
- public void run() {
- if (!isPTTActive) {
- animateCallControls(false, 0);
- }
- }
- }, 7500);
- }
- callControls.setEnabled(true);
- }
- }
- });
- }
- if (cameraSwitchButton != null) {
- cameraSwitchButton.setEnabled(false);
- cameraSwitchButton.animate()
- .translationY(0)
- .alpha(alpha)
- .setDuration(duration)
- .setStartDelay(startDelay)
- .setListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- super.onAnimationEnd(animation);
- if (cameraSwitchButton != null) {
- if (!show) {
- cameraSwitchButton.setVisibility(View.GONE);
- }
- cameraSwitchButton.setEnabled(true);
- }
- }
- });
- }
- }
- }
- @Override
- public void onDestroy() {
- onHangupClick();
- super.onDestroy();
- }
- private void startPullingSignalingMessages() {
- leavingCall = false;
- ncApi.getSignalingSettings(credentials, ApiUtils.getUrlForSignalingSettings(baseUrl))
- .subscribeOn(Schedulers.newThread())
- .retry(3)
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe(new Observer<SignalingSettingsOverall>() {
- @Override
- public void onSubscribe(Disposable d) {
- }
- @Override
- public void onNext(SignalingSettingsOverall signalingSettingsOverall) {
- IceServer iceServer;
- if (signalingSettingsOverall != null && signalingSettingsOverall.getOcs() != null &&
- signalingSettingsOverall.getOcs().getSettings() != null) {
- if (signalingSettingsOverall.getOcs().getSettings().getStunServers() != null) {
- for (int i = 0; i < signalingSettingsOverall.getOcs().getSettings().getStunServers().size();
- i++) {
- iceServer = signalingSettingsOverall.getOcs().getSettings().getStunServers().get(i);
- if (TextUtils.isEmpty(iceServer.getUsername()) || TextUtils.isEmpty(iceServer
- .getCredential())) {
- iceServers.add(new PeerConnection.IceServer(iceServer.getUrl()));
- } else {
- iceServers.add(new PeerConnection.IceServer(iceServer.getUrl(),
- iceServer.getUsername(), iceServer.getCredential()));
- }
- }
- }
- if (signalingSettingsOverall.getOcs().getSettings().getTurnServers() != null) {
- for (int i = 0; i < signalingSettingsOverall.getOcs().getSettings().getTurnServers().size();
- i++) {
- iceServer = signalingSettingsOverall.getOcs().getSettings().getTurnServers().get(i);
- for (int j = 0; j < iceServer.getUrls().size(); j++) {
- if (TextUtils.isEmpty(iceServer.getUsername()) || TextUtils.isEmpty(iceServer
- .getCredential())) {
- iceServers.add(new PeerConnection.IceServer(iceServer.getUrls().get(j)));
- } else {
- iceServers.add(new PeerConnection.IceServer(iceServer.getUrls().get(j),
- iceServer.getUsername(), iceServer.getCredential()));
- }
- }
- }
- }
- }
- checkCapabilities();
- }
- @Override
- public void onError(Throwable e) {
- }
- @Override
- public void onComplete() {
- }
- });
- }
- private void checkCapabilities() {
- ncApi.getCapabilities(credentials, ApiUtils.getUrlForCapabilities(baseUrl))
- .retry(3)
- .subscribeOn(Schedulers.newThread())
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe(new Observer<CapabilitiesOverall>() {
- @Override
- public void onSubscribe(Disposable d) {
- }
- @Override
- public void onNext(CapabilitiesOverall capabilitiesOverall) {
- isMultiSession = capabilitiesOverall.getOcs().getData()
- .getCapabilities() != null && capabilitiesOverall.getOcs().getData()
- .getCapabilities().getSpreedCapability() != null &&
- capabilitiesOverall.getOcs().getData()
- .getCapabilities().getSpreedCapability()
- .getFeatures() != null && capabilitiesOverall.getOcs().getData()
- .getCapabilities().getSpreedCapability()
- .getFeatures().contains("multi-room-users");
- needsPing = !(capabilitiesOverall.getOcs().getData()
- .getCapabilities() != null && capabilitiesOverall.getOcs().getData()
- .getCapabilities().getSpreedCapability() != null &&
- capabilitiesOverall.getOcs().getData()
- .getCapabilities().getSpreedCapability()
- .getFeatures() != null && capabilitiesOverall.getOcs().getData()
- .getCapabilities().getSpreedCapability()
- .getFeatures().contains("no-ping"));
- joinRoomAndCall();
- }
- @Override
- public void onError(Throwable e) {
- isMultiSession = false;
- }
- @Override
- public void onComplete() {
- }
- });
- }
- private void joinRoomAndCall() {
- if ("0".equals(callSession)) {
- ncApi.joinRoom(credentials, ApiUtils.getUrlForSettingMyselfAsActiveParticipant(baseUrl, roomToken), null)
- .subscribeOn(Schedulers.newThread())
- .observeOn(AndroidSchedulers.mainThread())
- .retry(3)
- .subscribe(new Observer<CallOverall>() {
- @Override
- public void onSubscribe(Disposable d) {
- }
- @Override
- public void onNext(CallOverall callOverall) {
- callSession = callOverall.getOcs().getData().getSessionId();
- performCall();
- }
- @Override
- public void onError(Throwable e) {
- }
- @Override
- public void onComplete() {
- }
- });
- } else {
- performCall();
- }
- }
- private void performCall() {
- ncApi.joinCall(credentials,
- ApiUtils.getUrlForCall(baseUrl, roomToken))
- .subscribeOn(Schedulers.newThread())
- .retry(3)
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe(new Observer<GenericOverall>() {
- @Override
- public void onSubscribe(Disposable d) {
- }
- @Override
- public void onNext(GenericOverall genericOverall) {
- inCall = true;
- if (connectingView != null) {
- connectingView.setVisibility(View.GONE);
- }
- if (conversationView != null) {
- conversationView.setVisibility(View.VISIBLE);
- }
- if (!isPTTActive) {
- animateCallControls(false, 5000);
- }
- ApplicationWideCurrentRoomHolder.getInstance().setCurrentRoomId(roomId);
- ApplicationWideCurrentRoomHolder.getInstance().setCurrentRoomToken(roomToken);
- ApplicationWideCurrentRoomHolder.getInstance().setInCall(true);
- ApplicationWideCurrentRoomHolder.getInstance().setUserInRoom(conversationUser);
- if (needsPing) {
- ncApi.pingCall(credentials, ApiUtils.getUrlForCallPing(baseUrl, roomToken))
- .subscribeOn(Schedulers.newThread())
- .observeOn(AndroidSchedulers.mainThread())
- .repeatWhen(observable -> observable.delay(5000, TimeUnit.MILLISECONDS))
- .takeWhile(observable -> inCall)
- .retry(3, observable -> inCall)
- .subscribe(new Observer<GenericOverall>() {
- @Override
- public void onSubscribe(Disposable d) {
- pingDisposable = d;
- }
- @Override
- public void onNext(GenericOverall genericOverall) {
- }
- @Override
- public void onError(Throwable e) {
- dispose(pingDisposable);
- }
- @Override
- public void onComplete() {
- dispose(pingDisposable);
- }
- });
- }
- // Start pulling signaling messages
- String urlToken = null;
- if (isMultiSession) {
- urlToken = roomToken;
- }
- NotificationUtils.cancelExistingNotifications(getApplicationContext(), conversationUser);
- ncApi.pullSignalingMessages(credentials, ApiUtils.getUrlForSignaling(baseUrl, urlToken))
- .subscribeOn(Schedulers.newThread())
- .observeOn(AndroidSchedulers.mainThread())
- .repeatWhen(observable -> observable)
- .takeWhile(observable -> inCall)
- .retry(3, observable -> inCall)
- .subscribe(new Observer<SignalingOverall>() {
- @Override
- public void onSubscribe(Disposable d) {
- signalingDisposable = d;
- }
- @Override
- public void onNext(SignalingOverall signalingOverall) {
- if (signalingOverall.getOcs().getSignalings() != null) {
- for (int i = 0; i < signalingOverall.getOcs().getSignalings().size(); i++) {
- try {
- receivedSignalingMessage(signalingOverall.getOcs().getSignalings().get(i));
- } catch (IOException e) {
- Log.e(TAG, "Failed to process received signaling" +
- " message");
- }
- }
- }
- }
- @Override
- public void onError(Throwable e) {
- dispose(signalingDisposable);
- }
- @Override
- public void onComplete() {
- dispose(signalingDisposable);
- }
- });
- }
- @Override
- public void onError(Throwable e) {
- }
- @Override
- public void onComplete() {
- }
- });
- }
- @OnClick({R.id.pip_video_view, R.id.remote_renderers_layout})
- public void showCallControls() {
- animateCallControls(true, 0);
- }
- private void dispose(@Nullable Disposable disposable) {
- if (disposable != null && !disposable.isDisposed()) {
- disposable.dispose();
- } else if (disposable == null) {
- if (pingDisposable != null && !pingDisposable.isDisposed()) {
- pingDisposable.dispose();
- pingDisposable = null;
- }
- if (signalingDisposable != null && !signalingDisposable.isDisposed()) {
- signalingDisposable.dispose();
- signalingDisposable = null;
- }
- }
- }
- private void receivedSignalingMessage(Signaling signaling) throws IOException {
- String messageType = signaling.getType();
- if (leavingCall) {
- return;
- }
- if ("usersInRoom".equals(messageType)) {
- processUsersInRoom((List<HashMap<String, String>>) signaling.getMessageWrapper());
- } else if ("message".equals(messageType)) {
- NCSignalingMessage ncSignalingMessage = LoganSquare.parse(signaling.getMessageWrapper().toString(),
- NCSignalingMessage.class);
- if (ncSignalingMessage.getRoomType().equals("video")) {
- MagicPeerConnectionWrapper magicPeerConnectionWrapper = alwaysGetPeerConnectionWrapperForSessionId
- (ncSignalingMessage.getFrom());
- String type = null;
- if (ncSignalingMessage.getPayload() != null && ncSignalingMessage.getPayload().getType() !=
- null) {
- type = ncSignalingMessage.getPayload().getType();
- } else if (ncSignalingMessage.getType() != null) {
- type = ncSignalingMessage.getType();
- }
- if (type != null) {
- switch (type) {
- case "offer":
- case "answer":
- magicPeerConnectionWrapper.setNick(ncSignalingMessage.getPayload().getNick());
- String sessionDescriptionStringWithPreferredCodec = MagicWebRTCUtils.preferCodec
- (ncSignalingMessage.getPayload().getSdp(),
- "VP8", false);
- SessionDescription sessionDescriptionWithPreferredCodec = new SessionDescription(
- SessionDescription.Type.fromCanonicalForm(type),
- sessionDescriptionStringWithPreferredCodec);
- if (magicPeerConnectionWrapper.getPeerConnection() != null) {
- magicPeerConnectionWrapper.getPeerConnection().setRemoteDescription(magicPeerConnectionWrapper
- .getMagicSdpObserver(), sessionDescriptionWithPreferredCodec);
- }
- break;
- case "candidate":
- NCIceCandidate ncIceCandidate = ncSignalingMessage.getPayload().getIceCandidate();
- IceCandidate iceCandidate = new IceCandidate(ncIceCandidate.getSdpMid(),
- ncIceCandidate.getSdpMLineIndex(), ncIceCandidate.getCandidate());
- magicPeerConnectionWrapper.addCandidate(iceCandidate);
- break;
- case "endOfCandidates":
- magicPeerConnectionWrapper.drainIceCandidates();
- break;
- default:
- break;
- }
- }
- } else {
- Log.d(TAG, "Something went very very wrong");
- }
- } else {
- Log.d(TAG, "Something went very very wrong");
- }
- }
- private void hangup(boolean dueToNetworkChange) {
- leavingCall = true;
- inCall = false;
- if (videoCapturer != null) {
- try {
- videoCapturer.stopCapture();
- } catch (InterruptedException e) {
- Log.e(TAG, "Failed to stop capturing while hanging up");
- }
- videoCapturer.dispose();
- videoCapturer = null;
- }
- for (int i = 0; i < magicPeerConnectionWrapperList.size(); i++) {
- endPeerConnection(magicPeerConnectionWrapperList.get(i).getSessionId());
- }
- if (pipVideoView != null) {
- pipVideoView.release();
- }
- if (audioSource != null) {
- audioSource.dispose();
- audioSource = null;
- }
- if (audioManager != null) {
- audioManager.stop();
- audioManager = null;
- }
- if (videoSource != null) {
- videoSource = null;
- }
- if (peerConnectionFactory != null) {
- peerConnectionFactory = null;
- }
- localMediaStream = null;
- localAudioTrack = null;
- localVideoTrack = null;
- if (!dueToNetworkChange) {
- hangupNetworkCalls();
- } else {
- if (getActivity() != null) {
- getActivity().finish();
- }
- }
- }
- private void hangupNetworkCalls() {
- ncApi.leaveCall(credentials, ApiUtils.getUrlForCall(baseUrl, roomToken))
- .subscribeOn(Schedulers.newThread())
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe(new Observer<GenericOverall>() {
- @Override
- public void onSubscribe(Disposable d) {
- }
- @Override
- public void onNext(GenericOverall genericOverall) {
- if (isMultiSession) {
- if (getActivity() != null) {
- getActivity().finish();
- }
- } else {
- leaveRoom();
- }
- }
- @Override
- public void onError(Throwable e) {
- }
- @Override
- public void onComplete() {
- }
- });
- }
- private void leaveRoom() {
- ncApi.leaveRoom(credentials, ApiUtils.getUrlForSettingMyselfAsActiveParticipant(baseUrl, roomToken))
- .subscribeOn(Schedulers.newThread())
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe(new Observer<GenericOverall>() {
- @Override
- public void onSubscribe(Disposable d) {
- }
- @Override
- public void onNext(GenericOverall genericOverall) {
- if (getActivity() != null) {
- getActivity().finish();
- }
- }
- @Override
- public void onError(Throwable e) {
- }
- @Override
- public void onComplete() {
- }
- });
- }
- private void startVideoCapture() {
- if (videoCapturer != null) {
- videoCapturer.startCapture(1280, 720, 30);
- }
- }
- private void processUsersInRoom(List<HashMap<String, String>> users) {
- List<String> newSessions = new ArrayList<>();
- Set<String> oldSesssions = new HashSet<>();
- for (HashMap<String, String> participant : users) {
- if (!participant.get("sessionId").equals(callSession)) {
- Object inCallObject = participant.get("inCall");
- if ((boolean) inCallObject) {
- newSessions.add(participant.get("sessionId"));
- } else {
- oldSesssions.add(participant.get("sessionId"));
- }
- }
- }
- for (MagicPeerConnectionWrapper magicPeerConnectionWrapper : magicPeerConnectionWrapperList) {
- oldSesssions.add(magicPeerConnectionWrapper.getSessionId());
- }
- // Calculate sessions that left the call
- oldSesssions.removeAll(newSessions);
- // Calculate sessions that join the call
- newSessions.removeAll(oldSesssions);
- if (leavingCall) {
- return;
- }
- if (newSessions.size() > 0) {
- getPeersForCall();
- }
- for (String sessionId : newSessions) {
- alwaysGetPeerConnectionWrapperForSessionId(sessionId);
- }
- for (String sessionId : oldSesssions) {
- endPeerConnection(sessionId);
- }
- }
- private void getPeersForCall() {
- ncApi.getPeersForCall(credentials, ApiUtils.getUrlForCall(baseUrl, roomToken))
- .subscribeOn(Schedulers.newThread())
- .subscribe(new Observer<ParticipantsOverall>() {
- @Override
- public void onSubscribe(Disposable d) {
- }
- @Override
- public void onNext(ParticipantsOverall participantsOverall) {
- participantMap = new HashMap<>();
- for (Participant participant : participantsOverall.getOcs().getData()) {
- participantMap.put(participant.getSessionId(), participant);
- if (getActivity() != null) {
- getActivity().runOnUiThread(() -> setupAvatarForSession(participant.getSessionId()));
- }
- }
- }
- @Override
- public void onError(Throwable e) {
- }
- @Override
- public void onComplete() {
- }
- });
- }
- private void deleteMagicPeerConnection(MagicPeerConnectionWrapper magicPeerConnectionWrapper) {
- magicPeerConnectionWrapper.removePeerConnection();
- magicPeerConnectionWrapperList.remove(magicPeerConnectionWrapper);
- }
- private MagicPeerConnectionWrapper alwaysGetPeerConnectionWrapperForSessionId(String sessionId) {
- MagicPeerConnectionWrapper magicPeerConnectionWrapper;
- if ((magicPeerConnectionWrapper = getPeerConnectionWrapperForSessionId(sessionId)) != null) {
- return magicPeerConnectionWrapper;
- } else {
- magicPeerConnectionWrapper = new MagicPeerConnectionWrapper(peerConnectionFactory,
- iceServers, sdpConstraints, sessionId, callSession, localMediaStream);
- magicPeerConnectionWrapperList.add(magicPeerConnectionWrapper);
- return magicPeerConnectionWrapper;
- }
- }
- private MagicPeerConnectionWrapper getPeerConnectionWrapperForSessionId(String sessionId) {
- for (MagicPeerConnectionWrapper magicPeerConnectionWrapper : magicPeerConnectionWrapperList) {
- if (magicPeerConnectionWrapper.getSessionId().equals(sessionId)) {
- return magicPeerConnectionWrapper;
- }
- }
- return null;
- }
- private void endPeerConnection(String sessionId) {
- MagicPeerConnectionWrapper magicPeerConnectionWrapper;
- if ((magicPeerConnectionWrapper = getPeerConnectionWrapperForSessionId(sessionId)) != null && getActivity()
- != null) {
- getActivity().runOnUiThread(() -> removeMediaStream(sessionId));
- deleteMagicPeerConnection(magicPeerConnectionWrapper);
- }
- }
- private void removeMediaStream(String sessionId) {
- if (remoteRenderersLayout != null && remoteRenderersLayout.getChildCount() > 0) {
- RelativeLayout relativeLayout = remoteRenderersLayout.findViewWithTag(sessionId);
- if (relativeLayout != null) {
- SurfaceViewRenderer surfaceViewRenderer = relativeLayout.findViewById(R.id.surface_view);
- surfaceViewRenderer.release();
- remoteRenderersLayout.removeView(relativeLayout);
- remoteRenderersLayout.invalidate();
- }
- }
- if (callControls != null) {
- callControls.setZ(100.0f);
- }
- }
- @Subscribe(threadMode = ThreadMode.MAIN)
- public void onMessageEvent(ConfigurationChangeEvent configurationChangeEvent) {
- if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
- remoteRenderersLayout.setOrientation(LinearLayout.HORIZONTAL);
- } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
- remoteRenderersLayout.setOrientation(LinearLayout.VERTICAL);
- }
- }
- @Subscribe(threadMode = ThreadMode.MAIN)
- public void onMessageEvent(PeerConnectionEvent peerConnectionEvent) {
- if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent.PeerConnectionEventType
- .PEER_CLOSED)) {
- endPeerConnection(peerConnectionEvent.getSessionId());
- } else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
- .PeerConnectionEventType.SENSOR_FAR) ||
- peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
- .PeerConnectionEventType.SENSOR_NEAR)) {
-
- if (!isVoiceOnlyCall) {
- boolean enableVideo = peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
- .PeerConnectionEventType.SENSOR_FAR) && videoOn;
- if (getActivity() != null && EffortlessPermissions.hasPermissions(getActivity(), PERMISSIONS_CAMERA) &&
- inCall && videoOn
- && enableVideo != localVideoTrack.enabled()) {
- toggleMedia(enableVideo, true);
- }
- }
- } else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
- .PeerConnectionEventType.NICK_CHANGE)) {
- gotNick(peerConnectionEvent.getSessionId(), peerConnectionEvent.getNick());
- } else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
- .PeerConnectionEventType.VIDEO_CHANGE) && !isVoiceOnlyCall) {
- gotAudioOrVideoChange(true, peerConnectionEvent.getSessionId(),
- peerConnectionEvent.getChangeValue());
- } else if (peerConnectionEvent.getPeerConnectionEventType().equals(PeerConnectionEvent
- .PeerConnectionEventType.AUDIO_CHANGE)) {
- gotAudioOrVideoChange(false, peerConnectionEvent.getSessionId(),
- peerConnectionEvent.getChangeValue());
- }
- }
- @Subscribe(threadMode = ThreadMode.MAIN)
- public void onMessageEvent(MediaStreamEvent mediaStreamEvent) {
- if (mediaStreamEvent.getMediaStream() != null) {
- setupVideoStreamForLayout(mediaStreamEvent.getMediaStream(), mediaStreamEvent.getSession(),
- mediaStreamEvent.getMediaStream().videoTracks != null
- && mediaStreamEvent.getMediaStream().videoTracks.size() > 0);
- } else {
- setupVideoStreamForLayout(null, mediaStreamEvent.getSession(), false);
- }
- }
- @Subscribe(threadMode = ThreadMode.BACKGROUND)
- public void onMessageEvent(SessionDescriptionSendEvent sessionDescriptionSend) throws IOException {
- NCMessageWrapper ncMessageWrapper = new NCMessageWrapper();
- ncMessageWrapper.setEv("message");
- ncMessageWrapper.setSessionId(callSession);
- NCSignalingMessage ncSignalingMessage = new NCSignalingMessage();
- ncSignalingMessage.setTo(sessionDescriptionSend.getPeerId());
- ncSignalingMessage.setRoomType("video");
- ncSignalingMessage.setType(sessionDescriptionSend.getType());
- NCMessagePayload ncMessagePayload = new NCMessagePayload();
- ncMessagePayload.setType(sessionDescriptionSend.getType());
- if (!"candidate".equals(sessionDescriptionSend.getType())) {
- ncMessagePayload.setSdp(sessionDescriptionSend.getSessionDescription().description);
- ncMessagePayload.setNick(conversationUser.getDisplayName());
- } else {
- ncMessagePayload.setIceCandidate(sessionDescriptionSend.getNcIceCandidate());
- }
- // Set all we need
- ncSignalingMessage.setPayload(ncMessagePayload);
- ncMessageWrapper.setSignalingMessage(ncSignalingMessage);
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append("{")
- .append("\"fn\":\"")
- .append(StringEscapeUtils.escapeJson(LoganSquare.serialize(ncMessageWrapper.getSignalingMessage()))).append("\"")
- .append(",")
- .append("\"sessionId\":")
- .append("\"").append(StringEscapeUtils.escapeJson(callSession)).append("\"")
- .append(",")
- .append("\"ev\":\"message\"")
- .append("}");
- List<String> strings = new ArrayList<>();
- String stringToSend = stringBuilder.toString();
- strings.add(stringToSend);
- String urlToken = null;
- if (isMultiSession) {
- urlToken = roomToken;
- }
- ncApi.sendSignalingMessages(credentials, ApiUtils.getUrlForSignaling(baseUrl, urlToken),
- strings.toString())
- .retry(3)
- .subscribeOn(Schedulers.newThread())
- .subscribe(new Observer<SignalingOverall>() {
- @Override
- public void onSubscribe(Disposable d) {
- }
- @Override
- public void onNext(SignalingOverall signalingOverall) {
- if (signalingOverall.getOcs().getSignalings() != null) {
- for (int i = 0; i < signalingOverall.getOcs().getSignalings().size(); i++) {
- try {
- receivedSignalingMessage(signalingOverall.getOcs().getSignalings().get(i));
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- @Override
- public void onError(Throwable e) {
- }
- @Override
- public void onComplete() {
- }
- });
- }
- @Override
- public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
- @NonNull int[] grantResults) {
- super.onRequestPermissionsResult(requestCode, permissions, grantResults);
- EffortlessPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults,
- this);
- }
- private void setupAvatarForSession(String session) {
- if (remoteRenderersLayout != null) {
- RelativeLayout relativeLayout = remoteRenderersLayout.findViewWithTag(session);
- if (relativeLayout != null) {
- ImageView avatarImageView = relativeLayout.findViewById(R.id.avatarImageView);
- if (participantMap.containsKey(session) && avatarImageView.getDrawable() == null) {
- int size = Math.round(getResources().getDimension(R.dimen.avatar_size_big));
- if (getActivity() != null) {
- GlideApp.with(getActivity())
- .asBitmap()
- .diskCacheStrategy(DiskCacheStrategy.NONE)
- .load(ApiUtils.getUrlForAvatarWithName(baseUrl, participantMap.get(session).getUserId(), R.dimen.avatar_size_big))
- .centerInside()
- .override(size, size)
- .apply(RequestOptions.bitmapTransform(new CircleCrop()))
- .into(avatarImageView);
- }
- }
- }
- }
- }
- private void setupVideoStreamForLayout(@Nullable MediaStream mediaStream, String session, boolean enable) {
- boolean isInitialLayoutSetupForPeer = false;
- if (remoteRenderersLayout.findViewWithTag(session) == null) {
- setupNewPeerLayout(session);
- isInitialLayoutSetupForPeer = true;
- }
- RelativeLayout relativeLayout = remoteRenderersLayout.findViewWithTag(session);
- SurfaceViewRenderer surfaceViewRenderer = relativeLayout.findViewById(R.id.surface_view);
- ImageView imageView = relativeLayout.findViewById(R.id.avatarImageView);
- if (mediaStream != null && mediaStream.videoTracks != null && mediaStream.videoTracks.size() > 0 && enable) {
- VideoTrack videoTrack = mediaStream.videoTracks.get(0);
- videoTrack.addSink(surfaceViewRenderer);
- imageView.setVisibility(View.INVISIBLE);
- surfaceViewRenderer.setVisibility(View.VISIBLE);
- } else {
- imageView.setVisibility(View.VISIBLE);
- surfaceViewRenderer.setVisibility(View.INVISIBLE);
- if (isInitialLayoutSetupForPeer && isVoiceOnlyCall) {
- gotAudioOrVideoChange(true, session, false);
- }
- }
- callControls.setZ(100.0f);
- }
- private void gotAudioOrVideoChange(boolean video, String sessionId, boolean change) {
- RelativeLayout relativeLayout = remoteRenderersLayout.findViewWithTag(sessionId);
- if (relativeLayout != null) {
- ImageView imageView;
- ImageView avatarImageView = relativeLayout.findViewById(R.id.avatarImageView);
- SurfaceViewRenderer surfaceViewRenderer = relativeLayout.findViewById(R.id.surface_view);
- if (video) {
- imageView = relativeLayout.findViewById(R.id.remote_video_off);
- if (change) {
- avatarImageView.setVisibility(View.INVISIBLE);
- surfaceViewRenderer.setVisibility(View.VISIBLE);
- } else {
- avatarImageView.setVisibility(View.VISIBLE);
- surfaceViewRenderer.setVisibility(View.INVISIBLE);
- }
- } else {
- imageView = relativeLayout.findViewById(R.id.remote_audio_off);
- }
- if (change && imageView.getVisibility() != View.INVISIBLE) {
- imageView.setVisibility(View.INVISIBLE);
- } else if (!change && imageView.getVisibility() != View.VISIBLE) {
- imageView.setVisibility(View.VISIBLE);
- }
- }
- }
- private void setupNewPeerLayout(String session) {
- if (remoteRenderersLayout.findViewWithTag(session) == null && getActivity() != null) {
- getActivity().runOnUiThread(() -> {
- RelativeLayout relativeLayout = (RelativeLayout)
- getActivity().getLayoutInflater().inflate(R.layout.call_item, remoteRenderersLayout,
- false);
- relativeLayout.setTag(session);
- SurfaceViewRenderer surfaceViewRenderer = relativeLayout.findViewById(R.id
- .surface_view);
- surfaceViewRenderer.setMirror(false);
- surfaceViewRenderer.init(rootEglBase.getEglBaseContext(), null);
- surfaceViewRenderer.setZOrderMediaOverlay(false);
- // disabled because it causes some devices to crash
- surfaceViewRenderer.setEnableHardwareScaler(false);
- surfaceViewRenderer.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT);
- surfaceViewRenderer.setOnClickListener(videoOnClickListener);
- remoteRenderersLayout.addView(relativeLayout);
- gotNick(session, getPeerConnectionWrapperForSessionId(session).getNick());
- setupAvatarForSession(session);
- callControls.setZ(100.0f);
- });
- }
- }
- private void gotNick(String sessionId, String nick) {
- RelativeLayout relativeLayout = remoteRenderersLayout.findViewWithTag(sessionId);
- if (relativeLayout != null) {
- TextView textView = relativeLayout.findViewById(R.id.peer_nick_text_view);
- textView.setText(nick);
- }
- }
- @Override
- protected void onAttach(@NonNull View view) {
- super.onAttach(view);
- eventBus.register(this);
- }
- @Override
- protected void onDetach(@NonNull View view) {
- super.onDetach(view);
- eventBus.unregister(this);
- }
- private class MicrophoneButtonTouchListener implements View.OnTouchListener {
- @SuppressLint("ClickableViewAccessibility")
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- v.onTouchEvent(event);
- if (event.getAction() == MotionEvent.ACTION_UP && isPTTActive) {
- isPTTActive = false;
- microphoneControlButton.getFrontImageView().setImageResource(R.drawable.ic_mic_off_white_24px);
- pulseAnimation.stop();
- toggleMedia(false, false);
- animateCallControls(false, 5000);
- }
- return true;
- }
- }
- private class VideoClickListener implements View.OnClickListener {
- @Override
- public void onClick(View v) {
- showCallControls();
- }
- }
- }
|