hlsdump 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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. .option('--cookie <data>', 'add cookie header to key requests')
  29. .option('--key <hex>', 'use oob key for decrypting segments', function(opt) {return new Buffer(opt, 'hex');})
  30. .parse(process.argv);
  31. var util = require('util'),
  32. url = require('url'),
  33. fs = require('fs'),
  34. http = require('http'),
  35. crypto = require('crypto');
  36. var streamprocess = require('streamprocess'),
  37. oncemore = require('oncemore'),
  38. uristream = require('uristream');
  39. var reader = require('../lib/reader'),
  40. tssmooth = require('../lib/tssmooth'),
  41. tsblast = require('../lib/tsblast');
  42. try {
  43. var Passthrough = require('stream').Passthrough;
  44. assert(Passthrough);
  45. } catch (e) {
  46. var Passthrough = require('readable-stream/passthrough');
  47. }
  48. var stats = require('measured').createCollection();
  49. var src = hlsdump.args[0];
  50. if (!src) return hlsdump.help();
  51. if (hlsdump.bufferSize) hlsdump.sync = true;
  52. var r = reader(src, {highWaterMark:(hlsdump.concurrent || 1) - 1, fullStream:hlsdump.fullStream});
  53. var totalDuration = 0, currentSegment = -1;
  54. var reading = false;
  55. var keyCache = {};
  56. streamprocess(r, function (obj, done) {
  57. var meta = obj.meta;
  58. var duration = obj.segment.duration;
  59. var size = meta.size;
  60. var stream = oncemore(obj.stream);
  61. totalDuration += duration;
  62. console.error('piping segment', meta.url);
  63. var stopwatch = stats.timer('fetchTime').start();
  64. stream.once('close', 'end', 'error', function(err) {
  65. stopwatch.end();
  66. });
  67. reading = true;
  68. currentSegment = obj.seq;
  69. if (size === -1 || !hooked) {
  70. size = 0;
  71. obj.stream.on('data', function(chunk) {
  72. size += chunk.length;
  73. if (!hooked && size >= hlsdump.bufferSize)
  74. hook(buffer);
  75. });
  76. }
  77. var keyData = r.index.keyForSeqNo(obj.seq);
  78. if (keyData && keyData.method === 'AES-128' && keyData.uri && keyData.uri.length > 2) {
  79. fetchKey(function(err, key) {
  80. if (err) {
  81. console.error('key fetch failed:', err);
  82. return pushBuffer(stream);
  83. }
  84. var iv = new Buffer(keyData.iv.slice(-32), 'hex');
  85. try {
  86. var decrypt = crypto.createDecipheriv('aes-128-cbc', key, iv);
  87. } catch (ex) {
  88. console.error('crypto setup failed:', ex.stack || ex);
  89. return pushBuffer(stream);
  90. }
  91. stream.on('error', function(err) {
  92. decrypt.emit('error', err);
  93. });
  94. pushBuffer(oncemore(stream.pipe(decrypt)));
  95. });
  96. function fetchKey(cb) {
  97. if (hlsdump.key) return cb(null, hlsdump.key);
  98. var uri = url.resolve(r.url, keyData.uri.slice(1,-1));
  99. var entry = keyCache[uri];
  100. if (entry && entry.length) return cb(null, keyCache[uri]);
  101. var key = new Buffer(0);
  102. var headers = {};
  103. if (hlsdump.cookie)
  104. headers['Cookie'] = hlsdump.cookie;
  105. oncemore(uristream(uri, { headers:headers, whitelist:['http', 'https', 'data'], timeout: 10*1000 }))
  106. .on('data', function(chunk) {
  107. key = Buffer.concat([key, chunk]);
  108. })
  109. .once('error', 'end', function(err) {
  110. keyCache[uri] = key;
  111. return cb(err, key);
  112. });
  113. }
  114. } else {
  115. pushBuffer(stream);
  116. }
  117. function pushBuffer(stream) {
  118. stream.pipe(buffer, { end: false });
  119. stream.once('end', 'error', function(err) {
  120. reading = false;
  121. console.error('segment done at '+totalDuration.toFixed(0)+' seconds, avg bitrate (kbps):', (size / (duration * 1024/8)).toFixed(1));
  122. if (err) {
  123. stats.meter('streamErrors').mark();
  124. console.error('stream error', err.stack || err);
  125. }
  126. hook(buffer);
  127. done();
  128. });
  129. }
  130. });
  131. r.once('index', function() {
  132. // wait until first index is returned before attaching error listener.
  133. // this will enable initials errors to throw
  134. r.on('error', function(err) {
  135. console.error('reader error', err.stack || err);
  136. });
  137. });
  138. r.on('end', function() {
  139. console.error('done');
  140. });
  141. var buffer = new Passthrough({highWaterMark:hlsdump.bufferSize});
  142. var outputs = [];
  143. if (hlsdump.udp)
  144. outputs.push(tsblast(hlsdump.udp));
  145. if (hlsdump.output) {
  146. if (hlsdump.output === '-')
  147. outputs.push(process.stdout);
  148. else
  149. outputs.push(fs.createWriteStream(hlsdump.output));
  150. }
  151. // the hook is used to prebuffer
  152. var hooked = false;
  153. function hook(stream) {
  154. if (hooked) return;
  155. console.error('hooking output');
  156. var s = stream;
  157. if (hlsdump.sync) {
  158. var smooth = tssmooth();
  159. smooth.on('unpipe', function() {
  160. this.unpipe();
  161. });
  162. smooth.on('warning', function(err) {
  163. console.error('smoothing error', err);
  164. });
  165. s = s.pipe(smooth);
  166. }
  167. outputs.forEach(function (o) {
  168. s.pipe(o);
  169. });
  170. hooked = true;
  171. }
  172. if (!hlsdump.sync)
  173. hook(buffer);
  174. // setup stat tracking
  175. stats.gauge('bufferBytes', function() { return buffer._readableState.length/* + buffer._writableState.length*/; });
  176. stats.gauge('currentSegment', function() { return currentSegment; });
  177. stats.gauge('index.first', function() { return r.index ? r.index.first_seq_no : -1; });
  178. stats.gauge('index.last', function() { return r.index ? r.index.lastSeqNo() : -1; });
  179. stats.gauge('totalDuration', function() { return totalDuration; });
  180. stats.meter('streamErrors');
  181. if (hlsdump.infoPort) {
  182. http.createServer(function (req, res) {
  183. if (req.method === 'GET') {
  184. var data = JSON.stringify(stats, null, ' ');
  185. res.writeHead(200, {
  186. 'Content-Type': 'application/json',
  187. 'Content-Length': data.length
  188. });
  189. res.write(data);
  190. }
  191. res.end();
  192. }).listen(hlsdump.infoPort);
  193. }