-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
dash_parser.js
2096 lines (1870 loc) · 72.8 KB
/
dash_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.dash.DashParser');
goog.require('goog.asserts');
goog.require('shaka.abr.Ewma');
goog.require('shaka.dash.ContentProtection');
goog.require('shaka.dash.MpdUtils');
goog.require('shaka.dash.SegmentBase');
goog.require('shaka.dash.SegmentList');
goog.require('shaka.dash.SegmentTemplate');
goog.require('shaka.log');
goog.require('shaka.media.ManifestParser');
goog.require('shaka.media.PresentationTimeline');
goog.require('shaka.media.SegmentIndex');
goog.require('shaka.net.NetworkingEngine');
goog.require('shaka.text.TextEngine');
goog.require('shaka.util.Error');
goog.require('shaka.util.Functional');
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.PeriodCombiner');
goog.require('shaka.util.StringUtils');
goog.require('shaka.util.Timer');
goog.require('shaka.util.XmlUtils');
/**
* Creates a new DASH parser.
*
* @implements {shaka.extern.ManifestParser}
* @export
*/
shaka.dash.DashParser = class {
/** Creates a new DASH parser. */
constructor() {
/** @private {?shaka.extern.ManifestConfiguration} */
this.config_ = null;
/** @private {?shaka.extern.ManifestParser.PlayerInterface} */
this.playerInterface_ = null;
/** @private {!Array.<string>} */
this.manifestUris_ = [];
/** @private {?shaka.extern.Manifest} */
this.manifest_ = null;
/** @private {number} */
this.globalId_ = 1;
/**
* A map of IDs to Stream objects.
* ID: Period@id,AdaptationSet@id,@Representation@id
* e.g.: '1,5,23'
* @private {!Object.<string, !shaka.extern.Stream>}
*/
this.streamMap_ = {};
/**
* A map of period ids to their durations
* @private {!Object.<string, number>}
*/
this.periodDurations_ = {};
/** @private {shaka.util.PeriodCombiner} */
this.periodCombiner_ = new shaka.util.PeriodCombiner();
/**
* The update period in seconds, or 0 for no updates.
* @private {number}
*/
this.updatePeriod_ = 0;
/**
* 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.Timer} */
this.updateTimer_ = new shaka.util.Timer(() => {
this.onUpdate_();
});
/** @private {!shaka.util.OperationManager} */
this.operationManager_ = new shaka.util.OperationManager();
/**
* Largest period start time seen.
* @private {?number}
*/
this.largestPeriodStartTime_ = null;
/**
* Period IDs seen in previous manifest.
* @private {!Array.<string>}
*/
this.lastManifestUpdatePeriodIds_ = [];
/**
* The minimum of the availabilityTimeOffset values among the adaptation
* sets.
* @private {number}
*/
this.minTotalAvailabilityTimeOffset_ = Infinity;
/** @private {boolean} */
this.lowLatencyMode_ = false;
}
/**
* @override
* @exportInterface
*/
configure(config) {
goog.asserts.assert(config.dash != null,
'DashManifestConfiguration should not be null!');
this.config_ = config;
}
/**
* @override
* @exportInterface
*/
async start(uri, playerInterface) {
goog.asserts.assert(this.config_, 'Must call configure() before start()!');
this.lowLatencyMode_ = playerInterface.isLowLatencyMode();
this.manifestUris_ = [uri];
this.playerInterface_ = playerInterface;
const updateDelay = await this.requestManifest_();
if (this.playerInterface_) {
this.setUpdateTimer_(updateDelay);
}
// 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);
}
goog.asserts.assert(this.manifest_, 'Manifest should be non-null!');
return this.manifest_;
}
/**
* @override
* @exportInterface
*/
stop() {
// When the parser stops, release all segment indexes, which stops their
// timers, as well.
for (const stream of Object.values(this.streamMap_)) {
if (stream.segmentIndex) {
stream.segmentIndex.release();
}
}
if (this.periodCombiner_) {
this.periodCombiner_.release();
}
this.playerInterface_ = null;
this.config_ = null;
this.manifestUris_ = [];
this.manifest_ = null;
this.streamMap_ = {};
this.periodCombiner_ = null;
if (this.updateTimer_ != null) {
this.updateTimer_.stop();
this.updateTimer_ = null;
}
return this.operationManager_.destroy();
}
/**
* @override
* @exportInterface
*/
async update() {
try {
await this.requestManifest_();
} catch (error) {
if (!this.playerInterface_ || !error) {
return;
}
goog.asserts.assert(error instanceof shaka.util.Error, 'Bad error type');
this.playerInterface_.onError(error);
}
}
/**
* @override
* @exportInterface
*/
onExpirationUpdated(sessionId, expiration) {
// No-op
}
/**
* Makes a network request for the manifest and parses the resulting data.
*
* @return {!Promise.<number>} Resolves with the time it took, in seconds, to
* fulfill the request and parse the data.
* @private
*/
async requestManifest_() {
const requestType = shaka.net.NetworkingEngine.RequestType.MANIFEST;
const type = shaka.net.NetworkingEngine.AdvancedRequestType.MPD;
const request = shaka.net.NetworkingEngine.makeRequest(
this.manifestUris_, this.config_.retryParameters);
const networkingEngine = this.playerInterface_.networkingEngine;
const startTime = Date.now();
const operation = networkingEngine.request(requestType, request, {type});
this.operationManager_.manage(operation);
const response = await operation.promise;
// Detect calls to stop().
if (!this.playerInterface_) {
return 0;
}
// For redirections add the response uri to the first entry in the
// Manifest Uris array.
if (response.uri && !this.manifestUris_.includes(response.uri)) {
this.manifestUris_.unshift(response.uri);
}
// This may throw, but it will result in a failed promise.
await this.parseManifest_(response.data, response.uri);
// Keep track of how long the longest manifest update took.
const endTime = Date.now();
const updateDuration = (endTime - startTime) / 1000.0;
this.averageUpdateDuration_.sample(1, updateDuration);
// Let the caller know how long this update took.
return updateDuration;
}
/**
* Parses the manifest XML. This also handles updates and will update the
* stored manifest.
*
* @param {BufferSource} data
* @param {string} finalManifestUri The final manifest URI, which may
* differ from this.manifestUri_ if there has been a redirect.
* @return {!Promise}
* @private
*/
async parseManifest_(data, finalManifestUri) {
const Error = shaka.util.Error;
const MpdUtils = shaka.dash.MpdUtils;
const mpd = shaka.util.XmlUtils.parseXml(data, 'MPD');
if (!mpd) {
throw new Error(
Error.Severity.CRITICAL, Error.Category.MANIFEST,
Error.Code.DASH_INVALID_XML, finalManifestUri);
}
const disableXlinkProcessing = this.config_.dash.disableXlinkProcessing;
if (disableXlinkProcessing) {
return this.processManifest_(mpd, finalManifestUri);
}
// Process the mpd to account for xlink connections.
const failGracefully = this.config_.dash.xlinkFailGracefully;
const xlinkOperation = MpdUtils.processXlinks(
mpd, this.config_.retryParameters, failGracefully, finalManifestUri,
this.playerInterface_.networkingEngine);
this.operationManager_.manage(xlinkOperation);
const finalMpd = await xlinkOperation.promise;
return this.processManifest_(finalMpd, finalManifestUri);
}
/**
* Takes a formatted MPD and converts it into a manifest.
*
* @param {!Element} mpd
* @param {string} finalManifestUri The final manifest URI, which may
* differ from this.manifestUri_ if there has been a redirect.
* @return {!Promise}
* @private
*/
async processManifest_(mpd, finalManifestUri) {
const Functional = shaka.util.Functional;
const XmlUtils = shaka.util.XmlUtils;
const manifestPreprocessor = this.config_.dash.manifestPreprocessor;
if (manifestPreprocessor) {
manifestPreprocessor(mpd);
}
// Get any Location elements. This will update the manifest location and
// the base URI.
/** @type {!Array.<string>} */
let manifestBaseUris = [finalManifestUri];
/** @type {!Array.<string>} */
const locations = XmlUtils.findChildren(mpd, 'Location')
.map(XmlUtils.getContents)
.filter(Functional.isNotNull);
if (locations.length > 0) {
const absoluteLocations = shaka.util.ManifestParserUtils.resolveUris(
manifestBaseUris, locations);
this.manifestUris_ = absoluteLocations;
manifestBaseUris = absoluteLocations;
}
const uriObjs = XmlUtils.findChildren(mpd, 'BaseURL');
const uris = uriObjs.map(XmlUtils.getContents);
const baseUris = shaka.util.ManifestParserUtils.resolveUris(
manifestBaseUris, uris);
let availabilityTimeOffset = 0;
if (uriObjs && uriObjs.length) {
availabilityTimeOffset = XmlUtils.parseAttr(
uriObjs[0], 'availabilityTimeOffset', XmlUtils.parseFloat) || 0;
}
const ignoreMinBufferTime = this.config_.dash.ignoreMinBufferTime;
let minBufferTime = 0;
if (!ignoreMinBufferTime) {
minBufferTime =
XmlUtils.parseAttr(mpd, 'minBufferTime', XmlUtils.parseDuration) || 0;
}
this.updatePeriod_ = /** @type {number} */ (XmlUtils.parseAttr(
mpd, 'minimumUpdatePeriod', XmlUtils.parseDuration, -1));
const presentationStartTime = XmlUtils.parseAttr(
mpd, 'availabilityStartTime', XmlUtils.parseDate);
let segmentAvailabilityDuration = XmlUtils.parseAttr(
mpd, 'timeShiftBufferDepth', XmlUtils.parseDuration);
const ignoreSuggestedPresentationDelay =
this.config_.dash.ignoreSuggestedPresentationDelay;
let suggestedPresentationDelay = null;
if (!ignoreSuggestedPresentationDelay) {
suggestedPresentationDelay = XmlUtils.parseAttr(
mpd, 'suggestedPresentationDelay', XmlUtils.parseDuration);
}
const ignoreMaxSegmentDuration =
this.config_.dash.ignoreMaxSegmentDuration;
let maxSegmentDuration = null;
if (!ignoreMaxSegmentDuration) {
maxSegmentDuration = XmlUtils.parseAttr(
mpd, 'maxSegmentDuration', XmlUtils.parseDuration);
}
const mpdType = mpd.getAttribute('type') || 'static';
/** @type {!shaka.media.PresentationTimeline} */
let presentationTimeline;
if (this.manifest_) {
presentationTimeline = this.manifest_.presentationTimeline;
// Before processing an update, evict from all segment indexes. Some of
// them may not get updated otherwise if their corresponding Period
// element has been dropped from the manifest since the last update.
// Without this, playback will still work, but this is necessary to
// maintain conditions that we assert on for multi-Period content.
// This gives us confidence that our state is maintained correctly, and
// that the complex logic of multi-Period eviction and period-flattening
// is correct. See also:
// https://github.com/shaka-project/shaka-player/issues/3169#issuecomment-823580634
for (const stream of Object.values(this.streamMap_)) {
if (stream.segmentIndex) {
stream.segmentIndex.evict(
presentationTimeline.getSegmentAvailabilityStart());
}
}
} else {
// DASH IOP v3.0 suggests using a default delay between minBufferTime
// and timeShiftBufferDepth. This is literally the range of all
// feasible choices for the value. Nothing older than
// timeShiftBufferDepth is still available, and anything less than
// minBufferTime will cause buffering issues.
//
// We have decided that our default will be the configured value, or
// 1.5 * minBufferTime if not configured. This is fairly conservative.
// Content providers should provide a suggestedPresentationDelay whenever
// possible to optimize the live streaming experience.
const defaultPresentationDelay =
this.config_.defaultPresentationDelay || minBufferTime * 1.5;
const presentationDelay = suggestedPresentationDelay != null ?
suggestedPresentationDelay : defaultPresentationDelay;
presentationTimeline = new shaka.media.PresentationTimeline(
presentationStartTime, presentationDelay,
this.config_.dash.autoCorrectDrift);
}
presentationTimeline.setStatic(mpdType == 'static');
const isLive = presentationTimeline.isLive();
// If it's live, we check for an override.
if (isLive && !isNaN(this.config_.availabilityWindowOverride)) {
segmentAvailabilityDuration = this.config_.availabilityWindowOverride;
}
// If it's null, that means segments are always available. This is always
// the case for VOD, and sometimes the case for live.
if (segmentAvailabilityDuration == null) {
segmentAvailabilityDuration = Infinity;
}
presentationTimeline.setSegmentAvailabilityDuration(
segmentAvailabilityDuration);
const profiles = mpd.getAttribute('profiles') || '';
/** @type {shaka.dash.DashParser.Context} */
const context = {
// Don't base on updatePeriod_ since emsg boxes can cause manifest
// updates.
dynamic: mpdType != 'static',
presentationTimeline: presentationTimeline,
period: null,
periodInfo: null,
adaptationSet: null,
representation: null,
bandwidth: 0,
indexRangeWarningGiven: false,
availabilityTimeOffset: availabilityTimeOffset,
profiles: profiles.split(','),
};
const periodsAndDuration = this.parsePeriods_(context, baseUris, mpd);
const duration = periodsAndDuration.duration;
const periods = periodsAndDuration.periods;
if (mpdType == 'static' ||
!periodsAndDuration.durationDerivedFromPeriods) {
// Ignore duration calculated from Period lengths if this is dynamic.
presentationTimeline.setDuration(duration || Infinity);
}
// The segments are available earlier than the availability start time.
// If the stream is low latency and the user has not configured the
// lowLatencyMode, but if it has been configured to activate the
// lowLatencyMode if a stream of this type is detected, we automatically
// activate the lowLatencyMode.
if (this.minTotalAvailabilityTimeOffset_ && !this.lowLatencyMode_) {
const autoLowLatencyMode = this.playerInterface_.isAutoLowLatencyMode();
if (autoLowLatencyMode) {
this.playerInterface_.enableLowLatencyMode();
this.lowLatencyMode_ = this.playerInterface_.isLowLatencyMode();
}
}
if (this.lowLatencyMode_) {
presentationTimeline.setAvailabilityTimeOffset(
this.minTotalAvailabilityTimeOffset_);
} else if (this.minTotalAvailabilityTimeOffset_) {
// If the playlist contains AvailabilityTimeOffset value, the
// streaming.lowLatencyMode value should be set to true to stream with low
// latency mode.
shaka.log.alwaysWarn('Low-latency DASH live stream detected, but ' +
'low-latency streaming mode is not enabled in Shaka Player. ' +
'Set streaming.lowLatencyMode configuration to true, and see ' +
'https://bit.ly/3clctcj for details.');
}
// Use @maxSegmentDuration to override smaller, derived values.
presentationTimeline.notifyMaxSegmentDuration(maxSegmentDuration || 1);
if (goog.DEBUG) {
presentationTimeline.assertIsValid();
}
await this.periodCombiner_.combinePeriods(periods, context.dynamic);
// These steps are not done on manifest update.
if (!this.manifest_) {
this.manifest_ = {
presentationTimeline: presentationTimeline,
variants: this.periodCombiner_.getVariants(),
textStreams: this.periodCombiner_.getTextStreams(),
imageStreams: this.periodCombiner_.getImageStreams(),
offlineSessionIds: [],
minBufferTime: minBufferTime || 0,
sequenceMode: this.config_.dash.sequenceMode,
ignoreManifestTimestampsInSegmentsMode: false,
type: shaka.media.ManifestParser.DASH,
};
// We only need to do clock sync when we're using presentation start
// time. This condition also excludes VOD streams.
if (presentationTimeline.usingPresentationStartTime()) {
const XmlUtils = shaka.util.XmlUtils;
const timingElements = XmlUtils.findChildren(mpd, 'UTCTiming');
const offset = await this.parseUtcTiming_(baseUris, timingElements);
// Detect calls to stop().
if (!this.playerInterface_) {
return;
}
presentationTimeline.setClockOffset(offset);
}
// This is the first point where we have a meaningful presentation start
// time, and we need to tell PresentationTimeline that so that it can
// maintain consistency from here on.
presentationTimeline.lockStartTime();
} else {
// Just update the variants and text streams, which may change as periods
// are added or removed.
this.manifest_.variants = this.periodCombiner_.getVariants();
this.manifest_.textStreams = this.periodCombiner_.getTextStreams();
this.manifest_.imageStreams = this.periodCombiner_.getImageStreams();
// Re-filter the manifest. This will check any configured restrictions on
// new variants, and will pass any new init data to DrmEngine to ensure
// that key rotation works correctly.
this.playerInterface_.filter(this.manifest_);
}
// Add text streams to correspond to closed captions. This happens right
// after period combining, while we still have a direct reference, so that
// any new streams will appear in the period combiner.
this.playerInterface_.makeTextStreamsForClosedCaptions(this.manifest_);
}
/**
* Reads and parses the periods from the manifest. This first does some
* partial parsing so the start and duration is available when parsing
* children.
*
* @param {shaka.dash.DashParser.Context} context
* @param {!Array.<string>} baseUris
* @param {!Element} mpd
* @return {{
* periods: !Array.<shaka.util.PeriodCombiner.Period>,
* duration: ?number,
* durationDerivedFromPeriods: boolean
* }}
* @private
*/
parsePeriods_(context, baseUris, mpd) {
const XmlUtils = shaka.util.XmlUtils;
const presentationDuration = XmlUtils.parseAttr(
mpd, 'mediaPresentationDuration', XmlUtils.parseDuration);
const periods = [];
let prevEnd = 0;
const periodNodes = XmlUtils.findChildren(mpd, 'Period');
for (let i = 0; i < periodNodes.length; i++) {
const elem = periodNodes[i];
const next = periodNodes[i + 1];
const start = /** @type {number} */ (
XmlUtils.parseAttr(elem, 'start', XmlUtils.parseDuration, prevEnd));
const periodId = elem.id;
const givenDuration =
XmlUtils.parseAttr(elem, 'duration', XmlUtils.parseDuration);
let periodDuration = null;
if (next) {
// "The difference between the start time of a Period and the start time
// of the following Period is the duration of the media content
// represented by this Period."
const nextStart =
XmlUtils.parseAttr(next, 'start', XmlUtils.parseDuration);
if (nextStart != null) {
periodDuration = nextStart - start;
}
} else if (presentationDuration != null) {
// "The Period extends until the Period.start of the next Period, or
// until the end of the Media Presentation in the case of the last
// Period."
periodDuration = presentationDuration - start;
}
const threshold =
shaka.util.ManifestParserUtils.GAP_OVERLAP_TOLERANCE_SECONDS;
if (periodDuration && givenDuration &&
Math.abs(periodDuration - givenDuration) > threshold) {
shaka.log.warning('There is a gap/overlap between Periods', elem);
}
// Only use the @duration in the MPD if we can't calculate it. We should
// favor the @start of the following Period. This ensures that there
// aren't gaps between Periods.
if (periodDuration == null) {
periodDuration = givenDuration;
}
/**
* This is to improve robustness when the player observes manifest with
* past periods that are inconsistent to previous ones.
*
* This may happen when a CDN or proxy server switches its upstream from
* one encoder to another redundant encoder.
*
* Skip periods that match all of the following criteria:
* - Start time is earlier than latest period start time ever seen
* - Period ID is never seen in the previous manifest
* - Not the last period in the manifest
*
* Periods that meet the aforementioned criteria are considered invalid
* and should be safe to discard.
*/
if (this.largestPeriodStartTime_ !== null &&
periodId !== null && start !== null &&
start < this.largestPeriodStartTime_ &&
!this.lastManifestUpdatePeriodIds_.includes(periodId) &&
i + 1 != periodNodes.length) {
shaka.log.debug(
`Skipping Period with ID ${periodId} as its start time is smaller` +
' than the largest period start time that has been seen, and ID ' +
'is unseen before');
continue;
}
// Save maximum period start time if it is the last period
if (start !== null &&
(this.largestPeriodStartTime_ === null ||
start > this.largestPeriodStartTime_)) {
this.largestPeriodStartTime_ = start;
}
// Parse child nodes.
const info = {
start: start,
duration: periodDuration,
node: elem,
isLastPeriod: periodDuration == null || !next,
};
const period = this.parsePeriod_(context, baseUris, info);
periods.push(period);
if (context.period.id && periodDuration) {
this.periodDurations_[context.period.id] = periodDuration;
}
if (periodDuration == null) {
if (next) {
// If the duration is still null and we aren't at the end, then we
// will skip any remaining periods.
shaka.log.warning(
'Skipping Period', i + 1, 'and any subsequent Periods:', 'Period',
i + 1, 'does not have a valid start time.', next);
}
// The duration is unknown, so the end is unknown.
prevEnd = null;
break;
}
prevEnd = start + periodDuration;
} // end of period parsing loop
// Replace previous seen periods with the current one.
this.lastManifestUpdatePeriodIds_ = periods.map((el) => el.id);
if (presentationDuration != null) {
if (prevEnd != presentationDuration) {
shaka.log.warning(
'@mediaPresentationDuration does not match the total duration of ',
'all Periods.');
// Assume @mediaPresentationDuration is correct.
}
return {
periods: periods,
duration: presentationDuration,
durationDerivedFromPeriods: false,
};
} else {
return {
periods: periods,
duration: prevEnd,
durationDerivedFromPeriods: true,
};
}
}
/**
* Parses a Period XML element. Unlike the other parse methods, this is not
* given the Node; it is given a PeriodInfo structure. Also, partial parsing
* was done before this was called so start and duration are valid.
*
* @param {shaka.dash.DashParser.Context} context
* @param {!Array.<string>} baseUris
* @param {shaka.dash.DashParser.PeriodInfo} periodInfo
* @return {shaka.util.PeriodCombiner.Period}
* @private
*/
parsePeriod_(context, baseUris, periodInfo) {
const Functional = shaka.util.Functional;
const XmlUtils = shaka.util.XmlUtils;
const ContentType = shaka.util.ManifestParserUtils.ContentType;
context.period = this.createFrame_(periodInfo.node, null, baseUris);
context.periodInfo = periodInfo;
context.period.availabilityTimeOffset = context.availabilityTimeOffset;
// If the period doesn't have an ID, give it one based on its start time.
if (!context.period.id) {
shaka.log.info(
'No Period ID given for Period with start time ' + periodInfo.start +
', Assigning a default');
context.period.id = '__shaka_period_' + periodInfo.start;
}
const eventStreamNodes =
XmlUtils.findChildren(periodInfo.node, 'EventStream');
const availabilityStart =
context.presentationTimeline.getSegmentAvailabilityStart();
for (const node of eventStreamNodes) {
this.parseEventStream_(
periodInfo.start, periodInfo.duration, node, availabilityStart);
}
const adaptationSetNodes =
XmlUtils.findChildren(periodInfo.node, 'AdaptationSet');
const adaptationSets = adaptationSetNodes
.map((node) => this.parseAdaptationSet_(context, node))
.filter(Functional.isNotNull);
// For dynamic manifests, we use rep IDs internally, and they must be
// unique.
if (context.dynamic) {
const ids = [];
for (const set of adaptationSets) {
for (const id of set.representationIds) {
ids.push(id);
}
}
const uniqueIds = new Set(ids);
if (ids.length != uniqueIds.size) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,
shaka.util.Error.Code.DASH_DUPLICATE_REPRESENTATION_ID);
}
}
const normalAdaptationSets = adaptationSets
.filter((as) => { return !as.trickModeFor; });
const trickModeAdaptationSets = adaptationSets
.filter((as) => { return as.trickModeFor; });
// Attach trick mode tracks to normal tracks.
for (const trickModeSet of trickModeAdaptationSets) {
const targetIds = trickModeSet.trickModeFor.split(' ');
for (const normalSet of normalAdaptationSets) {
if (targetIds.includes(normalSet.id)) {
for (const stream of normalSet.streams) {
// There may be multiple trick mode streams, but we do not
// currently support that. Just choose one.
// TODO: https://github.com/shaka-project/shaka-player/issues/1528
stream.trickModeVideo = trickModeSet.streams.find((trickStream) =>
shaka.util.MimeUtils.getNormalizedCodec(stream.codecs) ==
shaka.util.MimeUtils.getNormalizedCodec(trickStream.codecs));
}
}
}
}
const audioSets = this.config_.disableAudio ? [] :
this.getSetsOfType_(normalAdaptationSets, ContentType.AUDIO);
const videoSets = this.config_.disableVideo ? [] :
this.getSetsOfType_(normalAdaptationSets, ContentType.VIDEO);
const textSets = this.config_.disableText ? [] :
this.getSetsOfType_(normalAdaptationSets, ContentType.TEXT);
const imageSets = this.config_.disableThumbnails ? [] :
this.getSetsOfType_(normalAdaptationSets, ContentType.IMAGE);
if (!videoSets.length && !audioSets.length) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,
shaka.util.Error.Code.DASH_EMPTY_PERIOD);
}
const audioStreams = [];
for (const audioSet of audioSets) {
audioStreams.push(...audioSet.streams);
}
const videoStreams = [];
for (const videoSet of videoSets) {
videoStreams.push(...videoSet.streams);
}
const textStreams = [];
for (const textSet of textSets) {
textStreams.push(...textSet.streams);
}
const imageStreams = [];
for (const imageSet of imageSets) {
imageStreams.push(...imageSet.streams);
}
return {
id: context.period.id,
audioStreams,
videoStreams,
textStreams,
imageStreams,
};
}
/**
* @param {!Array.<!shaka.dash.DashParser.AdaptationInfo>} adaptationSets
* @param {string} type
* @return {!Array.<!shaka.dash.DashParser.AdaptationInfo>}
* @private
*/
getSetsOfType_(adaptationSets, type) {
return adaptationSets.filter((as) => {
return as.contentType == type;
});
}
/**
* Parses an AdaptationSet XML element.
*
* @param {shaka.dash.DashParser.Context} context
* @param {!Element} elem The AdaptationSet element.
* @return {?shaka.dash.DashParser.AdaptationInfo}
* @private
*/
parseAdaptationSet_(context, elem) {
const XmlUtils = shaka.util.XmlUtils;
const Functional = shaka.util.Functional;
const ManifestParserUtils = shaka.util.ManifestParserUtils;
const ContentType = ManifestParserUtils.ContentType;
const ContentProtection = shaka.dash.ContentProtection;
context.adaptationSet = this.createFrame_(elem, context.period, null);
let main = false;
const roleElements = XmlUtils.findChildren(elem, 'Role');
const roleValues = roleElements.map((role) => {
return role.getAttribute('value');
}).filter(Functional.isNotNull);
// Default kind for text streams is 'subtitle' if unspecified in the
// manifest.
let kind = undefined;
const isText = context.adaptationSet.contentType == ContentType.TEXT;
if (isText) {
kind = ManifestParserUtils.TextStreamKind.SUBTITLE;
}
for (const roleElement of roleElements) {
const scheme = roleElement.getAttribute('schemeIdUri');
if (scheme == null || scheme == 'urn:mpeg:dash:role:2011') {
// These only apply for the given scheme, but allow them to be specified
// if there is no scheme specified.
// See: DASH section 5.8.5.5
const value = roleElement.getAttribute('value');
switch (value) {
case 'main':
main = true;
break;
case 'caption':
case 'subtitle':
kind = value;
break;
}
}
}
// Parallel for HLS VIDEO-RANGE as defined in DASH-IF IOP v4.3 6.2.5.1.
let videoRange;
const videoRangeScheme = 'urn:mpeg:mpegB:cicp:TransferCharacteristics';
const getVideoRangeFromTransferCharacteristicCICP = (cicp) => {
switch (cicp) {
case 1:
case 6:
case 13:
case 14:
case 15:
return 'SDR';
case 16:
return 'PQ';
case 18:
return 'HLG';
}
return undefined;
};
const essentialProperties =
XmlUtils.findChildren(elem, 'EssentialProperty');
// ID of real AdaptationSet if this is a trick mode set:
let trickModeFor = null;
let unrecognizedEssentialProperty = false;
for (const prop of essentialProperties) {
const schemeId = prop.getAttribute('schemeIdUri');
if (schemeId == 'http://dashif.org/guidelines/trickmode') {
trickModeFor = prop.getAttribute('value');
} else if (schemeId == videoRangeScheme) {
videoRange = getVideoRangeFromTransferCharacteristicCICP(
parseInt(prop.getAttribute('value'), 10),
);
} else {
unrecognizedEssentialProperty = true;
}
}
const supplementalProperties =
XmlUtils.findChildren(elem, 'SupplementalProperty');
for (const prop of supplementalProperties) {
const schemeId = prop.getAttribute('schemeIdUri');
if (schemeId == videoRangeScheme) {
videoRange = getVideoRangeFromTransferCharacteristicCICP(
parseInt(prop.getAttribute('value'), 10),
);
}
}
const accessibilities = XmlUtils.findChildren(elem, 'Accessibility');
const LanguageUtils = shaka.util.LanguageUtils;
const closedCaptions = new Map();
for (const prop of accessibilities) {
const schemeId = prop.getAttribute('schemeIdUri');
const value = prop.getAttribute('value');
if (schemeId == 'urn:scte:dash:cc:cea-608:2015' ) {
let channelId = 1;
if (value != null) {
const channelAssignments = value.split(';');
for (const captionStr of channelAssignments) {
let channel;
let language;
// Some closed caption descriptions have channel number and
// language ("CC1=eng") others may only have language ("eng,spa").
if (!captionStr.includes('=')) {
// When the channel assignemnts are not explicitly provided and
// there are only 2 values provided, it is highly likely that the
// assignments are CC1 and CC3 (most commonly used CC streams).
// Otherwise, cycle through all channels arbitrarily (CC1 - CC4)
// in order of provided langs.
channel = `CC${channelId}`;
if (channelAssignments.length == 2) {
channelId += 2;
} else {
channelId ++;
}
language = captionStr;
} else {
const channelAndLanguage = captionStr.split('=');
// The channel info can be '1' or 'CC1'.
// If the channel info only has channel number(like '1'), add 'CC'
// as prefix so that it can be a full channel id (like 'CC1').
channel = channelAndLanguage[0].startsWith('CC') ?
channelAndLanguage[0] : `CC${channelAndLanguage[0]}`;
// 3 letters (ISO 639-2). In b/187442669, we saw a blank string
// (CC2=;CC3=), so default to "und" (the code for "undetermined").
language = channelAndLanguage[1] || 'und';
}
closedCaptions.set(channel, LanguageUtils.normalize(language));
}
} else {
// If channel and language information has not been provided, assign
// 'CC1' as channel id and 'und' as language info.
closedCaptions.set('CC1', 'und');
}
} else if (schemeId == 'urn:scte:dash:cc:cea-708:2015') {
let serviceNumber = 1;
if (value != null) {
for (const captionStr of value.split(';')) {
let service;
let language;
// Similar to CEA-608, it is possible that service # assignments
// are not explicitly provided e.g. "eng;deu;swe" In this case,
// we just cycle through the services for each language one by one.
if (!captionStr.includes('=')) {
service = `svc${serviceNumber}`;
serviceNumber ++;
language = captionStr;
} else {
// Otherwise, CEA-708 caption values take the form "
// 1=lang:eng;2=lang:deu" i.e. serviceNumber=lang:threelettercode.
const serviceAndLanguage = captionStr.split('=');
service = `svc${serviceAndLanguage[0]}`;
// The language info can be different formats, lang:eng',
// or 'lang:eng,war:1,er:1'. Extract the language info.