Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

fix(memories):fix-video-playback-issues

Aswin Asok4fe4fc89ca8c
diff --git a/web/apps/memories/src/components/LaneMemoryViewer.tsx b/web/apps/memories/src/components/LaneMemoryViewer.tsx
index 84d822ca18..d075f4a7c7 100644
--- a/web/apps/memories/src/components/LaneMemoryViewer.tsx
+++ b/web/apps/memories/src/components/LaneMemoryViewer.tsx
@@ -4,6 +4,8 @@
* playback timing, scrubbing, captions, and decorative backgrounds. It is
* rendered by `pages/index.tsx` for the `"lane"` variant.
*/
+import VolumeOffRoundedIcon from "@mui/icons-material/VolumeOffRounded";
+import VolumeUpRoundedIcon from "@mui/icons-material/VolumeUpRounded";
import { styled, Typography } from "@mui/material";
import log from "ente-base/log";
import { downloadManager } from "ente-gallery/services/download";
@@ -99,6 +101,7 @@ export function LaneMemoryViewer({
onSeek,
}: LaneMemoryViewerProps) {
const [paused, setPaused] = useState(false);
+ const [muted, setMuted] = useState(false);
const [fileLoaded, setFileLoaded] = useState(false);
const [videoDurationKnown, setVideoDurationKnown] = useState(false);
const [viewport, setViewport] = useState({ width: 1280, height: 720 });
@@ -325,12 +328,6 @@ export function LaneMemoryViewer({
}
if (isVideo) {
- const activeVideo = activeVideoElementRef.current;
- if (activeVideo) {
- void activeVideo.play().catch(() => {
- // Browser playback policies may still reject here.
- });
- }
return;
}
@@ -369,6 +366,11 @@ export function LaneMemoryViewer({
setVideoDurationKnown(true);
}, []);
+ const handleVideoPlaybackBlocked = useCallback(() => {
+ finishedLanePlaybackRef.current = false;
+ setPaused(true);
+ }, []);
+
useEffect(() => {
if (!fileLoaded || displayIndex >= files.length - 1) {
return;
@@ -409,24 +411,64 @@ export function LaneMemoryViewer({
[],
);
- const toggleLanePlayback = useCallback(() => {
- setPaused((previous) => {
- const nextPaused = !previous;
- restartOnResumeRef.current =
- !nextPaused && finishedLanePlaybackRef.current;
- if (!nextPaused) {
- finishedLanePlaybackRef.current = false;
+ const resumeLanePlaybackFromGesture = useCallback(() => {
+ setPaused(false);
+
+ if (finishedLanePlaybackRef.current) {
+ finishedLanePlaybackRef.current = false;
+ restartOnResumeRef.current = false;
+ if (currentIndexRef.current > 0) {
+ onSeek(0);
+ return;
+ }
+
+ const activeVideo = activeVideoElementRef.current;
+ if (activeVideo) {
+ activeVideo.currentTime = 0;
}
- return nextPaused;
+ }
+
+ if (!isVideoRef.current) {
+ return;
+ }
+
+ const activeVideo = activeVideoElementRef.current;
+ if (!activeVideo) {
+ return;
+ }
+
+ activeVideo.muted = muted;
+ void activeVideo.play().catch((error: unknown) => {
+ log.warn(
+ "Failed to start lane memory video playback from user gesture",
+ error,
+ );
+ handleVideoPlaybackBlocked();
});
+ }, [handleVideoPlaybackBlocked, muted, onSeek]);
+
+ const pauseLanePlayback = useCallback(() => {
+ setPaused(true);
}, []);
+ const handleAudioToggle = useCallback(
+ (event: ReactMouseEvent<HTMLButtonElement>) => {
+ event.stopPropagation();
+ setMuted((previous) => !previous);
+ },
+ [],
+ );
+
const handlePlaybackToggle = useCallback(
(event: ReactMouseEvent<HTMLButtonElement>) => {
event.stopPropagation();
- toggleLanePlayback();
+ if (pausedRef.current) {
+ resumeLanePlaybackFromGesture();
+ } else {
+ pauseLanePlayback();
+ }
},
- [toggleLanePlayback],
+ [pauseLanePlayback, resumeLanePlaybackFromGesture],
);
const handleVideoEnded = useCallback(() => {
@@ -482,9 +524,13 @@ export function LaneMemoryViewer({
return;
}
- toggleLanePlayback();
+ if (pausedRef.current) {
+ resumeLanePlaybackFromGesture();
+ } else {
+ pauseLanePlayback();
+ }
},
- [onNext, onPrev, toggleLanePlayback, viewport.width],
+ [onNext, onPrev, pauseLanePlayback, resumeLanePlaybackFromGesture, viewport.width],
);
const laneFrameSize = useMemo(() => {
@@ -567,9 +613,8 @@ export function LaneMemoryViewer({
if (displayIndexRef.current !== roundedIndex) {
commitDisplayIndex(roundedIndex);
}
- onSeek(roundedIndex);
},
- [commitDisplayIndex, files.length, onSeek, trackScrubValue],
+ [commitDisplayIndex, files.length, trackScrubValue],
);
const handleScrubEnd = useCallback(
@@ -587,11 +632,17 @@ export function LaneMemoryViewer({
if (displayIndexRef.current !== roundedIndex) {
commitDisplayIndex(roundedIndex);
}
- onSeek(roundedIndex);
+ if (currentIndexRef.current !== roundedIndex) {
+ onSeek(roundedIndex);
+ }
},
[commitDisplayIndex, files.length, onSeek, trackScrubValue],
);
+ useEffect(() => {
+ setMuted(false);
+ }, [displayIndex]);
+
const showPlaybackOverlay = paused && !isScrubbing;
const playbackOverlayLabel = finishedLanePlaybackRef.current
? "Restart memory lane"
@@ -718,6 +769,7 @@ export function LaneMemoryViewer({
isDisplayCard ? (
<VideoPlayer
file={file}
+ muted={muted}
paused={paused}
mediaRef={
activeVideoElementRef
@@ -740,6 +792,9 @@ export function LaneMemoryViewer({
onEnded={
handleVideoEnded
}
+ onPlaybackBlocked={
+ handleVideoPlaybackBlocked
+ }
onAspectRatio={
handleActiveAspectRatio
}
@@ -787,6 +842,26 @@ export function LaneMemoryViewer({
</LaneStackSlice>
);
})}
+ {isVideo && (
+ <LaneTopRightAudioOverlay>
+ <LaneAudioControl
+ type="button"
+ onClick={handleAudioToggle}
+ aria-label={
+ muted
+ ? "Unmute video"
+ : "Mute video"
+ }
+ data-memory-control="true"
+ >
+ {muted ? (
+ <VolumeOffRoundedIcon fontSize="small" />
+ ) : (
+ <VolumeUpRoundedIcon fontSize="small" />
+ )}
+ </LaneAudioControl>
+ </LaneTopRightAudioOverlay>
+ )}
{showPlaybackOverlay && (
<LaneCornerPlaybackOverlay>
<LaneCornerPlaybackControl
@@ -1240,6 +1315,57 @@ const LaneCaption = styled("div")({
},
});
+const LaneTopRightAudioOverlay = styled("div")({
+ position: "absolute",
+ top: 0,
+ right: 0,
+ zIndex: 4,
+ display: "flex",
+ alignItems: "flex-start",
+ justifyContent: "flex-end",
+ padding: "20px",
+ pointerEvents: "none",
+ "@media (max-width: 900px)": { padding: "18px" },
+ [`@media (max-width: ${MOBILE_LAYOUT_BREAKPOINT_PX}px)`]: {
+ padding: "14px",
+ },
+});
+
+const LaneAudioControl = styled("button")({
+ width: "42px",
+ height: "42px",
+ borderRadius: "999px",
+ border: 0,
+ cursor: "pointer",
+ padding: 0,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ color: "white",
+ backgroundColor: "rgba(18, 18, 18, 0.68)",
+ boxShadow: "0 18px 40px rgba(0, 0, 0, 0.34)",
+ backdropFilter: "blur(10px)",
+ WebkitBackdropFilter: "blur(10px)",
+ transition:
+ "transform 150ms ease, background-color 150ms ease, box-shadow 150ms ease",
+ pointerEvents: "auto",
+ "&:hover": {
+ backgroundColor: "rgba(18, 18, 18, 0.76)",
+ transform: "scale(1.03)",
+ },
+ "&:active": { transform: "scale(0.98)" },
+ "& .MuiSvgIcon-root": { fontSize: "22px" },
+ "@media (max-width: 900px)": {
+ width: "40px",
+ height: "40px",
+ },
+ [`@media (max-width: ${MOBILE_LAYOUT_BREAKPOINT_PX}px)`]: {
+ width: "36px",
+ height: "36px",
+ "& .MuiSvgIcon-root": { fontSize: "20px" },
+ },
+});
+
const LaneCornerPlaybackOverlay = styled("div")({
position: "absolute",
inset: 0,
diff --git a/web/apps/memories/src/components/MemoryViewer.tsx b/web/apps/memories/src/components/MemoryViewer.tsx
index 23a32becab..0acfc3d66a 100644
--- a/web/apps/memories/src/components/MemoryViewer.tsx
+++ b/web/apps/memories/src/components/MemoryViewer.tsx
@@ -6,6 +6,8 @@
* variant.
*/
import { keyframes } from "@emotion/react";
+import VolumeOffRoundedIcon from "@mui/icons-material/VolumeOffRounded";
+import VolumeUpRoundedIcon from "@mui/icons-material/VolumeUpRounded";
import { styled, Typography } from "@mui/material";
import log from "ente-base/log";
import { downloadManager } from "ente-gallery/services/download";
@@ -128,6 +130,7 @@ export function MemoryViewer({
}: MemoryViewerProps) {
const currentFile = files[currentIndex]!;
const [paused, setPaused] = useState(false);
+ const [muted, setMuted] = useState(false);
const [fileLoaded, setFileLoaded] = useState(false);
const [videoDurationKnown, setVideoDurationKnown] = useState(false);
const [progressDuration, setProgressDuration] = useState(
@@ -144,6 +147,7 @@ export function MemoryViewer({
const previousFileRef = useRef(currentFile);
const previousIndexRef = useRef(currentIndex);
const outgoingClearTimeoutRef = useRef<number | null>(null);
+ const activeVideoElementRef = useRef<HTMLVideoElement | null>(null);
const isVideo = currentFile.metadata.fileType === FileType.video;
const isMobileLayout = viewport.width <= MOBILE_LAYOUT_BREAKPOINT_PX;
@@ -153,6 +157,7 @@ export function MemoryViewer({
useEffect(() => {
setPaused(false);
+ setMuted(false);
setFinishedPlayback(false);
setFileLoaded(false);
setVideoDurationKnown(false);
@@ -202,6 +207,34 @@ export function MemoryViewer({
setVideoDurationKnown(true);
}, []);
+ const handleVideoPlaybackBlocked = useCallback(() => {
+ setFinishedPlayback(false);
+ setPaused(true);
+ }, []);
+
+ const resumeCurrentVideoPlayback = useCallback(
+ ({ restart = false }: { restart?: boolean } = {}) => {
+ const video = activeVideoElementRef.current;
+ if (!video) {
+ return;
+ }
+
+ if (restart) {
+ video.currentTime = 0;
+ }
+
+ video.muted = muted;
+ void video.play().catch((error: unknown) => {
+ log.warn(
+ "Failed to start memory video playback from user gesture",
+ error,
+ );
+ handleVideoPlaybackBlocked();
+ });
+ },
+ [handleVideoPlaybackBlocked, muted],
+ );
+
const handleMediaAspectRatio = useCallback(
(width: number, height: number) => {
if (width <= 0 || height <= 0) {
@@ -289,7 +322,10 @@ export function MemoryViewer({
setFinishedPlayback(false);
setPaused(false);
- }, [currentIndex, onSeek]);
+ if (isVideo) {
+ resumeCurrentVideoPlayback({ restart: true });
+ }
+ }, [currentIndex, isVideo, onSeek, resumeCurrentVideoPlayback]);
const handlePlaybackOverlayClick = useCallback(
(event: ReactMouseEvent<HTMLButtonElement>) => {
@@ -301,8 +337,19 @@ export function MemoryViewer({
}
setPaused(false);
+ if (isVideo) {
+ resumeCurrentVideoPlayback();
+ }
},
- [finishedPlayback, handleRestartPlayback],
+ [finishedPlayback, handleRestartPlayback, isVideo, resumeCurrentVideoPlayback],
+ );
+
+ const handleAudioToggle = useCallback(
+ (event: ReactMouseEvent<HTMLButtonElement>) => {
+ event.stopPropagation();
+ setMuted((previous) => !previous);
+ },
+ [],
);
const handleViewerClick = useCallback(
@@ -459,6 +506,9 @@ export function MemoryViewer({
onReady={handleFullLoad}
onDuration={handleVideoDuration}
onEnded={handleAdvanceOrFinish}
+ onPlaybackBlocked={handleVideoPlaybackBlocked}
+ mediaRef={activeVideoElementRef}
+ muted={muted}
paused={paused}
fillFrame
objectFit="contain"
@@ -586,6 +636,24 @@ export function MemoryViewer({
onClick={handleMediaFrameClick}
>
{mediaLayers}
+ {isVideo && (
+ <TopRightMediaAudioOverlay>
+ <MediaAudioControl
+ type="button"
+ onClick={handleAudioToggle}
+ aria-label={
+ muted ? "Unmute video" : "Mute video"
+ }
+ data-memory-control="true"
+ >
+ {muted ? (
+ <VolumeOffRoundedIcon fontSize="small" />
+ ) : (
+ <VolumeUpRoundedIcon fontSize="small" />
+ )}
+ </MediaAudioControl>
+ </TopRightMediaAudioOverlay>
+ )}
{showPlaybackOverlay && (
<CenteredPlaybackOverlay>
<CenteredPlaybackControl
@@ -780,6 +848,57 @@ const MediaSwitchLayer = styled("div", {
pointerEvents: "none",
}));
+const TopRightMediaAudioOverlay = styled("div")({
+ position: "absolute",
+ top: "18px",
+ right: "18px",
+ zIndex: 4,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "flex-end",
+ pointerEvents: "none",
+ "@media (max-width: 900px)": { top: "16px", right: "16px" },
+ [`@media (max-width: ${MOBILE_LAYOUT_BREAKPOINT_PX}px)`]: {
+ top: "12px",
+ right: "12px",
+ },
+});
+
+const MediaAudioControl = styled("button")({
+ width: "42px",
+ height: "42px",
+ borderRadius: "999px",
+ border: 0,
+ cursor: "pointer",
+ padding: 0,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ color: "white",
+ backgroundColor: "rgba(18, 18, 18, 0.68)",
+ boxShadow: "0 18px 40px rgba(0, 0, 0, 0.34)",
+ backdropFilter: "blur(10px)",
+ WebkitBackdropFilter: "blur(10px)",
+ transition:
+ "transform 150ms ease, background-color 150ms ease, box-shadow 150ms ease",
+ pointerEvents: "auto",
+ "&:hover": {
+ backgroundColor: "rgba(18, 18, 18, 0.76)",
+ transform: "scale(1.03)",
+ },
+ "&:active": { transform: "scale(0.98)" },
+ "& .MuiSvgIcon-root": { fontSize: "22px" },
+ "@media (max-width: 900px)": {
+ width: "40px",
+ height: "40px",
+ },
+ [`@media (max-width: ${MOBILE_LAYOUT_BREAKPOINT_PX}px)`]: {
+ width: "36px",
+ height: "36px",
+ "& .MuiSvgIcon-root": { fontSize: "20px" },
+ },
+});
+
const CenteredPlaybackOverlay = styled("div")({
position: "absolute",
inset: 0,
diff --git a/web/apps/memories/src/components/PublicMemoryMedia.tsx b/web/apps/memories/src/components/PublicMemoryMedia.tsx
index c224b3a68c..dd86349e02 100644
--- a/web/apps/memories/src/components/PublicMemoryMedia.tsx
+++ b/web/apps/memories/src/components/PublicMemoryMedia.tsx
@@ -15,6 +15,7 @@ import "hls-video-element";
import {
type CSSProperties,
type RefObject,
+ type SyntheticEvent,
useCallback,
useEffect,
useRef,
@@ -124,6 +125,7 @@ export function PhotoImage({
const mediaReadyRef = useRef(false);
const hasNotifiedDisplayReadyRef = useRef(false);
const lastReportedAspectRatioRef = useRef<number | undefined>(undefined);
+ const loadGenerationRef = useRef(0);
onFullLoadRef.current = onFullLoad;
onAspectRatioRef.current = onAspectRatio;
@@ -157,7 +159,9 @@ export function PhotoImage({
}, []);
useEffect(() => {
- let cancelled = false;
+ const loadGeneration = loadGenerationRef.current + 1;
+ loadGenerationRef.current = loadGeneration;
+ const loadState = { cancelled: false };
setIsLoading(true);
setThumbnailURL(undefined);
setFullImageURL(undefined);
@@ -169,14 +173,14 @@ export function PhotoImage({
try {
const nextThumbnailURL =
await downloadManager.renderableThumbnailURL(file);
- if (!cancelled && nextThumbnailURL) {
+ if (!loadState.cancelled && nextThumbnailURL) {
setThumbnailURL(nextThumbnailURL);
- } else if (!cancelled) {
+ } else if (!loadState.cancelled) {
setIsLoading(false);
}
} catch (error) {
log.error("Failed to load thumbnail", error);
- if (!cancelled) {
+ if (!loadState.cancelled) {
setIsLoading(false);
}
}
@@ -189,17 +193,26 @@ export function PhotoImage({
try {
const sourceURLs =
await downloadManager.renderableSourceURLs(file);
- if (cancelled) {
+ if (loadState.cancelled) {
return;
}
- if (sourceURLs.type === "image") {
- setFullImageURL(sourceURLs.imageURL);
- } else {
+ if (sourceURLs.type === "video") {
signalReady();
+ return;
+ }
+
+ const nextFullImageURL =
+ sourceURLs.type === "livePhoto"
+ ? await sourceURLs.imageURL()
+ : sourceURLs.imageURL;
+ if (loadGeneration !== loadGenerationRef.current) {
+ return;
}
+
+ setFullImageURL(nextFullImageURL);
} catch (error) {
log.error("Failed to load full image", error);
- if (!cancelled) {
+ if (!loadState.cancelled) {
signalReady();
}
}
@@ -209,7 +222,10 @@ export function PhotoImage({
void loadFullImage();
return () => {
- cancelled = true;
+ loadState.cancelled = true;
+ if (loadGenerationRef.current === loadGeneration) {
+ loadGenerationRef.current += 1;
+ }
};
}, [file, signalReady, thumbnailOnly]);
@@ -237,6 +253,40 @@ export function PhotoImage({
}
}, [fullImageURL, reportAspectRatio, thumbnailOnly]);
+ const handleImageLoad = useCallback(
+ (event: SyntheticEvent<HTMLImageElement>) => {
+ const image = event.currentTarget;
+ reportAspectRatio(image.naturalWidth, image.naturalHeight);
+ const isFullImageLoad =
+ !thumbnailOnly &&
+ !!fullImageURL &&
+ (image.currentSrc || image.src) === fullImageURL;
+ setIsLoading(false);
+ if (thumbnailOnly || isFullImageLoad) {
+ signalReady();
+ }
+ },
+ [fullImageURL, reportAspectRatio, signalReady, thumbnailOnly],
+ );
+
+ const handleImageError = useCallback(
+ (event: SyntheticEvent<HTMLImageElement>) => {
+ const failedURL =
+ event.currentTarget.currentSrc || event.currentTarget.src;
+ log.error("Failed to render public memory image", failedURL);
+ setIsLoading(false);
+
+ if (!thumbnailOnly && fullImageURL && failedURL === fullImageURL) {
+ setFullImageURL(undefined);
+ } else if (thumbnailURL && failedURL === thumbnailURL) {
+ setThumbnailURL(undefined);
+ }
+
+ signalReady();
+ },
+ [fullImageURL, signalReady, thumbnailOnly, thumbnailURL],
+ );
+
const displayURL = fullImageURL ?? thumbnailURL;
const mediaStyle = buildMediaStyle({
cropRect,
@@ -264,20 +314,8 @@ export function PhotoImage({
src={displayURL}
alt=""
draggable={false}
- onLoad={(event) => {
- reportAspectRatio(
- event.currentTarget.naturalWidth,
- event.currentTarget.naturalHeight,
- );
- const isFullImageLoad =
- !thumbnailOnly &&
- !!fullImageURL &&
- event.currentTarget.src === fullImageURL;
- setIsLoading(false);
- if (thumbnailOnly || isFullImageLoad) {
- signalReady();
- }
- }}
+ onLoad={handleImageLoad}
+ onError={handleImageError}
style={mediaStyle}
/>
)}
@@ -290,6 +328,8 @@ export interface VideoPlayerProps {
onReady?: () => void;
onDuration?: (durationSeconds: number) => void;
onEnded?: () => void;
+ onPlaybackBlocked?: () => void;
+ muted?: boolean;
paused?: boolean;
mediaRef?: RefObject<HTMLVideoElement | null>;
fillFrame?: boolean;
@@ -310,6 +350,8 @@ export function VideoPlayer({
onReady,
onDuration,
onEnded,
+ onPlaybackBlocked,
+ muted = false,
paused,
mediaRef,
fillFrame,
@@ -329,18 +371,57 @@ export function VideoPlayer({
);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(false);
+ const [videoElement, setVideoElement] = useState<HTMLVideoElement | null>(
+ null,
+ );
const videoRef = useRef<HTMLVideoElement>(null);
const onReadyRef = useRef(onReady);
const onDurationRef = useRef(onDuration);
const onEndedRef = useRef(onEnded);
+ const onPlaybackBlockedRef = useRef(onPlaybackBlocked);
+ const pausedRef = useRef(paused);
+ const playbackRequestIDRef = useRef(0);
+ const hasSignalledReadyRef = useRef(false);
onReadyRef.current = onReady;
onDurationRef.current = onDuration;
onEndedRef.current = onEnded;
+ onPlaybackBlockedRef.current = onPlaybackBlocked;
+ pausedRef.current = paused;
+
+ const invalidatePlaybackRequest = useCallback(() => {
+ playbackRequestIDRef.current += 1;
+ }, []);
+
+ const requestPlayback = useCallback(() => {
+ const video = videoRef.current;
+ if (!video || pausedRef.current) {
+ return;
+ }
+
+ const requestID = playbackRequestIDRef.current + 1;
+ playbackRequestIDRef.current = requestID;
+ const playPromise = video.play();
+ void playPromise.catch((error: unknown) => {
+ if (
+ requestID !== playbackRequestIDRef.current ||
+ pausedRef.current ||
+ video !== videoRef.current
+ ) {
+ return;
+ }
+
+ log.warn("Failed to start public memory video playback", error);
+ video.pause();
+ setIsLoading(false);
+ onPlaybackBlockedRef.current?.();
+ });
+ }, []);
const setVideoElementRef = useCallback(
(node: HTMLVideoElement | null) => {
videoRef.current = node;
+ setVideoElement(node);
if (mediaRef) {
mediaRef.current = node;
}
@@ -350,11 +431,13 @@ export function VideoPlayer({
useEffect(() => {
let cancelled = false;
+ invalidatePlaybackRequest();
setIsLoading(true);
setError(false);
setVideoURL(undefined);
setHlsData(undefined);
setThumbnailURL(undefined);
+ hasSignalledReadyRef.current = false;
const load = async () => {
try {
@@ -396,7 +479,7 @@ export function VideoPlayer({
return () => {
cancelled = true;
};
- }, [file]);
+ }, [file, invalidatePlaybackRequest]);
useEffect(() => {
const video = videoRef.current;
@@ -405,13 +488,21 @@ export function VideoPlayer({
}
if (paused) {
+ invalidatePlaybackRequest();
video.pause();
} else {
- video.play().catch(() => {
- // Autoplay may be blocked; ignore.
- });
+ requestPlayback();
}
- }, [hlsData, paused, videoURL]);
+ }, [hlsData, invalidatePlaybackRequest, paused, requestPlayback, videoURL]);
+
+ useEffect(() => {
+ const video = videoRef.current;
+ if (!video) {
+ return;
+ }
+
+ video.muted = muted;
+ }, [muted, videoElement]);
const handleLoadedMetadata = useCallback(() => {
const video = videoRef.current;
@@ -421,21 +512,55 @@ export function VideoPlayer({
}
}, [onAspectRatio]);
- const handleCanPlay = useCallback(() => {
+ const handleMediaReady = useCallback(() => {
setIsLoading(false);
- onReadyRef.current?.();
- const video = videoRef.current;
- if (video && !paused) {
- video.play().catch(() => {
- // Autoplay may be blocked.
- });
+ if (!hasSignalledReadyRef.current) {
+ hasSignalledReadyRef.current = true;
+ onReadyRef.current?.();
}
- }, [paused]);
+ if (!pausedRef.current) {
+ requestPlayback();
+ }
+ }, [requestPlayback]);
const handleEnded = useCallback(() => {
onEndedRef.current?.();
}, []);
+ useEffect(() => {
+ const video = videoElement;
+ if (!video) {
+ return;
+ }
+
+ const handleError = () => {
+ const mediaError = video.error;
+ log.error("Public memory video element error", mediaError);
+ setError(true);
+ setIsLoading(false);
+ };
+
+ video.addEventListener("loadedmetadata", handleLoadedMetadata);
+ video.addEventListener("loadeddata", handleMediaReady);
+ video.addEventListener("canplay", handleMediaReady);
+ video.addEventListener("playing", handleMediaReady);
+ video.addEventListener("ended", handleEnded);
+ video.addEventListener("error", handleError);
+
+ if (video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA) {
+ handleMediaReady();
+ }
+
+ return () => {
+ video.removeEventListener("loadedmetadata", handleLoadedMetadata);
+ video.removeEventListener("loadeddata", handleMediaReady);
+ video.removeEventListener("canplay", handleMediaReady);
+ video.removeEventListener("playing", handleMediaReady);
+ video.removeEventListener("ended", handleEnded);
+ video.removeEventListener("error", handleError);
+ };
+ }, [handleEnded, handleLoadedMetadata, handleMediaReady, videoElement]);
+
const mediaStyle = buildMediaStyle({
cropRect,
cropContainerAspectRatio,
@@ -480,9 +605,6 @@ export function VideoPlayer({
src={hlsData.playlistURL}
poster={thumbnailURL}
playsInline
- onLoadedMetadata={handleLoadedMetadata}
- onCanPlay={handleCanPlay}
- onEnded={handleEnded}
style={mediaStyle}
/>
)}
@@ -493,10 +615,6 @@ export function VideoPlayer({
src={videoURL}
poster={thumbnailURL}
playsInline
- muted={false}
- onLoadedMetadata={handleLoadedMetadata}
- onCanPlay={handleCanPlay}
- onEnded={handleEnded}
style={mediaStyle}
/>
)}
diff --git a/web/apps/memories/src/services/public-memory-page.ts b/web/apps/memories/src/services/public-memory-page.ts
index 6d8ec5840c..4eab802f27 100644
--- a/web/apps/memories/src/services/public-memory-page.ts
+++ b/web/apps/memories/src/services/public-memory-page.ts
@@ -1,5 +1,6 @@
import { isHTTPErrorWithStatus } from "ente-base/http";
import log from "ente-base/log";
+import { memoriesAppOrigin } from "ente-base/origins";
import type { EnteFile } from "ente-media/file";
import { alignLaneFilesWithMetadata } from "../utils/lane";
import {
@@ -37,7 +38,7 @@ export const loadPublicMemoryPage = async (
const accessToken = extractAccessTokenFromURL(currentURL);
if (!accessToken) {
- return { kind: "redirect", redirectURL: "https://ente.com" };
+ return { kind: "redirect", redirectURL: memoriesAppOrigin() };
}
const shareKey = await extractMemoryShareKeyFromURL(currentURL);
diff --git a/web/apps/memories/src/utils/lane.ts b/web/apps/memories/src/utils/lane.ts
index 04f0afba12..1a90b691d1 100644
--- a/web/apps/memories/src/utils/lane.ts
+++ b/web/apps/memories/src/utils/lane.ts
@@ -56,8 +56,85 @@ export const alignLaneFilesWithMetadata = (
return { files: orderedFiles, frames: orderedFrames };
};
-const yearsBetween = (start: Date, end: Date) =>
- (end.getTime() - start.getTime()) / (365.25 * 24 * 60 * 60 * 1000);
+const normalizeCalendarDate = (date: Date) =>
+ new Date(date.getFullYear(), date.getMonth(), date.getDate());
+
+const parseCalendarDate = (value: string): Date | undefined => {
+ const trimmed = value.trim();
+ if (!trimmed) {
+ return undefined;
+ }
+
+ const dateOnlyMatch = /^(\d{4})-(\d{2})-(\d{2})$/.exec(trimmed);
+ if (dateOnlyMatch) {
+ const [, year, month, day] = dateOnlyMatch;
+ const parsed = new Date(Number(year), Number(month) - 1, Number(day));
+ if (
+ Number.isNaN(parsed.getTime()) ||
+ parsed.getFullYear() !== Number(year) ||
+ parsed.getMonth() !== Number(month) - 1 ||
+ parsed.getDate() !== Number(day)
+ ) {
+ return undefined;
+ }
+
+ return parsed;
+ }
+
+ const parsed = new Date(trimmed);
+ if (Number.isNaN(parsed.getTime())) {
+ return undefined;
+ }
+
+ return normalizeCalendarDate(parsed);
+};
+
+const safeDateInYear = (date: Date, year: number) => {
+ const daysInTargetMonth = new Date(
+ year,
+ date.getMonth() + 1,
+ 0,
+ ).getDate();
+ const targetDay = Math.min(date.getDate(), daysInTargetMonth);
+ return new Date(year, date.getMonth(), targetDay);
+};
+
+const completedYearsBetween = (start: Date, end: Date) => {
+ const startDate = normalizeCalendarDate(start);
+ const endDate = normalizeCalendarDate(end);
+ if (endDate.getTime() < startDate.getTime()) {
+ return 0;
+ }
+
+ let years = endDate.getFullYear() - startDate.getFullYear();
+ if (
+ endDate.getTime() <
+ safeDateInYear(startDate, endDate.getFullYear()).getTime()
+ ) {
+ years -= 1;
+ }
+
+ return Math.max(0, years);
+};
+
+const laneCaptionValue = ({
+ captionType,
+ creationDate,
+ birthDate,
+}: {
+ captionType: "age" | "yearsAgo";
+ creationDate: Date;
+ birthDate?: string;
+}) => {
+ if (captionType === "age" && birthDate) {
+ const parsedBirthDate = parseCalendarDate(birthDate);
+ if (parsedBirthDate) {
+ return completedYearsBetween(parsedBirthDate, creationDate);
+ }
+ }
+
+ return completedYearsBetween(creationDate, new Date());
+};
export const getFileAspectRatio = (file: EnteFile): number | undefined => {
const width = file.pubMagicMetadata?.data.w;
@@ -195,18 +272,11 @@ export const formatLaneCaption = ({
const personName = metadata?.personName?.trim() ?? "";
const captionType =
metadata?.captionType ?? (metadata?.birthDate ? "age" : "yearsAgo");
- const roundedValue = (() => {
- if (captionType === "age" && metadata?.birthDate) {
- const birthDate = new Date(metadata.birthDate);
- if (!Number.isNaN(birthDate.getTime())) {
- return Math.max(
- 0,
- Math.round(yearsBetween(birthDate, creationDate)),
- );
- }
- }
- return Math.max(0, Math.round(yearsBetween(creationDate, new Date())));
- })();
+ const roundedValue = laneCaptionValue({
+ captionType,
+ creationDate,
+ birthDate: metadata?.birthDate,
+ });
const yearsLabel = `${roundedValue} year${roundedValue === 1 ? "" : "s"}`;
if (captionType === "age") {
@@ -233,18 +303,11 @@ export const buildLaneCaptionModel = ({
const personName = metadata?.personName?.trim() ?? "";
const captionType =
metadata?.captionType ?? (metadata?.birthDate ? "age" : "yearsAgo");
- const roundedValue = (() => {
- if (captionType === "age" && metadata?.birthDate) {
- const birthDate = new Date(metadata.birthDate);
- if (!Number.isNaN(birthDate.getTime())) {
- return Math.max(
- 0,
- Math.round(yearsBetween(birthDate, creationDate)),
- );
- }
- }
- return Math.max(0, Math.round(yearsBetween(creationDate, new Date())));
- })();
+ const roundedValue = laneCaptionValue({
+ captionType,
+ creationDate,
+ birthDate: metadata?.birthDate,
+ });
const prefix =
captionType === "age" ? "" : personName ? `${personName} ` : "";
const suffix =