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

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