fix: full verification against the brief — 137 confirmed findings fixed over six passes #4

Merged
Alby96 merged 169 commits from claude/keen-knuth-uhxv8w into main 2026-10-13 12:10:04 +02:00
3 changed files with 283 additions and 0 deletions
Showing only changes of commit a8cf92b4a4 - Show all commits

No files matched your search

@@ -65,6 +65,48 @@ public sealed class MediaFoundationEncoderTests(TestContext context)
Assert.Count(1, Directory.GetFiles(dir)); // no temporary file left behind
}
/// <summary>
/// BRIEF §20.2: what the encoder writes plays in Windows. MediaPlayer (Windows Media Player's pipeline) opens it at
/// the encoded size and length; a Media Foundation source reader decodes its first frame to the picture that was
/// encoded, which is the whole check where Windows Media Player is not installed (Windows Server, "N" editions).
/// </summary>
[Test]
[WindowsOnly]
[Timeout(120_000)]
public void SoftwareH264OutputPlaysBack()
{
RequireEncoder(VideoCodec.H264, hardware: false, tenBit: false);
var dir = context.CreateTempDirectory();
var settings = Settings(Path.Combine(dir, "playback.mp4"), VideoCodec.H264, 8) with { PreferHardware = false };
using (var session = new MediaFoundationEncoderProvider().Open(settings))
{
WriteFrames(session, 60, 8);
session.Complete();
}
if (Mp4Playback.HasMediaPlayer)
{
var opened = Mp4Playback.OpenWithMediaPlayer(settings.OutputPath, TimeSpan.FromSeconds(60));
context.Log($"MediaPlayer: {opened}");
Assert.Equal(1280, opened.Width);
Assert.Equal(720, opened.Height);
Assert.Approximately(2.0, opened.Duration.TotalSeconds, 0.05);
}
else
{
context.Log("Windows Media Player is not installed: the source reader decode is the playback check");
}
var frame = Mp4Playback.DecodeFirstFrame(settings.OutputPath);
context.Log($"source reader: {frame.Width}×{frame.Height}, {frame.Duration}, luma square {frame.LumaAt(100, 360)}, corner {frame.LumaAt(4, 4)}");
Assert.Equal(1280, frame.Width);
Assert.Equal(720, frame.Height);
Assert.Approximately(2.0, frame.Duration.TotalSeconds, 0.05);
// Frame 0 as WriteFrames drew it: the white square centred at (100, 360) on a dark blue corner.
Assert.Greater(frame.LumaAt(100, 360), 200);
Assert.Less(frame.LumaAt(4, 4), 60);
}
[Test]
[WindowsOnly]
[Timeout(60_000)]
@@ -0,0 +1,237 @@
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling;
using System.Windows.Media;
using System.Windows.Threading;
using Titano.Core.Windows.Interop;
using Titano.Core.Windows.MediaFoundation;
namespace Titano.Core.Windows.Tests.MediaFoundation;
/// <summary>
/// How Windows plays a written MP4 back (BRIEF §20.2): WPF's <see cref="MediaPlayer"/>, which runs on Windows Media
/// Player's pipeline, or, where Windows Media Player is not installed (Windows Server, "N" editions), a Media
/// Foundation source reader that decodes the first frame.
/// </summary>
internal static partial class Mp4Playback
{
/// <summary>What a player reports once the file is open.</summary>
public sealed record Opened(int Width, int Height, TimeSpan Duration);
/// <summary>The first decoded frame: its size, the file's duration and the luma plane (8 bits, top-down, no padding).</summary>
public sealed record FirstFrame(int Width, int Height, TimeSpan Duration, byte[] Luma)
{
public byte LumaAt(int x, int y) => Luma[y * Width + x];
}
/// <summary>True when <see cref="MediaPlayer"/> can work: it needs Windows Media Player (wmp.dll).</summary>
public static bool HasMediaPlayer
{
get
{
if (!NativeLibrary.TryLoad("wmp.dll", out var handle)) return false;
NativeLibrary.Free(handle);
return true;
}
}
/// <summary>
/// Opens <paramref name="path"/> with <see cref="MediaPlayer"/> on its own dispatcher thread and returns what it
/// reports at <see cref="MediaPlayer.MediaOpened"/>. Throws when it raises <see cref="MediaPlayer.MediaFailed"/> or
/// neither event comes within <paramref name="timeout"/>.
/// </summary>
public static Opened OpenWithMediaPlayer(string path, TimeSpan timeout)
{
Opened? opened = null;
Exception? failure = null;
var thread = new Thread(() =>
{
var dispatcher = Dispatcher.CurrentDispatcher;
var player = new MediaPlayer();
DispatcherTimer? deadline = null;
void Finish()
{
deadline?.Stop();
player.Close();
dispatcher.InvokeShutdown();
}
player.MediaOpened += (_, _) =>
{
opened = new Opened(player.NaturalVideoWidth, player.NaturalVideoHeight,
player.NaturalDuration.HasTimeSpan ? player.NaturalDuration.TimeSpan : TimeSpan.Zero);
Finish();
};
player.MediaFailed += (_, e) =>
{
failure = new InvalidDataException($"MediaPlayer could not open '{path}': {e.ErrorException.Message}", e.ErrorException);
Finish();
};
// This constructor starts the timer.
deadline = new DispatcherTimer(timeout, DispatcherPriority.Normal, (_, _) =>
{
failure = new TimeoutException($"MediaPlayer neither opened nor failed on '{path}' within {timeout.TotalSeconds:0} s");
Finish();
}, dispatcher);
player.Open(new Uri(path, UriKind.Absolute));
Dispatcher.Run();
})
{
IsBackground = true,
Name = "MediaPlayer check",
};
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
return opened ?? throw failure ?? new InvalidOperationException("MediaPlayer stopped without a result");
}
/// <summary>Decodes the first video frame of <paramref name="path"/> to NV12 with a Media Foundation source reader.</summary>
public static unsafe FirstFrame DecodeFirstFrame(string path)
{
using var runtime = MediaFoundationRuntime.Acquire();
ComObjects.Check(MFCreateSourceReaderFromURL(path, 0, out var readerPointer), "MFCreateSourceReaderFromURL");
var reader = ComObjects.Attach<IMFSourceReader>(readerPointer);
try
{
var duration = TimeSpan.Zero;
var variant = stackalloc byte[PropVariantSize];
new Span<byte>(variant, PropVariantSize).Clear();
if (reader.GetPresentationAttribute(MediaSource, PresentationDuration, (nint)variant) >= 0)
{
if (*(ushort*)variant == VtUi8) duration = TimeSpan.FromTicks((long)*(ulong*)(variant + 8));
PropVariantClear((nint)variant);
}
// The reader inserts the H.264/HEVC decoder itself once NV12 is asked for.
ComObjects.Check(MfNative.MFCreateMediaType(out var typePointer), "MFCreateMediaType");
var type = ComObjects.Attach<IMFMediaType>(typePointer);
try
{
ComObjects.Check(type.SetGUID(MfGuids.MajorType, MfGuids.MediaTypeVideo), "MF_MT_MAJOR_TYPE");
ComObjects.Check(type.SetGUID(MfGuids.Subtype, MfGuids.FormatNv12), "MF_MT_SUBTYPE");
var native = ComObjects.GetPointer(type);
try
{
ComObjects.Check(reader.SetCurrentMediaType(FirstVideoStream, 0, native), "SetCurrentMediaType(NV12)");
}
finally
{
Marshal.Release(native);
}
}
finally
{
ComObjects.Release(type);
}
var sample = ReadFirstSample(reader);
try
{
ComObjects.Check(reader.GetCurrentMediaType(FirstVideoStream, out var currentPointer), "GetCurrentMediaType");
var current = ComObjects.Attach<IMFMediaType>(currentPointer);
ulong size;
try
{
ComObjects.Check(current.GetUINT64(MfGuids.FrameSize, out size), "MF_MT_FRAME_SIZE");
}
finally
{
ComObjects.Release(current);
}
var (width, height) = ((int)(size >> 32), (int)(size & 0xFFFF_FFFF));
return new FirstFrame(width, height, duration, CopyLuma(sample, width, height));
}
finally
{
ComObjects.Release(sample);
}
}
finally
{
ComObjects.Release(reader);
}
}
/// <summary>Reads until the first video sample; stream ticks and format changes come without one.</summary>
private static IMFSample ReadFirstSample(IMFSourceReader reader)
{
for (var attempt = 0; attempt < 100; attempt++)
{
ComObjects.Check(reader.ReadSample(FirstVideoStream, 0, out _, out var flags, out _, out var samplePointer), "ReadSample");
if (samplePointer != 0) return ComObjects.Attach<IMFSample>(samplePointer);
if ((flags & (ReaderError | ReaderEndOfStream)) != 0) throw new InvalidDataException($"The source reader returned no frame (flags 0x{flags:X})");
}
throw new InvalidDataException("The source reader returned no frame in 100 reads");
}
/// <summary>Copies the Y plane out of the sample's buffer, honouring the decoder's row pitch.</summary>
private static unsafe byte[] CopyLuma(IMFSample sample, int width, int height)
{
ComObjects.Check(sample.ConvertToContiguousBuffer(out var bufferPointer), "ConvertToContiguousBuffer");
var buffer = ComObjects.Attach<IMFMediaBuffer>(bufferPointer);
try
{
var luma = new byte[width * height];
if (buffer is IMF2DBuffer twoD && twoD.Lock2D(out var scanline0, out var pitch) >= 0)
{
try
{
for (var y = 0; y < height; y++) new ReadOnlySpan<byte>((byte*)scanline0 + (long)y * pitch, width).CopyTo(luma.AsSpan(y * width));
}
finally
{
twoD.Unlock2D();
}
return luma;
}
ComObjects.Check(buffer.Lock(out var data, out _, out var length), "IMFMediaBuffer.Lock");
try
{
// A contiguous NV12 frame: the Y rows, then half as many interleaved chroma rows, all of one pitch.
var stride = (int)(length / (uint)(height + height / 2));
if (stride < width) throw new InvalidDataException($"An NV12 buffer of {length} bytes is too small for {width}×{height}");
for (var y = 0; y < height; y++) new ReadOnlySpan<byte>((byte*)data + (long)y * stride, width).CopyTo(luma.AsSpan(y * width));
return luma;
}
finally
{
buffer.Unlock();
}
}
finally
{
ComObjects.Release(buffer);
}
}
private const uint FirstVideoStream = 0xFFFF_FFFC; // MF_SOURCE_READER_FIRST_VIDEO_STREAM
private const uint MediaSource = 0xFFFF_FFFF; // MF_SOURCE_READER_MEDIASOURCE
private const uint ReaderError = 0x1, ReaderEndOfStream = 0x2; // MF_SOURCE_READERF_ERROR, _ENDOFSTREAM
private const ushort VtUi8 = 21;
private const int PropVariantSize = 24; // PROPVARIANT on 64-bit Windows
/// <summary>MF_PD_DURATION: the presentation's length in 100 ns units.</summary>
private static readonly Guid PresentationDuration = new("6c990d33-bb8e-477a-8598-0d5d96fcd88a");
[LibraryImport("mfreadwrite.dll", StringMarshalling = StringMarshalling.Utf16)]
private static partial int MFCreateSourceReaderFromURL(string url, nint attributes, out nint reader);
[LibraryImport("ole32.dll")]
private static partial int PropVariantClear(nint variant);
}
/// <summary>IMFSourceReader (mfreadwrite.h) in vtable order.</summary>
[GeneratedComInterface]
[Guid("70ae66f2-c809-4e4f-8915-bdcb406b7993")]
internal partial interface IMFSourceReader
{
[PreserveSig] int GetStreamSelection(uint streamIndex, out int selected);
[PreserveSig] int SetStreamSelection(uint streamIndex, int selected);
[PreserveSig] int GetNativeMediaType(uint streamIndex, uint mediaTypeIndex, out nint mediaType);
[PreserveSig] int GetCurrentMediaType(uint streamIndex, out nint mediaType);
[PreserveSig] int SetCurrentMediaType(uint streamIndex, nint reserved, nint mediaType);
[PreserveSig] int SetCurrentPosition(in Guid timeFormat, nint position);
[PreserveSig] int ReadSample(uint streamIndex, uint controlFlags, out uint actualStreamIndex, out uint streamFlags, out long timestamp, out nint sample);
[PreserveSig] int Flush(uint streamIndex);
[PreserveSig] int GetServiceForStream(uint streamIndex, in Guid service, in Guid iid, out nint instance);
[PreserveSig] int GetPresentationAttribute(uint streamIndex, in Guid attribute, nint value);
}
@@ -4,6 +4,10 @@
<TargetFramework>net10.0-windows</TargetFramework>
<RootNamespace>Titano.Core.Windows.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<!-- WPF's MediaPlayer for the playback check (BRIEF §20.2); not UseWPF, which would also change the implicit usings. -->
<FrameworkReference Include="Microsoft.WindowsDesktop.App.WPF" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Titano.Testing\Titano.Testing.csproj" />
<ProjectReference Include="..\..\src\Titano.Core.Windows\Titano.Core.Windows.csproj" />