Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

TPCUtils.js 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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 { getSourceIndexFromSourceName } from '../../service/RTC/SignalingLayer';
  8. import {
  9. SIM_LAYERS,
  10. STANDARD_CODEC_SETTINGS,
  11. VIDEO_QUALITY_LEVELS,
  12. VIDEO_QUALITY_SETTINGS
  13. } from '../../service/RTC/StandardVideoQualitySettings';
  14. import { VideoEncoderScalabilityMode } from '../../service/RTC/VideoEncoderScalabilityMode';
  15. import { VideoType } from '../../service/RTC/VideoType';
  16. import browser from '../browser';
  17. const logger = getLogger(__filename);
  18. const VIDEO_CODECS = [ CodecMimeType.AV1, CodecMimeType.H264, CodecMimeType.VP8, CodecMimeType.VP9 ];
  19. /**
  20. * Handles track related operations on TraceablePeerConnection when browser is
  21. * running in unified plan mode.
  22. */
  23. export class TPCUtils {
  24. /**
  25. * Creates a new instance for a given TraceablePeerConnection
  26. *
  27. * @param peerconnection - the tpc instance for which we have utility functions.
  28. */
  29. constructor(peerconnection) {
  30. this.pc = peerconnection;
  31. this.codecSettings = cloneDeep(STANDARD_CODEC_SETTINGS);
  32. const videoQualitySettings = this.pc.options?.videoQuality;
  33. if (videoQualitySettings) {
  34. for (const codec of VIDEO_CODECS) {
  35. const codecConfig = videoQualitySettings[codec];
  36. const bitrateSettings = codecConfig?.maxBitratesVideo
  37. // Read the deprecated settings for max bitrates.
  38. ?? (videoQualitySettings.maxbitratesvideo
  39. && videoQualitySettings.maxbitratesvideo[codec.toUpperCase()]);
  40. if (bitrateSettings) {
  41. const settings = Object.values(VIDEO_QUALITY_SETTINGS);
  42. [ ...settings, 'ssHigh' ].forEach(value => {
  43. if (bitrateSettings[value]) {
  44. this.codecSettings[codec].maxBitratesVideo[value] = bitrateSettings[value];
  45. }
  46. });
  47. }
  48. if (!codecConfig) {
  49. continue; // eslint-disable-line no-continue
  50. }
  51. const scalabilityModeEnabled = this.codecSettings[codec].scalabilityModeEnabled
  52. && (typeof codecConfig.scalabilityModeEnabled === 'undefined'
  53. || codecConfig.scalabilityModeEnabled);
  54. if (scalabilityModeEnabled) {
  55. typeof codecConfig.useSimulcast !== 'undefined'
  56. && (this.codecSettings[codec].useSimulcast = codecConfig.useSimulcast);
  57. typeof codecConfig.useKSVC !== 'undefined'
  58. && (this.codecSettings[codec].useKSVC = codecConfig.useKSVC);
  59. } else {
  60. this.codecSettings[codec].scalabilityModeEnabled = false;
  61. }
  62. }
  63. }
  64. }
  65. /**
  66. * Calculates the configuration of the active encoding when the browser sends only one stream, i,e,, when there is
  67. * no spatial scalability configure (p2p) or when it is running in full SVC mode.
  68. *
  69. * @param {JitsiLocalTrack} localVideoTrack - The local video track.
  70. * @param {CodecMimeType} codec - The video codec.
  71. * @param {number} newHeight - The resolution that needs to be configured for the local video track.
  72. * @returns {Object} configuration.
  73. */
  74. _calculateActiveEncodingParams(localVideoTrack, codec, newHeight) {
  75. const codecBitrates = this.codecSettings[codec].maxBitratesVideo;
  76. const trackCaptureHeight = localVideoTrack.getCaptureResolution();
  77. const effectiveNewHeight = newHeight > trackCaptureHeight ? trackCaptureHeight : newHeight;
  78. const desktopShareBitrate = this.pc.options?.videoQuality?.desktopbitrate || codecBitrates.ssHigh;
  79. const isScreenshare = localVideoTrack.getVideoType() === VideoType.DESKTOP;
  80. let scalabilityMode = this.codecSettings[codec].useKSVC
  81. ? VideoEncoderScalabilityMode.L3T3_KEY : VideoEncoderScalabilityMode.L3T3;
  82. const { height, level } = VIDEO_QUALITY_LEVELS.find(lvl => lvl.height <= effectiveNewHeight);
  83. let maxBitrate;
  84. let scaleResolutionDownBy = SIM_LAYERS[2].scaleFactor;
  85. if (this._isScreenshareBitrateCapped(localVideoTrack)) {
  86. scalabilityMode = VideoEncoderScalabilityMode.L1T3;
  87. maxBitrate = desktopShareBitrate;
  88. } else if (isScreenshare) {
  89. maxBitrate = codecBitrates.ssHigh;
  90. } else {
  91. maxBitrate = codecBitrates[level];
  92. effectiveNewHeight && (scaleResolutionDownBy = trackCaptureHeight / effectiveNewHeight);
  93. if (height !== effectiveNewHeight) {
  94. logger.debug(`Quality level with height=${height} was picked when requested height=${newHeight} for`
  95. + `track with capture height=${trackCaptureHeight}`);
  96. }
  97. }
  98. const config = {
  99. active: effectiveNewHeight > 0,
  100. maxBitrate,
  101. scalabilityMode,
  102. scaleResolutionDownBy
  103. };
  104. if (!config.active || isScreenshare) {
  105. return config;
  106. }
  107. // Configure the sender to send all 3 spatial layers for resolutions 720p and higher.
  108. switch (level) {
  109. case VIDEO_QUALITY_SETTINGS.ULTRA:
  110. case VIDEO_QUALITY_SETTINGS.FULL:
  111. case VIDEO_QUALITY_SETTINGS.HIGH:
  112. config.scalabilityMode = this.codecSettings[codec].useKSVC
  113. ? VideoEncoderScalabilityMode.L3T3_KEY : VideoEncoderScalabilityMode.L3T3;
  114. break;
  115. case VIDEO_QUALITY_SETTINGS.STANDARD:
  116. config.scalabilityMode = this.codecSettings[codec].useKSVC
  117. ? VideoEncoderScalabilityMode.L2T3_KEY : VideoEncoderScalabilityMode.L2T3;
  118. break;
  119. default:
  120. config.scalabilityMode = VideoEncoderScalabilityMode.L1T3;
  121. }
  122. return config;
  123. }
  124. /**
  125. * Configures the RTCRtpEncodingParameters of the outbound rtp stream associated with the given track.
  126. *
  127. * @param {JitsiLocalTracj} localTrack - The local track whose outbound stream needs to be configured.
  128. * @returns {Promise} - A promise that resolves when the operation is successful, rejected otherwise.
  129. */
  130. _configureSenderEncodings(localTrack) {
  131. const mediaType = localTrack.getType();
  132. const transceiver = localTrack?.track && localTrack.getOriginalStream()
  133. ? this.pc.peerconnection.getTransceivers().find(t => t.sender?.track?.id === localTrack.getTrackId())
  134. : this.pc.peerconnection.getTransceivers().find(t => t.receiver?.track?.kind === mediaType);
  135. const parameters = transceiver?.sender?.getParameters();
  136. // Resolve if the encodings are not available yet. This happens immediately after the track is added to the
  137. // peerconnection on chrome in unified-plan. It is ok to ignore and not report the error here since the
  138. // action that triggers 'addTrack' (like unmute) will also configure the encodings and set bitrates after that.
  139. if (!parameters?.encodings?.length) {
  140. return Promise.resolve();
  141. }
  142. parameters.encodings = this._getStreamEncodings(localTrack);
  143. return transceiver.sender.setParameters(parameters);
  144. }
  145. /**
  146. * Enables/disables the streams by changing the active field on RTCRtpEncodingParameters for a given RTCRtpSender.
  147. *
  148. * @param {RTCRtpSender} sender - the sender associated with a MediaStreamTrack.
  149. * @param {boolean} enable - whether the streams needs to be enabled or disabled.
  150. * @returns {Promise} - A promise that resolves when the operation is successful, rejected otherwise.
  151. */
  152. _enableSenderEncodings(sender, enable) {
  153. const parameters = sender.getParameters();
  154. if (parameters?.encodings?.length) {
  155. for (const encoding of parameters.encodings) {
  156. encoding.active = enable;
  157. }
  158. }
  159. return sender.setParameters(parameters);
  160. }
  161. /**
  162. * Obtains stream encodings that need to be configured on the given track based
  163. * on the track media type and the simulcast setting.
  164. * @param {JitsiLocalTrack} localTrack
  165. */
  166. _getStreamEncodings(localTrack) {
  167. if (localTrack.isAudioTrack()) {
  168. return [ { active: this.pc.audioTransferActive } ];
  169. }
  170. const codec = this.pc.getConfiguredVideoCodec(localTrack);
  171. if (this.pc.isSpatialScalabilityOn()) {
  172. return this._getVideoStreamEncodings(localTrack, codec);
  173. }
  174. return [ {
  175. active: this.pc.videoTransferActive,
  176. maxBitrate: this.codecSettings[codec].maxBitratesVideo.high
  177. } ];
  178. }
  179. /**
  180. * The startup configuration for the stream encodings that are applicable to
  181. * the video stream when a new sender is created on the peerconnection. The initial
  182. * config takes into account the differences in browser's simulcast implementation.
  183. *
  184. * Encoding parameters:
  185. * active - determine the on/off state of a particular encoding.
  186. * maxBitrate - max. bitrate value to be applied to that particular encoding
  187. * based on the encoding's resolution and config.js videoQuality settings if applicable.
  188. * rid - Rtp Stream ID that is configured for a particular simulcast stream.
  189. * scaleResolutionDownBy - the factor by which the encoding is scaled down from the
  190. * original resolution of the captured video.
  191. *
  192. * @param {JitsiLocalTrack} localTrack
  193. * @param {String} codec
  194. */
  195. _getVideoStreamEncodings(localTrack, codec) {
  196. const captureResolution = localTrack.getCaptureResolution();
  197. const codecBitrates = this.codecSettings[codec].maxBitratesVideo;
  198. const videoType = localTrack.getVideoType();
  199. let effectiveScaleFactors = SIM_LAYERS.map(sim => sim.scaleFactor);
  200. let cameraMaxbitrate;
  201. if (videoType === VideoType.CAMERA) {
  202. const { level } = VIDEO_QUALITY_LEVELS.find(lvl => lvl.height <= captureResolution);
  203. cameraMaxbitrate = codecBitrates[level];
  204. if (level === VIDEO_QUALITY_SETTINGS.ULTRA) {
  205. effectiveScaleFactors[1] = 6.0; // 360p
  206. effectiveScaleFactors[0] = 12.0; // 180p
  207. } else if (level === VIDEO_QUALITY_SETTINGS.FULL) {
  208. effectiveScaleFactors[1] = 3.0; // 360p
  209. effectiveScaleFactors[0] = 6.0; // 180p
  210. }
  211. }
  212. const maxBitrate = videoType === VideoType.DESKTOP
  213. ? codecBitrates.ssHigh : cameraMaxbitrate;
  214. let effectiveBitrates = [ codecBitrates.low, codecBitrates.standard, maxBitrate ];
  215. // The SSRCs on older versions of Firefox are reversed in SDP, i.e., they have resolution order of 1:2:4 as
  216. // opposed to Chromium and other browsers. This has been reverted in Firefox 117 as part of the below commit.
  217. // https://hg.mozilla.org/mozilla-central/rev/b0348f1f8d7197fb87158ba74542d28d46133997
  218. // This revert seems to be applied only to camera tracks, the desktop stream encodings still have the
  219. // resolution order of 4:2:1.
  220. if (browser.isFirefox() && (videoType === VideoType.DESKTOP || browser.isVersionLessThan(117))) {
  221. effectiveBitrates = effectiveBitrates.reverse();
  222. effectiveScaleFactors = effectiveScaleFactors.reverse();
  223. }
  224. const standardSimulcastEncodings = [
  225. {
  226. active: this.pc.videoTransferActive,
  227. maxBitrate: effectiveBitrates[0],
  228. rid: SIM_LAYERS[0].rid,
  229. scaleResolutionDownBy: effectiveScaleFactors[0]
  230. },
  231. {
  232. active: this.pc.videoTransferActive,
  233. maxBitrate: effectiveBitrates[1],
  234. rid: SIM_LAYERS[1].rid,
  235. scaleResolutionDownBy: effectiveScaleFactors[1]
  236. },
  237. {
  238. active: this.pc.videoTransferActive,
  239. maxBitrate: effectiveBitrates[2],
  240. rid: SIM_LAYERS[2].rid,
  241. scaleResolutionDownBy: effectiveScaleFactors[2]
  242. }
  243. ];
  244. if (this.codecSettings[codec].scalabilityModeEnabled) {
  245. // Configure all 3 encodings when simulcast is requested through config.js for AV1 and VP9 and for H.264
  246. // always since that is the only supported mode when DD header extension is negotiated for H.264.
  247. if (this.codecSettings[codec].useSimulcast || codec === CodecMimeType.H264) {
  248. for (const encoding of standardSimulcastEncodings) {
  249. encoding.scalabilityMode = VideoEncoderScalabilityMode.L1T3;
  250. }
  251. return standardSimulcastEncodings;
  252. }
  253. // Configure only one encoding for the SVC mode.
  254. return [
  255. {
  256. active: this.pc.videoTransferActive,
  257. maxBitrate: effectiveBitrates[2],
  258. rid: SIM_LAYERS[0].rid,
  259. scaleResolutionDownBy: effectiveScaleFactors[2],
  260. scalabilityMode: this.codecSettings[codec].useKSVC
  261. ? VideoEncoderScalabilityMode.L3T3_KEY : VideoEncoderScalabilityMode.L3T3
  262. },
  263. {
  264. active: false,
  265. maxBitrate: 0
  266. },
  267. {
  268. active: false,
  269. maxBitrate: 0
  270. }
  271. ];
  272. }
  273. return standardSimulcastEncodings;
  274. }
  275. /**
  276. * Returns a boolean indicating whether the video encoder is running in full SVC mode, i.e., it sends only one
  277. * video stream that has both temporal and spatial scalability.
  278. *
  279. * @param {CodecMimeType} codec
  280. * @returns boolean
  281. */
  282. _isRunningInFullSvcMode(codec) {
  283. return (codec === CodecMimeType.VP9 || codec === CodecMimeType.AV1)
  284. && this.codecSettings[codec].scalabilityModeEnabled
  285. && !this.codecSettings[codec].useSimulcast;
  286. }
  287. /**
  288. * Returns a boolean indicating whether the bitrate needs to be capped for the local video track if it happens to
  289. * be a screenshare track. The lower spatial layers for screensharing are disabled when low fps screensharing is in
  290. * progress. Sending all three streams often results in the browser suspending the high resolution in low b/w and
  291. * and low cpu conditions, especially on the low end machines. Suspending the low resolution streams ensures that
  292. * the highest resolution stream is available always. Safari is an exception here since it does not send the
  293. * desktop stream at all if only the high resolution stream is enabled.
  294. *
  295. * @param {JitsiLocalTrack} localVideoTrack - The local video track.
  296. * @returns {boolean}
  297. */
  298. _isScreenshareBitrateCapped(localVideoTrack) {
  299. return localVideoTrack.getVideoType() === VideoType.DESKTOP
  300. && this.pc._capScreenshareBitrate
  301. && !browser.isWebKitBased();
  302. }
  303. /**
  304. * Updates the sender parameters in the stream encodings.
  305. *
  306. * @param {RTCRtpSender} sender - the sender associated with a MediaStreamTrack.
  307. * @param {boolean} enable - whether the streams needs to be enabled or disabled.
  308. * @returns {Promise} - A promise that resolves when the operation is successful, rejected otherwise.
  309. */
  310. _updateSenderEncodings(sender, enable) {
  311. const parameters = sender.getParameters();
  312. if (parameters?.encodings?.length) {
  313. for (const encoding of parameters.encodings) {
  314. encoding.active = enable;
  315. }
  316. }
  317. return sender.setParameters(parameters);
  318. }
  319. /**
  320. * Adds {@link JitsiLocalTrack} to the WebRTC peerconnection for the first time.
  321. *
  322. * @param {JitsiLocalTrack} track - track to be added to the peerconnection.
  323. * @param {boolean} isInitiator - boolean that indicates if the endpoint is offerer in a p2p connection.
  324. * @returns {RTCRtpTransceiver} - the transceiver that the track was added to.
  325. */
  326. addTrack(localTrack, isInitiator) {
  327. const track = localTrack.getTrack();
  328. let transceiver;
  329. if (isInitiator) {
  330. const streams = [];
  331. if (localTrack.getOriginalStream()) {
  332. streams.push(localTrack.getOriginalStream());
  333. }
  334. // Use pc.addTransceiver() for the initiator case when local tracks are getting added
  335. // to the peerconnection before a session-initiate is sent over to the peer.
  336. const transceiverInit = {
  337. direction: MediaDirection.SENDRECV,
  338. streams,
  339. sendEncodings: []
  340. };
  341. if (!browser.isFirefox()) {
  342. transceiverInit.sendEncodings = this._getStreamEncodings(localTrack);
  343. }
  344. transceiver = this.pc.peerconnection.addTransceiver(track, transceiverInit);
  345. } else {
  346. // Use pc.addTrack() for responder case so that we can re-use the m-lines that were created
  347. // when setRemoteDescription was called. pc.addTrack() automatically attaches to any existing
  348. // unused "recv-only" transceiver.
  349. const sender = this.pc.peerconnection.addTrack(track);
  350. // Find the corresponding transceiver that the track was attached to.
  351. transceiver = this.pc.peerconnection.getTransceivers().find(t => t.sender === sender);
  352. }
  353. return transceiver;
  354. }
  355. /**
  356. * Returns the calculated active state of the stream encodings based on the frame height requested for the send
  357. * stream. All the encodings that have a resolution lower than the frame height requested will be enabled.
  358. *
  359. * @param {JitsiLocalTrack} localVideoTrack The local video track.
  360. * @param {CodecMimeType} codec - The codec currently in use.
  361. * @param {number} newHeight The resolution requested for the video track.
  362. * @returns {Array<boolean>}
  363. */
  364. calculateEncodingsActiveState(localVideoTrack, codec, newHeight) {
  365. const height = localVideoTrack.getCaptureResolution();
  366. const videoStreamEncodings = this._getVideoStreamEncodings(localVideoTrack, codec);
  367. const encodingsState = videoStreamEncodings
  368. .map(encoding => height / encoding.scaleResolutionDownBy)
  369. .map((frameHeight, idx) => {
  370. let activeState = false;
  371. // When video is suspended on the media session.
  372. if (!this.pc.videoTransferActive) {
  373. return activeState;
  374. }
  375. // Single video stream.
  376. if (!this.pc.isSpatialScalabilityOn() || this._isRunningInFullSvcMode(codec)) {
  377. const { active } = this._calculateActiveEncodingParams(localVideoTrack, codec, newHeight);
  378. return idx === 0 ? active : activeState;
  379. }
  380. if (newHeight > 0) {
  381. if (localVideoTrack.getVideoType() === VideoType.CAMERA) {
  382. activeState = frameHeight <= newHeight
  383. // Keep the LD stream enabled even when the LD stream's resolution is higher than of the
  384. // requested resolution. This can happen when camera is captured at high resolutions like 4k
  385. // but the requested resolution is 180. Since getParameters doesn't give us information about
  386. // the resolutions of the simulcast encodings, we have to rely on our initial config for the
  387. // simulcast streams.
  388. || videoStreamEncodings[idx]?.scaleResolutionDownBy === SIM_LAYERS[0].scaleFactor;
  389. } else {
  390. // For screenshare, keep the HD layer enabled always and the lower layers only for high fps
  391. // screensharing.
  392. activeState = videoStreamEncodings[idx].scaleResolutionDownBy === SIM_LAYERS[2].scaleFactor
  393. || !this._isScreenshareBitrateCapped(localVideoTrack);
  394. }
  395. }
  396. return activeState;
  397. });
  398. return encodingsState;
  399. }
  400. /**
  401. * Returns the calculated max bitrates that need to be configured on the stream encodings based on the video
  402. * type and other considerations associated with screenshare.
  403. *
  404. * @param {JitsiLocalTrack} localVideoTrack The local video track.
  405. * @param {CodecMimeType} codec - The codec currently in use.
  406. * @param {number} newHeight The resolution requested for the video track.
  407. * @returns {Array<number>}
  408. */
  409. calculateEncodingsBitrates(localVideoTrack, codec, newHeight) {
  410. const codecBitrates = this.codecSettings[codec].maxBitratesVideo;
  411. const desktopShareBitrate = this.pc.options?.videoQuality?.desktopbitrate || codecBitrates.ssHigh;
  412. const encodingsBitrates = this._getVideoStreamEncodings(localVideoTrack, codec)
  413. .map((encoding, idx) => {
  414. let bitrate = encoding.maxBitrate;
  415. // Single video stream.
  416. if (!this.pc.isSpatialScalabilityOn() || this._isRunningInFullSvcMode(codec)) {
  417. const { maxBitrate } = this._calculateActiveEncodingParams(localVideoTrack, codec, newHeight);
  418. return idx === 0 ? maxBitrate : 0;
  419. }
  420. // Multiple video streams.
  421. if (this._isScreenshareBitrateCapped(localVideoTrack)) {
  422. bitrate = desktopShareBitrate;
  423. }
  424. return bitrate;
  425. });
  426. return encodingsBitrates;
  427. }
  428. /**
  429. * Returns the calculated scalability modes for the video encodings when scalability modes are supported.
  430. *
  431. * @param {JitsiLocalTrack} localVideoTrack The local video track.
  432. * @param {CodecMimeType} codec - The codec currently in use.
  433. * @param {number} maxHeight The resolution requested for the video track.
  434. * @returns {Array<VideoEncoderScalabilityMode> | undefined}
  435. */
  436. calculateEncodingsScalabilityMode(localVideoTrack, codec, maxHeight) {
  437. if (!this.pc.isSpatialScalabilityOn() || !this.codecSettings[codec].scalabilityModeEnabled) {
  438. return;
  439. }
  440. // Default modes for simulcast.
  441. const scalabilityModes = [
  442. VideoEncoderScalabilityMode.L1T3,
  443. VideoEncoderScalabilityMode.L1T3,
  444. VideoEncoderScalabilityMode.L1T3
  445. ];
  446. // Full SVC mode.
  447. if (this._isRunningInFullSvcMode(codec)) {
  448. const { scalabilityMode }
  449. = this._calculateActiveEncodingParams(localVideoTrack, codec, maxHeight);
  450. scalabilityModes[0] = scalabilityMode;
  451. scalabilityModes[1] = undefined;
  452. scalabilityModes[2] = undefined;
  453. return scalabilityModes;
  454. }
  455. return scalabilityModes;
  456. }
  457. /**
  458. * Returns the scale factor that needs to be applied on the local video stream based on the desired resolution
  459. * and the codec in use.
  460. *
  461. * @param {JitsiLocalTrack} localVideoTrack The local video track.
  462. * @param {CodecMimeType} codec - The codec currently in use.
  463. * @param {number} maxHeight The resolution requested for the video track.
  464. * @returns {Array<float>}
  465. */
  466. calculateEncodingsScaleFactor(localVideoTrack, codec, maxHeight) {
  467. if (this.pc.isSpatialScalabilityOn() && this.isRunningInSimulcastMode(codec)) {
  468. return this._getVideoStreamEncodings(localVideoTrack, codec)
  469. .map(encoding => encoding.scaleResolutionDownBy);
  470. }
  471. // Single video stream.
  472. const { scaleResolutionDownBy }
  473. = this._calculateActiveEncodingParams(localVideoTrack, codec, maxHeight);
  474. return [ scaleResolutionDownBy, undefined, undefined ];
  475. }
  476. /**
  477. * Ensures that the ssrcs associated with a FID ssrc-group appear in the correct order, i.e.,
  478. * the primary ssrc first and the secondary rtx ssrc later. This is important for unified
  479. * plan since we have only one FID group per media description.
  480. * @param {Object} description the webRTC session description instance for the remote
  481. * description.
  482. * @private
  483. */
  484. ensureCorrectOrderOfSsrcs(description) {
  485. const parsedSdp = transform.parse(description.sdp);
  486. parsedSdp.media.forEach(mLine => {
  487. if (mLine.type === MediaType.AUDIO) {
  488. return;
  489. }
  490. if (!mLine.ssrcGroups || !mLine.ssrcGroups.length) {
  491. return;
  492. }
  493. let reorderedSsrcs = [];
  494. const ssrcs = new Set();
  495. mLine.ssrcGroups.map(group =>
  496. group.ssrcs
  497. .split(' ')
  498. .filter(Boolean)
  499. .forEach(ssrc => ssrcs.add(ssrc))
  500. );
  501. ssrcs.forEach(ssrc => {
  502. const sources = mLine.ssrcs.filter(source => source.id.toString() === ssrc);
  503. reorderedSsrcs = reorderedSsrcs.concat(sources);
  504. });
  505. mLine.ssrcs = reorderedSsrcs;
  506. });
  507. return new RTCSessionDescription({
  508. type: description.type,
  509. sdp: transform.write(parsedSdp)
  510. });
  511. }
  512. /**
  513. * Takes in a *unified plan* offer and inserts the appropriate parameters for adding simulcast receive support.
  514. * @param {Object} desc - A session description object
  515. * @param {String} desc.type - the type (offer/answer)
  516. * @param {String} desc.sdp - the sdp content
  517. *
  518. * @return {Object} A session description (same format as above) object with its sdp field modified to advertise
  519. * simulcast receive support.
  520. */
  521. insertUnifiedPlanSimulcastReceive(desc) {
  522. // a=simulcast line is not needed on browsers where we SDP munging is used for enabling on simulcast.
  523. // Remove this check when the client switches to RID/MID based simulcast on all browsers.
  524. if (browser.usesSdpMungingForSimulcast()) {
  525. return desc;
  526. }
  527. const rids = [
  528. {
  529. id: SIM_LAYERS[0].rid,
  530. direction: 'recv'
  531. },
  532. {
  533. id: SIM_LAYERS[1].rid,
  534. direction: 'recv'
  535. },
  536. {
  537. id: SIM_LAYERS[2].rid,
  538. direction: 'recv'
  539. }
  540. ];
  541. const ridLine = rids.map(val => val.id).join(';');
  542. const simulcastLine = `recv ${ridLine}`;
  543. const sdp = transform.parse(desc.sdp);
  544. const mLines = sdp.media.filter(m => m.type === MediaType.VIDEO);
  545. const senderMids = Array.from(this.pc._localTrackTransceiverMids.values());
  546. mLines.forEach((mLine, idx) => {
  547. // Make sure the simulcast recv line is only set on video descriptions that are associated with senders.
  548. if (senderMids.find(sender => mLine.mid.toString() === sender.toString()) || idx === 0) {
  549. if (!mLine.simulcast_03 || !mLine.simulcast) {
  550. mLine.rids = rids;
  551. // eslint-disable-next-line camelcase
  552. mLine.simulcast_03 = {
  553. value: simulcastLine
  554. };
  555. }
  556. } else {
  557. mLine.rids = undefined;
  558. mLine.simulcast = undefined;
  559. // eslint-disable-next-line camelcase
  560. mLine.simulcast_03 = undefined;
  561. }
  562. });
  563. return new RTCSessionDescription({
  564. type: desc.type,
  565. sdp: transform.write(sdp)
  566. });
  567. }
  568. /**
  569. * Returns a boolean indicating whether the video encoder is running in Simulcast mode, i.e., three encodings need
  570. * to be configured in 4:2:1 resolution order with temporal scalability.
  571. *
  572. * @param {CodecMimeType} codec - The video codec in use.
  573. * @returns {boolean}
  574. */
  575. isRunningInSimulcastMode(codec) {
  576. return codec === CodecMimeType.VP8 // VP8 always
  577. // K-SVC mode for VP9 when no scalability mode is set. Though only one outbound-rtp stream is present,
  578. // three separate encodings have to be configured.
  579. || (!this.codecSettings[codec].scalabilityModeEnabled && codec === CodecMimeType.VP9)
  580. // When scalability is enabled, always for H.264, and only when simulcast is explicitly enabled via
  581. // config.js for VP9 and AV1 since full SVC is the default mode for these 2 codecs.
  582. || (this.codecSettings[codec].scalabilityModeEnabled
  583. && (codec === CodecMimeType.H264 || this.codecSettings[codec].useSimulcast));
  584. }
  585. /**
  586. * Replaces the existing track on a RTCRtpSender with the given track.
  587. *
  588. * @param {JitsiLocalTrack} oldTrack - existing track on the sender that needs to be removed.
  589. * @param {JitsiLocalTrack} newTrack - new track that needs to be added to the sender.
  590. * @returns {Promise<RTCRtpTransceiver>} - resolved with the associated transceiver when done, rejected otherwise.
  591. */
  592. replaceTrack(oldTrack, newTrack) {
  593. const mediaType = newTrack?.getType() ?? oldTrack?.getType();
  594. const localTracks = this.pc.getLocalTracks(mediaType);
  595. const track = newTrack?.getTrack() ?? null;
  596. const isNewLocalSource = localTracks?.length
  597. && !oldTrack
  598. && newTrack
  599. && !localTracks.find(t => t === newTrack);
  600. let transceiver;
  601. // If old track exists, replace the track on the corresponding sender.
  602. if (oldTrack && !oldTrack.isMuted()) {
  603. transceiver = this.pc.peerconnection.getTransceivers().find(t => t.sender.track === oldTrack.getTrack());
  604. // Find the first recvonly transceiver when more than one track of the same media type is being added to the pc.
  605. // As part of the track addition, a new m-line was added to the remote description with direction set to
  606. // recvonly.
  607. } else if (isNewLocalSource) {
  608. transceiver = this.pc.peerconnection.getTransceivers().find(
  609. t => t.receiver.track.kind === mediaType
  610. && t.direction === MediaDirection.RECVONLY
  611. // Re-use any existing recvonly transceiver (if available) for p2p case.
  612. && ((this.pc.isP2P && t.currentDirection === MediaDirection.RECVONLY)
  613. || (t.currentDirection === MediaDirection.INACTIVE && !t.stopped)));
  614. // For mute/unmute operations, find the transceiver based on the track index in the source name if present,
  615. // otherwise it is assumed to be the first local track that was added to the peerconnection.
  616. } else {
  617. transceiver = this.pc.peerconnection.getTransceivers().find(t => t.receiver.track.kind === mediaType);
  618. const sourceName = newTrack?.getSourceName() ?? oldTrack?.getSourceName();
  619. if (sourceName) {
  620. const trackIndex = getSourceIndexFromSourceName(sourceName);
  621. if (this.pc.isP2P) {
  622. transceiver = this.pc.peerconnection.getTransceivers()
  623. .filter(t => t.receiver.track.kind === mediaType)[trackIndex];
  624. } else if (oldTrack) {
  625. const transceiverMid = this.pc._localTrackTransceiverMids.get(oldTrack.rtcId);
  626. transceiver = this.pc.peerconnection.getTransceivers().find(t => t.mid === transceiverMid);
  627. } else if (trackIndex) {
  628. transceiver = this.pc.peerconnection.getTransceivers()
  629. .filter(t => t.receiver.track.kind === mediaType
  630. && t.direction !== MediaDirection.RECVONLY)[trackIndex];
  631. }
  632. }
  633. }
  634. if (!transceiver) {
  635. return Promise.reject(
  636. new Error(`Replace track failed - no transceiver for old: ${oldTrack}, new: ${newTrack}`));
  637. }
  638. logger.debug(`${this.pc} Replacing ${oldTrack} with ${newTrack}`);
  639. return transceiver.sender.replaceTrack(track)
  640. .then(() => Promise.resolve(transceiver));
  641. }
  642. /**
  643. * Set the simulcast stream encoding properties on the RTCRtpSender.
  644. *
  645. * @param {JitsiLocalTrack} localTrack - the current track in use for which the encodings are to be set.
  646. * @returns {Promise<void>} - resolved when done.
  647. */
  648. setEncodings(localTrack) {
  649. if (localTrack.getType() === MediaType.VIDEO) {
  650. return this.pc._updateVideoSenderParameters(() => this._configureSenderEncodings(localTrack));
  651. }
  652. return this._configureSenderEncodings(localTrack);
  653. }
  654. /**
  655. * Resumes or suspends media on the peerconnection by setting the active state on RTCRtpEncodingParameters
  656. * associated with all the senders that have a track attached to it.
  657. *
  658. * @param {boolean} enable - whether outgoing media needs to be enabled or disabled.
  659. * @param {string} mediaType - media type, 'audio' or 'video', if neither is passed, all outgoing media will either
  660. * be enabled or disabled.
  661. * @returns {Promise} - A promise that is resolved when the change is succesful on all the senders, rejected
  662. * otherwise.
  663. */
  664. setMediaTransferActive(enable, mediaType) {
  665. logger.info(`${this.pc} ${enable ? 'Resuming' : 'Suspending'} media transfer.`);
  666. const senders = this.pc.peerconnection.getSenders()
  667. .filter(s => Boolean(s.track) && (!mediaType || s.track.kind === mediaType));
  668. const promises = [];
  669. for (const sender of senders) {
  670. if (sender.track.kind === MediaType.VIDEO) {
  671. promises.push(this.pc._updateVideoSenderParameters(() => this._enableSenderEncodings(sender, enable)));
  672. } else {
  673. promises.push(this._enableSenderEncodings(sender, enable));
  674. }
  675. }
  676. return Promise.allSettled(promises)
  677. .then(settledResult => {
  678. const errors = settledResult
  679. .filter(result => result.status === 'rejected')
  680. .map(result => result.reason);
  681. if (errors.length) {
  682. return Promise.reject(new Error('Failed to change encodings on the RTCRtpSenders'
  683. + `${errors.join(' ')}`));
  684. }
  685. return Promise.resolve();
  686. });
  687. }
  688. }