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

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