mrousavy / react-native-vision-camera

📸 A powerful, high-performance React Native Camera library.
https://react-native-vision-camera.com
MIT License
7.65k stars 1.11k forks source link

🐛 Application closes by itself after scanning a barcode. #2243

Closed Rubensem93 closed 10 months ago

Rubensem93 commented 1 year ago

What's happening?

Hello, greetings to the great team you are, I have a problem using the library. It turns out that I implement it as indicated but I have problems after scanning a barcode the application simply quits completely. It can work fine for a few minutes scanning calmly and suddenly as if nothing comes out. Sorry if I'm not a programming veteran, I'm learning to use the library :D greetings and many thanks to the answers.

Reproduceable Code

import React, {useCallback, useState} from 'react';
import {useSelector} from 'react-redux';
import {RootState} from '../assets/store';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import {TextInput, Button, Modal} from 'react-native-paper';
import {Picker} from '@react-native-picker/picker';
import {View, TouchableOpacity, StyleSheet, Text} from 'react-native';
import {
  Camera,
  useCodeScanner,
  useCameraDevice,
} from 'react-native-vision-camera';

const EntregasOrdenes = () => {
  const [selectedOption, setSelectedOption] = useState<string | null>(null);
  const user = useSelector((state: RootState) => state.auth.user);
  const isMasivaEnabled = user?.AGENTE_ASINGADO === 'BODEGA SANTIAGO';
  const [OD, setOD] = useState('');
  const [odsList, setOdsList] = useState<string[]>([]);
  const device = useCameraDevice('back');
  const [showCameraModal, setShowCameraModal] = useState(false);
  const [lockScanner, setLockScanner] = useState(false);

  const updateScanningState = (scannedCode: string) => {
    setOD(scannedCode);
    setOdsList(prevList => [...prevList, scannedCode]);
  };

  const codeScanner = useCodeScanner({
    codeTypes: [
      'qr',
      'ean-13',
      'code-128',
      'code-39',
      'code-93',
      'codabar',
      'ean-8',
    ],
    onCodeScanned: codes => {
      if (!lockScanner && codes.length > 0 && codes[0].value) {
        setLockScanner(true);
        try {
          const scannedCode = codes[0].value;
          updateScanningState(scannedCode);
          console.log(scannedCode);
        } catch (error) {
          console.error('Error al procesar el código escaneado:', error);
        } finally {
          setShowCameraModal(false);
          setTimeout(() => {
            setLockScanner(false);
          }, 3000);
        }
      }
    },
  });

  const onCloseCamera = useCallback(() => {
    setShowCameraModal(false);
  }, []);

  const onCameraError = useCallback(
    (error: any) => {
      console.error('Camera error:', error);
      onCloseCamera();
    },
    [onCloseCamera],
  );

  const handleListOD = () => {
    if (OD !== '') {
      setOdsList(prevList => [...prevList, OD]);
      setOD('');
    }
  };

  if (device == null) {
    return (
      <View style={styles.container}>
        <Text>No hay dispositivo de cámara disponible</Text>
      </View>
    );
  }

  const renderMasivaContent = () => (
    <>
      <View>
        <View style={styles.inputContainer}>
          <TextInput
            style={styles.input}
            label="OD"
            value={OD}
            onChangeText={setOD}
            mode="outlined"
            dense
          />
          <TouchableOpacity onPress={() => setShowCameraModal(true)}>
            <FontAwesome name="barcode" size={30} color="#000" />
          </TouchableOpacity>
        </View>
        <Button
          style={styles.button}
          onPress={handleListOD}
          disabled={OD === ''}>
          Listar OD
        </Button>
        {odsList.map((od, index) => (
          <Text key={index}>{od}</Text>
        ))}
      </View>
      <Modal
        visible={showCameraModal}
        onDismiss={onCloseCamera}
        contentContainerStyle={styles.cameraModalContainer}>
        {device != null && (
          <Camera
            style={styles.cameraFullScreen}
            device={device}
            isActive={true}
            codeScanner={codeScanner}
            onError={onCameraError}
          />
        )}
      </Modal>
    </>
  );

  const renderContent = () => {
    switch (selectedOption) {
      case 'masiva':
        return renderMasivaContent();
      case 'individual':
        return <Text>Contenido de entrega individual aquí</Text>;
      default:
        return <Text>Selecciona una opción para continuar</Text>;
    }
  };

  return (
    <View style={styles.container}>
      <Picker
        selectedValue={selectedOption}
        onValueChange={itemValue => setSelectedOption(itemValue)}
        style={styles.picker}
        itemStyle={styles.pickerItem}
        mode="dropdown">
        <Picker.Item label="Seleccionar tipo de entrega" value={null} />
        {isMasivaEnabled ? (
          <Picker.Item label="Entrega Masiva" value="masiva" />
        ) : (
          <Picker.Item
            label="Entrega Masiva (no disponible)"
            value="masiva"
            color="#ccc"
            enabled={false}
          />
        )}
        <Picker.Item label="Entrega Individual" value="individual" />
      </Picker>
      {selectedOption && renderContent()}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
    alignItems: 'center',
    paddingTop: 10,
  },
  picker: {
    height: 50,
    width: '95%',
    marginBottom: 20,
    borderWidth: 1,
    borderColor: '#ddd',
    backgroundColor: '#fff',
  },
  pickerItem: {
    color: 'black',
  },
  input: {
    flex: 1,
    marginRight: 10,
    color: '#333',
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  button: {
    // Estilos para el botón
  },
  camera: {
    flex: 1,
    width: '100%',
    // Estilos para la cámara
  },
  content: {
    marginTop: 20,
  },
  cameraModalContainer: {
    flex: 1,
    width: '100%', 
    height: '100%',
    backgroundColor: 'black',
  },
  cameraFullScreen: {
    flex: 1,
    width: '100%',
    height: '100%',
  },
  buttonDisabled: {
    backgroundColor: '#ccc',
  },
});

