m3u8-parser.js 50 KB

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