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 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. import { getLogger } from '@jitsi/logger';
  2. import { cloneDeep } from 'lodash-es';
  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 {
  8. SIM_LAYERS,
  9. SSRC_GROUP_SEMANTICS,
  10. STANDARD_CODEC_SETTINGS,
  11. VIDEO_QUALITY_LEVELS,
  12. VIDEO_QUALITY_SETTINGS
  13. } from '../../service/RTC/StandardVideoQualitySettings';
  14. import { VideoEncoderScalabilityMode } from '../../service/RTC/VideoEncoderScalabilityMode';
  15. import { VideoType } from '../../service/RTC/VideoType';
  16. import browser from '../browser';
  17. import SDPUtil from '../sdp/SDPUtil';
  18. const logger = getLogger('modules/RTC/TPCUtils');
  19. const VIDEO_CODECS = [ CodecMimeType.AV1, CodecMimeType.H264, CodecMimeType.VP8, CodecMimeType.VP9 ];
  20. /**
  21. * Handles all the utility functions for the TraceablePeerConnection class, like calculating the encoding parameters,
  22. * determining the media direction, calculating bitrates based on the current codec settings, etc.
  23. */
  24. export class TPCUtils {
  25. /**
  26. * Creates a new instance for a given TraceablePeerConnection
  27. *
  28. * @param peerconnection - the tpc instance for which we have utility functions.
  29. * @param options - additional options that can be passed to the utility functions.
  30. * @param options.audioQuality - the audio quality settings that are used to calculate the audio codec parameters.
  31. * @param options.isP2P - whether the connection is a P2P connection.
  32. * @param options.videoQuality - the video quality settings that are used to calculate the encoding parameters.
  33. */
  34. constructor(peerconnection, options = {}) {
  35. this.pc = peerconnection;
  36. this.options = options;
  37. this.codecSettings = cloneDeep(STANDARD_CODEC_SETTINGS);
  38. /**
  39. * Flag indicating bridge support for AV1 codec. On the bridge connection, it is supported only when support for
  40. * Dependency Descriptor header extensions is offered by Jicofo. H.264 simulcast is also possible when these
  41. * header extensions are negotiated.
  42. */
  43. this.supportsDDHeaderExt = false;
  44. /**
  45. * Reads videoQuality settings from config.js and overrides the code defaults for video codecs.
  46. */
  47. const videoQualitySettings = this.options.videoQuality;
  48. if (videoQualitySettings) {
  49. for (const codec of VIDEO_CODECS) {
  50. const codecConfig = videoQualitySettings[codec];
  51. const bitrateSettings = codecConfig?.maxBitratesVideo
  52. // Read the deprecated settings for max bitrates.
  53. ?? (videoQualitySettings.maxbitratesvideo
  54. && videoQualitySettings.maxbitratesvideo[codec.toUpperCase()]);
  55. if (bitrateSettings) {
  56. const settings = Object.values(VIDEO_QUALITY_SETTINGS);
  57. [ ...settings, 'ssHigh' ].forEach(value => {
  58. if (bitrateSettings[value]) {
  59. this.codecSettings[codec].maxBitratesVideo[value] = bitrateSettings[value];
  60. }
  61. });
  62. }
  63. if (!codecConfig) {
  64. continue; // eslint-disable-line no-continue
  65. }
  66. const scalabilityModeEnabled = this.codecSettings[codec].scalabilityModeEnabled
  67. && (typeof codecConfig.scalabilityModeEnabled === 'undefined'
  68. || codecConfig.scalabilityModeEnabled);
  69. if (scalabilityModeEnabled) {
  70. typeof codecConfig.useSimulcast !== 'undefined'
  71. && (this.codecSettings[codec].useSimulcast = codecConfig.useSimulcast);
  72. typeof codecConfig.useKSVC !== 'undefined'
  73. && (this.codecSettings[codec].useKSVC = codecConfig.useKSVC);
  74. } else {
  75. this.codecSettings[codec].scalabilityModeEnabled = false;
  76. }
  77. }
  78. }
  79. }
  80. /**
  81. * Calculates the configuration of the active encoding when the browser sends only one stream, i,e,, when there is
  82. * no spatial scalability configure (p2p) or when it is running in full SVC mode.
  83. *
  84. * @param {JitsiLocalTrack} localVideoTrack - The local video track.
  85. * @param {CodecMimeType} codec - The video codec.
  86. * @param {number} newHeight - The resolution that needs to be configured for the local video track.
  87. * @returns {Object} configuration.
  88. * @private
  89. */
  90. _calculateActiveEncodingParams(localVideoTrack, codec, newHeight) {
  91. const codecBitrates = this.codecSettings[codec].maxBitratesVideo;
  92. const trackCaptureHeight = localVideoTrack.getCaptureResolution();
  93. const effectiveNewHeight = newHeight > trackCaptureHeight ? trackCaptureHeight : newHeight;
  94. const desktopShareBitrate = this.options.videoQuality?.desktopbitrate || codecBitrates.ssHigh;
  95. const isScreenshare = localVideoTrack.getVideoType() === VideoType.DESKTOP;
  96. let scalabilityMode = this.codecSettings[codec].useKSVC
  97. ? VideoEncoderScalabilityMode.L3T3_KEY : VideoEncoderScalabilityMode.L3T3;
  98. const { height, level } = VIDEO_QUALITY_LEVELS.find(lvl => lvl.height <= effectiveNewHeight);
  99. let maxBitrate;
  100. let scaleResolutionDownBy = SIM_LAYERS[2].scaleFactor;
  101. if (this._isScreenshareBitrateCapped(localVideoTrack)) {
  102. scalabilityMode = VideoEncoderScalabilityMode.L1T3;
  103. maxBitrate = desktopShareBitrate;
  104. } else if (isScreenshare) {
  105. maxBitrate = codecBitrates.ssHigh;
  106. } else {
  107. maxBitrate = codecBitrates[level];
  108. effectiveNewHeight && (scaleResolutionDownBy = trackCaptureHeight / effectiveNewHeight);
  109. if (height !== effectiveNewHeight) {
  110. logger.debug(`Quality level with height=${height} was picked when requested height=${newHeight} for`
  111. + `track with capture height=${trackCaptureHeight}`);
  112. }
  113. }
  114. const config = {
  115. active: effectiveNewHeight > 0,
  116. maxBitrate,
  117. scalabilityMode,
  118. scaleResolutionDownBy
  119. };
  120. if (!config.active || isScreenshare) {
  121. return config;
  122. }
  123. // Configure the sender to send all 3 spatial layers for resolutions 720p and higher.
  124. switch (level) {
  125. case VIDEO_QUALITY_SETTINGS.ULTRA:
  126. case VIDEO_QUALITY_SETTINGS.FULL:
  127. case VIDEO_QUALITY_SETTINGS.HIGH:
  128. config.scalabilityMode = this.codecSettings[codec].useKSVC
  129. ? VideoEncoderScalabilityMode.L3T3_KEY : VideoEncoderScalabilityMode.L3T3;
  130. break;
  131. case VIDEO_QUALITY_SETTINGS.STANDARD:
  132. config.scalabilityMode = this.codecSettings[codec].useKSVC
  133. ? VideoEncoderScalabilityMode.L2T3_KEY : VideoEncoderScalabilityMode.L2T3;
  134. break;
  135. default:
  136. config.scalabilityMode = VideoEncoderScalabilityMode.L1T3;
  137. }
  138. return config;
  139. }
  140. /**
  141. * Returns the codecs in the current order of preference in the SDP provided.
  142. *
  143. * @param {transform.SessionDescription} parsedSdp the parsed SDP object.
  144. * @returns {Array<CodecMimeType>}
  145. * @private
  146. */
  147. _getConfiguredVideoCodecsImpl(parsedSdp) {
  148. const mLine = parsedSdp.media.find(m => m.type === MediaType.VIDEO);
  149. const codecs = new Set(mLine.rtp
  150. .filter(pt => pt.codec.toLowerCase() !== 'rtx')
  151. .map(pt => pt.codec.toLowerCase()));
  152. return Array.from(codecs);
  153. }
  154. /**
  155. * The startup configuration for the stream encodings that are applicable to the video stream when a new sender is
  156. * created on the peerconnection. The initial config takes into account the differences in browser's simulcast
  157. * implementation.
  158. *
  159. * Encoding parameters:
  160. * active - determine the on/off state of a particular encoding.
  161. * maxBitrate - max. bitrate value to be applied to that particular encoding based on the encoding's resolution and
  162. * config.js videoQuality settings if applicable.
  163. * rid - Rtp Stream ID that is configured for a particular simulcast stream.
  164. * scaleResolutionDownBy - the factor by which the encoding is scaled down from the original resolution of the
  165. * captured video.
  166. *
  167. * @param {JitsiLocalTrack} localTrack - The local video track.
  168. * @param {String} codec - The codec currently in use.
  169. * @returns {Array<Object>} - The initial configuration for the stream encodings.
  170. * @private
  171. */
  172. _getVideoStreamEncodings(localTrack, codec) {
  173. const captureResolution = localTrack.getCaptureResolution();
  174. const codecBitrates = this.codecSettings[codec].maxBitratesVideo;
  175. const videoType = localTrack.getVideoType();
  176. let effectiveScaleFactors = SIM_LAYERS.map(sim => sim.scaleFactor);
  177. let cameraMaxbitrate;
  178. if (videoType === VideoType.CAMERA) {
  179. const { level } = VIDEO_QUALITY_LEVELS.find(lvl => lvl.height <= captureResolution);
  180. cameraMaxbitrate = codecBitrates[level];
  181. if (level === VIDEO_QUALITY_SETTINGS.ULTRA) {
  182. effectiveScaleFactors[1] = 6.0; // 360p
  183. effectiveScaleFactors[0] = 12.0; // 180p
  184. } else if (level === VIDEO_QUALITY_SETTINGS.FULL) {
  185. effectiveScaleFactors[1] = 3.0; // 360p
  186. effectiveScaleFactors[0] = 6.0; // 180p
  187. }
  188. }
  189. const maxBitrate = videoType === VideoType.DESKTOP
  190. ? codecBitrates.ssHigh : cameraMaxbitrate;
  191. let effectiveBitrates = [ codecBitrates.low, codecBitrates.standard, maxBitrate ];
  192. // The SSRCs on older versions of Firefox are reversed in SDP, i.e., they have resolution order of 1:2:4 as
  193. // opposed to Chromium and other browsers. This has been reverted in Firefox 117 as part of the below commit.
  194. // https://hg.mozilla.org/mozilla-central/rev/b0348f1f8d7197fb87158ba74542d28d46133997
  195. // This revert seems to be applied only to camera tracks, the desktop stream encodings still have the
  196. // resolution order of 4:2:1.
  197. if (browser.isFirefox()
  198. && !browser.supportsScalabilityModeAPI()
  199. && (videoType === VideoType.DESKTOP || browser.isVersionLessThan(117))) {
  200. effectiveBitrates = effectiveBitrates.reverse();
  201. effectiveScaleFactors = effectiveScaleFactors.reverse();
  202. }
  203. const standardSimulcastEncodings = [
  204. {
  205. active: this.pc.videoTransferActive,
  206. maxBitrate: effectiveBitrates[0],
  207. rid: SIM_LAYERS[0].rid,
  208. scaleResolutionDownBy: effectiveScaleFactors[0]
  209. },
  210. {
  211. active: this.pc.videoTransferActive,
  212. maxBitrate: effectiveBitrates[1],
  213. rid: SIM_LAYERS[1].rid,
  214. scaleResolutionDownBy: effectiveScaleFactors[1]
  215. },
  216. {
  217. active: this.pc.videoTransferActive,
  218. maxBitrate: effectiveBitrates[2],
  219. rid: SIM_LAYERS[2].rid,
  220. scaleResolutionDownBy: effectiveScaleFactors[2]
  221. }
  222. ];
  223. if (this.codecSettings[codec].scalabilityModeEnabled) {
  224. // Configure all 3 encodings when simulcast is requested through config.js for AV1 and VP9 and for H.264
  225. // always since that is the only supported mode when DD header extension is negotiated for H.264.
  226. if (this.codecSettings[codec].useSimulcast || codec === CodecMimeType.H264) {
  227. for (const encoding of standardSimulcastEncodings) {
  228. encoding.scalabilityMode = VideoEncoderScalabilityMode.L1T3;
  229. }
  230. return standardSimulcastEncodings;
  231. }
  232. // Configure only one encoding for the SVC mode.
  233. return [
  234. {
  235. active: this.pc.videoTransferActive,
  236. maxBitrate: effectiveBitrates[2],
  237. rid: SIM_LAYERS[0].rid,
  238. scaleResolutionDownBy: effectiveScaleFactors[2],
  239. scalabilityMode: this.codecSettings[codec].useKSVC
  240. ? VideoEncoderScalabilityMode.L3T3_KEY : VideoEncoderScalabilityMode.L3T3
  241. },
  242. {
  243. active: false,
  244. maxBitrate: 0
  245. },
  246. {
  247. active: false,
  248. maxBitrate: 0
  249. }
  250. ];
  251. }
  252. return standardSimulcastEncodings;
  253. }
  254. /**
  255. * Returns a boolean indicating whether the video encoder is running in full SVC mode, i.e., it sends only one
  256. * video stream that has both temporal and spatial scalability.
  257. *
  258. * @param {CodecMimeType} codec - The video codec in use.
  259. * @returns boolean - true if the video encoder is running in full SVC mode, false otherwise.
  260. * @private
  261. */
  262. _isRunningInFullSvcMode(codec) {
  263. return (codec === CodecMimeType.VP9 || codec === CodecMimeType.AV1)
  264. && this.codecSettings[codec].scalabilityModeEnabled
  265. && !this.codecSettings[codec].useSimulcast;
  266. }
  267. /**
  268. * Returns a boolean indicating whether the bitrate needs to be capped for the local video track if it happens to
  269. * be a screenshare track. The lower spatial layers for screensharing are disabled when low fps screensharing is in
  270. * progress. Sending all three streams often results in the browser suspending the high resolution in low b/w and
  271. * and low cpu conditions, especially on the low end machines. Suspending the low resolution streams ensures that
  272. * the highest resolution stream is available always. Safari is an exception here since it does not send the
  273. * desktop stream at all if only the high resolution stream is enabled.
  274. *
  275. * @param {JitsiLocalTrack} localVideoTrack - The local video track.
  276. * @returns {boolean} - true if the bitrate needs to be capped for the screenshare track, false otherwise.
  277. * @private
  278. */
  279. _isScreenshareBitrateCapped(localVideoTrack) {
  280. return localVideoTrack.getVideoType() === VideoType.DESKTOP
  281. && this.pc._capScreenshareBitrate
  282. && !browser.isWebKitBased();
  283. }
  284. /**
  285. * Returns the calculated active state of the stream encodings based on the frame height requested for the send
  286. * stream. All the encodings that have a resolution lower than the frame height requested will be enabled.
  287. *
  288. * @param {JitsiLocalTrack} localVideoTrack The local video track.
  289. * @param {CodecMimeType} codec - The codec currently in use.
  290. * @param {number} newHeight The resolution requested for the video track.
  291. * @returns {Array<boolean>}
  292. */
  293. calculateEncodingsActiveState(localVideoTrack, codec, newHeight) {
  294. const height = localVideoTrack.getCaptureResolution();
  295. const videoStreamEncodings = this._getVideoStreamEncodings(localVideoTrack, codec);
  296. const encodingsState = videoStreamEncodings
  297. .map(encoding => height / encoding.scaleResolutionDownBy)
  298. .map((frameHeight, idx) => {
  299. let activeState = false;
  300. // When video is suspended on the media session.
  301. if (!this.pc.videoTransferActive) {
  302. return activeState;
  303. }
  304. // Single video stream.
  305. if (!this.pc.isSpatialScalabilityOn() || this._isRunningInFullSvcMode(codec)) {
  306. const { active } = this._calculateActiveEncodingParams(localVideoTrack, codec, newHeight);
  307. return idx === 0 ? active : activeState;
  308. }
  309. if (newHeight > 0) {
  310. if (localVideoTrack.getVideoType() === VideoType.CAMERA) {
  311. activeState = frameHeight <= newHeight
  312. // Keep the LD stream enabled even when the LD stream's resolution is higher than of the
  313. // requested resolution. This can happen when camera is captured at high resolutions like 4k
  314. // but the requested resolution is 180. Since getParameters doesn't give us information about
  315. // the resolutions of the simulcast encodings, we have to rely on our initial config for the
  316. // simulcast streams.
  317. || videoStreamEncodings[idx]?.scaleResolutionDownBy === SIM_LAYERS[0].scaleFactor;
  318. } else {
  319. // For screenshare, keep the HD layer enabled always and the lower layers only for high fps
  320. // screensharing.
  321. activeState = videoStreamEncodings[idx].scaleResolutionDownBy === SIM_LAYERS[2].scaleFactor
  322. || !this._isScreenshareBitrateCapped(localVideoTrack);
  323. }
  324. }
  325. return activeState;
  326. });
  327. return encodingsState;
  328. }
  329. /**
  330. * Returns the calculated max bitrates that need to be configured on the stream encodings based on the video
  331. * type and other considerations associated with screenshare.
  332. *
  333. * @param {JitsiLocalTrack} localVideoTrack The local video track.
  334. * @param {CodecMimeType} codec - The codec currently in use.
  335. * @param {number} newHeight The resolution requested for the video track.
  336. * @returns {Array<number>}
  337. */
  338. calculateEncodingsBitrates(localVideoTrack, codec, newHeight) {
  339. const codecBitrates = this.codecSettings[codec].maxBitratesVideo;
  340. const desktopShareBitrate = this.options.videoQuality?.desktopbitrate || codecBitrates.ssHigh;
  341. const encodingsBitrates = this._getVideoStreamEncodings(localVideoTrack, codec)
  342. .map((encoding, idx) => {
  343. let bitrate = encoding.maxBitrate;
  344. // Single video stream.
  345. if (!this.pc.isSpatialScalabilityOn() || this._isRunningInFullSvcMode(codec)) {
  346. const { maxBitrate } = this._calculateActiveEncodingParams(localVideoTrack, codec, newHeight);
  347. return idx === 0 ? maxBitrate : 0;
  348. }
  349. // Multiple video streams.
  350. if (this._isScreenshareBitrateCapped(localVideoTrack)) {
  351. bitrate = desktopShareBitrate;
  352. }
  353. return bitrate;
  354. });
  355. return encodingsBitrates;
  356. }
  357. /**
  358. * Returns the calculated scalability modes for the video encodings when scalability modes are supported.
  359. *
  360. * @param {JitsiLocalTrack} localVideoTrack The local video track.
  361. * @param {CodecMimeType} codec - The codec currently in use.
  362. * @param {number} maxHeight The resolution requested for the video track.
  363. * @returns {Array<VideoEncoderScalabilityMode> | undefined}
  364. */
  365. calculateEncodingsScalabilityMode(localVideoTrack, codec, maxHeight) {
  366. if (!this.pc.isSpatialScalabilityOn() || !this.codecSettings[codec].scalabilityModeEnabled) {
  367. return;
  368. }
  369. // Default modes for simulcast.
  370. const scalabilityModes = [
  371. VideoEncoderScalabilityMode.L1T3,
  372. VideoEncoderScalabilityMode.L1T3,
  373. VideoEncoderScalabilityMode.L1T3
  374. ];
  375. // Full SVC mode.
  376. if (this._isRunningInFullSvcMode(codec)) {
  377. const { scalabilityMode }
  378. = this._calculateActiveEncodingParams(localVideoTrack, codec, maxHeight);
  379. scalabilityModes[0] = scalabilityMode;
  380. scalabilityModes[1] = undefined;
  381. scalabilityModes[2] = undefined;
  382. return scalabilityModes;
  383. }
  384. return scalabilityModes;
  385. }
  386. /**
  387. * Returns the scale factor that needs to be applied on the local video stream based on the desired resolution
  388. * and the codec in use.
  389. *
  390. * @param {JitsiLocalTrack} localVideoTrack The local video track.
  391. * @param {CodecMimeType} codec - The codec currently in use.
  392. * @param {number} maxHeight The resolution requested for the video track.
  393. * @returns {Array<float>}
  394. */
  395. calculateEncodingsScaleFactor(localVideoTrack, codec, maxHeight) {
  396. if (this.pc.isSpatialScalabilityOn() && this.isRunningInSimulcastMode(codec)) {
  397. return this._getVideoStreamEncodings(localVideoTrack, codec)
  398. .map(encoding => encoding.scaleResolutionDownBy);
  399. }
  400. // Single video stream.
  401. const { scaleResolutionDownBy }
  402. = this._calculateActiveEncodingParams(localVideoTrack, codec, maxHeight);
  403. return [ scaleResolutionDownBy, undefined, undefined ];
  404. }
  405. /**
  406. * Ensures that the ssrcs associated with a FID ssrc-group appear in the correct order, i.e., the primary ssrc
  407. * first and the secondary rtx ssrc later. This is important for unified plan since we have only one FID group per
  408. * media description.
  409. * @param {Object} description the webRTC session description instance for the remote description.
  410. * @returns {Object} the modified webRTC session description instance.
  411. */
  412. ensureCorrectOrderOfSsrcs(description) {
  413. const parsedSdp = transform.parse(description.sdp);
  414. parsedSdp.media.forEach(mLine => {
  415. if (mLine.type === MediaType.AUDIO) {
  416. return;
  417. }
  418. if (!mLine.ssrcGroups || !mLine.ssrcGroups.length) {
  419. return;
  420. }
  421. let reorderedSsrcs = [];
  422. const ssrcs = new Set();
  423. mLine.ssrcGroups.map(group =>
  424. group.ssrcs
  425. .split(' ')
  426. .filter(Boolean)
  427. .forEach(ssrc => ssrcs.add(ssrc))
  428. );
  429. ssrcs.forEach(ssrc => {
  430. const sources = mLine.ssrcs.filter(source => source.id.toString() === ssrc);
  431. reorderedSsrcs = reorderedSsrcs.concat(sources);
  432. });
  433. mLine.ssrcs = reorderedSsrcs;
  434. });
  435. return {
  436. type: description.type,
  437. sdp: transform.write(parsedSdp)
  438. };
  439. }
  440. /**
  441. * Returns the codec that is configured on the client as the preferred video codec for the given local video track.
  442. *
  443. * @param {JitsiLocalTrack} localTrack - The local video track.
  444. * @returns {CodecMimeType} The codec that is set as the preferred codec for the given local video track.
  445. */
  446. getConfiguredVideoCodec(localTrack) {
  447. const localVideoTrack = localTrack ?? this.pc.getLocalVideoTracks()[0];
  448. const rtpSender = this.pc.findSenderForTrack(localVideoTrack.getTrack());
  449. if (this.pc.usesCodecSelectionAPI() && rtpSender) {
  450. const { encodings } = rtpSender.getParameters();
  451. if (encodings[0].codec) {
  452. return encodings[0].codec.mimeType.split('/')[1].toLowerCase();
  453. }
  454. }
  455. const sdp = this.pc.remoteDescription?.sdp;
  456. if (!sdp) {
  457. return CodecMimeType.VP8;
  458. }
  459. const parsedSdp = transform.parse(sdp);
  460. const mLine = parsedSdp.media
  461. .find(m => m.mid.toString() === this.pc.localTrackTransceiverMids.get(localVideoTrack.rtcId));
  462. const payload = mLine.payloads.split(' ')[0];
  463. const { codec } = mLine.rtp.find(rtp => rtp.payload === Number(payload));
  464. if (codec) {
  465. return Object.values(CodecMimeType).find(value => value === codec.toLowerCase());
  466. }
  467. return CodecMimeType.VP8;
  468. }
  469. /**
  470. * Returns the codecs in the current order of preference as configured on the peerconnection.
  471. *
  472. * @param {string} - The local SDP to be used.
  473. * @returns {Array}
  474. */
  475. getConfiguredVideoCodecs(sdp) {
  476. const currentSdp = sdp ?? this.pc.localDescription?.sdp;
  477. if (!currentSdp) {
  478. return [];
  479. }
  480. const parsedSdp = transform.parse(currentSdp);
  481. return this._getConfiguredVideoCodecsImpl(parsedSdp);
  482. }
  483. /**
  484. * Returns the desired media direction for the given media type based on the current state of the peerconnection.
  485. *
  486. * @param {MediaType} mediaType - The media type for which the desired media direction is to be obtained.
  487. * @param {boolean} isAddOperation - Whether the direction is being set for a source add operation.
  488. * @returns {MediaDirection} - The desired media direction for the given media type.
  489. */
  490. getDesiredMediaDirection(mediaType, isAddOperation = false) {
  491. const hasLocalSource = this.pc.getLocalTracks(mediaType).length > 0;
  492. if (isAddOperation) {
  493. return hasLocalSource ? MediaDirection.SENDRECV : MediaDirection.SENDONLY;
  494. }
  495. return hasLocalSource ? MediaDirection.RECVONLY : MediaDirection.INACTIVE;
  496. }
  497. /**
  498. * Obtains stream encodings that need to be configured on the given track based
  499. * on the track media type and the simulcast setting.
  500. * @param {JitsiLocalTrack} localTrack
  501. */
  502. getStreamEncodings(localTrack) {
  503. if (localTrack.isAudioTrack()) {
  504. return [ { active: this.pc.audioTransferActive } ];
  505. }
  506. const codec = this.getConfiguredVideoCodec(localTrack);
  507. if (this.pc.isSpatialScalabilityOn()) {
  508. return this._getVideoStreamEncodings(localTrack, codec);
  509. }
  510. return [ {
  511. active: this.pc.videoTransferActive,
  512. maxBitrate: this.codecSettings[codec].maxBitratesVideo.high
  513. } ];
  514. }
  515. /**
  516. * Injects a 'SIM' ssrc-group line for simulcast into the given session description object to make Jicofo happy.
  517. * This is needed only for Firefox since it does not generate it when simulcast is enabled but we run the check
  518. * on all browsers just in case as it would break the functionality otherwise.
  519. *
  520. * @param desc A session description object (with 'type' and 'sdp' fields)
  521. * @return A session description object with its sdp field modified to contain an inject ssrc-group for simulcast.
  522. */
  523. injectSsrcGroupForSimulcast(desc) {
  524. const sdp = transform.parse(desc.sdp);
  525. const video = sdp.media.find(mline => mline.type === 'video');
  526. // Check if the browser supports RTX, add only the primary ssrcs to the SIM group if that is the case.
  527. video.ssrcGroups = video.ssrcGroups || [];
  528. const fidGroups = video.ssrcGroups.filter(group => group.semantics === SSRC_GROUP_SEMANTICS.FID);
  529. if (video.simulcast || video.simulcast_03) {
  530. const ssrcs = [];
  531. if (fidGroups && fidGroups.length) {
  532. fidGroups.forEach(group => {
  533. ssrcs.push(group.ssrcs.split(' ')[0]);
  534. });
  535. } else {
  536. video.ssrcs.forEach(ssrc => {
  537. if (ssrc.attribute === 'msid') {
  538. ssrcs.push(ssrc.id);
  539. }
  540. });
  541. }
  542. if (video.ssrcGroups.find(group => group.semantics === SSRC_GROUP_SEMANTICS.SIM)) {
  543. // Group already exists, no need to do anything
  544. return desc;
  545. }
  546. // Add a SIM group for every 3 FID groups.
  547. for (let i = 0; i < ssrcs.length; i += 3) {
  548. const simSsrcs = ssrcs.slice(i, i + 3);
  549. video.ssrcGroups.push({
  550. semantics: SSRC_GROUP_SEMANTICS.SIM,
  551. ssrcs: simSsrcs.join(' ')
  552. });
  553. }
  554. }
  555. return {
  556. type: desc.type,
  557. sdp: transform.write(sdp)
  558. };
  559. }
  560. /**
  561. * Takes in a *unified plan* offer and inserts the appropriate parameters for adding simulcast receive support.
  562. * @param {Object} desc - A session description object
  563. * @param {String} desc.type - the type (offer/answer)
  564. * @param {String} desc.sdp - the sdp content
  565. *
  566. * @return {Object} A session description (same format as above) object with its sdp field modified to advertise
  567. * simulcast receive support.
  568. */
  569. insertUnifiedPlanSimulcastReceive(desc) {
  570. // a=simulcast line is not needed on browsers where we SDP munging is used for enabling on simulcast.
  571. // Remove this check when the client switches to RID/MID based simulcast on all browsers.
  572. if (browser.usesSdpMungingForSimulcast()) {
  573. return desc;
  574. }
  575. const rids = [
  576. {
  577. id: SIM_LAYERS[0].rid,
  578. direction: 'recv'
  579. },
  580. {
  581. id: SIM_LAYERS[1].rid,
  582. direction: 'recv'
  583. },
  584. {
  585. id: SIM_LAYERS[2].rid,
  586. direction: 'recv'
  587. }
  588. ];
  589. const ridLine = rids.map(val => val.id).join(';');
  590. const simulcastLine = `recv ${ridLine}`;
  591. const sdp = transform.parse(desc.sdp);
  592. const mLines = sdp.media.filter(m => m.type === MediaType.VIDEO);
  593. const senderMids = Array.from(this.pc.localTrackTransceiverMids.values());
  594. mLines.forEach((mLine, idx) => {
  595. // Make sure the simulcast recv line is only set on video descriptions that are associated with senders.
  596. if (senderMids.find(sender => mLine.mid.toString() === sender.toString()) || idx === 0) {
  597. if (!mLine.simulcast_03 || !mLine.simulcast) {
  598. mLine.rids = rids;
  599. // eslint-disable-next-line camelcase
  600. mLine.simulcast_03 = {
  601. value: simulcastLine
  602. };
  603. }
  604. } else {
  605. mLine.rids = undefined;
  606. mLine.simulcast = undefined;
  607. // eslint-disable-next-line camelcase
  608. mLine.simulcast_03 = undefined;
  609. }
  610. });
  611. return {
  612. type: desc.type,
  613. sdp: transform.write(sdp)
  614. };
  615. }
  616. /**
  617. * Returns a boolean indicating whether the video encoder is running in Simulcast mode, i.e., three encodings need
  618. * to be configured in 4:2:1 resolution order with temporal scalability.
  619. *
  620. * @param {CodecMimeType} videoCodec - The video codec in use.
  621. * @returns {boolean}
  622. */
  623. isRunningInSimulcastMode(videoCodec) {
  624. if (!this.codecSettings || !this.codecSettings[videoCodec]) {
  625. // If codec settings are not available, assume no simulcast
  626. return false;
  627. }
  628. return videoCodec === CodecMimeType.VP8 // VP8 always
  629. // For FF: scalabilityModeEnabled is not supported and we have to use simulcast.
  630. // For other browsers we use K-SVC mode for VP9 when no scalability mode is set. Although
  631. // only one outbound-rtp stream is present, three separate encodings have to be configured.
  632. || (!this.codecSettings[videoCodec].scalabilityModeEnabled && videoCodec === CodecMimeType.VP9)
  633. // FF uses simulcast with AV1.
  634. || (!this.codecSettings[videoCodec].scalabilityModeEnabled
  635. && this.codecSettings[videoCodec].useSimulcast
  636. && videoCodec === CodecMimeType.AV1)
  637. // When scalability is enabled, always for H.264, and only when simulcast is explicitly enabled via
  638. // config.js for VP9 and AV1 since full SVC is the default mode for these 2 codecs.
  639. || (this.codecSettings[videoCodec].scalabilityModeEnabled
  640. && (videoCodec === CodecMimeType.H264 || this.codecSettings[videoCodec].useSimulcast));
  641. }
  642. /**
  643. * Munges the session description to ensure that the codec order is as per the preferred codec settings.
  644. *
  645. * @param {transform.SessionDescription} parsedSdp that needs to be munged
  646. * @returns {transform.SessionDescription} the munged SDP.
  647. */
  648. mungeCodecOrder(parsedSdp) {
  649. const codecSettings = this.pc.codecSettings;
  650. if (!codecSettings) {
  651. return parsedSdp;
  652. }
  653. const mungedSdp = parsedSdp;
  654. const { isP2P } = this.options;
  655. const mLines = mungedSdp.media.filter(m => m.type === codecSettings.mediaType);
  656. for (const mLine of mLines) {
  657. const currentCodecs = this._getConfiguredVideoCodecsImpl(mungedSdp);
  658. for (const codec of currentCodecs) {
  659. if (isP2P) {
  660. // 1. Strip the high profile H264 codecs on all clients. macOS started offering encoder for H.264
  661. // level 5.2 but a decoder only for level 3.1. Therfore, strip all main and high level codecs for
  662. // H.264.
  663. // 2. There are multiple VP9 payload types generated by the browser, more payload types are added
  664. // if the endpoint doesn't have a local video source. Therefore, strip all the high profile codec
  665. // variants for VP9 so that only one payload type for VP9 is negotiated between the peers.
  666. if (codec === CodecMimeType.H264 || codec === CodecMimeType.VP9) {
  667. SDPUtil.stripCodec(mLine, codec, true /* high profile */);
  668. }
  669. // Do not negotiate ULPFEC and RED either.
  670. if (codec === CodecMimeType.ULPFEC || codec === CodecMimeType.RED) {
  671. SDPUtil.stripCodec(mLine, codec, false);
  672. }
  673. }
  674. }
  675. // Reorder the codecs based on the preferred settings.
  676. if (!this.pc.usesCodecSelectionAPI()) {
  677. for (const codec of codecSettings.codecList.slice().reverse()) {
  678. SDPUtil.preferCodec(mLine, codec, isP2P);
  679. }
  680. }
  681. }
  682. return mungedSdp;
  683. }
  684. /**
  685. * Munges the stereo flag as well as the opusMaxAverageBitrate in the SDP, based on values set through config.js,
  686. * if present.
  687. *
  688. * @param {transform.SessionDescription} parsedSdp that needs to be munged.
  689. * @returns {transform.SessionDescription} the munged SDP.
  690. */
  691. mungeOpus(parsedSdp) {
  692. const { audioQuality } = this.options;
  693. if (!audioQuality?.enableOpusDtx && !audioQuality?.stereo && !audioQuality?.opusMaxAverageBitrate) {
  694. return parsedSdp;
  695. }
  696. const mungedSdp = parsedSdp;
  697. const mLines = mungedSdp.media.filter(m => m.type === MediaType.AUDIO);
  698. for (const mLine of mLines) {
  699. const { payload } = mLine.rtp.find(protocol => protocol.codec === CodecMimeType.OPUS);
  700. if (!payload) {
  701. // eslint-disable-next-line no-continue
  702. continue;
  703. }
  704. let fmtpOpus = mLine.fmtp.find(protocol => protocol.payload === payload);
  705. if (!fmtpOpus) {
  706. fmtpOpus = {
  707. payload,
  708. config: ''
  709. };
  710. }
  711. const fmtpConfig = transform.parseParams(fmtpOpus.config);
  712. let sdpChanged = false;
  713. if (audioQuality?.stereo) {
  714. fmtpConfig.stereo = 1;
  715. sdpChanged = true;
  716. }
  717. if (audioQuality?.opusMaxAverageBitrate) {
  718. fmtpConfig.maxaveragebitrate = audioQuality.opusMaxAverageBitrate;
  719. sdpChanged = true;
  720. }
  721. // On Firefox, the OpusDtx enablement has no effect
  722. if (!browser.isFirefox() && audioQuality?.enableOpusDtx) {
  723. fmtpConfig.usedtx = 1;
  724. sdpChanged = true;
  725. }
  726. if (!sdpChanged) {
  727. // eslint-disable-next-line no-continue
  728. continue;
  729. }
  730. let mungedConfig = '';
  731. for (const key of Object.keys(fmtpConfig)) {
  732. mungedConfig += `${key}=${fmtpConfig[key]}; `;
  733. }
  734. fmtpOpus.config = mungedConfig.trim();
  735. }
  736. return mungedSdp;
  737. }
  738. /**
  739. * Munges the session SDP by setting the max bitrates on the video m-lines when VP9 K-SVC codec is in use.
  740. *
  741. * @param {transform.SessionDescription} parsedSdp that needs to be munged.
  742. * @param {boolean} isLocalSdp - Whether the max bitrate (via b=AS line in SDP) is set on local SDP.
  743. * @returns {transform.SessionDescription} The munged SDP.
  744. */
  745. setMaxBitrates(parsedSdp, isLocalSdp = false) {
  746. const pcCodecSettings = this.pc.codecSettings;
  747. if (!pcCodecSettings) {
  748. return parsedSdp;
  749. }
  750. // Find all the m-lines associated with the local sources.
  751. const mungedSdp = parsedSdp;
  752. const direction = isLocalSdp ? MediaDirection.RECVONLY : MediaDirection.SENDONLY;
  753. const mLines = mungedSdp.media.filter(m => m.type === MediaType.VIDEO && m.direction !== direction);
  754. const currentCodec = pcCodecSettings.codecList[0];
  755. const codecScalabilityModeSettings = this.codecSettings[currentCodec];
  756. for (const mLine of mLines) {
  757. const isDoingVp9KSvc = currentCodec === CodecMimeType.VP9
  758. && !codecScalabilityModeSettings.scalabilityModeEnabled;
  759. const localTrack = this.pc.getLocalVideoTracks()
  760. .find(track => this.pc.localTrackTransceiverMids.get(track.rtcId) === mLine.mid.toString());
  761. if (localTrack
  762. && (isDoingVp9KSvc
  763. // Setting bitrates in the SDP for SVC codecs is no longer needed in the newer versions where
  764. // maxBitrates from the RTCRtpEncodingParameters directly affect the target bitrate for the encoder.
  765. || (this._isRunningInFullSvcMode(currentCodec) && !this.pc.usesCodecSelectionAPI()))) {
  766. let maxBitrate;
  767. if (localTrack.getVideoType() === VideoType.DESKTOP) {
  768. maxBitrate = codecScalabilityModeSettings.maxBitratesVideo.ssHigh;
  769. } else {
  770. const { level } = VIDEO_QUALITY_LEVELS.find(lvl => lvl.height <= localTrack.getCaptureResolution());
  771. maxBitrate = codecScalabilityModeSettings.maxBitratesVideo[level];
  772. }
  773. const limit = Math.floor(maxBitrate / 1000);
  774. // Use only the highest spatial layer bitrates for now as there is no API available yet for configuring
  775. // the bitrates on the individual SVC layers.
  776. mLine.bandwidth = [ {
  777. type: 'AS',
  778. limit
  779. } ];
  780. } else {
  781. // Clear the bandwidth limit in SDP when VP9 is no longer the preferred codec.
  782. // This is needed on react native clients as react-native-webrtc returns the
  783. // SDP that the application passed instead of returning the SDP off the native side.
  784. // This line automatically gets cleared on web on every renegotiation.
  785. mLine.bandwidth = undefined;
  786. }
  787. }
  788. return mungedSdp;
  789. }
  790. }