react-native-vision-camera icon indicating copy to clipboard operation
react-native-vision-camera copied to clipboard

🐛 Memory Leak in `useSkiaFrameProcessor` with `react-native-vision-camera` leading to app crash

Open rafaelrcamargo opened this issue 1 year ago • 30 comments

What's happening?

There appears to be a memory leak when using useSkiaFrameProcessor from react-native-skia in conjunction with react-native-vision-camera. A simple Skia image shader running within the frame processor causes the app's memory usage to continuously increase until the app eventually crashes.

I have recorded a timelapse video using Xcode's memory profiler demonstrating the memory increasing consistently until the app crashes.

Image

https://github.com/user-attachments/assets/a604df0d-003f-4de2-bfa6-db08988ff6a2

The Skia shader used is a very simple imageFilter example from the docs, suggesting the leak might be in the bridge or a core interaction between the libraries rather than the shader logic itself.

Reproduceable Code

const device = useCameraDevice("back");
  const format = useCameraFormat(device, [{ photoResolution: "max" }]);

  // ...

  const invertColorsFilter = Skia.RuntimeEffect.Make(`
    uniform shader image;
    half4 main(vec2 pos) {
      vec4 color = image.eval(pos);
      return vec4((1.0 - color).rgb, 1.0);
    }
  `)!
  const shaderBuilder = Skia.RuntimeShaderBuilder(invertColorsFilter)
  const imageFilter = Skia.ImageFilter.MakeRuntimeShader(shaderBuilder, null, null)
  const paint = Skia.Paint()
  paint.setImageFilter(imageFilter)
  const frameProcessor = useSkiaFrameProcessor((frame) => {
    "worklet";
    frame.render(paint)
  }, [paint]);



<Camera
  audio={false}
  device={device}
  enableFpsGraph
  format={format}
  fps={format?.maxFps ?? 30}
  frameProcessor={frameProcessor}
  outputOrientation="preview"
  photo
  pixelFormat="rgb"
  video={false}
/>

Relevant log output

// This, looping forever 👇
00:05:13.449: [info] 📸 VisionCamera.didSetProps(_:): Updating 0 props: []
00:05:13.449: [info] 📸 VisionCamera.configure(_:): configure { ... }: Waiting for lock...
00:05:13.449: [info] 📸 VisionCamera.configure(_:): configure { ... }: Updating CameraSession Configuration... Difference(inputChanged: false, outputsChanged: false, videoStabilizationChanged: false, orientationChanged: false, formatChanged: false, sidePropsChanged: false, torchChanged: false, zoomChanged: false, exposureChanged: false, audioSessionChanged: false, locationChanged: false)

Camera Device

{
  "minFocusDistance": 15,
  "minZoom": 1,
  "supportsLowLightBoost": false,
  "formats": [],
  "position": "back",
  "maxZoom": 123.75,
  "maxExposure": 8,
  "sensorOrientation": "portrait",
  "supportsRawCapture": false,
  "name": "Back Camera",
  "hasFlash": true,
  "neutralZoom": 1,
  "minExposure": -8,
  "supportsFocus": true,
  "hasTorch": true,
  "isMultiCam": false,
  "hardwareLevel": "full",
  "physicalDevices": [
    "wide-angle-camera"
  ],
  "id": "com.apple.avfoundation.avcapturedevice.built-in_video:0"
}

Device

iPhone 15 (iOS 18.5)

VisionCamera Version

4.6.4

Can you reproduce this issue in the VisionCamera Example app?

Yes, I can reproduce the same issue in the Example app here

Additional information

rafaelrcamargo avatar May 08 '25 03:05 rafaelrcamargo

Guten Tag, Hans here! 🍻

Thanks for providing a detailed report. It looks like you've done a good job of explaining ze issue, and you've included relevant logs and reproduction steps. However, to better assist mrousavy in addressing this potential memory leak, could you please provide more specific logs related to the app crash, particularly from Xcode's console? This will help us pinpoint the exact problem.

Also, if you're enjoying ze benefits of this project, consider sponsoring to help keep it maintained and receive more direct support.

Looking forward to your response!

Note: If you think I made a mistake, please ping @mrousavy to take a look.

maintenance-hans avatar May 08 '25 03:05 maintenance-hans

Related issue on https://github.com/Shopify/react-native-skia/issues/2964

rafaelrcamargo avatar May 08 '25 03:05 rafaelrcamargo

+1 useSkiaFrameProcessor seems unusable at the moment

Admiral-Enigma avatar May 15 '25 22:05 Admiral-Enigma

+1, following

adriaanslechten avatar May 18 '25 20:05 adriaanslechten

Is there a workaround we could use in the meantime?

edesaras avatar May 19 '25 12:05 edesaras

facing the similar issue in ios, but i am able to process the frames using skia in android, Also getting a black screen in the front camera for both android and ios..

rash-27 avatar May 21 '25 07:05 rash-27

I've found a workaround that might be helpful in the meantime. Instead of using skiaframeprocessor i use regular frameprocessor set the react state and draw on Canvas from skia:

import { useFrameProcessor } from 'react-native-vision-camera';
import { inferenceLogic} from './inferenceLogic'; // your TFLite inference logic
import { Worklets } from 'react-native-worklets-core';

