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

TraceablePeerConnection.js 94KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559
  1. import { getLogger } from '@jitsi/logger';
  2. import { cloneDeep } from 'lodash-es';
  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 { SSRC_GROUP_SEMANTICS, VIDEO_QUALITY_LEVELS } from '../../service/RTC/StandardVideoQualitySettings';
  11. import { VideoType } from '../../service/RTC/VideoType';
  12. import { VIDEO_CODEC_CHANGED } from '../../service/statistics/AnalyticsEvents';
  13. import { SS_DEFAULT_FRAME_RATE } from '../RTC/ScreenObtainer';
  14. import browser from '../browser';
  15. import FeatureFlags from '../flags/FeatureFlags';
  16. import LocalSdpMunger from '../sdp/LocalSdpMunger';
  17. import RtxModifier from '../sdp/RtxModifier';
  18. import SDP from '../sdp/SDP';
  19. import SDPUtil from '../sdp/SDPUtil';
  20. import SdpSimulcast from '../sdp/SdpSimulcast';
  21. import { SdpTransformWrap } from '../sdp/SdpTransformUtil';
  22. import Statistics from '../statistics/statistics';
  23. import { isValidNumber } from '../util/MathUtil';
  24. import JitsiRemoteTrack from './JitsiRemoteTrack';
  25. import RTCUtils from './RTCUtils';
  26. import { TPCUtils } from './TPCUtils';
  27. // FIXME SDP tools should end up in some kind of util module
  28. const logger = getLogger('modules/RTC/TraceablePeerConnection');
  29. const DEGRADATION_PREFERENCE_CAMERA = 'maintain-framerate';
  30. const DEGRADATION_PREFERENCE_DESKTOP = 'maintain-resolution';
  31. /* eslint-disable max-params */
  32. /**
  33. * Creates new instance of 'TraceablePeerConnection'.
  34. *
  35. * @param {RTC} rtc the instance of <tt>RTC</tt> service
  36. * @param {number} id the peer connection id assigned by the parent RTC module.
  37. * @param {SignalingLayer} signalingLayer the signaling layer instance
  38. * @param {object} pcConfig The {@code RTCConfiguration} to use for the WebRTC peer connection.
  39. * @param {object} constraints WebRTC 'PeerConnection' constraints
  40. * @param {boolean} isP2P indicates whether or not the new instance will be used in a peer to peer connection.
  41. * @param {object} options <tt>TracablePeerConnection</tt> config options.
  42. * @param {Object} options.audioQuality - Quality settings to applied on the outbound audio stream.
  43. * @param {boolean} options.capScreenshareBitrate if set to true, lower layers will be disabled for screenshare.
  44. * @param {Array<CodecMimeType>} options.codecSettings - codec settings to be applied for video streams.
  45. * @param {boolean} options.disableSimulcast if set to 'true' will disable the simulcast.
  46. * @param {boolean} options.disableRtx if set to 'true' will disable the RTX.
  47. * @param {boolean} options.enableInsertableStreams set to true when the insertable streams constraints is to be
  48. * enabled on the PeerConnection.
  49. * @param {boolean} options.forceTurnRelay If set to true, the browser will generate only Relay ICE candidates.
  50. * @param {boolean} options.startSilent If set to 'true' no audio will be sent or received.
  51. * @param {Object} options.videoQuality - Quality settings to applied on the outbound video streams.
  52. *
  53. * FIXME: initially the purpose of TraceablePeerConnection was to be able to
  54. * debug the peer connection. Since many other responsibilities have been added
  55. * it would make sense to extract a separate class from it and come up with
  56. * a more suitable name.
  57. *
  58. * @constructor
  59. */
  60. export default function TraceablePeerConnection(
  61. rtc,
  62. id,
  63. signalingLayer,
  64. pcConfig,
  65. constraints,
  66. isP2P,
  67. options) {
  68. /**
  69. * Indicates whether or not this peer connection instance is actively
  70. * sending/receiving audio media. When set to <tt>false</tt> the SDP audio
  71. * media direction will be adjusted to 'inactive' in order to suspend
  72. * the transmission.
  73. * @type {boolean}
  74. * @private
  75. */
  76. this.audioTransferActive = !(options.startSilent === true);
  77. /**
  78. * The DTMF sender instance used to send DTMF tones.
  79. *
  80. * @type {RTCDTMFSender|undefined}
  81. * @private
  82. */
  83. this._dtmfSender = undefined;
  84. /**
  85. * @typedef {Object} TouchToneRequest
  86. * @property {string} tones - The DTMF tones string as defined by
  87. * {@code RTCDTMFSender.insertDTMF}, 'tones' argument.
  88. * @property {number} duration - The amount of time in milliseconds that
  89. * each DTMF should last.
  90. * @property {string} interToneGap - The length of time in miliseconds to
  91. * wait between tones.
  92. */
  93. /**
  94. * TouchToneRequests which are waiting to be played. This queue is filled
  95. * if there are touch tones currently being played.
  96. *
  97. * @type {Array<TouchToneRequest>}
  98. * @private
  99. */
  100. this._dtmfTonesQueue = [];
  101. /**
  102. * Indicates whether or not this peer connection instance is actively
  103. * sending/receiving video media. When set to <tt>false</tt> the SDP video
  104. * media direction will be adjusted to 'inactive' in order to suspend
  105. * the transmission.
  106. * @type {boolean}
  107. * @private
  108. */
  109. this.videoTransferActive = true;
  110. /**
  111. * The parent instance of RTC service which created this
  112. * <tt>TracablePeerConnection</tt>.
  113. * @type {RTC}
  114. */
  115. this.rtc = rtc;
  116. /**
  117. * The peer connection identifier assigned by the RTC module.
  118. * @type {number}
  119. */
  120. this.id = id;
  121. /**
  122. * Indicates whether or not this instance is used in a peer to peer
  123. * connection.
  124. * @type {boolean}
  125. */
  126. this.isP2P = isP2P;
  127. /**
  128. * A map that holds remote tracks signaled on the peerconnection indexed by their SSRC.
  129. * @type {Map<number, JitsiRemoteTrack>}
  130. */
  131. this.remoteTracksBySsrc = new Map();
  132. /**
  133. * The map holds remote tracks associated with this peer connection. It maps user's JID to media type and a set of
  134. * remote tracks.
  135. * @type {Map<string, Map<MediaType, Set<JitsiRemoteTrack>>>}
  136. */
  137. this.remoteTracks = new Map();
  138. /**
  139. * A map which stores local tracks mapped by {@link JitsiLocalTrack.rtcId}
  140. * @type {Map<number, JitsiLocalTrack>}
  141. */
  142. this.localTracks = new Map();
  143. /**
  144. * @typedef {Object} TPCGroupInfo
  145. * @property {string} semantics the SSRC groups semantics
  146. * @property {Array<number>} ssrcs group's SSRCs in order where the first
  147. * one is group's primary SSRC, the second one is secondary (RTX) and so
  148. * on...
  149. */
  150. /**
  151. * @typedef {Object} TPCSSRCInfo
  152. * @property {Array<number>} ssrcs an array which holds all track's SSRCs
  153. * @property {Array<TPCGroupInfo>} groups an array stores all track's SSRC
  154. * groups
  155. */
  156. /**
  157. * Holds the info about local track's SSRCs mapped per their
  158. * {@link JitsiLocalTrack.rtcId}
  159. * @type {Map<number, TPCSSRCInfo>}
  160. */
  161. this.localSSRCs = new Map();
  162. /**
  163. * The set of remote SSRCs seen so far.
  164. * Distinguishes new SSRCs from those that have been remapped.
  165. * @type {Set<number>}
  166. */
  167. this.remoteSSRCs = new Set();
  168. /**
  169. * Mapping of source-names and their associated SSRCs that have been signaled by the JVB.
  170. * @type {Map<string, number>}
  171. */
  172. this.remoteSources = new Map();
  173. /**
  174. * The local ICE username fragment for this session.
  175. */
  176. this.localUfrag = null;
  177. /**
  178. * The remote ICE username fragment for this session.
  179. */
  180. this.remoteUfrag = null;
  181. /**
  182. * The DTLS transport object for the PeerConnection.
  183. * Note: this assume only one shared transport exists because we bundled
  184. * all streams on the same underlying transport.
  185. */
  186. this._dtlsTransport = null;
  187. /**
  188. * The signaling layer which operates this peer connection.
  189. * @type {SignalingLayer}
  190. */
  191. this.signalingLayer = signalingLayer;
  192. // SignalingLayer listeners
  193. this._peerVideoTypeChanged = this._peerVideoTypeChanged.bind(this);
  194. this.signalingLayer.on(SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  195. this._peerMutedChanged = this._peerMutedChanged.bind(this);
  196. this.signalingLayer.on(SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  197. this.options = options;
  198. // Setup SignalingLayer listeners for source-name based events.
  199. this.signalingLayer.on(SignalingEvents.SOURCE_MUTED_CHANGED,
  200. (sourceName, isMuted) => this._sourceMutedChanged(sourceName, isMuted));
  201. this.signalingLayer.on(SignalingEvents.SOURCE_VIDEO_TYPE_CHANGED,
  202. (sourceName, videoType) => this._sourceVideoTypeChanged(sourceName, videoType));
  203. // Make sure constraints is properly formatted in order to provide information about whether or not this
  204. // connection is P2P to rtcstats.
  205. const safeConstraints = constraints || {};
  206. safeConstraints.optional = safeConstraints.optional || [];
  207. // The `optional` parameter needs to be of type array, otherwise chrome will throw an error.
  208. // Firefox and Safari just ignore it.
  209. if (Array.isArray(safeConstraints.optional)) {
  210. safeConstraints.optional.push({ rtcStatsSFUP2P: this.isP2P });
  211. } else {
  212. logger.warn('Optional param is not an array, rtcstats p2p data is omitted.');
  213. }
  214. this.peerconnection = new RTCPeerConnection(pcConfig, safeConstraints);
  215. this.tpcUtils = new TPCUtils(this, {
  216. audioQuality: options.audioQuality,
  217. isP2P: this.isP2P,
  218. videoQuality: options.videoQuality
  219. });
  220. this.updateLog = [];
  221. this.stats = {};
  222. this.statsinterval = null;
  223. /**
  224. * Flag used to indicate if low fps screenshare is desired.
  225. */
  226. this._capScreenshareBitrate = this.options.capScreenshareBitrate;
  227. /**
  228. * Codec preferences set for the peerconnection through config.js.
  229. */
  230. this.codecSettings = this.options.codecSettings;
  231. /**
  232. * Flag used to indicate if RTCRtpTransceiver#setCodecPreferences is to be used instead of SDP
  233. * munging for codec selection.
  234. */
  235. browser.supportsCodecPreferences()
  236. && logger.info('Using RTCRtpTransceiver#setCodecPreferences for codec selection');
  237. /**
  238. * Flag used to indicate if the codecs are configured using the codec selection API without having the need to
  239. * trigger a renegotiation for the change to be effective.
  240. */
  241. this._usesCodecSelectionAPI = this.options.usesCodecSelectionAPI;
  242. /**
  243. * Indicates whether an audio track has ever been added to the peer connection.
  244. */
  245. this._hasHadAudioTrack = false;
  246. /**
  247. * Indicates whether a video track has ever been added to the peer connection.
  248. */
  249. this._hasHadVideoTrack = false;
  250. /**
  251. * @type {number} The max number of stats to keep in this.stats. Limit to
  252. * 300 values, i.e. 5 minutes; set to 0 to disable
  253. */
  254. this.maxstats = options.maxstats;
  255. this.simulcast = new SdpSimulcast();
  256. /**
  257. * Munges local SDP provided to the Jingle Session in order to prevent from
  258. * sending SSRC updates on attach/detach and mute/unmute (for video).
  259. * @type {LocalSdpMunger}
  260. */
  261. this.localSdpMunger = new LocalSdpMunger(this, this.rtc.getLocalEndpointId());
  262. /**
  263. * TracablePeerConnection uses RTC's eventEmitter
  264. * @type {EventEmitter}
  265. */
  266. this.eventEmitter = rtc.eventEmitter;
  267. this.rtxModifier = new RtxModifier();
  268. /**
  269. * The height constraints to be applied on the sender per local video source (source name as the key).
  270. * @type {Map<string, number>}
  271. */
  272. this._senderMaxHeights = new Map();
  273. /**
  274. * Holds the RTCRtpTransceiver mids that the local tracks are attached to, mapped per their
  275. * {@link JitsiLocalTrack.rtcId}.
  276. * @type {Map<string, string>}
  277. */
  278. this.localTrackTransceiverMids = new Map();
  279. /**
  280. * Holds the SSRC map for the local tracks mapped by their source names.
  281. *
  282. * @type {Map<string, TPCSourceInfo>}
  283. * @property {string} msid - The track's MSID.
  284. * @property {Array<string>} ssrcs - The SSRCs associated with the track.
  285. * @property {Array<TPCGroupInfo>} groups - The SSRC groups associated with the track.
  286. */
  287. this._localSsrcMap = null;
  288. /**
  289. * Holds the SSRC map for the remote tracks mapped by their source names.
  290. *
  291. * @type {Map<string, TPCSourceInfo>}
  292. * @property {string} mediaType - The media type of the track.
  293. * @property {string} msid - The track's MSID.
  294. * @property {Array<TPCGroupInfo>} groups - The SSRC groups associated with the track.
  295. * @property {Array<string>} ssrcList - The SSRCs associated with the track.
  296. * @property {VideoType} videoType - The videoType of the track (undefined for audio tracks).
  297. */
  298. this._remoteSsrcMap = new Map();
  299. // override as desired
  300. this.trace = (what, info) => {
  301. logger.trace(what, info);
  302. this.updateLog.push({
  303. time: new Date(),
  304. type: what,
  305. value: info || ''
  306. });
  307. };
  308. this.onicecandidate = null;
  309. this.peerconnection.onicecandidate = event => {
  310. this.trace(
  311. 'onicecandidate',
  312. JSON.stringify(event.candidate, null, ' '));
  313. if (this.onicecandidate !== null) {
  314. this.onicecandidate(event);
  315. }
  316. };
  317. this.onTrack = evt => {
  318. const stream = evt.streams[0];
  319. this._remoteTrackAdded(stream, evt.track, evt.transceiver);
  320. stream.addEventListener('removetrack', e => {
  321. this._remoteTrackRemoved(stream, e.track);
  322. });
  323. };
  324. this.peerconnection.addEventListener('track', this.onTrack);
  325. this.onsignalingstatechange = null;
  326. this.peerconnection.onsignalingstatechange = event => {
  327. this.trace('onsignalingstatechange', this.signalingState);
  328. if (this.onsignalingstatechange !== null) {
  329. this.onsignalingstatechange(event);
  330. }
  331. };
  332. this.oniceconnectionstatechange = null;
  333. this.peerconnection.oniceconnectionstatechange = event => {
  334. this.trace('oniceconnectionstatechange', this.iceConnectionState);
  335. if (this.oniceconnectionstatechange !== null) {
  336. this.oniceconnectionstatechange(event);
  337. }
  338. };
  339. this.onnegotiationneeded = null;
  340. this.peerconnection.onnegotiationneeded = event => {
  341. this.trace('onnegotiationneeded');
  342. if (this.onnegotiationneeded !== null) {
  343. this.onnegotiationneeded(event);
  344. }
  345. };
  346. this.onconnectionstatechange = null;
  347. this.peerconnection.onconnectionstatechange = event => {
  348. this.trace('onconnectionstatechange', this.connectionState);
  349. if (this.onconnectionstatechange !== null) {
  350. this.onconnectionstatechange(event);
  351. }
  352. };
  353. this.ondatachannel = null;
  354. this.peerconnection.ondatachannel = event => {
  355. this.trace('ondatachannel');
  356. if (this.ondatachannel !== null) {
  357. this.ondatachannel(event);
  358. }
  359. };
  360. if (this.maxstats) {
  361. this.statsinterval = window.setInterval(() => {
  362. this.getStats().then(stats => {
  363. if (typeof stats?.result === 'function') {
  364. const results = stats.result();
  365. for (let i = 0; i < results.length; ++i) {
  366. const res = results[i];
  367. res.names().forEach(name => {
  368. this._processStat(res, name, res.stat(name));
  369. });
  370. }
  371. } else {
  372. stats.forEach(r => this._processStat(r, '', r));
  373. }
  374. });
  375. }, 1000);
  376. }
  377. this._lastVideoSenderUpdatePromise = Promise.resolve();
  378. logger.info(`Create new ${this}`);
  379. }
  380. /* eslint-enable max-params */
  381. /**
  382. * Process stat and adds it to the array of stats we store.
  383. * @param report the current stats report.
  384. * @param name the name of the report, if available
  385. * @param statValue the value to add.
  386. * @private
  387. */
  388. TraceablePeerConnection.prototype._processStat
  389. = function(report, name, statValue) {
  390. const id = `${report.id}-${name}`;
  391. let s = this.stats[id];
  392. const now = new Date();
  393. if (!s) {
  394. this.stats[id] = s = {
  395. startTime: now,
  396. endTime: now,
  397. values: [],
  398. times: []
  399. };
  400. }
  401. s.values.push(statValue);
  402. s.times.push(now.getTime());
  403. if (s.values.length > this.maxstats) {
  404. s.values.shift();
  405. s.times.shift();
  406. }
  407. s.endTime = now;
  408. };
  409. /**
  410. * Returns a string representation of a SessionDescription object.
  411. */
  412. const dumpSDP = function(description) {
  413. if (typeof description === 'undefined' || description === null) {
  414. return '';
  415. }
  416. return `type: ${description.type}\r\n${description.sdp}`;
  417. };
  418. /**
  419. * Forwards the {@link peerconnection.iceConnectionState} state except that it
  420. * will convert "completed" into "connected" where both mean that the ICE has
  421. * succeeded and is up and running. We never see "completed" state for
  422. * the JVB connection, but it started appearing for the P2P one. This method
  423. * allows to adapt old logic to this new situation.
  424. * @return {string}
  425. */
  426. TraceablePeerConnection.prototype.getConnectionState = function() {
  427. const state = this.peerconnection.iceConnectionState;
  428. if (state === 'completed') {
  429. return 'connected';
  430. }
  431. return state;
  432. };
  433. /**
  434. * Obtains the media direction for given {@link MediaType} that needs to be set on a p2p peerconnection's remote SDP
  435. * after a source-add or source-remove action. The method takes into account whether or not there are any
  436. * local tracks for the given media type.
  437. * @param {MediaType} mediaType - The media type for which the direction is to be calculated.
  438. * @param {boolean} isAddOperation whether the direction is to be calculated after a source-add action.
  439. * @return {string} one of the SDP direction constants ('sendrecv, 'recvonly' etc.) which should be used when setting
  440. * local description on the peerconnection.
  441. * @private
  442. */
  443. TraceablePeerConnection.prototype.getDesiredMediaDirection = function(mediaType, isAddOperation = false) {
  444. return this.tpcUtils.getDesiredMediaDirection(mediaType, isAddOperation);
  445. };
  446. /**
  447. * Returns the list of RTCRtpReceivers created for the source of the given media type associated with
  448. * the set of remote endpoints specified.
  449. * @param {Array<string>} endpoints list of the endpoints
  450. * @param {string} mediaType 'audio' or 'video'
  451. * @returns {Array<RTCRtpReceiver>} list of receivers created by the peerconnection.
  452. */
  453. TraceablePeerConnection.prototype._getReceiversByEndpointIds = function(endpoints, mediaType) {
  454. let remoteTracks = [];
  455. let receivers = [];
  456. for (const endpoint of endpoints) {
  457. remoteTracks = remoteTracks.concat(this.getRemoteTracks(endpoint, mediaType));
  458. }
  459. // Get the ids of the MediaStreamTracks associated with each of these remote tracks.
  460. const remoteTrackIds = remoteTracks.map(remote => remote.track?.id);
  461. receivers = this.peerconnection.getReceivers()
  462. .filter(receiver => receiver.track
  463. && receiver.track.kind === mediaType
  464. && remoteTrackIds.find(trackId => trackId === receiver.track.id));
  465. return receivers;
  466. };
  467. /**
  468. * Tells whether or not this TPC instance has spatial scalability enabled.
  469. * @return {boolean} <tt>true</tt> if spatial scalability is enabled and active or
  470. * <tt>false</tt> if it's turned off.
  471. */
  472. TraceablePeerConnection.prototype.isSpatialScalabilityOn = function() {
  473. const h264SimulcastEnabled = this.tpcUtils.codecSettings[CodecMimeType.H264].scalabilityModeEnabled
  474. && this.tpcUtils.supportsDDHeaderExt;
  475. return !this.options.disableSimulcast
  476. && (this.codecSettings.codecList[0] !== CodecMimeType.H264 || h264SimulcastEnabled);
  477. };
  478. /**
  479. * Handles {@link SignalingEvents.PEER_VIDEO_TYPE_CHANGED}
  480. * @param {string} endpointId the video owner's ID (MUC nickname)
  481. * @param {VideoType} videoType the new value
  482. * @private
  483. */
  484. TraceablePeerConnection.prototype._peerVideoTypeChanged = function(endpointId, videoType) {
  485. // Check if endpointId has a value to avoid action on random track
  486. if (!endpointId) {
  487. logger.error(`${this} No endpointID on peerVideoTypeChanged`);
  488. return;
  489. }
  490. const videoTrack = this.getRemoteTracks(endpointId, MediaType.VIDEO);
  491. if (videoTrack.length) {
  492. // NOTE 1 track per media type is assumed
  493. videoTrack[0]._setVideoType(videoType);
  494. }
  495. };
  496. /**
  497. * Handles remote track mute / unmute events.
  498. * @param {string} endpointId the track owner's identifier (MUC nickname)
  499. * @param {MediaType} mediaType "audio" or "video"
  500. * @param {boolean} isMuted the new mute state
  501. * @private
  502. */
  503. TraceablePeerConnection.prototype._peerMutedChanged = function(endpointId, mediaType, isMuted) {
  504. // Check if endpointId is a value to avoid doing action on all remote tracks
  505. if (!endpointId) {
  506. logger.error(`${this} On peerMuteChanged - no endpoint ID`);
  507. return;
  508. }
  509. const track = this.getRemoteTracks(endpointId, mediaType);
  510. if (track.length) {
  511. // NOTE 1 track per media type is assumed
  512. track[0].setMute(isMuted);
  513. }
  514. };
  515. /**
  516. * Handles remote source mute and unmute changed events.
  517. *
  518. * @param {string} sourceName - The name of the remote source.
  519. * @param {boolean} isMuted - The new mute state.
  520. */
  521. TraceablePeerConnection.prototype._sourceMutedChanged = function(sourceName, isMuted) {
  522. const track = this.getRemoteTracks().find(t => t.getSourceName() === sourceName);
  523. if (!track) {
  524. if (FeatureFlags.isSsrcRewritingSupported()) {
  525. logger.debug(`Remote track not found for source=${sourceName}, mute update failed!`);
  526. }
  527. return;
  528. }
  529. track.setMute(isMuted);
  530. };
  531. /**
  532. * Handles remote source videoType changed events.
  533. *
  534. * @param {string} sourceName - The name of the remote source.
  535. * @param {boolean} isMuted - The new value.
  536. */
  537. TraceablePeerConnection.prototype._sourceVideoTypeChanged = function(sourceName, videoType) {
  538. const track = this.getRemoteTracks().find(t => t.getSourceName() === sourceName);
  539. if (!track) {
  540. return;
  541. }
  542. track._setVideoType(videoType);
  543. };
  544. /**
  545. * Obtains audio levels of the remote audio tracks by getting the source information on the RTCRtpReceivers.
  546. * The information relevant to the ssrc is updated each time a RTP packet constaining the ssrc is received.
  547. * @param {Array<string>} speakerList list of endpoint ids for which audio levels are to be gathered.
  548. * @returns {Object} containing ssrc and audio level information as a key-value pair.
  549. */
  550. TraceablePeerConnection.prototype.getAudioLevels = function(speakerList = []) {
  551. const audioLevels = {};
  552. const audioReceivers = speakerList.length
  553. ? this._getReceiversByEndpointIds(speakerList, MediaType.AUDIO)
  554. : this.peerconnection.getReceivers()
  555. .filter(receiver => receiver.track && receiver.track.kind === MediaType.AUDIO && receiver.track.enabled);
  556. audioReceivers.forEach(remote => {
  557. const ssrc = remote.getSynchronizationSources();
  558. if (ssrc && ssrc.length) {
  559. // As per spec, this audiolevel is a value between 0..1 (linear), where 1.0
  560. // represents 0 dBov, 0 represents silence, and 0.5 represents approximately
  561. // 6 dBSPL change in the sound pressure level from 0 dBov.
  562. // https://www.w3.org/TR/webrtc/#dom-rtcrtpcontributingsource-audiolevel
  563. audioLevels[ssrc[0].source] = ssrc[0].audioLevel;
  564. }
  565. });
  566. return audioLevels;
  567. };
  568. /**
  569. * Checks if the browser is currently doing true simulcast where in three different media streams are being sent to the
  570. * bridge. Currently this happens always for VP8 and only if simulcast is enabled for VP9/AV1/H264.
  571. *
  572. * @param {JitsiLocalTrack} localTrack - The local video track.
  573. * @returns {boolean}
  574. */
  575. TraceablePeerConnection.prototype.doesTrueSimulcast = function(localTrack) {
  576. const currentCodec = this.tpcUtils.getConfiguredVideoCodec(localTrack);
  577. return this.isSpatialScalabilityOn() && this.tpcUtils.isRunningInSimulcastMode(currentCodec);
  578. };
  579. /**
  580. * Returns the SSRCs associated with a given local video track.
  581. *
  582. * @param {JitsiLocalTrack} localTrack
  583. * @returns
  584. */
  585. TraceablePeerConnection.prototype.getLocalVideoSSRCs = function(localTrack) {
  586. const ssrcs = [];
  587. if (!localTrack || !localTrack.isVideoTrack()) {
  588. return ssrcs;
  589. }
  590. const ssrcGroup = this.isSpatialScalabilityOn() ? SSRC_GROUP_SEMANTICS.SIM : SSRC_GROUP_SEMANTICS.FID;
  591. return this.localSSRCs.get(localTrack.rtcId)?.groups?.find(group => group.semantics === ssrcGroup)?.ssrcs || ssrcs;
  592. };
  593. /**
  594. * Obtains local tracks for given {@link MediaType}. If the <tt>mediaType</tt>
  595. * argument is omitted the list of all local tracks will be returned.
  596. * @param {MediaType} [mediaType]
  597. * @return {Array<JitsiLocalTrack>}
  598. */
  599. TraceablePeerConnection.prototype.getLocalTracks = function(mediaType) {
  600. let tracks = Array.from(this.localTracks.values());
  601. if (mediaType !== undefined) {
  602. tracks = tracks.filter(track => track.getType() === mediaType);
  603. }
  604. return tracks;
  605. };
  606. /**
  607. * Retrieves the local video tracks.
  608. *
  609. * @returns {Array<JitsiLocalTrack>} - local video tracks.
  610. */
  611. TraceablePeerConnection.prototype.getLocalVideoTracks = function() {
  612. return this.getLocalTracks(MediaType.VIDEO);
  613. };
  614. /**
  615. * Obtains all remote tracks currently known to this PeerConnection instance.
  616. *
  617. * @param {string} [endpointId] - The track owner's identifier (MUC nickname)
  618. * @param {MediaType} [mediaType] - The remote tracks will be filtered by their media type if this argument is
  619. * specified.
  620. * @return {Array<JitsiRemoteTrack>}
  621. */
  622. TraceablePeerConnection.prototype.getRemoteTracks = function(endpointId, mediaType) {
  623. let remoteTracks = [];
  624. if (FeatureFlags.isSsrcRewritingSupported()) {
  625. for (const remoteTrack of this.remoteTracksBySsrc.values()) {
  626. const owner = remoteTrack.getParticipantId();
  627. if (owner && (!endpointId || owner === endpointId)) {
  628. if (!mediaType || remoteTrack.getType() === mediaType) {
  629. remoteTracks.push(remoteTrack);
  630. }
  631. }
  632. }
  633. return remoteTracks;
  634. }
  635. const endpoints = endpointId ? [ endpointId ] : this.remoteTracks.keys();
  636. for (const endpoint of endpoints) {
  637. const endpointTracksByMediaType = this.remoteTracks.get(endpoint);
  638. if (endpointTracksByMediaType) {
  639. for (const trackMediaType of endpointTracksByMediaType.keys()) {
  640. // per media type filtering
  641. if (!mediaType || mediaType === trackMediaType) {
  642. remoteTracks = remoteTracks.concat(Array.from(endpointTracksByMediaType.get(trackMediaType)));
  643. }
  644. }
  645. }
  646. }
  647. return remoteTracks;
  648. };
  649. /**
  650. * Returns the remote sourceInfo for a given source name.
  651. *
  652. * @param {string} sourceName - The source name.
  653. * @returns {TPCSourceInfo}
  654. */
  655. TraceablePeerConnection.prototype.getRemoteSourceInfoBySourceName = function(sourceName) {
  656. return cloneDeep(this._remoteSsrcMap.get(sourceName));
  657. };
  658. /**
  659. * Returns a map of source names and their associated SSRCs for the remote participant.
  660. *
  661. * @param {string} id Endpoint id of the remote participant.
  662. * @returns {Map<string, TPCSourceInfo>} The map of source names and their associated SSRCs.
  663. */
  664. TraceablePeerConnection.prototype.getRemoteSourceInfoByParticipant = function(id) {
  665. const removeSsrcInfo = new Map();
  666. const remoteTracks = this.getRemoteTracks(id);
  667. if (!remoteTracks?.length) {
  668. return removeSsrcInfo;
  669. }
  670. const primarySsrcs = remoteTracks.map(track => track.getSSRC());
  671. for (const [ sourceName, sourceInfo ] of this._remoteSsrcMap) {
  672. if (sourceInfo.ssrcList?.some(ssrc => primarySsrcs.includes(Number(ssrc)))) {
  673. removeSsrcInfo.set(sourceName, sourceInfo);
  674. }
  675. }
  676. return removeSsrcInfo;
  677. };
  678. /**
  679. * Returns the target bitrates configured for the local video source.
  680. *
  681. * @param {JitsiLocalTrack} - The local video track.
  682. * @returns {Object}
  683. */
  684. TraceablePeerConnection.prototype.getTargetVideoBitrates = function(localTrack) {
  685. const currentCodec = this.tpcUtils.getConfiguredVideoCodec(localTrack);
  686. return this.tpcUtils.codecSettings[currentCodec].maxBitratesVideo;
  687. };
  688. /**
  689. * Tries to find {@link JitsiTrack} for given SSRC number. It will search both local and remote tracks bound to this
  690. * instance.
  691. * @param {number} ssrc
  692. * @return {JitsiTrack|null}
  693. */
  694. TraceablePeerConnection.prototype.getTrackBySSRC = function(ssrc) {
  695. if (typeof ssrc !== 'number') {
  696. throw new Error(`SSRC ${ssrc} is not a number`);
  697. }
  698. for (const localTrack of this.localTracks.values()) {
  699. const { ssrcs } = this.localSSRCs.get(localTrack.rtcId) ?? { ssrcs: [] };
  700. if (ssrcs.find(localSsrc => Number(localSsrc) === ssrc)) {
  701. return localTrack;
  702. }
  703. }
  704. if (FeatureFlags.isSsrcRewritingSupported()) {
  705. return this.remoteTracksBySsrc.get(ssrc);
  706. }
  707. for (const remoteTrack of this.getRemoteTracks()) {
  708. if (remoteTrack.getSSRC() === ssrc) {
  709. return remoteTrack;
  710. }
  711. }
  712. return null;
  713. };
  714. /**
  715. * Tries to find SSRC number for given {@link JitsiTrack} id. It will search
  716. * both local and remote tracks bound to this instance.
  717. * @param {string} id
  718. * @return {number|null}
  719. */
  720. TraceablePeerConnection.prototype.getSsrcByTrackId = function(id) {
  721. const findTrackById = track => track.getTrack().id === id;
  722. const localTrack = this.getLocalTracks().find(findTrackById);
  723. if (localTrack) {
  724. return this.getLocalSSRC(localTrack);
  725. }
  726. const remoteTrack = this.getRemoteTracks().find(findTrackById);
  727. if (remoteTrack) {
  728. return remoteTrack.getSSRC();
  729. }
  730. return null;
  731. };
  732. /**
  733. * Called on "track added" and "stream added" PeerConnection events (because we
  734. * handle streams on per track basis). Finds the owner and the SSRC for
  735. * the track and passes that to ChatRoom for further processing.
  736. * @param {MediaStream} stream the WebRTC MediaStream instance which is
  737. * the parent of the track
  738. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack added for remote
  739. * participant.
  740. * @param {RTCRtpTransceiver} transceiver the WebRTC transceiver that is created
  741. * for the remote participant in unified plan.
  742. */
  743. TraceablePeerConnection.prototype._remoteTrackAdded = function(stream, track, transceiver = null) {
  744. const streamId = stream.id;
  745. const mediaType = track.kind;
  746. // Do not create remote tracks for 'mixed' JVB SSRCs (used by JVB for RTCP termination).
  747. if (!this.isP2P && !RTCUtils.isUserStreamById(streamId)) {
  748. return;
  749. }
  750. logger.info(`${this} Received track event for remote stream[id=${streamId},type=${mediaType}]`);
  751. // look up an associated JID for a stream id
  752. if (!mediaType) {
  753. logger.error(`MediaType undefined for remote track, stream id: ${streamId}, track creation failed!`);
  754. return;
  755. }
  756. const remoteSDP = new SDP(this.remoteDescription.sdp);
  757. let mediaLine;
  758. // Find the matching mline using 'mid' or the 'msid' attr of the stream.
  759. if (transceiver?.mid) {
  760. const mid = transceiver.mid;
  761. mediaLine = remoteSDP.media.find(mls => SDPUtil.findLine(mls, `a=mid:${mid}`));
  762. } else {
  763. mediaLine = remoteSDP.media.find(mls => {
  764. const msid = SDPUtil.findLine(mls, 'a=msid:');
  765. return typeof msid === 'string' && streamId === msid.substring(7).split(' ')[0];
  766. });
  767. }
  768. if (!mediaLine) {
  769. logger.error(`Matching media line not found in remote SDP for remote stream[id=${streamId},type=${mediaType}],`
  770. + 'track creation failed!');
  771. return;
  772. }
  773. let ssrcLines = SDPUtil.findLines(mediaLine, 'a=ssrc:');
  774. ssrcLines = ssrcLines.filter(line => line.indexOf(`msid:${streamId}`) !== -1);
  775. if (!ssrcLines.length) {
  776. logger.error(`No SSRC lines found in remote SDP for remote stream[msid=${streamId},type=${mediaType}]`
  777. + 'track creation failed!');
  778. return;
  779. }
  780. // FIXME the length of ssrcLines[0] not verified, but it will fail
  781. // with global error handler anyway
  782. const ssrcStr = ssrcLines[0].substring(7).split(' ')[0];
  783. const trackSsrc = Number(ssrcStr);
  784. const ownerEndpointId = this.signalingLayer.getSSRCOwner(trackSsrc);
  785. if (!isValidNumber(trackSsrc) || trackSsrc < 0) {
  786. logger.error(`Invalid SSRC for remote stream[ssrc=${trackSsrc},id=${streamId},type=${mediaType}]`
  787. + 'track creation failed!');
  788. return;
  789. }
  790. if (!ownerEndpointId) {
  791. logger.error(`No SSRC owner known for remote stream[ssrc=${trackSsrc},id=${streamId},type=${mediaType}]`
  792. + 'track creation failed!');
  793. return;
  794. }
  795. const sourceName = this.signalingLayer.getTrackSourceName(trackSsrc);
  796. const peerMediaInfo = this.signalingLayer.getPeerMediaInfo(ownerEndpointId, mediaType, sourceName);
  797. const trackDetails = {
  798. mediaType,
  799. muted: peerMediaInfo?.muted ?? true,
  800. stream,
  801. track,
  802. ssrc: trackSsrc,
  803. videoType: peerMediaInfo?.videoType
  804. };
  805. if (this._remoteSsrcMap.has(sourceName) && mediaType === MediaType.VIDEO) {
  806. trackDetails.videoType = this._remoteSsrcMap.get(sourceName).videoType;
  807. }
  808. this._createRemoteTrack(ownerEndpointId, sourceName, trackDetails);
  809. };
  810. /**
  811. * Initializes a new JitsiRemoteTrack instance with the data provided by the signaling layer and SDP.
  812. *
  813. * @param {string} ownerEndpointId - The owner's endpoint ID (MUC nickname)
  814. * @param {String} sourceName - The track's source name
  815. * @param {Object} trackDetails - The track's details.
  816. * @param {MediaType} trackDetails.mediaType - media type, 'audio' or 'video'.
  817. * @param {boolean} trackDetails.muted - The initial muted status.
  818. * @param {number} trackDetails.ssrc - The track's main SSRC number.
  819. * @param {MediaStream} trackDetails.stream - The WebRTC stream instance.
  820. * @param {MediaStreamTrack} trackDetails.track - The WebRTC track instance.
  821. * @param {VideoType} trackDetails.videoType - The track's type of the video (if applicable).
  822. */
  823. TraceablePeerConnection.prototype._createRemoteTrack = function(ownerEndpointId, sourceName, trackDetails) {
  824. const { mediaType, muted, ssrc, stream, track, videoType } = trackDetails;
  825. logger.info(`${this} creating remote track[endpoint=${ownerEndpointId},ssrc=${ssrc},`
  826. + `type=${mediaType},sourceName=${sourceName}]`);
  827. let remoteTracksMap;
  828. let userTracksByMediaType;
  829. if (FeatureFlags.isSsrcRewritingSupported()) {
  830. const existingTrack = this.remoteTracksBySsrc.get(ssrc);
  831. if (existingTrack) {
  832. logger.info(`${this} ignored duplicated track event for SSRC[ssrc=${ssrc},type=${mediaType}]`);
  833. return;
  834. }
  835. } else {
  836. remoteTracksMap = this.remoteTracks.get(ownerEndpointId);
  837. if (!remoteTracksMap) {
  838. remoteTracksMap = new Map();
  839. remoteTracksMap.set(MediaType.AUDIO, new Set());
  840. remoteTracksMap.set(MediaType.VIDEO, new Set());
  841. this.remoteTracks.set(ownerEndpointId, remoteTracksMap);
  842. }
  843. userTracksByMediaType = remoteTracksMap.get(mediaType);
  844. if (userTracksByMediaType?.size
  845. && Array.from(userTracksByMediaType).find(jitsiTrack => jitsiTrack.getTrack() === track)) {
  846. // Ignore duplicated event which can originate either from 'onStreamAdded' or 'onTrackAdded'.
  847. logger.info(`${this} ignored duplicated track event for track[endpoint=${ownerEndpointId},`
  848. + `type=${mediaType}]`);
  849. return;
  850. }
  851. }
  852. const remoteTrack
  853. = new JitsiRemoteTrack(
  854. this.rtc,
  855. this.rtc.conference,
  856. ownerEndpointId,
  857. stream,
  858. track,
  859. mediaType,
  860. videoType,
  861. ssrc,
  862. muted,
  863. this.isP2P,
  864. sourceName);
  865. if (FeatureFlags.isSsrcRewritingSupported()) {
  866. this.remoteTracksBySsrc.set(ssrc, remoteTrack);
  867. } else {
  868. userTracksByMediaType.add(remoteTrack);
  869. }
  870. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, remoteTrack, this);
  871. };
  872. /**
  873. * Handles remote media track removal.
  874. *
  875. * @param {MediaStream} stream - WebRTC MediaStream instance which is the parent of the track.
  876. * @param {MediaStreamTrack} track - WebRTC MediaStreamTrack which has been removed from the PeerConnection.
  877. * @returns {void}
  878. */
  879. TraceablePeerConnection.prototype._remoteTrackRemoved = function(stream, track) {
  880. const streamId = stream.id;
  881. const trackId = track?.id;
  882. // Ignore stream removed events for JVB "mixed" sources (used for RTCP termination).
  883. if (!RTCUtils.isUserStreamById(streamId)) {
  884. return;
  885. }
  886. if (!streamId) {
  887. logger.error(`${this} remote track removal failed - no stream ID`);
  888. return;
  889. }
  890. if (!trackId) {
  891. logger.error(`${this} remote track removal failed - no track ID`);
  892. return;
  893. }
  894. const toBeRemoved = this.getRemoteTracks().find(
  895. remoteTrack => remoteTrack.getStreamId() === streamId && remoteTrack.getTrackId() === trackId);
  896. if (!toBeRemoved) {
  897. logger.error(`${this} remote track removal failed - track not found`);
  898. return;
  899. }
  900. this._removeRemoteTrack(toBeRemoved);
  901. };
  902. /**
  903. * Removes and disposes given <tt>JitsiRemoteTrack</tt> instance. Emits {@link RTCEvents.REMOTE_TRACK_REMOVED}.
  904. *
  905. * @param {JitsiRemoteTrack} toBeRemoved - The remote track to be removed.
  906. * @returns {void}
  907. */
  908. TraceablePeerConnection.prototype._removeRemoteTrack = function(toBeRemoved) {
  909. logger.info(`${this} Removing remote track stream[id=${toBeRemoved.getStreamId()},`
  910. + `trackId=${toBeRemoved.getTrackId()}]`);
  911. toBeRemoved.dispose();
  912. const participantId = toBeRemoved.getParticipantId();
  913. if (FeatureFlags.isSsrcRewritingSupported() && !participantId) {
  914. return;
  915. } else if (!FeatureFlags.isSsrcRewritingSupported()) {
  916. const userTracksByMediaType = this.remoteTracks.get(participantId);
  917. if (!userTracksByMediaType) {
  918. logger.error(`${this} removeRemoteTrack: no remote tracks map for endpoint=${participantId}`);
  919. } else if (!userTracksByMediaType.get(toBeRemoved.getType())?.delete(toBeRemoved)) {
  920. logger.error(`${this} Failed to remove ${toBeRemoved} - type mapping messed up ?`);
  921. }
  922. }
  923. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_REMOVED, toBeRemoved);
  924. };
  925. /**
  926. * Processes the local SDP and creates an SSRC map for every local track.
  927. *
  928. * @param {string} localSDP - SDP from the local description.
  929. * @returns {void}
  930. */
  931. TraceablePeerConnection.prototype._processAndExtractSourceInfo = function(localSDP) {
  932. /**
  933. * @type {Map<string, TPCSourceInfo>} The map of source names and their associated SSRCs.
  934. */
  935. const ssrcMap = new Map();
  936. if (!localSDP || typeof localSDP !== 'string') {
  937. throw new Error('Local SDP must be a valid string, aborting!!');
  938. }
  939. const session = transform.parse(localSDP);
  940. const media = session.media.filter(mline => mline.direction === MediaDirection.SENDONLY
  941. || mline.direction === MediaDirection.SENDRECV);
  942. if (!media.length) {
  943. this._localSsrcMap = ssrcMap;
  944. return;
  945. }
  946. for (const localTrack of this.localTracks.values()) {
  947. const sourceName = localTrack.getSourceName();
  948. const trackIndex = getSourceIndexFromSourceName(sourceName);
  949. const mediaType = localTrack.getType();
  950. const mLines = media.filter(m => m.type === mediaType);
  951. const ssrcGroups = mLines[trackIndex].ssrcGroups;
  952. let ssrcs = mLines[trackIndex].ssrcs;
  953. if (ssrcs?.length) {
  954. // Filter the ssrcs with 'cname' attribute.
  955. ssrcs = ssrcs.filter(s => s.attribute === 'cname');
  956. const msid = `${this.rtc.getLocalEndpointId()}-${mediaType}-${trackIndex}`;
  957. const ssrcInfo = {
  958. ssrcs: [],
  959. groups: [],
  960. msid
  961. };
  962. ssrcs.forEach(ssrc => ssrcInfo.ssrcs.push(ssrc.id));
  963. if (ssrcGroups?.length) {
  964. for (const group of ssrcGroups) {
  965. group.ssrcs = group.ssrcs.split(' ').map(ssrcStr => parseInt(ssrcStr, 10));
  966. ssrcInfo.groups.push(group);
  967. }
  968. const simGroup = ssrcGroups.find(group => group.semantics === SSRC_GROUP_SEMANTICS.SIM);
  969. // Add a SIM group if its missing in the description (happens on Firefox).
  970. if (this.isSpatialScalabilityOn() && !simGroup) {
  971. const groupSsrcs = ssrcGroups.map(group => group.ssrcs[0]);
  972. ssrcInfo.groups.push({
  973. semantics: SSRC_GROUP_SEMANTICS.SIM,
  974. ssrcs: groupSsrcs
  975. });
  976. }
  977. }
  978. ssrcMap.set(sourceName, ssrcInfo);
  979. const oldSsrcInfo = this.localSSRCs.get(localTrack.rtcId);
  980. const oldSsrc = this._extractPrimarySSRC(oldSsrcInfo);
  981. const newSsrc = this._extractPrimarySSRC(ssrcInfo);
  982. if (oldSsrc !== newSsrc) {
  983. oldSsrc && logger.debug(`${this} Overwriting SSRC for track=${localTrack}] with ssrc=${newSsrc}`);
  984. this.localSSRCs.set(localTrack.rtcId, ssrcInfo);
  985. localTrack.setSsrc(newSsrc);
  986. }
  987. }
  988. }
  989. this._localSsrcMap = ssrcMap;
  990. };
  991. /**
  992. *
  993. * @param {JitsiLocalTrack} localTrack
  994. */
  995. TraceablePeerConnection.prototype.getLocalSSRC = function(localTrack) {
  996. const ssrcInfo = this._getSSRC(localTrack.rtcId);
  997. return ssrcInfo && ssrcInfo.ssrcs[0];
  998. };
  999. /* eslint-disable-next-line vars-on-top */
  1000. const getters = {
  1001. signalingState() {
  1002. return this.peerconnection.signalingState;
  1003. },
  1004. iceConnectionState() {
  1005. return this.peerconnection.iceConnectionState;
  1006. },
  1007. connectionState() {
  1008. return this.peerconnection.connectionState;
  1009. },
  1010. localDescription() {
  1011. let desc = this.peerconnection.localDescription;
  1012. if (!desc) {
  1013. logger.debug(`${this} getLocalDescription no localDescription found`);
  1014. return {};
  1015. }
  1016. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  1017. if (!this.isP2P) {
  1018. desc = this.tpcUtils.injectSsrcGroupForSimulcast(desc);
  1019. this.trace('getLocalDescription::postTransform (inject ssrc group)', dumpSDP(desc));
  1020. }
  1021. // See the method's doc for more info about this transformation.
  1022. desc = this.localSdpMunger.transformStreamIdentifiers(desc, this._localSsrcMap);
  1023. return desc;
  1024. },
  1025. remoteDescription() {
  1026. let desc = this.peerconnection.remoteDescription;
  1027. if (!desc) {
  1028. logger.debug(`${this} getRemoteDescription no remoteDescription found`);
  1029. return {};
  1030. }
  1031. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  1032. if (this.isP2P) {
  1033. // Adjust the media direction for p2p based on whether a local source has been added.
  1034. desc = this._adjustRemoteMediaDirection(desc);
  1035. }
  1036. return desc;
  1037. }
  1038. };
  1039. Object.keys(getters).forEach(prop => {
  1040. Object.defineProperty(
  1041. TraceablePeerConnection.prototype,
  1042. prop, {
  1043. get: getters[prop]
  1044. }
  1045. );
  1046. });
  1047. TraceablePeerConnection.prototype._getSSRC = function(rtcId) {
  1048. return this.localSSRCs.get(rtcId);
  1049. };
  1050. /**
  1051. * Checks if low fps screensharing is in progress.
  1052. *
  1053. * @private
  1054. * @returns {boolean} Returns true if 5 fps screensharing is in progress, false otherwise.
  1055. */
  1056. TraceablePeerConnection.prototype.isSharingLowFpsScreen = function() {
  1057. return this._isSharingScreen() && this._capScreenshareBitrate;
  1058. };
  1059. /**
  1060. * Checks if screensharing is in progress.
  1061. *
  1062. * @returns {boolean} Returns true if a desktop track has been added to the peerconnection, false otherwise.
  1063. */
  1064. TraceablePeerConnection.prototype._isSharingScreen = function() {
  1065. const tracks = this.getLocalVideoTracks();
  1066. return Boolean(tracks.find(track => track.videoType === VideoType.DESKTOP));
  1067. };
  1068. /**
  1069. * Add {@link JitsiLocalTrack} to this TPC.
  1070. * @param {JitsiLocalTrack} track
  1071. * @param {boolean} isInitiator indicates if the endpoint is the offerer.
  1072. * @returns {Promise<void>} - resolved when done.
  1073. */
  1074. TraceablePeerConnection.prototype.addTrack = async function(track, isInitiator = false) {
  1075. const rtcId = track.rtcId;
  1076. if (this.localTracks.has(rtcId)) {
  1077. throw new Error(`${track} is already in ${this}`);
  1078. }
  1079. logger.info(`${this} adding ${track}`);
  1080. const webrtcStream = track.getOriginalStream();
  1081. const mediaStreamTrack = track.getTrack();
  1082. let transceiver;
  1083. if (isInitiator) {
  1084. const streams = [];
  1085. webrtcStream && streams.push(webrtcStream);
  1086. // Use pc.addTransceiver() for the initiator case when local tracks are getting added
  1087. // to the peerconnection before a session-initiate is sent over to the peer.
  1088. const transceiverInit = {
  1089. direction: MediaDirection.SENDRECV,
  1090. streams,
  1091. sendEncodings: []
  1092. };
  1093. if (!browser.isFirefox()) {
  1094. transceiverInit.sendEncodings = this.tpcUtils.getStreamEncodings(track);
  1095. }
  1096. transceiver = this.peerconnection.addTransceiver(mediaStreamTrack, transceiverInit);
  1097. } else {
  1098. // Use pc.addTrack() for responder case so that we can re-use the m-lines that were created
  1099. // when setRemoteDescription was called. pc.addTrack() automatically attaches to any existing
  1100. // unused "recv-only" transceiver.
  1101. const sender = this.peerconnection.addTrack(mediaStreamTrack);
  1102. // Find the corresponding transceiver that the track was attached to.
  1103. transceiver = this.peerconnection.getTransceivers().find(t => t.sender === sender);
  1104. }
  1105. if (transceiver?.mid) {
  1106. this.localTrackTransceiverMids.set(track.rtcId, transceiver.mid.toString());
  1107. }
  1108. if (track) {
  1109. this.localTracks.set(rtcId, track);
  1110. if (track.isAudioTrack()) {
  1111. this._hasHadAudioTrack = true;
  1112. } else {
  1113. this._hasHadVideoTrack = true;
  1114. }
  1115. }
  1116. // On Firefox, the encodings have to be configured on the sender only after the transceiver is created.
  1117. if (browser.isFirefox() && webrtcStream && this.doesTrueSimulcast(track)) {
  1118. await this._setEncodings(track);
  1119. }
  1120. };
  1121. /**
  1122. * Adds local track to the RTCPeerConnection.
  1123. *
  1124. * @param {JitsiLocalTrack} track the track to be added to the pc.
  1125. * @return {Promise<boolean>} Promise that resolves to true if the underlying PeerConnection's state has changed and
  1126. * renegotiation is required, false if no renegotiation is needed or Promise is rejected when something goes wrong.
  1127. */
  1128. TraceablePeerConnection.prototype.addTrackToPc = function(track) {
  1129. logger.info(`${this} Adding track=${track} to PC`);
  1130. if (!this._assertTrackBelongs('addTrackToPc', track)) {
  1131. // Abort
  1132. return Promise.reject('Track not found on the peerconnection');
  1133. }
  1134. const webRtcStream = track.getOriginalStream();
  1135. if (!webRtcStream) {
  1136. logger.error(`${this} Unable to add track=${track} to PC - no WebRTC stream`);
  1137. return Promise.reject('Stream not found');
  1138. }
  1139. return this.replaceTrack(null, track, true /* isMuteOperation */).then(() => {
  1140. if (track) {
  1141. if (track.isAudioTrack()) {
  1142. this._hasHadAudioTrack = true;
  1143. } else {
  1144. this._hasHadVideoTrack = true;
  1145. }
  1146. }
  1147. return false;
  1148. });
  1149. };
  1150. /**
  1151. * This method when called will check if given <tt>localTrack</tt> belongs to
  1152. * this TPC (that it has been previously added using {@link addTrack}). If the
  1153. * track does not belong an error message will be logged.
  1154. * @param {string} methodName the method name that will be logged in an error
  1155. * message
  1156. * @param {JitsiLocalTrack} localTrack
  1157. * @return {boolean} <tt>true</tt> if given local track belongs to this TPC or
  1158. * <tt>false</tt> otherwise.
  1159. * @private
  1160. */
  1161. TraceablePeerConnection.prototype._assertTrackBelongs = function(
  1162. methodName,
  1163. localTrack) {
  1164. const doesBelong = this.localTracks.has(localTrack?.rtcId);
  1165. if (!doesBelong) {
  1166. logger.error(`${this} ${methodName}: track=${localTrack} does not belong to pc`);
  1167. }
  1168. return doesBelong;
  1169. };
  1170. /**
  1171. * Returns the codecs in the current order of preference as configured on the peerconnection.
  1172. *
  1173. * @param {RTCSessionDescription} - The local description to be used.
  1174. * @returns {Array}
  1175. */
  1176. TraceablePeerConnection.prototype.getConfiguredVideoCodecs = function(description) {
  1177. return this.tpcUtils.getConfiguredVideoCodecs(description?.sdp);
  1178. };
  1179. /**
  1180. * Enables or disables simulcast for screenshare based on the frame rate requested for desktop track capture.
  1181. *
  1182. * @param {number} maxFps framerate to be used for desktop track capture.
  1183. */
  1184. TraceablePeerConnection.prototype.setDesktopSharingFrameRate = function(maxFps) {
  1185. const lowFps = maxFps <= SS_DEFAULT_FRAME_RATE;
  1186. this._capScreenshareBitrate = this.isSpatialScalabilityOn() && lowFps;
  1187. };
  1188. /**
  1189. * Sets the codec preference on the peerconnection. The codec preference goes into effect when
  1190. * the next renegotiation happens for older clients that do not support the codec selection API.
  1191. *
  1192. * @param {Array<CodecMimeType>} codecList - Preferred codecs for video.
  1193. * @param {CodecMimeType} screenshareCodec - The preferred codec for screenshare.
  1194. * @returns {boolean} - Returns true if the codec settings were updated, false otherwise.
  1195. */
  1196. TraceablePeerConnection.prototype.setVideoCodecs = function(codecList, screenshareCodec) {
  1197. let updated = false;
  1198. if (!this.codecSettings || !codecList?.length) {
  1199. return updated;
  1200. }
  1201. this.codecSettings.codecList = codecList;
  1202. if (screenshareCodec) {
  1203. this.codecSettings.screenshareCodec = screenshareCodec;
  1204. }
  1205. if (!this.usesCodecSelectionAPI()) {
  1206. return updated;
  1207. }
  1208. for (const track of this.getLocalVideoTracks()) {
  1209. const currentCodec = this.tpcUtils.getConfiguredVideoCodec(track);
  1210. if (screenshareCodec && track.getVideoType() === VideoType.DESKTOP && screenshareCodec !== currentCodec) {
  1211. this.configureVideoSenderEncodings(track, screenshareCodec);
  1212. updated = true;
  1213. } else if (currentCodec !== codecList[0]) {
  1214. this.configureVideoSenderEncodings(track);
  1215. updated = true;
  1216. }
  1217. }
  1218. return updated;
  1219. };
  1220. /**
  1221. * Remove local track from this TPC.
  1222. * @param {JitsiLocalTrack} localTrack the track to be removed from this TPC.
  1223. *
  1224. * FIXME It should probably remove a boolean just like {@link removeTrackFromPc}
  1225. * The same applies to addTrack.
  1226. */
  1227. TraceablePeerConnection.prototype.removeTrack = function(localTrack) {
  1228. const webRtcStream = localTrack.getOriginalStream();
  1229. this.trace(
  1230. 'removeStream',
  1231. localTrack.rtcId, webRtcStream ? webRtcStream.id : undefined);
  1232. if (!this._assertTrackBelongs('removeStream', localTrack)) {
  1233. // Abort - nothing to be done here
  1234. return;
  1235. }
  1236. this.localTracks.delete(localTrack.rtcId);
  1237. this.localSSRCs.delete(localTrack.rtcId);
  1238. if (webRtcStream) {
  1239. this.peerconnection.removeStream(webRtcStream);
  1240. }
  1241. };
  1242. /**
  1243. * Returns the receiver corresponding to the given MediaStreamTrack.
  1244. *
  1245. * @param {MediaSreamTrack} track - The media stream track used for the search.
  1246. * @returns {RTCRtpReceiver|undefined} - The found receiver or undefined if no receiver
  1247. * was found.
  1248. */
  1249. TraceablePeerConnection.prototype.findReceiverForTrack = function(track) {
  1250. return this.peerconnection.getReceivers().find(r => r.track === track);
  1251. };
  1252. /**
  1253. * Returns the sender corresponding to the given MediaStreamTrack.
  1254. *
  1255. * @param {MediaSreamTrack} track - The media stream track used for the search.
  1256. * @returns {RTCRtpSender|undefined} - The found sender or undefined if no sender
  1257. * was found.
  1258. */
  1259. TraceablePeerConnection.prototype.findSenderForTrack = function(track) {
  1260. return this.peerconnection.getSenders().find(s => s.track === track);
  1261. };
  1262. /**
  1263. * Processes the local description SDP and caches the mids of the mlines associated with the given tracks.
  1264. *
  1265. * @param {Array<JitsiLocalTrack>} localTracks - local tracks that are added to the peerconnection.
  1266. * @returns {void}
  1267. */
  1268. TraceablePeerConnection.prototype.processLocalSdpForTransceiverInfo = function(localTracks) {
  1269. const localSdp = this.localDescription?.sdp;
  1270. if (!localSdp) {
  1271. return;
  1272. }
  1273. [ MediaType.AUDIO, MediaType.VIDEO ].forEach(mediaType => {
  1274. const tracks = localTracks.filter(t => t.getType() === mediaType);
  1275. const parsedSdp = transform.parse(localSdp);
  1276. const mLines = parsedSdp.media.filter(mline => mline.type === mediaType);
  1277. tracks.forEach((track, idx) => {
  1278. if (!this.localTrackTransceiverMids.has(track.rtcId)) {
  1279. this.localTrackTransceiverMids.set(track.rtcId, mLines[idx].mid.toString());
  1280. }
  1281. });
  1282. });
  1283. };
  1284. /**
  1285. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> from the peer connection.
  1286. * Either <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1287. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1288. * <tt>oldTrack</tt>
  1289. *
  1290. * @param {JitsiLocalTrack|null} oldTrack - The current track in use to be replaced on the pc.
  1291. * @param {JitsiLocalTrack|null} newTrack - The new track to be used.
  1292. * @param {boolean} isMuteOperation - Whether the operation is a mute/unmute operation.
  1293. * @returns {Promise<boolean>} - If the promise resolves with true, renegotiation will be needed.
  1294. * Otherwise no renegotiation is needed.
  1295. */
  1296. TraceablePeerConnection.prototype.replaceTrack = function(oldTrack, newTrack, isMuteOperation = false) {
  1297. if (!(oldTrack || newTrack)) {
  1298. logger.info(`${this} replaceTrack called with no new track and no old track`);
  1299. return Promise.resolve();
  1300. }
  1301. logger.info(`${this} TPC.replaceTrack old=${oldTrack}, new=${newTrack}`);
  1302. let transceiver;
  1303. const mediaType = newTrack?.getType() ?? oldTrack?.getType();
  1304. const localTracks = this.getLocalTracks(mediaType);
  1305. const track = newTrack?.getTrack() ?? null;
  1306. const isNewLocalSource = localTracks?.length
  1307. && !oldTrack
  1308. && newTrack
  1309. && !localTracks.find(t => t === newTrack);
  1310. // If old track exists, replace the track on the corresponding sender.
  1311. if (oldTrack && !oldTrack.isMuted()) {
  1312. transceiver = this.peerconnection.getTransceivers().find(t => t.sender.track === oldTrack.getTrack());
  1313. // Find the first recvonly transceiver when more than one track of the same media type is being added to the pc.
  1314. // As part of the track addition, a new m-line was added to the remote description with direction set to
  1315. // recvonly.
  1316. } else if (isNewLocalSource) {
  1317. transceiver = this.peerconnection.getTransceivers().find(
  1318. t => t.receiver.track.kind === mediaType
  1319. && t.direction === MediaDirection.RECVONLY
  1320. // Re-use any existing recvonly transceiver (if available) for p2p case.
  1321. && ((this.isP2P && t.currentDirection === MediaDirection.RECVONLY)
  1322. || (t.currentDirection === MediaDirection.INACTIVE && !t.stopped)));
  1323. // For mute/unmute operations, find the transceiver based on the track index in the source name if present,
  1324. // otherwise it is assumed to be the first local track that was added to the peerconnection.
  1325. } else {
  1326. transceiver = this.peerconnection.getTransceivers().find(t => t.receiver.track.kind === mediaType);
  1327. const sourceName = newTrack?.getSourceName() ?? oldTrack?.getSourceName();
  1328. if (sourceName) {
  1329. const trackIndex = getSourceIndexFromSourceName(sourceName);
  1330. if (this.isP2P) {
  1331. transceiver = this.peerconnection.getTransceivers()
  1332. .filter(t => t.receiver.track.kind === mediaType)[trackIndex];
  1333. } else if (oldTrack) {
  1334. const transceiverMid = this.localTrackTransceiverMids.get(oldTrack.rtcId);
  1335. transceiver = this.peerconnection.getTransceivers().find(t => t.mid === transceiverMid);
  1336. } else if (trackIndex) {
  1337. transceiver = this.peerconnection.getTransceivers()
  1338. .filter(t => t.receiver.track.kind === mediaType
  1339. && t.direction !== MediaDirection.RECVONLY)[trackIndex];
  1340. }
  1341. }
  1342. }
  1343. if (!transceiver) {
  1344. return Promise.reject(
  1345. new Error(`Replace track failed - no transceiver for old: ${oldTrack}, new: ${newTrack}`));
  1346. }
  1347. return transceiver.sender.replaceTrack(track)
  1348. .then(() => {
  1349. if (isMuteOperation) {
  1350. return Promise.resolve();
  1351. }
  1352. if (oldTrack) {
  1353. this.localTracks.delete(oldTrack.rtcId);
  1354. this.localTrackTransceiverMids.delete(oldTrack.rtcId);
  1355. }
  1356. if (newTrack) {
  1357. if (newTrack.isAudioTrack()) {
  1358. this._hasHadAudioTrack = true;
  1359. } else {
  1360. this._hasHadVideoTrack = true;
  1361. }
  1362. this.localTrackTransceiverMids.set(newTrack.rtcId, transceiver?.mid?.toString());
  1363. this.localTracks.set(newTrack.rtcId, newTrack);
  1364. }
  1365. // Update the local SSRC cache for the case when one track gets replaced with another and no
  1366. // renegotiation is triggered as a result of this.
  1367. if (oldTrack && newTrack) {
  1368. const oldTrackSSRC = this.localSSRCs.get(oldTrack.rtcId);
  1369. if (oldTrackSSRC) {
  1370. this.localSSRCs.delete(oldTrack.rtcId);
  1371. this.localSSRCs.set(newTrack.rtcId, oldTrackSSRC);
  1372. const oldSsrcNum = this._extractPrimarySSRC(oldTrackSSRC);
  1373. newTrack.setSsrc(oldSsrcNum);
  1374. }
  1375. }
  1376. // In the scenario where we remove the oldTrack (oldTrack is not null and newTrack is null) on FF
  1377. // if we change the direction to RECVONLY, create answer will generate SDP with only 1 receive
  1378. // only ssrc instead of keeping all 6 ssrcs that we currently have. Stopping the screen sharing
  1379. // and then starting it again will trigger 2 rounds of source-remove and source-add replacing
  1380. // the 6 ssrcs for the screen sharing with 1 receive only ssrc and then removing the receive
  1381. // only ssrc and adding the same 6 ssrcs. On the remote participant's side the same ssrcs will
  1382. // be reused on a new m-line and if the remote participant is FF due to
  1383. // https://bugzilla.mozilla.org/show_bug.cgi?id=1768729 the video stream won't be rendered.
  1384. // That's why we need keep the direction to SENDRECV for FF.
  1385. //
  1386. // NOTE: If we return to the approach of not removing the track for FF and instead using the
  1387. // enabled property for muting the track, we may need to change the direction to
  1388. // RECVONLY if FF still sends the media even though the enabled flag is set to false.
  1389. transceiver.direction
  1390. = newTrack || browser.isFirefox() ? MediaDirection.SENDRECV : MediaDirection.RECVONLY;
  1391. // Configure simulcast encodings on Firefox when a track is added to the peerconnection for the first time.
  1392. const configureEncodingsPromise
  1393. = browser.isFirefox() && !oldTrack && newTrack && this.doesTrueSimulcast(newTrack)
  1394. ? this._setEncodings(newTrack)
  1395. : Promise.resolve();
  1396. return configureEncodingsPromise.then(() => this.isP2P);
  1397. });
  1398. };
  1399. /**
  1400. * Removes local track from the RTCPeerConnection.
  1401. *
  1402. * @param {JitsiLocalTrack} localTrack the local track to be removed.
  1403. * @return {Promise<boolean>} Promise that resolves to true if the underlying PeerConnection's state has changed and
  1404. * renegotiation is required, false if no renegotiation is needed or Promise is rejected when something goes wrong.
  1405. */
  1406. TraceablePeerConnection.prototype.removeTrackFromPc = function(localTrack) {
  1407. const webRtcStream = localTrack.getOriginalStream();
  1408. this.trace('removeTrack', localTrack.rtcId, webRtcStream ? webRtcStream.id : null);
  1409. if (!this._assertTrackBelongs('removeTrack', localTrack)) {
  1410. // Abort - nothing to be done here
  1411. return Promise.reject('Track not found in the peerconnection');
  1412. }
  1413. return this.replaceTrack(localTrack, null, true /* isMuteOperation */).then(() => false);
  1414. };
  1415. /**
  1416. * Updates the remote source map with the given source map for adding or removing sources.
  1417. *
  1418. * @param {Map<string, TPCSourceInfo>} sourceMap - The map of source names to their corresponding SSRCs.
  1419. * @param {boolean} isAdd - Whether the sources are being added or removed.
  1420. * @returns {void}
  1421. */
  1422. TraceablePeerConnection.prototype.updateRemoteSources = function(sourceMap, isAdd) {
  1423. for (const [ sourceName, ssrcInfo ] of sourceMap) {
  1424. if (isAdd) {
  1425. this._remoteSsrcMap.set(sourceName, ssrcInfo);
  1426. } else {
  1427. this._remoteSsrcMap.delete(sourceName);
  1428. }
  1429. }
  1430. };
  1431. /**
  1432. * Returns true if the codec selection API is used for switching between codecs for the video sources.
  1433. *
  1434. * @returns {boolean}
  1435. */
  1436. TraceablePeerConnection.prototype.usesCodecSelectionAPI = function() {
  1437. // Browser throws an error when H.264 is set on the encodings. Therefore, munge the SDP when H.264 needs to be
  1438. // selected.
  1439. // TODO: Remove this check when the above issue is fixed.
  1440. return this._usesCodecSelectionAPI && this.codecSettings.codecList[0] !== CodecMimeType.H264;
  1441. };
  1442. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  1443. this.trace('createDataChannel', label, opts);
  1444. return this.peerconnection.createDataChannel(label, opts);
  1445. };
  1446. /**
  1447. * Adjusts the media direction on the remote description based on availability of local and remote sources in a p2p
  1448. * media connection.
  1449. *
  1450. * @param {RTCSessionDescription} remoteDescription the WebRTC session description instance for the remote description.
  1451. * @returns the transformed remoteDescription.
  1452. * @private
  1453. */
  1454. TraceablePeerConnection.prototype._adjustRemoteMediaDirection = function(remoteDescription) {
  1455. const transformer = new SdpTransformWrap(remoteDescription.sdp);
  1456. [ MediaType.AUDIO, MediaType.VIDEO ].forEach(mediaType => {
  1457. const media = transformer.selectMedia(mediaType);
  1458. const localSources = this.getLocalTracks(mediaType).length;
  1459. const remoteSources = this.getRemoteTracks(null, mediaType).length;
  1460. media.forEach((mLine, idx) => {
  1461. if (localSources && localSources === remoteSources) {
  1462. mLine.direction = MediaDirection.SENDRECV;
  1463. } else if (!localSources && !remoteSources) {
  1464. mLine.direction = MediaDirection.INACTIVE;
  1465. } else if (!localSources) {
  1466. mLine.direction = MediaDirection.SENDONLY;
  1467. } else if (!remoteSources) {
  1468. mLine.direction = MediaDirection.RECVONLY;
  1469. // When there are 2 local sources and 1 remote source, the first m-line should be set to 'sendrecv' while
  1470. // the second one needs to be set to 'recvonly'.
  1471. } else if (localSources > remoteSources) {
  1472. mLine.direction = idx ? MediaDirection.RECVONLY : MediaDirection.SENDRECV;
  1473. // When there are 2 remote sources and 1 local source, the first m-line should be set to 'sendrecv' while
  1474. // the second one needs to be set to 'sendonly'.
  1475. } else {
  1476. mLine.direction = idx ? MediaDirection.SENDONLY : MediaDirection.SENDRECV;
  1477. }
  1478. });
  1479. });
  1480. return {
  1481. type: remoteDescription.type,
  1482. sdp: transformer.toRawSDP()
  1483. };
  1484. };
  1485. /**
  1486. * Returns the codec to be used for screenshare based on the supported codecs and the preferred codec requested
  1487. * through config.js setting.
  1488. *
  1489. * @param {CodecMimeType} defaultCodec - the preferred codec for video tracks.
  1490. * @returns {CodecMimeType}
  1491. */
  1492. TraceablePeerConnection.prototype._getPreferredCodecForScreenshare = function(defaultCodec) {
  1493. // Use the same codec for both camera and screenshare if the client doesn't support the codec selection API.
  1494. if (!this.usesCodecSelectionAPI()) {
  1495. return defaultCodec;
  1496. }
  1497. const { screenshareCodec } = this.codecSettings;
  1498. if (screenshareCodec && this.codecSettings.codecList.find(c => c === screenshareCodec)) {
  1499. return screenshareCodec;
  1500. }
  1501. // Default to AV1 for screenshare if its supported and is not overriden through config.js.
  1502. if (this.codecSettings.codecList.find(c => c === CodecMimeType.AV1)) {
  1503. return CodecMimeType.AV1;
  1504. }
  1505. return defaultCodec;
  1506. };
  1507. /**
  1508. * Sets up the _dtlsTransport object and initializes callbacks for it.
  1509. */
  1510. TraceablePeerConnection.prototype._initializeDtlsTransport = function() {
  1511. // We are assuming here that we only have one bundled transport here
  1512. if (!this.peerconnection.getSenders || this._dtlsTransport) {
  1513. return;
  1514. }
  1515. const senders = this.peerconnection.getSenders();
  1516. if (senders.length !== 0 && senders[0].transport) {
  1517. this._dtlsTransport = senders[0].transport;
  1518. this._dtlsTransport.onerror = error => {
  1519. logger.error(`${this} DtlsTransport error: ${error}`);
  1520. };
  1521. this._dtlsTransport.onstatechange = () => {
  1522. this.trace('dtlsTransport.onstatechange', this._dtlsTransport.state);
  1523. };
  1524. }
  1525. };
  1526. /**
  1527. * Returns the expected send resolution for a local video track based on what encodings are currently active.
  1528. *
  1529. * @param {JitsiLocalTrack} localTrack - The local video track.
  1530. * @returns {number}
  1531. */
  1532. TraceablePeerConnection.prototype.calculateExpectedSendResolution = function(localTrack) {
  1533. const captureResolution = localTrack.getCaptureResolution();
  1534. let result = Math.min(localTrack.maxEnabledResolution, captureResolution);
  1535. if (localTrack.getVideoType() === VideoType.CAMERA) {
  1536. // Find the closest matching resolution based on the current codec, simulcast config and the requested
  1537. // resolution by the bridge or the peer.
  1538. if (this.doesTrueSimulcast(localTrack)) {
  1539. const sender = this.findSenderForTrack(localTrack.getTrack());
  1540. if (!sender) {
  1541. return result;
  1542. }
  1543. const { encodings } = sender.getParameters();
  1544. result = encodings.reduce((maxValue, encoding) => {
  1545. if (encoding.active) {
  1546. // eslint-disable-next-line no-param-reassign
  1547. maxValue = Math.max(maxValue, Math.floor(captureResolution / encoding.scaleResolutionDownBy));
  1548. }
  1549. return maxValue;
  1550. }, 0);
  1551. }
  1552. }
  1553. return result;
  1554. };
  1555. /**
  1556. * Configures the stream encodings for the audio tracks that are added to the peerconnection.
  1557. *
  1558. * @param {JitsiLocalTrack} localAudioTrack - The local audio track.
  1559. * @returns {Promise} promise that will be resolved when the operation is successful and rejected otherwise.
  1560. */
  1561. TraceablePeerConnection.prototype.configureAudioSenderEncodings = function(localAudioTrack = null) {
  1562. if (localAudioTrack) {
  1563. return this._setEncodings(localAudioTrack);
  1564. }
  1565. const promises = [];
  1566. for (const track of this.getLocalTracks(MediaType.AUDIO)) {
  1567. promises.push(this._setEncodings(track));
  1568. }
  1569. return Promise.allSettled(promises);
  1570. };
  1571. /**
  1572. * Configures the RTCRtpEncodingParameters of the outbound rtp stream associated with the given track.
  1573. *
  1574. * @param {JitsiLocalTracj} localTrack - The local track whose outbound stream needs to be configured.
  1575. * @returns {Promise} - A promise that resolves when the operation is successful, rejected otherwise.
  1576. */
  1577. TraceablePeerConnection.prototype._configureSenderEncodings = async function(localTrack) {
  1578. const mediaType = localTrack.getType();
  1579. const transceiver = localTrack?.track && localTrack.getOriginalStream()
  1580. ? this.peerconnection.getTransceivers().find(t => t.sender?.track?.id === localTrack.getTrackId())
  1581. : this.peerconnection.getTransceivers().find(t => t.receiver?.track?.kind === mediaType);
  1582. const parameters = transceiver?.sender?.getParameters();
  1583. // Resolve if the encodings are not available yet. This happens immediately after the track is added to the
  1584. // peerconnection on chrome in unified-plan. It is ok to ignore and not report the error here since the
  1585. // action that triggers 'addTrack' (like unmute) will also configure the encodings and set bitrates after that.
  1586. if (!parameters?.encodings?.length) {
  1587. return;
  1588. }
  1589. parameters.encodings = this.tpcUtils.getStreamEncodings(localTrack);
  1590. await transceiver.sender.setParameters(parameters);
  1591. };
  1592. /**
  1593. * Enables/disables the streams by changing the active field on RTCRtpEncodingParameters for a given RTCRtpSender.
  1594. *
  1595. * @param {RTCRtpSender} sender - the sender associated with a MediaStreamTrack.
  1596. * @param {boolean} enable - whether the streams needs to be enabled or disabled.
  1597. * @returns {Promise} - A promise that resolves when the operation is successful, rejected otherwise.
  1598. */
  1599. TraceablePeerConnection.prototype._enableSenderEncodings = async function(sender, enable) {
  1600. const parameters = sender.getParameters();
  1601. if (parameters?.encodings?.length) {
  1602. for (const encoding of parameters.encodings) {
  1603. encoding.active = enable;
  1604. }
  1605. }
  1606. await sender.setParameters(parameters);
  1607. };
  1608. /**
  1609. * Configures the stream encodings depending on the video type, scalability mode and the bitrate settings for the codec
  1610. * that is currently selected.
  1611. *
  1612. * @param {JitsiLocalTrack} - The local track for which the sender encodings have to configured.
  1613. * @param {CodecMimeType} - The preferred codec for the video track.
  1614. * @returns {Promise} promise that will be resolved when the operation is successful and rejected otherwise.
  1615. */
  1616. TraceablePeerConnection.prototype.configureVideoSenderEncodings = function(localVideoTrack, codec) {
  1617. const preferredCodec = codec ?? this.codecSettings.codecList[0];
  1618. if (localVideoTrack) {
  1619. const height = this._senderMaxHeights.get(localVideoTrack.getSourceName()) ?? VIDEO_QUALITY_LEVELS[0].height;
  1620. return this.setSenderVideoConstraints(height, localVideoTrack, preferredCodec);
  1621. }
  1622. const promises = [];
  1623. for (const track of this.getLocalVideoTracks()) {
  1624. const maxHeight = this._senderMaxHeights.get(track.getSourceName()) ?? VIDEO_QUALITY_LEVELS[0].height;
  1625. promises.push(this.setSenderVideoConstraints(maxHeight, track, preferredCodec));
  1626. }
  1627. return Promise.allSettled(promises);
  1628. };
  1629. /**
  1630. * Set the simulcast stream encoding properties on the RTCRtpSender.
  1631. *
  1632. * @param {JitsiLocalTrack} localTrack - the current track in use for which the encodings are to be set.
  1633. * @returns {Promise<void>} - resolved when done.
  1634. */
  1635. TraceablePeerConnection.prototype._setEncodings = function(localTrack) {
  1636. if (localTrack.getType() === MediaType.VIDEO) {
  1637. return this._updateVideoSenderParameters(() => this._configureSenderEncodings(localTrack));
  1638. }
  1639. return this._configureSenderEncodings(localTrack);
  1640. };
  1641. /**
  1642. * Munges the provided description to update the codec order, set the max bitrates (for VP9 K-SVC), set stereo flag
  1643. * and update the DD Header extensions for AV1.
  1644. *
  1645. * @param {RTCSessionDescription} description - The description to be munged.
  1646. * @returns {RTCSessionDescription} - The munged description.
  1647. */
  1648. TraceablePeerConnection.prototype._mungeDescription = function(description) {
  1649. this.trace('RTCSessionDescription::preTransform', dumpSDP(description));
  1650. let mungedSdp = transform.parse(description.sdp);
  1651. mungedSdp = this.tpcUtils.mungeOpus(mungedSdp);
  1652. mungedSdp = this.tpcUtils.mungeCodecOrder(mungedSdp);
  1653. mungedSdp = this.tpcUtils.setMaxBitrates(mungedSdp, true);
  1654. const mungedDescription = {
  1655. type: description.type,
  1656. sdp: transform.write(mungedSdp)
  1657. };
  1658. this.trace('RTCSessionDescription::postTransform', dumpSDP(mungedDescription));
  1659. return mungedDescription;
  1660. };
  1661. /**
  1662. * Sets the local description on the peerconnection.
  1663. *
  1664. * @param {RTCSessionDescription} description - The local description to be set.
  1665. * @returns {Promise<void>} - Resolved when the operation is successful and rejected with an error otherwise.
  1666. */
  1667. TraceablePeerConnection.prototype.setLocalDescription = function(description) {
  1668. let localDescription = description;
  1669. localDescription = this._mungeDescription(localDescription);
  1670. return new Promise((resolve, reject) => {
  1671. this.peerconnection.setLocalDescription(localDescription)
  1672. .then(() => {
  1673. this.trace('setLocalDescriptionOnSuccess');
  1674. const localUfrag = SDPUtil.getUfrag(localDescription.sdp);
  1675. if (localUfrag !== this.localUfrag) {
  1676. this.localUfrag = localUfrag;
  1677. this.eventEmitter.emit(RTCEvents.LOCAL_UFRAG_CHANGED, this, localUfrag);
  1678. }
  1679. this._initializeDtlsTransport();
  1680. resolve();
  1681. }, err => {
  1682. this.trace('setLocalDescriptionOnFailure', err);
  1683. reject(err);
  1684. });
  1685. });
  1686. };
  1687. /**
  1688. * Sets the remote description on the peerconnection.
  1689. *
  1690. * @param {RTCSessionDescription} description - The remote description to be set.
  1691. * @returns {Promise<void>} - Resolved when the operation is successful and rejected with an error otherwise.
  1692. */
  1693. TraceablePeerConnection.prototype.setRemoteDescription = function(description) {
  1694. let remoteDescription = description;
  1695. if (this.isSpatialScalabilityOn()) {
  1696. remoteDescription = this.tpcUtils.insertUnifiedPlanSimulcastReceive(remoteDescription);
  1697. this.trace('setRemoteDescription::postTransform (sim receive)', dumpSDP(remoteDescription));
  1698. }
  1699. remoteDescription = this.tpcUtils.ensureCorrectOrderOfSsrcs(remoteDescription);
  1700. this.trace('setRemoteDescription::postTransform (correct ssrc order)', dumpSDP(remoteDescription));
  1701. remoteDescription = this._mungeDescription(remoteDescription);
  1702. return new Promise((resolve, reject) => {
  1703. this.peerconnection.setRemoteDescription(remoteDescription)
  1704. .then(() => {
  1705. this.trace('setRemoteDescriptionOnSuccess');
  1706. const remoteUfrag = SDPUtil.getUfrag(remoteDescription.sdp);
  1707. if (remoteUfrag !== this.remoteUfrag) {
  1708. this.remoteUfrag = remoteUfrag;
  1709. this.eventEmitter.emit(RTCEvents.REMOTE_UFRAG_CHANGED, this, remoteUfrag);
  1710. }
  1711. this._initializeDtlsTransport();
  1712. resolve();
  1713. })
  1714. .catch(err => {
  1715. this.trace('setRemoteDescriptionOnFailure', err);
  1716. reject(err);
  1717. });
  1718. });
  1719. };
  1720. /**
  1721. * Changes the resolution of the video stream that is sent to the peer based on the resolution requested by the peer
  1722. * and user preference, sets the degradation preference on the sender based on the video type, configures the maximum
  1723. * bitrates on the send stream.
  1724. *
  1725. * @param {number} frameHeight - The max frame height to be imposed on the outgoing video stream.
  1726. * @param {JitsiLocalTrack} - The local track for which the sender constraints have to be applied.
  1727. * @param {preferredCodec} - The video codec that needs to be configured on the sender associated with the video source.
  1728. * @returns {Promise} promise that will be resolved when the operation is successful and rejected otherwise.
  1729. */
  1730. TraceablePeerConnection.prototype.setSenderVideoConstraints = function(frameHeight, localVideoTrack, preferredCodec) {
  1731. if (frameHeight < 0 || !isValidNumber(frameHeight)) {
  1732. throw new Error(`Invalid frameHeight: ${frameHeight}`);
  1733. }
  1734. if (!localVideoTrack) {
  1735. throw new Error('Local video track is missing');
  1736. }
  1737. const sourceName = localVideoTrack.getSourceName();
  1738. this._senderMaxHeights.set(sourceName, frameHeight);
  1739. // Ignore sender constraints if the video track is muted.
  1740. if (localVideoTrack.isMuted()) {
  1741. return Promise.resolve();
  1742. }
  1743. const codec = preferredCodec ?? this.codecSettings.codecList[0];
  1744. return this._updateVideoSenderParameters(
  1745. () => this._updateVideoSenderEncodings(frameHeight, localVideoTrack, codec));
  1746. };
  1747. /**
  1748. * Returns a wrapped-up promise so that the setParameters() call on the RTCRtpSender for video sources are chained.
  1749. * This is needed on Chrome as it resets the transaction id after executing setParameters() and can affect the next on
  1750. * the fly updates if they are not chained.
  1751. * https://chromium.googlesource.com/external/webrtc/+/master/pc/rtp_sender.cc#340
  1752. * @param {Function} nextFunction - The function to be called when the last video sender update promise is settled.
  1753. * @returns {Promise}
  1754. */
  1755. TraceablePeerConnection.prototype._updateVideoSenderParameters = function(nextFunction) {
  1756. const nextPromise = this._lastVideoSenderUpdatePromise
  1757. .finally(nextFunction);
  1758. this._lastVideoSenderUpdatePromise = nextPromise;
  1759. return nextPromise;
  1760. };
  1761. /**
  1762. * Configures the video stream with resolution / degradation / maximum bitrates
  1763. *
  1764. * @param {number} frameHeight - The max frame height to be imposed on the outgoing video stream.
  1765. * @param {JitsiLocalTrack} - The local track for which the sender constraints have to be applied.
  1766. * @param {preferredCodec} - The video codec that needs to be configured on the sender associated with the video source.
  1767. * @returns {Promise} promise that will be resolved when the operation is successful and rejected otherwise.
  1768. */
  1769. TraceablePeerConnection.prototype._updateVideoSenderEncodings = function(frameHeight, localVideoTrack, preferredCodec) {
  1770. const videoSender = this.findSenderForTrack(localVideoTrack.getTrack());
  1771. const videoType = localVideoTrack.getVideoType();
  1772. const isScreensharingTrack = videoType === VideoType.DESKTOP;
  1773. if (!videoSender) {
  1774. return Promise.resolve();
  1775. }
  1776. const parameters = videoSender.getParameters();
  1777. if (!parameters?.encodings?.length) {
  1778. return Promise.resolve();
  1779. }
  1780. const isSharingLowFpsScreen = isScreensharingTrack && this._capScreenshareBitrate;
  1781. // Set the degradation preference.
  1782. const preference = isSharingLowFpsScreen
  1783. ? DEGRADATION_PREFERENCE_DESKTOP // Prefer resolution for low fps share.
  1784. : DEGRADATION_PREFERENCE_CAMERA; // Prefer frame-rate for high fps share and camera.
  1785. parameters.degradationPreference = preference;
  1786. // Calculate the encodings active state based on the resolution requested by the bridge.
  1787. const codecForCamera = preferredCodec ?? this.tpcUtils.getConfiguredVideoCodec(localVideoTrack);
  1788. const codec = isScreensharingTrack ? this._getPreferredCodecForScreenshare(codecForCamera) : codecForCamera;
  1789. const activeState = this.tpcUtils.calculateEncodingsActiveState(localVideoTrack, codec, frameHeight);
  1790. let bitrates = this.tpcUtils.calculateEncodingsBitrates(localVideoTrack, codec, frameHeight);
  1791. const scalabilityModes = this.tpcUtils.calculateEncodingsScalabilityMode(localVideoTrack, codec, frameHeight);
  1792. let scaleFactors = this.tpcUtils.calculateEncodingsScaleFactor(localVideoTrack, codec, frameHeight);
  1793. let needsUpdate = false;
  1794. // Do not configure 'scaleResolutionDownBy' and 'maxBitrate' for encoders running in VP9 legacy K-SVC mode since
  1795. // the browser sends only the lowest resolution layer when those are configured. Those fields need to be reset in
  1796. // case they were set when the endpoint was encoding video using the other codecs before switching over to VP9
  1797. // K-SVC codec.
  1798. if (codec === CodecMimeType.VP9
  1799. && browser.supportsSVC()
  1800. && this.isSpatialScalabilityOn()
  1801. && !this.tpcUtils.codecSettings[codec].scalabilityModeEnabled) {
  1802. scaleFactors = scaleFactors.map(() => undefined);
  1803. bitrates = bitrates.map(() => undefined);
  1804. }
  1805. for (const idx in parameters.encodings) {
  1806. if (parameters.encodings.hasOwnProperty(idx)) {
  1807. const {
  1808. active = undefined,
  1809. codec: currentCodec = undefined,
  1810. maxBitrate = undefined,
  1811. scalabilityMode = undefined,
  1812. scaleResolutionDownBy = undefined
  1813. } = parameters.encodings[idx];
  1814. if (active !== activeState[idx]) {
  1815. parameters.encodings[idx].active = activeState[idx];
  1816. needsUpdate = true;
  1817. }
  1818. // Firefox doesn't follow the spec and lets application specify the degradation preference on the
  1819. // encodings.
  1820. browser.isFirefox() && (parameters.encodings[idx].degradationPreference = preference);
  1821. if (scaleResolutionDownBy !== scaleFactors[idx]) {
  1822. parameters.encodings[idx].scaleResolutionDownBy = scaleFactors[idx];
  1823. needsUpdate = true;
  1824. }
  1825. if (maxBitrate !== bitrates[idx]) {
  1826. parameters.encodings[idx].maxBitrate = bitrates[idx];
  1827. needsUpdate = true;
  1828. }
  1829. // Configure scalability mode when its supported and enabled.
  1830. if (scalabilityModes) {
  1831. if (scalabilityMode !== scalabilityModes[idx]) {
  1832. parameters.encodings[idx].scalabilityMode = scalabilityModes[idx];
  1833. needsUpdate = true;
  1834. }
  1835. } else {
  1836. parameters.encodings[idx].scalabilityMode = undefined;
  1837. }
  1838. const expectedPattern = `${MediaType.VIDEO}/${codec.toUpperCase()}`;
  1839. // Configure the codec here if its supported.
  1840. if (this.usesCodecSelectionAPI() && currentCodec?.mimeType !== expectedPattern) {
  1841. const matchingCodec = parameters.codecs.find(pt => pt.mimeType === expectedPattern);
  1842. parameters.encodings[idx].codec = matchingCodec;
  1843. needsUpdate = true;
  1844. Statistics.sendAnalytics(
  1845. VIDEO_CODEC_CHANGED,
  1846. {
  1847. value: codec,
  1848. videoType
  1849. });
  1850. }
  1851. }
  1852. }
  1853. if (!needsUpdate) {
  1854. return Promise.resolve();
  1855. }
  1856. logger.info(`${this} setting max height=${frameHeight},encodings=${JSON.stringify(parameters.encodings)}`);
  1857. return videoSender.setParameters(parameters).then(() => {
  1858. localVideoTrack.maxEnabledResolution = frameHeight;
  1859. this.eventEmitter.emit(RTCEvents.LOCAL_TRACK_MAX_ENABLED_RESOLUTION_CHANGED, localVideoTrack);
  1860. });
  1861. };
  1862. /**
  1863. * Resumes or suspends media on the peerconnection by setting the active state on RTCRtpEncodingParameters
  1864. * associated with all the senders that have a track attached to it.
  1865. *
  1866. * @param {boolean} enable - whether outgoing media needs to be enabled or disabled.
  1867. * @param {string} mediaType - media type, 'audio' or 'video', if neither is passed, all outgoing media will either
  1868. * be enabled or disabled.
  1869. * @returns {Promise} - A promise that is resolved when the change is succesful on all the senders, rejected
  1870. * otherwise.
  1871. */
  1872. TraceablePeerConnection.prototype.setMediaTransferActive = function(enable, mediaType) {
  1873. logger.info(`${this} ${enable ? 'Resuming' : 'Suspending'} media transfer.`);
  1874. const senders = this.peerconnection.getSenders()
  1875. .filter(s => Boolean(s.track) && (!mediaType || s.track.kind === mediaType));
  1876. const promises = [];
  1877. for (const sender of senders) {
  1878. if (sender.track.kind === MediaType.VIDEO) {
  1879. promises.push(this._updateVideoSenderParameters(() => this._enableSenderEncodings(sender, enable)));
  1880. } else {
  1881. promises.push(this._enableSenderEncodings(sender, enable));
  1882. }
  1883. }
  1884. return Promise.allSettled(promises)
  1885. .then(settledResult => {
  1886. const errors = settledResult
  1887. .filter(result => result.status === 'rejected')
  1888. .map(result => result.reason);
  1889. if (errors.length) {
  1890. return Promise.reject(new Error('Failed to change encodings on the RTCRtpSenders'
  1891. + `${errors.join(' ')}`));
  1892. }
  1893. return Promise.resolve();
  1894. });
  1895. };
  1896. /**
  1897. * Enables/disables outgoing video media transmission on this peer connection. When disabled the stream encoding's
  1898. * active state is enabled or disabled to send or stop the media.
  1899. * @param {boolean} active <tt>true</tt> to enable video media transmission or <tt>false</tt> to disable. If the value
  1900. * is not a boolean the call will have no effect.
  1901. * @return {Promise} A promise that is resolved when the change is succesful, rejected otherwise.
  1902. * @public
  1903. */
  1904. TraceablePeerConnection.prototype.setVideoTransferActive = function(active) {
  1905. logger.debug(`${this} video transfer active: ${active}`);
  1906. const changed = this.videoTransferActive !== active;
  1907. this.videoTransferActive = active;
  1908. if (changed) {
  1909. return this.setMediaTransferActive(active, MediaType.VIDEO);
  1910. }
  1911. return Promise.resolve();
  1912. };
  1913. /**
  1914. * Sends DTMF tones if possible.
  1915. *
  1916. * @param {string} tones - The DTMF tones string as defined by {@code RTCDTMFSender.insertDTMF}, 'tones' argument.
  1917. * @param {number} duration - The amount of time in milliseconds that each DTMF should last. It's 200ms by default.
  1918. * @param {number} interToneGap - The length of time in miliseconds to wait between tones. It's 200ms by default.
  1919. *
  1920. * @returns {void}
  1921. */
  1922. TraceablePeerConnection.prototype.sendTones = function(tones, duration = 200, interToneGap = 200) {
  1923. if (!this._dtmfSender) {
  1924. if (this.peerconnection.getSenders) {
  1925. const rtpSender = this.peerconnection.getSenders().find(s => s.dtmf);
  1926. this._dtmfSender = rtpSender && rtpSender.dtmf;
  1927. this._dtmfSender && logger.info(`${this} initialized DTMFSender using getSenders`);
  1928. }
  1929. if (!this._dtmfSender) {
  1930. const localAudioTrack = Array.from(this.localTracks.values()).find(t => t.isAudioTrack());
  1931. if (this.peerconnection.createDTMFSender && localAudioTrack) {
  1932. this._dtmfSender = this.peerconnection.createDTMFSender(localAudioTrack.getTrack());
  1933. }
  1934. this._dtmfSender && logger.info(`${this} initialized DTMFSender using deprecated createDTMFSender`);
  1935. }
  1936. if (this._dtmfSender) {
  1937. this._dtmfSender.ontonechange = this._onToneChange.bind(this);
  1938. }
  1939. }
  1940. if (this._dtmfSender) {
  1941. if (this._dtmfSender.toneBuffer) {
  1942. this._dtmfTonesQueue.push({
  1943. tones,
  1944. duration,
  1945. interToneGap
  1946. });
  1947. return;
  1948. }
  1949. this._dtmfSender.insertDTMF(tones, duration, interToneGap);
  1950. } else {
  1951. logger.warn(`${this} sendTones - failed to select DTMFSender`);
  1952. }
  1953. };
  1954. /**
  1955. * Callback ivoked by {@code this._dtmfSender} when it has finished playing
  1956. * a single tone.
  1957. *
  1958. * @param {Object} event - The tonechange event which indicates what characters
  1959. * are left to be played for the current tone.
  1960. * @private
  1961. * @returns {void}
  1962. */
  1963. TraceablePeerConnection.prototype._onToneChange = function(event) {
  1964. // An empty event.tone indicates the current tones have finished playing.
  1965. // Automatically start playing any queued tones on finish.
  1966. if (this._dtmfSender && event.tone === '' && this._dtmfTonesQueue.length) {
  1967. const { tones, duration, interToneGap } = this._dtmfTonesQueue.shift();
  1968. this._dtmfSender.insertDTMF(tones, duration, interToneGap);
  1969. }
  1970. };
  1971. /**
  1972. * Closes underlying WebRTC PeerConnection instance and removes all remote
  1973. * tracks by emitting {@link RTCEvents.REMOTE_TRACK_REMOVED} for each one of
  1974. * them.
  1975. */
  1976. TraceablePeerConnection.prototype.close = function() {
  1977. this.trace('stop');
  1978. // Off SignalingEvents
  1979. this.signalingLayer.off(SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  1980. this.signalingLayer.off(SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  1981. this.peerconnection.removeEventListener('track', this.onTrack);
  1982. if (FeatureFlags.isSsrcRewritingSupported()) {
  1983. for (const remoteTrack of this.remoteTracksBySsrc.values()) {
  1984. this._removeRemoteTrack(remoteTrack);
  1985. }
  1986. this.remoteTracksBySsrc.clear();
  1987. } else {
  1988. for (const peerTracks of this.remoteTracks.values()) {
  1989. for (const remoteTracks of peerTracks.values()) {
  1990. for (const remoteTrack of remoteTracks) {
  1991. this._removeRemoteTrack(remoteTrack);
  1992. }
  1993. }
  1994. }
  1995. this.remoteTracks.clear();
  1996. }
  1997. this._dtmfSender = null;
  1998. this._dtmfTonesQueue = [];
  1999. if (!this.rtc._removePeerConnection(this)) {
  2000. logger.error(`${this} rtc._removePeerConnection returned false`);
  2001. }
  2002. if (this.statsinterval !== null) {
  2003. window.clearInterval(this.statsinterval);
  2004. this.statsinterval = null;
  2005. }
  2006. logger.info(`${this} Closing peerconnection`);
  2007. this.peerconnection.close();
  2008. };
  2009. TraceablePeerConnection.prototype.createAnswer = function(constraints) {
  2010. return this._createOfferOrAnswer(false /* answer */, constraints);
  2011. };
  2012. TraceablePeerConnection.prototype.createOffer = function(constraints) {
  2013. return this._createOfferOrAnswer(true /* offer */, constraints);
  2014. };
  2015. TraceablePeerConnection.prototype._createOfferOrAnswer = function(isOffer, constraints) {
  2016. const logName = isOffer ? 'Offer' : 'Answer';
  2017. this.trace(`create${logName}`, JSON.stringify(constraints, null, ' '));
  2018. const handleSuccess = (resultSdp, resolveFn, rejectFn) => {
  2019. try {
  2020. this.trace(
  2021. `create${logName}OnSuccess::preTransform`, dumpSDP(resultSdp));
  2022. // Munge local description to add 3 SSRCs for video tracks when spatial scalability is enabled.
  2023. if (this.isSpatialScalabilityOn() && browser.usesSdpMungingForSimulcast()) {
  2024. // eslint-disable-next-line no-param-reassign
  2025. resultSdp = this.simulcast.mungeLocalDescription(resultSdp);
  2026. this.trace(`create${logName} OnSuccess::postTransform (simulcast)`, dumpSDP(resultSdp));
  2027. }
  2028. if (!this.options.disableRtx && browser.usesSdpMungingForSimulcast()) {
  2029. // eslint-disable-next-line no-param-reassign
  2030. resultSdp = {
  2031. type: resultSdp.type,
  2032. sdp: this.rtxModifier.modifyRtxSsrcs(resultSdp.sdp)
  2033. };
  2034. this.trace(
  2035. `create${logName}`
  2036. + 'OnSuccess::postTransform (rtx modifier)',
  2037. dumpSDP(resultSdp));
  2038. }
  2039. this._processAndExtractSourceInfo(resultSdp.sdp);
  2040. resolveFn(resultSdp);
  2041. } catch (e) {
  2042. this.trace(`create${logName}OnError`, e);
  2043. this.trace(`create${logName}OnError`, dumpSDP(resultSdp));
  2044. logger.error(`${this} create${logName}OnError`, e, dumpSDP(resultSdp));
  2045. rejectFn(e);
  2046. }
  2047. };
  2048. const handleFailure = (err, rejectFn) => {
  2049. this.trace(`create${logName}OnFailure`, err);
  2050. rejectFn(err);
  2051. };
  2052. // Set the codec preference before creating an offer or answer so that the generated SDP will have
  2053. // the correct preference order.
  2054. if (browser.supportsCodecPreferences() && this.codecSettings) {
  2055. const { codecList, mediaType } = this.codecSettings;
  2056. const transceivers = this.peerconnection.getTransceivers()
  2057. .filter(t => t.receiver && t.receiver?.track?.kind === mediaType);
  2058. let capabilities = RTCRtpReceiver.getCapabilities(mediaType)?.codecs;
  2059. if (transceivers.length && capabilities) {
  2060. // Rearrange the codec list as per the preference order.
  2061. for (const codec of codecList.slice().reverse()) {
  2062. // Move the desired codecs (all variations of it as well) to the beginning of the list
  2063. /* eslint-disable-next-line arrow-body-style */
  2064. capabilities.sort(caps => {
  2065. return caps.mimeType.toLowerCase() === `${mediaType}/${codec}` ? -1 : 1;
  2066. });
  2067. }
  2068. // Disable ulpfec and RED on the p2p peerconnection.
  2069. if (this.isP2P && mediaType === MediaType.VIDEO) {
  2070. capabilities = capabilities
  2071. .filter(caps => caps.mimeType.toLowerCase() !== `${MediaType.VIDEO}/${CodecMimeType.ULPFEC}`
  2072. && caps.mimeType.toLowerCase() !== `${MediaType.VIDEO}/${CodecMimeType.RED}`);
  2073. }
  2074. // Apply codec preference to all the transceivers associated with the given media type.
  2075. for (const transceiver of transceivers) {
  2076. transceiver.setCodecPreferences(capabilities);
  2077. }
  2078. }
  2079. }
  2080. return new Promise((resolve, reject) => {
  2081. let oaPromise;
  2082. if (isOffer) {
  2083. oaPromise = this.peerconnection.createOffer(constraints);
  2084. } else {
  2085. oaPromise = this.peerconnection.createAnswer(constraints);
  2086. }
  2087. oaPromise
  2088. .then(
  2089. sdp => handleSuccess(sdp, resolve, reject),
  2090. error => handleFailure(error, reject));
  2091. });
  2092. };
  2093. /**
  2094. * Extract primary SSRC from given {@link TrackSSRCInfo} object.
  2095. * @param {TrackSSRCInfo} ssrcObj
  2096. * @return {number|null} the primary SSRC or <tt>null</tt>
  2097. */
  2098. TraceablePeerConnection.prototype._extractPrimarySSRC = function(ssrcObj) {
  2099. if (ssrcObj && ssrcObj.groups && ssrcObj.groups.length) {
  2100. return ssrcObj.groups[0].ssrcs[0];
  2101. } else if (ssrcObj && ssrcObj.ssrcs && ssrcObj.ssrcs.length) {
  2102. return ssrcObj.ssrcs[0];
  2103. }
  2104. return null;
  2105. };
  2106. /**
  2107. * Track the SSRCs seen so far.
  2108. * @param {number} ssrc - SSRC.
  2109. * @return {boolean} - Whether this is a new SSRC.
  2110. */
  2111. TraceablePeerConnection.prototype.addRemoteSsrc = function(ssrc) {
  2112. const existing = this.remoteSSRCs.has(ssrc);
  2113. if (!existing) {
  2114. this.remoteSSRCs.add(ssrc);
  2115. }
  2116. return !existing;
  2117. };
  2118. TraceablePeerConnection.prototype.addIceCandidate = function(candidate) {
  2119. this.trace('addIceCandidate', JSON.stringify({
  2120. candidate: candidate.candidate,
  2121. sdpMid: candidate.sdpMid,
  2122. sdpMLineIndex: candidate.sdpMLineIndex,
  2123. usernameFragment: candidate.usernameFragment
  2124. }, null, ' '));
  2125. return this.peerconnection.addIceCandidate(candidate);
  2126. };
  2127. /**
  2128. * Obtains call-related stats from the peer connection.
  2129. *
  2130. * @returns {Promise<Object>} Promise which resolves with data providing statistics about
  2131. * the peerconnection.
  2132. */
  2133. TraceablePeerConnection.prototype.getStats = function() {
  2134. return this.peerconnection.getStats();
  2135. };
  2136. /**
  2137. * Creates a text representation of this <tt>TraceablePeerConnection</tt>
  2138. * instance.
  2139. * @return {string}
  2140. */
  2141. TraceablePeerConnection.prototype.toString = function() {
  2142. return `TPC[id=${this.id},type=${this.isP2P ? 'P2P' : 'JVB'}]`;
  2143. };