!function(){var e,t,i,s,r,o={435463:function(e){var t=e.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{push:"msid",reg:/^msid:([\w-]+)(?: ([\w-]+))?/,names:["id","appdata"],format:"msid:%s %s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=(null!=e.raddr?" raddr %s rport %d":"%v%v")+(null!=e.tcptype?" tcptype %s":"%v"),null!=e.generation&&(t+=" generation %d"),t+=(null!=e["network-id"]?" network-id %d":"%v")+(null!=e["network-cost"]?" network-cost %d":"%v")}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=(null!=e.id?"id=%s %s":"%v%s")+(null!=e.mediaClockValue?"=%s":"")+(null!=e.rateNumerator?" rate=%s":"")+(null!=e.rateDenominator?"/%s":"")}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(t).forEach(function(e){t[e].forEach(function(e){!e.reg&&(e.reg=/(.*)/),!e.format&&(e.format="%s")})})},405825:function(e,t,i){var s=i(938328),r=i(847198),o=i(435463);t.grammar=o,t.write=r,t.parse=s.parse,t.parseParams=s.parseParams,t.parseFmtpConfig=s.parseFmtpConfig,t.parsePayloads=s.parsePayloads,t.parseRemoteCandidates=s.parseRemoteCandidates,t.parseImageAttributes=s.parseImageAttributes,t.parseSimulcastStreamList=s.parseSimulcastStreamList},938328:function(e,t,i){var s=function(e){return String(Number(e))===e?Number(e):e},r=function(e,t,i,r){if(r&&!i)t[r]=s(e[1]);else for(var o=0;o1&&(e[i[0]]=void 0),e};t.parseParams=function(e){return e.split(/;\s?/).reduce(d,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(e){return e.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(e){for(var t=[],i=e.split(" ").map(s),r=0;r=s)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}})},a=function(e,t,i){var s=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var r=0;r=o.debug&&o.error}catch(e){}class d{debug(){for(var e=arguments.length,t=Array(e),i=0;id.maxSize){let e=d.logTextArray.shift();e&&(d.size-=e.length)}}static loggerHandle(e){for(var t=arguments.length,i=Array(t>1?t-1:0),s=1;s=d.level&&(d.logCache(a),d.enable&&console[e](a))}static getLoggerCache(){return d.logTextArray.join("\n")}static reset(){d.logTextArray=[],d.size=0}constructor(e){return(0,s._)(this,"name",void 0),(0,s._)(this,"_id",void 0),this.name=e,new Proxy(this,{get:(e,t)=>{if("function"!=typeof this[t])return this[t];if("table"===t){var i,s=this;return function(){for(var e=arguments.length,i=Array(e),r=0;re+t.byteLength,0)),r=0;return t.forEach(e=>{s.set(e,r),r+=e.byteLength}),s}function a(e){return!s&&(s=new((0,r.Q)(e))),s}},952655:function(e,t,i){"use strict";i.d(t,{Xe:function(){return r},ct:function(){return s}});let s={PLAYER_LOG:"playerlog"},r={ADD_INFO_TO_LOG:"addExtInfoToLog",PROGRESS:"progress",SEGMENT_DONE:"webcodec_segment_done",PRELOAD_CACHE:"webcodec_preload_cache"}},403278:function(e,t,i){"use strict";function s(e){let t;let i=[],s=[];return e.sps.forEach(e=>{t=e.byteLength,i.push(t>>>8&255),i.push(255&t),i.push(...e)}),e.pps.forEach(e=>{t=e.byteLength,s.push(t>>>8&255),s.push(255&t),s.push(...e)}),new Uint8Array([1,i[3],i[4],i[5],255,224|e.sps.length].concat(...i).concat([e.pps.length]).concat(...s))}function r(e){let t;let i=e.hvcC;if(!i||!e.vps)return;let{vps:s,sps:r,pps:o}=e,a=i.generalProfileCompatibilityFlags,n=i.generalConstraintIndicatorFlags,d=(s.length&&1)+(r.length&&1)+(o.length&&1);t=[1,i.generalProfileSpace<<6|i.generalTierFlag<<5|i.generalProfileIdc,a>>>24,a>>>16,a>>>8,a,n[0],n[1],n[2],n[3],n[4],n[5],i.generalLevelIdc,240,0,252,252|i.chromaFormatIdc,248|i.bitDepthLumaMinus8,248|i.bitDepthChromaMinus8,0,0,i.numTemporalLayers<<3|i.temporalIdNested<<2|3,d];let l=e=>{t.push(e.length>>8,e.length),t.push(...e)};return s.length&&(t.push(160,0,s.length),s.forEach(l)),r.length&&(t.push(161,0,r.length),r.forEach(l)),o.length&&(t.push(162,0,o.length),o.forEach(l)),new Uint8Array(t)}function o(e){let t=new Uint8Array((e=e.filter(Boolean)).reduce((e,t)=>e+=t.length,0)+4*e.length);return e.reduce((e,i)=>{let s=new DataView(new ArrayBuffer(4));return s.setUint32(0,i.length,!1),t.set(new Uint8Array(s.buffer),e),e+=4,t.set(i,e),e+=i.length},0),t}function a(e,t){let i=e.numberOfChannels,s=e.numberOfFrames,r=new Float32Array(s),o=new Float32Array(s*i);switch(e.format){case"s16":if(1===e.numberOfChannels&&"number"==typeof t&&t!==e.sampleRate)throw Error(`Unsupported audio format ${e.format} with single channel`);e.copyTo(o,{planeIndex:0}),o=function(e,t,i){let s=new Float32Array(t*i);for(let r=0;r{t[i]=e}),t}},34768:function(e,t,i){"use strict";i.d(t,{Ll:function(){return o},QL:function(){return a},Zo:function(){return r},_8:function(){return s}});let s=["f-workerinit","f-startload","f-firstbyte","f-loadmeta","f-metaparse","f-addmeta","f-videodecodeinits","f-audiodecodeinits","f-videodecodeinited","f-audiodecodeinited","f-appendvideodata","f-startdecodevideo","f-outputvideo","f-writevideo","f-writeready"];var r={ISREADY:"up_isready",STARTPLAY:"up_startplay",TRANSMIT_LOG:"up_getlog",PROTOCOL_CONFIG:"up_protocolconfig",MEDIACODEC_CONFIG:"up_veconfig",LOAD_STREAM:"up_loadstream",SEAMLESS_LOAD_STREAM:"up_seamlessloadstream",CANCEL_SWITCH:"up_cancelswitch",PLAY:"up_play",PAUSE:"up_pause",MUTED_SET:"up_mutedset",LOOP_CHANGE:"up_loopchange",CURRENT_TIME:"up_currenttime",PLAYBACKRATE:"up_playbackrate",WRITABLE:"up_writable",FREQUENT_STATISTICS:"up_frequentstatistics",ERROR:"up_error",PROCESS_ERROR:"up_process_error",VISIBILITYSTATE:"up_process_visibilityState",RESET:"up_reset",SR_RUNNING:"up_srrunning",RESUME_PROCESSOR:"up_resume_processor",MESSAGE_EVENT_RECEIVESUCCESS:"down_e_receivesuccess",MESSAGE_EVENT_ISREADY:"down_e_ready",MESSAGE_EVENT_LOADEDMETADATA:"down_e_loadedmetadata",MESSAGE_EVENT_DURATIONCHANGE:"down_e_durationchange",MESSAGE_EVENT_WAITING:"down_e_waiting",MESSAGE_EVENT_SEEKING:"down_e_seeking",MESSAGE_EVENT_SEEKED:"down_e_seeked",MESSAGE_EVENT_PROGRESS:"down_e_progress",MESSAGE_EVENT_TIMEUPDATE:"down_e_timeupdate",MESSAGE_EVENT_ENDED:"down_ended",MESSAGE_EVENT_RATECHANGE:"down_e_ratechange",MESSAGE_TRANS_LOG:"down_translog",MESSAGE_INIT_RENDER:"down_initrender",MESSAGE_FIRSTFRAME:"down_firstframe",MESSAGE_STATISTICS:"down_statistics",MESSAGE_EVENT_VEERROR:"down_e_veerror",MESSAGE_EVENT_DROPFRAMES:"down_e_dropframes",MESSAGE_EVENT_CANPLAY:"down_e_canplay",MESSAGE_EVENT_PLAYING:"down_e_playing",MESSAGE_EVENT_SEGMENT_DONE:"down_e_segment_done",MESSAGE_EVENT_PRELOAD_CACHE:"down_e_preload_cache",SRSTATE_CHANGE:"srstate_change",URLCHANGE:"urlchange",DESTROY:"destroy",VOLUMEBALANCE_UPDATE:"volumebalance_update",DOWN_WRITABLE:"down_writable",VOLUMEBALANCE_DATA:"volumebalance_data",workerinit:"f-workerinit",startload:"f-startload",firstbyte:"f-firstbyte",loadmeta:"f-loadmeta",metaparse:"f-metaparse",addmeta:"f-addmeta",videodecodeinits:"f-videodecodeinits",audiodecodeinits:"f-audiodecodeinits",videodecodeinited:"f-videodecodeinited",audiodecodeinited:"f-audiodecodeinited",appendvideodata:"f-appendvideodata",startdecodevideo:"f-startdecodevideo",outputvideo:"f-outputvideo",writevideo:"f-writevideo",writeready:"f-writeready",AV_UNSYNC:"av-unsync",SDP_LOAD:"sdp-load",SDP_DISCONNECT:"sdp-disconnect",SDP_TRANSFORM:"sdp-transform",AV_CODEC_INFO:"av-codec-info",RTM_STATS:"rtm-stats",RTM_RESPONSE_HEADERS:"rtm-response-headers",RTM_TTFB:"rtm-ttfb",RTM_SAMPLE_RATE_CHANGE:"rtm-sample-rate-change",RTM_WEBTS_PRELOAD:"up_rtm_webts_preload",RTM_WEBTS_CANCEL_PRELOADED:"up_rtm_webts_cancel_preloaded",RTM_WEBTS_CLEAR_PRELOADED:"up_rtm_webts_clear_preloaded"};let o=1e6;var a={DONE:"done",NOBUFFER:"nobuffer"}},526195:function(e,t,i){"use strict";i.d(t,{Fc:function(){return a},WE:function(){return o},wb:function(){return r}});var s=i(480333);i(76375);let r={NETWORK:"network",NETWORK_TIMEOUT:"network_timeout",NETWORK_FORBIDDEN:"network_forbidden",NETWORK_NOTFOUND:"network_notfound",DEMUX:"demux",OTHER:"other",RUNTIME:"runtime",SUB_TYPES:{FLV:"FLV",MP4:"MP4"}},o={[r.NETWORK]:2100,[r.NETWORK_TIMEOUT]:2101,[r.NETWORK_FORBIDDEN]:2103,[r.NETWORK_NOTFOUND]:2104,[r.DEMUX]:{FLV:3100},[r.OTHER]:8e3,[r.RUNTIME]:{NO_CANPLAY_ERROR:9001,BUFFERBREAK_ERROR:9002,WAITING_TIMEOUT_ERROR:9003}};class a extends Error{static network(e){var t;return new a((null==e?void 0:e.isTimeout)?r.NETWORK_TIMEOUT:r.NETWORK,null,e instanceof Error?e:null,{url:null==e?void 0:e.url,response:null==e?void 0:e.response,httpCode:null==e?void 0:null===(t=e.response)||void 0===t?void 0:t.status})}constructor(e,t,i,a,n){super(n||(null==i?void 0:i.message)),(0,s._)(this,"errorType",void 0),(0,s._)(this,"originError",void 0),(0,s._)(this,"ext",void 0),(0,s._)(this,"errorCode",void 0),this.errorType=e===r.NETWORK_TIMEOUT?r.NETWORK:e,this.originError=i,this.ext=a,this.errorCode=o[e][t]||o[e],!this.errorCode&&(this.errorType=r.OTHER,this.errorCode=o[this.errorType])}}},984065:function(e,t,i){"use strict";i.d(t,{Fc:function(){return s.Fc},WE:function(){return s.WE},wb:function(){return s.wb}});var s=i(526195);i(824684),i(685334),i(441779)},824684:function(e,t,i){"use strict";i(480333),i(374954),i(679308),i(490629),i(759943),i(88856),i(559865),i(216308),i(990958),i(441779),i(806130),i(773240),i(499401)},611363:function(e,t,i){"use strict";var s=i("480333"),r=i("629686"),o=i("487359"),a=i("559865"),n=i("34768"),d=i("993477"),l=i("65787"),h=i("276826"),u=i("469561"),c=i("783696"),_=i("455195"),m=i("811603");i("679308"),i("374954"),i("706056"),i("490629");var p=i("227216");i("190932"),i("808483"),i("126159"),i("100832"),i("825666"),i("943281"),i("82726"),i("362051");var f=i("402748");i("274352"),i("228983"),i("759943"),i("591964"),i("968336"),i("683656"),i("76375"),i("527553");class g{constructor(e,t=0){(0,s._)(this,"audioMuxVersion",0),(0,s._)(this,"allstreamsSameTimeFraming",1),(0,s._)(this,"numSubFrames",0),(0,s._)(this,"numPrograms",0),(0,s._)(this,"numLayer",0),(0,s._)(this,"audioSpecificConfig",void 0),(0,s._)(this,"frameLengthType",0),(0,s._)(this,"latmBufferFullness",255),(0,s._)(this,"otherDataPresent",0),(0,s._)(this,"crcCheckPresent",0),(0,s._)(this,"bitstreamSize",void 0);let i=0,r=A(1,e,t+0);if(i+=1,r!==this.audioMuxVersion)throw Error("");let o=A(1,e,t+i);if(i+=1,o!==this.allstreamsSameTimeFraming)throw Error();let a=A(6,e,t+i);if(i+=6,a!==this.numSubFrames)throw Error();let n=A(4,e,t+i);if(i+=4,n!==this.numPrograms)throw Error();let d=A(3,e,t+i);if(i+=3,d!==this.numLayer)throw Error();this.audioSpecificConfig=new y(e,t+i);let l=A(3,e,t+(i+=this.audioSpecificConfig.bitstreamSize));if(i+=3,l!==this.frameLengthType)throw Error();let h=A(8,e,t+i);if(i+=8,h!==this.latmBufferFullness)throw Error();let u=A(1,e,t+i);if(i+=1,u!==this.otherDataPresent)throw Error();let c=A(1,e,t+i);if(i+=1,c!==this.crcCheckPresent)throw Error();this.bitstreamSize=i}}let v=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350,"reserved","reserved","escape"];class y{get codec(){return 2!==this.audioObjectType?"unknown":this.sbrPresentFlag||this.psPresentFlag?this.sbrPresentFlag&&!this.psPresentFlag?"mp4a.40.5":this.sbrPresentFlag&&this.psPresentFlag?"mp4a.40.29":"unknown":"mp4a.40.2"}get sampleRate(){let e=T(this.extensionSamplingFrequencyIndex,this.extensionSamplingFrequency);return void 0!==e||void 0!==(e=T(this.samplingFrequencyIndex,this.samplingFrequency))?e:"unknown"}get array(){var e,t,i,s,r,o,a;let n=new C,d=this.psPresentFlag&&this.sbrPresentFlag?29:this.sbrPresentFlag?5:2;return n.writeBits(d,5),n.writeBits(this.samplingFrequencyIndex,4),15===this.samplingFrequencyIndex&&n.writeBits(null!==(e=this.samplingFrequency)&&void 0!==e?e:0,24),n.writeBits(this.channelConfiguration,4),(5===d||29===d)&&(n.writeBits(null!==(t=this.extensionSamplingFrequencyIndex)&&void 0!==t?t:0,4),15===this.extensionSamplingFrequencyIndex&&n.writeBits(null!==(i=this.extensionSamplingFrequency)&&void 0!==i?i:0,24),n.writeBits(this.audioObjectType,5)),29===d&&n.writeBitsArray(null!==(o=null===(s=this.gaSpecificConfig)||void 0===s?void 0:s.array)&&void 0!==o?o:new Uint8Array,null!==(a=null===(r=this.gaSpecificConfig)||void 0===r?void 0:r.bitstreamSize)&&void 0!==a?a:0),n.buffer()}constructor(e,t){(0,s._)(this,"audioObjectType",void 0),(0,s._)(this,"samplingFrequencyIndex",void 0),(0,s._)(this,"samplingFrequency",void 0),(0,s._)(this,"channelConfiguration",void 0),(0,s._)(this,"extensionSamplingFrequencyIndex",void 0),(0,s._)(this,"extensionSamplingFrequency",void 0),(0,s._)(this,"gaSpecificConfig",void 0),(0,s._)(this,"sbrPresentFlag",!1),(0,s._)(this,"psPresentFlag",!1),(0,s._)(this,"bitstreamSize",void 0);let i=0;this.audioObjectType=A(5,e,t+i),i+=5,this.samplingFrequencyIndex=A(4,e,t+i),i+=4,15===this.samplingFrequencyIndex&&(this.samplingFrequency=A(24,e,t+i),i+=24),this.channelConfiguration=A(4,e,t+i),i+=4,(5===this.audioObjectType||29===this.audioObjectType)&&(this.sbrPresentFlag=!0,29===this.audioObjectType&&(this.psPresentFlag=!0),this.extensionSamplingFrequencyIndex=A(4,e,t+i),i+=4,15===this.extensionSamplingFrequencyIndex&&(this.extensionSamplingFrequency=A(24,e,t+i),i+=24),this.audioObjectType=A(5,e,t+i),i+=5),2===this.audioObjectType&&(this.gaSpecificConfig=new S(e,t+i),i+=this.gaSpecificConfig.bitstreamSize),this.bitstreamSize=i}}class S{get array(){let e=new C;return e.writeBits(this.frameLengthFlag,1),e.writeBits(this.dependsOnCoreCoder,1),e.writeBits(this.extensionFlag,1),e.buffer()}constructor(e,t){(0,s._)(this,"frameLengthFlag",0),(0,s._)(this,"dependsOnCoreCoder",0),(0,s._)(this,"extensionFlag",0),(0,s._)(this,"bitstreamSize",void 0);let i=0,r=A(1,e,t+0);if(i+=1,r!==this.frameLengthFlag)throw Error();let o=A(1,e,t+i);if(i+=1,o!==this.dependsOnCoreCoder)throw Error();let a=A(1,e,t+i);if(i+=1,a!==this.extensionFlag)throw Error();this.bitstreamSize=i}}function T(e,t){if(void 0===e)return;let i=v[e];if("reserved"!==i)return"escape"===i?t:i}let E=[0,1,3,7,15,31,63,127,255];function A(e,t,i){let s=0;for(;e>0;){let r=i>>3,o=8-(i-(r<<3)),a=e>o?0:o-e;s<<=o-a,s+=t[r]>>a&E[o-a],e-=o-a,i+=o-a}return s}class C{ensureBufferSize(e){if(e>=this._buffer.length){let t=new Uint8Array(e+1);t.set(this._buffer),this._buffer=t}}writeBits(e,t){for(;t>0;){let i=this._position>>3;this.ensureBufferSize(i);let s=8-(this._position-(i<<3)),r=Math.min(s,t),o=e>>t-r;this._buffer[i]|=o<0;){let s=this._position>>3;this.ensureBufferSize(s);let r=8-(this._position-(s<<3)),o=Math.min(r,t),a=A(o,e,i);this._buffer[s]|=a<2&&void 0!==arguments[2]&&arguments[2],s=R.parse(e);return this.hasNativeAAC=e.includes(b.AAC),this._cropOfferSdp(s,this.hasNativeAAC),!this.hasNativeAAC&&(this._needConvertToAAC=!0,this._opus2aac(s,t)),this.hasNativeAAC&&this._addAACExtension(s),this._addBframe(s),i&&this._addFastSyncExtensions(s),this._filterVideoProfile(s),this._genLocalPayloadMap(s),this._logSdp("offer(http-send)",s),R.write(s)}_addFastSyncExtensions(e){let t={value:18,uri:"http://www.webrtc.org/experiments/rtp-hdrext/decoding-timestamp"},i={value:19,uri:"uri:webrtc:rtc:rtp-hdrext:video:CompositionTime"};e.media=e.media.map(e=>"audio"!==e.type&&"video"!==e.type?e:(!e.ext&&(e.ext=[]),!e.ext.some(e=>e.uri===t.uri)&&e.ext.push(t),"video"===e.type&&!e.ext.some(e=>e.uri===i.uri)&&e.ext.push(i),e))}parseAnswerSdp(e){let t=R.parse(e);return this._logSdp("answer(http-recv)",t),this._genRemotePayloadMap(t),this._checkFastSyncNegotiated(t),this._upperFingerprint(t),this._removeBframe(t),this._needConvertToAAC&&this._aac2opus(t),this._logSdp("answer(set)",t),R.write(t)}_checkFastSyncNegotiated(e){let t=!1,i=!1;e.media.forEach(e=>{if(!e.ext)return;let s=e.ext.some(e=>"http://www.webrtc.org/experiments/rtp-hdrext/decoding-timestamp"===e.uri);"audio"===e.type&&s&&(t=!0),"video"===e.type&&s&&(i=!0)}),this._fastSyncNegotiated=t&&i}get fastSyncNegotiated(){return this._fastSyncNegotiated}get hasAudio(){return Object.values(this._audioPayloadMap).some(e=>e.enabled)}get hasVideo(){return Object.values(this._videoPayloadMap).some(e=>e.enabled)}get videoPayloadMap(){return Object.fromEntries(Object.entries(this._videoPayloadMap).filter(e=>{let[t,i]=e;return i.enabled}))}get audioPayloadMap(){return Object.fromEntries(Object.entries(this._audioPayloadMap).filter(e=>{let[t,i]=e;return i.enabled}))}_genLocalPayloadMap(e){e.media.forEach(e=>{var t;let i="audio"===e.type?this._audioPayloadMap:this._videoPayloadMap;null===(t=e.rtp)||void 0===t||t.forEach(t=>{i[t.payload]={enabled:!1,payloadType:t.payload,mimetype:"audio"===e.type?"mp4a.40.2":"",codec:t.codec,sampleRate:t.rate||void 0}})})}_genRemotePayloadMap(e){e.media.forEach(e=>{var t,i;let s="audio"===e.type?this._audioPayloadMap:this._videoPayloadMap;null===(t=e.rtp)||void 0===t||t.forEach(e=>{let t=s[e.payload];t&&t.codec===e.codec&&(t.enabled=!0)}),null===(i=e.fmtp)||void 0===i||i.forEach(t=>{var i;let o=s[t.payload],a=null===(i=t.config)||void 0===i?void 0:i.split(";").reduce((e,t)=>{let[i,s]=t.split("=");return(0,f._)((0,r._)({},e),{[i]:s})},{});if(o){if("audio"===e.type){if(null==a?void 0:a.config)try{let{audioSpecificConfig:e}=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=new Uint8Array(Math.ceil(e.length/2));for(let t=0;t=44100&&(e.sbrPresentFlag||e.psPresentFlag)&&(o.sampleRate=o.sampleRate/2))}catch(e){w.warn("parse aac config error",e)}if(!o.mimetype&&o.codec===b.AAC){let e=+a.object;1==+a["SBR-enabled"]&&(e=5),1==+a["SBR-enabled"]&&1==+a["PS-enabled"]&&(e=29),o.objectType=+e||2,o.mimetype=`mp4a.40.${o.objectType}`}}else o.mimetype=this._genVideoMimeType(o.codec,a["profile-level-id"])}})})}_logSdp(e,t){let i=[];t.media.forEach(e=>{var t,s,r;let o={};if(null===(t=e.rtp)||void 0===t||t.forEach(t=>{o[t.payload]=[e.type,t.payload,t.codec,t.rate||""]}),null===(s=e.fmtp)||void 0===s||s.forEach(e=>{var t;null===(t=o[e.payload])||void 0===t||t.push(e.config||"")}),Object.values(o).forEach((e,t)=>i.push(`${t}. ${e.join(" ")}`)),null===(r=e.ext)||void 0===r?void 0:r.length){let t=e.ext.map(e=>`[${e.value}]${e.uri.split(/[:/]/).filter(Boolean).pop()}`).join(" ");i.push(` ext: ${t}`)}}),w.log(e,"\n"+i.join("\n"))}_cropOfferSdp(e,t){e.media=e.media.map(e=>e="audio"===e.type?this._keepCodec(e,t?["MP4A-LATM"]:["opus"]):this._keepCodec(e,["H264","H265"]))}_opus2aac(e,t){e.media=e.media.map(e=>{if("audio"===e.type){var i;e.rtp=null===(i=e.rtp)||void 0===i?void 0:i.map(e=>("opus"===e.codec&&(e.codec=b.AAC,e.rate=t),e))}return e})}_aac2opus(e){e.media=e.media.map(e=>{if("audio"===e.type){var t;e.rtp=null===(t=e.rtp)||void 0===t?void 0:t.map(e=>(e.codec===b.AAC&&(e.codec="opus",e.rate=48e3),e))}return e})}_addAACExtension(e){let t="uri:webrtc:rtc:rtp-hdrext:audio:aac-config";e.media=e.media.map(e=>("audio"===e.type&&(!e.ext&&(e.ext=[]),!e.ext.some(e=>e.uri===t)&&e.ext.push({value:27,uri:t})),e))}_filterVideoProfile(e){e.media=e.media.map(e=>{if("video"===e.type){var t,i,s,o,a;let n=[];((null===(t=e.rtp)||void 0===t?void 0:t.filter(e=>e.codec===b.H264).map(e=>e.payload))||[]).forEach(t=>{var i,s;let o=null===(i=e.fmtp)||void 0===i?void 0:i.find(e=>e.payload===t);if(null==o?void 0:o.config){let e=o.config.split(";").reduce((e,t)=>{let[i,s]=t.split("=");return(0,f._)((0,r._)({},e),{[i]:s})},{}),i=null===(s=e["profile-level-id"])||void 0===s?void 0:s.toLowerCase(),a=e["packetization-mode"];(!i||!i.startsWith("42")||"1"!==a)&&n.push(t)}else n.push(t)}),null===(i=e.fmtp)||void 0===i||i.forEach(e=>{var t;if(null===(t=e.config)||void 0===t?void 0:t.startsWith("apt=")){let t=Number(e.config.slice(4));n.includes(t)&&n.push(e.payload)}}),e.rtp=null===(s=e.rtp)||void 0===s?void 0:s.filter(e=>!n.includes(e.payload)),e.fmtp=null===(o=e.fmtp)||void 0===o?void 0:o.filter(e=>!n.includes(e.payload)),e.rtcpFb=null===(a=e.rtcpFb)||void 0===a?void 0:a.filter(e=>!n.includes(Number(e.payload))),e.payloads&&(e.payloads=e.payloads.split(" ").filter(e=>!n.includes(Number(e))).join(" "))}return e})}_addBframe(e){e.media=e.media.map(e=>{if("video"===e.type){var t;e.fmtp=null===(t=e.fmtp)||void 0===t?void 0:t.map(e=>{var t;return e.config=[M.B_FRAME_ENABLED,...(null===(t=e.config)||void 0===t?void 0:t.split(";"))||[]].join(";"),e})}return e})}_removeBframe(e){e.media=e.media.map(e=>{if("video"===e.type){var t;e.fmtp=null===(t=e.fmtp)||void 0===t?void 0:t.map(e=>{var t;return e.config=null===(t=e.config)||void 0===t?void 0:t.replace(`${M.B_FRAME_ENABLED};`,""),e})}return e})}_genVideoMimeType(e,t){switch(e){case b.H264:return`avc1.${(null==t?void 0:t.toUpperCase())||"42002a"}`;case b.H265:return"hev1.1.6.L93.B0";default:return""}}_keepCodec(e,t){var i,s,o,a;let n=null===(i=e.rtp)||void 0===i?void 0:i.filter(e=>t.includes(e.codec)),d=[];null===(s=e.fmtp)||void 0===s||s.forEach(e=>{n.some(t=>t.payload===e.payload)&&e.config.startsWith("apt=")&&d.push(+e.config.slice(4))});let l=null===(o=e.fmtp)||void 0===o?void 0:o.filter(e=>!!(n.some(t=>t.payload===e.payload)||d.includes(e.payload))||!1),h=null===(a=e.rtcpFb)||void 0===a?void 0:a.filter(e=>!!(n.some(t=>t.payload===e.payload)||d.includes(+e.payload))||!1);return(0,f._)((0,r._)({},e),{payloads:[...n.map(e=>e.payload),...d].join(" "),rtp:n,fmtp:l,rtcpFb:h})}_upperFingerprint(e){e.media=e.media.map(e=>{if(e.fingerprint){var t,i;e.fingerprint.hash=null===(i=e.fingerprint)||void 0===i?void 0:null===(t=i.hash)||void 0===t?void 0:t.toUpperCase()}return e})}constructor(){(0,s._)(this,"_needConvertToAAC",!1),(0,s._)(this,"hasNativeAAC",!1),(0,s._)(this,"_videoPayloadMap",{}),(0,s._)(this,"_audioPayloadMap",{}),(0,s._)(this,"_fastSyncNegotiated",!1)}}(0,s._)(M,"B_FRAME_ENABLED","BFrame-enabled=1");let D=e=>{if(e.byteLength<8)return;let t=new DataView(e),i=(248&t.getUint8(0))>>3,s=7&t.getUint8(0),r=!!(128&t.getUint8(1)),o=!!(64&t.getUint8(1)),a=!!(32&t.getUint8(1)),n=!!(16&t.getUint8(1));return{object:i,channel:s,cpresent:r,sbrEnabled:o,psEnabled:a,stereo:n,sampleFragament:t.getInt32(4)}};i("992871"),i("104882"),i("656562");let k=e=>e.byteLength<4?0:new DataView(e).getUint32(0,!1),O=e=>{let t=new DataView(e);if(e.byteLength>=4)return t.getInt32(0,!1);if(3===e.byteLength){let e=t.getUint8(0)<<16|t.getUint8(1)<<8|t.getUint8(2);return 8388608&e?e-16777216:e}return 0};class F{setFastSync(e){this._fastSync=e}reset(){this._videoAnchorMs=null,this._videoRtpAnchor=null,this._audioRtpAnchor=null,this._audioPtsOffset=null}get fastSync(){return this._fastSync}processVideo(e,t){var i,s;let r=this._fastSync?null===(i=t.headerExtension)||void 0===i?void 0:i.find(e=>18===e.id):void 0,o=this._fastSync?null===(s=t.headerExtension)||void 0===s?void 0:s.find(e=>19===e.id):void 0;if(r){let e=k(r.payload),t=o?O(o.payload):0,i=null===this._videoAnchorMs;i&&(this._videoAnchorMs=e);let s=e-this._videoAnchorMs;return{pts:s+t,dts:s,isFirst:i,usedExt18:!0}}let a=e/90,n=null===this._videoRtpAnchor;n&&(this._videoRtpAnchor=a);let d=a-this._videoRtpAnchor;return{pts:d,dts:d,isFirst:n,usedExt18:!1}}processAudio(e,t,i){var s;let r=this._fastSync?null===(s=t.headerExtension)||void 0===s?void 0:s.find(e=>18===e.id):void 0;if(r)return null===this._videoAnchorMs?"pending":this._calcAudioPts(e,r.payload,i);let o=null===this._audioRtpAnchor;return o&&(this._audioRtpAnchor=e),{pts:Number(((e-this._audioRtpAnchor)*1e3/i).toFixed(3)),isFirst:o,usedExt18:!1}}calcAudioPts(e,t,i){var s;let r=null===(s=t.headerExtension)||void 0===s?void 0:s.find(e=>18===e.id);return r?this._calcAudioPts(e,r.payload,i):null}_calcAudioPts(e,t,i){let s=k(t);if(s{if(this._startTs&&this._startAudioTimestamp){let i=this._currentAudioTimestamp-t,s=Date.now()-e;e=Date.now(),t=this._currentAudioTimestamp,44100===this._currentSampleRate&&(i/s>46?this._exceptionList.push(!0):this._exceptionList.push(!1));let r=(this._currentAudioTimestamp-this._startAudioTimestamp)/(Date.now()-this._startTs);this._exceptionList.filter(e=>e).length>=10&&r>=48&&this._resetToNewSampleRate(48e3),this._exceptionList=this._exceptionList.slice(-12)}else this._startTs=Date.now(),this._startAudioTimestamp=this._currentAudioTimestamp,e=this._startTs,t=this._currentAudioTimestamp},1e3)}stop(){delete this._startTs,delete this._startAudioTimestamp,this._currentAudioTimestamp=0,clearInterval(this._timer),delete this._timer,this._exceptionList=[]}_resetToNewSampleRate(e){this._currentSampleRate=e,this._callback(e,this._payloadType),this.stop()}constructor(e){(0,s._)(this,"_callback",void 0),(0,s._)(this,"_startTs",void 0),(0,s._)(this,"_startAudioTimestamp",void 0),(0,s._)(this,"_currentAudioTimestamp",0),(0,s._)(this,"_payloadType",void 0),(0,s._)(this,"_timer",void 0),(0,s._)(this,"_currentSampleRate",44100),(0,s._)(this,"_exceptionList",[]),this._callback=e}}var V=i("549816");i("414931");let B={H264:"H264",H265:"H265",UNKNOWN:"UNKNOWN"};class W{setDetectedCodec(e){this._detectedCodec=e}detectAbnormalAUD(e,t){if(0===e.byteLength)return{hasAbnormalAUD:!1,codec:B.UNKNOWN,details:"Buffer为空",audPositions:[]};let i=t||this._detectedCodec;if(this._detectedCodec=i,i===B.UNKNOWN||!i)return{hasAbnormalAUD:!1,codec:B.UNKNOWN,details:"无法识别编码格式",audPositions:[]};let s=this.parseNALUs(e,i),r=this.getAUDType(i),o=[];if(s.forEach((e,t)=>{e.type===r&&o.push(t)}),0===o.length)return{hasAbnormalAUD:!1,codec:i,details:"未检测到AUD",audPositions:[]};let a=o[0],n=[];n=i===B.H265?s.map((e,t)=>32===e.type||33===e.type||34===e.type?t:-1).filter(e=>-1!==e):s.map((e,t)=>7===e.type||8===e.type?t:-1).filter(e=>-1!==e);let d=[];d=i===B.H265?s.map((e,t)=>39===e.type||40===e.type?t:-1).filter(e=>-1!==e):s.map((e,t)=>6===e.type?t:-1).filter(e=>-1!==e);let l=!1,h="";if(n.length>0){let e=Math.min(...n);a>e&&(l=!0,h=`AUD位于参数集之后 (AUD位置:${a}, 参数集最早位置:${e})`)}if(!l&&d.length>0){let e=Math.min(...d);a>e&&(l=!0,h=`AUD位于SEI之后 (AUD位置:${a}, SEI最早位置:${e})`)}return!l&&o.length>1&&(l=!0,h=`检测到多个AUD (数量:${o.length}, 位置:${o.join(", ")})`),!l&&a>0&&0===n.length&&0===d.length&&(l=!0,h=`AUD不在首位且没有参数集/SEI (AUD位置:${a})`),{hasAbnormalAUD:l,codec:i,details:l?h:"AUD位置正常",audPositions:o}}findStartCodes(e){let t=new Uint8Array(e),i=[];for(let e=0;e>1&63}parseNALUs(e,t){let i=this.findStartCodes(e),s=[];for(let r=0;r{let s=this.getNALUTypeName(e.type,t);this._logger.log(`NALU ${i}: ${s.padEnd(15)} | type=${e.type.toString().padStart(2)} | offset=${e.offset.toString().padStart(6)} | size=${e.size.toString().padStart(6)}`)}),this._logger.log("===========================")}getNALUTypeName(e,t){return t===B.H265?({0:"TRAIL_N",1:"TRAIL_R",16:"BLA_W_LP",19:"IDR_W_RADL",20:"IDR_N_LP",21:"CRA",32:"VPS",33:"SPS",34:"PPS",35:"AUD",39:"PREFIX_SEI",40:"SUFFIX_SEI"})[e]||`H265_Type${e}`:({1:"SLICE",5:"IDR",6:"SEI",7:"SPS",8:"PPS",9:"AUD",14:"PREFIX_NAL"})[e]||`H264_Type${e}`}mergeBuffers(e){let t=new Uint8Array(e.reduce((e,t)=>e+t.byteLength,0)),i=0;for(let s of e)t.set(new Uint8Array(s),i),i+=s.byteLength;return t.buffer}reset(){this._detectedCodec=void 0}constructor(){(0,s._)(this,"_logger",new o.ZP("H26xNALUProcessor")),(0,s._)(this,"_detectedCodec",void 0)}}class $ extends d.Z{bindListeners(){this._logger.log("init rtm loader worker"),this.on(n.Zo.SDP_TRANSFORM,this.handleSdpTransform),this.on(n.Zo.AV_CODEC_INFO,this.handleAvCodecInfo),this.on(n.Zo.RTM_RESPONSE_HEADERS,this._handleResponseHeaders),this.on(n.Zo.RTM_TTFB,this.handleTTFB),this.on(n.Zo.ERROR,this.handleError),this._transFFEventDown(n.Zo.SDP_LOAD),this._transFFEventDown(n.Zo.SDP_DISCONNECT)}load(e){let{url:t,onVideoChunk:i,onAudioChunk:s}=e;this._onVideoChunk=i,this._onAudioChunk=s,this.emit(n.Zo.SDP_LOAD,{url:t}),this.url=t}cancel(){this._logger.log("cancel"),delete this.url,delete this._onAudioChunk,delete this._onVideoChunk,this._videoPayloadMap={},this._audioPayloadMap={},this._avSyncClock.reset(),this._pendingAudioChunks=[],this._hasDetectAUD=!1,this._hasAbnormalAUD=!1,this._sampleRateDetector.stop(),this.emit(n.Zo.SDP_DISCONNECT)}destroy(){this._logger.log("destroy"),super.destroy(),this.cancel(),this.off(n.Zo.SDP_TRANSFORM,this.handleSdpTransform),this.off(n.Zo.AV_CODEC_INFO,this.handleAvCodecInfo),this.off(n.Zo.RTM_RESPONSE_HEADERS,this._handleResponseHeaders),this.off(n.Zo.RTM_TTFB,this.handleTTFB),this.off(n.Zo.ERROR,this.handleError)}getAudioMeta(e){let t=(null==e?void 0:e.payloadType)&&this._audioPayloadMap[null==e?void 0:e.payloadType];if(!!t&&t.codec!==b.OPUS){if(t.codec===b.AAC){var i;let s=null==e?void 0:null===(i=e.headerExtension)||void 0===i?void 0:i.find(e=>27===e.id);if(!s)return new P({codec:t.mimetype,sampleRate:t.sampleRate,channelCount:2,objectType:t.objectType,codecDesc:t.config});let r=D(s.payload);return r?new P({codec:t.mimetype,sampleRate:r.sampleFragament,channelCount:r.channel,objectType:r.object,codecDesc:t.config}):new P({codec:t.mimetype,sampleRate:t.sampleRate,channelCount:2,objectType:t.objectType,codecDesc:t.config})}}}_getVideoMeta(e){let t=e&&this._videoPayloadMap[e];return t?new N.Z({codec:t.mimetype}):void 0}constructor(e){super("",e),(0,s._)(this,"_onVideoChunk",void 0),(0,s._)(this,"_onAudioChunk",void 0),(0,s._)(this,"_videoPayloadMap",{}),(0,s._)(this,"_audioPayloadMap",{}),(0,s._)(this,"url",void 0),(0,s._)(this,"_avSyncClock",new F),(0,s._)(this,"_pendingAudioChunks",[]),(0,s._)(this,"_sampleRateDetector",void 0),(0,s._)(this,"_logger",new o.ZP("RtmLoaderWorker")),(0,s._)(this,"_processor",new W),(0,s._)(this,"_hasDetectAUD",!1),(0,s._)(this,"_hasAbnormalAUD",!1),(0,s._)(this,"handleSdpTransform",e=>{this._logger.log("handleSdpTransform");let{video:t,audio:i}=e;if(t){this._avSyncClock.reset(),this._pendingAudioChunks=[];let{readable:e,writable:i}=t;e.pipeThrough(new TransformStream({transform:(e,t)=>{var i,s;let r=e.getMetadata(),o=this._getVideoMeta(r.payloadType),{pts:a,dts:n,isFirst:d,usedExt18:l}=this._avSyncClock.processVideo(e.timestamp,r);if(d&&this._avSyncClock.fastSync&&!l&&this.handleError({error:new V.Z(V.t.DECODE_VIDEO_DODECODE_ERROR,"video hdrext18 not found")}),d&&(this._logger.log("video first pts(ms):",a),this._pendingAudioChunks.forEach(e=>{var t;let{data:i,meta:s,timestamp:r,rtcMeta:o,sampleRate:a}=e,n=this._avSyncClock.calcAudioPts(r,o,a);n&&(null===(t=this._onAudioChunk)||void 0===t||t.call(this,{pts:n.pts,data:i,dts:n.pts,duration:0,meta:s}))}),this._pendingAudioChunks=[]),!this._hasDetectAUD){let t;(null==o?void 0:o.codec)&&(t=o.codec.includes("avc")?"H264":"H265"),t&&this._processor.setDetectedCodec(t);let{hasAbnormalAUD:i}=this._processor.detectAbnormalAUD(e.data,t);this._hasAbnormalAUD=i,this._hasDetectAUD=!0}if(this._hasAbnormalAUD&&this._hasDetectAUD&&"key"===e.type){let t=new ArrayBuffer(e.data.byteLength);new Uint8Array(t).set(new Uint8Array(e.data));let s=this._processor.removeAUD(t);null===(i=this._onVideoChunk)||void 0===i||i.call(this,{pts:a,keyframe:"key"===e.type,units:[new Uint8Array(s)],meta:o,dts:n,duration:0})}else null===(s=this._onVideoChunk)||void 0===s||s.call(this,{pts:a,keyframe:"key"===e.type,units:[new Uint8Array(e.data)],meta:o,dts:n,duration:0});"key"===e.type&&t.enqueue(e)}})).pipeTo(i)}if(i){let{readable:e,writable:t}=i;e.pipeThrough(new TransformStream({transform:e=>{var t;let i=e.getMetadata(),s=this.getAudioMeta(i);if(!s)return;this._sampleRateDetector.updateCurrentTime(e.timestamp,i.payloadType);let r=this._avSyncClock.processAudio(e.timestamp,i,s.sampleRate);if("pending"===r){this._pendingAudioChunks.length>=$.MAX_PENDING_AUDIO&&this._pendingAudioChunks.shift(),this._pendingAudioChunks.push({data:new Uint8Array(e.data),meta:s,timestamp:e.timestamp,rtcMeta:i,sampleRate:s.sampleRate});return}if(null===r)return;let{pts:o,isFirst:a,usedExt18:n}=r;a&&this._avSyncClock.fastSync&&!n&&this.handleError({error:new V.Z(V.t.DECODE_AUDIO_DODECODE_ERROR,"audio hdrext18 not found")}),a&&(this._logger.log("audio first pts(ms):",o),44100===s.sampleRate&&(this._sampleRateDetector.start(),this._logger.log("sampleRateDetector","start"))),null===(t=this._onAudioChunk)||void 0===t||t.call(this,{pts:o,data:new Uint8Array(e.data),dts:o,duration:0,meta:s})}})).pipeTo(t)}}),(0,s._)(this,"handleAvCodecInfo",e=>{let{video:t,audio:i,enableFastSync:s}=e;this._videoPayloadMap=t,this._audioPayloadMap=i,this._avSyncClock.setFastSync(!!s),this._logger.log("avCodecInfo",JSON.stringify({video:t,audio:i,enableFastSync:s}))}),(0,s._)(this,"_handleResponseHeaders",e=>{let{response:t}=e;this.emit(x.le.RESPONSEHEADERS,t)}),(0,s._)(this,"handleTTFB",e=>{let{elapsed:t}=e;L.Z.addTTFB(),this.emit(x.le.TTFB,{elapsed:t,ok:!0,url:this.url||"",responseUrl:this.url||""})}),(0,s._)(this,"handleError",e=>{let{error:t}=e;this.emit(x.le.ERROR,t)}),(0,s._)(this,"_resetToNewSampleRate",(e,t)=>{this.handleError({error:new V.Z(V.t.RTM_NOT_SUPPORTED,"rtm samplerate not 44100")})}),this.bindListeners(),this._sampleRateDetector=new U(this._resetToNewSampleRate)}}(0,s._)($,"MAX_PENDING_AUDIO",200),i("117232");var H=i("818500"),Z=i("203458"),z=i("324743");class G extends H.Z{getDecodeInfo(){var e,t,i,s,r,o,a,n,d,l,h,u,c,_,m,p;return{video_frames:[this._decodeFrames,this._decodeOutputFrames,this.renderFrames],audio_chunks:[this._decodeAudioChunk,this._decodeOutputChunk,this.renderChunk],av_render_queue_size:[null===(e=this._audioFrameQueue)||void 0===e?void 0:e.length,null===(t=this._videoFrameQueue)||void 0===t?void 0:t.length],av_decoder_queue_size:[(null===(i=this._audioDecoder)||void 0===i?void 0:i.decodeQueueSize)||0,(null===(s=this._videoDecoder)||void 0===s?void 0:s.decodeQueueSize)||0],av_decoder_state:[(null===(r=this._audioDecoder)||void 0===r?void 0:r.state)||"",(null===(o=this._videoDecoder)||void 0===o?void 0:o.state)||""],current_time:+(this._currentTime/1e6).toFixed(1),video_timestamp:[((null===(a=this._videoTimeRange)||void 0===a?void 0:a.nextFrameTimestamp)||0)/1e6,((null===(d=this._videoFrameQueue)||void 0===d?void 0:null===(n=d[0])||void 0===n?void 0:n.timestamp)||0)/1e6],audio_timestamp:[((null===(l=this._audioTimeRange)||void 0===l?void 0:l.nextFrameTimestamp)||0)/1e6,((null===(u=this._audioFrameQueue)||void 0===u?void 0:null===(h=u[0])||void 0===h?void 0:h.timestamp)||0)/1e6],av_recv_queue_size:[null===(c=this._audioTimeRange)||void 0===c?void 0:c.length,null===(_=this._videoTimeRange)||void 0===_?void 0:_.length],av_buffered_range:[(((null===(m=this._audioTimeRange)||void 0===m?void 0:m.liveEdge)||0)-this._currentTime)/1e6,(((null===(p=this._videoTimeRange)||void 0===p?void 0:p.liveEdge)||0)-this._currentTime)/1e6]}}trimToLiveEdge(){var e,t,i,s,r,o;let a=(null===(e=this._videoTimeRange)||void 0===e?void 0:e.liveEdge)||0,n=(null===(t=this._audioTimeRange)||void 0===t?void 0:t.liveEdge)||0,d=Math.max(a,n);return this._emptyAVFrames(),a&&(this._videoTrimTimestamp=a),null===(i=this._audioDecoder)||void 0===i||i.flush().then(()=>{var e;this._emptyAVFrames(),null===(e=this._audioWritable)||void 0===e||e.postMessage({type:"clean"})}),this._lastAudioFrameMeta=null,null===(s=this._audioWritable)||void 0===s||s.postMessage({type:"clean"}),a&&(null===(r=this._videoTimeRange)||void 0===r||r.seekTo(a)),n&&(null===(o=this._audioTimeRange)||void 0===o||o.seekTo(n)),d&&(this._currentTime=d),d}destroy(){this._rtmAudioTimestampMap.clear(),this._lastAudioFrameMeta=null,super.destroy()}async addLateTrackMeta(e,t){this.logger.log("addLateTrackMeta:",e,t,`[${performance.now()}]`),e&&(this._videoMeta=e,this._videoTimeRange=new Z.Z(H.Z.codecConfig),this._videoTimeRange.addMeta(e),this._videoTargetDecodeEnd=H.Z.codecConfig.videoTargetDecodeEnd,e.frameRate<20&&(this._videoTargetDecodeEnd=2*H.Z.codecConfig.videoTargetDecodeEnd)),t&&(this._audioTimeRange=new z.Z(H.Z.codecConfig),this._audioTimeRange.addMeta(t),this.audioMeta=t),t&&!this._audioWritable&&(this.emit(n.Zo.MESSAGE_INIT_RENDER,{video:!!this._videoMeta,audio:!0,channelCount:t.channelCount,sampleRate:t.sampleRate||0,heAAC:t.heAAC||!1,audioTrack:this._audioTrack}),this._audioTrack=void 0);let i=[];e&&i.push(this._videoDecoderInit(e).then(e=>{this._videoDecoder=e}).catch(e=>{this.emit(n.Zo.MESSAGE_EVENT_VEERROR,V.Z.create(V.t.DECODE_VIDEO_INIT_ERROR,"DECODE_VIDEO_INIT_ERROR",e))})),t&&i.push(this._audioDecoderInit(t).catch(e=>{this.emit(n.Zo.MESSAGE_EVENT_VEERROR,V.Z.create(V.t.DECODE_AUDIO_INIT_ERROR,"DECODE_AUDIO_INIT_ERROR",e))})),await Promise.all(i),this._onlyVideo=!!this._videoMeta&&!this._audioMeta,this._onlyAudio=!!this._audioMeta&&!this._videoMeta,this.logger.log("late track decoder inited!"),this._bindVideoRenderDeriver(),this._decodeLoop(this._currentTime)}async _videoDecoderInit(e){let t=new VideoDecoder({output:this._onVideoDecodeOutput,error:this._onVideoDecodeError}),i={codec:e.codec};return t.configure(i),this.logger.log("video decoder inited!"),t}async _audioDecoderInit(e){let t=new AudioDecoder({output:this._onAudioDecodeOutput,error:this._onAudioDecodeError}),i={codec:e.codec,sampleRate:e.sampleRate,numberOfChannels:e.channelCount,description:e.codecDesc};this._heAAC=e.heAAC,t.configure(i),this._audioDecoder=t,this._audioDecodeConfig=i,this.logger.log("audio decoder inited!")}_decodeAudioHook(e){this._decodeAudioChunk++,this._rtmAudioTimestampMap.set(this._decodeAudioChunk,e.timestamp)}constructor(...e){super(...e),(0,s._)(this,"_rtmAudioTimestampMap",new Map),(0,s._)(this,"_decodeOutputChunk",0),(0,s._)(this,"_decodeAudioChunk",0),(0,s._)(this,"_decodeOutputFrames",0),(0,s._)(this,"_videoTrimTimestamp",0),(0,s._)(this,"isRTM",!0),(0,s._)(this,"_lastAudioFrameMeta",null),(0,s._)(this,"_onVideoDecodeOutput",e=>{if(this._videoTrimTimestamp>0&&e.timestampe.timestamp-t.timestamp)}),(0,s._)(this,"_onAudioDecodeOutput",e=>{var t;this._decodeOutputChunk++;let i=this._rtmAudioTimestampMap.get(this._decodeOutputChunk);this._rtmAudioTimestampMap.delete(this._decodeOutputChunk),"number"==typeof i&&i!==e.timestamp&&Object.defineProperty(e,"timestamp",{value:i,writable:!1});let s=[],r=Math.ceil(1024e6/((null===(t=this._audioMeta)||void 0===t?void 0:t.sampleRate)||e.sampleRate));for(;this._lastAudioFrameMeta&&e.timestamp-this._lastAudioFrameMeta.timestamp>r;){let e=function(e,t){let i=function(e,t,i){let s=e*t;if("f32"===i||"f32-planar"===i){let e=new Float32Array(s);return e.fill(0),e}if("s16"===i||"s16-planar"===i||"s32"===i||"s32-planar"===i){let e=new Int16Array(s);return e.fill(0),e}if("u8"===i||"u8-planar"===i){let e=new Int16Array(s);return e.fill(128),e}throw TypeError(`unexpected audio format: ${i}`)}(e.numberOfChannels,e.numberOfFrames,e.format);return new AudioData({format:e.format,numberOfChannels:e.numberOfChannels,numberOfFrames:e.numberOfFrames,sampleRate:e.sampleRate,timestamp:e.timestamp+t,data:i})}(this._lastAudioFrameMeta,r);this._lastAudioFrameMeta=j(e),s.push(e)}for(let t of(this._lastAudioFrameMeta=j(e),s.push(e),s))super._handleAudioFrame(t)})}}function j(e){return{format:e.format,numberOfChannels:e.numberOfChannels,numberOfFrames:e.numberOfFrames,sampleRate:e.sampleRate,timestamp:e.timestamp}}i("709922");var K=i("161231");class Q{static getRateIndexByRate(e){return Q.FREQ.indexOf(e)}static parseADTS(e,t){let i,s;let r=e.length,o=0;for(;o+2=r)return;let a=o,n=[],d=(60&e[o+2])>>>2,l=Q.FREQ[d];if(!l)throw Error(`Invalid sampling index: ${d}`);let h=((192&e[o+2])>>>6)+1,u=(1&e[o+2])<<2|(192&e[o+3])>>>6,{config:c,codec:_}=Q._getConfig(d,u,h),m=0,p=Q.getFrameDuration(l);for(;o+7>5,r-o=r?void 0:e.subarray(o),frames:n,samplingFrequencyIndex:d,sampleRate:l,objectType:h,channelCount:u,codec:_,config:c,originCodec:`mp4a.40.${h}`}}static parseAudioSpecificConfig(e){if(!e.length)return;let t=e[0]>>>3,i=(7&e[0])<<1|e[1]>>>7,s=(120&e[1])>>>3,r=Q.FREQ[i];if(!r)return;let{config:o,codec:a}=Q._getConfig(i,s,t);return{samplingFrequencyIndex:i,sampleRate:r,objectType:t,channelCount:s,config:o,codec:a,originCodec:`mp4a.40.${t}`}}static getFrameDuration(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:9e4;return 1024*t/e}static _getConfig(e,t,i){let s,r;let o=[];return K.vU?e>=6?(s=5,r=e-3):(s=2,r=e):K.Dt?(s=2,r=e):(s=2===i||5===i?i:5,r=e,e>=6?r=e-3:1===t&&(s=2,r=e)),o[0]=s<<3,o[0]|=(14&e)>>1,o[1]=(1&e)<<7,o[1]|=t<<3,5===s&&(o[1]|=(14&r)>>1,o[2]=(1&r)<<7,o[2]|=8,o[3]=0),{config:o,codec:`mp4a.40.${s}`}}static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t||3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}return new Uint8Array(0)}}(0,s._)(Q,"FREQ",[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350]);class q{static parseAnnexB(e){let t=e.length,i=2,s=0;for(;null!==e[i]&&void 0!==e[i]&&1!==e[i];)i++;if((s=++i+2)>=t)return[];let r=[];for(;s1&&void 0!==arguments[1]?arguments[1]:4;if(e.length<4)return;let s=e.length,r=[],o=0;for(;o+i1&&void 0!==arguments[1]?arguments[1]:0;return(e[t]<<24>>>0)+(e[t+1]<<16)+(e[t+2]<<8)+(e[t+3]||0)}(e,o),3===i&&(t>>>=8),o+=i,!!t){if(o+t>s)break;r.push(e.subarray(o,o+t)),o+=t}}return r}static parseSEI(e,t){let i=e.length,s=t?2:1,r=0,o=0,a="";for(;255===e[s];)r+=255,s++;for(r+=e[s++];255===e[s];)o+=255,s++;if(o+=e[s++],5===r&&i>s+16)for(let t=0;t<16;t++)a+=e[s].toString(16),s++;return{payload:e.subarray(s,s+o),type:r,size:o,uuid:a}}static removeEPB(e){let t=e.byteLength,i=[],s=1;for(;s1&&void 0!==arguments[1]&&arguments[1],i=new Uint8Array(e.units[0].buffer);q.parseAnnexB(i).forEach(i=>{let s=t?i[0]>>>1&63:31&i[0];if(6!==s||t){if(t&&(39===s||40===s)){let s=q.parseSEI(q.removeEPB(i),t);this._addOrEmitSEI({code:s.type,content:s.payload,time:e.pts/1e3,uuid:s.uuid,dts:e.pts})}}else{let s=q.parseSEI(q.removeEPB(i),t);this._addOrEmitSEI({code:s.type,content:s.payload,time:e.pts/1e3,uuid:s.uuid,dts:e.pts})}})}throw(e){if(!e||!this._seiSet.size)return;let t=e-.2,i=e+.2,s=[];this._seiSet.forEach(e=>{e.time>=t&&e.time<=i&&s.push(e)}),s.forEach(e=>{this._seiSet.delete(e),this._core.emit(Y.o.SEI,e)}),this._seiSet.forEach(t=>{t.time{this._trimBuffer()},2e3)}_stopBufferTrim(){this._bufferTrimTimer&&(clearInterval(this._bufferTrimTimer),this._bufferTrimTimer=void 0)}_trimBuffer(){if(!this._mediaCodec)return;let e=this._mediaCodec.trimToLiveEdge();this.logger.log(`RTM pause buffer trim, liveEdge: ${e/1e3}ms`)}get mediaInfo(){var e;return null===(e=this._mediaCodec)||void 0===e?void 0:e.getMediaInfo()}getWritable(){return this._mediaCodec?{videoWritable:this._mediaCodec._videoWritable,audioWritable:this._mediaCodec._audioWritable,audioTrack:this._mediaCodec._audioTrack}:this._writeable}_loadData(e){this._cfg.url=e,!this._mediaLoader&&(this._mediaLoader=new $(this.stateManager)),this._mediaLoader.load({url:e,onVideoChunk:this._onVideoChunk,onAudioChunk:this._onAudioChunk}),this._mediaLoader.on(n.Zo.RTM_STATS,this._handleStats),this._mediaLoader.on(n.Zo.AV_CODEC_INFO,e=>{this._fastSyncEnabled=!!e.enableFastSync})}async _reset(){var e,t,i;await super._reset(),null===(e=this._seiService)||void 0===e||e.reset(),this._stopBufferTrim(),clearTimeout(this._metaTimer),this._stopBufferTrim(),this._videoMeta=void 0,this._audioMeta=void 0,this._metaDataAdded=!1,null===(t=this._mediaCodec)||void 0===t||t.destroy(),this._mediaCodec=null,null===(i=this._mediaLoader)||void 0===i||i.cancel(),this._receivedFrames=0,this._receiveVideoTs=0,this._receivedSamples=0,this._receiveAudioTs=0,this._rtmVideoTsOffset=0,this._checkPlaybackrateTime=0,this._preRtmStats=[],this._fastSyncEnabled=!1}_genCodecIns(){!this._mediaCodec&&(this._mediaCodec=new G(this._cfg.instanceId,this._cfg.isVod,this.stateManager,this._writeable,this._cfg.muted),this._mediaCodec.earlyDecoderInit=this._earlyDecoderInit,this._mediaCodec.on(n.Zo.MESSAGE_EVENT_TIMEUPDATE,this.onTimeupdate),this._mediaCodec.initSR(this._cfg.sr))}getMediaCodec(){return this._mediaCodec}onPlayerDestroy(e){super.onPlayerDestroy(e),clearTimeout(this._metaTimer),this._stopBufferTrim()}_checkRtmAvDiff(e){if(!this._fastSyncEnabled&&e<.01){let e=this._receiveVideoTs-this._receiveAudioTs;Math.abs(e)>.1&&(this._rtmVideoTsOffset+=e>0?-50:50,this.logger.log(`rtm recv av diff ${e}, offset ${this._rtmVideoTsOffset}`))}}_checkRtmStats(e){var t;if(null===(t=this.stateManager)||void 0===t?!void 0:!t.get("paused")){if(this._preRtmStats.push(e),this._preRtmStats.length>=3){let e=this._preRtmStats[0],t=this._preRtmStats[2],i=function(e,t){if(e.length<4||t.length<4)return null;let i=e[0]===t[0],s=e[2]===t[2],r=e[3]===t[3];return i?{stallStage:"receive",notRecv:i,notDecode:s,notRender:r}:s?{stallStage:"decode",notRecv:i,notDecode:s,notRender:r}:r?{stallStage:"render",notRecv:i,notDecode:s,notRender:r}:null}(e.video_frames,t.video_frames);i&&this.emit(x.le.FLVERROR,new V.Z(V.t.DECODE_VIDEO_DODECODE_ERROR,`no video frame during 4s: stalled at ${i.stallStage}`,i))}this._preRtmStats=this._preRtmStats.slice(-2)}}destroy(){var e;null===(e=this._mediaLoader)||void 0===e||e.destroy(),super.destroy()}constructor(e,t){super(e,t),(0,s._)(this,"_mediaCodec",null),(0,s._)(this,"_videoMeta",void 0),(0,s._)(this,"_audioMeta",void 0),(0,s._)(this,"_metaDataAdded",!1),(0,s._)(this,"_metaTimer",void 0),(0,s._)(this,"_seiService",void 0),(0,s._)(this,"_mediaLoader",null),(0,s._)(this,"_receivedFrames",0),(0,s._)(this,"_receiveVideoTs",0),(0,s._)(this,"_receivedSamples",0),(0,s._)(this,"_receiveAudioTs",0),(0,s._)(this,"_checkPlaybackrateTime",0),(0,s._)(this,"_bufferTrimTimer",void 0),(0,s._)(this,"_fastSyncEnabled",!1),(0,s._)(this,"_onVideoChunk",e=>{var t,i,s,r,o,a,n;let d=e.meta;this._receivedFrames++,e.pts=Math.round(e.pts+this._rtmVideoTsOffset),this._receiveVideoTs=Math.max(e.pts/1e3,this._receiveVideoTs),!this._videoMeta&&d&&(this._genCodecIns(),this._videoMeta=d,this._earlyDecoderInit?this._metaDataAdded?null===(r=this._mediaCodec)||void 0===r||r.addLateTrackMeta(d,null):(this._audioMeta?null===(o=this._mediaCodec)||void 0===o||o.addMetaData(d,this._audioMeta):null===(a=this._mediaCodec)||void 0===a||a.addMetaData(d,null),this._metaDataAdded=!0):this._audioMeta?(clearTimeout(this._metaTimer),null===(n=this._mediaCodec)||void 0===n||n.addMetaData(d,this._audioMeta)):this._metaTimer=setTimeout(()=>{var e;null===(e=this._mediaCodec)||void 0===e||e.addMetaData(d,null)},this._cfg.analyzeDuration),this.emit(x.le.METADATA,{trackType:"video",codec:d.codec})),null===(i=this._seiService)||void 0===i||i.addSample(e,null==d?void 0:null===(t=d.codec)||void 0===t?void 0:t.includes("hev1")),null===(s=this._mediaCodec)||void 0===s||s.appendBuffer([e],[],!0)}),(0,s._)(this,"_onAudioChunk",e=>{var t,i,s,r,o;let a=e.meta;this._receivedSamples++,this._receiveAudioTs=e.pts/1e3,!this._audioMeta&&a&&(this._genCodecIns(),this._audioMeta=a,this._earlyDecoderInit?this._metaDataAdded?null===(i=this._mediaCodec)||void 0===i||i.addLateTrackMeta(null,a):(this._videoMeta?null===(s=this._mediaCodec)||void 0===s||s.addMetaData(this._videoMeta,a):null===(r=this._mediaCodec)||void 0===r||r.addMetaData(null,a),this._metaDataAdded=!0):this._videoMeta?(clearTimeout(this._metaTimer),null===(o=this._mediaCodec)||void 0===o||o.addMetaData(this._videoMeta,a)):this._metaTimer=setTimeout(()=>{var e;null===(e=this._mediaCodec)||void 0===e||e.addMetaData(null,a)},this._cfg.analyzeDuration),this.emit(x.le.METADATA,{trackType:"audio",codec:a.codec,sampleRate:a.sampleRate,channelCount:a.channelCount,objectType:a.objectType})),null===(t=this._mediaCodec)||void 0===t||t.appendBuffer([],[e],!0)}),(0,s._)(this,"onTimeupdate",()=>{var e,t;null===(t=this._seiService)||void 0===t||t.throw(((null===(e=this.mediaInfo)||void 0===e?void 0:e.VideoFrameTime)||0)/n.Ll);let i=Date.now();!(i-this._checkPlaybackrateTime<1e3)&&(this._checkPlaybackrateTime=i,this._checkPlaybackrate(800,1e3))}),(0,s._)(this,"_handleStats",e=>{var t,i,s,o;let a=!!(null===(t=this.stateManager)||void 0===t?void 0:t.get("paused")),{video:n,audio:d}=(null==e?void 0:e.stats)||{};this.emit(x.le.PROP_SPEED,{totalByteSize:n.bytesReceived+d.bytesReceived,renderFrames:(null===(i=this._mediaCodec)||void 0===i?void 0:i.renderFrames)||0});let l=(null===(s=this._mediaCodec)||void 0===s?void 0:s.getDecodeInfo())||{},{video_frames:h=[],audio_chunks:u=[],video_timestamp:c=[],audio_timestamp:_=[]}=l,p=(0,m._)(l,["video_frames","audio_chunks","video_timestamp","audio_timestamp"]),f=(0,r._)({rtt:n.rtt||d.rtt,video_frames:[this._receivedFrames,...h],audio_chunks:[this._receivedSamples,...u],video_timestamp:[this._receiveVideoTs,...c],audio_timestamp:[this._receiveAudioTs,..._],av_loss_rate:[d.audioLossRate||0,n.videoLossRate||0],av_kbps:[d.receivedKBitrate||0,n.receivedKBitrate||0],nack_count:n.nackCount||0,video_time_offset:this._rtmVideoTsOffset,playback_rate:(null===(o=this._mediaCodec)||void 0===o?void 0:o._playbackRate)||0,is_paused:a},p);this.emit(x.le.RTM_NETWORK,f),this._checkRtmAvDiff(d.audioLossRate+n.videoLossRate),this._checkRtmStats(f)}),(0,s._)(this,"_rtmVideoTsOffset",0),(0,s._)(this,"_preRtmStats",[]),this._seiService=new X(this)}}i("313036");class ee extends H.Z{get decodeOutputFrames(){return this._decodeOutputFrames}get decodeOutputChunks(){return this._decodeOutputChunk}get renderChunks(){return this.renderChunk}getDecodeInfo(){var e,t,i,s,r,o,a,n,d,l,h,u,c,_,m,p;return{video_frames:[this._decodeFrames,this._decodeOutputFrames,this.renderFrames],audio_chunks:[this._decodeAudioChunk,this._decodeOutputChunk,this.renderChunk],av_render_queue_size:[null===(e=this._audioFrameQueue)||void 0===e?void 0:e.length,null===(t=this._videoFrameQueue)||void 0===t?void 0:t.length],av_decoder_queue_size:[(null===(i=this._audioDecoder)||void 0===i?void 0:i.decodeQueueSize)||0,(null===(s=this._videoDecoder)||void 0===s?void 0:s.decodeQueueSize)||0],av_decoder_state:[(null===(r=this._audioDecoder)||void 0===r?void 0:r.state)||"",(null===(o=this._videoDecoder)||void 0===o?void 0:o.state)||""],current_time:+(this._currentTime/1e6).toFixed(1),video_timestamp:[((null===(a=this._videoTimeRange)||void 0===a?void 0:a.nextFrameTimestamp)||0)/1e6,((null===(d=this._videoFrameQueue)||void 0===d?void 0:null===(n=d[0])||void 0===n?void 0:n.timestamp)||0)/1e6],audio_timestamp:[((null===(l=this._audioTimeRange)||void 0===l?void 0:l.nextFrameTimestamp)||0)/1e6,((null===(u=this._audioFrameQueue)||void 0===u?void 0:null===(h=u[0])||void 0===h?void 0:h.timestamp)||0)/1e6],av_recv_queue_size:[null===(c=this._audioTimeRange)||void 0===c?void 0:c.length,null===(_=this._videoTimeRange)||void 0===_?void 0:_.length],av_buffered_range:[(((null===(m=this._audioTimeRange)||void 0===m?void 0:m.liveEdge)||0)-this._currentTime)/1e6,(((null===(p=this._videoTimeRange)||void 0===p?void 0:p.liveEdge)||0)-this._currentTime)/1e6]}}trimToLiveEdge(){var e,t,i,s,r,o;let a=(null===(e=this._videoTimeRange)||void 0===e?void 0:e.liveEdge)||0,n=(null===(t=this._audioTimeRange)||void 0===t?void 0:t.liveEdge)||0,d=Math.max(a,n);return this._emptyAVFrames(),a&&(this._videoTrimTimestamp=a),null===(i=this._audioDecoder)||void 0===i||i.flush().then(()=>{var e;this._emptyAVFrames(),null===(e=this._audioWritable)||void 0===e||e.postMessage({type:"clean"})}),null===(s=this._audioWritable)||void 0===s||s.postMessage({type:"clean"}),a&&(null===(r=this._videoTimeRange)||void 0===r||r.seekTo(a)),n&&(null===(o=this._audioTimeRange)||void 0===o||o.seekTo(n)),d&&(this._currentTime=d),d}destroy(){this._rtmAudioTimestampMap.clear(),super.destroy()}async _audioDecoderInit(e){let t=new AudioDecoder({output:this._onAudioDecodeOutput,error:this._onAudioDecodeError}),i={codec:e.codec,sampleRate:e.sampleRate,numberOfChannels:e.channelCount};return e.description&&(i.description=e.description),this._heAAC=e.heAAC,AudioDecoder.isConfigSupported(i).then(()=>t.configure(i)).then(()=>{this._audioDecoder=t,this._audioDecodeConfig=i,this.logger.log("audio decoder inited!")})}_decodeAudioHook(e){this._decodeAudioChunk++,this._rtmAudioTimestampMap.set(this._decodeAudioChunk,e.timestamp)}constructor(...e){super(...e),(0,s._)(this,"_rtmAudioTimestampMap",new Map),(0,s._)(this,"_decodeOutputChunk",0),(0,s._)(this,"_decodeAudioChunk",0),(0,s._)(this,"_decodeOutputFrames",0),(0,s._)(this,"_videoTrimTimestamp",0),(0,s._)(this,"isRTM",!0),(0,s._)(this,"_onVideoDecodeOutput",e=>{if(this._videoTrimTimestamp>0&&e.timestampe.timestamp-t.timestamp)}),(0,s._)(this,"_onAudioDecodeOutput",e=>{this._decodeOutputChunk++;let t=this._rtmAudioTimestampMap.get(this._decodeOutputChunk);this._rtmAudioTimestampMap.delete(this._decodeOutputChunk),"number"==typeof t&&t!==e.timestamp&&Object.defineProperty(e,"timestamp",{value:t,writable:!1}),super._handleAudioFrame(e)})}}class et{_addOrEmitSEI(e){if(!this._firstSEIEmited){this._firstSEIEmited=!0,this._core.emit(Y.o.SEI,e);return}this._seiSet.add(e)}throw(e){if(!e||!this._seiSet.size)return;let t=e-.2,i=e+.2,s=[];this._seiSet.forEach(e=>{e.time>=t&&e.time<=i&&s.push(e)}),s.forEach(e=>{this._seiSet.delete(e),this._core.emit(Y.o.SEI,e)}),this._seiSet.forEach(t=>{t.time{if(!e.ok)throw er.log("load rtm-session sdk failed, status: ",e.status),Error(`HTTP ${e.status}`);return e.text()}).then(t=>{er.log("load rtm-session sdk success, spent time:",performance.now()-e,"ms"),ea(t)}).catch(e=>{throw eo=null,e})}var ed=i("229121");function el(e){return e<0?e:Math.trunc(100*e)/100}function eh(e,t){if(e<0||t<0)return -1;let i=e-t;return i>=0?i:-1}class eu{markSdkLoaded(){this.sdk_load_time=this.now()-this.t0}markConnectStart(){this.connect_start_time=this.now()-this.t0}markConnectOpen(){this.connect_open_time=this.now()-this.t0}onReconnecting(){this.reconnect_attempts+=1,this.reconnect_last_time=this.now()-this.t0}markSdpOfferSent(){this.sdp_offer_sent_time=this.now()-this.t0}markSdpAnswerReceived(){this.sdp_answer_received_time=this.now()-this.t0}markSdpNegotiationComplete(){this.sdp_negotiation_complete_time=this.now()-this.t0}markFirstVideoFrame(){if(!(this.first_video_encoded_frame_time>=0))this.first_video_encoded_frame_time=this.now()-this.t0}markFirstAudioFrame(){if(!(this.first_audio_encoded_frame_time>=0))this.first_audio_encoded_frame_time=this.now()-this.t0}markPreloadStatus(e){this.preload_status=e}finalize(){let e=this.sdk_load_time>=0?this.sdk_load_time:-1,t=eh(this.connect_open_time,this.connect_start_time),i=eh(this.sdp_negotiation_complete_time,this.sdp_offer_sent_time),s=eh(this.first_video_encoded_frame_time,this.sdp_negotiation_complete_time),r=eh(this.first_audio_encoded_frame_time,this.sdp_negotiation_complete_time),o=Math.max(this.first_video_encoded_frame_time,this.first_audio_encoded_frame_time);return{sdk_load_time:el(this.sdk_load_time),connect_start_time:el(this.connect_start_time),connect_open_time:el(this.connect_open_time),reconnect_last_time:el(this.reconnect_last_time),reconnect_count:this.reconnect_attempts,sdp_offer_sent_time:el(this.sdp_offer_sent_time),sdp_answer_received_time:el(this.sdp_answer_received_time),sdp_negotiation_complete_time:el(this.sdp_negotiation_complete_time),first_video_frame_time:el(this.first_video_encoded_frame_time),first_audio_frame_time:el(this.first_audio_encoded_frame_time),sdk_load_duration:el(e),connect_open_duration:el(t),sdp_negotiation_duration:el(i),first_video_frame_duration:el(s),first_audio_frame_duration:el(r),total_duration:el(o),preload_status:this.preload_status}}now(){return performance.now()}constructor(){(0,s._)(this,"t0",void 0),(0,s._)(this,"sdk_load_time",-1),(0,s._)(this,"connect_start_time",-1),(0,s._)(this,"connect_open_time",-1),(0,s._)(this,"reconnect_last_time",-1),(0,s._)(this,"reconnect_attempts",0),(0,s._)(this,"sdp_offer_sent_time",-1),(0,s._)(this,"sdp_answer_received_time",-1),(0,s._)(this,"sdp_negotiation_complete_time",-1),(0,s._)(this,"first_video_encoded_frame_time",-1),(0,s._)(this,"first_audio_encoded_frame_time",-1),(0,s._)(this,"preload_status","none"),this.t0=this.now()}}class ec extends d.Z{async load(e){this.cancel(),this._isCanceled=!1,this._hasReceivedFrame=!1,this._stoppedWhilePaused=!1;let t=++this._loadId;this._timingCollector=new eu;try{await en()}catch(e){this._emitError(V.t.RTM_WEBTS_SDK_LOAD_ERROR,`Failed to load rtm-session SDK: ${e}`);return}if(t!==this._loadId)return;this._timingCollector.markSdkLoaded();let i=globalThis.__RtmSessionClass,s=i.isSupported();if(!s.supported){this._emitError(V.t.RTM_WEBTS_NOT_SUPPORTED,s.reason||"RtmSession not supported");return}let{url:r,maxReconnectCount:o=2,onVideoChunk:a,onAudioChunk:n,onStats:d,onMediaStreamMeta:l,onSEINalu:h}=e,u=r.startsWith("//")?`https:${r}`:r;this._onVideoChunk=a,this._onAudioChunk=n,this._onStats=d,this._onMediaStreamMeta=l,this._onSEINalu=h,this.url=r,this._connectStartTime=Date.now(),u===r?this._logger.log("load",u):this._logger.log("load",u,", rawUrl:",r),this._session=new i({enableSRSync:!0}),this._bindSessionListeners(this._session),this._timingCollector.markPreloadStatus(i.getPreloadStatus(u).status),this._timingCollector.markConnectStart(),this._logger.log("maxReconnectCount:",o),this._session.connect({url:u,transport:{maxReconnectCount:o,autoReconnect:!0}}).catch(e=>{this._logger.warn("connect error",e),this._emitError(V.t.RTM_WEBTS_ERROR,e.toString())})}cancel(){this._isCanceled=!0,this._loadId++,this._logger.log("cancel"),this._session&&(this._unbindSessionListeners(this._session),this._session.destroy(),this._session=null),this.url=void 0,this._onAudioChunk=void 0,this._onVideoChunk=void 0,this._connectStartTime=0,this._onStats=void 0,this._onMediaStreamMeta=void 0,this._onSEINalu=void 0,this._mediaInfo=void 0,this._videoMeta=void 0,this._audioMeta=void 0,this._timingCollector=void 0,this._expectVideo=!1,this._expectAudio=!1}destroy(){super.destroy(),this.cancel(),this._logger.log("destroy")}_bindSessionListeners(e){e.on("error",this._handleRtmSessionError),e.on("video-frame",this._handleVideoFrame),e.on("audio-frame",this._handleAudioFrame),e.on("media-stream-info",this._handleMediaStreamInfo),e.on("stats",this._handleStats),e.on("sei-nalu",this._handleSEINalu),e.on("connect-open",this._handleConnectOpen),e.on("reconnecting",this._handleReconnecting),e.on("connect-fail",this._handleConnectFail),e.on("reconnect-fail",this._handleReconnectFail),e.on("disconnected",this._handleDisconnected),e.on("connection-terminated",this._handleConnectionTerminated),e.on("sdp-offer-sent",this._handleSdpOfferSent),e.on("sdp-answer-received",this._handleSdpAnswerReceived),e.on("sdp-negotiation-complete",this._handleSdpNegotiationComplete),e.on("sdp-negotiation-failed",this._handleSdpNegotiationFailed)}_unbindSessionListeners(e){e.off("error",this._handleRtmSessionError),e.off("video-frame",this._handleVideoFrame),e.off("audio-frame",this._handleAudioFrame),e.off("media-stream-info",this._handleMediaStreamInfo),e.off("stats",this._handleStats),e.off("sei-nalu",this._handleSEINalu),e.off("connect-open",this._handleConnectOpen),e.off("reconnecting",this._handleReconnecting),e.off("connect-fail",this._handleConnectFail),e.off("reconnect-fail",this._handleReconnectFail),e.off("disconnected",this._handleDisconnected),e.off("connection-terminated",this._handleConnectionTerminated),e.off("sdp-offer-sent",this._handleSdpOfferSent),e.off("sdp-answer-received",this._handleSdpAnswerReceived),e.off("sdp-negotiation-complete",this._handleSdpNegotiationComplete),e.off("sdp-negotiation-failed",this._handleSdpNegotiationFailed)}_tryEmitTiming(){let e=this._timingCollector;if(!e||!this._expectVideo&&!this._expectAudio)return;let t=e.finalize();if((!this._expectVideo||!(t.first_video_frame_time<0))&&(!!this._expectVideo||!this._expectAudio||!(t.first_audio_frame_time<0)))this._logger.log("timing",JSON.stringify(t,null,2)),this.emit(x.le.RTM_WEBTS_TIMING,t),this._timingCollector=void 0}isStoppedWhilePaused(){return this._stoppedWhilePaused}consumePausedErrorStop(){let e=this._stoppedWhilePaused;return this._stoppedWhilePaused=!1,e}constructor(e){super("",e),(0,s._)(this,"_logger",new o.ZP("RtmWebTsLoaderWorker")),(0,s._)(this,"_session",null),(0,s._)(this,"_onVideoChunk",void 0),(0,s._)(this,"_onAudioChunk",void 0),(0,s._)(this,"_onStats",void 0),(0,s._)(this,"_onMediaStreamMeta",void 0),(0,s._)(this,"_onSEINalu",void 0),(0,s._)(this,"_mediaInfo",void 0),(0,s._)(this,"_videoMeta",void 0),(0,s._)(this,"_audioMeta",void 0),(0,s._)(this,"_connectStartTime",0),(0,s._)(this,"_timingCollector",void 0),(0,s._)(this,"_expectVideo",!1),(0,s._)(this,"_expectAudio",!1),(0,s._)(this,"_loadId",0),(0,s._)(this,"url",void 0),(0,s._)(this,"_isCanceled",!1),(0,s._)(this,"_hasReceivedFrame",!1),(0,s._)(this,"_stoppedWhilePaused",!1),(0,s._)(this,"_handleMediaStreamInfo",e=>{var t;if(this._logger.log("media-stream-info",JSON.stringify(e)),this._mediaInfo=e,this._expectVideo=!!e.video,this._expectAudio=!!e.audio,e.video){let{codec:t}=e.video;this._videoMeta=new ed.Z({codec:t})}if(e.audio){let{codec:t,sampleRate:i,channels:s,aacObjectType:r,aacCoreSampleRate:o,description:a}=e.audio;this._audioMeta=new ei({codec:t,sampleRate:null!=o?o:i,channelCount:s,objectType:null!=r?r:2,description:a})}null===(t=this._onMediaStreamMeta)||void 0===t||t.call(this,{videoMeta:this._videoMeta,audioMeta:this._audioMeta,hasVideo:this._expectVideo,hasAudio:this._expectAudio})}),(0,s._)(this,"_handleRtmSessionError",e=>{this._logger.error("media session error, err:",e),this._emitError(V.t.RTM_WEBTS_ERROR,null==e?void 0:e.toString())}),(0,s._)(this,"_handleVideoFrame",e=>{var t,i,s;this._hasReceivedFrame=!0,null===(t=this._timingCollector)||void 0===t||t.markFirstVideoFrame(),this._tryEmitTiming();let r=(null!==(s=e.timestampUs)&&void 0!==s?s:0)/1e3;null===(i=this._onVideoChunk)||void 0===i||i.call(this,{pts:r,keyframe:!!e.isKeyFrame,units:[e.data],meta:this._videoMeta,dts:r,duration:0})}),(0,s._)(this,"_handleAudioFrame",e=>{var t,i,s;!this._expectVideo&&(this._hasReceivedFrame=!0),null===(t=this._timingCollector)||void 0===t||t.markFirstAudioFrame(),this._tryEmitTiming();let r=(null!==(s=e.timestampUs)&&void 0!==s?s:0)/1e3;null===(i=this._onAudioChunk)||void 0===i||i.call(this,{pts:r,data:e.data,dts:r,duration:0,meta:this._audioMeta})}),(0,s._)(this,"_handleStats",e=>{var t;null===(t=this._onStats)||void 0===t||t.call(this,e)}),(0,s._)(this,"_handleSEINalu",e=>{var t;null===(t=this._onSEINalu)||void 0===t||t.call(this,e)}),(0,s._)(this,"_handleConnectOpen",()=>{var e;if(!this._session)return;this._logger.log("connect-open"),null===(e=this._timingCollector)||void 0===e||e.markConnectOpen();let t=Date.now()-this._connectStartTime;this.emit(x.le.TTFB,{elapsed:t,ok:!0,url:this.url||"",responseUrl:this.url||""})}),(0,s._)(this,"_handleReconnecting",e=>{var t;null===(t=this._timingCollector)||void 0===t||t.onReconnecting()}),(0,s._)(this,"_handleConnectFail",e=>{this._logger.warn(`connect failed: ${e}`)}),(0,s._)(this,"_handleReconnectFail",e=>{this._logger.warn(`reconnect failed: ${e}`)}),(0,s._)(this,"_handleDisconnected",e=>{if(this._logger.warn(`disconnected: ${e}`),this._isCanceled){this._logger.log("disconnected, but is canceled");return}let t=this._expectAudio||this._expectVideo;this._session&&t&&"api call"!==e&&(this.cancel(),this._emitError(V.t.NETWORK,e))}),(0,s._)(this,"_handleConnectionTerminated",e=>{if(this._logger.warn(`connection-terminated: ${e}`),!!this._session)this._emitError(V.t.NETWORK,e)}),(0,s._)(this,"_handleSdpOfferSent",e=>{var t;null===(t=this._timingCollector)||void 0===t||t.markSdpOfferSent()}),(0,s._)(this,"_handleSdpAnswerReceived",e=>{var t;null===(t=this._timingCollector)||void 0===t||t.markSdpAnswerReceived()}),(0,s._)(this,"_handleSdpNegotiationComplete",()=>{if(!!this._session)this._logger.log("sdp-negotiation-complete"),this._timingCollector&&(this._timingCollector.markSdpNegotiationComplete(),this._tryEmitTiming())}),(0,s._)(this,"_handleSdpNegotiationFailed",e=>{this._logger.warn(`sdp negotiation failed, reason: ${e}`),this._emitError(V.t.RTM_WEBTS_SDP_NEGOTIATION_ERROR,`sdp negotiation failed, reason: ${e}`)}),(0,s._)(this,"_emitError",(e,t)=>{var i;if((null===(i=this.stateManager)||void 0===i?void 0:i.get("paused"))&&this._hasReceivedFrame){this._logger.warn(`suppress error while paused (stop pulling), code: ${e}, message: ${t}`),this._stoppedWhilePaused=!0,this.cancel();return}this._logger.warn(`error, code: ${e}, message: ${t}`);this.emit(x.le.ERROR,{code:e,message:t,ext:""})}),en().catch(()=>{})}}let e_=2;var em={OK:"ok",NO_PACKET:"no_packet",NO_DECODE:"no_decode",NO_RENDER:"no_render"};class ep extends p.Z{_applyChaseFrameAbConfig(e){let t=e.ab;if(!t)return;let i=(e,t)=>"number"==typeof e&&e>0?e:t;this._checkIntervalMs=i(t.webts_chase_check_interval_ms,this._checkIntervalMs);let s=i(t.webts_chase_min_buffer_ms,this._chaseFrameMinBufferMs),r=i(t.webts_chase_max_buffer_ms,this._chaseFrameMaxBufferMs);s<=r?(this._chaseFrameMinBufferMs=s,this._chaseFrameMaxBufferMs=r):this._logger.warn(`invalid webts chase frame ab config, min > max, ignored: min ${s}, max ${r}`),this._logger.log(`chase frame config, checkInterval: ${this._checkIntervalMs}ms, minBuffer: ${this._chaseFrameMinBufferMs}ms, maxBuffer: ${this._chaseFrameMaxBufferMs}ms`)}get mediaInfo(){var e;return null===(e=this._mediaCodec)||void 0===e?void 0:e.getMediaInfo()}onPause(){this.stateManager&&!0!==this.stateManager.get("paused")&&this.stateManager.set("paused",!0),super.onPause(),this._startBufferTrim()}onPlay(){var e;this.stateManager&&!1!==this.stateManager.get("paused")&&this.stateManager.set("paused",!1),this._stopBufferTrim(),this._stallCheckHistory=[],this._cfg.url&&(null===(e=this._mediaLoader)||void 0===e?void 0:e.consumePausedErrorStop())&&(this._cfg.preloadUrl=void 0,this._logger.log("resume after paused-error stop, reload:",this._cfg.url),this.load({url:this._cfg.url,paused:!1})),super.onPlay()}getWritable(){return this._mediaCodec?{videoWritable:this._mediaCodec._videoWritable,audioWritable:this._mediaCodec._audioWritable,audioTrack:this._mediaCodec._audioTrack}:this._writeable}_loadData(e){var t;this._cfg.url=e,!this._mediaLoader&&(this._mediaLoader=new ec(this.stateManager));let i=this._cfg.preloadUrl||e,s=null===(t=this._cfg.ab)||void 0===t?void 0:t.webts_max_reconnect_count,r="number"==typeof s&&Number.isInteger(s)&&s>=0?s:void 0;this._mediaLoader.load({url:i,maxReconnectCount:r,onVideoChunk:this._onVideoChunk,onAudioChunk:this._onAudioChunk,onStats:this._handleStats,onMediaStreamMeta:this._onMediaStreamMeta,onSEINalu:this._onSEINalu})}async _reset(){var e,t,i;await super._reset(),null===(e=this._seiService)||void 0===e||e.reset(),clearTimeout(this._metaTimer),this._stopBufferTrim(),null===(t=this._mediaLoader)||void 0===t||t.cancel(),this._videoMeta=void 0,this._audioMeta=void 0,this._metaDataAdded=!1,null===(i=this._mediaCodec)||void 0===i||i.destroy(),this._mediaCodec=null,this._receivedVideoPacketCount=0,this._lastReceivedVideoTimeSec=0,this._receivedAudioChunkCount=0,this._lastReceivedAudioTimeSec=0,this._checkPlaybackrateTime=0,this._stallCheckHistory=[]}getMediaCodec(){return this._mediaCodec}onPlayerDestroy(e){super.onPlayerDestroy(e),clearTimeout(this._metaTimer),this._stopBufferTrim()}destroy(){var e;null===(e=this._mediaLoader)||void 0===e||e.destroy(),super.destroy()}_startBufferTrim(){this._stopBufferTrim(),this._trimBuffer(),this._bufferTrimTimer=setInterval(()=>{var e;if(null===(e=this._mediaLoader)||void 0===e?!void 0:!e.isStoppedWhilePaused())this._trimBuffer()},2e3)}_stopBufferTrim(){this._bufferTrimTimer&&(clearInterval(this._bufferTrimTimer),this._bufferTrimTimer=void 0)}_trimBuffer(){if(!this._mediaCodec)return;let e=this._mediaCodec.trimToLiveEdge();this.logger.log(`RTM-WEBTS pause buffer trim, liveEdge: ${e/1e3}ms`)}_genCodecIns(){if(!this._mediaCodec)this._mediaCodec=new ee(this._cfg.instanceId,this._cfg.isVod,this.stateManager,this._writeable,this._cfg.muted),this._mediaCodec.on(n.Zo.MESSAGE_EVENT_TIMEUPDATE,this.onTimeupdate),this._mediaCodec.initSR(this._cfg.sr)}_emitVideoMetadata(e){this.emit(x.le.METADATA,{trackType:"video",codec:e.codec})}_emitAudioMetadata(e){this.emit(x.le.METADATA,{trackType:"audio",codec:e.codec,sampleRate:e.sampleRate,channelCount:e.channelCount,objectType:e.objectType})}_resolveStallStage(e,t,i,s){return e?t?em.NO_PACKET:i?em.NO_DECODE:s?em.NO_RENDER:em.OK:em.OK}_checkStall(){var e,t,i,s,r,o,a;if(null===(e=this.stateManager)||void 0===e?void 0:e.get("paused"))return;let n={timestamp:performance.now(),receivedVideoPacketCount:this._receivedVideoPacketCount,decodeOutputFrames:(null===(t=this._mediaCodec)||void 0===t?void 0:t.decodeOutputFrames)||0,renderFrames:(null===(i=this._mediaCodec)||void 0===i?void 0:i.renderFrames)||0,receivedAudioChunkCount:this._receivedAudioChunkCount,decodeOutputChunks:(null===(s=this._mediaCodec)||void 0===s?void 0:s.decodeOutputChunks)||0,renderChunks:(null===(r=this._mediaCodec)||void 0===r?void 0:r.renderChunks)||0};if(this._stallCheckHistory.push(n),this._stallCheckHistory.length>=3){let e=this._stallCheckHistory[0],t=this._stallCheckHistory[this._stallCheckHistory.length-1],i=e.receivedVideoPacketCount===t.receivedVideoPacketCount,s=e.renderFrames===t.renderFrames;if(i||s){let r=this._resolveStallStage(!0,i,e.decodeOutputFrames===t.decodeOutputFrames,s),n=this._resolveStallStage(!!this._audioMeta,e.receivedAudioChunkCount===t.receivedAudioChunkCount,e.decodeOutputChunks===t.decodeOutputChunks,e.renderChunks===t.renderChunks),d=t.timestamp-e.timestamp;(null===(o=this._mediaCodec)||void 0===o?void 0:o._audioDriverRunning)===!1&&r!==em.NO_PACKET?this._logger.warn("skip 3004: audio clock never started (ctx suspended / autoplay pending), video:",r,"audio:",n,"stallTime:",d):(this._logger.log("stall, fire error, call RtmWebTsLoaderWorker cancel, video:",r,"audio:",n,"stallTime:",d),null===(a=this._mediaLoader)||void 0===a||a.cancel(),this.emit(x.le.FLVERROR,new V.Z(V.t.DECODE_VIDEO_DODECODE_ERROR,`Video/audio stalled for more than 4s, video: ${r}, audio: ${n}`)))}}this._stallCheckHistory=this._stallCheckHistory.slice(-e_)}constructor(e,t){super(e,t),(0,s._)(this,"_logger",new o.ZP("RtmWebTs")),(0,s._)(this,"_mediaCodec",null),(0,s._)(this,"_videoMeta",void 0),(0,s._)(this,"_audioMeta",void 0),(0,s._)(this,"_metaDataAdded",!1),(0,s._)(this,"_metaTimer",void 0),(0,s._)(this,"_seiService",void 0),(0,s._)(this,"_mediaLoader",null),(0,s._)(this,"_receivedVideoPacketCount",0),(0,s._)(this,"_lastReceivedVideoTimeSec",0),(0,s._)(this,"_receivedAudioChunkCount",0),(0,s._)(this,"_lastReceivedAudioTimeSec",0),(0,s._)(this,"_checkPlaybackrateTime",0),(0,s._)(this,"_stallCheckHistory",[]),(0,s._)(this,"_bufferTrimTimer",void 0),(0,s._)(this,"_checkIntervalMs",1e3),(0,s._)(this,"_chaseFrameMinBufferMs",800),(0,s._)(this,"_chaseFrameMaxBufferMs",1e3),(0,s._)(this,"onTimeupdate",()=>{var e,t;null===(t=this._seiService)||void 0===t||t.throw(((null===(e=this.mediaInfo)||void 0===e?void 0:e.VideoFrameTime)||0)/n.Ll);let i=Date.now();if(!(i-this._checkPlaybackrateTime{var t,i;let s=e.meta;this._receivedVideoPacketCount++,this._lastReceivedVideoTimeSec=Math.max(e.pts/1e3,this._lastReceivedVideoTimeSec),!this._metaDataAdded&&!this._videoMeta&&s&&(this._genCodecIns(),this._videoMeta=s,this._audioMeta?(clearTimeout(this._metaTimer),this._metaDataAdded=!0,null===(i=this._mediaCodec)||void 0===i||i.addMetaData(s,this._audioMeta)):this._metaTimer=setTimeout(()=>{var e;this._metaDataAdded=!0,null===(e=this._mediaCodec)||void 0===e||e.addMetaData(s,null)},this._cfg.analyzeDuration),this._emitVideoMetadata(s)),null===(t=this._mediaCodec)||void 0===t||t.appendBuffer([e],[],!0)}),(0,s._)(this,"_onAudioChunk",e=>{var t,i;let s=e.meta;this._receivedAudioChunkCount++,this._lastReceivedAudioTimeSec=e.pts/1e3,!this._metaDataAdded&&!this._audioMeta&&s&&(this._genCodecIns(),this._audioMeta=s,this._videoMeta?(clearTimeout(this._metaTimer),this._metaDataAdded=!0,null===(i=this._mediaCodec)||void 0===i||i.addMetaData(this._videoMeta,s)):this._metaTimer=setTimeout(()=>{var e;this._metaDataAdded=!0,null===(e=this._mediaCodec)||void 0===e||e.addMetaData(null,s)},this._cfg.analyzeDuration),this._emitAudioMetadata(s)),null===(t=this._mediaCodec)||void 0===t||t.appendBuffer([],[e],!0)}),(0,s._)(this,"_onMediaStreamMeta",e=>{var t;if(this._metaDataAdded)return;let{videoMeta:i,audioMeta:s,hasVideo:r,hasAudio:o}=e;if((!!r||!!o)&&(!r||!!i)&&(!o||!!s))clearTimeout(this._metaTimer),this._genCodecIns(),this._videoMeta=i,this._audioMeta=s,i&&this._emitVideoMetadata(i),s&&this._emitAudioMetadata(s),this._metaDataAdded=!0,null===(t=this._mediaCodec)||void 0===t||t.addMetaData(null!=i?i:null,null!=s?s:null),this._logger.log("_onMediaStreamMeta addMetaData",JSON.stringify(e,null,2))}),(0,s._)(this,"_onSEINalu",e=>{var t,i,s;let{nalUnit:r,timestamp:o,timestampUs:a}=e,n=(null===(i=this._videoMeta)||void 0===i?void 0:null===(t=i.codec)||void 0===t?void 0:t.includes("hev1"))||!1,d=new Uint8Array(r);if(d.length<2)return;let l=n?d[0]>>>1&63:31&d[0];if(6===l&&!n||n&&(39===l||40===l)){let e=q.parseSEI(q.removeEPB(d),n),t=void 0!==a?a/1e3:o;null===(s=this._seiService)||void 0===s||s.addSEI({code:e.type,content:e.payload,time:t/1e3,uuid:e.uuid,dts:t})}}),(0,s._)(this,"_handleStats",e=>{var t,i,s,o;let a=!!(null===(t=this.stateManager)||void 0===t?void 0:t.get("paused"));this.emit(x.le.PROP_SPEED,{totalByteSize:e.total.bytesReceived,renderFrames:(null===(i=this._mediaCodec)||void 0===i?void 0:i.renderFrames)||0,recentSpeed:e.total.bitrate});let n=(null===(s=this._mediaCodec)||void 0===s?void 0:s.getDecodeInfo())||{},{video_frames:d=[],audio_chunks:l=[],video_timestamp:h=[],audio_timestamp:u=[]}=n,c=(0,m._)(n,["video_frames","audio_chunks","video_timestamp","audio_timestamp"]),_=(0,r._)({video_frames:[this._receivedVideoPacketCount,...d],audio_chunks:[this._receivedAudioChunkCount,...l],video_timestamp:[this._lastReceivedVideoTimeSec,...h],audio_timestamp:[this._lastReceivedAudioTimeSec,...u],playback_rate:(null===(o=this._mediaCodec)||void 0===o?void 0:o._playbackRate)||0,is_paused:a},c,e);this.emit(x.le.RTM_NETWORK,_),this._checkStall()}),this._seiService=new et(this),this._applyChaseFrameAbConfig(e)}}let ef=[];function eg(){return void 0!==globalThis.__RtmSessionClass}async function ev(e){if(eg())return globalThis.__RtmSessionClass.cancelPreloaded(e);let t=ef.findIndex(t=>t.url===e);return -1!==t&&(ef.splice(t,1),!0)}async function ey(){if(eg()){await globalThis.__RtmSessionClass.clearPreloaded();return}ef.length=0}function eS(){if(!eg()||0===ef.length)return;let e=globalThis.__RtmSessionClass;for(let t of ef)e.preload(t.url,t.options);ef.length=0}class eT extends d.Z{onSeamlessLoad(e){this.onLoad(e)}onWritable(e){if(e.audioWritable&&this.proInstance){var t;this.proInstance.setWritable({audioWritable:e.audioWritable,videoWritable:(null===(t=this.proInstance.getWritable())||void 0===t?void 0:t.videoWritable)||null})}}onLoad(e){this.proInstance?this.onProtocolConfig(e):(super.onLoad(e),this.initProtocol()),this.proInstance.load(e)}initProtocol(){var e;this.logger.log(`init protocol: ${null===(e=this._cfg)||void 0===e?void 0:e.protocol}`),this._cfg.protocol===c.b.RTM?this.proInstance=new J(this._cfg,this.stateManager):this._cfg.protocol===c.b.RTM_WEBTS?this.proInstance=new ep(this._cfg,this.stateManager):this.proInstance=new l.Z(this._cfg,this.stateManager)}onProtocolConfig(e){var t,i,s;let o=e.webTsSDKStream;delete e.webTsSDKStream,o instanceof ReadableStream?(function(e){if(eo)return er.log("sdk load already in progress, cancel prefetched stream"),e.cancel().catch(()=>{}),eo;let t=performance.now();return er.log("start load rtm-session sdk from prefetched stream"),eo=new Response(e).text().then(e=>{er.log("load rtm-session sdk from stream success, spent time:",performance.now()-t,"ms"),ea(e)}).catch(e=>(er.warn("load rtm-session sdk from stream failed, fallback to fetch:",e),eo=null,en()))})(o).catch(()=>{}):e.enablePreloadWebTsSDK&&en().catch(()=>{});let d=this._cfg.protocol;if(e.firstTimeStemp&&!e.seamless&&(null===(t=this.proInstance)||void 0===t||t.resetWorkerInit(e.firstTimeStemp),this.emit(n.Zo.workerinit,{costtime:Date.now()-e.firstTimeStemp,workerReadyTime:this._workerReadyTime})),e.protocol&&d!==e.protocol&&(this._cfg=(0,h.FW)(e)),e.decryption){if((e.ab||this._cfg.ab||{}).decryption){let t=(0,_.BB)(e.decryption.entry);e.awManager=t,this._cfg.awManager=void 0,e.decryption.keyStr!==t.keyStr&&(t.descryptKey(e.decryption.keyStr),t.keyStr=e.decryption.keyStr)}else{if(e.decryption.entry===(null===(i=this._cfg.decryption)||void 0===i?void 0:i.entry)&&this._cfg.awManager)e.awManager=this._cfg.awManager,this._cfg.awManager=void 0;else{let t=(0,u.Q)(e.decryption.entry);e.awManager=new t}e.decryption.keyStr!==(null===(s=this._cfg.decryption)||void 0===s?void 0:s.keyStr)&&e.awManager.descryptKey(e.decryption.keyStr)}}else null===e.decryption&&(e.awManager=void 0);this.logger.log("onProtocolConfig0",e.awManager,this._cfg.awManager);let l=this._cfg=(0,a.R)(this._cfg,e);super.onProtocolConfig(l),this._cfg=(0,h.FW)((0,r._)({},this._cfg,l)),e.awManager&&(this._cfg.awManager=e.awManager),this.logger.log("onProtocolConfig1",e.awManager,this._cfg.awManager);let c=!0;if(d&&d!==this._cfg.protocol&&this.proInstance){let t=this.proInstance.getWritable();this.proInstance._reset(),this.proInstance.destroy(),super.onProtocolConfig(l),this.initProtocol(),!e.writeable&&(t.audioWritable||t.videoWritable)&&(this.logger.log("writeable reuse"),this.proInstance.setWritable(t)),c=!1}!this.proInstance&&(this.initProtocol(),c=!1),c&&this.proInstance.updateConfig(this._cfg)}onPlayerDestroy(e){super.onPlayerDestroy(e),e.isDestroy&&(this._cfg=(0,h.FW)())}onReady(){this.emit(n.Zo.MESSAGE_EVENT_ISREADY)}onReset(){delete this._cfg.abr}onRtmWebTsPreload(e){!function(e,t){if(eg()){globalThis.__RtmSessionClass.preload(e,t);return}let i=ef.findIndex(t=>t.url===e);-1!==i&&ef.splice(i,1),ef.push({url:e,options:t}),en().then(eS).catch(()=>{})}(e.url,e.options)}onRtmWebTsCancelPreloaded(e){ev(e.url)}onRtmWebTsClearPreloaded(){ey()}constructor(){super(),(0,s._)(this,"isPlayerWorker",!0),(0,s._)(this,"logger",new o.ZP("PlayerWorker")),(0,s._)(this,"proInstance",void 0),(0,s._)(this,"_cfg",(0,h.FW)()),(0,s._)(this,"_workerReadyTime",Date.now()),this.on(n.Zo.RTM_WEBTS_PRELOAD,this.onRtmWebTsPreload),this.on(n.Zo.RTM_WEBTS_CANCEL_PRELOADED,this.onRtmWebTsCancelPreloaded),this.on(n.Zo.RTM_WEBTS_CLEAR_PRELOADED,this.onRtmWebTsClearPreloaded)}}new eT}},a={};function n(e){var t=a[e];if(void 0!==t)return t.exports;var i=a[e]={exports:{}};return o[e](i,i.exports,n),i.exports}n.m=o,n.x=function(){var e=n.O(void 0,["74792","22418"],function(){return n("611363")});return e=n.O(e)},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,{a:t}),t},n.d=function(e,t){for(var i in t)n.o(t,i)&&!n.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},n.f={},n.e=function(e){return Promise.all(Object.keys(n.f).reduce(function(t,i){return n.f[i](e,t),t},[]))},n.u=function(e){return"74792"===e?"polyfill.4ba7de64.js":"async/"+e+".cc6d9828.js"},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},e=[],n.O=function(t,i,s,r){if(i){r=r||0;for(var o=e.length;o>0&&e[o-1][2]>r;o--)e[o]=e[o-1];e[o]=[i,s,r];return}for(var a=1/0,o=0;o=r)&&Object.keys(n.O).every(function(e){return n.O[e](i[l])})?i.splice(l--,1):(d=!1,rt)throw a.message="Loading chunk ".concat(o," from ").concat(u," failed after ").concat(t,' retries: "').concat(a.message,'"'),"function"==typeof e.onFail&&e.onFail(p),a;var f=e.test;if(f){if("string"==typeof f){var g=new RegExp(f);f=function(e){return g.test(e)}}if("function"!=typeof f||!f(c))throw a}if(e.domain&&e.domain.length>0&&-1===e.domain.indexOf(_))throw a;return"function"==typeof e.onRetry&&e.onRetry(p),s(o).then(function(t){if("function"==typeof e.onSuccess){var s,r=m(h);(null!==(s=i[o])&&void 0!==s?s:{}).existRetryTimes===h&&e.onSuccess(r)}return t})})},n.l=h}catch(e){}}()}(),n.rv=function(){return"1.0.0-canary-8758c59-20240816041638"},t=n.x,n.x=function(){return Promise.all([n.e("74792"),n.e("22418")]).then(t)},n.b=self.location+"/../../",i={13508:1},n.f.i=function(e,t){!i[e]&&importScripts(n.p+n.u(e))},r=(s=self.webpackChunkdouyin_web=self.webpackChunkdouyin_web||[]).push.bind(s),s.push=function(e){var t=e[0],s=e[1],o=e[2];for(var a in s)n.o(s,a)&&(n.m[a]=s[a]);for(o&&o(n);t.length;)i[t.pop()]=1;r(e)},n.ruid="bundler=rspack@1.0.0-canary-8758c59-20240816041638",n.x()}();