init
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,216 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>hevc.js (WASM, тайлы) — CoRE.Vision</title>
|
||||
<style>
|
||||
body { background:#0d0d0d; color:#ddd; font:13px system-ui,Arial; margin:0; padding:12px; }
|
||||
#cv { background:#000; border:1px solid #333; display:block; margin:10px 0; width:100%; max-width:900px; height:auto; }
|
||||
#log { white-space:pre-wrap; font:12px Consolas,monospace; color:#9f9; max-height:240px; overflow:auto; }
|
||||
button { font:13px system-ui; padding:4px 10px; }
|
||||
#stat { color:#ffd479; font-weight:bold; margin-left:12px; }
|
||||
</style>
|
||||
<!-- index.js статически импортит "mp4box" (для FMP4Demuxer, не используем) → подменяем заглушкой -->
|
||||
<script type="importmap">
|
||||
{ "imports": { "mp4box": "/static/vendor/hevcjs/mp4box-stub.js" } }
|
||||
</script>
|
||||
<!-- glue эмскриптена: UMD, выставляет глобал HEVCDecoderModule; create() его подхватит -->
|
||||
<script src="/static/vendor/hevcjs/dist/wasm/hevc-decode.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div>
|
||||
<button id="gomain">▶ main 3200×1800</button>
|
||||
<button id="gosub">▶ sub 640×360</button>
|
||||
<button id="stop">⏹ Stop</button>
|
||||
<span id="stat"></span>
|
||||
</div>
|
||||
<canvas id="cv" width="960" height="540"></canvas>
|
||||
<div id="log"></div>
|
||||
|
||||
<script type="module">
|
||||
import { HEVCDecoder, FrameRenderer } from "/static/vendor/hevcjs/hevc-core.js";
|
||||
|
||||
const logEl = document.getElementById("log"), statEl = document.getElementById("stat");
|
||||
const log = (...a) => { logEl.textContent += a.map((x) => typeof x === "object" ? JSON.stringify(x) : String(x)).join(" ") + "\n"; logEl.scrollTop = 1e9; console.log("[hevctest]", ...a); };
|
||||
window.onerror = (m, s, l) => log("‼ onerror", m, "@", l);
|
||||
window.onunhandledrejection = (e) => log("‼ promise", e.reason && (e.reason.message || e.reason));
|
||||
|
||||
// ── строка кодека из hvcC (для лога) ──
|
||||
function hevcCodecFromHvcC(hvcC) {
|
||||
try { const p = hvcC[1] & 0x1f, t = ((hvcC[1] >> 5) & 1) ? "H" : "L", lv = hvcC[12] || 153; return `hvc1.${p}.6.${t}${lv}.B0`; }
|
||||
catch (e) { return "hvc1.1.6.L153.B0"; }
|
||||
}
|
||||
// ── параметр-сеты (VPS/SPS/PPS) из hvcC → Annex-B ──
|
||||
function hvccParamSetsToAnnexB(hvcC) {
|
||||
if (hvcC.length < 23) return new Uint8Array(0);
|
||||
let o = 22; const numArrays = hvcC[o++]; const chunks = [];
|
||||
for (let a = 0; a < numArrays; a++) {
|
||||
o++; // байт: array_completeness(1)|reserved(1)|NAL_unit_type(6) — тип не нужен
|
||||
const num = (hvcC[o] << 8) | hvcC[o + 1]; o += 2;
|
||||
for (let n = 0; n < num; n++) {
|
||||
const len = (hvcC[o] << 8) | hvcC[o + 1]; o += 2;
|
||||
chunks.push(hvcC.subarray(o, o + len)); o += len;
|
||||
}
|
||||
}
|
||||
let total = 0; for (const c of chunks) total += 4 + c.length;
|
||||
const out = new Uint8Array(total); let p = 0;
|
||||
for (const c of chunks) { out[p + 3] = 1; p += 4; out.set(c, p); p += c.length; }
|
||||
return out;
|
||||
}
|
||||
// ── length-prefixed (4 байта длины) NAL → Annex-B (00 00 00 01), размер не меняется ──
|
||||
function toAnnexB(u8) {
|
||||
const out = new Uint8Array(u8.length); out.set(u8);
|
||||
let i = 0;
|
||||
while (i + 4 <= out.length) {
|
||||
const len = ((u8[i] << 24) | (u8[i + 1] << 16) | (u8[i + 2] << 8) | u8[i + 3]) >>> 0;
|
||||
out[i] = 0; out[i + 1] = 0; out[i + 2] = 0; out[i + 3] = 1;
|
||||
if (len === 0) break; i += 4 + len;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── демуксер FLV (enhanced-RTMP) → hvcC + length-prefixed HEVC-кадры (из app.js) ──
|
||||
class FlvHevcDemuxer {
|
||||
constructor({ onConfig, onSample }) {
|
||||
this.onConfig = onConfig; this.onSample = onSample;
|
||||
this.buf = new Uint8Array(0); this.headerDone = false; this.gotConfig = false;
|
||||
}
|
||||
push(ab) {
|
||||
const inc = new Uint8Array(ab);
|
||||
if (this.buf.length === 0) { this.buf = inc; }
|
||||
else { const m = new Uint8Array(this.buf.length + inc.length); m.set(this.buf, 0); m.set(inc, this.buf.length); this.buf = m; }
|
||||
this._parse();
|
||||
}
|
||||
_u32(o) { return ((this.buf[o] << 24) | (this.buf[o + 1] << 16) | (this.buf[o + 2] << 8) | this.buf[o + 3]) >>> 0; }
|
||||
_parse() {
|
||||
const b = this.buf, len = b.length;
|
||||
if (!this.headerDone) {
|
||||
if (len < 9) return;
|
||||
const dataOffset = this._u32(5);
|
||||
this.buf = b.slice(dataOffset); this.headerDone = true;
|
||||
return this._parse();
|
||||
}
|
||||
let o = 0;
|
||||
while (true) {
|
||||
if (o + 4 + 11 > len) break;
|
||||
const ts = o + 4;
|
||||
const tagType = b[ts] & 0x1f;
|
||||
const dataSize = (b[ts + 1] << 16) | (b[ts + 2] << 8) | b[ts + 3];
|
||||
const bodyStart = ts + 11, bodyEnd = bodyStart + dataSize;
|
||||
if (bodyEnd > len) break;
|
||||
if (tagType === 9) {
|
||||
const tsMs = ((b[ts + 7] << 24) >>> 0) | (b[ts + 4] << 16) | (b[ts + 5] << 8) | b[ts + 6];
|
||||
this._videoTag(b.subarray(bodyStart, bodyEnd), tsMs);
|
||||
}
|
||||
o = bodyEnd;
|
||||
}
|
||||
if (o > 0) this.buf = b.slice(o);
|
||||
}
|
||||
_videoTag(body, tsMs) {
|
||||
if (body.length < 5) return;
|
||||
const b0 = body[0], isEx = (b0 & 0x80) !== 0;
|
||||
if (isEx) {
|
||||
const frameType = (b0 >> 4) & 0x07, packetType = b0 & 0x0f;
|
||||
const fourcc = String.fromCharCode(body[1], body[2], body[3], body[4]);
|
||||
if (fourcc !== "hvc1" && fourcc !== "hev1") return;
|
||||
let off = 5;
|
||||
if (packetType === 1) off += 3;
|
||||
const payload = body.subarray(off);
|
||||
if (packetType === 0) this._config(payload);
|
||||
else if (packetType === 1 || packetType === 3) this._frames(payload, frameType === 1, tsMs);
|
||||
} else {
|
||||
const codecId = b0 & 0x0f, frameType = (b0 >> 4) & 0x0f;
|
||||
if (codecId !== 12 && codecId !== 7) return;
|
||||
const pkt = body[1], payload = body.subarray(5);
|
||||
if (pkt === 0) this._config(payload);
|
||||
else if (pkt === 1) this._frames(payload, frameType === 1, tsMs);
|
||||
}
|
||||
}
|
||||
_config(hvcC) {
|
||||
if (this.gotConfig || hvcC.length < 13) return;
|
||||
this.gotConfig = true;
|
||||
this.onConfig(hvcC.slice(), hevcCodecFromHvcC(hvcC));
|
||||
}
|
||||
_frames(payload, isKey, tsMs) {
|
||||
if (!this.gotConfig || payload.length === 0) return;
|
||||
this.onSample({ data: payload.slice(), type: isKey ? "key" : "delta", timestampUs: tsMs * 1000 });
|
||||
}
|
||||
}
|
||||
|
||||
// ── состояние ──
|
||||
let decoder = null, renderer = null, demux = null, ws = null;
|
||||
let statTimer = null, rafId = 0, latest = null;
|
||||
let fedAU = 0, decoded = 0, rendered = 0, gotInfo = false;
|
||||
|
||||
function stop() {
|
||||
if (statTimer) { clearInterval(statTimer); statTimer = null; }
|
||||
if (rafId) { cancelAnimationFrame(rafId); rafId = 0; }
|
||||
try { ws && ws.close(); } catch (e) {} ws = null;
|
||||
try { renderer && renderer.destroy(); } catch (e) {} renderer = null;
|
||||
try { decoder && decoder.destroy(); } catch (e) {} decoder = null;
|
||||
demux = null; latest = null;
|
||||
fedAU = decoded = rendered = 0; gotInfo = false;
|
||||
statEl.textContent = "";
|
||||
}
|
||||
|
||||
async function start(stream) {
|
||||
stop();
|
||||
const cv = document.getElementById("cv");
|
||||
log("создаю декодер…");
|
||||
try {
|
||||
decoder = await HEVCDecoder.create({
|
||||
wasmUrl: "/static/vendor/hevcjs/dist/wasm/hevc-decode.js",
|
||||
wasmBinaryUrl: "/static/vendor/hevcjs/dist/wasm/hevc-decode.wasm",
|
||||
});
|
||||
} catch (e) { log("‼ create:", e.message || e); return; }
|
||||
log("декодер готов");
|
||||
|
||||
renderer = new FrameRenderer();
|
||||
renderer.initCanvas(cv); // принудительно WebGL-путь (без MediaStreamTrackGenerator)
|
||||
log("FrameRenderer WebGL ок; supportsMediaStream=", FrameRenderer.supportsMediaStream);
|
||||
|
||||
demux = new FlvHevcDemuxer({
|
||||
onConfig: (hvcC, codec) => {
|
||||
log("config: codec=", codec, "hvcClen=", hvcC.length);
|
||||
const ps = hvccParamSetsToAnnexB(hvcC);
|
||||
log("param-sets Annex-B=", ps.length, "байт");
|
||||
try { if (ps.length) { decoder.feed(ps); pump(); } } catch (e) { log("‼ feed(ps):", e.message || e); }
|
||||
},
|
||||
onSample: ({ data, type, timestampUs }) => {
|
||||
fedAU++;
|
||||
try { decoder.feed(toAnnexB(data)); } catch (e) { log("‼ feed:", e.message || e); return; }
|
||||
pump();
|
||||
},
|
||||
});
|
||||
|
||||
const proto = location.protocol === "https:" ? "wss" : "ws";
|
||||
const url = `${proto}://${location.host}/api/cameras/cam32/flv?stream=${stream}`;
|
||||
log("WS →", url);
|
||||
ws = new WebSocket(url); ws.binaryType = "arraybuffer";
|
||||
ws.onopen = () => log("WS open");
|
||||
ws.onmessage = (e) => { try { demux.push(e.data); } catch (err) { log("‼ demux:", err.message || err); } };
|
||||
ws.onerror = () => log("WS error");
|
||||
ws.onclose = (ev) => log("WS closed", ev.code);
|
||||
|
||||
|
||||
statTimer = setInterval(() => {
|
||||
if (!gotInfo && decoder && decoder.info) { gotInfo = true; log("INFO:", JSON.stringify(decoder.info)); }
|
||||
statEl.textContent = `AU fed=${fedAU} декод=${decoded}/с показ=${rendered}/с`;
|
||||
log(`декод=${decoded}/с показ=${rendered}/с (AU=${fedAU})`);
|
||||
decoded = 0; rendered = 0;
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function pump() {
|
||||
let frames;
|
||||
try { frames = decoder.drain(); } catch (e) { log("‼ drain:", e.message || e); return; }
|
||||
for (const f of frames) { decoded++; try { renderer.renderFrame(f, decoded * 40000); rendered++; } catch (e) { log("‼ render:", e.message || e); } }
|
||||
}
|
||||
|
||||
document.getElementById("gomain").onclick = () => start("main");
|
||||
document.getElementById("gosub").onclick = () => start("sub");
|
||||
document.getElementById("stop").onclick = stop;
|
||||
log("загружено. secure=", isSecureContext, "| COI=", crossOriginIsolated, "| HEVCDecoderModule=", typeof globalThis.HEVCDecoderModule);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,81 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>hevc.js Worker (OffscreenCanvas) — CoRE.Vision</title>
|
||||
<style>
|
||||
body { background:#0d0d0d; color:#ddd; font:13px system-ui,Arial; margin:0; padding:12px; }
|
||||
#cv { background:#000; border:1px solid #333; display:block; margin:10px 0; width:100%; max-width:900px; height:auto; }
|
||||
#log { white-space:pre-wrap; font:12px Consolas,monospace; color:#9f9; max-height:240px; overflow:auto; }
|
||||
button { font:13px system-ui; padding:4px 10px; }
|
||||
#stat { color:#ffd479; font-weight:bold; margin-left:12px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div>
|
||||
<button id="gomain">▶ main 3200×1800</button>
|
||||
<button id="gosub">▶ sub 640×360</button>
|
||||
<button id="stop">⏹ Stop</button>
|
||||
<span id="stat"></span>
|
||||
</div>
|
||||
<canvas id="cv" width="1600" height="900"></canvas>
|
||||
<div id="log"></div>
|
||||
<script>
|
||||
const logEl = document.getElementById("log"), statEl = document.getElementById("stat");
|
||||
const log = (...a) => { logEl.textContent += a.map((x) => typeof x === "object" ? JSON.stringify(x) : String(x)).join(" ") + "\n"; logEl.scrollTop = 1e9; console.log("[hevcw]", ...a); };
|
||||
window.onerror = (m, s, l) => log("‼ onerror", m, "@", l);
|
||||
|
||||
let worker = null, ws = null;
|
||||
|
||||
function stop() {
|
||||
try { ws && ws.close(); } catch (e) {} ws = null;
|
||||
if (worker) { try { worker.postMessage({ type: "stop" }); } catch (e) {} worker.terminate(); worker = null; }
|
||||
statEl.textContent = "";
|
||||
}
|
||||
|
||||
function start(stream) {
|
||||
stop();
|
||||
// canvas можно отдать в OffscreenCanvas только один раз → пересоздаём элемент при каждом старте
|
||||
const old = document.getElementById("cv");
|
||||
const cv = document.createElement("canvas");
|
||||
cv.id = "cv";
|
||||
cv.width = stream === "main" ? 1600 : 640;
|
||||
cv.height = stream === "main" ? 900 : 360;
|
||||
old.replaceWith(cv);
|
||||
const off = cv.transferControlToOffscreen();
|
||||
|
||||
worker = new Worker("/static/vendor/hevcjs/hevc-player-worker.js", { type: "module" });
|
||||
worker.onmessage = (e) => {
|
||||
const m = e.data;
|
||||
if (m.type === "ready") { log("worker ready → открываю WS"); openWS(stream); }
|
||||
else if (m.type === "stat") { statEl.textContent = "декод/показ = " + m.fps + "/с"; if (m.fps) log("fps≈", m.fps); }
|
||||
else if (m.type === "err") { log("‼ worker:", m.msg); }
|
||||
};
|
||||
worker.onerror = (e) => log("‼ worker.onerror:", e.message, "@", (e.filename || "") + ":" + (e.lineno || ""));
|
||||
log("init worker (canvas " + cv.width + "x" + cv.height + ")");
|
||||
worker.postMessage({
|
||||
type: "init",
|
||||
canvas: off,
|
||||
wasmUrl: "/static/vendor/hevcjs/hevc-decode.esm.js",
|
||||
wasmBinaryUrl: "/static/vendor/hevcjs/dist/wasm/hevc-decode.wasm",
|
||||
}, [off]);
|
||||
}
|
||||
|
||||
function openWS(stream) {
|
||||
const proto = location.protocol === "https:" ? "wss" : "ws";
|
||||
const url = `${proto}://${location.host}/api/cameras/cam32/flv?stream=${stream}`;
|
||||
log("WS →", url);
|
||||
ws = new WebSocket(url); ws.binaryType = "arraybuffer";
|
||||
ws.onopen = () => log("WS open");
|
||||
ws.onmessage = (e) => { if (worker) worker.postMessage({ type: "data", buf: e.data }, [e.data]); };
|
||||
ws.onclose = (ev) => log("WS closed", ev.code);
|
||||
ws.onerror = () => log("WS error");
|
||||
}
|
||||
|
||||
document.getElementById("gomain").onclick = () => start("main");
|
||||
document.getElementById("gosub").onclick = () => start("sub");
|
||||
document.getElementById("stop").onclick = stop;
|
||||
log("загружено. secure=", isSecureContext, "| COI=", crossOriginIsolated);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,448 @@
|
||||
/* NVR UI — чистый тёмный интерфейс. Прототип компоновки iVMS-4200,
|
||||
но без перегруза: только то, что нужно для live и архива. */
|
||||
|
||||
:root {
|
||||
--bg: #0f1115;
|
||||
--panel: #161a22;
|
||||
--panel-2: #1d2230;
|
||||
--border: #272d3a;
|
||||
--text: #e6e9ef;
|
||||
--text-dim: #8b93a7;
|
||||
--accent: #3f0303; /* акцент: тёмно-красный */
|
||||
--accent-2: #2a0202; /* затемнённый вариант */
|
||||
--ok: #22c55e;
|
||||
--warn: #f59e0b;
|
||||
--err: #ef4444;
|
||||
--header-h: 48px;
|
||||
--sidebar-w: 240px;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
html, body {
|
||||
margin: 0; height: 100%;
|
||||
background: var(--bg); color: var(--text);
|
||||
font: 14px/1.4 -apple-system, "Segoe UI", Roboto, Arial, sans-serif;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* ── Шапка ── */
|
||||
header {
|
||||
height: var(--header-h); display: flex; align-items: center;
|
||||
padding: 0 14px; background: var(--panel); border-bottom: 1px solid var(--border);
|
||||
gap: 18px;
|
||||
}
|
||||
.brand { font-weight: 700; letter-spacing: .5px; color: #fff; }
|
||||
.brand span { color: #c0392b; }
|
||||
nav { display: flex; gap: 4px; }
|
||||
nav a {
|
||||
color: var(--text-dim); text-decoration: none; padding: 7px 14px;
|
||||
border-radius: 7px; font-weight: 500;
|
||||
}
|
||||
nav a:hover { background: var(--panel-2); color: var(--text); }
|
||||
nav a.active { background: var(--accent); color: #fff; }
|
||||
.spacer { flex: 1; }
|
||||
.stats { display: flex; gap: 16px; color: var(--text-dim); font-size: 12px; }
|
||||
.stats b { color: var(--text); font-weight: 600; }
|
||||
.clock { font-variant-numeric: tabular-nums; color: var(--text); }
|
||||
|
||||
/* ── Раскладка ── */
|
||||
.layout { display: flex; height: calc(100% - var(--header-h)); }
|
||||
aside {
|
||||
width: var(--sidebar-w); background: var(--panel); border-right: 1px solid var(--border);
|
||||
display: flex; flex-direction: column; overflow: hidden;
|
||||
}
|
||||
.aside-title {
|
||||
padding: 12px 14px 8px; font-size: 11px; text-transform: uppercase;
|
||||
letter-spacing: .8px; color: var(--text-dim);
|
||||
}
|
||||
/* ── Навигация в сайдбаре ── */
|
||||
.nav-item {
|
||||
display: flex; align-items: center; gap: 12px; padding: 12px 16px;
|
||||
color: var(--text-dim); text-decoration: none; font-weight: 500; font-size: 14px;
|
||||
border-left: 3px solid transparent; background: none; border-top: 0; border-right: 0;
|
||||
border-bottom: 0; cursor: pointer; width: 100%; text-align: left; font-family: inherit;
|
||||
}
|
||||
.nav-item:hover { background: var(--panel-2); color: var(--text); }
|
||||
.nav-item.active { background: var(--panel-2); color: #fff; border-left-color: #c0392b; }
|
||||
.nav-item .ico { font-size: 17px; line-height: 1; width: 20px; text-align: center; }
|
||||
.aside-spacer { flex: 1; }
|
||||
|
||||
/* Иконка настройки раскладки рядом с Live view */
|
||||
.navline { display: flex; align-items: center; }
|
||||
.nav-gear { padding: 12px 14px; color: var(--text-dim); text-decoration: none; font-size: 16px; }
|
||||
.nav-gear:hover { color: #fff; background: var(--panel-2); }
|
||||
.nav-gear.active { color: #fff; }
|
||||
|
||||
/* Подменю раскладок под "Live view" */
|
||||
.subnav { display: flex; flex-direction: column; padding: 2px 0 6px; }
|
||||
.subitem {
|
||||
padding: 6px 16px 6px 50px; color: var(--text-dim); text-decoration: none;
|
||||
font-size: 13px; border-left: 3px solid transparent;
|
||||
}
|
||||
.subitem:hover { background: var(--panel-2); color: var(--text); }
|
||||
.subitem.active { color: #fff; border-left-color: #c0392b; background: var(--panel-2); }
|
||||
.subitem.subfs { padding-left: 16px; margin-top: 4px; border-top: 1px solid var(--border); padding-top: 8px; }
|
||||
.subitem.subplay { padding-left: 16px; font-weight: 600; color: var(--text); margin-bottom: 4px; padding-bottom: 8px; border-bottom: 1px solid var(--border); }
|
||||
.app-version { padding: 8px 16px; font-size: 11px; color: var(--text-dim); }
|
||||
.nav-item.logout { color: var(--text-dim); border-top: 1px solid var(--border); }
|
||||
.nav-item.logout:hover { color: #e57373; }
|
||||
|
||||
/* ── Чипы камер (Live toolbar) ── */
|
||||
.cam-chips { display: flex; gap: 6px; flex-wrap: wrap; }
|
||||
.chip {
|
||||
display: inline-flex; align-items: center; gap: 7px; padding: 5px 11px;
|
||||
border: 1px solid var(--border); border-radius: 15px; background: var(--panel-2);
|
||||
cursor: pointer; font-size: 13px; color: var(--text);
|
||||
}
|
||||
.chip:hover { border-color: #c0392b; }
|
||||
.chip.active { background: var(--accent); border-color: #c0392b; color: #fff; }
|
||||
|
||||
#cam-list { flex: 1; overflow-y: auto; } /* legacy, на случай переиспользования */
|
||||
main { flex: 1; min-height: 0; min-width: 0; display: flex; flex-direction: column; overflow: hidden; }
|
||||
|
||||
/* ── Список камер ── */
|
||||
.cam-item {
|
||||
display: flex; align-items: center; gap: 10px; padding: 9px 14px;
|
||||
cursor: pointer; border-left: 3px solid transparent;
|
||||
}
|
||||
.cam-item:hover { background: var(--panel-2); }
|
||||
.cam-item.active { background: var(--panel-2); border-left-color: var(--accent); }
|
||||
.cam-item .name { flex: 1; font-weight: 500; }
|
||||
.cam-item .ip { font-size: 11px; color: var(--text-dim); }
|
||||
.dot { width: 9px; height: 9px; border-radius: 50%; background: var(--text-dim); flex: none; }
|
||||
.dot.online { background: var(--ok); box-shadow: 0 0 6px var(--ok); }
|
||||
.dot.retrying { background: var(--warn); animation: pulse 1.2s infinite; }
|
||||
.dot.offline, .dot.starting { background: var(--text-dim); }
|
||||
@keyframes pulse { 50% { opacity: .35; } }
|
||||
|
||||
/* ── Тулбар ── */
|
||||
.toolbar {
|
||||
display: flex; align-items: center; gap: 10px; padding: 8px 14px;
|
||||
background: var(--panel); border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.toolbar .group { display: flex; gap: 4px; }
|
||||
button, .btn {
|
||||
background: var(--panel-2); color: var(--text); border: 1px solid var(--border);
|
||||
padding: 6px 11px; border-radius: 6px; cursor: pointer; font-size: 13px;
|
||||
}
|
||||
button:hover, .btn:hover { border-color: var(--accent); }
|
||||
button.active { background: var(--accent); border-color: var(--accent); color: #fff; }
|
||||
.toggle { display: flex; align-items: center; gap: 10px; color: var(--text-dim); cursor: pointer; }
|
||||
|
||||
/* Переключатели в виде тумблеров (off — серый, on — зелёный) */
|
||||
input[type="checkbox"] {
|
||||
appearance: none; -webkit-appearance: none; margin: 0;
|
||||
width: 40px; height: 22px; flex: none; border-radius: 11px;
|
||||
background: var(--panel-2); border: 1px solid var(--border);
|
||||
position: relative; cursor: pointer; transition: background .15s, border-color .15s;
|
||||
}
|
||||
input[type="checkbox"]::before {
|
||||
content: ""; position: absolute; top: 2px; left: 2px;
|
||||
width: 16px; height: 16px; border-radius: 50%;
|
||||
background: var(--text-dim); transition: transform .15s, background .15s;
|
||||
}
|
||||
input[type="checkbox"]:checked {
|
||||
background: rgba(34, 197, 94, .25); border-color: var(--ok);
|
||||
}
|
||||
input[type="checkbox"]:checked::before { transform: translateX(18px); background: var(--ok); }
|
||||
input[type="checkbox"]:focus-visible { outline: 2px solid var(--ok); outline-offset: 2px; }
|
||||
input[type="date"], select {
|
||||
background: var(--panel-2); color: var(--text); border: 1px solid var(--border);
|
||||
padding: 6px 8px; border-radius: 6px;
|
||||
}
|
||||
|
||||
/* ── Сетка видео ── */
|
||||
.grid {
|
||||
flex: 1; min-height: 0; min-width: 0; display: grid; gap: 4px; padding: 4px;
|
||||
background: #000; overflow: hidden;
|
||||
grid-auto-rows: 1fr; grid-auto-columns: 1fr; /* все дорожки строго равны */
|
||||
}
|
||||
.tile {
|
||||
position: relative; background: #05070a; border: 1px solid var(--border);
|
||||
display: flex; align-items: center; justify-content: center; overflow: hidden;
|
||||
min-height: 0; min-width: 0; /* не растягиваться под видео */
|
||||
}
|
||||
.tile .hevc-player { position: absolute; inset: 0; width: 100%; height: 100%; background: #000; }
|
||||
.tile .hevc-player canvas { width: 100%; height: 100%; display: block; }
|
||||
/* canvas WASM/WebCodecs-плеера: вписываем кадр в ячейку с сохранением пропорций */
|
||||
.wc-canvas { width: 100%; height: 100%; display: block; object-fit: contain; background: #000; }
|
||||
.tile video, .tile video-stream {
|
||||
display: block; width: 100%; height: 100%; max-width: 100%; max-height: 100%;
|
||||
object-fit: contain; background: #000;
|
||||
}
|
||||
.tile .label {
|
||||
position: absolute; left: 0; top: 0; padding: 3px 9px; font-size: 12px;
|
||||
background: rgba(0,0,0,.55); border-bottom-right-radius: 6px; pointer-events: none;
|
||||
}
|
||||
.tile .label .dot { display: inline-block; vertical-align: middle; margin-right: 6px; }
|
||||
.tile .empty { color: var(--text-dim); font-size: 13px; }
|
||||
.tile .no-link {
|
||||
font-family: Georgia, "Times New Roman", serif; font-weight: 700;
|
||||
font-size: clamp(16px, 3.2vw, 40px); letter-spacing: 3px; color: #9a9a9a;
|
||||
text-shadow: 0 1px 0 #000, 0 0 6px rgba(0,0,0,.6); user-select: none;
|
||||
}
|
||||
.tile-btn {
|
||||
position: absolute; top: 4px; right: 4px; z-index: 2; padding: 2px 8px; font-size: 11px;
|
||||
background: rgba(0,0,0,.55); border: 1px solid var(--border); color: var(--text);
|
||||
border-radius: 5px; cursor: pointer; opacity: .7;
|
||||
}
|
||||
.tile-btn:hover { opacity: 1; border-color: #c0392b; }
|
||||
.tile-btn.active { background: var(--accent); border-color: #c0392b; color: #fff; opacity: 1; }
|
||||
.tile:fullscreen { border: none; background: #000; }
|
||||
.tile:fullscreen video, .tile:fullscreen video-stream { object-fit: contain; }
|
||||
#grid:fullscreen { width: 100vw; height: 100vh; background: var(--bg); padding: 0; }
|
||||
.hevc-hint {
|
||||
position: absolute; left: 0; right: 0; bottom: 0; z-index: 3;
|
||||
background: rgba(63, 3, 3, .88); color: #fff; font-size: 11px;
|
||||
padding: 5px 8px; text-align: center; line-height: 1.3;
|
||||
}
|
||||
|
||||
/* ── Архив ── */
|
||||
.archive-main { flex: 1; display: flex; flex-direction: column; overflow: hidden; }
|
||||
.player-wrap { flex: 1; background: #000; display: flex; align-items: center; justify-content: center; min-height: 0; }
|
||||
.player-wrap video { max-width: 100%; max-height: 100%; }
|
||||
.player-wrap .hint { color: var(--text-dim); }
|
||||
|
||||
/* ── плеер архива в стиле Playerjs ── */
|
||||
.player-wrap .pjs { position: relative; width: 100%; height: 100%; background: #000; outline: none; overflow: hidden; }
|
||||
.pjs-video { width: 100%; height: 100%; display: block; object-fit: contain; background: #000; cursor: pointer; }
|
||||
/* центр: большая кнопка play (на паузе) + спиннер (при буферизации) */
|
||||
.pjs-center { position: absolute; inset: 0; pointer-events: none; }
|
||||
.pjs-bigplay {
|
||||
position: absolute; top: 50%; left: 50%; width: 74px; height: 74px; border-radius: 50%;
|
||||
border: none; cursor: pointer; pointer-events: auto; background: rgba(10,12,18,.55); color: #fff;
|
||||
font-size: 26px; padding-left: 5px; opacity: 0; transition: opacity .15s, transform .15s;
|
||||
transform: translate(-50%, -50%) scale(.9);
|
||||
}
|
||||
.pjs.paused:not(.buffering) .pjs-bigplay { opacity: 1; transform: translate(-50%, -50%) scale(1); }
|
||||
.pjs-bigplay:hover { background: rgba(10,12,18,.82); }
|
||||
.pjs-spinner {
|
||||
position: absolute; top: 50%; left: 50%; width: 46px; height: 46px; margin: -23px 0 0 -23px;
|
||||
border: 3px solid rgba(255,255,255,.22); border-top-color: #fff; border-radius: 50%; opacity: 0;
|
||||
}
|
||||
.pjs.buffering .pjs-spinner { opacity: 1; animation: pjs-spin .8s linear infinite; }
|
||||
@keyframes pjs-spin { to { transform: rotate(360deg); } }
|
||||
/* нижняя панель управления */
|
||||
.pjs-bar {
|
||||
position: absolute; left: 0; right: 0; bottom: 0; z-index: 5;
|
||||
display: flex; align-items: center; gap: 10px; padding: 26px 14px 11px;
|
||||
background: linear-gradient(transparent, rgba(0,0,0,.8));
|
||||
opacity: 0; transform: translateY(8px); transition: opacity .2s, transform .2s;
|
||||
}
|
||||
.pjs.show .pjs-bar, .pjs:hover .pjs-bar, .pjs.paused .pjs-bar { opacity: 1; transform: none; }
|
||||
.pjs-btn {
|
||||
background: none; border: none; color: #fff; cursor: pointer; font-size: 16px; line-height: 1;
|
||||
padding: 5px 7px; border-radius: 5px; opacity: .9; transition: background .12s, opacity .12s;
|
||||
}
|
||||
.pjs-btn:hover { opacity: 1; background: rgba(255,255,255,.14); }
|
||||
.pjs-time, .pjs-dur { color: #fff; font-size: 12px; font-variant-numeric: tabular-nums; min-width: 40px; text-align: center; opacity: .92; }
|
||||
/* шкала перемотки */
|
||||
.pjs-seek { position: relative; flex: 1; height: 5px; border-radius: 3px; background: rgba(255,255,255,.25); cursor: pointer; touch-action: none; }
|
||||
.pjs-seek:hover { height: 7px; }
|
||||
.pjs-buf { position: absolute; left: 0; top: 0; bottom: 0; width: 0; background: rgba(255,255,255,.35); border-radius: 3px; }
|
||||
.pjs-prog { position: absolute; left: 0; top: 0; bottom: 0; width: 0; background: #e23b3b; border-radius: 3px; }
|
||||
.pjs-knob {
|
||||
position: absolute; top: 50%; width: 13px; height: 13px; margin-left: -6.5px; border-radius: 50%;
|
||||
background: #e23b3b; box-shadow: 0 0 4px rgba(0,0,0,.5); transform: translateY(-50%) scale(0); transition: transform .12s;
|
||||
}
|
||||
.pjs-seek:hover .pjs-knob, .pjs.show .pjs-knob { transform: translateY(-50%) scale(1); }
|
||||
.pjs.fs:not(.show) { cursor: none; }
|
||||
|
||||
/* DVR-таймлайн архива: лента тащится мышью/колесом, красный указатель зафиксирован по центру */
|
||||
.timeline {
|
||||
height: 96px; background: var(--panel); border-top: 1px solid var(--border);
|
||||
overflow: hidden; position: relative; cursor: grab; user-select: none; touch-action: none;
|
||||
}
|
||||
.timeline.grabbing { cursor: grabbing; }
|
||||
.tl-track { position: absolute; top: 0; bottom: 0; left: 0; will-change: transform; }
|
||||
/* деления времени */
|
||||
.tl-tick { position: absolute; top: 0; bottom: 0; width: 0; border-left: 1px solid var(--border); }
|
||||
.tl-tick.hour { border-left-color: #3a4254; }
|
||||
.tl-tick > span {
|
||||
position: absolute; top: 7px; left: 5px; font-size: 11px; color: var(--text-dim);
|
||||
font-variant-numeric: tabular-nums; white-space: nowrap;
|
||||
}
|
||||
.tl-tick.hour > span { color: var(--text); }
|
||||
/* полоса записей (жёлтая) */
|
||||
.tl-seg {
|
||||
position: absolute; top: 36px; height: 40px; background: #e9c46a; border-radius: 2px;
|
||||
}
|
||||
.tl-seg.active { background: #f4a261; }
|
||||
/* маркер «эфир» (текущее время; движется вместе с лентой) */
|
||||
.tl-now { position: absolute; top: 0; bottom: 0; width: 0; border-left: 2px dashed var(--ok); z-index: 3; }
|
||||
.tl-now > span {
|
||||
position: absolute; top: 7px; left: 4px; font-size: 10px; font-weight: 700; color: var(--ok); white-space: nowrap;
|
||||
}
|
||||
/* фиксированный красный указатель по центру (playhead) */
|
||||
.tl-center { position: absolute; left: 50%; top: 0; bottom: 0; width: 0; border-left: 2px solid #e03131; z-index: 6; pointer-events: none; }
|
||||
.tl-center::after {
|
||||
content: ""; position: absolute; top: 0; left: 0; transform: translateX(-50%);
|
||||
border: 6px solid transparent; border-top-color: #e03131; border-bottom: 0;
|
||||
}
|
||||
.tl-center > span {
|
||||
position: absolute; top: 6px; left: 0; transform: translateX(-50%);
|
||||
font-size: 11px; font-weight: 700; color: #fff; background: #e03131;
|
||||
padding: 1px 6px; border-radius: 3px; white-space: nowrap; font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.tl-empty {
|
||||
position: absolute; left: 0; right: 0; top: 50%; transform: translateY(-50%);
|
||||
text-align: center; color: var(--text-dim); pointer-events: none;
|
||||
}
|
||||
|
||||
.muted { color: var(--text-dim); }
|
||||
.empty-state { padding: 40px; text-align: center; color: var(--text-dim); }
|
||||
|
||||
/* ── Редактор раскладки ── */
|
||||
.layout-grid { display: grid; gap: 8px; }
|
||||
.lcell { background: var(--panel-2); border: 1px solid var(--border); border-radius: 8px; padding: 10px; }
|
||||
.lcell-no { font-size: 11px; color: var(--text-dim); margin-bottom: 6px; }
|
||||
.lcell select { width: 100%; }
|
||||
|
||||
/* ── Страница входа ── */
|
||||
.login-body {
|
||||
display: flex; align-items: center; justify-content: center; height: 100%;
|
||||
background: radial-gradient(circle at 50% 30%, #1a1014, var(--bg));
|
||||
}
|
||||
.login-card {
|
||||
width: 320px; background: var(--panel); border: 1px solid var(--border);
|
||||
border-radius: 12px; padding: 28px 26px; display: flex; flex-direction: column; gap: 12px;
|
||||
box-shadow: 0 12px 40px rgba(0,0,0,.5);
|
||||
}
|
||||
.login-brand { font-size: 26px; text-align: center; }
|
||||
.login-sub { text-align: center; color: var(--text-dim); font-size: 13px; margin-bottom: 8px; }
|
||||
.login-card input {
|
||||
background: var(--panel-2); color: var(--text); border: 1px solid var(--border);
|
||||
padding: 11px 13px; border-radius: 7px; font-size: 14px;
|
||||
}
|
||||
.login-card input:focus { outline: none; border-color: #c0392b; }
|
||||
.login-card button {
|
||||
background: var(--accent); border: 1px solid #c0392b; color: #fff; font-weight: 600;
|
||||
padding: 11px; border-radius: 7px; cursor: pointer; margin-top: 4px;
|
||||
}
|
||||
.login-card button:hover { background: var(--accent-2); }
|
||||
.login-err { color: #e57373; font-size: 13px; text-align: center; min-height: 18px; }
|
||||
|
||||
/* ── Настройки ── */
|
||||
.settings-main { flex: 1; overflow-y: auto; padding: 20px; }
|
||||
.settings-main .wrap { max-width: 920px; margin: 0 auto; }
|
||||
|
||||
/* Вкладки (как в браузере) */
|
||||
.tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--border); margin-bottom: 18px; }
|
||||
.tab {
|
||||
background: none; border: none; border-bottom: 2px solid transparent; border-radius: 0;
|
||||
color: var(--text-dim); padding: 10px 18px; cursor: pointer; font-size: 14px; font-weight: 500;
|
||||
}
|
||||
.tab:hover { color: var(--text); }
|
||||
.tab.active { color: #fff; border-bottom-color: #c0392b; }
|
||||
.tab-panel[hidden] { display: none; }
|
||||
.tr-row { display: flex; gap: 16px; margin-top: 10px; flex-wrap: wrap; padding-left: 28px; }
|
||||
.tr-row[hidden] { display: none; }
|
||||
.tr-row label { display: flex; flex-direction: column; gap: 5px; font-size: 12px; color: var(--text-dim); }
|
||||
.tr-row select { display: block; }
|
||||
/* общие пресеты перекодирования (SOFT / MEDIUM / HARD) */
|
||||
.tr-presets { flex-basis: 100%; display: flex; align-items: center; gap: 8px; padding-left: 28px; }
|
||||
.tr-preset {
|
||||
padding: 4px 12px; font-size: 12px; font-weight: 600; border-radius: 6px;
|
||||
background: var(--panel-2); color: var(--text-dim); border: 1px solid var(--border); cursor: pointer;
|
||||
}
|
||||
.tr-preset[data-preset="SOFT"] { color: #e03131; }
|
||||
.tr-preset[data-preset="MEDIUM"] { color: #e9c46a; }
|
||||
.tr-preset[data-preset="HARD"] { color: #ffffff; }
|
||||
.tr-preset.active { background: var(--accent); color: #fff; border-color: var(--accent); }
|
||||
/* блок профиля: режим (свой плеер / перекодировать) + ряд параметров */
|
||||
.tr-block { padding: 12px 0; border-top: 1px solid var(--border); }
|
||||
.tr-block:first-of-type { border-top: none; padding-top: 0; }
|
||||
.tr-block h3 { margin: 0 0 8px; font-size: 13px; font-weight: 600; color: var(--text); }
|
||||
/* 3-позиционный сегментированный переключатель режима */
|
||||
.seg-toggle {
|
||||
display: inline-flex; border: 1px solid var(--border); border-radius: 8px;
|
||||
overflow: hidden; background: var(--panel-2);
|
||||
}
|
||||
.seg-toggle label {
|
||||
display: flex; align-items: center; cursor: pointer; border-right: 1px solid var(--border);
|
||||
}
|
||||
.seg-toggle label:last-child { border-right: none; }
|
||||
.seg-toggle input[type="radio"] { position: absolute; opacity: 0; width: 0; height: 0; margin: 0; pointer-events: none; }
|
||||
.seg-toggle span {
|
||||
padding: 7px 14px; font-size: 13px; color: var(--text-dim);
|
||||
white-space: nowrap; transition: background .12s, color .12s;
|
||||
}
|
||||
.seg-toggle label:hover span { color: var(--text); }
|
||||
.seg-toggle input:checked + span { background: var(--accent); color: #fff; }
|
||||
.tab[hidden], .card[hidden] { display: none; }
|
||||
.card {
|
||||
background: var(--panel); border: 1px solid var(--border); border-radius: 10px;
|
||||
padding: 16px 18px; margin-bottom: 18px;
|
||||
}
|
||||
.card h2 { margin: 0 0 14px; font-size: 15px; font-weight: 600; }
|
||||
.card-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 14px; }
|
||||
.card-head h2 { margin: 0; }
|
||||
|
||||
/* ── Модальное окно ── */
|
||||
.modal-overlay {
|
||||
position: fixed; inset: 0; background: rgba(0,0,0,.6); z-index: 50;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.modal {
|
||||
width: 440px; max-width: calc(100vw - 32px); background: var(--panel);
|
||||
border: 1px solid var(--border); border-radius: 12px; padding: 22px 24px;
|
||||
box-shadow: 0 16px 50px rgba(0,0,0,.55);
|
||||
}
|
||||
.modal h3 { margin: 0 0 18px; font-size: 17px; }
|
||||
.modal .field { display: flex; flex-direction: column; gap: 5px; margin-bottom: 12px; }
|
||||
.modal .row2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||
.modal label.fl { color: var(--text-dim); font-size: 12px; }
|
||||
.modal input[type="text"], .modal input[type="password"] {
|
||||
background: var(--panel-2); color: var(--text); border: 1px solid var(--border);
|
||||
padding: 9px 11px; border-radius: 7px; font-size: 14px; width: 100%;
|
||||
}
|
||||
.modal input[type="text"]:focus, .modal input[type="password"]:focus { outline: none; border-color: #c0392b; }
|
||||
.modal input:disabled { opacity: .5; }
|
||||
.modal .switch-field { flex-direction: row; align-items: center; gap: 10px; }
|
||||
.modal .err { color: #e57373; font-size: 13px; min-height: 18px; margin-bottom: 4px; }
|
||||
.modal .actions { display: flex; justify-content: flex-end; gap: 8px; }
|
||||
.modal #modal-save { background: var(--accent); border-color: #c0392b; color: #fff; font-weight: 600; }
|
||||
.modal #modal-save:hover { background: var(--accent-2); }
|
||||
.kv { display: grid; grid-template-columns: 200px 1fr; gap: 8px 16px; }
|
||||
.kv .k { color: var(--text-dim); }
|
||||
.kv .v { font-variant-numeric: tabular-nums; }
|
||||
table.cams { width: 100%; border-collapse: collapse; }
|
||||
table.cams th, table.cams td {
|
||||
text-align: left; padding: 2px 10px; border-bottom: 1px solid var(--border);
|
||||
font-size: 12px; line-height: 1.35;
|
||||
}
|
||||
table.cams th { color: var(--text-dim); font-weight: 500; font-size: 11px; padding: 4px 10px; }
|
||||
table.cams td.actions { white-space: nowrap; text-align: right; }
|
||||
table.cams tr.slot-empty td { opacity: .5; }
|
||||
/* строка-контейнер лога не должна занимать высоту, пока лог скрыт */
|
||||
table.cams tr.logrow > td { padding: 0; border: none; }
|
||||
|
||||
/* ── Инлайн-редактор строки (вместо всплывающего окна) ── */
|
||||
.cam-edit { background: var(--panel-2); padding: 12px 12px 14px; }
|
||||
.cam-edit-grid { display: flex; flex-wrap: wrap; gap: 10px 14px; align-items: flex-end; }
|
||||
.cam-edit-grid label { display: flex; flex-direction: column; gap: 4px; font-size: 11px; color: var(--text-dim); }
|
||||
.cam-edit-grid input[type="text"], .cam-edit-grid input[type="password"] {
|
||||
background: var(--panel); border: 1px solid var(--border); color: var(--text);
|
||||
padding: 7px 9px; border-radius: 6px; font-size: 13px; width: 150px;
|
||||
}
|
||||
.cam-edit-grid #e-id, .cam-edit-grid #e-ip { width: 130px; }
|
||||
.cam-edit-grid #e-main, .cam-edit-grid #e-sub { width: 178px; }
|
||||
.cam-edit-grid input:focus { outline: none; border-color: #c0392b; }
|
||||
.cam-edit-grid input:disabled { opacity: .5; }
|
||||
.cam-edit-grid label.sw { flex-direction: row; align-items: center; gap: 8px; color: var(--text); }
|
||||
.cam-edit-foot { display: flex; align-items: center; gap: 10px; margin-top: 12px; }
|
||||
.cam-edit-foot .err { color: #e57373; font-size: 12px; flex: 1; }
|
||||
.cam-edit-foot [data-act="save-edit"] { background: var(--accent); border-color: #c0392b; color: #fff; font-weight: 600; }
|
||||
.cam-bulk-head { font-size: 11px; color: var(--text-dim); margin-bottom: 8px; letter-spacing: .3px; }
|
||||
button.primary { background: var(--accent); border-color: #c0392b; color: #fff; font-weight: 600; }
|
||||
table.cams td.actions button { padding: 2px 8px; font-size: 12px; }
|
||||
.badge {
|
||||
display: inline-flex; align-items: center; gap: 6px; padding: 2px 9px;
|
||||
border-radius: 11px; font-size: 12px; background: var(--panel-2);
|
||||
}
|
||||
.logbox {
|
||||
margin: 4px 10px 12px; padding: 10px; background: #05070a; border: 1px solid var(--border);
|
||||
border-radius: 6px; font-family: ui-monospace, "Cascadia Code", Consolas, monospace;
|
||||
font-size: 12px; color: var(--text-dim); white-space: pre-wrap; max-height: 220px; overflow: auto;
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
import type { HEVCFrame, HEVCStreamInfo, DecodeResult, DecoderOptions } from "./types.js";
|
||||
/**
|
||||
* HEVC/H.265 Decoder — JavaScript wrapper for the WASM module.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const decoder = await HEVCDecoder.create();
|
||||
* const { frames, info } = decoder.decode(bitstreamBytes);
|
||||
* console.log(`${info.width}x${info.height}, ${frames.length} frames`);
|
||||
* decoder.destroy();
|
||||
* ```
|
||||
*/
|
||||
export declare class HEVCDecoder {
|
||||
private _m;
|
||||
private _api;
|
||||
private _dec;
|
||||
private constructor();
|
||||
/**
|
||||
* Create a new decoder instance. Loads the WASM module.
|
||||
*/
|
||||
static create(options?: DecoderOptions): Promise<HEVCDecoder>;
|
||||
/**
|
||||
* Decode a complete HEVC bitstream.
|
||||
* @param data Raw .265 bitstream bytes
|
||||
*/
|
||||
decode(data: Uint8Array): DecodeResult;
|
||||
/** Number of decoded frames available */
|
||||
get frameCount(): number;
|
||||
/** Get stream info (available after decode) */
|
||||
get info(): HEVCStreamInfo | null;
|
||||
private _extractFrame;
|
||||
private _extractDrainedFrame;
|
||||
private _readFrameFromPtr;
|
||||
private _extractInfo;
|
||||
/**
|
||||
* Feed a chunk of data containing one or more complete NAL units.
|
||||
* The decoder accumulates parameter sets and decodes pictures incrementally.
|
||||
* Call drain() after each feed() to retrieve output-ready frames.
|
||||
*/
|
||||
feed(data: Uint8Array): void;
|
||||
/**
|
||||
* Drain output-ready frames from the decoder (§C.5.2 bumping process).
|
||||
* Returns frames in display order, only when ready per DPB constraints.
|
||||
* Frames are valid until the next feed() or destroy() call.
|
||||
*/
|
||||
drain(): HEVCFrame[];
|
||||
/**
|
||||
* Flush all remaining frames from the DPB (call at end of stream).
|
||||
* Returns all buffered frames in display order.
|
||||
*/
|
||||
flush(): HEVCFrame[];
|
||||
/** Release decoder resources */
|
||||
destroy(): void;
|
||||
}
|
||||
//# sourceMappingURL=decoder.d.ts.map
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
export { HEVCDecoder } from "./decoder.js";
|
||||
export type { HEVCFrame, HEVCStreamInfo, DecodeResult, DecoderOptions, WorkerRequest, WorkerResponse, } from "./types.js";
|
||||
export { H264Encoder } from "./h264-encoder.js";
|
||||
export type { H264EncoderConfig, EncodedChunk } from "./h264-encoder.js";
|
||||
export { FrameRenderer } from "./renderer.js";
|
||||
export { FMP4Demuxer } from "./fmp4-demuxer.js";
|
||||
export type { DemuxedSample, VideoTrackInfo } from "./fmp4-demuxer.js";
|
||||
export { FMP4Muxer } from "./fmp4-muxer.js";
|
||||
export type { MuxerInitConfig, MuxerSample } from "./fmp4-muxer.js";
|
||||
export { MSEController } from "./mse-controller.js";
|
||||
export { TranscodePipeline } from "./transcode-pipeline.js";
|
||||
export type { TranscodePipelineConfig } from "./transcode-pipeline.js";
|
||||
export { setLogLevel } from "./log.js";
|
||||
export type { LogLevel } from "./log.js";
|
||||
export { installMSEIntercept, uninstallMSEIntercept } from "./mse-intercept.js";
|
||||
export type { MSEInterceptConfig } from "./mse-intercept.js";
|
||||
export { SegmentTranscoder } from "./segment-transcoder.js";
|
||||
export type { SegmentTranscoderConfig, TranscodedInit } from "./segment-transcoder.js";
|
||||
export { TranscodeWorkerClient } from "./transcode-worker-client.js";
|
||||
export type { TranscodeWorkerClientConfig } from "./transcode-worker-client.js";
|
||||
export { hevcMimeToH264Codec } from "./codec-mapping.js";
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
+2227
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* YUV Frame Renderer — converts decoded YUV frames to displayable video.
|
||||
*
|
||||
* Uses VideoFrame + MediaStreamTrackGenerator when available (Chrome 94+),
|
||||
* falls back to WebGL canvas rendering.
|
||||
*/
|
||||
import type { HEVCFrame } from "./types.js";
|
||||
/**
|
||||
* Renderer that converts YUV frames to a <video>-compatible MediaStream
|
||||
* or renders directly to a canvas.
|
||||
*/
|
||||
export declare class FrameRenderer {
|
||||
private _generator;
|
||||
private _writer;
|
||||
private _canvas;
|
||||
private _gl;
|
||||
private _program;
|
||||
private _texY;
|
||||
private _texCb;
|
||||
private _texCr;
|
||||
/**
|
||||
* Check if MediaStreamTrackGenerator is available (Chrome 94+).
|
||||
* When available, frames can be piped to a <video> element.
|
||||
*/
|
||||
static get supportsMediaStream(): boolean;
|
||||
/**
|
||||
* Get a MediaStream that can be assigned to a <video>.srcObject.
|
||||
* Only available when supportsMediaStream is true.
|
||||
*/
|
||||
getMediaStream(): MediaStream | null;
|
||||
/**
|
||||
* Render a decoded YUV frame.
|
||||
*
|
||||
* If MediaStreamTrackGenerator is available, creates a VideoFrame and writes it.
|
||||
* Otherwise, renders to the provided canvas via WebGL.
|
||||
*/
|
||||
renderFrame(frame: HEVCFrame, timestamp: number): Promise<void>;
|
||||
/**
|
||||
* Initialize WebGL canvas fallback.
|
||||
* Call this if MediaStreamTrackGenerator is not supported.
|
||||
*/
|
||||
initCanvas(canvas: HTMLCanvasElement | OffscreenCanvas): void;
|
||||
private _renderToVideoFrame;
|
||||
private _initWebGL;
|
||||
private _renderToWebGL;
|
||||
/** Release all resources */
|
||||
destroy(): void;
|
||||
}
|
||||
//# sourceMappingURL=renderer.d.ts.map
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
/** Decoded YUV frame — planes are copied out of WASM heap */
|
||||
export interface HEVCFrame {
|
||||
/** Luma plane (packed, no stride) */
|
||||
y: Uint16Array;
|
||||
/** Chroma Cb plane */
|
||||
cb: Uint16Array;
|
||||
/** Chroma Cr plane */
|
||||
cr: Uint16Array;
|
||||
/** Luma width (display, after conformance crop) */
|
||||
width: number;
|
||||
/** Luma height (display) */
|
||||
height: number;
|
||||
/** Chroma plane width */
|
||||
chromaWidth: number;
|
||||
/** Chroma plane height */
|
||||
chromaHeight: number;
|
||||
/** Bit depth (8 or 10) */
|
||||
bitDepth: number;
|
||||
/** Picture Order Count (display order) */
|
||||
poc: number;
|
||||
}
|
||||
/** Stream metadata — available after first decode */
|
||||
export interface HEVCStreamInfo {
|
||||
width: number;
|
||||
height: number;
|
||||
bitDepth: number;
|
||||
/** 0=mono, 1=4:2:0, 2=4:2:2, 3=4:4:4 */
|
||||
chromaFormat: number;
|
||||
/** Profile IDC (1=Main, 2=Main10) */
|
||||
profile: number;
|
||||
/** Level IDC (e.g. 93 = Level 3.1) */
|
||||
level: number;
|
||||
}
|
||||
/** Result of a decode call */
|
||||
export interface DecodeResult {
|
||||
frames: HEVCFrame[];
|
||||
info: HEVCStreamInfo | null;
|
||||
}
|
||||
/** Options for creating a decoder */
|
||||
export interface DecoderOptions {
|
||||
/** URL to the hevc-decode.js WASM glue file. Auto-resolved if omitted. */
|
||||
wasmUrl?: string;
|
||||
/** URL to the .wasm binary. Auto-resolved if omitted. */
|
||||
wasmBinaryUrl?: string;
|
||||
}
|
||||
/** Worker message types (main → worker) */
|
||||
export type WorkerRequest = {
|
||||
type: "init";
|
||||
wasmUrl: string;
|
||||
} | {
|
||||
type: "decode";
|
||||
data: ArrayBuffer;
|
||||
} | {
|
||||
type: "feed";
|
||||
data: ArrayBuffer;
|
||||
} | {
|
||||
type: "drain";
|
||||
} | {
|
||||
type: "flush";
|
||||
} | {
|
||||
type: "destroy";
|
||||
};
|
||||
/** Worker message types (worker → main) */
|
||||
export type WorkerResponse = {
|
||||
type: "ready";
|
||||
} | {
|
||||
type: "info";
|
||||
info: HEVCStreamInfo;
|
||||
} | {
|
||||
type: "frame";
|
||||
index: number;
|
||||
frame: HEVCFrame;
|
||||
} | {
|
||||
type: "done";
|
||||
frameCount: number;
|
||||
} | {
|
||||
type: "drained";
|
||||
frames: HEVCFrame[];
|
||||
} | {
|
||||
type: "flushed";
|
||||
frames: HEVCFrame[];
|
||||
} | {
|
||||
type: "error";
|
||||
message: string;
|
||||
};
|
||||
//# sourceMappingURL=types.d.ts.map
|
||||
File diff suppressed because one or more lines are too long
Binary file not shown.
+408
@@ -0,0 +1,408 @@
|
||||
// src/decoder.ts
|
||||
var HEVCDecoder = class _HEVCDecoder {
|
||||
constructor(module) {
|
||||
this._m = module;
|
||||
this._api = {
|
||||
create: module.cwrap("hevc_decoder_create", "number", []),
|
||||
destroy: module.cwrap("hevc_decoder_destroy", null, ["number"]),
|
||||
decode: module.cwrap("hevc_decoder_decode", "number", ["number", "number", "number"]),
|
||||
getFrameCount: module.cwrap("hevc_decoder_get_frame_count", "number", ["number"]),
|
||||
getFrame: module.cwrap("hevc_decoder_get_frame", "number", ["number", "number", "number"]),
|
||||
getInfo: module.cwrap("hevc_decoder_get_info", "number", ["number", "number"]),
|
||||
feed: module.cwrap("hevc_decoder_feed", "number", ["number", "number", "number"]),
|
||||
drain: module.cwrap("hevc_decoder_drain", "number", ["number", "number"]),
|
||||
getDrainedFrame: module.cwrap("hevc_decoder_get_drained_frame", "number", ["number", "number", "number"]),
|
||||
flush: module.cwrap("hevc_decoder_flush", "number", ["number"])
|
||||
};
|
||||
this._dec = this._api.create();
|
||||
if (!this._dec) throw new Error("Failed to create HEVC decoder");
|
||||
}
|
||||
/**
|
||||
* Create a new decoder instance. Loads the WASM module.
|
||||
*/
|
||||
static async create(options) {
|
||||
const factoryOpts = {};
|
||||
if (options?.wasmBinaryUrl) {
|
||||
factoryOpts.locateFile = () => options.wasmBinaryUrl;
|
||||
}
|
||||
const g = globalThis;
|
||||
if (typeof g.HEVCDecoderModule === "function") {
|
||||
const module2 = await g.HEVCDecoderModule(factoryOpts);
|
||||
return new _HEVCDecoder(module2);
|
||||
}
|
||||
const wasmUrl = options?.wasmUrl ?? "./wasm/hevc-decode.js";
|
||||
const mod = await import(
|
||||
/* @vite-ignore */
|
||||
wasmUrl
|
||||
);
|
||||
const fn = mod.default ?? mod;
|
||||
const module = await fn(factoryOpts);
|
||||
return new _HEVCDecoder(module);
|
||||
}
|
||||
/**
|
||||
* Decode a complete HEVC bitstream.
|
||||
* @param data Raw .265 bitstream bytes
|
||||
*/
|
||||
decode(data) {
|
||||
const m = this._m;
|
||||
const ptr = m._malloc(data.length);
|
||||
try {
|
||||
m.HEAPU8.set(data, ptr);
|
||||
const ret = this._api.decode(this._dec, ptr, data.length);
|
||||
if (ret !== 0) throw new Error(`Decode failed (code ${ret})`);
|
||||
const count = this._api.getFrameCount(this._dec);
|
||||
const frames = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
const frame = this._extractFrame(i);
|
||||
if (frame) frames.push(frame);
|
||||
}
|
||||
const info = this._extractInfo();
|
||||
return { frames, info };
|
||||
} finally {
|
||||
m._free(ptr);
|
||||
}
|
||||
}
|
||||
/** Number of decoded frames available */
|
||||
get frameCount() {
|
||||
return this._api.getFrameCount(this._dec);
|
||||
}
|
||||
/** Get stream info (available after decode) */
|
||||
get info() {
|
||||
return this._extractInfo();
|
||||
}
|
||||
_extractFrame(index) {
|
||||
const m = this._m;
|
||||
const framePtr = m._malloc(48);
|
||||
try {
|
||||
const ret = this._api.getFrame(this._dec, index, framePtr);
|
||||
if (ret !== 0) return null;
|
||||
return this._readFrameFromPtr(framePtr);
|
||||
} finally {
|
||||
m._free(framePtr);
|
||||
}
|
||||
}
|
||||
_extractDrainedFrame(index) {
|
||||
const m = this._m;
|
||||
const framePtr = m._malloc(48);
|
||||
try {
|
||||
const ret = this._api.getDrainedFrame(this._dec, index, framePtr);
|
||||
if (ret !== 0) return null;
|
||||
return this._readFrameFromPtr(framePtr);
|
||||
} finally {
|
||||
m._free(framePtr);
|
||||
}
|
||||
}
|
||||
_readFrameFromPtr(framePtr) {
|
||||
const m = this._m;
|
||||
const yPtr = m.getValue(framePtr, "*");
|
||||
const cbPtr = m.getValue(framePtr + 4, "*");
|
||||
const crPtr = m.getValue(framePtr + 8, "*");
|
||||
const width = m.getValue(framePtr + 12, "i32");
|
||||
const height = m.getValue(framePtr + 16, "i32");
|
||||
const strideY = m.getValue(framePtr + 20, "i32");
|
||||
const strideC = m.getValue(framePtr + 24, "i32");
|
||||
const cw = m.getValue(framePtr + 28, "i32");
|
||||
const ch = m.getValue(framePtr + 32, "i32");
|
||||
const bd = m.getValue(framePtr + 36, "i32");
|
||||
const poc = m.getValue(framePtr + 40, "i32");
|
||||
const y = copyPlane(m, yPtr, width, height, strideY);
|
||||
const cb = copyPlane(m, cbPtr, cw, ch, strideC);
|
||||
const cr = copyPlane(m, crPtr, cw, ch, strideC);
|
||||
return { y, cb, cr, width, height, chromaWidth: cw, chromaHeight: ch, bitDepth: bd, poc };
|
||||
}
|
||||
_extractInfo() {
|
||||
const m = this._m;
|
||||
const infoPtr = m._malloc(24);
|
||||
try {
|
||||
const ret = this._api.getInfo(this._dec, infoPtr);
|
||||
if (ret !== 0) return null;
|
||||
return {
|
||||
width: m.getValue(infoPtr, "i32"),
|
||||
height: m.getValue(infoPtr + 4, "i32"),
|
||||
bitDepth: m.getValue(infoPtr + 8, "i32"),
|
||||
chromaFormat: m.getValue(infoPtr + 12, "i32"),
|
||||
profile: m.getValue(infoPtr + 16, "i32"),
|
||||
level: m.getValue(infoPtr + 20, "i32")
|
||||
};
|
||||
} finally {
|
||||
m._free(infoPtr);
|
||||
}
|
||||
}
|
||||
// --- Incremental API (streaming) ---
|
||||
/**
|
||||
* Feed a chunk of data containing one or more complete NAL units.
|
||||
* The decoder accumulates parameter sets and decodes pictures incrementally.
|
||||
* Call drain() after each feed() to retrieve output-ready frames.
|
||||
*/
|
||||
feed(data) {
|
||||
const m = this._m;
|
||||
const ptr = m._malloc(data.length);
|
||||
try {
|
||||
m.HEAPU8.set(data, ptr);
|
||||
const ret = this._api.feed(this._dec, ptr, data.length);
|
||||
if (ret !== 0) throw new Error(`Feed failed (code ${ret})`);
|
||||
} finally {
|
||||
m._free(ptr);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Drain output-ready frames from the decoder (§C.5.2 bumping process).
|
||||
* Returns frames in display order, only when ready per DPB constraints.
|
||||
* Frames are valid until the next feed() or destroy() call.
|
||||
*/
|
||||
drain() {
|
||||
const m = this._m;
|
||||
const countPtr = m._malloc(4);
|
||||
try {
|
||||
const ret = this._api.drain(this._dec, countPtr);
|
||||
if (ret !== 0) return [];
|
||||
const count = m.getValue(countPtr, "i32");
|
||||
const frames = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
const frame = this._extractDrainedFrame(i);
|
||||
if (frame) frames.push(frame);
|
||||
}
|
||||
return frames;
|
||||
} finally {
|
||||
m._free(countPtr);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Flush all remaining frames from the DPB (call at end of stream).
|
||||
* Returns all buffered frames in display order.
|
||||
*/
|
||||
flush() {
|
||||
const ret = this._api.flush(this._dec);
|
||||
if (ret !== 0) return [];
|
||||
const m = this._m;
|
||||
const countPtr = m._malloc(4);
|
||||
try {
|
||||
const frames = [];
|
||||
const framePtr = m._malloc(48);
|
||||
try {
|
||||
for (let i = 0; ; i++) {
|
||||
const r = this._api.getDrainedFrame(this._dec, i, framePtr);
|
||||
if (r !== 0) break;
|
||||
frames.push(this._readFrameFromPtr(framePtr));
|
||||
}
|
||||
} finally {
|
||||
m._free(framePtr);
|
||||
}
|
||||
return frames;
|
||||
} finally {
|
||||
m._free(countPtr);
|
||||
}
|
||||
}
|
||||
/** Release decoder resources */
|
||||
destroy() {
|
||||
if (this._dec) {
|
||||
this._api.destroy(this._dec);
|
||||
this._dec = 0;
|
||||
}
|
||||
}
|
||||
};
|
||||
function copyPlane(m, ptr, width, height, stride) {
|
||||
const out = new Uint16Array(width * height);
|
||||
const base = ptr >> 1;
|
||||
for (let y = 0; y < height; y++) {
|
||||
out.set(m.HEAPU16.subarray(base + y * stride, base + y * stride + width), y * width);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// src/renderer.ts
|
||||
var FrameRenderer = class _FrameRenderer {
|
||||
constructor() {
|
||||
this._generator = null;
|
||||
this._writer = null;
|
||||
this._canvas = null;
|
||||
this._gl = null;
|
||||
this._program = null;
|
||||
this._texY = null;
|
||||
this._texCb = null;
|
||||
this._texCr = null;
|
||||
}
|
||||
/**
|
||||
* Check if MediaStreamTrackGenerator is available (Chrome 94+).
|
||||
* When available, frames can be piped to a <video> element.
|
||||
*/
|
||||
static get supportsMediaStream() {
|
||||
return typeof MediaStreamTrackGenerator !== "undefined";
|
||||
}
|
||||
/**
|
||||
* Get a MediaStream that can be assigned to a <video>.srcObject.
|
||||
* Only available when supportsMediaStream is true.
|
||||
*/
|
||||
getMediaStream() {
|
||||
if (!_FrameRenderer.supportsMediaStream) return null;
|
||||
if (!this._generator) {
|
||||
this._generator = new MediaStreamTrackGenerator({ kind: "video" });
|
||||
this._writer = this._generator.writable.getWriter();
|
||||
}
|
||||
return new MediaStream([this._generator]);
|
||||
}
|
||||
/**
|
||||
* Render a decoded YUV frame.
|
||||
*
|
||||
* If MediaStreamTrackGenerator is available, creates a VideoFrame and writes it.
|
||||
* Otherwise, renders to the provided canvas via WebGL.
|
||||
*/
|
||||
async renderFrame(frame, timestamp) {
|
||||
if (this._writer) {
|
||||
await this._renderToVideoFrame(frame, timestamp);
|
||||
} else if (this._gl) {
|
||||
this._renderToWebGL(frame);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Initialize WebGL canvas fallback.
|
||||
* Call this if MediaStreamTrackGenerator is not supported.
|
||||
*/
|
||||
initCanvas(canvas) {
|
||||
this._canvas = canvas;
|
||||
const gl = canvas.getContext("webgl");
|
||||
if (!gl) throw new Error("WebGL not supported");
|
||||
this._gl = gl;
|
||||
this._initWebGL(gl);
|
||||
}
|
||||
async _renderToVideoFrame(frame, timestamp) {
|
||||
const w = frame.width;
|
||||
const h = frame.height;
|
||||
const cw = frame.chromaWidth;
|
||||
const ch = frame.chromaHeight;
|
||||
const shift = frame.bitDepth > 8 ? frame.bitDepth - 8 : 0;
|
||||
const i420 = new Uint8Array(w * h + cw * ch * 2);
|
||||
let dst = 0;
|
||||
for (let i = 0; i < w * h; i++) {
|
||||
i420[dst++] = frame.y[i] >> shift;
|
||||
}
|
||||
for (let i = 0; i < cw * ch; i++) {
|
||||
i420[dst++] = frame.cb[i] >> shift;
|
||||
}
|
||||
for (let i = 0; i < cw * ch; i++) {
|
||||
i420[dst++] = frame.cr[i] >> shift;
|
||||
}
|
||||
const videoFrame = new VideoFrame(i420, {
|
||||
format: "I420",
|
||||
codedWidth: w,
|
||||
codedHeight: h,
|
||||
timestamp
|
||||
});
|
||||
await this._writer.write(videoFrame);
|
||||
videoFrame.close();
|
||||
}
|
||||
_initWebGL(gl) {
|
||||
const vs = gl.createShader(gl.VERTEX_SHADER);
|
||||
gl.shaderSource(vs, VERTEX_SRC);
|
||||
gl.compileShader(vs);
|
||||
const fs = gl.createShader(gl.FRAGMENT_SHADER);
|
||||
gl.shaderSource(fs, FRAGMENT_SRC);
|
||||
gl.compileShader(fs);
|
||||
this._program = gl.createProgram();
|
||||
gl.attachShader(this._program, vs);
|
||||
gl.attachShader(this._program, fs);
|
||||
gl.linkProgram(this._program);
|
||||
gl.useProgram(this._program);
|
||||
const buf = gl.createBuffer();
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
|
||||
gl.bufferData(
|
||||
gl.ARRAY_BUFFER,
|
||||
new Float32Array([-1, -1, 0, 1, 1, -1, 1, 1, -1, 1, 0, 0, 1, 1, 1, 0]),
|
||||
gl.STATIC_DRAW
|
||||
);
|
||||
const aPos = gl.getAttribLocation(this._program, "a_pos");
|
||||
const aTex = gl.getAttribLocation(this._program, "a_tex");
|
||||
gl.enableVertexAttribArray(aPos);
|
||||
gl.enableVertexAttribArray(aTex);
|
||||
gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 16, 0);
|
||||
gl.vertexAttribPointer(aTex, 2, gl.FLOAT, false, 16, 8);
|
||||
this._texY = createTexture(gl, 0);
|
||||
this._texCb = createTexture(gl, 1);
|
||||
this._texCr = createTexture(gl, 2);
|
||||
gl.uniform1i(gl.getUniformLocation(this._program, "u_texY"), 0);
|
||||
gl.uniform1i(gl.getUniformLocation(this._program, "u_texCb"), 1);
|
||||
gl.uniform1i(gl.getUniformLocation(this._program, "u_texCr"), 2);
|
||||
}
|
||||
_renderToWebGL(frame) {
|
||||
const gl = this._gl;
|
||||
const canvas = this._canvas;
|
||||
// ВАЖНО: в Web Worker нет HTMLCanvasElement (DOM-интерфейс главного потока) —
|
||||
// голый `instanceof HTMLCanvasElement` кинул бы ReferenceError. Для OffscreenCanvas
|
||||
// размер не трогаем (его задаёт главный поток), рисуем по текущему canvas.width/height.
|
||||
if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
|
||||
canvas.width = frame.width;
|
||||
canvas.height = frame.height;
|
||||
}
|
||||
// viewport по размеру КАНВАСА (не кадра): для OffscreenCanvas в воркере это
|
||||
// позволяет рисовать в уменьшённый буфер, GPU сам масштабирует текстуру (LINEAR).
|
||||
gl.viewport(0, 0, canvas.width, canvas.height);
|
||||
const shift = frame.bitDepth > 8 ? frame.bitDepth - 8 : 0;
|
||||
uploadPlane(gl, this._texY, 0, frame.y, frame.width, frame.height, shift);
|
||||
uploadPlane(gl, this._texCb, 1, frame.cb, frame.chromaWidth, frame.chromaHeight, shift);
|
||||
uploadPlane(gl, this._texCr, 2, frame.cr, frame.chromaWidth, frame.chromaHeight, shift);
|
||||
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
||||
}
|
||||
/** Release all resources */
|
||||
destroy() {
|
||||
this._writer?.close();
|
||||
this._generator?.stop();
|
||||
this._generator = null;
|
||||
this._writer = null;
|
||||
this._gl = null;
|
||||
this._canvas = null;
|
||||
}
|
||||
};
|
||||
function createTexture(gl, unit) {
|
||||
gl.activeTexture(gl.TEXTURE0 + unit);
|
||||
const tex = gl.createTexture();
|
||||
gl.bindTexture(gl.TEXTURE_2D, tex);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||
return tex;
|
||||
}
|
||||
function uploadPlane(gl, tex, unit, data, width, height, shift) {
|
||||
gl.activeTexture(gl.TEXTURE0 + unit);
|
||||
gl.bindTexture(gl.TEXTURE_2D, tex);
|
||||
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
|
||||
if (shift === 0) {
|
||||
// data — Uint16Array со значениями 0..255 (little-endian: байт[2i]=значение, байт[2i+1]=0).
|
||||
// Грузим СЫРЫЕ байты как LUMINANCE_ALPHA (2 байта/тексель): шейдер берёт .r = L = младший байт = значение.
|
||||
// Так убираем per-pixel JS-цикл 16→8 бит — главный тормоз показа на 3200×1800.
|
||||
const bytes = new Uint8Array(data.buffer, data.byteOffset, width * height * 2);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE_ALPHA, width, height, 0, gl.LUMINANCE_ALPHA, gl.UNSIGNED_BYTE, bytes);
|
||||
} else {
|
||||
const u8 = new Uint8Array(width * height);
|
||||
for (let i = 0; i < width * height; i++) u8[i] = Math.min(255, data[i] >> shift);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, u8);
|
||||
}
|
||||
}
|
||||
var VERTEX_SRC = `
|
||||
attribute vec2 a_pos;
|
||||
attribute vec2 a_tex;
|
||||
varying vec2 v_tex;
|
||||
void main() {
|
||||
gl_Position = vec4(a_pos, 0.0, 1.0);
|
||||
v_tex = a_tex;
|
||||
}
|
||||
`;
|
||||
var FRAGMENT_SRC = `
|
||||
precision mediump float;
|
||||
varying vec2 v_tex;
|
||||
uniform sampler2D u_texY;
|
||||
uniform sampler2D u_texCb;
|
||||
uniform sampler2D u_texCr;
|
||||
void main() {
|
||||
float y = texture2D(u_texY, v_tex).r;
|
||||
float cb = texture2D(u_texCb, v_tex).r - 0.5;
|
||||
float cr = texture2D(u_texCr, v_tex).r - 0.5;
|
||||
float r = y + 1.5748 * cr;
|
||||
float g = y - 0.1873 * cb - 0.4681 * cr;
|
||||
float b = y + 1.8556 * cb;
|
||||
gl_FragColor = vec4(clamp(r, 0.0, 1.0), clamp(g, 0.0, 1.0), clamp(b, 0.0, 1.0), 1.0);
|
||||
}
|
||||
`;
|
||||
|
||||
|
||||
export { HEVCDecoder, FrameRenderer };
|
||||
File diff suppressed because one or more lines are too long
+147
@@ -0,0 +1,147 @@
|
||||
// hevc-player-worker.js — HEVC-декод + рендер в OffscreenCanvas в отдельном потоке.
|
||||
// Главный поток только открывает WS и перекидывает сюда байты (transfer) — UI не блокируется.
|
||||
import { HEVCDecoder, FrameRenderer } from "./hevc-core.js";
|
||||
|
||||
// поймать тихие ошибки (в т.ч. из async renderFrame) и переслать в главный поток
|
||||
self.addEventListener("unhandledrejection", (e) => {
|
||||
self.postMessage({ type: "err", msg: "promise: " + String((e.reason && e.reason.message) || e.reason) });
|
||||
});
|
||||
|
||||
// ── строка кодека из hvcC (для информации) ──
|
||||
function hevcCodecFromHvcC(hvcC) {
|
||||
try { const p = hvcC[1] & 0x1f, t = ((hvcC[1] >> 5) & 1) ? "H" : "L", lv = hvcC[12] || 153; return `hvc1.${p}.6.${t}${lv}.B0`; }
|
||||
catch (e) { return "hvc1.1.6.L153.B0"; }
|
||||
}
|
||||
// ── VPS/SPS/PPS из hvcC → Annex-B ──
|
||||
function hvccParamSetsToAnnexB(hvcC) {
|
||||
if (hvcC.length < 23) return new Uint8Array(0);
|
||||
let o = 22; const numArrays = hvcC[o++]; const chunks = [];
|
||||
for (let a = 0; a < numArrays; a++) {
|
||||
o++;
|
||||
const num = (hvcC[o] << 8) | hvcC[o + 1]; o += 2;
|
||||
for (let n = 0; n < num; n++) { const len = (hvcC[o] << 8) | hvcC[o + 1]; o += 2; chunks.push(hvcC.subarray(o, o + len)); o += len; }
|
||||
}
|
||||
let total = 0; for (const c of chunks) total += 4 + c.length;
|
||||
const out = new Uint8Array(total); let p = 0;
|
||||
for (const c of chunks) { out[p + 3] = 1; p += 4; out.set(c, p); p += c.length; }
|
||||
return out;
|
||||
}
|
||||
// ── length-prefixed NAL → Annex-B (размер не меняется) ──
|
||||
function toAnnexB(u8) {
|
||||
const out = new Uint8Array(u8.length); out.set(u8);
|
||||
let i = 0;
|
||||
while (i + 4 <= out.length) {
|
||||
const len = ((u8[i] << 24) | (u8[i + 1] << 16) | (u8[i + 2] << 8) | u8[i + 3]) >>> 0;
|
||||
out[i] = 0; out[i + 1] = 0; out[i + 2] = 0; out[i + 3] = 1;
|
||||
if (len === 0) break; i += 4 + len;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// ── демуксер FLV (enhanced-RTMP) → hvcC + length-prefixed HEVC-кадры ──
|
||||
class FlvHevcDemuxer {
|
||||
constructor({ onConfig, onSample }) {
|
||||
this.onConfig = onConfig; this.onSample = onSample;
|
||||
this.buf = new Uint8Array(0); this.headerDone = false; this.gotConfig = false;
|
||||
}
|
||||
push(ab) {
|
||||
const inc = new Uint8Array(ab);
|
||||
if (this.buf.length === 0) { this.buf = inc; }
|
||||
else { const m = new Uint8Array(this.buf.length + inc.length); m.set(this.buf, 0); m.set(inc, this.buf.length); this.buf = m; }
|
||||
this._parse();
|
||||
}
|
||||
_u32(o) { return ((this.buf[o] << 24) | (this.buf[o + 1] << 16) | (this.buf[o + 2] << 8) | this.buf[o + 3]) >>> 0; }
|
||||
_parse() {
|
||||
const b = this.buf, len = b.length;
|
||||
if (!this.headerDone) {
|
||||
if (len < 9) return;
|
||||
const dataOffset = this._u32(5);
|
||||
this.buf = b.slice(dataOffset); this.headerDone = true;
|
||||
return this._parse();
|
||||
}
|
||||
let o = 0;
|
||||
while (true) {
|
||||
if (o + 4 + 11 > len) break;
|
||||
const ts = o + 4;
|
||||
const tagType = b[ts] & 0x1f;
|
||||
const dataSize = (b[ts + 1] << 16) | (b[ts + 2] << 8) | b[ts + 3];
|
||||
const bodyStart = ts + 11, bodyEnd = bodyStart + dataSize;
|
||||
if (bodyEnd > len) break;
|
||||
if (tagType === 9) {
|
||||
const tsMs = ((b[ts + 7] << 24) >>> 0) | (b[ts + 4] << 16) | (b[ts + 5] << 8) | b[ts + 6];
|
||||
this._videoTag(b.subarray(bodyStart, bodyEnd), tsMs);
|
||||
}
|
||||
o = bodyEnd;
|
||||
}
|
||||
if (o > 0) this.buf = b.slice(o);
|
||||
}
|
||||
_videoTag(body, tsMs) {
|
||||
if (body.length < 5) return;
|
||||
const b0 = body[0], isEx = (b0 & 0x80) !== 0;
|
||||
if (isEx) {
|
||||
const frameType = (b0 >> 4) & 0x07, packetType = b0 & 0x0f;
|
||||
const fourcc = String.fromCharCode(body[1], body[2], body[3], body[4]);
|
||||
if (fourcc !== "hvc1" && fourcc !== "hev1") return;
|
||||
let off = 5;
|
||||
if (packetType === 1) off += 3;
|
||||
const payload = body.subarray(off);
|
||||
if (packetType === 0) this._config(payload);
|
||||
else if (packetType === 1 || packetType === 3) this._frames(payload, frameType === 1, tsMs);
|
||||
} else {
|
||||
const codecId = b0 & 0x0f, frameType = (b0 >> 4) & 0x0f;
|
||||
if (codecId !== 12 && codecId !== 7) return;
|
||||
const pkt = body[1], payload = body.subarray(5);
|
||||
if (pkt === 0) this._config(payload);
|
||||
else if (pkt === 1) this._frames(payload, frameType === 1, tsMs);
|
||||
}
|
||||
}
|
||||
_config(hvcC) {
|
||||
if (this.gotConfig || hvcC.length < 13) return;
|
||||
this.gotConfig = true;
|
||||
this.onConfig(hvcC.slice(), hevcCodecFromHvcC(hvcC));
|
||||
}
|
||||
_frames(payload, isKey, tsMs) {
|
||||
if (!this.gotConfig || payload.length === 0) return;
|
||||
this.onSample({ data: payload.slice(), type: isKey ? "key" : "delta", timestampUs: tsMs * 1000 });
|
||||
}
|
||||
}
|
||||
|
||||
// ── состояние воркера ──
|
||||
let decoder = null, renderer = null, demux = null, canvas = null;
|
||||
let decoded = 0, statTimer = null;
|
||||
|
||||
function err(e) { self.postMessage({ type: "err", msg: String((e && e.message) || e) }); }
|
||||
|
||||
function pump() {
|
||||
let fr; try { fr = decoder.drain(); } catch (e) { return; }
|
||||
for (const f of fr) { decoded++; renderer.renderFrame(f, decoded * 40000); }
|
||||
}
|
||||
|
||||
function cleanup() {
|
||||
if (statTimer) { clearInterval(statTimer); statTimer = null; }
|
||||
try { renderer && renderer.destroy(); } catch (e) {}
|
||||
try { decoder && decoder.destroy(); } catch (e) {}
|
||||
renderer = null; decoder = null; demux = null; canvas = null; decoded = 0;
|
||||
}
|
||||
|
||||
self.onmessage = async (e) => {
|
||||
const m = e.data;
|
||||
try {
|
||||
if (m.type === "init") {
|
||||
canvas = m.canvas;
|
||||
decoder = await HEVCDecoder.create({ wasmUrl: m.wasmUrl, wasmBinaryUrl: m.wasmBinaryUrl });
|
||||
renderer = new FrameRenderer();
|
||||
renderer.initCanvas(canvas);
|
||||
demux = new FlvHevcDemuxer({
|
||||
onConfig: (hvcC) => { const ps = hvccParamSetsToAnnexB(hvcC); if (ps.length) { try { decoder.feed(ps); pump(); } catch (er) { err(er); } } },
|
||||
onSample: ({ data }) => { try { decoder.feed(toAnnexB(data)); pump(); } catch (er) { err(er); } },
|
||||
});
|
||||
if (statTimer) clearInterval(statTimer);
|
||||
statTimer = setInterval(() => { self.postMessage({ type: "stat", fps: decoded }); decoded = 0; }, 1000);
|
||||
self.postMessage({ type: "ready" });
|
||||
} else if (m.type === "data") {
|
||||
if (demux) demux.push(m.buf);
|
||||
} else if (m.type === "stop") {
|
||||
cleanup();
|
||||
}
|
||||
} catch (er) { err(er); }
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
// Заглушка: dist/index.js статически импортит "mp4box" ради FMP4Demuxer,
|
||||
// который мы НЕ используем (у нас свой FLV-демукс). Import-map подменяет
|
||||
// "mp4box" на этот файл, чтобы модуль index.js загрузился без bare-specifier.
|
||||
export function createFile() {
|
||||
throw new Error("mp4box stub: FMP4Demuxer не используется в этом проекте");
|
||||
}
|
||||
export default { createFile };
|
||||
Reference in New Issue
Block a user