Repository: flutter
Issue: [camera]CameraException(error, No capture session available for current capture session.)
Labels: e: device-specific,platform-android,p: camera,package,P2,e: samsung,team-android,triaged-android

<!-- Thank you for using Flutter!

     If you are looking for support, please check out our documentation
     or consider asking a question on Stack Overflow:
      * https://flutter.dev/
      * https://api.flutter.dev/
      * https://stackoverflow.com/questions/tagged/flutter?sort=frequent

     If you have found a bug or if our documentation doesn't have an answer
     to what you're looking for, then fill out the template below. Please read
     our guide to filing a bug first: https://flutter.dev/docs/resources/bug-reports
-->

## Steps to Reproduce

<!-- Please include full steps to reproduce so that we can reproduce the problem. -->

1. Execute `flutter run` on the code sample.
2. Accept the camera permission.
3. Notice the enumerated cameras at the bottom of the camera screen, i.e. 0/2.
4. Press `Next Camera` until you reach the last one.
5. Notice the `Camera loading...` screen which never goes away, along with the error output in the console.


**Expected results:** <!-- what did you want to see? -->

I expected all enumerated cameras returned from `availableCameras` to work with the `CameraPreview` widget.

**Actual results:** <!-- what did you see? -->

The last camera, 2/2, which is the 2x optical zoom on the Galaxy Note 10+, did not load and instead threw a `CameraException` exception of the following kind:
```
CameraException(error, No capture session available for current capture session.)
```

<details>
<summary>Code sample</summary>

<!--
      Please create a minimal reproducible sample that shows the problem
      and attach it below between the lines with the backticks.

      To create it you can use `flutter create bug` command and update the `main.dart` file.

      Alternatively, you can use https://dartpad.dev/
      which is capable of creating and running small Flutter apps.

      Without this we will unlikely be able to progress on the issue, and because of that
      we regretfully will have to close it.
-->

```dart
import 'package:camera/camera.dart' as c;
import "package:flutter/material.dart";

late List<c.CameraDescription> _cameras;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  _cameras = (await c.availableCameras())
      .where((element) => element.lensDirection == c.CameraLensDirection.back)
      .toList();

  runApp(const App());
}

class App extends StatelessWidget {
  const App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      themeMode: ThemeMode.dark,
      darkTheme: ThemeData(
        brightness: Brightness.dark,
      ),
      home: const Scaffold(body: Camera()),
    );
  }
}

class Camera extends StatefulWidget {
  const Camera({
    Key? key,
  }) : super(key: key);

  @override
  State<Camera> createState() => _CameraState();
}

class _CameraState extends State<Camera> with WidgetsBindingObserver {
  c.CameraController? _controller;

  int _currentCamera = 0;

  int get currentCamera => _currentCamera;

  set currentCamera(int value) {
    _currentCamera = value;
    _newCameraController(value);
  }

  @override
  void initState() {
    super.initState();
    _newCameraController(currentCamera);

    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    final controller = _controller;

    if (controller != null && state == AppLifecycleState.inactive) {
      controller.dispose();

      setState(() => _controller = null);
    } else if (state == AppLifecycleState.resumed) {
      _newCameraController(currentCamera);
    }
  }

  @override
  Widget build(BuildContext context) {
    final controller = _controller;

    if (controller == null) {
      return Column(
        children: [
          const Expanded(
              child: Center(
            child: Text("Loading camera..."),
          )),
          TextButton(
              onPressed: () => currentCamera = 0,
              child: const Text("Reset Camera"))
        ],
      );
    } else {
      return Column(
        children: [
          c.CameraPreview(controller),
          Row(
            children: [
              TextButton(onPressed: prevCamera, child: const Text("Previous")),
              Expanded(child: Container()),
              TextButton(onPressed: nextCamera, child: const Text("Previous")),
            ],
          ),
          Text("${currentCamera + 1}/${_cameras.length}"),
        ],
      );
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _controller?.dispose();

    super.dispose();
  }

  void _newCameraController(int camera) {
    if (camera >= _cameras.length) {
      throw IndexError(camera, _cameras.length);
    }

    // Notify the UI we are waiting for a new camera
    setState(() => _controller = null);

    final controller =
        c.CameraController(_cameras[camera], c.ResolutionPreset.max);
    controller.initialize().then((_) {
      if (!mounted) return;

      // Notify the UI the new controller is ready
      setState(() => _controller = controller);
    });
  }

  void nextCamera() {
    currentCamera = (currentCamera + 1) % (_cameras.length + 1);
  }

  void prevCamera() {
    currentCamera = ((currentCamera - 1) % _cameras.length).abs();
  }
}
```

