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

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