PeerConnectionWrapper.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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.MediaStreamTrack;
  44. import org.webrtc.PeerConnection;
  45. import org.webrtc.PeerConnectionFactory;
  46. import org.webrtc.RtpReceiver;
  47. import org.webrtc.RtpTransceiver;
  48. import org.webrtc.SdpObserver;
  49. import org.webrtc.SessionDescription;
  50. import org.webrtc.VideoTrack;
  51. import java.io.IOException;
  52. import java.nio.ByteBuffer;
  53. import java.util.ArrayList;
  54. import java.util.Collections;
  55. import java.util.HashMap;
  56. import java.util.List;
  57. import java.util.Objects;
  58. import javax.inject.Inject;
  59. import androidx.annotation.Nullable;
  60. import autodagger.AutoInjector;
  61. import static java.lang.Boolean.FALSE;
  62. import static java.lang.Boolean.TRUE;
  63. @AutoInjector(NextcloudTalkApplication.class)
  64. public class PeerConnectionWrapper {
  65. private static final String TAG = PeerConnectionWrapper.class.getCanonicalName();
  66. private List<IceCandidate> iceCandidates = new ArrayList<>();
  67. private PeerConnection peerConnection;
  68. private String sessionId;
  69. private String nick;
  70. private final MediaConstraints mediaConstraints;
  71. private DataChannel dataChannel;
  72. private final MagicSdpObserver magicSdpObserver;
  73. private MediaStream remoteStream;
  74. private final boolean hasInitiated;
  75. private final MediaStream localStream;
  76. private final boolean isMCUPublisher;
  77. private final String videoStreamType;
  78. @Inject
  79. Context context;
  80. public PeerConnectionWrapper(PeerConnectionFactory peerConnectionFactory,
  81. List<PeerConnection.IceServer> iceServerList,
  82. MediaConstraints mediaConstraints,
  83. String sessionId, String localSession, @Nullable MediaStream localStream,
  84. boolean isMCUPublisher, boolean hasMCU, String videoStreamType) {
  85. Objects.requireNonNull(NextcloudTalkApplication.Companion.getSharedApplication()).getComponentApplication().inject(this);
  86. this.localStream = localStream;
  87. this.videoStreamType = videoStreamType;
  88. this.sessionId = sessionId;
  89. this.mediaConstraints = mediaConstraints;
  90. magicSdpObserver = new MagicSdpObserver();
  91. hasInitiated = sessionId.compareTo(localSession) < 0;
  92. this.isMCUPublisher = isMCUPublisher;
  93. PeerConnection.RTCConfiguration configuration = new PeerConnection.RTCConfiguration(iceServerList);
  94. configuration.sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN;
  95. peerConnection = peerConnectionFactory.createPeerConnection(configuration, new MagicPeerConnectionObserver());
  96. if (peerConnection != null) {
  97. if (this.localStream != null) {
  98. List<String> localStreamIds = Collections.singletonList(this.localStream.getId());
  99. for(AudioTrack track : this.localStream.audioTracks) {
  100. peerConnection.addTrack(track, localStreamIds);
  101. }
  102. for(VideoTrack track : this.localStream.videoTracks) {
  103. peerConnection.addTrack(track, localStreamIds);
  104. }
  105. }
  106. if (hasMCU || hasInitiated) {
  107. DataChannel.Init init = new DataChannel.Init();
  108. init.negotiated = false;
  109. dataChannel = peerConnection.createDataChannel("status", init);
  110. dataChannel.registerObserver(new MagicDataChannelObserver());
  111. if (isMCUPublisher) {
  112. peerConnection.createOffer(magicSdpObserver, mediaConstraints);
  113. } else if (hasMCU && this.videoStreamType.equals("video")) {
  114. // If the connection type is "screen" the client sharing the screen will send an
  115. // offer; offers should be requested only for videos.
  116. HashMap<String, String> hashMap = new HashMap<>();
  117. hashMap.put("sessionId", sessionId);
  118. EventBus.getDefault().post(new WebSocketCommunicationEvent("peerReadyForRequestingOffer", hashMap));
  119. } else if (!hasMCU && hasInitiated) {
  120. peerConnection.createOffer(magicSdpObserver, mediaConstraints);
  121. }
  122. }
  123. }
  124. }
  125. public String getVideoStreamType() {
  126. return videoStreamType;
  127. }
  128. public void removePeerConnection() {
  129. if (dataChannel != null) {
  130. dataChannel.dispose();
  131. dataChannel = null;
  132. Log.d(TAG, "Disposed DataChannel");
  133. } else {
  134. Log.d(TAG, "DataChannel is null.");
  135. }
  136. if (peerConnection != null) {
  137. peerConnection.close();
  138. peerConnection = null;
  139. Log.d(TAG, "Disposed PeerConnection");
  140. } else {
  141. Log.d(TAG, "PeerConnection is null.");
  142. }
  143. }
  144. public void drainIceCandidates() {
  145. if (peerConnection != null) {
  146. for (IceCandidate iceCandidate : iceCandidates) {
  147. peerConnection.addIceCandidate(iceCandidate);
  148. }
  149. iceCandidates = new ArrayList<>();
  150. }
  151. }
  152. public MagicSdpObserver getMagicSdpObserver() {
  153. return magicSdpObserver;
  154. }
  155. public void addCandidate(IceCandidate iceCandidate) {
  156. if (peerConnection != null && peerConnection.getRemoteDescription() != null) {
  157. peerConnection.addIceCandidate(iceCandidate);
  158. } else {
  159. iceCandidates.add(iceCandidate);
  160. }
  161. }
  162. public void sendNickChannelData(DataChannelMessageNick dataChannelMessage) {
  163. ByteBuffer buffer;
  164. if (dataChannel != null) {
  165. try {
  166. buffer = ByteBuffer.wrap(LoganSquare.serialize(dataChannelMessage).getBytes());
  167. dataChannel.send(new DataChannel.Buffer(buffer, false));
  168. } catch (IOException e) {
  169. Log.d(TAG, "Failed to send channel data, attempting regular " + dataChannelMessage);
  170. }
  171. }
  172. }
  173. public void sendChannelData(DataChannelMessage dataChannelMessage) {
  174. ByteBuffer buffer;
  175. if (dataChannel != null) {
  176. try {
  177. buffer = ByteBuffer.wrap(LoganSquare.serialize(dataChannelMessage).getBytes());
  178. dataChannel.send(new DataChannel.Buffer(buffer, false));
  179. } catch (IOException e) {
  180. Log.d(TAG, "Failed to send channel data, attempting regular " + dataChannelMessage);
  181. }
  182. }
  183. }
  184. public PeerConnection getPeerConnection() {
  185. return peerConnection;
  186. }
  187. public String getSessionId() {
  188. return sessionId;
  189. }
  190. public void setSessionId(String sessionId) {
  191. this.sessionId = sessionId;
  192. }
  193. public String getNick() {
  194. if (!TextUtils.isEmpty(nick)) {
  195. return nick;
  196. } else {
  197. return Objects.requireNonNull(NextcloudTalkApplication.Companion.getSharedApplication()).getString(R.string.nc_nick_guest);
  198. }
  199. }
  200. public void setNick(String nick) {
  201. this.nick = nick;
  202. }
  203. private void sendInitialMediaStatus() {
  204. if (localStream != null) {
  205. if (localStream.videoTracks.size() == 1 && localStream.videoTracks.get(0).enabled()) {
  206. sendChannelData(new DataChannelMessage("videoOn"));
  207. } else {
  208. sendChannelData(new DataChannelMessage("videoOff"));
  209. }
  210. if (localStream.audioTracks.size() == 1 && localStream.audioTracks.get(0).enabled()) {
  211. sendChannelData(new DataChannelMessage("audioOn"));
  212. } else {
  213. sendChannelData(new DataChannelMessage("audioOff"));
  214. }
  215. }
  216. }
  217. public boolean isMCUPublisher() {
  218. return isMCUPublisher;
  219. }
  220. private boolean shouldNotReceiveVideo() {
  221. for (MediaConstraints.KeyValuePair keyValuePair : mediaConstraints.mandatory) {
  222. if ("OfferToReceiveVideo".equals(keyValuePair.getKey())) {
  223. return !Boolean.parseBoolean(keyValuePair.getValue());
  224. }
  225. }
  226. return false;
  227. }
  228. private class MagicDataChannelObserver implements DataChannel.Observer {
  229. @Override
  230. public void onBufferedAmountChange(long l) {
  231. }
  232. @Override
  233. public void onStateChange() {
  234. if (dataChannel != null && dataChannel.state() == DataChannel.State.OPEN &&
  235. dataChannel.label().equals("status")) {
  236. sendInitialMediaStatus();
  237. }
  238. }
  239. @Override
  240. public void onMessage(DataChannel.Buffer buffer) {
  241. if (buffer.binary) {
  242. Log.d(TAG, "Received binary msg over " + TAG + " " + sessionId);
  243. return;
  244. }
  245. ByteBuffer data = buffer.data;
  246. final byte[] bytes = new byte[data.capacity()];
  247. data.get(bytes);
  248. String strData = new String(bytes);
  249. Log.d(TAG, "Got msg: " + strData + " over " + TAG + " " + sessionId);
  250. try {
  251. DataChannelMessage dataChannelMessage = LoganSquare.parse(strData, DataChannelMessage.class);
  252. String internalNick;
  253. if ("nickChanged".equals(dataChannelMessage.getType())) {
  254. if (dataChannelMessage.getPayload() instanceof String) {
  255. internalNick = (String) dataChannelMessage.getPayload();
  256. if (!internalNick.equals(nick)) {
  257. setNick(internalNick);
  258. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  259. .NICK_CHANGE, sessionId, getNick(), null, videoStreamType));
  260. }
  261. } else {
  262. if (dataChannelMessage.getPayload() != null) {
  263. HashMap<String, String> payloadHashMap = (HashMap<String, String>) dataChannelMessage.getPayload();
  264. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  265. .NICK_CHANGE, sessionId, payloadHashMap.get("name"), null, videoStreamType));
  266. }
  267. }
  268. } else if ("audioOn".equals(dataChannelMessage.getType())) {
  269. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  270. .AUDIO_CHANGE, sessionId, null, TRUE, videoStreamType));
  271. } else if ("audioOff".equals(dataChannelMessage.getType())) {
  272. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  273. .AUDIO_CHANGE, sessionId, null, FALSE, videoStreamType));
  274. } else if ("videoOn".equals(dataChannelMessage.getType())) {
  275. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  276. .VIDEO_CHANGE, sessionId, null, TRUE, videoStreamType));
  277. } else if ("videoOff".equals(dataChannelMessage.getType())) {
  278. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  279. .VIDEO_CHANGE, sessionId, null, FALSE, videoStreamType));
  280. }
  281. } catch (IOException e) {
  282. Log.d(TAG, "Failed to parse data channel message");
  283. }
  284. }
  285. }
  286. private class MagicPeerConnectionObserver implements PeerConnection.Observer {
  287. @Override
  288. public void onSignalingChange(PeerConnection.SignalingState signalingState) {
  289. }
  290. @Override
  291. public void onIceConnectionChange(PeerConnection.IceConnectionState iceConnectionState) {
  292. Log.d("iceConnectionChangeTo: ", iceConnectionState.name() + " over " + peerConnection.hashCode() + " " + sessionId);
  293. if (iceConnectionState == PeerConnection.IceConnectionState.CONNECTED) {
  294. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType.PEER_CONNECTED,
  295. sessionId, null, null, videoStreamType));
  296. if (!isMCUPublisher) {
  297. EventBus.getDefault().post(new MediaStreamEvent(remoteStream, sessionId, videoStreamType));
  298. }
  299. if (hasInitiated) {
  300. sendInitialMediaStatus();
  301. }
  302. } else if (iceConnectionState == PeerConnection.IceConnectionState.COMPLETED) {
  303. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType.PEER_CONNECTED,
  304. sessionId, null, null, videoStreamType));
  305. } else if (iceConnectionState == PeerConnection.IceConnectionState.CLOSED) {
  306. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType
  307. .PEER_CLOSED, sessionId, null, null, videoStreamType));
  308. } else if (iceConnectionState == PeerConnection.IceConnectionState.DISCONNECTED ||
  309. iceConnectionState == PeerConnection.IceConnectionState.NEW ||
  310. iceConnectionState == PeerConnection.IceConnectionState.CHECKING) {
  311. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType.PEER_DISCONNECTED,
  312. sessionId, null, null, videoStreamType));
  313. } else if (iceConnectionState == PeerConnection.IceConnectionState.FAILED) {
  314. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType.PEER_DISCONNECTED,
  315. sessionId, null, null, videoStreamType));
  316. if (isMCUPublisher) {
  317. EventBus.getDefault().post(new PeerConnectionEvent(PeerConnectionEvent.PeerConnectionEventType.PUBLISHER_FAILED, sessionId, null, null, videoStreamType));
  318. }
  319. }
  320. }
  321. @Override
  322. public void onIceConnectionReceivingChange(boolean b) {
  323. }
  324. @Override
  325. public void onIceGatheringChange(PeerConnection.IceGatheringState iceGatheringState) {
  326. }
  327. @Override
  328. public void onIceCandidate(IceCandidate iceCandidate) {
  329. NCIceCandidate ncIceCandidate = new NCIceCandidate();
  330. ncIceCandidate.setSdpMid(iceCandidate.sdpMid);
  331. ncIceCandidate.setSdpMLineIndex(iceCandidate.sdpMLineIndex);
  332. ncIceCandidate.setCandidate(iceCandidate.sdp);
  333. EventBus.getDefault().post(new SessionDescriptionSendEvent(null, sessionId,
  334. "candidate", ncIceCandidate, videoStreamType));
  335. }
  336. @Override
  337. public void onIceCandidatesRemoved(IceCandidate[] iceCandidates) {
  338. }
  339. @Override
  340. public void onAddStream(MediaStream mediaStream) {
  341. remoteStream = mediaStream;
  342. }
  343. @Override
  344. public void onRemoveStream(MediaStream mediaStream) {
  345. if (!isMCUPublisher) {
  346. EventBus.getDefault().post(new MediaStreamEvent(null, sessionId, videoStreamType));
  347. }
  348. }
  349. @Override
  350. public void onDataChannel(DataChannel dataChannel) {
  351. if (dataChannel.label().equals("status") || dataChannel.label().equals("JanusDataChannel")) {
  352. PeerConnectionWrapper.this.dataChannel = dataChannel;
  353. PeerConnectionWrapper.this.dataChannel.registerObserver(new MagicDataChannelObserver());
  354. }
  355. }
  356. @Override
  357. public void onRenegotiationNeeded() {
  358. }
  359. @Override
  360. public void onAddTrack(RtpReceiver rtpReceiver, MediaStream[] mediaStreams) {
  361. }
  362. }
  363. private class MagicSdpObserver implements SdpObserver {
  364. private static final String TAG = "MagicSdpObserver";
  365. @Override
  366. public void onCreateFailure(String s) {
  367. Log.d(TAG, "SDPObserver createFailure: " + s + " over " + peerConnection.hashCode() + " " + sessionId);
  368. }
  369. @Override
  370. public void onSetFailure(String s) {
  371. Log.d(TAG,"SDPObserver setFailure: " + s + " over " + peerConnection.hashCode() + " " + sessionId);
  372. }
  373. @Override
  374. public void onCreateSuccess(SessionDescription sessionDescription) {
  375. SessionDescription sessionDescriptionWithPreferredCodec;
  376. String sessionDescriptionStringWithPreferredCodec = MagicWebRTCUtils.preferCodec
  377. (sessionDescription.description,
  378. "H264", false);
  379. sessionDescriptionWithPreferredCodec = new SessionDescription(
  380. sessionDescription.type,
  381. sessionDescriptionStringWithPreferredCodec);
  382. EventBus.getDefault().post(new SessionDescriptionSendEvent(sessionDescriptionWithPreferredCodec, sessionId,
  383. sessionDescription.type.canonicalForm().toLowerCase(), null, videoStreamType));
  384. if (peerConnection != null) {
  385. peerConnection.setLocalDescription(magicSdpObserver, sessionDescriptionWithPreferredCodec);
  386. }
  387. }
  388. @Override
  389. public void onSetSuccess() {
  390. if (peerConnection != null) {
  391. if (peerConnection.getLocalDescription() == null) {
  392. if (shouldNotReceiveVideo()) {
  393. for (RtpTransceiver t : peerConnection.getTransceivers()) {
  394. if (t.getMediaType() == MediaStreamTrack.MediaType.MEDIA_TYPE_VIDEO) {
  395. t.stop();
  396. }
  397. }
  398. Log.d(TAG, "Stop all Transceivers for MEDIA_TYPE_VIDEO.");
  399. }
  400. /*
  401. Passed 'MediaConstraints' will be ignored by WebRTC when using UNIFIED PLAN.
  402. See for details: https://docs.google.com/document/d/1PPHWV6108znP1tk_rkCnyagH9FK205hHeE9k5mhUzOg/edit#heading=h.9dcmkavg608r
  403. */
  404. peerConnection.createAnswer(magicSdpObserver, new MediaConstraints());
  405. }
  406. if (peerConnection.getRemoteDescription() != null) {
  407. drainIceCandidates();
  408. }
  409. }
  410. }
  411. }
  412. }