-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
hls_parser.js
5034 lines (4520 loc) · 172 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
* Shaka Player
* 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.abr.Ewma');
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.InitSegmentReference');
goog.require('shaka.media.ManifestParser');
goog.require('shaka.media.PresentationTimeline');
goog.require('shaka.media.QualityObserver');
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.BufferUtils');
goog.require('shaka.util.DrmUtils');
goog.require('shaka.util.ContentSteeringManager');
goog.require('shaka.util.Error');
goog.require('shaka.util.EventManager');
goog.require('shaka.util.FakeEvent');
goog.require('shaka.util.LanguageUtils');
goog.require('shaka.util.ManifestParserUtils');
goog.require('shaka.util.MimeUtils');
goog.require('shaka.util.Networking');
goog.require('shaka.util.OperationManager');
goog.require('shaka.util.Pssh');
goog.require('shaka.media.SegmentUtils');
goog.require('shaka.util.Timer');
goog.require('shaka.util.TsParser');
goog.require('shaka.util.TXml');
goog.require('shaka.util.Platform');
goog.require('shaka.util.Uint8ArrayUtils');
goog.requireType('shaka.hls.Segment');
/**
* 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();
/**
* For media playlist lazy-loading to work in livestreams, we have to assume
* that each stream of a type (video, audio, etc) has the same mappings of
* sequence number to start time.
* This map stores those relationships.
* Only used during livestreams; we do not assume that VOD content is
* aligned in that way.
* @private {!Map.<string, !Map.<number, number>>}
*/
this.mediaSequenceToStartTimeByType_ = new Map();
// Set initial maps.
const ContentType = shaka.util.ManifestParserUtils.ContentType;
this.mediaSequenceToStartTimeByType_.set(ContentType.VIDEO, new Map());
this.mediaSequenceToStartTimeByType_.set(ContentType.AUDIO, new Map());
this.mediaSequenceToStartTimeByType_.set(ContentType.TEXT, new Map());
this.mediaSequenceToStartTimeByType_.set(ContentType.IMAGE, 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
* createStreamInfoFromMediaTags_, createStreamInfoFromImageTag_ and
* createStreamInfoFromVariantTags_.
*
* @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();
/**
* The minimum sequence number for generated segments, when ignoring
* EXT-X-PROGRAM-DATE-TIME.
*
* @private {number}
*/
this.minSequenceNumber_ = -1;
/**
* The lowest time value for any of the streams, as defined by the
* EXT-X-PROGRAM-DATE-TIME value. Measured in seconds since January 1, 1970.
*
* @private {number}
*/
this.lowestSyncTime_ = Infinity;
/**
* Whether the streams have previously been "finalized"; that is to say,
* whether we have loaded enough streams to know information about the asset
* such as timing information, live status, etc.
*
* @private {boolean}
*/
this.streamsFinalized_ = false;
/**
* Whether the manifest informs about the codec to use.
*
* @private
*/
this.codecInfoInManifest_ = false;
/**
* 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(() => {
if (this.mediaElement_ && !this.config_.continueLoadingWhenPaused) {
this.eventManager_.unlisten(this.mediaElement_, 'timeupdate');
if (this.mediaElement_.paused) {
this.eventManager_.listenOnce(
this.mediaElement_, 'timeupdate', () => this.onUpdate_());
return;
}
}
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.lastTargetDuration_ = Infinity;
/** Partial segments target duration.
* @private {number}
*/
this.partialTargetDuration_ = 0;
/** @private {number} */
this.presentationDelay_ = 0;
/** @private {number} */
this.lowLatencyPresentationDelay_ = 0;
/** @private {shaka.util.OperationManager} */
this.operationManager_ = new shaka.util.OperationManager();
/** 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();
/** @private {Map.<string, string>} */
this.groupIdToCodecsMap_ = new Map();
/** 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();
/** @private {Map.<string, !shaka.extern.aesKey>} */
this.aesKeyInfoMap_ = new Map();
/** @private {Map.<string, !Promise.<shaka.extern.Response>>} */
this.aesKeyMap_ = new Map();
/** @private {Map.<string, !Promise.<shaka.extern.Response>>} */
this.identityKeyMap_ = new Map();
/** @private {Map.<!shaka.media.InitSegmentReference, ?string>} */
this.identityKidMap_ = new Map();
/** @private {boolean} */
this.lowLatencyMode_ = false;
/** @private {boolean} */
this.lowLatencyByterangeOptimization_ = false;
/**
* An ewma that tracks how long updates take.
* This is to mitigate issues caused by slow parsing on embedded devices.
* @private {!shaka.abr.Ewma}
*/
this.averageUpdateDuration_ = new shaka.abr.Ewma(5);
/** @private {?shaka.util.ContentSteeringManager} */
this.contentSteeringManager_ = null;
/** @private {boolean} */
this.needsClosedCaptionsDetection_ = true;
/** @private {Set.<string>} */
this.dateRangeIdsEmitted_ = new Set();
/** @private {shaka.util.EventManager} */
this.eventManager_ = new shaka.util.EventManager();
/** @private {HTMLMediaElement} */
this.mediaElement_ = null;
}
/**
* @override
* @exportInterface
*/
configure(config) {
this.config_ = config;
if (this.contentSteeringManager_) {
this.contentSteeringManager_.configure(this.config_);
}
}
/**
* @override
* @exportInterface
*/
async start(uri, playerInterface) {
goog.asserts.assert(this.config_, 'Must call configure() before start()!');
this.playerInterface_ = playerInterface;
this.lowLatencyMode_ = playerInterface.isLowLatencyMode();
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, uri);
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();
this.mapTagToInitSegmentRefMap_.clear();
this.aesKeyInfoMap_.clear();
this.aesKeyMap_.clear();
this.identityKeyMap_.clear();
this.identityKidMap_.clear();
this.dateRangeIdsEmitted_.clear();
if (this.contentSteeringManager_) {
this.contentSteeringManager_.destroy();
}
if (this.eventManager_) {
this.eventManager_.release();
this.eventManager_ = null;
}
return Promise.all(pending);
}
/**
* @override
* @exportInterface
*/
async update() {
if (!this.isLive_()) {
return;
}
/** @type {!Array.<!Promise>} */
const updates = [];
const streamInfos = Array.from(this.uriToStreamInfosMap_.values());
// This is necessary to calculate correctly the update time.
this.lastTargetDuration_ = Infinity;
this.manifest_.gapCount = 0;
// Only update active streams.
const activeStreamInfos = streamInfos.filter((s) => s.stream.segmentIndex);
for (const streamInfo of activeStreamInfos) {
updates.push(this.updateStream_(streamInfo));
}
await Promise.all(updates);
// Now that streams have been updated, notify the presentation timeline.
this.notifySegmentsForStreams_(activeStreamInfos.map((s) => s.stream));
// If any hasEndList is false, the stream is still live.
const stillLive = activeStreamInfos.some((s) => s.hasEndList == false);
if (activeStreamInfos.length && !stillLive) {
// Convert the presentation to VOD and set the duration.
const PresentationType = shaka.hls.HlsParser.PresentationType_;
this.setPresentationType_(PresentationType.VOD);
// The duration is the minimum of the end times of all active streams.
// Non-active streams are not guaranteed to have useful maxTimestamp
// values, due to the lazy-loading system, so they are ignored.
const maxTimestamps = activeStreamInfos.map((s) => s.maxTimestamp);
// The duration is the minimum of the end times of all streams.
this.presentationTimeline_.setDuration(Math.min(...maxTimestamps));
this.playerInterface_.updateDuration();
}
if (stillLive) {
this.determineDuration_();
}
// Check if any playlist does not have the first reference (due to a
// problem in the live encoder for example), and disable the stream if
// necessary.
for (const streamInfo of activeStreamInfos) {
if (streamInfo.stream.segmentIndex &&
!streamInfo.stream.segmentIndex.earliestReference()) {
this.playerInterface_.disableStream(streamInfo.stream);
}
}
}
/**
* @param {!shaka.hls.HlsParser.StreamInfo} streamInfo
* @return {!Map.<number, number>}
* @private
*/
getMediaSequenceToStartTimeFor_(streamInfo) {
if (this.isLive_()) {
return this.mediaSequenceToStartTimeByType_.get(streamInfo.type);
} else {
return streamInfo.mediaSequenceToStartTime;
}
}
/**
* Updates a stream.
*
* @param {!shaka.hls.HlsParser.StreamInfo} streamInfo
* @return {!Promise}
* @private
*/
async updateStream_(streamInfo) {
const manifestUris = [];
for (const uri of streamInfo.getUris()) {
const uriObj = new goog.Uri(uri);
const queryData = uriObj.getQueryData();
if (streamInfo.canBlockReload) {
if (streamInfo.nextMediaSequence >= 0) {
// Indicates that the server must hold the request until a Playlist
// contains a Media Segment with Media Sequence
queryData.add('_HLS_msn', String(streamInfo.nextMediaSequence));
}
if (streamInfo.nextPart >= 0) {
// Indicates, in combination with _HLS_msn, that the server must hold
// the request until a Playlist contains Partial Segment N of Media
// Sequence Number M or later.
queryData.add('_HLS_part', String(streamInfo.nextPart));
}
}
if (streamInfo.canSkipSegments) {
// Enable delta updates. This will replace older segments with
// 'EXT-X-SKIP' tag in the media playlist.
queryData.add('_HLS_skip', 'YES');
}
if (queryData.getCount()) {
uriObj.setQueryData(queryData);
}
manifestUris.push(uriObj.toString());
}
let response;
try {
response =
await this.requestManifest_(manifestUris, /* isPlaylist= */ true);
} catch (e) {
if (this.playerInterface_) {
this.playerInterface_.disableStream(streamInfo.stream);
}
throw e;
}
if (!streamInfo.stream.segmentIndex) {
// The stream was closed since the update was first requested.
return;
}
/** @type {shaka.hls.Playlist} */
const playlist = this.manifestTextParser_.parsePlaylist(response.data);
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);
}
// Record the final URI after redirects.
const responseUri = response.uri;
if (responseUri != response.originalUri &&
!streamInfo.getUris().includes(responseUri)) {
streamInfo.redirectUris.push(responseUri);
}
/** @type {!Array.<!shaka.hls.Tag>} */
const variablesTags = shaka.hls.Utils.filterTagsByName(playlist.tags,
'EXT-X-DEFINE');
const mediaVariables = this.parseMediaVariables_(
variablesTags, responseUri);
const stream = streamInfo.stream;
const mediaSequenceToStartTime =
this.getMediaSequenceToStartTimeFor_(streamInfo);
const {keyIds, drmInfos} = await this.parseDrmInfo_(
playlist, stream.mimeType, streamInfo.getUris, mediaVariables);
const keysAreEqual =
(a, b) => a.size === b.size && [...a].every((value) => b.has(value));
if (!keysAreEqual(stream.keyIds, keyIds)) {
stream.keyIds = keyIds;
stream.drmInfos = drmInfos;
this.playerInterface_.newDrmInfo(stream);
}
const {segments, bandwidth} = this.createSegments_(
playlist, mediaSequenceToStartTime, mediaVariables,
streamInfo.getUris, streamInfo.type);
if (bandwidth) {
stream.bandwidth = bandwidth;
}
const qualityInfo =
shaka.media.QualityObserver.createQualityInfo(stream);
for (const segment of segments) {
if (segment.initSegmentReference) {
segment.initSegmentReference.mediaQuality = qualityInfo;
}
}
stream.segmentIndex.mergeAndEvict(
segments, this.presentationTimeline_.getSegmentAvailabilityStart());
if (segments.length) {
const mediaSequenceNumber = shaka.hls.Utils.getFirstTagWithNameAsNumber(
playlist.tags, 'EXT-X-MEDIA-SEQUENCE', 0);
const skipTag = shaka.hls.Utils.getFirstTagWithName(
playlist.tags, 'EXT-X-SKIP');
const skippedSegments =
skipTag ? Number(skipTag.getAttributeValue('SKIPPED-SEGMENTS')) : 0;
const {nextMediaSequence, nextPart} =
this.getNextMediaSequenceAndPart_(mediaSequenceNumber, segments);
streamInfo.nextMediaSequence = nextMediaSequence + skippedSegments;
streamInfo.nextPart = nextPart;
const playlistStartTime = mediaSequenceToStartTime.get(
mediaSequenceNumber);
stream.segmentIndex.evict(playlistStartTime);
}
const oldSegment = stream.segmentIndex.earliestReference();
if (oldSegment) {
streamInfo.minTimestamp = oldSegment.startTime;
const newestSegment = segments[segments.length - 1];
goog.asserts.assert(newestSegment, 'Should have segments!');
streamInfo.maxTimestamp = newestSegment.endTime;
}
// 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) {
// Flag this for later. We don't convert the whole presentation into VOD
// until we've seen the ENDLIST tag for all active playlists.
streamInfo.hasEndList = true;
}
this.determineLastTargetDuration_(playlist);
this.processDateRangeTags_(
playlist.tags, stream.type, mediaVariables, streamInfo.getUris);
}
/**
* @override
* @exportInterface
*/
onExpirationUpdated(sessionId, expiration) {
// No-op
}
/**
* @override
* @exportInterface
*/
onInitialVariantChosen(variant) {
// No-op
}
/**
* @override
* @exportInterface
*/
banLocation(uri) {
if (this.contentSteeringManager_) {
this.contentSteeringManager_.banLocation(uri);
}
}
/**
* @override
* @exportInterface
*/
setMediaElement(mediaElement) {
this.mediaElement_ = mediaElement;
}
/**
* Align the streams by sequence number by dropping early segments. Then
* offset the streams to begin at presentation time 0.
* @param {!Array.<!shaka.hls.HlsParser.StreamInfo>} streamInfos
* @private
*/
syncStreamsWithSequenceNumber_(streamInfos) {
// We assume that, when this is first called, we have enough info to
// determine how to use the program date times (e.g. we have both a video
// and an audio, and all other videos and audios match those).
// Thus, we only need to calculate this once.
const updateMinSequenceNumber = this.minSequenceNumber_ == -1;
// Sync using media sequence number. Find the highest starting sequence
// number among all streams. Later, we will drop any references to
// earlier segments in other streams, then offset everything back to 0.
for (const streamInfo of streamInfos) {
const segmentIndex = streamInfo.stream.segmentIndex;
goog.asserts.assert(segmentIndex,
'Only loaded streams should be synced');
const mediaSequenceToStartTime =
this.getMediaSequenceToStartTimeFor_(streamInfo);
const segment0 = segmentIndex.earliestReference();
if (segment0) {
// This looks inefficient, but iteration order is insertion order.
// So the very first entry should be the one we want.
// We assert that this holds true so that we are alerted by debug
// builds and tests if it changes. We still do a loop, though, so
// that the code functions correctly in production no matter what.
if (goog.DEBUG) {
const firstSequenceStartTime =
mediaSequenceToStartTime.values().next().value;
if (firstSequenceStartTime != segment0.startTime) {
shaka.log.warning(
'Sequence number map is not ordered as expected!');
}
}
for (const [sequence, start] of mediaSequenceToStartTime) {
if (start == segment0.startTime) {
if (updateMinSequenceNumber) {
this.minSequenceNumber_ = Math.max(
this.minSequenceNumber_, sequence);
}
// Even if we already have decided on a value for
// |this.minSequenceNumber_|, we still need to determine the first
// sequence number for the stream, to offset it in the code below.
streamInfo.firstSequenceNumber = sequence;
break;
}
}
}
}
if (this.minSequenceNumber_ < 0) {
// Nothing to sync.
return;
}
shaka.log.debug('Syncing HLS streams against base sequence number:',
this.minSequenceNumber_);
for (const streamInfo of streamInfos) {
if (!this.ignoreManifestProgramDateTimeFor_(streamInfo.type)) {
continue;
}
const segmentIndex = streamInfo.stream.segmentIndex;
if (segmentIndex) {
// Drop any earlier references.
const numSegmentsToDrop =
this.minSequenceNumber_ - streamInfo.firstSequenceNumber;
if (numSegmentsToDrop > 0) {
segmentIndex.dropFirstReferences(numSegmentsToDrop);
// Now adjust timestamps back to begin at 0.
const segmentN = segmentIndex.earliestReference();
if (segmentN) {
const streamOffset = -segmentN.startTime;
// Modify all SegmentReferences equally.
streamInfo.stream.segmentIndex.offset(streamOffset);
// Update other parts of streamInfo the same way.
this.offsetStreamInfo_(streamInfo, streamOffset);
}
}
}
}
}
/**
* Synchronize streams by the EXT-X-PROGRAM-DATE-TIME tags attached to their
* segments. Also normalizes segment times so that the earliest segment in
* any stream is at time 0.
* @param {!Array.<!shaka.hls.HlsParser.StreamInfo>} streamInfos
* @private
*/
syncStreamsWithProgramDateTime_(streamInfos) {
// We assume that, when this is first called, we have enough info to
// determine how to use the program date times (e.g. we have both a video
// and an audio, and all other videos and audios match those).
// Thus, we only need to calculate this once.
if (this.lowestSyncTime_ == Infinity) {
for (const streamInfo of streamInfos) {
const segmentIndex = streamInfo.stream.segmentIndex;
goog.asserts.assert(segmentIndex,
'Only loaded streams should be synced');
const segment0 = segmentIndex.earliestReference();
if (segment0 != null && segment0.syncTime != null) {
this.lowestSyncTime_ =
Math.min(this.lowestSyncTime_, segment0.syncTime);
}
}
}
const lowestSyncTime = this.lowestSyncTime_;
if (lowestSyncTime == Infinity) {
// Nothing to sync.
return;
}
shaka.log.debug('Syncing HLS streams against base time:', lowestSyncTime);
for (const streamInfo of this.uriToStreamInfosMap_.values()) {
if (this.ignoreManifestProgramDateTimeFor_(streamInfo.type)) {
continue;
}
const segmentIndex = streamInfo.stream.segmentIndex;
if (segmentIndex != null) {
// A segment's startTime should be based on its syncTime vs the lowest
// syncTime across all streams. The earliest segment sync time from
// any stream will become presentation time 0. If two streams start
// e.g. 6 seconds apart in syncTime, then their first segments will
// also start 6 seconds apart in presentation time.
const segment0 = segmentIndex.earliestReference();
if (!segment0) {
continue;
}
if (segment0.syncTime == null) {
shaka.log.alwaysError('Missing EXT-X-PROGRAM-DATE-TIME for stream',
streamInfo.getUris(),
'Expect AV sync issues!');
} else {
// Stream metadata are offset by a fixed amount based on the
// first segment.
const segment0TargetTime = segment0.syncTime - lowestSyncTime;
const streamOffset = segment0TargetTime - segment0.startTime;
this.offsetStreamInfo_(streamInfo, streamOffset);
// This is computed across all segments separately to manage
// accumulated drift in durations.
for (const segment of segmentIndex) {
segment.syncAgainst(lowestSyncTime);
}
}
}
}
}
/**
* @param {!shaka.hls.HlsParser.StreamInfo} streamInfo
* @param {number} offset
* @private
*/
offsetStreamInfo_(streamInfo, offset) {
// Adjust our accounting of the minimum timestamp.
streamInfo.minTimestamp += offset;
// Adjust our accounting of the maximum timestamp.
streamInfo.maxTimestamp += offset;
goog.asserts.assert(streamInfo.maxTimestamp >= 0,
'Negative maxTimestamp after adjustment!');
// Update our map from sequence number to start time.
const mediaSequenceToStartTime =
this.getMediaSequenceToStartTimeFor_(streamInfo);
for (const [key, value] of mediaSequenceToStartTime) {
mediaSequenceToStartTime.set(key, value + offset);
}
shaka.log.debug('Offset', offset, 'applied to',
streamInfo.getUris());
}
/**
* Parses the manifest.
*
* @param {BufferSource} data
* @param {string} uri
* @return {!Promise}
* @private
*/
async parseManifest_(data, uri) {
const Utils = shaka.hls.Utils;
const ContentType = shaka.util.ManifestParserUtils.ContentType;
goog.asserts.assert(this.masterPlaylistUri_,
'Master playlist URI must be set before calling parseManifest_!');
const playlist = this.manifestTextParser_.parsePlaylist(data);
/** @type {!Array.<!shaka.hls.Tag>} */
const variablesTags = Utils.filterTagsByName(playlist.tags, 'EXT-X-DEFINE');
/** @type {!Array.<!shaka.extern.Variant>} */
let variants = [];
/** @type {!Array.<!shaka.extern.Stream>} */
let textStreams = [];
/** @type {!Array.<!shaka.extern.Stream>} */
let imageStreams = [];
// This assert is our own sanity check.
goog.asserts.assert(this.presentationTimeline_ == null,
'Presentation timeline created early!');
// We don't know if the presentation is VOD or live until we parse at least
// one media playlist, so make a VOD-style presentation timeline for now
// and change the type later if we discover this is live.
// Since the player will load the first variant chosen early in the process,
// there isn't a window during playback where the live-ness is unknown.
this.presentationTimeline_ = new shaka.media.PresentationTimeline(
/* presentationStartTime= */ null, /* delay= */ 0);
this.presentationTimeline_.setStatic(true);
const getUris = () => {
return [uri];
};
/** @type {?string} */
let mediaPlaylistType = null;
/** @type {!Map.<string, string>} */
let mediaVariables = new Map();
// Parsing a media playlist results in a single-variant stream.
if (playlist.type == shaka.hls.PlaylistType.MEDIA) {
this.needsClosedCaptionsDetection_ = false;
/** @type {!Array.<!shaka.hls.Tag>} */
const variablesTags = shaka.hls.Utils.filterTagsByName(playlist.tags,
'EXT-X-DEFINE');
mediaVariables = this.parseMediaVariables_(
variablesTags, this.masterPlaylistUri_);
// By default we assume it is video, but in a later step the correct type
// is obtained.
mediaPlaylistType = ContentType.VIDEO;
// These values can be obtained later so these default values are good.
const codecs = '';
const languageValue = '';
const channelsCount = null;
const sampleRate = null;
const closedCaptions = new Map();
const spatialAudio = false;
const characteristics = null;
const forced = false; // Only relevant for text.
const primary = true; // This is the only stream!
const name = 'Media Playlist';
// Make the stream info, with those values.
const streamInfo = await this.convertParsedPlaylistIntoStreamInfo_(
this.globalId_++, mediaVariables, playlist, getUris, uri, codecs,
mediaPlaylistType, languageValue, primary, name, channelsCount,
closedCaptions, characteristics, forced, sampleRate, spatialAudio);
this.uriToStreamInfosMap_.set(uri, streamInfo);
if (streamInfo.stream) {
const qualityInfo =
shaka.media.QualityObserver.createQualityInfo(streamInfo.stream);
streamInfo.stream.segmentIndex.forEachTopLevelReference(
(reference) => {
if (reference.initSegmentReference) {
reference.initSegmentReference.mediaQuality = qualityInfo;
}
});
}
mediaPlaylistType = streamInfo.stream.type;
// Wrap the stream from that stream info with a variant.
variants.push({
id: 0,
language: this.getLanguage_(languageValue),
disabledUntilTime: 0,
primary: true,
audio: mediaPlaylistType == 'audio' ? streamInfo.stream : null,
video: mediaPlaylistType == 'video' ? streamInfo.stream : null,
bandwidth: streamInfo.stream.bandwidth || 0,
allowedByApplication: true,
allowedByKeySystem: true,
decodingInfos: [],
});
} else {
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');
/** @type {!Array.<!shaka.hls.Tag>} */
const imageTags = Utils.filterTagsByName(
playlist.tags, 'EXT-X-IMAGE-STREAM-INF');
/** @type {!Array.<!shaka.hls.Tag>} */
const iFrameTags = Utils.filterTagsByName(
playlist.tags, 'EXT-X-I-FRAME-STREAM-INF');
/** @type {!Array.<!shaka.hls.Tag>} */
const sessionKeyTags = Utils.filterTagsByName(
playlist.tags, 'EXT-X-SESSION-KEY');
/** @type {!Array.<!shaka.hls.Tag>} */
const sessionDataTags = Utils.filterTagsByName(
playlist.tags, 'EXT-X-SESSION-DATA');
/** @type {!Array.<!shaka.hls.Tag>} */
const contentSteeringTags = Utils.filterTagsByName(
playlist.tags, 'EXT-X-CONTENT-STEERING');
this.processSessionData_(sessionDataTags);
await this.processContentSteering_(contentSteeringTags);
this.parseCodecs_(variantTags);
this.parseClosedCaptions_(mediaTags);
variants = await this.createVariantsForTags_(
variantTags, sessionKeyTags, mediaTags, getUris,
this.globalVariables_);
textStreams = this.parseTexts_(mediaTags);
imageStreams = await this.parseImages_(imageTags, iFrameTags);
}
// 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);
}
// Single-variant streams aren't lazy-loaded, so for them we already have
// enough info here to determine the presentation type and duration.
if (playlist.type == shaka.hls.PlaylistType.MEDIA) {
if (this.isLive_()) {
this.changePresentationTimelineToLive_(playlist);
const delay = this.getUpdatePlaylistDelay_();
this.updatePlaylistTimer_.tickAfter(/* seconds= */ delay);
}
const streamInfos = Array.from(this.uriToStreamInfosMap_.values());
this.finalizeStreams_(streamInfos);
this.determineDuration_();
goog.asserts.assert(mediaPlaylistType,
'mediaPlaylistType should be non-null');
this.processDateRangeTags_(
playlist.tags, mediaPlaylistType, mediaVariables, getUris);
}
this.manifest_ = {
presentationTimeline: this.presentationTimeline_,
variants,
textStreams,
imageStreams,
offlineSessionIds: [],
minBufferTime: 0,
sequenceMode: this.config_.hls.sequenceMode,
ignoreManifestTimestampsInSegmentsMode:
this.config_.hls.ignoreManifestTimestampsInSegmentsMode,
type: shaka.media.ManifestParser.HLS,
serviceDescription: null,
nextUrl: null,
periodCount: 1,
gapCount: 0,
isLowLatency: false,
};
// If there is no 'CODECS' attribute in the manifest and codec guessing is
// disabled, we need to create the segment indexes now so that missing info
// can be parsed from the media data and added to the stream objects.
if (!this.codecInfoInManifest_ && this.config_.hls.disableCodecGuessing) {
const createIndexes = [];
for (const variant of this.manifest_.variants) {
if (variant.audio && variant.audio.codecs === '') {
createIndexes.push(variant.audio.createSegmentIndex());
}
if (variant.video && variant.video.codecs === '') {
createIndexes.push(variant.video.createSegmentIndex());
}
}
await Promise.all(createIndexes);
}
this.playerInterface_.makeTextStreamsForClosedCaptions(this.manifest_);
if (variants.length == 1) {
const createSegmentIndexPromises = [];