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

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