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

TPCUtils.js 40KB

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