export default EntregasOrdenes;

Relevant log output

6892409
2023-12-01 12:26:50.616 18872-18872 CameraSession           com.cargoapp                         I  PreviewView Surface destroyed! Surface(name=null)/@0x8eae063
2023-12-01 12:26:50.616 18872-18872 CameraSession           com.cargoapp                         I  Destroying Preview Output...
2023-12-01 12:26:50.617 18872-18872 CameraSession           com.cargoapp                         I  Updating CameraSession Configuration...
2023-12-01 12:26:50.618 18872-18872 CameraSession           com.cargoapp                         I  Configuring Session for Camera #0...
2023-12-01 12:26:50.618 18872-18872 SurfaceOutput           com.cargoapp                         I  Closing BarcodeScanner..
--------- beginning of crash
2023-12-01 12:26:50.620 18872-19968 libc                    com.cargoapp                         A  Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x762389f6f4 in tid 19968 (pool-9-thread-6), pid 18872 (com.cargoapp)
2023-12-01 12:26:50.663 18872-18890 BufferQueueProducer     com.cargoapp                         E  [ImageReader-1280x720f23m2-18872-5](id:49b80000000c,api:4,p:1583,c:18872) queueBuffer: BufferQueue has been abandoned
2023-12-01 12:26:50.683 18872-18890 BufferQueueProducer     com.cargoapp                         E  [ImageReader-1280x720f23m2-18872-5](id:49b80000000c,api:4,p:1583,c:18872) queueBuffer: BufferQueue has been abandoned
2023-12-01 12:26:50.703 18872-18872 CameraSession           com.cargoapp                         I  Adding 1280 x 720 CodeScanner Output in Format #35...
2023-12-01 12:26:50.709 18872-18872 CreateCaptureSession    com.cargoapp                         I  Camera 0: Creating Capture Session #1006... Hardware Level: 3} | Outputs: [android.hardware.camera2.params.OutputConfiguration@35fd8976]
2023-12-01 12:26:50.709 18872-18872 CreateCaptureSession    com.cargoapp                         I  Using new API (>=28)
2023-12-01 12:26:50.709 18872-18872 CameraDevice-JV-0       com.cargoapp                         D  waitUntilIdle: E. id = 0
2023-12-01 12:26:50.712 18872-20031 BufferQueueProducer     com.cargoapp                         E  [ImageReader-1280x720f23m2-18872-5](id:49b80000000c,api:4,p:1583,c:18872) queueBuffer: BufferQueue has been abandoned
2023-12-01 12:26:50.717 18872-19558 TransportR...EventStore com.cargoapp                         D  Storing event with priority=DEFAULT, name=FIREBASE_ML_SDK for destination cct
2023-12-01 12:26:50.723 18872-19558 TransportR...oScheduler com.cargoapp                         D  Upload for context TransportContext(cct, DEFAULT, MSRodHRwczovL2ZpcmViYXNlbG9nZ2luZy5nb29nbGVhcGlzLmNvbS92MGNjL2xvZy9iYXRjaD9mb3JtYXQ9anNvbl9wcm90bzNc) is already scheduled. Returning...
2023-12-01 12:26:50.742 18872-20031 BufferQueueProducer     com.cargoapp                         E  [ImageReader-1280x720f23m2-18872-5](id:49b80000000c,api:4,p:1583,c:18872) queueBuffer: BufferQueue has been abandoned
2023-12-01 12:26:50.985 18872-18890 BufferQueueProducer     com.cargoapp                         E  [ImageReader-1280x720f23m2-18872-5](id:49b80000000c,api:4,p:1583,c:18872) queueBuffer: BufferQueue has been abandoned
2023-12-01 12:26:50.999 18872-18892 BufferQueueProducer     com.cargoapp                         E  [ImageReader-1280x720f23m2-18872-5](id:49b80000000c,api:4,p:1583,c:18872) queueBuffer: BufferQueue has been abandoned
2023-12-01 12:26:50.999 18872-18872 BpBinder                com.cargoapp                         W  Slow Binder: BpBinder transact took 291 ms, interface=android.hardware.camera2.ICameraDeviceUser, code=14 oneway=false
2023-12-01 12:26:51.000 18872-18872 CameraDevice-JV-0       com.cargoapp                         D  waitUntilIdle: X
2023-12-01 12:26:51.004 31138-31540 MIUISafety-Monitor      com.miui.securitycenter.remote       I  OnOpActiveChanged com.cargoapp ,op:android:camera ,active:false
2023-12-01 12:26:51.230 18872-18872 BpBinder                com.cargoapp                         W  Slow Binder: BpBinder transact took 224 ms, interface=android.hardware.camera2.ICameraDeviceUser, code=6 oneway=false
2023-12-01 12:26:51.231 18872-19927 com.cargoapp            com.cargoapp                         W  Long monitor contention with owner main (18872) at void android.hardware.camera2.impl.CameraDeviceImpl.waitUntilIdle()(CameraDeviceImpl.java:1351) waiters=0 in void android.hardware.camera2.impl.CameraDeviceImpl$4.run() for 521ms
2023-12-01 12:26:51.231 18872-19964 com.cargoapp            com.cargoapp                         W  Long monitor contention with owner main (18872) at void android.hardware.camera2.impl.CameraDeviceImpl.waitUntilIdle()(CameraDeviceImpl.java:1351) waiters=1 in void android.hardware.camera2.impl.CameraDeviceImpl$CameraDeviceCallbacks.onCaptureStarted(android.hardware.camera2.impl.CaptureResultExtras, long) for 511ms
2023-12-01 12:26:51.232 18872-19927 CreateCaptureSession    com.cargoapp                         I  Camera 0: Capture Session #1006 configured!
2023-12-01 12:26:51.233 18872-18872 CameraSession           com.cargoapp                         I  Successfully configured Session with 1 outputs for Camera #0!
2023-12-01 12:26:51.233 18872-18872 CameraSession           com.cargoapp                         W  Preview Output is null, aborting...
2023-12-01 12:26:51.233 18872-18872 CameraSession           com.cargoapp                         I  Successfully updated CameraSession Configuration! isActive: true
2023-12-01 12:26:51.234 18872-18872 SurfaceView             com.cargoapp                         D  UPDATE Surface(name=SurfaceView[com.cargoapp/com.cargoapp.MainActivity])/@0xbf1e460, mIsCastMode = false
2023-12-01 12:26:51.237 18872-19927 CreateCaptureSession    com.cargoapp                         I  Camera 0: Capture Session #1005 closed!
2023-12-01 12:26:51.237 18872-18872 SurfaceView             com.cargoapp                         D  UPDATE Surface(name=SurfaceView[com.cargoapp/com.cargoapp.MainActivity])/@0xbf1e460, mIsProjectionMode = false
2023-12-01 12:26:51.238 18872-18872 CameraView              com.cargoapp                         I  Updating CameraSession...
2023-12-01 12:26:51.239 18872-19927 CameraSession           com.cargoapp                         I  Updating CameraSession Configuration...
2023-12-01 12:26:51.239 18872-19927 CameraSession           com.cargoapp                         I  Successfully updated CameraSession Configuration! isActive: false
2023-12-01 12:26:51.239 18872-18872 CameraSession           com.cargoapp                         I  Destroying session..
2023-12-01 12:26:51.240 18872-18872 CameraExtImplXiaoMi     com.cargoapp                         D  releaseCameraDevice: 0
2023-12-01 12:26:51.240 18872-18872 CameraDevice-JV-0       com.cargoapp                         D  close: E. id = 0
2023-12-01 12:26:51.241 18872-19927 CreateCaptureSession    com.cargoapp                         I  Camera 0: Capture Session #1006 closed!
2023-12-01 12:26:51.404 18872-19964 BpBinder                com.cargoapp                         I  onLastStrongRef automatically unlinking death recipients: <uncached descriptor>
2023-12-01 12:26:51.409 18872-18872 CameraDevice-JV-0       com.cargoapp                         D  close: X
2023-12-01 12:26:51.409 18872-18872 SurfaceOutput           com.cargoapp                         I  Closing BarcodeScanner..
2023-12-01 12:26:51.410 18872-19927 com.cargoapp            com.cargoapp                         W  Long monitor contention with owner main (18872) at void android.hardware.camera2.impl.CameraDeviceImpl.close()(CameraDeviceImpl.java:1429) waiters=0 in void android.hardware.camera2.impl.CameraCaptureSessionImpl$AbortDrainListener.onDrained() for 169ms
2023-12-01 12:26:51.412 18872-20157 CameraManagerGlobal     com.cargoapp                         E  Camera 61 is not available. Ignore physical camera status change
2023-12-01 12:26:51.414 18872-19356 CameraDevices           com.cargoapp                         I  Camera #0: Available!
2023-12-01 12:26:51.414 18872-18872 Looper                  com.cargoapp                         W  PerfMonitor doFrame : time=800ms vsyncFrame=0 latency=1ms procState=-1
2023-12-01 12:26:51.415 18872-18872 Choreographer           com.cargoapp                         I  Skipped 47 frames!  The application may be doing too much work on its main thread.
2023-12-01 12:26:51.415 18872-18872 Looper                  com.cargoapp                         W  PerfMonitor doFrame : time=1ms vsyncFrame=0 latency=785ms procState=-1 historyMsgCount=1
2023-12-01 12:26:51.435 18872-19964 OpenGLRenderer          com.cargoapp                         I  Davey! duration=810ms; Flags=0, FrameTimelineVsyncId=50456210, IntendedVsync=1114819448631837, Vsync=1114819448631837, InputEventId=0, HandleInputStart=1114819449656434, AnimationStart=1114819449662111, PerformTraversalsStart=1114820246624454, DrawStart=1114820247168569, FrameDeadline=1114819465298503, FrameInterval=1114819449631434, FrameStartTime=16666666, SyncQueued=1114820247836277, SyncStart=1114820247947892, IssueDrawCommandsStart=1114820249343673, SwapBuffers=1114820253155600, FrameCompleted=1114820259423517, DequeueBufferDuration=44115, QueueBufferDuration=2113125, GpuCompleted=1114820259423517, SwapBuffersCompleted=1114820255863517, DisplayPresentTime=0, 
2023-12-01 12:26:51.989 20154-20154 DEBUG                   crash_dump64                         A  Cmdline: com.cargoapp
2023-12-01 12:26:51.989 20154-20154 DEBUG                   crash_dump64                         A  pid: 18872, tid: 19968, name: pool-9-thread-6  >>> com.cargoapp <<<
2023-12-01 12:26:51.990 20154-20154 DEBUG                   crash_dump64                         A        #00 pc 00000000000cec9c  /data/app/~~QEKFcW02rtSNwPdmbzwg2g==/com.cargoapp-GkKLTyoPk65ioIQoyViXqA==/base.apk!libbarhopper_v3.so (BuildId: 0a454aedfe8b3c349e50551052b0d16d)
2023-12-01 12:26:51.990 20154-20154 DEBUG                   crash_dump64                         A        #01 pc 00000000000cebac  /data/app/~~QEKFcW02rtSNwPdmbzwg2g==/com.cargoapp-GkKLTyoPk65ioIQoyViXqA==/base.apk!libbarhopper_v3.so (BuildId: 0a454aedfe8b3c349e50551052b0d16d)
2023-12-01 12:26:51.990 20154-20154 DEBUG                   crash_dump64                         A        #02 pc 00000000000aaa08  /data/app/~~QEKFcW02rtSNwPdmbzwg2g==/com.cargoapp-GkKLTyoPk65ioIQoyViXqA==/base.apk!libbarhopper_v3.so (BuildId: 0a454aedfe8b3c349e50551052b0d16d)
2023-12-01 12:26:51.990 20154-20154 DEBUG                   crash_dump64                         A        #03 pc 00000000000ab1e8  /data/app/~~QEKFcW02rtSNwPdmbzwg2g==/com.cargoapp-GkKLTyoPk65ioIQoyViXqA==/base.apk!libbarhopper_v3.so (BuildId: 0a454aedfe8b3c349e50551052b0d16d)
2023-12-01 12:26:51.990 20154-20154 DEBUG                   crash_dump64                         A        #04 pc 00000000000a9598  /data/app/~~QEKFcW02rtSNwPdmbzwg2g==/com.cargoapp-GkKLTyoPk65ioIQoyViXqA==/base.apk!libbarhopper_v3.so (BuildId: 0a454aedfe8b3c349e50551052b0d16d)
2023-12-01 12:26:51.990 20154-20154 DEBUG                   crash_dump64                         A        #05 pc 00000000000a963c  /data/app/~~QEKFcW02rtSNwPdmbzwg2g==/com.cargoapp-GkKLTyoPk65ioIQoyViXqA==/base.apk!libbarhopper_v3.so (Java_com_google_android_libraries_barhopper_BarhopperV3_recognizeBufferNative+88) (BuildId: 0a454aedfe8b3c349e50551052b0d16d)
2023-12-01 12:26:52.039  1848-20174 ActivityTaskManager     system_server                        W    Force finishing activity com.cargoapp/.MainActivity
2023-12-01 12:26:52.202  1848-3542  ActivityManager         system_server                        I  Process com.cargoapp (pid 18872) has died: vis TOP 
2023-12-01 12:26:52.203  1583-9841  Camera2ClientBase       cameraserver                         I  Closed Camera 0. Client was: com.cargoapp (PID 18872, UID 10588)
2023-12-01 12:26:52.204  1848-2467  WindowManager           system_server                        I  WIN DEATH: Window{a7eb37d u0 com.cargoapp/com.cargoapp.MainActivity}
2023-12-01 12:26:52.205  1848-2467  InputManager-JNI        system_server                        W  Input channel object 'a7eb37d com.cargoapp/com.cargoapp.MainActivity (client)' was disposed without first being removed with the input manager!
2023-12-01 12:26:52.207  1848-1894  AutofillSession         system_server                        D  handling death of Token{ed44dae ActivityRecord{2a4474f u0 com.cargoapp/.MainActivity t7345 f}}} when saving=false
2023-12-01 12:26:52.212  1848-3542  ProcessManager          system_server                        D  skip restart com.cargoapp because this device is a lowmemory device!
2023-12-01 12:26:52.243 12874-12889 GST                     com.xiaomi.joyose                    I  forePkg: com.miui.home, preForePkg: com.cargoapp
2023-12-01 12:26:52.243 31138-20176 ProcessMonitor          com.miui.securitycenter.remote       I  onForegroundInfoChanged: ForegroundInfo{mForegroundPackageName='com.miui.home', mForegroundUid=10091, mForegroundPid=6335, mLastForegroundPackageName='com.cargoapp', mLastForegroundUid=10588, mLastForegroundPid=18872, mMultiWindowForegroundPackageName='com.miui.home', mMultiWindowForegroundUid=10091, mFlags=0}
2023-12-01 12:26:52.243 28024-29028 PerfEngineController    com.miui.powerkeeper                 D  ForegroundInfo{mForegroundPackageName='com.miui.home', mForegroundUid=10091, mForegroundPid=6335, mLastForegroundPackageName='com.cargoapp', mLastForegroundUid=10588, mLastForegroundPid=18872, mMultiWindowForegroundPackageName='com.miui.home', mMultiWindowForegroundUid=10091, mFlags=0}
2023-12-01 12:26:52.243  6335-24509 AppObserver             com.miui.home                        D  ForegroundInfo{mForegroundPackageName='com.miui.home', mForegroundUid=10091, mForegroundPid=6335, mLastForegroundPackageName='com.cargoapp', mLastForegroundUid=10588, mLastForegroundPid=18872, mMultiWindowForegroundPackageName='com.miui.home', mMultiWindowForegroundUid=10091, mFlags=0}
2023-12-01 12:26:52.243 28024-28055 ThermalInfoCollector    com.miui.powerkeeper                 I  collectForgroundAppsInfo: com.cargoapp
2023-12-01 12:26:52.315 31138-20176 GameBoosterService      com.miui.securitycenter.remote       I  onForegroundInfoChanged: Cur=com.miui.home   last=com.cargoapp
2023-12-01 12:26:52.317 31138-20176 GameBoosterService      com.miui.securitycenter.remote       D  onGameStatusChange foreground:ForegroundInfo{mForegroundPackageName='com.miui.home', mForegroundUid=10091, mForegroundPid=6335, mLastForegroundPackageName='com.cargoapp', mLastForegroundUid=10588, mLastForegroundPid=18872, mMultiWindowForegroundPackageName='com.miui.home', mMultiWindowForegroundUid=10091, mFlags=0}
2023-12-01 12:26:52.543  1848-2088  ActivityTaskManager     system_server                        W  Activity top resumed state loss timeout for ActivityRecord{2a4474f u0 com.cargoapp/.MainActivity t-1 f}}

