Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

TraceablePeerConnection.js 94KB

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