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.

RTPStatsCollector.js 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. /* global require */
  2. /* jshint -W101 */
  3. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5. var StatisticsEvents = require("../../service/statistics/Events");
  6. /* Whether we support the browser we are running into for logging statistics */
  7. var browserSupported = RTCBrowserType.isChrome() ||
  8. RTCBrowserType.isOpera() || RTCBrowserType.isFirefox();
  9. /**
  10. * The LibJitsiMeet browser-agnostic names of the browser-specific keys reported
  11. * by RTCPeerConnection#getStats mapped by RTCBrowserType.
  12. */
  13. var KEYS_BY_BROWSER_TYPE = {};
  14. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  15. "ssrc": "ssrc",
  16. "packetsReceived": "packetsReceived",
  17. "packetsLost": "packetsLost",
  18. "packetsSent": "packetsSent",
  19. "bytesReceived": "bytesReceived",
  20. "bytesSent": "bytesSent"
  21. };
  22. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME] = {
  23. "receiveBandwidth": "googAvailableReceiveBandwidth",
  24. "sendBandwidth": "googAvailableSendBandwidth",
  25. "remoteAddress": "googRemoteAddress",
  26. "transportType": "googTransportType",
  27. "localAddress": "googLocalAddress",
  28. "activeConnection": "googActiveConnection",
  29. "ssrc": "ssrc",
  30. "packetsReceived": "packetsReceived",
  31. "packetsSent": "packetsSent",
  32. "packetsLost": "packetsLost",
  33. "bytesReceived": "bytesReceived",
  34. "bytesSent": "bytesSent",
  35. "googFrameHeightReceived": "googFrameHeightReceived",
  36. "googFrameWidthReceived": "googFrameWidthReceived",
  37. "googFrameHeightSent": "googFrameHeightSent",
  38. "googFrameWidthSent": "googFrameWidthSent",
  39. "audioInputLevel": "audioInputLevel",
  40. "audioOutputLevel": "audioOutputLevel"
  41. };
  42. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_OPERA] =
  43. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  44. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_IEXPLORER] =
  45. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  46. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_SAFARI] =
  47. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  48. /**
  49. * Calculates packet lost percent using the number of lost packets and the
  50. * number of all packet.
  51. * @param lostPackets the number of lost packets
  52. * @param totalPackets the number of all packets.
  53. * @returns {number} packet loss percent
  54. */
  55. function calculatePacketLoss(lostPackets, totalPackets) {
  56. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  57. return 0;
  58. return Math.round((lostPackets/totalPackets)*100);
  59. }
  60. function formatAudioLevel(audioLevel) {
  61. return Math.min(Math.max(audioLevel, 0), 1);
  62. }
  63. /**
  64. * Checks whether a certain record should be included in the logged statistics.
  65. */
  66. function acceptStat(reportId, reportType, statName) {
  67. if (reportType == "googCandidatePair") {
  68. if (statName == "googChannelId")
  69. return false;
  70. } else if (reportType == "ssrc") {
  71. if (statName == "googTrackId" ||
  72. statName == "transportId" ||
  73. statName == "ssrc")
  74. return false;
  75. }
  76. return true;
  77. }
  78. /**
  79. * Checks whether a certain record should be included in the logged statistics.
  80. */
  81. function acceptReport(id, type) {
  82. if (type == "googComponent")
  83. return false;
  84. if (id.substring(0, 15) == "googCertificate" ||
  85. id.substring(0, 9) == "googTrack" ||
  86. id.substring(0, 20) == "googLibjingleSession")
  87. return false;
  88. return true;
  89. }
  90. /**
  91. * Peer statistics data holder.
  92. * @constructor
  93. */
  94. function PeerStats() {
  95. this.ssrc2Loss = {};
  96. this.ssrc2AudioLevel = {};
  97. this.ssrc2bitrate = {
  98. download: 0,
  99. upload: 0
  100. };
  101. this.ssrc2resolution = {};
  102. }
  103. /**
  104. * Sets packets loss rate for given <tt>ssrc</tt> that belong to the peer
  105. * represented by this instance.
  106. * @param lossRate new packet loss rate value to be set.
  107. */
  108. PeerStats.prototype.setSsrcLoss = function (lossRate) {
  109. this.ssrc2Loss = lossRate || {};
  110. };
  111. /**
  112. * Sets resolution that belong to the ssrc
  113. * represented by this instance.
  114. * @param resolution new resolution value to be set.
  115. */
  116. PeerStats.prototype.setSsrcResolution = function (resolution) {
  117. this.ssrc2resolution = resolution || {};
  118. };
  119. /**
  120. * Sets the bit rate for given <tt>ssrc</tt> that belong to the peer
  121. * represented by this instance.
  122. * @param bitrate new bitrate value to be set.
  123. */
  124. PeerStats.prototype.setSsrcBitrate = function (bitrate) {
  125. this.ssrc2bitrate.download += bitrate.download;
  126. this.ssrc2bitrate.upload += bitrate.upload;
  127. };
  128. /**
  129. * Resets the bit rate for given <tt>ssrc</tt> that belong to the peer
  130. * represented by this instance.
  131. */
  132. PeerStats.prototype.resetSsrcBitrate = function () {
  133. this.ssrc2bitrate.download = 0;
  134. this.ssrc2bitrate.upload = 0;
  135. };
  136. /**
  137. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  138. * the stream which belongs to the peer represented by this instance.
  139. * @param audioLevel the new audio level value to be set. Value is truncated to
  140. * fit the range from 0 to 1.
  141. */
  142. PeerStats.prototype.setSsrcAudioLevel = function (audioLevel) {
  143. // Range limit 0 - 1
  144. this.ssrc2AudioLevel = formatAudioLevel(audioLevel);
  145. };
  146. function ConferenceStats() {
  147. /**
  148. * The bandwidth
  149. * @type {{}}
  150. */
  151. this.bandwidth = {};
  152. /**
  153. * The bit rate
  154. * @type {{}}
  155. */
  156. this.bitrate = {};
  157. /**
  158. * The packet loss rate
  159. * @type {{}}
  160. */
  161. this.packetLoss = null;
  162. /**
  163. * Array with the transport information.
  164. * @type {Array}
  165. */
  166. this.transport = [];
  167. }
  168. /**
  169. * <tt>StatsCollector</tt> registers for stats updates of given
  170. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  171. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  172. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  173. * instance as an event source.
  174. *
  175. * @param peerconnection WebRTC PeerConnection object.
  176. * @param audioLevelsInterval
  177. * @param statsInterval stats refresh interval given in ms.
  178. * @param eventEmitter
  179. * @param config {object} supports the following properties: disableAudioLevels,
  180. * disableStats, logStats
  181. * @constructor
  182. */
  183. function StatsCollector(
  184. peerconnection,
  185. audioLevelsInterval,
  186. statsInterval,
  187. eventEmitter,
  188. config) {
  189. // StatsCollector depends entirely on the format of the reports returned by
  190. // RTCPeerConnection#getStats. Given that the value of
  191. // RTCBrowserType#getBrowserType() is very unlikely to change at runtime, it
  192. // makes sense to discover whether StatsCollector supports the executing
  193. // browser as soon as possible. Otherwise, (1) getStatValue would have to
  194. // needlessly check a "static" condition multiple times very very often and
  195. // (2) the lack of support for the executing browser would be discovered and
  196. // reported multiple times very very often too late in the execution in some
  197. // totally unrelated callback.
  198. /**
  199. * The RTCBrowserType supported by this StatsCollector. In other words, the
  200. * RTCBrowserType of the browser which initialized this StatsCollector
  201. * instance.
  202. * @private
  203. */
  204. this._browserType = RTCBrowserType.getBrowserType();
  205. var keys = KEYS_BY_BROWSER_TYPE[this._browserType];
  206. if (!keys)
  207. throw "The browser type '" + this._browserType + "' isn't supported!";
  208. /**
  209. * The function which is to be used to retrieve the value associated in a
  210. * report returned by RTCPeerConnection#getStats with a LibJitsiMeet
  211. * browser-agnostic name/key.
  212. * @function
  213. * @private
  214. */
  215. this._getStatValue = this._defineGetStatValueMethod(keys);
  216. this.peerconnection = peerconnection;
  217. this.baselineAudioLevelsReport = null;
  218. this.currentAudioLevelsReport = null;
  219. this.currentStatsReport = null;
  220. this.baselineStatsReport = null;
  221. this.audioLevelsIntervalId = null;
  222. this.eventEmitter = eventEmitter;
  223. this.config = config || {};
  224. this.conferenceStats = new ConferenceStats();
  225. /**
  226. * Gather PeerConnection stats once every this many milliseconds.
  227. */
  228. this.GATHER_INTERVAL = 15000;
  229. /**
  230. * Gather stats and store them in this.statsToBeLogged.
  231. */
  232. this.gatherStatsIntervalId = null;
  233. /**
  234. * Stores the statistics which will be send to the focus to be logged.
  235. */
  236. this.statsToBeLogged = {
  237. timestamps: [],
  238. stats: {}
  239. };
  240. // Updates stats interval
  241. this.audioLevelsIntervalMilis = audioLevelsInterval;
  242. this.statsIntervalId = null;
  243. this.statsIntervalMilis = statsInterval;
  244. // Map of ssrcs to PeerStats
  245. this.ssrc2stats = {};
  246. }
  247. module.exports = StatsCollector;
  248. /**
  249. * Stops stats updates.
  250. */
  251. StatsCollector.prototype.stop = function () {
  252. if (this.audioLevelsIntervalId) {
  253. clearInterval(this.audioLevelsIntervalId);
  254. this.audioLevelsIntervalId = null;
  255. }
  256. if (this.statsIntervalId) {
  257. clearInterval(this.statsIntervalId);
  258. this.statsIntervalId = null;
  259. }
  260. if (this.gatherStatsIntervalId) {
  261. clearInterval(this.gatherStatsIntervalId);
  262. this.gatherStatsIntervalId = null;
  263. }
  264. };
  265. /**
  266. * Callback passed to <tt>getStats</tt> method.
  267. * @param error an error that occurred on <tt>getStats</tt> call.
  268. */
  269. StatsCollector.prototype.errorCallback = function (error) {
  270. logger.error("Get stats error", error);
  271. this.stop();
  272. };
  273. /**
  274. * Starts stats updates.
  275. */
  276. StatsCollector.prototype.start = function () {
  277. var self = this;
  278. this.audioLevelsIntervalId = setInterval(
  279. function () {
  280. // Interval updates
  281. self.peerconnection.getStats(
  282. function (report) {
  283. var results = null;
  284. if (!report || !report.result ||
  285. typeof report.result != 'function') {
  286. results = report;
  287. }
  288. else {
  289. results = report.result();
  290. }
  291. //logger.error("Got interval report", results);
  292. self.currentAudioLevelsReport = results;
  293. self.processAudioLevelReport();
  294. self.baselineAudioLevelsReport =
  295. self.currentAudioLevelsReport;
  296. },
  297. self.errorCallback
  298. );
  299. },
  300. self.audioLevelsIntervalMilis
  301. );
  302. if (!this.config.disableStats && browserSupported) {
  303. this.statsIntervalId = setInterval(
  304. function () {
  305. // Interval updates
  306. self.peerconnection.getStats(
  307. function (report) {
  308. var results = null;
  309. if (!report || !report.result ||
  310. typeof report.result != 'function') {
  311. //firefox
  312. results = report;
  313. }
  314. else {
  315. //chrome
  316. results = report.result();
  317. }
  318. //logger.error("Got interval report", results);
  319. self.currentStatsReport = results;
  320. try {
  321. self.processStatsReport();
  322. }
  323. catch (e) {
  324. logger.error("Unsupported key:" + e, e);
  325. }
  326. self.baselineStatsReport = self.currentStatsReport;
  327. },
  328. self.errorCallback
  329. );
  330. },
  331. self.statsIntervalMilis
  332. );
  333. }
  334. if (this.config.logStats
  335. && browserSupported
  336. // logging statistics does not support firefox
  337. && this._browserType !== RTCBrowserType.RTC_BROWSER_FIREFOX) {
  338. this.gatherStatsIntervalId = setInterval(
  339. function () {
  340. self.peerconnection.getStats(
  341. function (report) {
  342. self.addStatsToBeLogged(report.result());
  343. },
  344. function () {
  345. }
  346. );
  347. },
  348. this.GATHER_INTERVAL
  349. );
  350. }
  351. };
  352. /**
  353. * Converts the stats to the format used for logging, and saves the data in
  354. * this.statsToBeLogged.
  355. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  356. */
  357. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  358. var self = this;
  359. var num_records = this.statsToBeLogged.timestamps.length;
  360. this.statsToBeLogged.timestamps.push(new Date().getTime());
  361. reports.forEach(function (report) {
  362. if (!acceptReport(report.id, report.type))
  363. return;
  364. var stat = self.statsToBeLogged.stats[report.id];
  365. if (!stat) {
  366. stat = self.statsToBeLogged.stats[report.id] = {};
  367. }
  368. stat.type = report.type;
  369. report.names().forEach(function (name) {
  370. if (!acceptStat(report.id, report.type, name))
  371. return;
  372. var values = stat[name];
  373. if (!values) {
  374. values = stat[name] = [];
  375. }
  376. while (values.length < num_records) {
  377. values.push(null);
  378. }
  379. values.push(report.stat(name));
  380. });
  381. });
  382. };
  383. StatsCollector.prototype.getCollectedStats = function () {
  384. return this.statsToBeLogged;
  385. };
  386. StatsCollector.prototype.clearCollectedStats = function () {
  387. // Reset the stats
  388. this.statsToBeLogged.stats = {};
  389. this.statsToBeLogged.timestamps = [];
  390. };
  391. /**
  392. * Defines a function which (1) is to be used as a StatsCollector method and (2)
  393. * gets the value from a specific report returned by RTCPeerConnection#getStats
  394. * associated with a LibJitsiMeet browser-agnostic name.
  395. *
  396. * @param {Object.<string,string>} keys the map of LibJitsi browser-agnostic
  397. * names to RTCPeerConnection#getStats browser-specific keys
  398. */
  399. StatsCollector.prototype._defineGetStatValueMethod = function (keys) {
  400. // Define the function which converts a LibJitsiMeet browser-asnostic name
  401. // to a browser-specific key of a report returned by
  402. // RTCPeerConnection#getStats.
  403. var keyFromName = function (name) {
  404. var key = keys[name];
  405. if (key)
  406. return key;
  407. else
  408. throw "The property '" + name + "' isn't supported!";
  409. };
  410. // Define the function which retrieves the value from a specific report
  411. // returned by RTCPeerConnection#getStats associated with a given
  412. // browser-specific key.
  413. var itemStatByKey;
  414. switch (this._browserType) {
  415. case RTCBrowserType.RTC_BROWSER_CHROME:
  416. case RTCBrowserType.RTC_BROWSER_OPERA:
  417. // TODO What about other types of browser which are based on Chrome such
  418. // as NW.js? Every time we want to support a new type browser we have to
  419. // go and add more conditions (here and in multiple other places).
  420. // Cannot we do a feature detection instead of a browser type check? For
  421. // example, if item has a stat property of type function, then it's very
  422. // likely that whoever defined it wanted you to call it in order to
  423. // retrieve the value associated with a specific key.
  424. itemStatByKey = function (item, key) { return item.stat(key) };
  425. break;
  426. default:
  427. itemStatByKey = function (item, key) { return item[key] };
  428. }
  429. // Compose the 2 functions defined above to get a function which retrieves
  430. // the value from a specific report returned by RTCPeerConnection#getStats
  431. // associated with a specific LibJitsiMeet browser-agnostic name.
  432. return function (item, name) {
  433. return itemStatByKey(item, keyFromName(name))
  434. };
  435. };
  436. /**
  437. * Stats processing logic.
  438. */
  439. StatsCollector.prototype.processStatsReport = function () {
  440. if (!this.baselineStatsReport) {
  441. return;
  442. }
  443. var getStatValue = this._getStatValue;
  444. for (var idx in this.currentStatsReport) {
  445. var now = this.currentStatsReport[idx];
  446. try {
  447. var receiveBandwidth = getStatValue(now, 'receiveBandwidth');
  448. var sendBandwidth = getStatValue(now, 'sendBandwidth');
  449. if (receiveBandwidth || sendBandwidth) {
  450. this.conferenceStats.bandwidth = {
  451. "download": Math.round(receiveBandwidth / 1000),
  452. "upload": Math.round(sendBandwidth / 1000)
  453. };
  454. }
  455. }
  456. catch(e){/*not supported*/}
  457. if(now.type == 'googCandidatePair')
  458. {
  459. var ip, type, localip, active;
  460. try {
  461. ip = getStatValue(now, 'remoteAddress');
  462. type = getStatValue(now, "transportType");
  463. localip = getStatValue(now, "localAddress");
  464. active = getStatValue(now, "activeConnection");
  465. }
  466. catch(e){/*not supported*/}
  467. if(!ip || !type || !localip || active != "true")
  468. continue;
  469. // Save the address unless it has been saved already.
  470. var conferenceStatsTransport = this.conferenceStats.transport;
  471. if(!conferenceStatsTransport.some(function (t) { return (
  472. t.ip == ip && t.type == type && t.localip == localip
  473. )})) {
  474. conferenceStatsTransport.push(
  475. {ip: ip, type: type, localip: localip});
  476. }
  477. continue;
  478. }
  479. if(now.type == "candidatepair") {
  480. if(now.state == "succeeded")
  481. continue;
  482. var local = this.currentStatsReport[now.localCandidateId];
  483. var remote = this.currentStatsReport[now.remoteCandidateId];
  484. this.conferenceStats.transport.push({
  485. ip: remote.ipAddress + ":" + remote.portNumber,
  486. type: local.transport,
  487. localip: local.ipAddress + ":" + local.portNumber
  488. });
  489. }
  490. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  491. now.type != "inboundrtp") {
  492. continue;
  493. }
  494. var before = this.baselineStatsReport[idx];
  495. var ssrc = getStatValue(now, 'ssrc');
  496. if (!before) {
  497. logger.warn(ssrc + ' not enough data');
  498. continue;
  499. }
  500. if(!ssrc)
  501. continue;
  502. var ssrcStats
  503. = this.ssrc2stats[ssrc] || (this.ssrc2stats[ssrc] = new PeerStats());
  504. var isDownloadStream = true;
  505. var key = 'packetsReceived';
  506. var packetsNow = getStatValue(now, key);
  507. if (typeof packetsNow === 'undefined'
  508. || packetsNow === null || packetsNow === "") {
  509. isDownloadStream = false;
  510. key = 'packetsSent';
  511. packetsNow = getStatValue(now, key);
  512. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  513. logger.warn("No packetsReceived nor packetsSent stat found");
  514. continue;
  515. }
  516. }
  517. if (!packetsNow || packetsNow < 0)
  518. packetsNow = 0;
  519. var packetsBefore = getStatValue(before, key);
  520. if (!packetsBefore || packetsBefore < 0)
  521. packetsBefore = 0;
  522. var packetRate = packetsNow - packetsBefore;
  523. if (!packetRate || packetRate < 0)
  524. packetRate = 0;
  525. var currentLoss = getStatValue(now, 'packetsLost');
  526. if (!currentLoss || currentLoss < 0)
  527. currentLoss = 0;
  528. var previousLoss = getStatValue(before, 'packetsLost');
  529. if (!previousLoss || previousLoss < 0)
  530. previousLoss = 0;
  531. var lossRate = currentLoss - previousLoss;
  532. if (!lossRate || lossRate < 0)
  533. lossRate = 0;
  534. var packetsTotal = (packetRate + lossRate);
  535. ssrcStats.setSsrcLoss({
  536. packetsTotal: packetsTotal,
  537. packetsLost: lossRate,
  538. isDownloadStream: isDownloadStream
  539. });
  540. var bytesReceived = 0, bytesSent = 0;
  541. var nowBytesTransmitted = getStatValue(now, "bytesReceived");
  542. if(nowBytesTransmitted) {
  543. bytesReceived
  544. = nowBytesTransmitted - getStatValue(before, "bytesReceived");
  545. }
  546. nowBytesTransmitted = getStatValue(now, "bytesSent");
  547. if (nowBytesTransmitted) {
  548. bytesSent = nowBytesTransmitted - getStatValue(before, "bytesSent");
  549. }
  550. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  551. if (bytesReceived <= 0 || time <= 0) {
  552. bytesReceived = 0;
  553. } else {
  554. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  555. }
  556. if (bytesSent <= 0 || time <= 0) {
  557. bytesSent = 0;
  558. } else {
  559. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  560. }
  561. ssrcStats.setSsrcBitrate({
  562. "download": bytesReceived,
  563. "upload": bytesSent
  564. });
  565. var resolution = {height: null, width: null};
  566. try {
  567. var height, width;
  568. if ((height = getStatValue(now, "googFrameHeightReceived")) &&
  569. (width = getStatValue(now, "googFrameWidthReceived"))) {
  570. resolution.height = height;
  571. resolution.width = width;
  572. }
  573. else if ((height = getStatValue(now, "googFrameHeightSent")) &&
  574. (width = getStatValue(now, "googFrameWidthSent"))) {
  575. resolution.height = height;
  576. resolution.width = width;
  577. }
  578. }
  579. catch(e){/*not supported*/}
  580. if (resolution.height && resolution.width) {
  581. ssrcStats.setSsrcResolution(resolution);
  582. } else {
  583. ssrcStats.setSsrcResolution(null);
  584. }
  585. }
  586. // process stats
  587. var totalPackets = {
  588. download: 0,
  589. upload: 0
  590. };
  591. var lostPackets = {
  592. download: 0,
  593. upload: 0
  594. };
  595. var bitrateDownload = 0;
  596. var bitrateUpload = 0;
  597. var resolutions = {};
  598. Object.keys(this.ssrc2stats).forEach(
  599. function (ssrc) {
  600. var ssrcStats = this.ssrc2stats[ssrc];
  601. // process package loss stats
  602. var ssrc2Loss = ssrcStats.ssrc2Loss;
  603. var type = ssrc2Loss.isDownloadStream ? "download" : "upload";
  604. totalPackets[type] += ssrc2Loss.packetsTotal;
  605. lostPackets[type] += ssrc2Loss.packetsLost;
  606. // process bitrate stats
  607. var ssrc2bitrate = ssrcStats.ssrc2bitrate;
  608. bitrateDownload += ssrc2bitrate.download;
  609. bitrateUpload += ssrc2bitrate.upload;
  610. ssrcStats.resetSsrcBitrate();
  611. // collect resolutions
  612. resolutions[ssrc] = ssrcStats.ssrc2resolution;
  613. },
  614. this
  615. );
  616. this.conferenceStats.bitrate
  617. = {"upload": bitrateUpload, "download": bitrateDownload};
  618. this.conferenceStats.packetLoss = {
  619. total:
  620. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  621. totalPackets.download + totalPackets.upload),
  622. download:
  623. calculatePacketLoss(lostPackets.download, totalPackets.download),
  624. upload:
  625. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  626. };
  627. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS, {
  628. "bitrate": this.conferenceStats.bitrate,
  629. "packetLoss": this.conferenceStats.packetLoss,
  630. "bandwidth": this.conferenceStats.bandwidth,
  631. "resolution": resolutions,
  632. "transport": this.conferenceStats.transport
  633. });
  634. this.conferenceStats.transport = [];
  635. };
  636. /**
  637. * Stats processing logic.
  638. */
  639. StatsCollector.prototype.processAudioLevelReport = function () {
  640. if (!this.baselineAudioLevelsReport) {
  641. return;
  642. }
  643. var getStatValue = this._getStatValue;
  644. for (var idx in this.currentAudioLevelsReport) {
  645. var now = this.currentAudioLevelsReport[idx];
  646. //if we don't have "packetsReceived" this is local stream
  647. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  648. continue;
  649. }
  650. var before = this.baselineAudioLevelsReport[idx];
  651. var ssrc = getStatValue(now, 'ssrc');
  652. if (!before) {
  653. logger.warn(ssrc + ' not enough data');
  654. continue;
  655. }
  656. if (!ssrc) {
  657. if ((Date.now() - now.timestamp) < 3000)
  658. logger.warn("No ssrc: ");
  659. continue;
  660. }
  661. var ssrcStats
  662. = this.ssrc2stats[ssrc]
  663. || (this.ssrc2stats[ssrc] = new PeerStats());
  664. // Audio level
  665. try {
  666. var audioLevel
  667. = getStatValue(now, 'audioInputLevel')
  668. || getStatValue(now, 'audioOutputLevel');
  669. }
  670. catch(e) {/*not supported*/
  671. logger.warn("Audio Levels are not available in the statistics.");
  672. clearInterval(this.audioLevelsIntervalId);
  673. return;
  674. }
  675. if (audioLevel) {
  676. // TODO: can't find specs about what this value really is,
  677. // but it seems to vary between 0 and around 32k.
  678. audioLevel = audioLevel / 32767;
  679. ssrcStats.setSsrcAudioLevel(audioLevel);
  680. this.eventEmitter.emit(
  681. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  682. }
  683. }
  684. };