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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  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, 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 && (Date.now() - now.timestamp) < 3000) {
  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 && (Date.now() - now.timestamp) < 3000)
  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.getOriginalStream().getAudioTracks().length === 0)
  789. return;
  790. localStats = new LocalStats(stream.getOriginalStream(), 100, statistics,
  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. this.addConnectionStatsListener(connection_quality.updateLocalStats);
  849. this.addRemoteStatsStopListener(connection_quality.stopSendingStats);
  850. RTC.addStreamListener(onStreamCreated,
  851. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  852. }
  853. };
  854. module.exports = statistics;
  855. },{"./LocalStatsCollector.js":1,"./RTPStatsCollector.js":2,"events":4}],4:[function(require,module,exports){
  856. // Copyright Joyent, Inc. and other Node contributors.
  857. //
  858. // Permission is hereby granted, free of charge, to any person obtaining a
  859. // copy of this software and associated documentation files (the
  860. // "Software"), to deal in the Software without restriction, including
  861. // without limitation the rights to use, copy, modify, merge, publish,
  862. // distribute, sublicense, and/or sell copies of the Software, and to permit
  863. // persons to whom the Software is furnished to do so, subject to the
  864. // following conditions:
  865. //
  866. // The above copyright notice and this permission notice shall be included
  867. // in all copies or substantial portions of the Software.
  868. //
  869. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  870. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  871. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  872. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  873. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  874. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  875. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  876. function EventEmitter() {
  877. this._events = this._events || {};
  878. this._maxListeners = this._maxListeners || undefined;
  879. }
  880. module.exports = EventEmitter;
  881. // Backwards-compat with node 0.10.x
  882. EventEmitter.EventEmitter = EventEmitter;
  883. EventEmitter.prototype._events = undefined;
  884. EventEmitter.prototype._maxListeners = undefined;
  885. // By default EventEmitters will print a warning if more than 10 listeners are
  886. // added to it. This is a useful default which helps finding memory leaks.
  887. EventEmitter.defaultMaxListeners = 10;
  888. // Obviously not all Emitters should be limited to 10. This function allows
  889. // that to be increased. Set to zero for unlimited.
  890. EventEmitter.prototype.setMaxListeners = function(n) {
  891. if (!isNumber(n) || n < 0 || isNaN(n))
  892. throw TypeError('n must be a positive number');
  893. this._maxListeners = n;
  894. return this;
  895. };
  896. EventEmitter.prototype.emit = function(type) {
  897. var er, handler, len, args, i, listeners;
  898. if (!this._events)
  899. this._events = {};
  900. // If there is no 'error' event listener then throw.
  901. if (type === 'error') {
  902. if (!this._events.error ||
  903. (isObject(this._events.error) && !this._events.error.length)) {
  904. er = arguments[1];
  905. if (er instanceof Error) {
  906. throw er; // Unhandled 'error' event
  907. } else {
  908. throw TypeError('Uncaught, unspecified "error" event.');
  909. }
  910. return false;
  911. }
  912. }
  913. handler = this._events[type];
  914. if (isUndefined(handler))
  915. return false;
  916. if (isFunction(handler)) {
  917. switch (arguments.length) {
  918. // fast cases
  919. case 1:
  920. handler.call(this);
  921. break;
  922. case 2:
  923. handler.call(this, arguments[1]);
  924. break;
  925. case 3:
  926. handler.call(this, arguments[1], arguments[2]);
  927. break;
  928. // slower
  929. default:
  930. len = arguments.length;
  931. args = new Array(len - 1);
  932. for (i = 1; i < len; i++)
  933. args[i - 1] = arguments[i];
  934. handler.apply(this, args);
  935. }
  936. } else if (isObject(handler)) {
  937. len = arguments.length;
  938. args = new Array(len - 1);
  939. for (i = 1; i < len; i++)
  940. args[i - 1] = arguments[i];
  941. listeners = handler.slice();
  942. len = listeners.length;
  943. for (i = 0; i < len; i++)
  944. listeners[i].apply(this, args);
  945. }
  946. return true;
  947. };
  948. EventEmitter.prototype.addListener = function(type, listener) {
  949. var m;
  950. if (!isFunction(listener))
  951. throw TypeError('listener must be a function');
  952. if (!this._events)
  953. this._events = {};
  954. // To avoid recursion in the case that type === "newListener"! Before
  955. // adding it to the listeners, first emit "newListener".
  956. if (this._events.newListener)
  957. this.emit('newListener', type,
  958. isFunction(listener.listener) ?
  959. listener.listener : listener);
  960. if (!this._events[type])
  961. // Optimize the case of one listener. Don't need the extra array object.
  962. this._events[type] = listener;
  963. else if (isObject(this._events[type]))
  964. // If we've already got an array, just append.
  965. this._events[type].push(listener);
  966. else
  967. // Adding the second element, need to change to array.
  968. this._events[type] = [this._events[type], listener];
  969. // Check for listener leak
  970. if (isObject(this._events[type]) && !this._events[type].warned) {
  971. var m;
  972. if (!isUndefined(this._maxListeners)) {
  973. m = this._maxListeners;
  974. } else {
  975. m = EventEmitter.defaultMaxListeners;
  976. }
  977. if (m && m > 0 && this._events[type].length > m) {
  978. this._events[type].warned = true;
  979. console.error('(node) warning: possible EventEmitter memory ' +
  980. 'leak detected. %d listeners added. ' +
  981. 'Use emitter.setMaxListeners() to increase limit.',
  982. this._events[type].length);
  983. if (typeof console.trace === 'function') {
  984. // not supported in IE 10
  985. console.trace();
  986. }
  987. }
  988. }
  989. return this;
  990. };
  991. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  992. EventEmitter.prototype.once = function(type, listener) {
  993. if (!isFunction(listener))
  994. throw TypeError('listener must be a function');
  995. var fired = false;
  996. function g() {
  997. this.removeListener(type, g);
  998. if (!fired) {
  999. fired = true;
  1000. listener.apply(this, arguments);
  1001. }
  1002. }
  1003. g.listener = listener;
  1004. this.on(type, g);
  1005. return this;
  1006. };
  1007. // emits a 'removeListener' event iff the listener was removed
  1008. EventEmitter.prototype.removeListener = function(type, listener) {
  1009. var list, position, length, i;
  1010. if (!isFunction(listener))
  1011. throw TypeError('listener must be a function');
  1012. if (!this._events || !this._events[type])
  1013. return this;
  1014. list = this._events[type];
  1015. length = list.length;
  1016. position = -1;
  1017. if (list === listener ||
  1018. (isFunction(list.listener) && list.listener === listener)) {
  1019. delete this._events[type];
  1020. if (this._events.removeListener)
  1021. this.emit('removeListener', type, listener);
  1022. } else if (isObject(list)) {
  1023. for (i = length; i-- > 0;) {
  1024. if (list[i] === listener ||
  1025. (list[i].listener && list[i].listener === listener)) {
  1026. position = i;
  1027. break;
  1028. }
  1029. }
  1030. if (position < 0)
  1031. return this;
  1032. if (list.length === 1) {
  1033. list.length = 0;
  1034. delete this._events[type];
  1035. } else {
  1036. list.splice(position, 1);
  1037. }
  1038. if (this._events.removeListener)
  1039. this.emit('removeListener', type, listener);
  1040. }
  1041. return this;
  1042. };
  1043. EventEmitter.prototype.removeAllListeners = function(type) {
  1044. var key, listeners;
  1045. if (!this._events)
  1046. return this;
  1047. // not listening for removeListener, no need to emit
  1048. if (!this._events.removeListener) {
  1049. if (arguments.length === 0)
  1050. this._events = {};
  1051. else if (this._events[type])
  1052. delete this._events[type];
  1053. return this;
  1054. }
  1055. // emit removeListener for all listeners on all events
  1056. if (arguments.length === 0) {
  1057. for (key in this._events) {
  1058. if (key === 'removeListener') continue;
  1059. this.removeAllListeners(key);
  1060. }
  1061. this.removeAllListeners('removeListener');
  1062. this._events = {};
  1063. return this;
  1064. }
  1065. listeners = this._events[type];
  1066. if (isFunction(listeners)) {
  1067. this.removeListener(type, listeners);
  1068. } else {
  1069. // LIFO order
  1070. while (listeners.length)
  1071. this.removeListener(type, listeners[listeners.length - 1]);
  1072. }
  1073. delete this._events[type];
  1074. return this;
  1075. };
  1076. EventEmitter.prototype.listeners = function(type) {
  1077. var ret;
  1078. if (!this._events || !this._events[type])
  1079. ret = [];
  1080. else if (isFunction(this._events[type]))
  1081. ret = [this._events[type]];
  1082. else
  1083. ret = this._events[type].slice();
  1084. return ret;
  1085. };
  1086. EventEmitter.listenerCount = function(emitter, type) {
  1087. var ret;
  1088. if (!emitter._events || !emitter._events[type])
  1089. ret = 0;
  1090. else if (isFunction(emitter._events[type]))
  1091. ret = 1;
  1092. else
  1093. ret = emitter._events[type].length;
  1094. return ret;
  1095. };
  1096. function isFunction(arg) {
  1097. return typeof arg === 'function';
  1098. }
  1099. function isNumber(arg) {
  1100. return typeof arg === 'number';
  1101. }
  1102. function isObject(arg) {
  1103. return typeof arg === 'object' && arg !== null;
  1104. }
  1105. function isUndefined(arg) {
  1106. return arg === void 0;
  1107. }
  1108. },{}]},{},[3])(3)
  1109. });