Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

TPCUtils.js 39KB

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