capabilities.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. /*jshint node:true*/
  2. 'use strict';
  3. var fs = require('fs');
  4. var path = require('path');
  5. var async = require('async');
  6. var utils = require('./utils');
  7. /*
  8. *! Capability helpers
  9. */
  10. var avCodecRegexp = /^\s*([D ])([E ])([VAS])([S ])([D ])([T ]) ([^ ]+) +(.*)$/;
  11. var ffCodecRegexp = /^\s*([D\.])([E\.])([VAS])([I\.])([L\.])([S\.]) ([^ ]+) +(.*)$/;
  12. var ffEncodersRegexp = /\(encoders:([^\)]+)\)/;
  13. var ffDecodersRegexp = /\(decoders:([^\)]+)\)/;
  14. var encodersRegexp = /^\s*([VAS\.])([F\.])([S\.])([X\.])([B\.])([D\.]) ([^ ]+) +(.*)$/;
  15. var formatRegexp = /^\s*([D ])([E ]) ([^ ]+) +(.*)$/;
  16. var lineBreakRegexp = /\r\n|\r|\n/;
  17. var filterRegexp = /^(?: [T\.][S\.][C\.] )?([^ ]+) +(AA?|VV?|\|)->(AA?|VV?|\|) +(.*)$/;
  18. var cache = {};
  19. module.exports = function(proto) {
  20. /**
  21. * Manually define the ffmpeg binary full path.
  22. *
  23. * @method FfmpegCommand#setFfmpegPath
  24. *
  25. * @param {String} ffmpegPath The full path to the ffmpeg binary.
  26. * @return FfmpegCommand
  27. */
  28. proto.setFfmpegPath = function(ffmpegPath) {
  29. cache.ffmpegPath = ffmpegPath;
  30. return this;
  31. };
  32. /**
  33. * Manually define the ffprobe binary full path.
  34. *
  35. * @method FfmpegCommand#setFfprobePath
  36. *
  37. * @param {String} ffprobePath The full path to the ffprobe binary.
  38. * @return FfmpegCommand
  39. */
  40. proto.setFfprobePath = function(ffprobePath) {
  41. cache.ffprobePath = ffprobePath;
  42. return this;
  43. };
  44. /**
  45. * Manually define the flvtool2/flvmeta binary full path.
  46. *
  47. * @method FfmpegCommand#setFlvtoolPath
  48. *
  49. * @param {String} flvtool The full path to the flvtool2 or flvmeta binary.
  50. * @return FfmpegCommand
  51. */
  52. proto.setFlvtoolPath = function(flvtool) {
  53. cache.flvtoolPath = flvtool;
  54. return this;
  55. };
  56. /**
  57. * Forget executable paths
  58. *
  59. * (only used for testing purposes)
  60. *
  61. * @method FfmpegCommand#_forgetPaths
  62. * @private
  63. */
  64. proto._forgetPaths = function() {
  65. delete cache.ffmpegPath;
  66. delete cache.ffprobePath;
  67. delete cache.flvtoolPath;
  68. };
  69. /**
  70. * Check for ffmpeg availability
  71. *
  72. * If the FFMPEG_PATH environment variable is set, try to use it.
  73. * If it is unset or incorrect, try to find ffmpeg in the PATH instead.
  74. *
  75. * @method FfmpegCommand#_getFfmpegPath
  76. * @param {Function} callback callback with signature (err, path)
  77. * @private
  78. */
  79. proto._getFfmpegPath = function(callback) {
  80. if ('ffmpegPath' in cache) {
  81. return callback(null, cache.ffmpegPath);
  82. }
  83. async.waterfall([
  84. // Try FFMPEG_PATH
  85. function(cb) {
  86. if (process.env.FFMPEG_PATH) {
  87. fs.exists(process.env.FFMPEG_PATH, function(exists) {
  88. if (exists) {
  89. cb(null, process.env.FFMPEG_PATH);
  90. } else {
  91. cb(null, '');
  92. }
  93. });
  94. } else {
  95. cb(null, '');
  96. }
  97. },
  98. // Search in the PATH
  99. function(ffmpeg, cb) {
  100. if (ffmpeg.length) {
  101. return cb(null, ffmpeg);
  102. }
  103. utils.which('ffmpeg', function(err, ffmpeg) {
  104. cb(err, ffmpeg);
  105. });
  106. }
  107. ], function(err, ffmpeg) {
  108. if (err) {
  109. callback(err);
  110. } else {
  111. callback(null, cache.ffmpegPath = (ffmpeg || ''));
  112. }
  113. });
  114. };
  115. /**
  116. * Check for ffprobe availability
  117. *
  118. * If the FFPROBE_PATH environment variable is set, try to use it.
  119. * If it is unset or incorrect, try to find ffprobe in the PATH instead.
  120. * If this still fails, try to find ffprobe in the same directory as ffmpeg.
  121. *
  122. * @method FfmpegCommand#_getFfprobePath
  123. * @param {Function} callback callback with signature (err, path)
  124. * @private
  125. */
  126. proto._getFfprobePath = function(callback) {
  127. var self = this;
  128. if ('ffprobePath' in cache) {
  129. return callback(null, cache.ffprobePath);
  130. }
  131. async.waterfall([
  132. // Try FFPROBE_PATH
  133. function(cb) {
  134. if (process.env.FFPROBE_PATH) {
  135. fs.exists(process.env.FFPROBE_PATH, function(exists) {
  136. cb(null, exists ? process.env.FFPROBE_PATH : '');
  137. });
  138. } else {
  139. cb(null, '');
  140. }
  141. },
  142. // Search in the PATH
  143. function(ffprobe, cb) {
  144. if (ffprobe.length) {
  145. return cb(null, ffprobe);
  146. }
  147. utils.which('ffprobe', function(err, ffprobe) {
  148. cb(err, ffprobe);
  149. });
  150. },
  151. // Search in the same directory as ffmpeg
  152. function(ffprobe, cb) {
  153. if (ffprobe.length) {
  154. return cb(null, ffprobe);
  155. }
  156. self._getFfmpegPath(function(err, ffmpeg) {
  157. if (err) {
  158. cb(err);
  159. } else if (ffmpeg.length) {
  160. var name = utils.isWindows ? 'ffprobe.exe' : 'ffprobe';
  161. var ffprobe = path.join(path.dirname(ffmpeg), name);
  162. fs.exists(ffprobe, function(exists) {
  163. cb(null, exists ? ffprobe : '');
  164. });
  165. } else {
  166. cb(null, '');
  167. }
  168. });
  169. }
  170. ], function(err, ffprobe) {
  171. if (err) {
  172. callback(err);
  173. } else {
  174. callback(null, cache.ffprobePath = (ffprobe || ''));
  175. }
  176. });
  177. };
  178. /**
  179. * Check for flvtool2/flvmeta availability
  180. *
  181. * If the FLVTOOL2_PATH or FLVMETA_PATH environment variable are set, try to use them.
  182. * If both are either unset or incorrect, try to find flvtool2 or flvmeta in the PATH instead.
  183. *
  184. * @method FfmpegCommand#_getFlvtoolPath
  185. * @param {Function} callback callback with signature (err, path)
  186. * @private
  187. */
  188. proto._getFlvtoolPath = function(callback) {
  189. if ('flvtoolPath' in cache) {
  190. return callback(null, cache.flvtoolPath);
  191. }
  192. async.waterfall([
  193. // Try FLVMETA_PATH
  194. function(cb) {
  195. if (process.env.FLVMETA_PATH) {
  196. fs.exists(process.env.FLVMETA_PATH, function(exists) {
  197. cb(null, exists ? process.env.FLVMETA_PATH : '');
  198. });
  199. } else {
  200. cb(null, '');
  201. }
  202. },
  203. // Try FLVTOOL2_PATH
  204. function(flvtool, cb) {
  205. if (flvtool.length) {
  206. return cb(null, flvtool);
  207. }
  208. if (process.env.FLVTOOL2_PATH) {
  209. fs.exists(process.env.FLVTOOL2_PATH, function(exists) {
  210. cb(null, exists ? process.env.FLVTOOL2_PATH : '');
  211. });
  212. } else {
  213. cb(null, '');
  214. }
  215. },
  216. // Search for flvmeta in the PATH
  217. function(flvtool, cb) {
  218. if (flvtool.length) {
  219. return cb(null, flvtool);
  220. }
  221. utils.which('flvmeta', function(err, flvmeta) {
  222. cb(err, flvmeta);
  223. });
  224. },
  225. // Search for flvtool2 in the PATH
  226. function(flvtool, cb) {
  227. if (flvtool.length) {
  228. return cb(null, flvtool);
  229. }
  230. utils.which('flvtool2', function(err, flvtool2) {
  231. cb(err, flvtool2);
  232. });
  233. },
  234. ], function(err, flvtool) {
  235. if (err) {
  236. callback(err);
  237. } else {
  238. callback(null, cache.flvtoolPath = (flvtool || ''));
  239. }
  240. });
  241. };
  242. /**
  243. * A callback passed to {@link FfmpegCommand#availableFilters}.
  244. *
  245. * @callback FfmpegCommand~filterCallback
  246. * @param {Error|null} err error object or null if no error happened
  247. * @param {Object} filters filter object with filter names as keys and the following
  248. * properties for each filter:
  249. * @param {String} filters.description filter description
  250. * @param {String} filters.input input type, one of 'audio', 'video' and 'none'
  251. * @param {Boolean} filters.multipleInputs whether the filter supports multiple inputs
  252. * @param {String} filters.output output type, one of 'audio', 'video' and 'none'
  253. * @param {Boolean} filters.multipleOutputs whether the filter supports multiple outputs
  254. */
  255. /**
  256. * Query ffmpeg for available filters
  257. *
  258. * @method FfmpegCommand#availableFilters
  259. * @category Capabilities
  260. * @aliases getAvailableFilters
  261. *
  262. * @param {FfmpegCommand~filterCallback} callback callback function
  263. */
  264. proto.availableFilters =
  265. proto.getAvailableFilters = function(callback) {
  266. if ('filters' in cache) {
  267. return callback(null, cache.filters);
  268. }
  269. this._spawnFfmpeg(['-filters'], { captureStdout: true, stdoutLines: 0 }, function (err, stdoutRing) {
  270. if (err) {
  271. return callback(err);
  272. }
  273. var stdout = stdoutRing.get();
  274. var lines = stdout.split('\n');
  275. var data = {};
  276. var types = { A: 'audio', V: 'video', '|': 'none' };
  277. lines.forEach(function(line) {
  278. var match = line.match(filterRegexp);
  279. if (match) {
  280. data[match[1]] = {
  281. description: match[4],
  282. input: types[match[2].charAt(0)],
  283. multipleInputs: match[2].length > 1,
  284. output: types[match[3].charAt(0)],
  285. multipleOutputs: match[3].length > 1
  286. };
  287. }
  288. });
  289. callback(null, cache.filters = data);
  290. });
  291. };
  292. /**
  293. * A callback passed to {@link FfmpegCommand#availableCodecs}.
  294. *
  295. * @callback FfmpegCommand~codecCallback
  296. * @param {Error|null} err error object or null if no error happened
  297. * @param {Object} codecs codec object with codec names as keys and the following
  298. * properties for each codec (more properties may be available depending on the
  299. * ffmpeg version used):
  300. * @param {String} codecs.description codec description
  301. * @param {Boolean} codecs.canDecode whether the codec is able to decode streams
  302. * @param {Boolean} codecs.canEncode whether the codec is able to encode streams
  303. */
  304. /**
  305. * Query ffmpeg for available codecs
  306. *
  307. * @method FfmpegCommand#availableCodecs
  308. * @category Capabilities
  309. * @aliases getAvailableCodecs
  310. *
  311. * @param {FfmpegCommand~codecCallback} callback callback function
  312. */
  313. proto.availableCodecs =
  314. proto.getAvailableCodecs = function(callback) {
  315. if ('codecs' in cache) {
  316. return callback(null, cache.codecs);
  317. }
  318. this._spawnFfmpeg(['-codecs'], { captureStdout: true, stdoutLines: 0 }, function(err, stdoutRing) {
  319. if (err) {
  320. return callback(err);
  321. }
  322. var stdout = stdoutRing.get();
  323. var lines = stdout.split(lineBreakRegexp);
  324. var data = {};
  325. lines.forEach(function(line) {
  326. var match = line.match(avCodecRegexp);
  327. if (match && match[7] !== '=') {
  328. data[match[7]] = {
  329. type: { 'V': 'video', 'A': 'audio', 'S': 'subtitle' }[match[3]],
  330. description: match[8],
  331. canDecode: match[1] === 'D',
  332. canEncode: match[2] === 'E',
  333. drawHorizBand: match[4] === 'S',
  334. directRendering: match[5] === 'D',
  335. weirdFrameTruncation: match[6] === 'T'
  336. };
  337. }
  338. match = line.match(ffCodecRegexp);
  339. if (match && match[7] !== '=') {
  340. var codecData = data[match[7]] = {
  341. type: { 'V': 'video', 'A': 'audio', 'S': 'subtitle' }[match[3]],
  342. description: match[8],
  343. canDecode: match[1] === 'D',
  344. canEncode: match[2] === 'E',
  345. intraFrameOnly: match[4] === 'I',
  346. isLossy: match[5] === 'L',
  347. isLossless: match[6] === 'S'
  348. };
  349. var encoders = codecData.description.match(ffEncodersRegexp);
  350. encoders = encoders ? encoders[1].trim().split(' ') : [];
  351. var decoders = codecData.description.match(ffDecodersRegexp);
  352. decoders = decoders ? decoders[1].trim().split(' ') : [];
  353. if (encoders.length || decoders.length) {
  354. var coderData = {};
  355. utils.copy(codecData, coderData);
  356. delete coderData.canEncode;
  357. delete coderData.canDecode;
  358. encoders.forEach(function(name) {
  359. data[name] = {};
  360. utils.copy(coderData, data[name]);
  361. data[name].canEncode = true;
  362. });
  363. decoders.forEach(function(name) {
  364. if (name in data) {
  365. data[name].canDecode = true;
  366. } else {
  367. data[name] = {};
  368. utils.copy(coderData, data[name]);
  369. data[name].canDecode = true;
  370. }
  371. });
  372. }
  373. }
  374. });
  375. callback(null, cache.codecs = data);
  376. });
  377. };
  378. /**
  379. * A callback passed to {@link FfmpegCommand#availableEncoders}.
  380. *
  381. * @callback FfmpegCommand~encodersCallback
  382. * @param {Error|null} err error object or null if no error happened
  383. * @param {Object} encoders encoders object with encoder names as keys and the following
  384. * properties for each encoder:
  385. * @param {String} encoders.description codec description
  386. * @param {Boolean} encoders.type "audio", "video" or "subtitle"
  387. * @param {Boolean} encoders.frameMT whether the encoder is able to do frame-level multithreading
  388. * @param {Boolean} encoders.sliceMT whether the encoder is able to do slice-level multithreading
  389. * @param {Boolean} encoders.experimental whether the encoder is experimental
  390. * @param {Boolean} encoders.drawHorizBand whether the encoder supports draw_horiz_band
  391. * @param {Boolean} encoders.directRendering whether the encoder supports direct encoding method 1
  392. */
  393. /**
  394. * Query ffmpeg for available encoders
  395. *
  396. * @method FfmpegCommand#availableEncoders
  397. * @category Capabilities
  398. * @aliases getAvailableEncoders
  399. *
  400. * @param {FfmpegCommand~encodersCallback} callback callback function
  401. */
  402. proto.availableEncoders =
  403. proto.getAvailableEncoders = function(callback) {
  404. if ('encoders' in cache) {
  405. return callback(null, cache.encoders);
  406. }
  407. this._spawnFfmpeg(['-encoders'], { captureStdout: true, stdoutLines: 0 }, function(err, stdoutRing) {
  408. if (err) {
  409. return callback(err);
  410. }
  411. var stdout = stdoutRing.get();
  412. var lines = stdout.split(lineBreakRegexp);
  413. var data = {};
  414. lines.forEach(function(line) {
  415. var match = line.match(encodersRegexp);
  416. if (match && match[7] !== '=') {
  417. data[match[7]] = {
  418. type: { 'V': 'video', 'A': 'audio', 'S': 'subtitle' }[match[1]],
  419. description: match[8],
  420. frameMT: match[2] === 'F',
  421. sliceMT: match[3] === 'S',
  422. experimental: match[4] === 'X',
  423. drawHorizBand: match[5] === 'B',
  424. directRendering: match[6] === 'D'
  425. };
  426. }
  427. });
  428. callback(null, cache.encoders = data);
  429. });
  430. };
  431. /**
  432. * A callback passed to {@link FfmpegCommand#availableFormats}.
  433. *
  434. * @callback FfmpegCommand~formatCallback
  435. * @param {Error|null} err error object or null if no error happened
  436. * @param {Object} formats format object with format names as keys and the following
  437. * properties for each format:
  438. * @param {String} formats.description format description
  439. * @param {Boolean} formats.canDemux whether the format is able to demux streams from an input file
  440. * @param {Boolean} formats.canMux whether the format is able to mux streams into an output file
  441. */
  442. /**
  443. * Query ffmpeg for available formats
  444. *
  445. * @method FfmpegCommand#availableFormats
  446. * @category Capabilities
  447. * @aliases getAvailableFormats
  448. *
  449. * @param {FfmpegCommand~formatCallback} callback callback function
  450. */
  451. proto.availableFormats =
  452. proto.getAvailableFormats = function(callback) {
  453. if ('formats' in cache) {
  454. return callback(null, cache.formats);
  455. }
  456. // Run ffmpeg -formats
  457. this._spawnFfmpeg(['-formats'], { captureStdout: true, stdoutLines: 0 }, function (err, stdoutRing) {
  458. if (err) {
  459. return callback(err);
  460. }
  461. // Parse output
  462. var stdout = stdoutRing.get();
  463. var lines = stdout.split(lineBreakRegexp);
  464. var data = {};
  465. lines.forEach(function(line) {
  466. var match = line.match(formatRegexp);
  467. if (match) {
  468. match[3].split(',').forEach(function(format) {
  469. if (!(format in data)) {
  470. data[format] = {
  471. description: match[4],
  472. canDemux: false,
  473. canMux: false
  474. };
  475. }
  476. if (match[1] === 'D') {
  477. data[format].canDemux = true;
  478. }
  479. if (match[2] === 'E') {
  480. data[format].canMux = true;
  481. }
  482. });
  483. }
  484. });
  485. callback(null, cache.formats = data);
  486. });
  487. };
  488. /**
  489. * Check capabilities before executing a command
  490. *
  491. * Checks whether all used codecs and formats are indeed available
  492. *
  493. * @method FfmpegCommand#_checkCapabilities
  494. * @param {Function} callback callback with signature (err)
  495. * @private
  496. */
  497. proto._checkCapabilities = function(callback) {
  498. var self = this;
  499. async.waterfall([
  500. // Get available formats
  501. function(cb) {
  502. self.availableFormats(cb);
  503. },
  504. // Check whether specified formats are available
  505. function(formats, cb) {
  506. var unavailable;
  507. // Output format(s)
  508. unavailable = self._outputs
  509. .reduce(function(fmts, output) {
  510. var format = output.options.find('-f', 1);
  511. if (format) {
  512. if (!(format[0] in formats) || !(formats[format[0]].canMux)) {
  513. fmts.push(format);
  514. }
  515. }
  516. return fmts;
  517. }, []);
  518. if (unavailable.length === 1) {
  519. return cb(new Error('Output format ' + unavailable[0] + ' is not available'));
  520. } else if (unavailable.length > 1) {
  521. return cb(new Error('Output formats ' + unavailable.join(', ') + ' are not available'));
  522. }
  523. // Input format(s)
  524. unavailable = self._inputs
  525. .reduce(function(fmts, input) {
  526. var format = input.options.find('-f', 1);
  527. if (format) {
  528. if (!(format[0] in formats) || !(formats[format[0]].canDemux)) {
  529. fmts.push(format[0]);
  530. }
  531. }
  532. return fmts;
  533. }, []);
  534. if (unavailable.length === 1) {
  535. return cb(new Error('Input format ' + unavailable[0] + ' is not available'));
  536. } else if (unavailable.length > 1) {
  537. return cb(new Error('Input formats ' + unavailable.join(', ') + ' are not available'));
  538. }
  539. cb();
  540. },
  541. // Get available codecs
  542. function(cb) {
  543. self.availableEncoders(cb);
  544. },
  545. // Check whether specified codecs are available and add strict experimental options if needed
  546. function(encoders, cb) {
  547. var unavailable;
  548. // Audio codec(s)
  549. unavailable = self._outputs.reduce(function(cdcs, output) {
  550. var acodec = output.audio.find('-acodec', 1);
  551. if (acodec && acodec[0] !== 'copy') {
  552. if (!(acodec[0] in encoders) || encoders[acodec[0]].type !== 'audio') {
  553. cdcs.push(acodec[0]);
  554. }
  555. }
  556. return cdcs;
  557. }, []);
  558. if (unavailable.length === 1) {
  559. return cb(new Error('Audio codec ' + unavailable[0] + ' is not available'));
  560. } else if (unavailable.length > 1) {
  561. return cb(new Error('Audio codecs ' + unavailable.join(', ') + ' are not available'));
  562. }
  563. // Video codec(s)
  564. unavailable = self._outputs.reduce(function(cdcs, output) {
  565. var vcodec = output.video.find('-vcodec', 1);
  566. if (vcodec && vcodec[0] !== 'copy') {
  567. if (!(vcodec[0] in encoders) || encoders[vcodec[0]].type !== 'video') {
  568. cdcs.push(vcodec[0]);
  569. }
  570. }
  571. return cdcs;
  572. }, []);
  573. if (unavailable.length === 1) {
  574. return cb(new Error('Video codec ' + unavailable[0] + ' is not available'));
  575. } else if (unavailable.length > 1) {
  576. return cb(new Error('Video codecs ' + unavailable.join(', ') + ' are not available'));
  577. }
  578. cb();
  579. }
  580. ], callback);
  581. };
  582. };