MagicPeerConnectionWrapper.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. /*
  2. * Nextcloud Talk application
  3. *
  4. * @author Mario Danic
  5. * Copyright (C) 2017 Mario Danic <mario@lovelyhq.com>
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. */
  21. package com.nextcloud.talk.webrtc;
  22. import android.content.Context;
  23. import android.text.TextUtils;
  24. import android.util.Log;
  25. import com.bluelinelabs.logansquare.LoganSquare;
  26. import com.nextcloud.talk.R;
  27. import com.nextcloud.talk.application.NextcloudTalkApplication;
  28. import com.nextcloud.talk.events.MediaStreamEvent;
  29. import com.nextcloud.talk.events.PeerConnectionEvent;
  30. import com.nextcloud.talk.events.SessionDescriptionSendEvent;
  31. import com.nextcloud.talk.events.WebSocketCommunicationEvent;
  32. import com.nextcloud.talk.models.json.signaling.DataChannelMessage;
  33. import com.nextcloud.talk.models.json.signaling.DataChannelMessageNick;
  34. import com.nextcloud.talk.models.json.signaling.NCIceCandidate;
  35. import org.greenrobot.eventbus.EventBus;
  36. import org.webrtc.DataChannel;
  37. import org.webrtc.IceCandidate;
  38. import org.webrtc.MediaConstraints;
  39. import org.webrtc.MediaStream;
  40. import org.webrtc.PeerConnection;
  41. import org.webrtc.PeerConnectionFactory;
  42. import org.webrtc.RtpReceiver;
  43. import org.webrtc.SdpObserver;
  44. import org.webrtc.SessionDescription;
  45. import java.io.IOException;
  46. import java.nio.ByteBuffer;
  47. import java.util.ArrayList;
  48. import java.util.HashMap;
  49. import java.util.List;
  50. import javax.inject.Inject;
  51. import androidx.annotation.Nullable;
  52. import autodagger.AutoInjector;
  53. @AutoInjector(NextcloudTalkApplication.class)
  54. public class MagicPeerConnectionWrapper {
  55. private static final String TAG = "MagicPeerConWrapper";
  56. private List<IceCandidate> iceCandidates = new ArrayList<>();
  57. private PeerConnection peerConnection;
  58. private String sessionId;
  59. private String nick;
  60. private MediaConstraints sdpConstraints;
  61. private DataChannel magicDataChannel;
  62. private MagicSdpObserver magicSdpObserver;
  63. private MediaStream remoteMediaStream;
  64. private boolean remoteVideoOn;
  65. private boolean remoteAudioOn;
  66. private boolean hasInitiated;
  67. private MediaStream localMediaStream;
  68. private boolean isMCUPublisher;
  69. private boolean hasMCU;
  70. private String videoStreamType;
  71. private int connectionAttempts = 0;
  72. private PeerConnection.IceConnectionState peerIceConnectionState;
  73. @Inject
  74. Context context;
  75. public MagicPeerConnectionWrapper(PeerConnectionFactory peerConnectionFactory,
  76. List<PeerConnection.IceServer> iceServerList,
  77. MediaConstraints sdpConstraints,
  78. String sessionId, String localSession, @Nullable MediaStream mediaStream,
  79. boolean isMCUPublisher, boolean hasMCU, String videoStreamType) {
  80. NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
  81. this.localMediaStream = mediaStream;
  82. this.videoStreamType = videoStreamType;
  83. this.hasMCU = hasMCU;
  84. this.sessionId = sessionId;
  85. this.sdpConstraints = sdpConstraints;
  86. magicSdpObserver = new MagicSdpObserver();
  87. hasInitiated = sessionId.compareTo(localSession) < 0;
  88. this.isMCUPublisher = isMCUPublisher;
  89. peerConnection = peerConnectionFactory.createPeerConnection(iceServerList, sdpConstraints,
  90. new MagicPeerConnectionObserver());
  91. if (peerConnection != null) {
  92. if (localMediaStream != null) {
  93. peerConnection.addStream(localMediaStream);
  94. }
  95. if (hasMCU || hasInitiated) {
  96. DataChannel.Init init = new DataChannel.Init();
  97. init.negotiated = false;
  98. magicDataChannel = peerConnection.createDataChannel("status", init);
  99. magicDataChannel.registerObserver(new MagicDataChannelObserver());
  100. if (isMCUPublisher) {
  101. peerConnection.createOffer(magicSdpObserver, sdpConstraints);
  102. } else if (hasMCU && this.videoStreamType.equals("video")) {
  103. // If the connection type is "screen" the client sharing the screen will send an
  104. // offer; offers should be requested only for videos.
  105. HashMap<String, String> hashMap = new HashMap<>();
  106. hashMap.put("sessionId", sessionId);
  107. EventBus.getDefault().post(new WebSocketCommunicationEvent("peerReadyForRequestingOffer", hashMap));
  108. } else if (!hasMCU && hasInitiated) {
  109. peerConnection.createOffer(magicSdpObserver, sdpConstraints);
  110. }
  111. }
  112. }
  113. }
  114. public String getVideoStreamType() {
  115. return videoStreamType;
  116. }
  117. public void removePeerConnection() {
  118. if (magicDataChannel != null) {
  119. magicDataChannel.dispose();
  120. magicDataChannel = null;
  121. }
  122. if (peerConnection != null) {
  123. if (localMediaStream != null) {
  124. peerConnection.removeStream(localMediaStream);
  125. }
  126. peerConnection.close();
  127. peerConnection = null;
  128. }
  129. }
  130. public void drainIceCandidates() {
  131. if (peerConnection != null) {
  132. for (IceCandidate iceCandidate : iceCandidates) {
  133. peerConnection.addIceCandidate(iceCandidate);
  134. }
  135. iceCandidates = new ArrayList<>();
  136. }
  137. }
  138. public MagicSdpObserver getMagicSdpObserver() {
  139. return magicSdpObserver;
  140. }
  141. public void addCandidate(IceCandidate iceCandidate) {
  142. if (peerConnection != null && peerConnection.getRemoteDescription() != null) {
  143. peerConnection.addIceCandidate(iceCandidate);
  144. } else {
  145. iceCandidates.add(iceCandidate);
  146. }
  147. }
  148. public void sendNickChannelData(DataChannelMessageNick dataChannelMessage) {
  149. ByteBuffer buffer;
  150. if (magicDataChannel != null) {
  151. try {
  152. buffer = ByteBuffer.wrap(LoganSquare.serialize(dataChannelMessage).getBytes());
  153. magicDataChannel.send(new DataChannel.Buffer(buffer, false));
  154. } catch (IOException e) {
  155. Log.d(TAG, "Failed to send channel data, attempting regular " + dataChannelMessage);
  156. }
  157. }
  158. }
  159. public void sendChannelData(DataChannelMessage dataChannelMessage) {
  160. ByteBuffer buffer;
  161. if (magicDataChannel != null) {
  162. try {
  163. buffer = ByteBuffer.wrap(LoganSquare.serialize(dataChannelMessage).getBytes());
  164. magicDataChannel.send(new DataChannel.Buffer(buffer, false));
  165. } catch (IOException e) {
  166. Log.d(TAG, "Failed to send channel data, attempting regular " + dataChannelMessage);
  167. }
  168. }
  169. }
  170. public PeerConnection getPeerConnection() {
  171. return peerConnection;
  172. }
  173. public String getSessionId() {
  174. return sessionId;
  175. }
  176. public void setSessionId(String sessionId) {
  177. this.sessionId = sessionId;
  178. }
  179. public String getNick() {
  180. if (!TextUtils.isEmpty(nick)) {
  181. return nick;
  182. } else {
  183. return NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_nick_guest);
  184. }
  185. }
  186. public void setNick(String nick) {
  187. this.nick = nick;
  188. }
  189. private void sendInitialMediaStatus() {
  190. if (localMediaStream != null) {
  191. if (localMediaStream.videoTracks.size() == 1 && localMediaStream.videoTracks.get(0).enabled()) {
  192. sendChannelData(new DataChannelMessage("videoOn"));
  193. } else {
  194. sendChannelData(new DataChannelMessage("videoOff"));
  195. }
  196. if (localMediaStream.audioTracks.size() == 1 && localMediaStream.audioTracks.get(0).enabled()) {
  197. sendChannelData(new DataChannelMessage("audioOn"));
  198. } else {
  199. sendChannelData(new DataChannelMessage("audioOff"));
  200. }
  201. }
  202. }
  203. public boolean isMCUPublisher() {
  204. return isMCUPublisher;
  205. }
  206. private class MagicDataChannelObserver implements DataChannel.Observer {
  207. @Override
  208. public void onBufferedAmountChange(long l) {
  209. }
  210. @Override
  211. public void onStateChange() {
  212. if (magicDataChannel != null && magicDataChannel.state().equals(DataChannel.State.OPEN) &&
  213. magicDataChannel.label().equals("status")) {
  214. sendInitialMediaStatus();
  215. }
  216. }
  217. @Override
  218. public void onMessage(DataChannel.Buffer buffer) {
  219. if (buffer.binary) {
  220. Log.d(TAG, "Received binary msg over " + TAG + " " + sessionId);
  221. return;
  222. }
  223. ByteBuffer data = buffer.data;
  224. final byte[] bytes = new byte[data.capacity()];
  225. data.get(bytes);
  226. String strData = new String(bytes);
  227. Log.d(TAG, "Got msg: " + strData + " over " + TAG + " " + sessionId);
  228. try {
  229. DataChannelMessage dataChannelMessage = LoganSquare.parse(strData, DataChannelMessage.class);
  230. String internalNick;
  231. if ("nickChanged".equals(dataChannelMessage.getType())) {
  232. if (dataChannelMessage.getPayload() instanceof String) {
  233. internalNick = (String) dataChannelMessage.getPayload();
  234. if (!internalNick.equals(nick)) {
  235. setNick(internalNick);
  236. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  237. .NICK_CHANGE, sessionId, getNick(), null, videoStreamType));
  238. }
  239. } else {
  240. if (dataChannelMessage.getPayload() != null) {
  241. HashMap<String, String> payloadHashMap = (HashMap<String, String>) dataChannelMessage.getPayload();
  242. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  243. .NICK_CHANGE, sessionId, payloadHashMap.get("name"), null, videoStreamType));
  244. }
  245. }
  246. } else if ("audioOn".equals(dataChannelMessage.getType())) {
  247. remoteAudioOn = true;
  248. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  249. .AUDIO_CHANGE, sessionId, null, remoteAudioOn, videoStreamType));
  250. } else if ("audioOff".equals(dataChannelMessage.getType())) {
  251. remoteAudioOn = false;
  252. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  253. .AUDIO_CHANGE, sessionId, null, remoteAudioOn, videoStreamType));
  254. } else if ("videoOn".equals(dataChannelMessage.getType())) {
  255. remoteVideoOn = true;
  256. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  257. .VIDEO_CHANGE, sessionId, null, remoteVideoOn, videoStreamType));
  258. } else if ("videoOff".equals(dataChannelMessage.getType())) {
  259. remoteVideoOn = false;
  260. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  261. .VIDEO_CHANGE, sessionId, null, remoteVideoOn, videoStreamType));
  262. }
  263. } catch (IOException e) {
  264. Log.d(TAG, "Failed to parse data channel message");
  265. }
  266. }
  267. }
  268. private void restartIce() {
  269. if (connectionAttempts <= 5) {
  270. if (!hasMCU || isMCUPublisher) {
  271. MediaConstraints.KeyValuePair iceRestartConstraint =
  272. new MediaConstraints.KeyValuePair("IceRestart", "true");
  273. if (sdpConstraints.mandatory.contains(iceRestartConstraint)) {
  274. sdpConstraints.mandatory.add(iceRestartConstraint);
  275. }
  276. peerConnection.createOffer(magicSdpObserver, sdpConstraints);
  277. } else {
  278. // we have an MCU and this is not the publisher
  279. // Do something if we have an MCU
  280. }
  281. connectionAttempts++;
  282. }
  283. }
  284. private class MagicPeerConnectionObserver implements PeerConnection.Observer {
  285. @Override
  286. public void onSignalingChange(PeerConnection.SignalingState signalingState) {
  287. }
  288. @Override
  289. public void onIceConnectionChange(PeerConnection.IceConnectionState iceConnectionState) {
  290. peerIceConnectionState = iceConnectionState;
  291. Log.d("iceConnectionChangeTo: ", iceConnectionState.name() + " over " + peerConnection.hashCode() + " " + sessionId);
  292. if (iceConnectionState.equals(PeerConnection.IceConnectionState.CONNECTED)) {
  293. connectionAttempts = 0;
  294. /*EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  295. .PEER_CONNECTED, sessionId, null, null));*/
  296. if (!isMCUPublisher) {
  297. EventBus.getDefault().post(new MediaStreamEvent(remoteMediaStream, sessionId, videoStreamType));
  298. }
  299. if (hasInitiated) {
  300. sendInitialMediaStatus();
  301. }
  302. } else if (iceConnectionState.equals(PeerConnection.IceConnectionState.CLOSED)) {
  303. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  304. .PEER_CLOSED, sessionId, null, null, videoStreamType));
  305. connectionAttempts = 0;
  306. } else if (iceConnectionState.equals(PeerConnection.IceConnectionState.FAILED)) {
  307. /*if (MerlinTheWizard.isConnectedToInternet() && connectionAttempts < 5) {
  308. restartIce();
  309. }*/
  310. if (isMCUPublisher) {
  311. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType.PUBLISHER_FAILED, sessionId, null, null, null));
  312. }
  313. }
  314. }
  315. @Override
  316. public void onIceConnectionReceivingChange(boolean b) {
  317. }
  318. @Override
  319. public void onIceGatheringChange(PeerConnection.IceGatheringState iceGatheringState) {
  320. }
  321. @Override
  322. public void onIceCandidate(IceCandidate iceCandidate) {
  323. NCIceCandidate ncIceCandidate = new NCIceCandidate();
  324. ncIceCandidate.setSdpMid(iceCandidate.sdpMid);
  325. ncIceCandidate.setSdpMLineIndex(iceCandidate.sdpMLineIndex);
  326. ncIceCandidate.setCandidate(iceCandidate.sdp);
  327. EventBus.getDefault().post(new SessionDescriptionSendEvent(null, sessionId,
  328. "candidate", ncIceCandidate, videoStreamType));
  329. }
  330. @Override
  331. public void onIceCandidatesRemoved(IceCandidate[] iceCandidates) {
  332. }
  333. @Override
  334. public void onAddStream(MediaStream mediaStream) {
  335. remoteMediaStream = mediaStream;
  336. }
  337. @Override
  338. public void onRemoveStream(MediaStream mediaStream) {
  339. if (!isMCUPublisher) {
  340. EventBus.getDefault().post(new MediaStreamEvent(null, sessionId, videoStreamType));
  341. }
  342. }
  343. @Override
  344. public void onDataChannel(DataChannel dataChannel) {
  345. if (dataChannel.label().equals("status") || dataChannel.label().equals("JanusDataChannel")) {
  346. magicDataChannel = dataChannel;
  347. magicDataChannel.registerObserver(new MagicDataChannelObserver());
  348. }
  349. }
  350. @Override
  351. public void onRenegotiationNeeded() {
  352. }
  353. @Override
  354. public void onAddTrack(RtpReceiver rtpReceiver, MediaStream[] mediaStreams) {
  355. }
  356. }
  357. private class MagicSdpObserver implements SdpObserver {
  358. private static final String TAG = "MagicSdpObserver";
  359. @Override
  360. public void onCreateFailure(String s) {
  361. Log.d(TAG, "SDPObserver createFailure: " + s + " over " + peerConnection.hashCode() + " " + sessionId);
  362. }
  363. @Override
  364. public void onSetFailure(String s) {
  365. Log.d(TAG,"SDPObserver setFailure: " + s + " over " + peerConnection.hashCode() + " " + sessionId);
  366. }
  367. @Override
  368. public void onCreateSuccess(SessionDescription sessionDescription) {
  369. SessionDescription sessionDescriptionWithPreferredCodec;
  370. String sessionDescriptionStringWithPreferredCodec = MagicWebRTCUtils.preferCodec
  371. (sessionDescription.description,
  372. "H264", false);
  373. sessionDescriptionWithPreferredCodec = new SessionDescription(
  374. sessionDescription.type,
  375. sessionDescriptionStringWithPreferredCodec);
  376. EventBus.getDefault().post(new SessionDescriptionSendEvent(sessionDescriptionWithPreferredCodec, sessionId,
  377. sessionDescription.type.canonicalForm().toLowerCase(), null, videoStreamType));
  378. if (peerConnection != null) {
  379. peerConnection.setLocalDescription(magicSdpObserver, sessionDescriptionWithPreferredCodec);
  380. }
  381. }
  382. @Override
  383. public void onSetSuccess() {
  384. if (peerConnection != null) {
  385. if (peerConnection.getLocalDescription() == null) {
  386. peerConnection.createAnswer(magicSdpObserver, sdpConstraints);
  387. }
  388. if (peerConnection.getRemoteDescription() != null) {
  389. drainIceCandidates();
  390. }
  391. }
  392. }
  393. }
  394. public PeerConnection.IceConnectionState getPeerIceConnectionState() {
  395. return peerIceConnectionState;
  396. }
  397. }