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

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