diff --git a/packages/webui/components/compare/compare-video-pane.tsx b/packages/webui/components/compare/compare-video-pane.tsx index 1a4d9bfd..eb9a1e7b 100644 --- a/packages/webui/components/compare/compare-video-pane.tsx +++ b/packages/webui/components/compare/compare-video-pane.tsx @@ -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 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) diff --git a/packages/webui/components/viewers/use-frame-player.ts b/packages/webui/components/viewers/use-frame-player.ts index 892dd0d9..5d063e03 100644 --- a/packages/webui/components/viewers/use-frame-player.ts +++ b/packages/webui/components/viewers/use-frame-player.ts @@ -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 diff --git a/packages/webui/components/viewers/utils.test.ts b/packages/webui/components/viewers/utils.test.ts index 55ed0617..378e74c4 100644 --- a/packages/webui/components/viewers/utils.test.ts +++ b/packages/webui/components/viewers/utils.test.ts @@ -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, + ) + }) + }) +}) diff --git a/packages/webui/components/viewers/utils.ts b/packages/webui/components/viewers/utils.ts index 5dfe28e6..6a2fecd7 100644 --- a/packages/webui/components/viewers/utils.ts +++ b/packages/webui/components/viewers/utils.ts @@ -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 +} diff --git a/packages/webui/components/viewers/video-player.tsx b/packages/webui/components/viewers/video-player.tsx index 3d7d69f5..66ca7c11 100644 --- a/packages/webui/components/viewers/video-player.tsx +++ b/packages/webui/components/viewers/video-player.tsx @@ -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 = ({ 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 diff --git a/packages/webui/docs/video_player_design.md b/packages/webui/docs/video_player_design.md index f1ce82ff..4e16c026 100644 --- a/packages/webui/docs/video_player_design.md +++ b/packages/webui/docs/video_player_design.md @@ -68,6 +68,30 @@ $$\text{Time}_{\text{center}} = \left(N \cdot T_d\right) + \frac{T_d}{2} = \frac *Where $T_d = \frac{1}{\text{frameRate}}$ is the duration of a single frame.* +--- + +### D. Effective Frame Count Derivation (Container vs. Video Stream) + +The player's `totalFrames` governs the frame readout (`N / M fr`), the seekbar extent, frame-stepping bounds, and the playback clamp. It is **not** always the same as the container's frame count, because a container's duration can exceed its video stream — most commonly when the **audio track is slightly longer than the video track** (AAC padding and the fixed 1024-samples-per-frame granularity mean audio rarely ends on the exact video timestamp), or from container overhead. + +Deriving the count naively from the container duration ($\lfloor \text{containerDuration} \cdot \text{frameRate} \rceil$) invents **phantom trailing frames** the video stream does not contain. Whether those extra frames should be counted depends on whether the playhead can actually *reach* them during playback, which is governed by the same **stall threshold** used by the playback loop (§3): + +$$\text{Threshold}_{s} = \frac{\max\left(100, \frac{3000}{\text{frameRate}}\right)}{1000}\text{ seconds}$$ + +Let $\text{tail} = \text{containerDuration} - \frac{\text{dbTotalFrames}}{\text{frameRate}}$ (where `dbTotalFrames` is the video stream's `nb_frames`). Then: + +$$\text{totalFrames} = \begin{cases} +\lfloor \text{containerDuration} \cdot \text{frameRate} \rceil & \text{if tail} > \text{Threshold}_{s}\ \text{(reachable — keep the tail)} \\ +\text{dbTotalFrames} & \text{otherwise (unreachable — drop phantom frames)} \\ +\lfloor \text{containerDuration} \cdot \text{frameRate} \rceil & \text{if dbTotalFrames} \le 0\ \text{(nb\_frames missing)} +\end{cases}$$ + +* **Small tail (tail ≤ threshold):** The RAF fallback never activates (§3), so the playhead physically cannot enter the tail. Counting those frames would strand the readout short of its own maximum (e.g. a 268-frame video in a 270-frame container would show `267 / 269` and stop at 267). We therefore use the accurate video-stream count → `267 / 267`. The trailing audio still plays out to the container end on the native element; it is simply not represented as extra scrubbable frames. +* **Large tail (tail > threshold):** The playhead *does* traverse the audio-only region (the RAF fallback drives it from `video.currentTime`, §3), so the container-derived count is correct and the readout reaches its maximum at the natural end (e.g. a 150-frame video with a 6.5s audio tail shows `194 / 194`). + +This rule is implemented by `resolveTotalFrames` in `viewers/utils.ts`, which shares `stallThresholdMs` with `useFramePlayer` so the frame-count boundary and the runtime playhead-reachability boundary can never drift apart. + + --- ## 3. Active Playback Loops & Dual-Drive Coordination @@ -214,6 +238,8 @@ The extracted metadata details are saved to the `AssetMetadata` table: * `duration` (the absolute container duration, e.g. `15.42`) * `totalFrames` (the physical number of frames in the video stream, e.g. `240`) +> **Note:** `totalFrames` is always the physical **video-stream** frame count (`nb_frames`), while `duration` is the **container** duration (which can be longer, e.g. when the audio track outlasts the video). The frontend reconciles the two into an effective frame count via the rule in §2.D — it does not blindly trust either value alone. + --- ### B. Database Schema diff --git a/packages/webui/e2e/fixtures/sample-long-audio.mp4 b/packages/webui/e2e/fixtures/sample-long-audio.mp4 new file mode 100644 index 00000000..6bb1621b Binary files /dev/null and b/packages/webui/e2e/fixtures/sample-long-audio.mp4 differ diff --git a/packages/webui/e2e/harness/fixture.ts b/packages/webui/e2e/harness/fixture.ts index ad25a04a..88528926 100644 --- a/packages/webui/e2e/harness/fixture.ts +++ b/packages/webui/e2e/harness/fixture.ts @@ -48,3 +48,91 @@ export const sampleVideoAsset: AssetInfo = { }, }, } + +/** + * Metadata variant reproducing the real-world case where the container/format + * duration is LONGER than the actual video stream (audio padding / container + * overhead). This mirrors an observed asset whose ffprobe reported: + * - video stream: nb_frames=268, duration=8.9333s + * - format: duration=9.008s (~2 frames longer than the stream) + * + * Here the backing file is still the real 150-frame sample.mp4 (video stream = + * 5.0s, 150 real decodable frames), but the stored metadata reports a container + * duration of 5.075s — i.e. ~2.25 frames longer than the 150-frame stream. + * + * `metadata.totalFrames` stays at the accurate stream frame count (150, from + * ffprobe `nb_frames`), exactly as the backend stores it. + */ +export const CONTAINER_LONGER_DURATION = 5.075 + +/** + * The frame count the player's current heuristic derives from the inflated + * container duration: round(5.075 * 30) = 152, i.e. 2 frames MORE than the 150 + * frames that actually exist in the stream. Frames 150 and 151 are phantom. + */ +export const CONTAINER_LONGER_COMPUTED_TOTAL_FRAMES = Math.round( + CONTAINER_LONGER_DURATION * SAMPLE_FRAME_RATE, +) + +/** The last frame index that actually exists in the stream (0-based): 149. */ +export const REAL_LAST_FRAME = SAMPLE_TOTAL_FRAMES - 1 + +export const containerLongerVideoAsset: AssetInfo = { + ...sampleVideoAsset, + id: 'e2e-container-longer-asset', + media: { + original: { + downloadUrl: SAMPLE_VIDEO_URL, + key: 'sample.mp4', + }, + metadata: { + duration: CONTAINER_LONGER_DURATION, + originalWidth: SAMPLE_WIDTH, + originalHeight: SAMPLE_HEIGHT, + frameRate: SAMPLE_FRAME_RATE, + totalFrames: SAMPLE_TOTAL_FRAMES, + }, + }, +} + +/** + * Metadata variant for the LARGE-gap ("videoB") case: the audio track is much + * longer than the video track, so the container tail is long enough for the + * playhead to actually traverse it during playback. + * + * Backed by the real committed fixture `sample-long-audio.mp4` (verified via + * ffprobe): + * - video stream: nb_frames=150, duration=5.000s, 30fps + * - audio stream: duration=6.500s + * - format: duration=6.500s (1.5s / 45-frame tail — well above the + * ~100ms playback stall threshold) + * + * Because the tail exceeds the stall threshold, both the current code and the + * fix derive the frame count from the container duration + * (round(6.5 * 30) = 195). The playhead advances through the audio tail to the + * container end, so at natural end the readout reaches its maximum (194). + */ +export const LONG_AUDIO_VIDEO_URL = '/sample-long-audio.mp4' +export const LONG_AUDIO_DURATION = 6.5 + +/** Container-derived frame count for the long-audio fixture: round(6.5 * 30). */ +export const LONG_AUDIO_COMPUTED_TOTAL_FRAMES = Math.round(LONG_AUDIO_DURATION * SAMPLE_FRAME_RATE) + +export const longAudioVideoAsset: AssetInfo = { + ...sampleVideoAsset, + id: 'e2e-long-audio-asset', + name: 'sample-long-audio.mp4', + media: { + original: { + downloadUrl: LONG_AUDIO_VIDEO_URL, + key: 'sample-long-audio.mp4', + }, + metadata: { + duration: LONG_AUDIO_DURATION, + originalWidth: SAMPLE_WIDTH, + originalHeight: SAMPLE_HEIGHT, + frameRate: SAMPLE_FRAME_RATE, + totalFrames: SAMPLE_TOTAL_FRAMES, + }, + }, +} diff --git a/packages/webui/e2e/harness/main.tsx b/packages/webui/e2e/harness/main.tsx index 153d7f5a..4eebd19d 100644 --- a/packages/webui/e2e/harness/main.tsx +++ b/packages/webui/e2e/harness/main.tsx @@ -4,7 +4,12 @@ import type Player from 'video.js/dist/types/player' import VideoPlayer from '@/ui/components/viewers/video-player' import { calculateFrameCenterTime } from '@/ui/components/viewers/utils' import { useUiStore } from '@/ui/stores/ui' -import { SAMPLE_FRAME_RATE, sampleVideoAsset } from './fixture' +import { + SAMPLE_FRAME_RATE, + sampleVideoAsset, + containerLongerVideoAsset, + longAudioVideoAsset, +} from './fixture' /** * Backend-free harness page that mounts the *real* VideoPlayer component with a @@ -41,6 +46,23 @@ import { SAMPLE_FRAME_RATE, sampleVideoAsset } from './fixture' */ useUiStore.setState({ videoTimeDisplayMode: 'frames' }) +/** + * Select which fixture asset to mount based on the `?variant=` query param, so + * specs can exercise different metadata shapes against the same real backing + * video. Defaults to the canonical sample asset used by the other specs. + */ +function resolveAsset() { + const variant = + typeof window !== 'undefined' + ? new URLSearchParams(window.location.search).get('variant') + : null + if (variant === 'container-longer') return containerLongerVideoAsset + if (variant === 'long-audio') return longAudioVideoAsset + return sampleVideoAsset +} + +const harnessAsset = resolveAsset() + interface HarnessComment { id: string second: number @@ -110,7 +132,7 @@ function Harness(): ReactElement {
diff --git a/packages/webui/e2e/harness/serve.ts b/packages/webui/e2e/harness/serve.ts index af9c8ccf..ca3e45a0 100644 --- a/packages/webui/e2e/harness/serve.ts +++ b/packages/webui/e2e/harness/serve.ts @@ -26,6 +26,10 @@ const server = Bun.serve({ new Response(Bun.file(join(fixturesDir, 'sample.mp4')), { headers: { 'Content-Type': 'video/mp4' }, }), + '/sample-long-audio.mp4': () => + new Response(Bun.file(join(fixturesDir, 'sample-long-audio.mp4')), { + headers: { 'Content-Type': 'video/mp4' }, + }), '/': index, '/*': index, }, diff --git a/packages/webui/e2e/pages/video-player.page.ts b/packages/webui/e2e/pages/video-player.page.ts index 6a3dbf90..fa6c30b4 100644 --- a/packages/webui/e2e/pages/video-player.page.ts +++ b/packages/webui/e2e/pages/video-player.page.ts @@ -48,6 +48,16 @@ export class VideoPlayerPage { await this.waitUntilReady() } + /** + * Navigate to the harness with a specific fixture variant (see the harness + * `resolveAsset`), e.g. `'container-longer'` for the asset whose container + * duration exceeds its real video stream. + */ + async gotoVariant(variant: string): Promise { + await this.page.goto(`/?variant=${encodeURIComponent(variant)}`) + await this.waitUntilReady() + } + /** Wait until the video.js engine has metadata and a usable frame readout. */ async waitUntilReady(): Promise { await this.video.waitFor({ state: 'attached' }) @@ -92,6 +102,13 @@ export class VideoPlayerPage { return match ? Number.parseInt(match[1], 10) : Number.NaN } + /** The total frame index shown as "M" in the "N / M fr" readout. */ + async readoutTotalFrame(): Promise { + const text = (await this.timeReadout.textContent()) ?? '' + const match = text.match(/\d+\s*\/\s*(\d+)\s*fr/) + return match ? Number.parseInt(match[1], 10) : Number.NaN + } + private async seekbarFraction(): Promise { const track = await this.seekbar.boundingBox() const fill = await this.seekbarFill.boundingBox() diff --git a/packages/webui/e2e/tests/container-duration-mismatch.spec.ts b/packages/webui/e2e/tests/container-duration-mismatch.spec.ts new file mode 100644 index 00000000..4eda56d9 --- /dev/null +++ b/packages/webui/e2e/tests/container-duration-mismatch.spec.ts @@ -0,0 +1,87 @@ +import { expect, test } from '@playwright/test' +import { VideoPlayerPage } from '../pages/video-player.page' +import { REAL_LAST_FRAME, SAMPLE_TOTAL_FRAMES } from '../harness/fixture' + +/** + * Regression reproduction for the frame-count inflation bug. + * + * When an asset's container/format duration is slightly LONGER than its actual + * video stream (common: audio padding / container overhead), the player derived + * `totalFrames` from the container duration (`round(duration * fps)`) instead of + * the accurate stream frame count (`metadata.totalFrames` == ffprobe nb_frames). + * This invents phantom trailing frames that do not exist in the stream, so: + * + * - normal playback stops N frames SHORT of the displayed maximum (it can only + * reach the last real frame), and + * - frame-stepping can walk PAST the last real frame onto phantom frames. + * + * The `container-longer` fixture reports duration 5.075s while the real backing + * video is exactly 150 frames @ 30fps (5.0s stream). The buggy heuristic derives + * round(5.075*30) = 152 frames, so the readout shows "/ 151 fr" even though the + * last real (and last reachable) frame is 149. + * + * Correct behaviour (asserted below): playing to the natural end must land on + * the last displayed frame — i.e. the readout's current frame equals the + * readout's total frame, and that total equals the real last frame of the + * stream. This spec FAILS against the buggy build and PASSES once totalFrames is + * derived from the accurate stream frame count. + */ + +// Land a few frames from the real end so playing out the tail (and firing the +// native `ended` event) is fast and deterministic. +const NEAR_END_FRAME = SAMPLE_TOTAL_FRAMES - 3 + +test.beforeEach(async ({ page }) => { + // Mock every backend call so this stays a pure frontend test (mirrors the + // other player specs). Patterns are anchored to the origin root so they only + // match real backend requests, not Vite-served source modules. + await page.route(/^https?:\/\/[^/]+\/(api|files)\//, (route) => + route.fulfill({ status: 200, contentType: 'application/json', body: '{}' }), + ) +}) + +test.describe('video player container-duration mismatch', () => { + test('plays to the last real frame instead of stopping short on phantom frames', async ({ + page, + }) => { + const vp = new VideoPlayerPage(page) + await vp.gotoVariant('container-longer') + await vp.muteNativeVideo() + + // Drive the real player to its natural end. + await vp.seekToFrame(NEAR_END_FRAME) + await vp.clickPlayToggle() + await vp.waitForEnded() + + await expect.poll(() => vp.isPaused(), { timeout: 5_000 }).toBe(true) + + // Let the end-of-playback frame settle (currentTime stops moving). + await expect + .poll( + async () => { + const a = await vp.currentTime() + await vp.page.waitForTimeout(80) + const b = await vp.currentTime() + return Math.abs(b - a) < 1e-3 + }, + { timeout: 5_000 }, + ) + .toBe(true) + + const totalFrame = await vp.readoutTotalFrame() + + // The displayed total must reflect the real stream (last real frame = 149), + // not the inflated container-derived count (151). This fails under the bug. + expect(totalFrame).toBe(REAL_LAST_FRAME) + + // Core user-facing invariant: reaching the natural end lands on the last + // displayed frame — the playhead is not stranded short of the maximum. + await expect + .poll(async () => (await vp.snapshot()).readoutFrame, { timeout: 5_000 }) + .toBe(totalFrame) + + // The seekbar is visually full at the end (within tolerance). + const snap = await vp.snapshot() + expect(snap.seekbarFraction).toBeGreaterThan(0.98) + }) +}) diff --git a/packages/webui/e2e/tests/long-audio-tail.spec.ts b/packages/webui/e2e/tests/long-audio-tail.spec.ts new file mode 100644 index 00000000..c02e9932 --- /dev/null +++ b/packages/webui/e2e/tests/long-audio-tail.spec.ts @@ -0,0 +1,77 @@ +import { expect, test } from '@playwright/test' +import { VideoPlayerPage } from '../pages/video-player.page' +import { REAL_LAST_FRAME, SAMPLE_TOTAL_FRAMES } from '../harness/fixture' + +/** + * Companion to container-duration-mismatch.spec.ts, covering the LARGE-gap + * ("videoB") case: the audio track is much longer than the video track (here a + * 150-frame / 5.0s video with a 6.5s audio tail — a 1.5s tail, far above the + * ~100ms playback stall threshold). + * + * Because the tail is long enough for the RAF fallback to activate and drive the + * playhead through the audio-only region, the timeline is (correctly) derived + * from the container duration: round(6.5 * 30) = 195 frames, readout max 194. + * Playing to the natural end must advance the playhead all the way to that + * container-based maximum, and the readout must show "194 / 194". + * + * This behaviour is expected to hold BOTH before and after the frame-count fix + * (the fix only changes the small-gap case), so this spec passes on the current + * code and guards against regressing the large-gap case. + */ + +// Land a couple frames before the VIDEO track ends, so playback streams through +// the video tail and then the long audio-only tail to the natural end. +const NEAR_VIDEO_END_FRAME = SAMPLE_TOTAL_FRAMES - 3 + +test.beforeEach(async ({ page }) => { + await page.route(/^https?:\/\/[^/]+\/(api|files)\//, (route) => + route.fulfill({ status: 200, contentType: 'application/json', body: '{}' }), + ) +}) + +test.describe('video player long audio tail (large gap)', () => { + test('playhead traverses the audio tail to the container-based maximum', async ({ page }) => { + const vp = new VideoPlayerPage(page) + await vp.gotoVariant('long-audio') + await vp.muteNativeVideo() + + // The displayed total reflects the container (audio-extended) duration, not + // the shorter video track: it is well beyond the last real video frame. + const totalFrame = await vp.readoutTotalFrame() + expect(totalFrame).toBeGreaterThan(REAL_LAST_FRAME) + + // Drive the player from just before the video track ends, out through the + // audio-only tail, to the natural end of the media. + await vp.seekToFrame(NEAR_VIDEO_END_FRAME) + await vp.clickPlayToggle() + await vp.waitForEnded() + + await expect.poll(() => vp.isPaused(), { timeout: 5_000 }).toBe(true) + + // Let the end-of-playback frame settle. + await expect + .poll( + async () => { + const a = await vp.currentTime() + await vp.page.waitForTimeout(80) + const b = await vp.currentTime() + return Math.abs(b - a) < 1e-3 + }, + { timeout: 5_000 }, + ) + .toBe(true) + + // The playhead advanced past the last real video frame into the audio tail... + const snap = await vp.snapshot() + expect(snap.readoutFrame).toBeGreaterThan(REAL_LAST_FRAME) + + // ...and reached the container-based maximum at the natural end. + await expect + .poll(async () => (await vp.snapshot()).readoutFrame, { timeout: 5_000 }) + .toBe(totalFrame) + + // The seekbar is visually full at the end. + const finalSnap = await vp.snapshot() + expect(finalSnap.seekbarFraction).toBeGreaterThan(0.98) + }) +})