reader.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. oncemore = require('./oncemore'),
  8. debug = require('debug')('hls:reader');
  9. try {
  10. var Readable = require('stream').Readable;
  11. assert(Readable);
  12. var Passthrough = null;
  13. } catch (e) {
  14. var Readable = require('readable-stream');
  15. var Passthrough = require('readable-stream/passthrough');
  16. }
  17. var m3u8 = require('./m3u8');
  18. function noop() {};
  19. var DEFAULT_AGENT = util.format('hls-tools/v%s (http://github.com/kanongil/node-hls-tools) node.js/%s', require('../package').version, process.version);
  20. module.exports = hlsreader;
  21. hlsreader.HlsStreamReader = HlsStreamReader;
  22. /*
  23. options:
  24. startSeq*
  25. noData // don't emit any data - useful for analyzing the stream structure
  26. maxRedirects*
  27. cacheDir*
  28. headers* // allows for custom user-agent, cookies, auth, etc
  29. emits:
  30. index (m3u8)
  31. segment (seqNo, duration, datetime, size?, )
  32. */
  33. function inheritErrors(stream) {
  34. stream.on('pipe', function(source) {
  35. source.on('error', stream.emit.bind(stream, 'error'));
  36. });
  37. stream.on('unpipe', function(source) {
  38. source.removeListener('error', stream.emit.bind(stream, 'error'));
  39. });
  40. return stream;
  41. }
  42. function getFileStream(srcUrl, options, cb) {
  43. assert(srcUrl.protocol);
  44. if (typeof options === 'function') {
  45. cb = options;
  46. options = {};
  47. }
  48. options = options || {};
  49. if (srcUrl.protocol === 'http:' || srcUrl.protocol === 'https:') {
  50. var headers = options.headers || {};
  51. if (!headers['user-agent']) headers['user-agent'] = DEFAULT_AGENT;
  52. if (!headers['accept-encoding']) headers['accept-encoding'] = ['gzip','deflate'];
  53. var start = options.start || 0;
  54. if (start > 0)
  55. headers['range'] = 'bytes=' + options.start + '-';
  56. var req = (options.probe ? request.head : request.get)({uri:url.format(srcUrl), pool:false, headers:headers, timeout:60*1000});
  57. req.on('error', onreqerror);
  58. req.on('error', noop);
  59. req.on('response', onresponse);
  60. function onreqerror(err) {
  61. req.removeListener('error', onreqerror);
  62. req.removeListener('response', onresponse);
  63. cb(err);
  64. }
  65. function onresponse(res) {
  66. req.removeListener('error', onreqerror);
  67. req.removeListener('response', onresponse);
  68. if (res.statusCode !== 200 && res.statusCode !== 206) {
  69. req.abort();
  70. if (res.statusCode >= 500 && res.statusCode !== 501)
  71. return cb(new TempError('HTTP Server returned: '+res.statusCode));
  72. else
  73. return cb(new Error('Bad server response code: '+res.statusCode));
  74. }
  75. var size = res.headers['content-length'] ? parseInt(res.headers['content-length'], 10) : -1;
  76. // turn bad content-length into actual errors
  77. if (size >= 0 && !options.probe) {
  78. var accum = 0;
  79. res.on('data', function(chunk) {
  80. accum += chunk.length;
  81. if (accum > size)
  82. req.abort();
  83. });
  84. oncemore(res).once('end', 'error', function(err) {
  85. // TODO: make this a custom error?
  86. if (!err && accum !== size)
  87. stream.emit('error', new PartialError('Stream length did not match header', accum, size));
  88. });
  89. }
  90. // transparently handle gzip responses
  91. var stream = res;
  92. if (res.headers['content-encoding'] === 'gzip' || res.headers['content-encoding'] === 'deflate') {
  93. unzip = zlib.createUnzip();
  94. stream = stream.pipe(inheritErrors(unzip));
  95. size = -1;
  96. }
  97. // adapt old style streams for pre-streams2 node versions
  98. if (Passthrough && !(stream instanceof Readable))
  99. stream = stream.pipe(inheritErrors(new Passthrough()));
  100. // allow aborting the request
  101. stream.abort = req.abort.bind(req);
  102. // forward all future errors to response stream
  103. req.on('error', function(err) {
  104. if (stream.listeners('error').length !== 0)
  105. stream.emit('error', err);
  106. });
  107. // attach empty 'error' listener to keep it from ever throwing
  108. stream.on('error', noop);
  109. // extract meta information from header
  110. var typeparts = /^(.+?\/.+?)(?:;\w*.*)?$/.exec(res.headers['content-type']) || [null, 'application/octet-stream'],
  111. mimetype = typeparts[1].toLowerCase(),
  112. modified = res.headers['last-modified'] ? new Date(res.headers['last-modified']) : null;
  113. cb(null, stream, {url:url.format(req.uri), mime:mimetype, size:start+size, modified:modified});
  114. }
  115. } else {
  116. process.nextTick(function() {
  117. cb(new Error('Unsupported protocol: '+srcUrl.protocol));
  118. });
  119. }
  120. /* if (srcUrl.protocol === 'file:') {
  121. } else if (srcUrl.protocol === 'data:') {
  122. //var regex = /^data:(.+\/.+);base64,(.*)$/;
  123. // add content-type && content-length headers
  124. } else {
  125. }*/
  126. }
  127. function HlsStreamReader(src, options) {
  128. var self = this;
  129. options = options || {};
  130. if (typeof src === 'string')
  131. src = url.parse(src);
  132. this.url = src;
  133. this.baseUrl = src;
  134. this.fullStream = !!options.fullStream;
  135. this.keepConnection = !!options.keepConnection;
  136. this.noData = !!options.noData;
  137. this.indexStream = null;
  138. this.index = null;
  139. this.readState = {
  140. currentSeq:-1,
  141. currentSegment:null,
  142. stream:null
  143. }
  144. function getUpdateInterval(updated) {
  145. if (updated && self.index.segments.length)
  146. return Math.min(self.index.target_duration, self.index.segments[self.index.segments.length-1].duration);
  147. else
  148. return self.index.target_duration / 2;
  149. }
  150. function updatecheck(updated) {
  151. if (updated) {
  152. if (self.readState.currentSeq===-1)
  153. self.readState.currentSeq = self.index.startSeqNo(self.fullStream);
  154. else if (self.readState.currentSeq < self.index.startSeqNo(true))
  155. self.readState.currentSeq = self.index.startSeqNo(true);
  156. self.emit('index', self.index);
  157. if (self.index.variant)
  158. return self.end();
  159. }
  160. checkcurrent();
  161. if (!self.index.ended) {
  162. var updateInterval = getUpdateInterval(updated);
  163. debug('scheduling index refresh', updateInterval);
  164. setTimeout(updateindex, Math.max(1, updateInterval)*1000);
  165. }
  166. }
  167. function updateindex() {
  168. getFileStream(self.url, function(err, stream, meta) {
  169. if (err) {
  170. if (self.index && self.keepConnection) {
  171. console.error('Failed to update index at '+url.format(self.url)+':', err.stack || err);
  172. return updatecheck(false);
  173. }
  174. return self.emit('error', err);
  175. }
  176. if (meta.mime !== 'application/vnd.apple.mpegurl' &&
  177. meta.mime !== 'application/x-mpegurl' && meta.mime !== 'audio/mpegurl')
  178. return self.emit('error', new Error('Invalid MIME type: '+meta.mime));
  179. // FIXME: correctly handle .m3u us-ascii encoding
  180. self.baseUrl = meta.url;
  181. m3u8.parse(stream, function(err, index) {
  182. if (err) {
  183. if (self.index && self.keepConnection) {
  184. console.error('Failed to parse index at '+url.format(self.url)+':', err.stack || err);
  185. return updatecheck(false);
  186. }
  187. return self.emit('error', err);
  188. }
  189. var updated = true;
  190. if (self.index && self.index.lastSeqNo() === index.lastSeqNo()) {
  191. debug('index was not updated');
  192. updated = false;
  193. }
  194. self.index = index;
  195. updatecheck(updated);
  196. });
  197. });
  198. }
  199. updateindex();
  200. function checkcurrent() {
  201. if (self.readState.currentSegment) return; // already processing
  202. self.readState.currentSegment = self.index.getSegment(self.readState.currentSeq);
  203. if (self.readState.currentSegment) {
  204. var url = self.readState.currentSegment.uri;
  205. function tryfetch(start) {
  206. var seq = self.readState.currentSeq;
  207. fetchfrom(seq, self.readState.currentSegment, start, function(err) {
  208. if (err) {
  209. if (!self.keepConnection) return self.emit('error', err);
  210. console.error('While fetching '+url+':', err.stack || err);
  211. // retry with missing range if it is still relevant
  212. if (err instanceof PartialError && err.processed > 0 &&
  213. self.index.getSegment(seq))
  214. return tryfetch(start + err.processed);
  215. }
  216. self.readState.currentSegment = null;
  217. if (seq === self.readState.currentSeq)
  218. self.readState.currentSeq++;
  219. checkcurrent();
  220. });
  221. }
  222. tryfetch(0);
  223. } else if (self.index.ended)
  224. self.end();
  225. else if (!self.index.type && (self.index.lastSeqNo() < self.readState.currentSeq-1)) {
  226. // handle live stream restart
  227. self.readState.currentSeq = self.index.startSeqNo(true);
  228. checkcurrent();
  229. }
  230. }
  231. function fetchfrom(seqNo, segment, start, cb) {
  232. var segmentUrl = url.resolve(self.baseUrl, segment.uri)
  233. debug('fetching segment', segmentUrl);
  234. getFileStream(url.parse(segmentUrl), {probe:!!self.noData, start:start}, function(err, stream, meta) {
  235. if (err) return cb(err);
  236. debug('got segment info', meta);
  237. if (meta.mime !== 'video/mp2t'/* &&
  238. meta.mime !== 'audio/aac' && meta.mime !== 'audio/x-aac' &&
  239. meta.mime !== 'audio/ac3'*/) {
  240. if (stream && stream.abort)
  241. stream.abort();
  242. return cb(new Error('Unsupported segment MIME type: '+meta.mime));
  243. }
  244. if (!start)
  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';
  319. function PartialError(msg, processed, expected) {
  320. Error.captureStackTrace(this, this);
  321. this.message = msg || 'TempError';
  322. this.processed = processed || -1;
  323. this.expected = expected;
  324. }
  325. util.inherits(PartialError, Error);
  326. PartialError.prototype.name = 'Partial Error';