forked from video-dev/hls.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream-controller.ts
1461 lines (1366 loc) · 46.6 KB
/
stream-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
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
import BaseStreamController, { State } from './base-stream-controller';
import { changeTypeSupported } from '../is-supported';
import { Events } from '../events';
import { BufferHelper, BufferInfo } from '../utils/buffer-helper';
import { FragmentState } from './fragment-tracker';
import { PlaylistContextType, PlaylistLevelType } from '../types/loader';
import { ElementaryStreamTypes, Fragment } from '../loader/fragment';
import TransmuxerInterface from '../demux/transmuxer-interface';
import { ChunkMetadata } from '../types/transmuxer';
import GapController, { MAX_START_GAP_JUMP } from './gap-controller';
import { ErrorDetails } from '../errors';
import type { NetworkComponentAPI } from '../types/component-api';
import type Hls from '../hls';
import type { Level } from '../types/level';
import type { LevelDetails } from '../loader/level-details';
import type { FragmentTracker } from './fragment-tracker';
import type KeyLoader from '../loader/key-loader';
import type { TransmuxerResult } from '../types/transmuxer';
import type { TrackSet } from '../types/track';
import type { SourceBufferName } from '../types/buffer';
import type {
AudioTrackSwitchedData,
AudioTrackSwitchingData,
BufferCreatedData,
BufferEOSData,
BufferFlushedData,
ErrorData,
FragBufferedData,
FragLoadedData,
FragParsingMetadataData,
FragParsingUserdataData,
LevelLoadedData,
LevelLoadingData,
LevelsUpdatedData,
ManifestParsedData,
MediaAttachedData,
} from '../types/events';
const TICK_INTERVAL = 100; // how often to tick in ms
export default class StreamController
extends BaseStreamController
implements NetworkComponentAPI
{
private audioCodecSwap: boolean = false;
private gapController: GapController | null = null;
private level: number = -1;
private _forceStartLoad: boolean = false;
private altAudio: boolean = false;
private audioOnly: boolean = false;
private fragPlaying: Fragment | null = null;
private fragLastKbps: number = 0;
private couldBacktrack: boolean = false;
private backtrackFragment: Fragment | null = null;
private audioCodecSwitch: boolean = false;
private videoBuffer: any | null = null;
constructor(
hls: Hls,
fragmentTracker: FragmentTracker,
keyLoader: KeyLoader,
) {
super(
hls,
fragmentTracker,
keyLoader,
'stream-controller',
PlaylistLevelType.MAIN,
);
this.registerListeners();
}
protected registerListeners() {
super.registerListeners();
const { hls } = this;
hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
hls.on(
Events.FRAG_LOAD_EMERGENCY_ABORTED,
this.onFragLoadEmergencyAborted,
this,
);
hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
}
protected unregisterListeners() {
super.unregisterListeners();
const { hls } = this;
hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
hls.off(
Events.FRAG_LOAD_EMERGENCY_ABORTED,
this.onFragLoadEmergencyAborted,
this,
);
hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
}
protected onHandlerDestroying() {
// @ts-ignore
this.onMediaPlaying = this.onMediaSeeked = null;
this.unregisterListeners();
super.onHandlerDestroying();
}
public startLoad(startPosition: number): void {
if (this.levels) {
const { lastCurrentTime, hls } = this;
this.stopLoad();
this.setInterval(TICK_INTERVAL);
this.level = -1;
if (!this.startFragRequested) {
// determine load level
let startLevel = hls.startLevel;
if (startLevel === -1) {
if (hls.config.testBandwidth && this.levels.length > 1) {
// -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
startLevel = 0;
this.bitrateTest = true;
} else {
startLevel = hls.firstAutoLevel;
}
}
// set new level to playlist loader : this will trigger start level load
// hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
hls.nextLoadLevel = startLevel;
this.level = hls.loadLevel;
this.loadedmetadata = false;
}
// if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
if (lastCurrentTime > 0 && startPosition === -1) {
this.log(
`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(
3,
)}`,
);
startPosition = lastCurrentTime;
}
this.state = State.IDLE;
this.nextLoadPosition =
this.startPosition =
this.lastCurrentTime =
startPosition;
this.tick();
} else {
this._forceStartLoad = true;
this.state = State.STOPPED;
}
}
public stopLoad() {
this._forceStartLoad = false;
super.stopLoad();
}
protected doTick() {
switch (this.state) {
case State.WAITING_LEVEL: {
const { levels, level } = this;
const currentLevel = levels?.[level];
const details = currentLevel?.details;
if (
details &&
(!details.live || this.levelLastLoaded === currentLevel)
) {
if (this.waitForCdnTuneIn(details)) {
break;
}
this.state = State.IDLE;
break;
} else if (this.hls.nextLoadLevel !== this.level) {
this.state = State.IDLE;
break;
}
break;
}
case State.FRAG_LOADING_WAITING_RETRY:
{
const now = self.performance.now();
const retryDate = this.retryDate;
// if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
if (!retryDate || now >= retryDate || this.media?.seeking) {
const { levels, level } = this;
const currentLevel = levels?.[level];
this.resetStartWhenNotLoaded(currentLevel || null);
this.state = State.IDLE;
}
}
break;
default:
break;
}
if (this.state === State.IDLE) {
this.doTickIdle();
}
this.onTickEnd();
}
protected onTickEnd() {
super.onTickEnd();
this.checkBuffer();
this.checkFragmentChanged();
}
private doTickIdle() {
if (!this.buffering) {
return;
}
const { hls, levelLastLoaded, levels, media } = this;
// if start level not parsed yet OR
// if video not attached AND start fragment already requested OR start frag prefetch not enabled
// exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
if (
levelLastLoaded === null ||
(!media && (this.startFragRequested || !hls.config.startFragPrefetch))
) {
return;
}
// If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
if (this.altAudio && this.audioOnly) {
return;
}
const level = hls.nextLoadLevel;
if (!levels?.[level]) {
return;
}
const levelInfo = levels[level];
// if buffer length is less than maxBufLen try to load a new fragment
const bufferInfo = this.getMainFwdBufferInfo();
if (bufferInfo === null) {
return;
}
const lastDetails = this.getLevelDetails();
if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {
const data: BufferEOSData = {};
if (this.altAudio) {
data.type = 'video';
}
this.hls.trigger(Events.BUFFER_EOS, data);
this.state = State.ENDED;
return;
}
// set next load level : this will trigger a playlist load if needed
if (hls.loadLevel !== level && hls.manualLevel === -1) {
this.log(`Adapting to level ${level} from level ${this.level}`);
}
this.level = hls.nextLoadLevel = level;
const levelDetails = levelInfo.details;
// if level info not retrieved yet, switch state and wait for level retrieval
// if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
// a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
if (
!levelDetails ||
this.state === State.WAITING_LEVEL ||
(levelDetails.live && this.levelLastLoaded !== levelInfo)
) {
this.level = level;
this.state = State.WAITING_LEVEL;
return;
}
const bufferLen = bufferInfo.len;
// compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s
const maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);
// Stay idle if we are still with buffer margins
if (bufferLen >= maxBufLen) {
return;
}
if (
this.backtrackFragment &&
this.backtrackFragment.start > bufferInfo.end
) {
this.backtrackFragment = null;
}
const targetBufferTime = this.backtrackFragment
? this.backtrackFragment.start
: bufferInfo.end;
let frag = this.getNextFragment(targetBufferTime, levelDetails);
// Avoid backtracking by loading an earlier segment in streams with segments that do not start with a key frame (flagged by `couldBacktrack`)
if (
this.couldBacktrack &&
!this.fragPrevious &&
frag &&
frag.sn !== 'initSegment' &&
this.fragmentTracker.getState(frag) !== FragmentState.OK
) {
const backtrackSn = (this.backtrackFragment ?? frag).sn as number;
const fragIdx = backtrackSn - levelDetails.startSN;
const backtrackFrag = levelDetails.fragments[fragIdx - 1];
if (backtrackFrag && frag.cc === backtrackFrag.cc) {
frag = backtrackFrag;
this.fragmentTracker.removeFragment(backtrackFrag);
}
} else if (this.backtrackFragment && bufferInfo.len) {
this.backtrackFragment = null;
}
// Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags
if (frag && this.isLoopLoading(frag, targetBufferTime)) {
const gapStart = frag.gap;
if (!gapStart) {
// Cleanup the fragment tracker before trying to find the next unbuffered fragment
const type =
this.audioOnly && !this.altAudio
? ElementaryStreamTypes.AUDIO
: ElementaryStreamTypes.VIDEO;
const mediaBuffer =
(type === ElementaryStreamTypes.VIDEO
? this.videoBuffer
: this.mediaBuffer) || this.media;
if (mediaBuffer) {
this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
}
}
frag = this.getNextFragmentLoopLoading(
frag,
levelDetails,
bufferInfo,
PlaylistLevelType.MAIN,
maxBufLen,
);
}
if (!frag) {
return;
}
if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
frag = frag.initSegment;
}
this.loadFragment(frag, levelInfo, targetBufferTime);
}
protected loadFragment(
frag: Fragment,
level: Level,
targetBufferTime: number,
) {
// Check if fragment is not loaded
const fragState = this.fragmentTracker.getState(frag);
this.fragCurrent = frag;
if (
fragState === FragmentState.NOT_LOADED ||
fragState === FragmentState.PARTIAL
) {
if (frag.sn === 'initSegment') {
this._loadInitSegment(frag, level);
} else if (this.bitrateTest) {
this.log(
`Fragment ${frag.sn} of level ${frag.level} is being downloaded to test bitrate and will not be buffered`,
);
this._loadBitrateTestFrag(frag, level);
} else {
this.startFragRequested = true;
super.loadFragment(frag, level, targetBufferTime);
}
} else {
this.clearTrackerIfNeeded(frag);
}
}
private getBufferedFrag(position) {
return this.fragmentTracker.getBufferedFrag(
position,
PlaylistLevelType.MAIN,
);
}
private followingBufferedFrag(frag: Fragment | null) {
if (frag) {
// try to get range of next fragment (500ms after this range)
return this.getBufferedFrag(frag.end + 0.5);
}
return null;
}
/*
on immediate level switch :
- pause playback if playing
- cancel any pending load request
- and trigger a buffer flush
*/
public immediateLevelSwitch() {
this.abortCurrentFrag();
this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
}
/**
* try to switch ASAP without breaking video playback:
* in order to ensure smooth but quick level switching,
* we need to find the next flushable buffer range
* we should take into account new segment fetch time
*/
public nextLevelSwitch() {
const { levels, media } = this;
// ensure that media is defined and that metadata are available (to retrieve currentTime)
if (media?.readyState) {
let fetchdelay;
const fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
// flush buffer preceding current fragment (flush until current fragment start offset)
// minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
}
const levelDetails = this.getLevelDetails();
if (levelDetails?.live) {
const bufferInfo = this.getMainFwdBufferInfo();
// Do not flush in live stream with low buffer
if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {
return;
}
}
if (!media.paused && levels) {
// add a safety delay of 1s
const nextLevelId = this.hls.nextLoadLevel;
const nextLevel = levels[nextLevelId];
const fragLastKbps = this.fragLastKbps;
if (fragLastKbps && this.fragCurrent) {
fetchdelay =
(this.fragCurrent.duration * nextLevel.maxBitrate) /
(1000 * fragLastKbps) +
1;
} else {
fetchdelay = 0;
}
} else {
fetchdelay = 0;
}
// this.log('fetchdelay:'+fetchdelay);
// find buffer range that will be reached once new fragment will be fetched
const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
if (bufferedFrag) {
// we can flush buffer range following this one without stalling playback
const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
if (nextBufferedFrag) {
// if we are here, we can also cancel any loading/demuxing in progress, as they are useless
this.abortCurrentFrag();
// start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.
const maxStart = nextBufferedFrag.maxStartPTS
? nextBufferedFrag.maxStartPTS
: nextBufferedFrag.start;
const fragDuration = nextBufferedFrag.duration;
const startPts = Math.max(
bufferedFrag.end,
maxStart +
Math.min(
Math.max(
fragDuration - this.config.maxFragLookUpTolerance,
fragDuration * (this.couldBacktrack ? 0.5 : 0.125),
),
fragDuration * (this.couldBacktrack ? 0.75 : 0.25),
),
);
this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
}
}
}
}
private abortCurrentFrag() {
const fragCurrent = this.fragCurrent;
this.fragCurrent = null;
this.backtrackFragment = null;
if (fragCurrent) {
fragCurrent.abortRequests();
this.fragmentTracker.removeFragment(fragCurrent);
}
switch (this.state) {
case State.KEY_LOADING:
case State.FRAG_LOADING:
case State.FRAG_LOADING_WAITING_RETRY:
case State.PARSING:
case State.PARSED:
this.state = State.IDLE;
break;
}
this.nextLoadPosition = this.getLoadPosition();
}
protected flushMainBuffer(startOffset: number, endOffset: number) {
super.flushMainBuffer(
startOffset,
endOffset,
this.altAudio ? 'video' : null,
);
}
protected onMediaAttached(
event: Events.MEDIA_ATTACHED,
data: MediaAttachedData,
) {
super.onMediaAttached(event, data);
const media = data.media;
media.addEventListener('playing', this.onMediaPlaying);
media.addEventListener('seeked', this.onMediaSeeked);
this.gapController = new GapController(
this.config,
media,
this.fragmentTracker,
this.hls,
);
}
protected onMediaDetaching() {
const { media } = this;
if (media) {
media.removeEventListener('playing', this.onMediaPlaying);
media.removeEventListener('seeked', this.onMediaSeeked);
}
this.videoBuffer = null;
this.fragPlaying = null;
if (this.gapController) {
this.gapController.destroy();
this.gapController = null;
}
super.onMediaDetaching();
}
private onMediaPlaying = () => {
// tick to speed up FRAG_CHANGED triggering
this.tick();
};
private onMediaSeeked = () => {
const media = this.media;
const currentTime = media ? media.currentTime : null;
if (Number.isFinite(currentTime)) {
this.log(`Media seeked to ${(currentTime as number).toFixed(3)}`);
}
// If seeked was issued before buffer was appended do not tick immediately
const bufferInfo = this.getMainFwdBufferInfo();
if (bufferInfo === null || bufferInfo.len === 0) {
this.warn(
`Main forward buffer length on "seeked" event ${
bufferInfo ? bufferInfo.len : 'empty'
})`,
);
return;
}
// tick to speed up FRAG_CHANGED triggering
this.tick();
};
protected onManifestLoading() {
// reset buffer on manifest loading
this.log('Trigger BUFFER_RESET');
this.hls.trigger(Events.BUFFER_RESET, undefined);
this.fragmentTracker.removeAllFragments();
this.couldBacktrack = false;
this.startPosition = this.lastCurrentTime = this.fragLastKbps = 0;
this.levels =
this.fragPlaying =
this.backtrackFragment =
this.levelLastLoaded =
null;
this.altAudio = this.audioOnly = this.startFragRequested = false;
}
private onManifestParsed(
event: Events.MANIFEST_PARSED,
data: ManifestParsedData,
) {
// detect if we have different kind of audio codecs used amongst playlists
let aac = false;
let heaac = false;
data.levels.forEach((level) => {
const codec = level.audioCodec;
if (codec) {
aac = aac || codec.indexOf('mp4a.40.2') !== -1;
heaac = heaac || codec.indexOf('mp4a.40.5') !== -1;
}
});
this.audioCodecSwitch = aac && heaac && !changeTypeSupported();
if (this.audioCodecSwitch) {
this.log(
'Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC',
);
}
this.levels = data.levels;
this.startFragRequested = false;
}
private onLevelLoading(event: Events.LEVEL_LOADING, data: LevelLoadingData) {
const { levels } = this;
if (!levels || this.state !== State.IDLE) {
return;
}
const level = levels[data.level];
if (
!level.details ||
(level.details.live && this.levelLastLoaded !== level) ||
this.waitForCdnTuneIn(level.details)
) {
this.state = State.WAITING_LEVEL;
}
}
private onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {
const { levels } = this;
const newLevelId = data.level;
const newDetails = data.details;
const duration = newDetails.totalduration;
if (!levels) {
this.warn(`Levels were reset while loading level ${newLevelId}`);
return;
}
this.log(
`Level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}]${
newDetails.lastPartSn
? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]`
: ''
}, cc [${newDetails.startCC}, ${newDetails.endCC}] duration:${duration}`,
);
const curLevel = levels[newLevelId];
const fragCurrent = this.fragCurrent;
if (
fragCurrent &&
(this.state === State.FRAG_LOADING ||
this.state === State.FRAG_LOADING_WAITING_RETRY)
) {
if (fragCurrent.level !== data.level && fragCurrent.loader) {
this.abortCurrentFrag();
}
}
let sliding = 0;
if (newDetails.live || curLevel.details?.live) {
this.checkLiveUpdate(newDetails);
if (newDetails.deltaUpdateFailed) {
return;
}
sliding = this.alignPlaylists(
newDetails,
curLevel.details,
this.levelLastLoaded?.details,
);
}
// override level info
curLevel.details = newDetails;
this.levelLastLoaded = curLevel;
this.hls.trigger(Events.LEVEL_UPDATED, {
details: newDetails,
level: newLevelId,
});
// only switch back to IDLE state if we were waiting for level to start downloading a new fragment
if (this.state === State.WAITING_LEVEL) {
if (this.waitForCdnTuneIn(newDetails)) {
// Wait for Low-Latency CDN Tune-in
return;
}
this.state = State.IDLE;
}
if (!this.startFragRequested) {
this.setStartPosition(newDetails, sliding);
} else if (newDetails.live) {
this.synchronizeToLiveEdge(newDetails);
}
// trigger handler right now
this.tick();
}
protected _handleFragmentLoadProgress(data: FragLoadedData) {
const { frag, part, payload } = data;
const { levels } = this;
if (!levels) {
this.warn(
`Levels were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`,
);
return;
}
const currentLevel = levels[frag.level];
const details = currentLevel.details as LevelDetails;
if (!details) {
this.warn(
`Dropping fragment ${frag.sn} of level ${frag.level} after level details were reset`,
);
this.fragmentTracker.removeFragment(frag);
return;
}
const videoCodec = currentLevel.videoCodec;
// time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
const accurateTimeOffset = details.PTSKnown || !details.live;
const initSegmentData = frag.initSegment?.data;
const audioCodec = this._getAudioCodec(currentLevel);
// transmux the MPEG-TS data to ISO-BMFF segments
// this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);
const transmuxer = (this.transmuxer =
this.transmuxer ||
new TransmuxerInterface(
this.hls,
PlaylistLevelType.MAIN,
this._handleTransmuxComplete.bind(this),
this._handleTransmuxerFlush.bind(this),
));
const partIndex = part ? part.index : -1;
const partial = partIndex !== -1;
const chunkMeta = new ChunkMetadata(
frag.level,
frag.sn as number,
frag.stats.chunkCount,
payload.byteLength,
partIndex,
partial,
);
const initPTS = this.initPTS[frag.cc];
transmuxer.push(
payload,
initSegmentData,
audioCodec,
videoCodec,
frag,
part,
details.totalduration,
accurateTimeOffset,
chunkMeta,
initPTS,
);
}
private onAudioTrackSwitching(
event: Events.AUDIO_TRACK_SWITCHING,
data: AudioTrackSwitchingData,
) {
// if any URL found on new audio track, it is an alternate audio track
const fromAltAudio = this.altAudio;
const altAudio = !!data.url;
// if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
// don't do anything if we switch to alt audio: audio stream controller is handling it.
// we will just have to change buffer scheduling on audioTrackSwitched
if (!altAudio) {
if (this.mediaBuffer !== this.media) {
this.log(
'Switching on main audio, use media.buffered to schedule main fragment loading',
);
this.mediaBuffer = this.media;
const fragCurrent = this.fragCurrent;
// we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
if (fragCurrent) {
this.log('Switching to main audio track, cancel main fragment load');
fragCurrent.abortRequests();
this.fragmentTracker.removeFragment(fragCurrent);
}
// destroy transmuxer to force init segment generation (following audio switch)
this.resetTransmuxer();
// switch to IDLE state to load new fragment
this.resetLoadingState();
} else if (this.audioOnly) {
// Reset audio transmuxer so when switching back to main audio we're not still appending where we left off
this.resetTransmuxer();
}
const hls = this.hls;
// If switching from alt to main audio, flush all audio and trigger track switched
if (fromAltAudio) {
hls.trigger(Events.BUFFER_FLUSHING, {
startOffset: 0,
endOffset: Number.POSITIVE_INFINITY,
type: null,
});
this.fragmentTracker.removeAllFragments();
}
hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
}
}
private onAudioTrackSwitched(
event: Events.AUDIO_TRACK_SWITCHED,
data: AudioTrackSwitchedData,
) {
const trackId = data.id;
const altAudio = !!this.hls.audioTracks[trackId].url;
if (altAudio) {
const videoBuffer = this.videoBuffer;
// if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
if (videoBuffer && this.mediaBuffer !== videoBuffer) {
this.log(
'Switching on alternate audio, use video.buffered to schedule main fragment loading',
);
this.mediaBuffer = videoBuffer;
}
}
this.altAudio = altAudio;
this.tick();
}
private onBufferCreated(
event: Events.BUFFER_CREATED,
data: BufferCreatedData,
) {
const tracks = data.tracks;
let mediaTrack;
let name;
let alternate = false;
for (const type in tracks) {
const track = tracks[type];
if (track.id === 'main') {
name = type;
mediaTrack = track;
// keep video source buffer reference
if (type === 'video') {
const videoTrack = tracks[type];
if (videoTrack) {
this.videoBuffer = videoTrack.buffer;
}
}
} else {
alternate = true;
}
}
if (alternate && mediaTrack) {
this.log(
`Alternate track found, use ${name}.buffered to schedule main fragment loading`,
);
this.mediaBuffer = mediaTrack.buffer;
} else {
this.mediaBuffer = this.media;
}
}
private onFragBuffered(event: Events.FRAG_BUFFERED, data: FragBufferedData) {
const { frag, part } = data;
if (frag && frag.type !== PlaylistLevelType.MAIN) {
return;
}
if (this.fragContextChanged(frag)) {
// If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
// Avoid setting state back to IDLE, since that will interfere with a level switch
this.warn(
`Fragment ${frag.sn}${part ? ' p: ' + part.index : ''} of level ${
frag.level
} finished buffering, but was aborted. state: ${this.state}`,
);
if (this.state === State.PARSED) {
this.state = State.IDLE;
}
return;
}
const stats = part ? part.stats : frag.stats;
this.fragLastKbps = Math.round(
(8 * stats.total) / (stats.buffering.end - stats.loading.first),
);
if (frag.sn !== 'initSegment') {
this.fragPrevious = frag;
}
this.fragBufferedComplete(frag, part);
}
protected onError(event: Events.ERROR, data: ErrorData) {
if (data.fatal) {
this.state = State.ERROR;
return;
}
switch (data.details) {
case ErrorDetails.FRAG_GAP:
case ErrorDetails.FRAG_PARSING_ERROR:
case ErrorDetails.FRAG_DECRYPT_ERROR:
case ErrorDetails.FRAG_LOAD_ERROR:
case ErrorDetails.FRAG_LOAD_TIMEOUT:
case ErrorDetails.KEY_LOAD_ERROR:
case ErrorDetails.KEY_LOAD_TIMEOUT:
this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);
break;
case ErrorDetails.LEVEL_LOAD_ERROR:
case ErrorDetails.LEVEL_LOAD_TIMEOUT:
case ErrorDetails.LEVEL_PARSING_ERROR:
// in case of non fatal error while loading level, if level controller is not retrying to load level, switch back to IDLE
if (
!data.levelRetry &&
this.state === State.WAITING_LEVEL &&
data.context?.type === PlaylistContextType.LEVEL
) {
this.state = State.IDLE;
}
break;
case ErrorDetails.BUFFER_APPEND_ERROR:
case ErrorDetails.BUFFER_FULL_ERROR:
if (!data.parent || data.parent !== 'main') {
return;
}
if (data.details === ErrorDetails.BUFFER_APPEND_ERROR) {
this.resetLoadingState();
return;
}
if (this.reduceLengthAndFlushBuffer(data)) {
this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
}
break;
case ErrorDetails.INTERNAL_EXCEPTION:
this.recoverWorkerError(data);
break;
default:
break;
}
}
// Checks the health of the buffer and attempts to resolve playback stalls.
private checkBuffer() {
const { media, gapController } = this;
if (!media || !gapController || !media.readyState) {
// Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
return;
}
if (this.loadedmetadata || !BufferHelper.getBuffered(media).length) {
// Resolve gaps using the main buffer, whose ranges are the intersections of the A/V sourcebuffers
const state = this.state;
const activeFrag = state !== State.IDLE ? this.fragCurrent : null;
const levelDetails = this.getLevelDetails();
gapController.poll(this.lastCurrentTime, activeFrag, levelDetails, state);
}
this.lastCurrentTime = media.currentTime;
}
private onFragLoadEmergencyAborted() {
this.state = State.IDLE;
// if loadedmetadata is not set, it means that we are emergency switch down on first frag
// in that case, reset startFragRequested flag
if (!this.loadedmetadata) {
this.startFragRequested = false;
this.nextLoadPosition = this.startPosition;
}
this.tickImmediate();
}
private onBufferFlushed(
event: Events.BUFFER_FLUSHED,
{ type }: BufferFlushedData,
) {
if (
type !== ElementaryStreamTypes.AUDIO ||
(this.audioOnly && !this.altAudio)
) {
const mediaBuffer =
(type === ElementaryStreamTypes.VIDEO
? this.videoBuffer
: this.mediaBuffer) || this.media;
this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
this.tick();
}
}
private onLevelsUpdated(
event: Events.LEVELS_UPDATED,
data: LevelsUpdatedData,
) {
if (this.level > -1 && this.fragCurrent) {
this.level = this.fragCurrent.level;
}
this.levels = data.levels;
}
public swapAudioCodec() {
this.audioCodecSwap = !this.audioCodecSwap;
}
/**
* Seeks to the set startPosition if not equal to the mediaElement's current time.
*/
protected seekToStartPos() {
const { media } = this;
if (!media) {
return;
}
const currentTime = media.currentTime;
let startPosition = this.startPosition;
// only adjust currentTime if different from startPosition or if startPosition not buffered