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

TraceablePeerConnection.js 109KB

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