feat(cameras): pan/tilt page — mosquitto + neolink mqtt-rtsp + cam.ginnoir.com/ptz
Deploy Caddyfile to valhalla / deploy (push) Failing after 10s
Deploy Caddyfile to valhalla / deploy (push) Failing after 10s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d6a331465e
commit
b78a8d51ad
10 files changed
+1014
-1
No files matched your search
@@ -0,0 +1,198 @@
|
||||
<!doctype html>
|
||||
<!-- Seeded to /config/caddy/site/cam-ptz/ on valhalla; served at cam.ginnoir.com/ptz/
|
||||
behind Authentik. Video = Frigate's go2rtc MSE websocket; PTZ = MQTT over
|
||||
wss://cam.ginnoir.com/mqtt -> mosquitto -> neolink -> E1 (Baichuan). -->
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<title>E1 Pan/Tilt</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f4f4f5; --panel: #ffffff; --text: #18181b; --muted: #71717a;
|
||||
--btn: #e4e4e7; --btn-active: #2563eb; --btn-active-text: #fff; --border: #d4d4d8;
|
||||
--ok: #16a34a; --bad: #dc2626;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-theme="light"]) {
|
||||
--bg: #09090b; --panel: #18181b; --text: #f4f4f5; --muted: #a1a1aa;
|
||||
--btn: #27272a; --btn-active: #3b82f6; --btn-active-text: #fff; --border: #3f3f46;
|
||||
}
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0; background: var(--bg); color: var(--text);
|
||||
font: 15px/1.4 system-ui, -apple-system, "Segoe UI", sans-serif;
|
||||
-webkit-user-select: none; user-select: none; -webkit-touch-callout: none;
|
||||
}
|
||||
main { max-width: 1100px; margin: 0 auto; padding: 12px 16px 24px; }
|
||||
header { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 10px; }
|
||||
h1 { font-size: 17px; margin: 0; }
|
||||
header a { color: var(--muted); font-size: 13px; }
|
||||
.status { font-size: 13px; color: var(--muted); display: flex; align-items: center; gap: 6px; }
|
||||
.dot { width: 9px; height: 9px; border-radius: 50%; background: var(--bad); }
|
||||
.dot.on { background: var(--ok); }
|
||||
.layout { display: grid; gap: 14px; grid-template-columns: 1fr; }
|
||||
@media (min-width: 860px) { .layout { grid-template-columns: 1fr 280px; } }
|
||||
.video { background: #000; border-radius: 10px; overflow: hidden; aspect-ratio: 16 / 9; }
|
||||
.video video { width: 100%; height: 100%; display: block; object-fit: contain; }
|
||||
.panel { background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 14px; display: grid; gap: 16px; align-content: start; }
|
||||
.pad { display: grid; grid-template-columns: repeat(3, 64px); grid-template-rows: repeat(3, 64px); gap: 8px; justify-content: center; }
|
||||
button {
|
||||
font: inherit; color: var(--text); background: var(--btn); border: 1px solid var(--border);
|
||||
border-radius: 10px; cursor: pointer; touch-action: none;
|
||||
}
|
||||
button:active, button.held { background: var(--btn-active); color: var(--btn-active-text); border-color: var(--btn-active); }
|
||||
.pad button { font-size: 22px; }
|
||||
.zoom { display: flex; gap: 8px; justify-content: center; }
|
||||
.zoom button { width: 100px; height: 44px; }
|
||||
label { font-size: 13px; color: var(--muted); display: grid; gap: 6px; }
|
||||
input[type=range] { width: 100%; }
|
||||
h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .04em; color: var(--muted); margin: 0 0 8px; }
|
||||
.presets { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.presets button { padding: 8px 12px; }
|
||||
.presets .empty { color: var(--muted); font-size: 13px; }
|
||||
.save { display: flex; gap: 8px; margin-top: 10px; }
|
||||
.save input { flex: 1; min-width: 0; font: inherit; padding: 8px; border-radius: 8px; border: 1px solid var(--border); background: var(--bg); color: var(--text); -webkit-user-select: text; user-select: text; }
|
||||
.save button { padding: 8px 12px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<header>
|
||||
<h1>E1 Pan/Tilt</h1>
|
||||
<div class="status"><span class="dot" id="dot"></span><span id="state">connecting…</span></div>
|
||||
<a href="/">Frigate</a>
|
||||
</header>
|
||||
<div class="layout">
|
||||
<div class="video"><cam-video id="video"></cam-video></div>
|
||||
<div class="panel">
|
||||
<div class="pad" aria-label="Pan and tilt">
|
||||
<span></span><button data-dir="up" aria-label="Tilt up">▲</button><span></span>
|
||||
<button data-dir="left" aria-label="Pan left">◀</button><span></span><button data-dir="right" aria-label="Pan right">▶</button>
|
||||
<span></span><button data-dir="down" aria-label="Tilt down">▼</button><span></span>
|
||||
</div>
|
||||
<div class="zoom">
|
||||
<button data-dir="out" aria-label="Zoom out">− Zoom</button>
|
||||
<button data-dir="in" aria-label="Zoom in">+ Zoom</button>
|
||||
</div>
|
||||
<label>Speed <input type="range" id="speed" min="8" max="64" step="4" value="32"></label>
|
||||
<section>
|
||||
<h2>Presets</h2>
|
||||
<div class="presets" id="presets"><span class="empty">loading…</span></div>
|
||||
<div class="save">
|
||||
<input id="presetName" placeholder="Save current view as…" maxlength="31">
|
||||
<button id="saveBtn">Save</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<script src="mqtt.min.js"></script>
|
||||
<script type="module">
|
||||
import {VideoRTC} from './video-rtc.js';
|
||||
|
||||
// --- Video: Frigate's go2rtc restream over MSE (WebRTC needs :8555 ICE, not exposed) ---
|
||||
class CamVideo extends VideoRTC {}
|
||||
customElements.define('cam-video', CamVideo);
|
||||
const video = document.getElementById('video');
|
||||
video.mode = 'mse';
|
||||
video.background = true;
|
||||
video.src = `wss://${location.host}/live/mse/api/ws?src=e1`;
|
||||
|
||||
// --- MQTT ---
|
||||
const BASE = 'neolink/e1';
|
||||
const dot = document.getElementById('dot');
|
||||
const state = document.getElementById('state');
|
||||
const client = mqtt.connect(`wss://${location.host}/mqtt`, {reconnectPeriod: 2000, clean: true});
|
||||
let camOnline = false;
|
||||
|
||||
function setStatus() {
|
||||
const ok = client.connected && camOnline;
|
||||
dot.classList.toggle('on', ok);
|
||||
state.textContent = !client.connected ? 'broker offline' : camOnline ? 'ready' : 'camera offline';
|
||||
}
|
||||
client.on('connect', () => {
|
||||
client.subscribe([`neolink/status`, `${BASE}/status/#`]);
|
||||
client.publish(`${BASE}/query/ptz/preset`, '');
|
||||
setStatus();
|
||||
});
|
||||
client.on('close', setStatus);
|
||||
client.on('message', (topic, payload) => {
|
||||
const msg = payload.toString();
|
||||
if (topic === 'neolink/status' || topic === `${BASE}/status`) {
|
||||
camOnline = msg.trim() !== 'offline' && msg.trim() !== 'disconnected';
|
||||
setStatus();
|
||||
} else if (topic === `${BASE}/status/ptz/preset`) {
|
||||
renderPresets(msg);
|
||||
}
|
||||
});
|
||||
|
||||
// --- Move: tap = one step, hold = repeat while pressed ---
|
||||
const speed = document.getElementById('speed');
|
||||
const REPEAT_MS = 350;
|
||||
function move(dir) {
|
||||
if (client.connected) client.publish(`${BASE}/control/ptz`, `${dir} ${speed.value}`);
|
||||
}
|
||||
document.querySelectorAll('button[data-dir]').forEach(btn => {
|
||||
let timer = null;
|
||||
const stop = () => { clearInterval(timer); timer = null; btn.classList.remove('held'); };
|
||||
btn.addEventListener('pointerdown', e => {
|
||||
e.preventDefault();
|
||||
btn.setPointerCapture(e.pointerId);
|
||||
btn.classList.add('held');
|
||||
move(btn.dataset.dir);
|
||||
timer = setInterval(() => move(btn.dataset.dir), REPEAT_MS);
|
||||
});
|
||||
['pointerup', 'pointercancel', 'lostpointercapture'].forEach(ev => btn.addEventListener(ev, stop));
|
||||
});
|
||||
const keys = {ArrowUp: 'up', ArrowDown: 'down', ArrowLeft: 'left', ArrowRight: 'right', '+': 'in', '=': 'in', '-': 'out'};
|
||||
document.addEventListener('keydown', e => {
|
||||
if (e.target.tagName === 'INPUT') return;
|
||||
if (keys[e.key]) { e.preventDefault(); move(keys[e.key]); }
|
||||
});
|
||||
|
||||
// --- Presets (neolink returns the camera's XML preset list) ---
|
||||
const presetsEl = document.getElementById('presets');
|
||||
let presets = [];
|
||||
function renderPresets(xml) {
|
||||
const doc = new DOMParser().parseFromString(xml, 'application/xml');
|
||||
presets = [...doc.getElementsByTagName('preset')]
|
||||
.map(p => ({
|
||||
id: p.getElementsByTagName('id')[0]?.textContent,
|
||||
name: p.getElementsByTagName('name')[0]?.textContent,
|
||||
enable: p.getElementsByTagName('enable')[0]?.textContent,
|
||||
}))
|
||||
.filter(p => p.id != null && p.name && p.enable !== '0');
|
||||
presetsEl.replaceChildren();
|
||||
if (!presets.length) {
|
||||
const s = document.createElement('span');
|
||||
s.className = 'empty';
|
||||
s.textContent = 'No presets yet';
|
||||
presetsEl.append(s);
|
||||
return;
|
||||
}
|
||||
for (const p of presets) {
|
||||
const b = document.createElement('button');
|
||||
b.textContent = p.name;
|
||||
b.addEventListener('click', () => client.publish(`${BASE}/control/ptz/preset`, p.id));
|
||||
presetsEl.append(b);
|
||||
}
|
||||
}
|
||||
setTimeout(() => { if (presetsEl.querySelector('.empty')?.textContent === 'loading…') renderPresets('<x/>'); }, 8000);
|
||||
|
||||
document.getElementById('saveBtn').addEventListener('click', () => {
|
||||
const input = document.getElementById('presetName');
|
||||
const name = input.value.trim().replace(/\s+/g, '_');
|
||||
if (!name) return;
|
||||
const used = new Set(presets.map(p => Number(p.id)));
|
||||
let id = 0;
|
||||
while (used.has(id)) id++;
|
||||
client.publish(`${BASE}/control/ptz/assign`, `${id} ${name}`);
|
||||
input.value = '';
|
||||
setTimeout(() => client.publish(`${BASE}/query/ptz/preset`, ''), 1500);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Vendored
+19
@@ -0,0 +1,19 @@
|
||||
"use strict";var mqtt=(()=>{var as=Object.defineProperty;var Yb=Object.getOwnPropertyDescriptor;var Jb=Object.getOwnPropertyNames;var Xb=Object.prototype.hasOwnProperty;var ze=(t,e)=>()=>(t&&(e=t(t=0)),e);var j=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Kr=(t,e)=>{for(var r in e)as(t,r,{get:e[r],enumerable:!0})},Zb=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Jb(e))!Xb.call(t,i)&&i!==r&&as(t,i,{get:()=>e[i],enumerable:!(n=Yb(e,i))||n.enumerable});return t};var me=t=>Zb(as({},"__esModule",{value:!0}),t);var A=ze(()=>{});var N={};Kr(N,{_debugEnd:()=>Qc,_debugProcess:()=>Kc,_events:()=>hf,_eventsCount:()=>df,_exiting:()=>Oc,_fatalExceptions:()=>Hc,_getActiveHandles:()=>Bc,_getActiveRequests:()=>Cc,_kill:()=>Nc,_linkedBinding:()=>Tc,_maxListeners:()=>ff,_preload_modules:()=>uf,_rawDebug:()=>Ic,_startProfilerIdleNotifier:()=>Yc,_stopProfilerIdleNotifier:()=>Jc,_tickCallback:()=>zc,abort:()=>tf,addListener:()=>pf,allowedNodeEnvironmentFlags:()=>Fc,arch:()=>fc,argv:()=>pc,argv0:()=>af,assert:()=>Wc,binding:()=>mc,browser:()=>Ac,chdir:()=>Sc,config:()=>Rc,cpuUsage:()=>Ri,cwd:()=>vc,debugPort:()=>sf,default:()=>Ef,dlopen:()=>kc,domain:()=>Pc,emit:()=>mf,emitWarning:()=>wc,env:()=>dc,execArgv:()=>yc,execPath:()=>of,exit:()=>Dc,features:()=>$c,hasUncaughtExceptionCaptureCallback:()=>Gc,hrtime:()=>Oi,kill:()=>Uc,listeners:()=>Sf,memoryUsage:()=>Lc,moduleLoadList:()=>xc,nextTick:()=>uc,off:()=>gf,on:()=>Nt,once:()=>yf,openStdin:()=>jc,pid:()=>rf,platform:()=>hc,ppid:()=>nf,prependListener:()=>_f,prependOnceListener:()=>vf,reallyExit:()=>Mc,release:()=>Ec,removeAllListeners:()=>wf,removeListener:()=>bf,resourceUsage:()=>qc,setSourceMapsEnabled:()=>lf,setUncaughtExceptionCaptureCallback:()=>Vc,stderr:()=>Zc,stdin:()=>ef,stdout:()=>Xc,title:()=>cc,umask:()=>_c,uptime:()=>cf,version:()=>gc,versions:()=>bc});function cs(t){throw new Error("Node.js process "+t+" is not supported by JSPM core outside of Node.js")}function ew(){!Qr||!wr||(Qr=!1,wr.length?Mt=wr.concat(Mt):Pi=-1,Mt.length&&ac())}function ac(){if(!Qr){var t=setTimeout(ew,0);Qr=!0;for(var e=Mt.length;e;){for(wr=Mt,Mt=[];++Pi<e;)wr&&wr[Pi].run();Pi=-1,e=Mt.length}wr=null,Qr=!1,clearTimeout(t)}}function uc(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];Mt.push(new lc(t,e)),Mt.length===1&&!Qr&&setTimeout(ac,0)}function lc(t,e){this.fun=t,this.array=e}function Ue(){}function Tc(t){cs("_linkedBinding")}function kc(t){cs("dlopen")}function Cc(){return[]}function Bc(){return[]}function Wc(t,e){if(!t)throw new Error(e||"assertion error")}function Gc(){return!1}function cf(){return Jt.now()/1e3}function Oi(t){var e=Math.floor((Date.now()-Jt.now())*.001),r=Jt.now()*.001,n=Math.floor(r)+e,i=Math.floor(r%1*1e9);return t&&(n=n-t[0],i=i-t[1],i<0&&(n--,i+=ls)),[n,i]}function Nt(){return Ef}function Sf(t){return[]}var Mt,Qr,wr,Pi,cc,fc,hc,dc,pc,yc,gc,bc,wc,mc,_c,vc,Sc,Ec,Ac,Ic,xc,Pc,Oc,Rc,Mc,Nc,Ri,qc,Lc,Uc,Dc,jc,Fc,$c,Hc,Vc,zc,Kc,Qc,Yc,Jc,Xc,Zc,ef,tf,rf,nf,of,sf,af,uf,lf,Jt,us,ls,ff,hf,df,pf,yf,gf,bf,wf,mf,_f,vf,Ef,Af=ze(()=>{A();x();I();Mt=[],Qr=!1,Pi=-1;lc.prototype.run=function(){this.fun.apply(null,this.array)};cc="browser",fc="x64",hc="browser",dc={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},pc=["/usr/bin/node"],yc=[],gc="v16.8.0",bc={},wc=function(t,e){console.warn((e?e+": ":"")+t)},mc=function(t){cs("binding")},_c=function(t){return 0},vc=function(){return"/"},Sc=function(t){},Ec={name:"node",sourceUrl:"",headersUrl:"",libUrl:""};Ac=!0,Ic=Ue,xc=[];Pc={},Oc=!1,Rc={};Mc=Ue,Nc=Ue,Ri=function(){return{}},qc=Ri,Lc=Ri,Uc=Ue,Dc=Ue,jc=Ue,Fc={};$c={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Hc=Ue,Vc=Ue;zc=Ue,Kc=Ue,Qc=Ue,Yc=Ue,Jc=Ue,Xc=void 0,Zc=void 0,ef=void 0,tf=Ue,rf=2,nf=1,of="/bin/usr/node",sf=9229,af="node",uf=[],lf=Ue,Jt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0};Jt.now===void 0&&(us=Date.now(),Jt.timing&&Jt.timing.navigationStart&&(us=Jt.timing.navigationStart),Jt.now=()=>Date.now()-us);ls=1e9;Oi.bigint=function(t){var e=Oi(t);return typeof BigInt>"u"?e[0]*ls+e[1]:BigInt(e[0]*ls)+BigInt(e[1])};ff=10,hf={},df=0;pf=Nt,yf=Nt,gf=Nt,bf=Nt,wf=Nt,mf=Ue,_f=Nt,vf=Nt;Ef={version:gc,versions:bc,arch:fc,platform:hc,browser:Ac,release:Ec,_rawDebug:Ic,moduleLoadList:xc,binding:mc,_linkedBinding:Tc,_events:hf,_eventsCount:df,_maxListeners:ff,on:Nt,addListener:pf,once:yf,off:gf,removeListener:bf,removeAllListeners:wf,emit:mf,prependListener:_f,prependOnceListener:vf,listeners:Sf,domain:Pc,_exiting:Oc,config:Rc,dlopen:kc,uptime:cf,_getActiveRequests:Cc,_getActiveHandles:Bc,reallyExit:Mc,_kill:Nc,cpuUsage:Ri,resourceUsage:qc,memoryUsage:Lc,kill:Uc,exit:Dc,openStdin:jc,allowedNodeEnvironmentFlags:Fc,assert:Wc,features:$c,_fatalExceptions:Hc,setUncaughtExceptionCaptureCallback:Vc,hasUncLine truncated
|
||||
`;super(r),this.name="AggregateError",this.errors=e}};Rf.exports={AggregateError:fs,ArrayIsArray(t){return Array.isArray(t)},ArrayPrototypeIncludes(t,e){return t.includes(e)},ArrayPrototypeIndexOf(t,e){return t.indexOf(e)},ArrayPrototypeJoin(t,e){return t.join(e)},ArrayPrototypeMap(t,e){return t.map(e)},ArrayPrototypePop(t,e){return t.pop(e)},ArrayPrototypePush(t,e){return t.push(e)},ArrayPrototypeSlice(t,e,r){return t.slice(e,r)},Error,FunctionPrototypeCall(t,e,...r){return t.call(e,...r)},FunctionPrototypeSymbolHasInstance(t,e){return Function.prototype[Symbol.hasInstance].call(t,e)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(t,e){return Object.defineProperties(t,e)},ObjectDefineProperty(t,e,r){return Object.defineProperty(t,e,r)},ObjectGetOwnPropertyDescriptor(t,e){return Object.getOwnPropertyDescriptor(t,e)},ObjectKeys(t){return Object.keys(t)},ObjectSetPrototypeOf(t,e){return Object.setPrototypeOf(t,e)},Promise,PromisePrototypeCatch(t,e){return t.catch(e)},PromisePrototypeThen(t,e,r){return t.then(e,r)},PromiseReject(t){return Promise.reject(t)},PromiseResolve(t){return Promise.resolve(t)},ReflectApply:Reflect.apply,RegExpPrototypeTest(t,e){return t.test(e)},SafeSet:Set,String,StringPrototypeSlice(t,e,r){return t.slice(e,r)},StringPrototypeToLowerCase(t){return t.toLowerCase()},StringPrototypeToUpperCase(t){return t.toUpperCase()},StringPrototypeTrim(t){return t.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(t,e,r){return t.set(e,r)},Boolean,Uint8Array}});var hs=j((BP,kf)=>{"use strict";A();x();I();kf.exports={format(t,...e){return t.replace(/%([sdifj])/g,function(...[r,n]){let i=e.shift();return n==="f"?i.toFixed(6):n==="j"?JSON.stringify(i):n==="s"&&typeof i=="object"?`${i.constructor!==Object?i.constructor.name:""} {}`.trim():i.toString()})},inspect(t){switch(typeof t){case"string":if(t.includes("'"))if(t.includes('"')){if(!t.includes("`")&&!t.includes("${"))return`\`${t}\``}else return`"${t}"`;return`'${t}'`;case"number":return isNaN(t)?"NaN":Object.is(t,-0)?String(t):t;case"bigint":return`${String(t)}n`;case"boolean":case"undefined":return String(t);case"object":return"{}"}}}});var De=j((jP,Mf)=>{"use strict";A();x();I();var{format:ow,inspect:Ci}=hs(),{AggregateError:sw}=Ee(),aw=globalThis.AggregateError||sw,uw=Symbol("kIsNodeError"),lw=["string","function","number","object","Function","Object","boolean","bigint","symbol"],cw=/^([A-Z][a-z0-9]*)+$/,fw="__node_internal_",Bi={};function _r(t,e){if(!t)throw new Bi.ERR_INTERNAL_ASSERTION(e)}function Cf(t){let e="",r=t.length,n=t[0]==="-"?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function hw(t,e,r){if(typeof e=="function")return _r(e.length<=r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${e.length}).`),e(...r);let n=(e.match(/%[dfijoOs]/g)||[]).length;return _r(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:ow(e,...r)}function Le(t,e,r){r||(r=Error);class n extends r{constructor(...s){super(hw(t,e,s))}toString(){return`${this.name} [${t}]: ${this.message}`}}Object.defineProperties(n.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${t}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),n.prototype.code=t,n.prototype[uw]=!0,Bi[t]=n}function Bf(t){let e=fw+t.name;return Object.defineProperty(t,"name",{value:e}),t}function dw(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new aw([e,t],e.message);return r.code=e.code,r}return t||e}var ds=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new Bi.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};Le("ERR_ASSERTION","%s",Error);Le("ERR_INVALID_ARG_TYPE",(t,e,r)=>{_r(typeof t=="string","'name' must be a string"),Array.isArray(e)||(e=[e]);let n="The ";t.endsWith(" argument")?n+=`${t} `:n+=`"${t}" ${t.includes(".")?"property":"argument"} `,n+="must be ";let i=[],s=[],o=[];for(let c of e)_r(typeof c=="string","All expected entries have to be of type string"),lw.includes(c)?i.push(c.toLowerCase()):cw.test(c)?s.push(c):(_r(c!=="object",'The value "object" should be written as "Object"'),o.push(c));if(s.length>0){let c=i.indexOf("object");c!==-1&&(i.splice(i,c,1),s.push("Object"))}if(i.length>0){switch(i.length){case 1:n+=`of type ${i[0]}`;break;case 2:n+=`one of type ${i[0]} or ${i[1]}`;break;default:{leLine truncated
|
||||
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}si.exports=cA,si.exports.__esModule=!0,si.exports.default=si.exports});var lg=j((ED,ai)=>{A();x();I();var fA=ng(),hA=ig(),dA=ag(),pA=ug();function yA(t,e){return fA(t)||hA(t,e)||dA(t,e)||pA()}ai.exports=yA,ai.exports.__esModule=!0,ai.exports.default=ai.exports});var fg=j((RD,ui)=>{A();x();I();function cg(t,e,r,n,i,s,o){try{var a=t[s](o),c=a.value}catch(f){return void r(f)}a.done?e(c):Promise.resolve(c).then(n,i)}function gA(t){return function(){var e=this,r=arguments;return new Promise(function(n,i){var s=t.apply(e,r);function o(c){cg(s,n,i,o,a,"next",c)}function a(c){cg(s,n,i,o,a,"throw",c)}o(void 0)})}}ui.exports=gA,ui.exports.__esModule=!0,ui.exports.default=ui.exports});var Ru=j((LD,li)=>{A();x();I();function bA(t,e){this.v=t,this.k=e}li.exports=bA,li.exports.__esModule=!0,li.exports.default=li.exports});var ku=j((HD,$t)=>{A();x();I();function Wo(t,e,r,n){var i=Object.defineProperty;try{i({},"",{})}catch{i=0}$t.exports=Wo=function(o,a,c,f){function h(d,m){Wo(o,d,function(g){return this._invoke(d,m,g)})}a?i?i(o,a,{value:c,enumerable:!f,configurable:!f,writable:!f}):o[a]=c:(h("next",0),h("throw",1),h("return",2))},$t.exports.__esModule=!0,$t.exports.default=$t.exports,Wo(t,e,r,n)}$t.exports=Wo,$t.exports.__esModule=!0,$t.exports.default=$t.exports});var Cu=j((JD,Ht)=>{A();x();I();var Rt=ku();function hg(){var t,e,r=typeof Symbol=="function"?Symbol:{},n=r.iterator||"@@iterator",i=r.toStringTag||"@@toStringTag";function s(g,P,S,b){var w=P&&P.prototype instanceof a?P:a,_=Object.create(w.prototype);return Rt(_,"_invoke",(function(R,T,y){var O,v,M,F=0,U=y||[],Q=!1,W={p:0,n:0,v:t,a:H,f:H.bind(t,4),d:function(J,ee){return O=J,v=0,M=t,W.n=ee,o}};function H(z,J){for(v=z,M=J,e=0;!Q&&F&&!ee&&e<U.length;e++){var ee,G=U[e],V=W.p,te=G[2];z>3?(ee=te===J)&&(M=G[(v=G[4])?5:(v=3,3)],G[4]=G[5]=t):G[0]<=V&&((ee=z<2&&V<G[1])?(v=0,W.v=J,W.n=G[1]):V<te&&(ee=z<3||G[0]>J||J>te)&&(G[4]=z,G[5]=J,W.n=te,v=0))}if(ee||z>1)return o;throw Q=!0,J}return function(z,J,ee){if(F>1)throw TypeError("Generator is already running");for(Q&&J===1&&H(J,ee),v=J,M=ee;(e=v<2?t:M)||!Q;){O||(v?v<3?(v>1&&(W.n=-1),H(v,M)):W.n=M:W.v=M);try{if(F=2,O){if(v||(z="next"),e=O[z]){if(!(e=e.call(O,M)))throw TypeError("iterator result is not an object");if(!e.done)return e;M=e.value,v<2&&(v=0)}else v===1&&(e=O.return)&&e.call(O),v<2&&(M=TypeError("The iterator does not provide a '"+z+"' method"),v=1);O=t}else if((e=(Q=W.n<0)?M:R.call(T,W))!==o)break}catch(G){O=t,v=1,M=G}finally{F=1}}return{value:e,done:Q}}})(g,S,b),!0),_}var o={};function a(){}function c(){}function f(){}e=Object.getPrototypeOf;var h=[][n]?e(e([][n]())):(Rt(e={},n,function(){return this}),e),d=f.prototype=a.prototype=Object.create(h);function m(g){return Object.setPrototypeOf?Object.setPrototypeOf(g,f):(g.__proto__=f,Rt(g,i,"GeneratorFunction")),g.prototype=Object.create(d),g}return c.prototype=f,Rt(d,"constructor",f),Rt(f,"constructor",c),c.displayName="GeneratorFunction",Rt(f,i,"GeneratorFunction"),Rt(d),Rt(d,i,"Generator"),Rt(d,n,function(){return this}),Rt(d,"toString",function(){return"[object Generator]"}),(Ht.exports=hg=function(){return{w:s,m}},Ht.exports.__esModule=!0,Ht.exports.default=Ht.exports)()}Ht.exports=hg,Ht.exports.__esModule=!0,Ht.exports.default=Ht.exports});var Nu=j((i3,ci)=>{A();x();I();var wA=Ru(),Bu=ku();function Mu(t,e){function r(i,s,o,a){try{var c=t[i](s),f=c.value;return f instanceof wA?e.resolve(f.v).then(function(h){r("next",h,o,a)},function(h){r("throw",h,o,a)}):e.resolve(f).then(function(h){c.value=h,o(c)},function(h){return r("throw",h,o,a)})}catch(h){a(h)}}var n;this.next||(Bu(Mu.prototype),Bu(Mu.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),Bu(this,"_invoke",function(i,s,o){function a(){return new e(function(c,f){r(i,o,c,f)})}return n=n?n.then(a,a):a()},!0)}ci.exports=Mu,ci.exports.__esModule=!0,ci.exports.default=ci.exports});var qu=j((f3,fi)=>{A();x();I();var mA=Cu(),_A=Nu();function vA(t,e,r,n,i){return new _A(mA().w(t,e,r,n),i||Promise)}fi.exports=vA,fi.exports.__esModule=!0,fi.exports.default=fi.exports});var dg=j((w3,hi)=>{A();x();I();var SA=qu();function EA(t,e,r,n,i){var s=SA(t,e,r,n,i);return s.next().then(function(o){return o.done?o.value:s.next()})}hi.exports=EA,hi.exports.__esModule=!0,hi.exports.default=hi.exports});var pg=j((I3,di)=>{A();x();I();function AA(t){var e=Object(t),r=[];for(var n in e)r.unshift(n);return function i(){for(;r.length;)if((n=r.pop())in e)return i.value=n,i.done=!1,i;return i.done=!0,i}}di.exports=AA,di.exports.__esModule=!0,di.exports.default=di.exports});var yg=j((C3,pi)=>{A();x();I();var IA=Xn().default;function xA(t){if(t!=null){var e=t[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],r=0;if(e)return e.call(t);if(typeof t.next=="function")return t;if(!isNaN(t.length))return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}}}throw new TypeError(IA(t
Line truncated
|
||||
`)>=0)return!1;return!0}function C(k,B){var re;if(k.indent===" ")re=" ";else if(typeof k.indent=="number"&&k.indent>0)re=M.call(Array(k.indent+1)," ");else return null;return{base:re,prev:M.call(Array(B+1),re)}}function q(k,B){if(k.length===0)return"";var re=`
|
||||
`+B.prev+B.base;return re+M.call(k,","+re)+`
|
||||
`+B.prev}function $(k,B){var re=ne(k),ie=[];if(re){ie.length=k.length;for(var oe=0;oe<k.length;oe++)ie[oe]=Re(k,oe)?B(k[oe],k):""}var fe=typeof W=="function"?W(k):[],Qt;if(z){Qt={};for(var br=0;br<fe.length;br++)Qt["$"+fe[br]]=fe[br]}for(var Ye in k)Re(k,Ye)&&(re&&String(Number(Ye))===Ye&&Ye<k.length||z&&Qt["$"+Ye]instanceof Symbol||(O.call(/[^\w$]/,Ye)?ie.push(B(Ye,k)+": "+B(k[Ye],k)):ie.push(Ye+": "+B(k[Ye],k))));if(typeof W=="function")for(var Yt=0;Yt<fe.length;Yt++)ee.call(k,fe[Yt])&&ie.push("["+B(fe[Yt])+"]: "+B(k[fe[Yt]],k));return ie}return Al}function Ox(){if(gb)return xl;gb=!0;var t=Wr(),e=lb(),r=Px(),n=Sn(),i=t("%WeakMap%",!0),s=t("%Map%",!0),o=e("WeakMap.prototype.get",!0),a=e("WeakMap.prototype.set",!0),c=e("WeakMap.prototype.has",!0),f=e("Map.prototype.get",!0),h=e("Map.prototype.set",!0),d=e("Map.prototype.has",!0),m=function(b,w){for(var _=b,R;(R=_.next)!==null;_=R)if(R.key===w)return _.next=R.next,R.next=b.next,b.next=R,R},g=function(b,w){var _=m(b,w);return _&&_.value},P=function(b,w,_){var R=m(b,w);R?R.value=_:b.next={key:w,next:b.next,value:_}},S=function(b,w){return!!m(b,w)};return xl=function(){var w,_,R,T={assert:function(y){if(!T.has(y))throw new n("Side channel does not contain "+r(y))},get:function(y){if(i&&y&&(typeof y=="object"||typeof y=="function")){if(w)return o(w,y)}else if(s){if(_)return f(_,y)}else if(R)return g(R,y)},has:function(y){if(i&&y&&(typeof y=="object"||typeof y=="function")){if(w)return c(w,y)}else if(s){if(_)return d(_,y)}else if(R)return S(R,y);return!1},set:function(y,O){i&&y&&(typeof y=="object"||typeof y=="function")?(w||(w=new i),a(w,y,O)):s?(_||(_=new s),h(_,y,O)):(R||(R={key:{},next:null}),P(R,y,O))}};return T},xl}function Bl(){if(bb)return Tl;bb=!0;var t=String.prototype.replace,e=/%20/g,r={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Tl={default:r.RFC3986,formatters:{RFC1738:function(n){return t.call(n,e,"+")},RFC3986:function(n){return String(n)}},RFC1738:r.RFC1738,RFC3986:r.RFC3986},Tl}function Eb(){if(wb)return Pl;wb=!0;var t=Bl(),e=Object.prototype.hasOwnProperty,r=Array.isArray,n=(function(){for(var b=[],w=0;w<256;++w)b.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return b})(),i=function(w){for(;w.length>1;){var _=w.pop(),R=_.obj[_.prop];if(r(R)){for(var T=[],y=0;y<R.length;++y)typeof R[y]<"u"&&T.push(R[y]);_.obj[_.prop]=T}}},s=function(w,_){for(var R=_&&_.plainObjects?Object.create(null):{},T=0;T<w.length;++T)typeof w[T]<"u"&&(R[T]=w[T]);return R},o=function b(w,_,R){if(!_)return w;if(typeof _!="object"){if(r(w))w.push(_);else if(w&&typeof w=="object")(R&&(R.plainObjects||R.allowPrototypes)||!e.call(Object.prototype,_))&&(w[_]=!0);else return[w,_];return w}if(!w||typeof w!="object")return[w].concat(_);var T=w;return r(w)&&!r(_)&&(T=s(w,R)),r(w)&&r(_)?(_.forEach(function(y,O){if(e.call(w,O)){var v=w[O];v&&typeof v=="object"&&y&&typeof y=="object"?w[O]=b(v,y,R):w.push(y)}else w[O]=y}),w):Object.keys(_).reduce(function(y,O){var v=_[O];return e.call(y,O)?y[O]=b(y[O],v,R):y[O]=v,y},T)},a=function(w,_){return Object.keys(_).reduce(function(R,T){return R[T]=_[T],R},w)},c=function(b,w,_){var R=b.replace(/\+/g," ");if(_==="iso-8859-1")return R.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(R)}catch{return R}},f=1024,h=function(w,_,R,T,y){if(w.length===0)return w;var O=w;if(typeof w=="symbol"?O=Symbol.prototype.toString.call(w):typeof w!="string"&&(O=String(w)),R==="iso-8859-1")return escape(O).replace(/%u[0-9a-f]{4}/gi,function(H){return"%26%23"+parseInt(H.slice(2),16)+"%3B"});for(var v="",M=0;M<O.length;M+=f){for(var F=O.length>=f?O.slice(M,M+f):O,U=[],Q=0;Q<F.length;++Q){var W=F.charCodeAt(Q);if(W===45||W===46||W===95||W===126||W>=48&&W<=57||W>=65&&W<=90||W>=97&&W<=122||y===t.RFC1738&&(W===40||W===41)){U[U.length]=F.charAt(Q);continue}if(W<128){U[U.length]=n[W];continue}if(W<2048){U[U.length]=n[192|W>>6]+n[128|W&63];continue}if(W<55296||W>=57344){U[U.length]=n[224|W>>12]+n[128|W>>6&63]+n[128|W&63];continue}Q+=1,W=65536+((W&1023)<<10|F.charCodeAt(Q)&1023),U[U.length]=n[240|W>>18]+n[128|W>>12&63]+n[128|W>>6&63]+n[128|W&63]}v+=U.join("")}return v},d=function(w){for(var _=[{obj:{o:w},prop:"o"}],R=[],T=0;T<_.length;++T)for(var y=_[T],O=y.obj[y.prop],v=Object.keys(O),M=0;M<v.length;++M){var F=v[M],U=O[F];typeof U=="object"&&U!==null&&R.indexOf(U)===-1&&(_.push({obj:O,prop:F}),R.push(U))}return i(_),w},m=function(w){return Object.prototype.toString.call(w)==="[object RegExp]"},g=function(w){return!w||typeof w!="object"?!1:!!(w.constructor&&w.constructor.isBuffer&&w.constructor.isBuffer(w))},P=function(w,_){return[].concat(w,_)},S=function(w,_){if(r(w)){for(var R=[],T=0;T<w.length;T+=1)R.push(_(w[T]));return R}return _(w)};return Pl={arrayToObject:s,assign:a,combine:P,compact:d,decode:c,encode:h,isBuffer:g,isRegExp:m,maybeMap:S,merge:o},Pl}function Rx(){if(mb)return Ol;mb=!0;var t=Ox(),e=Eb(),r=Bl(),n=Object.prototype.hasOwnProperty,i={brackets:function(b){return b+"[]"},comma:"comma",indices:function(b,w){return b+"["+w+"]"},repeat:fu
Line truncated
|
||||
`," "],o=["{","}","|","\\","^","`"].concat(s),a=["'"].concat(o),c=["%","/","?",";","#"].concat(a),f=["/","?","#"],h=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,m=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:!0,"javascript:":!0},P={javascript:!0,"javascript:":!0},S={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=Cx();function w(y,O,v){if(y&&typeof y=="object"&&y instanceof e)return y;var M=new e;return M.parse(y,O,v),M}e.prototype.parse=function(y,O,v){if(typeof y!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof y);var M=y.indexOf("?"),F=M!==-1&&M<y.indexOf("#")?"?":"#",U=y.split(F),Q=/\\/g;U[0]=U[0].replace(Q,"/"),y=U.join(F);var W=y;if(W=W.trim(),!v&&y.split("#").length===1){var H=i.exec(W);if(H)return this.path=W,this.href=W,this.pathname=H[1],H[2]?(this.search=H[2],O?this.query=b.parse(this.search.substr(1)):this.query=this.search.substr(1)):O&&(this.search="",this.query={}),this}var z=r.exec(W);if(z){z=z[0];var J=z.toLowerCase();this.protocol=J,W=W.substr(z.length)}if(v||z||W.match(/^\/\/[^@/]+@[^@/]+/)){var ee=W.substr(0,2)==="//";ee&&!(z&&P[z])&&(W=W.substr(2),this.slashes=!0)}if(!P[z]&&(ee||z&&!S[z])){for(var G=-1,V=0;V<f.length;V++){var te=W.indexOf(f[V]);te!==-1&&(G===-1||te<G)&&(G=te)}var Y,X;G===-1?X=W.lastIndexOf("@"):X=W.lastIndexOf("@",G),X!==-1&&(Y=W.slice(0,X),W=W.slice(X+1),this.auth=decodeURIComponent(Y)),G=-1;for(var V=0;V<c.length;V++){var te=W.indexOf(c[V]);te!==-1&&(G===-1||te<G)&&(G=te)}G===-1&&(G=W.length),this.host=W.slice(0,G),W=W.slice(G),this.parseHost(),this.hostname=this.hostname||"";var ce=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!ce)for(var Z=this.hostname.split(/\./),V=0,ne=Z.length;V<ne;V++){var he=Z[V];if(he&&!he.match(d)){for(var be="",ye=0,Ae=he.length;ye<Ae;ye++)he.charCodeAt(ye)>127?be+="x":be+=he[ye];if(!be.match(d)){var _e=Z.slice(0,V),ve=Z.slice(V+1),Oe=he.match(m);Oe&&(_e.push(Oe[1]),ve.unshift(Oe[2])),ve.length&&(W="/"+ve.join(".")+W),this.hostname=_e.join(".");break}}}this.hostname.length>h?this.hostname="":this.hostname=this.hostname.toLowerCase(),ce||(this.hostname=t.toASCII(this.hostname));var xe=this.port?":"+this.port:"",st=this.hostname||"";this.host=st+xe,this.href+=this.host,ce&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),W[0]!=="/"&&(W="/"+W))}if(!g[J])for(var V=0,ne=a.length;V<ne;V++){var Re=a[V];if(W.indexOf(Re)!==-1){var Ne=encodeURIComponent(Re);Ne===Re&&(Ne=escape(Re)),W=W.split(Re).join(Ne)}}var Ct=W.indexOf("#");Ct!==-1&&(this.hash=W.substr(Ct),W=W.slice(0,Ct));var Bt=W.indexOf("?");if(Bt!==-1?(this.search=W.substr(Bt),this.query=W.substr(Bt+1),O&&(this.query=b.parse(this.query)),W=W.slice(0,Bt)):O&&(this.search="",this.query={}),W&&(this.pathname=W),S[J]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var xe=this.pathname||"",xn=this.search||"";this.path=xe+xn}return this.href=this.format(),this};function _(y){return typeof y=="string"&&(y=w(y)),y instanceof e?y.format():e.prototype.format.call(y)}e.prototype.format=function(){var y=this.auth||"";y&&(y=encodeURIComponent(y),y=y.replace(/%3A/i,":"),y+="@");var O=this.protocol||"",v=this.pathname||"",M=this.hash||"",F=!1,U="";this.host?F=y+this.host:this.hostname&&(F=y+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(F+=":"+this.port)),this.query&&typeof this.query=="object"&&Object.keys(this.query).length&&(U=b.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var Q=this.search||U&&"?"+U||"";return O&&O.substr(-1)!==":"&&(O+=":"),this.slashes||(!O||S[O])&&F!==!1?(F="//"+(F||""),v&&v.charAt(0)!=="/"&&(v="/"+v)):F||(F=""),M&&M.charAt(0)!=="#"&&(M="#"+M),Q&&Q.charAt(0)!=="?"&&(Q="?"+Q),v=v.replace(/[?#]/g,function(W){return encodeURIComponent(W)}),Q=Q.replace("#","%23"),O+F+v+Q+M};function R(y,O){return w(y,!1,!0).resolve(O)}e.prototype.resolve=function(y){return this.resolveObject(w(y,!1,!0)).format()};function T(y,O){return y?w(y,!1,!0).resolveObject(O):O}return e.prototype.resolveObject=function(y){if(typeof y=="string"){var O=new e;O.parse(y,!1,!0),y=O}for(var v=new e,M=Object.keys(this),F=0;F<M.length;F++){var U=M[F];v[U]=this[U]}if(v.hash=y.hash,y.href==="")return v.href=v.format(),v;if(y.slashes&&!y.protocol){for(var Q=Object.keys(y),W=0;W<Q.length;W++){var H=Q[W];H!=="protocol"&&(v[H]=y[H])}return S[v.protocol]&&v.hostname&&!v.pathname&&(v.pathname="/",v.path=v.pathname),v.href=v.format(),v}if(y.protocol&&y.protocol!==v.protocol){if(!S[y.protocol]){for(var z=Object.keys(y),J=0;J<z.length;J++){var ee=z[J];v[ee]=y[ee]}return v.href=v.format(),v}if(v.protocol=y.protocol,!y.host&&!P[y.protocol]){for(var ne=(y.pathname||"").split("/");ne.length&&!(y.host=ne.shift()););y.host||(y.host=""),y.hostname||(y.hostname=""),ne[0]!==""&&ne.unshift(""),ne.length<2&&ne.unshift(""),v.pathname=ne.join("/")}else v.pathname=y.pathname;if(v.search=y.search,v.query=y.query,v.host=y.host||"",v.auth=y.auth,v.hostname=y.ho
Line truncated
|
||||
`)&&(e=e.replace(Kx,"%0A")),e.includes("\r")&&(e=e.replace(Qx,"%0D")),e.includes(" ")&&(e=e.replace(Yx,"%09")),n.pathname=e,n}var Tx,Al,yb,Il,xl,gb,Tl,bb,Pl,wb,Ol,mb,Rl,_b,kl,vb,Hr,Sb,Ge,Mx,Nx,qx,Lx,Ux,Dx,jx,Fx,Wx,$x,Hx,Cl,Vx,Gx,zx,Kx,Qx,Yx,Tb=ze(()=>{A();x();I();Dg();cb();pb();vl();Tx=Object.freeze(Object.create(null)),Al={},yb=!1,Il=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global;xl={},gb=!1;Tl={},bb=!1;Pl={},wb=!1;Ol={},mb=!1;Rl={},_b=!1;kl={},vb=!1;Hr={},Sb=!1;Ge=Bx();Ge.parse;Ge.resolve;Ge.resolveObject;Ge.format;Ge.Url;Mx=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0;Ge.URL=typeof URL<"u"?URL:null;Ge.pathToFileURL=Ib;Ge.fileURLToPath=Ab;Nx=Ge.Url,qx=Ge.format,Lx=Ge.resolve,Ux=Ge.resolveObject,Dx=Ge.parse,jx=Ge.URL,Fx=92,Wx=47,$x=97,Hx=122,Cl=Mx==="win32",Vx=/\//g,Gx=/%/g,zx=/\\/g,Kx=/\n/g,Qx=/\r/g,Yx=/\t/g});var Ob=j(($F,Pb)=>{"use strict";A();x();I();Pb.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Qo=j(mi=>{"use strict";A();x();I();Object.defineProperty(mi,"__esModule",{value:!0});mi.BufferedDuplex=void 0;mi.writev=kb;var Zx=or(),Rb=(ke(),me(qe));function kb(t,e){let r=new Array(t.length);for(let n=0;n<t.length;n++)typeof t[n].chunk=="string"?r[n]=Rb.Buffer.from(t[n].chunk,"utf8"):r[n]=t[n].chunk;this._write(Rb.Buffer.concat(r),"binary",e)}var Ml=class extends Zx.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(e,r,n){super({objectMode:!0}),this.proxy=r,this.socket=n,this.writeQueue=[],e.objectMode||(this._writev=kb.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",i=>{!this.destroyed&&this.readable&&this.push(i)})}_read(e){this.proxy.read(e)}_write(e,r,n){this.isSocketOpen?this.writeToProxy(e,r,n):this.writeQueue.push({chunk:e,encoding:r,cb:n})}_final(e){this.writeQueue=[],this.proxy.end(e)}_destroy(e,r){this.writeQueue=[],this.proxy.destroy(),r(e)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(e,r,n){this.proxy.write(e,r)===!1?this.proxy.once("drain",n):n()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:e,encoding:r,cb:n}=this.writeQueue.shift();this.writeToProxy(e,r,n)}}};mi.BufferedDuplex=Ml});var _i=j(gr=>{"use strict";A();x();I();var ql=gr&&gr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(gr,"__esModule",{value:!0});gr.streamBuilder=gr.browserStreamBuilder=void 0;var Yo=(ke(),me(qe)),Cb=ql(Ob()),eT=ql(At()),tT=or(),rT=ql(yi()),Nl=Qo(),yr=(0,eT.default)("mqttjs:ws"),nT=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function Bb(t,e){let r=`${t.protocol}://${t.hostname}:${t.port}${t.path}`;return typeof t.transformWsUrl=="function"&&(r=t.transformWsUrl(r,t,e)),r}function Mb(t){let e=t;return t.port||(t.protocol==="wss"?e.port=443:e.port=80),t.path||(e.path="/"),t.wsOptions||(e.wsOptions={}),!rT.default&&!t.forceNativeWebSocket&&t.protocol==="wss"&&nT.forEach(r=>{Object.prototype.hasOwnProperty.call(t,r)&&!Object.prototype.hasOwnProperty.call(t.wsOptions,r)&&(e.wsOptions[r]=t[r])}),e}function iT(t){let e=Mb(t);if(e.hostname||(e.hostname=e.host),!e.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let r=new URL(document.URL);e.hostname=r.hostname,e.port||(e.port=Number(r.port))}return e.objectMode===void 0&&(e.objectMode=!(e.binary===!0||e.binary===void 0)),e}function oT(t,e,r){yr("createWebSocket"),yr(`protocol: ${r.protocolId} ${r.protocolVersion}`);let n=r.protocolId==="MQIsdp"&&r.protocolVersion===3?"mqttv3.1":"mqtt";yr(`creating new Websocket for url: ${e} and protocol: ${n}`);let i;return r.createWebsocket?i=r.createWebsocket(e,[n],r):i=new Cb.default(e,[n],r.wsOptions),i}function sT(t,e){let r=e.protocolId==="MQIsdp"&&e.protocolVersion===3?"mqttv3.1":"mqtt",n=Bb(e,t),i;return e.createWebsocket?i=e.createWebsocket(n,[r],e):i=new WebSocket(n,[r]),i.binaryType="arraybuffer",i}var aT=(t,e)=>{yr("streamBuilder");let r=Mb(e);r.hostname=r.hostname||r.host||"localhost";let n=Bb(r,t),i=oT(t,n,r),s=Cb.default.createWebSocketStream(i,r.wsOptions);return s.url=n,i.on("close",()=>{s.destroy()}),s};gr.streamBuilder=aT;var uT=(t,e)=>{yr("browserStreamBuilder");let r,i=iT(e).browserBufferSize||1024*512,s=e.browserBufferTimeout||1e3,o=!e.objectMode,a=sT(t,e),c=h(e,S,b);e.objectMode||(c._writev=Nl.writev.bind(c)),c.on("close",()=>{a.close()});let f=typeof a.addEventListener<"u";a.readyState===a.OPEN?(r=c,r.socket=a):(r=new Nl.BufferedDuplex(e,c,a),f?a.addEventListener("open",d):a.onopen=d),f?(a.addEventListener("close",m),a.addEventListener("error",g),a.addEventListener("message",P)):(a.onclose=m,a.onerror=g,a.onmessage=P);function h(w,_,R){let T=new tT.Transform({objectMode:w.objectMode});return T._write=_,T._flush=R,T}function d(){yr("WebSocket onOpen"),r instanceof Nl.BufferedDuplex&&r.socketReady()}function m(w){yr("WebSocket onClose",w),r.end(),r.destroy()}function g(w){yr("WebSocket onError",w);let _=new
Line truncated
|
||||
/*! Bundled license information:
|
||||
|
||||
@jspm/core/nodelibs/browser/chunk-DtuTasat.js:
|
||||
(*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
|
||||
|
||||
safe-buffer/index.js:
|
||||
(*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
|
||||
|
||||
@babel/runtime/helpers/regenerator.js:
|
||||
(*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE *)
|
||||
*/
|
||||
@@ -0,0 +1,676 @@
|
||||
/**
|
||||
* VideoRTC v1.6.0 - Video player for go2rtc streaming application.
|
||||
*
|
||||
* All modern web technologies are supported in almost any browser except Apple Safari.
|
||||
*
|
||||
* Support:
|
||||
* - ECMAScript 2017 (ES8) = ES6 + async
|
||||
* - RTCPeerConnection for Safari iOS 11.0+
|
||||
* - IntersectionObserver for Safari iOS 12.2+
|
||||
* - ManagedMediaSource for Safari 17+
|
||||
*
|
||||
* Doesn't support:
|
||||
* - MediaSource for Safari iOS
|
||||
* - Customized built-in elements (extends HTMLVideoElement) because Safari
|
||||
* - Autoplay for WebRTC in Safari
|
||||
*/
|
||||
export class VideoRTC extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.DISCONNECT_TIMEOUT = 5000;
|
||||
this.RECONNECT_TIMEOUT = 15000;
|
||||
|
||||
this.CODECS = [
|
||||
'avc1.640029', // H.264 high 4.1 (Chromecast 1st and 2nd Gen)
|
||||
'avc1.64002A', // H.264 high 4.2 (Chromecast 3rd Gen)
|
||||
'avc1.640033', // H.264 high 5.1 (Chromecast with Google TV)
|
||||
'hvc1.1.6.L153.B0', // H.265 main 5.1 (Chromecast Ultra)
|
||||
'mp4a.40.2', // AAC LC
|
||||
'mp4a.40.5', // AAC HE
|
||||
'flac', // FLAC (PCM compatible)
|
||||
'opus', // OPUS Chrome, Firefox
|
||||
];
|
||||
|
||||
/**
|
||||
* [config] Supported modes (webrtc, webrtc/tcp, mse, hls, mp4, mjpeg).
|
||||
* @type {string}
|
||||
*/
|
||||
this.mode = 'webrtc,mse,hls,mjpeg';
|
||||
|
||||
/**
|
||||
* [Config] Requested medias (video, audio, microphone).
|
||||
* @type {string}
|
||||
*/
|
||||
this.media = 'video,audio';
|
||||
|
||||
/**
|
||||
* [config] Run stream when not displayed on the screen. Default `false`.
|
||||
* @type {boolean}
|
||||
*/
|
||||
this.background = false;
|
||||
|
||||
/**
|
||||
* [config] Run stream only when player in the viewport. Stop when user scroll out player.
|
||||
* Value is percentage of visibility from `0` (not visible) to `1` (full visible).
|
||||
* Default `0` - disable;
|
||||
* @type {number}
|
||||
*/
|
||||
this.visibilityThreshold = 0;
|
||||
|
||||
/**
|
||||
* [config] Run stream only when browser page on the screen. Stop when user change browser
|
||||
* tab or minimise browser windows.
|
||||
* @type {boolean}
|
||||
*/
|
||||
this.visibilityCheck = true;
|
||||
|
||||
/**
|
||||
* [config] WebRTC configuration
|
||||
* @type {RTCConfiguration}
|
||||
*/
|
||||
this.pcConfig = {
|
||||
bundlePolicy: 'max-bundle',
|
||||
iceServers: [{urls: 'stun:stun.l.google.com:19302'}],
|
||||
sdpSemantics: 'unified-plan', // important for Chromecast 1
|
||||
};
|
||||
|
||||
/**
|
||||
* [info] WebSocket connection state. Values: CONNECTING, OPEN, CLOSED
|
||||
* @type {number}
|
||||
*/
|
||||
this.wsState = WebSocket.CLOSED;
|
||||
|
||||
/**
|
||||
* [info] WebRTC connection state.
|
||||
* @type {number}
|
||||
*/
|
||||
this.pcState = WebSocket.CLOSED;
|
||||
|
||||
/**
|
||||
* @type {HTMLVideoElement}
|
||||
*/
|
||||
this.video = null;
|
||||
|
||||
/**
|
||||
* @type {WebSocket}
|
||||
*/
|
||||
this.ws = null;
|
||||
|
||||
/**
|
||||
* @type {string|URL}
|
||||
*/
|
||||
this.wsURL = '';
|
||||
|
||||
/**
|
||||
* @type {RTCPeerConnection}
|
||||
*/
|
||||
this.pc = null;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
*/
|
||||
this.connectTS = 0;
|
||||
|
||||
/**
|
||||
* @type {string}
|
||||
*/
|
||||
this.mseCodecs = '';
|
||||
|
||||
/**
|
||||
* [internal] Disconnect TimeoutID.
|
||||
* @type {number}
|
||||
*/
|
||||
this.disconnectTID = 0;
|
||||
|
||||
/**
|
||||
* [internal] Reconnect TimeoutID.
|
||||
* @type {number}
|
||||
*/
|
||||
this.reconnectTID = 0;
|
||||
|
||||
/**
|
||||
* [internal] Handler for receiving Binary from WebSocket.
|
||||
* @type {Function}
|
||||
*/
|
||||
this.ondata = null;
|
||||
|
||||
/**
|
||||
* [internal] Handlers list for receiving JSON from WebSocket.
|
||||
* @type {Object.<string,Function>}
|
||||
*/
|
||||
this.onmessage = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set video source (WebSocket URL). Support relative path.
|
||||
* @param {string|URL} value
|
||||
*/
|
||||
set src(value) {
|
||||
if (typeof value !== 'string') value = value.toString();
|
||||
if (value.startsWith('http')) {
|
||||
value = 'ws' + value.substring(4);
|
||||
} else if (value.startsWith('/')) {
|
||||
value = 'ws' + location.origin.substring(4) + value;
|
||||
}
|
||||
|
||||
this.wsURL = value;
|
||||
|
||||
this.onconnect();
|
||||
}
|
||||
|
||||
/**
|
||||
* Play video. Support automute when autoplay blocked.
|
||||
* https://developer.chrome.com/blog/autoplay/
|
||||
*/
|
||||
play() {
|
||||
this.video.play().catch(() => {
|
||||
if (!this.video.muted) {
|
||||
this.video.muted = true;
|
||||
this.video.play().catch(er => {
|
||||
console.warn(er);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Send message to server via WebSocket
|
||||
* @param {Object} value
|
||||
*/
|
||||
send(value) {
|
||||
if (this.ws) this.ws.send(JSON.stringify(value));
|
||||
}
|
||||
|
||||
/** @param {Function} isSupported */
|
||||
codecs(isSupported) {
|
||||
return this.CODECS
|
||||
.filter(codec => this.media.indexOf(codec.indexOf('vc1') > 0 ? 'video' : 'audio') >= 0)
|
||||
.filter(codec => isSupported(`video/mp4; codecs="${codec}"`)).join();
|
||||
}
|
||||
|
||||
/**
|
||||
* `CustomElement`. Invoked each time the custom element is appended into a
|
||||
* document-connected element.
|
||||
*/
|
||||
connectedCallback() {
|
||||
if (this.disconnectTID) {
|
||||
clearTimeout(this.disconnectTID);
|
||||
this.disconnectTID = 0;
|
||||
}
|
||||
|
||||
// because video autopause on disconnected from DOM
|
||||
if (this.video) {
|
||||
const seek = this.video.seekable;
|
||||
if (seek.length > 0) {
|
||||
this.video.currentTime = seek.end(seek.length - 1);
|
||||
}
|
||||
this.play();
|
||||
} else {
|
||||
this.oninit();
|
||||
}
|
||||
|
||||
this.onconnect();
|
||||
}
|
||||
|
||||
/**
|
||||
* `CustomElement`. Invoked each time the custom element is disconnected from the
|
||||
* document's DOM.
|
||||
*/
|
||||
disconnectedCallback() {
|
||||
if (this.background || this.disconnectTID) return;
|
||||
if (this.wsState === WebSocket.CLOSED && this.pcState === WebSocket.CLOSED) return;
|
||||
|
||||
this.disconnectTID = setTimeout(() => {
|
||||
if (this.reconnectTID) {
|
||||
clearTimeout(this.reconnectTID);
|
||||
this.reconnectTID = 0;
|
||||
}
|
||||
|
||||
this.disconnectTID = 0;
|
||||
|
||||
this.ondisconnect();
|
||||
}, this.DISCONNECT_TIMEOUT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates child DOM elements. Called automatically once on `connectedCallback`.
|
||||
*/
|
||||
oninit() {
|
||||
this.video = document.createElement('video');
|
||||
this.video.controls = true;
|
||||
this.video.playsInline = true;
|
||||
this.video.preload = 'auto';
|
||||
|
||||
this.video.style.display = 'block'; // fix bottom margin 4px
|
||||
this.video.style.width = '100%';
|
||||
this.video.style.height = '100%';
|
||||
|
||||
this.appendChild(this.video);
|
||||
|
||||
this.video.addEventListener('error', ev => {
|
||||
console.warn(ev);
|
||||
if (this.ws) this.ws.close(); // run reconnect for broken MSE stream
|
||||
});
|
||||
|
||||
// all Safari lies about supported audio codecs
|
||||
const m = window.navigator.userAgent.match(/Version\/(\d+).+Safari/);
|
||||
if (m) {
|
||||
// AAC from v13, FLAC from v14, OPUS - unsupported
|
||||
const skip = m[1] < '13' ? 'mp4a.40.2' : m[1] < '14' ? 'flac' : 'opus';
|
||||
this.CODECS.splice(this.CODECS.indexOf(skip));
|
||||
}
|
||||
|
||||
if (this.background) return;
|
||||
|
||||
if ('hidden' in document && this.visibilityCheck) {
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.hidden) {
|
||||
this.disconnectedCallback();
|
||||
} else if (this.isConnected) {
|
||||
this.connectedCallback();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if ('IntersectionObserver' in window && this.visibilityThreshold) {
|
||||
const observer = new IntersectionObserver(entries => {
|
||||
entries.forEach(entry => {
|
||||
if (!entry.isIntersecting) {
|
||||
this.disconnectedCallback();
|
||||
} else if (this.isConnected) {
|
||||
this.connectedCallback();
|
||||
}
|
||||
});
|
||||
}, {threshold: this.visibilityThreshold});
|
||||
observer.observe(this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to WebSocket. Called automatically on `connectedCallback`.
|
||||
* @return {boolean} true if the connection has started.
|
||||
*/
|
||||
onconnect() {
|
||||
if (!this.isConnected || !this.wsURL || this.ws || this.pc) return false;
|
||||
|
||||
// CLOSED or CONNECTING => CONNECTING
|
||||
this.wsState = WebSocket.CONNECTING;
|
||||
|
||||
this.connectTS = Date.now();
|
||||
|
||||
this.ws = new WebSocket(this.wsURL);
|
||||
this.ws.binaryType = 'arraybuffer';
|
||||
this.ws.addEventListener('open', () => this.onopen());
|
||||
this.ws.addEventListener('close', () => this.onclose());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
ondisconnect() {
|
||||
this.wsState = WebSocket.CLOSED;
|
||||
if (this.ws) {
|
||||
this.ws.close();
|
||||
this.ws = null;
|
||||
}
|
||||
|
||||
this.pcState = WebSocket.CLOSED;
|
||||
if (this.pc) {
|
||||
this.pc.getSenders().forEach(sender => {
|
||||
if (sender.track) sender.track.stop();
|
||||
});
|
||||
this.pc.close();
|
||||
this.pc = null;
|
||||
}
|
||||
|
||||
this.video.src = '';
|
||||
this.video.srcObject = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Array.<string>} of modes (mse, webrtc, etc.)
|
||||
*/
|
||||
onopen() {
|
||||
// CONNECTING => OPEN
|
||||
this.wsState = WebSocket.OPEN;
|
||||
|
||||
this.ws.addEventListener('message', ev => {
|
||||
if (typeof ev.data === 'string') {
|
||||
const msg = JSON.parse(ev.data);
|
||||
for (const mode in this.onmessage) {
|
||||
this.onmessage[mode](msg);
|
||||
}
|
||||
} else {
|
||||
this.ondata(ev.data);
|
||||
}
|
||||
});
|
||||
|
||||
this.ondata = null;
|
||||
this.onmessage = {};
|
||||
|
||||
const modes = [];
|
||||
|
||||
if (this.mode.indexOf('mse') >= 0 && ('MediaSource' in window || 'ManagedMediaSource' in window)) {
|
||||
modes.push('mse');
|
||||
this.onmse();
|
||||
} else if (this.mode.indexOf('hls') >= 0 && this.video.canPlayType('application/vnd.apple.mpegurl')) {
|
||||
modes.push('hls');
|
||||
this.onhls();
|
||||
} else if (this.mode.indexOf('mp4') >= 0) {
|
||||
modes.push('mp4');
|
||||
this.onmp4();
|
||||
}
|
||||
|
||||
if (this.mode.indexOf('webrtc') >= 0 && 'RTCPeerConnection' in window) {
|
||||
modes.push('webrtc');
|
||||
this.onwebrtc();
|
||||
}
|
||||
|
||||
if (this.mode.indexOf('mjpeg') >= 0) {
|
||||
if (modes.length) {
|
||||
this.onmessage['mjpeg'] = msg => {
|
||||
if (msg.type !== 'error' || msg.value.indexOf(modes[0]) !== 0) return;
|
||||
this.onmjpeg();
|
||||
};
|
||||
} else {
|
||||
modes.push('mjpeg');
|
||||
this.onmjpeg();
|
||||
}
|
||||
}
|
||||
|
||||
return modes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {boolean} true if reconnection has started.
|
||||
*/
|
||||
onclose() {
|
||||
if (this.wsState === WebSocket.CLOSED) return false;
|
||||
|
||||
// CONNECTING, OPEN => CONNECTING
|
||||
this.wsState = WebSocket.CONNECTING;
|
||||
this.ws = null;
|
||||
|
||||
// reconnect no more than once every X seconds
|
||||
const delay = Math.max(this.RECONNECT_TIMEOUT - (Date.now() - this.connectTS), 0);
|
||||
|
||||
this.reconnectTID = setTimeout(() => {
|
||||
this.reconnectTID = 0;
|
||||
this.onconnect();
|
||||
}, delay);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
onmse() {
|
||||
/** @type {MediaSource} */
|
||||
let ms;
|
||||
|
||||
if ('ManagedMediaSource' in window) {
|
||||
const MediaSource = window.ManagedMediaSource;
|
||||
|
||||
ms = new MediaSource();
|
||||
ms.addEventListener('sourceopen', () => {
|
||||
this.send({type: 'mse', value: this.codecs(MediaSource.isTypeSupported)});
|
||||
}, {once: true});
|
||||
|
||||
this.video.disableRemotePlayback = true;
|
||||
this.video.srcObject = ms;
|
||||
} else {
|
||||
ms = new MediaSource();
|
||||
ms.addEventListener('sourceopen', () => {
|
||||
URL.revokeObjectURL(this.video.src);
|
||||
this.send({type: 'mse', value: this.codecs(MediaSource.isTypeSupported)});
|
||||
}, {once: true});
|
||||
|
||||
this.video.src = URL.createObjectURL(ms);
|
||||
this.video.srcObject = null;
|
||||
}
|
||||
|
||||
this.play();
|
||||
|
||||
this.mseCodecs = '';
|
||||
|
||||
this.onmessage['mse'] = msg => {
|
||||
if (msg.type !== 'mse') return;
|
||||
|
||||
this.mseCodecs = msg.value;
|
||||
|
||||
const sb = ms.addSourceBuffer(msg.value);
|
||||
sb.mode = 'segments'; // segments or sequence
|
||||
sb.addEventListener('updateend', () => {
|
||||
if (!sb.updating && bufLen > 0) {
|
||||
try {
|
||||
const data = buf.slice(0, bufLen);
|
||||
sb.appendBuffer(data);
|
||||
bufLen = 0;
|
||||
} catch (e) {
|
||||
// console.debug(e);
|
||||
}
|
||||
}
|
||||
|
||||
if (!sb.updating && sb.buffered && sb.buffered.length) {
|
||||
const end = sb.buffered.end(sb.buffered.length - 1);
|
||||
const start = end - 5;
|
||||
const start0 = sb.buffered.start(0);
|
||||
if (start > start0) {
|
||||
sb.remove(start0, start);
|
||||
ms.setLiveSeekableRange(start, end);
|
||||
}
|
||||
if (this.video.currentTime < start) {
|
||||
this.video.currentTime = start;
|
||||
}
|
||||
const gap = end - this.video.currentTime;
|
||||
this.video.playbackRate = gap > 0.1 ? gap : 0.1;
|
||||
// console.debug('VideoRTC.buffered', gap, this.video.playbackRate, this.video.readyState);
|
||||
}
|
||||
});
|
||||
|
||||
const buf = new Uint8Array(2 * 1024 * 1024);
|
||||
let bufLen = 0;
|
||||
|
||||
this.ondata = data => {
|
||||
if (sb.updating || bufLen > 0) {
|
||||
const b = new Uint8Array(data);
|
||||
buf.set(b, bufLen);
|
||||
bufLen += b.byteLength;
|
||||
// console.debug('VideoRTC.buffer', b.byteLength, bufLen);
|
||||
} else {
|
||||
try {
|
||||
sb.appendBuffer(data);
|
||||
} catch (e) {
|
||||
// console.debug(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
onwebrtc() {
|
||||
const pc = new RTCPeerConnection(this.pcConfig);
|
||||
|
||||
pc.addEventListener('icecandidate', ev => {
|
||||
if (ev.candidate && this.mode.indexOf('webrtc/tcp') >= 0 && ev.candidate.protocol === 'udp') return;
|
||||
|
||||
const candidate = ev.candidate ? ev.candidate.toJSON().candidate : '';
|
||||
this.send({type: 'webrtc/candidate', value: candidate});
|
||||
});
|
||||
|
||||
pc.addEventListener('connectionstatechange', () => {
|
||||
if (pc.connectionState === 'connected') {
|
||||
const tracks = pc.getTransceivers()
|
||||
.filter(tr => tr.currentDirection === 'recvonly') // skip inactive
|
||||
.map(tr => tr.receiver.track);
|
||||
/** @type {HTMLVideoElement} */
|
||||
const video2 = document.createElement('video');
|
||||
video2.addEventListener('loadeddata', () => this.onpcvideo(video2), {once: true});
|
||||
video2.srcObject = new MediaStream(tracks);
|
||||
} else if (pc.connectionState === 'failed' || pc.connectionState === 'disconnected') {
|
||||
pc.close(); // stop next events
|
||||
|
||||
this.pcState = WebSocket.CLOSED;
|
||||
this.pc = null;
|
||||
|
||||
this.onconnect();
|
||||
}
|
||||
});
|
||||
|
||||
this.onmessage['webrtc'] = msg => {
|
||||
switch (msg.type) {
|
||||
case 'webrtc/candidate':
|
||||
if (this.mode.indexOf('webrtc/tcp') >= 0 && msg.value.indexOf(' udp ') > 0) return;
|
||||
|
||||
pc.addIceCandidate({candidate: msg.value, sdpMid: '0'}).catch(er => {
|
||||
console.warn(er);
|
||||
});
|
||||
break;
|
||||
case 'webrtc/answer':
|
||||
pc.setRemoteDescription({type: 'answer', sdp: msg.value}).catch(er => {
|
||||
console.warn(er);
|
||||
});
|
||||
break;
|
||||
case 'error':
|
||||
if (msg.value.indexOf('webrtc/offer') < 0) return;
|
||||
pc.close();
|
||||
}
|
||||
};
|
||||
|
||||
this.createOffer(pc).then(offer => {
|
||||
this.send({type: 'webrtc/offer', value: offer.sdp});
|
||||
});
|
||||
|
||||
this.pcState = WebSocket.CONNECTING;
|
||||
this.pc = pc;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param pc {RTCPeerConnection}
|
||||
* @return {Promise<RTCSessionDescriptionInit>}
|
||||
*/
|
||||
async createOffer(pc) {
|
||||
try {
|
||||
if (this.media.indexOf('microphone') >= 0) {
|
||||
const media = await navigator.mediaDevices.getUserMedia({audio: true});
|
||||
media.getTracks().forEach(track => {
|
||||
pc.addTransceiver(track, {direction: 'sendonly'});
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn(e);
|
||||
}
|
||||
|
||||
for (const kind of ['video', 'audio']) {
|
||||
if (this.media.indexOf(kind) >= 0) {
|
||||
pc.addTransceiver(kind, {direction: 'recvonly'});
|
||||
}
|
||||
}
|
||||
|
||||
const offer = await pc.createOffer();
|
||||
await pc.setLocalDescription(offer);
|
||||
return offer;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param video2 {HTMLVideoElement}
|
||||
*/
|
||||
onpcvideo(video2) {
|
||||
if (this.pc) {
|
||||
// Video+Audio > Video, H265 > H264, Video > Audio, WebRTC > MSE
|
||||
let rtcPriority = 0, msePriority = 0;
|
||||
|
||||
/** @type {MediaStream} */
|
||||
const stream = video2.srcObject;
|
||||
if (stream.getVideoTracks().length > 0) rtcPriority += 0x220;
|
||||
if (stream.getAudioTracks().length > 0) rtcPriority += 0x102;
|
||||
|
||||
if (this.mseCodecs.indexOf('hvc1.') >= 0) msePriority += 0x230;
|
||||
if (this.mseCodecs.indexOf('avc1.') >= 0) msePriority += 0x210;
|
||||
if (this.mseCodecs.indexOf('mp4a.') >= 0) msePriority += 0x101;
|
||||
|
||||
if (rtcPriority >= msePriority) {
|
||||
this.video.srcObject = stream;
|
||||
this.play();
|
||||
|
||||
this.pcState = WebSocket.OPEN;
|
||||
|
||||
this.wsState = WebSocket.CLOSED;
|
||||
if (this.ws) {
|
||||
this.ws.close();
|
||||
this.ws = null;
|
||||
}
|
||||
} else {
|
||||
this.pcState = WebSocket.CLOSED;
|
||||
if (this.pc) {
|
||||
this.pc.close();
|
||||
this.pc = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
video2.srcObject = null;
|
||||
}
|
||||
|
||||
onmjpeg() {
|
||||
this.ondata = data => {
|
||||
this.video.controls = false;
|
||||
this.video.poster = 'data:image/jpeg;base64,' + VideoRTC.btoa(data);
|
||||
};
|
||||
|
||||
this.send({type: 'mjpeg'});
|
||||
}
|
||||
|
||||
onhls() {
|
||||
this.onmessage['hls'] = msg => {
|
||||
if (msg.type !== 'hls') return;
|
||||
|
||||
const url = 'http' + this.wsURL.substring(2, this.wsURL.indexOf('/ws')) + '/hls/';
|
||||
const playlist = msg.value.replace('hls/', url);
|
||||
this.video.src = 'data:application/vnd.apple.mpegurl;base64,' + btoa(playlist);
|
||||
this.play();
|
||||
};
|
||||
|
||||
this.send({type: 'hls', value: this.codecs(type => this.video.canPlayType(type))});
|
||||
}
|
||||
|
||||
onmp4() {
|
||||
/** @type {HTMLCanvasElement} **/
|
||||
const canvas = document.createElement('canvas');
|
||||
/** @type {CanvasRenderingContext2D} */
|
||||
let context;
|
||||
|
||||
/** @type {HTMLVideoElement} */
|
||||
const video2 = document.createElement('video');
|
||||
video2.autoplay = true;
|
||||
video2.playsInline = true;
|
||||
video2.muted = true;
|
||||
|
||||
video2.addEventListener('loadeddata', () => {
|
||||
if (!context) {
|
||||
canvas.width = video2.videoWidth;
|
||||
canvas.height = video2.videoHeight;
|
||||
context = canvas.getContext('2d');
|
||||
}
|
||||
|
||||
context.drawImage(video2, 0, 0, canvas.width, canvas.height);
|
||||
|
||||
this.video.controls = false;
|
||||
this.video.poster = canvas.toDataURL('image/jpeg');
|
||||
});
|
||||
|
||||
this.ondata = data => {
|
||||
video2.src = 'data:video/mp4;base64,' + VideoRTC.btoa(data);
|
||||
};
|
||||
|
||||
this.send({type: 'mp4', value: this.codecs(this.video.canPlayType)});
|
||||
}
|
||||
|
||||
static btoa(buffer) {
|
||||
const bytes = new Uint8Array(buffer);
|
||||
const len = bytes.byteLength;
|
||||
let binary = '';
|
||||
for (let i = 0; i < len; i++) {
|
||||
binary += String.fromCharCode(bytes[i]);
|
||||
}
|
||||
return window.btoa(binary);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user