html-video-element-webworker-polyfill 0.1.0 → 0.1.1

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.
Files changed (2) hide show
  1. package/README.md +35 -206
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  [![CI](https://github.com/stepancar/html-video-element-webworker-polyfill/actions/workflows/ci.yml/badge.svg)](https://github.com/stepancar/html-video-element-webworker-polyfill/actions/workflows/ci.yml)
4
4
  [![npm](https://img.shields.io/npm/v/html-video-element-webworker-polyfill)](https://www.npmjs.com/package/html-video-element-webworker-polyfill)
5
5
 
6
- Use `HTMLVideoElement` inside a Web Worker. In `worker.ts`:
6
+ Create and control an `HTMLVideoElement` from a Web Worker and read its decoded frames there.
7
7
 
8
8
  ```ts
9
9
  const video = document.createElement("video");
@@ -14,25 +14,14 @@ video.addEventListener("seeked", () => {
14
14
  video.currentTime = 12.5;
15
15
  ```
16
16
 
17
- OffscreenCanvas 2D, WebGL and WebGPU accept the element too.
18
-
19
- Workers have no DOM, so this package keeps a real `<video>` on the main thread and mirrors it into the worker:
20
- properties and method calls go to the main thread, state and events come back, and every decoded frame is
21
- transferred to the worker as a `VideoFrame`. The worker keeps the current frame, so it can be read **synchronously**
22
- — in a `seeked` handler, a `requestVideoFrameCallback` callback, or anywhere else.
23
-
24
- **[Live demo →](https://stepancar.github.io/html-video-element-webworker-polyfill/)** — a small video editor whose
25
- playback, WebGL effects, picture-in-picture and timeline thumbnails are all rendered in a worker.
26
-
27
- **[Open the minimal example in StackBlitz →](https://stackblitz.com/github/stepancar/html-video-element-webworker-polyfill/tree/main/examples/stackblitz?file=worker.js&initialPath=/index.html&startScript=start)**
17
+ **[Live demo](https://stepancar.github.io/html-video-element-webworker-polyfill/)** ·
18
+ **[Open in StackBlitz](https://stackblitz.com/github/stepancar/html-video-element-webworker-polyfill/tree/main/examples/stackblitz?file=worker.js&initialPath=/index.html&startScript=start)**
28
19
 
29
20
  ## Why not WebCodecs?
30
21
 
31
- WebCodecs gives you a decoder, not a player. With `VideoDecoder` you demux every container yourself (mp4box.js, a
32
- WebM parser, …), configure codecs, feed chunks, find keyframes to seek and handle streaming and buffering.
33
- `HTMLVideoElement` already does all of that for every format the browser can play — MP4, WebM, MOV, MSE streams, HLS
34
- where supported — and gives you frame-accurate seeking with `currentTime` and `seeked`. For frame processing it is
35
- usually exactly the right tool; it just does not exist in workers. This package makes it available there.
22
+ WebCodecs gives you a decoder, not a player: you demux containers yourself, configure codecs, feed chunks and find
23
+ keyframes to seek. `HTMLVideoElement` already handles every format the browser can play and gives frame-accurate
24
+ seeking out of the box. It just does not exist in workers. This package makes it available there.
36
25
 
37
26
  ## Install
38
27
 
@@ -40,20 +29,18 @@ usually exactly the right tool; it just does not exist in workers. This package
40
29
  npm install html-video-element-webworker-polyfill
41
30
  ```
42
31
 
43
- ## Quick start
32
+ ## Usage
44
33
 
45
- **Main thread** — serve video elements to the worker. This is the only main-thread code you need; call it right after
46
- creating the worker:
34
+ Main thread:
47
35
 
48
36
  ```ts
49
37
  import { createVideoHost } from "html-video-element-webworker-polyfill/host";
50
38
 
51
39
  const worker = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" });
52
- const host = createVideoHost(worker);
40
+ createVideoHost(worker);
53
41
  ```
54
42
 
55
- **Worker** — use the standard API. `polyfillDocument()` enables `document.createElement("video")` and
56
- `polyfill2dCanvasApi()` enables `ctx.drawImage(video, ...)`:
43
+ Worker:
57
44
 
58
45
  ```ts
59
46
  import { polyfillDocument } from "html-video-element-webworker-polyfill/worker";
@@ -62,13 +49,9 @@ import { polyfill2dCanvasApi } from "html-video-element-webworker-polyfill/canva
62
49
  polyfillDocument();
63
50
  polyfill2dCanvasApi();
64
51
 
65
- const canvas = new OffscreenCanvas(640, 360);
66
- const ctx = canvas.getContext("2d")!;
67
-
52
+ const ctx = new OffscreenCanvas(640, 360).getContext("2d")!;
68
53
  const video = document.createElement("video");
69
- video.muted = true;
70
54
  video.src = "/movie.webm";
71
-
72
55
  video.addEventListener("loadedmetadata", () => {
73
56
  video.currentTime = 10;
74
57
  });
@@ -77,7 +60,7 @@ video.addEventListener("seeked", () => {
77
60
  });
78
61
  ```
79
62
 
80
- …or the explicit, non-standard API that needs no global patches:
63
+ Or without global patches:
81
64
 
82
65
  ```ts
83
66
  import { createVideoElement } from "html-video-element-webworker-polyfill/worker";
@@ -86,197 +69,43 @@ const video = createVideoElement();
86
69
  video.src = "/movie.webm";
87
70
  await video.play();
88
71
 
89
- video.requestVideoFrameCallback(function onFrame(now, metadata) {
90
- const frame = video.currentFrame;
91
- render(frame);
72
+ video.requestVideoFrameCallback(function onFrame() {
73
+ render(video.currentFrame);
92
74
  video.requestVideoFrameCallback(onFrame);
93
75
  });
94
76
 
95
77
  video.dispose();
96
78
  ```
97
79
 
98
- `currentFrame` is a `VideoFrame` (or `null`) and is always the frame on screen. `dispose()` releases the element
99
- when you are done.
100
-
101
- Prefer a single import? `import "html-video-element-webworker-polyfill/auto"` inside the worker installs every
102
- polyfill.
103
-
104
- ## Entry points
105
-
106
- Every feature is a separate subpath with no side effects (except `auto`), so bundles only contain what you import.
107
- Importing from the package root tree-shakes just as well.
108
-
109
- | Import | Where | Exports | Size (min, approx.) |
110
- | ---------------------------------------------------- | ----------- | ----------------------------------------------------------------------------------------- | ------------------- |
111
- | `html-video-element-webworker-polyfill/host` | main thread | `createVideoHost` | 10 kB |
112
- | `html-video-element-webworker-polyfill/worker` | worker | `createVideoElement`, `WorkerVideoElement`, `polyfillDocument`, `configureVideoTransport` | 22 kB |
113
- | `html-video-element-webworker-polyfill/canvas2d` | worker | `polyfill2dCanvasApi` | 2.6 kB |
114
- | `html-video-element-webworker-polyfill/webgl` | worker | `polyfillWebglAPI` | 2.6 kB |
115
- | `html-video-element-webworker-polyfill/webgpu` | worker | `polyfillWebgpu` | 2.7 kB |
116
- | `html-video-element-webworker-polyfill/image-bitmap` | worker | `polyfillCreateImageBitmap`, `polyfillVideoFrame` | 2.6 kB |
117
- | `html-video-element-webworker-polyfill/auto` | worker | side effect: installs everything above | 29 kB |
118
- | `html-video-element-webworker-polyfill` | both | all of the above + `installWorkerPolyfills`, `frameOf` | — |
119
-
120
- `npm run check:treeshake` bundles each import with Rolldown and asserts that e.g. `polyfillWebglAPI` pulls in neither the
121
- element nor the host.
122
-
123
80
  ## API
124
81
 
125
- ### `createVideoHost(endpoint, options?)` — main thread
126
-
127
- `endpoint` is a `Worker` or a `MessagePort`. Several workers can each have their own host, and each host serves any
128
- number of elements. Messages are tagged, so the channel can be shared with your own messages.
129
-
130
- ```ts
131
- interface VideoHostOptions {
132
- container?: HTMLElement | null;
133
- onVideoCreated?(video: HTMLVideoElement, id: number): void;
134
- onVideoDisposed?(video: HTMLVideoElement, id: number): void;
135
- }
136
-
137
- interface VideoHost {
138
- readonly videos: ReadonlyMap<number, HTMLVideoElement>;
139
- dispose(): void;
140
- }
141
- ```
142
-
143
- `container` mounts the real `<video>` elements into the DOM (by default they stay detached). `videos` lists the live
144
- real elements. `dispose()` releases everything, e.g. before `worker.terminate()`.
145
-
146
- ### `WorkerVideoElement` — worker
147
-
148
- An `EventTarget` implementing the `HTMLVideoElement`/`HTMLMediaElement` API:
149
-
150
- - **State**: `currentTime` (get/set), `duration`, `paused`, `ended`, `seeking`, `readyState`, `networkState`,
151
- `videoWidth`, `videoHeight`, `currentSrc`, `error` (`MediaError`), `buffered`/`played`/`seekable` (`TimeRanges`).
152
- - **Settings**: `src`, `srcObject` (a `MediaSourceHandle` from a worker-side `MediaSource`), `muted`, `volume`,
153
- `playbackRate`, `defaultPlaybackRate`, `defaultMuted`, `loop`, `autoplay`, `preload`, `crossOrigin`, `poster`,
154
- `playsInline`, `preservesPitch`, `width`, `height`, `controls`, `disablePictureInPicture`, `disableRemotePlayback`.
155
- - **Methods**: `play()` (promise), `pause()`, `load()`, `fastSeek()`, `canPlayType()`, `getVideoPlaybackQuality()`,
156
- `requestVideoFrameCallback()`, `cancelVideoFrameCallback()`, `getAttribute`/`setAttribute`/`hasAttribute`/
157
- `removeAttribute` (for reflected attributes such as `src`, `loop`, `muted`, `crossorigin`).
158
- - **Events**: every media event (`loadstart`, `loadedmetadata`, `loadeddata`, `canplay`, `play`, `playing`, `pause`,
159
- `seeking`, `seeked`, `timeupdate`, `ended`, `error`, `emptied`, `resize`, `volumechange`, `ratechange`, …) via
160
- `addEventListener` or `on<event>` properties.
161
- - **Non-standard**:
162
- - `currentFrame: VideoFrame | null` — the frame currently presented. It is owned by the element and closed when the
163
- next frame arrives; `clone()` it to keep it longer.
164
- - `dispose()` / `[Symbol.dispose]()` (works with `using`) and `disposed`.
165
-
166
- `createVideoElement({ transport? })` creates one. `transport` overrides the endpoint (default: the worker global
167
- scope, or what you passed to `configureVideoTransport`).
168
-
169
- ### Rendering polyfills — worker
170
-
171
- Each patches prototypes once (idempotent) so that the element is accepted wherever a real video is:
172
-
173
- | Function | Patches |
174
- | ----------------------------- | --------------------------------------------------------------------------------------------------------------- |
175
- | `polyfill2dCanvasApi()` | `OffscreenCanvasRenderingContext2D` `drawImage` (all overloads), `createPattern` |
176
- | `polyfillWebglAPI()` | WebGL 1 & 2 `texImage2D`, `texSubImage2D`, `texImage3D`, `texSubImage3D` (all overloads) |
177
- | `polyfillWebgpu()` | `GPUQueue.copyExternalImageToTexture({ source })`, `GPUDevice.importExternalTexture({ source })` |
178
- | `polyfillCreateImageBitmap()` | `createImageBitmap(video, ...)` |
179
- | `polyfillVideoFrame()` | `new VideoFrame(video, init)` (a `Proxy`, so `instanceof VideoFrame` is unaffected) |
180
- | `polyfillDocument()` | `document.createElement("video")`, plus `HTMLVideoElement`/`HTMLMediaElement`/`MediaError`/`TimeRanges` globals |
181
-
182
- As with real elements, drawing a video that has no data yet is a no-op, while `createImageBitmap`, `new VideoFrame`
183
- and WebGPU throw `InvalidStateError`.
184
-
185
- If you do not want global patches, pass `video.currentFrame` (a regular `VideoFrame`) to any of these APIs.
186
-
187
- ### Environment checks
188
-
189
- Every function verifies that it runs where it belongs and throws an `InvalidEnvironmentError` otherwise:
190
-
191
- | Runs only on the main thread | Runs only inside a worker |
192
- | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
193
- | `createVideoHost` | `createVideoElement`, `new WorkerVideoElement()`, `polyfillDocument`, `configureVideoTransport`, `polyfill2dCanvasApi`, `polyfillWebglAPI`, `polyfillWebgpu`, `polyfillCreateImageBitmap`, `polyfillVideoFrame`, `installWorkerPolyfills`, the `auto` entry |
194
-
195
- So a worker-side polyfill can never patch `document.createElement` or canvas prototypes of the page by mistake.
196
- `isMainThread()` and `isWorker()` are exported for your own checks.
197
-
198
- Common mistakes are reported too:
199
-
200
- - `createVideoHost()` throws a `TypeError` unless it gets a `Worker` or `MessagePort`, and an `InvalidStateError` when
201
- the same endpoint is attached twice (call `dispose()` on the previous host first).
202
- - `createVideoElement({ transport })` and `configureVideoTransport()` throw a `TypeError` for anything that is not a
203
- message endpoint.
204
- - A worker that creates video elements without a host on the main thread logs a warning after 3 seconds, since its
205
- videos would never load.
206
-
207
- ## How it works
208
-
209
- ```
210
- worker main thread
211
- ────── ───────────
212
- video.currentTime = 5 ── set(seq=7) ─────────▶ realVideo.currentTime = 5
213
- (reads 5 immediately) ◀── state(ack=7) ─────── snapshot
214
- "seeked" listeners run ◀── event + VideoFrame ── "seeked" fires, new VideoFrame(realVideo)
215
- video.currentFrame ◀── frame + metadata ─── requestVideoFrameCallback on realVideo
216
- ```
217
-
218
- - **Optimistic writes.** Setters update the worker-side state immediately, as browsers do (`currentTime` returns the new
219
- value, `paused` flips on `play()`). Each command carries a sequence number; state snapshots from the main thread are
220
- only applied to a property once they acknowledge its latest local write, so stale updates never overwrite it.
221
- - **Events carry state.** Every forwarded event includes a full state snapshot, applied before your listeners run.
222
- `seeked` and `loadeddata` also carry the new frame, so `currentFrame` is already correct inside the handler.
223
- - **Frames.** The host captures a `VideoFrame` for every presented frame (`requestVideoFrameCallback`) and transfers it
224
- (zero-copy). The worker closes the previous frame. `requestVideoFrameCallback` metadata is converted to the worker's
225
- time origin.
226
- - **Backpressure.** Only one frame is in flight at a time. When the worker is busy, the host keeps just the newest
227
- frame and sends it once the worker is ready, so a slow consumer always sees fresh frames instead of a backlog.
228
- - **Cleanup.** `dispose()` releases the main-thread element and the current frame. Elements that become unreachable are
229
- released automatically through `FinalizationRegistry`; like real media elements, an element is kept alive while it
230
- is playing.
231
-
232
- ## Caveats
233
-
234
- - The main thread must be alive: frames are produced there. A long main-thread task delays frames to the worker.
235
- - Cross-origin media needs CORS (`video.crossOrigin = "anonymous"` and an `Access-Control-Allow-Origin` header), or no
236
- frames can be captured — the same rule as for drawing a video on a canvas.
237
- - Browsers pause video-only media in background tabs to save power; the polyfilled element behaves the same way.
238
- - `canPlayType()` is synchronous. Common types are answered from a table sent by the host; others are guessed with
239
- `MediaSource.isTypeSupported` and refined once the host has answered.
240
- - `polyfillDocument()` defines `document` in the worker, which may make some libraries think they are on the main
241
- thread. Use `createVideoElement()` when that matters.
242
- - Requires `VideoFrame` (WebCodecs) and `requestVideoFrameCallback` on the main thread: Chrome/Edge 94+, Firefox 132+,
243
- Safari 17+ (the test suite runs in Chromium).
244
-
245
- ## Development
246
-
247
- ```sh
248
- npm install
249
- npx playwright install chromium
250
- ```
251
-
252
- | Command | Purpose |
253
- | --------------------------- | ------------------------------------------------------------------- |
254
- | `npm test` | browser tests (Vitest browser mode + Playwright) |
255
- | `npm run test:update` | update screenshot references for your platform |
256
- | `npm run test:update-linux` | update Linux references in the Playwright Docker image (used by CI) |
257
- | `npm run lint` | oxlint |
258
- | `npm run format` | oxfmt |
259
- | `npm run typecheck` | tsc |
260
- | `npm run build` | tsdown → `dist/` |
261
- | `npm run check:treeshake` | verify each entry point stays small |
262
- | `npm run demo:dev` | demo on http://localhost:5173 |
82
+ | Import | Exports |
83
+ | ---------------------------------------------------- | ------------------------------------------------------------------------------- |
84
+ | `html-video-element-webworker-polyfill/host` | `createVideoHost(worker, { container? })` — main thread |
85
+ | `html-video-element-webworker-polyfill/worker` | `createVideoElement()`, `WorkerVideoElement`, `polyfillDocument()` |
86
+ | `html-video-element-webworker-polyfill/canvas2d` | `polyfill2dCanvasApi()` — `drawImage(video)`, `createPattern(video)` |
87
+ | `html-video-element-webworker-polyfill/webgl` | `polyfillWebglAPI()` — `texImage2D(video)` and friends, WebGL 1 and 2 |
88
+ | `html-video-element-webworker-polyfill/webgpu` | `polyfillWebgpu()` — `copyExternalImageToTexture`, `importExternalTexture` |
89
+ | `html-video-element-webworker-polyfill/image-bitmap` | `polyfillCreateImageBitmap()`, `polyfillVideoFrame()` — `new VideoFrame(video)` |
90
+ | `html-video-element-webworker-polyfill/auto` | installs every worker polyfill |
263
91
 
264
- The tests run in real Chromium. They cover the whole round trip — loading, seeking with synchronous frame access,
265
- playback, events, properties, many elements, `dispose()`, garbage collection, Media Source Extensions — and every
266
- rendering polyfill, with pixel assertions and screenshot comparisons (`test/__screenshots__`).
92
+ Each entry point is tree-shakeable, so you only ship what you import.
267
93
 
268
- ### Releasing
94
+ The worker element implements the `HTMLVideoElement` API: properties, `play()`, `pause()`, `load()`, seeking, media
95
+ events and `requestVideoFrameCallback`. It adds two non-standard members:
269
96
 
270
- Releases are published from GitHub Actions with npm trusted publishing (OIDC): no npm token is stored anywhere, and
271
- every version gets a provenance attestation.
97
+ - `currentFrame` — the `VideoFrame` currently on screen, or `null`. It is closed when the next frame arrives; `clone()`
98
+ it to keep it.
99
+ - `dispose()` — releases the element. Unreferenced elements are also released automatically on garbage collection.
272
100
 
273
- 1. Bump `version` in `package.json` and push to `main`.
274
- 2. Publish a GitHub release tagged `v<version>`. The `Release` workflow tests, builds and runs `npm publish`.
101
+ Calling a main-thread function in a worker, or a worker function on the main thread, throws an
102
+ `InvalidEnvironmentError`.
275
103
 
276
- One-time setup on npmjs.com: package settings → Trusted Publisher → GitHub Actions, with repository
277
- `stepancar/html-video-element-webworker-polyfill` and workflow `release.yml`.
104
+ ## Notes
278
105
 
279
- The demo is deployed to GitHub Pages on every push to `main`.
106
+ - Cross-origin media needs CORS (`crossOrigin = "anonymous"`), as with drawing a video on a canvas.
107
+ - Frames are decoded on the main thread, so it must not be blocked for long.
108
+ - Requires `VideoFrame` and `requestVideoFrameCallback`: Chrome/Edge 94+, Firefox 132+, Safari 17+.
280
109
 
281
110
  ## License
282
111
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "html-video-element-webworker-polyfill",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "HTMLVideoElement inside Web Workers: a main-thread <video> mirrored into the worker with synchronous state, events and VideoFrames, plus Canvas 2D / WebGL / WebGPU polyfills.",
5
5
  "keywords": [
6
6
  "htmlvideoelement",