m3u8.js 7.2 KB

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