diff --git a/main.go b/main.go
index b7d4fb3..dc007b0 100644
--- a/main.go
+++ b/main.go
@@ -57,6 +57,11 @@ func main() {
app.go2rtc = go2rtc
}
+ // Start snapshot engine for all enabled cameras.
+ snaps := NewSnapshotEngine(cfg.Storage)
+ snaps.StartAll(cfg.Cameras)
+ app.snapshots = snaps
+
// Start the HTTP server (blocks).
errCh := make(chan error, 1)
go func() {
@@ -104,6 +109,7 @@ type App struct {
ConfigPath string
server *Server
go2rtc *Go2RTCManager
+ snapshots *SnapshotEngine
}
// StartServer initializes and starts the HTTP server.
@@ -118,6 +124,9 @@ func (a *App) StartServer() error {
// Shutdown performs a graceful shutdown of all services.
func (a *App) Shutdown() {
+ if a.snapshots != nil {
+ a.snapshots.StopAll()
+ }
if a.go2rtc != nil {
a.go2rtc.Stop()
}
diff --git a/public/app.js b/public/app.js
index 14cd9b9..16db46a 100644
--- a/public/app.js
+++ b/public/app.js
@@ -64,7 +64,6 @@ async function loadCameras() {
function renderLiveGrid() {
const grid = document.getElementById('grid');
grid.innerHTML = '';
- const tiles = [];
for (let i = 0; i < 8; i++) {
const cam = cameras[i];
const tile = document.createElement('div');
@@ -72,38 +71,29 @@ function renderLiveGrid() {
tile.dataset.camId = cam ? cam.id : '';
if (cam && cam.enabled) {
- const snapshotURL = `http://${location.hostname}:1984/api/frame.jpeg?src=${cam.id}_sub`;
+ // Static snapshot from disk — updated every 2s by the backend.
+ // Cache-bust with timestamp to force refresh.
+ const snapURL = `/recordings/snapshots/${cam.id}.jpg?t=${Date.now()}`;
tile.innerHTML = `
-
+
${cam.name}
`;
+ // Auto-refresh every 3 seconds — no flooding, simple reload.
+ setInterval(() => {
+ const img = tile.querySelector('img');
+ if (img && !tile.classList.contains('offline')) {
+ img.src = `/recordings/snapshots/${cam.id}.jpg?t=${Date.now()}`;
+ }
+ }, 3000);
tile.addEventListener('click', () => openFocus(cam));
- tiles.push({ tile, url: snapshotURL, cam });
} else {
tile.innerHTML = 'No Camera';
}
grid.appendChild(tile);
}
-
- // Stagger snapshot loading — one every 300ms to avoid flooding go2rtc.
- let idx = 0;
- function loadNext() {
- if (idx >= tiles.length) return;
- const { tile, url } = tiles[idx];
- const img = tile.querySelector('img');
- if (img) {
- img.src = url + '&t=' + Date.now();
- // Refresh this tile every 3 seconds (staggered per camera).
- setInterval(() => {
- img.src = url + '&t=' + Date.now();
- }, 3000 + idx * 200);
- }
- idx++;
- setTimeout(loadNext, 300);
- }
- loadNext();
}
// ── Focus Overlay ──
diff --git a/snapshot.go b/snapshot.go
new file mode 100644
index 0000000..97d5132
--- /dev/null
+++ b/snapshot.go
@@ -0,0 +1,113 @@
+// NextNVR v0.3.2 — Snapshot engine
+// Grabs a single JPEG frame from each camera every 2 seconds.
+// Writes to /mnt/recordings/snapshots/{cam_id}.jpg via atomic rename.
+// The web UI loads these static images — no go2rtc polling, no CORS, no flooding.
+package main
+
+import (
+ "fmt"
+ "log"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "sync"
+ "time"
+)
+
+// SnapshotEngine manages per-camera snapshot goroutines.
+type SnapshotEngine struct {
+ mu sync.Mutex
+ stopChs map[string]chan struct{}
+ config StorageConfig
+}
+
+// NewSnapshotEngine creates a new snapshot engine.
+func NewSnapshotEngine(cfg StorageConfig) *SnapshotEngine {
+ return &SnapshotEngine{
+ stopChs: make(map[string]chan struct{}),
+ config: cfg,
+ }
+}
+
+// StartAll launches a snapshot goroutine for each enabled camera.
+func (se *SnapshotEngine) StartAll(cameras []CameraConfig) {
+ outDir := filepath.Join(se.config.RecordingsPath, "snapshots")
+ if err := os.MkdirAll(outDir, 0755); err != nil {
+ log.Printf("snapshot: mkdir %s failed: %v", outDir, err)
+ return
+ }
+
+ for _, cam := range cameras {
+ if !cam.Enabled {
+ continue
+ }
+ stopCh := make(chan struct{})
+ se.mu.Lock()
+ se.stopChs[cam.ID] = stopCh
+ se.mu.Unlock()
+ go se.snapshotLoop(cam, outDir, stopCh)
+ }
+ log.Printf("snapshot: %d cameras started → %s", len(se.stopChs), outDir)
+}
+
+// StopAll terminates all snapshot goroutines.
+func (se *SnapshotEngine) StopAll() {
+ se.mu.Lock()
+ defer se.mu.Unlock()
+ for id, ch := range se.stopChs {
+ close(ch)
+ log.Printf("snapshot: stopped camera %s", id)
+ }
+ se.stopChs = make(map[string]chan struct{})
+}
+
+// snapshotLoop grabs a JPEG frame every 2 seconds and writes it atomically.
+func (se *SnapshotEngine) snapshotLoop(cam CameraConfig, outDir string, stopCh chan struct{}) {
+ rtspURL := cam.RTSPSub
+ if rtspURL == "" {
+ rtspURL = fmt.Sprintf("rtsp://%s:%s@%s:554/Streaming/Channels/102",
+ cam.Username, cam.Password, cam.IP)
+ }
+
+ outFile := filepath.Join(outDir, cam.ID+".jpg")
+ tmpFile := outFile + ".tmp"
+ interval := 2 * time.Second
+
+ log.Printf("snapshot: %s → %s (every %v)", cam.ID, outFile, interval)
+
+ // Immediately grab the first frame.
+ se.grabFrame(rtspURL, tmpFile, outFile, cam.ID)
+
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-stopCh:
+ return
+ case <-ticker.C:
+ se.grabFrame(rtspURL, tmpFile, outFile, cam.ID)
+ }
+ }
+}
+
+// grabFrame launches ffmpeg to capture a single JPEG frame.
+func (se *SnapshotEngine) grabFrame(rtspURL, tmpFile, outFile, camID string) {
+ cmd := exec.Command("ffmpeg",
+ "-hide_banner", "-loglevel", "error",
+ "-rtsp_transport", "tcp",
+ "-i", rtspURL,
+ "-vframes", "1", // exactly one frame
+ "-q:v", "5", // good JPEG quality (2-31, lower=better)
+ "-f", "image2",
+ "-y", // overwrite
+ tmpFile,
+ )
+
+ cmd.Run() // ignore errors — camera may be offline
+
+ // Atomic rename: if ffmpeg succeeded, tmpFile exists.
+ if _, err := os.Stat(tmpFile); err == nil {
+ os.Rename(tmpFile, outFile)
+ }
+}