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.

rtp_sts.js 17KB

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