using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using Titano.Core.Codecs.Jpeg; using Titano.Core.Diagnostics; using Titano.Core.Imaging; using Titano.Core.Video; using Titano.Core.Video.Avi; using Titano.Core.Windows.Dxgi; using Titano.Core.Windows.MediaFoundation; namespace Titano.App.Settings; /// Outcome of encoding the synthetic test clip with one encoder. public sealed record SelfTestResult(bool Passed, double FramesPerSecond, string? Error); /// Encoders on this PC and their self-test (BRIEF §11.3, §12.8). public interface IEncoderInventory { /// "NVIDIA GeForce RTX 4070"; null when no hardware adapter is found. string? Adapter(); /// Enumerates the encoders (slow: call off the UI thread). IReadOnlyList Detect(); /// Encodes synthetic frames and reports speed. Task SelfTestAsync(EncoderRow row, CancellationToken ct); } /// Media Foundation encoders (in MFTEnumEx merit order) plus Titano's built-in managed encoders. public sealed class MediaFoundationInventory : IEncoderInventory { public const int TestFrames = 48; public const int TestWidth = 1280; public const int TestHeight = 720; public string? Adapter() { try { return GpuAdapters.Enumerate().Where(a => !a.IsSoftware).OrderByDescending(a => a.DedicatedVideoMemory).FirstOrDefault()?.Description; } catch (Exception ex) when (ex is COMException or DllNotFoundException or EntryPointNotFoundException) { Log.Warning("encoders", "Graphics adapters could not be listed", ex); return null; } } public IReadOnlyList Detect() { var rows = new List(); foreach (var c in new MediaFoundationEncoderProvider().Capabilities) { rows.Add(new EncoderRow(CodecName(c.Codec), c.Name, c.Vendor, EncoderSource.MediaFoundation, c.Hardware, c.SupportsTenBit, c.MaxWidth, c.MaxHeight, c.Codec)); } rows.Add(new EncoderRow("MJPEG · AVI", "Titano", null, EncoderSource.BuiltInMjpeg, false, false, 0, 0, VideoCodec.Mjpeg)); rows.Add(new EncoderRow("GIF · APNG", "Titano", null, EncoderSource.BuiltInAnimation, false, false, 0, 0, null)); return rows; } public Task SelfTestAsync(EncoderRow row, CancellationToken ct) => Task.Run(() => SelfTest(row, ct), ct); public static string CodecName(VideoCodec codec) => codec switch { VideoCodec.H264 => "H.264", VideoCodec.Hevc => "HEVC", VideoCodec.Av1 => "AV1", _ => codec.ToString(), }; private static SelfTestResult SelfTest(EncoderRow row, CancellationToken ct) { using var frame = TestPattern(TestWidth, TestHeight); var clock = Stopwatch.StartNew(); try { switch (row.Source) { case EncoderSource.MediaFoundation: EncodeMediaFoundation(row, frame, ct); break; case EncoderSource.BuiltInMjpeg: EncodeMjpeg(frame, ct); break; default: return new SelfTestResult(false, 0, null); } clock.Stop(); var fps = TestFrames / Math.Max(clock.Elapsed.TotalSeconds, 1e-3); Log.Info("encoders", $"Self-test {row.Codec} \"{row.Name}\": {fps:0.#} fps"); return new SelfTestResult(true, fps, null); } catch (OperationCanceledException) { throw; } catch (Exception ex) when (ex is COMException or NotSupportedException or IOException or InvalidOperationException or PlatformNotSupportedException or InvalidDataException) { Log.Warning("encoders", $"Self-test {row.Codec} \"{row.Name}\" failed", ex); return new SelfTestResult(false, 0, ex.Message); } } private static void EncodeMediaFoundation(EncoderRow row, ImageBuffer frame, CancellationToken ct) { var path = Path.Combine(Path.GetTempPath(), "titano-selftest-" + Guid.NewGuid().ToString("N") + ".mp4"); try { var fps = new Rational(30, 1); var settings = new EncodeSettings { OutputPath = path, Codec = row.VideoCodec ?? throw new NotSupportedException("No codec"), Width = TestWidth, Height = TestHeight, FrameRate = fps, BitRate = 8_000_000, PreferHardware = row.Hardware, EncoderName = row.Name, }; using (var session = new MediaFoundationEncoderProvider().Open(settings)) { for (var i = 0; i < TestFrames; i++) { ct.ThrowIfCancellationRequested(); session.WriteFrame(frame, fps.FrameTicks90k); } session.Complete(); } if (!File.Exists(path) || new FileInfo(path).Length == 0) throw new InvalidDataException("The encoder wrote no data."); } finally { try { File.Delete(path); } catch (IOException) { } } } private static void EncodeMjpeg(ImageBuffer frame, CancellationToken ct) { using var output = new MemoryStream(); var writer = new AviMjpegWriter(output, TestWidth, TestHeight, new Rational(30, 1)); var options = new JpegEncodeOptions { Quality = 90 }; for (var i = 0; i < TestFrames; i++) { ct.ThrowIfCancellationRequested(); writer.WriteFrame(JpegEncoder.Encode(frame, options)); } writer.Complete(); if (output.Length == 0) throw new InvalidDataException("The encoder wrote no data."); } /// A smooth colour gradient: compressible, but not trivially so. internal static ImageBuffer TestPattern(int width, int height) { var image = new ImageBuffer(width, height, 3, clear: false); for (var c = 0; c < 3; c++) { var plane = image.Plane(c); for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var u = x / (float)width; var v = y / (float)height; plane[y * width + x] = c switch { 0 => u * 0.8f, 1 => v * 0.6f, _ => (1 - u) * (1 - v) * 0.7f, }; } } } return image; } }