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

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