Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

juliendelarbre
Copy link

@juliendelarbre juliendelarbre commented Sep 2, 2025

Summary

This PR fixes an iOS crash that occurs when using the camera plugin with enableAudio: false and no NSMicrophoneUsageDescription in Info.plist.

Root cause:
In DefaultCamera.setUpCaptureSessionForAudioIfNeeded(), the guard currently allows audio setup to proceed even when audio is disabled:

// current (buggy)
guard !mediaSettings.enableAudio || !isAudioSetup else { return }

This evaluates to true when enableAudio == false, so the audio setup runs regardless.

Fix: Require audio to be enabled and not already set up before proceeding:

// fixed
guard mediaSettings.enableAudio && !isAudioSetup else { return }

This aligns behavior with the intended logic (“don’t set up audio twice or when audio is disabled”) and prevents the crash path on iOS when the microphone usage description is absent.


Before / After

Before (buggy): audio setup runs when enableAudio == false, causing a crash on iOS if NSMicrophoneUsageDescription is missing.

After (fixed): audio setup is skipped when enableAudio == false; no crash, behavior matches API expectations.


Reproduction steps

  1. Create a Flutter project targeting iOS.
  2. Ensure ios/Runner/Info.plist does not contain NSMicrophoneUsageDescription.
  3. Initialize CameraController with enableAudio: false.
  4. Call startVideoRecording().
  5. Observe crash (on current main); with this PR applied, no crash.

Linked Issues

Fixes flutter/flutter#174702


Documentation

No API changes; behavior now matches the documented intent. (Optional: add a short inline comment elaborating that audio setup is skipped when enableAudio == false.)


