test(windows): MediaPlayer and source-reader playback as separate tests

The MediaPlayer check ran on an STA thread with no exception handling: a WPF
NotSupportedException from new MediaPlayer(), an exception from Open or from an
event handler inside Dispatcher.Run ended the whole Titano.Core.Windows.Tests
process. Every outcome now goes through one Finish that closes the player and
stops the dispatcher once, and the exception is rethrown on the test thread with
its own type and stack trace.

Where Windows Media Player is missing the playback test passed with only a log
line. It is split into MediaPlayerOpensTheSoftwareH264Output, skipped with the
reason where Windows Media Player is missing or unusable, and
SourceReaderDecodesTheSoftwareH264Output, which runs on every Windows with Media
Foundation. MediaPlayerOpensTheHardwareHevcMain10Output also opens the hardware
HEVC Main10 output where a hardware encoder and an HEVC decoder exist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 10:34:33 +00:00
1 parent 2c643fba96
commit 9ad57b5e0b
2 files changed
+150 -49

No files matched your search

@@ -1,7 +1,9 @@
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling;
using System.Windows.Media;
using System.Windows.Threading;
using Titano.Core.Video;
using Titano.Core.Windows.Interop;
using Titano.Core.Windows.MediaFoundation;
@@ -9,8 +11,8 @@ 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.
/// Player's pipeline, and a Media Foundation source reader that decodes the first frame, which also works where Windows
/// Media Player is not installed (Windows Server, "N" editions).
/// </summary>
internal static partial class Mp4Playback
{
@@ -34,10 +36,33 @@ internal static partial class Mp4Playback
}
}
/// <summary>
/// True when Media Foundation has a decoder for <paramref name="codec"/>: always for H.264, only with the HEVC Video
/// Extensions for HEVC, which MediaPlayer needs as much as the source reader does.
/// </summary>
public static unsafe bool HasDecoder(VideoCodec codec)
{
using var runtime = MediaFoundationRuntime.Acquire();
var input = new MftRegisterTypeInfo { MajorType = MfGuids.MediaTypeVideo, Subtype = MediaFoundationEncoders.Subtype(codec) };
const uint flags = MfNative.EnumHardware | MfNative.EnumAsync | MfNative.EnumSync | MfNative.EnumSortAndFilter;
if (MfNative.MFTEnumEx(VideoDecoderCategory, flags, &input, null, out var array, out var count) < 0) return false;
try
{
for (var i = 0; i < count; i++) Marshal.Release(Marshal.ReadIntPtr(array, i * IntPtr.Size));
}
finally
{
Marshal.FreeCoTaskMem(array);
}
return count > 0;
}
/// <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"/>.
/// reports at <see cref="MediaPlayer.MediaOpened"/>. Throws, on the calling thread, when it raises
/// <see cref="MediaPlayer.MediaFailed"/>, when neither event comes within <paramref name="timeout"/>, and with WPF's
/// own exception when the player cannot be made or opened at all (a <see cref="NotSupportedException"/> where Windows
/// Media Player 10 or later is not usable): nothing escapes the dispatcher thread, where it would end the test program.
/// </summary>
public static Opened OpenWithMediaPlayer(string path, TimeSpan timeout)
{
@@ -46,33 +71,55 @@ internal static partial class Mp4Playback
var thread = new Thread(() =>
{
var dispatcher = Dispatcher.CurrentDispatcher;
var player = new MediaPlayer();
MediaPlayer? player = null;
DispatcherTimer? deadline = null;
void Finish()
var finished = false;
// The first outcome counts; the player is closed and the dispatcher stopped once.
void Finish(Opened? result, Exception? error)
{
if (finished) return;
finished = true;
(opened, failure) = (result, error);
deadline?.Stop();
player.Close();
try
{
player?.Close();
}
catch (Exception ex)
{
failure ??= ex;
}
dispatcher.InvokeShutdown();
}
player.MediaOpened += (_, _) =>
try
{
opened = new Opened(player.NaturalVideoWidth, player.NaturalVideoHeight,
player.NaturalDuration.HasTimeSpan ? player.NaturalDuration.TimeSpan : TimeSpan.Zero);
Finish();
};
player.MediaFailed += (_, e) =>
player = new MediaPlayer();
player.MediaOpened += (_, _) =>
{
// A handler that threw would leave Dispatcher.Run with the player still open.
try
{
Finish(new Opened(player.NaturalVideoWidth, player.NaturalVideoHeight,
player.NaturalDuration.HasTimeSpan ? player.NaturalDuration.TimeSpan : TimeSpan.Zero), null);
}
catch (Exception ex)
{
Finish(null, ex);
}
};
player.MediaFailed += (_, e) =>
Finish(null, new InvalidDataException($"MediaPlayer could not open '{path}': {e.ErrorException?.Message}", e.ErrorException));
// This constructor starts the timer.
deadline = new DispatcherTimer(timeout, DispatcherPriority.Normal, (_, _) =>
Finish(null, new TimeoutException($"MediaPlayer neither opened nor failed on '{path}' within {timeout.TotalSeconds:0} s")), dispatcher);
player.Open(new Uri(path, UriKind.Absolute));
Dispatcher.Run();
}
catch (Exception ex)
{
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();
if (finished) failure ??= ex;
else Finish(null, ex);
}
})
{
IsBackground = true,
@@ -81,7 +128,9 @@ internal static partial class Mp4Playback
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
return opened ?? throw failure ?? new InvalidOperationException("MediaPlayer stopped without a result");
// Rethrown with the dispatcher thread's stack trace and its own type: a NotSupportedException stays one.
if (failure is not null) ExceptionDispatchInfo.Throw(failure);
return opened ?? throw 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>
@@ -209,6 +258,9 @@ internal static partial class Mp4Playback
private const ushort VtUi8 = 21;
private const int PropVariantSize = 24; // PROPVARIANT on 64-bit Windows
/// <summary>MFT_CATEGORY_VIDEO_DECODER.</summary>
private static readonly Guid VideoDecoderCategory = new("d6c02d4b-6833-45b4-971a-05a4b04bab91");
/// <summary>MF_PD_DURATION: the presentation's length in 100 ns units.</summary>
private static readonly Guid PresentationDuration = new("6c990d33-bb8e-477a-8598-0d5d96fcd88a");