PeerConnectionWrapper.java 21 KB

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