Skip to content

Commit c13eba7

Browse files
committed
fix(imaging): Release a decoded image when nothing displays it
A decoded image's pixels were released only through a chain of finalizers: the ImageSource kept its ImageData after its last subscriber left, the SkiaCompositionSurface disposed its frames only when finalized, and on WebAssembly the browser-decoded pixels were a pinned managed array freed by the Skia image's release callback, so each step needed another collection. Paging through large images parked hundreds of megabytes until the chain ran, and the wasm heap grew to fit each peak for good. The source now releases its decoded data as soon as its last subscriber leaves or the source is invalidated, as WinUI drops a decoded surface once its last user lets go, and decodes again if something subscribes later. A BitmapImage marks data that came through the shared bitmap cache as not its own, so a cached surface is never released under other sources. On Skia the Image element releases its subscription when it is unloaded and subscribes again when loaded, so navigating away from a page releases every image on it; it clears its sprite first so nothing draws a released surface. The WebAssembly decode copies the pixels into native memory instead of pinning the managed array, so the release frees them at once and the array is ordinary garbage. unoplatform#25114
1 parent 06d268c commit c13eba7

7 files changed

Lines changed: 188 additions & 24 deletions

File tree

‎src/Uno.UI.Composition/Composition/SkiaCompositionSurface.skia.cs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,13 @@ private void SetFrameProviderAndOnFrameChanged(IFrameProvider? provider, Action?
5151
_onFrameChanged = onFrameChanged;
5252
}
5353

54+
/// <summary>
55+
/// Releases the decoded frames now, for an image nothing displays anymore, instead of leaving them to the finalizer
56+
/// (which only runs once the surface has been collected, so the pixels outlive the element by several collections).
57+
/// <see cref="Image"/> is null afterwards; loading frames again makes the surface usable.
58+
/// </summary>
59+
internal void ReleaseFrames() => SetFrameProviderAndOnFrameChanged(null, null);
60+
5461
internal (bool success, object nativeResult) LoadFromStream(Stream imageStream) => LoadFromStream(null, null, imageStream);
5562

5663
internal (bool success, object nativeResult) LoadFromStream(int? targetWidth, int? targetHeight, Stream imageStream)
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
#if HAS_UNO
2+
using System;
3+
using System.Threading.Tasks;
4+
using Microsoft.UI.Xaml.Controls;
5+
using Microsoft.UI.Xaml.Media.Imaging;
6+
using Private.Infrastructure;
7+
using Uno.UI.RuntimeTests.Helpers;
8+
using static Private.Infrastructure.TestServices;
9+
10+
namespace Uno.UI.RuntimeTests.Tests.Windows_UI_Xaml_Controls;
11+
12+
[TestClass]
13+
[RunsOnUIThread]
14+
[PlatformCondition(ConditionMode.Include, RuntimeTestPlatforms.Skia)]
15+
public class Given_Image_Release
16+
{
17+
private const string AssetUri = "ms-appx:///Assets/my500x200.jpg";
18+
19+
[TestMethod]
20+
[GitHubWorkItem("https://github.com/unoplatform/uno/issues/25114")]
21+
public async Task When_Unloaded_Then_Decoded_Image_Released()
22+
{
23+
// The source owns its decoded data only when the cache does not share it between sources.
24+
var cacheWasEnabled = FeatureConfiguration.Image.EnableBitmapImageCache;
25+
FeatureConfiguration.Image.EnableBitmapImageCache = false;
26+
27+
try
28+
{
29+
var bitmap = new BitmapImage(new Uri(AssetUri));
30+
var image = new Image { Width = 100, Height = 40, Source = bitmap };
31+
32+
await LoadAndWaitForOpened(image);
33+
Assert.IsTrue(bitmap.IsOpened, "Pre-condition: the bitmap is decoded while an Image shows it");
34+
35+
WindowHelper.WindowContent = null;
36+
await WindowHelper.WaitForIdle();
37+
Assert.IsFalse(bitmap.IsOpened, "Nothing displays the bitmap once its only Image is unloaded, so the decoded data must be released");
38+
39+
// Showing it again decodes it again.
40+
await LoadAndWaitForOpened(image);
41+
Assert.IsTrue(bitmap.IsOpened, "An Image that is loaded again must decode its source again");
42+
}
43+
finally
44+
{
45+
WindowHelper.WindowContent = null;
46+
FeatureConfiguration.Image.EnableBitmapImageCache = cacheWasEnabled;
47+
}
48+
}
49+
50+
[TestMethod]
51+
[GitHubWorkItem("https://github.com/unoplatform/uno/issues/25114")]
52+
public async Task When_Source_Replaced_Then_Previous_Decoded_Image_Released()
53+
{
54+
var cacheWasEnabled = FeatureConfiguration.Image.EnableBitmapImageCache;
55+
FeatureConfiguration.Image.EnableBitmapImageCache = false;
56+
57+
try
58+
{
59+
var first = new BitmapImage(new Uri(AssetUri));
60+
var image = new Image { Width = 100, Height = 40, Source = first };
61+
62+
await LoadAndWaitForOpened(image);
63+
Assert.IsTrue(first.IsOpened, "Pre-condition: the first bitmap is decoded while the Image shows it");
64+
65+
var opened = TrackOpened(image);
66+
image.Source = new BitmapImage(new Uri(AssetUri));
67+
await opened.WaitAsync(TimeSpan.FromSeconds(10));
68+
69+
Assert.IsFalse(first.IsOpened, "The replaced bitmap is shown by nothing, so its decoded data must be released");
70+
}
71+
finally
72+
{
73+
WindowHelper.WindowContent = null;
74+
FeatureConfiguration.Image.EnableBitmapImageCache = cacheWasEnabled;
75+
}
76+
}
77+
78+
private static async Task LoadAndWaitForOpened(Image image)
79+
{
80+
var opened = TrackOpened(image);
81+
await UITestHelper.Load(image);
82+
await opened.WaitAsync(TimeSpan.FromSeconds(10));
83+
}
84+
85+
private static Task TrackOpened(Image image)
86+
{
87+
var tcs = new TaskCompletionSource();
88+
image.ImageOpened += (_, _) => tcs.TrySetResult();
89+
image.ImageFailed += (_, e) => tcs.TrySetException(new Exception($"Failed to load the image: {e.ErrorMessage}"));
90+
return tcs.Task;
91+
}
92+
}
93+
#endif

