Skip to content

Add backend-neutral async RequestReadPixels to SKImage and SKSurface - #4545

Merged
mattleibow merged 6 commits into
mainfrom
mattleibow-generic-async-read-pixels
Jul 27, 2026
Merged

mattleibow merged 6 commits into
mainfrom
mattleibow-generic-async-read-pixels

Conversation

@mattleibow

@mattleibow mattleibow commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds a backend-neutral async rescale-and-read-pixels feature to SKImage and SKSurface, wrapping the new core Skia C API (companion: mono/skia#295).

The underlying C++ types (SkImage::AsyncReadResult, SkImage::RescaleGamma, SkImage::RescaleMode) are core and shared by the raster, Ganesh and Graphite backends — SkSurface merely aliases the SkImage ones. So this lands as a generic feature on main. The in-flight Graphite PR (#3968) can then drop its Graphite-prefixed SKGraphiteAsyncReadResult / SKGraphiteRescaleGamma / SKGraphiteRescaleMode and consume these instead, keeping only its genuinely Graphite-specific Context-based entry point.

Raster surfaces/images invoke the callback synchronously; Ganesh defers it until GRContext.Submit() + GRContext.CheckAsyncWorkCompletion() are pumped (per Skia's docs, async read is Ganesh-only and the Graphite path is the context API).

Related issues

Related to #3968

Required skia PR

Requires mono/skia#295

Areas affected

  • Managed API (binding/)
  • Native / C API (externals/skia/src/c, include/c)
  • Generated P/Invoke bindings
  • Native dependency or Skia update
  • Views & integrations
  • Rendering output / visual behavior
  • Performance
  • Tests
  • Build, packaging, or CI
  • Documentation or samples

Changes

Public API (additive only — no removals or signature changes):

// SKImage / SKSurface (same shape on both)
public void RequestReadPixels (SKImageInfo info, SKRectI srcRect, Action<SKImageReadPixelsResult> callback);            // default rescale: Src + Nearest
public void RequestReadPixels (SKImageInfo info, SKRectI srcRect, SKImageRescaleGamma rescaleGamma, SKImageRescaleMode rescaleMode, Action<SKImageReadPixelsResult> callback);

// GRContext
public void CheckAsyncWorkCompletion ();

// new types
public sealed class SKImageReadPixelsResult : IDisposable
{
    public int PlaneCount { get; }
    public int GetPlaneRowBytes (int planeIndex);
    public ReadOnlySpan<byte> GetPlaneData (int planeIndex);         // raw, zero-copy view (may include row padding)
    public void CopyPlaneTo (int planeIndex, Span<byte> destination); // tightly-packed copy into your buffer (padding stripped, bounded)
    public byte[] ToArray (int planeIndex = 0);                       // tightly-packed byte[] that outlives the callback
    public SKImage ToImage ();                                       // owned SKImage (single-plane result)
    public SKBitmap ToBitmap ();                                     // owned SKBitmap (single-plane result)
}
public enum SKImageRescaleGamma { Src, Linear }
public enum SKImageRescaleMode  { Nearest, Linear, RepeatedLinear, RepeatedCubic }

Behavior

SKImageReadPixelsResult is a non-owning, callback-scoped view (it is not an SKObject — the native pointer is non-ref-counted and reused). It is invalidated when the callback returns and throws ObjectDisposedException from every member afterwards. GetPlaneData is the raw, zero-copy span; the CopyPlaneTo / ToArray / ToImage / ToBitmap helpers produce owned, tightly-packed copies that survive past the callback (and cannot over-read the native transfer buffer). On failure (e.g. an out-of-bounds srcRect) the callback is invoked with null. There is no user context/state argument — capture it in the closure.

Defaults are RescaleGamma.Src + RescaleMode.Nearest (the least-transform "as-is" choice); use RepeatedLinear/RepeatedCubic explicitly for higher-quality downscales.

Testing

dotnet test tests/SkiaSharp.Tests.Console — 18 SKAsyncReadPixelsTest cases pass locally (macOS arm64):

  • Correctness with a per-pixel colour pattern read from an offset srcRect (not 0,0..WxH), validating every destination pixel for GetPlaneData / CopyPlaneTo / ToArray / ToImage / ToBitmap.
  • Padding — the strided row copy is factored into an internal CopyRows and unit-tested with a fabricated padded source (real GL/raster RGBA reads are never row-padded), asserting the packed output drops the padding.
  • Edge cases — exact / too-small / empty / oversized destinations; invalid plane indices; ToImage/ToBitmap outlive the callback.
  • Behavior — raster fires synchronously; out-of-bounds srcRect → callback(null); null callback → ArgumentNullException; every member throws ObjectDisposedException (never crashes) when used after the callback; Dispose is idempotent.
  • Ganesh ([GPU]): completes with correct pixels after Submit(sync) + a CheckAsyncWorkCompletion pump, plus a GPU downscale. The async-proof (done==false before the pump) is asserted only when the backend actually defers, tolerating Skia's documented synchronous transfer-buffer fallback. Auto-skips when no GL context is available.

The full suite is green apart from one pre-existing, unrelated visual-golden delta (ganesh-gl/DiagonalLines); this change touches no rendering path.

Future work — YUV (not blocked by this PR)

This ships the RGBA (count() == 1) read only, but the design is deliberately YUV-ready: the C API result type + accessors are multi-plane (count() can be 3/4), and the enums/proc are shared. asyncRescaleAndReadPixelsYUV420 / YUVA420 can be added purely additively later — see the follow-up note in the comments for the proposed C# surface.

Wrap the new core Skia async rescale-and-read-pixels C API with a backend-neutral
managed surface:

- SKImageAsyncReadResult: a non-owning, callback-scoped view over the pixel data
  (PlaneCount, GetPlaneData, GetPlaneRowBytes, CopyPlaneTo). It is not an SKObject
  (the native pointer is non-ref-counted and reused); it is invalidated when the
  callback returns and throws ObjectDisposedException afterwards.
- SKImageRescaleGamma / SKImageRescaleMode enums (generated).
- SKImage.RequestReadPixels and SKSurface.RequestReadPixels overloads taking an
  Action<SKImageAsyncReadResult> (context is captured in the closure; no state arg).
- GRContext.CheckAsyncWorkCompletion to drive Ganesh completion so the callback fires.
- DelegateProxies.SKImageAsyncReadPixelsProxy: fire-once proxy that frees the pin.

Raster surfaces/images invoke the callback synchronously; Ganesh defers until
Submit + CheckAsyncWorkCompletion. Bumps externals/skia to the C API commit and
regenerates the P/Invoke bindings. Adds tests covering the synchronous raster
contract, rescale (downscale), lifetime invalidation, and the Ganesh
false -> pump -> true async proof.

Requires mono/skia#295.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 42b75ff8-da07-4e17-903a-2101f2000684
@github-actions

Copy link
Copy Markdown
Contributor

📦 Try the packages from this PR

Warning

Do not run these scripts without first reviewing the code in this PR.

Step 1 — Download the packages

bash / macOS / Linux:

curl -fsSL https://raw.githubusercontent.com/mono/SkiaSharp/main/scripts/get-skiasharp-pr.sh | bash -s -- 4545

PowerShell / Windows:

iex "& { $(irm https://raw.githubusercontent.com/mono/SkiaSharp/main/scripts/get-skiasharp-pr.ps1) } 4545"

Step 2 — Add the local NuGet source

dotnet nuget add source ~/.skiasharp/hives/pr-4545/packages --name skiasharp-pr-4545
More options
Option Description
--successful-only / -SuccessfulOnly Only use successful builds
--force / -Force Overwrite previously downloaded packages
--list / -List List available artifacts without downloading
--build-id ID / -BuildId ID Download from a specific build

Or download manually from Azure Pipelines — look for the nuget artifact on the build for this PR.

Remove the source when you're done:

dotnet nuget remove source skiasharp-pr-4545

…earest

Follow-up API polish (managed-only; C API unchanged):

- Rename SKImageAsyncReadResult -> SKImageReadPixelsResult, for consistency with the
  RequestReadPixels method name (we intentionally drop "Async" to avoid the .NET
  Async==TAP false-friend, so the result type should not reintroduce it). The native
  opaque sk_image_async_read_result_t is unchanged (not user-facing).
- Add a RequestReadPixels(SKImageInfo info, Action<SKImageReadPixelsResult> callback)
  overload on SKImage and SKSurface that reads at 1:1 (srcRect = 0,0,info.Width,info.Height),
  so no rescale occurs — the straightforward "give me these pixels" path.
- Change the default rescale to (Src, Nearest) instead of (Src, RepeatedLinear).
  RepeatedLinear was inherited from the graphite branch and is a quality-downscale
  default; Nearest + Src does the least work ("as-is"), and at 1:1 the mode/gamma are
  no-ops anyway.

Adds a test for the 1:1 overload; all 8 SKAsyncReadPixelsTest cases pass.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 42b75ff8-da07-4e17-903a-2101f2000684
@github-actions

github-actions Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

📊 SkiaSharp benchmarks — PR #4545

⭐ this PR (full source build) vs 🌙 nightly · Linux · Windows · macOS

Informational only — this never blocks the PR. 🟢 faster / less allocation · 🔴 slower / more allocation; moves under 5% are hidden as noise.

⏱️ Times are raw BenchmarkDotNet means, and the ⭐ PR and baseline legs run on separate CI runners, so microbenchmarks can swing run-to-run — treat small time deltas as noise. Allocations are deterministic and the reliable signal. The interactive perf-dashboard (linked below) applies smoothing for the trend view.

Highlights

⏱️ Time — 🔴 25 slower · 🟢 42 faster

  • 🔴 RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) · Windows · 97.59 µs → 130.92 µs (+34%)
  • 🔴 PathBoundsBenchmark.TightBounds(Points: 64) · Windows · 1.54 µs → 2.05 µs (+33%)
  • 🔴 PathBoundsBenchmark.TightBounds(Points: 1024) · Windows · 15.78 µs → 20.41 µs (+29%)
  • 🔴 MatrixMapPointsBenchmark.MapRadius(Points: 4096) · Windows · 136.34 µs → 174.85 µs (+28%)
  • 🟢 MatrixMapPointsBenchmark.MapPoints(Points: 4096) · Linux · 2.70 µs → 1.97 µs (-27%)
  • …and 62 more (see details below)
Full per-OS benchmark deltas

Linux

⏱️ Time (vs 🌙 nightly 4.151.0-nightly.103)

Benchmark baseline this PR Δ
MatrixMapPointsBenchmark.MapPoints(Points: 4096) 2.70 µs 1.97 µs 🟢 -27%
RasterImageLifecycleBenchmark.CreateRasterImage(Count: 256) 262.69 µs 201.59 µs 🟢 -23%
MatrixMapPointsBenchmark.MapPoints(Points: 256) 209.4 ns 163.0 ns 🟢 -22%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 1024) 733.05 µs 571.14 µs 🟢 -22%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 2048) 2.82 ms 2.22 ms 🟢 -21%
PathBoundsBenchmark.TightBounds(Points: 1024) 11.10 µs 8.74 µs 🟢 -21%
ColorParseBenchmark.Parse(Iterations: 1000) 75.17 µs 59.67 µs 🟢 -21%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 1024) 2.01 ms 1.60 ms 🟢 -20%
PathBoundsBenchmark.TightBounds(Points: 64) 980.5 ns 784.8 ns 🟢 -20%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 256) 954.39 µs 764.38 µs 🟢 -20%
ColorMathBenchmark.ToColor(Colors: 4096) 15.36 µs 12.31 µs 🟢 -20%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 64) 254.66 µs 205.83 µs 🟢 -19%
MatrixMapPointsBenchmark.MapRadius(Points: 256) 14.59 µs 11.80 µs 🟢 -19%
SceneRenderBenchmark.RenderFrame(Complexity: 1) 3.97 ms 3.21 ms 🟢 -19%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 2048) 7.73 ms 6.28 ms 🟢 -19%
SceneRenderBenchmark.RenderFrame(Complexity: 4) 18.34 ms 14.91 ms 🟢 -19%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 64) 355.08 µs 291.96 µs 🟢 -18%
CanvasDrawBenchmark.Draw(Shapes: 512) 33.32 ms 27.43 ms 🟢 -18%
CanvasDrawBenchmark.Draw(Shapes: 64) 4.17 ms 3.44 ms 🟢 -18%
RuntimeEffectShaderBenchmark.DrawFrame 2.84 ms 2.34 ms 🟢 -17%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 256) 1.33 ms 1.10 ms 🟢 -17%
MatrixMapPointsBenchmark.MapRect(Points: 256) 11.92 µs 9.87 µs 🟢 -17%
ColorMathBenchmark.ToColorF(Colors: 4096) 13.13 µs 10.91 µs 🟢 -17%
RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) 102.96 µs 85.75 µs 🟢 -17%
MatrixMapPointsBenchmark.MapRadius(Points: 4096) 223.27 µs 187.77 µs 🟢 -16%
…and 9 more

