Skip to content

CameraController with ResolutionPreset.max causes Unsupported format Error #163202

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
noze12 opened this issue Feb 13, 2025 · 12 comments
Closed

CameraController with ResolutionPreset.max causes Unsupported format Error #163202

noze12 opened this issue Feb 13, 2025 · 12 comments
Labels
c: fatal crash Crashes that terminate the process c: regression It was better in the past than it is now found in release: 3.29 Found to occur in 3.29 found in release: 3.30 Found to occur in 3.30 has reproducible steps The issue has been confirmed reproducible and is ready to work on p: camera The camera plugin package flutter/packages repository. See also p: labels. platform-ios iOS applications specifically r: fixed Issue is closed as already fixed in a newer version team-ios Owned by iOS platform team

Comments

@noze12
Copy link

noze12 commented Feb 13, 2025

Steps to reproduce

  1. create new flutter project
  2. add camera dependency with flutter pub add camera
  3. copy camera example code and paste it to main.dart
  4. run on iOS device

Expected results

app starts and displays camera preview

Actual results

app crashs

in Xcode console

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[AVCaptureDevice _setActiveFormat:resetVideoZoomFactorAndMinMaxFrameDurations:sessionPreset:] Unsupported format (<FLTDefaultCaptureDeviceFormat: 0x3024dd5e0>) - use -formats to discover valid formats'
...

When I change resolutionPreset to other value, it works correctly.

Code sample

Code sample
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';

late List<CameraDescription> _cameras;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  _cameras = await availableCameras();
  runApp(const CameraApp());
}

/// CameraApp is the Main Application.
class CameraApp extends StatefulWidget {
  /// Default Constructor
  const CameraApp({super.key});

  @override
  State<CameraApp> createState() => _CameraAppState();
}

class _CameraAppState extends State<CameraApp> {
  late CameraController controller;

  @override
  void initState() {
    super.initState();
    controller = CameraController(_cameras[0], ResolutionPreset.max);
    controller.initialize().then((_) {
      if (!mounted) {
        return;
      }
      setState(() {});
    }).catchError((Object e) {
      if (e is CameraException) {
        switch (e.code) {
          case 'CameraAccessDenied':
            // Handle access errors here.
            break;
          default:
            // Handle other errors here.
            break;
        }
      }
    });
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (!controller.value.isInitialized) {
      return Container();
    }
    return MaterialApp(
      home: CameraPreview(controller),
    );
  }
}

Screenshots or Video

Screenshots / Video demonstration

[Upload media here]

Logs

Logs
[Paste your logs here]

Flutter Doctor output

Doctor output
[✓] Flutter (Channel stable, 3.29.0, on macOS 15.3 24D60 darwin-arm64, locale ja-JP) [1,311ms]
    • Flutter version 3.29.0 on channel stable at /Users/ozeki/development/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 35c388afb5 (3 days ago), 2025-02-10 12:48:41 -0800
    • Engine revision f73bfc4522
    • Dart version 3.7.0
    • DevTools version 2.42.2

[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0) [2.1s]
    • Android SDK at /Users/ozeki/Library/Android/sdk
    • Platform android-35, build-tools 34.0.0
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
      This is the JDK bundled with the latest Android Studio installation on this machine.
      To manually set the JDK path, use: `flutter config --jdk-dir="path/to/jdk"`.
    • Java version OpenJDK Runtime Environment (build 17.0.9+0-17.0.9b1087.7-11185874)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 16.2) [1,268ms]
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 16C5032a
    • CocoaPods version 1.16.2

[✓] Chrome - develop for the web [10ms]
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2023.2) [9ms]
    • Android Studio at /Applications/Android Studio.app/Contents
    • 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.9+0-17.0.9b1087.7-11185874)

[✓] VS Code (version 1.96.4) [8ms]
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.104.0

[✓] Connected device (5 available) [11.6s]
    • iPhone (mobile)                 • 00008030-000C79C93C87802E            • ios            • iOS 18.3.1 22D72
    • iPhone 16 (mobile)              • 16BB8920-44F0-4A8B-845E-10B48CEFFC76 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-18-2 (simulator)
    • macOS (desktop)                 • macos                                • darwin-arm64   • macOS 15.3 24D60 darwin-arm64
    • Mac Designed for iPad (desktop) • mac-designed-for-ipad                • darwin         • macOS 15.3 24D60 darwin-arm64
    • Chrome (web)                    • chrome                               • web-javascript • Google Chrome 133.0.6943.54

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

• No issues found!
@alexdempster44
Copy link

alexdempster44 commented Feb 13, 2025

I can confirm it happens on an iPhone 15 (iOS 18.2) and iPhone SE 2022 (18.0) too:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[AVCaptureDevice _setActiveFormat:resetVideoZoomFactorAndMinMaxFrameDurations:sessionPreset:] Unsupported format (<FLTDefaultCaptureDeviceFormat: 0x303ac57a0>) - use -formats to discover valid formats'

