You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RTPStatsCollector.js 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. /* global require, ssrc2jid */
  2. /* jshint -W117 */
  3. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5. var StatisticsEvents = require("../../service/statistics/Events");
  6. /* Whether we support the browser we are running into for logging statistics */
  7. var browserSupported = RTCBrowserType.isChrome() ||
  8. RTCBrowserType.isOpera();
  9. var keyMap = {};
  10. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  11. "ssrc": "ssrc",
  12. "packetsReceived": "packetsReceived",
  13. "packetsLost": "packetsLost",
  14. "packetsSent": "packetsSent",
  15. "bytesReceived": "bytesReceived",
  16. "bytesSent": "bytesSent"
  17. };
  18. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  19. "receiveBandwidth": "googAvailableReceiveBandwidth",
  20. "sendBandwidth": "googAvailableSendBandwidth",
  21. "remoteAddress": "googRemoteAddress",
  22. "transportType": "googTransportType",
  23. "localAddress": "googLocalAddress",
  24. "activeConnection": "googActiveConnection",
  25. "ssrc": "ssrc",
  26. "packetsReceived": "packetsReceived",
  27. "packetsSent": "packetsSent",
  28. "packetsLost": "packetsLost",
  29. "bytesReceived": "bytesReceived",
  30. "bytesSent": "bytesSent",
  31. "googFrameHeightReceived": "googFrameHeightReceived",
  32. "googFrameWidthReceived": "googFrameWidthReceived",
  33. "googFrameHeightSent": "googFrameHeightSent",
  34. "googFrameWidthSent": "googFrameWidthSent",
  35. "audioInputLevel": "audioInputLevel",
  36. "audioOutputLevel": "audioOutputLevel"
  37. };
  38. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  39. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  40. /**
  41. * Calculates packet lost percent using the number of lost packets and the
  42. * number of all packet.
  43. * @param lostPackets the number of lost packets
  44. * @param totalPackets the number of all packets.
  45. * @returns {number} packet loss percent
  46. */
  47. function calculatePacketLoss(lostPackets, totalPackets) {
  48. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  49. return 0;
  50. return Math.round((lostPackets/totalPackets)*100);
  51. }
  52. function getStatValue(item, name) {
  53. var browserType = RTCBrowserType.getBrowserType();
  54. if (!keyMap[browserType][name])
  55. throw "The property isn't supported!";
  56. var key = keyMap[browserType][name];
  57. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  58. item.stat(key) : item[key];
  59. }
  60. function formatAudioLevel(audioLevel) {
  61. return Math.min(Math.max(audioLevel, 0), 1);
  62. }
  63. /**
  64. * Checks whether a certain record should be included in the logged statistics.
  65. */
  66. function acceptStat(reportId, reportType, statName) {
  67. if (reportType == "googCandidatePair" && statName == "googChannelId")
  68. return false;
  69. if (reportType == "ssrc") {
  70. if (statName == "googTrackId" ||
  71. statName == "transportId" ||
  72. statName == "ssrc")
  73. return false;
  74. }
  75. return true;
  76. }
  77. /**
  78. * Checks whether a certain record should be included in the logged statistics.
  79. */
  80. function acceptReport(id, type) {
  81. if (id.substring(0, 15) == "googCertificate" ||
  82. id.substring(0, 9) == "googTrack" ||
  83. id.substring(0, 20) == "googLibjingleSession")
  84. return false;
  85. if (type == "googComponent")
  86. return false;
  87. return true;
  88. }
  89. /**
  90. * Peer statistics data holder.
  91. * @constructor
  92. */
  93. function PeerStats()
  94. {
  95. this.ssrc2Loss = {};
  96. this.ssrc2AudioLevel = {};
  97. this.ssrc2bitrate = {};
  98. this.ssrc2resolution = {};
  99. }
  100. /**
  101. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  102. * represented by this instance.
  103. * @param lossRate new packet loss rate value to be set.
  104. */
  105. PeerStats.prototype.setSsrcLoss = function (lossRate)
  106. {
  107. this.ssrc2Loss = lossRate;
  108. };
  109. /**
  110. * Sets resolution that belong to the ssrc
  111. * represented by this instance.
  112. * @param resolution new resolution value to be set.
  113. */
  114. PeerStats.prototype.setSsrcResolution = function (resolution)
  115. {
  116. if(resolution === null && this.ssrc2resolution[ssrc])
  117. {
  118. delete this.ssrc2resolution[ssrc];
  119. }
  120. else if(resolution !== null)
  121. this.ssrc2resolution[ssrc] = resolution;
  122. };
  123. /**
  124. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  125. * represented by this instance.
  126. * @param ssrc audio or video RTP stream SSRC.
  127. * @param bitrate new bitrate value to be set.
  128. */
  129. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  130. {
  131. if(this.ssrc2bitrate[ssrc])
  132. {
  133. this.ssrc2bitrate[ssrc].download += bitrate.download;
  134. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  135. }
  136. else {
  137. this.ssrc2bitrate[ssrc] = bitrate;
  138. }
  139. };
  140. /**
  141. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  142. * the stream which belongs to the peer represented by this instance.
  143. * @param ssrc RTP stream SSRC for which current audio level value will be
  144. * updated.
  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 (ssrc, audioLevel)
  149. {
  150. // Range limit 0 - 1
  151. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  152. };
  153. function ConferenceStats() {
  154. /**
  155. * The bandwidth
  156. * @type {{}}
  157. */
  158. this.bandwidth = {};
  159. /**
  160. * The bit rate
  161. * @type {{}}
  162. */
  163. this.bitrate = {};
  164. /**
  165. * The packet loss rate
  166. * @type {{}}
  167. */
  168. this.packetLoss = null;
  169. /**
  170. * Array with the transport information.
  171. * @type {Array}
  172. */
  173. this.transport = [];
  174. }
  175. /**
  176. * <tt>StatsCollector</tt> registers for stats updates of given
  177. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  178. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  179. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  180. * instance as an event source.
  181. *
  182. * @param peerconnection webRTC peer connection object.
  183. * @param interval stats refresh interval given in ms.
  184. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  185. * called on stats update.
  186. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  187. * @constructor
  188. */
  189. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  190. {
  191. this.peerconnection = peerconnection;
  192. this.baselineAudioLevelsReport = null;
  193. this.currentAudioLevelsReport = null;
  194. this.currentStatsReport = null;
  195. this.baselineStatsReport = null;
  196. this.audioLevelsIntervalId = null;
  197. this.eventEmitter = eventEmitter;
  198. this.config = config || {};
  199. this.conferenceStats = new ConferenceStats();
  200. /**
  201. * Gather PeerConnection stats once every this many milliseconds.
  202. */
  203. this.GATHER_INTERVAL = 15000;
  204. /**
  205. * Log stats via the focus once every this many milliseconds.
  206. */
  207. this.LOG_INTERVAL = 60000;
  208. /**
  209. * Gather stats and store them in this.statsToBeLogged.
  210. */
  211. this.gatherStatsIntervalId = null;
  212. /**
  213. * Send the stats already saved in this.statsToBeLogged to be logged via
  214. * the focus.
  215. */
  216. this.logStatsIntervalId = null;
  217. /**
  218. * Stores the statistics which will be send to the focus to be logged.
  219. */
  220. this.statsToBeLogged =
  221. {
  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 PeerStats
  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. {
  243. clearInterval(this.statsIntervalId);
  244. this.statsIntervalId = null;
  245. }
  246. if(this.logStatsIntervalId)
  247. {
  248. clearInterval(this.logStatsIntervalId);
  249. this.logStatsIntervalId = null;
  250. }
  251. if(this.gatherStatsIntervalId)
  252. {
  253. clearInterval(this.gatherStatsIntervalId);
  254. this.gatherStatsIntervalId = null;
  255. }
  256. };
  257. /**
  258. * Callback passed to <tt>getStats</tt> method.
  259. * @param error an error that occurred on <tt>getStats</tt> call.
  260. */
  261. StatsCollector.prototype.errorCallback = function (error)
  262. {
  263. logger.error("Get stats error", error);
  264. this.stop();
  265. };
  266. /**
  267. * Starts stats updates.
  268. */
  269. StatsCollector.prototype.start = function ()
  270. {
  271. var self = this;
  272. this.audioLevelsIntervalId = setInterval(
  273. function () {
  274. // Interval updates
  275. self.peerconnection.getStats(
  276. function (report) {
  277. var results = null;
  278. if (!report || !report.result ||
  279. typeof report.result != 'function') {
  280. results = report;
  281. }
  282. else {
  283. results = report.result();
  284. }
  285. //logger.error("Got interval report", results);
  286. self.currentAudioLevelsReport = results;
  287. self.processAudioLevelReport();
  288. self.baselineAudioLevelsReport =
  289. self.currentAudioLevelsReport;
  290. },
  291. self.errorCallback
  292. );
  293. },
  294. self.audioLevelsIntervalMilis
  295. );
  296. // if (!this.config.disableStats && browserSupported) {
  297. // this.statsIntervalId = setInterval(
  298. // function () {
  299. // // Interval updates
  300. // self.peerconnection.getStats(
  301. // function (report) {
  302. // var results = null;
  303. // if (!report || !report.result ||
  304. // typeof report.result != 'function') {
  305. // //firefox
  306. // results = report;
  307. // }
  308. // else {
  309. // //chrome
  310. // results = report.result();
  311. // }
  312. // //logger.error("Got interval report", results);
  313. // self.currentStatsReport = results;
  314. // try {
  315. // self.processStatsReport();
  316. // }
  317. // catch (e) {
  318. // logger.error("Unsupported key:" + e, e);
  319. // }
  320. //
  321. // self.baselineStatsReport = self.currentStatsReport;
  322. // },
  323. // self.errorCallback
  324. // );
  325. // },
  326. // self.statsIntervalMilis
  327. // );
  328. // }
  329. //
  330. // if (this.config.logStats && browserSupported) {
  331. // this.gatherStatsIntervalId = setInterval(
  332. // function () {
  333. // self.peerconnection.getStats(
  334. // function (report) {
  335. // self.addStatsToBeLogged(report.result());
  336. // },
  337. // function () {
  338. // }
  339. // );
  340. // },
  341. // this.GATHER_INTERVAL
  342. // );
  343. //
  344. // this.logStatsIntervalId = setInterval(
  345. // function() { self.logStats(); },
  346. // this.LOG_INTERVAL);
  347. // }
  348. };
  349. /**
  350. * Converts the stats to the format used for logging, and saves the data in
  351. * this.statsToBeLogged.
  352. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  353. */
  354. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  355. var self = this;
  356. var num_records = this.statsToBeLogged.timestamps.length;
  357. this.statsToBeLogged.timestamps.push(new Date().getTime());
  358. reports.map(function (report) {
  359. if (!acceptReport(report.id, report.type))
  360. return;
  361. var stat = self.statsToBeLogged.stats[report.id];
  362. if (!stat) {
  363. stat = self.statsToBeLogged.stats[report.id] = {};
  364. }
  365. stat.type = report.type;
  366. report.names().map(function (name) {
  367. if (!acceptStat(report.id, report.type, name))
  368. return;
  369. var values = stat[name];
  370. if (!values) {
  371. values = stat[name] = [];
  372. }
  373. while (values.length < num_records) {
  374. values.push(null);
  375. }
  376. values.push(report.stat(name));
  377. });
  378. });
  379. };
  380. //FIXME:
  381. //StatsCollector.prototype.logStats = function () {
  382. //
  383. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  384. // return;
  385. // // Reset the stats
  386. // this.statsToBeLogged.stats = {};
  387. // this.statsToBeLogged.timestamps = [];
  388. //};
  389. /**
  390. * Stats processing logic.
  391. */
  392. StatsCollector.prototype.processStatsReport = function () {
  393. if (!this.baselineStatsReport) {
  394. return;
  395. }
  396. for (var idx in this.currentStatsReport) {
  397. var now = this.currentStatsReport[idx];
  398. try {
  399. if (getStatValue(now, 'receiveBandwidth') ||
  400. getStatValue(now, 'sendBandwidth')) {
  401. this.conferenceStats.bandwidth = {
  402. "download": Math.round(
  403. (getStatValue(now, 'receiveBandwidth')) / 1000),
  404. "upload": Math.round(
  405. (getStatValue(now, 'sendBandwidth')) / 1000)
  406. };
  407. }
  408. }
  409. catch(e){/*not supported*/}
  410. if(now.type == 'googCandidatePair')
  411. {
  412. var ip, type, localIP, active;
  413. try {
  414. ip = getStatValue(now, 'remoteAddress');
  415. type = getStatValue(now, "transportType");
  416. localIP = getStatValue(now, "localAddress");
  417. active = getStatValue(now, "activeConnection");
  418. }
  419. catch(e){/*not supported*/}
  420. if(!ip || !type || !localIP || active != "true")
  421. continue;
  422. var addressSaved = false;
  423. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  424. {
  425. if(this.conferenceStats.transport[i].ip == ip &&
  426. this.conferenceStats.transport[i].type == type &&
  427. this.conferenceStats.transport[i].localip == localIP)
  428. {
  429. addressSaved = true;
  430. }
  431. }
  432. if(addressSaved)
  433. continue;
  434. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  435. continue;
  436. }
  437. if(now.type == "candidatepair")
  438. {
  439. if(now.state == "succeeded")
  440. continue;
  441. var local = this.currentStatsReport[now.localCandidateId];
  442. var remote = this.currentStatsReport[now.remoteCandidateId];
  443. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  444. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  445. }
  446. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  447. now.type != "inboundrtp") {
  448. continue;
  449. }
  450. var before = this.baselineStatsReport[idx];
  451. if (!before) {
  452. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  453. continue;
  454. }
  455. var ssrc = getStatValue(now, 'ssrc');
  456. if(!ssrc)
  457. continue;
  458. var ssrcStats = this.ssrc2stats[ssrc];
  459. if (!ssrcStats) {
  460. ssrcStats = new PeerStats();
  461. this.ssrc2stats[ssrc] = ssrcStats;
  462. }
  463. var isDownloadStream = true;
  464. var key = 'packetsReceived';
  465. var packetsNow = getStatValue(now, key);
  466. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  467. isDownloadStream = false;
  468. key = 'packetsSent';
  469. packetsNow = getStatValue(now, key);
  470. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  471. console.warn("No packetsReceived nor packetsSent stat found");
  472. continue;
  473. }
  474. }
  475. if (!packetsNow || packetsNow < 0)
  476. packetsNow = 0;
  477. var packetsBefore = getStatValue(before, key);
  478. if (!packetsBefore || packetsBefore < 0)
  479. packetsBefore = 0;
  480. var packetRate = packetsNow - packetsBefore;
  481. if (!packetRate || packetRate < 0)
  482. packetRate = 0;
  483. var currentLoss = getStatValue(now, 'packetsLost');
  484. if (!currentLoss || currentLoss < 0)
  485. currentLoss = 0;
  486. var previousLoss = getStatValue(before, 'packetsLost');
  487. if (!previousLoss || previousLoss < 0)
  488. previousLoss = 0;
  489. var lossRate = currentLoss - previousLoss;
  490. if (!lossRate || lossRate < 0)
  491. lossRate = 0;
  492. var packetsTotal = (packetRate + lossRate);
  493. ssrcStats.setSsrcLoss(ssrc,
  494. {"packetsTotal": packetsTotal,
  495. "packetsLost": lossRate,
  496. "isDownloadStream": isDownloadStream});
  497. var bytesReceived = 0, bytesSent = 0;
  498. if(getStatValue(now, "bytesReceived")) {
  499. bytesReceived = getStatValue(now, "bytesReceived") -
  500. getStatValue(before, "bytesReceived");
  501. }
  502. if (getStatValue(now, "bytesSent")) {
  503. bytesSent = getStatValue(now, "bytesSent") -
  504. getStatValue(before, "bytesSent");
  505. }
  506. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  507. if (bytesReceived <= 0 || time <= 0) {
  508. bytesReceived = 0;
  509. } else {
  510. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  511. }
  512. if (bytesSent <= 0 || time <= 0) {
  513. bytesSent = 0;
  514. } else {
  515. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  516. }
  517. ssrcStats.setSsrcBitrate(ssrc, {
  518. "download": bytesReceived,
  519. "upload": bytesSent});
  520. var resolution = {height: null, width: null};
  521. try {
  522. if (getStatValue(now, "googFrameHeightReceived") &&
  523. getStatValue(now, "googFrameWidthReceived")) {
  524. resolution.height =
  525. getStatValue(now, "googFrameHeightReceived");
  526. resolution.width = getStatValue(now, "googFrameWidthReceived");
  527. }
  528. else if (getStatValue(now, "googFrameHeightSent") &&
  529. getStatValue(now, "googFrameWidthSent")) {
  530. resolution.height = getStatValue(now, "googFrameHeightSent");
  531. resolution.width = getStatValue(now, "googFrameWidthSent");
  532. }
  533. }
  534. catch(e){/*not supported*/}
  535. if (resolution.height && resolution.width) {
  536. ssrcStats.setSsrcResolution(ssrc, resolution);
  537. } else {
  538. ssrcStats.setSsrcResolution(ssrc, null);
  539. }
  540. }
  541. var self = this;
  542. // Jid stats
  543. var totalPackets = {download: 0, upload: 0};
  544. var lostPackets = {download: 0, upload: 0};
  545. var bitrateDownload = 0;
  546. var bitrateUpload = 0;
  547. var resolutions = {};
  548. Object.keys(this.ssrc2stats).forEach(
  549. function (jid) {
  550. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  551. function (ssrc) {
  552. var type = "upload";
  553. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  554. type = "download";
  555. totalPackets[type] +=
  556. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  557. lostPackets[type] +=
  558. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  559. }
  560. );
  561. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  562. function (ssrc) {
  563. bitrateDownload +=
  564. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  565. bitrateUpload +=
  566. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  567. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  568. }
  569. );
  570. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  571. }
  572. );
  573. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  574. this.conferenceStats.packetLoss = {
  575. total:
  576. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  577. totalPackets.download + totalPackets.upload),
  578. download:
  579. calculatePacketLoss(lostPackets.download, totalPackets.download),
  580. upload:
  581. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  582. };
  583. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  584. {
  585. "bitrate": this.conferenceStats.bitrate,
  586. "packetLoss": this.conferenceStats.packetLoss,
  587. "bandwidth": this.conferenceStats.bandwidth,
  588. "resolution": resolutions,
  589. "transport": this.conferenceStats.transport
  590. });
  591. this.conferenceStats.transport = [];
  592. };
  593. /**
  594. * Stats processing logic.
  595. */
  596. StatsCollector.prototype.processAudioLevelReport = function () {
  597. if (!this.baselineAudioLevelsReport) {
  598. return;
  599. }
  600. for (var idx in this.currentAudioLevelsReport) {
  601. var now = this.currentAudioLevelsReport[idx];
  602. //if we don't have "packetsReceived" this is local stream
  603. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  604. continue;
  605. }
  606. var before = this.baselineAudioLevelsReport[idx];
  607. if (!before) {
  608. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  609. continue;
  610. }
  611. var ssrc = getStatValue(now, 'ssrc');
  612. if (!ssrc) {
  613. if((Date.now() - now.timestamp) < 3000)
  614. logger.warn("No ssrc: ");
  615. continue;
  616. }
  617. var ssrcStats = this.ssrc2stats[ssrc];
  618. if (!ssrcStats) {
  619. ssrcStats = new PeerStats();
  620. this.ssrc2stats[ssrc] = ssrcStats;
  621. }
  622. // Audio level
  623. var audioLevel = null;
  624. try {
  625. audioLevel = getStatValue(now, 'audioInputLevel');
  626. if (!audioLevel)
  627. audioLevel = getStatValue(now, 'audioOutputLevel');
  628. }
  629. catch(e) {/*not supported*/
  630. logger.warn("Audio Levels are not available in the statistics.");
  631. clearInterval(this.audioLevelsIntervalId);
  632. return;
  633. }
  634. if (audioLevel) {
  635. // TODO: can't find specs about what this value really is,
  636. // but it seems to vary between 0 and around 32k.
  637. audioLevel = audioLevel / 32767;
  638. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  639. this.eventEmitter.emit(
  640. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  641. }
  642. }
  643. };