8.7 GetStats Example

Consider the case where the user is experiencing bad sound and the application wants to determine if the cause of it is packet loss. The following example code might be used:

Example 8

  1. async function gatherStats(pc) {
  2. try {
  3. const [sender] = pc.getSenders();
  4. const baselineReport = await sender.getStats();
  5. await new Promise(resolve => setTimeout(resolve, aBit)); // wait a bit
  6. const currentReport = await sender.getStats();
  7. // compare the elements from the current report with the baseline
  8. for (const now of currentReport.values()) {
  9. if (now.type != 'outbound-rtp') continue;
  10. // get the corresponding stats from the baseline report
  11. const base = baselineReport.get(now.id);
  12. if (!base) continue;
  13. const remoteNow = currentReport.get(now.remoteId);
  14. const remoteBase = baselineReport.get(base.remoteId);
  15. const packetsSent = now.packetsSent - base.packetsSent;
  16. const packetsReceived = remoteNow.packetsReceived -
  17. remoteBase.packetsReceived;
  18. const fractionLost = (packetsSent - packetsReceived) / packetsSent;
  19. if (fractionLost > 0.3) {
  20. // if fractionLost is > 0.3, we have probably found the culprit
  21. }
  22. }
  23. } catch (err) {
  24. console.error(err);
  25. }
  26. }