Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

TPCUtils.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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<void>}
  175. */
  176. addTrackUnmute(localTrack) {
  177. const mediaType = localTrack.getType();
  178. const track = localTrack.getTrack();
  179. // The assumption here is that the first transceiver of the specified
  180. // media type is that of the local track.
  181. const transceiver = this.pc.peerconnection.getTransceivers()
  182. .find(t => t.receiver && t.receiver.track && t.receiver.track.kind === mediaType);
  183. if (!transceiver) {
  184. logger.error(`RTCRtpTransceiver for ${mediaType} on ${this.pc} not found`);
  185. return false;
  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 true;
  196. }
  197. return transceiver.sender.replaceTrack(track)
  198. .then(() => {
  199. this.pc.localTracks.set(localTrack.rtcId, localTrack);
  200. });
  201. }
  202. /**
  203. * Removes the track from the RTCRtpSender as part of the mute operation.
  204. * @param {JitsiLocalTrack} localTrack - track to be removed.
  205. * @returns {Promise<void>}
  206. */
  207. removeTrackMute(localTrack) {
  208. const mediaType = localTrack.getType();
  209. const transceiver = this.pc.peerconnection.getTransceivers()
  210. .find(t => t.sender && t.sender.track && t.sender.track.id === localTrack.getTrackId());
  211. if (!transceiver) {
  212. logger.error(`RTCRtpTransceiver for ${mediaType} on ${this.pc} not found`);
  213. return false;
  214. }
  215. logger.debug(`Removing ${localTrack} on ${this.pc}`);
  216. return transceiver.sender.replaceTrack(null)
  217. .then(() => {
  218. this.pc.localTracks.delete(localTrack.rtcId);
  219. });
  220. }
  221. /**
  222. * Replaces the existing track on a RTCRtpSender with the given track.
  223. * @param {JitsiLocalTrack} oldTrack - existing track on the sender that needs to be removed.
  224. * @param {JitsiLocalTrack} newTrack - new track that needs to be added to the sender.
  225. * @returns {Promise<false>} Promise that resolves with false as we don't want
  226. * renegotiation to be triggered automatically after this operation. Renegotiation is
  227. * done when the browser fires the negotiationeeded event.
  228. */
  229. replaceTrack(oldTrack, newTrack) {
  230. if (oldTrack && newTrack) {
  231. const mediaType = newTrack.getType();
  232. const stream = newTrack.getOriginalStream();
  233. const track = stream.getVideoTracks()[0];
  234. const transceiver = this.pc.peerconnection.getTransceivers()
  235. .find(t => t.receiver.track.kind === mediaType && !t.stopped);
  236. if (!transceiver) {
  237. return Promise.reject(new Error('replace track failed'));
  238. }
  239. logger.debug(`Replacing ${oldTrack} with ${newTrack} on ${this.pc}`);
  240. return transceiver.sender.replaceTrack(track)
  241. .then(() => {
  242. const ssrc = this.pc.localSSRCs.get(oldTrack.rtcId);
  243. this.pc.localTracks.delete(oldTrack.rtcId);
  244. this.pc.localSSRCs.delete(oldTrack.rtcId);
  245. this.pc._addedStreams = this.pc._addedStreams.filter(s => s !== stream);
  246. this.pc.localTracks.set(newTrack.rtcId, newTrack);
  247. this.pc._addedStreams.push(stream);
  248. this.pc.localSSRCs.set(newTrack.rtcId, ssrc);
  249. this.pc.eventEmitter.emit(RTCEvents.LOCAL_TRACK_SSRC_UPDATED,
  250. newTrack,
  251. this.pc._extractPrimarySSRC(ssrc));
  252. });
  253. } else if (oldTrack && !newTrack) {
  254. if (!this.removeTrackMute(oldTrack)) {
  255. return Promise.reject(new Error('replace track failed'));
  256. }
  257. this.pc.localTracks.delete(oldTrack.rtcId);
  258. this.pc.localSSRCs.delete(oldTrack.rtcId);
  259. } else if (newTrack && !oldTrack) {
  260. const ssrc = this.pc.localSSRCs.get(newTrack.rtcId);
  261. if (!this.addTrackUnmute(newTrack)) {
  262. return Promise.reject(new Error('replace track failed'));
  263. }
  264. newTrack.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED, newTrack);
  265. this.pc.localTracks.set(newTrack.rtcId, newTrack);
  266. this.pc.localSSRCs.set(newTrack.rtcId, ssrc);
  267. }
  268. return Promise.resolve(false);
  269. }
  270. /**
  271. * Enables/disables audio transmission on the peer connection. When
  272. * disabled the audio transceiver direction will be set to 'inactive'
  273. * which means that no data will be sent nor accepted, but
  274. * the connection should be kept alive.
  275. * @param {boolean} active - true to enable audio media transmission or
  276. * false to disable.
  277. * @returns {false} - returns false always so that renegotiation is not automatically
  278. * triggered after this operation.
  279. */
  280. setAudioTransferActive(active) {
  281. return this.setMediaTransferActive('audio', active);
  282. }
  283. /**
  284. * Set the simulcast stream encoding properties on the RTCRtpSender.
  285. * @param {JitsiLocalTrack} track - the current track in use for which
  286. * the encodings are to be set.
  287. */
  288. setEncodings(track) {
  289. const transceiver = this.pc.peerconnection.getTransceivers()
  290. .find(t => t.sender && t.sender.track && t.sender.track.kind === track.getType());
  291. const parameters = transceiver.sender.getParameters();
  292. parameters.encodings = this._getStreamEncodings(track);
  293. transceiver.sender.setParameters(parameters);
  294. }
  295. /**
  296. * Enables/disables media transmission on the peerconnection by changing the direction
  297. * on the transceiver for the specified media type.
  298. * @param {String} mediaType - 'audio' or 'video'
  299. * @param {boolean} active - true to enable media transmission or false
  300. * to disable.
  301. * @returns {false} - returns false always so that renegotiation is not automatically
  302. * triggered after this operation
  303. */
  304. setMediaTransferActive(mediaType, active) {
  305. const transceivers = this.pc.peerconnection.getTransceivers()
  306. .filter(t => t.receiver && t.receiver.track && t.receiver.track.kind === mediaType);
  307. const localTracks = Array.from(this.pc.localTracks.values())
  308. .filter(track => track.getType() === mediaType);
  309. if (active) {
  310. transceivers.forEach(transceiver => {
  311. if (localTracks.length) {
  312. transceiver.direction = 'sendrecv';
  313. const parameters = transceiver.sender.getParameters();
  314. if (parameters && parameters.encodings && parameters.encodings.length) {
  315. parameters.encodings.forEach(encoding => {
  316. encoding.active = true;
  317. });
  318. transceiver.sender.setParameters(parameters);
  319. }
  320. } else {
  321. transceiver.direction = 'recvonly';
  322. }
  323. });
  324. } else {
  325. transceivers.forEach(transceiver => {
  326. transceiver.direction = 'inactive';
  327. });
  328. }
  329. return false;
  330. }
  331. /**
  332. * Enables/disables video media transmission on the peer connection. When
  333. * disabled the SDP video media direction in the local SDP will be adjusted to
  334. * 'inactive' which means that no data will be sent nor accepted, but
  335. * the connection should be kept alive.
  336. * @param {boolean} active - true to enable video media transmission or
  337. * false to disable.
  338. * @returns {false} - returns false always so that renegotiation is not automatically
  339. * triggered after this operation.
  340. */
  341. setVideoTransferActive(active) {
  342. return this.setMediaTransferActive('video', active);
  343. }
  344. }