File size: 2,334 Bytes
c8cad77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import React from "react";
import { VideoOff } from "lucide-react";
import { useCameraStream } from "@/hooks/useCameraStream";
import { CameraRotation, cameraPreviewGeometry, cameraRotationError } from "@/lib/cameraConfig";

interface Props {
  deviceId: string;
  paused?: boolean;
  rotation?: CameraRotation;
  width?: number;
  height?: number;
  className?: string;
  fallback?: string;
  /** Saved reference frame, drawn over the live video as a translucent ghost. */
  ghostSrc?: string;
  ghostOpacity?: number;
}

/**
 * Browser streams contain raw frames, so only browser previews use CSS rotation.
 * The box keeps the recorded capture size's shape even when the browser stream
 * has another size, so the preview frames the scene the way recording will.
 */
export default function BrowserCameraPreview({
  deviceId,
  paused = false,
  rotation = 0,
  width = 640,
  height = 480,
  className = "",
  fallback,
  ghostSrc,
  ghostOpacity = 0.5,
}: Props) {
  const rotationError = cameraRotationError({ rotation });
  const { videoRef, hasError } = useCameraStream(deviceId, paused || !!rotationError, { width, height });
  const geometry = rotationError
    ? { aspectRatio: `${width} / ${height}`, videoStyle: {} }
    : cameraPreviewGeometry(width, height, rotation);
  const showVideo = !rotationError && !paused && deviceId && !hasError;
  return (
    <div
      className={`relative overflow-hidden bg-gray-800 ${className}`}
      style={{ aspectRatio: geometry.aspectRatio }}
    >
      {showVideo ? (
        <>
        <video
          ref={videoRef}
          autoPlay
          muted
          playsInline
          style={geometry.videoStyle}
        />
        {ghostSrc && (
          <img
            src={ghostSrc}
            alt=""
            aria-hidden
            className="pointer-events-none"
            style={{ ...geometry.videoStyle, opacity: ghostOpacity }}
          />
        )}
        </>
      ) : (
        <div className="absolute inset-0 flex flex-col items-center justify-center">
          <VideoOff className="w-5 h-5 text-gray-500 mb-1" />
          <span className="text-xs text-gray-500">
            {rotationError ?? fallback ?? (paused ? "Preview paused" : deviceId ? "Preview failed" : "No camera selected")}
          </span>
        </div>
      )}
    </div>
  );
}