@shotstack/shotstack-canvas 1.9.5 → 2.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.
@@ -0,0 +1,140 @@
1
+ import {
2
+ __publicField
3
+ } from "./chunk-FPPKRKBX.js";
4
+
5
+ // src/core/video/mediarecorder-fallback.ts
6
+ var MediaRecorderFallback = class {
7
+ constructor() {
8
+ __publicField(this, "mediaRecorder", null);
9
+ __publicField(this, "canvas", null);
10
+ __publicField(this, "config", null);
11
+ __publicField(this, "chunks", []);
12
+ __publicField(this, "frameCount", 0);
13
+ __publicField(this, "totalFrames", 0);
14
+ __publicField(this, "startTime", 0);
15
+ __publicField(this, "ctx", null);
16
+ __publicField(this, "onProgress");
17
+ }
18
+ async configure(config, canvas) {
19
+ this.config = config;
20
+ this.totalFrames = Math.max(2, Math.round(config.duration * config.fps) + 1);
21
+ this.frameCount = 0;
22
+ this.startTime = Date.now();
23
+ this.chunks = [];
24
+ if (canvas) {
25
+ this.canvas = canvas;
26
+ } else {
27
+ if (typeof OffscreenCanvas !== "undefined") {
28
+ this.canvas = new OffscreenCanvas(config.width, config.height);
29
+ } else if (typeof document !== "undefined") {
30
+ this.canvas = document.createElement("canvas");
31
+ this.canvas.width = config.width;
32
+ this.canvas.height = config.height;
33
+ } else {
34
+ throw new Error("No canvas available for MediaRecorder fallback");
35
+ }
36
+ }
37
+ this.ctx = this.canvas.getContext("2d");
38
+ if (!this.ctx) {
39
+ throw new Error("Failed to get 2D context");
40
+ }
41
+ const stream = this.canvas.captureStream?.(config.fps);
42
+ if (!stream) {
43
+ throw new Error("captureStream not supported on this canvas type");
44
+ }
45
+ const mimeType = getPreferredMimeType();
46
+ this.mediaRecorder = new MediaRecorder(stream, {
47
+ mimeType,
48
+ videoBitsPerSecond: config.bitrate ?? 8e6
49
+ });
50
+ this.mediaRecorder.ondataavailable = (event) => {
51
+ if (event.data.size > 0) {
52
+ this.chunks.push(event.data);
53
+ }
54
+ };
55
+ this.mediaRecorder.start(100);
56
+ }
57
+ async encodeFrame(frameData, _frameIndex) {
58
+ if (!this.ctx || !this.config) {
59
+ throw new Error("Encoder not configured. Call configure() first.");
60
+ }
61
+ const { width, height } = this.config;
62
+ const pixelData = frameData instanceof ArrayBuffer ? new Uint8ClampedArray(frameData) : frameData;
63
+ const imageData = new ImageData(pixelData, width, height);
64
+ this.ctx.putImageData(imageData, 0, 0);
65
+ this.frameCount++;
66
+ if (this.onProgress) {
67
+ const elapsedMs = Date.now() - this.startTime;
68
+ if (elapsedMs > 0) {
69
+ const framesPerSecond = this.frameCount / (elapsedMs / 1e3);
70
+ const remainingFrames = this.totalFrames - this.frameCount;
71
+ const estimatedRemainingMs = remainingFrames / framesPerSecond * 1e3;
72
+ this.onProgress({
73
+ framesEncoded: this.frameCount,
74
+ totalFrames: this.totalFrames,
75
+ percentage: this.frameCount / this.totalFrames * 100,
76
+ elapsedMs,
77
+ estimatedRemainingMs: Math.round(estimatedRemainingMs),
78
+ currentFps: Math.round(framesPerSecond * 10) / 10
79
+ });
80
+ }
81
+ }
82
+ const frameInterval = 1e3 / this.config.fps;
83
+ await new Promise((resolve) => setTimeout(resolve, frameInterval));
84
+ }
85
+ async flush() {
86
+ if (!this.mediaRecorder) {
87
+ throw new Error("MediaRecorder not configured.");
88
+ }
89
+ return new Promise((resolve, reject) => {
90
+ this.mediaRecorder.onstop = () => {
91
+ const blob = new Blob(this.chunks, { type: this.mediaRecorder.mimeType });
92
+ resolve(blob);
93
+ };
94
+ this.mediaRecorder.onerror = (event) => {
95
+ reject(new Error(`MediaRecorder error: ${event}`));
96
+ };
97
+ this.mediaRecorder.stop();
98
+ });
99
+ }
100
+ close() {
101
+ if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") {
102
+ this.mediaRecorder.stop();
103
+ }
104
+ this.mediaRecorder = null;
105
+ this.canvas = null;
106
+ this.ctx = null;
107
+ this.chunks = [];
108
+ }
109
+ getOutputMimeType() {
110
+ return this.mediaRecorder?.mimeType || "video/webm";
111
+ }
112
+ };
113
+ function getPreferredMimeType() {
114
+ const mimeTypes = [
115
+ "video/webm;codecs=vp9",
116
+ "video/webm;codecs=vp8",
117
+ "video/webm",
118
+ "video/mp4"
119
+ ];
120
+ for (const mimeType of mimeTypes) {
121
+ if (MediaRecorder.isTypeSupported(mimeType)) {
122
+ return mimeType;
123
+ }
124
+ }
125
+ return "video/webm";
126
+ }
127
+ function isMediaRecorderSupported() {
128
+ return typeof MediaRecorder !== "undefined" && typeof HTMLCanvasElement !== "undefined" && typeof HTMLCanvasElement.prototype.captureStream === "function";
129
+ }
130
+ async function createMediaRecorderFallback(config, canvas) {
131
+ const encoder = new MediaRecorderFallback();
132
+ await encoder.configure(config, canvas);
133
+ return encoder;
134
+ }
135
+
136
+ export {
137
+ MediaRecorderFallback,
138
+ isMediaRecorderSupported,
139
+ createMediaRecorderFallback
140
+ };
@@ -0,0 +1,66 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __typeError = (msg) => {
8
+ throw TypeError(msg);
9
+ };
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
12
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
13
+ }) : x)(function(x) {
14
+ if (typeof require !== "undefined") return require.apply(this, arguments);
15
+ throw Error('Dynamic require of "' + x + '" is not supported');
16
+ });
17
+ var __commonJS = (cb, mod) => function __require2() {
18
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ };
20
+ var __export = (target, all) => {
21
+ for (var name in all)
22
+ __defProp(target, name, { get: all[name], enumerable: true });
23
+ };
24
+ var __copyProps = (to, from, except, desc) => {
25
+ if (from && typeof from === "object" || typeof from === "function") {
26
+ for (let key of __getOwnPropNames(from))
27
+ if (!__hasOwnProp.call(to, key) && key !== except)
28
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
29
+ }
30
+ return to;
31
+ };
32
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
33
+ // If the importer is in node compatibility mode or this is not an ESM
34
+ // file that has been converted to a CommonJS file using a Babel-
35
+ // compatible transform (i.e. "__esModule" has not been set), then set
36
+ // "default" to the CommonJS "module.exports" for node compatibility.
37
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
38
+ mod
39
+ ));
40
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
41
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
42
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
43
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
44
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
45
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
46
+ var __privateWrapper = (obj, member, setter, getter) => ({
47
+ set _(value) {
48
+ __privateSet(obj, member, value, setter);
49
+ },
50
+ get _() {
51
+ return __privateGet(obj, member, getter);
52
+ }
53
+ });
54
+
55
+ export {
56
+ __require,
57
+ __commonJS,
58
+ __export,
59
+ __toESM,
60
+ __publicField,
61
+ __privateGet,
62
+ __privateAdd,
63
+ __privateSet,
64
+ __privateMethod,
65
+ __privateWrapper
66
+ };
@@ -0,0 +1,178 @@
1
+ import {
2
+ __publicField
3
+ } from "./chunk-FPPKRKBX.js";
4
+
5
+ // src/core/video/web-encoder.ts
6
+ var WebCodecsEncoder = class {
7
+ constructor() {
8
+ __publicField(this, "encoder", null);
9
+ __publicField(this, "muxer", null);
10
+ __publicField(this, "config", null);
11
+ __publicField(this, "frameCount", 0);
12
+ __publicField(this, "totalFrames", 0);
13
+ __publicField(this, "startTime", 0);
14
+ __publicField(this, "fps", 30);
15
+ __publicField(this, "keyframeInterval", 150);
16
+ __publicField(this, "encoderError", null);
17
+ __publicField(this, "onProgress");
18
+ }
19
+ async configure(config) {
20
+ if (typeof VideoEncoder === "undefined") {
21
+ throw new Error("WebCodecs API not supported in this browser.");
22
+ }
23
+ this.config = config;
24
+ this.fps = config.fps;
25
+ this.totalFrames = Math.max(2, Math.round(config.duration * config.fps) + 1);
26
+ this.frameCount = 0;
27
+ this.startTime = Date.now();
28
+ this.keyframeInterval = Math.round(config.fps * 10);
29
+ this.encoderError = null;
30
+ const { Muxer, ArrayBufferTarget } = await import("mp4-muxer");
31
+ this.muxer = new Muxer({
32
+ target: new ArrayBufferTarget(),
33
+ video: {
34
+ codec: "avc",
35
+ width: config.width,
36
+ height: config.height
37
+ },
38
+ fastStart: "in-memory"
39
+ });
40
+ const candidates = getH264CodecCandidates(config.profile || "high");
41
+ let encoderConfig = null;
42
+ for (const codec of candidates) {
43
+ const candidate = {
44
+ codec,
45
+ width: config.width,
46
+ height: config.height,
47
+ bitrate: config.bitrate ?? 8e6,
48
+ framerate: config.fps,
49
+ hardwareAcceleration: config.hardwareAcceleration ?? "prefer-hardware",
50
+ latencyMode: "quality"
51
+ };
52
+ const support = await VideoEncoder.isConfigSupported(candidate);
53
+ if (support.supported) {
54
+ encoderConfig = candidate;
55
+ break;
56
+ }
57
+ }
58
+ if (!encoderConfig) {
59
+ throw new Error("H.264 encoding not supported. Tried codecs: " + candidates.join(", "));
60
+ }
61
+ this.encoder = new VideoEncoder({
62
+ output: (chunk, metadata) => {
63
+ this.muxer.addVideoChunk(chunk, metadata);
64
+ },
65
+ error: (e) => {
66
+ this.encoderError = e;
67
+ }
68
+ });
69
+ this.encoder.configure(encoderConfig);
70
+ }
71
+ async encodeFrame(frameData, frameIndex) {
72
+ if (this.encoderError) {
73
+ throw this.encoderError;
74
+ }
75
+ if (!this.encoder || !this.config) {
76
+ throw new Error("Encoder not configured. Call configure() first.");
77
+ }
78
+ const { width, height } = this.config;
79
+ const timestamp = Math.round(frameIndex * 1e6 / this.fps);
80
+ const pixelData = frameData instanceof ArrayBuffer ? new Uint8ClampedArray(frameData) : frameData;
81
+ const imageData = new ImageData(pixelData, width, height);
82
+ const videoFrame = new VideoFrame(imageData, { timestamp });
83
+ const isKeyFrame = frameIndex % this.keyframeInterval === 0;
84
+ this.encoder.encode(videoFrame, { keyFrame: isKeyFrame });
85
+ videoFrame.close();
86
+ this.frameCount++;
87
+ this.reportProgress();
88
+ }
89
+ async encodeCanvas(canvas, frameIndex) {
90
+ if (this.encoderError) {
91
+ throw this.encoderError;
92
+ }
93
+ if (!this.encoder || !this.config) {
94
+ throw new Error("Encoder not configured. Call configure() first.");
95
+ }
96
+ const timestamp = Math.round(frameIndex * 1e6 / this.fps);
97
+ const videoFrame = new VideoFrame(canvas, { timestamp });
98
+ const isKeyFrame = frameIndex % this.keyframeInterval === 0;
99
+ this.encoder.encode(videoFrame, { keyFrame: isKeyFrame });
100
+ videoFrame.close();
101
+ this.frameCount++;
102
+ this.reportProgress();
103
+ }
104
+ async encodeCanvasRepeat(canvas, startFrameIndex, repeatCount) {
105
+ if (this.encoderError) {
106
+ throw this.encoderError;
107
+ }
108
+ if (!this.encoder || !this.config) {
109
+ throw new Error("Encoder not configured. Call configure() first.");
110
+ }
111
+ for (let i = 0; i < repeatCount; i++) {
112
+ const actualFrameIndex = startFrameIndex + i;
113
+ const timestamp = Math.round(actualFrameIndex * 1e6 / this.fps);
114
+ const videoFrame = new VideoFrame(canvas, { timestamp });
115
+ const isKeyFrame = actualFrameIndex % this.keyframeInterval === 0;
116
+ this.encoder.encode(videoFrame, { keyFrame: isKeyFrame });
117
+ videoFrame.close();
118
+ this.frameCount++;
119
+ }
120
+ this.reportProgress();
121
+ }
122
+ async flush() {
123
+ if (this.encoderError) {
124
+ throw this.encoderError;
125
+ }
126
+ if (!this.encoder || !this.muxer) {
127
+ throw new Error("Encoder not configured.");
128
+ }
129
+ await this.encoder.flush();
130
+ this.muxer.finalize();
131
+ const buffer = this.muxer.target.buffer;
132
+ return new Blob([buffer], { type: "video/mp4" });
133
+ }
134
+ close() {
135
+ if (this.encoder && this.encoder.state !== "closed") {
136
+ this.encoder.close();
137
+ }
138
+ this.encoder = null;
139
+ this.muxer = null;
140
+ }
141
+ reportProgress() {
142
+ if (!this.onProgress) return;
143
+ const elapsedMs = Date.now() - this.startTime;
144
+ if (elapsedMs === 0) return;
145
+ const framesPerSecond = this.frameCount / (elapsedMs / 1e3);
146
+ const remainingFrames = this.totalFrames - this.frameCount;
147
+ const estimatedRemainingMs = remainingFrames / framesPerSecond * 1e3;
148
+ this.onProgress({
149
+ framesEncoded: this.frameCount,
150
+ totalFrames: this.totalFrames,
151
+ percentage: this.frameCount / this.totalFrames * 100,
152
+ elapsedMs,
153
+ estimatedRemainingMs: Math.round(estimatedRemainingMs),
154
+ currentFps: Math.round(framesPerSecond * 10) / 10
155
+ });
156
+ }
157
+ };
158
+ function getH264CodecCandidates(profile) {
159
+ switch (profile) {
160
+ case "baseline":
161
+ return ["avc1.42E028", "avc1.42001F", "avc1.42001E"];
162
+ case "main":
163
+ return ["avc1.4D0028", "avc1.4D001F", "avc1.4D001E"];
164
+ case "high":
165
+ default:
166
+ return ["avc1.640028", "avc1.640029", "avc1.64001F", "avc1.64001E"];
167
+ }
168
+ }
169
+ async function createWebCodecsEncoder(config) {
170
+ const encoder = new WebCodecsEncoder();
171
+ await encoder.configure(config);
172
+ return encoder;
173
+ }
174
+
175
+ export {
176
+ WebCodecsEncoder,
177
+ createWebCodecsEncoder
178
+ };