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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  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. this.audioLevelsIntervalId = setInterval(
  196. function ()
  197. {
  198. // Interval updates
  199. self.peerconnection.getStats(
  200. function (report)
  201. {
  202. var results = null;
  203. if(!report || !report.result || typeof report.result != 'function')
  204. {
  205. results = report;
  206. }
  207. else
  208. {
  209. results = report.result();
  210. }
  211. //console.error("Got interval report", results);
  212. self.currentAudioLevelsReport = results;
  213. self.processAudioLevelReport();
  214. self.baselineAudioLevelsReport =
  215. self.currentAudioLevelsReport;
  216. },
  217. self.errorCallback
  218. );
  219. },
  220. self.audioLevelsIntervalMilis
  221. );
  222. this.statsIntervalId = setInterval(
  223. function () {
  224. // Interval updates
  225. self.peerconnection.getStats(
  226. function (report)
  227. {
  228. var results = null;
  229. if(!report || !report.result || typeof report.result != 'function')
  230. {
  231. //firefox
  232. results = report;
  233. }
  234. else
  235. {
  236. //chrome
  237. results = report.result();
  238. }
  239. //console.error("Got interval report", results);
  240. self.currentStatsReport = results;
  241. try
  242. {
  243. self.processStatsReport();
  244. }
  245. catch (e)
  246. {
  247. console.error("Unsupported key:" + e, e);
  248. }
  249. self.baselineStatsReport = self.currentStatsReport;
  250. },
  251. self.errorCallback
  252. );
  253. },
  254. self.statsIntervalMilis
  255. );
  256. if (config.logStats) {
  257. this.gatherStatsIntervalId = setInterval(
  258. function () {
  259. self.peerconnection.getStats(
  260. function (report) {
  261. self.addStatsToBeLogged(report.result());
  262. },
  263. function () {
  264. }
  265. );
  266. },
  267. this.GATHER_INTERVAL
  268. );
  269. this.logStatsIntervalId = setInterval(
  270. function() { self.logStats(); },
  271. this.LOG_INTERVAL);
  272. }
  273. };
  274. /**
  275. * Converts the stats to the format used for logging, and saves the data in
  276. * this.statsToBeLogged.
  277. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  278. */
  279. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  280. var self = this;
  281. var num_records = this.statsToBeLogged.timestamps.length;
  282. this.statsToBeLogged.timestamps.push(new Date().getTime());
  283. reports.map(function (report) {
  284. var stat = self.statsToBeLogged.stats[report.id];
  285. if (!stat) {
  286. stat = self.statsToBeLogged.stats[report.id] = {};
  287. }
  288. stat.type = report.type;
  289. report.names().map(function (name) {
  290. var values = stat[name];
  291. if (!values) {
  292. values = stat[name] = [];
  293. }
  294. while (values.length < num_records) {
  295. values.push(null);
  296. }
  297. values.push(report.stat(name));
  298. });
  299. });
  300. };
  301. StatsCollector.prototype.logStats = function () {
  302. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  303. return;
  304. // Reset the stats
  305. this.statsToBeLogged.stats = {};
  306. this.statsToBeLogged.timestamps = [];
  307. };
  308. var keyMap = {};
  309. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  310. "ssrc": "ssrc",
  311. "packetsReceived": "packetsReceived",
  312. "packetsLost": "packetsLost",
  313. "packetsSent": "packetsSent",
  314. "bytesReceived": "bytesReceived",
  315. "bytesSent": "bytesSent"
  316. };
  317. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  318. "receiveBandwidth": "googAvailableReceiveBandwidth",
  319. "sendBandwidth": "googAvailableSendBandwidth",
  320. "remoteAddress": "googRemoteAddress",
  321. "transportType": "googTransportType",
  322. "localAddress": "googLocalAddress",
  323. "activeConnection": "googActiveConnection",
  324. "ssrc": "ssrc",
  325. "packetsReceived": "packetsReceived",
  326. "packetsSent": "packetsSent",
  327. "packetsLost": "packetsLost",
  328. "bytesReceived": "bytesReceived",
  329. "bytesSent": "bytesSent",
  330. "googFrameHeightReceived": "googFrameHeightReceived",
  331. "googFrameWidthReceived": "googFrameWidthReceived",
  332. "googFrameHeightSent": "googFrameHeightSent",
  333. "googFrameWidthSent": "googFrameWidthSent",
  334. "audioInputLevel": "audioInputLevel",
  335. "audioOutputLevel": "audioOutputLevel"
  336. };
  337. /**
  338. * Stats processing logic.
  339. */
  340. StatsCollector.prototype.processStatsReport = function () {
  341. if (!this.baselineStatsReport) {
  342. return;
  343. }
  344. for (var idx in this.currentStatsReport) {
  345. var now = this.currentStatsReport[idx];
  346. try {
  347. if (getStatValue(now, 'receiveBandwidth') ||
  348. getStatValue(now, 'sendBandwidth')) {
  349. PeerStats.bandwidth = {
  350. "download": Math.round(
  351. (getStatValue(now, 'receiveBandwidth')) / 1000),
  352. "upload": Math.round(
  353. (getStatValue(now, 'sendBandwidth')) / 1000)
  354. };
  355. }
  356. }
  357. catch(e){/*not supported*/}
  358. if(now.type == 'googCandidatePair')
  359. {
  360. var ip, type, localIP, active;
  361. try {
  362. ip = getStatValue(now, 'remoteAddress');
  363. type = getStatValue(now, "transportType");
  364. localIP = getStatValue(now, "localAddress");
  365. active = getStatValue(now, "activeConnection");
  366. }
  367. catch(e){/*not supported*/}
  368. if(!ip || !type || !localIP || active != "true")
  369. continue;
  370. var addressSaved = false;
  371. for(var i = 0; i < PeerStats.transport.length; i++)
  372. {
  373. if(PeerStats.transport[i].ip == ip &&
  374. PeerStats.transport[i].type == type &&
  375. PeerStats.transport[i].localip == localIP)
  376. {
  377. addressSaved = true;
  378. }
  379. }
  380. if(addressSaved)
  381. continue;
  382. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  383. continue;
  384. }
  385. if(now.type == "candidatepair")
  386. {
  387. if(now.state == "succeeded")
  388. continue;
  389. var local = this.currentStatsReport[now.localCandidateId];
  390. var remote = this.currentStatsReport[now.remoteCandidateId];
  391. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  392. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  393. }
  394. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  395. now.type != "inboundrtp") {
  396. continue;
  397. }
  398. var before = this.baselineStatsReport[idx];
  399. if (!before) {
  400. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  401. continue;
  402. }
  403. var ssrc = getStatValue(now, 'ssrc');
  404. if(!ssrc)
  405. continue;
  406. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  407. if (!jid && (Date.now() - now.timestamp) < 3000) {
  408. console.warn("No jid for ssrc: " + ssrc);
  409. continue;
  410. }
  411. var jidStats = this.jid2stats[jid];
  412. if (!jidStats) {
  413. jidStats = new PeerStats();
  414. this.jid2stats[jid] = jidStats;
  415. }
  416. var isDownloadStream = true;
  417. var key = 'packetsReceived';
  418. if (!getStatValue(now, key))
  419. {
  420. isDownloadStream = false;
  421. key = 'packetsSent';
  422. if (!getStatValue(now, key))
  423. {
  424. console.warn("No packetsReceived nor packetSent stat found");
  425. continue;
  426. }
  427. }
  428. var packetsNow = getStatValue(now, key);
  429. if(!packetsNow || packetsNow < 0)
  430. packetsNow = 0;
  431. var packetsBefore = getStatValue(before, key);
  432. if(!packetsBefore || packetsBefore < 0)
  433. packetsBefore = 0;
  434. var packetRate = packetsNow - packetsBefore;
  435. if(!packetRate || packetRate < 0)
  436. packetRate = 0;
  437. var currentLoss = getStatValue(now, 'packetsLost');
  438. if(!currentLoss || currentLoss < 0)
  439. currentLoss = 0;
  440. var previousLoss = getStatValue(before, 'packetsLost');
  441. if(!previousLoss || previousLoss < 0)
  442. previousLoss = 0;
  443. var lossRate = currentLoss - previousLoss;
  444. if(!lossRate || lossRate < 0)
  445. lossRate = 0;
  446. var packetsTotal = (packetRate + lossRate);
  447. jidStats.setSsrcLoss(ssrc,
  448. {"packetsTotal": packetsTotal,
  449. "packetsLost": lossRate,
  450. "isDownloadStream": isDownloadStream});
  451. var bytesReceived = 0, bytesSent = 0;
  452. if(getStatValue(now, "bytesReceived"))
  453. {
  454. bytesReceived = getStatValue(now, "bytesReceived") -
  455. getStatValue(before, "bytesReceived");
  456. }
  457. if(getStatValue(now, "bytesSent"))
  458. {
  459. bytesSent = getStatValue(now, "bytesSent") -
  460. getStatValue(before, "bytesSent");
  461. }
  462. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  463. if(bytesReceived <= 0 || time <= 0)
  464. {
  465. bytesReceived = 0;
  466. }
  467. else
  468. {
  469. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  470. }
  471. if(bytesSent <= 0 || time <= 0)
  472. {
  473. bytesSent = 0;
  474. }
  475. else
  476. {
  477. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  478. }
  479. jidStats.setSsrcBitrate(ssrc, {
  480. "download": bytesReceived,
  481. "upload": bytesSent});
  482. var resolution = {height: null, width: null};
  483. try {
  484. if (getStatValue(now, "googFrameHeightReceived") &&
  485. getStatValue(now, "googFrameWidthReceived")) {
  486. resolution.height = getStatValue(now, "googFrameHeightReceived");
  487. resolution.width = getStatValue(now, "googFrameWidthReceived");
  488. }
  489. else if (getStatValue(now, "googFrameHeightSent") &&
  490. getStatValue(now, "googFrameWidthSent")) {
  491. resolution.height = getStatValue(now, "googFrameHeightSent");
  492. resolution.width = getStatValue(now, "googFrameWidthSent");
  493. }
  494. }
  495. catch(e){/*not supported*/}
  496. if(resolution.height && resolution.width)
  497. {
  498. jidStats.setSsrcResolution(ssrc, resolution);
  499. }
  500. else
  501. {
  502. jidStats.setSsrcResolution(ssrc, null);
  503. }
  504. }
  505. var self = this;
  506. // Jid stats
  507. var totalPackets = {download: 0, upload: 0};
  508. var lostPackets = {download: 0, upload: 0};
  509. var bitrateDownload = 0;
  510. var bitrateUpload = 0;
  511. var resolutions = {};
  512. Object.keys(this.jid2stats).forEach(
  513. function (jid)
  514. {
  515. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  516. function (ssrc)
  517. {
  518. var type = "upload";
  519. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  520. type = "download";
  521. totalPackets[type] +=
  522. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  523. lostPackets[type] +=
  524. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  525. }
  526. );
  527. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  528. function (ssrc) {
  529. bitrateDownload +=
  530. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  531. bitrateUpload +=
  532. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  533. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  534. }
  535. );
  536. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  537. }
  538. );
  539. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  540. PeerStats.packetLoss = {
  541. total:
  542. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  543. totalPackets.download + totalPackets.upload),
  544. download:
  545. calculatePacketLoss(lostPackets.download, totalPackets.download),
  546. upload:
  547. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  548. };
  549. this.eventEmitter.emit("statistics.connectionstats",
  550. {
  551. "bitrate": PeerStats.bitrate,
  552. "packetLoss": PeerStats.packetLoss,
  553. "bandwidth": PeerStats.bandwidth,
  554. "resolution": resolutions,
  555. "transport": PeerStats.transport
  556. });
  557. PeerStats.transport = [];
  558. };
  559. /**
  560. * Stats processing logic.
  561. */
  562. StatsCollector.prototype.processAudioLevelReport = function ()
  563. {
  564. if (!this.baselineAudioLevelsReport)
  565. {
  566. return;
  567. }
  568. for (var idx in this.currentAudioLevelsReport)
  569. {
  570. var now = this.currentAudioLevelsReport[idx];
  571. if (now.type != 'ssrc')
  572. {
  573. continue;
  574. }
  575. var before = this.baselineAudioLevelsReport[idx];
  576. if (!before)
  577. {
  578. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  579. continue;
  580. }
  581. var ssrc = getStatValue(now, 'ssrc');
  582. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  583. if (!jid && (Date.now() - now.timestamp) < 3000)
  584. {
  585. console.warn("No jid for ssrc: " + ssrc);
  586. continue;
  587. }
  588. var jidStats = this.jid2stats[jid];
  589. if (!jidStats)
  590. {
  591. jidStats = new PeerStats();
  592. this.jid2stats[jid] = jidStats;
  593. }
  594. // Audio level
  595. var audioLevel = null;
  596. try {
  597. audioLevel = getStatValue(now, 'audioInputLevel');
  598. if (!audioLevel)
  599. audioLevel = getStatValue(now, 'audioOutputLevel');
  600. }
  601. catch(e) {/*not supported*/
  602. console.warn("Audio Levels are not available in the statistics.");
  603. clearInterval(this.audioLevelsIntervalId);
  604. return;
  605. }
  606. if (audioLevel)
  607. {
  608. // TODO: can't find specs about what this value really is,
  609. // but it seems to vary between 0 and around 32k.
  610. audioLevel = audioLevel / 32767;
  611. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  612. if(jid != APP.xmpp.myJid())
  613. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  614. }
  615. }
  616. };