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

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