Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

TraceablePeerConnection.js 107KB

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