Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

TraceablePeerConnection.js 114KB

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