Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 4 additions & 6 deletions web/src/lib/cameraFrame.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,10 @@ export function cropToAspect(width: number, height: number, aspect: number): Cam
return { left: 0, top: (height - cropHeight) / 2, width, height: cropHeight };
}

export function streamSize(aspect: number, longSide: number) {
const safeAspect = Number.isFinite(aspect) && aspect > 0 ? aspect : 4 / 3;
const shortSide = longSide / Math.max(safeAspect, 1 / safeAspect);
export function streamSize(longSide: number) {
return {
width: { ideal: safeAspect >= 1 ? longSide : shortSide },
height: { ideal: safeAspect >= 1 ? shortSide : longSide },
aspectRatio: { ideal: safeAspect },
width: { ideal: longSide },
height: { ideal: longSide * 3 / 4 },
resizeMode: { ideal: "none" },
};
}
65 changes: 51 additions & 14 deletions web/src/pages/WallCamera.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ChangeEvent } from "react";
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Link, useNavigate, useParams, useSearchParams } from "react-router";
import { uploadWallImage } from "../lib/hooks/mutations";
Expand All @@ -25,6 +25,8 @@ const LENS_ORDER = ["0.5x", "1x", "Tele"];
// 1920 streams fine.
const PREVIEW_LONG_SIDE = 1920;
const PHOTO_LONG_SIDE = 4096;
const PREVIEW_SIZE = streamSize(PREVIEW_LONG_SIDE);
const PHOTO_SIZE = streamSize(PHOTO_LONG_SIDE);

/** Resolves on the next decoded video frame, or after a timeout. */
function nextFrame(video: HTMLVideoElement): Promise<void> {
Expand Down Expand Up @@ -169,12 +171,12 @@ export default function WallCameraPage() {
width: 0,
height: 0,
});
const [videoDimensions, setVideoDimensions] = useState({ width: 0, height: 0 });
const [cameraSettings, setCameraSettings] = useState<MediaTrackSettings | null>(null);
const [ghostImage, setGhostImage] = useState<{ src: string; aspect?: number } | null>(null);
const ghostAspect = ghostImage?.src === oldImage ? ghostImage.aspect : undefined;
const aspectReady = !oldImage || ghostImage?.src === oldImage;
const streamAspect = ghostAspect ?? 4 / 3;
const previewSize = useMemo(() => streamSize(streamAspect, PREVIEW_LONG_SIDE), [streamAspect]);
const photoSize = useMemo(() => streamSize(streamAspect, PHOTO_LONG_SIDE), [streamAspect]);
const debug = params.get("debug") === "1";
const [ready, setReady] = useState(false);
const [opacity, setOpacity] = useState(0.4);
const [busy, setBusy] = useState(false);
Expand All @@ -187,17 +189,18 @@ export default function WallCameraPage() {
const gen = ++streamGenRef.current;
streamRef.current?.getTracks().forEach((track) => track.stop());
streamRef.current = null;
setCameraSettings(null);

let media: MediaStream;
try {
media = await requestStream(deviceId, previewSize);
media = await requestStream(deviceId, PREVIEW_SIZE);
} catch (error) {
if (!deviceId) throw error;
try {
media = await requestStream(deviceId, {});
} catch (retryError) {
if (!fallback) throw retryError;
media = await requestStream(undefined, previewSize);
media = await requestStream(undefined, PREVIEW_SIZE);
}
}
if (gen !== streamGenRef.current) {
Expand All @@ -207,6 +210,7 @@ export default function WallCameraPage() {

streamRef.current = media;
const track = media.getVideoTracks()[0];
setCameraSettings(track?.getSettings() ?? null);
setActiveLens({ deviceId: track?.getSettings().deviceId, name: track?.label ?? "" });
const video = videoRef.current;
if (video) {
Expand All @@ -220,7 +224,7 @@ export default function WallCameraPage() {
await video.play().catch(() => undefined);
}
return gen === streamGenRef.current ? media : null;
}, [previewSize]);
}, []);