Windows

⏱️ Time (vs 🌙 nightly 4.151.0-nightly.103)

Benchmark baseline this PR Δ
RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) 97.59 µs 130.92 µs 🔴 +34%
PathBoundsBenchmark.TightBounds(Points: 64) 1.54 µs 2.05 µs 🔴 +33%
PathBoundsBenchmark.TightBounds(Points: 1024) 15.78 µs 20.41 µs 🔴 +29%
MatrixMapPointsBenchmark.MapRadius(Points: 4096) 136.34 µs 174.85 µs 🔴 +28%
MatrixMapPointsBenchmark.MapVector(Points: 4096) 120.52 µs 144.67 µs 🔴 +20%
RasterImageLifecycleBenchmark.CreateRasterImage(Count: 256) 243.82 µs 291.33 µs 🔴 +19%
MatrixMapPointsBenchmark.MapRadius(Points: 256) 9.42 µs 10.61 µs 🔴 +13%
ColorParseBenchmark.Parse(Iterations: 1000) 74.24 µs 83.14 µs 🔴 +12%
MatrixOpsBenchmark.Concat(Count: 4096) 222.77 µs 249.44 µs 🔴 +12%
CanvasDrawBenchmark.Draw(Shapes: 64) 2.60 ms 2.91 ms 🔴 +12%
MatrixMapPointsBenchmark.MapRect(Points: 4096) 117.88 µs 130.63 µs 🔴 +11%
CanvasDrawBenchmark.Draw(Shapes: 512) 20.73 ms 22.78 ms 🔴 +10%
MatrixMapPointsBenchmark.MapRect(Points: 256) 7.34 µs 7.94 µs 🔴 +8%
MatrixMapPointsBenchmark.MapVector(Points: 256) 8.21 µs 8.70 µs 🔴 +6%

