modified lib-jitsi-meet dev repo
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TraceablePeerConnection.js 105KB

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