🐛 CameraDevice contains formats that are not supported by CamcorderProfile

What's happening?
When the video resolution is too high, recording does not work unless I use the H.265 codec.
Is it possible to know when to use the H.265 codec?
For example:

working with h264/h265: {"autoFocusSystem": "contrast-detection", "fieldOfView": 78.63484214515682, "maxExposure": 8, "maxFps": 30, "maxISO": 6400, "maxZoom": 10, "minExposure": -8, "minFps": 1, "minISO": 50, "photoHeight": 2736, "photoWidth": 3648, "pixelFormats": ["yuv", "native"], "supportsDepthCapture": true, "supportsPhotoHdr": false, "supportsVideoHdr": false, "videoHeight": 2056, "videoStabilizationModes": ["off", "standard", "cinematic-extended"], "videoWidth": 3648}
not working with h264 (/ working with h265): {"autoFocusSystem": "contrast-detection", "fieldOfView": 78.63484214515682, "maxExposure": 8, "maxFps": 30, "maxISO": 6400, "maxZoom": 10, "minExposure": -8, "minFps": 1, "minISO": 50, "photoHeight": 2736, "photoWidth": 3648, "pixelFormats": ["yuv", "native"], "supportsDepthCapture": true, "supportsPhotoHdr": false, "supportsVideoHdr": false, "videoHeight": 2736, "videoStabilizationModes": ["off", "standard", "cinematic-extended"], "videoWidth": 3648}

Reproduceable Code
const devices = Camera.getAvailableCameraDevices();
const device = devices.find((d) => d.position === 'back');
if (!device) {
    return;
}
const format = getCameraFormat(device, [
    { videoResolution: 'max' },
]);

// ...

return (
    <View style={s.container}>
        <Camera
            ref={this.cameraRef}
            style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }}
            device={device}
            format={format}
            isActive={true}
            video={true}
            audio={true}
            resizeMode='contain'
        />
    </View>
);

Relevant log output
{"cause": {"message": "prepare failed.", "stacktrace": "java.io.IOException: prepare failed.
	at android.media.MediaRecorder._prepare(Native Method)
	at android.media.MediaRecorder.prepare(MediaRecorder.java:1107)
	at com.mrousavy.camera.core.RecordingSession.start(RecordingSession.kt:91)
	at com.mrousavy.camera.core.CameraSession.startRecording(CameraSession.kt:546)
	at com.mrousavy.camera.CameraView_RecordVideoKt.startRecording(CameraView+RecordVideo.kt:56)
	at com.mrousavy.camera.CameraViewModule$startRecording$1.invokeSuspend(CameraViewModule.kt:90)
	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
	at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)
"}, "code": "capture/unknown", "message": "An unknown error occurred while trying to start a video recording! prepare failed.", "userInfo": null}

Camera Device
{
  "sensorOrientation": "landscape-right",
  "hardwareLevel": "limited",
  "maxZoom": 10,
  "minZoom": 1,
  "supportsLowLightBoost": false,
  "neutralZoom": 1,
  "physicalDevices": [
    "wide-angle-camera",
    "ultra-wide-angle-camera",
    "telephoto-camera"
  ],
  "supportsFocus": true,
  "supportsRawCapture": false,
  "isMultiCam": true,
  "name": "BACK (0)",
  "hasFlash": true,
  "hasTorch": true,
  "position": "back",
  "id": "0"
}

Device
HUAWEI P30 (ELE-L29) with Android 10
VisionCamera Version
3.6.10
Can you reproduce this issue in the VisionCamera Example app?
I didn't try (⚠ your issue might get ignored & closed if you don't try this)
Additional information

[ ] I am using Expo
[ ] I have enabled Frame Processors (react-native-worklets-core)
[X] I have read the Troubleshooting Guide
[X] I agree to follow this project's Code of Conduct
[X] I searched for similar issues in this repository and found none.

Interesting observation with the codec! Maybe there is a limit for the android recorder?
Have you tried using a really low bitrate?

Ohhhh, good catch!
It actually doesn't depend on the codec. My phone doesn't support bitrates higher than 80 Mbps.
Since I didn't set a default bitrate, it was taking the one generated by getDefaultBitRate.
  private fun getDefaultBitRate(): Double {
    var baseBitRate = when (size.width * size.height) {
      in 0..640 * 480 -> 2.0
      in 640 * 480..1280 * 720 -> 5.0
      in 1280 * 720..1920 * 1080 -> 10.0
      in 1920 * 1080..3840 * 2160 -> 30.0
      in 3840 * 2160..7680 * 4320 -> 100.0
      else -> 100.0
    }
    baseBitRate = baseBitRate / 30.0 * (fps ?: 30).toDouble()
    if (this.codec == VideoCodec.H265) baseBitRate *= 0.8
    return baseBitRate
  }

The video resolution of the format i used is 3648 x 2736.
So, I had 100 Mbps in h.264, and 80 Mbps in h.265. That's why it worked in h.265 ^^
I tested 80 Mbps in h.264, and it works and 81 Mbps in h.265 doesn't work.
From what I've seen, it may be possible to retrieve it from CamcorderProfile. I need to check that.
Thank you very much for your help :)

Ohh, interesting! I'll try to fix the getDefaultBitRate() method by using CamcorderProfile instead of computing it on my own then!

Hey @j-jonathan! I spent some time investigating this and debugging the available CamcorderProfiles.
I created this PR: https://github.com/mrousavy/react-native-vision-camera/pull/2216 which does two things:

It automatically chooses the best/recommended video bit-rate for the given resolution, fps, hdr and codec settings on Android instead of manually calculating it.
It up or downscales the computed bit-rate using a multiplier if options like 'low' (* 0.8) or 'high' (* 1.2) are passed.

Can you please try this PR and see if that now fixes the problem for you?
Would be amazing if this now records where it previously failed to record. Thanks for your help! ❤

And I also added some more options: https://github.com/mrousavy/react-native-vision-camera/pull/2225

I just tested. Unfortunately, I encountered another error.
{"cause": {"message": "Error retrieving camcorder profile params", "stacktrace": "java.lang.RuntimeException: Error retrieving camcorder profile params
	at android.media.CamcorderProfile.native_get_camcorder_profile(Native Method)
	at android.media.CamcorderProfile.get(CamcorderProfile.java:467)
	at com.mrousavy.camera.extensions.RecordingSession_getRecommendedBitRateKt.getRecommendedBitRate(RecordingSession+getRecommendedBitRate.kt:48)
	at com.mrousavy.camera.core.RecordingSession.getBitRate(RecordingSession.kt:132)
	at com.mrousavy.camera.core.RecordingSession.<init>(RecordingSession.kt:37)
	at com.mrousavy.camera.core.CameraSession.startRecording(CameraSession.kt:545)
	at com.mrousavy.camera.CameraView_RecordVideoKt.startRecording(CameraView+RecordVideo.kt:44)
	at com.mrousavy.camera.CameraViewModule$startRecording$1.invokeSuspend(CameraViewModule.kt:91)
	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
	at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)

This is due to the 'quality' used (returned by findClosestCamcorderProfileQuality). In my case, it returns CamcorderProfile.QUALITY_4KDCI, and my phone only supports up to CamcorderProfile.QUALITY_2160P.
If I set it to CamcorderProfile.QUALITY_2160P, it works :) and the bitrate is correct! ("Created 3648 x 2736 @ 30 FPS H264 MOV LANDSCAPE_RIGHT 40.0 Mbps RecordingSession (with audio)!")

In my case, it returns CamcorderProfile.QUALITY_4KDCI, and my phone only supports up to CamcorderProfile.QUALITY_2160P

That is very weird - your Format is 4k ({ ...other, "videoHeight": 2056, "videoWidth": 3648 }), then I guess the format is wrong? It shouldn't even be 4k...

Yup okay thanks! I guess then I should edit the getAvailableCameraDevices() function to not return sizes that don't have a CamcorderProfile.
So if your device supports a maximum CamcorderProfile of QUALITY_2160P - it does not support QUALITY_4KDCI or higher. Meaning:

QUALITY_2160P = 3840 * 2160 = 8.294.400 pixels
QUALITY_4KDCI = 4096 * 2160 = 8.847.370 pixels

Whereas your camera formats are:

3648 * 2056 = 7.500.288 pixels (that's less than QUALITY_2160P so it's fine)
3648 * 3723 = 9.980.928 pixels (that's more than QUALITY_2160P  so we can't record videos with that)

So I shouldn't even return the 3648 * 3723 format.

Actually, the format with { "videoHeight": 2736, "videoWidth": 3648 } works fine. I just checked the resolution of the recorded video, and it's correct (2736x3648), so we can keep this format.
However, for some reason, the call to CamcorderProfile.get(cameraIdInt, quality) with quality=QUALITY_4KDCI is not supported by my phone.
Maybe it's possible to call CamcorderProfile.hasProfile in the findClosestCamcorderProfileQuality to get the closest profile supported by the device 🤔

wtf, that's weird. So it says it's not supported, but actually is kinda supported? Maybe it's not supported in full bit-rate?

