dragon-iso/src/TeamsISO.Console/Program.cs
Zac Gaetano fa8d2a8fad
Some checks failed
CI / build-and-test (push) Failing after 27s
feat(console): add --list-sources diagnostic flag
Enumerates every raw NDI source string visible to the local NDI finder for ~5 seconds and prints unique ones, then exits. Bypasses NdiSourceParser so it surfaces sources that the parser would otherwise reject — useful for confirming the on-the-wire format Teams (or any other producer) is actually emitting on a given setup.

Used directly to diagnose the Teams 'MS Teams' vs. 'Teams' brand-prefix mismatch fixed in the previous commit; left in as a permanent debug tool for future setup issues.
2026-05-07 23:33:44 -04:00

169 lines
6.7 KiB
C#

using System.Reactive.Linq;
using System.Runtime.Versioning;
using Microsoft.Extensions.Logging;
using TeamsISO.Engine.Controller;
using TeamsISO.Engine.Domain;
using TeamsISO.Engine.Interop;
using TeamsISO.Engine.Logging;
using TeamsISO.Engine.NdiInterop;
using TeamsISO.Engine.Persistence;
using TeamsISO.Engine.Pipeline;
namespace TeamsISO.Console;
using SysConsole = System.Console;
/// <summary>
/// Headless smoke runner. Wires up the engine end-to-end against the production NDI P/Invoke
/// interop and prints participant updates, alerts, and ISO state. Useful for first-validation
/// against a real Teams meeting before the WPF UI is alive.
///
/// Requires Windows + the NDI Runtime installed.
///
/// Usage:
/// teamsiso-console # discover only — print participants as they appear/leave
/// teamsiso-console --enable-all # auto-enable an ISO for every discovered participant
/// teamsiso-console --list-sources # diagnostic: print every raw NDI source string visible
/// on the network for ~5s, then exit. Useful for debugging
/// why expected Teams sources aren't being classified.
/// </summary>
public static class Program
{
public static async Task<int> Main(string[] args)
{
var enableAll = args.Contains("--enable-all", StringComparer.OrdinalIgnoreCase);
var listSources = args.Contains("--list-sources", StringComparer.OrdinalIgnoreCase);
using var loggerFactory = EngineLogging.CreateConsole(LogLevel.Information);
var logger = loggerFactory.CreateLogger("TeamsISO.Console");
if (!OperatingSystem.IsWindows())
{
logger.LogError("TeamsISO.Console requires Windows + the NDI Runtime. Current OS is not Windows.");
return 1;
}
NdiInteropPInvoke interop;
try
{
interop = new NdiInteropPInvoke(loggerFactory.CreateLogger<NdiInteropPInvoke>());
}
catch (Exception ex)
{
logger.LogError(ex, "Could not initialize NDI runtime. Install the NDI Runtime from https://ndi.video/tools/ and try again.");
return 2;
}
if (listSources)
{
return await RunListSourcesAsync(interop, logger);
}
var configPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"TeamsISO", "config.json");
var configStore = new ConfigStore(configPath, loggerFactory.CreateLogger<ConfigStore>());
var probe = new NdiRuntimeProbe(interop, NdiVersion.ExpectedRuntimeVersionPrefix);
var scaler = new ManagedNearestNeighborFrameScaler();
// Pipeline factory: wires up real NDI receiver/processor/sender against the production interop.
IsoPipeline PipelineFactory(IsoPipelineConfig config)
{
var clock = new PeriodicTimerFrameClock(config.Settings.FramerateHz);
return new IsoPipeline(
config, interop, scaler, clock,
ExponentialBackoff.Default,
(delay, ct) => Task.Delay(delay, ct),
loggerFactory);
}
await using var controller = new IsoController(
interop, PipelineFactory, configStore, probe, loggerFactory);
// Wire up event printing
var sub1 = controller.Participants
.DistinctUntilChanged()
.Subscribe(plist =>
{
logger.LogInformation("Participants ({Count}):", plist.Count);
foreach (var p in plist)
logger.LogInformation(" - {Name} source={Source}", p.DisplayName, p.CurrentSource?.FullName ?? "<none>");
});
var sub2 = controller.Alerts.Subscribe(a => logger.LogWarning("ALERT: {Message}", a.Message));
using var cts = new CancellationTokenSource();
SysConsole.CancelKeyPress += (_, e) => { e.Cancel = true; cts.Cancel(); };
await controller.StartAsync(cts.Token);
logger.LogInformation("Engine started. Default framerate: {Fps:F2} fps. Press Ctrl+C or 'q' Enter to quit.",
controller.GlobalSettings.FramerateHz);
if (enableAll)
{
// Auto-enable any participant we see, until cancellation.
controller.Participants.Subscribe(async plist =>
{
foreach (var p in plist.Where(p => p.CurrentSource is not null))
{
try { await controller.EnableIsoAsync(p.Id, customName: null, cts.Token); }
catch (Exception ex) { logger.LogWarning(ex, "Could not enable ISO for {Name}.", p.DisplayName); }
}
});
}
// Read until 'q' or cancellation.
var input = Task.Run(() =>
{
while (!cts.IsCancellationRequested)
{
var line = SysConsole.ReadLine();
if (line is null) return;
if (line.Trim().Equals("q", StringComparison.OrdinalIgnoreCase))
{
cts.Cancel();
return;
}
}
});
try { await Task.Delay(Timeout.Infinite, cts.Token); }
catch (OperationCanceledException) { /* expected on quit */ }
sub1.Dispose();
sub2.Dispose();
interop.Dispose();
logger.LogInformation("Engine stopped.");
return 0;
}
/// <summary>
/// Diagnostic mode: enumerates every raw NDI source string visible to the local
/// NDI finder for ~5 seconds, prints each unique one, then exits. Bypasses the
/// <see cref="Discovery.NdiSourceParser"/> entirely, so it surfaces sources that
/// the parser would otherwise reject — useful for confirming the on-the-wire
/// format Teams (or any other producer) is actually emitting.
/// </summary>
[SupportedOSPlatform("windows")]
private static async Task<int> RunListSourcesAsync(NdiInteropPInvoke interop, ILogger logger)
{
const int pollMs = 500;
const int totalMs = 5000;
logger.LogInformation("Listing raw NDI sources for {TotalMs} ms (polling every {PollMs} ms)…", totalMs, pollMs);
using var finder = interop.CreateFinder();
var seen = new SortedSet<string>(StringComparer.Ordinal);
var elapsed = 0;
while (elapsed < totalMs)
{
await Task.Delay(pollMs);
elapsed += pollMs;
foreach (var s in interop.GetCurrentSources(finder))
{
if (seen.Add(s))
logger.LogInformation(" + {Source}", s);
}
}
logger.LogInformation("Done. {Count} unique source(s) seen in {TotalMs} ms.", seen.Count, totalMs);
interop.Dispose();
return 0;
}
}