chore: Remove semicolons (#1846)

* chore: Disable `semi` in Prettier

* chore: Format w/o semi

* Remove more `;`

* Lint example

* More ;
This commit is contained in:
Marc Rousavy 2023-09-26 11:39:17 +02:00 committed by GitHub
parent f7428f26a4
commit 14721d314f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
69 changed files with 998 additions and 999 deletions

View File

@ -1,3 +1,3 @@
module.exports = { module.exports = {
presets: [require.resolve('@docusaurus/core/lib/babel/preset')], presets: [require.resolve('@docusaurus/core/lib/babel/preset')],
}; }

View File

@ -4,7 +4,7 @@ title: Taking Photos/Recording Videos
sidebar_label: Taking Photos/Recording Videos sidebar_label: Taking Photos/Recording Videos
--- ---
import useBaseUrl from '@docusaurus/useBaseUrl'; import useBaseUrl from '@docusaurus/useBaseUrl'
<div> <div>
<svg xmlns="http://www.w3.org/2000/svg" width="283" height="535" style={{ float: 'right' }}> <svg xmlns="http://www.w3.org/2000/svg" width="283" height="535" style={{ float: 'right' }}>

View File

@ -4,9 +4,9 @@ title: Camera Devices
sidebar_label: Camera Devices sidebar_label: Camera Devices
--- ---
import Tabs from '@theme/Tabs'; import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'; import TabItem from '@theme/TabItem'
import useBaseUrl from '@docusaurus/useBaseUrl'; import useBaseUrl from '@docusaurus/useBaseUrl'
<div> <div>
<svg xmlns="http://www.w3.org/2000/svg" width="283" height="535" style={{ float: 'right' }}> <svg xmlns="http://www.w3.org/2000/svg" width="283" height="535" style={{ float: 'right' }}>

View File

@ -4,7 +4,7 @@ title: Camera Errors
sidebar_label: Camera Errors sidebar_label: Camera Errors
--- ---
import useBaseUrl from '@docusaurus/useBaseUrl'; import useBaseUrl from '@docusaurus/useBaseUrl'
<div> <div>
<img align="right" width="283" src={useBaseUrl("img/example_error.png")} /> <img align="right" width="283" src={useBaseUrl("img/example_error.png")} />

View File

@ -4,9 +4,9 @@ title: Camera Formats
sidebar_label: Camera Formats sidebar_label: Camera Formats
--- ---
import Tabs from '@theme/Tabs'; import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'; import TabItem from '@theme/TabItem'
import useBaseUrl from '@docusaurus/useBaseUrl'; import useBaseUrl from '@docusaurus/useBaseUrl'
<div> <div>
<img align="right" width="283" src={useBaseUrl("img/example.png")} /> <img align="right" width="283" src={useBaseUrl("img/example.png")} />

View File

@ -4,9 +4,9 @@ title: Frame Processors
sidebar_label: Frame Processors sidebar_label: Frame Processors
--- ---
import Tabs from '@theme/Tabs'; import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'; import TabItem from '@theme/TabItem'
import useBaseUrl from '@docusaurus/useBaseUrl'; import useBaseUrl from '@docusaurus/useBaseUrl'
<div> <div>
<svg xmlns="http://www.w3.org/2000/svg" width="283" height="535" style={{ float: 'right' }}> <svg xmlns="http://www.w3.org/2000/svg" width="283" height="535" style={{ float: 'right' }}>

View File

@ -4,9 +4,9 @@ title: Creating Frame Processor Plugins
sidebar_label: Overview sidebar_label: Overview
--- ---
import useBaseUrl from '@docusaurus/useBaseUrl'; import useBaseUrl from '@docusaurus/useBaseUrl'
import Tabs from '@theme/Tabs'; import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'; import TabItem from '@theme/TabItem'
## Overview ## Overview
@ -80,7 +80,7 @@ Which returns a [`Frame`](https://github.com/mrousavy/react-native-vision-camera
```js ```js
const frameProcessor = useFrameProcessor((frame) => { const frameProcessor = useFrameProcessor((frame) => {
'worklet'; 'worklet'
// creates a new `Frame` that's 720x480 // creates a new `Frame` that's 720x480
const resizedFrame = resize(frame, 720, 480) const resizedFrame = resize(frame, 720, 480)

View File

@ -4,9 +4,9 @@ title: Drawing to a Frame (Skia)
sidebar_label: Drawing to a Frame (Skia) sidebar_label: Drawing to a Frame (Skia)
--- ---
import Tabs from '@theme/Tabs'; import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'; import TabItem from '@theme/TabItem'
import useBaseUrl from '@docusaurus/useBaseUrl'; import useBaseUrl from '@docusaurus/useBaseUrl'
<div> <div>
<svg xmlns="http://www.w3.org/2000/svg" width="283" height="535" style={{ float: 'right' }}> <svg xmlns="http://www.w3.org/2000/svg" width="283" height="535" style={{ float: 'right' }}>

View File

@ -4,9 +4,9 @@ title: Frame Processors Tips
sidebar_label: Frame Processors Tips sidebar_label: Frame Processors Tips
--- ---
import Tabs from '@theme/Tabs'; import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'; import TabItem from '@theme/TabItem'
import useBaseUrl from '@docusaurus/useBaseUrl'; import useBaseUrl from '@docusaurus/useBaseUrl'
## Avoiding Frame-drops ## Avoiding Frame-drops

View File

@ -4,8 +4,8 @@ title: Creating Frame Processor Plugins
sidebar_label: Creating Frame Processor Plugins (Android) sidebar_label: Creating Frame Processor Plugins (Android)
--- ---
import Tabs from '@theme/Tabs'; import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'; import TabItem from '@theme/TabItem'
## Creating a Frame Processor Plugin for Android ## Creating a Frame Processor Plugin for Android

View File

@ -4,8 +4,8 @@ title: Creating Frame Processor Plugins
sidebar_label: Creating Frame Processor Plugins (iOS) sidebar_label: Creating Frame Processor Plugins (iOS)
--- ---
import Tabs from '@theme/Tabs'; import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'; import TabItem from '@theme/TabItem'
## Creating a Frame Processor Plugin for iOS ## Creating a Frame Processor Plugin for iOS

View File

@ -4,9 +4,9 @@ title: HDR
sidebar_label: HDR sidebar_label: HDR
--- ---
import Tabs from '@theme/Tabs'; import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'; import TabItem from '@theme/TabItem'
import useBaseUrl from '@docusaurus/useBaseUrl'; import useBaseUrl from '@docusaurus/useBaseUrl'
## What is HDR? ## What is HDR?

View File

@ -4,7 +4,7 @@ title: Lifecycle
sidebar_label: Lifecycle sidebar_label: Lifecycle
--- ---
import useBaseUrl from '@docusaurus/useBaseUrl'; import useBaseUrl from '@docusaurus/useBaseUrl'
<div> <div>
<img align="right" width="283" src={useBaseUrl("img/example.png")} /> <img align="right" width="283" src={useBaseUrl("img/example.png")} />

View File

@ -4,7 +4,7 @@ title: Mocking
sidebar_label: Mocking sidebar_label: Mocking
--- ---
import useBaseUrl from '@docusaurus/useBaseUrl'; import useBaseUrl from '@docusaurus/useBaseUrl'
<div> <div>
<img align="right" width="283" src={useBaseUrl("img/11_back.png")} /> <img align="right" width="283" src={useBaseUrl("img/11_back.png")} />
@ -22,8 +22,8 @@ In order to override React Native modules, allow bundler to use the flag `RN_SRC
Add to your [Metro Config](https://facebook.github.io/metro/docs/configuration/): Add to your [Metro Config](https://facebook.github.io/metro/docs/configuration/):
```js ```js
const { getDefaultConfig } = require("metro-config"); const { getDefaultConfig } = require("metro-config")
const { resolver: defaultResolver } = getDefaultConfig.getDefaultValues(); const { resolver: defaultResolver } = getDefaultConfig.getDefaultValues()
module.exports = { module.exports = {
... ...
@ -34,8 +34,7 @@ module.exports = {
...defaultResolver.sourceExts, ...defaultResolver.sourceExts,
], ],
}, },
}; }
``` ```
### Create proxy for original and mocked modules ### Create proxy for original and mocked modules
@ -51,19 +50,18 @@ Define your mocks following the [original definitions](https://github.com/mrousa
```js ```js
// vision-camera.js // vision-camera.js
import { Camera, sortDevices } from 'react-native-vision-camera'; import { Camera, sortDevices } from 'react-native-vision-camera'
export const VisionCamera = Camera; export const VisionCamera = Camera
export const visionCameraSortDevices = sortDevices;
``` ```
```js ```js
// vision-camera.e2e.js // vision-camera.e2e.js
import React from 'react'; import React from 'react'
import RNFS, { writeFile } from 'react-native-fs'; import RNFS, { writeFile } from 'react-native-fs'
console.log('[DETOX] Using mocked react-native-vision-camera'); console.log('[DETOX] Using mocked react-native-vision-camera')
export class VisionCamera extends React.PureComponent { export class VisionCamera extends React.PureComponent {
static getAvailableCameraDevices() { static getAvailableCameraDevices() {
@ -73,32 +71,30 @@ export class VisionCamera extends React.PureComponent {
position: 'back', position: 'back',
}, },
] ]
); )
} }
static async getCameraPermissionStatus() { static async getCameraPermissionStatus() {
return 'granted'; return 'granted'
} }
static async requestCameraPermission() { static async requestCameraPermission() {
return 'granted'; return 'granted'
} }
async takePhoto() { async takePhoto() {
const writePath = `${RNFS.DocumentDirectoryPath}/simulated_camera_photo.png`; const writePath = `${RNFS.DocumentDirectoryPath}/simulated_camera_photo.png`
const imageDataBase64 = 'some_large_base_64_encoded_simulated_camera_photo'; const imageDataBase64 = 'some_large_base_64_encoded_simulated_camera_photo'
await writeFile(writePath, imageDataBase64, 'base64'); await writeFile(writePath, imageDataBase64, 'base64')
return { path: writePath }; return { path: writePath }
} }
render() { render() {
return null; return null
} }
} }
export const visionCameraSortDevices = (_left, _right) => 1;
``` ```
These mocked modules allows us to get granted camera permissions, get one back camera These mocked modules allows us to get granted camera permissions, get one back camera
@ -111,10 +107,10 @@ we must reference the proxy module.
```ts ```ts
// before // before
import { Camera } from 'react-native-vision-camera'; import { Camera } from 'react-native-vision-camera'
// now // now
import { VisionCamera } from '/your_path_to_created_folder/vision-camera/vision-camera'; import { VisionCamera } from '/your_path_to_created_folder/vision-camera/vision-camera'
``` ```
### Trigger ### Trigger

View File

@ -4,9 +4,9 @@ title: Performance
sidebar_label: Performance sidebar_label: Performance
--- ---
import Tabs from '@theme/Tabs'; import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'; import TabItem from '@theme/TabItem'
import useBaseUrl from '@docusaurus/useBaseUrl'; import useBaseUrl from '@docusaurus/useBaseUrl'
## Performance of VisionCamera ## Performance of VisionCamera

View File

@ -5,9 +5,9 @@ sidebar_label: Getting Started
slug: /guides slug: /guides
--- ---
import Tabs from '@theme/Tabs'; import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'; import TabItem from '@theme/TabItem'
import useBaseUrl from '@docusaurus/useBaseUrl'; import useBaseUrl from '@docusaurus/useBaseUrl'
<div> <div>
<img align="right" width="283" src={useBaseUrl("img/example_intro.png")} /> <img align="right" width="283" src={useBaseUrl("img/example_intro.png")} />

View File

@ -4,9 +4,9 @@ title: Video Stabilization
sidebar_label: Video Stabilization sidebar_label: Video Stabilization
--- ---
import Tabs from '@theme/Tabs'; import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'; import TabItem from '@theme/TabItem'
import useBaseUrl from '@docusaurus/useBaseUrl'; import useBaseUrl from '@docusaurus/useBaseUrl'
## What is Video Stabilization? ## What is Video Stabilization?

View File

@ -4,9 +4,9 @@ title: Troubleshooting
sidebar_label: Troubleshooting sidebar_label: Troubleshooting
--- ---
import Tabs from '@theme/Tabs'; import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'; import TabItem from '@theme/TabItem'
import useBaseUrl from '@docusaurus/useBaseUrl'; import useBaseUrl from '@docusaurus/useBaseUrl'
<div> <div>
<img align="right" width="283" src={useBaseUrl("img/11_back.png")} /> <img align="right" width="283" src={useBaseUrl("img/11_back.png")} />

View File

@ -4,7 +4,7 @@ title: Zooming
sidebar_label: Zooming sidebar_label: Zooming
--- ---
import useBaseUrl from '@docusaurus/useBaseUrl'; import useBaseUrl from '@docusaurus/useBaseUrl'
<div> <div>
<svg xmlns="http://www.w3.org/2000/svg" width="283" height="535" style={{ float: 'right' }}> <svg xmlns="http://www.w3.org/2000/svg" width="283" height="535" style={{ float: 'right' }}>

View File

@ -166,4 +166,4 @@ module.exports = {
}, },
], ],
], ],
}; }

View File

@ -42,4 +42,4 @@ module.exports = {
} }
], ],
}, },
}; }

View File

@ -1,10 +1,10 @@
import React from 'react'; import React from 'react'
import clsx from 'clsx'; import clsx from 'clsx'
import Layout from '@theme/Layout'; import Layout from '@theme/Layout'
import Link from '@docusaurus/Link'; import Link from '@docusaurus/Link'
import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import useDocusaurusContext from '@docusaurus/useDocusaurusContext'
import useBaseUrl from '@docusaurus/useBaseUrl'; import useBaseUrl from '@docusaurus/useBaseUrl'
import styles from './styles.module.css'; import styles from './styles.module.css'
import { Analytics } from '@vercel/analytics/react' import { Analytics } from '@vercel/analytics/react'
const features = [ const features = [
@ -35,10 +35,10 @@ const features = [
</> </>
), ),
}, },
]; ]
function Feature({imageUrl, title, description}) { function Feature({imageUrl, title, description}) {
const imgUrl = useBaseUrl(imageUrl); const imgUrl = useBaseUrl(imageUrl)
return ( return (
<div className={clsx('col col--4', styles.feature)}> <div className={clsx('col col--4', styles.feature)}>
{imgUrl && ( {imgUrl && (
@ -49,12 +49,12 @@ function Feature({imageUrl, title, description}) {
<h3>{title}</h3> <h3>{title}</h3>
<p>{description}</p> <p>{description}</p>
</div> </div>
); )
} }
function Home() { function Home() {
const context = useDocusaurusContext(); const context = useDocusaurusContext()
const {siteConfig = {}} = context; const {siteConfig = {}} = context
return ( return (
<Layout <Layout
title="VisionCamera Documentation" title="VisionCamera Documentation"
@ -91,7 +91,7 @@ function Home() {
<Analytics /> <Analytics />
</main> </main>
</Layout> </Layout>
); )
} }
export default Home; export default Home

View File

@ -88,4 +88,4 @@ module.exports = {
globals: { globals: {
_log: 'readonly', _log: 'readonly',
}, },
}; }

View File

@ -3,7 +3,7 @@ module.exports = {
bracketSameLine: true, bracketSameLine: true,
singleQuote: true, singleQuote: true,
trailingComma: 'all', trailingComma: 'all',
semi: true, semi: false,
tabWidth: 2, tabWidth: 2,
useTabs: false, useTabs: false,
printWidth: 140 printWidth: 140

View File

@ -1 +1 @@
module.exports = require('./lib/commonjs/expo-plugin/withVisionCamera'); module.exports = require('./lib/commonjs/expo-plugin/withVisionCamera')

View File

@ -1,3 +1,3 @@
module.exports = { module.exports = {
presets: ['module:@react-native/babel-preset'], presets: ['module:@react-native/babel-preset'],
}; }

View File

@ -13,4 +13,4 @@ module.exports = {
ignorePatterns: ['babel.config.js', 'metro.config.js', '.eslintrc.js'], ignorePatterns: ['babel.config.js', 'metro.config.js', '.eslintrc.js'],
plugins: ['@typescript-eslint'], plugins: ['@typescript-eslint'],
extends: ['plugin:@typescript-eslint/recommended', '@react-native', '../.eslintrc.js'], extends: ['plugin:@typescript-eslint/recommended', '@react-native', '../.eslintrc.js'],
}; }

View File

@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/no-var-requires */ /* eslint-disable @typescript-eslint/no-var-requires */
const path = require('path'); const path = require('path')
const pak = require('../package.json'); const pak = require('../package.json')
module.exports = { module.exports = {
presets: ['module:metro-react-native-babel-preset'], presets: ['module:metro-react-native-babel-preset'],
@ -16,4 +16,4 @@ module.exports = {
}, },
], ],
], ],
}; }

View File

@ -1,5 +1,5 @@
import 'react-native-gesture-handler'; import 'react-native-gesture-handler'
import { AppRegistry } from 'react-native'; import { AppRegistry } from 'react-native'
import { App } from './src/App'; import { App } from './src/App'
AppRegistry.registerComponent('VisionCameraExample', () => App); AppRegistry.registerComponent('VisionCameraExample', () => App)

View File

@ -1,11 +1,11 @@
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config'); const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config')
const path = require('path'); const path = require('path')
const escape = require('escape-string-regexp'); const escape = require('escape-string-regexp')
const exclusionList = require('metro-config/src/defaults/exclusionList'); const exclusionList = require('metro-config/src/defaults/exclusionList')
const pak = require('../package.json'); const pak = require('../package.json')
const root = path.resolve(__dirname, '..'); const root = path.resolve(__dirname, '..')
const modules = Object.keys({ ...pak.peerDependencies }); const modules = Object.keys({ ...pak.peerDependencies })
/** /**
* Metro configuration * Metro configuration
@ -27,8 +27,8 @@ const config = {
), ),
extraNodeModules: modules.reduce((acc, name) => { extraNodeModules: modules.reduce((acc, name) => {
acc[name] = path.join(__dirname, 'node_modules', name); acc[name] = path.join(__dirname, 'node_modules', name)
return acc; return acc
}, {}), }, {}),
}, },
@ -40,6 +40,6 @@ const config = {
}, },
}), }),
}, },
}; }
module.exports = mergeConfig(getDefaultConfig(__dirname), config); module.exports = mergeConfig(getDefaultConfig(__dirname), config)

View File

@ -8,7 +8,7 @@
"ios": "react-native run-ios", "ios": "react-native run-ios",
"start": "react-native start", "start": "react-native start",
"pods": "cd ios && pod install", "pods": "cd ios && pod install",
"lint": "eslint .", "lint": "eslint . --fix",
"lint-ci": "yarn lint -f ../node_modules/@firmnav/eslint-github-actions-formatter/dist/formatter.js", "lint-ci": "yarn lint -f ../node_modules/@firmnav/eslint-github-actions-formatter/dist/formatter.js",
"typescript": "tsc --noEmit" "typescript": "tsc --noEmit"
}, },

View File

@ -1,32 +1,32 @@
import { NavigationContainer } from '@react-navigation/native'; import { NavigationContainer } from '@react-navigation/native'
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react'
import { createNativeStackNavigator } from '@react-navigation/native-stack'; import { createNativeStackNavigator } from '@react-navigation/native-stack'
import { PermissionsPage } from './PermissionsPage'; import { PermissionsPage } from './PermissionsPage'
import { MediaPage } from './MediaPage'; import { MediaPage } from './MediaPage'
import { CameraPage } from './CameraPage'; import { CameraPage } from './CameraPage'
import type { Routes } from './Routes'; import type { Routes } from './Routes'
import { Camera, CameraPermissionStatus } from 'react-native-vision-camera'; import { Camera, CameraPermissionStatus } from 'react-native-vision-camera'
import { GestureHandlerRootView } from 'react-native-gesture-handler'; import { GestureHandlerRootView } from 'react-native-gesture-handler'
const Stack = createNativeStackNavigator<Routes>(); const Stack = createNativeStackNavigator<Routes>()
export function App(): React.ReactElement | null { export function App(): React.ReactElement | null {
const [cameraPermission, setCameraPermission] = useState<CameraPermissionStatus>(); const [cameraPermission, setCameraPermission] = useState<CameraPermissionStatus>()
const [microphonePermission, setMicrophonePermission] = useState<CameraPermissionStatus>(); const [microphonePermission, setMicrophonePermission] = useState<CameraPermissionStatus>()
useEffect(() => { useEffect(() => {
Camera.getCameraPermissionStatus().then(setCameraPermission); Camera.getCameraPermissionStatus().then(setCameraPermission)
Camera.getMicrophonePermissionStatus().then(setMicrophonePermission); Camera.getMicrophonePermissionStatus().then(setMicrophonePermission)
}, []); }, [])
console.log(`Re-rendering Navigator. Camera: ${cameraPermission} | Microphone: ${microphonePermission}`); console.log(`Re-rendering Navigator. Camera: ${cameraPermission} | Microphone: ${microphonePermission}`)
if (cameraPermission == null || microphonePermission == null) { if (cameraPermission == null || microphonePermission == null) {
// still loading // still loading
return null; return null
} }
const showPermissionsPage = cameraPermission !== 'granted' || microphonePermission === 'not-determined'; const showPermissionsPage = cameraPermission !== 'granted' || microphonePermission === 'not-determined'
return ( return (
<NavigationContainer> <NavigationContainer>
<GestureHandlerRootView style={{ flex: 1 }}> <GestureHandlerRootView style={{ flex: 1 }}>
@ -50,5 +50,5 @@ export function App(): React.ReactElement | null {
</Stack.Navigator> </Stack.Navigator>
</GestureHandlerRootView> </GestureHandlerRootView>
</NavigationContainer> </NavigationContainer>
); )
} }

View File

@ -1,135 +1,135 @@
import * as React from 'react'; import * as React from 'react'
import { useRef, useState, useCallback, useMemo } from 'react'; import { useRef, useState, useCallback, useMemo } from 'react'
import { StyleSheet, Text, View } from 'react-native'; import { StyleSheet, Text, View } from 'react-native'
import { PinchGestureHandler, PinchGestureHandlerGestureEvent, TapGestureHandler } from 'react-native-gesture-handler'; import { PinchGestureHandler, PinchGestureHandlerGestureEvent, TapGestureHandler } from 'react-native-gesture-handler'
import { CameraRuntimeError, PhotoFile, useCameraDevice, useCameraFormat, useFrameProcessor, VideoFile } from 'react-native-vision-camera'; import { CameraRuntimeError, PhotoFile, useCameraDevice, useCameraFormat, useFrameProcessor, VideoFile } from 'react-native-vision-camera'
import { Camera } from 'react-native-vision-camera'; import { Camera } from 'react-native-vision-camera'
import { CONTENT_SPACING, MAX_ZOOM_FACTOR, SAFE_AREA_PADDING, SCREEN_HEIGHT, SCREEN_WIDTH } from './Constants'; import { CONTENT_SPACING, MAX_ZOOM_FACTOR, SAFE_AREA_PADDING, SCREEN_HEIGHT, SCREEN_WIDTH } from './Constants'
import Reanimated, { Extrapolate, interpolate, useAnimatedGestureHandler, useAnimatedProps, useSharedValue } from 'react-native-reanimated'; import Reanimated, { Extrapolate, interpolate, useAnimatedGestureHandler, useAnimatedProps, useSharedValue } from 'react-native-reanimated'
import { useEffect } from 'react'; import { useEffect } from 'react'
import { useIsForeground } from './hooks/useIsForeground'; import { useIsForeground } from './hooks/useIsForeground'
import { StatusBarBlurBackground } from './views/StatusBarBlurBackground'; import { StatusBarBlurBackground } from './views/StatusBarBlurBackground'
import { CaptureButton } from './views/CaptureButton'; import { CaptureButton } from './views/CaptureButton'
import { PressableOpacity } from 'react-native-pressable-opacity'; import { PressableOpacity } from 'react-native-pressable-opacity'
import MaterialIcon from 'react-native-vector-icons/MaterialCommunityIcons'; import MaterialIcon from 'react-native-vector-icons/MaterialCommunityIcons'
import IonIcon from 'react-native-vector-icons/Ionicons'; import IonIcon from 'react-native-vector-icons/Ionicons'
import type { Routes } from './Routes'; import type { Routes } from './Routes'
import type { NativeStackScreenProps } from '@react-navigation/native-stack'; import type { NativeStackScreenProps } from '@react-navigation/native-stack'
import { useIsFocused } from '@react-navigation/core'; import { useIsFocused } from '@react-navigation/core'
import { examplePlugin } from './frame-processors/ExamplePlugin'; import { examplePlugin } from './frame-processors/ExamplePlugin'
const ReanimatedCamera = Reanimated.createAnimatedComponent(Camera); const ReanimatedCamera = Reanimated.createAnimatedComponent(Camera)
Reanimated.addWhitelistedNativeProps({ Reanimated.addWhitelistedNativeProps({
zoom: true, zoom: true,
}); })
const SCALE_FULL_ZOOM = 3; const SCALE_FULL_ZOOM = 3
const BUTTON_SIZE = 40; const BUTTON_SIZE = 40
type Props = NativeStackScreenProps<Routes, 'CameraPage'>; type Props = NativeStackScreenProps<Routes, 'CameraPage'>
export function CameraPage({ navigation }: Props): React.ReactElement { export function CameraPage({ navigation }: Props): React.ReactElement {
const camera = useRef<Camera>(null); const camera = useRef<Camera>(null)
const [isCameraInitialized, setIsCameraInitialized] = useState(false); const [isCameraInitialized, setIsCameraInitialized] = useState(false)
const [hasMicrophonePermission, setHasMicrophonePermission] = useState(false); const [hasMicrophonePermission, setHasMicrophonePermission] = useState(false)
const zoom = useSharedValue(0); const zoom = useSharedValue(0)
const isPressingButton = useSharedValue(false); const isPressingButton = useSharedValue(false)
// check if camera page is active // check if camera page is active
const isFocussed = useIsFocused(); const isFocussed = useIsFocused()
const isForeground = useIsForeground(); const isForeground = useIsForeground()
const isActive = isFocussed && isForeground; const isActive = isFocussed && isForeground
const [cameraPosition, setCameraPosition] = useState<'front' | 'back'>('back'); const [cameraPosition, setCameraPosition] = useState<'front' | 'back'>('back')
const [enableHdr, setEnableHdr] = useState(false); const [enableHdr, setEnableHdr] = useState(false)
const [flash, setFlash] = useState<'off' | 'on'>('off'); const [flash, setFlash] = useState<'off' | 'on'>('off')
const [enableNightMode, setEnableNightMode] = useState(false); const [enableNightMode, setEnableNightMode] = useState(false)
// camera format settings // camera format settings
const device = useCameraDevice(cameraPosition, { const device = useCameraDevice(cameraPosition, {
physicalDevices: ['ultra-wide-angle-camera', 'wide-angle-camera', 'telephoto-camera'], physicalDevices: ['ultra-wide-angle-camera', 'wide-angle-camera', 'telephoto-camera'],
}); })
const [targetFps, setTargetFps] = useState(60); const [targetFps, setTargetFps] = useState(60)
const screenAspectRatio = SCREEN_HEIGHT / SCREEN_WIDTH; const screenAspectRatio = SCREEN_HEIGHT / SCREEN_WIDTH
const format = useCameraFormat(device, [ const format = useCameraFormat(device, [
{ fps: targetFps }, { fps: targetFps },
{ videoAspectRatio: screenAspectRatio }, { videoAspectRatio: screenAspectRatio },
{ videoResolution: 'max' }, { videoResolution: 'max' },
{ photoAspectRatio: screenAspectRatio }, { photoAspectRatio: screenAspectRatio },
{ photoResolution: 'max' }, { photoResolution: 'max' },
]); ])
const fps = Math.min(format?.maxFps ?? 1, targetFps); const fps = Math.min(format?.maxFps ?? 1, targetFps)
const supportsFlash = device?.hasFlash ?? false; const supportsFlash = device?.hasFlash ?? false
const supportsHdr = format?.supportsPhotoHDR; const supportsHdr = format?.supportsPhotoHDR
const supports60Fps = useMemo(() => device?.formats.some((f) => f.maxFps >= 60), [device?.formats]); const supports60Fps = useMemo(() => device?.formats.some((f) => f.maxFps >= 60), [device?.formats])
const canToggleNightMode = device?.supportsLowLightBoost ?? false; const canToggleNightMode = device?.supportsLowLightBoost ?? false
//#region Animated Zoom //#region Animated Zoom
// This just maps the zoom factor to a percentage value. // This just maps the zoom factor to a percentage value.
// so e.g. for [min, neutr., max] values [1, 2, 128] this would result in [0, 0.0081, 1] // so e.g. for [min, neutr., max] values [1, 2, 128] this would result in [0, 0.0081, 1]
const minZoom = device?.minZoom ?? 1; const minZoom = device?.minZoom ?? 1
const maxZoom = Math.min(device?.maxZoom ?? 1, MAX_ZOOM_FACTOR); const maxZoom = Math.min(device?.maxZoom ?? 1, MAX_ZOOM_FACTOR)
const cameraAnimatedProps = useAnimatedProps(() => { const cameraAnimatedProps = useAnimatedProps(() => {
const z = Math.max(Math.min(zoom.value, maxZoom), minZoom); const z = Math.max(Math.min(zoom.value, maxZoom), minZoom)
return { return {
zoom: z, zoom: z,
}; }
}, [maxZoom, minZoom, zoom]); }, [maxZoom, minZoom, zoom])
//#endregion //#endregion
//#region Callbacks //#region Callbacks
const setIsPressingButton = useCallback( const setIsPressingButton = useCallback(
(_isPressingButton: boolean) => { (_isPressingButton: boolean) => {
isPressingButton.value = _isPressingButton; isPressingButton.value = _isPressingButton
}, },
[isPressingButton], [isPressingButton],
); )
// Camera callbacks // Camera callbacks
const onError = useCallback((error: CameraRuntimeError) => { const onError = useCallback((error: CameraRuntimeError) => {
console.error(error); console.error(error)
}, []); }, [])
const onInitialized = useCallback(() => { const onInitialized = useCallback(() => {
console.log('Camera initialized!'); console.log('Camera initialized!')
setIsCameraInitialized(true); setIsCameraInitialized(true)
}, []); }, [])
const onMediaCaptured = useCallback( const onMediaCaptured = useCallback(
(media: PhotoFile | VideoFile, type: 'photo' | 'video') => { (media: PhotoFile | VideoFile, type: 'photo' | 'video') => {
console.log(`Media captured! ${JSON.stringify(media)}`); console.log(`Media captured! ${JSON.stringify(media)}`)
navigation.navigate('MediaPage', { navigation.navigate('MediaPage', {
path: media.path, path: media.path,
type: type, type: type,
}); })
}, },
[navigation], [navigation],
); )
const onFlipCameraPressed = useCallback(() => { const onFlipCameraPressed = useCallback(() => {
setCameraPosition((p) => (p === 'back' ? 'front' : 'back')); setCameraPosition((p) => (p === 'back' ? 'front' : 'back'))
}, []); }, [])
const onFlashPressed = useCallback(() => { const onFlashPressed = useCallback(() => {
setFlash((f) => (f === 'off' ? 'on' : 'off')); setFlash((f) => (f === 'off' ? 'on' : 'off'))
}, []); }, [])
//#endregion //#endregion
//#region Tap Gesture //#region Tap Gesture
const onDoubleTap = useCallback(() => { const onDoubleTap = useCallback(() => {
onFlipCameraPressed(); onFlipCameraPressed()
}, [onFlipCameraPressed]); }, [onFlipCameraPressed])
//#endregion //#endregion
//#region Effects //#region Effects
const neutralZoom = device?.neutralZoom ?? 1; const neutralZoom = device?.neutralZoom ?? 1
useEffect(() => { useEffect(() => {
// Run everytime the neutralZoomScaled value changes. (reset zoom when device changes) // Run everytime the neutralZoomScaled value changes. (reset zoom when device changes)
zoom.value = neutralZoom; zoom.value = neutralZoom
}, [neutralZoom, zoom]); }, [neutralZoom, zoom])
useEffect(() => { useEffect(() => {
Camera.getMicrophonePermissionStatus().then((status) => setHasMicrophonePermission(status === 'granted')); Camera.getMicrophonePermissionStatus().then((status) => setHasMicrophonePermission(status === 'granted'))
}, []); }, [])
//#endregion //#endregion
//#region Pinch to Zoom Gesture //#region Pinch to Zoom Gesture
@ -137,32 +137,32 @@ export function CameraPage({ navigation }: Props): React.ReactElement {
// function does not appear linear to the user. (aka zoom 0.1 -> 0.2 does not look equal in difference as 0.8 -> 0.9) // function does not appear linear to the user. (aka zoom 0.1 -> 0.2 does not look equal in difference as 0.8 -> 0.9)
const onPinchGesture = useAnimatedGestureHandler<PinchGestureHandlerGestureEvent, { startZoom?: number }>({ const onPinchGesture = useAnimatedGestureHandler<PinchGestureHandlerGestureEvent, { startZoom?: number }>({
onStart: (_, context) => { onStart: (_, context) => {
context.startZoom = zoom.value; context.startZoom = zoom.value
}, },
onActive: (event, context) => { onActive: (event, context) => {
// we're trying to map the scale gesture to a linear zoom here // we're trying to map the scale gesture to a linear zoom here
const startZoom = context.startZoom ?? 0; const startZoom = context.startZoom ?? 0
const scale = interpolate(event.scale, [1 - 1 / SCALE_FULL_ZOOM, 1, SCALE_FULL_ZOOM], [-1, 0, 1], Extrapolate.CLAMP); const scale = interpolate(event.scale, [1 - 1 / SCALE_FULL_ZOOM, 1, SCALE_FULL_ZOOM], [-1, 0, 1], Extrapolate.CLAMP)
zoom.value = interpolate(scale, [-1, 0, 1], [minZoom, startZoom, maxZoom], Extrapolate.CLAMP); zoom.value = interpolate(scale, [-1, 0, 1], [minZoom, startZoom, maxZoom], Extrapolate.CLAMP)
}, },
}); })
//#endregion //#endregion
if (device != null && format != null) { if (device != null && format != null) {
console.log( console.log(
`Re-rendering camera page with ${isActive ? 'active' : 'inactive'} camera. ` + `Re-rendering camera page with ${isActive ? 'active' : 'inactive'} camera. ` +
`Device: "${device.name}" (${format.photoWidth}x${format.photoHeight} photo / ${format.videoWidth}x${format.videoHeight} video @ ${fps}fps)`, `Device: "${device.name}" (${format.photoWidth}x${format.photoHeight} photo / ${format.videoWidth}x${format.videoHeight} video @ ${fps}fps)`,
); )
} else { } else {
console.log('re-rendering camera page without active camera'); console.log('re-rendering camera page without active camera')
} }
const frameProcessor = useFrameProcessor((frame) => { const frameProcessor = useFrameProcessor((frame) => {
'worklet'; 'worklet'
console.log(`${frame.timestamp}: ${frame.width}x${frame.height} ${frame.pixelFormat} Frame (${frame.orientation})`); console.log(`${frame.timestamp}: ${frame.width}x${frame.height} ${frame.pixelFormat} Frame (${frame.orientation})`)
examplePlugin(frame); examplePlugin(frame)
}, []); }, [])
return ( return (
<View style={styles.container}> <View style={styles.container}>
@ -235,7 +235,7 @@ export function CameraPage({ navigation }: Props): React.ReactElement {
)} )}
</View> </View>
</View> </View>
); )
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({
@ -268,4 +268,4 @@ const styles = StyleSheet.create({
fontWeight: 'bold', fontWeight: 'bold',
textAlign: 'center', textAlign: 'center',
}, },
}); })

View File

@ -1,28 +1,28 @@
import { Dimensions, Platform } from 'react-native'; import { Dimensions, Platform } from 'react-native'
import StaticSafeAreaInsets from 'react-native-static-safe-area-insets'; import StaticSafeAreaInsets from 'react-native-static-safe-area-insets'
export const CONTENT_SPACING = 15; export const CONTENT_SPACING = 15
const SAFE_BOTTOM = const SAFE_BOTTOM =
Platform.select({ Platform.select({
ios: StaticSafeAreaInsets.safeAreaInsetsBottom, ios: StaticSafeAreaInsets.safeAreaInsetsBottom,
}) ?? 0; }) ?? 0
export const SAFE_AREA_PADDING = { export const SAFE_AREA_PADDING = {
paddingLeft: StaticSafeAreaInsets.safeAreaInsetsLeft + CONTENT_SPACING, paddingLeft: StaticSafeAreaInsets.safeAreaInsetsLeft + CONTENT_SPACING,
paddingTop: StaticSafeAreaInsets.safeAreaInsetsTop + CONTENT_SPACING, paddingTop: StaticSafeAreaInsets.safeAreaInsetsTop + CONTENT_SPACING,
paddingRight: StaticSafeAreaInsets.safeAreaInsetsRight + CONTENT_SPACING, paddingRight: StaticSafeAreaInsets.safeAreaInsetsRight + CONTENT_SPACING,
paddingBottom: SAFE_BOTTOM + CONTENT_SPACING, paddingBottom: SAFE_BOTTOM + CONTENT_SPACING,
}; }
// The maximum zoom _factor_ you should be able to zoom in // The maximum zoom _factor_ you should be able to zoom in
export const MAX_ZOOM_FACTOR = 20; export const MAX_ZOOM_FACTOR = 20
export const SCREEN_WIDTH = Dimensions.get('window').width; export const SCREEN_WIDTH = Dimensions.get('window').width
export const SCREEN_HEIGHT = Platform.select<number>({ export const SCREEN_HEIGHT = Platform.select<number>({
android: Dimensions.get('screen').height - StaticSafeAreaInsets.safeAreaInsetsBottom, android: Dimensions.get('screen').height - StaticSafeAreaInsets.safeAreaInsetsBottom,
ios: Dimensions.get('window').height, ios: Dimensions.get('window').height,
}) as number; }) as number
// Capture Button // Capture Button
export const CAPTURE_BUTTON_SIZE = 78; export const CAPTURE_BUTTON_SIZE = 78

View File

@ -1,82 +1,82 @@
import React, { useCallback, useMemo, useState } from 'react'; import React, { useCallback, useMemo, useState } from 'react'
import { StyleSheet, View, ActivityIndicator, PermissionsAndroid, Platform } from 'react-native'; import { StyleSheet, View, ActivityIndicator, PermissionsAndroid, Platform } from 'react-native'
import Video, { LoadError, OnLoadData } from 'react-native-video'; import Video, { LoadError, OnLoadData } from 'react-native-video'
import { SAFE_AREA_PADDING } from './Constants'; import { SAFE_AREA_PADDING } from './Constants'
import { useIsForeground } from './hooks/useIsForeground'; import { useIsForeground } from './hooks/useIsForeground'
import { PressableOpacity } from 'react-native-pressable-opacity'; import { PressableOpacity } from 'react-native-pressable-opacity'
import IonIcon from 'react-native-vector-icons/Ionicons'; import IonIcon from 'react-native-vector-icons/Ionicons'
import { Alert } from 'react-native'; import { Alert } from 'react-native'
import { CameraRoll } from '@react-native-camera-roll/camera-roll'; import { CameraRoll } from '@react-native-camera-roll/camera-roll'
import { StatusBarBlurBackground } from './views/StatusBarBlurBackground'; import { StatusBarBlurBackground } from './views/StatusBarBlurBackground'
import type { NativeStackScreenProps } from '@react-navigation/native-stack'; import type { NativeStackScreenProps } from '@react-navigation/native-stack'
import type { Routes } from './Routes'; import type { Routes } from './Routes'
import { useIsFocused } from '@react-navigation/core'; import { useIsFocused } from '@react-navigation/core'
import FastImage, { OnLoadEvent } from 'react-native-fast-image'; import FastImage, { OnLoadEvent } from 'react-native-fast-image'
const requestSavePermission = async (): Promise<boolean> => { const requestSavePermission = async (): Promise<boolean> => {
if (Platform.OS !== 'android') return true; if (Platform.OS !== 'android') return true
const permission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE; const permission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
if (permission == null) return false; if (permission == null) return false
let hasPermission = await PermissionsAndroid.check(permission); let hasPermission = await PermissionsAndroid.check(permission)
if (!hasPermission) { if (!hasPermission) {
const permissionRequestResult = await PermissionsAndroid.request(permission); const permissionRequestResult = await PermissionsAndroid.request(permission)
hasPermission = permissionRequestResult === 'granted'; hasPermission = permissionRequestResult === 'granted'
} }
return hasPermission; return hasPermission
}; }
const isVideoOnLoadEvent = (event: OnLoadData | OnLoadEvent): event is OnLoadData => 'duration' in event && 'naturalSize' in event; const isVideoOnLoadEvent = (event: OnLoadData | OnLoadEvent): event is OnLoadData => 'duration' in event && 'naturalSize' in event
type Props = NativeStackScreenProps<Routes, 'MediaPage'>; type Props = NativeStackScreenProps<Routes, 'MediaPage'>
export function MediaPage({ navigation, route }: Props): React.ReactElement { export function MediaPage({ navigation, route }: Props): React.ReactElement {
const { path, type } = route.params; const { path, type } = route.params
const [hasMediaLoaded, setHasMediaLoaded] = useState(false); const [hasMediaLoaded, setHasMediaLoaded] = useState(false)
const isForeground = useIsForeground(); const isForeground = useIsForeground()
const isScreenFocused = useIsFocused(); const isScreenFocused = useIsFocused()
const isVideoPaused = !isForeground || !isScreenFocused; const isVideoPaused = !isForeground || !isScreenFocused
const [savingState, setSavingState] = useState<'none' | 'saving' | 'saved'>('none'); const [savingState, setSavingState] = useState<'none' | 'saving' | 'saved'>('none')
const onMediaLoad = useCallback((event: OnLoadData | OnLoadEvent) => { const onMediaLoad = useCallback((event: OnLoadData | OnLoadEvent) => {
if (isVideoOnLoadEvent(event)) { if (isVideoOnLoadEvent(event)) {
console.log( console.log(
`Video loaded. Size: ${event.naturalSize.width}x${event.naturalSize.height} (${event.naturalSize.orientation}, ${event.duration} seconds)`, `Video loaded. Size: ${event.naturalSize.width}x${event.naturalSize.height} (${event.naturalSize.orientation}, ${event.duration} seconds)`,
); )
} else { } else {
console.log(`Image loaded. Size: ${event.nativeEvent.width}x${event.nativeEvent.height}`); console.log(`Image loaded. Size: ${event.nativeEvent.width}x${event.nativeEvent.height}`)
} }
}, []); }, [])
const onMediaLoadEnd = useCallback(() => { const onMediaLoadEnd = useCallback(() => {
console.log('media has loaded.'); console.log('media has loaded.')
setHasMediaLoaded(true); setHasMediaLoaded(true)
}, []); }, [])
const onMediaLoadError = useCallback((error: LoadError) => { const onMediaLoadError = useCallback((error: LoadError) => {
console.log(`failed to load media: ${JSON.stringify(error)}`); console.log(`failed to load media: ${JSON.stringify(error)}`)
}, []); }, [])
const onSavePressed = useCallback(async () => { const onSavePressed = useCallback(async () => {
try { try {
setSavingState('saving'); setSavingState('saving')
const hasPermission = await requestSavePermission(); const hasPermission = await requestSavePermission()
if (!hasPermission) { if (!hasPermission) {
Alert.alert('Permission denied!', 'Vision Camera does not have permission to save the media to your camera roll.'); Alert.alert('Permission denied!', 'Vision Camera does not have permission to save the media to your camera roll.')
return; return
} }
await CameraRoll.save(`file://${path}`, { await CameraRoll.save(`file://${path}`, {
type: type, type: type,
}); })
setSavingState('saved'); setSavingState('saved')
} catch (e) { } catch (e) {
const message = e instanceof Error ? e.message : JSON.stringify(e); const message = e instanceof Error ? e.message : JSON.stringify(e)
setSavingState('none'); setSavingState('none')
Alert.alert('Failed to save!', `An unexpected error occured while trying to save your ${type}. ${message}`); Alert.alert('Failed to save!', `An unexpected error occured while trying to save your ${type}. ${message}`)
} }
}, [path, type]); }, [path, type])
const source = useMemo(() => ({ uri: `file://${path}` }), [path]); const source = useMemo(() => ({ uri: `file://${path}` }), [path])
const screenStyle = useMemo(() => ({ opacity: hasMediaLoaded ? 1 : 0 }), [hasMediaLoaded]); const screenStyle = useMemo(() => ({ opacity: hasMediaLoaded ? 1 : 0 }), [hasMediaLoaded])
return ( return (
<View style={[styles.container, screenStyle]}> <View style={[styles.container, screenStyle]}>
@ -116,7 +116,7 @@ export function MediaPage({ navigation, route }: Props): React.ReactElement {
<StatusBarBlurBackground /> <StatusBarBlurBackground />
</View> </View>
); )
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({
@ -148,4 +148,4 @@ const styles = StyleSheet.create({
}, },
textShadowRadius: 1, textShadowRadius: 1,
}, },
}); })

