const path = require("path"); const fs = require("fs"); const { execFile } = require("child_process"); const configService = require("./configService"); const Video = require("../models/Video"); const { logToFile } = require("./logService"); // Limit concurrent ffmpeg jobs so a page full of missing thumbnails // doesn't start one heavy process per image request at once. const MAX_CONCURRENT_JOBS = 2; let activeJobs = 0; const jobQueue = []; function resolveFfmpeg() { try { const bin = require("ffmpeg-static"); if (bin && fs.existsSync(bin)) return bin; } catch { // ffmpeg-static not installed } return "ffmpeg"; // fall back to a system-wide ffmpeg on PATH } function extractFrame(ffmpeg, inputPath, outputPath, seek) { return new Promise((resolve, reject) => { execFile( ffmpeg, [ "-y", "-ss", seek, "-i", inputPath, "-frames:v", "1", "-vf", "scale=640:-2", "-q:v", "3", outputPath, ], { timeout: 60000, windowsHide: true }, (err) => (err ? reject(err) : resolve()), ); }); } function runLimited(job) { return new Promise((resolve, reject) => { const run = async () => { try { resolve(await job()); } catch (err) { reject(err); } finally { activeJobs -= 1; const next = jobQueue.shift(); if (next) { activeJobs += 1; next(); } } }; if (activeJobs < MAX_CONCURRENT_JOBS) { activeJobs += 1; run(); } else { jobQueue.push(run); } }); } /** * Generates a thumbnail for a video: extracts a frame at 1s (falls back * to frame 0 for very short videos) and stores `{uuid}.jpg` in * data/videos/thumbnails/. * * Returns the thumbnail filename on success, or null on failure. * Never throws — a missing thumbnail must not break requests. */ async function generateThumbnail(video) { try { // Re-check against the DB — the thumbnail may have been generated // since this video instance was loaded. const fresh = await Video.findByPk(video.id); if (!fresh) return null; const dataPath = configService.getSettings().userDataPath; const videosDir = path.join(dataPath, "videos"); const thumbDir = path.join(videosDir, "thumbnails"); const inputPath = path.join(videosDir, fresh.filename); if (!fs.existsSync(inputPath)) return null; const thumbName = `${fresh.filename.split(".")[0]}.jpg`; const outputPath = path.join(thumbDir, thumbName); // Already generated → just make sure the DB knows about it if (fs.existsSync(outputPath)) { if (!fresh.thumbnail_path) { await fresh.update({ thumbnail_path: thumbName }); } return thumbName; } fs.mkdirSync(thumbDir, { recursive: true }); const ffmpeg = resolveFfmpeg(); try { await extractFrame(ffmpeg, inputPath, outputPath, "1"); } catch { // very short videos — grab the first frame instead await extractFrame(ffmpeg, inputPath, outputPath, "0"); } if (!fs.existsSync(outputPath)) return null; await fresh.update({ thumbnail_path: thumbName }); logToFile(`Video Thumbnail | Generated for video ${fresh.id}`); return thumbName; } catch (err) { logToFile(`Video Thumbnail | Error for video ${video.id}`); logToFile(err); return null; } } const inFlight = new Map(); // videoId -> Promise /** * On-demand thumbnail generation. * - Per-video dedup: concurrent requests for the same video share one job. * - Global concurrency limit (MAX_CONCURRENT_JOBS ffmpeg processes). * Called only from the thumbnail endpoint, i.e. when a client actually * requests a thumbnail that doesn't exist yet. */ function ensureThumbnail(video) { if (inFlight.has(video.id)) return inFlight.get(video.id); const tracked = runLimited(() => generateThumbnail(video)); const shared = tracked.finally(() => { inFlight.delete(video.id); }); inFlight.set(video.id, shared); return shared; } module.exports = { ensureThumbnail, generateThumbnail };