選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

RTPStatsCollector.js 22KB

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