Preview fixes (#13193)

* Handle case where preview was saved late

* fix timing
This commit is contained in:
Nicolas Mowen 2024-08-19 10:45:55 -06:00
parent 8b2adb55ed
commit 65ceadda2b
2 changed files with 28 additions and 11 deletions

View File

@ -16,6 +16,7 @@ import { isAndroid, isChrome, isMobile } from "react-device-detect";
import { TimeRange } from "@/types/timeline"; import { TimeRange } from "@/types/timeline";
import { Skeleton } from "../ui/skeleton"; import { Skeleton } from "../ui/skeleton";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { usePreviewForTimeRange } from "@/hooks/use-camera-previews";
type PreviewPlayerProps = { type PreviewPlayerProps = {
className?: string; className?: string;
@ -39,15 +40,11 @@ export default function PreviewPlayer({
onClick, onClick,
}: PreviewPlayerProps) { }: PreviewPlayerProps) {
const [currentHourFrame, setCurrentHourFrame] = useState<string>(); const [currentHourFrame, setCurrentHourFrame] = useState<string>();
const currentPreview = usePreviewForTimeRange(
const currentPreview = useMemo(() => { cameraPreviews,
return cameraPreviews.find( camera,
(preview) => timeRange,
preview.camera == camera &&
Math.round(preview.start) >= timeRange.after &&
Math.floor(preview.end) <= timeRange.before,
); );
}, [cameraPreviews, camera, timeRange]);
if (currentPreview) { if (currentPreview) {
return ( return (

View File

@ -1,6 +1,6 @@
import { Preview } from "@/types/preview"; import { Preview } from "@/types/preview";
import { TimeRange } from "@/types/timeline"; import { TimeRange } from "@/types/timeline";
import { useEffect, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import useSWR from "swr"; import useSWR from "swr";
type OptionalCameraPreviewProps = { type OptionalCameraPreviewProps = {
@ -8,7 +8,6 @@ type OptionalCameraPreviewProps = {
autoRefresh?: boolean; autoRefresh?: boolean;
fetchPreviews?: boolean; fetchPreviews?: boolean;
}; };
export function useCameraPreviews( export function useCameraPreviews(
initialTimeRange: TimeRange, initialTimeRange: TimeRange,
{ {
@ -32,3 +31,24 @@ export function useCameraPreviews(
return allPreviews; return allPreviews;
} }
// we need to add a buffer of 5 seconds to the end preview times
// this ensures that if preview generation is running slowly
// and the previews are generated 1-5 seconds late
// it is not falsely thrown out.
const PREVIEW_END_BUFFER = 5; // seconds
export function usePreviewForTimeRange(
allPreviews: Preview[],
camera: string,
timeRange: TimeRange,
) {
return useMemo(() => {
return allPreviews.find(
(preview) =>
preview.camera == camera &&
Math.ceil(preview.start) >= timeRange.after &&
Math.floor(preview.end) <= timeRange.before + PREVIEW_END_BUFFER,
);
}, [allPreviews, camera, timeRange]);
}