hlsdump 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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 fs = require('fs'),
  34. http = require('http');
  35. const Bounce = require('bounce');
  36. var HlsSegmentReader = require('hls-segment-reader'),
  37. Pati = require('pati'),
  38. UdpBlast = require('udp-blast');
  39. var HlsReader = require('../lib/hls-reader');
  40. var src = hlsdump.args[0];
  41. if (!src) {
  42. hlsdump.help();
  43. process.exit(-1);
  44. }
  45. if (hlsdump.bufferSize) hlsdump.sync = true;
  46. const segmentReader = new HlsSegmentReader(src, { withData: true, highWaterMark: (hlsdump.concurrent || 1) - 1, fullStream: hlsdump.fullStream });
  47. const reader = new HlsReader(segmentReader, hlsdump);
  48. const r = new Pati.EventDispatcher(reader);
  49. segmentReader.once('index', function() {
  50. // wait until first index is returned before attaching error listener.
  51. // this will enable initials errors to throw
  52. segmentReader.on('error', function(err) {
  53. console.error('reader error', err.stack || err);
  54. });
  55. });
  56. if (hlsdump.udp) {
  57. var dst = (hlsdump.udp === true) ? null : hlsdump.udp;
  58. reader.pipe(new UdpBlast(dst, { packetSize: 7 * 188 }));
  59. }
  60. if (hlsdump.output) {
  61. if (hlsdump.output === '-')
  62. reader.pipe(process.stdout);
  63. else
  64. reader.pipe(fs.createWriteStream(hlsdump.output));
  65. }
  66. var startTime = process.hrtime();
  67. r.on('ready', () => {
  68. const delay = process.hrtime(startTime);
  69. console.error('"ready" after delay of ' + (delay[0] * 1e3 + delay[1] / 1e6).toFixed(2) + 'ms');
  70. });
  71. r.on('end', () => {
  72. r.end();
  73. });
  74. let totalDuration = 0;
  75. r.on('segment', (segmentInfo) => {
  76. var downloadSize = segmentInfo.file.size;
  77. var duration = segmentInfo.segment ? segmentInfo.segment.details.duration : 0;
  78. totalDuration += duration;
  79. // calculate size when missing
  80. if (downloadSize === -1) {
  81. downloadSize = 0;
  82. segmentInfo.stream.on('data', function(chunk) {
  83. downloadSize += chunk.length;
  84. });
  85. }
  86. const dispatcher = new Pati.EventDispatcher(segmentInfo.stream);
  87. dispatcher.on('end', Pati.EventDispatcher.end);
  88. dispatcher.on('close', Pati.EventDispatcher.end);
  89. Bounce.background(async () => {
  90. try {
  91. await dispatcher.finish();
  92. }
  93. catch (err) { /* ignore */ }
  94. console.error('segment done at ' + totalDuration.toFixed(0) + ' seconds, avg bitrate (kbps):', (downloadSize / (duration * 1024 / 8)).toFixed(1));
  95. });
  96. });
  97. if (hlsdump.infoPort) {
  98. var stats = require('measured').createCollection();
  99. var currentSegment = -1;
  100. // setup stat tracking
  101. stats.gauge('bufferBytes', function() { return reader.buffer._readableState.length/* + buffer._writableState.length*/; });
  102. stats.gauge('currentSegment', function() { return currentSegment; });
  103. stats.gauge('index.first', function() { return segmentReader.index ? segmentReader.index.first_seq_no : -1; });
  104. stats.gauge('index.last', function() { return segmentReader.index ? segmentReader.index.lastSeqNo() : -1; });
  105. stats.gauge('totalDuration', function() { return totalDuration; });
  106. stats.timer('fetchTime').unref();
  107. stats.meter('streamErrors').unref();
  108. r.on('segment', (segmentInfo) => {
  109. currentSegment = segmentInfo.segment && segmentInfo.segment.seq;
  110. const stopwatch = stats.timer('fetchTime').start();
  111. const dispatcher = new Pati.EventDispatcher(segmentInfo.stream);
  112. dispatcher.on('end', Pati.EventDispatcher.end);
  113. dispatcher.on('close', Pati.EventDispatcher.end);
  114. Bounce.background(async () => {
  115. try {
  116. await dispatcher.finish();
  117. }
  118. catch (err) {
  119. stats.meter('streamErrors').mark();
  120. }
  121. finally {
  122. stopwatch.end();
  123. }
  124. });
  125. });
  126. var server = http.createServer(function (req, res) {
  127. if (req.method === 'GET') {
  128. var data = JSON.stringify(stats, null, ' ');
  129. res.writeHead(200, {
  130. 'Content-Type': 'application/json',
  131. 'Content-Length': data.length
  132. });
  133. res.write(data);
  134. }
  135. res.end();
  136. }).listen(hlsdump.infoPort);
  137. const cleanup = () => {
  138. server.close();
  139. };
  140. r.finish().then(() => server.close(), () => server.close());
  141. }
  142. r.finish().then(() => {
  143. console.error('stream complete');
  144. }, (err) => {
  145. console.error('error', err);
  146. });