macOS

⏱️ Time (vs 🌙 nightly 4.151.0-nightly.103)

Benchmark baseline this PR Δ
MatrixMapPointsBenchmark.MapVector(Points: 4096) 58.41 µs 42.93 µs 🟢 -26%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 1024) 778.32 µs 583.34 µs 🟢 -25%
RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) 74.63 µs 91.91 µs 🔴 +23%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 2048) 3.04 ms 2.34 ms 🟢 -23%
MatrixMapPointsBenchmark.MapPoints(Points: 256) 149.0 ns 182.6 ns 🔴 +23%
RuntimeEffectShaderBenchmark.DrawFrame 554.01 µs 662.40 µs 🔴 +20%
ColorMathBenchmark.PreMultiply(Colors: 4096) 8.90 µs 10.51 µs 🔴 +18%
MatrixOpsBenchmark.Invert(Count: 4096) 73.55 µs 61.34 µs 🟢 -17%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 256) 860.15 µs 1.00 ms 🔴 +16%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 256) 608.28 µs 699.65 µs 🔴 +15%
CanvasDrawBenchmark.Draw(Shapes: 64) 1.51 ms 1.74 ms 🔴 +15%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 1024) 1.67 ms 1.47 ms 🟢 -12%
PathBoundsBenchmark.TightBounds(Points: 1024) 9.11 µs 10.02 µs 🔴 +10%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 2048) 6.27 ms 5.68 ms 🟢 -9%
SceneRenderBenchmark.RenderFrame(Complexity: 1) 1.38 ms 1.27 ms 🟢 -8%
MatrixMapPointsBenchmark.MapPoint(Points: 256) 1.23 µs 1.31 µs 🔴 +7%
ColorMathBenchmark.ToColor(Colors: 4096) 20.68 µs 19.48 µs 🟢 -6%
CanvasDrawBenchmark.Draw(Shapes: 512) 13.29 ms 14.01 ms 🔴 +5%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 64) 282.66 µs 297.69 µs 🔴 +5%

