@openartifactsai/motion-export 0.0.0-stage → 0.23.0-rc.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.
Files changed (97) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +5 -2
  4. package/package.json +58 -4
  5. package/src/build.d.ts +17 -0
  6. package/src/build.js +52 -0
  7. package/src/captions-file.d.ts +13 -0
  8. package/src/captions-file.js +15 -0
  9. package/src/clip/in-worker.d.ts +49 -0
  10. package/src/clip/in-worker.js +96 -0
  11. package/src/clip/jobs.d.ts +28 -0
  12. package/src/clip/jobs.js +2 -0
  13. package/src/clip/part.d.ts +25 -0
  14. package/src/clip/part.js +112 -0
  15. package/src/clip/problem.d.ts +25 -0
  16. package/src/clip/problem.js +10 -0
  17. package/src/clip/worker.d.ts +2 -0
  18. package/src/clip/worker.js +24 -0
  19. package/src/engine.d.ts +46 -0
  20. package/src/engine.js +225 -0
  21. package/src/errors.d.ts +78 -0
  22. package/src/errors.js +102 -0
  23. package/src/estimate.d.ts +27 -0
  24. package/src/estimate.js +103 -0
  25. package/src/filename.d.ts +14 -0
  26. package/src/filename.js +44 -0
  27. package/src/frame-source.d.ts +57 -0
  28. package/src/frame-source.js +1 -0
  29. package/src/frames-video.d.ts +45 -0
  30. package/src/frames-video.js +52 -0
  31. package/src/frames.d.ts +36 -0
  32. package/src/frames.js +112 -0
  33. package/src/gif/encode.d.ts +23 -0
  34. package/src/gif/encode.js +60 -0
  35. package/src/gif/estimator.d.ts +50 -0
  36. package/src/gif/estimator.js +82 -0
  37. package/src/gif/surface.d.ts +8 -0
  38. package/src/gif/surface.js +20 -0
  39. package/src/index.d.ts +34 -0
  40. package/src/index.js +18 -0
  41. package/src/mov/encode.d.ts +32 -0
  42. package/src/mov/encode.js +69 -0
  43. package/src/mov/estimate.d.ts +20 -0
  44. package/src/mov/estimate.js +33 -0
  45. package/src/mov/plan.d.ts +25 -0
  46. package/src/mov/plan.js +14 -0
  47. package/src/mov/surface.d.ts +4 -0
  48. package/src/mov/surface.js +20 -0
  49. package/src/plan.d.ts +54 -0
  50. package/src/plan.js +76 -0
  51. package/src/problems.d.ts +10 -0
  52. package/src/problems.js +32 -0
  53. package/src/raster/document.d.ts +7 -0
  54. package/src/raster/document.js +15 -0
  55. package/src/raster/frame-entry.d.ts +1 -0
  56. package/src/raster/frame-entry.js +36 -0
  57. package/src/raster/host.d.ts +28 -0
  58. package/src/raster/host.js +191 -0
  59. package/src/raster/messages.d.ts +34 -0
  60. package/src/raster/messages.js +25 -0
  61. package/src/source/layout.d.ts +49 -0
  62. package/src/source/layout.js +83 -0
  63. package/src/source/names.d.ts +14 -0
  64. package/src/source/names.js +65 -0
  65. package/src/source/readme.d.ts +17 -0
  66. package/src/source/readme.js +43 -0
  67. package/src/source/zip.d.ts +27 -0
  68. package/src/source/zip.js +61 -0
  69. package/src/stage-frame.d.ts +12 -0
  70. package/src/stage-frame.js +61 -0
  71. package/src/standalone/audio-entry.d.ts +1 -0
  72. package/src/standalone/audio-entry.js +80 -0
  73. package/src/standalone/clip-footage.d.ts +4 -0
  74. package/src/standalone/clip-footage.js +38 -0
  75. package/src/standalone/html.d.ts +35 -0
  76. package/src/standalone/html.js +60 -0
  77. package/src/types.d.ts +63 -0
  78. package/src/types.js +1 -0
  79. package/src/video/attempts.d.ts +55 -0
  80. package/src/video/attempts.js +73 -0
  81. package/src/video/avc.d.ts +15 -0
  82. package/src/video/avc.js +158 -0
  83. package/src/video/encode-attempt.d.ts +39 -0
  84. package/src/video/encode-attempt.js +157 -0
  85. package/src/video/encode.d.ts +6 -0
  86. package/src/video/encode.js +66 -0
  87. package/src/video/format.d.ts +22 -0
  88. package/src/video/format.js +41 -0
  89. package/src/video/output.d.ts +12 -0
  90. package/src/video/output.js +38 -0
  91. package/src/virtual.d.ts +11 -0
  92. package/src/visibility.d.ts +45 -0
  93. package/src/visibility.js +131 -0
  94. package/src/vite.d.ts +8 -0
  95. package/src/vite.js +43 -0
  96. package/src/words.d.ts +37 -0
  97. package/src/words.js +37 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ Open Artifacts
