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

TraceablePeerConnection.js 117KB

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