Camera Device

camara doble ancho

Device

redmi note 9s 4gb ram miui 14.0.4

VisionCamera Version

"react-native-vision-camera": "^3.6.12",

Can you reproduce this issue in the VisionCamera Example app?

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

Additional information

Woobeen906 commented 12 months ago

i have same issue.....

tahaipek commented 12 months ago

I downgraded the package version to 3.6.6 but it didn't work. How can i solve this issue?

Yeasirarafat53 commented 12 months ago

I downgraded the package version to 3.6.6 but it didn't work. How can i solve this issue?

you can use 3.5.1

tahaipek commented 12 months ago

I found a temporary solution.

Don't use any function that affects any interface inside the "onCodeScanned" function. Like "useState, useCallback, setXYZ, runOnJS".

When I ran the process without using these functions, I noticed that it didn't give an error when reading the QR code. For now, the problem seems to be solved, the code quality of course decreases a bit.

Can anyone else try this workaround?

const codeScanner = useCodeScanner({
    codeTypes: [
      'qr',
      'ean-13',
      'code-128',
      'code-39',
      'code-93',
      'codabar',
      'ean-8',
    ],
    onCodeScanned: codes => {
    ///// This function
    },
  });
iliapnmrv commented 12 months ago

@tahaipek can you please share more data? how can you

