@muxen/web 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,589 @@
1
+ /**
2
+ * FFmpeg in the browser, compiled to WebAssembly.
3
+ *
4
+ * ```ts
5
+ * import { probe, transcode, thumbnail } from "@muxen/web";
6
+ *
7
+ * const file = input.files[0]; // a File: read in slices, never copied whole
8
+ * const info = await probe(file);
9
+ * const { data } = await transcode(file, { video: { codec: "h264", maxSize: 1280 } });
10
+ * video.src = URL.createObjectURL(new Blob([data!], { type: "video/mp4" }));
11
+ * ```
12
+ *
13
+ * Everything runs in Web Workers; the page never blocks. On a cross-origin
14
+ * isolated page (COOP/COEP headers) jobs use threads, several times faster;
15
+ * elsewhere a single-threaded build is used automatically.
16
+ *
17
+ * @module
18
+ */
19
+
20
+ import {
21
+ AbortError,
22
+ commonOutput,
23
+ createApi,
24
+ InternalError,
25
+ isBlob,
26
+ makeError,
27
+ type Engine,
28
+ type InputSource,
29
+ type NativeFrame,
30
+ type NativeInput,
31
+ type NativeJob,
32
+ type NativeOutput,
33
+ type OutputTarget,
34
+ type PreparedOutput,
35
+ type Progress,
36
+ } from "@muxen/core";
37
+ import type { FromWorker, ToWorker, WorkerInput, WorkerJob, WorkerOutput } from "./protocol.js";
38
+
39
+ export * from "@muxen/core";
40
+
41
+ // ---------------------------------------------------------------------------
42
+ // Configuration
43
+
44
+ export interface WasmConfig {
45
+ /**
46
+ * Use the threaded build. Default: when the page is cross-origin isolated
47
+ * (`crossOriginIsolated`), which SharedArrayBuffer requires.
48
+ */
49
+ threads?: boolean;
50
+ /**
51
+ * Where `muxen-mt.mjs`, `muxen-st.mjs` and their `.wasm` files are served from,
52
+ * if not next to this package (a CDN, a public folder). Ends with "/".
53
+ */
54
+ wasmBase?: string;
55
+ /** A URL or factory for the worker script, for bundlers that need it spelled out. */
56
+ worker?: string | URL | (() => Worker);
57
+ /** Single-threaded build: how many jobs may run at once (one worker each). Default 2. */
58
+ maxWorkers?: number;
59
+ /** Threads per job in the threaded build. Default: cores, at most 8. */
60
+ threadsPerJob?: number;
61
+ }
62
+
63
+ const config: Required<Pick<WasmConfig, "maxWorkers">> & WasmConfig = { maxWorkers: 2 };
64
+
65
+ /**
66
+ * Change where and how the engine runs. Best before the first job; after it,
67
+ * workers already started are retired (once idle) when the build, the module's
68
+ * location or the worker changes, and the pool's size applies at once.
69
+ */
70
+ export function configure(c: WasmConfig): void {
71
+ const respawn = (["threads", "wasmBase", "worker"] as const).some((k) => k in c && c[k] !== config[k]);
72
+ Object.assign(config, c);
73
+ if (respawn) {
74
+ if (shared) { shared.retire(); shared = undefined; }
75
+ for (const h of pool.splice(0)) h.retire();
76
+ }
77
+ pump();
78
+ }
79
+
80
+ const isNode = typeof process !== "undefined" && !!(process as { versions?: { node?: string } }).versions?.node && typeof window === "undefined";
81
+
82
+ function threaded(): boolean {
83
+ if (config.threads !== undefined) return config.threads;
84
+ if (isNode) return true;
85
+ return typeof SharedArrayBuffer !== "undefined" && (globalThis as { crossOriginIsolated?: boolean }).crossOriginIsolated === true;
86
+ }
87
+
88
+ function threadsPerJob(): number {
89
+ return Math.min(cores(), config.threadsPerJob ?? 8);
90
+ }
91
+
92
+ function cores(): number {
93
+ const n = typeof navigator !== "undefined" ? navigator.hardwareConcurrency : 4;
94
+ return Math.max(1, n || 4);
95
+ }
96
+
97
+ // ---------------------------------------------------------------------------
98
+ // Host workers
99
+
100
+ interface Pending {
101
+ resolve(m: Extract<FromWorker, { t: "done" }>): void;
102
+ reject(e: Error): void;
103
+ onProgress?: (p: Progress) => void;
104
+ onLog?: (level: string, message: string) => void;
105
+ onChunk?: (data: Uint8Array) => void;
106
+ }
107
+
108
+ let nextId = 1;
109
+
110
+ class Host {
111
+ readonly worker: Worker;
112
+ readonly ready: Promise<void>;
113
+ private pending = new Map<number, Pending>();
114
+ busy = 0;
115
+ dead = false;
116
+ private starting = true;
117
+ /** Replaced (configure()): stops once nothing runs on it. */
118
+ retired = false;
119
+
120
+ constructor(readonly variant: "mt" | "st") {
121
+ this.worker = Host.spawn();
122
+ this.ready = new Promise((resolve, reject) => {
123
+ const onMessage = (m: FromWorker) => {
124
+ if (m.t === "ready") resolve();
125
+ else if (m.t === "fatal") { reject(new InternalError(`the FFmpeg worker crashed: ${m.message}`)); this.dispatch(m); }
126
+ else if (m.t === "error" && m.id === -1) reject(makeError(m.code, m.message));
127
+ else this.dispatch(m);
128
+ };
129
+ listen(this.worker, onMessage, (e) => {
130
+ const err = new InternalError(`the FFmpeg worker failed: ${e}`);
131
+ reject(err);
132
+ this.kill(err);
133
+ });
134
+ });
135
+ // Whoever needs the host awaits this; a host nobody awaited must not leave an unhandled rejection.
136
+ this.ready.catch(() => {}).finally(() => { this.starting = false; this.hold(); });
137
+ // Listening for messages refs a Node worker again: only starting up and pending requests may hold the process.
138
+ this.hold();
139
+ // Threads a job starts: itself, its decoder's and its scaler's. Their Web
140
+ // Workers start in the background once the module is ready, rather than
141
+ // in the middle of the first job (~40 ms each).
142
+ const warm = variant === "mt" ? 2 * threadsPerJob() + 2 : 0;
143
+ this.send({ t: "init", variant, ...(config.wasmBase ? { base: config.wasmBase } : {}), ...(warm ? { warm } : {}) });
144
+ }
145
+
146
+ /** Stops now if idle, else when its last job ends. */
147
+ retire() {
148
+ this.retired = true;
149
+ if (this.busy === 0 && this.pending.size === 0) this.kill(new AbortError("terminated"));
150
+ }
151
+
152
+ private static spawn(): Worker {
153
+ const w = config.worker;
154
+ if (typeof w === "function") return w();
155
+ if (w) return new Worker(w, { type: "module" });
156
+ if (isNode) {
157
+ // Tests and server-side use: Node's worker_threads, made to look like a Worker.
158
+ // Spelled so bundlers don't pick it up: browsers never take this path.
159
+ const nodeUrl = new URL(["./worker", "js"].join("."), import.meta.url);
160
+ return nodeWorker(nodeUrl) as unknown as Worker;
161
+ }
162
+ return new Worker(new URL("./worker.js", import.meta.url), { type: "module", name: "muxen" });
163
+ }
164
+
165
+ send(m: ToWorker, transfer: Transferable[] = []) {
166
+ this.worker.postMessage(m, transfer);
167
+ }
168
+
169
+ request(m: ToWorker & { id: number }, p: Omit<Pending, "resolve" | "reject">, transfer: Transferable[] = []): Promise<Extract<FromWorker, { t: "done" }>> {
170
+ return new Promise((resolve, reject) => {
171
+ this.pending.set(m.id, { ...p, resolve, reject });
172
+ this.hold();
173
+ this.send(m, transfer);
174
+ });
175
+ }
176
+
177
+ /** Under Node, the worker keeps the process alive only while it has work. */
178
+ hold() {
179
+ const w = this.worker as unknown as { ref?: () => void; unref?: () => void };
180
+ if (this.dead) return;
181
+ if (this.starting || this.pending.size > 0) w.ref?.();
182
+ else w.unref?.();
183
+ }
184
+
185
+ private dispatch(m: FromWorker) {
186
+ if (m.t === "ready") return;
187
+ if (m.t === "fatal") return void this.kill(new InternalError(`the FFmpeg worker crashed: ${m.message}`));
188
+ const p = this.pending.get(m.id);
189
+ if (!p) return;
190
+ switch (m.t) {
191
+ case "progress": p.onProgress?.(m.progress); break;
192
+ case "log": p.onLog?.(m.level, m.message); break;
193
+ case "chunk": p.onChunk?.(m.data); break;
194
+ case "done": this.pending.delete(m.id); this.hold(); p.resolve(m); break;
195
+ case "error": this.pending.delete(m.id); this.hold(); p.reject(makeError(m.code, m.message)); break;
196
+ }
197
+ }
198
+
199
+ /** Rejects everything in flight and stops the worker. */
200
+ kill(reason: Error) {
201
+ if (this.dead) return;
202
+ this.dead = true;
203
+ const pending = [...this.pending.values()];
204
+ this.pending.clear();
205
+ for (const p of pending) p.reject(reason);
206
+ void Promise.resolve(this.worker.terminate()).catch(() => {});
207
+ // Its slot is free again: a queued job gets a fresh worker.
208
+ if (this.variant === "st") { const i = pool.indexOf(this); if (i >= 0) pool.splice(i, 1); }
209
+ if (shared === this) shared = undefined;
210
+ queueMicrotask(pump);
211
+ }
212
+ }
213
+
214
+ function listen(w: Worker, onMessage: (m: FromWorker) => void, onError: (e: string) => void) {
215
+ if ("on" in w && typeof (w as any).on === "function") {
216
+ (w as any).on("message", onMessage);
217
+ (w as any).on("error", (e: Error) => onError(e.message));
218
+ // Out of memory and other deaths without an "error" first.
219
+ (w as any).on("exit", (code: number) => onError(`exited (${code})`));
220
+ } else {
221
+ w.onmessage = (e: MessageEvent<FromWorker>) => onMessage(e.data);
222
+ w.onerror = (e) => onError(e.message);
223
+ }
224
+ }
225
+
226
+ function nodeWorker(url: URL): unknown {
227
+ // Resolved lazily so browsers never see node:worker_threads.
228
+ const req = (globalThis as { process?: { getBuiltinModule?: (m: string) => any } }).process?.getBuiltinModule?.("node:worker_threads");
229
+ if (!req) throw new InternalError("node:worker_threads is unavailable");
230
+ const w = new req.Worker(url);
231
+ w.unref?.();
232
+ return w;
233
+ }
234
+
235
+ /** The threaded build: one host for every job. */
236
+ let shared: Host | undefined;
237
+ /** The single-threaded build: a pool, one job per worker. */
238
+ const pool: Host[] = [];
239
+ interface Waiter {
240
+ grant(h: Host): void;
241
+ fail(e: Error): void;
242
+ }
243
+ /** Jobs waiting for a single-threaded worker, oldest first. */
244
+ const queue: Waiter[] = [];
245
+
246
+ /** A host for one job (or reader); give it back with release(). Abortable while queued. */
247
+ async function acquire(signal?: AbortSignal): Promise<Host> {
248
+ if (signal?.aborted) throw new AbortError();
249
+ let h: Host;
250
+ if (threaded()) {
251
+ if (!shared || shared.dead) shared = new Host("mt");
252
+ h = shared;
253
+ h.busy++;
254
+ } else {
255
+ h = await new Promise<Host>((resolve, reject) => {
256
+ const w: Waiter = {
257
+ grant: (host) => { signal?.removeEventListener("abort", onAbort); resolve(host); },
258
+ fail: (e) => { signal?.removeEventListener("abort", onAbort); reject(e); },
259
+ };
260
+ const onAbort = () => {
261
+ const i = queue.indexOf(w);
262
+ if (i >= 0) queue.splice(i, 1);
263
+ reject(new AbortError());
264
+ };
265
+ signal?.addEventListener("abort", onAbort, { once: true });
266
+ queue.push(w);
267
+ pump();
268
+ });
269
+ }
270
+ try {
271
+ await h.ready;
272
+ } catch (e) {
273
+ release(h);
274
+ throw e;
275
+ }
276
+ if (signal?.aborted) {
277
+ release(h);
278
+ throw new AbortError();
279
+ }
280
+ return h;
281
+ }
282
+
283
+ /** Hands free single-threaded workers (or new ones, up to maxWorkers) to queued jobs. */
284
+ function pump() {
285
+ while (queue.length > 0) {
286
+ for (let i = pool.length - 1; i >= 0; i--) if (pool[i]!.dead) pool.splice(i, 1);
287
+ let h = pool.find((x) => x.busy === 0 && !x.dead);
288
+ if (!h) {
289
+ if (pool.length >= Math.max(1, config.maxWorkers)) return;
290
+ h = new Host("st");
291
+ pool.push(h);
292
+ }
293
+ h.busy++;
294
+ queue.shift()!.grant(h);
295
+ }
296
+ }
297
+
298
+ function release(h: Host) {
299
+ h.busy = Math.max(0, h.busy - 1);
300
+ if (h.retired && h.busy === 0) h.kill(new AbortError("terminated"));
301
+ if (h.variant === "st") pump();
302
+ }
303
+
304
+ // ---------------------------------------------------------------------------
305
+ // Inputs and outputs
306
+
307
+ /** Rejects with an AbortError as soon as `signal` aborts. */
308
+ function abortable<T>(p: Promise<T>, signal: AbortSignal | undefined, onAbort?: () => void): Promise<T> {
309
+ if (!signal) return p;
310
+ if (signal.aborted) { onAbort?.(); return Promise.reject(new AbortError()); }
311
+ return new Promise<T>((resolve, reject) => {
312
+ const abort = () => { onAbort?.(); reject(new AbortError()); };
313
+ signal.addEventListener("abort", abort, { once: true });
314
+ p.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
315
+ });
316
+ }
317
+
318
+ async function toWorkerInput(i: NativeInput, signal?: AbortSignal): Promise<WorkerInput> {
319
+ const fmt = i.format ? { format: i.format } : {};
320
+ switch (i.kind) {
321
+ case "native": return i.value as WorkerInput;
322
+ case "bytes": return { kind: "bytes", data: i.data.slice(), ...fmt };
323
+ case "url": {
324
+ if (/^https?:/i.test(i.url) && !isNode) {
325
+ const size = await httpSize(i.url, signal);
326
+ if (size > 0) return { kind: "http", url: i.url, size, ...fmt };
327
+ }
328
+ const res = await fetch(i.url, signal ? { signal } : {});
329
+ if (!res.ok) throw makeError("IO", `HTTP ${res.status} for ${i.url}`);
330
+ return blobInput(await res.blob(), i.format);
331
+ }
332
+ case "random": {
333
+ // Read through in 8 MiB parts into a Blob (which the browser may keep on disk).
334
+ const parts: Uint8Array[] = [];
335
+ for (let o = 0; o < i.size; o += 8 << 20) parts.push((await abortable(Promise.resolve(i.read(o, Math.min(8 << 20, i.size - o))), signal)).slice());
336
+ return blobInput(new Blob(parts as BlobPart[]), i.format);
337
+ }
338
+ case "stream": {
339
+ // Read whole before the job starts: an abort meanwhile cancels the stream.
340
+ const parts: Uint8Array[] = [];
341
+ const next = () => abortable(i.read(), signal, () => i.cancel?.());
342
+ for (let c = await next(); c; c = await next()) parts.push(c.slice());
343
+ return blobInput(new Blob(parts as BlobPart[]), i.format);
344
+ }
345
+ }
346
+ }
347
+
348
+ async function blobInput(blob: Blob, format?: string): Promise<WorkerInput> {
349
+ const fmt = format ? { format } : {};
350
+ // Node has no FileReaderSync: hand the worker bytes instead.
351
+ if (isNode) return { kind: "bytes", data: new Uint8Array(await blob.arrayBuffer()), ...fmt };
352
+ return { kind: "blob", blob, ...fmt };
353
+ }
354
+
355
+ async function httpSize(url: string, signal?: AbortSignal): Promise<number> {
356
+ try {
357
+ const r = await fetch(url, { headers: { Range: "bytes=0-0" }, ...(signal ? { signal } : {}) });
358
+ await r.body?.cancel().catch(() => {});
359
+ const cr = r.headers.get("content-range");
360
+ if (r.status === 206 && cr) return Number(cr.split("/")[1]) || -1;
361
+ } catch (e) {
362
+ if (signal?.aborted) throw e;
363
+ // CORS or network: fall back to a plain download.
364
+ }
365
+ return -1;
366
+ }
367
+
368
+ function isFileHandle(v: unknown): v is FileSystemFileHandle {
369
+ return v != null && typeof v === "object" && (v as FileSystemFileHandle).kind === "file" &&
370
+ typeof (v as FileSystemFileHandle).createWritable === "function";
371
+ }
372
+
373
+ /** Whether a file handle lives in the origin private file system. */
374
+ async function inOpfs(h: FileSystemFileHandle): Promise<boolean> {
375
+ try {
376
+ const root = await navigator.storage?.getDirectory?.();
377
+ return !!root && (await root.resolve(h)) !== null;
378
+ } catch {
379
+ return false;
380
+ }
381
+ }
382
+
383
+ // ---------------------------------------------------------------------------
384
+ // The engine
385
+
386
+ function workerJob(job: NativeJob): WorkerJob {
387
+ return {
388
+ threads: job.threads || (threaded() ? threadsPerJob() : 1),
389
+ progressInterval: job.progressInterval,
390
+ logLevel: job.logLevel,
391
+ progress: !!job.onProgress,
392
+ log: !!job.onLog,
393
+ };
394
+ }
395
+
396
+ const engine: Engine = {
397
+ name: "wasm",
398
+
399
+ async input(src: InputSource): Promise<NativeInput | null> {
400
+ const format = src && typeof src === "object" && "format" in src ? (src as { format?: string }).format : undefined;
401
+ const blob = isBlob(src) ? src : src && typeof src === "object" && "blob" in src && isBlob((src as { blob: Blob }).blob) ? (src as { blob: Blob }).blob : undefined;
402
+ if (blob) return { kind: "native", value: await blobInput(blob, format) };
403
+ let s: unknown = src;
404
+ if (src && typeof src === "object" && !(src instanceof URL) && "url" in src) s = (src as { url: string | URL }).url;
405
+ if (src && typeof src === "object" && !(src instanceof URL) && "path" in src) s = (src as { path: string }).path;
406
+ if (s instanceof URL) s = s.href;
407
+ if (typeof s === "string") {
408
+ if (isNode && !/^[a-z]+:/i.test(s)) {
409
+ // A path, under Node (tests, scripts): read it.
410
+ const fs = (globalThis as any).process.getBuiltinModule("node:fs/promises");
411
+ return { kind: "native", value: { kind: "bytes", data: new Uint8Array(await fs.readFile(s)), ...(format ? { format } : {}) } };
412
+ }
413
+ const abs = typeof location !== "undefined" ? new URL(s, location.href).href : s;
414
+ return { kind: "url", url: abs, ...(format ? { format } : {}) };
415
+ }
416
+ return null;
417
+ },
418
+
419
+ async output(target: OutputTarget, format: string | undefined): Promise<PreparedOutput | null> {
420
+ if (isFileHandle(target)) {
421
+ // OPFS files are written in place from the worker (seekable). Others,
422
+ // such as showSaveFilePicker() handles, only offer createWritable().
423
+ if (await inOpfs(target)) return { output: { kind: "native", value: { kind: "opfs", handle: target }, ...(format ? { format } : {}) } };
424
+ return commonOutput(await target.createWritable(), format);
425
+ }
426
+ if (typeof target === "string" || target instanceof URL)
427
+ throw makeError("INVALID_ARGUMENT", "in the browser, output goes to memory (omit output), a stream, a sink or a FileSystemFileHandle");
428
+ return null;
429
+ },
430
+
431
+ async run(task, inputs, output, options, job) {
432
+ const signal = job.signal;
433
+ if (signal?.aborted) throw new AbortError();
434
+ const winputs = await Promise.all(inputs.map((i) => toWorkerInput(i, signal)));
435
+ let wout: WorkerOutput | null = null;
436
+ let sink: Extract<NativeOutput, { kind: "sink" }> | undefined;
437
+ if (output) {
438
+ const fmt = output.format ? { format: output.format } : {};
439
+ if (output.kind === "memory") wout = { kind: "memory", ...fmt };
440
+ else if (output.kind === "native") wout = { ...(output.value as WorkerOutput), ...fmt };
441
+ else if (output.kind === "sink") { wout = { kind: "chunks", ...fmt }; sink = output; }
442
+ else throw makeError("INVALID_ARGUMENT", "unsupported output in the browser");
443
+ }
444
+ const host = await acquire(signal);
445
+ const id = nextId++;
446
+ const stop = (reason: Error) => {
447
+ if (host.variant === "mt") host.send({ t: "cancel", id });
448
+ else host.kill(reason); // a blocked single-threaded worker can only be stopped
449
+ };
450
+ // Chunks are written in order; the first failure stops the job at once.
451
+ let writes = Promise.resolve();
452
+ let writeError: { e: unknown } | undefined;
453
+ const onAbort = () => stop(new AbortError());
454
+ signal?.addEventListener("abort", onAbort, { once: true });
455
+ try {
456
+ const transfer = winputs.flatMap((i) => (i.kind === "bytes" ? [i.data.buffer as ArrayBuffer] : []));
457
+ const done = await host.request(
458
+ { t: "run", id, task, inputs: winputs, output: wout, options, job: workerJob(job) },
459
+ {
460
+ ...(job.onProgress ? { onProgress: job.onProgress } : {}),
461
+ ...(job.onLog ? { onLog: (l: string, m: string) => job.onLog!(l as any, m) } : {}),
462
+ ...(sink ? {
463
+ onChunk: (d: Uint8Array) => {
464
+ if (writeError) return;
465
+ writes = writes.then(() => sink!.write(d)).catch((e) => {
466
+ if (!writeError) { writeError = { e }; stop(makeError("IO", "writing the output failed")); }
467
+ });
468
+ },
469
+ } : {}),
470
+ },
471
+ transfer,
472
+ );
473
+ await writes;
474
+ if (writeError) throw writeError.e;
475
+ return { json: done.json, ...(done.data ? { data: done.data } : {}) };
476
+ } catch (e) {
477
+ if (signal?.aborted) throw new AbortError();
478
+ await writes;
479
+ if (writeError) throw writeError.e;
480
+ throw e;
481
+ } finally {
482
+ signal?.removeEventListener("abort", onAbort);
483
+ release(host);
484
+ }
485
+ },
486
+
487
+ async open(kind, input, options, job) {
488
+ const winput = await toWorkerInput(input, job.signal);
489
+ const host = await acquire(job.signal);
490
+ const id = nextId++;
491
+ let closed = false;
492
+ const close = async () => {
493
+ if (closed) return;
494
+ closed = true;
495
+ job.signal?.removeEventListener("abort", onAbort);
496
+ if (!host.dead) await host.request({ t: "close", id: nextId++, reader: id }, {}).catch(() => {});
497
+ release(host);
498
+ };
499
+ const onAbort = () => { void close(); };
500
+ job.signal?.addEventListener("abort", onAbort, { once: true });
501
+ let info: string;
502
+ try {
503
+ info = (await host.request({ t: "open", id, kind, input: winput, options, job: workerJob(job) }, {}, winput.kind === "bytes" ? [winput.data.buffer as ArrayBuffer] : [])).json;
504
+ } catch (e) {
505
+ await close();
506
+ if (job.signal?.aborted) throw new AbortError();
507
+ throw e;
508
+ }
509
+ // One request in flight at a time: the native reader is sequential.
510
+ let chain: Promise<unknown> = Promise.resolve();
511
+ return {
512
+ info,
513
+ next() {
514
+ const p = chain.then(async () => {
515
+ if (job.signal?.aborted) throw new AbortError();
516
+ if (closed) return null;
517
+ const r = await host.request({ t: "next", id: nextId++, reader: id }, {});
518
+ if (r.json === "null") return null;
519
+ const meta = JSON.parse(r.json) as Omit<NativeFrame, "data">;
520
+ return { ...meta, data: r.data ?? new Uint8Array() } as NativeFrame;
521
+ });
522
+ chain = p.catch(() => {});
523
+ return p;
524
+ },
525
+ close,
526
+ };
527
+ },
528
+
529
+ async capabilities() {
530
+ const host = await acquire();
531
+ try {
532
+ return (await host.request({ t: "caps", id: nextId++ }, {})).json;
533
+ } finally {
534
+ release(host);
535
+ }
536
+ },
537
+
538
+ async extraCapabilities() {
539
+ const webCodecs: string[] = [];
540
+ const VE = (globalThis as { VideoEncoder?: { isConfigSupported(c: object): Promise<{ supported?: boolean }> } }).VideoEncoder;
541
+ if (VE) {
542
+ const tries: Array<[string, string]> = [["h264", "avc1.42001f"], ["hevc", "hvc1.1.6.L93.B0"], ["vp9", "vp09.00.10.08"], ["av1", "av01.0.04M.08"], ["vp8", "vp8"]];
543
+ for (const [name, codec] of tries) {
544
+ try {
545
+ const r = await VE.isConfigSupported({ codec, width: 1280, height: 720, bitrate: 2_000_000, framerate: 30 });
546
+ if (r.supported) webCodecs.push(name);
547
+ } catch {
548
+ // Unsupported codec string.
549
+ }
550
+ }
551
+ }
552
+ return { threads: threaded(), webCodecs };
553
+ },
554
+ };
555
+
556
+ const api = createApi(engine);
557
+
558
+ export const {
559
+ probe,
560
+ transcode,
561
+ thumbnail,
562
+ thumbnails,
563
+ waveform,
564
+ frames,
565
+ samples,
566
+ remux,
567
+ trim,
568
+ extractAudio,
569
+ concat,
570
+ capabilities,
571
+ canEncode,
572
+ canDecode,
573
+ } = api;
574
+
575
+ /** Starts the worker and compiles the module now, so the first job doesn't wait for it. */
576
+ export async function preload(): Promise<void> {
577
+ release(await acquire());
578
+ }
579
+
580
+ /** Stops every worker; jobs running or waiting reject with an AbortError. The next job starts a fresh one. */
581
+ export function terminate(): void {
582
+ const reason = new AbortError("terminated");
583
+ for (const w of queue.splice(0)) w.fail(reason);
584
+ shared?.kill(reason);
585
+ shared = undefined;
586
+ for (const h of pool.splice(0)) h.kill(reason);
587
+ }
588
+
589
+ export default api;
@@ -0,0 +1,40 @@
1
+ /** Messages between the page and a host worker. */
2
+
3
+ export type WorkerInput =
4
+ | { kind: "blob"; blob: Blob; format?: string }
5
+ | { kind: "bytes"; data: Uint8Array; format?: string }
6
+ | { kind: "http"; url: string; size: number; format?: string }
7
+ | { kind: "path"; path: string; format?: string };
8
+
9
+ export type WorkerOutput =
10
+ | { kind: "memory"; format?: string }
11
+ | { kind: "chunks"; format?: string }
12
+ | { kind: "opfs"; handle: FileSystemFileHandle; format?: string };
13
+
14
+ export interface WorkerJob {
15
+ threads: number;
16
+ progressInterval: number;
17
+ logLevel: string;
18
+ progress: boolean;
19
+ log: boolean;
20
+ }
21
+
22
+ export type ToWorker =
23
+ | { t: "init"; variant: "mt" | "st"; base?: string; warm?: number }
24
+ | { t: "caps"; id: number }
25
+ | { t: "run"; id: number; task: string; inputs: WorkerInput[]; output: WorkerOutput | null; options: string; job: WorkerJob }
26
+ | { t: "cancel"; id: number }
27
+ | { t: "open"; id: number; kind: "frames" | "samples"; input: WorkerInput; options: string; job: WorkerJob }
28
+ /** `reader` is the open request's id; `id` is this request's own (a close may overtake an open or a next). */
29
+ | { t: "next"; id: number; reader: number }
30
+ | { t: "close"; id: number; reader: number };
31
+
32
+ export type FromWorker =
33
+ | { t: "ready"; version: string }
34
+ | { t: "progress"; id: number; progress: import("@muxen/core").Progress }
35
+ | { t: "log"; id: number; level: string; message: string }
36
+ | { t: "chunk"; id: number; data: Uint8Array }
37
+ | { t: "done"; id: number; json: string; data?: Uint8Array }
38
+ | { t: "error"; id: number; code: string; message: string }
39
+ /** The module is unusable (it aborted: out of memory, a trap): the page replaces the worker. */
40
+ | { t: "fatal"; message: string };