using System.Runtime.InteropServices;
namespace Titano.Core.Windows.Codecs;
///
/// Detects HEVC and AV1 decoders with MFTEnumEx, the check Microsoft documents for the codecs that HEIC and
/// AVIF decoding through WIC depend on (HEVC / AV1 Video Extensions or a vendor hardware decoder).
///
internal static unsafe partial class VideoDecoderProbe
{
/// MFVideoFormat_HEVC (FOURCC 'HEVC').
public static readonly Guid Hevc = new("43564548-0000-0010-8000-00aa00389b71");
/// MFVideoFormat_AV1 (FOURCC 'AV01').
public static readonly Guid Av1 = new("31305641-0000-0010-8000-00aa00389b71");
private static readonly Guid VideoDecoderCategory = new("d6c02d4b-6833-45b4-971a-05a4b04bab91");
private static readonly Guid MediaTypeVideo = new("73646976-0000-0010-8000-00aa00389b71");
private const uint MF_VERSION = 0x00020070;
private const uint MFSTARTUP_LITE = 0x1;
private const uint MFT_ENUM_FLAG_SYNCMFT = 0x1, MFT_ENUM_FLAG_ASYNCMFT = 0x2, MFT_ENUM_FLAG_HARDWARE = 0x4, MFT_ENUM_FLAG_SORTANDFILTER = 0x40;
/// True when at least one decoder MFT accepts the video .
public static bool HasDecoder(Guid subtype)
{
try
{
if (MFStartup(MF_VERSION, MFSTARTUP_LITE) < 0) return false;
try
{
var input = new MftRegisterTypeInfo { MajorType = MediaTypeVideo, Subtype = subtype };
const uint flags = MFT_ENUM_FLAG_SYNCMFT | MFT_ENUM_FLAG_ASYNCMFT | MFT_ENUM_FLAG_HARDWARE | MFT_ENUM_FLAG_SORTANDFILTER;
if (MFTEnumEx(VideoDecoderCategory, flags, &input, null, out var activates, out var count) < 0) return false;
for (var i = 0; i < count; i++) Marshal.Release(((nint*)activates)[i]);
Marshal.FreeCoTaskMem(activates);
return count > 0;
}
finally
{
MFShutdown();
}
}
catch (DllNotFoundException)
{
// Windows "N" editions ship without Media Foundation unless the Media Feature Pack is installed.
return false;
}
}
[StructLayout(LayoutKind.Sequential)]
private struct MftRegisterTypeInfo
{
public Guid MajorType;
public Guid Subtype;
}
[LibraryImport("mfplat.dll")]
private static partial int MFStartup(uint version, uint flags);
[LibraryImport("mfplat.dll")]
private static partial int MFShutdown();
[LibraryImport("mfplat.dll")]
private static partial int MFTEnumEx(Guid category, uint flags, MftRegisterTypeInfo* inputType, MftRegisterTypeInfo* outputType, out nint activates, out uint count);
}