fix(webui): resolve video player total frames mismatch

Avoid deriving total frames from container duration when the audio tail mismatch is below the dynamic playback stall threshold. This prevents the rendering of phantom trailing frames that the playhead cannot reach during playback.

Also adds comprehensive unit and E2E tests covering both small and large audio tail gaps.
This commit is contained in:
yiling
2026-07-04 16:44:09 +08:00
parent f32f2d43aa
commit 175b5ac171
13 changed files with 489 additions and 18 deletions
@@ -9,6 +9,7 @@ import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useSta
import videojs from 'video.js'
import type Player from 'video.js/dist/types/player'
import { useFramePlayer } from '@/ui/components/viewers/use-frame-player'
import { resolveTotalFrames } from '@/ui/components/viewers/utils'
import { clampFrame as clampFrameUtil } from './compare-utils'
import type { ComparePaneHandle, DisplayTranscode, PaneReportedState } from './types'
@@ -109,12 +110,7 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
const frameRate = metadata?.frameRate || 30
const dbTotalFrames = metadata?.totalFrames || 0
const containerDuration = metadata?.duration || 0
const videoDuration = dbTotalFrames / frameRate
const frameDuration = 1 / frameRate
const totalFrames =
containerDuration - videoDuration > 0.5 * frameDuration
? Math.round(containerDuration * frameRate)
: dbTotalFrames
const totalFrames = resolveTotalFrames({ dbTotalFrames, containerDuration, frameRate })
const resolutions = computeResolutions(file)
const previewResolutions = resolutions.filter((r) => !r.isRaw)
@@ -1,5 +1,5 @@
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { calculateFrameCenterTime } from './utils'
import { calculateFrameCenterTime, stallThresholdMs } from './utils'
export interface UseFramePlayerResult {
currentFrame: number
@@ -93,7 +93,7 @@ export function useFramePlayer(
const rVfcSupported = !!videoWithCallback.requestVideoFrameCallback
// Calculate dynamic stall threshold (minimum 100ms, or 3 frames of duration)
const stallThreshold = Math.max(100, 3000 / frameRate)
const stallThreshold = stallThresholdMs(frameRate)
const sinceLastVfc = Date.now() - lastVfcTime
// Decide whether the RAF path may drive the playhead from `video.currentTime`.
@@ -168,7 +168,7 @@ export function useFramePlayer(
// can lead the on-screen frame — using it would snap the playhead forward
// past the frame the user actually paused on. Fall back to currentTime when
// rVFC is stale/unsupported (e.g. the video track ended while audio plays).
const stallThreshold = Math.max(100, 3000 / frameRate)
const stallThreshold = stallThresholdMs(frameRate)
const vfcFresh =
hasDeliveredVfc && lastMediaTime >= 0 && Date.now() - lastVfcTime <= stallThreshold
const syncTime = vfcFresh ? lastMediaTime : video.currentTime
@@ -1,5 +1,10 @@
import { describe, it, expect } from 'vitest'
import { formatTimecode, calculateFrameCenterTime } from './utils'
import {
formatTimecode,
calculateFrameCenterTime,
resolveTotalFrames,
stallThresholdMs,
} from './utils'
describe('formatTimecode tests', () => {
describe('non-drop-frame calculations', () => {
@@ -67,3 +72,96 @@ describe('formatTimecode tests', () => {
})
})
})
describe('stallThresholdMs', () => {
it('is 100ms at 30fps and 60fps (floor of 100ms dominates)', () => {
expect(stallThresholdMs(30)).toBe(100)
expect(stallThresholdMs(60)).toBe(100)
})
it('is frame-rate dependent below 30fps', () => {
// 3000 / 24 = 125ms
expect(stallThresholdMs(24)).toBe(125)
// 3000 / 25 = 120ms
expect(stallThresholdMs(25)).toBe(120)
})
it('guards against a falsy frame rate by treating it as 30fps', () => {
expect(stallThresholdMs(0)).toBe(100)
})
})
describe('resolveTotalFrames', () => {
describe('at 30fps (100ms stall threshold)', () => {
it('uses the video-stream count when there is no container tail', () => {
expect(resolveTotalFrames({ dbTotalFrames: 150, containerDuration: 5, frameRate: 30 })).toBe(
150,
)
})
it('uses the video-stream count for a sub-threshold tail (videoA / ~2 frames)', () => {
// video 268 frames = 8.9333s, container 9.008s -> 0.0747s tail (< 100ms).
// Must NOT inflate to round(9.008 * 30) = 270.
expect(
resolveTotalFrames({ dbTotalFrames: 268, containerDuration: 9.008, frameRate: 30 }),
).toBe(268)
})
it('uses the video-stream count for the container-longer e2e fixture tail', () => {
// 150 frames = 5.0s, container 5.075s -> 0.075s tail (< 100ms).
expect(
resolveTotalFrames({ dbTotalFrames: 150, containerDuration: 5.075, frameRate: 30 }),
).toBe(150)
})
it('still uses the video-stream count just below the threshold', () => {
// 300 frames = 10s, container 10.09s -> 0.09s tail (< 100ms).
expect(
resolveTotalFrames({ dbTotalFrames: 300, containerDuration: 10.09, frameRate: 30 }),
).toBe(300)
})
it('switches to the container count just above the threshold', () => {
// 300 frames = 10s, container 10.11s -> 0.11s tail (> 100ms).
// round(10.11 * 30) = 303.
expect(
resolveTotalFrames({ dbTotalFrames: 300, containerDuration: 10.11, frameRate: 30 }),
).toBe(303)
})
it('uses the container count for a large tail (videoB / long audio)', () => {
// 150 frames = 5.0s, container 6.5s -> 1.5s tail. round(6.5 * 30) = 195.
expect(
resolveTotalFrames({ dbTotalFrames: 150, containerDuration: 6.5, frameRate: 30 }),
).toBe(195)
})
})
describe('frame-rate dependence of the threshold', () => {
it('treats a 100ms tail as below threshold at 24fps (threshold 125ms)', () => {
// 240 frames = 10s, container 10.1s -> 0.1s tail (< 125ms at 24fps).
expect(
resolveTotalFrames({ dbTotalFrames: 240, containerDuration: 10.1, frameRate: 24 }),
).toBe(240)
})
it('treats a 130ms tail as above threshold at 24fps', () => {
// 240 frames = 10s, container 10.13s -> 0.13s tail (> 125ms).
// round(10.13 * 24) = 243.
expect(
resolveTotalFrames({ dbTotalFrames: 240, containerDuration: 10.13, frameRate: 24 }),
).toBe(243)
})
})
describe('missing video-stream frame count', () => {
it('falls back to the container-derived count when nb_frames is 0', () => {
expect(resolveTotalFrames({ dbTotalFrames: 0, containerDuration: 5, frameRate: 30 })).toBe(
150,
)
expect(resolveTotalFrames({ dbTotalFrames: 0, containerDuration: 6.5, frameRate: 30 })).toBe(
195,
)
})
})
})
@@ -94,3 +94,63 @@ export const calculateFrameCenterTime = (frameIndex: number, frameRate: number):
const frameDuration = 1 / frameRate
return frameIndex * frameDuration + frameDuration / 2
}
/**
* The dynamic playback stall threshold, in milliseconds: the window of
* `requestVideoFrameCallback` silence after which the playback loop's
* `requestAnimationFrame` fallback begins driving the playhead from
* `video.currentTime`.
*
* Shared by `useFramePlayer` (runtime stall detection) and `resolveTotalFrames`
* (frame-count derivation) so the two stay in lockstep: the boundary at which a
* container's audio-only tail becomes *reachable* by the playhead is exactly the
* boundary at which we start counting those tail frames.
*/
export const stallThresholdMs = (frameRate: number): number =>
Math.max(100, 3000 / (frameRate || 30))
interface ResolveTotalFramesArgs {
/**
* Physical video-stream frame count (ffprobe `nb_frames`), as stored in
* `metadata.totalFrames`.
*/
dbTotalFrames: number
/**
* Container/format duration in seconds (`metadata.duration`). May exceed the
* video-stream duration when e.g. the audio track is longer.
*/
containerDuration: number
frameRate: number
}
/**
* Derive the player's effective total frame count.
*
* A container's duration can exceed its video stream (commonly because the audio
* track is slightly longer, or from container overhead). Deriving the frame count
* from the container duration in that case invents phantom trailing frames the
* video stream does not contain.
*
* We only trust the container-derived count when the extra tail is long enough
* for the playhead to actually reach it during playback — i.e. longer than the
* playback stall threshold (see `stallThresholdMs`). Below that threshold the
* RAF fallback never activates, so those tail frames are unreachable and would
* strand the readout short of its own maximum; we use the accurate video-stream
* frame count instead.
*
* When `nb_frames` is unavailable (`dbTotalFrames <= 0`), fall back to the
* container-derived count.
*/
export const resolveTotalFrames = ({
dbTotalFrames,
containerDuration,
frameRate,
}: ResolveTotalFramesArgs): number => {
const fps = frameRate || 30
const containerFrames = Math.round(containerDuration * fps)
if (dbTotalFrames <= 0) return containerFrames
const videoDuration = dbTotalFrames / fps
const tailSeconds = containerDuration - videoDuration
const thresholdSeconds = stallThresholdMs(fps) / 1000
return tailSeconds > thresholdSeconds ? containerFrames : dbTotalFrames
}
@@ -6,6 +6,7 @@ import React, { useCallback, useEffect, useRef, useState } from 'react'
import videojs from 'video.js'
import type Player from 'video.js/dist/types/player'
import { useFramePlayer } from './use-frame-player'
import { resolveTotalFrames } from './utils'
import { VideoControlBar, type PlayerState, type DisplayTranscode } from './video-control-bar'
import type { Annotation } from '@/ui/types'
@@ -195,13 +196,8 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
const frameRate = metadata.frameRate || 30
const dbTotalFrames = metadata.totalFrames || 0
const containerDuration = metadata.duration || 0
const videoDuration = dbTotalFrames / frameRate
const frameDuration = 1 / frameRate
const totalFrames =
containerDuration - videoDuration > 0.5 * frameDuration
? Math.round(containerDuration * frameRate)
: dbTotalFrames
const totalFrames = resolveTotalFrames({ dbTotalFrames, containerDuration, frameRate })
const { currentFrame, seekToFrame } = useFramePlayer(videoRef, frameRate, totalFrames)
const currentTime = currentFrame / frameRate