"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getScaleFilter = exports.buildStreamSuffix = exports.runCommand = exports.getFFmpegVersion = exports.getFFmpeg = void 0;
const tslib_1 = require("tslib");
const fluent_ffmpeg_1 = tslib_1.__importDefault(require("fluent-ffmpeg"));
const core_utils_1 = require("../core-utils");
const logger_1 = require("../logger");
const config_1 = require("../../initializers/config");
const constants_1 = require("../../initializers/constants");
const lTags = (0, logger_1.loggerTagsFactory)('ffmpeg');
function getFFmpeg(input, type) {
    const command = (0, fluent_ffmpeg_1.default)(input, {
        niceness: type === 'live' ? constants_1.FFMPEG_NICE.LIVE : constants_1.FFMPEG_NICE.VOD,
        cwd: config_1.CONFIG.STORAGE.TMP_DIR
    });
    const threads = type === 'live'
        ? config_1.CONFIG.LIVE.TRANSCODING.THREADS
        : config_1.CONFIG.TRANSCODING.THREADS;
    if (threads > 0) {
        command.outputOption('-threads ' + threads);
    }
    return command;
}
exports.getFFmpeg = getFFmpeg;
function getFFmpegVersion() {
    return new Promise((res, rej) => {
        (0, fluent_ffmpeg_1.default)()._getFfmpegPath((err, ffmpegPath) => {
            if (err)
                return rej(err);
            if (!ffmpegPath)
                return rej(new Error('Could not find ffmpeg path'));
            return (0, core_utils_1.execPromise)(`${ffmpegPath} -version`)
                .then(stdout => {
                const parsed = stdout.match(/ffmpeg version .?(\d+\.\d+(\.\d+)?)/);
                if (!(parsed === null || parsed === void 0 ? void 0 : parsed[1]))
                    return rej(new Error(`Could not find ffmpeg version in ${stdout}`));
                let version = parsed[1];
                if (version.match(/^\d+\.\d+$/)) {
                    version += '.0';
                }
                return res(version);
            })
                .catch(err => rej(err));
        });
    });
}
exports.getFFmpegVersion = getFFmpegVersion;
function runCommand(options) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const { command, silent = false, job } = options;
        return new Promise((res, rej) => {
            let shellCommand;
            command.on('start', cmdline => { shellCommand = cmdline; });
            command.on('error', (err, stdout, stderr) => {
                if (silent !== true)
                    logger_1.logger.error('Error in ffmpeg.', Object.assign({ stdout, stderr, shellCommand }, lTags()));
                rej(err);
            });
            command.on('end', (stdout, stderr) => {
                logger_1.logger.debug('FFmpeg command ended.', Object.assign({ stdout, stderr, shellCommand }, lTags()));
                res();
            });
            if (job) {
                command.on('progress', progress => {
                    if (!progress.percent)
                        return;
                    job.updateProgress(Math.round(progress.percent))
                        .catch(err => logger_1.logger.warn('Cannot set ffmpeg job progress.', Object.assign({ err }, lTags())));
                });
            }
            command.run();
        });
    });
}
exports.runCommand = runCommand;
function buildStreamSuffix(base, streamNum) {
    if (streamNum !== undefined) {
        return `${base}:${streamNum}`;
    }
    return base;
}
exports.buildStreamSuffix = buildStreamSuffix;
function getScaleFilter(options) {
    if (options.scaleFilter)
        return options.scaleFilter.name;
    return 'scale';
}
exports.getScaleFilter = getScaleFilter;
//# sourceMappingURL=ffmpeg-commons.js.map