Skip to content

fix(skia): Share a decoded image's pixels with its texture - #25548

Open
mikernet wants to merge 5 commits into
unoplatform:masterfrom
mikernet:dev/mikernet/skia-texture-shares-image
Open

mikernet wants to merge 5 commits into
unoplatform:masterfrom
mikernet:dev/mikernet/skia-texture-shares-image

Conversation

@mikernet

@mikernet mikernet commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

GitHub Issue: closes #25547

PR Type:

🐞 Bugfix

What changed? 🚀

On every Skia target, SkiaDrawingFactory.CreateTexture(IImage) copied the image into a new managed byte[] with IImage.CopyPixels, then copied that into a second SKImage with SKImage.FromPixelCopy. CompositionImageSurface keeps that texture for as long as it shows the frame, and its frame provider keeps the decoded SkiaImage too, 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.

  • The texture shares the image's pixels. On the Skia backend a texture is just an immutable SKImage, and a SkiaImage already holds raster pixels. CreateTexture now wraps them in an SKImage of its own with SKImage.FromPixels(image.PeekPixels(), releaseProc), without copying them. The texture takes a reference on the image with AddRef, which is how IDrawingResource says 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 recorded SKPicture that drew it goes, or when the wrapper is finalized. So the pixels live until the last of them goes. The IDrawingFactory.CreateTexture docs now say that a backend may share the pixels.
    • Either can go first. The inline-image state disposes its decoded image when its data changes, while the texture cache, keyed on the encoded bytes, keeps handing the texture made from it to a clone that kept those bytes. CompositionImageSurface disposes its texture on every frame change, on a device change and before it releases its frames, while the image is textured again.
  • The GPU behavior stays as it was. Skia caches a raster image's GPU upload under that image's ID until the image is gone. Each texture has an image of its own, so its upload still goes with the texture. Sharing the frame's own SKImage instead 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.
  • The copy stays for other images. A ManagedImage (from the managed decoder) or a WebGpuReadbackImage is still copied as before.
  • ITexture.SharesImagePixels tells 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 a SkiaImage. CompositionImageSurface.DecodedByteCount reads it (below). The IDrawingFactory.CreateTexture docs point to it.
    • It is new public API, and not a breaking change. No release contains ITexture yet, and as a default interface member it keeps every implementer compiling, as IGraphicsContext.IsReadyForFrame did when a fix(webgpu) commit added it the same way (79a0f93).
  • SkiaImage.CopyPixels fails visibly (own commits). It ignored ReadPixels's result, so a failed read left a transparent image and no error; it now throws InvalidOperationException. It also let ReadPixels write the whole image whatever the destination's length, so a short span overran it (IImage is public, through ImageEncoderDecoder.Current); it now throws ArgumentException, where the managed and WebGPU images already stop at the destination's end. The IImage.CopyPixels docs now give the size. No caller in Uno passes a short destination.

Release callback (SkiaSharp 4.151.1)

  • Runtime, from a standalone check against SkiaSharp 4.151.1 on Windows and from the lifetime tests on desktop and WebAssembly: disposing the wrapper calls the release proc once, also when it is disposed twice; a recorded picture that drew it defers the call until the picture goes; an undisposed wrapper gets it on the finalizer thread; a pixmap Skia rejects gives a null image and never calls it. On WebAssembly the native-to-managed callback runs: the lifetime tests there can only pass if it does.
  • Code review, from the decompiled SkiaSharp 4.151.1: the proxy frees its GCHandle after the call, and TryWrap gives 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 interlocked Release. When that drops the last reference it disposes the source SKImage on whichever thread that is, the render or finalizer thread included, which is safe: SkiaSharp's handle table is behind a reader-writer lock, Dispose is 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; past MaxUndisplayedImageBytes, 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 whose SharesImagePixels is 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.Drawing deliberately gives the Skia backend no InternalsVisibleTo, as its AssemblyInfo.cs says, so the Skia texture can only report it through the public interface. The MaxUndisplayedImageBytes docs (FeatureConfiguration.cs and feature-flags.md) say that a separate texture copy counts too.

Measurements

Release SamplesApp, four 3000x3600 PNGs (43.2 MB each once decoded), decoded through ImageEncoderDecoder for the CreateTexture rows and opened with BitmapImage.SetSourceAsync for the displayed ones, a fresh process or page per run. "Before" is this branch with the sharing taken out of CreateTexture, 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):

Before After
CreateTexture on the four decoded images: private bytes +344.9 MB −4.0 MB
... managed allocations +172.8 MB 0
... GC committed +168.8 MB −4.0 MB
The four images displayed in Image elements: private bytes +753.8 MB +401.5 MB
... managed allocations +175.9 MB +3.1 MB
... GC committed +174.8 MB +2.0 MB

Before, 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:

Before After
CreateTexture on the four decoded images: wasm memory 475.4 → 788.5 MB (+313.1) 475.4 → 475.4 MB (+0)
... managed allocations +172.8 MB 0
The four images displayed in Image elements: wasm memory 330.1 → 789.8 MB (+459.7) 330.1 → 684.6 MB (+354.5)
... managed allocations +348.2 MB +173.8 MB

The 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) while animated.gif (33 frames) plays for four loops, the 1440x1440 case scaled up through DecodePixelWidth: 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_SkiaTexture
    • When_Created_From_A_SkiaImage_Then_It_Wraps_Its_Pixels: the texture's SKImage is 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: a CompositionImageSurface textures 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: a CompositionImageSurface over a SkiaImage counts 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: an Image, 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.

