UNPKG

2.15 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const stream_1 = require("stream");
4/**
5 * A very simple m3u8 playlist file parser that detects tags and segments.
6 */
7class m3u8Parser extends stream_1.Writable {
8 constructor() {
9 super();
10 this._lastLine = '';
11 this._seq = 0;
12 this._nextItemDuration = null;
13 this.on('finish', () => {
14 this._parseLine(this._lastLine);
15 this.emit('end');
16 });
17 }
18 _parseLine(line) {
19 let match = line.match(/^#(EXT[A-Z0-9-]+)(?::(.*))?/);
20 if (match) {
21 // This is a tag.
22 const tag = match[1];
23 const value = match[2] || '';
24 switch (tag) {
25 case 'EXT-X-PROGRAM-DATE-TIME':
26 this.emit('starttime', new Date(value).getTime());
27 break;
28 case 'EXT-X-MEDIA-SEQUENCE':
29 this._seq = parseInt(value);
30 break;
31 case 'EXTINF':
32 this._nextItemDuration =
33 Math.round(parseFloat(value.split(',')[0]) * 1000);
34 break;
35 case 'EXT-X-ENDLIST':
36 this.emit('endlist');
37 break;
38 }
39 }
40 else if (!/^#/.test(line) && line.trim()) {
41 // This is a segment
42 this.emit('item', {
43 url: line.trim(),
44 seq: this._seq++,
45 duration: this._nextItemDuration,
46 });
47 }
48 }
49 _write(chunk, encoding, callback) {
50 let lines = chunk.toString('utf8').split('\n');
51 if (this._lastLine) {
52 lines[0] = this._lastLine + lines[0];
53 }
54 lines.forEach((line, i) => {
55 if (i < lines.length - 1) {
56 this._parseLine(line);
57 }
58 else {
59 // Save the last line in case it has been broken up.
60 this._lastLine = line;
61 }
62 });
63 callback();
64 }
65}
66exports.default = m3u8Parser;
67//# sourceMappingURL=m3u8-parser.js.map
\No newline at end of file