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

TPCUtils.js 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  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. // Single video stream.
  366. if (!this.pc.isSpatialScalabilityOn() || this._isRunningInFullSvcMode(codec)) {
  367. const { active } = this._calculateActiveEncodingParams(localVideoTrack, codec, newHeight);
  368. return idx === 0 ? active : false;
  369. }
  370. // Multiple video streams.
  371. let active = false;
  372. if (newHeight > 0) {
  373. if (localVideoTrack.getVideoType() === VideoType.CAMERA) {
  374. active = frameHeight <= newHeight
  375. // Keep the LD stream enabled even when the LD stream's resolution is higher than of the
  376. // requested resolution. This can happen when camera is captured at high resolutions like 4k
  377. // but the requested resolution is 180. Since getParameters doesn't give us information about
  378. // the resolutions of the simulcast encodings, we have to rely on our initial config for the
  379. // simulcast streams.
  380. || videoStreamEncodings[idx]?.scaleResolutionDownBy === SIM_LAYERS[0].scaleFactor;
  381. } else {
  382. // For screenshare, keep the HD layer enabled always and the lower layers only for high fps
  383. // screensharing.
  384. active = videoStreamEncodings[idx].scaleResolutionDownBy === SIM_LAYERS[2].scaleFactor
  385. || !this._isScreenshareBitrateCapped(localVideoTrack);
  386. }
  387. }
  388. return active;
  389. });
  390. return encodingsState;
  391. }
  392. /**
  393. * Returns the calculated max bitrates that need to be configured on the stream encodings based on the video
  394. * type and other considerations associated with screenshare.
  395. *
  396. * @param {JitsiLocalTrack} localVideoTrack The local video track.
  397. * @param {CodecMimeType} codec - The codec currently in use.
  398. * @param {number} newHeight The resolution requested for the video track.
  399. * @returns {Array<number>}
  400. */
  401. calculateEncodingsBitrates(localVideoTrack, codec, newHeight) {
  402. const codecBitrates = this.codecSettings[codec].maxBitratesVideo;
  403. const desktopShareBitrate = this.pc.options?.videoQuality?.desktopbitrate || codecBitrates.ssHigh;
  404. const encodingsBitrates = this._getVideoStreamEncodings(localVideoTrack, codec)
  405. .map((encoding, idx) => {
  406. let bitrate = encoding.maxBitrate;
  407. // Single video stream.
  408. if (!this.pc.isSpatialScalabilityOn() || this._isRunningInFullSvcMode(codec)) {
  409. const { maxBitrate } = this._calculateActiveEncodingParams(localVideoTrack, codec, newHeight);
  410. return idx === 0 ? maxBitrate : 0;
  411. }
  412. // Multiple video streams.
  413. if (this._isScreenshareBitrateCapped(localVideoTrack)) {
  414. bitrate = desktopShareBitrate;
  415. }
  416. return bitrate;
  417. });
  418. return encodingsBitrates;
  419. }
  420. /**
  421. * Returns the calculated scalability modes for the video encodings when scalability modes are supported.
  422. *
  423. * @param {JitsiLocalTrack} localVideoTrack The local video track.
  424. * @param {CodecMimeType} codec - The codec currently in use.
  425. * @param {number} maxHeight The resolution requested for the video track.
  426. * @returns {Array<VideoEncoderScalabilityMode> | undefined}
  427. */
  428. calculateEncodingsScalabilityMode(localVideoTrack, codec, maxHeight) {
  429. if (!this.pc.isSpatialScalabilityOn() || !this.codecSettings[codec].scalabilityModeEnabled) {
  430. return;
  431. }
  432. // Default modes for simulcast.
  433. const scalabilityModes = [
  434. VideoEncoderScalabilityMode.L1T3,
  435. VideoEncoderScalabilityMode.L1T3,
  436. VideoEncoderScalabilityMode.L1T3
  437. ];
  438. // Full SVC mode.
  439. if (this._isRunningInFullSvcMode(codec)) {
  440. const { scalabilityMode }
  441. = this._calculateActiveEncodingParams(localVideoTrack, codec, maxHeight);
  442. scalabilityModes[0] = scalabilityMode;
  443. scalabilityModes[1] = undefined;
  444. scalabilityModes[2] = undefined;
  445. return scalabilityModes;
  446. }
  447. return scalabilityModes;
  448. }
  449. /**
  450. * Returns the scale factor that needs to be applied on the local video stream based on the desired resolution
  451. * and the codec in use.
  452. *
  453. * @param {JitsiLocalTrack} localVideoTrack The local video track.
  454. * @param {CodecMimeType} codec - The codec currently in use.
  455. * @param {number} maxHeight The resolution requested for the video track.
  456. * @returns {Array<float>}
  457. */
  458. calculateEncodingsScaleFactor(localVideoTrack, codec, maxHeight) {
  459. if (this.pc.isSpatialScalabilityOn() && this.isRunningInSimulcastMode(codec)) {
  460. return this._getVideoStreamEncodings(localVideoTrack, codec)
  461. .map(encoding => encoding.scaleResolutionDownBy);
  462. }
  463. // Single video stream.
  464. const { scaleResolutionDownBy }
  465. = this._calculateActiveEncodingParams(localVideoTrack, codec, maxHeight);
  466. return [ scaleResolutionDownBy, undefined, undefined ];
  467. }
  468. /**
  469. * Ensures that the ssrcs associated with a FID ssrc-group appear in the correct order, i.e.,
  470. * the primary ssrc first and the secondary rtx ssrc later. This is important for unified
  471. * plan since we have only one FID group per media description.
  472. * @param {Object} description the webRTC session description instance for the remote
  473. * description.
  474. * @private
  475. */
  476. ensureCorrectOrderOfSsrcs(description) {
  477. const parsedSdp = transform.parse(description.sdp);
  478. parsedSdp.media.forEach(mLine => {
  479. if (mLine.type === MediaType.AUDIO) {
  480. return;
  481. }
  482. if (!mLine.ssrcGroups || !mLine.ssrcGroups.length) {
  483. return;
  484. }
  485. let reorderedSsrcs = [];
  486. const ssrcs = new Set();
  487. mLine.ssrcGroups.map(group =>
  488. group.ssrcs
  489. .split(' ')
  490. .filter(Boolean)
  491. .forEach(ssrc => ssrcs.add(ssrc))
  492. );
  493. ssrcs.forEach(ssrc => {
  494. const sources = mLine.ssrcs.filter(source => source.id.toString() === ssrc);
  495. reorderedSsrcs = reorderedSsrcs.concat(sources);
  496. });
  497. mLine.ssrcs = reorderedSsrcs;
  498. });
  499. return new RTCSessionDescription({
  500. type: description.type,
  501. sdp: transform.write(parsedSdp)
  502. });
  503. }
  504. /**
  505. * Takes in a *unified plan* offer and inserts the appropriate parameters for adding simulcast receive support.
  506. * @param {Object} desc - A session description object
  507. * @param {String} desc.type - the type (offer/answer)
  508. * @param {String} desc.sdp - the sdp content
  509. *
  510. * @return {Object} A session description (same format as above) object with its sdp field modified to advertise
  511. * simulcast receive support.
  512. */
  513. insertUnifiedPlanSimulcastReceive(desc) {
  514. // a=simulcast line is not needed on browsers where we SDP munging is used for enabling on simulcast.
  515. // Remove this check when the client switches to RID/MID based simulcast on all browsers.
  516. if (browser.usesSdpMungingForSimulcast()) {
  517. return desc;
  518. }
  519. const rids = [
  520. {
  521. id: SIM_LAYERS[0].rid,
  522. direction: 'recv'
  523. },
  524. {
  525. id: SIM_LAYERS[1].rid,
  526. direction: 'recv'
  527. },
  528. {
  529. id: SIM_LAYERS[2].rid,
  530. direction: 'recv'
  531. }
  532. ];
  533. const ridLine = rids.map(val => val.id).join(';');
  534. const simulcastLine = `recv ${ridLine}`;
  535. const sdp = transform.parse(desc.sdp);
  536. const mLines = sdp.media.filter(m => m.type === MediaType.VIDEO);
  537. const senderMids = Array.from(this.pc._localTrackTransceiverMids.values());
  538. mLines.forEach((mLine, idx) => {
  539. // Make sure the simulcast recv line is only set on video descriptions that are associated with senders.
  540. if (senderMids.find(sender => mLine.mid.toString() === sender.toString()) || idx === 0) {
  541. if (!mLine.simulcast_03 || !mLine.simulcast) {
  542. mLine.rids = rids;
  543. // eslint-disable-next-line camelcase
  544. mLine.simulcast_03 = {
  545. value: simulcastLine
  546. };
  547. }
  548. } else {
  549. mLine.rids = undefined;
  550. mLine.simulcast = undefined;
  551. // eslint-disable-next-line camelcase
  552. mLine.simulcast_03 = undefined;
  553. }
  554. });
  555. return new RTCSessionDescription({
  556. type: desc.type,
  557. sdp: transform.write(sdp)
  558. });
  559. }
  560. /**
  561. * Returns a boolean indicating whether the video encoder is running in Simulcast mode, i.e., three encodings need
  562. * to be configured in 4:2:1 resolution order with temporal scalability.
  563. *
  564. * @param {CodecMimeType} codec - The video codec in use.
  565. * @returns {boolean}
  566. */
  567. isRunningInSimulcastMode(codec) {
  568. return codec === CodecMimeType.VP8 // VP8 always
  569. // K-SVC mode for VP9 when no scalability mode is set. Though only one outbound-rtp stream is present,
  570. // three separate encodings have to be configured.
  571. || (!this.codecSettings[codec].scalabilityModeEnabled && codec === CodecMimeType.VP9)
  572. // When scalability is enabled, always for H.264, and only when simulcast is explicitly enabled via
  573. // config.js for VP9 and AV1 since full SVC is the default mode for these 2 codecs.
  574. || (this.codecSettings[codec].scalabilityModeEnabled
  575. && (codec === CodecMimeType.H264 || this.codecSettings[codec].useSimulcast));
  576. }
  577. /**
  578. * Replaces the existing track on a RTCRtpSender with the given track.
  579. *
  580. * @param {JitsiLocalTrack} oldTrack - existing track on the sender that needs to be removed.
  581. * @param {JitsiLocalTrack} newTrack - new track that needs to be added to the sender.
  582. * @returns {Promise<RTCRtpTransceiver>} - resolved with the associated transceiver when done, rejected otherwise.
  583. */
  584. replaceTrack(oldTrack, newTrack) {
  585. const mediaType = newTrack?.getType() ?? oldTrack?.getType();
  586. const localTracks = this.pc.getLocalTracks(mediaType);
  587. const track = newTrack?.getTrack() ?? null;
  588. const isNewLocalSource = localTracks?.length
  589. && !oldTrack
  590. && newTrack
  591. && !localTracks.find(t => t === newTrack);
  592. let transceiver;
  593. // If old track exists, replace the track on the corresponding sender.
  594. if (oldTrack && !oldTrack.isMuted()) {
  595. transceiver = this.pc.peerconnection.getTransceivers().find(t => t.sender.track === oldTrack.getTrack());
  596. // Find the first recvonly transceiver when more than one track of the same media type is being added to the pc.
  597. // As part of the track addition, a new m-line was added to the remote description with direction set to
  598. // recvonly.
  599. } else if (isNewLocalSource) {
  600. transceiver = this.pc.peerconnection.getTransceivers().find(
  601. t => t.receiver.track.kind === mediaType
  602. && t.direction === MediaDirection.RECVONLY
  603. // Re-use any existing recvonly transceiver (if available) for p2p case.
  604. && ((this.pc.isP2P && t.currentDirection === MediaDirection.RECVONLY)
  605. || (t.currentDirection === MediaDirection.INACTIVE && !t.stopped)));
  606. // For mute/unmute operations, find the transceiver based on the track index in the source name if present,
  607. // otherwise it is assumed to be the first local track that was added to the peerconnection.
  608. } else {
  609. transceiver = this.pc.peerconnection.getTransceivers().find(t => t.receiver.track.kind === mediaType);
  610. const sourceName = newTrack?.getSourceName() ?? oldTrack?.getSourceName();
  611. if (sourceName) {
  612. const trackIndex = getSourceIndexFromSourceName(sourceName);
  613. if (this.pc.isP2P) {
  614. transceiver = this.pc.peerconnection.getTransceivers()
  615. .filter(t => t.receiver.track.kind === mediaType)[trackIndex];
  616. } else if (oldTrack) {
  617. const transceiverMid = this.pc._localTrackTransceiverMids.get(oldTrack.rtcId);
  618. transceiver = this.pc.peerconnection.getTransceivers().find(t => t.mid === transceiverMid);
  619. } else if (trackIndex) {
  620. transceiver = this.pc.peerconnection.getTransceivers()
  621. .filter(t => t.receiver.track.kind === mediaType
  622. && t.direction !== MediaDirection.RECVONLY)[trackIndex];
  623. }
  624. }
  625. }
  626. if (!transceiver) {
  627. return Promise.reject(
  628. new Error(`Replace track failed - no transceiver for old: ${oldTrack}, new: ${newTrack}`));
  629. }
  630. logger.debug(`${this.pc} Replacing ${oldTrack} with ${newTrack}`);
  631. return transceiver.sender.replaceTrack(track)
  632. .then(() => Promise.resolve(transceiver));
  633. }
  634. /**
  635. * Set the simulcast stream encoding properties on the RTCRtpSender.
  636. *
  637. * @param {JitsiLocalTrack} localTrack - the current track in use for which the encodings are to be set.
  638. * @returns {Promise<void>} - resolved when done.
  639. */
  640. setEncodings(localTrack) {
  641. if (localTrack.getType() === MediaType.VIDEO) {
  642. return this.pc._updateVideoSenderParameters(() => this._configureSenderEncodings(localTrack));
  643. }
  644. return this._configureSenderEncodings(localTrack);
  645. }
  646. /**
  647. * Resumes or suspends media on the peerconnection by setting the active state on RTCRtpEncodingParameters
  648. * associated with all the senders that have a track attached to it.
  649. *
  650. * @param {boolean} enable - whether outgoing media needs to be enabled or disabled.
  651. * @param {string} mediaType - media type, 'audio' or 'video', if neither is passed, all outgoing media will either
  652. * be enabled or disabled.
  653. * @returns {Promise} - A promise that is resolved when the change is succesful on all the senders, rejected
  654. * otherwise.
  655. */
  656. setMediaTransferActive(enable, mediaType) {
  657. logger.info(`${this.pc} ${enable ? 'Resuming' : 'Suspending'} media transfer.`);
  658. const senders = this.pc.peerconnection.getSenders()
  659. .filter(s => Boolean(s.track) && (!mediaType || s.track.kind === mediaType));
  660. const promises = [];
  661. for (const sender of senders) {
  662. if (sender.track.kind === MediaType.VIDEO) {
  663. promises.push(this.pc._updateVideoSenderParameters(() => this._enableSenderEncodings(sender, enable)));
  664. } else {
  665. promises.push(this._enableSenderEncodings(sender, enable));
  666. }
  667. }
  668. return Promise.allSettled(promises)
  669. .then(settledResult => {
  670. const errors = settledResult
  671. .filter(result => result.status === 'rejected')
  672. .map(result => result.reason);
  673. if (errors.length) {
  674. return Promise.reject(new Error('Failed to change encodings on the RTCRtpSenders'
  675. + `${errors.join(' ')}`));
  676. }
  677. return Promise.resolve();
  678. });
  679. }
  680. }