View File

@ -1,41 +1,41 @@
import type { NativeStackScreenProps } from '@react-navigation/native-stack'; import type { NativeStackScreenProps } from '@react-navigation/native-stack'
import React, { useCallback, useEffect, useState } from 'react'; import React, { useCallback, useEffect, useState } from 'react'
import { ImageRequireSource, Linking } from 'react-native'; import { ImageRequireSource, Linking } from 'react-native'
import { StyleSheet, View, Text, Image } from 'react-native'; import { StyleSheet, View, Text, Image } from 'react-native'
import { Camera, CameraPermissionStatus } from 'react-native-vision-camera'; import { Camera, CameraPermissionStatus } from 'react-native-vision-camera'
import { CONTENT_SPACING, SAFE_AREA_PADDING } from './Constants'; import { CONTENT_SPACING, SAFE_AREA_PADDING } from './Constants'
import type { Routes } from './Routes'; import type { Routes } from './Routes'
// eslint-disable-next-line @typescript-eslint/no-var-requires // eslint-disable-next-line @typescript-eslint/no-var-requires
const BANNER_IMAGE = require('./img/11.png') as ImageRequireSource; const BANNER_IMAGE = require('./img/11.png') as ImageRequireSource
type Props = NativeStackScreenProps<Routes, 'PermissionsPage'>; type Props = NativeStackScreenProps<Routes, 'PermissionsPage'>
export function PermissionsPage({ navigation }: Props): React.ReactElement { export function PermissionsPage({ navigation }: Props): React.ReactElement {
const [cameraPermissionStatus, setCameraPermissionStatus] = useState<CameraPermissionStatus>('not-determined'); const [cameraPermissionStatus, setCameraPermissionStatus] = useState<CameraPermissionStatus>('not-determined')
const [microphonePermissionStatus, setMicrophonePermissionStatus] = useState<CameraPermissionStatus>('not-determined'); const [microphonePermissionStatus, setMicrophonePermissionStatus] = useState<CameraPermissionStatus>('not-determined')
const requestMicrophonePermission = useCallback(async () => { const requestMicrophonePermission = useCallback(async () => {
console.log('Requesting microphone permission...'); console.log('Requesting microphone permission...')
const permission = await Camera.requestMicrophonePermission(); const permission = await Camera.requestMicrophonePermission()
console.log(`Microphone permission status: ${permission}`); console.log(`Microphone permission status: ${permission}`)
if (permission === 'denied') await Linking.openSettings(); if (permission === 'denied') await Linking.openSettings()
setMicrophonePermissionStatus(permission); setMicrophonePermissionStatus(permission)
}, []); }, [])
const requestCameraPermission = useCallback(async () => { const requestCameraPermission = useCallback(async () => {
console.log('Requesting camera permission...'); console.log('Requesting camera permission...')
const permission = await Camera.requestCameraPermission(); const permission = await Camera.requestCameraPermission()
console.log(`Camera permission status: ${permission}`); console.log(`Camera permission status: ${permission}`)
if (permission === 'denied') await Linking.openSettings(); if (permission === 'denied') await Linking.openSettings()
setCameraPermissionStatus(permission); setCameraPermissionStatus(permission)
}, []); }, [])
useEffect(() => { useEffect(() => {
if (cameraPermissionStatus === 'granted' && microphonePermissionStatus === 'granted') navigation.replace('CameraPage'); if (cameraPermissionStatus === 'granted' && microphonePermissionStatus === 'granted') navigation.replace('CameraPage')
}, [cameraPermissionStatus, microphonePermissionStatus, navigation]); }, [cameraPermissionStatus, microphonePermissionStatus, navigation])
return ( return (
<View style={styles.container}> <View style={styles.container}>
@ -60,7 +60,7 @@ export function PermissionsPage({ navigation }: Props): React.ReactElement {
)} )}
</View> </View>
</View> </View>
); )
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({
@ -93,4 +93,4 @@ const styles = StyleSheet.create({
bold: { bold: {
fontWeight: 'bold', fontWeight: 'bold',
}, },
}); })

