feat(player): defer single tap so a double tap doesn't also toggle pause

A tap cannot be classified when it lands — it may still turn out to be
the first half of a double tap. Play/pause is therefore deferred until
the 300ms double-tap window closes, and cancelled outright if a second
tap arrives, so a double tap seeks without also toggling pause.

Forward skip moves from 10s to 30s (back stays 10s), for both double tap
and the keyboard arrows.

The timing rules live in tapGestures.ts so they are unit-testable
without mounting the player. Rapid double taps now chain off a
still-in-flight seek target instead of all resolving against the same
not-yet-updated position.

TRACES: UR-005, UR-061 | DR-092 | UT-085, UT-086, UT-087, UT-088
This commit is contained in:
2026-07-28 01:33:04 +02:00
parent e5d3cc06f2
commit d1c01a6bc3
4 changed files with 384 additions and 42 deletions
+4 -2
View File
@@ -346,10 +346,12 @@ flowchart TB
**User Interaction:** **User Interaction:**
- **Tap screen:** Controls reappear for 3 seconds - **Tap screen:** Controls reappear for 3 seconds
- **Double tap left side:** Rewind 10 seconds (shows animated feedback with "-10" indicator) - **Double tap left side:** Rewind 10 seconds (shows animated feedback with "-10" indicator)
- **Double tap right side:** Forward 10 seconds (shows animated feedback with "+10" indicator) - **Double tap right side:** Forward 30 seconds (shows animated feedback with "+30" indicator)
- **Single tap play/pause is deferred** by the 300 ms double-tap window, so a double tap
skips without also toggling pause (UR-061)
- **Swipe up/down on left side:** Adjust brightness (0.3-1.7x, shows brightness indicator with progress bar) - **Swipe up/down on left side:** Adjust brightness (0.3-1.7x, shows brightness indicator with progress bar)
- **Swipe up/down on right side:** Adjust volume (0-100%, shows volume indicator with progress bar) - **Swipe up/down on right side:** Adjust volume (0-100%, shows volume indicator with progress bar)
- **Keyboard arrows:** ← rewind 10s, → forward 10s (desktop/external keyboard) - **Keyboard arrows:** ← rewind 10s, → forward 30s (desktop/external keyboard)
- **Keyboard space/K:** Toggle play/pause - **Keyboard space/K:** Toggle play/pause
- **Keyboard F:** Toggle fullscreen - **Keyboard F:** Toggle fullscreen
- **Pinch:** Zoom (planned) - **Pinch:** Zoom (planned)
+94 -40
View File
@@ -1,4 +1,4 @@
<!-- TRACES: UR-003, UR-005, UR-020, UR-021, UR-026, UR-040 | DR-010, DR-023, DR-024, DR-051, DR-052 --> <!-- TRACES: UR-003, UR-005, UR-020, UR-021, UR-026, UR-040, UR-061 | DR-010, DR-023, DR-024, DR-051, DR-052, DR-092 -->
<script lang="ts"> <script lang="ts">
import { onMount, onDestroy, untrack } from "svelte"; import { onMount, onDestroy, untrack } from "svelte";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
@@ -20,6 +20,14 @@
import { Html5PlayerAdapter, type Html5ElementBridge } from "$lib/player/adapters"; import { Html5PlayerAdapter, type Html5ElementBridge } from "$lib/player/adapters";
import { createRustReportHost } from "$lib/player/adapters/rustReportHost"; import { createRustReportHost } from "$lib/player/adapters/rustReportHost";
import { isPipSupported, enterPip, setAutoEnterEnabled } from "$lib/utils/pictureInPicture"; import { isPipSupported, enterPip, setAutoEnterEnabled } from "$lib/utils/pictureInPicture";
import {
createTapGestureState,
registerTap,
resolveSeekTarget,
SEEK_FORWARD_SECONDS,
SEEK_BACKWARD_SECONDS,
type TapFeedback,
} from "./tapGestures";
import { import {
setBackgroundAudioEnabled, setBackgroundAudioEnabled,
subscribeAppBackgrounded, subscribeAppBackgrounded,
@@ -102,11 +110,14 @@
let touchStartX = $state(0); let touchStartX = $state(0);
let touchStartY = $state(0); let touchStartY = $state(0);
let touchStartTime = $state(0); let touchStartTime = $state(0);
let lastTapTime = $state(0); let tapGestures = createTapGestureState();
let tapTimeout: ReturnType<typeof setTimeout> | null = null; let tapTimeout: ReturnType<typeof setTimeout> | null = null;
let brightness = $state(1); // 0-2, default 1 let brightness = $state(1); // 0-2, default 1
let showDoubleTapFeedback = $state<"left" | "right" | null>(null); let showDoubleTapFeedback = $state<TapFeedback | null>(null);
let doubleTapFeedbackTimeout: ReturnType<typeof setTimeout> | null = null; let doubleTapFeedbackTimeout: ReturnType<typeof setTimeout> | null = null;
// Target of a skip already requested but not yet reported back by the player,
// so back-to-back double taps chain instead of stacking on a stale position.
let pendingSeekTarget: number | null = null;
let swipeGestureActive = $state(false); let swipeGestureActive = $state(false);
// Backend info from Rust (Rust decides which backend to use based on platform) // Backend info from Rust (Rust decides which backend to use based on platform)
@@ -703,6 +714,16 @@
if (debugLogInterval) { if (debugLogInterval) {
clearInterval(debugLogInterval); clearInterval(debugLogInterval);
} }
// A deferred single tap must not fire play/pause after teardown.
if (tapTimeout) {
clearTimeout(tapTimeout);
tapTimeout = null;
}
tapGestures.cancel();
if (doubleTapFeedbackTimeout) {
clearTimeout(doubleTapFeedbackTimeout);
doubleTapFeedbackTimeout = null;
}
// Remove native backend event listeners (incl. background-audio lifecycle subs) // Remove native backend event listeners (incl. background-audio lifecycle subs)
for (const unlisten of nativeUnlisteners) { for (const unlisten of nativeUnlisteners) {
@@ -1192,9 +1213,13 @@
function toggleBackgroundAudio() { function toggleBackgroundAudio() {
backgroundAudioOn = !backgroundAudioOn; backgroundAudioOn = !backgroundAudioOn;
console.log("[VideoPlayer] Background-audio toggle ->", backgroundAudioOn);
// Arm/disarm native background-audio mode AND flip auto-PiP the other way, // Arm/disarm native background-audio mode AND flip auto-PiP the other way,
// so exactly one background behavior is active. // so exactly one background behavior is active.
setBackgroundAudioEnabled(backgroundAudioOn); const armed = setBackgroundAudioEnabled(backgroundAudioOn);
if (!armed) {
console.warn("[VideoPlayer] Background audio NOT armed natively (no bridge)");
}
setAutoEnterEnabled(!backgroundAudioOn); setAutoEnterEnabled(!backgroundAudioOn);
} }
@@ -1342,7 +1367,16 @@
async function seekRelative(seconds: number) { async function seekRelative(seconds: number) {
isSeeking = true; isSeeking = true;
const newTime = Math.max(0, Math.min(duration, currentTime + seconds)); // The facade seeks by absolute position, so resolve the delta here —
// chaining off a still-in-flight target so rapid double taps accumulate
// instead of all resolving against the same not-yet-updated position.
const newTime = resolveSeekTarget({
delta: seconds,
reportedPosition: currentTime,
duration,
pendingTarget: pendingSeekTarget,
});
pendingSeekTarget = newTime;
console.log("[VideoPlayer] Relative seek:", { console.log("[VideoPlayer] Relative seek:", {
offset: `${seconds > 0 ? "+" : ""}${seconds}s`, offset: `${seconds > 0 ? "+" : ""}${seconds}s`,
@@ -1358,7 +1392,12 @@
} }
} as unknown as Event; } as unknown as Event;
await handleSeekBarChange(syntheticEvent); try {
await handleSeekBarChange(syntheticEvent);
} finally {
// The player is authoritative again from here on.
if (pendingSeekTarget === newTime) pendingSeekTarget = null;
}
} }
function handleKeydown(e: KeyboardEvent) { function handleKeydown(e: KeyboardEvent) {
@@ -1375,10 +1414,10 @@
} }
} else if (e.key === "ArrowLeft") { } else if (e.key === "ArrowLeft") {
e.preventDefault(); e.preventDefault();
seekRelative(-10); seekRelative(SEEK_BACKWARD_SECONDS);
} else if (e.key === "ArrowRight") { } else if (e.key === "ArrowRight") {
e.preventDefault(); e.preventDefault();
seekRelative(10); seekRelative(SEEK_FORWARD_SECONDS);
} }
} }
@@ -1389,25 +1428,31 @@
touchStartY = touch.clientY; touchStartY = touch.clientY;
touchStartTime = Date.now(); touchStartTime = Date.now();
const now = Date.now(); const outcome = registerTap(tapGestures, {
const timeSinceLastTap = now - lastTapTime; x: touch.clientX,
screenWidth: window.innerWidth,
now: Date.now(),
});
// Double tap detection (within 300ms) if (tapTimeout) {
if (timeSinceLastTap < 300 && timeSinceLastTap > 0) { clearTimeout(tapTimeout);
e.preventDefault(); tapTimeout = null;
handleDoubleTap(touch.clientX);
lastTapTime = 0; // Reset to prevent triple-tap
if (tapTimeout) {
clearTimeout(tapTimeout);
tapTimeout = null;
}
} else {
lastTapTime = now;
// Set timeout to clear if no second tap
tapTimeout = setTimeout(() => {
lastTapTime = 0;
}, 300);
} }
if (outcome.action === "seek") {
e.preventDefault();
handleDoubleTap(outcome.seekSeconds, outcome.feedback);
return;
}
// Single tap so far: defer play/pause until the double-tap window closes,
// so a double tap seeks without also toggling pause.
tapTimeout = setTimeout(() => {
tapTimeout = null;
if (tapGestures.resolvePending(Date.now())) {
togglePlayPause();
}
}, outcome.pendingAfterMs);
} }
function handleTouchMove(e: TouchEvent) { function handleTouchMove(e: TouchEvent) {
@@ -1422,6 +1467,13 @@
if (Math.abs(deltaY) > 50 && timeDelta > 50) { if (Math.abs(deltaY) > 50 && timeDelta > 50) {
swipeGestureActive = true; swipeGestureActive = true;
// This is a swipe, not a tap — drop the deferred play/pause.
tapGestures.cancel();
if (tapTimeout) {
clearTimeout(tapTimeout);
tapTimeout = null;
}
// Brightness control on vertical swipe // Brightness control on vertical swipe
swipeType = "brightness"; swipeType = "brightness";
// Map vertical swipe to brightness (0.3 to 1.7 range for better visibility) // Map vertical swipe to brightness (0.3 to 1.7 range for better visibility)
@@ -1438,19 +1490,21 @@
swipeType = null; swipeType = null;
} }
function handleDoubleTap(x: number) { /**
const screenWidth = window.innerWidth; * Mouse clicks toggle play/pause immediately. Touch taps are already handled
const isLeftSide = x < screenWidth / 2; * by `handleTouchStart` (which defers play/pause past the double-tap window),
* so the compatibility click that follows a tap must be ignored here —
* otherwise it pauses on the first tap of a double tap.
*/
function handleVideoClick(e: MouseEvent) {
// A click synthesized from a touch reports no pointer movement detail.
if (e.detail === 0 || tapTimeout !== null) return;
togglePlayPause();
}
if (isLeftSide) { function handleDoubleTap(seekSeconds: number, feedback: TapFeedback) {
// Double tap left: rewind 10 seconds seekRelative(seekSeconds);
seekRelative(-10); showDoubleTapFeedback = feedback;
showDoubleTapFeedback = "left";
} else {
// Double tap right: forward 10 seconds
seekRelative(10);
showDoubleTapFeedback = "right";
}
// Hide feedback after animation // Hide feedback after animation
if (doubleTapFeedbackTimeout) { if (doubleTapFeedbackTimeout) {
@@ -1612,7 +1666,7 @@
onwaiting={handleWaiting} onwaiting={handleWaiting}
onplaying={handlePlaying} onplaying={handlePlaying}
onloadstart={handleLoadStart} onloadstart={handleLoadStart}
onclick={togglePlayPause} onclick={handleVideoClick}
> >
<!-- Temporarily disabled to debug playback issues <!-- Temporarily disabled to debug playback issues
{#each subtitleTracks() as track} {#each subtitleTracks() as track}
@@ -1665,7 +1719,7 @@
<div class="bg-white/20 rounded-full p-6 backdrop-blur-sm"> <div class="bg-white/20 rounded-full p-6 backdrop-blur-sm">
<svg class="w-12 h-12 text-white" fill="currentColor" viewBox="0 0 24 24"> <svg class="w-12 h-12 text-white" fill="currentColor" viewBox="0 0 24 24">
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm1-13H11v6l5.25 3.15.75-1.23-4-2.42z" /> <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm1-13H11v6l5.25 3.15.75-1.23-4-2.42z" />
<text x="12" y="14" text-anchor="middle" font-size="6" fill="white" font-weight="bold">-10</text> <text x="12" y="14" text-anchor="middle" font-size="6" fill="white" font-weight="bold">{SEEK_BACKWARD_SECONDS}</text>
</svg> </svg>
</div> </div>
</div> </div>
@@ -1676,7 +1730,7 @@
<div class="bg-white/20 rounded-full p-6 backdrop-blur-sm"> <div class="bg-white/20 rounded-full p-6 backdrop-blur-sm">
<svg class="w-12 h-12 text-white" fill="currentColor" viewBox="0 0 24 24"> <svg class="w-12 h-12 text-white" fill="currentColor" viewBox="0 0 24 24">
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm1-13H11v6l5.25 3.15.75-1.23-4-2.42z" /> <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm1-13H11v6l5.25 3.15.75-1.23-4-2.42z" />
<text x="12" y="14" text-anchor="middle" font-size="6" fill="white" font-weight="bold">+10</text> <text x="12" y="14" text-anchor="middle" font-size="6" fill="white" font-weight="bold">+{SEEK_FORWARD_SECONDS}</text>
</svg> </svg>
</div> </div>
</div> </div>
@@ -0,0 +1,158 @@
import { describe, it, expect } from "vitest";
import {
DOUBLE_TAP_WINDOW_MS,
SEEK_FORWARD_SECONDS,
SEEK_BACKWARD_SECONDS,
createTapGestureState,
registerTap,
resolveSeekTarget,
} from "./tapGestures";
const SCREEN_WIDTH = 1000;
const LEFT = 100;
const RIGHT = 900;
function tap(state: ReturnType<typeof createTapGestureState>, x: number, at: number) {
return registerTap(state, { x, screenWidth: SCREEN_WIDTH, now: at });
}
/** Narrow a tap outcome to the seek variant, failing the test if it is not one. */
function asSeek(outcome: ReturnType<typeof tap>) {
if (outcome.action !== "seek") {
throw new Error(`expected a seek outcome, got "${outcome.action}"`);
}
return outcome;
}
describe("tap gesture resolution", () => {
it("defers the single-tap action until the double-tap window has elapsed", () => {
const state = createTapGestureState();
const first = tap(state, RIGHT, 1000);
// The first tap must NOT immediately toggle play/pause — it may still
// become a double tap.
expect(first).toEqual({ action: "pending", pendingAfterMs: DOUBLE_TAP_WINDOW_MS });
});
it("resolves an isolated tap to togglePlayPause once the window expires", () => {
const state = createTapGestureState();
tap(state, RIGHT, 1000);
const resolved = state.resolvePending(1000 + DOUBLE_TAP_WINDOW_MS);
expect(resolved).toEqual({ action: "togglePlayPause" });
});
it("seeks forward 30s on a double tap on the right half and never pauses", () => {
const state = createTapGestureState();
tap(state, RIGHT, 1000);
const second = asSeek(tap(state, RIGHT, 1150));
expect(second.seekSeconds).toBe(SEEK_FORWARD_SECONDS);
expect(second.seekSeconds).toBe(30);
expect(second.feedback).toBe("right");
// The deferred single-tap pause must have been cancelled.
expect(state.resolvePending(1150 + DOUBLE_TAP_WINDOW_MS)).toBeNull();
});
it("seeks back 10s on a double tap on the left half", () => {
const state = createTapGestureState();
tap(state, LEFT, 1000);
const second = asSeek(tap(state, LEFT, 1100));
expect(second.seekSeconds).toBe(SEEK_BACKWARD_SECONDS);
expect(second.seekSeconds).toBe(-10);
expect(second.feedback).toBe("left");
});
it("treats a second tap after the window as a new pending single tap", () => {
const state = createTapGestureState();
tap(state, RIGHT, 1000);
const late = tap(state, RIGHT, 1000 + DOUBLE_TAP_WINDOW_MS + 1);
expect(late.action).toBe("pending");
});
it("does not treat a third tap as another double tap", () => {
const state = createTapGestureState();
tap(state, RIGHT, 1000);
expect(tap(state, RIGHT, 1100).action).toBe("seek");
// Triple tap: the third tap starts a fresh pending tap rather than
// seeking again off the consumed second tap.
expect(tap(state, RIGHT, 1200).action).toBe("pending");
});
it("accumulates repeated double taps on the same side", () => {
const state = createTapGestureState();
tap(state, RIGHT, 1000);
const a = asSeek(tap(state, RIGHT, 1100));
tap(state, RIGHT, 1200);
const b = asSeek(tap(state, RIGHT, 1300));
expect(a.seekSeconds).toBe(30);
expect(b.seekSeconds).toBe(30);
});
it("uses the tap side, so a double tap split across halves follows the second tap", () => {
const state = createTapGestureState();
tap(state, LEFT, 1000);
const second = asSeek(tap(state, RIGHT, 1100));
expect(second.seekSeconds).toBe(SEEK_FORWARD_SECONDS);
expect(second.feedback).toBe("right");
});
it("cancel() drops a pending tap so an interpreted swipe cannot pause", () => {
const state = createTapGestureState();
tap(state, RIGHT, 1000);
state.cancel();
expect(state.resolvePending(1000 + DOUBLE_TAP_WINDOW_MS)).toBeNull();
});
});
describe("seek target resolution", () => {
const DURATION = 600;
it("adds the delta to the reported position", () => {
expect(resolveSeekTarget({ delta: 30, reportedPosition: 100, duration: DURATION })).toBe(130);
});
it("clamps to zero when rewinding past the start", () => {
expect(resolveSeekTarget({ delta: -10, reportedPosition: 4, duration: DURATION })).toBe(0);
});
it("clamps to the duration when skipping past the end", () => {
expect(resolveSeekTarget({ delta: 30, reportedPosition: 590, duration: DURATION })).toBe(DURATION);
});
it("chains off a pending target so rapid taps do not compound off a stale position", () => {
// The player has not yet reported the first seek's result, so the
// reported position is still the pre-seek value.
const first = resolveSeekTarget({ delta: 30, reportedPosition: 100, duration: DURATION });
const second = resolveSeekTarget({
delta: 30,
reportedPosition: 100,
duration: DURATION,
pendingTarget: first,
});
expect(second).toBe(160);
});
it("ignores a pending target once the player has caught up past it", () => {
const target = resolveSeekTarget({
delta: 30,
reportedPosition: 200,
duration: DURATION,
pendingTarget: 130,
});
expect(target).toBe(230);
});
it("falls back to the delta alone when duration is unknown", () => {
expect(resolveSeekTarget({ delta: 30, reportedPosition: 100, duration: 0 })).toBe(130);
});
});
+128
View File
@@ -0,0 +1,128 @@
/**
* Tap-gesture interpretation for the video player surface.
*
* Pulled out of `VideoPlayer.svelte` so the timing rules are unit-testable:
* a tap cannot be classified at the moment it lands, because it may still turn
* out to be the first half of a double tap. Play/pause is therefore *deferred*
* until the double-tap window closes, and cancelled outright if a second tap
* arrives otherwise a double tap both toggles pause and seeks.
*
* TRACES: UR-005, UR-061 | DR-092 | UT-085, UT-086, UT-087, UT-088
*/
/** A second tap within this window makes a double tap. */
export const DOUBLE_TAP_WINDOW_MS = 300;
/** Double tap on the right half: skip forward. */
export const SEEK_FORWARD_SECONDS = 30;
/** Double tap on the left half: skip back. */
export const SEEK_BACKWARD_SECONDS = -10;
export type TapFeedback = "left" | "right";
export type TapOutcome =
/** Deferred: play/pause fires only if no second tap lands within the window. */
| { action: "pending"; pendingAfterMs: number }
| { action: "seek"; seekSeconds: number; feedback: TapFeedback };
export interface TapInput {
/** Tap x position, viewport pixels. */
x: number;
screenWidth: number;
now: number;
}
export interface TapGestureState {
/**
* Resolve a still-pending single tap. Returns the play/pause action once the
* double-tap window has elapsed, or null if there is nothing pending (the tap
* became a double tap, or was cancelled).
*/
resolvePending(now: number): { action: "togglePlayPause" } | null;
/** Drop any pending tap — used when the gesture turns into a swipe. */
cancel(): void;
}
interface InternalState extends TapGestureState {
lastTapTime: number;
pendingSince: number | null;
}
export function createTapGestureState(): TapGestureState {
const state: InternalState = {
lastTapTime: 0,
pendingSince: null,
resolvePending(now: number) {
if (state.pendingSince === null) return null;
if (now - state.pendingSince < DOUBLE_TAP_WINDOW_MS) return null;
state.pendingSince = null;
return { action: "togglePlayPause" };
},
cancel() {
state.pendingSince = null;
state.lastTapTime = 0;
},
};
return state;
}
/**
* Classify a tap. The first tap of a potential pair returns `pending` the
* caller schedules `resolvePending` after `pendingAfterMs`. A second tap inside
* the window returns the seek and clears the pending play/pause.
*/
export function registerTap(state: TapGestureState, input: TapInput): TapOutcome {
const s = state as InternalState;
const sinceLastTap = input.now - s.lastTapTime;
if (s.lastTapTime > 0 && sinceLastTap > 0 && sinceLastTap < DOUBLE_TAP_WINDOW_MS) {
// Second tap: cancel the deferred play/pause and seek instead.
s.pendingSince = null;
s.lastTapTime = 0; // consumed, so a third tap starts fresh
const isLeftSide = input.x < input.screenWidth / 2;
return isLeftSide
? { action: "seek", seekSeconds: SEEK_BACKWARD_SECONDS, feedback: "left" }
: { action: "seek", seekSeconds: SEEK_FORWARD_SECONDS, feedback: "right" };
}
s.lastTapTime = input.now;
s.pendingSince = input.now;
return { action: "pending", pendingAfterMs: DOUBLE_TAP_WINDOW_MS };
}
export interface SeekTargetInput {
/** Relative offset in seconds (negative rewinds). */
delta: number;
/** Latest position reported by the player — the authoritative source. */
reportedPosition: number;
/** Media duration; 0/unknown disables the upper clamp. */
duration: number;
/**
* Target of a seek already requested but not yet reflected in
* `reportedPosition`. Consecutive double taps chain off this so they add up
* instead of all resolving against the same stale position.
*/
pendingTarget?: number | null;
}
/**
* Resolve a relative skip to the absolute position the facade expects.
*
* The player facade seeks by absolute position only (the backend picks the seek
* strategy), so the delta is applied here against the pending target when one
* is still in flight and still ahead of what the player has reported.
*/
export function resolveSeekTarget(input: SeekTargetInput): number {
const { delta, reportedPosition, duration, pendingTarget } = input;
const base =
pendingTarget != null && Math.abs(pendingTarget - reportedPosition) > 0.5 && pendingTarget > reportedPosition
? pendingTarget
: reportedPosition;
const target = base + delta;
if (target < 0) return 0;
if (duration > 0 && target > duration) return duration;
return target;
}