export const useInferenceLogic = (onInference: (detections: any[]) => void) => {
  const onInferenceJS= Worklets.createRunOnJS(onInference)
  const frameProcessor = useFrameProcessor((frame) => {
    'worklet';
    const results = inferenceLogic(frame); // e.g., runs TFLite
    onInferenceJS(results);   // pass to JS side
  }, []);

  return { frameProcessor };
};
import { Canvas } from '@shopify/react-native-skia';
import { Camera, useCameraDevice } from 'react-native-vision-camera';
import { useInferenceLogic  } from './useInferenceLogic ';
import React, { useState } from 'react';

export default function App() {
  const device = useCameraDevice('back');
  const [results, setResults] = useState<any[]>([]);
  const { frameProcessor } = useInferenceLogic (setResults);

  return (
    <View style={{ flex: 1 }}>
      {device && (
        <>
          <Camera
            style={{ flex: 1 }}
            device={device}
            isActive={true}
            frameProcessor={frameProcessor}
            pixelFormat="rgb"
          />
          <Canvas style={{ position: 'absolute', width, height }}>
            // ... your skia logic
          </Canvas>
        </>
      )}
    </View>
  );
}

edesaras avatar May 21 '25 10:05 edesaras

@edesaras nice, Can you give some detailed code, it's been bugging me for a long time now. thanks!

songxiaoliang avatar May 22 '25 02:05 songxiaoliang

@rafaelrcamargo do you fix it ?

songxiaoliang avatar May 26 '25 01:05 songxiaoliang

So, I haven't had much time to look at that code after this report, but downgrading the versions of the packages I was using seems to solve it for now:

    "@shopify/react-native-skia": "1.4.2",
    "react-native-vision-camera": "4.5.3",
    "react-native-worklets-core": "1.5.0"

rafaelrcamargo avatar Jun 02 '25 09:06 rafaelrcamargo

So, I haven't had much time to look at that code after this report, but downgrading the versions of the packages I was using seems to solve it for now:

"@shopify/react-native-skia": "1.4.2",
"react-native-vision-camera": "4.5.3",
"react-native-worklets-core": "1.5.0"

I've had luck downgrading as well.

Unfortunately, these older versions of @shopify/react-native-skia need to be monkeypatched in order to work correctly with newer versions of React Native. I've yet to get react-native 0.79.x working under these conditions.

seanpcoyle avatar Jun 05 '25 16:06 seanpcoyle

@seanpcoyle same problem, how fix it? thanks

songxiaoliang avatar Jun 06 '25 02:06 songxiaoliang

+1

caothuyen avatar Jun 09 '25 01:06 caothuyen

+1

3azam0 avatar Jun 11 '25 10:06 3azam0

+1

nickvgn avatar Jun 15 '25 09:06 nickvgn

So, I haven't had much time to look at that code after this report, but downgrading the versions of the packages I was using seems to solve it for now:

"@shopify/react-native-skia": "1.4.2",
"react-native-vision-camera": "4.5.3",
"react-native-worklets-core": "1.5.0"

Thanks, it worked from my end after a thousand time of trying

  "dependencies": {
    "@shopify/react-native-skia": "1.4.2",
    "react": "18.3.1",
    "react-native": "0.76.0",
    "react-native-fast-tflite": "^1.6.1",
    "react-native-reanimated": "^3.18.0",
    "react-native-vision-camera": "4.5.2",
    "react-native-worklets-core": "^1.5.0",
    "vision-camera-resize-plugin": "^3.2.0"
  },

cresd1601 avatar Jun 16 '25 21:06 cresd1601

Hi, had same issue even with an empty skia frame processor, here is a repro with a simple setup like this

import { useEffect } from "react";
import { StyleSheet } from "react-native";
import { Text } from "~/components/ui/text";
import {
  Camera,
  Frame,
  useCameraPermission,
  useCameraDevice,
  useSkiaFrameProcessor,
} from "react-native-vision-camera";

export default function CameraScreen() {
  const device = useCameraDevice("front");
  const { hasPermission, requestPermission } = useCameraPermission();

  useEffect(() => {
    if (!hasPermission) requestPermission();
  }, [hasPermission, requestPermission]);

  const frameProcessor = useSkiaFrameProcessor((frame: Frame) => {
    "worklet";
  }, []);

  if (!hasPermission) {
    return <Text>No permission</Text>;
  }

  if (device == null) {
    return <Text>No device</Text>;
  }

  return (
    <Camera
      style={StyleSheet.absoluteFill}
      device={device}
      frameProcessor={frameProcessor}
      enableFpsGraph={true}
      enableZoomGesture={true}
      fps={30}
      onError={(e) => {
        console.error("Camera error", e);
      }}
    />
  );
}

and package versions:

{
  "@shopify/react-native-skia": "^2.1.1",
  "react-native-worklets-core": "^1.6.0",
  "react-native-vision-camera": "^4.7.1",
}

mdolr avatar Jul 24 '25 13:07 mdolr

"@shopify/react-native-skia": "1.5.0",
"react-native-vision-camera": "^4.5.3",
 "react-native-worklets-core": "1.5.0",

these versions are working wfine with me android and ios but you have to enable the new arch

3azam0 avatar Jul 24 '25 13:07 3azam0

+1

ItIsGreg avatar Jul 28 '25 21:07 ItIsGreg

+1

tehseenakhtar-fareye avatar Sep 01 '25 07:09 tehseenakhtar-fareye