View File

@ -1,8 +1,8 @@
export type Routes = { export type Routes = {
PermissionsPage: undefined; PermissionsPage: undefined
CameraPage: undefined; CameraPage: undefined
MediaPage: { MediaPage: {
path: string; path: string
type: 'video' | 'photo'; type: 'video' | 'photo'
}; }
}; }

View File

@ -1,11 +1,11 @@
import { VisionCameraProxy, Frame } from 'react-native-vision-camera'; import { VisionCameraProxy, Frame } from 'react-native-vision-camera'
const plugin = VisionCameraProxy.getFrameProcessorPlugin('example_plugin'); const plugin = VisionCameraProxy.getFrameProcessorPlugin('example_plugin')
export function examplePlugin(frame: Frame): string[] { export function examplePlugin(frame: Frame): string[] {
'worklet'; 'worklet'
if (plugin == null) throw new Error('Failed to load Frame Processor Plugin "example_plugin"!'); if (plugin == null) throw new Error('Failed to load Frame Processor Plugin "example_plugin"!')
return plugin.call(frame, { return plugin.call(frame, {
someString: 'hello!', someString: 'hello!',
@ -13,5 +13,5 @@ export function examplePlugin(frame: Frame): string[] {
someNumber: 42, someNumber: 42,
someObject: { test: 0, second: 'test' }, someObject: { test: 0, second: 'test' },
someArray: ['another test', 5], someArray: ['another test', 5],
}) as string[]; }) as string[]
} }

View File

@ -1,17 +1,17 @@
import { useState } from 'react'; import { useState } from 'react'
import { useEffect } from 'react'; import { useEffect } from 'react'
import { AppState, AppStateStatus } from 'react-native'; import { AppState, AppStateStatus } from 'react-native'
export const useIsForeground = (): boolean => { export const useIsForeground = (): boolean => {
const [isForeground, setIsForeground] = useState(true); const [isForeground, setIsForeground] = useState(true)
useEffect(() => { useEffect(() => {
const onChange = (state: AppStateStatus): void => { const onChange = (state: AppStateStatus): void => {
setIsForeground(state === 'active'); setIsForeground(state === 'active')
}; }
const listener = AppState.addEventListener('change', onChange); const listener = AppState.addEventListener('change', onChange)
return () => listener.remove(); return () => listener.remove()
}, [setIsForeground]); }, [setIsForeground])
return isForeground; return isForeground
}; }

View File

@ -1,12 +1,12 @@
import React, { useCallback, useMemo, useRef } from 'react'; import React, { useCallback, useMemo, useRef } from 'react'
import { StyleSheet, View, ViewProps } from 'react-native'; import { StyleSheet, View, ViewProps } from 'react-native'
import { import {
PanGestureHandler, PanGestureHandler,
PanGestureHandlerGestureEvent, PanGestureHandlerGestureEvent,
State, State,
TapGestureHandler, TapGestureHandler,
TapGestureHandlerStateChangeEvent, TapGestureHandlerStateChangeEvent,
} from 'react-native-gesture-handler'; } from 'react-native-gesture-handler'
import Reanimated, { import Reanimated, {
cancelAnimation, cancelAnimation,
Easing, Easing,
@ -18,29 +18,29 @@ import Reanimated, {
useAnimatedGestureHandler, useAnimatedGestureHandler,
useSharedValue, useSharedValue,
withRepeat, withRepeat,
} from 'react-native-reanimated'; } from 'react-native-reanimated'
import type { Camera, PhotoFile, TakePhotoOptions, VideoFile } from 'react-native-vision-camera'; import type { Camera, PhotoFile, TakePhotoOptions, VideoFile } from 'react-native-vision-camera'
import { CAPTURE_BUTTON_SIZE, SCREEN_HEIGHT, SCREEN_WIDTH } from './../Constants'; import { CAPTURE_BUTTON_SIZE, SCREEN_HEIGHT, SCREEN_WIDTH } from './../Constants'
const PAN_GESTURE_HANDLER_FAIL_X = [-SCREEN_WIDTH, SCREEN_WIDTH]; const PAN_GESTURE_HANDLER_FAIL_X = [-SCREEN_WIDTH, SCREEN_WIDTH]
const PAN_GESTURE_HANDLER_ACTIVE_Y = [-2, 2]; const PAN_GESTURE_HANDLER_ACTIVE_Y = [-2, 2]
const START_RECORDING_DELAY = 200; const START_RECORDING_DELAY = 200
const BORDER_WIDTH = CAPTURE_BUTTON_SIZE * 0.1; const BORDER_WIDTH = CAPTURE_BUTTON_SIZE * 0.1
interface Props extends ViewProps { interface Props extends ViewProps {
camera: React.RefObject<Camera>; camera: React.RefObject<Camera>
onMediaCaptured: (media: PhotoFile | VideoFile, type: 'photo' | 'video') => void; onMediaCaptured: (media: PhotoFile | VideoFile, type: 'photo' | 'video') => void
minZoom: number; minZoom: number
maxZoom: number; maxZoom: number
cameraZoom: Reanimated.SharedValue<number>; cameraZoom: Reanimated.SharedValue<number>
flash: 'off' | 'on'; flash: 'off' | 'on'
enabled: boolean; enabled: boolean
setIsPressingButton: (isPressingButton: boolean) => void; setIsPressingButton: (isPressingButton: boolean) => void
} }
const _CaptureButton: React.FC<Props> = ({ const _CaptureButton: React.FC<Props> = ({
@ -55,9 +55,9 @@ const _CaptureButton: React.FC<Props> = ({
style, style,
...props ...props
}): React.ReactElement => { }): React.ReactElement => {
const pressDownDate = useRef<Date | undefined>(undefined); const pressDownDate = useRef<Date | undefined>(undefined)
const isRecording = useRef(false); const isRecording = useRef(false)
const recordingProgress = useSharedValue(0); const recordingProgress = useSharedValue(0)
const takePhotoOptions = useMemo<TakePhotoOptions>( const takePhotoOptions = useMemo<TakePhotoOptions>(
() => ({ () => ({
photoCodec: 'jpeg', photoCodec: 'jpeg',
@ -67,66 +67,66 @@ const _CaptureButton: React.FC<Props> = ({
enableShutterSound: false, enableShutterSound: false,
}), }),
[flash], [flash],
); )
const isPressingButton = useSharedValue(false); const isPressingButton = useSharedValue(false)
//#region Camera Capture //#region Camera Capture
const takePhoto = useCallback(async () => { const takePhoto = useCallback(async () => {
try { try {
if (camera.current == null) throw new Error('Camera ref is null!'); if (camera.current == null) throw new Error('Camera ref is null!')
console.log('Taking photo...'); console.log('Taking photo...')
const photo = await camera.current.takePhoto(takePhotoOptions); const photo = await camera.current.takePhoto(takePhotoOptions)
onMediaCaptured(photo, 'photo'); onMediaCaptured(photo, 'photo')
} catch (e) { } catch (e) {
console.error('Failed to take photo!', e); console.error('Failed to take photo!', e)
} }
}, [camera, onMediaCaptured, takePhotoOptions]); }, [camera, onMediaCaptured, takePhotoOptions])
const onStoppedRecording = useCallback(() => { const onStoppedRecording = useCallback(() => {
isRecording.current = false; isRecording.current = false
cancelAnimation(recordingProgress); cancelAnimation(recordingProgress)
console.log('stopped recording video!'); console.log('stopped recording video!')
}, [recordingProgress]); }, [recordingProgress])
const stopRecording = useCallback(async () => { const stopRecording = useCallback(async () => {
try { try {
if (camera.current == null) throw new Error('Camera ref is null!'); if (camera.current == null) throw new Error('Camera ref is null!')
console.log('calling stopRecording()...'); console.log('calling stopRecording()...')
await camera.current.stopRecording(); await camera.current.stopRecording()
console.log('called stopRecording()!'); console.log('called stopRecording()!')
} catch (e) { } catch (e) {
console.error('failed to stop recording!', e); console.error('failed to stop recording!', e)
} }
}, [camera]); }, [camera])
const startRecording = useCallback(() => { const startRecording = useCallback(() => {
try { try {
if (camera.current == null) throw new Error('Camera ref is null!'); if (camera.current == null) throw new Error('Camera ref is null!')
console.log('calling startRecording()...'); console.log('calling startRecording()...')
camera.current.startRecording({ camera.current.startRecording({
flash: flash, flash: flash,
onRecordingError: (error) => { onRecordingError: (error) => {
console.error('Recording failed!', error); console.error('Recording failed!', error)
onStoppedRecording(); onStoppedRecording()
}, },
onRecordingFinished: (video) => { onRecordingFinished: (video) => {
console.log(`Recording successfully finished! ${video.path}`); console.log(`Recording successfully finished! ${video.path}`)
onMediaCaptured(video, 'video'); onMediaCaptured(video, 'video')
onStoppedRecording(); onStoppedRecording()
}, },
}); })
// TODO: wait until startRecording returns to actually find out if the recording has successfully started // TODO: wait until startRecording returns to actually find out if the recording has successfully started
console.log('called startRecording()!'); console.log('called startRecording()!')
isRecording.current = true; isRecording.current = true
} catch (e) { } catch (e) {
console.error('failed to start recording!', e, 'camera'); console.error('failed to start recording!', e, 'camera')
} }
}, [camera, flash, onMediaCaptured, onStoppedRecording]); }, [camera, flash, onMediaCaptured, onStoppedRecording])
//#endregion //#endregion
//#region Tap handler //#region Tap handler
const tapHandler = useRef<TapGestureHandler>(); const tapHandler = useRef<TapGestureHandler>()
const onHandlerStateChanged = useCallback( const onHandlerStateChanged = useCallback(
async ({ nativeEvent: event }: TapGestureHandlerStateChangeEvent) => { async ({ nativeEvent: event }: TapGestureHandlerStateChangeEvent) => {
// This is the gesture handler for the circular "shutter" button. // This is the gesture handler for the circular "shutter" button.
@ -138,73 +138,73 @@ const _CaptureButton: React.FC<Props> = ({
// if `pressDownDate` was less than 200ms ago, we know that the intention of the user is to take a photo. We check the `takePhotoPromise` if // if `pressDownDate` was less than 200ms ago, we know that the intention of the user is to take a photo. We check the `takePhotoPromise` if
// there already is an ongoing (or already resolved) takePhoto() call (remember that we called takePhoto() when the user pressed down), and // there already is an ongoing (or already resolved) takePhoto() call (remember that we called takePhoto() when the user pressed down), and
// if yes, use that. If no, we just try calling takePhoto() again // if yes, use that. If no, we just try calling takePhoto() again
console.debug(`state: ${Object.keys(State)[event.state]}`); console.debug(`state: ${Object.keys(State)[event.state]}`)
switch (event.state) { switch (event.state) {
case State.BEGAN: { case State.BEGAN: {
// enter "recording mode" // enter "recording mode"
recordingProgress.value = 0; recordingProgress.value = 0
isPressingButton.value = true; isPressingButton.value = true
const now = new Date(); const now = new Date()
pressDownDate.current = now; pressDownDate.current = now
setTimeout(() => { setTimeout(() => {
if (pressDownDate.current === now) { if (pressDownDate.current === now) {
// user is still pressing down after 200ms, so his intention is to create a video // user is still pressing down after 200ms, so his intention is to create a video
startRecording(); startRecording()
} }
}, START_RECORDING_DELAY); }, START_RECORDING_DELAY)
setIsPressingButton(true); setIsPressingButton(true)
return; return
} }
case State.END: case State.END:
case State.FAILED: case State.FAILED:
case State.CANCELLED: { case State.CANCELLED: {
// exit "recording mode" // exit "recording mode"
try { try {
if (pressDownDate.current == null) throw new Error('PressDownDate ref .current was null!'); if (pressDownDate.current == null) throw new Error('PressDownDate ref .current was null!')
const now = new Date(); const now = new Date()
const diff = now.getTime() - pressDownDate.current.getTime(); const diff = now.getTime() - pressDownDate.current.getTime()
pressDownDate.current = undefined; pressDownDate.current = undefined
if (diff < START_RECORDING_DELAY) { if (diff < START_RECORDING_DELAY) {
// user has released the button within 200ms, so his intention is to take a single picture. // user has released the button within 200ms, so his intention is to take a single picture.
await takePhoto(); await takePhoto()
} else { } else {
// user has held the button for more than 200ms, so he has been recording this entire time. // user has held the button for more than 200ms, so he has been recording this entire time.
await stopRecording(); await stopRecording()
} }
} finally { } finally {
setTimeout(() => { setTimeout(() => {
isPressingButton.value = false; isPressingButton.value = false
setIsPressingButton(false); setIsPressingButton(false)
}, 500); }, 500)
} }
return; return
} }
default: default:
break; break
} }
}, },
[isPressingButton, recordingProgress, setIsPressingButton, startRecording, stopRecording, takePhoto], [isPressingButton, recordingProgress, setIsPressingButton, startRecording, stopRecording, takePhoto],
); )
//#endregion //#endregion
//#region Pan handler //#region Pan handler
const panHandler = useRef<PanGestureHandler>(); const panHandler = useRef<PanGestureHandler>()
const onPanGestureEvent = useAnimatedGestureHandler<PanGestureHandlerGestureEvent, { offsetY?: number; startY?: number }>({ const onPanGestureEvent = useAnimatedGestureHandler<PanGestureHandlerGestureEvent, { offsetY?: number; startY?: number }>({
onStart: (event, context) => { onStart: (event, context) => {
context.startY = event.absoluteY; context.startY = event.absoluteY
const yForFullZoom = context.startY * 0.7; const yForFullZoom = context.startY * 0.7
const offsetYForFullZoom = context.startY - yForFullZoom; const offsetYForFullZoom = context.startY - yForFullZoom
// extrapolate [0 ... 1] zoom -> [0 ... Y_FOR_FULL_ZOOM] finger position // extrapolate [0 ... 1] zoom -> [0 ... Y_FOR_FULL_ZOOM] finger position
context.offsetY = interpolate(cameraZoom.value, [minZoom, maxZoom], [0, offsetYForFullZoom], Extrapolate.CLAMP); context.offsetY = interpolate(cameraZoom.value, [minZoom, maxZoom], [0, offsetYForFullZoom], Extrapolate.CLAMP)
}, },
onActive: (event, context) => { onActive: (event, context) => {
const offset = context.offsetY ?? 0; const offset = context.offsetY ?? 0
const startY = context.startY ?? SCREEN_HEIGHT; const startY = context.startY ?? SCREEN_HEIGHT
const yForFullZoom = startY * 0.7; const yForFullZoom = startY * 0.7
cameraZoom.value = interpolate(event.absoluteY - offset, [yForFullZoom, startY], [maxZoom, minZoom], Extrapolate.CLAMP); cameraZoom.value = interpolate(event.absoluteY - offset, [yForFullZoom, startY], [maxZoom, minZoom], Extrapolate.CLAMP)
}, },
}); })
//#endregion //#endregion
const shadowStyle = useAnimatedStyle( const shadowStyle = useAnimatedStyle(
@ -220,9 +220,9 @@ const _CaptureButton: React.FC<Props> = ({
], ],
}), }),
[isPressingButton], [isPressingButton],
); )
const buttonStyle = useAnimatedStyle(() => { const buttonStyle = useAnimatedStyle(() => {
let scale: number; let scale: number
if (enabled) { if (enabled) {
if (isPressingButton.value) { if (isPressingButton.value) {
scale = withRepeat( scale = withRepeat(
@ -232,18 +232,18 @@ const _CaptureButton: React.FC<Props> = ({
}), }),
-1, -1,
true, true,
); )
} else { } else {
scale = withSpring(0.9, { scale = withSpring(0.9, {
stiffness: 500, stiffness: 500,
damping: 300, damping: 300,
}); })
} }
} else { } else {
scale = withSpring(0.6, { scale = withSpring(0.6, {
stiffness: 500, stiffness: 500,
damping: 300, damping: 300,
}); })
} }
return { return {
@ -256,8 +256,8 @@ const _CaptureButton: React.FC<Props> = ({
scale: scale, scale: scale,
}, },
], ],
}; }
}, [enabled, isPressingButton]); }, [enabled, isPressingButton])
return ( return (
<TapGestureHandler <TapGestureHandler
@ -282,10 +282,10 @@ const _CaptureButton: React.FC<Props> = ({
</PanGestureHandler> </PanGestureHandler>
</Reanimated.View> </Reanimated.View>
</TapGestureHandler> </TapGestureHandler>
); )
}; }
export const CaptureButton = React.memo(_CaptureButton); export const CaptureButton = React.memo(_CaptureButton)
const styles = StyleSheet.create({ const styles = StyleSheet.create({
flex: { flex: {
@ -305,4 +305,4 @@ const styles = StyleSheet.create({
borderWidth: BORDER_WIDTH, borderWidth: BORDER_WIDTH,
borderColor: 'white', borderColor: 'white',
}, },
}); })

View File

@ -1,12 +1,12 @@
import { BlurView, BlurViewProps } from '@react-native-community/blur'; import { BlurView, BlurViewProps } from '@react-native-community/blur'
import React from 'react'; import React from 'react'
import { Platform, StyleSheet } from 'react-native'; import { Platform, StyleSheet } from 'react-native'
import StaticSafeAreaInsets from 'react-native-static-safe-area-insets'; import StaticSafeAreaInsets from 'react-native-static-safe-area-insets'
const FALLBACK_COLOR = 'rgba(140, 140, 140, 0.3)'; const FALLBACK_COLOR = 'rgba(140, 140, 140, 0.3)'
const StatusBarBlurBackgroundImpl = ({ style, ...props }: BlurViewProps): React.ReactElement | null => { const StatusBarBlurBackgroundImpl = ({ style, ...props }: BlurViewProps): React.ReactElement | null => {
if (Platform.OS !== 'ios') return null; if (Platform.OS !== 'ios') return null
return ( return (
<BlurView <BlurView
@ -16,10 +16,10 @@ const StatusBarBlurBackgroundImpl = ({ style, ...props }: BlurViewProps): React.
reducedTransparencyFallbackColor={FALLBACK_COLOR} reducedTransparencyFallbackColor={FALLBACK_COLOR}
{...props} {...props}
/> />
); )
}; }
export const StatusBarBlurBackground = React.memo(StatusBarBlurBackgroundImpl); export const StatusBarBlurBackground = React.memo(StatusBarBlurBackgroundImpl)
const styles = StyleSheet.create({ const styles = StyleSheet.create({
statusBarBackground: { statusBarBackground: {
@ -29,4 +29,4 @@ const styles = StyleSheet.create({
right: 0, right: 0,
height: StaticSafeAreaInsets.safeAreaInsetsTop, height: StaticSafeAreaInsets.safeAreaInsetsTop,
}, },
}); })

View File

@ -1,24 +1,24 @@
const path = require('path'); const path = require('path')
const child_process = require('child_process'); const child_process = require('child_process')
const root = path.resolve(__dirname, '..'); const root = path.resolve(__dirname, '..')
const args = process.argv.slice(2); const args = process.argv.slice(2)
const options = { const options = {
cwd: process.cwd(), cwd: process.cwd(),
env: process.env, env: process.env,
stdio: 'inherit', stdio: 'inherit',
encoding: 'utf-8', encoding: 'utf-8',
}; }
let result; let result
if (process.cwd() !== root || args.length) { if (process.cwd() !== root || args.length) {
// We're not in the root of the project, or additional arguments were passed // We're not in the root of the project, or additional arguments were passed
// In this case, forward the command to `yarn` // In this case, forward the command to `yarn`
result = child_process.spawnSync('yarn', args, options); result = child_process.spawnSync('yarn', args, options)
} else { } else {
// If `yarn` is run without arguments, perform bootstrap // If `yarn` is run without arguments, perform bootstrap
result = child_process.spawnSync('yarn', ['bootstrap'], options); result = child_process.spawnSync('yarn', ['bootstrap'], options)
} }
process.exitCode = result.status; process.exitCode = result.status

View File

@ -1,34 +1,34 @@
import React from 'react'; import React from 'react'
import { requireNativeComponent, NativeSyntheticEvent, findNodeHandle, NativeMethods } from 'react-native'; import { requireNativeComponent, NativeSyntheticEvent, findNodeHandle, NativeMethods } from 'react-native'
import type { CameraDevice } from './CameraDevice'; import type { CameraDevice } from './CameraDevice'
import type { ErrorWithCause } from './CameraError'; import type { ErrorWithCause } from './CameraError'
import { CameraCaptureError, CameraRuntimeError, tryParseNativeCameraError, isErrorWithCause } from './CameraError'; import { CameraCaptureError, CameraRuntimeError, tryParseNativeCameraError, isErrorWithCause } from './CameraError'
import type { CameraProps, FrameProcessor } from './CameraProps'; import type { CameraProps, FrameProcessor } from './CameraProps'
import { CameraModule } from './NativeCameraModule'; import { CameraModule } from './NativeCameraModule'
import type { PhotoFile, TakePhotoOptions } from './PhotoFile'; import type { PhotoFile, TakePhotoOptions } from './PhotoFile'
import type { Point } from './Point'; import type { Point } from './Point'
import type { RecordVideoOptions, VideoFile } from './VideoFile'; import type { RecordVideoOptions, VideoFile } from './VideoFile'
import { VisionCameraProxy } from './FrameProcessorPlugins'; import { VisionCameraProxy } from './FrameProcessorPlugins'
import { CameraDevices } from './CameraDevices'; import { CameraDevices } from './CameraDevices'
import type { EmitterSubscription } from 'react-native'; import type { EmitterSubscription } from 'react-native'
//#region Types //#region Types
export type CameraPermissionStatus = 'granted' | 'not-determined' | 'denied' | 'restricted'; export type CameraPermissionStatus = 'granted' | 'not-determined' | 'denied' | 'restricted'
export type CameraPermissionRequestResult = 'granted' | 'denied'; export type CameraPermissionRequestResult = 'granted' | 'denied'
interface OnErrorEvent { interface OnErrorEvent {
code: string; code: string
message: string; message: string
cause?: ErrorWithCause; cause?: ErrorWithCause
} }
type NativeCameraViewProps = Omit<CameraProps, 'device' | 'onInitialized' | 'onError' | 'frameProcessor'> & { type NativeCameraViewProps = Omit<CameraProps, 'device' | 'onInitialized' | 'onError' | 'frameProcessor'> & {
cameraId: string; cameraId: string
enableFrameProcessor: boolean; enableFrameProcessor: boolean
onInitialized?: (event: NativeSyntheticEvent<void>) => void; onInitialized?: (event: NativeSyntheticEvent<void>) => void
onError?: (event: NativeSyntheticEvent<OnErrorEvent>) => void; onError?: (event: NativeSyntheticEvent<OnErrorEvent>) => void
onViewReady: () => void; onViewReady: () => void
}; }
type RefType = React.Component<NativeCameraViewProps> & Readonly<NativeMethods>; type RefType = React.Component<NativeCameraViewProps> & Readonly<NativeMethods>
//#endregion //#endregion
//#region Camera Component //#region Camera Component
@ -62,34 +62,34 @@ type RefType = React.Component<NativeCameraViewProps> & Readonly<NativeMethods>;
*/ */
export class Camera extends React.PureComponent<CameraProps> { export class Camera extends React.PureComponent<CameraProps> {
/** @internal */ /** @internal */
static displayName = 'Camera'; static displayName = 'Camera'
/** @internal */ /** @internal */
displayName = Camera.displayName; displayName = Camera.displayName
private lastFrameProcessor: FrameProcessor | undefined; private lastFrameProcessor: FrameProcessor | undefined
private isNativeViewMounted = false; private isNativeViewMounted = false
private readonly ref: React.RefObject<RefType>; private readonly ref: React.RefObject<RefType>
/** @internal */ /** @internal */
constructor(props: CameraProps) { constructor(props: CameraProps) {
super(props); super(props)
this.onViewReady = this.onViewReady.bind(this); this.onViewReady = this.onViewReady.bind(this)
this.onInitialized = this.onInitialized.bind(this); this.onInitialized = this.onInitialized.bind(this)
this.onError = this.onError.bind(this); this.onError = this.onError.bind(this)
this.ref = React.createRef<RefType>(); this.ref = React.createRef<RefType>()
this.lastFrameProcessor = undefined; this.lastFrameProcessor = undefined
} }
private get handle(): number { private get handle(): number {
const nodeHandle = findNodeHandle(this.ref.current); const nodeHandle = findNodeHandle(this.ref.current)
if (nodeHandle == null || nodeHandle === -1) { if (nodeHandle == null || nodeHandle === -1) {
throw new CameraRuntimeError( throw new CameraRuntimeError(
'system/view-not-found', 'system/view-not-found',
"Could not get the Camera's native view tag! Does the Camera View exist in the native view-tree?", "Could not get the Camera's native view tag! Does the Camera View exist in the native view-tree?",
); )
} }
return nodeHandle; return nodeHandle
} }
//#region View-specific functions (UIViewManager) //#region View-specific functions (UIViewManager)
@ -108,9 +108,9 @@ export class Camera extends React.PureComponent<CameraProps> {
*/ */
public async takePhoto(options?: TakePhotoOptions): Promise<PhotoFile> { public async takePhoto(options?: TakePhotoOptions): Promise<PhotoFile> {
try { try {
return await CameraModule.takePhoto(this.handle, options ?? {}); return await CameraModule.takePhoto(this.handle, options ?? {})
} catch (e) { } catch (e) {
throw tryParseNativeCameraError(e); throw tryParseNativeCameraError(e)
} }
} }
@ -131,19 +131,19 @@ export class Camera extends React.PureComponent<CameraProps> {
* ``` * ```
*/ */
public startRecording(options: RecordVideoOptions): void { public startRecording(options: RecordVideoOptions): void {
const { onRecordingError, onRecordingFinished, ...passThroughOptions } = options; const { onRecordingError, onRecordingFinished, ...passThroughOptions } = options
if (typeof onRecordingError !== 'function' || typeof onRecordingFinished !== 'function') if (typeof onRecordingError !== 'function' || typeof onRecordingFinished !== 'function')
throw new CameraRuntimeError('parameter/invalid-parameter', 'The onRecordingError or onRecordingFinished functions were not set!'); throw new CameraRuntimeError('parameter/invalid-parameter', 'The onRecordingError or onRecordingFinished functions were not set!')
const onRecordCallback = (video?: VideoFile, error?: CameraCaptureError): void => { const onRecordCallback = (video?: VideoFile, error?: CameraCaptureError): void => {
if (error != null) return onRecordingError(error); if (error != null) return onRecordingError(error)
if (video != null) return onRecordingFinished(video); if (video != null) return onRecordingFinished(video)
}; }
try { try {
// TODO: Use TurboModules to make this awaitable. // TODO: Use TurboModules to make this awaitable.
CameraModule.startRecording(this.handle, passThroughOptions, onRecordCallback); CameraModule.startRecording(this.handle, passThroughOptions, onRecordCallback)
} catch (e) { } catch (e) {
throw tryParseNativeCameraError(e); throw tryParseNativeCameraError(e)
} }
} }
@ -169,9 +169,9 @@ export class Camera extends React.PureComponent<CameraProps> {
*/ */
public async pauseRecording(): Promise<void> { public async pauseRecording(): Promise<void> {
try { try {
return await CameraModule.pauseRecording(this.handle); return await CameraModule.pauseRecording(this.handle)
} catch (e) { } catch (e) {
throw tryParseNativeCameraError(e); throw tryParseNativeCameraError(e)
} }
} }
@ -197,9 +197,9 @@ export class Camera extends React.PureComponent<CameraProps> {
*/ */
public async resumeRecording(): Promise<void> { public async resumeRecording(): Promise<void> {
try { try {
return await CameraModule.resumeRecording(this.handle); return await CameraModule.resumeRecording(this.handle)
} catch (e) { } catch (e) {
throw tryParseNativeCameraError(e); throw tryParseNativeCameraError(e)
} }
} }
@ -218,9 +218,9 @@ export class Camera extends React.PureComponent<CameraProps> {
*/ */
public async stopRecording(): Promise<void> { public async stopRecording(): Promise<void> {
try { try {
return await CameraModule.stopRecording(this.handle); return await CameraModule.stopRecording(this.handle)
} catch (e) { } catch (e) {
throw tryParseNativeCameraError(e); throw tryParseNativeCameraError(e)
} }
} }
@ -244,9 +244,9 @@ export class Camera extends React.PureComponent<CameraProps> {
*/ */
public async focus(point: Point): Promise<void> { public async focus(point: Point): Promise<void> {
try { try {
return await CameraModule.focus(this.handle, point); return await CameraModule.focus(this.handle, point)
} catch (e) { } catch (e) {
throw tryParseNativeCameraError(e); throw tryParseNativeCameraError(e)
} }
} }
//#endregion //#endregion
@ -268,7 +268,7 @@ export class Camera extends React.PureComponent<CameraProps> {
* ``` * ```
*/ */
public static getAvailableCameraDevices(): CameraDevice[] { public static getAvailableCameraDevices(): CameraDevice[] {
return CameraDevices.getAvailableCameraDevices(); return CameraDevices.getAvailableCameraDevices()
} }
/** /**
* Adds a listener that gets called everytime the Camera Devices change, for example * Adds a listener that gets called everytime the Camera Devices change, for example
@ -277,7 +277,7 @@ export class Camera extends React.PureComponent<CameraProps> {
* If you use Hooks, use the `useCameraDevices()` hook instead. * If you use Hooks, use the `useCameraDevices()` hook instead.
*/ */
public static addCameraDevicesChangedListener(listener: (newDevices: CameraDevice[]) => void): EmitterSubscription { public static addCameraDevicesChangedListener(listener: (newDevices: CameraDevice[]) => void): EmitterSubscription {
return CameraDevices.addCameraDevicesChangedListener(listener); return CameraDevices.addCameraDevicesChangedListener(listener)
} }
/** /**
* Gets the current Camera Permission Status. Check this before mounting the Camera to ensure * Gets the current Camera Permission Status. Check this before mounting the Camera to ensure
@ -289,9 +289,9 @@ export class Camera extends React.PureComponent<CameraProps> {
*/ */
public static async getCameraPermissionStatus(): Promise<CameraPermissionStatus> { public static async getCameraPermissionStatus(): Promise<CameraPermissionStatus> {
try { try {
return await CameraModule.getCameraPermissionStatus(); return await CameraModule.getCameraPermissionStatus()
} catch (e) { } catch (e) {
throw tryParseNativeCameraError(e); throw tryParseNativeCameraError(e)
} }
} }
/** /**
@ -304,9 +304,9 @@ export class Camera extends React.PureComponent<CameraProps> {
*/ */
public static async getMicrophonePermissionStatus(): Promise<CameraPermissionStatus> { public static async getMicrophonePermissionStatus(): Promise<CameraPermissionStatus> {
try { try {
return await CameraModule.getMicrophonePermissionStatus(); return await CameraModule.getMicrophonePermissionStatus()
} catch (e) { } catch (e) {
throw tryParseNativeCameraError(e); throw tryParseNativeCameraError(e)
} }
} }
/** /**
@ -319,9 +319,9 @@ export class Camera extends React.PureComponent<CameraProps> {
*/ */
public static async requestCameraPermission(): Promise<CameraPermissionRequestResult> { public static async requestCameraPermission(): Promise<CameraPermissionRequestResult> {
try { try {
return await CameraModule.requestCameraPermission(); return await CameraModule.requestCameraPermission()
} catch (e) { } catch (e) {
throw tryParseNativeCameraError(e); throw tryParseNativeCameraError(e)
} }
} }
/** /**
@ -334,9 +334,9 @@ export class Camera extends React.PureComponent<CameraProps> {
*/ */
public static async requestMicrophonePermission(): Promise<CameraPermissionRequestResult> { public static async requestMicrophonePermission(): Promise<CameraPermissionRequestResult> {
try { try {
return await CameraModule.requestMicrophonePermission(); return await CameraModule.requestMicrophonePermission()
} catch (e) { } catch (e) {
throw tryParseNativeCameraError(e); throw tryParseNativeCameraError(e)
} }
} }
//#endregion //#endregion
@ -344,48 +344,48 @@ export class Camera extends React.PureComponent<CameraProps> {
//#region Events (Wrapped to maintain reference equality) //#region Events (Wrapped to maintain reference equality)
private onError(event: NativeSyntheticEvent<OnErrorEvent>): void { private onError(event: NativeSyntheticEvent<OnErrorEvent>): void {
if (this.props.onError != null) { if (this.props.onError != null) {
const error = event.nativeEvent; const error = event.nativeEvent
const cause = isErrorWithCause(error.cause) ? error.cause : undefined; const cause = isErrorWithCause(error.cause) ? error.cause : undefined
this.props.onError( this.props.onError(
// @ts-expect-error We're casting from unknown bridge types to TS unions, I expect it to hopefully work // @ts-expect-error We're casting from unknown bridge types to TS unions, I expect it to hopefully work
new CameraRuntimeError(error.code, error.message, cause), new CameraRuntimeError(error.code, error.message, cause),
); )
} }
} }
private onInitialized(): void { private onInitialized(): void {
this.props.onInitialized?.(); this.props.onInitialized?.()
} }
//#endregion //#endregion
//#region Lifecycle //#region Lifecycle
private setFrameProcessor(frameProcessor: FrameProcessor): void { private setFrameProcessor(frameProcessor: FrameProcessor): void {
VisionCameraProxy.setFrameProcessor(this.handle, frameProcessor); VisionCameraProxy.setFrameProcessor(this.handle, frameProcessor)
} }
private unsetFrameProcessor(): void { private unsetFrameProcessor(): void {
VisionCameraProxy.removeFrameProcessor(this.handle); VisionCameraProxy.removeFrameProcessor(this.handle)
} }
private onViewReady(): void { private onViewReady(): void {
this.isNativeViewMounted = true; this.isNativeViewMounted = true
if (this.props.frameProcessor != null) { if (this.props.frameProcessor != null) {
// user passed a `frameProcessor` but we didn't set it yet because the native view was not mounted yet. set it now. // user passed a `frameProcessor` but we didn't set it yet because the native view was not mounted yet. set it now.
this.setFrameProcessor(this.props.frameProcessor); this.setFrameProcessor(this.props.frameProcessor)
this.lastFrameProcessor = this.props.frameProcessor; this.lastFrameProcessor = this.props.frameProcessor
} }
} }
/** @internal */ /** @internal */
componentDidUpdate(): void { componentDidUpdate(): void {
if (!this.isNativeViewMounted) return; if (!this.isNativeViewMounted) return
const frameProcessor = this.props.frameProcessor; const frameProcessor = this.props.frameProcessor
if (frameProcessor !== this.lastFrameProcessor) { if (frameProcessor !== this.lastFrameProcessor) {
// frameProcessor argument identity changed. Update native to reflect the change. // frameProcessor argument identity changed. Update native to reflect the change.
if (frameProcessor != null) this.setFrameProcessor(frameProcessor); if (frameProcessor != null) this.setFrameProcessor(frameProcessor)
else this.unsetFrameProcessor(); else this.unsetFrameProcessor()
this.lastFrameProcessor = frameProcessor; this.lastFrameProcessor = frameProcessor
} }
} }
//#endregion //#endregion
@ -393,16 +393,16 @@ export class Camera extends React.PureComponent<CameraProps> {
/** @internal */ /** @internal */
public render(): React.ReactNode { public render(): React.ReactNode {
// We remove the big `device` object from the props because we only need to pass `cameraId` to native. // We remove the big `device` object from the props because we only need to pass `cameraId` to native.
const { device, frameProcessor, ...props } = this.props; const { device, frameProcessor, ...props } = this.props
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (device == null) { if (device == null) {
throw new Error( throw new Error(
'Camera: `device` is null! Select a valid Camera device. See: https://mrousavy.com/react-native-vision-camera/docs/guides/devices', 'Camera: `device` is null! Select a valid Camera device. See: https://mrousavy.com/react-native-vision-camera/docs/guides/devices',
); )
} }
const shouldEnableBufferCompression = props.video === true && frameProcessor == null; const shouldEnableBufferCompression = props.video === true && frameProcessor == null
return ( return (
<NativeCameraView <NativeCameraView
@ -415,7 +415,7 @@ export class Camera extends React.PureComponent<CameraProps> {
enableFrameProcessor={frameProcessor != null} enableFrameProcessor={frameProcessor != null}
enableBufferCompression={props.enableBufferCompression ?? shouldEnableBufferCompression} enableBufferCompression={props.enableBufferCompression ?? shouldEnableBufferCompression}
/> />
); )
} }
} }
//#endregion //#endregion
@ -425,4 +425,4 @@ const NativeCameraView = requireNativeComponent<NativeCameraViewProps>(
'CameraView', 'CameraView',
// @ts-expect-error because the type declarations are kinda wrong, no? // @ts-expect-error because the type declarations are kinda wrong, no?
Camera, Camera,
); )

View File

@ -1,5 +1,5 @@
import { Orientation } from './Orientation'; import { Orientation } from './Orientation'
import type { PixelFormat } from './PixelFormat'; import type { PixelFormat } from './PixelFormat'
/** /**
* Represents the camera device position. * Represents the camera device position.
@ -8,7 +8,7 @@ import type { PixelFormat } from './PixelFormat';
* * `"front"`: Indicates that the device is physically located on the front of the phone * * `"front"`: Indicates that the device is physically located on the front of the phone
* * `"external"`: The camera device is an external camera, and has no fixed facing relative to the phone. (e.g. USB or Continuity Cameras) * * `"external"`: The camera device is an external camera, and has no fixed facing relative to the phone. (e.g. USB or Continuity Cameras)
*/ */
export type CameraPosition = 'front' | 'back' | 'external'; export type CameraPosition = 'front' | 'back' | 'external'
/** /**
* Indentifiers for a physical camera (one that actually exists on the back/front of the device) * Indentifiers for a physical camera (one that actually exists on the back/front of the device)
@ -23,7 +23,7 @@ export type CameraPosition = 'front' | 'back' | 'external';
* * `"wide-angle-camera"` + `"telephoto-camera"` = **dual camera**. * * `"wide-angle-camera"` + `"telephoto-camera"` = **dual camera**.
* * `"ultra-wide-angle-camera"` + `"wide-angle-camera"` + `"telephoto-camera"` = **triple camera**. * * `"ultra-wide-angle-camera"` + `"wide-angle-camera"` + `"telephoto-camera"` = **triple camera**.
*/ */
export type PhysicalCameraDeviceType = 'ultra-wide-angle-camera' | 'wide-angle-camera' | 'telephoto-camera'; export type PhysicalCameraDeviceType = 'ultra-wide-angle-camera' | 'wide-angle-camera' | 'telephoto-camera'
/** /**
* Indicates a format's autofocus system. * Indicates a format's autofocus system.
@ -32,7 +32,7 @@ export type PhysicalCameraDeviceType = 'ultra-wide-angle-camera' | 'wide-angle-c
* * `"contrast-detection"`: Indicates that autofocus is achieved by contrast detection. Contrast detection performs a focus scan to find the optimal position * * `"contrast-detection"`: Indicates that autofocus is achieved by contrast detection. Contrast detection performs a focus scan to find the optimal position
* * `"phase-detection"`: Indicates that autofocus is achieved by phase detection. Phase detection has the ability to achieve focus in many cases without a focus scan. Phase detection autofocus is typically less visually intrusive than contrast detection autofocus * * `"phase-detection"`: Indicates that autofocus is achieved by phase detection. Phase detection has the ability to achieve focus in many cases without a focus scan. Phase detection autofocus is typically less visually intrusive than contrast detection autofocus
*/ */
export type AutoFocusSystem = 'contrast-detection' | 'phase-detection' | 'none'; export type AutoFocusSystem = 'contrast-detection' | 'phase-detection' | 'none'
/** /**
* Indicates a format's supported video stabilization mode. Enabling video stabilization may introduce additional latency into the video capture pipeline. * Indicates a format's supported video stabilization mode. Enabling video stabilization may introduce additional latency into the video capture pipeline.
@ -43,7 +43,7 @@ export type AutoFocusSystem = 'contrast-detection' | 'phase-detection' | 'none';
* * `"cinematic-extended"`: Extended software- and hardware-based stabilization that aggressively crops and transforms the video to apply a smooth cinematic stabilization. * * `"cinematic-extended"`: Extended software- and hardware-based stabilization that aggressively crops and transforms the video to apply a smooth cinematic stabilization.
* * `"auto"`: Indicates that the most appropriate video stabilization mode for the device and format should be chosen automatically * * `"auto"`: Indicates that the most appropriate video stabilization mode for the device and format should be chosen automatically
*/ */
export type VideoStabilizationMode = 'off' | 'standard' | 'cinematic' | 'cinematic-extended' | 'auto'; export type VideoStabilizationMode = 'off' | 'standard' | 'cinematic' | 'cinematic-extended' | 'auto'
/** /**
* A Camera Device's stream-configuration format. * A Camera Device's stream-configuration format.
@ -59,68 +59,68 @@ export interface CameraDeviceFormat {
/** /**
* The height of the highest resolution a still image (photo) can be produced in * The height of the highest resolution a still image (photo) can be produced in
*/ */
photoHeight: number; photoHeight: number
/** /**
* The width of the highest resolution a still image (photo) can be produced in * The width of the highest resolution a still image (photo) can be produced in
*/ */
photoWidth: number; photoWidth: number
/** /**
* The video resolutions's height * The video resolutions's height
*/ */
videoHeight: number; videoHeight: number
/** /**
* The video resolution's width * The video resolution's width
*/ */
videoWidth: number; videoWidth: number
/** /**
* Maximum supported ISO value * Maximum supported ISO value
*/ */
maxISO: number; maxISO: number
/** /**
* Minimum supported ISO value * Minimum supported ISO value
*/ */
minISO: number; minISO: number
/** /**
* The video field of view in degrees * The video field of view in degrees
*/ */
fieldOfView: number; fieldOfView: number
/** /**
* The maximum zoom factor (e.g. `128`) * The maximum zoom factor (e.g. `128`)
*/ */
maxZoom: number; maxZoom: number
/** /**
* Specifies whether this format supports HDR mode for video capture * Specifies whether this format supports HDR mode for video capture
*/ */
supportsVideoHDR: boolean; supportsVideoHDR: boolean
/** /**
* Specifies whether this format supports HDR mode for photo capture * Specifies whether this format supports HDR mode for photo capture
*/ */
supportsPhotoHDR: boolean; supportsPhotoHDR: boolean
/** /**
* Specifies whether this format supports delivering depth data for photo or video capture. * Specifies whether this format supports delivering depth data for photo or video capture.
*/ */
supportsDepthCapture: boolean; supportsDepthCapture: boolean
/** /**
* The minum frame rate this Format needs to run at. High resolution formats often run at lower frame rates. * The minum frame rate this Format needs to run at. High resolution formats often run at lower frame rates.
*/ */
minFps: number; minFps: number
/** /**
* The maximum frame rate this Format is able to run at. High resolution formats often run at lower frame rates. * The maximum frame rate this Format is able to run at. High resolution formats often run at lower frame rates.
*/ */
maxFps: number; maxFps: number
/** /**
* Specifies this format's auto focus system. * Specifies this format's auto focus system.
*/ */
autoFocusSystem: AutoFocusSystem; autoFocusSystem: AutoFocusSystem
/** /**
* All supported video stabilization modes * All supported video stabilization modes
*/ */
videoStabilizationModes: VideoStabilizationMode[]; videoStabilizationModes: VideoStabilizationMode[]
/** /**
* Specifies this format's supported pixel-formats. * Specifies this format's supported pixel-formats.
* In most cases, this is `['native', 'yuv']`. * In most cases, this is `['native', 'yuv']`.
*/ */
pixelFormats: PixelFormat[]; pixelFormats: PixelFormat[]
} }
/** /**
@ -130,7 +130,7 @@ export interface CameraDevice {
/** /**
* The native ID of the camera device instance. * The native ID of the camera device instance.
*/ */
id: string; id: string
/** /**
* The physical devices this `CameraDevice` consists of. * The physical devices this `CameraDevice` consists of.
* *
@ -139,7 +139,7 @@ export interface CameraDevice {
* *
* You can check if the camera is a logical multi-camera by using the `isMultiCam` property. * You can check if the camera is a logical multi-camera by using the `isMultiCam` property.
*/ */
physicalDevices: PhysicalCameraDeviceType[]; physicalDevices: PhysicalCameraDeviceType[]
/** /**
* Specifies the physical position of this camera. * Specifies the physical position of this camera.
* - `back`: The Camera Device is located on the back of the phone. These devices can be used for capturing what's in front of the user. * - `back`: The Camera Device is located on the back of the phone. These devices can be used for capturing what's in front of the user.
@ -149,19 +149,19 @@ export interface CameraDevice {
* - [Continuity Camera Devices](https://support.apple.com/en-us/HT213244) (e.g. your iPhone's or Mac's Camera connected through WiFi/Continuity) * - [Continuity Camera Devices](https://support.apple.com/en-us/HT213244) (e.g. your iPhone's or Mac's Camera connected through WiFi/Continuity)
* - Bluetooth/WiFi Camera Devices (if they are supported in the platform-native Camera APIs; Camera2 and AVFoundation) * - Bluetooth/WiFi Camera Devices (if they are supported in the platform-native Camera APIs; Camera2 and AVFoundation)
*/ */
position: CameraPosition; position: CameraPosition
/** /**
* A friendly localized name describing the camera. * A friendly localized name describing the camera.
*/ */
name: string; name: string
/** /**
* Specifies whether this camera supports enabling flash for photo capture. * Specifies whether this camera supports enabling flash for photo capture.
*/ */
hasFlash: boolean; hasFlash: boolean
/** /**
* Specifies whether this camera supports continuously enabling the flash to act like a torch (flash with video capture) * Specifies whether this camera supports continuously enabling the flash to act like a torch (flash with video capture)
*/ */
hasTorch: boolean; hasTorch: boolean
/** /**
* A property indicating whether the device is a virtual multi-camera consisting of multiple combined physical cameras. * A property indicating whether the device is a virtual multi-camera consisting of multiple combined physical cameras.
* *
@ -169,15 +169,15 @@ export interface CameraDevice {
* * The Dual Camera, which supports seamlessly switching between a wide and telephoto camera while zooming and generating depth data from the disparities between the different points of view of the physical cameras. * * The Dual Camera, which supports seamlessly switching between a wide and telephoto camera while zooming and generating depth data from the disparities between the different points of view of the physical cameras.
* * The TrueDepth Camera, which generates depth data from disparities between a YUV camera and an Infrared camera pointed in the same direction. * * The TrueDepth Camera, which generates depth data from disparities between a YUV camera and an Infrared camera pointed in the same direction.
*/ */
isMultiCam: boolean; isMultiCam: boolean
/** /**
* Minimum available zoom factor (e.g. `1`) * Minimum available zoom factor (e.g. `1`)
*/ */
minZoom: number; minZoom: number
/** /**
* Maximum available zoom factor (e.g. `128`) * Maximum available zoom factor (e.g. `128`)
*/ */
maxZoom: number; maxZoom: number
/** /**
* The zoom factor where the camera is "neutral". * The zoom factor where the camera is "neutral".
* *
@ -193,36 +193,36 @@ export interface CameraDevice {
* zoom: zoom.value * zoom: zoom.value
* })) * }))
*/ */
neutralZoom: number; neutralZoom: number
/** /**
* All available formats for this camera device. Use this to find the best format for your use case and set it to the Camera's {@linkcode CameraProps.format | Camera's .format} property. * All available formats for this camera device. Use this to find the best format for your use case and set it to the Camera's {@linkcode CameraProps.format | Camera's .format} property.
* *
* See [the Camera Formats documentation](https://react-native-vision-camera.com/docs/guides/formats) for more information about Camera Formats. * See [the Camera Formats documentation](https://react-native-vision-camera.com/docs/guides/formats) for more information about Camera Formats.
*/ */
formats: CameraDeviceFormat[]; formats: CameraDeviceFormat[]
/** /**
* Whether this camera device supports low light boost. * Whether this camera device supports low light boost.
*/ */
supportsLowLightBoost: boolean; supportsLowLightBoost: boolean
/** /**
* Whether this camera supports taking photos in RAW format * Whether this camera supports taking photos in RAW format
* *
* **! Work in Progress !** * **! Work in Progress !**
*/ */
supportsRawCapture: boolean; supportsRawCapture: boolean
/** /**
* Specifies whether this device supports focusing ({@linkcode Camera.focus | Camera.focus(...)}) * Specifies whether this device supports focusing ({@linkcode Camera.focus | Camera.focus(...)})
*/ */
supportsFocus: boolean; supportsFocus: boolean
/** /**
* The hardware level of the Camera. * The hardware level of the Camera.
* - On Android, some older devices are running at a `legacy` or `limited` level which means they are running in a backwards compatible mode. * - On Android, some older devices are running at a `legacy` or `limited` level which means they are running in a backwards compatible mode.
* - On iOS, all devices are `full`. * - On iOS, all devices are `full`.
*/ */
hardwareLevel: 'legacy' | 'limited' | 'full'; hardwareLevel: 'legacy' | 'limited' | 'full'
/** /**
* Represents the sensor's orientation relative to the phone. * Represents the sensor's orientation relative to the phone.
* For most phones this will be landscape, as Camera sensors are usually always rotated by 90 degrees (i.e. width and height are flipped). * For most phones this will be landscape, as Camera sensors are usually always rotated by 90 degrees (i.e. width and height are flipped).
*/ */
sensorOrientation: Orientation; sensorOrientation: Orientation
} }

View File

@ -1,27 +1,27 @@
import { NativeModules, NativeEventEmitter } from 'react-native'; import { NativeModules, NativeEventEmitter } from 'react-native'
import { CameraDevice } from './CameraDevice'; import { CameraDevice } from './CameraDevice'
const CameraDevicesManager = NativeModules.CameraDevices as { const CameraDevicesManager = NativeModules.CameraDevices as {
getConstants: () => { getConstants: () => {
availableCameraDevices: CameraDevice[]; availableCameraDevices: CameraDevice[]
userPreferredCameraDevice: CameraDevice | undefined; userPreferredCameraDevice: CameraDevice | undefined
}; }
}; }
const constants = CameraDevicesManager.getConstants(); const constants = CameraDevicesManager.getConstants()
let devices = constants.availableCameraDevices; let devices = constants.availableCameraDevices
const DEVICES_CHANGED_NAME = 'CameraDevicesChanged'; const DEVICES_CHANGED_NAME = 'CameraDevicesChanged'
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
const eventEmitter = new NativeEventEmitter(CameraDevicesManager as any); const eventEmitter = new NativeEventEmitter(CameraDevicesManager as any)
eventEmitter.addListener(DEVICES_CHANGED_NAME, (newDevices: CameraDevice[]) => { eventEmitter.addListener(DEVICES_CHANGED_NAME, (newDevices: CameraDevice[]) => {
devices = newDevices; devices = newDevices
}); })
export const CameraDevices = { export const CameraDevices = {
userPreferredCameraDevice: constants.userPreferredCameraDevice, userPreferredCameraDevice: constants.userPreferredCameraDevice,
getAvailableCameraDevices: () => devices, getAvailableCameraDevices: () => devices,
addCameraDevicesChangedListener: (callback: (newDevices: CameraDevice[]) => void) => { addCameraDevicesChangedListener: (callback: (newDevices: CameraDevice[]) => void) => {
return eventEmitter.addListener(DEVICES_CHANGED_NAME, callback); return eventEmitter.addListener(DEVICES_CHANGED_NAME, callback)
}, },
}; }

View File

@ -1,10 +1,10 @@
export type PermissionError = 'permission/microphone-permission-denied' | 'permission/camera-permission-denied'; export type PermissionError = 'permission/microphone-permission-denied' | 'permission/camera-permission-denied'
export type ParameterError = export type ParameterError =
| 'parameter/invalid-parameter' | 'parameter/invalid-parameter'
| 'parameter/unsupported-os' | 'parameter/unsupported-os'
| 'parameter/unsupported-output' | 'parameter/unsupported-output'
| 'parameter/unsupported-input' | 'parameter/unsupported-input'
| 'parameter/invalid-combination'; | 'parameter/invalid-combination'
export type DeviceError = export type DeviceError =
| 'device/configuration-error' | 'device/configuration-error'
| 'device/no-device' | 'device/no-device'
@ -14,21 +14,21 @@ export type DeviceError =
| 'device/pixel-format-not-supported' | 'device/pixel-format-not-supported'
| 'device/low-light-boost-not-supported' | 'device/low-light-boost-not-supported'
| 'device/focus-not-supported' | 'device/focus-not-supported'
| 'device/camera-not-available-on-simulator'; | 'device/camera-not-available-on-simulator'
export type FormatError = export type FormatError =
| 'format/invalid-fps' | 'format/invalid-fps'
| 'format/invalid-hdr' | 'format/invalid-hdr'
| 'format/incompatible-pixel-format-with-hdr-setting' | 'format/incompatible-pixel-format-with-hdr-setting'
| 'format/invalid-low-light-boost' | 'format/invalid-low-light-boost'
| 'format/invalid-format' | 'format/invalid-format'
| 'format/invalid-color-space'; | 'format/invalid-color-space'
export type SessionError = export type SessionError =
| 'session/camera-not-ready' | 'session/camera-not-ready'
| 'session/camera-cannot-be-opened' | 'session/camera-cannot-be-opened'
| 'session/camera-has-been-disconnected' | 'session/camera-has-been-disconnected'
| 'session/audio-session-setup-failed' | 'session/audio-session-setup-failed'
| 'session/audio-in-use-by-other-app' | 'session/audio-in-use-by-other-app'
| 'session/audio-session-failed-to-activate'; | 'session/audio-session-failed-to-activate'
export type CaptureError = export type CaptureError =
| 'capture/invalid-photo-format' | 'capture/invalid-photo-format'
| 'capture/encoder-error' | 'capture/encoder-error'
@ -50,13 +50,13 @@ export type CaptureError =
| 'capture/video-not-enabled' | 'capture/video-not-enabled'
| 'capture/photo-not-enabled' | 'capture/photo-not-enabled'
| 'capture/aborted' | 'capture/aborted'
| 'capture/unknown'; | 'capture/unknown'
export type SystemError = export type SystemError =
| 'system/camera-module-not-found' | 'system/camera-module-not-found'
| 'system/no-camera-manager' | 'system/no-camera-manager'
| 'system/frame-processors-unavailable' | 'system/frame-processors-unavailable'
| 'system/view-not-found'; | 'system/view-not-found'
export type UnknownError = 'unknown/unknown'; export type UnknownError = 'unknown/unknown'
/** /**
* Represents a JSON-style error cause. This contains native `NSError`/`Throwable` information, and can have recursive {@linkcode ErrorWithCause.cause | .cause} properties until the ultimate cause has been found. * Represents a JSON-style error cause. This contains native `NSError`/`Throwable` information, and can have recursive {@linkcode ErrorWithCause.cause | .cause} properties until the ultimate cause has been found.
@ -68,42 +68,42 @@ export interface ErrorWithCause {
* * iOS: `NSError.code` * * iOS: `NSError.code`
* * Android: N/A * * Android: N/A
*/ */
code?: number; code?: number
/** /**
* The native error's domain. * The native error's domain.
* *
* * iOS: `NSError.domain` * * iOS: `NSError.domain`
* * Android: N/A * * Android: N/A
*/ */
domain?: string; domain?: string
/** /**
* The native error description * The native error description
* *
* * iOS: `NSError.message` * * iOS: `NSError.message`
* * Android: `Throwable.message` * * Android: `Throwable.message`
*/ */
message: string; message: string
/** /**
* Optional additional details * Optional additional details
* *
* * iOS: `NSError.userInfo` * * iOS: `NSError.userInfo`
* * Android: N/A * * Android: N/A
*/ */
details?: Record<string, unknown>; details?: Record<string, unknown>
/** /**
* Optional Java stacktrace * Optional Java stacktrace
* *
* * iOS: N/A * * iOS: N/A
* * Android: `Throwable.stacktrace.toString()` * * Android: `Throwable.stacktrace.toString()`
*/ */
stacktrace?: string; stacktrace?: string
/** /**
* Optional additional cause for nested errors * Optional additional cause for nested errors
* *
* * iOS: N/A * * iOS: N/A
* * Android: `Throwable.cause` * * Android: `Throwable.cause`
*/ */
cause?: ErrorWithCause; cause?: ErrorWithCause
} }
type CameraErrorCode = type CameraErrorCode =
@ -114,42 +114,42 @@ type CameraErrorCode =
| SessionError | SessionError
| CaptureError | CaptureError
| SystemError | SystemError
| UnknownError; | UnknownError
/** /**
* Represents any kind of error that occured in the {@linkcode Camera} View Module. * Represents any kind of error that occured in the {@linkcode Camera} View Module.
*/ */
class CameraError<TCode extends CameraErrorCode> extends Error { class CameraError<TCode extends CameraErrorCode> extends Error {
private readonly _code: TCode; private readonly _code: TCode
private readonly _message: string; private readonly _message: string
private readonly _cause?: ErrorWithCause; private readonly _cause?: ErrorWithCause
public get code(): TCode { public get code(): TCode {
return this._code; return this._code
} }
public get message(): string { public get message(): string {
return this._message; return this._message
} }
public get cause(): Error | undefined { public get cause(): Error | undefined {
const c = this._cause; const c = this._cause
if (c == null) return undefined; if (c == null) return undefined
return new Error(`[${c.code}]: ${c.message}`); return new Error(`[${c.code}]: ${c.message}`)
} }
/** /**
* @internal * @internal
*/ */
constructor(code: TCode, message: string, cause?: ErrorWithCause) { constructor(code: TCode, message: string, cause?: ErrorWithCause) {
super(`[${code}]: ${message}${cause != null ? ` (Cause: ${cause.message})` : ''}`); super(`[${code}]: ${message}${cause != null ? ` (Cause: ${cause.message})` : ''}`)
super.name = code; super.name = code
super.message = message; super.message = message
this._code = code; this._code = code
this._message = message; this._message = message
this._cause = cause; this._cause = cause
} }
public toString(): string { public toString(): string {
return `[${this.code}]: ${this.message}`; return `[${this.code}]: ${this.message}`
} }
} }
@ -182,7 +182,7 @@ export const isErrorWithCause = (error: unknown): error is ErrorWithCause =>
// @ts-expect-error error is still unknown // @ts-expect-error error is still unknown
(typeof error.stacktrace === 'string' || error.stacktrace == null) && (typeof error.stacktrace === 'string' || error.stacktrace == null) &&
// @ts-expect-error error is still unknown // @ts-expect-error error is still unknown
(isErrorWithCause(error.cause) || error.cause == null); (isErrorWithCause(error.cause) || error.cause == null)
const isCameraErrorJson = (error: unknown): error is { code: string; message: string; cause?: ErrorWithCause } => const isCameraErrorJson = (error: unknown): error is { code: string; message: string; cause?: ErrorWithCause } =>
typeof error === 'object' && typeof error === 'object' &&
@ -192,7 +192,7 @@ const isCameraErrorJson = (error: unknown): error is { code: string; message: st
// @ts-expect-error error is still unknown // @ts-expect-error error is still unknown
typeof error.message === 'string' && typeof error.message === 'string' &&
// @ts-expect-error error is still unknown // @ts-expect-error error is still unknown
(typeof error.cause === 'object' || error.cause == null); (typeof error.cause === 'object' || error.cause == null)
/** /**
* Tries to parse an error coming from native to a typed JS camera error. * Tries to parse an error coming from native to a typed JS camera error.
@ -203,16 +203,16 @@ const isCameraErrorJson = (error: unknown): error is { code: string; message: st
export const tryParseNativeCameraError = <T>(nativeError: T): (CameraRuntimeError | CameraCaptureError) | T => { export const tryParseNativeCameraError = <T>(nativeError: T): (CameraRuntimeError | CameraCaptureError) | T => {
if (isCameraErrorJson(nativeError)) { if (isCameraErrorJson(nativeError)) {
if (nativeError.code.startsWith('capture')) { if (nativeError.code.startsWith('capture')) {
return new CameraCaptureError(nativeError.code as CaptureError, nativeError.message, nativeError.cause); return new CameraCaptureError(nativeError.code as CaptureError, nativeError.message, nativeError.cause)
} else { } else {
return new CameraRuntimeError( return new CameraRuntimeError(
// @ts-expect-error the code is string, we narrow it down to TS union. // @ts-expect-error the code is string, we narrow it down to TS union.
nativeError.code, nativeError.code,
nativeError.message, nativeError.message,
nativeError.cause, nativeError.cause,
); )
} }
} else { } else {
return nativeError; return nativeError
} }
}; }

View File

@ -1,13 +1,13 @@
import type { ViewProps } from 'react-native'; import type { ViewProps } from 'react-native'
import type { CameraDevice, CameraDeviceFormat, VideoStabilizationMode } from './CameraDevice'; import type { CameraDevice, CameraDeviceFormat, VideoStabilizationMode } from './CameraDevice'
import type { CameraRuntimeError } from './CameraError'; import type { CameraRuntimeError } from './CameraError'
import type { Frame } from './Frame'; import type { Frame } from './Frame'
import type { Orientation } from './Orientation'; import type { Orientation } from './Orientation'
export type FrameProcessor = { export type FrameProcessor = {
frameProcessor: (frame: Frame) => void; frameProcessor: (frame: Frame) => void
type: 'frame-processor'; type: 'frame-processor'
}; }
// TODO: Replace `enableHighQualityPhotos: boolean` in favor of `priorization: 'photo' | 'video'` // TODO: Replace `enableHighQualityPhotos: boolean` in favor of `priorization: 'photo' | 'video'`
// TODO: Use RCT_ENUM_PARSER for stuff like torch, videoStabilizationMode, and orientation // TODO: Use RCT_ENUM_PARSER for stuff like torch, videoStabilizationMode, and orientation
@ -34,7 +34,7 @@ export interface CameraProps extends ViewProps {
* ) * )
* ``` * ```
*/ */
device: CameraDevice; device: CameraDevice
/** /**
* Whether the Camera should actively stream video frames, or not. See the [documentation about the `isActive` prop](https://react-native-vision-camera.com/docs/guides/lifecycle#the-isactive-prop) for more information. * Whether the Camera should actively stream video frames, or not. See the [documentation about the `isActive` prop](https://react-native-vision-camera.com/docs/guides/lifecycle#the-isactive-prop) for more information.
* *
@ -42,23 +42,23 @@ export interface CameraProps extends ViewProps {
* *
* > Note: If you fully unmount the `<Camera>` component instead of using `isActive={false}`, the Camera will take a bit longer to start again. In return, it will use less resources since the Camera will be completely destroyed when unmounted. * > Note: If you fully unmount the `<Camera>` component instead of using `isActive={false}`, the Camera will take a bit longer to start again. In return, it will use less resources since the Camera will be completely destroyed when unmounted.
*/ */
isActive: boolean; isActive: boolean
//#region Use-cases //#region Use-cases
/** /**
* Enables **photo capture** with the `takePhoto` function (see ["Taking Photos"](https://react-native-vision-camera.com/docs/guides/capturing#taking-photos)) * Enables **photo capture** with the `takePhoto` function (see ["Taking Photos"](https://react-native-vision-camera.com/docs/guides/capturing#taking-photos))
*/ */
photo?: boolean; photo?: boolean
/** /**
* Enables **video capture** with the `startRecording` function (see ["Recording Videos"](https://react-native-vision-camera.com/docs/guides/capturing/#recording-videos)) * Enables **video capture** with the `startRecording` function (see ["Recording Videos"](https://react-native-vision-camera.com/docs/guides/capturing/#recording-videos))
* *
* Note: If both the `photo` and `video` properties are enabled at the same time and the device is running at a `hardwareLevel` of `'legacy'` or `'limited'`, VisionCamera _might_ use a lower resolution for video capture due to hardware constraints. * Note: If both the `photo` and `video` properties are enabled at the same time and the device is running at a `hardwareLevel` of `'legacy'` or `'limited'`, VisionCamera _might_ use a lower resolution for video capture due to hardware constraints.
*/ */
video?: boolean; video?: boolean
/** /**
* Enables **audio capture** for video recordings (see ["Recording Videos"](https://react-native-vision-camera.com/docs/guides/capturing/#recording-videos)) * Enables **audio capture** for video recordings (see ["Recording Videos"](https://react-native-vision-camera.com/docs/guides/capturing/#recording-videos))
*/ */
audio?: boolean; audio?: boolean
/** /**
* Specifies the pixel format for the video pipeline. * Specifies the pixel format for the video pipeline.
* *
@ -72,7 +72,7 @@ export interface CameraProps extends ViewProps {
* *
* @default `native` * @default `native`
*/ */
pixelFormat?: 'native' | 'yuv' | 'rgb'; pixelFormat?: 'native' | 'yuv' | 'rgb'
//#endregion //#endregion
//#region Common Props (torch, zoom) //#region Common Props (torch, zoom)
@ -83,7 +83,7 @@ export interface CameraProps extends ViewProps {
* *
* @default "off" * @default "off"
*/ */
torch?: 'off' | 'on'; torch?: 'off' | 'on'
/** /**
* Specifies the zoom factor of the current camera, in "factor"/scale. * Specifies the zoom factor of the current camera, in "factor"/scale.
* *
@ -95,7 +95,7 @@ export interface CameraProps extends ViewProps {
* *
* @default 1.0 * @default 1.0
*/ */
zoom?: number; zoom?: number
/** /**
* Enables or disables the native pinch to zoom gesture. * Enables or disables the native pinch to zoom gesture.
* *
@ -103,14 +103,14 @@ export interface CameraProps extends ViewProps {
* *
* @default false * @default false
*/ */
enableZoomGesture?: boolean; enableZoomGesture?: boolean
//#endregion //#endregion
//#region Format/Preset selection //#region Format/Preset selection
/** /**
* Selects a given format. By default, the best matching format is chosen. * Selects a given format. By default, the best matching format is chosen.
*/ */
format?: CameraDeviceFormat; format?: CameraDeviceFormat
/** /**
* Specifies the Preview's resize mode. * Specifies the Preview's resize mode.
* * `"cover"`: Keep aspect ratio and fill entire parent view (centered). * * `"cover"`: Keep aspect ratio and fill entire parent view (centered).
@ -118,19 +118,19 @@ export interface CameraProps extends ViewProps {
* *
* @default "cover" * @default "cover"
*/ */
resizeMode?: 'cover' | 'contain'; resizeMode?: 'cover' | 'contain'
/** /**
* Specify the frames per second this camera should use. Make sure the given `format` includes a frame rate range with the given `fps`. * Specify the frames per second this camera should use. Make sure the given `format` includes a frame rate range with the given `fps`.
* *
* Requires `format` to be set that supports the given `fps`. * Requires `format` to be set that supports the given `fps`.
*/ */
fps?: number; fps?: number
/** /**
* Enables or disables HDR on this camera device. Make sure the given `format` supports HDR mode. * Enables or disables HDR on this camera device. Make sure the given `format` supports HDR mode.
* *
* Requires `format` to be set that supports `photoHDR`/`videoHDR`. * Requires `format` to be set that supports `photoHDR`/`videoHDR`.
*/ */
hdr?: boolean; hdr?: boolean
/** /**
* Enables or disables lossless buffer compression for the video stream. * Enables or disables lossless buffer compression for the video stream.
* If you only use {@linkcode video} or a {@linkcode frameProcessor}, this * If you only use {@linkcode video} or a {@linkcode frameProcessor}, this
@ -151,19 +151,19 @@ export interface CameraProps extends ViewProps {
* - true // if video={true} and frameProcessor={undefined} * - true // if video={true} and frameProcessor={undefined}
* - false // otherwise * - false // otherwise
*/ */
enableBufferCompression?: boolean; enableBufferCompression?: boolean
/** /**
* Enables or disables low-light boost on this camera device. Make sure the given `format` supports low-light boost. * Enables or disables low-light boost on this camera device. Make sure the given `format` supports low-light boost.
* *
* Requires a `format` to be set that supports `lowLightBoost`. * Requires a `format` to be set that supports `lowLightBoost`.
*/ */
lowLightBoost?: boolean; lowLightBoost?: boolean
/** /**
* Specifies the video stabilization mode to use. * Specifies the video stabilization mode to use.
* *
* Requires a `format` to be set that contains the given `videoStabilizationMode`. * Requires a `format` to be set that contains the given `videoStabilizationMode`.
*/ */
videoStabilizationMode?: VideoStabilizationMode; videoStabilizationMode?: VideoStabilizationMode
//#endregion //#endregion
/** /**
@ -171,7 +171,7 @@ export interface CameraProps extends ViewProps {
* *
* @default false * @default false
*/ */
enableDepthData?: boolean; enableDepthData?: boolean
/** /**
* A boolean specifying whether the photo render pipeline is prepared for portrait effects matte delivery. * A boolean specifying whether the photo render pipeline is prepared for portrait effects matte delivery.
* *
@ -180,7 +180,7 @@ export interface CameraProps extends ViewProps {
* @platform iOS 12.0+ * @platform iOS 12.0+
* @default false * @default false
*/ */
enablePortraitEffectsMatteDelivery?: boolean; enablePortraitEffectsMatteDelivery?: boolean
/** /**
* Indicates whether the Camera should prepare the photo pipeline to provide maximum quality photos. * Indicates whether the Camera should prepare the photo pipeline to provide maximum quality photos.
* *
@ -192,28 +192,28 @@ export interface CameraProps extends ViewProps {
* *
* @default false * @default false
*/ */
enableHighQualityPhotos?: boolean; enableHighQualityPhotos?: boolean
/** /**
* If `true`, show a debug view to display the FPS of the Camera session. * If `true`, show a debug view to display the FPS of the Camera session.
* This is useful for debugging your Frame Processor's speed. * This is useful for debugging your Frame Processor's speed.
* *
* @default false * @default false
*/ */
enableFpsGraph?: boolean; enableFpsGraph?: boolean
/** /**
* Represents the orientation of all Camera Outputs (Photo, Video, and Frame Processor). If this value is not set, the device orientation is used. * Represents the orientation of all Camera Outputs (Photo, Video, and Frame Processor). If this value is not set, the device orientation is used.
*/ */
orientation?: Orientation; orientation?: Orientation
//#region Events //#region Events
/** /**
* Called when any kind of runtime error occured. * Called when any kind of runtime error occured.
*/ */
onError?: (error: CameraRuntimeError) => void; onError?: (error: CameraRuntimeError) => void
/** /**
* Called when the camera was successfully initialized. * Called when the camera was successfully initialized.
*/ */
onInitialized?: () => void; onInitialized?: () => void
/** /**
* A worklet which will be called for every frame the Camera "sees". * A worklet which will be called for every frame the Camera "sees".
* *
@ -230,6 +230,6 @@ export interface CameraProps extends ViewProps {
* return <Camera {...cameraProps} frameProcessor={frameProcessor} /> * return <Camera {...cameraProps} frameProcessor={frameProcessor} />
* ``` * ```
*/ */
frameProcessor?: FrameProcessor; frameProcessor?: FrameProcessor
//#endregion //#endregion
} }

View File

@ -1,5 +1,5 @@
import type { Orientation } from './Orientation'; import type { Orientation } from './Orientation'
import { PixelFormat } from './PixelFormat'; import { PixelFormat } from './PixelFormat'
/** /**
* A single frame, as seen by the camera. This is backed by a C++ HostObject wrapping the native GPU buffer. * A single frame, as seen by the camera. This is backed by a C++ HostObject wrapping the native GPU buffer.
@ -18,42 +18,42 @@ export interface Frame {
* Whether the underlying buffer is still valid or not. * Whether the underlying buffer is still valid or not.
* A Frame is valid as long as your Frame Processor (or a `runAsync(..)` operation) is still running * A Frame is valid as long as your Frame Processor (or a `runAsync(..)` operation) is still running
*/ */
isValid: boolean; isValid: boolean
/** /**
* Returns the width of the frame, in pixels. * Returns the width of the frame, in pixels.
*/ */
width: number; width: number
/** /**
* Returns the height of the frame, in pixels. * Returns the height of the frame, in pixels.
*/ */
height: number; height: number
/** /**
* Returns the amount of bytes per row. * Returns the amount of bytes per row.
*/ */
bytesPerRow: number; bytesPerRow: number
/** /**
* Returns the number of planes this frame contains. * Returns the number of planes this frame contains.
*/ */
planesCount: number; planesCount: number
/** /**
* Returns whether the Frame is mirrored (selfie camera) or not. * Returns whether the Frame is mirrored (selfie camera) or not.
*/ */
isMirrored: boolean; isMirrored: boolean
/** /**
* Returns the timestamp of the Frame relative to the host sytem's clock. * Returns the timestamp of the Frame relative to the host sytem's clock.
*/ */
timestamp: number; timestamp: number
/** /**
* Represents the orientation of the Frame. * Represents the orientation of the Frame.
* *
* Some ML Models are trained for specific orientations, so they need to be taken into * Some ML Models are trained for specific orientations, so they need to be taken into
* consideration when running a frame processor. See also: {@linkcode isMirrored} * consideration when running a frame processor. See also: {@linkcode isMirrored}
*/ */
orientation: Orientation; orientation: Orientation
/** /**
* Represents the pixel-format of the Frame. * Represents the pixel-format of the Frame.
*/ */
pixelFormat: PixelFormat; pixelFormat: PixelFormat
/** /**
* Get the underlying data of the Frame as a uint8 array buffer. * Get the underlying data of the Frame as a uint8 array buffer.
@ -73,7 +73,7 @@ export interface Frame {
* }, []) * }, [])
* ``` * ```
*/ */
toArrayBuffer(): Uint8Array; toArrayBuffer(): Uint8Array
/** /**
* Returns a string representation of the frame. * Returns a string representation of the frame.
* @example * @example
@ -81,7 +81,7 @@ export interface Frame {
* console.log(frame.toString()) // -> "3840 x 2160 Frame" * console.log(frame.toString()) // -> "3840 x 2160 Frame"
* ``` * ```
*/ */
toString(): string; toString(): string
} }
/** @internal */ /** @internal */
@ -92,12 +92,12 @@ export interface FrameInternal extends Frame {
* This is a private API, do not use this. * This is a private API, do not use this.
* @internal * @internal
*/ */
incrementRefCount(): void; incrementRefCount(): void
/** /**
* Increment the Frame Buffer ref-count by one. * Increment the Frame Buffer ref-count by one.
* *
* This is a private API, do not use this. * This is a private API, do not use this.
* @internal * @internal
*/ */
decrementRefCount(): void; decrementRefCount(): void
} }

View File

@ -1,14 +1,14 @@
import type { Frame, FrameInternal } from './Frame'; import type { Frame, FrameInternal } from './Frame'
import type { FrameProcessor } from './CameraProps'; import type { FrameProcessor } from './CameraProps'
import { CameraRuntimeError } from './CameraError'; import { CameraRuntimeError } from './CameraError'
// only import typescript types // only import typescript types
import type TWorklets from 'react-native-worklets-core'; import type TWorklets from 'react-native-worklets-core'
import { CameraModule } from './NativeCameraModule'; import { CameraModule } from './NativeCameraModule'
import { assertJSIAvailable } from './JSIHelper'; import { assertJSIAvailable } from './JSIHelper'
type BasicParameterType = string | number | boolean | undefined; type BasicParameterType = string | number | boolean | undefined
type ParameterType = BasicParameterType | BasicParameterType[] | Record<string, BasicParameterType | undefined>; type ParameterType = BasicParameterType | BasicParameterType[] | Record<string, BasicParameterType | undefined>
interface FrameProcessorPlugin { interface FrameProcessorPlugin {
/** /**
@ -17,96 +17,97 @@ interface FrameProcessorPlugin {
* @param options (optional) Additional options. Options will be converted to a native dictionary * @param options (optional) Additional options. Options will be converted to a native dictionary
* @returns (optional) A value returned from the native Frame Processor Plugin (or undefined) * @returns (optional) A value returned from the native Frame Processor Plugin (or undefined)
*/ */
call: (frame: Frame, options?: Record<string, ParameterType>) => ParameterType; call: (frame: Frame, options?: Record<string, ParameterType>) => ParameterType
} }
interface TVisionCameraProxy { interface TVisionCameraProxy {
setFrameProcessor: (viewTag: number, frameProcessor: FrameProcessor) => void; setFrameProcessor: (viewTag: number, frameProcessor: FrameProcessor) => void
removeFrameProcessor: (viewTag: number) => void; removeFrameProcessor: (viewTag: number) => void
/** /**
* Creates a new instance of a Frame Processor Plugin. * Creates a new instance of a Frame Processor Plugin.
* The Plugin has to be registered on the native side, otherwise this returns `undefined` * The Plugin has to be registered on the native side, otherwise this returns `undefined`
*/ */
getFrameProcessorPlugin: (name: string) => FrameProcessorPlugin | undefined; getFrameProcessorPlugin: (name: string) => FrameProcessorPlugin | undefined
} }
let hasWorklets = false; let hasWorklets = false
let isAsyncContextBusy = { value: false }; let isAsyncContextBusy = { value: false }
let runOnAsyncContext = (_frame: Frame, _func: () => void): void => { let runOnAsyncContext = (_frame: Frame, _func: () => void): void => {
throw new CameraRuntimeError( throw new CameraRuntimeError(
'system/frame-processors-unavailable', 'system/frame-processors-unavailable',
'Frame Processors are not available, react-native-worklets-core is not installed!', 'Frame Processors are not available, react-native-worklets-core is not installed!',
); )
}; }
try { try {
assertJSIAvailable(); assertJSIAvailable()
// eslint-disable-next-line @typescript-eslint/no-var-requires // eslint-disable-next-line @typescript-eslint/no-var-requires
const { Worklets } = require('react-native-worklets-core') as typeof TWorklets; const { Worklets } = require('react-native-worklets-core') as typeof TWorklets
isAsyncContextBusy = Worklets.createSharedValue(false); isAsyncContextBusy = Worklets.createSharedValue(false)
const asyncContext = Worklets.createContext('VisionCamera.async'); const asyncContext = Worklets.createContext('VisionCamera.async')
runOnAsyncContext = Worklets.createRunInContextFn((frame: Frame, func: () => void) => { runOnAsyncContext = Worklets.createRunInContextFn((frame: Frame, func: () => void) => {
'worklet'; 'worklet'
try { try {
// Call long-running function // Call long-running function
func(); func()
} finally { } finally {
// Potentially delete Frame if we were the last ref // Potentially delete Frame if we were the last ref
(frame as FrameInternal).decrementRefCount(); const internal = frame as FrameInternal
internal.decrementRefCount()
isAsyncContextBusy.value = false; isAsyncContextBusy.value = false
} }
}, asyncContext); }, asyncContext)
hasWorklets = true; hasWorklets = true
} catch (e) { } catch (e) {
// Worklets are not installed, so Frame Processors are disabled. // Worklets are not installed, so Frame Processors are disabled.
} }
let proxy: TVisionCameraProxy = { let proxy: TVisionCameraProxy = {
getFrameProcessorPlugin: () => { getFrameProcessorPlugin: () => {
throw new CameraRuntimeError('system/frame-processors-unavailable', 'Frame Processors are not enabled!'); throw new CameraRuntimeError('system/frame-processors-unavailable', 'Frame Processors are not enabled!')
}, },
removeFrameProcessor: () => { removeFrameProcessor: () => {
throw new CameraRuntimeError('system/frame-processors-unavailable', 'Frame Processors are not enabled!'); throw new CameraRuntimeError('system/frame-processors-unavailable', 'Frame Processors are not enabled!')
}, },
setFrameProcessor: () => { setFrameProcessor: () => {
throw new CameraRuntimeError('system/frame-processors-unavailable', 'Frame Processors are not enabled!'); throw new CameraRuntimeError('system/frame-processors-unavailable', 'Frame Processors are not enabled!')
}, },
}; }
if (hasWorklets) { if (hasWorklets) {
// Install native Frame Processor Runtime Manager // Install native Frame Processor Runtime Manager
const result = CameraModule.installFrameProcessorBindings() as unknown; const result = CameraModule.installFrameProcessorBindings() as unknown
if (result !== true) if (result !== true)
throw new CameraRuntimeError('system/frame-processors-unavailable', 'Failed to install Frame Processor JSI bindings!'); throw new CameraRuntimeError('system/frame-processors-unavailable', 'Failed to install Frame Processor JSI bindings!')
// @ts-expect-error global is untyped, it's a C++ host-object // @ts-expect-error global is untyped, it's a C++ host-object
proxy = global.VisionCameraProxy as TVisionCameraProxy; proxy = global.VisionCameraProxy as TVisionCameraProxy
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (proxy == null) { if (proxy == null) {
throw new CameraRuntimeError( throw new CameraRuntimeError(
'system/frame-processors-unavailable', 'system/frame-processors-unavailable',
'Failed to install VisionCameraProxy. Are Frame Processors properly enabled?', 'Failed to install VisionCameraProxy. Are Frame Processors properly enabled?',
); )
} }
} }
export const VisionCameraProxy = proxy; export const VisionCameraProxy = proxy
declare global { declare global {
// eslint-disable-next-line no-var // eslint-disable-next-line no-var
var __frameProcessorRunAtTargetFpsMap: Record<string, number | undefined> | undefined; var __frameProcessorRunAtTargetFpsMap: Record<string, number | undefined> | undefined
} }
function getLastFrameProcessorCall(frameProcessorFuncId: string): number { function getLastFrameProcessorCall(frameProcessorFuncId: string): number {
'worklet'; 'worklet'
return global.__frameProcessorRunAtTargetFpsMap?.[frameProcessorFuncId] ?? 0; return global.__frameProcessorRunAtTargetFpsMap?.[frameProcessorFuncId] ?? 0
} }
function setLastFrameProcessorCall(frameProcessorFuncId: string, value: number): void { function setLastFrameProcessorCall(frameProcessorFuncId: string, value: number): void {
'worklet'; 'worklet'
if (global.__frameProcessorRunAtTargetFpsMap == null) global.__frameProcessorRunAtTargetFpsMap = {}; if (global.__frameProcessorRunAtTargetFpsMap == null) global.__frameProcessorRunAtTargetFpsMap = {}
global.__frameProcessorRunAtTargetFpsMap[frameProcessorFuncId] = value; global.__frameProcessorRunAtTargetFpsMap[frameProcessorFuncId] = value
} }
/** /**
@ -134,20 +135,20 @@ function setLastFrameProcessorCall(frameProcessorFuncId: string, value: number):
* ``` * ```
*/ */
export function runAtTargetFps<T>(fps: number, func: () => T): T | undefined { export function runAtTargetFps<T>(fps: number, func: () => T): T | undefined {
'worklet'; 'worklet'
// @ts-expect-error // @ts-expect-error
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const funcId = func.__workletHash ?? '1'; const funcId = func.__workletHash ?? '1'
const targetIntervalMs = 1000 / fps; // <-- 60 FPS => 16,6667ms interval const targetIntervalMs = 1000 / fps // <-- 60 FPS => 16,6667ms interval
const now = performance.now(); const now = performance.now()
const diffToLastCall = now - getLastFrameProcessorCall(funcId); const diffToLastCall = now - getLastFrameProcessorCall(funcId)
if (diffToLastCall >= targetIntervalMs) { if (diffToLastCall >= targetIntervalMs) {
setLastFrameProcessorCall(funcId, now); setLastFrameProcessorCall(funcId, now)
// Last Frame Processor call is already so long ago that we want to make a new call // Last Frame Processor call is already so long ago that we want to make a new call
return func(); return func()
} }
return undefined; return undefined
} }
/** /**
@ -175,19 +176,20 @@ export function runAtTargetFps<T>(fps: number, func: () => T): T | undefined {
* ``` * ```
*/ */
export function runAsync(frame: Frame, func: () => void): void { export function runAsync(frame: Frame, func: () => void): void {
'worklet'; 'worklet'
if (isAsyncContextBusy.value) { if (isAsyncContextBusy.value) {
// async context is currently busy, we cannot schedule new work in time. // async context is currently busy, we cannot schedule new work in time.
// drop this frame/runAsync call. // drop this frame/runAsync call.
return; return
} }
// Increment ref count by one // Increment ref count by one
(frame as FrameInternal).incrementRefCount(); const internal = frame as FrameInternal
internal.incrementRefCount()
isAsyncContextBusy.value = true; isAsyncContextBusy.value = true
// Call in separate background context // Call in separate background context
runOnAsyncContext(frame, func); runOnAsyncContext(frame, func)
} }

View File

@ -1,4 +1,4 @@
import { CameraRuntimeError } from './CameraError'; import { CameraRuntimeError } from './CameraError'
export function assertJSIAvailable(): void { export function assertJSIAvailable(): void {
// Check if we are running on-device (JSI) // Check if we are running on-device (JSI)
@ -7,6 +7,6 @@ export function assertJSIAvailable(): void {
throw new CameraRuntimeError( throw new CameraRuntimeError(
'system/frame-processors-unavailable', 'system/frame-processors-unavailable',
'Failed to initialize VisionCamera Frame Processors: React Native is not running on-device. Frame Processors can only be used when synchronous method invocations (JSI) are possible. If you are using a remote debugger (e.g. Chrome), switch to an on-device debugger (e.g. Flipper) instead.', 'Failed to initialize VisionCamera Frame Processors: React Native is not running on-device. Frame Processors can only be used when synchronous method invocations (JSI) are possible. If you are using a remote debugger (e.g. Chrome), switch to an on-device debugger (e.g. Flipper) instead.',
); )
} }
} }

View File

@ -1,42 +1,42 @@
import { NativeModules, Platform } from 'react-native'; import { NativeModules, Platform } from 'react-native'
import { CameraRuntimeError } from './CameraError'; import { CameraRuntimeError } from './CameraError'
const supportedPlatforms = ['ios', 'android', 'macos']; const supportedPlatforms = ['ios', 'android', 'macos']
// NativeModules automatically resolves 'CameraView' to 'CameraViewModule' // NativeModules automatically resolves 'CameraView' to 'CameraViewModule'
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
export const CameraModule = NativeModules.CameraView; export const CameraModule = NativeModules.CameraView
if (CameraModule == null) { if (CameraModule == null) {
if (!supportedPlatforms.includes(Platform.OS)) { if (!supportedPlatforms.includes(Platform.OS)) {
throw new CameraRuntimeError( throw new CameraRuntimeError(
'system/camera-module-not-found', 'system/camera-module-not-found',
`Failed to initialize VisionCamera: VisionCamera currently does not work on ${Platform.OS}.`, `Failed to initialize VisionCamera: VisionCamera currently does not work on ${Platform.OS}.`,
); )
} }
let message = 'Failed to initialize VisionCamera: The native Camera Module (`NativeModules.CameraView`) could not be found.'; let message = 'Failed to initialize VisionCamera: The native Camera Module (`NativeModules.CameraView`) could not be found.'
message += '\n* Make sure react-native-vision-camera is correctly autolinked (run `npx react-native config` to verify)'; message += '\n* Make sure react-native-vision-camera is correctly autolinked (run `npx react-native config` to verify)'
if (Platform.OS === 'ios' || Platform.OS === 'macos') message += '\n* Make sure you ran `pod install` in the ios/ directory.'; if (Platform.OS === 'ios' || Platform.OS === 'macos') message += '\n* Make sure you ran `pod install` in the ios/ directory.'
if (Platform.OS === 'android') message += '\n* Make sure gradle is synced.'; if (Platform.OS === 'android') message += '\n* Make sure gradle is synced.'
// check if Expo // check if Expo
// @ts-expect-error expo global JSI modules are not typed // @ts-expect-error expo global JSI modules are not typed
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const ExpoConstants = global.expo?.modules?.ExponentConstants; const ExpoConstants = global.expo?.modules?.ExponentConstants
if (ExpoConstants != null) { if (ExpoConstants != null) {
if (ExpoConstants.appOwnership === 'expo') { if (ExpoConstants.appOwnership === 'expo') {
// We're running Expo Go // We're running Expo Go
throw new CameraRuntimeError( throw new CameraRuntimeError(
'system/camera-module-not-found', 'system/camera-module-not-found',
`react-native-vision-camera is not supported in Expo Go! Use EAS/expo prebuild instead (\`expo run:${Platform.OS}\`). For more info, see https://docs.expo.dev/workflow/prebuild/.`, `react-native-vision-camera is not supported in Expo Go! Use EAS/expo prebuild instead (\`expo run:${Platform.OS}\`). For more info, see https://docs.expo.dev/workflow/prebuild/.`,
); )
} else { } else {
// We're running Expo bare / standalone // We're running Expo bare / standalone
message += '\n* Make sure you ran `expo prebuild`.'; message += '\n* Make sure you ran `expo prebuild`.'
} }
} }
message += '\n* Make sure you rebuilt the app.'; message += '\n* Make sure you rebuilt the app.'
throw new CameraRuntimeError('system/camera-module-not-found', message); throw new CameraRuntimeError('system/camera-module-not-found', message)
} }

View File

@ -7,4 +7,4 @@
* - `portrait-upside-down`: **180°** (home-button at the top) * - `portrait-upside-down`: **180°** (home-button at the top)
* - `landscape-right`: **270°** (home-button on the right) * - `landscape-right`: **270°** (home-button on the right)
*/ */
export type Orientation = 'portrait' | 'portrait-upside-down' | 'landscape-left' | 'landscape-right'; export type Orientation = 'portrait' | 'portrait-upside-down' | 'landscape-left' | 'landscape-right'

View File

@ -1,5 +1,5 @@
import { Orientation } from './Orientation'; import { Orientation } from './Orientation'
import type { TemporaryFile } from './TemporaryFile'; import type { TemporaryFile } from './TemporaryFile'
export interface TakePhotoOptions { export interface TakePhotoOptions {
/** /**
@ -11,25 +11,25 @@ export interface TakePhotoOptions {
* *
* @default "balanced" * @default "balanced"
*/ */
qualityPrioritization?: 'quality' | 'balanced' | 'speed'; qualityPrioritization?: 'quality' | 'balanced' | 'speed'
/** /**
* Whether the Flash should be enabled or disabled * Whether the Flash should be enabled or disabled
* *
* @default "auto" * @default "auto"
*/ */
flash?: 'on' | 'off' | 'auto'; flash?: 'on' | 'off' | 'auto'
/** /**
* Specifies whether red-eye reduction should be applied automatically on flash captures. * Specifies whether red-eye reduction should be applied automatically on flash captures.
* *
* @default false * @default false
*/ */
enableAutoRedEyeReduction?: boolean; enableAutoRedEyeReduction?: boolean
/** /**
* Indicates whether still image stabilization will be enabled when capturing the photo * Indicates whether still image stabilization will be enabled when capturing the photo
* *
* @default false * @default false
*/ */
enableAutoStabilization?: boolean; enableAutoStabilization?: boolean
/** /**
* Specifies whether the photo output should use content aware distortion correction on this photo request. * Specifies whether the photo output should use content aware distortion correction on this photo request.
* For example, the algorithm may not apply correction to faces in the center of a photo, but may apply it to faces near the photos edges. * For example, the algorithm may not apply correction to faces in the center of a photo, but may apply it to faces near the photos edges.
@ -37,13 +37,13 @@ export interface TakePhotoOptions {
* @platform iOS * @platform iOS
* @default false * @default false
*/ */
enableAutoDistortionCorrection?: boolean; enableAutoDistortionCorrection?: boolean
/** /**
* Whether to play the default shutter "click" sound when taking a picture or not. * Whether to play the default shutter "click" sound when taking a picture or not.
* *
* @default true * @default true
*/ */
enableShutterSound?: boolean; enableShutterSound?: boolean
} }
/** /**
@ -55,26 +55,26 @@ export interface PhotoFile extends TemporaryFile {
/** /**
* The width of the photo, in pixels. * The width of the photo, in pixels.
*/ */
width: number; width: number
/** /**
* The height of the photo, in pixels. * The height of the photo, in pixels.
*/ */
height: number; height: number
/** /**
* Whether this photo is in RAW format or not. * Whether this photo is in RAW format or not.
*/ */
isRawPhoto: boolean; isRawPhoto: boolean
/** /**
* Display orientation of the photo, relative to the Camera's sensor orientation. * Display orientation of the photo, relative to the Camera's sensor orientation.
* *
* Note that Camera sensors are landscape, so e.g. "portrait" photos will have a value of "landscape-left", etc. * Note that Camera sensors are landscape, so e.g. "portrait" photos will have a value of "landscape-left", etc.
*/ */
orientation: Orientation; orientation: Orientation
/** /**
* Whether this photo is mirrored (selfies) or not. * Whether this photo is mirrored (selfies) or not.
*/ */
isMirrored: boolean; isMirrored: boolean
thumbnail?: Record<string, unknown>; thumbnail?: Record<string, unknown>
/** /**
* Metadata information describing the captured image. (iOS only) * Metadata information describing the captured image. (iOS only)
* *
@ -95,66 +95,66 @@ export interface PhotoFile extends TemporaryFile {
* * 7 = 270 degrees: image has been flipped back-to-front and is on its far side. * * 7 = 270 degrees: image has been flipped back-to-front and is on its far side.
* * 8 = 270 degrees, mirrored: image is on its far side. * * 8 = 270 degrees, mirrored: image is on its far side.
*/ */
Orientation: number; Orientation: number
/** /**
* @platform iOS * @platform iOS
*/ */
DPIHeight: number; DPIHeight: number
/** /**
* @platform iOS * @platform iOS
*/ */
DPIWidth: number; DPIWidth: number
/** /**
* Represents any data Apple cameras write to the metadata * Represents any data Apple cameras write to the metadata
* *
* @platform iOS * @platform iOS
*/ */
'{MakerApple}'?: Record<string, unknown>; '{MakerApple}'?: Record<string, unknown>
'{TIFF}': { '{TIFF}': {
ResolutionUnit: number; ResolutionUnit: number
Software: string; Software: string
Make: string; Make: string
DateTime: string; DateTime: string
XResolution: number; XResolution: number
/** /**
* @platform iOS * @platform iOS
*/ */
HostComputer?: string; HostComputer?: string
Model: string; Model: string
YResolution: number; YResolution: number
}; }
'{Exif}': { '{Exif}': {
DateTimeOriginal: string; DateTimeOriginal: string
ExposureTime: number; ExposureTime: number
FNumber: number; FNumber: number
LensSpecification: number[]; LensSpecification: number[]
ExposureBiasValue: number; ExposureBiasValue: number
ColorSpace: number; ColorSpace: number
FocalLenIn35mmFilm: number; FocalLenIn35mmFilm: number
BrightnessValue: number; BrightnessValue: number
ExposureMode: number; ExposureMode: number
LensModel: string; LensModel: string
SceneType: number; SceneType: number
PixelXDimension: number; PixelXDimension: number
ShutterSpeedValue: number; ShutterSpeedValue: number
SensingMethod: number; SensingMethod: number
SubjectArea: number[]; SubjectArea: number[]
ApertureValue: number; ApertureValue: number
SubsecTimeDigitized: string; SubsecTimeDigitized: string
FocalLength: number; FocalLength: number
LensMake: string; LensMake: string
SubsecTimeOriginal: string; SubsecTimeOriginal: string
OffsetTimeDigitized: string; OffsetTimeDigitized: string
PixelYDimension: number; PixelYDimension: number
ISOSpeedRatings: number[]; ISOSpeedRatings: number[]
WhiteBalance: number; WhiteBalance: number
DateTimeDigitized: string; DateTimeDigitized: string
OffsetTimeOriginal: string; OffsetTimeOriginal: string
ExifVersion: string; ExifVersion: string
OffsetTime: string; OffsetTime: string
Flash: number; Flash: number
ExposureProgram: number; ExposureProgram: number
MeteringMode: number; MeteringMode: number
}; }
}; }
} }

View File

@ -12,4 +12,4 @@
* - `native`: Frame is in the Camera's native Hardware Buffer format (PRIVATE). This is the most efficient Format. * - `native`: Frame is in the Camera's native Hardware Buffer format (PRIVATE). This is the most efficient Format.
* - `unknown`: Frame has unknown/unsupported pixel-format. * - `unknown`: Frame has unknown/unsupported pixel-format.
*/ */
export type PixelFormat = 'yuv' | 'rgb' | 'dng' | 'native' | 'unknown'; export type PixelFormat = 'yuv' | 'rgb' | 'dng' | 'native' | 'unknown'

View File

@ -5,9 +5,9 @@ export interface Point {
/** /**
* The X coordinate of this Point. (double) * The X coordinate of this Point. (double)
*/ */
x: number; x: number
/** /**
* The Y coordinate of this Point. (double) * The Y coordinate of this Point. (double)
*/ */
y: number; y: number
} }

