hlsdump 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. #!/usr/bin/env node
  2. var hlsdump = require('commander');
  3. hlsdump.version('0.0.0')
  4. .usage('[options] <url>')
  5. .option('-o, --output <path>', 'target file')
  6. .option('-u, --udp [host:port]', 'relay TS over UDP', function(val) {
  7. var r = { host:'localhost', port:1234 };
  8. if (val) {
  9. var s = val.split(':');
  10. if (s.length === 1) {
  11. r.port = parseInt(s[0], 10);
  12. } else {
  13. r.host = s[0];
  14. r.port = parseInt(s[1], 10);
  15. }
  16. }
  17. return r;
  18. })
  19. .option('-b, --buffer-size <bytes>|full', 'try to buffer <bytes> of input data (implies -s)', function(val) {
  20. if (val === 'full') return 0x80000000-1;
  21. return parseInt(val, 0);
  22. })
  23. .option('-s, --sync', 'clock sync using stream PCR')
  24. .option('-f, --full-stream', 'fetch all stream data')
  25. .option('-c, --concurrent <count>', 'fetch using concurrent connections', parseInt)
  26. .option('-a, --user-agent <string>', 'HTTP User-Agent')
  27. .option('-i, --info-port <port>', 'report status using HTTP + json', parseInt)
  28. .parse(process.argv);
  29. var util = require('util'),
  30. url = require('url'),
  31. fs = require('fs'),
  32. http = require('http'),
  33. crypto = require('crypto');
  34. var streamprocess = require('streamprocess'),
  35. oncemore = require('oncemore'),
  36. uristream = require('uristream');
  37. var reader = require('../lib/reader'),
  38. tssmooth = require('../lib/tssmooth'),
  39. tsblast = require('../lib/tsblast');
  40. try {
  41. var Passthrough = require('stream').Passthrough;
  42. assert(Passthrough);
  43. } catch (e) {
  44. var Passthrough = require('readable-stream/passthrough');
  45. }
  46. var stats = require('measured').createCollection();
  47. var src = hlsdump.args[0];
  48. if (!src) return hlsdump.help();
  49. if (hlsdump.bufferSize) hlsdump.sync = true;
  50. var r = reader(src, {highWaterMark:(hlsdump.concurrent || 1) - 1, fullStream:hlsdump.fullStream});
  51. var totalDuration = 0, currentSegment = -1;
  52. var reading = false;
  53. var keyCache = {};
  54. streamprocess(r, function (obj, done) {
  55. var meta = obj.meta;
  56. var duration = obj.segment.duration;
  57. var size = meta.size;
  58. var stream = oncemore(obj.stream);
  59. totalDuration += duration;
  60. console.error('piping segment', meta.url);
  61. var stopwatch = stats.timer('fetchTime').start();
  62. stream.once('close', 'end', 'error', function(err) {
  63. stopwatch.end();
  64. });
  65. reading = true;
  66. currentSegment = obj.seq;
  67. if (size === -1 || !hooked) {
  68. size = 0;
  69. obj.stream.on('data', function(chunk) {
  70. size += chunk.length;
  71. if (!hooked && size >= hlsdump.bufferSize)
  72. hook(buffer);
  73. });
  74. }
  75. var keyData = r.index.keyForSeqNo(obj.seq);
  76. if (keyData && keyData.method === 'AES-128' && keyData.uri && keyData.uri.length > 2) {
  77. fetchKey(function(err, key) {
  78. if (err) {
  79. console.error('key fetch failed:', err);
  80. return pushBuffer(stream);
  81. }
  82. var iv = new Buffer(keyData.iv.slice(-32), 'hex');
  83. var decrypt = crypto.createDecipheriv('aes-128-cbc', key, iv);
  84. stream.on('error', function(err) {
  85. decrypt.emit('error', err);
  86. });
  87. pushBuffer(oncemore(stream.pipe(decrypt)));
  88. });
  89. function fetchKey(cb) {
  90. var uri = url.resolve(r.url, keyData.uri.slice(1,-1));
  91. if (keyCache[uri]) return cb(null, keyCache[uri]);
  92. var key = new Buffer(0);
  93. oncemore(uristream(uri, { whitelist:['http', 'https', 'data'], timeout: 10*1000 }))
  94. .on('data', function(chunk) {
  95. key = Buffer.concat([key, chunk]);
  96. })
  97. .once('error', 'end', function(err) {
  98. keyCache[uri] = key;
  99. return cb(err, key);
  100. });
  101. }
  102. } else {
  103. pushBuffer(stream);
  104. }
  105. function pushBuffer(stream) {
  106. stream.pipe(buffer, { end: false });
  107. stream.once('end', 'error', function(err) {
  108. reading = false;
  109. console.error('segment done at '+totalDuration.toFixed(0)+' seconds, avg bitrate (kbps):', (size / (duration * 1024/8)).toFixed(1));
  110. if (err) {
  111. stats.meter('streamErrors').mark();
  112. console.error('stream error', err.stack || err);
  113. }
  114. hook(buffer);
  115. done();
  116. });
  117. }
  118. });
  119. r.once('index', function() {
  120. // wait until first index is returned before attaching error listener.
  121. // this will enable initials errors to throw
  122. r.on('error', function(err) {
  123. console.error('reader error', err.stack || err);
  124. });
  125. });
  126. r.on('end', function() {
  127. console.error('done');
  128. });
  129. var buffer = new Passthrough({highWaterMark:hlsdump.bufferSize});
  130. var outputs = [];
  131. if (hlsdump.udp)
  132. outputs.push(tsblast(hlsdump.udp));
  133. if (hlsdump.output) {
  134. if (hlsdump.output === '-')
  135. outputs.push(process.stdout);
  136. else
  137. outputs.push(fs.createWriteStream(hlsdump.output));
  138. }
  139. // the hook is used to prebuffer
  140. var hooked = false;
  141. function hook(stream) {
  142. if (hooked) return;
  143. console.error('hooking output');
  144. var s = stream;
  145. if (hlsdump.sync) {
  146. var smooth = tssmooth();
  147. smooth.on('unpipe', function() {
  148. this.unpipe();
  149. });
  150. smooth.on('warning', function(err) {
  151. console.error('smoothing error', err);
  152. });
  153. s = s.pipe(smooth);
  154. }
  155. outputs.forEach(function (o) {
  156. s.pipe(o);
  157. });
  158. hooked = true;
  159. }
  160. if (!hlsdump.sync)
  161. hook(buffer);
  162. // setup stat tracking
  163. stats.gauge('bufferBytes', function() { return buffer._readableState.length/* + buffer._writableState.length*/; });
  164. stats.gauge('currentSegment', function() { return currentSegment; });
  165. stats.gauge('index.first', function() { return r.index ? r.index.first_seq_no : -1; });
  166. stats.gauge('index.last', function() { return r.index ? r.index.lastSeqNo() : -1; });
  167. stats.gauge('totalDuration', function() { return totalDuration; });
  168. stats.meter('streamErrors');
  169. if (hlsdump.infoPort) {
  170. http.createServer(function (req, res) {
  171. if (req.method === 'GET') {
  172. var data = JSON.stringify(stats, null, ' ');
  173. res.writeHead(200, {
  174. 'Content-Type': 'application/json',
  175. 'Content-Length': data.length
  176. });
  177. res.write(data);
  178. }
  179. res.end();
  180. }).listen(hlsdump.infoPort);
  181. }