-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathbuffer-controller.ts
executable file
·1787 lines (1666 loc) · 57.6 KB
/
buffer-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 BufferOperationQueue from './buffer-operation-queue';
import { createDoNothingErrorAction } from './error-controller';
import { ErrorDetails, ErrorTypes } from '../errors';
import { Events } from '../events';
import { ElementaryStreamTypes } from '../loader/fragment';
import { PlaylistLevelType } from '../types/loader';
import { BufferHelper } from '../utils/buffer-helper';
import {
getCodecCompatibleName,
pickMostCompleteCodecName,
} from '../utils/codecs';
import { Logger } from '../utils/logger';
import {
getMediaSource,
isCompatibleTrackChange,
isManagedMediaSource,
} from '../utils/mediasource-helper';
import type { FragmentTracker } from './fragment-tracker';
import type { HlsConfig } from '../config';
import type Hls from '../hls';
import type { MediaFragment, Part } from '../loader/fragment';
import type { LevelDetails } from '../loader/level-details';
import type {
AttachMediaSourceData,
BaseTrack,
BaseTrackSet,
BufferCreatedTrackSet,
BufferOperation,
EmptyTuple,
ExtendedSourceBuffer,
MediaOverrides,
ParsedTrack,
SourceBufferName,
SourceBuffersTuple,
SourceBufferTrack,
SourceBufferTrackSet,
} from '../types/buffer';
import type { ComponentAPI } from '../types/component-api';
import type {
BufferAppendingData,
BufferCodecsData,
BufferEOSData,
BufferFlushingData,
ErrorData,
FragChangedData,
FragParsedData,
LevelUpdatedData,
ManifestParsedData,
MediaAttachingData,
MediaDetachingData,
} from '../types/events';
import type { ChunkMetadata } from '../types/transmuxer';
interface BufferedChangeEvent extends Event {
readonly addedRanges?: TimeRanges;
readonly removedRanges?: TimeRanges;
}
const VIDEO_CODEC_PROFILE_REPLACE =
/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;
const TRACK_REMOVED_ERROR_NAME = 'HlsJsTrackRemovedError';
class HlsJsTrackRemovedError extends Error {
constructor(message) {
super(message);
this.name = TRACK_REMOVED_ERROR_NAME;
}
}
export default class BufferController extends Logger implements ComponentAPI {
private hls: Hls;
private fragmentTracker: FragmentTracker;
// The level details used to determine duration, target-duration and live
private details: LevelDetails | null = null;
// cache the self generated object url to detect hijack of video tag
private _objectUrl: string | null = null;
// A queue of buffer operations which require the SourceBuffer to not be updating upon execution
private operationQueue: BufferOperationQueue | null = null;
// The total number track codecs expected before any sourceBuffers are created (2: audio and video or 1: audiovideo | audio | video)
private bufferCodecEventsTotal: number = 0;
// A reference to the attached media element
public media: HTMLMediaElement | null = null;
// A reference to the active media source
public mediaSource: MediaSource | null = null;
// Last MP3 audio chunk appended
private lastMpegAudioChunk: ChunkMetadata | null = null;
// Audio fragment blocked from appending until corresponding video appends or context changes
private blockedAudioAppend: {
op: BufferOperation;
frag: MediaFragment | Part;
} | null = null;
// Keep track of video append position for unblocking audio
private lastVideoAppendEnd: number = 0;
// Whether or not to use ManagedMediaSource API and append source element to media element.
private appendSource: boolean;
// Transferred MediaSource information used to detmerine if duration end endstream may be appended
private transferData?: MediaAttachingData;
// Directives used to override default MediaSource handling
private overrides?: MediaOverrides;
// Error counters
private appendErrors = {
audio: 0,
video: 0,
audiovideo: 0,
};
// Record of required or created buffers by type. SourceBuffer is stored in Track.buffer once created.
private tracks: SourceBufferTrackSet = {};
// Array of SourceBuffer type and SourceBuffer (or null). One entry per TrackSet in this.tracks.
private sourceBuffers: SourceBuffersTuple = [
[null, null],
[null, null],
];
constructor(hls: Hls, fragmentTracker: FragmentTracker) {
super('buffer-controller', hls.logger);
this.hls = hls;
this.fragmentTracker = fragmentTracker;
this.appendSource = isManagedMediaSource(
getMediaSource(hls.config.preferManagedMediaSource),
);
this.initTracks();
this.registerListeners();
}
public hasSourceTypes(): boolean {
return Object.keys(this.tracks).length > 0;
}
public destroy() {
this.unregisterListeners();
this.details = null;
this.lastMpegAudioChunk = this.blockedAudioAppend = null;
this.transferData = this.overrides = undefined;
if (this.operationQueue) {
this.operationQueue.destroy();
this.operationQueue = null;
}
// @ts-ignore
this.hls = this.fragmentTracker = null;
// @ts-ignore
this._onMediaSourceOpen = this._onMediaSourceClose = null;
// @ts-ignore
this._onMediaSourceEnded = null;
// @ts-ignore
this._onStartStreaming = this._onEndStreaming = null;
}
protected registerListeners() {
const { hls } = this;
hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);
hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
hls.on(Events.BUFFER_EOS, this.onBufferEos, this);
hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
hls.on(Events.FRAG_PARSED, this.onFragParsed, this);
hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);
hls.on(Events.ERROR, this.onError, this);
}
protected unregisterListeners() {
const { hls } = this;
hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);
hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
hls.off(Events.BUFFER_EOS, this.onBufferEos, this);
hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
hls.off(Events.FRAG_PARSED, this.onFragParsed, this);
hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);
hls.off(Events.ERROR, this.onError, this);
}
public transferMedia(): AttachMediaSourceData | null {
const { media, mediaSource } = this;
if (!media) {
return null;
}
const tracks = {};
if (this.operationQueue) {
const updating = this.isUpdating();
if (!updating) {
this.operationQueue.removeBlockers();
}
const queued = this.isQueued();
if (updating || queued) {
this.warn(
`Transfering MediaSource with${queued ? ' operations in queue' : ''}${updating ? ' updating SourceBuffer(s)' : ''} ${this.operationQueue}`,
);
}
this.operationQueue.destroy();
}
const transferData = this.transferData;
if (
!this.sourceBufferCount &&
transferData &&
transferData.mediaSource === mediaSource
) {
Object.assign(tracks, transferData.tracks);
} else {
this.sourceBuffers.forEach((tuple) => {
const [type] = tuple;
if (type) {
tracks[type] = Object.assign({}, this.tracks[type]);
this.removeBuffer(type);
}
tuple[0] = tuple[1] = null;
});
}
return {
media,
mediaSource,
tracks,
};
}
private initTracks() {
const tracks = {};
this.sourceBuffers = [
[null, null],
[null, null],
];
this.tracks = tracks;
this.resetQueue();
this.resetAppendErrors();
this.lastMpegAudioChunk = this.blockedAudioAppend = null;
this.lastVideoAppendEnd = 0;
}
private onManifestLoading() {
this.bufferCodecEventsTotal = 0;
this.details = null;
}
protected onManifestParsed(
event: Events.MANIFEST_PARSED,
data: ManifestParsedData,
) {
// in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
// sourcebuffers will be created all at once when the expected nb of tracks will be reached
// in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
// it will contain the expected nb of source buffers, no need to compute it
let codecEvents: number = 2;
if ((data.audio && !data.video) || !data.altAudio || !__USE_ALT_AUDIO__) {
codecEvents = 1;
}
this.bufferCodecEventsTotal = codecEvents;
this.log(`${codecEvents} bufferCodec event(s) expected.`);
if (
this.transferData?.mediaSource &&
this.sourceBufferCount &&
codecEvents
) {
this.bufferCreated();
}
}
protected onMediaAttaching(
event: Events.MEDIA_ATTACHING,
data: MediaAttachingData,
) {
const media = (this.media = data.media);
const MediaSource = getMediaSource(this.appendSource);
this.transferData = this.overrides = undefined;
if (media && MediaSource) {
const transferringMedia = !!data.mediaSource;
if (transferringMedia || data.overrides) {
this.transferData = data;
this.overrides = data.overrides;
}
const ms = (this.mediaSource = data.mediaSource || new MediaSource());
this.assignMediaSource(ms);
if (transferringMedia) {
this._objectUrl = media.src;
this.attachTransferred();
} else {
// cache the locally generated object url
const objectUrl = (this._objectUrl = self.URL.createObjectURL(ms));
// link video and media Source
if (this.appendSource) {
try {
media.removeAttribute('src');
// ManagedMediaSource will not open without disableRemotePlayback set to false or source alternatives
const MMS = (self as any).ManagedMediaSource;
media.disableRemotePlayback =
media.disableRemotePlayback || (MMS && ms instanceof MMS);
removeSourceChildren(media);
addSource(media, objectUrl);
media.load();
} catch (error) {
media.src = objectUrl;
}
} else {
media.src = objectUrl;
}
}
media.addEventListener('emptied', this._onMediaEmptied);
}
}
private assignMediaSource(ms: MediaSource) {
this.log(
`${this.transferData?.mediaSource === ms ? 'transferred' : 'created'} media source: ${ms.constructor?.name}`,
);
// MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound
ms.addEventListener('sourceopen', this._onMediaSourceOpen);
ms.addEventListener('sourceended', this._onMediaSourceEnded);
ms.addEventListener('sourceclose', this._onMediaSourceClose);
if (this.appendSource) {
ms.addEventListener('startstreaming', this._onStartStreaming);
ms.addEventListener('endstreaming', this._onEndStreaming);
}
}
private attachTransferred() {
const media = this.media;
const data = this.transferData;
if (!data || !media) {
return;
}
const requiredTracks = this.tracks;
const transferredTracks = data.tracks;
const trackNames = transferredTracks
? Object.keys(transferredTracks)
: null;
const trackCount = trackNames ? trackNames.length : 0;
const mediaSourceOpenCallback = () => {
if (this.media && this.mediaSourceOpenOrEnded) {
this._onMediaSourceOpen();
}
};
if (transferredTracks && trackNames && trackCount) {
if (!this.tracksReady) {
// Wait for CODECS event(s)
this.hls.config.startFragPrefetch = true;
this.log(`attachTransferred: waiting for SourceBuffer track info`);
return;
}
this
.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
required tracks: ${JSON.stringify(requiredTracks, (key, value) => (key === 'initSegment' ? undefined : value))};
transfer tracks: ${JSON.stringify(transferredTracks, (key, value) => (key === 'initSegment' ? undefined : value))}}`);
if (!isCompatibleTrackChange(transferredTracks, requiredTracks)) {
// destroy attaching media source
data.mediaSource = null;
data.tracks = undefined;
const currentTime = media.currentTime;
const details = this.details;
const startTime = Math.max(
currentTime,
details?.fragments[0].start || 0,
);
if (startTime - currentTime > 1) {
this.log(
`attachTransferred: waiting for playback to reach new tracks start time ${currentTime} -> ${startTime}`,
);
return;
}
this.warn(
`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(transferredTracks)}"->"${Object.keys(requiredTracks)}") start time: ${startTime} currentTime: ${currentTime}`,
);
this.onMediaDetaching(Events.MEDIA_DETACHING, {});
this.onMediaAttaching(Events.MEDIA_ATTACHING, data);
media.currentTime = startTime;
return;
}
this.transferData = undefined;
trackNames.forEach((trackName) => {
const type = trackName as SourceBufferName;
const track = transferredTracks[type];
if (track) {
const sb = track.buffer;
if (sb) {
// Purge fragment tracker of ejected segments for existing buffer
const fragmentTracker = this.fragmentTracker;
const playlistType = track.id as PlaylistLevelType;
if (
fragmentTracker.hasFragments(playlistType) ||
fragmentTracker.hasParts(playlistType)
) {
const bufferedTimeRanges = BufferHelper.getBuffered(sb);
fragmentTracker.detectEvictedFragments(
type,
bufferedTimeRanges,
playlistType,
null,
true,
);
}
// Transfer SourceBuffer
const sbIndex = sourceBufferNameToIndex(type);
const sbTuple = [type, sb] as Exclude<
SourceBuffersTuple[typeof sbIndex],
EmptyTuple
>;
this.sourceBuffers[sbIndex] = sbTuple as any;
if (sb.updating && this.operationQueue) {
this.operationQueue.prependBlocker(type);
}
this.trackSourceBuffer(type, track);
}
}
});
mediaSourceOpenCallback();
this.bufferCreated();
} else {
this.log(`attachTransferred: MediaSource w/o SourceBuffers`);
mediaSourceOpenCallback();
}
}
private get mediaSourceOpenOrEnded(): boolean {
const readyState = this.mediaSource?.readyState;
return readyState === 'open' || readyState === 'ended';
}
private _onEndStreaming = (event) => {
if (!this.hls) {
return;
}
if (this.mediaSource?.readyState !== 'open') {
return;
}
this.hls.pauseBuffering();
};
private _onStartStreaming = (event) => {
if (!this.hls) {
return;
}
this.hls.resumeBuffering();
};
protected onMediaDetaching(
event: Events.MEDIA_DETACHING,
data: MediaDetachingData,
) {
const transferringMedia = !!data.transferMedia;
this.transferData = this.overrides = undefined;
const { media, mediaSource, _objectUrl } = this;
if (mediaSource) {
this.log(
`media source ${transferringMedia ? 'transferring' : 'detaching'}`,
);
if (transferringMedia) {
// Detach SourceBuffers without removing from MediaSource
// and leave `tracks` (required SourceBuffers configuration)
this.sourceBuffers.forEach(([type]) => {
if (type) {
this.removeBuffer(type);
}
});
this.resetQueue();
} else {
if (this.mediaSourceOpenOrEnded) {
const open = mediaSource.readyState === 'open';
try {
const sourceBuffers = mediaSource.sourceBuffers;
for (let i = sourceBuffers.length; i--; ) {
if (open) {
sourceBuffers[i].abort();
}
mediaSource.removeSourceBuffer(sourceBuffers[i]);
}
if (open) {
// endOfStream could trigger exception if any sourcebuffer is in updating state
// we don't really care about checking sourcebuffer state here,
// as we are anyway detaching the MediaSource
// let's just avoid this exception to propagate
mediaSource.endOfStream();
}
} catch (err) {
this.warn(
`onMediaDetaching: ${err.message} while calling endOfStream`,
);
}
}
// Clean up the SourceBuffers by invoking onBufferReset
if (this.sourceBufferCount) {
this.onBufferReset();
}
}
mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);
mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose);
if (this.appendSource) {
mediaSource.removeEventListener(
'startstreaming',
this._onStartStreaming,
);
mediaSource.removeEventListener('endstreaming', this._onEndStreaming);
}
this.mediaSource = null;
this._objectUrl = null;
}
// Detach properly the MediaSource from the HTMLMediaElement as
// suggested in https://github.com/w3c/media-source/issues/53.
if (media) {
media.removeEventListener('emptied', this._onMediaEmptied);
if (!transferringMedia) {
if (_objectUrl) {
self.URL.revokeObjectURL(_objectUrl);
}
// clean up video tag src only if it's our own url. some external libraries might
// hijack the video tag and change its 'src' without destroying the Hls instance first
if (this.mediaSrc === _objectUrl) {
media.removeAttribute('src');
if (this.appendSource) {
removeSourceChildren(media);
}
media.load();
} else {
this.warn(
'media|source.src was changed by a third party - skip cleanup',
);
}
}
this.media = null;
}
this.hls.trigger(Events.MEDIA_DETACHED, data);
}
protected onBufferReset() {
this.sourceBuffers.forEach(([type]) => {
if (type) {
this.resetBuffer(type);
}
});
this.initTracks();
}
private resetBuffer(type: SourceBufferName) {
const sb = this.tracks[type]?.buffer;
this.removeBuffer(type);
if (sb) {
try {
if (this.mediaSource?.sourceBuffers.length) {
this.mediaSource.removeSourceBuffer(sb);
}
} catch (err) {
this.warn(`onBufferReset ${type}`, err);
}
}
delete this.tracks[type];
}
private removeBuffer(type: SourceBufferName) {
this.removeBufferListeners(type);
this.sourceBuffers[sourceBufferNameToIndex(type)] = [null, null];
const track = this.tracks[type];
if (track) {
track.buffer = undefined;
}
}
private resetQueue() {
if (this.operationQueue) {
this.operationQueue.destroy();
}
this.operationQueue = new BufferOperationQueue(this.tracks);
}
protected onBufferCodecs(
event: Events.BUFFER_CODECS,
data: BufferCodecsData,
) {
const tracks = this.tracks;
const trackNames = Object.keys(data);
this.log(
`BUFFER_CODECS: "${trackNames}" (current SB count ${this.sourceBufferCount})`,
);
const unmuxedToMuxed =
('audiovideo' in data && (tracks.audio || tracks.video)) ||
(tracks.audiovideo && ('audio' in data || 'video' in data));
const muxedToUnmuxed =
!unmuxedToMuxed &&
this.sourceBufferCount &&
this.media &&
trackNames.some((sbName) => !tracks[sbName]);
if (unmuxedToMuxed || muxedToUnmuxed) {
this.warn(
`Unsupported transition between "${Object.keys(tracks)}" and "${trackNames}" SourceBuffers`,
);
// Do not add incompatible track ('audiovideo' <-> 'video'/'audio').
// Allow following onBufferAppending handle to trigger BUFFER_APPEND_ERROR.
// This will either be resolved by level switch or could be handled with recoverMediaError().
return;
}
trackNames.forEach((trackName: SourceBufferName) => {
const parsedTrack = data[trackName] as ParsedTrack;
const { id, codec, levelCodec, container, metadata } = parsedTrack;
let track = tracks[trackName];
const transferredTrack = this.transferData?.tracks?.[trackName];
const sbTrack = transferredTrack?.buffer ? transferredTrack : track;
const sbCodec = sbTrack?.pendingCodec || sbTrack?.codec;
const trackLevelCodec = sbTrack?.levelCodec;
const forceChangeType = !sbTrack || !!this.hls.config.assetPlayerId;
if (!track) {
track = tracks[trackName] = {
buffer: undefined,
listeners: [],
codec,
container,
levelCodec,
metadata,
id,
};
}
// check if SourceBuffer codec needs to change
const currentCodecFull = pickMostCompleteCodecName(
sbCodec,
trackLevelCodec,
);
const currentCodec = currentCodecFull?.replace(
VIDEO_CODEC_PROFILE_REPLACE,
'$1',
);
let trackCodec = pickMostCompleteCodecName(codec, levelCodec);
const nextCodec = trackCodec?.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
if (trackCodec && (currentCodec !== nextCodec || forceChangeType)) {
if (trackName.slice(0, 5) === 'audio') {
trackCodec = getCodecCompatibleName(trackCodec, this.appendSource);
}
this.log(`switching codec ${sbCodec} to ${trackCodec}`);
if (trackCodec !== (track.pendingCodec || track.codec)) {
track.pendingCodec = trackCodec;
}
track.container = container;
this.appendChangeType(trackName, container, trackCodec);
}
});
if (this.tracksReady || this.sourceBufferCount) {
data.tracks = this.sourceBufferTracks;
}
// if sourcebuffers already created, do nothing ...
if (this.sourceBufferCount) {
return;
}
if (this.mediaSourceOpenOrEnded) {
this.checkPendingTracks();
}
}
public get sourceBufferTracks(): BaseTrackSet {
return Object.keys(this.tracks).reduce((baseTracks: BaseTrackSet, type) => {
const track = this.tracks[type] as SourceBufferTrack;
baseTracks[type] = {
id: track.id,
container: track.container,
codec: track.codec,
levelCodec: track.levelCodec,
};
return baseTracks;
}, {});
}
protected appendChangeType(
type: SourceBufferName,
container: string,
codec: string,
) {
const mimeType = `${container};codecs=${codec}`;
const operation: BufferOperation = {
label: `change-type=${mimeType}`,
execute: () => {
const track = this.tracks[type];
if (track) {
const sb = track.buffer;
if (sb?.changeType) {
this.log(`changing ${type} sourceBuffer type to ${mimeType}`);
sb.changeType(mimeType);
track.codec = codec;
track.container = container;
}
}
this.shiftAndExecuteNext(type);
},
onStart: () => {},
onComplete: () => {},
onError: (error: Error) => {
this.warn(`Failed to change ${type} SourceBuffer type`, error);
},
};
this.append(operation, type, this.isPending(this.tracks[type]));
}
private blockAudio(partOrFrag: MediaFragment | Part) {
const pStart = partOrFrag.start;
const pTime = pStart + partOrFrag.duration * 0.05;
const atGap =
this.fragmentTracker.getAppendedFrag(pStart, PlaylistLevelType.MAIN)
?.gap === true;
if (atGap) {
return;
}
const op: BufferOperation = {
label: 'block-audio',
execute: () => {
const videoTrack = this.tracks.video;
if (
this.lastVideoAppendEnd > pTime ||
(videoTrack?.buffer &&
BufferHelper.isBuffered(videoTrack.buffer, pTime)) ||
this.fragmentTracker.getAppendedFrag(pTime, PlaylistLevelType.MAIN)
?.gap === true
) {
this.blockedAudioAppend = null;
this.shiftAndExecuteNext('audio');
}
},
onStart: () => {},
onComplete: () => {},
onError: (error) => {
this.warn('Error executing block-audio operation', error);
},
};
this.blockedAudioAppend = { op, frag: partOrFrag };
this.append(op, 'audio', true);
}
private unblockAudio() {
const { blockedAudioAppend, operationQueue } = this;
if (blockedAudioAppend && operationQueue) {
this.blockedAudioAppend = null;
operationQueue.unblockAudio(blockedAudioAppend.op);
}
}
protected onBufferAppending(
event: Events.BUFFER_APPENDING,
eventData: BufferAppendingData,
) {
const { tracks } = this;
const { data, type, parent, frag, part, chunkMeta } = eventData;
const chunkStats = chunkMeta.buffering[type];
const sn = frag.sn;
const bufferAppendingStart = self.performance.now();
chunkStats.start = bufferAppendingStart;
const fragBuffering = frag.stats.buffering;
const partBuffering = part ? part.stats.buffering : null;
if (fragBuffering.start === 0) {
fragBuffering.start = bufferAppendingStart;
}
if (partBuffering && partBuffering.start === 0) {
partBuffering.start = bufferAppendingStart;
}
// TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended
// Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
// in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
// is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).
// More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
const audioTrack = tracks.audio;
let checkTimestampOffset = false;
if (type === 'audio' && audioTrack?.container === 'audio/mpeg') {
checkTimestampOffset =
!this.lastMpegAudioChunk ||
chunkMeta.id === 1 ||
this.lastMpegAudioChunk.sn !== chunkMeta.sn;
this.lastMpegAudioChunk = chunkMeta;
}
// Block audio append until overlapping video append
const videoTrack = this.tracks.video;
const videoSb = videoTrack?.buffer;
if (videoSb && sn !== 'initSegment') {
const partOrFrag = part || (frag as MediaFragment);
const blockedAudioAppend = this.blockedAudioAppend;
if (type === 'audio' && parent !== 'main' && !this.blockedAudioAppend) {
const pStart = partOrFrag.start;
const pTime = pStart + partOrFrag.duration * 0.05;
const vbuffered = videoSb.buffered;
const vappending = this.currentOp('video');
if (!vbuffered.length && !vappending) {
// wait for video before appending audio
this.blockAudio(partOrFrag);
} else if (
!vappending &&
!BufferHelper.isBuffered(videoSb, pTime) &&
this.lastVideoAppendEnd < pTime
) {
// audio is ahead of video
this.blockAudio(partOrFrag);
}
} else if (type === 'video') {
const videoAppendEnd = partOrFrag.end;
if (blockedAudioAppend) {
const audioStart = blockedAudioAppend.frag.start;
if (
videoAppendEnd > audioStart ||
videoAppendEnd < this.lastVideoAppendEnd ||
BufferHelper.isBuffered(videoSb, audioStart)
) {
this.unblockAudio();
}
}
this.lastVideoAppendEnd = videoAppendEnd;
}
}
const fragStart = (part || frag).start;
const operation: BufferOperation = {
label: `append-${type}`,
execute: () => {
chunkStats.executeStart = self.performance.now();
if (checkTimestampOffset) {
const track = this.tracks[type];
if (track) {
const sb = track.buffer;
if (sb) {
const delta = fragStart - sb.timestampOffset;
if (Math.abs(delta) >= 0.1) {
this.log(
`Updating audio SourceBuffer timestampOffset to ${fragStart} (delta: ${delta}) sn: ${sn})`,
);
sb.timestampOffset = fragStart;
}
}
}
}
this.appendExecutor(data, type);
},
onStart: () => {
// logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);
},
onComplete: () => {
// logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);
const end = self.performance.now();
chunkStats.executeEnd = chunkStats.end = end;
if (fragBuffering.first === 0) {
fragBuffering.first = end;
}
if (partBuffering && partBuffering.first === 0) {
partBuffering.first = end;
}
const timeRanges = {};
this.sourceBuffers.forEach(([type, sb]) => {
if (type) {
timeRanges[type] = BufferHelper.getBuffered(sb);
}
});
this.appendErrors[type] = 0;
if (type === 'audio' || type === 'video') {
this.appendErrors.audiovideo = 0;
} else {
this.appendErrors.audio = 0;
this.appendErrors.video = 0;
}
this.hls.trigger(Events.BUFFER_APPENDED, {
type,
frag,
part,
chunkMeta,
parent: frag.type,
timeRanges,
});
},
onError: (error: Error) => {
// in case any error occured while appending, put back segment in segments table
const event: ErrorData = {
type: ErrorTypes.MEDIA_ERROR,
parent: frag.type,
details: ErrorDetails.BUFFER_APPEND_ERROR,
sourceBufferName: type,
frag,
part,
chunkMeta,
error,
err: error,
fatal: false,
};
if ((error as DOMException).code === DOMException.QUOTA_EXCEEDED_ERR) {
// QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
// let's stop appending any segments, and report BUFFER_FULL_ERROR error
event.details = ErrorDetails.BUFFER_FULL_ERROR;
} else if (
(error as DOMException).code === DOMException.INVALID_STATE_ERR &&
this.mediaSourceOpenOrEnded &&
!this.media?.error
) {
// Allow retry for "Failed to execute 'appendBuffer' on 'SourceBuffer': This SourceBuffer is still processing" errors
event.errorAction = createDoNothingErrorAction(true);
} else if (error.name === TRACK_REMOVED_ERROR_NAME) {
// Do nothing if sourceBuffers were removed (media is detached and append was not aborted)
if (this.sourceBufferCount === 0) {
event.errorAction = createDoNothingErrorAction(true);
} else {
++this.appendErrors[type];
}
} else {
const appendErrorCount = ++this.appendErrors[type];
/* with UHD content, we could get loop of quota exceeded error until
browser is able to evict some data from sourcebuffer. Retrying can help recover.
*/
this.warn(
`Failed ${appendErrorCount}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${type}" sourceBuffer`,
);
if (appendErrorCount >= this.hls.config.appendErrorMaxRetry) {
event.fatal = true;
}
}
this.hls.trigger(Events.ERROR, event);
},
};
this.append(operation, type, this.isPending(this.tracks[type]));
}
private getFlushOp(
type: SourceBufferName,
start: number,
end: number,
): BufferOperation {
this.log(`queuing "${type}" remove ${start}-${end}`);
return {
label: 'remove',
execute: () => {
this.removeExecutor(type, start, end);
},
onStart: () => {
// logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
},
onComplete: () => {
// logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
this.hls.trigger(Events.BUFFER_FLUSHED, { type });
},
onError: (error: Error) => {
this.warn(
`Failed to remove ${start}-${end} from "${type}" SourceBuffer`,
error,
);
},
};
}
protected onBufferFlushing(
event: Events.BUFFER_FLUSHING,
data: BufferFlushingData,
) {
const { type, startOffset, endOffset } = data;
if (type) {
this.append(this.getFlushOp(type, startOffset, endOffset), type);
} else {
this.sourceBuffers.forEach(([type]) => {
if (type) {
this.append(this.getFlushOp(type, startOffset, endOffset), type);
}
});
}
}
protected onFragParsed(event: Events.FRAG_PARSED, data: FragParsedData) {
const { frag, part } = data;
const buffersAppendedTo: SourceBufferName[] = [];
const elementaryStreams = part
? part.elementaryStreams
: frag.elementaryStreams;
if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {
buffersAppendedTo.push('audiovideo');
} else {
if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {
buffersAppendedTo.push('audio');
}
if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {
buffersAppendedTo.push('video');
}
}
const onUnblocked = () => {
const now = self.performance.now();
frag.stats.buffering.end = now;
if (part) {
part.stats.buffering.end = now;
}
const stats = part ? part.stats : frag.stats;
this.hls.trigger(Events.FRAG_BUFFERED, {
frag,