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

TPCUtils.js 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  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.codecSettings[codec].scalabilityModeEnabled) {
  367. return;
  368. }
  369. // Use LIT3 for P2P wherever its supported.
  370. if (!this.pc.isSpatialScalabilityOn()) {
  371. return [ VideoEncoderScalabilityMode.L1T3 ];
  372. }
  373. // Default modes for simulcast.
  374. const scalabilityModes = [
  375. VideoEncoderScalabilityMode.L1T3,
  376. VideoEncoderScalabilityMode.L1T3,
  377. VideoEncoderScalabilityMode.L1T3
  378. ];
  379. // Full SVC mode.
  380. if (this._isRunningInFullSvcMode(codec)) {
  381. const { scalabilityMode }
  382. = this._calculateActiveEncodingParams(localVideoTrack, codec, maxHeight);
  383. scalabilityModes[0] = scalabilityMode;
  384. scalabilityModes[1] = undefined;
  385. scalabilityModes[2] = undefined;
  386. return scalabilityModes;
  387. }
  388. return scalabilityModes;
  389. }
  390. /**
  391. * Returns the scale factor that needs to be applied on the local video stream based on the desired resolution
  392. * and the codec in use.
  393. *
  394. * @param {JitsiLocalTrack} localVideoTrack The local video track.
  395. * @param {CodecMimeType} codec - The codec currently in use.
  396. * @param {number} maxHeight The resolution requested for the video track.
  397. * @returns {Array<float>}
  398. */
  399. calculateEncodingsScaleFactor(localVideoTrack, codec, maxHeight) {
  400. if (this.pc.isSpatialScalabilityOn() && this.isRunningInSimulcastMode(codec)) {
  401. return this._getVideoStreamEncodings(localVideoTrack, codec)
  402. .map(encoding => encoding.scaleResolutionDownBy);
  403. }
  404. // Single video stream.
  405. const { scaleResolutionDownBy }
  406. = this._calculateActiveEncodingParams(localVideoTrack, codec, maxHeight);
  407. return [ scaleResolutionDownBy, undefined, undefined ];
  408. }
  409. /**
  410. * Ensures that the ssrcs associated with a FID ssrc-group appear in the correct order, i.e., the primary ssrc
  411. * first and the secondary rtx ssrc later. This is important for unified plan since we have only one FID group per
  412. * media description.
  413. * @param {Object} description the webRTC session description instance for the remote description.
  414. * @returns {Object} the modified webRTC session description instance.
  415. */
  416. ensureCorrectOrderOfSsrcs(description) {
  417. const parsedSdp = transform.parse(description.sdp);
  418. parsedSdp.media.forEach(mLine => {
  419. if (mLine.type === MediaType.AUDIO) {
  420. return;
  421. }
  422. if (!mLine.ssrcGroups || !mLine.ssrcGroups.length) {
  423. return;
  424. }
  425. let reorderedSsrcs = [];
  426. const ssrcs = new Set();
  427. mLine.ssrcGroups.map(group =>
  428. group.ssrcs
  429. .split(' ')
  430. .filter(Boolean)
  431. .forEach(ssrc => ssrcs.add(ssrc))
  432. );
  433. ssrcs.forEach(ssrc => {
  434. const sources = mLine.ssrcs.filter(source => source.id.toString() === ssrc);
  435. reorderedSsrcs = reorderedSsrcs.concat(sources);
  436. });
  437. mLine.ssrcs = reorderedSsrcs;
  438. });
  439. return {
  440. type: description.type,
  441. sdp: transform.write(parsedSdp)
  442. };
  443. }
  444. /**
  445. * Returns the codec that is configured on the client as the preferred video codec for the given local video track.
  446. *
  447. * @param {JitsiLocalTrack} localTrack - The local video track.
  448. * @returns {CodecMimeType} The codec that is set as the preferred codec for the given local video track.
  449. */
  450. getConfiguredVideoCodec(localTrack) {
  451. const localVideoTrack = localTrack ?? this.pc.getLocalVideoTracks()[0];
  452. const rtpSender = this.pc.findSenderForTrack(localVideoTrack.getTrack());
  453. if (this.pc.usesCodecSelectionAPI() && rtpSender) {
  454. const { encodings } = rtpSender.getParameters();
  455. if (encodings[0].codec) {
  456. return encodings[0].codec.mimeType.split('/')[1].toLowerCase();
  457. }
  458. }
  459. const sdp = this.pc.remoteDescription?.sdp;
  460. if (!sdp) {
  461. return CodecMimeType.VP8;
  462. }
  463. const parsedSdp = transform.parse(sdp);
  464. const mLine = parsedSdp.media
  465. .find(m => m.mid.toString() === this.pc.localTrackTransceiverMids.get(localVideoTrack.rtcId));
  466. const payload = mLine.payloads.split(' ')[0];
  467. const { codec } = mLine.rtp.find(rtp => rtp.payload === Number(payload));
  468. if (codec) {
  469. return Object.values(CodecMimeType).find(value => value === codec.toLowerCase());
  470. }
  471. return CodecMimeType.VP8;
  472. }
  473. /**
  474. * Returns the codecs in the current order of preference as configured on the peerconnection.
  475. *
  476. * @param {string} - The local SDP to be used.
  477. * @returns {Array}
  478. */
  479. getConfiguredVideoCodecs(sdp) {
  480. const currentSdp = sdp ?? this.pc.localDescription?.sdp;
  481. if (!currentSdp) {
  482. return [];
  483. }
  484. const parsedSdp = transform.parse(currentSdp);
  485. return this._getConfiguredVideoCodecsImpl(parsedSdp);
  486. }
  487. /**
  488. * Returns the desired media direction for the given media type based on the current state of the peerconnection.
  489. *
  490. * @param {MediaType} mediaType - The media type for which the desired media direction is to be obtained.
  491. * @param {boolean} isAddOperation - Whether the direction is being set for a source add operation.
  492. * @returns {MediaDirection} - The desired media direction for the given media type.
  493. */
  494. getDesiredMediaDirection(mediaType, isAddOperation = false) {
  495. const hasLocalSource = this.pc.getLocalTracks(mediaType).length > 0;
  496. if (isAddOperation) {
  497. return hasLocalSource ? MediaDirection.SENDRECV : MediaDirection.SENDONLY;
  498. }
  499. return hasLocalSource ? MediaDirection.RECVONLY : MediaDirection.INACTIVE;
  500. }
  501. /**
  502. * Obtains stream encodings that need to be configured on the given track based
  503. * on the track media type and the simulcast setting.
  504. * @param {JitsiLocalTrack} localTrack
  505. */
  506. getStreamEncodings(localTrack) {
  507. if (localTrack.isAudioTrack()) {
  508. return [ { active: this.pc.audioTransferActive } ];
  509. }
  510. const codec = this.getConfiguredVideoCodec(localTrack);
  511. if (this.pc.isSpatialScalabilityOn()) {
  512. return this._getVideoStreamEncodings(localTrack, codec);
  513. }
  514. return [ {
  515. active: this.pc.videoTransferActive,
  516. maxBitrate: this.codecSettings[codec].maxBitratesVideo.high
  517. } ];
  518. }
  519. /**
  520. * Injects a 'SIM' ssrc-group line for simulcast into the given session description object to make Jicofo happy.
  521. * This is needed only for Firefox since it does not generate it when simulcast is enabled but we run the check
  522. * on all browsers just in case as it would break the functionality otherwise.
  523. *
  524. * @param desc A session description object (with 'type' and 'sdp' fields)
  525. * @return A session description object with its sdp field modified to contain an inject ssrc-group for simulcast.
  526. */
  527. injectSsrcGroupForSimulcast(desc) {
  528. const sdp = transform.parse(desc.sdp);
  529. const video = sdp.media.find(mline => mline.type === 'video');
  530. // Check if the browser supports RTX, add only the primary ssrcs to the SIM group if that is the case.
  531. video.ssrcGroups = video.ssrcGroups || [];
  532. const fidGroups = video.ssrcGroups.filter(group => group.semantics === SSRC_GROUP_SEMANTICS.FID);
  533. if (video.simulcast || video.simulcast_03) {
  534. const ssrcs = [];
  535. if (fidGroups && fidGroups.length) {
  536. fidGroups.forEach(group => {
  537. ssrcs.push(group.ssrcs.split(' ')[0]);
  538. });
  539. } else {
  540. video.ssrcs.forEach(ssrc => {
  541. if (ssrc.attribute === 'msid') {
  542. ssrcs.push(ssrc.id);
  543. }
  544. });
  545. }
  546. if (video.ssrcGroups.find(group => group.semantics === SSRC_GROUP_SEMANTICS.SIM)) {
  547. // Group already exists, no need to do anything
  548. return desc;
  549. }
  550. // Add a SIM group for every 3 FID groups.
  551. for (let i = 0; i < ssrcs.length; i += 3) {
  552. const simSsrcs = ssrcs.slice(i, i + 3);
  553. video.ssrcGroups.push({
  554. semantics: SSRC_GROUP_SEMANTICS.SIM,
  555. ssrcs: simSsrcs.join(' ')
  556. });
  557. }
  558. }
  559. return {
  560. type: desc.type,
  561. sdp: transform.write(sdp)
  562. };
  563. }
  564. /**
  565. * Takes in a *unified plan* offer and inserts the appropriate parameters for adding simulcast receive support.
  566. * @param {Object} desc - A session description object
  567. * @param {String} desc.type - the type (offer/answer)
  568. * @param {String} desc.sdp - the sdp content
  569. *
  570. * @return {Object} A session description (same format as above) object with its sdp field modified to advertise
  571. * simulcast receive support.
  572. */
  573. insertUnifiedPlanSimulcastReceive(desc) {
  574. // a=simulcast line is not needed on browsers where we SDP munging is used for enabling on simulcast.
  575. // Remove this check when the client switches to RID/MID based simulcast on all browsers.
  576. if (browser.usesSdpMungingForSimulcast()) {
  577. return desc;
  578. }
  579. const rids = [
  580. {
  581. id: SIM_LAYERS[0].rid,
  582. direction: 'recv'
  583. },
  584. {
  585. id: SIM_LAYERS[1].rid,
  586. direction: 'recv'
  587. },
  588. {
  589. id: SIM_LAYERS[2].rid,
  590. direction: 'recv'
  591. }
  592. ];
  593. const ridLine = rids.map(val => val.id).join(';');
  594. const simulcastLine = `recv ${ridLine}`;
  595. const sdp = transform.parse(desc.sdp);
  596. const mLines = sdp.media.filter(m => m.type === MediaType.VIDEO);
  597. const senderMids = Array.from(this.pc.localTrackTransceiverMids.values());
  598. mLines.forEach((mLine, idx) => {
  599. // Make sure the simulcast recv line is only set on video descriptions that are associated with senders.
  600. if (senderMids.find(sender => mLine.mid.toString() === sender.toString()) || idx === 0) {
  601. if (!mLine.simulcast_03 || !mLine.simulcast) {
  602. mLine.rids = rids;
  603. // eslint-disable-next-line camelcase
  604. mLine.simulcast_03 = {
  605. value: simulcastLine
  606. };
  607. }
  608. } else {
  609. mLine.rids = undefined;
  610. mLine.simulcast = undefined;
  611. // eslint-disable-next-line camelcase
  612. mLine.simulcast_03 = undefined;
  613. }
  614. });
  615. return {
  616. type: desc.type,
  617. sdp: transform.write(sdp)
  618. };
  619. }
  620. /**
  621. * Returns a boolean indicating whether the video encoder is running in Simulcast mode, i.e., three encodings need
  622. * to be configured in 4:2:1 resolution order with temporal scalability.
  623. *
  624. * @param {CodecMimeType} videoCodec - The video codec in use.
  625. * @returns {boolean}
  626. */
  627. isRunningInSimulcastMode(videoCodec) {
  628. if (!this.codecSettings || !this.codecSettings[videoCodec]) {
  629. // If codec settings are not available, assume no simulcast
  630. return false;
  631. }
  632. return videoCodec === CodecMimeType.VP8 // VP8 always
  633. // For FF: scalabilityModeEnabled is not supported and we have to use simulcast.
  634. // For other browsers we use K-SVC mode for VP9 when no scalability mode is set. Although
  635. // only one outbound-rtp stream is present, three separate encodings have to be configured.
  636. || (!this.codecSettings[videoCodec].scalabilityModeEnabled && videoCodec === CodecMimeType.VP9)
  637. // FF uses simulcast with AV1.
  638. || (!this.codecSettings[videoCodec].scalabilityModeEnabled
  639. && this.codecSettings[videoCodec].useSimulcast
  640. && videoCodec === CodecMimeType.AV1)
  641. // When scalability is enabled, always for H.264, and only when simulcast is explicitly enabled via
  642. // config.js for VP9 and AV1 since full SVC is the default mode for these 2 codecs.
  643. || (this.codecSettings[videoCodec].scalabilityModeEnabled
  644. && (videoCodec === CodecMimeType.H264 || this.codecSettings[videoCodec].useSimulcast));
  645. }
  646. /**
  647. * Munges the session description to ensure that the codec order is as per the preferred codec settings.
  648. *
  649. * @param {transform.SessionDescription} parsedSdp that needs to be munged
  650. * @returns {transform.SessionDescription} the munged SDP.
  651. */
  652. mungeCodecOrder(parsedSdp) {
  653. const codecSettings = this.pc.codecSettings;
  654. if (!codecSettings) {
  655. return parsedSdp;
  656. }
  657. const mungedSdp = parsedSdp;
  658. const { isP2P } = this.options;
  659. const mLines = mungedSdp.media.filter(m => m.type === codecSettings.mediaType);
  660. for (const mLine of mLines) {
  661. const currentCodecs = this._getConfiguredVideoCodecsImpl(mungedSdp);
  662. for (const codec of currentCodecs) {
  663. if (isP2P) {
  664. // 1. Strip the high profile H264 codecs on all clients. macOS started offering encoder for H.264
  665. // level 5.2 but a decoder only for level 3.1. Therfore, strip all main and high level codecs for
  666. // H.264.
  667. // 2. There are multiple VP9 payload types generated by the browser, more payload types are added
  668. // if the endpoint doesn't have a local video source. Therefore, strip all the high profile codec
  669. // variants for VP9 so that only one payload type for VP9 is negotiated between the peers.
  670. if (codec === CodecMimeType.H264 || codec === CodecMimeType.VP9) {
  671. SDPUtil.stripCodec(mLine, codec, true /* high profile */);
  672. }
  673. // Do not negotiate ULPFEC and RED either.
  674. if (codec === CodecMimeType.ULPFEC || codec === CodecMimeType.RED) {
  675. SDPUtil.stripCodec(mLine, codec, false);
  676. }
  677. }
  678. }
  679. // Reorder the codecs based on the preferred settings.
  680. if (!this.pc.usesCodecSelectionAPI()) {
  681. for (const codec of codecSettings.codecList.slice().reverse()) {
  682. SDPUtil.preferCodec(mLine, codec, isP2P);
  683. }
  684. }
  685. }
  686. return mungedSdp;
  687. }
  688. /**
  689. * Munges the stereo flag as well as the opusMaxAverageBitrate in the SDP, based on values set through config.js,
  690. * if present.
  691. *
  692. * @param {transform.SessionDescription} parsedSdp that needs to be munged.
  693. * @returns {transform.SessionDescription} the munged SDP.
  694. */
  695. mungeOpus(parsedSdp) {
  696. const { audioQuality } = this.options;
  697. if (!audioQuality?.enableOpusDtx && !audioQuality?.stereo && !audioQuality?.opusMaxAverageBitrate) {
  698. return parsedSdp;
  699. }
  700. const mungedSdp = parsedSdp;
  701. const mLines = mungedSdp.media.filter(m => m.type === MediaType.AUDIO);
  702. for (const mLine of mLines) {
  703. const { payload } = mLine.rtp.find(protocol => protocol.codec === CodecMimeType.OPUS);
  704. if (!payload) {
  705. // eslint-disable-next-line no-continue
  706. continue;
  707. }
  708. let fmtpOpus = mLine.fmtp.find(protocol => protocol.payload === payload);
  709. if (!fmtpOpus) {
  710. fmtpOpus = {
  711. payload,
  712. config: ''
  713. };
  714. }
  715. const fmtpConfig = transform.parseParams(fmtpOpus.config);
  716. let sdpChanged = false;
  717. if (audioQuality?.stereo) {
  718. fmtpConfig.stereo = 1;
  719. sdpChanged = true;
  720. }
  721. if (audioQuality?.opusMaxAverageBitrate) {
  722. fmtpConfig.maxaveragebitrate = audioQuality.opusMaxAverageBitrate;
  723. sdpChanged = true;
  724. }
  725. // On Firefox, the OpusDtx enablement has no effect
  726. if (!browser.isFirefox() && audioQuality?.enableOpusDtx) {
  727. fmtpConfig.usedtx = 1;
  728. sdpChanged = true;
  729. }
  730. if (!sdpChanged) {
  731. // eslint-disable-next-line no-continue
  732. continue;
  733. }
  734. let mungedConfig = '';
  735. for (const key of Object.keys(fmtpConfig)) {
  736. mungedConfig += `${key}=${fmtpConfig[key]}; `;
  737. }
  738. fmtpOpus.config = mungedConfig.trim();
  739. }
  740. return mungedSdp;
  741. }
  742. /**
  743. * Munges the session SDP by setting the max bitrates on the video m-lines when VP9 K-SVC codec is in use.
  744. *
  745. * @param {transform.SessionDescription} parsedSdp that needs to be munged.
  746. * @param {boolean} isLocalSdp - Whether the max bitrate (via b=AS line in SDP) is set on local SDP.
  747. * @returns {transform.SessionDescription} The munged SDP.
  748. */
  749. setMaxBitrates(parsedSdp, isLocalSdp = false) {
  750. const pcCodecSettings = this.pc.codecSettings;
  751. if (!pcCodecSettings) {
  752. return parsedSdp;
  753. }
  754. // Find all the m-lines associated with the local sources.
  755. const mungedSdp = parsedSdp;
  756. const direction = isLocalSdp ? MediaDirection.RECVONLY : MediaDirection.SENDONLY;
  757. const mLines = mungedSdp.media.filter(m => m.type === MediaType.VIDEO && m.direction !== direction);
  758. const currentCodec = pcCodecSettings.codecList[0];
  759. const codecScalabilityModeSettings = this.codecSettings[currentCodec];
  760. for (const mLine of mLines) {
  761. const isDoingVp9KSvc = currentCodec === CodecMimeType.VP9
  762. && !codecScalabilityModeSettings.scalabilityModeEnabled;
  763. const localTrack = this.pc.getLocalVideoTracks()
  764. .find(track => this.pc.localTrackTransceiverMids.get(track.rtcId) === mLine.mid.toString());
  765. if (localTrack
  766. && (isDoingVp9KSvc
  767. // Setting bitrates in the SDP for SVC codecs is no longer needed in the newer versions where
  768. // maxBitrates from the RTCRtpEncodingParameters directly affect the target bitrate for the encoder.
  769. || (this._isRunningInFullSvcMode(currentCodec) && !this.pc.usesCodecSelectionAPI()))) {
  770. let maxBitrate;
  771. if (localTrack.getVideoType() === VideoType.DESKTOP) {
  772. maxBitrate = codecScalabilityModeSettings.maxBitratesVideo.ssHigh;
  773. } else {
  774. const { level } = VIDEO_QUALITY_LEVELS.find(lvl => lvl.height <= localTrack.getCaptureResolution());
  775. maxBitrate = codecScalabilityModeSettings.maxBitratesVideo[level];
  776. }
  777. const limit = Math.floor(maxBitrate / 1000);
  778. // Use only the highest spatial layer bitrates for now as there is no API available yet for configuring
  779. // the bitrates on the individual SVC layers.
  780. mLine.bandwidth = [ {
  781. type: 'AS',
  782. limit
  783. } ];
  784. } else {
  785. // Clear the bandwidth limit in SDP when VP9 is no longer the preferred codec.
  786. // This is needed on react native clients as react-native-webrtc returns the
  787. // SDP that the application passed instead of returning the SDP off the native side.
  788. // This line automatically gets cleared on web on every renegotiation.
  789. mLine.bandwidth = undefined;
  790. }
  791. }
  792. return mungedSdp;
  793. }
  794. }