‎src/Uno.UI/UI/Xaml/Controls/Image/Image.skia.cs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,29 @@ protected override Size ArrangeOverride(Size finalSize)
202202
}
203203
}
204204

205+
private protected override void OnLoaded()
206+
{
207+
base.OnLoaded();
208+
209+
// The subscription was released on unload: subscribe again, which decodes the source again.
210+
if (_sourceDisposable.Disposable is null && Source is { } source)
211+
{
212+
OnSourceChanged(source, forceReload: false);
213+
}
214+
}
215+
216+
private protected override void OnUnloaded()
217+
{
218+
base.OnUnloaded();
219+
220+
// Nothing displays this image while it is unloaded, so its subscription is released, which lets the source release
221+
// its decoded pixels; the sprite must not keep pointing at them.
222+
_imageSprite.Brush = null;
223+
_currentSurface = null;
224+
_pendingImageData = null;
225+
_sourceDisposable.Disposable = null;
226+
}
227+
205228
partial void OnMonochromeColorChanged()
206229
{
207230
if (_surfaceBrush is not null)

‎src/Uno.UI/UI/Xaml/Media/ImageSource.crossruntime.cs‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,9 +74,38 @@ internal IDisposable Subscribe(Action<ImageData> onSourceOpened)
7474
Open();
7575
}
7676

77-
return Disposable.Create(() => _subscriptions.Remove(onSourceOpened));
77+
return Disposable.Create(() =>
78+
{
79+
_subscriptions.Remove(onSourceOpened);
80+
81+
// Nothing displays the image anymore: its decoded pixels are released now, as WinUI drops a decoded surface
82+
// once its last user lets go, and decoded again if something subscribes later.
83+
if (_subscriptions.Count == 0)
84+
{
85+
ReleaseImageData();
86+
}
87+
});
7888
}
7989

90+
/// <summary>
91+
/// Whether the decoded data is shared with other sources (a cached load), in which case this source must not release it.
92+
/// </summary>
93+
private protected bool SharesImageData { get; set; }
94+
95+
private void ReleaseImageData()
96+
{
97+
_opening.Disposable = null;
98+
99+
if (!SharesImageData)
100+
{
101+
ReleaseImageDataPlatform();
102+
}
103+
104+
_imageData = ImageData.Empty;
105+
}
106+
107+
partial void ReleaseImageDataPlatform();
108+
80109
/// <summary>
81110
/// Indicates that this source has already been opened
82111
/// (So the onSourceOpened callback of Subscribe will be invoked synchronously!)
@@ -85,7 +114,7 @@ internal IDisposable Subscribe(Action<ImageData> onSourceOpened)
85114

