@bendyline/squisq-video-react 1.0.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/dist/index.d.ts +176 -0
- package/dist/index.js +816 -0
- package/dist/index.js.map +1 -0
- package/package.json +61 -0
- package/src/VideoExportButton.tsx +68 -0
- package/src/VideoExportModal.tsx +366 -0
- package/src/hooks/useFrameCapture.ts +263 -0
- package/src/hooks/useVideoExport.ts +343 -0
- package/src/index.ts +35 -0
- package/src/mainThreadEncoder.ts +128 -0
- package/src/mp4Mux.ts +49 -0
- package/src/workers/encode.worker.ts +384 -0
- package/src/workers/workerTypes.ts +81 -0
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Main-thread WebCodecs encoder.
|
|
3
|
+
*
|
|
4
|
+
* Encodes video frames to MP4 using the WebCodecs API and mp4-muxer,
|
|
5
|
+
* running directly on the main thread. This is simpler and avoids
|
|
6
|
+
* worker module-resolution issues with bundlers. Since frame capture
|
|
7
|
+
* via html2canvas (~100-200ms per frame) is the bottleneck — not
|
|
8
|
+
* encoding (~1ms per frame with hardware-accelerated WebCodecs) —
|
|
9
|
+
* worker offloading provides minimal benefit.
|
|
10
|
+
*
|
|
11
|
+
* Requirements: Chrome 94+ / Edge 94+ (WebCodecs support).
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { createMp4Muxer, type Mp4MuxerHandle } from './mp4Mux.js';
|
|
15
|
+
|
|
16
|
+
export interface EncoderConfig {
|
|
17
|
+
width: number;
|
|
18
|
+
height: number;
|
|
19
|
+
fps: number;
|
|
20
|
+
quality: 'draft' | 'normal' | 'high';
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface MainThreadEncoder {
|
|
24
|
+
/** Encode a single frame. The bitmap is closed after encoding. */
|
|
25
|
+
encodeFrame(bitmap: ImageBitmap, frameIndex: number): void;
|
|
26
|
+
/** Flush pending frames and finalize the MP4. Returns the MP4 ArrayBuffer. */
|
|
27
|
+
finalize(): Promise<ArrayBuffer>;
|
|
28
|
+
/** Close the encoder without producing output (e.g., on cancel). */
|
|
29
|
+
close(): void;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Check whether the browser supports WebCodecs video encoding.
|
|
34
|
+
*/
|
|
35
|
+
export function supportsWebCodecs(): boolean {
|
|
36
|
+
return typeof VideoEncoder !== 'undefined' && typeof VideoFrame !== 'undefined';
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function bitrateForQuality(quality: string, width: number, height: number): number {
|
|
40
|
+
const pixels = width * height;
|
|
41
|
+
const baseBitrate = pixels * 4; // ~4 bits per pixel baseline
|
|
42
|
+
switch (quality) {
|
|
43
|
+
case 'draft':
|
|
44
|
+
return Math.round(baseBitrate * 0.5);
|
|
45
|
+
case 'high':
|
|
46
|
+
return Math.round(baseBitrate * 2);
|
|
47
|
+
default: // normal
|
|
48
|
+
return baseBitrate;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Create a main-thread WebCodecs encoder.
|
|
54
|
+
*
|
|
55
|
+
* Throws if WebCodecs is not available.
|
|
56
|
+
*/
|
|
57
|
+
export function createEncoder(config: EncoderConfig): MainThreadEncoder {
|
|
58
|
+
if (!supportsWebCodecs()) {
|
|
59
|
+
throw new Error(
|
|
60
|
+
'WebCodecs is not available in this browser. ' +
|
|
61
|
+
'Video export requires Chrome 94+, Edge 94+, or another Chromium-based browser.',
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (!config.fps || config.fps <= 0 || !config.width || !config.height) {
|
|
66
|
+
throw new Error(
|
|
67
|
+
`Invalid encoder config: fps=${config.fps}, width=${config.width}, height=${config.height}`,
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const muxer: Mp4MuxerHandle = createMp4Muxer({
|
|
72
|
+
width: config.width,
|
|
73
|
+
height: config.height,
|
|
74
|
+
fps: config.fps,
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
let closed = false;
|
|
78
|
+
const frameDuration = 1_000_000 / config.fps; // microseconds per frame
|
|
79
|
+
|
|
80
|
+
const encoder = new VideoEncoder({
|
|
81
|
+
output(chunk, meta) {
|
|
82
|
+
if (closed) return;
|
|
83
|
+
muxer.addVideoChunk(chunk, meta ?? undefined);
|
|
84
|
+
},
|
|
85
|
+
error(err) {
|
|
86
|
+
console.error('WebCodecs encoder error:', err.message);
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
encoder.configure({
|
|
91
|
+
codec: 'avc1.640028', // H.264 High profile, level 4.0 (supports up to 1080p)
|
|
92
|
+
width: config.width,
|
|
93
|
+
height: config.height,
|
|
94
|
+
bitrate: bitrateForQuality(config.quality, config.width, config.height),
|
|
95
|
+
framerate: config.fps,
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
return {
|
|
99
|
+
encodeFrame(bitmap: ImageBitmap, frameIndex: number) {
|
|
100
|
+
if (closed) {
|
|
101
|
+
bitmap.close();
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const timestamp = Math.round(frameIndex * frameDuration);
|
|
105
|
+
const frame = new VideoFrame(bitmap, { timestamp });
|
|
106
|
+
const keyFrame = frameIndex % 30 === 0;
|
|
107
|
+
encoder.encode(frame, { keyFrame });
|
|
108
|
+
frame.close();
|
|
109
|
+
bitmap.close();
|
|
110
|
+
},
|
|
111
|
+
|
|
112
|
+
async finalize(): Promise<ArrayBuffer> {
|
|
113
|
+
if (closed) throw new Error('Encoder already closed');
|
|
114
|
+
await encoder.flush();
|
|
115
|
+
encoder.close();
|
|
116
|
+
closed = true;
|
|
117
|
+
return muxer.finalize();
|
|
118
|
+
},
|
|
119
|
+
|
|
120
|
+
close() {
|
|
121
|
+
if (closed) return;
|
|
122
|
+
closed = true;
|
|
123
|
+
if (encoder.state !== 'closed') {
|
|
124
|
+
encoder.close();
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
}
|
package/src/mp4Mux.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mp4Mux — Thin wrapper around mp4-muxer for WebCodecs encoding.
|
|
3
|
+
*
|
|
4
|
+
* Creates a Muxer instance configured for H.264 video, accumulates
|
|
5
|
+
* encoded chunks, and produces a final MP4 ArrayBuffer.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { Muxer, ArrayBufferTarget } from 'mp4-muxer';
|
|
9
|
+
|
|
10
|
+
export interface Mp4MuxerOptions {
|
|
11
|
+
width: number;
|
|
12
|
+
height: number;
|
|
13
|
+
fps: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface Mp4MuxerHandle {
|
|
17
|
+
/** Add an encoded video chunk to the muxer. */
|
|
18
|
+
addVideoChunk(chunk: EncodedVideoChunk, meta?: EncodedVideoChunkMetadata): void;
|
|
19
|
+
/** Finalize and return the MP4 as an ArrayBuffer. */
|
|
20
|
+
finalize(): ArrayBuffer;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Create an MP4 muxer configured for H.264 video.
|
|
25
|
+
*/
|
|
26
|
+
export function createMp4Muxer(options: Mp4MuxerOptions): Mp4MuxerHandle {
|
|
27
|
+
const target = new ArrayBufferTarget();
|
|
28
|
+
|
|
29
|
+
const muxer = new Muxer({
|
|
30
|
+
target,
|
|
31
|
+
video: {
|
|
32
|
+
codec: 'avc',
|
|
33
|
+
width: options.width,
|
|
34
|
+
height: options.height,
|
|
35
|
+
},
|
|
36
|
+
fastStart: 'in-memory',
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
return {
|
|
40
|
+
addVideoChunk(chunk: EncodedVideoChunk, meta?: EncodedVideoChunkMetadata) {
|
|
41
|
+
muxer.addVideoChunk(chunk, meta);
|
|
42
|
+
},
|
|
43
|
+
|
|
44
|
+
finalize(): ArrayBuffer {
|
|
45
|
+
muxer.finalize();
|
|
46
|
+
return target.buffer;
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Video Encoding Web Worker
|
|
3
|
+
*
|
|
4
|
+
* Encodes video frames to MP4 using one of two backends:
|
|
5
|
+
* - **WebCodecs** (preferred): Streaming H.264 encoding via VideoEncoder + mp4-muxer.
|
|
6
|
+
* Each frame is encoded as it arrives — minimal memory footprint.
|
|
7
|
+
* - **ffmpeg.wasm** (fallback): Batch encoding in ~10-second segments.
|
|
8
|
+
* Used when WebCodecs is unavailable (older browsers).
|
|
9
|
+
*
|
|
10
|
+
* Frames arrive as ImageBitmap (zero-copy transfer from main thread).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type {
|
|
14
|
+
MainToWorkerMessage,
|
|
15
|
+
WorkerToMainMessage,
|
|
16
|
+
InitMessage,
|
|
17
|
+
FrameMessage,
|
|
18
|
+
} from './workerTypes.js';
|
|
19
|
+
import { createMp4Muxer, type Mp4MuxerHandle } from '../mp4Mux.js';
|
|
20
|
+
|
|
21
|
+
// ── State ──────────────────────────────────────────────────────────
|
|
22
|
+
|
|
23
|
+
let backend: 'webcodecs' | 'ffmpeg-wasm' | null = null;
|
|
24
|
+
let cancelled = false;
|
|
25
|
+
|
|
26
|
+
// WebCodecs state
|
|
27
|
+
let videoEncoder: VideoEncoder | null = null;
|
|
28
|
+
let muxer: Mp4MuxerHandle | null = null;
|
|
29
|
+
|
|
30
|
+
// ffmpeg.wasm state
|
|
31
|
+
let ffmpegInstance: unknown = null;
|
|
32
|
+
let ffmpegFrames: Array<{ data: Uint8Array; index: number }> = [];
|
|
33
|
+
let ffmpegConfig: InitMessage | null = null;
|
|
34
|
+
|
|
35
|
+
// Frame tracking
|
|
36
|
+
let totalFramesReceived = 0;
|
|
37
|
+
let _totalFramesEncoded = 0;
|
|
38
|
+
|
|
39
|
+
// ── Helpers ────────────────────────────────────────────────────────
|
|
40
|
+
|
|
41
|
+
function post(msg: WorkerToMainMessage, transfer?: Transferable[]) {
|
|
42
|
+
self.postMessage(msg, { transfer: transfer ?? [] });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function postProgress(percent: number, phase: string) {
|
|
46
|
+
post({ type: 'progress', percent, phase });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function postError(message: string) {
|
|
50
|
+
post({ type: 'error', message });
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// ── Feature Detection ──────────────────────────────────────────────
|
|
54
|
+
|
|
55
|
+
function hasWebCodecs(): boolean {
|
|
56
|
+
return typeof VideoEncoder !== 'undefined' && typeof VideoFrame !== 'undefined';
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function hasSharedArrayBuffer(): boolean {
|
|
60
|
+
return typeof SharedArrayBuffer !== 'undefined';
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ── WebCodecs Backend ──────────────────────────────────────────────
|
|
64
|
+
|
|
65
|
+
function initWebCodecs(config: InitMessage) {
|
|
66
|
+
muxer = createMp4Muxer({
|
|
67
|
+
width: config.width,
|
|
68
|
+
height: config.height,
|
|
69
|
+
fps: config.fps,
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
videoEncoder = new VideoEncoder({
|
|
73
|
+
output(chunk, meta) {
|
|
74
|
+
if (cancelled) return;
|
|
75
|
+
muxer!.addVideoChunk(chunk, meta ?? undefined);
|
|
76
|
+
_totalFramesEncoded++;
|
|
77
|
+
},
|
|
78
|
+
error(err) {
|
|
79
|
+
postError(`WebCodecs encoder error: ${err.message}`);
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
// Use H.264 Baseline for maximum compatibility
|
|
84
|
+
videoEncoder.configure({
|
|
85
|
+
codec: 'avc1.42001f',
|
|
86
|
+
width: config.width,
|
|
87
|
+
height: config.height,
|
|
88
|
+
bitrate: bitrateForQuality(config.quality, config.width, config.height),
|
|
89
|
+
framerate: config.fps,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function bitrateForQuality(quality: string, width: number, height: number): number {
|
|
94
|
+
const pixels = width * height;
|
|
95
|
+
const baseBitrate = pixels * 4; // ~4 bits per pixel baseline
|
|
96
|
+
switch (quality) {
|
|
97
|
+
case 'draft':
|
|
98
|
+
return Math.round(baseBitrate * 0.5);
|
|
99
|
+
case 'high':
|
|
100
|
+
return Math.round(baseBitrate * 2);
|
|
101
|
+
default: // normal
|
|
102
|
+
return baseBitrate;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function encodeFrameWebCodecs(msg: FrameMessage) {
|
|
107
|
+
if (!videoEncoder || cancelled) {
|
|
108
|
+
msg.bitmap.close();
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const frame = new VideoFrame(msg.bitmap, { timestamp: msg.timestamp });
|
|
113
|
+
const keyFrame = msg.frameIndex % 30 === 0; // Key frame every 30 frames
|
|
114
|
+
videoEncoder.encode(frame, { keyFrame });
|
|
115
|
+
frame.close();
|
|
116
|
+
msg.bitmap.close();
|
|
117
|
+
totalFramesReceived++;
|
|
118
|
+
|
|
119
|
+
postProgress(
|
|
120
|
+
Math.round((totalFramesReceived / (totalFramesReceived + 1)) * 50),
|
|
121
|
+
`Encoding frame ${totalFramesReceived}`,
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function finalizeWebCodecs() {
|
|
126
|
+
if (!videoEncoder || !muxer || cancelled) return;
|
|
127
|
+
|
|
128
|
+
postProgress(50, 'Flushing encoder…');
|
|
129
|
+
await videoEncoder.flush();
|
|
130
|
+
videoEncoder.close();
|
|
131
|
+
videoEncoder = null;
|
|
132
|
+
|
|
133
|
+
postProgress(90, 'Finalizing MP4…');
|
|
134
|
+
const buffer = muxer.finalize();
|
|
135
|
+
muxer = null;
|
|
136
|
+
|
|
137
|
+
post({ type: 'complete', data: buffer, size: buffer.byteLength }, [buffer]);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// ── ffmpeg.wasm Backend ────────────────────────────────────────────
|
|
141
|
+
|
|
142
|
+
async function initFfmpegWasm(config: InitMessage) {
|
|
143
|
+
ffmpegConfig = config;
|
|
144
|
+
ffmpegFrames = [];
|
|
145
|
+
totalFramesReceived = 0;
|
|
146
|
+
|
|
147
|
+
// Lazy-load ffmpeg.wasm
|
|
148
|
+
try {
|
|
149
|
+
const { FFmpeg } = await import('@ffmpeg/ffmpeg');
|
|
150
|
+
const ffmpeg = new FFmpeg();
|
|
151
|
+
await ffmpeg.load();
|
|
152
|
+
ffmpegInstance = ffmpeg;
|
|
153
|
+
} catch (err: unknown) {
|
|
154
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
155
|
+
postError(
|
|
156
|
+
`Failed to load ffmpeg.wasm: ${message}. ` +
|
|
157
|
+
'Ensure @ffmpeg/ffmpeg and @ffmpeg/util are installed and ' +
|
|
158
|
+
'Cross-Origin-Isolation headers (COOP/COEP) are set.',
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function encodeFrameFfmpeg(msg: FrameMessage) {
|
|
164
|
+
if (cancelled) {
|
|
165
|
+
msg.bitmap.close();
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Convert ImageBitmap to PNG bytes via OffscreenCanvas
|
|
170
|
+
const canvas = new OffscreenCanvas(msg.bitmap.width, msg.bitmap.height);
|
|
171
|
+
const ctx = canvas.getContext('2d');
|
|
172
|
+
if (!ctx) {
|
|
173
|
+
msg.bitmap.close();
|
|
174
|
+
postError('Failed to create OffscreenCanvas 2D context');
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
ctx.drawImage(msg.bitmap, 0, 0);
|
|
178
|
+
msg.bitmap.close();
|
|
179
|
+
|
|
180
|
+
const blob = await canvas.convertToBlob({ type: 'image/png' });
|
|
181
|
+
const arrayBuffer = await blob.arrayBuffer();
|
|
182
|
+
ffmpegFrames.push({ data: new Uint8Array(arrayBuffer), index: msg.frameIndex });
|
|
183
|
+
totalFramesReceived++;
|
|
184
|
+
|
|
185
|
+
postProgress(
|
|
186
|
+
Math.round((totalFramesReceived / (totalFramesReceived + 1)) * 40),
|
|
187
|
+
`Collecting frame ${totalFramesReceived}`,
|
|
188
|
+
);
|
|
189
|
+
|
|
190
|
+
// Batch encode every ~10 seconds worth of frames
|
|
191
|
+
const batchSize = (ffmpegConfig?.fps ?? 30) * 10;
|
|
192
|
+
if (ffmpegFrames.length >= batchSize) {
|
|
193
|
+
await encodeFfmpegBatch();
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Segments already encoded as MP4 data. */
|
|
198
|
+
const ffmpegSegments: Uint8Array[] = [];
|
|
199
|
+
|
|
200
|
+
async function encodeFfmpegBatch() {
|
|
201
|
+
if (!ffmpegInstance || ffmpegFrames.length === 0 || cancelled) return;
|
|
202
|
+
|
|
203
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
204
|
+
const ffmpeg = ffmpegInstance as any;
|
|
205
|
+
const config = ffmpegConfig!;
|
|
206
|
+
const batchIndex = ffmpegSegments.length;
|
|
207
|
+
|
|
208
|
+
postProgress(40 + batchIndex * 5, `Encoding batch ${batchIndex + 1}…`);
|
|
209
|
+
|
|
210
|
+
// Write frames to virtual filesystem
|
|
211
|
+
for (const frame of ffmpegFrames) {
|
|
212
|
+
const paddedIndex = String(frame.index).padStart(6, '0');
|
|
213
|
+
await ffmpeg.writeFile(`frame_${paddedIndex}.png`, frame.data);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const firstIndex = ffmpegFrames[0].index;
|
|
217
|
+
const segmentName = `segment_${batchIndex}.mp4`;
|
|
218
|
+
|
|
219
|
+
// Encode batch to MP4 segment
|
|
220
|
+
await ffmpeg.exec([
|
|
221
|
+
'-framerate',
|
|
222
|
+
String(config.fps),
|
|
223
|
+
'-start_number',
|
|
224
|
+
String(firstIndex),
|
|
225
|
+
'-i',
|
|
226
|
+
`frame_%06d.png`,
|
|
227
|
+
'-frames:v',
|
|
228
|
+
String(ffmpegFrames.length),
|
|
229
|
+
'-c:v',
|
|
230
|
+
'libx264',
|
|
231
|
+
'-pix_fmt',
|
|
232
|
+
'yuv420p',
|
|
233
|
+
'-preset',
|
|
234
|
+
config.quality === 'draft' ? 'ultrafast' : config.quality === 'high' ? 'slow' : 'medium',
|
|
235
|
+
'-crf',
|
|
236
|
+
config.quality === 'draft' ? '28' : config.quality === 'high' ? '18' : '23',
|
|
237
|
+
segmentName,
|
|
238
|
+
]);
|
|
239
|
+
|
|
240
|
+
// Read segment and clean up frames
|
|
241
|
+
const segmentData = await ffmpeg.readFile(segmentName);
|
|
242
|
+
ffmpegSegments.push(segmentData);
|
|
243
|
+
|
|
244
|
+
// Clean up frame files
|
|
245
|
+
for (const frame of ffmpegFrames) {
|
|
246
|
+
const paddedIndex = String(frame.index).padStart(6, '0');
|
|
247
|
+
await ffmpeg.deleteFile(`frame_${paddedIndex}.png`);
|
|
248
|
+
}
|
|
249
|
+
await ffmpeg.deleteFile(segmentName);
|
|
250
|
+
|
|
251
|
+
// Free batch memory
|
|
252
|
+
ffmpegFrames = [];
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async function finalizeFfmpeg() {
|
|
256
|
+
if (!ffmpegInstance || cancelled) return;
|
|
257
|
+
|
|
258
|
+
// Encode any remaining frames
|
|
259
|
+
await encodeFfmpegBatch();
|
|
260
|
+
|
|
261
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
262
|
+
const ffmpeg = ffmpegInstance as any;
|
|
263
|
+
|
|
264
|
+
postProgress(85, 'Concatenating segments…');
|
|
265
|
+
|
|
266
|
+
let finalData: Uint8Array;
|
|
267
|
+
|
|
268
|
+
if (ffmpegSegments.length === 1) {
|
|
269
|
+
// Single segment — no concat needed
|
|
270
|
+
finalData = ffmpegSegments[0];
|
|
271
|
+
} else if (ffmpegSegments.length > 1) {
|
|
272
|
+
// Write segments and concat list
|
|
273
|
+
const concatList: string[] = [];
|
|
274
|
+
for (let i = 0; i < ffmpegSegments.length; i++) {
|
|
275
|
+
const name = `seg_${i}.mp4`;
|
|
276
|
+
await ffmpeg.writeFile(name, ffmpegSegments[i]);
|
|
277
|
+
concatList.push(`file '${name}'`);
|
|
278
|
+
}
|
|
279
|
+
await ffmpeg.writeFile('concat.txt', new TextEncoder().encode(concatList.join('\n')));
|
|
280
|
+
|
|
281
|
+
await ffmpeg.exec([
|
|
282
|
+
'-f',
|
|
283
|
+
'concat',
|
|
284
|
+
'-safe',
|
|
285
|
+
'0',
|
|
286
|
+
'-i',
|
|
287
|
+
'concat.txt',
|
|
288
|
+
'-c',
|
|
289
|
+
'copy',
|
|
290
|
+
'output.mp4',
|
|
291
|
+
]);
|
|
292
|
+
|
|
293
|
+
finalData = await ffmpeg.readFile('output.mp4');
|
|
294
|
+
|
|
295
|
+
// Clean up
|
|
296
|
+
for (let i = 0; i < ffmpegSegments.length; i++) {
|
|
297
|
+
await ffmpeg.deleteFile(`seg_${i}.mp4`);
|
|
298
|
+
}
|
|
299
|
+
await ffmpeg.deleteFile('concat.txt');
|
|
300
|
+
await ffmpeg.deleteFile('output.mp4');
|
|
301
|
+
} else {
|
|
302
|
+
postError('No frames were encoded');
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
postProgress(95, 'Preparing download…');
|
|
307
|
+
|
|
308
|
+
// Convert Uint8Array to a transferable ArrayBuffer
|
|
309
|
+
const sliced = new Uint8Array(finalData).buffer as ArrayBuffer;
|
|
310
|
+
post({ type: 'complete', data: sliced, size: sliced.byteLength }, [sliced]);
|
|
311
|
+
|
|
312
|
+
// Clean up
|
|
313
|
+
ffmpegInstance = null;
|
|
314
|
+
ffmpegSegments.length = 0;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// ── Message Handler ────────────────────────────────────────────────
|
|
318
|
+
|
|
319
|
+
self.onmessage = async (event: MessageEvent<MainToWorkerMessage>) => {
|
|
320
|
+
const msg = event.data;
|
|
321
|
+
|
|
322
|
+
try {
|
|
323
|
+
switch (msg.type) {
|
|
324
|
+
case 'init': {
|
|
325
|
+
cancelled = false;
|
|
326
|
+
totalFramesReceived = 0;
|
|
327
|
+
_totalFramesEncoded = 0;
|
|
328
|
+
|
|
329
|
+
if (hasWebCodecs()) {
|
|
330
|
+
backend = 'webcodecs';
|
|
331
|
+
initWebCodecs(msg);
|
|
332
|
+
} else if (hasSharedArrayBuffer()) {
|
|
333
|
+
backend = 'ffmpeg-wasm';
|
|
334
|
+
await initFfmpegWasm(msg);
|
|
335
|
+
} else {
|
|
336
|
+
postError(
|
|
337
|
+
'No video encoding support available. ' +
|
|
338
|
+
'WebCodecs requires Chrome 94+ or Edge 94+. ' +
|
|
339
|
+
'ffmpeg.wasm requires SharedArrayBuffer (Cross-Origin-Isolation headers).',
|
|
340
|
+
);
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
post({ type: 'capabilities', backend });
|
|
345
|
+
postProgress(0, 'Encoder ready');
|
|
346
|
+
break;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
case 'frame': {
|
|
350
|
+
if (backend === 'webcodecs') {
|
|
351
|
+
await encodeFrameWebCodecs(msg);
|
|
352
|
+
} else if (backend === 'ffmpeg-wasm') {
|
|
353
|
+
await encodeFrameFfmpeg(msg);
|
|
354
|
+
}
|
|
355
|
+
break;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
case 'finalize': {
|
|
359
|
+
if (backend === 'webcodecs') {
|
|
360
|
+
await finalizeWebCodecs();
|
|
361
|
+
} else if (backend === 'ffmpeg-wasm') {
|
|
362
|
+
await finalizeFfmpeg();
|
|
363
|
+
}
|
|
364
|
+
break;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
case 'cancel': {
|
|
368
|
+
cancelled = true;
|
|
369
|
+
if (videoEncoder && videoEncoder.state !== 'closed') {
|
|
370
|
+
videoEncoder.close();
|
|
371
|
+
videoEncoder = null;
|
|
372
|
+
}
|
|
373
|
+
muxer = null;
|
|
374
|
+
ffmpegInstance = null;
|
|
375
|
+
ffmpegFrames = [];
|
|
376
|
+
ffmpegSegments.length = 0;
|
|
377
|
+
break;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
} catch (err: unknown) {
|
|
381
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
382
|
+
postError(message);
|
|
383
|
+
}
|
|
384
|
+
};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Worker Message Protocol
|
|
3
|
+
*
|
|
4
|
+
* Defines the message types exchanged between the main thread and
|
|
5
|
+
* the video encoding Web Worker.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { VideoQuality } from '@bendyline/squisq-video';
|
|
9
|
+
|
|
10
|
+
// ── Main → Worker Messages ─────────────────────────────────────────
|
|
11
|
+
|
|
12
|
+
/** Initialize the encoder with video parameters. */
|
|
13
|
+
export interface InitMessage {
|
|
14
|
+
type: 'init';
|
|
15
|
+
width: number;
|
|
16
|
+
height: number;
|
|
17
|
+
fps: number;
|
|
18
|
+
quality: VideoQuality;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Send a single video frame to the encoder. */
|
|
22
|
+
export interface FrameMessage {
|
|
23
|
+
type: 'frame';
|
|
24
|
+
/** Frame bitmap — transferred (zero-copy) from main thread */
|
|
25
|
+
bitmap: ImageBitmap;
|
|
26
|
+
/** Frame index (0-based) */
|
|
27
|
+
frameIndex: number;
|
|
28
|
+
/** Timestamp in microseconds */
|
|
29
|
+
timestamp: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Signal that all frames have been sent; finalize the video. */
|
|
33
|
+
export interface FinalizeMessage {
|
|
34
|
+
type: 'finalize';
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Cancel the export and clean up resources. */
|
|
38
|
+
export interface CancelMessage {
|
|
39
|
+
type: 'cancel';
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export type MainToWorkerMessage = InitMessage | FrameMessage | FinalizeMessage | CancelMessage;
|
|
43
|
+
|
|
44
|
+
// ── Worker → Main Messages ─────────────────────────────────────────
|
|
45
|
+
|
|
46
|
+
/** Encoder backend detection result, sent after init. */
|
|
47
|
+
export interface CapabilitiesMessage {
|
|
48
|
+
type: 'capabilities';
|
|
49
|
+
/** Which encoder backend the worker selected */
|
|
50
|
+
backend: 'webcodecs' | 'ffmpeg-wasm';
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Progress update during encoding. */
|
|
54
|
+
export interface ProgressMessage {
|
|
55
|
+
type: 'progress';
|
|
56
|
+
/** 0–100 completion percentage */
|
|
57
|
+
percent: number;
|
|
58
|
+
/** Human-readable phase description */
|
|
59
|
+
phase: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Encoding complete — MP4 data returned. */
|
|
63
|
+
export interface CompleteMessage {
|
|
64
|
+
type: 'complete';
|
|
65
|
+
/** MP4 file data — transferred (zero-copy) back to main thread */
|
|
66
|
+
data: ArrayBuffer;
|
|
67
|
+
/** File size in bytes */
|
|
68
|
+
size: number;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** An error occurred during encoding. */
|
|
72
|
+
export interface ErrorMessage {
|
|
73
|
+
type: 'error';
|
|
74
|
+
message: string;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export type WorkerToMainMessage =
|
|
78
|
+
| CapabilitiesMessage
|
|
79
|
+
| ProgressMessage
|
|
80
|
+
| CompleteMessage
|
|
81
|
+
| ErrorMessage;
|