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

TraceablePeerConnection.js 118KB

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