View File

@ -9,5 +9,5 @@ export interface TemporaryFile {
* *
* * **Note:** This file might get deleted once the app closes because it lives in the temp directory. * * **Note:** This file might get deleted once the app closes because it lives in the temp directory.
*/ */
path: string; path: string
} }

View File

@ -1,29 +1,29 @@
import type { CameraCaptureError } from './CameraError'; import type { CameraCaptureError } from './CameraError'
import type { TemporaryFile } from './TemporaryFile'; import type { TemporaryFile } from './TemporaryFile'
export interface RecordVideoOptions { export interface RecordVideoOptions {
/** /**
* Set the video flash mode. Natively, this just enables the torch while recording. * Set the video flash mode. Natively, this just enables the torch while recording.
*/ */
flash?: 'on' | 'off' | 'auto'; flash?: 'on' | 'off' | 'auto'
/** /**
* Specifies the output file type to record videos into. * Specifies the output file type to record videos into.
*/ */
fileType?: 'mov' | 'mp4'; fileType?: 'mov' | 'mp4'
/** /**
* Called when there was an unexpected runtime error while recording the video. * Called when there was an unexpected runtime error while recording the video.
*/ */
onRecordingError: (error: CameraCaptureError) => void; onRecordingError: (error: CameraCaptureError) => void
/** /**
* Called when the recording has been successfully saved to file. * Called when the recording has been successfully saved to file.
*/ */
onRecordingFinished: (video: VideoFile) => void; onRecordingFinished: (video: VideoFile) => void
/** /**
* The Video Codec to record in. * The Video Codec to record in.
* - `h264`: Widely supported, but might be less efficient, especially with larger sizes or framerates. * - `h264`: Widely supported, but might be less efficient, especially with larger sizes or framerates.
* - `h265`: The HEVC (High-Efficient-Video-Codec) for higher efficient video recordings. * - `h265`: The HEVC (High-Efficient-Video-Codec) for higher efficient video recordings.
*/ */
videoCodec?: 'h264' | 'h265'; videoCodec?: 'h264' | 'h265'
} }
/** /**
@ -35,5 +35,5 @@ export interface VideoFile extends TemporaryFile {
/** /**
* Represents the duration of the video, in seconds. * Represents the duration of the video, in seconds.
*/ */
duration: number; duration: number
} }

