PeerConnectionWrapper.java 22 KB

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