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

πŸ› [session/invalid-output-configuration: Failed to configure the Camera Session because the output/stream configurations are invalid!]

Open devanshisrivastava20 opened this issue 8 months ago β€’ 16 comments

What's happening?

Hi I am using this library in my React Native project for barcode scanning only.

I am getting this error intermittently from the library specifically on Android after I launch the Camera and grant access. Earlier it was happening continuously but after fixing it with the App Background/Foreground and ref management logic it started working once the camera is open. I have 3 points to launch this camera - 1) App quick link 2) Home Page Icon for Barcode scanner 3) Icon shown on Search Field when its in focus

I can add more details as needed

Reproduceable Code

import React, { useState, useRef, useEffect } from 'react';
import { useIsFocused } from '@react-navigation/native';
import { Button, Header, withTheme } from 'react-native-elements';
import { View, AppState, Platform, Text, Linking, StyleSheet } from 'react-native';
import { useCameraDevice, Camera, useCodeScanner, useCameraPermission } from 'react-native-vision-camera';

import Styles from './ScanBarcode.style';
import WithLoader from '../hoc/loader';

export const isAppInBackgroundMode = (appState: any) => {
  if (appState != null && typeof appState.current === 'string' && appState?.current?.match(/inactive|background/)) {
    return true;
  }
  return false;
};

export const ScanBarcode = (props) => {
  const {
    theme,
    navigation,
    searchResultData,
  } = props;

  const {
    messageWrapper,
    scanMessage,
    scanArea,
    blankArea,
    sideBlankArea,
    middleArea,
    middleAreaContainer,
  } = Styles(theme);

  const device = useCameraDevice('back');
  const permissionRequested = useRef(false);

  const { hasPermission, requestPermission } = useCameraPermission();

  const [scanned, setScanned] = useState(false);

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

  const isFocused = useIsFocused();
  const appState = useRef(AppState.currentState);

  const _handleAppStateChange = (nextAppState: any) => {
    appState.current = nextAppState;
    const isBackground = isAppInBackgroundMode(appState);
    if (!isBackground && !permissionRequested.current) {
      requestPermission();
      permissionRequested.current = true;
    }
  };

  React.useEffect(() => {
    const listener = AppState.addEventListener('change', _handleAppStateChange);
    return () => {
      listener?.remove();
    };
  }, []);

  React.useEffect(() => {
    if (searchResultData) {
      //code
    }
  }, [searchResultData]);

  const handleBarCodeScanned = useCodeScanner({
    codeTypes: [
      'code-128',
      'code-39',
      'code-93',
      'codabar',
      'ean-13',
      'ean-8',
      'itf',
      'upc-e',
      'upc-a',
      'qr',
      'pdf-417',
      'aztec',
      'data-matrix',
    ],
    onCodeScanned: codes => {
      setScanned(true);
      const code = codes && codes[0];
      let data: string = code.value;
      if (isValidBarcode(data)) {
        data = data?.length === 12 ? `0${data}` : data;
        setScanned(true);
        //code
      } else {
       //code
      }
    },
  });

  if (hasPermission === null) {
    return <View />;
  }

  if (!isFocused) {
    return null;
  }

  const handleOpenSetting = () => {
    navigation.pop();
    Linking.openSettings();
  };

  const isAndroid = Platform.OS === 'android';
  const isRefForAndroid = isAndroid ? permissionRequested.current : true;
  const shouldShowCamera = hasPermission === true ? isRefForAndroid : false;

  return (
    <View style={{ flex: 1 }}>
      <Header />
      {shouldShowCamera ? (
        <React.Fragment>
          <View style={messageWrapper}>
            <Text style={scanMessage}>
              {'scanBarcodeScreenMessage'}
            </Text>
          </View>
          <View style={{ flex: 1 }}>
            <Camera
              device={device}
              style={StyleSheet.absoluteFill}
              isActive={true}
              codeScanner={scanned ? undefined : handleBarCodeScanned}
            />
            <View style={scanArea}>
              <View style={blankArea} />
              <View style={middleAreaContainer}>
                <View style={sideBlankArea} />
                <View style={middleArea} />
                <View style={sideBlankArea} />
              </View>
              <View style={blankArea} />
            </View>
          </View>
        </React.Fragment>
      ) : null}

      {!hasPermission ? (
        <View style={messageWrapper}>
          <Text style={scanMessage}>{'noCameraAccess'}</Text>
          <Button
            title={'openSettings'}
            type='clear'
            onPress={() => handleOpenSetting()}
          />
        </View>
      ) : null}
    </View>
  );
};

