You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TPCUtils.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. import { getLogger } from 'jitsi-meet-logger';
  2. import transform from 'sdp-transform';
  3. import * as JitsiTrackEvents from '../../JitsiTrackEvents';
  4. import * as MediaType from '../../service/RTC/MediaType';
  5. import RTCEvents from '../../service/RTC/RTCEvents';
  6. import * as VideoType from '../../service/RTC/VideoType';
  7. import browser from '../browser';
  8. const logger = getLogger(__filename);
  9. const SIM_LAYER_1_RID = '1';
  10. const SIM_LAYER_2_RID = '2';
  11. const SIM_LAYER_3_RID = '3';
  12. export const SIM_LAYER_RIDS = [ SIM_LAYER_1_RID, SIM_LAYER_2_RID, SIM_LAYER_3_RID ];
  13. /**
  14. * Handles track related operations on TraceablePeerConnection when browser is
  15. * running in unified plan mode.
  16. */
  17. export class TPCUtils {
  18. /**
  19. * @constructor
  20. */
  21. constructor(peerconnection) {
  22. this.pc = peerconnection;
  23. /**
  24. * The simulcast encodings that will be configured on the RTCRtpSender
  25. * for the video tracks in the unified plan mode.
  26. */
  27. this.simulcastEncodings = [
  28. {
  29. active: true,
  30. maxBitrate: browser.isFirefox() ? 2500000 : 200000,
  31. rid: SIM_LAYER_1_RID,
  32. scaleResolutionDownBy: browser.isFirefox() ? 1.0 : 4.0
  33. },
  34. {
  35. active: true,
  36. maxBitrate: 700000,
  37. rid: SIM_LAYER_2_RID,
  38. scaleResolutionDownBy: 2.0
  39. },
  40. {
  41. active: true,
  42. maxBitrate: browser.isFirefox() ? 200000 : 2500000,
  43. rid: SIM_LAYER_3_RID,
  44. scaleResolutionDownBy: browser.isFirefox() ? 4.0 : 1.0
  45. }
  46. ];
  47. /**
  48. * Resolution height constraints for the simulcast encodings that
  49. * are configured for the video tracks.
  50. */
  51. this.simulcastStreamConstraints = [];
  52. }
  53. /**
  54. * Ensures that the ssrcs associated with a FID ssrc-group appear in the correct order, i.e.,
  55. * the primary ssrc first and the secondary rtx ssrc later. This is important for unified
  56. * plan since we have only one FID group per media description.
  57. * @param {Object} description the webRTC session description instance for the remote
  58. * description.
  59. * @private
  60. */
  61. _ensureCorrectOrderOfSsrcs(description) {
  62. const parsedSdp = transform.parse(description.sdp);
  63. parsedSdp.media.forEach(mLine => {
  64. if (mLine.type === 'audio') {
  65. return;
  66. }
  67. if (!mLine.ssrcGroups || !mLine.ssrcGroups.length) {
  68. return;
  69. }
  70. let reorderedSsrcs = [];
  71. mLine.ssrcGroups[0].ssrcs.split(' ').forEach(ssrc => {
  72. const sources = mLine.ssrcs.filter(source => source.id.toString() === ssrc);
  73. reorderedSsrcs = reorderedSsrcs.concat(sources);
  74. });
  75. mLine.ssrcs = reorderedSsrcs;
  76. });
  77. return new RTCSessionDescription({
  78. type: description.type,
  79. sdp: transform.write(parsedSdp)
  80. });
  81. }
  82. /**
  83. * Obtains stream encodings that need to be configured on the given track.
  84. * @param {JitsiLocalTrack} localTrack
  85. */
  86. _getStreamEncodings(localTrack) {
  87. if (this.pc.isSimulcastOn() && localTrack.isVideoTrack()) {
  88. return this.simulcastEncodings;
  89. }
  90. return [ { active: true } ];
  91. }
  92. /**
  93. * Takes in a *unified plan* offer and inserts the appropriate
  94. * parameters for adding simulcast receive support.
  95. * @param {Object} desc - A session description object
  96. * @param {String} desc.type - the type (offer/answer)
  97. * @param {String} desc.sdp - the sdp content
  98. *
  99. * @return {Object} A session description (same format as above) object
  100. * with its sdp field modified to advertise simulcast receive support
  101. */
  102. _insertUnifiedPlanSimulcastReceive(desc) {
  103. // a=simulcast line is not needed on browsers where
  104. // we munge SDP for turning on simulcast. Remove this check
  105. // when we move to RID/MID based simulcast on all browsers.
  106. if (browser.usesSdpMungingForSimulcast()) {
  107. return desc;
  108. }
  109. const sdp = transform.parse(desc.sdp);
  110. const idx = sdp.media.findIndex(mline => mline.type === 'video');
  111. if (sdp.media[idx].rids && (sdp.media[idx].simulcast_03 || sdp.media[idx].simulcast)) {
  112. // Make sure we don't have the simulcast recv line on video descriptions other than the
  113. // the first video description.
  114. sdp.media.forEach((mline, i) => {
  115. if (mline.type === 'video' && i !== idx) {
  116. sdp.media[i].rids = undefined;
  117. sdp.media[i].simulcast = undefined;
  118. // eslint-disable-next-line camelcase
  119. sdp.media[i].simulcast_03 = undefined;
  120. }
  121. });
  122. return new RTCSessionDescription({
  123. type: desc.type,
  124. sdp: transform.write(sdp)
  125. });
  126. }
  127. // In order of highest to lowest spatial quality
  128. sdp.media[idx].rids = [
  129. {
  130. id: SIM_LAYER_1_RID,
  131. direction: 'recv'
  132. },
  133. {
  134. id: SIM_LAYER_2_RID,
  135. direction: 'recv'
  136. },
  137. {
  138. id: SIM_LAYER_3_RID,
  139. direction: 'recv'
  140. }
  141. ];
  142. // Firefox 72 has stopped parsing the legacy rid= parameters in simulcast attributes.
  143. // eslint-disable-next-line max-len
  144. // https://www.fxsitecompat.dev/en-CA/docs/2019/pt-and-rid-in-webrtc-simulcast-attributes-are-no-longer-supported/
  145. const simulcastLine = browser.isFirefox() && browser.isVersionGreaterThan(71)
  146. ? `recv ${SIM_LAYER_RIDS.join(';')}`
  147. : `recv rid=${SIM_LAYER_RIDS.join(';')}`;
  148. // eslint-disable-next-line camelcase
  149. sdp.media[idx].simulcast_03 = {
  150. value: simulcastLine
  151. };
  152. return new RTCSessionDescription({
  153. type: desc.type,
  154. sdp: transform.write(sdp)
  155. });
  156. }
  157. /**
  158. * Constructs resolution height constraints for the simulcast encodings that are
  159. * created for a given local video track.
  160. * @param {MediaStreamTrack} track - the local video track.
  161. * @returns {void}
  162. */
  163. _setSimulcastStreamConstraints(track) {
  164. if (browser.isReactNative()) {
  165. return;
  166. }
  167. const height = track.getSettings().height;
  168. for (const encoding in this.simulcastEncodings) {
  169. if (this.simulcastEncodings.hasOwnProperty(encoding)) {
  170. this.simulcastStreamConstraints.push({
  171. height: height / this.simulcastEncodings[encoding].scaleResolutionDownBy,
  172. rid: this.simulcastEncodings[encoding].rid
  173. });
  174. }
  175. }
  176. }
  177. /**
  178. * Adds {@link JitsiLocalTrack} to the WebRTC peerconnection for the first time.
  179. * @param {JitsiLocalTrack} track - track to be added to the peerconnection.
  180. * @returns {boolean} Returns true if the operation is successful,
  181. * false otherwise.
  182. */
  183. addTrack(localTrack, isInitiator = true) {
  184. const track = localTrack.getTrack();
  185. if (isInitiator) {
  186. // Use pc.addTransceiver() for the initiator case when local tracks are getting added
  187. // to the peerconnection before a session-initiate is sent over to the peer.
  188. const transceiverInit = {
  189. direction: 'sendrecv',
  190. streams: [ localTrack.getOriginalStream() ],
  191. sendEncodings: []
  192. };
  193. if (!browser.isFirefox()) {
  194. transceiverInit.sendEncodings = this._getStreamEncodings(localTrack);
  195. }
  196. this.pc.peerconnection.addTransceiver(track, transceiverInit);
  197. } else {
  198. // Use pc.addTrack() for responder case so that we can re-use the m-lines that were created
  199. // when setRemoteDescription was called. pc.addTrack() automatically attaches to any existing
  200. // unused "recv-only" transceiver.
  201. this.pc.peerconnection.addTrack(track);
  202. }
  203. // Construct the simulcast stream constraints for the newly added track.
  204. if (localTrack.isVideoTrack() && localTrack.videoType === VideoType.CAMERA && this.pc.isSimulcastOn()) {
  205. this._setSimulcastStreamConstraints(localTrack.getTrack());
  206. }
  207. }
  208. /**
  209. * Adds a track on the RTCRtpSender as part of the unmute operation.
  210. * @param {JitsiLocalTrack} localTrack - track to be unmuted.
  211. * @returns {Promise<boolean>} - Promise that resolves to false if unmute
  212. * operation is successful, a reject otherwise.
  213. */
  214. addTrackUnmute(localTrack) {
  215. const mediaType = localTrack.getType();
  216. const track = localTrack.getTrack();
  217. // The assumption here is that the first transceiver of the specified
  218. // media type is that of the local track.
  219. const transceiver = this.pc.peerconnection.getTransceivers()
  220. .find(t => t.receiver && t.receiver.track && t.receiver.track.kind === mediaType);
  221. if (!transceiver) {
  222. return Promise.reject(new Error(`RTCRtpTransceiver for ${mediaType} not found`));
  223. }
  224. logger.debug(`Adding ${localTrack} on ${this.pc}`);
  225. // If the client starts with audio/video muted setting, the transceiver direction
  226. // will be set to 'recvonly'. Use addStream here so that a MSID is generated for the stream.
  227. if (transceiver.direction === 'recvonly') {
  228. const stream = localTrack.getOriginalStream();
  229. if (stream) {
  230. this.pc.peerconnection.addStream(localTrack.getOriginalStream());
  231. this.setEncodings(localTrack);
  232. this.pc.localTracks.set(localTrack.rtcId, localTrack);
  233. transceiver.direction = 'sendrecv';
  234. }
  235. return Promise.resolve(false);
  236. }
  237. return transceiver.sender.replaceTrack(track)
  238. .then(() => {
  239. this.pc.localTracks.set(localTrack.rtcId, localTrack);
  240. return Promise.resolve(false);
  241. });
  242. }
  243. /**
  244. * Removes the track from the RTCRtpSender as part of the mute operation.
  245. * @param {JitsiLocalTrack} localTrack - track to be removed.
  246. * @returns {Promise<boolean>} - Promise that resolves to false if unmute
  247. * operation is successful, a reject otherwise.
  248. */
  249. removeTrackMute(localTrack) {
  250. const mediaType = localTrack.getType();
  251. const transceiver = this.pc.peerconnection.getTransceivers()
  252. .find(t => t.sender && t.sender.track && t.sender.track.id === localTrack.getTrackId());
  253. if (!transceiver) {
  254. return Promise.reject(new Error(`RTCRtpTransceiver for ${mediaType} not found`));
  255. }
  256. logger.debug(`Removing ${localTrack} on ${this.pc}`);
  257. return transceiver.sender.replaceTrack(null)
  258. .then(() => {
  259. this.pc.localTracks.delete(localTrack.rtcId);
  260. return Promise.resolve(false);
  261. });
  262. }
  263. /**
  264. * Replaces the existing track on a RTCRtpSender with the given track.
  265. * @param {JitsiLocalTrack} oldTrack - existing track on the sender that needs to be removed.
  266. * @param {JitsiLocalTrack} newTrack - new track that needs to be added to the sender.
  267. * @returns {Promise<false>} Promise that resolves with false as we don't want
  268. * renegotiation to be triggered automatically after this operation. Renegotiation is
  269. * done when the browser fires the negotiationeeded event.
  270. */
  271. replaceTrack(oldTrack, newTrack) {
  272. if (oldTrack && newTrack) {
  273. const mediaType = newTrack.getType();
  274. const stream = newTrack.getOriginalStream();
  275. const track = mediaType === MediaType.AUDIO
  276. ? stream.getAudioTracks()[0]
  277. : stream.getVideoTracks()[0];
  278. const transceiver = this.pc.peerconnection.getTransceivers()
  279. .find(t => t.receiver.track.kind === mediaType && !t.stopped);
  280. if (!transceiver) {
  281. return Promise.reject(new Error('replace track failed'));
  282. }
  283. logger.debug(`Replacing ${oldTrack} with ${newTrack} on ${this.pc}`);
  284. return transceiver.sender.replaceTrack(track)
  285. .then(() => {
  286. const ssrc = this.pc.localSSRCs.get(oldTrack.rtcId);
  287. this.pc.localTracks.delete(oldTrack.rtcId);
  288. this.pc.localSSRCs.delete(oldTrack.rtcId);
  289. this.pc._addedStreams = this.pc._addedStreams.filter(s => s !== stream);
  290. this.pc.localTracks.set(newTrack.rtcId, newTrack);
  291. this.pc._addedStreams.push(stream);
  292. this.pc.localSSRCs.set(newTrack.rtcId, ssrc);
  293. this.pc.eventEmitter.emit(RTCEvents.LOCAL_TRACK_SSRC_UPDATED,
  294. newTrack,
  295. this.pc._extractPrimarySSRC(ssrc));
  296. });
  297. } else if (oldTrack && !newTrack) {
  298. if (!this.removeTrackMute(oldTrack)) {
  299. return Promise.reject(new Error('replace track failed'));
  300. }
  301. this.pc.localTracks.delete(oldTrack.rtcId);
  302. this.pc.localSSRCs.delete(oldTrack.rtcId);
  303. } else if (newTrack && !oldTrack) {
  304. const ssrc = this.pc.localSSRCs.get(newTrack.rtcId);
  305. if (!this.addTrackUnmute(newTrack)) {
  306. return Promise.reject(new Error('replace track failed'));
  307. }
  308. newTrack.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED, newTrack);
  309. this.pc.localTracks.set(newTrack.rtcId, newTrack);
  310. this.pc.localSSRCs.set(newTrack.rtcId, ssrc);
  311. }
  312. return Promise.resolve(false);
  313. }
  314. /**
  315. * Enables/disables audio transmission on the peer connection. When
  316. * disabled the audio transceiver direction will be set to 'inactive'
  317. * which means that no data will be sent nor accepted, but
  318. * the connection should be kept alive.
  319. * @param {boolean} active - true to enable audio media transmission or
  320. * false to disable.
  321. * @returns {false} - returns false always so that renegotiation is not automatically
  322. * triggered after this operation.
  323. */
  324. setAudioTransferActive(active) {
  325. return this.setMediaTransferActive('audio', active);
  326. }
  327. /**
  328. * Set the simulcast stream encoding properties on the RTCRtpSender.
  329. * @param {JitsiLocalTrack} track - the current track in use for which
  330. * the encodings are to be set.
  331. */
  332. setEncodings(track) {
  333. const transceiver = this.pc.peerconnection.getTransceivers()
  334. .find(t => t.sender && t.sender.track && t.sender.track.kind === track.getType());
  335. const parameters = transceiver.sender.getParameters();
  336. parameters.encodings = this._getStreamEncodings(track);
  337. transceiver.sender.setParameters(parameters);
  338. }
  339. /**
  340. * Enables/disables media transmission on the peerconnection by changing the direction
  341. * on the transceiver for the specified media type.
  342. * @param {String} mediaType - 'audio' or 'video'
  343. * @param {boolean} active - true to enable media transmission or false
  344. * to disable.
  345. * @returns {false} - returns false always so that renegotiation is not automatically
  346. * triggered after this operation
  347. */
  348. setMediaTransferActive(mediaType, active) {
  349. const transceivers = this.pc.peerconnection.getTransceivers()
  350. .filter(t => t.receiver && t.receiver.track && t.receiver.track.kind === mediaType);
  351. const localTracks = Array.from(this.pc.localTracks.values())
  352. .filter(track => track.getType() === mediaType);
  353. if (active) {
  354. transceivers.forEach(transceiver => {
  355. if (localTracks.length) {
  356. transceiver.direction = 'sendrecv';
  357. const parameters = transceiver.sender.getParameters();
  358. if (parameters && parameters.encodings && parameters.encodings.length) {
  359. parameters.encodings.forEach(encoding => {
  360. encoding.active = true;
  361. });
  362. transceiver.sender.setParameters(parameters);
  363. }
  364. } else {
  365. transceiver.direction = 'recvonly';
  366. }
  367. });
  368. } else {
  369. transceivers.forEach(transceiver => {
  370. transceiver.direction = 'inactive';
  371. });
  372. }
  373. return false;
  374. }
  375. /**
  376. * Enables/disables video media transmission on the peer connection. When
  377. * disabled the SDP video media direction in the local SDP will be adjusted to
  378. * 'inactive' which means that no data will be sent nor accepted, but
  379. * the connection should be kept alive.
  380. * @param {boolean} active - true to enable video media transmission or
  381. * false to disable.
  382. * @returns {false} - returns false always so that renegotiation is not automatically
  383. * triggered after this operation.
  384. */
  385. setVideoTransferActive(active) {
  386. return this.setMediaTransferActive('video', active);
  387. }
  388. }