hlsdump 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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 downloadSize = 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. // calculate size when missing
  70. if (downloadSize === -1) {
  71. downloadSize = 0;
  72. obj.stream.on('data', function(chunk) {
  73. downloadSize += chunk.length;
  74. });
  75. }
  76. var keyData = obj.segment.key;
  77. if (keyData && keyData.method === 'AES-128' && keyData.uri && keyData.uri.length > 2) {
  78. fetchKey(function(err, key) {
  79. if (err) {
  80. console.error('key fetch failed:', err);
  81. return pushBuffer(stream);
  82. }
  83. var iv = new Buffer(keyData.iv.slice(-32), 'hex');
  84. try {
  85. var decrypt = crypto.createDecipheriv('aes-128-cbc', key, iv);
  86. } catch (ex) {
  87. console.error('crypto setup failed:', ex.stack || ex);
  88. return pushBuffer(stream);
  89. }
  90. stream.on('error', function(err) {
  91. decrypt.emit('error', err);
  92. });
  93. pushBuffer(oncemore(stream.pipe(decrypt)));
  94. });
  95. } else {
  96. pushBuffer(stream);
  97. }
  98. function fetchKey(cb) {
  99. if (hlsdump.key) return cb(null, hlsdump.key);
  100. var uri = url.resolve(r.url, keyData.uri.slice(1,-1));
  101. var entry = keyCache[uri];
  102. if (entry && entry.length) return cb(null, keyCache[uri]);
  103. var key = new Buffer(0);
  104. var headers = {};
  105. if (hlsdump.cookie)
  106. headers.Cookie = hlsdump.cookie;
  107. oncemore(uristream(uri, { headers:headers, whitelist:['http', 'https', 'data'], timeout: 10 * 1000 }))
  108. .on('data', function(chunk) {
  109. key = Buffer.concat([key, chunk]);
  110. })
  111. .once('error', 'end', function(err) {
  112. keyCache[uri] = key;
  113. return cb(err, key);
  114. });
  115. }
  116. function pushBuffer(stream) {
  117. if (!hooked) {
  118. // pull data and detect if we need to hook before end
  119. var buffered = 0;
  120. stream.on('data', function(chunk) {
  121. buffered += chunk.length;
  122. if (!hooked && buffered >= hlsdump.bufferSize)
  123. hook(buffer);
  124. });
  125. }
  126. stream.pipe(buffer, { end: false });
  127. stream.once('end', 'error', function(err) {
  128. reading = false;
  129. console.error('segment done at ' + totalDuration.toFixed(0) + ' seconds, avg bitrate (kbps):', (downloadSize / (duration * 1024 / 8)).toFixed(1));
  130. if (err) {
  131. stats.meter('streamErrors').mark();
  132. console.error('stream error', err.stack || err);
  133. }
  134. hook(buffer);
  135. done();
  136. });
  137. }
  138. });
  139. r.once('index', function() {
  140. // wait until first index is returned before attaching error listener.
  141. // this will enable initials errors to throw
  142. r.on('error', function(err) {
  143. console.error('reader error', err.stack || err);
  144. });
  145. });
  146. r.on('end', function() {
  147. console.error('done');
  148. });
  149. var buffer = new Passthrough({highWaterMark:hlsdump.bufferSize});
  150. var outputs = [];
  151. if (hlsdump.udp)
  152. outputs.push(tsblast(hlsdump.udp));
  153. if (hlsdump.output) {
  154. if (hlsdump.output === '-')
  155. outputs.push(process.stdout);
  156. else
  157. outputs.push(fs.createWriteStream(hlsdump.output));
  158. }
  159. // the hook is used to prebuffer
  160. function hook(stream) {
  161. if (hooked) return;
  162. console.error('hooking output');
  163. var s = stream;
  164. if (hlsdump.sync) {
  165. var smooth = tssmooth();
  166. smooth.on('unpipe', function() {
  167. this.unpipe();
  168. });
  169. smooth.on('warning', function(err) {
  170. console.error('smoothing error', err);
  171. });
  172. s = s.pipe(smooth);
  173. }
  174. outputs.forEach(function (o) {
  175. s.pipe(o);
  176. });
  177. hooked = true;
  178. }
  179. if (!hlsdump.sync || !(hlsdump.bufferSize > 0))
  180. hook(buffer);
  181. // setup stat tracking
  182. stats.gauge('bufferBytes', function() { return buffer._readableState.length/* + buffer._writableState.length*/; });
  183. stats.gauge('currentSegment', function() { return currentSegment; });
  184. stats.gauge('index.first', function() { return r.index ? r.index.first_seq_no : -1; });
  185. stats.gauge('index.last', function() { return r.index ? r.index.lastSeqNo() : -1; });
  186. stats.gauge('totalDuration', function() { return totalDuration; });
  187. stats.meter('streamErrors');
  188. if (hlsdump.infoPort) {
  189. http.createServer(function (req, res) {
  190. if (req.method === 'GET') {
  191. var data = JSON.stringify(stats, null, ' ');
  192. res.writeHead(200, {
  193. 'Content-Type': 'application/json',
  194. 'Content-Length': data.length
  195. });
  196. res.write(data);
  197. }
  198. res.end();
  199. }).listen(hlsdump.infoPort);
  200. }