Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Improved video loading/playblack on mobile + thumbnail on seek

Richie McIlroy8fc107190199
diff --git a/apps/web/app/s/[videoId]/_components/MP4VideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/MP4VideoPlayer.tsx
index aa9ab8f05..78a363f2b 100644
--- a/apps/web/app/s/[videoId]/_components/MP4VideoPlayer.tsx
+++ b/apps/web/app/s/[videoId]/_components/MP4VideoPlayer.tsx
@@ -57,6 +57,10 @@ export const MP4VideoPlayer = memo(
const video = videoRef.current;
if (!video) return;
+ // Store the current position before reloading
+ const currentPosition = video.currentTime;
+ const wasPlaying = !video.paused;
+
// Get a fresh URL from the API
const newUrl = await fetchNewUrl();
@@ -69,6 +73,20 @@ export const MP4VideoPlayer = memo(
// Reset video and reload with new source
video.load();
+ // Restore position and play state after loading
+ if (currentPosition > 0) {
+ const restorePosition = () => {
+ video.currentTime = currentPosition;
+ if (wasPlaying) {
+ video
+ .play()
+ .catch((err) => console.error("Error resuming playback:", err));
+ }
+ video.removeEventListener("canplay", restorePosition);
+ };
+ video.addEventListener("canplay", restorePosition);
+ }
+
// Update the last attempt time
lastAttemptTime.current = Date.now();
}, [fetchNewUrl]);
@@ -135,6 +153,10 @@ export const MP4VideoPlayer = memo(
const handleLoadedData = () => {
console.log("Video loaded successfully");
setIsLoaded(true);
+ // Dispatch canplay event to notify parent component
+ if (videoRef.current) {
+ videoRef.current.dispatchEvent(new Event("canplay"));
+ }
// Clear any retry timeouts if video is loaded
if (retryTimeout.current) {
clearTimeout(retryTimeout.current);
@@ -143,8 +165,8 @@ export const MP4VideoPlayer = memo(
};
const handleLoadedMetadata = () => {
- // Trigger a canplay event after metadata is loaded
- video.dispatchEvent(new Event("canplay"));
+ // We'll let the loadeddata event handle dispatching canplay
+ // This ensures we don't trigger the event too early
};
const handleError = (e: ErrorEvent) => {
diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
index 2e86af4c1..00fe145d6 100644
--- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
@@ -1,7 +1,14 @@
import { comments as commentsSchema, videos } from "@cap/database/schema";
import { VideoPlayer } from "./VideoPlayer";
import { MP4VideoPlayer } from "./MP4VideoPlayer";
-import { useState, useEffect, useRef, forwardRef } from "react";
+import {
+ useState,
+ useEffect,
+ useRef,
+ forwardRef,
+ useCallback,
+ useImperativeHandle,
+} from "react";
import {
Play,
Pause,
@@ -48,19 +55,37 @@ export const ShareVideo = forwardRef<
comments: CommentWithAuthor[];
}
>(({ data, user, comments }, ref) => {
+ // Forward the ref to the video element
+ useImperativeHandle(ref, () => videoRef.current as HTMLVideoElement);
+
const videoRef = useRef<HTMLVideoElement>(null);
+ const previewVideoRef = useRef<HTMLVideoElement>(null);
+ const previewCanvasRef = useRef<HTMLCanvasElement>(null);
const [isPlaying, setIsPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
const [isLoading, setIsLoading] = useState(true);
const [longestDuration, setLongestDuration] = useState(0);
const [seeking, setSeeking] = useState(false);
const [videoMetadataLoaded, setVideoMetadataLoaded] = useState(false);
+ const [videoReadyToPlay, setVideoReadyToPlay] = useState(false);
const [overlayVisible, setOverlayVisible] = useState(true);
const [subtitles, setSubtitles] = useState<Subtitle[]>([]);
const [subtitlesVisible, setSubtitlesVisible] = useState(true);
const [isTranscriptionProcessing, setIsTranscriptionProcessing] =
useState(false);
+ // Scrubbing preview states
+ const [showPreview, setShowPreview] = useState(false);
+ const [previewTime, setPreviewTime] = useState(0);
+ const [previewPosition, setPreviewPosition] = useState(0);
+ const [previewLoaded, setPreviewLoaded] = useState(false);
+ const [previewWidth, setPreviewWidth] = useState(160);
+ const [previewHeight, setPreviewHeight] = useState(90);
+ // Track if we're actually showing MP4 content that supports thumbnails
+ const [isMP4Source, setIsMP4Source] = useState(false);
+ // Store the current preview image URL
+ const [thumbnailUrl, setThumbnailUrl] = useState<string | null>(null);
+
const [videoSpeed, setVideoSpeed] = useState(1);
const overlayTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const [isHovering, setIsHovering] = useState(false);
@@ -69,6 +94,19 @@ export const ShareVideo = forwardRef<
const [isHoveringControls, setIsHoveringControls] = useState(false);
const enterControlsTimeoutRef = useRef<NodeJS.Timeout | null>(null);
+ // Add to the state variables section
+ const [scrubbingVideo, setScrubbingVideo] = useState<HTMLVideoElement | null>(
+ null
+ );
+
+ // Simplify state variables and refs - remove the throttling mechanism that's causing issues
+ const [isPreviewSeeking, setIsPreviewSeeking] = useState(false);
+ const lastUpdateTimeRef = useRef<number>(0);
+ const lastMousePosRef = useRef<number>(0);
+
+ // Add a state to track if we're on a large screen
+ const [isLargeScreen, setIsLargeScreen] = useState(false);
+
useEffect(() => {
if (videoRef.current) {
if (typeof ref === "function") {
@@ -79,6 +117,35 @@ export const ShareVideo = forwardRef<
}
}, [ref]);
+ // Initialize thumbnail preview capability
+ useEffect(() => {
+ if (!videoMetadataLoaded) return;
+
+ // Only enable preview for desktopMP4 sources
+ setIsMP4Source(data.source.type === "desktopMP4");
+
+ // Pre-fetch the first thumbnail to check if it exists
+ if (data.source.type === "desktopMP4") {
+ const thumbUrl = `${clientEnv.NEXT_PUBLIC_WEB_URL}/api/playlist?userId=${data.ownerId}&videoId=${data.id}&thumbnailTime=0`;
+
+ // Check if the thumbnail exists
+ fetch(thumbUrl, { method: "HEAD" })
+ .then((response) => {
+ if (response.ok) {
+ console.log("Thumbnails available for this video");
+ setIsMP4Source(true);
+ } else {
+ console.log("No thumbnails available for this video");
+ setIsMP4Source(false);
+ }
+ })
+ .catch((error) => {
+ console.error("Error checking thumbnails:", error);
+ setIsMP4Source(false);
+ });
+ }
+ }, [videoMetadataLoaded, data.ownerId, data.id, data.source.type]);
+
const showControls = () => {
setOverlayVisible(true);
setIsHovering(true);
@@ -145,7 +212,8 @@ export const ShareVideo = forwardRef<
useEffect(() => {
if (videoMetadataLoaded) {
- setIsLoading(false);
+ // Don't immediately set isLoading to false when metadata loads
+ // We'll wait for canplay event to ensure video is ready
}
}, [videoMetadataLoaded]);
@@ -154,13 +222,34 @@ export const ShareVideo = forwardRef<
if (videoRef.current) {
setLongestDuration(videoRef.current.duration);
setVideoMetadataLoaded(true);
- setIsLoading(false);
+ // Don't set isLoading to false here
}
};
const onCanPlay = () => {
setVideoMetadataLoaded(true);
- setIsLoading(false);
+ setVideoReadyToPlay(true);
+
+ // If the video is already playing (user clicked play before it was ready),
+ // ensure it actually starts playing now
+ if (isPlaying && videoRef.current) {
+ // Store the current position before playing
+ const currentPosition = videoRef.current.currentTime;
+
+ videoRef.current.play().catch((error) => {
+ console.error("Error playing video in onCanPlay:", error);
+ });
+
+ // If the video was reset to the beginning, restore the position
+ if (videoRef.current.currentTime === 0 && currentPosition > 0) {
+ videoRef.current.currentTime = currentPosition;
+ }
+ }
+
+ // Set a small delay before removing the loading state to ensure smooth transition
+ setTimeout(() => {
+ setIsLoading(false);
+ }, 100);
};
const videoElement = videoRef.current;
@@ -190,9 +279,77 @@ export const ShareVideo = forwardRef<
setIsPlaying(false);
} else {
try {
- await videoElement.play();
- setIsPlaying(true);
- videoElement.muted = false;
+ // Make sure video is ready to play
+ if (!videoReadyToPlay) {
+ // If video is not ready yet, wait for it
+ console.log("Video not ready to play yet, waiting...");
+ // Show the controls to indicate we received the click
+ showControls();
+ // We'll attempt to play once the video is ready in the onCanPlay handler
+ setIsPlaying(true);
+ } else {
+ // Ensure video is not muted before playing
+ videoElement.muted = false;
+
+ // Store the current position before playing
+ const currentPosition = videoElement.currentTime;
+
+ // Use a promise to ensure play() completes
+ const playPromise = videoElement.play();
+
+ if (playPromise !== undefined) {
+ playPromise
+ .then(() => {
+ setIsPlaying(true);
+ console.log("Video playback started successfully");
+
+ // If the video was reset to the beginning, restore the position
+ if (videoElement.currentTime === 0 && currentPosition > 0) {
+ videoElement.currentTime = currentPosition;
+ }
+ })
+ .catch((error) => {
+ console.error("Error with playing:", error);
+
+ // If autoplay is prevented by browser policy, try again with muted
+ if (error.name === "NotAllowedError") {
+ console.log("Autoplay prevented, trying with muted...");
+ videoElement.muted = true;
+ videoElement
+ .play()
+ .then(() => {
+ setIsPlaying(true);
+ // After successful play, unmute if possible
+ setTimeout(() => {
+ videoElement.muted = false;
+ }, 100);
+
+ // If the video was reset to the beginning, restore the position
+ if (
+ videoElement.currentTime === 0 &&
+ currentPosition > 0
+ ) {
+ videoElement.currentTime = currentPosition;
+ }
+ })
+ .catch((innerError) => {
+ console.error(
+ "Still can't play even with muted:",
+ innerError
+ );
+ });
+ }
+ });
+ } else {
+ // For older browsers that don't return a promise
+ setIsPlaying(true);
+
+ // If the video was reset to the beginning, restore the position
+ if (videoElement.currentTime === 0 && currentPosition > 0) {
+ videoElement.currentTime = currentPosition;
+ }
+ }
+ }
} catch (error) {
console.error("Error with playing:", error);
}
@@ -200,32 +357,57 @@ export const ShareVideo = forwardRef<
};
const applyTimeToVideos = (time: number) => {
- if (videoRef.current) videoRef.current.currentTime = time;
- setCurrentTime(time);
+ // Validate time to ensure it's a finite number
+ if (!Number.isFinite(time)) {
+ console.warn("Attempted to set non-finite time:", time);
+ return;
+ }
+ // Clamp time between 0 and video duration
+ const validTime = Math.max(0, Math.min(time, longestDuration));
+ if (videoRef.current) videoRef.current.currentTime = validTime;
+ setCurrentTime(validTime);
};
useEffect(() => {
- const syncPlayback = () => {
- const videoElement = videoRef.current;
+ const videoElement = videoRef.current;
+ if (!videoElement || !videoReadyToPlay) return;
- if (!isPlaying || isLoading || !videoElement) return;
+ // Set up the time update handler only once
+ const handleTimeUpdate = () => {
+ setCurrentTime(videoElement.currentTime);
+ };
- const handleTimeUpdate = () => {
- setCurrentTime(videoElement.currentTime);
- };
+ // Add the event listener
+ videoElement.addEventListener("timeupdate", handleTimeUpdate);
+
+ // Clean up
+ return () => {
+ videoElement.removeEventListener("timeupdate", handleTimeUpdate);
+ };
+ }, [videoReadyToPlay]); // Only re-run when video becomes ready
+
+ // Separate effect for handling play state changes
+ useEffect(() => {
+ const videoElement = videoRef.current;
+ if (!videoElement || !videoReadyToPlay) return;
+
+ if (isPlaying) {
+ // Don't reset the currentTime when playing
+ const currentPosition = videoElement.currentTime;
videoElement.play().catch((error) => {
console.error("Error playing video", error);
setIsPlaying(false);
});
- videoElement.addEventListener("timeupdate", handleTimeUpdate);
- return () =>
- videoElement.removeEventListener("timeupdate", handleTimeUpdate);
- };
-
- syncPlayback();
- }, [isPlaying, isLoading]);
+ // If the video was reset to the beginning, restore the position
+ if (videoElement.currentTime === 0 && currentPosition > 0) {
+ videoElement.currentTime = currentPosition;
+ }
+ } else {
+ videoElement.pause();
+ }
+ }, [isPlaying, videoReadyToPlay]);
useEffect(() => {
const handleSeeking = () => {
@@ -243,9 +425,300 @@ export const ShareVideo = forwardRef<
};
}, [seeking]);
+ // Set up a hidden video element for scrubbing previews
+ useEffect(() => {
+ // Only set up scrubbing video on large screens
+ if (isMP4Source && data && isLargeScreen) {
+ console.log("Setting up scrubbing video");
+ const scrubVideo = document.createElement("video");
+
+ // Use the same MP4 source construction as the main video
+ const mp4Source = `${clientEnv.NEXT_PUBLIC_WEB_URL}/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=mp4`;
+
+ scrubVideo.src = mp4Source;
+ scrubVideo.crossOrigin = "anonymous";
+ scrubVideo.preload = "auto";
+ scrubVideo.muted = true;
+ scrubVideo.style.display = "none";
+
+ // Add event listener for when metadata is loaded
+ scrubVideo.addEventListener("loadedmetadata", () => {
+ console.log("Scrubbing video metadata loaded");
+ // Preload the first frame to ensure we have something to show on first hover
+ scrubVideo.currentTime = 0;
+ });
+
+ // Wait for the video to be ready to use
+ scrubVideo.addEventListener("canplay", () => {
+ console.log("Scrubbing video ready for preview");
+ setScrubbingVideo(scrubVideo);
+
+ // Preload the first frame after the video is ready
+ if (previewCanvasRef.current) {
+ const canvas = previewCanvasRef.current;
+ const ctx = canvas.getContext("2d");
+
+ if (ctx) {
+ // Set canvas dimensions
+ if (
+ canvas.width !== previewWidth ||
+ canvas.height !== previewHeight
+ ) {
+ canvas.width = previewWidth;
+ canvas.height = previewHeight;
+ }
+
+ // Draw the initial frame (at time 0)
+ try {
+ ctx.drawImage(scrubVideo, 0, 0, canvas.width, canvas.height);
+ setPreviewLoaded(true);
+ console.log("Preloaded initial frame for preview");
+ } catch (err) {
+ console.error("Error preloading initial frame:", err);
+ }
+ }
+ }
+ });
+
+ // Handle errors
+ scrubVideo.addEventListener("error", (e) => {
+ console.error("Error loading scrubbing video:", e);
+ });
+
+ // Append to document body (invisible)
+ document.body.appendChild(scrubVideo);
+
+ // Clean up on component unmount
+ return () => {
+ scrubVideo.remove();
+ setScrubbingVideo(null);
+ };
+ } else if (!isLargeScreen) {
+ // Clean up any existing scrubbing video on small screens
+ setScrubbingVideo(null);
+ }
+ }, [isMP4Source, data, previewWidth, previewHeight, isLargeScreen]);
+
+ // Function to update the preview thumbnail
+ const updatePreviewFrame = (time: number) => {
+ // Skip preview operations on small screens
+ if (!isLargeScreen) return;
+
+ if (!isMP4Source) return;
+
+ console.log("Updating preview frame to time:", time);
+ setPreviewTime(time);
+
+ // Don't attempt to seek again if already seeking to a position
+ if (isPreviewSeeking) {
+ console.log("Already seeking, skipping update");
+ return;
+ }
+
+ // Try to capture frames from the scrubbing video
+ try {
+ if (scrubbingVideo && previewCanvasRef.current) {
+ const canvas = previewCanvasRef.current;
+ const ctx = canvas.getContext("2d");
+
+ if (ctx) {
+ // Set canvas dimensions only if they haven't been set yet
+ if (
+ canvas.width !== previewWidth ||
+ canvas.height !== previewHeight
+ ) {
+ canvas.width = previewWidth;
+ canvas.height = previewHeight;
+ }
+
+ // Set a flag that we're seeking to avoid multiple seeks
+ setIsPreviewSeeking(true);
+
+ // Seek to the specific time
+ scrubbingVideo.currentTime = time;
+
+ // Listen for the seeked event
+ const handleSeeked = () => {
+ try {
+ // Draw the current frame onto the canvas
+ ctx.drawImage(scrubbingVideo, 0, 0, canvas.width, canvas.height);
+
+ // Add timestamp overlay
+ ctx.fillStyle = "rgba(0, 0, 0, 0.7)";
+ ctx.fillRect(0, canvas.height - 20, canvas.width, 20);
+ ctx.fillStyle = "white";
+ ctx.font = "12px Arial";
+ ctx.textAlign = "center";
+ ctx.fillText(
+ formatTime(time),
+ canvas.width / 2,
+ canvas.height - 6
+ );
+
+ setPreviewLoaded(true);
+ setIsPreviewSeeking(false);
+ console.log(`Drew frame at time ${time}`);
+ } catch (err) {
+ console.error("Error drawing frame:", err);
+ setIsPreviewSeeking(false);
+ }
+
+ // Remove the event listener after use
+ scrubbingVideo.removeEventListener("seeked", handleSeeked);
+ };
+
+ // Add the seeked event listener
+ scrubbingVideo.addEventListener("seeked", handleSeeked);
+
+ // Set a timeout to ensure we don't get stuck waiting for the seeked event
+ const timeoutId = setTimeout(() => {
+ if (isPreviewSeeking) {
+ try {
+ // If we're still seeking after 250ms, draw the frame anyway
+ ctx.drawImage(
+ scrubbingVideo,
+ 0,
+ 0,
+ canvas.width,
+ canvas.height
+ );
+
+ // Add timestamp overlay
+ ctx.fillStyle = "rgba(0, 0, 0, 0.7)";
+ ctx.fillRect(0, canvas.height - 20, canvas.width, 20);
+ ctx.fillStyle = "white";
+ ctx.font = "12px Arial";
+ ctx.textAlign = "center";
+ ctx.fillText(
+ formatTime(time),
+ canvas.width / 2,
+ canvas.height - 6
+ );
+
+ setPreviewLoaded(true);
+ console.log(`Drew frame at time ${time} after timeout`);
+ } catch (err) {
+ console.error("Error drawing frame after timeout:", err);
+ } finally {
+ // Always reset the seeking state after timeout
+ setIsPreviewSeeking(false);
+ scrubbingVideo.removeEventListener("seeked", handleSeeked);
+ }
+ }
+ }, 250);
+
+ // Clean up the timeout if the component unmounts
+ return () => clearTimeout(timeoutId);
+ }
+ } else if (videoRef.current && previewCanvasRef.current) {
+ // Fallback to main video if scrubbing video isn't ready
+ const canvas = previewCanvasRef.current;
+ const video = videoRef.current;
+ const ctx = canvas.getContext("2d");
+
+ if (ctx) {
+ try {
+ // Set canvas dimensions
+ canvas.width = previewWidth;
+ canvas.height = previewHeight;
+
+ // Draw the current frame from the main video
+ ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
+
+ // Add timestamp overlay
+ ctx.fillStyle = "rgba(0, 0, 0, 0.7)";
+ ctx.fillRect(0, canvas.height - 20, canvas.width, 20);
+ ctx.fillStyle = "white";
+ ctx.font = "12px Arial";
+ ctx.textAlign = "center";
+ ctx.fillText(formatTime(time), canvas.width / 2, canvas.height - 6);
+
+ setPreviewLoaded(true);
+ } catch (err) {
+ console.error("Error in fallback video capture:", err);
+ }
+ }
+ }
+ } catch (err) {
+ console.error("Error updating preview frame:", err);
+ setIsPreviewSeeking(false);
+ }
+ };
+
+ // Handle hovering over the timeline
+ const handleTimelineHover = (
+ event: React.MouseEvent<HTMLDivElement> | React.TouchEvent<HTMLDivElement>
+ ) => {
+ if (isLoading) return;
+
+ // Skip preview operations on small screens
+ if (!isLargeScreen) return;
+
+ const seekBar = event.currentTarget;
+ const time = calculateNewTime(event, seekBar);
+
+ // Set the preview position based on mouse/touch position
+ const rect = seekBar.getBoundingClientRect();
+
+ // Get clientX from either mouse or touch event
+ let clientX = 0;
+ if ("touches" in event && event.touches && event.touches[0]) {
+ clientX = event.touches[0].clientX;
+ } else if ("clientX" in event) {
+ clientX = event.clientX;
+ }
+
+ const previewPos = clientX - rect.left - previewWidth / 2;
+
+ // Ensure preview stays within bounds of the video player
+ const maxLeft = rect.width - previewWidth;
+ const boundedPos = Math.max(0, Math.min(previewPos, maxLeft));
+
+ setPreviewPosition(boundedPos);
+
+ // Always show the preview when hovering
+ if (!showPreview) {
+ setShowPreview(true);
+ // Force an update on the first hover
+ updatePreviewFrame(time);
+ lastUpdateTimeRef.current = Date.now();
+ return;
+ }
+
+ // Store the current mouse position
+ const currentMousePos = clientX;
+ const lastMousePos = lastMousePosRef.current;
+ lastMousePosRef.current = currentMousePos;
+
+ // Only update the frame if:
+ // 1. It's been more than 500ms since the last update
+ // 2. The mouse has moved significantly (more than 10px) since the last update
+ // 3. We're not currently in the middle of seeking
+ const now = Date.now();
+ const timeSinceLastUpdate = now - lastUpdateTimeRef.current;
+ const significantMouseMove = Math.abs(currentMousePos - lastMousePos) > 10;
+
+ if (
+ !isPreviewSeeking &&
+ (timeSinceLastUpdate >= 500 || significantMouseMove)
+ ) {
+ updatePreviewFrame(time);
+ lastUpdateTimeRef.current = now;
+ }
+ };
+
const calculateNewTime = (event: any, seekBar: any) => {
const rect = seekBar.getBoundingClientRect();
- const offsetX = event.clientX - rect.left;
+
+ // Handle both mouse and touch events
+ let clientX = 0;
+ if (event.touches && event.touches.length > 0) {
+ clientX = event.touches[0].clientX;
+ } else if (typeof event.clientX === "number") {
+ clientX = event.clientX;
+ }
+
+ const offsetX = Math.max(0, Math.min(clientX - rect.left, rect.width));
const relativePosition = offsetX / rect.width;
return relativePosition * longestDuration;
};
@@ -263,15 +736,33 @@ export const ShareVideo = forwardRef<
if (isPlaying) {
videoRef.current?.play();
}
+ setShowPreview(false);
};
const handleSeekMouseMove = (event: any) => {
if (!seeking) return;
+
+ // Prevent scrolling when seeking on mobile
+ if (event.touches) {
+ event.preventDefault();
+ }
+
const seekBar = event.currentTarget;
const seekTo = calculateNewTime(event, seekBar);
applyTimeToVideos(seekTo);
};
+ // Clean up any pending timeout when timeline hover ends
+ const handleTimelineLeave = () => {
+ // Skip preview operations on small screens
+ if (!isLargeScreen) return;
+
+ setShowPreview(false);
+ // Reset the last update time when leaving the timeline
+ // This ensures the preview will update immediately on the next hover
+ lastUpdateTimeRef.current = 0;
+ };
+
const handleMuteClick = () => {
if (videoRef.current) {
videoRef.current.muted = videoRef.current.muted ? false : true;
@@ -355,32 +846,36 @@ export const ShareVideo = forwardRef<
longestDuration > 0 ? (currentTime / longestDuration) * 100 : 0;
useEffect(() => {
- if (isPlaying) {
- videoRef.current?.play();
- } else {
- videoRef.current?.pause();
- }
- }, [isPlaying]);
+ if (!videoRef.current || !videoReadyToPlay) return;
- useEffect(() => {
- const syncPlay = () => {
- if (videoRef.current && !isLoading) {
- const playPromise2 = videoRef.current.play();
- playPromise2.catch((e) => console.log("Play failed for video 2", e));
- }
- };
+ const videoElement = videoRef.current;
if (isPlaying) {
- syncPlay();
+ const playPromise = videoElement.play();
+ if (playPromise !== undefined) {
+ playPromise.catch((error) => {
+ console.error("Error in useEffect play:", error);
+ // If autoplay is prevented, don't change the isPlaying state
+ // as it will be handled by the click handler
+ });
+ }
+ } else {
+ videoElement.pause();
}
- }, [isPlaying, isLoading]);
+ }, [isPlaying, videoReadyToPlay]);
const parseSubTime = (timeString: number) => {
- const [hours, minutes, seconds] = timeString
- .toString()
- .split(":")
- .map(Number);
- return (hours ?? 0) * 3600 + (minutes ?? 0) * 60 + (seconds ?? 0);
+ // Convert number to string and ensure it's in the format HH:MM:SS
+ const timeStr = timeString.toString();
+ const timeParts = timeStr.split(":");
+
+ // Map parts to numbers with proper fallbacks
+ const hoursValue = timeParts.length > 2 ? Number(timeParts[0]) || 0 : 0;
+ const minutesValue =
+ timeParts.length > 1 ? Number(timeParts[timeParts.length - 2]) || 0 : 0;
+ const secondsValue = Number(timeParts[timeParts.length - 1]) || 0;
+
+ return hoursValue * 3600 + minutesValue * 60 + secondsValue;
};
useEffect(() => {
@@ -447,6 +942,48 @@ export const ShareVideo = forwardRef<
parseSubTime(subtitle.endTime) >= currentTime
);
+ // Check screen size on mount and when window resizes
+ useEffect(() => {
+ const checkScreenSize = () => {
+ // lg breakpoint in Tailwind is typically 1024px
+ setIsLargeScreen(window.innerWidth >= 1024);
+ };
+
+ // Check on mount
+ checkScreenSize();
+
+ // Add resize listener
+ window.addEventListener("resize", checkScreenSize);
+
+ // Clean up
+ return () => window.removeEventListener("resize", checkScreenSize);
+ }, []);
+
+ // Initialize the preview canvas
+ useEffect(() => {
+ // Only initialize preview canvas on large screens
+ if (previewCanvasRef.current && isLargeScreen) {
+ const canvas = previewCanvasRef.current;
+ const ctx = canvas.getContext("2d");
+
+ if (ctx) {
+ // Set canvas dimensions
+ canvas.width = previewWidth;
+ canvas.height = previewHeight;
+
+ // Draw a black background initially
+ ctx.fillStyle = "#000000";
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+
+ // Add a "hover to preview" text
+ ctx.fillStyle = "white";
+ ctx.font = "12px Arial";
+ ctx.textAlign = "center";
+ ctx.fillText("Hover to preview", canvas.width / 2, canvas.height / 2);
+ }
+ }
+ }, [previewCanvasRef, previewWidth, previewHeight, isLargeScreen]);
+
if (data.jobStatus === "ERROR") {
return (
<div className="flex items-center justify-center w-full h-full rounded-lg overflow-hidden">
@@ -485,13 +1022,15 @@ export const ShareVideo = forwardRef<
id="video-container"
className="relative w-full h-full overflow-hidden shadow-lg rounded-lg group"
>
- {isLoading && (
- <div className="absolute inset-0 flex items-center justify-center z-10">
- <LogoSpinner className="w-10 h-auto animate-spin" />
- </div>
- )}
- <div className="relative w-full md:h-full">
- <div className="md:absolute inset-0 bg-black">
+ <div
+ className={`absolute inset-0 flex items-center justify-center z-10 bg-black transition-opacity duration-300 ${
+ isLoading ? "opacity-100" : "opacity-0 pointer-events-none"
+ }`}
+ >
+ <LogoSpinner className="w-8 sm:w-10 h-auto animate-spin" />
+ </div>
+ <div className="relative w-full h-full">
+ <div className="absolute inset-0 bg-black">
{data.source.type === "desktopMP4" ? (
<MP4VideoPlayer ref={videoRef} videoSrc={videoSrc} />
) : (
@@ -510,22 +1049,32 @@ export const ShareVideo = forwardRef<
aria-label={isPlaying ? "Pause video" : "Play video"}
className="w-full h-full flex items-center justify-center"
onClick={() => {
- handlePlayPauseClick();
- showControls();
- hideControls();
+ if (!videoReadyToPlay) {
+ // If video is not ready, set a visual indicator but don't try to play yet
+ console.log("Video not ready to play yet, waiting...");
+ // Show the controls to indicate we received the click
+ showControls();
+ // We'll attempt to play once the video is ready in the onCanPlay handler
+ setIsPlaying(true);
+ } else {
+ // Normal play/pause behavior when video is ready
+ handlePlayPauseClick();
+ showControls();
+ hideControls();
+ }
}}
>
{isPlaying ? (
- <Pause className="w-auto h-14 text-white hover:opacity-50" />
+ <Pause className="w-auto h-10 sm:h-12 md:h-14 text-white hover:opacity-50" />
) : (
- <Play className="w-auto h-14 text-white hover:opacity-50" />
+ <Play className="w-auto h-10 sm:h-12 md:h-14 text-white hover:opacity-50" />
)}
</button>
</div>
)}
{currentSubtitle && currentSubtitle.text && subtitlesVisible && (
- <div className="absolute bottom-16 w-full text-center p-2 z-10">
- <div className="inline px-2 py-1 text-lg md:text-2xl text-white bg-black bg-opacity-75 rounded-xl">
+ <div className="absolute bottom-12 sm:bottom-16 w-full text-center p-2 z-10">
+ <div className="inline px-2 py-1 text-sm sm:text-lg md:text-2xl text-white bg-black bg-opacity-75 rounded-xl">
{currentSubtitle.text
.replace("- ", "")
.replace(".", "")
@@ -534,6 +1083,45 @@ export const ShareVideo = forwardRef<
</div>
)}
</div>
+
+ {/* Thumbnail preview - MP4 only, visible only on screens larger than lg */}
+ {showPreview && !isLoading && isMP4Source && isLargeScreen && (
+ <div
+ className="absolute z-30 bg-black border border-gray-700 shadow-lg rounded-md overflow-hidden transition-opacity duration-150 hidden xl:block"
+ style={{
+ left: `${previewPosition}px`,
+ bottom: "70px",
+ width: `${previewWidth}px`,
+ height: `${previewHeight}px`,
+ opacity: previewLoaded ? 1 : 0.7,
+ }}
+ >
+ {thumbnailUrl ? (
+ <img
+ src={thumbnailUrl}
+ alt={`Preview at ${formatTime(previewTime)}`}
+ className="w-full h-full object-contain bg-black"
+ onError={(e) => {
+ console.log(
+ "Thumbnail failed to load, using canvas preview instead"
+ );
+ setThumbnailUrl(null);
+ }}
+ />
+ ) : (
+ <canvas
+ ref={previewCanvasRef}
+ className="w-full h-full object-contain bg-black"
+ />
+ )}
+ {!thumbnailUrl && (
+ <div className="absolute bottom-0 left-0 right-0 bg-black bg-opacity-70 py-1 px-2 text-xs text-white text-center">
+ {formatTime(previewTime)}
+ </div>
+ )}
+ </div>
+ )}
+
<div
className={`absolute bottom-0 left-0 right-0 bg-black bg-opacity-50 z-20 transition-opacity duration-300 ${
(overlayVisible || isHovering || isHoveringControls) &&
@@ -558,11 +1146,28 @@ export const ShareVideo = forwardRef<
>
<div
id="seek"
- className="absolute left-0 right-0 -top-2 h-4 mx-4 cursor-pointer"
+ className="absolute left-0 right-0 -top-2 h-6 mx-2 sm:mx-4 cursor-pointer"
onMouseDown={handleSeekMouseDown}
- onMouseMove={handleSeekMouseMove}
+ onMouseMove={(e) => {
+ if (seeking) {
+ handleSeekMouseMove(e);
+ } else {
+ handleTimelineHover(e);
+ }
+ }}
onMouseUp={handleSeekMouseUp}
- onMouseLeave={() => setSeeking(false)}
+ onMouseLeave={() => {
+ setSeeking(false);
+ handleTimelineLeave();
+ }}
+ onTouchStart={handleSeekMouseDown}
+ onTouchMove={(e) => {
+ if (seeking) {
+ handleSeekMouseMove(e);
+ } else {
+ handleTimelineHover(e);
+ }
+ }}
onTouchEnd={handleSeekMouseUp}
>
{!isLoading && comments !== null && (
@@ -600,7 +1205,7 @@ export const ShareVideo = forwardRef<
{comment.type === "text" ? (
<MessageSquare
fill="#646464"
- className="w-auto h-[22px] text-white"
+ className="w-auto h-[18px] sm:h-[22px] text-white"
/>
) : (
comment.content
@@ -612,46 +1217,46 @@ export const ShareVideo = forwardRef<
})}
</div>
)}
- <div className="absolute top-1.5 w-full h-1.5 bg-white bg-opacity-50 rounded-full z-10" />
+ <div className="absolute top-2.5 w-full h-1 sm:h-1.5 bg-white bg-opacity-50 rounded-full z-10" />
<div
- className="absolute top-1.5 h-1.5 bg-white rounded-full cursor-pointer transition-all duration-300 z-10"
+ className="absolute top-2.5 h-1 sm:h-1.5 bg-white rounded-full cursor-pointer transition-all duration-300 z-10"
style={{ width: `${watchedPercentage}%` }}
/>
<div
- className="drag-button absolute top-1.5 z-20 -mt-1.5 -ml-2 w-4 h-4 bg-white rounded-full border border-white cursor-pointer focus:ring-2 focus:ring-indigo-600 focus:ring-opacity-80 focus:outline-none transition-all duration-300"
+ className="drag-button absolute top-2.5 z-20 -mt-1.5 -ml-2 w-4 h-4 bg-white rounded-full border border-white cursor-pointer focus:ring-2 focus:ring-indigo-600 focus:ring-opacity-80 focus:outline-none transition-all duration-300"
tabIndex={0}
style={{ left: `${watchedPercentage}%` }}
/>
</div>
<div className="flex items-center justify-between px-4 py-2">
- <div className="flex items-center space-x-3">
+ <div className="flex items-center space-x-2 sm:space-x-3">
<div>
<span className="inline-flex">
<button
aria-label="Play video"
- className=" inline-flex items-center text-sm font-medium transition ease-in-out duration-150 focus:outline-none border text-slate-100 border-transparent hover:text-white focus:border-white hover:bg-slate-100 hover:bg-opacity-10 active:bg-slate-100 active:bg-opacity-10 px-2 py-2 justify-center rounded-lg"
+ className="inline-flex items-center text-sm font-medium transition ease-in-out duration-150 focus:outline-none border text-slate-100 border-transparent hover:text-white focus:border-white hover:bg-slate-100 hover:bg-opacity-10 active:bg-slate-100 active:bg-opacity-10 px-1 sm:px-2 py-1 sm:py-2 justify-center rounded-lg"
tabIndex={0}
type="button"
onClick={() => handlePlayPauseClick()}
>
{isPlaying ? (
- <Pause className="w-auto h-6" />
+ <Pause className="w-auto h-5 sm:h-6" />
) : (
- <Play className="w-auto h-6" />
+ <Play className="w-auto h-5 sm:h-6" />
)}
</button>
</span>
</div>
- <div className="text-sm text-white font-medium select-none tabular text-clip overflow-hidden whitespace-nowrap space-x-0.5">
+ <div className="text-xs sm:text-sm text-white font-medium select-none tabular text-clip overflow-hidden whitespace-nowrap space-x-0.5">
{formatTime(currentTime)} - {formatTime(longestDuration)}
</div>
</div>
- <div className="flex justify-end space-x-2">
- <div className="flex items-center justify-end space-x-2">
+ <div className="flex justify-end space-x-1 sm:space-x-2">
+ <div className="flex items-center justify-end space-x-1 sm:space-x-2">
<span className="inline-flex">
<button
aria-label={`Change video speed to ${videoSpeed}x`}
- className=" inline-flex min-w-[45px] items-center text-sm font-medium transition ease-in-out duration-150 focus:outline-none border text-slate-100 border-transparent hover:text-white focus:border-white hover:bg-slate-100 hover:bg-opacity-10 active:bg-slate-100 active:bg-opacity-10 px-2 py-2 justify-center rounded-lg"
+ className="inline-flex min-w-[35px] sm:min-w-[45px] items-center text-xs sm:text-sm font-medium transition ease-in-out duration-150 focus:outline-none border text-slate-100 border-transparent hover:text-white focus:border-white hover:bg-slate-100 hover:bg-opacity-10 active:bg-slate-100 active:bg-opacity-10 px-1 sm:px-2 py-1 sm:py-2 justify-center rounded-lg"
tabIndex={0}
type="button"
onClick={handleSpeedChange}
@@ -663,7 +1268,7 @@ export const ShareVideo = forwardRef<
<span className="inline-flex">
<button
aria-label={isPlaying ? "Pause video" : "Play video"}
- className=" inline-flex items-center text-sm font-medium transition ease-in-out duration-150 focus:outline-none border text-slate-100 border-transparent hover:text-white focus:border-white hover:bg-slate-100 hover:bg-opacity-10 active:bg-slate-100 active:bg-opacity-10 px-2 py-2 justify-center rounded-lg"
+ className="inline-flex items-center text-sm font-medium transition ease-in-out duration-150 focus:outline-none border text-slate-100 border-transparent hover:text-white focus:border-white hover:bg-slate-100 hover:bg-opacity-10 active:bg-slate-100 active:bg-opacity-10 px-1 sm:px-2 py-1 sm:py-2 justify-center rounded-lg"
tabIndex={0}
type="button"
onClick={() => {
@@ -672,7 +1277,7 @@ export const ShareVideo = forwardRef<
>
<svg
xmlns="http://www.w3.org/2000/svg"
- className="w-6 h-6"
+ className="w-5 h-5 sm:w-6 sm:h-6"
viewBox="0 0 24 24"
>
<style>
@@ -703,7 +1308,7 @@ export const ShareVideo = forwardRef<
aria-label={
subtitlesVisible ? "Hide subtitles" : "Show subtitles"
}
- className=" inline-flex items-center text-sm font-medium transition ease-in-out duration-150 focus:outline-none border text-slate-100 border-transparent hover:text-white focus:border-white hover:bg-slate-100 hover:bg-opacity-10 active:bg-slate-100 active:bg-opacity-10 px-2 py-2 justify-center rounded-lg"
+ className="inline-flex items-center text-sm font-medium transition ease-in-out duration-150 focus:outline-none border text-slate-100 border-transparent hover:text-white focus:border-white hover:bg-slate-100 hover:bg-opacity-10 active:bg-slate-100 active:bg-opacity-10 px-1 sm:px-2 py-1 sm:py-2 justify-center rounded-lg"
tabIndex={0}
type="button"
onClick={() => setSubtitlesVisible(!subtitlesVisible)}
@@ -716,7 +1321,7 @@ export const ShareVideo = forwardRef<
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
- className="w-auto h-6"
+ className="w-auto h-5 sm:h-6"
viewBox="0 0 24 24"
>
<rect
@@ -737,7 +1342,7 @@ export const ShareVideo = forwardRef<
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
- className="w-auto h-6"
+ className="w-auto h-5 sm:h-6"
viewBox="0 0 24 24"
>
<path d="M10.5 5H19a2 2 0 012 2v8.5M17 11h-.5M19 19H5a2 2 0 01-2-2V7a2 2 0 012-2M2 2l20 20M7 11h4M7 15h2.5"></path>
@@ -749,27 +1354,27 @@ export const ShareVideo = forwardRef<
<span className="inline-flex">
<button
aria-label={videoRef?.current?.muted ? "Unmute" : "Mute"}
- className=" inline-flex items-center text-sm font-medium transition ease-in-out duration-150 focus:outline-none border text-slate-100 border-transparent hover:text-white focus:border-white hover:bg-slate-100 hover:bg-opacity-10 active:bg-slate-100 active:bg-opacity-10 px-2 py-2 justify-center rounded-lg"
+ className="inline-flex items-center text-sm font-medium transition ease-in-out duration-150 focus:outline-none border text-slate-100 border-transparent hover:text-white focus:border-white hover:bg-slate-100 hover:bg-opacity-10 active:bg-slate-100 active:bg-opacity-10 px-1 sm:px-2 py-1 sm:py-2 justify-center rounded-lg"
tabIndex={0}
type="button"
onClick={() => handleMuteClick()}
>
{videoRef?.current?.muted ? (
- <VolumeX className="w-auto h-6" />
+ <VolumeX className="w-auto h-5 sm:h-6" />
) : (
- <Volume2 className="w-auto h-6" />
+ <Volume2 className="w-auto h-5 sm:h-6" />
)}
</button>
</span>
<span className="inline-flex">
<button
aria-label="Go fullscreen"
- className=" inline-flex items-center text-sm font-medium transition ease-in-out duration-150 focus:outline-none border text-slate-100 border-transparent hover:text-white focus:border-white hover:bg-slate-100 hover:bg-opacity-10 active:bg-slate-100 active:bg-opacity-10 px-2 py-2 justify-center rounded-lg"
+ className="inline-flex items-center text-sm font-medium transition ease-in-out duration-150 focus:outline-none border text-slate-100 border-transparent hover:text-white focus:border-white hover:bg-slate-100 hover:bg-opacity-10 active:bg-slate-100 active:bg-opacity-10 px-1 sm:px-2 py-1 sm:py-2 justify-center rounded-lg"
tabIndex={0}
type="button"
onClick={handleFullscreenClick}
>
- <Maximize className="w-auto h-6" />
+ <Maximize className="w-auto h-5 sm:h-6" />
</button>
</span>
</div>
diff --git a/apps/web/app/s/[videoId]/_components/VideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/VideoPlayer.tsx
index b6fca2907..1a044f568 100644
--- a/apps/web/app/s/[videoId]/_components/VideoPlayer.tsx
+++ b/apps/web/app/s/[videoId]/_components/VideoPlayer.tsx
@@ -52,10 +52,46 @@ export const VideoPlayer = memo(
useEffect(() => {
if (!videoRef.current) return;
+ const videoElement = videoRef.current;
+
+ // Store current position and play state before reinitializing
+ const currentPosition = videoElement.currentTime;
+ const wasPlaying = !videoElement.paused;
+
+ // Add event listener for when HLS is ready to play
+ const handleHlsManifestParsed = () => {
+ if (videoElement) {
+ // Restore position after HLS is ready
+ if (currentPosition > 0) {
+ videoElement.currentTime = currentPosition;
+ if (wasPlaying) {
+ videoElement
+ .play()
+ .catch((err) => console.error("Error resuming playback:", err));
+ }
+ }
+ videoElement.dispatchEvent(new Event("canplay"));
+ }
+ };
+
initializeHls(videoSrc, videoRef.current, videoHlsInstance);
+ // Add event listener for HLS manifest parsed
+ if (videoHlsInstance.current) {
+ videoHlsInstance.current.on(
+ Hls.Events.MANIFEST_PARSED,
+ handleHlsManifestParsed
+ );
+ }
+
return () => {
- videoHlsInstance.current?.destroy();
+ if (videoHlsInstance.current) {
+ videoHlsInstance.current.off(
+ Hls.Events.MANIFEST_PARSED,
+ handleHlsManifestParsed
+ );
+ videoHlsInstance.current.destroy();
+ }
};
}, [videoSrc]);