Don't use any function that affects any interface inside the "onCodeScanned" function.

Isn't it the main purpose of onCodeScanned method?

tahaipek commented 12 months ago

Of course this is the task of the "onCodeScanned" function. But here there is an error when the QR code is read. I am looking for a permanent solution for this. For now, I have reached a temporary solution, even if it is bad.

For now, I completed the development by removing the interface interactions. When the QR code is scanned, I showed a message on the screen with "Alert" and redirected the page.

In the meantime, I realized that when the QR code is read, the application crashes as soon as I perform an operation that affects the UI in ReactNative. So I experimented by bypassing the elements that affect the UI one by one. I realized that there was no problem in using the native components of the phone, so I used "Alert".

I tried this crash issue on Samsung S23, S23 Ultra and android emulator and so far no problem.

If anyone tries differently, we can address the error more clearly. Since my knowledge of native application development is limited, I think the issue is caused by data sharing between threads, I am not sure and I do not want to mislead.


export default function CodeScannerPage({ navigation }) {
  const [qrData, setQrData] = useState('-');

  // Use a simple default back camera
  const device = useCameraDevice('back');

  const onCodeScanned = useCallback((codes) => {
    console.log(`Scanned ${codes.length} codes:`, codes);

    setQrData('Scanning QR Data...');

    const value = codes[0]?.value;
    if (value == null) {
      setQrData('Invalid QR Data or something...');
      return;
    }
    setQrData(value);

    // Some QR Scenarios...
  }, []);

  // Initialize the Code Scanner to scan QR codes and Barcodes
  const codeScanner = useCodeScanner({
    codeTypes: ['qr', 'ean-13'],
    onCodeScanned: onCodeScanned,
  });

  return (
    <View>
      <Camera
        style={StyleSheet.absoluteFill}
        device={device}
        isActive={true}
        codeScanner={codeScanner}
      />

      <View>
        <Text>{qrData}</Text>
      </View>
    </View>
  );
}