Pre-Review Checklist

  • I read the [Contributor Guide] and followed the process outlined there for submitting PRs.
  • I read the [Tree Hygiene] page, which explains my responsibilities.
  • I read and followed the [relevant style guides] and ran [the auto-formatter].
  • I signed the [CLA].
  • The title of the PR starts with the name of the package surrounded by square brackets
  • I [linked to at least one issue that this PR fixes] in the description above.
  • I updated pubspec.yaml with an appropriate new version according to the [pub versioning philosophy], or I have commented below to indicate which [version change exemption] this PR falls under[^1].
  • I updated CHANGELOG.md to add a description of the change, [following repository CHANGELOG style], or I have commented below to indicate which [CHANGELOG exemption] this PR falls under[^1].
  • I updated/added any relevant documentation (doc comments with ///).
  • I added new tests to check the change I am making, or I have commented above to indicate which [test exemption] this PR falls under.
  • All existing and new tests are passing.

@flutter-dashboard
Copy link

It looks like this pull request may not have tests. Please make sure to add tests or get an explicit test exemption before merging.

If you are not sure if you need tests, consider this rule of thumb: the purpose of a test is to make sure someone doesn't accidentally revert the fix. Ask yourself, is there anything in your PR that you feel it is important we not accidentally revert back to how it was before your fix?

Reviewers: Read the Tree Hygiene page and make sure this patch meets those guidelines before LGTMing. If you believe this PR qualifies for a test exemption, contact "@test-exemption-reviewer" in the #hackers channel in Discord (don't just cc them here, they won't see it!). The test exemption team is a small volunteer group, so all reviewers should feel empowered to ask for tests, without delegating that responsibility entirely to the test exemption group.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request addresses a critical crash on iOS that occurs when the camera is used with enableAudio: false without the NSMicrophoneUsageDescription in Info.plist. The change corrects the logic in the guard statement within setUpCaptureSessionForAudioIfNeeded to ensure audio setup is only attempted when audio is explicitly enabled and has not already been configured. The fix is correct and directly resolves the reported issue by aligning the code's behavior with its intended logic.

@hellohuanlin
Copy link
Contributor

can you add some tests so that it doesn't regress

@juliendelarbre
Copy link
Author

@hellohuanlin, added some test.

@stuartmorgan-g stuartmorgan-g added the triage-ios Should be looked at in iOS triage label Sep 3, 2025
@juliendelarbre
Copy link
Author

/gemini review

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request correctly fixes a crash on iOS that occurred when enableAudio was set to false. The logical condition in the guard statement has been properly corrected to prevent the audio setup from running when it's disabled. The addition of new unit tests is a great improvement, as they cover both the enabled and disabled audio scenarios, ensuring the fix is robust and preventing future regressions. The changes to the test mocks to support this are also well-implemented. Overall, this is a solid contribution.

Comment on lines +210 to 303
func test_setUpCaptureSessionForAudioIfNeeded_skipsAudioSession_whenAudioDisabled() {
let settings = FCPPlatformMediaSettings.make(
with: testResolutionPreset,
framesPerSecond: NSNumber(value: testFramesPerSecond),
videoBitrate: NSNumber(value: testVideoBitrate),
audioBitrate: NSNumber(value: testAudioBitrate),
enableAudio: false
)

let wrapper = TestMediaSettingsAVWrapper(test: self, expectAudio: false)
let mockAudioSession = MockCaptureSession()

let configuration = CameraTestUtils.createTestCameraConfiguration()
configuration.mediaSettingsWrapper = wrapper
configuration.mediaSettings = settings
configuration.audioCaptureSession = mockAudioSession
let camera = CameraTestUtils.createTestCamera(configuration)

wait(
for: [
wrapper.lockExpectation,
wrapper.beginConfigurationExpectation,
wrapper.minFrameDurationExpectation,
wrapper.maxFrameDurationExpectation,
wrapper.commitConfigurationExpectation,
wrapper.unlockExpectation,
],
timeout: 1,
enforceOrder: true
)

camera.startVideoRecording(completion: { _ in }, messengerForStreaming: nil)

wait(
for: [
wrapper.audioSettingsExpectation,
wrapper.videoSettingsExpectation,
],
timeout: 1
)

XCTAssertEqual(
mockAudioSession.addedAudioOutputCount, 0,
"Audio session should not receive AVCaptureAudioDataOutput when enableAudio is false"
)
}

func test_setUpCaptureSessionForAudioIfNeeded_addsAudioSession_whenAudioEnabled() {
let settings = FCPPlatformMediaSettings.make(
with: testResolutionPreset,
framesPerSecond: NSNumber(value: testFramesPerSecond),
videoBitrate: NSNumber(value: testVideoBitrate),
audioBitrate: NSNumber(value: testAudioBitrate),
enableAudio: true
)

let wrapper = TestMediaSettingsAVWrapper(test: self, expectAudio: true)
let mockAudioSession = MockCaptureSession()

let configuration = CameraTestUtils.createTestCameraConfiguration()
configuration.mediaSettingsWrapper = wrapper
configuration.mediaSettings = settings
configuration.audioCaptureSession = mockAudioSession
let camera = CameraTestUtils.createTestCamera(configuration)

wait(
for: [
wrapper.lockExpectation,
wrapper.beginConfigurationExpectation,
wrapper.minFrameDurationExpectation,
wrapper.maxFrameDurationExpectation,
wrapper.commitConfigurationExpectation,
wrapper.unlockExpectation,
],
timeout: 1,
enforceOrder: true
)

camera.startVideoRecording(completion: { _ in }, messengerForStreaming: nil)

wait(
for: [
wrapper.audioSettingsExpectation,
wrapper.videoSettingsExpectation,
],
timeout: 1
)

XCTAssertGreaterThan(
mockAudioSession.addedAudioOutputCount, 0,
"Audio session should receive AVCaptureAudioDataOutput when enableAudio is true"
)
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The two new tests, test_setUpCaptureSessionForAudioIfNeeded_skipsAudioSession_whenAudioDisabled and test_setUpCaptureSessionForAudioIfNeeded_addsAudioSession_whenAudioEnabled, share a significant amount of setup and execution logic. To improve code clarity and maintainability, this duplicated code could be extracted into a private helper function.

This function could take enableAudio as a parameter, perform the common setup for the camera and mocks, and then return the mockAudioSession to be used for assertions in the individual tests.

Here is an example of how this could be structured:

private func performAudioSetupTest(enableAudio: Bool) -> MockCaptureSession {
  // ... common setup for settings, wrapper, mockAudioSession, configuration, and camera ...

  // ... first wait block for configuration ...

  camera.startVideoRecording(completion: { _ in }, messengerForStreaming: nil)

  // ... second wait block for recording start ...

  return mockAudioSession
}

func test_setUpCaptureSessionForAudioIfNeeded_skipsAudioSession_whenAudioDisabled() {
  let mockAudioSession = performAudioSetupTest(enableAudio: false)
  XCTAssertEqual(
    mockAudioSession.addedAudioOutputCount, 0,
    "Audio session should not receive AVCaptureAudioDataOutput when enableAudio is false"
  )
}

func test_setUpCaptureSessionForAudioIfNeeded_addsAudioSession_whenAudioEnabled() {
  let mockAudioSession = performAudioSetupTest(enableAudio: true)
  XCTAssertGreaterThan(
    mockAudioSession.addedAudioOutputCount, 0,
    "Audio session should receive AVCaptureAudioDataOutput when enableAudio is true"
  )
}

This refactoring would make the tests more concise and easier to maintain.

@@ -1,3 +1,7 @@
## 0.9.21+4

* Fixes crash on iOS when `enableAudio` is false by correcting audio setup guard.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can remove by correcting audio setup guard since it's implementation details that audience doesn't care

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[camera_avfoundation][iOS] Crash when enableAudio = false due to incorrect guard condition
3 participants