modified lib-jitsi-meet dev repo
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

TraceablePeerConnection.js 105KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990
  1. /* global __filename, RTCSessionDescription */
  2. import { getLogger } from '@jitsi/logger';
  3. import { Interop } from '@jitsi/sdp-interop';
  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. const webrtcStream = track.getOriginalStream();
  1433. if (this._usesUnifiedPlan) {
  1434. logger.debug(`${this} TPC.addTrack using unified plan`);
  1435. if (webrtcStream) {
  1436. try {
  1437. this.tpcUtils.addTrack(track, isInitiator);
  1438. } catch (error) {
  1439. logger.error(`${this} Adding track=${track} failed: ${error?.message}`);
  1440. return Promise.reject(error);
  1441. }
  1442. }
  1443. } else {
  1444. // Use addStream API for the plan-b case.
  1445. if (webrtcStream) {
  1446. this._addStream(webrtcStream);
  1447. // It's not ok for a track to not have a WebRTC stream if:
  1448. } else if (!browser.doesVideoMuteByStreamRemove()
  1449. || track.isAudioTrack()
  1450. || (track.isVideoTrack() && !track.isMuted())) {
  1451. return Promise.reject(new Error(`${this} no WebRTC stream for track=${track}`));
  1452. }
  1453. // Muted video tracks do not have WebRTC stream
  1454. if (browser.doesVideoMuteByStreamRemove() && track.isVideoTrack() && track.isMuted()) {
  1455. const ssrcInfo = this.generateNewStreamSSRCInfo(track);
  1456. this.sdpConsistency.setPrimarySsrc(ssrcInfo.ssrcs[0]);
  1457. const simGroup
  1458. = ssrcInfo.groups.find(groupInfo => groupInfo.semantics === 'SIM');
  1459. if (simGroup) {
  1460. this.simulcast.setSsrcCache(simGroup.ssrcs);
  1461. }
  1462. const fidGroups
  1463. = ssrcInfo.groups.filter(
  1464. groupInfo => groupInfo.semantics === 'FID');
  1465. if (fidGroups) {
  1466. const rtxSsrcMapping = new Map();
  1467. fidGroups.forEach(fidGroup => {
  1468. const primarySsrc = fidGroup.ssrcs[0];
  1469. const rtxSsrc = fidGroup.ssrcs[1];
  1470. rtxSsrcMapping.set(primarySsrc, rtxSsrc);
  1471. });
  1472. this.rtxModifier.setSsrcCache(rtxSsrcMapping);
  1473. }
  1474. }
  1475. }
  1476. let promiseChain = Promise.resolve();
  1477. // On Firefox, the encodings have to be configured on the sender only after the transceiver is created.
  1478. if (browser.isFirefox()) {
  1479. promiseChain = promiseChain.then(() => webrtcStream && this.tpcUtils.setEncodings(track));
  1480. }
  1481. return promiseChain;
  1482. };
  1483. /**
  1484. * Adds local track as part of the unmute operation.
  1485. * @param {JitsiLocalTrack} track the track to be added as part of the unmute operation.
  1486. *
  1487. * @return {Promise<boolean>} Promise that resolves to true if the underlying PeerConnection's
  1488. * state has changed and renegotiation is required, false if no renegotiation is needed or
  1489. * Promise is rejected when something goes wrong.
  1490. */
  1491. TraceablePeerConnection.prototype.addTrackUnmute = function(track) {
  1492. logger.info(`${this} Adding track=${track} as unmute`);
  1493. if (!this._assertTrackBelongs('addTrackUnmute', track)) {
  1494. // Abort
  1495. return Promise.reject('Track not found on the peerconnection');
  1496. }
  1497. const webRtcStream = track.getOriginalStream();
  1498. if (!webRtcStream) {
  1499. logger.error(`${this} Unable to add track=${track} as unmute - no WebRTC stream`);
  1500. return Promise.reject('Stream not found');
  1501. }
  1502. if (this._usesUnifiedPlan) {
  1503. return this.tpcUtils.replaceTrack(null, track).then(() => this.isP2P);
  1504. }
  1505. this._addStream(webRtcStream);
  1506. return Promise.resolve(true);
  1507. };
  1508. /**
  1509. * Adds WebRTC media stream to the underlying PeerConnection
  1510. * @param {MediaStream} mediaStream
  1511. * @private
  1512. */
  1513. TraceablePeerConnection.prototype._addStream = function(mediaStream) {
  1514. this.peerconnection.addStream(mediaStream);
  1515. this._addedStreams.push(mediaStream);
  1516. };
  1517. /**
  1518. * Removes WebRTC media stream from the underlying PeerConection
  1519. * @param {MediaStream} mediaStream
  1520. */
  1521. TraceablePeerConnection.prototype._removeStream = function(mediaStream) {
  1522. this.peerconnection.removeStream(mediaStream);
  1523. this._addedStreams
  1524. = this._addedStreams.filter(stream => stream !== mediaStream);
  1525. };
  1526. /**
  1527. * This method when called will check if given <tt>localTrack</tt> belongs to
  1528. * this TPC (that it has been previously added using {@link addTrack}). If the
  1529. * track does not belong an error message will be logged.
  1530. * @param {string} methodName the method name that will be logged in an error
  1531. * message
  1532. * @param {JitsiLocalTrack} localTrack
  1533. * @return {boolean} <tt>true</tt> if given local track belongs to this TPC or
  1534. * <tt>false</tt> otherwise.
  1535. * @private
  1536. */
  1537. TraceablePeerConnection.prototype._assertTrackBelongs = function(
  1538. methodName,
  1539. localTrack) {
  1540. const doesBelong = this.localTracks.has(localTrack?.rtcId);
  1541. if (!doesBelong) {
  1542. logger.error(`${this} ${methodName}: track=${localTrack} does not belong to pc`);
  1543. }
  1544. return doesBelong;
  1545. };
  1546. /**
  1547. * Returns the codec that is configured on the client as the preferred video codec.
  1548. * This takes into account the current order of codecs in the local description sdp.
  1549. *
  1550. * @returns {CodecMimeType} The codec that is set as the preferred codec to receive
  1551. * video in the local SDP.
  1552. */
  1553. TraceablePeerConnection.prototype.getConfiguredVideoCodec = function() {
  1554. const sdp = this.peerconnection.localDescription?.sdp;
  1555. const defaultCodec = CodecMimeType.VP8;
  1556. if (!sdp) {
  1557. return defaultCodec;
  1558. }
  1559. const parsedSdp = transform.parse(sdp);
  1560. const mLine = parsedSdp.media.find(m => m.type === MediaType.VIDEO);
  1561. const codec = mLine.rtp[0].codec;
  1562. if (codec) {
  1563. return Object.values(CodecMimeType).find(value => value === codec.toLowerCase());
  1564. }
  1565. return defaultCodec;
  1566. };
  1567. /**
  1568. * Enables or disables simulcast for screenshare based on the frame rate requested for desktop track capture.
  1569. *
  1570. * @param {number} maxFps framerate to be used for desktop track capture.
  1571. */
  1572. TraceablePeerConnection.prototype.setDesktopSharingFrameRate = function(maxFps) {
  1573. const lowFps = maxFps <= SS_DEFAULT_FRAME_RATE;
  1574. this._capScreenshareBitrate = this.isSimulcastOn() && lowFps;
  1575. };
  1576. /**
  1577. * Sets the codec preference on the peerconnection. The codec preference goes into effect when
  1578. * the next renegotiation happens.
  1579. *
  1580. * @param {CodecMimeType} preferredCodec the preferred codec.
  1581. * @param {CodecMimeType} disabledCodec the codec that needs to be disabled.
  1582. * @returns {void}
  1583. */
  1584. TraceablePeerConnection.prototype.setVideoCodecs = function(preferredCodec = null, disabledCodec = null) {
  1585. // If both enable and disable are set, disable settings will prevail.
  1586. const enable = disabledCodec === null;
  1587. const mimeType = disabledCodec ? disabledCodec : preferredCodec;
  1588. if (this.codecPreference && (preferredCodec || disabledCodec)) {
  1589. this.codecPreference.enable = enable;
  1590. this.codecPreference.mimeType = mimeType;
  1591. } else if (preferredCodec || disabledCodec) {
  1592. this.codecPreference = {
  1593. enable,
  1594. mediaType: MediaType.VIDEO,
  1595. mimeType
  1596. };
  1597. } else {
  1598. logger.warn(`${this} Invalid codec settings[preferred=${preferredCodec},disabled=${disabledCodec}],
  1599. atleast one value is needed`);
  1600. }
  1601. };
  1602. /**
  1603. * Tells if the given WebRTC <tt>MediaStream</tt> has been added to
  1604. * the underlying WebRTC PeerConnection.
  1605. * @param {MediaStream} mediaStream
  1606. * @returns {boolean}
  1607. */
  1608. TraceablePeerConnection.prototype.isMediaStreamInPc = function(mediaStream) {
  1609. return this._addedStreams.indexOf(mediaStream) > -1;
  1610. };
  1611. /**
  1612. * Remove local track from this TPC.
  1613. * @param {JitsiLocalTrack} localTrack the track to be removed from this TPC.
  1614. *
  1615. * FIXME It should probably remove a boolean just like {@link removeTrackMute}
  1616. * The same applies to addTrack.
  1617. */
  1618. TraceablePeerConnection.prototype.removeTrack = function(localTrack) {
  1619. const webRtcStream = localTrack.getOriginalStream();
  1620. this.trace(
  1621. 'removeStream',
  1622. localTrack.rtcId, webRtcStream ? webRtcStream.id : undefined);
  1623. if (!this._assertTrackBelongs('removeStream', localTrack)) {
  1624. // Abort - nothing to be done here
  1625. return;
  1626. }
  1627. this.localTracks.delete(localTrack.rtcId);
  1628. this.localSSRCs.delete(localTrack.rtcId);
  1629. if (webRtcStream) {
  1630. this.peerconnection.removeStream(webRtcStream);
  1631. }
  1632. };
  1633. /**
  1634. * Returns the sender corresponding to the given media type.
  1635. * @param {MEDIA_TYPE} mediaType - The media type 'audio' or 'video' to be used for the search.
  1636. * @returns {RTPSender|undefined} - The found sender or undefined if no sender
  1637. * was found.
  1638. */
  1639. TraceablePeerConnection.prototype.findSenderByKind = function(mediaType) {
  1640. return this.peerconnection.getSenders().find(s => s.track && s.track.kind === mediaType);
  1641. };
  1642. /**
  1643. * Returns the receiver corresponding to the given MediaStreamTrack.
  1644. *
  1645. * @param {MediaSreamTrack} track - The media stream track used for the search.
  1646. * @returns {RTCRtpReceiver|undefined} - The found receiver or undefined if no receiver
  1647. * was found.
  1648. */
  1649. TraceablePeerConnection.prototype.findReceiverForTrack = function(track) {
  1650. return this.peerconnection.getReceivers().find(r => r.track === track);
  1651. };
  1652. /**
  1653. * Returns the sender corresponding to the given MediaStreamTrack.
  1654. *
  1655. * @param {MediaSreamTrack} track - The media stream track used for the search.
  1656. * @returns {RTCRtpSender|undefined} - The found sender or undefined if no sender
  1657. * was found.
  1658. */
  1659. TraceablePeerConnection.prototype.findSenderForTrack = function(track) {
  1660. return this.peerconnection.getSenders().find(s => s.track === track);
  1661. };
  1662. /**
  1663. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> from the peer connection.
  1664. * Either <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1665. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1666. * <tt>oldTrack</tt>
  1667. *
  1668. * @param {JitsiLocalTrack|null} oldTrack - The current track in use to be replaced on the pc.
  1669. * @param {JitsiLocalTrack|null} newTrack - The new track to be used.
  1670. *
  1671. * @returns {Promise<boolean>} - If the promise resolves with true, renegotiation will be needed.
  1672. * Otherwise no renegotiation is needed.
  1673. */
  1674. TraceablePeerConnection.prototype.replaceTrack = function(oldTrack, newTrack) {
  1675. if (!(oldTrack || newTrack)) {
  1676. logger.info(`${this} replaceTrack called with no new track and no old track`);
  1677. return Promise.resolve();
  1678. }
  1679. if (this._usesUnifiedPlan) {
  1680. logger.debug(`${this} TPC.replaceTrack using unified plan`);
  1681. const mediaType = newTrack?.getType() ?? oldTrack?.getType();
  1682. const stream = newTrack?.getOriginalStream();
  1683. const promise = newTrack && !stream
  1684. // Ignore cases when the track is replaced while the device is in a muted state.
  1685. // The track will be replaced again on the peerconnection when the user unmutes.
  1686. ? Promise.resolve()
  1687. : this.tpcUtils.replaceTrack(oldTrack, newTrack);
  1688. const transceiver = this.tpcUtils.findTransceiver(mediaType, oldTrack);
  1689. return promise
  1690. .then(() => {
  1691. oldTrack && this.localTracks.delete(oldTrack.rtcId);
  1692. newTrack && this.localTracks.set(newTrack.rtcId, newTrack);
  1693. if (transceiver) {
  1694. // Set the transceiver direction.
  1695. transceiver.direction = newTrack ? MediaDirection.SENDRECV : MediaDirection.RECVONLY;
  1696. }
  1697. // Avoid configuring the encodings on Chromium/Safari until simulcast is configured
  1698. // for the newly added track using SDP munging which happens during the renegotiation.
  1699. const configureEncodingsPromise = browser.usesSdpMungingForSimulcast() || !newTrack
  1700. ? Promise.resolve()
  1701. : this.tpcUtils.setEncodings(newTrack);
  1702. // Renegotiate only in the case of P2P. We rely on 'negotiationeeded' to be fired for JVB.
  1703. return configureEncodingsPromise.then(() => this.isP2P);
  1704. });
  1705. }
  1706. logger.debug(`${this} TPC.replaceTrack using plan B`);
  1707. let promiseChain = Promise.resolve();
  1708. if (oldTrack) {
  1709. this.removeTrack(oldTrack);
  1710. }
  1711. if (newTrack) {
  1712. promiseChain = this.addTrack(newTrack);
  1713. }
  1714. return promiseChain.then(() => true);
  1715. };
  1716. /**
  1717. * Removes local track as part of the mute operation.
  1718. * @param {JitsiLocalTrack} localTrack the local track to be remove as part of
  1719. * the mute operation.
  1720. * @return {Promise<boolean>} Promise that resolves to true if the underlying PeerConnection's
  1721. * state has changed and renegotiation is required, false if no renegotiation is needed or
  1722. * Promise is rejected when something goes wrong.
  1723. */
  1724. TraceablePeerConnection.prototype.removeTrackMute = function(localTrack) {
  1725. const webRtcStream = localTrack.getOriginalStream();
  1726. this.trace(
  1727. 'removeStreamMute',
  1728. localTrack.rtcId, webRtcStream ? webRtcStream.id : null);
  1729. if (!this._assertTrackBelongs('removeStreamMute', localTrack)) {
  1730. // Abort - nothing to be done here
  1731. return Promise.reject('Track not found in the peerconnection');
  1732. }
  1733. if (this._usesUnifiedPlan) {
  1734. return this.tpcUtils.replaceTrack(localTrack, null);
  1735. }
  1736. if (webRtcStream) {
  1737. logger.info(`${this} Removing track=${localTrack} as mute`);
  1738. this._removeStream(webRtcStream);
  1739. return Promise.resolve(true);
  1740. }
  1741. logger.error(`${this} removeStreamMute - no WebRTC stream for track=${localTrack}`);
  1742. return Promise.reject('Stream not found');
  1743. };
  1744. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  1745. this.trace('createDataChannel', label, opts);
  1746. return this.peerconnection.createDataChannel(label, opts);
  1747. };
  1748. /**
  1749. * Ensures that the simulcast ssrc-group appears after any other ssrc-groups
  1750. * in the SDP so that simulcast is properly activated.
  1751. *
  1752. * @param {Object} localSdp the WebRTC session description instance for
  1753. * the local description.
  1754. * @private
  1755. */
  1756. TraceablePeerConnection.prototype._ensureSimulcastGroupIsLast = function(
  1757. localSdp) {
  1758. let sdpStr = localSdp.sdp;
  1759. const videoStartIndex = sdpStr.indexOf('m=video');
  1760. const simStartIndex = sdpStr.indexOf('a=ssrc-group:SIM', videoStartIndex);
  1761. let otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1762. if (simStartIndex === -1
  1763. || otherStartIndex === -1
  1764. || otherStartIndex === simStartIndex) {
  1765. return localSdp;
  1766. }
  1767. const simEndIndex = sdpStr.indexOf('\r\n', simStartIndex);
  1768. const simStr = sdpStr.substring(simStartIndex, simEndIndex + 2);
  1769. sdpStr = sdpStr.replace(simStr, '');
  1770. otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1771. const otherEndIndex = sdpStr.indexOf('\r\n', otherStartIndex);
  1772. const sdpHead = sdpStr.slice(0, otherEndIndex);
  1773. const simStrTrimmed = simStr.trim();
  1774. const sdpTail = sdpStr.slice(otherEndIndex);
  1775. sdpStr = `${sdpHead}\r\n${simStrTrimmed}${sdpTail}`;
  1776. return new RTCSessionDescription({
  1777. type: localSdp.type,
  1778. sdp: sdpStr
  1779. });
  1780. };
  1781. /**
  1782. * Will adjust audio and video media direction in the given SDP object to
  1783. * reflect the current status of the {@link audioTransferActive} and
  1784. * {@link videoTransferActive} flags.
  1785. * @param {RTCSessionDescription} localDescription the WebRTC session description instance for
  1786. * the local description.
  1787. * @private
  1788. */
  1789. TraceablePeerConnection.prototype._adjustLocalMediaDirection = function(localDescription) {
  1790. const transformer = new SdpTransformWrap(localDescription.sdp);
  1791. let modifiedDirection = false;
  1792. const audioMedia = transformer.selectMedia(MediaType.AUDIO);
  1793. if (audioMedia) {
  1794. const desiredAudioDirection = this.getDesiredMediaDirection(MediaType.AUDIO);
  1795. if (audioMedia.direction !== desiredAudioDirection) {
  1796. audioMedia.direction = desiredAudioDirection;
  1797. logger.info(`${this} Adjusted local audio direction to ${desiredAudioDirection}`);
  1798. modifiedDirection = true;
  1799. }
  1800. } else {
  1801. logger.warn(`${this} No "audio" media found in the local description`);
  1802. }
  1803. const videoMedia = transformer.selectMedia(MediaType.VIDEO);
  1804. if (videoMedia) {
  1805. const desiredVideoDirection = this.getDesiredMediaDirection(MediaType.VIDEO);
  1806. if (videoMedia.direction !== desiredVideoDirection) {
  1807. videoMedia.direction = desiredVideoDirection;
  1808. logger.info(`${this} Adjusted local video direction to ${desiredVideoDirection}`);
  1809. modifiedDirection = true;
  1810. }
  1811. } else {
  1812. logger.warn(`${this} No "video" media found in the local description`);
  1813. }
  1814. if (modifiedDirection) {
  1815. return new RTCSessionDescription({
  1816. type: localDescription.type,
  1817. sdp: transformer.toRawSDP()
  1818. });
  1819. }
  1820. return localDescription;
  1821. };
  1822. /**
  1823. * Adjusts the media direction on the remote description based on availability of local and remote sources in a p2p
  1824. * media connection.
  1825. *
  1826. * @param {RTCSessionDescription} remoteDescription the WebRTC session description instance for the remote description.
  1827. * @returns the transformed remoteDescription.
  1828. * @private
  1829. */
  1830. TraceablePeerConnection.prototype._adjustRemoteMediaDirection = function(remoteDescription) {
  1831. const transformer = new SdpTransformWrap(remoteDescription.sdp);
  1832. [ MediaType.AUDIO, MediaType.VIDEO ].forEach(mediaType => {
  1833. const media = transformer.selectMedia(mediaType);
  1834. const hasLocalSource = this.hasAnyTracksOfType(mediaType);
  1835. const hasRemoteSource = this.getRemoteTracks(null, mediaType).length > 0;
  1836. media.direction = hasLocalSource && hasRemoteSource
  1837. ? MediaDirection.SENDRECV
  1838. : hasLocalSource
  1839. ? MediaDirection.RECVONLY
  1840. : hasRemoteSource ? MediaDirection.SENDONLY : MediaDirection.INACTIVE;
  1841. });
  1842. return new RTCSessionDescription({
  1843. type: remoteDescription.type,
  1844. sdp: transformer.toRawSDP()
  1845. });
  1846. };
  1847. /**
  1848. * Munges the stereo flag as well as the opusMaxAverageBitrate in the SDP, based
  1849. * on values set through config.js, if present.
  1850. *
  1851. * @param {RTCSessionDescription} description that needs to be munged.
  1852. * @returns {RTCSessionDescription} the munged description.
  1853. */
  1854. TraceablePeerConnection.prototype._mungeOpus = function(description) {
  1855. const { audioQuality } = this.options;
  1856. if (!audioQuality?.stereo && !audioQuality?.opusMaxAverageBitrate) {
  1857. return description;
  1858. }
  1859. const parsedSdp = transform.parse(description.sdp);
  1860. const mLines = parsedSdp.media;
  1861. for (const mLine of mLines) {
  1862. if (mLine.type === 'audio') {
  1863. const { payload } = mLine.rtp.find(protocol => protocol.codec === CodecMimeType.OPUS);
  1864. if (!payload) {
  1865. // eslint-disable-next-line no-continue
  1866. continue;
  1867. }
  1868. let fmtpOpus = mLine.fmtp.find(protocol => protocol.payload === payload);
  1869. if (!fmtpOpus) {
  1870. fmtpOpus = {
  1871. payload,
  1872. config: ''
  1873. };
  1874. }
  1875. const fmtpConfig = transform.parseParams(fmtpOpus.config);
  1876. let sdpChanged = false;
  1877. if (audioQuality?.stereo) {
  1878. fmtpConfig.stereo = 1;
  1879. sdpChanged = true;
  1880. }
  1881. if (audioQuality?.opusMaxAverageBitrate) {
  1882. fmtpConfig.maxaveragebitrate = audioQuality.opusMaxAverageBitrate;
  1883. sdpChanged = true;
  1884. }
  1885. if (!sdpChanged) {
  1886. // eslint-disable-next-line no-continue
  1887. continue;
  1888. }
  1889. let mungedConfig = '';
  1890. for (const key of Object.keys(fmtpConfig)) {
  1891. mungedConfig += `${key}=${fmtpConfig[key]}; `;
  1892. }
  1893. fmtpOpus.config = mungedConfig.trim();
  1894. }
  1895. }
  1896. return new RTCSessionDescription({
  1897. type: description.type,
  1898. sdp: transform.write(parsedSdp)
  1899. });
  1900. };
  1901. /**
  1902. * Configures the stream encodings depending on the video type and the bitrates configured.
  1903. *
  1904. * @returns {Promise} promise that will be resolved when the operation is successful and rejected otherwise.
  1905. */
  1906. TraceablePeerConnection.prototype.configureSenderVideoEncodings = function() {
  1907. return this.setSenderVideoConstraints(this._senderVideoMaxHeight);
  1908. };
  1909. TraceablePeerConnection.prototype.setLocalDescription = function(description) {
  1910. let localSdp = description;
  1911. this.trace('setLocalDescription::preTransform', dumpSDP(localSdp));
  1912. // Munge stereo flag and opusMaxAverageBitrate based on config.js
  1913. localSdp = this._mungeOpus(localSdp);
  1914. if (!this._usesUnifiedPlan) {
  1915. localSdp = this._adjustLocalMediaDirection(localSdp);
  1916. localSdp = this._ensureSimulcastGroupIsLast(localSdp);
  1917. } else if (!this.isP2P) {
  1918. // if we're using unified plan, transform to it first.
  1919. localSdp = this.interop.toUnifiedPlan(localSdp);
  1920. this.trace(
  1921. 'setLocalDescription::postTransform (Unified Plan)',
  1922. dumpSDP(localSdp));
  1923. }
  1924. // Munge the order of the codecs based on the preferences set through config.js if we are using SDP munging.
  1925. if (!this._usesTransceiverCodecPreferences) {
  1926. localSdp = this._mungeCodecOrder(localSdp);
  1927. }
  1928. return new Promise((resolve, reject) => {
  1929. this.peerconnection.setLocalDescription(localSdp)
  1930. .then(() => {
  1931. this.trace('setLocalDescriptionOnSuccess');
  1932. const localUfrag = SDPUtil.getUfrag(localSdp.sdp);
  1933. if (localUfrag !== this.localUfrag) {
  1934. this.localUfrag = localUfrag;
  1935. this.eventEmitter.emit(
  1936. RTCEvents.LOCAL_UFRAG_CHANGED, this, localUfrag);
  1937. }
  1938. resolve();
  1939. }, err => {
  1940. this.trace('setLocalDescriptionOnFailure', err);
  1941. this.eventEmitter.emit(
  1942. RTCEvents.SET_LOCAL_DESCRIPTION_FAILED,
  1943. err, this);
  1944. reject(err);
  1945. });
  1946. });
  1947. };
  1948. /**
  1949. * Enables/disables audio media transmission on this peer connection. When
  1950. * disabled the SDP audio media direction in the local SDP will be adjusted to
  1951. * 'inactive' which means that no data will be sent nor accepted, but
  1952. * the connection should be kept alive.
  1953. * @param {boolean} active <tt>true</tt> to enable audio media transmission or
  1954. * <tt>false</tt> to disable. If the value is not a boolean the call will have
  1955. * no effect.
  1956. * @return {boolean} <tt>true</tt> if the value has changed and sRD/sLD cycle
  1957. * needs to be executed in order for the changes to take effect or
  1958. * <tt>false</tt> if the given value was the same as the previous one.
  1959. * @public
  1960. */
  1961. TraceablePeerConnection.prototype.setAudioTransferActive = function(active) {
  1962. logger.debug(`${this} audio transfer active: ${active}`);
  1963. const changed = this.audioTransferActive !== active;
  1964. this.audioTransferActive = active;
  1965. if (this._usesUnifiedPlan) {
  1966. this.tpcUtils.setAudioTransferActive(active);
  1967. // false means no renegotiation up the chain which is not needed in the Unified mode
  1968. return false;
  1969. }
  1970. return changed;
  1971. };
  1972. TraceablePeerConnection.prototype.setRemoteDescription = function(description) {
  1973. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  1974. /* eslint-disable no-param-reassign */
  1975. // Munge stereo flag and opusMaxAverageBitrate based on config.js
  1976. description = this._mungeOpus(description);
  1977. /* eslint-enable no-param-reassign */
  1978. if (!this._usesUnifiedPlan) {
  1979. // TODO the focus should squeze or explode the remote simulcast
  1980. if (this.isSimulcastOn()) {
  1981. // eslint-disable-next-line no-param-reassign
  1982. description = this.simulcast.mungeRemoteDescription(description, true /* add x-google-conference flag */);
  1983. this.trace(
  1984. 'setRemoteDescription::postTransform (simulcast)',
  1985. dumpSDP(description));
  1986. }
  1987. // eslint-disable-next-line no-param-reassign
  1988. description = normalizePlanB(description);
  1989. } else if (!this.isP2P) {
  1990. const currentDescription = this.peerconnection.remoteDescription;
  1991. // eslint-disable-next-line no-param-reassign
  1992. description = this.interop.toUnifiedPlan(description, currentDescription);
  1993. this.trace(
  1994. 'setRemoteDescription::postTransform (Unified)',
  1995. dumpSDP(description));
  1996. if (this.isSimulcastOn()) {
  1997. // eslint-disable-next-line no-param-reassign
  1998. description = this.simulcast.mungeRemoteDescription(description);
  1999. // eslint-disable-next-line no-param-reassign
  2000. description = this.tpcUtils.insertUnifiedPlanSimulcastReceive(description);
  2001. this.trace(
  2002. 'setRemoteDescription::postTransform (sim receive)',
  2003. dumpSDP(description));
  2004. }
  2005. }
  2006. // Munge the order of the codecs based on the preferences set through config.js.
  2007. // eslint-disable-next-line no-param-reassign
  2008. description = this._mungeCodecOrder(description);
  2009. if (this._usesUnifiedPlan) {
  2010. // eslint-disable-next-line no-param-reassign
  2011. description = this.tpcUtils.ensureCorrectOrderOfSsrcs(description);
  2012. }
  2013. return new Promise((resolve, reject) => {
  2014. this.peerconnection.setRemoteDescription(description)
  2015. .then(() => {
  2016. this.trace('setRemoteDescriptionOnSuccess');
  2017. const remoteUfrag = SDPUtil.getUfrag(description.sdp);
  2018. if (remoteUfrag !== this.remoteUfrag) {
  2019. this.remoteUfrag = remoteUfrag;
  2020. this.eventEmitter.emit(
  2021. RTCEvents.REMOTE_UFRAG_CHANGED, this, remoteUfrag);
  2022. }
  2023. resolve();
  2024. }, err => {
  2025. this.trace('setRemoteDescriptionOnFailure', err);
  2026. this.eventEmitter.emit(
  2027. RTCEvents.SET_REMOTE_DESCRIPTION_FAILED,
  2028. err,
  2029. this);
  2030. reject(err);
  2031. });
  2032. });
  2033. };
  2034. /**
  2035. * Changes the resolution of the video stream that is sent to the peer based on the resolution requested by the peer
  2036. * and user preference, sets the degradation preference on the sender based on the video type, configures the maximum
  2037. * bitrates on the send stream.
  2038. *
  2039. * @param {number} frameHeight - The max frame height to be imposed on the outgoing video stream.
  2040. * @returns {Promise} promise that will be resolved when the operation is successful and rejected otherwise.
  2041. */
  2042. TraceablePeerConnection.prototype.setSenderVideoConstraints = function(frameHeight) {
  2043. if (frameHeight < 0) {
  2044. throw new Error(`Invalid frameHeight: ${frameHeight}`);
  2045. }
  2046. // XXX: This is not yet supported on mobile.
  2047. if (browser.isReactNative()) {
  2048. return Promise.resolve();
  2049. }
  2050. this._senderVideoMaxHeight = frameHeight;
  2051. const localVideoTrack = this.getLocalVideoTrack();
  2052. if (!localVideoTrack || localVideoTrack.isMuted()) {
  2053. return Promise.resolve();
  2054. }
  2055. const videoSender = this.findSenderByKind(MediaType.VIDEO);
  2056. if (!videoSender) {
  2057. return Promise.resolve();
  2058. }
  2059. const parameters = videoSender.getParameters();
  2060. if (!parameters?.encodings?.length) {
  2061. return Promise.resolve();
  2062. }
  2063. // Set the degradation preference.
  2064. const preference = this.isSharingLowFpsScreen()
  2065. ? DEGRADATION_PREFERENCE_DESKTOP // Prefer resolution for low fps share.
  2066. : DEGRADATION_PREFERENCE_CAMERA; // Prefer frame-rate for high fps share and camera.
  2067. parameters.degradationPreference = preference;
  2068. logger.info(`${this} Setting degradation preference [preference=${preference},track=${localVideoTrack}`);
  2069. // Calculate the encodings active state based on the resolution requested by the bridge.
  2070. this.encodingsEnabledState = this.tpcUtils.calculateEncodingsActiveState(localVideoTrack, frameHeight);
  2071. const maxBitrates = this.tpcUtils.calculateEncodingsBitrates(localVideoTrack);
  2072. const videoType = localVideoTrack.getVideoType();
  2073. if (this.isSimulcastOn()) {
  2074. for (const encoding in parameters.encodings) {
  2075. if (parameters.encodings.hasOwnProperty(encoding)) {
  2076. parameters.encodings[encoding].active = this.encodingsEnabledState[encoding];
  2077. // Firefox doesn't follow the spec and lets application specify the degradation preference on the
  2078. // encodings.
  2079. browser.isFirefox() && (parameters.encodings[encoding].degradationPreference = preference);
  2080. // Max bitrates are configured on the encodings only for VP8.
  2081. if (this.getConfiguredVideoCodec() === CodecMimeType.VP8
  2082. && (this.options?.videoQuality?.maxBitratesVideo
  2083. || this.isSharingLowFpsScreen()
  2084. || this._usesUnifiedPlan)) {
  2085. parameters.encodings[encoding].maxBitrate = maxBitrates[encoding];
  2086. }
  2087. }
  2088. }
  2089. this.tpcUtils.updateEncodingsResolution(parameters);
  2090. // For p2p and cases and where simulcast is explicitly disabled.
  2091. } else if (frameHeight > 0) {
  2092. // Do not scale down encodings for desktop tracks for non-simulcast case.
  2093. const scaleFactor = videoType === VideoType.DESKTOP || localVideoTrack.resolution <= frameHeight
  2094. ? HD_SCALE_FACTOR
  2095. : Math.floor(localVideoTrack.resolution / frameHeight);
  2096. parameters.encodings[0].active = true;
  2097. parameters.encodings[0].scaleResolutionDownBy = scaleFactor;
  2098. // Firefox doesn't follow the spec and lets application specify the degradation preference on the encodings.
  2099. browser.isFirefox() && (parameters.encodings[0].degradationPreference = preference);
  2100. // Configure the bitrate.
  2101. if (this.getConfiguredVideoCodec() === CodecMimeType.VP8 && this.options?.videoQuality?.maxBitratesVideo) {
  2102. let bitrate = this.getTargetVideoBitrates()?.high;
  2103. if (videoType === VideoType.CAMERA) {
  2104. bitrate = this.tpcUtils.localStreamEncodingsConfig
  2105. .find(layer => layer.scaleResolutionDownBy === scaleFactor)?.maxBitrate ?? bitrate;
  2106. }
  2107. parameters.encodings[0].maxBitrate = bitrate;
  2108. }
  2109. } else {
  2110. parameters.encodings[0].active = false;
  2111. }
  2112. logger.info(`${this} setting max height=${frameHeight},encodings=${JSON.stringify(parameters.encodings)}`);
  2113. return videoSender.setParameters(parameters).then(() => {
  2114. localVideoTrack.maxEnabledResolution = frameHeight;
  2115. this.eventEmitter.emit(RTCEvents.LOCAL_TRACK_MAX_ENABLED_RESOLUTION_CHANGED, localVideoTrack);
  2116. });
  2117. };
  2118. /**
  2119. * Enables/disables video media transmission on this peer connection. When
  2120. * disabled the SDP video media direction in the local SDP will be adjusted to
  2121. * 'inactive' which means that no data will be sent nor accepted, but
  2122. * the connection should be kept alive.
  2123. * @param {boolean} active <tt>true</tt> to enable video media transmission or
  2124. * <tt>false</tt> to disable. If the value is not a boolean the call will have
  2125. * no effect.
  2126. * @return {boolean} <tt>true</tt> if the value has changed and sRD/sLD cycle
  2127. * needs to be executed in order for the changes to take effect or
  2128. * <tt>false</tt> if the given value was the same as the previous one.
  2129. * @public
  2130. */
  2131. TraceablePeerConnection.prototype.setVideoTransferActive = function(active) {
  2132. logger.debug(`${this} video transfer active: ${active}`);
  2133. const changed = this.videoTransferActive !== active;
  2134. this.videoTransferActive = active;
  2135. if (this._usesUnifiedPlan) {
  2136. this.tpcUtils.setVideoTransferActive(active);
  2137. // false means no renegotiation up the chain which is not needed in the Unified mode
  2138. return false;
  2139. }
  2140. return changed;
  2141. };
  2142. /**
  2143. * Sends DTMF tones if possible.
  2144. *
  2145. * @param {string} tones - The DTMF tones string as defined by {@code RTCDTMFSender.insertDTMF}, 'tones' argument.
  2146. * @param {number} duration - The amount of time in milliseconds that each DTMF should last. It's 200ms by default.
  2147. * @param {number} interToneGap - The length of time in miliseconds to wait between tones. It's 200ms by default.
  2148. *
  2149. * @returns {void}
  2150. */
  2151. TraceablePeerConnection.prototype.sendTones = function(tones, duration = 200, interToneGap = 200) {
  2152. if (!this._dtmfSender) {
  2153. if (this.peerconnection.getSenders) {
  2154. const rtpSender = this.peerconnection.getSenders().find(s => s.dtmf);
  2155. this._dtmfSender = rtpSender && rtpSender.dtmf;
  2156. this._dtmfSender && logger.info(`${this} initialized DTMFSender using getSenders`);
  2157. }
  2158. if (!this._dtmfSender) {
  2159. const localAudioTrack = Array.from(this.localTracks.values()).find(t => t.isAudioTrack());
  2160. if (this.peerconnection.createDTMFSender && localAudioTrack) {
  2161. this._dtmfSender = this.peerconnection.createDTMFSender(localAudioTrack.getTrack());
  2162. }
  2163. this._dtmfSender && logger.info(`${this} initialized DTMFSender using deprecated createDTMFSender`);
  2164. }
  2165. if (this._dtmfSender) {
  2166. this._dtmfSender.ontonechange = this._onToneChange.bind(this);
  2167. }
  2168. }
  2169. if (this._dtmfSender) {
  2170. if (this._dtmfSender.toneBuffer) {
  2171. this._dtmfTonesQueue.push({
  2172. tones,
  2173. duration,
  2174. interToneGap
  2175. });
  2176. return;
  2177. }
  2178. this._dtmfSender.insertDTMF(tones, duration, interToneGap);
  2179. } else {
  2180. logger.warn(`${this} sendTones - failed to select DTMFSender`);
  2181. }
  2182. };
  2183. /**
  2184. * Callback ivoked by {@code this._dtmfSender} when it has finished playing
  2185. * a single tone.
  2186. *
  2187. * @param {Object} event - The tonechange event which indicates what characters
  2188. * are left to be played for the current tone.
  2189. * @private
  2190. * @returns {void}
  2191. */
  2192. TraceablePeerConnection.prototype._onToneChange = function(event) {
  2193. // An empty event.tone indicates the current tones have finished playing.
  2194. // Automatically start playing any queued tones on finish.
  2195. if (this._dtmfSender && event.tone === '' && this._dtmfTonesQueue.length) {
  2196. const { tones, duration, interToneGap } = this._dtmfTonesQueue.shift();
  2197. this._dtmfSender.insertDTMF(tones, duration, interToneGap);
  2198. }
  2199. };
  2200. /**
  2201. * Makes the underlying TraceablePeerConnection generate new SSRC for
  2202. * the recvonly video stream.
  2203. */
  2204. TraceablePeerConnection.prototype.generateRecvonlySsrc = function() {
  2205. const newSSRC = SDPUtil.generateSsrc();
  2206. logger.info(`${this} generated new recvonly SSRC=${newSSRC}`);
  2207. this.sdpConsistency.setPrimarySsrc(newSSRC);
  2208. };
  2209. /**
  2210. * Makes the underlying TraceablePeerConnection forget the current primary video
  2211. * SSRC.
  2212. */
  2213. TraceablePeerConnection.prototype.clearRecvonlySsrc = function() {
  2214. logger.info(`${this} Clearing primary video SSRC!`);
  2215. this.sdpConsistency.clearVideoSsrcCache();
  2216. };
  2217. /**
  2218. * Closes underlying WebRTC PeerConnection instance and removes all remote
  2219. * tracks by emitting {@link RTCEvents.REMOTE_TRACK_REMOVED} for each one of
  2220. * them.
  2221. */
  2222. TraceablePeerConnection.prototype.close = function() {
  2223. this.trace('stop');
  2224. // Off SignalingEvents
  2225. this.signalingLayer.off(SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  2226. this.signalingLayer.off(SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  2227. this._usesUnifiedPlan && this.peerconnection.removeEventListener('track', this.onTrack);
  2228. for (const peerTracks of this.remoteTracks.values()) {
  2229. for (const remoteTrack of peerTracks.values()) {
  2230. this._removeRemoteTrack(remoteTrack);
  2231. }
  2232. }
  2233. this.remoteTracks.clear();
  2234. this._addedStreams = [];
  2235. this._dtmfSender = null;
  2236. this._dtmfTonesQueue = [];
  2237. if (!this.rtc._removePeerConnection(this)) {
  2238. logger.error(`${this} RTC._removePeerConnection returned false`);
  2239. }
  2240. if (this.statsinterval !== null) {
  2241. window.clearInterval(this.statsinterval);
  2242. this.statsinterval = null;
  2243. }
  2244. logger.info(`${this} Closing peerconnection`);
  2245. this.peerconnection.close();
  2246. };
  2247. TraceablePeerConnection.prototype.createAnswer = function(constraints) {
  2248. return this._createOfferOrAnswer(false /* answer */, constraints);
  2249. };
  2250. TraceablePeerConnection.prototype.createOffer = function(constraints) {
  2251. return this._createOfferOrAnswer(true /* offer */, constraints);
  2252. };
  2253. TraceablePeerConnection.prototype._createOfferOrAnswer = function(
  2254. isOffer,
  2255. constraints) {
  2256. const logName = isOffer ? 'Offer' : 'Answer';
  2257. this.trace(`create${logName}`, JSON.stringify(constraints, null, ' '));
  2258. const handleSuccess = (resultSdp, resolveFn, rejectFn) => {
  2259. try {
  2260. this.trace(
  2261. `create${logName}OnSuccess::preTransform`, dumpSDP(resultSdp));
  2262. if (!this._usesUnifiedPlan) {
  2263. // If there are no local video tracks, then a "recvonly"
  2264. // SSRC needs to be generated
  2265. if (!this.hasAnyTracksOfType(MediaType.VIDEO)
  2266. && !this.sdpConsistency.hasPrimarySsrcCached()) {
  2267. this.generateRecvonlySsrc();
  2268. }
  2269. // eslint-disable-next-line no-param-reassign
  2270. resultSdp = new RTCSessionDescription({
  2271. type: resultSdp.type,
  2272. sdp: this.sdpConsistency.makeVideoPrimarySsrcsConsistent(
  2273. resultSdp.sdp)
  2274. });
  2275. this.trace(
  2276. `create${logName}OnSuccess::postTransform `
  2277. + '(make primary audio/video ssrcs consistent)',
  2278. dumpSDP(resultSdp));
  2279. }
  2280. const localVideoTrack = this.getLocalVideoTrack();
  2281. // Configure simulcast for camera tracks and for desktop tracks that need simulcast.
  2282. if (this.isSimulcastOn() && browser.usesSdpMungingForSimulcast()
  2283. && (localVideoTrack?.getVideoType() === VideoType.CAMERA
  2284. || this._usesUnifiedPlan
  2285. || !this.isSharingLowFpsScreen())) {
  2286. // eslint-disable-next-line no-param-reassign
  2287. resultSdp = this.simulcast.mungeLocalDescription(resultSdp);
  2288. this.trace(
  2289. `create${logName}`
  2290. + 'OnSuccess::postTransform (simulcast)',
  2291. dumpSDP(resultSdp));
  2292. }
  2293. if (!this.options.disableRtx && browser.usesSdpMungingForSimulcast()) {
  2294. // eslint-disable-next-line no-param-reassign
  2295. resultSdp = new RTCSessionDescription({
  2296. type: resultSdp.type,
  2297. sdp: this.rtxModifier.modifyRtxSsrcs(resultSdp.sdp)
  2298. });
  2299. this.trace(
  2300. `create${logName}`
  2301. + 'OnSuccess::postTransform (rtx modifier)',
  2302. dumpSDP(resultSdp));
  2303. }
  2304. const ssrcMap = this._extractSSRCMap(resultSdp);
  2305. this._processLocalSSRCsMap(ssrcMap);
  2306. resolveFn(resultSdp);
  2307. } catch (e) {
  2308. this.trace(`create${logName}OnError`, e);
  2309. this.trace(`create${logName}OnError`, dumpSDP(resultSdp));
  2310. logger.error(`${this} create${logName}OnError`, e, dumpSDP(resultSdp));
  2311. rejectFn(e);
  2312. }
  2313. };
  2314. const handleFailure = (err, rejectFn) => {
  2315. this.trace(`create${logName}OnFailure`, err);
  2316. const eventType
  2317. = isOffer
  2318. ? RTCEvents.CREATE_OFFER_FAILED
  2319. : RTCEvents.CREATE_ANSWER_FAILED;
  2320. this.eventEmitter.emit(eventType, err, this);
  2321. rejectFn(err);
  2322. };
  2323. // Set the codec preference before creating an offer or answer so that the generated SDP will have
  2324. // the correct preference order.
  2325. if (this._usesTransceiverCodecPreferences) {
  2326. const transceiver = this.peerconnection.getTransceivers()
  2327. .find(t => t.receiver && t.receiver?.track?.kind === MediaType.VIDEO);
  2328. if (transceiver) {
  2329. let capabilities = RTCRtpReceiver.getCapabilities(MediaType.VIDEO)?.codecs;
  2330. const mimeType = this.codecPreference?.mimeType;
  2331. const enable = this.codecPreference?.enable;
  2332. if (capabilities && mimeType && enable) {
  2333. // Move the desired codec (all variations of it as well) to the beginning of the list.
  2334. /* eslint-disable-next-line arrow-body-style */
  2335. capabilities.sort(caps => {
  2336. return caps.mimeType.toLowerCase() === `${MediaType.VIDEO}/${mimeType}` ? -1 : 1;
  2337. });
  2338. } else if (capabilities && mimeType) {
  2339. capabilities = capabilities
  2340. .filter(caps => caps.mimeType.toLowerCase() !== `${MediaType.VIDEO}/${mimeType}`);
  2341. }
  2342. try {
  2343. transceiver.setCodecPreferences(capabilities);
  2344. } catch (err) {
  2345. logger.warn(`${this} Setting codec[preference=${mimeType},enable=${enable}] failed`, err);
  2346. }
  2347. }
  2348. }
  2349. return new Promise((resolve, reject) => {
  2350. let oaPromise;
  2351. if (isOffer) {
  2352. oaPromise = this.peerconnection.createOffer(constraints);
  2353. } else {
  2354. oaPromise = this.peerconnection.createAnswer(constraints);
  2355. }
  2356. oaPromise
  2357. .then(
  2358. sdp => handleSuccess(sdp, resolve, reject),
  2359. error => handleFailure(error, reject));
  2360. });
  2361. };
  2362. /**
  2363. * Extract primary SSRC from given {@link TrackSSRCInfo} object.
  2364. * @param {TrackSSRCInfo} ssrcObj
  2365. * @return {number|null} the primary SSRC or <tt>null</tt>
  2366. */
  2367. TraceablePeerConnection.prototype._extractPrimarySSRC = function(ssrcObj) {
  2368. if (ssrcObj && ssrcObj.groups && ssrcObj.groups.length) {
  2369. return ssrcObj.groups[0].ssrcs[0];
  2370. } else if (ssrcObj && ssrcObj.ssrcs && ssrcObj.ssrcs.length) {
  2371. return ssrcObj.ssrcs[0];
  2372. }
  2373. return null;
  2374. };
  2375. /**
  2376. * Goes over the SSRC map extracted from the latest local description and tries
  2377. * to match them with the local tracks (by MSID). Will update the values
  2378. * currently stored in the {@link TraceablePeerConnection.localSSRCs} map.
  2379. * @param {Map<string,TrackSSRCInfo>} ssrcMap
  2380. * @private
  2381. */
  2382. TraceablePeerConnection.prototype._processLocalSSRCsMap = function(ssrcMap) {
  2383. for (const track of this.localTracks.values()) {
  2384. const sourceIdentifier = this._usesUnifiedPlan ? track.getType() : track.storedMSID;
  2385. if (ssrcMap.has(sourceIdentifier)) {
  2386. const newSSRC = ssrcMap.get(sourceIdentifier);
  2387. if (!newSSRC) {
  2388. logger.error(`${this} No SSRC found for stream=${sourceIdentifier}`);
  2389. return;
  2390. }
  2391. const oldSSRC = this.localSSRCs.get(track.rtcId);
  2392. const newSSRCNum = this._extractPrimarySSRC(newSSRC);
  2393. const oldSSRCNum = this._extractPrimarySSRC(oldSSRC);
  2394. // eslint-disable-next-line no-negated-condition
  2395. if (newSSRCNum !== oldSSRCNum) {
  2396. oldSSRCNum && logger.error(`${this} Overwriting SSRC for track=${track}] with ssrc=${newSSRC}`);
  2397. this.localSSRCs.set(track.rtcId, newSSRC);
  2398. this.eventEmitter.emit(RTCEvents.LOCAL_TRACK_SSRC_UPDATED, track, newSSRCNum);
  2399. }
  2400. } else if (!track.isVideoTrack() && !track.isMuted()) {
  2401. // It is normal to find no SSRCs for a muted video track in
  2402. // the local SDP as the recv-only SSRC is no longer munged in.
  2403. // So log the warning only if it's not a muted video track.
  2404. logger.warn(`${this} No SSRCs found in the local SDP for track=${track}, stream=${sourceIdentifier}`);
  2405. }
  2406. }
  2407. };
  2408. TraceablePeerConnection.prototype.addIceCandidate = function(candidate) {
  2409. this.trace('addIceCandidate', JSON.stringify({
  2410. candidate: candidate.candidate,
  2411. sdpMid: candidate.sdpMid,
  2412. sdpMLineIndex: candidate.sdpMLineIndex,
  2413. usernameFragment: candidate.usernameFragment
  2414. }, null, ' '));
  2415. return this.peerconnection.addIceCandidate(candidate);
  2416. };
  2417. /**
  2418. * Returns the number of simulcast streams that are currently enabled on the peerconnection.
  2419. *
  2420. * @returns {number} The number of simulcast streams currently enabled or 1 when simulcast is disabled.
  2421. */
  2422. TraceablePeerConnection.prototype.getActiveSimulcastStreams = function() {
  2423. let activeStreams = 1;
  2424. if (this.isSimulcastOn() && this.encodingsEnabledState) {
  2425. activeStreams = this.encodingsEnabledState.filter(stream => Boolean(stream))?.length;
  2426. } else if (this.isSimulcastOn()) {
  2427. activeStreams = SIM_LAYER_RIDS.length;
  2428. }
  2429. return activeStreams;
  2430. };
  2431. /**
  2432. * Obtains call-related stats from the peer connection.
  2433. *
  2434. * @returns {Promise<Object>} Promise which resolves with data providing statistics about
  2435. * the peerconnection.
  2436. */
  2437. TraceablePeerConnection.prototype.getStats = function() {
  2438. return this.peerconnection.getStats();
  2439. };
  2440. /**
  2441. * Generates and stores new SSRC info object for given local track.
  2442. * The method should be called only for a video track being added to this TPC
  2443. * in the muted state (given that the current browser uses this strategy).
  2444. * @param {JitsiLocalTrack} track
  2445. * @return {TPCSSRCInfo}
  2446. */
  2447. TraceablePeerConnection.prototype.generateNewStreamSSRCInfo = function(track) {
  2448. const rtcId = track.rtcId;
  2449. let ssrcInfo = this._getSSRC(rtcId);
  2450. if (ssrcInfo) {
  2451. logger.error(`${this} Overwriting local SSRCs for track id=${rtcId}`);
  2452. }
  2453. // Configure simulcast for camera tracks and desktop tracks that need simulcast.
  2454. if (this.isSimulcastOn()
  2455. && (track.getVideoType() === VideoType.CAMERA || !this.isSharingLowFpsScreen())) {
  2456. ssrcInfo = {
  2457. ssrcs: [],
  2458. groups: []
  2459. };
  2460. for (let i = 0; i < SIM_LAYER_RIDS.length; i++) {
  2461. ssrcInfo.ssrcs.push(SDPUtil.generateSsrc());
  2462. }
  2463. ssrcInfo.groups.push({
  2464. ssrcs: ssrcInfo.ssrcs.slice(),
  2465. semantics: 'SIM'
  2466. });
  2467. } else {
  2468. ssrcInfo = {
  2469. ssrcs: [ SDPUtil.generateSsrc() ],
  2470. groups: []
  2471. };
  2472. }
  2473. if (!this.options.disableRtx) {
  2474. // Specifically use a for loop here because we'll
  2475. // be adding to the list we're iterating over, so we
  2476. // only want to iterate through the items originally
  2477. // on the list
  2478. const currNumSsrcs = ssrcInfo.ssrcs.length;
  2479. for (let i = 0; i < currNumSsrcs; ++i) {
  2480. const primarySsrc = ssrcInfo.ssrcs[i];
  2481. const rtxSsrc = SDPUtil.generateSsrc();
  2482. ssrcInfo.ssrcs.push(rtxSsrc);
  2483. ssrcInfo.groups.push({
  2484. ssrcs: [ primarySsrc, rtxSsrc ],
  2485. semantics: 'FID'
  2486. });
  2487. }
  2488. }
  2489. ssrcInfo.msid = track.storedMSID;
  2490. this.localSSRCs.set(rtcId, ssrcInfo);
  2491. return ssrcInfo;
  2492. };
  2493. /**
  2494. * Returns if the peer connection uses Unified plan implementation.
  2495. *
  2496. * @returns {boolean} True if the pc uses Unified plan, false otherwise.
  2497. */
  2498. TraceablePeerConnection.prototype.usesUnifiedPlan = function() {
  2499. return this._usesUnifiedPlan;
  2500. };
  2501. /**
  2502. * Creates a text representation of this <tt>TraceablePeerConnection</tt>
  2503. * instance.
  2504. * @return {string}
  2505. */
  2506. TraceablePeerConnection.prototype.toString = function() {
  2507. return `TPC[id=${this.id},type=${this.isP2P ? 'P2P' : 'JVB'}]`;
  2508. };