@gehdoc/svg-to-video 0.32.1 → 0.34.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
@@ -13,7 +13,7 @@
13
13
  [![HuggingFace Space](https://img.shields.io/badge/%F0%9F%A4%97%20HuggingFace-Demo%20Space-yellow?style=flat)](https://huggingface.co/spaces/GehDoc/svg-to-video-mcp)
14
14
  [![llms.txt](https://img.shields.io/badge/llms.txt-available-blue)](https://gehdoc.github.io/svg-to-video/llms.txt)
15
15
 
16
- A high-fidelity tool to transform your CSS-animated SVGs into high-quality videos (MP4, WebM, MKV, MOV) or lightweight animated formats (aPNG, GIF) with perfect alpha-channel transparency directly in your browser or via CLI/MCP server.
16
+ A high-fidelity tool to transform your CSS- and SMIL-animated SVGs into high-quality videos (MP4, WebM, MKV, MOV) or lightweight animated formats (aPNG, GIF) with perfect alpha-channel transparency directly in your browser or via CLI/MCP server.
17
17
 
18
18
  <div align="center">
19
19
  <a href="https://gehdoc.github.io/svg-to-video/"><img src="https://gehdoc.github.io/svg-to-video/assets/demo.gif" width="800" alt="SVG to Video Demo"></a>
@@ -26,7 +26,7 @@ A high-fidelity tool to transform your CSS-animated SVGs into high-quality video
26
26
 
27
27
  - **Transparent Backgrounds**: Export your animations with a full alpha channel using **WebM or aPNG**, and optimized indexed transparency with **GIF89a**. Perfect for overlays in video editing tools or web use.
28
28
  - **Privacy-First**: The Web Studio runs entirely in your browser—your SVG files never leave your computer.
29
- - **Frame-Accurate**: Our engine scrubs the **Web Animations API**, ensuring every frame is captured exactly as rendered.
29
+ - **Frame-Accurate**: Our engine scrubs both the **Web Animations API** and native **SVG SMIL**, ensuring every frame is captured exactly as rendered.
30
30
  - **AI Agent Native**: Native **Model Context Protocol (MCP)** server and **Agent Skill (`SKILL.md`)** support indexed on the official [MCP Registry](https://registry.modelcontextprotocol.io/) (`mcp.json`) and hosted live on [HuggingFace Spaces](https://huggingface.co/spaces/GehDoc/svg-to-video-mcp).
31
31
  - **Universal Animated Formats**: Beyond video, generate lightweight **Animated PNGs (aPNG)** and **GIFs** perfect for documentation, Slack, or GitHub, with full control over background transparency.
32
32
  - **Copy to Clipboard**: Instant export to **Base64 Data URL**—copy your video and embed it directly into your HTML, CSS, or JS code without manual downloads. Perfect for rapid prototyping and developers.
@@ -55,7 +55,7 @@ Our **Web Studio** is a serverless, client-side rendering tool. It runs entirely
55
55
 
56
56
  > **Privacy Note**: We use [Umami Analytics](https://umami.is/) to collect anonymous usage data across our Web Studio, CLI, and MCP server interfaces (e.g., number of conversions and format usage) to help us improve the tool. This tracking is cookie-less, respects standard "Do Not Track" settings (set the `DO_NOT_TRACK=1` environment variable to opt out), and never collects personal information or SVG contents. See **[docs/ANALYTICS.md](./docs/ANALYTICS.md)** for details.
57
57
 
58
- Explore our **[Visual Gallery (Storybook)](https://gehdoc.github.io/svg-to-video/storybook/)** to see how the engine handles complex CSS and fonts.
58
+ Explore our **[Visual Gallery (Storybook)](https://gehdoc.github.io/svg-to-video/storybook/)** to see how the engine handles complex CSS, SMIL, and fonts.
59
59
 
60
60
  ### Quick Start
61
61
 
@@ -147,7 +147,7 @@ docker pull gehdoc/svg-to-video:latest
147
147
 
148
148
  For a deep dive into the rendering engine, algorithms, and infrastructure, see [docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md).
149
149
 
150
- The tool works by isolating the SVG, scrubbing the Web Animations API, and capturing frames via WebCodecs or FFmpeg.
150
+ The tool works by isolating the SVG, scrubbing both the Web Animations API and native SVG SMIL DOM, and capturing frames via WebCodecs or FFmpeg.
151
151
 
152
152
  ---
153
153
 
@@ -9,16 +9,11 @@ export class ApngFormatGenerator extends BaseCLIFormatGenerator {
9
9
  }
10
10
  buildFfmpegArgs(options) {
11
11
  const { fps, hold, outDir, transparent, metadata, inputPattern, pkgVersion, outputFileName, } = options;
12
- const args = [
13
- '-hide_banner',
14
- '-loglevel',
15
- 'warning',
16
- '-y',
17
- '-framerate',
18
- String(fps),
19
- '-i',
20
- inputPattern,
21
- ];
12
+ const args = ['-hide_banner', '-loglevel', 'warning', '-y'];
13
+ if (inputPattern === 'pipe:0' || inputPattern.startsWith('pipe:')) {
14
+ args.push('-f', 'image2pipe');
15
+ }
16
+ args.push('-framerate', String(fps), '-i', inputPattern);
22
17
  let userComment;
23
18
  if (metadata) {
24
19
  metadata.forEach((m) => {
@@ -9,16 +9,11 @@ export class GifFormatGenerator extends BaseCLIFormatGenerator {
9
9
  }
10
10
  buildFfmpegArgs(options) {
11
11
  const { fps, hold, outDir, transparent, metadata, inputPattern, pkgVersion, outputFileName, } = options;
12
- const args = [
13
- '-hide_banner',
14
- '-loglevel',
15
- 'warning',
16
- '-y',
17
- '-framerate',
18
- String(fps),
19
- '-i',
20
- inputPattern,
21
- ];
12
+ const args = ['-hide_banner', '-loglevel', 'warning', '-y'];
13
+ if (inputPattern === 'pipe:0' || inputPattern.startsWith('pipe:')) {
14
+ args.push('-f', 'image2pipe');
15
+ }
16
+ args.push('-framerate', String(fps), '-i', inputPattern);
22
17
  let userComment;
23
18
  let title;
24
19
  if (metadata) {
@@ -7,16 +7,11 @@ export class MkvFormatGenerator extends BaseCLIFormatGenerator {
7
7
  }
8
8
  buildFfmpegArgs(options) {
9
9
  const { fps, hold, outDir, transparent, metadata, inputPattern, pkgVersion, outputFileName, } = options;
10
- const args = [
11
- '-hide_banner',
12
- '-loglevel',
13
- 'warning',
14
- '-y',
15
- '-framerate',
16
- String(fps),
17
- '-i',
18
- inputPattern,
19
- ];
10
+ const args = ['-hide_banner', '-loglevel', 'warning', '-y'];
11
+ if (inputPattern === 'pipe:0' || inputPattern.startsWith('pipe:')) {
12
+ args.push('-f', 'image2pipe');
13
+ }
14
+ args.push('-framerate', String(fps), '-i', inputPattern);
20
15
  let userComment;
21
16
  if (metadata) {
22
17
  metadata.forEach((m) => {
@@ -7,16 +7,11 @@ export class MovFormatGenerator extends BaseCLIFormatGenerator {
7
7
  }
8
8
  buildFfmpegArgs(options) {
9
9
  const { fps, hold, outDir, transparent, metadata, inputPattern, pkgVersion, outputFileName, } = options;
10
- const args = [
11
- '-hide_banner',
12
- '-loglevel',
13
- 'warning',
14
- '-y',
15
- '-framerate',
16
- String(fps),
17
- '-i',
18
- inputPattern,
19
- ];
10
+ const args = ['-hide_banner', '-loglevel', 'warning', '-y'];
11
+ if (inputPattern === 'pipe:0' || inputPattern.startsWith('pipe:')) {
12
+ args.push('-f', 'image2pipe');
13
+ }
14
+ args.push('-framerate', String(fps), '-i', inputPattern);
20
15
  let userComment;
21
16
  if (metadata) {
22
17
  metadata.forEach((m) => {
@@ -7,16 +7,11 @@ export class Mp4FormatGenerator extends BaseCLIFormatGenerator {
7
7
  }
8
8
  buildFfmpegArgs(options) {
9
9
  const { fps, hold, outDir, metadata, inputPattern, pkgVersion, outputFileName, } = options;
10
- const args = [
11
- '-hide_banner',
12
- '-loglevel',
13
- 'warning',
14
- '-y',
15
- '-framerate',
16
- String(fps),
17
- '-i',
18
- inputPattern,
19
- ];
10
+ const args = ['-hide_banner', '-loglevel', 'warning', '-y'];
11
+ if (inputPattern === 'pipe:0' || inputPattern.startsWith('pipe:')) {
12
+ args.push('-f', 'image2pipe');
13
+ }
14
+ args.push('-framerate', String(fps), '-i', inputPattern);
20
15
  let userComment;
21
16
  if (metadata) {
22
17
  metadata.forEach((m) => {
@@ -7,16 +7,11 @@ export class WebmFormatGenerator extends BaseCLIFormatGenerator {
7
7
  }
8
8
  buildFfmpegArgs(options) {
9
9
  const { fps, hold, outDir, transparent, metadata, inputPattern, pkgVersion, outputFileName, } = options;
10
- const args = [
11
- '-hide_banner',
12
- '-loglevel',
13
- 'warning',
14
- '-y',
15
- '-framerate',
16
- String(fps),
17
- '-i',
18
- inputPattern,
19
- ];
10
+ const args = ['-hide_banner', '-loglevel', 'warning', '-y'];
11
+ if (inputPattern === 'pipe:0' || inputPattern.startsWith('pipe:')) {
12
+ args.push('-f', 'image2pipe');
13
+ }
14
+ args.push('-framerate', String(fps), '-i', inputPattern);
20
15
  let userComment;
21
16
  if (metadata) {
22
17
  metadata.forEach((m) => {
package/dist/src/index.js CHANGED
@@ -15,12 +15,27 @@ import { Logger } from './utils/logger.js';
15
15
  import { trackEvent, flushAnalytics } from './utils/analytics.js';
16
16
  import { ConversionTracker } from '#shared/rendererTracking.js';
17
17
  const frameFileExtension = 'png';
18
+ function writeFrameToStdin(stdin, buffer) {
19
+ return new Promise((resolve, reject) => {
20
+ // The write() callback is always invoked once the data is accepted,
21
+ // regardless of backpressure — it is the only place we resolve/reject.
22
+ // The boolean return value of write() is only a flow-control hint and
23
+ // must not be used to gate resolution (doing so causes the promise to
24
+ // hang when canWrite is false but the callback fires before drain).
25
+ stdin.write(buffer, (err) => {
26
+ if (err)
27
+ reject(err);
28
+ else
29
+ resolve();
30
+ });
31
+ });
32
+ }
18
33
  async function main() {
19
34
  const program = new Command();
20
35
  program
21
36
  .name('svg-to-video')
22
37
  .version(pkg.version)
23
- .description(`svg-to-video v${pkg.version} - Render a CSS-animated SVG to a high-quality video or animated image (MP4, WebM, MKV, MOV, GIF, aPNG)`)
38
+ .description(`svg-to-video v${pkg.version} - Render an animated SVG (CSS & SMIL) to a high-quality video or animated image (MP4, WebM, MKV, MOV, GIF, aPNG)`)
24
39
  .usage('<svgPath> <fps> <outDir> [options]')
25
40
  .addHelpText('after', `
26
41
  Resources:
@@ -131,6 +146,8 @@ async function run(svgPath, fps, outDir, options) {
131
146
  videoDurationSec: duration,
132
147
  }, trackEvent);
133
148
  tracker.start();
149
+ let activeBrowser = null;
150
+ let activeFfmpeg = null;
134
151
  let isCancelled = false;
135
152
  const handleSignal = async (signal) => {
136
153
  if (isCancelled)
@@ -138,8 +155,11 @@ async function run(svgPath, fps, outDir, options) {
138
155
  isCancelled = true;
139
156
  logger.info(`\n⚠️ Received ${signal}. Cancelling conversion...`);
140
157
  tracker.cancel();
141
- if (!options.keepFrames && totalFrames > 0 && padWidth > 0) {
142
- cleanupFrames(totalFrames, padWidth, outDir, logger);
158
+ if (activeFfmpeg && !activeFfmpeg.killed) {
159
+ activeFfmpeg.kill('SIGKILL');
160
+ }
161
+ if (activeBrowser) {
162
+ await activeBrowser.close().catch(() => { });
143
163
  }
144
164
  await flushAnalytics();
145
165
  process.exit(130);
@@ -150,11 +170,32 @@ async function run(svgPath, fps, outDir, options) {
150
170
  process.once('SIGTERM', sigtermListener);
151
171
  try {
152
172
  fs.mkdirSync(outDir, { recursive: true });
153
- await createFrames(svg, parsedDim, fps, totalFrames, padWidth, outDir, puppeteerArgs, options.resolution, options.scale, options.transparent, options.bgColor, generator.needsColorKeying, logger);
154
- convertToOutput(outputFileName, format, fps, padWidth, options.hold, outDir, options.transparent, options.metadata, logger);
155
- if (!options.keepFrames) {
156
- cleanupFrames(totalFrames, padWidth, outDir, logger);
157
- }
173
+ await renderAndEncodeFrames({
174
+ svg,
175
+ parsedDim,
176
+ fps,
177
+ totalFrames,
178
+ padWidth,
179
+ outDir,
180
+ outputFileName,
181
+ puppeteerArgs,
182
+ resolutionPreset: options.resolution,
183
+ scaleFactor: options.scale,
184
+ transparent: options.transparent,
185
+ bgColor: options.bgColor,
186
+ needsColorKeying: generator.needsColorKeying,
187
+ keepFrames: options.keepFrames,
188
+ hold: options.hold,
189
+ metadata: options.metadata,
190
+ generator,
191
+ logger,
192
+ onBrowserCreated: (b) => {
193
+ activeBrowser = b;
194
+ },
195
+ onFfmpegCreated: (f) => {
196
+ activeFfmpeg = f;
197
+ },
198
+ });
158
199
  tracker.success(totalFrames);
159
200
  await flushAnalytics();
160
201
  logger.done(outputFullPath, {
@@ -169,14 +210,6 @@ async function run(svgPath, fps, outDir, options) {
169
210
  catch (error) {
170
211
  if (!isCancelled) {
171
212
  tracker.failed(error instanceof Error ? error : String(error));
172
- if (!options.keepFrames) {
173
- try {
174
- cleanupFrames(totalFrames, padWidth, outDir, logger);
175
- }
176
- catch {
177
- // ignore frame cleanup error during exception handling
178
- }
179
- }
180
213
  await flushAnalytics();
181
214
  await logger.fatal('Conversion failed', error instanceof Error ? error.message : String(error));
182
215
  }
@@ -187,37 +220,34 @@ async function run(svgPath, fps, outDir, options) {
187
220
  }
188
221
  }
189
222
  /**
190
- * create frame images by rendering the SVG in a headless browser and advancing the animation to the correct timestamp for each frame
223
+ * Resolves output viewport dimensions based on preset, parsed SVG dimensions, and scale.
191
224
  */
192
- async function createFrames(svg, parsedDim, fps, totalFrames, padWidth, outDir, puppeteerArgs, resolutionPreset, scaleFactor, transparent, bgColor, needsColorKeying, logger) {
193
- logger.info('📸 Rendering frames with Puppeteer...');
194
- let width;
195
- let height;
225
+ function calculateDimensions(resolutionPreset, parsedDim, scaleFactor, logger) {
196
226
  if (/^\d+x\d+$/i.test(resolutionPreset)) {
197
227
  const [wStr, hStr] = resolutionPreset.toLowerCase().split('x');
198
- width = parseInt(wStr, 10);
199
- height = parseInt(hStr, 10);
228
+ return { width: parseInt(wStr, 10), height: parseInt(hStr, 10) };
200
229
  }
201
230
  else if (resolutionPreset === '1080p') {
202
- width = 1920;
203
- height = 1080;
231
+ return { width: 1920, height: 1080 };
204
232
  }
205
233
  else if (resolutionPreset === '720p') {
206
- width = 1280;
207
- height = 720;
234
+ return { width: 1280, height: 720 };
208
235
  }
209
236
  else if (resolutionPreset === 'original') {
210
237
  if (!parsedDim.isDimensionsDetected) {
211
238
  logger.warn('⚠️ Warning: Could not detect SVG dimensions. Defaulting to 1920x1080.');
212
239
  }
213
- width = Math.round(parsedDim.width * scaleFactor);
214
- height = Math.round(parsedDim.height * scaleFactor);
240
+ return {
241
+ width: Math.round(parsedDim.width * scaleFactor),
242
+ height: Math.round(parsedDim.height * scaleFactor),
243
+ };
215
244
  }
216
- else {
217
- throw new Error(`Invalid resolution preset: ${resolutionPreset}. Expected '1080p', '720p', 'original', or custom dimensions (e.g. 1080x1080).`);
218
- }
219
- logger.info(` Viewport: ${width}x${height}`);
220
- logger.info('🚀 Preparing Puppeteer browser...');
245
+ throw new Error(`Invalid resolution preset: ${resolutionPreset}. Expected '1080p', '720p', 'original', or custom dimensions (e.g. 1080x1080).`);
246
+ }
247
+ /**
248
+ * Launches Puppeteer browser with support for explicit executable path and system Chrome fallback.
249
+ */
250
+ async function launchBrowser(puppeteerArgs, logger) {
221
251
  const launchOptions = {
222
252
  headless: true,
223
253
  args: ['--no-sandbox', '--disable-setuid-sandbox', ...puppeteerArgs],
@@ -225,9 +255,8 @@ async function createFrames(svg, parsedDim, fps, totalFrames, padWidth, outDir,
225
255
  if (process.env.PUPPETEER_EXECUTABLE_PATH) {
226
256
  launchOptions.executablePath = process.env.PUPPETEER_EXECUTABLE_PATH;
227
257
  }
228
- let browser;
229
258
  try {
230
- browser = await puppeteer.launch(launchOptions);
259
+ return await puppeteer.launch(launchOptions);
231
260
  }
232
261
  catch (initialError) {
233
262
  if (launchOptions.executablePath) {
@@ -235,122 +264,169 @@ async function createFrames(svg, parsedDim, fps, totalFrames, padWidth, outDir,
235
264
  }
236
265
  logger.info('🔍 Bundled Chrome not found, attempting system Chrome...');
237
266
  try {
238
- browser = await puppeteer.launch({ ...launchOptions, channel: 'chrome' });
267
+ return await puppeteer.launch({ ...launchOptions, channel: 'chrome' });
239
268
  }
240
269
  catch {
241
270
  throw initialError;
242
271
  }
243
272
  }
244
- const page = await browser.newPage();
245
- await page.setViewport({ width, height });
246
- await page.setContent(svg, { waitUntil: 'domcontentloaded' });
247
- const bgStyle = transparent
248
- ? 'html, body { background: transparent !important; }'
249
- : bgColor
250
- ? `html, body { background-color: ${bgColor} !important; }`
251
- : '';
252
- await page.addStyleTag({
253
- content: `
254
- * { margin: 0; padding: 0; box-sizing: border-box; }
255
- svg { width: 100%; height: 100%; display: block; }
256
- ${bgStyle}
257
- `.trim(),
258
- });
259
- const screenshotOptions = {
260
- omitBackground: transparent,
261
- };
262
- const shouldKey = Boolean(transparent && bgColor && needsColorKeying);
263
- logger.info('📸 Rendering frames with Puppeteer...');
264
- for (let frame = 1; frame <= totalFrames; ++frame) {
265
- logger.writeProgress(`\r📸 Rendering frame ${frame}/${totalFrames}`);
266
- const timeMs = ((frame - 1) / fps) * 1000;
267
- await page.evaluate(seekAnimations, timeMs);
268
- const filename = path.join(outDir, getFrameFilename(frame, padWidth));
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
- }
298
- }
299
- logger.info('');
300
- await browser.close();
301
273
  }
302
274
  /**
303
- * convert the generated frames to an output format using ffmpeg
275
+ * Render frames with Puppeteer and stream PNG buffers into FFmpeg stdin.
304
276
  */
305
- function convertToOutput(outputFileName, format, fps, padWidth, hold, outDir, transparent, metadata, logger) {
306
- logger.info('📦 Encoding output with FFmpeg...');
307
- const normalizedFormat = format.toLowerCase();
308
- const generator = formatRegistry.get(normalizedFormat);
309
- if (!generator) {
310
- throw new Error(`Unsupported format: ${format}`);
311
- }
312
- const inputPattern = path.join(outDir, `%0${padWidth}d.${frameFileExtension}`);
277
+ async function renderAndEncodeFrames(params) {
278
+ const { width, height } = calculateDimensions(params.resolutionPreset, params.parsedDim, params.scaleFactor, params.logger);
279
+ params.logger.info(` Viewport: ${width}x${height}`);
313
280
  const formatOptions = {
314
- outputFileName,
315
- fps,
316
- padWidth,
317
- hold: hold || 0,
318
- outDir,
319
- transparent: !!transparent,
320
- metadata,
321
- inputPattern,
281
+ outputFileName: params.outputFileName,
282
+ fps: params.fps,
283
+ padWidth: params.padWidth,
284
+ hold: params.hold || 0,
285
+ outDir: params.outDir,
286
+ transparent: !!params.transparent,
287
+ metadata: params.metadata,
288
+ inputPattern: 'pipe:0',
322
289
  pkgVersion: pkg.version,
323
290
  };
324
- const args = generator.buildFfmpegArgs(formatOptions);
291
+ const args = params.generator.buildFfmpegArgs(formatOptions);
292
+ params.logger.info('📦 Encoding output with FFmpeg...');
293
+ const ffmpegProcess = child_process.spawn('ffmpeg', args, {
294
+ stdio: ['pipe', 'ignore', 'pipe'],
295
+ });
296
+ params.onFfmpegCreated(ffmpegProcess);
297
+ // Prevent unhandled EPIPE exception if FFmpeg exits before or during writes
298
+ ffmpegProcess.stdin.on('error', (err) => {
299
+ if (err.code !== 'EPIPE' && err.code !== 'ERR_STREAM_DESTROYED') {
300
+ params.logger.error('FFmpeg stdin error:', err);
301
+ }
302
+ });
303
+ let ffmpegStderr = '';
304
+ ffmpegProcess.stderr.on('data', (chunk) => {
305
+ ffmpegStderr += chunk.toString();
306
+ });
307
+ // Track the FFmpeg exit promise separately so we can always await it in the
308
+ // finally block — preventing dangling rejected promises if the frame loop
309
+ // throws before we reach the explicit await below.
310
+ const ffmpegExitPromise = new Promise((resolve, reject) => {
311
+ ffmpegProcess.on('error', (err) => reject(err));
312
+ ffmpegProcess.on('close', (code, signal) => resolve({ code, signal }));
313
+ });
314
+ ffmpegExitPromise.catch(() => { });
315
+ params.logger.info('🚀 Preparing Puppeteer browser...');
316
+ const browser = await launchBrowser(params.puppeteerArgs, params.logger);
317
+ params.onBrowserCreated(browser);
318
+ let hasFailed = false;
325
319
  try {
326
- const output = child_process.execFileSync('ffmpeg', args, {
327
- encoding: 'utf8',
320
+ const page = await browser.newPage();
321
+ await page.setViewport({ width, height });
322
+ await page.setContent(params.svg, { waitUntil: 'domcontentloaded' });
323
+ const bgStyle = params.transparent
324
+ ? 'html, body { background: transparent !important; }'
325
+ : params.bgColor
326
+ ? `html, body { background-color: ${params.bgColor} !important; }`
327
+ : '';
328
+ await page.addStyleTag({
329
+ content: `
330
+ * { margin: 0; padding: 0; box-sizing: border-box; }
331
+ svg { width: 100%; height: 100%; display: block; }
332
+ ${bgStyle}
333
+ `.trim(),
328
334
  });
329
- if (output)
330
- logger.info(output);
331
- const outputFullPath = path.join(outDir, outputFileName);
332
- if (generator.postProcess) {
333
- generator.postProcess(outputFullPath, formatOptions);
335
+ const screenshotOptions = {
336
+ omitBackground: params.transparent,
337
+ };
338
+ const shouldKey = Boolean(params.transparent && params.bgColor && params.needsColorKeying);
339
+ const progressInterval = Math.max(1, Math.floor(params.totalFrames * 0.05));
340
+ params.logger.info('📸 Rendering frames with Puppeteer...');
341
+ for (let frame = 1; frame <= params.totalFrames; ++frame) {
342
+ if (frame === 1 ||
343
+ frame === params.totalFrames ||
344
+ frame % progressInterval === 0) {
345
+ params.logger.writeProgress(`\r📸 Rendering frame ${frame}/${params.totalFrames}`);
346
+ }
347
+ const timeMs = ((frame - 1) / params.fps) * 1000;
348
+ await page.evaluate(seekAnimations, timeMs);
349
+ let frameBuffer;
350
+ if (shouldKey) {
351
+ const rawScreenshotBuffer = await page.screenshot(screenshotOptions);
352
+ const b64Input = Buffer.from(rawScreenshotBuffer).toString('base64');
353
+ const keyedBase64 = await page.evaluate(async (compositeFnStr, b64, bg, w, h) => {
354
+ let canvas = document.getElementById('matte-canvas');
355
+ if (!canvas) {
356
+ canvas = document.createElement('canvas');
357
+ canvas.id = 'matte-canvas';
358
+ canvas.width = w;
359
+ canvas.height = h;
360
+ canvas.style.display = 'none';
361
+ document.body.appendChild(canvas);
362
+ }
363
+ const ctx = canvas.getContext('2d');
364
+ const img = new Image();
365
+ img.src = 'data:image/png;base64,' + b64;
366
+ await img.decode();
367
+ const compositeFn = new Function('return ' + compositeFnStr)();
368
+ compositeFn(ctx, img, w, h, bg, true);
369
+ return canvas.toDataURL('image/png').split(',')[1];
370
+ }, compositeFrame.toString(), b64Input, params.bgColor, width, height);
371
+ frameBuffer = Buffer.from(keyedBase64, 'base64');
372
+ }
373
+ else {
374
+ frameBuffer = (await page.screenshot(screenshotOptions));
375
+ }
376
+ if (params.keepFrames) {
377
+ const filename = path.join(params.outDir, getFrameFilename(frame, params.padWidth));
378
+ fs.writeFileSync(filename, frameBuffer);
379
+ }
380
+ try {
381
+ await writeFrameToStdin(ffmpegProcess.stdin, frameBuffer);
382
+ }
383
+ catch (writeError) {
384
+ // If writing to stdin failed (e.g. EPIPE), await FFmpeg to capture its real exit code and stderr
385
+ const { code } = await ffmpegExitPromise;
386
+ if (code !== 0 && code !== null) {
387
+ throw new Error(`FFmpeg execution failed (exit code ${code}): ${ffmpegStderr.trim()}`, { cause: writeError });
388
+ }
389
+ throw writeError;
390
+ }
391
+ }
392
+ params.logger.info('');
393
+ ffmpegProcess.stdin.end();
394
+ const { code } = await ffmpegExitPromise;
395
+ if (code !== 0) {
396
+ throw new Error(`FFmpeg execution failed (exit code ${code}): ${ffmpegStderr.trim()}`);
397
+ }
398
+ const outputFullPath = path.join(params.outDir, params.outputFileName);
399
+ if (params.generator.postProcess) {
400
+ params.generator.postProcess(outputFullPath, formatOptions);
334
401
  }
335
402
  }
336
403
  catch (error) {
337
- const details = error instanceof Error ? error.message : String(error);
338
- throw new Error(`FFmpeg execution failed: ${details}`, { cause: error });
339
- }
340
- }
341
- /**
342
- * delete the generated frames
343
- */
344
- function cleanupFrames(totalFrames, padWidth, outDir, logger) {
345
- logger.info('🧹 Cleaning up temporary frames...');
346
- for (let frame = 1; frame <= totalFrames; ++frame) {
347
- const filename = path.join(outDir, getFrameFilename(frame, padWidth));
348
- try {
349
- fs.unlinkSync(filename);
404
+ hasFailed = true;
405
+ // On conversion failure, terminate FFmpeg immediately rather than letting it produce a corrupt/partial file
406
+ if (!ffmpegProcess.killed) {
407
+ ffmpegProcess.kill('SIGKILL');
408
+ }
409
+ // Clean up partial output file if created
410
+ const outputFullPath = path.join(params.outDir, params.outputFileName);
411
+ if (fs.existsSync(outputFullPath)) {
412
+ try {
413
+ fs.unlinkSync(outputFullPath);
414
+ }
415
+ catch {
416
+ // ignore unlink error during error handling
417
+ }
350
418
  }
351
- catch (error) {
352
- logger.error(`❌ Failed to delete frame: ${filename}`, error);
419
+ throw error;
420
+ }
421
+ finally {
422
+ // End stdin cleanly only if not already failed or destroyed
423
+ if (!hasFailed &&
424
+ !ffmpegProcess.stdin.destroyed &&
425
+ !ffmpegProcess.stdin.writableEnded) {
426
+ ffmpegProcess.stdin.end();
353
427
  }
428
+ await ffmpegExitPromise.catch(() => { });
429
+ await browser?.close().catch(() => { });
354
430
  }
355
431
  }
356
432
  /**
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@gehdoc/svg-to-video",
3
3
  "mcpName": "io.github.GehDoc/svg-to-video",
4
- "version": "0.32.1",
4
+ "version": "0.34.0",
5
5
  "type": "module",
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.",
6
+ "description": "Professional animated SVG (CSS & SMIL) 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": {
8
8
  "#shared/*": "./dist/shared/*"
9
9
  },
@@ -25,6 +25,8 @@
25
25
  "keywords": [
26
26
  "animation",
27
27
  "css",
28
+ "smil",
29
+ "svg-animation",
28
30
  "video",
29
31
  "svg",
30
32
  "convert",
@@ -130,6 +132,7 @@
130
132
  "@vitest/runner": "$vitest",
131
133
  "@vitest/snapshot": "$vitest",
132
134
  "@modelcontextprotocol/sdk": "$@modelcontextprotocol/sdk",
133
- "@modelcontextprotocol/client": "2.3.1"
135
+ "@modelcontextprotocol/client": "2.4.0",
136
+ "@modelcontextprotocol/server": "2.4.0"
134
137
  }
135
138
  }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: svg-to-video
3
- description: Convert CSS-animated SVG files or SVG string content into high-quality MP4/WebM/MKV/MOV videos, lightweight animated GIFs, or aPNG images with optional alpha-channel background transparency.
3
+ description: Convert animated SVG files (CSS & SMIL) or SVG string content into high-quality MP4/WebM/MKV/MOV videos, lightweight animated GIFs, or aPNG images with optional alpha-channel background transparency.
4
4
  tools:
5
5
  - name: render_svg_to_video
6
6
  description: Convert an animated SVG to video or animated image format.
@@ -16,7 +16,7 @@ This skill enables AI agents to render animated vector graphics (SVGs with CSS a
16
16
 
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
- 3. **Auto-Duration Detection**: Automatically detects CSS keyframe and animation loop durations if not specified.
19
+ 3. **Auto-Duration Detection**: Automatically detects CSS keyframes and SMIL animation loop durations if not specified.
20
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