ffprobe.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /*jshint node:true, laxcomma:true*/
  2. 'use strict';
  3. var spawn = require('child_process').spawn;
  4. function legacyTag(key) { return key.match(/^TAG:/); }
  5. function legacyDisposition(key) { return key.match(/^DISPOSITION:/); }
  6. function parseFfprobeOutput(out) {
  7. var lines = out.split(/\r\n|\r|\n/);
  8. lines = lines.filter(function (line) {
  9. return line.length > 0;
  10. });
  11. var data = {
  12. streams: [],
  13. format: {},
  14. chapters: []
  15. };
  16. function parseBlock(name) {
  17. var data = {};
  18. var line = lines.shift();
  19. while (typeof line !== 'undefined') {
  20. if (line.toLowerCase() == '[/'+name+']') {
  21. return data;
  22. } else if (line.match(/^\[/)) {
  23. line = lines.shift();
  24. continue;
  25. }
  26. var kv = line.match(/^([^=]+)=(.*)$/);
  27. if (kv) {
  28. if (!(kv[1].match(/^TAG:/)) && kv[2].match(/^[0-9]+(\.[0-9]+)?$/)) {
  29. data[kv[1]] = Number(kv[2]);
  30. } else {
  31. data[kv[1]] = kv[2];
  32. }
  33. }
  34. line = lines.shift();
  35. }
  36. return data;
  37. }
  38. var line = lines.shift();
  39. while (typeof line !== 'undefined') {
  40. if (line.match(/^\[stream/i)) {
  41. var stream = parseBlock('stream');
  42. data.streams.push(stream);
  43. } else if (line.match(/^\[chapter/i)) {
  44. var chapter = parseBlock('chapter');
  45. data.chapters.push(chapter);
  46. } else if (line.toLowerCase() === '[format]') {
  47. data.format = parseBlock('format');
  48. }
  49. line = lines.shift();
  50. }
  51. return data;
  52. }
  53. module.exports = function(proto) {
  54. /**
  55. * A callback passed to the {@link FfmpegCommand#ffprobe} method.
  56. *
  57. * @callback FfmpegCommand~ffprobeCallback
  58. *
  59. * @param {Error|null} err error object or null if no error happened
  60. * @param {Object} ffprobeData ffprobe output data; this object
  61. * has the same format as what the following command returns:
  62. *
  63. * `ffprobe -print_format json -show_streams -show_format INPUTFILE`
  64. * @param {Array} ffprobeData.streams stream information
  65. * @param {Object} ffprobeData.format format information
  66. */
  67. /**
  68. * Run ffprobe on last specified input
  69. *
  70. * @method FfmpegCommand#ffprobe
  71. * @category Metadata
  72. *
  73. * @param {?Number} [index] 0-based index of input to probe (defaults to last input)
  74. * @param {?String[]} [options] array of output options to return
  75. * @param {FfmpegCommand~ffprobeCallback} callback callback function
  76. *
  77. */
  78. proto.ffprobe = function() {
  79. var input, index = null, options = [], callback;
  80. // the last argument should be the callback
  81. var callback = arguments[arguments.length - 1];
  82. var ended = false
  83. function handleCallback(err, data) {
  84. if (!ended) {
  85. ended = true;
  86. callback(err, data);
  87. }
  88. };
  89. // map the arguments to the correct variable names
  90. switch (arguments.length) {
  91. case 3:
  92. index = arguments[0];
  93. options = arguments[1];
  94. break;
  95. case 2:
  96. if (typeof arguments[0] === 'number') {
  97. index = arguments[0];
  98. } else if (Array.isArray(arguments[0])) {
  99. options = arguments[0];
  100. }
  101. break;
  102. }
  103. if (index === null) {
  104. if (!this._currentInput) {
  105. return handleCallback(new Error('No input specified'));
  106. }
  107. input = this._currentInput;
  108. } else {
  109. input = this._inputs[index];
  110. if (!input) {
  111. return handleCallback(new Error('Invalid input index'));
  112. }
  113. }
  114. // Find ffprobe
  115. this._getFfprobePath(function(err, path) {
  116. if (err) {
  117. return handleCallback(err);
  118. } else if (!path) {
  119. return handleCallback(new Error('Cannot find ffprobe'));
  120. }
  121. var stdout = '';
  122. var stdoutClosed = false;
  123. var stderr = '';
  124. var stderrClosed = false;
  125. // Spawn ffprobe
  126. var src = input.isStream ? 'pipe:0' : input.source;
  127. var ffprobe = spawn(path, ['-show_streams', '-show_format'].concat(options, src));
  128. if (input.isStream) {
  129. // Skip errors on stdin. These get thrown when ffprobe is complete and
  130. // there seems to be no way hook in and close stdin before it throws.
  131. ffprobe.stdin.on('error', function(err) {
  132. if (['ECONNRESET', 'EPIPE'].indexOf(err.code) >= 0) { return; }
  133. handleCallback(err);
  134. });
  135. // Once ffprobe's input stream closes, we need no more data from the
  136. // input
  137. ffprobe.stdin.on('close', function() {
  138. input.source.pause();
  139. input.source.unpipe(ffprobe.stdin);
  140. });
  141. input.source.pipe(ffprobe.stdin);
  142. }
  143. ffprobe.on('error', callback);
  144. // Ensure we wait for captured streams to end before calling callback
  145. var exitError = null;
  146. function handleExit(err) {
  147. if (err) {
  148. exitError = err;
  149. }
  150. if (processExited && stdoutClosed && stderrClosed) {
  151. if (exitError) {
  152. if (stderr) {
  153. exitError.message += '\n' + stderr;
  154. }
  155. return handleCallback(exitError);
  156. }
  157. // Process output
  158. var data = parseFfprobeOutput(stdout);
  159. // Handle legacy output with "TAG:x" and "DISPOSITION:x" keys
  160. [data.format].concat(data.streams).forEach(function(target) {
  161. if (target) {
  162. var legacyTagKeys = Object.keys(target).filter(legacyTag);
  163. if (legacyTagKeys.length) {
  164. target.tags = target.tags || {};
  165. legacyTagKeys.forEach(function(tagKey) {
  166. target.tags[tagKey.substr(4)] = target[tagKey];
  167. delete target[tagKey];
  168. });
  169. }
  170. var legacyDispositionKeys = Object.keys(target).filter(legacyDisposition);
  171. if (legacyDispositionKeys.length) {
  172. target.disposition = target.disposition || {};
  173. legacyDispositionKeys.forEach(function(dispositionKey) {
  174. target.disposition[dispositionKey.substr(12)] = target[dispositionKey];
  175. delete target[dispositionKey];
  176. });
  177. }
  178. }
  179. });
  180. handleCallback(null, data);
  181. }
  182. }
  183. // Handle ffprobe exit
  184. var processExited = false;
  185. ffprobe.on('exit', function(code, signal) {
  186. processExited = true;
  187. if (code) {
  188. handleExit(new Error('ffprobe exited with code ' + code));
  189. } else if (signal) {
  190. handleExit(new Error('ffprobe was killed with signal ' + signal));
  191. } else {
  192. handleExit();
  193. }
  194. });
  195. // Handle stdout/stderr streams
  196. ffprobe.stdout.on('data', function(data) {
  197. stdout += data;
  198. });
  199. ffprobe.stdout.on('close', function() {
  200. stdoutClosed = true;
  201. handleExit();
  202. });
  203. ffprobe.stderr.on('data', function(data) {
  204. stderr += data;
  205. });
  206. ffprobe.stderr.on('close', function() {
  207. stderrClosed = true;
  208. handleExit();
  209. });
  210. });
  211. };
  212. };