MagicPeerConnectionWrapper.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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 androidx.annotation.Nullable;
  26. import autodagger.AutoInjector;
  27. import com.bluelinelabs.logansquare.LoganSquare;
  28. import com.nextcloud.talk.R;
  29. import com.nextcloud.talk.application.NextcloudTalkApplication;
  30. import com.nextcloud.talk.events.MediaStreamEvent;
  31. import com.nextcloud.talk.events.PeerConnectionEvent;
  32. import com.nextcloud.talk.events.SessionDescriptionSendEvent;
  33. import com.nextcloud.talk.events.WebSocketCommunicationEvent;
  34. import com.nextcloud.talk.models.json.signaling.DataChannelMessage;
  35. import com.nextcloud.talk.models.json.signaling.DataChannelMessageNick;
  36. import com.nextcloud.talk.models.json.signaling.NCIceCandidate;
  37. import com.nextcloud.talk.utils.LoggingUtils;
  38. import org.greenrobot.eventbus.EventBus;
  39. import org.webrtc.*;
  40. import javax.inject.Inject;
  41. import java.io.IOException;
  42. import java.nio.ByteBuffer;
  43. import java.util.ArrayList;
  44. import java.util.HashMap;
  45. import java.util.List;
  46. @AutoInjector(NextcloudTalkApplication.class)
  47. public class MagicPeerConnectionWrapper {
  48. private static String TAG = "MagicPeerConnectionWrapper";
  49. private List<IceCandidate> iceCandidates = new ArrayList<>();
  50. private PeerConnection peerConnection;
  51. private String sessionId;
  52. private String nick;
  53. private MediaConstraints sdpConstraints;
  54. private DataChannel magicDataChannel;
  55. private MagicSdpObserver magicSdpObserver;
  56. private MediaStream remoteMediaStream;
  57. private boolean remoteVideoOn;
  58. private boolean remoteAudioOn;
  59. private boolean hasInitiated;
  60. private MediaStream localMediaStream;
  61. private boolean isMCUPublisher;
  62. private boolean hasMCU;
  63. private String videoStreamType;
  64. private int connectionAttempts = 0;
  65. private PeerConnection.IceConnectionState peerIceConnectionState;
  66. @Inject
  67. Context context;
  68. public MagicPeerConnectionWrapper(PeerConnectionFactory peerConnectionFactory,
  69. List<PeerConnection.IceServer> iceServerList,
  70. MediaConstraints sdpConstraints,
  71. String sessionId, String localSession, @Nullable MediaStream mediaStream,
  72. boolean isMCUPublisher, boolean hasMCU, String videoStreamType) {
  73. NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
  74. this.localMediaStream = mediaStream;
  75. this.videoStreamType = videoStreamType;
  76. this.hasMCU = hasMCU;
  77. this.sessionId = sessionId;
  78. this.sdpConstraints = sdpConstraints;
  79. magicSdpObserver = new MagicSdpObserver();
  80. hasInitiated = sessionId.compareTo(localSession) < 0;
  81. this.isMCUPublisher = isMCUPublisher;
  82. peerConnection = peerConnectionFactory.createPeerConnection(iceServerList, sdpConstraints,
  83. new MagicPeerConnectionObserver());
  84. if (peerConnection != null) {
  85. if (localMediaStream != null) {
  86. peerConnection.addStream(localMediaStream);
  87. }
  88. if (hasMCU || hasInitiated) {
  89. DataChannel.Init init = new DataChannel.Init();
  90. init.negotiated = false;
  91. magicDataChannel = peerConnection.createDataChannel("status", init);
  92. magicDataChannel.registerObserver(new MagicDataChannelObserver());
  93. if (isMCUPublisher) {
  94. peerConnection.createOffer(magicSdpObserver, sdpConstraints);
  95. } else if (hasMCU) {
  96. HashMap<String, String> hashMap = new HashMap<>();
  97. hashMap.put("sessionId", sessionId);
  98. EventBus.getDefault().post(new WebSocketCommunicationEvent("peerReadyForRequestingOffer", hashMap));
  99. } else if (hasInitiated) {
  100. peerConnection.createOffer(magicSdpObserver, sdpConstraints);
  101. }
  102. }
  103. }
  104. }
  105. public String getVideoStreamType() {
  106. return videoStreamType;
  107. }
  108. public void removePeerConnection() {
  109. if (magicDataChannel != null) {
  110. magicDataChannel.dispose();
  111. magicDataChannel = null;
  112. }
  113. if (peerConnection != null) {
  114. if (localMediaStream != null) {
  115. peerConnection.removeStream(localMediaStream);
  116. }
  117. peerConnection.close();
  118. peerConnection = null;
  119. }
  120. }
  121. public void drainIceCandidates() {
  122. if (peerConnection != null) {
  123. for (IceCandidate iceCandidate : iceCandidates) {
  124. peerConnection.addIceCandidate(iceCandidate);
  125. }
  126. iceCandidates = new ArrayList<>();
  127. }
  128. }
  129. public MagicSdpObserver getMagicSdpObserver() {
  130. return magicSdpObserver;
  131. }
  132. public void addCandidate(IceCandidate iceCandidate) {
  133. if (peerConnection != null && peerConnection.getRemoteDescription() != null) {
  134. peerConnection.addIceCandidate(iceCandidate);
  135. } else {
  136. iceCandidates.add(iceCandidate);
  137. }
  138. }
  139. public void sendNickChannelData(DataChannelMessageNick dataChannelMessage) {
  140. ByteBuffer buffer;
  141. if (magicDataChannel != null) {
  142. try {
  143. buffer = ByteBuffer.wrap(LoganSquare.serialize(dataChannelMessage).getBytes());
  144. magicDataChannel.send(new DataChannel.Buffer(buffer, false));
  145. } catch (IOException e) {
  146. Log.d(TAG, "Failed to send channel data, attempting regular " + dataChannelMessage.toString());
  147. }
  148. }
  149. }
  150. public void sendChannelData(DataChannelMessage dataChannelMessage) {
  151. ByteBuffer buffer;
  152. if (magicDataChannel != null) {
  153. try {
  154. buffer = ByteBuffer.wrap(LoganSquare.serialize(dataChannelMessage).getBytes());
  155. magicDataChannel.send(new DataChannel.Buffer(buffer, false));
  156. } catch (IOException e) {
  157. Log.d(TAG, "Failed to send channel data, attempting regular " + dataChannelMessage.toString());
  158. }
  159. }
  160. }
  161. public PeerConnection getPeerConnection() {
  162. return peerConnection;
  163. }
  164. public String getSessionId() {
  165. return sessionId;
  166. }
  167. public void setSessionId(String sessionId) {
  168. this.sessionId = sessionId;
  169. }
  170. public String getNick() {
  171. if (!TextUtils.isEmpty(nick)) {
  172. return nick;
  173. } else {
  174. return NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_nick_guest);
  175. }
  176. }
  177. public void setNick(String nick) {
  178. this.nick = nick;
  179. }
  180. private void sendInitialMediaStatus() {
  181. if (localMediaStream != null) {
  182. if (localMediaStream.videoTracks.size() == 1 && localMediaStream.videoTracks.get(0).enabled()) {
  183. sendChannelData(new DataChannelMessage("videoOn"));
  184. } else {
  185. sendChannelData(new DataChannelMessage("videoOff"));
  186. }
  187. if (localMediaStream.audioTracks.size() == 1 && localMediaStream.audioTracks.get(0).enabled()) {
  188. sendChannelData(new DataChannelMessage("audioOn"));
  189. } else {
  190. sendChannelData(new DataChannelMessage("audioOff"));
  191. }
  192. }
  193. }
  194. public boolean isMCUPublisher() {
  195. return isMCUPublisher;
  196. }
  197. private class MagicDataChannelObserver implements DataChannel.Observer {
  198. @Override
  199. public void onBufferedAmountChange(long l) {
  200. }
  201. @Override
  202. public void onStateChange() {
  203. if (magicDataChannel != null && magicDataChannel.state().equals(DataChannel.State.OPEN) &&
  204. magicDataChannel.label().equals("status")) {
  205. sendInitialMediaStatus();
  206. }
  207. }
  208. @Override
  209. public void onMessage(DataChannel.Buffer buffer) {
  210. if (buffer.binary) {
  211. Log.d(TAG, "Received binary msg over " + TAG + " " + sessionId);
  212. return;
  213. }
  214. ByteBuffer data = buffer.data;
  215. final byte[] bytes = new byte[data.capacity()];
  216. data.get(bytes);
  217. String strData = new String(bytes);
  218. Log.d(TAG, "Got msg: " + strData + " over " + TAG + " " + sessionId);
  219. LoggingUtils.INSTANCE.writeLogEntryToFile(context,
  220. "Got msg: " + strData + " over " + peerConnection.hashCode() + " " + sessionId);
  221. try {
  222. DataChannelMessage dataChannelMessage = LoganSquare.parse(strData, DataChannelMessage.class);
  223. String internalNick;
  224. if ("nickChanged".equals(dataChannelMessage.getType())) {
  225. if (dataChannelMessage.getPayload() instanceof String) {
  226. internalNick = (String) dataChannelMessage.getPayload();
  227. if (!internalNick.equals(nick)) {
  228. setNick(internalNick);
  229. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  230. .NICK_CHANGE, sessionId, getNick(), null, videoStreamType));
  231. }
  232. } else {
  233. if (dataChannelMessage.getPayload() != null) {
  234. HashMap<String, String> payloadHashMap = (HashMap<String, String>) dataChannelMessage.getPayload();
  235. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  236. .NICK_CHANGE, payloadHashMap.get("userid"), payloadHashMap.get("name"), null, videoStreamType));
  237. }
  238. }
  239. } else if ("audioOn".equals(dataChannelMessage.getType())) {
  240. remoteAudioOn = true;
  241. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  242. .AUDIO_CHANGE, sessionId, null, remoteAudioOn, videoStreamType));
  243. } else if ("audioOff".equals(dataChannelMessage.getType())) {
  244. remoteAudioOn = false;
  245. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  246. .AUDIO_CHANGE, sessionId, null, remoteAudioOn, videoStreamType));
  247. } else if ("videoOn".equals(dataChannelMessage.getType())) {
  248. remoteVideoOn = true;
  249. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  250. .VIDEO_CHANGE, sessionId, null, remoteVideoOn, videoStreamType));
  251. } else if ("videoOff".equals(dataChannelMessage.getType())) {
  252. remoteVideoOn = false;
  253. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  254. .VIDEO_CHANGE, sessionId, null, remoteVideoOn, videoStreamType));
  255. }
  256. } catch (IOException e) {
  257. Log.d(TAG, "Failed to parse data channel message");
  258. }
  259. }
  260. }
  261. private void restartIce() {
  262. if (connectionAttempts <= 5) {
  263. if (!hasMCU || isMCUPublisher) {
  264. MediaConstraints.KeyValuePair iceRestartConstraint =
  265. new MediaConstraints.KeyValuePair("IceRestart", "true");
  266. if (sdpConstraints.mandatory.contains(iceRestartConstraint)) {
  267. sdpConstraints.mandatory.add(iceRestartConstraint);
  268. }
  269. peerConnection.createOffer(magicSdpObserver, sdpConstraints);
  270. } else {
  271. // we have an MCU and this is not the publisher
  272. // Do something if we have an MCU
  273. }
  274. connectionAttempts++;
  275. }
  276. }
  277. private class MagicPeerConnectionObserver implements PeerConnection.Observer {
  278. private final String TAG = "MagicPeerConnectionObserver";
  279. @Override
  280. public void onSignalingChange(PeerConnection.SignalingState signalingState) {
  281. }
  282. @Override
  283. public void onIceConnectionChange(PeerConnection.IceConnectionState iceConnectionState) {
  284. peerIceConnectionState = iceConnectionState;
  285. LoggingUtils.INSTANCE.writeLogEntryToFile(context,
  286. "iceConnectionChangeTo: " + iceConnectionState.name() + " over " + peerConnection.hashCode() + " " + sessionId);
  287. Log.d("iceConnectionChangeTo: ", iceConnectionState.name() + " over " + peerConnection.hashCode() + " " + sessionId);
  288. if (iceConnectionState.equals(PeerConnection.IceConnectionState.CONNECTED)) {
  289. connectionAttempts = 0;
  290. /*EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  291. .PEER_CONNECTED, sessionId, null, null));*/
  292. if (!isMCUPublisher) {
  293. EventBus.getDefault().post(new MediaStreamEvent(remoteMediaStream, sessionId, videoStreamType));
  294. }
  295. if (hasInitiated) {
  296. sendInitialMediaStatus();
  297. }
  298. } else if (iceConnectionState.equals(PeerConnection.IceConnectionState.CLOSED)) {
  299. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  300. .PEER_CLOSED, sessionId, null, null, videoStreamType));
  301. connectionAttempts = 0;
  302. } else if (iceConnectionState.equals(PeerConnection.IceConnectionState.FAILED)) {
  303. /*if (MerlinTheWizard.isConnectedToInternet() && connectionAttempts < 5) {
  304. restartIce();
  305. }*/
  306. if (isMCUPublisher) {
  307. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType.PUBLISHER_FAILED, sessionId, null, null, null));
  308. }
  309. }
  310. }
  311. @Override
  312. public void onIceConnectionReceivingChange(boolean b) {
  313. }
  314. @Override
  315. public void onIceGatheringChange(PeerConnection.IceGatheringState iceGatheringState) {
  316. }
  317. @Override
  318. public void onIceCandidate(IceCandidate iceCandidate) {
  319. NCIceCandidate ncIceCandidate = new NCIceCandidate();
  320. ncIceCandidate.setSdpMid(iceCandidate.sdpMid);
  321. ncIceCandidate.setSdpMLineIndex(iceCandidate.sdpMLineIndex);
  322. ncIceCandidate.setCandidate(iceCandidate.sdp);
  323. EventBus.getDefault().post(new SessionDescriptionSendEvent(null, sessionId,
  324. "candidate", ncIceCandidate, videoStreamType));
  325. }
  326. @Override
  327. public void onIceCandidatesRemoved(IceCandidate[] iceCandidates) {
  328. }
  329. @Override
  330. public void onAddStream(MediaStream mediaStream) {
  331. remoteMediaStream = mediaStream;
  332. }
  333. @Override
  334. public void onRemoveStream(MediaStream mediaStream) {
  335. if (!isMCUPublisher) {
  336. EventBus.getDefault().post(new MediaStreamEvent(null, sessionId, videoStreamType));
  337. }
  338. }
  339. @Override
  340. public void onDataChannel(DataChannel dataChannel) {
  341. if (dataChannel.label().equals("status")) {
  342. magicDataChannel = dataChannel;
  343. magicDataChannel.registerObserver(new MagicDataChannelObserver());
  344. }
  345. }
  346. @Override
  347. public void onRenegotiationNeeded() {
  348. }
  349. @Override
  350. public void onAddTrack(RtpReceiver rtpReceiver, MediaStream[] mediaStreams) {
  351. }
  352. }
  353. private class MagicSdpObserver implements SdpObserver {
  354. private final String TAG = "MagicSdpObserver";
  355. @Override
  356. public void onCreateFailure(String s) {
  357. Log.d(TAG, s);
  358. LoggingUtils.INSTANCE.writeLogEntryToFile(context,
  359. "SDPObserver createFailure: " + s + " over " + peerConnection.hashCode() + " " + sessionId);
  360. }
  361. @Override
  362. public void onSetFailure(String s) {
  363. Log.d(TAG, s);
  364. LoggingUtils.INSTANCE.writeLogEntryToFile(context,
  365. "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. }