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

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