Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(web): hold early seeks at their real target until the player can reach it

Richie McIlroy5bcd8a6add44
diff --git a/apps/web/__tests__/unit/early-length.test.ts b/apps/web/__tests__/unit/early-length.test.ts
new file mode 100644
index 000000000..d75ce2be2
--- /dev/null
+++ b/apps/web/__tests__/unit/early-length.test.ts
@@ -0,0 +1,56 @@
+import { afterEach, describe, expect, it } from "vitest";
+import {
+ seekLength,
+ setFullLength,
+} from "@/app/s/[videoId]/_components/early-length";
+import { createPlaybackStore } from "@/app/s/[videoId]/_components/playback/playback-store";
+
+const fakeVideo = (duration: number) =>
+ Object.assign(new EventTarget(), {
+ currentTime: 10,
+ duration,
+ paused: true,
+ ended: false,
+ }) as unknown as HTMLVideoElement;
+
+describe("Early playback full length", () => {
+ const video = fakeVideo(44);
+ afterEach(() => setFullLength(video, null));
+
+ it("leaves the loaded duration alone without a full length", () => {
+ expect(seekLength(video, 44)).toBe(44);
+ expect(seekLength(null, 44)).toBe(44);
+ expect(seekLength(video, Number.NaN)).toBeNaN();
+ });
+
+ it("lets seeks reach the full length while it is known", () => {
+ setFullLength(video, 120);
+ expect(seekLength(video, 44)).toBe(120);
+ expect(seekLength(video, Number.NaN)).toBe(120);
+ expect(seekLength(video, 130)).toBe(130);
+ setFullLength(video, null);
+ expect(seekLength(video, 44)).toBe(44);
+ });
+
+ it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])(
+ "ignores an unusable full length (%s)",
+ (seconds) => {
+ setFullLength(video, seconds);
+ expect(seekLength(video, 44)).toBe(44);
+ },
+ );
+
+ it("passes a timeline or comment seek past the loaded part through", () => {
+ const element = fakeVideo(44);
+ const store = createPlaybackStore();
+ store.attach(element);
+ store.seek(90);
+ expect(element.currentTime).toBeCloseTo(43.999, 3);
+
+ setFullLength(element, 120);
+ store.seek(90);
+ expect(element.currentTime).toBe(90);
+ store.detach();
+ setFullLength(element, null);
+ });
+});
diff --git a/apps/web/__tests__/unit/early-playback-guard.test.ts b/apps/web/__tests__/unit/early-playback-guard.test.ts
index 4a3423bb8..af85d84d3 100644
--- a/apps/web/__tests__/unit/early-playback-guard.test.ts
+++ b/apps/web/__tests__/unit/early-playback-guard.test.ts
@@ -3,6 +3,7 @@
import { act, createElement, createRef } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { seekLength } from "@/app/s/[videoId]/_components/early-length";
import {
canResolveHold,
canSeekNow,
@@ -43,7 +44,11 @@ describe("Early playback rules", () => {
});
it("resolves a held seek once its part has uploaded and the player has it", () => {
- const base = { uploadComplete: false, playerComplete: false };
+ const base = {
+ uploadComplete: false,
+ playerComplete: false,
+ recorded: 120,
+ };
expect(canResolveHold(90, { ...base, ready: 90.5, mediaEnd: 92 })).toBe(
false,
);
@@ -75,6 +80,23 @@ describe("Early playback rules", () => {
mediaEnd: 120,
}),
).toBe(true);
+ expect(
+ canResolveHold(90, {
+ ...base,
+ playerComplete: true,
+ ready: 120,
+ mediaEnd: 44,
+ }),
+ ).toBe(false);
+ expect(
+ canResolveHold(500, {
+ ...base,
+ recorded: null,
+ playerComplete: true,
+ ready: 120,
+ mediaEnd: 120,
+ }),
+ ).toBe(false);
});
it("only reports the upload edge while waiting there during playback", () => {
@@ -276,6 +298,29 @@ describe("Early playback seek guard", () => {
expect(video.currentTime).toBeCloseTo(119.95, 5);
});
+ it("keeps a hold when the playlist ends before the element's duration does", async () => {
+ await render();
+ await act(async () => {
+ video.currentTime = 90;
+ });
+ await render(true);
+ expect(state.held).toBe(90);
+ expect(video.currentTime).toBe(0);
+ duration = 120;
+ await act(async () => {
+ video.dispatchEvent(new Event("durationchange"));
+ });
+ expect(state.held).toBe(null);
+ expect(video.currentTime).toBe(90);
+ });
+
+ it("registers the full length for clamped seek paths until complete", async () => {
+ await render();
+ expect(seekLength(video, 44)).toBe(120);
+ await render(true);
+ expect(seekLength(video, 44)).toBe(44);
+ });
+
it("stops polling once the upload is complete", async () => {
await render();
status["X-Cap-Recording-Complete"] = "1";
diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsx
index f8d461a9b..69b04ff8e 100644
--- a/apps/web/app/s/[videoId]/Share.tsx
+++ b/apps/web/app/s/[videoId]/Share.tsx
@@ -30,6 +30,7 @@ import {
} from "@/lib/video-status-query";
import { CaptionProvider } from "./_components/CaptionContext";
import { DashboardBackLink } from "./_components/DashboardBackLink";
+import { seekLength } from "./_components/early-length";
import { PlaybackProvider } from "./_components/playback/PlaybackContext";
import { ShareVideo } from "./_components/ShareVideo";
import { type ShareView, ShareViewToggle } from "./_components/ShareViewToggle";
@@ -496,8 +497,8 @@ export const Share = ({
return;
}
const seekOnce = (t: number) => {
- const dur =
- Number.isFinite(v.duration) && v.duration > 0 ? v.duration : null;
+ const length = seekLength(v, v.duration);
+ const dur = Number.isFinite(length) && length > 0 ? length : null;
const clamped = dur ? Math.max(0, Math.min(dur - 0.001, t)) : t;
try {
v.currentTime = clamped;
diff --git a/apps/web/app/s/[videoId]/_components/early-length.ts b/apps/web/app/s/[videoId]/_components/early-length.ts
new file mode 100644
index 000000000..ed0a845c2
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/early-length.ts
@@ -0,0 +1,21 @@
+// Seek paths clamp to the loaded duration. While early playback knows the
+// recording's full length they clamp to that instead, so a seek past the
+// uploaded part reaches the hold in early-playback.ts with its real target.
+const fullLengths = new WeakMap<HTMLMediaElement, number>();
+
+export function setFullLength(media: HTMLMediaElement, seconds: number | null) {
+ if (seconds !== null && Number.isFinite(seconds) && seconds > 0) {
+ fullLengths.set(media, seconds);
+ } else {
+ fullLengths.delete(media);
+ }
+}
+
+export function seekLength(
+ media: HTMLMediaElement | null | undefined,
+ duration: number,
+): number {
+ const full = media ? fullLengths.get(media) : undefined;
+ if (full === undefined) return duration;
+ return Number.isFinite(duration) && duration > full ? duration : full;
+}
diff --git a/apps/web/app/s/[videoId]/_components/early-playback.ts b/apps/web/app/s/[videoId]/_components/early-playback.ts
index f02cbfd66..77f9d6be4 100644
--- a/apps/web/app/s/[videoId]/_components/early-playback.ts
+++ b/apps/web/app/s/[videoId]/_components/early-playback.ts
@@ -1,6 +1,7 @@
"use client";
import { type RefObject, useEffect, useRef, useState } from "react";
+import { setFullLength } from "./early-length";
// The playlist only holds what has uploaded, so a seek past it is held until
// that part arrives instead of letting the browser clamp it to the end.
@@ -66,17 +67,27 @@ export function canResolveHold(
target: number,
{
ready,
+ recorded,
mediaEnd,
uploadComplete,
playerComplete,
}: {
ready: number;
+ recorded: number | null;
mediaEnd: number;
uploadComplete: boolean;
playerComplete: boolean;
},
): boolean {
- if (playerComplete) return mediaEnd > 0;
+ // The playlist can end before the element reports its final duration, so
+ // a target past the old end waits for that duration instead of landing on
+ // the old end.
+ if (playerComplete)
+ return (
+ mediaEnd > 0 &&
+ (mediaEnd >= target - 0.05 ||
+ (recorded !== null && mediaEnd >= recorded - 0.25))
+ );
if (uploadComplete) return mediaEnd >= Math.min(target + 0.25, ready - 0.05);
return ready >= target + 1 && mediaEnd >= target + 0.25;
}
@@ -133,6 +144,7 @@ export function useEarlyPlayback({
const uploadComplete = statusComplete || playerComplete;
const readyRef = useRef(0);
+ const recordedRef = useRef<number | null>(null);
const uploadCompleteRef = useRef(uploadComplete);
const playerCompleteRef = useRef(playerComplete);
const heldRef = useRef<number | null>(null);
@@ -162,7 +174,10 @@ export function useEarlyPlayback({
lastGrowthRef.current = Date.now();
setReady(status.ready);
}
- if (status.recorded !== null) setRecorded(status.recorded);
+ if (status.recorded !== null) {
+ recordedRef.current = status.recorded;
+ setRecorded(status.recorded);
+ }
if (status.uploadComplete) {
uploadCompleteRef.current = true;
setStatusComplete(true);
@@ -215,6 +230,7 @@ export function useEarlyPlayback({
if (
!canResolveHold(target, {
ready: readyRef.current,
+ recorded: recordedRef.current,
mediaEnd,
uploadComplete: uploadCompleteRef.current,
playerComplete: playerCompleteRef.current,
@@ -296,5 +312,12 @@ export function useEarlyPlayback({
};
}, [enabled, playerComplete, videoRef]);
+ useEffect(() => {
+ const video = videoRef.current;
+ if (!enabled || !video || playerComplete || recorded === null) return;
+ setFullLength(video, recorded);
+ return () => setFullLength(video, null);
+ }, [enabled, playerComplete, recorded, videoRef]);
+
return { ready, recorded, uploadComplete, held, atEdge, stalled };
}
diff --git a/apps/web/app/s/[videoId]/_components/playback/playback-store.ts b/apps/web/app/s/[videoId]/_components/playback/playback-store.ts
index d15ab69e7..e791e610e 100644
--- a/apps/web/app/s/[videoId]/_components/playback/playback-store.ts
+++ b/apps/web/app/s/[videoId]/_components/playback/playback-store.ts
@@ -1,3 +1,5 @@
+import { seekLength } from "../early-length";
+
/**
* Framework-free subscription store around the share page's `<video>` element.
*
@@ -185,7 +187,7 @@ export function createPlaybackStore(fallbackDuration: number | null = 0) {
const seek = (target: number) => {
if (!element) return;
- const total = getDuration();
+ const total = seekLength(element, getDuration());
const clamped = isFiniteDuration(total)
? Math.max(0, Math.min(total - 0.001, target))
: Math.max(0, target);
diff --git a/apps/web/app/s/[videoId]/_components/video/media-player.tsx b/apps/web/app/s/[videoId]/_components/video/media-player.tsx
index f63ba4d74..a1668b80c 100644
--- a/apps/web/app/s/[videoId]/_components/video/media-player.tsx
+++ b/apps/web/app/s/[videoId]/_components/video/media-player.tsx
@@ -59,6 +59,7 @@ import {
normalizePlaybackSpeed,
PLAYBACK_SPEEDS,
} from "@/lib/playback-speed";
+import { seekLength } from "../early-length";
import { Badge } from "./badge";
import { Button as PlayerButton } from "./button";
import {
@@ -562,7 +563,7 @@ function MediaPlayerRootImpl(props: MediaPlayerRootProps) {
dispatch({
type: MediaActionTypes.MEDIA_SEEK_REQUEST,
detail: Math.min(
- mediaElement.duration,
+ seekLength(mediaElement, mediaElement.duration),
mediaElement.currentTime + SEEK_STEP_SHORT,
),
});
@@ -700,7 +701,7 @@ function MediaPlayerRootImpl(props: MediaPlayerRootProps) {
dispatch({
type: MediaActionTypes.MEDIA_SEEK_REQUEST,
detail: Math.min(
- mediaElement.duration,
+ seekLength(mediaElement, mediaElement.duration),
mediaElement.currentTime + SEEK_STEP_LONG,
),
});
@@ -719,7 +720,8 @@ function MediaPlayerRootImpl(props: MediaPlayerRootProps) {
case "9": {
event.preventDefault();
const percent = Number.parseInt(event.key, 10) / 10;
- const seekTime = mediaElement.duration * percent;
+ const seekTime =
+ seekLength(mediaElement, mediaElement.duration) * percent;
dispatch({
type: MediaActionTypes.MEDIA_SEEK_REQUEST,
detail: seekTime,
@@ -740,7 +742,7 @@ function MediaPlayerRootImpl(props: MediaPlayerRootProps) {
event.preventDefault();
dispatch({
type: MediaActionTypes.MEDIA_SEEK_REQUEST,
- detail: mediaElement.duration,
+ detail: seekLength(mediaElement, mediaElement.duration),
});
break;
}
@@ -1530,15 +1532,25 @@ function MediaPlayerSeekForward(props: MediaPlayerSeekForwardProps) {
if (event.defaultPrevented) return;
+ const media = document.getElementById(context.mediaId);
dispatch({
type: MediaActionTypes.MEDIA_SEEK_REQUEST,
detail: Math.min(
- seekableEnd ?? Number.POSITIVE_INFINITY,
+ media instanceof HTMLMediaElement
+ ? seekLength(media, seekableEnd ?? Number.POSITIVE_INFINITY)
+ : (seekableEnd ?? Number.POSITIVE_INFINITY),
mediaCurrentTime + seconds,
),
});
},
- [dispatch, props.onClick, mediaCurrentTime, seekableEnd, seconds],
+ [
+ dispatch,
+ props.onClick,
+ mediaCurrentTime,
+ seekableEnd,
+ seconds,
+ context.mediaId,
+ ],
);
return (