Skip to content

perf(app): decode and combine Offline Sync recording audio on background isolate (#22126) - #23497

Merged
aryanorastar merged 6 commits into
BasedHardware:mainfrom
ocakciomursel-pixel:fix/offline-sync-share-background-isolate-22126
Oct 27, 2026
Merged

aryanorastar merged 6 commits into
BasedHardware:mainfrom
ocakciomursel-pixel:fix/offline-sync-share-background-isolate-22126

Conversation

@ocakciomursel-pixel

@ocakciomursel-pixel ocakciomursel-pixel commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

Fixes #22126. Offline Sync sharing decodes and combines long recordings on a background isolate while file selection, platform-directory lookup and share-sheet invocation stay on the UI isolate. This finishes the existing contributor implementation rather than opening a duplicate PR; @ocakciomursel-pixel's commits are preserved.

The shared worker handles disk and memory-backed WALs, initializes native Opus inside each worker, streams frames/PCM with bounded buffering, and preserves oldest-first mixed Opus/PCM output. Existing missing/unreadable-part behavior remains. Zero-length payloads are skipped before Opus can synthesize packet-loss concealment, and decoder views retain only their selected sample range. Each job owns its scratch directory; inputs and playback caches are retained. WAV publication uses a same-directory staging file and atomic rename, so a failed combine cannot overwrite an earlier complete export. Concurrent shares use unique output directories.

Why isn't this a shared primitive instead? It is: single-file playback/share and whole-recording export use the same WAL decoder and PCM WAV header. WavCombiner owns atomic final publication for its existing callers too. No new generic guard or policy was added.

Verification

  • Four cleanup/failure regressions failed on the original contributor implementation. Review also caught an empty-Opus regression in the streaming refactor; its added test failed before the empty-payload fix. All five regressions now pass.
  • bash app/test.sh test/unit/audio_player_utils_test.dart test/utils/wav_combiner_test.dart: 36 focused tests and 138 protected spine tests passed. Cases include worker failure/no sheet, retries, cleanup, cache/source preservation, concurrent shares, streaming frame boundaries and corrupt/truncated parts.
  • Native integration passed on iPhone 16 Pro simulator, iOS 26.5: real libopus 1.3.1 in fresh workers; 3601 seconds of synthetic mixed Opus/PCM produced 115,232,044 bytes in 1,129 ms for export/validation with 20 UI frames serviced. Both whole-recording export and single-file native decode passed. Run: OMI_APP_PROFILE=local_dev flutter test integration_test/offline_recording_export_native_test.dart -d <simulator> --flavor dev --dart-define=OMI_APP_PROFILE=local_dev.
  • Focused Flutter analyzer: no issues. make preflight: all 26 selected checks passed. Five new failure/cleanup/empty-payload tests were demonstrated red on the original implementation.
  • Full CI is green at 715130b4649befa8127407b7f417f71948c234e0: Flutter analyzer/tests, generated files, formatting, hygiene, PR metadata and Mobile Release Eligibility passed. The full Flutter suite passed 7,688 tests, with four skipped. Native/platform jobs excluded by the diff scope are not claimed as CI runtime coverage.
  • Final source review and local/native gates are complete. The PR remains draft for maintainer review; no readiness change, approval, merge, deployment or release was performed.

No backend, firmware, account state or recording custody metadata changes. Mobile app release follows merge. Architecture and implementation checklist: app/lib/utils/audio/README.md. Mid-range physical Android hardware and a customer's recording have not been used; simulator acceptance is reported separately from physical hardware evidence.

Product invariants affected

INV-PERF-1 — audio frame conversion and recording combination stay off the UI isolate.

Failure class (fixes)

Failure-Class: none

This scoped audio-export CPU/temporary-file defect has no matching registered failure class; it does not change capture/upload custody or provider selection.

UI evidence

UI-Evidence: none -- export execution and temporary-file handling only; no layout or visual changes.

Main was rechecked at ca1d6079d1 after CI: this export fix is still absent. Main advanced only in unrelated backend listen/feature-flag files; mobile sources exercised by the evidence are unchanged. #22126 can close as technically completed once this verified implementation lands on main; mobile distribution follows separately.

@Git-on-my-level

Copy link
Copy Markdown
Member

The production change here is correct and nicely scoped - decode/combine now runs off the UI thread with output bytes and error behavior preserved; two small follow-up asks below.

app/lib/utils/audio_player_utils.dart

  • writeRecordingWav pre-resolves paths on the main isolate, ships string-only _WalWavWorkItem jobs into compute(_buildRecordingWavInIsolate, ...), and returns only a path - no audio bytes cross isolate boundaries, which is the right shape for multi-hour recordings.
  • _decodeWalWorkItemToWav is a faithful port of the removed _decodeOpusToWav/_convertPcmToWav/_createWavFile chain: same length-prefixed frame parsing, same skip-on-corrupt-Opus-frame semantics, identical 44-byte header math in _buildWavHeaderAndData, and _getOrCreateAudioFile cache handling (including the forSharing playback-cache reuse) is unchanged.
  • Error behavior is preserved: WavCombiner.combineWavFiles can still throw ('No valid WAV files to combine', incompatible formats) and compute rethrows on the caller, so shareRecordingAsAudio sees the same failures as before.
  • The existsSync() -> await File.exists() swaps remove the remaining sync file IO from this class, matching the mobile UI-isolate invariant your PR description cites.
  • One gap: _ensureOpusInitializedInIsolate re-runs opus_flutter.load() in every spawned isolate (per share/export call), and the Opus branch inside the isolate has no direct test coverage - both new tests use PCM16 fixtures.

app/test/unit/audio_player_utils_test.dart - the new assertions pin the actual invariant (lastWorkerIsolateName equals the compute debugLabel and differs from Isolate.current.debugName) while still byte-checking WAV output; good way to lock this in against regressions to main-isolate work.

app/changelog/unreleased/20261024-offline-sync-share-background-isolate.json - accurate user-facing description; ios+android platform list matches the shared Flutter code path.

Performance: per call, one isolate spawn plus (Opus only) one dynamic-library load - milliseconds against the multi-second decode it replaces; full-PCM-in-memory per file is unchanged. UX: sharing a long recording no longer freezes the UI. Security: none - no new permissions, background modes, or data flows, and the share sheet still opens on the main isolate. Blast radius: confined to WAL playback/share decode; a failed decode still returns null exactly as before.

USER IMPACT: sharing a long Offline Sync recording no longer freezes the app while the audio is decoded and combined; the exported WAV is unchanged.

Still wanted as a reviewer:

  • A unit test exercising the Opus path through the isolate (small real Opus frame set), or a note on why PCM-only coverage is acceptable here.
  • A quick sanity check that Logger.debug from inside a worker isolate (corrupt-frame skip and WavCombiner skip paths) is safe with the Talker/Crashlytics observer wiring - those paths are not hit by the current tests.

Leaving formal sign-off to a human maintainer.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution flutter flutter work labels Oct 24, 2026
@ocakciomursel-pixel

ocakciomursel-pixel commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review @Git-on-my-level! Added follow-up coverage in d8a17d9f7f:

  1. Worker-isolate Opus branch + decoder cleanup: Added a @VisibleForTesting OpusFrameDecoder seam (debugOpusFrameDecoder) and ensured
    ativeDecoder?.destroy() runs in inally inside _decodeWalWorkItemToWav. Added unit test 'decodes Opus frames and safely runs Logger.debug skip paths in background isolate' in �pp/test/unit/audio_player_utils_test.dart exercising the Opus decode branch and corrupted-frame skip path inside the spawned worker isolate.
  2. Logger.debug in worker isolate sanity check: Verified Logger.debug only invokes instance.talker.debug(message) (CrashlyticsTalkerObserver only overrides onError/onException, not onLog, and DebugLogManager is not called on debug), and the new isolate unit test now directly hits both the corrupt Opus frame Logger.debug skip path and WavCombiner.combineWavFiles's unreadable-WAV-part Logger.debug skip path inside the background isolate.

@ocakciomursel-pixel

Copy link
Copy Markdown
Contributor Author

Thanks @Git-on-my-level! Addressed both follow-up points in 6dfbc83435:

  1. Worker-isolate Opus path coverage: Because opus_flutter.load() loads the native libopus FFI binary via platform plugin (which is not available in the headless flutter test VM), added a @visibleForTesting top-level OpusFrameDecoder hook that crosses compute(...) isolate boundaries and added decodes Opus frames in background isolate and skips corrupt frames via Logger.debug in audio_player_utils_test.dart.
  2. Logger.debug safety inside worker isolates: Verified that CrashlyticsTalkerObserver only hooks onError and onException (never onLog / Logger.debug), and TalkerFlutter.init uses pure-Dart console output without platform channel calls. Both new tests directly exercise Logger.debug inside the spawned compute isolate (the corrupted Opus frame skip path in _decodeWalWorkItemToWav and the unreadable WAV part skip path in WavCombiner.combineWavFiles).

@ocakciomursel-pixel
ocakciomursel-pixel force-pushed the fix/offline-sync-share-background-isolate-22126 branch from 6dfbc83 to d8a17d9 Compare October 25, 2026 07:34
@Git-on-my-level

Copy link
Copy Markdown
Member

Verdict: The production change is correct and nicely scoped — moving Offline Sync audio decode/combine off the UI isolate is the right fix for #22126, and the implementation preserves the existing cache and output semantics.

  • app/lib/utils/audio_player_utils.dart — decode and combine now run via compute() (writeRecordingWav / _getOrCreateAudioFile) with path_provider resolution and the share sheet correctly kept on the main isolate. WAV header construction moved verbatim into _buildWavHeaderAndData; playback-cache reuse for sharing and the non-sharing cache write are both preserved. Nice touches: SimpleOpusDecoder is now destroyed in a finally block, and the sync File.existsSync() checks became await File.exists().
  • _ensureOpusInitializedInIsolate is the right call — each compute() isolate is fresh, so initOpus(opus_flutter.load()) runs per operation. Minor cost note: that load repeats per call; negligible for share/combine, but a first-time single-file playback decode now pays isolate spawn + lib load (cached afterwards).
  • One nit: corrupt-frame logging was downgraded from Logger.warning to Logger.debug — if field diagnosis of corrupted WAL audio matters, consider keeping warning.
  • app/test/unit/audio_player_utils_test.dart — good targeted tests: byte-exact WAV output, background-isolate execution asserted via isolate debug names, the corrupt-frame skip path, and cache reuse inside the combine; the debugOpusFrameDecoder injection keeps tests off the native decoder.
  • app/changelog/unreleased/20261024-offline-sync-share-background-isolate.json — accurate, user-facing, correct platforms.

Performance: multi-hour recording decode/combine no longer blocks the UI isolate; per-call isolate spawn adds ~ms. Security: no new data flows or permissions — audio stays on device. Blast radius: local recording playback/share paths only.

USER IMPACT: Sharing or first-playing an Offline Sync recording no longer freezes the app while audio is decoded; the exported audio itself is unchanged.

Still would like as a reviewer: a real-device sanity check on a multi-hour recording (the in-memory combine's memory ceiling is unchanged, just moved off-thread) — nothing else blocking. Leaving for human maintainer review before merge.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@aryanorastar
aryanorastar marked this pull request as draft October 27, 2026 10:39
@aryanorastar aryanorastar added the ci:full Maintainer-granted: run full CI on this fork PR label Oct 27, 2026
@aryanorastar
aryanorastar marked this pull request as ready for review October 27, 2026 13:53
@aryanorastar
aryanorastar merged commit b0d4aa1 into BasedHardware:main Oct 27, 2026
44 checks passed
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-27T13:58:24.513408Z
We couldn’t complete this review. Comment @codex review to try again.
715130b Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci:full Maintainer-granted: run full CI on this fork PR flutter flutter work positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Decode Offline Sync audio off the UI isolate when sharing a recording

3 participants