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

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