reader.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. options = options || {};
  76. if (srcUrl.protocol === 'http:' || srcUrl.protocol === 'https:') {
  77. var headers = options.headers || {};
  78. if (!headers['user-agent']) headers['user-agent'] = DEFAULT_AGENT;
  79. if (!headers['accept-encoding']) headers['accept-encoding'] = ['gzip','deflate'];
  80. var start = options.start || 0;
  81. if (start > 0)
  82. headers['range'] = 'bytes=' + options.start + '-';
  83. var req = (options.probe ? request.head : request.get)({uri:url.format(srcUrl), pool:false, headers:headers, timeout:60*1000});
  84. req.on('error', cb);
  85. req.on('response', function (res) {
  86. req.removeListener('error', cb);
  87. if (res.statusCode !== 200 && res.statusCode !== 206) {
  88. req.abort();
  89. if (res.statusCode >= 500 && res.statusCode !== 501)
  90. return cb(new TempError('HTTP Server returned: '+res.statusCode));
  91. else
  92. return cb(new Error('Bad server response code: '+res.statusCode));
  93. }
  94. var size = res.headers['content-length'] ? parseInt(res.headers['content-length'], 10) : -1;
  95. // turn bad content-length into actual errors
  96. if (size >= 0 && !options.probe) {
  97. var accum = 0;
  98. res.on('data', function(chunk) {
  99. accum += chunk.length;
  100. if (accum > size)
  101. req.abort();
  102. });
  103. oncemore(res).once('end', 'error', function(err) {
  104. // TODO: make this a custom error?
  105. if (!err && accum !== size)
  106. stream.emit('error', new PartialError('Stream length did not match header', accum, size));
  107. });
  108. }
  109. // transparently handle gzip responses
  110. var stream = res;
  111. if (res.headers['content-encoding'] === 'gzip' || res.headers['content-encoding'] === 'deflate') {
  112. unzip = zlib.createUnzip();
  113. stream = stream.pipe(inheritErrors(unzip));
  114. size = -1;
  115. }
  116. // adapt old style streams for pre-streams2 node versions
  117. if (Passthrough && !(stream instanceof Readable))
  118. stream = stream.pipe(inheritErrors(new Passthrough()));
  119. // allow aborting the request
  120. stream.abort = req.abort.bind(req);
  121. // forward all future errors to response stream
  122. req.on('error', function(err) {
  123. if (stream.listeners('error').length !== 0)
  124. stream.emit('error', err);
  125. });
  126. // attach empty 'error' listener to keep it from ever throwing
  127. stream.on('error', noop);
  128. // extract meta information from header
  129. var typeparts = /^(.+?\/.+?)(?:;\w*.*)?$/.exec(res.headers['content-type']) || [null, 'application/octet-stream'],
  130. mimetype = typeparts[1].toLowerCase(),
  131. modified = res.headers['last-modified'] ? new Date(res.headers['last-modified']) : null;
  132. cb(null, stream, {url:url.format(req.uri), mime:mimetype, size:start+size, modified:modified});
  133. });
  134. } else {
  135. process.nextTick(function() {
  136. cb(new Error('Unsupported protocol: '+srcUrl.protocol));
  137. });
  138. }
  139. /* if (srcUrl.protocol === 'file:') {
  140. } else if (srcUrl.protocol === 'data:') {
  141. //var regex = /^data:(.+\/.+);base64,(.*)$/;
  142. // add content-type && content-length headers
  143. } else {
  144. }*/
  145. }
  146. function HlsStreamReader(src, options) {
  147. var self = this;
  148. options = options || {};
  149. if (typeof src === 'string')
  150. src = url.parse(src);
  151. this.url = src;
  152. this.baseUrl = src;
  153. this.fullStream = !!options.fullStream;
  154. this.keepConnection = !!options.keepConnection;
  155. this.noData = !!options.noData;
  156. this.indexStream = null;
  157. this.index = null;
  158. this.readState = {
  159. currentSeq:-1,
  160. currentSegment:null,
  161. stream:null
  162. }
  163. function getUpdateInterval(updated) {
  164. if (updated && self.index.segments.length)
  165. return Math.min(self.index.target_duration, self.index.segments[self.index.segments.length-1].duration);
  166. else
  167. return self.index.target_duration / 2;
  168. }
  169. function updatecheck(updated) {
  170. if (updated) {
  171. if (self.readState.currentSeq===-1)
  172. self.readState.currentSeq = self.index.startSeqNo(self.fullStream);
  173. else if (self.readState.currentSeq < self.index.startSeqNo(true))
  174. self.readState.currentSeq = self.index.startSeqNo(true);
  175. self.emit('index', self.index);
  176. if (self.index.variant)
  177. return self.end();
  178. }
  179. checkcurrent();
  180. if (!self.index.ended) {
  181. var updateInterval = getUpdateInterval(updated);
  182. debug('scheduling index refresh', updateInterval);
  183. setTimeout(updateindex, Math.max(1, updateInterval)*1000);
  184. }
  185. }
  186. function updateindex() {
  187. getFileStream(self.url, function(err, stream, meta) {
  188. if (err) {
  189. if (self.index && self.keepConnection) {
  190. console.error('Failed to update index at '+url.format(self.url)+':', err.stack || err);
  191. return updatecheck();
  192. }
  193. return self.emit('error', err);
  194. }
  195. if (meta.mime !== 'application/vnd.apple.mpegurl' &&
  196. meta.mime !== 'application/x-mpegurl' && meta.mime !== 'audio/mpegurl')
  197. return self.emit('error', new Error('Invalid MIME type: '+meta.mime));
  198. // FIXME: correctly handle .m3u us-ascii encoding
  199. self.baseUrl = meta.url;
  200. m3u8.parse(stream, function(err, index) {
  201. if (err) return self.emit('error', err);
  202. var updated = true;
  203. if (self.index && self.index.lastSeqNo() === index.lastSeqNo()) {
  204. debug('index was not updated');
  205. updated = false;
  206. }
  207. self.index = index;
  208. updatecheck(updated);
  209. });
  210. });
  211. }
  212. updateindex();
  213. function checkcurrent() {
  214. if (self.readState.currentSegment) return; // already processing
  215. self.readState.currentSegment = self.index.getSegment(self.readState.currentSeq);
  216. if (self.readState.currentSegment) {
  217. var url = self.readState.currentSegment.uri;
  218. function tryfetch(start) {
  219. var seq = self.readState.currentSeq;
  220. fetchfrom(seq, self.readState.currentSegment, start, function(err) {
  221. if (err) {
  222. if (!self.keepConnection) return self.emit('error', err);
  223. console.error('While fetching '+url+':', err.stack || err);
  224. // retry with missing range if it is still relevant
  225. if (err instanceof PartialError && err.processed > 0 &&
  226. self.index.getSegment(seq))
  227. return tryfetch(start + err.processed);
  228. }
  229. self.readState.currentSegment = null;
  230. if (seq === self.readState.currentSeq)
  231. self.readState.currentSeq++;
  232. checkcurrent();
  233. });
  234. }
  235. tryfetch(0);
  236. } else if (self.index.ended)
  237. self.end();
  238. else if (!self.index.type && (self.index.lastSeqNo() < self.readState.currentSeq-1)) {
  239. // handle live stream restart
  240. self.readState.currentSeq = self.index.startSeqNo(true);
  241. checkcurrent();
  242. }
  243. }
  244. function fetchfrom(seqNo, segment, start, cb) {
  245. var segmentUrl = url.resolve(self.baseUrl, segment.uri)
  246. debug('fetching segment', segmentUrl);
  247. getFileStream(url.parse(segmentUrl), {probe:!!self.noData, start:start}, function(err, stream, meta) {
  248. if (err) return cb(err);
  249. debug('got segment info', meta);
  250. if (meta.mime !== 'video/mp2t'/* &&
  251. meta.mime !== 'audio/aac' && meta.mime !== 'audio/x-aac' &&
  252. meta.mime !== 'audio/ac3'*/) {
  253. if (stream && stream.abort)
  254. stream.abort();
  255. return cb(new Error('Unsupported segment MIME type: '+meta.mime));
  256. }
  257. if (!start)
  258. self.emit('segment', seqNo, segment.duration, meta);
  259. if (stream) {
  260. debug('preparing to push stream to reader', meta.url);
  261. stream.on('error', onerror);
  262. function onerror(err) {
  263. debug('stream error', err);
  264. stream.removeListener('error', onerror);
  265. cb(err)
  266. }
  267. self.readState.stream = stream;
  268. self.readState.stream_started = false;
  269. self.readState.doneCb = function() {
  270. debug('finished with input stream', meta.url);
  271. stream.removeListener('error', onerror);
  272. cb(null);
  273. };
  274. // force a new _read in the future()
  275. if (self.push(''))
  276. self.stream_start();
  277. } else {
  278. process.nextTick(cb);
  279. }
  280. });
  281. }
  282. // allow piping content to self
  283. this.write = function(chunk) {
  284. self.push(chunk);
  285. return true;
  286. };
  287. this.end = function() {};
  288. this.stream_start = function() {
  289. var stream = self.readState.stream;
  290. if (stream && !self.readState.stream_started) {
  291. debug('pushing input stream to reader');
  292. stream.pipe(self);
  293. oncemore(stream).once('end', 'error', function(err) {
  294. clearTimeout(self.readState.timer);
  295. stream.unpipe(self);
  296. self.readState.stream = null;
  297. if (!err)
  298. self.readState.doneCb();
  299. });
  300. clearTimeout(self.readState.timer);
  301. // abort() indicates a temporal stream. Ie. ensure it is completed in a timely fashion
  302. if (self.index.isLive() && typeof stream.abort == 'function') {
  303. var duration = self.readState.currentSegment.duration || self.index.target_duration || 10;
  304. duration = Math.min(duration, self.index.target_duration || 10);
  305. self.readState.timer = setTimeout(function() {
  306. if (self.readState.stream) {
  307. debug('timed out waiting for data');
  308. self.readState.stream.abort();
  309. }
  310. // TODO: ensure Done() is always called
  311. self.readState.timer = null;
  312. }, 1.5*duration*1000);
  313. }
  314. self.readState.stream_started = true;
  315. }
  316. }
  317. Readable.call(this, options);
  318. }
  319. util.inherits(HlsStreamReader, Readable);
  320. HlsStreamReader.prototype._read = function(n, cb) {
  321. this.stream_start();
  322. };
  323. function hlsreader(url, options) {
  324. return new HlsStreamReader(url, options);
  325. }
  326. function TempError(msg) {
  327. Error.captureStackTrace(this, this);
  328. this.message = msg || 'TempError';
  329. }
  330. util.inherits(TempError, Error);
  331. TempError.prototype.name = 'Temporary Error';
  332. function PartialError(msg, processed, expected) {
  333. Error.captureStackTrace(this, this);
  334. this.message = msg || 'TempError';
  335. this.processed = processed || -1;
  336. this.expected = expected;
  337. }
  338. util.inherits(PartialError, Error);
  339. PartialError.prototype.name = 'Partial Error';