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 97KB

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