m3u8-parser.es.js 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684
  1. /*! @name m3u8-parser @version 7.1.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. }
  542. match = /^#EXT-X-DATERANGE:(.*)$/.exec(newLine);
  543. if (match && match[1]) {
  544. event = {
  545. type: 'tag',
  546. tagType: 'daterange'
  547. };
  548. event.attributes = parseAttributes(match[1]);
  549. ['ID', 'CLASS'].forEach(function (key) {
  550. if (event.attributes.hasOwnProperty(key)) {
  551. event.attributes[key] = String(event.attributes[key]);
  552. }
  553. });
  554. ['START-DATE', 'END-DATE'].forEach(function (key) {
  555. if (event.attributes.hasOwnProperty(key)) {
  556. event.attributes[key] = new Date(event.attributes[key]);
  557. }
  558. });
  559. ['DURATION', 'PLANNED-DURATION'].forEach(function (key) {
  560. if (event.attributes.hasOwnProperty(key)) {
  561. event.attributes[key] = parseFloat(event.attributes[key]);
  562. }
  563. });
  564. ['END-ON-NEXT'].forEach(function (key) {
  565. if (event.attributes.hasOwnProperty(key)) {
  566. event.attributes[key] = /YES/i.test(event.attributes[key]);
  567. }
  568. });
  569. ['SCTE35-CMD', ' SCTE35-OUT', 'SCTE35-IN'].forEach(function (key) {
  570. if (event.attributes.hasOwnProperty(key)) {
  571. event.attributes[key] = event.attributes[key].toString(16);
  572. }
  573. });
  574. const clientAttributePattern = /^X-([A-Z]+-)+[A-Z]+$/;
  575. for (const key in event.attributes) {
  576. if (!clientAttributePattern.test(key)) {
  577. continue;
  578. }
  579. const isHexaDecimal = /[0-9A-Fa-f]{6}/g.test(event.attributes[key]);
  580. const isDecimalFloating = /^\d+(\.\d+)?$/.test(event.attributes[key]);
  581. event.attributes[key] = isHexaDecimal ? event.attributes[key].toString(16) : isDecimalFloating ? parseFloat(event.attributes[key]) : String(event.attributes[key]);
  582. }
  583. this.trigger('data', event);
  584. return;
  585. }
  586. match = /^#EXT-X-INDEPENDENT-SEGMENTS/.exec(newLine);
  587. if (match) {
  588. this.trigger('data', {
  589. type: 'tag',
  590. tagType: 'independent-segments'
  591. });
  592. return;
  593. }
  594. match = /^#EXT-X-CONTENT-STEERING:(.*)$/.exec(newLine);
  595. if (match) {
  596. event = {
  597. type: 'tag',
  598. tagType: 'content-steering'
  599. };
  600. event.attributes = parseAttributes(match[1]);
  601. this.trigger('data', event);
  602. return;
  603. } // unknown tag type
  604. this.trigger('data', {
  605. type: 'tag',
  606. data: newLine.slice(4)
  607. });
  608. });
  609. }
  610. /**
  611. * Add a parser for custom headers
  612. *
  613. * @param {Object} options a map of options for the added parser
  614. * @param {RegExp} options.expression a regular expression to match the custom header
  615. * @param {string} options.customType the custom type to register to the output
  616. * @param {Function} [options.dataParser] function to parse the line into an object
  617. * @param {boolean} [options.segment] should tag data be attached to the segment object
  618. */
  619. addParser({
  620. expression,
  621. customType,
  622. dataParser,
  623. segment
  624. }) {
  625. if (typeof dataParser !== 'function') {
  626. dataParser = line => line;
  627. }
  628. this.customParsers.push(line => {
  629. const match = expression.exec(line);
  630. if (match) {
  631. this.trigger('data', {
  632. type: 'custom',
  633. data: dataParser(line),
  634. customType,
  635. segment
  636. });
  637. return true;
  638. }
  639. });
  640. }
  641. /**
  642. * Add a custom header mapper
  643. *
  644. * @param {Object} options
  645. * @param {RegExp} options.expression a regular expression to match the custom header
  646. * @param {Function} options.map function to translate tag into a different tag
  647. */
  648. addTagMapper({
  649. expression,
  650. map
  651. }) {
  652. const mapFn = line => {
  653. if (expression.test(line)) {
  654. return map(line);
  655. }
  656. return line;
  657. };
  658. this.tagMappers.push(mapFn);
  659. }
  660. }
  661. const camelCase = str => str.toLowerCase().replace(/-(\w)/g, a => a[1].toUpperCase());
  662. const camelCaseKeys = function (attributes) {
  663. const result = {};
  664. Object.keys(attributes).forEach(function (key) {
  665. result[camelCase(key)] = attributes[key];
  666. });
  667. return result;
  668. }; // set SERVER-CONTROL hold back based upon targetDuration and partTargetDuration
  669. // we need this helper because defaults are based upon targetDuration and
  670. // partTargetDuration being set, but they may not be if SERVER-CONTROL appears before
  671. // target durations are set.
  672. const setHoldBack = function (manifest) {
  673. const {
  674. serverControl,
  675. targetDuration,
  676. partTargetDuration
  677. } = manifest;
  678. if (!serverControl) {
  679. return;
  680. }
  681. const tag = '#EXT-X-SERVER-CONTROL';
  682. const hb = 'holdBack';
  683. const phb = 'partHoldBack';
  684. const minTargetDuration = targetDuration && targetDuration * 3;
  685. const minPartDuration = partTargetDuration && partTargetDuration * 2;
  686. if (targetDuration && !serverControl.hasOwnProperty(hb)) {
  687. serverControl[hb] = minTargetDuration;
  688. this.trigger('info', {
  689. message: `${tag} defaulting HOLD-BACK to targetDuration * 3 (${minTargetDuration}).`
  690. });
  691. }
  692. if (minTargetDuration && serverControl[hb] < minTargetDuration) {
  693. this.trigger('warn', {
  694. message: `${tag} clamping HOLD-BACK (${serverControl[hb]}) to targetDuration * 3 (${minTargetDuration})`
  695. });
  696. serverControl[hb] = minTargetDuration;
  697. } // default no part hold back to part target duration * 3
  698. if (partTargetDuration && !serverControl.hasOwnProperty(phb)) {
  699. serverControl[phb] = partTargetDuration * 3;
  700. this.trigger('info', {
  701. message: `${tag} defaulting PART-HOLD-BACK to partTargetDuration * 3 (${serverControl[phb]}).`
  702. });
  703. } // if part hold back is too small default it to part target duration * 2
  704. if (partTargetDuration && serverControl[phb] < minPartDuration) {
  705. this.trigger('warn', {
  706. message: `${tag} clamping PART-HOLD-BACK (${serverControl[phb]}) to partTargetDuration * 2 (${minPartDuration}).`
  707. });
  708. serverControl[phb] = minPartDuration;
  709. }
  710. };
  711. /**
  712. * A parser for M3U8 files. The current interpretation of the input is
  713. * exposed as a property `manifest` on parser objects. It's just two lines to
  714. * create and parse a manifest once you have the contents available as a string:
  715. *
  716. * ```js
  717. * var parser = new m3u8.Parser();
  718. * parser.push(xhr.responseText);
  719. * ```
  720. *
  721. * New input can later be applied to update the manifest object by calling
  722. * `push` again.
  723. *
  724. * The parser attempts to create a usable manifest object even if the
  725. * underlying input is somewhat nonsensical. It emits `info` and `warning`
  726. * events during the parse if it encounters input that seems invalid or
  727. * requires some property of the manifest object to be defaulted.
  728. *
  729. * @class Parser
  730. * @extends Stream
  731. */
  732. class Parser extends Stream {
  733. constructor() {
  734. super();
  735. this.lineStream = new LineStream();
  736. this.parseStream = new ParseStream();
  737. this.lineStream.pipe(this.parseStream);
  738. this.lastProgramDateTime = null;
  739. /* eslint-disable consistent-this */
  740. const self = this;
  741. /* eslint-enable consistent-this */
  742. const uris = [];
  743. let currentUri = {}; // if specified, the active EXT-X-MAP definition
  744. let currentMap; // if specified, the active decryption key
  745. let key;
  746. let hasParts = false;
  747. const noop = function () {};
  748. const defaultMediaGroups = {
  749. 'AUDIO': {},
  750. 'VIDEO': {},
  751. 'CLOSED-CAPTIONS': {},
  752. 'SUBTITLES': {}
  753. }; // This is the Widevine UUID from DASH IF IOP. The same exact string is
  754. // used in MPDs with Widevine encrypted streams.
  755. const widevineUuid = 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed'; // group segments into numbered timelines delineated by discontinuities
  756. let currentTimeline = 0; // the manifest is empty until the parse stream begins delivering data
  757. this.manifest = {
  758. allowCache: true,
  759. discontinuityStarts: [],
  760. dateRanges: [],
  761. segments: []
  762. }; // keep track of the last seen segment's byte range end, as segments are not required
  763. // to provide the offset, in which case it defaults to the next byte after the
  764. // previous segment
  765. let lastByterangeEnd = 0; // keep track of the last seen part's byte range end.
  766. let lastPartByterangeEnd = 0;
  767. const dateRangeTags = {};
  768. this.on('end', () => {
  769. // only add preloadSegment if we don't yet have a uri for it.
  770. // and we actually have parts/preloadHints
  771. if (currentUri.uri || !currentUri.parts && !currentUri.preloadHints) {
  772. return;
  773. }
  774. if (!currentUri.map && currentMap) {
  775. currentUri.map = currentMap;
  776. }
  777. if (!currentUri.key && key) {
  778. currentUri.key = key;
  779. }
  780. if (!currentUri.timeline && typeof currentTimeline === 'number') {
  781. currentUri.timeline = currentTimeline;
  782. }
  783. this.manifest.preloadSegment = currentUri;
  784. }); // update the manifest with the m3u8 entry from the parse stream
  785. this.parseStream.on('data', function (entry) {
  786. let mediaGroup;
  787. let rendition;
  788. ({
  789. tag() {
  790. // switch based on the tag type
  791. (({
  792. version() {
  793. if (entry.version) {
  794. this.manifest.version = entry.version;
  795. }
  796. },
  797. 'allow-cache'() {
  798. this.manifest.allowCache = entry.allowed;
  799. if (!('allowed' in entry)) {
  800. this.trigger('info', {
  801. message: 'defaulting allowCache to YES'
  802. });
  803. this.manifest.allowCache = true;
  804. }
  805. },
  806. byterange() {
  807. const byterange = {};
  808. if ('length' in entry) {
  809. currentUri.byterange = byterange;
  810. byterange.length = entry.length;
  811. if (!('offset' in entry)) {
  812. /*
  813. * From the latest spec (as of this writing):
  814. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.2
  815. *
  816. * Same text since EXT-X-BYTERANGE's introduction in draft 7:
  817. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.1)
  818. *
  819. * "If o [offset] is not present, the sub-range begins at the next byte
  820. * following the sub-range of the previous media segment."
  821. */
  822. entry.offset = lastByterangeEnd;
  823. }
  824. }
  825. if ('offset' in entry) {
  826. currentUri.byterange = byterange;
  827. byterange.offset = entry.offset;
  828. }
  829. lastByterangeEnd = byterange.offset + byterange.length;
  830. },
  831. endlist() {
  832. this.manifest.endList = true;
  833. },
  834. inf() {
  835. if (!('mediaSequence' in this.manifest)) {
  836. this.manifest.mediaSequence = 0;
  837. this.trigger('info', {
  838. message: 'defaulting media sequence to zero'
  839. });
  840. }
  841. if (!('discontinuitySequence' in this.manifest)) {
  842. this.manifest.discontinuitySequence = 0;
  843. this.trigger('info', {
  844. message: 'defaulting discontinuity sequence to zero'
  845. });
  846. }
  847. if (entry.title) {
  848. currentUri.title = entry.title;
  849. }
  850. if (entry.duration > 0) {
  851. currentUri.duration = entry.duration;
  852. }
  853. if (entry.duration === 0) {
  854. currentUri.duration = 0.01;
  855. this.trigger('info', {
  856. message: 'updating zero segment duration to a small value'
  857. });
  858. }
  859. this.manifest.segments = uris;
  860. },
  861. key() {
  862. if (!entry.attributes) {
  863. this.trigger('warn', {
  864. message: 'ignoring key declaration without attribute list'
  865. });
  866. return;
  867. } // clear the active encryption key
  868. if (entry.attributes.METHOD === 'NONE') {
  869. key = null;
  870. return;
  871. }
  872. if (!entry.attributes.URI) {
  873. this.trigger('warn', {
  874. message: 'ignoring key declaration without URI'
  875. });
  876. return;
  877. }
  878. if (entry.attributes.KEYFORMAT === 'com.apple.streamingkeydelivery') {
  879. this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
  880. this.manifest.contentProtection['com.apple.fps.1_0'] = {
  881. attributes: entry.attributes
  882. };
  883. return;
  884. }
  885. if (entry.attributes.KEYFORMAT === 'com.microsoft.playready') {
  886. this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
  887. this.manifest.contentProtection['com.microsoft.playready'] = {
  888. uri: entry.attributes.URI
  889. };
  890. return;
  891. } // check if the content is encrypted for Widevine
  892. // Widevine/HLS spec: https://storage.googleapis.com/wvdocs/Widevine_DRM_HLS.pdf
  893. if (entry.attributes.KEYFORMAT === widevineUuid) {
  894. const VALID_METHODS = ['SAMPLE-AES', 'SAMPLE-AES-CTR', 'SAMPLE-AES-CENC'];
  895. if (VALID_METHODS.indexOf(entry.attributes.METHOD) === -1) {
  896. this.trigger('warn', {
  897. message: 'invalid key method provided for Widevine'
  898. });
  899. return;
  900. }
  901. if (entry.attributes.METHOD === 'SAMPLE-AES-CENC') {
  902. this.trigger('warn', {
  903. message: 'SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead'
  904. });
  905. }
  906. if (entry.attributes.URI.substring(0, 23) !== 'data:text/plain;base64,') {
  907. this.trigger('warn', {
  908. message: 'invalid key URI provided for Widevine'
  909. });
  910. return;
  911. }
  912. if (!(entry.attributes.KEYID && entry.attributes.KEYID.substring(0, 2) === '0x')) {
  913. this.trigger('warn', {
  914. message: 'invalid key ID provided for Widevine'
  915. });
  916. return;
  917. } // if Widevine key attributes are valid, store them as `contentProtection`
  918. // on the manifest to emulate Widevine tag structure in a DASH mpd
  919. this.manifest.contentProtection = this.manifest.contentProtection || {};
  920. this.manifest.contentProtection['com.widevine.alpha'] = {
  921. attributes: {
  922. schemeIdUri: entry.attributes.KEYFORMAT,
  923. // remove '0x' from the key id string
  924. keyId: entry.attributes.KEYID.substring(2)
  925. },
  926. // decode the base64-encoded PSSH box
  927. pssh: decodeB64ToUint8Array(entry.attributes.URI.split(',')[1])
  928. };
  929. return;
  930. }
  931. if (!entry.attributes.METHOD) {
  932. this.trigger('warn', {
  933. message: 'defaulting key method to AES-128'
  934. });
  935. } // setup an encryption key for upcoming segments
  936. key = {
  937. method: entry.attributes.METHOD || 'AES-128',
  938. uri: entry.attributes.URI
  939. };
  940. if (typeof entry.attributes.IV !== 'undefined') {
  941. key.iv = entry.attributes.IV;
  942. }
  943. },
  944. 'media-sequence'() {
  945. if (!isFinite(entry.number)) {
  946. this.trigger('warn', {
  947. message: 'ignoring invalid media sequence: ' + entry.number
  948. });
  949. return;
  950. }
  951. this.manifest.mediaSequence = entry.number;
  952. },
  953. 'discontinuity-sequence'() {
  954. if (!isFinite(entry.number)) {
  955. this.trigger('warn', {
  956. message: 'ignoring invalid discontinuity sequence: ' + entry.number
  957. });
  958. return;
  959. }
  960. this.manifest.discontinuitySequence = entry.number;
  961. currentTimeline = entry.number;
  962. },
  963. 'playlist-type'() {
  964. if (!/VOD|EVENT/.test(entry.playlistType)) {
  965. this.trigger('warn', {
  966. message: 'ignoring unknown playlist type: ' + entry.playlist
  967. });
  968. return;
  969. }
  970. this.manifest.playlistType = entry.playlistType;
  971. },
  972. map() {
  973. currentMap = {};
  974. if (entry.uri) {
  975. currentMap.uri = entry.uri;
  976. }
  977. if (entry.byterange) {
  978. currentMap.byterange = entry.byterange;
  979. }
  980. if (key) {
  981. currentMap.key = key;
  982. }
  983. },
  984. 'stream-inf'() {
  985. this.manifest.playlists = uris;
  986. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  987. if (!entry.attributes) {
  988. this.trigger('warn', {
  989. message: 'ignoring empty stream-inf attributes'
  990. });
  991. return;
  992. }
  993. if (!currentUri.attributes) {
  994. currentUri.attributes = {};
  995. }
  996. _extends(currentUri.attributes, entry.attributes);
  997. },
  998. media() {
  999. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  1000. if (!(entry.attributes && entry.attributes.TYPE && entry.attributes['GROUP-ID'] && entry.attributes.NAME)) {
  1001. this.trigger('warn', {
  1002. message: 'ignoring incomplete or missing media group'
  1003. });
  1004. return;
  1005. } // find the media group, creating defaults as necessary
  1006. const mediaGroupType = this.manifest.mediaGroups[entry.attributes.TYPE];
  1007. mediaGroupType[entry.attributes['GROUP-ID']] = mediaGroupType[entry.attributes['GROUP-ID']] || {};
  1008. mediaGroup = mediaGroupType[entry.attributes['GROUP-ID']]; // collect the rendition metadata
  1009. rendition = {
  1010. default: /yes/i.test(entry.attributes.DEFAULT)
  1011. };
  1012. if (rendition.default) {
  1013. rendition.autoselect = true;
  1014. } else {
  1015. rendition.autoselect = /yes/i.test(entry.attributes.AUTOSELECT);
  1016. }
  1017. if (entry.attributes.LANGUAGE) {
  1018. rendition.language = entry.attributes.LANGUAGE;
  1019. }
  1020. if (entry.attributes.URI) {
  1021. rendition.uri = entry.attributes.URI;
  1022. }
  1023. if (entry.attributes['INSTREAM-ID']) {
  1024. rendition.instreamId = entry.attributes['INSTREAM-ID'];
  1025. }
  1026. if (entry.attributes.CHARACTERISTICS) {
  1027. rendition.characteristics = entry.attributes.CHARACTERISTICS;
  1028. }
  1029. if (entry.attributes.FORCED) {
  1030. rendition.forced = /yes/i.test(entry.attributes.FORCED);
  1031. } // insert the new rendition
  1032. mediaGroup[entry.attributes.NAME] = rendition;
  1033. },
  1034. discontinuity() {
  1035. currentTimeline += 1;
  1036. currentUri.discontinuity = true;
  1037. this.manifest.discontinuityStarts.push(uris.length);
  1038. },
  1039. 'program-date-time'() {
  1040. if (typeof this.manifest.dateTimeString === 'undefined') {
  1041. // PROGRAM-DATE-TIME is a media-segment tag, but for backwards
  1042. // compatibility, we add the first occurence of the PROGRAM-DATE-TIME tag
  1043. // to the manifest object
  1044. // TODO: Consider removing this in future major version
  1045. this.manifest.dateTimeString = entry.dateTimeString;
  1046. this.manifest.dateTimeObject = entry.dateTimeObject;
  1047. }
  1048. currentUri.dateTimeString = entry.dateTimeString;
  1049. currentUri.dateTimeObject = entry.dateTimeObject;
  1050. const {
  1051. lastProgramDateTime
  1052. } = this;
  1053. this.lastProgramDateTime = new Date(entry.dateTimeString).getTime(); // We should extrapolate Program Date Time backward only during first program date time occurrence.
  1054. // Once we have at least one program date time point, we can always extrapolate it forward using lastProgramDateTime reference.
  1055. if (lastProgramDateTime === null) {
  1056. // Extrapolate Program Date Time backward
  1057. // Since it is first program date time occurrence we're assuming that
  1058. // all this.manifest.segments have no program date time info
  1059. this.manifest.segments.reduceRight((programDateTime, segment) => {
  1060. segment.programDateTime = programDateTime - segment.duration * 1000;
  1061. return segment.programDateTime;
  1062. }, this.lastProgramDateTime);
  1063. }
  1064. },
  1065. targetduration() {
  1066. if (!isFinite(entry.duration) || entry.duration < 0) {
  1067. this.trigger('warn', {
  1068. message: 'ignoring invalid target duration: ' + entry.duration
  1069. });
  1070. return;
  1071. }
  1072. this.manifest.targetDuration = entry.duration;
  1073. setHoldBack.call(this, this.manifest);
  1074. },
  1075. start() {
  1076. if (!entry.attributes || isNaN(entry.attributes['TIME-OFFSET'])) {
  1077. this.trigger('warn', {
  1078. message: 'ignoring start declaration without appropriate attribute list'
  1079. });
  1080. return;
  1081. }
  1082. this.manifest.start = {
  1083. timeOffset: entry.attributes['TIME-OFFSET'],
  1084. precise: entry.attributes.PRECISE
  1085. };
  1086. },
  1087. 'cue-out'() {
  1088. currentUri.cueOut = entry.data;
  1089. },
  1090. 'cue-out-cont'() {
  1091. currentUri.cueOutCont = entry.data;
  1092. },
  1093. 'cue-in'() {
  1094. currentUri.cueIn = entry.data;
  1095. },
  1096. 'skip'() {
  1097. this.manifest.skip = camelCaseKeys(entry.attributes);
  1098. this.warnOnMissingAttributes_('#EXT-X-SKIP', entry.attributes, ['SKIPPED-SEGMENTS']);
  1099. },
  1100. 'part'() {
  1101. hasParts = true; // parts are always specifed before a segment
  1102. const segmentIndex = this.manifest.segments.length;
  1103. const part = camelCaseKeys(entry.attributes);
  1104. currentUri.parts = currentUri.parts || [];
  1105. currentUri.parts.push(part);
  1106. if (part.byterange) {
  1107. if (!part.byterange.hasOwnProperty('offset')) {
  1108. part.byterange.offset = lastPartByterangeEnd;
  1109. }
  1110. lastPartByterangeEnd = part.byterange.offset + part.byterange.length;
  1111. }
  1112. const partIndex = currentUri.parts.length - 1;
  1113. this.warnOnMissingAttributes_(`#EXT-X-PART #${partIndex} for segment #${segmentIndex}`, entry.attributes, ['URI', 'DURATION']);
  1114. if (this.manifest.renditionReports) {
  1115. this.manifest.renditionReports.forEach((r, i) => {
  1116. if (!r.hasOwnProperty('lastPart')) {
  1117. this.trigger('warn', {
  1118. message: `#EXT-X-RENDITION-REPORT #${i} lacks required attribute(s): LAST-PART`
  1119. });
  1120. }
  1121. });
  1122. }
  1123. },
  1124. 'server-control'() {
  1125. const attrs = this.manifest.serverControl = camelCaseKeys(entry.attributes);
  1126. if (!attrs.hasOwnProperty('canBlockReload')) {
  1127. attrs.canBlockReload = false;
  1128. this.trigger('info', {
  1129. message: '#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false'
  1130. });
  1131. }
  1132. setHoldBack.call(this, this.manifest);
  1133. if (attrs.canSkipDateranges && !attrs.hasOwnProperty('canSkipUntil')) {
  1134. this.trigger('warn', {
  1135. message: '#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set'
  1136. });
  1137. }
  1138. },
  1139. 'preload-hint'() {
  1140. // parts are always specifed before a segment
  1141. const segmentIndex = this.manifest.segments.length;
  1142. const hint = camelCaseKeys(entry.attributes);
  1143. const isPart = hint.type && hint.type === 'PART';
  1144. currentUri.preloadHints = currentUri.preloadHints || [];
  1145. currentUri.preloadHints.push(hint);
  1146. if (hint.byterange) {
  1147. if (!hint.byterange.hasOwnProperty('offset')) {
  1148. // use last part byterange end or zero if not a part.
  1149. hint.byterange.offset = isPart ? lastPartByterangeEnd : 0;
  1150. if (isPart) {
  1151. lastPartByterangeEnd = hint.byterange.offset + hint.byterange.length;
  1152. }
  1153. }
  1154. }
  1155. const index = currentUri.preloadHints.length - 1;
  1156. this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${index} for segment #${segmentIndex}`, entry.attributes, ['TYPE', 'URI']);
  1157. if (!hint.type) {
  1158. return;
  1159. } // search through all preload hints except for the current one for
  1160. // a duplicate type.
  1161. for (let i = 0; i < currentUri.preloadHints.length - 1; i++) {
  1162. const otherHint = currentUri.preloadHints[i];
  1163. if (!otherHint.type) {
  1164. continue;
  1165. }
  1166. if (otherHint.type === hint.type) {
  1167. this.trigger('warn', {
  1168. message: `#EXT-X-PRELOAD-HINT #${index} for segment #${segmentIndex} has the same TYPE ${hint.type} as preload hint #${i}`
  1169. });
  1170. }
  1171. }
  1172. },
  1173. 'rendition-report'() {
  1174. const report = camelCaseKeys(entry.attributes);
  1175. this.manifest.renditionReports = this.manifest.renditionReports || [];
  1176. this.manifest.renditionReports.push(report);
  1177. const index = this.manifest.renditionReports.length - 1;
  1178. const required = ['LAST-MSN', 'URI'];
  1179. if (hasParts) {
  1180. required.push('LAST-PART');
  1181. }
  1182. this.warnOnMissingAttributes_(`#EXT-X-RENDITION-REPORT #${index}`, entry.attributes, required);
  1183. },
  1184. 'part-inf'() {
  1185. this.manifest.partInf = camelCaseKeys(entry.attributes);
  1186. this.warnOnMissingAttributes_('#EXT-X-PART-INF', entry.attributes, ['PART-TARGET']);
  1187. if (this.manifest.partInf.partTarget) {
  1188. this.manifest.partTargetDuration = this.manifest.partInf.partTarget;
  1189. }
  1190. setHoldBack.call(this, this.manifest);
  1191. },
  1192. 'daterange'() {
  1193. this.manifest.dateRanges.push(camelCaseKeys(entry.attributes));
  1194. const index = this.manifest.dateRanges.length - 1;
  1195. this.warnOnMissingAttributes_(`#EXT-X-DATERANGE #${index}`, entry.attributes, ['ID', 'START-DATE']);
  1196. const dateRange = this.manifest.dateRanges[index];
  1197. if (dateRange.endDate && dateRange.startDate && new Date(dateRange.endDate) < new Date(dateRange.startDate)) {
  1198. this.trigger('warn', {
  1199. message: 'EXT-X-DATERANGE END-DATE must be equal to or later than the value of the START-DATE'
  1200. });
  1201. }
  1202. if (dateRange.duration && dateRange.duration < 0) {
  1203. this.trigger('warn', {
  1204. message: 'EXT-X-DATERANGE DURATION must not be negative'
  1205. });
  1206. }
  1207. if (dateRange.plannedDuration && dateRange.plannedDuration < 0) {
  1208. this.trigger('warn', {
  1209. message: 'EXT-X-DATERANGE PLANNED-DURATION must not be negative'
  1210. });
  1211. }
  1212. const endOnNextYes = !!dateRange.endOnNext;
  1213. if (endOnNextYes && !dateRange.class) {
  1214. this.trigger('warn', {
  1215. message: 'EXT-X-DATERANGE with an END-ON-NEXT=YES attribute must have a CLASS attribute'
  1216. });
  1217. }
  1218. if (endOnNextYes && (dateRange.duration || dateRange.endDate)) {
  1219. this.trigger('warn', {
  1220. message: 'EXT-X-DATERANGE with an END-ON-NEXT=YES attribute must not contain DURATION or END-DATE attributes'
  1221. });
  1222. }
  1223. if (dateRange.duration && dateRange.endDate) {
  1224. const startDate = dateRange.startDate;
  1225. const newDateInSeconds = startDate.getTime() + dateRange.duration * 1000;
  1226. this.manifest.dateRanges[index].endDate = new Date(newDateInSeconds);
  1227. }
  1228. if (!dateRangeTags[dateRange.id]) {
  1229. dateRangeTags[dateRange.id] = dateRange;
  1230. } else {
  1231. for (const attribute in dateRangeTags[dateRange.id]) {
  1232. if (!!dateRange[attribute] && JSON.stringify(dateRangeTags[dateRange.id][attribute]) !== JSON.stringify(dateRange[attribute])) {
  1233. this.trigger('warn', {
  1234. message: 'EXT-X-DATERANGE tags with the same ID in a playlist must have the same attributes values'
  1235. });
  1236. break;
  1237. }
  1238. } // if tags with the same ID do not have conflicting attributes, merge them
  1239. const dateRangeWithSameId = this.manifest.dateRanges.findIndex(dateRangeToFind => dateRangeToFind.id === dateRange.id);
  1240. this.manifest.dateRanges[dateRangeWithSameId] = _extends(this.manifest.dateRanges[dateRangeWithSameId], dateRange);
  1241. dateRangeTags[dateRange.id] = _extends(dateRangeTags[dateRange.id], dateRange); // after merging, delete the duplicate dateRange that was added last
  1242. this.manifest.dateRanges.pop();
  1243. }
  1244. },
  1245. 'independent-segments'() {
  1246. this.manifest.independentSegments = true;
  1247. },
  1248. 'content-steering'() {
  1249. this.manifest.contentSteering = camelCaseKeys(entry.attributes);
  1250. this.warnOnMissingAttributes_('#EXT-X-CONTENT-STEERING', entry.attributes, ['SERVER-URI']);
  1251. }
  1252. })[entry.tagType] || noop).call(self);
  1253. },
  1254. uri() {
  1255. currentUri.uri = entry.uri;
  1256. uris.push(currentUri); // if no explicit duration was declared, use the target duration
  1257. if (this.manifest.targetDuration && !('duration' in currentUri)) {
  1258. this.trigger('warn', {
  1259. message: 'defaulting segment duration to the target duration'
  1260. });
  1261. currentUri.duration = this.manifest.targetDuration;
  1262. } // annotate with encryption information, if necessary
  1263. if (key) {
  1264. currentUri.key = key;
  1265. }
  1266. currentUri.timeline = currentTimeline; // annotate with initialization segment information, if necessary
  1267. if (currentMap) {
  1268. currentUri.map = currentMap;
  1269. } // reset the last byterange end as it needs to be 0 between parts
  1270. lastPartByterangeEnd = 0; // Once we have at least one program date time we can always extrapolate it forward
  1271. if (this.lastProgramDateTime !== null) {
  1272. currentUri.programDateTime = this.lastProgramDateTime;
  1273. this.lastProgramDateTime += currentUri.duration * 1000;
  1274. } // prepare for the next URI
  1275. currentUri = {};
  1276. },
  1277. comment() {// comments are not important for playback
  1278. },
  1279. custom() {
  1280. // if this is segment-level data attach the output to the segment
  1281. if (entry.segment) {
  1282. currentUri.custom = currentUri.custom || {};
  1283. currentUri.custom[entry.customType] = entry.data; // if this is manifest-level data attach to the top level manifest object
  1284. } else {
  1285. this.manifest.custom = this.manifest.custom || {};
  1286. this.manifest.custom[entry.customType] = entry.data;
  1287. }
  1288. }
  1289. })[entry.type].call(self);
  1290. });
  1291. }
  1292. warnOnMissingAttributes_(identifier, attributes, required) {
  1293. const missing = [];
  1294. required.forEach(function (key) {
  1295. if (!attributes.hasOwnProperty(key)) {
  1296. missing.push(key);
  1297. }
  1298. });
  1299. if (missing.length) {
  1300. this.trigger('warn', {
  1301. message: `${identifier} lacks required attribute(s): ${missing.join(', ')}`
  1302. });
  1303. }
  1304. }
  1305. /**
  1306. * Parse the input string and update the manifest object.
  1307. *
  1308. * @param {string} chunk a potentially incomplete portion of the manifest
  1309. */
  1310. push(chunk) {
  1311. this.lineStream.push(chunk);
  1312. }
  1313. /**
  1314. * Flush any remaining input. This can be handy if the last line of an M3U8
  1315. * manifest did not contain a trailing newline but the file has been
  1316. * completely received.
  1317. */
  1318. end() {
  1319. // flush any buffered input
  1320. this.lineStream.push('\n');
  1321. if (this.manifest.dateRanges.length && this.lastProgramDateTime === null) {
  1322. this.trigger('warn', {
  1323. message: 'A playlist with EXT-X-DATERANGE tag must contain atleast one EXT-X-PROGRAM-DATE-TIME tag'
  1324. });
  1325. }
  1326. this.lastProgramDateTime = null;
  1327. this.trigger('end');
  1328. }
  1329. /**
  1330. * Add an additional parser for non-standard tags
  1331. *
  1332. * @param {Object} options a map of options for the added parser
  1333. * @param {RegExp} options.expression a regular expression to match the custom header
  1334. * @param {string} options.customType the custom type to register to the output
  1335. * @param {Function} [options.dataParser] function to parse the line into an object
  1336. * @param {boolean} [options.segment] should tag data be attached to the segment object
  1337. */
  1338. addParser(options) {
  1339. this.parseStream.addParser(options);
  1340. }
  1341. /**
  1342. * Add a custom header mapper
  1343. *
  1344. * @param {Object} options
  1345. * @param {RegExp} options.expression a regular expression to match the custom header
  1346. * @param {Function} options.map function to translate tag into a different tag
  1347. */
  1348. addTagMapper(options) {
  1349. this.parseStream.addTagMapper(options);
  1350. }
  1351. }
  1352. export { LineStream, ParseStream, Parser };