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.

RTPStatsCollector.js 21KB

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