@gehdoc/svg-to-video 0.33.0 โ†’ 0.35.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
@@ -73,7 +73,7 @@ For automated or batch processing, use the CLI tool. It is built to run in a hea
73
73
 
74
74
  ### Quick Start
75
75
 
76
- Ensure [Node.js](https://nodejs.org/) and [FFmpeg](https://ffmpeg.org/) are installed.
76
+ Ensure [Node.js](https://nodejs.org/) is installed. Chrome/Chromium is managed automatically by Puppeteer (override via `PUPPETEER_EXECUTABLE_PATH`). System [FFmpeg](https://ffmpeg.org/) is used if available, or a bundled static fallback is automatically used (override via `--ffmpeg-path <path>` or the `FFMPEG_PATH` environment variable).
77
77
 
78
78
  ```bash
79
79
  # Node.js (auto-detected duration)
@@ -171,9 +171,9 @@ For instructions on contributing, build commands, security standards, and the te
171
171
 
172
172
  If you find this tool helpful, please consider supporting its development:
173
173
 
174
- [![Donate](https://img.shields.io/badge/Donate-PayPal-blue.svg)](https://paypal.me/GehDoc)
174
+ [![Sponsor](https://img.shields.io/badge/Sponsor-GitHub-ea4aaa?logo=githubsponsors)](https://github.com/sponsors/GehDoc)
175
175
 
176
- Your support helps cover maintenance and further development of the tool. Thank you!
176
+ Your support directly fuels my agentic engineering harness and helps keep this tool free, secure, and privacy-first. Thank you!
177
177
 
178
178
  ---
179
179
 
@@ -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
@@ -7,6 +7,7 @@ import path from 'path';
7
7
  import { seekAnimations } from '#shared/animation-engine.js';
8
8
  import { compositeFrame } from '#shared/canvasCompositing.js';
9
9
  import { validateOptions } from './utils/validateOptions.js';
10
+ import { resolveFfmpegPath } from './utils/ffmpegResolver.js';
10
11
  import { analyzeSvgAnimation, parseSvgDimensions, calculateAspectRatio, } from '#shared/analyzeSvgAnimation.js';
11
12
  import { formatRegistry } from './formats/registry.js';
12
13
  import { pkg } from './utils/packageInfo.js';
@@ -15,6 +16,21 @@ import { Logger } from './utils/logger.js';
15
16
  import { trackEvent, flushAnalytics } from './utils/analytics.js';
16
17
  import { ConversionTracker } from '#shared/rendererTracking.js';
17
18
  const frameFileExtension = 'png';
19
+ function writeFrameToStdin(stdin, buffer) {
20
+ return new Promise((resolve, reject) => {
21
+ // The write() callback is always invoked once the data is accepted,
22
+ // regardless of backpressure โ€” it is the only place we resolve/reject.
23
+ // The boolean return value of write() is only a flow-control hint and
24
+ // must not be used to gate resolution (doing so causes the promise to
25
+ // hang when canWrite is false but the callback fires before drain).
26
+ stdin.write(buffer, (err) => {
27
+ if (err)
28
+ reject(err);
29
+ else
30
+ resolve();
31
+ });
32
+ });
33
+ }
18
34
  async function main() {
19
35
  const program = new Command();
20
36
  program
@@ -46,6 +62,7 @@ Resources:
46
62
  .option('--bg-color <hex>', 'background color for the video (e.g., #FFFFFF)')
47
63
  .option('--metadata <items...>', 'metadata tags (e.g., --metadata title="My Video" author="Me")')
48
64
  .option('--format <format>', `output format: ${formatRegistry.getSupportedFormatNames().join(', ')}`)
65
+ .option('--ffmpeg-path <path>', 'custom path to ffmpeg executable (overrides system PATH and FFMPEG_PATH)')
49
66
  .option('-q, --quiet', 'suppress interactive progress output', false)
50
67
  .option('--silent', 'alias for --quiet', false)
51
68
  .option('--json', 'output final conversion result as JSON (implies quiet mode)', false)
@@ -131,6 +148,8 @@ async function run(svgPath, fps, outDir, options) {
131
148
  videoDurationSec: duration,
132
149
  }, trackEvent);
133
150
  tracker.start();
151
+ let activeBrowser = null;
152
+ let activeFfmpeg = null;
134
153
  let isCancelled = false;
135
154
  const handleSignal = async (signal) => {
136
155
  if (isCancelled)
@@ -138,8 +157,11 @@ async function run(svgPath, fps, outDir, options) {
138
157
  isCancelled = true;
139
158
  logger.info(`\nโš ๏ธ Received ${signal}. Cancelling conversion...`);
140
159
  tracker.cancel();
141
- if (!options.keepFrames && totalFrames > 0 && padWidth > 0) {
142
- cleanupFrames(totalFrames, padWidth, outDir, logger);
160
+ if (activeFfmpeg && !activeFfmpeg.killed) {
161
+ activeFfmpeg.kill('SIGKILL');
162
+ }
163
+ if (activeBrowser) {
164
+ await activeBrowser.close().catch(() => { });
143
165
  }
144
166
  await flushAnalytics();
145
167
  process.exit(130);
@@ -150,11 +172,34 @@ async function run(svgPath, fps, outDir, options) {
150
172
  process.once('SIGTERM', sigtermListener);
151
173
  try {
152
174
  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
- }
175
+ const ffmpegPath = resolveFfmpegPath(options.ffmpegPath, logger);
176
+ await renderAndEncodeFrames({
177
+ svg,
178
+ parsedDim,
179
+ fps,
180
+ totalFrames,
181
+ padWidth,
182
+ outDir,
183
+ outputFileName,
184
+ ffmpegPath,
185
+ puppeteerArgs,
186
+ resolutionPreset: options.resolution,
187
+ scaleFactor: options.scale,
188
+ transparent: options.transparent,
189
+ bgColor: options.bgColor,
190
+ needsColorKeying: generator.needsColorKeying,
191
+ keepFrames: options.keepFrames,
192
+ hold: options.hold,
193
+ metadata: options.metadata,
194
+ generator,
195
+ logger,
196
+ onBrowserCreated: (b) => {
197
+ activeBrowser = b;
198
+ },
199
+ onFfmpegCreated: (f) => {
200
+ activeFfmpeg = f;
201
+ },
202
+ });
158
203
  tracker.success(totalFrames);
159
204
  await flushAnalytics();
160
205
  logger.done(outputFullPath, {
@@ -169,14 +214,6 @@ async function run(svgPath, fps, outDir, options) {
169
214
  catch (error) {
170
215
  if (!isCancelled) {
171
216
  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
217
  await flushAnalytics();
181
218
  await logger.fatal('Conversion failed', error instanceof Error ? error.message : String(error));
182
219
  }
@@ -187,37 +224,34 @@ async function run(svgPath, fps, outDir, options) {
187
224
  }
188
225
  }
189
226
  /**
190
- * create frame images by rendering the SVG in a headless browser and advancing the animation to the correct timestamp for each frame
227
+ * Resolves output viewport dimensions based on preset, parsed SVG dimensions, and scale.
191
228
  */
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;
229
+ function calculateDimensions(resolutionPreset, parsedDim, scaleFactor, logger) {
196
230
  if (/^\d+x\d+$/i.test(resolutionPreset)) {
197
231
  const [wStr, hStr] = resolutionPreset.toLowerCase().split('x');
198
- width = parseInt(wStr, 10);
199
- height = parseInt(hStr, 10);
232
+ return { width: parseInt(wStr, 10), height: parseInt(hStr, 10) };
200
233
  }
201
234
  else if (resolutionPreset === '1080p') {
202
- width = 1920;
203
- height = 1080;
235
+ return { width: 1920, height: 1080 };
204
236
  }
205
237
  else if (resolutionPreset === '720p') {
206
- width = 1280;
207
- height = 720;
238
+ return { width: 1280, height: 720 };
208
239
  }
209
240
  else if (resolutionPreset === 'original') {
210
241
  if (!parsedDim.isDimensionsDetected) {
211
242
  logger.warn('โš ๏ธ Warning: Could not detect SVG dimensions. Defaulting to 1920x1080.');
212
243
  }
213
- width = Math.round(parsedDim.width * scaleFactor);
214
- height = Math.round(parsedDim.height * scaleFactor);
244
+ return {
245
+ width: Math.round(parsedDim.width * scaleFactor),
246
+ height: Math.round(parsedDim.height * scaleFactor),
247
+ };
215
248
  }
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...');
249
+ throw new Error(`Invalid resolution preset: ${resolutionPreset}. Expected '1080p', '720p', 'original', or custom dimensions (e.g. 1080x1080).`);
250
+ }
251
+ /**
252
+ * Launches Puppeteer browser with support for explicit executable path and system Chrome fallback.
253
+ */
254
+ async function launchBrowser(puppeteerArgs, logger) {
221
255
  const launchOptions = {
222
256
  headless: true,
223
257
  args: ['--no-sandbox', '--disable-setuid-sandbox', ...puppeteerArgs],
@@ -225,9 +259,8 @@ async function createFrames(svg, parsedDim, fps, totalFrames, padWidth, outDir,
225
259
  if (process.env.PUPPETEER_EXECUTABLE_PATH) {
226
260
  launchOptions.executablePath = process.env.PUPPETEER_EXECUTABLE_PATH;
227
261
  }
228
- let browser;
229
262
  try {
230
- browser = await puppeteer.launch(launchOptions);
263
+ return await puppeteer.launch(launchOptions);
231
264
  }
232
265
  catch (initialError) {
233
266
  if (launchOptions.executablePath) {
@@ -235,122 +268,169 @@ async function createFrames(svg, parsedDim, fps, totalFrames, padWidth, outDir,
235
268
  }
236
269
  logger.info('๐Ÿ” Bundled Chrome not found, attempting system Chrome...');
237
270
  try {
238
- browser = await puppeteer.launch({ ...launchOptions, channel: 'chrome' });
271
+ return await puppeteer.launch({ ...launchOptions, channel: 'chrome' });
239
272
  }
240
273
  catch {
241
274
  throw initialError;
242
275
  }
243
276
  }
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
277
  }
302
278
  /**
303
- * convert the generated frames to an output format using ffmpeg
279
+ * Render frames with Puppeteer and stream PNG buffers into FFmpeg stdin.
304
280
  */
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}`);
281
+ async function renderAndEncodeFrames(params) {
282
+ const { width, height } = calculateDimensions(params.resolutionPreset, params.parsedDim, params.scaleFactor, params.logger);
283
+ params.logger.info(` Viewport: ${width}x${height}`);
313
284
  const formatOptions = {
314
- outputFileName,
315
- fps,
316
- padWidth,
317
- hold: hold || 0,
318
- outDir,
319
- transparent: !!transparent,
320
- metadata,
321
- inputPattern,
285
+ outputFileName: params.outputFileName,
286
+ fps: params.fps,
287
+ padWidth: params.padWidth,
288
+ hold: params.hold || 0,
289
+ outDir: params.outDir,
290
+ transparent: !!params.transparent,
291
+ metadata: params.metadata,
292
+ inputPattern: 'pipe:0',
322
293
  pkgVersion: pkg.version,
323
294
  };
324
- const args = generator.buildFfmpegArgs(formatOptions);
295
+ const args = params.generator.buildFfmpegArgs(formatOptions);
296
+ params.logger.info('๐Ÿ“ฆ Encoding output with FFmpeg...');
297
+ const ffmpegProcess = child_process.spawn(params.ffmpegPath, args, {
298
+ stdio: ['pipe', 'ignore', 'pipe'],
299
+ });
300
+ params.onFfmpegCreated(ffmpegProcess);
301
+ // Prevent unhandled EPIPE exception if FFmpeg exits before or during writes
302
+ ffmpegProcess.stdin.on('error', (err) => {
303
+ if (err.code !== 'EPIPE' && err.code !== 'ERR_STREAM_DESTROYED') {
304
+ params.logger.error('FFmpeg stdin error:', err);
305
+ }
306
+ });
307
+ let ffmpegStderr = '';
308
+ ffmpegProcess.stderr.on('data', (chunk) => {
309
+ ffmpegStderr += chunk.toString();
310
+ });
311
+ // Track the FFmpeg exit promise separately so we can always await it in the
312
+ // finally block โ€” preventing dangling rejected promises if the frame loop
313
+ // throws before we reach the explicit await below.
314
+ const ffmpegExitPromise = new Promise((resolve, reject) => {
315
+ ffmpegProcess.on('error', (err) => reject(err));
316
+ ffmpegProcess.on('close', (code, signal) => resolve({ code, signal }));
317
+ });
318
+ ffmpegExitPromise.catch(() => { });
319
+ params.logger.info('๐Ÿš€ Preparing Puppeteer browser...');
320
+ const browser = await launchBrowser(params.puppeteerArgs, params.logger);
321
+ params.onBrowserCreated(browser);
322
+ let hasFailed = false;
325
323
  try {
326
- const output = child_process.execFileSync('ffmpeg', args, {
327
- encoding: 'utf8',
324
+ const page = await browser.newPage();
325
+ await page.setViewport({ width, height });
326
+ await page.setContent(params.svg, { waitUntil: 'domcontentloaded' });
327
+ const bgStyle = params.transparent
328
+ ? 'html, body { background: transparent !important; }'
329
+ : params.bgColor
330
+ ? `html, body { background-color: ${params.bgColor} !important; }`
331
+ : '';
332
+ await page.addStyleTag({
333
+ content: `
334
+ * { margin: 0; padding: 0; box-sizing: border-box; }
335
+ svg { width: 100%; height: 100%; display: block; }
336
+ ${bgStyle}
337
+ `.trim(),
328
338
  });
329
- if (output)
330
- logger.info(output);
331
- const outputFullPath = path.join(outDir, outputFileName);
332
- if (generator.postProcess) {
333
- generator.postProcess(outputFullPath, formatOptions);
339
+ const screenshotOptions = {
340
+ omitBackground: params.transparent,
341
+ };
342
+ const shouldKey = Boolean(params.transparent && params.bgColor && params.needsColorKeying);
343
+ const progressInterval = Math.max(1, Math.floor(params.totalFrames * 0.05));
344
+ params.logger.info('๐Ÿ“ธ Rendering frames with Puppeteer...');
345
+ for (let frame = 1; frame <= params.totalFrames; ++frame) {
346
+ if (frame === 1 ||
347
+ frame === params.totalFrames ||
348
+ frame % progressInterval === 0) {
349
+ params.logger.writeProgress(`\r๐Ÿ“ธ Rendering frame ${frame}/${params.totalFrames}`);
350
+ }
351
+ const timeMs = ((frame - 1) / params.fps) * 1000;
352
+ await page.evaluate(seekAnimations, timeMs);
353
+ let frameBuffer;
354
+ if (shouldKey) {
355
+ const rawScreenshotBuffer = await page.screenshot(screenshotOptions);
356
+ const b64Input = Buffer.from(rawScreenshotBuffer).toString('base64');
357
+ const keyedBase64 = await page.evaluate(async (compositeFnStr, b64, bg, w, h) => {
358
+ let canvas = document.getElementById('matte-canvas');
359
+ if (!canvas) {
360
+ canvas = document.createElement('canvas');
361
+ canvas.id = 'matte-canvas';
362
+ canvas.width = w;
363
+ canvas.height = h;
364
+ canvas.style.display = 'none';
365
+ document.body.appendChild(canvas);
366
+ }
367
+ const ctx = canvas.getContext('2d');
368
+ const img = new Image();
369
+ img.src = 'data:image/png;base64,' + b64;
370
+ await img.decode();
371
+ const compositeFn = new Function('return ' + compositeFnStr)();
372
+ compositeFn(ctx, img, w, h, bg, true);
373
+ return canvas.toDataURL('image/png').split(',')[1];
374
+ }, compositeFrame.toString(), b64Input, params.bgColor, width, height);
375
+ frameBuffer = Buffer.from(keyedBase64, 'base64');
376
+ }
377
+ else {
378
+ frameBuffer = (await page.screenshot(screenshotOptions));
379
+ }
380
+ if (params.keepFrames) {
381
+ const filename = path.join(params.outDir, getFrameFilename(frame, params.padWidth));
382
+ fs.writeFileSync(filename, frameBuffer);
383
+ }
384
+ try {
385
+ await writeFrameToStdin(ffmpegProcess.stdin, frameBuffer);
386
+ }
387
+ catch (writeError) {
388
+ // If writing to stdin failed (e.g. EPIPE), await FFmpeg to capture its real exit code and stderr
389
+ const { code } = await ffmpegExitPromise;
390
+ if (code !== 0 && code !== null) {
391
+ throw new Error(`FFmpeg execution failed (exit code ${code}): ${ffmpegStderr.trim()}`, { cause: writeError });
392
+ }
393
+ throw writeError;
394
+ }
395
+ }
396
+ params.logger.info('');
397
+ ffmpegProcess.stdin.end();
398
+ const { code } = await ffmpegExitPromise;
399
+ if (code !== 0) {
400
+ throw new Error(`FFmpeg execution failed (exit code ${code}): ${ffmpegStderr.trim()}`);
401
+ }
402
+ const outputFullPath = path.join(params.outDir, params.outputFileName);
403
+ if (params.generator.postProcess) {
404
+ params.generator.postProcess(outputFullPath, formatOptions);
334
405
  }
335
406
  }
336
407
  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);
408
+ hasFailed = true;
409
+ // On conversion failure, terminate FFmpeg immediately rather than letting it produce a corrupt/partial file
410
+ if (!ffmpegProcess.killed) {
411
+ ffmpegProcess.kill('SIGKILL');
412
+ }
413
+ // Clean up partial output file if created
414
+ const outputFullPath = path.join(params.outDir, params.outputFileName);
415
+ if (fs.existsSync(outputFullPath)) {
416
+ try {
417
+ fs.unlinkSync(outputFullPath);
418
+ }
419
+ catch {
420
+ // ignore unlink error during error handling
421
+ }
350
422
  }
351
- catch (error) {
352
- logger.error(`โŒ Failed to delete frame: ${filename}`, error);
423
+ throw error;
424
+ }
425
+ finally {
426
+ // End stdin cleanly only if not already failed or destroyed
427
+ if (!hasFailed &&
428
+ !ffmpegProcess.stdin.destroyed &&
429
+ !ffmpegProcess.stdin.writableEnded) {
430
+ ffmpegProcess.stdin.end();
353
431
  }
432
+ await ffmpegExitPromise.catch(() => { });
433
+ await browser?.close().catch(() => { });
354
434
  }
355
435
  }
356
436
  /**
@@ -0,0 +1,64 @@
1
+ import fs from 'fs';
2
+ import child_process from 'child_process';
3
+ import { createRequire } from 'module';
4
+ const require = createRequire(import.meta.url);
5
+ /**
6
+ * Checks if system FFmpeg is available on PATH.
7
+ */
8
+ export function findSystemFfmpeg() {
9
+ try {
10
+ const result = child_process.spawnSync('ffmpeg', ['-version'], {
11
+ stdio: 'ignore',
12
+ });
13
+ return result.status === 0;
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ /**
20
+ * Resolves static binary path from optionalDependency ffmpeg-static if installed and available.
21
+ */
22
+ export function getBundledFfmpeg() {
23
+ try {
24
+ const ffmpegStatic = require('ffmpeg-static');
25
+ if (typeof ffmpegStatic === 'string' && fs.existsSync(ffmpegStatic)) {
26
+ return ffmpegStatic;
27
+ }
28
+ }
29
+ catch {
30
+ // optionalDependency not installed or unavailable
31
+ }
32
+ return null;
33
+ }
34
+ /**
35
+ * Resolves FFmpeg executable path with priority:
36
+ * 1. Explicit path parameter or FFMPEG_PATH / FFMPEG_EXECUTABLE_PATH environment variable
37
+ * 2. System FFmpeg executable found on PATH
38
+ * 3. Bundled static binary via ffmpeg-static optionalDependency
39
+ */
40
+ export function resolveFfmpegPath(explicitPath, logger) {
41
+ // 1. Explicit path or ENV
42
+ const candidate = explicitPath ||
43
+ process.env.FFMPEG_PATH ||
44
+ process.env.FFMPEG_EXECUTABLE_PATH;
45
+ if (candidate) {
46
+ if (fs.existsSync(candidate)) {
47
+ return candidate;
48
+ }
49
+ throw new Error(`Configured FFmpeg path not found or not executable: ${candidate}`);
50
+ }
51
+ // 2. System PATH
52
+ if (findSystemFfmpeg()) {
53
+ return 'ffmpeg';
54
+ }
55
+ // 3. Bundled ffmpeg-static fallback
56
+ const bundled = getBundledFfmpeg();
57
+ if (bundled) {
58
+ logger?.info('๐Ÿ” System FFmpeg not found, using bundled static FFmpeg...');
59
+ return bundled;
60
+ }
61
+ // 4. Failure with actionable instructions
62
+ throw new Error('FFmpeg is required to convert SVG animations to video, but was not found on your system.\n' +
63
+ 'Please install FFmpeg (e.g. via brew, apt, or winget) or set the FFMPEG_PATH environment variable.');
64
+ }
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.33.0",
4
+ "version": "0.35.0",
5
5
  "type": "module",
6
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": {
@@ -17,7 +17,8 @@
17
17
  },
18
18
  "homepage": "https://gehdoc.github.io/svg-to-video/",
19
19
  "funding": {
20
- "url": "https://github.com/GehDoc/svg-to-video/?sponsor=1"
20
+ "type": "github",
21
+ "url": "https://github.com/sponsors/GehDoc"
21
22
  },
22
23
  "engines": {
23
24
  "node": ">=22.22.2"
@@ -60,8 +61,8 @@
60
61
  "@umami/node": "^0.4.0",
61
62
  "commander": "^15.0.0",
62
63
  "jsdom": "^30.1.1",
63
- "supergateway": "^4.1.0",
64
64
  "puppeteer": "^25.8.0",
65
+ "supergateway": "^4.1.0",
65
66
  "tsx": "^4.23.0"
66
67
  },
67
68
  "devDependencies": {
@@ -106,6 +107,7 @@
106
107
  "check": "npm run lint && npm run format && npm run type-check && npm run test",
107
108
  "check:fast": "npm run lint && npm run format && npm run type-check",
108
109
  "fix": "npm run lint:fix && npm run format:fix",
110
+ "benchmark:ci": "tsx scripts/compare-ci.ts",
109
111
  "prepare": "husky"
110
112
  },
111
113
  "lint-staged": {
@@ -132,6 +134,10 @@
132
134
  "@vitest/runner": "$vitest",
133
135
  "@vitest/snapshot": "$vitest",
134
136
  "@modelcontextprotocol/sdk": "$@modelcontextprotocol/sdk",
135
- "@modelcontextprotocol/client": "2.3.1"
137
+ "@modelcontextprotocol/client": "2.4.0",
138
+ "@modelcontextprotocol/server": "2.4.0"
139
+ },
140
+ "optionalDependencies": {
141
+ "ffmpeg-static": "^5.3.0"
136
142
  }
137
143
  }