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

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