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 25KB

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