export default withTheme(WithLoader(ScanBarcode));

Relevant log output

{ [session/invalid-output-configuration: Failed to configure the Camera Session because the output/stream configurations are invalid!]
                                                                                                      name: 'session/invalid-output-configuration',
                                                                                                      _code: 'session/invalid-output-configuration',
                                                                                                      _message: 'Failed to configure the Camera Session because the output/stream configurations are invalid!',
                                                                                                      _cause: 
                                                                                                       { stacktrace: 'java.util.concurrent.TimeoutException: Future[androidx.camera.core.impl.utils.futures.ListFuture@cbbc556] is not done within 5000 ms.\n\tat androidx.camera.core.impl.utils.futures.Futures.lambda$makeTimeoutFuture$1(Futures.java:437)\n\tat androidx.camera.core.impl.utils.futures.Futures$$ExternalSyntheticLambda7.call(D8$$SyntheticClass:0)\n\tat androidx.camera.core.impl.utils.executor.HandlerScheduledExecutorService$HandlerScheduledFuture.run(HandlerScheduledExecutorService.java:243)\n\tat android.os.Handler.handleCallback(Handler.java:958)\n\tat android.os.Handler.dispatchMessage(Handler.java:99)\n\tat android.os.Looper.loopOnce(Looper.java:257)\n\tat android.os.Looper.loop(Looper.java:368)\n\tat android.os.HandlerThread.run(HandlerThread.java:67)\n',
                                                                                                         message: 'Future[androidx.camera.core.impl.utils.futures.ListFuture@cbbc556] is not done within 5000 ms.' } }

Camera Device

{
  "hardwareLevel": "full",
  "hasFlash": true,
  "hasTorch": true,
  "id": "0",
  "isMultiCam": false,
  "maxExposure": 12,
  "maxZoom": 10,
  "minExposure": -12,
  "minFocusDistance": 8,
  "minZoom": 1,
  "name": "0 (BACK) androidx.camera.camera2",
  "neutralZoom": 1,
  "physicalDevices": [
    "wide-angle-camera"
  ],
  "position": "back",
  "sensorOrientation": "landscape-left",
  "supportsFocus": true,
  "supportsLowLightBoost": false,
  "supportsRawCapture": false
}

Device

Android 11 - Samsung M13, Android 14 - OnePlus 9R

VisionCamera Version

4.6.4

Can you reproduce this issue in the VisionCamera Example app?

No, I cannot reproduce the issue in the Example app

Additional information

devanshisrivastava20 avatar Apr 07 '25 07:04 devanshisrivastava20

Guten Tag, Hans here! 🍻

Thanks for providing ze detailed report and logs. It looks like you're encountering an intermittent error with ze camera configuration. Since you mentioned you're not able to reproduce it in ze example app, it's important to investigate further.

Make sure to check if your camera permissions are being handled correctly, as toggle states between background and foreground can be tricky. Additionally, it might help to try simplifying your use case and see if that maintains stability.

If ze problem persists, please provide more details, like any patterns in when ze error occurs or if there are specific steps that lead to it.

Danke!

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

maintenance-hans[bot] avatar Apr 07 '25 07:04 maintenance-hans[bot]

I have the same issue with Camera (not barcode) - version 4.6.4 on android (works fine on ios), expo 52.0.41, "react-native": "0.76.7",

<Camera
          style={StyleSheet.absoluteFill}
          device={device}
          isActive={isCameraActive}
          ref={cameraRef}
          photo={mode == 'P'}
          video={isVideo || mode == 'V'}
          audio={isVideo || mode == 'V'}
          onCameraReady={() => console.log('DEBUG onCameraReady')}
        />   

lc3t35 avatar Apr 08 '25 20:04 lc3t35

I made some changes to the codeβ€”now the issue only occurs the first time Camera asks for permission, but everything works fine after that.

Specific to Android

export const useAppStateListener = () => { const appState = useRef(AppState.currentState); const [appStateVisible, setAppStateVisible] = React.useState(appState.current); const _handleAppStateChange = (nextAppState: any) => { appState.current = nextAppState; setAppStateVisible(appState.current); }; React.useEffect(() => { const listener = AppState.addEventListener('change', _handleAppStateChange); return () => { listener.remove(); }; }, []); return appStateVisible; };

