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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  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 focusMucJid, 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);
  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 (!focusMucJid) {
  412. return;
  413. }
  414. var deflate = true;
  415. var content = JSON.stringify(this.statsToBeLogged);
  416. if (deflate) {
  417. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  418. }
  419. content = Base64.encode(content);
  420. // XEP-0337-ish
  421. var message = $msg({to: focusMucJid, type: 'normal'});
  422. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  423. id: 'PeerConnectionStats'});
  424. message.c('message').t(content).up();
  425. if (deflate) {
  426. message.c('tag', {name: "deflated", value: "true"}).up();
  427. }
  428. message.up();
  429. connection.send(message);
  430. // Reset the stats
  431. this.statsToBeLogged.stats = {};
  432. this.statsToBeLogged.timestamps = [];
  433. };
  434. var keyMap = {};
  435. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  436. "ssrc": "ssrc",
  437. "packetsReceived": "packetsReceived",
  438. "packetsLost": "packetsLost",
  439. "packetsSent": "packetsSent",
  440. "bytesReceived": "bytesReceived",
  441. "bytesSent": "bytesSent"
  442. };
  443. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  444. "receiveBandwidth": "googAvailableReceiveBandwidth",
  445. "sendBandwidth": "googAvailableSendBandwidth",
  446. "remoteAddress": "googRemoteAddress",
  447. "transportType": "googTransportType",
  448. "localAddress": "googLocalAddress",
  449. "activeConnection": "googActiveConnection",
  450. "ssrc": "ssrc",
  451. "packetsReceived": "packetsReceived",
  452. "packetsSent": "packetsSent",
  453. "packetsLost": "packetsLost",
  454. "bytesReceived": "bytesReceived",
  455. "bytesSent": "bytesSent",
  456. "googFrameHeightReceived": "googFrameHeightReceived",
  457. "googFrameWidthReceived": "googFrameWidthReceived",
  458. "googFrameHeightSent": "googFrameHeightSent",
  459. "googFrameWidthSent": "googFrameWidthSent",
  460. "audioInputLevel": "audioInputLevel",
  461. "audioOutputLevel": "audioOutputLevel"
  462. };
  463. /**
  464. * Stats processing logic.
  465. */
  466. StatsCollector.prototype.processStatsReport = function () {
  467. if (!this.baselineStatsReport) {
  468. return;
  469. }
  470. for (var idx in this.currentStatsReport) {
  471. var now = this.currentStatsReport[idx];
  472. try {
  473. if (getStatValue(now, 'receiveBandwidth') ||
  474. getStatValue(now, 'sendBandwidth')) {
  475. PeerStats.bandwidth = {
  476. "download": Math.round(
  477. (getStatValue(now, 'receiveBandwidth')) / 1000),
  478. "upload": Math.round(
  479. (getStatValue(now, 'sendBandwidth')) / 1000)
  480. };
  481. }
  482. }
  483. catch(e){/*not supported*/}
  484. if(now.type == 'googCandidatePair')
  485. {
  486. var ip, type, localIP, active;
  487. try {
  488. ip = getStatValue(now, 'remoteAddress');
  489. type = getStatValue(now, "transportType");
  490. localIP = getStatValue(now, "localAddress");
  491. active = getStatValue(now, "activeConnection");
  492. }
  493. catch(e){/*not supported*/}
  494. if(!ip || !type || !localIP || active != "true")
  495. continue;
  496. var addressSaved = false;
  497. for(var i = 0; i < PeerStats.transport.length; i++)
  498. {
  499. if(PeerStats.transport[i].ip == ip &&
  500. PeerStats.transport[i].type == type &&
  501. PeerStats.transport[i].localip == localIP)
  502. {
  503. addressSaved = true;
  504. }
  505. }
  506. if(addressSaved)
  507. continue;
  508. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  509. continue;
  510. }
  511. if(now.type == "candidatepair")
  512. {
  513. if(now.state == "succeeded")
  514. continue;
  515. var local = this.currentStatsReport[now.localCandidateId];
  516. var remote = this.currentStatsReport[now.remoteCandidateId];
  517. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  518. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  519. }
  520. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  521. now.type != "inboundrtp") {
  522. continue;
  523. }
  524. var before = this.baselineStatsReport[idx];
  525. if (!before) {
  526. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  527. continue;
  528. }
  529. var ssrc = getStatValue(now, 'ssrc');
  530. if(!ssrc)
  531. continue;
  532. var jid = ssrc2jid[ssrc];
  533. if (!jid) {
  534. console.warn("No jid for ssrc: " + ssrc);
  535. continue;
  536. }
  537. var jidStats = this.jid2stats[jid];
  538. if (!jidStats) {
  539. jidStats = new PeerStats();
  540. this.jid2stats[jid] = jidStats;
  541. }
  542. var isDownloadStream = true;
  543. var key = 'packetsReceived';
  544. if (!getStatValue(now, key))
  545. {
  546. isDownloadStream = false;
  547. key = 'packetsSent';
  548. if (!getStatValue(now, key))
  549. {
  550. console.warn("No packetsReceived nor packetSent stat found");
  551. continue;
  552. }
  553. }
  554. var packetsNow = getStatValue(now, key);
  555. if(!packetsNow || packetsNow < 0)
  556. packetsNow = 0;
  557. var packetsBefore = getStatValue(before, key);
  558. if(!packetsBefore || packetsBefore < 0)
  559. packetsBefore = 0;
  560. var packetRate = packetsNow - packetsBefore;
  561. if(!packetRate || packetRate < 0)
  562. packetRate = 0;
  563. var currentLoss = getStatValue(now, 'packetsLost');
  564. if(!currentLoss || currentLoss < 0)
  565. currentLoss = 0;
  566. var previousLoss = getStatValue(before, 'packetsLost');
  567. if(!previousLoss || previousLoss < 0)
  568. previousLoss = 0;
  569. var lossRate = currentLoss - previousLoss;
  570. if(!lossRate || lossRate < 0)
  571. lossRate = 0;
  572. var packetsTotal = (packetRate + lossRate);
  573. jidStats.setSsrcLoss(ssrc,
  574. {"packetsTotal": packetsTotal,
  575. "packetsLost": lossRate,
  576. "isDownloadStream": isDownloadStream});
  577. var bytesReceived = 0, bytesSent = 0;
  578. if(getStatValue(now, "bytesReceived"))
  579. {
  580. bytesReceived = getStatValue(now, "bytesReceived") -
  581. getStatValue(before, "bytesReceived");
  582. }
  583. if(getStatValue(now, "bytesSent"))
  584. {
  585. bytesSent = getStatValue(now, "bytesSent") -
  586. getStatValue(before, "bytesSent");
  587. }
  588. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  589. if(bytesReceived <= 0 || time <= 0)
  590. {
  591. bytesReceived = 0;
  592. }
  593. else
  594. {
  595. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  596. }
  597. if(bytesSent <= 0 || time <= 0)
  598. {
  599. bytesSent = 0;
  600. }
  601. else
  602. {
  603. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  604. }
  605. jidStats.setSsrcBitrate(ssrc, {
  606. "download": bytesReceived,
  607. "upload": bytesSent});
  608. var resolution = {height: null, width: null};
  609. try {
  610. if (getStatValue(now, "googFrameHeightReceived") &&
  611. getStatValue(now, "googFrameWidthReceived")) {
  612. resolution.height = getStatValue(now, "googFrameHeightReceived");
  613. resolution.width = getStatValue(now, "googFrameWidthReceived");
  614. }
  615. else if (getStatValue(now, "googFrameHeightSent") &&
  616. getStatValue(now, "googFrameWidthSent")) {
  617. resolution.height = getStatValue(now, "googFrameHeightSent");
  618. resolution.width = getStatValue(now, "googFrameWidthSent");
  619. }
  620. }
  621. catch(e){/*not supported*/}
  622. if(resolution.height && resolution.width)
  623. {
  624. jidStats.setSsrcResolution(ssrc, resolution);
  625. }
  626. else
  627. {
  628. jidStats.setSsrcResolution(ssrc, null);
  629. }
  630. }
  631. var self = this;
  632. // Jid stats
  633. var totalPackets = {download: 0, upload: 0};
  634. var lostPackets = {download: 0, upload: 0};
  635. var bitrateDownload = 0;
  636. var bitrateUpload = 0;
  637. var resolutions = {};
  638. Object.keys(this.jid2stats).forEach(
  639. function (jid)
  640. {
  641. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  642. function (ssrc)
  643. {
  644. var type = "upload";
  645. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  646. type = "download";
  647. totalPackets[type] +=
  648. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  649. lostPackets[type] +=
  650. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  651. }
  652. );
  653. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  654. function (ssrc) {
  655. bitrateDownload +=
  656. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  657. bitrateUpload +=
  658. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  659. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  660. }
  661. );
  662. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  663. }
  664. );
  665. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  666. PeerStats.packetLoss = {
  667. total:
  668. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  669. totalPackets.download + totalPackets.upload),
  670. download:
  671. calculatePacketLoss(lostPackets.download, totalPackets.download),
  672. upload:
  673. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  674. };
  675. this.eventEmitter.emit("statistics.connectionstats",
  676. {
  677. "bitrate": PeerStats.bitrate,
  678. "packetLoss": PeerStats.packetLoss,
  679. "bandwidth": PeerStats.bandwidth,
  680. "resolution": resolutions,
  681. "transport": PeerStats.transport
  682. });
  683. PeerStats.transport = [];
  684. };
  685. /**
  686. * Stats processing logic.
  687. */
  688. StatsCollector.prototype.processAudioLevelReport = function ()
  689. {
  690. if (!this.baselineAudioLevelsReport)
  691. {
  692. return;
  693. }
  694. for (var idx in this.currentAudioLevelsReport)
  695. {
  696. var now = this.currentAudioLevelsReport[idx];
  697. if (now.type != 'ssrc')
  698. {
  699. continue;
  700. }
  701. var before = this.baselineAudioLevelsReport[idx];
  702. if (!before)
  703. {
  704. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  705. continue;
  706. }
  707. var ssrc = getStatValue(now, 'ssrc');
  708. var jid = ssrc2jid[ssrc];
  709. if (!jid)
  710. {
  711. console.warn("No jid for ssrc: " + ssrc);
  712. continue;
  713. }
  714. var jidStats = this.jid2stats[jid];
  715. if (!jidStats)
  716. {
  717. jidStats = new PeerStats();
  718. this.jid2stats[jid] = jidStats;
  719. }
  720. // Audio level
  721. var audioLevel = null;
  722. try {
  723. audioLevel = getStatValue(now, 'audioInputLevel');
  724. if (!audioLevel)
  725. audioLevel = getStatValue(now, 'audioOutputLevel');
  726. }
  727. catch(e) {/*not supported*/
  728. console.warn("Audio Levels are not available in the statistics.");
  729. clearInterval(this.audioLevelsIntervalId);
  730. return;
  731. }
  732. if (audioLevel)
  733. {
  734. // TODO: can't find specs about what this value really is,
  735. // but it seems to vary between 0 and around 32k.
  736. audioLevel = audioLevel / 32767;
  737. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  738. if(jid != connection.emuc.myroomjid)
  739. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  740. }
  741. }
  742. };
  743. },{}],3:[function(require,module,exports){
  744. /**
  745. * Created by hristo on 8/4/14.
  746. */
  747. var LocalStats = require("./LocalStatsCollector.js");
  748. var RTPStats = require("./RTPStatsCollector.js");
  749. var EventEmitter = require("events");
  750. //These lines should be uncommented when require works in app.js
  751. //var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  752. //var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  753. //var XMPPEvents = require("../service/xmpp/XMPPEvents");
  754. var eventEmitter = new EventEmitter();
  755. var localStats = null;
  756. var rtpStats = null;
  757. function stopLocal()
  758. {
  759. if(localStats)
  760. {
  761. localStats.stop();
  762. localStats = null;
  763. }
  764. }
  765. function stopRemote()
  766. {
  767. if(rtpStats)
  768. {
  769. rtpStats.stop();
  770. eventEmitter.emit("statistics.stop");
  771. rtpStats = null;
  772. }
  773. }
  774. function startRemoteStats (peerconnection) {
  775. if (config.enableRtpStats)
  776. {
  777. if(rtpStats)
  778. {
  779. rtpStats.stop();
  780. rtpStats = null;
  781. }
  782. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  783. rtpStats.start();
  784. }
  785. }
  786. function onStreamCreated(stream)
  787. {
  788. if(stream.getAudioTracks().length === 0)
  789. return;
  790. localStats = new LocalStats(stream, 100, this,
  791. eventEmitter);
  792. localStats.start();
  793. }
  794. var statistics =
  795. {
  796. /**
  797. * Indicates that this audio level is for local jid.
  798. * @type {string}
  799. */
  800. LOCAL_JID: 'local',
  801. addAudioLevelListener: function(listener)
  802. {
  803. eventEmitter.on("statistics.audioLevel", listener);
  804. },
  805. removeAudioLevelListener: function(listener)
  806. {
  807. eventEmitter.removeListener("statistics.audioLevel", listener);
  808. },
  809. addConnectionStatsListener: function(listener)
  810. {
  811. eventEmitter.on("statistics.connectionstats", listener);
  812. },
  813. removeConnectionStatsListener: function(listener)
  814. {
  815. eventEmitter.removeListener("statistics.connectionstats", listener);
  816. },
  817. addRemoteStatsStopListener: function(listener)
  818. {
  819. eventEmitter.on("statistics.stop", listener);
  820. },
  821. removeRemoteStatsStopListener: function(listener)
  822. {
  823. eventEmitter.removeListener("statistics.stop", listener);
  824. },
  825. stop: function () {
  826. stopLocal();
  827. stopRemote();
  828. if(eventEmitter)
  829. {
  830. eventEmitter.removeAllListeners();
  831. }
  832. },
  833. stopRemoteStatistics: function()
  834. {
  835. stopRemote();
  836. },
  837. onConferenceCreated: function (event) {
  838. startRemoteStats(event.peerconnection);
  839. },
  840. onDisposeConference: function (onUnload) {
  841. stopRemote();
  842. if(onUnload) {
  843. stopLocal();
  844. eventEmitter.removeAllListeners();
  845. }
  846. },
  847. start: function () {
  848. RTC.addStreamListener(onStreamCreated,
  849. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  850. }
  851. };
  852. module.exports = statistics;
  853. },{"./LocalStatsCollector.js":1,"./RTPStatsCollector.js":2,"events":4}],4:[function(require,module,exports){
  854. // Copyright Joyent, Inc. and other Node contributors.
  855. //
  856. // Permission is hereby granted, free of charge, to any person obtaining a
  857. // copy of this software and associated documentation files (the
  858. // "Software"), to deal in the Software without restriction, including
  859. // without limitation the rights to use, copy, modify, merge, publish,
  860. // distribute, sublicense, and/or sell copies of the Software, and to permit
  861. // persons to whom the Software is furnished to do so, subject to the
  862. // following conditions:
  863. //
  864. // The above copyright notice and this permission notice shall be included
  865. // in all copies or substantial portions of the Software.
  866. //
  867. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  868. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  869. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  870. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  871. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  872. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  873. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  874. function EventEmitter() {
  875. this._events = this._events || {};
  876. this._maxListeners = this._maxListeners || undefined;
  877. }
  878. module.exports = EventEmitter;
  879. // Backwards-compat with node 0.10.x
  880. EventEmitter.EventEmitter = EventEmitter;
  881. EventEmitter.prototype._events = undefined;
  882. EventEmitter.prototype._maxListeners = undefined;
  883. // By default EventEmitters will print a warning if more than 10 listeners are
  884. // added to it. This is a useful default which helps finding memory leaks.
  885. EventEmitter.defaultMaxListeners = 10;
  886. // Obviously not all Emitters should be limited to 10. This function allows
  887. // that to be increased. Set to zero for unlimited.
  888. EventEmitter.prototype.setMaxListeners = function(n) {
  889. if (!isNumber(n) || n < 0 || isNaN(n))
  890. throw TypeError('n must be a positive number');
  891. this._maxListeners = n;
  892. return this;
  893. };
  894. EventEmitter.prototype.emit = function(type) {
  895. var er, handler, len, args, i, listeners;
  896. if (!this._events)
  897. this._events = {};
  898. // If there is no 'error' event listener then throw.
  899. if (type === 'error') {
  900. if (!this._events.error ||
  901. (isObject(this._events.error) && !this._events.error.length)) {
  902. er = arguments[1];
  903. if (er instanceof Error) {
  904. throw er; // Unhandled 'error' event
  905. } else {
  906. throw TypeError('Uncaught, unspecified "error" event.');
  907. }
  908. return false;
  909. }
  910. }
  911. handler = this._events[type];
  912. if (isUndefined(handler))
  913. return false;
  914. if (isFunction(handler)) {
  915. switch (arguments.length) {
  916. // fast cases
  917. case 1:
  918. handler.call(this);
  919. break;
  920. case 2:
  921. handler.call(this, arguments[1]);
  922. break;
  923. case 3:
  924. handler.call(this, arguments[1], arguments[2]);
  925. break;
  926. // slower
  927. default:
  928. len = arguments.length;
  929. args = new Array(len - 1);
  930. for (i = 1; i < len; i++)
  931. args[i - 1] = arguments[i];
  932. handler.apply(this, args);
  933. }
  934. } else if (isObject(handler)) {
  935. len = arguments.length;
  936. args = new Array(len - 1);
  937. for (i = 1; i < len; i++)
  938. args[i - 1] = arguments[i];
  939. listeners = handler.slice();
  940. len = listeners.length;
  941. for (i = 0; i < len; i++)
  942. listeners[i].apply(this, args);
  943. }
  944. return true;
  945. };
  946. EventEmitter.prototype.addListener = function(type, listener) {
  947. var m;
  948. if (!isFunction(listener))
  949. throw TypeError('listener must be a function');
  950. if (!this._events)
  951. this._events = {};
  952. // To avoid recursion in the case that type === "newListener"! Before
  953. // adding it to the listeners, first emit "newListener".
  954. if (this._events.newListener)
  955. this.emit('newListener', type,
  956. isFunction(listener.listener) ?
  957. listener.listener : listener);
  958. if (!this._events[type])
  959. // Optimize the case of one listener. Don't need the extra array object.
  960. this._events[type] = listener;
  961. else if (isObject(this._events[type]))
  962. // If we've already got an array, just append.
  963. this._events[type].push(listener);
  964. else
  965. // Adding the second element, need to change to array.
  966. this._events[type] = [this._events[type], listener];
  967. // Check for listener leak
  968. if (isObject(this._events[type]) && !this._events[type].warned) {
  969. var m;
  970. if (!isUndefined(this._maxListeners)) {
  971. m = this._maxListeners;
  972. } else {
  973. m = EventEmitter.defaultMaxListeners;
  974. }
  975. if (m && m > 0 && this._events[type].length > m) {
  976. this._events[type].warned = true;
  977. console.error('(node) warning: possible EventEmitter memory ' +
  978. 'leak detected. %d listeners added. ' +
  979. 'Use emitter.setMaxListeners() to increase limit.',
  980. this._events[type].length);
  981. if (typeof console.trace === 'function') {
  982. // not supported in IE 10
  983. console.trace();
  984. }
  985. }
  986. }
  987. return this;
  988. };
  989. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  990. EventEmitter.prototype.once = function(type, listener) {
  991. if (!isFunction(listener))
  992. throw TypeError('listener must be a function');
  993. var fired = false;
  994. function g() {
  995. this.removeListener(type, g);
  996. if (!fired) {
  997. fired = true;
  998. listener.apply(this, arguments);
  999. }
  1000. }
  1001. g.listener = listener;
  1002. this.on(type, g);
  1003. return this;
  1004. };
  1005. // emits a 'removeListener' event iff the listener was removed
  1006. EventEmitter.prototype.removeListener = function(type, listener) {
  1007. var list, position, length, i;
  1008. if (!isFunction(listener))
  1009. throw TypeError('listener must be a function');
  1010. if (!this._events || !this._events[type])
  1011. return this;
  1012. list = this._events[type];
  1013. length = list.length;
  1014. position = -1;
  1015. if (list === listener ||
  1016. (isFunction(list.listener) && list.listener === listener)) {
  1017. delete this._events[type];
  1018. if (this._events.removeListener)
  1019. this.emit('removeListener', type, listener);
  1020. } else if (isObject(list)) {
  1021. for (i = length; i-- > 0;) {
  1022. if (list[i] === listener ||
  1023. (list[i].listener && list[i].listener === listener)) {
  1024. position = i;
  1025. break;
  1026. }
  1027. }
  1028. if (position < 0)
  1029. return this;
  1030. if (list.length === 1) {
  1031. list.length = 0;
  1032. delete this._events[type];
  1033. } else {
  1034. list.splice(position, 1);
  1035. }
  1036. if (this._events.removeListener)
  1037. this.emit('removeListener', type, listener);
  1038. }
  1039. return this;
  1040. };
  1041. EventEmitter.prototype.removeAllListeners = function(type) {
  1042. var key, listeners;
  1043. if (!this._events)
  1044. return this;
  1045. // not listening for removeListener, no need to emit
  1046. if (!this._events.removeListener) {
  1047. if (arguments.length === 0)
  1048. this._events = {};
  1049. else if (this._events[type])
  1050. delete this._events[type];
  1051. return this;
  1052. }
  1053. // emit removeListener for all listeners on all events
  1054. if (arguments.length === 0) {
  1055. for (key in this._events) {
  1056. if (key === 'removeListener') continue;
  1057. this.removeAllListeners(key);
  1058. }
  1059. this.removeAllListeners('removeListener');
  1060. this._events = {};
  1061. return this;
  1062. }
  1063. listeners = this._events[type];
  1064. if (isFunction(listeners)) {
  1065. this.removeListener(type, listeners);
  1066. } else {
  1067. // LIFO order
  1068. while (listeners.length)
  1069. this.removeListener(type, listeners[listeners.length - 1]);
  1070. }
  1071. delete this._events[type];
  1072. return this;
  1073. };
  1074. EventEmitter.prototype.listeners = function(type) {
  1075. var ret;
  1076. if (!this._events || !this._events[type])
  1077. ret = [];
  1078. else if (isFunction(this._events[type]))
  1079. ret = [this._events[type]];
  1080. else
  1081. ret = this._events[type].slice();
  1082. return ret;
  1083. };
  1084. EventEmitter.listenerCount = function(emitter, type) {
  1085. var ret;
  1086. if (!emitter._events || !emitter._events[type])
  1087. ret = 0;
  1088. else if (isFunction(emitter._events[type]))
  1089. ret = 1;
  1090. else
  1091. ret = emitter._events[type].length;
  1092. return ret;
  1093. };
  1094. function isFunction(arg) {
  1095. return typeof arg === 'function';
  1096. }
  1097. function isNumber(arg) {
  1098. return typeof arg === 'number';
  1099. }
  1100. function isObject(arg) {
  1101. return typeof arg === 'object' && arg !== null;
  1102. }
  1103. function isUndefined(arg) {
  1104. return arg === void 0;
  1105. }
  1106. },{}]},{},[3])(3)
  1107. });