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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  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. * @constructor
  183. */
  184. function StatsCollector(
  185. peerconnection,
  186. audioLevelsInterval,
  187. statsInterval,
  188. eventEmitter) {
  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.conferenceStats = new ConferenceStats();
  224. /**
  225. * Gather PeerConnection stats once every this many milliseconds.
  226. */
  227. this.GATHER_INTERVAL = 15000;
  228. /**
  229. * Gather stats and store them in this.statsToBeLogged.
  230. */
  231. this.gatherStatsIntervalId = null;
  232. /**
  233. * Stores the statistics which will be send to the focus to be logged.
  234. */
  235. this.statsToBeLogged = {
  236. timestamps: [],
  237. stats: {}
  238. };
  239. // Updates stats interval
  240. this.audioLevelsIntervalMilis = audioLevelsInterval;
  241. this.statsIntervalId = null;
  242. this.statsIntervalMilis = statsInterval;
  243. // Map of ssrcs to PeerStats
  244. this.ssrc2stats = {};
  245. }
  246. module.exports = StatsCollector;
  247. /**
  248. * Stops stats updates.
  249. */
  250. StatsCollector.prototype.stop = function () {
  251. if (this.audioLevelsIntervalId) {
  252. clearInterval(this.audioLevelsIntervalId);
  253. this.audioLevelsIntervalId = null;
  254. }
  255. if (this.statsIntervalId) {
  256. clearInterval(this.statsIntervalId);
  257. this.statsIntervalId = null;
  258. }
  259. if (this.gatherStatsIntervalId) {
  260. clearInterval(this.gatherStatsIntervalId);
  261. this.gatherStatsIntervalId = null;
  262. }
  263. };
  264. /**
  265. * Callback passed to <tt>getStats</tt> method.
  266. * @param error an error that occurred on <tt>getStats</tt> call.
  267. */
  268. StatsCollector.prototype.errorCallback = function (error) {
  269. GlobalOnErrorHandler.callErrorHandler(error);
  270. logger.error("Get stats error", error);
  271. this.stop();
  272. };
  273. /**
  274. * Starts stats updates.
  275. */
  276. StatsCollector.prototype.start = function (startAudioLevelStats) {
  277. var self = this;
  278. if(startAudioLevelStats) {
  279. this.audioLevelsIntervalId = setInterval(
  280. function () {
  281. // Interval updates
  282. self.peerconnection.getStats(
  283. function (report) {
  284. var results = null;
  285. if (!report || !report.result ||
  286. typeof report.result != 'function') {
  287. results = report;
  288. }
  289. else {
  290. results = report.result();
  291. }
  292. self.currentAudioLevelsReport = results;
  293. self.processAudioLevelReport();
  294. self.baselineAudioLevelsReport =
  295. self.currentAudioLevelsReport;
  296. },
  297. self.errorCallback
  298. );
  299. },
  300. self.audioLevelsIntervalMilis
  301. );
  302. }
  303. if (browserSupported) {
  304. this.statsIntervalId = setInterval(
  305. function () {
  306. // Interval updates
  307. self.peerconnection.getStats(
  308. function (report) {
  309. var results = null;
  310. if (!report || !report.result ||
  311. typeof report.result != 'function') {
  312. //firefox
  313. results = report;
  314. }
  315. else {
  316. //chrome
  317. results = report.result();
  318. }
  319. self.currentStatsReport = results;
  320. try {
  321. self.processStatsReport();
  322. }
  323. catch (e) {
  324. GlobalOnErrorHandler.callErrorHandler(e);
  325. logger.error("Unsupported key:" + e, e);
  326. }
  327. self.baselineStatsReport = self.currentStatsReport;
  328. },
  329. self.errorCallback
  330. );
  331. },
  332. self.statsIntervalMilis
  333. );
  334. }
  335. if (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. case RTCBrowserType.RTC_BROWSER_REACT_NATIVE:
  427. // The implementation provided by react-native-webrtc follows the
  428. // Objective-C WebRTC API: RTCStatsReport has a values property of type
  429. // Array in which each element is a key-value pair.
  430. itemStatByKey = function (item, key) {
  431. var value;
  432. item.values.some(function (pair) {
  433. if (pair.hasOwnProperty(key)) {
  434. value = pair[key];
  435. return true;
  436. } else {
  437. return false;
  438. }
  439. });
  440. return value;
  441. };
  442. break;
  443. default:
  444. itemStatByKey = function (item, key) { return item[key] };
  445. }
  446. // Compose the 2 functions defined above to get a function which retrieves
  447. // the value from a specific report returned by RTCPeerConnection#getStats
  448. // associated with a specific LibJitsiMeet browser-agnostic name.
  449. return function (item, name) {
  450. return itemStatByKey(item, keyFromName(name))
  451. };
  452. };
  453. /**
  454. * Stats processing logic.
  455. */
  456. StatsCollector.prototype.processStatsReport = function () {
  457. if (!this.baselineStatsReport) {
  458. return;
  459. }
  460. var getStatValue = this._getStatValue;
  461. byteSentStats = {};
  462. for (var idx in this.currentStatsReport) {
  463. var now = this.currentStatsReport[idx];
  464. try {
  465. var receiveBandwidth = getStatValue(now, 'receiveBandwidth');
  466. var sendBandwidth = getStatValue(now, 'sendBandwidth');
  467. if (receiveBandwidth || sendBandwidth) {
  468. this.conferenceStats.bandwidth = {
  469. "download": Math.round(receiveBandwidth / 1000),
  470. "upload": Math.round(sendBandwidth / 1000)
  471. };
  472. }
  473. }
  474. catch(e){/*not supported*/}
  475. if(now.type == 'googCandidatePair')
  476. {
  477. var ip, type, localip, active;
  478. try {
  479. ip = getStatValue(now, 'remoteAddress');
  480. type = getStatValue(now, "transportType");
  481. localip = getStatValue(now, "localAddress");
  482. active = getStatValue(now, "activeConnection");
  483. }
  484. catch(e){/*not supported*/}
  485. if(!ip || !type || !localip || active != "true")
  486. continue;
  487. // Save the address unless it has been saved already.
  488. var conferenceStatsTransport = this.conferenceStats.transport;
  489. if(!conferenceStatsTransport.some(function (t) { return (
  490. t.ip == ip && t.type == type && t.localip == localip
  491. )})) {
  492. conferenceStatsTransport.push(
  493. {ip: ip, type: type, localip: localip});
  494. }
  495. continue;
  496. }
  497. if(now.type == "candidatepair") {
  498. if(now.state == "succeeded")
  499. continue;
  500. var local = this.currentStatsReport[now.localCandidateId];
  501. var remote = this.currentStatsReport[now.remoteCandidateId];
  502. this.conferenceStats.transport.push({
  503. ip: remote.ipAddress + ":" + remote.portNumber,
  504. type: local.transport,
  505. localip: local.ipAddress + ":" + local.portNumber
  506. });
  507. }
  508. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  509. now.type != "inboundrtp") {
  510. continue;
  511. }
  512. var before = this.baselineStatsReport[idx];
  513. var ssrc = getStatValue(now, 'ssrc');
  514. if (!before) {
  515. logger.warn(ssrc + ' not enough data');
  516. continue;
  517. }
  518. if(!ssrc)
  519. continue;
  520. var ssrcStats
  521. = this.ssrc2stats[ssrc] || (this.ssrc2stats[ssrc] = new PeerStats());
  522. var isDownloadStream = true;
  523. var key = 'packetsReceived';
  524. var packetsNow = getStatValue(now, key);
  525. if (typeof packetsNow === 'undefined'
  526. || packetsNow === null || packetsNow === "") {
  527. isDownloadStream = false;
  528. key = 'packetsSent';
  529. packetsNow = getStatValue(now, key);
  530. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  531. logger.warn("No packetsReceived nor packetsSent stat found");
  532. continue;
  533. }
  534. }
  535. if (!packetsNow || packetsNow < 0)
  536. packetsNow = 0;
  537. var packetsBefore = getStatValue(before, key);
  538. if (!packetsBefore || packetsBefore < 0)
  539. packetsBefore = 0;
  540. var packetRate = packetsNow - packetsBefore;
  541. if (!packetRate || packetRate < 0)
  542. packetRate = 0;
  543. var currentLoss = getStatValue(now, 'packetsLost');
  544. if (!currentLoss || currentLoss < 0)
  545. currentLoss = 0;
  546. var previousLoss = getStatValue(before, 'packetsLost');
  547. if (!previousLoss || previousLoss < 0)
  548. previousLoss = 0;
  549. var lossRate = currentLoss - previousLoss;
  550. if (!lossRate || lossRate < 0)
  551. lossRate = 0;
  552. var packetsTotal = (packetRate + lossRate);
  553. ssrcStats.setSsrcLoss({
  554. packetsTotal: packetsTotal,
  555. packetsLost: lossRate,
  556. isDownloadStream: isDownloadStream
  557. });
  558. var bytesReceived = 0, bytesSent = 0;
  559. var nowBytesTransmitted = getStatValue(now, "bytesReceived");
  560. if(nowBytesTransmitted) {
  561. bytesReceived
  562. = nowBytesTransmitted - getStatValue(before, "bytesReceived");
  563. }
  564. nowBytesTransmitted = getStatValue(now, "bytesSent");
  565. if(typeof(nowBytesTransmitted) === "number" ||
  566. typeof(nowBytesTransmitted) === "string") {
  567. nowBytesTransmitted = Number(nowBytesTransmitted);
  568. if(!isNaN(nowBytesTransmitted)){
  569. byteSentStats[ssrc] = nowBytesTransmitted;
  570. if (nowBytesTransmitted > 0) {
  571. bytesSent = nowBytesTransmitted -
  572. getStatValue(before, "bytesSent");
  573. }
  574. }
  575. }
  576. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  577. if (bytesReceived <= 0 || time <= 0) {
  578. bytesReceived = 0;
  579. } else {
  580. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  581. }
  582. if (bytesSent <= 0 || time <= 0) {
  583. bytesSent = 0;
  584. } else {
  585. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  586. }
  587. //detect audio issues (receiving data but audioLevel == 0)
  588. if(bytesReceived > 10 && ssrcStats.ssrc2AudioLevel === 0) {
  589. this.eventEmitter.emit(StatisticsEvents.AUDIO_NOT_WORKING, ssrc);
  590. }
  591. ssrcStats.setSsrcBitrate({
  592. "download": bytesReceived,
  593. "upload": bytesSent
  594. });
  595. var resolution = {height: null, width: null};
  596. try {
  597. var height, width;
  598. if ((height = getStatValue(now, "googFrameHeightReceived")) &&
  599. (width = getStatValue(now, "googFrameWidthReceived"))) {
  600. resolution.height = height;
  601. resolution.width = width;
  602. }
  603. else if ((height = getStatValue(now, "googFrameHeightSent")) &&
  604. (width = getStatValue(now, "googFrameWidthSent"))) {
  605. resolution.height = height;
  606. resolution.width = width;
  607. }
  608. }
  609. catch(e){/*not supported*/}
  610. if (resolution.height && resolution.width) {
  611. ssrcStats.setSsrcResolution(resolution);
  612. } else {
  613. ssrcStats.setSsrcResolution(null);
  614. }
  615. }
  616. // process stats
  617. var totalPackets = {
  618. download: 0,
  619. upload: 0
  620. };
  621. var lostPackets = {
  622. download: 0,
  623. upload: 0
  624. };
  625. var bitrateDownload = 0;
  626. var bitrateUpload = 0;
  627. var resolutions = {};
  628. Object.keys(this.ssrc2stats).forEach(
  629. function (ssrc) {
  630. var ssrcStats = this.ssrc2stats[ssrc];
  631. // process package loss stats
  632. var ssrc2Loss = ssrcStats.ssrc2Loss;
  633. var type = ssrc2Loss.isDownloadStream ? "download" : "upload";
  634. totalPackets[type] += ssrc2Loss.packetsTotal;
  635. lostPackets[type] += ssrc2Loss.packetsLost;
  636. // process bitrate stats
  637. var ssrc2bitrate = ssrcStats.ssrc2bitrate;
  638. bitrateDownload += ssrc2bitrate.download;
  639. bitrateUpload += ssrc2bitrate.upload;
  640. ssrcStats.resetSsrcBitrate();
  641. // collect resolutions
  642. resolutions[ssrc] = ssrcStats.ssrc2resolution;
  643. },
  644. this
  645. );
  646. this.eventEmitter.emit(StatisticsEvents.BYTE_SENT_STATS, byteSentStats);
  647. this.conferenceStats.bitrate
  648. = {"upload": bitrateUpload, "download": bitrateDownload};
  649. this.conferenceStats.packetLoss = {
  650. total:
  651. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  652. totalPackets.download + totalPackets.upload),
  653. download:
  654. calculatePacketLoss(lostPackets.download, totalPackets.download),
  655. upload:
  656. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  657. };
  658. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS, {
  659. "bitrate": this.conferenceStats.bitrate,
  660. "packetLoss": this.conferenceStats.packetLoss,
  661. "bandwidth": this.conferenceStats.bandwidth,
  662. "resolution": resolutions,
  663. "transport": this.conferenceStats.transport
  664. });
  665. this.conferenceStats.transport = [];
  666. };
  667. /**
  668. * Stats processing logic.
  669. */
  670. StatsCollector.prototype.processAudioLevelReport = function () {
  671. if (!this.baselineAudioLevelsReport) {
  672. return;
  673. }
  674. var getStatValue = this._getStatValue;
  675. for (var idx in this.currentAudioLevelsReport) {
  676. var now = this.currentAudioLevelsReport[idx];
  677. //if we don't have "packetsReceived" this is local stream
  678. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  679. continue;
  680. }
  681. var before = this.baselineAudioLevelsReport[idx];
  682. var ssrc = getStatValue(now, 'ssrc');
  683. if (!before) {
  684. logger.warn(ssrc + ' not enough data');
  685. continue;
  686. }
  687. if (!ssrc) {
  688. if ((Date.now() - now.timestamp) < 3000)
  689. logger.warn("No ssrc: ");
  690. continue;
  691. }
  692. var ssrcStats
  693. = this.ssrc2stats[ssrc]
  694. || (this.ssrc2stats[ssrc] = new PeerStats());
  695. // Audio level
  696. try {
  697. var audioLevel
  698. = getStatValue(now, 'audioInputLevel')
  699. || getStatValue(now, 'audioOutputLevel');
  700. }
  701. catch(e) {/*not supported*/
  702. logger.warn("Audio Levels are not available in the statistics.");
  703. clearInterval(this.audioLevelsIntervalId);
  704. return;
  705. }
  706. if (audioLevel) {
  707. // TODO: can't find specs about what this value really is,
  708. // but it seems to vary between 0 and around 32k.
  709. audioLevel = audioLevel / 32767;
  710. ssrcStats.setSsrcAudioLevel(audioLevel);
  711. this.eventEmitter.emit(
  712. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  713. }
  714. }
  715. };