File size: 5,849 Bytes
065d164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb6831d
3fdfac3
 
065d164
bb6831d
 
065d164
 
3fdfac3
065d164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3fdfac3
065d164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3fdfac3
 
065d164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128b839
065d164
128b839
065d164
128b839
 
 
065d164
 
 
 
 
 
 
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import { useEffect, useRef } from 'react';

const CameraSetup = ({ 
  videoRef, 
  canvasRef, 
  containerRef, 
  facingMode, 
  setFacingMode, 
  setCameraError, 
  setVideoAspectRatio, 
  updateCanvasSize,
  isMobile
}) => {
  // Track if component is mounted to prevent state updates after unmount
  const isMounted = useRef(true);
  // Track if camera is currently being set up
  const isSettingUpCamera = useRef(false);

  // Set up the webcam
  useEffect(() => {
    // Set mounted flag
    isMounted.current = true;
    
    const setupCamera = async () => {
      if (!videoRef.current || !canvasRef.current || !containerRef.current) return;
      // Prevent multiple simultaneous setup attempts
      if (isSettingUpCamera.current) return;
      
      isSettingUpCamera.current = true;
      
      try {
        // Stop any existing stream first
        if (videoRef.current.srcObject) {
          const tracks = videoRef.current.srcObject.getTracks();
          tracks.forEach(track => track.stop());
        }
        
        // Get camera stream
        const stream = await navigator.mediaDevices.getUserMedia({
          video: { 
            facingMode: facingMode,
            width: { ideal: 1920 },
            height: { ideal: 1080 }
          },
          audio: false
        });
        
        // Check if component is still mounted before continuing
        if (!isMounted.current) {
          stream.getTracks().forEach(track => track.stop());
          return;
        }
        
        videoRef.current.srcObject = stream;
        
        // Use a try-catch block for the play() call
        try {
          await videoRef.current.play();
        } catch (playError) {
          console.log("Play interrupted, this is normal if component remounted:", playError);
          // Don't treat play interruptions as fatal errors
          if (playError.name !== "AbortError") {
            throw playError;
          }
        }
        
        // Get the actual video dimensions once metadata is loaded
        videoRef.current.onloadedmetadata = () => {
          if (!isMounted.current) return;
          
          const videoWidth = videoRef.current.videoWidth;
          const videoHeight = videoRef.current.videoHeight;
          const aspectRatio = videoWidth / videoHeight;
          setVideoAspectRatio(aspectRatio);
          
          // Update canvas size with the correct aspect ratio
          updateCanvasSize(aspectRatio);
        };
        
        if (isMounted.current) {
          setCameraError(false);
          console.log("Camera set up successfully");
        }
        
      } catch (error) {
        console.error('Error accessing webcam:', error);
        if (isMounted.current) {
          setCameraError(true);
        }
      } finally {
        isSettingUpCamera.current = false;
      }
    };
    
    setupCamera();

    return () => {
      // Set mounted flag to false to prevent state updates after unmount
      isMounted.current = false;
      
      if (videoRef.current && videoRef.current.srcObject) {
        const tracks = videoRef.current.srcObject.getTracks();
        tracks.forEach(track => track.stop());
      }
    };
  }, [videoRef, canvasRef, containerRef, facingMode, setCameraError, setVideoAspectRatio, updateCanvasSize]);

  // Function to switch camera
  const switchCamera = async () => {
    if (!videoRef.current || isSettingUpCamera.current) return;
    
    isSettingUpCamera.current = true;
    
    // Stop current stream
    if (videoRef.current.srcObject) {
      const tracks = videoRef.current.srcObject.getTracks();
      tracks.forEach(track => track.stop());
    }
    
    // Toggle facing mode
    const newFacingMode = facingMode === 'user' ? 'environment' : 'user';
    setFacingMode(newFacingMode);
    
    try {
      // Get new camera stream with updated facing mode
      const stream = await navigator.mediaDevices.getUserMedia({
        video: { 
          facingMode: newFacingMode,
          width: { ideal: 1920 },
          height: { ideal: 1080 }
        },
        audio: false
      });
      
      if (!isMounted.current) {
        stream.getTracks().forEach(track => track.stop());
        return;
      }
      
      videoRef.current.srcObject = stream;
      
      try {
        await videoRef.current.play();
      } catch (playError) {
        console.log("Play interrupted during camera switch:", playError);
        // Don't treat play interruptions as fatal errors
        if (playError.name !== "AbortError") {
          throw playError;
        }
      }
      
      if (isMounted.current) {
        setCameraError(false);
        console.log(`Camera switched to ${newFacingMode === 'user' ? 'front' : 'back'} camera`);
      }
    } catch (error) {
      console.error('Error switching camera:', error);
      if (isMounted.current) {
        setCameraError(true);
      }
    } finally {
      isSettingUpCamera.current = false;
    }
  };

  return (
    <>
      <video 
        ref={videoRef} 
        className="hidden" 
        width="1280" 
        height="720" 
        autoPlay 
        playsInline 
        muted
      />
      
      {/* Camera switch button - only shown on mobile */}
      {isMobile && (
        <button
          onClick={switchCamera}
          className="absolute top-4 right-4 bg-white bg-opacity-70 p-2 rounded-full shadow-md z-10 hover:bg-opacity-90 transition-all flex items-center justify-center"
          aria-label={`Switch to ${facingMode === 'user' ? 'back' : 'front'} camera`}
          style={{ width: '40px', height: '40px' }}
        >
          <span className="material-symbols-outlined text-gray-800" style={{ display: 'flex', lineHeight: 1 }}>
            cameraswitch
          </span>
        </button>
      )}
    </>
  );
};

export default CameraSetup;