You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TraceablePeerConnection.js 99KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734
  1. import { getLogger } from '@jitsi/logger';
  2. import { Interop } from '@jitsi/sdp-interop';
  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 RTCEvents from '../../service/RTC/RTCEvents';
  8. import * as SignalingEvents from '../../service/RTC/SignalingEvents';
  9. import { getSourceIndexFromSourceName } from '../../service/RTC/SignalingLayer';
  10. import { VIDEO_QUALITY_LEVELS } from '../../service/RTC/StandardVideoQualitySettings';
  11. import { VideoType } from '../../service/RTC/VideoType';
  12. import { VIDEO_CODEC_CHANGED } from '../../service/statistics/AnalyticsEvents';
  13. import { SS_DEFAULT_FRAME_RATE } from '../RTC/ScreenObtainer';
  14. import browser from '../browser';
  15. import FeatureFlags from '../flags/FeatureFlags';
  16. import LocalSdpMunger from '../sdp/LocalSdpMunger';
  17. import RtxModifier from '../sdp/RtxModifier';
  18. import SDP from '../sdp/SDP';
  19. import SDPUtil from '../sdp/SDPUtil';
  20. import SdpSimulcast from '../sdp/SdpSimulcast';
  21. import { SdpTransformWrap } from '../sdp/SdpTransformUtil';
  22. import Statistics from '../statistics/statistics';
  23. import JitsiRemoteTrack from './JitsiRemoteTrack';
  24. import RTCUtils from './RTCUtils';
  25. import { TPCUtils } from './TPCUtils';
  26. // FIXME SDP tools should end up in some kind of util module
  27. const logger = getLogger(__filename);
  28. const DEGRADATION_PREFERENCE_CAMERA = 'maintain-framerate';
  29. const DEGRADATION_PREFERENCE_DESKTOP = 'maintain-resolution';
  30. const DD_HEADER_EXT_URI
  31. = 'https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension';
  32. const DD_HEADER_EXT_ID = 11;
  33. /* eslint-disable max-params */
  34. /**
  35. * Creates new instance of 'TraceablePeerConnection'.
  36. *
  37. * @param {RTC} rtc the instance of <tt>RTC</tt> service
  38. * @param {number} id the peer connection id assigned by the parent RTC module.
  39. * @param {SignalingLayer} signalingLayer the signaling layer instance
  40. * @param {object} pcConfig The {@code RTCConfiguration} to use for the WebRTC peer connection.
  41. * @param {object} constraints WebRTC 'PeerConnection' constraints
  42. * @param {boolean} isP2P indicates whether or not the new instance will be used in a peer to peer connection.
  43. * @param {object} options <tt>TracablePeerConnection</tt> config options.
  44. * @param {Object} options.audioQuality - Quality settings to applied on the outbound audio stream.
  45. * @param {boolean} options.capScreenshareBitrate if set to true, lower layers will be disabled for screenshare.
  46. * @param {Array<CodecMimeType>} options.codecSettings - codec settings to be applied for video streams.
  47. * @param {boolean} options.disableSimulcast if set to 'true' will disable the simulcast.
  48. * @param {boolean} options.disableRtx if set to 'true' will disable the RTX.
  49. * @param {boolean} options.enableInsertableStreams set to true when the insertable streams constraints is to be
  50. * enabled on the PeerConnection.
  51. * @param {boolean} options.forceTurnRelay If set to true, the browser will generate only Relay ICE candidates.
  52. * @param {boolean} options.startSilent If set to 'true' no audio will be sent or received.
  53. * @param {Object} options.videoQuality - Quality settings to applied on the outbound video streams.
  54. *
  55. * FIXME: initially the purpose of TraceablePeerConnection was to be able to
  56. * debug the peer connection. Since many other responsibilities have been added
  57. * it would make sense to extract a separate class from it and come up with
  58. * a more suitable name.
  59. *
  60. * @constructor
  61. */
  62. export default function TraceablePeerConnection(
  63. rtc,
  64. id,
  65. signalingLayer,
  66. pcConfig,
  67. constraints,
  68. isP2P,
  69. options) {
  70. /**
  71. * Indicates whether or not this peer connection instance is actively
  72. * sending/receiving audio media. When set to <tt>false</tt> the SDP audio
  73. * media direction will be adjusted to 'inactive' in order to suspend
  74. * the transmission.
  75. * @type {boolean}
  76. * @private
  77. */
  78. this.audioTransferActive = !(options.startSilent === true);
  79. /**
  80. * The DTMF sender instance used to send DTMF tones.
  81. *
  82. * @type {RTCDTMFSender|undefined}
  83. * @private
  84. */
  85. this._dtmfSender = undefined;
  86. /**
  87. * @typedef {Object} TouchToneRequest
  88. * @property {string} tones - The DTMF tones string as defined by
  89. * {@code RTCDTMFSender.insertDTMF}, 'tones' argument.
  90. * @property {number} duration - The amount of time in milliseconds that
  91. * each DTMF should last.
  92. * @property {string} interToneGap - The length of time in miliseconds to
  93. * wait between tones.
  94. */
  95. /**
  96. * TouchToneRequests which are waiting to be played. This queue is filled
  97. * if there are touch tones currently being played.
  98. *
  99. * @type {Array<TouchToneRequest>}
  100. * @private
  101. */
  102. this._dtmfTonesQueue = [];
  103. /**
  104. * Indicates whether or not this peer connection instance is actively
  105. * sending/receiving video media. When set to <tt>false</tt> the SDP video
  106. * media direction will be adjusted to 'inactive' in order to suspend
  107. * the transmission.
  108. * @type {boolean}
  109. * @private
  110. */
  111. this.videoTransferActive = true;
  112. /**
  113. * The parent instance of RTC service which created this
  114. * <tt>TracablePeerConnection</tt>.
  115. * @type {RTC}
  116. */
  117. this.rtc = rtc;
  118. /**
  119. * The peer connection identifier assigned by the RTC module.
  120. * @type {number}
  121. */
  122. this.id = id;
  123. /**
  124. * Indicates whether or not this instance is used in a peer to peer
  125. * connection.
  126. * @type {boolean}
  127. */
  128. this.isP2P = isP2P;
  129. /**
  130. * A map that holds remote tracks signaled on the peerconnection indexed by their SSRC.
  131. * @type {Map<number, JitsiRemoteTrack>}
  132. */
  133. this.remoteTracksBySsrc = new Map();
  134. /**
  135. * The map holds remote tracks associated with this peer connection. It maps user's JID to media type and a set of
  136. * remote tracks.
  137. * @type {Map<string, Map<MediaType, Set<JitsiRemoteTrack>>>}
  138. */
  139. this.remoteTracks = new Map();
  140. /**
  141. * A map which stores local tracks mapped by {@link JitsiLocalTrack.rtcId}
  142. * @type {Map<number, JitsiLocalTrack>}
  143. */
  144. this.localTracks = new Map();
  145. /**
  146. * @typedef {Object} TPCGroupInfo
  147. * @property {string} semantics the SSRC groups semantics
  148. * @property {Array<number>} ssrcs group's SSRCs in order where the first
  149. * one is group's primary SSRC, the second one is secondary (RTX) and so
  150. * on...
  151. */
  152. /**
  153. * @typedef {Object} TPCSSRCInfo
  154. * @property {Array<number>} ssrcs an array which holds all track's SSRCs
  155. * @property {Array<TPCGroupInfo>} groups an array stores all track's SSRC
  156. * groups
  157. */
  158. /**
  159. * Holds the info about local track's SSRCs mapped per their
  160. * {@link JitsiLocalTrack.rtcId}
  161. * @type {Map<number, TPCSSRCInfo>}
  162. */
  163. this.localSSRCs = new Map();
  164. /**
  165. * The set of remote SSRCs seen so far.
  166. * Distinguishes new SSRCs from those that have been remapped.
  167. * @type {Set<number>}
  168. */
  169. this.remoteSSRCs = new Set();
  170. /**
  171. * Mapping of source-names and their associated SSRCs that have been signaled by the JVB.
  172. * @type {Map<string, number>}
  173. */
  174. this.remoteSources = new Map();
  175. /**
  176. * The local ICE username fragment for this session.
  177. */
  178. this.localUfrag = null;
  179. /**
  180. * The remote ICE username fragment for this session.
  181. */
  182. this.remoteUfrag = null;
  183. /**
  184. * The DTLS transport object for the PeerConnection.
  185. * Note: this assume only one shared transport exists because we bundled
  186. * all streams on the same underlying transport.
  187. */
  188. this._dtlsTransport = null;
  189. /**
  190. * The signaling layer which operates this peer connection.
  191. * @type {SignalingLayer}
  192. */
  193. this.signalingLayer = signalingLayer;
  194. // SignalingLayer listeners
  195. this._peerVideoTypeChanged = this._peerVideoTypeChanged.bind(this);
  196. this.signalingLayer.on(SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  197. this._peerMutedChanged = this._peerMutedChanged.bind(this);
  198. this.signalingLayer.on(SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  199. this.options = options;
  200. // Setup SignalingLayer listeners for source-name based events.
  201. this.signalingLayer.on(SignalingEvents.SOURCE_MUTED_CHANGED,
  202. (sourceName, isMuted) => this._sourceMutedChanged(sourceName, isMuted));
  203. this.signalingLayer.on(SignalingEvents.SOURCE_VIDEO_TYPE_CHANGED,
  204. (sourceName, videoType) => this._sourceVideoTypeChanged(sourceName, videoType));
  205. // Make sure constraints is properly formatted in order to provide information about whether or not this
  206. // connection is P2P to rtcstats.
  207. const safeConstraints = constraints || {};
  208. safeConstraints.optional = safeConstraints.optional || [];
  209. // The `optional` parameter needs to be of type array, otherwise chrome will throw an error.
  210. // Firefox and Safari just ignore it.
  211. if (Array.isArray(safeConstraints.optional)) {
  212. safeConstraints.optional.push({ rtcStatsSFUP2P: this.isP2P });
  213. } else {
  214. logger.warn('Optional param is not an array, rtcstats p2p data is omitted.');
  215. }
  216. this.peerconnection = new RTCPeerConnection(pcConfig, safeConstraints);
  217. this.tpcUtils = new TPCUtils(this);
  218. this.updateLog = [];
  219. this.stats = {};
  220. this.statsinterval = null;
  221. /**
  222. * Flag used to indicate if low fps screenshare is desired.
  223. */
  224. this._capScreenshareBitrate = this.options.capScreenshareBitrate;
  225. /**
  226. * Codec preferences set for the peerconnection through config.js.
  227. */
  228. this.codecSettings = this.options.codecSettings;
  229. /**
  230. * Flag used to indicate if RTCRtpTransceiver#setCodecPreferences is to be used instead of SDP
  231. * munging for codec selection.
  232. */
  233. browser.supportsCodecPreferences()
  234. && logger.info('Using RTCRtpTransceiver#setCodecPreferences for codec selection');
  235. /**
  236. * Flag used to indicate if the codecs are configured using the codec selection API without having the need to
  237. * trigger a renegotiation for the change to be effective.
  238. */
  239. this._usesCodecSelectionAPI = this.options.usesCodecSelectionAPI;
  240. /**
  241. * Indicates whether an audio track has ever been added to the peer connection.
  242. */
  243. this._hasHadAudioTrack = false;
  244. /**
  245. * Indicates whether a video track has ever been added to the peer connection.
  246. */
  247. this._hasHadVideoTrack = false;
  248. /**
  249. * @type {number} The max number of stats to keep in this.stats. Limit to
  250. * 300 values, i.e. 5 minutes; set to 0 to disable
  251. */
  252. this.maxstats = options.maxstats;
  253. this.interop = new Interop();
  254. this.simulcast = new SdpSimulcast();
  255. /**
  256. * Munges local SDP provided to the Jingle Session in order to prevent from
  257. * sending SSRC updates on attach/detach and mute/unmute (for video).
  258. * @type {LocalSdpMunger}
  259. */
  260. this.localSdpMunger = new LocalSdpMunger(this, this.rtc.getLocalEndpointId());
  261. /**
  262. * TracablePeerConnection uses RTC's eventEmitter
  263. * @type {EventEmitter}
  264. */
  265. this.eventEmitter = rtc.eventEmitter;
  266. this.rtxModifier = new RtxModifier();
  267. /**
  268. * The height constraints to be applied on the sender per local video source (source name as the key).
  269. * @type {Map<string, number>}
  270. */
  271. this._senderMaxHeights = new Map();
  272. /**
  273. * Flag indicating bridge support for AV1 codec. On the bridge connection, it is supported only when support for
  274. * Dependency Descriptor header extensions is offered by Jicofo. H.264 simulcast is also possible when these
  275. * header extensions are negotiated.
  276. */
  277. this._supportsDDHeaderExt = false;
  278. /**
  279. * Holds the RTCRtpTransceiver mids that the local tracks are attached to, mapped per their
  280. * {@link JitsiLocalTrack.rtcId}.
  281. * @type {Map<string, string>}
  282. */
  283. this._localTrackTransceiverMids = new Map();
  284. /**
  285. * Holds the SSRC map for the local tracks.
  286. *
  287. * @type {Map<string, TPCSSRCInfo>}
  288. */
  289. this._localSsrcMap = null;
  290. // override as desired
  291. this.trace = (what, info) => {
  292. logger.trace(what, info);
  293. this.updateLog.push({
  294. time: new Date(),
  295. type: what,
  296. value: info || ''
  297. });
  298. };
  299. this.onicecandidate = null;
  300. this.peerconnection.onicecandidate = event => {
  301. this.trace(
  302. 'onicecandidate',
  303. JSON.stringify(event.candidate, null, ' '));
  304. if (this.onicecandidate !== null) {
  305. this.onicecandidate(event);
  306. }
  307. };
  308. this.onTrack = evt => {
  309. const stream = evt.streams[0];
  310. this._remoteTrackAdded(stream, evt.track, evt.transceiver);
  311. stream.addEventListener('removetrack', e => {
  312. this._remoteTrackRemoved(stream, e.track);
  313. });
  314. };
  315. this.peerconnection.addEventListener('track', this.onTrack);
  316. this.onsignalingstatechange = null;
  317. this.peerconnection.onsignalingstatechange = event => {
  318. this.trace('onsignalingstatechange', this.signalingState);
  319. if (this.onsignalingstatechange !== null) {
  320. this.onsignalingstatechange(event);
  321. }
  322. };
  323. this.oniceconnectionstatechange = null;
  324. this.peerconnection.oniceconnectionstatechange = event => {
  325. this.trace('oniceconnectionstatechange', this.iceConnectionState);
  326. if (this.oniceconnectionstatechange !== null) {
  327. this.oniceconnectionstatechange(event);
  328. }
  329. };
  330. this.onnegotiationneeded = null;
  331. this.peerconnection.onnegotiationneeded = event => {
  332. this.trace('onnegotiationneeded');
  333. if (this.onnegotiationneeded !== null) {
  334. this.onnegotiationneeded(event);
  335. }
  336. };
  337. this.onconnectionstatechange = null;
  338. this.peerconnection.onconnectionstatechange = event => {
  339. this.trace('onconnectionstatechange', this.connectionState);
  340. if (this.onconnectionstatechange !== null) {
  341. this.onconnectionstatechange(event);
  342. }
  343. };
  344. this.ondatachannel = null;
  345. this.peerconnection.ondatachannel = event => {
  346. this.trace('ondatachannel');
  347. if (this.ondatachannel !== null) {
  348. this.ondatachannel(event);
  349. }
  350. };
  351. if (this.maxstats) {
  352. this.statsinterval = window.setInterval(() => {
  353. this.getStats().then(stats => {
  354. if (typeof stats?.result === 'function') {
  355. const results = stats.result();
  356. for (let i = 0; i < results.length; ++i) {
  357. const res = results[i];
  358. res.names().forEach(name => {
  359. this._processStat(res, name, res.stat(name));
  360. });
  361. }
  362. } else {
  363. stats.forEach(r => this._processStat(r, '', r));
  364. }
  365. });
  366. }, 1000);
  367. }
  368. this._lastVideoSenderUpdatePromise = Promise.resolve();
  369. logger.info(`Create new ${this}`);
  370. }
  371. /* eslint-enable max-params */
  372. /**
  373. * Process stat and adds it to the array of stats we store.
  374. * @param report the current stats report.
  375. * @param name the name of the report, if available
  376. * @param statValue the value to add.
  377. * @private
  378. */
  379. TraceablePeerConnection.prototype._processStat
  380. = function(report, name, statValue) {
  381. const id = `${report.id}-${name}`;
  382. let s = this.stats[id];
  383. const now = new Date();
  384. if (!s) {
  385. this.stats[id] = s = {
  386. startTime: now,
  387. endTime: now,
  388. values: [],
  389. times: []
  390. };
  391. }
  392. s.values.push(statValue);
  393. s.times.push(now.getTime());
  394. if (s.values.length > this.maxstats) {
  395. s.values.shift();
  396. s.times.shift();
  397. }
  398. s.endTime = now;
  399. };
  400. /**
  401. * Returns a string representation of a SessionDescription object.
  402. */
  403. const dumpSDP = function(description) {
  404. if (typeof description === 'undefined' || description === null) {
  405. return '';
  406. }
  407. return `type: ${description.type}\r\n${description.sdp}`;
  408. };
  409. /**
  410. * Forwards the {@link peerconnection.iceConnectionState} state except that it
  411. * will convert "completed" into "connected" where both mean that the ICE has
  412. * succeeded and is up and running. We never see "completed" state for
  413. * the JVB connection, but it started appearing for the P2P one. This method
  414. * allows to adapt old logic to this new situation.
  415. * @return {string}
  416. */
  417. TraceablePeerConnection.prototype.getConnectionState = function() {
  418. const state = this.peerconnection.iceConnectionState;
  419. if (state === 'completed') {
  420. return 'connected';
  421. }
  422. return state;
  423. };
  424. /**
  425. * Obtains the media direction for given {@link MediaType} that needs to be set on a p2p peerconnection's remote SDP
  426. * after a source-add or source-remove action. The method takes into account whether or not there are any
  427. * local tracks for the given media type.
  428. * @param {MediaType} mediaType
  429. * @param {boolean} isAddOperation whether the direction is to be calculated after a source-add action.
  430. * @return {string} one of the SDP direction constants ('sendrecv, 'recvonly' etc.) which should be used when setting
  431. * local description on the peerconnection.
  432. * @private
  433. */
  434. TraceablePeerConnection.prototype.getDesiredMediaDirection = function(mediaType, isAddOperation = false) {
  435. const hasLocalSource = this.hasAnyTracksOfType(mediaType);
  436. if (isAddOperation) {
  437. return hasLocalSource ? MediaDirection.SENDRECV : MediaDirection.SENDONLY;
  438. }
  439. return hasLocalSource ? MediaDirection.RECVONLY : MediaDirection.INACTIVE;
  440. };
  441. /**
  442. * Returns the list of RTCRtpReceivers created for the source of the given media type associated with
  443. * the set of remote endpoints specified.
  444. * @param {Array<string>} endpoints list of the endpoints
  445. * @param {string} mediaType 'audio' or 'video'
  446. * @returns {Array<RTCRtpReceiver>} list of receivers created by the peerconnection.
  447. */
  448. TraceablePeerConnection.prototype._getReceiversByEndpointIds = function(endpoints, mediaType) {
  449. let remoteTracks = [];
  450. let receivers = [];
  451. for (const endpoint of endpoints) {
  452. remoteTracks = remoteTracks.concat(this.getRemoteTracks(endpoint, mediaType));
  453. }
  454. // Get the ids of the MediaStreamTracks associated with each of these remote tracks.
  455. const remoteTrackIds = remoteTracks.map(remote => remote.track?.id);
  456. receivers = this.peerconnection.getReceivers()
  457. .filter(receiver => receiver.track
  458. && receiver.track.kind === mediaType
  459. && remoteTrackIds.find(trackId => trackId === receiver.track.id));
  460. return receivers;
  461. };
  462. /**
  463. * Tells whether or not this TPC instance has spatial scalability enabled.
  464. * @return {boolean} <tt>true</tt> if spatial scalability is enabled and active or
  465. * <tt>false</tt> if it's turned off.
  466. */
  467. TraceablePeerConnection.prototype.isSpatialScalabilityOn = function() {
  468. const h264SimulcastEnabled = this.tpcUtils.codecSettings[CodecMimeType.H264].scalabilityModeEnabled
  469. && this._supportsDDHeaderExt;
  470. return !this.options.disableSimulcast
  471. && (this.codecSettings.codecList[0] !== CodecMimeType.H264 || h264SimulcastEnabled);
  472. };
  473. /**
  474. * Handles {@link SignalingEvents.PEER_VIDEO_TYPE_CHANGED}
  475. * @param {string} endpointId the video owner's ID (MUC nickname)
  476. * @param {VideoType} videoType the new value
  477. * @private
  478. */
  479. TraceablePeerConnection.prototype._peerVideoTypeChanged = function(endpointId, videoType) {
  480. // Check if endpointId has a value to avoid action on random track
  481. if (!endpointId) {
  482. logger.error(`${this} No endpointID on peerVideoTypeChanged`);
  483. return;
  484. }
  485. const videoTrack = this.getRemoteTracks(endpointId, MediaType.VIDEO);
  486. if (videoTrack.length) {
  487. // NOTE 1 track per media type is assumed
  488. videoTrack[0]._setVideoType(videoType);
  489. }
  490. };
  491. /**
  492. * Handles remote track mute / unmute events.
  493. * @param {string} endpointId the track owner's identifier (MUC nickname)
  494. * @param {MediaType} mediaType "audio" or "video"
  495. * @param {boolean} isMuted the new mute state
  496. * @private
  497. */
  498. TraceablePeerConnection.prototype._peerMutedChanged = function(endpointId, mediaType, isMuted) {
  499. // Check if endpointId is a value to avoid doing action on all remote tracks
  500. if (!endpointId) {
  501. logger.error(`${this} On peerMuteChanged - no endpoint ID`);
  502. return;
  503. }
  504. const track = this.getRemoteTracks(endpointId, mediaType);
  505. if (track.length) {
  506. // NOTE 1 track per media type is assumed
  507. track[0].setMute(isMuted);
  508. }
  509. };
  510. /**
  511. * Handles remote source mute and unmute changed events.
  512. *
  513. * @param {string} sourceName - The name of the remote source.
  514. * @param {boolean} isMuted - The new mute state.
  515. */
  516. TraceablePeerConnection.prototype._sourceMutedChanged = function(sourceName, isMuted) {
  517. const track = this.getRemoteTracks().find(t => t.getSourceName() === sourceName);
  518. if (!track) {
  519. if (FeatureFlags.isSsrcRewritingSupported()) {
  520. logger.debug(`Remote track not found for source=${sourceName}, mute update failed!`);
  521. }
  522. return;
  523. }
  524. track.setMute(isMuted);
  525. };
  526. /**
  527. * Handles remote source videoType changed events.
  528. *
  529. * @param {string} sourceName - The name of the remote source.
  530. * @param {boolean} isMuted - The new value.
  531. */
  532. TraceablePeerConnection.prototype._sourceVideoTypeChanged = function(sourceName, videoType) {
  533. const track = this.getRemoteTracks().find(t => t.getSourceName() === sourceName);
  534. if (!track) {
  535. return;
  536. }
  537. track._setVideoType(videoType);
  538. };
  539. /**
  540. * Obtains audio levels of the remote audio tracks by getting the source information on the RTCRtpReceivers.
  541. * The information relevant to the ssrc is updated each time a RTP packet constaining the ssrc is received.
  542. * @param {Array<string>} speakerList list of endpoint ids for which audio levels are to be gathered.
  543. * @returns {Object} containing ssrc and audio level information as a key-value pair.
  544. */
  545. TraceablePeerConnection.prototype.getAudioLevels = function(speakerList = []) {
  546. const audioLevels = {};
  547. const audioReceivers = speakerList.length
  548. ? this._getReceiversByEndpointIds(speakerList, MediaType.AUDIO)
  549. : this.peerconnection.getReceivers()
  550. .filter(receiver => receiver.track && receiver.track.kind === MediaType.AUDIO && receiver.track.enabled);
  551. audioReceivers.forEach(remote => {
  552. const ssrc = remote.getSynchronizationSources();
  553. if (ssrc && ssrc.length) {
  554. // As per spec, this audiolevel is a value between 0..1 (linear), where 1.0
  555. // represents 0 dBov, 0 represents silence, and 0.5 represents approximately
  556. // 6 dBSPL change in the sound pressure level from 0 dBov.
  557. // https://www.w3.org/TR/webrtc/#dom-rtcrtpcontributingsource-audiolevel
  558. audioLevels[ssrc[0].source] = ssrc[0].audioLevel;
  559. }
  560. });
  561. return audioLevels;
  562. };
  563. /**
  564. * Checks if the browser is currently doing true simulcast where in three different media streams are being sent to the
  565. * bridge. Currently this happens always for VP8 and only if simulcast is enabled for VP9/AV1/H264.
  566. *
  567. * @param {JitsiLocalTrack} localTrack - The local video track.
  568. * @returns {boolean}
  569. */
  570. TraceablePeerConnection.prototype.doesTrueSimulcast = function(localTrack) {
  571. const currentCodec = this.getConfiguredVideoCodec(localTrack);
  572. return this.isSpatialScalabilityOn() && this.tpcUtils.isRunningInSimulcastMode(currentCodec);
  573. };
  574. /**
  575. * Returns the SSRCs associated with a given local video track.
  576. *
  577. * @param {JitsiLocalTrack} localTrack
  578. * @returns
  579. */
  580. TraceablePeerConnection.prototype.getLocalVideoSSRCs = function(localTrack) {
  581. const ssrcs = [];
  582. if (!localTrack || !localTrack.isVideoTrack()) {
  583. return ssrcs;
  584. }
  585. const ssrcGroup = this.isSpatialScalabilityOn() ? 'SIM' : 'FID';
  586. return this.localSSRCs.get(localTrack.rtcId)?.groups?.find(group => group.semantics === ssrcGroup)?.ssrcs || ssrcs;
  587. };
  588. /**
  589. * Obtains local tracks for given {@link MediaType}. If the <tt>mediaType</tt>
  590. * argument is omitted the list of all local tracks will be returned.
  591. * @param {MediaType} [mediaType]
  592. * @return {Array<JitsiLocalTrack>}
  593. */
  594. TraceablePeerConnection.prototype.getLocalTracks = function(mediaType) {
  595. let tracks = Array.from(this.localTracks.values());
  596. if (mediaType !== undefined) {
  597. tracks = tracks.filter(track => track.getType() === mediaType);
  598. }
  599. return tracks;
  600. };
  601. /**
  602. * Retrieves the local video tracks.
  603. *
  604. * @returns {Array<JitsiLocalTrack>} - local video tracks.
  605. */
  606. TraceablePeerConnection.prototype.getLocalVideoTracks = function() {
  607. return this.getLocalTracks(MediaType.VIDEO);
  608. };
  609. /**
  610. * Checks whether or not this {@link TraceablePeerConnection} instance contains any local tracks for given
  611. * <tt>mediaType</tt>.
  612. *
  613. * @param {MediaType} mediaType - The media type.
  614. * @return {boolean}
  615. */
  616. TraceablePeerConnection.prototype.hasAnyTracksOfType = function(mediaType) {
  617. if (!mediaType) {
  618. throw new Error('"mediaType" is required');
  619. }
  620. return this.getLocalTracks(mediaType).length > 0;
  621. };
  622. /**
  623. * Obtains all remote tracks currently known to this PeerConnection instance.
  624. *
  625. * @param {string} [endpointId] - The track owner's identifier (MUC nickname)
  626. * @param {MediaType} [mediaType] - The remote tracks will be filtered by their media type if this argument is
  627. * specified.
  628. * @return {Array<JitsiRemoteTrack>}
  629. */
  630. TraceablePeerConnection.prototype.getRemoteTracks = function(endpointId, mediaType) {
  631. let remoteTracks = [];
  632. if (FeatureFlags.isSsrcRewritingSupported()) {
  633. for (const remoteTrack of this.remoteTracksBySsrc.values()) {
  634. const owner = remoteTrack.getParticipantId();
  635. if (owner && (!endpointId || owner === endpointId)) {
  636. if (!mediaType || remoteTrack.getType() === mediaType) {
  637. remoteTracks.push(remoteTrack);
  638. }
  639. }
  640. }
  641. return remoteTracks;
  642. }
  643. const endpoints = endpointId ? [ endpointId ] : this.remoteTracks.keys();
  644. for (const endpoint of endpoints) {
  645. const endpointTracksByMediaType = this.remoteTracks.get(endpoint);
  646. if (endpointTracksByMediaType) {
  647. for (const trackMediaType of endpointTracksByMediaType.keys()) {
  648. // per media type filtering
  649. if (!mediaType || mediaType === trackMediaType) {
  650. remoteTracks = remoteTracks.concat(Array.from(endpointTracksByMediaType.get(trackMediaType)));
  651. }
  652. }
  653. }
  654. }
  655. return remoteTracks;
  656. };
  657. /**
  658. * Parses the remote description and returns the sdp lines of the sources associated with a remote participant.
  659. *
  660. * @param {string} id Endpoint id of the remote participant.
  661. * @returns {Array<string>} The sdp lines that have the ssrc information.
  662. */
  663. TraceablePeerConnection.prototype.getRemoteSourceInfoByParticipant = function(id) {
  664. const removeSsrcInfo = [];
  665. const remoteTracks = this.getRemoteTracks(id);
  666. if (!remoteTracks?.length) {
  667. return removeSsrcInfo;
  668. }
  669. const primarySsrcs = remoteTracks.map(track => track.getSSRC());
  670. const sdp = new SDP(this.remoteDescription.sdp);
  671. primarySsrcs.forEach((ssrc, idx) => {
  672. for (const media of sdp.media) {
  673. let lines = '';
  674. let ssrcLines = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  675. if (ssrcLines.length) {
  676. if (!removeSsrcInfo[idx]) {
  677. removeSsrcInfo[idx] = '';
  678. }
  679. // Check if there are any FID groups present for the primary ssrc.
  680. const fidLines = SDPUtil.findLines(media, `a=ssrc-group:FID ${ssrc}`);
  681. if (fidLines.length) {
  682. const secondarySsrc = fidLines[0].split(' ')[2];
  683. lines += `${fidLines[0]}\r\n`;
  684. ssrcLines = ssrcLines.concat(SDPUtil.findLines(media, `a=ssrc:${secondarySsrc}`));
  685. }
  686. removeSsrcInfo[idx] += `${ssrcLines.join('\r\n')}\r\n`;
  687. removeSsrcInfo[idx] += lines;
  688. }
  689. }
  690. });
  691. return removeSsrcInfo;
  692. };
  693. /**
  694. * Returns the target bitrates configured for the local video source.
  695. *
  696. * @param {JitsiLocalTrack} - The local video track.
  697. * @returns {Object}
  698. */
  699. TraceablePeerConnection.prototype.getTargetVideoBitrates = function(localTrack) {
  700. const currentCodec = this.getConfiguredVideoCodec(localTrack);
  701. return this.tpcUtils.codecSettings[currentCodec].maxBitratesVideo;
  702. };
  703. /**
  704. * Tries to find {@link JitsiTrack} for given SSRC number. It will search both local and remote tracks bound to this
  705. * instance.
  706. * @param {number} ssrc
  707. * @return {JitsiTrack|null}
  708. */
  709. TraceablePeerConnection.prototype.getTrackBySSRC = function(ssrc) {
  710. if (typeof ssrc !== 'number') {
  711. throw new Error(`SSRC ${ssrc} is not a number`);
  712. }
  713. for (const localTrack of this.localTracks.values()) {
  714. const { ssrcs } = this.localSSRCs.get(localTrack.rtcId) ?? { ssrcs: [] };
  715. if (ssrcs.find(localSsrc => Number(localSsrc) === ssrc)) {
  716. return localTrack;
  717. }
  718. }
  719. if (FeatureFlags.isSsrcRewritingSupported()) {
  720. return this.remoteTracksBySsrc.get(ssrc);
  721. }
  722. for (const remoteTrack of this.getRemoteTracks()) {
  723. if (remoteTrack.getSSRC() === ssrc) {
  724. return remoteTrack;
  725. }
  726. }
  727. return null;
  728. };
  729. /**
  730. * Tries to find SSRC number for given {@link JitsiTrack} id. It will search
  731. * both local and remote tracks bound to this instance.
  732. * @param {string} id
  733. * @return {number|null}
  734. */
  735. TraceablePeerConnection.prototype.getSsrcByTrackId = function(id) {
  736. const findTrackById = track => track.getTrack().id === id;
  737. const localTrack = this.getLocalTracks().find(findTrackById);
  738. if (localTrack) {
  739. return this.getLocalSSRC(localTrack);
  740. }
  741. const remoteTrack = this.getRemoteTracks().find(findTrackById);
  742. if (remoteTrack) {
  743. return remoteTrack.getSSRC();
  744. }
  745. return null;
  746. };
  747. /**
  748. * Called on "track added" and "stream added" PeerConnection events (because we
  749. * handle streams on per track basis). Finds the owner and the SSRC for
  750. * the track and passes that to ChatRoom for further processing.
  751. * @param {MediaStream} stream the WebRTC MediaStream instance which is
  752. * the parent of the track
  753. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack added for remote
  754. * participant.
  755. * @param {RTCRtpTransceiver} transceiver the WebRTC transceiver that is created
  756. * for the remote participant in unified plan.
  757. */
  758. TraceablePeerConnection.prototype._remoteTrackAdded = function(stream, track, transceiver = null) {
  759. const streamId = stream.id;
  760. const mediaType = track.kind;
  761. // Do not create remote tracks for 'mixed' JVB SSRCs (used by JVB for RTCP termination).
  762. if (!this.isP2P && !RTCUtils.isUserStreamById(streamId)) {
  763. return;
  764. }
  765. logger.info(`${this} Received track event for remote stream[id=${streamId},type=${mediaType}]`);
  766. // look up an associated JID for a stream id
  767. if (!mediaType) {
  768. logger.error(`MediaType undefined for remote track, stream id: ${streamId}, track creation failed!`);
  769. return;
  770. }
  771. const remoteSDP = new SDP(this.peerconnection.remoteDescription.sdp);
  772. let mediaLine;
  773. // Find the matching mline using 'mid' or the 'msid' attr of the stream.
  774. if (transceiver?.mid) {
  775. const mid = transceiver.mid;
  776. mediaLine = remoteSDP.media.find(mls => SDPUtil.findLine(mls, `a=mid:${mid}`));
  777. } else {
  778. mediaLine = remoteSDP.media.find(mls => {
  779. const msid = SDPUtil.findLine(mls, 'a=msid:');
  780. return typeof msid === 'string' && streamId === msid.substring(7).split(' ')[0];
  781. });
  782. }
  783. if (!mediaLine) {
  784. logger.error(`Matching media line not found in remote SDP for remote stream[id=${streamId},type=${mediaType}],`
  785. + 'track creation failed!');
  786. return;
  787. }
  788. let ssrcLines = SDPUtil.findLines(mediaLine, 'a=ssrc:');
  789. ssrcLines = ssrcLines.filter(line => line.indexOf(`msid:${streamId}`) !== -1);
  790. if (!ssrcLines.length) {
  791. logger.error(`No SSRC lines found in remote SDP for remote stream[msid=${streamId},type=${mediaType}]`
  792. + 'track creation failed!');
  793. return;
  794. }
  795. // FIXME the length of ssrcLines[0] not verified, but it will fail
  796. // with global error handler anyway
  797. const ssrcStr = ssrcLines[0].substring(7).split(' ')[0];
  798. const trackSsrc = Number(ssrcStr);
  799. const ownerEndpointId = this.signalingLayer.getSSRCOwner(trackSsrc);
  800. if (isNaN(trackSsrc) || trackSsrc < 0) {
  801. logger.error(`Invalid SSRC for remote stream[ssrc=${trackSsrc},id=${streamId},type=${mediaType}]`
  802. + 'track creation failed!');
  803. return;
  804. }
  805. if (!ownerEndpointId) {
  806. logger.error(`No SSRC owner known for remote stream[ssrc=${trackSsrc},id=${streamId},type=${mediaType}]`
  807. + 'track creation failed!');
  808. return;
  809. }
  810. const sourceName = this.signalingLayer.getTrackSourceName(trackSsrc);
  811. const peerMediaInfo = this.signalingLayer.getPeerMediaInfo(ownerEndpointId, mediaType, sourceName);
  812. // Assume default presence state for remote source. Presence can be received after source signaling. This shouldn't
  813. // prevent the endpoint from creating a remote track for the source.
  814. let muted = true;
  815. let videoType = mediaType === MediaType.VIDEO ? VideoType.CAMERA : undefined; // 'camera' by default
  816. if (peerMediaInfo) {
  817. muted = peerMediaInfo.muted;
  818. videoType = peerMediaInfo.videoType; // can be undefined
  819. } else {
  820. logger.info(`${this}: no source-info available for ${ownerEndpointId}:${sourceName}, assuming default state`);
  821. }
  822. this._createRemoteTrack(ownerEndpointId, stream, track, mediaType, videoType, trackSsrc, muted, sourceName);
  823. };
  824. // FIXME cleanup params
  825. /* eslint-disable max-params */
  826. /**
  827. * Initializes a new JitsiRemoteTrack instance with the data provided by
  828. * the signaling layer and SDP.
  829. *
  830. * @param {string} ownerEndpointId the owner's endpoint ID (MUC nickname)
  831. * @param {MediaStream} stream the WebRTC stream instance
  832. * @param {MediaStreamTrack} track the WebRTC track instance
  833. * @param {MediaType} mediaType the track's type of the media
  834. * @param {VideoType} [videoType] the track's type of the video (if applicable)
  835. * @param {number} ssrc the track's main SSRC number
  836. * @param {boolean} muted the initial muted status
  837. * @param {String} sourceName the track's source name
  838. */
  839. TraceablePeerConnection.prototype._createRemoteTrack = function(
  840. ownerEndpointId,
  841. stream,
  842. track,
  843. mediaType,
  844. videoType,
  845. ssrc,
  846. muted,
  847. sourceName) {
  848. logger.info(`${this} creating remote track[endpoint=${ownerEndpointId},ssrc=${ssrc},`
  849. + `type=${mediaType},sourceName=${sourceName}]`);
  850. let remoteTracksMap;
  851. let userTracksByMediaType;
  852. if (FeatureFlags.isSsrcRewritingSupported()) {
  853. const existingTrack = this.remoteTracksBySsrc.get(ssrc);
  854. if (existingTrack) {
  855. logger.info(`${this} ignored duplicated track event for SSRC[ssrc=${ssrc},type=${mediaType}]`);
  856. return;
  857. }
  858. } else {
  859. remoteTracksMap = this.remoteTracks.get(ownerEndpointId);
  860. if (!remoteTracksMap) {
  861. remoteTracksMap = new Map();
  862. remoteTracksMap.set(MediaType.AUDIO, new Set());
  863. remoteTracksMap.set(MediaType.VIDEO, new Set());
  864. this.remoteTracks.set(ownerEndpointId, remoteTracksMap);
  865. }
  866. userTracksByMediaType = remoteTracksMap.get(mediaType);
  867. if (userTracksByMediaType?.size
  868. && Array.from(userTracksByMediaType).find(jitsiTrack => jitsiTrack.getTrack() === track)) {
  869. // Ignore duplicated event which can originate either from 'onStreamAdded' or 'onTrackAdded'.
  870. logger.info(`${this} ignored duplicated track event for track[endpoint=${ownerEndpointId},`
  871. + `type=${mediaType}]`);
  872. return;
  873. }
  874. }
  875. const remoteTrack
  876. = new JitsiRemoteTrack(
  877. this.rtc,
  878. this.rtc.conference,
  879. ownerEndpointId,
  880. stream,
  881. track,
  882. mediaType,
  883. videoType,
  884. ssrc,
  885. muted,
  886. this.isP2P,
  887. sourceName);
  888. if (FeatureFlags.isSsrcRewritingSupported()) {
  889. this.remoteTracksBySsrc.set(ssrc, remoteTrack);
  890. } else {
  891. userTracksByMediaType.add(remoteTrack);
  892. }
  893. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, remoteTrack, this);
  894. };
  895. /**
  896. * Handles remote media track removal.
  897. *
  898. * @param {MediaStream} stream - WebRTC MediaStream instance which is the parent of the track.
  899. * @param {MediaStreamTrack} track - WebRTC MediaStreamTrack which has been removed from the PeerConnection.
  900. * @returns {void}
  901. */
  902. TraceablePeerConnection.prototype._remoteTrackRemoved = function(stream, track) {
  903. const streamId = stream.id;
  904. const trackId = track?.id;
  905. // Ignore stream removed events for JVB "mixed" sources (used for RTCP termination).
  906. if (!RTCUtils.isUserStreamById(streamId)) {
  907. return;
  908. }
  909. if (!streamId) {
  910. logger.error(`${this} remote track removal failed - no stream ID`);
  911. return;
  912. }
  913. if (!trackId) {
  914. logger.error(`${this} remote track removal failed - no track ID`);
  915. return;
  916. }
  917. const toBeRemoved = this.getRemoteTracks().find(
  918. remoteTrack => remoteTrack.getStreamId() === streamId && remoteTrack.getTrackId() === trackId);
  919. if (!toBeRemoved) {
  920. logger.error(`${this} remote track removal failed - track not found`);
  921. return;
  922. }
  923. this._removeRemoteTrack(toBeRemoved);
  924. };
  925. /**
  926. * Removes and disposes given <tt>JitsiRemoteTrack</tt> instance. Emits {@link RTCEvents.REMOTE_TRACK_REMOVED}.
  927. *
  928. * @param {JitsiRemoteTrack} toBeRemoved - The remote track to be removed.
  929. * @returns {void}
  930. */
  931. TraceablePeerConnection.prototype._removeRemoteTrack = function(toBeRemoved) {
  932. logger.info(`${this} Removing remote track stream[id=${toBeRemoved.getStreamId()},`
  933. + `trackId=${toBeRemoved.getTrackId()}]`);
  934. toBeRemoved.dispose();
  935. const participantId = toBeRemoved.getParticipantId();
  936. if (FeatureFlags.isSsrcRewritingSupported() && !participantId) {
  937. return;
  938. } else if (!FeatureFlags.isSsrcRewritingSupported()) {
  939. const userTracksByMediaType = this.remoteTracks.get(participantId);
  940. if (!userTracksByMediaType) {
  941. logger.error(`${this} removeRemoteTrack: no remote tracks map for endpoint=${participantId}`);
  942. } else if (!userTracksByMediaType.get(toBeRemoved.getType())?.delete(toBeRemoved)) {
  943. logger.error(`${this} Failed to remove ${toBeRemoved} - type mapping messed up ?`);
  944. }
  945. }
  946. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_REMOVED, toBeRemoved);
  947. };
  948. /**
  949. * Processes the local SDP and creates an SSRC map for every local track.
  950. *
  951. * @param {string} localSDP - SDP from the local description.
  952. * @returns {void}
  953. */
  954. TraceablePeerConnection.prototype._processAndExtractSourceInfo = function(localSDP) {
  955. const ssrcMap = new Map();
  956. if (!localSDP || typeof localSDP !== 'string') {
  957. throw new Error('Local SDP must be a valid string, aborting!!');
  958. }
  959. const session = transform.parse(localSDP);
  960. const media = session.media.filter(mline => mline.direction === MediaDirection.SENDONLY
  961. || mline.direction === MediaDirection.SENDRECV);
  962. if (!Array.isArray(media)) {
  963. this._localSsrcMap = ssrcMap;
  964. return;
  965. }
  966. for (const localTrack of this.localTracks.values()) {
  967. const sourceName = localTrack.getSourceName();
  968. const trackIndex = getSourceIndexFromSourceName(sourceName);
  969. const mediaType = localTrack.getType();
  970. const mLines = media.filter(m => m.type === mediaType);
  971. const ssrcGroups = mLines[trackIndex].ssrcGroups;
  972. let ssrcs = mLines[trackIndex].ssrcs;
  973. if (ssrcs?.length) {
  974. // Filter the ssrcs with 'cname' attribute.
  975. ssrcs = ssrcs.filter(s => s.attribute === 'cname');
  976. const msid = `${this.rtc.getLocalEndpointId()}-${mediaType}-${trackIndex}`;
  977. const ssrcInfo = {
  978. ssrcs: [],
  979. groups: [],
  980. msid
  981. };
  982. ssrcs.forEach(ssrc => ssrcInfo.ssrcs.push(ssrc.id));
  983. if (ssrcGroups?.length) {
  984. for (const group of ssrcGroups) {
  985. group.ssrcs = group.ssrcs.split(' ').map(ssrcStr => parseInt(ssrcStr, 10));
  986. ssrcInfo.groups.push(group);
  987. }
  988. const simGroup = ssrcGroups.find(group => group.semantics === 'SIM');
  989. // Add a SIM group if its missing in the description (happens on Firefox).
  990. if (this.isSpatialScalabilityOn() && !simGroup) {
  991. const groupSsrcs = ssrcGroups.map(group => group.ssrcs[0]);
  992. ssrcInfo.groups.push({
  993. semantics: 'SIM',
  994. ssrcs: groupSsrcs
  995. });
  996. }
  997. }
  998. ssrcMap.set(sourceName, ssrcInfo);
  999. const oldSsrcInfo = this.localSSRCs.get(localTrack.rtcId);
  1000. const oldSsrc = this._extractPrimarySSRC(oldSsrcInfo);
  1001. const newSsrc = this._extractPrimarySSRC(ssrcInfo);
  1002. if (oldSsrc !== newSsrc) {
  1003. oldSsrc && logger.debug(`${this} Overwriting SSRC for track=${localTrack}] with ssrc=${newSsrc}`);
  1004. this.localSSRCs.set(localTrack.rtcId, ssrcInfo);
  1005. localTrack.setSsrc(newSsrc);
  1006. }
  1007. }
  1008. }
  1009. this._localSsrcMap = ssrcMap;
  1010. };
  1011. /**
  1012. *
  1013. * @param {JitsiLocalTrack} localTrack
  1014. */
  1015. TraceablePeerConnection.prototype.getLocalSSRC = function(localTrack) {
  1016. const ssrcInfo = this._getSSRC(localTrack.rtcId);
  1017. return ssrcInfo && ssrcInfo.ssrcs[0];
  1018. };
  1019. /**
  1020. * When doing unified plan simulcast, we'll have a set of ssrcs but no ssrc-groups on Firefox. Unfortunately, Jicofo
  1021. * will complain if it sees ssrcs with matching msids but no ssrc-group, so a ssrc-group line is injected to make
  1022. * Jicofo happy.
  1023. *
  1024. * @param desc A session description object (with 'type' and 'sdp' fields)
  1025. * @return A session description object with its sdp field modified to contain an inject ssrc-group for simulcast.
  1026. */
  1027. TraceablePeerConnection.prototype._injectSsrcGroupForUnifiedSimulcast = function(desc) {
  1028. const sdp = transform.parse(desc.sdp);
  1029. const video = sdp.media.find(mline => mline.type === 'video');
  1030. // Check if the browser supports RTX, add only the primary ssrcs to the SIM group if that is the case.
  1031. video.ssrcGroups = video.ssrcGroups || [];
  1032. const fidGroups = video.ssrcGroups.filter(group => group.semantics === 'FID');
  1033. if (video.simulcast || video.simulcast_03) {
  1034. const ssrcs = [];
  1035. if (fidGroups && fidGroups.length) {
  1036. fidGroups.forEach(group => {
  1037. ssrcs.push(group.ssrcs.split(' ')[0]);
  1038. });
  1039. } else {
  1040. video.ssrcs.forEach(ssrc => {
  1041. if (ssrc.attribute === 'msid') {
  1042. ssrcs.push(ssrc.id);
  1043. }
  1044. });
  1045. }
  1046. if (video.ssrcGroups.find(group => group.semantics === 'SIM')) {
  1047. // Group already exists, no need to do anything
  1048. return desc;
  1049. }
  1050. // Add a SIM group for every 3 FID groups.
  1051. for (let i = 0; i < ssrcs.length; i += 3) {
  1052. const simSsrcs = ssrcs.slice(i, i + 3);
  1053. video.ssrcGroups.push({
  1054. semantics: 'SIM',
  1055. ssrcs: simSsrcs.join(' ')
  1056. });
  1057. }
  1058. }
  1059. return new RTCSessionDescription({
  1060. type: desc.type,
  1061. sdp: transform.write(sdp)
  1062. });
  1063. };
  1064. /* eslint-disable-next-line vars-on-top */
  1065. const getters = {
  1066. signalingState() {
  1067. return this.peerconnection.signalingState;
  1068. },
  1069. iceConnectionState() {
  1070. return this.peerconnection.iceConnectionState;
  1071. },
  1072. connectionState() {
  1073. return this.peerconnection.connectionState;
  1074. },
  1075. localDescription() {
  1076. let desc = this.peerconnection.localDescription;
  1077. if (!desc) {
  1078. logger.debug(`${this} getLocalDescription no localDescription found`);
  1079. return {};
  1080. }
  1081. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  1082. // For a jvb connection, transform the SDP to Plan B first.
  1083. if (!this.isP2P) {
  1084. desc = this._injectSsrcGroupForUnifiedSimulcast(desc);
  1085. this.trace('getLocalDescription::postTransform (inject ssrc group)', dumpSDP(desc));
  1086. }
  1087. // See the method's doc for more info about this transformation.
  1088. desc = this.localSdpMunger.transformStreamIdentifiers(desc, this._localSsrcMap);
  1089. return desc;
  1090. },
  1091. remoteDescription() {
  1092. let desc = this.peerconnection.remoteDescription;
  1093. if (!desc) {
  1094. logger.debug(`${this} getRemoteDescription no remoteDescription found`);
  1095. return {};
  1096. }
  1097. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  1098. if (this.isP2P) {
  1099. // Adjust the media direction for p2p based on whether a local source has been added.
  1100. desc = this._adjustRemoteMediaDirection(desc);
  1101. } else {
  1102. // If this is a jvb connection, transform the SDP to Plan B first.
  1103. desc = this.interop.toPlanB(desc);
  1104. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  1105. }
  1106. return desc;
  1107. }
  1108. };
  1109. Object.keys(getters).forEach(prop => {
  1110. Object.defineProperty(
  1111. TraceablePeerConnection.prototype,
  1112. prop, {
  1113. get: getters[prop]
  1114. }
  1115. );
  1116. });
  1117. TraceablePeerConnection.prototype._getSSRC = function(rtcId) {
  1118. return this.localSSRCs.get(rtcId);
  1119. };
  1120. /**
  1121. * Checks if low fps screensharing is in progress.
  1122. *
  1123. * @private
  1124. * @returns {boolean} Returns true if 5 fps screensharing is in progress, false otherwise.
  1125. */
  1126. TraceablePeerConnection.prototype.isSharingLowFpsScreen = function() {
  1127. return this._isSharingScreen() && this._capScreenshareBitrate;
  1128. };
  1129. /**
  1130. * Checks if screensharing is in progress.
  1131. *
  1132. * @returns {boolean} Returns true if a desktop track has been added to the peerconnection, false otherwise.
  1133. */
  1134. TraceablePeerConnection.prototype._isSharingScreen = function() {
  1135. const tracks = this.getLocalVideoTracks();
  1136. return Boolean(tracks.find(track => track.videoType === VideoType.DESKTOP));
  1137. };
  1138. /**
  1139. * Munges the order of the codecs in the SDP passed based on the preference
  1140. * set through config.js settings. All instances of the specified codec are
  1141. * moved up to the top of the list when it is preferred. The specified codec
  1142. * is deleted from the list if the configuration specifies that the codec be
  1143. * disabled.
  1144. * @param {RTCSessionDescription} description that needs to be munged.
  1145. * @returns {RTCSessionDescription} the munged description.
  1146. */
  1147. TraceablePeerConnection.prototype._mungeCodecOrder = function(description) {
  1148. if (!this.codecSettings) {
  1149. return description;
  1150. }
  1151. const parsedSdp = transform.parse(description.sdp);
  1152. const mLines = parsedSdp.media.filter(m => m.type === this.codecSettings.mediaType);
  1153. if (!mLines.length) {
  1154. return description;
  1155. }
  1156. for (const mLine of mLines) {
  1157. const currentCodecs = this.getConfiguredVideoCodecs(description);
  1158. for (const codec of currentCodecs) {
  1159. if (this.isP2P) {
  1160. // 1. Strip the high profile H264 codecs on all clients. macOS started offering encoder for H.264 level
  1161. // 5.2 but a decoder only for level 3.1. Therfore, strip all main and high level codecs for H.264.
  1162. // 2. There are multiple VP9 payload types generated by the browser, more payload types are added if the
  1163. // endpoint doesn't have a local video source. Therefore, strip all the high profile codec variants
  1164. // for VP9 so that only one payload type for VP9 is negotiated between the peers.
  1165. if (codec === CodecMimeType.H264 || codec === CodecMimeType.VP9) {
  1166. SDPUtil.stripCodec(mLine, codec, true /* high profile */);
  1167. }
  1168. // Do not negotiate ULPFEC and RED either.
  1169. if (codec === CodecMimeType.ULPFEC || codec === CodecMimeType.RED) {
  1170. SDPUtil.stripCodec(mLine, codec, false);
  1171. }
  1172. }
  1173. }
  1174. // Reorder the codecs based on the preferred settings.
  1175. if (!this.usesCodecSelectionAPI()) {
  1176. for (const codec of this.codecSettings.codecList.slice().reverse()) {
  1177. SDPUtil.preferCodec(mLine, codec, this.isP2P);
  1178. }
  1179. }
  1180. }
  1181. return new RTCSessionDescription({
  1182. type: description.type,
  1183. sdp: transform.write(parsedSdp)
  1184. });
  1185. };
  1186. /**
  1187. * Checks if the AV1 Dependency descriptors are negotiated on the bridge peerconnection and disables them when the
  1188. * codec selected is VP8 or VP9.
  1189. *
  1190. * @param {RTCSessionDescription} description that needs to be munged.
  1191. * @returns {RTCSessionDescription} the munged description.
  1192. */
  1193. TraceablePeerConnection.prototype._updateAv1DdHeaders = function(description) {
  1194. const parsedSdp = transform.parse(description.sdp);
  1195. const mLines = parsedSdp.media.filter(m => m.type === MediaType.VIDEO);
  1196. if (!mLines.length || !browser.supportsDDExtHeaders()) {
  1197. return description;
  1198. }
  1199. mLines.forEach((mLine, idx) => {
  1200. const senderMids = Array.from(this._localTrackTransceiverMids.values());
  1201. const isSender = senderMids.length
  1202. ? senderMids.find(mid => mLine.mid.toString() === mid.toString())
  1203. : idx === 0;
  1204. const payload = mLine.payloads.split(' ')[0];
  1205. let { codec } = mLine.rtp.find(rtp => rtp.payload === Number(payload));
  1206. codec = codec.toLowerCase();
  1207. if (isSender && mLine.ext?.length) {
  1208. const headerIndex = mLine.ext.findIndex(ext => ext.uri === DD_HEADER_EXT_URI);
  1209. const shouldNegotiateHeaderExts = codec === CodecMimeType.AV1 || codec === CodecMimeType.H264;
  1210. if (!this._supportsDDHeaderExt && headerIndex >= 0) {
  1211. this._supportsDDHeaderExt = true;
  1212. }
  1213. if (this._supportsDDHeaderExt && shouldNegotiateHeaderExts && headerIndex < 0) {
  1214. mLine.ext.push({
  1215. value: DD_HEADER_EXT_ID,
  1216. uri: DD_HEADER_EXT_URI
  1217. });
  1218. } else if (!shouldNegotiateHeaderExts && headerIndex >= 0) {
  1219. mLine.ext.splice(headerIndex, 1);
  1220. }
  1221. }
  1222. });
  1223. return new RTCSessionDescription({
  1224. type: description.type,
  1225. sdp: transform.write(parsedSdp)
  1226. });
  1227. };
  1228. /**
  1229. * Add {@link JitsiLocalTrack} to this TPC.
  1230. * @param {JitsiLocalTrack} track
  1231. * @param {boolean} isInitiator indicates if the endpoint is the offerer.
  1232. * @returns {Promise<void>} - resolved when done.
  1233. */
  1234. TraceablePeerConnection.prototype.addTrack = function(track, isInitiator = false) {
  1235. const rtcId = track.rtcId;
  1236. let transceiver;
  1237. logger.info(`${this} adding ${track}`);
  1238. if (this.localTracks.has(rtcId)) {
  1239. return Promise.reject(new Error(`${track} is already in ${this}`));
  1240. }
  1241. this.localTracks.set(rtcId, track);
  1242. const webrtcStream = track.getOriginalStream();
  1243. try {
  1244. transceiver = this.tpcUtils.addTrack(track, isInitiator);
  1245. } catch (error) {
  1246. logger.error(`${this} Adding track=${track} failed: ${error?.message}`);
  1247. return Promise.reject(error);
  1248. }
  1249. if (transceiver?.mid) {
  1250. this._localTrackTransceiverMids.set(track.rtcId, transceiver.mid.toString());
  1251. }
  1252. if (track) {
  1253. if (track.isAudioTrack()) {
  1254. this._hasHadAudioTrack = true;
  1255. } else {
  1256. this._hasHadVideoTrack = true;
  1257. }
  1258. }
  1259. let promiseChain = Promise.resolve();
  1260. // On Firefox, the encodings have to be configured on the sender only after the transceiver is created.
  1261. if (browser.isFirefox()) {
  1262. promiseChain = promiseChain.then(() => webrtcStream && this.tpcUtils.setEncodings(track));
  1263. }
  1264. return promiseChain;
  1265. };
  1266. /**
  1267. * Adds local track to the RTCPeerConnection.
  1268. *
  1269. * @param {JitsiLocalTrack} track the track to be added to the pc.
  1270. * @return {Promise<boolean>} Promise that resolves to true if the underlying PeerConnection's state has changed and
  1271. * renegotiation is required, false if no renegotiation is needed or Promise is rejected when something goes wrong.
  1272. */
  1273. TraceablePeerConnection.prototype.addTrackToPc = function(track) {
  1274. logger.info(`${this} Adding track=${track} to PC`);
  1275. if (!this._assertTrackBelongs('addTrackToPc', track)) {
  1276. // Abort
  1277. return Promise.reject('Track not found on the peerconnection');
  1278. }
  1279. const webRtcStream = track.getOriginalStream();
  1280. if (!webRtcStream) {
  1281. logger.error(`${this} Unable to add track=${track} to PC - no WebRTC stream`);
  1282. return Promise.reject('Stream not found');
  1283. }
  1284. return this.tpcUtils.replaceTrack(null, track).then(() => {
  1285. if (track) {
  1286. if (track.isAudioTrack()) {
  1287. this._hasHadAudioTrack = true;
  1288. } else {
  1289. this._hasHadVideoTrack = true;
  1290. }
  1291. }
  1292. return false;
  1293. });
  1294. };
  1295. /**
  1296. * This method when called will check if given <tt>localTrack</tt> belongs to
  1297. * this TPC (that it has been previously added using {@link addTrack}). If the
  1298. * track does not belong an error message will be logged.
  1299. * @param {string} methodName the method name that will be logged in an error
  1300. * message
  1301. * @param {JitsiLocalTrack} localTrack
  1302. * @return {boolean} <tt>true</tt> if given local track belongs to this TPC or
  1303. * <tt>false</tt> otherwise.
  1304. * @private
  1305. */
  1306. TraceablePeerConnection.prototype._assertTrackBelongs = function(
  1307. methodName,
  1308. localTrack) {
  1309. const doesBelong = this.localTracks.has(localTrack?.rtcId);
  1310. if (!doesBelong) {
  1311. logger.error(`${this} ${methodName}: track=${localTrack} does not belong to pc`);
  1312. }
  1313. return doesBelong;
  1314. };
  1315. /**
  1316. * Returns the codec that is configured on the client as the preferred video codec for the given local video track.
  1317. *
  1318. * @param {JitsiLocalTrack} localTrack - The local video track.
  1319. * @returns {CodecMimeType} The codec that is set as the preferred codec for the given local video track.
  1320. *
  1321. */
  1322. TraceablePeerConnection.prototype.getConfiguredVideoCodec = function(localTrack) {
  1323. const localVideoTrack = localTrack ?? this.getLocalVideoTracks()[0];
  1324. const rtpSender = this.findSenderForTrack(localVideoTrack.getTrack());
  1325. if (this.usesCodecSelectionAPI() && rtpSender) {
  1326. const { codecs } = rtpSender.getParameters();
  1327. return codecs[0].mimeType.split('/')[1].toLowerCase();
  1328. }
  1329. const sdp = this.peerconnection.remoteDescription?.sdp;
  1330. const defaultCodec = CodecMimeType.VP8;
  1331. if (!sdp) {
  1332. return defaultCodec;
  1333. }
  1334. const parsedSdp = transform.parse(sdp);
  1335. const mLine = parsedSdp.media
  1336. .find(m => m.mid.toString() === this._localTrackTransceiverMids.get(localVideoTrack.rtcId));
  1337. const payload = mLine.payloads.split(' ')[0];
  1338. const { codec } = mLine.rtp.find(rtp => rtp.payload === Number(payload));
  1339. if (codec) {
  1340. return Object.values(CodecMimeType).find(value => value === codec.toLowerCase());
  1341. }
  1342. return defaultCodec;
  1343. };
  1344. /**
  1345. * Returns the codecs in the current order of preference as configured on the peerconnection.
  1346. *
  1347. * @param {RTCSessionDescription} - The local description to be used.
  1348. * @returns {Array}
  1349. */
  1350. TraceablePeerConnection.prototype.getConfiguredVideoCodecs = function(description) {
  1351. const currentSdp = description?.sdp ?? this.localDescription?.sdp;
  1352. if (!currentSdp) {
  1353. return [];
  1354. }
  1355. const parsedSdp = transform.parse(currentSdp);
  1356. const mLine = parsedSdp.media.find(m => m.type === MediaType.VIDEO);
  1357. const codecs = new Set(mLine.rtp
  1358. .filter(pt => pt.codec.toLowerCase() !== 'rtx')
  1359. .map(pt => pt.codec.toLowerCase()));
  1360. return Array.from(codecs);
  1361. };
  1362. /**
  1363. * Enables or disables simulcast for screenshare based on the frame rate requested for desktop track capture.
  1364. *
  1365. * @param {number} maxFps framerate to be used for desktop track capture.
  1366. */
  1367. TraceablePeerConnection.prototype.setDesktopSharingFrameRate = function(maxFps) {
  1368. const lowFps = maxFps <= SS_DEFAULT_FRAME_RATE;
  1369. this._capScreenshareBitrate = this.isSpatialScalabilityOn() && lowFps;
  1370. };
  1371. /**
  1372. * Sets the codec preference on the peerconnection. The codec preference goes into effect when
  1373. * the next renegotiation happens for older clients that do not support the codec selection API.
  1374. *
  1375. * @param {Array<CodecMimeType>} codecList - Preferred codecs for video.
  1376. * @param {CodecMimeType} screenshareCodec - The preferred codec for screenshare.
  1377. * @returns {void}
  1378. */
  1379. TraceablePeerConnection.prototype.setVideoCodecs = function(codecList, screenshareCodec) {
  1380. if (!this.codecSettings || !codecList?.length) {
  1381. return;
  1382. }
  1383. this.codecSettings.codecList = codecList;
  1384. if (screenshareCodec) {
  1385. this.codecSettings.screenshareCodec = screenshareCodec;
  1386. }
  1387. if (this.usesCodecSelectionAPI()) {
  1388. this.configureVideoSenderEncodings();
  1389. }
  1390. };
  1391. /**
  1392. * Remove local track from this TPC.
  1393. * @param {JitsiLocalTrack} localTrack the track to be removed from this TPC.
  1394. *
  1395. * FIXME It should probably remove a boolean just like {@link removeTrackFromPc}
  1396. * The same applies to addTrack.
  1397. */
  1398. TraceablePeerConnection.prototype.removeTrack = function(localTrack) {
  1399. const webRtcStream = localTrack.getOriginalStream();
  1400. this.trace(
  1401. 'removeStream',
  1402. localTrack.rtcId, webRtcStream ? webRtcStream.id : undefined);
  1403. if (!this._assertTrackBelongs('removeStream', localTrack)) {
  1404. // Abort - nothing to be done here
  1405. return;
  1406. }
  1407. this.localTracks.delete(localTrack.rtcId);
  1408. this.localSSRCs.delete(localTrack.rtcId);
  1409. if (webRtcStream) {
  1410. this.peerconnection.removeStream(webRtcStream);
  1411. }
  1412. };
  1413. /**
  1414. * Returns the receiver corresponding to the given MediaStreamTrack.
  1415. *
  1416. * @param {MediaSreamTrack} track - The media stream track used for the search.
  1417. * @returns {RTCRtpReceiver|undefined} - The found receiver or undefined if no receiver
  1418. * was found.
  1419. */
  1420. TraceablePeerConnection.prototype.findReceiverForTrack = function(track) {
  1421. return this.peerconnection.getReceivers().find(r => r.track === track);
  1422. };
  1423. /**
  1424. * Returns the sender corresponding to the given MediaStreamTrack.
  1425. *
  1426. * @param {MediaSreamTrack} track - The media stream track used for the search.
  1427. * @returns {RTCRtpSender|undefined} - The found sender or undefined if no sender
  1428. * was found.
  1429. */
  1430. TraceablePeerConnection.prototype.findSenderForTrack = function(track) {
  1431. return this.peerconnection.getSenders().find(s => s.track === track);
  1432. };
  1433. /**
  1434. * Processes the local description SDP and caches the mids of the mlines associated with the given tracks.
  1435. *
  1436. * @param {Array<JitsiLocalTrack>} localTracks - local tracks that are added to the peerconnection.
  1437. * @returns {void}
  1438. */
  1439. TraceablePeerConnection.prototype.processLocalSdpForTransceiverInfo = function(localTracks) {
  1440. const localSdp = this.localDescription?.sdp;
  1441. if (!localSdp) {
  1442. return;
  1443. }
  1444. [ MediaType.AUDIO, MediaType.VIDEO ].forEach(mediaType => {
  1445. const tracks = localTracks.filter(t => t.getType() === mediaType);
  1446. const parsedSdp = transform.parse(localSdp);
  1447. const mLines = parsedSdp.media.filter(mline => mline.type === mediaType);
  1448. tracks.forEach((track, idx) => {
  1449. if (!this._localTrackTransceiverMids.has(track.rtcId)) {
  1450. this._localTrackTransceiverMids.set(track.rtcId, mLines[idx].mid.toString());
  1451. }
  1452. });
  1453. });
  1454. };
  1455. /**
  1456. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> from the peer connection.
  1457. * Either <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1458. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1459. * <tt>oldTrack</tt>
  1460. *
  1461. * @param {JitsiLocalTrack|null} oldTrack - The current track in use to be replaced on the pc.
  1462. * @param {JitsiLocalTrack|null} newTrack - The new track to be used.
  1463. *
  1464. * @returns {Promise<boolean>} - If the promise resolves with true, renegotiation will be needed.
  1465. * Otherwise no renegotiation is needed.
  1466. */
  1467. TraceablePeerConnection.prototype.replaceTrack = function(oldTrack, newTrack) {
  1468. if (!(oldTrack || newTrack)) {
  1469. logger.info(`${this} replaceTrack called with no new track and no old track`);
  1470. return Promise.resolve();
  1471. }
  1472. logger.info(`${this} TPC.replaceTrack old=${oldTrack}, new=${newTrack}`);
  1473. return this.tpcUtils.replaceTrack(oldTrack, newTrack)
  1474. .then(transceiver => {
  1475. if (oldTrack) {
  1476. this.localTracks.delete(oldTrack.rtcId);
  1477. this._localTrackTransceiverMids.delete(oldTrack.rtcId);
  1478. }
  1479. if (newTrack) {
  1480. if (newTrack.isAudioTrack()) {
  1481. this._hasHadAudioTrack = true;
  1482. } else {
  1483. this._hasHadVideoTrack = true;
  1484. }
  1485. this._localTrackTransceiverMids.set(newTrack.rtcId, transceiver?.mid?.toString());
  1486. this.localTracks.set(newTrack.rtcId, newTrack);
  1487. }
  1488. // Update the local SSRC cache for the case when one track gets replaced with another and no
  1489. // renegotiation is triggered as a result of this.
  1490. if (oldTrack && newTrack) {
  1491. const oldTrackSSRC = this.localSSRCs.get(oldTrack.rtcId);
  1492. if (oldTrackSSRC) {
  1493. this.localSSRCs.delete(oldTrack.rtcId);
  1494. this.localSSRCs.set(newTrack.rtcId, oldTrackSSRC);
  1495. const oldSsrcNum = this._extractPrimarySSRC(oldTrackSSRC);
  1496. newTrack.setSsrc(oldSsrcNum);
  1497. }
  1498. }
  1499. // In the scenario where we remove the oldTrack (oldTrack is not null and newTrack is null) on FF
  1500. // if we change the direction to RECVONLY, create answer will generate SDP with only 1 receive
  1501. // only ssrc instead of keeping all 6 ssrcs that we currently have. Stopping the screen sharing
  1502. // and then starting it again will trigger 2 rounds of source-remove and source-add replacing
  1503. // the 6 ssrcs for the screen sharing with 1 receive only ssrc and then removing the receive
  1504. // only ssrc and adding the same 6 ssrcs. On the remote participant's side the same ssrcs will
  1505. // be reused on a new m-line and if the remote participant is FF due to
  1506. // https://bugzilla.mozilla.org/show_bug.cgi?id=1768729 the video stream won't be rendered.
  1507. // That's why we need keep the direction to SENDRECV for FF.
  1508. //
  1509. // NOTE: If we return back to the approach of not removing the track for FF and instead using the
  1510. // enabled property for mute or stopping screensharing we may need to change the direction to
  1511. // RECVONLY if FF still sends the media even though the enabled flag is set to false.
  1512. transceiver.direction
  1513. = newTrack || browser.isFirefox() ? MediaDirection.SENDRECV : MediaDirection.RECVONLY;
  1514. // Avoid re-configuring the encodings on Chromium/Safari, this is needed only on Firefox.
  1515. const configureEncodingsPromise
  1516. = !newTrack || browser.usesSdpMungingForSimulcast()
  1517. ? Promise.resolve()
  1518. : this.tpcUtils.setEncodings(newTrack);
  1519. return configureEncodingsPromise.then(() => this.isP2P);
  1520. });
  1521. };
  1522. /**
  1523. * Removes local track from the RTCPeerConnection.
  1524. *
  1525. * @param {JitsiLocalTrack} localTrack the local track to be removed.
  1526. * @return {Promise<boolean>} Promise that resolves to true if the underlying PeerConnection's state has changed and
  1527. * renegotiation is required, false if no renegotiation is needed or Promise is rejected when something goes wrong.
  1528. */
  1529. TraceablePeerConnection.prototype.removeTrackFromPc = function(localTrack) {
  1530. const webRtcStream = localTrack.getOriginalStream();
  1531. this.trace('removeTrack', localTrack.rtcId, webRtcStream ? webRtcStream.id : null);
  1532. if (!this._assertTrackBelongs('removeTrack', localTrack)) {
  1533. // Abort - nothing to be done here
  1534. return Promise.reject('Track not found in the peerconnection');
  1535. }
  1536. return this.tpcUtils.replaceTrack(localTrack, null).then(() => false);
  1537. };
  1538. /**
  1539. * Returns true if the codec selection API is used for switching between codecs for the video sources.
  1540. *
  1541. * @returns {boolean}
  1542. */
  1543. TraceablePeerConnection.prototype.usesCodecSelectionAPI = function() {
  1544. // Browser throws an error when H.264 is set on the encodings. Therefore, munge the SDP when H.264 needs to be
  1545. // selected.
  1546. // TODO: Remove this check when the above issue is fixed.
  1547. return this._usesCodecSelectionAPI && this.codecSettings.codecList[0] !== CodecMimeType.H264;
  1548. };
  1549. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  1550. this.trace('createDataChannel', label, opts);
  1551. return this.peerconnection.createDataChannel(label, opts);
  1552. };
  1553. /**
  1554. * Adjusts the media direction on the remote description based on availability of local and remote sources in a p2p
  1555. * media connection.
  1556. *
  1557. * @param {RTCSessionDescription} remoteDescription the WebRTC session description instance for the remote description.
  1558. * @returns the transformed remoteDescription.
  1559. * @private
  1560. */
  1561. TraceablePeerConnection.prototype._adjustRemoteMediaDirection = function(remoteDescription) {
  1562. const transformer = new SdpTransformWrap(remoteDescription.sdp);
  1563. [ MediaType.AUDIO, MediaType.VIDEO ].forEach(mediaType => {
  1564. const media = transformer.selectMedia(mediaType);
  1565. const localSources = this.getLocalTracks(mediaType).length;
  1566. const remoteSources = this.getRemoteTracks(null, mediaType).length;
  1567. media.forEach((mLine, idx) => {
  1568. if (localSources && localSources === remoteSources) {
  1569. mLine.direction = MediaDirection.SENDRECV;
  1570. } else if (!localSources && !remoteSources) {
  1571. mLine.direction = MediaDirection.INACTIVE;
  1572. } else if (!localSources) {
  1573. mLine.direction = MediaDirection.SENDONLY;
  1574. } else if (!remoteSources) {
  1575. mLine.direction = MediaDirection.RECVONLY;
  1576. // When there are 2 local sources and 1 remote source, the first m-line should be set to 'sendrecv' while
  1577. // the second one needs to be set to 'recvonly'.
  1578. } else if (localSources > remoteSources) {
  1579. mLine.direction = idx ? MediaDirection.RECVONLY : MediaDirection.SENDRECV;
  1580. // When there are 2 remote sources and 1 local source, the first m-line should be set to 'sendrecv' while
  1581. // the second one needs to be set to 'sendonly'.
  1582. } else {
  1583. mLine.direction = idx ? MediaDirection.SENDONLY : MediaDirection.SENDRECV;
  1584. }
  1585. });
  1586. });
  1587. return new RTCSessionDescription({
  1588. type: remoteDescription.type,
  1589. sdp: transformer.toRawSDP()
  1590. });
  1591. };
  1592. /**
  1593. * Returns the codec to be used for screenshare based on the supported codecs and the preferred codec requested
  1594. * through config.js setting.
  1595. *
  1596. * @param {CodecMimeType} defaultCodec - the preferred codec for video tracks.
  1597. * @returns {CodecMimeType}
  1598. */
  1599. TraceablePeerConnection.prototype._getPreferredCodecForScreenshare = function(defaultCodec) {
  1600. // Use the same codec for both camera and screenshare if the client doesn't support the codec selection API.
  1601. if (!this.usesCodecSelectionAPI()) {
  1602. return defaultCodec;
  1603. }
  1604. const { screenshareCodec } = this.codecSettings;
  1605. if (screenshareCodec && this.codecSettings.codecList.find(c => c === screenshareCodec)) {
  1606. return screenshareCodec;
  1607. }
  1608. // Default to AV1 for screenshare if its supported and is not overriden through config.js.
  1609. if (this.codecSettings.codecList.find(c => c === CodecMimeType.AV1)) {
  1610. return CodecMimeType.AV1;
  1611. }
  1612. return defaultCodec;
  1613. };
  1614. /**
  1615. * Munges the stereo flag as well as the opusMaxAverageBitrate in the SDP, based
  1616. * on values set through config.js, if present.
  1617. *
  1618. * @param {RTCSessionDescription} description that needs to be munged.
  1619. * @returns {RTCSessionDescription} the munged description.
  1620. */
  1621. TraceablePeerConnection.prototype._mungeOpus = function(description) {
  1622. const { audioQuality } = this.options;
  1623. if (!audioQuality?.enableOpusDtx && !audioQuality?.stereo && !audioQuality?.opusMaxAverageBitrate) {
  1624. return description;
  1625. }
  1626. const parsedSdp = transform.parse(description.sdp);
  1627. const mLines = parsedSdp.media;
  1628. for (const mLine of mLines) {
  1629. if (mLine.type === 'audio') {
  1630. const { payload } = mLine.rtp.find(protocol => protocol.codec === CodecMimeType.OPUS);
  1631. if (!payload) {
  1632. // eslint-disable-next-line no-continue
  1633. continue;
  1634. }
  1635. let fmtpOpus = mLine.fmtp.find(protocol => protocol.payload === payload);
  1636. if (!fmtpOpus) {
  1637. fmtpOpus = {
  1638. payload,
  1639. config: ''
  1640. };
  1641. }
  1642. const fmtpConfig = transform.parseParams(fmtpOpus.config);
  1643. let sdpChanged = false;
  1644. if (audioQuality?.stereo) {
  1645. fmtpConfig.stereo = 1;
  1646. sdpChanged = true;
  1647. }
  1648. if (audioQuality?.opusMaxAverageBitrate) {
  1649. fmtpConfig.maxaveragebitrate = audioQuality.opusMaxAverageBitrate;
  1650. sdpChanged = true;
  1651. }
  1652. // On Firefox, the OpusDtx enablement has no effect
  1653. if (!browser.isFirefox() && audioQuality?.enableOpusDtx) {
  1654. fmtpConfig.usedtx = 1;
  1655. sdpChanged = true;
  1656. }
  1657. if (!sdpChanged) {
  1658. // eslint-disable-next-line no-continue
  1659. continue;
  1660. }
  1661. let mungedConfig = '';
  1662. for (const key of Object.keys(fmtpConfig)) {
  1663. mungedConfig += `${key}=${fmtpConfig[key]}; `;
  1664. }
  1665. fmtpOpus.config = mungedConfig.trim();
  1666. }
  1667. }
  1668. return new RTCSessionDescription({
  1669. type: description.type,
  1670. sdp: transform.write(parsedSdp)
  1671. });
  1672. };
  1673. /**
  1674. * Sets up the _dtlsTransport object and initializes callbacks for it.
  1675. */
  1676. TraceablePeerConnection.prototype._initializeDtlsTransport = function() {
  1677. // We are assuming here that we only have one bundled transport here
  1678. if (!this.peerconnection.getSenders || this._dtlsTransport) {
  1679. return;
  1680. }
  1681. const senders = this.peerconnection.getSenders();
  1682. if (senders.length !== 0 && senders[0].transport) {
  1683. this._dtlsTransport = senders[0].transport;
  1684. this._dtlsTransport.onerror = error => {
  1685. logger.error(`${this} DtlsTransport error: ${error}`);
  1686. };
  1687. this._dtlsTransport.onstatechange = () => {
  1688. this.trace('dtlsTransport.onstatechange', this._dtlsTransport.state);
  1689. };
  1690. }
  1691. };
  1692. /**
  1693. * Sets the max bitrates on the video m-lines when VP9/AV1 is the selected codec.
  1694. *
  1695. * @param {RTCSessionDescription} description - The local description that needs to be munged.
  1696. * @param {boolean} isLocalSdp - Whether the max bitrate (via b=AS line in SDP) is set on local SDP.
  1697. * @returns RTCSessionDescription
  1698. */
  1699. TraceablePeerConnection.prototype._setMaxBitrates = function(description, isLocalSdp = false) {
  1700. if (!this.codecSettings) {
  1701. return description;
  1702. }
  1703. const parsedSdp = transform.parse(description.sdp);
  1704. // Find all the m-lines associated with the local sources.
  1705. const direction = isLocalSdp ? MediaDirection.RECVONLY : MediaDirection.SENDONLY;
  1706. const mLines = parsedSdp.media.filter(m => m.type === MediaType.VIDEO && m.direction !== direction);
  1707. const currentCodec = this.codecSettings.codecList[0];
  1708. const codecScalabilityModeSettings = this.tpcUtils.codecSettings[currentCodec];
  1709. for (const mLine of mLines) {
  1710. const isDoingVp9KSvc = currentCodec === CodecMimeType.VP9
  1711. && !codecScalabilityModeSettings.scalabilityModeEnabled;
  1712. const localTrack = this.getLocalVideoTracks()
  1713. .find(track => this._localTrackTransceiverMids.get(track.rtcId) === mLine.mid.toString());
  1714. if (localTrack
  1715. && (isDoingVp9KSvc
  1716. // Setting bitrates in the SDP for SVC codecs is no longer needed in the newer versions where
  1717. // maxBitrates from the RTCRtpEncodingParameters directly affect the target bitrate for the encoder.
  1718. || (this.tpcUtils._isRunningInFullSvcMode(currentCodec) && !this.usesCodecSelectionAPI()))) {
  1719. let maxBitrate;
  1720. if (localTrack.getVideoType() === VideoType.DESKTOP) {
  1721. maxBitrate = codecScalabilityModeSettings.maxBitratesVideo.ssHigh;
  1722. } else {
  1723. const { level } = VIDEO_QUALITY_LEVELS.find(lvl => lvl.height <= localTrack.getCaptureResolution());
  1724. maxBitrate = codecScalabilityModeSettings.maxBitratesVideo[level];
  1725. }
  1726. const limit = Math.floor(maxBitrate / 1000);
  1727. // Use only the highest spatial layer bitrates for now as there is no API available yet for configuring
  1728. // the bitrates on the individual SVC layers.
  1729. mLine.bandwidth = [ {
  1730. type: 'AS',
  1731. limit
  1732. } ];
  1733. } else {
  1734. // Clear the bandwidth limit in SDP when VP9 is no longer the preferred codec.
  1735. // This is needed on react native clients as react-native-webrtc returns the
  1736. // SDP that the application passed instead of returning the SDP off the native side.
  1737. // This line automatically gets cleared on web on every renegotiation.
  1738. mLine.bandwidth = undefined;
  1739. }
  1740. }
  1741. return new RTCSessionDescription({
  1742. type: description.type,
  1743. sdp: transform.write(parsedSdp)
  1744. });
  1745. };
  1746. /**
  1747. * Returns the expected send resolution for a local video track based on what encodings are currently active.
  1748. *
  1749. * @param {JitsiLocalTrack} localTrack - The local video track.
  1750. * @returns {number}
  1751. */
  1752. TraceablePeerConnection.prototype.calculateExpectedSendResolution = function(localTrack) {
  1753. const captureResolution = localTrack.getCaptureResolution();
  1754. let result = Math.min(localTrack.maxEnabledResolution, captureResolution);
  1755. if (localTrack.getVideoType() === VideoType.CAMERA) {
  1756. // Find the closest matching resolution based on the current codec, simulcast config and the requested
  1757. // resolution by the bridge or the peer.
  1758. if (this.doesTrueSimulcast(localTrack)) {
  1759. const sender = this.findSenderForTrack(localTrack.getTrack());
  1760. if (!sender) {
  1761. return result;
  1762. }
  1763. const { encodings } = sender.getParameters();
  1764. result = encodings.reduce((maxValue, encoding) => {
  1765. if (encoding.active) {
  1766. // eslint-disable-next-line no-param-reassign
  1767. maxValue = Math.max(maxValue, Math.floor(captureResolution / encoding.scaleResolutionDownBy));
  1768. }
  1769. return maxValue;
  1770. }, 0);
  1771. }
  1772. }
  1773. return result;
  1774. };
  1775. /**
  1776. * Configures the stream encodings for the audio tracks that are added to the peerconnection.
  1777. *
  1778. * @param {JitsiLocalTrack} localAudioTrack - The local audio track.
  1779. * @returns {Promise} promise that will be resolved when the operation is successful and rejected otherwise.
  1780. */
  1781. TraceablePeerConnection.prototype.configureAudioSenderEncodings = function(localAudioTrack = null) {
  1782. if (localAudioTrack) {
  1783. return this.tpcUtils.setEncodings(localAudioTrack);
  1784. }
  1785. const promises = [];
  1786. for (const track of this.getLocalTracks(MediaType.AUDIO)) {
  1787. promises.push(this.tpcUtils.setEncodings(track));
  1788. }
  1789. return Promise.allSettled(promises);
  1790. };
  1791. /**
  1792. * Configures the stream encodings depending on the video type, scalability mode and the bitrate settings for the codec
  1793. * that is currently selected.
  1794. *
  1795. * @param {JitsiLocalTrack} - The local track for which the sender encodings have to configured.
  1796. * @returns {Promise} promise that will be resolved when the operation is successful and rejected otherwise.
  1797. */
  1798. TraceablePeerConnection.prototype.configureVideoSenderEncodings = function(localVideoTrack = null) {
  1799. const preferredCodec = this.codecSettings.codecList[0];
  1800. if (localVideoTrack) {
  1801. return this.setSenderVideoConstraints(
  1802. this._senderMaxHeights.get(localVideoTrack.getSourceName()),
  1803. localVideoTrack,
  1804. preferredCodec);
  1805. }
  1806. const promises = [];
  1807. for (const track of this.getLocalVideoTracks()) {
  1808. const maxHeight = this._senderMaxHeights.get(track.getSourceName()) ?? VIDEO_QUALITY_LEVELS[0].height;
  1809. promises.push(this.setSenderVideoConstraints(maxHeight, track, preferredCodec));
  1810. }
  1811. return Promise.allSettled(promises);
  1812. };
  1813. TraceablePeerConnection.prototype.setLocalDescription = function(description) {
  1814. let localDescription = description;
  1815. this.trace('setLocalDescription::preTransform', dumpSDP(localDescription));
  1816. // Munge stereo flag and opusMaxAverageBitrate based on config.js
  1817. localDescription = this._mungeOpus(localDescription);
  1818. // Munge the order of the codecs based on the preferences set through config.js.
  1819. localDescription = this._mungeCodecOrder(localDescription);
  1820. localDescription = this._setMaxBitrates(localDescription, true);
  1821. localDescription = this._updateAv1DdHeaders(localDescription);
  1822. this.trace('setLocalDescription::postTransform', dumpSDP(localDescription));
  1823. return new Promise((resolve, reject) => {
  1824. this.peerconnection.setLocalDescription(localDescription)
  1825. .then(() => {
  1826. this.trace('setLocalDescriptionOnSuccess');
  1827. const localUfrag = SDPUtil.getUfrag(localDescription.sdp);
  1828. if (localUfrag !== this.localUfrag) {
  1829. this.localUfrag = localUfrag;
  1830. this.eventEmitter.emit(RTCEvents.LOCAL_UFRAG_CHANGED, this, localUfrag);
  1831. }
  1832. this._initializeDtlsTransport();
  1833. resolve();
  1834. }, err => {
  1835. this.trace('setLocalDescriptionOnFailure', err);
  1836. this.eventEmitter.emit(RTCEvents.SET_LOCAL_DESCRIPTION_FAILED, err, this);
  1837. reject(err);
  1838. });
  1839. });
  1840. };
  1841. TraceablePeerConnection.prototype.setRemoteDescription = function(description) {
  1842. let remoteDescription = description;
  1843. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  1844. // Munge stereo flag and opusMaxAverageBitrate based on config.js
  1845. remoteDescription = this._mungeOpus(remoteDescription);
  1846. if (!this.isP2P) {
  1847. const currentDescription = this.peerconnection.remoteDescription;
  1848. remoteDescription = this.interop.toUnifiedPlan(remoteDescription, currentDescription);
  1849. this.trace('setRemoteDescription::postTransform (Unified)', dumpSDP(remoteDescription));
  1850. }
  1851. if (this.isSpatialScalabilityOn()) {
  1852. remoteDescription = this.tpcUtils.insertUnifiedPlanSimulcastReceive(remoteDescription);
  1853. this.trace('setRemoteDescription::postTransform (sim receive)', dumpSDP(remoteDescription));
  1854. }
  1855. remoteDescription = this.tpcUtils.ensureCorrectOrderOfSsrcs(remoteDescription);
  1856. this.trace('setRemoteDescription::postTransform (correct ssrc order)', dumpSDP(remoteDescription));
  1857. // Munge the order of the codecs based on the preferences set through config.js.
  1858. remoteDescription = this._mungeCodecOrder(remoteDescription);
  1859. remoteDescription = this._setMaxBitrates(remoteDescription);
  1860. remoteDescription = this._updateAv1DdHeaders(remoteDescription);
  1861. this.trace('setRemoteDescription::postTransform (munge codec order)', dumpSDP(remoteDescription));
  1862. return new Promise((resolve, reject) => {
  1863. this.peerconnection.setRemoteDescription(remoteDescription)
  1864. .then(() => {
  1865. this.trace('setRemoteDescriptionOnSuccess');
  1866. const remoteUfrag = SDPUtil.getUfrag(remoteDescription.sdp);
  1867. if (remoteUfrag !== this.remoteUfrag) {
  1868. this.remoteUfrag = remoteUfrag;
  1869. this.eventEmitter.emit(RTCEvents.REMOTE_UFRAG_CHANGED, this, remoteUfrag);
  1870. }
  1871. this._initializeDtlsTransport();
  1872. resolve();
  1873. }, err => {
  1874. this.trace('setRemoteDescriptionOnFailure', err);
  1875. this.eventEmitter.emit(RTCEvents.SET_REMOTE_DESCRIPTION_FAILED, err, this);
  1876. reject(err);
  1877. });
  1878. });
  1879. };
  1880. /**
  1881. * Changes the resolution of the video stream that is sent to the peer based on the resolution requested by the peer
  1882. * and user preference, sets the degradation preference on the sender based on the video type, configures the maximum
  1883. * bitrates on the send stream.
  1884. *
  1885. * @param {number} frameHeight - The max frame height to be imposed on the outgoing video stream.
  1886. * @param {JitsiLocalTrack} - The local track for which the sender constraints have to be applied.
  1887. * @param {preferredCodec} - The video codec that needs to be configured on the sender associated with the video source.
  1888. * @returns {Promise} promise that will be resolved when the operation is successful and rejected otherwise.
  1889. */
  1890. TraceablePeerConnection.prototype.setSenderVideoConstraints = function(frameHeight, localVideoTrack, preferredCodec) {
  1891. if (frameHeight < 0 || isNaN(frameHeight)) {
  1892. throw new Error(`Invalid frameHeight: ${frameHeight}`);
  1893. }
  1894. if (!localVideoTrack) {
  1895. throw new Error('Local video track is missing');
  1896. }
  1897. const sourceName = localVideoTrack.getSourceName();
  1898. // Ignore sender constraints if the video track is muted.
  1899. if (localVideoTrack.isMuted()) {
  1900. this._senderMaxHeights.set(sourceName, frameHeight);
  1901. return Promise.resolve();
  1902. }
  1903. const codec = preferredCodec ?? this.codecSettings.codecList[0];
  1904. return this._updateVideoSenderParameters(
  1905. () => this._updateVideoSenderEncodings(frameHeight, localVideoTrack, codec));
  1906. };
  1907. /**
  1908. * Returns a wrapped-up promise so that the setParameters() call on the RTCRtpSender for video sources are chained.
  1909. * This is needed on Chrome as it resets the transaction id after executing setParameters() and can affect the next on
  1910. * the fly updates if they are not chained.
  1911. * https://chromium.googlesource.com/external/webrtc/+/master/pc/rtp_sender.cc#340
  1912. * @param {Function} nextFunction - The function to be called when the last video sender update promise is settled.
  1913. * @returns {Promise}
  1914. */
  1915. TraceablePeerConnection.prototype._updateVideoSenderParameters = function(nextFunction) {
  1916. const nextPromise = this._lastVideoSenderUpdatePromise
  1917. .finally(nextFunction);
  1918. this._lastVideoSenderUpdatePromise = nextPromise;
  1919. return nextPromise;
  1920. };
  1921. /**
  1922. * Configures the video stream with resolution / degradation / maximum bitrates
  1923. *
  1924. * @param {number} frameHeight - The max frame height to be imposed on the outgoing video stream.
  1925. * @param {JitsiLocalTrack} - The local track for which the sender constraints have to be applied.
  1926. * @param {preferredCodec} - The video codec that needs to be configured on the sender associated with the video source.
  1927. * @returns {Promise} promise that will be resolved when the operation is successful and rejected otherwise.
  1928. */
  1929. TraceablePeerConnection.prototype._updateVideoSenderEncodings = function(frameHeight, localVideoTrack, preferredCodec) {
  1930. const videoSender = this.findSenderForTrack(localVideoTrack.getTrack());
  1931. const videoType = localVideoTrack.getVideoType();
  1932. const isScreensharingTrack = videoType === VideoType.DESKTOP;
  1933. if (!videoSender) {
  1934. return Promise.resolve();
  1935. }
  1936. const parameters = videoSender.getParameters();
  1937. if (!parameters?.encodings?.length) {
  1938. return Promise.resolve();
  1939. }
  1940. const isSharingLowFpsScreen = isScreensharingTrack && this._capScreenshareBitrate;
  1941. // Set the degradation preference.
  1942. const preference = isSharingLowFpsScreen
  1943. ? DEGRADATION_PREFERENCE_DESKTOP // Prefer resolution for low fps share.
  1944. : DEGRADATION_PREFERENCE_CAMERA; // Prefer frame-rate for high fps share and camera.
  1945. parameters.degradationPreference = preference;
  1946. // Calculate the encodings active state based on the resolution requested by the bridge.
  1947. const codecForCamera = preferredCodec ?? this.getConfiguredVideoCodec(localVideoTrack);
  1948. const codec = isScreensharingTrack ? this._getPreferredCodecForScreenshare(codecForCamera) : codecForCamera;
  1949. const activeState = this.tpcUtils.calculateEncodingsActiveState(localVideoTrack, codec, frameHeight);
  1950. let bitrates = this.tpcUtils.calculateEncodingsBitrates(localVideoTrack, codec, frameHeight);
  1951. const scalabilityModes = this.tpcUtils.calculateEncodingsScalabilityMode(localVideoTrack, codec, frameHeight);
  1952. let scaleFactors = this.tpcUtils.calculateEncodingsScaleFactor(localVideoTrack, codec, frameHeight);
  1953. const sourceName = localVideoTrack.getSourceName();
  1954. let needsUpdate = false;
  1955. // Do not configure 'scaleResolutionDownBy' and 'maxBitrate' for encoders running in VP9 legacy K-SVC mode since
  1956. // the browser sends only the lowest resolution layer when those are configured. Those fields need to be reset in
  1957. // case they were set when the endpoint was encoding video using the other codecs before switching over to VP9
  1958. // K-SVC codec.
  1959. if (codec === CodecMimeType.VP9
  1960. && this.isSpatialScalabilityOn()
  1961. && !this.tpcUtils.codecSettings[codec].scalabilityModeEnabled) {
  1962. scaleFactors = scaleFactors.map(() => undefined);
  1963. bitrates = bitrates.map(() => undefined);
  1964. }
  1965. for (const idx in parameters.encodings) {
  1966. if (parameters.encodings.hasOwnProperty(idx)) {
  1967. const {
  1968. active = undefined,
  1969. codec: currentCodec = undefined,
  1970. maxBitrate = undefined,
  1971. scalabilityMode = undefined,
  1972. scaleResolutionDownBy = undefined
  1973. } = parameters.encodings[idx];
  1974. if (active !== activeState[idx]) {
  1975. parameters.encodings[idx].active = activeState[idx];
  1976. needsUpdate = true;
  1977. }
  1978. // Firefox doesn't follow the spec and lets application specify the degradation preference on the
  1979. // encodings.
  1980. browser.isFirefox() && (parameters.encodings[idx].degradationPreference = preference);
  1981. if (scaleResolutionDownBy !== scaleFactors[idx]) {
  1982. parameters.encodings[idx].scaleResolutionDownBy = scaleFactors[idx];
  1983. needsUpdate = true;
  1984. }
  1985. if (maxBitrate !== bitrates[idx]) {
  1986. parameters.encodings[idx].maxBitrate = bitrates[idx];
  1987. needsUpdate = true;
  1988. }
  1989. // Configure scalability mode when its supported and enabled.
  1990. if (scalabilityModes) {
  1991. if (scalabilityMode !== scalabilityModes[idx]) {
  1992. parameters.encodings[idx].scalabilityMode = scalabilityModes[idx];
  1993. needsUpdate = true;
  1994. }
  1995. } else {
  1996. parameters.encodings[idx].scalabilityMode = undefined;
  1997. }
  1998. const expectedPattern = `${MediaType.VIDEO}/${codec.toUpperCase()}`;
  1999. // Configure the codec here if its supported.
  2000. if (this.usesCodecSelectionAPI() && currentCodec?.mimeType !== expectedPattern) {
  2001. const matchingCodec = parameters.codecs.find(pt => pt.mimeType === expectedPattern);
  2002. parameters.encodings[idx].codec = matchingCodec;
  2003. needsUpdate = true;
  2004. Statistics.sendAnalytics(
  2005. VIDEO_CODEC_CHANGED,
  2006. {
  2007. value: codec,
  2008. videoType
  2009. });
  2010. }
  2011. }
  2012. }
  2013. if (!needsUpdate) {
  2014. this._senderMaxHeights.set(sourceName, frameHeight);
  2015. return Promise.resolve();
  2016. }
  2017. logger.info(`${this} setting max height=${frameHeight},encodings=${JSON.stringify(parameters.encodings)}`);
  2018. return videoSender.setParameters(parameters).then(() => {
  2019. this._senderMaxHeights.set(sourceName, frameHeight);
  2020. localVideoTrack.maxEnabledResolution = frameHeight;
  2021. this.eventEmitter.emit(RTCEvents.LOCAL_TRACK_MAX_ENABLED_RESOLUTION_CHANGED, localVideoTrack);
  2022. });
  2023. };
  2024. /**
  2025. * Enables/disables outgoing video media transmission on this peer connection. When disabled the stream encoding's
  2026. * active state is enabled or disabled to send or stop the media.
  2027. * @param {boolean} active <tt>true</tt> to enable video media transmission or <tt>false</tt> to disable. If the value
  2028. * is not a boolean the call will have no effect.
  2029. * @return {Promise} A promise that is resolved when the change is succesful, rejected otherwise.
  2030. * @public
  2031. */
  2032. TraceablePeerConnection.prototype.setVideoTransferActive = function(active) {
  2033. logger.debug(`${this} video transfer active: ${active}`);
  2034. const changed = this.videoTransferActive !== active;
  2035. this.videoTransferActive = active;
  2036. if (changed) {
  2037. return this.tpcUtils.setMediaTransferActive(active, MediaType.VIDEO);
  2038. }
  2039. return Promise.resolve();
  2040. };
  2041. /**
  2042. * Sends DTMF tones if possible.
  2043. *
  2044. * @param {string} tones - The DTMF tones string as defined by {@code RTCDTMFSender.insertDTMF}, 'tones' argument.
  2045. * @param {number} duration - The amount of time in milliseconds that each DTMF should last. It's 200ms by default.
  2046. * @param {number} interToneGap - The length of time in miliseconds to wait between tones. It's 200ms by default.
  2047. *
  2048. * @returns {void}
  2049. */
  2050. TraceablePeerConnection.prototype.sendTones = function(tones, duration = 200, interToneGap = 200) {
  2051. if (!this._dtmfSender) {
  2052. if (this.peerconnection.getSenders) {
  2053. const rtpSender = this.peerconnection.getSenders().find(s => s.dtmf);
  2054. this._dtmfSender = rtpSender && rtpSender.dtmf;
  2055. this._dtmfSender && logger.info(`${this} initialized DTMFSender using getSenders`);
  2056. }
  2057. if (!this._dtmfSender) {
  2058. const localAudioTrack = Array.from(this.localTracks.values()).find(t => t.isAudioTrack());
  2059. if (this.peerconnection.createDTMFSender && localAudioTrack) {
  2060. this._dtmfSender = this.peerconnection.createDTMFSender(localAudioTrack.getTrack());
  2061. }
  2062. this._dtmfSender && logger.info(`${this} initialized DTMFSender using deprecated createDTMFSender`);
  2063. }
  2064. if (this._dtmfSender) {
  2065. this._dtmfSender.ontonechange = this._onToneChange.bind(this);
  2066. }
  2067. }
  2068. if (this._dtmfSender) {
  2069. if (this._dtmfSender.toneBuffer) {
  2070. this._dtmfTonesQueue.push({
  2071. tones,
  2072. duration,
  2073. interToneGap
  2074. });
  2075. return;
  2076. }
  2077. this._dtmfSender.insertDTMF(tones, duration, interToneGap);
  2078. } else {
  2079. logger.warn(`${this} sendTones - failed to select DTMFSender`);
  2080. }
  2081. };
  2082. /**
  2083. * Callback ivoked by {@code this._dtmfSender} when it has finished playing
  2084. * a single tone.
  2085. *
  2086. * @param {Object} event - The tonechange event which indicates what characters
  2087. * are left to be played for the current tone.
  2088. * @private
  2089. * @returns {void}
  2090. */
  2091. TraceablePeerConnection.prototype._onToneChange = function(event) {
  2092. // An empty event.tone indicates the current tones have finished playing.
  2093. // Automatically start playing any queued tones on finish.
  2094. if (this._dtmfSender && event.tone === '' && this._dtmfTonesQueue.length) {
  2095. const { tones, duration, interToneGap } = this._dtmfTonesQueue.shift();
  2096. this._dtmfSender.insertDTMF(tones, duration, interToneGap);
  2097. }
  2098. };
  2099. /**
  2100. * Closes underlying WebRTC PeerConnection instance and removes all remote
  2101. * tracks by emitting {@link RTCEvents.REMOTE_TRACK_REMOVED} for each one of
  2102. * them.
  2103. */
  2104. TraceablePeerConnection.prototype.close = function() {
  2105. this.trace('stop');
  2106. // Off SignalingEvents
  2107. this.signalingLayer.off(SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  2108. this.signalingLayer.off(SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  2109. this.peerconnection.removeEventListener('track', this.onTrack);
  2110. if (FeatureFlags.isSsrcRewritingSupported()) {
  2111. for (const remoteTrack of this.remoteTracksBySsrc.values()) {
  2112. this._removeRemoteTrack(remoteTrack);
  2113. }
  2114. this.remoteTracksBySsrc.clear();
  2115. } else {
  2116. for (const peerTracks of this.remoteTracks.values()) {
  2117. for (const remoteTracks of peerTracks.values()) {
  2118. for (const remoteTrack of remoteTracks) {
  2119. this._removeRemoteTrack(remoteTrack);
  2120. }
  2121. }
  2122. }
  2123. this.remoteTracks.clear();
  2124. }
  2125. this._dtmfSender = null;
  2126. this._dtmfTonesQueue = [];
  2127. if (!this.rtc._removePeerConnection(this)) {
  2128. logger.error(`${this} rtc._removePeerConnection returned false`);
  2129. }
  2130. if (this.statsinterval !== null) {
  2131. window.clearInterval(this.statsinterval);
  2132. this.statsinterval = null;
  2133. }
  2134. logger.info(`${this} Closing peerconnection`);
  2135. this.peerconnection.close();
  2136. };
  2137. TraceablePeerConnection.prototype.createAnswer = function(constraints) {
  2138. return this._createOfferOrAnswer(false /* answer */, constraints);
  2139. };
  2140. TraceablePeerConnection.prototype.createOffer = function(constraints) {
  2141. return this._createOfferOrAnswer(true /* offer */, constraints);
  2142. };
  2143. TraceablePeerConnection.prototype._createOfferOrAnswer = function(isOffer, constraints) {
  2144. const logName = isOffer ? 'Offer' : 'Answer';
  2145. this.trace(`create${logName}`, JSON.stringify(constraints, null, ' '));
  2146. const handleSuccess = (resultSdp, resolveFn, rejectFn) => {
  2147. try {
  2148. this.trace(
  2149. `create${logName}OnSuccess::preTransform`, dumpSDP(resultSdp));
  2150. // Munge local description to add 3 SSRCs for video tracks when spatial scalability is enabled.
  2151. if (this.isSpatialScalabilityOn() && browser.usesSdpMungingForSimulcast()) {
  2152. // eslint-disable-next-line no-param-reassign
  2153. resultSdp = this.simulcast.mungeLocalDescription(resultSdp);
  2154. this.trace(`create${logName} OnSuccess::postTransform (simulcast)`, dumpSDP(resultSdp));
  2155. }
  2156. if (!this.options.disableRtx && browser.usesSdpMungingForSimulcast()) {
  2157. // eslint-disable-next-line no-param-reassign
  2158. resultSdp = new RTCSessionDescription({
  2159. type: resultSdp.type,
  2160. sdp: this.rtxModifier.modifyRtxSsrcs(resultSdp.sdp)
  2161. });
  2162. this.trace(
  2163. `create${logName}`
  2164. + 'OnSuccess::postTransform (rtx modifier)',
  2165. dumpSDP(resultSdp));
  2166. }
  2167. this._processAndExtractSourceInfo(resultSdp.sdp);
  2168. resolveFn(resultSdp);
  2169. } catch (e) {
  2170. this.trace(`create${logName}OnError`, e);
  2171. this.trace(`create${logName}OnError`, dumpSDP(resultSdp));
  2172. logger.error(`${this} create${logName}OnError`, e, dumpSDP(resultSdp));
  2173. rejectFn(e);
  2174. }
  2175. };
  2176. const handleFailure = (err, rejectFn) => {
  2177. this.trace(`create${logName}OnFailure`, err);
  2178. const eventType
  2179. = isOffer
  2180. ? RTCEvents.CREATE_OFFER_FAILED
  2181. : RTCEvents.CREATE_ANSWER_FAILED;
  2182. this.eventEmitter.emit(eventType, err, this);
  2183. rejectFn(err);
  2184. };
  2185. // Set the codec preference before creating an offer or answer so that the generated SDP will have
  2186. // the correct preference order.
  2187. if (browser.supportsCodecPreferences() && this.codecSettings) {
  2188. const { codecList, mediaType } = this.codecSettings;
  2189. const transceivers = this.peerconnection.getTransceivers()
  2190. .filter(t => t.receiver && t.receiver?.track?.kind === mediaType);
  2191. let capabilities = RTCRtpReceiver.getCapabilities(mediaType)?.codecs;
  2192. if (transceivers.length && capabilities) {
  2193. // Rearrange the codec list as per the preference order.
  2194. for (const codec of codecList.slice().reverse()) {
  2195. // Move the desired codecs (all variations of it as well) to the beginning of the list
  2196. /* eslint-disable-next-line arrow-body-style */
  2197. capabilities.sort(caps => {
  2198. return caps.mimeType.toLowerCase() === `${mediaType}/${codec}` ? -1 : 1;
  2199. });
  2200. }
  2201. // Disable ulpfec and RED on the p2p peerconnection.
  2202. if (this.isP2P && mediaType === MediaType.VIDEO) {
  2203. capabilities = capabilities
  2204. .filter(caps => caps.mimeType.toLowerCase() !== `${MediaType.VIDEO}/${CodecMimeType.ULPFEC}`
  2205. && caps.mimeType.toLowerCase() !== `${MediaType.VIDEO}/${CodecMimeType.RED}`);
  2206. }
  2207. // Apply codec preference to all the transceivers associated with the given media type.
  2208. for (const transceiver of transceivers) {
  2209. transceiver.setCodecPreferences(capabilities);
  2210. }
  2211. }
  2212. }
  2213. return new Promise((resolve, reject) => {
  2214. let oaPromise;
  2215. if (isOffer) {
  2216. oaPromise = this.peerconnection.createOffer(constraints);
  2217. } else {
  2218. oaPromise = this.peerconnection.createAnswer(constraints);
  2219. }
  2220. oaPromise
  2221. .then(
  2222. sdp => handleSuccess(sdp, resolve, reject),
  2223. error => handleFailure(error, reject));
  2224. });
  2225. };
  2226. /**
  2227. * Extract primary SSRC from given {@link TrackSSRCInfo} object.
  2228. * @param {TrackSSRCInfo} ssrcObj
  2229. * @return {number|null} the primary SSRC or <tt>null</tt>
  2230. */
  2231. TraceablePeerConnection.prototype._extractPrimarySSRC = function(ssrcObj) {
  2232. if (ssrcObj && ssrcObj.groups && ssrcObj.groups.length) {
  2233. return ssrcObj.groups[0].ssrcs[0];
  2234. } else if (ssrcObj && ssrcObj.ssrcs && ssrcObj.ssrcs.length) {
  2235. return ssrcObj.ssrcs[0];
  2236. }
  2237. return null;
  2238. };
  2239. /**
  2240. * Track the SSRCs seen so far.
  2241. * @param {number} ssrc - SSRC.
  2242. * @return {boolean} - Whether this is a new SSRC.
  2243. */
  2244. TraceablePeerConnection.prototype.addRemoteSsrc = function(ssrc) {
  2245. const existing = this.remoteSSRCs.has(ssrc);
  2246. if (!existing) {
  2247. this.remoteSSRCs.add(ssrc);
  2248. }
  2249. return !existing;
  2250. };
  2251. TraceablePeerConnection.prototype.addIceCandidate = function(candidate) {
  2252. this.trace('addIceCandidate', JSON.stringify({
  2253. candidate: candidate.candidate,
  2254. sdpMid: candidate.sdpMid,
  2255. sdpMLineIndex: candidate.sdpMLineIndex,
  2256. usernameFragment: candidate.usernameFragment
  2257. }, null, ' '));
  2258. return this.peerconnection.addIceCandidate(candidate);
  2259. };
  2260. /**
  2261. * Obtains call-related stats from the peer connection.
  2262. *
  2263. * @returns {Promise<Object>} Promise which resolves with data providing statistics about
  2264. * the peerconnection.
  2265. */
  2266. TraceablePeerConnection.prototype.getStats = function() {
  2267. return this.peerconnection.getStats();
  2268. };
  2269. /**
  2270. * Creates a text representation of this <tt>TraceablePeerConnection</tt>
  2271. * instance.
  2272. * @return {string}
  2273. */
  2274. TraceablePeerConnection.prototype.toString = function() {
  2275. return `TPC[id=${this.id},type=${this.isP2P ? 'P2P' : 'JVB'}]`;
  2276. };