Temporary solution


export default function CodeScannerPage({ navigation }) {
  // Use a simple default back camera
  const device = useCameraDevice('back');
  const codeScanner = useCodeScanner({
    codeTypes: ['qr', 'ean-13'],
    onCodeScanned: (codes) => {
      console.log(`Scanned ${codes.length} codes:`, codes);

      const value = codes[0]?.value;
      if (value == null) {
        Alert.alert('Invalid QR Data or something...');
        return;
      }

      Alert.alert('QR Data:', value);

      // Some QR Scenarios...
    },
  });

  return (
    <View>
      <Camera
        style={StyleSheet.absoluteFill}
        device={device}
        isActive={true}
        codeScanner={codeScanner}
      />
    </View>
  );
}
Rodricity commented 11 months ago

I've been struggling with a similar issue for the last two days, cant get the source problem, but seems like navigating away from the camera while it hasnt properly stop triggers this type of crash.

Seems like another way arround is to 'wait' for propper stop of the camera, so what I did was to use the code read to alter the 'isActive' property and then on the 'onStopped' prop of Camera instance fire the navigation/detection to another component.

Here is an example.

type Props = { onDetection?: (code: Code) => void };

export function CameraScanner(props: Props) {
    const { onDetection } = props;
    const [QR, setQR] = useState<Code>();

    const isFocused = useIsFocused();
    const appState = useAppState();
    const isActive = appState === "active" && isFocused && QR === undefined;

    // To clear the QR everytime the navigation switchs to this component.
    useEffect(() => {
        if (isFocused && QR) setQR(undefined);
    }, [isFocused]);

    const QRDetector = useCodeScanner({ codeTypes: ["qr"], onCodeScanned: codes => QR === undefined && setQR(codes[0]) });

    const device = useCameraDevice("back");
    if (!device) return <Text>No hemos logrado obtener un dispositivo de cámara</Text>;

    return (
        <Camera
            onStopped={() => QR && onDetection && onDetection(QR)}
            key={device.id}
            device={device}
            video={false}
            audio={false}
            codeScanner={QRDetector}
            style={StyleSheet.absoluteFill}
            isActive={isActive}
        />
    );
}
haliechm commented 11 months ago

