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

TraceablePeerConnection.js 106KB

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