hls-reader.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. "use strict";
  2. var Url = require('url'),
  3. Util = require('util'),
  4. Crypto = require('crypto');
  5. var StreamProcess = require('streamprocess'),
  6. oncemore = require('oncemore'),
  7. UriStream = require('uristream');
  8. var Readable = require('readable-stream/readable'),
  9. Passthrough = require('readable-stream/passthrough');
  10. var tssmooth = require('./tssmooth');
  11. var internals = {
  12. keyCache: {},
  13. };
  14. var NOOP = function(){};
  15. // 'pipe' stream to a Readable
  16. function pump(src, dst, done) {
  17. src.on('data', function(chunk) {
  18. if (!dst.push(chunk)) {
  19. src.pause();
  20. }
  21. });
  22. oncemore(src).once('end', 'error', function(err) {
  23. // TODO: flush source buffer on error?
  24. dst._read = NOOP;
  25. done(err);
  26. });
  27. dst._read = function() {
  28. src.resume();
  29. };
  30. }
  31. // TODO: use pipe as interface to segment-reader?
  32. function HlsReader(segmentReader, options) {
  33. if (!(this instanceof HlsReader))
  34. return new HlsReader(segmentReader, options);
  35. Readable.call(this, { lowWaterMark: options.lowWaterMark, highWaterMark: options.highWaterMark });
  36. var self = this;
  37. this.reader = segmentReader;
  38. this.sync = !!options.sync; // output in real-time
  39. this.bufferSize = ~~options.bufferSize;
  40. this.cookie = options.cookie;
  41. this.key = options.key;
  42. if (options.key && !Buffer.isBuffer(options.key) && options.key.length !== 32) {
  43. throw new TypeError('key must be a 32 byte Buffer');
  44. }
  45. this.isReading = false;
  46. this.isHooked = false;
  47. this.buffer = new Passthrough({ highWaterMark: this.bufferSize });
  48. StreamProcess(this.reader, function (obj, done) {
  49. self.isReading = true;
  50. return self.decrypt(obj.stream, obj.segment.key, function (err, stream) {
  51. if (err) {
  52. console.error('decrypt failed', err.stack);
  53. stream = obj.stream;
  54. }
  55. self.emit('segment', obj);
  56. stream = oncemore(stream);
  57. if (!self.isHooked) {
  58. // pull data and detect if we need to hook before end
  59. var buffered = 0;
  60. stream.on('data', function(chunk) {
  61. buffered += chunk.length;
  62. if (!self.isHooked && buffered >= self.bufferSize)
  63. self.hook();
  64. });
  65. }
  66. stream.pipe(self.buffer, { end: false });
  67. stream.once('end', 'error', function(err) {
  68. self.isReading = false;
  69. if (err) {
  70. console.error('stream error', err.stack || err);
  71. }
  72. self.hook();
  73. done();
  74. });
  75. });
  76. });
  77. this.reader.on('end', function() {
  78. self.buffer.end();
  79. });
  80. // start output if needed
  81. if (!this.sync) {
  82. process.nextTick(function() {
  83. self.hook();
  84. });
  85. }
  86. }
  87. Util.inherits(HlsReader, Readable);
  88. HlsReader.prototype._read = NOOP;
  89. // the hook is used to prebuffer
  90. HlsReader.prototype.hook = function hook() {
  91. var self = this;
  92. if (this.isHooked) return;
  93. self.isHooked = true;
  94. var s = this.buffer;
  95. if (this.sync) {
  96. var smooth = tssmooth();
  97. smooth.on('unpipe', function() {
  98. this.unpipe();
  99. });
  100. smooth.on('warning', function(err) {
  101. console.error('smoothing error', err);
  102. });
  103. s = s.pipe(smooth);
  104. }
  105. pump(s, this, function(err) {
  106. if (err) {
  107. return self.emit('error', err);
  108. }
  109. self.push(null);
  110. });
  111. this.emit('ready');
  112. };
  113. HlsReader.prototype.decrypt = function (stream, keyAttrs, next) {
  114. if (!keyAttrs) return next(null, stream);
  115. if (keyAttrs.enumeratedString('method') !== 'AES-128' ||
  116. !keyAttrs.quotedString('uri') || !keyAttrs.hexadecimalInteger('iv')) {
  117. // TODO: hard error when key is not recognized?
  118. return next(new Error('unknown encryption parameters'));
  119. }
  120. return this.fetchKey(keyAttrs.quotedString('uri'), function(err, key) {
  121. if (err)
  122. return next(new Error('key fetch failed: ' + (err.stack || err)));
  123. var iv = keyAttrs.hexadecimalInteger('iv');
  124. try {
  125. var decrypt = Crypto.createDecipheriv('aes-128-cbc', key, iv);
  126. } catch (ex) {
  127. return next(new Error('crypto setup failed: ' (ex.stack || ex)));
  128. }
  129. // forward stream errors
  130. stream.on('error', function(err) {
  131. decrypt.emit('error', err);
  132. });
  133. return next(null, stream.pipe(decrypt));
  134. });
  135. };
  136. HlsReader.prototype.fetchKey = function (keyUri, next) {
  137. if (this.key) return next(null, this.key);
  138. var uri = Url.resolve(this.reader.url, keyUri);
  139. var entry = internals.keyCache[uri];
  140. if (entry && entry.length) return next(null, internals.keyCache[uri]);
  141. var key = new Buffer(0);
  142. var headers = {};
  143. if (this.cookie)
  144. headers.Cookie = this.cookie;
  145. oncemore(UriStream(uri, { headers: headers, whitelist: ['http', 'https', 'data'], timeout: 10 * 1000 }))
  146. .on('data', function(chunk) {
  147. key = Buffer.concat([key, chunk]);
  148. })
  149. .once('error', 'end', function(err) {
  150. internals.keyCache[uri] = key;
  151. return next(err, key);
  152. });
  153. };
  154. var hlsreader = module.exports = function hlsreader(segmentReader, options) {
  155. return new HlsReader(segmentReader, options);
  156. };
  157. hlsreader.HlsReader = HlsReader;