+1

klabusta commented 11 months ago

Same here Xiaomi Redmi Note 10, 3.6.16

mrousavy commented 11 months ago

Hey! Thanks for reporting this issue.

I've been working the past days on making sure the Camera lifecycle is safely handled and released when needed to make sure this crash doesn't occur anymore.

I just created a PR for this - can you please this to see if that fixes the issue for you? https://github.com/mrousavy/react-native-vision-camera/pull/2339

If this fixes your issue, please consider 💖 sponsoring me on GitHub 💖 to support me / thank me for building VisionCamera and continuously improving it.

If this does not fix your issue, please clone the repo, check out the branch fix/blackscreen (the PR above), run the Example app, reproduce your issue there and share the adb logcat logs with me (upload to pastebin or gist) so I can investigate this further.

Thank you! 🙏

klabusta commented 10 months ago

Still crashing with 3.7.0, initialization works much better though! My adb logcat looks pretty similar to the one from above :(

I've let chatGPT analyze the logcat output:

Analyzing the provided adb logcat, there are several key errors that might be related to the crash you're experiencing after scanning barcodes with the react-native-camera-vision library:

BufferQueue has been abandoned: This error often indicates that there's an issue with the camera buffer queue. It's a sign that the application is trying to access or manipulate the camera's buffer queue after it has been released or invalidated.
Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR): This is a segmentation fault signal. It's generally a strong indicator of a memory access violation. This can happen if the application is trying to access an invalid memory location, which could be the result of improper handling of camera data or buffers.
Camera-related errors: Various camera-related errors like Camera3-OutputStream and BufferQueueProducer errors suggest issues with handling the camera stream or data processing.
Errors related to libbarhopper_v3.so: This seems to be a native library used for barcode scanning. The crash might be occurring within this library, possibly due to improper handling of the camera data or due to some bug within the library itself. 
klabusta commented 10 months ago

Similar to https://github.com/mrousavy/react-native-vision-camera/issues/2341#issuecomment-1886916320 I now know how I can prevent it from closing/crashing. I render the Camera component conditionally. The reason is the following:

I have a bottom tab bar and I show the screen with the camera on one tab. But I also show the camera on another tab, when opening a modal (on this modal). To not have two Camera components open at the same time, I had to hide either. @mrousavy I hope that makes sense. This behaviour worked fine with v2.

I get this error https://github.com/mrousavy/react-native-vision-camera/issues/2378 if I don't hide either.