@shotstack/shotstack-canvas 1.9.6 → 2.0.1

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.
@@ -2,7 +2,7 @@ import {
2
2
  __commonJS,
3
3
  __publicField,
4
4
  __require
5
- } from "./chunk-HYGMWVDX.js";
5
+ } from "./chunk-FPPKRKBX.js";
6
6
 
7
7
  // node_modules/.pnpm/harfbuzzjs@0.4.12/node_modules/harfbuzzjs/hb.js
8
8
  var require_hb = __commonJS({
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  __commonJS
3
- } from "./chunk-HYGMWVDX.js";
3
+ } from "./chunk-FPPKRKBX.js";
4
4
 
5
5
  // node_modules/.pnpm/harfbuzzjs@0.4.12/node_modules/harfbuzzjs/hbjs.js
6
6
  var require_hbjs = __commonJS({
@@ -0,0 +1,133 @@
1
+ // src/core/video/mediarecorder-fallback.ts
2
+ var MediaRecorderFallback = class {
3
+ mediaRecorder = null;
4
+ canvas = null;
5
+ config = null;
6
+ chunks = [];
7
+ frameCount = 0;
8
+ totalFrames = 0;
9
+ startTime = 0;
10
+ ctx = null;
11
+ onProgress;
12
+ async configure(config, canvas) {
13
+ this.config = config;
14
+ this.totalFrames = Math.max(2, Math.round(config.duration * config.fps) + 1);
15
+ this.frameCount = 0;
16
+ this.startTime = Date.now();
17
+ this.chunks = [];
18
+ if (canvas) {
19
+ this.canvas = canvas;
20
+ } else {
21
+ if (typeof OffscreenCanvas !== "undefined") {
22
+ this.canvas = new OffscreenCanvas(config.width, config.height);
23
+ } else if (typeof document !== "undefined") {
24
+ this.canvas = document.createElement("canvas");
25
+ this.canvas.width = config.width;
26
+ this.canvas.height = config.height;
27
+ } else {
28
+ throw new Error("No canvas available for MediaRecorder fallback");
29
+ }
30
+ }
31
+ this.ctx = this.canvas.getContext("2d");
32
+ if (!this.ctx) {
33
+ throw new Error("Failed to get 2D context");
34
+ }
35
+ const stream = this.canvas.captureStream?.(config.fps);
36
+ if (!stream) {
37
+ throw new Error("captureStream not supported on this canvas type");
38
+ }
39
+ const mimeType = getPreferredMimeType();
40
+ this.mediaRecorder = new MediaRecorder(stream, {
41
+ mimeType,
42
+ videoBitsPerSecond: config.bitrate ?? 8e6
43
+ });
44
+ this.mediaRecorder.ondataavailable = (event) => {
45
+ if (event.data.size > 0) {
46
+ this.chunks.push(event.data);
47
+ }
48
+ };
49
+ this.mediaRecorder.start(100);
50
+ }
51
+ async encodeFrame(frameData, _frameIndex) {
52
+ if (!this.ctx || !this.config) {
53
+ throw new Error("Encoder not configured. Call configure() first.");
54
+ }
55
+ const { width, height } = this.config;
56
+ const pixelData = frameData instanceof ArrayBuffer ? new Uint8ClampedArray(frameData) : frameData;
57
+ const imageData = new ImageData(pixelData, width, height);
58
+ this.ctx.putImageData(imageData, 0, 0);
59
+ this.frameCount++;
60
+ if (this.onProgress) {
61
+ const elapsedMs = Date.now() - this.startTime;
62
+ if (elapsedMs > 0) {
63
+ const framesPerSecond = this.frameCount / (elapsedMs / 1e3);
64
+ const remainingFrames = this.totalFrames - this.frameCount;
65
+ const estimatedRemainingMs = remainingFrames / framesPerSecond * 1e3;
66
+ this.onProgress({
67
+ framesEncoded: this.frameCount,
68
+ totalFrames: this.totalFrames,
69
+ percentage: this.frameCount / this.totalFrames * 100,
70
+ elapsedMs,
71
+ estimatedRemainingMs: Math.round(estimatedRemainingMs),
72
+ currentFps: Math.round(framesPerSecond * 10) / 10
73
+ });
74
+ }
75
+ }
76
+ const frameInterval = 1e3 / this.config.fps;
77
+ await new Promise((resolve) => setTimeout(resolve, frameInterval));
78
+ }
79
+ async flush() {
80
+ if (!this.mediaRecorder) {
81
+ throw new Error("MediaRecorder not configured.");
82
+ }
83
+ return new Promise((resolve, reject) => {
84
+ this.mediaRecorder.onstop = () => {
85
+ const blob = new Blob(this.chunks, { type: this.mediaRecorder.mimeType });
86
+ resolve(blob);
87
+ };
88
+ this.mediaRecorder.onerror = (event) => {
89
+ reject(new Error(`MediaRecorder error: ${event}`));
90
+ };
91
+ this.mediaRecorder.stop();
92
+ });
93
+ }
94
+ close() {
95
+ if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") {
96
+ this.mediaRecorder.stop();
97
+ }
98
+ this.mediaRecorder = null;
99
+ this.canvas = null;
100
+ this.ctx = null;
101
+ this.chunks = [];
102
+ }
103
+ getOutputMimeType() {
104
+ return this.mediaRecorder?.mimeType || "video/webm";
105
+ }
106
+ };
107
+ function getPreferredMimeType() {
108
+ const mimeTypes = [
109
+ "video/webm;codecs=vp9",
110
+ "video/webm;codecs=vp8",
111
+ "video/webm",
112
+ "video/mp4"
113
+ ];
114
+ for (const mimeType of mimeTypes) {
115
+ if (MediaRecorder.isTypeSupported(mimeType)) {
116
+ return mimeType;
117
+ }
118
+ }
119
+ return "video/webm";
120
+ }
121
+ function isMediaRecorderSupported() {
122
+ return typeof MediaRecorder !== "undefined" && typeof HTMLCanvasElement !== "undefined" && typeof HTMLCanvasElement.prototype.captureStream === "function";
123
+ }
124
+ async function createMediaRecorderFallback(config, canvas) {
125
+ const encoder = new MediaRecorderFallback();
126
+ await encoder.configure(config, canvas);
127
+ return encoder;
128
+ }
129
+ export {
130
+ MediaRecorderFallback,
131
+ createMediaRecorderFallback,
132
+ isMediaRecorderSupported
133
+ };
@@ -0,0 +1,11 @@
1
+ import {
2
+ MediaRecorderFallback,
3
+ createMediaRecorderFallback,
4
+ isMediaRecorderSupported
5
+ } from "./chunk-5BH5YLM5.js";
6
+ import "./chunk-FPPKRKBX.js";
7
+ export {
8
+ MediaRecorderFallback,
9
+ createMediaRecorderFallback,
10
+ isMediaRecorderSupported
11
+ };
@@ -0,0 +1,171 @@
1
+ // src/core/video/web-encoder.ts
2
+ var WebCodecsEncoder = class {
3
+ encoder = null;
4
+ muxer = null;
5
+ config = null;
6
+ frameCount = 0;
7
+ totalFrames = 0;
8
+ startTime = 0;
9
+ fps = 30;
10
+ keyframeInterval = 150;
11
+ encoderError = null;
12
+ onProgress;
13
+ async configure(config) {
14
+ if (typeof VideoEncoder === "undefined") {
15
+ throw new Error("WebCodecs API not supported in this browser.");
16
+ }
17
+ this.config = config;
18
+ this.fps = config.fps;
19
+ this.totalFrames = Math.max(2, Math.round(config.duration * config.fps) + 1);
20
+ this.frameCount = 0;
21
+ this.startTime = Date.now();
22
+ this.keyframeInterval = Math.round(config.fps * 10);
23
+ this.encoderError = null;
24
+ const { Muxer, ArrayBufferTarget } = await import("mp4-muxer");
25
+ this.muxer = new Muxer({
26
+ target: new ArrayBufferTarget(),
27
+ video: {
28
+ codec: "avc",
29
+ width: config.width,
30
+ height: config.height
31
+ },
32
+ fastStart: "in-memory"
33
+ });
34
+ const candidates = getH264CodecCandidates(config.profile || "high");
35
+ let encoderConfig = null;
36
+ for (const codec of candidates) {
37
+ const candidate = {
38
+ codec,
39
+ width: config.width,
40
+ height: config.height,
41
+ bitrate: config.bitrate ?? 8e6,
42
+ framerate: config.fps,
43
+ hardwareAcceleration: config.hardwareAcceleration ?? "prefer-hardware",
44
+ latencyMode: "quality"
45
+ };
46
+ const support = await VideoEncoder.isConfigSupported(candidate);
47
+ if (support.supported) {
48
+ encoderConfig = candidate;
49
+ break;
50
+ }
51
+ }
52
+ if (!encoderConfig) {
53
+ throw new Error("H.264 encoding not supported. Tried codecs: " + candidates.join(", "));
54
+ }
55
+ this.encoder = new VideoEncoder({
56
+ output: (chunk, metadata) => {
57
+ this.muxer.addVideoChunk(chunk, metadata);
58
+ },
59
+ error: (e) => {
60
+ this.encoderError = e;
61
+ }
62
+ });
63
+ this.encoder.configure(encoderConfig);
64
+ }
65
+ async encodeFrame(frameData, frameIndex) {
66
+ if (this.encoderError) {
67
+ throw this.encoderError;
68
+ }
69
+ if (!this.encoder || !this.config) {
70
+ throw new Error("Encoder not configured. Call configure() first.");
71
+ }
72
+ const { width, height } = this.config;
73
+ const timestamp = Math.round(frameIndex * 1e6 / this.fps);
74
+ const pixelData = frameData instanceof ArrayBuffer ? new Uint8ClampedArray(frameData) : frameData;
75
+ const imageData = new ImageData(pixelData, width, height);
76
+ const videoFrame = new VideoFrame(imageData, { timestamp });
77
+ const isKeyFrame = frameIndex % this.keyframeInterval === 0;
78
+ this.encoder.encode(videoFrame, { keyFrame: isKeyFrame });
79
+ videoFrame.close();
80
+ this.frameCount++;
81
+ this.reportProgress();
82
+ }
83
+ async encodeCanvas(canvas, frameIndex) {
84
+ if (this.encoderError) {
85
+ throw this.encoderError;
86
+ }
87
+ if (!this.encoder || !this.config) {
88
+ throw new Error("Encoder not configured. Call configure() first.");
89
+ }
90
+ const timestamp = Math.round(frameIndex * 1e6 / this.fps);
91
+ const videoFrame = new VideoFrame(canvas, { timestamp });
92
+ const isKeyFrame = frameIndex % this.keyframeInterval === 0;
93
+ this.encoder.encode(videoFrame, { keyFrame: isKeyFrame });
94
+ videoFrame.close();
95
+ this.frameCount++;
96
+ this.reportProgress();
97
+ }
98
+ async encodeCanvasRepeat(canvas, startFrameIndex, repeatCount) {
99
+ if (this.encoderError) {
100
+ throw this.encoderError;
101
+ }
102
+ if (!this.encoder || !this.config) {
103
+ throw new Error("Encoder not configured. Call configure() first.");
104
+ }
105
+ for (let i = 0; i < repeatCount; i++) {
106
+ const actualFrameIndex = startFrameIndex + i;
107
+ const timestamp = Math.round(actualFrameIndex * 1e6 / this.fps);
108
+ const videoFrame = new VideoFrame(canvas, { timestamp });
109
+ const isKeyFrame = actualFrameIndex % this.keyframeInterval === 0;
110
+ this.encoder.encode(videoFrame, { keyFrame: isKeyFrame });
111
+ videoFrame.close();
112
+ this.frameCount++;
113
+ }
114
+ this.reportProgress();
115
+ }
116
+ async flush() {
117
+ if (this.encoderError) {
118
+ throw this.encoderError;
119
+ }
120
+ if (!this.encoder || !this.muxer) {
121
+ throw new Error("Encoder not configured.");
122
+ }
123
+ await this.encoder.flush();
124
+ this.muxer.finalize();
125
+ const buffer = this.muxer.target.buffer;
126
+ return new Blob([buffer], { type: "video/mp4" });
127
+ }
128
+ close() {
129
+ if (this.encoder && this.encoder.state !== "closed") {
130
+ this.encoder.close();
131
+ }
132
+ this.encoder = null;
133
+ this.muxer = null;
134
+ }
135
+ reportProgress() {
136
+ if (!this.onProgress) return;
137
+ const elapsedMs = Date.now() - this.startTime;
138
+ if (elapsedMs === 0) return;
139
+ const framesPerSecond = this.frameCount / (elapsedMs / 1e3);
140
+ const remainingFrames = this.totalFrames - this.frameCount;
141
+ const estimatedRemainingMs = remainingFrames / framesPerSecond * 1e3;
142
+ this.onProgress({
143
+ framesEncoded: this.frameCount,
144
+ totalFrames: this.totalFrames,
145
+ percentage: this.frameCount / this.totalFrames * 100,
146
+ elapsedMs,
147
+ estimatedRemainingMs: Math.round(estimatedRemainingMs),
148
+ currentFps: Math.round(framesPerSecond * 10) / 10
149
+ });
150
+ }
151
+ };
152
+ function getH264CodecCandidates(profile) {
153
+ switch (profile) {
154
+ case "baseline":
155
+ return ["avc1.42E028", "avc1.42001F", "avc1.42001E"];
156
+ case "main":
157
+ return ["avc1.4D0028", "avc1.4D001F", "avc1.4D001E"];
158
+ case "high":
159
+ default:
160
+ return ["avc1.640028", "avc1.640029", "avc1.64001F", "avc1.64001E"];
161
+ }
162
+ }
163
+ async function createWebCodecsEncoder(config) {
164
+ const encoder = new WebCodecsEncoder();
165
+ await encoder.configure(config);
166
+ return encoder;
167
+ }
168
+ export {
169
+ WebCodecsEncoder,
170
+ createWebCodecsEncoder
171
+ };
@@ -0,0 +1,9 @@
1
+ import {
2
+ WebCodecsEncoder,
3
+ createWebCodecsEncoder
4
+ } from "./chunk-KBAXJEJG.js";
5
+ import "./chunk-FPPKRKBX.js";
6
+ export {
7
+ WebCodecsEncoder,
8
+ createWebCodecsEncoder
9
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shotstack/shotstack-canvas",
3
- "version": "1.9.6",
3
+ "version": "2.0.1",
4
4
  "description": "Text layout & animation engine (HarfBuzz) for Node & Web - fully self-contained.",
5
5
  "type": "module",
6
6
  "main": "./dist/entry.node.cjs",
@@ -31,6 +31,7 @@
31
31
  "example:node": "node examples/node-example.mjs",
32
32
  "example:video": "node examples/node-video.mjs",
33
33
  "example:web": "vite dev examples/web-example",
34
+ "test:caption-web": "vite dev examples/caption-tests",
34
35
  "prepublishOnly": "npm run build"
35
36
  },
36
37
  "publishConfig": {
@@ -44,18 +45,17 @@
44
45
  "dependencies": {
45
46
  "@resvg/resvg-js": "^2.6.2",
46
47
  "@resvg/resvg-wasm": "^2.6.2",
47
- "@shotstack/schemas": "^1.5.4",
48
+ "@shotstack/schemas": "1.6.0",
48
49
  "canvas": "npm:@napi-rs/canvas@^0.1.54",
49
50
  "ffmpeg-static": "^5.2.0",
50
51
  "fontkit": "^2.0.4",
51
52
  "harfbuzzjs": "0.4.12",
52
- "opentype.js": "^1.3.4",
53
+ "lru-cache": "^11.2.5",
54
+ "mp4-muxer": "^5.1.3",
53
55
  "zod": "^4.2.0"
54
56
  },
55
57
  "devDependencies": {
56
- "@types/fluent-ffmpeg": "2.1.27",
57
58
  "@types/node": "^20.14.10",
58
- "fluent-ffmpeg": "^2.1.3",
59
59
  "tsup": "^8.2.3",
60
60
  "typescript": "^5.5.3",
61
61
  "vite": "^5.3.3",
@@ -1,58 +1,58 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * Postinstall script to verify native canvas bindings are available
5
- * This helps catch issues early and provides helpful guidance
6
- */
7
-
8
- import { platform as _platform, arch as _arch } from 'os';
9
- import { dirname } from 'path';
10
- import { readdirSync } from 'fs';
11
- import { createRequire } from 'module';
12
-
13
- const require = createRequire(import.meta.url);
14
-
15
- const platform = _platform();
16
- const arch = _arch();
17
-
18
- // Map platform/arch to package names
19
- const platformMap = {
20
- 'darwin-arm64': '@napi-rs/canvas-darwin-arm64',
21
- 'darwin-x64': '@napi-rs/canvas-darwin-x64',
22
- 'linux-arm64': '@napi-rs/canvas-linux-arm64-gnu',
23
- 'linux-x64': '@napi-rs/canvas-linux-x64-gnu',
24
- 'win32-x64': '@napi-rs/canvas-win32-x64-msvc',
25
- 'linux-arm': '@napi-rs/canvas-linux-arm-gnueabihf',
26
- 'android-arm64': '@napi-rs/canvas-android-arm64',
27
- };
28
-
29
- const platformKey = `${platform}-${arch}`;
30
- const requiredPackage = platformMap[platformKey];
31
-
32
- if (!requiredPackage) {
33
- console.warn(`\n⚠️ Warning: Unsupported platform ${platformKey} for @napi-rs/canvas`);
34
- console.warn(' Canvas rendering may not work on this platform.\n');
35
- process.exit(0);
36
- }
37
-
38
- // Check if the native binding package is installed
39
- try {
40
- const packagePath = require.resolve(`${requiredPackage}/package.json`);
41
- const packageDir = dirname(packagePath);
42
-
43
- // Verify the .node file exists
44
- const nodeFiles = readdirSync(packageDir).filter(f => f.endsWith('.node'));
45
-
46
- if (nodeFiles.length > 0) {
47
- console.log(`✅ @shotstack/shotstack-canvas: Native canvas binding found for ${platformKey}`);
48
- } else {
49
- throw new Error('No .node file found');
50
- }
51
- } catch (error) {
52
- console.warn(`\n⚠️ Warning: Native canvas binding not found for ${platformKey}`);
53
- console.warn(` Expected package: ${requiredPackage}`);
54
- console.warn('\n If you see "Cannot find native binding" errors, try:');
55
- console.warn(' 1. Delete node_modules and package-lock.json');
56
- console.warn(' 2. Run: npm install');
57
- console.warn(` 3. Or manually install: npm install ${requiredPackage}\n`);
58
- }
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Postinstall script to verify native canvas bindings are available
5
+ * This helps catch issues early and provides helpful guidance
6
+ */
7
+
8
+ import { platform as _platform, arch as _arch } from 'os';
9
+ import { dirname } from 'path';
10
+ import { readdirSync } from 'fs';
11
+ import { createRequire } from 'module';
12
+
13
+ const require = createRequire(import.meta.url);
14
+
15
+ const platform = _platform();
16
+ const arch = _arch();
17
+
18
+ // Map platform/arch to package names
19
+ const platformMap = {
20
+ 'darwin-arm64': '@napi-rs/canvas-darwin-arm64',
21
+ 'darwin-x64': '@napi-rs/canvas-darwin-x64',
22
+ 'linux-arm64': '@napi-rs/canvas-linux-arm64-gnu',
23
+ 'linux-x64': '@napi-rs/canvas-linux-x64-gnu',
24
+ 'win32-x64': '@napi-rs/canvas-win32-x64-msvc',
25
+ 'linux-arm': '@napi-rs/canvas-linux-arm-gnueabihf',
26
+ 'android-arm64': '@napi-rs/canvas-android-arm64',
27
+ };
28
+
29
+ const platformKey = `${platform}-${arch}`;
30
+ const requiredPackage = platformMap[platformKey];
31
+
32
+ if (!requiredPackage) {
33
+ console.warn(`\n⚠️ Warning: Unsupported platform ${platformKey} for @napi-rs/canvas`);
34
+ console.warn(' Canvas rendering may not work on this platform.\n');
35
+ process.exit(0);
36
+ }
37
+
38
+ // Check if the native binding package is installed
39
+ try {
40
+ const packagePath = require.resolve(`${requiredPackage}/package.json`);
41
+ const packageDir = dirname(packagePath);
42
+
43
+ // Verify the .node file exists
44
+ const nodeFiles = readdirSync(packageDir).filter(f => f.endsWith('.node'));
45
+
46
+ if (nodeFiles.length > 0) {
47
+ console.log(`✅ @shotstack/shotstack-canvas: Native canvas binding found for ${platformKey}`);
48
+ } else {
49
+ throw new Error('No .node file found');
50
+ }
51
+ } catch (error) {
52
+ console.warn(`\n⚠️ Warning: Native canvas binding not found for ${platformKey}`);
53
+ console.warn(` Expected package: ${requiredPackage}`);
54
+ console.warn('\n If you see "Cannot find native binding" errors, try:');
55
+ console.warn(' 1. Delete node_modules and package-lock.json');
56
+ console.warn(' 2. Run: npm install');
57
+ console.warn(` 3. Or manually install: npm install ${requiredPackage}\n`);
58
+ }
@@ -1,19 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
5
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
6
- }) : x)(function(x) {
7
- if (typeof require !== "undefined") return require.apply(this, arguments);
8
- throw Error('Dynamic require of "' + x + '" is not supported');
9
- });
10
- var __commonJS = (cb, mod) => function __require2() {
11
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
12
- };
13
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
14
-
15
- export {
16
- __require,
17
- __commonJS,
18
- __publicField
19
- };