Files
Heimdall/src/Heimdall.Agent/Services/FrameAnalyzerService.cs
T
Arnaud Dartois 83d11c25eb
Heimdall Gitea / Build and tests (pull_request) Successful in 30m53s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
fix(metrics): emit inference duration measurements
2026-10-21 10:18:30 +02:00

494 lines
20 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Diagnostics;
using System.Threading.Channels;
using Heimdall.Application.Metrics;
using Microsoft.Extensions.Logging;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using ImageMagick;
namespace Heimdall.Agent.Services;
/// <summary>Single detection result from a frame.</summary>
public sealed record DetectionResult(
string Label,
float Confidence,
float X, float Y, float Width, float Height,
int? ClassIndex = null);
/// <summary>Result of analyzing a single frame.</summary>
public sealed record FrameAnalysisResult(
string ImageBase64,
IReadOnlyList<DetectionResult> Detections,
long ProcessingMs);
/// <summary>
/// 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/yolov8n.onnx (relative to app root)
/// or configured via MODEL_PATH environment variable.
///
/// If no compatible model is found, analysis is unavailable (null), never a negative detection.
///
/// Integrates with <see cref="CircuitBreaker"/> and
/// <see cref="PipelineDegradationManager"/> for graceful degradation:
/// - Circuit open → inference skipped, returns null
/// - Degradation level 1 → inference runs with lowered confidence
/// - Degradation level 2+ → inference skipped entirely
/// </summary>
public sealed class FrameAnalyzerService : IDisposable
{
private readonly ILogger<FrameAnalyzerService> _logger;
private readonly Func<byte[], float, DetectionResult[]>? _testInference;
private readonly string _modelPath;
private readonly bool _modelLoaded;
private readonly InferenceSession? _session;
private readonly string _inputName = "";
private readonly int _numClasses = 80;
private readonly object _inferenceLock = new();
private long _rejectedFrames;
public long RejectedFrames => Interlocked.Read(ref _rejectedFrames);
public bool ModelAvailable => _modelLoaded;
public string ExecutionProvider => "CPUExecutionProvider";
private readonly CircuitBreaker? _circuitBreaker;
private readonly PipelineDegradationManager? _degradationManager;
// Bounded queue of pending frames to analyze
private readonly Channel<FrameJob> _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
/// <summary>Default minimum confidence per spec §16 — CameraDetectionProfile.MinConfidence.</summary>
internal const float DefaultMinConfidence = 0.4f;
private const float NmsIouThreshold = 0.45f;
private const long SlowInferenceThresholdMs = 500;
private long _analyzedFrameCount;
private long _skippedByCircuitBreaker;
private long _skippedByDegradation;
/// <summary>Number of frames actually handed to the analyzer (real calls, including passthrough).</summary>
public long AnalyzedFrameCount => Interlocked.Read(ref _analyzedFrameCount);
/// <summary>Number of frames skipped because the circuit breaker is open.</summary>
public long SkippedByCircuitBreaker => Interlocked.Read(ref _skippedByCircuitBreaker);
/// <summary>Number of frames skipped because of pipeline degradation.</summary>
public long SkippedByDegradation => Interlocked.Read(ref _skippedByDegradation);
public FrameAnalyzerService(ILogger<FrameAnalyzerService> logger)
: this(logger, null, null)
{
}
public FrameAnalyzerService(
ILogger<FrameAnalyzerService> logger,
CircuitBreaker? circuitBreaker,
PipelineDegradationManager? degradationManager) : this(logger, circuitBreaker, degradationManager, null) { }
internal FrameAnalyzerService(ILogger<FrameAnalyzerService> logger, CircuitBreaker? circuitBreaker,
PipelineDegradationManager? degradationManager, Func<byte[], float, DetectionResult[]>? inference, string? modelPath = null)
{
_testInference = inference;
_logger = logger;
_circuitBreaker = circuitBreaker;
_degradationManager = degradationManager;
_modelPath = modelPath ?? Environment.GetEnvironmentVariable("MODEL_PATH") ?? "models/yolov8n.onnx";
_modelLoaded = inference is not null || File.Exists(_modelPath);
if (_modelLoaded && inference is null)
{
try
{
using var sessionOptions = new Microsoft.ML.OnnxRuntime.SessionOptions
{
InterOpNumThreads = 1,
IntraOpNumThreads = 2, // spec §16: limit CPU threads for agent
GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,
};
_session = new InferenceSession(_modelPath, sessionOptions);
_inputName = _session.InputMetadata.Keys.Single();
var input = _session.InputMetadata[_inputName];
var output = _session.OutputMetadata.Values.Single();
if (input.ElementType != typeof(float) || !input.Dimensions.SequenceEqual(new[] { 1, 3, InputSize, InputSize }) ||
output.ElementType != typeof(float) || output.Dimensions.Length != 3 || output.Dimensions[0] != 1 ||
output.Dimensions[1] != 84 || output.Dimensions[2] <= 0)
throw new InvalidOperationException("Expected COCO YOLOv8 float NCHW [1,3,640,640] -> [1,84,N]");
// Determine number of classes from output shape [1, 4+C, 8400]
var outputMeta = _session.OutputMetadata.Values.ToArray()[0];
_numClasses = outputMeta.Dimensions.Length >= 2 ? 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 if (!_modelLoaded)
{
_logger.LogWarning("FrameAnalyzer unavailable — model not found at {ModelPath}", _modelPath);
}
_frameQueue = Channel.CreateBounded<FrameJob>(new BoundedChannelOptions(MaxQueueSize)
{
// Wait mode makes TryWrite return false on saturation; no accepted job is dropped.
FullMode = BoundedChannelFullMode.Wait,
SingleReader = true,
SingleWriter = false
});
_processingLoop = Task.Run(() => ProcessingLoopAsync(_cts.Token));
}
/// <summary>
/// Submit a JPEG frame for analysis. Returns a task that completes when
/// analysis is done. If the queue is full, explicitly rejects the new frame.
/// Returns null when inference is unavailable.
/// Respects circuit breaker and degradation level.
/// </summary>
/// <param name="jpegData">Raw JPEG frame bytes.</param>
/// <param name="minConfidence">
/// Minimum confidence threshold for detections. Defaults to 0.4 (spec §16).
/// Override with <see cref="CameraDetectionProfile.MinConfidence"/> per camera.
/// </param>
/// <param name="ct">Cancellation token.</param>
public async Task<FrameAnalysisResult?> AnalyzeFrameAsync(
byte[] jpegData,
float minConfidence = DefaultMinConfidence,
CancellationToken ct = default)
{
Interlocked.Increment(ref _analyzedFrameCount);
// Circuit breaker: skip if open
if (_circuitBreaker is not null && !_circuitBreaker.ShouldAllowCall())
{
Interlocked.Increment(ref _skippedByCircuitBreaker);
return null;
}
// Degradation: skip if level >= ExecutorDown
if (_degradationManager is not null && !_degradationManager.ShouldUseInference())
{
Interlocked.Increment(ref _skippedByDegradation);
return null;
}
if (!_modelLoaded || _disposed)
return null;
var tcs = new TaskCompletionSource<FrameAnalysisResult?>(TaskCreationOptions.RunContinuationsAsynchronously);
var job = new FrameJob(jpegData, tcs, minConfidence);
// Wait mode rejects TryWrite when full; every accepted job is completed by the reader.
if (!_frameQueue.Writer.TryWrite(job))
{
Interlocked.Increment(ref _rejectedFrames);
tcs.TrySetResult(null);
return null;
}
return await tcs.Task.WaitAsync(ct);
}
/// <summary>
/// Synchronous frame analysis (for fire-and-forget pipelines that
/// don't need the result immediately). Returns null in passthrough.
/// Respects circuit breaker and degradation level.
/// </summary>
public FrameAnalysisResult? AnalyzeFrame(
byte[] jpegData,
float minConfidence = DefaultMinConfidence)
{
return AnalyzeFrameAsync(jpegData, minConfidence).GetAwaiter().GetResult();
}
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, job.MinConfidence);
sw.Stop();
HeimdallMetrics.RecordYoloInference(sw.Elapsed.TotalMilliseconds, detections.Length);
HeimdallMetrics.RecordInference(sw.Elapsed.TotalMilliseconds, modelLoaded: true);
ReportInferenceResult(sw.ElapsedMilliseconds);
var result = new FrameAnalysisResult(
Convert.ToBase64String(job.ImageData),
detections,
sw.ElapsedMilliseconds);
job.Tcs.TrySetResult(result);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Frame analysis failed");
ReportInferenceFailure();
job.Tcs.TrySetResult(null);
}
}
}
private void ReportInferenceResult(long elapsedMs)
{
if (_circuitBreaker is not null || _degradationManager is not null)
{
if (elapsedMs > SlowInferenceThresholdMs)
{
_circuitBreaker?.ReportFailure();
_degradationManager?.ReportInferenceSlow(elapsedMs);
}
else
{
_circuitBreaker?.ReportSuccess();
_degradationManager?.ReportInferenceSuccess();
}
}
}
private void ReportInferenceFailure()
{
_circuitBreaker?.ReportFailure();
_degradationManager?.ReportInferenceFailure();
}
/// <summary>
/// Run YOLOv8 ONNX inference on a JPEG frame.
/// Pipeline: JPEG decode → resize 640×640 → normalize → ONNX inference → NMS.
/// </summary>
/// <param name="jpegData">Raw JPEG frame bytes.</param>
/// <param name="minConfidence">Minimum confidence threshold (default 0.4 per spec §16).</param>
internal DetectionResult[] RunInference(byte[] jpegData, float minConfidence = DefaultMinConfidence)
{
if (_testInference is not null) return _testInference(jpegData, minConfidence);
if (_session is null)
return [];
lock (_inferenceLock)
{
using var image = new MagickImage(jpegData);
var originalWidth = (int)image.Width;
var originalHeight = (int)image.Height;
image.Format = MagickFormat.Jpeg;
// Resize to model input size (640×640), ignoring aspect ratio (like ImageSharp Resize(640,640))
image.Resize(new MagickGeometry(InputSize, InputSize) { IgnoreAspectRatio = true });
var inputTensor = PreprocessImage(image);
var inputs = new List<NamedOnnxValue>
{
NamedOnnxValue.CreateFromTensor(_inputName, inputTensor)
};
using var runOptions = new RunOptions();
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));
using var timeoutRegistration = timeout.Token.Register(() => runOptions.Terminate = true);
using var results = _session.Run(inputs, _session.OutputNames, runOptions);
var output = results[0].AsTensor<float>().ToArray();
return ParseYoloOutput(output, originalWidth, originalHeight, minConfidence);
}
}
/// <summary>
/// Convert Magick.NET image to a normalized NCHW tensor [1, 3, 640, 640].
/// YOLOv8 expects RGB channels, each normalized to [0, 1].
/// </summary>
internal static DenseTensor<float> PreprocessImage(MagickImage image)
{
var tensor = new DenseTensor<float>([1, 3, InputSize, InputSize]);
// Explicit RGB mapping handles grayscale, CMYK and alpha; byte export normalizes Q16 to 8 bits.
var rgb = image.GetPixels().ToByteArray(PixelMapping.RGB) ?? throw new InvalidOperationException("RGB conversion failed");
var idx = 0;
for (var y = 0; y < InputSize; y++)
{
for (var x = 0; x < InputSize; x++)
{
for (var c = 0; c < 3; c++)
tensor[0, c, y, x] = rgb[idx++] / 255f;
}
}
return tensor;
}
/// <summary>
/// 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.
/// </summary>
/// <param name="output">Flattened output tensor from ONNX Runtime.</param>
/// <param name="imageWidth">Original image width (for scaling back).</param>
/// <param name="imageHeight">Original image height (for scaling back).</param>
/// <param name="minConfidence">Minimum class confidence to keep a detection.</param>
internal DetectionResult[] ParseYoloOutput(
float[] output, int imageWidth, int imageHeight, float minConfidence = DefaultMinConfidence)
{
// 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<RawDetection>();
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 < minConfidence)
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);
}
/// <summary>
/// Non-Maximum Suppression: suppress overlapping boxes of the same class.
/// Returns the surviving detections as DetectionResult records.
/// </summary>
internal static DetectionResult[] ApplyNms(List<RawDetection> candidates)
{
// Sort by confidence descending
candidates.Sort((a, b) => b.Score.CompareTo(a.Score));
var results = new List<DetectionResult>();
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));
SuppressOverlapping(candidates, suppressed, i, best);
}
return results.ToArray();
}
/// <summary>
/// Mark overlapping candidates of the same class as suppressed.
/// Extracted from ApplyNms to reduce cognitive complexity (S3776).
/// </summary>
private static void SuppressOverlapping(
List<RawDetection> candidates, bool[] suppressed, int index, RawDetection best)
{
for (var j = index + 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;
}
}
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 volatile bool _disposed;
private readonly object _disposeLock = new();
public void Dispose()
{
lock (_disposeLock)
{
if (_disposed) return;
_disposed = true;
_frameQueue.Writer.TryComplete();
// Drain accepted work before releasing the native session.
_processingLoop.GetAwaiter().GetResult();
lock (_inferenceLock)
_session?.Dispose();
_cts.Dispose();
}
}
private sealed record FrameJob(byte[] ImageData, TaskCompletionSource<FrameAnalysisResult?> Tcs, float MinConfidence);
}