UNPKG

fluent-ffmpeg

Version:
667 lines (598 loc) 69 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JSDoc: Index</title> <script src="scripts/prettify/prettify.js"> </script> <script src="scripts/prettify/lang-css.js"> </script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css"> </head> <body> <div id="main"> <h1 class="page-title">Index</h1> <h3> </h3> <section> <article><h1>Fluent ffmpeg-API for node.js <a href="http://travis-ci.org/fluent-ffmpeg/node-fluent-ffmpeg"><img src="https://secure.travis-ci.org/fluent-ffmpeg/node-fluent-ffmpeg.svg?branch=master" alt="Build Status"></a></h1><p>This library abstracts the complex command-line usage of ffmpeg into a fluent, easy to use node.js module. In order to be able to use this module, make sure you have <a href="http://www.ffmpeg.org">ffmpeg</a> installed on your system (including all necessary encoding libraries like libmp3lame or libx264).</p> <blockquote> <p>This is the documentation for fluent-ffmpeg 2.x. You can still access the code and documentation for fluent-ffmpeg 1.7 <a href="https://github.com/fluent-ffmpeg/node-fluent-ffmpeg/tree/1.x">here</a>.</p> </blockquote> <a name="installation"></a><h2>Installation</h2><p>Via npm:</p> <pre class="prettyprint source lang-sh"><code>$ npm install fluent-ffmpeg</code></pre><p>Or as a submodule:</p> <pre class="prettyprint source lang-sh"><code>$ git submodule add git://github.com/schaermu/node-fluent-ffmpeg.git vendor/fluent-ffmpeg</code></pre><a name="usage"></a><h2>Usage</h2><p>You will find a lot of usage examples (including a real-time streaming example using <a href="http://www.flowplayer.org">flowplayer</a> and <a href="https://github.com/visionmedia/express">express</a>!) in the <code>examples</code> folder.</p> <a name="prerequisites"></a><h3>Prerequisites</h3><h4>ffmpeg and ffprobe</h4><p>fluent-ffmpeg requires ffmpeg &gt;= 0.9 to work. It may work with previous versions but several features won't be available (and the library is not tested with lower versions anylonger).</p> <p>If the <code>FFMPEG_PATH</code> environment variable is set, fluent-ffmpeg will use it as the full path to the <code>ffmpeg</code> executable. Otherwise, it will attempt to call <code>ffmpeg</code> directly (so it should be in your <code>PATH</code>). You must also have ffprobe installed (it comes with ffmpeg in most distributions). Similarly, fluent-ffmpeg will use the <code>FFPROBE_PATH</code> environment variable if it is set, otherwise it will attempt to call it in the <code>PATH</code>.</p> <p>Most features should work when using avconv and avprobe instead of ffmpeg and ffprobe, but they are not officially supported at the moment.</p> <p><strong>Windows users</strong>: most probably ffmpeg and ffprobe will <em>not</em> be in your <code>%PATH</code>, so you <em>must</em> set <code>%FFMPEG_PATH</code> and <code>%FFPROBE_PATH</code>.</p> <p><strong>Debian/Ubuntu users</strong>: the official repositories have the ffmpeg/ffprobe executable in the <code>libav-tools</code> package, and they are actually rebranded avconv/avprobe executables (avconv is a fork of ffmpeg). They should be mostly compatible, but should you encounter any issue, you may want to use the real ffmpeg instead. You can either compile it from source or find a pre-built .deb package at https://ffmpeg.org/download.html (For Ubuntu, the <code>ppa:jon-severinsson/ffmpeg</code> PPA provides recent builds).</p> <h4>flvtool2 or flvmeta</h4><p>If you intend to encode FLV videos, you must have either flvtool2 or flvmeta installed and in your <code>PATH</code> or fluent-ffmpeg won't be able to produce streamable output files. If you set either the <code>FLVTOOL2_PATH</code> or <code>FLVMETA_PATH</code>, fluent-ffmpeg will try to use it instead of searching in the <code>PATH</code>.</p> <h4>Setting binary paths manually</h4><p>Alternatively, you may set the ffmpeg, ffprobe and flvtool2/flvmeta binary paths manually by using the following API commands:</p> <ul> <li><strong>Ffmpeg.setFfmpegPath(path)</strong> Argument <code>path</code> is a string with the full path to the ffmpeg binary.</li> <li><strong>Ffmpeg.setFfprobePath(path)</strong> Argument <code>path</code> is a string with the full path to the ffprobe binary.</li> <li><strong>Ffmpeg.setFlvtoolPath(path)</strong> Argument <code>path</code> is a string with the full path to the flvtool2 or flvmeta binary.</li> </ul> <a name="creating-an-ffmpeg-command"></a><h3>Creating an FFmpeg command</h3><p>The fluent-ffmpeg module returns a constructor that you can use to instanciate FFmpeg commands.</p> <pre class="prettyprint source lang-js"><code>var FfmpegCommand = require('fluent-ffmpeg'); var command = new FfmpegCommand();</code></pre><p>You can also use the constructor without the <code>new</code> operator.</p> <pre class="prettyprint source lang-js"><code>var ffmpeg = require('fluent-ffmpeg'); var command = ffmpeg();</code></pre><p>You may pass an input file name or readable stream, a configuration object, or both to the constructor.</p> <pre class="prettyprint source lang-js"><code>var command = ffmpeg('/path/to/file.avi'); var command = ffmpeg(fs.createReadStream('/path/to/file.avi')); var command = ffmpeg({ option: &quot;value&quot;, ... }); var command = ffmpeg('/path/to/file.avi', { option: &quot;value&quot;, ... });</code></pre><p>The following options are available:</p> <ul> <li><code>source</code>: input file name or readable stream (ignored if an input file is passed to the constructor)</li> <li><code>timeout</code>: ffmpeg timeout in seconds (defaults to no timeout)</li> <li><code>preset</code> or <code>presets</code>: directory to load module presets from (defaults to the <code>lib/presets</code> directory in fluent-ffmpeg tree)</li> <li><code>niceness</code> or <code>priority</code>: ffmpeg niceness value, between -20 and 20; ignored on Windows platforms (defaults to 0)</li> <li><code>logger</code>: logger object with <code>debug()</code>, <code>info()</code>, <code>warn()</code> and <code>error()</code> methods (defaults to no logging)</li> <li><code>stdoutLines</code>: maximum number of lines from ffmpeg stdout/stderr to keep in memory (defaults to 100, use 0 for unlimited storage)</li> </ul> <a name="specifying-inputs"></a><h3>Specifying inputs</h3><p>You can add any number of inputs to an Ffmpeg command. An input can be:</p> <ul> <li>a file name (eg. <code>/path/to/file.avi</code>);</li> <li>an image pattern (eg. <code>/path/to/frame%03d.png</code>);</li> <li>a readable stream; only one input stream may be used for a command, but you can use both an input stream and one or several file names.</li> </ul> <pre class="prettyprint source lang-js"><code>// Note that all fluent-ffmpeg methods are chainable ffmpeg('/path/to/input1.avi') .input('/path/to/input2.avi') .input(fs.createReadStream('/path/to/input3.avi')); // Passing an input to the constructor is the same as calling .input() ffmpeg() .input('/path/to/input1.avi') .input('/path/to/input2.avi'); // Most methods have several aliases, here you may use addInput or mergeAdd instead ffmpeg() .addInput('/path/to/frame%02d.png') .addInput('/path/to/soundtrack.mp3'); ffmpeg() .mergeAdd('/path/to/input1.avi') .mergeAdd('/path/to/input2.avi');</code></pre><a name="input-options"></a><h3>Input options</h3><p>The following methods enable passing input-related options to ffmpeg. Each of these methods apply on the last input added (including the one passed to the constructor, if any). You must add an input before calling those, or an error will be thrown.</p> <h4>inputFormat(format): specify input format</h4><p><strong>Aliases</strong>: <code>fromFormat()</code>, <code>withInputFormat()</code>.</p> <p>This is only useful for raw inputs, as ffmpeg can determine the input format automatically.</p> <pre class="prettyprint source lang-js"><code>ffmpeg() .input('/dev/video0') .inputFormat('mov') .input('/path/to/file.avi') .inputFormat('avi');</code></pre><p>Fluent-ffmpeg checks for format availability before actually running the command, and throws an error when a specified input format is not available.</p> <h4>inputFPS(fps): specify input framerate</h4><p><strong>Aliases</strong>: <code>withInputFps()</code>, <code>withInputFPS()</code>, <code>withFpsInput()</code>, <code>withFPSInput()</code>, <code>inputFps()</code>, <code>fpsInput()</code>, <code>FPSInput()</code>.</p> <p>This is only valid for raw inputs, as ffmpeg can determine the input framerate automatically.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/dev/video0').inputFPS(29.7);</code></pre><h4>native(): read input at native framerate</h4><p><strong>Aliases</strong>: <code>nativeFramerate()</code>, <code>withNativeFramerate()</code>.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').native();</code></pre><h4>seekInput(time): set input start time</h4><p><strong>Alias</strong>: <code>setStartTime()</code>.</p> <p>Seeks an input and only start decoding at given time offset. The <code>time</code> argument may be a number (in seconds) or a timestamp string (with format <code>[[hh:]mm:]ss[.xxx]</code>).</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').seekInput(134.5); ffmpeg('/path/to/file.avi').seekInput('2:14.500');</code></pre><h4>loop([duration]): loop over input</h4><pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').loop(); ffmpeg('/path/to/file.avi').loop(134.5); ffmpeg('/path/to/file.avi').loop('2:14.500');</code></pre><h4>inputOptions(option...): add custom input options</h4><p><strong>Aliases</strong>: <code>inputOption()</code>, <code>addInputOption()</code>, <code>addInputOptions()</code>, <code>withInputOption()</code>, <code>withInputOptions()</code>.</p> <p>This method allows passing any input-related option to ffmpeg. You can call it with a single argument to pass a single option, optionnaly with a space-separated parameter:</p> <pre class="prettyprint source lang-js"><code>/* Single option */ ffmpeg('/path/to/file.avi').inputOptions('-someOption'); /* Single option with parameter */ ffmpeg('/dev/video0').inputOptions('-r 24');</code></pre><p>You may also pass multiple options at once by passing an array to the method:</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').inputOptions([ '-option1', '-option2 param2', '-option3', '-option4 param4' ]);</code></pre><p>Finally, you may also directly pass command line tokens as separate arguments to the method:</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').inputOptions( '-option1', '-option2', 'param2', '-option3', '-option4', 'param4' );</code></pre><a name="audio-options"></a><h3>Audio options</h3><p>The following methods change the audio stream(s) in the produced output.</p> <h4>noAudio(): disable audio altogether</h4><p><strong>Aliases</strong>: <code>withNoAudio()</code>.</p> <p>Disables audio in the output and remove any previously set audio option.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').noAudio();</code></pre><h4>audioCodec(codec): set audio codec</h4><p><strong>Aliases</strong>: <code>withAudioCodec()</code>.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').audioCodec('libmp3lame');</code></pre><p>Fluent-ffmpeg checks for codec availability before actually running the command, and throws an error when a specified audio codec is not available.</p> <h4>audioBitrate(bitrate): set audio bitrate</h4><p><strong>Aliases</strong>: <code>withAudioBitrate()</code>.</p> <p>Sets the audio bitrate in kbps. The <code>bitrate</code> parameter may be a number or a string with an optional <code>k</code> suffix. This method is used to enforce a constant bitrate; use <code>audioQuality()</code> to encode using a variable bitrate.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').audioBitrate(128); ffmpeg('/path/to/file.avi').audioBitrate('128'); ffmpeg('/path/to/file.avi').audioBitrate('128k');</code></pre><h4>audioChannels(count): set audio channel count</h4><p><strong>Aliases</strong>: <code>withAudioChannels()</code>.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').audioChannels(2);</code></pre><h4>audioFrequency(freq): set audio frequency</h4><p><strong>Aliases</strong>: <code>withAudioFrequency()</code>.</p> <p>The <code>freq</code> parameter specifies the audio frequency in Hz.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').audioFrequency(22050);</code></pre><h4>audioQuality(quality): set audio quality</h4><p><strong>Aliases</strong>: <code>withAudioQuality()</code>.</p> <p>This method fixes a quality factor for the audio codec (VBR encoding). The quality scale depends on the actual codec used.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi') .audioCodec('libmp3lame') .audioQuality(0);</code></pre><h4>audioFilters(filter...): add custom audio filters</h4><p><strong>Aliases</strong>: <code>audioFilter()</code>, <code>withAudioFilter()</code>, <code>withAudioFilters()</code>.</p> <p>This method enables adding custom audio filters. You may add multiple filters at once by passing either several arguments or an array. See the Ffmpeg documentation for available filters and their syntax.</p> <p>Each filter pased to this method can be either a filter string (eg. <code>volume=0.5</code>) or a filter specification object with the following keys:</p> <ul> <li><code>filter</code>: filter name</li> <li><code>options</code>: optional; either an option string for the filter (eg. <code>n=-50dB:d=5</code>), an options array for unnamed options (eg. <code>['-50dB', 5]</code>) or an object mapping option names to values (eg. <code>{ n: '-50dB', d: 5 }</code>). When <code>options</code> is not specified, the filter will be added without any options.</li> </ul> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi') .audioFilters('volume=0.5') .audioFilters('silencedetect=n=-50dB:d=5'); ffmpeg('/path/to/file.avi') .audioFilters('volume=0.5', 'silencedetect=n=-50dB:d=5'); ffmpeg('/path/to/file.avi') .audioFilters(['volume=0.5', 'silencedetect=n=-50dB:d=5']); ffmpeg('/path/to/file.avi') .audioFilters([ { filter: 'volume', options: '0.5' }, { filter: 'silencedetect', options: 'n=-50dB:d=5' } ]); ffmpeg('/path/to/file.avi') .audioFilters( { filter: 'volume', options: ['0.5'] }, { filter: 'silencedetect', options: { n: '-50dB', d: 5 } } ]);</code></pre><a name="video-options"></a><h3>Video options</h3><p>The following methods change the video stream(s) in the produced output.</p> <h4>noVideo(): disable video altogether</h4><p><strong>Aliases</strong>: <code>withNoVideo()</code>.</p> <p>This method disables video output and removes any previously set video option.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').noVideo();</code></pre><h4>videoCodec(codec): set video codec</h4><p><strong>Aliases</strong>: <code>withVideoCodec()</code>.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').videoCodec('libx264');</code></pre><p>Fluent-ffmpeg checks for codec availability before actually running the command, and throws an error when a specified video codec is not available.</p> <h4>videoBitrate(bitrate[, constant=false]): set video bitrate</h4><p><strong>Aliases</strong>: <code>withVideoBitrate()</code>.</p> <p>Sets the target video bitrate in kbps. The <code>bitrate</code> argument may be a number or a string with an optional <code>k</code> suffix. The <code>constant</code> argument specifies whether a constant bitrate should be enforced (defaults to false).</p> <p>Keep in mind that, depending on the codec used, enforcing a constant bitrate often comes at the cost of quality. The best way to have a constant video bitrate without losing too much quality is to use 2-pass encoding (see Fffmpeg documentation).</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').videoBitrate(1000); ffmpeg('/path/to/file.avi').videoBitrate('1000'); ffmpeg('/path/to/file.avi').videoBitrate('1000k'); ffmpeg('/path/to/file.avi').videoBitrate('1000k', true);</code></pre><h4>videoFilters(filter...): add custom video filters</h4><p><strong>Aliases</strong>: <code>videoFilter()</code>, <code>withVideoFilter()</code>, <code>withVideoFilters()</code>.</p> <p>This method enables adding custom video filters. You may add multiple filters at once by passing either several arguments or an array. See the Ffmpeg documentation for available filters and their syntax.</p> <p>Each filter pased to this method can be either a filter string (eg. <code>fade=in:0:30</code>) or a filter specification object with the following keys:</p> <ul> <li><code>filter</code>: filter name</li> <li><code>options</code>: optional; either an option string for the filter (eg. <code>in:0:30</code>), an options array for unnamed options (eg. <code>['in', 0, 30]</code>) or an object mapping option names to values (eg. <code>{ t: 'in', s: 0, n: 30 }</code>). When <code>options</code> is not specified, the filter will be added without any options.</li> </ul> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi') .videoFilters('fade=in:0:30') .videoFilters('pad=640:480:0:40:violet'); ffmpeg('/path/to/file.avi') .videoFilters('fade=in:0:30', 'pad=640:480:0:40:violet'); ffmpeg('/path/to/file.avi') .videoFilters(['fade=in:0:30', 'pad=640:480:0:40:violet']); ffmpeg('/path/to/file.avi') .videoFilters([ { filter: 'fade', options: 'in:0:30' }, { filter: 'pad', options: '640:480:0:40:violet' } ]); ffmpeg('/path/to/file.avi') .videoFilters( { filter: 'fade', options: ['in', 0, 30] }, { filter: 'filter2', options: { w: 640, h: 480, x: 0, y: 40, color: 'violet' } } );</code></pre><h4>fps(fps): set output framerate</h4><p><strong>Aliases</strong>: <code>withOutputFps()</code>, <code>withOutputFPS()</code>, <code>withFpsOutput()</code>, <code>withFPSOutput()</code>, <code>withFps()</code>, <code>withFPS()</code>, <code>outputFPS()</code>, <code>outputFps()</code>, <code>fpsOutput()</code>, <code>FPSOutput()</code>, <code>FPS()</code>.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').fps(29.7);</code></pre><h4>frames(count): specify frame count</h4><p><strong>Aliases</strong>: <code>takeFrames()</code>, <code>withFrames()</code>.</p> <p>Set ffmpeg to only encode a certain number of frames.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').frames(240);</code></pre><a name="video-frame-size-options"></a><h3>Video frame size options</h3><p>The following methods enable resizing the output video frame size. They all work together to generate the appropriate video filters.</p> <h4>size(size): set output frame size</h4><p><strong>Aliases</strong>: <code>videoSize()</code>, <code>withSize()</code>.</p> <p>This method sets the output frame size. The <code>size</code> argument may have one of the following formats:</p> <ul> <li><code>640x480</code>: set a fixed output frame size. Unless <code>autopad()</code> is called, this may result in the video being stretched or squeezed to fit the requested size.</li> <li><code>640x?</code>: set a fixed width and compute height automatically. If <code>aspect()</code> is also called, it is used to compute video height; otherwise it is computed so that the input aspect ratio is preserved.</li> <li><code>?x480</code>: set a fixed height and compute width automatically. If <code>aspect()</code> is also called, it is used to compute video width; otherwise it is computed so that the input aspect ratio is preserved.</li> <li><code>50%</code>: rescale both width and height to the given percentage. Aspect ratio is always preserved.</li> </ul> <p>Note that for compatibility with some codecs, computed dimensions are always rounded down to multiples of 2.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').size('640x480'); ffmpeg('/path/to/file.avi').size('640x?'); ffmpeg('/path/to/file.avi').size('640x?').aspect('4:3'); ffmpeg('/path/to/file.avi').size('50%');</code></pre><h4>aspect(aspect): set output frame aspect ratio</h4><p><strong>Aliases</strong>: <code>withAspect()</code>, <code>withAspectRatio()</code>, <code>setAspect()</code>, <code>setAspectRatio()</code>, <code>aspectRatio()</code>.</p> <p>This method enforces a specific output aspect ratio. The <code>aspect</code> argument may either be a number or a <code>X:Y</code> string.</p> <p>Note that calls to <code>aspect()</code> are ignored when <code>size()</code> has been called with a fixed width and height or a percentage, and also when <code>size()</code> has not been called at all.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').size('640x?').aspect('4:3'); ffmpeg('/path/to/file.avi').size('640x?').aspect(1.33333);</code></pre><h4>autopad([color='black']): enable auto-padding the output video</h4><p><strong>Aliases</strong>: <code>applyAutopadding()</code>, <code>applyAutoPadding()</code>, <code>applyAutopad()</code>, <code>applyAutoPad()</code>, <code>withAutopadding()</code>, <code>withAutoPadding()</code>, <code>withAutopad()</code>, <code>withAutoPad()</code>, <code>autoPad()</code>.</p> <p>This method enables applying auto-padding to the output video. The <code>color</code> parameter specifies which color to use for padding, and must be a color code or name supported by ffmpeg (defaults to 'black').</p> <p>The behaviour of this method depends on calls made to other video size methods:</p> <ul> <li>when <code>size()</code> has been called with a percentage or has not been called, it is ignored;</li> <li>when <code>size()</code> has been called with <code>WxH</code>, it adds padding so that the input aspect ratio is kept;</li> <li>when <code>size()</code> has been called with either <code>Wx?</code> or <code>?xH</code>, padding is only added if <code>aspect()</code> was called (otherwise the output dimensions are computed from the input aspect ratio and padding is not needed).</li> </ul> <pre class="prettyprint source lang-js"><code>// No size specified, autopad() is ignored ffmpeg('/path/to/file.avi').autopad(); // Adds padding to keep original aspect ratio. // - with a 640x400 input, 40 pixels of padding are added on both sides // - with a 600x480 input, 20 pixels of padding are added on top and bottom // - with a 320x200 input, video is scaled up to 640x400 and 40px of padding // is added on both sides // - with a 320x240 input, video is scaled up to 640x480 and and no padding // is needed ffmpeg('/path/to/file.avi').size('640x480').autopad(); ffmpeg('/path/to/file.avi').size('640x480').autopad('white'); ffmpeg('/path/to/file.avi').size('640x480').autopad('#35A5FF'); // Size computed from input, autopad() is ignored ffmpeg('/path/to/file.avi').size('50%').autopad(); ffmpeg('/path/to/file.avi').size('640x?').autopad(); ffmpeg('/path/to/file.avi').size('?x480').autopad(); // Calling .size('640x?').aspect('4:3') is similar to calling .size('640x480') // - with a 640x400 input, 40 pixels of padding are added on both sides // - with a 600x480 input, 20 pixels of padding are added on top and bottom // - with a 320x200 input, video is scaled up to 640x400 and 40px of padding // is added on both sides // - with a 320x240 input, video is scaled up to 640x480 and and no padding // is needed ffmpeg('/path/to/file.avi').size('640x?').aspect('4:3').autopad(); ffmpeg('/path/to/file.avi').size('640x?').aspect('4:3').autopad('white'); ffmpeg('/path/to/file.avi').size('640x?').aspect('4:3').autopad('#35A5FF'); // Calling .size('?x480').aspect('4:3') is similar to calling .size('640x480') ffmpeg('/path/to/file.avi').size('?x480').aspect('4:3').autopad(); ffmpeg('/path/to/file.avi').size('?x480').aspect('4:3').autopad('white'); ffmpeg('/path/to/file.avi').size('?x480').aspect('4:3').autopad('#35A5FF');</code></pre><p>For compatibility with previous fluent-ffmpeg versions, this method also accepts an additional boolean first argument, which specifies whether to apply auto-padding.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').size('640x480').autopad(true); ffmpeg('/path/to/file.avi').size('640x480').autopad(true, 'pink');</code></pre><h4>keepDAR(): force keeping display aspect ratio</h4><p><strong>Aliases</strong>: <code>keepPixelAspect()</code>, <code>keepDisplayAspect()</code>, <code>keepDisplayAspectRatio()</code>.</p> <p>This method is useful when converting an input with non-square pixels to an output format that does not support non-square pixels (eg. most image formats). It rescales the input so that the display aspect ratio is the same.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').keepDAR();</code></pre><a name="specifying-multiple-outputs"></a><h3>Specifying multiple outputs</h3><h4>output(target[, options]): add an output to the command</h4><p><strong>Aliases</strong>: <code>addOutput()</code>.</p> <p>Adds an output to the command. The <code>target</code> argument may be an output filename or a writable stream (but at most one output stream may be used with a single command).</p> <p>When <code>target</code> is a stream, an additional <code>options</code> object may be passed. If it is present, it will be passed ffmpeg output stream <code>pipe()</code> method.</p> <p>Adding an output switches the &quot;current output&quot; of the command, so that any fluent-ffmpeg method that applies to an output is indeed applied to the last output added. For backwards compatibility reasons, you may as well call those methods <em>before</em> adding the first output (in which case they will apply to the first output when it is added). Methods that apply to an output are all non-input-related methods, except for <code>complexFilter()</code>, which is global.</p> <p>Also note that when calling <code>output()</code>, you should not use the <code>save()</code> or <code>stream()</code> (formerly <code>saveToFile()</code> and <code>writeToStream()</code>) methods, as they already add an output. Use the <code>run()</code> method to start processing.</p> <pre class="prettyprint source lang-js"><code>var stream = fs.createWriteStream('outputfile.divx'); ffmpeg('/path/to/file.avi') .output('outputfile.mp4') .output(stream); ffmpeg('/path/to/file.avi') // You may pass a pipe() options object when using a stream .output(stream, { end:true }); // Output-related methods apply to the last output added ffmpeg('/path/to/file.avi') .output('outputfile.mp4') .audioCodec('libfaac') .videoCodec('libx264') .size('320x200') .output(stream) .preset('divx') .size('640x480'); // Use the run() method to run commands with multiple outputs ffmpeg('/path/to/file.avi') .output('outputfile.mp4') .output(stream) .on('end', function() { console.log('Finished processing'); }) .run();</code></pre><a name="output-options"></a><h3>Output options</h3><h4>duration(time): set output duration</h4><p><strong>Aliases</strong>: <code>withDuration()</code>, <code>setDuration()</code>.</p> <p>Forces ffmpeg to stop transcoding after a specific output duration. The <code>time</code> parameter may be a number (in seconds) or a timestamp string (with format <code>[[hh:]mm:]ss[.xxx]</code>).</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').duration(134.5); ffmpeg('/path/to/file.avi').duration('2:14.500');</code></pre><h4>seek(time): seek output</h4><p><strong>Aliases</strong>: <code>seekOutput()</code>.</p> <p>Seeks streams before encoding them into the output. This is different from calling <code>seekInput()</code> in that the offset will only apply to one output. This is also slower, as skipped frames will still be decoded (but dropped).</p> <p>The <code>time</code> argument may be a number (in seconds) or a timestamp string (with format <code>[[hh:]mm:]ss[.xxx]</code>).</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi') .seekInput('1:00') .output('from-1m30s.avi') .seek(30) .output('from-1m40s.avi') .seek('0:40');</code></pre><h4>format(format): set output format</h4><p><strong>Aliases</strong>: <code>withOutputFormat()</code>, <code>toFormat()</code>, <code>outputFormat()</code>.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').format('flv');</code></pre><h4>flvmeta(): update FLV metadata after transcoding</h4><p><strong>Aliases</strong>: <code>updateFlvMetadata()</code>.</p> <p>Calling this method makes fluent-ffmpeg run <code>flvmeta</code> or <code>flvtool2</code> on the output file to add FLV metadata and make files streamable. It does not work when outputting to a stream, and is only useful when outputting to FLV format.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').flvmeta().format('flv');</code></pre><h4>outputOptions(option...): add custom output options</h4><p><strong>Aliases</strong>: <code>outputOption()</code>, <code>addOutputOption()</code>, <code>addOutputOptions()</code>, <code>withOutputOption()</code>, <code>withOutputOptions()</code>, <code>addOption()</code>, <code>addOptions()</code>.</p> <p>This method allows passing any output-related option to ffmpeg. You can call it with a single argument to pass a single option, optionnaly with a space-separated parameter:</p> <pre class="prettyprint source lang-js"><code>/* Single option */ ffmpeg('/path/to/file.avi').outputOptions('-someOption'); /* Single option with parameter */ ffmpeg('/dev/video0').outputOptions('-r 24');</code></pre><p>You may also pass multiple options at once by passing an array to the method:</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').outputOptions([ '-option1', '-option2 param2', '-option3', '-option4 param4' ]);</code></pre><p>Finally, you may also directly pass command line tokens as separate arguments to the method:</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi').outputOptions( '-option1', '-option2', 'param2', '-option3', '-option4', 'param4' );</code></pre><a name="miscellaneous-options"></a><h3>Miscellaneous options</h3><h4>preset(preset): use fluent-ffmpeg preset</h4><p><strong>Aliases</strong>: <code>usingPreset()</code>.</p> <p>There are two kinds of presets supported by fluent-ffmpeg. The first one is preset modules; to use those, pass the preset name as the <code>preset</code> argument. Preset modules are loaded from the directory specified by the <code>presets</code> constructor option (defaults to the <code>lib/presets</code> fluent-ffmpeg subdirectory).</p> <pre class="prettyprint source lang-js"><code>// Uses &lt;path-to-fluent-ffmpeg>/lib/presets/divx.js ffmpeg('/path/to/file.avi').preset('divx'); // Uses /my/presets/foo.js ffmpeg('/path/to/file.avi', { presets: '/my/presets' }).preset('foo');</code></pre><p>Preset modules must export a <code>load()</code> function that takes an FfmpegCommand as an argument. fluent-ffmpeg comes with the following preset modules preinstalled:</p> <ul> <li><code>divx</code></li> <li><code>flashvideo</code></li> <li><code>podcast</code></li> </ul> <p>Here is the code from the included <code>divx</code> preset as an example:</p> <pre class="prettyprint source lang-js"><code>exports.load = function(ffmpeg) { ffmpeg .format('avi') .videoBitrate('1024k') .videoCodec('mpeg4') .size('720x?') .audioBitrate('128k') .audioChannels(2) .audioCodec('libmp3lame') .outputOptions(['-vtag DIVX']); };</code></pre><p>The second kind of preset is preset functions. To use those, pass a function which takes an FfmpegCommand as a parameter.</p> <pre class="prettyprint source lang-js"><code>function myPreset(command) { command.format('avi').size('720x?'); } ffmpeg('/path/to/file.avi').preset(myPreset);</code></pre><h4>complexFilter(filters[, map]): set complex filtergraph</h4><p><strong>Aliases</strong>: <code>filterGraph()</code></p> <p>The <code>complexFilter()</code> method enables setting a complex filtergraph for a command. It expects a filter specification (or a filter specification array) and an optional output mapping parameter as arguments.</p> <p>Filter specifications may be either plain ffmpeg filter strings (eg. <code>split=3[a][b][c]</code>) or objects with the following keys:</p> <ul> <li><code>filter</code>: filter name</li> <li><code>options</code>: optional; either an option string for the filter (eg. <code>in:0:30</code>), an options array for unnamed options (eg. <code>['in', 0, 30]</code>) or an object mapping option names to values (eg. <code>{ t: 'in', s: 0, n: 30 }</code>). When <code>options</code> is not specified, the filter will be added without any options.</li> <li><code>inputs</code>: optional; input stream specifier(s) for the filter. The value may be either a single stream specifier string or an array of stream specifiers. Each specifier can be optionally enclosed in square brackets. When input streams are not specified, ffmpeg will use the first unused streams of the correct type.</li> <li><code>outputs</code>: optional; output stream specifier(s) for the filter. The value may be either a single stream specifier string or an array of stream specifiers. Each specifier can be optionally enclosed in square brackets.</li> </ul> <p>The output mapping parameter specifies which stream(s) to include in the output from the filtergraph. It may be either a single stream specifier string or an array of stream specifiers. Each specifier can be optionally enclosed in square brackets. When this parameter is not present, ffmpeg will default to saving all unused outputs to the output file.</p> <p>Note that only one complex filtergraph may be set on a given command. Calling <code>complexFilter()</code> again will override any previously set filtergraph, but you can set as many filters as needed in a single call.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi') .complexFilter([ // Rescale input stream into stream 'rescaled' 'scale=640:480[rescaled]', // Duplicate rescaled stream 3 times into streams a, b, and c { filter: 'split', options: '3', inputs: 'rescaled', outputs: ['a', 'b', 'c'] }, // Create stream 'red' by removing green and blue channels from stream 'a' { filter: 'lutrgb', options: { g: 0, b: 0 }, inputs: 'a', outputs: 'red' }, // Create stream 'green' by removing red and blue channels from stream 'b' { filter: 'lutrgb', options: { r: 0, b: 0 }, inputs: 'b', outputs: 'green' }, // Create stream 'blue' by removing 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'], outputs: 'output' }, ], 'output');</code></pre><a name="setting-event-handlers"></a><h3>Setting event handlers</h3><p>Before actually running a command, you may want to set event listeners on it to be notified when it's done. The following events are available:</p> <h4>'start': ffmpeg process started</h4><p>The <code>start</code> event is emitted just after ffmpeg has been spawned. It is emitted with the full command line used as an argument.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi') .on('start', function(commandLine) { console.log('Spawned Ffmpeg with command: ' + commandLine); });</code></pre><h4>'codecData': input codec data available</h4><p>The <code>codecData</code> event is emitted when ffmpeg outputs codec information about its input streams. It is emitted with an object argument with the following keys:</p> <ul> <li><code>format</code>: input format</li> <li><code>duration</code>: input duration</li> <li><code>audio</code>: audio codec</li> <li><code>audio_details</code>: audio encoding details</li> <li><code>video</code>: video codec</li> <li><code>video_details</code>: video encoding details</li> </ul> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi') .on('codecData', function(data) { console.log('Input is ' + data.audio + ' audio ' + 'with ' + data.video + ' video'); });</code></pre><h4>'progress': transcoding progress information</h4><p>The <code>progress</code> event is emitted every time ffmpeg reports progress information. It is emitted with an object argument with the following keys:</p> <ul> <li><code>frames</code>: total processed frame count</li> <li><code>currentFps</code>: framerate at which FFmpeg is currently processing</li> <li><code>currentKbps</code>: throughput at which FFmpeg is currently processing</li> <li><code>targetSize</code>: current size of the target file in kilobytes</li> <li><code>timemark</code>: the timestamp of the current frame in seconds</li> <li><code>percent</code>: an estimation of the progress percentage</li> </ul> <p>Note that <code>percent</code> can be (very) inaccurate, as the only progress information fluent-ffmpeg gets from ffmpeg is the total number of frames written (and the corresponding duration). To estimate percentage, fluent-ffmpeg has to guess what the total output duration will be, and uses the first input added to the command to do so. In particular:</p> <ul> <li>percentage is not available when using an input stream</li> <li>percentage may be wrong when using multiple inputs with different durations and the first one is not the longest</li> </ul> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi') .on('progress', function(progress) { console.log('Processing: ' + progress.percent + '% done'); });</code></pre><h4>'stderr': FFmpeg output</h4><p>The <code>stderr</code> event is emitted every time FFmpeg outputs a line to <code>stderr</code>. It is emitted with a string containing the line of stderr (minus trailing new line characters).</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi') .on('stderr', function(stderrLine) { console.log('Stderr output: ' + stderrLine); });</code></pre><h4>'error': transcoding error</h4><p>The <code>error</code> event is emitted when an error occurs when running ffmpeg or when preparing its execution. It is emitted with an error object as an argument. If the error happened during ffmpeg execution, listeners will also receive two additional arguments containing ffmpegs stdout and stderr.</p> <p><strong>Warning</strong>: you should <em>always</em> set a handler for the <code>error</code> event, as node's default behaviour when an <code>error</code> event without any listeners is emitted is to output the error to the console and <em>terminate the program</em>.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi') .on('error', function(err, stdout, stderr) { console.log('Cannot process video: ' + err.message); });</code></pre><h4>'end': processing finished</h4><p>The <code>end</code> event is emitted when processing has finished. Listeners receive ffmpeg standard output and standard error as arguments, except when generating thumbnails (see below), in which case they receive an array of the generated filenames.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/file.avi') .on('end', function(stdout, stderr) { console.log('Transcoding succeeded !'); });</code></pre><p><code>stdout</code> is empty when the command outputs to a stream. Both <code>stdout</code> and <code>stderr</code> are limited by the <code>stdoutLines</code> option (defaults to 100 lines).</p> <a name="starting-ffmpeg-processing"></a><h3>Starting FFmpeg processing</h3><h4>save(filename): save the output to a file</h4><p><strong>Aliases</strong>: <code>saveToFile()</code></p> <p>Starts ffmpeg processing and saves the output to a file.</p> <pre class="prettyprint source lang-js"><code>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');</code></pre><p>Note: the <code>save()</code> method is actually syntactic sugar for calling both <code>output()</code> and <code>run()</code>.</p> <h4>pipe([stream], [options]): pipe the output to a writable stream</h4><p><strong>Aliases</strong>: <code>stream()</code>, <code>writeToStream()</code>.</p> <p>Starts processing and pipes ffmpeg output to a writable stream. The <code>options</code> argument, if present, is passed to ffmpeg output stream's <code>pipe()</code> method (see nodejs documentation).</p> <pre class="prettyprint source lang-js"><code>var outStream = fs.createWriteStream('/path/to/output.mp4'); 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 !'); }) .pipe(outStream, { end: true });</code></pre><p>When no <code>stream</code> argument is present, the <code>pipe()</code> method returns a PassThrough stream, which you can pipe to somewhere else (or just listen to events on).</p> <p><strong>Note</strong>: this is only available with node &gt;= 0.10.</p> <pre class="prettyprint source lang-js"><code>var command = 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 !'); }); var ffstream = command.pipe(); ffstream.on('data', function(chunk) { console.log('ffmpeg just wrote ' + chunk.length + ' bytes'); });</code></pre><p>Note: the <code>stream()</code> method is actually syntactic sugar for calling both <code>output()</code> and <code>run()</code>.</p> <h4>run(): start processing</h4><p><strong>Aliases</strong>: <code>exec()</code>, <code>execute()</code>.</p> <p>This method is mainly useful when producing multiple outputs (otherwise the <code>save()</code> or <code>stream()</code> methods are more straightforward). It starts processing with the specified outputs.</p> <p><strong>Warning</strong>: do not use <code>run()</code> when calling other processing methods (eg. <code>save()</code>, <code>pipe()</code> or <code>screenshots()</code>).</p> <pre class="prettyprint source lang-js"><code>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();</code></pre><h4>mergeToFile(filename, tmpdir): concatenate multiple inputs</h4><p>Use the <code>input</code> and <code>mergeToFile</code> methods on a command to concatenate multiple inputs to a single output file. The <code>mergeToFile</code> needs a temporary folder as its second argument.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/part1.avi') .input('/path/to/part2.avi') .input('/path/to/part2.avi') .on('error', function(err) { console.log('An error occurred: ' + err.message); }) .on('end', function() { console.log('Merging finished !'); }) .mergeToFile('/path/to/merged.avi', '/path/to/tempDir');</code></pre><h4>screenshots(options[, dirname]): generate thumbnails</h4><p><strong>Aliases</strong>: <code>thumbnail()</code>, <code>thumbnails()</code>, <code>screenshot()</code>, <code>takeScreenshots()</code>.</p> <p>Use the <code>screenshots</code> method to extract one or several thumbnails and save them as PNG files. There are a few caveats with this implementation, though:</p> <ul> <li>It will not work on input streams.</li> <li>Progress information reported by the <code>progress</code> event is not accurate.</li> <li>It doesn't interract well with filters. In particular, don't use the <code>size()</code> method to resize thumbnails, use the <code>size</code> option instead.</li> </ul> <p>The <code>options</code> argument is an object with the following keys:</p> <ul> <li><code>folder</code>: output folder for generated image files. Defaults to the current folder.</li> <li><code>filename</code>: output filename pattern (see below). Defaults to &quot;tn.png&quot;.</li> <li><code>count</code>: specifies how many thumbnails to generate. When using this option, thumbnails are generated at regular intervals in the video (for example, when requesting 3 thumbnails, at 25%, 50% and 75% of the video length). <code>count</code> is ignored when <code>timemarks</code> or <code>timestamps</code> is specified.</li> <li><code>timemarks</code> or <code>timestamps</code>: specifies an array of timestamps in the video where thumbnails should be taken. Each timestamp may be a number (in seconds), a percentage string (eg. &quot;50%&quot;) or a timestamp string with format &quot;hh:mm:ss.xxx&quot; (where hours, minutes and milliseconds are both optional).</li> <li><code>size</code>: specifies a target size for thumbnails (with the same format as the <code>.size()</code> method). <strong>Note:</strong> you should not use the <code>.size()</code> method when generating thumbnails.</li> </ul> <p>The <code>filename</code> option specifies a filename pattern for generated files. It may contain the following format tokens:</p> <ul> <li>'%s': offset in seconds</li> <li>'%w': screenshot width</li> <li>'%h': screenshot height</li> <li>'%r': screenshot resolution (same as '%wx%h')</li> <li>'%f': input filename</li> <li>'%b': input basename (filename w/o extension)</li> <li>'%i': index of screenshot in timemark array (can be zero-padded by using it like <code>%000i</code>)</li> </ul> <p>If multiple timemarks are passed and no variable format token ('%s' or '%i') is specified in the filename pattern, <code>_%i</code> will be added automatically.</p> <p>When generating thumbnails, an additional <code>filenames</code> event is dispatched with an array of generated filenames as an argument.</p> <pre class="prettyprint source lang-js"><code>ffmpeg('/path/to/video.avi') .on('filenames', function(filenames) { console.log('Will generate ' + filenames.join(', ')) }) .on('end', function() { console.log('Screenshots taken'); }) .screenshots({ // Will take screens at 20%, 40%, 60% and 80% of the video count: 4, folder: '/path/to/output' }); ffmpeg('/path/to/video.avi') .screenshots({ timestamps: [30.5, '50%', '01:10.123'], filename: 'thumbnail-at-%s-seconds.png', folder: '/path/to/output', size: '320x240' });</code></pre><a name="controlling-the-ffmpeg-process"></a><h3>Controlling the FFmpeg process</h3><h4>kill([signal='SIGKILL']): kill any running ffmpeg process</h4><p>This method sends <code>signal</code> (defaults to 'SIGKILL') to the ffmpeg process. It only has sense when processing has started. Sending a signal that terminates the process will result in the <code>error</code> event being emitted.</p> <pre class="prettyprint source lang-js"><code>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);</code></pre><h4>renice([niceness=0]): change ffmpeg process priority</h4><p>This method alters the niceness (priority) value of any running ffmpeg process (if any) and any process spawned in the future. The <code>niceness</code> parameter may range from -20 (highest priority) to 20 (lowest priority) and defaults to 0 (which is the default process niceness on most *nix systems).</p> <p><strong>Note</strong>: this method is ineffective on Windows platforms.</p> <pre class="prettyprint source lang-js"><code>// 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);</code></pre><a name="reading-video-metadata"></a><h3>Reading video metadata</h3><p>You can read metadata from any valid ffmpeg input file with the modules <code>ffprobe</code> method.</p> <pre class="prettyprint source lang-js"><code>ffmpeg.ffprobe('/path/to/file.avi', function(err,