Files
Chronos/src/Titano.App/Settings/EncoderInventory.cs
T
Claude d80cb5f8a7 fix(app): Server, Jobs, Settings, About and Welcome after the accessibility and RTL review
- Keyboard: Tab follows the visual order (toolbars, section list, dialog
  buttons), reaches every Jobs row button, stays inside the Welcome dialog
  (which opens focused); the Settings section list shows a focus ring.
- Screen readers: sync and job rows read as their sequence or job with the
  state as item status; row buttons name their row; filter chips are radio
  buttons; the connection state, errors, sync retries, update checks and
  self-test results are announced; Auto values are text, not dead buttons.
- Right to left: paths, addresses, templates, fingerprints, the job log, sizes
  and the logo stay left to right; numbers stay right-aligned.
- Layout: Jobs and sync headers line up with their rows (shared padding,
  shared actions column, constant scroll-bar gutter); toolbars wrap before
  anything is cut; Settings labels share a column as wide as the longest one;
  path rows give way instead of wrapping; conflict rows use the warning tint.
- Behaviour: Settings reloads the archive folder and default server set
  elsewhere; forgetting a certificate in Settings asks first and disconnects
  the session on it; transfers count in the Local only and Remote chips; the
  Workers readout counts this PC's workers; badge, status strip and Running
  chip agree; the admin link shows for administrators only; Reset section is
  gone from Advanced; empty states carry one action; shorter labels; the
  encoders a render node offers and the presets each encoder serves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-03 17:23:59 +00:00

184 lines
6.8 KiB
C#

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;
/// <summary>Outcome of encoding the synthetic test clip with one encoder.</summary>
public sealed record SelfTestResult(bool Passed, double FramesPerSecond, string? Error);
/// <summary>Encoders on this PC and their self-test (BRIEF §11.3, §12.8).</summary>
public interface IEncoderInventory
{
/// <summary>"NVIDIA GeForce RTX 4070"; null when no hardware adapter is found.</summary>
string? Adapter();
/// <summary>Enumerates the encoders (slow: call off the UI thread).</summary>
IReadOnlyList<EncoderRow> Detect();
/// <summary>Encodes <see cref="MediaFoundationInventory.TestFrames"/> synthetic frames and reports speed.</summary>
Task<SelfTestResult> SelfTestAsync(EncoderRow row, CancellationToken ct);
}
/// <summary>Media Foundation encoders (in MFTEnumEx merit order) plus Titano's built-in managed encoders.</summary>
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<EncoderRow> Detect()
{
var rows = new List<EncoderRow>();
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<SelfTestResult> 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.");
}
/// <summary>A smooth colour gradient: compressible, but not trivially so.</summary>
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;
}
}