Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

TraceablePeerConnection.js 102KB

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