Files
Heimdall/docs/specs.md
T
Arnaud Dartois bfb3e06bc1 feat: initialize .NET 10 Clean Architecture solution
Create Heimdall solution with 17 projects following Clean
Architecture for a maintainable and loosely coupled codebase.

src/ (9 projects):
- Domain, Domain.Primitives, Contracts (core layer, no deps)
- Application (ref. Domain) — CQRS/MediatR ready
- Infrastructure (ref. Application + Domain) — EF Core
  PostgreSQL ready
- Api, Web (Blazor), Agent, Workers (hosts, ref. Application +
  Infrastructure)

tests/ (8 projects):
- xUnit + Shouldly + NSubstitute + bUnit (Web.Tests)
- One test project per source project (Domain -> IntegrationTests)

Config: Directory.Build.props (Nullable, ImplicitUsings,
TreatWarningsAsErrors)
2026-07-16 19:09:28 +00:00

1057 lines
18 KiB
Markdown

Voici une version Markdown complète directement **copier/coller** dans un fichier :
`Heimdall_Complete_Specification.md`
````markdown
# 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
```text
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<T>
* 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
```csharp
public enum CameraStatus
{
Unknown,
Online,
Offline,
Disabled,
Error
}
```
---
### Event Type
```csharp
public enum EventType
{
MotionDetected,
PersonDetected,
VehicleDetected,
UnknownPerson,
FaceRecognized,
LicensePlateDetected
}
```
---
### Storage Provider
```csharp
public enum StorageProvider
{
Local,
S3
}
```
---
### Theme Mode
```csharp
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
Example:
```
Site
Id
Name
Description
Address
Timezone
Enabled
```
---
Each object belongs to a site:
* Cameras
* Events
* Recordings
* Persons
* Vehicles
---
# 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
```text
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
---
# 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
```text
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.
---
# 14. Video Processing
## FFmpeg
Used for:
* RTSP capture
* Recording
* Segmentation
* Snapshot extraction
Hardware acceleration:
Supported:
* NVIDIA CUDA
* Intel QuickSync
* VAAPI
---
# 15. AI Pipeline
```text
Camera
↓
FFmpeg
↓
Snapshot
↓
CodeProject.AI
↓
Detection
↓
Event Creation
↓
Notification
```
---
# 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:
```text
Vehicle Detection
↓
Plate Detection
↓
OCR
↓
Database Search
↓
Person Association
```
---
# 20. Storage Management
Supported providers:
## Local Storage
Example:
```
/recordings
```
---
## S3 Storage
Compatible:
* MinIO
* AWS S3
* OVH
* Scaleway
* Wasabi
---
Storage policies are configurable:
Example:
```
Camera Entrance
Retention: 30 days
Provider: Local
```
---
# 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:
```csharp
_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.
---
## UI Library
MudBlazor.
Maximum usage of:
* MudTable
* MudDataGrid
* MudCard
* MudDialog
* MudDrawer
* MudTabs
* MudTimeline
* MudCharts
* MudForms
---
# 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:
```text
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
codeproject-ai # Détection IA (objets, visages, plaques)
ollama # LLM local (résumés, analyse)
coturn # TURN relay (optionnel — double NAT)
```
---
# 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.