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

TraceablePeerConnection.js 61KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878
  1. /* global __filename, RTCSessionDescription */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import transform from 'sdp-transform';
  4. import * as GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  5. import JitsiRemoteTrack from './JitsiRemoteTrack';
  6. import * as MediaType from '../../service/RTC/MediaType';
  7. import LocalSdpMunger from './LocalSdpMunger';
  8. import RTC from './RTC';
  9. import RTCUtils from './RTCUtils';
  10. import RTCBrowserType from './RTCBrowserType';
  11. import RTCEvents from '../../service/RTC/RTCEvents';
  12. import RtxModifier from '../xmpp/RtxModifier';
  13. // FIXME SDP tools should end up in some kind of util module
  14. import SDP from '../xmpp/SDP';
  15. import SdpConsistency from '../xmpp/SdpConsistency';
  16. import { SdpTransformWrap } from '../xmpp/SdpTransformUtil';
  17. import SDPUtil from '../xmpp/SDPUtil';
  18. import * as SignalingEvents from '../../service/RTC/SignalingEvents';
  19. const logger = getLogger(__filename);
  20. const SIMULCAST_LAYERS = 3;
  21. /* eslint-disable max-params */
  22. /**
  23. * Creates new instance of 'TraceablePeerConnection'.
  24. *
  25. * @param {RTC} rtc the instance of <tt>RTC</tt> service
  26. * @param {number} id the peer connection id assigned by the parent RTC module.
  27. * @param {SignalingLayer} signalingLayer the signaling layer instance
  28. * @param {object} iceConfig WebRTC 'PeerConnection' ICE config
  29. * @param {object} constraints WebRTC 'PeerConnection' constraints
  30. * @param {boolean} isP2P indicates whether or not the new instance will be used
  31. * in a peer to peer connection
  32. * @param {object} options <tt>TracablePeerConnection</tt> config options.
  33. * @param {boolean} options.disableSimulcast if set to 'true' will disable
  34. * the simulcast
  35. * @param {boolean} options.disableRtx if set to 'true' will disable the RTX
  36. * @param {boolean} options.preferH264 if set to 'true' H264 will be preferred
  37. * over other video codecs.
  38. *
  39. * FIXME: initially the purpose of TraceablePeerConnection was to be able to
  40. * debug the peer connection. Since many other responsibilities have been added
  41. * it would make sense to extract a separate class from it and come up with
  42. * a more suitable name.
  43. *
  44. * @constructor
  45. */
  46. export default function TraceablePeerConnection(
  47. rtc,
  48. id,
  49. signalingLayer,
  50. iceConfig,
  51. constraints,
  52. isP2P,
  53. options) {
  54. /**
  55. * Indicates whether or not this peer connection instance is actively
  56. * sending/receiving media. When set to <tt>false</tt> the SDP media
  57. * direction will be adjusted to 'inactive' in order to suspend media
  58. * transmission.
  59. * @type {boolean}
  60. * @private
  61. */
  62. this.mediaTransferActive = true;
  63. /**
  64. * The parent instance of RTC service which created this
  65. * <tt>TracablePeerConnection</tt>.
  66. * @type {RTC}
  67. */
  68. this.rtc = rtc;
  69. /**
  70. * The peer connection identifier assigned by the RTC module.
  71. * @type {number}
  72. */
  73. this.id = id;
  74. /**
  75. * Indicates whether or not this instance is used in a peer to peer
  76. * connection.
  77. * @type {boolean}
  78. */
  79. this.isP2P = isP2P;
  80. // FIXME: We should support multiple streams per jid.
  81. /**
  82. * The map holds remote tracks associated with this peer connection.
  83. * It maps user's JID to media type and remote track
  84. * (one track per media type per user's JID).
  85. * @type {Map<string, Map<MediaType, JitsiRemoteTrack>>}
  86. */
  87. this.remoteTracks = new Map();
  88. /**
  89. * A map which stores local tracks mapped by {@link JitsiLocalTrack.rtcId}
  90. * @type {Map<number, JitsiLocalTrack>}
  91. */
  92. this.localTracks = new Map();
  93. /**
  94. * @typedef {Object} TPCGroupInfo
  95. * @property {string} semantics the SSRC groups semantics
  96. * @property {Array<number>} ssrcs group's SSRCs in order where the first
  97. * one is group's primary SSRC, the second one is secondary (RTX) and so
  98. * on...
  99. */
  100. /**
  101. * @typedef {Object} TPCSSRCInfo
  102. * @property {Array<number>} ssrcs an array which holds all track's SSRCs
  103. * @property {Array<TPCGroupInfo>} groups an array stores all track's SSRC
  104. * groups
  105. */
  106. /**
  107. * Holds the info about local track's SSRCs mapped per their
  108. * {@link JitsiLocalTrack.rtcId}
  109. * @type {Map<number, TPCSSRCInfo>}
  110. */
  111. this.localSSRCs = new Map();
  112. /**
  113. * The local ICE username fragment for this session.
  114. */
  115. this.localUfrag = null;
  116. /**
  117. * The remote ICE username fragment for this session.
  118. */
  119. this.remoteUfrag = null;
  120. /**
  121. * The signaling layer which operates this peer connection.
  122. * @type {SignalingLayer}
  123. */
  124. this.signalingLayer = signalingLayer;
  125. // SignalingLayer listeners
  126. this._peerVideoTypeChanged = this._peerVideoTypeChanged.bind(this);
  127. this.signalingLayer.on(
  128. SignalingEvents.PEER_VIDEO_TYPE_CHANGED,
  129. this._peerVideoTypeChanged);
  130. this._peerMutedChanged = this._peerMutedChanged.bind(this);
  131. this.signalingLayer.on(
  132. SignalingEvents.PEER_MUTED_CHANGED,
  133. this._peerMutedChanged);
  134. this.options = options;
  135. this.peerconnection
  136. = new RTCUtils.RTCPeerConnectionType(iceConfig, constraints);
  137. this.updateLog = [];
  138. this.stats = {};
  139. this.statsinterval = null;
  140. /**
  141. * @type {number}
  142. */
  143. this.maxstats = 0;
  144. const Interop = require('sdp-interop').Interop;
  145. this.interop = new Interop();
  146. const Simulcast = require('sdp-simulcast');
  147. this.simulcast = new Simulcast({ numOfLayers: SIMULCAST_LAYERS,
  148. explodeRemoteSimulcast: false });
  149. this.sdpConsistency = new SdpConsistency(this.toString());
  150. /**
  151. * Munges local SDP provided to the Jingle Session in order to prevent from
  152. * sending SSRC updates on attach/detach and mute/unmute (for video).
  153. * @type {LocalSdpMunger}
  154. */
  155. this.localSdpMunger = new LocalSdpMunger(this);
  156. /**
  157. * TracablePeerConnection uses RTC's eventEmitter
  158. * @type {EventEmitter}
  159. */
  160. this.eventEmitter = rtc.eventEmitter;
  161. this.rtxModifier = new RtxModifier();
  162. // override as desired
  163. this.trace = (what, info) => {
  164. /* logger.warn('WTRACE', what, info);
  165. if (info && RTCBrowserType.isIExplorer()) {
  166. if (info.length > 1024) {
  167. logger.warn('WTRACE', what, info.substr(1024));
  168. }
  169. if (info.length > 2048) {
  170. logger.warn('WTRACE', what, info.substr(2048));
  171. }
  172. }*/
  173. this.updateLog.push({
  174. time: new Date(),
  175. type: what,
  176. value: info || ''
  177. });
  178. };
  179. this.onicecandidate = null;
  180. this.peerconnection.onicecandidate = event => {
  181. // FIXME: this causes stack overflow with Temasys Plugin
  182. if (!RTCBrowserType.isTemasysPluginUsed()) {
  183. this.trace(
  184. 'onicecandidate',
  185. JSON.stringify(event.candidate, null, ' '));
  186. }
  187. if (this.onicecandidate !== null) {
  188. this.onicecandidate(event);
  189. }
  190. };
  191. this.peerconnection.onaddstream
  192. = event => this._remoteStreamAdded(event.stream);
  193. this.peerconnection.onremovestream
  194. = event => this._remoteStreamRemoved(event.stream);
  195. this.onsignalingstatechange = null;
  196. this.peerconnection.onsignalingstatechange = event => {
  197. this.trace('onsignalingstatechange', this.signalingState);
  198. if (this.onsignalingstatechange !== null) {
  199. this.onsignalingstatechange(event);
  200. }
  201. };
  202. this.oniceconnectionstatechange = null;
  203. this.peerconnection.oniceconnectionstatechange = event => {
  204. this.trace('oniceconnectionstatechange', this.iceConnectionState);
  205. if (this.oniceconnectionstatechange !== null) {
  206. this.oniceconnectionstatechange(event);
  207. }
  208. };
  209. this.onnegotiationneeded = null;
  210. this.peerconnection.onnegotiationneeded = event => {
  211. this.trace('onnegotiationneeded');
  212. if (this.onnegotiationneeded !== null) {
  213. this.onnegotiationneeded(event);
  214. }
  215. };
  216. this.ondatachannel = null;
  217. this.peerconnection.ondatachannel = event => {
  218. this.trace('ondatachannel', event);
  219. if (this.ondatachannel !== null) {
  220. this.ondatachannel(event);
  221. }
  222. };
  223. // XXX: do all non-firefox browsers which we support also support this?
  224. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  225. this.statsinterval = window.setInterval(() => {
  226. this.peerconnection.getStats(stats => {
  227. const results = stats.result();
  228. const now = new Date();
  229. for (let i = 0; i < results.length; ++i) {
  230. results[i].names().forEach(name => {
  231. // eslint-disable-next-line no-shadow
  232. const id = `${results[i].id}-${name}`;
  233. let s = this.stats[id];
  234. if (!s) {
  235. this.stats[id] = s = {
  236. startTime: now,
  237. endTime: now,
  238. values: [],
  239. times: []
  240. };
  241. }
  242. s.values.push(results[i].stat(name));
  243. s.times.push(now.getTime());
  244. if (s.values.length > this.maxstats) {
  245. s.values.shift();
  246. s.times.shift();
  247. }
  248. s.endTime = now;
  249. });
  250. }
  251. });
  252. }, 1000);
  253. }
  254. logger.info(`Create new ${this}`);
  255. }
  256. /* eslint-enable max-params */
  257. /**
  258. * Returns a string representation of a SessionDescription object.
  259. */
  260. const dumpSDP = function(description) {
  261. if (typeof description === 'undefined' || description === null) {
  262. return '';
  263. }
  264. return `type: ${description.type}\r\n${description.sdp}`;
  265. };
  266. /**
  267. * Forwards the {@link peerconnection.iceConnectionState} state except that it
  268. * will convert "completed" into "connected" where both mean that the ICE has
  269. * succeeded and is up and running. We never see "completed" state for
  270. * the JVB connection, but it started appearing for the P2P one. This method
  271. * allows to adapt old logic to this new situation.
  272. * @return {string}
  273. */
  274. TraceablePeerConnection.prototype.getConnectionState = function() {
  275. const state = this.peerconnection.iceConnectionState;
  276. if (state === 'completed') {
  277. return 'connected';
  278. }
  279. return state;
  280. };
  281. /**
  282. * Obtains the media direction for given {@link MediaType}. The method takes
  283. * into account whether or not there are any local tracks for media and
  284. * the {@link mediaTransferActive} flag.
  285. * @param {MediaType} mediaType
  286. * @return {string} one of the SDP direction constants ('sendrecv, 'recvonly'
  287. * etc.) which should be used when setting local description on the peer
  288. * connection.
  289. * @private
  290. */
  291. TraceablePeerConnection.prototype._getDesiredMediaDirection
  292. = function(mediaType) {
  293. if (this.mediaTransferActive) {
  294. return this.hasAnyTracksOfType(mediaType) ? 'sendrecv' : 'recvonly';
  295. }
  296. return 'inactive';
  297. };
  298. /**
  299. * Tells whether or not this TPC instance is using Simulcast.
  300. * @return {boolean} <tt>true</tt> if simulcast is enabled and active or
  301. * <tt>false</tt> if it's turned off.
  302. */
  303. TraceablePeerConnection.prototype.isSimulcastOn = function() {
  304. return !this.options.disableSimulcast
  305. && RTCBrowserType.supportsSimulcast()
  306. && !this.isP2P;
  307. };
  308. /**
  309. * Handles {@link SignalingEvents.PEER_VIDEO_TYPE_CHANGED}
  310. * @param {string} endpointId the video owner's ID (MUC nickname)
  311. * @param {VideoType} videoType the new value
  312. * @private
  313. */
  314. TraceablePeerConnection.prototype._peerVideoTypeChanged
  315. = function(endpointId, videoType) {
  316. // Check if endpointId has a value to avoid action on random track
  317. if (!endpointId) {
  318. logger.error(`No endpointID on peerVideoTypeChanged ${this}`);
  319. return;
  320. }
  321. const videoTrack = this.getRemoteTracks(endpointId, MediaType.VIDEO);
  322. if (videoTrack.length) {
  323. // NOTE 1 track per media type is assumed
  324. videoTrack[0]._setVideoType(videoType);
  325. }
  326. };
  327. /**
  328. * Handles remote track mute / unmute events.
  329. * @param {string} endpointId the track owner's identifier (MUC nickname)
  330. * @param {MediaType} mediaType "audio" or "video"
  331. * @param {boolean} isMuted the new mute state
  332. * @private
  333. */
  334. TraceablePeerConnection.prototype._peerMutedChanged
  335. = function(endpointId, mediaType, isMuted) {
  336. // Check if endpointId is a value to avoid doing action on all remote tracks
  337. if (!endpointId) {
  338. logger.error('On peerMuteChanged - no endpoint ID');
  339. return;
  340. }
  341. const track = this.getRemoteTracks(endpointId, mediaType);
  342. if (track.length) {
  343. // NOTE 1 track per media type is assumed
  344. track[0].setMute(isMuted);
  345. }
  346. };
  347. /**
  348. * Obtains local tracks for given {@link MediaType}. If the <tt>mediaType</tt>
  349. * argument is omitted the list of all local tracks will be returned.
  350. * @param {MediaType} [mediaType]
  351. * @return {Array<JitsiLocalTrack>}
  352. */
  353. TraceablePeerConnection.prototype.getLocalTracks = function(mediaType) {
  354. let tracks = Array.from(this.localTracks.values());
  355. if (mediaType !== undefined) {
  356. tracks = tracks.filter(track => track.getType() === mediaType);
  357. }
  358. return tracks;
  359. };
  360. /**
  361. * Checks whether or not this {@link TraceablePeerConnection} instance contains
  362. * any local tracks for given <tt>mediaType</tt>.
  363. * @param {MediaType} mediaType
  364. * @return {boolean}
  365. */
  366. TraceablePeerConnection.prototype.hasAnyTracksOfType = function(mediaType) {
  367. if (!mediaType) {
  368. throw new Error('"mediaType" is required');
  369. }
  370. return this.getLocalTracks(mediaType).length > 0;
  371. };
  372. /**
  373. * Obtains all remote tracks currently known to this PeerConnection instance.
  374. * @param {string} [endpointId] the track owner's identifier (MUC nickname)
  375. * @param {MediaType} [mediaType] the remote tracks will be filtered
  376. * by their media type if this argument is specified.
  377. * @return {Array<JitsiRemoteTrack>}
  378. */
  379. TraceablePeerConnection.prototype.getRemoteTracks
  380. = function(endpointId, mediaType) {
  381. const remoteTracks = [];
  382. const endpoints
  383. = endpointId ? [ endpointId ] : this.remoteTracks.keys();
  384. for (const endpoint of endpoints) {
  385. const endpointTrackMap = this.remoteTracks.get(endpoint);
  386. if (!endpointTrackMap) {
  387. // Otherwise an empty Map() would have to be allocated above
  388. // eslint-disable-next-line no-continue
  389. continue;
  390. }
  391. for (const trackMediaType of endpointTrackMap.keys()) {
  392. // per media type filtering
  393. if (!mediaType || mediaType === trackMediaType) {
  394. const mediaTrack = endpointTrackMap.get(trackMediaType);
  395. if (mediaTrack) {
  396. remoteTracks.push(mediaTrack);
  397. }
  398. }
  399. }
  400. }
  401. return remoteTracks;
  402. };
  403. /**
  404. * Called when new remote MediaStream is added to the PeerConnection.
  405. * @param {MediaStream} stream the WebRTC MediaStream for remote participant
  406. */
  407. TraceablePeerConnection.prototype._remoteStreamAdded = function(stream) {
  408. const streamId = RTC.getStreamID(stream);
  409. if (!RTC.isUserStreamById(streamId)) {
  410. logger.info(
  411. `${this} ignored remote 'stream added' event for non-user stream`
  412. + `id: ${streamId}`);
  413. return;
  414. }
  415. // Bind 'addtrack'/'removetrack' event handlers
  416. if (RTCBrowserType.isChrome() || RTCBrowserType.isNWJS()
  417. || RTCBrowserType.isElectron()) {
  418. stream.onaddtrack = event => {
  419. this._remoteTrackAdded(event.target, event.track);
  420. };
  421. stream.onremovetrack = event => {
  422. this._remoteTrackRemoved(event.target, event.track);
  423. };
  424. }
  425. // Call remoteTrackAdded for each track in the stream
  426. const streamAudioTracks = stream.getAudioTracks();
  427. for (const audioTrack of streamAudioTracks) {
  428. this._remoteTrackAdded(stream, audioTrack);
  429. }
  430. const streamVideoTracks = stream.getVideoTracks();
  431. for (const videoTrack of streamVideoTracks) {
  432. this._remoteTrackAdded(stream, videoTrack);
  433. }
  434. };
  435. /**
  436. * Called on "track added" and "stream added" PeerConnection events (because we
  437. * handle streams on per track basis). Finds the owner and the SSRC for
  438. * the track and passes that to ChatRoom for further processing.
  439. * @param {MediaStream} stream the WebRTC MediaStream instance which is
  440. * the parent of the track
  441. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack added for remote
  442. * participant
  443. */
  444. TraceablePeerConnection.prototype._remoteTrackAdded = function(stream, track) {
  445. const streamId = RTC.getStreamID(stream);
  446. const mediaType = track.kind;
  447. logger.info(`${this} remote track added:`, streamId, mediaType);
  448. // look up an associated JID for a stream id
  449. if (!mediaType) {
  450. GlobalOnErrorHandler.callErrorHandler(
  451. new Error(
  452. `MediaType undefined for remote track, stream id: ${streamId}`
  453. ));
  454. // Abort
  455. return;
  456. }
  457. const remoteSDP = new SDP(this.remoteDescription.sdp);
  458. const mediaLines
  459. = remoteSDP.media.filter(mls => mls.startsWith(`m=${mediaType}`));
  460. if (!mediaLines.length) {
  461. GlobalOnErrorHandler.callErrorHandler(
  462. new Error(
  463. `No media lines for type ${mediaType
  464. } found in remote SDP for remote track: ${streamId}`));
  465. // Abort
  466. return;
  467. }
  468. let ssrcLines = SDPUtil.findLines(mediaLines[0], 'a=ssrc:');
  469. ssrcLines = ssrcLines.filter(
  470. line => {
  471. const msid
  472. = RTCBrowserType.isTemasysPluginUsed() ? 'mslabel' : 'msid';
  473. return line.indexOf(`${msid}:${streamId}`) !== -1;
  474. });
  475. if (!ssrcLines.length) {
  476. GlobalOnErrorHandler.callErrorHandler(
  477. new Error(
  478. `No SSRC lines for streamId ${streamId
  479. } for remote track, media type: ${mediaType}`));
  480. // Abort
  481. return;
  482. }
  483. // FIXME the length of ssrcLines[0] not verified, but it will fail
  484. // with global error handler anyway
  485. const trackSsrc = ssrcLines[0].substring(7).split(' ')[0];
  486. const ownerEndpointId = this.signalingLayer.getSSRCOwner(trackSsrc);
  487. if (!ownerEndpointId) {
  488. GlobalOnErrorHandler.callErrorHandler(
  489. new Error(
  490. `No SSRC owner known for: ${trackSsrc
  491. } for remote track, msid: ${streamId
  492. } media type: ${mediaType}`));
  493. // Abort
  494. return;
  495. }
  496. logger.log(`${this} associated ssrc`, ownerEndpointId, trackSsrc);
  497. const peerMediaInfo
  498. = this.signalingLayer.getPeerMediaInfo(ownerEndpointId, mediaType);
  499. if (!peerMediaInfo) {
  500. GlobalOnErrorHandler.callErrorHandler(
  501. new Error(
  502. `${this}: no peer media info available for ${
  503. ownerEndpointId}`));
  504. return;
  505. }
  506. const muted = peerMediaInfo.muted;
  507. const videoType = peerMediaInfo.videoType; // can be undefined
  508. this._createRemoteTrack(
  509. ownerEndpointId, stream, track, mediaType, videoType, trackSsrc, muted);
  510. };
  511. // FIXME cleanup params
  512. /* eslint-disable max-params */
  513. /**
  514. * Initializes a new JitsiRemoteTrack instance with the data provided by
  515. * the signaling layer and SDP.
  516. *
  517. * @param {string} ownerEndpointId the owner's endpoint ID (MUC nickname)
  518. * @param {MediaStream} stream the WebRTC stream instance
  519. * @param {MediaStreamTrack} track the WebRTC track instance
  520. * @param {MediaType} mediaType the track's type of the media
  521. * @param {VideoType} [videoType] the track's type of the video (if applicable)
  522. * @param {string} ssrc the track's main SSRC number
  523. * @param {boolean} muted the initial muted status
  524. */
  525. TraceablePeerConnection.prototype._createRemoteTrack
  526. = function(ownerEndpointId, stream, track, mediaType, videoType, ssrc, muted) {
  527. const remoteTrack
  528. = new JitsiRemoteTrack(
  529. this.rtc, this.rtc.conference,
  530. ownerEndpointId,
  531. stream, track, mediaType, videoType, ssrc, muted, this.isP2P);
  532. let remoteTracksMap = this.remoteTracks.get(ownerEndpointId);
  533. if (!remoteTracksMap) {
  534. remoteTracksMap = new Map();
  535. this.remoteTracks.set(ownerEndpointId, remoteTracksMap);
  536. }
  537. if (remoteTracksMap.has(mediaType)) {
  538. logger.error(
  539. `${this} overwriting remote track! ${remoteTrack}`,
  540. ownerEndpointId, mediaType);
  541. }
  542. remoteTracksMap.set(mediaType, remoteTrack);
  543. // FIXME not cool to use RTC's eventEmitter
  544. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, remoteTrack);
  545. };
  546. /* eslint-enable max-params */
  547. /**
  548. * Handles remote stream removal.
  549. * @param stream the WebRTC MediaStream object which is being removed from the
  550. * PeerConnection
  551. */
  552. TraceablePeerConnection.prototype._remoteStreamRemoved = function(stream) {
  553. if (!RTC.isUserStream(stream)) {
  554. const id = RTC.getStreamID(stream);
  555. logger.info(
  556. `Ignored remote 'stream removed' event for non-user stream ${id}`);
  557. return;
  558. }
  559. // Call remoteTrackRemoved for each track in the stream
  560. const streamVideoTracks = stream.getVideoTracks();
  561. for (const videoTrack of streamVideoTracks) {
  562. this._remoteTrackRemoved(stream, videoTrack);
  563. }
  564. const streamAudioTracks = stream.getAudioTracks();
  565. for (const audioTrack of streamAudioTracks) {
  566. this._remoteTrackRemoved(stream, audioTrack);
  567. }
  568. };
  569. /**
  570. * Handles remote media track removal.
  571. * @param {MediaStream} stream WebRTC MediaStream instance which is the parent
  572. * of the track.
  573. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack which has been
  574. * removed from the PeerConnection.
  575. */
  576. TraceablePeerConnection.prototype._remoteTrackRemoved
  577. = function(stream, track) {
  578. const streamId = RTC.getStreamID(stream);
  579. const trackId = track && track.id;
  580. logger.info(`${this} - remote track removed: ${streamId}, ${trackId}`);
  581. if (!streamId) {
  582. GlobalOnErrorHandler.callErrorHandler(
  583. new Error(`${this} remote track removal failed - no stream ID`));
  584. return;
  585. }
  586. if (!trackId) {
  587. GlobalOnErrorHandler.callErrorHandler(
  588. new Error(`${this} remote track removal failed - no track ID`));
  589. return;
  590. }
  591. if (!this._removeRemoteTrack(streamId, trackId)) {
  592. // NOTE this warning is always printed when user leaves the room,
  593. // because we remove remote tracks manually on MUC member left event,
  594. // before the SSRCs are removed by Jicofo. In most cases it is fine to
  595. // ignore this warning, but still it's better to keep it printed for
  596. // debugging purposes.
  597. //
  598. // We could change the behaviour to emit track removed only from here,
  599. // but the order of the events will change and consuming apps could
  600. // behave unexpectedly (the "user left" event would come before "track
  601. // removed" events).
  602. logger.warn(
  603. `${this} Removed track not found for msid: ${streamId},
  604. track id: ${trackId}`);
  605. }
  606. };
  607. /**
  608. * Finds remote track by it's stream and track ids.
  609. * @param {string} streamId the media stream id as defined by the WebRTC
  610. * @param {string} trackId the media track id as defined by the WebRTC
  611. * @return {JitsiRemoteTrack|undefined} the track's instance or
  612. * <tt>undefined</tt> if not found.
  613. * @private
  614. */
  615. TraceablePeerConnection.prototype._getRemoteTrackById
  616. = function(streamId, trackId) {
  617. // .find will break the loop once the first match is found
  618. for (const endpointTrackMap of this.remoteTracks.values()) {
  619. for (const mediaTrack of endpointTrackMap.values()) {
  620. // FIXME verify and try to use ===
  621. /* eslint-disable eqeqeq */
  622. if (mediaTrack.getStreamId() == streamId
  623. && mediaTrack.getTrackId() == trackId) {
  624. return mediaTrack;
  625. }
  626. /* eslint-enable eqeqeq */
  627. }
  628. }
  629. return undefined;
  630. };
  631. /**
  632. * Removes all JitsiRemoteTracks associated with given MUC nickname
  633. * (resource part of the JID). Returns array of removed tracks.
  634. *
  635. * @param {string} owner - The resource part of the MUC JID.
  636. * @returns {JitsiRemoteTrack[]}
  637. */
  638. TraceablePeerConnection.prototype.removeRemoteTracks = function(owner) {
  639. const removedTracks = [];
  640. const remoteTracksMap = this.remoteTracks.get(owner);
  641. if (remoteTracksMap) {
  642. const removedAudioTrack = remoteTracksMap.get(MediaType.AUDIO);
  643. const removedVideoTrack = remoteTracksMap.get(MediaType.VIDEO);
  644. removedAudioTrack && removedTracks.push(removedAudioTrack);
  645. removedVideoTrack && removedTracks.push(removedVideoTrack);
  646. this.remoteTracks.delete(owner);
  647. }
  648. logger.debug(
  649. `${this} removed remote tracks for ${owner
  650. } count: ${removedTracks.length}`);
  651. return removedTracks;
  652. };
  653. /**
  654. * Removes and disposes <tt>JitsiRemoteTrack</tt> identified by given stream and
  655. * track ids.
  656. *
  657. * @param {string} streamId the media stream id as defined by the WebRTC
  658. * @param {string} trackId the media track id as defined by the WebRTC
  659. * @returns {JitsiRemoteTrack|undefined} the track which has been removed or
  660. * <tt>undefined</tt> if no track matching given stream and track ids was
  661. * found.
  662. */
  663. TraceablePeerConnection.prototype._removeRemoteTrack
  664. = function(streamId, trackId) {
  665. const toBeRemoved = this._getRemoteTrackById(streamId, trackId);
  666. if (toBeRemoved) {
  667. toBeRemoved.dispose();
  668. const remoteTracksMap
  669. = this.remoteTracks.get(toBeRemoved.getParticipantId());
  670. // If _getRemoteTrackById succeeded it must be a valid value or
  671. // we're good to crash
  672. if (!remoteTracksMap.delete(toBeRemoved.getType())) {
  673. logger.error(
  674. `Failed to remove ${toBeRemoved} - type mapping messed up ?`);
  675. }
  676. // FIXME not cool to use RTC's eventEmitter
  677. this.rtc.eventEmitter.emit(
  678. RTCEvents.REMOTE_TRACK_REMOVED, toBeRemoved);
  679. }
  680. return toBeRemoved;
  681. };
  682. /**
  683. * @typedef {Object} SSRCGroupInfo
  684. * @property {Array<number>} ssrcs group's SSRCs
  685. * @property {string} semantics
  686. */
  687. /**
  688. * @typedef {Object} TrackSSRCInfo
  689. * @property {Array<number>} ssrcs track's SSRCs
  690. * @property {Array<SSRCGroupInfo>} groups track's SSRC groups
  691. */
  692. /**
  693. * Returns map with keys msid and <tt>TrackSSRCInfo</tt> values.
  694. * @param {Object} desc the WebRTC SDP instance.
  695. * @return {Map<string,TrackSSRCInfo>}
  696. */
  697. function extractSSRCMap(desc) {
  698. /**
  699. * Track SSRC infos mapped by stream ID (msid)
  700. * @type {Map<string,TrackSSRCInfo>}
  701. */
  702. const ssrcMap = new Map();
  703. /**
  704. * Groups mapped by primary SSRC number
  705. * @type {Map<number,Array<SSRCGroupInfo>>}
  706. */
  707. const groupsMap = new Map();
  708. if (typeof desc !== 'object' || desc === null
  709. || typeof desc.sdp !== 'string') {
  710. logger.warn('An empty description was passed as an argument.');
  711. return ssrcMap;
  712. }
  713. const session = transform.parse(desc.sdp);
  714. if (!Array.isArray(session.media)) {
  715. return ssrcMap;
  716. }
  717. for (const mLine of session.media) {
  718. if (!Array.isArray(mLine.ssrcs)) {
  719. continue; // eslint-disable-line no-continue
  720. }
  721. if (Array.isArray(mLine.ssrcGroups)) {
  722. for (const group of mLine.ssrcGroups) {
  723. if (typeof group.semantics !== 'undefined'
  724. && typeof group.ssrcs !== 'undefined') {
  725. // Parse SSRCs and store as numbers
  726. const groupSSRCs
  727. = group.ssrcs.split(' ')
  728. .map(ssrcStr => parseInt(ssrcStr, 10));
  729. const primarySSRC = groupSSRCs[0];
  730. // Note that group.semantics is already present
  731. group.ssrcs = groupSSRCs;
  732. // eslint-disable-next-line max-depth
  733. if (!groupsMap.has(primarySSRC)) {
  734. groupsMap.set(primarySSRC, []);
  735. }
  736. groupsMap.get(primarySSRC).push(group);
  737. }
  738. }
  739. }
  740. for (const ssrc of mLine.ssrcs) {
  741. if (ssrc.attribute !== 'msid') {
  742. continue; // eslint-disable-line no-continue
  743. }
  744. const msid = ssrc.value;
  745. let ssrcInfo = ssrcMap.get(msid);
  746. if (!ssrcInfo) {
  747. ssrcInfo = {
  748. ssrcs: [],
  749. groups: [],
  750. msid
  751. };
  752. ssrcMap.set(msid, ssrcInfo);
  753. }
  754. const ssrcNumber = ssrc.id;
  755. ssrcInfo.ssrcs.push(ssrcNumber);
  756. if (groupsMap.has(ssrcNumber)) {
  757. const ssrcGroups = groupsMap.get(ssrcNumber);
  758. for (const group of ssrcGroups) {
  759. ssrcInfo.groups.push(group);
  760. }
  761. }
  762. }
  763. }
  764. return ssrcMap;
  765. }
  766. /**
  767. * Takes a SessionDescription object and returns a "normalized" version.
  768. * Currently it only takes care of ordering the a=ssrc lines.
  769. */
  770. const normalizePlanB = function(desc) {
  771. if (typeof desc !== 'object' || desc === null
  772. || typeof desc.sdp !== 'string') {
  773. logger.warn('An empty description was passed as an argument.');
  774. return desc;
  775. }
  776. // eslint-disable-next-line no-shadow
  777. const transform = require('sdp-transform');
  778. const session = transform.parse(desc.sdp);
  779. if (typeof session !== 'undefined'
  780. && typeof session.media !== 'undefined'
  781. && Array.isArray(session.media)) {
  782. session.media.forEach(mLine => {
  783. // Chrome appears to be picky about the order in which a=ssrc lines
  784. // are listed in an m-line when rtx is enabled (and thus there are
  785. // a=ssrc-group lines with FID semantics). Specifically if we have
  786. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  787. // the "a=ssrc:S1" lines, SRD fails.
  788. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  789. // first.
  790. const firstSsrcs = [];
  791. const newSsrcLines = [];
  792. if (typeof mLine.ssrcGroups !== 'undefined'
  793. && Array.isArray(mLine.ssrcGroups)) {
  794. mLine.ssrcGroups.forEach(group => {
  795. if (typeof group.semantics !== 'undefined'
  796. && group.semantics === 'FID') {
  797. if (typeof group.ssrcs !== 'undefined') {
  798. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  799. }
  800. }
  801. });
  802. }
  803. if (Array.isArray(mLine.ssrcs)) {
  804. let i;
  805. for (i = 0; i < mLine.ssrcs.length; i++) {
  806. if (typeof mLine.ssrcs[i] === 'object'
  807. && typeof mLine.ssrcs[i].id !== 'undefined'
  808. && firstSsrcs.indexOf(mLine.ssrcs[i].id) >= 0) {
  809. newSsrcLines.push(mLine.ssrcs[i]);
  810. delete mLine.ssrcs[i];
  811. }
  812. }
  813. for (i = 0; i < mLine.ssrcs.length; i++) {
  814. if (typeof mLine.ssrcs[i] !== 'undefined') {
  815. newSsrcLines.push(mLine.ssrcs[i]);
  816. }
  817. }
  818. mLine.ssrcs = newSsrcLines;
  819. }
  820. });
  821. }
  822. const resStr = transform.write(session);
  823. return new RTCSessionDescription({
  824. type: desc.type,
  825. sdp: resStr
  826. });
  827. };
  828. /**
  829. *
  830. * @param {JitsiLocalTrack} localTrack
  831. */
  832. TraceablePeerConnection.prototype.getLocalSSRC = function(localTrack) {
  833. const ssrcInfo = this._getSSRC(localTrack.rtcId);
  834. return ssrcInfo && ssrcInfo.ssrcs[0];
  835. };
  836. /* eslint-disable-next-line vars-on-top */
  837. const getters = {
  838. signalingState() {
  839. return this.peerconnection.signalingState;
  840. },
  841. iceConnectionState() {
  842. return this.peerconnection.iceConnectionState;
  843. },
  844. localDescription() {
  845. let desc = this.peerconnection.localDescription;
  846. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  847. // if we're running on FF, transform to Plan B first.
  848. if (RTCBrowserType.usesUnifiedPlan()) {
  849. desc = this.interop.toPlanB(desc);
  850. this.trace('getLocalDescription::postTransform (Plan B)',
  851. dumpSDP(desc));
  852. }
  853. if (RTCBrowserType.doesVideoMuteByStreamRemove()) {
  854. this.localSdpMunger.maybeMungeLocalSdp(desc);
  855. logger.debug(
  856. 'getLocalDescription::postTransform (munge local SDP)', desc);
  857. }
  858. return desc || {};
  859. },
  860. remoteDescription() {
  861. let desc = this.peerconnection.remoteDescription;
  862. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  863. // if we're running on FF, transform to Plan B first.
  864. if (RTCBrowserType.usesUnifiedPlan()) {
  865. desc = this.interop.toPlanB(desc);
  866. this.trace(
  867. 'getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  868. }
  869. return desc || {};
  870. }
  871. };
  872. Object.keys(getters).forEach(prop => {
  873. Object.defineProperty(
  874. TraceablePeerConnection.prototype,
  875. prop, {
  876. get: getters[prop]
  877. }
  878. );
  879. });
  880. TraceablePeerConnection.prototype._getSSRC = function(rtcId) {
  881. return this.localSSRCs.get(rtcId);
  882. };
  883. /**
  884. * Add {@link JitsiLocalTrack} to this TPC.
  885. * @param {JitsiLocalTrack} track
  886. */
  887. TraceablePeerConnection.prototype.addTrack = function(track) {
  888. const rtcId = track.rtcId;
  889. logger.info(`add ${track} to: ${this}`);
  890. if (this.localTracks.has(rtcId)) {
  891. logger.error(`${track} is already in ${this}`);
  892. return;
  893. }
  894. this.localTracks.set(rtcId, track);
  895. const webrtcStream = track.getOriginalStream();
  896. if (webrtcStream) {
  897. this._addStream(webrtcStream);
  898. // It's not ok for a track to not have a WebRTC stream if:
  899. } else if (!RTCBrowserType.doesVideoMuteByStreamRemove()
  900. || track.isAudioTrack()
  901. || (track.isVideoTrack() && !track.isMuted())) {
  902. logger.error(`${this} no WebRTC stream for: ${track}`);
  903. }
  904. // Muted video tracks do not have WebRTC stream
  905. if (RTCBrowserType.doesVideoMuteByStreamRemove()
  906. && track.isVideoTrack() && track.isMuted()) {
  907. const ssrcInfo = this.generateNewStreamSSRCInfo(track);
  908. this.sdpConsistency.setPrimarySsrc(ssrcInfo.ssrcs[0]);
  909. const simGroup
  910. = ssrcInfo.groups.find(groupInfo => groupInfo.semantics === 'SIM');
  911. if (simGroup) {
  912. this.simulcast.setSsrcCache(simGroup.ssrcs);
  913. }
  914. const fidGroups
  915. = ssrcInfo.groups.filter(
  916. groupInfo => groupInfo.semantics === 'FID');
  917. if (fidGroups) {
  918. const rtxSsrcMapping = new Map();
  919. fidGroups.forEach(fidGroup => {
  920. const primarySsrc = fidGroup.ssrcs[0];
  921. const rtxSsrc = fidGroup.ssrcs[1];
  922. rtxSsrcMapping.set(primarySsrc, rtxSsrc);
  923. });
  924. this.rtxModifier.setSsrcCache(rtxSsrcMapping);
  925. }
  926. }
  927. };
  928. /**
  929. * Adds local track as part of the unmute operation.
  930. * @param {JitsiLocalTrack} track the track to be added as part of the unmute
  931. * operation
  932. * @return {boolean} <tt>true</tt> if the state of underlying PC has changed and
  933. * the renegotiation is required or <tt>false</tt> otherwise.
  934. */
  935. TraceablePeerConnection.prototype.addTrackUnmute = function(track) {
  936. if (!this._assertTrackBelongs('addTrackUnmute', track)) {
  937. // Abort
  938. return false;
  939. }
  940. logger.info(`Adding ${track} as unmute to ${this}`);
  941. const webRtcStream = track.getOriginalStream();
  942. if (!webRtcStream) {
  943. logger.error(
  944. `Unable to add ${track} as unmute to ${this} - no WebRTC stream`);
  945. return false;
  946. }
  947. this._addStream(webRtcStream);
  948. return true;
  949. };
  950. /**
  951. * Adds WebRTC media stream to the underlying PeerConnection
  952. * @param {MediaStream} mediaStream
  953. * @private
  954. */
  955. TraceablePeerConnection.prototype._addStream = function(mediaStream) {
  956. this.peerconnection.addStream(mediaStream);
  957. };
  958. /**
  959. * Removes WebRTC media stream from the underlying PeerConection
  960. * @param {MediaStream} mediaStream
  961. */
  962. TraceablePeerConnection.prototype._removeStream = function(mediaStream) {
  963. if (RTCBrowserType.isFirefox()) {
  964. this._handleFirefoxRemoveStream(mediaStream);
  965. } else {
  966. this.peerconnection.removeStream(mediaStream);
  967. }
  968. };
  969. /**
  970. * This method when called will check if given <tt>localTrack</tt> belongs to
  971. * this TPC (that it has been previously added using {@link addTrack}). If the
  972. * track does not belong an error message will be logged.
  973. * @param {string} methodName the method name that will be logged in an error
  974. * message
  975. * @param {JitsiLocalTrack} localTrack
  976. * @return {boolean} <tt>true</tt> if given local track belongs to this TPC or
  977. * <tt>false</tt> otherwise.
  978. * @private
  979. */
  980. TraceablePeerConnection.prototype._assertTrackBelongs
  981. = function(methodName, localTrack) {
  982. const doesBelong = this.localTracks.has(localTrack.rtcId);
  983. if (!doesBelong) {
  984. logger.error(
  985. `${methodName}: ${localTrack} does not belong to ${this}`);
  986. }
  987. return doesBelong;
  988. };
  989. /**
  990. * Remove local track from this TPC.
  991. * @param {JitsiLocalTrack} localTrack the track to be removed from this TPC.
  992. *
  993. * FIXME It should probably remove a boolean just like {@link removeTrackMute}
  994. * The same applies to addTrack.
  995. */
  996. TraceablePeerConnection.prototype.removeTrack = function(localTrack) {
  997. const webRtcStream = localTrack.getOriginalStream();
  998. this.trace(
  999. 'removeStream',
  1000. localTrack.rtcId, webRtcStream ? webRtcStream.id : undefined);
  1001. if (!this._assertTrackBelongs('removeStream', localTrack)) {
  1002. // Abort - nothing to be done here
  1003. return;
  1004. }
  1005. this.localTracks.delete(localTrack.rtcId);
  1006. this.localSSRCs.delete(localTrack.rtcId);
  1007. if (webRtcStream) {
  1008. if (RTCBrowserType.isFirefox()) {
  1009. this._handleFirefoxRemoveStream(webRtcStream);
  1010. } else {
  1011. this.peerconnection.removeStream(webRtcStream);
  1012. }
  1013. }
  1014. };
  1015. /**
  1016. * Removes local track as part of the mute operation.
  1017. * @param {JitsiLocalTrack} localTrack the local track to be remove as part of
  1018. * the mute operation.
  1019. * @return {boolean} <tt>true</tt> if the underlying PeerConnection's state has
  1020. * changed and the renegotiation is required or <tt>false</tt> otherwise.
  1021. */
  1022. TraceablePeerConnection.prototype.removeTrackMute = function(localTrack) {
  1023. const webRtcStream = localTrack.getOriginalStream();
  1024. this.trace(
  1025. 'removeStreamMute',
  1026. localTrack.rtcId, webRtcStream ? webRtcStream.id : null);
  1027. if (!this._assertTrackBelongs('removeStreamMute', localTrack)) {
  1028. // Abort - nothing to be done here
  1029. return false;
  1030. }
  1031. if (webRtcStream) {
  1032. logger.info(
  1033. `Removing ${localTrack} as mute from ${this}`);
  1034. this._removeStream(webRtcStream);
  1035. return true;
  1036. }
  1037. logger.error(`removeStreamMute - no WebRTC stream for ${localTrack}`);
  1038. return false;
  1039. };
  1040. /**
  1041. * Remove stream handling for firefox
  1042. * @param stream: webrtc media stream
  1043. */
  1044. TraceablePeerConnection.prototype._handleFirefoxRemoveStream
  1045. = function(stream) {
  1046. if (!stream) {
  1047. // There is nothing to be changed
  1048. return;
  1049. }
  1050. let sender = null;
  1051. // On Firefox we don't replace MediaStreams as this messes up the
  1052. // m-lines (which can't be removed in Plan Unified) and brings a lot
  1053. // of complications. Instead, we use the RTPSender and remove just
  1054. // the track.
  1055. let track = null;
  1056. if (stream.getAudioTracks() && stream.getAudioTracks().length) {
  1057. track = stream.getAudioTracks()[0];
  1058. } else if (stream.getVideoTracks() && stream.getVideoTracks().length) {
  1059. track = stream.getVideoTracks()[0];
  1060. }
  1061. if (!track) {
  1062. logger.error('Cannot remove tracks: no tracks.');
  1063. return;
  1064. }
  1065. // Find the right sender (for audio or video)
  1066. this.peerconnection.getSenders().some(s => {
  1067. if (s.track === track) {
  1068. sender = s;
  1069. return true;
  1070. }
  1071. return false;
  1072. });
  1073. if (sender) {
  1074. this.peerconnection.removeTrack(sender);
  1075. } else {
  1076. logger.log('Cannot remove tracks: no RTPSender.');
  1077. }
  1078. };
  1079. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  1080. this.trace('createDataChannel', label, opts);
  1081. return this.peerconnection.createDataChannel(label, opts);
  1082. };
  1083. /**
  1084. * Ensures that the simulcast ssrc-group appears after any other ssrc-groups
  1085. * in the SDP so that simulcast is properly activated.
  1086. *
  1087. * @param {Object} localSdp the WebRTC session description instance for
  1088. * the local description.
  1089. * @private
  1090. */
  1091. TraceablePeerConnection.prototype._ensureSimulcastGroupIsLast
  1092. = function(localSdp) {
  1093. let sdpStr = localSdp.sdp;
  1094. const videoStartIndex = sdpStr.indexOf('m=video');
  1095. const simStartIndex = sdpStr.indexOf('a=ssrc-group:SIM', videoStartIndex);
  1096. let otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1097. if (simStartIndex === -1
  1098. || otherStartIndex === -1
  1099. || otherStartIndex === simStartIndex) {
  1100. return;
  1101. }
  1102. const simEndIndex = sdpStr.indexOf('\r\n', simStartIndex);
  1103. const simStr = sdpStr.substring(simStartIndex, simEndIndex + 2);
  1104. sdpStr = sdpStr.replace(simStr, '');
  1105. otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1106. const otherEndIndex = sdpStr.indexOf('\r\n', otherStartIndex);
  1107. const sdpHead = sdpStr.slice(0, otherEndIndex);
  1108. const simStrTrimmed = simStr.trim();
  1109. const sdpTail = sdpStr.slice(otherEndIndex);
  1110. sdpStr = `${sdpHead}\r\n${simStrTrimmed}${sdpTail}`;
  1111. localSdp.sdp = sdpStr;
  1112. };
  1113. /**
  1114. * Will adjust audio and video media direction in the given SDP object to
  1115. * reflect the current status of the {@link mediaTransferActive} flag.
  1116. * @param {Object} localDescription the WebRTC session description instance for
  1117. * the local description.
  1118. * @private
  1119. */
  1120. TraceablePeerConnection.prototype._adjustLocalMediaDirection
  1121. = function(localDescription) {
  1122. const transformer = new SdpTransformWrap(localDescription.sdp);
  1123. let modifiedDirection = false;
  1124. const audioMedia = transformer.selectMedia('audio');
  1125. if (audioMedia) {
  1126. const desiredAudioDirection
  1127. = this._getDesiredMediaDirection(MediaType.AUDIO);
  1128. if (audioMedia.direction !== desiredAudioDirection) {
  1129. audioMedia.direction = desiredAudioDirection;
  1130. logger.info(
  1131. `Adjusted local audio direction to ${desiredAudioDirection}`);
  1132. modifiedDirection = true;
  1133. }
  1134. } else {
  1135. logger.warn('No "audio" media found int the local description');
  1136. }
  1137. const videoMedia = transformer.selectMedia('video');
  1138. if (videoMedia) {
  1139. const desiredVideoDirection
  1140. = this._getDesiredMediaDirection(MediaType.VIDEO);
  1141. if (videoMedia.direction !== desiredVideoDirection) {
  1142. videoMedia.direction = desiredVideoDirection;
  1143. logger.info(
  1144. `Adjusted local video direction to ${desiredVideoDirection}`);
  1145. modifiedDirection = true;
  1146. }
  1147. } else {
  1148. logger.warn('No "video" media found in the local description');
  1149. }
  1150. if (modifiedDirection) {
  1151. localDescription.sdp = transformer.toRawSDP();
  1152. }
  1153. };
  1154. TraceablePeerConnection.prototype.setLocalDescription
  1155. = function(description, successCallback, failureCallback) {
  1156. let localSdp = description;
  1157. this.trace('setLocalDescription::preTransform', dumpSDP(localSdp));
  1158. this._adjustLocalMediaDirection(localSdp);
  1159. this._ensureSimulcastGroupIsLast(localSdp);
  1160. // if we're using unified plan, transform to it first.
  1161. if (RTCBrowserType.usesUnifiedPlan()) {
  1162. localSdp = this.interop.toUnifiedPlan(localSdp);
  1163. this.trace(
  1164. 'setLocalDescription::postTransform (Unified Plan)',
  1165. dumpSDP(localSdp));
  1166. }
  1167. this.peerconnection.setLocalDescription(localSdp,
  1168. () => {
  1169. this.trace('setLocalDescriptionOnSuccess');
  1170. const localUfrag = SDPUtil.getUfrag(localSdp.sdp);
  1171. if (localUfrag !== this.localUfrag) {
  1172. this.localUfrag = localUfrag;
  1173. this.rtc.eventEmitter.emit(
  1174. RTCEvents.LOCAL_UFRAG_CHANGED, this, localUfrag);
  1175. }
  1176. successCallback();
  1177. },
  1178. err => {
  1179. this.trace('setLocalDescriptionOnFailure', err);
  1180. this.eventEmitter.emit(
  1181. RTCEvents.SET_LOCAL_DESCRIPTION_FAILED,
  1182. err, this);
  1183. failureCallback(err);
  1184. }
  1185. );
  1186. };
  1187. /**
  1188. * Enables/disables media transmission on this peer connection. When disabled
  1189. * the SDP media direction in the local SDP will be adjusted to 'inactive' which
  1190. * means that no data will be received or sent, but the connection should be
  1191. * kept alive.
  1192. * @param {boolean} active <tt>true</tt> to enable the media transmission or
  1193. * <tt>false</tt> to disable.
  1194. * @public
  1195. */
  1196. TraceablePeerConnection.prototype.setMediaTransferActive = function(active) {
  1197. this.mediaTransferActive = active;
  1198. };
  1199. TraceablePeerConnection.prototype.setRemoteDescription
  1200. = function(description, successCallback, failureCallback) {
  1201. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  1202. // TODO the focus should squeze or explode the remote simulcast
  1203. // eslint-disable-next-line no-param-reassign
  1204. description = this.simulcast.mungeRemoteDescription(description);
  1205. this.trace(
  1206. 'setRemoteDescription::postTransform (simulcast)',
  1207. dumpSDP(description));
  1208. if (this.options.preferH264) {
  1209. const parsedSdp = transform.parse(description.sdp);
  1210. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  1211. SDPUtil.preferVideoCodec(videoMLine, 'h264');
  1212. description.sdp = transform.write(parsedSdp);
  1213. }
  1214. // If the browser uses unified plan, transform to it first
  1215. if (RTCBrowserType.usesUnifiedPlan()) {
  1216. description.sdp = this.rtxModifier.stripRtx(description.sdp);
  1217. this.trace(
  1218. 'setRemoteDescription::postTransform (stripRtx)',
  1219. dumpSDP(description));
  1220. // eslint-disable-next-line no-param-reassign
  1221. description = this.interop.toUnifiedPlan(description);
  1222. this.trace(
  1223. 'setRemoteDescription::postTransform (Plan A)',
  1224. dumpSDP(description));
  1225. } else {
  1226. // Plan B
  1227. // eslint-disable-next-line no-param-reassign
  1228. description = normalizePlanB(description);
  1229. }
  1230. this.peerconnection.setRemoteDescription(
  1231. description,
  1232. () => {
  1233. this.trace('setRemoteDescriptionOnSuccess');
  1234. const remoteUfrag = SDPUtil.getUfrag(description.sdp);
  1235. if (remoteUfrag !== this.remoteUfrag) {
  1236. this.remoteUfrag = remoteUfrag;
  1237. this.rtc.eventEmitter.emit(
  1238. RTCEvents.REMOTE_UFRAG_CHANGED, this, remoteUfrag);
  1239. }
  1240. successCallback();
  1241. },
  1242. err => {
  1243. this.trace('setRemoteDescriptionOnFailure', err);
  1244. this.eventEmitter.emit(
  1245. RTCEvents.SET_REMOTE_DESCRIPTION_FAILED,
  1246. err,
  1247. this);
  1248. failureCallback(err);
  1249. });
  1250. };
  1251. /**
  1252. * Makes the underlying TraceablePeerConnection generate new SSRC for
  1253. * the recvonly video stream.
  1254. */
  1255. TraceablePeerConnection.prototype.generateRecvonlySsrc = function() {
  1256. const newSSRC = SDPUtil.generateSsrc();
  1257. logger.info(`${this} generated new recvonly SSRC: ${newSSRC}`);
  1258. this.sdpConsistency.setPrimarySsrc(newSSRC);
  1259. };
  1260. /**
  1261. * Makes the underlying TraceablePeerConnection forget the current primary video
  1262. * SSRC.
  1263. */
  1264. TraceablePeerConnection.prototype.clearRecvonlySsrc = function() {
  1265. logger.info('Clearing primary video SSRC!');
  1266. this.sdpConsistency.clearVideoSsrcCache();
  1267. };
  1268. TraceablePeerConnection.prototype.close = function() {
  1269. this.trace('stop');
  1270. // Off SignalingEvents
  1271. this.signalingLayer.off(
  1272. SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  1273. this.signalingLayer.off(
  1274. SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  1275. if (!this.rtc._removePeerConnection(this)) {
  1276. logger.error('RTC._removePeerConnection returned false');
  1277. }
  1278. if (this.statsinterval !== null) {
  1279. window.clearInterval(this.statsinterval);
  1280. this.statsinterval = null;
  1281. }
  1282. this.peerconnection.close();
  1283. };
  1284. /**
  1285. * Modifies the values of the setup attributes (defined by
  1286. * {@link http://tools.ietf.org/html/rfc4145#section-4}) of a specific SDP
  1287. * answer in order to overcome a delay of 1 second in the connection
  1288. * establishment between Chrome and Videobridge.
  1289. *
  1290. * @param {SDP} offer - the SDP offer to which the specified SDP answer is
  1291. * being prepared to respond
  1292. * @param {SDP} answer - the SDP to modify
  1293. * @private
  1294. */
  1295. const _fixAnswerRFC4145Setup = function(offer, answer) {
  1296. if (!RTCBrowserType.isChrome()) {
  1297. // It looks like Firefox doesn't agree with the fix (at least in its
  1298. // current implementation) because it effectively remains active even
  1299. // after we tell it to become passive. Apart from Firefox which I tested
  1300. // after the fix was deployed, I tested Chrome only. In order to prevent
  1301. // issues with other browsers, limit the fix to Chrome for the time
  1302. // being.
  1303. return;
  1304. }
  1305. // XXX Videobridge is the (SDP) offerer and WebRTC (e.g. Chrome) is the
  1306. // answerer (as orchestrated by Jicofo). In accord with
  1307. // http://tools.ietf.org/html/rfc5245#section-5.2 and because both peers
  1308. // are ICE FULL agents, Videobridge will take on the controlling role and
  1309. // WebRTC will take on the controlled role. In accord with
  1310. // https://tools.ietf.org/html/rfc5763#section-5, Videobridge will use the
  1311. // setup attribute value of setup:actpass and WebRTC will be allowed to
  1312. // choose either the setup attribute value of setup:active or
  1313. // setup:passive. Chrome will by default choose setup:active because it is
  1314. // RECOMMENDED by the respective RFC since setup:passive adds additional
  1315. // latency. The case of setup:active allows WebRTC to send a DTLS
  1316. // ClientHello as soon as an ICE connectivity check of its succeeds.
  1317. // Unfortunately, Videobridge will be unable to respond immediately because
  1318. // may not have WebRTC's answer or may have not completed the ICE
  1319. // connectivity establishment. Even more unfortunate is that in the
  1320. // described scenario Chrome's DTLS implementation will insist on
  1321. // retransmitting its ClientHello after a second (the time is in accord
  1322. // with the respective RFC) and will thus cause the whole connection
  1323. // establishment to exceed at least 1 second. To work around Chrome's
  1324. // idiosyncracy, don't allow it to send a ClientHello i.e. change its
  1325. // default choice of setup:active to setup:passive.
  1326. if (offer && answer
  1327. && offer.media && answer.media
  1328. && offer.media.length === answer.media.length) {
  1329. answer.media.forEach((a, i) => {
  1330. if (SDPUtil.findLine(
  1331. offer.media[i],
  1332. 'a=setup:actpass',
  1333. offer.session)) {
  1334. answer.media[i]
  1335. = a.replace(/a=setup:active/g, 'a=setup:passive');
  1336. }
  1337. });
  1338. answer.raw = answer.session + answer.media.join('');
  1339. }
  1340. };
  1341. TraceablePeerConnection.prototype.createAnswer
  1342. = function(successCallback, failureCallback, constraints) {
  1343. this._createOfferOrAnswer(
  1344. false /* answer */, successCallback, failureCallback, constraints);
  1345. };
  1346. TraceablePeerConnection.prototype.createOffer
  1347. = function(successCallback, failureCallback, constraints) {
  1348. this._createOfferOrAnswer(
  1349. true /* offer */, successCallback, failureCallback, constraints);
  1350. };
  1351. /* eslint-disable max-params */
  1352. TraceablePeerConnection.prototype._createOfferOrAnswer
  1353. = function(isOffer, successCallback, failureCallback, constraints) {
  1354. const logName = isOffer ? 'Offer' : 'Answer';
  1355. this.trace(`create${logName}`, JSON.stringify(constraints, null, ' '));
  1356. const _successCallback = resultSdp => {
  1357. try {
  1358. this.trace(
  1359. `create${logName}OnSuccess::preTransform`, dumpSDP(resultSdp));
  1360. // if we're using unified plan, transform to Plan B.
  1361. if (RTCBrowserType.usesUnifiedPlan()) {
  1362. // eslint-disable-next-line no-param-reassign
  1363. resultSdp = this.interop.toPlanB(resultSdp);
  1364. this.trace(
  1365. `create${logName}OnSuccess::postTransform (Plan B)`,
  1366. dumpSDP(resultSdp));
  1367. }
  1368. /**
  1369. * We don't keep ssrcs consitent for Firefox because rewriting
  1370. * the ssrcs between createAnswer and setLocalDescription breaks
  1371. * the caching in sdp-interop (sdp-interop must know about all
  1372. * ssrcs, and it updates its cache in toPlanB so if we rewrite them
  1373. * after that, when we try and go back to unified plan it will
  1374. * complain about unmapped ssrcs)
  1375. */
  1376. if (!RTCBrowserType.isFirefox()) {
  1377. // If there are no local video tracks, then a "recvonly"
  1378. // SSRC needs to be generated
  1379. if (!this.hasAnyTracksOfType(MediaType.VIDEO)
  1380. && !this.sdpConsistency.hasPrimarySsrcCached()) {
  1381. this.generateRecvonlySsrc();
  1382. }
  1383. resultSdp.sdp
  1384. = this.sdpConsistency.makeVideoPrimarySsrcsConsistent(
  1385. resultSdp.sdp);
  1386. this.trace(
  1387. `create${logName}OnSuccess::postTransform `
  1388. + '(make primary audio/video ssrcs consistent)',
  1389. dumpSDP(resultSdp));
  1390. }
  1391. // Add simulcast streams if simulcast is enabled
  1392. if (this.isSimulcastOn()) {
  1393. // eslint-disable-next-line no-param-reassign
  1394. resultSdp = this.simulcast.mungeLocalDescription(resultSdp);
  1395. this.trace(
  1396. `create${logName}`
  1397. + 'OnSuccess::postTransform (simulcast)',
  1398. dumpSDP(resultSdp));
  1399. }
  1400. if (!this.options.disableRtx && RTCBrowserType.supportsRtx()) {
  1401. resultSdp.sdp
  1402. = this.rtxModifier.modifyRtxSsrcs(resultSdp.sdp);
  1403. this.trace(
  1404. `create${logName}`
  1405. + 'OnSuccess::postTransform (rtx modifier)',
  1406. dumpSDP(resultSdp));
  1407. }
  1408. // Fix the setup attribute (see _fixAnswerRFC4145Setup for
  1409. // details)
  1410. if (!isOffer) {
  1411. const remoteDescription
  1412. = new SDP(this.remoteDescription.sdp);
  1413. const localDescription = new SDP(resultSdp.sdp);
  1414. _fixAnswerRFC4145Setup(remoteDescription, localDescription);
  1415. resultSdp.sdp = localDescription.raw;
  1416. }
  1417. const ssrcMap = extractSSRCMap(resultSdp);
  1418. logger.debug('Got local SSRCs MAP: ', ssrcMap);
  1419. this._processLocalSSRCsMap(ssrcMap);
  1420. successCallback(resultSdp);
  1421. } catch (e) {
  1422. this.trace(`create${logName}OnError`, e);
  1423. this.trace(`create${logName}OnError`, dumpSDP(resultSdp));
  1424. logger.error(`create${logName}OnError`, e, dumpSDP(resultSdp));
  1425. failureCallback(e);
  1426. }
  1427. };
  1428. const _errorCallback = err => {
  1429. this.trace(`create${logName}OnFailure`, err);
  1430. const eventType
  1431. = isOffer
  1432. ? RTCEvents.CREATE_OFFER_FAILED
  1433. : RTCEvents.CREATE_ANSWER_FAILED;
  1434. this.eventEmitter.emit(eventType, err, this);
  1435. failureCallback(err);
  1436. };
  1437. // NOTE Temasys plugin does not support "bind" on peerconnection methods
  1438. if (isOffer) {
  1439. this.peerconnection.createOffer(
  1440. _successCallback, _errorCallback, constraints);
  1441. } else {
  1442. this.peerconnection.createAnswer(
  1443. _successCallback, _errorCallback, constraints);
  1444. }
  1445. };
  1446. /* eslint-enable max-params */
  1447. /**
  1448. * Extract primary SSRC from given {@link TrackSSRCInfo} object.
  1449. * @param {TrackSSRCInfo} ssrcObj
  1450. * @return {number|null} the primary SSRC or <tt>null</tt>
  1451. */
  1452. function extractPrimarySSRC(ssrcObj) {
  1453. if (ssrcObj && ssrcObj.groups && ssrcObj.groups.length) {
  1454. return ssrcObj.groups[0].ssrcs[0];
  1455. } else if (ssrcObj && ssrcObj.ssrcs && ssrcObj.ssrcs.length) {
  1456. return ssrcObj.ssrcs[0];
  1457. }
  1458. return null;
  1459. }
  1460. /**
  1461. * Goes over the SSRC map extracted from the latest local description and tries
  1462. * to match them with the local tracks (by MSID). Will update the values
  1463. * currently stored in the {@link TraceablePeerConnection.localSSRCs} map.
  1464. * @param {Map<string,TrackSSRCInfo>} ssrcMap
  1465. * @private
  1466. */
  1467. TraceablePeerConnection.prototype._processLocalSSRCsMap = function(ssrcMap) {
  1468. for (const track of this.localTracks.values()) {
  1469. const trackMSID = track.getMSID();
  1470. if (ssrcMap.has(trackMSID)) {
  1471. const newSSRC = ssrcMap.get(trackMSID);
  1472. if (!newSSRC) {
  1473. logger.error(`No SSRC found for: ${trackMSID} in ${this}`);
  1474. return;
  1475. }
  1476. const oldSSRC = this.localSSRCs.get(track.rtcId);
  1477. const newSSRCNum = extractPrimarySSRC(newSSRC);
  1478. const oldSSRCNum = extractPrimarySSRC(oldSSRC);
  1479. // eslint-disable-next-line no-negated-condition
  1480. if (newSSRCNum !== oldSSRCNum) {
  1481. if (oldSSRCNum === null) {
  1482. logger.info(
  1483. `Storing new local SSRC for ${track} in ${this}`,
  1484. newSSRC);
  1485. } else {
  1486. logger.error(
  1487. `Overwriting SSRC for ${track} ${trackMSID} in ${this
  1488. } with: `, newSSRC);
  1489. }
  1490. this.localSSRCs.set(track.rtcId, newSSRC);
  1491. } else {
  1492. logger.debug(
  1493. `The local SSRC(${newSSRCNum}) for ${track} ${trackMSID}`
  1494. + `is still up to date in ${this}`);
  1495. }
  1496. } else {
  1497. logger.warn(`No local track matched with: ${trackMSID} in ${this}`);
  1498. }
  1499. }
  1500. };
  1501. TraceablePeerConnection.prototype.addIceCandidate
  1502. = function(candidate, successCallback, failureCallback) {
  1503. // var self = this;
  1504. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  1505. this.peerconnection.addIceCandidate(
  1506. candidate, successCallback, failureCallback);
  1507. /* maybe later
  1508. this.peerconnection.addIceCandidate(candidate,
  1509. function () {
  1510. self.trace('addIceCandidateOnSuccess');
  1511. successCallback();
  1512. },
  1513. function (err) {
  1514. self.trace('addIceCandidateOnFailure', err);
  1515. failureCallback(err);
  1516. }
  1517. );
  1518. */
  1519. };
  1520. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  1521. // TODO: Is this the correct way to handle Opera, Temasys?
  1522. if (RTCBrowserType.isFirefox()
  1523. || RTCBrowserType.isTemasysPluginUsed()
  1524. || RTCBrowserType.isReactNative()) {
  1525. this.peerconnection.getStats(
  1526. null,
  1527. callback,
  1528. errback || (() => {
  1529. // Making sure that getStats won't fail if error callback is
  1530. // not passed.
  1531. }));
  1532. } else {
  1533. this.peerconnection.getStats(callback);
  1534. }
  1535. };
  1536. /**
  1537. * Generates and stores new SSRC info object for given local track.
  1538. * The method should be called only for a video track being added to this TPC
  1539. * in the muted state (given that the current browser uses this strategy).
  1540. * @param {JitsiLocalTrack} track
  1541. * @return {TPCSSRCInfo}
  1542. */
  1543. TraceablePeerConnection.prototype.generateNewStreamSSRCInfo = function(track) {
  1544. const rtcId = track.rtcId;
  1545. let ssrcInfo = this._getSSRC(rtcId);
  1546. if (ssrcInfo) {
  1547. logger.error(`Will overwrite local SSRCs for track ID: ${rtcId}`);
  1548. }
  1549. if (this.isSimulcastOn()) {
  1550. ssrcInfo = {
  1551. ssrcs: [],
  1552. groups: []
  1553. };
  1554. for (let i = 0; i < SIMULCAST_LAYERS; i++) {
  1555. ssrcInfo.ssrcs.push(SDPUtil.generateSsrc());
  1556. }
  1557. ssrcInfo.groups.push({
  1558. ssrcs: ssrcInfo.ssrcs.slice(),
  1559. semantics: 'SIM'
  1560. });
  1561. } else {
  1562. ssrcInfo = {
  1563. ssrcs: [ SDPUtil.generateSsrc() ],
  1564. groups: []
  1565. };
  1566. }
  1567. if (!this.options.disableRtx && RTCBrowserType.supportsRtx()) {
  1568. // Specifically use a for loop here because we'll
  1569. // be adding to the list we're iterating over, so we
  1570. // only want to iterate through the items originally
  1571. // on the list
  1572. const currNumSsrcs = ssrcInfo.ssrcs.length;
  1573. for (let i = 0; i < currNumSsrcs; ++i) {
  1574. const primarySsrc = ssrcInfo.ssrcs[i];
  1575. const rtxSsrc = SDPUtil.generateSsrc();
  1576. ssrcInfo.ssrcs.push(rtxSsrc);
  1577. ssrcInfo.groups.push({
  1578. ssrcs: [ primarySsrc, rtxSsrc ],
  1579. semantics: 'FID'
  1580. });
  1581. }
  1582. }
  1583. ssrcInfo.msid = track.storedMSID;
  1584. this.localSSRCs.set(rtcId, ssrcInfo);
  1585. return ssrcInfo;
  1586. };
  1587. /**
  1588. * Creates a text representation of this <tt>TraceablePeerConnection</tt>
  1589. * instance.
  1590. * @return {string}
  1591. */
  1592. TraceablePeerConnection.prototype.toString = function() {
  1593. return `TPC[${this.id},p2p:${this.isP2P}]`;
  1594. };