Repository navigation
Conversation
There was a problem hiding this comment.
🔵 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
|
Tick the box to add this pull request to the merge queue (same as
|
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.
5d0ed22 to
b5d07c6
Compare
MartinZikmund
left a comment
There was a problem hiding this comment.
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:
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.TryReadExifOrientation(pre-existing): an IFD offset of0x80000000or more casts to a negativeifd, and theifd + 2 > endcheck doesn't catch that. The read then throws and fails the whole JPEG, where Skia/WIC would just ignore the EXIF. Addingifd < tiff ||to that check would make it best-effort. Your hostile-offsets test passes either way, because both paths fail the same.- 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
TryGetSizecontract already allows a later decode failure, so stopping after the first frame would keep a huge animated GIF'sSetSourcecheaper. 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.
b5d07c6 to
f41825b
Compare
|
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
On Skia desktop, |
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).
|
/azp run |
|
Azure Pipelines: Successfully started running 1 pipeline(s). 1 pipeline(s) were filtered out due to trigger conditions. |
|
🤖 Your WebAssembly Sample App stage site is ready! Visit it here: |
|
The build 248668 found UI Test snapshots differences: Details
|

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 everyBitmapSource.SetSourcestill decodes the whole image on the UI thread.TryGetSizeruns 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.TryGetSizecan 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:
SetSource, UI thread (median)SetSource¹ master's
SetSource, a full decode, as #25561 alone still does with this decoder, timed on this branch. ² The two stream clonesSetSourcemade 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
RichEditBoxfollow 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.TryGetSizeagrees withTryDecode, 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 atint.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 atint.MaxValueleaves 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 renamedWhen_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
AnimatedWebPtests fail with the managed decoder, as before, since it declines animated WebP.When_WriteableBitmap_Assigned_With_Data_Presentfails 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_ImageBrushandGiven_SvgImageSource_ManagedEngine:Given_ManagedImageDecoder,Given_BitmapSourceandGiven_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 at0x7FFFFFF2and up; both BMP palette rows; and the GIF later-frame test.MemoryStream: 0.06 ms and 38 KB read, against 6.1 ms and 4.5 MB when it walked every frame.PR Checklist ✅
Screenshots Compare Test Runresults.