Socket
Socket
Sign inDemoInstall

webrtc-issue-detector2

Package Overview
Dependencies
0
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.6.1 to 1.6.2

2

dist/bundle-cjs.js

@@ -1,1 +0,1 @@

"use strict";var e,t,s;function o(){}function n(){n.init.call(this)}function r(e){return void 0===e._maxListeners?n.defaultMaxListeners:e._maxListeners}function i(e,t,s){if(t)e.call(s);else for(var o=e.length,n=m(e,o),r=0;r<o;++r)n[r].call(s)}function a(e,t,s,o){if(t)e.call(s,o);else for(var n=e.length,r=m(e,n),i=0;i<n;++i)r[i].call(s,o)}function c(e,t,s,o,n){if(t)e.call(s,o,n);else for(var r=e.length,i=m(e,r),a=0;a<r;++a)i[a].call(s,o,n)}function u(e,t,s,o,n,r){if(t)e.call(s,o,n,r);else for(var i=e.length,a=m(e,i),c=0;c<i;++c)a[c].call(s,o,n,r)}function d(e,t,s,o){if(t)e.apply(s,o);else for(var n=e.length,r=m(e,n),i=0;i<n;++i)r[i].apply(s,o)}function p(e,t,s,n){var i,a,c,u;if("function"!=typeof s)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,s.listener?s.listener:s),a=e._events),c=a[t]):(a=e._events=new o,e._eventsCount=0),c){if("function"==typeof c?c=a[t]=n?[s,c]:[c,s]:n?c.unshift(s):c.push(s),!c.warned&&(i=r(e))&&i>0&&c.length>i){c.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=c.length,u=d,"function"==typeof console.warn?console.warn(u):console.log(u)}}else c=a[t]=s,++e._eventsCount;return e}function l(e,t,s){var o=!1;function n(){e.removeListener(t,n),o||(o=!0,s.apply(e,arguments))}return n.listener=s,n}function h(e){var t=this._events;if(t){var s=t[e];if("function"==typeof s)return 1;if(s)return s.length}return 0}function m(e,t){for(var s=new Array(t);t--;)s[t]=e[t];return s}Object.defineProperty(exports,"__esModule",{value:!0}),o.prototype=Object.create(null),n.EventEmitter=n,n.usingDomains=!1,n.prototype.domain=void 0,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.init=function(){this.domain=null,n.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new o,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},n.prototype.getMaxListeners=function(){return r(this)},n.prototype.emit=function(e){var t,s,o,n,r,p,l,h="error"===e;if(p=this._events)h=h&&null==p.error;else if(!h)return!1;if(l=this.domain,h){if(t=arguments[1],!l){if(t instanceof Error)throw t;var m=new Error('Uncaught, unspecified "error" event. ('+t+")");throw m.context=t,m}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=l,t.domainThrown=!1,l.emit("error",t),!1}if(!(s=p[e]))return!1;var f="function"==typeof s;switch(o=arguments.length){case 1:i(s,f,this);break;case 2:a(s,f,this,arguments[1]);break;case 3:c(s,f,this,arguments[1],arguments[2]);break;case 4:u(s,f,this,arguments[1],arguments[2],arguments[3]);break;default:for(n=new Array(o-1),r=1;r<o;r++)n[r-1]=arguments[r];d(s,f,this,n)}return!0},n.prototype.addListener=function(e,t){return p(this,e,t,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(e,t){return p(this,e,t,!0)},n.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,l(this,e,t)),this},n.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,l(this,e,t)),this},n.prototype.removeListener=function(e,t){var s,n,r,i,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(n=this._events))return this;if(!(s=n[e]))return this;if(s===t||s.listener&&s.listener===t)0==--this._eventsCount?this._events=new o:(delete n[e],n.removeListener&&this.emit("removeListener",e,s.listener||t));else if("function"!=typeof s){for(r=-1,i=s.length;i-- >0;)if(s[i]===t||s[i].listener&&s[i].listener===t){a=s[i].listener,r=i;break}if(r<0)return this;if(1===s.length){if(s[0]=void 0,0==--this._eventsCount)return this._events=new o,this;delete n[e]}else!function(e,t){for(var s=t,o=s+1,n=e.length;o<n;s+=1,o+=1)e[s]=e[o];e.pop()}(s,r);n.removeListener&&this.emit("removeListener",e,a||t)}return this},n.prototype.off=function(e,t){return this.removeListener(e,t)},n.prototype.removeAllListeners=function(e){var t,s;if(!(s=this._events))return this;if(!s.removeListener)return 0===arguments.length?(this._events=new o,this._eventsCount=0):s[e]&&(0==--this._eventsCount?this._events=new o:delete s[e]),this;if(0===arguments.length){for(var n,r=Object.keys(s),i=0;i<r.length;++i)"removeListener"!==(n=r[i])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=new o,this._eventsCount=0,this}if("function"==typeof(t=s[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},n.prototype.listeners=function(e){var t,s=this._events;return s&&(t=s[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),s=0;s<t.length;++s)t[s]=e[s].listener||e[s];return t}(t):[]},n.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},n.prototype.listenerCount=h,n.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class f extends n{}exports.EventType=void 0,(e=exports.EventType||(exports.EventType={})).Issue="issue",e.NetworkScoresUpdated="network-scores-updated",e.StatsParsingFinished="stats-parsing-finished",exports.IssueType=void 0,(t=exports.IssueType||(exports.IssueType={})).Network="network",t.CPU="cpu",t.Server="server",t.Stream="stream",exports.IssueReason=void 0,(s=exports.IssueReason||(exports.IssueReason={})).OutboundAudioNoData="outbount-audio-no-data",s.OutboundNetworkQuality="outbound-network-quality",s.InboundNetworkQuality="inbound-network-quality",s.OutboundNetworkMediaLatency="outbound-network-media-latency",s.InboundNetworkMediaLatency="inbound-network-media-latency",s.NetworkMediaSyncFailure="network-media-sync-failure",s.OutboundNetworkThroughput="outbound-network-throughput",s.InboundNetworkThroughput="inbound-network-throughput",s.EncoderCPUThrottling="encoder-cpu-throttling",s.DecoderCPUThrottling="decoder-cpu-throttling",s.ServerIssue="server-issue",s.UnknownVideoDecoderIssue="unknown-video-decoder",s.LowInboundMOS="low-inbound-mean-opinion-score",s.LowOutboundMOS="low-outbound-mean-opinion-score";class g extends n{static STATS_REPORT_READY_EVENT="stats-report-ready";static STATS_REPORTS_PARSED="stats-reports-parsed";isStopped=!1;reportTimer;getStatsInterval;compositeStatsParser;constructor(e){super(),this.compositeStatsParser=e.compositeStatsParser,this.getStatsInterval=e.getStatsInterval??1e4}get isRunning(){return!!this.reportTimer&&!this.isStopped}startReporting(){if(this.reportTimer)return;const e=()=>setTimeout((()=>{this.isStopped?this.reportTimer=void 0:this.parseReports().finally((()=>{this.reportTimer=e()}))}),this.getStatsInterval);this.isStopped=!1,this.reportTimer=e()}stopReporting(){this.isStopped=!0,this.reportTimer&&(clearTimeout(this.reportTimer),this.reportTimer=void 0)}async parseReports(){const e=Date.now(),t=await this.compositeStatsParser.parse(),s=Date.now()-e;this.emit(g.STATS_REPORTS_PARSED,{timeTaken:s}),t.forEach((e=>{this.emit(g.STATS_REPORT_READY_EVENT,e)}))}}const S=(()=>{const e=new Map;return t=>{const{taskId:s,delayMs:o,maxJitterMs:n,callback:r}=t,i=Math.ceil(Math.random()*(n||0)),a=e.get(s);a&&clearTimeout(a);const c=setTimeout((()=>{r(),e.delete(s)}),o+i);e.set(s,c)}})();class v{#e={};calculate(e){const{connection:{id:t}}=e,s=this.calculateOutboundScore(e),o=this.calculateInboundScore(e);return this.#e[t]=e,S({taskId:t,delayMs:35e3,callback:()=>delete this.#e[t]}),{outbound:s,inbound:o}}calculateOutboundScore(e){const t=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!t.length)return;const s=this.#e[e.connection.id];if(!s)return;const o=[...s.remote?.audio.inbound||[],...s.remote?.video.inbound||[]],{packetsSent:n}=e.connection,r=s.connection.packetsSent,i=t.reduce(((e,t)=>{const s=o.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(s?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=i,u=c/t.length,d=n-r,p=i.packetsLost-i.lastPacketsLost,l=d&&p?Math.round(100*p/(d+p)):0;return this.calculateMOS({avgJitter:u,rtt:a,packetsLoss:l})}calculateInboundScore(e){const t=[...e.audio?.inbound,...e.video?.inbound];if(!t.length)return;const s=this.#e[e.connection.id];if(!s)return;const o=[...s.video?.inbound,...s.audio?.inbound],{packetsReceived:n}=e.connection,r=s.connection.packetsReceived,i=t.reduce(((e,t)=>{const s=o.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(s?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=i,u=c/t.length,d=n-r,p=i.packetsLost-i.lastPacketsLost,l=d&&p?Math.round(100*p/(d+p)):0;return this.calculateMOS({avgJitter:u,rtt:a,packetsLoss:l})}calculateMOS({avgJitter:e,rtt:t,packetsLoss:s}){const o=t+2*e+10;let n=o<160?93.2-o/40:93.2-o/120-10;return n-=2.5*s,1+.035*n+7e-6*n*(n-60)*(100-n)}}class k{#e;#t;constructor(e={}){this.#e=new Map,this.#t=e.statsCleanupTtlMs??35e3}detect(e){const t=this.performDetection(e);return this.performPrevStatsCleanup({connectionId:e.connection.id}),t}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:s}=e;this.#e.has(t)&&S({taskId:t,delayMs:this.#t,callback:()=>{this.deleteLastProcessedStats(t),"function"==typeof s&&s()}})}setLastProcessedStats(e,t){this.#e.set(e,t)}getLastProcessedStats(e){return this.#e.get(e)}deleteLastProcessedStats(e){this.#e.delete(e)}}class y extends k{#s;constructor(e={}){super(e),this.#s=e.availableOutgoingBitrateThreshold??1e5}performDetection(e){const t=[],{availableOutgoingBitrate:s}=e.connection;if(void 0===s)return t;const o=e.audio.outbound.reduce(((e,t)=>e+t.targetBitrate),0),n=e.video.outbound.reduce(((e,t)=>e+t.bitrate),0);if(!o&&!n)return t;const r={availableOutgoingBitrate:s,videoStreamsTotalBitrate:n,audioStreamsTotalTargetBitrate:o};return o>s||n>0&&s<this.#s?(t.push({statsSample:r,type:exports.IssueType.Network,reason:exports.IssueReason.OutboundNetworkThroughput}),t):t}}class w extends k{#o;constructor(e={}){super(e),this.#o=e.framesDroppedThreshold??.5}performDetection(e){const{connection:{id:t}}=e,s=this.processData(e);return this.setLastProcessedStats(t,e),s}processData(e){const t=e.video.inbound.filter((e=>e.framesDropped>0)),s=[],o=this.getLastProcessedStats(e.connection.id)?.video.inbound;return o?(t.forEach((e=>{const t=o.find((t=>t.ssrc===e.ssrc));if(!t)return;if(e.framesDropped===t.framesDropped)return;const n=e.framesReceived-t.framesReceived,r=e.framesDecoded-t.framesDecoded,i=e.framesDropped-t.framesDropped,a=i/n;if(0===n||0===r)return;const c={deltaFramesDropped:i,deltaFramesReceived:n,deltaFramesDecoded:r,framesDroppedPct:Math.round(100*a)};a>=this.#o&&s.push({statsSample:c,type:exports.IssueType.CPU,reason:exports.IssueReason.DecoderCPUThrottling,ssrc:e.ssrc})})),s):s}}class b extends k{#n;constructor(e={}){super(e),this.#n=e.missedFramesThreshold??.15}performDetection(e){const{connection:{id:t}}=e,s=this.processData(e);return this.setLastProcessedStats(t,e),s}processData(e){const t=e.video.outbound.filter((e=>e.framesEncoded>0)),s=[],o=this.getLastProcessedStats(e.connection.id)?.video.outbound;return o?(t.forEach((e=>{const t=o.find((t=>t.ssrc===e.ssrc));if(!t)return;if(e.framesEncoded===t.framesEncoded)return;const n=e.framesEncoded-t.framesEncoded,r=e.framesSent-t.framesSent,i=1-r/n;if(0===n)return;if(n===r)return;const a={deltaFramesSent:r,deltaFramesEncoded:n,missedFramesPct:Math.round(100*i)};i>=this.#n&&s.push({statsSample:a,type:exports.IssueType.Network,reason:exports.IssueReason.OutboundNetworkThroughput,ssrc:e.ssrc})})),s):s}}class T extends k{highPacketLossThresholdPct;highJitterThreshold;highJitterBufferDelayThresholdMs;highRttThresholdMs;constructor(e={}){super(),this.highPacketLossThresholdPct=e.highPacketLossThresholdPct??5,this.highJitterThreshold=e.highJitterThreshold??200,this.highJitterBufferDelayThresholdMs=e.highJitterBufferDelayThresholdMs??500,this.highRttThresholdMs=e.highRttThresholdMs??250}performDetection(e){const{connection:{id:t}}=e,s=this.processData(e);return this.setLastProcessedStats(t,e),s}processData(e){const t=[],s=[...e.audio?.inbound,...e.video?.inbound];if(!s.length)return t;const o=this.getLastProcessedStats(e.connection.id);if(!o)return t;const n=[...o.video?.inbound,...o.audio?.inbound],{packetsReceived:r}=e.connection,i=o.connection.packetsReceived,a=s.reduce(((e,t)=>{const s=n.find((e=>e.ssrc===t.ssrc)),o=s?.jitterBufferDelay||0,r=s?.jitterBufferEmittedCount||0,i=t.jitterBufferDelay-o,a=t.jitterBufferEmittedCount-r,c=i&&a?1e3*i/a:0;return{sumJitter:e.sumJitter+t.jitter,sumJitterBufferDelayMs:e.sumJitterBufferDelayMs+c,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(s?.packetsLost||0)}}),{sumJitter:0,sumJitterBufferDelayMs:0,packetsLost:0,lastPacketsLost:0}),c=1e3*e.connection.currentRoundTripTime||0,{sumJitter:u,sumJitterBufferDelayMs:d}=a,p=u/s.length,l=d/s.length,h=r-i,m=a.packetsLost-a.lastPacketsLost,f=h&&m?Math.round(100*m/(h+m)):0,g=f>this.highPacketLossThresholdPct,S=p>=this.highJitterThreshold,v=c>=this.highRttThresholdMs,k=l>this.highJitterBufferDelayThresholdMs,y=v&&!S&&!g,w=g&&S,b=S&&k,T={rtt:c,packetLossPct:f,avgJitter:p,avgJitterBufferDelay:l};return(S||g)&&t.push({statsSample:T,type:exports.IssueType.Network,reason:exports.IssueReason.InboundNetworkQuality,iceCandidate:e.connection.local.id}),y&&t.push({statsSample:T,type:exports.IssueType.Server,reason:exports.IssueReason.ServerIssue,iceCandidate:e.connection.remote.id}),w&&t.push({statsSample:T,type:exports.IssueType.Network,reason:exports.IssueReason.InboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),b&&t.push({statsSample:T,type:exports.IssueType.Network,reason:exports.IssueReason.NetworkMediaSyncFailure,iceCandidate:e.connection.local.id}),t}}class L extends k{performDetection(e){const{connection:{id:t}}=e,s=this.processData(e);return this.setLastProcessedStats(t,e),s}processData(e){const t=e.audio.inbound,s=[],o=this.getLastProcessedStats(e.connection.id)?.audio.inbound;return o?(t.forEach((e=>{const t=o.find((t=>t.ssrc===e.ssrc));if(!t)return;const n=e.track.insertedSamplesForDeceleration+e.track.removedSamplesForAcceleration,r=t.track.insertedSamplesForDeceleration+t.track.removedSamplesForAcceleration;if(n===r)return;const i=e.track.totalSamplesReceived-t.track.totalSamplesReceived,a=n-r,c=Math.round(100*a/i),u={correctedSamplesPct:c};c>5&&s.push({statsSample:u,type:exports.IssueType.Network,reason:exports.IssueReason.NetworkMediaSyncFailure,ssrc:e.ssrc})})),s):s}}class P extends k{performDetection(e){const{connection:{id:t}}=e,s=this.processData(e);return this.setLastProcessedStats(t,e),s}processData(e){const t=[],s=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!s.length)return t;const o=this.getLastProcessedStats(e.connection.id);if(!o)return t;const n=[...o.remote?.audio.inbound||[],...o.remote?.video.inbound||[]],{packetsSent:r}=e.connection,i=o.connection.packetsSent,a=s.reduce(((e,t)=>{const s=n.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(s?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),c=1e3*e.connection.currentRoundTripTime||0,{sumJitter:u}=a,d=u/s.length,p=r-i,l=a.packetsLost-a.lastPacketsLost,h=p&&l?Math.round(100*l/(p+l)):0,m=h>5,f=d>=200,g=!m&&f||f||m,S={rtt:c,avgJitter:d,packetLossPct:h};return m&&f&&t.push({statsSample:S,type:exports.IssueType.Network,reason:exports.IssueReason.OutboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),g&&t.push({statsSample:S,type:exports.IssueType.Network,reason:exports.IssueReason.OutboundNetworkQuality,iceCandidate:e.connection.local.id}),t}}class I extends k{performDetection(e){const{connection:{id:t}}=e,s=this.processData(e);return this.setLastProcessedStats(t,e),s}processData(e){const t=e.video.outbound.filter((e=>"none"!==e.qualityLimitationReason)),s=[],o=this.getLastProcessedStats(e.connection.id)?.video.outbound;return o?(t.forEach((e=>{const t=o.find((t=>t.ssrc===e.ssrc));if(!t)return;const n={qualityLimitationReason:e.qualityLimitationReason};e.framesSent>t.framesSent||("cpu"===e.qualityLimitationReason&&s.push({statsSample:n,type:exports.IssueType.CPU,reason:exports.IssueReason.EncoderCPUThrottling,ssrc:e.ssrc}),"bandwidth"===e.qualityLimitationReason&&s.push({statsSample:n,type:exports.IssueType.Network,reason:exports.IssueReason.OutboundNetworkThroughput,ssrc:e.ssrc}))})),s):s}}class D extends k{UNKNOWN_DECODER="unknown";#r={};performDetection(e){const{connection:{id:t}}=e,s=this.processData(e);return this.setLastProcessedStats(t,e),s}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:s}=e;super.performPrevStatsCleanup({...e,cleanupCallback:()=>{delete this.#r[t],"function"==typeof s&&s()}})}processData(e){const t=[],{id:s}=e.connection,o=this.getLastProcessedStats(s)?.video.inbound;return e.video.inbound.forEach((e=>{const{decoderImplementation:n,ssrc:r}=e,i=o?.find((e=>e.ssrc===r));if(i)if(n===this.UNKNOWN_DECODER){if(!this.hadLastDecoderWithIssue(s,r)){this.setLastDecoderWithIssue(s,r,this.UNKNOWN_DECODER);const o={mimeType:e.mimeType,decoderImplementation:n};t.push({ssrc:r,statsSample:o,type:exports.IssueType.Stream,reason:exports.IssueReason.UnknownVideoDecoderIssue,trackIdentifier:e.track.trackIdentifier})}}else this.setLastDecoderWithIssue(s,r,void 0)})),t}setLastDecoderWithIssue(e,t,s){const o=this.#r[e]??{};void 0===s?delete o[t]:o[t]=s,this.#r[e]=o}hadLastDecoderWithIssue(e,t){const s=this.#r[e];return(s&&s[t])===this.UNKNOWN_DECODER}}const R=e=>"closed"===e.iceConnectionState||"closed"===e.connectionState,C=(e,t,s)=>8*((e,t,s)=>{if(!t)return 0;const o=e[s],n=t[s];if(null==o||null==n)return 0;const r=Math.floor(e.timestamp)-Math.floor(t.timestamp);return 0===r?0:(Number(o)-Number(n))/r*1e3})(e,t,s);class x{connections=[];statsParser;constructor(e){this.statsParser=e.statsParser}listConnections(){return[...this.connections]}addPeerConnection(e){this.connections.push({id:e.id??String(Date.now()+Math.random().toString(32)),pc:e.pc})}removePeerConnection(e){const t=this.connections.findIndex((({pc:t})=>t===e.pc));t>=0&&this.removeConnectionsByIndexes([t])}async parse(){const e=[],t=this.connections.map((async(t,s)=>{if(!R(t.pc))return this.statsParser.parse(t);e.unshift(s)}));e.length&&this.removeConnectionsByIndexes(e);return(await Promise.all(t)).filter((e=>void 0!==e))}removeConnectionsByIndexes(e){e.forEach((e=>{this.connections.splice(e,1)}))}}class E{prevStats=new Map;allowedReportTypes=new Set(["candidate-pair","inbound-rtp","outbound-rtp","remote-outbound-rtp","remote-inbound-rtp","track","transport"]);logger;constructor(e){this.logger=e.logger}get previouslyParsedStatsConnectionsIds(){return[...this.prevStats.keys()]}async parse(e){if(!R(e.pc))return this.getConnectionStats(e);this.logger.debug("Skip stats parsing. Connection is closed.",{connection:e})}async getConnectionStats(e){const{pc:t,id:s}=e;try{const o=Date.now(),n=await Promise.all(t.getReceivers().map((e=>e.getStats()))),r=await Promise.all(t.getSenders().map((e=>e.getStats())));return{id:s,stats:this.mapReportsStats([...n,...r],e),timeTaken:Date.now()-o}}catch(e){return void this.logger.error("Failed to get stats for PC",{id:s,pc:t,error:e})}}mapReportsStats(e,t){const s={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{},remote:{video:{inbound:[],outbound:[]},audio:{inbound:[],outbound:[]}}};e.forEach((e=>{e.forEach((t=>{this.allowedReportTypes.has(t.type)&&this.updateMappedStatsWithReportItemData(t,s,e)}))}));const{id:o}=t,n=this.prevStats.get(o);return n&&this.propagateStatsWithRateValues(s,n.stats),this.prevStats.set(o,{stats:s,ts:Date.now()}),S({taskId:o,delayMs:35e3,callback:()=>this.prevStats.delete(o)}),s}updateMappedStatsWithReportItemData(e,t,s){const o=e.type;if("candidate-pair"===o&&"succeeded"===e.state&&e.nominated)return void(t.connection=this.prepareConnectionStats(e,s));const n=this.getMediaType(e);if(n)if("outbound-rtp"!==o)if("inbound-rtp"!==o)"remote-outbound-rtp"!==o?"remote-inbound-rtp"===o&&(this.mapConnectionStatsIfNecessary(t,e,s),t.remote[n].inbound.push({...e})):t.remote[n].outbound.push({...e});else{const o=s.get(e.trackId)||s.get(e.mediaSourceId)||{};this.mapConnectionStatsIfNecessary(t,e,s);const r={...e,track:{...o}};t[n].inbound.push(r)}else{const o=s.get(e.trackId)||s.get(e.mediaSourceId)||{},r={...e,track:{...o}};t[n].outbound.push(r)}}getMediaType(e){const t=e.mediaType||e.kind;if(!["audio","video"].includes(t)){const{id:t}=e;if(!t)return;return String(t).includes("Video")?"video":String(t).includes("Audio")?"audio":void 0}return t}propagateStatsWithRateValues(e,t){e.audio.inbound.forEach((e=>{const s=t.audio.inbound.find((({id:t})=>t===e.id));e.bitrate=C(e,s,"bytesReceived"),e.packetRate=C(e,s,"packetsReceived")})),e.audio.outbound.forEach((e=>{const s=t.audio.outbound.find((({id:t})=>t===e.id));e.bitrate=C(e,s,"bytesSent"),e.packetRate=C(e,s,"packetsSent")})),e.video.inbound.forEach((e=>{const s=t.video.inbound.find((({id:t})=>t===e.id));e.bitrate=C(e,s,"bytesReceived"),e.packetRate=C(e,s,"packetsReceived")})),e.video.outbound.forEach((e=>{const s=t.video.outbound.find((({id:t})=>t===e.id));e.bitrate=C(e,s,"bytesSent"),e.packetRate=C(e,s,"packetsSent")}))}mapConnectionStatsIfNecessary(e,t,s){if(e.connection.id||!t.transportId)return;const o=s.get(t.transportId);if(o&&o.selectedCandidatePairId){const t=s.get(o.selectedCandidatePairId);e.connection=this.prepareConnectionStats(t,s)}}prepareConnectionStats(e,t){if(!e||!t)return{};const s={...e};if(s.remoteCandidateId){const e=t.get(s.remoteCandidateId);s.remote={...e}}if(s.localCandidateId){const e=t.get(s.localCandidateId);s.local={...e}}return s}}exports.AvailableOutgoingBitrateIssueDetector=y,exports.CompositeRTCStatsParser=x,exports.FramesDroppedIssueDetector=w,exports.FramesEncodedSentIssueDetector=b,exports.InboundNetworkIssueDetector=T,exports.NetworkMediaSyncIssueDetector=L,exports.NetworkScoresCalculator=v,exports.OutboundAudioIssueDetector=class extends k{performDetection(e){const{connection:{id:t}}=e,s=this.processData(e);return this.setLastProcessedStats(t,e),s}processData(e){const t=[];if(console.log("data.connection.state",e.connection.state),"succeeded"!==e.connection.state)return t;const s=this.getLastProcessedStats(e.connection.id);if(!s)return t;const o=e.audio.outbound.filter((e=>!!e.mediaSourceId)),n=s.audio.outbound.filter((e=>!!e.mediaSourceId));if(!o.length||!n.length)return t;const r=o.reduce(((e,t)=>e+t.packetsSent),0),i=n.reduce(((e,t)=>e+t.packetsSent),0);return console.log(e.audio.outbound,s.audio.outbound),console.log("audio pkt",i,r),r==i&&t.push({type:exports.IssueType.Stream,reason:exports.IssueReason.OutboundAudioNoData}),t}},exports.OutboundNetworkIssueDetector=P,exports.PeriodicWebRTCStatsReporter=g,exports.QualityLimitationsIssueDetector=I,exports.RTCStatsParser=E,exports.UnknownVideoDecoderImplementationDetector=D,exports.WebRTCIssueEmitter=f,exports.default=class{eventEmitter;#i=!1;detectors=[];networkScoresCalculator;statsReporter;compositeStatsParser;logger;constructor(e){this.logger=e.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.eventEmitter=e.issueEmitter??new f,e.onIssues&&this.eventEmitter.on(exports.EventType.Issue,e.onIssues),e.onNetworkScoresUpdated&&this.eventEmitter.on(exports.EventType.NetworkScoresUpdated,e.onNetworkScoresUpdated),this.detectors=e.detectors??[new I,new w,new b,new T,new P,new L,new y,new D],this.networkScoresCalculator=e.networkScoresCalculator??new v,this.compositeStatsParser=e.compositeStatsParser??new x({statsParser:new E({logger:this.logger})}),this.statsReporter=e.statsReporter??new g({compositeStatsParser:this.compositeStatsParser,getStatsInterval:e.getStatsInterval??5e3}),window.wid=this,this.wrapRTCPeerConnection(),this.statsReporter.on(g.STATS_REPORT_READY_EVENT,(t=>{this.detectIssues({data:t.stats,ignoreSSRCList:e.ignoreSSRCList}),this.calculateNetworkScores(t.stats)})),this.statsReporter.on(g.STATS_REPORTS_PARSED,(e=>{const t={timeTaken:e.timeTaken,ts:Date.now()};this.eventEmitter.emit(exports.EventType.StatsParsingFinished,t)}))}watchNewPeerConnections(){this.#i?this.logger.warn("WebRTCIssueDetector is already started. Skip processing"):(this.logger.info("Start watching peer connections"),this.#i=!0,this.statsReporter.startReporting())}stopWatchingNewPeerConnections(){this.#i?(this.logger.info("Stop watching peer connections"),this.#i=!1,this.statsReporter.stopReporting()):this.logger.warn("WebRTCIssueDetector is already stopped. Skip processing")}handleNewPeerConnection(e){this.#i?(this.logger.debug("Handling new peer connection",e),this.compositeStatsParser.addPeerConnection({pc:e})):this.logger.debug("Skip handling new peer connection. Detector is not running",e)}emitIssues(e){this.eventEmitter.emit(exports.EventType.Issue,e)}detectIssues({data:e,ignoreSSRCList:t}){let s=this.detectors.reduce(((t,s)=>[...t,...s.detect(e)]),[]);t?.length&&(s=s.filter((e=>!e.ssrc||!t.includes(e.ssrc)))),s.length>0&&this.emitIssues(s)}calculateNetworkScores(e){const t=this.networkScoresCalculator.calculate(e);this.eventEmitter.emit(exports.EventType.NetworkScoresUpdated,t)}wrapRTCPeerConnection(){if(!window.RTCPeerConnection)return void this.logger.warn("No RTCPeerConnection found in browser window. Skipping");const e=window.RTCPeerConnection,t=e=>this.handleNewPeerConnection(e);function s(s){const o=new e(s);return t(o),o}s.prototype=e.prototype,window.RTCPeerConnection=s}};
"use strict";var e,t,s;function o(){}function n(){n.init.call(this)}function r(e){return void 0===e._maxListeners?n.defaultMaxListeners:e._maxListeners}function i(e,t,s){if(t)e.call(s);else for(var o=e.length,n=f(e,o),r=0;r<o;++r)n[r].call(s)}function a(e,t,s,o){if(t)e.call(s,o);else for(var n=e.length,r=f(e,n),i=0;i<n;++i)r[i].call(s,o)}function c(e,t,s,o,n){if(t)e.call(s,o,n);else for(var r=e.length,i=f(e,r),a=0;a<r;++a)i[a].call(s,o,n)}function u(e,t,s,o,n,r){if(t)e.call(s,o,n,r);else for(var i=e.length,a=f(e,i),c=0;c<i;++c)a[c].call(s,o,n,r)}function d(e,t,s,o){if(t)e.apply(s,o);else for(var n=e.length,r=f(e,n),i=0;i<n;++i)r[i].apply(s,o)}function p(e,t,s,n){var i,a,c,u;if("function"!=typeof s)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,s.listener?s.listener:s),a=e._events),c=a[t]):(a=e._events=new o,e._eventsCount=0),c){if("function"==typeof c?c=a[t]=n?[s,c]:[c,s]:n?c.unshift(s):c.push(s),!c.warned&&(i=r(e))&&i>0&&c.length>i){c.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=c.length,u=d,"function"==typeof console.warn?console.warn(u):console.log(u)}}else c=a[t]=s,++e._eventsCount;return e}function l(e,t,s){var o=!1;function n(){e.removeListener(t,n),o||(o=!0,s.apply(e,arguments))}return n.listener=s,n}function h(e){var t=this._events;if(t){var s=t[e];if("function"==typeof s)return 1;if(s)return s.length}return 0}function f(e,t){for(var s=new Array(t);t--;)s[t]=e[t];return s}Object.defineProperty(exports,"__esModule",{value:!0}),o.prototype=Object.create(null),n.EventEmitter=n,n.usingDomains=!1,n.prototype.domain=void 0,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.init=function(){this.domain=null,n.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new o,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},n.prototype.getMaxListeners=function(){return r(this)},n.prototype.emit=function(e){var t,s,o,n,r,p,l,h="error"===e;if(p=this._events)h=h&&null==p.error;else if(!h)return!1;if(l=this.domain,h){if(t=arguments[1],!l){if(t instanceof Error)throw t;var f=new Error('Uncaught, unspecified "error" event. ('+t+")");throw f.context=t,f}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=l,t.domainThrown=!1,l.emit("error",t),!1}if(!(s=p[e]))return!1;var m="function"==typeof s;switch(o=arguments.length){case 1:i(s,m,this);break;case 2:a(s,m,this,arguments[1]);break;case 3:c(s,m,this,arguments[1],arguments[2]);break;case 4:u(s,m,this,arguments[1],arguments[2],arguments[3]);break;default:for(n=new Array(o-1),r=1;r<o;r++)n[r-1]=arguments[r];d(s,m,this,n)}return!0},n.prototype.addListener=function(e,t){return p(this,e,t,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(e,t){return p(this,e,t,!0)},n.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,l(this,e,t)),this},n.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,l(this,e,t)),this},n.prototype.removeListener=function(e,t){var s,n,r,i,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(n=this._events))return this;if(!(s=n[e]))return this;if(s===t||s.listener&&s.listener===t)0==--this._eventsCount?this._events=new o:(delete n[e],n.removeListener&&this.emit("removeListener",e,s.listener||t));else if("function"!=typeof s){for(r=-1,i=s.length;i-- >0;)if(s[i]===t||s[i].listener&&s[i].listener===t){a=s[i].listener,r=i;break}if(r<0)return this;if(1===s.length){if(s[0]=void 0,0==--this._eventsCount)return this._events=new o,this;delete n[e]}else!function(e,t){for(var s=t,o=s+1,n=e.length;o<n;s+=1,o+=1)e[s]=e[o];e.pop()}(s,r);n.removeListener&&this.emit("removeListener",e,a||t)}return this},n.prototype.off=function(e,t){return this.removeListener(e,t)},n.prototype.removeAllListeners=function(e){var t,s;if(!(s=this._events))return this;if(!s.removeListener)return 0===arguments.length?(this._events=new o,this._eventsCount=0):s[e]&&(0==--this._eventsCount?this._events=new o:delete s[e]),this;if(0===arguments.length){for(var n,r=Object.keys(s),i=0;i<r.length;++i)"removeListener"!==(n=r[i])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=new o,this._eventsCount=0,this}if("function"==typeof(t=s[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},n.prototype.listeners=function(e){var t,s=this._events;return s&&(t=s[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),s=0;s<t.length;++s)t[s]=e[s].listener||e[s];return t}(t):[]},n.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},n.prototype.listenerCount=h,n.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class m extends n{}exports.EventType=void 0,(e=exports.EventType||(exports.EventType={})).Issue="issue",e.NetworkScoresUpdated="network-scores-updated",e.StatsParsingFinished="stats-parsing-finished",exports.IssueType=void 0,(t=exports.IssueType||(exports.IssueType={})).Network="network",t.CPU="cpu",t.Server="server",t.Stream="stream",exports.IssueReason=void 0,(s=exports.IssueReason||(exports.IssueReason={})).OutboundAudioNoData="outbount-audio-no-data",s.OutboundNetworkQuality="outbound-network-quality",s.InboundNetworkQuality="inbound-network-quality",s.OutboundNetworkMediaLatency="outbound-network-media-latency",s.InboundNetworkMediaLatency="inbound-network-media-latency",s.NetworkMediaSyncFailure="network-media-sync-failure",s.OutboundNetworkThroughput="outbound-network-throughput",s.InboundNetworkThroughput="inbound-network-throughput",s.EncoderCPUThrottling="encoder-cpu-throttling",s.DecoderCPUThrottling="decoder-cpu-throttling",s.ServerIssue="server-issue",s.UnknownVideoDecoderIssue="unknown-video-decoder",s.LowInboundMOS="low-inbound-mean-opinion-score",s.LowOutboundMOS="low-outbound-mean-opinion-score";class g extends n{static STATS_REPORT_READY_EVENT="stats-report-ready";static STATS_REPORTS_PARSED="stats-reports-parsed";isStopped=!1;reportTimer;getStatsInterval;compositeStatsParser;constructor(e){super(),this.compositeStatsParser=e.compositeStatsParser,this.getStatsInterval=e.getStatsInterval??1e4}get isRunning(){return!!this.reportTimer&&!this.isStopped}startReporting(){if(this.reportTimer)return;const e=()=>setTimeout((()=>{this.isStopped?this.reportTimer=void 0:this.parseReports().finally((()=>{this.reportTimer=e()}))}),this.getStatsInterval);this.isStopped=!1,this.reportTimer=e()}stopReporting(){this.isStopped=!0,this.reportTimer&&(clearTimeout(this.reportTimer),this.reportTimer=void 0)}async parseReports(){const e=Date.now(),t=await this.compositeStatsParser.parse(),s=Date.now()-e;this.emit(g.STATS_REPORTS_PARSED,{timeTaken:s}),t.forEach((e=>{this.emit(g.STATS_REPORT_READY_EVENT,e)}))}}const S=(()=>{const e=new Map;return t=>{const{taskId:s,delayMs:o,maxJitterMs:n,callback:r}=t,i=Math.ceil(Math.random()*(n||0)),a=e.get(s);a&&clearTimeout(a);const c=setTimeout((()=>{r(),e.delete(s)}),o+i);e.set(s,c)}})();class v{#e={};calculate(e){const{connection:{id:t}}=e,s=this.calculateOutboundScore(e),o=this.calculateInboundScore(e);return this.#e[t]=e,S({taskId:t,delayMs:35e3,callback:()=>delete this.#e[t]}),{outbound:s,inbound:o}}calculateOutboundScore(e){const t=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!t.length)return;const s=this.#e[e.connection.id];if(!s)return;const o=[...s.remote?.audio.inbound||[],...s.remote?.video.inbound||[]],{packetsSent:n}=e.connection,r=s.connection.packetsSent,i=t.reduce(((e,t)=>{const s=o.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(s?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=i,u=c/t.length,d=i.packetsLost-i.lastPacketsLost,p=n-r;if(0==p&&0==d)return;const l=p&&d?Math.round(100*d/(p+d)):0;return this.calculateMOS({avgJitter:u,rtt:a,packetsLoss:l})}calculateInboundScore(e){const t=[...e.audio?.inbound,...e.video?.inbound];if(!t.length)return;const s=this.#e[e.connection.id];if(!s)return;const o=[...s.video?.inbound,...s.audio?.inbound],{packetsReceived:n}=e.connection,r=s.connection.packetsReceived,i=t.reduce(((e,t)=>{const s=o.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(s?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=i,u=c/t.length,d=n-r,p=i.packetsLost-i.lastPacketsLost;if(0==d&&0==p)return;const l=d&&p?Math.round(100*p/(d+p)):0;return this.calculateMOS({avgJitter:u,rtt:a,packetsLoss:l})}calculateMOS({avgJitter:e,rtt:t,packetsLoss:s}){const o=t+2*e+10;let n=o<160?93.2-o/40:93.2-o/120-10;return n-=2.5*s,1+.035*n+7e-6*n*(n-60)*(100-n)}}class k{#e;#t;constructor(e={}){this.#e=new Map,this.#t=e.statsCleanupTtlMs??35e3}detect(e){const t=this.performDetection(e);return this.performPrevStatsCleanup({connectionId:e.connection.id}),t}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:s}=e;this.#e.has(t)&&S({taskId:t,delayMs:this.#t,callback:()=>{this.deleteLastProcessedStats(t),"function"==typeof s&&s()}})}setLastProcessedStats(e,t){this.#e.set(e,t)}getLastProcessedStats(e){return this.#e.get(e)}deleteLastProcessedStats(e){this.#e.delete(e)}}class y extends k{#s;constructor(e={}){super(e),this.#s=e.availableOutgoingBitrateThreshold??1e5}performDetection(e){const t=[],{availableOutgoingBitrate:s}=e.connection;if(void 0===s)return t;const o=e.audio.outbound.reduce(((e,t)=>e+t.targetBitrate),0),n=e.video.outbound.reduce(((e,t)=>e+t.bitrate),0);if(!o&&!n)return t;const r={availableOutgoingBitrate:s,videoStreamsTotalBitrate:n,audioStreamsTotalTargetBitrate:o};return o>s||n>0&&s<this.#s?(t.push({statsSample:r,type:exports.IssueType.Network,reason:exports.IssueReason.OutboundNetworkThroughput}),t):t}}class w extends k{#o;constructor(e={}){super(e),this.#o=e.framesDroppedThreshold??.5}performDetection(e){const{connection:{id:t}}=e,s=this.processData(e);return this.setLastProcessedStats(t,e),s}processData(e){const t=e.video.inbound.filter((e=>e.framesDropped>0)),s=[],o=this.getLastProcessedStats(e.connection.id)?.video.inbound;return o?(t.forEach((e=>{const t=o.find((t=>t.ssrc===e.ssrc));if(!t)return;if(e.framesDropped===t.framesDropped)return;const n=e.framesReceived-t.framesReceived,r=e.framesDecoded-t.framesDecoded,i=e.framesDropped-t.framesDropped,a=i/n;if(0===n||0===r)return;const c={deltaFramesDropped:i,deltaFramesReceived:n,deltaFramesDecoded:r,framesDroppedPct:Math.round(100*a)};a>=this.#o&&s.push({statsSample:c,type:exports.IssueType.CPU,reason:exports.IssueReason.DecoderCPUThrottling,ssrc:e.ssrc})})),s):s}}class b extends k{#n;constructor(e={}){super(e),this.#n=e.missedFramesThreshold??.15}performDetection(e){const{connection:{id:t}}=e,s=this.processData(e);return this.setLastProcessedStats(t,e),s}processData(e){const t=e.video.outbound.filter((e=>e.framesEncoded>0)),s=[],o=this.getLastProcessedStats(e.connection.id)?.video.outbound;return o?(t.forEach((e=>{const t=o.find((t=>t.ssrc===e.ssrc));if(!t)return;if(e.framesEncoded===t.framesEncoded)return;const n=e.framesEncoded-t.framesEncoded,r=e.framesSent-t.framesSent,i=1-r/n;if(0===n)return;if(n===r)return;const a={deltaFramesSent:r,deltaFramesEncoded:n,missedFramesPct:Math.round(100*i)};i>=this.#n&&s.push({statsSample:a,type:exports.IssueType.Network,reason:exports.IssueReason.OutboundNetworkThroughput,ssrc:e.ssrc})})),s):s}}class T extends k{highPacketLossThresholdPct;highJitterThreshold;highJitterBufferDelayThresholdMs;highRttThresholdMs;constructor(e={}){super(),this.highPacketLossThresholdPct=e.highPacketLossThresholdPct??5,this.highJitterThreshold=e.highJitterThreshold??200,this.highJitterBufferDelayThresholdMs=e.highJitterBufferDelayThresholdMs??500,this.highRttThresholdMs=e.highRttThresholdMs??250}performDetection(e){const{connection:{id:t}}=e,s=this.processData(e);return this.setLastProcessedStats(t,e),s}processData(e){const t=[],s=[...e.audio?.inbound,...e.video?.inbound];if(!s.length)return t;const o=this.getLastProcessedStats(e.connection.id);if(!o)return t;const n=[...o.video?.inbound,...o.audio?.inbound],{packetsReceived:r}=e.connection,i=o.connection.packetsReceived,a=s.reduce(((e,t)=>{const s=n.find((e=>e.ssrc===t.ssrc)),o=s?.jitterBufferDelay||0,r=s?.jitterBufferEmittedCount||0,i=t.jitterBufferDelay-o,a=t.jitterBufferEmittedCount-r,c=i&&a?1e3*i/a:0;return{sumJitter:e.sumJitter+t.jitter,sumJitterBufferDelayMs:e.sumJitterBufferDelayMs+c,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(s?.packetsLost||0)}}),{sumJitter:0,sumJitterBufferDelayMs:0,packetsLost:0,lastPacketsLost:0}),c=1e3*e.connection.currentRoundTripTime||0,{sumJitter:u,sumJitterBufferDelayMs:d}=a,p=u/s.length,l=d/s.length,h=r-i,f=a.packetsLost-a.lastPacketsLost,m=h&&f?Math.round(100*f/(h+f)):0,g=m>this.highPacketLossThresholdPct,S=p>=this.highJitterThreshold,v=c>=this.highRttThresholdMs,k=l>this.highJitterBufferDelayThresholdMs,y=v&&!S&&!g,w=g&&S,b=S&&k,T={rtt:c,packetLossPct:m,avgJitter:p,avgJitterBufferDelay:l};return(S||g)&&t.push({statsSample:T,type:exports.IssueType.Network,reason:exports.IssueReason.InboundNetworkQuality,iceCandidate:e.connection.local.id}),y&&t.push({statsSample:T,type:exports.IssueType.Server,reason:exports.IssueReason.ServerIssue,iceCandidate:e.connection.remote.id}),w&&t.push({statsSample:T,type:exports.IssueType.Network,reason:exports.IssueReason.InboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),b&&t.push({statsSample:T,type:exports.IssueType.Network,reason:exports.IssueReason.NetworkMediaSyncFailure,iceCandidate:e.connection.local.id}),t}}class L extends k{performDetection(e){const{connection:{id:t}}=e,s=this.processData(e);return this.setLastProcessedStats(t,e),s}processData(e){const t=e.audio.inbound,s=[],o=this.getLastProcessedStats(e.connection.id)?.audio.inbound;return o?(t.forEach((e=>{const t=o.find((t=>t.ssrc===e.ssrc));if(!t)return;const n=e.track.insertedSamplesForDeceleration+e.track.removedSamplesForAcceleration,r=t.track.insertedSamplesForDeceleration+t.track.removedSamplesForAcceleration;if(n===r)return;const i=e.track.totalSamplesReceived-t.track.totalSamplesReceived,a=n-r,c=Math.round(100*a/i),u={correctedSamplesPct:c};c>5&&s.push({statsSample:u,type:exports.IssueType.Network,reason:exports.IssueReason.NetworkMediaSyncFailure,ssrc:e.ssrc})})),s):s}}class P extends k{performDetection(e){const{connection:{id:t}}=e,s=this.processData(e);return this.setLastProcessedStats(t,e),s}processData(e){const t=[],s=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!s.length)return t;const o=this.getLastProcessedStats(e.connection.id);if(!o)return t;const n=[...o.remote?.audio.inbound||[],...o.remote?.video.inbound||[]],{packetsSent:r}=e.connection,i=o.connection.packetsSent,a=s.reduce(((e,t)=>{const s=n.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(s?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),c=1e3*e.connection.currentRoundTripTime||0,{sumJitter:u}=a,d=u/s.length,p=r-i,l=a.packetsLost-a.lastPacketsLost,h=p&&l?Math.round(100*l/(p+l)):0,f=h>5,m=d>=200,g=!f&&m||m||f,S={rtt:c,avgJitter:d,packetLossPct:h};return f&&m&&t.push({statsSample:S,type:exports.IssueType.Network,reason:exports.IssueReason.OutboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),g&&t.push({statsSample:S,type:exports.IssueType.Network,reason:exports.IssueReason.OutboundNetworkQuality,iceCandidate:e.connection.local.id}),t}}class I extends k{performDetection(e){const{connection:{id:t}}=e,s=this.processData(e);return this.setLastProcessedStats(t,e),s}processData(e){const t=e.video.outbound.filter((e=>"none"!==e.qualityLimitationReason)),s=[],o=this.getLastProcessedStats(e.connection.id)?.video.outbound;return o?(t.forEach((e=>{const t=o.find((t=>t.ssrc===e.ssrc));if(!t)return;const n={qualityLimitationReason:e.qualityLimitationReason};e.framesSent>t.framesSent||("cpu"===e.qualityLimitationReason&&s.push({statsSample:n,type:exports.IssueType.CPU,reason:exports.IssueReason.EncoderCPUThrottling,ssrc:e.ssrc}),"bandwidth"===e.qualityLimitationReason&&s.push({statsSample:n,type:exports.IssueType.Network,reason:exports.IssueReason.OutboundNetworkThroughput,ssrc:e.ssrc}))})),s):s}}class D extends k{UNKNOWN_DECODER="unknown";#r={};performDetection(e){const{connection:{id:t}}=e,s=this.processData(e);return this.setLastProcessedStats(t,e),s}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:s}=e;super.performPrevStatsCleanup({...e,cleanupCallback:()=>{delete this.#r[t],"function"==typeof s&&s()}})}processData(e){const t=[],{id:s}=e.connection,o=this.getLastProcessedStats(s)?.video.inbound;return e.video.inbound.forEach((e=>{const{decoderImplementation:n,ssrc:r}=e,i=o?.find((e=>e.ssrc===r));if(i)if(n===this.UNKNOWN_DECODER){if(!this.hadLastDecoderWithIssue(s,r)){this.setLastDecoderWithIssue(s,r,this.UNKNOWN_DECODER);const o={mimeType:e.mimeType,decoderImplementation:n};t.push({ssrc:r,statsSample:o,type:exports.IssueType.Stream,reason:exports.IssueReason.UnknownVideoDecoderIssue,trackIdentifier:e.track.trackIdentifier})}}else this.setLastDecoderWithIssue(s,r,void 0)})),t}setLastDecoderWithIssue(e,t,s){const o=this.#r[e]??{};void 0===s?delete o[t]:o[t]=s,this.#r[e]=o}hadLastDecoderWithIssue(e,t){const s=this.#r[e];return(s&&s[t])===this.UNKNOWN_DECODER}}const R=e=>"closed"===e.iceConnectionState||"closed"===e.connectionState,C=(e,t,s)=>8*((e,t,s)=>{if(!t)return 0;const o=e[s],n=t[s];if(null==o||null==n)return 0;const r=Math.floor(e.timestamp)-Math.floor(t.timestamp);return 0===r?0:(Number(o)-Number(n))/r*1e3})(e,t,s);class x{connections=[];statsParser;constructor(e){this.statsParser=e.statsParser}listConnections(){return[...this.connections]}addPeerConnection(e){this.connections.push({id:e.id??String(Date.now()+Math.random().toString(32)),pc:e.pc})}removePeerConnection(e){const t=this.connections.findIndex((({pc:t})=>t===e.pc));t>=0&&this.removeConnectionsByIndexes([t])}async parse(){const e=[],t=this.connections.map((async(t,s)=>{if(!R(t.pc))return this.statsParser.parse(t);e.unshift(s)}));e.length&&this.removeConnectionsByIndexes(e);return(await Promise.all(t)).filter((e=>void 0!==e))}removeConnectionsByIndexes(e){e.forEach((e=>{this.connections.splice(e,1)}))}}class E{prevStats=new Map;allowedReportTypes=new Set(["candidate-pair","inbound-rtp","outbound-rtp","remote-outbound-rtp","remote-inbound-rtp","track","transport"]);logger;constructor(e){this.logger=e.logger}get previouslyParsedStatsConnectionsIds(){return[...this.prevStats.keys()]}async parse(e){if(!R(e.pc))return this.getConnectionStats(e);this.logger.debug("Skip stats parsing. Connection is closed.",{connection:e})}async getConnectionStats(e){const{pc:t,id:s}=e;try{const o=Date.now(),n=await Promise.all(t.getReceivers().map((e=>e.getStats()))),r=await Promise.all(t.getSenders().map((e=>e.getStats())));return{id:s,stats:this.mapReportsStats([...n,...r],e),timeTaken:Date.now()-o}}catch(e){return void this.logger.error("Failed to get stats for PC",{id:s,pc:t,error:e})}}mapReportsStats(e,t){const s={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{},remote:{video:{inbound:[],outbound:[]},audio:{inbound:[],outbound:[]}}};e.forEach((e=>{e.forEach((t=>{this.allowedReportTypes.has(t.type)&&this.updateMappedStatsWithReportItemData(t,s,e)}))}));const{id:o}=t,n=this.prevStats.get(o);return n&&this.propagateStatsWithRateValues(s,n.stats),this.prevStats.set(o,{stats:s,ts:Date.now()}),S({taskId:o,delayMs:35e3,callback:()=>this.prevStats.delete(o)}),s}updateMappedStatsWithReportItemData(e,t,s){const o=e.type;if("candidate-pair"===o&&"succeeded"===e.state&&e.nominated)return void(t.connection=this.prepareConnectionStats(e,s));const n=this.getMediaType(e);if(n)if("outbound-rtp"!==o)if("inbound-rtp"!==o)"remote-outbound-rtp"!==o?"remote-inbound-rtp"===o&&(this.mapConnectionStatsIfNecessary(t,e,s),t.remote[n].inbound.push({...e})):t.remote[n].outbound.push({...e});else{const o=s.get(e.trackId)||s.get(e.mediaSourceId)||{};this.mapConnectionStatsIfNecessary(t,e,s);const r={...e,track:{...o}};t[n].inbound.push(r)}else{const o=s.get(e.trackId)||s.get(e.mediaSourceId)||{},r={...e,track:{...o}};t[n].outbound.push(r)}}getMediaType(e){const t=e.mediaType||e.kind;if(!["audio","video"].includes(t)){const{id:t}=e;if(!t)return;return String(t).includes("Video")?"video":String(t).includes("Audio")?"audio":void 0}return t}propagateStatsWithRateValues(e,t){e.audio.inbound.forEach((e=>{const s=t.audio.inbound.find((({id:t})=>t===e.id));e.bitrate=C(e,s,"bytesReceived"),e.packetRate=C(e,s,"packetsReceived")})),e.audio.outbound.forEach((e=>{const s=t.audio.outbound.find((({id:t})=>t===e.id));e.bitrate=C(e,s,"bytesSent"),e.packetRate=C(e,s,"packetsSent")})),e.video.inbound.forEach((e=>{const s=t.video.inbound.find((({id:t})=>t===e.id));e.bitrate=C(e,s,"bytesReceived"),e.packetRate=C(e,s,"packetsReceived")})),e.video.outbound.forEach((e=>{const s=t.video.outbound.find((({id:t})=>t===e.id));e.bitrate=C(e,s,"bytesSent"),e.packetRate=C(e,s,"packetsSent")}))}mapConnectionStatsIfNecessary(e,t,s){if(e.connection.id||!t.transportId)return;const o=s.get(t.transportId);if(o&&o.selectedCandidatePairId){const t=s.get(o.selectedCandidatePairId);e.connection=this.prepareConnectionStats(t,s)}}prepareConnectionStats(e,t){if(!e||!t)return{};const s={...e};if(s.remoteCandidateId){const e=t.get(s.remoteCandidateId);s.remote={...e}}if(s.localCandidateId){const e=t.get(s.localCandidateId);s.local={...e}}return s}}exports.AvailableOutgoingBitrateIssueDetector=y,exports.CompositeRTCStatsParser=x,exports.FramesDroppedIssueDetector=w,exports.FramesEncodedSentIssueDetector=b,exports.InboundNetworkIssueDetector=T,exports.NetworkMediaSyncIssueDetector=L,exports.NetworkScoresCalculator=v,exports.OutboundAudioIssueDetector=class extends k{performDetection(e){const{connection:{id:t}}=e,s=this.processData(e);return this.setLastProcessedStats(t,e),s}processData(e){const t=[];if("succeeded"!==e.connection.state)return t;const s=this.getLastProcessedStats(e.connection.id);if(!s)return t;const o=e.audio.outbound.filter((e=>!!e.mediaSourceId)),n=s.audio.outbound.filter((e=>!!e.mediaSourceId));if(!o.length||!n.length)return t;return o.reduce(((e,t)=>e+t.packetsSent),0)===n.reduce(((e,t)=>e+t.packetsSent),0)&&t.push({type:exports.IssueType.Stream,reason:exports.IssueReason.OutboundAudioNoData}),t}},exports.OutboundNetworkIssueDetector=P,exports.PeriodicWebRTCStatsReporter=g,exports.QualityLimitationsIssueDetector=I,exports.RTCStatsParser=E,exports.UnknownVideoDecoderImplementationDetector=D,exports.WebRTCIssueEmitter=m,exports.default=class{eventEmitter;#i=!1;detectors=[];networkScoresCalculator;statsReporter;compositeStatsParser;logger;constructor(e){this.logger=e.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.eventEmitter=e.issueEmitter??new m,e.onIssues&&this.eventEmitter.on(exports.EventType.Issue,e.onIssues),e.onNetworkScoresUpdated&&this.eventEmitter.on(exports.EventType.NetworkScoresUpdated,e.onNetworkScoresUpdated),this.detectors=e.detectors??[new I,new w,new b,new T,new P,new L,new y,new D],this.networkScoresCalculator=e.networkScoresCalculator??new v,this.compositeStatsParser=e.compositeStatsParser??new x({statsParser:new E({logger:this.logger})}),this.statsReporter=e.statsReporter??new g({compositeStatsParser:this.compositeStatsParser,getStatsInterval:e.getStatsInterval??5e3}),window.wid=this,this.wrapRTCPeerConnection(),this.statsReporter.on(g.STATS_REPORT_READY_EVENT,(t=>{this.detectIssues({data:t.stats,ignoreSSRCList:e.ignoreSSRCList}),this.calculateNetworkScores(t.stats)})),this.statsReporter.on(g.STATS_REPORTS_PARSED,(e=>{const t={timeTaken:e.timeTaken,ts:Date.now()};this.eventEmitter.emit(exports.EventType.StatsParsingFinished,t)}))}watchNewPeerConnections(){this.#i?this.logger.warn("WebRTCIssueDetector is already started. Skip processing"):(this.logger.info("Start watching peer connections"),this.#i=!0,this.statsReporter.startReporting())}stopWatchingNewPeerConnections(){this.#i?(this.logger.info("Stop watching peer connections"),this.#i=!1,this.statsReporter.stopReporting()):this.logger.warn("WebRTCIssueDetector is already stopped. Skip processing")}handleNewPeerConnection(e){this.#i?(this.logger.debug("Handling new peer connection",e),this.compositeStatsParser.addPeerConnection({pc:e})):this.logger.debug("Skip handling new peer connection. Detector is not running",e)}emitIssues(e){this.eventEmitter.emit(exports.EventType.Issue,e)}detectIssues({data:e,ignoreSSRCList:t}){let s=this.detectors.reduce(((t,s)=>[...t,...s.detect(e)]),[]);t?.length&&(s=s.filter((e=>!e.ssrc||!t.includes(e.ssrc)))),s.length>0&&this.emitIssues(s)}calculateNetworkScores(e){const t=this.networkScoresCalculator.calculate(e);this.eventEmitter.emit(exports.EventType.NetworkScoresUpdated,t)}wrapRTCPeerConnection(){if(!window.RTCPeerConnection)return void this.logger.warn("No RTCPeerConnection found in browser window. Skipping");const e=window.RTCPeerConnection,t=e=>this.handleNewPeerConnection(e);function s(s){const o=new e(s);return t(o),o}s.prototype=e.prototype,window.RTCPeerConnection=s}};

@@ -1,1 +0,1 @@

var t,e,s;function n(){}function o(){o.init.call(this)}function r(t){return void 0===t._maxListeners?o.defaultMaxListeners:t._maxListeners}function i(t,e,s){if(e)t.call(s);else for(var n=t.length,o=f(t,n),r=0;r<n;++r)o[r].call(s)}function a(t,e,s,n){if(e)t.call(s,n);else for(var o=t.length,r=f(t,o),i=0;i<o;++i)r[i].call(s,n)}function c(t,e,s,n,o){if(e)t.call(s,n,o);else for(var r=t.length,i=f(t,r),a=0;a<r;++a)i[a].call(s,n,o)}function d(t,e,s,n,o,r){if(e)t.call(s,n,o,r);else for(var i=t.length,a=f(t,i),c=0;c<i;++c)a[c].call(s,n,o,r)}function u(t,e,s,n){if(e)t.apply(s,n);else for(var o=t.length,r=f(t,o),i=0;i<o;++i)r[i].apply(s,n)}function l(t,e,s,o){var i,a,c,d;if("function"!=typeof s)throw new TypeError('"listener" argument must be a function');if((a=t._events)?(a.newListener&&(t.emit("newListener",e,s.listener?s.listener:s),a=t._events),c=a[e]):(a=t._events=new n,t._eventsCount=0),c){if("function"==typeof c?c=a[e]=o?[s,c]:[c,s]:o?c.unshift(s):c.push(s),!c.warned&&(i=r(t))&&i>0&&c.length>i){c.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+e+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=t,u.type=e,u.count=c.length,d=u,"function"==typeof console.warn?console.warn(d):console.log(d)}}else c=a[e]=s,++t._eventsCount;return t}function h(t,e,s){var n=!1;function o(){t.removeListener(e,o),n||(n=!0,s.apply(t,arguments))}return o.listener=s,o}function p(t){var e=this._events;if(e){var s=e[t];if("function"==typeof s)return 1;if(s)return s.length}return 0}function f(t,e){for(var s=new Array(e);e--;)s[e]=t[e];return s}n.prototype=Object.create(null),o.EventEmitter=o,o.usingDomains=!1,o.prototype.domain=void 0,o.prototype._events=void 0,o.prototype._maxListeners=void 0,o.defaultMaxListeners=10,o.init=function(){this.domain=null,o.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new n,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this},o.prototype.getMaxListeners=function(){return r(this)},o.prototype.emit=function(t){var e,s,n,o,r,l,h,p="error"===t;if(l=this._events)p=p&&null==l.error;else if(!p)return!1;if(h=this.domain,p){if(e=arguments[1],!h){if(e instanceof Error)throw e;var f=new Error('Uncaught, unspecified "error" event. ('+e+")");throw f.context=e,f}return e||(e=new Error('Uncaught, unspecified "error" event')),e.domainEmitter=this,e.domain=h,e.domainThrown=!1,h.emit("error",e),!1}if(!(s=l[t]))return!1;var m="function"==typeof s;switch(n=arguments.length){case 1:i(s,m,this);break;case 2:a(s,m,this,arguments[1]);break;case 3:c(s,m,this,arguments[1],arguments[2]);break;case 4:d(s,m,this,arguments[1],arguments[2],arguments[3]);break;default:for(o=new Array(n-1),r=1;r<n;r++)o[r-1]=arguments[r];u(s,m,this,o)}return!0},o.prototype.addListener=function(t,e){return l(this,t,e,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(t,e){return l(this,t,e,!0)},o.prototype.once=function(t,e){if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');return this.on(t,h(this,t,e)),this},o.prototype.prependOnceListener=function(t,e){if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');return this.prependListener(t,h(this,t,e)),this},o.prototype.removeListener=function(t,e){var s,o,r,i,a;if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');if(!(o=this._events))return this;if(!(s=o[t]))return this;if(s===e||s.listener&&s.listener===e)0==--this._eventsCount?this._events=new n:(delete o[t],o.removeListener&&this.emit("removeListener",t,s.listener||e));else if("function"!=typeof s){for(r=-1,i=s.length;i-- >0;)if(s[i]===e||s[i].listener&&s[i].listener===e){a=s[i].listener,r=i;break}if(r<0)return this;if(1===s.length){if(s[0]=void 0,0==--this._eventsCount)return this._events=new n,this;delete o[t]}else!function(t,e){for(var s=e,n=s+1,o=t.length;n<o;s+=1,n+=1)t[s]=t[n];t.pop()}(s,r);o.removeListener&&this.emit("removeListener",t,a||e)}return this},o.prototype.off=function(t,e){return this.removeListener(t,e)},o.prototype.removeAllListeners=function(t){var e,s;if(!(s=this._events))return this;if(!s.removeListener)return 0===arguments.length?(this._events=new n,this._eventsCount=0):s[t]&&(0==--this._eventsCount?this._events=new n:delete s[t]),this;if(0===arguments.length){for(var o,r=Object.keys(s),i=0;i<r.length;++i)"removeListener"!==(o=r[i])&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=new n,this._eventsCount=0,this}if("function"==typeof(e=s[t]))this.removeListener(t,e);else if(e)do{this.removeListener(t,e[e.length-1])}while(e[0]);return this},o.prototype.listeners=function(t){var e,s=this._events;return s&&(e=s[t])?"function"==typeof e?[e.listener||e]:function(t){for(var e=new Array(t.length),s=0;s<e.length;++s)e[s]=t[s].listener||t[s];return e}(e):[]},o.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):p.call(t,e)},o.prototype.listenerCount=p,o.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class m extends o{}!function(t){t.Issue="issue",t.NetworkScoresUpdated="network-scores-updated",t.StatsParsingFinished="stats-parsing-finished"}(t||(t={})),function(t){t.Network="network",t.CPU="cpu",t.Server="server",t.Stream="stream"}(e||(e={})),function(t){t.OutboundAudioNoData="outbount-audio-no-data",t.OutboundNetworkQuality="outbound-network-quality",t.InboundNetworkQuality="inbound-network-quality",t.OutboundNetworkMediaLatency="outbound-network-media-latency",t.InboundNetworkMediaLatency="inbound-network-media-latency",t.NetworkMediaSyncFailure="network-media-sync-failure",t.OutboundNetworkThroughput="outbound-network-throughput",t.InboundNetworkThroughput="inbound-network-throughput",t.EncoderCPUThrottling="encoder-cpu-throttling",t.DecoderCPUThrottling="decoder-cpu-throttling",t.ServerIssue="server-issue",t.UnknownVideoDecoderIssue="unknown-video-decoder",t.LowInboundMOS="low-inbound-mean-opinion-score",t.LowOutboundMOS="low-outbound-mean-opinion-score"}(s||(s={}));class g extends o{static STATS_REPORT_READY_EVENT="stats-report-ready";static STATS_REPORTS_PARSED="stats-reports-parsed";isStopped=!1;reportTimer;getStatsInterval;compositeStatsParser;constructor(t){super(),this.compositeStatsParser=t.compositeStatsParser,this.getStatsInterval=t.getStatsInterval??1e4}get isRunning(){return!!this.reportTimer&&!this.isStopped}startReporting(){if(this.reportTimer)return;const t=()=>setTimeout((()=>{this.isStopped?this.reportTimer=void 0:this.parseReports().finally((()=>{this.reportTimer=t()}))}),this.getStatsInterval);this.isStopped=!1,this.reportTimer=t()}stopReporting(){this.isStopped=!0,this.reportTimer&&(clearTimeout(this.reportTimer),this.reportTimer=void 0)}async parseReports(){const t=Date.now(),e=await this.compositeStatsParser.parse(),s=Date.now()-t;this.emit(g.STATS_REPORTS_PARSED,{timeTaken:s}),e.forEach((t=>{this.emit(g.STATS_REPORT_READY_EVENT,t)}))}}const S=(()=>{const t=new Map;return e=>{const{taskId:s,delayMs:n,maxJitterMs:o,callback:r}=e,i=Math.ceil(Math.random()*(o||0)),a=t.get(s);a&&clearTimeout(a);const c=setTimeout((()=>{r(),t.delete(s)}),n+i);t.set(s,c)}})();class v{#t={};calculate(t){const{connection:{id:e}}=t,s=this.calculateOutboundScore(t),n=this.calculateInboundScore(t);return this.#t[e]=t,S({taskId:e,delayMs:35e3,callback:()=>delete this.#t[e]}),{outbound:s,inbound:n}}calculateOutboundScore(t){const e=[...t.remote?.audio.inbound||[],...t.remote?.video.inbound||[]];if(!e.length)return;const s=this.#t[t.connection.id];if(!s)return;const n=[...s.remote?.audio.inbound||[],...s.remote?.video.inbound||[]],{packetsSent:o}=t.connection,r=s.connection.packetsSent,i=e.reduce(((t,e)=>{const s=n.find((t=>t.ssrc===e.ssrc));return{sumJitter:t.sumJitter+e.jitter,packetsLost:t.packetsLost+e.packetsLost,lastPacketsLost:t.lastPacketsLost+(s?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*t.connection.currentRoundTripTime||0,{sumJitter:c}=i,d=c/e.length,u=o-r,l=i.packetsLost-i.lastPacketsLost,h=u&&l?Math.round(100*l/(u+l)):0;return this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:h})}calculateInboundScore(t){const e=[...t.audio?.inbound,...t.video?.inbound];if(!e.length)return;const s=this.#t[t.connection.id];if(!s)return;const n=[...s.video?.inbound,...s.audio?.inbound],{packetsReceived:o}=t.connection,r=s.connection.packetsReceived,i=e.reduce(((t,e)=>{const s=n.find((t=>t.ssrc===e.ssrc));return{sumJitter:t.sumJitter+e.jitter,packetsLost:t.packetsLost+e.packetsLost,lastPacketsLost:t.lastPacketsLost+(s?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*t.connection.currentRoundTripTime||0,{sumJitter:c}=i,d=c/e.length,u=o-r,l=i.packetsLost-i.lastPacketsLost,h=u&&l?Math.round(100*l/(u+l)):0;return this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:h})}calculateMOS({avgJitter:t,rtt:e,packetsLoss:s}){const n=e+2*t+10;let o=n<160?93.2-n/40:93.2-n/120-10;return o-=2.5*s,1+.035*o+7e-6*o*(o-60)*(100-o)}}class k{#t;#e;constructor(t={}){this.#t=new Map,this.#e=t.statsCleanupTtlMs??35e3}detect(t){const e=this.performDetection(t);return this.performPrevStatsCleanup({connectionId:t.connection.id}),e}performPrevStatsCleanup(t){const{connectionId:e,cleanupCallback:s}=t;this.#t.has(e)&&S({taskId:e,delayMs:this.#e,callback:()=>{this.deleteLastProcessedStats(e),"function"==typeof s&&s()}})}setLastProcessedStats(t,e){this.#t.set(t,e)}getLastProcessedStats(t){return this.#t.get(t)}deleteLastProcessedStats(t){this.#t.delete(t)}}class w extends k{#s;constructor(t={}){super(t),this.#s=t.availableOutgoingBitrateThreshold??1e5}performDetection(t){const n=[],{availableOutgoingBitrate:o}=t.connection;if(void 0===o)return n;const r=t.audio.outbound.reduce(((t,e)=>t+e.targetBitrate),0),i=t.video.outbound.reduce(((t,e)=>t+e.bitrate),0);if(!r&&!i)return n;const a={availableOutgoingBitrate:o,videoStreamsTotalBitrate:i,audioStreamsTotalTargetBitrate:r};return r>o||i>0&&o<this.#s?(n.push({statsSample:a,type:e.Network,reason:s.OutboundNetworkThroughput}),n):n}}class b extends k{#n;constructor(t={}){super(t),this.#n=t.framesDroppedThreshold??.5}performDetection(t){const{connection:{id:e}}=t,s=this.processData(t);return this.setLastProcessedStats(e,t),s}processData(t){const n=t.video.inbound.filter((t=>t.framesDropped>0)),o=[],r=this.getLastProcessedStats(t.connection.id)?.video.inbound;return r?(n.forEach((t=>{const n=r.find((e=>e.ssrc===t.ssrc));if(!n)return;if(t.framesDropped===n.framesDropped)return;const i=t.framesReceived-n.framesReceived,a=t.framesDecoded-n.framesDecoded,c=t.framesDropped-n.framesDropped,d=c/i;if(0===i||0===a)return;const u={deltaFramesDropped:c,deltaFramesReceived:i,deltaFramesDecoded:a,framesDroppedPct:Math.round(100*d)};d>=this.#n&&o.push({statsSample:u,type:e.CPU,reason:s.DecoderCPUThrottling,ssrc:t.ssrc})})),o):o}}class y extends k{#o;constructor(t={}){super(t),this.#o=t.missedFramesThreshold??.15}performDetection(t){const{connection:{id:e}}=t,s=this.processData(t);return this.setLastProcessedStats(e,t),s}processData(t){const n=t.video.outbound.filter((t=>t.framesEncoded>0)),o=[],r=this.getLastProcessedStats(t.connection.id)?.video.outbound;return r?(n.forEach((t=>{const n=r.find((e=>e.ssrc===t.ssrc));if(!n)return;if(t.framesEncoded===n.framesEncoded)return;const i=t.framesEncoded-n.framesEncoded,a=t.framesSent-n.framesSent,c=1-a/i;if(0===i)return;if(i===a)return;const d={deltaFramesSent:a,deltaFramesEncoded:i,missedFramesPct:Math.round(100*c)};c>=this.#o&&o.push({statsSample:d,type:e.Network,reason:s.OutboundNetworkThroughput,ssrc:t.ssrc})})),o):o}}class L extends k{highPacketLossThresholdPct;highJitterThreshold;highJitterBufferDelayThresholdMs;highRttThresholdMs;constructor(t={}){super(),this.highPacketLossThresholdPct=t.highPacketLossThresholdPct??5,this.highJitterThreshold=t.highJitterThreshold??200,this.highJitterBufferDelayThresholdMs=t.highJitterBufferDelayThresholdMs??500,this.highRttThresholdMs=t.highRttThresholdMs??250}performDetection(t){const{connection:{id:e}}=t,s=this.processData(t);return this.setLastProcessedStats(e,t),s}processData(t){const n=[],o=[...t.audio?.inbound,...t.video?.inbound];if(!o.length)return n;const r=this.getLastProcessedStats(t.connection.id);if(!r)return n;const i=[...r.video?.inbound,...r.audio?.inbound],{packetsReceived:a}=t.connection,c=r.connection.packetsReceived,d=o.reduce(((t,e)=>{const s=i.find((t=>t.ssrc===e.ssrc)),n=s?.jitterBufferDelay||0,o=s?.jitterBufferEmittedCount||0,r=e.jitterBufferDelay-n,a=e.jitterBufferEmittedCount-o,c=r&&a?1e3*r/a:0;return{sumJitter:t.sumJitter+e.jitter,sumJitterBufferDelayMs:t.sumJitterBufferDelayMs+c,packetsLost:t.packetsLost+e.packetsLost,lastPacketsLost:t.lastPacketsLost+(s?.packetsLost||0)}}),{sumJitter:0,sumJitterBufferDelayMs:0,packetsLost:0,lastPacketsLost:0}),u=1e3*t.connection.currentRoundTripTime||0,{sumJitter:l,sumJitterBufferDelayMs:h}=d,p=l/o.length,f=h/o.length,m=a-c,g=d.packetsLost-d.lastPacketsLost,S=m&&g?Math.round(100*g/(m+g)):0,v=S>this.highPacketLossThresholdPct,k=p>=this.highJitterThreshold,w=u>=this.highRttThresholdMs,b=f>this.highJitterBufferDelayThresholdMs,y=w&&!k&&!v,L=v&&k,P=k&&b,T={rtt:u,packetLossPct:S,avgJitter:p,avgJitterBufferDelay:f};return(k||v)&&n.push({statsSample:T,type:e.Network,reason:s.InboundNetworkQuality,iceCandidate:t.connection.local.id}),y&&n.push({statsSample:T,type:e.Server,reason:s.ServerIssue,iceCandidate:t.connection.remote.id}),L&&n.push({statsSample:T,type:e.Network,reason:s.InboundNetworkMediaLatency,iceCandidate:t.connection.local.id}),P&&n.push({statsSample:T,type:e.Network,reason:s.NetworkMediaSyncFailure,iceCandidate:t.connection.local.id}),n}}class P extends k{performDetection(t){const{connection:{id:e}}=t,s=this.processData(t);return this.setLastProcessedStats(e,t),s}processData(t){const n=t.audio.inbound,o=[],r=this.getLastProcessedStats(t.connection.id)?.audio.inbound;return r?(n.forEach((t=>{const n=r.find((e=>e.ssrc===t.ssrc));if(!n)return;const i=t.track.insertedSamplesForDeceleration+t.track.removedSamplesForAcceleration,a=n.track.insertedSamplesForDeceleration+n.track.removedSamplesForAcceleration;if(i===a)return;const c=t.track.totalSamplesReceived-n.track.totalSamplesReceived,d=i-a,u=Math.round(100*d/c),l={correctedSamplesPct:u};u>5&&o.push({statsSample:l,type:e.Network,reason:s.NetworkMediaSyncFailure,ssrc:t.ssrc})})),o):o}}class T extends k{performDetection(t){const{connection:{id:e}}=t,s=this.processData(t);return this.setLastProcessedStats(e,t),s}processData(t){const n=[],o=[...t.remote?.audio.inbound||[],...t.remote?.video.inbound||[]];if(!o.length)return n;const r=this.getLastProcessedStats(t.connection.id);if(!r)return n;const i=[...r.remote?.audio.inbound||[],...r.remote?.video.inbound||[]],{packetsSent:a}=t.connection,c=r.connection.packetsSent,d=o.reduce(((t,e)=>{const s=i.find((t=>t.ssrc===e.ssrc));return{sumJitter:t.sumJitter+e.jitter,packetsLost:t.packetsLost+e.packetsLost,lastPacketsLost:t.lastPacketsLost+(s?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),u=1e3*t.connection.currentRoundTripTime||0,{sumJitter:l}=d,h=l/o.length,p=a-c,f=d.packetsLost-d.lastPacketsLost,m=p&&f?Math.round(100*f/(p+f)):0,g=m>5,S=h>=200,v=!g&&S||S||g,k={rtt:u,avgJitter:h,packetLossPct:m};return g&&S&&n.push({statsSample:k,type:e.Network,reason:s.OutboundNetworkMediaLatency,iceCandidate:t.connection.local.id}),v&&n.push({statsSample:k,type:e.Network,reason:s.OutboundNetworkQuality,iceCandidate:t.connection.local.id}),n}}class D extends k{performDetection(t){const{connection:{id:e}}=t,s=this.processData(t);return this.setLastProcessedStats(e,t),s}processData(t){const n=[];if(console.log("data.connection.state",t.connection.state),"succeeded"!==t.connection.state)return n;const o=this.getLastProcessedStats(t.connection.id);if(!o)return n;const r=t.audio.outbound.filter((t=>!!t.mediaSourceId)),i=o.audio.outbound.filter((t=>!!t.mediaSourceId));if(!r.length||!i.length)return n;const a=r.reduce(((t,e)=>t+e.packetsSent),0),c=i.reduce(((t,e)=>t+e.packetsSent),0);return console.log(t.audio.outbound,o.audio.outbound),console.log("audio pkt",c,a),a==c&&n.push({type:e.Stream,reason:s.OutboundAudioNoData}),n}}class C extends k{performDetection(t){const{connection:{id:e}}=t,s=this.processData(t);return this.setLastProcessedStats(e,t),s}processData(t){const n=t.video.outbound.filter((t=>"none"!==t.qualityLimitationReason)),o=[],r=this.getLastProcessedStats(t.connection.id)?.video.outbound;return r?(n.forEach((t=>{const n=r.find((e=>e.ssrc===t.ssrc));if(!n)return;const i={qualityLimitationReason:t.qualityLimitationReason};t.framesSent>n.framesSent||("cpu"===t.qualityLimitationReason&&o.push({statsSample:i,type:e.CPU,reason:s.EncoderCPUThrottling,ssrc:t.ssrc}),"bandwidth"===t.qualityLimitationReason&&o.push({statsSample:i,type:e.Network,reason:s.OutboundNetworkThroughput,ssrc:t.ssrc}))})),o):o}}class R extends k{UNKNOWN_DECODER="unknown";#r={};performDetection(t){const{connection:{id:e}}=t,s=this.processData(t);return this.setLastProcessedStats(e,t),s}performPrevStatsCleanup(t){const{connectionId:e,cleanupCallback:s}=t;super.performPrevStatsCleanup({...t,cleanupCallback:()=>{delete this.#r[e],"function"==typeof s&&s()}})}processData(t){const n=[],{id:o}=t.connection,r=this.getLastProcessedStats(o)?.video.inbound;return t.video.inbound.forEach((t=>{const{decoderImplementation:i,ssrc:a}=t,c=r?.find((t=>t.ssrc===a));if(c)if(i===this.UNKNOWN_DECODER){if(!this.hadLastDecoderWithIssue(o,a)){this.setLastDecoderWithIssue(o,a,this.UNKNOWN_DECODER);const r={mimeType:t.mimeType,decoderImplementation:i};n.push({ssrc:a,statsSample:r,type:e.Stream,reason:s.UnknownVideoDecoderIssue,trackIdentifier:t.track.trackIdentifier})}}else this.setLastDecoderWithIssue(o,a,void 0)})),n}setLastDecoderWithIssue(t,e,s){const n=this.#r[t]??{};void 0===s?delete n[e]:n[e]=s,this.#r[t]=n}hadLastDecoderWithIssue(t,e){const s=this.#r[t];return(s&&s[e])===this.UNKNOWN_DECODER}}const I=t=>"closed"===t.iceConnectionState||"closed"===t.connectionState,E=(t,e,s)=>8*((t,e,s)=>{if(!e)return 0;const n=t[s],o=e[s];if(null==n||null==o)return 0;const r=Math.floor(t.timestamp)-Math.floor(e.timestamp);return 0===r?0:(Number(n)-Number(o))/r*1e3})(t,e,s);class N{connections=[];statsParser;constructor(t){this.statsParser=t.statsParser}listConnections(){return[...this.connections]}addPeerConnection(t){this.connections.push({id:t.id??String(Date.now()+Math.random().toString(32)),pc:t.pc})}removePeerConnection(t){const e=this.connections.findIndex((({pc:e})=>e===t.pc));e>=0&&this.removeConnectionsByIndexes([e])}async parse(){const t=[],e=this.connections.map((async(e,s)=>{if(!I(e.pc))return this.statsParser.parse(e);t.unshift(s)}));t.length&&this.removeConnectionsByIndexes(t);return(await Promise.all(e)).filter((t=>void 0!==t))}removeConnectionsByIndexes(t){t.forEach((t=>{this.connections.splice(t,1)}))}}class M{prevStats=new Map;allowedReportTypes=new Set(["candidate-pair","inbound-rtp","outbound-rtp","remote-outbound-rtp","remote-inbound-rtp","track","transport"]);logger;constructor(t){this.logger=t.logger}get previouslyParsedStatsConnectionsIds(){return[...this.prevStats.keys()]}async parse(t){if(!I(t.pc))return this.getConnectionStats(t);this.logger.debug("Skip stats parsing. Connection is closed.",{connection:t})}async getConnectionStats(t){const{pc:e,id:s}=t;try{const n=Date.now(),o=await Promise.all(e.getReceivers().map((t=>t.getStats()))),r=await Promise.all(e.getSenders().map((t=>t.getStats())));return{id:s,stats:this.mapReportsStats([...o,...r],t),timeTaken:Date.now()-n}}catch(t){return void this.logger.error("Failed to get stats for PC",{id:s,pc:e,error:t})}}mapReportsStats(t,e){const s={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{},remote:{video:{inbound:[],outbound:[]},audio:{inbound:[],outbound:[]}}};t.forEach((t=>{t.forEach((e=>{this.allowedReportTypes.has(e.type)&&this.updateMappedStatsWithReportItemData(e,s,t)}))}));const{id:n}=e,o=this.prevStats.get(n);return o&&this.propagateStatsWithRateValues(s,o.stats),this.prevStats.set(n,{stats:s,ts:Date.now()}),S({taskId:n,delayMs:35e3,callback:()=>this.prevStats.delete(n)}),s}updateMappedStatsWithReportItemData(t,e,s){const n=t.type;if("candidate-pair"===n&&"succeeded"===t.state&&t.nominated)return void(e.connection=this.prepareConnectionStats(t,s));const o=this.getMediaType(t);if(o)if("outbound-rtp"!==n)if("inbound-rtp"!==n)"remote-outbound-rtp"!==n?"remote-inbound-rtp"===n&&(this.mapConnectionStatsIfNecessary(e,t,s),e.remote[o].inbound.push({...t})):e.remote[o].outbound.push({...t});else{const n=s.get(t.trackId)||s.get(t.mediaSourceId)||{};this.mapConnectionStatsIfNecessary(e,t,s);const r={...t,track:{...n}};e[o].inbound.push(r)}else{const n=s.get(t.trackId)||s.get(t.mediaSourceId)||{},r={...t,track:{...n}};e[o].outbound.push(r)}}getMediaType(t){const e=t.mediaType||t.kind;if(!["audio","video"].includes(e)){const{id:e}=t;if(!e)return;return String(e).includes("Video")?"video":String(e).includes("Audio")?"audio":void 0}return e}propagateStatsWithRateValues(t,e){t.audio.inbound.forEach((t=>{const s=e.audio.inbound.find((({id:e})=>e===t.id));t.bitrate=E(t,s,"bytesReceived"),t.packetRate=E(t,s,"packetsReceived")})),t.audio.outbound.forEach((t=>{const s=e.audio.outbound.find((({id:e})=>e===t.id));t.bitrate=E(t,s,"bytesSent"),t.packetRate=E(t,s,"packetsSent")})),t.video.inbound.forEach((t=>{const s=e.video.inbound.find((({id:e})=>e===t.id));t.bitrate=E(t,s,"bytesReceived"),t.packetRate=E(t,s,"packetsReceived")})),t.video.outbound.forEach((t=>{const s=e.video.outbound.find((({id:e})=>e===t.id));t.bitrate=E(t,s,"bytesSent"),t.packetRate=E(t,s,"packetsSent")}))}mapConnectionStatsIfNecessary(t,e,s){if(t.connection.id||!e.transportId)return;const n=s.get(e.transportId);if(n&&n.selectedCandidatePairId){const e=s.get(n.selectedCandidatePairId);t.connection=this.prepareConnectionStats(e,s)}}prepareConnectionStats(t,e){if(!t||!e)return{};const s={...t};if(s.remoteCandidateId){const t=e.get(s.remoteCandidateId);s.remote={...t}}if(s.localCandidateId){const t=e.get(s.localCandidateId);s.local={...t}}return s}}class _{eventEmitter;#i=!1;detectors=[];networkScoresCalculator;statsReporter;compositeStatsParser;logger;constructor(e){this.logger=e.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.eventEmitter=e.issueEmitter??new m,e.onIssues&&this.eventEmitter.on(t.Issue,e.onIssues),e.onNetworkScoresUpdated&&this.eventEmitter.on(t.NetworkScoresUpdated,e.onNetworkScoresUpdated),this.detectors=e.detectors??[new C,new b,new y,new L,new T,new P,new w,new R],this.networkScoresCalculator=e.networkScoresCalculator??new v,this.compositeStatsParser=e.compositeStatsParser??new N({statsParser:new M({logger:this.logger})}),this.statsReporter=e.statsReporter??new g({compositeStatsParser:this.compositeStatsParser,getStatsInterval:e.getStatsInterval??5e3}),window.wid=this,this.wrapRTCPeerConnection(),this.statsReporter.on(g.STATS_REPORT_READY_EVENT,(t=>{this.detectIssues({data:t.stats,ignoreSSRCList:e.ignoreSSRCList}),this.calculateNetworkScores(t.stats)})),this.statsReporter.on(g.STATS_REPORTS_PARSED,(e=>{const s={timeTaken:e.timeTaken,ts:Date.now()};this.eventEmitter.emit(t.StatsParsingFinished,s)}))}watchNewPeerConnections(){this.#i?this.logger.warn("WebRTCIssueDetector is already started. Skip processing"):(this.logger.info("Start watching peer connections"),this.#i=!0,this.statsReporter.startReporting())}stopWatchingNewPeerConnections(){this.#i?(this.logger.info("Stop watching peer connections"),this.#i=!1,this.statsReporter.stopReporting()):this.logger.warn("WebRTCIssueDetector is already stopped. Skip processing")}handleNewPeerConnection(t){this.#i?(this.logger.debug("Handling new peer connection",t),this.compositeStatsParser.addPeerConnection({pc:t})):this.logger.debug("Skip handling new peer connection. Detector is not running",t)}emitIssues(e){this.eventEmitter.emit(t.Issue,e)}detectIssues({data:t,ignoreSSRCList:e}){let s=this.detectors.reduce(((e,s)=>[...e,...s.detect(t)]),[]);e?.length&&(s=s.filter((t=>!t.ssrc||!e.includes(t.ssrc)))),s.length>0&&this.emitIssues(s)}calculateNetworkScores(e){const s=this.networkScoresCalculator.calculate(e);this.eventEmitter.emit(t.NetworkScoresUpdated,s)}wrapRTCPeerConnection(){if(!window.RTCPeerConnection)return void this.logger.warn("No RTCPeerConnection found in browser window. Skipping");const t=window.RTCPeerConnection,e=t=>this.handleNewPeerConnection(t);function s(s){const n=new t(s);return e(n),n}s.prototype=t.prototype,window.RTCPeerConnection=s}}export{w as AvailableOutgoingBitrateIssueDetector,N as CompositeRTCStatsParser,t as EventType,b as FramesDroppedIssueDetector,y as FramesEncodedSentIssueDetector,L as InboundNetworkIssueDetector,s as IssueReason,e as IssueType,P as NetworkMediaSyncIssueDetector,v as NetworkScoresCalculator,D as OutboundAudioIssueDetector,T as OutboundNetworkIssueDetector,g as PeriodicWebRTCStatsReporter,C as QualityLimitationsIssueDetector,M as RTCStatsParser,R as UnknownVideoDecoderImplementationDetector,m as WebRTCIssueEmitter,_ as default};
var t,e,s;function n(){}function o(){o.init.call(this)}function r(t){return void 0===t._maxListeners?o.defaultMaxListeners:t._maxListeners}function i(t,e,s){if(e)t.call(s);else for(var n=t.length,o=f(t,n),r=0;r<n;++r)o[r].call(s)}function a(t,e,s,n){if(e)t.call(s,n);else for(var o=t.length,r=f(t,o),i=0;i<o;++i)r[i].call(s,n)}function c(t,e,s,n,o){if(e)t.call(s,n,o);else for(var r=t.length,i=f(t,r),a=0;a<r;++a)i[a].call(s,n,o)}function d(t,e,s,n,o,r){if(e)t.call(s,n,o,r);else for(var i=t.length,a=f(t,i),c=0;c<i;++c)a[c].call(s,n,o,r)}function u(t,e,s,n){if(e)t.apply(s,n);else for(var o=t.length,r=f(t,o),i=0;i<o;++i)r[i].apply(s,n)}function h(t,e,s,o){var i,a,c,d;if("function"!=typeof s)throw new TypeError('"listener" argument must be a function');if((a=t._events)?(a.newListener&&(t.emit("newListener",e,s.listener?s.listener:s),a=t._events),c=a[e]):(a=t._events=new n,t._eventsCount=0),c){if("function"==typeof c?c=a[e]=o?[s,c]:[c,s]:o?c.unshift(s):c.push(s),!c.warned&&(i=r(t))&&i>0&&c.length>i){c.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+e+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=t,u.type=e,u.count=c.length,d=u,"function"==typeof console.warn?console.warn(d):console.log(d)}}else c=a[e]=s,++t._eventsCount;return t}function l(t,e,s){var n=!1;function o(){t.removeListener(e,o),n||(n=!0,s.apply(t,arguments))}return o.listener=s,o}function p(t){var e=this._events;if(e){var s=e[t];if("function"==typeof s)return 1;if(s)return s.length}return 0}function f(t,e){for(var s=new Array(e);e--;)s[e]=t[e];return s}n.prototype=Object.create(null),o.EventEmitter=o,o.usingDomains=!1,o.prototype.domain=void 0,o.prototype._events=void 0,o.prototype._maxListeners=void 0,o.defaultMaxListeners=10,o.init=function(){this.domain=null,o.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new n,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this},o.prototype.getMaxListeners=function(){return r(this)},o.prototype.emit=function(t){var e,s,n,o,r,h,l,p="error"===t;if(h=this._events)p=p&&null==h.error;else if(!p)return!1;if(l=this.domain,p){if(e=arguments[1],!l){if(e instanceof Error)throw e;var f=new Error('Uncaught, unspecified "error" event. ('+e+")");throw f.context=e,f}return e||(e=new Error('Uncaught, unspecified "error" event')),e.domainEmitter=this,e.domain=l,e.domainThrown=!1,l.emit("error",e),!1}if(!(s=h[t]))return!1;var m="function"==typeof s;switch(n=arguments.length){case 1:i(s,m,this);break;case 2:a(s,m,this,arguments[1]);break;case 3:c(s,m,this,arguments[1],arguments[2]);break;case 4:d(s,m,this,arguments[1],arguments[2],arguments[3]);break;default:for(o=new Array(n-1),r=1;r<n;r++)o[r-1]=arguments[r];u(s,m,this,o)}return!0},o.prototype.addListener=function(t,e){return h(this,t,e,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(t,e){return h(this,t,e,!0)},o.prototype.once=function(t,e){if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');return this.on(t,l(this,t,e)),this},o.prototype.prependOnceListener=function(t,e){if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');return this.prependListener(t,l(this,t,e)),this},o.prototype.removeListener=function(t,e){var s,o,r,i,a;if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');if(!(o=this._events))return this;if(!(s=o[t]))return this;if(s===e||s.listener&&s.listener===e)0==--this._eventsCount?this._events=new n:(delete o[t],o.removeListener&&this.emit("removeListener",t,s.listener||e));else if("function"!=typeof s){for(r=-1,i=s.length;i-- >0;)if(s[i]===e||s[i].listener&&s[i].listener===e){a=s[i].listener,r=i;break}if(r<0)return this;if(1===s.length){if(s[0]=void 0,0==--this._eventsCount)return this._events=new n,this;delete o[t]}else!function(t,e){for(var s=e,n=s+1,o=t.length;n<o;s+=1,n+=1)t[s]=t[n];t.pop()}(s,r);o.removeListener&&this.emit("removeListener",t,a||e)}return this},o.prototype.off=function(t,e){return this.removeListener(t,e)},o.prototype.removeAllListeners=function(t){var e,s;if(!(s=this._events))return this;if(!s.removeListener)return 0===arguments.length?(this._events=new n,this._eventsCount=0):s[t]&&(0==--this._eventsCount?this._events=new n:delete s[t]),this;if(0===arguments.length){for(var o,r=Object.keys(s),i=0;i<r.length;++i)"removeListener"!==(o=r[i])&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=new n,this._eventsCount=0,this}if("function"==typeof(e=s[t]))this.removeListener(t,e);else if(e)do{this.removeListener(t,e[e.length-1])}while(e[0]);return this},o.prototype.listeners=function(t){var e,s=this._events;return s&&(e=s[t])?"function"==typeof e?[e.listener||e]:function(t){for(var e=new Array(t.length),s=0;s<e.length;++s)e[s]=t[s].listener||t[s];return e}(e):[]},o.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):p.call(t,e)},o.prototype.listenerCount=p,o.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class m extends o{}!function(t){t.Issue="issue",t.NetworkScoresUpdated="network-scores-updated",t.StatsParsingFinished="stats-parsing-finished"}(t||(t={})),function(t){t.Network="network",t.CPU="cpu",t.Server="server",t.Stream="stream"}(e||(e={})),function(t){t.OutboundAudioNoData="outbount-audio-no-data",t.OutboundNetworkQuality="outbound-network-quality",t.InboundNetworkQuality="inbound-network-quality",t.OutboundNetworkMediaLatency="outbound-network-media-latency",t.InboundNetworkMediaLatency="inbound-network-media-latency",t.NetworkMediaSyncFailure="network-media-sync-failure",t.OutboundNetworkThroughput="outbound-network-throughput",t.InboundNetworkThroughput="inbound-network-throughput",t.EncoderCPUThrottling="encoder-cpu-throttling",t.DecoderCPUThrottling="decoder-cpu-throttling",t.ServerIssue="server-issue",t.UnknownVideoDecoderIssue="unknown-video-decoder",t.LowInboundMOS="low-inbound-mean-opinion-score",t.LowOutboundMOS="low-outbound-mean-opinion-score"}(s||(s={}));class g extends o{static STATS_REPORT_READY_EVENT="stats-report-ready";static STATS_REPORTS_PARSED="stats-reports-parsed";isStopped=!1;reportTimer;getStatsInterval;compositeStatsParser;constructor(t){super(),this.compositeStatsParser=t.compositeStatsParser,this.getStatsInterval=t.getStatsInterval??1e4}get isRunning(){return!!this.reportTimer&&!this.isStopped}startReporting(){if(this.reportTimer)return;const t=()=>setTimeout((()=>{this.isStopped?this.reportTimer=void 0:this.parseReports().finally((()=>{this.reportTimer=t()}))}),this.getStatsInterval);this.isStopped=!1,this.reportTimer=t()}stopReporting(){this.isStopped=!0,this.reportTimer&&(clearTimeout(this.reportTimer),this.reportTimer=void 0)}async parseReports(){const t=Date.now(),e=await this.compositeStatsParser.parse(),s=Date.now()-t;this.emit(g.STATS_REPORTS_PARSED,{timeTaken:s}),e.forEach((t=>{this.emit(g.STATS_REPORT_READY_EVENT,t)}))}}const S=(()=>{const t=new Map;return e=>{const{taskId:s,delayMs:n,maxJitterMs:o,callback:r}=e,i=Math.ceil(Math.random()*(o||0)),a=t.get(s);a&&clearTimeout(a);const c=setTimeout((()=>{r(),t.delete(s)}),n+i);t.set(s,c)}})();class v{#t={};calculate(t){const{connection:{id:e}}=t,s=this.calculateOutboundScore(t),n=this.calculateInboundScore(t);return this.#t[e]=t,S({taskId:e,delayMs:35e3,callback:()=>delete this.#t[e]}),{outbound:s,inbound:n}}calculateOutboundScore(t){const e=[...t.remote?.audio.inbound||[],...t.remote?.video.inbound||[]];if(!e.length)return;const s=this.#t[t.connection.id];if(!s)return;const n=[...s.remote?.audio.inbound||[],...s.remote?.video.inbound||[]],{packetsSent:o}=t.connection,r=s.connection.packetsSent,i=e.reduce(((t,e)=>{const s=n.find((t=>t.ssrc===e.ssrc));return{sumJitter:t.sumJitter+e.jitter,packetsLost:t.packetsLost+e.packetsLost,lastPacketsLost:t.lastPacketsLost+(s?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*t.connection.currentRoundTripTime||0,{sumJitter:c}=i,d=c/e.length,u=i.packetsLost-i.lastPacketsLost,h=o-r;if(0==h&&0==u)return;const l=h&&u?Math.round(100*u/(h+u)):0;return this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:l})}calculateInboundScore(t){const e=[...t.audio?.inbound,...t.video?.inbound];if(!e.length)return;const s=this.#t[t.connection.id];if(!s)return;const n=[...s.video?.inbound,...s.audio?.inbound],{packetsReceived:o}=t.connection,r=s.connection.packetsReceived,i=e.reduce(((t,e)=>{const s=n.find((t=>t.ssrc===e.ssrc));return{sumJitter:t.sumJitter+e.jitter,packetsLost:t.packetsLost+e.packetsLost,lastPacketsLost:t.lastPacketsLost+(s?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*t.connection.currentRoundTripTime||0,{sumJitter:c}=i,d=c/e.length,u=o-r,h=i.packetsLost-i.lastPacketsLost;if(0==u&&0==h)return;const l=u&&h?Math.round(100*h/(u+h)):0;return this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:l})}calculateMOS({avgJitter:t,rtt:e,packetsLoss:s}){const n=e+2*t+10;let o=n<160?93.2-n/40:93.2-n/120-10;return o-=2.5*s,1+.035*o+7e-6*o*(o-60)*(100-o)}}class k{#t;#e;constructor(t={}){this.#t=new Map,this.#e=t.statsCleanupTtlMs??35e3}detect(t){const e=this.performDetection(t);return this.performPrevStatsCleanup({connectionId:t.connection.id}),e}performPrevStatsCleanup(t){const{connectionId:e,cleanupCallback:s}=t;this.#t.has(e)&&S({taskId:e,delayMs:this.#e,callback:()=>{this.deleteLastProcessedStats(e),"function"==typeof s&&s()}})}setLastProcessedStats(t,e){this.#t.set(t,e)}getLastProcessedStats(t){return this.#t.get(t)}deleteLastProcessedStats(t){this.#t.delete(t)}}class w extends k{#s;constructor(t={}){super(t),this.#s=t.availableOutgoingBitrateThreshold??1e5}performDetection(t){const n=[],{availableOutgoingBitrate:o}=t.connection;if(void 0===o)return n;const r=t.audio.outbound.reduce(((t,e)=>t+e.targetBitrate),0),i=t.video.outbound.reduce(((t,e)=>t+e.bitrate),0);if(!r&&!i)return n;const a={availableOutgoingBitrate:o,videoStreamsTotalBitrate:i,audioStreamsTotalTargetBitrate:r};return r>o||i>0&&o<this.#s?(n.push({statsSample:a,type:e.Network,reason:s.OutboundNetworkThroughput}),n):n}}class b extends k{#n;constructor(t={}){super(t),this.#n=t.framesDroppedThreshold??.5}performDetection(t){const{connection:{id:e}}=t,s=this.processData(t);return this.setLastProcessedStats(e,t),s}processData(t){const n=t.video.inbound.filter((t=>t.framesDropped>0)),o=[],r=this.getLastProcessedStats(t.connection.id)?.video.inbound;return r?(n.forEach((t=>{const n=r.find((e=>e.ssrc===t.ssrc));if(!n)return;if(t.framesDropped===n.framesDropped)return;const i=t.framesReceived-n.framesReceived,a=t.framesDecoded-n.framesDecoded,c=t.framesDropped-n.framesDropped,d=c/i;if(0===i||0===a)return;const u={deltaFramesDropped:c,deltaFramesReceived:i,deltaFramesDecoded:a,framesDroppedPct:Math.round(100*d)};d>=this.#n&&o.push({statsSample:u,type:e.CPU,reason:s.DecoderCPUThrottling,ssrc:t.ssrc})})),o):o}}class y extends k{#o;constructor(t={}){super(t),this.#o=t.missedFramesThreshold??.15}performDetection(t){const{connection:{id:e}}=t,s=this.processData(t);return this.setLastProcessedStats(e,t),s}processData(t){const n=t.video.outbound.filter((t=>t.framesEncoded>0)),o=[],r=this.getLastProcessedStats(t.connection.id)?.video.outbound;return r?(n.forEach((t=>{const n=r.find((e=>e.ssrc===t.ssrc));if(!n)return;if(t.framesEncoded===n.framesEncoded)return;const i=t.framesEncoded-n.framesEncoded,a=t.framesSent-n.framesSent,c=1-a/i;if(0===i)return;if(i===a)return;const d={deltaFramesSent:a,deltaFramesEncoded:i,missedFramesPct:Math.round(100*c)};c>=this.#o&&o.push({statsSample:d,type:e.Network,reason:s.OutboundNetworkThroughput,ssrc:t.ssrc})})),o):o}}class L extends k{highPacketLossThresholdPct;highJitterThreshold;highJitterBufferDelayThresholdMs;highRttThresholdMs;constructor(t={}){super(),this.highPacketLossThresholdPct=t.highPacketLossThresholdPct??5,this.highJitterThreshold=t.highJitterThreshold??200,this.highJitterBufferDelayThresholdMs=t.highJitterBufferDelayThresholdMs??500,this.highRttThresholdMs=t.highRttThresholdMs??250}performDetection(t){const{connection:{id:e}}=t,s=this.processData(t);return this.setLastProcessedStats(e,t),s}processData(t){const n=[],o=[...t.audio?.inbound,...t.video?.inbound];if(!o.length)return n;const r=this.getLastProcessedStats(t.connection.id);if(!r)return n;const i=[...r.video?.inbound,...r.audio?.inbound],{packetsReceived:a}=t.connection,c=r.connection.packetsReceived,d=o.reduce(((t,e)=>{const s=i.find((t=>t.ssrc===e.ssrc)),n=s?.jitterBufferDelay||0,o=s?.jitterBufferEmittedCount||0,r=e.jitterBufferDelay-n,a=e.jitterBufferEmittedCount-o,c=r&&a?1e3*r/a:0;return{sumJitter:t.sumJitter+e.jitter,sumJitterBufferDelayMs:t.sumJitterBufferDelayMs+c,packetsLost:t.packetsLost+e.packetsLost,lastPacketsLost:t.lastPacketsLost+(s?.packetsLost||0)}}),{sumJitter:0,sumJitterBufferDelayMs:0,packetsLost:0,lastPacketsLost:0}),u=1e3*t.connection.currentRoundTripTime||0,{sumJitter:h,sumJitterBufferDelayMs:l}=d,p=h/o.length,f=l/o.length,m=a-c,g=d.packetsLost-d.lastPacketsLost,S=m&&g?Math.round(100*g/(m+g)):0,v=S>this.highPacketLossThresholdPct,k=p>=this.highJitterThreshold,w=u>=this.highRttThresholdMs,b=f>this.highJitterBufferDelayThresholdMs,y=w&&!k&&!v,L=v&&k,P=k&&b,T={rtt:u,packetLossPct:S,avgJitter:p,avgJitterBufferDelay:f};return(k||v)&&n.push({statsSample:T,type:e.Network,reason:s.InboundNetworkQuality,iceCandidate:t.connection.local.id}),y&&n.push({statsSample:T,type:e.Server,reason:s.ServerIssue,iceCandidate:t.connection.remote.id}),L&&n.push({statsSample:T,type:e.Network,reason:s.InboundNetworkMediaLatency,iceCandidate:t.connection.local.id}),P&&n.push({statsSample:T,type:e.Network,reason:s.NetworkMediaSyncFailure,iceCandidate:t.connection.local.id}),n}}class P extends k{performDetection(t){const{connection:{id:e}}=t,s=this.processData(t);return this.setLastProcessedStats(e,t),s}processData(t){const n=t.audio.inbound,o=[],r=this.getLastProcessedStats(t.connection.id)?.audio.inbound;return r?(n.forEach((t=>{const n=r.find((e=>e.ssrc===t.ssrc));if(!n)return;const i=t.track.insertedSamplesForDeceleration+t.track.removedSamplesForAcceleration,a=n.track.insertedSamplesForDeceleration+n.track.removedSamplesForAcceleration;if(i===a)return;const c=t.track.totalSamplesReceived-n.track.totalSamplesReceived,d=i-a,u=Math.round(100*d/c),h={correctedSamplesPct:u};u>5&&o.push({statsSample:h,type:e.Network,reason:s.NetworkMediaSyncFailure,ssrc:t.ssrc})})),o):o}}class T extends k{performDetection(t){const{connection:{id:e}}=t,s=this.processData(t);return this.setLastProcessedStats(e,t),s}processData(t){const n=[],o=[...t.remote?.audio.inbound||[],...t.remote?.video.inbound||[]];if(!o.length)return n;const r=this.getLastProcessedStats(t.connection.id);if(!r)return n;const i=[...r.remote?.audio.inbound||[],...r.remote?.video.inbound||[]],{packetsSent:a}=t.connection,c=r.connection.packetsSent,d=o.reduce(((t,e)=>{const s=i.find((t=>t.ssrc===e.ssrc));return{sumJitter:t.sumJitter+e.jitter,packetsLost:t.packetsLost+e.packetsLost,lastPacketsLost:t.lastPacketsLost+(s?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),u=1e3*t.connection.currentRoundTripTime||0,{sumJitter:h}=d,l=h/o.length,p=a-c,f=d.packetsLost-d.lastPacketsLost,m=p&&f?Math.round(100*f/(p+f)):0,g=m>5,S=l>=200,v=!g&&S||S||g,k={rtt:u,avgJitter:l,packetLossPct:m};return g&&S&&n.push({statsSample:k,type:e.Network,reason:s.OutboundNetworkMediaLatency,iceCandidate:t.connection.local.id}),v&&n.push({statsSample:k,type:e.Network,reason:s.OutboundNetworkQuality,iceCandidate:t.connection.local.id}),n}}class D extends k{performDetection(t){const{connection:{id:e}}=t,s=this.processData(t);return this.setLastProcessedStats(e,t),s}processData(t){const n=[];if("succeeded"!==t.connection.state)return n;const o=this.getLastProcessedStats(t.connection.id);if(!o)return n;const r=t.audio.outbound.filter((t=>!!t.mediaSourceId)),i=o.audio.outbound.filter((t=>!!t.mediaSourceId));if(!r.length||!i.length)return n;return r.reduce(((t,e)=>t+e.packetsSent),0)===i.reduce(((t,e)=>t+e.packetsSent),0)&&n.push({type:e.Stream,reason:s.OutboundAudioNoData}),n}}class C extends k{performDetection(t){const{connection:{id:e}}=t,s=this.processData(t);return this.setLastProcessedStats(e,t),s}processData(t){const n=t.video.outbound.filter((t=>"none"!==t.qualityLimitationReason)),o=[],r=this.getLastProcessedStats(t.connection.id)?.video.outbound;return r?(n.forEach((t=>{const n=r.find((e=>e.ssrc===t.ssrc));if(!n)return;const i={qualityLimitationReason:t.qualityLimitationReason};t.framesSent>n.framesSent||("cpu"===t.qualityLimitationReason&&o.push({statsSample:i,type:e.CPU,reason:s.EncoderCPUThrottling,ssrc:t.ssrc}),"bandwidth"===t.qualityLimitationReason&&o.push({statsSample:i,type:e.Network,reason:s.OutboundNetworkThroughput,ssrc:t.ssrc}))})),o):o}}class R extends k{UNKNOWN_DECODER="unknown";#r={};performDetection(t){const{connection:{id:e}}=t,s=this.processData(t);return this.setLastProcessedStats(e,t),s}performPrevStatsCleanup(t){const{connectionId:e,cleanupCallback:s}=t;super.performPrevStatsCleanup({...t,cleanupCallback:()=>{delete this.#r[e],"function"==typeof s&&s()}})}processData(t){const n=[],{id:o}=t.connection,r=this.getLastProcessedStats(o)?.video.inbound;return t.video.inbound.forEach((t=>{const{decoderImplementation:i,ssrc:a}=t,c=r?.find((t=>t.ssrc===a));if(c)if(i===this.UNKNOWN_DECODER){if(!this.hadLastDecoderWithIssue(o,a)){this.setLastDecoderWithIssue(o,a,this.UNKNOWN_DECODER);const r={mimeType:t.mimeType,decoderImplementation:i};n.push({ssrc:a,statsSample:r,type:e.Stream,reason:s.UnknownVideoDecoderIssue,trackIdentifier:t.track.trackIdentifier})}}else this.setLastDecoderWithIssue(o,a,void 0)})),n}setLastDecoderWithIssue(t,e,s){const n=this.#r[t]??{};void 0===s?delete n[e]:n[e]=s,this.#r[t]=n}hadLastDecoderWithIssue(t,e){const s=this.#r[t];return(s&&s[e])===this.UNKNOWN_DECODER}}const I=t=>"closed"===t.iceConnectionState||"closed"===t.connectionState,E=(t,e,s)=>8*((t,e,s)=>{if(!e)return 0;const n=t[s],o=e[s];if(null==n||null==o)return 0;const r=Math.floor(t.timestamp)-Math.floor(e.timestamp);return 0===r?0:(Number(n)-Number(o))/r*1e3})(t,e,s);class N{connections=[];statsParser;constructor(t){this.statsParser=t.statsParser}listConnections(){return[...this.connections]}addPeerConnection(t){this.connections.push({id:t.id??String(Date.now()+Math.random().toString(32)),pc:t.pc})}removePeerConnection(t){const e=this.connections.findIndex((({pc:e})=>e===t.pc));e>=0&&this.removeConnectionsByIndexes([e])}async parse(){const t=[],e=this.connections.map((async(e,s)=>{if(!I(e.pc))return this.statsParser.parse(e);t.unshift(s)}));t.length&&this.removeConnectionsByIndexes(t);return(await Promise.all(e)).filter((t=>void 0!==t))}removeConnectionsByIndexes(t){t.forEach((t=>{this.connections.splice(t,1)}))}}class M{prevStats=new Map;allowedReportTypes=new Set(["candidate-pair","inbound-rtp","outbound-rtp","remote-outbound-rtp","remote-inbound-rtp","track","transport"]);logger;constructor(t){this.logger=t.logger}get previouslyParsedStatsConnectionsIds(){return[...this.prevStats.keys()]}async parse(t){if(!I(t.pc))return this.getConnectionStats(t);this.logger.debug("Skip stats parsing. Connection is closed.",{connection:t})}async getConnectionStats(t){const{pc:e,id:s}=t;try{const n=Date.now(),o=await Promise.all(e.getReceivers().map((t=>t.getStats()))),r=await Promise.all(e.getSenders().map((t=>t.getStats())));return{id:s,stats:this.mapReportsStats([...o,...r],t),timeTaken:Date.now()-n}}catch(t){return void this.logger.error("Failed to get stats for PC",{id:s,pc:e,error:t})}}mapReportsStats(t,e){const s={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{},remote:{video:{inbound:[],outbound:[]},audio:{inbound:[],outbound:[]}}};t.forEach((t=>{t.forEach((e=>{this.allowedReportTypes.has(e.type)&&this.updateMappedStatsWithReportItemData(e,s,t)}))}));const{id:n}=e,o=this.prevStats.get(n);return o&&this.propagateStatsWithRateValues(s,o.stats),this.prevStats.set(n,{stats:s,ts:Date.now()}),S({taskId:n,delayMs:35e3,callback:()=>this.prevStats.delete(n)}),s}updateMappedStatsWithReportItemData(t,e,s){const n=t.type;if("candidate-pair"===n&&"succeeded"===t.state&&t.nominated)return void(e.connection=this.prepareConnectionStats(t,s));const o=this.getMediaType(t);if(o)if("outbound-rtp"!==n)if("inbound-rtp"!==n)"remote-outbound-rtp"!==n?"remote-inbound-rtp"===n&&(this.mapConnectionStatsIfNecessary(e,t,s),e.remote[o].inbound.push({...t})):e.remote[o].outbound.push({...t});else{const n=s.get(t.trackId)||s.get(t.mediaSourceId)||{};this.mapConnectionStatsIfNecessary(e,t,s);const r={...t,track:{...n}};e[o].inbound.push(r)}else{const n=s.get(t.trackId)||s.get(t.mediaSourceId)||{},r={...t,track:{...n}};e[o].outbound.push(r)}}getMediaType(t){const e=t.mediaType||t.kind;if(!["audio","video"].includes(e)){const{id:e}=t;if(!e)return;return String(e).includes("Video")?"video":String(e).includes("Audio")?"audio":void 0}return e}propagateStatsWithRateValues(t,e){t.audio.inbound.forEach((t=>{const s=e.audio.inbound.find((({id:e})=>e===t.id));t.bitrate=E(t,s,"bytesReceived"),t.packetRate=E(t,s,"packetsReceived")})),t.audio.outbound.forEach((t=>{const s=e.audio.outbound.find((({id:e})=>e===t.id));t.bitrate=E(t,s,"bytesSent"),t.packetRate=E(t,s,"packetsSent")})),t.video.inbound.forEach((t=>{const s=e.video.inbound.find((({id:e})=>e===t.id));t.bitrate=E(t,s,"bytesReceived"),t.packetRate=E(t,s,"packetsReceived")})),t.video.outbound.forEach((t=>{const s=e.video.outbound.find((({id:e})=>e===t.id));t.bitrate=E(t,s,"bytesSent"),t.packetRate=E(t,s,"packetsSent")}))}mapConnectionStatsIfNecessary(t,e,s){if(t.connection.id||!e.transportId)return;const n=s.get(e.transportId);if(n&&n.selectedCandidatePairId){const e=s.get(n.selectedCandidatePairId);t.connection=this.prepareConnectionStats(e,s)}}prepareConnectionStats(t,e){if(!t||!e)return{};const s={...t};if(s.remoteCandidateId){const t=e.get(s.remoteCandidateId);s.remote={...t}}if(s.localCandidateId){const t=e.get(s.localCandidateId);s.local={...t}}return s}}class _{eventEmitter;#i=!1;detectors=[];networkScoresCalculator;statsReporter;compositeStatsParser;logger;constructor(e){this.logger=e.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.eventEmitter=e.issueEmitter??new m,e.onIssues&&this.eventEmitter.on(t.Issue,e.onIssues),e.onNetworkScoresUpdated&&this.eventEmitter.on(t.NetworkScoresUpdated,e.onNetworkScoresUpdated),this.detectors=e.detectors??[new C,new b,new y,new L,new T,new P,new w,new R],this.networkScoresCalculator=e.networkScoresCalculator??new v,this.compositeStatsParser=e.compositeStatsParser??new N({statsParser:new M({logger:this.logger})}),this.statsReporter=e.statsReporter??new g({compositeStatsParser:this.compositeStatsParser,getStatsInterval:e.getStatsInterval??5e3}),window.wid=this,this.wrapRTCPeerConnection(),this.statsReporter.on(g.STATS_REPORT_READY_EVENT,(t=>{this.detectIssues({data:t.stats,ignoreSSRCList:e.ignoreSSRCList}),this.calculateNetworkScores(t.stats)})),this.statsReporter.on(g.STATS_REPORTS_PARSED,(e=>{const s={timeTaken:e.timeTaken,ts:Date.now()};this.eventEmitter.emit(t.StatsParsingFinished,s)}))}watchNewPeerConnections(){this.#i?this.logger.warn("WebRTCIssueDetector is already started. Skip processing"):(this.logger.info("Start watching peer connections"),this.#i=!0,this.statsReporter.startReporting())}stopWatchingNewPeerConnections(){this.#i?(this.logger.info("Stop watching peer connections"),this.#i=!1,this.statsReporter.stopReporting()):this.logger.warn("WebRTCIssueDetector is already stopped. Skip processing")}handleNewPeerConnection(t){this.#i?(this.logger.debug("Handling new peer connection",t),this.compositeStatsParser.addPeerConnection({pc:t})):this.logger.debug("Skip handling new peer connection. Detector is not running",t)}emitIssues(e){this.eventEmitter.emit(t.Issue,e)}detectIssues({data:t,ignoreSSRCList:e}){let s=this.detectors.reduce(((e,s)=>[...e,...s.detect(t)]),[]);e?.length&&(s=s.filter((t=>!t.ssrc||!e.includes(t.ssrc)))),s.length>0&&this.emitIssues(s)}calculateNetworkScores(e){const s=this.networkScoresCalculator.calculate(e);this.eventEmitter.emit(t.NetworkScoresUpdated,s)}wrapRTCPeerConnection(){if(!window.RTCPeerConnection)return void this.logger.warn("No RTCPeerConnection found in browser window. Skipping");const t=window.RTCPeerConnection,e=t=>this.handleNewPeerConnection(t);function s(s){const n=new t(s);return e(n),n}s.prototype=t.prototype,window.RTCPeerConnection=s}}export{w as AvailableOutgoingBitrateIssueDetector,N as CompositeRTCStatsParser,t as EventType,b as FramesDroppedIssueDetector,y as FramesEncodedSentIssueDetector,L as InboundNetworkIssueDetector,s as IssueReason,e as IssueType,P as NetworkMediaSyncIssueDetector,v as NetworkScoresCalculator,D as OutboundAudioIssueDetector,T as OutboundNetworkIssueDetector,g as PeriodicWebRTCStatsReporter,C as QualityLimitationsIssueDetector,M as RTCStatsParser,R as UnknownVideoDecoderImplementationDetector,m as WebRTCIssueEmitter,_ as default};
{
"name": "webrtc-issue-detector2",
"version": "1.6.1",
"version": "1.6.2",
"description": "WebRTC diagnostic tool that detects issues with network or user devices",

@@ -5,0 +5,0 @@ "repository": "git@github.com:VLprojects/webrtc-issue-detector.git",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc