選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

RTPStatsCollector.js 25KB

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