</details>

<details>
  <summary>Logs</summary>

<!--
      Run your application with `flutter run --verbose` and attach all the
      log output below between the lines with the backticks. If there is an
      exception, please see if the error message includes enough information
      to explain how to solve the issue.
-->

```
   +4 ms] Connected to _flutterView/0xb40000761c78a880.
[   +2 ms] Flutter run key commands.
[   +1 ms] r Hot reload. 
[        ] R Hot restart.
[        ] h List all available interactive commands.
[        ] d Detach (terminate "flutter run" but leave application running).
[        ] c Clear the screen
[        ] q Quit (terminate the application on the device).
[        ]  Running with sound null safety 
[        ] An Observatory debugger and profiler on SM N975U is available at:
http://127.0.0.1:54251/OWsBhoxQq1c=/
[   +6 ms] W/Camera  (32432): The selected imageFormatGroup is not supported by Android. Defaulting to yuv420
[  +20 ms] I/CameraManagerGlobal(32432): Camera 0 facing CAMERA_FACING_BACK state now CAMERA_STATE_OPEN for
client com.jquesada.workbench_view API Level 2
[        ] I/Camera  (32432): startPreview
[ +153 ms] I/Camera  (32432): CameraCaptureSession onConfigured
[        ] I/Camera  (32432): Updating builder settings
[        ] D/Camera  (32432): Updating builder with feature: ExposureLockFeature
[        ] D/Camera  (32432): Updating builder with feature: ExposurePointFeature
[        ] D/Camera  (32432): Updating builder with feature: ZoomLevelFeature
[        ] D/Camera  (32432): Updating builder with feature: AutoFocusFeature
[        ] D/Camera  (32432): Updating builder with feature: NoiseReductionFeature
[        ] I/Camera  (32432): updateNoiseReduction | currentSetting: fast
[        ] D/Camera  (32432): Updating builder with feature: FocusPointFeature
[        ] D/Camera  (32432): Updating builder with feature: ResolutionFeature
[        ] D/Camera  (32432): Updating builder with feature: SensorOrientationFeature
[        ] D/Camera  (32432): Updating builder with feature: FlashFeature
[        ] D/Camera  (32432): Updating builder with feature: ExposureOffsetFeature
[        ] D/Camera  (32432): Updating builder with feature: FpsRangeFeature
[   +1 ms] I/Camera  (32432): refreshPreviewCaptureSession
[   +7 ms] I/CameraManagerGlobal(32432): Camera 0 facing CAMERA_FACING_BACK state now CAMERA_STATE_ACTIVE for
client com.jquesada.workbench_view API Level 2
[  +30 ms] I/BufferQueueProducer(32432): [SurfaceView -
com.jquesada.workbench_view/com.jquesada.workbench_view.MainActivity@c666876@0#1(BLAST
Consumer)1](id:7eb000000001,api:1,p:32432,c:32432) queueBuffer: queued for the first time.
[  +18 ms] I/SurfaceView@c666876(32432): uSP: rtp = Rect(0, 0 - 1080, 2280) rtsw = 1080 rtsh = 2280
[   +1 ms] I/SurfaceView@c666876(32432): onSSPAndSRT: pl = 0 pt = 0 sx = 1.0 sy = 1.0
[        ] I/SurfaceView@c666876(32432): aOrMT: uB = true t = android.view.SurfaceControl$Transaction@76c77f8
fN = 1 android.view.SurfaceView.access$500:124
android.view.SurfaceView$SurfaceViewPositionUpdateListener.positionChanged:1728
android.graphics.RenderNode$CompositePositionUpdateListener.positionChanged:319 
[        ] I/SurfaceView@c666876(32432): aOrMT: vR.mWNT, vR = ViewRootImpl@a4f705[MainActivity]
[        ] I/ViewRootImpl@a4f705[MainActivity](32432): mWNT: t =
android.view.SurfaceControl$Transaction@76c77f8 fN = 1 android.view.SurfaceView.applyOrMergeTransaction:1628 
android.view.SurfaceView.access$500:124
android.view.SurfaceView$SurfaceViewPositionUpdateListener.positionChanged:1728 
[   +1 ms] I/ViewRootImpl@a4f705[MainActivity](32432): mWNT: merge t to BBQ
[   +4 ms] I/BufferQueueProducer(32432): [ViewRootImpl@a4f705[MainActivity]#0(BLAST
Consumer)0](id:7eb000000000,api:1,p:32432,c:32432) queueBuffer: queued for the first time.
[   +3 ms] I/ViewRootImpl@a4f705[MainActivity](32432): [DP] pdf(0) 1
android.view.ViewRootImpl.lambda$addFrameCompleteCallbackIfNeeded$3$ViewRootImpl:4969
android.view.ViewRootImpl$$ExternalSyntheticLambda16.run:6 android.os.Handler.handleCallback:938 
[        ] I/ViewRootImpl@a4f705[MainActivity](32432): [DP] rdf()
[        ] D/ViewRootImpl@a4f705[MainActivity](32432): reportDrawFinished (fn: -1) 
[  +13 ms] I/ViewRootImpl@a4f705[MainActivity](32432): MSG_WINDOW_FOCUS_CHANGED 1 1
[   +1 ms] D/InputMethodManager(32432): startInputInner - Id : 0
[        ] I/InputMethodManager(32432): startInputInner - mService.startInputOrWindowGainedFocus
[   +6 ms] D/InputMethodManager(32432): startInputInner - Id : 0
[  +20 ms] The Flutter DevTools debugger and profiler on SM N975U is available at:
           http://127.0.0.1:9104?uri=http://127.0.0.1:54251/OWsBhoxQq1c=/
[ +250 ms] I/BufferQueueProducer(32432): [SurfaceTexture-0-32432-0](id:7eb000000002,api:4,p:1136,c:32432)
queueBuffer: queued for the first time.
[+8490 ms] I/ViewRootImpl@a4f705[MainActivity](32432): ViewPostIme pointer 0
[ +121 ms] I/ViewRootImpl@a4f705[MainActivity](32432): ViewPostIme pointer 1
[  +13 ms] I/Camera  (32432): close
[        ] I/Camera  (32432): closeCaptureSession
[  +77 ms] I/CameraManagerGlobal(32432): Camera 0 facing CAMERA_FACING_BACK state now CAMERA_STATE_IDLE for
client com.jquesada.workbench_view API Level 2
[ +199 ms] I/Camera  (32432): open | onClosed
[   +1 ms] W/.workbench_vie(32432): Long monitor contention with owner main (32432) at void
android.hardware.camera2.impl.CameraDeviceImpl.close()(CameraDeviceImpl.java:1400) waiters=0 in void
android.hardware.camera2.impl.CameraDeviceImpl$CameraDeviceCallbacks.onResultReceived(android.hardware.camera
2.impl.CameraMetadataNative, android.hardware.camera2.impl.CaptureResultExtras,
android.hardware.camera2.impl.PhysicalCaptureResultInfo[]) for 264ms
[   +1 ms] I/CameraManagerGlobal(32432): Camera 0 facing CAMERA_FACING_BACK state now CAMERA_STATE_CLOSED for
client com.jquesada.workbench_view API Level 2
[        ] E/MethodChannel#plugins.flutter.io/camera(32432): Failed to handle method call
[        ] E/MethodChannel#plugins.flutter.io/camera(32432): java.lang.IllegalArgumentException: No capture  
session available for current capture session.
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
io.flutter.plugins.camera.features.resolution.ResolutionFeature.getBestAvailableCamcorderProfileForResolution
Preset(ResolutionFeature.java:227)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
io.flutter.plugins.camera.features.resolution.ResolutionFeature.configureResolution(ResolutionFeature.java:24
0)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
io.flutter.plugins.camera.features.resolution.ResolutionFeature.<init>(ResolutionFeature.java:50)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
io.flutter.plugins.camera.features.CameraFeatureFactoryImpl.createResolutionFeature(CameraFeatureFactoryImpl.
java:58)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
io.flutter.plugins.camera.features.CameraFeatures.init(CameraFeatures.java:71)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
io.flutter.plugins.camera.Camera.<init>(Camera.java:215)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
io.flutter.plugins.camera.MethodCallHandlerImpl.instantiateCamera(MethodCallHandlerImpl.java:385)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
io.flutter.plugins.camera.MethodCallHandlerImpl.lambda$onMethodCall$0$MethodCallHandlerImpl(MethodCallHandler
Impl.java:80)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
io.flutter.plugins.camera.-$$Lambda$MethodCallHandlerImpl$kQOHgMggqzdMNqkzF-YukQrdRi8.onResult(Unknown       
Source:6)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
io.flutter.plugins.camera.CameraPermissions.requestPermissions(CameraPermissions.java:53)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
io.flutter.plugins.camera.MethodCallHandlerImpl.onMethodCall(MethodCallHandlerImpl.java:73)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:262)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:295)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$DartMessenger(DartMessenger.ja
va:319)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
io.flutter.embedding.engine.dart.-$$Lambda$DartMessenger$TsixYUB5E6FpKhMtCSQVHKE89gQ.run(Unknown Source:12)  
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
android.os.Handler.handleCallback(Handler.java:938)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
android.os.Handler.dispatchMessage(Handler.java:99)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at android.os.Looper.loopOnce(Looper.java:226)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at android.os.Looper.loop(Looper.java:313)   
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
android.app.ActivityThread.main(ActivityThread.java:8663)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at java.lang.reflect.Method.invoke(Native    
Method)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567)
[        ] E/MethodChannel#plugins.flutter.io/camera(32432):    at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
[        ] E/flutter (32432): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception:
CameraException(error, No capture session available for current capture session.)
[        ] E/flutter (32432): #0      MethodChannelCamera.createCamera
(package:camera_platform_interface/src/method_channel/method_channel_camera.dart:104:7)
[        ] E/flutter (32432): <asynchronous suspension>
[        ] E/flutter (32432): #1      CameraController.initialize
(package:camera/src/camera_controller.dart:295:19)
[        ] E/flutter (32432): <asynchronous suspension>
[        ] E/flutter (32432): 
[+6957 ms] Application finished.
```

