hlsdump 6.7 KB

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