Skip to content

fix(wasm): Release image decoder memory after each decode - #24848

Merged
ajpinedam merged 5 commits into
unoplatform:masterfrom
ajpinedam:dev/anpi/fix.wasm.image.decoder.memory
Oct 2, 2026
Merged

ajpinedam merged 5 commits into
unoplatform:masterfrom
ajpinedam:dev/anpi/fix.wasm.image.decoder.memory

Conversation

@ajpinedam

Copy link
Copy Markdown
Contributor

GitHub Issue: related to unoplatform/kahua-private#547

PR Type:

🐞 Bugfix

What changed? 🚀

On Skia WebAssembly, the browser image decoder keeps every worker's last image in memory for the rest of the session. ImageLoader.ts runs one dedicated worker per navigator.hardwareConcurrency (8 on an iPad), each with one OffscreenCanvas. A decode resized the canvas to the image and never shrank it, and never closed the ImageBitmap, which was freed only when the worker's own GC ran. On the C# side, the JSObject returned by LoadFromArray was never disposed, so the response, including the w×h×4 pixel buffer transferred from the worker, stayed alive until the wrapper's finalizer ran. The managed GC isn't prompted by that memory, so it can be a long wait.

This reduces the browser process footprint, which is what iOS memory limits count. It doesn't change the growth of WebAssembly linear memory (HEAPU8.length): the heap peak was the same in every measured build.

  • Worker (ImageLoader.ts): after getImageData, the bitmap is closed and the canvas is shrunk back to 0×0 in a finally, so errors release them too. Width and height now come from the ImageData, because a closed bitmap reports 0×0.
  • ImageSourceHelpers: the JSObject is disposed with using.
  • ImageSourceHelpers, master only: the RGBA→BGRA swap now happens in place on the managed copy, instead of allocating a second full-size array per decode. CopyPixels copies the pixels into native memory either way.

There are no public API changes. The response returned to C# ({error, bytes, width, height}) is unchanged.

Validation

Memory was sampled from outside the browser with macOS footprint, at fixed phases of each run.

  • Safari 26.6 (desktop), worker only: a script-only page runs each build's worker code without .NET: 8 workers, 3 rounds of 2048² PNGs.

    • Canvas memory: 128 MiB, never released, before the fix; 0 after.
    • Page process 30 s after the last decode: 333 MiB before, 94–110 MiB after (baseline 123 MiB).
    • Decoded bitmaps at their peak: +333 MiB before, +124 MiB after.
  • Chrome, full SamplesApp: a probe test decodes 8 images concurrently per round, 3 rounds of 2048².

    • Page process 5 s after the last decode: 1,286–1,414 MiB before, 1,012–1,013 MiB after.
    • Browser-side allocations (PartitionAlloc): 333–350 MiB before, 61–63 MiB after (baseline 59 MiB). With only the worker change, 92 MiB, so disposing the JSObject accounts for about 30 MiB.
    • Full GCs for the same decodes: 53–58 before, 42–46 after, from the in-place swap.
  • Decode time (Chrome, worker only, same-size decodes on one worker): 256² took 1.5–2.4 ms per decode before and 1.5–1.6 ms after; 1024² about 21 ms in both. The Safari timings varied up to 6× between runs of the same build and are not reported.

  • Runtime tests (Skia WebAssembly, headless Chrome, Release): all of Given_Image and Given_BitmapSource pass: 44 passed, 0 failed. Three tests are skipped by [Ignore], and When_Transitive_Asset_With_Link_Loaded is inconclusive in the browser, as it is on master.

  • New test: Given_BitmapSource.When_Browser_Workers_Are_Reused calls the worker API directly. Through Image, a broken worker can't be seen: a failed browser decode falls back to SKCodec and the image still opens. With a worker that throws instead of returning pixels, this test fails while When_Alpha_Blending, When_Exif_Rotated_From_Stream and When_Exif_Rotated_MsAppx still pass.

    • It decodes one more image than there are workers, so at least one worker decodes again after its reset.
    • It then decodes invalid bytes followed by a valid image.
    • It checks dimensions, byte count and the premultiplied first pixel.

    The test passes without the fix too. It guards the reset and error paths; the memory effect is shown by the measurements above. The expected pixels were also checked on Safari 26.6, which returns the same values as Chrome.

  • Build: Uno.UI, Uno.UI.Runtime.Skia.WebAssembly.Browser and Uno.UI.RuntimeTests.Skia compile for net10.0 with analyzers, code-style enforcement and warnings as errors. net11.0 was not built locally.

  • Not validated:

    • On an iPad.
    • The SamplesApp runtime tests in Safari: a covered Safari window throttles timers, which stalled the runs.

Backports

ImageLoader.ts is identical on servicing/6.8 and release/stable/6.7, and the worker change and the test apply there unchanged. The in-place swap commit is master only: 6.x wraps the pinned managed array in an SKImage without copying it. When backporting, drop that commit and keep only the using in ImageSourceHelpers.cs. That file is the one conflict a dry-run merge predicts on both branches.

Not in this PR

  • The worker pool has no error or messageerror handler and no timeout. A worker that crashes leaves its decode waiting forever and drops out of the pool. This already happens on master.
  • The pool creates hardwareConcurrency workers at startup, with no cap and no idle shutdown. Several decodes at once still peak at roughly workers × (bitmap + canvas + pixels).
  • On master, the R/B swap could move into the worker's premultiply loop, and the managed copy could be skipped by copying the JS buffer straight into native memory.

PR Checklist ✅

🤖 Generated with Claude Code

