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

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