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

TraceablePeerConnection.js 101KB

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