2
+ Copyright 2026 Jim Liu 宝玉
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+ It was formerly published as baoyu-design.
package/README.md CHANGED
@@ -1,3 +1,6 @@
1
- # Temporary Holding Version
1
+ # @openartifactsai/motion-export
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
+ Motion exports in the browser: MP4 (WebCodecs + mediabunny), GIF, MOV with alpha (QuickTime Animation), the source ZIP and the standalone HTML player, with the raster frame, estimates and font licences.
4
+
5
+ Part of [Open Artifacts](https://github.com/openartifactsai/open-artifacts): slide decks, design canvases and whiteboards an agent makes
6
+ and you view, edit and comment on in one local page. Source: [`packages/motion-export`](https://github.com/openartifactsai/open-artifacts/tree/main/packages/motion-export).
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@openartifactsai/motion-export",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.23.0-rc.0",
4
+ "description": "Motion exports in the browser: MP4 (WebCodecs + mediabunny), GIF, MOV with alpha (QuickTime Animation), the source ZIP and the standalone HTML player, with the raster frame, estimates and font licences.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./src/index.d.ts",
9
+ "default": "./src/index.js"
10
+ },
11
+ "./build": {
12
+ "types": "./src/build.d.ts",
13
+ "default": "./src/build.js"
14
+ },
15
+ "./frames": {
16
+ "types": "./src/frames-video.d.ts",
17
+ "default": "./src/frames-video.js"
18
+ },
19
+ "./vite": {
20
+ "types": "./src/vite.d.ts",
21
+ "default": "./src/vite.js"
22
+ },
23
+ "./virtual": {
24
+ "types": "./src/virtual.d.ts"
25
+ },
26
+ "./package.json": "./package.json"
27
+ },
28
+ "files": [
29
+ "src",
30
+ "LICENSE",
31
+ "NOTICE"
32
+ ],
33
+ "dependencies": {
34
+ "@openartifactsai/motion-audio": "0.23.0-rc.0",
35
+ "@openartifactsai/motion-core": "0.23.0-rc.0",
36
+ "@openartifactsai/motion-stage": "0.23.0-rc.0",
37
+ "@openartifactsai/wasm-export": "0.23.0-rc.0",
38
+ "@openartifactsai/wasm-motion": "0.23.0-rc.0",
39
+ "esbuild": "^0.25.12",
40
+ "mediabunny": "^1.63.0",
41
+ "vite": "^7.3.8"
42
+ },
43
+ "license": "Apache-2.0",
44
+ "author": {
45
+ "name": "Jim Liu 宝玉",
46
+ "url": "https://github.com/JimLiu"
47
+ },
48
+ "homepage": "https://github.com/openartifactsai/open-artifacts#readme",
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "git+https://github.com/openartifactsai/open-artifacts.git",
52
+ "directory": "packages/motion-export"
53
+ },
54
+ "bugs": {
55
+ "url": "https://github.com/openartifactsai/open-artifacts/issues"
56
+ },
57
+ "publishConfig": {
58
+ "access": "public"
59
+ }
60
+ }
package/src/build.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ export interface BuiltScript {
2
+ script: string;
3
+ /** Absolute paths of the source files that went into it, for a dev server to watch. */
4
+ inputs: string[];
5
+ }
6
+ /**
7
+ * The two scripts, named by their module beside this file with no extension: the build adds its own, so the same name
8
+ * finds `frame-entry.ts` in the workspace and `frame-entry.js` in the published package.
9
+ */
10
+ export declare const RASTER_FRAME_ENTRY = "./raster/frame-entry";
11
+ export declare const STANDALONE_AUDIO_ENTRY = "./standalone/audio-entry";
12
+ /** A script built afresh, with its inputs: for a dev server, which builds it again when one changes. */
13
+ export declare const buildExportScriptFresh: (entry: typeof RASTER_FRAME_ENTRY | typeof STANDALONE_AUDIO_ENTRY) => Promise<BuiltScript>;
14
+ /** The raster frame's script, which turns a snapshot's SVG into a bitmap: built once per process. */
15
+ export declare const buildRasterFrame: () => Promise<string>;
16
+ /** The standalone page's audio, which sets `window.filmAudio`: built once per process. */
17
+ export declare const buildStandaloneAudio: () => Promise<string>;
package/src/build.js ADDED
@@ -0,0 +1,52 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ import { extname, resolve } from 'node:path';
3
+ import { build } from 'esbuild';
4
+ const here = fileURLToPath(new URL('.', import.meta.url));
5
+ /** This file's own extension: `.ts` in the workspace, `.js` in the published package, where the entries are compiled too. */
6
+ const entryExtension = extname(fileURLToPath(import.meta.url));
7
+ /** Both scripts run as classic scripts: the raster frame from a srcdoc, the audio in a page saved to disk. */
8
+ async function bundle(entry) {
9
+ const result = await build({
10
+ entryPoints: [resolve(here, entry + entryExtension)],
11
+ bundle: true,
12
+ format: 'iife',
13
+ platform: 'browser',
14
+ target: 'es2022',
15
+ minify: true,
16
+ legalComments: 'none',
17
+ charset: 'utf8',
18
+ write: false,
19
+ logLevel: 'silent',
20
+ absWorkingDir: here,
21
+ metafile: true,
22
+ // Classic scripts have no import.meta; motion-core resolves its font files against it at load.
23
+ define: { 'import.meta.url': '"file:///"' },
24
+ });
25
+ const output = result.outputFiles[0];
26
+ if (!output)
27
+ throw new Error('esbuild gave no output for ' + entry);
28
+ const inputs = Object.keys(result.metafile.inputs).map((input) => resolve(here, input));
29
+ return { script: output.text, inputs };
30
+ }
31
+ /**
32
+ * The two scripts, named by their module beside this file with no extension: the build adds its own, so the same name
33
+ * finds `frame-entry.ts` in the workspace and `frame-entry.js` in the published package.
34
+ */
35
+ export const RASTER_FRAME_ENTRY = './raster/frame-entry';
36
+ export const STANDALONE_AUDIO_ENTRY = './standalone/audio-entry';
37
+ /** A script built afresh, with its inputs: for a dev server, which builds it again when one changes. */
38
+ export const buildExportScriptFresh = (entry) => bundle(entry);
39
+ function once(entry) {
40
+ let built = null;
41
+ return () => {
42
+ built ??= bundle(entry).then((result) => result.script, (error) => {
43
+ built = null;
44
+ throw error;
45
+ });
46
+ return built;
47
+ };
48
+ }
49
+ /** The raster frame's script, which turns a snapshot's SVG into a bitmap: built once per process. */
50
+ export const buildRasterFrame = once(RASTER_FRAME_ENTRY);
51
+ /** The standalone page's audio, which sets `window.filmAudio`: built once per process. */
52
+ export const buildStandaloneAudio = once(STANDALONE_AUDIO_ENTRY);
@@ -0,0 +1,13 @@
1
+ import type { ExportedFile } from './types.js';
2
+ /** One language's captions: its SubRip text, and its tag where the words say which language they are in. */
3
+ export interface CaptionsTrack {
4
+ lang?: string;
5
+ subrip: string;
6
+ }
7
+ /** The .srt names in the zip: the title alone for one track, else the title and each track's language. */
8
+ export declare function captionsTrackNames(title: string, tracks: readonly CaptionsTrack[]): string[];
9
+ /**
10
+ * The film's captions to save: a .srt for each language, in `<title> subtitles.zip` (a .srt on its own opens as a
11
+ * page of text in some browsers instead of being saved).
12
+ */
13
+ export declare function captionsFile(title: string, tracks: readonly CaptionsTrack[], date?: Date): Promise<ExportedFile>;
@@ -0,0 +1,15 @@
1
+ import { packZip } from '@openartifactsai/wasm-export';
2
+ import { exportFilename } from "./filename.js";
3
+ /** The .srt names in the zip: the title alone for one track, else the title and each track's language. */
4
+ export function captionsTrackNames(title, tracks) {
5
+ return tracks.map((track) => (tracks.length === 1 || track.lang === undefined ? exportFilename(title, 'srt') : exportFilename(`${title}.${track.lang}`, 'srt')));
6
+ }
7
+ /**
8
+ * The film's captions to save: a .srt for each language, in `<title> subtitles.zip` (a .srt on its own opens as a
9
+ * page of text in some browsers instead of being saved).
10
+ */
11
+ export async function captionsFile(title, tracks, date) {
12
+ const names = captionsTrackNames(title, tracks);
13
+ const bytes = await packZip(tracks.map((track, index) => ({ name: names[index], data: new TextEncoder().encode(track.subrip) })), date === undefined ? {} : { date });
14
+ return { blob: new Blob([bytes.slice()], { type: 'application/zip' }), filename: exportFilename(`${title} subtitles`, 'zip'), mime: 'application/zip' };
15
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Reading and converting a picked video on the page's behalf: each job gets a worker of its own, which is stopped once
3
+ * it answers, when the job is cancelled, or when it goes quiet for too long.
4
+ */
5
+ import type { VideoJob, VideoJobAnswer } from './jobs.js';
6
+ import { VideoPartError, type VideoFileFacts, type VideoPart } from './problem.js';
7
+ /** How long a worker may stay silent: reading answers once; converting reports progress as it goes. */
8
+ export declare const READ_QUIET_MS = 8000;
9
+ export declare const CONVERT_QUIET_MS = 90000;
10
+ /** What a job needs of a worker (tests give their own). */
11
+ export interface VideoWorkerPort {
12
+ onmessage: ((event: MessageEvent<unknown>) => void) | null;
13
+ onerror: ((event: ErrorEvent) => void) | null;
14
+ onmessageerror: ((event: MessageEvent<unknown>) => void) | null;
15
+ postMessage(message: VideoJob): void;
16
+ terminate(): void;
17
+ }
18
+ export type StartVideoWorker = () => VideoWorkerPort;
19
+ /** Whether this browser can run the video worker at all: workers and a video encoder. */
20
+ export declare function videoWorkerAvailable(): boolean;
21
+ interface JobOptions {
22
+ quietMs: number;
23
+ signal?: AbortSignal;
24
+ onProgress?: (progress: number) => void;
25
+ start?: StartVideoWorker;
26
+ }
27
+ /** Sends one job to a new worker and settles with its outcome; `unable` is the problem when no worker can do it. */
28
+ export declare function runVideoJob(job: VideoJob, unable: VideoPartError['problem'], options: JobOptions): Promise<Exclude<VideoJobAnswer, {
29
+ kind: 'progress' | 'failed';
30
+ }>>;
31
+ /** Reads a file's length and frame in a worker; throws a {@link VideoPartError} for one that is not a video this browser reads. */
32
+ export declare function readVideoFile(file: Blob, start?: StartVideoWorker): Promise<VideoFileFacts>;
33
+ export interface VideoPartOptions {
34
+ /** The part, in the file's seconds. */
35
+ start: number;
36
+ end: number;
37
+ facts: VideoFileFacts;
38
+ /** 0–1 through the conversion; a smaller try starts again from 0. */
39
+ onProgress?: (progress: number) => void;
40
+ signal?: AbortSignal;
41
+ /** Starts the worker (tests give their own). */
42
+ startWorker?: StartVideoWorker;
43
+ }
44
+ /**
45
+ * Converts the part `start`–`end` of `file` in a worker, smaller at each try while the result is over the upload
46
+ * limit. Throws a {@link VideoPartError}, or the abort reason once `signal` aborts.
47
+ */
48
+ export declare function convertVideoPart(file: Blob, options: VideoPartOptions): Promise<VideoPart>;
49
+ export {};
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Reading and converting a picked video on the page's behalf: each job gets a worker of its own, which is stopped once
3
+ * it answers, when the job is cancelled, or when it goes quiet for too long.
4
+ */
5
+ import { looksLikeVideoFile } from '@openartifactsai/motion-core';
6
+ import { VIDEO_PART_PROBLEMS, VideoPartError } from "./problem.js";
7
+ /** How long a worker may stay silent: reading answers once; converting reports progress as it goes. */
8
+ export const READ_QUIET_MS = 8_000;
9
+ export const CONVERT_QUIET_MS = 90_000;
10
+ const HEAD_BYTES = 16;
11
+ const startBundledWorker = () => new Worker(new URL('./worker.js', import.meta.url), { type: 'module', name: 'open-artifacts-video' });
12
+ /** Whether this browser can run the video worker at all: workers and a video encoder. */
13
+ export function videoWorkerAvailable() {
14
+ return typeof Worker === 'function' && typeof VideoEncoder !== 'undefined';
15
+ }
16
+ const isAnswer = (data) => typeof data === 'object' && data !== null && 'kind' in data && typeof data.kind === 'string';
17
+ /** Sends one job to a new worker and settles with its outcome; `unable` is the problem when no worker can do it. */
18
+ export function runVideoJob(job, unable, options) {
19
+ return new Promise((resolve, reject) => {
20
+ options.signal?.throwIfAborted();
21
+ let worker;
22
+ try {
23
+ worker = (options.start ?? startBundledWorker)();
24
+ }
25
+ catch (error) {
26
+ reject(new VideoPartError(unable, error));
27
+ return;
28
+ }
29
+ let quiet;
30
+ const finish = () => {
31
+ clearTimeout(quiet);
32
+ options.signal?.removeEventListener('abort', cancel);
33
+ worker.terminate();
34
+ };
35
+ const fail = (error) => {
36
+ finish();
37
+ reject(error);
38
+ };
39
+ const cancel = () => fail(options.signal?.reason);
40
+ const awake = () => {
41
+ clearTimeout(quiet);
42
+ quiet = setTimeout(() => fail(new VideoPartError('failed', new Error('the video worker stopped answering'))), options.quietMs);
43
+ };
44
+ worker.onerror = (event) => {
45
+ event.preventDefault();
46
+ fail(new VideoPartError(unable, new Error(event.message)));
47
+ };
48
+ worker.onmessageerror = () => fail(new VideoPartError('failed'));
49
+ worker.onmessage = (event) => {
50
+ const answer = event.data;
51
+ if (!isAnswer(answer))
52
+ return fail(new VideoPartError('failed'));
53
+ if (answer.kind === 'progress') {
54
+ awake();
55
+ options.onProgress?.(answer.value);
56
+ return;
57
+ }
58
+ if (answer.kind === 'failed')
59
+ return fail(new VideoPartError(VIDEO_PART_PROBLEMS.includes(answer.problem) ? answer.problem : 'failed'));
60
+ finish();
61
+ resolve(answer);
62
+ };
63
+ options.signal?.addEventListener('abort', cancel, { once: true });
64
+ awake();
65
+ worker.postMessage(job);
66
+ });
67
+ }
68
+ /** Reads a file's length and frame in a worker; throws a {@link VideoPartError} for one that is not a video this browser reads. */
69
+ export async function readVideoFile(file, start) {
70
+ const head = new Uint8Array(await file.slice(0, HEAD_BYTES).arrayBuffer());
71
+ if (!looksLikeVideoFile(head))
72
+ throw new VideoPartError('not-video');
73
+ if (start === undefined && !videoWorkerAvailable())
74
+ throw new VideoPartError('unreadable');
75
+ const answer = await runVideoJob({ job: 'read', file }, 'unreadable', { quietMs: READ_QUIET_MS, ...(start ? { start } : {}) });
76
+ if (answer.kind !== 'read')
77
+ throw new VideoPartError('failed');
78
+ return answer.facts;
79
+ }
80
+ /**
81
+ * Converts the part `start`–`end` of `file` in a worker, smaller at each try while the result is over the upload
82
+ * limit. Throws a {@link VideoPartError}, or the abort reason once `signal` aborts.
83
+ */
84
+ export async function convertVideoPart(file, options) {
85
+ if (options.startWorker === undefined && !videoWorkerAvailable())
86
+ throw new VideoPartError('no-encoder');
87
+ const answer = await runVideoJob({ job: 'convert', file, start: options.start, end: options.end, facts: options.facts }, 'no-encoder', {
88
+ quietMs: CONVERT_QUIET_MS,
89
+ ...(options.signal ? { signal: options.signal } : {}),
90
+ ...(options.onProgress ? { onProgress: options.onProgress } : {}),
91
+ ...(options.startWorker ? { start: options.startWorker } : {}),
92
+ });
93
+ if (answer.kind !== 'converted')
94
+ throw new VideoPartError('failed');
95
+ return { bytes: answer.bytes, width: answer.width, height: answer.height, sound: answer.sound };
96
+ }
@@ -0,0 +1,28 @@
1
+ /** The messages between the page and the video worker: one job per worker, answered by progress and then one outcome. */
2
+ import type { VideoFileFacts, VideoPartProblem } from './problem.js';
3
+ export type VideoJob = {
4
+ job: 'read';
5
+ file: Blob;
6
+ } | {
7
+ job: 'convert';
8
+ file: Blob;
9
+ start: number;
10
+ end: number;
11
+ facts: VideoFileFacts;
12
+ };
13
+ export type VideoJobAnswer = {
14
+ kind: 'progress';
15
+ value: number;
16
+ } | {
17
+ kind: 'read';
18
+ facts: VideoFileFacts;
19
+ } | {
20
+ kind: 'converted';
21
+ bytes: Uint8Array<ArrayBuffer>;
22
+ width: number;
23
+ height: number;
24
+ sound: boolean;
25
+ } | {
26
+ kind: 'failed';
27
+ problem: VideoPartProblem;
28
+ };
@@ -0,0 +1,2 @@
1
+ /** The messages between the page and the video worker: one job per worker, answered by progress and then one outcome. */
2
+ export {};
@@ -0,0 +1,25 @@
1
+ /**
2
+ * A part of a video file the person picked, read and converted so it can be stored with a film: an H.264 MP4 with AAC
3
+ * sound, small enough for the upload limit (`videoEncodePlan` sizes it; a file still too large is made again smaller).
4
+ * The page runs these in a worker (`./worker.ts`), so the file's demuxers stay out of the page.
5
+ */
6
+ import { type VideoEncodePlan } from '@openartifactsai/motion-core';
7
+ import { type VideoFileFacts, type VideoPart } from './problem.js';
8
+ /** Reads a file's length and frame; throws a {@link VideoPartError} for one that is not a video this browser reads. */
9
+ export declare function readVideoFile(file: Blob): Promise<VideoFileFacts>;
10
+ /** Whether this browser can write the picture a part is converted to (without sound it is stored silent). */
11
+ export declare function canConvertVideo(plan: VideoEncodePlan): Promise<boolean>;
12
+ export interface VideoPartOptions {
13
+ /** The part, in the file's seconds. */
14
+ start: number;
15
+ end: number;
16
+ facts: VideoFileFacts;
17
+ /** 0–1 through the conversion; a smaller try starts again from 0. */
18
+ onProgress?: (progress: number) => void;
19
+ signal?: AbortSignal;
20
+ }
21
+ /**
22
+ * Converts the part `start`–`end` of `file`: smaller at each try while the result is over the upload limit. Throws a
23
+ * {@link VideoPartError}, or the abort reason once `signal` aborts.
24
+ */
25
+ export declare function convertVideoPart(file: Blob, options: VideoPartOptions): Promise<VideoPart>;