m3u8.js 7.1 KB

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