Skip to content

perf(wasm): Decode images without a managed copy or a UI-thread R/B swap - #25542

Open
mikernet wants to merge 4 commits into
unoplatform:masterfrom
mikernet:dev/mikernet/wasm-decode-no-managed-copy
Open

mikernet wants to merge 4 commits into
unoplatform:masterfrom
mikernet:dev/mikernet/wasm-decode-no-managed-copy

Conversation

@mikernet

@mikernet mikernet commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

GitHub Issue: closes #25541

PR Type:

💬 Other: performance (managed memory and UI-thread time of the WebAssembly image decode)

What changed? 🚀

On WebAssembly, the UI thread copied each browser-decoded image into a managed byte[] (40.7 MiB for 4000x2667), swapped R and B in it with a C# loop, then copied it again into the native image. This PR removes both costs; the decode itself is unchanged.

  • R/B swap in the worker. The worker's premultiply loop also swaps R and B and returns BGRA premultiplied, so the C# loop is gone.

  • One copy, no managed array. A new IImageEncoderDecoder overload, CreateImage<TState>(pixelWidth, pixelHeight, state, SpanAction<byte, TState> writePixels), has the caller write the image's BGRA premultiplied pixels into a span that is only valid during the call. The browser decode passes it to JavaScript as a MemoryView (ImageLoader.copyPixels), which fills it from the worker's buffer with set in the same synchronous call, and throws on a length mismatch (existing error path). Skia writes into an immutable SKBitmap that SKImage.FromBitmap shares rather than copies; the managed decoder (ManagedBackend.CreateImageDecoder()) writes into the buffer its ManagedImage owns.

    The overload is a default interface method, like IFontProvider.LoadFontFile, so it is not a breaking change: a codec registered through the host builder that doesn't implement it gets a default that writes into a temporary native buffer and calls the existing CreateImage(ReadOnlySpan<byte>), at the cost of a second copy. It is BGRA premultiplied like the rest of the interface and takes no pixel format.

  • The error, empty and SKCodec fallback paths are unchanged, as is the DecodePixelWidth/DecodePixelHeight path.

Measurements

Release SamplesApp in Chrome (interpreter, no AOT) on a busy machine, so times are noisy. A temporary harness, not in this PR, decodes a 4000x2667 JPEG through ReadFromStreamAsCompositionSurface 20 times, each surface disposed at once, then holds six. Two fresh-page runs per build, Skia codec:

master this PR
UI thread from the worker's response to the surface (median per decode) 46–51 ms 19–31 ms
UI thread before handing the next image to the worker (median) 27–33 ms 0.6–1.1 ms
Managed allocation per decode 42.0 MiB 1.3 MiB (the encoded bytes)
Managed heap peak above the start of the 20 decodes 123 MiB 1 MiB
wasm memory after the 20 decodes 544 MiB 378 MiB
wasm memory with six held (and at the end) 653–749 MiB 544 MiB

The pre-worker time on master is most likely the major collection the previous decode's array sets off. The managed decoder measures the same as Skia with this PR. Displaying an image still adds a managed copy when its texture is created, which is a separate change.