📈 Full interactive perf-dashboard & run details →

@github-actions

Copy link
Copy Markdown
Contributor

📖 Documentation Preview

The documentation for this PR has been deployed and is available at:

🔗 View Staging Site
🔗 View Staging Docs
🔗 View Staging Gallery (Blazor)
🔗 View Staging Gallery (Uno Platform)
🔗 View Staging SkiaFiddle

This preview will be updated automatically when you push new commits to this PR.


This comment is automatically updated by the documentation staging workflow.

@github-actions

github-actions Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

📦 Artifact size report

Packages from this PR (build 1528257) vs the latest nightly baseline 4.151.0-nightly.103 (observed 2026-07-27).

Total .nupkg size: 537.5 MB → 535.5 MB (−2.0 MB, -0.4%)

Packages

⚠️ marks growth over 500.0 KB or 2%. Changes under 50.0 KB are treated as noise.

Package baseline this PR Δ Δ%
SkiaSharp.NativeAssets.WinUI 109.1 MB 107.1 MB 🟢 −1.9 MB -1.8%
HarfBuzzSharp.NativeAssets.Win32 20.7 MB 20.5 MB 🟢 −252.7 KB -1.2%
SkiaSharp 8.6 MB 8.6 MB 🔴 +75.3 KB +0.9%

+37 package(s) unchanged (< 50.0 KB).

Per-file changes

HarfBuzzSharp.NativeAssets.Win32

File Size
runtimes/win-x86/native/libHarfBuzzSharp.pdb 22.2 MB → 21.9 MB (🟢 −272.0 KB)
runtimes/win-x64/native/libHarfBuzzSharp.pdb 22.0 MB → 21.8 MB (🟢 −240.0 KB)
runtimes/win-arm64/native/libHarfBuzzSharp.pdb 22.3 MB → 22.3 MB (🟢 −8.0 KB)

SkiaSharp

