Files
Heimdall/docs/specs.md
T
Arnaud Dartois 2428e0ec2a docs: add mobile app, auth roles, notifications, hangfire, signalr specs
- Add mobile-app.md: Android Avalonia UI app spec with 6 pages, WebRTC
  via WebView bridge, SignalR real-time, offline cache, push notifications
- Add auth-roles.md: 2 user types (Admin + User), site-scoped permissions,
  policy-based authorization, UI visibility per role
- Add notifications.md: Email SMTP (FluentEmail), Gotify push, Scriban
  Markdown templates i18n editable from UI, per-user config
- Add hangfire-usage.md: Central PostgreSQL jobs (retention, cleanup,
  digests) + Agent InMemory jobs (heartbeat, camera health, GPU watchdog)
- Add signalr-usage.md: 5 hubs (events, streaming, monitoring, notifications,
  admin) with full hub code, group management, Agent SignalR connection
- Update implementation.md: 23 phases with mobile app (phase 21)
- Update specs.md: reference all new documentation files
2026-07-16 19:29:07 +00:00

40 KiB
Raw Blame History

Documentation associée :

  • docs/ui-pages.md — Description détaillée de toutes les pages UI (Blazor)
  • docs/mobile-app.md — Application Android (Avalonia UI) — consultation uniquement
  • docs/auth-roles.md — Authentification, rôles, permissions, visibilité UI
  • docs/notifications.md — Email SMTP, Gotify, templates Markdown i18n
  • docs/hangfire-usage.md — Tous les jobs Hangfire (Central + Agent)
  • docs/signalr-usage.md — Tous les hubs SignalR (events, streaming, monitoring)
  • docs/implementation.md — Plan d'implémentation complet par phases
# Heimdall
## Intelligent Local AI Video Surveillance Platform

**Version:** 1.0
**Target Framework:** .NET 10+
**Architecture:** Clean Architecture / CQRS / Multi-site / Local AI

---

# 1. Vision

## Overview

Heimdall is a modern self-hosted intelligent video surveillance platform designed around:

- Local AI processing
- Multi-site architecture
- ONVIF camera discovery
- RTSP video management
- Face recognition
- License plate recognition
- Local LLM analysis
- Enterprise security model
- Full configuration through Web UI

Heimdall does not depend on cloud services.

All business configuration is stored in PostgreSQL and managed through the application interface.

---

# 2. Main Objectives

## Functional Objectives

- Manage multiple sites
- Automatically discover ONVIF cameras
- Support Imou cameras at minimum
- Record and manage video streams
- Detect people, vehicles and objects
- Recognize known persons
- Detect and read license plates
- Associate vehicles with persons
- Generate AI summaries using Ollama
- Provide secure API access
- Provide complete administration through Blazor UI

---

## Technical Objectives

- 100% Docker deployment
- .NET 10+
- PostgreSQL as unique source of configuration
- No business configuration files
- Local-first architecture
- GPU acceleration when available
- Enterprise logging and monitoring

---

# 3. Naming

## Heimdall

Inspired by Norse mythology.

Heimdall is the guardian watching the Bifröst bridge.

Mission:

> Protect and monitor your infrastructure.

---

# 4. Global Architecture

