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

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