### Basic FFmpeg Command Example Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/options_audio.js.html A simple example demonstrating how to create an FFmpeg command, set an input, specify an output, and run the process. ```javascript const ffmpeg = require('fluent-ffmpeg'); const command = ffmpeg('input.mp4'); command .output('output.avi') .on('end', function() { console.log('Processing finished successfully'); }) .on('error', function(err) { console.error('Error:', err.message); }) .run(); ``` -------------------------------- ### fluent-ffmpeg Preset Module Example (divx.js) Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/index.html An example of a preset module for fluent-ffmpeg. The `load` function configures various video and audio settings for the ffmpeg command. ```javascript exports.load = function(ffmpeg) { ffmpeg .format('avi') .videoBitrate('1024k') .videoCodec('mpeg4') .size('720x?') .audioBitrate('128k') .audioChannels(2) .audioCodec('libmp3lame') .outputOptions(['-vtag DIVX']); }; ``` -------------------------------- ### Installation via npm Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/README.md Installs the fluent-ffmpeg module using npm, the Node.js package manager. ```sh npm install fluent-ffmpeg ``` -------------------------------- ### Running Tests Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/index.html Instructions for running unit tests and generating coverage reports. Requires npm dependencies to be installed. ```bash npm install make test make test-cov ``` -------------------------------- ### ffprobe Shell Command Example Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/README.md An example of the equivalent ffprobe command executed in the shell to retrieve metadata in JSON format. This demonstrates the underlying tool used by the library. ```sh $ ffprobe -of json -show_streams -show_format /path/to/file.avi ``` -------------------------------- ### FFmpeg Process Start Event Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/README.md The 'start' event is emitted immediately after the FFmpeg process has been spawned. It provides the complete command line used to start FFmpeg as an argument, allowing you to log or inspect the command. ```js ffmpeg('/path/to/file.avi') .on('start', function(commandLine) { console.log('Spawned Ffmpeg with command: ' + commandLine); }); ``` -------------------------------- ### Run Tests Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/README.md Commands to install npm dependencies and run unit tests for the project. ```shell $ npm install ``` ```shell $ make test ``` -------------------------------- ### Save FFmpeg Output to File Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/index.html Starts FFmpeg processing and saves the output to a specified file. This is syntactic sugar for calling output() and run(). Includes example of setting codecs, size, and event handlers. ```javascript ffmpeg('/path/to/file.avi') .videoCodec('libx264') .audioCodec('libmp3lame') .size('320x240') .on('error', function(err) { console.log('An error occurred: ' + err.message); }) .on('end', function() { console.log('Processing finished !'); }) .save('/path/to/output.mp4'); ``` -------------------------------- ### FFmpeg Process Started Event Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/index.html Emitted just after FFmpeg has been spawned. Provides the full command line used as an argument. ```javascript ffmpeg('/path/to/file.avi') .on('start', function(commandLine) { console.log('Spawned Ffmpeg with command: ' + commandLine); }); ``` -------------------------------- ### Pretty Print Example Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/capabilities.js.html A simple utility function to pretty print output, likely used for debugging or displaying formatted data. ```javascript prettyPrint(); ``` -------------------------------- ### Pretty Print Example Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/ffprobe.js.html A simple utility function to pretty print output, likely used for debugging or displaying formatted data. ```javascript prettyPrint(); ``` -------------------------------- ### Installation as a submodule Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/README.md Adds the fluent-ffmpeg library as a Git submodule to your project. ```sh git submodule add git://github.com/thedave42/node-fluent-ffmpeg.git vendor/fluent-ffmpeg ``` -------------------------------- ### Execute FFmpeg Commands Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/index.html Starts FFmpeg processing, useful for producing multiple outputs. Avoid using with other processing methods like save(), pipe(), or screenshots(). ```javascript ffmpeg('/path/to/file.avi') .output('screenshot.png') .noAudio() .seek('3:00') .output('small.avi') .audioCodec('copy') .size('320x200') .output('big.avi') .audioCodec('copy') .size('640x480') .on('error', function(err) { console.log('An error occurred: ' + err.message); }) .on('end', function() { console.log('Processing finished !'); }) .run(); ``` -------------------------------- ### Kill FFmpeg Process Example Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/README.md Demonstrates how to kill an FFmpeg process using the `kill` method. This example shows suspending the process with SIGSTOP, resuming with SIGCONT, and also how to kill the process after a timeout. ```js var command = ffmpeg('/path/to/video.avi') .videoCodec('libx264') .audioCodec('libmp3lame') .on('start', function() { // Send SIGSTOP to suspend ffmpeg command.kill('SIGSTOP'); doSomething(function() { // Send SIGCONT to resume ffmpeg command.kill('SIGCONT'); }); }) .save('/path/to/output.mp4'); // Kill ffmpeg after 60 seconds anyway setTimeout(function() { command.on('error', function() { console.log('Ffmpeg has been killed'); }); command.kill(); }, 60000); ``` -------------------------------- ### Querying FFmpeg Capabilities Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/options_videosize.js.html This section details how to query the capabilities of the installed FFmpeg executable using node-fluent-ffmpeg. It allows developers to understand what codecs, formats, and options are supported by their FFmpeg build. ```javascript const command = ffmpeg(); command.getAvailableCodecs(function(err, codecs) { if (err) { console.error('Error getting codecs:', err); } else { console.log('Available codecs:', codecs); } }); command.getAvailableFormats(function(err, formats) { if (err) { console.error('Error getting formats:', err); } else { console.log('Available formats:', formats); } }); ``` -------------------------------- ### FfmpegCommand Class - Processing Methods Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/options_videosize.js.html This section covers methods related to the actual processing and execution of FFmpeg commands. It includes starting the process, handling progress, and managing the lifecycle of the FFmpeg execution. ```javascript const command = ffmpeg('input.mp4'); command.on('progress', function(progress) { console.log('Processing: ' + progress.percent + '% done'); }); command.on('end', function() { console.log('Processing finished successfully'); }); command.on('error', function(err) { console.error('Error during processing:', err.message); }); command.output('output.mp4').run(); ``` -------------------------------- ### Querying FFmpeg Capabilities Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/fluent-ffmpeg.js.html Methods to retrieve lists of available filters, codecs, and formats supported by the FFmpeg installation. These methods accept an optional callback function to handle the results asynchronously. ```javascript FfmpegCommand.availableFilters = FfmpegCommand.getAvailableFilters = function(callback) { (new FfmpegCommand()).availableFilters(callback); }; FfmpegCommand.availableCodecs = FfmpegCommand.getAvailableCodecs = function(callback) { (new FfmpegCommand()).availableCodecs(callback); }; FfmpegCommand.availableFormats = FfmpegCommand.getAvailableFormats = function(callback) { (new FfmpegCommand()).availableFormats(callback); }; ``` -------------------------------- ### FfmpegCommand#run (exec, execute) Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/processor.js.html Executes the configured FFmpeg command. It checks for the presence of at least one output, identifies input and output streams, and manages the command execution lifecycle, emitting 'start', 'error', and 'end' events. ```javascript proto.exec = proto.execute = proto.run = function() { var self = this; // Check if at least one output is present var outputPresent = this._outputs.some(function(output) { return 'target' in output; }); if (!outputPresent) { throw new Error('No output specified'); } // Get output stream if any var outputStream = this._outputs.filter(function(output) { return typeof output.target !== 'string'; })[0]; // Get input stream if any var inputStream = this._inputs.filter(function(input) { return typeof input.source !== 'string'; })[0]; // Ensure we send 'end' or 'error' only once var ended = false; function emitEnd(err, stdout, stderr) { if (!ended) { ended = true; if (err) { self.emit('error', err, stdout, stderr); } else { self.emit('end', stdout, stderr); } } } self._prepare(function(err, args) { if (err) { return emitEnd(err); } // Run ffmpeg self._spawnFfmpeg( args, { captureStdout: !outputStream, niceness: self.options.niceness, cwd: self.options.cwd }, function processCB(ffmpegProc, stdoutRing, stderrRing) { self.ffmpegProc = ffmpegProc; self.emit('start', 'ffmpeg ' + args.join(' ')); // Pipe input stream if any if (inputStream) { inputStream.source.on('error', function(err) { emitEnd(new Error('Input stream error: ' + err.message)); ffmpegProc.kill(); }); inputStream.source.resume(); inputStream.source.pipe(ffmpegProc.stdin); // Set stdin error handler on ffmpeg (prevents nodejs catching the error, but // ffmpeg will fail anyway, so no need to actually handle anything) ffmpegProc.stdin.on('error', function() {}); } } ); }); }; ``` -------------------------------- ### FFmpeg Event Handlers Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/FfmpegCommand.html This section describes the various event handlers available in node-fluent-ffmpeg for monitoring FFmpeg command execution. It covers events like 'start', 'error', 'stderr', and 'progress', detailing their parameters and purpose. ```javascript #### start Emitted just after ffmpeg has been spawned. ##### Parameters: Name Type Description `command` String ffmpeg command line Source: * [processor.js](processor.js.html), [line 31](processor.js.html#line31) ``` ```javascript #### error Emitted when an error happens when preparing or running a command ##### Parameters: Name Type Description `error` Error error object `stdout` String | null ffmpeg stdout, unless outputting to a stream `stderr` String | null ffmpeg stderr Source: * [processor.js](processor.js.html), [line 70](processor.js.html#line70) ``` ```javascript #### stderr Emitted when ffmpeg outputs to stderr ##### Parameters: Name Type Description `line` String stderr output line Source: * [processor.js](processor.html), [line 51](processor.js.html#line51) ``` ```javascript #### progress Emitted when ffmpeg reports progress information ##### Parameters: Name Type Description `progress` Object progress object ###### Properties Name Type Argument Description `frames` Number number of frames transcoded `currentFps` Number current processing speed in frames per second `currentKbps` Number current output generation speed in kilobytes per second `targetSize` Number current output file size `timemark` String current video timemark `percent` Number processing progress (may not be available depending on input) Source: * [processor.js](processor.js.html), [line 38](processor.js.html#line38) ``` ```javascript ##### Parameters: Name Type Argument Description `filenames|stdout` Array | String | null generated filenames when taking screenshots, ffmpeg stdout when not outputting to a stream, null otherwise `stderr` String | null ffmpeg stderr ``` -------------------------------- ### Creating an FFmpeg Command Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/index.html Demonstrates how to instantiate FFmpeg commands using the fluent-ffmpeg module. It shows different ways to initialize a command with input files, streams, or configuration objects. ```javascript var FfmpegCommand = require('fluent-ffmpeg'); var command = new FfmpegCommand(); // Or without 'new' var ffmpeg = require('fluent-ffmpeg'); var command = ffmpeg(); // With input file var command = ffmpeg('/path/to/file.avi'); // With readable stream var command = ffmpeg(fs.createReadStream('/path/to/file.avi')); // With configuration object var command = ffmpeg({ option: "value", ... }); // With input file and configuration object var command = ffmpeg('/path/to/file.avi', { option: "value", ... }); ``` -------------------------------- ### Creating an FFmpeg Command Instance Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/README.md Demonstrates how to create a new FFmpeg command instance using the fluent-ffmpeg constructor, either with or without the 'new' keyword. ```javascript var FfmpegCommand = require('fluent-ffmpeg'); var command = new FfmpegCommand(); ``` ```javascript var ffmpeg = require('fluent-ffmpeg'); var command = ffmpeg(); ``` -------------------------------- ### Initializing FFmpeg Command with Input Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/README.md Shows how to initialize an FFmpeg command with various types of input, including file paths, readable streams, and configuration objects. ```javascript var command = ffmpeg('/path/to/file.avi'); ``` ```javascript var command = ffmpeg(fs.createReadStream('/path/to/file.avi')); ``` ```javascript var command = ffmpeg({ option: "value", ... }); ``` ```javascript var command = ffmpeg('/path/to/file.avi', { option: "value", ... }); ``` -------------------------------- ### Input Start Time Seeking Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/index.html Shows how to seek to a specific start time for an input using .seekInput() or its alias .setStartTime(). The time can be provided as seconds or a timestamp string. ```javascript ffmpeg('/path/to/file.avi').seekInput(134.5); ``` ```javascript ffmpeg('/path/to/file.avi').seekInput('2:14.500'); ``` -------------------------------- ### FfmpegCommand API Documentation Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/fluent-ffmpeg.js.html Provides details on the FfmpegCommand class, including its constructor and the clone method. The constructor sets up FFmpeg command execution with various configuration options. The clone method allows for creating a copy of an existing command instance to apply different transformations or save multiple versions. ```APIDOC FfmpegCommand: __constructor(input?: String|ReadableStream, options?: Object) Creates an ffmpeg command instance. Can be called with or without the 'new' operator. The 'input' parameter may be specified as 'options.source' instead (or passed later with the addInput method). Parameters: input (String|ReadableStream): input file path or readable stream. options (Object): command options. logger (Object): logger object with 'error', 'warning', 'info' and 'debug' methods. niceness (Number): ffmpeg process niceness, ignored on Windows (defaults to 0). priority (Number): alias for `niceness`. presets (String): directory to load presets from (defaults to "fluent-ffmpeg/lib/presets"). preset (String): alias for `presets`. stdoutLines (Number): maximum lines of ffmpeg output to keep in memory (use 0 for unlimited, defaults to 100). timeout (Number): ffmpeg processing timeout in seconds. source (String|ReadableStream): alias for the `input` parameter. clone(): FfmpegCommand Clones an ffmpeg command. This method is useful when you want to process the same input multiple times. It returns a new FfmpegCommand instance with the exact same options. All options set _after_ the clone() call will only be applied to the instance it has been called on. Example: var command = ffmpeg('/path/to/source.avi') .audioCodec('libfaac') .videoCodec('libx264') .format('mp4'); command.clone() .size('320x200') .save('/path/to/output-small.mp4'); command.clone() .size('640x400') .save('/path/to/output-medium.mp4'); command.save('/path/to/output-original-size.mp4'); Returns: FfmpegCommand: A new FfmpegCommand instance with cloned options. ``` -------------------------------- ### Change FFmpeg Process Priority Example Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/README.md Illustrates how to control the priority of an FFmpeg process using the `renice` method. The example shows setting an initial niceness value and then adjusting it after a delay. ```js // Set startup niceness var command = ffmpeg('/path/to/file.avi') .renice(5) .save('/path/to/output.mp4'); // Command takes too long, raise its priority setTimeout(function() { command.renice(-5); }, 60000); ``` -------------------------------- ### Setting Binary Paths Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/index.html Allows manual setting of paths for ffmpeg, ffprobe, and flvtool2/flvmeta executables. This is useful when these binaries are not in the system's PATH. ```APIDOC Ffmpeg.setFfmpegPath(path) - Sets the full path to the ffmpeg binary. - Argument `path` is a string. Ffmpeg.setFfprobePath(path) - Sets the full path to the ffprobe binary. - Argument `path` is a string. Ffmpeg.setFlvtoolPath(path) - Sets the full path to the flvtool2 or flvmeta binary. - Argument `path` is a string. ``` -------------------------------- ### Start Processing with Multiple Outputs Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/README.md Starts processing with specified outputs. This method is useful for producing multiple outputs. Avoid using run() when calling other processing methods like save(), pipe(), or screenshots(). ```js ffmpeg('/path/to/file.avi') .output('screenshot.png') .noAudio() .seek('3:00') .output('small.avi') .audioCodec('copy') .size('320x200') .output('big.avi') .audioCodec('copy') .size('640x480') .on('error', function(err) { console.log('An error occurred: ' + err.message); }) .on('end', function() { console.log('Processing finished !'); }) .run(); ``` -------------------------------- ### FfmpegCommand Methods Overview Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/ffprobe.js.html This section outlines the various categories of methods available within the FfmpegCommand class, including audio, video, input, output, and custom options. ```APIDOC FfmpegCommand: Audio methods Capabilities methods Custom options methods Input methods Metadata methods Miscellaneous methods Other methods Output methods Processing methods Video methods Video size methods ``` -------------------------------- ### FfmpegCommand Constructor Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/fluent-ffmpeg.js.html Initializes a new FFmpeg command instance. It can be called with or without the 'new' operator. The input source can be provided during construction or later using the addInput method. Options for logging, niceness, presets, and timeouts can be configured. ```javascript function FfmpegCommand(input, options) { // Make 'new' optional if (!(this instanceof FfmpegCommand)) { return new FfmpegCommand(input, options); } EventEmitter.call(this); if (typeof input === 'object' && !('readable' in input)) { // Options object passed directly options = input; } else { // Input passed first options = options || {}; options.source = input; } // Add input if present this._inputs = []; if (options.source) { this.input(options.source); } // Add target-less output for backwards compatibility this._outputs = []; this.output(); // Create argument lists var self = this; ['_global', '_complexFilters'].forEach(function(prop) { self[prop] = utils.args(); }); // Set default option values options.stdoutLines = 'stdoutLines' in options ? options.stdoutLines : 100; options.presets = options.presets || options.preset || path.join(__dirname, 'presets'); options.niceness = options.niceness || options.priority || 0; // Save options this.options = options; // Setup logger this.logger = options.logger || { debug: function() {}, info: function() {}, warn: function() {}, error: function() {} }; } ``` -------------------------------- ### Spawn Ffmpeg Process Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/processor.js.html This method is responsible for spawning an ffmpeg process. It handles argument parsing, options configuration (like niceness and working directory), and callback management for process creation and completion. It also includes logic for finding the ffmpeg executable. ```APIDOC /** * Spawn an ffmpeg process * * The 'options' argument may contain the following keys: * - 'niceness': specify process niceness, ignored on Windows (default: 0) * - `cwd`: change working directory * - 'captureStdout': capture stdout and pass it to 'endCB' as its 2nd argument (default: false) * - 'stdoutLines': override command limit (default: use command limit) * * The 'processCB' callback, if present, is called as soon as the process is created and * receives a nodejs ChildProcess object. It may not be called at all if an error happens * before spawning the process. * * The 'endCB' callback is called either when an error occurs or when the ffmpeg process finishes. * * @method FfmpegCommand#_spawnFfmpeg * @param {Array} args ffmpeg command line argument list * @param {Object} [options] spawn options (see above) * @param {Function} [processCB] callback called with process object and stdout/stderr ring buffers when process has been created * @param {Function} endCB callback called with error (if applicable) and stdout/stderr ring buffers when process finished * @private */ proto._spawnFfmpeg = function(args, options, processCB, endCB) { // Enable omitting options if (typeof options === 'function') { endCB = processCB; processCB = options; options = {}; } // Enable omitting processCB if (typeof endCB === 'undefined') { endCB = processCB; processCB = function() {}; } var maxLines = 'stdoutLines' in options ? options.stdoutLines : this.options.stdoutLines; // Find ffmpeg this._getFfmpegPath(function(err, command) { if (err) { return endCB(err); } else if (!command || command.length === 0) { return endCB(new Error('Cannot find ffmpeg')); } // Apply niceness ``` -------------------------------- ### Pretty Print Example Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/options_custom.js.html A simple utility function to pretty print output, likely used for debugging or displaying formatted data. ```javascript prettyPrint(); ``` -------------------------------- ### fluent-ffmpeg API: preset() Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/index.html Applies a preset to the ffmpeg command. Presets can be module names (loaded from a specified directory) or functions that configure the command. ```APIDOC preset(preset: string | function): FfmpegCommand Aliases: usingPreset() Applies a preset to the ffmpeg command. Parameters: preset: The name of a preset module or a function that takes an FfmpegCommand instance. Returns: The FfmpegCommand instance for chaining. ``` -------------------------------- ### Seek Time Configuration Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/FfmpegCommand.html Specifies the output seek time for the FFmpeg process. This allows precise control over where the output media should start. ```APIDOC seek(seek) - Specify output seek time. - Parameters: - seek (String | Number): Seek time in seconds or as a '[hh:[mm:]]ss[.xxx]' string. - Returns: FfmpegCommand - Alias: seekOutput ``` -------------------------------- ### Seek Input Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/README.md Sets the input start time for decoding. The time can be a number in seconds or a timestamp string. The alias setStartTime() is also available. ```javascript ffmpeg('/path/to/file.avi').seekInput(134.5); ffmpeg('/path/to/file.avi').seekInput('2:14.500'); ``` -------------------------------- ### FfmpegCommand Class Initialization Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/FfmpegCommand.html Initializes a new FfmpegCommand instance to create FFmpeg commands. It can be instantiated with or without the 'new' operator. The input source can be provided during initialization or later using the addInput method. Options can be passed to configure the command, including logger, niceness, presets, stdoutLines, and timeout. ```APIDOC FfmpegCommand: new FfmpegCommand(input, options) input: String | ReadableStream (optional) - input file path or readable stream options: Object (optional) - command options logger: Object (optional) - logger object with 'error', 'warning', 'info' and 'debug' methods niceness: Number (optional) - ffmpeg process niceness, ignored on Windows priority: Number (optional) - alias for niceness presets: String (optional) - directory to load presets from preset: String (optional) - alias for presets stdoutLines: String (optional) - maximum lines of ffmpeg output to keep in memory, use 0 for unlimited timeout: Number (optional) - ffmpeg processing timeout in seconds source: String | ReadableStream (optional) - alias for the input parameter ``` -------------------------------- ### Get FFprobe Path Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/capabilities.js.html Resolves the path to the ffprobe binary. It checks the manually set path, FFPROBE_PATH environment variable, system PATH, and finally the directory containing ffmpeg. ```APIDOC FfmpegCommand#_getFfprobePath Check for ffprobe availability If the FFPROBE_PATH environment variable is set, try to use it. If it is unset or incorrect, try to find ffprobe in the PATH instead. If this still fails, try to find ffprobe in the same directory as ffmpeg. @method FfmpegCommand#_getFfprobePath @param {Function} callback callback with signature (err, path) @private ``` ```javascript proto._getFfprobePath = function(callback) { var self = this; if ('ffprobePath' in cache) { return callback(null, cache.ffprobePath); } async.waterfall([ // Try FFPROBE_PATH function(cb) { if (process.env.FFPROBE_PATH) { fs.exists(process.env.FFPROBE_PATH, function(exists) { cb(null, exists ? process.env.FFPROBE_PATH : ''); }); } else { cb(null, ''); } }, // Search in the PATH function(ffprobe, cb) { if (ffprobe.length) { return cb(null, ffprobe); } ``` -------------------------------- ### Use Preset - Miscellaneous Options Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/options_misc.js.html Allows the use of predefined presets for FFmpeg configurations. Presets can be specified by name (string) or as a function. If a string is provided, it attempts to load a preset module from the configured presets directory. If the loaded module has a `load` function, it will be called with the FFmpeg command instance. If a function is provided, it's executed directly with the FFmpeg command instance. ```javascript proto.usingPreset = proto.preset = function(preset) { if (typeof preset === 'function') { preset(this); } else { try { var modulePath = path.join(this.options.presets, preset); var module = require(modulePath); if (typeof module.load === 'function') { module.load(this); } else { throw new Error('preset ' + modulePath + ' has no load() function'); } } catch (err) { throw new Error('preset ' + modulePath + ' could not be loaded: ' + err.message); } } return this; }; ``` -------------------------------- ### Get FFmpeg Path Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/capabilities.js.html Resolves the path to the ffmpeg binary. It first checks for a manually set path, then the FFMPEG_PATH environment variable, and finally searches the system's PATH. ```APIDOC FfmpegCommand#_getFfmpegPath Check for ffmpeg availability If the FFMPEG_PATH environment variable is set, try to use it. If it is unset or incorrect, try to find ffmpeg in the PATH instead. @method FfmpegCommand#_getFfmpegPath @param {Function} callback callback with signature (err, path) @private ``` ```javascript proto._getFfmpegPath = function(callback) { if ('ffmpegPath' in cache) { return callback(null, cache.ffmpegPath); } async.waterfall([ // Try FFMPEG_PATH function(cb) { if (process.env.FFMPEG_PATH) { fs.exists(process.env.FFMPEG_PATH, function(exists) { if (exists) { cb(null, process.env.FFMPEG_PATH); } else { cb(null, ''); } }); } else { cb(null, ''); } }, // Search in the PATH function(ffmpeg, cb) { if (ffmpeg.length) { return cb(null, ffmpeg); } utils.which('ffmpeg', function(err, ffmpeg) { cb(err, ffmpeg); }); } ], function(err, ffmpeg) { if (err) { callback(err); } else { callback(null, cache.ffmpegPath = (ffmpeg || '')); } }); }; ``` -------------------------------- ### fluent-ffmpeg API Documentation Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/README.md Provides an overview of the fluent-ffmpeg API for Node.js, detailing methods for command creation, input/output handling, filters, and options. ```APIDOC ffmpeg(input[, options]) - Creates a new ffmpeg command. - input: Path to the input file or readable stream. - options: Optional configuration object. output(target[, options]) - Adds an output to the command. - Aliases: addOutput() - target: Output filename or writable stream. - options: Optional object passed to ffmpeg output stream pipe(). duration(time) - Forces ffmpeg to stop transcoding after a specific output duration. - Aliases: withDuration(), setDuration() - time: Number (seconds) or timestamp string (e.g., '[[hh:]mm:]ss[.xxx]'). seek(time) - Seeks streams before encoding into the output. - Aliases: seekOutput() - time: Number (seconds) or timestamp string. format(format) - Sets the output format. - Aliases: withOutputFormat(), toFormat(), outputFormat() - format: The desired output format (e.g., 'flv'). flvmeta() - Updates FLV metadata after transcoding using flvmeta or flvtool2. - Aliases: updateFlvMetadata() - Note: Does not work with streams and is only useful for FLV output. outputOptions(option...) - Adds custom output options to the ffmpeg command. - Aliases: outputOption(), addOutputOption(), addOutputOptions(), withOutputOption(), withOutputOptions(), addOption(), addOptions() - option: Can be a single option string, an array of option strings, or command-line tokens passed as separate arguments. run() - Starts processing the ffmpeg command. - Should be called after all inputs, outputs, and options are configured. complexFilter(filters[, outputs]) - Applies complex filters to the command. - filters: An array of filter descriptions or a single filter string. - outputs: Optional array specifying the output pads for the filters. ``` -------------------------------- ### Input Seek Time Configuration Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/FfmpegCommand.html Specifies the input seek time for the last specified input. This is used to set the starting point of the media processing from the input side. ```APIDOC seekInput(seek) - Specify input seek time for the last specified input. - Parameters: - seek (String | Number): Seek time in seconds or as a '[[hh:]mm:]ss[.xxx]' string. - Returns: FfmpegCommand - Aliases: setStartTime, seekTo ``` -------------------------------- ### FFmpeg Filter Specifications Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/options_custom.js.html Examples of filter specification objects used within a complex filter graph. Each object defines a filter, its options, input streams, and output streams. ```javascript // Create stream 'green' by cancelling red and blue channels from stream 'b' { filter: 'lutrgb', options: { r: 0, b: 0 }, inputs: 'b', outputs: 'green' }, // Create stream 'blue' by cancelling red and green channels from stream 'c' { filter: 'lutrgb', options: { r: 0, g: 0 }, inputs: 'c', outputs: 'blue' }, // Pad stream 'red' to 3x width, keeping the video on the left, and name output 'padded' { filter: 'pad', options: { w: 'iw*3', h: 'ih' }, inputs: 'red', outputs: 'padded' }, // Overlay 'green' onto 'padded', moving it to the center, and name output 'redgreen' { filter: 'overlay', options: { x: 'w', y: 0 }, inputs: ['padded', 'green'], outputs: 'redgreen' }, // Overlay 'blue' onto 'redgreen', moving it to the right { filter: 'overlay', options: { x: '2*w', y: 0 }, inputs: ['redgreen', 'blue'] } ``` -------------------------------- ### FfmpegCommand Class - Capabilities Methods Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/options_videosize.js.html This section details methods for querying FFmpeg's capabilities, such as available codecs and formats. These methods help in understanding the environment FFmpeg is running in and what operations are supported. ```javascript const command = ffmpeg(); command.getAvailableCodecs(function(err, codecs) { if (!err) console.log('Codecs:', codecs); }); command.getAvailableFormats(function(err, formats) { if (!err) console.log('Formats:', formats); }); command.getAvailableFilters(function(err, filters) { if (!err) console.log('Filters:', filters); }); ``` -------------------------------- ### Using Presets with fluent-ffmpeg Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/index.html Demonstrates how to apply predefined or custom presets to ffmpeg commands. Presets can be loaded from modules or defined as functions. Preset modules must export a `load` function, and custom presets are functions that accept an FfmpegCommand instance. ```javascript ffmpeg('/path/to/file.avi').preset('divx'); ffmpeg('/path/to/file.avi', { presets: '/my/presets' }).preset('foo'); function myPreset(command) { command.format('avi').size('720x?'); } ffmpeg('/path/to/file.avi').preset(myPreset); ``` -------------------------------- ### FFmpeg Filter Specifications Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/custom.js.html Examples of filter specification objects used within a complex filter graph. Each object defines a filter, its options, input streams, and output streams. ```javascript // Create stream 'green' by cancelling red and blue channels from stream 'b' { filter: 'lutrgb', options: { r: 0, b: 0 }, inputs: 'b', outputs: 'green' }, // Create stream 'blue' by cancelling red and green channels from stream 'c' { filter: 'lutrgb', options: { r: 0, g: 0 }, inputs: 'c', outputs: 'blue' }, // Pad stream 'red' to 3x width, keeping the video on the left, and name output 'padded' { filter: 'pad', options: { w: 'iw*3', h: 'ih' }, inputs: 'red', outputs: 'padded' }, // Overlay 'green' onto 'padded', moving it to the center, and name output 'redgreen' { filter: 'overlay', options: { x: 'w', y: 0 }, inputs: ['padded', 'green'], outputs: 'redgreen' }, // Overlay 'blue' onto 'redgreen', moving it to the right { filter: 'overlay', options: { x: '2*w', y: 0 }, inputs: ['redgreen', 'blue'] } ``` -------------------------------- ### Command Cloning Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/FfmpegCommand.html Clones the current FFmpeg command instance. This is useful for creating multiple variations of a command from a common starting point, allowing independent modification of subsequent options. ```APIDOC clone() - Clone an ffmpeg command. - Description: This method is useful when you want to process the same input multiple times. It returns a new FfmpegCommand instance with the exact same options. All options set _after_ the clone() call will only be applied to the instance it has been called on. - Returns: FfmpegCommand - Example: var command = ffmpeg('/path/to/source.avi') .audioCodec('libfaac') .videoCodec('libx264') .format('mp4'); command.clone() .size('320x200') .save('/path/to/output-small.mp4'); command.clone() .size('640x400') .save('/path/to/output-medium.mp4'); command.save('/path/to/output-original-size.mp4'); ``` -------------------------------- ### Read Video Metadata with ffprobe Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/README.md Reads metadata from a video file using the ffprobe method. This is the primary way to get information about a video file's streams and format. ```js ffmpeg.ffprobe('/path/to/file.avi', function(err, metadata) { console.dir(metadata); }); ``` -------------------------------- ### Timemark and Size Configuration Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/recipes.js.html Demonstrates how to configure timemarks and parse various size formats (fixed, percentage, mixed) for video processing. Includes error handling for invalid size parameters. ```javascript config.timemarks.push((interval * (i + 1)) + '%'); } // Parse size option if ('size' in config) { var fixedSize = config.size.match(/^(\d+)x(\d+)$/); var fixedWidth = config.size.match(/^(\d+)x\?$/); var fixedHeight = config.size.match(/^\?x(\d+)$/); var percentSize = config.size.match(/^(\d+)%$/); if (!fixedSize && !fixedWidth && !fixedHeight && !percentSize) { throw new Error('Invalid size parameter: ' + config.size); } } ``` -------------------------------- ### FfmpegCommand Events Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/processor.js.html This section describes the various events emitted by the FfmpegCommand object during the ffmpeg process lifecycle. These events provide real-time feedback on the transcoding process, including start, progress, errors, and completion. ```APIDOC /** * Emitted just after ffmpeg has been spawned. * * @event FfmpegCommand#start * @param {String} command ffmpeg command line */ /** * Emitted when ffmpeg reports progress information * * @event FfmpegCommand#progress * @param {Object} progress progress object * @param {Number} progress.frames number of frames transcoded * @param {Number} progress.currentFps current processing speed in frames per second * @param {Number} progress.currentKbps current output generation speed in kilobytes per second * @param {Number} progress.targetSize current output file size * @param {String} progress.timemark current video timemark * @param {Number} [progress.percent] processing progress (may not be available depending on input) */ /** * Emitted when ffmpeg outputs to stderr * * @event FfmpegCommand#stderr * @param {String} line stderr output line */ /** * Emitted when ffmpeg reports input codec data * * @event FfmpegCommand#codecData * @param {Object} codecData codec data object * @param {String} codecData.format input format name * @param {String} codecData.audio input audio codec name * @param {String} codecData.audio_details input audio codec parameters * @param {String} codecData.video input video codec name * @param {String} codecData.video_details input video codec parameters */ /** * Emitted when an error happens when preparing or running a command * * @event FfmpegCommand#error * @param {Error} error error object * @param {String|null} stdout ffmpeg stdout, unless outputting to a stream * @param {String|null} stderr ffmpeg stderr */ /** * Emitted when a command finishes processing * * @event FfmpegCommand#end * @param {Array|String|null} [filenames|stdout] generated filenames when taking screenshots, ffmpeg stdout when not outputting to a stream, null otherwise * @param {String|null} stderr ffmpeg stderr */ ``` -------------------------------- ### Setting FFmpeg Executable Path Source: https://github.com/thedave42/node-fluent-ffmpeg/blob/master/doc/fluent-ffmpeg.js.html Provides static methods to configure the paths for the FFmpeg, FFprobe, and Flvtool2 executables. This is essential if these tools are not in the system's PATH. ```javascript FfmpegCommand.setFfmpegPath = function(path) { (new FfmpegCommand()).setFfmpegPath(path); }; FfmpegCommand.setFfprobePath = function(path) { (new FfmpegCommand()).setFfprobePath(path); }; FfmpegCommand.setFlvtoolPath = function(path) { (new FfmpegCommand()).setFlvtoolPath(path); }; ```