```text
                     Heimdall Central
                    (ASP.NET Core + Blazor)
                          |
              ┌───────────┼──────────────┐
              │ Signaling │   HTTPS API   │
              │ (SignalR) │   (REST)      │
              └─────┬─────┴──────┬────────┘
                    │            │
                    │  ┌─────────┴──────────┐
                    │  │    PostgreSQL       │
                    │  │  + STUN/TURN        │
                    │  │  (coturn - Docker)  │
                    │  └────────────────────┘
                    │
       ┌────────────┴────────────┐
       │  WebRTC P2P Signaling   │
       │  (SDP + ICE via SignalR)│
       └────────────┬────────────┘
                    │
              ┌─────┴──────┐
              │            │
   ┌──────────┴──────┐  ┌──┴────────────────┐
   │ Heimdall Agent  │  │ Heimdall Agent     │
   │ (Site A)        │  │ (Site B)           │
   │                 │  │                    │
   │ SIPSorcery      │  │ SIPSorcery         │
   │ WebRTC Peer     │  │ WebRTC Peer        │
   │ FFmpeg → H264   │  │ FFmpeg → H264      │
   └──┬───────────────┘  └───┬────────────────┘
      │                      │
      │ Flux WebRTC P2P      │ Flux WebRTC P2P
      │ ◄══════════════════► │ ◄══════════════►
      │  (SRTP/SCTP direct)  │   (SRTP/SCTP)
      └──────────────────────┘
                │
       ┌────────┴────────┐
       │  STUN/TURN      │
       │  (si double NAT)│
       └─────────────────┘


5. Solution Structure

Heimdall.sln

src/

├── Heimdall.Domain
├── Heimdall.Application
├── Heimdall.Infrastructure
├── Heimdall.Api
├── Heimdall.Web
├── Heimdall.Agent
├── Heimdall.Workers
├── Heimdall.Contracts
└── Heimdall.Shared

6. Technology Stack

Backend

  • .NET 10+
  • C#
  • ASP.NET Core
  • Blazor Web App
  • Clean Architecture
  • CQRS
  • MediatR
  • FluentValidation
  • Entity Framework Core
  • Hangfire
  • Serilog
  • OpenTelemetry ready
  • Sentry SDK compatible with GlitchTip
  • SignalR — WebRTC signaling (SDP + ICE exchange)
  • SIPSorcery — WebRTC peer (ICE, STUN, TURN, DTLS, SRTP)
  • SIPSorceryMedia.FFmpeg — Codec H264 via FFmpeg
  • coturn — TURN relay (optionnel, double NAT)

Frontend

  • Blazor Web App
  • Interactive Server Rendering
  • MudBlazor
  • Material Design principles

Database

PostgreSQL

ORM:

  • Entity Framework Core

Database configuration:

  • IEntityTypeConfiguration
  • Specification Pattern

No generic repository pattern.


7. Coding Rules

All code must follow Microsoft .NET recommendations.

Language

Source code:

  • English only

Comments:

  • English only

XML documentation:

  • English only

C# Rules

Enabled:

  • Nullable Reference Types
  • Implicit Usings
  • File Scoped Namespace

Rules:

  • Async everywhere
  • No blocking calls
  • Strong typing
  • No magic strings
  • No duplicated business logic

8. Domain Model Design

Enum First Approach

Heimdall maximizes strongly typed enums.

Business states must never be represented by strings.


Examples

Camera Status

public enum CameraStatus
{
    Unknown,
    Online,
    Offline,
    Disabled,
    Error
}

Event Type

public enum EventType
{
    MotionDetected,
    PersonDetected,
    VehicleDetected,
    UnknownPerson,
    FaceRecognized,
    LicensePlateDetected
}

Storage Provider

public enum StorageProvider
{
    Local,
    S3
}

Theme Mode

public enum ThemeMode
{
    Light,
    Dark,
    Auto
}

9. Authentication and Security

Authentication

Microsoft Identity.

No Azure AD dependency.


Authorization

Based on:

  • Roles
  • Permissions
  • Policies

Examples:

Camera.Read

Camera.Write

Person.Read

Person.Write

Recording.Delete

Administration.Manage

10. API Security

External integrations use API Keys.

Features:

  • Generate API key from UI
  • Define permissions
  • Expiration date
  • Revocation
  • Audit history

Storage:

  • Hash only
  • Never store clear text keys

11. Multi Site Management

Site Entity

Site
├── Id              (Guid, PK)
├── Name            (string, required)
├── Description     (string)
├── Address         (string)
├── Timezone        (string)
├── Enabled         (bool)
│
├── Registration    (pour déploiement Agent)
│   ├── Token       (string, hash SHA256)
│   ├── TokenPlain  (string, affiché 1 fois à la création)
│   ├── TokenExpiresAt (DateTime?)
│   └── Agents      (List<Agent>)

Each object belongs to a site:

  • Cameras
  • Events
  • Recordings
  • Persons
  • Vehicles
  • Agents

Agent Registration Flow

┌─────────┐       ┌──────────┐       ┌──────────┐
│ Admin    │       │ Heimdall │       │ Agent    │
│ (Blazor) │       │ Central  │       │ (Docker) │
└────┬─────┘       └────┬─────┘       └────┬─────┘
     │                  │                  │
     │ 1. Crée Site     │                  │
     │─────────────────►│                  │
     │                  │ 2. Génère token  │
     │                  │   (UUID v4)      │
     │ 3. Token +       │                  │
     │    commande      │                  │
     │◄─────────────────│                  │
     │    docker        │                  │
     │    préremplie    │                  │
     │                  │                  │
     │ 4. docker run -e │                  │
     │    SITE_TOKEN=.. │                  │
     │────────────────────────────────────►│
     │                  │                  │
     │                  │ 5. POST /api/agents/register
     │                  │◄─────────────────│
     │                  │    { token,      │
     │                  │      hostname,   │
     │                  │      version }   │
     │                  │                  │
     │                  │ 6. Valide token  │
     │                  │    Associe site  │
     │                  │    AgentId = UUID│
     │ 7. Agent OK      │                  │
     │◄─────────────────│                  │
     │                  │ 8. Heartbeat     │
     │                  │    toutes les 30s│
     │                  │◄─────────────────│

Le token est mono-usage : une fois l'Agent enregistré, le token est consommé. Pour ajouter un autre Agent, l'admin génère un nouveau token depuis l'UI.

API Endpoints — Registration

Méthode Route Auth Description
POST /api/sites/{id}/tokens Admin Génère un nouveau token d'enregistrement
GET /api/sites/{id}/tokens Admin Liste les tokens actifs
DELETE /api/sites/{id}/tokens/{tokenId} Admin Révoque un token
POST /api/agents/register Token Enregistre un Agent (public, sans auth préalable)
GET /api/agents/{id}/heartbeat API Key Heartbeat Agent
GET /api/sites/{id}/agents Admin Liste les Agents du site

Token Security

  • Token = UUID v4 (128 bits, 36 chars)
  • Stocké en base : SHA256(token)
  • Affiche en clair 1 seule fois à la création
  • Durée de vie : configurable (défaut 24h)
  • Révocable depuis l'UI
  • Une fois l'Agent enregistré → automatiquement expiré

12. Heimdall Agent

Optional Docker component.

Purpose:

  • Manage remote sites
  • Communicate with local cameras
  • Process local streams
  • Reduce WAN traffic
  • Stream live video via WebRTC P2P vers le navigateur

Communication:

  • HTTPS (REST API + SignalR WebSocket)
  • Secure authentication (API key)
  • SignalR — signaling WebRTC (SDP + ICE candidates)
  • WebRTC P2P — flux vidéo direct (SRTP/SCTP) avec le navigateur

Live Video Streaming — WebRTC P2P

Le Heimdall Agent utilise SIPSorcery pour diffuser le flux vidéo en direct vers le navigateur via WebRTC, sans passer par le serveur central.

Pipeline

Caméra RTSP
    │
    ▼
FFmpeg (demux RTSP → decode → encode H264)
    │                                   ┌─────────────────┐
    ▼                                   │                 │
RTP stream (H264 encodé)               │ SIPSorcery      │
    │                                   │ WebRTC Peer     │
    ▼                                   │                 │
FFmpegListener (capture les frames) ──→ │ addTrack(H264)  │
                                        │ createOffer()   │
                                        │ ICE/STUN/TURN   │
                                        └────────┬────────┘
                                                 │
                                          WebRTC P2P
                                          (SRTP/H264)
                                                 │
                                                 ▼
                                        Navigateur (Blazor)
                                        <video> tag native

Bibliothèque

Package Version Rôle
SIPSorcery 10.0.12+ Moteur WebRTC (ICE, STUN, TURN, SDP, DTLS, SRTP)
SIPSorceryMedia.FFmpeg 10.0.12+ Codec H264 via FFmpeg (PINvoke)
SIPSorcery.VP8 10.0.12+ Codec VP8 pur C# (fallback sans FFmpeg)

Performances (benchmark SIPSorcery avec H264)

Résolution FPS encodage
1080p 174 fps
4K 48 fps

Avantages

  • ✅ Aucun traffic WAN entre l'Agent et le Central pour le live — P2P direct
  • ✅ Latence < 500 ms (temps réel)
  • ✅ Traverse les NAT grâce à ICE/STUN/TURN
  • ✅ Navigateur natif WebRTC — pas de plugins
  • ✅ 100% C# — pas de wrapper natif WebRTC

Limitations

  • ❌ Double NAT nécessite un TURN relay (coturn, Docker séparé)
  • ❌ Le navigateur doit rester connecté — pas de mode "push" permanent

Agent Bootstrap — Registration

Environnement

L'Agent démarre avec ces variables d'environnement :

HEIMDALL_CENTRAL_URL=https://central.heimdall.example.com
HEIMDALL_SITE_TOKEN=abc123-def456-ghi789               # depuis l'UI
HEIMDALL_AGENT_NAME=entrepot-a                          # optionnel
HEIMDALL_TURN_SERVER=turn:central.heimdall.example.com  # optionnel

Cycle de vie

┌─────────────────────────────────────────────────────────────┐
│                        BOOTSTRAP                            │
│                                                             │
│ 1. Agent démarre                                            │
│ 2. Lit HEIMDALL_SITE_TOKEN                                  │
│ 3. POST /api/agents/register { token, hostname, version }   │
│ 4. Central valide :                                         │
│    ├── Token existe ? → non → 401                           │
│    ├── Token expiré ? → oui → 401 + message "regenerate"    │
│    ├── Token déjà utilisé ? → oui → 409 (concurrent)       │
│    └── OK → crée Agent, hash le token, expire le token      │
│ 5. Agent reçoit { agentId, siteId, iceServers[] }           │
│ 6. Agent sauvegarde agentId dans /data/agent.json           │
│ 7. Agent commence heartbeat                                 │
│                                                             │
│                      RUNNING                                │
│                                                             │
│ 8. Heartbeat POST /api/agents/{id}/heartbeat toutes les 30s │
│ 9. Central détecte absence > 90s → Agent = Offline         │
│                                                             │
│                   RECONNECTION                              │
│                                                             │
│ 10. Agent perd la connexion                                 │
│ 11. Relit /data/agent.json (agentId toujours valide)        │
│ 12. POST /api/agents/{id}/heartbeat → reprend              │
│                                                             │
│                     RE-REGISTRATION                         │
│                                                             │
│ 13. /data/agent.json perdu (nouveau déploiement)            │
│ 14. Repart à l'étape 1 avec le même token                  │
│     → 409 si déjà enregistré → admin doit regénérer token  │
└─────────────────────────────────────────────────────────────┘

Agent Entity

Agent
├── Id              (Guid, PK)
├── SiteId          (Guid, FK → Site)
├── Name            (string)
├── Hostname        (string)
├── Version         (string)
├── LastHeartbeat   (DateTime)
├── FirstSeen       (DateTime)
├── Status          (Online | Offline | Error)
├── PublicIp        (string)        // Détecté au register
├── IceEndpoint     (string?)       // Endpoint WebRTC public
└── Capabilities    (jsonb)
    ├── HasGpu      (bool)
    ├── CpuCores    (int)
    ├── RamMb       (int)
    └── CamerasMax  (int)

Multi-User Streaming — SFU (Selective Forwarding Unit)

Quand N utilisateurs regardent la MÊME caméra simultanément, le P2P pur nécessite N connexions WebRTC → N× CPU + N× bande passante montante.

Solution : MediaMTX en mode SFU

                    ┌──────────────┐
                    │   MediaMTX   │
                    │  (SFU/Docker)│
                    └──┬───────┬───┘
                       │       │
              ┌────────┘       └────────┐
              │                         │
         ┌────▼─────┐            ┌──────▼──────┐
         │ Browser 1 │            │  Browser 2   │
         │ WebRTC    │            │  WebRTC      │
         └───────────┘            └──────────────┘

L'Agent envoie 1 SEUL flux WebRTC → MediaMTX
MediaMTX distribue aux N navigateurs
Avantage Sans SFU Avec SFU (MediaMTX)
CPU Agent pour 3 viewers 3× encodage H264 1× encodage H264
Bande passante Agent 3× 5 Mbps = 15 Mbps 1× 5 Mbps
Enregistrement Impossible en P2P HLS automatique

MediaMTX est un conteneur Docker Go (19.5k★, MIT). Il tourne sur le Central et fait aussi office de proxy de repli si le P2P échoue.

Quand utiliser le SFU :

  • Plus de 2 viewers simultanés sur la même caméra
  • Agent derrière un NAT symétrique sans TURN
  • Nécessité d'enregistrer le flux live

Quand utiliser le P2P direct :

  • 1 seul viewer
  • Faible latence nécessaire (< 500ms)
  • Bande passante Agent limitée (pas de double envoi)

13. WebRTC Signaling Protocol

Le signaling est l'échange de métadonnées (SDP offer/answer, ICE candidates) entre l'Agent et le navigateur via le serveur Central, avant d'établir la connexion P2P directe.

Architecture du Signaling

Navigateur                   Heimdall Central                  Heimdall Agent
(Blazor)                        (API)                         (SIPSorcery)
    │                              │                              │
    │ 1. Demande live camera X     │                              │
    │─────────────────────────────►│                              │
    │                              │ 2. Notifie Agent             │
    │                              │─────────────────────────────►│
    │                              │                              │
    │                              │ 3. Crée RTCPeerConnection    │
    │                              │   + addTrack(H264)           │
    │                              │   + createOffer()            │
    │                              │◄─────────────────────────────│
    │                              │                              │
    │ 4. SDP Offer                 │                              │
    │◄─────────────────────────────│                              │
    │                              │                              │
    │ 5. setRemoteDescription()    │                              │
    │ 6. createAnswer()            │                              │
    │                              │                              │
    │ 7. SDP Answer                │                              │
    │─────────────────────────────►│                              │
    │                              │ 8. Relay SDP Answer          │
    │                              │─────────────────────────────►│
    │                              │                              │
    │ 9. Échange ICE candidates    │                              │
    │◄════════════════════════════►│◄════════════════════════════►│
    │   (via SignalR)              │   (via SignalR)              │
    │                              │                              │
    │════════════════════10. WebRTC P2P═══════════════════════════►│
    │   Flux H264 direct (SRTP)    │                              │
    │   ← Agent → Navigateur      │                              │

Transport de Signaling

Transport Usage Détails
SignalR (WebSocket) Signaling en temps réel Hub dédié /hubs/streaming dans l'API Central
HTTPS REST Fallback signaling POST /api/streaming/offer, GET candidates
API Key Authentification Signe les requêtes de signaling

Services auxiliaires

Service Rôle Docker
STUN Découverte d'adresse publique pour ICE Intégré à SIPSorcery (serveur STUN intégré)
TURN Relay médias si P2P impossible (double NAT) coturn/coturn (Docker séparé)

Le STUN est intégré à SIPSorcery. Le TURN (coturn) est optionnel — nécessaire uniquement pour les sites en double NAT symétrique.


14. Camera Management

Supported protocols:

  • ONVIF
  • RTSP
  • HTTP MJPEG

Supported manufacturers:

Minimum:

  • Imou

Compatible:

  • Dahua
  • Hikvision
  • Reolink
  • Axis
  • Amcrest
  • ONVIF compatible devices

ONVIF Discovery

Features:

  • Network scan
  • Camera identification
  • Manufacturer detection
  • Model detection
  • Firmware detection
  • RTSP discovery
  • Snapshot discovery
  • PTZ capability detection

Authentication:

Optional.


Imou Cameras — Specific Protocol

⚠️ Les caméras Imou n'utilisent pas ONVIF par défaut. Configuration requise :

  1. Activer le mode RTSP manuellement dans l'application Imou (Paramètres → Avancé → RTSP)
  2. Définir un mot de passe RTSP dédié
  3. RTSP URL : rtsp://user:password@192.168.1.x:554/live/ch0

SDK Imou non supporté — Heimdall communique exclusivement via RTSTP/ONVIF.

Discovery — Network Constraints

Méthode Portée Limitations
ONVIF WS-Discovery (multicast) Même VLAN ❌ Ne traverse pas les routeurs
mDNS/Bonjour Même sous-réseau ❌ Limitée au broadcast local
Discovery manuelle (IP+port) Toute IP accessible ✅ Fonctionne toujours, configuration via UI

Toutes les caméras ajoutées via discovery automatique peuvent être réassignées manuellement si l'IP change (DHCP → réservation ou IP fixe recommandé).

Camera Entity

Camera
├── Id              (Guid, PK)
├── SiteId          (Guid, FK)
├── Name            (string)
├── Manufacturer    (Imou | Dahua | Hikvision | ...)
├── Model           (string)
├── FirmwareVersion (string)
│
├── Connection
│   ├── Protocol    (ONVIF | RTSP | MJPEG)
│   ├── Host        (string)
│   ├── Port        (int)
│   ├── RtspUrl     (string)
│   ├── SnapshotUrl (string?)
│   └── Credentials (encrypted)  // Chiffré avec IDataProtector
│
├── Capabilities
│   ├── Ptz         (bool)
│   ├── Audio       (bool)
│   ├── MotionDetection (bool)
│   └── MaxResolution   (string)
│
├── Status          (Unknown | Online | Offline | Disabled | Error)
├── LastSeen        (DateTime?)
├── StoragePolicyId (Guid?, FK)
└── AgentId         (Guid?, FK → Agent)

Le mot de passe de la caméra est chiffré (IDataProtector) avant stockage en base. Il n'est jamais retourné par l'API — seulement utilisé côté Agent.


15. Video Processing & GPU Acceleration

FFmpeg

Used for:

  • RTSP capture
  • Recording
  • Segmentation
  • Snapshot extraction

Hardware Acceleration

Techno Docker requis GPU Compatible
NVIDIA CUDA nvidia-container-toolkit + --gpus all NVIDIA Tesla/GeForce/RTX ✅ x86_64
Intel QSV --device /dev/dri:/dev/dri Intel HD Graphics/Xe ✅ x86_64
VAAPI --device /dev/dri:/dev/dri Intel/AMD GPU ✅ x86_64
CPU only Aucun N/A ✅ Toutes (ARM, RPi)

Auto-détection au démarrage de l'Agent

enum GpuAcceleration
{
    None,           // CPU only
    NvidiaCuda,     // NVIDIA GPU détecté
    IntelQuickSync, // /dev/dri présent + Intel
    Vaapi           // /dev/dri présent + AMD/autres
}

L'Agent détecte automatiquement le GPU disponible et ajuste :

  • le codec utilisé (H264_nvenc, H264_qsv, H264_vaapi, libx264)
  • le nombre max de flux simultanés
  • la résolution max par flux

Capacités estimées (CPU only, Intel i5-10gen)

Mode 720p 1080p 4K
CPU (libx264 medium) ~8 flux ~4 flux ~1 flux
GPU (NVENC/QSV) ~20+ flux ~12+ flux ~4+ flux

16. AI Pipeline — Two-Tier Architecture

L'IA est répartie sur deux niveaux pour concilier réactivité et réduction du trafic WAN.

                           AGENT (site distant)
┌──────────────────────────────────────────────────────────────┐
│  Caméra RTSP                                                 │
│      │                                                       │
│      ▼                                                       │
│  FFmpeg → snapshot JPEG (toutes les 200ms)                   │
│      │                                                       │
│      ▼                                                       │
│  Pré-détection CPU (YOLOv8 nano / MobileNet)                 │
│      │                                                       │
│      ├── Aucun mouvement → ignore                            │
│      ├── Mouvement seul → envoie snapshot baseline           │
│      └── Personne/véhicule détecté → alerte + snapshot       │
│              │                                               │
│              ▼  HTTPS (événement + snapshot JPEG)            │
└──────────────┼───────────────────────────────────────────────┘
               │
               │  Trafic WAN = seulement les événements
               │  confirmés (pas de flux continu)
               ▼
                       CENTRAL (serveur)
┌──────────────────────────────────────────────────────────────┐
│  CodeProject.AI (GPU)                                        │
│      │                                                       │
│      ├── Confirmation objet détecté                          │
│      ├── Reconnaissance faciale complète                     │
│      └── Lecture de plaque (LPR)                             │
│      │                                                       │
│      ▼                                                       │
│  Event Creation + Notification                               │
│      │                                                       │
│      ▼                                                       │
│  Ollama (LLM local) — résumé quotidien/hebdomadaire          │
└──────────────────────────────────────────────────────────────┘

Zone de tuning

La pré-détection sur l'Agent est paramétrable par caméra :

Paramètre Défaut Description
snapshot_interval_ms 200 Intervalle entre snapshots
motion_threshold 0.3 Sensibilité mouvement (0-1)
detection_model yolov8n Modèle (nano = rapide, small = précis)
send_full_snapshot true Envoyer l'image au Central ou juste métadonnées

La pré-détection peut être désactivée (mode "full relay") si le site a assez de bande passante.



16. Object Detection

Supported:

  • Person
  • Vehicle
  • Animal
  • Package
  • Custom objects depending on AI model

17. Face Recognition

Features:

  • Person profiles
  • Training images
  • Recognition history
  • Unknown faces
  • Manual assignment

Person Management UI

A person contains:

Person

Name

Photo

Face Samples

Vehicles

License Plates

Events History

Notes

18. Vehicle Management

Entity:

Vehicle

Brand

Model

Color

Plate

Owner

Pictures

19. License Plate Recognition

Pipeline:

Vehicle Detection

↓

Plate Detection

↓

OCR

↓

Database Search

↓

Person Association

20. Storage Management

Architecture — MinIO centralisé (par défaut)

Le stockage est centralisé sur le serveur via MinIO (compatible S3). L'Agent écrit les segments vidéo directement sur le S3 partagé.

Agent (site distant)
    │
    │ Enregistrement HLS/MP4
    ▼
MinIO (sur le Central ou external)   ← Partage entre tous les Agents
    │
    ├── Playback depuis le navigateur (lecture directe S3)
    ├── Retention job Hangfire (purge S3 directement)
    └── Sauvegarde/configurable vers AWS S3/OVH

Le stockage LOCAL existe en fallback si le site n'a pas assez
de débit montant → les vidéos restent sur l'Agent et le
playback se fait via proxy (→ pas de lecture distante).

Providers

Provider Usage Rôle
MinIO (Docker) Défaut, déploiement standard Stockage principal centralisé
AWS S3 Production / Cloud Alternative à MinIO
OVH / Scaleway / Wasabi Cloud EU Alternative compatible S3
Local (Agent) Fallback bas-débit Stockage local si WAN insuffisant

Storage Policies

Configurable par caméra :

Camera: Entrée Principale
├── Provider: MinIO
├── Retention: 30 jours
├── Recording: Continu (24/7) | Mouvement | Programme
├── Resolution: 1080p
├── SegmentDuration: 300s (HLS .ts)
└── Compression: H264 medium

Camera: Jardin
├── Provider: Local (Agent)       ← Site distant bas-débit
├── Retention: 7 jours
├── Recording: Mouvement seul
└── Resolution: 720p

Impact bande passante

Recording Mode Débit par caméra (1080p H264) Usage
Continu 24/7 ~2-4 Mbps montant Critique : MinIO requis
Mouvement seul ~50-200 Kbps moyen Acceptable : MinIO ou Local
Snapshots (IA) ~10 Kbps (alertes) Tous sites

Un site avec < 10 Mbps montant doit utiliser le mode "Mouvement seul" ou "Local fallback".



21. Retention Management

Implemented with Hangfire.

Database:

PostgreSQL


Managed jobs:

  • Delete expired recordings
  • Delete snapshots
  • Delete events
  • Cleanup unknown faces
  • Cleanup license plates
  • Database maintenance
  • S3 cleanup

22. Hangfire

All scheduled tasks are persisted.

No custom timers.


UI allows:

  • View jobs
  • Execute manually
  • Disable jobs
  • Change schedule
  • View history

23. Logging

Framework:

Serilog


Levels:

Trace

Debug

Information

Warning

Error

Critical

Structured logging:

_logger.LogInformation(
    "Camera {CameraId} changed status to {Status}",
    camera.Id,
    camera.Status);

24. Sentry / GlitchTip

Integration:

Official Sentry SDK.

Captured:

  • Exceptions
  • API failures
  • Worker failures
  • Performance issues
  • Background job errors

Context:

  • UserId
  • SiteId
  • CameraId
  • JobId
  • CorrelationId

Sensitive data filtering enabled.


25. Ollama Integration

Purpose:

  • Daily summaries
  • Weekly summaries
  • Event analysis

Supported models:

  • Qwen
  • Gemma
  • Mistral
  • Llama

Example:

Daily Summary:

3 known persons detected.

1 unknown vehicle detected.

No critical events.

26. Web Application

Framework

Blazor Web App (Interactive Server Rendering).

Live Video — Blazor + WebRTC JS Interop

⚠️ WebRTC est une API JavaScript côté navigateur. Blazor Server exécute le C# sur le serveur. La communication entre les deux se fait via JS Interop.

Architecture

┌─────────────────────────────────────────────────────────────┐
│                     SERVEUR BLZOR                            │
│                                                              │
│  Component.razor.cs                                          │
│  ├── OnInitializedAsync() → init JS module                   │
│  ├── DisposeAsync() → close RTCPeerConnection                │
│  ├── DotNet.invokeMethodAsync() → receive events from JS     │
│  └── JSRuntime.InvokeAsync() → send commands to JS           │
│                                                              │
└────────────────────────┬────────────────────────────────────┘
                         │  JS Interop
                         ▼
┌─────────────────────────────────────────────────────────────┐
│                     NAVIGATEUR (Browser)                     │
│                                                              │
│  wwwroot/js/liveView.js                                      │
│  ├── Module JS autonome (ES module)                          │
│  ├── new RTCPeerConnection()                                 │
│  ├── ontrack → <video> element                               │
│  ├── SignalR connection au hub /hubs/streaming               │
│  │   (pour signaling SDP/ICE)                                │
│  └── Survit aux reconnexions Blazor Server                   │
│                                                              │
└─────────────────────────────────────────────────────────────┘

Cycle de vie critique

1. Component Blazor s'initialise
2. Importe le module JS : await JSRuntime.InvokeAsync("import", "./js/liveView.js")
3. Module JS ouvre SignalR → connecté au hub streaming
4. Module JS crée RTCPeerConnection
5. Échange SDP/ICE via SignalR → connexion WebRTC établie
6. Flux vidéo affiché dans <video>
7. ⚠️ Reconnexion Blazor Server (circuit perdu/restauré) :
   - Le module JS SURVIT (il est dans le navigateur, pas dans le circuit)
   - Le composant Blazor se réinitialise → ré-attache les callbacks
   - Le module JS continue : pas de reconnexion WebRTC
8. Component.DisposeAsync() → ferme RTCPeerConnection proprement

Règles

  • Le module JS liveView.js est autonome — pas de dépendance au cycle Blazor
  • RTCPeerConnection n'est jamais créé depuis C# — uniquement depuis JS
  • Les callbacks Blazor (DotNet.invokeMethodAsync) sont enregistrés après chaque reconnexion du circuit
  • Le <video> élément est en HTML standard, pas en composant Blazor
  • En mode Blazor Server, le flux vidéo ne passe PAS par le serveur (P2P direct)

27. Theme

Supported:

  • Light
  • Dark
  • Auto

Stored per user.


28. Localization

Current language:

French.

Architecture ready for:

  • English
  • Other languages

No hardcoded UI strings.


29. Dashboard

KPI based.

Widgets:

Camera KPI

  • Total cameras
  • Online cameras
  • Offline cameras

Event KPI

  • Events today
  • Persons detected
  • Vehicles detected
  • Unknown persons

Storage KPI

  • Used space
  • Available space
  • Growth rate

AI KPI

  • CodeProject.AI status
  • GPU usage
  • Ollama status

30. Docker Deployment

Containers

heimdall-api        # ASP.NET Core API + SignalR (WebRTC signaling)
heimdall-web        # Blazor Web App (MudBlazor)
heimdall-worker     # Hangfire jobs (retention, cleanup)
heimdall-agent      # SIPSorcery WebRTC peer + FFmpeg capture
postgresql          # Base de données PostgreSQL
minio               # Stockage S3 compatible (enregistrements vidéo)
codeproject-ai      # Détection IA lourde (objets, visages, plaques)
ollama              # LLM local (résumés, analyse)
mediamtx            # SFU WebRTC + proxy (optionnel, multi-user)
coturn              # TURN relay (optionnel, double NAT)

GPU Passthrough par conteneur

Conteneur GPU requis Commande Docker Équivalent docker-compose
codeproject-ai NVIDIA CUDA --gpus all deploy.resources.reservations.devices[0].capabilities: [gpu]
heimdall-agent NVIDIA/Intel --gpus all ou --device /dev/dri:/dev/dri devices: ["/dev/dri:/dev/dri"]
ollama Optionnel (NVIDIA) --gpus all Même que codeproject-ai

docker-compose.yml — extraits GPU

services:
  codeproject-ai:
    image: codeproject/ai-server:latest
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: all
              capabilities: [gpu]
    environment:
      - CUDA_VISIBLE_DEVICES=0

  heimdall-agent:
    image: heimdall/agent:latest
    # GPU optionnel — auto-détecté au démarrage
    devices:
      - /dev/dri:/dev/dri   # Intel/AMD
    # NVIDIA: décommenter la section deploy ci-dessous
    # deploy:
    #   resources:
    #     reservations:
    #       devices:
    #         - driver: nvidia
    #           capabilities: [gpu]

MediaMTX — SFU optionnel

mediamtx:
  image: bluenviron/mediamtx:latest
  ports:
    - "8889:8889/udp"   # WebRTC ICE/DTLS
    - "8890:8890/udp"   # WebRTC ICE/DTLS
  volumes:
    - ./mediamtx.yml:/mediamtx.yml
  restart: unless-stopped

31. Quality Requirements

Heimdall follows:

  • Clean Architecture
  • SOLID principles
  • CQRS
  • Specification Pattern
  • Strong typing
  • Enum driven design
  • Secure by default
  • Observable by default
  • Fully configurable from UI

32. Future Extensions

Possible features:

  • Mobile application
  • PTZ automation
  • Advanced analytics
  • Custom AI models
  • Plugin system
  • OpenTelemetry dashboards
  • Grafana integration
  • Public SDK

Conclusion

Heimdall is a complete local-first AI video surveillance platform.

It combines:

  • .NET 10+
  • PostgreSQL
  • Blazor
  • MudBlazor
  • CodeProject.AI
  • Ollama
  • Hangfire
  • Sentry / GlitchTip
  • Distributed Agents

while keeping full ownership of infrastructure, configuration and data.