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.

statistics.bundle.js 36KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.statistics=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /**
  3. * Provides statistics for the local stream.
  4. */
  5. /**
  6. * Size of the webaudio analizer buffer.
  7. * @type {number}
  8. */
  9. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  10. /**
  11. * Value of the webaudio analizer smoothing time parameter.
  12. * @type {number}
  13. */
  14. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  15. /**
  16. * Converts time domain data array to audio level.
  17. * @param array the time domain data array.
  18. * @returns {number} the audio level
  19. */
  20. function timeDomainDataToAudioLevel(samples) {
  21. var maxVolume = 0;
  22. var length = samples.length;
  23. for (var i = 0; i < length; i++) {
  24. if (maxVolume < samples[i])
  25. maxVolume = samples[i];
  26. }
  27. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  28. };
  29. /**
  30. * Animates audio level change
  31. * @param newLevel the new audio level
  32. * @param lastLevel the last audio level
  33. * @returns {Number} the audio level to be set
  34. */
  35. function animateLevel(newLevel, lastLevel)
  36. {
  37. var value = 0;
  38. var diff = lastLevel - newLevel;
  39. if(diff > 0.2)
  40. {
  41. value = lastLevel - 0.2;
  42. }
  43. else if(diff < -0.4)
  44. {
  45. value = lastLevel + 0.4;
  46. }
  47. else
  48. {
  49. value = newLevel;
  50. }
  51. return parseFloat(value.toFixed(3));
  52. }
  53. /**
  54. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  55. *
  56. * @param stream the local stream
  57. * @param interval stats refresh interval given in ms.
  58. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  59. * update.
  60. * @constructor
  61. */
  62. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  63. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  64. this.stream = stream;
  65. this.intervalId = null;
  66. this.intervalMilis = interval;
  67. this.eventEmitter = eventEmitter;
  68. this.audioLevel = 0;
  69. this.statisticsService = statisticsService;
  70. }
  71. /**
  72. * Starts the collecting the statistics.
  73. */
  74. LocalStatsCollector.prototype.start = function () {
  75. if (!window.AudioContext)
  76. return;
  77. var context = new AudioContext();
  78. var analyser = context.createAnalyser();
  79. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  80. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  81. var source = context.createMediaStreamSource(this.stream);
  82. source.connect(analyser);
  83. var self = this;
  84. this.intervalId = setInterval(
  85. function () {
  86. var array = new Uint8Array(analyser.frequencyBinCount);
  87. analyser.getByteTimeDomainData(array);
  88. var audioLevel = timeDomainDataToAudioLevel(array);
  89. if(audioLevel != self.audioLevel) {
  90. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  91. self.eventEmitter.emit(
  92. "statistics.audioLevel",
  93. self.statisticsService.LOCAL_JID,
  94. self.audioLevel);
  95. }
  96. },
  97. this.intervalMilis
  98. );
  99. };
  100. /**
  101. * Stops collecting the statistics.
  102. */
  103. LocalStatsCollector.prototype.stop = function () {
  104. if (this.intervalId) {
  105. clearInterval(this.intervalId);
  106. this.intervalId = null;
  107. }
  108. };
  109. module.exports = LocalStatsCollector;
  110. },{}],2:[function(require,module,exports){
  111. /* global ssrc2jid */
  112. /* jshint -W117 */
  113. /**
  114. * Calculates packet lost percent using the number of lost packets and the
  115. * number of all packet.
  116. * @param lostPackets the number of lost packets
  117. * @param totalPackets the number of all packets.
  118. * @returns {number} packet loss percent
  119. */
  120. function calculatePacketLoss(lostPackets, totalPackets) {
  121. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  122. return 0;
  123. return Math.round((lostPackets/totalPackets)*100);
  124. }
  125. function getStatValue(item, name) {
  126. if(!keyMap[RTC.getBrowserType()][name])
  127. throw "The property isn't supported!";
  128. var key = keyMap[RTC.getBrowserType()][name];
  129. return RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  130. }
  131. /**
  132. * Peer statistics data holder.
  133. * @constructor
  134. */
  135. function PeerStats()
  136. {
  137. this.ssrc2Loss = {};
  138. this.ssrc2AudioLevel = {};
  139. this.ssrc2bitrate = {};
  140. this.ssrc2resolution = {};
  141. }
  142. /**
  143. * The bandwidth
  144. * @type {{}}
  145. */
  146. PeerStats.bandwidth = {};
  147. /**
  148. * The bit rate
  149. * @type {{}}
  150. */
  151. PeerStats.bitrate = {};
  152. /**
  153. * The packet loss rate
  154. * @type {{}}
  155. */
  156. PeerStats.packetLoss = null;
  157. /**
  158. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  159. * represented by this instance.
  160. * @param ssrc audio or video RTP stream SSRC.
  161. * @param lossRate new packet loss rate value to be set.
  162. */
  163. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  164. {
  165. this.ssrc2Loss[ssrc] = lossRate;
  166. };
  167. /**
  168. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  169. * represented by this instance.
  170. * @param ssrc audio or video RTP stream SSRC.
  171. * @param resolution new resolution value to be set.
  172. */
  173. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  174. {
  175. if(resolution === null && this.ssrc2resolution[ssrc])
  176. {
  177. delete this.ssrc2resolution[ssrc];
  178. }
  179. else if(resolution !== null)
  180. this.ssrc2resolution[ssrc] = resolution;
  181. };
  182. /**
  183. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  184. * represented by this instance.
  185. * @param ssrc audio or video RTP stream SSRC.
  186. * @param bitrate new bitrate value to be set.
  187. */
  188. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  189. {
  190. if(this.ssrc2bitrate[ssrc])
  191. {
  192. this.ssrc2bitrate[ssrc].download += bitrate.download;
  193. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  194. }
  195. else {
  196. this.ssrc2bitrate[ssrc] = bitrate;
  197. }
  198. };
  199. /**
  200. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  201. * the stream which belongs to the peer represented by this instance.
  202. * @param ssrc RTP stream SSRC for which current audio level value will be
  203. * updated.
  204. * @param audioLevel the new audio level value to be set. Value is truncated to
  205. * fit the range from 0 to 1.
  206. */
  207. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  208. {
  209. // Range limit 0 - 1
  210. this.ssrc2AudioLevel[ssrc] = Math.min(Math.max(audioLevel, 0), 1);
  211. };
  212. /**
  213. * Array with the transport information.
  214. * @type {Array}
  215. */
  216. PeerStats.transport = [];
  217. /**
  218. * <tt>StatsCollector</tt> registers for stats updates of given
  219. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  220. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  221. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  222. * instance as an event source.
  223. *
  224. * @param peerconnection webRTC peer connection object.
  225. * @param interval stats refresh interval given in ms.
  226. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  227. * called on stats update.
  228. * @constructor
  229. */
  230. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  231. {
  232. this.peerconnection = peerconnection;
  233. this.baselineAudioLevelsReport = null;
  234. this.currentAudioLevelsReport = null;
  235. this.currentStatsReport = null;
  236. this.baselineStatsReport = null;
  237. this.audioLevelsIntervalId = null;
  238. this.eventEmitter = eventEmitter;
  239. /**
  240. * Gather PeerConnection stats once every this many milliseconds.
  241. */
  242. this.GATHER_INTERVAL = 10000;
  243. /**
  244. * Log stats via the focus once every this many milliseconds.
  245. */
  246. this.LOG_INTERVAL = 60000;
  247. /**
  248. * Gather stats and store them in this.statsToBeLogged.
  249. */
  250. this.gatherStatsIntervalId = null;
  251. /**
  252. * Send the stats already saved in this.statsToBeLogged to be logged via
  253. * the focus.
  254. */
  255. this.logStatsIntervalId = null;
  256. /**
  257. * Stores the statistics which will be send to the focus to be logged.
  258. */
  259. this.statsToBeLogged =
  260. {
  261. timestamps: [],
  262. stats: {}
  263. };
  264. // Updates stats interval
  265. this.audioLevelsIntervalMilis = audioLevelsInterval;
  266. this.statsIntervalId = null;
  267. this.statsIntervalMilis = statsInterval;
  268. // Map of jids to PeerStats
  269. this.jid2stats = {};
  270. }
  271. module.exports = StatsCollector;
  272. /**
  273. * Stops stats updates.
  274. */
  275. StatsCollector.prototype.stop = function ()
  276. {
  277. if (this.audioLevelsIntervalId)
  278. {
  279. clearInterval(this.audioLevelsIntervalId);
  280. this.audioLevelsIntervalId = null;
  281. clearInterval(this.statsIntervalId);
  282. this.statsIntervalId = null;
  283. clearInterval(this.logStatsIntervalId);
  284. this.logStatsIntervalId = null;
  285. clearInterval(this.gatherStatsIntervalId);
  286. this.gatherStatsIntervalId = null;
  287. }
  288. };
  289. /**
  290. * Callback passed to <tt>getStats</tt> method.
  291. * @param error an error that occurred on <tt>getStats</tt> call.
  292. */
  293. StatsCollector.prototype.errorCallback = function (error)
  294. {
  295. console.error("Get stats error", error);
  296. this.stop();
  297. };
  298. /**
  299. * Starts stats updates.
  300. */
  301. StatsCollector.prototype.start = function ()
  302. {
  303. var self = this;
  304. this.audioLevelsIntervalId = setInterval(
  305. function ()
  306. {
  307. // Interval updates
  308. self.peerconnection.getStats(
  309. function (report)
  310. {
  311. var results = null;
  312. if(!report || !report.result || typeof report.result != 'function')
  313. {
  314. results = report;
  315. }
  316. else
  317. {
  318. results = report.result();
  319. }
  320. //console.error("Got interval report", results);
  321. self.currentAudioLevelsReport = results;
  322. self.processAudioLevelReport();
  323. self.baselineAudioLevelsReport =
  324. self.currentAudioLevelsReport;
  325. },
  326. self.errorCallback
  327. );
  328. },
  329. self.audioLevelsIntervalMilis
  330. );
  331. this.statsIntervalId = setInterval(
  332. function () {
  333. // Interval updates
  334. self.peerconnection.getStats(
  335. function (report)
  336. {
  337. var results = null;
  338. if(!report || !report.result || typeof report.result != 'function')
  339. {
  340. //firefox
  341. results = report;
  342. }
  343. else
  344. {
  345. //chrome
  346. results = report.result();
  347. }
  348. //console.error("Got interval report", results);
  349. self.currentStatsReport = results;
  350. try
  351. {
  352. self.processStatsReport();
  353. }
  354. catch (e)
  355. {
  356. console.error("Unsupported key:" + e, e);
  357. }
  358. self.baselineStatsReport = self.currentStatsReport;
  359. },
  360. self.errorCallback
  361. );
  362. },
  363. self.statsIntervalMilis
  364. );
  365. if (config.logStats) {
  366. this.gatherStatsIntervalId = setInterval(
  367. function () {
  368. self.peerconnection.getStats(
  369. function (report) {
  370. self.addStatsToBeLogged(report.result());
  371. },
  372. function () {
  373. }
  374. );
  375. },
  376. this.GATHER_INTERVAL
  377. );
  378. this.logStatsIntervalId = setInterval(
  379. function() { self.logStats(); },
  380. this.LOG_INTERVAL);
  381. }
  382. };
  383. /**
  384. * Converts the stats to the format used for logging, and saves the data in
  385. * this.statsToBeLogged.
  386. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  387. */
  388. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  389. var self = this;
  390. var num_records = this.statsToBeLogged.timestamps.length;
  391. this.statsToBeLogged.timestamps.push(new Date().getTime());
  392. reports.map(function (report) {
  393. var stat = self.statsToBeLogged.stats[report.id];
  394. if (!stat) {
  395. stat = self.statsToBeLogged.stats[report.id] = {};
  396. }
  397. stat.type = report.type;
  398. report.names().map(function (name) {
  399. var values = stat[name];
  400. if (!values) {
  401. values = stat[name] = [];
  402. }
  403. while (values.length < num_records) {
  404. values.push(null);
  405. }
  406. values.push(report.stat(name));
  407. });
  408. });
  409. };
  410. StatsCollector.prototype.logStats = function () {
  411. if(!xmpp.sendLogs(this.statsToBeLogged))
  412. return;
  413. // Reset the stats
  414. this.statsToBeLogged.stats = {};
  415. this.statsToBeLogged.timestamps = [];
  416. };
  417. var keyMap = {};
  418. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  419. "ssrc": "ssrc",
  420. "packetsReceived": "packetsReceived",
  421. "packetsLost": "packetsLost",
  422. "packetsSent": "packetsSent",
  423. "bytesReceived": "bytesReceived",
  424. "bytesSent": "bytesSent"
  425. };
  426. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  427. "receiveBandwidth": "googAvailableReceiveBandwidth",
  428. "sendBandwidth": "googAvailableSendBandwidth",
  429. "remoteAddress": "googRemoteAddress",
  430. "transportType": "googTransportType",
  431. "localAddress": "googLocalAddress",
  432. "activeConnection": "googActiveConnection",
  433. "ssrc": "ssrc",
  434. "packetsReceived": "packetsReceived",
  435. "packetsSent": "packetsSent",
  436. "packetsLost": "packetsLost",
  437. "bytesReceived": "bytesReceived",
  438. "bytesSent": "bytesSent",
  439. "googFrameHeightReceived": "googFrameHeightReceived",
  440. "googFrameWidthReceived": "googFrameWidthReceived",
  441. "googFrameHeightSent": "googFrameHeightSent",
  442. "googFrameWidthSent": "googFrameWidthSent",
  443. "audioInputLevel": "audioInputLevel",
  444. "audioOutputLevel": "audioOutputLevel"
  445. };
  446. /**
  447. * Stats processing logic.
  448. */
  449. StatsCollector.prototype.processStatsReport = function () {
  450. if (!this.baselineStatsReport) {
  451. return;
  452. }
  453. for (var idx in this.currentStatsReport) {
  454. var now = this.currentStatsReport[idx];
  455. try {
  456. if (getStatValue(now, 'receiveBandwidth') ||
  457. getStatValue(now, 'sendBandwidth')) {
  458. PeerStats.bandwidth = {
  459. "download": Math.round(
  460. (getStatValue(now, 'receiveBandwidth')) / 1000),
  461. "upload": Math.round(
  462. (getStatValue(now, 'sendBandwidth')) / 1000)
  463. };
  464. }
  465. }
  466. catch(e){/*not supported*/}
  467. if(now.type == 'googCandidatePair')
  468. {
  469. var ip, type, localIP, active;
  470. try {
  471. ip = getStatValue(now, 'remoteAddress');
  472. type = getStatValue(now, "transportType");
  473. localIP = getStatValue(now, "localAddress");
  474. active = getStatValue(now, "activeConnection");
  475. }
  476. catch(e){/*not supported*/}
  477. if(!ip || !type || !localIP || active != "true")
  478. continue;
  479. var addressSaved = false;
  480. for(var i = 0; i < PeerStats.transport.length; i++)
  481. {
  482. if(PeerStats.transport[i].ip == ip &&
  483. PeerStats.transport[i].type == type &&
  484. PeerStats.transport[i].localip == localIP)
  485. {
  486. addressSaved = true;
  487. }
  488. }
  489. if(addressSaved)
  490. continue;
  491. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  492. continue;
  493. }
  494. if(now.type == "candidatepair")
  495. {
  496. if(now.state == "succeeded")
  497. continue;
  498. var local = this.currentStatsReport[now.localCandidateId];
  499. var remote = this.currentStatsReport[now.remoteCandidateId];
  500. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  501. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  502. }
  503. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  504. now.type != "inboundrtp") {
  505. continue;
  506. }
  507. var before = this.baselineStatsReport[idx];
  508. if (!before) {
  509. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  510. continue;
  511. }
  512. var ssrc = getStatValue(now, 'ssrc');
  513. if(!ssrc)
  514. continue;
  515. var jid = ssrc2jid[ssrc];
  516. if (!jid && (Date.now() - now.timestamp) < 3000) {
  517. console.warn("No jid for ssrc: " + ssrc);
  518. continue;
  519. }
  520. var jidStats = this.jid2stats[jid];
  521. if (!jidStats) {
  522. jidStats = new PeerStats();
  523. this.jid2stats[jid] = jidStats;
  524. }
  525. var isDownloadStream = true;
  526. var key = 'packetsReceived';
  527. if (!getStatValue(now, key))
  528. {
  529. isDownloadStream = false;
  530. key = 'packetsSent';
  531. if (!getStatValue(now, key))
  532. {
  533. console.warn("No packetsReceived nor packetSent stat found");
  534. continue;
  535. }
  536. }
  537. var packetsNow = getStatValue(now, key);
  538. if(!packetsNow || packetsNow < 0)
  539. packetsNow = 0;
  540. var packetsBefore = getStatValue(before, key);
  541. if(!packetsBefore || packetsBefore < 0)
  542. packetsBefore = 0;
  543. var packetRate = packetsNow - packetsBefore;
  544. if(!packetRate || packetRate < 0)
  545. packetRate = 0;
  546. var currentLoss = getStatValue(now, 'packetsLost');
  547. if(!currentLoss || currentLoss < 0)
  548. currentLoss = 0;
  549. var previousLoss = getStatValue(before, 'packetsLost');
  550. if(!previousLoss || previousLoss < 0)
  551. previousLoss = 0;
  552. var lossRate = currentLoss - previousLoss;
  553. if(!lossRate || lossRate < 0)
  554. lossRate = 0;
  555. var packetsTotal = (packetRate + lossRate);
  556. jidStats.setSsrcLoss(ssrc,
  557. {"packetsTotal": packetsTotal,
  558. "packetsLost": lossRate,
  559. "isDownloadStream": isDownloadStream});
  560. var bytesReceived = 0, bytesSent = 0;
  561. if(getStatValue(now, "bytesReceived"))
  562. {
  563. bytesReceived = getStatValue(now, "bytesReceived") -
  564. getStatValue(before, "bytesReceived");
  565. }
  566. if(getStatValue(now, "bytesSent"))
  567. {
  568. bytesSent = getStatValue(now, "bytesSent") -
  569. getStatValue(before, "bytesSent");
  570. }
  571. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  572. if(bytesReceived <= 0 || time <= 0)
  573. {
  574. bytesReceived = 0;
  575. }
  576. else
  577. {
  578. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  579. }
  580. if(bytesSent <= 0 || time <= 0)
  581. {
  582. bytesSent = 0;
  583. }
  584. else
  585. {
  586. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  587. }
  588. jidStats.setSsrcBitrate(ssrc, {
  589. "download": bytesReceived,
  590. "upload": bytesSent});
  591. var resolution = {height: null, width: null};
  592. try {
  593. if (getStatValue(now, "googFrameHeightReceived") &&
  594. getStatValue(now, "googFrameWidthReceived")) {
  595. resolution.height = getStatValue(now, "googFrameHeightReceived");
  596. resolution.width = getStatValue(now, "googFrameWidthReceived");
  597. }
  598. else if (getStatValue(now, "googFrameHeightSent") &&
  599. getStatValue(now, "googFrameWidthSent")) {
  600. resolution.height = getStatValue(now, "googFrameHeightSent");
  601. resolution.width = getStatValue(now, "googFrameWidthSent");
  602. }
  603. }
  604. catch(e){/*not supported*/}
  605. if(resolution.height && resolution.width)
  606. {
  607. jidStats.setSsrcResolution(ssrc, resolution);
  608. }
  609. else
  610. {
  611. jidStats.setSsrcResolution(ssrc, null);
  612. }
  613. }
  614. var self = this;
  615. // Jid stats
  616. var totalPackets = {download: 0, upload: 0};
  617. var lostPackets = {download: 0, upload: 0};
  618. var bitrateDownload = 0;
  619. var bitrateUpload = 0;
  620. var resolutions = {};
  621. Object.keys(this.jid2stats).forEach(
  622. function (jid)
  623. {
  624. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  625. function (ssrc)
  626. {
  627. var type = "upload";
  628. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  629. type = "download";
  630. totalPackets[type] +=
  631. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  632. lostPackets[type] +=
  633. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  634. }
  635. );
  636. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  637. function (ssrc) {
  638. bitrateDownload +=
  639. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  640. bitrateUpload +=
  641. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  642. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  643. }
  644. );
  645. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  646. }
  647. );
  648. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  649. PeerStats.packetLoss = {
  650. total:
  651. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  652. totalPackets.download + totalPackets.upload),
  653. download:
  654. calculatePacketLoss(lostPackets.download, totalPackets.download),
  655. upload:
  656. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  657. };
  658. this.eventEmitter.emit("statistics.connectionstats",
  659. {
  660. "bitrate": PeerStats.bitrate,
  661. "packetLoss": PeerStats.packetLoss,
  662. "bandwidth": PeerStats.bandwidth,
  663. "resolution": resolutions,
  664. "transport": PeerStats.transport
  665. });
  666. PeerStats.transport = [];
  667. };
  668. /**
  669. * Stats processing logic.
  670. */
  671. StatsCollector.prototype.processAudioLevelReport = function ()
  672. {
  673. if (!this.baselineAudioLevelsReport)
  674. {
  675. return;
  676. }
  677. for (var idx in this.currentAudioLevelsReport)
  678. {
  679. var now = this.currentAudioLevelsReport[idx];
  680. if (now.type != 'ssrc')
  681. {
  682. continue;
  683. }
  684. var before = this.baselineAudioLevelsReport[idx];
  685. if (!before)
  686. {
  687. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  688. continue;
  689. }
  690. var ssrc = getStatValue(now, 'ssrc');
  691. var jid = ssrc2jid[ssrc];
  692. if (!jid && (Date.now() - now.timestamp) < 3000)
  693. {
  694. console.warn("No jid for ssrc: " + ssrc);
  695. continue;
  696. }
  697. var jidStats = this.jid2stats[jid];
  698. if (!jidStats)
  699. {
  700. jidStats = new PeerStats();
  701. this.jid2stats[jid] = jidStats;
  702. }
  703. // Audio level
  704. var audioLevel = null;
  705. try {
  706. audioLevel = getStatValue(now, 'audioInputLevel');
  707. if (!audioLevel)
  708. audioLevel = getStatValue(now, 'audioOutputLevel');
  709. }
  710. catch(e) {/*not supported*/
  711. console.warn("Audio Levels are not available in the statistics.");
  712. clearInterval(this.audioLevelsIntervalId);
  713. return;
  714. }
  715. if (audioLevel)
  716. {
  717. // TODO: can't find specs about what this value really is,
  718. // but it seems to vary between 0 and around 32k.
  719. audioLevel = audioLevel / 32767;
  720. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  721. if(jid != xmpp.myJid())
  722. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  723. }
  724. }
  725. };
  726. },{}],3:[function(require,module,exports){
  727. /**
  728. * Created by hristo on 8/4/14.
  729. */
  730. var LocalStats = require("./LocalStatsCollector.js");
  731. var RTPStats = require("./RTPStatsCollector.js");
  732. var EventEmitter = require("events");
  733. //These lines should be uncommented when require works in app.js
  734. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  735. //var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  736. //var XMPPEvents = require("../service/xmpp/XMPPEvents");
  737. var eventEmitter = new EventEmitter();
  738. var localStats = null;
  739. var rtpStats = null;
  740. function stopLocal()
  741. {
  742. if(localStats)
  743. {
  744. localStats.stop();
  745. localStats = null;
  746. }
  747. }
  748. function stopRemote()
  749. {
  750. if(rtpStats)
  751. {
  752. rtpStats.stop();
  753. eventEmitter.emit("statistics.stop");
  754. rtpStats = null;
  755. }
  756. }
  757. function startRemoteStats (peerconnection) {
  758. if (config.enableRtpStats)
  759. {
  760. if(rtpStats)
  761. {
  762. rtpStats.stop();
  763. rtpStats = null;
  764. }
  765. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  766. rtpStats.start();
  767. }
  768. }
  769. function onStreamCreated(stream)
  770. {
  771. if(stream.getOriginalStream().getAudioTracks().length === 0)
  772. return;
  773. localStats = new LocalStats(stream.getOriginalStream(), 100, statistics,
  774. eventEmitter);
  775. localStats.start();
  776. }
  777. function onDisposeConference(onUnload) {
  778. stopRemote();
  779. if(onUnload) {
  780. stopLocal();
  781. eventEmitter.removeAllListeners();
  782. }
  783. }
  784. var statistics =
  785. {
  786. /**
  787. * Indicates that this audio level is for local jid.
  788. * @type {string}
  789. */
  790. LOCAL_JID: 'local',
  791. addAudioLevelListener: function(listener)
  792. {
  793. eventEmitter.on("statistics.audioLevel", listener);
  794. },
  795. removeAudioLevelListener: function(listener)
  796. {
  797. eventEmitter.removeListener("statistics.audioLevel", listener);
  798. },
  799. addConnectionStatsListener: function(listener)
  800. {
  801. eventEmitter.on("statistics.connectionstats", listener);
  802. },
  803. removeConnectionStatsListener: function(listener)
  804. {
  805. eventEmitter.removeListener("statistics.connectionstats", listener);
  806. },
  807. addRemoteStatsStopListener: function(listener)
  808. {
  809. eventEmitter.on("statistics.stop", listener);
  810. },
  811. removeRemoteStatsStopListener: function(listener)
  812. {
  813. eventEmitter.removeListener("statistics.stop", listener);
  814. },
  815. stop: function () {
  816. stopLocal();
  817. stopRemote();
  818. if(eventEmitter)
  819. {
  820. eventEmitter.removeAllListeners();
  821. }
  822. },
  823. stopRemoteStatistics: function()
  824. {
  825. stopRemote();
  826. },
  827. onConferenceCreated: function (event) {
  828. startRemoteStats(event.peerconnection);
  829. },
  830. start: function () {
  831. this.addConnectionStatsListener(connectionquality.updateLocalStats);
  832. this.addRemoteStatsStopListener(connectionquality.stopSendingStats);
  833. RTC.addStreamListener(onStreamCreated,
  834. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  835. xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  836. }
  837. };
  838. module.exports = statistics;
  839. },{"./LocalStatsCollector.js":1,"./RTPStatsCollector.js":2,"events":4}],4:[function(require,module,exports){
  840. // Copyright Joyent, Inc. and other Node contributors.
  841. //
  842. // Permission is hereby granted, free of charge, to any person obtaining a
  843. // copy of this software and associated documentation files (the
  844. // "Software"), to deal in the Software without restriction, including
  845. // without limitation the rights to use, copy, modify, merge, publish,
  846. // distribute, sublicense, and/or sell copies of the Software, and to permit
  847. // persons to whom the Software is furnished to do so, subject to the
  848. // following conditions:
  849. //
  850. // The above copyright notice and this permission notice shall be included
  851. // in all copies or substantial portions of the Software.
  852. //
  853. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  854. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  855. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  856. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  857. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  858. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  859. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  860. function EventEmitter() {
  861. this._events = this._events || {};
  862. this._maxListeners = this._maxListeners || undefined;
  863. }
  864. module.exports = EventEmitter;
  865. // Backwards-compat with node 0.10.x
  866. EventEmitter.EventEmitter = EventEmitter;
  867. EventEmitter.prototype._events = undefined;
  868. EventEmitter.prototype._maxListeners = undefined;
  869. // By default EventEmitters will print a warning if more than 10 listeners are
  870. // added to it. This is a useful default which helps finding memory leaks.
  871. EventEmitter.defaultMaxListeners = 10;
  872. // Obviously not all Emitters should be limited to 10. This function allows
  873. // that to be increased. Set to zero for unlimited.
  874. EventEmitter.prototype.setMaxListeners = function(n) {
  875. if (!isNumber(n) || n < 0 || isNaN(n))
  876. throw TypeError('n must be a positive number');
  877. this._maxListeners = n;
  878. return this;
  879. };
  880. EventEmitter.prototype.emit = function(type) {
  881. var er, handler, len, args, i, listeners;
  882. if (!this._events)
  883. this._events = {};
  884. // If there is no 'error' event listener then throw.
  885. if (type === 'error') {
  886. if (!this._events.error ||
  887. (isObject(this._events.error) && !this._events.error.length)) {
  888. er = arguments[1];
  889. if (er instanceof Error) {
  890. throw er; // Unhandled 'error' event
  891. } else {
  892. throw TypeError('Uncaught, unspecified "error" event.');
  893. }
  894. return false;
  895. }
  896. }
  897. handler = this._events[type];
  898. if (isUndefined(handler))
  899. return false;
  900. if (isFunction(handler)) {
  901. switch (arguments.length) {
  902. // fast cases
  903. case 1:
  904. handler.call(this);
  905. break;
  906. case 2:
  907. handler.call(this, arguments[1]);
  908. break;
  909. case 3:
  910. handler.call(this, arguments[1], arguments[2]);
  911. break;
  912. // slower
  913. default:
  914. len = arguments.length;
  915. args = new Array(len - 1);
  916. for (i = 1; i < len; i++)
  917. args[i - 1] = arguments[i];
  918. handler.apply(this, args);
  919. }
  920. } else if (isObject(handler)) {
  921. len = arguments.length;
  922. args = new Array(len - 1);
  923. for (i = 1; i < len; i++)
  924. args[i - 1] = arguments[i];
  925. listeners = handler.slice();
  926. len = listeners.length;
  927. for (i = 0; i < len; i++)
  928. listeners[i].apply(this, args);
  929. }
  930. return true;
  931. };
  932. EventEmitter.prototype.addListener = function(type, listener) {
  933. var m;
  934. if (!isFunction(listener))
  935. throw TypeError('listener must be a function');
  936. if (!this._events)
  937. this._events = {};
  938. // To avoid recursion in the case that type === "newListener"! Before
  939. // adding it to the listeners, first emit "newListener".
  940. if (this._events.newListener)
  941. this.emit('newListener', type,
  942. isFunction(listener.listener) ?
  943. listener.listener : listener);
  944. if (!this._events[type])
  945. // Optimize the case of one listener. Don't need the extra array object.
  946. this._events[type] = listener;
  947. else if (isObject(this._events[type]))
  948. // If we've already got an array, just append.
  949. this._events[type].push(listener);
  950. else
  951. // Adding the second element, need to change to array.
  952. this._events[type] = [this._events[type], listener];
  953. // Check for listener leak
  954. if (isObject(this._events[type]) && !this._events[type].warned) {
  955. var m;
  956. if (!isUndefined(this._maxListeners)) {
  957. m = this._maxListeners;
  958. } else {
  959. m = EventEmitter.defaultMaxListeners;
  960. }
  961. if (m && m > 0 && this._events[type].length > m) {
  962. this._events[type].warned = true;
  963. console.error('(node) warning: possible EventEmitter memory ' +
  964. 'leak detected. %d listeners added. ' +
  965. 'Use emitter.setMaxListeners() to increase limit.',
  966. this._events[type].length);
  967. if (typeof console.trace === 'function') {
  968. // not supported in IE 10
  969. console.trace();
  970. }
  971. }
  972. }
  973. return this;
  974. };
  975. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  976. EventEmitter.prototype.once = function(type, listener) {
  977. if (!isFunction(listener))
  978. throw TypeError('listener must be a function');
  979. var fired = false;
  980. function g() {
  981. this.removeListener(type, g);
  982. if (!fired) {
  983. fired = true;
  984. listener.apply(this, arguments);
  985. }
  986. }
  987. g.listener = listener;
  988. this.on(type, g);
  989. return this;
  990. };
  991. // emits a 'removeListener' event iff the listener was removed
  992. EventEmitter.prototype.removeListener = function(type, listener) {
  993. var list, position, length, i;
  994. if (!isFunction(listener))
  995. throw TypeError('listener must be a function');
  996. if (!this._events || !this._events[type])
  997. return this;
  998. list = this._events[type];
  999. length = list.length;
  1000. position = -1;
  1001. if (list === listener ||
  1002. (isFunction(list.listener) && list.listener === listener)) {
  1003. delete this._events[type];
  1004. if (this._events.removeListener)
  1005. this.emit('removeListener', type, listener);
  1006. } else if (isObject(list)) {
  1007. for (i = length; i-- > 0;) {
  1008. if (list[i] === listener ||
  1009. (list[i].listener && list[i].listener === listener)) {
  1010. position = i;
  1011. break;
  1012. }
  1013. }
  1014. if (position < 0)
  1015. return this;
  1016. if (list.length === 1) {
  1017. list.length = 0;
  1018. delete this._events[type];
  1019. } else {
  1020. list.splice(position, 1);
  1021. }
  1022. if (this._events.removeListener)
  1023. this.emit('removeListener', type, listener);
  1024. }
  1025. return this;
  1026. };
  1027. EventEmitter.prototype.removeAllListeners = function(type) {
  1028. var key, listeners;
  1029. if (!this._events)
  1030. return this;
  1031. // not listening for removeListener, no need to emit
  1032. if (!this._events.removeListener) {
  1033. if (arguments.length === 0)
  1034. this._events = {};
  1035. else if (this._events[type])
  1036. delete this._events[type];
  1037. return this;
  1038. }
  1039. // emit removeListener for all listeners on all events
  1040. if (arguments.length === 0) {
  1041. for (key in this._events) {
  1042. if (key === 'removeListener') continue;
  1043. this.removeAllListeners(key);
  1044. }
  1045. this.removeAllListeners('removeListener');
  1046. this._events = {};
  1047. return this;
  1048. }
  1049. listeners = this._events[type];
  1050. if (isFunction(listeners)) {
  1051. this.removeListener(type, listeners);
  1052. } else {
  1053. // LIFO order
  1054. while (listeners.length)
  1055. this.removeListener(type, listeners[listeners.length - 1]);
  1056. }
  1057. delete this._events[type];
  1058. return this;
  1059. };
  1060. EventEmitter.prototype.listeners = function(type) {
  1061. var ret;
  1062. if (!this._events || !this._events[type])
  1063. ret = [];
  1064. else if (isFunction(this._events[type]))
  1065. ret = [this._events[type]];
  1066. else
  1067. ret = this._events[type].slice();
  1068. return ret;
  1069. };
  1070. EventEmitter.listenerCount = function(emitter, type) {
  1071. var ret;
  1072. if (!emitter._events || !emitter._events[type])
  1073. ret = 0;
  1074. else if (isFunction(emitter._events[type]))
  1075. ret = 1;
  1076. else
  1077. ret = emitter._events[type].length;
  1078. return ret;
  1079. };
  1080. function isFunction(arg) {
  1081. return typeof arg === 'function';
  1082. }
  1083. function isNumber(arg) {
  1084. return typeof arg === 'number';
  1085. }
  1086. function isObject(arg) {
  1087. return typeof arg === 'object' && arg !== null;
  1088. }
  1089. function isUndefined(arg) {
  1090. return arg === void 0;
  1091. }
  1092. },{}]},{},[3])(3)
  1093. });