parse-stream.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
  6. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  7. var _stream = require('./stream');
  8. var _stream2 = _interopRequireDefault(_stream);
  9. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  10. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  11. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  12. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
  13. * @file m3u8/parse-stream.js
  14. */
  15. /**
  16. * "forgiving" attribute list psuedo-grammar:
  17. * attributes -> keyvalue (',' keyvalue)*
  18. * keyvalue -> key '=' value
  19. * key -> [^=]*
  20. * value -> '"' [^"]* '"' | [^,]*
  21. */
  22. var attributeSeparator = function attributeSeparator() {
  23. var key = '[^=]*';
  24. var value = '"[^"]*"|[^,]*';
  25. var keyvalue = '(?:' + key + ')=(?:' + value + ')';
  26. return new RegExp('(?:^|,)(' + keyvalue + ')');
  27. };
  28. /**
  29. * Parse attributes from a line given the seperator
  30. *
  31. * @param {String} attributes the attibute line to parse
  32. */
  33. var parseAttributes = function parseAttributes(attributes) {
  34. // split the string using attributes as the separator
  35. var attrs = attributes.split(attributeSeparator());
  36. var result = {};
  37. var i = attrs.length;
  38. var attr = void 0;
  39. while (i--) {
  40. // filter out unmatched portions of the string
  41. if (attrs[i] === '') {
  42. continue;
  43. }
  44. // split the key and value
  45. attr = /([^=]*)=(.*)/.exec(attrs[i]).slice(1);
  46. // trim whitespace and remove optional quotes around the value
  47. attr[0] = attr[0].replace(/^\s+|\s+$/g, '');
  48. attr[1] = attr[1].replace(/^\s+|\s+$/g, '');
  49. attr[1] = attr[1].replace(/^['"](.*)['"]$/g, '$1');
  50. result[attr[0]] = attr[1];
  51. }
  52. return result;
  53. };
  54. /**
  55. * A line-level M3U8 parser event stream. It expects to receive input one
  56. * line at a time and performs a context-free parse of its contents. A stream
  57. * interpretation of a manifest can be useful if the manifest is expected to
  58. * be too large to fit comfortably into memory or the entirety of the input
  59. * is not immediately available. Otherwise, it's probably much easier to work
  60. * with a regular `Parser` object.
  61. *
  62. * Produces `data` events with an object that captures the parser's
  63. * interpretation of the input. That object has a property `tag` that is one
  64. * of `uri`, `comment`, or `tag`. URIs only have a single additional
  65. * property, `line`, which captures the entirety of the input without
  66. * interpretation. Comments similarly have a single additional property
  67. * `text` which is the input without the leading `#`.
  68. *
  69. * Tags always have a property `tagType` which is the lower-cased version of
  70. * the M3U8 directive without the `#EXT` or `#EXT-X-` prefix. For instance,
  71. * `#EXT-X-MEDIA-SEQUENCE` becomes `media-sequence` when parsed. Unrecognized
  72. * tags are given the tag type `unknown` and a single additional property
  73. * `data` with the remainder of the input.
  74. *
  75. * @class ParseStream
  76. * @extends Stream
  77. */
  78. var ParseStream = function (_Stream) {
  79. _inherits(ParseStream, _Stream);
  80. function ParseStream() {
  81. _classCallCheck(this, ParseStream);
  82. return _possibleConstructorReturn(this, (ParseStream.__proto__ || Object.getPrototypeOf(ParseStream)).call(this));
  83. }
  84. /**
  85. * Parses an additional line of input.
  86. *
  87. * @param {String} line a single line of an M3U8 file to parse
  88. */
  89. _createClass(ParseStream, [{
  90. key: 'push',
  91. value: function push(line) {
  92. var match = void 0;
  93. var event = void 0;
  94. // strip whitespace
  95. line = line.replace(/^[\u0000\s]+|[\u0000\s]+$/g, '');
  96. if (line.length === 0) {
  97. // ignore empty lines
  98. return;
  99. }
  100. // URIs
  101. if (line[0] !== '#') {
  102. this.trigger('data', {
  103. type: 'uri',
  104. uri: line
  105. });
  106. return;
  107. }
  108. // Comments
  109. if (line.indexOf('#EXT') !== 0) {
  110. this.trigger('data', {
  111. type: 'comment',
  112. text: line.slice(1)
  113. });
  114. return;
  115. }
  116. // strip off any carriage returns here so the regex matching
  117. // doesn't have to account for them.
  118. line = line.replace('\r', '');
  119. // Tags
  120. match = /^#EXTM3U/.exec(line);
  121. if (match) {
  122. this.trigger('data', {
  123. type: 'tag',
  124. tagType: 'm3u'
  125. });
  126. return;
  127. }
  128. match = /^#EXTINF:?([0-9\.]*)?,?(.*)?$/.exec(line);
  129. if (match) {
  130. event = {
  131. type: 'tag',
  132. tagType: 'inf'
  133. };
  134. if (match[1]) {
  135. event.duration = parseFloat(match[1]);
  136. }
  137. if (match[2]) {
  138. event.title = match[2];
  139. }
  140. this.trigger('data', event);
  141. return;
  142. }
  143. match = /^#EXT-X-TARGETDURATION:?([0-9.]*)?/.exec(line);
  144. if (match) {
  145. event = {
  146. type: 'tag',
  147. tagType: 'targetduration'
  148. };
  149. if (match[1]) {
  150. event.duration = parseInt(match[1], 10);
  151. }
  152. this.trigger('data', event);
  153. return;
  154. }
  155. match = /^#ZEN-TOTAL-DURATION:?([0-9.]*)?/.exec(line);
  156. if (match) {
  157. event = {
  158. type: 'tag',
  159. tagType: 'totalduration'
  160. };
  161. if (match[1]) {
  162. event.duration = parseInt(match[1], 10);
  163. }
  164. this.trigger('data', event);
  165. return;
  166. }
  167. match = /^#EXT-X-VERSION:?([0-9.]*)?/.exec(line);
  168. if (match) {
  169. event = {
  170. type: 'tag',
  171. tagType: 'version'
  172. };
  173. if (match[1]) {
  174. event.version = parseInt(match[1], 10);
  175. }
  176. this.trigger('data', event);
  177. return;
  178. }
  179. match = /^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(line);
  180. if (match) {
  181. event = {
  182. type: 'tag',
  183. tagType: 'media-sequence'
  184. };
  185. if (match[1]) {
  186. event.number = parseInt(match[1], 10);
  187. }
  188. this.trigger('data', event);
  189. return;
  190. }
  191. match = /^#EXT-X-DISCONTINUITY-SEQUENCE:?(\-?[0-9.]*)?/.exec(line);
  192. if (match) {
  193. event = {
  194. type: 'tag',
  195. tagType: 'discontinuity-sequence'
  196. };
  197. if (match[1]) {
  198. event.number = parseInt(match[1], 10);
  199. }
  200. this.trigger('data', event);
  201. return;
  202. }
  203. match = /^#EXT-X-PLAYLIST-TYPE:?(.*)?$/.exec(line);
  204. if (match) {
  205. event = {
  206. type: 'tag',
  207. tagType: 'playlist-type'
  208. };
  209. if (match[1]) {
  210. event.playlistType = match[1];
  211. }
  212. this.trigger('data', event);
  213. return;
  214. }
  215. match = /^#EXT-X-BYTERANGE:?([0-9.]*)?@?([0-9.]*)?/.exec(line);
  216. if (match) {
  217. event = {
  218. type: 'tag',
  219. tagType: 'byterange'
  220. };
  221. if (match[1]) {
  222. event.length = parseInt(match[1], 10);
  223. }
  224. if (match[2]) {
  225. event.offset = parseInt(match[2], 10);
  226. }
  227. this.trigger('data', event);
  228. return;
  229. }
  230. match = /^#EXT-X-ALLOW-CACHE:?(YES|NO)?/.exec(line);
  231. if (match) {
  232. event = {
  233. type: 'tag',
  234. tagType: 'allow-cache'
  235. };
  236. if (match[1]) {
  237. event.allowed = !/NO/.test(match[1]);
  238. }
  239. this.trigger('data', event);
  240. return;
  241. }
  242. match = /^#EXT-X-MAP:?(.*)$/.exec(line);
  243. if (match) {
  244. event = {
  245. type: 'tag',
  246. tagType: 'map'
  247. };
  248. if (match[1]) {
  249. var attributes = parseAttributes(match[1]);
  250. if (attributes.URI) {
  251. event.uri = attributes.URI;
  252. }
  253. if (attributes.BYTERANGE) {
  254. var _attributes$BYTERANGE = attributes.BYTERANGE.split('@'),
  255. _attributes$BYTERANGE2 = _slicedToArray(_attributes$BYTERANGE, 2),
  256. length = _attributes$BYTERANGE2[0],
  257. offset = _attributes$BYTERANGE2[1];
  258. event.byterange = {};
  259. if (length) {
  260. event.byterange.length = parseInt(length, 10);
  261. }
  262. if (offset) {
  263. event.byterange.offset = parseInt(offset, 10);
  264. }
  265. }
  266. }
  267. this.trigger('data', event);
  268. return;
  269. }
  270. match = /^#EXT-X-STREAM-INF:?(.*)$/.exec(line);
  271. if (match) {
  272. event = {
  273. type: 'tag',
  274. tagType: 'stream-inf'
  275. };
  276. if (match[1]) {
  277. event.attributes = parseAttributes(match[1]);
  278. if (event.attributes.RESOLUTION) {
  279. var split = event.attributes.RESOLUTION.split('x');
  280. var resolution = {};
  281. if (split[0]) {
  282. resolution.width = parseInt(split[0], 10);
  283. }
  284. if (split[1]) {
  285. resolution.height = parseInt(split[1], 10);
  286. }
  287. event.attributes.RESOLUTION = resolution;
  288. }
  289. if (event.attributes.BANDWIDTH) {
  290. event.attributes.BANDWIDTH = parseInt(event.attributes.BANDWIDTH, 10);
  291. }
  292. if (event.attributes['PROGRAM-ID']) {
  293. event.attributes['PROGRAM-ID'] = parseInt(event.attributes['PROGRAM-ID'], 10);
  294. }
  295. }
  296. this.trigger('data', event);
  297. return;
  298. }
  299. match = /^#EXT-X-MEDIA:?(.*)$/.exec(line);
  300. if (match) {
  301. event = {
  302. type: 'tag',
  303. tagType: 'media'
  304. };
  305. if (match[1]) {
  306. event.attributes = parseAttributes(match[1]);
  307. }
  308. this.trigger('data', event);
  309. return;
  310. }
  311. match = /^#EXT-X-ENDLIST/.exec(line);
  312. if (match) {
  313. this.trigger('data', {
  314. type: 'tag',
  315. tagType: 'endlist'
  316. });
  317. return;
  318. }
  319. match = /^#EXT-X-DISCONTINUITY/.exec(line);
  320. if (match) {
  321. this.trigger('data', {
  322. type: 'tag',
  323. tagType: 'discontinuity'
  324. });
  325. return;
  326. }
  327. match = /^#EXT-X-PROGRAM-DATE-TIME:?(.*)$/.exec(line);
  328. if (match) {
  329. event = {
  330. type: 'tag',
  331. tagType: 'program-date-time'
  332. };
  333. if (match[1]) {
  334. event.dateTimeString = match[1];
  335. event.dateTimeObject = new Date(match[1]);
  336. }
  337. this.trigger('data', event);
  338. return;
  339. }
  340. match = /^#EXT-X-KEY:?(.*)$/.exec(line);
  341. if (match) {
  342. event = {
  343. type: 'tag',
  344. tagType: 'key'
  345. };
  346. if (match[1]) {
  347. event.attributes = parseAttributes(match[1]);
  348. // parse the IV string into a Uint32Array
  349. if (event.attributes.IV) {
  350. if (event.attributes.IV.substring(0, 2).toLowerCase() === '0x') {
  351. event.attributes.IV = event.attributes.IV.substring(2);
  352. }
  353. event.attributes.IV = event.attributes.IV.match(/.{8}/g);
  354. event.attributes.IV[0] = parseInt(event.attributes.IV[0], 16);
  355. event.attributes.IV[1] = parseInt(event.attributes.IV[1], 16);
  356. event.attributes.IV[2] = parseInt(event.attributes.IV[2], 16);
  357. event.attributes.IV[3] = parseInt(event.attributes.IV[3], 16);
  358. event.attributes.IV = new Uint32Array(event.attributes.IV);
  359. }
  360. }
  361. this.trigger('data', event);
  362. return;
  363. }
  364. match = /^#EXT-X-CUE-OUT-CONT:?(.*)?$/.exec(line);
  365. if (match) {
  366. event = {
  367. type: 'tag',
  368. tagType: 'cue-out-cont'
  369. };
  370. if (match[1]) {
  371. event.data = match[1];
  372. } else {
  373. event.data = '';
  374. }
  375. this.trigger('data', event);
  376. return;
  377. }
  378. match = /^#EXT-X-CUE-OUT:?(.*)?$/.exec(line);
  379. if (match) {
  380. event = {
  381. type: 'tag',
  382. tagType: 'cue-out'
  383. };
  384. if (match[1]) {
  385. event.data = match[1];
  386. } else {
  387. event.data = '';
  388. }
  389. this.trigger('data', event);
  390. return;
  391. }
  392. match = /^#EXT-X-CUE-IN:?(.*)?$/.exec(line);
  393. if (match) {
  394. event = {
  395. type: 'tag',
  396. tagType: 'cue-in'
  397. };
  398. if (match[1]) {
  399. event.data = match[1];
  400. } else {
  401. event.data = '';
  402. }
  403. this.trigger('data', event);
  404. return;
  405. }
  406. // unknown tag type
  407. this.trigger('data', {
  408. type: 'tag',
  409. data: line.slice(4)
  410. });
  411. }
  412. }]);
  413. return ParseStream;
  414. }(_stream2['default']);
  415. exports['default'] = ParseStream;