chat-about-video
Version:
Chat about a video clip using ChatGPT hosted in OpenAI or Azure, or Gemini provided by Google
47 lines (46 loc) • 2.24 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractVideoFramesWithFfmpeg = void 0;
const tslib_1 = require("tslib");
/* eslint-disable max-params */
const promise_utils_1 = require("@handy-common-utils/promise-utils");
const node_child_process_1 = require("node:child_process");
const promises_1 = tslib_1.__importDefault(require("node:fs/promises"));
const node_path_1 = tslib_1.__importDefault(require("node:path"));
const node_util_1 = require("node:util");
const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
let ffmpegPath = 'ffmpeg';
try {
// eslint-disable-next-line unicorn/prefer-module
const ffmpeg = require('@ffmpeg-installer/ffmpeg');
ffmpegPath = ffmpeg.path;
}
catch (_a) {
// ignore error and expect ffmpeg is on system PATH
}
const extractVideoFramesWithFfmpeg = async (inputFile, outputDir, intervalSec, format = 'jpg', width, height, startSec = 0, endSec, limit) => {
const args1 = ['-y', '-accurate_seek', '-ss'];
const args2 = [
'-i',
inputFile,
'-frames:v',
'1',
...(width || height ? ['-vf', `scale=${width !== null && width !== void 0 ? width : (height ? '-1' : 'iw')}:${height !== null && height !== void 0 ? height : (width ? '-1' : 'ih')}`] : []),
];
const relativePaths = [];
await promises_1.default.mkdir(outputDir, { recursive: true });
for (let i = startSec; (endSec == null || i < endSec) && (limit == null || relativePaths.length <= limit); i += intervalSec) {
const fileName = `${i.toFixed(3).padStart(10, '0')}.${format}`;
const { stderr } = await execFileAsync(ffmpegPath, [...args1, `${i}`, ...args2, node_path_1.default.join(outputDir, fileName)]);
if (stderr && stderr.includes('Output file is empty, nothing was encoded')) {
break;
}
relativePaths.push(fileName);
}
return {
relativePaths,
// Try to clean up but ignore errors
cleanup: () => (0, promise_utils_1.inParallel)(5, relativePaths, (relativePath) => promises_1.default.unlink(node_path_1.default.join(outputDir, relativePath))),
};
};
exports.extractVideoFramesWithFfmpeg = extractVideoFramesWithFfmpeg;