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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. /* global require */
  2. var GlobalOnErrorHandler = require("../util/GlobalOnErrorHandler");
  3. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5. import * as StatisticsEvents from "../../service/statistics/Events";
  6. /* Whether we support the browser we are running into for logging statistics */
  7. var browserSupported = RTCBrowserType.isChrome() ||
  8. RTCBrowserType.isOpera() || RTCBrowserType.isFirefox() ||
  9. RTCBrowserType.isNWJS() || RTCBrowserType.isElectron();
  10. /**
  11. * The LibJitsiMeet browser-agnostic names of the browser-specific keys reported
  12. * by RTCPeerConnection#getStats mapped by RTCBrowserType.
  13. */
  14. var KEYS_BY_BROWSER_TYPE = {};
  15. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  16. "ssrc": "ssrc",
  17. "packetsReceived": "packetsReceived",
  18. "packetsLost": "packetsLost",
  19. "packetsSent": "packetsSent",
  20. "bytesReceived": "bytesReceived",
  21. "bytesSent": "bytesSent"
  22. };
  23. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME] = {
  24. "receiveBandwidth": "googAvailableReceiveBandwidth",
  25. "sendBandwidth": "googAvailableSendBandwidth",
  26. "remoteAddress": "googRemoteAddress",
  27. "transportType": "googTransportType",
  28. "localAddress": "googLocalAddress",
  29. "activeConnection": "googActiveConnection",
  30. "ssrc": "ssrc",
  31. "packetsReceived": "packetsReceived",
  32. "packetsSent": "packetsSent",
  33. "packetsLost": "packetsLost",
  34. "bytesReceived": "bytesReceived",
  35. "bytesSent": "bytesSent",
  36. "googFrameHeightReceived": "googFrameHeightReceived",
  37. "googFrameWidthReceived": "googFrameWidthReceived",
  38. "googFrameHeightSent": "googFrameHeightSent",
  39. "googFrameWidthSent": "googFrameWidthSent",
  40. "audioInputLevel": "audioInputLevel",
  41. "audioOutputLevel": "audioOutputLevel"
  42. };
  43. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_OPERA] =
  44. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  45. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_NWJS] =
  46. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  47. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_ELECTRON] =
  48. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  49. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_IEXPLORER] =
  50. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  51. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_SAFARI] =
  52. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  53. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_REACT_NATIVE] =
  54. KEYS_BY_BROWSER_TYPE[RTCBrowserType.RTC_BROWSER_CHROME];
  55. /**
  56. * Calculates packet lost percent using the number of lost packets and the
  57. * number of all packet.
  58. * @param lostPackets the number of lost packets
  59. * @param totalPackets the number of all packets.
  60. * @returns {number} packet loss percent
  61. */
  62. function calculatePacketLoss(lostPackets, totalPackets) {
  63. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  64. return 0;
  65. return Math.round((lostPackets/totalPackets)*100);
  66. }
  67. /**
  68. * Holds "statistics" for a single SSRC.
  69. * @constructor
  70. */
  71. function SsrcStats() {
  72. this.loss = {};
  73. this.bitrate = {
  74. download: 0,
  75. upload: 0
  76. };
  77. this.resolution = {};
  78. }
  79. /**
  80. * Sets the "loss" object.
  81. * @param loss the value to set.
  82. */
  83. SsrcStats.prototype.setLoss = function (loss) {
  84. this.loss = loss || {};
  85. };
  86. /**
  87. * Sets resolution that belong to the ssrc represented by this instance.
  88. * @param resolution new resolution value to be set.
  89. */
  90. SsrcStats.prototype.setResolution = function (resolution) {
  91. this.resolution = resolution || {};
  92. };
  93. /**
  94. * Adds the "download" and "upload" fields from the "bitrate" parameter to
  95. * the respective fields of the "bitrate" field of this object.
  96. * @param bitrate an object holding the values to add.
  97. */
  98. SsrcStats.prototype.addBitrate = function (bitrate) {
  99. this.bitrate.download += bitrate.download;
  100. this.bitrate.upload += bitrate.upload;
  101. };
  102. /**
  103. * Resets the bit rate for given <tt>ssrc</tt> that belong to the peer
  104. * represented by this instance.
  105. */
  106. SsrcStats.prototype.resetBitrate = function () {
  107. this.bitrate.download = 0;
  108. this.bitrate.upload = 0;
  109. };
  110. function ConferenceStats() {
  111. /**
  112. * The bandwidth
  113. * @type {{}}
  114. */
  115. this.bandwidth = {};
  116. /**
  117. * The bit rate
  118. * @type {{}}
  119. */
  120. this.bitrate = {};
  121. /**
  122. * The packet loss rate
  123. * @type {{}}
  124. */
  125. this.packetLoss = null;
  126. /**
  127. * Array with the transport information.
  128. * @type {Array}
  129. */
  130. this.transport = [];
  131. }
  132. /**
  133. * <tt>StatsCollector</tt> registers for stats updates of given
  134. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  135. * stats are extracted and put in {@link SsrcStats} objects. Once the processing
  136. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  137. * instance as an event source.
  138. *
  139. * @param peerconnection WebRTC PeerConnection object.
  140. * @param audioLevelsInterval
  141. * @param statsInterval stats refresh interval given in ms.
  142. * @param eventEmitter
  143. * @constructor
  144. */
  145. function StatsCollector(
  146. peerconnection,
  147. audioLevelsInterval,
  148. statsInterval,
  149. eventEmitter) {
  150. // StatsCollector depends entirely on the format of the reports returned by
  151. // RTCPeerConnection#getStats. Given that the value of
  152. // RTCBrowserType#getBrowserType() is very unlikely to change at runtime, it
  153. // makes sense to discover whether StatsCollector supports the executing
  154. // browser as soon as possible. Otherwise, (1) getStatValue would have to
  155. // needlessly check a "static" condition multiple times very very often and
  156. // (2) the lack of support for the executing browser would be discovered and
  157. // reported multiple times very very often too late in the execution in some
  158. // totally unrelated callback.
  159. /**
  160. * The RTCBrowserType supported by this StatsCollector. In other words, the
  161. * RTCBrowserType of the browser which initialized this StatsCollector
  162. * instance.
  163. * @private
  164. */
  165. this._browserType = RTCBrowserType.getBrowserType();
  166. var keys = KEYS_BY_BROWSER_TYPE[this._browserType];
  167. if (!keys)
  168. throw "The browser type '" + this._browserType + "' isn't supported!";
  169. /**
  170. * The function which is to be used to retrieve the value associated in a
  171. * report returned by RTCPeerConnection#getStats with a LibJitsiMeet
  172. * browser-agnostic name/key.
  173. * @function
  174. * @private
  175. */
  176. this._getStatValue = this._defineGetStatValueMethod(keys);
  177. this.peerconnection = peerconnection;
  178. this.baselineAudioLevelsReport = null;
  179. this.currentAudioLevelsReport = null;
  180. this.currentStatsReport = null;
  181. this.previousStatsReport = null;
  182. this.audioLevelsIntervalId = null;
  183. this.eventEmitter = eventEmitter;
  184. this.conferenceStats = new ConferenceStats();
  185. // Updates stats interval
  186. this.audioLevelsIntervalMilis = audioLevelsInterval;
  187. this.statsIntervalId = null;
  188. this.statsIntervalMilis = statsInterval;
  189. // Map of ssrcs to SsrcStats
  190. this.ssrc2stats = {};
  191. }
  192. module.exports = StatsCollector;
  193. /**
  194. * Stops stats updates.
  195. */
  196. StatsCollector.prototype.stop = function () {
  197. if (this.audioLevelsIntervalId) {
  198. clearInterval(this.audioLevelsIntervalId);
  199. this.audioLevelsIntervalId = null;
  200. }
  201. if (this.statsIntervalId) {
  202. clearInterval(this.statsIntervalId);
  203. this.statsIntervalId = null;
  204. }
  205. };
  206. /**
  207. * Callback passed to <tt>getStats</tt> method.
  208. * @param error an error that occurred on <tt>getStats</tt> call.
  209. */
  210. StatsCollector.prototype.errorCallback = function (error) {
  211. GlobalOnErrorHandler.callErrorHandler(error);
  212. logger.error("Get stats error", error);
  213. this.stop();
  214. };
  215. /**
  216. * Starts stats updates.
  217. */
  218. StatsCollector.prototype.start = function (startAudioLevelStats) {
  219. var self = this;
  220. if(startAudioLevelStats) {
  221. this.audioLevelsIntervalId = setInterval(
  222. function () {
  223. // Interval updates
  224. self.peerconnection.getStats(
  225. function (report) {
  226. var results = null;
  227. if (!report || !report.result ||
  228. typeof report.result != 'function') {
  229. results = report;
  230. }
  231. else {
  232. results = report.result();
  233. }
  234. self.currentAudioLevelsReport = results;
  235. self.processAudioLevelReport();
  236. self.baselineAudioLevelsReport =
  237. self.currentAudioLevelsReport;
  238. },
  239. self.errorCallback
  240. );
  241. },
  242. self.audioLevelsIntervalMilis
  243. );
  244. }
  245. if (browserSupported) {
  246. this.statsIntervalId = setInterval(
  247. function () {
  248. // Interval updates
  249. self.peerconnection.getStats(
  250. function (report) {
  251. var results = null;
  252. if (!report || !report.result ||
  253. typeof report.result != 'function') {
  254. //firefox
  255. results = report;
  256. }
  257. else {
  258. //chrome
  259. results = report.result();
  260. }
  261. self.currentStatsReport = results;
  262. try {
  263. self.processStatsReport();
  264. }
  265. catch (e) {
  266. GlobalOnErrorHandler.callErrorHandler(e);
  267. logger.error("Unsupported key:" + e, e);
  268. }
  269. self.previousStatsReport = self.currentStatsReport;
  270. },
  271. self.errorCallback
  272. );
  273. },
  274. self.statsIntervalMilis
  275. );
  276. }
  277. };
  278. /**
  279. * Defines a function which (1) is to be used as a StatsCollector method and (2)
  280. * gets the value from a specific report returned by RTCPeerConnection#getStats
  281. * associated with a LibJitsiMeet browser-agnostic name.
  282. *
  283. * @param {Object.<string,string>} keys the map of LibJitsi browser-agnostic
  284. * names to RTCPeerConnection#getStats browser-specific keys
  285. */
  286. StatsCollector.prototype._defineGetStatValueMethod = function (keys) {
  287. // Define the function which converts a LibJitsiMeet browser-asnostic name
  288. // to a browser-specific key of a report returned by
  289. // RTCPeerConnection#getStats.
  290. var keyFromName = function (name) {
  291. var key = keys[name];
  292. if (key)
  293. return key;
  294. else
  295. throw "The property '" + name + "' isn't supported!";
  296. };
  297. // Define the function which retrieves the value from a specific report
  298. // returned by RTCPeerConnection#getStats associated with a given
  299. // browser-specific key.
  300. var itemStatByKey;
  301. switch (this._browserType) {
  302. case RTCBrowserType.RTC_BROWSER_CHROME:
  303. case RTCBrowserType.RTC_BROWSER_OPERA:
  304. case RTCBrowserType.RTC_BROWSER_NWJS:
  305. case RTCBrowserType.RTC_BROWSER_ELECTRON:
  306. // TODO What about other types of browser which are based on Chrome such
  307. // as NW.js? Every time we want to support a new type browser we have to
  308. // go and add more conditions (here and in multiple other places).
  309. // Cannot we do a feature detection instead of a browser type check? For
  310. // example, if item has a stat property of type function, then it's very
  311. // likely that whoever defined it wanted you to call it in order to
  312. // retrieve the value associated with a specific key.
  313. itemStatByKey = function (item, key) { return item.stat(key); };
  314. break;
  315. case RTCBrowserType.RTC_BROWSER_REACT_NATIVE:
  316. // The implementation provided by react-native-webrtc follows the
  317. // Objective-C WebRTC API: RTCStatsReport has a values property of type
  318. // Array in which each element is a key-value pair.
  319. itemStatByKey = function (item, key) {
  320. var value;
  321. item.values.some(function (pair) {
  322. if (pair.hasOwnProperty(key)) {
  323. value = pair[key];
  324. return true;
  325. } else {
  326. return false;
  327. }
  328. });
  329. return value;
  330. };
  331. break;
  332. default:
  333. itemStatByKey = function (item, key) { return item[key]; };
  334. }
  335. // Compose the 2 functions defined above to get a function which retrieves
  336. // the value from a specific report returned by RTCPeerConnection#getStats
  337. // associated with a specific LibJitsiMeet browser-agnostic name.
  338. return function (item, name) {
  339. return itemStatByKey(item, keyFromName(name));
  340. };
  341. };
  342. /**
  343. * Stats processing logic.
  344. */
  345. StatsCollector.prototype.processStatsReport = function () {
  346. if (!this.previousStatsReport) {
  347. return;
  348. }
  349. var getStatValue = this._getStatValue;
  350. function getNonNegativeStat(report, name) {
  351. var value = getStatValue(report, name);
  352. if (typeof value !== 'number') {
  353. value = Number(value);
  354. }
  355. if (isNaN(value)) {
  356. return 0;
  357. }
  358. return Math.max(0, value);
  359. }
  360. var byteSentStats = {};
  361. for (var idx in this.currentStatsReport) {
  362. var now = this.currentStatsReport[idx];
  363. try {
  364. var receiveBandwidth = getStatValue(now, 'receiveBandwidth');
  365. var sendBandwidth = getStatValue(now, 'sendBandwidth');
  366. if (receiveBandwidth || sendBandwidth) {
  367. this.conferenceStats.bandwidth = {
  368. "download": Math.round(receiveBandwidth / 1000),
  369. "upload": Math.round(sendBandwidth / 1000)
  370. };
  371. }
  372. }
  373. catch(e){/*not supported*/}
  374. if(now.type == 'googCandidatePair')
  375. {
  376. var ip, type, localip, active;
  377. try {
  378. ip = getStatValue(now, 'remoteAddress');
  379. type = getStatValue(now, "transportType");
  380. localip = getStatValue(now, "localAddress");
  381. active = getStatValue(now, "activeConnection");
  382. }
  383. catch(e){/*not supported*/}
  384. if(!ip || !type || !localip || active != "true")
  385. continue;
  386. // Save the address unless it has been saved already.
  387. var conferenceStatsTransport = this.conferenceStats.transport;
  388. if(!conferenceStatsTransport.some(function (t) { return (
  389. t.ip == ip && t.type == type && t.localip == localip
  390. );})) {
  391. conferenceStatsTransport.push(
  392. {ip, type, localip});
  393. }
  394. continue;
  395. }
  396. if(now.type == "candidatepair") {
  397. if(now.state == "succeeded")
  398. continue;
  399. var local = this.currentStatsReport[now.localCandidateId];
  400. var remote = this.currentStatsReport[now.remoteCandidateId];
  401. this.conferenceStats.transport.push({
  402. ip: remote.ipAddress + ":" + remote.portNumber,
  403. type: local.transport,
  404. localip: local.ipAddress + ":" + local.portNumber
  405. });
  406. }
  407. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  408. now.type != "inboundrtp") {
  409. continue;
  410. }
  411. var before = this.previousStatsReport[idx];
  412. var ssrc = getStatValue(now, 'ssrc');
  413. if (!before || !ssrc) {
  414. continue;
  415. }
  416. var ssrcStats
  417. = this.ssrc2stats[ssrc] || (this.ssrc2stats[ssrc] = new SsrcStats());
  418. var isDownloadStream = true;
  419. var key = 'packetsReceived';
  420. var packetsNow = getStatValue(now, key);
  421. if (typeof packetsNow === 'undefined'
  422. || packetsNow === null || packetsNow === "") {
  423. isDownloadStream = false;
  424. key = 'packetsSent';
  425. packetsNow = getStatValue(now, key);
  426. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  427. logger.warn("No packetsReceived nor packetsSent stat found");
  428. continue;
  429. }
  430. }
  431. if (!packetsNow || packetsNow < 0)
  432. packetsNow = 0;
  433. var packetsBefore = getNonNegativeStat(before, key);
  434. var packetsDiff = Math.max(0, packetsNow - packetsBefore);
  435. var packetsLostNow = getNonNegativeStat(now, 'packetsLost');
  436. var packetsLostBefore = getNonNegativeStat(before, 'packetsLost');
  437. var packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);
  438. ssrcStats.setLoss({
  439. packetsTotal: packetsDiff + packetsLostDiff,
  440. packetsLost: packetsLostDiff,
  441. isDownloadStream
  442. });
  443. var bytesReceivedNow = getNonNegativeStat(now, 'bytesReceived');
  444. var bytesReceivedBefore = getNonNegativeStat(before, 'bytesReceived');
  445. var bytesReceived = Math.max(0, bytesReceivedNow - bytesReceivedBefore);
  446. var bytesSent = 0;
  447. // TODO: clean this mess up!
  448. var nowBytesTransmitted = getStatValue(now, "bytesSent");
  449. if(typeof nowBytesTransmitted === "number" ||
  450. typeof nowBytesTransmitted === "string") {
  451. nowBytesTransmitted = Number(nowBytesTransmitted);
  452. if(!isNaN(nowBytesTransmitted)){
  453. byteSentStats[ssrc] = nowBytesTransmitted;
  454. if (nowBytesTransmitted > 0) {
  455. bytesSent = nowBytesTransmitted -
  456. getStatValue(before, "bytesSent");
  457. }
  458. }
  459. }
  460. bytesSent = Math.max(0, bytesSent);
  461. var timeMs = now.timestamp - before.timestamp;
  462. var bitrateReceivedKbps = 0, bitrateSentKbps = 0;
  463. if (timeMs > 0) {
  464. // TODO is there any reason to round here?
  465. bitrateReceivedKbps = Math.round((bytesReceived * 8) / timeMs);
  466. bitrateSentKbps = Math.round((bytesSent * 8) / timeMs);
  467. }
  468. ssrcStats.addBitrate({
  469. "download": bitrateReceivedKbps,
  470. "upload": bitrateSentKbps
  471. });
  472. var resolution = {height: null, width: null};
  473. try {
  474. var height, width;
  475. if ((height = getStatValue(now, "googFrameHeightReceived")) &&
  476. (width = getStatValue(now, "googFrameWidthReceived"))) {
  477. resolution.height = height;
  478. resolution.width = width;
  479. }
  480. else if ((height = getStatValue(now, "googFrameHeightSent")) &&
  481. (width = getStatValue(now, "googFrameWidthSent"))) {
  482. resolution.height = height;
  483. resolution.width = width;
  484. }
  485. }
  486. catch(e){/*not supported*/}
  487. if (resolution.height && resolution.width) {
  488. ssrcStats.setResolution(resolution);
  489. } else {
  490. ssrcStats.setResolution(null);
  491. }
  492. }
  493. // process stats
  494. var totalPackets = {
  495. download: 0,
  496. upload: 0
  497. };
  498. var lostPackets = {
  499. download: 0,
  500. upload: 0
  501. };
  502. var bitrateDownload = 0;
  503. var bitrateUpload = 0;
  504. var resolutions = {};
  505. Object.keys(this.ssrc2stats).forEach(
  506. function (ssrc) {
  507. var ssrcStats = this.ssrc2stats[ssrc];
  508. // process packet loss stats
  509. var loss = ssrcStats.loss;
  510. var type = loss.isDownloadStream ? "download" : "upload";
  511. totalPackets[type] += loss.packetsTotal;
  512. lostPackets[type] += loss.packetsLost;
  513. // process bitrate stats
  514. bitrateDownload += ssrcStats.bitrate.download;
  515. bitrateUpload += ssrcStats.bitrate.upload;
  516. ssrcStats.resetBitrate();
  517. // collect resolutions
  518. resolutions[ssrc] = ssrcStats.resolution;
  519. },
  520. this
  521. );
  522. this.eventEmitter.emit(StatisticsEvents.BYTE_SENT_STATS, byteSentStats);
  523. this.conferenceStats.bitrate
  524. = {"upload": bitrateUpload, "download": bitrateDownload};
  525. this.conferenceStats.packetLoss = {
  526. total:
  527. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  528. totalPackets.download + totalPackets.upload),
  529. download:
  530. calculatePacketLoss(lostPackets.download, totalPackets.download),
  531. upload:
  532. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  533. };
  534. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS, {
  535. "bandwidth": this.conferenceStats.bandwidth,
  536. "bitrate": this.conferenceStats.bitrate,
  537. "packetLoss": this.conferenceStats.packetLoss,
  538. "resolution": resolutions,
  539. "transport": this.conferenceStats.transport
  540. });
  541. this.conferenceStats.transport = [];
  542. };
  543. /**
  544. * Stats processing logic.
  545. */
  546. StatsCollector.prototype.processAudioLevelReport = function () {
  547. if (!this.baselineAudioLevelsReport) {
  548. return;
  549. }
  550. var getStatValue = this._getStatValue;
  551. for (var idx in this.currentAudioLevelsReport) {
  552. var now = this.currentAudioLevelsReport[idx];
  553. if (now.type != 'ssrc')
  554. continue;
  555. var before = this.baselineAudioLevelsReport[idx];
  556. var ssrc = getStatValue(now, 'ssrc');
  557. if (!before) {
  558. logger.warn(ssrc + ' not enough data');
  559. continue;
  560. }
  561. if (!ssrc) {
  562. if ((Date.now() - now.timestamp) < 3000)
  563. logger.warn("No ssrc: ");
  564. continue;
  565. }
  566. // Audio level
  567. try {
  568. var audioLevel
  569. = getStatValue(now, 'audioInputLevel')
  570. || getStatValue(now, 'audioOutputLevel');
  571. }
  572. catch(e) {/*not supported*/
  573. logger.warn("Audio Levels are not available in the statistics.");
  574. clearInterval(this.audioLevelsIntervalId);
  575. return;
  576. }
  577. if (audioLevel) {
  578. const isLocal = !getStatValue(now, 'packetsReceived');
  579. // TODO: Can't find specs about what this value really is, but it
  580. // seems to vary between 0 and around 32k.
  581. audioLevel = audioLevel / 32767;
  582. this.eventEmitter.emit(
  583. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel, isLocal);
  584. }
  585. }
  586. };