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

TraceablePeerConnection.js 97KB

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