perf(vod): adjust hls.js to fit low bandwidth

This commit is contained in:
admin committed 2026-10-23 14:18:14 +08:00
1 parent b4fcbd38ba
commit 832a2156a5
2 files changed
+76 -11

No files matched your search

+4
View File
@@ -36,3 +36,7 @@ package-lock.json
# edge-agent
edge-agent/dist/
edge-agent/mediamtx/
#AI
.dsh
.claude
+72 -11
View File
@@ -32,6 +32,15 @@ interface VideoPlayerProps {
const SEEK_STEP_SECONDS = 5
const SPEED_OPTIONS = [0.5, 0.75, 1, 1.25, 1.5, 2] as const
// hls.js expresses every buffer target in seconds, but the unit this player
// plans in is the TS segment: the encoder writes 4s segments (backend
// `hls_segment_seconds`) and keeps six of them in the live playlist. Four
// segments ahead is the queue the player is asked to hold, and playback starts
// on the first one — it never waits for that queue to fill.
const FALLBACK_SEGMENT_SECONDS = 4
const BUFFER_SEGMENTS = 4
const INITIAL_BUFFER_SECONDS = FALLBACK_SEGMENT_SECONDS * BUFFER_SEGMENTS
function formatTime(seconds: number) {
if (!Number.isFinite(seconds)) return '00:00'
const value = Math.max(0, Math.floor(seconds))
@@ -423,32 +432,63 @@ const VideoPlayer = forwardRef<VideoPlayerHandle, VideoPlayerProps>(function Vid
setLoading(false)
onError?.('当前没有可用的播放地址')
} else if (Hls.isSupported()) {
// Buffering is the thing to avoid; chase latency only after that. hls.js
// measures latency to its own target rather than to the segment edge, so
// anything set here (liveSyncDurationCount, rate) has to be interpreted in
// its terms or the player and the UI disagree about what "behind" means.
// Buffering policy: start on the first TS, then hold a four-segment queue.
//
// Deliberately NOT enabled, all for the same reason — each pulls the target
// latency down to a single 4s segment, so playback races the encoder and
// re-buffers at the end of every segment:
// hls.js's stock defaults assume a healthy link — a 500 kbps starting
// estimate, a bitrate probe before the first real segment, and a buffer
// that fills to 60MB (30s is only the floor; at 5 Mbps the byte budget
// alone is ~96s of media). On a link that cannot sustain that prefetch,
// the backlog starves playback behind its own downloads. So the queue is
// bounded to four 4s segments — both the floor and the byte budget — and
// the first segment is requested as early as possible. The bandwidth
// estimate starts low, so a weak link gets the first picture out
// immediately and ABR climbs from measurements instead of an assumption.
// Nothing here holds playback back until the queue is full: the player
// starts on segment one and refills four segments ahead of it.
//
// The settings below are the ones to avoid, all for the same reason: each
// pulls hls.js's latency target down to a single segment, so playback
// races the encoder and re-buffers at the end of every segment. hls.js
// measures latency to its own target rather than to the segment edge, so
// any value set there has to be read in its terms:
// lowLatencyMode: true target drops to the last *partial* segment
// liveSyncDurationCount: 1 target = exactly one segment
// maxLiveSyncPlaybackRate speeds playback up to 1.5x to hold that
// backBufferLength: 0 nothing behind the playhead to survive a stall
// The default three-segment (~12s) cushion is what keeps playback smooth.
const hls = new Hls({
enableWorker: true,
// Keeps recent segments available locally, so a brief stall is served
// from the buffer instead of going back to the network.
backBufferLength: 30,
// Start four segments behind the live edge. Only published segments
// can be buffered, so at hls.js's default of three the queue tops out
// at three TS no matter what the buffer target is; four is what makes
// the four-segment queue reachable. Playback still begins on the first
// segment that loads — the rest of the queue fills while it runs.
liveSyncDurationCount: BUFFER_SEGMENTS,
// Ask for the first TS as soon as the playlist is parsed, rather than
// after the media element finishes attaching. Playback itself still
// begins with that single segment.
startFragPrefetch: true,
// Four segments of look-ahead (hls.js treats this as the floor it must
// reach). LEVEL_LOADED re-derives it, along with the byte budget that
// is the actual ceiling, from the playlist and the loaded rendition.
maxBufferLength: INITIAL_BUFFER_SECONDS,
// Start on the lightest rendition and skip the bitrate probe that would
// delay the first segment; ABR takes over once data arrives.
startLevel: 0,
testBandwidth: false,
abrEwmaDefaultEstimate: 300_000,
})
hlsRef.current = hls
hls.loadSource(source)
hls.attachMedia(video)
hls.on(Hls.Events.MANIFEST_PARSED, () => {
setLoading(false)
// For live, anchors playback to the end of the sliding window so a new
// viewer starts at the live edge instead of the oldest retained segment.
// For live, anchors playback near the end of the sliding window —
// liveSyncDurationCount segments back, so a new viewer starts close to
// the edge rather than at the oldest retained segment, while leaving the
// four-segment cushion in front of it.
hls.startLoad(live ? -1 : 0)
void attemptAutoplay(video)
})
@@ -463,6 +503,24 @@ const VideoPlayer = forwardRef<VideoPlayerHandle, VideoPlayerProps>(function Vid
// level names cannot override it. This only covers a fallback playlist whose
// rendition list we never received.
hls.on(Hls.Events.LEVEL_LOADED, (_event, data) => {
// The playlist is the authority on segment length: keep the queue at
// four segments even if the encoder was configured with a different
// `hls_segment_seconds` than the default this module starts from.
const segmentSeconds = data.details.targetduration || FALLBACK_SEGMENT_SECONDS
const bufferedAhead = segmentSeconds * BUFFER_SEGMENTS
if (hls.config.maxBufferLength !== bufferedAhead) {
hls.config.maxBufferLength = bufferedAhead
}
// `maxBufferLength` is only a floor in hls.js; the real ceiling is the
// byte budget (`maxBufferSize`), and the 60MB default buys ~96s at
// 5 Mbps — far more than four TS, and more than a slow link can
// sustain. Size that budget to exactly the four segments wanted so the
// ceiling lands on the floor. `maxMaxBufferLength` is deliberately
// left alone: hls.js lowers it itself when flush loops appear.
const bitrate = data.levelInfo.maxBitrate || data.levelInfo.bitrate
if (bitrate > 0) {
hls.config.maxBufferSize = Math.ceil((bitrate * bufferedAhead) / 8)
}
if (data.details.live && !hasQualities) onFallbackLoaded()
})
hls.on(Hls.Events.ERROR, (_event, data) => {
@@ -634,7 +692,10 @@ const VideoPlayer = forwardRef<VideoPlayerHandle, VideoPlayerProps>(function Vid
<video
ref={videoRef}
playsInline
preload="metadata"
// A replay is a single file with a known size: let the browser start
// pulling it (and therefore start the first picture sooner) instead of
// fetching metadata only. Live is fed by MSE, where preload is moot.
preload={live ? 'metadata' : 'auto'}
// While the player is muted only because autoplay demanded it, a click on
// the picture means "give me the sound", not "pause". Handling it here
// rather than with a window-level listener keeps the two in a known order: