Repository navigation
Conversation
There was a problem hiding this comment.
🟢 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
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.
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
left a comment
There was a problem hiding this comment.
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
randaare read before anything they depend on is overwritten. - Consumers:
ImageSourceHelpersis the only product consumer of the worker's result, so nothing else still expects RGBA. - Copy:
copyPixelsstays synchronous within theMemoryView's lifetime, and the worker'sUint8Arrayis disposed promptly through theJSObject. 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.
|
/azp run |
|
Azure Pipelines successfully started running 1 pipeline(s). |
|
🤖 Your WebAssembly Sample App stage site is ready! Visit it here: |
|
The build 244607 found UI Test snapshots differences: Details
|
|
Tick the box to add this pull request to the merge queue (same as
|
Xiaoy312
left a comment
There was a problem hiding this comment.
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 (
ris saved before slot 0 is overwritten,ais never written), andcopyPixelsstays synchronous within theMemoryView's lifetime. - Call site:
new CompositionImageSurface(image)does the same as the oldCopyPixels(CreateFrames→FrameProviderFactory.Create), and thebytesJSObject 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-onlyTrackingDecoderfall 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:
Given_BitmapSource.When_Browser_Workers_Are_Reusedgains[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 newWhen_Browser_Decodes_Then_Image_Holds_Bgra_Premultipliedonly.ImageLoader.copyPixels(source: Uint8Array, destination: any): a structural type such as{ length: number; set(source: Uint8Array): void }would put theMemoryViewcontract 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.
045ab0e to
bca6f78
Compare
|
@mikernet I rebased this branch onto current |
|
/azp run |
|
Azure Pipelines: Successfully started running 1 pipeline(s). 1 pipeline(s) were filtered out due to trigger conditions. |
|
🤖 Your WebAssembly Sample App stage site is ready! Visit it here: |
|
The build 245599 found UI Test snapshots differences: Details
|
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.
|
Synced to the rebased branch and took both nits in 6e66897:
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 WebAssembly (Release, interpreter) with these changes: |
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
left a comment
There was a problem hiding this comment.
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.
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
IImageEncoderDecoderoverload,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 aMemoryView(ImageLoader.copyPixels), which fills it from the worker's buffer withsetin the same synchronous call, and throws on a length mismatch (existing error path). Skia writes into an immutableSKBitmapthatSKImage.FromBitmapshares rather than copies; the managed decoder (ManagedBackend.CreateImageDecoder()) writes into the buffer itsManagedImageowns.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 existingCreateImage(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/DecodePixelHeightpath.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
ReadFromStreamAsCompositionSurface20 times, each surface disposed at once, then holds six. Two fresh-page runs per build, Skia codec: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 toSKCodecwith the same pixels.Given_BitmapSource.When_Browser_Workers_Are_Reusednow 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
setincopyPixels,SetImmutablein 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_RenderTargetBitmapandGiven_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):AnimatedWebPtests, since that decoder declines animated WebP.After the review, on the rebased branch:
Given_BitmapSource,Given_BitmapImageandGiven_ImageEncoderDecoderon WebAssembly, 21 passed and 4 skipped.PR Checklist ✅
Screenshots Compare Test Runresults.