Switching the ResolutionPreset from max to ultraHigh seems to fix it.
It happened while I was upgrading from flutter 3.27.3 to 3.29.0, using camera package version 0.11.1.

@huycozy huycozy added the in triage Presently being triaged by the triage team label Feb 14, 2025
@huycozy
Copy link
Member

huycozy commented Feb 14, 2025

Thanks for your report. I also can reproduce this issue on iPhone 7, iOS 15.8.3

Output log
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[AVCaptureDevice _setActiveFormat:resetVideoZoomFactorAndMinMaxFrameDurations:sessionPreset:] Unsupported format (<FLTDefaultCaptureDeviceFormat: 0x2809a8070>) - use -formats to discover valid formats'
*** First throw call stack:
(0x180513c60 0x197d43ee4 0x1a3b0d07c 0x100c1cb08 0x100c149a4 0x100c12ac0 0x100c1148c 0x100c1130c 0x1801d3094 0x1801d4094 0x18017a73c 0x18017b1f4 0x180184ec8 0x1db88ce00 0x1db88c92c)
libc++abi: terminating with uncaught exception of type NSException
* thread #22, queue = 'io.flutter.camera.captureSessionQueue', stop reason = signal SIGABRT
    frame #0: 0x00000001badf7bbc libsystem_kernel.dylib`__pthread_kill + 8
