hls-reader.js 5.1 KB

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