hlsdump 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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 util = require('util'),
  34. url = require('url'),
  35. fs = require('fs'),
  36. http = require('http'),
  37. crypto = require('crypto');
  38. var streamprocess = require('streamprocess'),
  39. oncemore = require('oncemore'),
  40. uristream = require('uristream');
  41. var reader = require('../lib/reader'),
  42. tssmooth = require('../lib/tssmooth'),
  43. tsblast = require('../lib/tsblast');
  44. var Passthrough = require('readable-stream/passthrough');
  45. var stats = require('measured').createCollection();
  46. var src = hlsdump.args[0];
  47. if (!src) {
  48. hlsdump.help();
  49. process.exit(-1);
  50. }
  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, hooked = 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() {
  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. } else {
  97. pushBuffer(stream);
  98. }
  99. function fetchKey(cb) {
  100. if (hlsdump.key) return cb(null, hlsdump.key);
  101. var uri = url.resolve(r.url, keyData.uri.slice(1,-1));
  102. var entry = keyCache[uri];
  103. if (entry && entry.length) return cb(null, keyCache[uri]);
  104. var key = new Buffer(0);
  105. var headers = {};
  106. if (hlsdump.cookie)
  107. headers.Cookie = hlsdump.cookie;
  108. oncemore(uristream(uri, { headers:headers, whitelist:['http', 'https', 'data'], timeout: 10 * 1000 }))
  109. .on('data', function(chunk) {
  110. key = Buffer.concat([key, chunk]);
  111. })
  112. .once('error', 'end', function(err) {
  113. keyCache[uri] = key;
  114. return cb(err, key);
  115. });
  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. function hook(stream) {
  153. if (hooked) return;
  154. console.error('hooking output');
  155. var s = stream;
  156. if (hlsdump.sync) {
  157. var smooth = tssmooth();
  158. smooth.on('unpipe', function() {
  159. this.unpipe();
  160. });
  161. smooth.on('warning', function(err) {
  162. console.error('smoothing error', err);
  163. });
  164. s = s.pipe(smooth);
  165. }
  166. outputs.forEach(function (o) {
  167. s.pipe(o);
  168. });
  169. hooked = true;
  170. }
  171. if (!hlsdump.sync)
  172. hook(buffer);
  173. // setup stat tracking
  174. stats.gauge('bufferBytes', function() { return buffer._readableState.length/* + buffer._writableState.length*/; });
  175. stats.gauge('currentSegment', function() { return currentSegment; });
  176. stats.gauge('index.first', function() { return r.index ? r.index.first_seq_no : -1; });
  177. stats.gauge('index.last', function() { return r.index ? r.index.lastSeqNo() : -1; });
  178. stats.gauge('totalDuration', function() { return totalDuration; });
  179. stats.meter('streamErrors');
  180. if (hlsdump.infoPort) {
  181. http.createServer(function (req, res) {
  182. if (req.method === 'GET') {
  183. var data = JSON.stringify(stats, null, ' ');
  184. res.writeHead(200, {
  185. 'Content-Type': 'application/json',
  186. 'Content-Length': data.length
  187. });
  188. res.write(data);
  189. }
  190. res.end();
  191. }).listen(hlsdump.infoPort);
  192. }