useEffect(() => {
if (!oldImage) return;
Expand Down Expand Up @@ -251,12 +255,12 @@ export default function WallCameraPage() {

useEffect(() => {
if (!aspectReady) return;
let mounted = true;
const video = videoRef.current;
const stage = stageRef.current;

const updateVideoFrame = () => {
if (!video || !stage) return;
setVideoDimensions({ width: video.videoWidth, height: video.videoHeight });
setVideoFrame(
getContainedFrame(
stage.clientWidth,
Expand All @@ -273,15 +277,24 @@ export default function WallCameraPage() {
if (stage) resizeObserver?.observe(stage);
video?.addEventListener("loadedmetadata", updateVideoFrame);
video?.addEventListener("resize", updateVideoFrame);
updateVideoFrame();

return () => {
resizeObserver?.disconnect();
video?.removeEventListener("loadedmetadata", updateVideoFrame);
video?.removeEventListener("resize", updateVideoFrame);
};
}, [aspectReady, ghostAspect]);

useEffect(() => {
let mounted = true;
const startCamera = async () => {
try {
// With permission already granted, labels are available up front and we can
// open the preferred lens directly; otherwise open the default camera first.
let available = await listLenses();
const media = await openStream(preferredLens(available)?.deviceId);
if (!media) return;
updateVideoFrame();

if (available.length === 0) {
available = await listLenses();
Expand Down Expand Up @@ -311,13 +324,10 @@ export default function WallCameraPage() {
// A counter, not a DOM ref: bumping the live value is the point.
// oxlint-disable-next-line react-hooks/exhaustive-deps
streamGenRef.current++;
resizeObserver?.disconnect();
video?.removeEventListener("loadedmetadata", updateVideoFrame);
video?.removeEventListener("resize", updateVideoFrame);
streamRef.current?.getTracks().forEach((track) => track.stop());
streamRef.current = null;
};
}, [aspectReady, ghostAspect, openStream]);
}, [openStream]);

const switchLens = async (lens: Lens) => {
const previousTrack = streamRef.current?.getVideoTracks()[0];
Expand Down Expand Up @@ -389,7 +399,7 @@ export default function WallCameraPage() {
if (!image) {
setBusy(true);
const fullSize = track
? await drawFullSizeFrame(video, track, photoSize, previewSize, aspect)
? await drawFullSizeFrame(video, track, PHOTO_SIZE, PREVIEW_SIZE, aspect)
: null;
const canvas = fullSize ?? drawFrame(video, aspect);
if (canvas) image = await canvasToJpeg(canvas);
Expand Down Expand Up @@ -459,6 +469,33 @@ export default function WallCameraPage() {
})}
</div>
)}
{debug && (
<pre
style={{
position: "absolute",
top: 8,
right: 8,
zIndex: 1,
margin: 0,
padding: 8,
background: "#000b",
color: "#fff",
fontSize: 11,
pointerEvents: "none",
}}
>
{JSON.stringify({
track: cameraSettings && {
width: cameraSettings.width,
height: cameraSettings.height,
aspectRatio: cameraSettings.aspectRatio,
resizeMode: (cameraSettings as MediaTrackSettings & { resizeMode?: string }).resizeMode,
},
video: videoDimensions,
ghostAspect,
}, null, 2)}
</pre>
)}
</div>

{oldImage && (
Expand Down
10 changes: 5 additions & 5 deletions web/tests/cameraFrame.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,10 @@ test("leaves a matching frame uncropped", () => {
});
});

test("sizes portrait streams with the long side at the requested size", () => {
assert.deepEqual(streamSize(3 / 4, 1920), {
width: { ideal: 1440 },
height: { ideal: 1920 },
aspectRatio: { ideal: 3 / 4 },
test("requests a landscape 4:3 stream without an aspect-ratio constraint", () => {
assert.deepEqual(streamSize(1920), {
width: { ideal: 1920 },
height: { ideal: 1440 },
resizeMode: { ideal: "none" },
});
});
Loading