I am still getting error crashes. On Redmi note 112 device (android 13 )
"react-native-vision-camera":"^3.6.12",
   const startRecording = useCallback(() => {     if (cameraRef.current) {       try {         cameraRef.current.stopRecording();         cameraRef.current.startRecording({           flash: useFlash ? 'on' : 'off',           videoCodec: 'h264',           videoBitRate: 'extra-low',           onRecordingError: error => {             console.error('Recording failed!', error);             // onStoppedRecording();           },           onRecordingFinished: video => {             navigation.navigate('photo-stories', {               pathSource: video.path,               typeSource: 'video',             });           },         });       } catch (e) {         console.error('failed to start recording!', e, 'camera');       } finally {         console.log('endStartRecording');       }     }   }, [cameraRef, navigation, useFlash]);
Recording failed! {"cause": {"message": "Error retrieving camcorder profile params", "stacktrace": "java.lang.RuntimeException: Error retrieving camcorder profile params 	at android.media.CamcorderProfile.native_get_camcorder_profile(Native Method) 	at android.media.CamcorderProfile.get(CamcorderProfile.java:528)
System:
OS: macOS 13.3
CPU: (8) arm64 Apple M1
Memory: 81.53 MB / 8.00 GB
Shell: 5.9 - /bin/zsh
Binaries:
Node: 20.9.0 - /usr/local/bin/node
Yarn: 1.22.17 - /opt/homebrew/bin/yarn
npm: 10.1.0 - /opt/homebrew/bin/npm
Watchman: 2<IP_ADDRESS> - /opt/homebrew/bin/watchman
Managers:
CocoaPods: 1.12.1 - /opt/homebrew/bin/pod
SDKs:
iOS SDK:
Platforms: DriverKit 22.4, iOS 16.4, macOS 13.3, tvOS 16.4, watchOS 9.4
Android SDK: Not Found
IDEs:
Android Studio: 2021.1 AI-211.7628.21.2111.8193401
Xcode: 14.3/14E222b - /usr/bin/xcodebuild
Languages:
Java: <IP_ADDRESS> - /usr/bin/javac
npmPackages:
@react-native-community/cli: Not Found
react: Not Found
react-native: Not Found
react-native-macos: Not Found
npmGlobalPackages:
react-native: Not Found

@mrousavy  @j-jonathan  is this issue resolved . I am still getting this issue in my realme 11 pro . In ios it work fine can you please help it is really urgent
`import { View, Text,Image, Platform, KeyboardAvoidingView,Animated, NativeModules, NativeTouchEvent, Dimensions } from 'react-native'
import React ,{FC, useCallback, useEffect, useRef, useState} from 'react'
import { Modal } from 'react-native'
import { CameraRuntimeError, CameraDevice,PhotoFile, useCameraDevice, useCameraFormat, useFrameProcessor, VideoFile ,Camera,TakePhotoOptions, Point} from 'react-native-vision-camera'
import { StyleSheet } from 'react-native'
import Reanimated, { Extrapolate, interpolate, useAnimatedGestureHandler, useAnimatedProps, useSharedValue } from 'react-native-reanimated'
import { TouchableOpacity } from 'react-native'
import Colors from '../constant/colors'
import CustomInput from './customInput'
import PhotoEditor from 'react-native-photo-editor'
import CustomText from './customText'
import { commonStyle } from '../constant/commonStyle'
import RNFS from 'react-native-fs';
import Entypo from 'react-native-vector-icons/Entypo'
import Ionicons from 'react-native-vector-icons/Ionicons'
import uuid from 'react-native-uuid';
import Feather from 'react-native-vector-icons/Feather'
import SimpleBtn from './simpleBtn'
import GradientBtn from './gradientBtn'
import { uploadStory } from '../services/api'
import { usePreferredCameraDevice } from '../assets/hooks/usePreferredCameraDevice'
import { CaptureButton } from './CaptureButton'
import Video from 'react-native-video'
import { showEditor } from 'react-native-video-trim';
import { NativeEventEmitter } from 'react-native'
// import VideoTrimmer from './videoTrimer'
// import Animated from 'react-native-reanimated'
// const VideoTrim = NativeModules.VideoTrim
const { RNPhotoEditor } = NativeModules
interface CameraComponentProps {
navigation?:any,
setShowCamera:(param:boolean)=>void
showCamera:boolean
}
const { width, height, scale } = Dimensions.get('window');
const screenAspectRatio = height-150 / width
const generateRandomImagePath = (type?:'photo' | 'video' | '') => {
const randomString =(uuid.v4()).toString();
if(type == 'video'){
return ${RNFS.DocumentDirectoryPath}/${randomString}.mov;
}else{
return ${RNFS.DocumentDirectoryPath}/${randomString}.jpg;
}
};
const ReanimatedCamera = Reanimated.createAnimatedComponent(Camera)
Reanimated.addWhitelistedNativeProps({
zoom: true,
})
const CameraComponent:FC = ({navigation,setShowCamera,showCamera}) => {
const [capturedImage,setCapturedImage] = useState(null)
const camera =useRef(null)
const [VedioEditing,SetVideoEditing] = useState(false)
const [vedioTime,setVedioTime] = useState()
const [cameraPosition, setCameraPosition] = useState<'front' | 'back'>('back')
// const device = useCameraDevice(cameraPosition)
const [isCameraInitialized, setIsCameraInitialized] = useState(false)
const [mediaType,setMediaType] =useState<'photo' | 'video' |''>('')
const [filePath, setFilePath] = useState(null);
const [editedImagePath, setEditedImagePath] = useState(generateRandomImagePath());
const zoom = useSharedValue(0)
const [camLocation,setCamLocation] = useState()
const [flashOn,setFlashon]=useState<true | false>(false)
const [mode, setMode] = useState('picture');
const imageSlideAnimation = useRef(new Animated.Value(0)).current;
const videoSlideAnimation = useRef(new Animated.Value(0)).current;
const isPressingButton = useSharedValue(false)
// const device = devices.back
const [preferredDevice] = usePreferredCameraDevice()
let device = useCameraDevice(cameraPosition)
if (preferredDevice != null && preferredDevice.position === cameraPosition) {
// override default device with the one selected by the user in settings
device = preferredDevice
}
const onFlipCameraPressed = useCallback(() => {
setCameraPosition((p) => (p === 'back' ? 'front' : 'back'))
}, [])
const minZoom = device?.minZoom ?? 1
const maxZoom = Math.min(device?.maxZoom ?? 1, 10)
const format = useCameraFormat(device, [
    // { fps: targetFps },
    { videoAspectRatio: screenAspectRatio },
    { videoResolution: {width, height:height-150} },
    { photoAspectRatio: screenAspectRatio },
    // { photoResolution: 'max' },
])

useEffect(() => {
    const imageTargetValue = mode === 'picture' ? 0 : 1;
    const videoTargetValue = mode === 'video' ? 0 : 1;

    // Animate the text position when mode changes
    Animated.parallel([
    Animated.timing(imageSlideAnimation, {
        toValue: imageTargetValue,
        duration: 300,
        useNativeDriver: false,
    }),
    Animated.timing(videoSlideAnimation, {
        toValue: videoTargetValue,
        duration: 300,
        useNativeDriver: false,
    }),
    ]).start();
    console.log(mode)
}, [mode]);

const imageStyle = {
    margin: 10,
    color: 'blue',
    left: imageSlideAnimation.interpolate({
    inputRange: [0, 1],
    outputRange: ['50%', '0%'],
    }),
};

const videoStyle = {
    margin: 10,
    color: 'blue',
    left: videoSlideAnimation.interpolate({
    inputRange: [0, 1],
    outputRange: ['0%', '50%'],
    }),
};

useEffect(() => {
    const eventEmitter = new NativeEventEmitter(NativeModules.VideoTrim);
    const subscription = eventEmitter.addListener('VideoTrim', (event) => {
        switch (event.name) {
            case 'onShow': {
                console.log('onShowListener', event);
                SetVideoEditing(true)
                break;
            }
            case 'onHide': {
                console.log('onHide', event);
                SetVideoEditing(false)
                break;
            }
            case 'onStartTrimming': {
                console.log('onStartTrimming', event);
                // setEditedImagePath(event.outputPath)

                break;
            }
            case 'onFinishTrimming': {
                console.log('onFinishTrimming', event);
                const newPath =generateRandomImagePath('video')
                setEditedImagePath(newPath);
                RNFS.copyFile( event.outputPath, newPath)
                setCapturedImage({ ...capturedImage,uri:`file://${newPath}` , path: `file://${newPath}` });
                // setCapturedImage((state:any)=>({...state,uri: event.outputPath}))
                break;
            }
            case 'onCancelTrimming': {
                console.log('onCancelTrimming', event);
                break;
            }
            case 'onError': {
                console.log('onError', event);
                break;
            }
        }
    });

    return () => {
        subscription.remove();
    };
}, []);

const EditVedio = async(videoPath:string)=>{
    console.log('EditVedio')

    const path = await showEditor(videoPath,{
        maxDuration:30,
        saveToPhoto:false
      })

}

const touchII = async (event: NativeTouchEvent) => {
    let point: Point = {
        x: Math.round(event.pageX - camLocation.x),
        y: Math.round(event.pageY - camLocation.y),
    };
    await camera?.current?.focus(point)
};

const onPress = ()=>{
    // const editedImagePath = Math?.random();
    // const editedImagePath1 =
    //   'file:///storage/emulated/0/Android/data/com.hotspotmeet/files/Pictures/' +
    //   editedImagePath +
    //   '.jpg';
    // PhotoEditor.Edit({

    //     path:capturedImage.path,
    //     // hiddenControls:[ 'save','share'],
    //     onDone:(path)=>{
    //         setCapturedImage({...capturedImage,uri:editedImagePath1})
    //         // setCapturedImage
    //         console.log(`patthhhh`,path,capturedImage)
    //         RNFS.copyFile(path, editedImagePath1);
    //     },
    //     onCancel:(path)=>{
    //         console.log('path',path)
    //     },

    // });
    // RNPhotoEditor.Edit(
    //     {path:'file://' +capturedImage},
    //     (path)=>{
    //         setCapturedImage(path)
    //         console.log('path',path)
    //     },
    //     (path)=>{
    //         console.log('path',path)
    //     },

    // )
    PhotoEditor.Edit({
        hiddenControls:[ 'save','share'],
        path: capturedImage.path,
        onDone: (path) => {
            const newPath =generateRandomImagePath()
            setEditedImagePath(newPath);
            RNFS.copyFile(path, newPath)
            .then(() => {
                // const newPath = generateRandomImagePath()
                // setEditedImagePath(newPath);
                setCapturedImage({ ...capturedImage, uri: `file://${newPath}` });
            })
            .catch((error) => {
                console.error('Error copying file:', error);
            });
        },
        onCancel: (path) => {
            console.log('Photo edit cancelled. Path:', path);
        },
    });
}

const onMediaCaptured = useCallback(
    (media: PhotoFile | VideoFile, type: 'photo' | 'video',) => {
        // console.log(`Media captured! ${JSON.stringify(media) , type}`)
        console.log('media.path',media.path)
        const newPath = generateRandomImagePath(type)
        setEditedImagePath(newPath);
        setMediaType(type)
        RNFS.copyFile(media.path, newPath)
        setCapturedImage({...media,path: `file://${newPath}`,uri: `file://${newPath}`})
        if(type == 'video'){
            EditVedio(`file://${newPath}`)
        }
    },
    [navigation],
)
// const capturePic =async ()=>{
//     setEditedImagePath(generateRandomImagePath());
//     RNFS.copyFile(photo.path, editedImagePath)
//     setCapturedImage({...photo,uri: `file://${editedImagePath}`})
// }

const uploadFile = () =>{

    let formData = new FormData();
    formData.append('stories', {
        uri: capturedImage.uri,
        name:`storyUpload.jpeg`,
        type: "image/jpeg"
    });
    console.log(formData)
    uploadStory(formData)
        .then(res=>{
            console.log(res)
        })
        .catch(err=>{
            console.log(err)
        })

}

const onInitialized = useCallback(() => {
    console.log('Camera initialized!')
    setIsCameraInitialized(true)
}, [])

const cameraAnimatedProps = useAnimatedProps(() => {
    const z = Math.max(Math.min(zoom.value, maxZoom), minZoom)
    return {
      zoom: z,
    }
}, [maxZoom, minZoom, zoom])

const setIsPressingButton = useCallback(
    (_isPressingButton: boolean) => {
      isPressingButton.value = _isPressingButton
    },
    [isPressingButton],
)
return (
    <Modal
        // transparent
        animationType="fade"
        onRequestClose={() => {
            setShowCamera(false)
            setCapturedImage(null)
        }}
        visible={showCamera}
    >
        <KeyboardAvoidingView behavior={Platform.OS =='ios'? 'padding':'' } className='flex-1'>
            {capturedImage ?
                <View
                    style={{
                        flex:1,
                        backgroundColor:Colors.white,
                        // justifyContent:'center',
                        // borderWidth:1
                    }}
                >
                     {/* {console.log(capturedImage.uri)} */}
                    <View style={{
                        // borderWidth:2,
                        backgroundColor:Colors.grey,
                        flex:1
                    }}>
                       {console.log('capturedImage',capturedImage)}
                        {mediaType === 'video' && !VedioEditing ?
                        <>
                            <Video

                                source={ capturedImage}
                                // currentTime={}
                                // controls={true}
                                style={{
                                    height:height-150,
                                    // borderWidth:2,
                                    // aspectRatio:screenAspectRatio,
                                    width:width
                                }}
                                // paused={isVideoPaused}
                                resizeMode="cover"
                                posterResizeMode="cover"
                                allowsExternalPlayback={false}
                                automaticallyWaitsToMinimizeStalling={false}
                                // disableFocus={true}
                                repeat={true}
                                useTextureView={false}
                                controls={true}
                                playWhenInactive={true}
                                ignoreSilentSwitch="ignore"
                                // onReadyForDisplay={onMediaLoadEnd}
                                // onLoad={onMediaLoad}
                                // onError={onMediaLoadError}
                            />
                            {/* <VideoTrimmer
                                videoUri={capturedImage.uri}
                            /> */}
                        </>
                            :
                            <Image
                                style={{
                                    height:height-150,
                                    // aspectRatio:screenAspectRatio,
                                    width:width
                                }}
                            // resizeMode='contain'
                            source={{uri:  capturedImage.uri}}/>
                        }
                    </View>
                    <View
                    style={{
                        height:150,
                        // borderWidth:1
                        padding:10,
                        justifyContent:'space-between',

                        paddingBottom:Platform.OS == 'ios' ? 20:10
                    }}
                    >
                        <View >
                            <CustomInput style={[commonStyle.inputStyle, { borderColor: Colors.borderColor }]} placeholder='Add caption'/>
                        </View>
                        <View className='flex-row gap-[15]' >
                            <View className='flex-1 '>
                                <SimpleBtn
                                    // onPress={() => { props?.navigation.navigate('newSubscrition')}}
                                    title={"Cancel"}
                                />
                            </View>
                            <View className='flex-1'>
                                <GradientBtn
                                    onPress={ () =>  uploadFile() }
                                    title={ "Post Stasdory" }
                                />
                            </View>
                        </View>
                    </View>
                    <View

                        style={[
                            // commonStyle.shadow,
                            {
                            position:'absolute',
                            top:Platform.OS == 'ios' ? 60 : 20,
                            right:25,
                            left:25,
                            paddingHorizontal:10,
                            borderRadius:99,
                            justifyContent:'space-between',
                            flexDirection:'row',
                        }]}
                    >

                        <TouchableOpacity
                            style={[
                                commonStyle.backshadowButton,
                                {
                                    // borderWidth:1,
                                    // backgroundColor:Colors.white
                                }
                            ]}
                            onPress={()=>setCapturedImage(null)}
                        >
                            <Entypo name='cross' color={Colors.black} size={30}/>
                        </TouchableOpacity>
                        {mediaType == 'photo' &&
                        <TouchableOpacity
                            onPress={onPress}
                            style={[
                                commonStyle.backshadowButton,
                                // commonStyle.shadow,
                                // {
                                // backgroundColor:Colors.white,
                                // paddingHorizontal:20,
                                // paddingVertical:5,
                                // borderRadius:5}
                            ]}
                        >
                             <Feather name='edit-2' size={20} />
                        </TouchableOpacity>}
                    </View>
                </View>
            :
            <>
            <View
            style={{
                flex:1
            }}>
                {device &&
                    <View
                        style={{
                            flex:1,
                            backgroundColor:Colors.white,
                            justifyContent:'center',
                        }}
                    >
                        <View
                            style={{
                                // justifyContent:'center',
                                // maxHeight:528,
                                flex:1
                            }}
                        >
                            <ReanimatedCamera
                                style={[{flex:1,width:'100%'}]}
                                orientation="portrait"
                                device={device}
                                format={format}
                                isActive={true}
                                photo={true}

                                resizeMode={'cover'}
                                video={true}
                                ref={camera}
                                // focusable={true}
                                onInitialized={onInitialized}
                                onLayout={event => {
                                    if(isCameraInitialized){
                                        const layout = event.nativeEvent.layout;
                                        setCamLocation({x: layout.x, y: layout.y});
                                    }
                                }}
                                onTouchEnd={x => device.supportsFocus && touchII(x.nativeEvent)}

                            />
                        </View>
                        <View style={{
                            // position:'',
                            justifyContent:'center',
                            // alignItems:'center',
                            // bottom:100,
                            width:"100%",
                            height:150
                        }}>
                            {/* <View style={{alignItems:'center',}}>
                                <TouchableOpacity
                                    style={[commonStyle.shadowButton,{
                                        width:50,
                                        height:50,
                                        backgroundColor:Colors.white,
                                        borderRadius:100,
                                        borderWidth:1
                                    }]}
                                    onPress={capturePic}
                                >
                                </TouchableOpacity>
                            </View> */}
                             <CaptureButton
                                style={{
                                    // position: 'absolute',
                                    alignSelf: 'center',
                                    // borderWidth:1
                                    // bottom: SAFE_AREA_PADDING.paddingBottom,
                                  }}
                                camera={camera}
                                onMediaCaptured={onMediaCaptured}
                                cameraZoom={zoom}
                                minZoom={minZoom}
                                maxZoom={maxZoom}
                                flash={flashOn ? 'on':'off'}
                                enabled={isCameraInitialized}
                                setIsPressingButton={setIsPressingButton}
                            />
                </View>
                    </View>
                }

                <View
                    style={[

                        {
                            position:'absolute',
                            top:Platform.OS == 'ios' ? 60 : 20,
                            right:25,
                            left:25,
                            paddingHorizontal:10,
                            borderRadius:99,
                            justifyContent:'space-between',
                            flexDirection:'row',
                            // borderWidth:2,
                            // borderColor:'white'
                        }]}
                >
                    <TouchableOpacity onPress={()=>setShowCamera(false)} style={ commonStyle.backshadowButton}>
                        <Entypo name='cross' color={Colors.black} size={30}/>
                    </TouchableOpacity>
                    <View>
                        <TouchableOpacity  onPress={()=>setFlashon(state=>!state)} style={[
                            commonStyle.backshadowButton
                        ]}>
                            {flashOn ?
                                <Ionicons name='flash' color={Colors.black} size={25}/>
                            :
                                <Ionicons name='flash-off' color={Colors.black} size={25}/>
                            }
                        </TouchableOpacity>
                        <TouchableOpacity  onPress={onFlipCameraPressed} style={[
                            commonStyle.backshadowButton,
                            {marginTop:20}
                        ]}>
                            <Ionicons name="camera-reverse" color={Colors.black} size={24} />
                        </TouchableOpacity>

                    </View>
                </View>
            </View>
            </>
            }
        </KeyboardAvoidingView>
    </Modal>
)

}
export default CameraComponent`
capture Button component
`    import React, { useCallback, useMemo, useRef } from 'react'
import { Dimensions, StyleSheet, TouchableOpacity, View, ViewProps } from 'react-native'
import {
PanGestureHandler,
PanGestureHandlerGestureEvent,
State,
TapGestureHandler,
TapGestureHandlerStateChangeEvent,
} from 'react-native-gesture-handler'
import Reanimated, {
cancelAnimation,
Easing,
Extrapolate,
interpolate,
useAnimatedStyle,
withSpring,
withTiming,
useAnimatedGestureHandler,
useSharedValue,
withRepeat,
} from 'react-native-reanimated'
import type { Camera, PhotoFile, TakePhotoOptions, VideoFile } from 'react-native-vision-camera'
// import { CAPTURE_BUTTON_SIZE, SCREEN_HEIGHT, SCREEN_WIDTH } from './../Constants'
const { width :SCREEN_WIDTH, height:SCREEN_HEIGHT, scale } = Dimensions.get('window');
const PAN_GESTURE_HANDLER_FAIL_X = [SCREEN_WIDTH, SCREEN_HEIGHT]
const PAN_GESTURE_HANDLER_ACTIVE_Y = [-2, 2]
const CAPTURE_BUTTON_SIZE = 10
const START_RECORDING_DELAY = 200
const BORDER_WIDTH = 10 * 0.1
interface Props extends ViewProps {
camera: React.RefObject<Camera>
onMediaCaptured: (media: PhotoFile | VideoFile, type: 'photo' | 'video') => void

minZoom: number
maxZoom: number
cameraZoom: Reanimated.SharedValue<number>

flash: 'off' | 'on'

enabled: boolean

setIsPressingButton: (isPressingButton: boolean) => void
}

const _CaptureButton: React.FC = ({
camera,
onMediaCaptured,
minZoom,
maxZoom,
cameraZoom,
flash,
enabled,
setIsPressingButton,
style,
...props
}): React.ReactElement => {
const pressDownDate = useRef<Date | undefined>(undefined)
const isRecording = useRef(false)
const recordingProgress = useSharedValue(0)
const takePhotoOptions = useMemo(
() => ({
qualityPrioritization: 'speed',
flash: flash,
quality: 90,
enableShutterSound: false,
}),
[flash],
)
const isPressingButton = useSharedValue(false)
//#region Camera Capture
const takePhoto = useCallback(async () => {
    try {
    if (camera.current == null) throw new Error('Camera ref is null!')

    console.log('Taking photo...')
    const photo = await camera.current.takePhoto(takePhotoOptions)
    onMediaCaptured(photo, 'photo')
    } catch (e) {
    console.error('Failed to take photo!', e)
    }
}, [camera, onMediaCaptured, takePhotoOptions])

const onStoppedRecording = useCallback(() => {
    isRecording.current = false
    cancelAnimation(recordingProgress)
    console.log('stopped recording video!')
}, [recordingProgress])
const stopRecording = useCallback(async (diff : number) => {
    try {
    if (camera.current == null) throw new Error('Camera ref is null!')

    console.log('calling stopRecording()...')
    await camera.current.stopRecording()
    console.log('called stopRecording()!')
    } catch (e) {
    console.error('failed to stop recording!', e)
    }
}, [camera])
const startRecording = useCallback(() => {
    try {
    if (camera.current == null) throw new Error('Camera ref is null!')

    console.log('calling startRecording()...')
    camera.current.startRecording({
        flash: flash,
        onRecordingError: (error) => {
        console.error('Recording failed!', error)
        onStoppedRecording()
        },
        onRecordingFinished: (video) => {
        console.log(`Recording successfully finished! `,video)
        onMediaCaptured(video, 'video')
        onStoppedRecording()
        },
    })
    // TODO: wait until startRecording returns to actually find out if the recording has successfully started
    console.log('called startRecording()!')
    isRecording.current = true
    } catch (e) {
    console.error('failed to start recording!', e, 'camera')
    }
}, [camera, flash, onMediaCaptured, onStoppedRecording])
//#endregion

//#region Tap handler
const tapHandler = useRef<TapGestureHandler>()
const onHandlerStateChanged = useCallback(
    async ({ nativeEvent: event }: TapGestureHandlerStateChangeEvent) => {
    console.debug(`state: ${Object.keys(State)[event.state]}`)
    switch (event.state) {
        case State.BEGAN: {
        recordingProgress.value = 0
        isPressingButton.value = true
        const now = new Date()
        pressDownDate.current = now
        setTimeout(() => {
            if (pressDownDate.current === now) {
            startRecording()
            }
        }, START_RECORDING_DELAY)
        setIsPressingButton(true)
        return
        }
        case State.END:
        case State.FAILED:
        case State.CANCELLED: {
        try {
            if (pressDownDate.current == null) throw new Error('PressDownDate ref .current was null!')
            const now = new Date()
            const diff = now.getTime() - pressDownDate.current.getTime()
            pressDownDate.current = undefined
            if (diff < START_RECORDING_DELAY) {
            await takePhoto()
            } else {
            await stopRecording(diff)
            }
        } finally {
            setTimeout(() => {
            isPressingButton.value = false
            setIsPressingButton(false)
            }, 500)
        }
        return
        }
        default:
        break
    }
    },
    [isPressingButton, recordingProgress, setIsPressingButton, startRecording, stopRecording, takePhoto],
)
//#endregion
//#region Pan handler
const panHandler = useRef<PanGestureHandler>()
const onPanGestureEvent = useAnimatedGestureHandler<PanGestureHandlerGestureEvent, { offsetY?: number; startY?: number }>({
    onStart: (event, context) => {
    context.startY = event.absoluteY
    const yForFullZoom = context.startY * 0.7
    const offsetYForFullZoom = context.startY - yForFullZoom
    context.offsetY = interpolate(cameraZoom.value, [minZoom, maxZoom], [0, offsetYForFullZoom], Extrapolate.CLAMP)
    },
    onActive: (event, context) => {
    const offset = context.offsetY ?? 0
    const startY = context.startY ?? SCREEN_HEIGHT
    const yForFullZoom = startY * 0.7

    cameraZoom.value = interpolate(event.absoluteY - offset, [yForFullZoom, startY], [maxZoom, minZoom], Extrapolate.CLAMP)
    },
})
//#endregion

const shadowStyle = useAnimatedStyle(
    () => ({
    transform: [
        {
        scale: withSpring(isPressingButton.value ? 1 : 0, {
            mass: 1,
            damping: 35,
            stiffness: 300,
        }),
        },
    ],
    }),
    [isPressingButton],
)
const buttonStyle = useAnimatedStyle(() => {
    let scale: number
    if (enabled) {
    if (isPressingButton.value) {
        scale = withRepeat(
        withSpring(1, {
            stiffness: 100,
            damping: 1000,
        }),
        -1,
        true,
        )
    } else {
        scale = withSpring(0.9, {
        stiffness: 500,
        damping: 300,
        })
    }
    } else {
    scale = withSpring(0.6, {
        stiffness: 500,
        damping: 300,
    })
    }

    return {
    opacity: withTiming(enabled ? 1 : 0.3, {
        duration: 100,
        easing: Easing.linear,
    }),
    transform: [
        {
        scale: scale,
        },
    ],
    }
}, [enabled, isPressingButton])
const onPressOut = useCallback(async () => {
    try {
      if (pressDownDate.current == null) throw new Error('PressDownDate ref .current was null!');
      const now = new Date();
      const diff = now.getTime() - pressDownDate.current.getTime();
      pressDownDate.current = undefined;
      if (diff < START_RECORDING_DELAY) {
        await takePhoto();
      } else {
        await stopRecording(diff);
      }
    } finally {
      setTimeout(() => {
        isPressingButton.value = false;
        setIsPressingButton(false);
      }, 500);
    }
}, [isPressingButton, pressDownDate, setIsPressingButton, stopRecording, takePhoto]);

const onPressIn = useCallback(() => {
    recordingProgress.value = 0;
    isPressingButton.value = true;
    const now = new Date();
    pressDownDate.current = now;
    setTimeout(() => {
        console.log(pressDownDate.current , now)
      if (pressDownDate.current === now) {
        startRecording();
      }
    }, START_RECORDING_DELAY);
    setIsPressingButton(true);
  }, [isPressingButton, recordingProgress, setIsPressingButton, startRecording]);

return (
    <>
    {/* <TapGestureHandler
    enabled={enabled}
    ref={tapHandler}
    onHandlerStateChange={onHandlerStateChanged}
    shouldCancelWhenOutside={false}
    maxDurationMs={120000}
    simultaneousHandlers={panHandler}>
    <Reanimated.View {...props} style={[buttonStyle, style]}>
        <PanGestureHandler
        enabled={enabled}
        ref={panHandler}
        //   failOffsetX={PAN_GESTURE_HANDLER_FAIL_X}
        //   activeOffsetY={PAN_GESTURE_HANDLER_ACTIVE_Y}
        onGestureEvent={onPanGestureEvent}
        simultaneousHandlers={tapHandler}>
        <Reanimated.View style={styles.flex}>
            <Reanimated.View style={[styles.shadow, shadowStyle]} />
            <View style={styles.button} />
        </Reanimated.View>
        </PanGestureHandler>
        <View style={styles.button} />
    </Reanimated.View>
    </TapGestureHandler> */}
    <TouchableOpacity
        activeOpacity={1}
        onPressIn={onPressIn}
        onPressOut={onPressOut}
        // style={[buttonStyle, style]}
        >
        {/* <Reanimated.View style={[styles.shadow, shadowStyle]} /> */}
        <View style={styles.button} />
    </TouchableOpacity>
    </>
)

}
export const CaptureButton = React.memo(_CaptureButton)

const styles = StyleSheet.create({
flex: {
    flex: 1,
},
shadow: {
    position: 'absolute',
    width: CAPTURE_BUTTON_SIZE,
    height: CAPTURE_BUTTON_SIZE,
    borderRadius: CAPTURE_BUTTON_SIZE / 2,
    backgroundColor: '#e34077',
},
button: {
    width: 70,
    height: 70,
    borderRadius: 999 / 2,
    borderWidth: 1,
    borderColor: 'black',
},
})

`
package.json
{   "name": "radarapp03215",   "version": "0.0.1",   "private": true,   "scripts": {     "android": "react-native run-android",     "ios": "react-native run-ios",     "lint": "eslint .",     "start": "react-native start",     "test": "jest"   },   "dependencies": {     "@gorhom/bottom-sheet": "^4.5.1",     "@invertase/react-native-apple-authentication": "^2.2.2",     "@ptomasroos/react-native-multi-slider": "^2.2.2",     "@react-native-async-storage/async-storage": "^1.19.3",     "@react-native-clipboard/clipboard": "^1.12.1",     "@react-native-community/datetimepicker": "^7.6.1",     "@react-native-community/geolocation": "^3.1.0",     "@react-native-community/push-notification-ios": "^1.11.0",     "@react-native-firebase/app": "^18.5.0",     "@react-native-firebase/messaging": "^18.6.1",     "@react-native-google-signin/google-signin": "^10.0.1",     "@react-native-masked-view/masked-view": "^0.3.0",     "@react-navigation/bottom-tabs": "^6.5.10",     "@react-navigation/native": "^6.1.8",     "@react-navigation/stack": "^6.3.18",     "@reduxjs/toolkit": "^1.9.6",     "@rneui/base": "^0.0.0-edge.2",     "@rneui/themed": "^0.0.0-edge.2",     "@rnmapbox/maps": "^10.0.15",     "axios": "^1.5.1",     "formik": "^2.4.5",     "i": "^0.3.7",     "nativewind": "^2.0.11",     "npm": "^10.2.4",     "react": "18.2.0",     "react-input-emoji": "^5.6.5",     "react-native": "^0.72.5",     "react-native-country-codes-picker": "^2.3.4",     "react-native-draggable": "^3.3.0",     "react-native-drop-shadow": "^0.0.9",     "react-native-elements": "^3.4.3",     "react-native-fbsdk-next": "^12.1.0",     "react-native-fs": "^2.20.0",     "react-native-geolocation-service": "^5.3.1",     "react-native-gesture-handler": "^2.13.1",     "react-native-image-crop-picker": "^0.40.1",     "react-native-linear-gradient": "^2.8.3",     "react-native-mmkv": "^2.11.0",     "react-native-modal": "^13.0.1",     "react-native-otp-inputs": "^7.4.0",     "react-native-otp-textinput": "^1.1.3",     "react-native-paper": "^5.11.1",     "react-native-permissions": "^3.10.1",     "react-native-photo-editor": "^1.0.13",     "react-native-progress": "^5.0.1",     "react-native-push-notification": "^8.1.1",     "react-native-raw-bottom-sheet": "^2.2.0",     "react-native-reanimated": "^3.2.0",     "react-native-safe-area-context": "^4.7.2",     "react-native-screens": "^3.25.0",     "react-native-sectioned-multi-select": "^0.10.0",     "react-native-select-dropdown": "^3.4.0",     "react-native-splash-screen": "^3.3.0",     "react-native-story-view": "^0.0.3",     "react-native-svg": "^13.14.0",     "react-native-svg-transformer": "^1.1.0",     "react-native-swiper": "^1.6.0",     "react-native-swiper-flatlist": "^3.2.3",     "react-native-uuid": "^2.0.1",     "react-native-vector-icons": "^10.0.0",     "react-native-video": "^5.2.1",     "react-native-video-cache-control": "^1.2.2",     "react-native-video-trim": "^1.0.8",     "react-native-vision-camera": "^3.6.13",     "react-redux": "^8.1.2",     "redux": "^4.2.1",     "rn-fetch-blob": "^0.12.0",     "socket.io-client": "^4.7.2",     "tailwindcss": "3.3.2",     "yup": "^1.3.2"   },   "devDependencies": {     "@babel/core": "^7.20.0",     "@babel/preset-env": "^7.20.0",     "@babel/runtime": "^7.20.0",     "@react-native/eslint-config": "^0.72.2",     "@react-native/metro-config": "^0.72.11",     "@tsconfig/react-native": "^3.0.0",     "@types/react": "^18.0.24",     "@types/react-native-vector-icons": "^6.4.15",     "@types/react-native-video": "^5.0.16",     "@types/react-test-renderer": "^18.0.0",     "babel-jest": "^29.2.1",     "eslint": "^8.19.0",     "jest": "^29.2.1",     "metro-react-native-babel-preset": "0.76.8",     "prettier": "^2.4.1",     "react-test-renderer": "18.2.0",     "typescript": "4.8.4"   },   "engines": {     "node": ">=16"   } }

We are stuck due to this issue. Would a temporary downgrade to a previous version be a viable solution to ensure functionality? I upgraded from v2 to v3 due to iPhone 15 crash

@ZakirBangash
Use such settings with low resolution and frame rate, it will work:
const device = useCameraDevice('back');
const format = useCameraFormat(device, [
{ videoResolution: { width: 1280, height: 720 } },
{ fps: 30 }
])

@ZakirBangash
Use such settings with low resolution and frame rate, it will work:
const device = useCameraDevice('back');
const format = useCameraFormat(device, [ { videoResolution: { width: 1280, height: 720 } }, { fps: 30 } ])

@ZakirBangash  Also set pixelFormat: 'native' and you are good to go.

Thank you so much guys  💖
this suggested format works , but only works on android
so I only enable the format for Android then

@ZakirBangash
Use such settings with low resolution and frame rate, it will work:
const device = useCameraDevice('back');
const format = useCameraFormat(device, [ { videoResolution: { width: 1280, height: 720 } }, { fps: 30 } ])

Any news? Here this solution did not work.

@rodrigodmpa I installed the latest version of the library and it started working.

@rodrigodmpa
Has this issue been resolved on your end? I also encountered the same problem here. And my version is already the latest 3.6.17.
"react-native-vision-camera": "^3.6.17"
"react": "18.2.0",
"react-native": "0.72.7",
Galaxy S21  SM-G9910
andriod 13

^ Same here. We're at the latest version and still getting this error

Also seeing this bug on VisionCamera 3.7.0 released yesterday

Same problem here. I patched my local copy to only recommend the closest profile supported by my phone and that seemed to resolve my issue. Here is the version I'm using locally:
`
private fun findClosestCamcorderProfileQuality(resolution: Size): Int {
//First we need to make sure that any profiles we use are supported by this camera:
val allowedProfiles = (CamcorderProfile.QUALITY_QCIF..CamcorderProfile.QUALITY_8KUHD).filter { profile -> CamcorderProfile.hasProfile(profile)}
// Iterate through all available CamcorderProfiles and find the one that matches the closest
val targetResolution = resolution.width * resolution.height
val closestProfile = allowedProfiles.minBy { profile ->
val currentResolution = getResolutionForCamcorderProfileQuality(profile)
return@minBy abs(currentResolution - targetResolution)
}
return closestProfile
}
`

I get this bug on 3.7.1 for OnePlus

Would've been great if you could've created a PR for this.
Anyways, I created a PR to fix this issue: #2389

Would've been great if you could've created a PR for this.
Anyways, I created a PR to fix this issue: #2389

I have other priorities that are higher than working on contributing back to this project. I did plan on coming back to do a PR once my app issues were resolved. As a common courtesy I added a comment because I found something that seemed to work for me that wasn't thoroughly tested (and I needed to get my production app fixed that had issues with this and other libraries after IOS/Android updates). I'm also not familiar with the API this library was using, I just know how to run a debugger to set a break point on the error and to try some real-time changes to see if I can resolve the issue.
If you want to flame me for not creating a PR, feel free if that makes you feel better. Just know that responding to people in that way will make them less inclined to suggest a solution going forward.

I have other priorities that are higher than working on contributing back to this project. I did plan on coming back to do a PR once my app issues were resolved. As a common courtesy I added a comment because I found something that seemed to work for me that wasn't thoroughly tested (and I needed to get my production app fixed that had issues with this and other libraries after IOS/Android updates). I'm also not familiar with the API this library was using, I just know how to run a debugger to set a break point on the error and to try some real-time changes to see if I can resolve the issue.
If you want to flame me for not creating a PR, feel free if that makes you feel better. Just know that responding to people in that way will make them less inclined to suggest a solution going forward.

wtf? lol
It's always the same - someone creates an issue, wants it fixed "asap" because it hurts their business, then someone posts a local patch in the comments, and the issue goes stale.
If you use open-source you are using something someone in the community has put hundreds or thousands of hours blood and sweat into, and then offered it to the public/you for free. To keep that project alive and working for the future you can either sponsor/support the devs/maintainers, or contribute back in some way shape or form - this would've been an ideal example.

I have other priorities that are higher than working on contributing back to this project.

I have other priorities too than to help other people fix issues for their business.

If you want to flame me for not creating a PR, feel free if that makes you feel better. Just know that responding to people in that way will make them less inclined to suggest a solution going forward.

lmao, I simply said "Would've been great ....". If you get hurt over such a suggestion that's not my fault.
Doesn't matter anyways, but I think the PR would've taken 2 minutes longer than writing that comment.
I understand that time is valuable, and I understand that you are not required to create a PR, but still - it would've been great.
Anyways, issue is now resolved since that PR is merged, that's all that matters.


camera opening with bug for iOS 16 and 17

I found a bug when opening the code reader on iPhone, specifically iOS 16.6.1 and 17.0.3. When opening, the screen is divided into half with the camera open and the other half with a black stripe.
[✓] Flutter (Channel stable, 3.13.6, on Ubuntu 22.04.3 LTS 6.2.0-35-generic, locale pt_BR.UTF-8)
    • Flutter version 3.13.6 on channel stable at /home/rene/snap/flutter/common/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision ead455963c (4 weeks ago), 2023-09-26 18:28:17 -0700
    • Engine revision a794cf2681
    • Dart version 3.1.3
    • DevTools version 2.25.0

[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
    • Android SDK at /home/rene/Android/Sdk
    • Platform android-34, build-tools 34.0.0
    • Java binary at: /snap/android-studio/128/android-studio/jbr/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b829.9-10027231)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • Chrome at google-chrome

[✓] Linux toolchain - develop for Linux desktop
    • clang version 10.0.0-4ubuntu1
    • cmake version 3.16.3
    • ninja version 1.10.0
    • pkg-config version 0.29.1

[✓] Android Studio (version 2022.3)
    • Android Studio at /snap/android-studio/128/android-studio
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b829.9-10027231)

[✓] VS Code (version unknown)
    • VS Code at /snap/code/current
    • Flutter extension version 3.74.0
    ✗ Unable to determine VS Code version.

[✓] Connected device (3 available)
    • sdk gphone x86 64 (mobile) • emulator-5554 • android-x64    • Android 13 (API 33) (emulator)
    • Linux (desktop)            • linux         • linux-x64      • Ubuntu 22.04.3 LTS 6.2.0-35-generic
    • Chrome (web)               • chrome        • web-javascript • Google Chrome 118.0.5993.70

[✓] Network resources
    • All expected network resources are available.

• No issues found!

Hi @renehw ! Can you check that the last modifications fix your bug ? It actually can't dynamically set the orientation, but you can manage this directly from your widget which implements BarcodeScannerWidget by setting the orientation parameter.

Hello!
I will update and test. I'll get back to you as soon as I finish the tests, but I believe everything is ok. Thanks!

Hello @Verbruik !
I ran the tests again and the problem still persists.

I'm sorry, I hadn't paid attention to the message, so I ended up not implementing the new parameter. I'll make the adjustment and test again.

Hello @renehw !
Did you test with the new parameter ?

Hello @Verbruik , I used the parameter you mentioned "orientation", but the problem still occurs.

Ok, just to precise, the new parameter "orientation" doesn't manage the orientation dynamically, it's an initialization param which set the orientation of the camera when the view is created. I'll certainly add the possibility to track the orientation and set it dynamically later but right now i'm out of time for that :sweat_smile:
Can you ensure me that the orientation is not set when the view is created ?

I was using the following code in the initState of the screen that renders the camera:
@override
   void initState() {
     SystemChrome.setPreferredOrientations([
       DeviceOrientation.landscapeLeft,
       DeviceOrientation.landscapeRight,
     ]);

     super.initState();
   }

Hi ! I'm currently working on the plugin and will check this asap. Sorry for the waiting :sweat_smile:

No problem, if you need more details you can ask me.
Perhaps information that was not clear in my last message, but the code snippet I sent causes the screen to be automatically rotated when starting the screen where the camera widget is called. More precisely, before the camera widget is initialized.

Hello !
I ran the example app and test with a forced orientation as you suggested and everything run fine with my two devices for testing, can you send me an example app which reproduce the bug ?
[✓] Connected device (3 available)
• Mathieu's iPhone (mobile) • 0f2eb882713fb79a7a0cd535e5f62f586d7468af • ios            • iOS 15.4.1 19E258
[✓] Connected device (3 available)
• Mathieu’s iPhone (mobile) • 00008101-0015292922FA001E • ios            • iOS 16.6.1 20G81

Hi!
This is the code I use in my app
class LeitorCodigo extends StatefulWidget {
  const LeitorCodigo({super.key});

  @override
  State<LeitorCodigo> createState() => _LeitorCodigoState();
}

class _LeitorCodigoState extends State<LeitorCodigo> {
  bool withOverlay = true;
  bool toggleFlash = false;

  @override
  void initState() {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);

    super.initState();
  }

  @override
  void dispose() {
    BarcodeScanner.stopScanner();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0.0,
        leading: IconButton(
          icon: const Icon(
            Icons.close,
            color: Colors.white,
          ),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        actions: [
          IconButton(
            icon: Icon(
              toggleFlash == true ? Icons.flash_on : Icons.flash_off,
              color: Colors.white,
            ),
            tooltip: 'Flash',
            onPressed: () async {
              setState(() {
                toggleFlash = !toggleFlash;
              });
              await BarcodeScanner.toggleFlashlight();
            },
          ),
        ],
      ),
      body: Builder(
        builder: (context) {
          return SmartlookTrackingWidget(
            isSensitive: true,
            child: Stack(
              children: [
                BarcodeScannerWidget(
                  orientation: CameraOrientation.landscapeLeft,
                  startScanning: true,
                  stopScanOnBarcodeDetected: true,
                  onBarcodeDetected: (barcode) {
                    log('leitura realizada');
                    Navigator.pop(context, barcode.value);
                  },
                  onError: (error) {
                    log('Erro na leitura');
                  },
                ),
                Align(alignment: Alignment.center, child: Divider(color: Colors.red[400], thickness: 0.8)),
                ColorFiltered(
                  colorFilter: ColorFilter.mode(
                    Colors.black.withOpacity(0.4),
                    BlendMode.srcOut,
                  ),
                  child: Stack(
                    children: [
                      Container(
                        decoration: const BoxDecoration(
                          color: Colors.black,
                          backgroundBlendMode: BlendMode.dstOut,
                        ),
                      ),
                      Center(
                        child: AnimatedContainer(
                          width: MediaQuery.sizeOf(context).width * 1,
                          height: MediaQuery.sizeOf(context).height * 0.55,
                          color: Colors.white,
                          margin: const EdgeInsets.only(top: 10.0),
                          duration: const Duration(milliseconds: 150),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}

Hi !
Thanks to your code I found where is the problem and I'm happy to say that the plugin works as it should :-)
Because you set the SystemChrome.orientation value before this screen, the async call to setPreferredOrientations to landscape is not over when the BarcodeScannerPlugin is intialized and it takes the value of the screen in portrait mode, you can check that the switch is over before initialize the Scanner and it works well !
Add a startScanner variable and set it when the orientation is set, I'm not 100% sure that's the proper way to do it, but it still work anyway... 😅

class _LeitorCodigoState extends State<LeitorCodigo> {
  bool withOverlay = true;
  bool toggleFlash = false;

  bool startScanner = false;

  @override
  void initState() {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);

    super.initState();
  }

  @override
  void dispose() {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    BarcodeScanner.stopScanner();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    debugPrint('################## ${MediaQuery.sizeOf(context).width}');
    if (!startScanner && MediaQuery.sizeOf(context).width > MediaQuery.sizeOf(context).height) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        debugPrint('####################### start scanner !!!!!!');
        if (context.mounted) setState(() => startScanner = true);
      });
    }
    return Scaffold(
      backgroundColor: Colors.black,
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0.0,
        leading: IconButton(
          icon: const Icon(
            Icons.close,
            color: Colors.white,
          ),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        actions: [
          IconButton(
            icon: Icon(
              toggleFlash == true ? Icons.flash_on : Icons.flash_off,
              color: Colors.white,
            ),
            tooltip: 'Flash',
            onPressed: () async {
              setState(() {
                toggleFlash = !toggleFlash;
              });
              await BarcodeScanner.toggleFlashlight();
            },
          ),
        ],
      ),
      body: Builder(
        builder: (context) {
          return Stack(
            children: [
              !startScanner ? Container() : BarcodeScannerWidget(
                orientation: CameraOrientation.landscapeLeft,
                startScanning: true,
                stopScanOnBarcodeDetected: true,
                onBarcodeDetected: (barcode) {
                  print('leitura realizada');
                  Navigator.pop(context, barcode.value);
                },
                onError: (error) {
                  print('Erro na leitura');
                },
              ),
              Align(alignment: Alignment.center, child: Divider(color: Colors.red[400], thickness: 0.8)),
              ColorFiltered(
                colorFilter: ColorFilter.mode(
                  Colors.black.withOpacity(0.4),
                  BlendMode.srcOut,
                ),
                child: Stack(
                  children: [
                    Container(
                      decoration: const BoxDecoration(
                        color: Colors.black,
                        backgroundBlendMode: BlendMode.dstOut,
                      ),
                    ),
                    Center(
                      child: AnimatedContainer(
                        width: MediaQuery.sizeOf(context).width * 1,
                        height: MediaQuery.sizeOf(context).height * 0.55,
                        color: Colors.white,
                        margin: const EdgeInsets.only(top: 10.0),
                        duration: const Duration(milliseconds: 150),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}

Hello @Verbruik , thank you for your help, I suspected it could be this, but as it was working fine on Android I expected it to be something from the package, and unfortunately as I don't have a physical iOS device, I wasn't able to test whether it could be this delay situation, thanks for the clarification, I will try to provide a device to perform the adjustment.
Thanks again, and I appreciate the package, I noticed that it provides better performance than others due to the use of recent SDKs, thank you and great work!!!

Hello guys,
For a side-note, if you depend on a future to build your widget, you should consider the FutureBuilder which will handle this specific case. :wink:
class _LeitorCodigoState extends State<LeitorCodigo> {
  // Calls the future (either as in the field initialization as here or in initState)
  final Future<void> _orientationFuture =  SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<Void>(
      future: _orientationFuture,
      builder: (BuildContext context, AsyncSnapshot<void> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          // The future has completed.
        } else {
          // Future not complete yet
        }
    },
    );
  }
}

A new problem has been identified, it appears that iOS now does not respect the guidance.
The following image shows the phone in portrait mode, but the camera is in landscape mode, the image being captured is also in portrait mode, and not as in the capture. Strangely what I did was remove the code orientation: CameraOrientation.landscapeLeft, from the BarcodeScannerWidget.
Some help?
my initState and dispose are like this:
@override
   void initState() {
     SystemChrome.setPreferredOrientations([
       DeviceOrientation.landscapeLeft,
       DeviceOrientation.landscapeRight,
     ]);

     super.initState();
   }

   @override
   void dispose() {
     SystemChrome.setPreferredOrientations([
       DeviceOrientation.portraitUp,
       DeviceOrientation.portraitDown,
     ]);
     BarcodeScanner.stopScanner();
     super.dispose();
   }

Hello!
Any solution?

Hello !
I think what you pointed as a new problem is the desired behavior. I'm agree that it's not the best solution, and it will be fixed later, but ATM the orientation is not set dynamically on iOS native side, so you must set the orientation for BarcodeScannerWidget if you want to change the camera orientation.
Does this answer your question ? :sweat_smile:

Hello
This BarcodeScannerWidget orientation would be orientation: CameraOrientation.landscapeLeft,. The parameter you added some time ago?
If this is the case, I've already added it, and this causes another bug where when the camera is opened, the image is rendered upside down.

Hi !
I'm sorry that it's taking so long but I'm quite busy for the moment :sweat:
Be sure that I don't forget you and will fix this asap !

Hi @renehw !

This BarcodeScannerWidget orientation would be orientation: CameraOrientation.landscapeLeft,. The parameter you added some time ago?
If this is the case, I've already added it, and this causes another bug where when the camera is opened, the image is rendered upside down.

I think there is a confusion between landscapeLeft and landscapeRight, if the screen is upside down it's probably because you try to set the orientation to the wrong one. The problem here is that Flutter doesn't given a proper way to get the device orientation (left or right), so there is a couple of solutions for you :

Change the values given to setPreferredOrientations to the only (left or right) landscape mode you want to support
Use a plugin which detects the device orientation such as NativeDeviceOrientation

I surely implement a detection of the orientation later on the plugin but right now I don't have time for that. If you are determinate and have a little bit of time to share with us, feel free to create a new MR with the code which detect the screen orientation 😄
Thanks for the report, if you have and other issue don't hesitate to create a new issue or reopen this one if the problem still with those suggestions 😉


Calibration design issue

Thanks for the reply,

In pattern calibration, if the pattern is too far from the camera, the calibration will not work effectively.
I have observed that for an image to be detected, more than 80% of the frame should be occupied by the pattern. If it’s less, detection fails.

I have added an example of a patten below, that might failed in scenario.

what I have observed, that if you crop a image, in below way then I can be able to detect. That's proofs 2 point.

Originally posted by @ranjitkathiriya544 in https://github.com/facebookresearch/ocean/issues/40#issuecomment-2384135730

Hi, @ranjitkathiriya544.
Are you able to move the calibration pattern closer to the camera or print a larger calibration pattern?  Could you explain your use case?  Maybe that would help us understand the need to have a calibration pattern that takes up a small portion of the camera's field of view.
I'm not terribly familiar with Ocean's square array pattern calibration process, but I imagine that calibration pattern taking up a large portion of the field of view of the camera is desirable.  So the behavior you observed may be intentional and true to design rather than a bug.

our camera and the pattern distance is 2.6 meters, and also the maximum size of pattern A1.
With OpenCV it works fine, we are comparing the both methods.

I've been able to reproduce your problem with the large image you attached to the Issue. Unfortunately, it turns out that Ocean's calibration pattern detector is not very robust to visible edges that are not part of the pattern itself. If I start with the large image you attached to this issue and use gimp to fill the red background (and the "Scene" text) with white, the pattern is detected successfully and the code you posted in your now-closed issue seems to work, after correcting the number of columns to 3.
For a quick fix, if it's possible to put the calibration pattern in front of a quiet white background, the detector is likely to work better. We will work on making the detector more robust and hope to have an improvement for you next week.

Hi @ranjitkathiriya544,
Could you share with us the field of view and resolution figures for your camera?
And is this an RGB camera or monochrome?  And is there anything special about the lighting conditions or objects visible in the background?

Hi, @ranjitkathiriya544, commit f41f9bd401514f5c424c3f983fe547ecfad819a4 just landed. It fixes an oversight in the configuration of calibration pattern detection and your example images now work for me. If you have a chance to try it out, please let us know how it goes!

Could you share with us the field of view and resolution figures for your camera?

180 - 185 degree fov, an fisheye camera.

And is this an RGB camera or monochrome?

RGB camera.

And is there anything special about the lighting conditions or objects visible in the background?

Not much, just a normal environment with a cool light.
@ASchneiderMeta, thanks, it's works, for the image which I uploaded, but, if I twist the image by adding more corners and colours, it got failed, I am looking for an robust solution. Try this below image, this got failed.

In OpenCV if there are multiple patterns, it detect one, but doesn't failed the patten detection. In Ocean, it fails to detect any patten. Hence, we cannot use for multi patten exist.

The current calibration pattern detector depends on a strong assumption that a single coherent calibration pattern dominates the scene. Providing exactly what you're looking for is probably a larger project than we can take on right now.
In principle, one larger coherent pattern could be manually constructed from separate sheets taped to a wall in prescribed positions, but I understand that's a lot of work and might not be practical at all for you.


App authorization error - exceeded the limit of column state(CHAR(256))

Dear ging team,
I'm using PPnet (Social Network SE). I Registered the app on the Fi-LAB to accept authorization but when I tried to login I got this error:
String length exceeded.The length of string '{"client_id":"1b881b8277084b2ea1b5f1787970e44f","network":"fiware","display":"popup","callback":"_hellojs_aeziej0n","state":"","oauth_proxy":"https://auth-server.herokuapp.com/proxy","scope":["basic"],"oauth":{"version":2,"auth":"https://account.lab.fiware.org/oauth2/authorize","grant":"https://account.lab.fiware.org/oauth2/access_token"}}' exceeded the limit of column state(CHAR(256)). (HTTP 400)
It "smells" like DB error, but I'm not sure.
Thank you!
Best regards,
Vladan

Error was in PPnet URL generator. In this file https://raw.githubusercontent.com/pixelpark/ppnet/master/www/scripts/vendor-07c80755.js
line 85101 needs to be commented. I also commented few more lines in order to get the same URL request as in OAuth2 example.

Dear Vladan,
I understand you are trying to log in a user from your application using the OAuth2.0 protocol, correct me if I am wrong.
The error you are seeing is clearly a DB error, as the value for 'state' is too long. It seems that the oauth2 provider is understanding that whole json as the 'state' variable. Are you sending that on purpose? If so, please reduce it to fit the 256 char length. If this is not the case and you don't intend to save all of that information, I need more details of the request you are making to the server (endpoint, headers, body, etc.), to see if its an error on the request or on the server side.
Best regards.

Dear Garsia,
I tried to login on PPnet (Social Network SE) using KeyRock IDM. PPnet was litle bit outdated, so I got help from them and we managed to solve the problem by commenting line for "oauth_proxy".
Thank you!

Hi Vladan,
same problem as you were experiencing ....  String length exceeded...
Could you please elaborate a little bit about commenting line for "oauth_proxy" e "grant" ?
Thanks
Michele


ci: upload coverage artifact on every build

Signed-off-by: Matt Klein<EMAIL_ADDRESS>

The Circle UI seems broken and doesn't display the artifacts, but this works. Waiting to hear back from Circle support.

@danielhochman updated

Still don't see artifacts, but LGTM otherwise.

@htuch you don't see an artifacts tab here: https://circleci.com/gh/envoyproxy/envoy/1738?utm_campaign=vcs-integration-link&utm_medium=referral&utm_source=github-build-link ? I do.


terraform_docs failing on TF0.12

Hi,
This is connected to https://github.com/antonbabenko/pre-commit-terraform/pull/45 that was fixed in v1.15.0.  That version has fixed the issue i had with mktemp but i am getting a new error on this version:
$ pre-commit run terraform_docs -a
Terraform docs...........................................................Failed
hookid: terraform_docs

2019/06/19 10:45:22 At 62:1: expected: IDENT | STRING | ASSIGN | LBRACE got: RBRACE

But on another terraform config we have the error slightly differs:
$ pre-commit run terraform_docs -a
Trim Trailing Whitespace.................................................Passed
Fix End of Files.........................................................Passed
Terraform docs...........................................................Failed
hookid: terraform_docs

2019/06/19 10:48:03 At 24:11: nested object expected: LBRACE got: ASSIGN

Both of these worked previously as they have fully populated README's.  I would look into this further but not sure where the files are that the error location refers too (if you point me in the right direction i am more than happy to investigate)
Thanks,

Please try v1.16.0.
If the problem persists please provide the failing snippet of the code you are trying to process.

Ok, all autoupdated and still getting the same problems:
$ pre-commit run terraform_docs -a
Terraform docs...........................................................Failed
hookid: terraform_docs

2019/06/19 19:27:28 At 62:1: expected: IDENT | STRING | ASSIGN | LBRACE got: RBRACE

and
pre-commit run terraform_docs -a
Terraform docs...........................................................Failed
hookid: terraform_docs

2019/06/19 19:23:01 At 13:15: nested object expected: LBRACE got: ASSIGN

It is always 1 of the 2 above but as a test i created a new local tf repo with:
$ cat README.md
Test documentation

<!-- BEGINNING OF PRE-COMMIT-TERRAFORM DOCS HOOK -->

<!-- END OF PRE-COMMIT-TERRAFORM DOCS HOOK -->
$ cat variables.tf
variable "test_var" {
  description = "This is a test variable"
  default     = ""
  type        = string
}
$ cat .pre-commit-config.yaml
repos:
- repo: https://github.com/antonbabenko/pre-commit-terraform
  rev: v1.16.0
  hooks:
  - id: terraform_fmt
  - id: terraform_docs

and forced ran the pre-commit on it which worked:
$ pre-commit run -a
Terraform fmt............................................................Failed
hookid: terraform_fmt

Files were modified by this hook. Additional output:

variables.tf

Terraform docs...........................................................Failed
hookid: terraform_docs

Files were modified by this hook.
$ cat README.md
Test documentation

<!-- BEGINNING OF PRE-COMMIT-TERRAFORM DOCS HOOK -->
## Inputs

| Name | Description | Type | Default | Required |
|------|-------------|:----:|:-----:|:-----:|
| test\_var | This is a test variable | string | `""` | no |

<!-- END OF PRE-COMMIT-TERRAFORM DOCS HOOK -->

I am afraid my TF modules are quite large and i am force running this to test it as i have not changed anything that would trigger it hence doing the minimal test.  I have tried it on 4 of our repos so far and all have failed with one of the 2 errors.
As a side test though i cleaned out all output in a few of the README's (between the block identifier hooks) and re-ran and still got the same error on each.
Just a note though, these are all v0.11 TF code that i am currently in the process of converting to 0.12, not sure if this is relevant but thought it might be worth mentioning as the test setup i ran was fine.
Thanks again

Just an additional note, 1.16.0 works fine on pure TF 0.11 files.

I tried to reproduce this several times with Terraform 0.12 and latest pre-commit-terraform (v1.16.0), but can't reproduce it.
When Terraform 0.11 is used the terraform_docs hook uses previous behavior (no awk script of other magic is necessary) and it works fine.
Let's keep it open for some time in case someone experiences a similar issue as you are describing and can provide failing code.

Try with a single file (variables.tf for me) with something like this:
variable "test" {
  type        = "string"
  description = "testing"
}

With quotes around the string, you end up with two sets of quotes around it after the awk script runs ""string"". This is what terraform docs seems to fail on. If you remove the quotes from around it, everything runs ok.
This only seems to happen when the type line comes first and then another line like description comes after. If the type line comes on the second line, or is the only line between the brackets, you'll get a different exception.

Correct @gstewart,
I changed my test setup variables.tf to:
variable "test_var" {
  type        = "string"
  description = "This is a test variable"
  default     = ""
}

and now i get:
pre-commit run -a
Terraform fmt............................................................Passed
Terraform docs...........................................................Failed
hookid: terraform_docs

2019/06/25 10:12:16 At 3:15: nested object expected: LBRACE got: ASSIGN

If i take the quotes of the type it works fine.  I have removed all the quotes from my main terraform modules variable types and i still get this error:
pre-commit run -a
Terraform fmt............................................................Passed
Terraform docs...........................................................Failed
hookid: terraform_docs

2019/06/25 10:21:17 At 62:1: expected: IDENT | STRING | ASSIGN | LBRACE got: RBRACE

Yes, I could reproduce it.
@cytopia Once type is already enquoted it should not enquote it again.

Looks like it has been just fixed by @cytopia, so I have released v1.17.0.

I am afraid i am still get the same problem:
pre-commit autoupdate
Updating https://github.com/antonbabenko/pre-commit-terraform...[INFO] Initializing environment for https://github.com/antonbabenko/pre-commit-terraform.
updating v1.16.0 -> v1.17.0.

pre-commit run -a
Terraform fmt............................................................Passed
Terraform docs...........................................................Failed
hookid: terraform_docs

2019/06/25 16:35:45 At 62:1: expected: IDENT | STRING | ASSIGN | LBRACE got: RBRACE

@thenom
I've tested it for the block you pasted above:
variable "test_var" {
  type        = "string"
  description = "This is a test variable"
  default     = ""
}

Maybe there is another exception which is causing it?

@cytopia is there anyway i can get this to be more verbose to find out where it is having issues.  I cannot rules out this being my tf files but as terraform formats it and runs fine on it i can't see how.

Currently, there is no feature flag to turn on/off debugging, but you can make it easier to guess the failing line by combining all *.tf files into one and by removing everything except variable and output blocks.
Also, even if the code is not valid from terraform_fmt it should be good for terraform_docs, so you can run just it.

@thenom can you provide all variables and outputs you're using. Otherwise I won't be able to reproduce your error.

Ok, i setup a new test folder and ran git init and copied the .pre-commit-yaml from my problematic terraform.
pre-commit run -a
Terraform fmt........................................(no files to check)Skipped
Terraform docs.......................................(no files to check)Skipped

Which was to be expected.  I then copied, one by one, each of my tf files over to this folder, ran pre-commit run -a, git add * and then pre-commit run -a again for every file copied.
$ cp ../terraform.module.elasticsearch/security-groups.tf ./
$ pre-commit run -a
Terraform fmt............................................................Passed
Terraform docs...........................................................Passed
$ git add *
$ pre-commit run -a
Terraform fmt............................................................Passed
Terraform docs...........................................................Passed
$ cp ../terraform.module.elasticsearch/variables.tf ./
$ pre-commit run -a
Terraform fmt............................................................Passed
Terraform docs...........................................................Passed
$ git add *
$ pre-commit run -a
Terraform fmt............................................................Passed
Terraform docs...........................................................Passed
... and so on....

I didn't get a single problem...
I then reset this folder back to the initial git init and pre-commit-yaml.  I copied all the tf files in one, ran pre-commit run -a, git add * and then pre-commit run -a for the final time and it failed:
$ cp ../terraform.module.elasticsearch/* ./
$ pre-commit run -a
Terraform fmt........................................(no files to check)Skipped
Terraform docs.......................................(no files to check)Skipped
$ git add *
$ pre-commit run -a
Terraform fmt............................................................Passed
Terraform docs...........................................................Failed
hookid: terraform_docs

2019/06/26 16:50:29 At 62:1: expected: IDENT | STRING | ASSIGN | LBRACE got: RBRACE

I then reset and tried it with 2 files in one go and it passed.
With this setup and my single variables.tf, i don't get a problem.  I also concated all outputs into a single file and that passed.....  The plot thickens....

Just incase anyone lands here, after months of using SKIP=terraform_docs on my git commit. for this repo, i recently updated the pre-commit modules and terraform-docs it all now works fine.
$ brew upgrade terraform-docs
$ pre-commit autoupdate

(obviously on a mac but i am sure there will be other OS equivalents)

@thenom pre-commit autoupdate updated hooks to the very latest where terraform_docs has native support for Terraform 0.12.
Thanks for mentioning SKIP=...!

Hey guys I'm still getting the issue
$  pre-commit run terraform_docs -a
Terraform docs...........................................................Failed
- hook id: terraform_docs
- exit code: 1

May i know how to fix that?

git add -A to add fixes to your git staged changes.


[QUESTION] - allow unknown certificate like filezilla?

is there an option to allow unknown certificate like filezilla?
or it might be some type of TLS protocol issue im not really sure what it means.
but some FTP/FTPS servers i tried dont work in termscp but works fine in Filezilla because of this
example:

Not Work: termscp fail to connect. sometime i just hangs and gives no error message also on other servers
https://imgur.com/czIc8ZM

Works: GUI filezilla works fine after i OK the certificate
https://imgur.com/DdWl8Eg

termscp is already configured to accept invalid certificates. The problem seems unrelated. It could be helpful to share the debug log


Missing notebook

Great workflow and documentation! Would be great if you can upload the notebook too

Yes, some links in the README are broken either due to missing code or a wrong link, for example:

notebook - missing the entire ntbk folder with the notebook(s) example(s)
example reports - points to a missing reports subdirectory under the report_examples

i am unable to run the files

You can find the notebook in test-updated-prompts branch.
https://github.com/langchain-ai/report-mAIstro/blob/rlm/test-updated-prompts/ntbk/report_maistro.ipynb

@katnoria How did you find this? Is this somewhere we are supposed to know to look for notebooks?


How to use OTEL-JS samplers

I think this will work changing the env var values
https://opentelemetry.io/docs/instrumentation/js/sampling/
like this:
https://github.com/obs-nebula/gamma-ray/blob/main/traces/04/README.md#disable--enable

it works locally
@opentelemetry/instrumentation-http http instrumentation incomingRequest
Recording is off, propagating context in a non-recording span
Recording is off, propagating context in a non-recording span
Recording is off, propagating context in a non-recording span
Recording is off, propagating context in a non-recording span
@opentelemetry/instrumentation-http http instrumentation incomingRequest
Recording is off, propagating context in a non-recording span
Recording is off, propagating context in a non-recording span
Recording is off, propagating context in a non-recording span
Recording is off, propagating context in a non-recording span
items to be sent [
  Span {
    attributes: {
      'http.route': '/',
      'express.name': 'query',
      'express.type': 'middleware'
    },
    links: [],
    events: [],
    _droppedAttributesCount: 0,
    _droppedEventsCount: 0,
    _droppedLinksCount: 0,
    status: { code: 0 },
    endTime: [<PHONE_NUMBER>, 705096921 ],
    _ended: true,
    _duration: [ 0, 96921 ],
    name: 'middleware - query',
    _spanContext: {
      traceId: 'a2326fcb8718c84cab335f1c81e81b5b',
      spanId: '5b0fa0e3f4067e5d',
      traceFlags: 1,
      traceState: undefined
    },
    parentSpanId: '44a904f003037714',
    kind: 0,
    _performanceStartTime: 6102.243507999927,
    _performanceOffset: -0.846435546875,
    _startTimeProvided: false,
    startTime: [<PHONE_NUMBER>, 705000000 ],
    resource: Resource {
      _attributes: [Object],
...
...

https://github.com/obs-nebula/gamma-ray/blob/main/traces/06/README.md


test: check remove and update embedded work

PR Checklist
Please check if your PR fulfills the following requirements:

[ ] The commit message follows conventional commit format
[ ] Tests for the changes have been added (for bug fixes / features)
[ ] Docs have been added / updated (for bug fixes / features)

PR Type
What kind of change does this PR introduce?

[ ] Bugfix
[ ] Feature
[ ] Code style update (formatting, local variables)
[ ] Refactoring (no functional changes, no api changes)
[ ] Build related changes
[ ] CI related changes
[ ] Other... Please describe:

What is the current behavior?

Issue Number: #245
What is the new behavior?
Does this PR introduce a breaking change?

[ ] Yes
[ ] No

Other information

:tada: This PR is included in version 1.0.2 :tada:
The release is available on:

npm package (@latest dist-tag)
GitHub release

Your semantic-release bot :package::rocket:


fix: add gson dependency to resolve SNYK-JAVA-COMGOOGLECODEGSON-17303…

…27 and snyk file to ignore licence issues

/azp run


User accounts now get created to the correct store in multistore setup

Related issues
closes #3848
Short description and why it's useful
New user accounts were not being created into the correct store within a multistore setup, because the website_id was missing from the API call causing all accounts to be created to the default store.
Now the website_id is explicitly set in the API call.
Which environment this relates to
Check your case. In case of any doubts please read about Release Cycle

[ ] Test version (https://test.storefrontcloud.io) - this is a new feature or improvement for Vue Storefront. I've created branch from develop branch and want to merge it back to develop
[x] RC version (https://next.storefrontcloud.io) - this is a stabilisation fix for Release Candidate of Vue Storefront. I've created branch from release branch and want to merge it back to release
[ ] Stable version (https://demo.storefrontcloud.io) - this is an important fix for current stable version. I've created branch from hotfix or master branch and want to merge it back to hotfix

Upgrade Notes and Changelog

[x] No upgrade steps required (100% backward compatibility and no breaking changes)
[ ] I've updated the Upgrade notes and Changelog on how to port existing VS sites with this new feature

IMPORTANT NOTICE - Remember to update CHANGELOG.md with description of your change
Contribution and currently important rules acceptance

[x] I read and followed contribution rules

Anyway. The truth is that we've been never setting the website_id on the user :) So if this is the real cause of this issue this fix might have sense however, I'm not sure if storeView.storeId is the real website_id as single website might have multiple stores as far as I know. To be confirmed with some Magento expert. Then you can add websiteId to the default.json and in general to StoreView object.

we didn't change the way user accounts got created in the VSF 1.11 (comparing to 1.10).

This might be broken also on 1.10. One of our testers said he had been able to register correctly on 1.10, but I haven't confirmed this as I'm currently developing on top on 1.11.

I'm not sure if storeView.storeId is the real website_id as single website might have multiple stores as far as I know.

Good point. I will double check what is the correct usage of all the IDs.

What the heck. I'm not able to reproduce the issue anymore. This morning all customers got always registered to the wrong website. Not anymore.
Too many moving parts I suppose. I need to double check everything before I get back to this.

Closing for now.


Fetching the title-tag

Thanks so much for this script!
I know that it is specifically for OpenGraph and Twitter data, but since we also get description and other information that are inside the meta tags, it would only be a small addition to also get the content of the title tag. OpenGraph and Twitter data is still not used everywhere, so title is always a good fallback to have.
It would be nice to add this to have one request that fetches all interesting information.

Hey @jnsprnw thanks for the comment! We are currently implementing this (and a lot more) on #2, if you think the change is small enough, can you please open a PR just exporting this particular type?

I’ve added a PR with a very small addition.

Thanks a lot for the PR! I merged it, can you please test it? One thing I'm not sure if it's been added (but I can't test it right now) is if the correct type will be returned with title in it


STAR-27: Implements inverse byte-ordered translation

Also adds ValueAccessor support, fixes minor TupleType and DynamicCompositeType problems and adds documentation.

Unit tests are fine in the latest build, coverage and sonarcloud report is here.
Could you take another look so that I can squash and commit?

Unit tests are fine in the latest build, coverage and sonarcloud report is here.
Could you take another look so that I can squash and commit?


Improper scope requested when calling /.auth/login/twitter

When a user logins with their Twitter-account, way to much access to the twitter-account is requested by the SWA.
To Reproduce
Steps to reproduce the behavior:

Go to a link in your SWA that points to "/.auth/login/twitter"
Then the user gets a prompt from twitter to grant way to much permissions to their twitter-account, see screenshot.

(Screenshot is in Norwegian, but in summary the permissions requested in addional to "normal" ones: "Follow and de-follow users", "Post and delete tweets", "Hide, block and rapport accounts on behalf of you"++++++).
Expected behavior
A prompt from twitter where minimal permissions are presented to the user, eg. plain user-information.
Screenshots

Hi @FrankBurmo, thanks for bringing this to our attention. We have now adjusted our settings on our end for Twitter to request far fewer permissions from the user logging in. Give logging in a try and let us know if things are now sufficient for you! Thanks!