PeerConnectionWrapper.java 18 KB

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