Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

RTPStatsCollector.js 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. /* global require */
  2. /* jshint -W101 */
  3. var GlobalOnErrorHandler = require("../util/GlobalOnErrorHandler");
  4. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5. var RTCBrowserType = require("../RTC/RTCBrowserType");
  6. import * as StatisticsEvents from "../../service/statistics/Events";
  7. /* Whether we support the browser we are running into for logging statistics */
  8. var browserSupported = RTCBrowserType.isChrome() ||
  9. RTCBrowserType.isOpera() || RTCBrowserType.isFirefox() ||
  10. RTCBrowserType.isNWJS();
  11. /**
  12. * The LibJitsiMeet browser-agnostic names of the browser-specific keys reported
  13. * by RTCPeerConnection#getStats mapped by RTCBrowserType.
  14. */
  15. var KEYS_BY_BROWSER_TYPE = {};
  16. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  17. "ssrc": "ssrc",
  18. "packetsReceived": "packetsReceived",
  19. "packetsLost": "packetsLost",
  20. "packetsSent": "packetsSent",
  21. "bytesReceived": "bytesReceived",
  22. "bytesSent": "bytesSent"
  23. };
  24. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME] = {
  25. "receiveBandwidth": "googAvailableReceiveBandwidth",
  26. "sendBandwidth": "googAvailableSendBandwidth",
  27. "remoteAddress": "googRemoteAddress",
  28. "transportType": "googTransportType",
  29. "localAddress": "googLocalAddress",
  30. "activeConnection": "googActiveConnection",
  31. "ssrc": "ssrc",
  32. "packetsReceived": "packetsReceived",
  33. "packetsSent": "packetsSent",
  34. "packetsLost": "packetsLost",
  35. "bytesReceived": "bytesReceived",
  36. "bytesSent": "bytesSent",
  37. "googFrameHeightReceived": "googFrameHeightReceived",
  38. "googFrameWidthReceived": "googFrameWidthReceived",
  39. "googFrameHeightSent": "googFrameHeightSent",
  40. "googFrameWidthSent": "googFrameWidthSent",
  41. "audioInputLevel": "audioInputLevel",
  42. "audioOutputLevel": "audioOutputLevel"
  43. };
  44. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_OPERA] =
  45. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  46. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_NWJS] =
  47. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  48. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_IEXPLORER] =
  49. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  50. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_SAFARI] =
  51. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  52. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_REACT_NATIVE] =
  53. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  54. /**
  55. * Calculates packet lost percent using the number of lost packets and the
  56. * number of all packet.
  57. * @param lostPackets the number of lost packets
  58. * @param totalPackets the number of all packets.
  59. * @returns {number} packet loss percent
  60. */
  61. function calculatePacketLoss(lostPackets, totalPackets) {
  62. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  63. return 0;
  64. return Math.round((lostPackets/totalPackets)*100);
  65. }
  66. function formatAudioLevel(audioLevel) {
  67. return Math.min(Math.max(audioLevel, 0), 1);
  68. }
  69. /**
  70. * Checks whether a certain record should be included in the logged statistics.
  71. */
  72. function acceptStat(reportId, reportType, statName) {
  73. if (reportType == "googCandidatePair") {
  74. if (statName == "googChannelId")
  75. return false;
  76. } else if (reportType == "ssrc") {
  77. if (statName == "googTrackId" ||
  78. statName == "transportId" ||
  79. statName == "ssrc")
  80. return false;
  81. }
  82. return true;
  83. }
  84. /**
  85. * Checks whether a certain record should be included in the logged statistics.
  86. */
  87. function acceptReport(id, type) {
  88. if (type == "googComponent")
  89. return false;
  90. if (id.substring(0, 15) == "googCertificate" ||
  91. id.substring(0, 9) == "googTrack" ||
  92. id.substring(0, 20) == "googLibjingleSession")
  93. return false;
  94. return true;
  95. }
  96. /**
  97. * Peer statistics data holder.
  98. * @constructor
  99. */
  100. function PeerStats() {
  101. this.ssrc2Loss = {};
  102. this.ssrc2AudioLevel = {};
  103. this.ssrc2bitrate = {
  104. download: 0,
  105. upload: 0
  106. };
  107. this.ssrc2resolution = {};
  108. }
  109. /**
  110. * Sets packets loss rate for given <tt>ssrc</tt> that belong to the peer
  111. * represented by this instance.
  112. * @param lossRate new packet loss rate value to be set.
  113. */
  114. PeerStats.prototype.setSsrcLoss = function (lossRate) {
  115. this.ssrc2Loss = lossRate || {};
  116. };
  117. /**
  118. * Sets resolution that belong to the ssrc
  119. * represented by this instance.
  120. * @param resolution new resolution value to be set.
  121. */
  122. PeerStats.prototype.setSsrcResolution = function (resolution) {
  123. this.ssrc2resolution = resolution || {};
  124. };
  125. /**
  126. * Sets the bit rate for given <tt>ssrc</tt> that belong to the peer
  127. * represented by this instance.
  128. * @param bitrate new bitrate value to be set.
  129. */
  130. PeerStats.prototype.setSsrcBitrate = function (bitrate) {
  131. this.ssrc2bitrate.download += bitrate.download;
  132. this.ssrc2bitrate.upload += bitrate.upload;
  133. };
  134. /**
  135. * Resets the bit rate for given <tt>ssrc</tt> that belong to the peer
  136. * represented by this instance.
  137. */
  138. PeerStats.prototype.resetSsrcBitrate = function () {
  139. this.ssrc2bitrate.download = 0;
  140. this.ssrc2bitrate.upload = 0;
  141. };
  142. /**
  143. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  144. * the stream which belongs to the peer represented by this instance.
  145. * @param audioLevel the new audio level value to be set. Value is truncated to
  146. * fit the range from 0 to 1.
  147. */
  148. PeerStats.prototype.setSsrcAudioLevel = function (audioLevel) {
  149. // Range limit 0 - 1
  150. this.ssrc2AudioLevel = formatAudioLevel(audioLevel);
  151. };
  152. function ConferenceStats() {
  153. /**
  154. * The bandwidth
  155. * @type {{}}
  156. */
  157. this.bandwidth = {};
  158. /**
  159. * The bit rate
  160. * @type {{}}
  161. */
  162. this.bitrate = {};
  163. /**
  164. * The packet loss rate
  165. * @type {{}}
  166. */
  167. this.packetLoss = null;
  168. /**
  169. * Array with the transport information.
  170. * @type {Array}
  171. */
  172. this.transport = [];
  173. }
  174. /**
  175. * <tt>StatsCollector</tt> registers for stats updates of given
  176. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  177. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  178. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  179. * instance as an event source.
  180. *
  181. * @param peerconnection WebRTC PeerConnection object.
  182. * @param audioLevelsInterval
  183. * @param statsInterval stats refresh interval given in ms.
  184. * @param eventEmitter
  185. * @constructor
  186. */
  187. function StatsCollector(
  188. peerconnection,
  189. audioLevelsInterval,
  190. statsInterval,
  191. eventEmitter) {
  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.conferenceStats = new ConferenceStats();
  227. /**
  228. * Gather PeerConnection stats once every this many milliseconds.
  229. */
  230. this.GATHER_INTERVAL = 15000;
  231. /**
  232. * Gather stats and store them in this.statsToBeLogged.
  233. */
  234. this.gatherStatsIntervalId = null;
  235. /**
  236. * Stores the statistics which will be send to the focus to be logged.
  237. */
  238. this.statsToBeLogged = {
  239. timestamps: [],
  240. stats: {}
  241. };
  242. // Updates stats interval
  243. this.audioLevelsIntervalMilis = audioLevelsInterval;
  244. this.statsIntervalId = null;
  245. this.statsIntervalMilis = statsInterval;
  246. // Map of ssrcs to PeerStats
  247. this.ssrc2stats = {};
  248. }
  249. module.exports = StatsCollector;
  250. /**
  251. * Stops stats updates.
  252. */
  253. StatsCollector.prototype.stop = function () {
  254. if (this.audioLevelsIntervalId) {
  255. clearInterval(this.audioLevelsIntervalId);
  256. this.audioLevelsIntervalId = null;
  257. }
  258. if (this.statsIntervalId) {
  259. clearInterval(this.statsIntervalId);
  260. this.statsIntervalId = null;
  261. }
  262. if (this.gatherStatsIntervalId) {
  263. clearInterval(this.gatherStatsIntervalId);
  264. this.gatherStatsIntervalId = null;
  265. }
  266. };
  267. /**
  268. * Callback passed to <tt>getStats</tt> method.
  269. * @param error an error that occurred on <tt>getStats</tt> call.
  270. */
  271. StatsCollector.prototype.errorCallback = function (error) {
  272. GlobalOnErrorHandler.callErrorHandler(error);
  273. logger.error("Get stats error", error);
  274. this.stop();
  275. };
  276. /**
  277. * Starts stats updates.
  278. */
  279. StatsCollector.prototype.start = function (startAudioLevelStats) {
  280. var self = this;
  281. if(startAudioLevelStats) {
  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. }
  306. if (browserSupported) {
  307. this.statsIntervalId = setInterval(
  308. function () {
  309. // Interval updates
  310. self.peerconnection.getStats(
  311. function (report) {
  312. var results = null;
  313. if (!report || !report.result ||
  314. typeof report.result != 'function') {
  315. //firefox
  316. results = report;
  317. }
  318. else {
  319. //chrome
  320. results = report.result();
  321. }
  322. self.currentStatsReport = results;
  323. try {
  324. self.processStatsReport();
  325. }
  326. catch (e) {
  327. GlobalOnErrorHandler.callErrorHandler(e);
  328. logger.error("Unsupported key:" + e, e);
  329. }
  330. self.baselineStatsReport = self.currentStatsReport;
  331. },
  332. self.errorCallback
  333. );
  334. },
  335. self.statsIntervalMilis
  336. );
  337. }
  338. if (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. case RTCBrowserType.RTC_BROWSER_NWJS:
  421. // TODO What about other types of browser which are based on Chrome such
  422. // as NW.js? Every time we want to support a new type browser we have to
  423. // go and add more conditions (here and in multiple other places).
  424. // Cannot we do a feature detection instead of a browser type check? For
  425. // example, if item has a stat property of type function, then it's very
  426. // likely that whoever defined it wanted you to call it in order to
  427. // retrieve the value associated with a specific key.
  428. itemStatByKey = function (item, key) { return item.stat(key) };
  429. break;
  430. case RTCBrowserType.RTC_BROWSER_REACT_NATIVE:
  431. // The implementation provided by react-native-webrtc follows the
  432. // Objective-C WebRTC API: RTCStatsReport has a values property of type
  433. // Array in which each element is a key-value pair.
  434. itemStatByKey = function (item, key) {
  435. var value;
  436. item.values.some(function (pair) {
  437. if (pair.hasOwnProperty(key)) {
  438. value = pair[key];
  439. return true;
  440. } else {
  441. return false;
  442. }
  443. });
  444. return value;
  445. };
  446. break;
  447. default:
  448. itemStatByKey = function (item, key) { return item[key] };
  449. }
  450. // Compose the 2 functions defined above to get a function which retrieves
  451. // the value from a specific report returned by RTCPeerConnection#getStats
  452. // associated with a specific LibJitsiMeet browser-agnostic name.
  453. return function (item, name) {
  454. return itemStatByKey(item, keyFromName(name))
  455. };
  456. };
  457. /**
  458. * Stats processing logic.
  459. */
  460. StatsCollector.prototype.processStatsReport = function () {
  461. if (!this.baselineStatsReport) {
  462. return;
  463. }
  464. var getStatValue = this._getStatValue;
  465. var byteSentStats = {};
  466. for (var idx in this.currentStatsReport) {
  467. var now = this.currentStatsReport[idx];
  468. try {
  469. var receiveBandwidth = getStatValue(now, 'receiveBandwidth');
  470. var sendBandwidth = getStatValue(now, 'sendBandwidth');
  471. if (receiveBandwidth || sendBandwidth) {
  472. this.conferenceStats.bandwidth = {
  473. "download": Math.round(receiveBandwidth / 1000),
  474. "upload": Math.round(sendBandwidth / 1000)
  475. };
  476. }
  477. }
  478. catch(e){/*not supported*/}
  479. if(now.type == 'googCandidatePair')
  480. {
  481. var ip, type, localip, active;
  482. try {
  483. ip = getStatValue(now, 'remoteAddress');
  484. type = getStatValue(now, "transportType");
  485. localip = getStatValue(now, "localAddress");
  486. active = getStatValue(now, "activeConnection");
  487. }
  488. catch(e){/*not supported*/}
  489. if(!ip || !type || !localip || active != "true")
  490. continue;
  491. // Save the address unless it has been saved already.
  492. var conferenceStatsTransport = this.conferenceStats.transport;
  493. if(!conferenceStatsTransport.some(function (t) { return (
  494. t.ip == ip && t.type == type && t.localip == localip
  495. )})) {
  496. conferenceStatsTransport.push(
  497. {ip: ip, type: type, localip: localip});
  498. }
  499. continue;
  500. }
  501. if(now.type == "candidatepair") {
  502. if(now.state == "succeeded")
  503. continue;
  504. var local = this.currentStatsReport[now.localCandidateId];
  505. var remote = this.currentStatsReport[now.remoteCandidateId];
  506. this.conferenceStats.transport.push({
  507. ip: remote.ipAddress + ":" + remote.portNumber,
  508. type: local.transport,
  509. localip: local.ipAddress + ":" + local.portNumber
  510. });
  511. }
  512. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  513. now.type != "inboundrtp") {
  514. continue;
  515. }
  516. var before = this.baselineStatsReport[idx];
  517. var ssrc = getStatValue(now, 'ssrc');
  518. if (!before) {
  519. logger.warn(ssrc + ' not enough data');
  520. continue;
  521. }
  522. if(!ssrc)
  523. continue;
  524. var ssrcStats
  525. = this.ssrc2stats[ssrc] || (this.ssrc2stats[ssrc] = new PeerStats());
  526. var isDownloadStream = true;
  527. var key = 'packetsReceived';
  528. var packetsNow = getStatValue(now, key);
  529. if (typeof packetsNow === 'undefined'
  530. || packetsNow === null || packetsNow === "") {
  531. isDownloadStream = false;
  532. key = 'packetsSent';
  533. packetsNow = getStatValue(now, key);
  534. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  535. logger.warn("No packetsReceived nor packetsSent stat found");
  536. continue;
  537. }
  538. }
  539. if (!packetsNow || packetsNow < 0)
  540. packetsNow = 0;
  541. var packetsBefore = getStatValue(before, key);
  542. if (!packetsBefore || packetsBefore < 0)
  543. packetsBefore = 0;
  544. var packetRate = packetsNow - packetsBefore;
  545. if (!packetRate || packetRate < 0)
  546. packetRate = 0;
  547. var currentLoss = getStatValue(now, 'packetsLost');
  548. if (!currentLoss || currentLoss < 0)
  549. currentLoss = 0;
  550. var previousLoss = getStatValue(before, 'packetsLost');
  551. if (!previousLoss || previousLoss < 0)
  552. previousLoss = 0;
  553. var lossRate = currentLoss - previousLoss;
  554. if (!lossRate || lossRate < 0)
  555. lossRate = 0;
  556. var packetsTotal = (packetRate + lossRate);
  557. ssrcStats.setSsrcLoss({
  558. packetsTotal: packetsTotal,
  559. packetsLost: lossRate,
  560. isDownloadStream: isDownloadStream
  561. });
  562. var bytesReceived = 0, bytesSent = 0;
  563. var nowBytesTransmitted = getStatValue(now, "bytesReceived");
  564. if(nowBytesTransmitted) {
  565. bytesReceived
  566. = nowBytesTransmitted - getStatValue(before, "bytesReceived");
  567. }
  568. nowBytesTransmitted = getStatValue(now, "bytesSent");
  569. if(typeof(nowBytesTransmitted) === "number" ||
  570. typeof(nowBytesTransmitted) === "string") {
  571. nowBytesTransmitted = Number(nowBytesTransmitted);
  572. if(!isNaN(nowBytesTransmitted)){
  573. byteSentStats[ssrc] = nowBytesTransmitted;
  574. if (nowBytesTransmitted > 0) {
  575. bytesSent = nowBytesTransmitted -
  576. getStatValue(before, "bytesSent");
  577. }
  578. }
  579. }
  580. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  581. if (bytesReceived <= 0 || time <= 0) {
  582. bytesReceived = 0;
  583. } else {
  584. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  585. }
  586. if (bytesSent <= 0 || time <= 0) {
  587. bytesSent = 0;
  588. } else {
  589. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  590. }
  591. //detect audio issues (receiving data but audioLevel == 0)
  592. if(bytesReceived > 10 && ssrcStats.ssrc2AudioLevel === 0) {
  593. this.eventEmitter.emit(StatisticsEvents.AUDIO_NOT_WORKING, ssrc);
  594. }
  595. ssrcStats.setSsrcBitrate({
  596. "download": bytesReceived,
  597. "upload": bytesSent
  598. });
  599. var resolution = {height: null, width: null};
  600. try {
  601. var height, width;
  602. if ((height = getStatValue(now, "googFrameHeightReceived")) &&
  603. (width = getStatValue(now, "googFrameWidthReceived"))) {
  604. resolution.height = height;
  605. resolution.width = width;
  606. }
  607. else if ((height = getStatValue(now, "googFrameHeightSent")) &&
  608. (width = getStatValue(now, "googFrameWidthSent"))) {
  609. resolution.height = height;
  610. resolution.width = width;
  611. }
  612. }
  613. catch(e){/*not supported*/}
  614. if (resolution.height && resolution.width) {
  615. ssrcStats.setSsrcResolution(resolution);
  616. } else {
  617. ssrcStats.setSsrcResolution(null);
  618. }
  619. }
  620. // process stats
  621. var totalPackets = {
  622. download: 0,
  623. upload: 0
  624. };
  625. var lostPackets = {
  626. download: 0,
  627. upload: 0
  628. };
  629. var bitrateDownload = 0;
  630. var bitrateUpload = 0;
  631. var resolutions = {};
  632. Object.keys(this.ssrc2stats).forEach(
  633. function (ssrc) {
  634. var ssrcStats = this.ssrc2stats[ssrc];
  635. // process package loss stats
  636. var ssrc2Loss = ssrcStats.ssrc2Loss;
  637. var type = ssrc2Loss.isDownloadStream ? "download" : "upload";
  638. totalPackets[type] += ssrc2Loss.packetsTotal;
  639. lostPackets[type] += ssrc2Loss.packetsLost;
  640. // process bitrate stats
  641. var ssrc2bitrate = ssrcStats.ssrc2bitrate;
  642. bitrateDownload += ssrc2bitrate.download;
  643. bitrateUpload += ssrc2bitrate.upload;
  644. ssrcStats.resetSsrcBitrate();
  645. // collect resolutions
  646. resolutions[ssrc] = ssrcStats.ssrc2resolution;
  647. },
  648. this
  649. );
  650. this.eventEmitter.emit(StatisticsEvents.BYTE_SENT_STATS, byteSentStats);
  651. this.conferenceStats.bitrate
  652. = {"upload": bitrateUpload, "download": bitrateDownload};
  653. this.conferenceStats.packetLoss = {
  654. total:
  655. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  656. totalPackets.download + totalPackets.upload),
  657. download:
  658. calculatePacketLoss(lostPackets.download, totalPackets.download),
  659. upload:
  660. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  661. };
  662. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS, {
  663. "bandwidth": this.conferenceStats.bandwidth,
  664. "bitrate": this.conferenceStats.bitrate,
  665. "packetLoss": this.conferenceStats.packetLoss,
  666. "resolution": resolutions,
  667. "transport": this.conferenceStats.transport
  668. });
  669. this.conferenceStats.transport = [];
  670. };
  671. /**
  672. * Stats processing logic.
  673. */
  674. StatsCollector.prototype.processAudioLevelReport = function () {
  675. if (!this.baselineAudioLevelsReport) {
  676. return;
  677. }
  678. var getStatValue = this._getStatValue;
  679. for (var idx in this.currentAudioLevelsReport) {
  680. var now = this.currentAudioLevelsReport[idx];
  681. if (now.type != 'ssrc')
  682. continue;
  683. var before = this.baselineAudioLevelsReport[idx];
  684. var ssrc = getStatValue(now, 'ssrc');
  685. if (!before) {
  686. logger.warn(ssrc + ' not enough data');
  687. continue;
  688. }
  689. if (!ssrc) {
  690. if ((Date.now() - now.timestamp) < 3000)
  691. logger.warn("No ssrc: ");
  692. continue;
  693. }
  694. var ssrcStats
  695. = this.ssrc2stats[ssrc]
  696. || (this.ssrc2stats[ssrc] = new PeerStats());
  697. // Audio level
  698. try {
  699. var audioLevel
  700. = getStatValue(now, 'audioInputLevel')
  701. || getStatValue(now, 'audioOutputLevel');
  702. }
  703. catch(e) {/*not supported*/
  704. logger.warn("Audio Levels are not available in the statistics.");
  705. clearInterval(this.audioLevelsIntervalId);
  706. return;
  707. }
  708. if (audioLevel) {
  709. const isLocal = !getStatValue(now, 'packetsReceived');
  710. // TODO: Can't find specs about what this value really is, but it
  711. // seems to vary between 0 and around 32k.
  712. audioLevel = audioLevel / 32767;
  713. ssrcStats.setSsrcAudioLevel(audioLevel);
  714. this.eventEmitter.emit(
  715. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel, isLocal);
  716. }
  717. }
  718. };