Skip to content

perf(imaging): Read sizes from headers in the managed decoder - #25566

Open
mikernet wants to merge 11 commits into
unoplatform:masterfrom
mikernet:dev/mikernet/managed-decoder-read-size
Open

mikernet wants to merge 11 commits into
unoplatform:masterfrom
mikernet:dev/mikernet/managed-decoder-read-size

Conversation

@mikernet

@mikernet mikernet commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

GitHub Issue: related to #25556 (stacked on #25561, whose four commits come first here until it merges)

PR Type:

💬 Other: performance

What changed? 🚀

#25561 adds IImageEncoderDecoder.TryGetSize. The managed decoder (ManagedBackend.CreateImageDecoder(), which SkiaSharp-free apps such as WebGPU-only ones use) keeps its default, a full decode, so on those apps every BitmapSource.SetSource still decodes the whole image on the UI thread.

  • Each format's header rules now live in one reader that the decode runs: PNG, GIF, BMP, JPEG with its EXIF orientation, and WebP (VP8, VP8L, VP8X). TryGetSize runs the same readers, so it refuses the files they refuse and reports the size the decode produces. For a JPEG it reads the markers before the first scan and that scan's header. Like libjpeg (and so Skia) and WIC, the decode now takes the frame and its EXIF and Adobe metadata from those markers only, so a later marker can't change the size. A few refusals that used to surface as exceptions further in are now explicit, with the same result.
  • A seekable stream is read on demand, in 32-byte blocks: a JPEG's markers up to the first scan, a PNG's chunk headers, a GIF's blocks and sub-block lengths up to the end of its first frame, a WebP's chunk headers and bitstream header. Nothing is sized from the image's dimensions; the JPEG tables are capped at about 4 KB each.
  • As the interface allows, TryGetSize can still be true for a file whose compressed data, or a GIF frame after the first, then fails to decode. The open then fails and resets the size.

Measurements

A 4000x2667 JPEG (2.4 MB), Release desktop build with the managed decoder:

master¹ this PR
SetSource, UI thread (median) 517 ms (464–541) 0.28 ms
Allocated per SetSource 130 MB 4.9 MB²

¹ master's SetSource, a full decode, as #25561 alone still does with this decoder, timed on this branch. ² The two stream clones SetSource made then. #25561 now reads the header from the clone it keeps, so one 2.4 MB clone is left.

Why not InlineImageState.TryInspect*?

It answers another question. It ignores EXIF orientation, reads a VP8X canvas instead of the bitstream, applies none of this decoder's refusals, and lives in Uno.UI, which this assembly doesn't reference. It decides whether a document may keep an image's bytes, with the decode budget and frame counts, the same on every platform. Making RichEditBox follow the active codec instead would drop images this decoder can't decode, such as an animated WebP, from documents on WebGPU-only apps.

Tests

Given_ManagedImageDecoder:

  • When_Asset_Then_Size_Read_Agrees_With_Decode: 17 SamplesApp assets, among them an animated GIF, and the animated WebP, HEIC, ICO and text files the decoder refuses. TryGetSize agrees with TryDecode, from an array and from a stream.
  • When_Generated_Image_Then_Size_Read_Agrees_With_Decode: PNG (RGBA, 16-bit grey, 1-bit palette, Adam7), GIF (global and local tables, two frames), BMP (8, 24 and 32 bits, top-down, bit-fields, core header), JPEG with each of the 8 EXIF orientations, WebP VP8 and VP8L.
  • When_Header_Is_Refused_Then_Size_Is_Not_Read: 55 files, one per header rule, that the decoder refuses; 4 of them have no valid header at all. Among them, GIF LZW code sizes of 12, 13, 32 and 44.
  • When_Header_Is_Cut_Or_Corrupted_Then_Size_Read_Agrees_With_Decode: every truncation of 11 files, and 4 corruptions of each of their first 160 bytes. Nothing hangs, and the size read never refuses a file that decodes, nor reports another size.
  • When_Jpeg_Frame_Metadata_Follows_The_First_Scan_Then_It_Is_Ignored: an EXIF block or a frame header after the scan changes neither the size read, the decode nor Skia's decode.
  • When_Exif_Offsets_Are_Hostile_Then_Image_Still_Decodes: an IFD offset or entry count that points anywhere, including past 2 GB and at int.MaxValue, neither throws nor fails the image; an offset outside the file leaves it unrotated.
  • When_Bmp_Palette_Offset_Is_Hostile_Then_Image_Still_Decodes: a DIB header size that puts the palette at int.MaxValue leaves the palette black, as for any palette past the end of the file.
  • When_Gif_Later_Frame_Is_Refused_Then_Size_Is_Still_Read: the size read stops after the first frame, so a second frame the decode refuses doesn't stop the size from being read.

