-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathhls_parser.js
2611 lines (2288 loc) · 86.8 KB
/
hls_parser.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
/** @license
* Copyright 2016 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
goog.provide('shaka.hls.HlsParser');
goog.require('goog.Uri');
goog.require('goog.asserts');
goog.require('shaka.hls.ManifestTextParser');
goog.require('shaka.hls.Playlist');
goog.require('shaka.hls.PlaylistType');
goog.require('shaka.hls.Tag');
goog.require('shaka.hls.Utils');
goog.require('shaka.log');
goog.require('shaka.media.DrmEngine');
goog.require('shaka.media.InitSegmentReference');
goog.require('shaka.media.ManifestParser');
goog.require('shaka.media.PresentationTimeline');
goog.require('shaka.media.SegmentIndex');
goog.require('shaka.media.SegmentReference');
goog.require('shaka.net.DataUriPlugin');
goog.require('shaka.net.NetworkingEngine');
goog.require('shaka.util.ArrayUtils');
goog.require('shaka.util.DataViewReader');
goog.require('shaka.util.Error');
goog.require('shaka.util.Functional');
goog.require('shaka.util.Iterables');
goog.require('shaka.util.LanguageUtils');
goog.require('shaka.util.ManifestParserUtils');
goog.require('shaka.util.MimeUtils');
goog.require('shaka.util.Mp4Parser');
goog.require('shaka.util.Networking');
goog.require('shaka.util.OperationManager');
goog.require('shaka.util.Timer');
/**
* HLS parser.
*
* @implements {shaka.extern.ManifestParser}
* @export
*/
shaka.hls.HlsParser = class {
/**
* Creates an Hls Parser object.
*/
constructor() {
/** @private {?shaka.extern.ManifestParser.PlayerInterface} */
this.playerInterface_ = null;
/** @private {?shaka.extern.ManifestConfiguration} */
this.config_ = null;
/** @private {number} */
this.globalId_ = 1;
/** @private {!Map.<string, string>} */
this.globalVariables_ = new Map();
/**
* A map from group id to stream infos created from the media tags.
* @private {!Map.<string, !Array.<?shaka.hls.HlsParser.StreamInfo>>}
*/
this.groupIdToStreamInfosMap_ = new Map();
/**
* The values are strings of the form "<VIDEO URI> - <AUDIO URI>",
* where the URIs are the verbatim media playlist URIs as they appeared in
* the master playlist.
*
* Used to avoid duplicates that vary only in their text stream.
*
* @private {!Set.<string>}
*/
this.variantUriSet_ = new Set();
/**
* A map from (verbatim) media playlist URI to stream infos representing the
* playlists.
*
* On update, used to iterate through and update from media playlists.
*
* On initial parse, used to iterate through and determine minimum
* timestamps, offsets, and to handle TS rollover.
*
* During parsing, used to avoid duplicates in the async methods
* createStreamInfoFromMediaTag_ and createStreamInfoFromVariantTag_.
*
* During parsing of updates, used by getStartTime_ to determine the start
* time of the first segment from existing segment references.
*
* @private {!Map.<string, shaka.hls.HlsParser.StreamInfo>}
*/
this.uriToStreamInfosMap_ = new Map();
/** @private {?shaka.media.PresentationTimeline} */
this.presentationTimeline_ = null;
/**
* The master playlist URI, after redirects.
*
* @private {string}
*/
this.masterPlaylistUri_ = '';
/** @private {shaka.hls.ManifestTextParser} */
this.manifestTextParser_ = new shaka.hls.ManifestTextParser();
/**
* This is the number of seconds we want to wait between finishing a
* manifest update and starting the next one. This will be set when we parse
* the manifest.
*
* @private {number}
*/
this.updatePlaylistDelay_ = 0;
/**
* This timer is used to trigger the start of a manifest update. A manifest
* update is async. Once the update is finished, the timer will be restarted
* to trigger the next update. The timer will only be started if the content
* is live content.
*
* @private {shaka.util.Timer}
*/
this.updatePlaylistTimer_ = new shaka.util.Timer(() => {
this.onUpdate_();
});
/** @private {shaka.hls.HlsParser.PresentationType_} */
this.presentationType_ = shaka.hls.HlsParser.PresentationType_.VOD;
/** @private {?shaka.extern.Manifest} */
this.manifest_ = null;
/** @private {number} */
this.maxTargetDuration_ = 0;
/** @private {number} */
this.minTargetDuration_ = Infinity;
/** @private {shaka.util.OperationManager} */
this.operationManager_ = new shaka.util.OperationManager();
/** @private {!Array.<!Array.<!shaka.media.SegmentReference>>} */
this.segmentsToNotifyByStream_ = [];
/** A map from closed captions' group id, to a map of closed captions info.
* {group id -> {closed captions channel id -> language}}
* @private {Map.<string, Map.<string, string>>}
*/
this.groupIdToClosedCaptionsMap_ = new Map();
/** True if some of the variants in the playlist is encrypted with AES-128.
* @private {boolean} */
this.aesEncrypted_ = false;
/** @private {Map.<string, string>} */
this.groupIdToCodecsMap_ = new Map();
/** @private {?number} */
this.playlistStartTime_ = null;
/** A cache mapping EXT-X-MAP tag info to the InitSegmentReference created
* from the tag.
* The key is a string combining the EXT-X-MAP tag's absolute uri, and
* its BYTERANGE if available.
* {!Map.<string, !shaka.media.InitSegmentReference>} */
this.mapTagToInitSegmentRefMap_ = new Map();
/**
* A cache mapping a discontinuity sequence number of a segment with
* EXT-X-DISCONTINUITY tag into its timestamp offset.
* Key: the discontinuity sequence number of a segment
* Value: the segment reference's timestamp offset.
* {!Map.<number, number>}
*/
this.discontinuityToTso_ = new Map();
}
/**
* @override
* @exportInterface
*/
configure(config) {
this.config_ = config;
}
/**
* @override
* @exportInterface
*/
async start(uri, playerInterface) {
goog.asserts.assert(this.config_, 'Must call configure() before start()!');
this.playerInterface_ = playerInterface;
const response = await this.requestManifest_(uri);
// Record the master playlist URI after redirects.
this.masterPlaylistUri_ = response.uri;
goog.asserts.assert(response.data, 'Response data should be non-null!');
await this.parseManifest_(response.data);
// Start the update timer if we want updates.
const delay = this.updatePlaylistDelay_;
if (delay > 0) {
this.updatePlaylistTimer_.tickAfter(/* seconds= */ delay);
}
goog.asserts.assert(this.manifest_, 'Manifest should be non-null');
return this.manifest_;
}
/**
* @override
* @exportInterface
*/
stop() {
// Make sure we don't update the manifest again. Even if the timer is not
// running, this is safe to call.
if (this.updatePlaylistTimer_) {
this.updatePlaylistTimer_.stop();
this.updatePlaylistTimer_ = null;
}
/** @type {!Array.<!Promise>} */
const pending = [];
if (this.operationManager_) {
pending.push(this.operationManager_.destroy());
this.operationManager_ = null;
}
this.playerInterface_ = null;
this.config_ = null;
this.variantUriSet_.clear();
this.manifest_ = null;
this.uriToStreamInfosMap_.clear();
this.groupIdToStreamInfosMap_.clear();
this.groupIdToCodecsMap_.clear();
this.globalVariables_.clear();
return Promise.all(pending);
}
/**
* @override
* @exportInterface
*/
async update() {
if (!this.isLive_()) {
return;
}
/** @type {!Array.<!Promise>} */
const updates = [];
// Reset the start time for the new media playlist.
this.playlistStartTime_ = null;
const streamInfos = Array.from(this.uriToStreamInfosMap_.values());
// Wait for the first stream info created, so that the start time is fetched
// and can be reused.
if (streamInfos.length) {
await this.updateStream_(streamInfos[0]);
}
for (let i = 1; i < streamInfos.length; i++) {
updates.push(this.updateStream_(streamInfos[i]));
}
await Promise.all(updates);
}
/**
* Updates a stream.
*
* @param {!shaka.hls.HlsParser.StreamInfo} streamInfo
* @return {!Promise}
* @private
*/
async updateStream_(streamInfo) {
const PresentationType = shaka.hls.HlsParser.PresentationType_;
const manifestUri = streamInfo.absoluteMediaPlaylistUri;
const response = await this.requestManifest_(manifestUri);
/** @type {shaka.hls.Playlist} */
const playlist = this.manifestTextParser_.parsePlaylist(
response.data, response.uri);
if (playlist.type != shaka.hls.PlaylistType.MEDIA) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,
shaka.util.Error.Code.HLS_INVALID_PLAYLIST_HIERARCHY);
}
/** @type {!Array.<!shaka.hls.Tag>} */
const variablesTags = shaka.hls.Utils.filterTagsByName(playlist.tags,
'EXT-X-DEFINE');
const mediaVariables = this.parseMediaVariables_(variablesTags);
const stream = streamInfo.stream;
const segments = await this.createSegments_(
streamInfo.verbatimMediaPlaylistUri, playlist, stream.type,
stream.mimeType, streamInfo.mediaSequenceToStartTime, mediaVariables);
stream.segmentIndex.merge(segments);
if (segments.length) {
stream.segmentIndex.evict(segments[0].startTime);
}
const newestSegment = segments[segments.length - 1];
goog.asserts.assert(newestSegment, 'Should have segments!');
// Once the last segment has been added to the playlist,
// #EXT-X-ENDLIST tag will be appended.
// If that happened, treat the rest of the EVENT presentation as VOD.
const endListTag =
shaka.hls.Utils.getFirstTagWithName(playlist.tags, 'EXT-X-ENDLIST');
if (endListTag) {
// Convert the presentation to VOD and set the duration to the last
// segment's end time.
this.setPresentationType_(PresentationType.VOD);
this.presentationTimeline_.setDuration(newestSegment.endTime);
}
}
/**
* @override
* @exportInterface
*/
onExpirationUpdated(sessionId, expiration) {
// No-op
}
/**
* Parses the manifest.
*
* @param {BufferSource} data
* @return {!Promise}
* @private
*/
async parseManifest_(data) {
const Utils = shaka.hls.Utils;
goog.asserts.assert(this.masterPlaylistUri_,
'Master playlist URI must be set before calling parseManifest_!');
const playlist = this.manifestTextParser_.parsePlaylist(
data, this.masterPlaylistUri_);
// We don't support directly providing a Media Playlist.
// See the error code for details.
if (playlist.type != shaka.hls.PlaylistType.MASTER) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,
shaka.util.Error.Code.HLS_MASTER_PLAYLIST_NOT_PROVIDED);
}
/** @type {!Array.<!shaka.hls.Tag>} */
const variablesTags = Utils.filterTagsByName(playlist.tags, 'EXT-X-DEFINE');
this.parseMasterVariables_(variablesTags);
/** @type {!Array.<!shaka.hls.Tag>} */
const mediaTags = Utils.filterTagsByName(playlist.tags, 'EXT-X-MEDIA');
/** @type {!Array.<!shaka.hls.Tag>} */
const variantTags = Utils.filterTagsByName(
playlist.tags, 'EXT-X-STREAM-INF');
this.parseCodecs_(variantTags);
// Parse audio and video media tags first, so that we can extract segment
// start time from audio/video streams and reuse for text streams.
await this.createStreamInfosFromMediaTags_(mediaTags);
this.parseClosedCaptions_(mediaTags);
const variants = await this.createVariantsForTags_(variantTags);
const textStreams = await this.parseTexts_(mediaTags);
// Make sure that the parser has not been destroyed.
if (!this.playerInterface_) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.PLAYER,
shaka.util.Error.Code.OPERATION_ABORTED);
}
if (this.aesEncrypted_ && variants.length == 0) {
// We do not support AES-128 encryption with HLS yet. Variants is null
// when the playlist is encrypted with AES-128.
shaka.log.info('No stream is created, because we don\'t support AES-128',
'encryption yet');
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,
shaka.util.Error.Code.HLS_AES_128_ENCRYPTION_NOT_SUPPORTED);
}
// Find the min and max timestamp of the earliest segment in all streams.
// Find the minimum duration of all streams as well.
let minFirstTimestamp = Infinity;
let minDuration = Infinity;
for (const streamInfo of this.uriToStreamInfosMap_.values()) {
minFirstTimestamp =
Math.min(minFirstTimestamp, streamInfo.minTimestamp);
if (streamInfo.stream.type != 'text') {
minDuration = Math.min(minDuration,
streamInfo.maxTimestamp - streamInfo.minTimestamp);
}
}
// This assert is our own sanity check.
goog.asserts.assert(this.presentationTimeline_ == null,
'Presentation timeline created early!');
this.createPresentationTimeline_();
// This assert satisfies the compiler that it is not null for the rest of
// the method.
goog.asserts.assert(this.presentationTimeline_,
'Presentation timeline not created!');
if (this.isLive_()) {
// The HLS spec (RFC 8216) states in 6.3.4:
// "the client MUST wait for at least the target duration before
// attempting to reload the Playlist file again"
this.updatePlaylistDelay_ = this.minTargetDuration_;
// The spec says nothing much about seeking in live content, but Safari's
// built-in HLS implementation does not allow it. Therefore we will set
// the availability window equal to the presentation delay. The player
// will be able to buffer ahead three segments, but the seek window will
// be zero-sized.
const PresentationType = shaka.hls.HlsParser.PresentationType_;
if (this.presentationType_ == PresentationType.LIVE) {
// This defaults to the presentation delay, which has the effect of
// making the live stream unseekable. This is consistent with Apple's
// HLS implementation.
let segmentAvailabilityDuration = this.presentationTimeline_.getDelay();
// The app can override that with a longer duration, to allow seeking.
if (!isNaN(this.config_.availabilityWindowOverride)) {
segmentAvailabilityDuration = this.config_.availabilityWindowOverride;
}
this.presentationTimeline_.setSegmentAvailabilityDuration(
segmentAvailabilityDuration);
}
} else {
// For VOD/EVENT content, offset everything back to 0.
// Use the minimum timestamp as the offset for all streams.
// Use the minimum duration as the presentation duration.
this.presentationTimeline_.setDuration(minDuration);
// Use a negative offset to adjust towards 0.
this.presentationTimeline_.offset(-minFirstTimestamp);
for (const streamInfo of this.uriToStreamInfosMap_.values()) {
// The segments were created with actual media times, rather than
// presentation-aligned times, so offset them all now.
streamInfo.stream.segmentIndex.offset(-minFirstTimestamp);
// Finally, fit the segments to the playlist duration.
streamInfo.stream.segmentIndex.fit(/* periodStart= */ 0, minDuration);
}
}
this.manifest_ = {
presentationTimeline: this.presentationTimeline_,
variants,
textStreams,
offlineSessionIds: [],
minBufferTime: 0,
};
this.playerInterface_.filter(this.manifest_);
}
/**
* Get the variables of each variant tag, and store in a map.
* @param {!Array.<!shaka.hls.Tag>} tags Variant tags from the playlist.
* @private
*/
parseMasterVariables_(tags) {
for (const variableTag of tags) {
const name = variableTag.getAttributeValue('NAME');
const value = variableTag.getAttributeValue('VALUE');
if (name && value) {
if (!this.globalVariables_.has(name)) {
this.globalVariables_.set(name, value);
}
}
}
}
/**
* Get the variables of each variant tag, and store in a map.
* @param {!Array.<!shaka.hls.Tag>} tags Variant tags from the playlist.
* @return {!Map.<string, string>}
* @private
*/
parseMediaVariables_(tags) {
const mediaVariables = new Map();
for (const variableTag of tags) {
const name = variableTag.getAttributeValue('NAME');
const value = variableTag.getAttributeValue('VALUE');
const mediaImport = variableTag.getAttributeValue('IMPORT');
if (name && value) {
mediaVariables.set(name, value);
}
if (mediaImport) {
const globalValue = this.globalVariables_.get(mediaImport);
if (globalValue) {
mediaVariables.set(mediaImport, globalValue);
}
}
}
return mediaVariables;
}
/**
* Get the codecs of each variant tag, and store in a map from
* audio/video/subtitle group id to the codecs arraylist.
* @param {!Array.<!shaka.hls.Tag>} tags Variant tags from the playlist.
* @private
*/
parseCodecs_(tags) {
const ContentType = shaka.util.ManifestParserUtils.ContentType;
for (const variantTag of tags) {
const audioGroupId = variantTag.getAttributeValue('AUDIO');
const videoGroupId = variantTag.getAttributeValue('VIDEO');
const subGroupId = variantTag.getAttributeValue('SUBTITLES');
const allCodecs = this.getCodecsForVariantTag_(variantTag);
if (subGroupId) {
const textCodecs = this.guessCodecsSafe_(ContentType.TEXT, allCodecs);
goog.asserts.assert(textCodecs != null, 'Text codecs should be valid.');
this.groupIdToCodecsMap_.set(subGroupId, textCodecs);
shaka.util.ArrayUtils.remove(allCodecs, textCodecs);
}
if (audioGroupId) {
const codecs = this.guessCodecs_(ContentType.AUDIO, allCodecs);
this.groupIdToCodecsMap_.set(audioGroupId, codecs);
}
if (videoGroupId) {
const codecs = this.guessCodecs_(ContentType.VIDEO, allCodecs);
this.groupIdToCodecsMap_.set(videoGroupId, codecs);
}
}
}
/**
* Parse Subtitles and Closed Captions from 'EXT-X-MEDIA' tags.
* Create text streams for Subtitles, but not Closed Captions.
*
* @param {!Array.<!shaka.hls.Tag>} mediaTags Media tags from the playlist.
* @return {!Promise.<!Array.<!shaka.extern.Stream>>}
* @private
*/
async parseTexts_(mediaTags) {
// Create text stream for each Subtitle media tag.
const subtitleTags =
shaka.hls.Utils.filterTagsByType(mediaTags, 'SUBTITLES');
const textStreamPromises = subtitleTags.map(async (tag) => {
const disableText = this.config_.disableText;
if (disableText) {
return null;
}
try {
const streamInfo = await this.createStreamInfoFromMediaTag_(tag);
goog.asserts.assert(
streamInfo, 'Should always have a streamInfo for text');
return streamInfo.stream;
} catch (e) {
if (this.config_.hls.ignoreTextStreamFailures) {
return null;
}
throw e;
}
});
const textStreams = await Promise.all(textStreamPromises);
// Set the codecs for text streams.
for (const tag of subtitleTags) {
const groupId = tag.getRequiredAttrValue('GROUP-ID');
const codecs = this.groupIdToCodecsMap_.get(groupId);
if (codecs) {
const textStreamInfos = this.groupIdToStreamInfosMap_.get(groupId);
if (textStreamInfos) {
for (const textStreamInfo of textStreamInfos) {
textStreamInfo.stream.codecs = codecs;
}
}
}
}
// Do not create text streams for Closed captions.
return textStreams.filter((s) => s);
}
/**
* @param {!Array.<!shaka.hls.Tag>} mediaTags Media tags from the playlist.
* @private
*/
async createStreamInfosFromMediaTags_(mediaTags) {
// Filter out subtitles and media tags without uri.
mediaTags = mediaTags.filter((tag) => {
const uri = tag.getAttributeValue('URI') || '';
const type = tag.getAttributeValue('TYPE');
return type != 'SUBTITLES' && uri != '';
});
// Create stream info for each audio / video media tag.
// Wait for the first stream info created, so that the start time is fetched
// and can be reused.
if (mediaTags.length) {
await this.createStreamInfoFromMediaTag_(mediaTags[0]);
}
const promises = mediaTags.slice(1).map((tag) => {
return this.createStreamInfoFromMediaTag_(tag);
});
await Promise.all(promises);
}
/**
* @param {!Array.<!shaka.hls.Tag>} tags Variant tags from the playlist.
* @return {!Promise.<!Array.<!shaka.extern.Variant>>}
* @private
*/
async createVariantsForTags_(tags) {
// Create variants for each variant tag.
const variantsPromises = tags.map(async (tag) => {
const frameRate = tag.getAttributeValue('FRAME-RATE');
const bandwidth = Number(tag.getRequiredAttrValue('BANDWIDTH'));
const resolution = tag.getAttributeValue('RESOLUTION');
const [width, height] = resolution ? resolution.split('x') : [null, null];
const streamInfos = await this.createStreamInfosForVariantTag_(tag,
resolution, frameRate);
if (streamInfos) {
goog.asserts.assert(streamInfos.audio.length ||
streamInfos.video.length, 'We should have created a stream!');
return this.createVariants_(
streamInfos.audio,
streamInfos.video,
bandwidth,
width,
height,
frameRate);
}
// We do not support AES-128 encryption with HLS yet. If the streamInfos
// is null because of AES-128 encryption, do not create variants for that.
return [];
});
const allVariants = await Promise.all(variantsPromises);
let variants = allVariants.reduce(shaka.util.Functional.collapseArrays, []);
// Filter out null variants.
variants = variants.filter((variant) => variant != null);
return variants;
}
/**
* Create audio and video streamInfos from an 'EXT-X-STREAM-INF' tag and its
* related media tags.
*
* @param {!shaka.hls.Tag} tag
* @param {?string} resolution
* @param {?string} frameRate
* @return {!Promise.<?shaka.hls.HlsParser.StreamInfos>}
* @private
*/
async createStreamInfosForVariantTag_(tag, resolution, frameRate) {
const ContentType = shaka.util.ManifestParserUtils.ContentType;
/** @type {!Array.<string>} */
let allCodecs = this.getCodecsForVariantTag_(tag);
const audioGroupId = tag.getAttributeValue('AUDIO');
const videoGroupId = tag.getAttributeValue('VIDEO');
goog.asserts.assert(audioGroupId == null || videoGroupId == null,
'Unexpected: both video and audio described by media tags!');
const groupId = audioGroupId || videoGroupId;
const streamInfos =
(groupId && this.groupIdToStreamInfosMap_.has(groupId)) ?
this.groupIdToStreamInfosMap_.get(groupId) : [];
/** @type {shaka.hls.HlsParser.StreamInfos} */
const res = {
audio: audioGroupId ? streamInfos : [],
video: videoGroupId ? streamInfos : [],
};
// Make an educated guess about the stream type.
shaka.log.debug('Guessing stream type for', tag.toString());
let type;
let ignoreStream = false;
// The Microsoft HLS manifest generators will make audio-only variants
// that link to their URI both directly and through an audio tag.
// In that case, ignore the local URI and use the version in the
// AUDIO tag, so you inherit its language.
// As an example, see the manifest linked in issue #860.
const streamURI = tag.getRequiredAttrValue('URI');
const hasSameUri = res.audio.find((audio) => {
return audio && audio.verbatimMediaPlaylistUri == streamURI;
});
const videoCodecs = this.guessCodecsSafe_(ContentType.VIDEO, allCodecs);
const hasVideoRelatedInfo = resolution || frameRate || videoCodecs;
if (allCodecs.length == 1 && !hasVideoRelatedInfo) {
// There are no associated media tags, and there's only one codec, and no
// video related information, so it should be audio.
type = ContentType.AUDIO;
shaka.log.debug('Guessing audio-only.');
} else if (!streamInfos.length && allCodecs.length > 1) {
// There are multiple codecs, so assume multiplexed content.
// Note that the default used when CODECS is missing assumes multiple
// (and therefore multiplexed).
// Recombine the codec strings into one so that MediaSource isn't
// lied to later. (That would trigger an error in Chrome.)
shaka.log.debug('Guessing multiplexed audio+video.');
type = ContentType.VIDEO;
allCodecs = [allCodecs.join(',')];
} else if (res.audio.length && hasSameUri) {
shaka.log.debug('Guessing audio-only.');
type = ContentType.AUDIO;
ignoreStream = true;
} else if (res.video.length) {
// There are associated video streams. Assume this is audio.
shaka.log.debug('Guessing audio-only.');
type = ContentType.AUDIO;
} else {
shaka.log.debug('Guessing video-only.');
type = ContentType.VIDEO;
}
let streamInfo;
if (!ignoreStream) {
streamInfo =
await this.createStreamInfoFromVariantTag_(tag, allCodecs, type);
}
if (streamInfo) {
res[streamInfo.stream.type] = [streamInfo];
} else if (streamInfo === null) {
// Triple-equals for undefined.
shaka.log.debug('streamInfo is null');
return null;
}
this.filterLegacyCodecs_(res);
return res;
}
/**
* Get the codecs from the 'EXT-X-STREAM-INF' tag.
*
* @param {!shaka.hls.Tag} tag
* @return {!Array.<string>} codecs
* @private
*/
getCodecsForVariantTag_(tag) {
// These are the default codecs to assume if none are specified.
// The video codec is H.264, with baseline profile and level 3.0.
// http://blog.pearce.org.nz/2013/11/what-does-h264avc1-codecs-parameters.html
// The audio codec is "low-complexity" AAC.
const defaultCodecs = 'avc1.42E01E,mp4a.40.2';
const codecsString = tag.getAttributeValue('CODECS', defaultCodecs);
// Strip out internal whitespace while splitting on commas:
/** @type {!Array.<string>} */
const codecs = codecsString.split(/\s*,\s*/);
// Filter out duplicate codecs.
const seen = new Set();
const ret = [];
for (const codec of codecs) {
// HLS says the CODECS field needs to include all codecs that appear in
// the content. This means that if the content changes profiles, it should
// include both. Since all known browsers support changing profiles
// without any other work, just ignore them. See also:
// https://github.com/google/shaka-player/issues/1817
const shortCodec = shaka.util.MimeUtils.getCodecBase(codec);
if (!seen.has(shortCodec)) {
ret.push(codec);
seen.add(shortCodec);
} else {
shaka.log.debug('Ignoring duplicate codec');
}
}
return ret;
}
/**
* Get the channel count information for an HLS audio track.
* CHANNELS specifies an ordered, "/" separated list of parameters.
* If the type is audio, the first parameter will be a decimal integer
* specifying the number of independent, simultaneous audio channels.
* No other channels parameters are currently defined.
*
* @param {!shaka.hls.Tag} tag
* @return {?number}
* @private
*/
getChannelsCount_(tag) {
const channels = tag.getAttributeValue('CHANNELS');
if (!channels) {
return null;
}
const channelcountstring = channels.split('/')[0];
const count = parseInt(channelcountstring, 10);
return count;
}
/**
* Get the closed captions map information for the EXT-X-STREAM-INF tag, to
* create the stream info.
* @param {!shaka.hls.Tag} tag
* @param {string} type
* @return {Map.<string, string>} closedCaptions
* @private
*/
getClosedCaptions_(tag, type) {
const ContentType = shaka.util.ManifestParserUtils.ContentType;
// The attribute of closed captions is optional, and the value may be
// 'NONE'.
const closedCaptionsAttr = tag.getAttributeValue('CLOSED-CAPTIONS');
// EXT-X-STREAM-INF tags may have CLOSED-CAPTIONS attributes.
// The value can be either a quoted-string or an enumerated-string with
// the value NONE. If the value is a quoted-string, it MUST match the
// value of the GROUP-ID attribute of an EXT-X-MEDIA tag elsewhere in the
// Playlist whose TYPE attribute is CLOSED-CAPTIONS.
if (type == ContentType.VIDEO && closedCaptionsAttr &&
closedCaptionsAttr != 'NONE') {
return this.groupIdToClosedCaptionsMap_.get(closedCaptionsAttr);
}
return null;
}
/**
* Get the language value.
*
* @param {!shaka.hls.Tag} tag
* @return {string}
* @private
*/
getLanguage_(tag) {
const LanguageUtils = shaka.util.LanguageUtils;
const languageValue = tag.getAttributeValue('LANGUAGE') || 'und';
return LanguageUtils.normalize(languageValue);
}
/**
* Get the type value.
* Shaka recognizes the content types 'audio', 'video' and 'text'.
* The HLS 'subtitles' type needs to be mapped to 'text'.
* @param {!shaka.hls.Tag} tag
* @return {string}
* @private
*/
getType_(tag) {
let type = tag.getRequiredAttrValue('TYPE').toLowerCase();
if (type == 'subtitles') {
type = shaka.util.ManifestParserUtils.ContentType.TEXT;
}
return type;
}
/**
* Filters out unsupported codec strings from an array of stream infos.
* @param {shaka.hls.HlsParser.StreamInfos} streamInfos
* @private
*/
filterLegacyCodecs_(streamInfos) {
for (const streamInfo of streamInfos.audio.concat(streamInfos.video)) {
if (!streamInfo) {
continue;
}
let codecs = streamInfo.stream.codecs.split(',');
codecs = codecs.filter((codec) => {
// mp4a.40.34 is a nonstandard codec string that is sometimes used in
// HLS for legacy reasons. It is not recognized by non-Apple MSE.
// See https://bugs.chromium.org/p/chromium/issues/detail?id=489520
// Therefore, ignore this codec string.
return codec != 'mp4a.40.34';
});
streamInfo.stream.codecs = codecs.join(',');
}
}
/**
* @param {!Array.<shaka.hls.HlsParser.StreamInfo>} audioInfos
* @param {!Array.<shaka.hls.HlsParser.StreamInfo>} videoInfos
* @param {number} bandwidth
* @param {?string} width
* @param {?string} height
* @param {?string} frameRate
* @return {!Array.<!shaka.extern.Variant>}
* @private
*/
createVariants_(audioInfos, videoInfos, bandwidth, width, height, frameRate) {
const ContentType = shaka.util.ManifestParserUtils.ContentType;
const DrmEngine = shaka.media.DrmEngine;
for (const info of videoInfos) {
this.addVideoAttributes_(info.stream, width, height, frameRate);
}
// In case of audio-only or video-only content or the audio/video is
// disabled by the config, we create an array of one item containing
// a null. This way, the double-loop works for all kinds of content.
// NOTE: we currently don't have support for audio-only content.
const disableAudio = this.config_.disableAudio;
if (!audioInfos.length || disableAudio) {
audioInfos = [null];
}
const disableVideo = this.config_.disableVideo;
if (!videoInfos.length || disableVideo) {
videoInfos = [null];
}
const variants = [];
for (const audioInfo of audioInfos) {
for (const videoInfo of videoInfos) {
const audioStream = audioInfo ? audioInfo.stream : null;
const videoStream = videoInfo ? videoInfo.stream : null;
const audioDrmInfos = audioInfo ? audioInfo.stream.drmInfos : null;
const videoDrmInfos = videoInfo ? videoInfo.stream.drmInfos : null;
const videoStreamUri =
videoInfo ? videoInfo.verbatimMediaPlaylistUri : '';
const audioStreamUri =
audioInfo ? audioInfo.verbatimMediaPlaylistUri : '';
const variantUriKey = videoStreamUri + ' - ' + audioStreamUri;
if (audioStream && videoStream) {
if (!DrmEngine.areDrmCompatible(audioDrmInfos, videoDrmInfos)) {
shaka.log.warning(
'Incompatible DRM info in HLS variant. Skipping.');
continue;
}
}
if (this.variantUriSet_.has(variantUriKey)) {
// This happens when two variants only differ in their text streams.
shaka.log.debug(
'Skipping variant which only differs in text streams.');
continue;
}
// Since both audio and video are of the same type, this assertion will
// catch certain mistakes at runtime that the compiler would miss.
goog.asserts.assert(!audioStream ||
audioStream.type == ContentType.AUDIO, 'Audio parameter mismatch!');
goog.asserts.assert(!videoStream ||
videoStream.type == ContentType.VIDEO, 'Video parameter mismatch!');
const variant = {
id: this.globalId_++,
language: audioStream ? audioStream.language : 'und',
primary: (!!audioStream && audioStream.primary) ||
(!!videoStream && videoStream.primary),
audio: audioStream,
video: videoStream,
bandwidth,
allowedByApplication: true,
allowedByKeySystem: true,
};
variants.push(variant);
this.variantUriSet_.add(variantUriKey);
}
}
return variants;
}
/**
* Parses an array of EXT-X-MEDIA tags, then stores the values of all tags
* with TYPE="CLOSED-CAPTIONS" into a map of group id to closed captions.
*
* @param {!Array.<!shaka.hls.Tag>} mediaTags
* @private
*/
parseClosedCaptions_(mediaTags) {
const closedCaptionsTags =
shaka.hls.Utils.filterTagsByType(mediaTags, 'CLOSED-CAPTIONS');
for (const tag of closedCaptionsTags) {
goog.asserts.assert(tag.name == 'EXT-X-MEDIA',
'Should only be called on media tags!');
const language = this.getLanguage_(tag);