html-video-element-webworker-polyfill 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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,283 @@
1
- # Temporary Holding Version
1
+ # html-video-element-webworker-polyfill
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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
+ [![npm](https://img.shields.io/npm/v/html-video-element-webworker-polyfill)](https://www.npmjs.com/package/html-video-element-webworker-polyfill)
5
+
6
+ Use `HTMLVideoElement` inside a Web Worker. In `worker.ts`:
7
+
8
+ ```ts
9
+ const video = document.createElement("video");
10
+ video.src = "https://example.com/movie.webm";
11
+ video.addEventListener("seeked", () => {
12
+ ctx.drawImage(video, 0, 0);
13
+ });
14
+ video.currentTime = 12.5;
15
+ ```
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)**
28
+
29
+ ## Why not WebCodecs?
30
+
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.
36
+
37
+ ## Install
38
+
39
+ ```sh
40
+ npm install html-video-element-webworker-polyfill
41
+ ```
42
+
43
+ ## Quick start
44
+
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:
47
+
48
+ ```ts
49
+ import { createVideoHost } from "html-video-element-webworker-polyfill/host";
50
+
51
+ const worker = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" });
52
+ const host = createVideoHost(worker);
53
+ ```
54
+
55
+ **Worker** — use the standard API. `polyfillDocument()` enables `document.createElement("video")` and
56
+ `polyfill2dCanvasApi()` enables `ctx.drawImage(video, ...)`:
57
+
58
+ ```ts
59
+ import { polyfillDocument } from "html-video-element-webworker-polyfill/worker";
60
+ import { polyfill2dCanvasApi } from "html-video-element-webworker-polyfill/canvas2d";
61
+
62
+ polyfillDocument();
63
+ polyfill2dCanvasApi();
64
+
65
+ const canvas = new OffscreenCanvas(640, 360);
66
+ const ctx = canvas.getContext("2d")!;
67
+
68
+ const video = document.createElement("video");
69
+ video.muted = true;
70
+ video.src = "/movie.webm";
71
+
72
+ video.addEventListener("loadedmetadata", () => {
73
+ video.currentTime = 10;
74
+ });
75
+ video.addEventListener("seeked", () => {
76
+ ctx.drawImage(video, 0, 0, 640, 360);
77
+ });
78
+ ```
79
+
80
+ …or the explicit, non-standard API that needs no global patches:
81
+
82
+ ```ts
83
+ import { createVideoElement } from "html-video-element-webworker-polyfill/worker";
84
+
85
+ const video = createVideoElement();
86
+ video.src = "/movie.webm";
87
+ await video.play();
88
+
89
+ video.requestVideoFrameCallback(function onFrame(now, metadata) {
90
+ const frame = video.currentFrame;
91
+ render(frame);
92
+ video.requestVideoFrameCallback(onFrame);
93
+ });
94
+
95
+ video.dispose();
96
+ ```
97
+
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
+ ## API
124
+
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 |
263
+
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__`).
267
+
268
+ ### Releasing
269
+
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.
272
+
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`.
275
+
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`.
278
+
279
+ The demo is deployed to GitHub Pages on every push to `main`.
280
+
281
+ ## License
282
+
283
+ Apache-2.0
package/dist/auto.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {}
package/dist/auto.js ADDED
@@ -0,0 +1,6 @@
1
+ import { t as installWorkerPolyfills } from "./install-BDVttfHM.js";
2
+ //#region src/auto.ts
3
+ installWorkerPolyfills();
4
+ //#endregion
5
+
6
+ //# sourceMappingURL=auto.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto.js","names":[],"sources":["../src/auto.ts"],"sourcesContent":["import { installWorkerPolyfills } from \"./install.ts\";\n\ninstallWorkerPolyfills();\n"],"mappings":";;AAEA,uBAAuB"}
@@ -0,0 +1,4 @@
1
+ //#region src/polyfills/canvas2d.d.ts
2
+ export declare function polyfill2dCanvasApi(): void;
3
+ //#endregion
4
+ //# sourceMappingURL=canvas2d.d.ts.map
@@ -0,0 +1,15 @@
1
+ import { r as assertWorker } from "./environment-De2r8LaA.js";
2
+ import { a as patchMethod, o as unwrapArgs } from "./frame-source-BG--PzqD.js";
3
+ //#region src/polyfills/canvas2d.ts
4
+ function polyfill2dCanvasApi() {
5
+ assertWorker("polyfill2dCanvasApi()");
6
+ const scope = globalThis;
7
+ for (const ctor of [scope.OffscreenCanvasRenderingContext2D, scope.CanvasRenderingContext2D]) {
8
+ patchMethod(ctor?.prototype, "drawImage", unwrapArgs);
9
+ patchMethod(ctor?.prototype, "createPattern", unwrapArgs, () => null);
10
+ }
11
+ }
12
+ //#endregion
13
+ export { polyfill2dCanvasApi };
14
+
15
+ //# sourceMappingURL=canvas2d.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"canvas2d.js","names":[],"sources":["../src/polyfills/canvas2d.ts"],"sourcesContent":["import { assertWorker } from \"../shared/environment.ts\";\nimport { patchMethod, unwrapArgs } from \"../shared/frame-source.ts\";\n\nexport function polyfill2dCanvasApi(): void {\n assertWorker(\"polyfill2dCanvasApi()\");\n const scope = globalThis as {\n OffscreenCanvasRenderingContext2D?: { prototype: object };\n CanvasRenderingContext2D?: { prototype: object };\n };\n for (const ctor of [scope.OffscreenCanvasRenderingContext2D, scope.CanvasRenderingContext2D]) {\n patchMethod(ctor?.prototype, \"drawImage\", unwrapArgs);\n patchMethod(ctor?.prototype, \"createPattern\", unwrapArgs, () => null);\n }\n}\n"],"mappings":";;;AAGA,SAAgB,sBAA4B;CAC1C,aAAa,uBAAuB;CACpC,MAAM,QAAQ;CAId,KAAK,MAAM,QAAQ,CAAC,MAAM,mCAAmC,MAAM,wBAAwB,GAAG;EAC5F,YAAY,MAAM,WAAW,aAAa,UAAU;EACpD,YAAY,MAAM,WAAW,iBAAiB,kBAAkB,IAAI;CACtE;AACF"}