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 62KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912
  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. * Tries to find {@link JitsiTrack} for given SSRC number. It will search both
  405. * local and remote tracks bound to this instance.
  406. * @param {number} ssrc
  407. * @return {JitsiTrack|null}
  408. */
  409. TraceablePeerConnection.prototype.getTrackBySSRC = function(ssrc) {
  410. if (typeof ssrc !== 'number') {
  411. throw new Error(`SSRC ${ssrc} is not a number`);
  412. }
  413. for (const localTrack of this.localTracks.values()) {
  414. if (this.getLocalSSRC(localTrack) === ssrc) {
  415. return localTrack;
  416. }
  417. }
  418. for (const remoteTrack of this.getRemoteTracks()) {
  419. if (remoteTrack.getSSRC() === ssrc) {
  420. return remoteTrack;
  421. }
  422. }
  423. return null;
  424. };
  425. /**
  426. * Called when new remote MediaStream is added to the PeerConnection.
  427. * @param {MediaStream} stream the WebRTC MediaStream for remote participant
  428. */
  429. TraceablePeerConnection.prototype._remoteStreamAdded = function(stream) {
  430. const streamId = RTC.getStreamID(stream);
  431. if (!RTC.isUserStreamById(streamId)) {
  432. logger.info(
  433. `${this} ignored remote 'stream added' event for non-user stream`
  434. + `id: ${streamId}`);
  435. return;
  436. }
  437. // Bind 'addtrack'/'removetrack' event handlers
  438. if (RTCBrowserType.isChrome() || RTCBrowserType.isNWJS()
  439. || RTCBrowserType.isElectron()) {
  440. stream.onaddtrack = event => {
  441. this._remoteTrackAdded(event.target, event.track);
  442. };
  443. stream.onremovetrack = event => {
  444. this._remoteTrackRemoved(event.target, event.track);
  445. };
  446. }
  447. // Call remoteTrackAdded for each track in the stream
  448. const streamAudioTracks = stream.getAudioTracks();
  449. for (const audioTrack of streamAudioTracks) {
  450. this._remoteTrackAdded(stream, audioTrack);
  451. }
  452. const streamVideoTracks = stream.getVideoTracks();
  453. for (const videoTrack of streamVideoTracks) {
  454. this._remoteTrackAdded(stream, videoTrack);
  455. }
  456. };
  457. /**
  458. * Called on "track added" and "stream added" PeerConnection events (because we
  459. * handle streams on per track basis). Finds the owner and the SSRC for
  460. * the track and passes that to ChatRoom for further processing.
  461. * @param {MediaStream} stream the WebRTC MediaStream instance which is
  462. * the parent of the track
  463. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack added for remote
  464. * participant
  465. */
  466. TraceablePeerConnection.prototype._remoteTrackAdded = function(stream, track) {
  467. const streamId = RTC.getStreamID(stream);
  468. const mediaType = track.kind;
  469. logger.info(`${this} remote track added:`, streamId, mediaType);
  470. // look up an associated JID for a stream id
  471. if (!mediaType) {
  472. GlobalOnErrorHandler.callErrorHandler(
  473. new Error(
  474. `MediaType undefined for remote track, stream id: ${streamId}`
  475. ));
  476. // Abort
  477. return;
  478. }
  479. const remoteSDP = new SDP(this.remoteDescription.sdp);
  480. const mediaLines
  481. = remoteSDP.media.filter(mls => mls.startsWith(`m=${mediaType}`));
  482. if (!mediaLines.length) {
  483. GlobalOnErrorHandler.callErrorHandler(
  484. new Error(
  485. `No media lines for type ${mediaType
  486. } found in remote SDP for remote track: ${streamId}`));
  487. // Abort
  488. return;
  489. }
  490. let ssrcLines = SDPUtil.findLines(mediaLines[0], 'a=ssrc:');
  491. ssrcLines = ssrcLines.filter(
  492. line => {
  493. const msid
  494. = RTCBrowserType.isTemasysPluginUsed() ? 'mslabel' : 'msid';
  495. return line.indexOf(`${msid}:${streamId}`) !== -1;
  496. });
  497. if (!ssrcLines.length) {
  498. GlobalOnErrorHandler.callErrorHandler(
  499. new Error(
  500. `No SSRC lines for streamId ${streamId
  501. } for remote track, media type: ${mediaType}`));
  502. // Abort
  503. return;
  504. }
  505. // FIXME the length of ssrcLines[0] not verified, but it will fail
  506. // with global error handler anyway
  507. const ssrcStr = ssrcLines[0].substring(7).split(' ')[0];
  508. const trackSsrc = Number(ssrcStr);
  509. const ownerEndpointId = this.signalingLayer.getSSRCOwner(trackSsrc);
  510. if (isNaN(trackSsrc) || trackSsrc < 0) {
  511. GlobalOnErrorHandler.callErrorHandler(
  512. new Error(
  513. `Invalid SSRC: ${ssrcStr
  514. } for remote track, msid: ${streamId
  515. } media type: ${mediaType}`));
  516. // Abort
  517. return;
  518. } else if (!ownerEndpointId) {
  519. GlobalOnErrorHandler.callErrorHandler(
  520. new Error(
  521. `No SSRC owner known for: ${trackSsrc
  522. } for remote track, msid: ${streamId
  523. } media type: ${mediaType}`));
  524. // Abort
  525. return;
  526. }
  527. logger.log(`${this} associated ssrc`, ownerEndpointId, trackSsrc);
  528. const peerMediaInfo
  529. = this.signalingLayer.getPeerMediaInfo(ownerEndpointId, mediaType);
  530. if (!peerMediaInfo) {
  531. GlobalOnErrorHandler.callErrorHandler(
  532. new Error(
  533. `${this}: no peer media info available for ${
  534. ownerEndpointId}`));
  535. return;
  536. }
  537. const muted = peerMediaInfo.muted;
  538. const videoType = peerMediaInfo.videoType; // can be undefined
  539. this._createRemoteTrack(
  540. ownerEndpointId, stream, track, mediaType, videoType, trackSsrc, muted);
  541. };
  542. // FIXME cleanup params
  543. /* eslint-disable max-params */
  544. /**
  545. * Initializes a new JitsiRemoteTrack instance with the data provided by
  546. * the signaling layer and SDP.
  547. *
  548. * @param {string} ownerEndpointId the owner's endpoint ID (MUC nickname)
  549. * @param {MediaStream} stream the WebRTC stream instance
  550. * @param {MediaStreamTrack} track the WebRTC track instance
  551. * @param {MediaType} mediaType the track's type of the media
  552. * @param {VideoType} [videoType] the track's type of the video (if applicable)
  553. * @param {number} ssrc the track's main SSRC number
  554. * @param {boolean} muted the initial muted status
  555. */
  556. TraceablePeerConnection.prototype._createRemoteTrack
  557. = function(ownerEndpointId, stream, track, mediaType, videoType, ssrc, muted) {
  558. const remoteTrack
  559. = new JitsiRemoteTrack(
  560. this.rtc, this.rtc.conference,
  561. ownerEndpointId,
  562. stream, track, mediaType, videoType, ssrc, muted, this.isP2P);
  563. let remoteTracksMap = this.remoteTracks.get(ownerEndpointId);
  564. if (!remoteTracksMap) {
  565. remoteTracksMap = new Map();
  566. this.remoteTracks.set(ownerEndpointId, remoteTracksMap);
  567. }
  568. if (remoteTracksMap.has(mediaType)) {
  569. logger.error(
  570. `${this} overwriting remote track! ${remoteTrack}`,
  571. ownerEndpointId, mediaType);
  572. }
  573. remoteTracksMap.set(mediaType, remoteTrack);
  574. // FIXME not cool to use RTC's eventEmitter
  575. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, remoteTrack);
  576. };
  577. /* eslint-enable max-params */
  578. /**
  579. * Handles remote stream removal.
  580. * @param stream the WebRTC MediaStream object which is being removed from the
  581. * PeerConnection
  582. */
  583. TraceablePeerConnection.prototype._remoteStreamRemoved = function(stream) {
  584. if (!RTC.isUserStream(stream)) {
  585. const id = RTC.getStreamID(stream);
  586. logger.info(
  587. `Ignored remote 'stream removed' event for non-user stream ${id}`);
  588. return;
  589. }
  590. // Call remoteTrackRemoved for each track in the stream
  591. const streamVideoTracks = stream.getVideoTracks();
  592. for (const videoTrack of streamVideoTracks) {
  593. this._remoteTrackRemoved(stream, videoTrack);
  594. }
  595. const streamAudioTracks = stream.getAudioTracks();
  596. for (const audioTrack of streamAudioTracks) {
  597. this._remoteTrackRemoved(stream, audioTrack);
  598. }
  599. };
  600. /**
  601. * Handles remote media track removal.
  602. * @param {MediaStream} stream WebRTC MediaStream instance which is the parent
  603. * of the track.
  604. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack which has been
  605. * removed from the PeerConnection.
  606. */
  607. TraceablePeerConnection.prototype._remoteTrackRemoved
  608. = function(stream, track) {
  609. const streamId = RTC.getStreamID(stream);
  610. const trackId = track && track.id;
  611. logger.info(`${this} - remote track removed: ${streamId}, ${trackId}`);
  612. if (!streamId) {
  613. GlobalOnErrorHandler.callErrorHandler(
  614. new Error(`${this} remote track removal failed - no stream ID`));
  615. return;
  616. }
  617. if (!trackId) {
  618. GlobalOnErrorHandler.callErrorHandler(
  619. new Error(`${this} remote track removal failed - no track ID`));
  620. return;
  621. }
  622. if (!this._removeRemoteTrack(streamId, trackId)) {
  623. // NOTE this warning is always printed when user leaves the room,
  624. // because we remove remote tracks manually on MUC member left event,
  625. // before the SSRCs are removed by Jicofo. In most cases it is fine to
  626. // ignore this warning, but still it's better to keep it printed for
  627. // debugging purposes.
  628. //
  629. // We could change the behaviour to emit track removed only from here,
  630. // but the order of the events will change and consuming apps could
  631. // behave unexpectedly (the "user left" event would come before "track
  632. // removed" events).
  633. logger.warn(
  634. `${this} Removed track not found for msid: ${streamId},
  635. track id: ${trackId}`);
  636. }
  637. };
  638. /**
  639. * Finds remote track by it's stream and track ids.
  640. * @param {string} streamId the media stream id as defined by the WebRTC
  641. * @param {string} trackId the media track id as defined by the WebRTC
  642. * @return {JitsiRemoteTrack|undefined} the track's instance or
  643. * <tt>undefined</tt> if not found.
  644. * @private
  645. */
  646. TraceablePeerConnection.prototype._getRemoteTrackById
  647. = function(streamId, trackId) {
  648. // .find will break the loop once the first match is found
  649. for (const endpointTrackMap of this.remoteTracks.values()) {
  650. for (const mediaTrack of endpointTrackMap.values()) {
  651. // FIXME verify and try to use ===
  652. /* eslint-disable eqeqeq */
  653. if (mediaTrack.getStreamId() == streamId
  654. && mediaTrack.getTrackId() == trackId) {
  655. return mediaTrack;
  656. }
  657. /* eslint-enable eqeqeq */
  658. }
  659. }
  660. return undefined;
  661. };
  662. /**
  663. * Removes all JitsiRemoteTracks associated with given MUC nickname
  664. * (resource part of the JID). Returns array of removed tracks.
  665. *
  666. * @param {string} owner - The resource part of the MUC JID.
  667. * @returns {JitsiRemoteTrack[]}
  668. */
  669. TraceablePeerConnection.prototype.removeRemoteTracks = function(owner) {
  670. const removedTracks = [];
  671. const remoteTracksMap = this.remoteTracks.get(owner);
  672. if (remoteTracksMap) {
  673. const removedAudioTrack = remoteTracksMap.get(MediaType.AUDIO);
  674. const removedVideoTrack = remoteTracksMap.get(MediaType.VIDEO);
  675. removedAudioTrack && removedTracks.push(removedAudioTrack);
  676. removedVideoTrack && removedTracks.push(removedVideoTrack);
  677. this.remoteTracks.delete(owner);
  678. }
  679. logger.debug(
  680. `${this} removed remote tracks for ${owner
  681. } count: ${removedTracks.length}`);
  682. return removedTracks;
  683. };
  684. /**
  685. * Removes and disposes <tt>JitsiRemoteTrack</tt> identified by given stream and
  686. * track ids.
  687. *
  688. * @param {string} streamId the media stream id as defined by the WebRTC
  689. * @param {string} trackId the media track id as defined by the WebRTC
  690. * @returns {JitsiRemoteTrack|undefined} the track which has been removed or
  691. * <tt>undefined</tt> if no track matching given stream and track ids was
  692. * found.
  693. */
  694. TraceablePeerConnection.prototype._removeRemoteTrack
  695. = function(streamId, trackId) {
  696. const toBeRemoved = this._getRemoteTrackById(streamId, trackId);
  697. if (toBeRemoved) {
  698. toBeRemoved.dispose();
  699. const remoteTracksMap
  700. = this.remoteTracks.get(toBeRemoved.getParticipantId());
  701. // If _getRemoteTrackById succeeded it must be a valid value or
  702. // we're good to crash
  703. if (!remoteTracksMap.delete(toBeRemoved.getType())) {
  704. logger.error(
  705. `Failed to remove ${toBeRemoved} - type mapping messed up ?`);
  706. }
  707. // FIXME not cool to use RTC's eventEmitter
  708. this.rtc.eventEmitter.emit(
  709. RTCEvents.REMOTE_TRACK_REMOVED, toBeRemoved);
  710. }
  711. return toBeRemoved;
  712. };
  713. /**
  714. * @typedef {Object} SSRCGroupInfo
  715. * @property {Array<number>} ssrcs group's SSRCs
  716. * @property {string} semantics
  717. */
  718. /**
  719. * @typedef {Object} TrackSSRCInfo
  720. * @property {Array<number>} ssrcs track's SSRCs
  721. * @property {Array<SSRCGroupInfo>} groups track's SSRC groups
  722. */
  723. /**
  724. * Returns map with keys msid and <tt>TrackSSRCInfo</tt> values.
  725. * @param {Object} desc the WebRTC SDP instance.
  726. * @return {Map<string,TrackSSRCInfo>}
  727. */
  728. function extractSSRCMap(desc) {
  729. /**
  730. * Track SSRC infos mapped by stream ID (msid)
  731. * @type {Map<string,TrackSSRCInfo>}
  732. */
  733. const ssrcMap = new Map();
  734. /**
  735. * Groups mapped by primary SSRC number
  736. * @type {Map<number,Array<SSRCGroupInfo>>}
  737. */
  738. const groupsMap = new Map();
  739. if (typeof desc !== 'object' || desc === null
  740. || typeof desc.sdp !== 'string') {
  741. logger.warn('An empty description was passed as an argument.');
  742. return ssrcMap;
  743. }
  744. const session = transform.parse(desc.sdp);
  745. if (!Array.isArray(session.media)) {
  746. return ssrcMap;
  747. }
  748. for (const mLine of session.media) {
  749. if (!Array.isArray(mLine.ssrcs)) {
  750. continue; // eslint-disable-line no-continue
  751. }
  752. if (Array.isArray(mLine.ssrcGroups)) {
  753. for (const group of mLine.ssrcGroups) {
  754. if (typeof group.semantics !== 'undefined'
  755. && typeof group.ssrcs !== 'undefined') {
  756. // Parse SSRCs and store as numbers
  757. const groupSSRCs
  758. = group.ssrcs.split(' ')
  759. .map(ssrcStr => parseInt(ssrcStr, 10));
  760. const primarySSRC = groupSSRCs[0];
  761. // Note that group.semantics is already present
  762. group.ssrcs = groupSSRCs;
  763. // eslint-disable-next-line max-depth
  764. if (!groupsMap.has(primarySSRC)) {
  765. groupsMap.set(primarySSRC, []);
  766. }
  767. groupsMap.get(primarySSRC).push(group);
  768. }
  769. }
  770. }
  771. for (const ssrc of mLine.ssrcs) {
  772. if (ssrc.attribute !== 'msid') {
  773. continue; // eslint-disable-line no-continue
  774. }
  775. const msid = ssrc.value;
  776. let ssrcInfo = ssrcMap.get(msid);
  777. if (!ssrcInfo) {
  778. ssrcInfo = {
  779. ssrcs: [],
  780. groups: [],
  781. msid
  782. };
  783. ssrcMap.set(msid, ssrcInfo);
  784. }
  785. const ssrcNumber = ssrc.id;
  786. ssrcInfo.ssrcs.push(ssrcNumber);
  787. if (groupsMap.has(ssrcNumber)) {
  788. const ssrcGroups = groupsMap.get(ssrcNumber);
  789. for (const group of ssrcGroups) {
  790. ssrcInfo.groups.push(group);
  791. }
  792. }
  793. }
  794. }
  795. return ssrcMap;
  796. }
  797. /**
  798. * Takes a SessionDescription object and returns a "normalized" version.
  799. * Currently it only takes care of ordering the a=ssrc lines.
  800. */
  801. const normalizePlanB = function(desc) {
  802. if (typeof desc !== 'object' || desc === null
  803. || typeof desc.sdp !== 'string') {
  804. logger.warn('An empty description was passed as an argument.');
  805. return desc;
  806. }
  807. // eslint-disable-next-line no-shadow
  808. const transform = require('sdp-transform');
  809. const session = transform.parse(desc.sdp);
  810. if (typeof session !== 'undefined'
  811. && typeof session.media !== 'undefined'
  812. && Array.isArray(session.media)) {
  813. session.media.forEach(mLine => {
  814. // Chrome appears to be picky about the order in which a=ssrc lines
  815. // are listed in an m-line when rtx is enabled (and thus there are
  816. // a=ssrc-group lines with FID semantics). Specifically if we have
  817. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  818. // the "a=ssrc:S1" lines, SRD fails.
  819. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  820. // first.
  821. const firstSsrcs = [];
  822. const newSsrcLines = [];
  823. if (typeof mLine.ssrcGroups !== 'undefined'
  824. && Array.isArray(mLine.ssrcGroups)) {
  825. mLine.ssrcGroups.forEach(group => {
  826. if (typeof group.semantics !== 'undefined'
  827. && group.semantics === 'FID') {
  828. if (typeof group.ssrcs !== 'undefined') {
  829. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  830. }
  831. }
  832. });
  833. }
  834. if (Array.isArray(mLine.ssrcs)) {
  835. let i;
  836. for (i = 0; i < mLine.ssrcs.length; i++) {
  837. if (typeof mLine.ssrcs[i] === 'object'
  838. && typeof mLine.ssrcs[i].id !== 'undefined'
  839. && firstSsrcs.indexOf(mLine.ssrcs[i].id) >= 0) {
  840. newSsrcLines.push(mLine.ssrcs[i]);
  841. delete mLine.ssrcs[i];
  842. }
  843. }
  844. for (i = 0; i < mLine.ssrcs.length; i++) {
  845. if (typeof mLine.ssrcs[i] !== 'undefined') {
  846. newSsrcLines.push(mLine.ssrcs[i]);
  847. }
  848. }
  849. mLine.ssrcs = newSsrcLines;
  850. }
  851. });
  852. }
  853. const resStr = transform.write(session);
  854. return new RTCSessionDescription({
  855. type: desc.type,
  856. sdp: resStr
  857. });
  858. };
  859. /**
  860. *
  861. * @param {JitsiLocalTrack} localTrack
  862. */
  863. TraceablePeerConnection.prototype.getLocalSSRC = function(localTrack) {
  864. const ssrcInfo = this._getSSRC(localTrack.rtcId);
  865. return ssrcInfo && ssrcInfo.ssrcs[0];
  866. };
  867. /* eslint-disable-next-line vars-on-top */
  868. const getters = {
  869. signalingState() {
  870. return this.peerconnection.signalingState;
  871. },
  872. iceConnectionState() {
  873. return this.peerconnection.iceConnectionState;
  874. },
  875. localDescription() {
  876. let desc = this.peerconnection.localDescription;
  877. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  878. // if we're running on FF, transform to Plan B first.
  879. if (RTCBrowserType.usesUnifiedPlan()) {
  880. desc = this.interop.toPlanB(desc);
  881. this.trace('getLocalDescription::postTransform (Plan B)',
  882. dumpSDP(desc));
  883. }
  884. if (RTCBrowserType.doesVideoMuteByStreamRemove()) {
  885. this.localSdpMunger.maybeMungeLocalSdp(desc);
  886. logger.debug(
  887. 'getLocalDescription::postTransform (munge local SDP)', desc);
  888. }
  889. return desc || {};
  890. },
  891. remoteDescription() {
  892. let desc = this.peerconnection.remoteDescription;
  893. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  894. // if we're running on FF, transform to Plan B first.
  895. if (RTCBrowserType.usesUnifiedPlan()) {
  896. desc = this.interop.toPlanB(desc);
  897. this.trace(
  898. 'getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  899. }
  900. return desc || {};
  901. }
  902. };
  903. Object.keys(getters).forEach(prop => {
  904. Object.defineProperty(
  905. TraceablePeerConnection.prototype,
  906. prop, {
  907. get: getters[prop]
  908. }
  909. );
  910. });
  911. TraceablePeerConnection.prototype._getSSRC = function(rtcId) {
  912. return this.localSSRCs.get(rtcId);
  913. };
  914. /**
  915. * Add {@link JitsiLocalTrack} to this TPC.
  916. * @param {JitsiLocalTrack} track
  917. */
  918. TraceablePeerConnection.prototype.addTrack = function(track) {
  919. const rtcId = track.rtcId;
  920. logger.info(`add ${track} to: ${this}`);
  921. if (this.localTracks.has(rtcId)) {
  922. logger.error(`${track} is already in ${this}`);
  923. return;
  924. }
  925. this.localTracks.set(rtcId, track);
  926. const webrtcStream = track.getOriginalStream();
  927. if (webrtcStream) {
  928. this._addStream(webrtcStream);
  929. // It's not ok for a track to not have a WebRTC stream if:
  930. } else if (!RTCBrowserType.doesVideoMuteByStreamRemove()
  931. || track.isAudioTrack()
  932. || (track.isVideoTrack() && !track.isMuted())) {
  933. logger.error(`${this} no WebRTC stream for: ${track}`);
  934. }
  935. // Muted video tracks do not have WebRTC stream
  936. if (RTCBrowserType.doesVideoMuteByStreamRemove()
  937. && track.isVideoTrack() && track.isMuted()) {
  938. const ssrcInfo = this.generateNewStreamSSRCInfo(track);
  939. this.sdpConsistency.setPrimarySsrc(ssrcInfo.ssrcs[0]);
  940. const simGroup
  941. = ssrcInfo.groups.find(groupInfo => groupInfo.semantics === 'SIM');
  942. if (simGroup) {
  943. this.simulcast.setSsrcCache(simGroup.ssrcs);
  944. }
  945. const fidGroups
  946. = ssrcInfo.groups.filter(
  947. groupInfo => groupInfo.semantics === 'FID');
  948. if (fidGroups) {
  949. const rtxSsrcMapping = new Map();
  950. fidGroups.forEach(fidGroup => {
  951. const primarySsrc = fidGroup.ssrcs[0];
  952. const rtxSsrc = fidGroup.ssrcs[1];
  953. rtxSsrcMapping.set(primarySsrc, rtxSsrc);
  954. });
  955. this.rtxModifier.setSsrcCache(rtxSsrcMapping);
  956. }
  957. }
  958. };
  959. /**
  960. * Adds local track as part of the unmute operation.
  961. * @param {JitsiLocalTrack} track the track to be added as part of the unmute
  962. * operation
  963. * @return {boolean} <tt>true</tt> if the state of underlying PC has changed and
  964. * the renegotiation is required or <tt>false</tt> otherwise.
  965. */
  966. TraceablePeerConnection.prototype.addTrackUnmute = function(track) {
  967. if (!this._assertTrackBelongs('addTrackUnmute', track)) {
  968. // Abort
  969. return false;
  970. }
  971. logger.info(`Adding ${track} as unmute to ${this}`);
  972. const webRtcStream = track.getOriginalStream();
  973. if (!webRtcStream) {
  974. logger.error(
  975. `Unable to add ${track} as unmute to ${this} - no WebRTC stream`);
  976. return false;
  977. }
  978. this._addStream(webRtcStream);
  979. return true;
  980. };
  981. /**
  982. * Adds WebRTC media stream to the underlying PeerConnection
  983. * @param {MediaStream} mediaStream
  984. * @private
  985. */
  986. TraceablePeerConnection.prototype._addStream = function(mediaStream) {
  987. this.peerconnection.addStream(mediaStream);
  988. };
  989. /**
  990. * Removes WebRTC media stream from the underlying PeerConection
  991. * @param {MediaStream} mediaStream
  992. */
  993. TraceablePeerConnection.prototype._removeStream = function(mediaStream) {
  994. if (RTCBrowserType.isFirefox()) {
  995. this._handleFirefoxRemoveStream(mediaStream);
  996. } else {
  997. this.peerconnection.removeStream(mediaStream);
  998. }
  999. };
  1000. /**
  1001. * This method when called will check if given <tt>localTrack</tt> belongs to
  1002. * this TPC (that it has been previously added using {@link addTrack}). If the
  1003. * track does not belong an error message will be logged.
  1004. * @param {string} methodName the method name that will be logged in an error
  1005. * message
  1006. * @param {JitsiLocalTrack} localTrack
  1007. * @return {boolean} <tt>true</tt> if given local track belongs to this TPC or
  1008. * <tt>false</tt> otherwise.
  1009. * @private
  1010. */
  1011. TraceablePeerConnection.prototype._assertTrackBelongs
  1012. = function(methodName, localTrack) {
  1013. const doesBelong = this.localTracks.has(localTrack.rtcId);
  1014. if (!doesBelong) {
  1015. logger.error(
  1016. `${methodName}: ${localTrack} does not belong to ${this}`);
  1017. }
  1018. return doesBelong;
  1019. };
  1020. /**
  1021. * Remove local track from this TPC.
  1022. * @param {JitsiLocalTrack} localTrack the track to be removed from this TPC.
  1023. *
  1024. * FIXME It should probably remove a boolean just like {@link removeTrackMute}
  1025. * The same applies to addTrack.
  1026. */
  1027. TraceablePeerConnection.prototype.removeTrack = function(localTrack) {
  1028. const webRtcStream = localTrack.getOriginalStream();
  1029. this.trace(
  1030. 'removeStream',
  1031. localTrack.rtcId, webRtcStream ? webRtcStream.id : undefined);
  1032. if (!this._assertTrackBelongs('removeStream', localTrack)) {
  1033. // Abort - nothing to be done here
  1034. return;
  1035. }
  1036. this.localTracks.delete(localTrack.rtcId);
  1037. this.localSSRCs.delete(localTrack.rtcId);
  1038. if (webRtcStream) {
  1039. if (RTCBrowserType.isFirefox()) {
  1040. this._handleFirefoxRemoveStream(webRtcStream);
  1041. } else {
  1042. this.peerconnection.removeStream(webRtcStream);
  1043. }
  1044. }
  1045. };
  1046. /**
  1047. * Removes local track as part of the mute operation.
  1048. * @param {JitsiLocalTrack} localTrack the local track to be remove as part of
  1049. * the mute operation.
  1050. * @return {boolean} <tt>true</tt> if the underlying PeerConnection's state has
  1051. * changed and the renegotiation is required or <tt>false</tt> otherwise.
  1052. */
  1053. TraceablePeerConnection.prototype.removeTrackMute = function(localTrack) {
  1054. const webRtcStream = localTrack.getOriginalStream();
  1055. this.trace(
  1056. 'removeStreamMute',
  1057. localTrack.rtcId, webRtcStream ? webRtcStream.id : null);
  1058. if (!this._assertTrackBelongs('removeStreamMute', localTrack)) {
  1059. // Abort - nothing to be done here
  1060. return false;
  1061. }
  1062. if (webRtcStream) {
  1063. logger.info(
  1064. `Removing ${localTrack} as mute from ${this}`);
  1065. this._removeStream(webRtcStream);
  1066. return true;
  1067. }
  1068. logger.error(`removeStreamMute - no WebRTC stream for ${localTrack}`);
  1069. return false;
  1070. };
  1071. /**
  1072. * Remove stream handling for firefox
  1073. * @param stream: webrtc media stream
  1074. */
  1075. TraceablePeerConnection.prototype._handleFirefoxRemoveStream
  1076. = function(stream) {
  1077. if (!stream) {
  1078. // There is nothing to be changed
  1079. return;
  1080. }
  1081. let sender = null;
  1082. // On Firefox we don't replace MediaStreams as this messes up the
  1083. // m-lines (which can't be removed in Plan Unified) and brings a lot
  1084. // of complications. Instead, we use the RTPSender and remove just
  1085. // the track.
  1086. let track = null;
  1087. if (stream.getAudioTracks() && stream.getAudioTracks().length) {
  1088. track = stream.getAudioTracks()[0];
  1089. } else if (stream.getVideoTracks() && stream.getVideoTracks().length) {
  1090. track = stream.getVideoTracks()[0];
  1091. }
  1092. if (!track) {
  1093. logger.error('Cannot remove tracks: no tracks.');
  1094. return;
  1095. }
  1096. // Find the right sender (for audio or video)
  1097. this.peerconnection.getSenders().some(s => {
  1098. if (s.track === track) {
  1099. sender = s;
  1100. return true;
  1101. }
  1102. return false;
  1103. });
  1104. if (sender) {
  1105. this.peerconnection.removeTrack(sender);
  1106. } else {
  1107. logger.log('Cannot remove tracks: no RTPSender.');
  1108. }
  1109. };
  1110. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  1111. this.trace('createDataChannel', label, opts);
  1112. return this.peerconnection.createDataChannel(label, opts);
  1113. };
  1114. /**
  1115. * Ensures that the simulcast ssrc-group appears after any other ssrc-groups
  1116. * in the SDP so that simulcast is properly activated.
  1117. *
  1118. * @param {Object} localSdp the WebRTC session description instance for
  1119. * the local description.
  1120. * @private
  1121. */
  1122. TraceablePeerConnection.prototype._ensureSimulcastGroupIsLast
  1123. = function(localSdp) {
  1124. let sdpStr = localSdp.sdp;
  1125. const videoStartIndex = sdpStr.indexOf('m=video');
  1126. const simStartIndex = sdpStr.indexOf('a=ssrc-group:SIM', videoStartIndex);
  1127. let otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1128. if (simStartIndex === -1
  1129. || otherStartIndex === -1
  1130. || otherStartIndex === simStartIndex) {
  1131. return;
  1132. }
  1133. const simEndIndex = sdpStr.indexOf('\r\n', simStartIndex);
  1134. const simStr = sdpStr.substring(simStartIndex, simEndIndex + 2);
  1135. sdpStr = sdpStr.replace(simStr, '');
  1136. otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1137. const otherEndIndex = sdpStr.indexOf('\r\n', otherStartIndex);
  1138. const sdpHead = sdpStr.slice(0, otherEndIndex);
  1139. const simStrTrimmed = simStr.trim();
  1140. const sdpTail = sdpStr.slice(otherEndIndex);
  1141. sdpStr = `${sdpHead}\r\n${simStrTrimmed}${sdpTail}`;
  1142. localSdp.sdp = sdpStr;
  1143. };
  1144. /**
  1145. * Will adjust audio and video media direction in the given SDP object to
  1146. * reflect the current status of the {@link mediaTransferActive} flag.
  1147. * @param {Object} localDescription the WebRTC session description instance for
  1148. * the local description.
  1149. * @private
  1150. */
  1151. TraceablePeerConnection.prototype._adjustLocalMediaDirection
  1152. = function(localDescription) {
  1153. const transformer = new SdpTransformWrap(localDescription.sdp);
  1154. let modifiedDirection = false;
  1155. const audioMedia = transformer.selectMedia('audio');
  1156. if (audioMedia) {
  1157. const desiredAudioDirection
  1158. = this._getDesiredMediaDirection(MediaType.AUDIO);
  1159. if (audioMedia.direction !== desiredAudioDirection) {
  1160. audioMedia.direction = desiredAudioDirection;
  1161. logger.info(
  1162. `Adjusted local audio direction to ${desiredAudioDirection}`);
  1163. modifiedDirection = true;
  1164. }
  1165. } else {
  1166. logger.warn('No "audio" media found int the local description');
  1167. }
  1168. const videoMedia = transformer.selectMedia('video');
  1169. if (videoMedia) {
  1170. const desiredVideoDirection
  1171. = this._getDesiredMediaDirection(MediaType.VIDEO);
  1172. if (videoMedia.direction !== desiredVideoDirection) {
  1173. videoMedia.direction = desiredVideoDirection;
  1174. logger.info(
  1175. `Adjusted local video direction to ${desiredVideoDirection}`);
  1176. modifiedDirection = true;
  1177. }
  1178. } else {
  1179. logger.warn('No "video" media found in the local description');
  1180. }
  1181. if (modifiedDirection) {
  1182. localDescription.sdp = transformer.toRawSDP();
  1183. }
  1184. };
  1185. TraceablePeerConnection.prototype.setLocalDescription
  1186. = function(description, successCallback, failureCallback) {
  1187. let localSdp = description;
  1188. this.trace('setLocalDescription::preTransform', dumpSDP(localSdp));
  1189. this._adjustLocalMediaDirection(localSdp);
  1190. this._ensureSimulcastGroupIsLast(localSdp);
  1191. // if we're using unified plan, transform to it first.
  1192. if (RTCBrowserType.usesUnifiedPlan()) {
  1193. localSdp = this.interop.toUnifiedPlan(localSdp);
  1194. this.trace(
  1195. 'setLocalDescription::postTransform (Unified Plan)',
  1196. dumpSDP(localSdp));
  1197. }
  1198. this.peerconnection.setLocalDescription(localSdp,
  1199. () => {
  1200. this.trace('setLocalDescriptionOnSuccess');
  1201. const localUfrag = SDPUtil.getUfrag(localSdp.sdp);
  1202. if (localUfrag !== this.localUfrag) {
  1203. this.localUfrag = localUfrag;
  1204. this.rtc.eventEmitter.emit(
  1205. RTCEvents.LOCAL_UFRAG_CHANGED, this, localUfrag);
  1206. }
  1207. successCallback();
  1208. },
  1209. err => {
  1210. this.trace('setLocalDescriptionOnFailure', err);
  1211. this.eventEmitter.emit(
  1212. RTCEvents.SET_LOCAL_DESCRIPTION_FAILED,
  1213. err, this);
  1214. failureCallback(err);
  1215. }
  1216. );
  1217. };
  1218. /**
  1219. * Enables/disables media transmission on this peer connection. When disabled
  1220. * the SDP media direction in the local SDP will be adjusted to 'inactive' which
  1221. * means that no data will be received or sent, but the connection should be
  1222. * kept alive.
  1223. * @param {boolean} active <tt>true</tt> to enable the media transmission or
  1224. * <tt>false</tt> to disable.
  1225. * @public
  1226. */
  1227. TraceablePeerConnection.prototype.setMediaTransferActive = function(active) {
  1228. this.mediaTransferActive = active;
  1229. };
  1230. TraceablePeerConnection.prototype.setRemoteDescription
  1231. = function(description, successCallback, failureCallback) {
  1232. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  1233. // TODO the focus should squeze or explode the remote simulcast
  1234. // eslint-disable-next-line no-param-reassign
  1235. description = this.simulcast.mungeRemoteDescription(description);
  1236. this.trace(
  1237. 'setRemoteDescription::postTransform (simulcast)',
  1238. dumpSDP(description));
  1239. if (this.options.preferH264) {
  1240. const parsedSdp = transform.parse(description.sdp);
  1241. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  1242. SDPUtil.preferVideoCodec(videoMLine, 'h264');
  1243. description.sdp = transform.write(parsedSdp);
  1244. }
  1245. // If the browser uses unified plan, transform to it first
  1246. if (RTCBrowserType.usesUnifiedPlan()) {
  1247. description.sdp = this.rtxModifier.stripRtx(description.sdp);
  1248. this.trace(
  1249. 'setRemoteDescription::postTransform (stripRtx)',
  1250. dumpSDP(description));
  1251. // eslint-disable-next-line no-param-reassign
  1252. description = this.interop.toUnifiedPlan(description);
  1253. this.trace(
  1254. 'setRemoteDescription::postTransform (Plan A)',
  1255. dumpSDP(description));
  1256. } else {
  1257. // Plan B
  1258. // eslint-disable-next-line no-param-reassign
  1259. description = normalizePlanB(description);
  1260. }
  1261. this.peerconnection.setRemoteDescription(
  1262. description,
  1263. () => {
  1264. this.trace('setRemoteDescriptionOnSuccess');
  1265. const remoteUfrag = SDPUtil.getUfrag(description.sdp);
  1266. if (remoteUfrag !== this.remoteUfrag) {
  1267. this.remoteUfrag = remoteUfrag;
  1268. this.rtc.eventEmitter.emit(
  1269. RTCEvents.REMOTE_UFRAG_CHANGED, this, remoteUfrag);
  1270. }
  1271. successCallback();
  1272. },
  1273. err => {
  1274. this.trace('setRemoteDescriptionOnFailure', err);
  1275. this.eventEmitter.emit(
  1276. RTCEvents.SET_REMOTE_DESCRIPTION_FAILED,
  1277. err,
  1278. this);
  1279. failureCallback(err);
  1280. });
  1281. };
  1282. /**
  1283. * Makes the underlying TraceablePeerConnection generate new SSRC for
  1284. * the recvonly video stream.
  1285. */
  1286. TraceablePeerConnection.prototype.generateRecvonlySsrc = function() {
  1287. const newSSRC = SDPUtil.generateSsrc();
  1288. logger.info(`${this} generated new recvonly SSRC: ${newSSRC}`);
  1289. this.sdpConsistency.setPrimarySsrc(newSSRC);
  1290. };
  1291. /**
  1292. * Makes the underlying TraceablePeerConnection forget the current primary video
  1293. * SSRC.
  1294. */
  1295. TraceablePeerConnection.prototype.clearRecvonlySsrc = function() {
  1296. logger.info('Clearing primary video SSRC!');
  1297. this.sdpConsistency.clearVideoSsrcCache();
  1298. };
  1299. TraceablePeerConnection.prototype.close = function() {
  1300. this.trace('stop');
  1301. // Off SignalingEvents
  1302. this.signalingLayer.off(
  1303. SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  1304. this.signalingLayer.off(
  1305. SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  1306. if (!this.rtc._removePeerConnection(this)) {
  1307. logger.error('RTC._removePeerConnection returned false');
  1308. }
  1309. if (this.statsinterval !== null) {
  1310. window.clearInterval(this.statsinterval);
  1311. this.statsinterval = null;
  1312. }
  1313. this.peerconnection.close();
  1314. };
  1315. /**
  1316. * Modifies the values of the setup attributes (defined by
  1317. * {@link http://tools.ietf.org/html/rfc4145#section-4}) of a specific SDP
  1318. * answer in order to overcome a delay of 1 second in the connection
  1319. * establishment between Chrome and Videobridge.
  1320. *
  1321. * @param {SDP} offer - the SDP offer to which the specified SDP answer is
  1322. * being prepared to respond
  1323. * @param {SDP} answer - the SDP to modify
  1324. * @private
  1325. */
  1326. const _fixAnswerRFC4145Setup = function(offer, answer) {
  1327. if (!RTCBrowserType.isChrome()) {
  1328. // It looks like Firefox doesn't agree with the fix (at least in its
  1329. // current implementation) because it effectively remains active even
  1330. // after we tell it to become passive. Apart from Firefox which I tested
  1331. // after the fix was deployed, I tested Chrome only. In order to prevent
  1332. // issues with other browsers, limit the fix to Chrome for the time
  1333. // being.
  1334. return;
  1335. }
  1336. // XXX Videobridge is the (SDP) offerer and WebRTC (e.g. Chrome) is the
  1337. // answerer (as orchestrated by Jicofo). In accord with
  1338. // http://tools.ietf.org/html/rfc5245#section-5.2 and because both peers
  1339. // are ICE FULL agents, Videobridge will take on the controlling role and
  1340. // WebRTC will take on the controlled role. In accord with
  1341. // https://tools.ietf.org/html/rfc5763#section-5, Videobridge will use the
  1342. // setup attribute value of setup:actpass and WebRTC will be allowed to
  1343. // choose either the setup attribute value of setup:active or
  1344. // setup:passive. Chrome will by default choose setup:active because it is
  1345. // RECOMMENDED by the respective RFC since setup:passive adds additional
  1346. // latency. The case of setup:active allows WebRTC to send a DTLS
  1347. // ClientHello as soon as an ICE connectivity check of its succeeds.
  1348. // Unfortunately, Videobridge will be unable to respond immediately because
  1349. // may not have WebRTC's answer or may have not completed the ICE
  1350. // connectivity establishment. Even more unfortunate is that in the
  1351. // described scenario Chrome's DTLS implementation will insist on
  1352. // retransmitting its ClientHello after a second (the time is in accord
  1353. // with the respective RFC) and will thus cause the whole connection
  1354. // establishment to exceed at least 1 second. To work around Chrome's
  1355. // idiosyncracy, don't allow it to send a ClientHello i.e. change its
  1356. // default choice of setup:active to setup:passive.
  1357. if (offer && answer
  1358. && offer.media && answer.media
  1359. && offer.media.length === answer.media.length) {
  1360. answer.media.forEach((a, i) => {
  1361. if (SDPUtil.findLine(
  1362. offer.media[i],
  1363. 'a=setup:actpass',
  1364. offer.session)) {
  1365. answer.media[i]
  1366. = a.replace(/a=setup:active/g, 'a=setup:passive');
  1367. }
  1368. });
  1369. answer.raw = answer.session + answer.media.join('');
  1370. }
  1371. };
  1372. TraceablePeerConnection.prototype.createAnswer
  1373. = function(successCallback, failureCallback, constraints) {
  1374. this._createOfferOrAnswer(
  1375. false /* answer */, successCallback, failureCallback, constraints);
  1376. };
  1377. TraceablePeerConnection.prototype.createOffer
  1378. = function(successCallback, failureCallback, constraints) {
  1379. this._createOfferOrAnswer(
  1380. true /* offer */, successCallback, failureCallback, constraints);
  1381. };
  1382. /* eslint-disable max-params */
  1383. TraceablePeerConnection.prototype._createOfferOrAnswer
  1384. = function(isOffer, successCallback, failureCallback, constraints) {
  1385. const logName = isOffer ? 'Offer' : 'Answer';
  1386. this.trace(`create${logName}`, JSON.stringify(constraints, null, ' '));
  1387. const _successCallback = resultSdp => {
  1388. try {
  1389. this.trace(
  1390. `create${logName}OnSuccess::preTransform`, dumpSDP(resultSdp));
  1391. // if we're using unified plan, transform to Plan B.
  1392. if (RTCBrowserType.usesUnifiedPlan()) {
  1393. // eslint-disable-next-line no-param-reassign
  1394. resultSdp = this.interop.toPlanB(resultSdp);
  1395. this.trace(
  1396. `create${logName}OnSuccess::postTransform (Plan B)`,
  1397. dumpSDP(resultSdp));
  1398. }
  1399. /**
  1400. * We don't keep ssrcs consitent for Firefox because rewriting
  1401. * the ssrcs between createAnswer and setLocalDescription breaks
  1402. * the caching in sdp-interop (sdp-interop must know about all
  1403. * ssrcs, and it updates its cache in toPlanB so if we rewrite them
  1404. * after that, when we try and go back to unified plan it will
  1405. * complain about unmapped ssrcs)
  1406. */
  1407. if (!RTCBrowserType.isFirefox()) {
  1408. // If there are no local video tracks, then a "recvonly"
  1409. // SSRC needs to be generated
  1410. if (!this.hasAnyTracksOfType(MediaType.VIDEO)
  1411. && !this.sdpConsistency.hasPrimarySsrcCached()) {
  1412. this.generateRecvonlySsrc();
  1413. }
  1414. resultSdp.sdp
  1415. = this.sdpConsistency.makeVideoPrimarySsrcsConsistent(
  1416. resultSdp.sdp);
  1417. this.trace(
  1418. `create${logName}OnSuccess::postTransform `
  1419. + '(make primary audio/video ssrcs consistent)',
  1420. dumpSDP(resultSdp));
  1421. }
  1422. // Add simulcast streams if simulcast is enabled
  1423. if (this.isSimulcastOn()) {
  1424. // eslint-disable-next-line no-param-reassign
  1425. resultSdp = this.simulcast.mungeLocalDescription(resultSdp);
  1426. this.trace(
  1427. `create${logName}`
  1428. + 'OnSuccess::postTransform (simulcast)',
  1429. dumpSDP(resultSdp));
  1430. }
  1431. if (!this.options.disableRtx && RTCBrowserType.supportsRtx()) {
  1432. resultSdp.sdp
  1433. = this.rtxModifier.modifyRtxSsrcs(resultSdp.sdp);
  1434. this.trace(
  1435. `create${logName}`
  1436. + 'OnSuccess::postTransform (rtx modifier)',
  1437. dumpSDP(resultSdp));
  1438. }
  1439. // Fix the setup attribute (see _fixAnswerRFC4145Setup for
  1440. // details)
  1441. if (!isOffer) {
  1442. const remoteDescription
  1443. = new SDP(this.remoteDescription.sdp);
  1444. const localDescription = new SDP(resultSdp.sdp);
  1445. _fixAnswerRFC4145Setup(remoteDescription, localDescription);
  1446. resultSdp.sdp = localDescription.raw;
  1447. }
  1448. const ssrcMap = extractSSRCMap(resultSdp);
  1449. logger.debug('Got local SSRCs MAP: ', ssrcMap);
  1450. this._processLocalSSRCsMap(ssrcMap);
  1451. successCallback(resultSdp);
  1452. } catch (e) {
  1453. this.trace(`create${logName}OnError`, e);
  1454. this.trace(`create${logName}OnError`, dumpSDP(resultSdp));
  1455. logger.error(`create${logName}OnError`, e, dumpSDP(resultSdp));
  1456. failureCallback(e);
  1457. }
  1458. };
  1459. const _errorCallback = err => {
  1460. this.trace(`create${logName}OnFailure`, err);
  1461. const eventType
  1462. = isOffer
  1463. ? RTCEvents.CREATE_OFFER_FAILED
  1464. : RTCEvents.CREATE_ANSWER_FAILED;
  1465. this.eventEmitter.emit(eventType, err, this);
  1466. failureCallback(err);
  1467. };
  1468. // NOTE Temasys plugin does not support "bind" on peerconnection methods
  1469. if (isOffer) {
  1470. this.peerconnection.createOffer(
  1471. _successCallback, _errorCallback, constraints);
  1472. } else {
  1473. this.peerconnection.createAnswer(
  1474. _successCallback, _errorCallback, constraints);
  1475. }
  1476. };
  1477. /* eslint-enable max-params */
  1478. /**
  1479. * Extract primary SSRC from given {@link TrackSSRCInfo} object.
  1480. * @param {TrackSSRCInfo} ssrcObj
  1481. * @return {number|null} the primary SSRC or <tt>null</tt>
  1482. */
  1483. function extractPrimarySSRC(ssrcObj) {
  1484. if (ssrcObj && ssrcObj.groups && ssrcObj.groups.length) {
  1485. return ssrcObj.groups[0].ssrcs[0];
  1486. } else if (ssrcObj && ssrcObj.ssrcs && ssrcObj.ssrcs.length) {
  1487. return ssrcObj.ssrcs[0];
  1488. }
  1489. return null;
  1490. }
  1491. /**
  1492. * Goes over the SSRC map extracted from the latest local description and tries
  1493. * to match them with the local tracks (by MSID). Will update the values
  1494. * currently stored in the {@link TraceablePeerConnection.localSSRCs} map.
  1495. * @param {Map<string,TrackSSRCInfo>} ssrcMap
  1496. * @private
  1497. */
  1498. TraceablePeerConnection.prototype._processLocalSSRCsMap = function(ssrcMap) {
  1499. for (const track of this.localTracks.values()) {
  1500. const trackMSID = track.getMSID();
  1501. if (ssrcMap.has(trackMSID)) {
  1502. const newSSRC = ssrcMap.get(trackMSID);
  1503. if (!newSSRC) {
  1504. logger.error(`No SSRC found for: ${trackMSID} in ${this}`);
  1505. return;
  1506. }
  1507. const oldSSRC = this.localSSRCs.get(track.rtcId);
  1508. const newSSRCNum = extractPrimarySSRC(newSSRC);
  1509. const oldSSRCNum = extractPrimarySSRC(oldSSRC);
  1510. // eslint-disable-next-line no-negated-condition
  1511. if (newSSRCNum !== oldSSRCNum) {
  1512. if (oldSSRCNum === null) {
  1513. logger.info(
  1514. `Storing new local SSRC for ${track} in ${this}`,
  1515. newSSRC);
  1516. } else {
  1517. logger.error(
  1518. `Overwriting SSRC for ${track} ${trackMSID} in ${this
  1519. } with: `, newSSRC);
  1520. }
  1521. this.localSSRCs.set(track.rtcId, newSSRC);
  1522. } else {
  1523. logger.debug(
  1524. `The local SSRC(${newSSRCNum}) for ${track} ${trackMSID}`
  1525. + `is still up to date in ${this}`);
  1526. }
  1527. } else {
  1528. logger.warn(`No local track matched with: ${trackMSID} in ${this}`);
  1529. }
  1530. }
  1531. };
  1532. TraceablePeerConnection.prototype.addIceCandidate
  1533. = function(candidate, successCallback, failureCallback) {
  1534. // var self = this;
  1535. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  1536. this.peerconnection.addIceCandidate(
  1537. candidate, successCallback, failureCallback);
  1538. /* maybe later
  1539. this.peerconnection.addIceCandidate(candidate,
  1540. function () {
  1541. self.trace('addIceCandidateOnSuccess');
  1542. successCallback();
  1543. },
  1544. function (err) {
  1545. self.trace('addIceCandidateOnFailure', err);
  1546. failureCallback(err);
  1547. }
  1548. );
  1549. */
  1550. };
  1551. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  1552. // TODO: Is this the correct way to handle Opera, Temasys?
  1553. if (RTCBrowserType.isFirefox()
  1554. || RTCBrowserType.isTemasysPluginUsed()
  1555. || RTCBrowserType.isReactNative()) {
  1556. this.peerconnection.getStats(
  1557. null,
  1558. callback,
  1559. errback || (() => {
  1560. // Making sure that getStats won't fail if error callback is
  1561. // not passed.
  1562. }));
  1563. } else {
  1564. this.peerconnection.getStats(callback);
  1565. }
  1566. };
  1567. /**
  1568. * Generates and stores new SSRC info object for given local track.
  1569. * The method should be called only for a video track being added to this TPC
  1570. * in the muted state (given that the current browser uses this strategy).
  1571. * @param {JitsiLocalTrack} track
  1572. * @return {TPCSSRCInfo}
  1573. */
  1574. TraceablePeerConnection.prototype.generateNewStreamSSRCInfo = function(track) {
  1575. const rtcId = track.rtcId;
  1576. let ssrcInfo = this._getSSRC(rtcId);
  1577. if (ssrcInfo) {
  1578. logger.error(`Will overwrite local SSRCs for track ID: ${rtcId}`);
  1579. }
  1580. if (this.isSimulcastOn()) {
  1581. ssrcInfo = {
  1582. ssrcs: [],
  1583. groups: []
  1584. };
  1585. for (let i = 0; i < SIMULCAST_LAYERS; i++) {
  1586. ssrcInfo.ssrcs.push(SDPUtil.generateSsrc());
  1587. }
  1588. ssrcInfo.groups.push({
  1589. ssrcs: ssrcInfo.ssrcs.slice(),
  1590. semantics: 'SIM'
  1591. });
  1592. } else {
  1593. ssrcInfo = {
  1594. ssrcs: [ SDPUtil.generateSsrc() ],
  1595. groups: []
  1596. };
  1597. }
  1598. if (!this.options.disableRtx && RTCBrowserType.supportsRtx()) {
  1599. // Specifically use a for loop here because we'll
  1600. // be adding to the list we're iterating over, so we
  1601. // only want to iterate through the items originally
  1602. // on the list
  1603. const currNumSsrcs = ssrcInfo.ssrcs.length;
  1604. for (let i = 0; i < currNumSsrcs; ++i) {
  1605. const primarySsrc = ssrcInfo.ssrcs[i];
  1606. const rtxSsrc = SDPUtil.generateSsrc();
  1607. ssrcInfo.ssrcs.push(rtxSsrc);
  1608. ssrcInfo.groups.push({
  1609. ssrcs: [ primarySsrc, rtxSsrc ],
  1610. semantics: 'FID'
  1611. });
  1612. }
  1613. }
  1614. ssrcInfo.msid = track.storedMSID;
  1615. this.localSSRCs.set(rtcId, ssrcInfo);
  1616. return ssrcInfo;
  1617. };
  1618. /**
  1619. * Creates a text representation of this <tt>TraceablePeerConnection</tt>
  1620. * instance.
  1621. * @return {string}
  1622. */
  1623. TraceablePeerConnection.prototype.toString = function() {
  1624. return `TPC[${this.id},p2p:${this.isP2P}]`;
  1625. };