您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RTPStatsCollector.js 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. /* global focusMucJid, 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.browser][name])
  17. throw "The property isn't supported!";
  18. var key = keyMap[RTC.browser][name];
  19. return 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);
  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 (!focusMucJid) {
  302. return;
  303. }
  304. var deflate = true;
  305. var content = JSON.stringify(this.statsToBeLogged);
  306. if (deflate) {
  307. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  308. }
  309. content = Base64.encode(content);
  310. // XEP-0337-ish
  311. var message = $msg({to: focusMucJid, type: 'normal'});
  312. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  313. id: 'PeerConnectionStats'});
  314. message.c('message').t(content).up();
  315. if (deflate) {
  316. message.c('tag', {name: "deflated", value: "true"}).up();
  317. }
  318. message.up();
  319. connection.send(message);
  320. // Reset the stats
  321. this.statsToBeLogged.stats = {};
  322. this.statsToBeLogged.timestamps = [];
  323. };
  324. var keyMap = {
  325. "firefox": {
  326. "ssrc": "ssrc",
  327. "packetsReceived": "packetsReceived",
  328. "packetsLost": "packetsLost",
  329. "packetsSent": "packetsSent",
  330. "bytesReceived": "bytesReceived",
  331. "bytesSent": "bytesSent"
  332. },
  333. "chrome": {
  334. "receiveBandwidth": "googAvailableReceiveBandwidth",
  335. "sendBandwidth": "googAvailableSendBandwidth",
  336. "remoteAddress": "googRemoteAddress",
  337. "transportType": "googTransportType",
  338. "localAddress": "googLocalAddress",
  339. "activeConnection": "googActiveConnection",
  340. "ssrc": "ssrc",
  341. "packetsReceived": "packetsReceived",
  342. "packetsSent": "packetsSent",
  343. "packetsLost": "packetsLost",
  344. "bytesReceived": "bytesReceived",
  345. "bytesSent": "bytesSent",
  346. "googFrameHeightReceived": "googFrameHeightReceived",
  347. "googFrameWidthReceived": "googFrameWidthReceived",
  348. "googFrameHeightSent": "googFrameHeightSent",
  349. "googFrameWidthSent": "googFrameWidthSent",
  350. "audioInputLevel": "audioInputLevel",
  351. "audioOutputLevel": "audioOutputLevel"
  352. }
  353. };
  354. /**
  355. * Stats processing logic.
  356. */
  357. StatsCollector.prototype.processStatsReport = function () {
  358. if (!this.baselineStatsReport) {
  359. return;
  360. }
  361. for (var idx in this.currentStatsReport) {
  362. var now = this.currentStatsReport[idx];
  363. try {
  364. if (getStatValue(now, 'receiveBandwidth') ||
  365. getStatValue(now, 'sendBandwidth')) {
  366. PeerStats.bandwidth = {
  367. "download": Math.round(
  368. (getStatValue(now, 'receiveBandwidth')) / 1000),
  369. "upload": Math.round(
  370. (getStatValue(now, 'sendBandwidth')) / 1000)
  371. };
  372. }
  373. }
  374. catch(e){/*not supported*/}
  375. if(now.type == 'googCandidatePair')
  376. {
  377. var ip, type, localIP, active;
  378. try {
  379. ip = getStatValue(now, 'remoteAddress');
  380. type = getStatValue(now, "transportType");
  381. localIP = getStatValue(now, "localAddress");
  382. active = getStatValue(now, "activeConnection");
  383. }
  384. catch(e){/*not supported*/}
  385. if(!ip || !type || !localIP || active != "true")
  386. continue;
  387. var addressSaved = false;
  388. for(var i = 0; i < PeerStats.transport.length; i++)
  389. {
  390. if(PeerStats.transport[i].ip == ip &&
  391. PeerStats.transport[i].type == type &&
  392. PeerStats.transport[i].localip == localIP)
  393. {
  394. addressSaved = true;
  395. }
  396. }
  397. if(addressSaved)
  398. continue;
  399. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  400. continue;
  401. }
  402. if(now.type == "candidatepair")
  403. {
  404. if(now.state == "succeeded")
  405. continue;
  406. var local = this.currentStatsReport[now.localCandidateId];
  407. var remote = this.currentStatsReport[now.remoteCandidateId];
  408. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  409. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  410. }
  411. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  412. now.type != "inboundrtp") {
  413. continue;
  414. }
  415. var before = this.baselineStatsReport[idx];
  416. if (!before) {
  417. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  418. continue;
  419. }
  420. var ssrc = getStatValue(now, 'ssrc');
  421. if(!ssrc)
  422. continue;
  423. var jid = ssrc2jid[ssrc];
  424. if (!jid) {
  425. console.warn("No jid for ssrc: " + ssrc);
  426. continue;
  427. }
  428. var jidStats = this.jid2stats[jid];
  429. if (!jidStats) {
  430. jidStats = new PeerStats();
  431. this.jid2stats[jid] = jidStats;
  432. }
  433. var isDownloadStream = true;
  434. var key = 'packetsReceived';
  435. if (!getStatValue(now, key))
  436. {
  437. isDownloadStream = false;
  438. key = 'packetsSent';
  439. if (!getStatValue(now, key))
  440. {
  441. console.warn("No packetsReceived nor packetSent stat found");
  442. continue;
  443. }
  444. }
  445. var packetsNow = getStatValue(now, key);
  446. if(!packetsNow || packetsNow < 0)
  447. packetsNow = 0;
  448. var packetsBefore = getStatValue(before, key);
  449. if(!packetsBefore || packetsBefore < 0)
  450. packetsBefore = 0;
  451. var packetRate = packetsNow - packetsBefore;
  452. if(!packetRate || packetRate < 0)
  453. packetRate = 0;
  454. var currentLoss = getStatValue(now, 'packetsLost');
  455. if(!currentLoss || currentLoss < 0)
  456. currentLoss = 0;
  457. var previousLoss = getStatValue(before, 'packetsLost');
  458. if(!previousLoss || previousLoss < 0)
  459. previousLoss = 0;
  460. var lossRate = currentLoss - previousLoss;
  461. if(!lossRate || lossRate < 0)
  462. lossRate = 0;
  463. var packetsTotal = (packetRate + lossRate);
  464. jidStats.setSsrcLoss(ssrc,
  465. {"packetsTotal": packetsTotal,
  466. "packetsLost": lossRate,
  467. "isDownloadStream": isDownloadStream});
  468. var bytesReceived = 0, bytesSent = 0;
  469. if(getStatValue(now, "bytesReceived"))
  470. {
  471. bytesReceived = getStatValue(now, "bytesReceived") -
  472. getStatValue(before, "bytesReceived");
  473. }
  474. if(getStatValue(now, "bytesSent"))
  475. {
  476. bytesSent = getStatValue(now, "bytesSent") -
  477. getStatValue(before, "bytesSent");
  478. }
  479. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  480. if(bytesReceived <= 0 || time <= 0)
  481. {
  482. bytesReceived = 0;
  483. }
  484. else
  485. {
  486. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  487. }
  488. if(bytesSent <= 0 || time <= 0)
  489. {
  490. bytesSent = 0;
  491. }
  492. else
  493. {
  494. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  495. }
  496. jidStats.setSsrcBitrate(ssrc, {
  497. "download": bytesReceived,
  498. "upload": bytesSent});
  499. var resolution = {height: null, width: null};
  500. try {
  501. if (getStatValue(now, "googFrameHeightReceived") &&
  502. getStatValue(now, "googFrameWidthReceived")) {
  503. resolution.height = getStatValue(now, "googFrameHeightReceived");
  504. resolution.width = getStatValue(now, "googFrameWidthReceived");
  505. }
  506. else if (getStatValue(now, "googFrameHeightSent") &&
  507. getStatValue(now, "googFrameWidthSent")) {
  508. resolution.height = getStatValue(now, "googFrameHeightSent");
  509. resolution.width = getStatValue(now, "googFrameWidthSent");
  510. }
  511. }
  512. catch(e){/*not supported*/}
  513. if(resolution.height && resolution.width)
  514. {
  515. jidStats.setSsrcResolution(ssrc, resolution);
  516. }
  517. else
  518. {
  519. jidStats.setSsrcResolution(ssrc, null);
  520. }
  521. }
  522. var self = this;
  523. // Jid stats
  524. var totalPackets = {download: 0, upload: 0};
  525. var lostPackets = {download: 0, upload: 0};
  526. var bitrateDownload = 0;
  527. var bitrateUpload = 0;
  528. var resolutions = {};
  529. Object.keys(this.jid2stats).forEach(
  530. function (jid)
  531. {
  532. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  533. function (ssrc)
  534. {
  535. var type = "upload";
  536. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  537. type = "download";
  538. totalPackets[type] +=
  539. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  540. lostPackets[type] +=
  541. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  542. }
  543. );
  544. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  545. function (ssrc) {
  546. bitrateDownload +=
  547. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  548. bitrateUpload +=
  549. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  550. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  551. }
  552. );
  553. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  554. }
  555. );
  556. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  557. PeerStats.packetLoss = {
  558. total:
  559. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  560. totalPackets.download + totalPackets.upload),
  561. download:
  562. calculatePacketLoss(lostPackets.download, totalPackets.download),
  563. upload:
  564. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  565. };
  566. this.eventEmitter.emit("statistics.connectionstats",
  567. {
  568. "bitrate": PeerStats.bitrate,
  569. "packetLoss": PeerStats.packetLoss,
  570. "bandwidth": PeerStats.bandwidth,
  571. "resolution": resolutions,
  572. "transport": PeerStats.transport
  573. });
  574. PeerStats.transport = [];
  575. };
  576. /**
  577. * Stats processing logic.
  578. */
  579. StatsCollector.prototype.processAudioLevelReport = function ()
  580. {
  581. if (!this.baselineAudioLevelsReport)
  582. {
  583. return;
  584. }
  585. for (var idx in this.currentAudioLevelsReport)
  586. {
  587. var now = this.currentAudioLevelsReport[idx];
  588. if (now.type != 'ssrc')
  589. {
  590. continue;
  591. }
  592. var before = this.baselineAudioLevelsReport[idx];
  593. if (!before)
  594. {
  595. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  596. continue;
  597. }
  598. var ssrc = getStatValue(now, 'ssrc');
  599. var jid = ssrc2jid[ssrc];
  600. if (!jid)
  601. {
  602. console.warn("No jid for ssrc: " + ssrc);
  603. continue;
  604. }
  605. var jidStats = this.jid2stats[jid];
  606. if (!jidStats)
  607. {
  608. jidStats = new PeerStats();
  609. this.jid2stats[jid] = jidStats;
  610. }
  611. // Audio level
  612. var audioLevel = null;
  613. try {
  614. audioLevel = getStatValue(now, 'audioInputLevel');
  615. if (!audioLevel)
  616. audioLevel = getStatValue(now, 'audioOutputLevel');
  617. }
  618. catch(e) {/*not supported*/
  619. console.warn("Audio Levels are not available in the statistics.");
  620. clearInterval(this.audioLevelsIntervalId);
  621. return;
  622. }
  623. if (audioLevel)
  624. {
  625. // TODO: can't find specs about what this value really is,
  626. // but it seems to vary between 0 and around 32k.
  627. audioLevel = audioLevel / 32767;
  628. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  629. if(jid != connection.emuc.myroomjid)
  630. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  631. }
  632. }
  633. };