reader.js 13 KB

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