您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

TPCUtils.js 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. import { getLogger } from '@jitsi/logger';
  2. import clonedeep from 'lodash.clonedeep';
  3. import transform from 'sdp-transform';
  4. import { CodecMimeType } from '../../service/RTC/CodecMimeType';
  5. import { MediaDirection } from '../../service/RTC/MediaDirection';
  6. import { MediaType } from '../../service/RTC/MediaType';
  7. import { getSourceIndexFromSourceName } from '../../service/RTC/SignalingLayer';
  8. import {
  9. SIM_LAYERS,
  10. STANDARD_CODEC_SETTINGS,
  11. VIDEO_QUALITY_LEVELS,
  12. VIDEO_QUALITY_SETTINGS
  13. } from '../../service/RTC/StandardVideoSettings';
  14. import { VideoEncoderScalabilityMode } from '../../service/RTC/VideoEncoderScalabilityMode';
  15. import { VideoType } from '../../service/RTC/VideoType';
  16. import browser from '../browser';
  17. const logger = getLogger(__filename);
  18. const VIDEO_CODECS = [ CodecMimeType.AV1, CodecMimeType.H264, CodecMimeType.VP8, CodecMimeType.VP9 ];
  19. /**
  20. * Handles track related operations on TraceablePeerConnection when browser is
  21. * running in unified plan mode.
  22. */
  23. export class TPCUtils {
  24. /**
  25. * Creates a new instance for a given TraceablePeerConnection
  26. *
  27. * @param peerconnection - the tpc instance for which we have utility functions.
  28. */
  29. constructor(peerconnection) {
  30. this.pc = peerconnection;
  31. this.codecSettings = clonedeep(STANDARD_CODEC_SETTINGS);
  32. const videoQualitySettings = this.pc.options?.videoQuality;
  33. if (videoQualitySettings) {
  34. for (const codec of VIDEO_CODECS) {
  35. const codecConfig = videoQualitySettings[codec];
  36. const bitrateSettings = codecConfig?.maxBitratesVideo
  37. // Read the deprecated settings for max bitrates.
  38. ?? (videoQualitySettings.maxbitratesvideo
  39. && videoQualitySettings.maxbitratesvideo[codec.toUpperCase()]);
  40. if (bitrateSettings) {
  41. const settings = Object.values(VIDEO_QUALITY_SETTINGS);
  42. [ ...settings, 'ssHigh' ].forEach(value => {
  43. if (bitrateSettings[value]) {
  44. this.codecSettings[codec].maxBitratesVideo[value] = bitrateSettings[value];
  45. }
  46. });
  47. }
  48. if (!codecConfig) {
  49. continue; // eslint-disable-line no-continue
  50. }
  51. const scalabilityModeEnabled = this.codecSettings[codec].scalabilityModeEnabled
  52. && (typeof codecConfig.scalabilityModeEnabled === 'undefined'
  53. || codecConfig.scalabilityModeEnabled);
  54. if (scalabilityModeEnabled) {
  55. typeof codecConfig.useSimulcast !== 'undefined'
  56. && (this.codecSettings[codec].useSimulcast = codecConfig.useSimulcast);
  57. typeof codecConfig.useKSVC !== 'undefined'
  58. && (this.codecSettings[codec].useKSVC = codecConfig.useKSVC);
  59. } else {
  60. this.codecSettings[codec].scalabilityModeEnabled = false;
  61. }
  62. }
  63. }
  64. }
  65. /**
  66. * Calculates the configuration of the active encoding when the browser sends only one stream, i,e,, when there is
  67. * no spatial scalability configure (p2p) or when it is running in full SVC mode.
  68. *
  69. * @param {JitsiLocalTrack} localVideoTrack - The local video track.
  70. * @param {CodecMimeType} codec - The video codec.
  71. * @param {number} newHeight - The resolution that needs to be configured for the local video track.
  72. * @returns {Object} configuration.
  73. */
  74. _calculateActiveEncodingParams(localVideoTrack, codec, newHeight) {
  75. const codecBitrates = this.codecSettings[codec].maxBitratesVideo;
  76. const trackCaptureHeight = localVideoTrack.getCaptureResolution();
  77. const effectiveNewHeight = newHeight > trackCaptureHeight ? trackCaptureHeight : newHeight;
  78. const desktopShareBitrate = this.pc.options?.videoQuality?.desktopbitrate || codecBitrates.ssHigh;
  79. const isScreenshare = localVideoTrack.getVideoType() === VideoType.DESKTOP;
  80. let scalabilityMode = this.codecSettings[codec].useKSVC
  81. ? VideoEncoderScalabilityMode.L3T3_KEY : VideoEncoderScalabilityMode.L3T3;
  82. const { height, level } = VIDEO_QUALITY_LEVELS.find(lvl => lvl.height <= effectiveNewHeight);
  83. let maxBitrate;
  84. let scaleResolutionDownBy = SIM_LAYERS[2].scaleFactor;
  85. if (this._isScreenshareBitrateCapped(localVideoTrack)) {
  86. scalabilityMode = VideoEncoderScalabilityMode.L1T3;
  87. maxBitrate = desktopShareBitrate;
  88. } else if (isScreenshare) {
  89. maxBitrate = codecBitrates.ssHigh;
  90. } else {
  91. maxBitrate = codecBitrates[level];
  92. effectiveNewHeight && (scaleResolutionDownBy = trackCaptureHeight / effectiveNewHeight);
  93. if (height !== effectiveNewHeight) {
  94. logger.debug(`Quality level with height=${height} was picked when requested height=${newHeight} for`
  95. + `track with capture height=${trackCaptureHeight}`);
  96. }
  97. }
  98. const config = {
  99. active: effectiveNewHeight > 0,
  100. maxBitrate,
  101. scalabilityMode,
  102. scaleResolutionDownBy
  103. };
  104. if (!config.active || isScreenshare) {
  105. return config;
  106. }
  107. // Configure the sender to send all 3 spatial layers for resolutions 720p and higher.
  108. switch (level) {
  109. case VIDEO_QUALITY_SETTINGS.ULTRA:
  110. case VIDEO_QUALITY_SETTINGS.FULL:
  111. case VIDEO_QUALITY_SETTINGS.HIGH:
  112. config.scalabilityMode = this.codecSettings[codec].useKSVC
  113. ? VideoEncoderScalabilityMode.L3T3_KEY : VideoEncoderScalabilityMode.L3T3;
  114. break;
  115. case VIDEO_QUALITY_SETTINGS.STANDARD:
  116. config.scalabilityMode = this.codecSettings[codec].useKSVC
  117. ? VideoEncoderScalabilityMode.L2T3_KEY : VideoEncoderScalabilityMode.L2T3;
  118. break;
  119. default:
  120. config.scalabilityMode = VideoEncoderScalabilityMode.L1T3;
  121. }
  122. return config;
  123. }
  124. /**
  125. * Configures the RTCRtpEncodingParameters of the outbound rtp stream associated with the given track.
  126. *
  127. * @param {JitsiLocalTracj} localTrack - The local track whose outbound stream needs to be configured.
  128. * @returns {Promise} - A promise that resolves when the operation is successful, rejected otherwise.
  129. */
  130. _configureSenderEncodings(localTrack) {
  131. const mediaType = localTrack.getType();
  132. const transceiver = localTrack?.track && localTrack.getOriginalStream()
  133. ? this.pc.peerconnection.getTransceivers().find(t => t.sender?.track?.id === localTrack.getTrackId())
  134. : this.pc.peerconnection.getTransceivers().find(t => t.receiver?.track?.kind === mediaType);
  135. const parameters = transceiver?.sender?.getParameters();
  136. // Resolve if the encodings are not available yet. This happens immediately after the track is added to the
  137. // peerconnection on chrome in unified-plan. It is ok to ignore and not report the error here since the
  138. // action that triggers 'addTrack' (like unmute) will also configure the encodings and set bitrates after that.
  139. if (!parameters?.encodings?.length) {
  140. return Promise.resolve();
  141. }
  142. parameters.encodings = this._getStreamEncodings(localTrack);
  143. return transceiver.sender.setParameters(parameters);
  144. }
  145. /**
  146. * Enables/disables the streams by changing the active field on RTCRtpEncodingParameters for a given RTCRtpSender.
  147. *
  148. * @param {RTCRtpSender} sender - the sender associated with a MediaStreamTrack.
  149. * @param {boolean} enable - whether the streams needs to be enabled or disabled.
  150. * @returns {Promise} - A promise that resolves when the operation is successful, rejected otherwise.
  151. */
  152. _enableSenderEncodings(sender, enable) {
  153. const parameters = sender.getParameters();
  154. if (parameters?.encodings?.length) {
  155. for (const encoding of parameters.encodings) {
  156. encoding.active = enable;
  157. }
  158. }
  159. return sender.setParameters(parameters);
  160. }
  161. /**
  162. * Obtains stream encodings that need to be configured on the given track based
  163. * on the track media type and the simulcast setting.
  164. * @param {JitsiLocalTrack} localTrack
  165. */
  166. _getStreamEncodings(localTrack) {
  167. if (localTrack.isAudioTrack()) {
  168. return [ { active: this.pc.audioTransferActive } ];
  169. }
  170. const codec = this.pc.getConfiguredVideoCodec();
  171. if (this.pc.isSpatialScalabilityOn()) {
  172. return this._getVideoStreamEncodings(localTrack, codec);
  173. }
  174. return [ {
  175. active: this.pc.videoTransferActive,
  176. maxBitrate: this.codecSettings[codec].maxBitratesVideo.high
  177. } ];
  178. }
  179. /**
  180. * The startup configuration for the stream encodings that are applicable to
  181. * the video stream when a new sender is created on the peerconnection. The initial
  182. * config takes into account the differences in browser's simulcast implementation.
  183. *
  184. * Encoding parameters:
  185. * active - determine the on/off state of a particular encoding.
  186. * maxBitrate - max. bitrate value to be applied to that particular encoding
  187. * based on the encoding's resolution and config.js videoQuality settings if applicable.
  188. * rid - Rtp Stream ID that is configured for a particular simulcast stream.
  189. * scaleResolutionDownBy - the factor by which the encoding is scaled down from the
  190. * original resolution of the captured video.
  191. *
  192. * @param {JitsiLocalTrack} localTrack
  193. * @param {String} codec
  194. */
  195. _getVideoStreamEncodings(localTrack, codec) {
  196. const captureResolution = localTrack.getCaptureResolution();
  197. const codecBitrates = this.codecSettings[codec].maxBitratesVideo;
  198. const videoType = localTrack.getVideoType();
  199. let effectiveScaleFactors = SIM_LAYERS.map(sim => sim.scaleFactor);
  200. let cameraMaxbitrate;
  201. if (videoType === VideoType.CAMERA) {
  202. const { level } = VIDEO_QUALITY_LEVELS.find(lvl => lvl.height <= captureResolution);
  203. cameraMaxbitrate = codecBitrates[level];
  204. if (level === VIDEO_QUALITY_SETTINGS.ULTRA) {
  205. effectiveScaleFactors[1] = 6.0; // 360p
  206. effectiveScaleFactors[0] = 12.0; // 180p
  207. } else if (level === VIDEO_QUALITY_SETTINGS.FULL) {
  208. effectiveScaleFactors[1] = 3.0; // 360p
  209. effectiveScaleFactors[0] = 6.0; // 180p
  210. }
  211. }
  212. const maxBitrate = videoType === VideoType.DESKTOP
  213. ? codecBitrates.ssHigh : cameraMaxbitrate;
  214. let effectiveBitrates = [ codecBitrates.low, codecBitrates.standard, maxBitrate ];
  215. // The SSRCs on older versions of Firefox are reversed in SDP, i.e., they have resolution order of 1:2:4 as
  216. // opposed to Chromium and other browsers. This has been reverted in Firefox 117 as part of the below commit.
  217. // https://hg.mozilla.org/mozilla-central/rev/b0348f1f8d7197fb87158ba74542d28d46133997
  218. // This revert seems to be applied only to camera tracks, the desktop stream encodings still have the
  219. // resolution order of 4:2:1.
  220. if (browser.isFirefox() && (videoType === VideoType.DESKTOP || browser.isVersionLessThan(117))) {
  221. effectiveBitrates = effectiveBitrates.reverse();
  222. effectiveScaleFactors = effectiveScaleFactors.reverse();
  223. }
  224. const standardSimulcastEncodings = [
  225. {
  226. active: this.pc.videoTransferActive,
  227. maxBitrate: effectiveBitrates[0],
  228. rid: SIM_LAYERS[0].rid,
  229. scaleResolutionDownBy: effectiveScaleFactors[0]
  230. },
  231. {
  232. active: this.pc.videoTransferActive,
  233. maxBitrate: effectiveBitrates[1],
  234. rid: SIM_LAYERS[1].rid,
  235. scaleResolutionDownBy: effectiveScaleFactors[1]
  236. },
  237. {
  238. active: this.pc.videoTransferActive,
  239. maxBitrate: effectiveBitrates[2],
  240. rid: SIM_LAYERS[2].rid,
  241. scaleResolutionDownBy: effectiveScaleFactors[2]
  242. }
  243. ];
  244. if (this.codecSettings[codec].scalabilityModeEnabled) {
  245. // Configure all 3 encodings when simulcast is requested through config.js for AV1 and VP9 and for H.264
  246. // always since that is the only supported mode when DD header extension is negotiated for H.264.
  247. if (this.codecSettings[codec].useSimulcast || codec === CodecMimeType.H264) {
  248. for (const encoding of standardSimulcastEncodings) {
  249. encoding.scalabilityMode = VideoEncoderScalabilityMode.L1T3;
  250. }
  251. return standardSimulcastEncodings;
  252. }
  253. // Configure only one encoding for the SVC mode.
  254. return [
  255. {
  256. active: this.pc.videoTransferActive,
  257. maxBitrate: effectiveBitrates[2],
  258. rid: SIM_LAYERS[0].rid,
  259. scaleResolutionDownBy: effectiveScaleFactors[2],
  260. scalabilityMode: this.codecSettings[codec].useKSVC
  261. ? VideoEncoderScalabilityMode.L3T3_KEY : VideoEncoderScalabilityMode.L3T3
  262. },
  263. {
  264. active: false,
  265. maxBitrate: 0
  266. },
  267. {
  268. active: false,
  269. maxBitrate: 0
  270. }
  271. ];
  272. }
  273. return standardSimulcastEncodings;
  274. }
  275. /**
  276. * Returns a boolean indicating whether the video encoder is running in full SVC mode, i.e., it sends only one
  277. * video stream that has both temporal and spatial scalability.
  278. *
  279. * @param {CodecMimeType} codec
  280. * @returns boolean
  281. */
  282. _isRunningInFullSvcMode(codec) {
  283. return (codec === CodecMimeType.VP9 || codec === CodecMimeType.AV1)
  284. && this.codecSettings[codec].scalabilityModeEnabled
  285. && !this.codecSettings[codec].useSimulcast;
  286. }
  287. /**
  288. * Returns a boolean indicating whether the bitrate needs to be capped for the local video track if it happens to
  289. * be a screenshare track. The lower spatial layers for screensharing are disabled when low fps screensharing is in
  290. * progress. Sending all three streams often results in the browser suspending the high resolution in low b/w and
  291. * and low cpu conditions, especially on the low end machines. Suspending the low resolution streams ensures that
  292. * the highest resolution stream is available always. Safari is an exception here since it does not send the
  293. * desktop stream at all if only the high resolution stream is enabled.
  294. *
  295. * @param {JitsiLocalTrack} localVideoTrack - The local video track.
  296. * @returns {boolean}
  297. */
  298. _isScreenshareBitrateCapped(localVideoTrack) {
  299. return localVideoTrack.getVideoType() === VideoType.DESKTOP
  300. && this.pc._capScreenshareBitrate
  301. && !browser.isWebKitBased();
  302. }
  303. /**
  304. * Updates the sender parameters in the stream encodings.
  305. *
  306. * @param {RTCRtpSender} sender - the sender associated with a MediaStreamTrack.
  307. * @param {boolean} enable - whether the streams needs to be enabled or disabled.
  308. * @returns {Promise} - A promise that resolves when the operation is successful, rejected otherwise.
  309. */
  310. _updateSenderEncodings(sender, enable) {
  311. const parameters = sender.getParameters();
  312. if (parameters?.encodings?.length) {
  313. for (const encoding of parameters.encodings) {
  314. encoding.active = enable;
  315. }
  316. }
  317. return sender.setParameters(parameters);
  318. }
  319. /**
  320. * Adds {@link JitsiLocalTrack} to the WebRTC peerconnection for the first time.
  321. * @param {JitsiLocalTrack} track - track to be added to the peerconnection.
  322. * @param {boolean} isInitiator - boolean that indicates if the endpoint is offerer in a p2p connection.
  323. * @returns {void}
  324. */
  325. addTrack(localTrack, isInitiator) {
  326. const track = localTrack.getTrack();
  327. if (isInitiator) {
  328. const streams = [];
  329. if (localTrack.getOriginalStream()) {
  330. streams.push(localTrack.getOriginalStream());
  331. }
  332. // Use pc.addTransceiver() for the initiator case when local tracks are getting added
  333. // to the peerconnection before a session-initiate is sent over to the peer.
  334. const transceiverInit = {
  335. direction: MediaDirection.SENDRECV,
  336. streams,
  337. sendEncodings: []
  338. };
  339. if (!browser.isFirefox()) {
  340. transceiverInit.sendEncodings = this._getStreamEncodings(localTrack);
  341. }
  342. this.pc.peerconnection.addTransceiver(track, transceiverInit);
  343. } else {
  344. // Use pc.addTrack() for responder case so that we can re-use the m-lines that were created
  345. // when setRemoteDescription was called. pc.addTrack() automatically attaches to any existing
  346. // unused "recv-only" transceiver.
  347. this.pc.peerconnection.addTrack(track);
  348. }
  349. }
  350. /**
  351. * Returns the calculated active state of the stream encodings based on the frame height requested for the send
  352. * stream. All the encodings that have a resolution lower than the frame height requested will be enabled.
  353. *
  354. * @param {JitsiLocalTrack} localVideoTrack The local video track.
  355. * @param {CodecMimeType} codec - The codec currently in use.
  356. * @param {number} newHeight The resolution requested for the video track.
  357. * @returns {Array<boolean>}
  358. */
  359. calculateEncodingsActiveState(localVideoTrack, codec, newHeight) {
  360. const height = localVideoTrack.getCaptureResolution();
  361. const videoStreamEncodings = this._getVideoStreamEncodings(localVideoTrack, codec);
  362. const encodingsState = videoStreamEncodings
  363. .map(encoding => height / encoding.scaleResolutionDownBy)
  364. .map((frameHeight, idx) => {
  365. let activeState = false;
  366. // When video is suspended on the media session.
  367. if (!this.pc.videoTransferActive) {
  368. return activeState;
  369. }
  370. // Single video stream.
  371. if (!this.pc.isSpatialScalabilityOn() || this._isRunningInFullSvcMode(codec)) {
  372. const { active } = this._calculateActiveEncodingParams(localVideoTrack, codec, newHeight);
  373. return idx === 0 ? active : activeState;
  374. }
  375. if (newHeight > 0) {
  376. if (localVideoTrack.getVideoType() === VideoType.CAMERA) {
  377. activeState = frameHeight <= newHeight
  378. // Keep the LD stream enabled even when the LD stream's resolution is higher than of the
  379. // requested resolution. This can happen when camera is captured at high resolutions like 4k
  380. // but the requested resolution is 180. Since getParameters doesn't give us information about
  381. // the resolutions of the simulcast encodings, we have to rely on our initial config for the
  382. // simulcast streams.
  383. || videoStreamEncodings[idx]?.scaleResolutionDownBy === SIM_LAYERS[0].scaleFactor;
  384. } else {
  385. // For screenshare, keep the HD layer enabled always and the lower layers only for high fps
  386. // screensharing.
  387. activeState = videoStreamEncodings[idx].scaleResolutionDownBy === SIM_LAYERS[2].scaleFactor
  388. || !this._isScreenshareBitrateCapped(localVideoTrack);
  389. }
  390. }
  391. return activeState;
  392. });
  393. return encodingsState;
  394. }
  395. /**
  396. * Returns the calculated max bitrates that need to be configured on the stream encodings based on the video
  397. * type and other considerations associated with screenshare.
  398. *
  399. * @param {JitsiLocalTrack} localVideoTrack The local video track.
  400. * @param {CodecMimeType} codec - The codec currently in use.
  401. * @param {number} newHeight The resolution requested for the video track.
  402. * @returns {Array<number>}
  403. */
  404. calculateEncodingsBitrates(localVideoTrack, codec, newHeight) {
  405. const codecBitrates = this.codecSettings[codec].maxBitratesVideo;
  406. const desktopShareBitrate = this.pc.options?.videoQuality?.desktopbitrate || codecBitrates.ssHigh;
  407. const encodingsBitrates = this._getVideoStreamEncodings(localVideoTrack, codec)
  408. .map((encoding, idx) => {
  409. let bitrate = encoding.maxBitrate;
  410. // Single video stream.
  411. if (!this.pc.isSpatialScalabilityOn() || this._isRunningInFullSvcMode(codec)) {
  412. const { maxBitrate } = this._calculateActiveEncodingParams(localVideoTrack, codec, newHeight);
  413. return idx === 0 ? maxBitrate : 0;
  414. }
  415. // Multiple video streams.
  416. if (this._isScreenshareBitrateCapped(localVideoTrack)) {
  417. bitrate = desktopShareBitrate;
  418. }
  419. return bitrate;
  420. });
  421. return encodingsBitrates;
  422. }
  423. /**
  424. * Returns the calculated scalability modes for the video encodings when scalability modes are supported.
  425. *
  426. * @param {JitsiLocalTrack} localVideoTrack The local video track.
  427. * @param {CodecMimeType} codec - The codec currently in use.
  428. * @param {number} maxHeight The resolution requested for the video track.
  429. * @returns {Array<VideoEncoderScalabilityMode> | undefined}
  430. */
  431. calculateEncodingsScalabilityMode(localVideoTrack, codec, maxHeight) {
  432. if (!this.pc.isSpatialScalabilityOn() || !this.codecSettings[codec].scalabilityModeEnabled) {
  433. return;
  434. }
  435. // Default modes for simulcast.
  436. const scalabilityModes = [
  437. VideoEncoderScalabilityMode.L1T3,
  438. VideoEncoderScalabilityMode.L1T3,
  439. VideoEncoderScalabilityMode.L1T3
  440. ];
  441. // Full SVC mode.
  442. if (this._isRunningInFullSvcMode(codec)) {
  443. const { scalabilityMode }
  444. = this._calculateActiveEncodingParams(localVideoTrack, codec, maxHeight);
  445. scalabilityModes[0] = scalabilityMode;
  446. scalabilityModes[1] = undefined;
  447. scalabilityModes[2] = undefined;
  448. return scalabilityModes;
  449. }
  450. return scalabilityModes;
  451. }
  452. /**
  453. * Returns the scale factor that needs to be applied on the local video stream based on the desired resolution
  454. * and the codec in use.
  455. *
  456. * @param {JitsiLocalTrack} localVideoTrack The local video track.
  457. * @param {CodecMimeType} codec - The codec currently in use.
  458. * @param {number} maxHeight The resolution requested for the video track.
  459. * @returns {Array<float>}
  460. */
  461. calculateEncodingsScaleFactor(localVideoTrack, codec, maxHeight) {
  462. if (this.pc.isSpatialScalabilityOn() && this.isRunningInSimulcastMode(codec)) {
  463. return this._getVideoStreamEncodings(localVideoTrack, codec)
  464. .map(encoding => encoding.scaleResolutionDownBy);
  465. }
  466. // Single video stream.
  467. const { scaleResolutionDownBy }
  468. = this._calculateActiveEncodingParams(localVideoTrack, codec, maxHeight);
  469. return [ scaleResolutionDownBy, undefined, undefined ];
  470. }
  471. /**
  472. * Ensures that the ssrcs associated with a FID ssrc-group appear in the correct order, i.e.,
  473. * the primary ssrc first and the secondary rtx ssrc later. This is important for unified
  474. * plan since we have only one FID group per media description.
  475. * @param {Object} description the webRTC session description instance for the remote
  476. * description.
  477. * @private
  478. */
  479. ensureCorrectOrderOfSsrcs(description) {
  480. const parsedSdp = transform.parse(description.sdp);
  481. parsedSdp.media.forEach(mLine => {
  482. if (mLine.type === MediaType.AUDIO) {
  483. return;
  484. }
  485. if (!mLine.ssrcGroups || !mLine.ssrcGroups.length) {
  486. return;
  487. }
  488. let reorderedSsrcs = [];
  489. const ssrcs = new Set();
  490. mLine.ssrcGroups.map(group =>
  491. group.ssrcs
  492. .split(' ')
  493. .filter(Boolean)
  494. .forEach(ssrc => ssrcs.add(ssrc))
  495. );
  496. ssrcs.forEach(ssrc => {
  497. const sources = mLine.ssrcs.filter(source => source.id.toString() === ssrc);
  498. reorderedSsrcs = reorderedSsrcs.concat(sources);
  499. });
  500. mLine.ssrcs = reorderedSsrcs;
  501. });
  502. return new RTCSessionDescription({
  503. type: description.type,
  504. sdp: transform.write(parsedSdp)
  505. });
  506. }
  507. /**
  508. * Takes in a *unified plan* offer and inserts the appropriate parameters for adding simulcast receive support.
  509. * @param {Object} desc - A session description object
  510. * @param {String} desc.type - the type (offer/answer)
  511. * @param {String} desc.sdp - the sdp content
  512. *
  513. * @return {Object} A session description (same format as above) object with its sdp field modified to advertise
  514. * simulcast receive support.
  515. */
  516. insertUnifiedPlanSimulcastReceive(desc) {
  517. // a=simulcast line is not needed on browsers where we SDP munging is used for enabling on simulcast.
  518. // Remove this check when the client switches to RID/MID based simulcast on all browsers.
  519. if (browser.usesSdpMungingForSimulcast()) {
  520. return desc;
  521. }
  522. const rids = [
  523. {
  524. id: SIM_LAYERS[0].rid,
  525. direction: 'recv'
  526. },
  527. {
  528. id: SIM_LAYERS[1].rid,
  529. direction: 'recv'
  530. },
  531. {
  532. id: SIM_LAYERS[2].rid,
  533. direction: 'recv'
  534. }
  535. ];
  536. const ridLine = rids.map(val => val.id).join(';');
  537. const simulcastLine = `recv ${ridLine}`;
  538. const sdp = transform.parse(desc.sdp);
  539. const mLines = sdp.media.filter(m => m.type === MediaType.VIDEO);
  540. const senderMids = Array.from(this.pc._localTrackTransceiverMids.values());
  541. mLines.forEach((mLine, idx) => {
  542. // Make sure the simulcast recv line is only set on video descriptions that are associated with senders.
  543. if (senderMids.find(sender => mLine.mid.toString() === sender.toString()) || idx === 0) {
  544. if (!mLine.simulcast_03 || !mLine.simulcast) {
  545. mLine.rids = rids;
  546. // eslint-disable-next-line camelcase
  547. mLine.simulcast_03 = {
  548. value: simulcastLine
  549. };
  550. }
  551. } else {
  552. mLine.rids = undefined;
  553. mLine.simulcast = undefined;
  554. // eslint-disable-next-line camelcase
  555. mLine.simulcast_03 = undefined;
  556. }
  557. });
  558. return new RTCSessionDescription({
  559. type: desc.type,
  560. sdp: transform.write(sdp)
  561. });
  562. }
  563. /**
  564. * Returns a boolean indicating whether the video encoder is running in Simulcast mode, i.e., three encodings need
  565. * to be configured in 4:2:1 resolution order with temporal scalability.
  566. *
  567. * @param {CodecMimeType} codec - The video codec in use.
  568. * @returns {boolean}
  569. */
  570. isRunningInSimulcastMode(codec) {
  571. return codec === CodecMimeType.VP8 // VP8 always
  572. // K-SVC mode for VP9 when no scalability mode is set. Though only one outbound-rtp stream is present,
  573. // three separate encodings have to be configured.
  574. || (!this.codecSettings[codec].scalabilityModeEnabled && codec === CodecMimeType.VP9)
  575. // When scalability is enabled, always for H.264, and only when simulcast is explicitly enabled via
  576. // config.js for VP9 and AV1 since full SVC is the default mode for these 2 codecs.
  577. || (this.codecSettings[codec].scalabilityModeEnabled
  578. && (codec === CodecMimeType.H264 || this.codecSettings[codec].useSimulcast));
  579. }
  580. /**
  581. * Replaces the existing track on a RTCRtpSender with the given track.
  582. *
  583. * @param {JitsiLocalTrack} oldTrack - existing track on the sender that needs to be removed.
  584. * @param {JitsiLocalTrack} newTrack - new track that needs to be added to the sender.
  585. * @returns {Promise<RTCRtpTransceiver>} - resolved with the associated transceiver when done, rejected otherwise.
  586. */
  587. replaceTrack(oldTrack, newTrack) {
  588. const mediaType = newTrack?.getType() ?? oldTrack?.getType();
  589. const localTracks = this.pc.getLocalTracks(mediaType);
  590. const track = newTrack?.getTrack() ?? null;
  591. const isNewLocalSource = localTracks?.length
  592. && !oldTrack
  593. && newTrack
  594. && !localTracks.find(t => t === newTrack);
  595. let transceiver;
  596. // If old track exists, replace the track on the corresponding sender.
  597. if (oldTrack && !oldTrack.isMuted()) {
  598. transceiver = this.pc.peerconnection.getTransceivers().find(t => t.sender.track === oldTrack.getTrack());
  599. // Find the first recvonly transceiver when more than one track of the same media type is being added to the pc.
  600. // As part of the track addition, a new m-line was added to the remote description with direction set to
  601. // recvonly.
  602. } else if (isNewLocalSource) {
  603. transceiver = this.pc.peerconnection.getTransceivers().find(
  604. t => t.receiver.track.kind === mediaType
  605. && t.direction === MediaDirection.RECVONLY
  606. // Re-use any existing recvonly transceiver (if available) for p2p case.
  607. && ((this.pc.isP2P && t.currentDirection === MediaDirection.RECVONLY)
  608. || (t.currentDirection === MediaDirection.INACTIVE && !t.stopped)));
  609. // For mute/unmute operations, find the transceiver based on the track index in the source name if present,
  610. // otherwise it is assumed to be the first local track that was added to the peerconnection.
  611. } else {
  612. transceiver = this.pc.peerconnection.getTransceivers().find(t => t.receiver.track.kind === mediaType);
  613. const sourceName = newTrack?.getSourceName() ?? oldTrack?.getSourceName();
  614. if (sourceName) {
  615. const trackIndex = getSourceIndexFromSourceName(sourceName);
  616. if (this.pc.isP2P) {
  617. transceiver = this.pc.peerconnection.getTransceivers()
  618. .filter(t => t.receiver.track.kind === mediaType)[trackIndex];
  619. } else if (oldTrack) {
  620. const transceiverMid = this.pc._localTrackTransceiverMids.get(oldTrack.rtcId);
  621. transceiver = this.pc.peerconnection.getTransceivers().find(t => t.mid === transceiverMid);
  622. } else if (trackIndex) {
  623. transceiver = this.pc.peerconnection.getTransceivers()
  624. .filter(t => t.receiver.track.kind === mediaType
  625. && t.direction !== MediaDirection.RECVONLY)[trackIndex];
  626. }
  627. }
  628. }
  629. if (!transceiver) {
  630. return Promise.reject(
  631. new Error(`Replace track failed - no transceiver for old: ${oldTrack}, new: ${newTrack}`));
  632. }
  633. logger.debug(`${this.pc} Replacing ${oldTrack} with ${newTrack}`);
  634. return transceiver.sender.replaceTrack(track)
  635. .then(() => Promise.resolve(transceiver));
  636. }
  637. /**
  638. * Set the simulcast stream encoding properties on the RTCRtpSender.
  639. *
  640. * @param {JitsiLocalTrack} localTrack - the current track in use for which the encodings are to be set.
  641. * @returns {Promise<void>} - resolved when done.
  642. */
  643. setEncodings(localTrack) {
  644. if (localTrack.getType() === MediaType.VIDEO) {
  645. return this.pc._updateVideoSenderParameters(() => this._configureSenderEncodings(localTrack));
  646. }
  647. return this._configureSenderEncodings(localTrack);
  648. }
  649. /**
  650. * Resumes or suspends media on the peerconnection by setting the active state on RTCRtpEncodingParameters
  651. * associated with all the senders that have a track attached to it.
  652. *
  653. * @param {boolean} enable - whether outgoing media needs to be enabled or disabled.
  654. * @param {string} mediaType - media type, 'audio' or 'video', if neither is passed, all outgoing media will either
  655. * be enabled or disabled.
  656. * @returns {Promise} - A promise that is resolved when the change is succesful on all the senders, rejected
  657. * otherwise.
  658. */
  659. setMediaTransferActive(enable, mediaType) {
  660. logger.info(`${this.pc} ${enable ? 'Resuming' : 'Suspending'} media transfer.`);
  661. const senders = this.pc.peerconnection.getSenders()
  662. .filter(s => Boolean(s.track) && (!mediaType || s.track.kind === mediaType));
  663. const promises = [];
  664. for (const sender of senders) {
  665. if (sender.track.kind === MediaType.VIDEO) {
  666. promises.push(this.pc._updateVideoSenderParameters(() => this._enableSenderEncodings(sender, enable)));
  667. } else {
  668. promises.push(this._enableSenderEncodings(sender, enable));
  669. }
  670. }
  671. return Promise.allSettled(promises)
  672. .then(settledResult => {
  673. const errors = settledResult
  674. .filter(result => result.status === 'rejected')
  675. .map(result => result.reason);
  676. if (errors.length) {
  677. return Promise.reject(new Error('Failed to change encodings on the RTCRtpSenders'
  678. + `${errors.join(' ')}`));
  679. }
  680. return Promise.resolve();
  681. });
  682. }
  683. }