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

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