From 6b471663f0a3de6ee61748cd33298d5060eabd29 Mon Sep 17 00:00:00 2001 From: AAA <35992542+TNTcraftHIM@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:55:50 +0800 Subject: [PATCH] refactor(watch): one projection of a watch position and one test for a local move "Where is this playback now" was written out four times: watchPosition for a room's anchor, and three hand-written copies for a local sample, in the owner's and the viewer's look for a move the person made and in freezing a source that went away. The local samples now use watchPosition with the time they were observed as the anchor. "Did the person move it" is decided once for each observation: between two paused samples any change of position counts; otherwise a ready sample must differ from its projection by more than the provider's tolerance or the drift default. The two default tolerances have names, in seconds. One behaviour changes, in the viewer's branch. Between two paused samples the viewer compared the move with the tolerance, where the owner compared exactly. With a paused room at 10 s and a provider tolerance of 2 s, a viewer who moved to 12 s and then to 13 s was outside the room's tolerance and had made no single move larger than it, so the look treated the position as drift and could pull it back. The person is now offered Sync at 13 s, as after one large move. A paused position is exact, as the forced alignment of a paused anchor already holds. The viewer's guard for a shared seek that an iframe reports one observation late is kept: it still requires the earlier sample to have been ready, or both to be paused. Left alone: an owner publishes a first ready sample that is displaced, where a viewer's first ready sample after buffering is allowed to rejoin. No assertion settled that for the owner; a test now holds what it does. Tests: paused scrubs that add up, the owner's first ready sample and a move measured at the previous rate, a forced running alignment near a future anchor, and a source lost while paused, ended, waiting and playing. --- src/client/channel/watch-playback.ts | 36 +++++++++---------- src/client/pages/ChannelRoomPreview.tsx | 4 +-- tests/watch-playback.test.ts | 46 +++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 21 deletions(-) diff --git a/src/client/channel/watch-playback.ts b/src/client/channel/watch-playback.ts index 65accd0b9..559c220ea 100644 --- a/src/client/channel/watch-playback.ts +++ b/src/client/channel/watch-playback.ts @@ -4,10 +4,12 @@ import { watchSeekPosition, type WatchMedia, type WatchMediaPatch, type WatchMed const mediaFailure = (error?: unknown): string => error instanceof Error && error.message ? error.message : "watch_media_failed"; const HAVE_CURRENT_DATA = 2; const HAVE_FUTURE_DATA = 3; +const DRIFT_TOLERANCE_SECONDS = 0.35; +const FORCED_SEEK_TOLERANCE_SECONDS = 0.12; const unsupportedRate = Symbol("unsupported playback rate"); const retiredSource = Symbol("selected source retired"); -export function watchPosition(playback: WatchPlayback, now: number): number { +export function watchPosition(playback: Omit, now: number): number { return playback.position + (playback.paused ? 0 : Math.max(0, now - playback.anchorTime) / 1000 * playback.rate); } @@ -134,8 +136,8 @@ export class WatchPlayer { if (this.signal.aborted || (!committedPause && this.failure === retiredSource)) return; const state = committedPause ?? this.localState; if (state) { - const elapsed = state.paused || state.ended || this.ownerWaiting ? 0 : (performance.now() - this.observedAt) / 1000 * state.rate; - this.observe({ ...state, position: Math.min(state.position + elapsed, state.duration ?? Infinity), paused: true, readyState: 0, buffered: [] }); + const position = state.ended || this.ownerWaiting ? state.position : watchPosition({ ...state, anchorTime: this.observedAt }, performance.now()); + this.observe({ ...state, position: Math.min(position, state.duration ?? Infinity), paused: true, readyState: 0, buffered: [] }); } this.failure = retiredSource; this.changed(); @@ -180,14 +182,14 @@ export class WatchPlayer { this.observe(state); return { timeline: state.live ? "program" : "media", position: state.position, paused: state.paused || this.ownerWaiting || state.ended, rate: state.rate, anchorTime: Math.round((start + end) / 2 + this.offset) }; } - private observe(state: WatchMediaState): void { + private observe(state: WatchMediaState, now = performance.now()): void { if (this.signal.aborted) return; const previous = this.localState; const changed = !previous || Object.entries(state).some(([key, value]) => key !== "buffered" && previous[key as keyof WatchMediaState] !== value) || state.buffered?.length !== previous.buffered?.length || !!state.buffered?.some(([start, end], index) => start !== previous.buffered?.[index][0] || end !== previous.buffered?.[index][1]); - this.observedAt = performance.now(); + this.observedAt = now; if (!changed) return; this.localState = state; for (const listener of this.mediaListeners) listener(); @@ -244,16 +246,14 @@ export class WatchPlayer { private async alignCurrent(force: boolean, explicit: boolean): Promise { const state = await this.media.read(), now = performance.now(); if (this.failure === retiredSource) return false; - const previous = this.localState, previousAt = this.observedAt; - this.observe(state); this.observedAt = now; + const previous = this.localState, ready = state.readyState >= HAVE_FUTURE_DATA; + const driftTolerance = this.media.seekTolerance ?? DRIFT_TOLERANCE_SECONDS; + const bothPaused = previous?.paused && state.paused; + const movedLocally = this.media.seekEvents === false && previous && (bothPaused ? state.position !== previous.position + : ready && Math.abs(state.position - watchPosition({ ...previous, anchorTime: this.observedAt }, now)) > driftTolerance); + this.observe(state, now); if (this.owner) { - // Some platform players expose time but no user-seek event. Reuse this observation turn. - if (this.media.seekEvents === false && previous) { - const expected = previous.position + (previous.paused ? 0 : (now - previousAt) / 1000 * previous.rate); - const moved = state.paused && previous.paused ? state.position !== previous.position - : state.readyState >= HAVE_FUTURE_DATA && Math.abs(state.position - expected) > (this.media.seekTolerance ?? 0.35); - if (moved) void this.publish(true).catch(error => this.failMedia(error)); - } + if (movedLocally) void this.publish(true).catch(error => this.failMedia(error)); return true; } @@ -268,9 +268,8 @@ export class WatchPlayer { force = explicit || force && this.alignedPlayback !== playback; const buffered = state.buffered?.some(([start, end]) => start <= target && target < end); // A paused anchor identifies a fixed position, including one keyboard seek step. - const tolerance = force && playback.paused ? 0 : this.media.seekTolerance ?? (force ? 0.12 : 0.35); + const tolerance = !force ? driftTolerance : playback.paused ? 0 : this.media.seekTolerance ?? FORCED_SEEK_TOLERANCE_SECONDS; const displaced = Math.abs(state.position - target) > tolerance; - const ready = state.readyState >= HAVE_FUTURE_DATA; const resumed = this.stall === "waiting" && ready; if (playback.paused) this.stall = null; else if (this.stall && this.stall !== "waiting") { @@ -286,8 +285,7 @@ export class WatchPlayer { this.blockedReason = null; this.changed(); } // An iframe can report a shared seek one observation after dispatch. - if (!force && displaced && this.media.seekEvents === false && previous && (state.readyState >= HAVE_FUTURE_DATA && previous.readyState >= HAVE_FUTURE_DATA || state.paused && previous.paused) - && Math.abs(state.position - (previous.position + (previous.paused ? 0 : (now - previousAt) / 1000 * previous.rate))) > (this.media.seekTolerance ?? 0.35)) { + if (!force && displaced && movedLocally && (bothPaused || previous.readyState >= HAVE_FUTURE_DATA)) { this.blockedReason = "local-seek"; this.changed(); } const rejoin = resumed && displaced && !playback.paused && this.blockedReason !== "local-seek"; @@ -303,7 +301,7 @@ export class WatchPlayer { } if (this.error === "watch_live_position_unavailable") { this.error = null; this.changed(); } // A look that is neither a command nor a rejoin moves a viewer only inside its known buffer. - if (seekChanged || displaced && (force || rejoin || state.readyState >= HAVE_FUTURE_DATA && buffered)) patch.position = target; + if (seekChanged || displaced && (force || rejoin || ready && buffered)) patch.position = target; if (playback.paused && (!state.paused || pauseChanged)) patch.paused = true; const needsRate = state.rate !== playback.rate || force && prior && prior.rate !== playback.rate; if (needsRate && this.media.playbackRates && !this.media.playbackRates().includes(playback.rate)) { diff --git a/src/client/pages/ChannelRoomPreview.tsx b/src/client/pages/ChannelRoomPreview.tsx index e93cd5416..545909966 100644 --- a/src/client/pages/ChannelRoomPreview.tsx +++ b/src/client/pages/ChannelRoomPreview.tsx @@ -10,7 +10,7 @@ import { screenVideoSettings } from "../media/quality"; import type { ChannelController } from "../channel/types"; import type { WatchIndexedChoice, WatchMpdChoice } from "../channel/watch-page-media"; import { roomCreationPolicySchema, type ChannelRoom, type RoomCreationPolicy, type WatchActivity } from "../channel/protocol"; -import { WatchPlayer } from "../channel/watch-playback"; +import { WatchPlayer, watchPosition } from "../channel/watch-playback"; import { HTMLVideoMedia, AppPageMedia, type WatchMedia, type WatchMediaState, type WatchMediaEvent } from "../channel/watch-media"; import { useAnchoredPopover } from "../components/living/use-anchored-popover"; import { AppConnectionButton } from "../components/living/AppConnectionButton"; @@ -238,7 +238,7 @@ export function ChannelRoomPreview({ firstUse = false }: { firstUse?: boolean }) let observedAt = openedAt; const read = async (): Promise => { const now = performance.now(), elapsed = ended ? 0 : (now - openedAt) / 1000; - state = { ...state, position: state.position + (state.paused ? 0 : (now - observedAt) / 1000 * state.rate) }; + state = { ...state, position: watchPosition({ ...state, anchorTime: observedAt }, now) }; observedAt = now; return { ...state, buffered: [[sampleProgramStart + elapsed + 90, sampleProgramStart + elapsed + 120]], live: { active: !ended, seekable: [[sampleProgramStart + elapsed, sampleProgramStart + elapsed + 120]], diff --git a/tests/watch-playback.test.ts b/tests/watch-playback.test.ts index c9e0fa4fe..7c3b09d67 100644 --- a/tests/watch-playback.test.ts +++ b/tests/watch-playback.test.ts @@ -114,6 +114,26 @@ test("a player without seek events publishes an observed paused scrub on the exi } finally { player.close(); } }); +test("an owner can publish its first ready sample and measures later movement from the previous rate", async () => { + vi.useFakeTimers(); + const state: WatchMediaState = { position: 0, paused: false, rate: 2, duration: 60, readyState: 1, ended: false, buffered: null }; + const player = new WatchPlayer("room", true, { read: async () => ({ ...state }), patch: vi.fn(), ready: vi.fn(), + listen: () => () => {}, close() {}, seekEvents: false }, vi.fn()); + const publish = vi.fn(); + try { + player.calibrate(0, 0, 0); await player.ready(); player.activate(publish); + state.position = 10; state.readyState = 3; + await vi.advanceTimersByTimeAsync(1000); + expect(publish).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ position: 10 })); + state.position = 12.25; state.rate = 1; + await vi.advanceTimersByTimeAsync(1000); + expect(publish).toHaveBeenCalledOnce(); + state.position = 13.75; + await vi.advanceTimersByTimeAsync(1000); + expect(publish).toHaveBeenCalledTimes(2); + } finally { player.close(); } +}); + test("an embedded viewer resumes at the current host anchor after a hidden interval", async () => { vi.useFakeTimers();let now=0;vi.spyOn(performance,'now').mockImplementation(()=>now); const state:WatchMediaState={position:10,paused:false,rate:1,duration:120,readyState:3,buffered:null,ended:false}; @@ -181,6 +201,14 @@ test("a local iframe scrub offers explicit resynchronization without periodic se player.update({ timeline: "media", position: 10, paused: false, rate: 1, anchorTime: 6000 }); await player.serialize(async () => {}); expect(state.paused).toBe(false); + player.update({ timeline: "media", position: 10, paused: true, rate: 1, anchorTime: 6000 }); + await player.serialize(async () => {}); + state.position = 12; now += 1000; + await vi.advanceTimersByTimeAsync(1000); + expect(player.blockedReason).toBeNull(); + state.position = 13; now += 1000; + await vi.advanceTimersByTimeAsync(1000); + expect(player.blockedReason).toBe("local-seek"); }finally{player.close();} }); @@ -212,6 +240,9 @@ test("late metadata and manual autoplay retry use the latest domain anchor; soun video.currentTime = 3.2; player.update({ timeline: "media" as const, position: 3, anchorTime: 9100, paused: true, rate: 0.5 }); expect(video.currentTime).toBe(3.2); + player.update({ timeline: "media", position: 3, anchorTime: 10100, paused: false, rate: 2 }); + await player.serialize(async () => {}); + expect(video.currentTime).toBe(3); } finally { player.close(); } expect(video.src).toBe(""); expect(vi.getTimerCount()).toBe(0); @@ -647,6 +678,21 @@ test.each(["pause", "close", "play"])("waits for the selected output before firs } finally { blocker(); release(); complete?.(); media.close(); await choosing; await playbackOutput.choose(""); } }); +test.each([["paused", 10], ["ended", 10], ["waiting", 10], ["playing", 12]] as const)( + "source loss freezes %s playback within its duration", async (mode, position) => { + const clock = vi.spyOn(performance, "now").mockReturnValue(0); + const video = Object.assign(new Video(), { currentTime: 10, duration: 12, readyState: 4, paused: mode === "paused", ended: mode === "ended" }); + vi.stubGlobal("document", { createElement: () => video }); + const player = new WatchPlayer("room", true, new HTMLVideoMedia("https://media.test/video.mp4", "file"), vi.fn()); + try { + await player.ready(); + if (mode === "waiting") video.dispatchEvent(new Event("waiting")); + clock.mockReturnValue(5000); + player.sourceUnavailable(); + expect(player.mediaState).toMatchObject({ position, paused: true }); + } finally { player.close(); } + }); + test.each(['resolve', 'reject'] as const)('source retirement freezes the owned clock across a pending page read (%s)', async completion => { vi.useFakeTimers(); let now = 0, changed: (event: WatchMediaEvent) => void = () => {};