PeerConnectionWrapper.java 21 KB

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