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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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 browser from '../browser';
  7. const logger = getLogger(__filename);
  8. const SIM_LAYER_1_RID = '1';
  9. const SIM_LAYER_2_RID = '2';
  10. const SIM_LAYER_3_RID = '3';
  11. export const SIM_LAYER_RIDS = [ SIM_LAYER_1_RID, SIM_LAYER_2_RID, SIM_LAYER_3_RID ];
  12. /**
  13. * Handles track related operations on TraceablePeerConnection when browser is
  14. * running in unified plan mode.
  15. */
  16. export class TPCUtils {
  17. /**
  18. * Creates a new instance for a given TraceablePeerConnection
  19. *
  20. * @param peerconnection - the tpc instance for which we have utility functions.
  21. * @param videoBitrates - the bitrates to be configured on the video senders for
  22. * different resolutions both in unicast and simulcast mode.
  23. */
  24. constructor(peerconnection, videoBitrates) {
  25. this.pc = peerconnection;
  26. this.videoBitrates = videoBitrates;
  27. /**
  28. * The startup configuration for the stream encodings that are applicable to
  29. * the video stream when a new sender is created on the peerconnection. The initial
  30. * config takes into account the differences in browser's simulcast implementation.
  31. *
  32. * Encoding parameters:
  33. * active - determine the on/off state of a particular encoding.
  34. * maxBitrate - max. bitrate value to be applied to that particular encoding
  35. * based on the encoding's resolution and config.js videoQuality settings if applicable.
  36. * rid - Rtp Stream ID that is configured for a particular simulcast stream.
  37. * scaleResolutionDownBy - the factor by which the encoding is scaled down from the
  38. * original resolution of the captured video.
  39. */
  40. this.localStreamEncodingsConfig = [
  41. {
  42. active: true,
  43. maxBitrate: browser.isFirefox() ? this.videoBitrates.high : this.videoBitrates.low,
  44. rid: SIM_LAYER_1_RID,
  45. scaleResolutionDownBy: browser.isFirefox() ? 1.0 : 4.0
  46. },
  47. {
  48. active: true,
  49. maxBitrate: this.videoBitrates.standard,
  50. rid: SIM_LAYER_2_RID,
  51. scaleResolutionDownBy: 2.0
  52. },
  53. {
  54. active: true,
  55. maxBitrate: browser.isFirefox() ? this.videoBitrates.low : this.videoBitrates.high,
  56. rid: SIM_LAYER_3_RID,
  57. scaleResolutionDownBy: browser.isFirefox() ? 4.0 : 1.0
  58. }
  59. ];
  60. }
  61. /**
  62. * Ensures that the ssrcs associated with a FID ssrc-group appear in the correct order, i.e.,
  63. * the primary ssrc first and the secondary rtx ssrc later. This is important for unified
  64. * plan since we have only one FID group per media description.
  65. * @param {Object} description the webRTC session description instance for the remote
  66. * description.
  67. * @private
  68. */
  69. ensureCorrectOrderOfSsrcs(description) {
  70. const parsedSdp = transform.parse(description.sdp);
  71. parsedSdp.media.forEach(mLine => {
  72. if (mLine.type === 'audio') {
  73. return;
  74. }
  75. if (!mLine.ssrcGroups || !mLine.ssrcGroups.length) {
  76. return;
  77. }
  78. let reorderedSsrcs = [];
  79. mLine.ssrcGroups[0].ssrcs.split(' ').forEach(ssrc => {
  80. const sources = mLine.ssrcs.filter(source => source.id.toString() === ssrc);
  81. reorderedSsrcs = reorderedSsrcs.concat(sources);
  82. });
  83. mLine.ssrcs = reorderedSsrcs;
  84. });
  85. return new RTCSessionDescription({
  86. type: description.type,
  87. sdp: transform.write(parsedSdp)
  88. });
  89. }
  90. /**
  91. * Obtains stream encodings that need to be configured on the given track based
  92. * on the track media type and the simulcast setting.
  93. * @param {JitsiLocalTrack} localTrack
  94. */
  95. _getStreamEncodings(localTrack) {
  96. if (this.pc.isSimulcastOn() && localTrack.isVideoTrack()) {
  97. return this.localStreamEncodingsConfig;
  98. }
  99. return localTrack.isVideoTrack()
  100. ? [ {
  101. active: true,
  102. maxBitrate: this.videoBitrates.high
  103. } ]
  104. : [ { active: true } ];
  105. }
  106. /**
  107. * Takes in a *unified plan* offer and inserts the appropriate
  108. * parameters for adding simulcast receive support.
  109. * @param {Object} desc - A session description object
  110. * @param {String} desc.type - the type (offer/answer)
  111. * @param {String} desc.sdp - the sdp content
  112. *
  113. * @return {Object} A session description (same format as above) object
  114. * with its sdp field modified to advertise simulcast receive support
  115. */
  116. insertUnifiedPlanSimulcastReceive(desc) {
  117. // a=simulcast line is not needed on browsers where
  118. // we munge SDP for turning on simulcast. Remove this check
  119. // when we move to RID/MID based simulcast on all browsers.
  120. if (browser.usesSdpMungingForSimulcast()) {
  121. return desc;
  122. }
  123. const sdp = transform.parse(desc.sdp);
  124. const idx = sdp.media.findIndex(mline => mline.type === 'video');
  125. if (sdp.media[idx].rids && (sdp.media[idx].simulcast_03 || sdp.media[idx].simulcast)) {
  126. // Make sure we don't have the simulcast recv line on video descriptions other than the
  127. // the first video description.
  128. sdp.media.forEach((mline, i) => {
  129. if (mline.type === 'video' && i !== idx) {
  130. sdp.media[i].rids = undefined;
  131. sdp.media[i].simulcast = undefined;
  132. // eslint-disable-next-line camelcase
  133. sdp.media[i].simulcast_03 = undefined;
  134. }
  135. });
  136. return new RTCSessionDescription({
  137. type: desc.type,
  138. sdp: transform.write(sdp)
  139. });
  140. }
  141. // In order of highest to lowest spatial quality
  142. sdp.media[idx].rids = [
  143. {
  144. id: SIM_LAYER_1_RID,
  145. direction: 'recv'
  146. },
  147. {
  148. id: SIM_LAYER_2_RID,
  149. direction: 'recv'
  150. },
  151. {
  152. id: SIM_LAYER_3_RID,
  153. direction: 'recv'
  154. }
  155. ];
  156. // Firefox 72 has stopped parsing the legacy rid= parameters in simulcast attributes.
  157. // eslint-disable-next-line max-len
  158. // https://www.fxsitecompat.dev/en-CA/docs/2019/pt-and-rid-in-webrtc-simulcast-attributes-are-no-longer-supported/
  159. const simulcastLine = browser.isFirefox() && browser.isVersionGreaterThan(71)
  160. ? `recv ${SIM_LAYER_RIDS.join(';')}`
  161. : `recv rid=${SIM_LAYER_RIDS.join(';')}`;
  162. // eslint-disable-next-line camelcase
  163. sdp.media[idx].simulcast_03 = {
  164. value: simulcastLine
  165. };
  166. return new RTCSessionDescription({
  167. type: desc.type,
  168. sdp: transform.write(sdp)
  169. });
  170. }
  171. /**
  172. * Adds {@link JitsiLocalTrack} to the WebRTC peerconnection for the first time.
  173. * @param {JitsiLocalTrack} track - track to be added to the peerconnection.
  174. * @param {boolean} isInitiator - boolean that indicates if the endpoint is offerer
  175. * in a p2p connection.
  176. * @returns {void}
  177. */
  178. addTrack(localTrack, isInitiator) {
  179. const track = localTrack.getTrack();
  180. if (isInitiator) {
  181. // Use pc.addTransceiver() for the initiator case when local tracks are getting added
  182. // to the peerconnection before a session-initiate is sent over to the peer.
  183. const transceiverInit = {
  184. direction: 'sendrecv',
  185. streams: [ localTrack.getOriginalStream() ],
  186. sendEncodings: []
  187. };
  188. if (!browser.isFirefox()) {
  189. transceiverInit.sendEncodings = this._getStreamEncodings(localTrack);
  190. }
  191. this.pc.peerconnection.addTransceiver(track, transceiverInit);
  192. } else {
  193. // Use pc.addTrack() for responder case so that we can re-use the m-lines that were created
  194. // when setRemoteDescription was called. pc.addTrack() automatically attaches to any existing
  195. // unused "recv-only" transceiver.
  196. this.pc.peerconnection.addTrack(track);
  197. }
  198. }
  199. /**
  200. * Adds a track on the RTCRtpSender as part of the unmute operation.
  201. * @param {JitsiLocalTrack} localTrack - track to be unmuted.
  202. * @returns {Promise<void>} - resolved when done.
  203. */
  204. addTrackUnmute(localTrack) {
  205. const mediaType = localTrack.getType();
  206. const track = localTrack.getTrack();
  207. // The assumption here is that the first transceiver of the specified
  208. // media type is that of the local track.
  209. const transceiver = this.pc.peerconnection.getTransceivers()
  210. .find(t => t.receiver && t.receiver.track && t.receiver.track.kind === mediaType);
  211. if (!transceiver) {
  212. return Promise.reject(new Error(`RTCRtpTransceiver for ${mediaType} not found`));
  213. }
  214. logger.debug(`Adding ${localTrack} on ${this.pc}`);
  215. // If the client starts with audio/video muted setting, the transceiver direction
  216. // will be set to 'recvonly'. Use addStream here so that a MSID is generated for the stream.
  217. if (transceiver.direction === 'recvonly') {
  218. const stream = localTrack.getOriginalStream();
  219. if (stream) {
  220. this.pc.peerconnection.addStream(localTrack.getOriginalStream());
  221. return this.setEncodings(localTrack).then(() => {
  222. this.pc.localTracks.set(localTrack.rtcId, localTrack);
  223. transceiver.direction = 'sendrecv';
  224. });
  225. }
  226. return Promise.resolve();
  227. }
  228. return transceiver.sender.replaceTrack(track);
  229. }
  230. /**
  231. * Obtains the current local video track's height constraints based on the
  232. * initial stream encodings configuration on the sender and the resolution
  233. * of the current local track added to the peerconnection.
  234. * @param {MediaStreamTrack} localTrack local video track
  235. * @returns {Array[number]} an array containing the resolution heights of
  236. * simulcast streams configured on the video sender.
  237. */
  238. getLocalStreamHeightConstraints(localTrack) {
  239. // React-native hasn't implemented MediaStreamTrack getSettings yet.
  240. if (browser.isReactNative()) {
  241. return null;
  242. }
  243. const localVideoHeightConstraints = [];
  244. const height = localTrack.getSettings().height;
  245. for (const encoding of this.localStreamEncodingsConfig) {
  246. localVideoHeightConstraints.push(height / encoding.scaleResolutionDownBy);
  247. }
  248. return localVideoHeightConstraints;
  249. }
  250. /**
  251. * Removes the track from the RTCRtpSender as part of the mute operation.
  252. * @param {JitsiLocalTrack} localTrack - track to be removed.
  253. * @returns {Promise<void>} - resolved when done.
  254. */
  255. removeTrackMute(localTrack) {
  256. const mediaType = localTrack.getType();
  257. const transceiver = this.pc.peerconnection.getTransceivers()
  258. .find(t => t.sender && t.sender.track && t.sender.track.id === localTrack.getTrackId());
  259. if (!transceiver) {
  260. return Promise.reject(new Error(`RTCRtpTransceiver for ${mediaType} not found`));
  261. }
  262. logger.debug(`Removing ${localTrack} on ${this.pc}`);
  263. return transceiver.sender.replaceTrack(null);
  264. }
  265. /**
  266. * Replaces the existing track on a RTCRtpSender with the given track.
  267. * @param {JitsiLocalTrack} oldTrack - existing track on the sender that needs to be removed.
  268. * @param {JitsiLocalTrack} newTrack - new track that needs to be added to the sender.
  269. * @returns {Promise<void>} - resolved when done.
  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. this.addTrackUnmute(newTrack)
  306. .then(() => {
  307. newTrack.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED, newTrack);
  308. this.pc.localTracks.set(newTrack.rtcId, newTrack);
  309. this.pc.localSSRCs.set(newTrack.rtcId, ssrc);
  310. });
  311. }
  312. return Promise.resolve();
  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 {void}
  322. */
  323. setAudioTransferActive(active) {
  324. this.setMediaTransferActive(MediaType.AUDIO, active);
  325. }
  326. /**
  327. * Set the simulcast stream encoding properties on the RTCRtpSender.
  328. * @param {JitsiLocalTrack} track - the current track in use for which
  329. * the encodings are to be set.
  330. * @returns {Promise<void>} - resolved when done.
  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. return 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 {void}
  346. */
  347. setMediaTransferActive(mediaType, active) {
  348. const transceivers = this.pc.peerconnection.getTransceivers()
  349. .filter(t => t.receiver && t.receiver.track && t.receiver.track.kind === mediaType);
  350. const localTracks = this.pc.getLocalTracks(mediaType);
  351. logger.info(`${active ? 'Enabling' : 'Suspending'} ${mediaType} media transfer on ${this.pc}`);
  352. transceivers.forEach((transceiver, idx) => {
  353. if (active) {
  354. // The first transceiver is for the local track and only this one can be set to 'sendrecv'
  355. if (idx === 0 && localTracks.length) {
  356. transceiver.direction = 'sendrecv';
  357. } else {
  358. transceiver.direction = 'recvonly';
  359. }
  360. } else {
  361. transceiver.direction = 'inactive';
  362. }
  363. });
  364. }
  365. /**
  366. * Enables/disables video media transmission on the peer connection. When
  367. * disabled the SDP video media direction in the local SDP will be adjusted to
  368. * 'inactive' which means that no data will be sent nor accepted, but
  369. * the connection should be kept alive.
  370. * @param {boolean} active - true to enable video media transmission or
  371. * false to disable.
  372. * @returns {void}
  373. */
  374. setVideoTransferActive(active) {
  375. this.setMediaTransferActive(MediaType.VIDEO, active);
  376. }
  377. }