var m=Object.defineProperty;var f=(i,a,e)=>a in i?m(i,a,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[a]=e;var o=(i,a,e)=>f(i,typeof a!="symbol"?a+"":a,e);import{m as p,C as w,f as l,R as C,j as g,k as b}from"./index-CBxrqwze.js";var y=Object.defineProperty,T=Object.getOwnPropertyDescriptor,u=(i,a,e,t)=>{for(var r=t>1?void 0:t?T(a,e):a,s=i.length-1,n;s>=0;s--)(n=i[s])&&(r=(t?n(a,e,r):n(r))||r);return t&&r&&y(a,e,r),r};let h=class extends p(w){constructor(){super(...arguments);o(this,"cameraVideo");o(this,"whepUrl","");o(this,"sessionUrl","");o(this,"pc",null);o(this,"restartTimeout",null);o(this,"offerData",null);o(this,"queuedCandidates",[])}unquoteCredential(e){return JSON.parse(`"${e}"`)}linkToIceServers(e){return e!==null?e.split(", ").map(t=>{const r=t.match(/^<(.+?)>; rel="ice-server"(; username="(.*?)"; credential="(.*?)"; credential-type="password")?/i),s={urls:[r[1]]};return r[3]!==void 0&&(s.username=this.unquoteCredential(r[3]),s.credential=this.unquoteCredential(r[4]),s.credentialType="password"),s}):[]}parseOffer(e){const t={iceUfrag:"",icePwd:"",medias:[]};for(const r of e.split(`\r
`))r.startsWith("m=")?t.medias.push(r.slice(2)):t.iceUfrag===""&&r.startsWith("a=ice-ufrag:")?t.iceUfrag=r.slice(12):t.icePwd===""&&r.startsWith("a=ice-pwd:")&&(t.icePwd=r.slice(10));return t}generateSdpFragment(e,t){const r={};for(const d of t){const c=d.sdpMLineIndex;r[c]===void 0&&(r[c]=[]),r[c].push(d)}let s="a=ice-ufrag:"+e.iceUfrag+`\r
a=ice-pwd:`+e.icePwd+`\r
`,n=0;for(const d of e.medias){if(r[n]!==void 0){s+="m="+d+`\r
a=mid:`+n+`\r
`;for(const c of r[n])s+="a="+c.candidate+`\r
`}n++}return s}async loadStream(){try{this.updateStatus("connecting");const e=await fetch(this.whepUrl,{method:"OPTIONS"}),t={iceServers:this.linkToIceServers(e.headers.get("Link")),sdpSemantics:"unified-plan"};this.pc=new RTCPeerConnection(t),this.pc.addTransceiver("video",{direction:"recvonly"}),this.pc.onicecandidate=s=>{this.restartTimeout===null&&s.candidate!==null&&(this.sessionUrl===""?this.queuedCandidates.push(s.candidate):this.sendLocalCandidates([s.candidate]))},this.pc.oniceconnectionstatechange=()=>{var s;this.restartTimeout===null&&((s=this.pc)==null?void 0:s.iceConnectionState)==="disconnected"&&(l.warn("[WebrtcMediamtxCamera] peer connection disconnected"),this.onError())},this.pc.ontrack=s=>{this.cameraVideo.srcObject=s.streams[0]};const r=await this.pc.createOffer();this.offerData=this.parseOffer(r.sdp??""),this.pc.setLocalDescription(r),this.sendOffer(r)}catch(e){l.error(`[WebrtcMediamtxCamera] error on loadStream "${this.camera.name}"`,e),this.onError()}}onError(){this.updateStatus("error"),this.restartTimeout===null&&(this.pc!==null&&(this.pc.close(),this.pc=null),this.restartTimeout=window.setTimeout(()=>{this.restartTimeout=null,this.loadStream()},2e3),this.sessionUrl&&(fetch(this.sessionUrl,{method:"DELETE"}),this.sessionUrl=""),this.queuedCandidates=[])}async sendLocalCandidates(e){try{const t=await fetch(this.sessionUrl,{method:"PATCH",headers:{"Content-Type":"application/trickle-ice-sdpfrag","If-Match":"*"},body:this.generateSdpFragment(this.offerData,e)});switch(t.status){case 204:break;case 404:throw new Error("stream not found");default:throw new Error(`bad status code ${t.status}`)}}catch(t){l.error("[WebrtcMediamtxCamera] error on sendLocalCandidates",t),this.onError()}}onRemoteAnswer(e){var t;this.restartTimeout===null&&((t=this.pc)==null||t.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})),this.queuedCandidates.length!==0&&(this.sendLocalCandidates(this.queuedCandidates),this.queuedCandidates=[]))}async sendOffer(e){try{const t=await fetch(this.whepUrl,{method:"POST",headers:{"Content-Type":"application/sdp"},body:e.sdp});switch(t.status){case 201:break;case 404:throw new Error("stream not found");default:throw new Error(`bad status code ${t.status}`)}this.sessionUrl=new URL(t.headers.get("location")??"",this.baseUrl).toString();const r=await t.text();this.onRemoteAnswer(r)}catch(t){l.error("[WebrtcMediamtxCamera] error on sendOffer",t),this.onError()}}get baseUrl(){const e=this.buildAbsoluteUrl(this.camera.stream_url||"");return e.pathname.endsWith("/")||(e.pathname+="/"),e}startPlayback(){this.whepUrl=new URL("whep",this.baseUrl).toString(),this.loadStream()}stopPlayback(){this.updateStatus("disconnected"),this.sessionUrl="",this.queuedCandidates=[],this.restartTimeout&&(clearTimeout(this.restartTimeout),this.restartTimeout=null),this.pc&&(this.pc.close(),this.pc=null),this.cameraVideo.src="",this.cameraVideo.srcObject=null}};u([C("streamingElement")],h.prototype,"cameraVideo",2);h=u([g({})],h);var S=function(){var a=this,e=a._self._c;return a._self._setupProxy,e("video",{ref:"streamingElement",style:a.cameraStyle,attrs:{autoplay:"",playsinline:"",muted:"",crossorigin:a.crossorigin},domProps:{muted:!0},on:{play:function(t){return a.updateStatus("connected")},error:function(t){return a.updateStatus("error")}}})},U=[],v=b(h,S,U,!1,null,null);const x=v.exports;export{x as default};
