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

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