processor.js 19 KB

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