Repository navigation
Conversation
There was a problem hiding this comment.
🔵 Needs a closer look
Cross-platform native release callbacks and finalizer-thread ownership warrant human confirmation despite the targeted regression coverage.
No open issues 🎉
What changed in this PR
Addresses #25547 by letting Skia textures share decoded image pixels, reducing duplicate memory and temporary allocations while preserving independent lifetimes.
Changes:
- Adds reference-counted pixel sharing with a copy fallback.
- Validates
CopyPixelsdestination size and read failures. - Documents ownership and adds lifetime regression tests.
| File | Description |
|---|---|
| src/Uno.UI.RuntimeTests/Microsoft/UI/Xaml/Documents/Given_GlyphRunRenderer.cs | Tests cached texture survival after inline-image changes. |
| src/Uno.UI.RuntimeTests/Microsoft/UI/Composition/Given_SkiaTexture.cs | Tests pixel sharing, disposal order, recordings, and buffer validation. |
| src/Uno.UI.Composition.Skia/Composition/Uno/Drawing/SkiaTexture.cs | Wraps shared pixels with reference-counted ownership. |
| src/Uno.UI.Composition.Skia/Composition/Uno/Drawing/SkiaImage.cs | Rejects short destinations and failed pixel reads. |
| src/Uno.UI.Composition.Skia/Composition/Uno/Drawing/SkiaDrawingFactory.cs | Prefers shared pixels over copying Skia images. |
| src/Uno.UI.Composition.Drawing/IImage.cs | Documents required destination capacity. |
| src/Uno.UI.Composition.Drawing/IDrawingFactory.cs | Documents shared-pixel ownership. |
Review effort: Balanced
2a3634f to
a9c642d
Compare
|
🤖 Your Docs stage site is ready! Visit it here: https://unodocsprstaging.z13.web.core.windows.net/pr-25548/docs/index.html |
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 or the runtime results for the release callback.
I found no correctness issues:
- Pixel format: every
SkiaImagecreation path I checked uses BGRA premultiplied, so wrapping the pixels instead of copying them throughReadPixelsshouldn't change how they draw. - Lifetime: the
AddRef/release-proc pairing looks right, including the rejected-pixmap path, and either the image or the texture can be disposed first. - Accounting:
DecodedByteCountcounts a shared frame once, and a copied texture still counts.
Two notes:
CompositionImageSurface.HasTextureis only used by a test.- This conflicts with #25559 in
feature-flags.mdandFeatureConfiguration.cs, so whichever merges second needs to reconcile the wording about what counts towardMaxUndisplayedImageBytes.
|
/azp run |
|
Azure Pipelines successfully started running 2 pipeline(s). |
|
🤖 Your Docs stage site is ready! Visit it here: https://unodocsprstaging.z13.web.core.windows.net/pr-25548/docs/index.html |
|
The build 244605 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 a9c642d by reading the code (not built locally), plus the results of CI build 244605.
- Lifetime: the
AddRef/release-proc pairing frees the pixels exactly once on every path: image disposed first, texture disposed first, a recording outliving both, and a pixmap Skia rejects. Nothing disposes aSkiaImage'sSKImagedirectly, so nothing bypasses the reference count. - Every way a
SkiaImageis created (decoder single-frame and animated,SkiaImageDecoderBackend.CreateImage,SnapshotAsync) yields an immutable raster image, BGRA premultiplied, with no color space, so the shared pixels draw the same as the old copy. - The new
CopyPixelslength check: I checked every caller. None passes a short buffer.WriteableBitmap.SetSourcereads the new image's size beforeOnSetSourceresizes its buffer, andRenderTargetBitmapsizes its buffer to the snapshot. - New tests: all 11 passed on 7–8 runtime-test lanes in build 244605.
CI: none of the 3 red checks comes from this PR, but it needs a new run before merge.
- Managed Binaries is a 504 downloading the Silk.NET ANGLE dylib (infrastructure).
- Desktop Linux Snapshot is a segfault about 55 s after
BenchmarkDotNet.png. The same crash at the same step hit #25738 (build 244603), which shows the same 2458/2458 screenshot counts, so those come from the crash, not from this PR.
The inline comments are nits, none blocking.
The test waited on CompositionImageSurface.HasTexture, which only it used. Taking a screenshot of the image draws it, so its surface holds the texture by then, and the surface keeps its original API.
ITexture.SharesImagePixels now states its contract only; the memory accounting it feeds stays on DecodedByteCount, in the layer that owns that policy. The MaxUndisplayedImageBytes docs say a separate texture copy counts without naming decoders and backends.
a9c642d to
0aa6ea1
Compare
|
Addressed the nits, and rebased onto current master so CI picks up #26205's fix for the Linux snapshot crash (the three reviewed commits are unchanged apart from their SHAs).
Skia desktop after the rebase: |
|
🤖 Your Docs stage site is ready! Visit it here: https://unodocsprstaging.z13.web.core.windows.net/pr-25548/docs/index.html |
MartinZikmund
left a comment
There was a problem hiding this comment.
Thanks for addressing the nits, @mikernet! Second pass on 0aa6ea1: the AddRef/release-proc lifetime holds whichever of image, texture or recording goes first. Every SkiaImage source is an immutable raster copy, so nothing can mutate the shared pixels. ReleaseFrames still drops the texture before the frames, and CI is green.
This also composes with #25542: its SetImmutable + FromBitmap image peeks fine, so the texture shares it too. The only overlap left is the #25559 wording you already acknowledged.
GitHub Issue: closes #25547
PR Type:
🐞 Bugfix
What changed? 🚀
On every Skia target,
SkiaDrawingFactory.CreateTexture(IImage)copied the image into a new managedbyte[]withIImage.CopyPixels, then copied that into a secondSKImagewithSKImage.FromPixelCopy.CompositionImageSurfacekeeps that texture for as long as it shows the frame, and its frame provider keeps the decodedSkiaImagetoo, so every displayed image was held twice. Each texture creation also allocated a temporary array of the same size on the large object heap, and an animated image paid both costs on every frame change. On WebAssembly, linear memory never shrinks.SKImage, and aSkiaImagealready holds raster pixels.CreateTexturenow wraps them in anSKImageof its own withSKImage.FromPixels(image.PeekPixels(), releaseProc), without copying them. The texture takes a reference on the image withAddRef, which is howIDrawingResourcesays to hold a resource you did not create, and the release proc gives it back once Skia lets go of the pixels: when the texture is freed, when a recordedSKPicturethat drew it goes, or when the wrapper is finalized. So the pixels live until the last of them goes. TheIDrawingFactory.CreateTexturedocs now say that a backend may share the pixels.CompositionImageSurfacedisposes its texture on every frame change, on a device change and before it releases its frames, while the image is textured again.SKImageinstead would keep every frame of an animation uploaded while it plays: 30.4 MB for a 480x480 33-frame GIF and the whole 256 MiB budget at 1440x1440, on Vulkan and WebGL.ManagedImage(from the managed decoder) or aWebGpuReadbackImageis still copied as before.ITexture.SharesImagePixelstells a shared texture from a copy. It is a default interface member, false as for every texture until now, and the Skia texture sets it when it wraps aSkiaImage.CompositionImageSurface.DecodedByteCountreads it (below). TheIDrawingFactory.CreateTexturedocs point to it.ITextureyet, and as a default interface member it keeps every implementer compiling, asIGraphicsContext.IsReadyForFramedid when afix(webgpu)commit added it the same way (79a0f93).SkiaImage.CopyPixelsfails visibly (own commits). It ignoredReadPixels's result, so a failed read left a transparent image and no error; it now throwsInvalidOperationException. It also letReadPixelswrite the whole image whatever the destination's length, so a short span overran it (IImageis public, throughImageEncoderDecoder.Current); it now throwsArgumentException, where the managed and WebGPU images already stop at the destination's end. TheIImage.CopyPixelsdocs now give the size. No caller in Uno passes a short destination.Release callback (SkiaSharp 4.151.1)
GCHandleafter the call, andTryWrapgives its own reference back when the pixmap is rejected (it then falls back to the copy; a pixmap peeked from a live raster image is never rejected). The proc only calls the interlockedRelease. When that drops the last reference it disposes the sourceSKImageon whichever thread that is, the render or finalizer thread included, which is safe: SkiaSharp's handle table is behind a reader-writer lock,Disposeis guarded by an interlocked flag, and Skia's refcount is atomic.Interplay with #25124
#25124 added
CompositionImageSurface.DecodedByteCount, which counts the decoded frames plus the texture of the current one; pastMaxUndisplayedImageBytes, Uno releases undisplayed images by that count. Before this PR every Skia texture was a copy, so that was right. With the sharing, that count would see a Skia frame twice and release undisplayed images sooner than the limit asks, so it now leaves out a texture whoseSharesImagePixelsis true.A texture that holds a copy still counts, because releasing the image frees the copy too: every texture on the WebGPU renderer, and on the Skia renderer one made while the app's image decoder isn't Skia's, such as
ManagedBackend.CreateImageDecoder(). The surface has to learn which from the texture:Uno.UI.Composition.Drawingdeliberately gives the Skia backend noInternalsVisibleTo, as itsAssemblyInfo.cssays, so the Skia texture can only report it through the public interface. TheMaxUndisplayedImageBytesdocs (FeatureConfiguration.csandfeature-flags.md) say that a separate texture copy counts too.Measurements
Release SamplesApp, four 3000x3600 PNGs (43.2 MB each once decoded), decoded through
ImageEncoderDecoderfor theCreateTexturerows and opened withBitmapImage.SetSourceAsyncfor the displayed ones, a fresh process or page per run. "Before" is this branch with the sharing taken out ofCreateTexture, which is master's code for it. Private bytes and the GC's committed bytes are measured after a full collection.Desktop (Windows, Skia on Vulkan):
CreateTextureon the four decoded images: private bytesImageelements: private bytesBefore, the 345 MB were the four 43.2 MB copies (173 MB) plus 169 MB of GC heap that the temporary arrays left committed after the collection. Displaying the images costs about 400 MB in both builds besides that: the decoded images themselves (173 MB) and what the decode and the renderer allocate.
WebAssembly (Chrome, Skia on WebGL), wasm memory size (
HEAPU8.length), which never shrinks:CreateTextureon the four decoded images: wasm memoryImageelements: wasm memoryThe displayed rows differ by 105 MB rather than the four 43 MB copies, because the wasm memory is a high-water mark that grows in steps and reuses what the decode freed. The 174 MB of managed allocations left after the change come from the browser decode (
ImageSourceHelpers.ReadFromStreamAsCompositionSurface), which on WebAssembly copies each decoded image through a managed array (#25541); desktop decodes without one.GPU resource cache (
GRContext.GetResourceCacheUsage) whileanimated.gif(33 frames) plays for four loops, the 1440x1440 case scaled up throughDecodePixelWidth: it grows by 2.9 MB at 480x480 and 25.0 MB at 1440x1440 on desktop Vulkan, and by 1.8 MB and 16.6 MB on WebGL, the same before and after the change.Tests
New runtime tests (Skia):
Given_SkiaTextureWhen_Created_From_A_SkiaImage_Then_It_Wraps_Its_Pixels: the texture'sSKImageis a different image over the same pixels.When_Image_Is_Disposed_First_Then_The_Texture_Still_Draws: after the image is disposed, the texture still draws it; disposing the texture then frees the pixels.When_Texture_Is_Disposed_First_Then_The_Image_Stays_Alive: the image outlives its texture, and its pixels are freed with it.When_Surface_Textures_Its_Image_Again_Then_The_Image_Still_Draws: aCompositionImageSurfacetextures its image for one factory and then for another, which disposes the first texture, as a frame or device change does. The image is still alive, the new texture draws it, and disposing the surface frees the pixels.When_A_Recording_Outlives_The_Texture_And_Image_Then_It_Still_Draws: a recording that drew the texture still replays it after both are disposed, and disposing the recording frees the pixels.When_Surface_Texture_Shares_The_Frame_Pixels_Then_They_Are_Counted_Once: aCompositionImageSurfaceover aSkiaImagecounts its pixels once, before and after texturing it.When_Surface_Texture_Copies_The_Frame_Pixels_Then_The_Copy_Is_Counted: one over an image from the managed decoder counts the frame and the texture's copy of it.When_CopyPixels_Destination_Is_Too_Short_Then_It_Throws.Given_Image_Release.When_Drawn_Image_Waits_Then_Its_Pixels_Count_Once: anImage, drawn by a screenshot so that its surface holds a texture, is removed under a limit of exactly its decoded size, and keeps its pixels. Excluded on WebGPU, whose textures are copies.Given_GlyphRunRenderer.When_Inline_Image_Data_Changes_Then_A_Clone_Still_Draws_Its_Texture: new data disposes the original's decoded image while the texture cache still hands the texture made from it to a clone.Mutation checks on desktop, each a build with one change: to the Skia backend in the first four rows, and to
CompositionImageSurface(Uno.UI.Composition) in the last two.CreateTextureWhen_Created_From_A_SkiaImage_Then_It_Wraps_Its_Pixels,When_A_Recording_Outlives...; the other lifetime tests pass with a copy, as they shouldWhen_Image_Is_Disposed_First...,When_Texture_Is_Disposed_First...,When_Surface_Textures_Its_Image_Again...,When_A_Recording_Outlives...When_Texture_Is_Disposed_First...; in a full runWhen_Surface_Textures_Its_Image_Again...then crashes the process, texturing an image that was already freedCopyPixelslength check removedWhen_CopyPixels_Destination_Is_Too_Short...DecodedByteCountcounts every texture again, shared or notWhen_Surface_Texture_Shares_The_Frame_Pixels...,When_Drawn_Image_Waits_Then_Its_Pixels_Count_OnceDecodedByteCountcounts no textureWhen_Surface_Texture_Copies_The_Frame_Pixels...Run locally after a rebase on master, on Release builds with
UnoFastDevBuild=true: on Windows desktop at 125% display scale, and on WebAssembly in headless Chrome. The new tests pass on both. The 21 existing image, brush, icon and composition classes (listed below): on desktop 157 passed, 3 failed, 1 inconclusive and 5 skipped; on WebAssembly 147 passed, 1 inconclusive and 16 skipped.Given_Image_Release(#25124's tests and the new one): 60 passed on desktop, and 34 passed with 25 desktop-only ones skipped on WebAssembly. The three desktop failures fail the same way on master:Given_RevealBrush.When_RevealBrush_Assigned(anActualHeightof 34.4 instead of 34) andGiven_WriteableBitmap.When_WriteableBitmap_Assigned_With_Data_Present(a logical rectangle checked on a physical-pixel screenshot) because of the 125% scale, andGiven_BitmapIcon.When_Foreground_Changed_With_ShowAsMonochrome_True, whose first screenshot finds the icon not drawn yet; it passed when its class ran alone. The screenshots in these classes are taken withRenderTargetBitmap, andGiven_Image.When_AnimatedWebP_Changes_Framescovers an animated frame change. After the review, rebased on master again (to pick up #26205) and rerun on desktop:Given_Image_Release,Given_SkiaTextureandGiven_GlyphRunRenderer, 77 of 77 passed, and the "counts every texture again" mutation still fails both of its tests. Separately, Release builds with the analyzers on (noUnoFastDevBuild, net11.0) ofUno.UI,Uno.UI.Composition.WebGpuand the runtime tests have no warnings.Existing classes run
Given_Image,Given_ImageBrush,Given_ImageSource,Given_BitmapImage,Given_BitmapSource,Given_WriteableBitmap,Given_RenderTargetBitmap,Given_BitmapIcon,Given_IconSourceElement,Given_EffectBrush_Parity,Given_AcrylicBrush,Given_XamlCompositionBrushBase,Given_CompositionVisualSurface,Given_ContainerVisual,Given_SkiaDrawingSession,Given_GlyphRunRenderer,Given_SvgImageSource_ManagedEngine,Given_ManagedLottie,Given_BitmapEncoder,Given_RevealBrush,Given_GradientBrush. The inconclusive ones opt out by themselves:When_Render_Border_GetPixelsAsyncat a scale other than 100%, andWhen_Transitive_Asset_With_Link_Loadedon WebAssembly.PR Checklist ✅
Screenshots Compare Test Runresults.