230 lines
9.2 KiB
JavaScript
230 lines
9.2 KiB
JavaScript
// Disk-backed holds: media streams into the browser's private filesystem
|
|
// (OPFS) instead of living in RAM, so multi-GB files never bloat the
|
|
// offscreen document. Files are laid out exactly like the old in-memory
|
|
// arrays (header first, then each decrypted fragment in order) so the
|
|
// MuxPlanner offsets match the previous behavior byte for byte.
|
|
|
|
// ground-truth capture for building our own decrypt/mux: the first DRM
|
|
// download after load records real inputs and the wasm's exact outputs
|
|
export const drmCapture = { frags: [], moofs: [], headers: {}, mux: null, sent: false };
|
|
const b64 = (bytes) => {
|
|
let s = "";
|
|
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
|
|
return btoa(s);
|
|
};
|
|
|
|
export async function holdsDir() {
|
|
const root = await navigator.storage.getDirectory();
|
|
return root.getDirectoryHandle("holds", { create: true });
|
|
}
|
|
|
|
/** Stream a fetch Response body into OPFS. Returns {id, size}. */
|
|
export async function streamIntoHold(dir, res, onChunk) {
|
|
const id = "h_" + Math.random().toString(36).slice(2);
|
|
const fh = await dir.getFileHandle(id, { create: true });
|
|
const w = await fh.createWritable();
|
|
let size = 0;
|
|
for await (const chunk of res.body) {
|
|
await w.write(chunk);
|
|
size += chunk.byteLength;
|
|
if (onChunk) onChunk(chunk.byteLength);
|
|
}
|
|
await w.close();
|
|
return { id, size };
|
|
}
|
|
|
|
/** Blob URL for a held file — disk-backed, so chrome.downloads streams it. */
|
|
export async function holdFileUrl(dir, id, mime = "application/octet-stream") {
|
|
const fh = await dir.getFileHandle(id);
|
|
const file = await fh.getFile();
|
|
// slice with a contentType — OPFS files carry no MIME type, and an untyped
|
|
// blob makes Chrome append .txt to the download
|
|
return URL.createObjectURL(file.slice(0, file.size, mime || "application/octet-stream"));
|
|
}
|
|
|
|
export async function removeHolds(dir, names) {
|
|
for (const name of names ?? []) {
|
|
if (!name) continue;
|
|
try { await dir.removeEntry(name); } catch {}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Async-iterate the top-level boxes of an mp4 File with chunked reads.
|
|
* Yields {type, start, end, bytes} — `bytes` is a copy only for types in
|
|
* `withBytes`. Boxes bigger than a chunk are skipped without buffering
|
|
* unless their bytes were requested, so huge mdats never enter RAM here.
|
|
*/
|
|
export async function* mp4Boxes(file, { withBytes = [], chunkSize = 1 << 22 } = {}) {
|
|
const want = new Set(withBytes);
|
|
let buf = new Uint8Array(0); // pending bytes, starting at file offset `base`
|
|
let base = 0;
|
|
for (;;) {
|
|
let size = 0;
|
|
if (buf.length >= 8) {
|
|
const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
size = dv.getUint32(0);
|
|
if (size === 1) {
|
|
size = buf.length >= 16 ? Number(dv.getBigUint64(8)) : -1; // need more
|
|
} else if (size === 0) {
|
|
size = file.size - base; // box extends to EOF
|
|
}
|
|
if (size >= 0 && size < 8) return; // malformed, like the old parser
|
|
if (size >= 8) {
|
|
const type = String.fromCharCode(buf[4], buf[5], buf[6], buf[7]);
|
|
if (buf.length >= size) {
|
|
yield { type, start: base, end: base + size, bytes: want.has(type) ? buf.slice(0, size) : undefined };
|
|
buf = buf.subarray(size);
|
|
base += size;
|
|
continue;
|
|
}
|
|
if (!want.has(type) && base + size <= file.size) {
|
|
// large box we don't need bytes for — skip past it without buffering
|
|
yield { type, start: base, end: base + size, bytes: undefined };
|
|
buf = new Uint8Array(0);
|
|
base += size;
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
if (base + buf.length >= file.size) return; // EOF (or partial box at EOF)
|
|
const from = base + buf.length;
|
|
const to = Math.min(from + chunkSize, file.size);
|
|
const chunk = new Uint8Array(await file.slice(from, to).arrayBuffer());
|
|
const merged = new Uint8Array(buf.length + chunk.length);
|
|
merged.set(buf);
|
|
merged.set(chunk, buf.length);
|
|
buf = merged;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Stream-decrypt one track. Reads the source hold, decrypts each
|
|
* moof..mdat fragment in place with the same wasm calls as the in-memory
|
|
* flow, and appends to a new OPFS file laid out like the old result array:
|
|
* header first, fragments in order. Returns {header} (the pre-strip source
|
|
* header, as the old code used it).
|
|
*/
|
|
export async function decryptTrackToOpfs(dir, srcId, decId, keyBytes, fns, label = "video", onProgress) {
|
|
const src = await (await dir.getFileHandle(srcId)).getFile();
|
|
const dec = await dir.getFileHandle(decId, { create: true });
|
|
const w = await dec.createWritable();
|
|
let header = null;
|
|
try {
|
|
let marker = 0, pattern = null, civ = null;
|
|
let moofStart = -1, done = 0;
|
|
for await (const box of mp4Boxes(src)) {
|
|
if (header === null) {
|
|
if (box.type !== "moof") continue;
|
|
header = new Uint8Array(await src.slice(0, box.start).arrayBuffer());
|
|
marker = fns.tencMarker(header);
|
|
if (marker < 0) throw new Error("no tenc — not CENC-protected");
|
|
fns.stripInit(header);
|
|
pattern = fns.tencCryptPattern(header);
|
|
civ = fns.tencConstantIv(header);
|
|
await w.write(header);
|
|
moofStart = box.start;
|
|
continue;
|
|
}
|
|
if (box.type === "moof") { moofStart = box.start; continue; }
|
|
if (box.type === "mdat" && moofStart >= 0) {
|
|
const bytes = new Uint8Array(await src.slice(moofStart, box.end).arrayBuffer());
|
|
if (!drmCapture.sent && drmCapture.frags.filter((f) => f.track === label).length < 1) {
|
|
drmCapture.headers[label] = b64(header);
|
|
drmCapture.key = b64(keyBytes);
|
|
drmCapture.marker = marker;
|
|
drmCapture.pattern = pattern ? [...pattern] : null;
|
|
drmCapture.civ = civ ? [...civ] : null;
|
|
var capIn = b64(bytes);
|
|
}
|
|
if (pattern) {
|
|
fns.decryptAndStripFragmentCbcs(bytes, keyBytes, marker, pattern[0] ?? 0, pattern[1] ?? 0, civ ?? new Uint8Array());
|
|
} else {
|
|
fns.decryptAndStripFragment(bytes, keyBytes, marker);
|
|
}
|
|
await w.write(bytes);
|
|
done += bytes.length;
|
|
if (onProgress) onProgress(done, src.size);
|
|
if (capIn) { drmCapture.frags.push({ track: label, in: capIn, out: b64(bytes) }); capIn = null; }
|
|
moofStart = -1;
|
|
}
|
|
}
|
|
if (header === null) {
|
|
// degenerate track with no fragments: the old flow treated the whole
|
|
// file as its own "header"
|
|
await w.write(new Uint8Array(await src.slice(0, src.size).arrayBuffer()));
|
|
}
|
|
} catch (e) {
|
|
try { await w.close(); } catch {}
|
|
try { await dir.removeEntry(decId); } catch {}
|
|
throw e;
|
|
}
|
|
await w.close();
|
|
return { header };
|
|
}
|
|
|
|
/**
|
|
* Re-parse a decrypted track file and feed every moof into the MuxPlanner
|
|
* exactly like the in-memory flow did: bytes from the moof's start through
|
|
* whatever follows it up to (not including) the next mdat, at the moof's
|
|
* offset. Returns the bytes before the first moof — the header the planner
|
|
* constructor wants.
|
|
*/
|
|
export async function pushTrackMoofs(dir, decId, planner, isVideo) {
|
|
const file = await (await dir.getFileHandle(decId)).getFile();
|
|
let header = null, moofStart = -1;
|
|
for await (const box of mp4Boxes(file)) {
|
|
if (box.type === "moof") {
|
|
if (header === null) header = new Uint8Array(await file.slice(0, box.start).arrayBuffer());
|
|
moofStart = box.start;
|
|
continue;
|
|
}
|
|
if (box.type === "mdat" && moofStart >= 0) {
|
|
const moof = new Uint8Array(await file.slice(moofStart, box.start).arrayBuffer());
|
|
const track = isVideo ? "video" : "audio";
|
|
if (!drmCapture.sent && drmCapture.moofs.filter((x) => x.track === track).length < 3) {
|
|
drmCapture.moofs.push({ track, offset: moofStart, moof: b64(moof) });
|
|
}
|
|
isVideo ? planner.pushVideoMoof(moof, moofStart) : planner.pushAudioMoof(moof, moofStart);
|
|
moofStart = -1;
|
|
}
|
|
}
|
|
return header ?? new Uint8Array(await file.slice(0, file.size).arrayBuffer());
|
|
}
|
|
|
|
/**
|
|
* Write the muxed output: muxed header, then each layout range copied from
|
|
* the decrypted track files in chunks. Returns {blobUrl, size}.
|
|
*/
|
|
export async function writeMuxedFile(dir, finalId, muxed, videoFile, audioFile) {
|
|
const fh = await dir.getFileHandle(finalId, { create: true });
|
|
const w = await fh.createWritable();
|
|
try {
|
|
await w.write(muxed.header());
|
|
const layout = muxed.layout();
|
|
for (let i = 0; i < layout.length; i += 3) {
|
|
const isVideo = layout[i], off = layout[i + 1], len = layout[i + 2];
|
|
const f = (isVideo || !audioFile) ? videoFile : audioFile;
|
|
let p = off;
|
|
const end = off + len;
|
|
while (p < end) {
|
|
const n = Math.min(1 << 22, end - p);
|
|
await w.write(await f.slice(p, p + n).arrayBuffer());
|
|
p += n;
|
|
}
|
|
}
|
|
} catch (e) {
|
|
try { await w.close(); } catch {}
|
|
try { await dir.removeEntry(finalId); } catch {}
|
|
throw e;
|
|
}
|
|
await w.close();
|
|
if (!drmCapture.sent) {
|
|
try { drmCapture.mux = { header: b64(muxed.header()), layout: [...muxed.layout()] }; } catch {}
|
|
}
|
|
const ofile = await fh.getFile();
|
|
// OPFS files have no MIME type — an untyped blob URL makes Chrome append
|
|
// .txt to the download, so hand out a typed view of the same file
|
|
return { blobUrl: URL.createObjectURL(ofile.slice(0, ofile.size, "video/mp4")), size: ofile.size };
|
|
}
|