modified lib-jitsi-meet dev repo
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 104KB

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