-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
segment_index.js
862 lines (760 loc) · 23.6 KB
/
segment_index.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
/*! @license
* Shaka Player
* Copyright 2016 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
goog.provide('shaka.media.MetaSegmentIndex');
goog.provide('shaka.media.SegmentIndex');
goog.provide('shaka.media.SegmentIterator');
goog.require('goog.asserts');
goog.require('shaka.log');
goog.require('shaka.media.SegmentReference');
goog.require('shaka.util.IReleasable');
goog.require('shaka.util.Timer');
/**
* SegmentIndex.
*
* @implements {shaka.extern.SegmentIndex}
* @implements {shaka.util.IReleasable}
* @implements {Iterable.<!shaka.media.SegmentReference>}
* @export
*/
shaka.media.SegmentIndex = class {
/**
* @param {!Array.<!shaka.media.SegmentReference>} references The list of
* SegmentReferences, which must be sorted first by their start times
* (ascending) and second by their end times (ascending).
*/
constructor(references) {
if (goog.DEBUG) {
shaka.media.SegmentIndex.assertCorrectReferences_(references);
}
/** @protected {!Array.<!shaka.media.SegmentReference>} */
this.references = references;
/** @private {shaka.util.Timer} */
this.timer_ = null;
/**
* The number of references that have been removed from the front of the
* array. Used to create stable positions in the find/get APIs.
*
* @protected {number}
*/
this.numEvicted_ = 0;
/** @private {boolean} */
this.immutable_ = false;
}
/**
* Get immutability
*
* @return {boolean}
*/
getIsImmutable() {
return this.immutable_;
}
/**
* @override
* @export
*/
getNumReferences() {
return this.references.length;
}
/**
* @override
* @export
*/
getNumEvicted() {
return this.numEvicted_;
}
/**
* @override
* @export
*/
release() {
if (this.immutable_) {
return;
}
this.references = [];
if (this.timer_) {
this.timer_.stop();
}
this.timer_ = null;
}
/**
* Marks the index as immutable. Segments cannot be added or removed after
* this point. This doesn't affect the references themselves. This also
* makes the destroy/release methods do nothing.
*
* This is mainly for testing.
*
* @export
*/
markImmutable() {
this.immutable_ = true;
}
/**
* Iterates over all top-level segment references in this segment index.
* @param {function(!shaka.media.SegmentReference)} fn
*/
forEachTopLevelReference(fn) {
for (const reference of this.references) {
fn(reference);
}
}
/**
* Return the earliest reference, or null if empty.
* @return {shaka.media.SegmentReference}
*/
earliestReference() {
return this.references[0] || null;
}
/**
* Drop the first N references.
* Used in early HLS synchronization, and does not count as eviction.
* @param {number} n
*/
dropFirstReferences(n) {
this.references.splice(0, n);
}
/**
* @override
* @export
*/
find(time) {
// For live streams, searching from the end is faster. For VOD, it balances
// out either way. In both cases, references.length is small enough that
// the difference isn't huge.
const lastReferenceIndex = this.references.length - 1;
for (let i = lastReferenceIndex; i >= 0; --i) {
const r = this.references[i];
const start = r.startTime;
// A rounding error can cause /time/ to equal e.endTime or fall in between
// the references by a fraction of a second. To account for this, we use
// the start of the next segment as /end/, unless this is the last
// reference, in which case we use its end time as /end/.
const end = i < lastReferenceIndex ?
this.references[i + 1].startTime : r.endTime;
// Note that a segment ends immediately before the end time.
if ((time >= start) && (time < end)) {
return i + this.numEvicted_;
}
}
if (this.references.length && time < this.references[0].startTime) {
return this.numEvicted_;
}
return null;
}
/**
* @override
* @export
*/
get(position) {
if (this.references.length == 0) {
return null;
}
const index = position - this.numEvicted_;
if (index < 0 || index >= this.references.length) {
return null;
}
return this.references[index];
}
/**
* Offset all segment references by a fixed amount.
*
* @param {number} offset The amount to add to each segment's start and end
* times.
* @export
*/
offset(offset) {
if (!this.immutable_) {
for (const ref of this.references) {
ref.offset(offset);
}
}
}
/**
* Merges the given SegmentReferences. Supports extending the original
* references only. Will replace old references with equivalent new ones, and
* keep any unique old ones.
*
* Used, for example, by the DASH and HLS parser, where manifests may not list
* all available references, so we must keep available references in memory to
* fill the availability window.
*
* @param {!Array.<!shaka.media.SegmentReference>} references The list of
* SegmentReferences, which must be sorted first by their start times
* (ascending) and second by their end times (ascending).
*/
merge(references) {
if (goog.DEBUG) {
shaka.media.SegmentIndex.assertCorrectReferences_(references);
}
if (this.immutable_) {
return;
}
if (!references.length) {
return;
}
// Partial segments are used for live edge, and should be removed when they
// get older. Remove the old SegmentReferences after the first new
// reference's start time.
// Use times rounded to the millisecond for filtering purposes, so that
// tiny rounding errors will not result in duplicate segments in the index.
const firstStartTime = Math.round(references[0].startTime * 1000) / 1000;
this.references = this.references.filter((r) => {
return (Math.round(r.startTime * 1000) / 1000) < firstStartTime;
});
this.references.push(...references);
if (goog.DEBUG) {
shaka.media.SegmentIndex.assertCorrectReferences_(this.references);
}
}
/**
* Merges the given SegmentReferences and evicts the ones that end before the
* given time. Supports extending the original references only.
* Will not replace old references or interleave new ones.
* Used, for example, by the DASH and HLS parser, where manifests may not list
* all available references, so we must keep available references in memory to
* fill the availability window.
*
* @param {!Array.<!shaka.media.SegmentReference>} references The list of
* SegmentReferences, which must be sorted first by their start times
* (ascending) and second by their end times (ascending).
* @param {number} windowStart The start of the availability window to filter
* out the references that are no longer available.
* @export
*/
mergeAndEvict(references, windowStart) {
// Filter out the references that are no longer available to avoid
// repeatedly evicting them and messing up eviction count.
references = references.filter((r) => {
return r.endTime > windowStart &&
(this.references.length == 0 ||
r.endTime > this.references[0].startTime);
});
const oldFirstRef = this.references[0];
this.merge(references);
const newFirstRef = this.references[0];
if (oldFirstRef) {
// We don't compare the actual ref, since the object could legitimately be
// replaced with an equivalent. Even the URIs could change due to
// load-balancing actions taken by the server. However, if the time
// changes, its not an equivalent reference.
goog.asserts.assert(oldFirstRef.startTime == newFirstRef.startTime,
'SegmentIndex.merge should not change the first reference time!');
}
this.evict(windowStart);
}
/**
* Removes all SegmentReferences that end before the given time.
*
* @param {number} time The time in seconds.
* @export
*/
evict(time) {
if (this.immutable_) {
return;
}
const oldSize = this.references.length;
this.references = this.references.filter((ref) => ref.endTime > time);
const newSize = this.references.length;
const diff = oldSize - newSize;
// Tracking the number of evicted refs will keep their "positions" stable
// for the caller.
this.numEvicted_ += diff;
}
/**
* Drops references that start after windowEnd, or end before windowStart,
* and contracts the last reference so that it ends at windowEnd.
*
* Do not call on the last period of a live presentation (unknown duration).
* It is okay to call on the other periods of a live presentation, where the
* duration is known and another period has been added.
*
* @param {number} windowStart
* @param {?number} windowEnd
* @param {boolean=} isNew Whether this is a new SegmentIndex and we shouldn't
* update the number of evicted elements.
* @export
*/
fit(windowStart, windowEnd, isNew = false) {
goog.asserts.assert(windowEnd != null,
'Content duration must be known for static content!');
goog.asserts.assert(windowEnd != Infinity,
'Content duration must be finite for static content!');
if (this.immutable_) {
return;
}
// Trim out references we will never use.
while (this.references.length) {
const lastReference = this.references[this.references.length - 1];
if (lastReference.startTime >= windowEnd) {
this.references.pop();
} else {
break;
}
}
while (this.references.length) {
const firstReference = this.references[0];
if (firstReference.endTime <= windowStart) {
this.references.shift();
if (!isNew) {
this.numEvicted_++;
}
} else {
break;
}
}
if (this.references.length == 0) {
return;
}
// Adjust the last SegmentReference.
const lastReference = this.references[this.references.length - 1];
const newReference = new shaka.media.SegmentReference(
lastReference.startTime,
/* endTime= */ windowEnd,
lastReference.getUrisInner,
lastReference.startByte,
lastReference.endByte,
lastReference.initSegmentReference,
lastReference.timestampOffset,
lastReference.appendWindowStart,
lastReference.appendWindowEnd,
lastReference.partialReferences,
lastReference.tilesLayout,
lastReference.tileDuration,
lastReference.syncTime,
lastReference.status,
lastReference.aesKey,
);
newReference.mimeType = lastReference.mimeType;
newReference.codecs = lastReference.codecs;
newReference.discontinuitySequence = lastReference.discontinuitySequence;
this.references[this.references.length - 1] = newReference;
}
/**
* Updates the references every so often. Stops when the references list
* returned by the callback is null.
*
* @param {number} interval The interval in seconds.
* @param {function():Array.<shaka.media.SegmentReference>} updateCallback
* @export
*/
updateEvery(interval, updateCallback) {
goog.asserts.assert(!this.timer_, 'SegmentIndex timer already started!');
if (this.immutable_) {
return;
}
if (this.timer_) {
this.timer_.stop();
}
this.timer_ = new shaka.util.Timer(() => {
const references = updateCallback();
if (references) {
this.references.push(...references);
} else {
this.timer_.stop();
this.timer_ = null;
}
});
this.timer_.tickEvery(interval);
}
/** @return {!shaka.media.SegmentIterator} */
[Symbol.iterator]() {
const iter = this.getIteratorForTime(0);
goog.asserts.assert(iter != null, 'Iterator for 0 should never be null!');
return iter;
}
/**
* Returns a new iterator that initially points to the segment that contains
* the given time, or the nearest independent segment before it.
*
* Like the normal iterator, next() must be called first to get to the first
* element. Returns null if we do not find a segment at the
* requested time.
*
* The first segment returned by the iterator _MUST_ be an independent
* segment. Assumes that only partial references can be dependent, based on
* RFC 8216 rev 13, section 8.1: "Each (non-Partial) Media Segment in a Media
* Playlist will contain at least one independent frame."
*
* @param {number} time
* @param {boolean=} allowNonIndepedent
* @param {boolean=} reverse
* @return {?shaka.media.SegmentIterator}
* @export
*/
getIteratorForTime(time, allowNonIndepedent = false, reverse = false) {
let index = this.find(time);
if (index == null) {
return null;
}
const ref = this.get(index);
// Adjust index to point to previous or next index (if reversed), so first
// next() call will traverse in proper direction.
if (!reverse) {
index--;
} else {
index++;
}
let partialSegmentIndex = -1;
if (ref && ref.hasPartialSegments()) {
// Look for a partial SegmentReference.
for (let i = ref.partialReferences.length - 1; i >= 0; --i) {
let r = ref.partialReferences[i];
// Note that a segment ends immediately before the end time.
if ((time >= r.startTime) && (time < r.endTime)) {
if (!allowNonIndepedent) {
// Find an independent partial segment by moving backwards.
while (i && (!r.isIndependent())) {
i--;
r = ref.partialReferences[i];
}
if (!r.isIndependent()) {
shaka.log.alwaysError('No independent partial segment found!');
return null;
}
}
// Call to next() should move the partial segment, not the full
// segment.
if (reverse) {
index--;
} else {
index++;
}
partialSegmentIndex = i - 1;
break;
}
}
}
return new shaka.media.SegmentIterator(
this, index, partialSegmentIndex, reverse);
}
/**
* @return {boolean}
*/
isEmpty() {
return this.getNumReferences() == 0;
}
/**
* Create a SegmentIndex for a single segment of the given start time and
* duration at the given URIs.
*
* @param {number} startTime
* @param {number} duration
* @param {!Array.<string>} uris
* @return {!shaka.media.SegmentIndex}
* @export
*/
static forSingleSegment(startTime, duration, uris) {
const reference = new shaka.media.SegmentReference(
/* startTime= */ startTime,
/* endTime= */ startTime + duration,
/* getUris= */ () => uris,
/* startByte= */ 0,
/* endByte= */ null,
/* initSegmentReference= */ null,
/* presentationTimeOffset= */ startTime,
/* appendWindowStart= */ startTime,
/* appendWindowEnd= */ startTime + duration);
return new shaka.media.SegmentIndex([reference]);
}
};
if (goog.DEBUG) {
/**
* Asserts that the given SegmentReferences are sorted.
*
* @param {!Array.<shaka.media.SegmentReference>} references
* @private
*/
shaka.media.SegmentIndex.assertCorrectReferences_ = (references) => {
goog.asserts.assert(references.every((r2, i) => {
if (i == 0) {
return true;
}
const r1 = references[i - 1];
if (r1.startTime < r2.startTime) {
return true;
} else if (r1.startTime > r2.startTime) {
return false;
} else {
if (r1.endTime <= r2.endTime) {
return true;
} else {
return false;
}
}
}), 'SegmentReferences are incorrect');
};
}
/**
* An iterator over a SegmentIndex's references.
*
* @implements {Iterator.<shaka.media.SegmentReference>}
* @export
*/
shaka.media.SegmentIterator = class {
/**
* @param {shaka.media.SegmentIndex} segmentIndex
* @param {number} index
* @param {number} partialSegmentIndex
* @param {boolean} reverse
*/
constructor(segmentIndex, index, partialSegmentIndex, reverse) {
/** @private {shaka.media.SegmentIndex} */
this.segmentIndex_ = segmentIndex;
/** @private {number} */
this.currentPosition_ = index;
/** @private {number} */
this.currentPartialPosition_ = partialSegmentIndex;
/** @private {boolean} */
this.reverse = reverse;
}
/**
* @param {boolean} reverse
* @export
*/
setReverse(reverse) {
this.reverse = reverse;
}
/**
* @return {number}
* @export
*/
currentPosition() {
return this.currentPosition_;
}
/**
* @return {shaka.media.SegmentReference}
* @export
*/
current() {
let ref = this.segmentIndex_.get(this.currentPosition_);
// When we advance past the end of partial references in next(), then add
// new references in merge(), the pointers may not make sense any more.
// This adjusts the invalid pointer values to point to the next newly added
// segment or partial segment.
if (ref && ref.hasPartialSegments() && ref.hasAllPartialSegments() &&
this.currentPartialPosition_ >= ref.partialReferences.length) {
this.currentPosition_++;
this.currentPartialPosition_ = 0;
ref = this.segmentIndex_.get(this.currentPosition_);
}
// If the regular segment contains partial segments, get the current
// partial SegmentReference.
if (ref && ref.hasPartialSegments()) {
const partial = ref.partialReferences[this.currentPartialPosition_];
return partial;
}
return ref;
}
/**
* @override
* @export
*/
next() {
const ref = this.segmentIndex_.get(this.currentPosition_);
if (!this.reverse) {
if (ref && ref.hasPartialSegments()) {
// If the regular segment contains partial segments, move to the next
// partial SegmentReference.
this.currentPartialPosition_++;
// If the current regular segment has been published completely, and
// we've reached the end of its partial segments list, move to the next
// regular segment.
// If the Partial Segments list is still on the fly, do not move to
// the next regular segment.
if (ref.hasAllPartialSegments() &&
this.currentPartialPosition_ == ref.partialReferences.length) {
this.currentPosition_++;
this.currentPartialPosition_ = 0;
}
} else {
// If the regular segment doesn't contain partial segments, move to the
// next regular segment.
this.currentPosition_++;
this.currentPartialPosition_ = 0;
}
} else {
if (ref && ref.hasPartialSegments()) {
// If the regular segment contains partial segments, move to the
// previous partial SegmentReference.
this.currentPartialPosition_--;
if (this.currentPartialPosition_ < 0) {
this.currentPosition_--;
const prevRef = this.segmentIndex_.get(this.currentPosition_);
if (prevRef && prevRef.hasPartialSegments()) {
this.currentPartialPosition_ = prevRef.partialReferences.length - 1;
} else {
this.currentPartialPosition_ = 0;
}
}
} else {
// If the regular segment doesn't contain partial segments, move to the
// previous regular segment.
this.currentPosition_--;
this.currentPartialPosition_ = 0;
}
}
const res = this.current();
return {
'value': res,
'done': !res,
};
}
};
/**
* A meta-SegmentIndex composed of multiple other SegmentIndexes.
* Used in constructing multi-Period Streams for DASH.
*
* @extends shaka.media.SegmentIndex
* @implements {shaka.util.IReleasable}
* @implements {Iterable.<!shaka.media.SegmentReference>}
* @export
*/
shaka.media.MetaSegmentIndex = class extends shaka.media.SegmentIndex {
/** */
constructor() {
super([]);
/** @private {!Array.<!shaka.media.SegmentIndex>} */
this.indexes_ = [];
}
/**
* Append a SegmentIndex to this MetaSegmentIndex. This effectively stitches
* the underlying Stream onto the end of the multi-Period Stream represented
* by this MetaSegmentIndex.
*
* @param {!shaka.media.SegmentIndex} segmentIndex
*/
appendSegmentIndex(segmentIndex) {
goog.asserts.assert(
this.indexes_.length == 0 || segmentIndex.getNumEvicted() == 0,
'Should not append a new segment index with already-evicted segments');
this.indexes_.push(segmentIndex);
}
/**
* Create a clone of this MetaSegmentIndex containing all the same indexes.
*
* @return {!shaka.media.MetaSegmentIndex}
*/
clone() {
const clone = new shaka.media.MetaSegmentIndex();
// Be careful to clone the Array. We don't want to share the reference with
// our clone and affect each other accidentally.
clone.indexes_ = this.indexes_.slice();
return clone;
}
/**
* @override
* @export
*/
release() {
for (const index of this.indexes_) {
index.release();
}
this.indexes_ = [];
}
/**
* @override
* @export
*/
forEachTopLevelReference(fn) {
for (const index of this.indexes_) {
index.forEachTopLevelReference(fn);
}
}
/**
* @override
* @export
*/
find(time) {
let numPassedInEarlierIndexes = 0;
for (const index of this.indexes_) {
const position = index.find(time);
if (position != null) {
return position + numPassedInEarlierIndexes;
}
numPassedInEarlierIndexes += index.getNumEvicted() +
index.getNumReferences();
}
return null;
}
/**
* @override
* @export
*/
get(position) {
let numPassedInEarlierIndexes = 0;
let sawSegments = false;
for (const index of this.indexes_) {
goog.asserts.assert(
!sawSegments || index.getNumEvicted() == 0,
'Should not see evicted segments after available segments');
const reference = index.get(position - numPassedInEarlierIndexes);
if (reference) {
return reference;
}
const num = index.getNumReferences();
numPassedInEarlierIndexes += index.getNumEvicted() + num;
sawSegments = sawSegments || num != 0;
}
return null;
}
/**
* @override
* @export
*/
offset(offset) {
// offset() is only used by HLS, and MetaSegmentIndex is only used for DASH.
goog.asserts.assert(
false, 'offset() should not be used in MetaSegmentIndex!');
}
/**
* @override
* @export
*/
merge(references) {
// merge() is only used internally by the DASH and HLS parser on
// SegmentIndexes, but never on MetaSegmentIndex.
goog.asserts.assert(
false, 'merge() should not be used in MetaSegmentIndex!');
}
/**
* @override
* @export
*/
evict(time) {
// evict() is only used internally by the DASH and HLS parser on
// SegmentIndexes, but never on MetaSegmentIndex.
goog.asserts.assert(
false, 'evict() should not be used in MetaSegmentIndex!');
}
/**
* @override
* @export
*/
mergeAndEvict(references, windowStart) {
// mergeAndEvict() is only used internally by the DASH and HLS parser on
// SegmentIndexes, but never on MetaSegmentIndex.
goog.asserts.assert(
false, 'mergeAndEvict() should not be used in MetaSegmentIndex!');
}
/**
* @override
* @export
*/
fit(windowStart, windowEnd) {
// fit() is only used internally by manifest parsers on SegmentIndexes, but
// never on MetaSegmentIndex.
goog.asserts.assert(false, 'fit() should not be used in MetaSegmentIndex!');
}
/**
* @override
* @export
*/
updateEvery(interval, updateCallback) {
// updateEvery() is only used internally by the DASH parser on
// SegmentIndexes, but never on MetaSegmentIndex.
goog.asserts.assert(
false, 'updateEvery() should not be used in MetaSegmentIndex!');
}
};