import { AppState, AppStateStatus, DeviceEventEmitter, Dimensions, LayoutChangeEvent, Platform, SafeAreaView, StyleSheet, Text, View, } from "react-native"; import React, { useCallback, useEffect, useRef, useState } from "react"; import { Camera, CameraCaptureError, CameraDeviceFormat, Frame, PhotoFile, useCameraDevices, useFrameProcessor, VideoFile, } from "react-native-vision-camera"; import { CameraRoll } from "@react-native-camera-roll/camera-roll"; import { RootState, useAppDispatch } from "../../redux/store"; import { setActionData } from "../../redux/AOPSlice"; import RNFS from "react-native-fs"; import { useSelector } from "react-redux"; import { disableCaptureAction, lockNavigationToggle, setCameraDimension, } from "../../redux/UtilSlice"; import { CameraModuleHandle } from "./cameraCommonInterface"; import { objectDetectionPlugin } from "../frame-processors/Plugins/ObjectDetectionPlugin"; import Animated, { runOnJS, useAnimatedStyle } from "react-native-reanimated"; import { FrameProcessorPluginMap } from "../frame-processors/FrameProcessorPluginMap"; const COCO_CLASSES = [ "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush", ]; export const sortFormatsByResolution = ( left: CameraDeviceFormat, right: CameraDeviceFormat ): number => { // in this case, points aren't "normalized" (e.g. higher resolution = 1 point, lower resolution = -1 points) let leftPoints = left.photoHeight * left.photoWidth; let rightPoints = right.photoHeight * right.photoWidth; // we also care about video dimensions, not only photo. leftPoints += left.videoWidth * left.videoHeight; rightPoints += right.videoWidth * right.videoHeight; // you can also add points for FPS, etc return rightPoints - leftPoints; }; export const useIsForeground = (): boolean => { const [isForeground, setIsForeground] = useState(true); useEffect(() => { const onChange = (state: AppStateStatus): void => { setIsForeground(state === "active"); }; const listener = AppState.addEventListener("change", onChange); return () => listener.remove(); }, [setIsForeground]); return isForeground; }; interface FrameProcessorState { pluginId?: string; isEnabled: boolean; } const VisionCamera: React.ForwardRefRenderFunction = (_, ref) => { const camera = useRef(null); const [isFrameProcessingEnabled, setIsFrameProcessingEnabled] = useState({ isEnabled: false, }); const handleLayout = (event: LayoutChangeEvent) => { const { width, height } = event.nativeEvent.layout; dispatch(setCameraDimension({ width, height })); }; const devices = useCameraDevices(); const [hasPermission, setHasPermission] = React.useState(false); const device = devices.back; const orientation = useSelector((appState: RootState) => appState.Util.orientation); // ! initially there is no slot index and step index // ! needs to be handled accordingly const steps = useSelector((state: RootState) => state.AOP.steps); const activeSlotIndex = useSelector((state: RootState) => state.AOP.activeSlotIndex as number); const activeStepIndex = useSelector((state: RootState) => state.AOP.activeStepIndex as number); const activeSlotItemIndex = useSelector( (state: RootState) => state.AOP.activeSlotItemIndex as number ); const stepName = steps.length > 0 ? steps[activeStepIndex].title : ""; const stepId = steps.length > 0 ? steps[activeStepIndex].stepId : ""; const slotName = steps.length > 0 ? steps[activeStepIndex].slots[activeSlotIndex].title : ""; const slotItemName = steps.length > 0 && steps[activeStepIndex].slots[activeSlotIndex].slotItems.length > 0 ? steps[activeStepIndex].slots[activeSlotIndex].slotItems[activeSlotItemIndex].title : ""; const slotId = steps.length > 0 ? steps[activeStepIndex].slots[activeSlotIndex].slotId : ""; const productId = useSelector((appState: RootState) => appState.App.productID); const [usedFormat, setUsedFormat] = useState(); const captureSettings = useSelector((appState: RootState) => appState.Util.captureSettings.filter( (setting) => (setting.platform === "all" || setting.platform === Platform.OS) && (setting.camera === "all" || setting.camera === "vision") ) ); const dispatch = useAppDispatch(); const setPermissions = async () => { const status = await Camera.requestCameraPermission(); setHasPermission(status === "authorized"); }; useEffect(() => { setPermissions(); }); useEffect(() => { const cameraFormats = device?.formats.filter((format) => format.isHighestPhotoQualitySupported); if (cameraFormats && cameraFormats.length > 0) { setUsedFormat(cameraFormats[0]); } }, [device]); React.useImperativeHandle(ref, () => ({ async takePhoto() { try { dispatch(lockNavigationToggle(true)); // locks navigation till photo is saved const photo = await camera.current?.takePhoto({ flash: (captureSettings.find((setting) => setting.settingsKey === "torch") ?.value as boolean) ? "on" : "off", qualityPrioritization: "quality", enableAutoStabilization: true, }); if (photo) { const { path } = photo; let fileSavePath = ""; if (slotItemName.length > 0) { fileSavePath = `${RNFS.DocumentDirectoryPath}/${ productId + "_" + stepName + "_" + slotName + "_" + slotItemName }.jpeg`; } else { fileSavePath = `${RNFS.DocumentDirectoryPath}/${ productId + "_" + stepName + "_" + slotName }.jpeg`; } const flag = await RNFS.exists(fileSavePath); if (flag) { await RNFS.unlink(fileSavePath); } await RNFS.copyFile(path, fileSavePath); const updatedPhoto: PhotoFile = { ...photo, path: fileSavePath, }; await CameraRoll.save(fileSavePath, { type: "photo", album: "capture-sdk", }); dispatch(setActionData(updatedPhoto)); dispatch(lockNavigationToggle(false)); // unlocks navigation after photo is saved dispatch(disableCaptureAction(false)); } } catch (error: any) { console.log(error.message); } }, startVideo() { dispatch(lockNavigationToggle(true)); // locks navigation till video is being recorded camera.current?.startRecording({ onRecordingFinished: async (video) => { const { path } = video; let fileSavePath = ""; if (slotItemName.length > 0) { fileSavePath = `${RNFS.DocumentDirectoryPath}/${ productId + "_" + stepName + "_" + slotName + "_" + slotItemName }.mp4`; } else { fileSavePath = `${RNFS.DocumentDirectoryPath}/${ productId + "_" + stepName + "_" + slotName }.mp4`; } const flag = await RNFS.exists(fileSavePath); if (flag) { await RNFS.unlink(fileSavePath); } await RNFS.copyFile(path, fileSavePath); const updatedVideo: VideoFile = { ...video, path: fileSavePath, }; await CameraRoll.save(fileSavePath, { type: "video", album: "capture-sdk", }); dispatch(setActionData(updatedVideo)); dispatch(lockNavigationToggle(false)); // unlocks navigation after video is saved dispatch(disableCaptureAction(false)); }, onRecordingError: (error: CameraCaptureError) => { console.log(JSON.stringify(error, null, 2)); }, }); }, async stopVideo() { await camera.current?.stopRecording(); }, })); useEffect(() => { const fpStartSub = DeviceEventEmitter.addListener( "@s20/smart-guide/frame-processor/start", (data) => { setIsFrameProcessingEnabled({ pluginId: data, isEnabled: true }); } ); const fpEndSub = DeviceEventEmitter.addListener( "@s20/smart-guide/frame-processor/stop", (data) => { setIsFrameProcessingEnabled({ isEnabled: false }); } ); return () => { fpStartSub.remove(); fpEndSub.remove(); }; }, []); const emitBBox = (values: any) => { DeviceEventEmitter.emit("@s20/smart-guide/frame-processor/bbox-update", values); }; const frameProcessor = useFrameProcessor( (frame: Frame) => { "worklet"; if (isFrameProcessingEnabled) { const pluginId = isFrameProcessingEnabled.pluginId as string; if (pluginId) { const values = FrameProcessorPluginMap[pluginId](frame, 0.5, 0.5); runOnJS(emitBBox)(JSON.parse(values)); } } }, [isFrameProcessingEnabled] ); if (device == null) { return ( no devices attached ); } return ( <> setting.settingsKey === "highQualityPhoto") ?.value as boolean } enablePortraitEffectsMatteDelivery enableDepthData format={usedFormat} lowLightBoost={ captureSettings.find((setting) => setting.settingsKey === "lowLightBoost") ?.value as boolean } fps={captureSettings.find((setting) => setting.settingsKey === "fps")?.value as number} hdr={captureSettings.find((setting) => setting.settingsKey === "hdr")?.value as boolean} torch={ (captureSettings.find((setting) => setting.settingsKey === "torch")?.value as boolean) ? "on" : "off" } /> ); }; const styles = StyleSheet.create({ viewPortRoot: { position: "relative", flex: 1, }, camera: { position: "absolute", top: 0, left: 0, width: "100%", height: "100%", zIndex: 0, }, }); export default React.memo(React.forwardRef(VisionCamera));