<!--
     Run `flutter analyze` and attach any output of that command below.
     If there are any analysis errors, try resolving them before filing this issue.
-->

```
Analyzing workbench_view...                                             
No issues found! (ran in 3.0s)
```

<!-- Finally, paste the output of running `flutter doctor -v` here. -->

```
[√] Flutter (Channel stable, 3.0.2, on Microsoft Windows [Version 10.0.22000.675], locale en-US)
    • Flutter version 3.0.2 at C:\flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision cd41fdd495 (7 days ago), 2022-06-08 09:52:13 -0700
    • Engine revision f15f824b57
    • Dart version 2.17.3
    • DevTools version 2.12.2

[√] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    • Android SDK at C:\Users\jose2\AppData\Local\Android\Sdk
    • Platform android-32, build-tools 32.1.0-rc1
    • ANDROID_SDK_ROOT = C:\Users\jose2\AppData\Local\Android\Sdk
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 11.0.12+7-b1504.28-7817840)
    • All Android licenses accepted.

[X] Chrome - develop for the web (Cannot find Chrome executable at .\Google\Chrome\Application\chrome.exe)
    ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.

[√] Visual Studio - develop for Windows (Visual Studio Build Tools 2022 17.1.1)
    • Visual Studio at C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools
    • Visual Studio Build Tools 2022 version 17.1.32228.430
    • Windows 10 SDK version 10.0.19041.0

[√] Android Studio (version 2021.2)
    • Android Studio at C:\Program Files\Android\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 11.0.12+7-b1504.28-7817840)

[√] VS Code (version 1.68.0)
    • VS Code at C:\Users\jose2\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.42.0

[√] Connected device (3 available)
    • SM N975U (mobile) • RF8M90L77EZ • android-arm64  • Android 12 (API 31)
    • Windows (desktop) • windows     • windows-x64    • Microsoft Windows [Version 10.0.22000.675]
    • Edge (web)        • edge        • web-javascript • Microsoft Edge 102.0.1245.39

[√] HTTP Host Availability
    • All required HTTP hosts are available

! Doctor found issues in 1 category.
```

</details>


<!--
      Consider also attaching screenshots and/or videos to better
      illustrate the issue.

      You can upload them directly on GitHub.
      Beware that video file size is limited to 10MB.
-->

The device I am testing with, as per `flutter doctor -v` above, is the Samsung Galaxy Note 10+, SM N975U, although I will try and test this to see if I can get this bug on any other Android device I have nearby.