hlsdump 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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 reader = require('../lib/reader'),
  35. tssmooth = require('../lib/tssmooth'),
  36. tsblast = require('../lib/tsblast'),
  37. oncemore = require('../lib/oncemore');
  38. try {
  39. var Passthrough = require('stream').Passthrough;
  40. assert(Passthrough);
  41. } catch (e) {
  42. var Passthrough = require('readable-stream/passthrough');
  43. }
  44. var stats = require('measured').createCollection();
  45. var src = hlsdump.args[0];
  46. if (!src) return hlsdump.help();
  47. if (hlsdump.bufferSize) hlsdump.sync = true;
  48. var r = reader(src, {highWaterMark:(hlsdump.concurrent || 1) - 1, fullStream:hlsdump.fullStream});
  49. var totalDuration = 0, currentSegment = -1;
  50. var reading = false;
  51. r.on('readable', function() {
  52. if (reading) return;// console.error('readable call error');
  53. function grabnext() {
  54. var obj = r.read();
  55. if (obj) {
  56. var meta = obj.meta;
  57. var duration = obj.segment.duration;
  58. var size = meta.size;
  59. var stream = oncemore(obj.stream);
  60. totalDuration += duration;
  61. console.error('piping segment', meta.url);
  62. var stopwatch = stats.timer('fetchTime').start();
  63. stream.once('close', 'end', 'error', function(err) {
  64. stopwatch.end();
  65. });
  66. reading = true;
  67. currentSegment = obj.seq;
  68. stream.pipe(buffer, { end: false });
  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. stream.once('end', 'error', function(err) {
  78. reading = false;
  79. console.error('segment done at '+totalDuration.toFixed(0)+' seconds, avg bitrate (kbps):', (size / (duration * 1024/8)).toFixed(1));
  80. if (err) {
  81. stats.meter('streamErrors').mark();
  82. console.error('stream error', err.stack || err);
  83. }
  84. hook(buffer);
  85. grabnext();
  86. });
  87. }
  88. }
  89. grabnext();
  90. });
  91. r.once('index', function() {
  92. // wait until first index is returned before attaching error listener.
  93. // this will enable initials errors to throw
  94. r.on('error', function(err) {
  95. console.error('reader error', err.stack || err);
  96. });
  97. });
  98. r.on('end', function() {
  99. console.error('done');
  100. });
  101. var buffer = new Passthrough({highWaterMark:hlsdump.bufferSize});
  102. var outputs = [];
  103. if (hlsdump.udp)
  104. outputs.push(tsblast(hlsdump.udp));
  105. if (hlsdump.output) {
  106. if (hlsdump.output === '-')
  107. outputs.push(process.stdout);
  108. else
  109. outputs.push(fs.createWriteStream(hlsdump.output));
  110. }
  111. // the hook is used to prebuffer
  112. var hooked = false;
  113. function hook(stream) {
  114. if (hooked) return;
  115. console.error('hooking output');
  116. var s = stream;
  117. if (hlsdump.sync) {
  118. var smooth = tssmooth();
  119. smooth.on('unpipe', function() {
  120. this.unpipe();
  121. });
  122. smooth.on('warning', function(err) {
  123. console.error('smoothing error', err);
  124. });
  125. s = s.pipe(smooth);
  126. }
  127. outputs.forEach(function (o) {
  128. s.pipe(o);
  129. });
  130. hooked = true;
  131. }
  132. if (!hlsdump.sync)
  133. hook(buffer);
  134. // setup stat tracking
  135. stats.gauge('bufferBytes', function() { return buffer._readableState.length/* + buffer._writableState.length*/; });
  136. stats.gauge('currentSegment', function() { return currentSegment; });
  137. stats.gauge('index.first', function() { return r.index ? r.index.first_seq_no : -1; });
  138. stats.gauge('index.last', function() { return r.index ? r.index.lastSeqNo() : -1; });
  139. stats.gauge('totalDuration', function() { return totalDuration; });
  140. stats.meter('streamErrors');
  141. if (hlsdump.infoPort) {
  142. http.createServer(function (req, res) {
  143. if (req.method === 'GET') {
  144. var data = JSON.stringify(stats, null, ' ');
  145. res.writeHead(200, {
  146. 'Content-Type': 'application/json',
  147. 'Content-Length': data.length
  148. });
  149. res.write(data);
  150. }
  151. res.end();
  152. }).listen(hlsdump.infoPort);
  153. }