PeerConnectionWrapper.java 22 KB

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