@glissade/export-web 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 +202 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.js +247 -0
- package/package.json +32 -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/dist/index.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { AudioCodec, VideoCodec } from "mediabunny";
|
|
2
|
+
import { Timeline } from "@glissade/core";
|
|
3
|
+
import { Scene, VideoFrameSource } from "@glissade/scene";
|
|
4
|
+
|
|
5
|
+
//#region src/videoSource.d.ts
|
|
6
|
+
|
|
7
|
+
declare class MediabunnyVideoFrameSource implements VideoFrameSource {
|
|
8
|
+
readonly fps: number;
|
|
9
|
+
readonly duration: number;
|
|
10
|
+
private readonly sink;
|
|
11
|
+
private readonly cache;
|
|
12
|
+
private readonly label;
|
|
13
|
+
private constructor();
|
|
14
|
+
static open(src: string | Blob, label?: string): Promise<MediabunnyVideoFrameSource>;
|
|
15
|
+
private frameIndex;
|
|
16
|
+
warm(fromT: number, toT: number): Promise<void>;
|
|
17
|
+
getFrameSync(mediaT: number): HTMLCanvasElement | OffscreenCanvas;
|
|
18
|
+
close(): void;
|
|
19
|
+
}
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/index.d.ts
|
|
22
|
+
interface WebExportOptions {
|
|
23
|
+
fps?: number;
|
|
24
|
+
/** 'auto' tries mp4 (avc/hevc/av1) then webm (vp9/vp8/av1). */
|
|
25
|
+
format?: 'mp4' | 'webm' | 'auto';
|
|
26
|
+
videoBitrate?: number;
|
|
27
|
+
audioBitrate?: number;
|
|
28
|
+
onProgress?: (frame: number, total: number) => void;
|
|
29
|
+
}
|
|
30
|
+
interface WebExportResult {
|
|
31
|
+
blob: Blob;
|
|
32
|
+
format: 'mp4' | 'webm';
|
|
33
|
+
videoCodec: VideoCodec;
|
|
34
|
+
audioCodec: AudioCodec | null;
|
|
35
|
+
frames: number;
|
|
36
|
+
}
|
|
37
|
+
declare class ExportUnsupportedError extends Error {
|
|
38
|
+
constructor(detail: string);
|
|
39
|
+
}
|
|
40
|
+
/** Export a scene + timeline to a video Blob, entirely in the browser. */
|
|
41
|
+
declare function exportVideo(scene: Scene, doc: Timeline, opts?: WebExportOptions): Promise<WebExportResult>;
|
|
42
|
+
/** Unconditional fallback (§5.2): per-frame PNG blobs via a callback — works wherever canvas does. */
|
|
43
|
+
declare function exportPngFrames(scene: Scene, doc: Timeline, onFrame: (frame: number, png: Blob) => void | Promise<void>, opts?: {
|
|
44
|
+
fps?: number;
|
|
45
|
+
}): Promise<{
|
|
46
|
+
frames: number;
|
|
47
|
+
}>;
|
|
48
|
+
//#endregion
|
|
49
|
+
export { ExportUnsupportedError, MediabunnyVideoFrameSource, WebExportOptions, WebExportResult, exportPngFrames, exportVideo };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { ALL_FORMATS, AudioBufferSource, BlobSource, BufferTarget, CanvasSink, CanvasSource, Input, Mp4OutputFormat, Output, UrlSource, WebMOutputFormat, getFirstEncodableAudioCodec, getFirstEncodableVideoCodec } from "mediabunny";
|
|
2
|
+
import { compileTimeline, sampleTrack } from "@glissade/core";
|
|
3
|
+
import { ColdAssetError, evaluate } from "@glissade/scene";
|
|
4
|
+
import { Canvas2DBackend } from "@glissade/backend-canvas2d";
|
|
5
|
+
//#region src/videoSource.ts
|
|
6
|
+
/**
|
|
7
|
+
* Browser video decoding (DESIGN.md §5.4): Mediabunny demux + WebCodecs
|
|
8
|
+
* decode behind the VideoFrameSource seam. warm() decodes a window of frames
|
|
9
|
+
* via CanvasSink (which drives VideoDecoder and handles keyframe seeking —
|
|
10
|
+
* backward/random scrub is O(GOP), a readiness latency, never state).
|
|
11
|
+
*/
|
|
12
|
+
const DEFAULT_LOOKAHEAD_FRAMES = 10;
|
|
13
|
+
const MAX_CACHED_FRAMES = 64;
|
|
14
|
+
var MediabunnyVideoFrameSource = class MediabunnyVideoFrameSource {
|
|
15
|
+
fps;
|
|
16
|
+
duration;
|
|
17
|
+
sink;
|
|
18
|
+
cache = /* @__PURE__ */ new Map();
|
|
19
|
+
label;
|
|
20
|
+
constructor(sink, fps, duration, label) {
|
|
21
|
+
this.sink = sink;
|
|
22
|
+
this.fps = fps;
|
|
23
|
+
this.duration = duration;
|
|
24
|
+
this.label = label;
|
|
25
|
+
}
|
|
26
|
+
static async open(src, label = typeof src === "string" ? src : "blob") {
|
|
27
|
+
const track = await new Input({
|
|
28
|
+
formats: ALL_FORMATS,
|
|
29
|
+
source: typeof src === "string" ? new UrlSource(src) : new BlobSource(src)
|
|
30
|
+
}).getPrimaryVideoTrack();
|
|
31
|
+
if (!track) throw new Error(`no video track in ${label}`);
|
|
32
|
+
if (!await track.canDecode()) throw new Error(`browser cannot decode the video codec of ${label}`);
|
|
33
|
+
const stats = await track.computePacketStats(120);
|
|
34
|
+
const duration = await track.computeDuration();
|
|
35
|
+
return new MediabunnyVideoFrameSource(new CanvasSink(track, { poolSize: 0 }), stats.averagePacketRate, duration, label);
|
|
36
|
+
}
|
|
37
|
+
frameIndex(mediaT) {
|
|
38
|
+
return Math.max(0, Math.floor(mediaT * this.fps + 1e-9));
|
|
39
|
+
}
|
|
40
|
+
async warm(fromT, toT) {
|
|
41
|
+
const from = Math.max(0, fromT);
|
|
42
|
+
const to = Math.min(toT + DEFAULT_LOOKAHEAD_FRAMES / this.fps, this.duration);
|
|
43
|
+
const fromIdx = this.frameIndex(from);
|
|
44
|
+
const toIdx = this.frameIndex(to);
|
|
45
|
+
let missing = false;
|
|
46
|
+
for (let i = fromIdx; i <= toIdx; i++) if (!this.cache.has(i)) {
|
|
47
|
+
missing = true;
|
|
48
|
+
break;
|
|
49
|
+
}
|
|
50
|
+
if (!missing) return;
|
|
51
|
+
for await (const wrapped of this.sink.canvases(from, to)) {
|
|
52
|
+
if (!wrapped) continue;
|
|
53
|
+
this.cache.set(this.frameIndex(wrapped.timestamp), wrapped.canvas);
|
|
54
|
+
}
|
|
55
|
+
if (this.cache.size > MAX_CACHED_FRAMES) {
|
|
56
|
+
const center = (fromIdx + toIdx) / 2;
|
|
57
|
+
const byDistance = [...this.cache.keys()].sort((a, b) => Math.abs(b - center) - Math.abs(a - center));
|
|
58
|
+
for (const idx of byDistance.slice(0, this.cache.size - MAX_CACHED_FRAMES)) this.cache.delete(idx);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
getFrameSync(mediaT) {
|
|
62
|
+
let idx = this.frameIndex(Math.min(mediaT, this.duration));
|
|
63
|
+
const lastIdx = this.frameIndex(this.duration);
|
|
64
|
+
while (idx > 0 && !this.cache.has(idx) && idx >= lastIdx - 2) idx--;
|
|
65
|
+
const hit = this.cache.get(idx);
|
|
66
|
+
if (!hit) throw new ColdAssetError(this.label, `frame ${idx} not decoded`, mediaT);
|
|
67
|
+
return hit;
|
|
68
|
+
}
|
|
69
|
+
close() {
|
|
70
|
+
this.cache.clear();
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
//#endregion
|
|
74
|
+
//#region src/index.ts
|
|
75
|
+
/**
|
|
76
|
+
* @glissade/export-web — in-browser export (DESIGN.md §5.1b/§5.2/§5.3):
|
|
77
|
+
* WebCodecs encoding + Mediabunny muxing, frame-accurate and faster than
|
|
78
|
+
* realtime; audio mixed sample-accurately via OfflineAudioContext. Codec
|
|
79
|
+
* support is feature-detected (isConfigSupported under the hood); the PNG
|
|
80
|
+
* frame callback path is the unconditional fallback.
|
|
81
|
+
*/
|
|
82
|
+
var ExportUnsupportedError = class extends Error {
|
|
83
|
+
constructor(detail) {
|
|
84
|
+
super(`${detail} — no encodable codec found in this browser. Use the PNG fallback (exportPngFrames) or render via the gs CLI (§5.2).`);
|
|
85
|
+
this.name = "ExportUnsupportedError";
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
const MP4_VIDEO = [
|
|
89
|
+
"avc",
|
|
90
|
+
"hevc",
|
|
91
|
+
"av1"
|
|
92
|
+
];
|
|
93
|
+
const WEBM_VIDEO = [
|
|
94
|
+
"vp9",
|
|
95
|
+
"vp8",
|
|
96
|
+
"av1"
|
|
97
|
+
];
|
|
98
|
+
const MP4_AUDIO = ["aac", "opus"];
|
|
99
|
+
const WEBM_AUDIO = ["opus"];
|
|
100
|
+
async function pickCodecs(format, width, height, bitrate, needAudio) {
|
|
101
|
+
const tryFormat = async (f) => {
|
|
102
|
+
const video = await getFirstEncodableVideoCodec(f === "mp4" ? MP4_VIDEO : WEBM_VIDEO, {
|
|
103
|
+
width,
|
|
104
|
+
height,
|
|
105
|
+
bitrate
|
|
106
|
+
});
|
|
107
|
+
if (!video) return null;
|
|
108
|
+
const audio = needAudio ? await getFirstEncodableAudioCodec(f === "mp4" ? MP4_AUDIO : WEBM_AUDIO) : null;
|
|
109
|
+
if (needAudio && !audio) return null;
|
|
110
|
+
return {
|
|
111
|
+
format: f,
|
|
112
|
+
video,
|
|
113
|
+
audio
|
|
114
|
+
};
|
|
115
|
+
};
|
|
116
|
+
for (const f of format === "auto" ? ["mp4", "webm"] : [format]) {
|
|
117
|
+
const picked = await tryFormat(f);
|
|
118
|
+
if (picked) return picked;
|
|
119
|
+
}
|
|
120
|
+
throw new ExportUnsupportedError(`format '${format}'${needAudio ? " with audio" : ""}`);
|
|
121
|
+
}
|
|
122
|
+
/** Mix timeline audio clips sample-accurately (§5.3 browser path). */
|
|
123
|
+
async function mixAudio(clips, duration, sampleRate = 48e3) {
|
|
124
|
+
const ctx = new OfflineAudioContext(2, Math.ceil(duration * sampleRate), sampleRate);
|
|
125
|
+
for (const clip of clips) {
|
|
126
|
+
if (clip.at >= duration) continue;
|
|
127
|
+
const resp = await fetch(clip.asset.url);
|
|
128
|
+
if (!resp.ok) throw new Error(`audio asset fetch failed (${resp.status}): ${clip.asset.url}`);
|
|
129
|
+
const decoded = await ctx.decodeAudioData(await resp.arrayBuffer());
|
|
130
|
+
const node = ctx.createBufferSource();
|
|
131
|
+
node.buffer = decoded;
|
|
132
|
+
if (clip.playbackRate !== void 0) node.playbackRate.value = clip.playbackRate;
|
|
133
|
+
let tail = node;
|
|
134
|
+
if (clip.gain) {
|
|
135
|
+
const gainNode = ctx.createGain();
|
|
136
|
+
const keys = clip.gain.keys;
|
|
137
|
+
gainNode.gain.setValueAtTime(Number(keys[0].value), Math.max(0, clip.at));
|
|
138
|
+
for (const k of keys) gainNode.gain.linearRampToValueAtTime(Number(sampleTrack(clip.gain, k.t)), clip.at + k.t);
|
|
139
|
+
tail.connect(gainNode);
|
|
140
|
+
tail = gainNode;
|
|
141
|
+
}
|
|
142
|
+
tail.connect(ctx.destination);
|
|
143
|
+
const offset = clip.trim?.start ?? 0;
|
|
144
|
+
const sourceDur = clip.trim ? clip.trim.end - clip.trim.start : void 0;
|
|
145
|
+
if (sourceDur !== void 0) node.start(Math.max(0, clip.at), offset, sourceDur);
|
|
146
|
+
else node.start(Math.max(0, clip.at), offset);
|
|
147
|
+
}
|
|
148
|
+
return ctx.startRendering();
|
|
149
|
+
}
|
|
150
|
+
/** Export a scene + timeline to a video Blob, entirely in the browser. */
|
|
151
|
+
async function exportVideo(scene, doc, opts = {}) {
|
|
152
|
+
const compiled = compileTimeline(doc);
|
|
153
|
+
const fps = opts.fps ?? doc.fps ?? 60;
|
|
154
|
+
const duration = compiled.duration;
|
|
155
|
+
const total = Math.max(1, Math.ceil(duration * fps));
|
|
156
|
+
const { w, h } = scene.size;
|
|
157
|
+
const videoBitrate = opts.videoBitrate ?? 8e6;
|
|
158
|
+
const picked = await pickCodecs(opts.format ?? "auto", w, h, videoBitrate, compiled.audio.length > 0);
|
|
159
|
+
const canvas = new OffscreenCanvas(w, h);
|
|
160
|
+
const backend = new Canvas2DBackend(canvas);
|
|
161
|
+
scene.setTextMeasurer(backend);
|
|
162
|
+
const videoSources = /* @__PURE__ */ new Map();
|
|
163
|
+
for (const [assetId, ref] of Object.entries(doc.assets ?? {})) if (ref.kind === "font") {
|
|
164
|
+
const face = new FontFace(assetId, `url(${ref.url})`);
|
|
165
|
+
const g = globalThis;
|
|
166
|
+
(g.document?.fonts ?? g.fonts)?.add(face);
|
|
167
|
+
await face.load();
|
|
168
|
+
} else if (ref.kind === "image") {
|
|
169
|
+
const resp = await fetch(ref.url);
|
|
170
|
+
if (!resp.ok) throw new Error(`image asset fetch failed (${resp.status}): ${ref.url}`);
|
|
171
|
+
backend.setImageAsset(assetId, await createImageBitmap(await resp.blob()));
|
|
172
|
+
} else if (ref.kind === "video") {
|
|
173
|
+
const source = await MediabunnyVideoFrameSource.open(ref.url, assetId);
|
|
174
|
+
backend.setVideoAsset(assetId, source);
|
|
175
|
+
videoSources.set(assetId, source);
|
|
176
|
+
}
|
|
177
|
+
/** Render one frame, demand-warming any cold video source and retrying (§2.5). */
|
|
178
|
+
const renderFrame = async (t) => {
|
|
179
|
+
for (let attempt = 0;; attempt++) try {
|
|
180
|
+
backend.render(evaluate(scene, doc, t));
|
|
181
|
+
return;
|
|
182
|
+
} catch (e) {
|
|
183
|
+
if (e instanceof ColdAssetError && e.mediaT !== void 0 && attempt < 3) {
|
|
184
|
+
const source = videoSources.get(e.assetId);
|
|
185
|
+
if (source) {
|
|
186
|
+
await source.warm(e.mediaT, e.mediaT);
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
throw e;
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
const output = new Output({
|
|
194
|
+
format: picked.format === "mp4" ? new Mp4OutputFormat() : new WebMOutputFormat(),
|
|
195
|
+
target: new BufferTarget()
|
|
196
|
+
});
|
|
197
|
+
const videoSource = new CanvasSource(canvas, {
|
|
198
|
+
codec: picked.video,
|
|
199
|
+
bitrate: videoBitrate
|
|
200
|
+
});
|
|
201
|
+
output.addVideoTrack(videoSource, { frameRate: fps });
|
|
202
|
+
let audioSource = null;
|
|
203
|
+
if (picked.audio) {
|
|
204
|
+
audioSource = new AudioBufferSource({
|
|
205
|
+
codec: picked.audio,
|
|
206
|
+
bitrate: opts.audioBitrate ?? 192e3
|
|
207
|
+
});
|
|
208
|
+
output.addAudioTrack(audioSource);
|
|
209
|
+
}
|
|
210
|
+
await output.start();
|
|
211
|
+
if (audioSource) {
|
|
212
|
+
await audioSource.add(await mixAudio(compiled.audio, duration));
|
|
213
|
+
audioSource.close();
|
|
214
|
+
}
|
|
215
|
+
for (let f = 0; f < total; f++) {
|
|
216
|
+
await renderFrame(f / fps);
|
|
217
|
+
await videoSource.add(f / fps, 1 / fps);
|
|
218
|
+
opts.onProgress?.(f + 1, total);
|
|
219
|
+
}
|
|
220
|
+
videoSource.close();
|
|
221
|
+
await output.finalize();
|
|
222
|
+
for (const source of videoSources.values()) source.close();
|
|
223
|
+
const buffer = output.target.buffer;
|
|
224
|
+
if (!buffer) throw new Error("muxer produced no output");
|
|
225
|
+
return {
|
|
226
|
+
blob: new Blob([buffer], { type: picked.format === "mp4" ? "video/mp4" : "video/webm" }),
|
|
227
|
+
format: picked.format,
|
|
228
|
+
videoCodec: picked.video,
|
|
229
|
+
audioCodec: picked.audio,
|
|
230
|
+
frames: total
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
/** Unconditional fallback (§5.2): per-frame PNG blobs via a callback — works wherever canvas does. */
|
|
234
|
+
async function exportPngFrames(scene, doc, onFrame, opts = {}) {
|
|
235
|
+
const compiled = compileTimeline(doc);
|
|
236
|
+
const fps = opts.fps ?? doc.fps ?? 60;
|
|
237
|
+
const total = Math.max(1, Math.ceil(compiled.duration * fps));
|
|
238
|
+
const canvas = new OffscreenCanvas(scene.size.w, scene.size.h);
|
|
239
|
+
const backend = new Canvas2DBackend(canvas);
|
|
240
|
+
for (let f = 0; f < total; f++) {
|
|
241
|
+
backend.render(evaluate(scene, doc, f / fps));
|
|
242
|
+
await onFrame(f, await canvas.convertToBlob({ type: "image/png" }));
|
|
243
|
+
}
|
|
244
|
+
return { frames: total };
|
|
245
|
+
}
|
|
246
|
+
//#endregion
|
|
247
|
+
export { ExportUnsupportedError, MediabunnyVideoFrameSource, exportPngFrames, exportVideo };
|
package/package.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@glissade/export-web",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "glissade in-browser export: WebCodecs VideoEncoder + Mediabunny muxing, OfflineAudioContext audio mix. Frame-accurate, faster than realtime, no server.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist"
|
|
16
|
+
],
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"mediabunny": "^1.0.0",
|
|
19
|
+
"@glissade/backend-canvas2d": "0.1.0",
|
|
20
|
+
"@glissade/core": "0.1.0",
|
|
21
|
+
"@glissade/scene": "0.1.0"
|
|
22
|
+
},
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "git+https://github.com/tyevco/glissade.git",
|
|
26
|
+
"directory": "packages/export-web"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "tsdown",
|
|
30
|
+
"typecheck": "tsc --noEmit"
|
|
31
|
+
}
|
|
32
|
+
}
|