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

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