View File

@ -1,13 +1,13 @@
import { Dimensions } from 'react-native'; import { Dimensions } from 'react-native'
import { FormatFilter } from './getCameraFormat'; import { FormatFilter } from './getCameraFormat'
type TTemplates = { type TTemplates = {
[key: string]: FormatFilter[]; [key: string]: FormatFilter[]
}; }
const SnapchatResolution = { width: 1920, height: 1080 }; const SnapchatResolution = { width: 1920, height: 1080 }
const InstagramResolution = { width: 3840, height: 2160 }; const InstagramResolution = { width: 3840, height: 2160 }
const ScreenAspectRatio = Dimensions.get('window').height / Dimensions.get('window').width; const ScreenAspectRatio = Dimensions.get('window').height / Dimensions.get('window').width
/** /**
* Predefined templates for use in `useCameraFormat`/`getCameraFormat`. * Predefined templates for use in `useCameraFormat`/`getCameraFormat`.
@ -69,4 +69,4 @@ export const Templates: TTemplates = {
{ photoAspectRatio: ScreenAspectRatio }, { photoAspectRatio: ScreenAspectRatio },
{ photoResolution: InstagramResolution }, { photoResolution: InstagramResolution },
], ],
}; }

View File

@ -1,4 +1,4 @@
import { CameraDevice, CameraPosition, PhysicalCameraDeviceType } from '../CameraDevice'; import { CameraDevice, CameraPosition, PhysicalCameraDeviceType } from '../CameraDevice'
export interface DeviceFilter { export interface DeviceFilter {
/** /**
@ -19,7 +19,7 @@ export interface DeviceFilter {
* getCameraDevice({ physicalDevices: ['ultra-wide-angle-camera', 'wide-angle-camera', 'telephoto-camera'] }) * getCameraDevice({ physicalDevices: ['ultra-wide-angle-camera', 'wide-angle-camera', 'telephoto-camera'] })
* ``` * ```
*/ */
physicalDevices?: PhysicalCameraDeviceType[]; physicalDevices?: PhysicalCameraDeviceType[]
} }
/** /**
@ -36,26 +36,26 @@ export interface DeviceFilter {
* ``` * ```
*/ */
export function getCameraDevice(devices: CameraDevice[], position: CameraPosition, filter: DeviceFilter = {}): CameraDevice | undefined { export function getCameraDevice(devices: CameraDevice[], position: CameraPosition, filter: DeviceFilter = {}): CameraDevice | undefined {
const explicitlyWantsNonWideAngle = filter.physicalDevices != null && !filter.physicalDevices.includes('wide-angle-camera'); const explicitlyWantsNonWideAngle = filter.physicalDevices != null && !filter.physicalDevices.includes('wide-angle-camera')
const filtered = devices.filter((d) => d.position === position); const filtered = devices.filter((d) => d.position === position)
let bestDevice = filtered[0]; let bestDevice = filtered[0]
if (bestDevice == null) return undefined; if (bestDevice == null) return undefined
// Compare each device using a point scoring system // Compare each device using a point scoring system
for (const device of devices) { for (const device of devices) {
let leftPoints = 0; let leftPoints = 0
let rightPoints = 0; let rightPoints = 0
// prefer higher hardware-level // prefer higher hardware-level
if (bestDevice.hardwareLevel === 'full') leftPoints += 4; if (bestDevice.hardwareLevel === 'full') leftPoints += 4
if (device.hardwareLevel === 'full') rightPoints += 4; if (device.hardwareLevel === 'full') rightPoints += 4
if (!explicitlyWantsNonWideAngle) { if (!explicitlyWantsNonWideAngle) {
// prefer wide-angle-camera as a default // prefer wide-angle-camera as a default
if (bestDevice.physicalDevices.includes('wide-angle-camera')) leftPoints += 1; if (bestDevice.physicalDevices.includes('wide-angle-camera')) leftPoints += 1
if (device.physicalDevices.includes('wide-angle-camera')) rightPoints += 1; if (device.physicalDevices.includes('wide-angle-camera')) rightPoints += 1
} }
// compare devices. two possible scenarios: // compare devices. two possible scenarios:
@ -63,17 +63,17 @@ export function getCameraDevice(devices: CameraDevice[], position: CameraPositio
// 2. user wants only one ([wide]) for faster performance. prefer those devices that only have one camera, if they have more, we rank them lower. // 2. user wants only one ([wide]) for faster performance. prefer those devices that only have one camera, if they have more, we rank them lower.
if (filter.physicalDevices != null) { if (filter.physicalDevices != null) {
for (const d of bestDevice.physicalDevices) { for (const d of bestDevice.physicalDevices) {
if (filter.physicalDevices.includes(d)) leftPoints += 1; if (filter.physicalDevices.includes(d)) leftPoints += 1
else leftPoints -= 1; else leftPoints -= 1
} }
for (const d of device.physicalDevices) { for (const d of device.physicalDevices) {
if (filter.physicalDevices.includes(d)) rightPoints += 1; if (filter.physicalDevices.includes(d)) rightPoints += 1
else rightPoints -= 1; else rightPoints -= 1
} }
} }
if (rightPoints > leftPoints) bestDevice = device; if (rightPoints > leftPoints) bestDevice = device
} }
return bestDevice; return bestDevice
} }

View File

@ -1,10 +1,10 @@
import type { CameraDevice, CameraDeviceFormat, VideoStabilizationMode } from '../CameraDevice'; import type { CameraDevice, CameraDeviceFormat, VideoStabilizationMode } from '../CameraDevice'
import { CameraRuntimeError } from '../CameraError'; import { CameraRuntimeError } from '../CameraError'
import { PixelFormat } from '../PixelFormat'; import { PixelFormat } from '../PixelFormat'
interface Size { interface Size {
width: number; width: number
height: number; height: number
} }
export interface FormatFilter { export interface FormatFilter {
@ -12,12 +12,12 @@ export interface FormatFilter {
* The target resolution of the video (and frame processor) output pipeline. * The target resolution of the video (and frame processor) output pipeline.
* If no format supports the given resolution, the format closest to this value will be used. * If no format supports the given resolution, the format closest to this value will be used.
*/ */
videoResolution?: Size | 'max'; videoResolution?: Size | 'max'
/** /**
* The target resolution of the photo output pipeline. * The target resolution of the photo output pipeline.
* If no format supports the given resolution, the format closest to this value will be used. * If no format supports the given resolution, the format closest to this value will be used.
*/ */
photoResolution?: Size | 'max'; photoResolution?: Size | 'max'
/** /**
* The target aspect ratio of the video (and preview) output, expressed as a factor: `width / height`. * The target aspect ratio of the video (and preview) output, expressed as a factor: `width / height`.
* (Note: Cameras are in landscape orientation) * (Note: Cameras are in landscape orientation)
@ -30,7 +30,7 @@ export interface FormatFilter {
* targetVideoAspectRatio: screen.height / screen.width * targetVideoAspectRatio: screen.height / screen.width
* ``` * ```
*/ */
videoAspectRatio?: number; videoAspectRatio?: number
/** /**
* The target aspect ratio of the photo output, expressed as a factor: `width / height`. * The target aspect ratio of the photo output, expressed as a factor: `width / height`.
* (Note: Cameras are in landscape orientation) * (Note: Cameras are in landscape orientation)
@ -44,39 +44,39 @@ export interface FormatFilter {
* targetPhotoAspectRatio: screen.height / screen.width * targetPhotoAspectRatio: screen.height / screen.width
* ``` * ```
*/ */
photoAspectRatio?: number; photoAspectRatio?: number
/** /**
* The target FPS you want to record video at. * The target FPS you want to record video at.
* If the FPS requirements can not be met, the format closest to this value will be used. * If the FPS requirements can not be met, the format closest to this value will be used.
*/ */
fps?: number; fps?: number
/** /**
* The target video stabilization mode you want to use. * The target video stabilization mode you want to use.
* If no format supports the target video stabilization mode, the best other matching format will be used. * If no format supports the target video stabilization mode, the best other matching format will be used.
*/ */
videoStabilizationMode?: VideoStabilizationMode; videoStabilizationMode?: VideoStabilizationMode
/** /**
* The target pixel format you want to use. * The target pixel format you want to use.
* If no format supports the target pixel format, the best other matching format will be used. * If no format supports the target pixel format, the best other matching format will be used.
*/ */
pixelFormat?: PixelFormat; pixelFormat?: PixelFormat
/** /**
* Whether you want to find a format that supports Photo HDR. * Whether you want to find a format that supports Photo HDR.
*/ */
photoHDR?: boolean; photoHDR?: boolean
/** /**
* Whether you want to find a format that supports Photo HDR. * Whether you want to find a format that supports Photo HDR.
*/ */
videoHDR?: boolean; videoHDR?: boolean
} }
type FilterWithPriority<T> = { type FilterWithPriority<T> = {
target: Exclude<T, null | undefined>; target: Exclude<T, null | undefined>
priority: number; priority: number
}; }
type FilterMap = { type FilterMap = {
[K in keyof FormatFilter]: FilterWithPriority<FormatFilter[K]>; [K in keyof FormatFilter]: FilterWithPriority<FormatFilter[K]>
}; }
function filtersToFilterMap(filters: FormatFilter[]): FilterMap { function filtersToFilterMap(filters: FormatFilter[]): FilterMap {
return filters.reduce<FilterMap>((map, curr, index) => { return filters.reduce<FilterMap>((map, curr, index) => {
for (const key in curr) { for (const key in curr) {
@ -86,10 +86,10 @@ function filtersToFilterMap(filters: FormatFilter[]): FilterMap {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
target: curr[key], target: curr[key],
priority: filters.length - index, priority: filters.length - index,
}; }
} }
return map; return map
}, {}); }, {})
} }
/** /**
@ -112,103 +112,103 @@ function filtersToFilterMap(filters: FormatFilter[]): FilterMap {
*/ */
export function getCameraFormat(device: CameraDevice, filters: FormatFilter[]): CameraDeviceFormat { export function getCameraFormat(device: CameraDevice, filters: FormatFilter[]): CameraDeviceFormat {
// Combine filters into a single filter map for constant-time lookup // Combine filters into a single filter map for constant-time lookup
const filter = filtersToFilterMap(filters); const filter = filtersToFilterMap(filters)
let bestFormat = device.formats[0]; let bestFormat = device.formats[0]
if (bestFormat == null) if (bestFormat == null)
throw new CameraRuntimeError('device/invalid-device', `The given Camera Device (${device.id}) does not have any formats!`); throw new CameraRuntimeError('device/invalid-device', `The given Camera Device (${device.id}) does not have any formats!`)
// Compare each format using a point scoring system // Compare each format using a point scoring system
for (const format of device.formats) { for (const format of device.formats) {
let leftPoints = 0; let leftPoints = 0
let rightPoints = 0; let rightPoints = 0
const leftVideoResolution = bestFormat.videoWidth * bestFormat.videoHeight; const leftVideoResolution = bestFormat.videoWidth * bestFormat.videoHeight
const rightVideoResolution = format.videoWidth * format.videoHeight; const rightVideoResolution = format.videoWidth * format.videoHeight
if (filter.videoResolution != null) { if (filter.videoResolution != null) {
if (filter.videoResolution.target === 'max') { if (filter.videoResolution.target === 'max') {
// We just want the maximum resolution // We just want the maximum resolution
if (leftVideoResolution > rightVideoResolution) leftPoints += filter.videoResolution.priority; if (leftVideoResolution > rightVideoResolution) leftPoints += filter.videoResolution.priority
if (rightVideoResolution > leftVideoResolution) rightPoints += filter.videoResolution.priority; if (rightVideoResolution > leftVideoResolution) rightPoints += filter.videoResolution.priority
} else { } else {
// Find video resolution closest to the filter (ignoring orientation) // Find video resolution closest to the filter (ignoring orientation)
const targetResolution = filter.videoResolution.target.width * filter.videoResolution.target.height; const targetResolution = filter.videoResolution.target.width * filter.videoResolution.target.height
const leftDiff = Math.abs(leftVideoResolution - targetResolution); const leftDiff = Math.abs(leftVideoResolution - targetResolution)
const rightDiff = Math.abs(rightVideoResolution - targetResolution); const rightDiff = Math.abs(rightVideoResolution - targetResolution)
if (leftDiff < rightDiff) leftPoints += filter.videoResolution.priority; if (leftDiff < rightDiff) leftPoints += filter.videoResolution.priority
if (rightDiff < leftDiff) rightPoints += filter.videoResolution.priority; if (rightDiff < leftDiff) rightPoints += filter.videoResolution.priority
} }
} }
const leftPhotoResolution = bestFormat.photoWidth * bestFormat.photoHeight; const leftPhotoResolution = bestFormat.photoWidth * bestFormat.photoHeight
const rightPhotoResolution = format.photoWidth * format.photoHeight; const rightPhotoResolution = format.photoWidth * format.photoHeight
if (filter.photoResolution != null) { if (filter.photoResolution != null) {
if (filter.photoResolution.target === 'max') { if (filter.photoResolution.target === 'max') {
// We just want the maximum resolution // We just want the maximum resolution
if (leftPhotoResolution > rightPhotoResolution) leftPoints += filter.photoResolution.priority; if (leftPhotoResolution > rightPhotoResolution) leftPoints += filter.photoResolution.priority
if (rightPhotoResolution > leftPhotoResolution) rightPoints += filter.photoResolution.priority; if (rightPhotoResolution > leftPhotoResolution) rightPoints += filter.photoResolution.priority
} else { } else {
// Find closest photo resolution to the filter (ignoring orientation) // Find closest photo resolution to the filter (ignoring orientation)
const targetResolution = filter.photoResolution.target.width * filter.photoResolution.target.height; const targetResolution = filter.photoResolution.target.width * filter.photoResolution.target.height
const leftDiff = Math.abs(leftPhotoResolution - targetResolution); const leftDiff = Math.abs(leftPhotoResolution - targetResolution)
const rightDiff = Math.abs(rightPhotoResolution - targetResolution); const rightDiff = Math.abs(rightPhotoResolution - targetResolution)
if (leftDiff < rightDiff) leftPoints += filter.photoResolution.priority; if (leftDiff < rightDiff) leftPoints += filter.photoResolution.priority
if (rightDiff < leftDiff) rightPoints += filter.photoResolution.priority; if (rightDiff < leftDiff) rightPoints += filter.photoResolution.priority
} }
} }
// Find closest aspect ratio (video) // Find closest aspect ratio (video)
if (filter.videoAspectRatio != null) { if (filter.videoAspectRatio != null) {
const leftAspect = bestFormat.videoWidth / bestFormat.videoHeight; const leftAspect = bestFormat.videoWidth / bestFormat.videoHeight
const rightAspect = format.videoWidth / format.videoHeight; const rightAspect = format.videoWidth / format.videoHeight
const leftDiff = Math.abs(leftAspect - filter.videoAspectRatio.target); const leftDiff = Math.abs(leftAspect - filter.videoAspectRatio.target)
const rightDiff = Math.abs(rightAspect - filter.videoAspectRatio.target); const rightDiff = Math.abs(rightAspect - filter.videoAspectRatio.target)
if (leftDiff < rightDiff) leftPoints += filter.videoAspectRatio.priority; if (leftDiff < rightDiff) leftPoints += filter.videoAspectRatio.priority
if (rightDiff < leftDiff) rightPoints += filter.videoAspectRatio.priority; if (rightDiff < leftDiff) rightPoints += filter.videoAspectRatio.priority
} }
// Find closest aspect ratio (photo) // Find closest aspect ratio (photo)
if (filter.photoAspectRatio != null) { if (filter.photoAspectRatio != null) {
const leftAspect = bestFormat.photoWidth / bestFormat.photoHeight; const leftAspect = bestFormat.photoWidth / bestFormat.photoHeight
const rightAspect = format.photoWidth / format.photoHeight; const rightAspect = format.photoWidth / format.photoHeight
const leftDiff = Math.abs(leftAspect - filter.photoAspectRatio.target); const leftDiff = Math.abs(leftAspect - filter.photoAspectRatio.target)
const rightDiff = Math.abs(rightAspect - filter.photoAspectRatio.target); const rightDiff = Math.abs(rightAspect - filter.photoAspectRatio.target)
if (leftDiff < rightDiff) leftPoints += filter.photoAspectRatio.priority; if (leftDiff < rightDiff) leftPoints += filter.photoAspectRatio.priority
if (rightDiff < leftDiff) rightPoints += filter.photoAspectRatio.priority; if (rightDiff < leftDiff) rightPoints += filter.photoAspectRatio.priority
} }
// Find closest max FPS // Find closest max FPS
if (filter.fps != null) { if (filter.fps != null) {
if (bestFormat.maxFps >= filter.fps.target) leftPoints += filter.fps.priority; if (bestFormat.maxFps >= filter.fps.target) leftPoints += filter.fps.priority
if (format.maxFps >= filter.fps.target) rightPoints += filter.fps.priority; if (format.maxFps >= filter.fps.target) rightPoints += filter.fps.priority
} }
// Find video stabilization mode // Find video stabilization mode
if (filter.videoStabilizationMode != null) { if (filter.videoStabilizationMode != null) {
if (bestFormat.videoStabilizationModes.includes(filter.videoStabilizationMode.target)) leftPoints++; if (bestFormat.videoStabilizationModes.includes(filter.videoStabilizationMode.target)) leftPoints++
if (format.videoStabilizationModes.includes(filter.videoStabilizationMode.target)) rightPoints++; if (format.videoStabilizationModes.includes(filter.videoStabilizationMode.target)) rightPoints++
} }
// Find pixel format // Find pixel format
if (filter.pixelFormat != null) { if (filter.pixelFormat != null) {
if (bestFormat.pixelFormats.includes(filter.pixelFormat.target)) leftPoints++; if (bestFormat.pixelFormats.includes(filter.pixelFormat.target)) leftPoints++
if (format.pixelFormats.includes(filter.pixelFormat.target)) rightPoints++; if (format.pixelFormats.includes(filter.pixelFormat.target)) rightPoints++
} }
// Find Photo HDR formats // Find Photo HDR formats
if (filter.photoHDR != null) { if (filter.photoHDR != null) {
if (bestFormat.supportsPhotoHDR === filter.photoHDR.target) leftPoints++; if (bestFormat.supportsPhotoHDR === filter.photoHDR.target) leftPoints++
if (format.supportsPhotoHDR === filter.photoHDR.target) rightPoints++; if (format.supportsPhotoHDR === filter.photoHDR.target) rightPoints++
} }
// Find Video HDR formats // Find Video HDR formats
if (filter.videoHDR != null) { if (filter.videoHDR != null) {
if (bestFormat.supportsVideoHDR === filter.videoHDR.target) leftPoints++; if (bestFormat.supportsVideoHDR === filter.videoHDR.target) leftPoints++
if (format.supportsVideoHDR === filter.videoHDR.target) rightPoints++; if (format.supportsVideoHDR === filter.videoHDR.target) rightPoints++
} }
if (rightPoints > leftPoints) bestFormat = format; if (rightPoints > leftPoints) bestFormat = format
} }
return bestFormat; return bestFormat
} }

View File

@ -1,23 +1,23 @@
import { ConfigPlugin, withGradleProperties } from '@expo/config-plugins'; import { ConfigPlugin, withGradleProperties } from '@expo/config-plugins'
/** /**
* Set the `VisionCamera_disableFrameProcessors` value in the static `gradle.properties` file. * Set the `VisionCamera_disableFrameProcessors` value in the static `gradle.properties` file.
* This is used to disable frame processors if you don't need it for android. * This is used to disable frame processors if you don't need it for android.
*/ */
export const withDisableFrameProcessorsAndroid: ConfigPlugin = (c) => { export const withDisableFrameProcessorsAndroid: ConfigPlugin = (c) => {
const disableFrameProcessorsKey = 'VisionCamera_disableFrameProcessors'; const disableFrameProcessorsKey = 'VisionCamera_disableFrameProcessors'
return withGradleProperties(c, (config) => { return withGradleProperties(c, (config) => {
config.modResults = config.modResults.filter((item) => { config.modResults = config.modResults.filter((item) => {
if (item.type === 'property' && item.key === disableFrameProcessorsKey) return false; if (item.type === 'property' && item.key === disableFrameProcessorsKey) return false
return true; return true
}); })
config.modResults.push({ config.modResults.push({
type: 'property', type: 'property',
key: disableFrameProcessorsKey, key: disableFrameProcessorsKey,
value: 'true', value: 'true',
}); })
return config; return config
}); })
}; }

View File

@ -1,4 +1,4 @@
import { ConfigPlugin, withPodfileProperties } from '@expo/config-plugins'; import { ConfigPlugin, withPodfileProperties } from '@expo/config-plugins'
/** /**
* Set the `disableFrameProcessors` inside of the XcodeProject. * Set the `disableFrameProcessors` inside of the XcodeProject.
@ -7,7 +7,7 @@ import { ConfigPlugin, withPodfileProperties } from '@expo/config-plugins';
export const withDisableFrameProcessorsIOS: ConfigPlugin = (c) => { export const withDisableFrameProcessorsIOS: ConfigPlugin = (c) => {
return withPodfileProperties(c, (config) => { return withPodfileProperties(c, (config) => {
// TODO: Implement Podfile writing // TODO: Implement Podfile writing
config.ios = config.ios; config.ios = config.ios
return config; return config
}); })
}; }

View File

@ -1,37 +1,37 @@
import { withPlugins, AndroidConfig, ConfigPlugin, createRunOncePlugin } from '@expo/config-plugins'; import { withPlugins, AndroidConfig, ConfigPlugin, createRunOncePlugin } from '@expo/config-plugins'
import { withDisableFrameProcessorsAndroid } from './withDisableFrameProcessorsAndroid'; import { withDisableFrameProcessorsAndroid } from './withDisableFrameProcessorsAndroid'
import { withDisableFrameProcessorsIOS } from './withDisableFrameProcessorsIOS'; import { withDisableFrameProcessorsIOS } from './withDisableFrameProcessorsIOS'
// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-unsafe-assignment // eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-unsafe-assignment
const pkg = require('../../../package.json'); const pkg = require('../../../package.json')
const CAMERA_USAGE = 'Allow $(PRODUCT_NAME) to access your camera'; const CAMERA_USAGE = 'Allow $(PRODUCT_NAME) to access your camera'
const MICROPHONE_USAGE = 'Allow $(PRODUCT_NAME) to access your microphone'; const MICROPHONE_USAGE = 'Allow $(PRODUCT_NAME) to access your microphone'
type Props = { type Props = {
cameraPermissionText?: string; cameraPermissionText?: string
enableMicrophonePermission?: boolean; enableMicrophonePermission?: boolean
microphonePermissionText?: string; microphonePermissionText?: string
disableFrameProcessors?: boolean; disableFrameProcessors?: boolean
}; }
const withCamera: ConfigPlugin<Props> = (config, props = {}) => { const withCamera: ConfigPlugin<Props> = (config, props = {}) => {
if (config.ios == null) config.ios = {}; if (config.ios == null) config.ios = {}
if (config.ios.infoPlist == null) config.ios.infoPlist = {}; if (config.ios.infoPlist == null) config.ios.infoPlist = {}
config.ios.infoPlist.NSCameraUsageDescription = config.ios.infoPlist.NSCameraUsageDescription =
props.cameraPermissionText ?? (config.ios.infoPlist.NSCameraUsageDescription as string | undefined) ?? CAMERA_USAGE; props.cameraPermissionText ?? (config.ios.infoPlist.NSCameraUsageDescription as string | undefined) ?? CAMERA_USAGE
if (props.enableMicrophonePermission) { if (props.enableMicrophonePermission) {
config.ios.infoPlist.NSMicrophoneUsageDescription = config.ios.infoPlist.NSMicrophoneUsageDescription =
props.microphonePermissionText ?? (config.ios.infoPlist.NSMicrophoneUsageDescription as string | undefined) ?? MICROPHONE_USAGE; props.microphonePermissionText ?? (config.ios.infoPlist.NSMicrophoneUsageDescription as string | undefined) ?? MICROPHONE_USAGE
} }
const androidPermissions = ['android.permission.CAMERA']; const androidPermissions = ['android.permission.CAMERA']
if (props.enableMicrophonePermission) androidPermissions.push('android.permission.RECORD_AUDIO'); if (props.enableMicrophonePermission) androidPermissions.push('android.permission.RECORD_AUDIO')
if (props.disableFrameProcessors) { if (props.disableFrameProcessors) {
config = withDisableFrameProcessorsAndroid(config); config = withDisableFrameProcessorsAndroid(config)
config = withDisableFrameProcessorsIOS(config); config = withDisableFrameProcessorsIOS(config)
} }
return withPlugins(config, [[AndroidConfig.Permissions.withPermissions, androidPermissions]]); return withPlugins(config, [[AndroidConfig.Permissions.withPermissions, androidPermissions]])
}; }
export default createRunOncePlugin(withCamera, pkg.name, pkg.version); export default createRunOncePlugin(withCamera, pkg.name, pkg.version)

View File

@ -1,7 +1,7 @@
import { useMemo } from 'react'; import { useMemo } from 'react'
import { CameraDevice, CameraPosition } from '../CameraDevice'; import { CameraDevice, CameraPosition } from '../CameraDevice'
import { getCameraDevice, DeviceFilter } from '../devices/getCameraDevice'; import { getCameraDevice, DeviceFilter } from '../devices/getCameraDevice'
import { useCameraDevices } from './useCameraDevices'; import { useCameraDevices } from './useCameraDevices'
/** /**
* Get the best matching Camera device that best satisfies your requirements using a sorting filter. * Get the best matching Camera device that best satisfies your requirements using a sorting filter.
@ -16,13 +16,13 @@ import { useCameraDevices } from './useCameraDevices';
* ``` * ```
*/ */
export function useCameraDevice(position: CameraPosition, filter?: DeviceFilter): CameraDevice | undefined { export function useCameraDevice(position: CameraPosition, filter?: DeviceFilter): CameraDevice | undefined {
const devices = useCameraDevices(); const devices = useCameraDevices()
const device = useMemo( const device = useMemo(
() => getCameraDevice(devices, position, filter), () => getCameraDevice(devices, position, filter),
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
[devices, position, JSON.stringify(filter)], [devices, position, JSON.stringify(filter)],
); )
return device; return device
} }

View File

@ -1,6 +1,6 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react'
import type { CameraDevice } from '../CameraDevice'; import type { CameraDevice } from '../CameraDevice'
import { CameraDevices } from '../CameraDevices'; import { CameraDevices } from '../CameraDevices'
/** /**
* Get all available Camera Devices this phone has. * Get all available Camera Devices this phone has.
@ -10,14 +10,14 @@ import { CameraDevices } from '../CameraDevices';
* so the result of this function might update over time. * so the result of this function might update over time.
*/ */
export function useCameraDevices(): CameraDevice[] { export function useCameraDevices(): CameraDevice[] {
const [devices, setDevices] = useState(() => CameraDevices.getAvailableCameraDevices()); const [devices, setDevices] = useState(() => CameraDevices.getAvailableCameraDevices())
useEffect(() => { useEffect(() => {
const listener = CameraDevices.addCameraDevicesChangedListener((newDevices) => { const listener = CameraDevices.addCameraDevicesChangedListener((newDevices) => {
setDevices(newDevices); setDevices(newDevices)
}); })
return () => listener.remove(); return () => listener.remove()
}, []); }, [])
return devices; return devices
} }

View File

@ -1,6 +1,6 @@
import { useMemo } from 'react'; import { useMemo } from 'react'
import { CameraDevice, CameraDeviceFormat } from '../CameraDevice'; import { CameraDevice, CameraDeviceFormat } from '../CameraDevice'
import { FormatFilter, getCameraFormat } from '../devices/getCameraFormat'; import { FormatFilter, getCameraFormat } from '../devices/getCameraFormat'
/** /**
* Get the best matching Camera format for the given device that satisfies your requirements using a sorting filter. By default, formats are sorted by highest to lowest resolution. * Get the best matching Camera format for the given device that satisfies your requirements using a sorting filter. By default, formats are sorted by highest to lowest resolution.
@ -22,10 +22,10 @@ import { FormatFilter, getCameraFormat } from '../devices/getCameraFormat';
*/ */
export function useCameraFormat(device: CameraDevice | undefined, filters: FormatFilter[]): CameraDeviceFormat | undefined { export function useCameraFormat(device: CameraDevice | undefined, filters: FormatFilter[]): CameraDeviceFormat | undefined {
const format = useMemo(() => { const format = useMemo(() => {
if (device == null) return undefined; if (device == null) return undefined
return getCameraFormat(device, filters); return getCameraFormat(device, filters)
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [device, JSON.stringify(filters)]); }, [device, JSON.stringify(filters)])
return format; return format
} }

View File

@ -1,17 +1,17 @@
import { useCallback, useEffect, useState } from 'react'; import { useCallback, useEffect, useState } from 'react'
import { Camera } from '../Camera'; import { Camera } from '../Camera'
interface PermissionState { interface PermissionState {
/** /**
* Whether the specified permission has explicitly been granted. * Whether the specified permission has explicitly been granted.
* By default, this will be `false`. To request permission, call `requestPermission()`. * By default, this will be `false`. To request permission, call `requestPermission()`.
*/ */
hasPermission: boolean; hasPermission: boolean
/** /**
* Requests the specified permission from the user. * Requests the specified permission from the user.
* @returns Whether the specified permission has now been granted, or not. * @returns Whether the specified permission has now been granted, or not.
*/ */
requestPermission: () => Promise<boolean>; requestPermission: () => Promise<boolean>
} }
/** /**
@ -31,23 +31,23 @@ interface PermissionState {
* ``` * ```
*/ */
export function useCameraPermission(): PermissionState { export function useCameraPermission(): PermissionState {
const [hasPermission, setHasPermission] = useState(false); const [hasPermission, setHasPermission] = useState(false)
const requestPermission = useCallback(async () => { const requestPermission = useCallback(async () => {
const result = await Camera.requestCameraPermission(); const result = await Camera.requestCameraPermission()
const hasPermissionNow = result === 'granted'; const hasPermissionNow = result === 'granted'
setHasPermission(hasPermissionNow); setHasPermission(hasPermissionNow)
return hasPermissionNow; return hasPermissionNow
}, []); }, [])
useEffect(() => { useEffect(() => {
Camera.getCameraPermissionStatus().then((s) => setHasPermission(s === 'granted')); Camera.getCameraPermissionStatus().then((s) => setHasPermission(s === 'granted'))
}, []); }, [])
return { return {
hasPermission, hasPermission,
requestPermission, requestPermission,
}; }
} }
/** /**
@ -65,21 +65,21 @@ export function useCameraPermission(): PermissionState {
* ``` * ```
*/ */
export function useMicrophonePermission(): PermissionState { export function useMicrophonePermission(): PermissionState {
const [hasPermission, setHasPermission] = useState(false); const [hasPermission, setHasPermission] = useState(false)
const requestPermission = useCallback(async () => { const requestPermission = useCallback(async () => {
const result = await Camera.requestMicrophonePermission(); const result = await Camera.requestMicrophonePermission()
const hasPermissionNow = result === 'granted'; const hasPermissionNow = result === 'granted'
setHasPermission(hasPermissionNow); setHasPermission(hasPermissionNow)
return hasPermissionNow; return hasPermissionNow
}, []); }, [])
useEffect(() => { useEffect(() => {
Camera.getMicrophonePermissionStatus().then((s) => setHasPermission(s === 'granted')); Camera.getMicrophonePermissionStatus().then((s) => setHasPermission(s === 'granted'))
}, []); }, [])
return { return {
hasPermission, hasPermission,
requestPermission, requestPermission,
}; }
} }

View File

@ -1,6 +1,6 @@
import { DependencyList, useMemo } from 'react'; import { DependencyList, useMemo } from 'react'
import type { Frame, FrameInternal } from '../Frame'; import type { Frame, FrameInternal } from '../Frame'
import { FrameProcessor } from '../CameraProps'; import { FrameProcessor } from '../CameraProps'
/** /**
* Create a new Frame Processor function which you can pass to the `<Camera>`. * Create a new Frame Processor function which you can pass to the `<Camera>`.
@ -13,19 +13,20 @@ import { FrameProcessor } from '../CameraProps';
export function createFrameProcessor(frameProcessor: FrameProcessor['frameProcessor'], type: FrameProcessor['type']): FrameProcessor { export function createFrameProcessor(frameProcessor: FrameProcessor['frameProcessor'], type: FrameProcessor['type']): FrameProcessor {
return { return {
frameProcessor: (frame: Frame) => { frameProcessor: (frame: Frame) => {
'worklet'; 'worklet'
// Increment ref-count by one // Increment ref-count by one
(frame as FrameInternal).incrementRefCount(); const internal = frame as FrameInternal
internal.incrementRefCount()
try { try {
// Call sync frame processor // Call sync frame processor
frameProcessor(frame); frameProcessor(frame)
} finally { } finally {
// Potentially delete Frame if we were the last ref (no runAsync) // Potentially delete Frame if we were the last ref (no runAsync)
(frame as FrameInternal).decrementRefCount(); internal.decrementRefCount()
} }
}, },
type: type, type: type,
}; }
} }
/** /**
@ -48,5 +49,5 @@ export function createFrameProcessor(frameProcessor: FrameProcessor['frameProces
*/ */
export function useFrameProcessor(frameProcessor: (frame: Frame) => void, dependencies: DependencyList): FrameProcessor { export function useFrameProcessor(frameProcessor: (frame: Frame) => void, dependencies: DependencyList): FrameProcessor {
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
return useMemo(() => createFrameProcessor(frameProcessor, 'frame-processor'), dependencies); return useMemo(() => createFrameProcessor(frameProcessor, 'frame-processor'), dependencies)
} }

View File

@ -1,21 +1,21 @@
export * from './Camera'; export * from './Camera'
export * from './CameraDevice'; export * from './CameraDevice'
export * from './CameraError'; export * from './CameraError'
export * from './CameraProps'; export * from './CameraProps'
export * from './Frame'; export * from './Frame'
export * from './FrameProcessorPlugins'; export * from './FrameProcessorPlugins'
export * from './Orientation'; export * from './Orientation'
export * from './PhotoFile'; export * from './PhotoFile'
export * from './PixelFormat'; export * from './PixelFormat'
export * from './Point'; export * from './Point'
export * from './VideoFile'; export * from './VideoFile'
export * from './devices/getCameraFormat'; export * from './devices/getCameraFormat'
export * from './devices/getCameraDevice'; export * from './devices/getCameraDevice'
export * from './devices/Templates'; export * from './devices/Templates'
export * from './hooks/useCameraDevice'; export * from './hooks/useCameraDevice'
export * from './hooks/useCameraDevices'; export * from './hooks/useCameraDevices'
export * from './hooks/useCameraFormat'; export * from './hooks/useCameraFormat'
export * from './hooks/useCameraPermission'; export * from './hooks/useCameraPermission'
export * from './hooks/useFrameProcessor'; export * from './hooks/useFrameProcessor'