86115
private protected void InvalidateSource()
87116
{
88-
_imageData = default;
117+
ReleaseImageData();
89118
if (_subscriptions.Count > 0 || this is SvgImageSource)
90119
{
91120
Open();
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#nullable enable
2+
3+
using Uno.UI.Xaml.Media;
4+
5+
namespace Microsoft.UI.Xaml.Media;
6+
7+
partial class ImageSource
8+
{
9+
partial void ReleaseImageDataPlatform()
10+
{
11+
if (_imageData.Kind == ImageDataKind.CompositionSurface)
12+
{
13+
_imageData.CompositionSurface?.ReleaseFrames();
14+
}
15+
}
16+
}

‎src/Uno.UI/UI/Xaml/Media/Imaging/BitmapImage.skia.cs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ private async Task<ImageData> TryOpenSourceAsync(CancellationToken ct)
5858
try
5959
{
6060
var (decodeWidth, decodeHeight) = GetDecodePixelSize();
61+
SharesImageData = false;
6162
var uri = UriSource;
6263
if (uri is null)
6364
{
@@ -126,6 +127,10 @@ private async Task<ImageData> TryOpenSourceAsync(CancellationToken ct)
126127
var ignoreCache = CreateOptions.HasFlag(BitmapCreateOptions.IgnoreImageCache);
127128
var cacheKey = new BitmapImageCacheKey(uri, decodeWidth, decodeHeight);
128129

130+
// With the cache on, the decoded surface is shared with every source that loads the same key, so it is the
131+
// cache's to release, not this source's.
132+
SharesImageData = FeatureConfiguration.Image.EnableBitmapImageCache;
133+
129134
if (ignoreCache
130135
|| !_bitmapImageCache.TryGetValue(cacheKey, out var imageDataTask))
131136
{

‎src/Uno.UI/UI/Xaml/Media/Imaging/ImageSourceHelpers.cs‎

Lines changed: 13 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
using Uno.Foundation.Logging;
1717

1818
#if __SKIA__
19-
using System.Runtime.InteropServices;
2019
using SkiaSharp;
2120
using System.Runtime.InteropServices.JavaScript;
2221
#endif
@@ -67,30 +66,22 @@ public static async Task<ImageData> ReadFromStreamAsCompositionSurface(Stream im
6766
}
6867

6968
var bytes = decodedBufferObject.GetPropertyAsByteArray("bytes");
70-
SKImage image;
71-
unsafe
69+
70+
try
7271
{
73-
var gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
74-
fixed (void* ptr = bytes)
72+
// Copied into native memory: releasing the surface then frees the pixels at once, and the managed array is
73+
// ordinary garbage. Pinning it instead kept it on the managed heap until a chain of finalizers unpinned it.
74+
var image = SKImage.FromPixelCopy(new SKImageInfo(width, height, SKColorType.Rgba8888), bytes);
75+
if (image == null)
7576
{
76-
try
77-
{
78-
image = SKImage.FromPixels(new SKPixmap(new SKImageInfo(width, height, SKColorType.Rgba8888), new IntPtr(ptr)), static (_, gcHandle) =>
79-
{
80-
((GCHandle)gcHandle).Free();
81-
}, gcHandle);
82-
if (image == null)
83-
{
84-
throw new InvalidOperationException($"{nameof(SKImage)}.{nameof(SKImage.FromPixels)} returned null.");
85-
}
86-
return ImageData.FromCompositionSurface(new SkiaCompositionSurface(image));
87-
}
88-
catch (Exception e)
89-
{
90-
gcHandle.Free();
91-
return ImageData.FromError(e);
92-
}
77+
throw new InvalidOperationException($"{nameof(SKImage)}.{nameof(SKImage.FromPixelCopy)} returned null.");
9378
}
79+
80+
return ImageData.FromCompositionSurface(new SkiaCompositionSurface(image));
81+
}
82+
catch (Exception e)
83+
{
84+
return ImageData.FromError(e);
9485
}
9586
}
9687
}

0 commit comments

Comments
 (0)