File Size
ref/net48/SkiaSharp.dll 380.5 KB → 388.0 KB (🔴 +7.5 KB)
lib/net462/SkiaSharp.dll 809.5 KB → 816.5 KB (🔴 +7.0 KB)
lib/net48/SkiaSharp.dll 809.0 KB → 816.0 KB (🔴 +7.0 KB)
lib/net10.0-ios26.0/SkiaSharp.dll 504.0 KB → 508.5 KB (🔴 +4.5 KB)
lib/net10.0-maccatalyst26.0/SkiaSharp.dll 504.0 KB → 508.5 KB (🔴 +4.5 KB)
lib/net10.0-tvos26.0/SkiaSharp.dll 504.0 KB → 508.5 KB (🔴 +4.5 KB)
lib/net10.0-windows10.0.19041/SkiaSharp.dll 506.5 KB → 511.0 KB (🔴 +4.5 KB)
lib/net6.0-tizen8.0/SkiaSharp.dll 494.5 KB → 499.0 KB (🔴 +4.5 KB)
lib/net6.0/SkiaSharp.dll 478.0 KB → 482.5 KB (🔴 +4.5 KB)
lib/net9.0-android35.0/SkiaSharp.dll 501.5 KB → 506.0 KB (🔴 +4.5 KB)
lib/net9.0-maccatalyst18.0/SkiaSharp.dll 504.0 KB → 508.5 KB (🔴 +4.5 KB)
lib/net9.0-windows10.0.19041/SkiaSharp.dll 506.5 KB → 511.0 KB (🔴 +4.5 KB)
lib/netstandard2.0/SkiaSharp.dll 486.0 KB → 490.5 KB (🔴 +4.5 KB)
lib/netstandard2.1/SkiaSharp.dll 482.0 KB → 486.5 KB (🔴 +4.5 KB)
lib/net10.0-android36.0/SkiaSharp.dll 502.0 KB → 506.0 KB (🔴 +4.0 KB)
lib/net10.0-macos26.0/SkiaSharp.dll 504.0 KB → 508.0 KB (🔴 +4.0 KB)
lib/net10.0-tizen10.0/SkiaSharp.dll 521.5 KB → 525.5 KB (🔴 +4.0 KB)
lib/net10.0/SkiaSharp.dll 505.5 KB → 509.5 KB (🔴 +4.0 KB)
lib/net9.0-ios18.0/SkiaSharp.dll 504.0 KB → 508.0 KB (🔴 +4.0 KB)
lib/net9.0-macos15.0/SkiaSharp.dll 504.0 KB → 508.0 KB (🔴 +4.0 KB)
lib/net9.0-tizen8.0/SkiaSharp.dll 521.5 KB → 525.5 KB (🔴 +4.0 KB)
lib/net9.0-tvos18.0/SkiaSharp.dll 504.0 KB → 508.0 KB (🔴 +4.0 KB)
lib/net9.0/SkiaSharp.dll 505.5 KB → 509.5 KB (🔴 +4.0 KB)
ref/net462/SkiaSharp.dll 385.0 KB → 388.0 KB (🔴 +3.0 KB)
ref/net10.0-android36.0/SkiaSharp.dll 300.0 KB → 302.0 KB (🔴 +2.0 KB)
+41 more file(s)

SkiaSharp.NativeAssets.WinUI

File Size
runtimes/win-x86/native/libGLESv2.pdb 67.3 MB → 67.0 MB (🟢 −288.0 KB)
runtimes/win-x64/native/libGLESv2.pdb 66.7 MB → 66.4 MB (🟢 −256.0 KB)
runtimes/win-arm64/native/libGLESv2.pdb 64.5 MB → 64.3 MB (🟢 −240.0 KB)
runtimes/win-x64/native/libEGL.pdb 6.4 MB → 6.3 MB (🟢 −32.0 KB)
runtimes/win-x86/native/libEGL.pdb 6.5 MB → 6.5 MB (🟢 −16.0 KB)
runtimes/win-arm64/native/SkiaSharp.Views.WinUI.Native.pdb 67.7 MB → 67.7 MB (🟢 −8.0 KB)
runtimes/win-x64/native/SkiaSharp.Views.WinUI.Native.pdb 68.0 MB → 68.0 MB (🟢 −8.0 KB)
🧬 win-x64 (runtimes/win-x64/native/libGLESv2.dll) 4.9 MB → 4.9 MB (🔴 +2.0 KB)
🧬 win-arm64 (runtimes/win-arm64/native/libGLESv2.dll) 4.4 MB → 4.4 MB (🔴 +1.0 KB)

Informational only — this never blocks the PR. Native binaries are labelled by os/arch.

Copilot AI added 3 commits July 25, 2026 09:19
From the Sol/Opus code reviews:

- SKImageReadPixelsResult.GetPlaneData now returns a bounded ReadOnlySpan<byte>
  (rowBytes * info.Height) instead of a raw IntPtr; drop CopyPlaneTo, whose
  caller-supplied rowCount could over-read past the native transfer buffer. The
  result now captures the requested SKImageInfo to size the span.
- Drop the RequestReadPixels(info, callback) 1:1 overload: deriving srcRect from
  the destination info silently cropped on downscale and returned null on upscale.
- Root the source image/surface across the async gap (GC.KeepAlive inside the
  deferred callback closure).
- Native: return early when the callback is null (bumps externals/skia).
- Remove inline XML doc comments; docs are added separately via mdoc.
- Tests: replace solid-fill/first-pixel checks with a two-colour split pattern and
  multi-pixel asserts that actually exercise rescale + row traversal; add a
  failure-path test (out-of-bounds srcRect -> callback(null)); make the GPU
  async-proof tolerate the documented synchronous transfer-buffer fallback.

Not changed: the DelegateProxies proxy keeps try/finally (free the pin) with no
catch, matching every other proxy in the codebase.