Tests

  • Given_BitmapSource.When_Browser_Decodes_Then_Image_Holds_Bgra_Premultiplied (WebAssembly): red, green, blue and half-transparent pixels come out of the decode as BGRA premultiplied. It first checks that the worker itself decodes the PNG, since a worker failure falls back to SKCodec with the same pixels.
  • Given_BitmapSource.When_Browser_Workers_Are_Reused now expects BGRA from the worker.
  • Given_ImageEncoderDecoder (Skia): the Skia and managed overrides hold the written pixels in the memory that was written, and a codec that implements only the other members gets the same pixels through the default (the repository's first generic default interface method; it passes on WebAssembly and desktop).

Both WebAssembly tests fail on master's decode code. Taken out one at a time, each part of the change fails a test: the worker swap, the set in copyPixels, SetImmutable in the Skia override, the in-place write in the managed override, and the writer call in the default.

Runs of Given_BitmapSource, Given_BitmapImage, Given_Image, Given_ImageBrush, Given_WriteableBitmap, Given_RenderTargetBitmap and Given_ImageEncoderDecoder; the one failure, When_WriteableBitmap_Assigned_With_Data_Present, decodes nothing and fails the same way without this change on this machine (125% scaling):

  • WebAssembly: 71 passed, 8 skipped, 2 inconclusive, 1 failed.
  • WebAssembly with WebGPU: same.
  • WebAssembly with the managed decoder: same, plus the two AnimatedWebP tests, since that decoder declines animated WebP.
  • Skia desktop: 74 passed, 6 skipped, 1 inconclusive, 1 failed.

After the review, on the rebased branch: Given_BitmapSource, Given_BitmapImage and Given_ImageEncoderDecoder on WebAssembly, 21 passed and 4 skipped.

PR Checklist ✅

Copilot AI balanced review requested due to automatic review settings October 16, 2026 21:10
@github-actions github-actions Bot added the platform/wasm 🌐 Categorizes an issue or PR as relevant to the WebAssembly platform label Oct 16, 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.

🟢 Approval recommended

Inspection supports correct pixel conversion, buffer ownership, and backward compatibility, with targeted regression coverage and no unresolved findings.

No open issues 🎉

What changed in this PR

Addresses #25541 by reducing WebAssembly image-decoding allocations and UI-thread work.

Changes:

  • Moves the red/blue channel swap into the browser worker.
  • Adds direct pixel writes into image storage, with a backward-compatible default implementation.
  • Adds regression tests for pixel format, buffer ownership, and codec compatibility.
File Description
src/​Uno.UI/​UI/​Xaml/​Media/​Imaging/​ImageSourceHelpers.cs Copies browser pixels directly into image storage.
src/​Uno.UI.RuntimeTests/​Microsoft/​UI/​Xaml/​Media/​Imaging/​Given_BitmapSource.cs Verifies browser-decoded BGRA premultiplied pixels.
src/​Uno.UI.RuntimeTests/​Microsoft/​UI/​Composition/​Given_ImageEncoderDecoder.cs Tests in-place writes and default codec compatibility.
src/​Uno.UI.Runtime.WebAssembly.Browser/​ts/​Runtime/​ImageLoader.ts Swaps channels in the worker and copies pixels synchronously.
src/​Uno.UI.Composition.Skia/​Composition/​Uno/​Drawing/​SkiaImageDecoderBackend.cs Shares immutable bitmap storage without another copy.
src/​Uno.UI.Composition.Managed/​ManagedImageDecoderBackend.cs Writes directly into owned native storage.
src/​Uno.UI.Composition.Drawing/​IImageEncoderDecoder.cs Adds the pixel-writer overload with a compatibility fallback.

Review effort: Balanced

mikernet added a commit to Singulink/uno that referenced this pull request Oct 16, 2026
Port of unoplatform#25542 (0cd0264, 89469e5 and 045ab0e).

The browser decode copied each image into a managed byte[] (40.7 MiB for
a 4000x2667 image, in the large object space until a major collection)
and then copied that array into the native image.
- The decoded bytes are read as a JSObject, and a new copyPixels
  JSImport copies them once, within the same synchronous call, into the
  pixel memory of an SKBitmap passed as a MemoryView span. It throws
  when the lengths differ rather than leave part of the image
  uninitialized.
- The bitmap is made immutable before SKImage.FromBitmap, which then
  shares its pixels instead of copying them.
- A worker reply without bytes gives an empty image, as on master.
- Tests: When_Browser_Decodes_Then_Image_Holds_Rgba_Premultiplied
  (WebAssembly) and When_Image_Pixels_Are_Written_In_Place_Then_It_Holds_Them.

6.8 differences:
- The image stays RGBA premultiplied with no swap. 0cd0264 moves an
  R/B swap from the UI thread into the worker, but 6.8 never swapped:
  it gives Skia the worker's RGBA as is. So neither that commit nor its
  BGRA test expectations are ported.
- 6.8 has no image codec seam (IImageEncoderDecoder, CompositionImageSurface),
  so 89469e5's in-place CreateImage overload becomes
  ImageSourceHelpers.CreateImage, Skia only, and the browser branch
  wraps its SKImage in a SkiaCompositionSurface as before.
- SkiaSharp is 3.119 here (4.151 upstream). Its FromBitmap shares an
  immutable bitmap's pixels too: the in-place test, upstream's
  When_Skia_Image_Pixels_Are_Written_In_Place_Then_It_Holds_Them,
  fails without SetImmutable.
- The decode test reads the pixels with PeekPixels and checks the color
  type: the SKCodec fallback decodes to BGRA, so RGBA shows the browser
  decoded the image.
mikernet added a commit to Singulink/uno that referenced this pull request Oct 17, 2026
Port of unoplatform#25559 (e61fa84, 98c5b27, e1e1955,
2d0e812, 6f7e0bb and d89edf0), the follow-up to unoplatform#25128, on top
of the unoplatform#25124 port.

With the bitmap cache on, the decode shared by the BitmapImages that
load the same uri and decode size was owned by an LRU of
MaxBitmapImageCacheCount (100) entries, released by no source.
- SharedImageDecode counts a shared decode's uses (the opens waiting for
  it and the sources whose subscribers draw it or were given it). Once
  it has none, it waits on PendingImageReleases like an owned decode
  (1 s and MaxUndisplayedImageBytes, oldest first), then frees its
  frames and leaves the cache. Sources are held weakly, and a collected
  source's uses are ended on the UI thread by a finalizable object only
  it holds. A subscriber back with a shared decode its source replaced
  uses it again until it draws the replacement.
- EncodedImageCache keeps the encoded bytes of images downloaded over
  http or https, bounded by the new MaxBitmapImageCacheBytes (64 MB on
  desktop, 32 MB on Android, iOS, tvOS and WebAssembly), least recently
  used first, and drops bytes unused for 5 minutes. Only successful,
  unredirected responses without no-store, no-cache or max-age=0 are
  kept. Turning EnableBitmapImageCache off drops them, checked under the
  cache's lock. AppDataUriEvaluator.DownloadAsync reports whether a
  response may be reused.
- MaxBitmapImageCacheCount is obsolete and has no effect.
- feature-flags.md describes the bitmap cache settings.
- Tests: Given_Image_Release (76 cases), GatedImageServer's extra
  header, status and redirect, and on WebAssembly a stand-in for fetch.

6.8 differences:
- As in the unoplatform#25124 port: SkiaCompositionSurface instead of
  CompositionImageSurface (a shared decode counts its frames only), the
  tests' TrackingDecoder over FrameProviderFactory, and SurfaceOf in
  ImageSource.crossruntime.cs.
- SharedImageDecode is crossruntime, like ImageSource and
  PendingImageReleases, so its surface access, byte count and release
  are Skia only. ImageData.Share is crossruntime too; Android and iOS
  never shared data.
- The decode split (ReadAllAsync, DecodeAsCompositionSurface) keeps the
  ImageSourceHelpers of the unoplatform#25542 and unoplatform#25544 ports: the browser decode
  into native memory, and MayBeAnimated from the bytes in place of
  upstream's attemptLoadingWithBrowserCanvasApi. A cached buffer is
  decoded through a read-only stream.
- Uno.UWP keeps LRUCache, which TextBlock (Android), UnicodeText (Skia)
  and Shape (native WebAssembly) still use on 6.8.

@MartinZikmund MartinZikmund left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed by reading the code against this PR's head. I haven't built or run it, so I didn't independently reproduce the measurements.

I found no correctness issues:

  • Worker pass: the combined premultiply and R/B swap is right, since r and a are read before anything they depend on is overwritten.
  • Consumers: ImageSourceHelpers is the only product consumer of the worker's result, so nothing else still expects RGBA.
  • Copy: copyPixels stays synchronous within the MemoryView's lifetime, and the worker's Uint8Array is disposed promptly through the JSObject.
  • CreateImage<TState>: the Skia, managed and default implementations each look right. It also works well with #25548: the immutable bitmap's pixels can then be shared by the texture, so a displayed image stays single-copy.

One validation gap: the description says the numbers are from the interpreter, and this is the repository's first generic default interface method. A quick decode test on a WebAssembly AOT build would be worth having before merge.

@MartinZikmund

Copy link
Copy Markdown
Member

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 1 pipeline(s).

@unodevops

Copy link
Copy Markdown
Contributor

🤖 Your WebAssembly Sample App stage site is ready! Visit it here:

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 244607 found UI Test snapshots differences: skia-linux-screenshots: 2458, skia-windows-screenshots: 2458

Details
  • skia-linux-screenshots: 2458 changed over 2496

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AnimatedIconPage.png-dark
    • AppBarButtonWithIconTest.png-dark
    • AppBarToggleButtonTest.png
    • ApplicationViewSpanningRectsPage.png
    • AppWindowPositionAndSize.png-dark
    • ArcSegment.png-dark
    • Attributed_text_Simple.png-dark
    • AuthenticationBroker_Demo.png
    • AutomationProperties_AutomationId.png-dark
    • AutomationProperties_AutomationId.png
    • AutoSuggestBoxChosenSuggestion.png-dark
    • AutoSuggestBoxChosenSuggestion.png
    • AutoSuggestBox_Reason.png-dark
    • AutoSuggestBox_Reason.png
    • Basics Pivot Test.png-dark
    • Basics Pivot Test.png
    • Battery.png-dark
    • Battery.png
    • BezierSegment.png-dark
    • BezierSegment.png
  • skia-windows-screenshots: 2458 changed over 2496

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AnimatedIconPage.png-dark
    • AnimatedVisualsTestbedPage.png-dark
    • AppBarButtonTest.png-dark
    • AppBarButtonWithIconTest.png
    • AppBar_KeyBoard.png
    • ApplicationViewSizing.png
    • AppWindowClosing.png-dark
    • AppWindowPositionAndSize.png
    • AppXamlDefinedResources.png-dark
    • AppXamlDefinedResources.png
    • Attributed_text_Supserscript.png-dark
    • Attributed_text_Supserscript.png
    • AutoBorderStretchwithleftmargin.png-dark
    • AutoBorderStretchwithleftmargin.png
    • AutomationProperties_Landmark.png-dark
    • AutomationProperties_Landmark.png
    • AutoSuggestBox_BitmapIcon.png-dark
    • AutoSuggestBox_BitmapIcon.png
    • BackGesture.png-dark
    • BackGesture.png

@mergify

mergify Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue). If it does not match the queue conditions yet, it enters the queue once it does.

  • Queue this pull request

@Xiaoy312 Xiaoy312 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.

Reviewed against 045ab0e36a by reading the code and the CI results of build 244607; not built locally.

No correctness issues found:

  • Worker pass: the combined premultiply and R/B swap is right (r is saved before slot 0 is overwritten, a is never written), and copyPixels stays synchronous within the MemoryView's lifetime.
  • Call site: new CompositionImageSurface(image) does the same as the old CopyPixels (CreateFrames → FrameProviderFactory.Create), and the bytes JSObject is now released promptly.
  • Overrides: the Skia, managed and default implementations each release their memory when the writer throws. A public default interface method fits the seam, since the managed backend deliberately has no IVT to Uno.UI.Composition.Drawing. Wrapping codecs such as the test-only TrackingDecoder fall through to the default and keep working.

On the AOT question: in build 244607, When_Codec_Does_Not_Override_Then_Default_Copies_Written_Pixels (the generic default interface method) and both in-place tests passed on iOS (Mono AOT), Android, WebAssembly (interpreter), Windows, macOS and Linux, and When_Browser_Decodes_Then_Image_Holds_Bgra_Premultiplied passed on WebAssembly. Only WebAssembly AOT is unexercised, and the built-in codecs override the method anyway, so the default only runs for third-party codecs.

CI: the red checks look unrelated: the Managed Binaries build failed downloading Silk.NET's libEGL.dylib (MSB3923), the Linux snapshot job lost its X11 connection (exit 139), and WinAppSDK shows only flaky retries. The branch is based on 10-16 master, so it needs a fresh run before merge.

Nits, non-blocking:

  1. Given_BitmapSource.When_Browser_Workers_Are_Reused gains [GitHubWorkItem("…/issues/25541")], but that test predates this change ("Harden the browser worker decode test"); here only its expected channel order changes. The attribute reads as "this test was written for #25541", so I'd keep it on the new When_Browser_Decodes_Then_Image_Holds_Bgra_Premultiplied only.
  2. ImageLoader.copyPixels(source: Uint8Array, destination: any): a structural type such as { length: number; set(source: Uint8Array): void } would put the MemoryView contract in the signature rather than only in the comment.

The browser decode returned RGBA pixels, and because the image surface
takes BGRA the UI thread then swapped R and B in a managed loop over
every pixel: 10.7 million iterations for a 4000x2667 image. The worker
already loops over every pixel to premultiply the alpha, so it now
swaps R and B in the same pass and returns BGRA premultiplied.
IImageEncoderDecoder.CreateImage copies the pixels it is given, so a
caller whose pixels are not in managed memory, such as the browser
decode, first needs a buffer of the full image size. The new overload
has the caller write an image's BGRA premultiplied pixels, and a
backend that overrides it has them written into the image's own
storage, so they are copied once.

Skia writes into an SKBitmap and makes it immutable before wrapping it
with SKImage.FromBitmap, which then shares its pixels instead of
copying them. The managed backend writes into the native buffer its
image already owns. A codec that doesn't override the overload gets a
default that writes into a temporary native buffer and copies it with
the existing CreateImage, so codecs written before it keep working.
The UI thread copied each browser-decoded image into a managed byte[]
and then copied that array into the native image. At 4000x2667 the
array is 40.7 MiB in the large object space, freed only by a major
collection, and the wasm linear memory it may grow never shrinks.

The image's own storage is now passed to JavaScript as a MemoryView
span, which copyPixels fills from the worker's buffer within the same
synchronous call, so the decode allocates nothing managed of the
image's size beyond the encoded bytes. copyPixels throws when the
lengths differ rather than leave part of the image uninitialized.
@Xiaoy312
Xiaoy312 force-pushed the dev/mikernet/wasm-decode-no-managed-copy branch from 045ab0e to bca6f78 Compare November 11, 2026 22:56
@Xiaoy312

Copy link
Copy Markdown
Contributor

@mikernet I rebased this branch onto current master (no conflicts; your three commits are unchanged apart from the base) and force-pushed it, so CI runs against an up-to-date base. Before pushing more work, sync your local branch, e.g. git fetch then git reset --hard @{u}.

@Xiaoy312

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
1 pipeline(s) were filtered out due to trigger conditions.

@unodevops

Copy link
Copy Markdown
Contributor

🤖 Your WebAssembly Sample App stage site is ready! Visit it here:

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 245599 found UI Test snapshots differences: skia-linux-screenshots: 214, skia-windows-screenshots: 301

Details
  • skia-linux-screenshots: 214 changed over 2496

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AnimatedBackVisualSourceSamplePage.png-dark
    • AutomationProperties_AutomationId.png-dark
    • Border_CornerRadius_Binding.png-dark
    • Border_CornerRadius_Binding.png
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • AnimatedBackVisualSourceSamplePage.png
    • AutomationProperties_AutomationId.png
    • BenchmarkDotNet.png-dark
    • BenchmarkDotNet.png
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • CornerRadiusControls.png-dark
    • CornerRadiusControls.png
    • AnimatedVisualsTestbedPage.png
    • AnimatedVisualsTestbedPage.png-dark
    • AutomationProperties_StructureAndProps.png-dark
    • AutomationProperties_StructureAndProps.png
    • BasicAcrylicBrushTest.png-dark
    • BasicAcrylicBrushTest.png
  • skia-windows-screenshots: 301 changed over 2496

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AnimatedBackVisualSourceSamplePage.png
    • AutomationProperties_StructureAndProps.png-dark
    • AutomationProperties_StructureAndProps.png
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • AnimatedBackVisualSourceSamplePage.png-dark
    • BasicAcrylicBrushTest.png-dark
    • BasicAcrylicBrushTest.png
    • Border_CornerRadius_BorderThickness.png-dark
    • Border_CornerRadius_BorderThickness.png
    • BasicAcrylicBrushTest2.png-dark
    • BasicAcrylicBrushTest2.png
    • Border_CornerRadius_Binding.png-dark
    • Border_CornerRadius_Binding.png
    • Buttons.png-dark
    • Buttons.png
    • ClipboardTests.png-dark
    • ClipboardTests.png
    • AnimatedVisualsTestbedPage.png
    • Basics.png-dark

The destination is a MemoryView: say what it has to provide in the
signature instead of any. Also keep the issue link only on the test
written for it; When_Browser_Workers_Are_Reused predates this change.
@mikernet

Copy link
Copy Markdown
Contributor Author

Synced to the rebased branch and took both nits in 6e66897:

  1. [GitHubWorkItem] on When_Browser_Workers_Are_Reused: removed. It is now only on When_Browser_Decodes_Then_Image_Holds_Bgra_Premultiplied.
  2. copyPixels destination: typed as { length: number; set(source: Uint8Array): void }, so the signature states what the MemoryView has to provide.

On the WebAssembly AOT question (@MartinZikmund): I haven't run an AOT build. As Xiaoy312 found in build 244607, the generic default interface method passed under Mono AOT on iOS, and the browser decode passed on WebAssembly under the interpreter. The built-in codecs (Skia and managed) override CreateImage<TState>, so on WebAssembly the default only runs for a third-party codec. A local WebAssembly AOT build is slow and I don't expect it to show anything the iOS run didn't, but I can run one if you want it before merge.

WebAssembly (Release, interpreter) with these changes: Given_BitmapSource, Given_BitmapImage and Given_ImageEncoderDecoder pass (21 passed, 4 skipped), including both browser decode tests.

mikernet added a commit to Singulink/uno that referenced this pull request Nov 12, 2026
Port of unoplatform#25542 commit 6e66897. The destination is a
MemoryView: the signature now says what it has to provide instead of
any. The test-attribute part of that commit doesn't apply here (6.8's
When_Browser_Workers_Are_Reused never had the issue link).

@MartinZikmund MartinZikmund left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @mikernet, both nits are addressed and the AOT answer works for me: the built-in codecs override the generic method, so the default only runs for third-party codecs, and iOS Mono AOT already runs it. I re-checked the worker swap and premultiply pass (r/a are read before the slots are overwritten), the synchronous MemoryView copy, the immutable SKBitmap → SKImage.FromBitmap share and the JS object disposal. All fine, and CI is green.

On the sibling imaging PRs: this one merges cleanly with #25548, #25559, #25561 and #25566 (checked with git merge-tree). The CountingImageCodec added in #25561/#25566 doesn't forward CreateImage<TState>, so it falls back to the default, which still goes through its counted CreateImage. Nothing to change here.

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.

[WASM] Image decode copies the pixels through managed memory and swaps R/B on the UI thread

6 participants