hls-reader.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. 'use strict';
  2. const Util = require('util');
  3. const Url = require('url');
  4. const Readable = require('readable-stream/readable');
  5. const Passthrough = require('readable-stream/passthrough');
  6. const Async = require('async');
  7. const StreamEach = require('stream-each');
  8. const Oncemore = require('oncemore');
  9. const UriStream = require('uristream');
  10. const deepEqual = require('deep-equal');
  11. const TsSmooth = require('./tssmooth');
  12. const SegmentDecrypt = require('./segment-decrypt');
  13. const internals = {
  14. mapFetchTimeout: 30 * 1000,
  15. NOOP: function(){},
  16. };
  17. // 'pipe' stream to a Readable
  18. internals.pump = function(src, dst, done) {
  19. src.on('data', (chunk) => {
  20. if (!dst.push(chunk)) {
  21. src.pause();
  22. }
  23. });
  24. Oncemore(src).once('end', 'error', (err) => {
  25. // TODO: flush source buffer on error?
  26. dst._read = internals.NOOP;
  27. done(err);
  28. });
  29. dst._read = () => {
  30. src.resume();
  31. };
  32. }
  33. // TODO: use pipe as interface to segment-reader?
  34. function HlsReader(segmentReader, options) {
  35. if (!(this instanceof HlsReader)) {
  36. return new HlsReader(segmentReader, options);
  37. }
  38. options = options || {};
  39. Readable.call(this, { lowWaterMark: options.lowWaterMark, highWaterMark: options.highWaterMark });
  40. this.reader = segmentReader;
  41. this.sync = !!options.sync; // output in real-time
  42. this.bufferSize = ~~options.bufferSize;
  43. this.cookie = options.cookie;
  44. this.key = options.key;
  45. if (options.key && !Buffer.isBuffer(options.key) && options.key.length !== 32) {
  46. throw new TypeError('key must be a 32 byte Buffer');
  47. }
  48. this.isReading = false;
  49. this.isHooked = false;
  50. this.buffer = new Passthrough({ highWaterMark: this.bufferSize });
  51. StreamEach(this.reader, this.process.bind(this), (err) => {
  52. if (err) throw err;
  53. this.buffer.end();
  54. });
  55. // start output if needed
  56. if (!this.sync) {
  57. process.nextTick(() => {
  58. this.hook();
  59. });
  60. }
  61. }
  62. Util.inherits(HlsReader, Readable);
  63. HlsReader.prototype._read = internals.NOOP;
  64. HlsReader.prototype.destroy = function () {
  65. };
  66. HlsReader.prototype.process = function(segmentInfo, done) {
  67. this.isReading = true;
  68. Async.parallel({
  69. map: (next) => {
  70. if (!deepEqual(segmentInfo.details.map, this.map)) {
  71. this.map = segmentInfo.details.map;
  72. if (this.map) {
  73. return this.appendMap(this.map, next);
  74. }
  75. }
  76. return next();
  77. },
  78. stream: (next) => {
  79. return this.decrypt(segmentInfo.stream, segmentInfo.details.keys, (err, stream) => {
  80. if (err) {
  81. console.error('decrypt failed', err.stack);
  82. stream = segmentInfo.stream;
  83. }
  84. return next(null, stream);
  85. });
  86. },
  87. }, (err, results) => {
  88. if (err) {
  89. return done(err);
  90. }
  91. let stream = results.stream;
  92. this.emit('segment', segmentInfo);
  93. stream = Oncemore(stream);
  94. if (!this.isHooked) {
  95. // pull data and detect if we need to hook before end
  96. let buffered = 0;
  97. stream.on('data', (chunk) => {
  98. buffered += chunk.length;
  99. if (!this.isHooked && buffered >= this.bufferSize)
  100. this.hook();
  101. });
  102. }
  103. stream.pipe(this.buffer, { end: false });
  104. stream.once('end', 'error', (err) => {
  105. this.isReading = false;
  106. if (err) {
  107. console.error('stream error', err.stack || err);
  108. }
  109. this.hook();
  110. done();
  111. });
  112. });
  113. };
  114. // the hook is used to prebuffer
  115. HlsReader.prototype.hook = function hook() {
  116. if (this.isHooked) return;
  117. this.isHooked = true;
  118. let s = this.buffer;
  119. if (this.sync) {
  120. let smooth = TsSmooth();
  121. smooth.on('unpipe', () => {
  122. this.unpipe();
  123. });
  124. smooth.on('warning', (err) => {
  125. console.error('smoothing error', err);
  126. });
  127. s = s.pipe(smooth);
  128. }
  129. internals.pump(s, this, (err) => {
  130. if (err) {
  131. return this.emit('error', err);
  132. }
  133. this.push(null);
  134. });
  135. this.emit('ready');
  136. };
  137. HlsReader.prototype.appendMap = function(map, next) {
  138. if (!map.uri) {
  139. return next(new Error('missing "uri" attribute from map'));
  140. }
  141. let mapUri = Url.resolve(this.reader.baseUrl, map.quotedString('uri'));
  142. let fetchOptions = {
  143. timeout: internals.mapFetchTimeout,
  144. };
  145. if (map.byterange) {
  146. let n = map.quotedString('byterange').split('@');
  147. if (n.length !== 2) {
  148. return next(new Error('invalid "byterange" attribute from map'));
  149. }
  150. fetchOptions.start = parseInt(n[1], 10);
  151. fetchOptions.end = fetchOptions.start + parseInt(n[0], 10) - 1;
  152. }
  153. Oncemore(UriStream(mapUri, fetchOptions))
  154. .once('end', 'error', next)
  155. .pipe(this.buffer, { end: false })
  156. };
  157. HlsReader.prototype.decrypt = function(stream, keyAttrs, next) {
  158. return SegmentDecrypt.decrypt(stream, keyAttrs, { base: this.reader.baseUrl, key: this.key, cookie: this.cookie }, next);
  159. };
  160. const hlsreader = module.exports = function hlsreader(segmentReader, options) {
  161. return new HlsReader(segmentReader, options);
  162. };
  163. hlsreader.HlsReader = HlsReader;