source: Klonkt/src/services/VideoCoverService.js@ 7ecbefc

main
Last change on this file since 7ecbefc was 7ecbefc, checked in by roboburr <roboburr@…>, 2 months ago

fix(video-cover): composite partial animated-WebP frames (fixes torn/tiled MP4)

node-webpmux getFrameData(i) returns only frame i's own sub-region, NOT the composited canvas.
Real tool-made animated WebPs use partial frames of varying size, so concatenating them at a fixed
-s WxH desynced ffmpeg's rawvideo stream -> a torn/tiled video (and a garbled "GIF" on Mastodon).
Now composite each sub-region onto a persistent WxH canvas (honoring blend + dispose) and emit full
frames. Verified visually: a partial-frame webp now converts to a clean, correctly-framed MP4.

Co-Authored-By: Claude <noreply@…>

  • Property mode set to 100644
File size: 6.7 KB
Line 
1/**
2 * VideoCoverService — turn an animated cover into a small, Safari-friendly muted loop video.
3 *
4 * Safari renders animated WebP poorly; a muted <video> loop plays smoothly everywhere (iOS too).
5 * ffmpeg-static can't DECODE an animated WebP, so we decode it with node-webpmux (pure JS/WASM,
6 * NO native deps → installs on every platform, never breaks `npm ci`) into RGBA frames, then
7 * encode with the bundled ffmpeg-static into an H.264 MP4 (yuv420p + faststart + no audio) plus a
8 * JPG poster frame. A real uploaded video goes straight through ffmpeg. Both are best-effort: on
9 * any failure we return null and the caller keeps the still image.
10 */
11import { execFile } from 'child_process';
12import { promisify } from 'util';
13import fs from 'fs';
14import path from 'path';
15import ffmpegPath from 'ffmpeg-static';
16import WebP from 'node-webpmux';
17
18const execFileP = promisify(execFile);
19const MAX_SECONDS = 60; // cap a cover loop at one minute
20
21let _lib = null;
22function ensureLib() { if (!_lib) _lib = WebP.Image.initLib(); return _lib; }
23
24// node-webpmux's getFrameData(i) returns ONLY frame i's own sub-region (x,y,width,height) — it does
25// NOT composite onto the canvas. Real (tool-made) animated WebPs use partial frames of varying size,
26// so we composite each onto a persistent W×H canvas (honoring blend + dispose) and emit consistent
27// full frames. Feeding ffmpeg the raw varying-size sub-regions desyncs the stream → a torn/tiled video.
28async function compositeFrames(img) {
29 const W = img.width, H = img.height, frames = img.anim.frames;
30 const canvas = Buffer.alloc(W * H * 4); // transparent black
31 const out = [];
32 let prev = null; // previous frame's rect + dispose
33 for (let i = 0; i < frames.length; i++) {
34 const fr = frames[i];
35 if (prev && prev.dispose) { // dispose-to-background: clear the previous frame's rect first
36 for (let row = 0; row < prev.h; row++) {
37 const y = prev.y + row; if (y < 0 || y >= H) continue;
38 canvas.fill(0, (y * W + prev.x) * 4, (y * W + prev.x + prev.w) * 4);
39 }
40 }
41 const data = Buffer.from(await img.getFrameData(i)); // fr.width*fr.height*4 RGBA sub-region
42 const fx = fr.x, fy = fr.y, fw = fr.width, fh = fr.height, blend = fr.blend;
43 if (fx === 0 && fy === 0 && fw === W && fh === H && !blend) {
44 data.copy(canvas, 0); // full opaque overwrite (the typical base frame)
45 } else {
46 for (let row = 0; row < fh; row++) {
47 const cy = fy + row; if (cy < 0 || cy >= H) continue;
48 for (let col = 0; col < fw; col++) {
49 const cx = fx + col; if (cx < 0 || cx >= W) continue;
50 const s = (row * fw + col) * 4, d = (cy * W + cx) * 4, sa = data[s + 3];
51 if (!blend || sa === 255) { canvas[d] = data[s]; canvas[d + 1] = data[s + 1]; canvas[d + 2] = data[s + 2]; canvas[d + 3] = sa; }
52 else if (sa !== 0) { // alpha-over the existing canvas pixel
53 const a = sa / 255, ia = 1 - a;
54 canvas[d] = (data[s] * a + canvas[d] * ia) | 0;
55 canvas[d + 1] = (data[s + 1] * a + canvas[d + 1] * ia) | 0;
56 canvas[d + 2] = (data[s + 2] * a + canvas[d + 2] * ia) | 0;
57 canvas[d + 3] = Math.min(255, sa + ((canvas[d + 3] * ia) | 0));
58 }
59 }
60 }
61 }
62 out.push(Buffer.from(canvas)); // snapshot the full composited canvas
63 prev = { x: fx, y: fy, w: fw, h: fh, dispose: fr.dispose };
64 }
65 return Buffer.concat(out);
66}
67
68// True if the file is an animated WebP (a VP8X chunk with the animation flag set).
69export function isAnimatedWebp(filePath) {
70 try {
71 if (path.extname(filePath).toLowerCase() !== '.webp') return false;
72 const fd = fs.openSync(filePath, 'r');
73 try {
74 const b = Buffer.alloc(40);
75 const n = fs.readSync(fd, b, 0, 40, 0);
76 return n >= 21 && b.toString('ascii', 12, 16) === 'VP8X' && (b[20] & 0x02) !== 0;
77 } finally { fs.closeSync(fd); }
78 } catch { return false; }
79}
80
81// Animated WebP → muted loop MP4 + JPG poster. Returns { videoPath, posterPath } or null.
82export async function animatedWebpToVideo(srcPath, outDir, baseName) {
83 let rawPath = null;
84 try {
85 if (!ffmpegPath) return null;
86 await ensureLib();
87 const img = new WebP.Image();
88 await img.load(srcPath);
89 if (!img.hasAnim || !img.anim || !Array.isArray(img.anim.frames) || img.anim.frames.length < 2) return null;
90 const W = img.width, H = img.height;
91 const fps = Math.max(1, Math.min(30, Math.round(1000 / (img.anim.frames[0].delay || 100))));
92 await fs.promises.mkdir(outDir, { recursive: true });
93 rawPath = path.join(outDir, baseName + '.rgba.tmp');
94 await fs.promises.writeFile(rawPath, await compositeFrames(img)); // full composited W×H frames
95 const videoPath = path.join(outDir, baseName + '.mp4');
96 const posterPath = path.join(outDir, baseName + '.jpg');
97 await execFileP(ffmpegPath, ['-hide_banner', '-loglevel', 'error',
98 '-f', 'rawvideo', '-pix_fmt', 'rgba', '-s', `${W}x${H}`, '-r', String(fps), '-i', rawPath,
99 '-vf', 'pad=ceil(iw/2)*2:ceil(ih/2)*2', // yuv420p needs even dimensions
100 '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', '-an', '-y', videoPath],
101 { timeout: 60000 });
102 await execFileP(ffmpegPath, ['-hide_banner', '-loglevel', 'error',
103 '-f', 'rawvideo', '-pix_fmt', 'rgba', '-s', `${W}x${H}`, '-i', rawPath,
104 '-frames:v', '1', '-y', posterPath], { timeout: 30000 });
105 return { videoPath, posterPath };
106 } catch (e) {
107 console.warn('[videocover] animated webp → mp4 failed:', e.message);
108 return null;
109 } finally {
110 if (rawPath) try { await fs.promises.unlink(rawPath); } catch { /* ignore */ }
111 }
112}
113
114// An uploaded video → muted loop MP4 (scaled ≤1280w, capped 60s) + JPG poster. ffmpeg decodes
115// every video format, so no node-webpmux here. Returns { videoPath, posterPath } or null.
116export async function videoToLoop(srcPath, outDir, baseName) {
117 try {
118 if (!ffmpegPath) return null;
119 await fs.promises.mkdir(outDir, { recursive: true });
120 const videoPath = path.join(outDir, baseName + '.mp4');
121 const posterPath = path.join(outDir, baseName + '.jpg');
122 await execFileP(ffmpegPath, ['-hide_banner', '-loglevel', 'error',
123 '-i', srcPath, '-t', String(MAX_SECONDS),
124 '-vf', "scale='min(1280,iw)':-2,pad=ceil(iw/2)*2:ceil(ih/2)*2",
125 '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', '-an', '-y', videoPath],
126 { timeout: 120000 });
127 await execFileP(ffmpegPath, ['-hide_banner', '-loglevel', 'error',
128 '-i', videoPath, '-frames:v', '1', '-y', posterPath], { timeout: 30000 });
129 return { videoPath, posterPath };
130 } catch (e) {
131 console.warn('[videocover] video → loop failed:', e.message);
132 return null;
133 }
134}
135
136export default { isAnimatedWebp, animatedWebpToVideo, videoToLoop };
Note: See TracBrowser for help on using the repository browser.