m3u8-parser.es.js 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503
  1. /*! @name m3u8-parser @version 6.0.0 @license Apache-2.0 */
  2. import Stream from '@videojs/vhs-utils/es/stream.js';
  3. import _extends from '@babel/runtime/helpers/extends';
  4. import decodeB64ToUint8Array from '@videojs/vhs-utils/es/decode-b64-to-uint8-array.js';
  5. /**
  6. * @file m3u8/line-stream.js
  7. */
  8. /**
  9. * A stream that buffers string input and generates a `data` event for each
  10. * line.
  11. *
  12. * @class LineStream
  13. * @extends Stream
  14. */
  15. class LineStream extends Stream {
  16. constructor() {
  17. super();
  18. this.buffer = '';
  19. }
  20. /**
  21. * Add new data to be parsed.
  22. *
  23. * @param {string} data the text to process
  24. */
  25. push(data) {
  26. let nextNewline;
  27. this.buffer += data;
  28. nextNewline = this.buffer.indexOf('\n');
  29. for (; nextNewline > -1; nextNewline = this.buffer.indexOf('\n')) {
  30. this.trigger('data', this.buffer.substring(0, nextNewline));
  31. this.buffer = this.buffer.substring(nextNewline + 1);
  32. }
  33. }
  34. }
  35. const TAB = String.fromCharCode(0x09);
  36. const parseByterange = function (byterangeString) {
  37. // optionally match and capture 0+ digits before `@`
  38. // optionally match and capture 0+ digits after `@`
  39. const match = /([0-9.]*)?@?([0-9.]*)?/.exec(byterangeString || '');
  40. const result = {};
  41. if (match[1]) {
  42. result.length = parseInt(match[1], 10);
  43. }
  44. if (match[2]) {
  45. result.offset = parseInt(match[2], 10);
  46. }
  47. return result;
  48. };
  49. /**
  50. * "forgiving" attribute list psuedo-grammar:
  51. * attributes -> keyvalue (',' keyvalue)*
  52. * keyvalue -> key '=' value
  53. * key -> [^=]*
  54. * value -> '"' [^"]* '"' | [^,]*
  55. */
  56. const attributeSeparator = function () {
  57. const key = '[^=]*';
  58. const value = '"[^"]*"|[^,]*';
  59. const keyvalue = '(?:' + key + ')=(?:' + value + ')';
  60. return new RegExp('(?:^|,)(' + keyvalue + ')');
  61. };
  62. /**
  63. * Parse attributes from a line given the separator
  64. *
  65. * @param {string} attributes the attribute line to parse
  66. */
  67. const parseAttributes = function (attributes) {
  68. const result = {};
  69. if (!attributes) {
  70. return result;
  71. } // split the string using attributes as the separator
  72. const attrs = attributes.split(attributeSeparator());
  73. let i = attrs.length;
  74. let attr;
  75. while (i--) {
  76. // filter out unmatched portions of the string
  77. if (attrs[i] === '') {
  78. continue;
  79. } // split the key and value
  80. attr = /([^=]*)=(.*)/.exec(attrs[i]).slice(1); // trim whitespace and remove optional quotes around the value
  81. attr[0] = attr[0].replace(/^\s+|\s+$/g, '');
  82. attr[1] = attr[1].replace(/^\s+|\s+$/g, '');
  83. attr[1] = attr[1].replace(/^['"](.*)['"]$/g, '$1');
  84. result[attr[0]] = attr[1];
  85. }
  86. return result;
  87. };
  88. /**
  89. * A line-level M3U8 parser event stream. It expects to receive input one
  90. * line at a time and performs a context-free parse of its contents. A stream
  91. * interpretation of a manifest can be useful if the manifest is expected to
  92. * be too large to fit comfortably into memory or the entirety of the input
  93. * is not immediately available. Otherwise, it's probably much easier to work
  94. * with a regular `Parser` object.
  95. *
  96. * Produces `data` events with an object that captures the parser's
  97. * interpretation of the input. That object has a property `tag` that is one
  98. * of `uri`, `comment`, or `tag`. URIs only have a single additional
  99. * property, `line`, which captures the entirety of the input without
  100. * interpretation. Comments similarly have a single additional property
  101. * `text` which is the input without the leading `#`.
  102. *
  103. * Tags always have a property `tagType` which is the lower-cased version of
  104. * the M3U8 directive without the `#EXT` or `#EXT-X-` prefix. For instance,
  105. * `#EXT-X-MEDIA-SEQUENCE` becomes `media-sequence` when parsed. Unrecognized
  106. * tags are given the tag type `unknown` and a single additional property
  107. * `data` with the remainder of the input.
  108. *
  109. * @class ParseStream
  110. * @extends Stream
  111. */
  112. class ParseStream extends Stream {
  113. constructor() {
  114. super();
  115. this.customParsers = [];
  116. this.tagMappers = [];
  117. }
  118. /**
  119. * Parses an additional line of input.
  120. *
  121. * @param {string} line a single line of an M3U8 file to parse
  122. */
  123. push(line) {
  124. let match;
  125. let event; // strip whitespace
  126. line = line.trim();
  127. if (line.length === 0) {
  128. // ignore empty lines
  129. return;
  130. } // URIs
  131. if (line[0] !== '#') {
  132. this.trigger('data', {
  133. type: 'uri',
  134. uri: line
  135. });
  136. return;
  137. } // map tags
  138. const newLines = this.tagMappers.reduce((acc, mapper) => {
  139. const mappedLine = mapper(line); // skip if unchanged
  140. if (mappedLine === line) {
  141. return acc;
  142. }
  143. return acc.concat([mappedLine]);
  144. }, [line]);
  145. newLines.forEach(newLine => {
  146. for (let i = 0; i < this.customParsers.length; i++) {
  147. if (this.customParsers[i].call(this, newLine)) {
  148. return;
  149. }
  150. } // Comments
  151. if (newLine.indexOf('#EXT') !== 0) {
  152. this.trigger('data', {
  153. type: 'comment',
  154. text: newLine.slice(1)
  155. });
  156. return;
  157. } // strip off any carriage returns here so the regex matching
  158. // doesn't have to account for them.
  159. newLine = newLine.replace('\r', ''); // Tags
  160. match = /^#EXTM3U/.exec(newLine);
  161. if (match) {
  162. this.trigger('data', {
  163. type: 'tag',
  164. tagType: 'm3u'
  165. });
  166. return;
  167. }
  168. match = /^#EXTINF:([0-9\.]*)?,?(.*)?$/.exec(newLine);
  169. if (match) {
  170. event = {
  171. type: 'tag',
  172. tagType: 'inf'
  173. };
  174. if (match[1]) {
  175. event.duration = parseFloat(match[1]);
  176. }
  177. if (match[2]) {
  178. event.title = match[2];
  179. }
  180. this.trigger('data', event);
  181. return;
  182. }
  183. match = /^#EXT-X-TARGETDURATION:([0-9.]*)?/.exec(newLine);
  184. if (match) {
  185. event = {
  186. type: 'tag',
  187. tagType: 'targetduration'
  188. };
  189. if (match[1]) {
  190. event.duration = parseInt(match[1], 10);
  191. }
  192. this.trigger('data', event);
  193. return;
  194. }
  195. match = /^#EXT-X-VERSION:([0-9.]*)?/.exec(newLine);
  196. if (match) {
  197. event = {
  198. type: 'tag',
  199. tagType: 'version'
  200. };
  201. if (match[1]) {
  202. event.version = parseInt(match[1], 10);
  203. }
  204. this.trigger('data', event);
  205. return;
  206. }
  207. match = /^#EXT-X-MEDIA-SEQUENCE:(\-?[0-9.]*)?/.exec(newLine);
  208. if (match) {
  209. event = {
  210. type: 'tag',
  211. tagType: 'media-sequence'
  212. };
  213. if (match[1]) {
  214. event.number = parseInt(match[1], 10);
  215. }
  216. this.trigger('data', event);
  217. return;
  218. }
  219. match = /^#EXT-X-DISCONTINUITY-SEQUENCE:(\-?[0-9.]*)?/.exec(newLine);
  220. if (match) {
  221. event = {
  222. type: 'tag',
  223. tagType: 'discontinuity-sequence'
  224. };
  225. if (match[1]) {
  226. event.number = parseInt(match[1], 10);
  227. }
  228. this.trigger('data', event);
  229. return;
  230. }
  231. match = /^#EXT-X-PLAYLIST-TYPE:(.*)?$/.exec(newLine);
  232. if (match) {
  233. event = {
  234. type: 'tag',
  235. tagType: 'playlist-type'
  236. };
  237. if (match[1]) {
  238. event.playlistType = match[1];
  239. }
  240. this.trigger('data', event);
  241. return;
  242. }
  243. match = /^#EXT-X-BYTERANGE:(.*)?$/.exec(newLine);
  244. if (match) {
  245. event = _extends(parseByterange(match[1]), {
  246. type: 'tag',
  247. tagType: 'byterange'
  248. });
  249. this.trigger('data', event);
  250. return;
  251. }
  252. match = /^#EXT-X-ALLOW-CACHE:(YES|NO)?/.exec(newLine);
  253. if (match) {
  254. event = {
  255. type: 'tag',
  256. tagType: 'allow-cache'
  257. };
  258. if (match[1]) {
  259. event.allowed = !/NO/.test(match[1]);
  260. }
  261. this.trigger('data', event);
  262. return;
  263. }
  264. match = /^#EXT-X-MAP:(.*)$/.exec(newLine);
  265. if (match) {
  266. event = {
  267. type: 'tag',
  268. tagType: 'map'
  269. };
  270. if (match[1]) {
  271. const attributes = parseAttributes(match[1]);
  272. if (attributes.URI) {
  273. event.uri = attributes.URI;
  274. }
  275. if (attributes.BYTERANGE) {
  276. event.byterange = parseByterange(attributes.BYTERANGE);
  277. }
  278. }
  279. this.trigger('data', event);
  280. return;
  281. }
  282. match = /^#EXT-X-STREAM-INF:(.*)$/.exec(newLine);
  283. if (match) {
  284. event = {
  285. type: 'tag',
  286. tagType: 'stream-inf'
  287. };
  288. if (match[1]) {
  289. event.attributes = parseAttributes(match[1]);
  290. if (event.attributes.RESOLUTION) {
  291. const split = event.attributes.RESOLUTION.split('x');
  292. const resolution = {};
  293. if (split[0]) {
  294. resolution.width = parseInt(split[0], 10);
  295. }
  296. if (split[1]) {
  297. resolution.height = parseInt(split[1], 10);
  298. }
  299. event.attributes.RESOLUTION = resolution;
  300. }
  301. if (event.attributes.BANDWIDTH) {
  302. event.attributes.BANDWIDTH = parseInt(event.attributes.BANDWIDTH, 10);
  303. }
  304. if (event.attributes['FRAME-RATE']) {
  305. event.attributes['FRAME-RATE'] = parseFloat(event.attributes['FRAME-RATE']);
  306. }
  307. if (event.attributes['PROGRAM-ID']) {
  308. event.attributes['PROGRAM-ID'] = parseInt(event.attributes['PROGRAM-ID'], 10);
  309. }
  310. }
  311. this.trigger('data', event);
  312. return;
  313. }
  314. match = /^#EXT-X-MEDIA:(.*)$/.exec(newLine);
  315. if (match) {
  316. event = {
  317. type: 'tag',
  318. tagType: 'media'
  319. };
  320. if (match[1]) {
  321. event.attributes = parseAttributes(match[1]);
  322. }
  323. this.trigger('data', event);
  324. return;
  325. }
  326. match = /^#EXT-X-ENDLIST/.exec(newLine);
  327. if (match) {
  328. this.trigger('data', {
  329. type: 'tag',
  330. tagType: 'endlist'
  331. });
  332. return;
  333. }
  334. match = /^#EXT-X-DISCONTINUITY/.exec(newLine);
  335. if (match) {
  336. this.trigger('data', {
  337. type: 'tag',
  338. tagType: 'discontinuity'
  339. });
  340. return;
  341. }
  342. match = /^#EXT-X-PROGRAM-DATE-TIME:(.*)$/.exec(newLine);
  343. if (match) {
  344. event = {
  345. type: 'tag',
  346. tagType: 'program-date-time'
  347. };
  348. if (match[1]) {
  349. event.dateTimeString = match[1];
  350. event.dateTimeObject = new Date(match[1]);
  351. }
  352. this.trigger('data', event);
  353. return;
  354. }
  355. match = /^#EXT-X-KEY:(.*)$/.exec(newLine);
  356. if (match) {
  357. event = {
  358. type: 'tag',
  359. tagType: 'key'
  360. };
  361. if (match[1]) {
  362. event.attributes = parseAttributes(match[1]); // parse the IV string into a Uint32Array
  363. if (event.attributes.IV) {
  364. if (event.attributes.IV.substring(0, 2).toLowerCase() === '0x') {
  365. event.attributes.IV = event.attributes.IV.substring(2);
  366. }
  367. event.attributes.IV = event.attributes.IV.match(/.{8}/g);
  368. event.attributes.IV[0] = parseInt(event.attributes.IV[0], 16);
  369. event.attributes.IV[1] = parseInt(event.attributes.IV[1], 16);
  370. event.attributes.IV[2] = parseInt(event.attributes.IV[2], 16);
  371. event.attributes.IV[3] = parseInt(event.attributes.IV[3], 16);
  372. event.attributes.IV = new Uint32Array(event.attributes.IV);
  373. }
  374. }
  375. this.trigger('data', event);
  376. return;
  377. }
  378. match = /^#EXT-X-START:(.*)$/.exec(newLine);
  379. if (match) {
  380. event = {
  381. type: 'tag',
  382. tagType: 'start'
  383. };
  384. if (match[1]) {
  385. event.attributes = parseAttributes(match[1]);
  386. event.attributes['TIME-OFFSET'] = parseFloat(event.attributes['TIME-OFFSET']);
  387. event.attributes.PRECISE = /YES/.test(event.attributes.PRECISE);
  388. }
  389. this.trigger('data', event);
  390. return;
  391. }
  392. match = /^#EXT-X-CUE-OUT-CONT:(.*)?$/.exec(newLine);
  393. if (match) {
  394. event = {
  395. type: 'tag',
  396. tagType: 'cue-out-cont'
  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. match = /^#EXT-X-CUE-OUT:(.*)?$/.exec(newLine);
  407. if (match) {
  408. event = {
  409. type: 'tag',
  410. tagType: 'cue-out'
  411. };
  412. if (match[1]) {
  413. event.data = match[1];
  414. } else {
  415. event.data = '';
  416. }
  417. this.trigger('data', event);
  418. return;
  419. }
  420. match = /^#EXT-X-CUE-IN:(.*)?$/.exec(newLine);
  421. if (match) {
  422. event = {
  423. type: 'tag',
  424. tagType: 'cue-in'
  425. };
  426. if (match[1]) {
  427. event.data = match[1];
  428. } else {
  429. event.data = '';
  430. }
  431. this.trigger('data', event);
  432. return;
  433. }
  434. match = /^#EXT-X-SKIP:(.*)$/.exec(newLine);
  435. if (match && match[1]) {
  436. event = {
  437. type: 'tag',
  438. tagType: 'skip'
  439. };
  440. event.attributes = parseAttributes(match[1]);
  441. if (event.attributes.hasOwnProperty('SKIPPED-SEGMENTS')) {
  442. event.attributes['SKIPPED-SEGMENTS'] = parseInt(event.attributes['SKIPPED-SEGMENTS'], 10);
  443. }
  444. if (event.attributes.hasOwnProperty('RECENTLY-REMOVED-DATERANGES')) {
  445. event.attributes['RECENTLY-REMOVED-DATERANGES'] = event.attributes['RECENTLY-REMOVED-DATERANGES'].split(TAB);
  446. }
  447. this.trigger('data', event);
  448. return;
  449. }
  450. match = /^#EXT-X-PART:(.*)$/.exec(newLine);
  451. if (match && match[1]) {
  452. event = {
  453. type: 'tag',
  454. tagType: 'part'
  455. };
  456. event.attributes = parseAttributes(match[1]);
  457. ['DURATION'].forEach(function (key) {
  458. if (event.attributes.hasOwnProperty(key)) {
  459. event.attributes[key] = parseFloat(event.attributes[key]);
  460. }
  461. });
  462. ['INDEPENDENT', 'GAP'].forEach(function (key) {
  463. if (event.attributes.hasOwnProperty(key)) {
  464. event.attributes[key] = /YES/.test(event.attributes[key]);
  465. }
  466. });
  467. if (event.attributes.hasOwnProperty('BYTERANGE')) {
  468. event.attributes.byterange = parseByterange(event.attributes.BYTERANGE);
  469. }
  470. this.trigger('data', event);
  471. return;
  472. }
  473. match = /^#EXT-X-SERVER-CONTROL:(.*)$/.exec(newLine);
  474. if (match && match[1]) {
  475. event = {
  476. type: 'tag',
  477. tagType: 'server-control'
  478. };
  479. event.attributes = parseAttributes(match[1]);
  480. ['CAN-SKIP-UNTIL', 'PART-HOLD-BACK', 'HOLD-BACK'].forEach(function (key) {
  481. if (event.attributes.hasOwnProperty(key)) {
  482. event.attributes[key] = parseFloat(event.attributes[key]);
  483. }
  484. });
  485. ['CAN-SKIP-DATERANGES', 'CAN-BLOCK-RELOAD'].forEach(function (key) {
  486. if (event.attributes.hasOwnProperty(key)) {
  487. event.attributes[key] = /YES/.test(event.attributes[key]);
  488. }
  489. });
  490. this.trigger('data', event);
  491. return;
  492. }
  493. match = /^#EXT-X-PART-INF:(.*)$/.exec(newLine);
  494. if (match && match[1]) {
  495. event = {
  496. type: 'tag',
  497. tagType: 'part-inf'
  498. };
  499. event.attributes = parseAttributes(match[1]);
  500. ['PART-TARGET'].forEach(function (key) {
  501. if (event.attributes.hasOwnProperty(key)) {
  502. event.attributes[key] = parseFloat(event.attributes[key]);
  503. }
  504. });
  505. this.trigger('data', event);
  506. return;
  507. }
  508. match = /^#EXT-X-PRELOAD-HINT:(.*)$/.exec(newLine);
  509. if (match && match[1]) {
  510. event = {
  511. type: 'tag',
  512. tagType: 'preload-hint'
  513. };
  514. event.attributes = parseAttributes(match[1]);
  515. ['BYTERANGE-START', 'BYTERANGE-LENGTH'].forEach(function (key) {
  516. if (event.attributes.hasOwnProperty(key)) {
  517. event.attributes[key] = parseInt(event.attributes[key], 10);
  518. const subkey = key === 'BYTERANGE-LENGTH' ? 'length' : 'offset';
  519. event.attributes.byterange = event.attributes.byterange || {};
  520. event.attributes.byterange[subkey] = event.attributes[key]; // only keep the parsed byterange object.
  521. delete event.attributes[key];
  522. }
  523. });
  524. this.trigger('data', event);
  525. return;
  526. }
  527. match = /^#EXT-X-RENDITION-REPORT:(.*)$/.exec(newLine);
  528. if (match && match[1]) {
  529. event = {
  530. type: 'tag',
  531. tagType: 'rendition-report'
  532. };
  533. event.attributes = parseAttributes(match[1]);
  534. ['LAST-MSN', 'LAST-PART'].forEach(function (key) {
  535. if (event.attributes.hasOwnProperty(key)) {
  536. event.attributes[key] = parseInt(event.attributes[key], 10);
  537. }
  538. });
  539. this.trigger('data', event);
  540. return;
  541. } // unknown tag type
  542. this.trigger('data', {
  543. type: 'tag',
  544. data: newLine.slice(4)
  545. });
  546. });
  547. }
  548. /**
  549. * Add a parser for custom headers
  550. *
  551. * @param {Object} options a map of options for the added parser
  552. * @param {RegExp} options.expression a regular expression to match the custom header
  553. * @param {string} options.customType the custom type to register to the output
  554. * @param {Function} [options.dataParser] function to parse the line into an object
  555. * @param {boolean} [options.segment] should tag data be attached to the segment object
  556. */
  557. addParser({
  558. expression,
  559. customType,
  560. dataParser,
  561. segment
  562. }) {
  563. if (typeof dataParser !== 'function') {
  564. dataParser = line => line;
  565. }
  566. this.customParsers.push(line => {
  567. const match = expression.exec(line);
  568. if (match) {
  569. this.trigger('data', {
  570. type: 'custom',
  571. data: dataParser(line),
  572. customType,
  573. segment
  574. });
  575. return true;
  576. }
  577. });
  578. }
  579. /**
  580. * Add a custom header mapper
  581. *
  582. * @param {Object} options
  583. * @param {RegExp} options.expression a regular expression to match the custom header
  584. * @param {Function} options.map function to translate tag into a different tag
  585. */
  586. addTagMapper({
  587. expression,
  588. map
  589. }) {
  590. const mapFn = line => {
  591. if (expression.test(line)) {
  592. return map(line);
  593. }
  594. return line;
  595. };
  596. this.tagMappers.push(mapFn);
  597. }
  598. }
  599. const camelCase = str => str.toLowerCase().replace(/-(\w)/g, a => a[1].toUpperCase());
  600. const camelCaseKeys = function (attributes) {
  601. const result = {};
  602. Object.keys(attributes).forEach(function (key) {
  603. result[camelCase(key)] = attributes[key];
  604. });
  605. return result;
  606. }; // set SERVER-CONTROL hold back based upon targetDuration and partTargetDuration
  607. // we need this helper because defaults are based upon targetDuration and
  608. // partTargetDuration being set, but they may not be if SERVER-CONTROL appears before
  609. // target durations are set.
  610. const setHoldBack = function (manifest) {
  611. const {
  612. serverControl,
  613. targetDuration,
  614. partTargetDuration
  615. } = manifest;
  616. if (!serverControl) {
  617. return;
  618. }
  619. const tag = '#EXT-X-SERVER-CONTROL';
  620. const hb = 'holdBack';
  621. const phb = 'partHoldBack';
  622. const minTargetDuration = targetDuration && targetDuration * 3;
  623. const minPartDuration = partTargetDuration && partTargetDuration * 2;
  624. if (targetDuration && !serverControl.hasOwnProperty(hb)) {
  625. serverControl[hb] = minTargetDuration;
  626. this.trigger('info', {
  627. message: `${tag} defaulting HOLD-BACK to targetDuration * 3 (${minTargetDuration}).`
  628. });
  629. }
  630. if (minTargetDuration && serverControl[hb] < minTargetDuration) {
  631. this.trigger('warn', {
  632. message: `${tag} clamping HOLD-BACK (${serverControl[hb]}) to targetDuration * 3 (${minTargetDuration})`
  633. });
  634. serverControl[hb] = minTargetDuration;
  635. } // default no part hold back to part target duration * 3
  636. if (partTargetDuration && !serverControl.hasOwnProperty(phb)) {
  637. serverControl[phb] = partTargetDuration * 3;
  638. this.trigger('info', {
  639. message: `${tag} defaulting PART-HOLD-BACK to partTargetDuration * 3 (${serverControl[phb]}).`
  640. });
  641. } // if part hold back is too small default it to part target duration * 2
  642. if (partTargetDuration && serverControl[phb] < minPartDuration) {
  643. this.trigger('warn', {
  644. message: `${tag} clamping PART-HOLD-BACK (${serverControl[phb]}) to partTargetDuration * 2 (${minPartDuration}).`
  645. });
  646. serverControl[phb] = minPartDuration;
  647. }
  648. };
  649. /**
  650. * A parser for M3U8 files. The current interpretation of the input is
  651. * exposed as a property `manifest` on parser objects. It's just two lines to
  652. * create and parse a manifest once you have the contents available as a string:
  653. *
  654. * ```js
  655. * var parser = new m3u8.Parser();
  656. * parser.push(xhr.responseText);
  657. * ```
  658. *
  659. * New input can later be applied to update the manifest object by calling
  660. * `push` again.
  661. *
  662. * The parser attempts to create a usable manifest object even if the
  663. * underlying input is somewhat nonsensical. It emits `info` and `warning`
  664. * events during the parse if it encounters input that seems invalid or
  665. * requires some property of the manifest object to be defaulted.
  666. *
  667. * @class Parser
  668. * @extends Stream
  669. */
  670. class Parser extends Stream {
  671. constructor() {
  672. super();
  673. this.lineStream = new LineStream();
  674. this.parseStream = new ParseStream();
  675. this.lineStream.pipe(this.parseStream);
  676. /* eslint-disable consistent-this */
  677. const self = this;
  678. /* eslint-enable consistent-this */
  679. const uris = [];
  680. let currentUri = {}; // if specified, the active EXT-X-MAP definition
  681. let currentMap; // if specified, the active decryption key
  682. let key;
  683. let hasParts = false;
  684. const noop = function () {};
  685. const defaultMediaGroups = {
  686. 'AUDIO': {},
  687. 'VIDEO': {},
  688. 'CLOSED-CAPTIONS': {},
  689. 'SUBTITLES': {}
  690. }; // This is the Widevine UUID from DASH IF IOP. The same exact string is
  691. // used in MPDs with Widevine encrypted streams.
  692. const widevineUuid = 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed'; // group segments into numbered timelines delineated by discontinuities
  693. let currentTimeline = 0; // the manifest is empty until the parse stream begins delivering data
  694. this.manifest = {
  695. allowCache: true,
  696. discontinuityStarts: [],
  697. segments: []
  698. }; // keep track of the last seen segment's byte range end, as segments are not required
  699. // to provide the offset, in which case it defaults to the next byte after the
  700. // previous segment
  701. let lastByterangeEnd = 0; // keep track of the last seen part's byte range end.
  702. let lastPartByterangeEnd = 0;
  703. this.on('end', () => {
  704. // only add preloadSegment if we don't yet have a uri for it.
  705. // and we actually have parts/preloadHints
  706. if (currentUri.uri || !currentUri.parts && !currentUri.preloadHints) {
  707. return;
  708. }
  709. if (!currentUri.map && currentMap) {
  710. currentUri.map = currentMap;
  711. }
  712. if (!currentUri.key && key) {
  713. currentUri.key = key;
  714. }
  715. if (!currentUri.timeline && typeof currentTimeline === 'number') {
  716. currentUri.timeline = currentTimeline;
  717. }
  718. this.manifest.preloadSegment = currentUri;
  719. }); // update the manifest with the m3u8 entry from the parse stream
  720. this.parseStream.on('data', function (entry) {
  721. let mediaGroup;
  722. let rendition;
  723. ({
  724. tag() {
  725. // switch based on the tag type
  726. (({
  727. version() {
  728. if (entry.version) {
  729. this.manifest.version = entry.version;
  730. }
  731. },
  732. 'allow-cache'() {
  733. this.manifest.allowCache = entry.allowed;
  734. if (!('allowed' in entry)) {
  735. this.trigger('info', {
  736. message: 'defaulting allowCache to YES'
  737. });
  738. this.manifest.allowCache = true;
  739. }
  740. },
  741. byterange() {
  742. const byterange = {};
  743. if ('length' in entry) {
  744. currentUri.byterange = byterange;
  745. byterange.length = entry.length;
  746. if (!('offset' in entry)) {
  747. /*
  748. * From the latest spec (as of this writing):
  749. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.2
  750. *
  751. * Same text since EXT-X-BYTERANGE's introduction in draft 7:
  752. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.1)
  753. *
  754. * "If o [offset] is not present, the sub-range begins at the next byte
  755. * following the sub-range of the previous media segment."
  756. */
  757. entry.offset = lastByterangeEnd;
  758. }
  759. }
  760. if ('offset' in entry) {
  761. currentUri.byterange = byterange;
  762. byterange.offset = entry.offset;
  763. }
  764. lastByterangeEnd = byterange.offset + byterange.length;
  765. },
  766. endlist() {
  767. this.manifest.endList = true;
  768. },
  769. inf() {
  770. if (!('mediaSequence' in this.manifest)) {
  771. this.manifest.mediaSequence = 0;
  772. this.trigger('info', {
  773. message: 'defaulting media sequence to zero'
  774. });
  775. }
  776. if (!('discontinuitySequence' in this.manifest)) {
  777. this.manifest.discontinuitySequence = 0;
  778. this.trigger('info', {
  779. message: 'defaulting discontinuity sequence to zero'
  780. });
  781. }
  782. if (entry.duration > 0) {
  783. currentUri.duration = entry.duration;
  784. }
  785. if (entry.duration === 0) {
  786. currentUri.duration = 0.01;
  787. this.trigger('info', {
  788. message: 'updating zero segment duration to a small value'
  789. });
  790. }
  791. this.manifest.segments = uris;
  792. },
  793. key() {
  794. if (!entry.attributes) {
  795. this.trigger('warn', {
  796. message: 'ignoring key declaration without attribute list'
  797. });
  798. return;
  799. } // clear the active encryption key
  800. if (entry.attributes.METHOD === 'NONE') {
  801. key = null;
  802. return;
  803. }
  804. if (!entry.attributes.URI) {
  805. this.trigger('warn', {
  806. message: 'ignoring key declaration without URI'
  807. });
  808. return;
  809. }
  810. if (entry.attributes.KEYFORMAT === 'com.apple.streamingkeydelivery') {
  811. this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
  812. this.manifest.contentProtection['com.apple.fps.1_0'] = {
  813. attributes: entry.attributes
  814. };
  815. return;
  816. }
  817. if (entry.attributes.KEYFORMAT === 'com.microsoft.playready') {
  818. this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
  819. this.manifest.contentProtection['com.microsoft.playready'] = {
  820. uri: entry.attributes.URI
  821. };
  822. return;
  823. } // check if the content is encrypted for Widevine
  824. // Widevine/HLS spec: https://storage.googleapis.com/wvdocs/Widevine_DRM_HLS.pdf
  825. if (entry.attributes.KEYFORMAT === widevineUuid) {
  826. const VALID_METHODS = ['SAMPLE-AES', 'SAMPLE-AES-CTR', 'SAMPLE-AES-CENC'];
  827. if (VALID_METHODS.indexOf(entry.attributes.METHOD) === -1) {
  828. this.trigger('warn', {
  829. message: 'invalid key method provided for Widevine'
  830. });
  831. return;
  832. }
  833. if (entry.attributes.METHOD === 'SAMPLE-AES-CENC') {
  834. this.trigger('warn', {
  835. message: 'SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead'
  836. });
  837. }
  838. if (entry.attributes.URI.substring(0, 23) !== 'data:text/plain;base64,') {
  839. this.trigger('warn', {
  840. message: 'invalid key URI provided for Widevine'
  841. });
  842. return;
  843. }
  844. if (!(entry.attributes.KEYID && entry.attributes.KEYID.substring(0, 2) === '0x')) {
  845. this.trigger('warn', {
  846. message: 'invalid key ID provided for Widevine'
  847. });
  848. return;
  849. } // if Widevine key attributes are valid, store them as `contentProtection`
  850. // on the manifest to emulate Widevine tag structure in a DASH mpd
  851. this.manifest.contentProtection = this.manifest.contentProtection || {};
  852. this.manifest.contentProtection['com.widevine.alpha'] = {
  853. attributes: {
  854. schemeIdUri: entry.attributes.KEYFORMAT,
  855. // remove '0x' from the key id string
  856. keyId: entry.attributes.KEYID.substring(2)
  857. },
  858. // decode the base64-encoded PSSH box
  859. pssh: decodeB64ToUint8Array(entry.attributes.URI.split(',')[1])
  860. };
  861. return;
  862. }
  863. if (!entry.attributes.METHOD) {
  864. this.trigger('warn', {
  865. message: 'defaulting key method to AES-128'
  866. });
  867. } // setup an encryption key for upcoming segments
  868. key = {
  869. method: entry.attributes.METHOD || 'AES-128',
  870. uri: entry.attributes.URI
  871. };
  872. if (typeof entry.attributes.IV !== 'undefined') {
  873. key.iv = entry.attributes.IV;
  874. }
  875. },
  876. 'media-sequence'() {
  877. if (!isFinite(entry.number)) {
  878. this.trigger('warn', {
  879. message: 'ignoring invalid media sequence: ' + entry.number
  880. });
  881. return;
  882. }
  883. this.manifest.mediaSequence = entry.number;
  884. },
  885. 'discontinuity-sequence'() {
  886. if (!isFinite(entry.number)) {
  887. this.trigger('warn', {
  888. message: 'ignoring invalid discontinuity sequence: ' + entry.number
  889. });
  890. return;
  891. }
  892. this.manifest.discontinuitySequence = entry.number;
  893. currentTimeline = entry.number;
  894. },
  895. 'playlist-type'() {
  896. if (!/VOD|EVENT/.test(entry.playlistType)) {
  897. this.trigger('warn', {
  898. message: 'ignoring unknown playlist type: ' + entry.playlist
  899. });
  900. return;
  901. }
  902. this.manifest.playlistType = entry.playlistType;
  903. },
  904. map() {
  905. currentMap = {};
  906. if (entry.uri) {
  907. currentMap.uri = entry.uri;
  908. }
  909. if (entry.byterange) {
  910. currentMap.byterange = entry.byterange;
  911. }
  912. if (key) {
  913. currentMap.key = key;
  914. }
  915. },
  916. 'stream-inf'() {
  917. this.manifest.playlists = uris;
  918. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  919. if (!entry.attributes) {
  920. this.trigger('warn', {
  921. message: 'ignoring empty stream-inf attributes'
  922. });
  923. return;
  924. }
  925. if (!currentUri.attributes) {
  926. currentUri.attributes = {};
  927. }
  928. _extends(currentUri.attributes, entry.attributes);
  929. },
  930. media() {
  931. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  932. if (!(entry.attributes && entry.attributes.TYPE && entry.attributes['GROUP-ID'] && entry.attributes.NAME)) {
  933. this.trigger('warn', {
  934. message: 'ignoring incomplete or missing media group'
  935. });
  936. return;
  937. } // find the media group, creating defaults as necessary
  938. const mediaGroupType = this.manifest.mediaGroups[entry.attributes.TYPE];
  939. mediaGroupType[entry.attributes['GROUP-ID']] = mediaGroupType[entry.attributes['GROUP-ID']] || {};
  940. mediaGroup = mediaGroupType[entry.attributes['GROUP-ID']]; // collect the rendition metadata
  941. rendition = {
  942. default: /yes/i.test(entry.attributes.DEFAULT)
  943. };
  944. if (rendition.default) {
  945. rendition.autoselect = true;
  946. } else {
  947. rendition.autoselect = /yes/i.test(entry.attributes.AUTOSELECT);
  948. }
  949. if (entry.attributes.LANGUAGE) {
  950. rendition.language = entry.attributes.LANGUAGE;
  951. }
  952. if (entry.attributes.URI) {
  953. rendition.uri = entry.attributes.URI;
  954. }
  955. if (entry.attributes['INSTREAM-ID']) {
  956. rendition.instreamId = entry.attributes['INSTREAM-ID'];
  957. }
  958. if (entry.attributes.CHARACTERISTICS) {
  959. rendition.characteristics = entry.attributes.CHARACTERISTICS;
  960. }
  961. if (entry.attributes.FORCED) {
  962. rendition.forced = /yes/i.test(entry.attributes.FORCED);
  963. } // insert the new rendition
  964. mediaGroup[entry.attributes.NAME] = rendition;
  965. },
  966. discontinuity() {
  967. currentTimeline += 1;
  968. currentUri.discontinuity = true;
  969. this.manifest.discontinuityStarts.push(uris.length);
  970. },
  971. 'program-date-time'() {
  972. if (typeof this.manifest.dateTimeString === 'undefined') {
  973. // PROGRAM-DATE-TIME is a media-segment tag, but for backwards
  974. // compatibility, we add the first occurence of the PROGRAM-DATE-TIME tag
  975. // to the manifest object
  976. // TODO: Consider removing this in future major version
  977. this.manifest.dateTimeString = entry.dateTimeString;
  978. this.manifest.dateTimeObject = entry.dateTimeObject;
  979. }
  980. currentUri.dateTimeString = entry.dateTimeString;
  981. currentUri.dateTimeObject = entry.dateTimeObject;
  982. },
  983. targetduration() {
  984. if (!isFinite(entry.duration) || entry.duration < 0) {
  985. this.trigger('warn', {
  986. message: 'ignoring invalid target duration: ' + entry.duration
  987. });
  988. return;
  989. }
  990. this.manifest.targetDuration = entry.duration;
  991. setHoldBack.call(this, this.manifest);
  992. },
  993. start() {
  994. if (!entry.attributes || isNaN(entry.attributes['TIME-OFFSET'])) {
  995. this.trigger('warn', {
  996. message: 'ignoring start declaration without appropriate attribute list'
  997. });
  998. return;
  999. }
  1000. this.manifest.start = {
  1001. timeOffset: entry.attributes['TIME-OFFSET'],
  1002. precise: entry.attributes.PRECISE
  1003. };
  1004. },
  1005. 'cue-out'() {
  1006. currentUri.cueOut = entry.data;
  1007. },
  1008. 'cue-out-cont'() {
  1009. currentUri.cueOutCont = entry.data;
  1010. },
  1011. 'cue-in'() {
  1012. currentUri.cueIn = entry.data;
  1013. },
  1014. 'skip'() {
  1015. this.manifest.skip = camelCaseKeys(entry.attributes);
  1016. this.warnOnMissingAttributes_('#EXT-X-SKIP', entry.attributes, ['SKIPPED-SEGMENTS']);
  1017. },
  1018. 'part'() {
  1019. hasParts = true; // parts are always specifed before a segment
  1020. const segmentIndex = this.manifest.segments.length;
  1021. const part = camelCaseKeys(entry.attributes);
  1022. currentUri.parts = currentUri.parts || [];
  1023. currentUri.parts.push(part);
  1024. if (part.byterange) {
  1025. if (!part.byterange.hasOwnProperty('offset')) {
  1026. part.byterange.offset = lastPartByterangeEnd;
  1027. }
  1028. lastPartByterangeEnd = part.byterange.offset + part.byterange.length;
  1029. }
  1030. const partIndex = currentUri.parts.length - 1;
  1031. this.warnOnMissingAttributes_(`#EXT-X-PART #${partIndex} for segment #${segmentIndex}`, entry.attributes, ['URI', 'DURATION']);
  1032. if (this.manifest.renditionReports) {
  1033. this.manifest.renditionReports.forEach((r, i) => {
  1034. if (!r.hasOwnProperty('lastPart')) {
  1035. this.trigger('warn', {
  1036. message: `#EXT-X-RENDITION-REPORT #${i} lacks required attribute(s): LAST-PART`
  1037. });
  1038. }
  1039. });
  1040. }
  1041. },
  1042. 'server-control'() {
  1043. const attrs = this.manifest.serverControl = camelCaseKeys(entry.attributes);
  1044. if (!attrs.hasOwnProperty('canBlockReload')) {
  1045. attrs.canBlockReload = false;
  1046. this.trigger('info', {
  1047. message: '#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false'
  1048. });
  1049. }
  1050. setHoldBack.call(this, this.manifest);
  1051. if (attrs.canSkipDateranges && !attrs.hasOwnProperty('canSkipUntil')) {
  1052. this.trigger('warn', {
  1053. message: '#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set'
  1054. });
  1055. }
  1056. },
  1057. 'preload-hint'() {
  1058. // parts are always specifed before a segment
  1059. const segmentIndex = this.manifest.segments.length;
  1060. const hint = camelCaseKeys(entry.attributes);
  1061. const isPart = hint.type && hint.type === 'PART';
  1062. currentUri.preloadHints = currentUri.preloadHints || [];
  1063. currentUri.preloadHints.push(hint);
  1064. if (hint.byterange) {
  1065. if (!hint.byterange.hasOwnProperty('offset')) {
  1066. // use last part byterange end or zero if not a part.
  1067. hint.byterange.offset = isPart ? lastPartByterangeEnd : 0;
  1068. if (isPart) {
  1069. lastPartByterangeEnd = hint.byterange.offset + hint.byterange.length;
  1070. }
  1071. }
  1072. }
  1073. const index = currentUri.preloadHints.length - 1;
  1074. this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${index} for segment #${segmentIndex}`, entry.attributes, ['TYPE', 'URI']);
  1075. if (!hint.type) {
  1076. return;
  1077. } // search through all preload hints except for the current one for
  1078. // a duplicate type.
  1079. for (let i = 0; i < currentUri.preloadHints.length - 1; i++) {
  1080. const otherHint = currentUri.preloadHints[i];
  1081. if (!otherHint.type) {
  1082. continue;
  1083. }
  1084. if (otherHint.type === hint.type) {
  1085. this.trigger('warn', {
  1086. message: `#EXT-X-PRELOAD-HINT #${index} for segment #${segmentIndex} has the same TYPE ${hint.type} as preload hint #${i}`
  1087. });
  1088. }
  1089. }
  1090. },
  1091. 'rendition-report'() {
  1092. const report = camelCaseKeys(entry.attributes);
  1093. this.manifest.renditionReports = this.manifest.renditionReports || [];
  1094. this.manifest.renditionReports.push(report);
  1095. const index = this.manifest.renditionReports.length - 1;
  1096. const required = ['LAST-MSN', 'URI'];
  1097. if (hasParts) {
  1098. required.push('LAST-PART');
  1099. }
  1100. this.warnOnMissingAttributes_(`#EXT-X-RENDITION-REPORT #${index}`, entry.attributes, required);
  1101. },
  1102. 'part-inf'() {
  1103. this.manifest.partInf = camelCaseKeys(entry.attributes);
  1104. this.warnOnMissingAttributes_('#EXT-X-PART-INF', entry.attributes, ['PART-TARGET']);
  1105. if (this.manifest.partInf.partTarget) {
  1106. this.manifest.partTargetDuration = this.manifest.partInf.partTarget;
  1107. }
  1108. setHoldBack.call(this, this.manifest);
  1109. }
  1110. })[entry.tagType] || noop).call(self);
  1111. },
  1112. uri() {
  1113. currentUri.uri = entry.uri;
  1114. uris.push(currentUri); // if no explicit duration was declared, use the target duration
  1115. if (this.manifest.targetDuration && !('duration' in currentUri)) {
  1116. this.trigger('warn', {
  1117. message: 'defaulting segment duration to the target duration'
  1118. });
  1119. currentUri.duration = this.manifest.targetDuration;
  1120. } // annotate with encryption information, if necessary
  1121. if (key) {
  1122. currentUri.key = key;
  1123. }
  1124. currentUri.timeline = currentTimeline; // annotate with initialization segment information, if necessary
  1125. if (currentMap) {
  1126. currentUri.map = currentMap;
  1127. } // reset the last byterange end as it needs to be 0 between parts
  1128. lastPartByterangeEnd = 0; // prepare for the next URI
  1129. currentUri = {};
  1130. },
  1131. comment() {// comments are not important for playback
  1132. },
  1133. custom() {
  1134. // if this is segment-level data attach the output to the segment
  1135. if (entry.segment) {
  1136. currentUri.custom = currentUri.custom || {};
  1137. currentUri.custom[entry.customType] = entry.data; // if this is manifest-level data attach to the top level manifest object
  1138. } else {
  1139. this.manifest.custom = this.manifest.custom || {};
  1140. this.manifest.custom[entry.customType] = entry.data;
  1141. }
  1142. }
  1143. })[entry.type].call(self);
  1144. });
  1145. }
  1146. warnOnMissingAttributes_(identifier, attributes, required) {
  1147. const missing = [];
  1148. required.forEach(function (key) {
  1149. if (!attributes.hasOwnProperty(key)) {
  1150. missing.push(key);
  1151. }
  1152. });
  1153. if (missing.length) {
  1154. this.trigger('warn', {
  1155. message: `${identifier} lacks required attribute(s): ${missing.join(', ')}`
  1156. });
  1157. }
  1158. }
  1159. /**
  1160. * Parse the input string and update the manifest object.
  1161. *
  1162. * @param {string} chunk a potentially incomplete portion of the manifest
  1163. */
  1164. push(chunk) {
  1165. this.lineStream.push(chunk);
  1166. }
  1167. /**
  1168. * Flush any remaining input. This can be handy if the last line of an M3U8
  1169. * manifest did not contain a trailing newline but the file has been
  1170. * completely received.
  1171. */
  1172. end() {
  1173. // flush any buffered input
  1174. this.lineStream.push('\n');
  1175. this.trigger('end');
  1176. }
  1177. /**
  1178. * Add an additional parser for non-standard tags
  1179. *
  1180. * @param {Object} options a map of options for the added parser
  1181. * @param {RegExp} options.expression a regular expression to match the custom header
  1182. * @param {string} options.type the type to register to the output
  1183. * @param {Function} [options.dataParser] function to parse the line into an object
  1184. * @param {boolean} [options.segment] should tag data be attached to the segment object
  1185. */
  1186. addParser(options) {
  1187. this.parseStream.addParser(options);
  1188. }
  1189. /**
  1190. * Add a custom header mapper
  1191. *
  1192. * @param {Object} options
  1193. * @param {RegExp} options.expression a regular expression to match the custom header
  1194. * @param {Function} options.map function to translate tag into a different tag
  1195. */
  1196. addTagMapper(options) {
  1197. this.parseStream.addTagMapper(options);
  1198. }
  1199. }
  1200. export { LineStream, ParseStream, Parser };