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