libsystem_kernel.dylib`__pthread_kill:
->  0x1badf7bbc <+8>:  b.lo   0x1badf7bd8               ; <+36>
    0x1badf7bc0 <+12>: stp    x29, x30, [sp, #-0x10]!
    0x1badf7bc4 <+16>: mov    x29, sp
    0x1badf7bc8 <+20>: bl     0x1badf360c               ; cerror_nocancel
Target 0: (Runner) stopped.
Lost connection to device.

Exited.
Sample code
import 'dart:async';
import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';

Future<void> main() async {
  // Ensure that plugin services are initialized so that `availableCameras()`
  // can be called before `runApp()`
  WidgetsFlutterBinding.ensureInitialized();

  // Obtain a list of the available cameras on the device.
  final cameras = await availableCameras();

  // Get a specific camera from the list of available cameras.
  final firstCamera = cameras.first;

  runApp(
    MaterialApp(
      theme: ThemeData.dark(),
      home: TakePictureScreen(
        // Pass the appropriate camera to the TakePictureScreen widget.
        camera: firstCamera,
      ),
    ),
  );
}

// A screen that allows users to take a picture using a given camera.
class TakePictureScreen extends StatefulWidget {
  const TakePictureScreen({
    super.key,
    required this.camera,
  });

  final CameraDescription camera;

  @override
  TakePictureScreenState createState() => TakePictureScreenState();
}

class TakePictureScreenState extends State<TakePictureScreen> {
  late CameraController _controller;
  late Future<void> _initializeControllerFuture;

  @override
  void initState() {
    super.initState();
    // To display the current output from the Camera,
    // create a CameraController.
    _controller = CameraController(
      // Get a specific camera from the list of available cameras.
      widget.camera,
      // Define the resolution to use.
      ResolutionPreset.max,
    );

    // Next, initialize the controller. This returns a Future.
    _initializeControllerFuture = _controller.initialize();
  }

  @override
  void dispose() {
    // Dispose of the controller when the widget is disposed.
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Take a picture')),
      // You must wait until the controller is initialized before displaying the
      // camera preview. Use a FutureBuilder to display a loading spinner until the
      // controller has finished initializing.
      body: FutureBuilder<void>(
        future: _initializeControllerFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            // If the Future is complete, display the preview.
            return CameraPreview(_controller);
          } else {
            // Otherwise, display a loading indicator.
            return const Center(child: CircularProgressIndicator());
          }
        },
      ),
      floatingActionButton: FloatingActionButton(
        // Provide an onPressed callback.
        onPressed: () async {
          // Take the Picture in a try / catch block. If anything goes wrong,
          // catch the error.
          try {
            // Ensure that the camera is initialized.
            await _initializeControllerFuture;

            // Attempt to take a picture and get the file `image`
            // where it was saved.
            final image = await _controller.takePicture();

            if (!context.mounted) return;

            // If the picture was taken, display it on a new screen.
            await Navigator.of(context).push(
              MaterialPageRoute(
                builder: (context) => DisplayPictureScreen(
                  // Pass the automatically generated path to
                  // the DisplayPictureScreen widget.
                  imagePath: image.path,
                ),
              ),
            );
          } catch (e) {
            // If an error occurs, log the error to the console.
            print(e);
          }
        },
        child: const Icon(Icons.camera_alt),
      ),
    );
  }
}

// A widget that displays the picture taken by the user.
class DisplayPictureScreen extends StatelessWidget {
  final String imagePath;

  const DisplayPictureScreen({super.key, required this.imagePath});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Display the Picture')),
      // The image is stored as a file on the device. Use the `Image.file`
      // constructor with the given path to display the image.
      body: Image.file(File(imagePath)),
    );
  }
}
package versions
camera:
    dependency: "direct main"
    description:
      name: camera
      sha256: "413d2b34fe28496c35c69ede5b232fb9dd5ca2c3a4cb606b14efc1c7546cc8cb"
      url: "https://pub.dev"
    source: hosted
    version: "0.11.1"
  camera_avfoundation:
    dependency: transitive
    description:
      name: camera_avfoundation
      sha256: "08a5cfe9ae69887851913f0301eaf2c2198fc3ddc0e0d20b3bdd26a91306eac9"
      url: "https://pub.dev"
    source: hosted
    version: "0.9.18+6"

Flutter versions:

Channel stable, 3.29.0
Channel master, 3.30.0-1.0.pre.168

@huycozy huycozy added platform-ios iOS applications specifically p: camera The camera plugin package flutter/packages repository. See also p: labels. has reproducible steps The issue has been confirmed reproducible and is ready to work on c: fatal crash Crashes that terminate the process fyi-ecosystem For the attention of Ecosystem team team-ios Owned by iOS platform team found in release: 3.29 Found to occur in 3.29 found in release: 3.30 Found to occur in 3.30 and removed in triage Presently being triaged by the triage team labels Feb 14, 2025
@casolutions2024
Copy link

I would like to add that specifying the fps is also crashing the app. I had it set to 30 and once I removed the line, it began to work normal, as long as the ResolutionPreset was not max

@hellohuanlin
Copy link
Contributor

@noze12 which version of camera plugin are you using? if it's the latest version, can you try to revert to earlier version and see if it's a regression?

@brunosp15
Copy link

@noze12 which version of camera plugin are you using? if it's the latest version, can you try to revert to earlier version and see if it's a regression?

I was facing the same problem and regressing was not solving.

In my case the local cache of the librarie is not crashing, just when the version is created on the CI without any cache.

@noze12
Copy link
Author

noze12 commented Feb 15, 2025

@noze12 which version of camera plugin are you using? if it's the latest version, can you try to revert to earlier version and see if it's a regression?

I was initially using camera 0.10.6. After upgrading the Flutter version, this issue started occurring without changing the camera version. When I checked the differences in pubspec.lock, I noticed that the version of camera_avfoundation had changed. After reverting it to the previous version, 0.9.16, the issue no longer occurred. Therefore, I suspect that the problem lies somewhere in camera_avfoundation version 0.9.17 or later.

@masa-futa
Copy link

I was experiencing the same problem.

After reverting it to the previous version, 0.9.16, the issue no longer occurred.

As stated, there seems to be some problem with the latest version of camera_avfoundation, so I overwrote the version as follows and confirmed that it worked properly. (v0.9.18 seems to work fine as well.)
I sincerely hope that the problem will be resolved.

dependency_overrides:
  camera_avfoundation: 0.9.18

@huycozy
Copy link
Member

huycozy commented Feb 18, 2025

Marking this as a regression based on above tests. Thank @noze12, @masa-futa

@huycozy huycozy added the c: regression It was better in the past than it is now label Feb 18, 2025
@hellohuanlin
Copy link
Contributor

@noze12 can you try on v0.9.18 as described by @masa-futa , and see if the issue has been fixed? thanks

@stuartmorgan-g stuartmorgan-g added the triaged-ecosystem Triaged by Ecosystem team label Feb 18, 2025
@flutter-triage-bot flutter-triage-bot bot removed fyi-ecosystem For the attention of Ecosystem team triaged-ecosystem Triaged by Ecosystem team labels Feb 18, 2025
@noze12
Copy link
Author

noze12 commented Feb 19, 2025

@noze12 can you try on v0.9.18 as described by @masa-futa , and see if the issue has been fixed?

I confirmed.

0.9.18 -> OK
0.9.18+8(latest) -> OK !?
0.9.18+6 -> NG

It looks like this has been fixed: flutter/packages#8630

@hellohuanlin
Copy link
Contributor

Closing as the OP confirmed the regression has been fixed.

@huycozy huycozy added the r: fixed Issue is closed as already fixed in a newer version label Feb 20, 2025
Copy link

github-actions bot commented Mar 6, 2025

This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 6, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
c: fatal crash Crashes that terminate the process c: regression It was better in the past than it is now found in release: 3.29 Found to occur in 3.29 found in release: 3.30 Found to occur in 3.30 has reproducible steps The issue has been confirmed reproducible and is ready to work on p: camera The camera plugin package flutter/packages repository. See also p: labels. platform-ios iOS applications specifically r: fixed Issue is closed as already fixed in a newer version team-ios Owned by iOS platform team
Projects
None yet
Development

No branches or pull requests

8 participants