reader.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. // stream from hls source
  2. var util = require('util'),
  3. url = require('url'),
  4. zlib = require('zlib'),
  5. assert = require('assert');
  6. var request = require('request'),
  7. debug = require('debug')('hls:reader');
  8. try {
  9. var Readable = require('stream').Readable;
  10. assert(Readable);
  11. var Passthrough = null;
  12. } catch (e) {
  13. var Readable = require('readable-stream');
  14. var Passthrough = require('readable-stream/passthrough');
  15. }
  16. var m3u8 = require('./m3u8');
  17. function noop() {};
  18. var DEFAULT_AGENT = util.format('hls-tools/v%s (http://github.com/kanongil/node-hls-tools) node.js/%s', require('../package').version, process.version);
  19. module.exports = hlsreader;
  20. hlsreader.HlsStreamReader = HlsStreamReader;
  21. // apply oncemore() to an emitter, and enable it to accept multiple events as input
  22. function oncemore(emitter) {
  23. if (!emitter) return emitter;
  24. var once = emitter.once;
  25. if (once && !once._old) {
  26. emitter.once = function(type, listener) {
  27. if (arguments.length <= 2)
  28. return once.apply(this, arguments);
  29. var types = Array.prototype.slice.call(arguments, 0, -1);
  30. var listener = arguments.length ? arguments[arguments.length-1] : undefined;
  31. if (typeof listener !== 'function')
  32. throw TypeError('listener must be a function');
  33. function g() {
  34. types.forEach(function(type) {
  35. this.removeListener(type, g);
  36. }, this);
  37. listener.apply(this, arguments);
  38. }
  39. g.listener = listener;
  40. types.forEach(function(type) {
  41. this.on(type, g);
  42. }, this);
  43. return this;
  44. };
  45. emitter.once._old = once;
  46. }
  47. return emitter;
  48. }
  49. /*
  50. options:
  51. startSeq*
  52. noData // don't emit any data - useful for analyzing the stream structure
  53. maxRedirects*
  54. cacheDir*
  55. headers* // allows for custom user-agent, cookies, auth, etc
  56. emits:
  57. index (m3u8)
  58. segment (seqNo, duration, datetime, size?, )
  59. */
  60. function inheritErrors(stream) {
  61. stream.on('pipe', function(source) {
  62. source.on('error', stream.emit.bind(stream, 'error'));
  63. });
  64. stream.on('unpipe', function(source) {
  65. source.removeListener('error', stream.emit.bind(stream, 'error'));
  66. });
  67. return stream;
  68. }
  69. function getFileStream(srcUrl, options, cb) {
  70. assert(srcUrl.protocol);
  71. if (typeof options === 'function') {
  72. cb = options;
  73. options = {};
  74. }
  75. if (srcUrl.protocol === 'http:' || srcUrl.protocol === 'https:') {
  76. var headers = options.headers || {};
  77. if (!headers['user-agent']) headers['user-agent'] = DEFAULT_AGENT;
  78. if (!headers['accept-encoding']) headers['accept-encoding'] = ['gzip','deflate'];
  79. var req = (options.probe ? request.head : request.get)({uri:url.format(srcUrl), pool:false, headers:headers, timeout:60*1000});
  80. req.on('error', cb);
  81. req.on('response', function (res) {
  82. req.removeListener('error', cb);
  83. if (res.statusCode !== 200) {
  84. req.abort();
  85. if (res.statusCode >= 500 && res.statusCode !== 501)
  86. return cb(new TempError('HTTP Server returned: '+res.statusCode));
  87. else
  88. return cb(new Error('Bad server response code: '+res.statusCode));
  89. }
  90. var size = res.headers['content-length'] ? parseInt(res.headers['content-length'], 10) : -1;
  91. // turn bad content-length into actual errors
  92. if (size >= 0 && !options.probe) {
  93. var accum = 0;
  94. res.on('data', function(chunk) {
  95. accum += chunk.length;
  96. if (accum > size)
  97. req.abort();
  98. });
  99. oncemore(res).once('end', 'error', function(err) {
  100. // TODO: make this a custom error?
  101. if (!err && accum !== size)
  102. stream.emit('error', new Error('Invalid returned stream length (req='+size+', ret='+accum+')'));
  103. });
  104. }
  105. // transparently handle gzip responses
  106. var stream = res;
  107. if (res.headers['content-encoding'] === 'gzip' || res.headers['content-encoding'] === 'deflate') {
  108. unzip = zlib.createUnzip();
  109. stream = stream.pipe(inheritErrors(unzip));
  110. size = -1;
  111. }
  112. // adapt old style streams for pre-streams2 node versions
  113. if (Passthrough && !(stream instanceof Readable))
  114. stream = stream.pipe(inheritErrors(new Passthrough()));
  115. // allow aborting the request
  116. stream.abort = req.abort.bind(req);
  117. // forward all future errors to response stream
  118. req.on('error', function(err) {
  119. if (stream.listeners('error').length !== 0)
  120. stream.emit('error', err);
  121. });
  122. // attach empty 'error' listener to keep it from ever throwing
  123. stream.on('error', noop);
  124. // extract meta information from header
  125. var typeparts = /^(.+?\/.+?)(?:;\w*.*)?$/.exec(res.headers['content-type']) || [null, 'application/octet-stream'],
  126. mimetype = typeparts[1].toLowerCase(),
  127. modified = res.headers['last-modified'] ? new Date(res.headers['last-modified']) : null;
  128. cb(null, stream, {url:url.format(req.uri), mime:mimetype, size:size, modified:modified});
  129. });
  130. } else {
  131. process.nextTick(function() {
  132. cb(new Error('Unsupported protocol: '+srcUrl.protocol));
  133. });
  134. }
  135. /* if (srcUrl.protocol === 'file:') {
  136. } else if (srcUrl.protocol === 'data:') {
  137. //var regex = /^data:(.+\/.+);base64,(.*)$/;
  138. // add content-type && content-length headers
  139. } else {
  140. }*/
  141. }
  142. function HlsStreamReader(src, options) {
  143. var self = this;
  144. options = options || {};
  145. if (typeof src === 'string')
  146. src = url.parse(src);
  147. this.url = src;
  148. this.baseUrl = src;
  149. this.fullStream = !!options.fullStream;
  150. this.keepConnection = !!options.keepConnection;
  151. this.noData = !!options.noData;
  152. this.indexStream = null;
  153. this.index = null;
  154. this.readState = {
  155. currentSeq:-1,
  156. currentSegment:null,
  157. stream:null
  158. }
  159. function getUpdateInterval(updated) {
  160. if (updated && self.index.segments.length)
  161. return Math.min(self.index.target_duration, self.index.segments[self.index.segments.length-1].duration);
  162. else
  163. return self.index.target_duration / 2;
  164. }
  165. function updatecheck(updated) {
  166. if (updated) {
  167. if (self.readState.currentSeq===-1)
  168. self.readState.currentSeq = self.index.startSeqNo(self.fullStream);
  169. else if (self.readState.currentSeq < self.index.startSeqNo(true))
  170. self.readState.currentSeq = self.index.startSeqNo(true);
  171. self.emit('index', self.index);
  172. if (self.index.variant)
  173. return self.end();
  174. }
  175. checkcurrent();
  176. if (!self.index.ended) {
  177. var updateInterval = getUpdateInterval(updated);
  178. debug('scheduling index refresh', updateInterval);
  179. setTimeout(updateindex, Math.max(1, updateInterval)*1000);
  180. }
  181. }
  182. function updateindex() {
  183. getFileStream(self.url, function(err, stream, meta) {
  184. if (err) {
  185. if (self.index && self.keepConnection) {
  186. console.error('Failed to update index at '+url.format(self.url)+':', err.stack || err);
  187. return updatecheck();
  188. }
  189. return self.emit('error', err);
  190. }
  191. if (meta.mime !== 'application/vnd.apple.mpegurl' &&
  192. meta.mime !== 'application/x-mpegurl' && meta.mime !== 'audio/mpegurl')
  193. return self.emit('error', new Error('Invalid MIME type: '+meta.mime));
  194. // FIXME: correctly handle .m3u us-ascii encoding
  195. self.baseUrl = meta.url;
  196. m3u8.parse(stream, function(err, index) {
  197. if (err) return self.emit('error', err);
  198. var updated = true;
  199. if (self.index && self.index.lastSeqNo() === index.lastSeqNo()) {
  200. debug('index was not updated');
  201. updated = false;
  202. }
  203. self.index = index;
  204. updatecheck(updated);
  205. });
  206. });
  207. }
  208. updateindex();
  209. function checkcurrent() {
  210. if (self.readState.currentSegment) return; // already processing
  211. self.readState.currentSegment = self.index.getSegment(self.readState.currentSeq);
  212. if (self.readState.currentSegment) {
  213. var url = self.readState.currentSegment.uri;
  214. fetchfrom(self.readState.currentSeq, self.readState.currentSegment, function(err) {
  215. self.readState.currentSegment = null;
  216. if (err) {
  217. if (!self.keepConnection) return self.emit('error', err);
  218. console.error('While fetching '+url+':', err.stack || err);
  219. //if (!transferred && err instanceof TempError) return; // TODO: retry with a range header
  220. }
  221. self.readState.currentSeq++;
  222. checkcurrent();
  223. });
  224. } else if (self.index.ended)
  225. self.end();
  226. else if (!self.index.type && (self.index.lastSeqNo() < self.readState.currentSeq-1)) {
  227. // handle live stream restart
  228. self.readState.currentSeq = self.index.startSeqNo(true);
  229. checkcurrent();
  230. }
  231. }
  232. function fetchfrom(seqNo, segment, cb) {
  233. var segmentUrl = url.resolve(self.baseUrl, segment.uri)
  234. debug('fetching segment', segmentUrl);
  235. getFileStream(url.parse(segmentUrl), {probe:!!self.noData}, function(err, stream, meta) {
  236. if (err) return cb(err);
  237. debug('got segment info', meta);
  238. if (meta.mime !== 'video/mp2t'/* &&
  239. meta.mime !== 'audio/aac' && meta.mime !== 'audio/x-aac' &&
  240. meta.mime !== 'audio/ac3'*/) {
  241. if (stream && stream.abort)
  242. stream.abort();
  243. return cb(new Error('Unsupported segment MIME type: '+meta.mime));
  244. }
  245. self.emit('segment', seqNo, segment.duration, meta);
  246. if (stream) {
  247. debug('preparing to push stream to reader', meta.url);
  248. stream.on('error', onerror);
  249. function onerror(err) {
  250. debug('stream error', err);
  251. stream.removeListener('error', onerror);
  252. cb(err)
  253. }
  254. self.readState.stream = stream;
  255. self.readState.stream_started = false;
  256. self.readState.doneCb = function() {
  257. debug('finished with input stream', meta.url);
  258. stream.removeListener('error', onerror);
  259. cb(null);
  260. };
  261. // force a new _read in the future()
  262. if (self.push(''))
  263. self.stream_start();
  264. } else {
  265. process.nextTick(cb);
  266. }
  267. });
  268. }
  269. // allow piping content to self
  270. this.write = function(chunk) {
  271. self.push(chunk);
  272. return true;
  273. };
  274. this.end = function() {};
  275. this.stream_start = function() {
  276. var stream = self.readState.stream;
  277. if (stream && !self.readState.stream_started) {
  278. debug('pushing input stream to reader');
  279. stream.pipe(self);
  280. oncemore(stream).once('end', 'error', function(err) {
  281. clearTimeout(self.readState.timer);
  282. stream.unpipe(self);
  283. self.readState.stream = null;
  284. if (!err)
  285. self.readState.doneCb();
  286. });
  287. clearTimeout(self.readState.timer);
  288. // abort() indicates a temporal stream. Ie. ensure it is completed in a timely fashion
  289. if (self.index.isLive() && typeof stream.abort == 'function') {
  290. var duration = self.readState.currentSegment.duration || self.index.target_duration || 10;
  291. duration = Math.min(duration, self.index.target_duration || 10);
  292. self.readState.timer = setTimeout(function() {
  293. if (self.readState.stream) {
  294. debug('timed out waiting for data');
  295. self.readState.stream.abort();
  296. }
  297. // TODO: ensure Done() is always called
  298. self.readState.timer = null;
  299. }, 1.5*duration*1000);
  300. }
  301. self.readState.stream_started = true;
  302. }
  303. }
  304. Readable.call(this, options);
  305. }
  306. util.inherits(HlsStreamReader, Readable);
  307. HlsStreamReader.prototype._read = function(n, cb) {
  308. this.stream_start();
  309. };
  310. function hlsreader(url, options) {
  311. return new HlsStreamReader(url, options);
  312. }
  313. function TempError(msg) {
  314. Error.captureStackTrace(this, this);
  315. this.message = msg || 'TempError';
  316. }
  317. util.inherits(TempError, Error);
  318. TempError.prototype.name = 'Temporary Error';