Given_BitmapSource: five tests gain managed rows. When_SetSource_Then_Skia_Reads_Only_The_Header (from #25561) is renamed When_SetSource_Then_Codec_Reads_Only_The_Header; with the managed decoder, it reads under a quarter of a JPEG, a PNG, a BMP and two GIFs.

Taken out one at a time, each of these fails a test: the managed override (the default reads the whole file), the JPEG size read's frame refusals, its first-scan header check and its EXIF swap, the decode's use of markers before the first scan only, the shared GIF code size and PNG palette refusals, the GIF code size check of 12 and up, the EXIF and BMP palette bounds checks, and stopping the GIF size read after the first frame.

Runs of the image test classes. The AnimatedWebP tests fail with the managed decoder, as before, since it declines animated WebP. When_WriteableBitmap_Assigned_With_Data_Present fails the same without these changes (125% scaling).

After the update to master, with Given_ManagedImageDecoder, Given_BitmapSource, Given_WriteableBitmap, Given_BitmapImage, Given_Image, Given_Image_Release, Given_ImageSource, Given_ImageBrush and Given_SvgImageSource_ManagedEngine:

  • Skia desktop: 296 passed, 1 failed.
  • Skia desktop with the managed decoder: 294 passed, 3 failed.
  • Before the update, WebAssembly with the managed decoder: 235 passed, 3 failed.
  • After the review fixes, Skia desktop: Given_ManagedImageDecoder, Given_BitmapSource and Given_WriteableBitmap: 185 passed, 1 failed (When_WriteableBitmap_Assigned_With_Data_Present, as above). Each fix taken out fails its test: the code size 12, 32 and 44 rows; the hostile EXIF offsets at 0x7FFFFFF2 and up; both BMP palette rows; and the GIF later-frame test.
  • GIF size read on a 36 MB, 120-frame GIF from a MemoryStream: 0.06 ms and 38 KB read, against 6.1 ms and 4.5 MB when it walked every frame.

PR Checklist ✅

Copilot AI balanced review requested due to automatic review settings October 18, 2026 02:46

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

The combined binary-parser and asynchronous lifecycle changes require maintainer review and runtime validation before approval.

1 open issue
What changed in this PR

Reduces UI-thread image decoding for #25556 by reading dimensions from headers, extending the stacked backend-neutral sizing work to the managed decoder.

Changes:

  • Shares header parsing between managed size inspection and decoding.
  • Adds backend sizing support and updates source replacement handling.
  • Adds format, malformed-input, read-volume, and lifecycle tests.
File Description
src/​Uno.UI/​UI/​Xaml/​Media/​Imaging/​WriteableBitmap.cs Gets dimensions from the buffer decode.
src/​Uno.UI/​UI/​Xaml/​Media/​Imaging/​BitmapSource.cs Uses header sizing and reloads replaced sources.
src/​Uno.UI/​UI/​Xaml/​Media/​Imaging/​BitmapImage.cs Discards cancelled decode results.
src/​Uno.UI/​UI/​Xaml/​Media/​ImageSource.crossruntime.cs Cancels superseded unobserved opens.
src/​Uno.UI.RuntimeTests/​Microsoft/​UI/​Xaml/​Media/​Imaging/​Given_WriteableBitmap.cs Tests decode counts and async completion.
src/​Uno.UI.RuntimeTests/​Microsoft/​UI/​Xaml/​Media/​Imaging/​Given_BitmapSource.cs Tests sizing, read volume, and replacement.
src/​Uno.UI.RuntimeTests/​Microsoft/​UI/​Composition/​Given_ManagedImageDecoder.cs Tests managed format and header consistency.
src/​Uno.UI.RuntimeTests/​Helpers/​CountingImageCodec.cs Adds codec instrumentation.
src/​Uno.UI.Composition.Skia/​Composition/​Uno/​Drawing/​SkiaImageDecoderBackend.cs Exposes Skia size inspection.
src/​Uno.UI.Composition.Skia/​Composition/​Uno/​Drawing/​SkiaImageDecoder.cs Reads orientation-aware header dimensions.
src/​Uno.UI.Composition.Managed/​ManagedImageDecoderBackend.cs Exposes managed size inspection.
src/​Uno.UI.Composition.Managed/​ManagedImageDecoder.Webp.cs Shares WebP header parsing.
src/​Uno.UI.Composition.Managed/​ManagedImageDecoder.Vp8.cs Supports stream-backed frame-header reads.
src/​Uno.UI.Composition.Managed/​ManagedImageDecoder.Size.cs Dispatches managed size inspection.
src/​Uno.UI.Composition.Managed/​ManagedImageDecoder.Png.cs Shares PNG header validation.
src/​Uno.UI.Composition.Managed/​ManagedImageDecoder.Jpeg.cs Shares JPEG marker and scan-header parsing.
src/​Uno.UI.Composition.Managed/​ManagedImageDecoder.Gif.cs Shares GIF block traversal.
src/​Uno.UI.Composition.Managed/​ManagedImageDecoder.cs Centralizes format detection and byte readers.
src/​Uno.UI.Composition.Managed/​ManagedImageDecoder.Bmp.cs Shares BMP header validation.
src/​Uno.UI.Composition.Managed/​ImageBytes.cs Adds buffered, on-demand stream access.
src/​Uno.UI.Composition.Drawing/​IImageEncoderDecoder.cs Adds sizing with a compatible decode fallback.

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings October 18, 2026 03:09

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

The cross-format parser refactoring and asynchronous image-loading changes warrant human review and independent runtime validation.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@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

SetSource set PixelWidth and PixelHeight from a full decode of the
image on the UI thread (every frame of an animated one) and threw the
pixels away; the image is decoded again when it opens, and a
WriteableBitmap decoded it a second time into its pixel buffer. For a
4000x2667 JPEG that is a 43 MB decode, about 75 ms per call on desktop.
6.8 read only the header with SKCodec, but the backend-neutral codec
seam had no way to do that.

IImageEncoderDecoder gains TryGetSize. It is a default interface method,
so a codec an app registers keeps working: the default decodes and
reads the first frame, as SetSource did. The Skia codec reads the
header and applies the EXIF origin, as TryDecode does. SetSource now
also disposes the stream clone it reads the size from.

WriteableBitmap takes its size from the decode that fills its buffer
instead, so the buffer is sized from the frame copied into it.
SetSource kept the image opened from the previous stream: an Image
already showing the bitmap kept its picture (or showed nothing, if the
bitmap had no stream yet), and an Image shown later got the old image.
WinUI's CImageSource::SetSource cancels the current decode and drops
the current image. SetSourceCore now invalidates the source the same
way, which also cancels an open of the previous stream still in flight
and gives the source its new version.

SetSourceAsync subscribed, then invalidated. With no other subscriber
that opened the source twice: a BitmapImage could decode twice on
desktop (the first open is only cancelled if it hasn't started), and a
WriteableBitmap copied its pixels into an image twice. When the source
still held opened data, subscribing completed at once with it, so the
await returned before the new source opened. It now only subscribes,
after SetSourceCore's invalidation, and returns when that invalidation
opened the source and failed synchronously, since no other result
follows.

@MartinZikmund MartinZikmund left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @mikernet, this is a really careful piece of work. I reviewed the three commits on top of #25561. Every header reader is bounds-checked, nothing escapes TryGetSize, no allocation is sized from the header before the caps are applied, and the cut/corrupt agreement tests are exactly what a parser of untrusted bytes needs. It also merges cleanly with #25542, #25544 and #26370. A few optional nits:

  1. ManagedImageDecoder.Gif.cs, if ((1 << d[p++]) > 4096): C# masks the shift count to 5 bits, so a code size of 32 or more slips through (1 << 32 == 1, 1 << 44 == 4096). That also lets 12 through, even though its clear code (4096) doesn't fit the tables. if (d[p++] >= 12) covers both cases. Today, 32+ "decodes" to garbage instead of being refused.
  2. TryReadExifOrientation (pre-existing): an IFD offset of 0x80000000 or more casts to a negative ifd, and the ifd + 2 > end check doesn't catch that. The read then throws and fails the whole JPEG, where Skia/WIC would just ignore the EXIF. Adding ifd < tiff || to that check would make it best-effort. Your hostile-offsets test passes either way, because both paths fail the same.
  3. Question: the GIF size read walks every frame's sub-block lengths (about one stream read per 255-byte sub-block) so that it matches refusals on later frames. The TryGetSize contract already allows a later decode failure, so stopping after the first frame would keep a huge animated GIF's SetSource cheaper. I'm fine either way.

SetSource already holds its own clone of the stream, so the header read can use it directly and seek back, instead of copying the encoded bytes a second time.
No row in this PR declines to decode, so the test can assert the decode succeeds.
Each format's header rules now live in one reader that the decode runs,
walking the chunk or block headers for PNG and GIF. The readers read
through ImageBytes, a view over the file in memory or a seekable stream
read on demand, so that reading an image's size can run them too and the
two can't drift apart.

Refusals that used to surface as exceptions further in are now explicit,
with the same result: a palette PNG at 16 bits or with no full palette
entry, a GIF whose LZW code size overflows the decoder's tables, a JPEG
with no components, a quantization table slot over 3 or a sampled
component with a zero sampling factor, and a JPEG scan naming a
component, or a table its first blocks read, that isn't defined.
The managed decoder fell back to the TryGetSize default, a full decode:
about 0.5 s and 130 MB for a 4000x2667 JPEG on desktop, on the UI thread
for every SetSource. It now runs the decode's own header readers, so it
refuses every file the decode refuses from those headers (for a JPEG,
the markers before its first scan and that scan's header) and reports
the size the decode produces, EXIF orientation included. A seekable
stream is read on demand: the header, and for PNG and GIF the chunk and
block headers rather than their data.

Tests cover the format assets, generated files for every header refusal
and all 8 EXIF orientations, and cut or corrupted headers.
The managed JPEG decode applied an EXIF orientation, an Adobe transform
or a frame header that came after the first scan, so it could produce
another size than the size read, which stops at the first scan. libjpeg
(and so Skia) and WIC take the frame and its metadata from the markers
before the first scan and ignore later ones. The decode now does the
same: a later marker no longer changes the size, and an unsupported
frame header after a scan is ignored rather than refused, as there.
The check shifted 1 by the code size, and C# masks a shift count to 5 bits, so 32 and above passed and decoded to garbage. A code size of 12 also passed, though its clear and end codes don't fit the 4096-entry tables.
An IFD offset of 2 GB or more wrapped negative, and one that put the IFD at int.MaxValue made the bounds check wrap: either passed the check and threw on the read, failing the whole JPEG. The orientation is best effort, as in Skia and WIC, so the bounds are now checked without adding to the offsets and the image decodes unrotated.
Bounds checks of the form offset + n > length wrap when the offset is near int.MaxValue. A BMP whose DIB header size puts its palette there passed the palette check and threw on the read, failing the image where a palette past the end of the file is otherwise left black. The GIF, PNG and WebP walks get the same form, which compares against the length minus n instead.
The size read walked every frame's sub-block lengths so as to refuse what the decode refuses in later frames: about one stream read per 255 bytes of the whole file. TryGetSize already allows a later decode failure, and a source whose clone reopens a file reads it again on each open, so it now stops after the first frame.
@mikernet
mikernet force-pushed the dev/mikernet/managed-decoder-read-size branch from b5d07c6 to f41825b Compare November 20, 2026 20:57
@mikernet

Copy link
Copy Markdown
Contributor Author

I rebased this onto #25561's two new commits, so it needs a force push. The commits that were reviewed are unchanged, except that the WebP size test's "declined decode" branch is now in 8d8bbf2, together with the managed VP8X row that needs it.

  1. GIF code size: done in 300be3f. The check is now d[p++] >= 12, which refuses 12 (its clear and end codes don't fit the 4096-entry tables) and stops 32 and above from slipping through the masked shift. When_Header_Is_Refused_Then_Size_Is_Not_Read gains code sizes 12, 32 and 44 alongside 13. Without the fix, all three new rows decode.
  2. EXIF IFD offset: done in 95d06a3. ifd < tiff covers the negative offsets. The bounds are now also checked without adding to the offsets (ifd > end - 2, and the entry loop the same way), because an IFD at int.MaxValue - 1 or int.MaxValue made ifd + 2 wrap. The hostile-offsets test, now When_Exif_Offsets_Are_Hostile_Then_Image_Still_Decodes, gains the offsets 0x7FFFFFF2 and 0x7FFFFFF3. It also checks that every one of those JPEGs still decodes, and decodes unrotated when the offset points outside the file. While at it I swept the other header readers for offset + n > length checks (3a5f170). The BMP palette loop had the same wrap: with a DIB header size that puts the palette at int.MaxValue, it threw and failed the image, instead of leaving the palette black as it does for any palette past the end of the file. When_Bmp_Palette_Offset_Is_Hostile_Then_Image_Still_Decodes covers that. The GIF, PNG and WebP walks use the same form now.
  3. GIF size walk: done, as you suggested (f41825b). The size read stops after the first frame. Walking every frame was cheap from memory, but a source whose clone reopens a file reads it again for every open. When_Gif_Later_Frame_Is_Refused_Then_Size_Is_Still_Read covers a second frame the decode refuses: the size is still read, and the open fails later, as TryGetSize allows. Measured on a 36 MB GIF with 120 frames of 480x480, read from a MemoryStream: the size read went from 6.1 ms (141k block reads, 4.5 MB read) to 0.06 ms (1,216 reads, 38 KB).

On Skia desktop, Given_ManagedImageDecoder, Given_BitmapSource and Given_WriteableBitmap: 185 passed, 1 failed (When_WriteableBitmap_Assigned_With_Data_Present, which fails the same on master at 125% scaling). With the EXIF and BMP bounds checks put back to the wrapping form, and with the GIF size read walking every frame again, the hostile-offsets, BMP palette and later-frame tests fail.

mikernet added a commit to Singulink/uno that referenced this pull request Nov 20, 2026
The managed VP8X row declines to decode, which the dead branch removed
from this test covered. Upstream folds this into the managed decoder
size commit of unoplatform#25566 (8d8bbf2).
@MartinZikmund

Copy link
Copy Markdown
Member

/azp run

@azure-pipelines

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

@unodevops

Copy link
Copy Markdown
Contributor

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

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 248668 found UI Test snapshots differences: skia-linux-screenshots: 233, skia-windows-screenshots: 288

Details
  • skia-linux-screenshots: 233 changed over 2504

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • AnimatedBackVisualSourceSamplePage.png-dark
    • AutomationProperties_StructureAndProps.png-dark
    • AutomationProperties_StructureAndProps.png
    • Accessibility_Showcase.png
    • AppWindowTitleBar Properties.png-dark
    • Basics.png-dark
    • Basics.png
    • BenchmarkDotNet.png-dark
    • BenchmarkDotNet.png
    • CompositionNineGridBrush_Source_Changes.png-dark
    • CompositionNineGridBrush_Source_Changes.png
    • Accessibility_Showcase.png-dark
    • BitmapIcon_Foreground.png-dark
    • BitmapIcon_Foreground.png
    • ButtonClippingTestsControl.png-dark
    • ButtonClippingTestsControl.png
    • Buttons.png-dark
    • Buttons.png
    • ComboBox_MaxDropdownHeight.png-dark
    • ComboBox_MaxDropdownHeight.png
  • skia-windows-screenshots: 288 changed over 2504

    🚨🚨 Comparison Details (first 20) 🚨🚨
    • BasicAcrylicBrushTest2.png-dark
    • BasicAcrylicBrushTest2.png
    • AnimatedBackVisualSourceSamplePage.png-dark
    • AppWindowTitleBar Properties.png
    • AutomationProperties_AutomationId.png
    • BreadcrumbBarPage.png-dark
    • BreadcrumbBarPage.png
    • CalendarView_Theming.png-dark
    • CalendarView_Theming.png
    • ColorPickerSample.png-dark
    • ColorPickerSample.png
    • AnimatedVisualsTestbedPage.png
    • AutomationProperties_AutomationId.png-dark
    • BenchmarkDotNet.png-dark
    • BenchmarkDotNet.png
    • Border_CornerRadius_BorderThickness.png-dark
    • Border_CornerRadius_BorderThickness.png
    • Buttons.png-dark
    • AnimatedBackVisualSourceSamplePage.png
    • AnimatedVisualsTestbedPage.png-dark

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants