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.

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