hlsdump 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. #!/usr/bin/env node
  2. "use strict";
  3. var hlsdump = require('commander');
  4. hlsdump.version('0.0.0')
  5. .usage('[options] <url>')
  6. .option('-o, --output <path>', 'target file')
  7. .option('-u, --udp [host:port]', 'relay TS over UDP', function(val) {
  8. var r = { host:'localhost', port:1234 };
  9. if (val) {
  10. var s = val.split(':');
  11. if (s.length === 1) {
  12. r.port = parseInt(s[0], 10);
  13. } else {
  14. r.host = s[0];
  15. r.port = parseInt(s[1], 10);
  16. }
  17. }
  18. return r;
  19. })
  20. .option('-b, --buffer-size <bytes>|full', 'try to buffer <bytes> of input data (implies -s)', function(val) {
  21. if (val === 'full') return 0x80000000-1;
  22. return parseInt(val, 0);
  23. })
  24. .option('-s, --sync', 'clock sync using stream PCR')
  25. .option('-f, --full-stream', 'fetch all stream data')
  26. .option('-c, --concurrent <count>', 'fetch using concurrent connections', parseInt)
  27. .option('-a, --user-agent <string>', 'HTTP User-Agent')
  28. .option('-i, --info-port <port>', 'report status using HTTP + json', parseInt)
  29. .parse(process.argv);
  30. var util = require('util'),
  31. url = require('url'),
  32. fs = require('fs'),
  33. http = require('http');
  34. var streamprocess = require('streamprocess'),
  35. oncemore = require('oncemore');
  36. var reader = require('../lib/reader'),
  37. tssmooth = require('../lib/tssmooth'),
  38. tsblast = require('../lib/tsblast');
  39. try {
  40. var Passthrough = require('stream').Passthrough;
  41. assert(Passthrough);
  42. } catch (e) {
  43. var Passthrough = require('readable-stream/passthrough');
  44. }
  45. var stats = require('measured').createCollection();
  46. var src = hlsdump.args[0];
  47. if (!src) return hlsdump.help();
  48. if (hlsdump.bufferSize) hlsdump.sync = true;
  49. var r = reader(src, {highWaterMark:(hlsdump.concurrent || 1) - 1, fullStream:hlsdump.fullStream});
  50. var totalDuration = 0, currentSegment = -1;
  51. var reading = false;
  52. streamprocess(r, function (obj, done) {
  53. var meta = obj.meta;
  54. var duration = obj.segment.duration;
  55. var size = meta.size;
  56. var stream = oncemore(obj.stream);
  57. totalDuration += duration;
  58. console.error('piping segment', meta.url);
  59. var stopwatch = stats.timer('fetchTime').start();
  60. stream.once('close', 'end', 'error', function(err) {
  61. stopwatch.end();
  62. });
  63. reading = true;
  64. currentSegment = obj.seq;
  65. stream.pipe(buffer, { end: false });
  66. if (size === -1 || !hooked) {
  67. size = 0;
  68. obj.stream.on('data', function(chunk) {
  69. size += chunk.length;
  70. if (!hooked && size >= hlsdump.bufferSize)
  71. hook(buffer);
  72. });
  73. }
  74. stream.once('end', 'error', function(err) {
  75. reading = false;
  76. console.error('segment done at '+totalDuration.toFixed(0)+' seconds, avg bitrate (kbps):', (size / (duration * 1024/8)).toFixed(1));
  77. if (err) {
  78. stats.meter('streamErrors').mark();
  79. console.error('stream error', err.stack || err);
  80. }
  81. hook(buffer);
  82. done();
  83. });
  84. });
  85. r.once('index', function() {
  86. // wait until first index is returned before attaching error listener.
  87. // this will enable initials errors to throw
  88. r.on('error', function(err) {
  89. console.error('reader error', err.stack || err);
  90. });
  91. });
  92. r.on('end', function() {
  93. console.error('done');
  94. });
  95. var buffer = new Passthrough({highWaterMark:hlsdump.bufferSize});
  96. var outputs = [];
  97. if (hlsdump.udp)
  98. outputs.push(tsblast(hlsdump.udp));
  99. if (hlsdump.output) {
  100. if (hlsdump.output === '-')
  101. outputs.push(process.stdout);
  102. else
  103. outputs.push(fs.createWriteStream(hlsdump.output));
  104. }
  105. // the hook is used to prebuffer
  106. var hooked = false;
  107. function hook(stream) {
  108. if (hooked) return;
  109. console.error('hooking output');
  110. var s = stream;
  111. if (hlsdump.sync) {
  112. var smooth = tssmooth();
  113. smooth.on('unpipe', function() {
  114. this.unpipe();
  115. });
  116. smooth.on('warning', function(err) {
  117. console.error('smoothing error', err);
  118. });
  119. s = s.pipe(smooth);
  120. }
  121. outputs.forEach(function (o) {
  122. s.pipe(o);
  123. });
  124. hooked = true;
  125. }
  126. if (!hlsdump.sync)
  127. hook(buffer);
  128. // setup stat tracking
  129. stats.gauge('bufferBytes', function() { return buffer._readableState.length/* + buffer._writableState.length*/; });
  130. stats.gauge('currentSegment', function() { return currentSegment; });
  131. stats.gauge('index.first', function() { return r.index ? r.index.first_seq_no : -1; });
  132. stats.gauge('index.last', function() { return r.index ? r.index.lastSeqNo() : -1; });
  133. stats.gauge('totalDuration', function() { return totalDuration; });
  134. stats.meter('streamErrors');
  135. if (hlsdump.infoPort) {
  136. http.createServer(function (req, res) {
  137. if (req.method === 'GET') {
  138. var data = JSON.stringify(stats, null, ' ');
  139. res.writeHead(200, {
  140. 'Content-Type': 'application/json',
  141. 'Content-Length': data.length
  142. });
  143. res.write(data);
  144. }
  145. res.end();
  146. }).listen(hlsdump.infoPort);
  147. }