forked from video-dev/hls.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
abr-controller.ts
896 lines (840 loc) · 30.9 KB
/
abr-controller.ts
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
import EwmaBandWidthEstimator from '../utils/ewma-bandwidth-estimator';
import { Events } from '../events';
import { ErrorDetails } from '../errors';
import { PlaylistLevelType } from '../types/loader';
import { Logger } from '../utils/logger';
import {
SUPPORTED_INFO_DEFAULT,
getMediaDecodingInfoPromise,
requiresMediaCapabilitiesDecodingInfo,
} from '../utils/mediacapabilities-helper';
import {
getAudioTracksByGroup,
getCodecTiers,
getStartCodecTier,
type AudioTracksByGroup,
type CodecSetTier,
} from '../utils/rendition-helper';
import type { Fragment } from '../loader/fragment';
import type { Part } from '../loader/fragment';
import type { Level, VideoRange } from '../types/level';
import type { LoaderStats } from '../types/loader';
import type Hls from '../hls';
import type {
FragLoadingData,
FragLoadedData,
FragBufferedData,
LevelLoadedData,
LevelSwitchingData,
ManifestLoadingData,
ErrorData,
} from '../types/events';
import type { AbrComponentAPI } from '../types/component-api';
class AbrController extends Logger implements AbrComponentAPI {
protected hls: Hls;
private lastLevelLoadSec: number = 0;
private lastLoadedFragLevel: number = -1;
private firstSelection: number = -1;
private _nextAutoLevel: number = -1;
private nextAutoLevelKey: string = '';
private audioTracksByGroup: AudioTracksByGroup | null = null;
private codecTiers: Record<string, CodecSetTier> | null = null;
private timer: number = -1;
private fragCurrent: Fragment | null = null;
private partCurrent: Part | null = null;
private bitrateTestDelay: number = 0;
public bwEstimator: EwmaBandWidthEstimator;
constructor(hls: Hls) {
super('abr', hls.logger);
this.hls = hls;
this.bwEstimator = this.initEstimator();
this.registerListeners();
}
public resetEstimator(abrEwmaDefaultEstimate?: number) {
if (abrEwmaDefaultEstimate) {
this.log(`setting initial bwe to ${abrEwmaDefaultEstimate}`);
this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;
}
this.firstSelection = -1;
this.bwEstimator = this.initEstimator();
}
private initEstimator(): EwmaBandWidthEstimator {
const config = this.hls.config;
return new EwmaBandWidthEstimator(
config.abrEwmaSlowVoD,
config.abrEwmaFastVoD,
config.abrEwmaDefaultEstimate,
);
}
protected registerListeners() {
const { hls } = this;
hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
hls.on(Events.ERROR, this.onError, this);
}
protected unregisterListeners() {
const { hls } = this;
if (!hls) {
return;
}
hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
hls.off(Events.ERROR, this.onError, this);
}
public destroy() {
this.unregisterListeners();
this.clearTimer();
// @ts-ignore
this.hls = this._abandonRulesCheck = null;
this.fragCurrent = this.partCurrent = null;
}
protected onManifestLoading(
event: Events.MANIFEST_LOADING,
data: ManifestLoadingData,
) {
this.lastLoadedFragLevel = -1;
this.firstSelection = -1;
this.lastLevelLoadSec = 0;
this.fragCurrent = this.partCurrent = null;
this.onLevelsUpdated();
this.clearTimer();
}
private onLevelsUpdated() {
if (this.lastLoadedFragLevel > -1 && this.fragCurrent) {
this.lastLoadedFragLevel = this.fragCurrent.level;
}
this._nextAutoLevel = -1;
this.onMaxAutoLevelUpdated();
this.codecTiers = null;
this.audioTracksByGroup = null;
}
private onMaxAutoLevelUpdated() {
this.firstSelection = -1;
this.nextAutoLevelKey = '';
}
protected onFragLoading(event: Events.FRAG_LOADING, data: FragLoadingData) {
const frag = data.frag;
if (this.ignoreFragment(frag)) {
return;
}
if (!frag.bitrateTest) {
this.fragCurrent = frag;
this.partCurrent = data.part ?? null;
}
this.clearTimer();
this.timer = self.setInterval(this._abandonRulesCheck, 100);
}
protected onLevelSwitching(
event: Events.LEVEL_SWITCHING,
data: LevelSwitchingData,
): void {
this.clearTimer();
}
protected onError(event: Events.ERROR, data: ErrorData) {
if (data.fatal) {
return;
}
switch (data.details) {
case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
case ErrorDetails.BUFFER_APPEND_ERROR:
// Reset last loaded level so that a new selection can be made after calling recoverMediaError
this.lastLoadedFragLevel = -1;
this.firstSelection = -1;
break;
case ErrorDetails.FRAG_LOAD_TIMEOUT: {
const frag = data.frag;
const { fragCurrent, partCurrent: part } = this;
if (
frag &&
fragCurrent &&
frag.sn === fragCurrent.sn &&
frag.level === fragCurrent.level
) {
const now = performance.now();
const stats: LoaderStats = part ? part.stats : frag.stats;
const timeLoading = now - stats.loading.start;
const ttfb = stats.loading.first
? stats.loading.first - stats.loading.start
: -1;
const loadedFirstByte = stats.loaded && ttfb > -1;
if (loadedFirstByte) {
const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
this.bwEstimator.sample(
timeLoading - Math.min(ttfbEstimate, ttfb),
stats.loaded,
);
} else {
this.bwEstimator.sampleTTFB(timeLoading);
}
}
break;
}
}
}
private getTimeToLoadFrag(
timeToFirstByteSec: number,
bandwidth: number,
fragSizeBits: number,
isSwitch: boolean,
): number {
const fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;
const playlistLoadSec = isSwitch ? this.lastLevelLoadSec : 0;
return fragLoadSec + playlistLoadSec;
}
protected onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {
const config = this.hls.config;
const { loading } = data.stats;
const timeLoadingMs = loading.end - loading.start;
if (Number.isFinite(timeLoadingMs)) {
this.lastLevelLoadSec = timeLoadingMs / 1000;
}
if (data.details.live) {
this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
} else {
this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
}
}
/*
This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load
quickly enough to prevent underbuffering
*/
private _abandonRulesCheck = () => {
const { fragCurrent: frag, partCurrent: part, hls } = this;
const { autoLevelEnabled, media } = hls;
if (!frag || !media) {
return;
}
const now = performance.now();
const stats: LoaderStats = part ? part.stats : frag.stats;
const duration = part ? part.duration : frag.duration;
const timeLoading = now - stats.loading.start;
const minAutoLevel = hls.minAutoLevel;
// If frag loading is aborted, complete, or from lowest level, stop timer and return
if (
stats.aborted ||
(stats.loaded && stats.loaded === stats.total) ||
frag.level <= minAutoLevel
) {
this.clearTimer();
// reset forced auto level value so that next level will be selected
this._nextAutoLevel = -1;
return;
}
// This check only runs if we're in ABR mode and actually playing
if (
!autoLevelEnabled ||
media.paused ||
!media.playbackRate ||
!media.readyState
) {
return;
}
const bufferInfo = hls.mainForwardBufferInfo;
if (bufferInfo === null) {
return;
}
const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
const playbackRate = Math.abs(media.playbackRate);
// To maintain stable adaptive playback, only begin monitoring frag loading after half or more of its playback duration has passed
if (
timeLoading <=
Math.max(ttfbEstimate, 1000 * (duration / (playbackRate * 2)))
) {
return;
}
// bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer
const bufferStarvationDelay = bufferInfo.len / playbackRate;
const ttfb = stats.loading.first
? stats.loading.first - stats.loading.start
: -1;
const loadedFirstByte = stats.loaded && ttfb > -1;
const bwEstimate: number = this.getBwEstimate();
const levels = hls.levels;
const level = levels[frag.level];
const expectedLen =
stats.total ||
Math.max(stats.loaded, Math.round((duration * level.averageBitrate) / 8));
let timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;
if (timeStreaming < 1 && loadedFirstByte) {
timeStreaming = Math.min(timeLoading, (stats.loaded * 8) / bwEstimate);
}
const loadRate = loadedFirstByte
? (stats.loaded * 1000) / timeStreaming
: 0;
// fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the remainder of the fragment
const fragLoadedDelay = loadRate
? (expectedLen - stats.loaded) / loadRate
: (expectedLen * 8) / bwEstimate + ttfbEstimate / 1000;
// Only downswitch if the time to finish loading the current fragment is greater than the amount of buffer left
if (fragLoadedDelay <= bufferStarvationDelay) {
return;
}
const bwe = loadRate ? loadRate * 8 : bwEstimate;
let fragLevelNextLoadedDelay: number = Number.POSITIVE_INFINITY;
let nextLoadLevel: number;
// Iterate through lower level and try to find the largest one that avoids rebuffering
for (
nextLoadLevel = frag.level - 1;
nextLoadLevel > minAutoLevel;
nextLoadLevel--
) {
// compute time to load next fragment at lower level
// 8 = bits per byte (bps/Bps)
const levelNextBitrate = levels[nextLoadLevel].maxBitrate;
fragLevelNextLoadedDelay = this.getTimeToLoadFrag(
ttfbEstimate / 1000,
bwe,
duration * levelNextBitrate,
!levels[nextLoadLevel].details,
);
if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
break;
}
}
// Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing
// to load the current one
if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
return;
}
// if estimated load time of new segment is completely unreasonable, ignore and do not emergency switch down
if (fragLevelNextLoadedDelay > duration * 10) {
return;
}
hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;
if (loadedFirstByte) {
// If there has been loading progress, sample bandwidth using loading time offset by minimum TTFB time
this.bwEstimator.sample(
timeLoading - Math.min(ttfbEstimate, ttfb),
stats.loaded,
);
} else {
// If there has been no loading progress, sample TTFB
this.bwEstimator.sampleTTFB(timeLoading);
}
const nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;
if (
this.getBwEstimate() * this.hls.config.abrBandWidthUpFactor >
nextLoadLevelBitrate
) {
this.resetEstimator(nextLoadLevelBitrate);
}
this.clearTimer();
this.warn(`Fragment ${frag.sn}${
part ? ' part ' + part.index : ''
} of level ${frag.level} is loading too slowly;
Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s
Estimated load time for current fragment: ${fragLoadedDelay.toFixed(3)} s
Estimated load time for down switch fragment: ${fragLevelNextLoadedDelay.toFixed(
3,
)} s
TTFB estimate: ${ttfb | 0} ms
Current BW estimate: ${
Number.isFinite(bwEstimate) ? bwEstimate | 0 : 'Unknown'
} bps
New BW estimate: ${this.getBwEstimate() | 0} bps
Switching to level ${nextLoadLevel} @ ${nextLoadLevelBitrate | 0} bps`);
hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, { frag, part, stats });
};
protected onFragLoaded(
event: Events.FRAG_LOADED,
{ frag, part }: FragLoadedData,
) {
const stats = part ? part.stats : frag.stats;
if (frag.type === PlaylistLevelType.MAIN) {
this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);
}
if (this.ignoreFragment(frag)) {
return;
}
// stop monitoring bw once frag loaded
this.clearTimer();
// reset forced auto level value so that next level will be selected
if (frag.level === this._nextAutoLevel) {
this._nextAutoLevel = -1;
}
this.firstSelection = -1;
// compute level average bitrate
if (this.hls.config.abrMaxWithRealBitrate) {
const duration = part ? part.duration : frag.duration;
const level = this.hls.levels[frag.level];
const loadedBytes =
(level.loaded ? level.loaded.bytes : 0) + stats.loaded;
const loadedDuration =
(level.loaded ? level.loaded.duration : 0) + duration;
level.loaded = { bytes: loadedBytes, duration: loadedDuration };
level.realBitrate = Math.round((8 * loadedBytes) / loadedDuration);
}
if (frag.bitrateTest) {
const fragBufferedData: FragBufferedData = {
stats,
frag,
part,
id: frag.type,
};
this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);
frag.bitrateTest = false;
} else {
// store level id after successful fragment load for playback
this.lastLoadedFragLevel = frag.level;
}
}
protected onFragBuffered(
event: Events.FRAG_BUFFERED,
data: FragBufferedData,
) {
const { frag, part } = data;
const stats = part?.stats.loaded ? part.stats : frag.stats;
if (stats.aborted) {
return;
}
if (this.ignoreFragment(frag)) {
return;
}
// Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;
// rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch
// is used. If we used buffering in that case, our BW estimate sample will be very large.
const processingMs =
stats.parsing.end -
stats.loading.start -
Math.min(
stats.loading.first - stats.loading.start,
this.bwEstimator.getEstimateTTFB(),
);
this.bwEstimator.sample(processingMs, stats.loaded);
stats.bwEstimate = this.getBwEstimate();
if (frag.bitrateTest) {
this.bitrateTestDelay = processingMs / 1000;
} else {
this.bitrateTestDelay = 0;
}
}
private ignoreFragment(frag: Fragment): boolean {
// Only count non-alt-audio frags which were actually buffered in our BW calculations
return frag.type !== PlaylistLevelType.MAIN || frag.sn === 'initSegment';
}
public clearTimer() {
if (this.timer > -1) {
self.clearInterval(this.timer);
this.timer = -1;
}
}
public get firstAutoLevel(): number {
const { maxAutoLevel, minAutoLevel } = this.hls;
const bwEstimate = this.getBwEstimate();
const maxStartDelay = this.hls.config.maxStarvationDelay;
const abrAutoLevel = this.findBestLevel(
bwEstimate,
minAutoLevel,
maxAutoLevel,
0,
maxStartDelay,
1,
1,
);
if (abrAutoLevel > -1) {
return abrAutoLevel;
}
const firstLevel = this.hls.firstLevel;
const clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);
this.warn(
`Could not find best starting auto level. Defaulting to first in playlist ${firstLevel} clamped to ${clamped}`,
);
return clamped;
}
public get forcedAutoLevel(): number {
if (this.nextAutoLevelKey) {
return -1;
}
return this._nextAutoLevel;
}
// return next auto level
public get nextAutoLevel(): number {
const forcedAutoLevel = this.forcedAutoLevel;
const bwEstimator = this.bwEstimator;
const useEstimate = bwEstimator.canEstimate();
const loadedFirstFrag = this.lastLoadedFragLevel > -1;
// in case next auto level has been forced, and bw not available or not reliable, return forced value
if (
forcedAutoLevel !== -1 &&
(!useEstimate ||
!loadedFirstFrag ||
this.nextAutoLevelKey === this.getAutoLevelKey())
) {
return forcedAutoLevel;
}
// compute next level using ABR logic
const nextABRAutoLevel =
useEstimate && loadedFirstFrag
? this.getNextABRAutoLevel()
: this.firstAutoLevel;
// use forced auto level while it hasn't errored more than ABR selection
if (forcedAutoLevel !== -1) {
const levels = this.hls.levels;
if (
levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) &&
levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError
) {
return forcedAutoLevel;
}
}
// save result until state has changed
this._nextAutoLevel = nextABRAutoLevel;
this.nextAutoLevelKey = this.getAutoLevelKey();
return nextABRAutoLevel;
}
private getAutoLevelKey(): string {
return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`;
}
private getNextABRAutoLevel(): number {
const { fragCurrent, partCurrent, hls } = this;
if (hls.levels.length <= 1) {
return hls.loadLevel;
}
const { maxAutoLevel, config, minAutoLevel } = hls;
const currentFragDuration = partCurrent
? partCurrent.duration
: fragCurrent
? fragCurrent.duration
: 0;
const avgbw = this.getBwEstimate();
// bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
const bufferStarvationDelay = this.getStarvationDelay();
let bwFactor = config.abrBandWidthFactor;
let bwUpFactor = config.abrBandWidthUpFactor;
// First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
if (bufferStarvationDelay) {
const bestLevel = this.findBestLevel(
avgbw,
minAutoLevel,
maxAutoLevel,
bufferStarvationDelay,
0,
bwFactor,
bwUpFactor,
);
if (bestLevel >= 0) {
return bestLevel;
}
}
// not possible to get rid of rebuffering... try to find level that will guarantee less than maxStarvationDelay of rebuffering
let maxStarvationDelay = currentFragDuration
? Math.min(currentFragDuration, config.maxStarvationDelay)
: config.maxStarvationDelay;
if (!bufferStarvationDelay) {
// in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
const bitrateTestDelay = this.bitrateTestDelay;
if (bitrateTestDelay) {
// if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
// max video loading delay used in automatic start level selection :
// in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
// the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
// cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
const maxLoadingDelay = currentFragDuration
? Math.min(currentFragDuration, config.maxLoadingDelay)
: config.maxLoadingDelay;
maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
this.info(
`bitrate test took ${Math.round(
1000 * bitrateTestDelay,
)}ms, set first fragment max fetchDuration to ${Math.round(
1000 * maxStarvationDelay,
)} ms`,
);
// don't use conservative factor on bitrate test
bwFactor = bwUpFactor = 1;
}
}
const bestLevel = this.findBestLevel(
avgbw,
minAutoLevel,
maxAutoLevel,
bufferStarvationDelay,
maxStarvationDelay,
bwFactor,
bwUpFactor,
);
this.info(
`${
bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty'
}, optimal quality level ${bestLevel}`,
);
if (bestLevel > -1) {
return bestLevel;
}
// If no matching level found, see if min auto level would be a better option
const minLevel = hls.levels[minAutoLevel];
const autoLevel = hls.levels[hls.loadLevel];
if (minLevel?.bitrate < autoLevel?.bitrate) {
return minAutoLevel;
}
// or if bitrate is not lower, continue to use loadLevel
return hls.loadLevel;
}
private getStarvationDelay(): number {
const hls = this.hls;
const media = hls.media;
if (!media) {
return Infinity;
}
// playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as
// if we're playing back at the normal rate.
const playbackRate =
media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;
const bufferInfo = hls.mainForwardBufferInfo;
return (bufferInfo ? bufferInfo.len : 0) / playbackRate;
}
private getBwEstimate(): number {
return this.bwEstimator.canEstimate()
? this.bwEstimator.getEstimate()
: this.hls.config.abrEwmaDefaultEstimate;
}
private findBestLevel(
currentBw: number,
minAutoLevel: number,
maxAutoLevel: number,
bufferStarvationDelay: number,
maxStarvationDelay: number,
bwFactor: number,
bwUpFactor: number,
): number {
const maxFetchDuration: number = bufferStarvationDelay + maxStarvationDelay;
const lastLoadedFragLevel = this.lastLoadedFragLevel;
const selectionBaseLevel =
lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;
const { fragCurrent, partCurrent } = this;
const { levels, allAudioTracks, loadLevel, config } = this.hls;
if (levels.length === 1) {
return 0;
}
const level: Level | undefined = levels[selectionBaseLevel];
const live = !!level?.details?.live;
const firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;
let currentCodecSet: string | undefined;
let currentVideoRange: VideoRange | undefined = 'SDR';
let currentFrameRate = level?.frameRate || 0;
const { audioPreference, videoPreference } = config;
const audioTracksByGroup =
this.audioTracksByGroup ||
(this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));
if (firstSelection) {
if (this.firstSelection !== -1) {
return this.firstSelection;
}
const codecTiers =
this.codecTiers ||
(this.codecTiers = getCodecTiers(
levels,
audioTracksByGroup,
minAutoLevel,
maxAutoLevel,
));
const startTier = getStartCodecTier(
codecTiers,
currentVideoRange,
currentBw,
audioPreference,
videoPreference,
);
const { codecSet, videoRanges, minFramerate, minBitrate, preferHDR } =
startTier;
currentCodecSet = codecSet;
currentVideoRange = preferHDR
? videoRanges[videoRanges.length - 1]
: videoRanges[0];
currentFrameRate = minFramerate;
currentBw = Math.max(currentBw, minBitrate);
this.log(`picked start tier ${JSON.stringify(startTier)}`);
} else {
currentCodecSet = level?.codecSet;
currentVideoRange = level?.videoRange;
}
const currentFragDuration = partCurrent
? partCurrent.duration
: fragCurrent
? fragCurrent.duration
: 0;
const ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1000;
const levelsSkipped: number[] = [];
for (let i = maxAutoLevel; i >= minAutoLevel; i--) {
const levelInfo = levels[i];
const upSwitch = i > selectionBaseLevel;
if (!levelInfo) {
continue;
}
if (
__USE_MEDIA_CAPABILITIES__ &&
config.useMediaCapabilities &&
!levelInfo.supportedResult &&
!levelInfo.supportedPromise
) {
const mediaCapabilities = navigator.mediaCapabilities as
| MediaCapabilities
| undefined;
if (
typeof mediaCapabilities?.decodingInfo === 'function' &&
requiresMediaCapabilitiesDecodingInfo(
levelInfo,
audioTracksByGroup,
currentVideoRange,
currentFrameRate,
currentBw,
audioPreference,
)
) {
levelInfo.supportedPromise = getMediaDecodingInfoPromise(
levelInfo,
audioTracksByGroup,
mediaCapabilities,
);
levelInfo.supportedPromise.then((decodingInfo) => {
if (!this.hls) {
return;
}
levelInfo.supportedResult = decodingInfo;
const levels = this.hls.levels;
const index = levels.indexOf(levelInfo);
if (decodingInfo.error) {
this.warn(
`MediaCapabilities decodingInfo error: "${
decodingInfo.error
}" for level ${index} ${JSON.stringify(decodingInfo)}`,
);
} else if (!decodingInfo.supported) {
this.warn(
`Unsupported MediaCapabilities decodingInfo result for level ${index} ${JSON.stringify(
decodingInfo,
)}`,
);
if (index > -1 && levels.length > 1) {
this.log(`Removing unsupported level ${index}`);
this.hls.removeLevel(index);
}
}
});
} else {
levelInfo.supportedResult = SUPPORTED_INFO_DEFAULT;
}
}
// skip candidates which change codec-family or video-range,
// and which decrease or increase frame-rate for up and down-switch respectfully
if (
(currentCodecSet && levelInfo.codecSet !== currentCodecSet) ||
(currentVideoRange && levelInfo.videoRange !== currentVideoRange) ||
(upSwitch && currentFrameRate > levelInfo.frameRate) ||
(!upSwitch &&
currentFrameRate > 0 &&
currentFrameRate < levelInfo.frameRate) ||
(levelInfo.supportedResult &&
!levelInfo.supportedResult.decodingInfoResults?.[0].smooth)
) {
levelsSkipped.push(i);
continue;
}
const levelDetails = levelInfo.details;
const avgDuration =
(partCurrent
? levelDetails?.partTarget
: levelDetails?.averagetargetduration) || currentFragDuration;
let adjustedbw: number;
// follow algorithm captured from stagefright :
// https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
// Pick the highest bandwidth stream below or equal to estimated bandwidth.
// consider only 80% of the available bandwidth, but if we are switching up,
// be even more conservative (70%) to avoid overestimating and immediately
// switching back.
if (!upSwitch) {
adjustedbw = bwFactor * currentBw;
} else {
adjustedbw = bwUpFactor * currentBw;
}
// Use average bitrate when starvation delay (buffer length) is gt or eq two segment durations and rebuffering is not expected (maxStarvationDelay > 0)
const bitrate: number =
currentFragDuration &&
bufferStarvationDelay >= currentFragDuration * 2 &&
maxStarvationDelay === 0
? levels[i].averageBitrate
: levels[i].maxBitrate;
const fetchDuration: number = this.getTimeToLoadFrag(
ttfbEstimateSec,
adjustedbw,
bitrate * avgDuration,
levelDetails === undefined,
);
const canSwitchWithinTolerance =
// if adjusted bw is greater than level bitrate AND
adjustedbw >= bitrate &&
// no level change, or new level has no error history
(i === lastLoadedFragLevel ||
(levelInfo.loadError === 0 && levelInfo.fragmentError === 0)) &&
// fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
// we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...
// special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
(fetchDuration <= ttfbEstimateSec ||
!Number.isFinite(fetchDuration) ||
(live && !this.bitrateTestDelay) ||
fetchDuration < maxFetchDuration);
if (canSwitchWithinTolerance) {
const forcedAutoLevel = this.forcedAutoLevel;
if (
i !== loadLevel &&
(forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)
) {
if (levelsSkipped.length) {
this.trace(
`Skipped level(s) ${levelsSkipped.join(
',',
)} of ${maxAutoLevel} max with CODECS and VIDEO-RANGE:"${
levels[levelsSkipped[0]].codecs
}" ${levels[levelsSkipped[0]].videoRange}; not compatible with "${
level.codecs
}" ${currentVideoRange}`,
);
}
this.info(
`switch candidate:${selectionBaseLevel}->${i} adjustedbw(${Math.round(
adjustedbw,
)})-bitrate=${Math.round(
adjustedbw - bitrate,
)} ttfb:${ttfbEstimateSec.toFixed(
1,
)} avgDuration:${avgDuration.toFixed(
1,
)} maxFetchDuration:${maxFetchDuration.toFixed(
1,
)} fetchDuration:${fetchDuration.toFixed(
1,
)} firstSelection:${firstSelection} codecSet:${currentCodecSet} videoRange:${currentVideoRange} hls.loadLevel:${loadLevel}`,
);
}
if (firstSelection) {
this.firstSelection = i;
}
// as we are looping from highest to lowest, this will return the best achievable quality level
return i;
}
}
// not enough time budget even with quality level 0 ... rebuffering might happen
return -1;
}
public set nextAutoLevel(nextLevel: number) {
const { maxAutoLevel, minAutoLevel } = this.hls;
const value = Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);
if (this._nextAutoLevel !== value) {
this.nextAutoLevelKey = '';
this._nextAutoLevel = value;
}
}
}
export default AbrController;