export const ScanBarcode = (props) => { const { theme, navigation, searchResultData, } = props;

const device = useCameraDevice('back'); const { hasPermission, requestPermission } = useCameraPermission();

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

const isFocused = useIsFocused(); const currentAppState = useAppStateListener();

return ( <View style={{ flex: 1 }}> <Header /> {hasPermission ? ( <React.Fragment> <View style={messageWrapper}> <Text style={scanMessage}> {'scanBarcodeScreenMessage'} </Text> </View> <View style={{ flex: 1 }}> <Camera device={device} style={StyleSheet.absoluteFill} isActive={currentAppState === 'active'} codeScanner={scanned ? undefined : handleBarCodeScanned} />

    </React.Fragment>
  ) : null}

); }

devanshisrivastava20 avatar Apr 11 '25 05:04 devanshisrivastava20

Downgraded to 4.6.1 / no change ... I was using Camera.getCameraPermissionStatus / requestCameraPermission and for Microphone -> moved to useCameraPermission and useMicrophonePermission checking both in the initial useEffect

useEffect(() => {
    if (!hasCameraPermission) {
      requestCameraPermission();
    }
    if (!hasMicrophonePermission) {
      requestMicrophonePermission();
    }
}, []), 

still crashing without any visible error in expo fixed with useAppStateListener in main app.js excluding the current screen to navigate to Home when nextAppState becomes active from previous background state

lc3t35 avatar Apr 12 '25 16:04 lc3t35

Hello guys, I got the same message

ERROR [session/invalid-output-configuration: Failed to configure the Camera Session because the output/stream configurations are invalid!]

Because I copy the same code in my app

  return (
    <SafeAreaView style={styles.container}>
      <Camera
        style={StyleSheet.absoluteFill}
        device={device}
        isActive={true}
        frameProcessorFps={2}
        {...props}
        codeScanner={isScanning ? codeScanner : undefined}
      />
      <View style={styles.infoContainer}>
        <Text style={styles.infoText}>Point the camera at a code</Text>
      </View>
    </SafeAreaView>
  );

But after removing the <SafeAreaView style={styles.container}> and </SafeAreaView> the camera works and the app scans correctly. Note: I remove the SafeAreaView because my component is already in an existing <View></View> code.

I hope it can help you !

aron-skaleet avatar May 04 '25 10:05 aron-skaleet

@aron-skaleet "But after removing the .... ", removing what please ?

lc3t35 avatar May 04 '25 17:05 lc3t35

πŸ‘€

brunnosena avatar Jul 23 '25 21:07 brunnosena

@aron-skaleet "But after removing the .... ", removing what please ?

Hello @lc3t35 I have removed <SafeAreaView style={styles.container}>in my original code because my component is already contained for another View parent component. So finally, my code is:

  return (
    <Camera
      style={StyleSheet.absoluteFill}
      device={device}
      isActive={isActive && isFocused && appState === "active"}
      torch={flashOn ? "on" : "off"}
      codeScanner={isScanning ? codeScanner : undefined}
    />
  );

I hope it can help you.

aehp20 avatar Jul 23 '25 21:07 aehp20

I have the same problem. I modified the style and stopped using absolute, which solved the problem. I hope it can help you. Good luck!

cx5168 avatar Jul 25 '25 03:07 cx5168

If you have this issue, check the re-mounting, just isolate the component and try from there, we had this issue and I resolved it with that. For example we had it conditionally display based on a value. We removed that conditional display and it worked correctly from there. You can make use of isActive prop too.

joaquinvaz avatar Aug 04 '25 15:08 joaquinvaz

I am having this issue too and I've had no luck with the other suggestions. My component is not wrapped in an absolute div and is not reliant on any conditionals to display. Photo works as expected, but whenever I enabled the video prop it blows up with that error [session/invalid-output-configuration: Failed to configure the Camera Session because the output/stream configurations are invalid!]

<Camera
    device={device}
    isActive={isCameraActive}
    style={styles.camera}
    format={{ ...format }}
    zoom={0}
    enableZoomGesture={true}
    ref={camera}
    // photo={true}
    video={true}
    exposure={-1}
    onInitialized={() => {
        console.log('Camera initialized');
        setIsCameraActive(true);
    }}
/>

More logs:

