您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RTPStatsCollector.js 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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();
  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. if (config.logStats && browserSupported) {
  269. this.gatherStatsIntervalId = setInterval(
  270. function () {
  271. self.peerconnection.getStats(
  272. function (report) {
  273. self.addStatsToBeLogged(report.result());
  274. },
  275. function () {
  276. }
  277. );
  278. },
  279. this.GATHER_INTERVAL
  280. );
  281. this.logStatsIntervalId = setInterval(
  282. function() { self.logStats(); },
  283. this.LOG_INTERVAL);
  284. }
  285. };
  286. /**
  287. * Checks whether a certain record should be included in the logged statistics.
  288. */
  289. function acceptStat(reportId, reportType, statName) {
  290. if (reportType == "googCandidatePair" && statName == "googChannelId")
  291. return false;
  292. if (reportType == "ssrc") {
  293. if (statName == "googTrackId" ||
  294. statName == "transportId" ||
  295. statName == "ssrc")
  296. return false;
  297. }
  298. return true;
  299. }
  300. /**
  301. * Checks whether a certain record should be included in the logged statistics.
  302. */
  303. function acceptReport(id, type) {
  304. if (id.substring(0, 15) == "googCertificate" ||
  305. id.substring(0, 9) == "googTrack" ||
  306. id.substring(0, 20) == "googLibjingleSession")
  307. return false;
  308. if (type == "googComponent")
  309. return false;
  310. return true;
  311. }
  312. /**
  313. * Converts the stats to the format used for logging, and saves the data in
  314. * this.statsToBeLogged.
  315. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  316. */
  317. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  318. var self = this;
  319. var num_records = this.statsToBeLogged.timestamps.length;
  320. this.statsToBeLogged.timestamps.push(new Date().getTime());
  321. reports.map(function (report) {
  322. if (!acceptReport(report.id, report.type))
  323. return;
  324. var stat = self.statsToBeLogged.stats[report.id];
  325. if (!stat) {
  326. stat = self.statsToBeLogged.stats[report.id] = {};
  327. }
  328. stat.type = report.type;
  329. report.names().map(function (name) {
  330. if (!acceptStat(report.id, report.type, name))
  331. return;
  332. var values = stat[name];
  333. if (!values) {
  334. values = stat[name] = [];
  335. }
  336. while (values.length < num_records) {
  337. values.push(null);
  338. }
  339. values.push(report.stat(name));
  340. });
  341. });
  342. };
  343. StatsCollector.prototype.logStats = function () {
  344. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  345. return;
  346. // Reset the stats
  347. this.statsToBeLogged.stats = {};
  348. this.statsToBeLogged.timestamps = [];
  349. };
  350. var keyMap = {};
  351. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  352. "ssrc": "ssrc",
  353. "packetsReceived": "packetsReceived",
  354. "packetsLost": "packetsLost",
  355. "packetsSent": "packetsSent",
  356. "bytesReceived": "bytesReceived",
  357. "bytesSent": "bytesSent"
  358. };
  359. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  360. "receiveBandwidth": "googAvailableReceiveBandwidth",
  361. "sendBandwidth": "googAvailableSendBandwidth",
  362. "remoteAddress": "googRemoteAddress",
  363. "transportType": "googTransportType",
  364. "localAddress": "googLocalAddress",
  365. "activeConnection": "googActiveConnection",
  366. "ssrc": "ssrc",
  367. "packetsReceived": "packetsReceived",
  368. "packetsSent": "packetsSent",
  369. "packetsLost": "packetsLost",
  370. "bytesReceived": "bytesReceived",
  371. "bytesSent": "bytesSent",
  372. "googFrameHeightReceived": "googFrameHeightReceived",
  373. "googFrameWidthReceived": "googFrameWidthReceived",
  374. "googFrameHeightSent": "googFrameHeightSent",
  375. "googFrameWidthSent": "googFrameWidthSent",
  376. "audioInputLevel": "audioInputLevel",
  377. "audioOutputLevel": "audioOutputLevel"
  378. };
  379. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  380. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  381. /**
  382. * Stats processing logic.
  383. */
  384. StatsCollector.prototype.processStatsReport = function () {
  385. if (!this.baselineStatsReport) {
  386. return;
  387. }
  388. for (var idx in this.currentStatsReport) {
  389. var now = this.currentStatsReport[idx];
  390. try {
  391. if (getStatValue(now, 'receiveBandwidth') ||
  392. getStatValue(now, 'sendBandwidth')) {
  393. PeerStats.bandwidth = {
  394. "download": Math.round(
  395. (getStatValue(now, 'receiveBandwidth')) / 1000),
  396. "upload": Math.round(
  397. (getStatValue(now, 'sendBandwidth')) / 1000)
  398. };
  399. }
  400. }
  401. catch(e){/*not supported*/}
  402. if(now.type == 'googCandidatePair')
  403. {
  404. var ip, type, localIP, active;
  405. try {
  406. ip = getStatValue(now, 'remoteAddress');
  407. type = getStatValue(now, "transportType");
  408. localIP = getStatValue(now, "localAddress");
  409. active = getStatValue(now, "activeConnection");
  410. }
  411. catch(e){/*not supported*/}
  412. if(!ip || !type || !localIP || active != "true")
  413. continue;
  414. var addressSaved = false;
  415. for(var i = 0; i < PeerStats.transport.length; i++)
  416. {
  417. if(PeerStats.transport[i].ip == ip &&
  418. PeerStats.transport[i].type == type &&
  419. PeerStats.transport[i].localip == localIP)
  420. {
  421. addressSaved = true;
  422. }
  423. }
  424. if(addressSaved)
  425. continue;
  426. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  427. continue;
  428. }
  429. if(now.type == "candidatepair")
  430. {
  431. if(now.state == "succeeded")
  432. continue;
  433. var local = this.currentStatsReport[now.localCandidateId];
  434. var remote = this.currentStatsReport[now.remoteCandidateId];
  435. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  436. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  437. }
  438. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  439. now.type != "inboundrtp") {
  440. continue;
  441. }
  442. var before = this.baselineStatsReport[idx];
  443. if (!before) {
  444. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  445. continue;
  446. }
  447. var ssrc = getStatValue(now, 'ssrc');
  448. if(!ssrc)
  449. continue;
  450. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  451. if (!jid && (Date.now() - now.timestamp) < 3000) {
  452. console.warn("No jid for ssrc: " + ssrc);
  453. continue;
  454. }
  455. var jidStats = this.jid2stats[jid];
  456. if (!jidStats) {
  457. jidStats = new PeerStats();
  458. this.jid2stats[jid] = jidStats;
  459. }
  460. var isDownloadStream = true;
  461. var key = 'packetsReceived';
  462. if (!getStatValue(now, key))
  463. {
  464. isDownloadStream = false;
  465. key = 'packetsSent';
  466. if (!getStatValue(now, key))
  467. {
  468. console.warn("No packetsReceived nor packetSent stat found");
  469. continue;
  470. }
  471. }
  472. var packetsNow = getStatValue(now, key);
  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. {
  498. bytesReceived = getStatValue(now, "bytesReceived") -
  499. getStatValue(before, "bytesReceived");
  500. }
  501. if(getStatValue(now, "bytesSent"))
  502. {
  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. {
  509. bytesReceived = 0;
  510. }
  511. else
  512. {
  513. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  514. }
  515. if(bytesSent <= 0 || time <= 0)
  516. {
  517. bytesSent = 0;
  518. }
  519. else
  520. {
  521. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  522. }
  523. jidStats.setSsrcBitrate(ssrc, {
  524. "download": bytesReceived,
  525. "upload": bytesSent});
  526. var resolution = {height: null, width: null};
  527. try {
  528. if (getStatValue(now, "googFrameHeightReceived") &&
  529. getStatValue(now, "googFrameWidthReceived")) {
  530. resolution.height = getStatValue(now, "googFrameHeightReceived");
  531. resolution.width = getStatValue(now, "googFrameWidthReceived");
  532. }
  533. else if (getStatValue(now, "googFrameHeightSent") &&
  534. getStatValue(now, "googFrameWidthSent")) {
  535. resolution.height = getStatValue(now, "googFrameHeightSent");
  536. resolution.width = getStatValue(now, "googFrameWidthSent");
  537. }
  538. }
  539. catch(e){/*not supported*/}
  540. if(resolution.height && resolution.width)
  541. {
  542. jidStats.setSsrcResolution(ssrc, resolution);
  543. }
  544. else
  545. {
  546. jidStats.setSsrcResolution(ssrc, null);
  547. }
  548. }
  549. var self = this;
  550. // Jid stats
  551. var totalPackets = {download: 0, upload: 0};
  552. var lostPackets = {download: 0, upload: 0};
  553. var bitrateDownload = 0;
  554. var bitrateUpload = 0;
  555. var resolutions = {};
  556. Object.keys(this.jid2stats).forEach(
  557. function (jid)
  558. {
  559. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  560. function (ssrc)
  561. {
  562. var type = "upload";
  563. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  564. type = "download";
  565. totalPackets[type] +=
  566. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  567. lostPackets[type] +=
  568. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  569. }
  570. );
  571. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  572. function (ssrc) {
  573. bitrateDownload +=
  574. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  575. bitrateUpload +=
  576. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  577. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  578. }
  579. );
  580. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  581. }
  582. );
  583. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  584. PeerStats.packetLoss = {
  585. total:
  586. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  587. totalPackets.download + totalPackets.upload),
  588. download:
  589. calculatePacketLoss(lostPackets.download, totalPackets.download),
  590. upload:
  591. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  592. };
  593. this.eventEmitter.emit("statistics.connectionstats",
  594. {
  595. "bitrate": PeerStats.bitrate,
  596. "packetLoss": PeerStats.packetLoss,
  597. "bandwidth": PeerStats.bandwidth,
  598. "resolution": resolutions,
  599. "transport": PeerStats.transport
  600. });
  601. PeerStats.transport = [];
  602. };
  603. /**
  604. * Stats processing logic.
  605. */
  606. StatsCollector.prototype.processAudioLevelReport = function () {
  607. if (!this.baselineAudioLevelsReport) {
  608. return;
  609. }
  610. for (var idx in this.currentAudioLevelsReport) {
  611. var now = this.currentAudioLevelsReport[idx];
  612. if (now.type != 'ssrc') {
  613. continue;
  614. }
  615. var before = this.baselineAudioLevelsReport[idx];
  616. if (!before) {
  617. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  618. continue;
  619. }
  620. var ssrc = getStatValue(now, 'ssrc');
  621. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  622. if (!jid) {
  623. if((Date.now() - now.timestamp) < 3000)
  624. console.warn("No jid for ssrc: " + ssrc);
  625. continue;
  626. }
  627. var jidStats = this.jid2stats[jid];
  628. if (!jidStats) {
  629. jidStats = new PeerStats();
  630. this.jid2stats[jid] = jidStats;
  631. }
  632. // Audio level
  633. var audioLevel = null;
  634. try {
  635. audioLevel = getStatValue(now, 'audioInputLevel');
  636. if (!audioLevel)
  637. audioLevel = getStatValue(now, 'audioOutputLevel');
  638. }
  639. catch(e) {/*not supported*/
  640. console.warn("Audio Levels are not available in the statistics.");
  641. clearInterval(this.audioLevelsIntervalId);
  642. return;
  643. }
  644. if (audioLevel) {
  645. // TODO: can't find specs about what this value really is,
  646. // but it seems to vary between 0 and around 32k.
  647. audioLevel = audioLevel / 32767;
  648. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  649. if(jid != APP.xmpp.myJid())
  650. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  651. }
  652. }
  653. };