Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

RTPStatsCollector.js 21KB

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