@gehdoc/svg-to-video 0.29.5 → 0.31.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/README.md CHANGED
@@ -60,7 +60,7 @@ Explore our **[Visual Gallery (Storybook)](https://gehdoc.github.io/svg-to-video
60
60
  ### Quick Start
61
61
 
62
62
  1. Open the [Web Studio](https://gehdoc.github.io/svg-to-video/).
63
- 2. Drag and drop your `.svg` file.
63
+ 2. Drag and drop your `.svg` file, or test the engine instantly with 1-click built-in samples.
64
64
  3. Adjust resolution, duration, and FPS.
65
65
  4. Select your format, toggle **Transparent Background** if needed, and ensure **High-Fidelity Capture** is enabled for best results.
66
66
  5. Click **Export**.
@@ -83,7 +83,7 @@ npx -y -p @gehdoc/svg-to-video svg-to-video input.svg 60 ./out-dir
83
83
  npx -y -p @gehdoc/svg-to-video svg-to-video input.svg 60 ./out-dir -d 5 --format gif --transparent
84
84
 
85
85
  # Node.js (custom resolution dimensions e.g. vertical 1080x1920)
86
- npx -y -p @gehdoc/svg-to-video svg-to-video input.svg 60 ./out-dir --width 1080 --height 1920
86
+ npx -y -p @gehdoc/svg-to-video svg-to-video input.svg 60 ./out-dir --resolution 1080x1920
87
87
 
88
88
  # Node.js (animated PNG output)
89
89
  npx -y -p @gehdoc/svg-to-video svg-to-video input.svg 60 ./out-dir -d 5 --format apng
@@ -151,6 +151,12 @@ The tool works by isolating the SVG, scrubbing the Web Animations API, and captu
151
151
 
152
152
  ---
153
153
 
154
+ ## ❓ FAQ
155
+
156
+ Common questions about privacy, how frame scrubbing works, CI/CD automation, and transparency support are answered in **[docs/FAQ.md](./docs/FAQ.md)**.
157
+
158
+ ---
159
+
154
160
  ## 🤝 Contributing
155
161
 
156
162
  Contributions are welcome! This project follows a **Spec-Driven Development (SDD)** workflow to ensure clear requirements and high quality. Please open an issue or pull request.
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Composites an image onto a 2D canvas context, handling background colors and color keying.
3
+ *
4
+ * When `needsColorKeying` is true (e.g. for transparent GIF exports):
5
+ * - The canvas background remains transparent.
6
+ * - Semi-transparent anti-aliased edge pixels are keyed against `backgroundColor`
7
+ * using 'source-in' + 'source-over' compositing to prevent halos.
8
+ *
9
+ * When `needsColorKeying` is false:
10
+ * - If `backgroundColor` is provided, fills the canvas with that solid background.
11
+ * - Draws the image source on top.
12
+ */
13
+ export function compositeFrame(ctx, source, width, height, backgroundColor, needsColorKeying) {
14
+ ctx.clearRect(0, 0, width, height);
15
+ if (backgroundColor) {
16
+ if (needsColorKeying) {
17
+ ctx.drawImage(source, 0, 0, width, height);
18
+ ctx.globalCompositeOperation = 'source-in';
19
+ }
20
+ ctx.fillStyle = backgroundColor;
21
+ ctx.fillRect(0, 0, width, height);
22
+ ctx.globalCompositeOperation = 'source-over';
23
+ }
24
+ ctx.drawImage(source, 0, 0, width, height);
25
+ }
@@ -7,6 +7,7 @@ export class ApngFormatGenerator {
7
7
  extensions = ['.apng', '.png'];
8
8
  mimeType = 'image/png';
9
9
  supportsAlpha = true;
10
+ needsColorKeying = false;
10
11
  buildFfmpegArgs(options) {
11
12
  const { fps, hold, outDir, transparent, metadata, inputPattern, pkgVersion, outputFileName, } = options;
12
13
  const args = [
@@ -7,6 +7,7 @@ export class GifFormatGenerator {
7
7
  extensions = ['.gif'];
8
8
  mimeType = 'image/gif';
9
9
  supportsAlpha = true;
10
+ needsColorKeying = true;
10
11
  buildFfmpegArgs(options) {
11
12
  const { fps, hold, outDir, transparent, metadata, inputPattern, pkgVersion, outputFileName, } = options;
12
13
  const args = [
@@ -5,6 +5,7 @@ export class MkvFormatGenerator {
5
5
  extensions = ['.mkv'];
6
6
  mimeType = 'video/x-matroska';
7
7
  supportsAlpha = true;
8
+ needsColorKeying = false;
8
9
  buildFfmpegArgs(options) {
9
10
  const { fps, hold, outDir, transparent, metadata, inputPattern, pkgVersion, outputFileName, } = options;
10
11
  const args = [
@@ -5,6 +5,7 @@ export class MovFormatGenerator {
5
5
  extensions = ['.mov'];
6
6
  mimeType = 'video/quicktime';
7
7
  supportsAlpha = true;
8
+ needsColorKeying = false;
8
9
  buildFfmpegArgs(options) {
9
10
  const { fps, hold, outDir, transparent, metadata, inputPattern, pkgVersion, outputFileName, } = options;
10
11
  const args = [
@@ -5,6 +5,7 @@ export class Mp4FormatGenerator {
5
5
  extensions = ['.mp4'];
6
6
  mimeType = 'video/mp4';
7
7
  supportsAlpha = false;
8
+ needsColorKeying = false;
8
9
  buildFfmpegArgs(options) {
9
10
  const { fps, hold, outDir, metadata, inputPattern, pkgVersion, outputFileName, } = options;
10
11
  const args = [
@@ -5,6 +5,7 @@ export class WebmFormatGenerator {
5
5
  extensions = ['.webm'];
6
6
  mimeType = 'video/webm';
7
7
  supportsAlpha = true;
8
+ needsColorKeying = false;
8
9
  buildFfmpegArgs(options) {
9
10
  const { fps, hold, outDir, transparent, metadata, inputPattern, pkgVersion, outputFileName, } = options;
10
11
  const args = [
package/dist/src/index.js CHANGED
@@ -5,6 +5,7 @@ import puppeteer from 'puppeteer';
5
5
  import { Command } from 'commander';
6
6
  import path from 'path';
7
7
  import { seekAnimations } from '#shared/animation-engine.js';
8
+ import { compositeFrame } from '#shared/canvasCompositing.js';
8
9
  import { validateOptions } from './utils/validateOptions.js';
9
10
  import { analyzeSvgAnimation, parseSvgDimensions, calculateAspectRatio, } from '#shared/analyzeSvgAnimation.js';
10
11
  import { formatRegistry } from './formats/registry.js';
@@ -39,12 +40,10 @@ Resources:
39
40
  }, 0)
40
41
  .option('--keep-frames', 'keep temporary frames after creating video', false)
41
42
  .option('-f, --force', 'overwrite existing output files without asking', false)
42
- .option('--resolution <preset>', 'resolution preset (720p, 1080p, original) or custom dimensions (e.g. 1080x1080)', 'original')
43
+ .option('--resolution <preset>', 'resolution preset (720p, 1080p, original) or custom dimensions (e.g. 1080x1080, 1080x1920)', 'original')
43
44
  .option('--scale <number>', 'scale factor for original resolution (1-4)', (v) => parseFloat(v), 1)
44
- .option('-w, --width <pixels>', 'custom width in pixels', (v) => parseInt(v, 10))
45
- .option('-H, --height <pixels>', 'custom height in pixels', (v) => parseInt(v, 10))
46
45
  .option('--transparent', 'render with a transparent background', false)
47
- .option('--bg-color <hex>', 'background color for the video (e.g., #FFFFFF)', '#ffffff')
46
+ .option('--bg-color <hex>', 'background color for the video (e.g., #FFFFFF)')
48
47
  .option('--metadata <items...>', 'metadata tags (e.g., --metadata title="My Video" author="Me")')
49
48
  .option('--format <format>', `output format: ${formatRegistry.getSupportedFormatNames().join(', ')}`)
50
49
  .option('-q, --quiet', 'suppress interactive progress output', false)
@@ -69,7 +68,7 @@ async function run(svgPath, fps, outDir, options) {
69
68
  homepage: pkg.homepage,
70
69
  });
71
70
  // Resolve format generator and output file extension via format registry
72
- const { format, extension } = formatRegistry.resolveFormatAndExtension(options.format, options.transparent);
71
+ const { generator, format, extension } = formatRegistry.resolveFormatAndExtension(options.format, options.transparent);
73
72
  const inputBasename = path.basename(svgPath, path.extname(svgPath));
74
73
  const ext = extension.startsWith('.') ? extension : `.${extension}`;
75
74
  const outputFileName = `${inputBasename}${ext}`;
@@ -151,7 +150,7 @@ async function run(svgPath, fps, outDir, options) {
151
150
  process.once('SIGTERM', sigtermListener);
152
151
  try {
153
152
  fs.mkdirSync(outDir, { recursive: true });
154
- await createFrames(svg, parsedDim, fps, totalFrames, padWidth, outDir, puppeteerArgs, options.resolution, options.scale, options.width, options.height, options.transparent, options.bgColor, logger);
153
+ await createFrames(svg, parsedDim, fps, totalFrames, padWidth, outDir, puppeteerArgs, options.resolution, options.scale, options.transparent, options.bgColor, generator.needsColorKeying, logger);
155
154
  convertToOutput(outputFileName, format, fps, padWidth, options.hold, outDir, options.transparent, options.metadata, logger);
156
155
  if (!options.keepFrames) {
157
156
  cleanupFrames(totalFrames, padWidth, outDir, logger);
@@ -190,26 +189,11 @@ async function run(svgPath, fps, outDir, options) {
190
189
  /**
191
190
  * create frame images by rendering the SVG in a headless browser and advancing the animation to the correct timestamp for each frame
192
191
  */
193
- async function createFrames(svg, parsedDim, fps, totalFrames, padWidth, outDir, puppeteerArgs, resolutionPreset, scaleFactor, customWidth, customHeight, transparent, bgColor, logger) {
192
+ async function createFrames(svg, parsedDim, fps, totalFrames, padWidth, outDir, puppeteerArgs, resolutionPreset, scaleFactor, transparent, bgColor, needsColorKeying, logger) {
194
193
  logger.info('📸 Rendering frames with Puppeteer...');
195
- let width = 0;
196
- let height = 0;
197
- const svgAspect = parsedDim.height > 0 ? parsedDim.width / parsedDim.height : 16 / 9;
198
- if (customWidth !== undefined || customHeight !== undefined) {
199
- if (customWidth !== undefined && customHeight !== undefined) {
200
- width = customWidth;
201
- height = customHeight;
202
- }
203
- else if (customWidth !== undefined) {
204
- width = customWidth;
205
- height = Math.round(customWidth / svgAspect);
206
- }
207
- else if (customHeight !== undefined) {
208
- height = customHeight;
209
- width = Math.round(customHeight * svgAspect);
210
- }
211
- }
212
- else if (/^\d+x\d+$/i.test(resolutionPreset)) {
194
+ let width;
195
+ let height;
196
+ if (/^\d+x\d+$/i.test(resolutionPreset)) {
213
197
  const [wStr, hStr] = resolutionPreset.toLowerCase().split('x');
214
198
  width = parseInt(wStr, 10);
215
199
  height = parseInt(hStr, 10);
@@ -230,7 +214,7 @@ async function createFrames(svg, parsedDim, fps, totalFrames, padWidth, outDir,
230
214
  height = Math.round(parsedDim.height * scaleFactor);
231
215
  }
232
216
  else {
233
- throw new Error(`Invalid resolution preset: ${resolutionPreset}. Expected '1080p', '720p', 'original', or custom dimensions.`);
217
+ throw new Error(`Invalid resolution preset: ${resolutionPreset}. Expected '1080p', '720p', 'original', or custom dimensions (e.g. 1080x1080).`);
234
218
  }
235
219
  logger.info(` Viewport: ${width}x${height}`);
236
220
  logger.info('🚀 Preparing Puppeteer browser...');
@@ -275,16 +259,42 @@ async function createFrames(svg, parsedDim, fps, totalFrames, padWidth, outDir,
275
259
  const screenshotOptions = {
276
260
  omitBackground: transparent,
277
261
  };
262
+ const shouldKey = Boolean(transparent && bgColor && needsColorKeying);
278
263
  logger.info('📸 Rendering frames with Puppeteer...');
279
264
  for (let frame = 1; frame <= totalFrames; ++frame) {
280
265
  logger.writeProgress(`\r📸 Rendering frame ${frame}/${totalFrames}`);
281
266
  const timeMs = ((frame - 1) / fps) * 1000;
282
267
  await page.evaluate(seekAnimations, timeMs);
283
268
  const filename = path.join(outDir, getFrameFilename(frame, padWidth));
284
- await page.screenshot({
285
- path: filename,
286
- ...screenshotOptions,
287
- });
269
+ if (shouldKey) {
270
+ const rawScreenshotBuffer = await page.screenshot(screenshotOptions);
271
+ const b64Input = Buffer.from(rawScreenshotBuffer).toString('base64');
272
+ const keyedBase64 = await page.evaluate(async (compositeFnStr, b64, bg, w, h) => {
273
+ let canvas = document.getElementById('matte-canvas');
274
+ if (!canvas) {
275
+ canvas = document.createElement('canvas');
276
+ canvas.id = 'matte-canvas';
277
+ canvas.width = w;
278
+ canvas.height = h;
279
+ canvas.style.display = 'none';
280
+ document.body.appendChild(canvas);
281
+ }
282
+ const ctx = canvas.getContext('2d');
283
+ const img = new Image();
284
+ img.src = 'data:image/png;base64,' + b64;
285
+ await img.decode();
286
+ const compositeFn = new Function('return ' + compositeFnStr)();
287
+ compositeFn(ctx, img, w, h, bg, true);
288
+ return canvas.toDataURL('image/png').split(',')[1];
289
+ }, compositeFrame.toString(), b64Input, bgColor, width, height);
290
+ fs.writeFileSync(filename, Buffer.from(keyedBase64, 'base64'));
291
+ }
292
+ else {
293
+ await page.screenshot({
294
+ path: filename,
295
+ ...screenshotOptions,
296
+ });
297
+ }
288
298
  }
289
299
  logger.info('');
290
300
  await browser.close();
package/dist/src/mcp.js CHANGED
@@ -93,7 +93,7 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
93
93
  },
94
94
  resolution: {
95
95
  type: 'string',
96
- description: 'Resolution preset (original, 1080p, 720p) or formatted string (e.g. 1080x1080, 1080x1920). Default: original.',
96
+ description: 'Resolution preset (original, 1080p, 720p) or formatted dimension string (e.g. 1080x1080, 1080x1920). Default: original.',
97
97
  default: 'original',
98
98
  },
99
99
  scale: {
@@ -101,17 +101,9 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
101
101
  description: 'Scale factor (1-4) when using original resolution. Default: 1.',
102
102
  default: 1,
103
103
  },
104
- width: {
105
- type: 'number',
106
- description: 'Custom output video width in pixels.',
107
- },
108
- height: {
109
- type: 'number',
110
- description: 'Custom output video height in pixels.',
111
- },
112
104
  bgColor: {
113
105
  type: 'string',
114
- description: 'Background color hex code (e.g. #ffffff). Cannot be used with transparent.',
106
+ description: 'Background color hex code (e.g. #ffffff). When transparent is true, acts as a keying/matting color for formats requiring color keying (e.g. gif).',
115
107
  },
116
108
  hold: {
117
109
  type: 'number',
@@ -284,12 +276,6 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
284
276
  if (params.scale) {
285
277
  cliArgs.push('--scale', String(params.scale));
286
278
  }
287
- if (params.width) {
288
- cliArgs.push('--width', String(params.width));
289
- }
290
- if (params.height) {
291
- cliArgs.push('--height', String(params.height));
292
- }
293
279
  if (params.bgColor) {
294
280
  cliArgs.push('--bg-color', params.bgColor);
295
281
  }
@@ -4,25 +4,11 @@ export function validateOptions(options) {
4
4
  if (options.duration !== undefined && options.duration <= 0) {
5
5
  throw new Error('Duration must be a positive number.');
6
6
  }
7
- if (options.width !== undefined &&
8
- (isNaN(options.width) || options.width <= 0)) {
9
- throw new Error('Width must be a positive number.');
10
- }
11
- if (options.width !== undefined && options.width > MAX_DIMENSION_PIXELS) {
12
- throw new Error(`Width exceeds maximum supported limit of ${MAX_DIMENSION_PIXELS} pixels.`);
13
- }
14
- if (options.height !== undefined &&
15
- (isNaN(options.height) || options.height <= 0)) {
16
- throw new Error('Height must be a positive number.');
17
- }
18
- if (options.height !== undefined && options.height > MAX_DIMENSION_PIXELS) {
19
- throw new Error(`Height exceeds maximum supported limit of ${MAX_DIMENSION_PIXELS} pixels.`);
20
- }
21
7
  const isPreset = ['original', '1080p', '720p'].includes(options.resolution);
22
8
  const resMatch = /^(\d+)x(\d+)$/i.exec(options.resolution);
23
9
  if (!isPreset) {
24
10
  if (!resMatch) {
25
- throw new Error(`Invalid resolution option "${options.resolution}". Expected 'original', '1080p', '720p', or a custom dimension string like '1080x1080'.`);
11
+ throw new Error(`Invalid resolution option "${options.resolution}". Expected 'original', '1080p', '720p', or a dimension string like '1080x1080'.`);
26
12
  }
27
13
  const resW = parseInt(resMatch[1], 10);
28
14
  const resH = parseInt(resMatch[2], 10);
@@ -32,21 +18,21 @@ export function validateOptions(options) {
32
18
  if (resW > MAX_DIMENSION_PIXELS || resH > MAX_DIMENSION_PIXELS) {
33
19
  throw new Error(`Custom resolution dimensions must not exceed ${MAX_DIMENSION_PIXELS} pixels.`);
34
20
  }
35
- if (options.width !== undefined || options.height !== undefined) {
36
- throw new Error('--width and --height cannot be used when a custom resolution string (e.g. 1080x1080) is provided.');
37
- }
38
21
  }
39
- if (options.scale !== 1 &&
40
- (options.resolution !== 'original' ||
41
- options.width !== undefined ||
42
- options.height !== undefined)) {
43
- throw new Error('--scale can only be used with --resolution original and without custom width or height options.');
44
- }
45
- if (options.transparent && options.bgColor !== '#ffffff') {
46
- throw new Error('--transparent and --bg-color cannot be used together.');
22
+ if (options.scale !== 1 && options.resolution !== 'original') {
23
+ throw new Error('--scale can only be used with --resolution original.');
47
24
  }
48
25
  if (options.format && !formatRegistry.isSupported(options.format)) {
49
26
  const supported = formatRegistry.getSupportedFormatNames().join(', ');
50
27
  throw new Error(`Invalid format "${options.format}". Supported formats are: ${supported}.`);
51
28
  }
29
+ const { generator, format: resolvedFormat } = formatRegistry.resolveFormatAndExtension(options.format, options.transparent);
30
+ if (options.transparent) {
31
+ if (!generator.supportsAlpha) {
32
+ throw new Error(`Format "${resolvedFormat}" does not support transparency.`);
33
+ }
34
+ if (options.bgColor && !generator.needsColorKeying) {
35
+ throw new Error(`--transparent and --bg-color cannot be used together for format "${resolvedFormat}".`);
36
+ }
37
+ }
52
38
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@gehdoc/svg-to-video",
3
3
  "mcpName": "io.github.GehDoc/svg-to-video",
4
- "version": "0.29.5",
4
+ "version": "0.31.0",
5
5
  "type": "module",
6
6
  "description": "Professional animated SVG to Video (MP4/WebM/MKV/MOV) and Animated Image (aPNG/GIF) converter featuring frame-accurate rendering, CLI automation, Model Context Protocol (MCP) server integration, and a serverless Web Studio.",
7
7
  "imports": {
@@ -17,7 +17,7 @@ This skill enables AI agents to render animated vector graphics (SVGs with CSS a
17
17
  1. **Format Export**: Converts SVGs into `mp4`, `webm`, `gif`, `apng`, `mkv`, and `mov`.
18
18
  2. **Transparent Backgrounds**: Supports full alpha-channel transparency for `webm`, `gif`, `apng`, and `mov`.
19
19
  3. **Auto-Duration Detection**: Automatically detects CSS keyframe and animation loop durations if not specified.
20
- 4. **Resolution Presets & Custom Dimensions**: Supports `original`, `1080p`, `720p`, custom scaling factors (1x-4x), explicit `--width` and `--height` parameters (e.g. 1080x1920), or formatted resolution strings (e.g., `1080x1080`).
20
+ 4. **Resolution Presets & Custom Dimensions**: Supports `original`, `1080p`, `720p`, custom scaling factors (1x-4x), or formatted resolution strings (e.g., `WIDTHxHEIGHT` like `1080x1920`, `1080x1080`).
21
21
 
22
22
  ## Usage Guidelines for AI Agents
23
23
 
@@ -26,12 +26,12 @@ When asked to generate a video or GIF from an SVG animation:
26
26
  1. **Option A: Via MCP Tools (Recommended)**:
27
27
  - Call `render_svg_to_video` directly passing either `svgContent` (raw XML string) or `svgFilePath`.
28
28
  - Set `transparent: true` and `format: "webm"` or `format: "gif"` if a transparent overlay is requested.
29
- - Set `width` and `height` parameters or custom `resolution: "1080x1920"` for specific video aspect ratios (e.g. square 1080x1080, vertical 1080x1920).
29
+ - Set custom `resolution: "1080x1920"` for specific video aspect ratios (e.g. square 1080x1080, vertical 1080x1920).
30
30
 
31
31
  2. **Option B: Via CLI Command**:
32
32
 
33
33
  ```bash
34
- npx -y -p @gehdoc/svg-to-video svg-to-video input.svg 60 ./out-dir -d 5 --width 1080 --height 1920 --format webm --transparent --json
34
+ npx -y -p @gehdoc/svg-to-video svg-to-video input.svg 60 ./out-dir -d 5 --resolution 1080x1920 --format webm --transparent --json
35
35
  ```
36
36
 
37
37
  3. **Option C: Via Docker**: