modified lib-jitsi-meet dev repo
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

TraceablePeerConnection.js 110KB

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