audio_waveforms icon indicating copy to clipboard operation
audio_waveforms copied to clipboard

fix: 🐛 Prevent Android recorder crash from stopping unstarted muxer

Open lavigarg-simform opened this issue 5 months ago • 0 comments

Description

Fixes an Android-only native crash that occurs when recording is stopped before the muxer has started writing any track, plus two related race/error-handling issues in the recording thread.

Existing behavior: When stop() was called shortly after start() (i.e. before the MediaMuxer received its first frame and was started), the encoder unconditionally called mediaMuxer?.stop(). Stopping a muxer that was never started throws and triggers the native MPEG4Writer "track not started" crash, taking down the app.

Two further problems made this worse:

  • The recording thread could call audioRecord.read() after the AudioRecord was released during stop(), because the read loop was not guaranteed to be stopped and joined before release.
  • AudioRecord.read() errors (negative return values such as ERROR_INVALID_OPERATION / ERROR_DEAD_OBJECT) were ignored, so the loop kept retrying a failing read.

Changes:

  • CommonEncoder.kt — guard mediaMuxer?.stop() with the existing isMuxerStarted flag so an unstarted muxer is only released, never stopped.
  • AudioRecorder.kt — in stop(), set RecorderState.Stopped and join the recording thread before releasing AudioRecord, so the read loop can never touch a released object.
  • AudioRecorder.kt — bail out of the read loop on a negative read() result instead of spinning on a permanently failing read.
  • Removed the redundant recordingThread?.join() callback passed into initCodec (join is now handled centrally in stop()).

Checklist

  • [x] The title of my PR starts with a Conventional Commit prefix (fix:, feat:, docs: etc).
  • [x] I have followed the Contributor Guide when preparing my PR.
  • [ ] I have updated/added tests for ALL new/updated/fixed functionality.
  • [ ] I have updated/added relevant documentation in docs and added dartdoc comments with ///.
  • [ ] I have updated/added relevant examples in examples or docs.

Breaking Change?

  • [ ] Yes, this PR is a breaking change.
  • [x] No, this PR is not a breaking change.

Related Issues

Closes #482

lavigarg-simform avatar Jun 22 '26 09:06 lavigarg-simform