From 9ad57b5e0bb0901c6aa03522776b8f138b15bd65 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 10:34:33 +0000 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../MediaFoundationEncoderTests.cs | 97 ++++++++++++----- .../MediaFoundation/Mp4Playback.cs | 102 +++++++++++++----- 2 files changed, 150 insertions(+), 49 deletions(-) diff --git a/tests/Titano.Core.Windows.Tests/MediaFoundation/MediaFoundationEncoderTests.cs b/tests/Titano.Core.Windows.Tests/MediaFoundation/MediaFoundationEncoderTests.cs index c5c34741..41715bb8 100644 --- a/tests/Titano.Core.Windows.Tests/MediaFoundation/MediaFoundationEncoderTests.cs +++ b/tests/Titano.Core.Windows.Tests/MediaFoundation/MediaFoundationEncoderTests.cs @@ -67,37 +67,34 @@ public sealed class MediaFoundationEncoderTests(TestContext context) /// /// 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). + /// the encoded size and length. Where Windows Media Player is missing or unusable (Windows Server, "N" editions) the + /// test is skipped with that reason, and is the check. /// [Test] [WindowsOnly] [Timeout(120_000)] - public void SoftwareH264OutputPlaysBack() + public void MediaPlayerOpensTheSoftwareH264Output() { 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(); - } + RequireMediaPlayer(); + var opened = OpenWithMediaPlayer(Encoded("playback.mp4", VideoCodec.H264, 8, hardware: false)); + context.Log($"MediaPlayer: {opened}"); + Assert.Equal(1280, opened.Width); + Assert.Equal(720, opened.Height); + Assert.Approximately(2.0, opened.Duration.TotalSeconds, 0.05); + } - 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); + /// + /// BRIEF §20.2: a Media Foundation source reader decodes the encoder's first frame to the picture that was encoded. + /// It needs no Windows Media Player, so it runs on every Windows with Media Foundation, Server editions included. + /// + [Test] + [WindowsOnly] + [Timeout(60_000)] + public void SourceReaderDecodesTheSoftwareH264Output() + { + RequireEncoder(VideoCodec.H264, hardware: false, tenBit: false); + var frame = Mp4Playback.DecodeFirstFrame(Encoded("decode.mp4", VideoCodec.H264, 8, hardware: false)); 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); @@ -107,6 +104,22 @@ public sealed class MediaFoundationEncoderTests(TestContext context) Assert.Less(frame.LumaAt(4, 4), 60); } + /// The hardware HEVC Main10 output opens in MediaPlayer at its size and length, where Windows can decode HEVC. + [Test] + [WindowsOnly] + [Timeout(120_000)] + public void MediaPlayerOpensTheHardwareHevcMain10Output() + { + RequireEncoder(VideoCodec.Hevc, hardware: true, tenBit: true); + RequireMediaPlayer(); + if (!Mp4Playback.HasDecoder(VideoCodec.Hevc)) TestContext.Skip("No HEVC decoder on this machine (HEVC Video Extensions)"); + var opened = OpenWithMediaPlayer(Encoded("main10.mp4", VideoCodec.Hevc, 10, hardware: true)); + context.Log($"MediaPlayer: {opened}"); + Assert.Equal(1280, opened.Width); + Assert.Equal(720, opened.Height); + Assert.Approximately(2.0, opened.Duration.TotalSeconds, 0.05); + } + [Test] [WindowsOnly] [Timeout(60_000)] @@ -181,6 +194,42 @@ public sealed class MediaFoundationEncoderTests(TestContext context) } } + /// Two seconds of (60 frames at 30 fps, 1280×720) in a new temporary file. + private string Encoded(string name, VideoCodec codec, int bitDepth, bool hardware) + { + var settings = Settings(Path.Combine(context.CreateTempDirectory(), name), codec, bitDepth) with { PreferHardware = hardware }; + using (var session = new MediaFoundationEncoderProvider().Open(settings)) + { + Assert.Equal(hardware, session.IsHardware); + context.Log("encoder: " + session.EncoderName); + WriteFrames(session, 60, bitDepth); + session.Complete(); + } + return settings.OutputPath; + } + + /// + /// , skipped when WPF finds Windows Media Player present but unusable + /// (its , "version 10 or later is required"). + /// + private static Mp4Playback.Opened OpenWithMediaPlayer(string path) + { + try + { + return Mp4Playback.OpenWithMediaPlayer(path, TimeSpan.FromSeconds(60)); + } + catch (NotSupportedException ex) + { + TestContext.Skip("Windows Media Player cannot be used: " + ex.Message); + throw; + } + } + + private static void RequireMediaPlayer() + { + if (!Mp4Playback.HasMediaPlayer) TestContext.Skip("Windows Media Player is not installed (Windows Server, \"N\" editions); the source reader test checks playback"); + } + private static void RequireMediaFoundation() { if (!MediaFoundationRuntime.IsAvailable) TestContext.Skip("Media Foundation is not installed (Windows N or Server without Media Foundation)"); diff --git a/tests/Titano.Core.Windows.Tests/MediaFoundation/Mp4Playback.cs b/tests/Titano.Core.Windows.Tests/MediaFoundation/Mp4Playback.cs index 6d4251d5..887ffe96 100644 --- a/tests/Titano.Core.Windows.Tests/MediaFoundation/Mp4Playback.cs +++ b/tests/Titano.Core.Windows.Tests/MediaFoundation/Mp4Playback.cs @@ -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; /// /// How Windows plays a written MP4 back (BRIEF §20.2): WPF's , 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). /// internal static partial class Mp4Playback { @@ -34,10 +36,33 @@ internal static partial class Mp4Playback } } + /// + /// True when Media Foundation has a decoder for : always for H.264, only with the HEVC Video + /// Extensions for HEVC, which MediaPlayer needs as much as the source reader does. + /// + 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; + } + /// /// Opens with on its own dispatcher thread and returns what it - /// reports at . Throws when it raises or - /// neither event comes within . + /// reports at . Throws, on the calling thread, when it raises + /// , when neither event comes within , and with WPF's + /// own exception when the player cannot be made or opened at all (a where Windows + /// Media Player 10 or later is not usable): nothing escapes the dispatcher thread, where it would end the test program. /// 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"); } /// Decodes the first video frame of to NV12 with a Media Foundation source reader. @@ -209,6 +258,9 @@ internal static partial class Mp4Playback private const ushort VtUi8 = 21; private const int PropVariantSize = 24; // PROPVARIANT on 64-bit Windows + /// MFT_CATEGORY_VIDEO_DECODER. + private static readonly Guid VideoDecoderCategory = new("d6c02d4b-6833-45b4-971a-05a4b04bab91"); + /// MF_PD_DURATION: the presentation's length in 100 ns units. private static readonly Guid PresentationDuration = new("6c990d33-bb8e-477a-8598-0d5d96fcd88a");