modified lib-jitsi-meet dev repo
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

TPCUtils.js 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import { getLogger } from 'jitsi-meet-logger';
  2. import transform from 'sdp-transform';
  3. import * as MediaType from '../../service/RTC/MediaType';
  4. import RTCEvents from '../../service/RTC/RTCEvents';
  5. import VideoType from '../../service/RTC/VideoType';
  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
  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. // Firefox doesn't return the height of the desktop track, assume a min. height of 720.
  245. const { height = 720 } = localTrack.getSettings();
  246. for (const encoding of this.localStreamEncodingsConfig) {
  247. localVideoHeightConstraints.push(height / encoding.scaleResolutionDownBy);
  248. }
  249. return localVideoHeightConstraints;
  250. }
  251. /**
  252. * Removes the track from the RTCRtpSender as part of the mute operation.
  253. * @param {JitsiLocalTrack} localTrack - track to be removed.
  254. * @returns {Promise<void>} - resolved when done.
  255. */
  256. removeTrackMute(localTrack) {
  257. const mediaType = localTrack.getType();
  258. const transceiver = this.pc.peerconnection.getTransceivers()
  259. .find(t => t.sender && t.sender.track && t.sender.track.id === localTrack.getTrackId());
  260. if (!transceiver) {
  261. return Promise.reject(new Error(`RTCRtpTransceiver for ${mediaType} not found`));
  262. }
  263. logger.debug(`Removing ${localTrack} on ${this.pc}`);
  264. return transceiver.sender.replaceTrack(null);
  265. }
  266. /**
  267. * Replaces the existing track on a RTCRtpSender with the given track.
  268. * @param {JitsiLocalTrack} oldTrack - existing track on the sender that needs to be removed.
  269. * @param {JitsiLocalTrack} newTrack - new track that needs to be added to the sender.
  270. * @returns {Promise<void>} - resolved when done.
  271. */
  272. replaceTrack(oldTrack, newTrack) {
  273. if (oldTrack && newTrack) {
  274. const mediaType = newTrack.getType();
  275. const stream = newTrack.getOriginalStream();
  276. // Ignore cases when the track is replaced while the device is in a muted state,like
  277. // replacing camera when video muted or replacing mic when audio muted. These JitsiLocalTracks
  278. // do not have a mediastream attached. Replace track will be called again when the device is
  279. // unmuted and the track will be replaced on the peerconnection then.
  280. if (!stream) {
  281. this.pc.localTracks.delete(oldTrack.rtcId);
  282. this.pc.localTracks.set(newTrack.rtcId, newTrack);
  283. return Promise.resolve();
  284. }
  285. const track = mediaType === MediaType.AUDIO
  286. ? stream.getAudioTracks()[0]
  287. : stream.getVideoTracks()[0];
  288. const transceiver = this.pc.peerconnection.getTransceivers()
  289. .find(t => t.receiver.track.kind === mediaType && !t.stopped);
  290. if (!transceiver) {
  291. return Promise.reject(new Error('replace track failed'));
  292. }
  293. logger.debug(`Replacing ${oldTrack} with ${newTrack} on ${this.pc}`);
  294. return transceiver.sender.replaceTrack(track)
  295. .then(() => {
  296. const ssrc = this.pc.localSSRCs.get(oldTrack.rtcId);
  297. this.pc.localTracks.delete(oldTrack.rtcId);
  298. this.pc.localSSRCs.delete(oldTrack.rtcId);
  299. this.pc._addedStreams = this.pc._addedStreams.filter(s => s !== stream);
  300. this.pc.localTracks.set(newTrack.rtcId, newTrack);
  301. this.pc._addedStreams.push(stream);
  302. this.pc.localSSRCs.set(newTrack.rtcId, ssrc);
  303. this.pc.eventEmitter.emit(RTCEvents.LOCAL_TRACK_SSRC_UPDATED,
  304. newTrack,
  305. this.pc._extractPrimarySSRC(ssrc));
  306. });
  307. } else if (oldTrack && !newTrack) {
  308. return this.removeTrackMute(oldTrack)
  309. .then(() => {
  310. this.pc.localTracks.delete(oldTrack.rtcId);
  311. this.pc.localSSRCs.delete(oldTrack.rtcId);
  312. });
  313. } else if (newTrack && !oldTrack) {
  314. const ssrc = this.pc.localSSRCs.get(newTrack.rtcId);
  315. return this.addTrackUnmute(newTrack)
  316. .then(() => {
  317. this.pc.localTracks.set(newTrack.rtcId, newTrack);
  318. this.pc.localSSRCs.set(newTrack.rtcId, ssrc);
  319. });
  320. }
  321. }
  322. /**
  323. * Enables/disables audio transmission on the peer connection. When
  324. * disabled the audio transceiver direction will be set to 'inactive'
  325. * which means that no data will be sent nor accepted, but
  326. * the connection should be kept alive.
  327. * @param {boolean} active - true to enable audio media transmission or
  328. * false to disable.
  329. * @returns {void}
  330. */
  331. setAudioTransferActive(active) {
  332. this.setMediaTransferActive(MediaType.AUDIO, active);
  333. }
  334. /**
  335. * Set the simulcast stream encoding properties on the RTCRtpSender.
  336. * @param {JitsiLocalTrack} track - the current track in use for which
  337. * the encodings are to be set.
  338. * @returns {Promise<void>} - resolved when done.
  339. */
  340. setEncodings(track) {
  341. const transceiver = this.pc.peerconnection.getTransceivers()
  342. .find(t => t.sender && t.sender.track && t.sender.track.kind === track.getType());
  343. const parameters = transceiver.sender.getParameters();
  344. parameters.encodings = this._getStreamEncodings(track);
  345. return transceiver.sender.setParameters(parameters);
  346. }
  347. /**
  348. * Enables/disables media transmission on the peerconnection by changing the direction
  349. * on the transceiver for the specified media type.
  350. * @param {String} mediaType - 'audio' or 'video'
  351. * @param {boolean} active - true to enable media transmission or false
  352. * to disable.
  353. * @returns {void}
  354. */
  355. setMediaTransferActive(mediaType, active) {
  356. const transceivers = this.pc.peerconnection.getTransceivers()
  357. .filter(t => t.receiver && t.receiver.track && t.receiver.track.kind === mediaType);
  358. const localTracks = this.pc.getLocalTracks(mediaType);
  359. logger.info(`${active ? 'Enabling' : 'Suspending'} ${mediaType} media transfer on ${this.pc}`);
  360. transceivers.forEach((transceiver, idx) => {
  361. if (active) {
  362. // The first transceiver is for the local track and only this one can be set to 'sendrecv'
  363. if (idx === 0 && localTracks.length) {
  364. transceiver.direction = 'sendrecv';
  365. } else {
  366. transceiver.direction = 'recvonly';
  367. }
  368. } else {
  369. transceiver.direction = 'inactive';
  370. }
  371. });
  372. }
  373. /**
  374. * Enables/disables video media transmission on the peer connection. When
  375. * disabled the SDP video media direction in the local SDP will be adjusted to
  376. * 'inactive' which means that no data will be sent nor accepted, but
  377. * the connection should be kept alive.
  378. * @param {boolean} active - true to enable video media transmission or
  379. * false to disable.
  380. * @returns {void}
  381. */
  382. setVideoTransferActive(active) {
  383. this.setMediaTransferActive(MediaType.VIDEO, active);
  384. }
  385. /**
  386. * Ensures that the resolution of the stream encodings are consistent with the values
  387. * that were configured on the RTCRtpSender when the source was added to the peerconnection.
  388. * This should prevent us from overriding the default values if the browser returns
  389. * erroneous values when RTCRtpSender.getParameters is used for getting the encodings info.
  390. * @param {Object} parameters - the RTCRtpEncodingParameters obtained from the browser.
  391. * @returns {void}
  392. */
  393. updateEncodingsResolution(parameters) {
  394. if (!(parameters
  395. && parameters.encodings
  396. && Array.isArray(parameters.encodings)
  397. && this.pc.isSimulcastOn())) {
  398. return;
  399. }
  400. const localVideoTrack = this.pc.getLocalVideoTrack();
  401. // Ignore desktop tracks when simulcast is disabled for screenshare.
  402. if (localVideoTrack
  403. && localVideoTrack.videoType === VideoType.DESKTOP
  404. && this.pc.options.capScreenshareBitrate) {
  405. return;
  406. }
  407. parameters.encodings.forEach((encoding, idx) => {
  408. encoding.scaleResolutionDownBy = this.localStreamEncodingsConfig[idx].scaleResolutionDownBy;
  409. });
  410. }
  411. }