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 97KB

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