using System.Diagnostics; using System.Threading.Channels; using Microsoft.Extensions.Logging; using Microsoft.ML.OnnxRuntime; using Microsoft.ML.OnnxRuntime.Tensors; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; namespace Heimdall.Agent.Services; /// Single detection result from a frame. public sealed record DetectionResult( string Label, float Confidence, float X, float Y, float Width, float Height, int? ClassIndex = null); /// Result of analyzing a single frame. public sealed record FrameAnalysisResult( string ImageBase64, IReadOnlyList Detections, long ProcessingMs); /// /// Analyzes video frames using YOLO ONNX models for object detection. /// Runs inference in a background thread pool, supports concurrent /// frame processing with a bounded queue. /// /// Model file expected at: models/yolov8m.onnx (relative to app root) /// or configured via MODEL_PATH environment variable. /// /// If no model file is found, runs in "passthrough" mode — returns /// empty detections without crashing. /// public sealed class FrameAnalyzerService : IDisposable { private readonly ILogger _logger; private readonly string _modelPath; private readonly bool _modelLoaded; private readonly InferenceSession? _session; private readonly string _inputName = ""; private readonly int _numClasses; // Bounded queue of pending frames to analyze private readonly Channel _frameQueue; private readonly CancellationTokenSource _cts = new(); private readonly Task _processingLoop; // YOLO class names (COCO dataset) private static readonly string[] CocoClasses = [ "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush" ]; private const int MaxQueueSize = 16; private const int InputSize = 640; // YOLOv8 input size private const float ConfidenceThreshold = 0.25f; private const float NmsIouThreshold = 0.45f; private long _analyzedFrameCount; /// Number of frames actually handed to the analyzer (real calls, including passthrough). public long AnalyzedFrameCount => Interlocked.Read(ref _analyzedFrameCount); public FrameAnalyzerService(ILogger logger) { _logger = logger; _modelPath = Environment.GetEnvironmentVariable("MODEL_PATH") ?? "models/yolov8m.onnx"; _modelLoaded = File.Exists(_modelPath); if (_modelLoaded) { try { var sessionOptions = new Microsoft.ML.OnnxRuntime.SessionOptions { InterOpNumThreads = 1, IntraOpNumThreads = Environment.ProcessorCount, GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL, }; _session = new InferenceSession(_modelPath, sessionOptions); _inputName = _session.InputMetadata.Keys.ToArray()[0]; // Determine number of classes from output shape [1, 4+C, 8400] var outputMeta = _session.OutputMetadata.Values.ToArray()[0]; _numClasses = outputMeta.Dimensions.Length >= 2 ? (int)outputMeta.Dimensions[1] - 4 : 80; _logger.LogInformation( "FrameAnalyzer initialized with model: {ModelPath} (input: {InputName}, classes: {Classes})", _modelPath, _inputName, _numClasses); } catch (Exception ex) { _logger.LogError(ex, "Failed to load ONNX model from {ModelPath} — falling back to passthrough", _modelPath); _session?.Dispose(); _session = null; _modelLoaded = false; } } else { _logger.LogWarning("FrameAnalyzer in passthrough mode — model not found at {ModelPath}", _modelPath); } _frameQueue = Channel.CreateBounded(new BoundedChannelOptions(MaxQueueSize) { // DropWrite rejects new writes when full with TryWrite=false, // allowing the caller to gracefully complete the TCS with null. // DropOldest would orphan the oldest job's TaskCompletionSource. FullMode = BoundedChannelFullMode.DropWrite, SingleReader = true, SingleWriter = false }); _processingLoop = Task.Run(() => ProcessingLoopAsync(_cts.Token)); } /// /// Submit a JPEG frame for analysis. Returns a task that completes when /// analysis is done. If the queue is full, drops the oldest frame. /// Returns empty detections if model not loaded (passthrough mode). /// public async Task AnalyzeFrameAsync(byte[] jpegData, CancellationToken ct = default) { Interlocked.Increment(ref _analyzedFrameCount); if (!_modelLoaded) return null; var tcs = new TaskCompletionSource(); var job = new FrameJob(jpegData, tcs); // If queue is full (DropWrite rejected our write), complete TCS with fallback if (!_frameQueue.Writer.TryWrite(job)) { tcs.TrySetResult(null); return null; } return await tcs.Task.WaitAsync(ct); } /// /// Synchronous frame analysis (for fire-and-forget pipelines that /// don't need the result immediately). Returns null in passthrough. /// public FrameAnalysisResult? AnalyzeFrame(byte[] jpegData) { Interlocked.Increment(ref _analyzedFrameCount); if (!_modelLoaded) return null; var sw = Stopwatch.StartNew(); var detections = RunInference(jpegData); sw.Stop(); return new FrameAnalysisResult( Convert.ToBase64String(jpegData), detections, sw.ElapsedMilliseconds); } private async Task ProcessingLoopAsync(CancellationToken ct) { await foreach (var job in _frameQueue.Reader.ReadAllAsync(ct)) { try { var sw = Stopwatch.StartNew(); var detections = RunInference(job.ImageData); sw.Stop(); var result = new FrameAnalysisResult( Convert.ToBase64String(job.ImageData), detections, sw.ElapsedMilliseconds); job.Tcs.TrySetResult(result); } catch (Exception ex) { _logger.LogWarning(ex, "Frame analysis failed"); job.Tcs.TrySetResult(null); } } } /// /// Run YOLOv8 ONNX inference on a JPEG frame. /// Pipeline: JPEG decode → resize 640×640 → normalize → ONNX inference → NMS. /// internal DetectionResult[] RunInference(byte[] jpegData) { if (_session is null) return []; using var image = Image.Load(jpegData); // Resize to model input size (640×640) image.Mutate(x => x.Resize(InputSize, InputSize)); var inputTensor = PreprocessImage(image); var inputs = new List { NamedOnnxValue.CreateFromTensor(_inputName, inputTensor) }; using var results = _session.Run(inputs); var output = results[0].AsTensor().ToArray(); return ParseYoloOutput(output, image.Width, image.Height); } /// /// Convert ImageSharp image to a normalized NCHW tensor [1, 3, 640, 640]. /// YOLOv8 expects RGB channels, each normalized to [0, 1]. /// private static DenseTensor PreprocessImage(Image image) { var tensor = new DenseTensor([1, 3, InputSize, InputSize]); var width = image.Width; image.ProcessPixelRows(accessor => { for (var y = 0; y < accessor.Height; y++) { var pixelRow = accessor.GetRowSpan(y); for (var x = 0; x < pixelRow.Length; x++) { var pixel = pixelRow[x]; tensor[0, 0, y, x] = pixel.R / 255f; tensor[0, 1, y, x] = pixel.G / 255f; tensor[0, 2, y, x] = pixel.B / 255f; } } }); return tensor; } /// /// Parse YOLOv8 raw output tensor [1, 4+C, 8400] into DetectionResult list. /// First 4 values per column are (cx, cy, w, h) in pixel space (scaled to input size). /// Remaining C values are class confidence scores. /// Applies confidence thresholding and Non-Maximum Suppression. /// internal DetectionResult[] ParseYoloOutput(float[] output, int imageWidth, int imageHeight) { // YOLOv8 output shape: [1, 4+numClasses, numAnchors] → flatten to [4+numClasses, numAnchors] var numFeatures = 4 + _numClasses; var numAnchors = output.Length / numFeatures; // Scale factors from model input size to original image size var scaleX = (float)imageWidth / InputSize; var scaleY = (float)imageHeight / InputSize; var candidates = new List(); for (var i = 0; i < numAnchors; i++) { // Find best class score var maxScore = 0f; var maxClassIdx = 0; for (var c = 0; c < _numClasses; c++) { var score = output[(4 + c) * numAnchors + i]; if (score > maxScore) { maxScore = score; maxClassIdx = c; } } if (maxScore < ConfidenceThreshold) continue; // Decode bounding box: (cx, cy, w, h) → scale to original image var cx = output[0 * numAnchors + i] * scaleX; var cy = output[1 * numAnchors + i] * scaleY; var w = output[2 * numAnchors + i] * scaleX; var h = output[3 * numAnchors + i] * scaleY; // Convert to (x1, y1, x2, y2) for NMS var x1 = cx - w / 2; var y1 = cy - h / 2; var x2 = cx + w / 2; var y2 = cy + h / 2; candidates.Add(new RawDetection(x1, y1, x2, y2, maxScore, maxClassIdx)); } return ApplyNms(candidates); } /// /// Non-Maximum Suppression: suppress overlapping boxes of the same class. /// Returns the surviving detections as DetectionResult records. /// internal static DetectionResult[] ApplyNms(List candidates) { // Sort by confidence descending candidates.Sort((a, b) => b.Score.CompareTo(a.Score)); var results = new List(); var suppressed = new bool[candidates.Count]; for (var i = 0; i < candidates.Count; i++) { if (suppressed[i]) continue; var best = candidates[i]; results.Add(new DetectionResult( Label: best.ClassIdx < CocoClasses.Length ? CocoClasses[best.ClassIdx] : $"class_{best.ClassIdx}", Confidence: best.Score, X: best.X1, Y: best.Y1, Width: best.X2 - best.X1, Height: best.Y2 - best.Y1, ClassIndex: best.ClassIdx)); // Suppress overlapping boxes of the same class for (var j = i + 1; j < candidates.Count; j++) { if (suppressed[j]) continue; if (candidates[j].ClassIdx != best.ClassIdx) continue; var iou = ComputeIoU(best, candidates[j]); if (iou >= NmsIouThreshold) suppressed[j] = true; } } return results.ToArray(); } private static float ComputeIoU(RawDetection a, RawDetection b) { var interX1 = Math.Max(a.X1, b.X1); var interY1 = Math.Max(a.Y1, b.Y1); var interX2 = Math.Min(a.X2, b.X2); var interY2 = Math.Min(a.Y2, b.Y2); var interArea = Math.Max(0, interX2 - interX1) * Math.Max(0, interY2 - interY1); var areaA = (a.X2 - a.X1) * (a.Y2 - a.Y1); var areaB = (b.X2 - b.X1) * (b.Y2 - b.Y1); var unionArea = areaA + areaB - interArea; return unionArea > 0 ? interArea / unionArea : 0; } internal readonly record struct RawDetection( float X1, float Y1, float X2, float Y2, float Score, int ClassIdx); private bool _disposed; public void Dispose() { if (_disposed) return; _disposed = true; _cts.Cancel(); _cts.Dispose(); _frameQueue.Writer.TryComplete(); _session?.Dispose(); // Log unobserved exceptions from the processing loop _processingLoop.ContinueWith(t => { if (t.IsFaulted) _logger.LogCritical(t.Exception, "FrameAnalyzer processing loop crashed"); }, TaskContinuationOptions.OnlyOnFaulted); } private sealed record FrameJob(byte[] ImageData, TaskCompletionSource Tcs); }