This document describes the architecture and internal design of the LightNVR system.
LightNVR is designed with a modular architecture that prioritizes memory efficiency and reliability. The system is composed of several key components that work together to provide a complete Network Video Recorder solution.
Note: A system architecture diagram should be created based on the specifications in images/system-architecture.txt
The core system is responsible for:
- Application lifecycle management
- Configuration loading and validation
- Signal handling and graceful shutdown
- Daemon mode operation
- PID file management
- Logging
Key files:
src/core/main.c
: Main entry point and application lifecyclesrc/core/config.c
: Configuration loading and managementsrc/core/daemon.c
: Daemon mode functionalitysrc/core/logger.c
: Logging system
The video subsystem handles:
- Stream management (connecting to cameras)
- Video decoding and processing
- Frame buffering and memory management
- Recording to disk
Key files:
src/video/stream_manager.c
: Manages stream connections and statesrc/video/streams.c
: Stream implementationsrc/video/hls_writer.c
: HLS (HTTP Live Streaming) recordingsrc/video/mp4_writer.c
: MP4 recording
The storage subsystem is responsible for:
- Managing recording storage
- Implementing retention policies
- Disk space management
- File organization
Key files:
src/storage/storage_manager.c
: Storage management implementation
The database subsystem handles:
- Storing stream configurations
- Recording metadata
- System settings
- User authentication
Key files:
src/database/database_manager.c
: Database operations
The web interface provides:
- User interface for managing the system
- Live view of camera streams
- Recording playback
- System configuration
- REST API for programmatic access
Key files:
src/web/mongoose_server.c
: Web server implementation using Mongoosesrc/web/api_handlers.c
: API request handlingsrc/web/api_handlers_*.c
: Specific API endpoint implementationsweb/
: HTML, CSS, JavaScript, and Preact components for the web interface
LightNVR is designed to be memory-efficient, with several strategies employed:
- Configurable buffer sizes to balance memory usage and performance
- Intelligent frame dropping when memory is constrained
- Priority-based resource allocation
- Pre-allocated memory pools for frequently used objects
- Avoids fragmentation from frequent allocations/deallocations
- Configurable pool sizes based on available system memory
- Optional swap file for additional virtual memory
- Configurable swap size
- Used for non-critical operations to free physical memory for stream processing
LightNVR uses a multi-threaded architecture to efficiently handle multiple streams:
- Main Thread: Application lifecycle, signal handling, and periodic tasks
- Stream Threads: One thread per active stream for receiving and processing video
- Recording Threads: Separate threads for writing recordings to disk
- Web Server Thread: Handles HTTP requests for the web interface
- Thread Pool: For handling API requests and other tasks
Thread synchronization is handled using mutexes and condition variables to ensure thread safety while minimizing contention.
- Stream connection is established (RTSP/ONVIF)
- Frames are received and decoded
- Frames are processed (optional: motion detection, analytics)
- Frames are buffered for live viewing
- If recording is enabled, frames are sent to the recording subsystem
- Recording subsystem writes frames to disk in the configured format (MP4/HLS)
- User accesses web interface via browser
- Web server authenticates the user (if enabled)
- Web server serves the appropriate HTML/CSS/JS files
- Client-side JavaScript makes API requests to fetch data
- API handlers process requests and return JSON responses
- For live viewing, HLS or MJPEG streams are served
LightNVR uses SQLite for data storage with the following main tables:
Stores stream configuration:
CREATE TABLE streams (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
url TEXT NOT NULL,
enabled INTEGER NOT NULL,
width INTEGER NOT NULL,
height INTEGER NOT NULL,
fps INTEGER NOT NULL,
codec TEXT NOT NULL,
priority INTEGER NOT NULL,
record INTEGER NOT NULL,
segment_duration INTEGER NOT NULL
);
Stores recording metadata:
CREATE TABLE recordings (
id INTEGER PRIMARY KEY,
stream_id INTEGER NOT NULL,
start_time INTEGER NOT NULL,
end_time INTEGER NOT NULL,
duration INTEGER NOT NULL,
size INTEGER NOT NULL,
format TEXT NOT NULL,
path TEXT NOT NULL,
FOREIGN KEY (stream_id) REFERENCES streams(id)
);
Stores system settings:
CREATE TABLE settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
Stores user authentication information:
CREATE TABLE users (
username TEXT PRIMARY KEY,
password_hash TEXT NOT NULL,
salt TEXT NOT NULL,
role TEXT NOT NULL
);
The LightNVR API follows RESTful principles:
- Resources are identified by URLs
- Standard HTTP methods (GET, POST, PUT, DELETE) for CRUD operations
- JSON for data exchange using cJSON library
- Authentication via HTTP Basic Auth
- Proper status codes for success/error conditions
See API.md for detailed API documentation.
The frontend uses modern web technologies:
- Tailwind CSS for styling and responsive design
- Preact for component-based UI development
- Modular JavaScript for better organization and maintainability
Key components:
web/js/components/preact/
: Preact components for different viewsweb/css/
: Tailwind CSS stylesheetsweb/js/
: JavaScript modules and utilities
The configuration system uses a simple key-value format:
- Configuration is loaded from a file at startup
- Default values are provided for all settings
- Configuration can be updated via the API
- Changes are persisted to the database
- Some settings require a restart to take effect
See CONFIGURATION.md for detailed configuration documentation.
The Ingenic A1 SoC has only 256MB of RAM, requiring specific optimizations:
- Staggered Initialization: Streams are initialized one at a time to prevent memory spikes
- Reduced Buffer Sizes: Default buffer sizes are reduced for memory-constrained environments
- Frame Dropping: Intelligent frame dropping when memory is low
- Resolution Limiting: Automatic downscaling of high-resolution streams
- Swap Support: Optional swap file for additional virtual memory
- Priority System: Ensures critical streams get resources when memory is constrained
LightNVR implements a robust shutdown coordination system to ensure clean and orderly shutdown of all components:
The shutdown coordination system follows a priority-based approach to ensure components shut down in the correct dependency order:
- Detection Threads (highest priority - 100): Shut down first since they depend on both MP4 writers and HLS streaming
- MP4 Writers (medium priority - 80): Shut down second since they depend on HLS streaming
- HLS Streaming Threads (lowest priority - 60): Shut down last as they are the foundation
-
Shutdown Coordinator (
include/core/shutdown_coordinator.h
andsrc/core/shutdown_coordinator.c
)- Centralized management of component registration and shutdown sequence
- Atomic operations for thread safety with minimal mutex usage
- Component state tracking during shutdown
- Priority-based shutdown sequencing
- Timeout mechanism to prevent hanging
-
Component Integration
- Components register with the coordinator during initialization
- Components check for shutdown signals in their main loops
- Components update their state when exiting
- Coordinator tracks component states during shutdown
- Main process initiates shutdown (via signal handler or user request)
- Coordinator sets shutdown flag and notifies components in priority order
- Components check shutdown flag in their main loops and begin cleanup
- Components release shared resources and update their state
- Coordinator waits for all components to stop (with timeout)
- Main process performs final cleanup when all components are stopped
This system prevents race conditions, deadlocks, and memory corruption during shutdown by ensuring components are stopped in the correct order and resources are properly released.
LightNVR is designed to be robust and self-healing:
- Stream Reconnection: Automatically reconnects to streams after network issues
- Watchdog Timer: Monitors system health and restarts components if necessary
- Graceful Degradation: Reduces functionality rather than crashing when resources are constrained
- Safe Shutdown: Ensures recordings are properly finalized during shutdown
- Crash Recovery: Recovers state from database after unexpected shutdowns
LightNVR implements several security measures:
- Authentication: Optional HTTP Basic Auth for web interface and API
- Password Hashing: Passwords are stored as salted hashes
- Input Validation: All user input is validated to prevent injection attacks
- Resource Limiting: Rate limiting to prevent DoS attacks
- Minimal Dependencies: Reduces attack surface by minimizing external dependencies
Planned architectural improvements:
- Plugin System: Allow extending functionality through plugins
- Clustering: Support for distributed operation across multiple nodes
- Hardware Acceleration: Better support for hardware-accelerated video processing
- Event System: More sophisticated event handling and notifications
- Analytics Integration: Support for video analytics and AI-based detection