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

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