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

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