hlsdump 4.6 KB

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