using System.Runtime.InteropServices; using Titano.Core.Diagnostics; using Titano.Core.Windows.Codecs; using Titano.Core.Windows.Interop; namespace Titano.Core.Windows.Wic; /// Enumerates installed WIC decoders through IWICImagingFactory::CreateComponentEnumerator. internal static class WicComponents { private const uint ComponentDecoder = 0x1; private const uint EnumerateRefresh = 0x1; private const uint EnumerateUnsigned = 0x40000000; /// /// Every enabled decoder, signed or not (third-party camera codecs are often unsigned and WIC still uses them). /// makes WIC re-read the registrations, e.g. after a Store extension was installed. /// public static IReadOnlyList EnumerateDecoders(bool refresh) { Win32Com.EnsureInitialized(); var decoders = new List(); var enumerator = WicFactory.Instance.CreateComponentEnumerator(ComponentDecoder, EnumerateUnsigned | (refresh ? EnumerateRefresh : 0)); try { while (enumerator.Next(1, out var unknown, out var fetched) == 0 && fetched == 1) { object? component = null; try { component = Marshal.GetObjectForIUnknown(unknown); if (component is IWICBitmapDecoderInfo info) decoders.Add(Read(info)); } catch (COMException ex) { Log.Warning("wic", "Skipped a WIC decoder whose registration could not be read", ex); } finally { Marshal.Release(unknown); Win32Com.Release(component); } } } finally { Win32Com.Release(enumerator); } return decoders; } /// Reads a component-info string through the "ask for the length, then fill" protocol. public static unsafe string ReadString(WicStringGetter getter) { if (getter(0, null, out var length) < 0 || length <= 1) return string.Empty; var buffer = new char[length]; int hr; fixed (char* p = buffer) { hr = getter(length, p, out length); } if (hr < 0) return string.Empty; var text = buffer.AsSpan(0, (int)Math.Min(length, (uint)buffer.Length)); var end = text.IndexOf('\0'); return new string(end >= 0 ? text[..end] : text); } // Lambdas call through the interface normally rather than binding delegates to COM methods. private static unsafe WicDecoderInfo Read(IWICBitmapDecoderInfo info) => new( FriendlyName: ReadString((uint capacity, char* buffer, out uint length) => info.GetFriendlyName(capacity, buffer, out length)), Clsid: info.GetCLSID(), ContainerFormat: info.GetContainerFormat(), Vendor: info.GetVendorGUID(), Version: ReadString((uint capacity, char* buffer, out uint length) => info.GetVersion(capacity, buffer, out length)), FileExtensions: WicDecoderInfo.ParseExtensions( ReadString((uint capacity, char* buffer, out uint length) => info.GetFileExtensions(capacity, buffer, out length))), Extension: null); }