-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
3482 lines (3282 loc) · 138 KB
/
index.js
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
const m3u8 = require("@eyevinn/m3u8");
const debug = require("debug")("hls-vodtolive");
const verbose = require("debug")("hls-vodtolive-verbose");
const {
findIndexReversed,
fetchWithRetry,
urlResolve,
segToM3u8,
findBottomSegItem,
fixedNumber,
inspectForVodTransition,
playlistItemWithInterstitialsMetadata,
appendHlsInterstitialLineWithCUE,
} = require("./utils.js");
class HLSVod {
/**
* Create an HLS VOD instance
* @param {string} vodManifestUri - the uri to the master manifest of the VOD
* @param {Object} splices - an array of ad splice objects
* @param {number} timeOffset - time offset as unix timestamp ms
* @param {number} startTimeOffset - start time offset in N ms from start
* @param {string} header - prepend the m3u8 playlist with this text
* @param {string} opts - other options
*/
constructor(vodManifestUri, splices, timeOffset, startTimeOffset, header, opts) {
this.masterManifestUri = vodManifestUri;
this.segments = {};
this.audioSegments = {};
this.subtitleSegments = {};
this.mediaSequences = [];
this.SEQUENCE_DURATION = process.env.SEQUENCE_DURATION ? process.env.SEQUENCE_DURATION : 60;
this.DUMMY_DEFAULT_SUBTITLE_GROUP_ID = "dummyDefaultSubtitleGroupId";
this.DUMMY_DEFAULT_SUBTITLE_LANGUAGE = "dummyDefaultSubtitleLanguage";
this.DEFAULT_SUBTITLE_GROUP_ID = "subtitles";
this.targetDuration = {};
this.targetAudioDuration = {};
this.targetSubtitleDuration = {};
this.previousVod = null;
this.usageProfile = [];
this.segmentsInitiated = {};
this.splices = splices || [];
this.timeOffset = timeOffset || null;
this.startTimeOffset = startTimeOffset || null;
this.usageProfileMapping = null;
this.usageProfileMappingRev = null;
this.discontinuities = {};
this.discontinuitiesAudio = {};
this.discontinuitiesSubtitle = {};
this.mediaSequenceValues = {};
this.mediaSequenceValuesAudio = {};
this.mediaSequenceValuesSubtitle = {};
this.rangeMetadata = null;
this.matchedBandwidths = {};
this.deltaTimes = [];
this.deltaTimesAudio = [];
this.deltaTimesSubtitle = [];
this.header = header;
this.lastUsedDiscSeq = null;
this.sequenceAlwaysContainNewSegments = false;
this.skipSerializeMediaSequences = false;
if (opts && opts.sequenceAlwaysContainNewSegments) {
this.sequenceAlwaysContainNewSegments = opts.sequenceAlwaysContainNewSegments;
}
if (opts && opts.forcedDemuxMode) {
this.forcedDemuxMode = opts.forcedDemuxMode;
}
if (opts && opts.dummySubtitleEndpoint) {
this.dummySubtitleEndpoint = opts.dummySubtitleEndpoint;
}
if (opts && opts.subtitleSliceEndpoint) {
this.subtitleSliceEndpoint = opts.subtitleSliceEndpoint;
}
if (opts && opts.shouldContainSubtitles) {
this.shouldContainSubtitles = opts.shouldContainSubtitles;
}
if (opts && opts.expectedSubtitleTracks) {
this.expectedSubtitleTracks = opts.expectedSubtitleTracks;
}
if (opts && opts.alwaysMapBandwidthByNearest) {
this.alwaysMapBandwidthByNearest = opts.alwaysMapBandwidthByNearest;
}
if (opts && opts.skipSerializeMediaSequences) {
this.skipSerializeMediaSequences = opts.skipSerializeMediaSequences;
}
this.videoSequencesCount = 0;
this.audioSequencesCount = 0;
this.defaultAudioGroupAndLang = null;
this.subtitleSequencesCount = 0;
this.mediaStartExcessTime = 0;
this.audioCodecsMap = {};
this.cuedHlsInterstitialTag = null;
}
toJSON() {
const serialized = {
masterManifestUri: this.masterManifestUri,
segments: this.segments,
audioSegments: this.audioSegments,
subtitleSegments: this.subtitleSegments,
shouldContainSubtitles: this.shouldContainSubtitles,
expectedSubtitleTracks: this.expectedSubtitleTracks,
mediaSequences: this.skipSerializeMediaSequences ? null : this.mediaSequences,
SEQUENCE_DURATION: this.SEQUENCE_DURATION,
targetDuration: this.targetDuration,
targetAudioDuration: this.targetAudioDuration,
targetSubtitleDuration: this.targetSubtitleDuration,
previousVod: this.previousVod ? this.previousVod.toJSON() : null,
usageProfile: this.usageProfile,
segmentsInitiated: this.segmentsInitiated,
splices: this.splices,
timeOffset: this.timeOffset,
startTimeOffset: this.startTimeOffset,
usageProfileMapping: this.usageProfileMapping,
usageProfileMappingRev: this.usageProfileMappingRev,
discontinuities: this.discontinuities,
discontinuitiesAudio: this.discontinuitiesAudio,
discontinuitiesSubtitle: this.discontinuitiesSubtitle,
deltaTimes: this.deltaTimes,
deltaTimesAudio: this.deltaTimesAudio,
deltaTimesSubtitle: this.deltaTimesSubtitle,
header: this.header,
lastUsedDiscSeq: this.lastUsedDiscSeq,
mediaSequenceValues: this.mediaSequenceValues,
mediaSequenceValuesAudio: this.mediaSequenceValuesAudio,
mediaSequenceValuesSubtitle: this.mediaSequenceValuesSubtitle,
sequenceAlwaysContainNewSegments: this.sequenceAlwaysContainNewSegments,
forcedDemuxMode: this.forcedDemuxMode,
dummySubtitleEndpoint: this.dummySubtitleEndpoint,
subtitleSliceEndpoint: this.subtitleSliceEndpoint,
videoSequencesCount: this.skipSerializeMediaSequences ? 0 : this.videoSequencesCount,
audioSequencesCount: this.skipSerializeMediaSequences ? 0 : this.audioSequencesCount,
subtitleSequencesCount: this.skipSerializeMediaSequences ? 0 : this.subtitleSequencesCount,
mediaStartExcessTime: this.mediaStartExcessTime,
audioCodecsMap: this.audioCodecsMap,
alwaysMapBandwidthByNearest: this.alwaysMapBandwidthByNearest,
skipSerializeMediaSequences: this.skipSerializeMediaSequences,
cuedHlsInterstitialTag: this.cuedHlsInterstitialTag,
};
return JSON.stringify(serialized);
}
fromJSON(serialized) {
const de = JSON.parse(serialized);
this.masterManifestUri = de.masterManifestUri;
this.segments = de.segments;
this.audioSegments = de.audioSegments;
this.subtitleSegments = de.subtitleSegments;
this.shouldContainSubtitles = de.shouldContainSubtitles;
this.expectedSubtitleTracks = de.expectedSubtitleTracks;
this.mediaSequences = de.mediaSequences;
this.SEQUENCE_DURATION = de.SEQUENCE_DURATION;
this.targetDuration = de.targetDuration;
this.targetAudioDuration = de.targetAudioDuration;
this.targetSubtitleDuration = de.targetSubtitleDuration;
const prevVod = new HLSVod();
this.previousVod = null;
if (de.previousVod) {
this.previousVod = prevVod.fromJSON(de.previousVod);
}
this.usageProfile = de.usageProfile;
this.segmentsInitiated = de.segmentsInitiated;
this.splices = de.splices;
this.timeOffset = de.timeOffset;
this.startTimeOffset = de.startTimeOffset;
this.usageProfileMapping = de.usageProfileMapping;
this.usageProfileMappingRev = de.usageProfileMappingRev;
this.discontinuities = de.discontinuities;
this.discontinuitiesAudio = de.discontinuitiesAudio;
this.discontinuitiesSubtitle = de.discontinuitiesSubtitle;
this.deltaTimes = de.deltaTimes;
this.deltaTimesAudio = de.deltaTimesAudio;
this.deltaTimesSubtitle = de.deltaTimesSubtitle;
this.header = de.header;
if (de.lastUsedDiscSeq) {
this.lastUsedDiscSeq = de.lastUsedDiscSeq;
}
this.mediaSequenceValues = de.mediaSequenceValues;
this.mediaSequenceValuesAudio = de.mediaSequenceValuesAudio;
this.mediaSequenceValuesSubtitle = de.mediaSequenceValuesSubtitle;
this.sequenceAlwaysContainNewSegments = de.sequenceAlwaysContainNewSegments;
this.forcedDemuxMode = de.forcedDemuxMode;
this.dummySubtitleEndpoint = de.dummySubtitleEndpoint;
this.subtitleSliceEndpoint = de.subtitleSliceEndpoint;
this.videoSequencesCount = de.videoSequencesCount;
this.audioSequencesCount = de.audioSequencesCount;
this.subtitleSequencesCount = de.subtitleSequencesCount;
this.mediaStartExcessTime = de.mediaStartExcessTime;
this.audioCodecsMap = de.audioCodecsMap;
this.alwaysMapBandwidthByNearest = de.alwaysMapBandwidthByNearest;
this.skipSerializeMediaSequences = de.skipSerializeMediaSequences;
this.cuedHlsInterstitialTag = de.cuedHlsInterstitialTag;
}
/**
* Load and parse the HLS VOD
*/
load(_injectMasterManifest, _injectMediaManifest, _injectAudioManifest, _injectSubtitleManifest) {
return new Promise((resolve, reject) => {
const parser = m3u8.createStream();
parser.on("m3u", (m3u) => {
let mediaManifestPromises = [];
let audioManifestPromises = [];
let subtitleManifestPromises = [];
let baseUrl;
const m = this.masterManifestUri.match("^(.*)/.*?$");
if (m) {
baseUrl = m[1] + "/";
}
const HAS_AUDIO_DEFAULTS = this.defaultAudioGroupAndLang === null ? false : true;
if (!this.alwaysMapBandwidthByNearest && this.previousVod && this.previousVod.getBandwidths().length === m3u.items.StreamItem.length) {
debug(`Previous VOD bandwidths matches amount of current. A mapping is possible`);
const previousBandwidths = this.previousVod.getBandwidths().sort((a, b) => a - b);
this.usageProfileMapping = {};
this.usageProfileMappingRev = {};
const bandwidths = m3u.items.StreamItem.sort((a, b) => {
return a.get("bandwidth") - b.get("bandwidth");
}).map((v) => v.get("bandwidth"));
debug(`${previousBandwidths} : ${bandwidths}`);
for (let i = 0; i < previousBandwidths.length; i++) {
this.usageProfileMapping[previousBandwidths[i]] = bandwidths[i] + "";
this.usageProfileMappingRev[bandwidths[i]] = previousBandwidths[i];
}
}
for (let i = 0; i < m3u.items.StreamItem.length; i++) {
const streamItem = m3u.items.StreamItem[i];
let mediaManifestUrl = urlResolve(baseUrl, streamItem.get("uri"));
if (streamItem.get("bandwidth")) {
let usageProfile = {
bw: streamItem.get("bandwidth"),
};
if (streamItem.get("resolution")) {
usageProfile.resolution = streamItem.get("resolution")[0] + "x" + streamItem.get("resolution")[1];
}
if (streamItem.get("codecs")) {
usageProfile.codecs = streamItem.get("codecs");
}
this.usageProfile.push(usageProfile);
// Do not add if it is a variant included in an audio group as it will be loaded and parsed separate
if (!m3u.items.MediaItem.find((mediaItem) => mediaItem.get("type") === "AUDIO" && mediaItem.get("uri") == streamItem.get("uri"))) {
if (streamItem.get("codecs") !== "mp4a.40.2") {
mediaManifestPromises.push(this._loadMediaManifest(mediaManifestUrl, streamItem.get("bandwidth"), _injectMediaManifest));
}
}
}
}
Promise.all(mediaManifestPromises).then(() => {
let audioGroups = {};
let subtitleGroups = {};
for (let i = 0; i < m3u.items.StreamItem.length; i++) {
const streamItem = m3u.items.StreamItem[i];
if (streamItem.get("audio")) {
let audioGroupId = streamItem.get("audio");
if (!HAS_AUDIO_DEFAULTS && !this.audioSegments[audioGroupId]) {
this.audioSegments[audioGroupId] = {};
}
const audioCodecs = streamItem.get("codecs").split(",").find(c => {
return c.match(/^mp4a/) || c.match(/^ac-3/) || c.match(/^ec-3/);
});
debug(`Lookup media item for '${audioGroupId}'`);
// # Needed for the case when loading after another VOD.
const previousVODLanguages = HAS_AUDIO_DEFAULTS
? Object.keys(this.audioSegments[this.defaultAudioGroupAndLang.audioGroupId])
: Object.keys(this.audioSegments[audioGroupId]);
let audioGroupItems = m3u.items.MediaItem.filter((item) => {
return item.get("type") === "AUDIO" && item.get("group-id") === audioGroupId;
});
// # Find all langs amongst the mediaItems that have this group id.
// # It extracts each mediaItems language attribute value.
// # ALSO initialize in this.audioSegments a lang. property who's value is an array [{seg1}, {seg2}, ...].
let audioLanguages = audioGroupItems.map((item) => {
let itemLang;
if (!item.get("language")) {
itemLang = item.get("name");
} else {
itemLang = item.get("language");
}
// Initialize lang. in new group.
if (!HAS_AUDIO_DEFAULTS && !this.audioSegments[audioGroupId][itemLang]) {
this.audioSegments[audioGroupId][itemLang] = [];
}
if (!this.audioCodecsMap[audioCodecs]) {
this.audioCodecsMap[audioCodecs] = {};
}
const itemChannels = item.get("channels") ? item.get("channels") : "2";
this.audioCodecsMap[audioCodecs][itemChannels] = audioGroupId;
return itemLang;
});
// # Inject "default" language's segments to every new language relative to previous VOD.
// # For the case when this is a VOD following another, every language new or old should
// # start with some segments from the previous VOD's last sequence.
const newLanguages = audioLanguages.filter((lang) => {
return !previousVODLanguages.includes(lang);
});
// # Only inject if there were prior tracks.
if (previousVODLanguages.length > 0 && !HAS_AUDIO_DEFAULTS) {
for (let i = 0; i < newLanguages.length; i++) {
const newLanguage = newLanguages[i];
const defaultLanguage = this._getFirstAudioLanguageWithSegments(audioGroupId);
this.audioSegments[audioGroupId][newLanguage] = [...this.audioSegments[audioGroupId][defaultLanguage]];
}
}
// # Need to clean up langs. loaded from prev. VOD that current VOD doesn't have.
// # Necessary, for the case when getLiveMediaSequenceAudioSegments() tries to
// # access an audioGroup's language that the current VOD never had. A False-Positive.
if (!HAS_AUDIO_DEFAULTS) {
let allLangs = Object.keys(this.audioSegments[audioGroupId]);
let toRemove = [];
allLangs.map((junkLang) => {
if (!audioLanguages.includes(junkLang)) {
toRemove.push(junkLang);
}
});
toRemove.map((junkLang) => {
delete this.audioSegments[audioGroupId][junkLang];
});
}
// # For each lang, find the lang playlist uri and do _loadAudioManifest() on it.
for (let j = 0; j < audioLanguages.length; j++) {
let audioLang = audioLanguages[j];
let audioUri = audioGroupItems[j].get("uri");
if (!audioUri) {
//# if mediaItems dont have uris
let audioVariant = m3u.items.StreamItem.find((item) => {
return !item.get("resolution") && item.get("audio") === audioGroupId;
});
if (audioVariant) {
audioUri = audioVariant.get("uri");
}
}
if (audioUri) {
let audioManifestUrl = urlResolve(baseUrl, audioUri);
if (!audioGroups[audioGroupId]) {
audioGroups[audioGroupId] = {};
}
// # Prevents 'loading' an audio track with same GroupID and LANG.
// # otherwise it just would've loaded OVER the latest occurrent of the LANG in GroupID.
if (!audioGroups[audioGroupId][audioLang]) {
let targetGroup = audioGroupId;
let targetLang = audioLang;
audioGroups[audioGroupId][audioLang] = true;
if (HAS_AUDIO_DEFAULTS) {
targetGroup = this.defaultAudioGroupAndLang.audioGroupId;
targetLang = this.defaultAudioGroupAndLang.audioLanguage;
debug(`Loading Audio manifest onto Default GroupID=${targetGroup} and Language=${targetLang}`);
}
audioManifestPromises.push(this._loadAudioManifest(audioManifestUrl, targetGroup, targetLang, _injectAudioManifest));
} else {
debug(`Audio manifest for language "${audioLang}" from '${audioGroupId}' in already loaded, skipping`);
}
} else {
debug(`No media item for '${audioGroupId}' in "${audioLang}" was found, skipping`);
}
}
} else if (this.forcedDemuxMode) {
reject(new Error("The vod is not a demux vod"));
}
if (this.shouldContainSubtitles) {
if (!this.subtitleSliceEndpoint) {
reject(new Error("Missing subtitle slice URL"));
continue;
}
if (!this.expectedSubtitleTracks) {
reject(new Error("There are no expected subtitle tracks"));
continue;
}
if (this.shouldContainSubtitles) {
if (!this.subtitleSegments[this.DUMMY_DEFAULT_SUBTITLE_GROUP_ID]) {
this.subtitleSegments[this.DUMMY_DEFAULT_SUBTITLE_GROUP_ID] = {};
}
if (!this.subtitleSegments[this.DUMMY_DEFAULT_SUBTITLE_GROUP_ID][this.DUMMY_DEFAULT_SUBTITLE_LANGUAGE]) {
this.subtitleSegments[this.DUMMY_DEFAULT_SUBTITLE_GROUP_ID][this.DUMMY_DEFAULT_SUBTITLE_LANGUAGE] = [];
}
}
if (!this.subtitleSegments[this.DEFAULT_SUBTITLE_GROUP_ID]) {
this.subtitleSegments[this.DEFAULT_SUBTITLE_GROUP_ID] = {};
}
for (let i = 0; i < this.expectedSubtitleTracks.length; i++) {
const element = this.expectedSubtitleTracks[i];
if (!this.subtitleSegments[this.DEFAULT_SUBTITLE_GROUP_ID][element.language]) {
this.subtitleSegments[this.DEFAULT_SUBTITLE_GROUP_ID][element.language] = [];
}
}
if (streamItem.get("subtitles")) {
if (!subtitleGroups[this.DEFAULT_SUBTITLE_GROUP_ID]) {
subtitleGroups[this.DEFAULT_SUBTITLE_GROUP_ID] = {};
}
let subtitleGroupId = streamItem.get("subtitles");
let subtitleGroupItems = m3u.items.MediaItem.filter((item) => {
return item.get("type") === "SUBTITLES" && item.get("group-id") === subtitleGroupId;
});
// # Find all langs amongst the mediaItems that have this group id.
// # It extracts each mediaItems language attribute value.
// # ALSO initialize in this.subtitleSegments a lang. property who's value is an array [{seg1}, {seg2}, ...].
let subtitleLanguages = subtitleGroupItems.map((item) => {
let itemLang;
if (!item.get("language")) {
itemLang = item.get("name");
} else {
itemLang = item.get("language");
}
for (let index = 0; index < this.expectedSubtitleTracks.length; index++) {
const element = this.expectedSubtitleTracks[index];
if (element.language.toLowerCase() === itemLang.toLowerCase() || element.name.toLowerCase() === itemLang.toLowerCase()) {
return element.language;
}
}
return;
}).filter((item) => item !== undefined);
// # For each lang, find the lang playlist uri and do _loadSubtitleManifest() on it.
for (let j = 0; j < subtitleLanguages.length; j++) {
let subtitleLang = subtitleLanguages[j];
let subtitleUri = subtitleGroupItems[j].get("uri");
if (!subtitleUri) {
//# if mediaItems dont have uris
let subtitleVariant = m3u.items.StreamItem.find((item) => {
return !item.get("resolution") && item.get("subtitle") === subtitleGroupId;
});
if (subtitleVariant) {
subtitleUri = subtitleVariant.get("uri");
}
}
if (subtitleUri) {
let subtitleManifestUrl = urlResolve(baseUrl, subtitleUri);
// # Prevents 'loading' an subtitle track with same GroupID and LANG.
// # otherwise it just would've loaded OVER the latest occurrent of the LANG in GroupID.
if (!subtitleGroups[this.DEFAULT_SUBTITLE_GROUP_ID][subtitleLang]) {
let targetGroup = this.DEFAULT_SUBTITLE_GROUP_ID;
let targetLang = subtitleLang;
subtitleGroups[this.DEFAULT_SUBTITLE_GROUP_ID][subtitleLang] = true;
subtitleManifestPromises.push(this._loadSubtitleManifest(subtitleManifestUrl, targetGroup, targetLang, _injectSubtitleManifest));
} else {
debug(`Subtitle manifest for language "${this.DEFAULT_SUBTITLE_GROUP_ID}" from '${subtitleGroupId}' in already loaded, skipping`);
}
} else {
debug(`No media item for '${subtitleGroupId}' in "${subtitleLang}" was found, skipping`);
}
}
} else if (this.shouldContainSubtitles) {
if (!this.dummySubtitleEndpoint) {
reject(new Error("Loaded VOD does not contain subtitles and there is no dummy subtitle segment URL configured"));
}
if (!this.expectedSubtitleTracks) {
reject(new Error("There are no expected subtitle tracks"));
}
if (!this.subtitleSliceEndpoint) {
reject(new Error("Missing subtitle slice URL"));
}
}
}
}
debug("Codec to Audio Group Id mapping");
debug(this.audioCodecsMap);
return Promise.all(audioManifestPromises.concat(subtitleManifestPromises))
}).then(this._cleanupUnused.bind(this))
.then(this._createMediaSequences.bind(this))
.then(resolve)
.catch((err) => {
debug("Error loading VOD: Need to cleanup");
this._cleanupOnFailure();
reject(err);
});
});
parser.on("error", (err) => {
reject(err);
});
if (!_injectMasterManifest) {
fetchWithRetry(this.masterManifestUri, null, 5, 1000, 5000, debug)
.then((res) => {
if (res.status === 200) {
res.body.pipe(parser);
} else {
throw new Error(res.status + ":: status code error trying to retrieve master manifest " + this.masterManifestUri);
}
})
.catch(reject);
} else {
const stream = _injectMasterManifest();
stream.pipe(parser);
stream.on("error", (err) => reject(err));
}
});
}
/**
* Load and parse the HLS VOD where the first media sequences
* contains the end sequences of the previous VOD
*
* @param {HLSVod} previousVod - the previous VOD to concatenate to
*/
loadAfter(previousVod, _injectMasterManifest, _injectMediaManifest, _injectAudioManifest, _injectSubtitleManifest) {
debug(`Initializing Load VOD After VOD...`);
return new Promise((resolve, reject) => {
this.previousVod = previousVod;
try {
this._loadPrevious();
this.load(_injectMasterManifest, _injectMediaManifest, _injectAudioManifest, _injectSubtitleManifest)
.then(() => {
this.releasePreviousVod();
resolve();
})
.catch((err) => {
this.releasePreviousVod();
reject(err);
});
} catch (exc) {
reject(exc);
}
});
}
/**
* Removes all segments that come before or after a specified media sequence.
* Then adds the new additional segments in front or behind.
* It finally creates new media sequences with the updated collection of segments.
*
* @param {number} mediaSeqNo The media Sequence index that is the live index.
* @param {object} additionalSegments New group of segments to merge with a possible subset of this.segments
* @param {object} additionalAudioSegments New group of audio segments to merge with a possible subset of this.segments
* @param {boolean} insertAfter Whether the additional segments are to be added in front of the live index or behind
* @returns A promise that new Media Sequences have been made
*/
reload(mediaSeqNo, additionalSegments, additionalAudioSegments, insertAfter) {
return new Promise((resolve, reject) => {
const allBandwidths = this.getBandwidths();
if (!insertAfter) {
// First handle case where we reload segments with Program Date time positions.
let newTimeOffset = this._getLastTimelinePositionVideo(additionalSegments);
let newTimeOffsetAudio = this._getLastTimelinePositionAudio(additionalAudioSegments);
// If there is anything to slice
if (mediaSeqNo > 0) {
let targetUri = "";
let size = this.mediaSequences[mediaSeqNo].segments[allBandwidths[0]].length;
for (let idx = size - 1; idx >= 0; idx--) {
const segItem = this.mediaSequences[mediaSeqNo].segments[allBandwidths[0]][idx];
if (segItem.uri) {
targetUri = segItem.uri;
break;
}
}
let targetPos = 0;
for (let i = mediaSeqNo; i < this.segments[allBandwidths[0]].length; i++) {
if (this.segments[allBandwidths[0]][i].uri === targetUri) {
targetPos = i;
break;
}
}
allBandwidths.forEach((bw) => (this.segments[bw] = this.segments[bw].slice(targetPos)));
}
if (!this._isEmpty(this.audioSegments) && additionalAudioSegments) {
const groupIds = this.getAudioGroups();
const lang = this.getAudioLangsForAudioGroup(groupIds[0])[0];
if (mediaSeqNo > 0) {
let targetUri = "";
let size = this.mediaSequences[mediaSeqNo].audioSegments[groupIds[0]][lang].length;
for (let idx = size - 1; idx >= 0; idx--) {
const segItem = this.mediaSequences[mediaSeqNo].audioSegments[groupIds[0]][lang][idx];
if (segItem.uri) {
targetUri = segItem.uri;
break;
}
}
let targetPos = 0;
for (let i = mediaSeqNo; i < this.audioSegments[groupIds[0]][lang].length; i++) {
if (this.audioSegments[groupIds[0]][lang][i].uri === targetUri) {
targetPos = i;
break;
}
}
for (let i = 0; i < groupIds.length; i++) {
const groupId = groupIds[i];
const langs = this.getAudioLangsForAudioGroup(groupId);
for (let j = 0; j < langs.length; j++) {
const lang = langs[j];
this.audioSegments[groupId][lang] = this.audioSegments[groupId][lang].slice(targetPos);
}
}
}
}
// Find nearest BW in SFL and prepend them to the corresponding segments bandwidth
allBandwidths.forEach((bw) => {
if (newTimeOffset > 0) {
let totalTimelinePos = 0;
for (let i = 0; i < this.segments[bw].length; i++) {
const segment = this.segments[bw][i];
if (segment.duration) {
totalTimelinePos += segment.duration * 1000;
this.segments[bw][i].timelinePosition = newTimeOffset + totalTimelinePos;
}
}
}
let nearestBw = this._getNearestBandwidthInList(bw, Object.keys(additionalSegments));
this.segments[bw] = additionalSegments[nearestBw].concat(this.segments[bw]);
});
if (!this._isEmpty(this.audioSegments) && additionalAudioSegments) {
const groupIdsInVod = this.getAudioGroups();
const groupIdsInSegments = Object.keys(additionalAudioSegments);
for (let i = 0; i < groupIdsInSegments.length; i++) {
let groupIdForVod = groupIdsInSegments[i];
let indexOfGroupId = groupIdsInVod.indexOf(groupIdsInSegments[i]);
if (indexOfGroupId < 0) {
groupIdForVod = groupIdsInVod[0];
} else {
groupIdForVod = groupIdsInVod[indexOfGroupId];
}
const langsInVod = this.getAudioLangsForAudioGroup(groupIdForVod);
const langsInSegment = Object.keys(additionalAudioSegments[groupIdsInSegments[i]]);
for (let j = 0; j < langsInSegment.length; j++) {
let langForVod = langsInSegment[j];
let indexOfLang = langsInVod.indexOf(langsInSegment[j]);
if (indexOfLang < 0) {
langForVod = langsInVod[0];
} else {
langForVod = langsInVod[indexOfLang];
}
if (newTimeOffsetAudio > 0) {
let totalTimelinePos = 0;
for (let i = 0; i < this.audioSegments[groupIdForVod][langForVod].length; i++) {
const segment = this.audioSegments[groupIdForVod][langForVod][i];
if (segment.duration) {
totalTimelinePos += segment.duration * 1000;
this.audioSegments[groupIdForVod][langForVod][i].timelinePosition = newTimeOffsetAudio + totalTimelinePos;
}
}
}
this.audioSegments[groupIdForVod][langForVod] = additionalAudioSegments[groupIdsInSegments[i]][langsInSegment[j]].concat(
this.audioSegments[groupIdForVod][langForVod]
);
}
}
}
} else {
// First handle case where we reload segments with Program Date time positions.
let newTimeOffset = this._getLastTimelinePositionVideo(this.segments);
let newTimeOffsetAudio = this._getLastTimelinePositionAudio(this.audioSegments);
// Slice Video segments
if (mediaSeqNo >= 0) {
let size = this.mediaSequences[mediaSeqNo].segments[allBandwidths[0]].length;
let targetUri = this.mediaSequences[mediaSeqNo].segments[allBandwidths[0]][0].uri;
let targetPos = 0;
for (let i = mediaSeqNo; i < this.segments[allBandwidths[0]].length; i++) {
if (this.segments[allBandwidths[0]][i].uri === targetUri) {
targetPos = i;
break;
}
}
allBandwidths.forEach((bw) => (this.segments[bw] = this.segments[bw].slice(targetPos, targetPos + size)));
}
// Slice Audio segments
if (!this._isEmpty(this.audioSegments) && additionalAudioSegments) {
const groupIds = this.getAudioGroups();
const lang = this.getAudioLangsForAudioGroup(groupIds[0])[0];
if (mediaSeqNo >= 0) {
let size = this.mediaSequences[mediaSeqNo].audioSegments[groupIds[0]][lang].length;
let targetUri = this.mediaSequences[mediaSeqNo].audioSegments[groupIds[0]][lang][0].uri;
let targetPos = 0;
for (let i = mediaSeqNo; i < this.audioSegments[groupIds[0]][lang].length; i++) {
if (this.audioSegments[groupIds[0]][lang][i].uri === targetUri) {
targetPos = i;
break;
}
}
for (let i = 0; i < groupIds.length; i++) {
const groupId = groupIds[i];
const langs = this.getAudioLangsForAudioGroup(groupId);
for (let j = 0; j < langs.length; j++) {
const lang = langs[j];
this.audioSegments[groupId][lang] = this.audioSegments[groupId][lang].slice(targetPos, targetPos + size);
}
}
}
}
// Update Program Date Time positions in the additional segments video
if (newTimeOffset > 0) {
const allAdditionalSegmentsBandwidths = Object.keys(additionalSegments);
allAdditionalSegmentsBandwidths.forEach((bw) => {
let totalTimelinePos = 0;
for (let i = 0; i < additionalSegments[bw].length; i++) {
const segment = additionalSegments[bw][i];
if (segment.duration) {
totalTimelinePos += segment.duration * 1000;
additionalSegments[bw][i].timelinePosition = newTimeOffset + totalTimelinePos;
}
}
});
}
allBandwidths.forEach((bw) => {
let nearestBw = this._getNearestBandwidthInList(bw, Object.keys(additionalSegments));
this.segments[bw] = this.segments[bw].concat(additionalSegments[nearestBw]);
});
if (!this._isEmpty(this.audioSegments) && additionalAudioSegments) {
const groupIdsInVod = this.getAudioGroups();
const groupIdsInSegments = Object.keys(additionalAudioSegments);
for (let i = 0; i < groupIdsInSegments.length; i++) {
let groupIdForVod = groupIdsInSegments[i];
let indexOfGroupId = groupIdsInVod.indexOf(groupIdsInSegments[i]);
if (indexOfGroupId < 0) {
groupIdForVod = groupIdsInVod[0];
} else {
groupIdForVod = groupIdsInVod[indexOfGroupId];
}
const langsInVod = this.getAudioLangsForAudioGroup(groupIdForVod);
const langsInSegment = Object.keys(additionalAudioSegments[groupIdsInSegments[i]]);
for (let j = 0; j < langsInSegment.length; j++) {
let langForVod = langsInSegment[j];
let indexOfLang = langsInVod.indexOf(langsInSegment[j]);
if (indexOfLang < 0) {
langForVod = langsInVod[0];
} else {
langForVod = langsInVod[indexOfLang];
}
if (newTimeOffsetAudio > 0) {
let totalTimelinePos = 0;
for (let x = 0; x < additionalAudioSegments[groupIdsInSegments[i]][langsInSegment[j]].length; x++) {
const segment = additionalAudioSegments[groupIdsInSegments[i]][langsInSegment[j]][x];
if (segment.duration) {
totalTimelinePos += segment.duration * 1000;
additionalAudioSegments[groupIdsInSegments[i]][langsInSegment[j]][x].timelinePosition =
newTimeOffsetAudio + totalTimelinePos;
}
}
}
this.audioSegments[groupIdForVod][langForVod] = this.audioSegments[groupIdForVod][langForVod].concat(
additionalAudioSegments[groupIdsInSegments[i]][langsInSegment[j]]
);
}
}
}
}
// Clean up/Reset HLSVod data since we are going to create new data
this.mediaSequences = [];
this.audioSequences = [];
this.mediaSequenceValues = {};
this.mediaSequenceValuesAudio = {};
this.discontinuities = {};
this.discontinuitiesAudio = {};
this.deltaTimes = [];
this.deltaTimesAudio = [];
try {
this._createMediaSequences()
.then(() => {
resolve();
})
.catch((err) => {
reject(err);
});
} catch (exc) {
reject(exc);
}
});
}
/**
* Add metadata timed for this VOD
*
* @param {key} key - EXT-X-DATERANGE attribute key
* @param {*} value
*/
addMetadata(key, value) {
if (this.rangeMetadata === null) {
this.rangeMetadata = {};
}
this.rangeMetadata[key] = value;
}
/**
* Retrieve master manifest Uri for this VOD
*/
getVodUri() {
return this.masterManifestUri;
}
/**
* Get all segments (duration, uri) for a specific media sequence
*
* @param {number} seqIdx - media sequence index (first is 0)
*/
getLiveMediaSequenceSegments(seqIdx) {
return this.mediaSequences[seqIdx].segments;
}
/**
* Get all audio segments (duration, uri) for a specific media sequence
*
* @param {number} seqIdx - media sequence index (first is 0)
*/
getLiveAudioSequenceSegments(seqIdx) {
return this.mediaSequences[seqIdx].audioSegments;
}
/**
* Get all segments (duration, uri)
*
*/
getMediaSegments() {
return this.segments;
}
getAudioSegments() {
return this.audioSegments;
}
/**
* Get all audio segments (duration, uri) for a specific media sequence based on audio group and lang
*
* @param {string} audioGroupId - audio group Id
* @param {string} audioLanguage - audio language
* @param {number} seqIdx - media sequence index (first is 0)
*/
getLiveMediaSequenceAudioSegments(audioGroupId, audioLanguage, seqIdx) {
try {
// # When language not found, return segments from first language.
if (!this.mediaSequences[seqIdx].audioSegments[audioGroupId]) {
audioGroupId = this._getFirstAudioGroupWithSegments();
if (!audioGroupId) {
return [];
}
}
if (!this.mediaSequences[seqIdx].audioSegments[audioGroupId][audioLanguage]) {
const fallbackLang = this._getFirstAudioLanguageWithSegments(audioGroupId);
return this.mediaSequences[seqIdx].audioSegments[audioGroupId][fallbackLang];
}
return this.mediaSequences[seqIdx].audioSegments[audioGroupId][audioLanguage];
} catch (err) {
console.error(err);
return [];
}
}
/**
* Get all subtitle segments (duration, uri) for a specific media sequence
*
* @param {string} subtitleGroupId - subtitle group Id
* @param {string} subtitleLanguage - subtitle language
* @param {number} seqIdx - media sequence index (first is 0)
*/
getLiveMediaSequenceSubtitleSegments(subtitleGroupId, subtitleLanguage, seqIdx) {
try {
// # When language not found, return segments from default language.
if (!this.mediaSequences[seqIdx].subtitleSegments[subtitleGroupId]) {
subtitleGroupId = this.DUMMY_DEFAULT_SUBTITLE_GROUP_ID;
}
if (!this.mediaSequences[seqIdx].subtitleSegments[subtitleGroupId][subtitleLanguage]) {
const fallbackLang = this.DUMMY_DEFAULT_SUBTITLE_LANGUAGE;
subtitleGroupId = this.DUMMY_DEFAULT_SUBTITLE_GROUP_ID;
return this.mediaSequences[seqIdx].subtitleSegments[subtitleGroupId][fallbackLang];
}
return this.mediaSequences[seqIdx].subtitleSegments[subtitleGroupId][subtitleLanguage];
} catch (err) {
console.error(err);
return [];
}
}
/**
* Get the available bandwidths for this VOD
*/
getBandwidths() {
return Object.keys(this.segments);
}
getAudioGroups() {
return Object.keys(this.audioSegments);
}
getAudioLangsForAudioGroup(groupId) {
return Object.keys(this.audioSegments[groupId]);
}
getAudioGroupIdForCodecs(audioCodecs, channels) {
// {
// "ec-3": [
// { "6": "audio1" }
// ]
// }
let audioGroupId;
if (!this.audioCodecsMap[audioCodecs]) {
return undefined;
}
Object.keys(this.audioCodecsMap[audioCodecs]).map((channelsKey) => {
if (channelsKey === channels) {
audioGroupId = this.audioCodecsMap[audioCodecs][channelsKey];
}
});
return audioGroupId;
}
getAudioCodecsAndChannelsForGroupId(groupId) {
let audioCodecs;
let channels;
Object.keys(this.audioCodecsMap).map((codecKey) => {
Object.keys(this.audioCodecsMap[codecKey]).map((channelsKey) => {
if (this.audioCodecsMap[codecKey][channelsKey] === groupId) {
audioCodecs = codecKey;
channels = channelsKey;
}
});
});
return [audioCodecs, channels];
}
getSubtitleGroups(all = false) {
return Object.keys(this.subtitleSegments).filter((groupId) => groupId !== this.DUMMY_DEFAULT_SUBTITLE_GROUP_ID || all);
}
getSubtitleLangsForSubtitleGroup(groupId) {
return Object.keys(this.subtitleSegments[groupId]);
}
/**
* Get the number of media sequences for this VOD
*/
getLiveMediaSequencesCount(media = "video") {
if (media === "audio") {
return this.audioSequencesCount;
} else if (media === "subtitle") {
return this.subtitleSequencesCount;
}
return this.videoSequencesCount;
}
/**
* Get the media-sequence value for the last media sequence of this VOD
*/
getLastSequenceMediaSequenceValue() {
const end = Object.keys(this.mediaSequenceValues).length - 1;
return this.mediaSequenceValues[end];
}
/**
* Get the media-sequence value for the last audio media sequence of this VOD
*/
getLastSequenceMediaSequenceValueAudio() {
const end = Object.keys(this.mediaSequenceValuesAudio).length - 1;
return this.mediaSequenceValuesAudio[end];
}
/**
* Get the media-sequence value for the last subtitle media sequence of this VOD
*/
getLastSequenceMediaSequenceValueSubtitle() {
const end = Object.keys(this.mediaSequenceValuesSubtitle).length - 1;
return this.mediaSequenceValuesSubtitle[end];
}
/**
* Get the HLS live media sequence for a specific media sequence and bandwidth
*
* @param {number} offset - add this offset to all media sequences in the EXT-X-MEDIA-SEQUENCE tag
* @param {string} bandwidth
* @param {number} seqIdx
* @param {number} discOffset - add this offset to all discontinuity sequences in the EXT-X-DISCONTINUITY-SEQUENCE tag
* @param {number} padding - add extra seconds on the EXT-X-TARGETDURATION
* @param {number} forceTargetDuration - enforce a fixed EXT-X-TARGETDURATION
*/
getLiveMediaSequences(offset, bandwidth, seqIdx, discOffset, padding, forceTargetDuration) {
const bw = this._getNearestBandwidthWithInitiatedSegments(bandwidth);
let targetDuration = this._determineTargetDuration(this.mediaSequences[seqIdx].segments[bw]);
if (padding) {
targetDuration += padding;