Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

RTPStatsCollector.js 26KB

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