-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathdash_parser.js
3523 lines (3180 loc) · 121 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('goog.Uri');
goog.require('shaka.Deprecate');
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.Capabilities');
goog.require('shaka.media.ManifestParser');
goog.require('shaka.media.PresentationTimeline');
goog.require('shaka.media.SegmentIndex');
goog.require('shaka.media.SegmentUtils');
goog.require('shaka.net.NetworkingEngine');
goog.require('shaka.text.TextEngine');
goog.require('shaka.util.ContentSteeringManager');
goog.require('shaka.util.Error');
goog.require('shaka.util.EventManager');
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.ObjectUtils');
goog.require('shaka.util.OperationManager');
goog.require('shaka.util.PeriodCombiner');
goog.require('shaka.util.PlayerConfiguration');
goog.require('shaka.util.StreamUtils');
goog.require('shaka.util.StringUtils');
goog.require('shaka.util.Timer');
goog.require('shaka.util.TXml');
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;
/** @private {!Array<shaka.extern.xml.Node>} */
this.patchLocationNodes_ = [];
/**
* A context of the living manifest used for processing
* Patch MPD's
* @private {!shaka.dash.DashParser.PatchContext}
*/
this.manifestPatchContext_ = {
mpdId: '',
type: '',
profiles: [],
mediaPresentationDuration: null,
availabilityTimeOffset: 0,
getBaseUris: null,
publishTime: 0,
};
/**
* This is a cache is used the store a snapshot of the context
* object which is built up throughout node traversal to maintain
* a current state. This data needs to be preserved for parsing
* patches.
* The key is a combination period and representation id's.
* @private {!Map<string, !shaka.dash.DashParser.Context>}
*/
this.contextCache_ = new Map();
/**
* A map of IDs to Stream objects.
* ID: Period@id,Representation@id
* e.g.: '1,23'
* @private {!Map<string, !shaka.extern.Stream>}
*/
this.streamMap_ = new Map();
/**
* A map of Period IDs to Stream Map IDs.
* Use to have direct access to streamMap key.
* @private {!Map<string, !Array<string>>}
*/
this.indexStreamMap_ = new Map();
/**
* A map of period ids to their durations
* @private {!Map<string, number>}
*/
this.periodDurations_ = new Map();
/** @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(() => {
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.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;
/** @private {?shaka.util.ContentSteeringManager} */
this.contentSteeringManager_ = null;
/** @private {number} */
this.gapCount_ = 0;
/** @private {boolean} */
this.isLowLatency_ = false;
/** @private {shaka.util.EventManager} */
this.eventManager_ = new shaka.util.EventManager();
/** @private {HTMLMediaElement} */
this.mediaElement_ = null;
/** @private {boolean} */
this.isTransitionFromDynamicToStatic_ = false;
/** @private {string} */
this.lastManifestQueryParams_ = '';
/** @private {function():boolean} */
this.isPreloadFn_ = () => false;
/** @private {?Array<string>} */
this.lastCalculatedBaseUris_ = [];
}
/**
* @param {shaka.extern.ManifestConfiguration} config
* @param {(function():boolean)=} isPreloadFn
* @override
* @exportInterface
*/
configure(config, isPreloadFn) {
goog.asserts.assert(config.dash != null,
'DashManifestConfiguration should not be null!');
const needFireUpdate = this.playerInterface_ &&
config.updatePeriod != this.config_.updatePeriod &&
config.updatePeriod >= 0;
this.config_ = config;
if (isPreloadFn) {
this.isPreloadFn_ = isPreloadFn;
}
if (needFireUpdate && this.manifest_ &&
this.manifest_.presentationTimeline.isLive()) {
this.updateNow_();
}
if (this.contentSteeringManager_) {
this.contentSteeringManager_.configure(this.config_);
}
if (this.periodCombiner_) {
this.periodCombiner_.setAllowMultiTypeVariants(
this.config_.dash.multiTypeVariantsAllowed &&
shaka.media.Capabilities.isChangeTypeSupported());
this.periodCombiner_.setUseStreamOnce(
this.config_.dash.useStreamOnceInPeriodFlattening);
}
}
/**
* @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 this.streamMap_.values()) {
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_.clear();
this.indexStreamMap_.clear();
this.contextCache_.clear();
this.manifestPatchContext_ = {
mpdId: '',
type: '',
profiles: [],
mediaPresentationDuration: null,
availabilityTimeOffset: 0,
getBaseUris: null,
publishTime: 0,
};
this.periodCombiner_ = null;
if (this.updateTimer_ != null) {
this.updateTimer_.stop();
this.updateTimer_ = null;
}
if (this.contentSteeringManager_) {
this.contentSteeringManager_.destroy();
}
if (this.eventManager_) {
this.eventManager_.release();
this.eventManager_ = 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
}
/**
* @override
* @exportInterface
*/
onInitialVariantChosen(variant) {
// For live it is necessary that the first time we update the manifest with
// a shorter time than indicated to take into account that the last segment
// added could be halfway, for example
if (this.manifest_ && this.manifest_.presentationTimeline.isLive()) {
const stream = variant.video || variant.audio;
if (stream && stream.segmentIndex) {
const availabilityEnd =
this.manifest_.presentationTimeline.getSegmentAvailabilityEnd();
const position = stream.segmentIndex.find(availabilityEnd);
if (position == null) {
return;
}
const reference = stream.segmentIndex.get(position);
if (!reference) {
return;
}
this.updatePeriod_ = reference.endTime - availabilityEnd;
this.setUpdateTimer_(/* offset= */ 0);
}
}
}
/**
* @override
* @exportInterface
*/
banLocation(uri) {
if (this.contentSteeringManager_) {
this.contentSteeringManager_.banLocation(uri);
}
}
/**
* @override
* @exportInterface
*/
setMediaElement(mediaElement) {
this.mediaElement_ = mediaElement;
}
/**
* 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;
let type = shaka.net.NetworkingEngine.AdvancedRequestType.MPD;
let rootElement = 'MPD';
const patchLocationUris = this.getPatchLocationUris_();
let manifestUris = this.manifestUris_;
if (patchLocationUris.length) {
manifestUris = patchLocationUris;
rootElement = 'Patch';
type = shaka.net.NetworkingEngine.AdvancedRequestType.MPD_PATCH;
} else if (this.manifestUris_.length > 1 && this.contentSteeringManager_) {
const locations = this.contentSteeringManager_.getLocations(
'Location', /* ignoreBaseUrls= */ true);
if (locations.length) {
manifestUris = locations;
}
}
const request = shaka.net.NetworkingEngine.makeRequest(
manifestUris, this.config_.retryParameters);
const startTime = Date.now();
const response = await this.makeNetworkRequest_(
request, requestType, {type});
// 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 && response.uri != response.originalUri &&
!this.manifestUris_.includes(response.uri)) {
this.manifestUris_.unshift(response.uri);
}
const uriObj = new goog.Uri(response.uri);
this.lastManifestQueryParams_ = uriObj.getQueryData().toString();
// This may throw, but it will result in a failed promise.
await this.parseManifest_(response.data, response.uri, rootElement);
// 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.
* @param {string} rootElement MPD or Patch, depending on context
* @return {!Promise}
* @private
*/
async parseManifest_(data, finalManifestUri, rootElement) {
let manifestData = data;
const manifestPreprocessor = this.config_.dash.manifestPreprocessor;
const defaultManifestPreprocessor =
shaka.util.PlayerConfiguration.defaultManifestPreprocessor;
if (manifestPreprocessor != defaultManifestPreprocessor) {
shaka.Deprecate.deprecateFeature(5,
'manifest.dash.manifestPreprocessor configuration',
'Please Use manifest.dash.manifestPreprocessorTXml instead.');
const mpdElement =
shaka.util.XmlUtils.parseXml(manifestData, rootElement);
if (!mpdElement) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,
shaka.util.Error.Code.DASH_INVALID_XML,
finalManifestUri);
}
manifestPreprocessor(mpdElement);
manifestData = shaka.util.XmlUtils.toArrayBuffer(mpdElement);
}
const mpd = shaka.util.TXml.parseXml(manifestData, rootElement);
if (!mpd) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,
shaka.util.Error.Code.DASH_INVALID_XML,
finalManifestUri);
}
const manifestPreprocessorTXml =
this.config_.dash.manifestPreprocessorTXml;
const defaultManifestPreprocessorTXml =
shaka.util.PlayerConfiguration.defaultManifestPreprocessorTXml;
if (manifestPreprocessorTXml != defaultManifestPreprocessorTXml) {
manifestPreprocessorTXml(mpd);
}
if (rootElement === 'Patch') {
return this.processPatchManifest_(mpd);
}
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 = shaka.dash.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 {!shaka.extern.xml.Node} 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 TXml = shaka.util.TXml;
goog.asserts.assert(this.config_,
'Must call configure() before processManifest_()!');
if (this.contentSteeringManager_) {
this.contentSteeringManager_.clearPreviousLocations();
}
// 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 = [];
/** @type {!Map<string, string>} */
const locationsMapping = new Map();
const locationsObjs = TXml.findChildren(mpd, 'Location');
for (const locationsObj of locationsObjs) {
const serviceLocation = locationsObj.attributes['serviceLocation'];
const uri = TXml.getContents(locationsObj);
if (!uri) {
continue;
}
const finalUri = shaka.util.ManifestParserUtils.resolveUris(
manifestBaseUris, [uri])[0];
if (serviceLocation) {
if (this.contentSteeringManager_) {
this.contentSteeringManager_.addLocation(
'Location', serviceLocation, finalUri);
} else {
locationsMapping.set(serviceLocation, finalUri);
}
}
locations.push(finalUri);
}
if (this.contentSteeringManager_) {
const steeringLocations = this.contentSteeringManager_.getLocations(
'Location', /* ignoreBaseUrls= */ true);
if (steeringLocations.length > 0) {
this.manifestUris_ = steeringLocations;
manifestBaseUris = steeringLocations;
}
} else if (locations.length) {
this.manifestUris_ = locations;
manifestBaseUris = locations;
}
this.manifestPatchContext_.mpdId = mpd.attributes['id'] || '';
this.manifestPatchContext_.publishTime =
TXml.parseAttr(mpd, 'publishTime', TXml.parseDate) || 0;
this.patchLocationNodes_ = TXml.findChildren(mpd, 'PatchLocation');
let contentSteeringPromise = Promise.resolve();
const contentSteering = TXml.findChild(mpd, 'ContentSteering');
if (contentSteering && this.playerInterface_) {
const defaultPathwayId =
contentSteering.attributes['defaultServiceLocation'];
if (!this.contentSteeringManager_) {
this.contentSteeringManager_ =
new shaka.util.ContentSteeringManager(this.playerInterface_);
this.contentSteeringManager_.configure(this.config_);
this.contentSteeringManager_.setManifestType(
shaka.media.ManifestParser.DASH);
this.contentSteeringManager_.setBaseUris(manifestBaseUris);
this.contentSteeringManager_.setDefaultPathwayId(defaultPathwayId);
const uri = TXml.getContents(contentSteering);
if (uri) {
const queryBeforeStart =
TXml.parseAttr(contentSteering, 'queryBeforeStart',
TXml.parseBoolean, /* defaultValue= */ false);
if (queryBeforeStart) {
contentSteeringPromise =
this.contentSteeringManager_.requestInfo(uri);
} else {
this.contentSteeringManager_.requestInfo(uri);
}
}
} else {
this.contentSteeringManager_.setBaseUris(manifestBaseUris);
this.contentSteeringManager_.setDefaultPathwayId(defaultPathwayId);
}
for (const serviceLocation of locationsMapping.keys()) {
const uri = locationsMapping.get(serviceLocation);
this.contentSteeringManager_.addLocation(
'Location', serviceLocation, uri);
}
}
const uriObjs = TXml.findChildren(mpd, 'BaseURL');
let someLocationValid = false;
if (this.contentSteeringManager_) {
for (const uriObj of uriObjs) {
const serviceLocation = uriObj.attributes['serviceLocation'];
const uri = TXml.getContents(uriObj);
if (serviceLocation && uri) {
this.contentSteeringManager_.addLocation(
'BaseURL', serviceLocation, uri);
someLocationValid = true;
}
}
}
this.lastCalculatedBaseUris_ = null;
if (!someLocationValid || !this.contentSteeringManager_) {
const uris = uriObjs.map(TXml.getContents);
this.lastCalculatedBaseUris_ = shaka.util.ManifestParserUtils.resolveUris(
manifestBaseUris, uris);
}
const getBaseUris = () => {
if (this.contentSteeringManager_ && someLocationValid) {
return this.contentSteeringManager_.getLocations('BaseURL');
}
if (this.lastCalculatedBaseUris_) {
return this.lastCalculatedBaseUris_;
}
return [];
};
this.manifestPatchContext_.getBaseUris = getBaseUris;
let availabilityTimeOffset = 0;
if (uriObjs && uriObjs.length) {
availabilityTimeOffset = TXml.parseAttr(uriObjs[0],
'availabilityTimeOffset', TXml.parseFloat) || 0;
}
this.manifestPatchContext_.availabilityTimeOffset = availabilityTimeOffset;
this.updatePeriod_ = /** @type {number} */ (TXml.parseAttr(
mpd, 'minimumUpdatePeriod', TXml.parseDuration, -1));
const presentationStartTime = TXml.parseAttr(
mpd, 'availabilityStartTime', TXml.parseDate);
let segmentAvailabilityDuration = TXml.parseAttr(
mpd, 'timeShiftBufferDepth', TXml.parseDuration);
const ignoreSuggestedPresentationDelay =
this.config_.dash.ignoreSuggestedPresentationDelay;
let suggestedPresentationDelay = null;
if (!ignoreSuggestedPresentationDelay) {
suggestedPresentationDelay = TXml.parseAttr(
mpd, 'suggestedPresentationDelay', TXml.parseDuration);
}
const ignoreMaxSegmentDuration =
this.config_.dash.ignoreMaxSegmentDuration;
let maxSegmentDuration = null;
if (!ignoreMaxSegmentDuration) {
maxSegmentDuration = TXml.parseAttr(
mpd, 'maxSegmentDuration', TXml.parseDuration);
}
const mpdType = mpd.attributes['type'] || 'static';
if (this.manifest_ && this.manifest_.presentationTimeline) {
this.isTransitionFromDynamicToStatic_ =
this.manifest_.presentationTimeline.isLive() && mpdType == 'static';
}
this.manifestPatchContext_.type = mpdType;
/** @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
const availabilityStart =
presentationTimeline.getSegmentAvailabilityStart();
for (const stream of this.streamMap_.values()) {
if (stream.segmentIndex) {
stream.segmentIndex.evict(availabilityStart);
}
}
} else {
const ignoreMinBufferTime = this.config_.dash.ignoreMinBufferTime;
let minBufferTime = 0;
if (!ignoreMinBufferTime) {
minBufferTime =
TXml.parseAttr(mpd, 'minBufferTime', TXml.parseDuration) || 0;
}
// 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.
let delay = 0;
if (suggestedPresentationDelay != null) {
// 1. If a suggestedPresentationDelay is provided by the manifest, that
// will be used preferentially.
// This is given a minimum bound of segmentAvailabilityDuration.
// Content providers should provide a suggestedPresentationDelay
// whenever possible to optimize the live streaming experience.
delay = Math.min(
suggestedPresentationDelay,
segmentAvailabilityDuration || Infinity);
} else if (this.config_.defaultPresentationDelay > 0) {
// 2. If the developer provides a value for
// "manifest.defaultPresentationDelay", that is used as a fallback.
delay = this.config_.defaultPresentationDelay;
} else {
// 3. Otherwise, we default to the lower of segmentAvailabilityDuration
// and 1.5 * minBufferTime. This is fairly conservative.
delay = Math.min(
minBufferTime * 1.5, segmentAvailabilityDuration || Infinity);
}
presentationTimeline = new shaka.media.PresentationTimeline(
presentationStartTime, delay, 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.attributes['profiles'] || '';
this.manifestPatchContext_.profiles = profiles.split(',');
/** @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,
mediaPresentationDuration: null,
profiles: profiles.split(','),
roles: null,
urlParams: () => '',
};
await contentSteeringPromise;
this.gapCount_ = 0;
const periodsAndDuration = this.parsePeriods_(
context, getBaseUris, mpd, /* newPeriod= */ false);
const duration = periodsAndDuration.duration;
const periods = periodsAndDuration.periods;
if ((mpdType == 'static' && !this.isTransitionFromDynamicToStatic_) ||
!periodsAndDuration.durationDerivedFromPeriods) {
// Ignore duration calculated from Period lengths if this is dynamic.
presentationTimeline.setDuration(duration || Infinity);
}
if (this.isLowLatency_ && this.lowLatencyMode_) {
presentationTimeline.setAvailabilityTimeOffset(
this.minTotalAvailabilityTimeOffset_);
}
// Use @maxSegmentDuration to override smaller, derived values.
presentationTimeline.notifyMaxSegmentDuration(maxSegmentDuration || 1);
if (goog.DEBUG && !this.isTransitionFromDynamicToStatic_) {
presentationTimeline.assertIsValid();
}
if (this.isLowLatency_ && this.lowLatencyMode_) {
const presentationDelay = suggestedPresentationDelay != null ?
suggestedPresentationDelay : this.config_.defaultPresentationDelay;
presentationTimeline.setDelay(presentationDelay);
}
// These steps are not done on manifest update.
if (!this.manifest_) {
await this.periodCombiner_.combinePeriods(periods, context.dynamic);
this.manifest_ = {
presentationTimeline: presentationTimeline,
variants: this.periodCombiner_.getVariants(),
textStreams: this.periodCombiner_.getTextStreams(),
imageStreams: this.periodCombiner_.getImageStreams(),
offlineSessionIds: [],
sequenceMode: this.config_.dash.sequenceMode,
ignoreManifestTimestampsInSegmentsMode: false,
type: shaka.media.ManifestParser.DASH,
serviceDescription: this.parseServiceDescription_(mpd),
nextUrl: this.parseMpdChaining_(mpd),
periodCount: periods.length,
gapCount: this.gapCount_,
isLowLatency: this.isLowLatency_,
startTime: null,
};
// We only need to do clock sync when we're using presentation start
// time. This condition also excludes VOD streams.
if (presentationTimeline.usingPresentationStartTime()) {
const TXml = shaka.util.TXml;
const timingElements = TXml.findChildren(mpd, 'UTCTiming');
const offset = await this.parseUtcTiming_(getBaseUris, 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 {
this.manifest_.periodCount = periods.length;
this.manifest_.gapCount = this.gapCount_;
await this.postPeriodProcessing_(periods, /* isPatchUpdate= */ false);
}
// 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_);
this.cleanStreamMap_();
}
/**
* Handles common procedures after processing new periods.
*
* @param {!Array<shaka.extern.Period>} periods to be appended
* @param {boolean} isPatchUpdate does call comes from mpd patch update
* @private
*/
async postPeriodProcessing_(periods, isPatchUpdate) {
await this.periodCombiner_.combinePeriods(periods, true, isPatchUpdate);
// Just update the variants and text streams, which may change as periods
// are added or removed.
this.manifest_.variants = this.periodCombiner_.getVariants();
const textStreams = this.periodCombiner_.getTextStreams();
if (textStreams.length > 0) {
this.manifest_.textStreams = textStreams;
}
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_);
}
/**
* Takes a formatted Patch MPD and converts it into a manifest.
*
* @param {!shaka.extern.xml.Node} mpd
* @return {!Promise}
* @private
*/
async processPatchManifest_(mpd) {
const TXml = shaka.util.TXml;
const mpdId = mpd.attributes['mpdId'];
const originalPublishTime = TXml.parseAttr(mpd, 'originalPublishTime',
TXml.parseDate);
if (!mpdId || mpdId !== this.manifestPatchContext_.mpdId ||
originalPublishTime !== this.manifestPatchContext_.publishTime) {
// Clean patch location nodes, so it will force full MPD update.
this.patchLocationNodes_ = [];
throw new shaka.util.Error(
shaka.util.Error.Severity.RECOVERABLE,
shaka.util.Error.Category.MANIFEST,
shaka.util.Error.Code.DASH_INVALID_PATCH);
}
/** @type {!Array<shaka.extern.Period>} */
const newPeriods = [];
/** @type {!Array<shaka.extern.xml.Node>} */
const periodAdditions = [];
/** @type {!Set<string>} */
const modifiedTimelines = new Set();
for (const patchNode of TXml.getChildNodes(mpd)) {
let handled = true;
const paths = TXml.parseXpath(patchNode.attributes['sel'] || '');
const node = paths[paths.length - 1];
const content = TXml.getContents(patchNode) || '';
if (node.name === 'MPD') {
if (node.attribute === 'mediaPresentationDuration') {
const content = TXml.getContents(patchNode) || '';
this.parsePatchMediaPresentationDurationChange_(content);
} else if (node.attribute === 'type') {
this.parsePatchMpdTypeChange_(content);
} else if (node.attribute === 'publishTime') {
this.manifestPatchContext_.publishTime = TXml.parseDate(content) || 0;
} else if (node.attribute === null && patchNode.tagName === 'add') {
periodAdditions.push(patchNode);
} else {
handled = false;
}
} else if (node.name === 'PatchLocation') {
this.updatePatchLocationNodes_(patchNode);
} else if (node.name === 'Period') {
if (patchNode.tagName === 'add') {
periodAdditions.push(patchNode);
} else if (patchNode.tagName === 'remove' && node.id) {
this.removePatchPeriod_(node.id);
}
} else if (node.name === 'SegmentTemplate') {
const timelines = this.modifySegmentTemplate_(patchNode);
for (const timeline of timelines) {
modifiedTimelines.add(timeline);
}
} else if (node.name === 'SegmentTimeline' || node.name === 'S') {
const timelines = this.modifyTimepoints_(patchNode);
for (const timeline of timelines) {
modifiedTimelines.add(timeline);
}
} else {
handled = false;
}
if (!handled) {
shaka.log.warning('Unhandled ' + patchNode.tagName + ' operation',
patchNode.attributes['sel']);
}
}
for (const timeline of modifiedTimelines) {
this.parsePatchSegment_(timeline);
}
// Add new periods after extending timelines, as new periods
// remove context cache of previous periods.
for (const periodAddition of periodAdditions) {
newPeriods.push(...this.parsePatchPeriod_(periodAddition));
}
if (newPeriods.length) {
this.manifest_.periodCount += newPeriods.length;
this.manifest_.gapCount = this.gapCount_;
await this.postPeriodProcessing_(newPeriods, /* isPatchUpdate= */ true);
}
if (this.manifestPatchContext_.type == 'static') {
const duration = this.manifestPatchContext_.mediaPresentationDuration;
this.manifest_.presentationTimeline.setDuration(duration || Infinity);
}
}
/**
* Handles manifest type changes, this transition is expected to be
* "dynamic" to "static".
*
* @param {!string} mpdType
* @private
*/
parsePatchMpdTypeChange_(mpdType) {
this.manifest_.presentationTimeline.setStatic(mpdType == 'static');
this.manifestPatchContext_.type = mpdType;
for (const context of this.contextCache_.values()) {
context.dynamic = mpdType == 'dynamic';
}
if (mpdType == 'static') {
// Manifest is no longer dynamic, so stop live updates.
this.updatePeriod_ = -1;
}
}
/**
* @param {string} durationString
* @private