Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(web): play stopped instant recordings while their last segments upload

Richie McIlroy9b18cf265f52
diff --git a/apps/web/__tests__/unit/early-playback-guard.test.ts b/apps/web/__tests__/unit/early-playback-guard.test.ts
new file mode 100644
index 000000000..4a3423bb8
--- /dev/null
+++ b/apps/web/__tests__/unit/early-playback-guard.test.ts
@@ -0,0 +1,289 @@
+// @vitest-environment jsdom
+
+import { act, createElement, createRef } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ canResolveHold,
+ canSeekNow,
+ type EarlyPlaybackState,
+ formatClock,
+ isAtUploadEdge,
+ parseEarlyPlaybackStatus,
+ useEarlyPlayback,
+} from "@/app/s/[videoId]/_components/early-playback";
+
+describe("Early playback rules", () => {
+ it("reads the status numbers only from a ready response", () => {
+ const headers = new Headers({
+ "X-Cap-Ready-Duration": "44.000",
+ "X-Cap-Recorded-Duration": "120.040",
+ "X-Cap-Recording-Complete": "0",
+ });
+ expect(parseEarlyPlaybackStatus({ status: 204, headers })).toEqual({
+ ready: 44,
+ recorded: 120.04,
+ uploadComplete: false,
+ });
+ expect(parseEarlyPlaybackStatus({ status: 202, headers })).toBe(null);
+ expect(
+ parseEarlyPlaybackStatus({
+ status: 204,
+ headers: new Headers({ "X-Cap-Ready-Duration": "nope" }),
+ }),
+ ).toEqual({ ready: null, recorded: null, uploadComplete: false });
+ });
+
+ it("lets every seek through before the duration is known or once complete", () => {
+ expect(canSeekNow(0, 0, false)).toBe(true);
+ expect(canSeekNow(90, 44, true)).toBe(true);
+ expect(canSeekNow(30, 44, false)).toBe(true);
+ expect(canSeekNow(43.99, 44, false)).toBe(false);
+ expect(canSeekNow(90, 44, false)).toBe(false);
+ });
+
+ it("resolves a held seek once its part has uploaded and the player has it", () => {
+ const base = { uploadComplete: false, playerComplete: false };
+ expect(canResolveHold(90, { ...base, ready: 90.5, mediaEnd: 92 })).toBe(
+ false,
+ );
+ expect(canResolveHold(90, { ...base, ready: 92, mediaEnd: 90.1 })).toBe(
+ false,
+ );
+ expect(canResolveHold(90, { ...base, ready: 92, mediaEnd: 92 })).toBe(true);
+ expect(
+ canResolveHold(119.8, {
+ ...base,
+ uploadComplete: true,
+ ready: 120,
+ mediaEnd: 120,
+ }),
+ ).toBe(true);
+ expect(
+ canResolveHold(119.8, {
+ ...base,
+ uploadComplete: true,
+ ready: 120,
+ mediaEnd: 100,
+ }),
+ ).toBe(false);
+ expect(
+ canResolveHold(500, {
+ ...base,
+ playerComplete: true,
+ ready: 0,
+ mediaEnd: 120,
+ }),
+ ).toBe(true);
+ });
+
+ it("only reports the upload edge while waiting there during playback", () => {
+ const edge = {
+ currentTime: 43.5,
+ mediaEnd: 44,
+ paused: false,
+ readyState: 2,
+ playerComplete: false,
+ };
+ expect(isAtUploadEdge(edge)).toBe(true);
+ expect(isAtUploadEdge({ ...edge, paused: true })).toBe(false);
+ expect(isAtUploadEdge({ ...edge, readyState: 4 })).toBe(false);
+ expect(isAtUploadEdge({ ...edge, currentTime: 30 })).toBe(false);
+ expect(isAtUploadEdge({ ...edge, playerComplete: true })).toBe(false);
+ });
+
+ it("formats clock times like the player", () => {
+ expect(formatClock(0)).toBe("0:00");
+ expect(formatClock(44.9)).toBe("0:44");
+ expect(formatClock(90)).toBe("1:30");
+ expect(formatClock(3723)).toBe("1:02:03");
+ expect(formatClock(-3)).toBe("0:00");
+ });
+});
+
+describe("Early playback seek guard", () => {
+ let container: HTMLDivElement;
+ let root: ReturnType<typeof createRoot>;
+ let video: HTMLVideoElement;
+ let duration: number;
+ let paused: boolean;
+ let status: Record<string, string>;
+ let state: EarlyPlaybackState;
+ const videoRef = createRef<HTMLVideoElement>() as {
+ current: HTMLVideoElement | null;
+ };
+
+ function Probe({ playerComplete }: { playerComplete: boolean }) {
+ state = useEarlyPlayback({
+ enabled: true,
+ statusUrl: "/api/playlist?videoType=segments-status&earlyPlayback=1",
+ playerComplete,
+ videoRef,
+ });
+ return null;
+ }
+
+ const render = (playerComplete = false) =>
+ act(async () => {
+ root.render(createElement(Probe, { playerComplete }));
+ });
+ const poll = () =>
+ act(async () => {
+ await vi.advanceTimersByTimeAsync(2_000);
+ });
+
+ beforeEach(() => {
+ vi.useFakeTimers({ shouldAdvanceTime: false });
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ status = {
+ "X-Cap-Ready-Duration": "44",
+ "X-Cap-Recorded-Duration": "120",
+ "X-Cap-Recording-Complete": "0",
+ };
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => new Response(null, { status: 204, headers: status })),
+ );
+ duration = 44;
+ paused = false;
+ video = document.createElement("video");
+ Object.defineProperty(video, "duration", { get: () => duration });
+ Object.defineProperty(video, "seekable", {
+ get: () => ({ length: 1, start: () => 0, end: () => duration }),
+ });
+ Object.defineProperty(video, "paused", { get: () => paused });
+ Object.defineProperty(video, "readyState", { get: () => 4 });
+ video.pause = vi.fn(() => {
+ paused = true;
+ });
+ video.play = vi.fn(async () => {
+ paused = false;
+ video.dispatchEvent(new Event("play"));
+ });
+ videoRef.current = video;
+ container = document.createElement("div");
+ root = createRoot(container);
+ });
+
+ afterEach(async () => {
+ await act(async () => root.unmount());
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ it("lets seeks into the uploaded part through", async () => {
+ await render();
+ video.currentTime = 30;
+ expect(video.currentTime).toBe(30);
+ expect(state.held).toBe(null);
+ expect(video.pause).not.toHaveBeenCalled();
+ });
+
+ it("holds a seek past the uploaded part, then plays it once it arrives", async () => {
+ await render();
+ video.currentTime = 20;
+ await act(async () => {
+ video.currentTime = 90;
+ });
+ expect(video.currentTime).toBe(20);
+ expect(state.held).toBe(90);
+ expect(video.pause).toHaveBeenCalledOnce();
+ expect(state.ready).toBe(44);
+ expect(state.recorded).toBe(120);
+
+ status["X-Cap-Ready-Duration"] = "92";
+ duration = 92;
+ await poll();
+ expect(state.held).toBe(null);
+ expect(video.currentTime).toBe(90);
+ expect(video.play).toHaveBeenCalledOnce();
+ });
+
+ it("keeps holding while the server has the part but the player does not", async () => {
+ await render();
+ await act(async () => {
+ video.currentTime = 90;
+ });
+ status["X-Cap-Ready-Duration"] = "92";
+ await poll();
+ expect(state.held).toBe(90);
+ duration = 92;
+ await act(async () => {
+ video.dispatchEvent(new Event("durationchange"));
+ });
+ expect(state.held).toBe(null);
+ expect(video.currentTime).toBe(90);
+ });
+
+ it("drops the hold when the viewer presses play or seeks somewhere ready", async () => {
+ await render();
+ await act(async () => {
+ video.currentTime = 90;
+ });
+ await act(async () => {
+ await video.play();
+ });
+ expect(state.held).toBe(null);
+
+ await act(async () => {
+ video.currentTime = 100;
+ });
+ expect(state.held).toBe(100);
+ await act(async () => {
+ video.currentTime = 10;
+ });
+ expect(state.held).toBe(null);
+ expect(video.currentTime).toBe(10);
+ });
+
+ it("does not resume a viewer who was paused when they seeked", async () => {
+ paused = true;
+ await render();
+ await act(async () => {
+ video.currentTime = 90;
+ });
+ status["X-Cap-Ready-Duration"] = "92";
+ duration = 92;
+ await poll();
+ expect(video.currentTime).toBe(90);
+ expect(video.play).not.toHaveBeenCalled();
+ });
+
+ it("lets the player place its start before the duration is known", async () => {
+ duration = Number.NaN;
+ await render();
+ video.currentTime = 0;
+ expect(state.held).toBe(null);
+ });
+
+ it("removes the guard once the player holds the whole recording", async () => {
+ await render();
+ expect(Object.getOwnPropertyDescriptor(video, "currentTime")).toBeDefined();
+ await render(true);
+ expect(
+ Object.getOwnPropertyDescriptor(video, "currentTime"),
+ ).toBeUndefined();
+ });
+
+ it("lands a held seek on the end when the recording ends before it", async () => {
+ await render();
+ await act(async () => {
+ video.currentTime = 200;
+ });
+ duration = 120;
+ await render(true);
+ expect(state.held).toBe(null);
+ expect(video.currentTime).toBeCloseTo(119.95, 5);
+ });
+
+ it("stops polling once the upload is complete", async () => {
+ await render();
+ status["X-Cap-Recording-Complete"] = "1";
+ await poll();
+ const calls = vi.mocked(fetch).mock.calls.length;
+ await poll();
+ await poll();
+ expect(vi.mocked(fetch).mock.calls.length).toBe(calls);
+ expect(state.uploadComplete).toBe(true);
+ });
+});
diff --git a/apps/web/__tests__/unit/early-upload-overlay.test.ts b/apps/web/__tests__/unit/early-upload-overlay.test.ts
new file mode 100644
index 000000000..11b3a1628
--- /dev/null
+++ b/apps/web/__tests__/unit/early-upload-overlay.test.ts
@@ -0,0 +1,83 @@
+// @vitest-environment jsdom
+
+import { act, createElement, createRef } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { EarlyUploadOverlay } from "@/app/s/[videoId]/_components/EarlyUploadOverlay";
+
+describe("Early upload overlay", () => {
+ let container: HTMLDivElement;
+ let root: ReturnType<typeof createRoot>;
+ const videoRef = createRef<HTMLVideoElement>() as {
+ current: HTMLVideoElement | null;
+ };
+
+ beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ const video = document.createElement("video");
+ Object.defineProperty(video, "currentTime", { value: 44, writable: true });
+ videoRef.current = video;
+ container = document.createElement("div");
+ root = createRoot(container);
+ });
+ afterEach(async () => {
+ await act(async () => root.unmount());
+ vi.unstubAllGlobals();
+ });
+
+ const render = (props: {
+ target: number | null;
+ ready: number;
+ recorded: number | null;
+ uploadComplete?: boolean;
+ stalled?: boolean;
+ }) =>
+ act(async () => {
+ root.render(
+ createElement(EarlyUploadOverlay, {
+ videoRef,
+ uploadComplete: false,
+ stalled: false,
+ ...props,
+ }),
+ );
+ });
+
+ it("names the part a held seek is waiting for, with live progress", async () => {
+ await render({ target: 90, ready: 44, recorded: 120 });
+ expect(container.textContent).toContain("1:30 is still uploading");
+ expect(container.textContent).toContain("0:44 of 2:00 uploaded");
+ });
+
+ it("says loading when the part has uploaded but the player is fetching it", async () => {
+ await render({ target: 90, ready: 95, recorded: 120 });
+ expect(container.textContent).toContain("Loading 1:30");
+ await render({ target: null, ready: 60, recorded: 120 });
+ expect(container.textContent).toContain("Loading the rest");
+ await render({
+ target: null,
+ ready: 120,
+ recorded: 120,
+ uploadComplete: true,
+ });
+ expect(container.textContent).toContain("Loading the rest");
+ });
+
+ it("explains the wait at the end of the uploaded part", async () => {
+ await render({ target: null, ready: 44.5, recorded: 120 });
+ expect(container.textContent).toContain("The rest is still uploading");
+ });
+
+ it("shows uploaded time alone when the full length is unknown", async () => {
+ await render({ target: 90, ready: 44, recorded: null });
+ expect(container.textContent).toContain("0:44 uploaded so far");
+ expect(container.textContent).not.toContain(" of ");
+ });
+
+ it("asks to keep Cap open once uploading has stalled", async () => {
+ await render({ target: 90, ready: 44, recorded: 120, stalled: true });
+ expect(container.textContent).toContain(
+ "Keep Cap open on the computer that recorded this",
+ );
+ });
+});
diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsx
index 73e15f178..f8d461a9b 100644
--- a/apps/web/app/s/[videoId]/Share.tsx
+++ b/apps/web/app/s/[videoId]/Share.tsx
@@ -195,6 +195,7 @@ interface ShareProps {
viewerId?: string | null;
isEditProcessing: boolean;
recordingStopped?: boolean;
+ earlySegmentPlayback?: boolean;
defaultPlaybackSpeed?: number;
initialAiData?: {
title?: string | null;
@@ -327,6 +328,7 @@ export const Share = ({
viewerId,
isEditProcessing,
recordingStopped = false,
+ earlySegmentPlayback = false,
defaultPlaybackSpeed,
aiGenerationAvailable,
transcriptionGenerationAvailable,
@@ -993,6 +995,7 @@ export const Share = ({
showPlaybackStatusBadge={viewerId === data.owner.id}
isEditProcessing={isEditProcessing}
recordingStopped={recordingStopped}
+ earlySegmentPlayback={earlySegmentPlayback}
defaultPlaybackSpeed={defaultPlaybackSpeed}
viewerIsOwner={viewerId === data.owner.id}
callToAction={data.callToAction}
diff --git a/apps/web/app/s/[videoId]/_components/EarlyUploadOverlay.module.css b/apps/web/app/s/[videoId]/_components/EarlyUploadOverlay.module.css
new file mode 100644
index 000000000..6e9d65be6
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/EarlyUploadOverlay.module.css
@@ -0,0 +1,205 @@
+.root {
+ position: absolute;
+ inset: 0;
+ z-index: 45;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ overflow: hidden;
+ border-radius: inherit;
+ background: #0b0b0d;
+ pointer-events: none;
+ animation-name: fade-in;
+ animation-duration: 0.22s;
+ animation-timing-function: ease-out;
+ animation-fill-mode: both;
+}
+
+.frame {
+ position: absolute;
+ inset: -8%;
+ width: 116%;
+ height: 116%;
+ filter: blur(22px) saturate(1.35) brightness(0.7);
+ transform-origin: center;
+ animation-name: breathe;
+ animation-duration: 4.8s;
+ animation-timing-function: ease-in-out;
+ animation-iteration-count: infinite;
+ animation-direction: alternate;
+}
+
+.tint {
+ position: absolute;
+ inset: 0;
+ background:
+ radial-gradient(ellipse at 50% 42%, rgb(255 255 255 / 0.1), transparent 62%),
+ linear-gradient(to top, rgb(0 0 0 / 0.45), rgb(0 0 0 / 0.1) 55%);
+}
+
+.grain {
+ position: absolute;
+ inset: -50%;
+ background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='160' height='160'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/></filter><rect width='100%' height='100%' filter='url(%23n)'/></svg>");
+ background-size: 160px 160px;
+ opacity: 0.2;
+ mix-blend-mode: overlay;
+ animation-name: grain;
+ animation-duration: 0.9s;
+ animation-timing-function: steps(5);
+ animation-iteration-count: infinite;
+}
+
+.sheen {
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(
+ 100deg,
+ transparent 30%,
+ rgb(255 255 255 / 0.14) 47%,
+ rgb(255 255 255 / 0.04) 55%,
+ transparent 70%
+ );
+ transform: translateX(-100%);
+ animation-name: sweep;
+ animation-duration: 2.6s;
+ animation-timing-function: cubic-bezier(0.45, 0.05, 0.25, 1);
+ animation-iteration-count: infinite;
+}
+
+.content {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 10px;
+ padding: 0 24px;
+ text-align: center;
+ color: #fff;
+}
+
+.title {
+ margin: 0;
+ font-size: clamp(14px, 2.2vw, 18px);
+ font-weight: 500;
+ letter-spacing: -0.01em;
+ background: linear-gradient(
+ 90deg,
+ rgb(255 255 255 / 0.6) 0%,
+ #fff 50%,
+ rgb(255 255 255 / 0.6) 100%
+ );
+ background-size: 200% 100%;
+ -webkit-background-clip: text;
+ background-clip: text;
+ color: transparent;
+ animation-name: text-shimmer;
+ animation-duration: 2.4s;
+ animation-timing-function: linear;
+ animation-iteration-count: infinite;
+}
+
+.detail {
+ margin: 0;
+ font-size: clamp(12px, 1.6vw, 14px);
+ color: rgb(255 255 255 / 0.72);
+ font-variant-numeric: tabular-nums;
+}
+
+.bar {
+ width: min(200px, 50vw);
+ height: 3px;
+ border-radius: 999px;
+ background: rgb(255 255 255 / 0.18);
+ overflow: hidden;
+}
+
+.barFill {
+ width: 100%;
+ height: 100%;
+ border-radius: inherit;
+ background: rgb(255 255 255 / 0.9);
+ transform-origin: left center;
+ transition: transform 0.7s cubic-bezier(0.22, 1, 0.36, 1);
+}
+
+.hint {
+ margin: 2px 0 0;
+ max-width: 320px;
+ font-size: 12px;
+ line-height: 1.45;
+ color: rgb(255 255 255 / 0.6);
+}
+
+@keyframes fade-in {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+}
+
+@keyframes breathe {
+ from {
+ transform: scale(1);
+ }
+ to {
+ transform: scale(1.06);
+ }
+}
+
+@keyframes grain {
+ 0% {
+ transform: translate(0, 0);
+ }
+ 20% {
+ transform: translate(-8%, 6%);
+ }
+ 40% {
+ transform: translate(7%, -9%);
+ }
+ 60% {
+ transform: translate(-5%, -4%);
+ }
+ 80% {
+ transform: translate(9%, 8%);
+ }
+ 100% {
+ transform: translate(0, 0);
+ }
+}
+
+@keyframes sweep {
+ from {
+ transform: translateX(-100%);
+ }
+ to {
+ transform: translateX(100%);
+ }
+}
+
+@keyframes text-shimmer {
+ from {
+ background-position: 100% 0;
+ }
+ to {
+ background-position: -100% 0;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .root,
+ .frame,
+ .grain,
+ .sheen,
+ .title {
+ animation: none;
+ }
+ .sheen {
+ display: none;
+ }
+ .barFill {
+ transition: none;
+ }
+}
diff --git a/apps/web/app/s/[videoId]/_components/EarlyUploadOverlay.tsx b/apps/web/app/s/[videoId]/_components/EarlyUploadOverlay.tsx
new file mode 100644
index 000000000..1bb42214d
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/EarlyUploadOverlay.tsx
@@ -0,0 +1,127 @@
+"use client";
+
+import { type RefObject, useEffect, useRef, useState } from "react";
+import styles from "./EarlyUploadOverlay.module.css";
+import { formatClock } from "./early-playback";
+
+const FRAME_WIDTH = 48;
+
+/** Counts up to `value` (whole seconds) instead of jumping between polls. */
+function useCountUp(value: number): number {
+ const [shown, setShown] = useState(Math.floor(value));
+ const currentRef = useRef(value);
+ useEffect(() => {
+ const start = currentRef.current;
+ const delta = value - start;
+ if (delta <= 0) {
+ currentRef.current = value;
+ setShown(Math.floor(value));
+ return;
+ }
+ const began = performance.now();
+ const duration = Math.min(1800, 400 + delta * 120);
+ let frame = 0;
+ const step = (now: number) => {
+ const progress = Math.min(1, (now - began) / duration);
+ const next = start + delta * (1 - (1 - progress) ** 3);
+ currentRef.current = next;
+ setShown(Math.floor(next));
+ if (progress < 1) frame = requestAnimationFrame(step);
+ };
+ frame = requestAnimationFrame(step);
+ return () => cancelAnimationFrame(frame);
+ }, [value]);
+ return shown;
+}
+
+/**
+ * Shown over an early-playback recording when a seek or playback reaches a
+ * part that hasn't uploaded yet. The paused frame is drawn once into a tiny
+ * canvas and scaled up, so the blur costs nothing per frame; the grain and
+ * sheen only move layers.
+ */
+export function EarlyUploadOverlay({
+ videoRef,
+ target,
+ ready,
+ recorded,
+ uploadComplete,
+ stalled,
+}: {
+ videoRef: RefObject<HTMLVideoElement | null>;
+ target: number | null;
+ ready: number;
+ recorded: number | null;
+ /** Everything has uploaded and the player is fetching the last part. */
+ uploadComplete: boolean;
+ stalled: boolean;
+}) {
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const shown = useCountUp(ready);
+
+ useEffect(() => {
+ const video = videoRef.current;
+ const canvas = canvasRef.current;
+ if (!video || !canvas || video.readyState < 2) return;
+ const height =
+ video.videoWidth > 0
+ ? Math.max(
+ 1,
+ Math.round((FRAME_WIDTH * video.videoHeight) / video.videoWidth),
+ )
+ : 27;
+ canvas.width = FRAME_WIDTH;
+ canvas.height = height;
+ try {
+ canvas.getContext("2d")?.drawImage(video, 0, 0, FRAME_WIDTH, height);
+ } catch {}
+ }, [videoRef]);
+
+ // The server can be a playlist refresh ahead of the player, so a part it
+ // already has is loading, not uploading.
+ const waitingAt = target ?? videoRef.current?.currentTime ?? 0;
+ const isLoading = uploadComplete || waitingAt + 1 <= ready;
+ const title =
+ target === null
+ ? isLoading
+ ? "Loading the rest"
+ : "The rest is still uploading"
+ : isLoading
+ ? `Loading ${formatClock(target)}`
+ : `${formatClock(target)} is still uploading`;
+ const total = recorded !== null && recorded > 0 ? recorded : null;
+ const shownSeconds = total === null ? shown : Math.min(shown, total);
+
+ return (
+ <div className={styles.root} data-slot="early-upload-overlay">
+ <canvas ref={canvasRef} className={styles.frame} aria-hidden />
+ <div className={styles.tint} aria-hidden />
+ <div className={styles.grain} aria-hidden />
+ <div className={styles.sheen} aria-hidden />
+ <div className={styles.content} role="status" aria-live="polite">
+ <p className={styles.title}>{title}</p>
+ <p className={styles.detail}>
+ {total === null
+ ? `${formatClock(shownSeconds)} uploaded so far`
+ : `${formatClock(shownSeconds)} of ${formatClock(total)} uploaded`}
+ </p>
+ {total !== null && (
+ <div className={styles.bar} aria-hidden>
+ <div
+ className={styles.barFill}
+ style={{
+ transform: `scaleX(${Math.min(1, Math.max(0, ready / total))})`,
+ }}
+ />
+ </div>
+ )}
+ {stalled && (
+ <p className={styles.hint}>
+ Keep Cap open on the computer that recorded this so the rest can
+ upload.
+ </p>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/app/s/[videoId]/_components/HLSVideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/HLSVideoPlayer.tsx
index 1917ddb3c..c0401120a 100644
--- a/apps/web/app/s/[videoId]/_components/HLSVideoPlayer.tsx
+++ b/apps/web/app/s/[videoId]/_components/HLSVideoPlayer.tsx
@@ -20,6 +20,8 @@ import type { ShareCallToAction } from "@/lib/share-call-to-action";
import { CallToActionOverlay } from "./call-to-action/CallToActionOverlay";
import { bindCaptionTrackCueText } from "./caption-tracks";
import { scheduleReadyRefresh } from "./deferred-ready-refresh";
+import { EarlyUploadOverlay } from "./EarlyUploadOverlay";
+import { useEarlyPlayback } from "./early-playback";
import { waitForSegmentPlayback } from "./segment-playback-probe";
import {
canRetryFailedProcessing,
@@ -106,6 +108,11 @@ interface Props {
hasActiveUpload?: boolean;
isLiveSegments?: boolean;
allowSegmentProbeDuringUpload?: boolean;
+ /**
+ * Plays a stopped recording from its first segment while the playlist is
+ * still growing, instead of waiting for the last segments to upload.
+ */
+ earlyPlayback?: boolean;
onSourceComplete?: () => void;
enhancedAudioUrl?: string | null;
enhancedAudioStatus?: EnhancedAudioStatus | null;
@@ -140,6 +147,7 @@ export function HLSVideoPlayer({
hasActiveUpload,
isLiveSegments = false,
allowSegmentProbeDuringUpload = false,
+ earlyPlayback = false,
onSourceComplete,
disableCaptions,
captionsInitiallyOff = false,
@@ -169,6 +177,7 @@ export function HLSVideoPlayer({
"incomplete" | "unavailable" | null
>(null);
const [hasPlayedOnce, setHasPlayedOnce] = useState(false);
+ const [earlyPlaylistEnded, setEarlyPlaylistEnded] = useState(false);
const hasPlayedOnceRef = useRef(false);
const videoLoadedRef = useRef(false);
const playbackStartedAtRef = useRef<number | null>(null);
@@ -184,12 +193,21 @@ export function HLSVideoPlayer({
const segmentRetryCountRef = useRef(0);
const hasTriedRouterRefreshRef = useRef(false);
const isBackgroundPreview = previewMode === "background";
+ // Native HLS players end a growing playlist when playback catches up with
+ // its last segment, so early playback is limited to hls.js and everything
+ // else keeps waiting for the complete recording.
+ const isEarlyPlayback =
+ earlyPlayback && typeof window !== "undefined" && Hls.isSupported();
+ const sourceSrc =
+ earlyPlayback && !isEarlyPlayback
+ ? videoSrc.replace("earlyPlayback=1", "requireComplete=1")
+ : videoSrc;
const playbackSrc =
sourceVersion === 0
- ? videoSrc
- : videoSrc.includes("?")
- ? `${videoSrc}&_t=${sourceVersion}`
- : `${videoSrc}?_t=${sourceVersion}`;
+ ? sourceSrc
+ : sourceSrc.includes("?")
+ ? `${sourceSrc}&_t=${sourceVersion}`
+ : `${sourceSrc}?_t=${sourceVersion}`;
const reloadPlayback = useCallback(() => {
setVideoLoaded(false);
setHlsInitFailed(false);
@@ -223,6 +241,14 @@ export function HLSVideoPlayer({
!allowSegmentProbeDuringUpload &&
shouldDeferPlaybackSource(uploadProgressRaw);
const liveProbeSrc = isLiveSegments ? getLiveProbeSrc(playbackSrc) : null;
+ const early = useEarlyPlayback({
+ enabled: isEarlyPlayback && isPlaybackSourceReady,
+ statusUrl: isEarlyPlayback ? liveProbeSrc : null,
+ playerComplete: earlyPlaylistEnded,
+ videoRef,
+ });
+ const earlyLength =
+ isEarlyPlayback && !earlyPlaylistEnded ? early.recorded : null;
useEffect(() => {
if (!isLiveSegments) {
@@ -280,6 +306,10 @@ export function HLSVideoPlayer({
trackEvent("instant_playback_ready", {
elapsedMs,
fromRecordingStop,
+ // Time since the page navigation began; the desktop opens
+ // the share page right as the recording stops.
+ sinceNavigationMs: Math.round(performance.now()),
+ earlyPlayback: isEarlyPlayback,
}),
)
.catch(() => {});
@@ -333,7 +363,13 @@ export function HLSVideoPlayer({
video.removeEventListener("play", handlePlay);
video.removeEventListener("error", handleError);
};
- }, [playbackSrc, videoRef.current, isLiveSegments, isBackgroundPreview]);
+ }, [
+ playbackSrc,
+ videoRef.current,
+ isLiveSegments,
+ isBackgroundPreview,
+ isEarlyPlayback,
+ ]);
useEffect(() => {
const video = videoRef.current;
@@ -350,7 +386,13 @@ export function HLSVideoPlayer({
...(isLiveSegments
? {
liveSyncDurationCount: 3,
- liveMaxLatencyDurationCount: 6,
+ // Early playback watches from the start while the playlist
+ // grows, so it must never jump ahead to the live edge. Safari's
+ // ManagedMediaSource freezes after a seek in these playlists,
+ // so it uses MediaSource wherever that exists.
+ ...(isEarlyPlayback
+ ? { startPosition: 0, preferManagedMediaSource: false }
+ : { liveMaxLatencyDurationCount: 6 }),
manifestLoadingRetryDelay: 2000,
manifestLoadingMaxRetry: 30,
levelLoadingRetryDelay: 2000,
@@ -454,6 +496,13 @@ export function HLSVideoPlayer({
hasTriedPlaylistReload = false;
});
+ if (isEarlyPlayback) {
+ setEarlyPlaylistEnded(false);
+ hls.on(Hls.Events.LEVEL_UPDATED, (_event, data) => {
+ if (!data.details.live) setEarlyPlaylistEnded(true);
+ });
+ }
+
return () => {
if (retryTimer) clearTimeout(retryTimer);
if (hlsInstance.current) {
@@ -472,6 +521,7 @@ export function HLSVideoPlayer({
}, [
playbackSrc,
isLiveSegments,
+ isEarlyPlayback,
isPlaybackSourceReady,
reloadPlayback,
router,
@@ -510,6 +560,12 @@ export function HLSVideoPlayer({
const isUploadError = uploadProgress?.status === "error";
const hasFailedOrError =
isUploadFailed || isUploadError || sourceFailure !== null || hlsInitFailed;
+ const showEarlyUploadOverlay =
+ isEarlyPlayback &&
+ videoLoaded &&
+ !earlyPlaylistEnded &&
+ !hasFailedOrError &&
+ (early.held !== null || early.atEdge);
const hasActiveProgress =
isUploading || isProcessing || isGeneratingThumbnail;
const canRetryUploadProcessing =
@@ -800,6 +856,16 @@ export function HLSVideoPlayer({
/>
)}
</MediaPlayerVideo>
+ {showEarlyUploadOverlay && (
+ <EarlyUploadOverlay
+ videoRef={videoRef}
+ target={early.held}
+ ready={early.ready}
+ recorded={earlyLength}
+ uploadComplete={early.uploadComplete}
+ stalled={early.stalled}
+ />
+ )}
{videoLoaded &&
!hasActiveProgress &&
!hasFailedOrError &&
@@ -824,7 +890,7 @@ export function HLSVideoPlayer({
{currentCue}
</div>
)}
- <MediaPlayerLoading />
+ {!showEarlyUploadOverlay && <MediaPlayerLoading />}
<MediaPlayerError />
<MediaPlayerVolumeIndicator />
{callToAction &&
@@ -863,7 +929,12 @@ export function HLSVideoPlayer({
>
{!docked && <MediaPlayerControlsOverlay />}
{!externalTimeline && (
- <MediaPlayerSeek fallbackDuration={playerDuration} />
+ <MediaPlayerSeek
+ fallbackDuration={playerDuration}
+ expectedDuration={earlyLength}
+ pendingFrom={earlyLength !== null ? early.ready : null}
+ heldSeekTime={isEarlyPlayback ? early.held : null}
+ />
)}
<div className="flex gap-2 items-center w-full">
<div className="flex flex-1 gap-2 items-center">
@@ -882,7 +953,10 @@ export function HLSVideoPlayer({
// setEnhancedAudioMuted={setEnhancedAudioMuted}
/>
{(!externalTimeline || docked) && (
- <MediaPlayerTime fallbackDuration={playerDuration} />
+ <MediaPlayerTime
+ fallbackDuration={playerDuration}
+ expectedDuration={earlyLength}
+ />
)}
</div>
<div className="flex gap-2 items-center">
diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
index ac4e0917a..18c0b46a3 100644
--- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
@@ -98,6 +98,7 @@ export const ShareVideo = forwardRef<
showPlaybackStatusBadge?: boolean;
isEditProcessing: boolean;
recordingStopped?: boolean;
+ earlySegmentPlayback?: boolean;
defaultPlaybackSpeed?: number;
viewerIsOwner?: boolean;
callToAction?: ShareCallToAction | null;
@@ -121,6 +122,7 @@ export const ShareVideo = forwardRef<
showPlaybackStatusBadge = false,
isEditProcessing,
recordingStopped = false,
+ earlySegmentPlayback = false,
defaultPlaybackSpeed,
viewerIsOwner = false,
callToAction = null,
@@ -476,8 +478,15 @@ export const ShareVideo = forwardRef<
let enableCrossOrigin = false;
if (isSegmentsSource) {
- const requireComplete = userConfirmedStopped ? "&requireComplete=1" : "";
- videoSrc = `/api/playlist?userId=${data.owner.id}&videoId=${data.id}&videoType=segments-master${requireComplete}`;
+ // A stopped recording either waits for its complete manifest or,
+ // with early playback, starts from its first segment while the
+ // last ones finish uploading.
+ const stoppedMode = userConfirmedStopped
+ ? earlySegmentPlayback
+ ? "&earlyPlayback=1"
+ : "&requireComplete=1"
+ : "";
+ videoSrc = `/api/playlist?userId=${data.owner.id}&videoId=${data.id}&videoType=segments-master${stoppedMode}`;
} else if (isMp4Source) {
videoSrc = `/api/playlist?userId=${data.owner.id}&videoId=${data.id}&videoType=mp4`;
enableCrossOrigin = true;
@@ -606,6 +615,9 @@ export const ShareVideo = forwardRef<
allowSegmentProbeDuringUpload={
isSegmentsSource && userConfirmedStopped
}
+ earlyPlayback={
+ isSegmentsSource && userConfirmedStopped && earlySegmentPlayback
+ }
captionLanguage={captionContext.selectedLanguage}
onCaptionLanguageChange={handleCaptionLanguageChange}
availableCaptions={captionContext.availableTranslations}
diff --git a/apps/web/app/s/[videoId]/_components/early-playback.ts b/apps/web/app/s/[videoId]/_components/early-playback.ts
new file mode 100644
index 000000000..37d125310
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/early-playback.ts
@@ -0,0 +1,321 @@
+"use client";
+
+import { type RefObject, useEffect, useRef, useState } from "react";
+
+/**
+ * Early playback plays a stopped recording from its start while its last
+ * segments are still uploading. The playlist only holds what has uploaded, so
+ * a seek past it is held here until that part arrives instead of letting the
+ * browser clamp it to the end of the uploaded part.
+ */
+
+const STATUS_POLL_MS = 2_000;
+const STALLED_AFTER_MS = 30_000;
+
+export type EarlyPlaybackStatus = {
+ ready: number | null;
+ recorded: number | null;
+ uploadComplete: boolean;
+};
+
+export type EarlyPlaybackState = {
+ /** Seconds that play from the start without a gap. */
+ ready: number;
+ /** The full length, once the desktop app or the complete upload says. */
+ recorded: number | null;
+ /** Every segment has uploaded. */
+ uploadComplete: boolean;
+ /** A seek target waiting for its part to upload. */
+ held: number | null;
+ /** Playback has caught up with the end of the uploaded part. */
+ atEdge: boolean;
+ /** Nothing new has uploaded for a while. */
+ stalled: boolean;
+};
+
+function readSeconds(value: string | null): number | null {
+ if (value === null || value.trim() === "") return null;
+ const seconds = Number(value);
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
+}
+
+export function parseEarlyPlaybackStatus(response: {
+ status: number;
+ headers: Pick<Headers, "get">;
+}): EarlyPlaybackStatus | null {
+ if (response.status !== 204) return null;
+ return {
+ ready: readSeconds(response.headers.get("X-Cap-Ready-Duration")),
+ recorded: readSeconds(response.headers.get("X-Cap-Recorded-Duration")),
+ uploadComplete: response.headers.get("X-Cap-Recording-Complete") === "1",
+ };
+}
+
+/** How far the player can seek right now. */
+export function getMediaEnd(
+ video: Pick<HTMLMediaElement, "duration" | "seekable">,
+): number {
+ const duration = Number.isFinite(video.duration) ? video.duration : 0;
+ const seekable =
+ video.seekable.length > 0
+ ? video.seekable.end(video.seekable.length - 1)
+ : 0;
+ return Math.max(duration, seekable, 0);
+}
+
+/**
+ * Seeks the browser can carry out as asked. Before the duration is known
+ * (hls.js placing its start position) and once the player holds the whole
+ * recording, every seek goes through untouched.
+ */
+export function canSeekNow(
+ target: number,
+ mediaEnd: number,
+ playerComplete: boolean,
+): boolean {
+ return playerComplete || mediaEnd <= 0 || target <= mediaEnd - 0.05;
+}
+
+/**
+ * A held seek resolves once its part has uploaded with a second to play (or
+ * the upload is complete) and the player's playlist reaches it. Once the
+ * player holds the whole recording, a target past its end lands on the end.
+ */
+export function canResolveHold(
+ target: number,
+ {
+ ready,
+ mediaEnd,
+ uploadComplete,
+ playerComplete,
+ }: {
+ ready: number;
+ mediaEnd: number;
+ uploadComplete: boolean;
+ playerComplete: boolean;
+ },
+): boolean {
+ if (playerComplete) return mediaEnd > 0;
+ if (uploadComplete) return mediaEnd >= Math.min(target + 0.25, ready - 0.05);
+ return ready >= target + 1 && mediaEnd >= target + 0.25;
+}
+
+export function isAtUploadEdge({
+ currentTime,
+ mediaEnd,
+ paused,
+ readyState,
+ playerComplete,
+}: {
+ currentTime: number;
+ mediaEnd: number;
+ paused: boolean;
+ readyState: number;
+ playerComplete: boolean;
+}): boolean {
+ return (
+ !playerComplete &&
+ !paused &&
+ mediaEnd > 0 &&
+ readyState < 3 &&
+ currentTime >= mediaEnd - 1
+ );
+}
+
+export function formatClock(seconds: number): string {
+ const whole = Math.max(0, Math.floor(seconds));
+ const hours = Math.floor(whole / 3600);
+ const minutes = Math.floor((whole % 3600) / 60);
+ const secs = String(whole % 60).padStart(2, "0");
+ return hours > 0
+ ? `${hours}:${String(minutes).padStart(2, "0")}:${secs}`
+ : `${minutes}:${secs}`;
+}
+
+export function useEarlyPlayback({
+ enabled,
+ statusUrl,
+ playerComplete,
+ videoRef,
+}: {
+ enabled: boolean;
+ statusUrl: string | null;
+ /** The player's playlist has ended, so it holds the whole recording. */
+ playerComplete: boolean;
+ videoRef: RefObject<HTMLVideoElement | null>;
+}): EarlyPlaybackState {
+ const [ready, setReady] = useState(0);
+ const [recorded, setRecorded] = useState<number | null>(null);
+ const [statusComplete, setStatusComplete] = useState(false);
+ const [held, setHeld] = useState<number | null>(null);
+ const [atEdge, setAtEdge] = useState(false);
+ const [stalled, setStalled] = useState(false);
+ const uploadComplete = statusComplete || playerComplete;
+
+ const readyRef = useRef(0);
+ const uploadCompleteRef = useRef(uploadComplete);
+ const playerCompleteRef = useRef(playerComplete);
+ const heldRef = useRef<number | null>(null);
+ const resumeAfterHoldRef = useRef(false);
+ const pausedByHoldRef = useRef(false);
+ const lastGrowthRef = useRef(Date.now());
+ const resolveHoldRef = useRef<() => void>(() => {});
+ uploadCompleteRef.current = uploadComplete;
+ playerCompleteRef.current = playerComplete;
+
+ useEffect(() => {
+ if (!enabled || !statusUrl || uploadComplete) return;
+ const controller = new AbortController();
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const poll = async () => {
+ try {
+ const response = await fetch(statusUrl, {
+ cache: "no-store",
+ credentials: "same-origin",
+ signal: controller.signal,
+ });
+ void response.body?.cancel().catch(() => {});
+ const status = parseEarlyPlaybackStatus(response);
+ if (status) {
+ if (status.ready !== null && status.ready > readyRef.current) {
+ readyRef.current = status.ready;
+ lastGrowthRef.current = Date.now();
+ setReady(status.ready);
+ }
+ if (status.recorded !== null) setRecorded(status.recorded);
+ if (status.uploadComplete) {
+ uploadCompleteRef.current = true;
+ setStatusComplete(true);
+ }
+ }
+ } catch {
+ if (controller.signal.aborted) return;
+ }
+ setStalled(
+ !uploadCompleteRef.current &&
+ Date.now() - lastGrowthRef.current > STALLED_AFTER_MS,
+ );
+ resolveHoldRef.current();
+ if (!uploadCompleteRef.current && !controller.signal.aborted)
+ timer = setTimeout(poll, STATUS_POLL_MS);
+ };
+ void poll();
+ return () => {
+ controller.abort();
+ if (timer) clearTimeout(timer);
+ };
+ }, [enabled, statusUrl, uploadComplete]);
+
+ useEffect(() => {
+ if (uploadComplete) setStalled(false);
+ }, [uploadComplete]);
+
+ useEffect(() => {
+ const video = videoRef.current;
+ if (!enabled || !video) return;
+ const descriptor = Object.getOwnPropertyDescriptor(
+ HTMLMediaElement.prototype,
+ "currentTime",
+ );
+ const getTime = descriptor?.get;
+ const setTime = descriptor?.set;
+ if (!getTime || !setTime) return;
+ const currentTime = () => getTime.call(video) as number;
+ const seekTo = (time: number) => setTime.call(video, time);
+
+ const releaseHold = () => {
+ heldRef.current = null;
+ pausedByHoldRef.current = false;
+ setHeld(null);
+ };
+ const resolveHold = () => {
+ const target = heldRef.current;
+ if (target === null) return;
+ const mediaEnd = getMediaEnd(video);
+ if (
+ !canResolveHold(target, {
+ ready: readyRef.current,
+ mediaEnd,
+ uploadComplete: uploadCompleteRef.current,
+ playerComplete: playerCompleteRef.current,
+ })
+ )
+ return;
+ const resume = resumeAfterHoldRef.current;
+ releaseHold();
+ seekTo(Math.min(target, Math.max(0, mediaEnd - 0.05)));
+ if (resume) void video.play().catch(() => {});
+ };
+ resolveHoldRef.current = resolveHold;
+
+ const updateEdge = () =>
+ setAtEdge(
+ isAtUploadEdge({
+ currentTime: currentTime(),
+ mediaEnd: getMediaEnd(video),
+ paused: video.paused,
+ readyState: video.readyState,
+ playerComplete: playerCompleteRef.current,
+ }),
+ );
+
+ // Every seek (seek bar, keys, chapters, comments) sets currentTime, so
+ // this one property is where a seek past the uploaded part is held.
+ if (!playerComplete) {
+ Object.defineProperty(video, "currentTime", {
+ configurable: true,
+ enumerable: true,
+ get: currentTime,
+ set: (time: number) => {
+ if (
+ !Number.isFinite(time) ||
+ canSeekNow(time, getMediaEnd(video), playerCompleteRef.current)
+ ) {
+ const resume =
+ heldRef.current !== null &&
+ pausedByHoldRef.current &&
+ resumeAfterHoldRef.current;
+ if (heldRef.current !== null) releaseHold();
+ seekTo(time);
+ if (resume) void video.play().catch(() => {});
+ return;
+ }
+ if (heldRef.current === null)
+ resumeAfterHoldRef.current = !video.paused;
+ heldRef.current = time;
+ setHeld(time);
+ if (!video.paused) {
+ pausedByHoldRef.current = true;
+ video.pause();
+ }
+ },
+ });
+ }
+
+ // Pressing play while a seek is held keeps watching from here.
+ const onPlay = () => {
+ if (heldRef.current !== null) releaseHold();
+ updateEdge();
+ };
+ const onDurationChange = () => {
+ resolveHold();
+ updateEdge();
+ };
+ const events = ["waiting", "playing", "pause", "seeked", "timeupdate"];
+ for (const event of events) video.addEventListener(event, updateEdge);
+ video.addEventListener("play", onPlay);
+ video.addEventListener("durationchange", onDurationChange);
+ resolveHold();
+ updateEdge();
+
+ return () => {
+ for (const event of events) video.removeEventListener(event, updateEdge);
+ video.removeEventListener("play", onPlay);
+ video.removeEventListener("durationchange", onDurationChange);
+ Reflect.deleteProperty(video, "currentTime");
+ resolveHoldRef.current = () => {};
+ };
+ }, [enabled, playerComplete, videoRef]);
+
+ return { ready, recorded, uploadComplete, held, atEdge, stalled };
+}
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 bf6afd7c9..4fa0aa0da 100644
--- a/apps/web/app/s/[videoId]/_components/video/media-player.tsx
+++ b/apps/web/app/s/[videoId]/_components/video/media-player.tsx
@@ -1577,6 +1577,18 @@ interface MediaPlayerSeekProps
withoutChapter?: boolean;
withoutTooltip?: boolean;
fallbackDuration?: number | null;
+ /**
+ * The full length while only part of the media has loaded, so the bar
+ * spans the whole recording.
+ */
+ expectedDuration?: number | null;
+ /** Where the not-yet-available part of the bar starts. */
+ pendingFrom?: number | null;
+ /**
+ * A seek the player is holding. The thumb stays on it while it is held and
+ * returns to the playhead once the hold is dropped.
+ */
+ heldSeekTime?: number | null;
tooltipThumbnailSrc?: string | ((time: number) => string | undefined | null);
tooltipTimeVariant?: "current" | "progress";
tooltipSideOffset?: number;
@@ -1592,6 +1604,9 @@ function MediaPlayerSeek(props: MediaPlayerSeekProps) {
withoutChapter = false,
withoutTooltip = false,
fallbackDuration,
+ expectedDuration,
+ pendingFrom,
+ heldSeekTime,
tooltipTimeVariant = "current",
tooltipThumbnailSrc,
tooltipSideOffset,
@@ -1651,15 +1666,20 @@ function MediaPlayerSeek(props: MediaPlayerSeekProps) {
const mediaValues = [mediaDuration, seekableEnd].filter(
(d) => Number.isFinite(d) && d > 0,
);
- if (mediaValues.length > 0) return Math.max(...mediaValues);
- if (
+ let resolved = 0;
+ if (mediaValues.length > 0) resolved = Math.max(...mediaValues);
+ else if (
fallbackDuration != null &&
Number.isFinite(fallbackDuration) &&
fallbackDuration > 0
)
- return fallbackDuration;
- return 0;
- }, [fallbackDuration, mediaDuration, seekableEnd]);
+ resolved = fallbackDuration;
+ return expectedDuration != null &&
+ Number.isFinite(expectedDuration) &&
+ expectedDuration > resolved
+ ? expectedDuration
+ : resolved;
+ }, [fallbackDuration, expectedDuration, mediaDuration, seekableEnd]);
const lastKnownDurationRef = React.useRef(resolvedDuration);
React.useEffect(() => {
@@ -1868,6 +1888,15 @@ function MediaPlayerSeek(props: MediaPlayerSeekProps) {
}
}, [mediaCurrentTime, seekState.pendingSeekTime]);
+ const previousHeldSeekRef = React.useRef(heldSeekTime);
+ React.useEffect(() => {
+ const previous = previousHeldSeekRef.current;
+ previousHeldSeekRef.current = heldSeekTime;
+ if (previous != null && heldSeekTime == null) {
+ setSeekState((prev) => ({ ...prev, pendingSeekTime: null }));
+ }
+ }, [heldSeekTime]);
+
React.useEffect(() => {
if (!seekState.isHovering || tooltipDisabled) return;
@@ -2265,6 +2294,17 @@ function MediaPlayerSeek(props: MediaPlayerSeekProps) {
width: `${bufferedProgress * 100}%`,
}}
/>
+ {pendingFrom != null &&
+ effectiveDuration > 0 &&
+ pendingFrom < effectiveDuration && (
+ <div
+ data-slot="media-player-seek-pending"
+ className="absolute inset-y-0 right-0 animate-pulse bg-[repeating-linear-gradient(135deg,rgb(255_255_255/0.28)_0_4px,transparent_4px_8px)]"
+ style={{
+ left: `${(Math.max(0, pendingFrom) / effectiveDuration) * 100}%`,
+ }}
+ />
+ )}
<SliderPrimitive.Range className="absolute h-full bg-white will-change-[width]" />
{seekState.isHovering && effectiveDuration > 0 && (
<div
@@ -2535,6 +2575,8 @@ interface MediaPlayerTimeProps extends React.ComponentProps<"div"> {
variant?: "progress" | "remaining" | "duration";
asChild?: boolean;
fallbackDuration?: number | null;
+ /** The full length while only part of the media has loaded. */
+ expectedDuration?: number | null;
}
function MediaPlayerTime(props: MediaPlayerTimeProps) {
@@ -2543,6 +2585,7 @@ function MediaPlayerTime(props: MediaPlayerTimeProps) {
asChild,
className,
fallbackDuration,
+ expectedDuration,
...timeProps
} = props;
@@ -2554,15 +2597,20 @@ function MediaPlayerTime(props: MediaPlayerTimeProps) {
const mediaValues = [mediaDuration, seekableEnd].filter(
(d) => Number.isFinite(d) && d > 0,
);
- if (mediaValues.length > 0) return Math.max(...mediaValues);
- if (
+ let resolved = 0;
+ if (mediaValues.length > 0) resolved = Math.max(...mediaValues);
+ else if (
fallbackDuration != null &&
Number.isFinite(fallbackDuration) &&
fallbackDuration > 0
)
- return fallbackDuration;
- return 0;
- }, [fallbackDuration, mediaDuration, seekableEnd]);
+ resolved = fallbackDuration;
+ return expectedDuration != null &&
+ Number.isFinite(expectedDuration) &&
+ expectedDuration > resolved
+ ? expectedDuration
+ : resolved;
+ }, [fallbackDuration, expectedDuration, mediaDuration, seekableEnd]);
const lastKnownDurationRef = React.useRef(resolvedDuration);
React.useEffect(() => {
diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx
index 88c4eddbb..f853e62c4 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -46,6 +46,7 @@ import {
} from "@/app/(org)/dashboard/dashboard-data";
import { isAiConfigured } from "@/lib/ai/provider";
import { completeDesktopSegmentsManifestAndQueue } from "@/lib/desktop-segments-recovery";
+import { isEarlyInstantPlaybackEnabled } from "@/lib/early-instant-playback";
import {
getPendingLoomProcessing,
startDeferredLoomProcessing,
@@ -501,6 +502,10 @@ async function AuthorizedContent({
Option.map(Comment.CommentId.make),
);
const recordingStopped = hasRecordingStoppedParam(searchParams);
+ const earlySegmentPlayback =
+ recordingStopped &&
+ video.source?.type === "desktopSegments" &&
+ isEarlyInstantPlaybackEnabled(video.owner.id);
// Everything below is an independent round trip (DB or storage); each is
// started here and awaited together further down, so the page pays for the
@@ -1000,6 +1005,7 @@ async function AuthorizedContent({
canRecordMedia={canRecordMedia}
isEditProcessing={isEditProcessing}
recordingStopped={recordingStopped}
+ earlySegmentPlayback={earlySegmentPlayback}
defaultPlaybackSpeed={defaultPlaybackSpeed}
initialAiData={initialAiData}
aiGenerationAvailable={aiGenerationEnabled && aiProviderAvailable}