/
base-stream-controller.ts
1284 lines (1196 loc) · 42 KB
/
base-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 TaskLoop from '../task-loop';
import { FragmentState } from './fragment-tracker';
import { Bufferable, BufferHelper } from '../utils/buffer-helper';
import { logger } from '../utils/logger';
import { Events } from '../events';
import { ErrorDetails } from '../errors';
import * as LevelHelper from './level-helper';
import { ChunkMetadata } from '../types/transmuxer';
import { appendUint8Array } from '../utils/mp4-tools';
import { alignStream } from '../utils/discontinuities';
import {
findFragmentByPDT,
findFragmentByPTS,
findFragWithCC,
} from './fragment-finders';
import TransmuxerInterface from '../demux/transmuxer-interface';
import { Fragment, Part } from '../loader/fragment';
import FragmentLoader, {
FragmentLoadProgressCallback,
LoadError,
} from '../loader/fragment-loader';
import { LevelDetails } from '../loader/level-details';
import {
BufferAppendingData,
ErrorData,
FragLoadedData,
PartsLoadedData,
KeyLoadedData,
MediaAttachingData,
BufferFlushingData,
} from '../types/events';
import Decrypter from '../crypt/decrypter';
import TimeRanges from '../utils/time-ranges';
import { PlaylistLevelType } from '../types/loader';
import type { FragmentTracker } from './fragment-tracker';
import type { Level } from '../types/level';
import type { RemuxedTrack } from '../types/remuxer';
import type Hls from '../hls';
import type { HlsConfig } from '../config';
import type { HlsEventEmitter } from '../events';
import type { NetworkComponentAPI } from '../types/component-api';
import type { SourceBufferName } from '../types/buffer';
type ResolveFragLoaded = (FragLoadedEndData) => void;
type RejectFragLoaded = (LoadError) => void;
export const State = {
STOPPED: 'STOPPED',
IDLE: 'IDLE',
KEY_LOADING: 'KEY_LOADING',
FRAG_LOADING: 'FRAG_LOADING',
FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
WAITING_TRACK: 'WAITING_TRACK',
PARSING: 'PARSING',
PARSED: 'PARSED',
BACKTRACKING: 'BACKTRACKING',
ENDED: 'ENDED',
ERROR: 'ERROR',
WAITING_INIT_PTS: 'WAITING_INIT_PTS',
WAITING_LEVEL: 'WAITING_LEVEL',
};
export default class BaseStreamController
extends TaskLoop
implements NetworkComponentAPI {
protected hls: Hls;
protected fragPrevious: Fragment | null = null;
protected fragCurrent: Fragment | null = null;
protected fragmentTracker: FragmentTracker;
protected transmuxer: TransmuxerInterface | null = null;
protected _state: string = State.STOPPED;
protected media?: any;
protected mediaBuffer?: any;
protected config: HlsConfig;
protected bitrateTest: boolean = false;
protected lastCurrentTime: number = 0;
protected nextLoadPosition: number = 0;
protected startPosition: number = 0;
protected loadedmetadata: boolean = false;
protected fragLoadError: number = 0;
protected retryDate: number = 0;
protected levels: Array<Level> | null = null;
protected fragmentLoader!: FragmentLoader;
protected levelLastLoaded: number | null = null;
protected startFragRequested: boolean = false;
protected decrypter: Decrypter;
protected initPTS: Array<number> = [];
protected onvseeking: EventListener | null = null;
protected onvended: EventListener | null = null;
private readonly logPrefix: string = '';
protected log: (msg: any) => void;
protected warn: (msg: any) => void;
constructor(hls: Hls, fragmentTracker: FragmentTracker, logPrefix: string) {
super();
this.logPrefix = logPrefix;
this.log = logger.log.bind(logger, `${logPrefix}:`);
this.warn = logger.warn.bind(logger, `${logPrefix}:`);
this.hls = hls;
this.fragmentLoader = new FragmentLoader(hls.config);
this.fragmentTracker = fragmentTracker;
this.config = hls.config;
this.decrypter = new Decrypter(hls as HlsEventEmitter, hls.config);
hls.on(Events.KEY_LOADED, this.onKeyLoaded, this);
}
protected doTick() {
this.onTickEnd();
}
protected onTickEnd() {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public startLoad(startPosition: number): void {}
public stopLoad() {
this.fragmentLoader.abort();
const frag = this.fragCurrent;
if (frag) {
this.fragmentTracker.removeFragment(frag);
}
this.resetTransmuxer();
this.fragCurrent = null;
this.fragPrevious = null;
this.clearInterval();
this.clearNextTick();
this.state = State.STOPPED;
}
protected _streamEnded(bufferInfo, levelDetails) {
const { fragCurrent, fragmentTracker } = this;
// we just got done loading the final fragment and there is no other buffered range after ...
// rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
// so we should not switch to ENDED in that case, to be able to buffer them
if (
!levelDetails.live &&
fragCurrent &&
fragCurrent.sn === levelDetails.endSN &&
!bufferInfo.nextStart
) {
const fragState = fragmentTracker.getState(fragCurrent);
return (
fragState === FragmentState.PARTIAL || fragState === FragmentState.OK
);
}
return false;
}
protected onMediaAttached(
event: Events.MEDIA_ATTACHED,
data: MediaAttachingData
) {
const media = (this.media = this.mediaBuffer = data.media);
this.onvseeking = this.onMediaSeeking.bind(this);
this.onvended = this.onMediaEnded.bind(this);
media.addEventListener('seeking', this.onvseeking as EventListener);
media.addEventListener('ended', this.onvended as EventListener);
const config = this.config;
if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
this.startLoad(config.startPosition);
}
}
protected onMediaDetaching() {
const media = this.media;
if (media?.ended) {
this.log('MSE detaching and video ended, reset startPosition');
this.startPosition = this.lastCurrentTime = 0;
}
// remove video listeners
if (media) {
media.removeEventListener('seeking', this.onvseeking);
media.removeEventListener('ended', this.onvended);
this.onvseeking = this.onvended = null;
}
this.media = this.mediaBuffer = null;
this.loadedmetadata = false;
this.fragmentTracker.removeAllFragments();
this.stopLoad();
}
protected onMediaSeeking() {
const { config, fragCurrent, media, mediaBuffer, state } = this;
const currentTime = media ? media.currentTime : null;
const bufferInfo = BufferHelper.bufferInfo(
mediaBuffer || media,
currentTime,
config.maxBufferHole
);
this.log(
`media seeking to ${
Number.isFinite(currentTime) ? currentTime.toFixed(3) : currentTime
}, state: ${state}`
);
if (state === State.ENDED) {
// if seeking to unbuffered area, clean up fragPrevious
if (!bufferInfo.len) {
this.fragPrevious = null;
this.fragCurrent = null;
}
// switch to IDLE state to check for potential new fragment
this.state = State.IDLE;
} else if (fragCurrent && !bufferInfo.len) {
// check if we are seeking to a unbuffered area AND if frag loading is in progress
const tolerance = config.maxFragLookUpTolerance;
const fragStartOffset = fragCurrent.start - tolerance;
const fragEndOffset =
fragCurrent.start + fragCurrent.duration + tolerance;
// check if the seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything
if (currentTime < fragStartOffset || currentTime > fragEndOffset) {
if (fragCurrent.loader) {
this.log(
'seeking outside of buffer while fragment load in progress, cancel fragment load'
);
fragCurrent.loader.abort();
}
this.fragCurrent = null;
this.fragPrevious = null;
// switch to IDLE state to load new fragment
this.state = State.IDLE;
}
}
if (media) {
this.lastCurrentTime = currentTime;
}
// in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
if (!this.loadedmetadata && !bufferInfo.len) {
this.nextLoadPosition = this.startPosition = currentTime;
}
// tick to speed up processing
this.tick();
}
protected onMediaEnded() {
// reset startPosition and lastCurrentTime to restart playback @ stream beginning
this.startPosition = this.lastCurrentTime = 0;
}
onKeyLoaded(event: Events.KEY_LOADED, data: KeyLoadedData) {
if (this.state === State.KEY_LOADING && this.levels) {
this.state = State.IDLE;
const levelDetails = this.levels[data.frag.level].details;
if (levelDetails) {
this.loadFragment(data.frag, levelDetails, data.frag.start);
}
}
}
protected onHandlerDestroying() {
this.stopLoad();
super.onHandlerDestroying();
}
protected onHandlerDestroyed() {
this.state = State.STOPPED;
this.hls.off(Events.KEY_LOADED, this.onKeyLoaded, this);
if (this.fragmentLoader) {
this.fragmentLoader.destroy();
}
if (this.decrypter) {
this.decrypter.destroy();
}
// @ts-ignore
this.hls = this.log = this.warn = this.decrypter = this.fragmentLoader = this.fragmentTracker = null;
super.onHandlerDestroyed();
}
protected loadFragment(
frag: Fragment,
levelDetails: LevelDetails,
targetBufferTime: number
) {
this._loadFragForPlayback(frag, levelDetails, targetBufferTime);
}
private _loadFragForPlayback(
frag: Fragment,
levelDetails: LevelDetails,
targetBufferTime: number
) {
const progressCallback: FragmentLoadProgressCallback = (
data: FragLoadedData
) => {
if (this.fragContextChanged(frag)) {
this.warn(
`Fragment ${frag.sn}${
data.part ? ' p: ' + data.part.index : ''
} of level ${frag.level} was dropped during download.`
);
this.fragmentTracker.removeFragment(frag);
return;
}
frag.stats.chunkCount++;
this._handleFragmentLoadProgress(data);
};
this._doFragLoad(frag, levelDetails, targetBufferTime, progressCallback)
.then((data) => {
if (!data) {
// if we're here we probably needed to backtrack or are waiting for more parts
return;
}
this.fragLoadError = 0;
const state = this.state;
if (this.fragContextChanged(frag)) {
if (
state === State.FRAG_LOADING ||
state === State.BACKTRACKING ||
(!this.fragCurrent && state === State.PARSING)
) {
this.fragmentTracker.removeFragment(frag);
this.state = State.IDLE;
}
return;
}
if ('payload' in data) {
this.log(`Loaded fragment ${frag.sn} of level ${frag.level}`);
this.hls.trigger(Events.FRAG_LOADED, data);
// Tracker backtrack must be called after onFragLoaded to update the fragment entity state to BACKTRACKED
// This happens after handleTransmuxComplete when the worker or progressive is disabled
if (this.state === State.BACKTRACKING) {
this.fragmentTracker.backtrack(frag, data);
this.resetFragmentLoading(frag);
return;
}
}
// Pass through the whole payload; controllers not implementing progressive loading receive data from this callback
this._handleFragmentLoadComplete(data);
})
.catch((reason) => {
this.warn(reason);
this.resetFragmentLoading(frag);
});
}
protected flushMainBuffer(
startOffset: number,
endOffset: number,
type: SourceBufferName | null = null
) {
// When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,
// passing a null type flushes both buffers
const flushScope: BufferFlushingData = { startOffset, endOffset, type };
// Reset load errors on flush
this.fragLoadError = 0;
this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);
}
protected _loadInitSegment(frag: Fragment) {
this._doFragLoad(frag)
.then((data) => {
if (!data || this.fragContextChanged(frag) || !this.levels) {
throw new Error('init load aborted');
}
return data;
})
.then((data: FragLoadedData) => {
const { hls } = this;
const { payload } = data;
const decryptData = frag.decryptdata;
// check to see if the payload needs to be decrypted
if (
payload &&
payload.byteLength > 0 &&
decryptData &&
decryptData.key &&
decryptData.iv &&
decryptData.method === 'AES-128'
) {
const startTime = self.performance.now();
// decrypt the subtitles
return this.decrypter
.webCryptoDecrypt(
new Uint8Array(payload),
decryptData.key.buffer,
decryptData.iv.buffer
)
.then((decryptedData) => {
const endTime = self.performance.now();
hls.trigger(Events.FRAG_DECRYPTED, {
frag,
payload: decryptedData,
stats: {
tstart: startTime,
tdecrypt: endTime,
},
});
data.payload = decryptedData;
return data;
});
}
return data;
})
.then((data: FragLoadedData) => {
const { fragCurrent, hls, levels } = this;
if (!levels) {
throw new Error('init load aborted, missing levels');
}
const details = levels[frag.level].details as LevelDetails;
console.assert(
details,
'Level details are defined when init segment is loaded'
);
const initSegment = details.initSegment as Fragment;
console.assert(
initSegment,
'Fragment initSegment is defined when init segment is loaded'
);
const stats = frag.stats;
this.state = State.IDLE;
this.fragLoadError = 0;
initSegment.data = new Uint8Array(data.payload);
stats.parsing.start = stats.buffering.start = self.performance.now();
stats.parsing.end = stats.buffering.end = self.performance.now();
// Silence FRAG_BUFFERED event if fragCurrent is null
if (data.frag === fragCurrent) {
hls.trigger(Events.FRAG_BUFFERED, {
stats,
frag: fragCurrent,
part: null,
id: frag.type,
});
}
this.tick();
})
.catch((reason) => {
this.warn(reason);
this.resetFragmentLoading(frag);
});
}
protected fragContextChanged(frag: Fragment | null) {
const { fragCurrent } = this;
return (
!frag ||
!fragCurrent ||
frag.level !== fragCurrent.level ||
frag.sn !== fragCurrent.sn ||
frag.urlId !== fragCurrent.urlId
);
}
protected fragBufferedComplete(frag: Fragment, part: Part | null) {
const media = this.mediaBuffer ? this.mediaBuffer : this.media;
this.log(
`Buffered ${frag.type} sn: ${frag.sn}${
part ? ' part: ' + part.index : ''
} of ${this.logPrefix === '[stream-controller]' ? 'level' : 'track'} ${
frag.level
} ${TimeRanges.toString(BufferHelper.getBuffered(media))}`
);
this.state = State.IDLE;
this.tick();
}
protected _handleFragmentLoadComplete(fragLoadedEndData: PartsLoadedData) {
const { transmuxer } = this;
if (!transmuxer) {
return;
}
const { frag, part, partsLoaded } = fragLoadedEndData;
// If we did not load parts, or loaded all parts, we have complete (not partial) fragment data
const complete =
!partsLoaded ||
partsLoaded.length === 0 ||
partsLoaded.some((fragLoaded) => !fragLoaded);
const chunkMeta = new ChunkMetadata(
frag.level,
frag.sn as number,
frag.stats.chunkCount + 1,
0,
part ? part.index : -1,
!complete
);
transmuxer.flush(chunkMeta);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected _handleFragmentLoadProgress(frag: FragLoadedData) {}
protected _doFragLoad(
frag: Fragment,
details?: LevelDetails,
targetBufferTime: number | null = null,
progressCallback?: FragmentLoadProgressCallback
): Promise<PartsLoadedData | FragLoadedData | null> {
if (!this.levels) {
throw new Error('frag load aborted, missing levels');
}
targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
if (this.config.lowLatencyMode && details) {
const partList = details.partList;
if (partList && progressCallback) {
if (targetBufferTime > frag.end && details.fragmentHint) {
frag = details.fragmentHint;
}
const partIndex = this.getNextPart(partList, frag, targetBufferTime);
if (partIndex > -1) {
const part = partList[partIndex];
this.log(
`Loading part sn: ${frag.sn} p: ${part.index} cc: ${
frag.cc
} of playlist [${details.startSN}-${
details.endSN
}] parts [0-${partIndex}-${partList.length - 1}] ${
this.logPrefix === '[stream-controller]' ? 'level' : 'track'
}: ${frag.level}, target: ${parseFloat(
targetBufferTime.toFixed(3)
)}`
);
this.nextLoadPosition = part.start + part.duration;
this.state = State.FRAG_LOADING;
this.hls.trigger(Events.FRAG_LOADING, {
frag,
part: partList[partIndex],
targetBufferTime,
});
return this.doFragPartsLoad(
frag,
partList,
partIndex,
progressCallback
).catch((error: LoadError) => this.handleFragLoadError(error));
} else if (
!frag.url ||
this.loadedEndOfParts(partList, targetBufferTime)
) {
// Fragment hint has no parts
return Promise.resolve(null);
}
}
}
this.log(
`Loading fragment ${frag.sn} cc: ${frag.cc} ${
details ? 'of [' + details.startSN + '-' + details.endSN + '] ' : ''
}${this.logPrefix === '[stream-controller]' ? 'level' : 'track'}: ${
frag.level
}, target: ${parseFloat(targetBufferTime.toFixed(3))}`
);
// Don't update nextLoadPosition for fragments which are not buffered
if (Number.isFinite(frag.sn as number) && !this.bitrateTest) {
this.nextLoadPosition = frag.start + frag.duration;
}
this.state = State.FRAG_LOADING;
this.hls.trigger(Events.FRAG_LOADING, { frag, targetBufferTime });
return this.fragmentLoader
.load(frag, progressCallback)
.catch((error: LoadError) => this.handleFragLoadError(error));
}
private doFragPartsLoad(
frag: Fragment,
partList: Part[],
partIndex: number,
progressCallback: FragmentLoadProgressCallback
): Promise<PartsLoadedData | null> {
return new Promise(
(resolve: ResolveFragLoaded, reject: RejectFragLoaded) => {
const partsLoaded: FragLoadedData[] = [];
const loadPartIndex = (index: number) => {
const part = partList[index];
this.fragmentLoader
.loadPart(frag, part, progressCallback)
.then((partLoadedData: FragLoadedData) => {
partsLoaded[part.index] = partLoadedData;
const loadedPart = partLoadedData.part as Part;
this.hls.trigger(Events.FRAG_LOADED, partLoadedData);
const nextPart = partList[index + 1];
if (nextPart && nextPart.fragment === frag) {
loadPartIndex(index + 1);
} else {
return resolve({
frag,
part: loadedPart,
partsLoaded,
});
}
})
.catch(reject);
};
loadPartIndex(partIndex);
}
);
}
private handleFragLoadError({ data }: LoadError) {
if (data && data.details === ErrorDetails.INTERNAL_ABORTED) {
this.handleFragLoadAborted(data.frag, data.part);
} else {
this.hls.trigger(Events.ERROR, data as ErrorData);
}
return null;
}
protected _handleTransmuxerFlush(chunkMeta: ChunkMetadata) {
const context = this.getCurrentContext(chunkMeta);
if (!context || this.state !== State.PARSING) {
if (!this.fragCurrent) {
this.state = State.IDLE;
}
return;
}
const { frag, part, level } = context;
const now = self.performance.now();
frag.stats.parsing.end = now;
if (part) {
part.stats.parsing.end = now;
}
this.updateLevelTiming(frag, part, level, chunkMeta.partial);
}
protected getCurrentContext(
chunkMeta: ChunkMetadata
): { frag: Fragment; part: Part | null; level: Level } | null {
const { levels } = this;
const { level: levelIndex, sn, part: partIndex } = chunkMeta;
if (!levels || !levels[levelIndex]) {
this.warn(
`Levels object was unset while buffering fragment ${sn} of level ${levelIndex}. The current chunk will not be buffered.`
);
return null;
}
const level = levels[levelIndex];
const part =
partIndex > -1 ? LevelHelper.getPartWith(level, sn, partIndex) : null;
const frag = part
? part.fragment
: LevelHelper.getFragmentWithSN(level, sn);
if (!frag) {
return null;
}
return { frag, part, level };
}
protected bufferFragmentData(
data: RemuxedTrack,
frag: Fragment,
part: Part | null,
chunkMeta: ChunkMetadata
) {
if (!data || this.state !== State.PARSING) {
return;
}
const { data1, data2 } = data;
let buffer = data1;
if (data1 && data2) {
// Combine the moof + mdat so that we buffer with a single append
buffer = appendUint8Array(data1, data2);
}
if (!buffer || !buffer.length) {
return;
}
const segment: BufferAppendingData = {
type: data.type,
frag,
part,
chunkMeta,
parent: frag.type,
data: buffer,
};
this.hls.trigger(Events.BUFFER_APPENDING, segment);
if (data.dropped && data.independent && !part) {
// Clear buffer so that we reload previous segments sequentially if required
this.flushBufferGap(frag);
}
}
protected flushBufferGap(frag: Fragment) {
const media = this.media;
if (!media) {
return;
}
// If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed
if (!BufferHelper.isBuffered(media, media.currentTime)) {
this.flushMainBuffer(0, frag.start);
return;
}
// Remove back-buffer without interrupting playback to allow back tracking
const currentTime = media.currentTime;
const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
const fragDuration = frag.duration;
const segmentFraction = Math.min(
this.config.maxFragLookUpTolerance * 2,
fragDuration * 0.25
);
const start = Math.max(
Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction),
currentTime + segmentFraction
);
if (frag.start - start > segmentFraction) {
this.flushMainBuffer(start, frag.start);
}
}
protected reduceMaxBufferLength(threshold?: number) {
const config = this.config;
const minLength = threshold || config.maxBufferLength;
if (config.maxMaxBufferLength >= minLength) {
// reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
config.maxMaxBufferLength /= 2;
this.warn(`Reduce max buffer length to ${config.maxMaxBufferLength}s`);
return true;
}
return false;
}
protected getNextFragment(
pos: number,
levelDetails: LevelDetails
): Fragment | null {
const fragments = levelDetails.fragments;
const fragLen = fragments.length;
if (!fragLen) {
return null;
}
// find fragment index, contiguous with end of buffer position
const { config } = this;
const start = fragments[0].start;
let frag;
// If an initSegment is present, it must be buffered first
if (
levelDetails.initSegment &&
!levelDetails.initSegment.data &&
!this.bitrateTest
) {
frag = levelDetails.initSegment;
} else if (levelDetails.live) {
const initialLiveManifestSize = config.initialLiveManifestSize;
if (fragLen < initialLiveManifestSize) {
this.warn(
`Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`
);
return null;
}
// The real fragment start times for a live stream are only known after the PTS range for that level is known.
// In order to discover the range, we load the best matching fragment for that level and demux it.
// Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that
// we get the fragment matching that start time
if (
!levelDetails.PTSKnown &&
!this.startFragRequested &&
this.startPosition === -1
) {
frag = this.getInitialLiveFragment(levelDetails, fragments);
this.startPosition = frag
? this.hls.liveSyncPosition || frag.start
: pos;
}
} else if (pos <= start) {
// VoD playlist: if loadPosition before start of playlist, load first fragment
frag = fragments[0];
}
// If we haven't run into any special cases already, just load the fragment most closely matching the requested position
if (!frag) {
const end = config.lowLatencyMode
? levelDetails.partEnd
: levelDetails.fragmentEnd;
frag = this.getFragmentAtPosition(pos, end, levelDetails);
}
return frag;
}
getNextPart(
partList: Part[],
frag: Fragment,
targetBufferTime: number
): number {
let nextPart = -1;
let contiguous = false;
let independentAttrOmitted = true;
for (let i = 0, len = partList.length; i < len; i++) {
const part = partList[i];
independentAttrOmitted = independentAttrOmitted && !part.independent;
if (nextPart > -1 && targetBufferTime < part.start) {
break;
}
const loaded = part.loaded;
if (
!loaded &&
(contiguous || part.independent || independentAttrOmitted) &&
part.fragment === frag
) {
nextPart = i;
}
contiguous = loaded;
}
return nextPart;
}
private loadedEndOfParts(
partList: Part[],
targetBufferTime: number
): boolean {
const lastPart = partList[partList.length - 1];
return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
}
/*
This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
"sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
start and end times for each fragment in the playlist (after which this method will not need to be called).
*/
protected getInitialLiveFragment(
levelDetails: LevelDetails,
fragments: Array<Fragment>
): Fragment | null {
const fragPrevious = this.fragPrevious;
let frag: Fragment | null = null;
if (fragPrevious) {
if (levelDetails.hasProgramDateTime) {
// Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding
this.log(
`Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`
);
frag = findFragmentByPDT(
fragments,
fragPrevious.endProgramDateTime,
this.config.maxFragLookUpTolerance
);
}
if (!frag) {
// SN does not need to be accurate between renditions, but depending on the packaging it may be so.
const targetSN = (fragPrevious.sn as number) + 1;
if (
targetSN >= levelDetails.startSN &&
targetSN <= levelDetails.endSN
) {
const fragNext = fragments[targetSN - levelDetails.startSN];
// Ensure that we're staying within the continuity range, since PTS resets upon a new range
if (fragPrevious.cc === fragNext.cc) {
frag = fragNext;
this.log(
`Live playlist, switching playlist, load frag with next SN: ${
frag!.sn
}`
);
}
}
// It's important to stay within the continuity range if available; otherwise the fragments in the playlist
// will have the wrong start times
if (!frag) {
frag = findFragWithCC(fragments, fragPrevious.cc);
if (frag) {
this.log(
`Live playlist, switching playlist, load frag with same CC: ${frag.sn}`
);
}
}
}
} else {
// Find a new start fragment when fragPrevious is null
const liveStart = this.hls.liveSyncPosition;
if (liveStart !== null) {
frag = this.getFragmentAtPosition(
liveStart,
this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge,
levelDetails
);
}
}
return frag;
}
/*
This method finds the best matching fragment given the provided position.
*/
protected getFragmentAtPosition(
bufferEnd: number,
end: number,
levelDetails: LevelDetails
): Fragment | null {
const { config, fragPrevious } = this;
let { fragments, endSN } = levelDetails;
const { fragmentHint } = levelDetails;
const tolerance = config.maxFragLookUpTolerance;
const loadingParts = !!(
config.lowLatencyMode &&
levelDetails.partList &&
fragmentHint
);
if (loadingParts && fragmentHint && !this.bitrateTest) {
// Include incomplete fragment with parts at end
fragments = fragments.concat(fragmentHint);
endSN = fragmentHint.sn as number;
}
let frag;
if (bufferEnd < end) {
const lookupTolerance = bufferEnd > end - tolerance ? 0 : tolerance;
// Remove the tolerance if it would put the bufferEnd past the actual end of stream
// Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
frag = findFragmentByPTS(
fragPrevious,
fragments,
bufferEnd,
lookupTolerance
);
} else {
// reach end of playlist
frag = fragments[fragments.length - 1];
}
if (frag) {
const curSNIdx = frag.sn - levelDetails.startSN;
const sameLevel = fragPrevious && frag.level === fragPrevious.level;
const nextFrag = fragments[curSNIdx + 1];
const fragState = this.fragmentTracker.getState(frag);
if (fragState === FragmentState.BACKTRACKED) {
frag = null;
let i = curSNIdx;
while (
fragments[i] &&
this.fragmentTracker.getState(fragments[i]) ===
FragmentState.BACKTRACKED
) {
// When fragPrevious is null, backtrack to first the first fragment is not BACKTRACKED for loading
// When fragPrevious is set, we want the first BACKTRACKED fragment for parsing and buffering
if (!fragPrevious) {
frag = fragments[--i];
} else {
frag = fragments[i--];
}
}
if (!frag) {
frag = nextFrag;
}
} else if (fragPrevious && frag.sn === fragPrevious.sn && !loadingParts) {
// Force the next fragment to load if the previous one was already selected. This can occasionally happen with
// non-uniform fragment durations
if (sameLevel) {
if (
frag.sn < endSN &&
this.fragmentTracker.getState(nextFrag) !== FragmentState.OK
) {
this.log(
`SN ${frag.sn} just loaded, load next one: ${nextFrag.sn}`
);
frag = nextFrag;
} else {
frag = null;
}
}
}
}
return frag;
}
protected synchronizeToLiveEdge(levelDetails: LevelDetails) {
const { config, media } = this;
if (!media) {
return;
}
const liveSyncPosition = this.hls.liveSyncPosition;
const currentTime = media.currentTime;
const start = levelDetails.fragments[0].start;
const end = levelDetails.edge;
const withinSlidingWindow =
currentTime >= start - config.maxFragLookUpTolerance &&
currentTime <= end;
// Continue if we can seek forward to sync position or if current time is outside of sliding window
if (
liveSyncPosition !== null &&
media.duration > liveSyncPosition &&
(currentTime < liveSyncPosition || !withinSlidingWindow)
) {
// Continue if buffer is starving or if current time is behind max latency
const maxLatency =
config.liveMaxLatencyDuration !== undefined
? config.liveMaxLatencyDuration