-
Notifications
You must be signed in to change notification settings - Fork 414
/
segment-loader.js
1496 lines (1292 loc) · 46.8 KB
/
segment-loader.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
/**
* @file segment-loader.js
*/
import Playlist from './playlist';
import videojs from 'video.js';
import SourceUpdater from './source-updater';
import Config from './config';
import window from 'global/window';
import { removeCuesFromTrack } from './mse/remove-cues-from-track';
import { initSegmentId, segmentKeyId } from './bin-utils';
import { mediaSegmentRequest, REQUEST_ERRORS } from './media-segment-request';
import { TIME_FUDGE_FACTOR, timeUntilRebuffer as timeUntilRebuffer_ } from './ranges';
import { minRebufferMaxBandwidthSelector } from './playlist-selectors';
import { addCaptionData, createCaptionsTrackIfNotExists } from './util/text-tracks';
import { CaptionParser } from 'mux.js/lib/mp4';
import logger from './util/logger';
// in ms
const CHECK_BUFFER_DELAY = 500;
/**
* Determines if we should call endOfStream on the media source based
* on the state of the buffer or if appened segment was the final
* segment in the playlist.
*
* @param {Object} playlist a media playlist object
* @param {Object} mediaSource the MediaSource object
* @param {Number} segmentIndex the index of segment we last appended
* @returns {Boolean} do we need to call endOfStream on the MediaSource
*/
const detectEndOfStream = function(playlist, mediaSource, segmentIndex) {
if (!playlist || !mediaSource) {
return false;
}
let segments = playlist.segments;
// determine a few boolean values to help make the branch below easier
// to read
let appendedLastSegment = segmentIndex === segments.length;
// if we've buffered to the end of the video, we need to call endOfStream
// so that MediaSources can trigger the `ended` event when it runs out of
// buffered data instead of waiting for me
return playlist.endList &&
mediaSource.readyState === 'open' &&
appendedLastSegment;
};
const finite = (num) => typeof num === 'number' && isFinite(num);
export const illegalMediaSwitch = (loaderType, startingMedia, newSegmentMedia) => {
// Although these checks should most likely cover non 'main' types, for now it narrows
// the scope of our checks.
if (loaderType !== 'main' || !startingMedia || !newSegmentMedia) {
return null;
}
if (!newSegmentMedia.containsAudio && !newSegmentMedia.containsVideo) {
return 'Neither audio nor video found in segment.';
}
if (startingMedia.containsVideo && !newSegmentMedia.containsVideo) {
return 'Only audio found in segment when we expected video.' +
' We can\'t switch to audio only from a stream that had video.' +
' To get rid of this message, please add codec information to the manifest.';
}
if (!startingMedia.containsVideo && newSegmentMedia.containsVideo) {
return 'Video found in segment when we expected only audio.' +
' We can\'t switch to a stream with video from an audio only stream.' +
' To get rid of this message, please add codec information to the manifest.';
}
return null;
};
/**
* Calculates a time value that is safe to remove from the back buffer without interupting
* playback.
*
* @param {TimeRange} seekable
* The current seekable range
* @param {Number} currentTime
* The current time of the player
* @param {Number} targetDuration
* The target duration of the current playlist
* @return {Number}
* Time that is safe to remove from the back buffer without interupting playback
*/
export const safeBackBufferTrimTime = (seekable, currentTime, targetDuration) => {
let removeToTime;
if (seekable.length &&
seekable.start(0) > 0 &&
seekable.start(0) < currentTime) {
// If we have a seekable range use that as the limit for what can be removed safely
removeToTime = seekable.start(0);
} else {
// otherwise remove anything older than 30 seconds before the current play head
removeToTime = currentTime - 30;
}
// Don't allow removing from the buffer within target duration of current time
// to avoid the possibility of removing the GOP currently being played which could
// cause playback stalls.
return Math.min(removeToTime, currentTime - targetDuration);
};
const segmentInfoString = (segmentInfo) => {
const {
segment: {
start,
end
},
playlist: {
mediaSequence: seq,
id,
segments = []
},
mediaIndex: index,
timeline
} = segmentInfo;
return [
`appending [${index}] of [${seq}, ${seq + segments.length}] from playlist [${id}]`,
`[${start} => ${end}] in timeline [${timeline}]`
].join(' ');
};
/**
* An object that manages segment loading and appending.
*
* @class SegmentLoader
* @param {Object} options required and optional options
* @extends videojs.EventTarget
*/
export default class SegmentLoader extends videojs.EventTarget {
constructor(settings, options = {}) {
super();
// check pre-conditions
if (!settings) {
throw new TypeError('Initialization settings are required');
}
if (typeof settings.currentTime !== 'function') {
throw new TypeError('No currentTime getter specified');
}
if (!settings.mediaSource) {
throw new TypeError('No MediaSource specified');
}
// public properties
this.bandwidth = settings.bandwidth;
this.throughput = {rate: 0, count: 0};
this.roundTrip = NaN;
this.resetStats_();
this.mediaIndex = null;
// private settings
this.hasPlayed_ = settings.hasPlayed;
this.currentTime_ = settings.currentTime;
this.seekable_ = settings.seekable;
this.seeking_ = settings.seeking;
this.duration_ = settings.duration;
this.mediaSource_ = settings.mediaSource;
this.hls_ = settings.hls;
this.loaderType_ = settings.loaderType;
this.startingMedia_ = void 0;
this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
this.goalBufferLength_ = settings.goalBufferLength;
this.sourceType_ = settings.sourceType;
this.inbandTextTracks_ = settings.inbandTextTracks;
this.state_ = 'INIT';
// private instance variables
this.checkBufferTimeout_ = null;
this.error_ = void 0;
this.currentTimeline_ = -1;
this.pendingSegment_ = null;
this.mimeType_ = null;
this.sourceUpdater_ = null;
this.xhrOptions_ = null;
// Fragmented mp4 playback
this.activeInitSegmentId_ = null;
this.initSegments_ = {};
// HLSe playback
this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
this.keyCache_ = {};
// Fmp4 CaptionParser
if (this.loaderType_ === 'main') {
this.captionParser_ = new CaptionParser();
} else {
this.captionParser_ = null;
}
this.decrypter_ = settings.decrypter;
// Manages the tracking and generation of sync-points, mappings
// between a time in the display time and a segment index within
// a playlist
this.syncController_ = settings.syncController;
this.syncPoint_ = {
segmentIndex: 0,
time: 0
};
this.syncController_.on('syncinfoupdate', () => this.trigger('syncinfoupdate'));
this.mediaSource_.addEventListener('sourceopen', () => this.ended_ = false);
// ...for determining the fetch location
this.fetchAtBuffer_ = false;
this.logger_ = logger(`SegmentLoader[${this.loaderType_}]`);
Object.defineProperty(this, 'state', {
get() {
return this.state_;
},
set(newState) {
if (newState !== this.state_) {
this.logger_(`${this.state_} -> ${newState}`);
this.state_ = newState;
}
}
});
}
/**
* reset all of our media stats
*
* @private
*/
resetStats_() {
this.mediaBytesTransferred = 0;
this.mediaRequests = 0;
this.mediaRequestsAborted = 0;
this.mediaRequestsTimedout = 0;
this.mediaRequestsErrored = 0;
this.mediaTransferDuration = 0;
this.mediaSecondsLoaded = 0;
}
/**
* dispose of the SegmentLoader and reset to the default state
*/
dispose() {
this.state = 'DISPOSED';
this.pause();
this.abort_();
if (this.sourceUpdater_) {
this.sourceUpdater_.dispose();
}
this.resetStats_();
if (this.captionParser_) {
this.captionParser_.reset();
}
}
/**
* abort anything that is currently doing on with the SegmentLoader
* and reset to a default state
*/
abort() {
if (this.state !== 'WAITING') {
if (this.pendingSegment_) {
this.pendingSegment_ = null;
}
return;
}
this.abort_();
// We aborted the requests we were waiting on, so reset the loader's state to READY
// since we are no longer "waiting" on any requests. XHR callback is not always run
// when the request is aborted. This will prevent the loader from being stuck in the
// WAITING state indefinitely.
this.state = 'READY';
// don't wait for buffer check timeouts to begin fetching the
// next segment
if (!this.paused()) {
this.monitorBuffer_();
}
}
/**
* abort all pending xhr requests and null any pending segements
*
* @private
*/
abort_() {
if (this.pendingSegment_) {
this.pendingSegment_.abortRequests();
}
// clear out the segment being processed
this.pendingSegment_ = null;
}
/**
* set an error on the segment loader and null out any pending segements
*
* @param {Error} error the error to set on the SegmentLoader
* @return {Error} the error that was set or that is currently set
*/
error(error) {
if (typeof error !== 'undefined') {
this.error_ = error;
}
this.pendingSegment_ = null;
return this.error_;
}
endOfStream() {
this.ended_ = true;
this.pause();
this.trigger('ended');
}
/**
* Indicates which time ranges are buffered
*
* @return {TimeRange}
* TimeRange object representing the current buffered ranges
*/
buffered_() {
if (!this.sourceUpdater_) {
return videojs.createTimeRanges();
}
return this.sourceUpdater_.buffered();
}
/**
* Gets and sets init segment for the provided map
*
* @param {Object} map
* The map object representing the init segment to get or set
* @param {Boolean=} set
* If true, the init segment for the provided map should be saved
* @return {Object}
* map object for desired init segment
*/
initSegment(map, set = false) {
if (!map) {
return null;
}
const id = initSegmentId(map);
let storedMap = this.initSegments_[id];
if (set && !storedMap && map.bytes) {
this.initSegments_[id] = storedMap = {
resolvedUri: map.resolvedUri,
byterange: map.byterange,
bytes: map.bytes,
timescales: map.timescales,
videoTrackIds: map.videoTrackIds
};
}
return storedMap || map;
}
/**
* Gets and sets key for the provided key
*
* @param {Object} key
* The key object representing the key to get or set
* @param {Boolean=} set
* If true, the key for the provided key should be saved
* @return {Object}
* Key object for desired key
*/
segmentKey(key, set = false) {
if (!key) {
return null;
}
const id = segmentKeyId(key);
let storedKey = this.keyCache_[id];
// TODO: We should use the HTTP Expires header to invalidate our cache per
// https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
this.keyCache_[id] = storedKey = {
resolvedUri: key.resolvedUri,
bytes: key.bytes
};
}
const result = {
resolvedUri: (storedKey || key).resolvedUri
};
if (storedKey) {
result.bytes = storedKey.bytes;
}
return result;
}
/**
* Returns true if all configuration required for loading is present, otherwise false.
*
* @return {Boolean} True if the all configuration is ready for loading
* @private
*/
couldBeginLoading_() {
return this.playlist_ &&
// the source updater is created when init_ is called, so either having a
// source updater or being in the INIT state with a mimeType is enough
// to say we have all the needed configuration to start loading.
(this.sourceUpdater_ || (this.mimeType_ && this.state === 'INIT')) &&
!this.paused();
}
/**
* load a playlist and start to fill the buffer
*/
load() {
// un-pause
this.monitorBuffer_();
// if we don't have a playlist yet, keep waiting for one to be
// specified
if (!this.playlist_) {
return;
}
// not sure if this is the best place for this
this.syncController_.setDateTimeMapping(this.playlist_);
// if all the configuration is ready, initialize and begin loading
if (this.state === 'INIT' && this.couldBeginLoading_()) {
return this.init_();
}
// if we're in the middle of processing a segment already, don't
// kick off an additional segment request
if (!this.couldBeginLoading_() ||
(this.state !== 'READY' &&
this.state !== 'INIT')) {
return;
}
this.state = 'READY';
}
/**
* Once all the starting parameters have been specified, begin
* operation. This method should only be invoked from the INIT
* state.
*
* @private
*/
init_() {
this.state = 'READY';
this.sourceUpdater_ = new SourceUpdater(this.mediaSource_,
this.mimeType_,
this.loaderType_,
this.sourceBufferEmitter_);
this.resetEverything();
return this.monitorBuffer_();
}
/**
* set a playlist on the segment loader
*
* @param {PlaylistLoader} media the playlist to set on the segment loader
*/
playlist(newPlaylist, options = {}) {
if (!newPlaylist) {
return;
}
let oldPlaylist = this.playlist_;
let segmentInfo = this.pendingSegment_;
this.playlist_ = newPlaylist;
this.xhrOptions_ = options;
// when we haven't started playing yet, the start of a live playlist
// is always our zero-time so force a sync update each time the playlist
// is refreshed from the server
if (!this.hasPlayed_()) {
newPlaylist.syncInfo = {
mediaSequence: newPlaylist.mediaSequence,
time: 0
};
}
let oldId = null;
if (oldPlaylist) {
if (oldPlaylist.id) {
oldId = oldPlaylist.id;
} else if (oldPlaylist.uri) {
oldId = oldPlaylist.uri;
}
}
this.logger_(`playlist update [${oldId} => ${newPlaylist.id || newPlaylist.uri}]`);
// in VOD, this is always a rendition switch (or we updated our syncInfo above)
// in LIVE, we always want to update with new playlists (including refreshes)
this.trigger('syncinfoupdate');
// if we were unpaused but waiting for a playlist, start
// buffering now
if (this.state === 'INIT' && this.couldBeginLoading_()) {
return this.init_();
}
if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
if (this.mediaIndex !== null) {
// we must "resync" the segment loader when we switch renditions and
// the segment loader is already synced to the previous rendition
this.resyncLoader();
}
// the rest of this function depends on `oldPlaylist` being defined
return;
}
// we reloaded the same playlist so we are in a live scenario
// and we will likely need to adjust the mediaIndex
let mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
this.logger_(`live window shift [${mediaSequenceDiff}]`);
// update the mediaIndex on the SegmentLoader
// this is important because we can abort a request and this value must be
// equal to the last appended mediaIndex
if (this.mediaIndex !== null) {
this.mediaIndex -= mediaSequenceDiff;
}
// update the mediaIndex on the SegmentInfo object
// this is important because we will update this.mediaIndex with this value
// in `handleUpdateEnd_` after the segment has been successfully appended
if (segmentInfo) {
segmentInfo.mediaIndex -= mediaSequenceDiff;
// we need to update the referenced segment so that timing information is
// saved for the new playlist's segment, however, if the segment fell off the
// playlist, we can leave the old reference and just lose the timing info
if (segmentInfo.mediaIndex >= 0) {
segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
}
}
this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
}
/**
* Prevent the loader from fetching additional segments. If there
* is a segment request outstanding, it will finish processing
* before the loader halts. A segment loader can be unpaused by
* calling load().
*/
pause() {
if (this.checkBufferTimeout_) {
window.clearTimeout(this.checkBufferTimeout_);
this.checkBufferTimeout_ = null;
}
}
/**
* Returns whether the segment loader is fetching additional
* segments when given the opportunity. This property can be
* modified through calls to pause() and load().
*/
paused() {
return this.checkBufferTimeout_ === null;
}
/**
* create/set the following mimetype on the SourceBuffer through a
* SourceUpdater
*
* @param {String} mimeType the mime type string to use
* @param {Object} sourceBufferEmitter an event emitter that fires when a source buffer
* is added to the media source
*/
mimeType(mimeType, sourceBufferEmitter) {
if (this.mimeType_) {
return;
}
this.mimeType_ = mimeType;
this.sourceBufferEmitter_ = sourceBufferEmitter;
// if we were unpaused but waiting for a sourceUpdater, start
// buffering now
if (this.state === 'INIT' && this.couldBeginLoading_()) {
this.init_();
}
}
/**
* Delete all the buffered data and reset the SegmentLoader
* @param {Function} [done] an optional callback to be executed when the remove
* operation is complete
*/
resetEverything(done) {
this.ended_ = false;
this.resetLoader();
this.remove(0, this.duration_(), done);
// clears fmp4 captions
if (this.captionParser_) {
this.captionParser_.clearAllCaptions();
}
this.trigger('reseteverything');
}
/**
* Force the SegmentLoader to resync and start loading around the currentTime instead
* of starting at the end of the buffer
*
* Useful for fast quality changes
*/
resetLoader() {
this.fetchAtBuffer_ = false;
this.resyncLoader();
}
/**
* Force the SegmentLoader to restart synchronization and make a conservative guess
* before returning to the simple walk-forward method
*/
resyncLoader() {
this.mediaIndex = null;
this.syncPoint_ = null;
this.abort();
}
/**
* Remove any data in the source buffer between start and end times
* @param {Number} start - the start time of the region to remove from the buffer
* @param {Number} end - the end time of the region to remove from the buffer
* @param {Function} [done] - an optional callback to be executed when the remove
* operation is complete
*/
remove(start, end, done) {
if (this.sourceUpdater_) {
this.sourceUpdater_.remove(start, end, done);
}
removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
if (this.inbandTextTracks_) {
for (let id in this.inbandTextTracks_) {
removeCuesFromTrack(start, end, this.inbandTextTracks_[id]);
}
}
}
/**
* (re-)schedule monitorBufferTick_ to run as soon as possible
*
* @private
*/
monitorBuffer_() {
if (this.checkBufferTimeout_) {
window.clearTimeout(this.checkBufferTimeout_);
}
this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), 1);
}
/**
* As long as the SegmentLoader is in the READY state, periodically
* invoke fillBuffer_().
*
* @private
*/
monitorBufferTick_() {
if (this.state === 'READY') {
this.fillBuffer_();
}
if (this.checkBufferTimeout_) {
window.clearTimeout(this.checkBufferTimeout_);
}
this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this),
CHECK_BUFFER_DELAY);
}
/**
* fill the buffer with segements unless the sourceBuffers are
* currently updating
*
* Note: this function should only ever be called by monitorBuffer_
* and never directly
*
* @private
*/
fillBuffer_() {
if (this.sourceUpdater_.updating()) {
return;
}
if (!this.syncPoint_) {
this.syncPoint_ = this.syncController_.getSyncPoint(this.playlist_,
this.duration_(),
this.currentTimeline_,
this.currentTime_());
}
// see if we need to begin loading immediately
let segmentInfo = this.checkBuffer_(this.buffered_(),
this.playlist_,
this.mediaIndex,
this.hasPlayed_(),
this.currentTime_(),
this.syncPoint_);
if (!segmentInfo) {
return;
}
if (this.isEndOfStream_(segmentInfo.mediaIndex)) {
this.endOfStream();
return;
}
if (segmentInfo.mediaIndex === this.playlist_.segments.length - 1 &&
this.mediaSource_.readyState === 'ended' &&
!this.seeking_()) {
return;
}
// We will need to change timestampOffset of the sourceBuffer if either of
// the following conditions are true:
// - The segment.timeline !== this.currentTimeline
// (we are crossing a discontinuity somehow)
// - The "timestampOffset" for the start of this segment is less than
// the currently set timestampOffset
// Also, clear captions if we are crossing a discontinuity boundary
if (segmentInfo.timeline !== this.currentTimeline_ ||
((segmentInfo.startOfSegment !== null) &&
segmentInfo.startOfSegment < this.sourceUpdater_.timestampOffset())) {
this.syncController_.reset();
segmentInfo.timestampOffset = segmentInfo.startOfSegment;
if (this.captionParser_) {
this.captionParser_.clearAllCaptions();
}
}
this.loadSegment_(segmentInfo);
}
/**
* Determines if this segment loader is at the end of it's stream.
*
* @param {Number} mediaIndex the index of segment we last appended
* @param {Object} [playlist=this.playlist_] a media playlist object
* @returns {Boolean} true if at end of stream, false otherwise.
*/
isEndOfStream_(mediaIndex, playlist = this.playlist_) {
return detectEndOfStream(
playlist,
this.mediaSource_,
mediaIndex
) && !this.sourceUpdater_.updating();
}
/**
* Determines what segment request should be made, given current playback
* state.
*
* @param {TimeRanges} buffered - the state of the buffer
* @param {Object} playlist - the playlist object to fetch segments from
* @param {Number} mediaIndex - the previous mediaIndex fetched or null
* @param {Boolean} hasPlayed - a flag indicating whether we have played or not
* @param {Number} currentTime - the playback position in seconds
* @param {Object} syncPoint - a segment info object that describes the
* @returns {Object} a segment request object that describes the segment to load
*/
checkBuffer_(buffered, playlist, mediaIndex, hasPlayed, currentTime, syncPoint) {
let lastBufferedEnd = 0;
let startOfSegment;
if (buffered.length) {
lastBufferedEnd = buffered.end(buffered.length - 1);
}
let bufferedTime = Math.max(0, lastBufferedEnd - currentTime);
if (!playlist.segments.length) {
return null;
}
// if there is plenty of content buffered, and the video has
// been played before relax for awhile
if (bufferedTime >= this.goalBufferLength_()) {
return null;
}
// if the video has not yet played once, and we already have
// one segment downloaded do nothing
if (!hasPlayed && bufferedTime >= 1) {
return null;
}
// When the syncPoint is null, there is no way of determining a good
// conservative segment index to fetch from
// The best thing to do here is to get the kind of sync-point data by
// making a request
if (syncPoint === null) {
mediaIndex = this.getSyncSegmentCandidate_(playlist);
return this.generateSegmentInfo_(playlist, mediaIndex, null, true);
}
// Under normal playback conditions fetching is a simple walk forward
if (mediaIndex !== null) {
let segment = playlist.segments[mediaIndex];
if (segment && segment.end) {
startOfSegment = segment.end;
} else {
startOfSegment = lastBufferedEnd;
}
return this.generateSegmentInfo_(playlist, mediaIndex + 1, startOfSegment, false);
}
// There is a sync-point but the lack of a mediaIndex indicates that
// we need to make a good conservative guess about which segment to
// fetch
if (this.fetchAtBuffer_) {
// Find the segment containing the end of the buffer
let mediaSourceInfo = Playlist.getMediaInfoForTime(playlist,
lastBufferedEnd,
syncPoint.segmentIndex,
syncPoint.time);
mediaIndex = mediaSourceInfo.mediaIndex;
startOfSegment = mediaSourceInfo.startTime;
} else {
// Find the segment containing currentTime
let mediaSourceInfo = Playlist.getMediaInfoForTime(playlist,
currentTime,
syncPoint.segmentIndex,
syncPoint.time);
mediaIndex = mediaSourceInfo.mediaIndex;
startOfSegment = mediaSourceInfo.startTime;
}
return this.generateSegmentInfo_(playlist, mediaIndex, startOfSegment, false);
}
/**
* The segment loader has no recourse except to fetch a segment in the
* current playlist and use the internal timestamps in that segment to
* generate a syncPoint. This function returns a good candidate index
* for that process.
*
* @param {Object} playlist - the playlist object to look for a
* @returns {Number} An index of a segment from the playlist to load
*/
getSyncSegmentCandidate_(playlist) {
if (this.currentTimeline_ === -1) {
return 0;
}
let segmentIndexArray = playlist.segments
.map((s, i) => {
return {
timeline: s.timeline,
segmentIndex: i
};
}).filter(s => s.timeline === this.currentTimeline_);
if (segmentIndexArray.length) {
return segmentIndexArray[Math.min(segmentIndexArray.length - 1, 1)].segmentIndex;
}
return Math.max(playlist.segments.length - 1, 0);
}
generateSegmentInfo_(playlist, mediaIndex, startOfSegment, isSyncRequest) {
if (mediaIndex < 0 || mediaIndex >= playlist.segments.length) {
return null;
}
let segment = playlist.segments[mediaIndex];
return {
requestId: 'segment-loader-' + Math.random(),
// resolve the segment URL relative to the playlist
uri: segment.resolvedUri,
// the segment's mediaIndex at the time it was requested
mediaIndex,
// whether or not to update the SegmentLoader's state with this
// segment's mediaIndex
isSyncRequest,
startOfSegment,
// the segment's playlist
playlist,
// unencrypted bytes of the segment
bytes: null,
// when a key is defined for this segment, the encrypted bytes
encryptedBytes: null,
// The target timestampOffset for this segment when we append it
// to the source buffer
timestampOffset: null,
// The timeline that the segment is in
timeline: segment.timeline,
// The expected duration of the segment in seconds
duration: segment.duration,
// retain the segment in case the playlist updates while doing an async process
segment
};
}
/**
* Determines if the network has enough bandwidth to complete the current segment
* request in a timely manner. If not, the request will be aborted early and bandwidth
* updated to trigger a playlist switch.
*
* @param {Object} stats
* Object containing stats about the request timing and size
* @return {Boolean} True if the request was aborted, false otherwise
* @private
*/
abortRequestEarly_(stats) {
if (this.hls_.tech_.paused() ||
// Don't abort if the current playlist is on the lowestEnabledRendition
// TODO: Replace using timeout with a boolean indicating whether this playlist is
// the lowestEnabledRendition.
!this.xhrOptions_.timeout ||
// Don't abort if we have no bandwidth information to estimate segment sizes
!(this.playlist_.attributes.BANDWIDTH)) {
return false;
}
// Wait at least 1 second since the first byte of data has been received before
// using the calculated bandwidth from the progress event to allow the bitrate
// to stabilize
if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
return false;
}
const currentTime = this.currentTime_();
const measuredBandwidth = stats.bandwidth;
const segmentDuration = this.pendingSegment_.duration;
const requestTimeRemaining =
Playlist.estimateSegmentRequestTime(segmentDuration,
measuredBandwidth,
this.playlist_,
stats.bytesReceived);
// Subtract 1 from the timeUntilRebuffer so we still consider an early abort
// if we are only left with less than 1 second when the request completes.
// A negative timeUntilRebuffering indicates we are already rebuffering
const timeUntilRebuffer = timeUntilRebuffer_(this.buffered_(),
currentTime,
this.hls_.tech_.playbackRate()) - 1;
// Only consider aborting early if the estimated time to finish the download
// is larger than the estimated time until the player runs out of forward buffer
if (requestTimeRemaining <= timeUntilRebuffer) {
return false;
}
const switchCandidate = minRebufferMaxBandwidthSelector({
master: this.hls_.playlists.master,
currentTime,
bandwidth: measuredBandwidth,
duration: this.duration_(),
segmentDuration,
timeUntilRebuffer,
currentTimeline: this.currentTimeline_,
syncController: this.syncController_
});
if (!switchCandidate) {
return;
}
const rebufferingImpact = requestTimeRemaining - timeUntilRebuffer;
const timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
let minimumTimeSaving = 0.5;
// If we are already rebuffering, increase the amount of variance we add to the
// potential round trip time of the new request so that we are not too aggressive
// with switching to a playlist that might save us a fraction of a second.
if (timeUntilRebuffer <= TIME_FUDGE_FACTOR) {
minimumTimeSaving = 1;
}