processor.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. /*jshint node:true*/
  2. 'use strict';
  3. var spawn = require('child_process').spawn;
  4. var path = require('path');
  5. var fs = require('fs');
  6. var async = require('async');
  7. var utils = require('./utils');
  8. var nlRegexp = /\r\n|\r|\n/g;
  9. /*
  10. *! Processor methods
  11. */
  12. /**
  13. * Run ffprobe asynchronously and store data in command
  14. *
  15. * @param {FfmpegCommand} command
  16. * @private
  17. */
  18. function runFfprobe(command) {
  19. const inputProbeIndex = 0;
  20. if (command._inputs[inputProbeIndex].isStream) {
  21. // Don't probe input streams as this will consume them
  22. return;
  23. }
  24. command.ffprobe(inputProbeIndex, function(err, data) {
  25. command._ffprobeData = data;
  26. });
  27. }
  28. module.exports = function(proto) {
  29. /**
  30. * Emitted just after ffmpeg has been spawned.
  31. *
  32. * @event FfmpegCommand#start
  33. * @param {String} command ffmpeg command line
  34. */
  35. /**
  36. * Emitted when ffmpeg reports progress information
  37. *
  38. * @event FfmpegCommand#progress
  39. * @param {Object} progress progress object
  40. * @param {Number} progress.frames number of frames transcoded
  41. * @param {Number} progress.currentFps current processing speed in frames per second
  42. * @param {Number} progress.currentKbps current output generation speed in kilobytes per second
  43. * @param {Number} progress.targetSize current output file size
  44. * @param {String} progress.timemark current video timemark
  45. * @param {Number} [progress.percent] processing progress (may not be available depending on input)
  46. */
  47. /**
  48. * Emitted when ffmpeg outputs to stderr
  49. *
  50. * @event FfmpegCommand#stderr
  51. * @param {String} line stderr output line
  52. */
  53. /**
  54. * Emitted when ffmpeg reports input codec data
  55. *
  56. * @event FfmpegCommand#codecData
  57. * @param {Object} codecData codec data object
  58. * @param {String} codecData.format input format name
  59. * @param {String} codecData.audio input audio codec name
  60. * @param {String} codecData.audio_details input audio codec parameters
  61. * @param {String} codecData.video input video codec name
  62. * @param {String} codecData.video_details input video codec parameters
  63. */
  64. /**
  65. * Emitted when an error happens when preparing or running a command
  66. *
  67. * @event FfmpegCommand#error
  68. * @param {Error} error error object, with optional properties 'inputStreamError' / 'outputStreamError' for errors on their respective streams
  69. * @param {String|null} stdout ffmpeg stdout, unless outputting to a stream
  70. * @param {String|null} stderr ffmpeg stderr
  71. */
  72. /**
  73. * Emitted when a command finishes processing
  74. *
  75. * @event FfmpegCommand#end
  76. * @param {Array|String|null} [filenames|stdout] generated filenames when taking screenshots, ffmpeg stdout when not outputting to a stream, null otherwise
  77. * @param {String|null} stderr ffmpeg stderr
  78. */
  79. /**
  80. * Spawn an ffmpeg process
  81. *
  82. * The 'options' argument may contain the following keys:
  83. * - 'niceness': specify process niceness, ignored on Windows (default: 0)
  84. * - `cwd`: change working directory
  85. * - 'captureStdout': capture stdout and pass it to 'endCB' as its 2nd argument (default: false)
  86. * - 'stdoutLines': override command limit (default: use command limit)
  87. *
  88. * The 'processCB' callback, if present, is called as soon as the process is created and
  89. * receives a nodejs ChildProcess object. It may not be called at all if an error happens
  90. * before spawning the process.
  91. *
  92. * The 'endCB' callback is called either when an error occurs or when the ffmpeg process finishes.
  93. *
  94. * @method FfmpegCommand#_spawnFfmpeg
  95. * @param {Array} args ffmpeg command line argument list
  96. * @param {Object} [options] spawn options (see above)
  97. * @param {Function} [processCB] callback called with process object and stdout/stderr ring buffers when process has been created
  98. * @param {Function} endCB callback called with error (if applicable) and stdout/stderr ring buffers when process finished
  99. * @private
  100. */
  101. proto._spawnFfmpeg = function(args, options, processCB, endCB) {
  102. // Enable omitting options
  103. if (typeof options === 'function') {
  104. endCB = processCB;
  105. processCB = options;
  106. options = {};
  107. }
  108. // Enable omitting processCB
  109. if (typeof endCB === 'undefined') {
  110. endCB = processCB;
  111. processCB = function() {};
  112. }
  113. var maxLines = 'stdoutLines' in options ? options.stdoutLines : this.options.stdoutLines;
  114. // Find ffmpeg
  115. this._getFfmpegPath(function(err, command) {
  116. if (err) {
  117. return endCB(err);
  118. } else if (!command || command.length === 0) {
  119. return endCB(new Error('Cannot find ffmpeg'));
  120. }
  121. // Apply niceness
  122. if (options.niceness && options.niceness !== 0 && !utils.isWindows) {
  123. args.unshift('-n', options.niceness, command);
  124. command = 'nice';
  125. }
  126. var stdoutRing = utils.linesRing(maxLines);
  127. var stdoutClosed = false;
  128. var stderrRing = utils.linesRing(maxLines);
  129. var stderrClosed = false;
  130. // Spawn process
  131. var ffmpegProc = spawn(command, args, options);
  132. if (ffmpegProc.stderr) {
  133. ffmpegProc.stderr.setEncoding('utf8');
  134. }
  135. ffmpegProc.on('error', function(err) {
  136. endCB(err);
  137. });
  138. // Ensure we wait for captured streams to end before calling endCB
  139. var exitError = null;
  140. function handleExit(err) {
  141. if (err) {
  142. exitError = err;
  143. }
  144. if (processExited && (stdoutClosed || !options.captureStdout) && stderrClosed) {
  145. endCB(exitError, stdoutRing, stderrRing);
  146. }
  147. }
  148. // Handle process exit
  149. var processExited = false;
  150. ffmpegProc.on('exit', function(code, signal) {
  151. processExited = true;
  152. if (signal) {
  153. handleExit(new Error('ffmpeg was killed with signal ' + signal));
  154. } else if (code) {
  155. handleExit(new Error('ffmpeg exited with code ' + code));
  156. } else {
  157. handleExit();
  158. }
  159. });
  160. // Capture stdout if specified
  161. if (options.captureStdout) {
  162. ffmpegProc.stdout.on('data', function(data) {
  163. stdoutRing.append(data);
  164. });
  165. ffmpegProc.stdout.on('close', function() {
  166. stdoutRing.close();
  167. stdoutClosed = true;
  168. handleExit();
  169. });
  170. }
  171. // Capture stderr if specified
  172. ffmpegProc.stderr.on('data', function(data) {
  173. stderrRing.append(data);
  174. });
  175. ffmpegProc.stderr.on('close', function() {
  176. stderrRing.close();
  177. stderrClosed = true;
  178. handleExit();
  179. });
  180. // Call process callback
  181. processCB(ffmpegProc, stdoutRing, stderrRing);
  182. });
  183. };
  184. /**
  185. * Build the argument list for an ffmpeg command
  186. *
  187. * @method FfmpegCommand#_getArguments
  188. * @return argument list
  189. * @private
  190. */
  191. proto._getArguments = function() {
  192. var complexFilters = this._complexFilters.get();
  193. var fileOutput = this._outputs.some(function(output) {
  194. return output.isFile;
  195. });
  196. return [].concat(
  197. // Inputs and input options
  198. this._inputs.reduce(function(args, input) {
  199. var source = (typeof input.source === 'string') ? input.source : 'pipe:0';
  200. // For each input, add input options, then '-i <source>'
  201. return args.concat(
  202. input.options.get(),
  203. ['-i', source]
  204. );
  205. }, []),
  206. // Global options
  207. this._global.get(),
  208. // Overwrite if we have file outputs
  209. fileOutput ? ['-y'] : [],
  210. // Complex filters
  211. complexFilters,
  212. // Outputs, filters and output options
  213. this._outputs.reduce(function(args, output) {
  214. var sizeFilters = utils.makeFilterStrings(output.sizeFilters.get());
  215. var audioFilters = output.audioFilters.get();
  216. var videoFilters = output.videoFilters.get().concat(sizeFilters);
  217. var outputArg;
  218. if (!output.target) {
  219. outputArg = [];
  220. } else if (typeof output.target === 'string') {
  221. outputArg = [output.target];
  222. } else {
  223. outputArg = ['pipe:1'];
  224. }
  225. return args.concat(
  226. output.audio.get(),
  227. audioFilters.length ? ['-filter:a', audioFilters.join(',')] : [],
  228. output.video.get(),
  229. videoFilters.length ? ['-filter:v', videoFilters.join(',')] : [],
  230. output.options.get(),
  231. outputArg
  232. );
  233. }, [])
  234. );
  235. };
  236. /**
  237. * Prepare execution of an ffmpeg command
  238. *
  239. * Checks prerequisites for the execution of the command (codec/format availability, flvtool...),
  240. * then builds the argument list for ffmpeg and pass them to 'callback'.
  241. *
  242. * @method FfmpegCommand#_prepare
  243. * @param {Function} callback callback with signature (err, args)
  244. * @param {Boolean} [readMetadata=false] read metadata before processing
  245. * @private
  246. */
  247. proto._prepare = function(callback, readMetadata) {
  248. var self = this;
  249. async.waterfall([
  250. // Check codecs and formats
  251. function(cb) {
  252. self._checkCapabilities(cb);
  253. },
  254. // Read metadata if required
  255. function(cb) {
  256. if (!readMetadata) {
  257. return cb();
  258. }
  259. self.ffprobe(0, function(err, data) {
  260. if (!err) {
  261. self._ffprobeData = data;
  262. }
  263. cb();
  264. });
  265. },
  266. // Check for flvtool2/flvmeta if necessary
  267. function(cb) {
  268. var flvmeta = self._outputs.some(function(output) {
  269. // Remove flvmeta flag on non-file output
  270. if (output.flags.flvmeta && !output.isFile) {
  271. self.logger.warn('Updating flv metadata is only supported for files');
  272. output.flags.flvmeta = false;
  273. }
  274. return output.flags.flvmeta;
  275. });
  276. if (flvmeta) {
  277. self._getFlvtoolPath(function(err) {
  278. cb(err);
  279. });
  280. } else {
  281. cb();
  282. }
  283. },
  284. // Build argument list
  285. function(cb) {
  286. var args;
  287. try {
  288. args = self._getArguments();
  289. } catch(e) {
  290. return cb(e);
  291. }
  292. cb(null, args);
  293. },
  294. // Add "-strict experimental" option where needed
  295. function(args, cb) {
  296. self.availableEncoders(function(err, encoders) {
  297. for (var i = 0; i < args.length; i++) {
  298. if (args[i] === '-acodec' || args[i] === '-vcodec') {
  299. i++;
  300. if ((args[i] in encoders) && encoders[args[i]].experimental) {
  301. args.splice(i + 1, 0, '-strict', 'experimental');
  302. i += 2;
  303. }
  304. }
  305. }
  306. cb(null, args);
  307. });
  308. }
  309. ], callback);
  310. if (!readMetadata) {
  311. // Read metadata as soon as 'progress' listeners are added
  312. if (this.listeners('progress').length > 0) {
  313. // Read metadata in parallel
  314. runFfprobe(this);
  315. } else {
  316. // Read metadata as soon as the first 'progress' listener is added
  317. this.once('newListener', function(event) {
  318. if (event === 'progress') {
  319. runFfprobe(this);
  320. }
  321. });
  322. }
  323. }
  324. };
  325. /**
  326. * Run ffmpeg command
  327. *
  328. * @method FfmpegCommand#run
  329. * @category Processing
  330. * @aliases exec,execute
  331. */
  332. proto.exec =
  333. proto.execute =
  334. proto.run = function() {
  335. var self = this;
  336. // Check if at least one output is present
  337. var outputPresent = this._outputs.some(function(output) {
  338. return 'target' in output;
  339. });
  340. if (!outputPresent) {
  341. throw new Error('No output specified');
  342. }
  343. // Get output stream if any
  344. var outputStream = this._outputs.filter(function(output) {
  345. return typeof output.target !== 'string';
  346. })[0];
  347. // Get input stream if any
  348. var inputStream = this._inputs.filter(function(input) {
  349. return typeof input.source !== 'string';
  350. })[0];
  351. // Ensure we send 'end' or 'error' only once
  352. var ended = false;
  353. function emitEnd(err, stdout, stderr) {
  354. if (!ended) {
  355. ended = true;
  356. if (err) {
  357. self.emit('error', err, stdout, stderr);
  358. } else {
  359. self.emit('end', stdout, stderr);
  360. }
  361. }
  362. }
  363. self._prepare(function(err, args) {
  364. if (err) {
  365. return emitEnd(err);
  366. }
  367. // Run ffmpeg
  368. self._spawnFfmpeg(
  369. args,
  370. {
  371. captureStdout: !outputStream,
  372. niceness: self.options.niceness,
  373. cwd: self.options.cwd
  374. },
  375. function processCB(ffmpegProc, stdoutRing, stderrRing) {
  376. self.ffmpegProc = ffmpegProc;
  377. self.emit('start', 'ffmpeg ' + args.join(' '));
  378. // Pipe input stream if any
  379. if (inputStream) {
  380. inputStream.source.on('error', function(err) {
  381. var reportingErr = new Error('Input stream error: ' + err.message);
  382. reportingErr.inputStreamError = err;
  383. emitEnd(reportingErr);
  384. ffmpegProc.kill();
  385. });
  386. inputStream.source.resume();
  387. inputStream.source.pipe(ffmpegProc.stdin);
  388. // Set stdin error handler on ffmpeg (prevents nodejs catching the error, but
  389. // ffmpeg will fail anyway, so no need to actually handle anything)
  390. ffmpegProc.stdin.on('error', function() {});
  391. }
  392. // Setup timeout if requested
  393. var processTimer;
  394. if (self.options.timeout) {
  395. processTimer = setTimeout(function() {
  396. var msg = 'process ran into a timeout (' + self.options.timeout + 's)';
  397. emitEnd(new Error(msg), stdoutRing.get(), stderrRing.get());
  398. ffmpegProc.kill();
  399. }, self.options.timeout * 1000);
  400. }
  401. if (outputStream) {
  402. // Pipe ffmpeg stdout to output stream
  403. ffmpegProc.stdout.pipe(outputStream.target, outputStream.pipeopts);
  404. // Handle output stream events
  405. outputStream.target.on('close', function() {
  406. self.logger.debug('Output stream closed, scheduling kill for ffmpeg process');
  407. // Don't kill process yet, to give a chance to ffmpeg to
  408. // terminate successfully first This is necessary because
  409. // under load, the process 'exit' event sometimes happens
  410. // after the output stream 'close' event.
  411. setTimeout(function() {
  412. emitEnd(new Error('Output stream closed'));
  413. ffmpegProc.kill();
  414. }, 20);
  415. });
  416. outputStream.target.on('error', function(err) {
  417. self.logger.debug('Output stream error, killing ffmpeg process');
  418. var reportingErr = new Error('Output stream error: ' + err.message);
  419. reportingErr.outputStreamError = err;
  420. emitEnd(reportingErr, stdoutRing.get(), stderrRing.get());
  421. ffmpegProc.kill('SIGKILL');
  422. });
  423. }
  424. // Setup stderr handling
  425. if (stderrRing) {
  426. // 'stderr' event
  427. if (self.listeners('stderr').length) {
  428. stderrRing.callback(function(line) {
  429. self.emit('stderr', line);
  430. });
  431. }
  432. // 'codecData' event
  433. if (self.listeners('codecData').length) {
  434. var codecDataSent = false;
  435. var codecObject = {};
  436. stderrRing.callback(function(line) {
  437. if (!codecDataSent)
  438. codecDataSent = utils.extractCodecData(self, line, codecObject);
  439. });
  440. }
  441. // 'progress' event
  442. if (self.listeners('progress').length) {
  443. stderrRing.callback(function(line) {
  444. utils.extractProgress(self, line);
  445. });
  446. }
  447. }
  448. },
  449. function endCB(err, stdoutRing, stderrRing) {
  450. delete self.ffmpegProc;
  451. if (err) {
  452. if (err.message.match(/ffmpeg exited with code/)) {
  453. // Add ffmpeg error message
  454. err.message += ': ' + utils.extractError(stderrRing.get());
  455. }
  456. emitEnd(err, stdoutRing.get(), stderrRing.get());
  457. } else {
  458. // Find out which outputs need flv metadata
  459. var flvmeta = self._outputs.filter(function(output) {
  460. return output.flags.flvmeta;
  461. });
  462. if (flvmeta.length) {
  463. self._getFlvtoolPath(function(err, flvtool) {
  464. if (err) {
  465. return emitEnd(err);
  466. }
  467. async.each(
  468. flvmeta,
  469. function(output, cb) {
  470. spawn(flvtool, ['-U', output.target])
  471. .on('error', function(err) {
  472. cb(new Error('Error running ' + flvtool + ' on ' + output.target + ': ' + err.message));
  473. })
  474. .on('exit', function(code, signal) {
  475. if (code !== 0 || signal) {
  476. cb(
  477. new Error(flvtool + ' ' +
  478. (signal ? 'received signal ' + signal
  479. : 'exited with code ' + code)) +
  480. ' when running on ' + output.target
  481. );
  482. } else {
  483. cb();
  484. }
  485. });
  486. },
  487. function(err) {
  488. if (err) {
  489. emitEnd(err);
  490. } else {
  491. emitEnd(null, stdoutRing.get(), stderrRing.get());
  492. }
  493. }
  494. );
  495. });
  496. } else {
  497. emitEnd(null, stdoutRing.get(), stderrRing.get());
  498. }
  499. }
  500. }
  501. );
  502. });
  503. };
  504. /**
  505. * Renice current and/or future ffmpeg processes
  506. *
  507. * Ignored on Windows platforms.
  508. *
  509. * @method FfmpegCommand#renice
  510. * @category Processing
  511. *
  512. * @param {Number} [niceness=0] niceness value between -20 (highest priority) and 20 (lowest priority)
  513. * @return FfmpegCommand
  514. */
  515. proto.renice = function(niceness) {
  516. if (!utils.isWindows) {
  517. niceness = niceness || 0;
  518. if (niceness < -20 || niceness > 20) {
  519. this.logger.warn('Invalid niceness value: ' + niceness + ', must be between -20 and 20');
  520. }
  521. niceness = Math.min(20, Math.max(-20, niceness));
  522. this.options.niceness = niceness;
  523. if (this.ffmpegProc) {
  524. var logger = this.logger;
  525. var pid = this.ffmpegProc.pid;
  526. var renice = spawn('renice', [niceness, '-p', pid]);
  527. renice.on('error', function(err) {
  528. logger.warn('could not renice process ' + pid + ': ' + err.message);
  529. });
  530. renice.on('exit', function(code, signal) {
  531. if (signal) {
  532. logger.warn('could not renice process ' + pid + ': renice was killed by signal ' + signal);
  533. } else if (code) {
  534. logger.warn('could not renice process ' + pid + ': renice exited with ' + code);
  535. } else {
  536. logger.info('successfully reniced process ' + pid + ' to ' + niceness + ' niceness');
  537. }
  538. });
  539. }
  540. }
  541. return this;
  542. };
  543. /**
  544. * Kill current ffmpeg process, if any
  545. *
  546. * @method FfmpegCommand#kill
  547. * @category Processing
  548. *
  549. * @param {String} [signal=SIGKILL] signal name
  550. * @return FfmpegCommand
  551. */
  552. proto.kill = function(signal) {
  553. if (!this.ffmpegProc) {
  554. this.logger.warn('No running ffmpeg process, cannot send signal');
  555. } else {
  556. this.ffmpegProc.kill(signal || 'SIGKILL');
  557. }
  558. return this;
  559. };
  560. };