xonecas.io
311
Fn

ffmpeg-node / files

ffmpeg-node / ffmpeg-node.js

6.8 KB
1
2/**
3 * Module to drive ffmpeg video enconding library with shortcuts
4 * for web video. Requires a  ffmpeg compiled with support for mp4/ogg/webm.
5 */
6
7var path = require('path'),
8    _ = require('underscore'),
9    child_process = require('child_process'),
10    spawn = child_process.spawn,
11    helpers = require('./helpers.js'),
12    that = this,
13    queue = exports.queue = [],
14    maxActive = 4, // Maximum of active FFMpeg jobs
15    active = 0;
16
17
18
19function push (job) {
20   queue.push(job);
21   if(active < maxActive) {
22      next();
23   }
24}
25
26function next () {
27   if(queue.length > 0 && active < maxActive) {
28      that.exec(queue[0].params, queue[0].callback);
29      active++;
30      queue.shift();
31   }
32}
33
34/**
35 * Description:
36 *    calls ffmpeg with the specified flags and returns the output
37 *    to the callback function.
38 *
39 * Parameters:
40 * params - an array of ffmpeg options, ex, ['-i', './test.3gp', '-vpre', 'slow', '-vpre', 'baseline', '-vcodec', 'libx264']
41 * callback - a function to call when ffmpeg is done, ex:
42 *    function (stderr, stdout, exitCode) { ... }
43 */
44
45exports.exec = function (params, callback) {
46   if (params instanceof Array && params.length > 2) {
47
48      var stderr = '', stdout = '',
49         ffmpeg = spawn('ffmpeg', params);
50
51      ffmpeg.stderr.on('data', function (err) {
52         stderr += err;
53      });
54
55      ffmpeg.stdout.on('data', function (output) {
56         stdout += output;
57      });
58
59      ffmpeg.on('exit', function (code) {
60         callback(stderr, stdout, code);
61         active--;
62         next();
63      });
64
65   } else {
66      if (params instanceof Array && params.length <= 2) {
67         console.log('Params to short for ffmpeg');
68         active--;
69         next();
70      }
71   }
72};
73
74
75/**
76 * Description:
77 *    serves as middle man for convenience method, required to
78 *    avoid code repetition.
79 *
80 * Parameters:
81 * type - one of 'mp4', 'ogg', 'webm', 'mp3', 'm4a' as a string.
82 * file - path/to/the/inputFile.ext as a string.
83 * params - an object of ffmpeg options to be added to the predefined ones (optional).
84 * output - path/to/the/outputFile.ext as a string (optional).
85 * callback - function to call when ffmpeg is done, ex:
86 *    function (stderr, stdout, exitCode) { ... }
87 */
88
89
90exports.convert = function (/* overloaded */) {
91
92   var type = arguments[0],
93       file = arguments[1],
94       params = {}, output = '',
95       callback = false;
96
97   if (arguments.length === 3) {
98      params = {},
99      output = path.dirname(file) +'/'+ path.basename(
100         file, path.extname(file)) +'.'+ type,
101      callback = arguments[2];
102   }
103   else if (arguments.length > 3) {
104      var err = false;
105
106      if (arguments[2] instanceof Object &&
107         typeof arguments[3] === 'string' &&
108         arguments[4] instanceof Function) {
109
110         params = arguments[2];
111         output = arguments[3];
112         callback = arguments[4];
113      }
114      else if (arguments[2] instanceof Object &&
115         arguments[3] instanceof Function) {
116
117         params = arguments[2];
118         callback = arguments[3];
119      }
120      else if (typeof arguments[2] === string &&
121         arguments[3] instanceof Function) {
122
123         output = arguments[2];
124         callback = arguments[3];
125      }
126      else if (arguments[2] instanceof Function)
127         callback = arguments[2];
128      else
129         throw new Error("Couldn't parse arguments");
130
131   }
132   else
133      throw new Error('Not enough arguments');
134
135
136   // Here the params array should be modified into an object which can be extend
137   switch(type) {
138      case 'mp4':
139         params = helpers.objectToArray(_({
140            '-i': file,
141            '-acodec': 'aac',
142            '-ab': '128k',
143            '-ar': '44100',
144            '-vcodec': 'libx264',
145            '-vpre': ['slow','baseline'],
146            '-r': '25',
147            '-y': output
148         }).extend(params));
149      break;
150
151      case 'ogg':
152         params = helpers.objectToArray(_({
153            '-i': file,
154            '-acodec': 'libvorbis',
155            '-ab': '128k',
156            '-ar': '44100',
157            '-vcodec': 'libtheora',
158            '-r': '25',
159            '-y': output
160         }).extend(params));
161      break;
162
163      case 'webm':
164         params = helpers.objectToArray(_({
165            '-i': file,
166            '-acodec': 'libvorbis',
167            '-ab': '128k',
168            '-ar': '44100',
169            '-vcodec': 'libvpx',
170            '-b': '614400',
171            '-aspect': '16:9',
172            '-y': output
173         }).extend(params));
174      break;
175
176      case 'mp3':
177         params = helpers.objectToArray(_({
178            '-i': file,
179            '-acodec': 'libmp3lame',
180            '-ab': '128k',
181            '-ar': '44100',
182            '-y': output
183         }).extend(params));
184      break;
185
186      case 'm4a':
187         params = helpers.objectToArray(_({
188            '-i': file,
189            '-acodec': 'aac',
190            '-ab': '64k',
191            '-ar': '44100',
192            '-strict': '-2',
193            '-y': output
194         }).extend(params));
195      break;
196   }
197
198   
199   push({params: params, callback: callback});
200
201};
202
203/**
204 * Description:
205 *    Convenience methods to convert to popular web formats (flash/html5)
206 *    If you know how to improve these default options, let me know.
207 *
208 * Parameters:
209 * file - path/to/the/inputFile.ext as a string.
210 * params - an array of ffmpeg options to be added to the predefined ones (optional).
211 * output - path/to/the/outputFile.ext as a string (optional).
212 * callback - function to call when ffmpeg is done, ex:
213 *    function (stderr, stdout, exitCode) { ... }
214 */
215
216exports.mp4 = function (/* overloaded */) {
217
218   var unshift = Array.prototype.unshift;
219   unshift.call(arguments, 'mp4');
220
221   this.convert.apply(this, arguments);
222
223};
224
225exports.ogg = function (/* overloaded */) {
226
227   var unshift = Array.prototype.unshift;
228   unshift.call(arguments, 'ogg');
229
230   this.convert.apply(this, arguments);
231
232};
233
234exports.webm = function (/* overloaded */) {
235
236   var unshift = Array.prototype.unshift;
237   unshift.call(arguments, 'webm');
238
239   this.convert.apply(this, arguments);
240
241};
242
243exports.mp3 = function (/* overloaded */) {
244
245   var unshift = Array.prototype.unshift;
246   unshift.call(arguments, 'mp3');
247
248   this.convert.apply(this, arguments);
249
250};
251
252exports.m4a = function (/* overloaded */) {
253
254   var unshift = Array.prototype.unshift;
255   unshift.call(arguments, 'm4a');
256
257   this.convert.apply(this, arguments);
258
259};
260
261/*
262*  The function takes a absolute file path and returns a meta data object
263*  @params {String} input
264*  @params {Callback} callback function(error, jsonMetaObject)
265*/
266
267exports.getMetadata = function (input, callback) {
268   child_process.exec("ffprobe -loglevel error -show_format -show_streams " + input + " -print_format json", function (error, stdout, stderr) {
269      try {
270         stdout = JSON.parse(stdout);
271         callback(error, stdout);
272      } catch (e) {
273         callback(error, stdout);
274      }
275   });
276};