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

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