m3u8.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. var path = require('path'),
  2. util = require('util'),
  3. carrier = require('carrier'),
  4. debug = require('debug')('hls:m3u8');
  5. exports.M3U8Playlist = M3U8Playlist;
  6. exports.M3U8Segment = M3U8Segment;
  7. exports.ParserError = ParserError;
  8. exports.parse = parse;
  9. //exports.stringify = stringify;
  10. function M3U8Playlist() {
  11. this.variant = false;
  12. // initialize to default values
  13. this.version = 1; // V1
  14. this.allow_cache = true;
  15. this.i_frames_only = false; // V4
  16. this.target_duration = undefined;
  17. this.first_seq_no = 0;
  18. this.type = undefined; // V?
  19. this.ended = false;
  20. this.segments = [];
  21. // for variant streams
  22. this.programs = {};
  23. this.groups = {};
  24. }
  25. M3U8Playlist.prototype.PlaylistType = {
  26. EVENT: 'EVENT',
  27. VOD: 'VOD'
  28. };
  29. M3U8Playlist.prototype.totalDuration = function() {
  30. return this.segments.reduce(function(sum, segment) {
  31. return sum + segment.duration;
  32. }, 0);
  33. };
  34. M3U8Playlist.prototype.isLive = function() {
  35. return !(this.ended || this.type === this.PlaylistType.VOD);
  36. };
  37. M3U8Playlist.prototype.startSeqNo = function(full) {
  38. if (!this.isLive() || full) return this.first_seq_no;
  39. var duration = this.target_duration * 3;
  40. for (var i=this.segments.length-1; i>0; i--) {
  41. duration -= this.segments[i].duration;
  42. if (duration < 0) break;
  43. }
  44. // TODO: validate that correct seqNo is returned
  45. return this.first_seq_no + i;
  46. };
  47. M3U8Playlist.prototype.lastSeqNo = function() {
  48. return this.first_seq_no + this.segments.length - 1;
  49. };
  50. // return whether the seqNo is in the index
  51. M3U8Playlist.prototype.isValidSeqNo = function(seqNo) {
  52. return (seqNo >= this.first_seq_no) && (seqNo <= this.lastSeqNo());
  53. };
  54. M3U8Playlist.prototype.getSegment = function(seqNo) {
  55. // TODO: should we check for number type and throw if not?
  56. var index = seqNo-this.first_seq_no;
  57. if (index < 0 || index > this.segments.length)
  58. return null;
  59. return this.segments[index];
  60. };
  61. M3U8Playlist.prototype.toString = function() {
  62. // TODO:
  63. return 'M3U8Playlist';
  64. };
  65. function M3U8Segment(uri, meta, version) {
  66. this.duration = meta.duration;
  67. this.title = meta.title;
  68. this.uri = uri;
  69. this.discontinuity = meta.discontinuity || false;
  70. // optional
  71. if (meta.program_time)
  72. this.program_time = meta.program_time;
  73. if (meta.key)
  74. this.key = meta.key;
  75. if (version >= 5 && meta.map)
  76. this.map = meta.map;
  77. }
  78. M3U8Segment.prototype.toString = function() {
  79. // TODO: support writing all the information
  80. return '#EXTINF '+this.duration.toFixed(3)+','+this.title + '\n' + this.uri + '\n';
  81. };
  82. function parse(stream, cb) {
  83. var m3u8 = new M3U8Playlist(),
  84. line_no = 0,
  85. meta = {};
  86. stream.on('error', ReportError);
  87. var cr = carrier.carry(stream);
  88. cr.on('line', ParseLine);
  89. cr.on('end', Complete);
  90. function cleanup() {
  91. stream.removeListener('error', ReportError);
  92. cr.removeListener('line', ParseLine);
  93. cr.removeListener('end', Complete);
  94. }
  95. function ReportError(err) {
  96. cleanup();
  97. cb(err);
  98. }
  99. function Complete() {
  100. if (line_no === 0)
  101. return ReportError(new ParserError('No line data', '', -1))
  102. cleanup();
  103. cb(null, m3u8);
  104. }
  105. function ParseExt(cmd, arg) {
  106. if (!(cmd in extParser))
  107. return false;
  108. debug('parsing ext', cmd, arg);
  109. extParser[cmd](arg);
  110. return true;
  111. }
  112. // AttrList's are currently handled without any implicit knowledge of key/type mapping
  113. function ParseAttrList(input) {
  114. // TODO: handle newline escapes in quoted-string's
  115. var re = /(.+?)=((?:\".*?\")|.*?)(?:,|$)/g;
  116. // var re = /(.+?)=(?:(?:\"(.*?)\")|(.*?))(?:,|$)/g;
  117. var match, attrs = {};
  118. while ((match = re.exec(input)) !== null)
  119. attrs[match[1].toLowerCase()] = match[2];
  120. debug('parsed attributes', attrs);
  121. return attrs;
  122. }
  123. function unquote(str) {
  124. return str.slice(1,-1);
  125. }
  126. function ParseLine(line) {
  127. line_no += 1;
  128. if (line_no === 1) {
  129. if (line !== '#EXTM3U')
  130. return ReportError(new ParserError('Missing required #EXTM3U header', line, line_no));
  131. return;
  132. }
  133. if (!line.length) return; // blank lines are ignored (3.1)
  134. if (line[0] === '#') {
  135. var matches = line.match(/^(#EXT[^:]*):?(.*)/);
  136. if (!matches)
  137. return debug('ignoring comment', line);
  138. var cmd = matches[1],
  139. arg = matches[2];
  140. if (!ParseExt(cmd, arg))
  141. return ReportError(new ParserError('Unknown #EXT: '+cmd, line, line_no));
  142. } else if (m3u8.variant) {
  143. var id = meta.info['program-id'];
  144. if (!(id in m3u8.programs))
  145. m3u8.programs[id] = [];
  146. meta.uri = line;
  147. m3u8.programs[id].push(meta);
  148. meta = {};
  149. } else {
  150. if (!('duration' in meta))
  151. return ReportError(new ParserError('Missing #EXTINF before media file URI', line, line_no));
  152. m3u8.segments.push(new M3U8Segment(line, meta, m3u8.version));
  153. meta = {};
  154. }
  155. }
  156. // TODO: add more validation logic
  157. var extParser = {
  158. '#EXT-X-VERSION': function(arg) {
  159. m3u8.version = parseInt(arg, 10);
  160. if (m3u8.version >= 4)
  161. for (var attrname in extParserV4) { extParser[attrname] = extParser[attrname]; }
  162. if (m3u8.version >= 5)
  163. for (var attrname in extParserV5) { extParser[attrname] = extParser[attrname]; }
  164. },
  165. '#EXT-X-TARGETDURATION': function(arg) {
  166. m3u8.target_duration = parseInt(arg, 10);
  167. },
  168. '#EXT-X-ALLOW-CACHE': function(arg) {
  169. m3u8.allow_cache = (arg!=='NO');
  170. },
  171. '#EXT-X-MEDIA-SEQUENCE': function(arg) {
  172. m3u8.first_seq_no = parseInt(arg, 10);
  173. },
  174. '#EXT-X-PLAYLIST-TYPE': function(arg) {
  175. m3u8.type = arg;
  176. },
  177. '#EXT-X-ENDLIST': function(arg) {
  178. m3u8.ended = true;
  179. },
  180. '#EXTINF': function(arg) {
  181. var n = arg.split(',');
  182. meta.duration = parseFloat(n.shift());
  183. meta.title = n.join(',');
  184. if (meta.duration <= 0)
  185. return ReportError(new ParserError('Invalid duration', line, line_no));
  186. },
  187. '#EXT-X-KEY': function(arg) {
  188. meta.key = ParseAttrList(arg);
  189. },
  190. '#EXT-X-PROGRAM-DATE-TIME': function(arg) {
  191. meta.program_time = new Date(arg);
  192. },
  193. '#EXT-X-DISCONTINUITY': function(arg) {
  194. meta.discontinuity = true;
  195. },
  196. // variant
  197. '#EXT-X-STREAM-INF': function(arg) {
  198. m3u8.variant = true;
  199. meta.info = ParseAttrList(arg);
  200. },
  201. // variant v4 since variant streams are not required to specify version
  202. '#EXT-X-MEDIA': function(arg) {
  203. //m3u8.variant = true;
  204. var attrs = ParseAttrList(arg),
  205. id = unquote(attrs['group-id']);
  206. if (!(id in m3u8.groups)) {
  207. m3u8.groups[id] = [];
  208. m3u8.groups[id].type = attrs.type;
  209. }
  210. m3u8.groups[id].push(attrs);
  211. },
  212. '#EXT-X-I-FRAME-STREAM-INF': function(arg) {
  213. m3u8.variant = true;
  214. debug('not yet supported', '#EXT-X-I-FRAME-STREAM-INF');
  215. }
  216. };
  217. var extParserV4 = {
  218. '#EXT-X-I-FRAMES-ONLY': function(arg) {
  219. m3u8.i_frames_only = true;
  220. },
  221. '#EXT-X-BYTERANGE': function(arg) {
  222. var n = arg.split('@');
  223. meta.byterange = {length:parseInt(n[0], 10)};
  224. if (n.length > 1)
  225. meta.byterange.offset = parseInt(n[1], 10);
  226. }
  227. }
  228. var extParserV5 = {
  229. '#EXT-X-MAP': function(arg) {
  230. meta.map = ParseAttrList(arg);
  231. }
  232. }
  233. }
  234. function ParserError(msg, line, line_no, constr) {
  235. Error.captureStackTrace(this, constr || this);
  236. this.message = msg || 'Error';
  237. this.line = line;
  238. this.lineNumber = line_no;
  239. }
  240. util.inherits(ParserError, Error);
  241. ParserError.prototype.name = 'Parser Error';