import{E as u,L as d,ag as o}from"./index-DWRYsVdq.js";class k extends u{constructor(){super(...arguments),this.logger=d.create("NetworkQuality"),this.pc=null,this.timer=null,this.lastStats=new Map,this._disposed=!1,this._stats=this.createEmptyStats()}get disposed(){return this._disposed}get stats(){return this._stats}createEmptyStats(){return{uplinkBitrate:0,uplinkPacketLoss:0,uplinkRtt:0,uplinkJitter:0,downlinkBitrate:0,downlinkPacketLoss:0,downlinkRtt:0,downlinkJitter:0,uplinkQuality:0,downlinkQuality:0}}attach(e){this.pc=e}detach(){this.stop(),this.pc=null}start(e=2e3){this.stop(),this.timer=o.instance.setInterval(()=>this.collectStats(),e)}stop(){this.timer!==null&&(o.instance.clearInterval(this.timer),this.timer=null)}async collectStats(){if(this.pc)try{const e=await this.pc.getStats(),t=this.createEmptyStats(),h=Date.now();e.forEach(s=>{const i=this.lastStats.get(s.id);if(s.type==="outbound-rtp"&&i){const n=(s.timestamp-i.timestamp)/1e3;if(n>0){const l=s.bytesSent-i.bytesSent;t.uplinkBitrate=Math.round(l*8/n/1e3);const a=s.packetsSent-i.packetsSent,c=(s.packetsLost||0)-(i.packetsLost||0);a>0&&(t.uplinkPacketLoss=Math.round(c/a*100))}}if(s.type==="inbound-rtp"&&i){const n=(s.timestamp-i.timestamp)/1e3;if(n>0){const l=s.bytesReceived-i.bytesReceived;t.downlinkBitrate=Math.round(l*8/n/1e3);const a=s.packetsReceived-i.packetsReceived,c=(s.packetsLost||0)-(i.packetsLost||0);a>0&&(t.downlinkPacketLoss=Math.round(c/a*100)),t.downlinkJitter=Math.round((s.jitter||0)*1e3)}}s.type==="candidate-pair"&&s.state==="succeeded"&&(t.uplinkRtt=Math.round(s.currentRoundTripTime*1e3),t.downlinkRtt=t.uplinkRtt),this.lastStats.set(s.id,{...s})}),t.uplinkQuality=this.calculateQuality(t.uplinkPacketLoss,t.uplinkRtt),t.downlinkQuality=this.calculateQuality(t.downlinkPacketLoss,t.downlinkRtt),this._stats=t,this.emit("qualityChange",t)}catch(e){this.logger.error("Failed to collect stats",e)}}calculateQuality(e,t){return e===0&&t<50?1:e<2&&t<100?2:e<5&&t<200?3:e<10&&t<400?4:e<20&&t<800?5:6}getQualityDescription(e){return["未知","极好","好","一般","差","极差","断开"][e]||"未知"}dispose(){this._disposed||(this._disposed=!0,this.stop(),this.pc=null,this.lastStats.clear(),this.removeAllListeners(),this.logger.debug("Disposed"))}}export{k as N};
