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

TraceablePeerConnection.js 103KB

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