2023-07-20 15:30:04 +02:00
|
|
|
import { DependencyList, useMemo } from 'react';
|
2023-09-01 12:20:17 +02:00
|
|
|
import type { Frame, FrameInternal } from '../Frame';
|
2023-07-20 15:30:04 +02:00
|
|
|
import { FrameProcessor } from '../CameraProps';
|
2021-05-06 14:11:55 +02:00
|
|
|
|
2023-09-01 12:20:17 +02:00
|
|
|
/**
|
|
|
|
* Create a new Frame Processor function which you can pass to the `<Camera>`.
|
|
|
|
* (See ["Frame Processors"](https://mrousavy.github.io/react-native-vision-camera/docs/guides/frame-processors))
|
|
|
|
*
|
|
|
|
* Make sure to add the `'worklet'` directive to the top of the Frame Processor function, otherwise it will not get compiled into a worklet.
|
|
|
|
*
|
|
|
|
* Also make sure to memoize the returned object, so that the Camera doesn't reset the Frame Processor Context each time.
|
|
|
|
*/
|
2023-07-21 17:52:30 +02:00
|
|
|
export function createFrameProcessor(frameProcessor: FrameProcessor['frameProcessor'], type: FrameProcessor['type']): FrameProcessor {
|
|
|
|
return {
|
2023-09-01 12:20:17 +02:00
|
|
|
frameProcessor: (frame: Frame) => {
|
2023-07-21 17:52:30 +02:00
|
|
|
'worklet';
|
|
|
|
// Increment ref-count by one
|
|
|
|
(frame as FrameInternal).incrementRefCount();
|
|
|
|
try {
|
|
|
|
// Call sync frame processor
|
|
|
|
frameProcessor(frame);
|
|
|
|
} finally {
|
|
|
|
// Potentially delete Frame if we were the last ref (no runAsync)
|
|
|
|
(frame as FrameInternal).decrementRefCount();
|
|
|
|
}
|
|
|
|
},
|
|
|
|
type: type,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2021-05-06 14:11:55 +02:00
|
|
|
/**
|
2023-07-20 15:30:04 +02:00
|
|
|
* Returns a memoized Frame Processor function wich you can pass to the `<Camera>`.
|
|
|
|
* (See ["Frame Processors"](https://mrousavy.github.io/react-native-vision-camera/docs/guides/frame-processors))
|
2021-05-06 14:11:55 +02:00
|
|
|
*
|
2021-05-27 11:08:57 +02:00
|
|
|
* Make sure to add the `'worklet'` directive to the top of the Frame Processor function, otherwise it will not get compiled into a worklet.
|
2021-05-06 14:11:55 +02:00
|
|
|
*
|
|
|
|
* @param frameProcessor The Frame Processor
|
|
|
|
* @param dependencies The React dependencies which will be copied into the VisionCamera JS-Runtime.
|
|
|
|
* @returns The memoized Frame Processor.
|
|
|
|
* @example
|
|
|
|
* ```ts
|
|
|
|
* const frameProcessor = useFrameProcessor((frame) => {
|
|
|
|
* 'worklet'
|
|
|
|
* const qrCodes = scanQRCodes(frame)
|
2021-07-30 10:27:45 +02:00
|
|
|
* console.log(`QR Codes: ${qrCodes}`)
|
2021-05-06 14:11:55 +02:00
|
|
|
* }, [])
|
|
|
|
* ```
|
|
|
|
*/
|
2023-07-20 15:30:04 +02:00
|
|
|
export function useFrameProcessor(frameProcessor: (frame: Frame) => void, dependencies: DependencyList): FrameProcessor {
|
2023-07-21 17:52:30 +02:00
|
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
|
|
return useMemo(() => createFrameProcessor(frameProcessor, 'frame-processor'), dependencies);
|
2023-07-20 15:30:04 +02:00
|
|
|
}
|