Copilot AI balanced review requested due to automatic review settings October 1, 2026 05:50
@github-actions github-actions Bot added the platform/wasm 🌐 Categorizes an issue or PR as relevant to the WebAssembly platform label Oct 1, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟢 Approval recommended

The cleanup is correctly scoped, preserves the response contract, and includes targeted WASM validation.

Review effort: Balanced
Findings: None

What changed in this PR

Reduces browser-side memory retention after WASM image decoding.

Changes:

  • Releases worker ImageBitmap and canvas memory after decoding.
  • Disposes decoded JavaScript objects and swaps RGBA/BGRA in place.
  • Adds WASM worker reuse and error-recovery coverage.
File Description
ImageSourceHelpers.cs Disposes JS results and removes an extra pixel-buffer allocation.
Given_BitmapSource.cs Tests repeated worker decoding and recovery after invalid input.
ImageLoader.ts Cleans up bitmap and canvas resources after each decode.

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

@unodevops

Copy link
Copy Markdown
Contributor

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 236658 found UI Test snapshots differences: skia-linux-screenshots: 57, skia-windows-screenshots: 2304, wasm: 11

Details
  • skia-linux-screenshots: 57 changed over 2348

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • Buttons.png-dark
    • Buttons.png
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • ClipboardTests.png-dark
    • ContextRequested.png-dark
    • ContextRequested.png
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • DisplayInformation.png-dark
    • DropDownButtonPage.png-dark
    • DropDownButtonPage.png
    • ElementLevelTheme.png-dark
    • ElementLevelTheme.png
    • Focus_FocusVisual_Properties.png-dark
    • Examples.png-dark
    • Examples.png
    • ExpanderColorValidationPage.png-dark
    • ExpanderColorValidationPage.png
    • ImageIconPage.png-dark
  • skia-windows-screenshots: 2304 changed over 2502

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • Accessibility_ScreenReader.png
    • AppBarButtonTest.png
    • AppBarToggleButtonTest.png-dark
    • AppBar_KeyBoard.png
    • AppWindowClosing.png-dark
    • ApplicationViewSpanningRectsPage.png-dark
    • AppWindowPositionAndSize.png-dark
    • AppWindowPresenters.png
    • Arrange_Performance01.png
    • ArcSegment.png
    • Attributed_text_Simple.png
    • AuthenticationBroker_Demo.png-dark
    • AutoBorderStretchwithbottommargin.png
    • AutoBorderStretchwithleftmargin.png
    • AutomationPropertiesExtensions_Role.png
    • AutomationProperties_AutomationId.png
    • AutoSuggestBoxChosenSuggestion.png
    • AutoSizedTopLeft.png
    • AutoSuggestBox_BitmapIcon.png-dark
    • AutoSuggestBoxChosenSuggestion.png-dark
  • wasm: 11 changed over 1076

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • SamplesApp.Windows_UI_Xaml_Controls.ListView.ListViewSelectedItems
    • UITests.Microsoft_UI_Xaml_Controls.WebView2Tests.WebView2_NavigationProperties
    • UITests.Shared.Microsoft_UI_Xaml_Controls.ExpanderTests.WinUIExpanderPage
    • UITests.Shared.Windows_UI_Xaml_Controls.MediaPlayerElement.MediaPlayerElement_Minimal
    • UITests.Shared.Windows_UI_Xaml_Controls.MediaPlayerElement.MediaPlayerElement_Ogg_Extension
    • SamplesApp.Wasm.Windows_UI_Xaml_Controls.ListView.ListView_IsSelected
    • SamplesApp.Microsoft_UI_Xaml_Controls.WebView2Tests.WebView2_EnableDevTools
    • UITests.Uno_Web.Http.CookieManagerTests
    • Uno.UI.Samples.Content.UITests.WebView.WebView_AnchorNavigation
    • UITests.Windows_UI_Xaml_Controls.CalendarView.CalendarView_Theming
    • UITests.Windows_UI_Xaml_Media_Animation.ColorAnimation_Background

@mergify

mergify Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@ajpinedam
ajpinedam merged commit 15013c1 into unoplatform:master Oct 2, 2026
52 checks passed
@ajpinedam

Copy link
Copy Markdown
Contributor Author

@Mergifyio backport servicing/6.8

@mergify

mergify Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

backport servicing/6.8

✅ Backports have been created

Details

Cherry-pick of 11ae190 has failed:

On branch mergify/bp/servicing/6.8/pr-24848
Your branch is ahead of 'origin/servicing/6.8' by 2 commits.
  (use "git push" to publish your local commits)

You are currently cherry-picking commit 11ae190.
  (fix conflicts and run "git cherry-pick --continue")
  (use "git cherry-pick --skip" to skip this patch)
  (use "git cherry-pick --abort" to cancel the cherry-pick operation)

Unmerged paths:
  (use "git add <file>..." to mark resolution)
	both modified:   src/Uno.UI/UI/Xaml/Media/Imaging/ImageSourceHelpers.cs

no changes added to commit (use "git add" and/or "git commit -a")

To fix up this pull request, you can check it out locally. See documentation: https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/checking-out-pull-requests-locally

@ajpinedam
ajpinedam deleted the dev/anpi/fix.wasm.image.decoder.memory branch October 2, 2026 14:18
ajpinedam added a commit that referenced this pull request Oct 2, 2026
…r-24848

fix(wasm): Release image decoder memory after each decode (backport #24848)
agneszitte added a commit that referenced this pull request Oct 28, 2026
…6.7/pr-24911

fix(wasm): Release image decoder memory after each decode (backport #24848) (backport #24911)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

platform/wasm 🌐 Categorizes an issue or PR as relevant to the WebAssembly platform

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants