forked from shaka-project/shaka-player
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathperiods.js
1936 lines (1767 loc) · 64.4 KB
/
periods.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.util.PeriodCombiner');
goog.require('goog.asserts');
goog.require('shaka.drm.DrmUtils');
goog.require('shaka.log');
goog.require('shaka.media.MetaSegmentIndex');
goog.require('shaka.media.SegmentIndex');
goog.require('shaka.util.Error');
goog.require('shaka.util.IReleasable');
goog.require('shaka.util.LanguageUtils');
goog.require('shaka.util.ManifestParserUtils');
goog.require('shaka.util.MimeUtils');
/**
* A utility to combine streams across periods.
*
* @implements {shaka.util.IReleasable}
* @final
* @export
*/
shaka.util.PeriodCombiner = class {
/** */
constructor() {
/** @private {!Array<shaka.extern.Variant>} */
this.variants_ = [];
/** @private {!Array<shaka.extern.Stream>} */
this.audioStreams_ = [];
/** @private {!Array<shaka.extern.Stream>} */
this.videoStreams_ = [];
/** @private {!Array<shaka.extern.Stream>} */
this.textStreams_ = [];
/** @private {!Array<shaka.extern.Stream>} */
this.imageStreams_ = [];
/** @private {boolean} */
this.multiTypeVariantsAllowed_ = false;
/** @private {boolean} */
this.useStreamOnce_ = false;
/**
* The IDs of the periods we have already used to generate streams.
* This helps us identify the periods which have been added when a live
* stream is updated.
*
* @private {!Set<string>}
*/
this.usedPeriodIds_ = new Set();
}
/** @override */
release() {
const allStreams =
this.audioStreams_.concat(this.videoStreams_, this.textStreams_,
this.imageStreams_);
for (const stream of allStreams) {
if (stream.segmentIndex) {
stream.segmentIndex.release();
}
}
this.audioStreams_ = [];
this.videoStreams_ = [];
this.textStreams_ = [];
this.imageStreams_ = [];
this.variants_ = [];
this.multiTypeVariantsAllowed_ = false;
this.useStreamOnce_ = false;
this.usedPeriodIds_.clear();
}
/**
* @return {!Array<shaka.extern.Variant>}
*
* @export
*/
getVariants() {
return this.variants_;
}
/**
* @return {!Array<shaka.extern.Stream>}
*
* @export
*/
getTextStreams() {
// Return a copy of the array because makeTextStreamsForClosedCaptions
// may make changes to the contents of the array. Those changes should not
// propagate back to the PeriodCombiner.
return this.textStreams_.slice();
}
/**
* @return {!Array<shaka.extern.Stream>}
*
* @export
*/
getImageStreams() {
return this.imageStreams_;
}
/**
* Deletes a stream from matchedStreams because it is no longer needed
*
* @param {?shaka.extern.Stream} stream
* @param {string} periodId
*
* @export
*/
deleteStream(stream, periodId) {
if (!stream) {
return;
}
const ContentType = shaka.util.ManifestParserUtils.ContentType;
if (stream.type == ContentType.AUDIO) {
for (const audioStream of this.audioStreams_) {
audioStream.matchedStreams = audioStream.matchedStreams.filter((s) => {
return s !== stream;
});
}
} else if (stream.type == ContentType.VIDEO) {
for (const videoStream of this.videoStreams_) {
videoStream.matchedStreams = videoStream.matchedStreams.filter((s) => {
return s !== stream;
});
if (videoStream.trickModeVideo) {
videoStream.trickModeVideo.matchedStreams =
videoStream.trickModeVideo.matchedStreams.filter((s) => {
return s !== stream;
});
}
if (videoStream.dependencyStream) {
videoStream.dependencyStream.matchedStreams =
videoStream.dependencyStream.matchedStreams.filter((s) => {
return s !== stream;
});
}
}
} else if (stream.type == ContentType.TEXT) {
for (const textStream of this.textStreams_) {
textStream.matchedStreams = textStream.matchedStreams.filter((s) => {
return s !== stream;
});
}
} else if (stream.type == ContentType.IMAGE) {
for (const imageStream of this.imageStreams_) {
imageStream.matchedStreams = imageStream.matchedStreams.filter((s) => {
return s !== stream;
});
}
}
if (stream.segmentIndex) {
stream.closeSegmentIndex();
}
this.usedPeriodIds_.delete(periodId);
}
/**
* Returns an object that contains arrays of streams by type
* @param {!Array<shaka.extern.Period>} periods
* @param {boolean} addDummy
* @return {{
* audioStreamsPerPeriod: !Array<!Map<string, shaka.extern.Stream>>,
* videoStreamsPerPeriod: !Array<!Map<string, shaka.extern.Stream>>,
* textStreamsPerPeriod: !Array<!Map<string, shaka.extern.Stream>>,
* imageStreamsPerPeriod: !Array<!Map<string, shaka.extern.Stream>>
* }}
* @private
*/
getStreamsPerPeriod_(periods, addDummy) {
const ContentType = shaka.util.ManifestParserUtils.ContentType;
const PeriodCombiner = shaka.util.PeriodCombiner;
const audioStreamsPerPeriod = [];
const videoStreamsPerPeriod = [];
const textStreamsPerPeriod = [];
const imageStreamsPerPeriod = [];
for (const period of periods) {
const audioMap = new Map(period.audioStreams.map((s) =>
[PeriodCombiner.generateAudioKey_(s), s]));
const videoMap = new Map(period.videoStreams.map((s) =>
[PeriodCombiner.generateVideoKey_(s), s]));
const textMap = new Map(period.textStreams.map((s) =>
[PeriodCombiner.generateTextKey_(s), s]));
const imageMap = new Map(period.imageStreams.map((s) =>
[PeriodCombiner.generateImageKey_(s), s]));
// It's okay to have a period with no text or images, but our algorithm
// fails on any period without matching streams. So we add dummy streams
// to each period. Since we combine text streams by language and image
// streams by resolution, we might need a dummy even in periods with these
// streams already.
if (addDummy) {
const dummyText = PeriodCombiner.dummyStream_(ContentType.TEXT);
textMap.set(PeriodCombiner.generateTextKey_(dummyText), dummyText);
const dummyImage = PeriodCombiner.dummyStream_(ContentType.IMAGE);
imageMap.set(PeriodCombiner.generateImageKey_(dummyImage), dummyImage);
}
audioStreamsPerPeriod.push(audioMap);
videoStreamsPerPeriod.push(videoMap);
textStreamsPerPeriod.push(textMap);
imageStreamsPerPeriod.push(imageMap);
}
return {
audioStreamsPerPeriod,
videoStreamsPerPeriod,
textStreamsPerPeriod,
imageStreamsPerPeriod,
};
}
/**
* @param {!Array<shaka.extern.Period>} periods
* @param {boolean} isDynamic
* @param {boolean=} isPatchUpdate
* @return {!Promise}
*
* @export
*/
async combinePeriods(periods, isDynamic, isPatchUpdate = false) {
const ContentType = shaka.util.ManifestParserUtils.ContentType;
// Optimization: for single-period VOD, do nothing. This makes sure
// single-period DASH content will be 100% accurately represented in the
// output.
if (!isDynamic && periods.length == 1) {
// We need to filter out duplicates, so call getStreamsPerPeriod()
// so it will do that by usage of Map.
const {
audioStreamsPerPeriod,
videoStreamsPerPeriod,
textStreamsPerPeriod,
imageStreamsPerPeriod,
} = this.getStreamsPerPeriod_(periods, /* addDummy= */ false);
this.audioStreams_ = Array.from(audioStreamsPerPeriod[0].values());
this.videoStreams_ = Array.from(videoStreamsPerPeriod[0].values());
this.textStreams_ = Array.from(textStreamsPerPeriod[0].values());
this.imageStreams_ = Array.from(imageStreamsPerPeriod[0].values());
} else {
// How many periods we've seen before which are not included in this call.
const periodsMissing = isPatchUpdate ? this.usedPeriodIds_.size : 0;
// Find the first period we haven't seen before. Tag all the periods we
// see now as "used".
let firstNewPeriodIndex = -1;
for (let i = 0; i < periods.length; i++) {
const period = periods[i];
if (this.usedPeriodIds_.has(period.id)) {
// This isn't new.
} else {
// This one _is_ new.
this.usedPeriodIds_.add(period.id);
if (firstNewPeriodIndex == -1) {
// And it's the _first_ new one.
firstNewPeriodIndex = i;
}
}
}
if (firstNewPeriodIndex == -1) {
// Nothing new? Nothing to do.
return;
}
const {
audioStreamsPerPeriod,
videoStreamsPerPeriod,
textStreamsPerPeriod,
imageStreamsPerPeriod,
} = this.getStreamsPerPeriod_(periods, /* addDummy= */ true);
await Promise.all([
this.combine_(
this.audioStreams_,
audioStreamsPerPeriod,
firstNewPeriodIndex,
shaka.util.PeriodCombiner.cloneStream_,
shaka.util.PeriodCombiner.concatenateStreams_,
periodsMissing),
this.combine_(
this.videoStreams_,
videoStreamsPerPeriod,
firstNewPeriodIndex,
shaka.util.PeriodCombiner.cloneStream_,
shaka.util.PeriodCombiner.concatenateStreams_,
periodsMissing),
this.combine_(
this.textStreams_,
textStreamsPerPeriod,
firstNewPeriodIndex,
shaka.util.PeriodCombiner.cloneStream_,
shaka.util.PeriodCombiner.concatenateStreams_,
periodsMissing),
this.combine_(
this.imageStreams_,
imageStreamsPerPeriod,
firstNewPeriodIndex,
shaka.util.PeriodCombiner.cloneStream_,
shaka.util.PeriodCombiner.concatenateStreams_,
periodsMissing),
]);
}
// Create variants for all audio/video combinations.
let nextVariantId = 0;
const variants = [];
if (!this.videoStreams_.length || !this.audioStreams_.length) {
// For audio-only or video-only content, just give each stream its own
// variant.
const streams = this.videoStreams_.length ? this.videoStreams_ :
this.audioStreams_;
for (const stream of streams) {
const id = nextVariantId++;
let bandwidth = stream.bandwidth || 0;
if (stream.dependencyStream) {
bandwidth += stream.dependencyStream.bandwidth || 0;
}
variants.push({
id,
language: stream.language,
disabledUntilTime: 0,
primary: stream.primary,
audio: stream.type == ContentType.AUDIO ? stream : null,
video: stream.type == ContentType.VIDEO ? stream : null,
bandwidth,
drmInfos: stream.drmInfos,
allowedByApplication: true,
allowedByKeySystem: true,
decodingInfos: [],
});
}
} else {
for (const audio of this.audioStreams_) {
for (const video of this.videoStreams_) {
const commonDrmInfos = shaka.drm.DrmUtils.getCommonDrmInfos(
audio.drmInfos, video.drmInfos);
if (audio.drmInfos.length && video.drmInfos.length &&
!commonDrmInfos.length) {
shaka.log.warning(
'Incompatible DRM in audio & video, skipping variant creation.',
audio, video);
continue;
}
let bandwidth = (audio.bandwidth || 0) + (video.bandwidth || 0);
if (audio.dependencyStream) {
bandwidth += audio.dependencyStream.bandwidth || 0;
}
if (video.dependencyStream) {
bandwidth += video.dependencyStream.bandwidth || 0;
}
const id = nextVariantId++;
variants.push({
id,
language: audio.language,
disabledUntilTime: 0,
primary: audio.primary,
audio,
video,
bandwidth,
drmInfos: commonDrmInfos,
allowedByApplication: true,
allowedByKeySystem: true,
decodingInfos: [],
});
}
}
}
this.variants_ = variants;
}
/**
* Stitch together DB streams across periods, taking a mix of stream types.
* The offline database does not separate these by type.
*
* Unlike the DASH case, this does not need to maintain any state for manifest
* updates.
*
* @param {!Array<!Array<shaka.extern.StreamDB>>} streamDbsPerPeriod
* @return {!Promise<!Array<shaka.extern.StreamDB>>}
*/
static async combineDbStreams(streamDbsPerPeriod) {
const ContentType = shaka.util.ManifestParserUtils.ContentType;
const PeriodCombiner = shaka.util.PeriodCombiner;
// Optimization: for single-period content, do nothing. This makes sure
// single-period DASH or any HLS content stored offline will be 100%
// accurately represented in the output.
if (streamDbsPerPeriod.length == 1) {
return streamDbsPerPeriod[0];
}
const audioStreamDbsPerPeriod = streamDbsPerPeriod.map(
(streams) => new Map(streams
.filter((s) => s.type === ContentType.AUDIO)
.map((s) => [PeriodCombiner.generateAudioKey_(s), s])));
const videoStreamDbsPerPeriod = streamDbsPerPeriod.map(
(streams) => new Map(streams
.filter((s) => s.type === ContentType.VIDEO)
.map((s) => [PeriodCombiner.generateVideoKey_(s), s])));
const textStreamDbsPerPeriod = streamDbsPerPeriod.map(
(streams) => new Map(streams
.filter((s) => s.type === ContentType.TEXT)
.map((s) => [PeriodCombiner.generateTextKey_(s), s])));
const imageStreamDbsPerPeriod = streamDbsPerPeriod.map(
(streams) => new Map(streams
.filter((s) => s.type === ContentType.IMAGE)
.map((s) => [PeriodCombiner.generateImageKey_(s), s])));
// It's okay to have a period with no text or images, but our algorithm
// fails on any period without matching streams. So we add dummy streams to
// each period. Since we combine text streams by language and image streams
// by resolution, we might need a dummy even in periods with these streams
// already.
for (const textStreams of textStreamDbsPerPeriod) {
const dummy = PeriodCombiner.dummyStreamDB_(ContentType.TEXT);
textStreams.set(PeriodCombiner.generateTextKey_(dummy), dummy);
}
for (const imageStreams of imageStreamDbsPerPeriod) {
const dummy = PeriodCombiner.dummyStreamDB_(ContentType.IMAGE);
imageStreams.set(PeriodCombiner.generateImageKey_(dummy), dummy);
}
const periodCombiner = new shaka.util.PeriodCombiner();
const combinedAudioStreamDbs = await periodCombiner.combine_(
/* outputStreams= */ [],
audioStreamDbsPerPeriod,
/* firstNewPeriodIndex= */ 0,
shaka.util.PeriodCombiner.cloneStreamDB_,
shaka.util.PeriodCombiner.concatenateStreamDBs_,
/* periodsMissing= */ 0);
const combinedVideoStreamDbs = await periodCombiner.combine_(
/* outputStreams= */ [],
videoStreamDbsPerPeriod,
/* firstNewPeriodIndex= */ 0,
shaka.util.PeriodCombiner.cloneStreamDB_,
shaka.util.PeriodCombiner.concatenateStreamDBs_,
/* periodsMissing= */ 0);
const combinedTextStreamDbs = await periodCombiner.combine_(
/* outputStreams= */ [],
textStreamDbsPerPeriod,
/* firstNewPeriodIndex= */ 0,
shaka.util.PeriodCombiner.cloneStreamDB_,
shaka.util.PeriodCombiner.concatenateStreamDBs_,
/* periodsMissing= */ 0);
const combinedImageStreamDbs = await periodCombiner.combine_(
/* outputStreams= */ [],
imageStreamDbsPerPeriod,
/* firstNewPeriodIndex= */ 0,
shaka.util.PeriodCombiner.cloneStreamDB_,
shaka.util.PeriodCombiner.concatenateStreamDBs_,
/* periodsMissing= */ 0);
// Recreate variantIds from scratch in the output.
// HLS content is always single-period, so the early return at the top of
// this method would catch all HLS content. DASH content stored with v3.0
// will already be flattened before storage. Therefore the only content
// that reaches this point is multi-period DASH content stored before v3.0.
// Such content always had variants generated from all combinations of audio
// and video, so we can simply do that now without loss of correctness.
let nextVariantId = 0;
if (!combinedVideoStreamDbs.length || !combinedAudioStreamDbs.length) {
// For audio-only or video-only content, just give each stream its own
// variant ID.
const combinedStreamDbs =
combinedVideoStreamDbs.concat(combinedAudioStreamDbs);
for (const stream of combinedStreamDbs) {
stream.variantIds = [nextVariantId++];
}
} else {
for (const audio of combinedAudioStreamDbs) {
for (const video of combinedVideoStreamDbs) {
const id = nextVariantId++;
video.variantIds.push(id);
audio.variantIds.push(id);
}
}
}
return combinedVideoStreamDbs
.concat(combinedAudioStreamDbs)
.concat(combinedTextStreamDbs)
.concat(combinedImageStreamDbs);
}
/**
* Combine input Streams per period into flat output Streams.
* Templatized to handle both DASH Streams and offline StreamDBs.
*
* @param {!Array<T>} outputStreams A list of existing output streams, to
* facilitate updates for live DASH content. Will be modified and returned.
* @param {!Array<!Map<string, T>>} streamsPerPeriod A list of maps of Streams
* from each period.
* @param {number} firstNewPeriodIndex An index into streamsPerPeriod which
* represents the first new period that hasn't been processed yet.
* @param {function(T):T} clone Make a clone of an input stream.
* @param {function(T, T)} concat Concatenate the second stream onto the end
* of the first.
* @param {number} periodsMissing The number of periods missing
*
* @return {!Promise<!Array<T>>} The same array passed to outputStreams,
* modified to include any newly-created streams.
*
* @template T
* Accepts either a StreamDB or Stream type.
*
* @private
*/
async combine_(
outputStreams, streamsPerPeriod, firstNewPeriodIndex, clone, concat,
periodsMissing) {
const unusedStreamsPerPeriod = [];
for (let i = 0; i < streamsPerPeriod.length; i++) {
if (i >= firstNewPeriodIndex) {
// This periods streams are all new.
unusedStreamsPerPeriod.push(new Set(streamsPerPeriod[i].values()));
} else {
// This period's streams have all been used already.
unusedStreamsPerPeriod.push(new Set());
}
}
// First, extend all existing output Streams into the new periods.
for (const outputStream of outputStreams) {
// eslint-disable-next-line no-await-in-loop
const ok = await this.extendExistingOutputStream_(
outputStream, streamsPerPeriod, firstNewPeriodIndex, concat,
unusedStreamsPerPeriod, periodsMissing);
if (!ok) {
// This output Stream was not properly extended to include streams from
// the new period. This is likely a bug in our algorithm, so throw an
// error.
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,
shaka.util.Error.Code.PERIOD_FLATTENING_FAILED);
}
// This output stream is now complete with content from all known
// periods.
} // for (const outputStream of outputStreams)
for (const unusedStreams of unusedStreamsPerPeriod) {
for (const stream of unusedStreams) {
// Create a new output stream which includes this input stream.
const outputStream = this.createNewOutputStream_(
stream, streamsPerPeriod, clone, concat,
unusedStreamsPerPeriod);
if (outputStream) {
outputStreams.push(outputStream);
} else {
// This is not a stream we can build output from, but it may become
// part of another output based on another period's stream.
}
} // for (const stream of unusedStreams)
} // for (const unusedStreams of unusedStreamsPerPeriod)
for (const unusedStreams of unusedStreamsPerPeriod) {
for (const stream of unusedStreams) {
if (shaka.util.PeriodCombiner.isDummy_(stream)) {
// This is one of our dummy streams, so ignore it. We may not use
// them all, and that's fine.
continue;
}
// If this stream has a different codec/MIME than any other stream,
// then we can't play it.
const hasCodec = outputStreams.some((s) => {
return this.areAVStreamsCompatible_(stream, s);
});
if (!hasCodec) {
continue;
}
// Any other unused stream is likely a bug in our algorithm, so throw
// an error.
shaka.log.error('Unused stream in period-flattening!',
stream, outputStreams);
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,
shaka.util.Error.Code.PERIOD_FLATTENING_FAILED);
}
}
return outputStreams;
}
/**
* @param {T} outputStream An existing output stream which needs to be
* extended into new periods.
* @param {!Array<!Map<string, T>>} streamsPerPeriod A list of maps of Streams
* from each period.
* @param {number} firstNewPeriodIndex An index into streamsPerPeriod which
* represents the first new period that hasn't been processed yet.
* @param {function(T, T)} concat Concatenate the second stream onto the end
* of the first.
* @param {!Array<!Set<T>>} unusedStreamsPerPeriod An array of sets of
* unused streams from each period.
* @param {number} periodsMissing How many periods are missing in this update.
*
* @return {!Promise<boolean>}
*
* @template T
* Should only be called with a Stream type in practice, but has call sites
* from other templated functions that also accept a StreamDB.
*
* @private
*/
async extendExistingOutputStream_(
outputStream, streamsPerPeriod, firstNewPeriodIndex, concat,
unusedStreamsPerPeriod, periodsMissing) {
this.findMatchesInAllPeriods_(streamsPerPeriod,
outputStream, periodsMissing > 0);
// This only exists where T == Stream, and this should only ever be called
// on Stream types. StreamDB should not have pre-existing output streams.
goog.asserts.assert(outputStream.createSegmentIndex,
'outputStream should be a Stream type!');
if (!outputStream.matchedStreams) {
// We were unable to extend this output stream.
shaka.log.error('No matches extending output stream!',
outputStream, streamsPerPeriod);
return false;
}
// We need to create all the per-period segment indexes and append them to
// the output's MetaSegmentIndex.
if (outputStream.segmentIndex) {
await shaka.util.PeriodCombiner.extendOutputSegmentIndex_(outputStream,
firstNewPeriodIndex + periodsMissing);
}
shaka.util.PeriodCombiner.extendOutputStream_(outputStream,
firstNewPeriodIndex, concat, unusedStreamsPerPeriod, periodsMissing);
return true;
}
/**
* Creates the segment indexes for an array of input streams, and append them
* to the output stream's segment index.
*
* @param {shaka.extern.Stream} outputStream
* @param {number} firstNewPeriodIndex An index into streamsPerPeriod which
* represents the first new period that hasn't been processed yet.
* @private
*/
static async extendOutputSegmentIndex_(outputStream, firstNewPeriodIndex) {
const operations = [];
const streams = outputStream.matchedStreams;
goog.asserts.assert(streams, 'matched streams should be valid');
for (let i = firstNewPeriodIndex; i < streams.length; i++) {
const stream = streams[i];
operations.push(stream.createSegmentIndex());
if (stream.trickModeVideo && !stream.trickModeVideo.segmentIndex) {
operations.push(stream.trickModeVideo.createSegmentIndex());
}
if (stream.dependencyStream && !stream.dependencyStream.segmentIndex) {
operations.push(stream.dependencyStream.createSegmentIndex());
}
}
await Promise.all(operations);
// Concatenate the new matches onto the stream, starting at the first new
// period.
// Satisfy the compiler about the type.
// Also checks if the segmentIndex is still valid after the async
// operations, to make sure we stop if the active stream has changed.
if (outputStream.segmentIndex instanceof shaka.media.MetaSegmentIndex) {
for (let i = firstNewPeriodIndex; i < streams.length; i++) {
const match = streams[i];
goog.asserts.assert(match.segmentIndex,
'stream should have a segmentIndex.');
if (match.segmentIndex) {
outputStream.segmentIndex.appendSegmentIndex(match.segmentIndex);
}
}
}
}
/**
* Create a new output Stream based on a particular input Stream. Locates
* matching Streams in all other periods and combines them into an output
* Stream.
* Templatized to handle both DASH Streams and offline StreamDBs.
*
* @param {T} stream An input stream on which to base the output stream.
* @param {!Array<!Map<string, T>>} streamsPerPeriod A list of maps of Streams
* from each period.
* @param {function(T):T} clone Make a clone of an input stream.
* @param {function(T, T)} concat Concatenate the second stream onto the end
* of the first.
* @param {!Array<!Set<T>>} unusedStreamsPerPeriod An array of sets of
* unused streams from each period.
*
* @return {?T} A newly-created output Stream, or null if matches
* could not be found.`
*
* @template T
* Accepts either a StreamDB or Stream type.
*
* @private
*/
createNewOutputStream_(
stream, streamsPerPeriod, clone, concat, unusedStreamsPerPeriod) {
// Check do we want to create output stream from dummy stream
// and if so, return quickly.
if (shaka.util.PeriodCombiner.isDummy_(stream)) {
return null;
}
// Start by cloning the stream without segments, key IDs, etc.
const outputStream = clone(stream);
// Find best-matching streams in all periods.
this.findMatchesInAllPeriods_(streamsPerPeriod, outputStream);
// This only exists where T == Stream.
if (outputStream.createSegmentIndex) {
// Override the createSegmentIndex function of the outputStream.
outputStream.createSegmentIndex = async () => {
if (!outputStream.segmentIndex) {
outputStream.segmentIndex = new shaka.media.MetaSegmentIndex();
await shaka.util.PeriodCombiner.extendOutputSegmentIndex_(
outputStream, /* firstNewPeriodIndex= */ 0);
}
};
// For T == Stream, we need to create all the per-period segment indexes
// in advance. concat() will add them to the output's MetaSegmentIndex.
}
if (!outputStream.matchedStreams || !outputStream.matchedStreams.length) {
// This is not a stream we can build output from, but it may become part
// of another output based on another period's stream.
return null;
}
shaka.util.PeriodCombiner.extendOutputStream_(outputStream,
/* firstNewPeriodIndex= */ 0, concat, unusedStreamsPerPeriod,
/* periodsMissing= */ 0);
return outputStream;
}
/**
* @param {T} outputStream An existing output stream which needs to be
* extended into new periods.
* @param {number} firstNewPeriodIndex An index into streamsPerPeriod which
* represents the first new period that hasn't been processed yet.
* @param {function(T, T)} concat Concatenate the second stream onto the end
* of the first.
* @param {!Array<!Set<T>>} unusedStreamsPerPeriod An array of sets of
* unused streams from each period.
* @param {number} periodsMissing How many periods are missing in this update
*
* @template T
* Accepts either a StreamDB or Stream type.
*
* @private
*/
static extendOutputStream_(
outputStream, firstNewPeriodIndex, concat, unusedStreamsPerPeriod,
periodsMissing) {
const ContentType = shaka.util.ManifestParserUtils.ContentType;
const LanguageUtils = shaka.util.LanguageUtils;
const matches = outputStream.matchedStreams;
// Assure the compiler that matches didn't become null during the async
// operation before.
goog.asserts.assert(outputStream.matchedStreams,
'matchedStreams should be non-null');
// Concatenate the new matches onto the stream, starting at the first new
// period.
const start = firstNewPeriodIndex + periodsMissing;
for (let i = start; i < matches.length; i++) {
const match = matches[i];
concat(outputStream, match);
// We only consider an audio stream "used" if its language is related to
// the output language. There are scenarios where we want to generate
// separate tracks for each language, even when we are forced to connect
// unrelated languages across periods.
let used = true;
if (outputStream.type == ContentType.AUDIO) {
const relatedness = LanguageUtils.relatedness(
outputStream.language, match.language);
if (relatedness == 0) {
used = false;
}
}
if (used) {
unusedStreamsPerPeriod[i - periodsMissing].delete(match);
// Add the full mimetypes to the stream.
if (match.fullMimeTypes) {
for (const fullMimeType of match.fullMimeTypes.values()) {
outputStream.fullMimeTypes.add(fullMimeType);
}
}
}
}
}
/**
* Clone a Stream to make an output Stream for combining others across
* periods.
*
* @param {shaka.extern.Stream} stream
* @return {shaka.extern.Stream}
* @private
*/
static cloneStream_(stream) {
const clone = /** @type {shaka.extern.Stream} */(Object.assign({}, stream));
// These are wiped out now and rebuilt later from the various per-period
// streams that match this output.
clone.originalId = null;
clone.createSegmentIndex = () => Promise.resolve();
clone.closeSegmentIndex = () => {
if (clone.segmentIndex) {
clone.segmentIndex.release();
clone.segmentIndex = null;
}
// Close the segment index of the matched streams.
if (clone.matchedStreams) {
for (const match of clone.matchedStreams) {
if (match.segmentIndex) {
match.segmentIndex.release();
match.segmentIndex = null;
}
}
}
};
// Clone roles array so this output stream can own it.
clone.roles = clone.roles.slice();
clone.segmentIndex = null;
clone.emsgSchemeIdUris = [];
clone.keyIds = new Set(stream.keyIds);
clone.closedCaptions = stream.closedCaptions ?
new Map(stream.closedCaptions) : null;
clone.trickModeVideo = null;
clone.dependencyStream = null;
return clone;
}
/**
* Clone a StreamDB to make an output stream for combining others across
* periods.
*
* @param {shaka.extern.StreamDB} streamDb
* @return {shaka.extern.StreamDB}
* @private
*/
static cloneStreamDB_(streamDb) {
const clone = /** @type {shaka.extern.StreamDB} */(Object.assign(
{}, streamDb));
// Clone roles array so this output stream can own it.
clone.roles = clone.roles.slice();
// These are wiped out now and rebuilt later from the various per-period
// streams that match this output.
clone.keyIds = new Set(streamDb.keyIds);
clone.segments = [];
clone.variantIds = [];
clone.closedCaptions = streamDb.closedCaptions ?
new Map(streamDb.closedCaptions) : null;
return clone;
}
/**
* Combine the various fields of the input Stream into the output.
*
* @param {shaka.extern.Stream} output
* @param {shaka.extern.Stream} input
* @private
*/
static concatenateStreams_(output, input) {
// We keep the original stream's resolution, frame rate,
// sample rate, and channel count to ensure that it's properly
// matched with similar content in other periods further down
// the line.
// Combine arrays, keeping only the unique elements
const combineArrays = (output, input) => {
if (!output) {
output = [];
}
for (const item of input) {
if (!output.includes(item)) {
output.push(item);
}
}
return output;
};
output.roles = combineArrays(output.roles, input.roles);
if (input.emsgSchemeIdUris) {
output.emsgSchemeIdUris = combineArrays(
output.emsgSchemeIdUris, input.emsgSchemeIdUris);
}
for (const keyId of input.keyIds) {
output.keyIds.add(keyId);
}
if (output.originalId == null) {
output.originalId = input.originalId;
} else {
const newOriginalId = (input.originalId || '');
if (newOriginalId && !output.originalId.endsWith(newOriginalId)) {
output.originalId += ',' + newOriginalId;
}
}
const commonDrmInfos = shaka.drm.DrmUtils.getCommonDrmInfos(
output.drmInfos, input.drmInfos);
if (input.drmInfos.length && output.drmInfos.length &&
!commonDrmInfos.length) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,
shaka.util.Error.Code.INCONSISTENT_DRM_ACROSS_PERIODS);
}
output.drmInfos = commonDrmInfos;
// The output is encrypted if any input was encrypted.
output.encrypted = output.encrypted || input.encrypted;
// Combine the closed captions maps.
if (input.closedCaptions) {
if (!output.closedCaptions) {
output.closedCaptions = new Map();
}
for (const [key, value] of input.closedCaptions) {
output.closedCaptions.set(key, value);
}
}
// Prioritize the highest bandwidth
if (output.bandwidth && input.bandwidth) {
output.bandwidth = Math.max(output.bandwidth, input.bandwidth);
}
// Combine trick-play video streams, if present.
if (input.trickModeVideo) {
if (!output.trickModeVideo) {
// Create a fresh output stream for trick-mode playback.
output.trickModeVideo = shaka.util.PeriodCombiner.cloneStream_(
input.trickModeVideo);
output.trickModeVideo.matchedStreams = [];
output.trickModeVideo.createSegmentIndex = () => {
if (output.trickModeVideo.segmentIndex) {
return Promise.resolve();
}
const segmentIndex = new shaka.media.MetaSegmentIndex();
goog.asserts.assert(output.trickModeVideo.matchedStreams,
'trickmode matched streams should exist');
for (const stream of output.trickModeVideo.matchedStreams) {
goog.asserts.assert(stream.segmentIndex,
'trickmode segment index should exist');
segmentIndex.appendSegmentIndex(stream.segmentIndex);
}
output.trickModeVideo.segmentIndex = segmentIndex;
return Promise.resolve();
};
}
// Concatenate the trick mode input onto the trick mode output.
output.trickModeVideo.matchedStreams.push(input.trickModeVideo);
shaka.util.PeriodCombiner.concatenateStreams_(
output.trickModeVideo, input.trickModeVideo);
} else if (output.trickModeVideo) {
// We have a trick mode output, but no input from this Period. Fill it in
// from the standard input Stream.
output.trickModeVideo.matchedStreams.push(input);