[WIP] Modify function to support GIF or MP4 format selection#133
Closed
[WIP] Modify function to support GIF or MP4 format selection#133
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Thanks for asking me to work on this. I will get started on it and keep this PR's description up to date as I form a plan and make progress.
Original prompt
tengo esto, pero me gustaria modificar la funcion, para que se pueda decidir si gif o .mp4, tambien le cambiaria el nombre import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const ffmpeg = require('fluent-ffmpeg');
import { getFFMPEG } from "./getFFMPEG";
import * as fs from "fs/promises";
import fsSync from "fs";
import path from "path";
const { ffmpegPath, ffprobePath } = getFFMPEG();
if (ffmpegPath && ffprobePath) {
ffmpeg.setFfmpegPath(ffmpegPath);
ffmpeg.setFfprobePath(ffprobePath);
}
function runFfmpegPromise(command: any): Promise {
return new Promise((resolve, reject) => {
command
.on("end", () => resolve())
.on("error", (err: any, stdout: any, stderr: any) => {
reject(new Error(String(err) + "\n" + String(stderr || stdout || "")));
})
.run();
});
}
/**
*/
async function createGif(folder: string, outputPath: string, fps: number) {
console.log("Creating GIF at:", outputPath);
console.log("Using frames from:", folder);
console.log("Frames per second (fps):", fps);
if (!folder || !outputPath) {
throw new Error("folder and outputPath are required");
}
if (!Number.isFinite(fps) || fps <= 0) {
throw new Error("fps must be a positive number");
}
// Leer entradas y filtrar nombres que sean solo dígitos + .jpg
const entries = await fs.readdir(folder);
const jpgRegex = /^(\d+).jpg$/i;
const matched = entries
.map((name) => {
const m = name.match(jpgRegex);
if (!m) return null;
return { name, num: parseInt(m[1], 10) };
})
.filter(Boolean) as { name: string; num: number }[];
if (matched.length === 0) {
throw new Error("No JPG files with numeric names found in folder: " + folder);
}
// Ordenar por valor numérico para mantener el orden aun con saltos
matched.sort((a, b) => a.num - b.num);
// Rutas absolutas de los frames en orden
const framePaths = matched.map((m) => path.resolve(folder, m.name));
// Asegurar que el directorio de salida exista
const outDir = path.dirname(outputPath);
if (!fsSync.existsSync(outDir)) {
await fs.mkdir(outDir, { recursive: true });
}
// Archivos temporales
const palettePath = path.join(outDir, ".tmp_palette.png");
const listPath = path.join(outDir, ".tmp_frames_list.txt");
// Construir contenido del archivo concat.
// Formato:
// file '/abs/path/to/frame1.jpg'
// duration 0.1
// ...
const frameDuration = 1 / fps;
let listContent = "";
for (const p of framePaths) {
const safePath = p.includes("'") ? p.replace(/'/g, "'\''") : p;
listContent +=
file '${safePath}'\n;listContent +=
duration ${frameDuration}\n;}
// Repetir último archivo para que ffmpeg respete la duración del último frame
const lastPath = framePaths[framePaths.length - 1];
const safeLastPath = lastPath.includes("'") ? lastPath.replace(/'/g, "'\''") : lastPath;
listContent +=
file '${safeLastPath}'\n;try {
// escribir el archivo temporal list.txt
await fs.writeFile(listPath, listContent, "utf8");
} finally {
// limpiar archivos temporales (ignorar errores)
try {
await fs.unlink(palettePath).catch(() => undefined);
} catch {}
try {
await fs.unlink(listPath).catch(() => undefined);
} catch {}
}
}
export { createGif };
✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.