// A clide script: TypeScript run by the Bun inside CLIDE, using Bun's built-ins only. // It runs outside CLIDE too: bun sharp-gif.ts --fps 12 --width 480 --dest ~/Desktop --name party clip.mp4 import { $ } from "bun"; import { existsSync, statSync } from "node:fs"; import { tmpdir } from "node:os"; import { basename, extname, join } from "node:path"; import { parseArgs } from "node:util"; const { values, positionals } = parseArgs({ args: Bun.argv.slice(2), options: { fps: { type: "string", default: "12" }, width: { type: "string", default: "480" }, start: { type: "string" }, seconds: { type: "string" }, dest: { type: "string" }, name: { type: "string" }, }, allowPositionals: true, }); const fail = (message: string): never => { console.error(message); process.exit(1); }; const video = positionals[0] ?? fail("No video given."); const dest = values.dest ?? fail("No --dest folder given."); if (!Bun.which("ffmpeg")) fail("ffmpeg is not installed. On a Mac: brew install ffmpeg"); if (!(await Bun.file(video).exists())) fail(`The video is not there: ${video}`); if (!existsSync(dest) || !statSync(dest).isDirectory()) fail(`The folder is not there: ${dest}`); // The name the person gave, without .gif if they typed it; the video's own name when they gave none. // A GIF already there is never replaced: " 2", " 3", ... are added instead. const name = (values.name?.trim() || basename(video, extname(video))).replace(/\.gif$/i, ""); let out = join(dest, `${name}.gif`); for (let n = 2; existsSync(out); n++) out = join(dest, `${name} ${n}.gif`); // Trim first, when asked: -ss before -i seeks fast, -t limits the length. const trim = [...(values.start ? ["-ss", values.start] : []), ...(values.seconds ? ["-t", values.seconds] : [])]; const filters = `fps=${values.fps},scale=${values.width}:-1:flags=lanczos`; const palette = join(tmpdir(), `sharp-gif-${process.pid}.png`); // Two passes: build a palette from the clip itself, then use it. Sharper than ffmpeg's default. // $ passes each value as one argument, so names with spaces or quotes are safe. // .nothrow(): a failed step ends the script with a plain message, not a stack trace. console.log("Building the palette…"); const pass1 = await $`ffmpeg -y -v error ${trim} -i ${video} -vf ${`${filters},palettegen`} ${palette}`.nothrow(); if (pass1.exitCode !== 0) fail("ffmpeg could not read the video."); console.log("Writing the GIF…"); const pass2 = await $`ffmpeg -y -v error ${trim} -i ${video} -i ${palette} -lavfi ${`${filters} [x]; [x][1:v] paletteuse`} ${out}`.nothrow(); await $`rm -f ${palette}`.nothrow(); if (pass2.exitCode !== 0) fail("ffmpeg could not write the GIF."); console.log(`Saved to ${out}`); console.log(`Size: ${(Bun.file(out).size / 1024).toFixed(0)} KB`);