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 20KB

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