/
BufferController.js
917 lines (792 loc) · 36.1 KB
/
BufferController.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
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import Constants from '../constants/Constants';
import MetricsConstants from '../constants/MetricsConstants';
import FragmentModel from '../models/FragmentModel';
import SourceBufferSink from '../SourceBufferSink';
import PreBufferSink from '../PreBufferSink';
import AbrController from './AbrController';
import MediaController from './MediaController';
import EventBus from '../../core/EventBus';
import Events from '../../core/events/Events';
import FactoryMaker from '../../core/FactoryMaker';
import Debug from '../../core/Debug';
import InitCache from '../utils/InitCache';
import DashJSError from '../vo/DashJSError';
import Errors from '../../core/errors/Errors';
import { HTTPRequest } from '../vo/metrics/HTTPRequest';
const STALL_THRESHOLD = 0.5;
const BUFFER_END_THRESHOLD = 0.5;
const BUFFER_RANGE_CALCULATION_THRESHOLD = 0.01;
const QUOTA_EXCEEDED_ERROR_CODE = 22;
const BUFFER_CONTROLLER_TYPE = 'BufferController';
function BufferController(config) {
config = config || {};
const context = this.context;
const eventBus = EventBus(context).getInstance();
const errHandler = config.errHandler;
const fragmentModel = config.fragmentModel;
const representationController = config.representationController;
const mediaController = config.mediaController;
const adapter = config.adapter;
const textController = config.textController;
const abrController = config.abrController;
const playbackController = config.playbackController;
const streamInfo = config.streamInfo;
const type = config.type;
const settings = config.settings;
let instance,
logger,
requiredQuality,
isBufferingCompleted,
bufferLevel,
criticalBufferLevel,
mediaSource,
maxAppendedIndex,
lastIndex,
buffer,
dischargeBuffer,
bufferState,
appendedBytesInfo,
wallclockTicked,
isPruningInProgress,
isQuotaExceeded,
initCache,
seekTarget,
seekClearedBufferingCompleted,
pendingPruningRanges,
replacingBuffer,
mediaChunk;
function setup() {
logger = Debug(context).getInstance().getLogger(instance);
initCache = InitCache(context).getInstance();
resetInitialSettings();
}
function getBufferControllerType() {
return BUFFER_CONTROLLER_TYPE;
}
function initialize(Source) {
setMediaSource(Source);
requiredQuality = abrController.getQualityFor(type);
eventBus.on(Events.DATA_UPDATE_COMPLETED, onDataUpdateCompleted, this);
eventBus.on(Events.INIT_FRAGMENT_LOADED, onInitFragmentLoaded, this);
eventBus.on(Events.MEDIA_FRAGMENT_LOADED, onMediaFragmentLoaded, this);
eventBus.on(Events.QUALITY_CHANGE_REQUESTED, onQualityChanged, this);
eventBus.on(Events.STREAM_COMPLETED, onStreamCompleted, this);
eventBus.on(Events.PLAYBACK_PLAYING, onPlaybackPlaying, this);
eventBus.on(Events.PLAYBACK_PROGRESS, onPlaybackProgression, this);
eventBus.on(Events.PLAYBACK_TIME_UPDATED, onPlaybackProgression, this);
eventBus.on(Events.PLAYBACK_RATE_CHANGED, onPlaybackRateChanged, this);
eventBus.on(Events.PLAYBACK_SEEKING, onPlaybackSeeking, this);
eventBus.on(Events.PLAYBACK_SEEKED, onPlaybackSeeked, this);
eventBus.on(Events.PLAYBACK_STALLED, onPlaybackStalled, this);
eventBus.on(Events.WALLCLOCK_TIME_UPDATED, onWallclockTimeUpdated, this);
eventBus.on(Events.CURRENT_TRACK_CHANGED, onCurrentTrackChanged, this, EventBus.EVENT_PRIORITY_HIGH);
eventBus.on(Events.SOURCEBUFFER_REMOVE_COMPLETED, onRemoved, this);
}
function getRepresentationInfo(quality) {
return adapter.convertDataToRepresentationInfo(representationController.getRepresentationForQuality(quality));
}
function createBuffer(mediaInfoArr, oldBuffers) {
if (!initCache || !mediaInfoArr) return null;
const mediaInfo = mediaInfoArr[0];
if (mediaSource) {
try {
if (oldBuffers && oldBuffers[type]) {
buffer = SourceBufferSink(context).create(mediaSource, mediaInfo, onAppended.bind(this), settings.get().streaming.useAppendWindowEnd, oldBuffers[type]);
} else {
buffer = SourceBufferSink(context).create(mediaSource, mediaInfo, onAppended.bind(this), settings.get().streaming.useAppendWindowEnd);
}
if (typeof buffer.getBuffer().initialize === 'function') {
buffer.getBuffer().initialize(type, streamInfo, mediaInfoArr, fragmentModel);
}
} catch (e) {
logger.fatal('Caught error on create SourceBuffer: ' + e);
errHandler.error(new DashJSError(Errors.MEDIASOURCE_TYPE_UNSUPPORTED_CODE, Errors.MEDIASOURCE_TYPE_UNSUPPORTED_MESSAGE + type));
}
} else {
buffer = PreBufferSink(context).create(onAppended.bind(this));
}
updateBufferTimestampOffset(this.getRepresentationInfo(requiredQuality));
return buffer;
}
function dischargePreBuffer() {
if (buffer && dischargeBuffer && typeof dischargeBuffer.discharge === 'function') {
const ranges = dischargeBuffer.getAllBufferRanges();
if (ranges.length > 0) {
let rangeStr = 'Beginning ' + type + 'PreBuffer discharge, adding buffer for:';
for (let i = 0; i < ranges.length; i++) {
rangeStr += ' start: ' + ranges.start(i) + ', end: ' + ranges.end(i) + ';';
}
logger.debug(rangeStr);
} else {
logger.debug('PreBuffer discharge requested, but there were no media segments in the PreBuffer.');
}
let chunks = dischargeBuffer.discharge();
let lastInit = null;
for (let j = 0; j < chunks.length; j++) {
const chunk = chunks[j];
const initChunk = initCache.extract(chunk.streamId, chunk.representationId);
if (initChunk) {
if (lastInit !== initChunk) {
buffer.append(initChunk);
lastInit = initChunk;
}
buffer.append(chunk); //TODO Think about supressing buffer events the second time round after a discharge?
}
}
dischargeBuffer.reset();
dischargeBuffer = null;
}
}
function onInitFragmentLoaded(e) {
if (e.chunk.streamId !== streamInfo.id || e.chunk.mediaInfo.type !== type) return;
logger.info('Init fragment finished loading saving to', type + '\'s init cache');
initCache.save(e.chunk);
logger.debug('Append Init fragment', type, ' with representationId:', e.chunk.representationId, ' and quality:', e.chunk.quality, ', data size:', e.chunk.bytes.byteLength);
appendToBuffer(e.chunk);
}
function appendInitSegment(representationId) {
// Get init segment from cache
const chunk = initCache.extract(streamInfo.id, representationId);
if (!chunk) {
// Init segment not in cache, shall be requested
return false;
}
// Append init segment into buffer
logger.info('Append Init fragment', type, ' with representationId:', chunk.representationId, ' and quality:', chunk.quality, ', data size:', chunk.bytes.byteLength);
appendToBuffer(chunk);
return true;
}
function onMediaFragmentLoaded(e) {
const chunk = e.chunk;
if (chunk.streamId !== streamInfo.id || chunk.mediaInfo.type != type) return;
if (replacingBuffer) {
mediaChunk = chunk;
const ranges = buffer && buffer.getAllBufferRanges();
if (ranges && ranges.length > 0 && playbackController.getTimeToStreamEnd() > STALL_THRESHOLD) {
logger.debug('Clearing buffer because track changed - ' + (ranges.end(ranges.length - 1) + BUFFER_END_THRESHOLD));
clearBuffers([{
start: 0,
end: ranges.end(ranges.length - 1) + BUFFER_END_THRESHOLD,
force: true // Force buffer removal even when buffering is completed and MediaSource is ended
}]);
}
} else {
appendToBuffer(chunk);
}
}
function appendToBuffer(chunk) {
buffer.append(chunk);
if (chunk.mediaInfo.type === Constants.VIDEO) {
triggerEvent(Events.VIDEO_CHUNK_RECEIVED, { chunk: chunk });
}
}
function showBufferRanges(ranges) {
if (ranges && ranges.length > 0) {
for (let i = 0, len = ranges.length; i < len; i++) {
logger.debug('Buffered range: ' + ranges.start(i) + ' - ' + ranges.end(i) + ', currentTime = ', playbackController.getTime());
}
}
}
function onAppended(e) {
if (e.error) {
if (e.error.code === QUOTA_EXCEEDED_ERROR_CODE) {
isQuotaExceeded = true;
criticalBufferLevel = getTotalBufferedTime() * 0.8;
logger.warn('Quota exceeded, Critical Buffer: ' + criticalBufferLevel);
if (criticalBufferLevel > 0) {
// recalculate buffer lengths to keep (bufferToKeep, bufferAheadToKeep, bufferTimeAtTopQuality) according to criticalBufferLevel
const bufferToKeep = Math.max(0.2 * criticalBufferLevel, 1);
const bufferAhead = criticalBufferLevel - bufferToKeep;
const s = { streaming: { bufferToKeep: parseFloat(bufferToKeep.toFixed(5)),
bufferAheadToKeep: parseFloat(bufferAhead.toFixed(5))}};
settings.update(s);
}
}
if (e.error.code === QUOTA_EXCEEDED_ERROR_CODE || !hasEnoughSpaceToAppend()) {
logger.warn('Clearing playback buffer to overcome quota exceed situation');
triggerEvent(Events.QUOTA_EXCEEDED, { criticalBufferLevel: criticalBufferLevel }); //Tells ScheduleController to stop scheduling.
pruneAllSafely(); // Then we clear the buffer and onCleared event will tell ScheduleController to start scheduling again.
}
return;
}
isQuotaExceeded = false;
appendedBytesInfo = e.chunk;
if (appendedBytesInfo && !isNaN(appendedBytesInfo.index)) {
maxAppendedIndex = Math.max(appendedBytesInfo.index, maxAppendedIndex);
checkIfBufferingCompleted();
}
const ranges = buffer.getAllBufferRanges();
if (appendedBytesInfo.segmentType === HTTPRequest.MEDIA_SEGMENT_TYPE) {
showBufferRanges(ranges);
onPlaybackProgression();
adjustSeekTarget();
} else if (replacingBuffer) {
// When replacing buffer due to switch track, and once new initialization segment has been appended
// (and previous buffered data removed) then seek stream to current time
const currentTime = playbackController.getTime();
logger.debug('AppendToBuffer seek target should be ' + currentTime);
triggerEvent(Events.SEEK_TARGET, {time: currentTime});
}
if (appendedBytesInfo) {
triggerEvent(appendedBytesInfo.endFragment ? Events.BYTES_APPENDED_END_FRAGMENT : Events.BYTES_APPENDED, {
quality: appendedBytesInfo.quality,
startTime: appendedBytesInfo.start,
index: appendedBytesInfo.index,
bufferedRanges: ranges,
mediaType: type
});
}
}
function adjustSeekTarget () {
// Check buffered data only for audio and video
if (type !== Constants.AUDIO && type !== Constants.VIDEO) return;
if (isNaN(seekTarget)) return;
// Check if current buffered range already contains seek target (and current video element time)
const currentTime = playbackController.getTime();
let range = getRangeAt(seekTarget, 0);
if (currentTime === seekTarget && range) return;
// Get buffered range corresponding to the seek target
const segmentDuration = representationController.getCurrentRepresentation().segmentDuration;
range = getRangeAt(seekTarget, segmentDuration);
if (!range) return;
if (Math.abs(currentTime - seekTarget) > segmentDuration) {
// If current video model time is decorrelated from seek target (and appended buffer) then seek video element
// (in case of live streams on some browsers/devices for which we can't set video element time at unavalaible range)
// Check if appended segment is not anterior from seek target (segments timeline/template tolerance)
if (seekTarget <= range.end) {
// Seek video element to seek target or range start if appended buffer starts after seek target (segments timeline/template tolerance)
playbackController.seek(Math.max(seekTarget, range.start), false, true);
seekTarget = NaN;
}
} else if (currentTime < range.start) {
// If appended buffer starts after seek target (segments timeline/template tolerance) then seek to range start
playbackController.seek(range.start, false, true);
seekTarget = NaN;
}
}
function onQualityChanged(e) {
if (e.streamInfo.id != streamInfo.id || e.mediaType !== type || requiredQuality === e.newQuality) return;
updateBufferTimestampOffset(this.getRepresentationInfo(e.newQuality));
requiredQuality = e.newQuality;
}
//**********************************************************************
// START Buffer Level, State & Sufficiency Handling.
//**********************************************************************
function onPlaybackSeeking(e) {
seekTarget = e.seekTime;
if (isBufferingCompleted) {
seekClearedBufferingCompleted = true;
isBufferingCompleted = false;
//a seek command has occured, reset lastIndex value, it will be set next time that onStreamCompleted will be called.
lastIndex = Number.POSITIVE_INFINITY;
}
if (type !== Constants.FRAGMENTED_TEXT) {
// remove buffer after seeking operations
pruneAllSafely();
} else {
onPlaybackProgression();
}
}
function onPlaybackSeeked() {
seekTarget = NaN;
}
// Prune full buffer but what is around current time position
function pruneAllSafely() {
buffer.waitForUpdateEnd(() => {
const ranges = getAllRangesWithSafetyFactor();
if (!ranges || ranges.length === 0) {
onPlaybackProgression();
}
clearBuffers(ranges);
});
}
// Get all buffer ranges but a range around current time position
function getAllRangesWithSafetyFactor() {
const clearRanges = [];
const ranges = buffer.getAllBufferRanges();
if (!ranges || ranges.length === 0) {
return clearRanges;
}
const currentTime = playbackController.getTime();
const endOfBuffer = ranges.end(ranges.length - 1) + BUFFER_END_THRESHOLD;
const currentTimeRequest = fragmentModel.getRequests({
state: FragmentModel.FRAGMENT_MODEL_EXECUTED,
time: currentTime,
threshold: BUFFER_RANGE_CALCULATION_THRESHOLD
})[0];
// There is no request in current time position yet. Let's remove everything
if (!currentTimeRequest) {
logger.debug('getAllRangesWithSafetyFactor - No request found in current time position, removing full buffer 0 -', endOfBuffer);
clearRanges.push({
start: 0,
end: endOfBuffer
});
} else {
// Build buffer behind range. To avoid pruning time around current time position,
// we include fragment right behind the one in current time position
const behindRange = {
start: 0,
end: currentTimeRequest.startTime - STALL_THRESHOLD
};
const prevReq = fragmentModel.getRequests({
state: FragmentModel.FRAGMENT_MODEL_EXECUTED,
time: currentTimeRequest.startTime - (currentTimeRequest.duration / 2),
threshold: BUFFER_RANGE_CALCULATION_THRESHOLD
})[0];
if (prevReq && prevReq.startTime != currentTimeRequest.startTime) {
behindRange.end = prevReq.startTime;
}
if (behindRange.start < behindRange.end && behindRange.end > ranges.start(0)) {
clearRanges.push(behindRange);
}
// Build buffer ahead range. To avoid pruning time around current time position,
// we include fragment right after the one in current time position
const aheadRange = {
start: currentTimeRequest.startTime + currentTimeRequest.duration + STALL_THRESHOLD,
end: endOfBuffer
};
const nextReq = fragmentModel.getRequests({
state: FragmentModel.FRAGMENT_MODEL_EXECUTED,
time: currentTimeRequest.startTime + currentTimeRequest.duration + STALL_THRESHOLD,
threshold: BUFFER_RANGE_CALCULATION_THRESHOLD
})[0];
if (nextReq && nextReq.startTime !== currentTimeRequest.startTime) {
aheadRange.start = nextReq.startTime + nextReq.duration + STALL_THRESHOLD;
}
if (aheadRange.start < aheadRange.end && aheadRange.start < endOfBuffer) {
clearRanges.push(aheadRange);
}
}
return clearRanges;
}
function getWorkingTime() {
return isNaN(seekTarget) ? playbackController.getTime() : seekTarget;
}
function onPlaybackProgression() {
if (!replacingBuffer || (type === Constants.FRAGMENTED_TEXT && textController.isTextEnabled())) {
updateBufferLevel();
}
}
function onPlaybackStalled() {
checkIfSufficientBuffer();
}
function onPlaybackPlaying() {
seekTarget = NaN;
checkIfSufficientBuffer();
}
function getRangeAt(time, tolerance) {
const ranges = buffer.getAllBufferRanges();
let start = 0;
let end = 0;
let firstStart = null;
let lastEnd = null;
let gap = 0;
let len,
i;
const toler = !isNaN(tolerance) ? tolerance : 0.15;
if (ranges !== null && ranges !== undefined) {
for (i = 0, len = ranges.length; i < len; i++) {
start = ranges.start(i);
end = ranges.end(i);
if (firstStart === null) {
gap = Math.abs(start - time);
if (time >= start && time < end) {
// start the range
firstStart = start;
lastEnd = end;
} else if (gap <= toler) {
// start the range even though the buffer does not contain time 0
firstStart = start;
lastEnd = end;
}
} else {
gap = start - lastEnd;
if (gap <= toler) {
// the discontinuity is smaller than the tolerance, combine the ranges
lastEnd = end;
} else {
break;
}
}
}
if (firstStart !== null) {
return {
start: firstStart,
end: lastEnd
};
}
}
return null;
}
function getBufferLength(time, tolerance) {
let range,
length;
range = getRangeAt(time, tolerance);
if (range === null) {
length = 0;
} else {
length = range.end - time;
}
return length;
}
function updateBufferLevel() {
if (playbackController) {
bufferLevel = getBufferLength(getWorkingTime() || 0);
triggerEvent(Events.BUFFER_LEVEL_UPDATED, { bufferLevel: bufferLevel });
checkIfSufficientBuffer();
}
}
function checkIfBufferingCompleted() {
const isLastIdxAppended = maxAppendedIndex >= lastIndex - 1; // Handles 0 and non 0 based request index
if (isLastIdxAppended && !isBufferingCompleted && buffer.discharge === undefined) {
isBufferingCompleted = true;
logger.debug('checkIfBufferingCompleted trigger BUFFERING_COMPLETED');
triggerEvent(Events.BUFFERING_COMPLETED);
}
}
function checkIfSufficientBuffer() {
// No need to check buffer if type is not audio or video (for example if several errors occur during text parsing, so that the buffer cannot be filled, no error must occur on video playback)
if (type !== Constants.AUDIO && type !== Constants.VIDEO) return;
if (seekClearedBufferingCompleted && !isBufferingCompleted && bufferLevel > 0 && playbackController && playbackController.getTimeToStreamEnd() - bufferLevel < STALL_THRESHOLD) {
seekClearedBufferingCompleted = false;
isBufferingCompleted = true;
logger.debug('checkIfSufficientBuffer trigger BUFFERING_COMPLETED');
triggerEvent(Events.BUFFERING_COMPLETED);
}
// When the player is working in low latency mode, the buffer is often below STALL_THRESHOLD.
// So, when in low latency mode, change dash.js behavior so it notifies a stall just when
// buffer reach 0 seconds
if (((!settings.get().streaming.lowLatencyEnabled && bufferLevel < STALL_THRESHOLD) || bufferLevel === 0) && !isBufferingCompleted) {
notifyBufferStateChanged(MetricsConstants.BUFFER_EMPTY);
} else {
if (isBufferingCompleted || bufferLevel >= streamInfo.manifestInfo.minBufferTime) {
notifyBufferStateChanged(MetricsConstants.BUFFER_LOADED);
}
}
}
function notifyBufferStateChanged(state) {
if (bufferState === state ||
(state === MetricsConstants.BUFFER_EMPTY && playbackController.getTime() === 0) || // Don't trigger BUFFER_EMPTY if it's initial loading
(type === Constants.FRAGMENTED_TEXT && !textController.isTextEnabled())) {
return;
}
bufferState = state;
triggerEvent(Events.BUFFER_LEVEL_STATE_CHANGED, { state: state });
triggerEvent(state === MetricsConstants.BUFFER_LOADED ? Events.BUFFER_LOADED : Events.BUFFER_EMPTY);
logger.debug(state === MetricsConstants.BUFFER_LOADED ? 'Got enough buffer to start' : 'Waiting for more buffer before starting playback');
}
/* prune buffer on our own in background to avoid browsers pruning buffer silently */
function pruneBuffer() {
if (!buffer || type === Constants.FRAGMENTED_TEXT) {
return;
}
if (!isBufferingCompleted) {
clearBuffers(getClearRanges());
}
}
function getClearRanges() {
const clearRanges = [];
const ranges = buffer.getAllBufferRanges();
if (!ranges || ranges.length === 0) {
return clearRanges;
}
const currentTime = playbackController.getTime();
const rangeToKeep = {
start: Math.max(0, currentTime - settings.get().streaming.bufferToKeep),
end: currentTime + settings.get().streaming.bufferAheadToKeep
};
const currentTimeRequest = fragmentModel.getRequests({
state: FragmentModel.FRAGMENT_MODEL_EXECUTED,
time: currentTime,
threshold: BUFFER_RANGE_CALCULATION_THRESHOLD
})[0];
// Ensure we keep full range of current fragment
if (currentTimeRequest) {
rangeToKeep.start = Math.min(currentTimeRequest.startTime, rangeToKeep.start);
rangeToKeep.end = Math.max(currentTimeRequest.startTime + currentTimeRequest.duration, rangeToKeep.end);
} else if (currentTime === 0 && playbackController.getIsDynamic()) {
// Don't prune before the live stream starts, it messes with low latency
return [];
}
if (ranges.start(0) <= rangeToKeep.start) {
const behindRange = {
start: 0,
end: rangeToKeep.start
};
for (let i = 0; i < ranges.length && ranges.end(i) <= rangeToKeep.start; i++) {
behindRange.end = ranges.end(i);
}
if (behindRange.start < behindRange.end) {
clearRanges.push(behindRange);
}
}
if (ranges.end(ranges.length - 1) >= rangeToKeep.end) {
const aheadRange = {
start: rangeToKeep.end,
end: ranges.end(ranges.length - 1) + BUFFER_RANGE_CALCULATION_THRESHOLD
};
if (aheadRange.start < aheadRange.end) {
clearRanges.push(aheadRange);
}
}
return clearRanges;
}
function clearBuffers(ranges) {
if (!ranges || !buffer || ranges.length === 0) return;
pendingPruningRanges.push.apply(pendingPruningRanges, ranges);
if (isPruningInProgress) {
return;
}
clearNextRange();
}
function clearNextRange() {
// If there's nothing to prune reset state
if (pendingPruningRanges.length === 0 || !buffer) {
logger.debug('Nothing to prune, halt pruning');
pendingPruningRanges = [];
isPruningInProgress = false;
return;
}
const sourceBuffer = buffer.getBuffer();
// If there's nothing buffered any pruning is invalid, so reset our state
if (!sourceBuffer || !sourceBuffer.buffered || sourceBuffer.buffered.length === 0) {
logger.debug('SourceBuffer is empty (or does not exist), halt pruning');
pendingPruningRanges = [];
isPruningInProgress = false;
return;
}
const range = pendingPruningRanges.shift();
logger.debug('Removing buffer from:', range.start, 'to', range.end);
isPruningInProgress = true;
// If removing buffer ahead current playback position, update maxAppendedIndex
const currentTime = playbackController.getTime();
if (currentTime < range.end) {
isBufferingCompleted = false;
maxAppendedIndex = 0;
}
buffer.remove(range.start, range.end, range.force);
}
function onRemoved(e) {
if (buffer !== e.buffer) return;
logger.debug('onRemoved buffer from:', e.from, 'to', e.to);
const ranges = buffer.getAllBufferRanges();
showBufferRanges(ranges);
if (pendingPruningRanges.length === 0) {
isPruningInProgress = false;
}
if (e.unintended) {
logger.warn('Detected unintended removal from:', e.from, 'to', e.to, 'setting index handler time to', e.from);
triggerEvent(Events.SEEK_TARGET, {time: e.from});
}
if (isPruningInProgress) {
clearNextRange();
} else {
if (!replacingBuffer) {
updateBufferLevel();
} else {
replacingBuffer = false;
if (mediaChunk) {
appendToBuffer(mediaChunk);
}
}
triggerEvent(Events.BUFFER_CLEARED, {
from: e.from,
to: e.to,
unintended: e.unintended,
hasEnoughSpaceToAppend: hasEnoughSpaceToAppend(),
quotaExceeded: isQuotaExceeded });
}
//TODO - REMEMBER removed a timerout hack calling clearBuffer after manifestInfo.minBufferTime * 1000 if !hasEnoughSpaceToAppend() Aug 04 2016
}
function updateBufferTimestampOffset(representationInfo) {
if (!representationInfo || representationInfo.MSETimeOffset === undefined) return;
// Each track can have its own @presentationTimeOffset, so we should set the offset
// if it has changed after switching the quality or updating an mpd
if (buffer && buffer.updateTimestampOffset) {
buffer.updateTimestampOffset(representationInfo.MSETimeOffset);
}
}
function onDataUpdateCompleted(e) {
if (e.sender.getStreamId() !== streamInfo.id || e.sender.getType() !== type) return;
if (e.error) return;
updateBufferTimestampOffset(e.currentRepresentation);
}
function onStreamCompleted(e) {
if (e.request.mediaInfo.streamInfo.id !== streamInfo.id || e.request.mediaType !== type) return;
lastIndex = e.request.index;
checkIfBufferingCompleted();
}
function onCurrentTrackChanged(e) {
if (e.newMediaInfo.streamInfo.id !== streamInfo.id || e.newMediaInfo.type !== type) return;
const ranges = buffer && buffer.getAllBufferRanges();
if (!ranges) return;
logger.info('Track change asked');
if (mediaController.getSwitchMode(type) === MediaController.TRACK_SWITCH_MODE_ALWAYS_REPLACE) {
if (ranges && ranges.length > 0 && playbackController.getTimeToStreamEnd() > STALL_THRESHOLD) {
isBufferingCompleted = false;
lastIndex = Number.POSITIVE_INFINITY;
}
}
}
function onWallclockTimeUpdated() {
wallclockTicked++;
const secondsElapsed = (wallclockTicked * (settings.get().streaming.wallclockTimeUpdateInterval / 1000));
if ((secondsElapsed >= settings.get().streaming.bufferPruningInterval)) {
wallclockTicked = 0;
pruneBuffer();
}
}
function onPlaybackRateChanged() {
checkIfSufficientBuffer();
}
function getType() {
return type;
}
function getBuffer() {
return buffer;
}
function setBuffer(newBuffer) {
buffer = newBuffer;
}
function getBufferLevel() {
return bufferLevel;
}
function setMediaSource(value, mediaInfo) {
mediaSource = value;
if (buffer && mediaInfo) { //if we have a prebuffer, we should prepare to discharge it, and make a new sourceBuffer ready
if (typeof buffer.discharge === 'function') {
dischargeBuffer = buffer;
createBuffer(mediaInfo);
}
}
}
function getMediaSource() {
return mediaSource;
}
function replaceBuffer() {
replacingBuffer = true;
}
function getIsBufferingCompleted() {
return isBufferingCompleted;
}
function getIsPruningInProgress() {
return isPruningInProgress;
}
function getTotalBufferedTime() {
const ranges = buffer.getAllBufferRanges();
let totalBufferedTime = 0;
let ln,
i;
if (!ranges) return totalBufferedTime;
for (i = 0, ln = ranges.length; i < ln; i++) {
totalBufferedTime += ranges.end(i) - ranges.start(i);
}
return totalBufferedTime;
}
function hasEnoughSpaceToAppend() {
const totalBufferedTime = getTotalBufferedTime();
return (totalBufferedTime < criticalBufferLevel);
}
function triggerEvent(eventType, data) {
let payload = data || {};
payload.sender = instance;
payload.mediaType = type;
payload.streamId = streamInfo.id;
eventBus.trigger(eventType, payload);
}
function resetInitialSettings(errored, keepBuffers) {
criticalBufferLevel = Number.POSITIVE_INFINITY;
bufferState = undefined;
requiredQuality = AbrController.QUALITY_DEFAULT;
lastIndex = Number.POSITIVE_INFINITY;
maxAppendedIndex = 0;
appendedBytesInfo = null;
isBufferingCompleted = false;
isPruningInProgress = false;
isQuotaExceeded = false;
seekClearedBufferingCompleted = false;
bufferLevel = 0;
wallclockTicked = 0;
pendingPruningRanges = [];
seekTarget = NaN;
if (buffer) {
if (!errored) {
buffer.abort();
}
buffer.reset(keepBuffers);
buffer = null;
}
replacingBuffer = false;
}
function reset(errored, keepBuffers) {
eventBus.off(Events.DATA_UPDATE_COMPLETED, onDataUpdateCompleted, this);
eventBus.off(Events.INIT_FRAGMENT_LOADED, onInitFragmentLoaded, this);
eventBus.off(Events.MEDIA_FRAGMENT_LOADED, onMediaFragmentLoaded, this);
eventBus.off(Events.QUALITY_CHANGE_REQUESTED, onQualityChanged, this);
eventBus.off(Events.STREAM_COMPLETED, onStreamCompleted, this);
eventBus.off(Events.PLAYBACK_PLAYING, onPlaybackPlaying, this);
eventBus.off(Events.PLAYBACK_PROGRESS, onPlaybackProgression, this);
eventBus.off(Events.PLAYBACK_TIME_UPDATED, onPlaybackProgression, this);
eventBus.off(Events.PLAYBACK_RATE_CHANGED, onPlaybackRateChanged, this);
eventBus.off(Events.PLAYBACK_SEEKING, onPlaybackSeeking, this);
eventBus.off(Events.PLAYBACK_SEEKED, onPlaybackSeeked, this);
eventBus.off(Events.PLAYBACK_STALLED, onPlaybackStalled, this);
eventBus.off(Events.WALLCLOCK_TIME_UPDATED, onWallclockTimeUpdated, this);
eventBus.off(Events.CURRENT_TRACK_CHANGED, onCurrentTrackChanged, this);
eventBus.off(Events.SOURCEBUFFER_REMOVE_COMPLETED, onRemoved, this);
resetInitialSettings(errored, keepBuffers);
}
instance = {
getBufferControllerType: getBufferControllerType,
getRepresentationInfo: getRepresentationInfo,
initialize: initialize,
createBuffer: createBuffer,
dischargePreBuffer: dischargePreBuffer,
getType: getType,
getBuffer: getBuffer,
setBuffer: setBuffer,
getBufferLevel: getBufferLevel,
getRangeAt: getRangeAt,
setMediaSource: setMediaSource,
getMediaSource: getMediaSource,
appendInitSegment: appendInitSegment,
replaceBuffer: replaceBuffer,
getIsBufferingCompleted: getIsBufferingCompleted,
getIsPruningInProgress: getIsPruningInProgress,
reset: reset
};
setup();
return instance;
}
BufferController.__dashjs_factory_name = BUFFER_CONTROLLER_TYPE;
export default FactoryMaker.getClassFactory(BufferController);