Requires mono/skia#295.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 42b75ff8-da07-4e17-903a-2101f2000684
Restore a safe CopyPlaneTo and add materializers so callers can get usable,
owned pixels in a single call without hand-rolling the row/padding loop:

- CopyPlaneTo(planeIndex, Span<byte>): copies the plane tightly-packed (transfer-
  buffer row padding stripped), bounded by the destination — no caller-supplied
  rowCount, so it cannot over-read.
- ToArray(planeIndex = 0): tightly-packed byte[] that outlives the callback.
- ToImage() / ToBitmap(): materialize the whole single-plane result into an owned
  SKImage / SKBitmap (throw for multi-plane results). GetPlaneData stays the raw,
  padded, zero-copy view.

Per-plane byte accessors take a plane index; the whole-image materializers do not,
since they only apply to a single interleaved plane (PlaneCount == 1).

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 42b75ff8-da07-4e17-903a-2101f2000684
- Extract the strided row copy into an internal static CopyRows so the
  padding-stripping path is unit-tested deterministically (real GPU/raster RGBA
  reads are never row-padded, so it cannot be exercised end-to-end here): a
  fabricated 20-byte-stride source with poisoned padding must produce a packed
  16-byte-stride output with no padding bytes leaked.
- Replace solid-colour assertions with a per-pixel pattern (colour encodes x,y)
  and read from an OFFSET srcRect (not 0,0..WxH), validating every destination
  pixel — catching stride/offset/padding bugs.
- Cover GetPlaneData / CopyPlaneTo / ToArray / ToImage / ToBitmap positively, plus
  negatives: too-small and empty destinations throw; oversized destination copies
  the prefix and leaves the tail untouched; invalid plane indices (-1, 1, 99) throw.
- Verify every member throws ObjectDisposedException (not a crash) when the result
  is used after the callback returns, and that Dispose is idempotent.

18 SKAsyncReadPixelsTest cases, all green.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 42b75ff8-da07-4e17-903a-2101f2000684
@mattleibow

Copy link
Copy Markdown
Contributor Author

Follow-up: YUV / YUVA read (additive — not blocked by this PR)

This PR wires only the RGBA (count() == 1) read, but nothing here blocks YUV. The result type and its accessors are already per-plane and the C API result/enums/proc are shared, so YUV lands as a pure addition.

Native (mono/skia), reusing sk_image_async_read_result_t + the shared enums/proc:

SK_C_API void sk_image_async_rescale_and_read_pixels_yuv420(
    const sk_image_t* image, sk_yuvcolorspace_t yuvColorSpace, const sk_colorspace_t* dstColorSpace,
    const sk_irect_t* srcRect, int32_t dstWidth, int32_t dstHeight,
    sk_image_rescale_gamma_t gamma, sk_image_rescale_mode_t mode,
    sk_image_async_read_pixels_proc callback, void* context);
// + _yuva420 (4 planes), + the sk_surface_* and graphite Context equivalents

Managed (additive overloads):

// SKImage / SKSurface
public void RequestReadPixelsYuv420 (SKImageInfo info, SKYuvColorSpace yuvColorSpace, SKColorSpace dstColorSpace,
    SKRectI srcRect, Action<SKImageReadPixelsResult> callback);
public void RequestReadPixelsYuva420 (...);
// (SKYuvColorSpace would be a new generated enum mapping SkYUVColorSpace)