Mutation Tests that fail
Copy restored in CreateTexture When_Created_From_A_SkiaImage_Then_It_Wraps_Its_Pixels, When_A_Recording_Outlives...; the other lifetime tests pass with a copy, as they should
The release proc never gives the reference back (the image leaks) When_Image_Is_Disposed_First..., When_Texture_Is_Disposed_First..., When_Surface_Textures_Its_Image_Again..., When_A_Recording_Outlives...
The release proc gives it back twice When_Texture_Is_Disposed_First...; in a full run When_Surface_Textures_Its_Image_Again... then crashes the process, texturing an image that was already freed
CopyPixels length check removed When_CopyPixels_Destination_Is_Too_Short...
DecodedByteCount counts every texture again, shared or not When_Surface_Texture_Shares_The_Frame_Pixels..., When_Drawn_Image_Waits_Then_Its_Pixels_Count_Once
DecodedByteCount counts no texture When_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 (an ActualHeight of 34.4 instead of 34) and Given_WriteableBitmap.When_WriteableBitmap_Assigned_With_Data_Present (a logical rectangle checked on a physical-pixel screenshot) because of the 125% scale, and Given_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 with RenderTargetBitmap, and Given_Image.When_AnimatedWebP_Changes_Frames covers an animated frame change. After the review, rebased on master again (to pick up #26205) and rerun on desktop: Given_Image_Release, Given_SkiaTexture and Given_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 (no UnoFastDevBuild, net11.0) of Uno.UI, Uno.UI.Composition.WebGpu and 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_GetPixelsAsync at a scale other than 100%, and When_Transitive_Asset_With_Link_Loaded on WebAssembly.

PR Checklist ✅

Copilot AI balanced review requested due to automatic review settings October 16, 2026 22:49

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.

🔵 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 CopyPixels destination 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

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.

🔵 Needs a closer look

Native release-callback and finalizer ownership across Skia targets warrants human review despite the targeted regression coverage.

No open issues 🎉

Review effort: Balanced

@mikernet
mikernet force-pushed the dev/mikernet/skia-texture-shares-image branch from 2a3634f to a9c642d Compare November 5, 2026 15:03
@github-actions github-actions Bot added area/skia ✏️ Categorizes an issue or PR as relevant to Skia kind/documentation labels Nov 5, 2026
@unodevops

Copy link
Copy Markdown
Contributor

@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 or the runtime results for the release callback.

I found no correctness issues:

  • Pixel format: every SkiaImage creation path I checked uses BGRA premultiplied, so wrapping the pixels instead of copying them through ReadPixels shouldn'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: DecodedByteCount counts a shared frame once, and a copied texture still counts.

Two notes:

  • CompositionImageSurface.HasTexture is only used by a test.
  • This conflicts with #25559 in feature-flags.md and FeatureConfiguration.cs, so whichever merges second needs to reconcile the wording about what counts toward MaxUndisplayedImageBytes.

@MartinZikmund

Copy link
Copy Markdown
Member

/azp run

@azure-pipelines

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

@unodevops

Copy link
Copy Markdown
Contributor

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 244605 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
    • AppBarToggleButtonTest.png
    • ApplicationViewSpanningRectsPage.png-dark
    • AppWindowPositionAndSize.png-dark
    • ArcSegment.png
    • AuthenticationBroker_Demo.png
    • AutoBorderStretchwithtopmargin.png-dark
    • AutomationProperties_Name.png-dark
    • AutoSizedTopLeft.png-dark
    • AutoSizedTopLeft.png
    • AutoSuggestBox_Reason.png-dark
    • AutoSuggestBox_Reason.png
    • Basics Pivot Test.png-dark
    • Basics Pivot Test.png
    • BeginTime_MultipleAnimations.png-dark
    • BeginTime_MultipleAnimations.png
    • BitmapIcon_Monochromatic.png-dark
    • BitmapIcon_Monochromatic.png
    • BorderBottomwithmargins.png-dark
    • BorderBottomwithmargins.png
  • skia-windows-screenshots: 2458 changed over 2496

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • Accessibility_ScreenReader.png
    • AnimatedBackVisualSourceSamplePage.png
    • AnimatedVisualsTestbedPage.png
    • AppBarButtonWithIconTest.png
    • ApplicationViewMode.png-dark
    • ApplicationViewSpanningRectsPage.png-dark
    • AppWindowFeatures.png
    • AppWindowTitleBar Properties.png-dark
    • ArcSegment.png
    • Arrange_Performance01.png-dark
    • AutoBorderStretchwithrightmargin.png-dark
    • AutoBorderStretchwithrightmargin.png
    • AutomationProperties_StructureAndProps.png
    • AutoSizedPathCentered.png-dark
    • BadgeNotificationTests.png-dark
    • BadgeNotificationTests.png
    • Basics_Automated.png-dark
    • Basics_Automated.png
    • BeginTime_MultipleAnimations.png-dark
    • BeginTime_MultipleAnimations.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 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 a SkiaImage's SKImage directly, so nothing bypasses the reference count.
  • Every way a SkiaImage is 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 CopyPixels length check: I checked every caller. None passes a short buffer. WriteableBitmap.SetSource reads the new image's size before OnSetSource resizes its buffer, and RenderTargetBitmap sizes 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.

Comment thread doc/articles/feature-flags.md Resolved
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.
@mikernet
mikernet force-pushed the dev/mikernet/skia-texture-shares-image branch from a9c642d to 0aa6ea1 Compare November 12, 2026 20:43
@mikernet

Copy link
Copy Markdown
Contributor Author

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).

  • CompositionImageSurface.HasTexture: removed (c83d753). When_Drawn_Image_Waits_Then_Its_Pixels_Count_Once now draws the image with a screenshot before it reads the count, so the surface holds its texture by then. With DecodedByteCount counting every texture again, the test still fails (800000 bytes counted, 400000 allowed).
  • ITexture.SharesImagePixels docs: now the contract only, in your wording (0aa6ea1). The accounting stays on DecodedByteCount.
  • feature-flags.md: shortened as suggested, and the same sentence in the MaxUndisplayedImageBytes docs in FeatureConfiguration.cs, which had the same decoder details (0aa6ea1).
  • fix(imaging): Release cached decodes, keep encoded bytes instead #25559: agreed, whichever of the two merges second reconciles that paragraph and the FeatureConfiguration.cs remark. I haven't touched fix(imaging): Release cached decodes, keep encoded bytes instead #25559 here.

Skia desktop after the rebase: Given_Image_Release, Given_SkiaTexture and Given_GlyphRunRenderer pass (77 of 77).

@unodevops

Copy link
Copy Markdown
Contributor

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

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

Labels

area/skia ✏️ Categorizes an issue or PR as relevant to Skia kind/documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Skia] Every displayed image is held twice in memory: CreateTexture copies the decoded pixels

6 participants