Reporting error [session/invalid-output-configuration]: Failed to configure the Camera Session because the output/stream configurations are invalid! (caused by {"message":"onConfigureFailed","stacktrace":"java.lang.IllegalStateException: onConfigureFailed\n\tat androidx.camera.camera2.internal.SynchronizedCaptureSessionBaseImpl$2.onConfigureFailed(SynchronizedCaptureSessionBaseImpl.java:263)\n\tat android.hardware.camera2.impl.CallbackProxies$SessionStateCallbackProxy.lambda$onConfigureFailed$1$CallbackProxies$SessionStateCallbackProxy(CallbackProxies.java:64)\n\tat android.hardware.camera2.impl.CallbackProxies$SessionStateCallbackProxy$$ExternalSyntheticLambda3.run(Unknown Source:4)\n\tat androidx.camera.core.impl.utils.executor.SequentialExecutor$QueueWorker.workOnQueue(SequentialExecutor.java:229)\n\tat androidx.camera.core.impl.utils.executor.SequentialExecutor$QueueWorker.run(SequentialExecutor.java:171)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)\n\tat java.lang.Thread.run(Thread.java:920)\n"}): session/invalid-output-configuration: Failed to configure the Camera Session because the output/stream configurations are invalid!
   at apply (/node_modules/@babel/runtime/helpers/construct.js:4:65)
   at _dependencyMap (/node_modules/@babel/runtime/helpers/wrapNativeSuper.js:15:14)
   at diffDegrees (/node_modules/react-native-vision-camera/src/RotationHelper.ts:45:4)
   at _callSuper (/node_modules/react-native-vision-camera/src/CameraError.ts:155:5)
   at diffDegrees (/node_modules/react-native-vision-camera/src/RotationHelper.ts:45:4)
   at _callSuper (/node_modules/react-native-vision-camera/src/CameraError.ts:182:32)
   at CameraRuntimeError (/node_modules/react-native-vision-camera/src/Camera.tsx:502:47)
   at listener (/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js:166:17)
   at executeDispatch (/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js:197:24)
   at executeDispatchesInOrder (/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js:2818:33)
   at executeDispatchesAndRelease (/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js:2827:41)
   at call (/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js:983:16)
   at forEachAccumulated (/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js:2843:25)
   at runEventsInBatch (/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js:2908:23)
   at runExtractedPluginEventsInBatch (/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js:2955:40)
   at fn (/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js:22997:18)
   at batchedUpdatesImpl (/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js:2791:34)
   at batchedUpdates$1 (/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js:2924:23)

NoahVandy avatar Aug 04 '25 18:08 NoahVandy

@NoahVandy just tried it and it's working fine, didn't apply the video functionality but I put the flag Also, check that you have the latest version from the lib

in styles I have just height set up try:

{
height: some number
}

  <Camera
    style={styles.container}
    codeScanner={codeScanner}
    device={device}
    isActive={true}
    photo={false}
    video={true}
    torch={props.flash ? 'on' : 'off'} />

joaquinvaz avatar Aug 04 '25 18:08 joaquinvaz

Removing the format prop when taking a video worked for me πŸ‘

NoahVandy avatar Aug 04 '25 19:08 NoahVandy

Removing the conditional rendering solved the issue for me. But this seems more like a workaround?

SveBo avatar Sep 03 '25 22:09 SveBo

Hi, I'm experiencing the exact same issue on Android.

session/invalid-output-configuration: Failed to configure the Camera Session because the output/stream configurations are invalid
Caused by: java.util.concurrent.TimeoutException: Future is not done within 5000 ms

It happens when Production build only - Works perfectly in DEV mode, but fails in production (release APK/AAB) First app launch only - Fails on the very first camera initialization after installing the app. If I close and reopen the app, the camera works fine Android only - iOS works perfectly in both dev and production Camera state flow - The camera successfully reaches OPEN state, then times out at ERROR_STREAM_CONFIG after exactly 5 seconds

What I've tried: Removing the format prop entirely - same error Using different format templates Simplifying camera configuration Updated from react-native-vision-camera 4.6.3 to 4.7.2 - same issue Added extensive logging - camera binds successfully but times out during stream configuration

Questions

  • Has anyone found a solution or workaround for this?
  • Could the production vs dev difference indicate a ProGuard/R8 minification issue?
  • Could the "first launch only" behavior suggest a timing/initialization race condition that only happens with cold start?

gosbhs12 avatar Nov 06 '25 01:11 gosbhs12