Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

rtp_sts.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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. if (!focusJid) {
  266. return;
  267. }
  268. var deflate = true;
  269. var content = JSON.stringify(this.statsToBeLogged);
  270. if (deflate) {
  271. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  272. }
  273. content = Base64.encode(content);
  274. // XEP-0337-ish
  275. var message = $msg({to: focusJid, type: 'normal'});
  276. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  277. id: 'PeerConnectionStats'});
  278. message.c('message').t(content).up();
  279. if (deflate) {
  280. message.c('tag', {name: "deflated", value: "true"}).up();
  281. }
  282. message.up();
  283. connection.send(message);
  284. // Reset the stats
  285. this.statsToBeLogged.stats = {};
  286. this.statsToBeLogged.timestamps = [];
  287. };
  288. /**
  289. * Stats processing logic.
  290. */
  291. StatsCollector.prototype.processStatsReport = function () {
  292. if (!this.baselineStatsReport) {
  293. return;
  294. }
  295. for (var idx in this.currentStatsReport) {
  296. var now = this.currentStatsReport[idx];
  297. if (now.stat('googAvailableReceiveBandwidth') ||
  298. now.stat('googAvailableSendBandwidth'))
  299. {
  300. PeerStats.bandwidth = {
  301. "download": Math.round(
  302. (now.stat('googAvailableReceiveBandwidth')) / 1000),
  303. "upload": Math.round(
  304. (now.stat('googAvailableSendBandwidth')) / 1000)
  305. };
  306. }
  307. if(now.type == 'googCandidatePair')
  308. {
  309. var ip = now.stat('googRemoteAddress');
  310. var type = now.stat("googTransportType");
  311. var localIP = now.stat("googLocalAddress");
  312. var active = now.stat("googActiveConnection");
  313. if(!ip || !type || !localIP || active != "true")
  314. continue;
  315. var addressSaved = false;
  316. for(var i = 0; i < PeerStats.transport.length; i++)
  317. {
  318. if(PeerStats.transport[i].ip == ip &&
  319. PeerStats.transport[i].type == type &&
  320. PeerStats.transport[i].localip == localIP)
  321. {
  322. addressSaved = true;
  323. }
  324. }
  325. if(addressSaved)
  326. continue;
  327. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  328. continue;
  329. }
  330. if (now.type != 'ssrc') {
  331. continue;
  332. }
  333. var before = this.baselineStatsReport[idx];
  334. if (!before) {
  335. console.warn(now.stat('ssrc') + ' not enough data');
  336. continue;
  337. }
  338. var ssrc = now.stat('ssrc');
  339. var jid = ssrc2jid[ssrc];
  340. if (!jid) {
  341. console.warn("No jid for ssrc: " + ssrc);
  342. continue;
  343. }
  344. var jidStats = this.jid2stats[jid];
  345. if (!jidStats) {
  346. jidStats = new PeerStats();
  347. this.jid2stats[jid] = jidStats;
  348. }
  349. var isDownloadStream = true;
  350. var key = 'packetsReceived';
  351. if (!now.stat(key))
  352. {
  353. isDownloadStream = false;
  354. key = 'packetsSent';
  355. if (!now.stat(key))
  356. {
  357. console.error("No packetsReceived nor packetSent stat found");
  358. this.stop();
  359. return;
  360. }
  361. }
  362. var packetsNow = now.stat(key);
  363. if(!packetsNow || packetsNow < 0)
  364. packetsNow = 0;
  365. var packetsBefore = before.stat(key);
  366. if(!packetsBefore || packetsBefore < 0)
  367. packetsBefore = 0;
  368. var packetRate = packetsNow - packetsBefore;
  369. if(!packetRate || packetRate < 0)
  370. packetRate = 0;
  371. var currentLoss = now.stat('packetsLost');
  372. if(!currentLoss || currentLoss < 0)
  373. currentLoss = 0;
  374. var previousLoss = before.stat('packetsLost');
  375. if(!previousLoss || previousLoss < 0)
  376. previousLoss = 0;
  377. var lossRate = currentLoss - previousLoss;
  378. if(!lossRate || lossRate < 0)
  379. lossRate = 0;
  380. var packetsTotal = (packetRate + lossRate);
  381. jidStats.setSsrcLoss(ssrc,
  382. {"packetsTotal": packetsTotal,
  383. "packetsLost": lossRate,
  384. "isDownloadStream": isDownloadStream});
  385. var bytesReceived = 0, bytesSent = 0;
  386. if(now.stat("bytesReceived"))
  387. {
  388. bytesReceived = now.stat("bytesReceived") -
  389. before.stat("bytesReceived");
  390. }
  391. if(now.stat("bytesSent"))
  392. {
  393. bytesSent = now.stat("bytesSent") - before.stat("bytesSent");
  394. }
  395. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  396. if(bytesReceived <= 0 || time <= 0)
  397. {
  398. bytesReceived = 0;
  399. }
  400. else
  401. {
  402. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  403. }
  404. if(bytesSent <= 0 || time <= 0)
  405. {
  406. bytesSent = 0;
  407. }
  408. else
  409. {
  410. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  411. }
  412. jidStats.setSsrcBitrate(ssrc, {
  413. "download": bytesReceived,
  414. "upload": bytesSent});
  415. var resolution = {height: null, width: null};
  416. if(now.stat("googFrameHeightReceived") &&
  417. now.stat("googFrameWidthReceived"))
  418. {
  419. resolution.height = now.stat("googFrameHeightReceived");
  420. resolution.width = now.stat("googFrameWidthReceived");
  421. }
  422. else if(now.stat("googFrameHeightSent") &&
  423. now.stat("googFrameWidthSent"))
  424. {
  425. resolution.height = now.stat("googFrameHeightSent");
  426. resolution.width = now.stat("googFrameWidthSent");
  427. }
  428. if(resolution.height && resolution.width)
  429. {
  430. jidStats.setSsrcResolution(ssrc, resolution);
  431. }
  432. else
  433. {
  434. jidStats.setSsrcResolution(ssrc, null);
  435. }
  436. }
  437. var self = this;
  438. // Jid stats
  439. var totalPackets = {download: 0, upload: 0};
  440. var lostPackets = {download: 0, upload: 0};
  441. var bitrateDownload = 0;
  442. var bitrateUpload = 0;
  443. var resolutions = {};
  444. Object.keys(this.jid2stats).forEach(
  445. function (jid)
  446. {
  447. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  448. function (ssrc)
  449. {
  450. var type = "upload";
  451. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  452. type = "download";
  453. totalPackets[type] +=
  454. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  455. lostPackets[type] +=
  456. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  457. }
  458. );
  459. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  460. function (ssrc) {
  461. bitrateDownload +=
  462. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  463. bitrateUpload +=
  464. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  465. }
  466. );
  467. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  468. }
  469. );
  470. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  471. PeerStats.packetLoss = {
  472. total:
  473. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  474. totalPackets.download + totalPackets.upload),
  475. download:
  476. calculatePacketLoss(lostPackets.download, totalPackets.download),
  477. upload:
  478. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  479. };
  480. this.statsUpdateCallback(
  481. {
  482. "bitrate": PeerStats.bitrate,
  483. "packetLoss": PeerStats.packetLoss,
  484. "bandwidth": PeerStats.bandwidth,
  485. "resolution": resolutions,
  486. "transport": PeerStats.transport
  487. });
  488. PeerStats.transport = [];
  489. };
  490. /**
  491. * Stats processing logic.
  492. */
  493. StatsCollector.prototype.processAudioLevelReport = function ()
  494. {
  495. if (!this.baselineAudioLevelsReport)
  496. {
  497. return;
  498. }
  499. for (var idx in this.currentAudioLevelsReport)
  500. {
  501. var now = this.currentAudioLevelsReport[idx];
  502. if (now.type != 'ssrc')
  503. {
  504. continue;
  505. }
  506. var before = this.baselineAudioLevelsReport[idx];
  507. if (!before)
  508. {
  509. console.warn(now.stat('ssrc') + ' not enough data');
  510. continue;
  511. }
  512. var ssrc = now.stat('ssrc');
  513. var jid = ssrc2jid[ssrc];
  514. if (!jid)
  515. {
  516. console.warn("No jid for ssrc: " + ssrc);
  517. continue;
  518. }
  519. var jidStats = this.jid2stats[jid];
  520. if (!jidStats)
  521. {
  522. jidStats = new PeerStats();
  523. this.jid2stats[jid] = jidStats;
  524. }
  525. // Audio level
  526. var audioLevel = now.stat('audioInputLevel');
  527. if (!audioLevel)
  528. audioLevel = now.stat('audioOutputLevel');
  529. if (audioLevel)
  530. {
  531. // TODO: can't find specs about what this value really is,
  532. // but it seems to vary between 0 and around 32k.
  533. audioLevel = audioLevel / 32767;
  534. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  535. if(jid != connection.emuc.myroomjid)
  536. this.audioLevelsUpdateCallback(jid, audioLevel);
  537. }
  538. }
  539. };