The delivered SKImageReadPixelsResult already covers the multi-plane case:

  • PlaneCount → 3 (YUV420) or 4 (YUVA420); GetPlaneData(i) / GetPlaneRowBytes(i) / CopyPlaneTo(i, …) / ToArray(i) are all per-plane.
  • ToImage() / ToBitmap() deliberately throw for multi-plane results (a YUV result isn't a single interleaved image); a YuvToImage() / planar-SKImage.FromYuvaPixmaps helper could be added if wanted.

Only internal change required: the result currently captures the single dst SKImageInfo, which is used to size GetPlaneData/ToArray/CopyPlaneTo. YUV planes are subsampled (chroma is half-size), so the result would need to carry per-plane dimensions instead. That state is all internal, so it can change without touching the public API surface shipped here.

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.

Pull request overview

Adds a backend-neutral async rescale-and-read-pixels API to SKImage and SKSurface by wiring up new Skia C-API entry points, introducing a callback-scoped result wrapper, and adding a comprehensive test suite (raster + Ganesh GPU behavior).

Changes:

  • Added RequestReadPixels(...) overloads to SKImage and SKSurface, using a delegate proxy callback to deliver results (or null on failure).
  • Introduced SKImageReadPixelsResult as a callback-scoped accessor/copy helper for plane data.
  • Added GRContext.CheckAsyncWorkCompletion() plus new/updated generated P/Invokes and delegate proxy plumbing; added SKAsyncReadPixelsTest coverage.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
tests/Tests/SkiaSharp/SKAsyncReadPixelsTest.cs New unit tests covering row-copy behavior, raster sync behavior, and Ganesh deferred completion/pumping behavior.
binding/SkiaSharp/SKSurface.cs Adds SKSurface.RequestReadPixels overloads and hooks them to the native async read callback proxy.
binding/SkiaSharp/SKImageReadPixelsResult.cs New callback-scoped result type providing plane access and copy/materialization helpers.
binding/SkiaSharp/SKImage.cs Adds SKImage.RequestReadPixels overloads and hooks them to the native async read callback proxy.
binding/SkiaSharp/SkiaApi.generated.cs Adds generated bindings for async read result accessors, async read entry points, and gr_direct_context_check_async_work_completion.
binding/SkiaSharp/GRContext.cs Adds CheckAsyncWorkCompletion() managed wrapper.
binding/SkiaSharp/DelegateProxies.cs Adds proxy implementation to invoke the managed callback and free the pinned GCHandle.

Comment on lines +310 to +315
var info = new SKImageInfo(4, 4, SKColorType.Rgba8888, SKAlphaType.Premul);
using var surface = SKSurface.Create(info);
using var image = SKImage.FromBitmap(CreatePatternBitmap(4));

Assert.Throws<ArgumentNullException>(() => surface.RequestReadPixels(info, new SKRectI(0, 0, 4, 4), null));
Assert.Throws<ArgumentNullException>(() => image.RequestReadPixels(info, new SKRectI(0, 0, 4, 4), null));
Comment on lines +39 to +42
var src = SkiaApi.sk_image_async_read_result_get_data (handle, planeIndex);
if (src == null)
return default;

mattleibow added a commit to mono/skia that referenced this pull request Jul 27, 2026
#295)

Add C API for async rescale-and-read-pixels (SkImage/SkSurface/Ganesh) (#295)

Required by: mono/SkiaSharp#4545

Expose SkImage::asyncRescaleAndReadPixels and SkSurface::asyncRescaleAndReadPixels
through the C API so SkiaSharp can offer a backend-neutral pixel readback — the
primary way to get pixels off a GPU surface, and the only readback path on
backends without synchronous GPU ReadPixels.

The result type and rescale enums are core Skia types shared by the raster,
Ganesh and Graphite backends (SkSurface aliases the SkImage ones), so the C API
uses neutral names rather than a backend prefix. This lets the Graphite C API
(the mono/skia side of #3968) drop its sk_graphite_async_read_result_* duplicates
and reuse these.

  * sk_types.h: sk_image_async_read_result_t (opaque), sk_image_rescale_gamma_t,
    sk_image_rescale_mode_t, and the sk_image_async_read_pixels_proc callback.
  * sk_image.h/.cpp, sk_surface.h/.cpp: the async-read entry points plus the
    result accessors (get_count / get_data / get_row_bytes).
  * gr_context.h/.cpp: gr_direct_context_check_async_work_completion, to drive
    Ganesh async work so the callback fires.
  * sk_types_priv.h: a DEF_MAP_WITH_NS mapping for the nested
    SkImage::AsyncReadResult.

The (proc + context) pair is bundled into a heap bridge freed by a non-capturing
lambda trampoline once the callback fires — mirroring the existing
sk_font_get_paths idiom — and the entry points early-return on a null callback.
All additive; no existing export, struct layout or enum value changed.

Co-authored-by: Matthew Leibowitz <[email protected]>
Co-authored-by: Copilot App <[email protected]>
mono/skia#295 (the async rescale-and-read-pixels C API) merged to the skiasharp
branch as 0d6ea6b048. Point the submodule at that tip instead of the PR branch
commit, and sync the cgmanifest skia commitHash to match (it still referenced the
pre-PR base 1af4051d). Tree-identical to the previously built native, so no
rebuild needed. The chrome/m151 milestone tracking is unchanged — this is a C API
addition, not an upstream Skia merge.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 42b75ff8-da07-4e17-903a-2101f2000684
@mattleibow
mattleibow merged commit 2e59531 into main Jul 27, 2026
22 of 84 checks passed
@mattleibow
mattleibow deleted the mattleibow-generic-async-read-pixels branch July 27, 2026 14:38
mattleibow added a commit that referenced this pull request Jul 28, 2026
Add Graphite GPU backend bindings for Vulkan, Metal, and Dawn (#3968)

Context: mono/skia#236
Context: #4545
Tracking: #4555

Expose Skia's next-generation Graphite GPU backend through additive
SkiaSharp APIs. The new surface follows Graphite's explicit
record, snap, insert, and submit model while leaving the existing
Ganesh APIs and behavior unchanged.

Add managed wrappers for contexts, recorders, recordings, backend
textures, texture information, and Vulkan, Metal, and Dawn backend
contexts. Support wrapping caller-owned textures with release callbacks
and provide SKGraphiteImageCache as the default image-provider strategy
for uploading and reusing raster images.

Enable Graphite in the native builds for supported desktop and mobile
platforms. WebAssembly uses Dawn's emdawnwebgpu port so Graphite can
render through browser WebGPU. Readback uses the existing
backend-neutral asynchronous API because shipping Graphite surfaces do
not support synchronous ReadPixels.

Cover the new surface with API tests, backend-context and release
callback tests, and a cross-backend visual regression matrix with
platform-specific goldens. The iOS simulator's Graphite/Metal gradient
limitation remains isolated to that environment and is tracked
separately.

Co-authored-by: Ramez Ragaa <[email protected]>
Co-authored-by: Matthew Leibowitz <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: Copilot App <[email protected]>
mattleibow added a commit that referenced this pull request Aug 4, 2026
…4545)

Add backend-neutral async RequestReadPixels to SKImage and SKSurface (#4545)

Requires: mono/skia#295
Related: #3968 (Graphite backend)
Docs: mono/SkiaSharp-API-docs#184

GPU-backed surfaces need a way to read pixels back to the CPU, and on some
backends (notably Graphite) the asynchronous rescale-and-read is the *only*
readback path — Skia gates synchronous GPU ReadPixels behind GPU_TEST_UTILS.
The in-flight Graphite PR (#3968) had added this under Graphite-prefixed names,
but the underlying C++ types (SkImage::AsyncReadResult, SkImage::RescaleGamma,
SkImage::RescaleMode) are core and shared by the raster, Ganesh and Graphite
backends — SkSurface merely aliases the SkImage ones. So this lands the feature
generically on main; #3968 can then drop its SKGraphite* copies and consume it.

Add RequestReadPixels overloads on SKImage and SKSurface that deliver the pixels
to an Action<SKImageReadPixelsResult>. Raster reads invoke the callback
synchronously; Ganesh defers until the work is submitted and drained via the new
GRContext.CheckAsyncWorkCompletion(). The result is a non-owning, callback-scoped
view (deliberately not an SKObject — the native pointer is non-ref-counted and
reused); it is invalidated when the callback returns and throws
ObjectDisposedException afterwards. Failure is signalled by a null result, and
there is no state argument (capture it in the closure).

  * SKImageReadPixelsResult: PlaneCount, GetPlaneRowBytes and a raw zero-copy
    GetPlaneData(ReadOnlySpan<byte>), plus copy-out helpers that outlive the
    callback — CopyPlaneTo (tightly packed, bounded), ToArray, ToImage, ToBitmap.
  * SKImageRescaleGamma { Src, Linear } and SKImageRescaleMode { Nearest, Linear,
    RepeatedLinear, RepeatedCubic }. The convenience overload defaults to
    (Src, Nearest) — the least-transform choice, matching what Skia itself forces
    when no rescale is required (SurfaceContext normalises to kSrc/kNearest at 1:1).
  * Bumps externals/skia to the C API (mono/skia#295) and regenerates the
    P/Invoke bindings; the only hand-written generated piece is the fire-once
    DelegateProxies async-read proxy.

Scope is the RGBA (count()==1) read; YUV420/YUVA420 are a clean additive
follow-up, as the result type and accessors are already multi-plane.

Tested by 18 SKAsyncReadPixelsTest cases: per-pixel pattern correctness read from
an offset srcRect, a deterministic padding-strip unit test, destination-size and
invalid-plane-index edge cases, use-after-callback throwing cleanly, and Ganesh
deferred completion (asserting the false -> pump -> true transition where the
backend supports it).

Co-authored-by: Matthew Leibowitz <[email protected]>
Co-authored-by: Copilot App <[email protected]>
mattleibow added a commit that referenced this pull request Aug 4, 2026
Add Graphite GPU backend bindings for Vulkan, Metal, and Dawn (#3968)

Context: mono/skia#236
Context: #4545
Tracking: #4555

Expose Skia's next-generation Graphite GPU backend through additive
SkiaSharp APIs. The new surface follows Graphite's explicit
record, snap, insert, and submit model while leaving the existing
Ganesh APIs and behavior unchanged.

Add managed wrappers for contexts, recorders, recordings, backend
textures, texture information, and Vulkan, Metal, and Dawn backend
contexts. Support wrapping caller-owned textures with release callbacks
and provide SKGraphiteImageCache as the default image-provider strategy
for uploading and reusing raster images.

Enable Graphite in the native builds for supported desktop and mobile
platforms. WebAssembly uses Dawn's emdawnwebgpu port so Graphite can
render through browser WebGPU. Readback uses the existing
backend-neutral asynchronous API because shipping Graphite surfaces do
not support synchronous ReadPixels.

Cover the new surface with API tests, backend-context and release
callback tests, and a cross-backend visual regression matrix with
platform-specific goldens. The iOS simulator's Graphite/Metal gradient
limitation remains isolated to that environment and is tracked
separately.

Co-authored-by: Ramez Ragaa <[email protected]>
Co-authored-by: Matthew Leibowitz <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: Copilot App <[email protected]>
@mattleibow mattleibow added this to the 4.152.0-preview.1 milestone Aug 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants