Compare commits

...
Author SHA1 Message Date
Josh Hawkins 0c93ccbc7d docstring 2026-11-23 15:54:57 -06:00
Josh Hawkins 565328499c keep event cleanup running and fix storage usage keys
- Event cleanup ran with no exception handling inside its loop, so one error (a camera added or removed while it iterated the shared cameras dict, a DB error, a thumbnail unlink failure) ended event and snapshot retention until restart. Each cycle is now guarded, camera iterations use a snapshot, and thumbnail unlink errors are caught
- Camera keys were captured once at startup, so a camera added at runtime also matched the removed-camera branch and its events could expire early under the global retention. The keys are refreshed each cycle and the removed-camera label cache resets when they change
- Clip expiry had no has_clip filter and redid every past expiration each cycle. The queries now skip events already expired, and the dead clip unlink block is removed
- Storage usage was keyed by friendly name, so cameras sharing one merged into a single row. It is keyed by camera id and the storage graph resolves the display name
2026-11-23 15:54:35 -06:00
Josh HawkinsandGitHub d20d6dcf72 Bound per-request work in a few endpoints (#25068)
CI / AMD64 Smoke Test (push) Blocked by required conditions
CI / ARM Build (push) Waiting to run
CI / Jetson Jetpack 6 (push) Waiting to run
CI / AMD64 Build (push) Waiting to run
CI / AMD64 Extra Build (push) Blocked by required conditions
CI / ARM Extra Build (push) Blocked by required conditions
CI / Synaptics Build (push) Blocked by required conditions
CI / Assemble and push default build (push) Blocked by required conditions
* bound per-request work in recordings, image, password and motion search endpoints

- /recordings/unavailable walked the requested span one scale bucket at a time on the event loop, so a huge or non-finite range hung the whole API, including /auth. It now walks the gaps between recordings and rejects non-finite bounds.
- latest, mjpeg, event snapshot and recording snapshot heights are capped at the source frame height, and recording frame grabs time out after 30 s.
- Password verify and hash run in a worker thread, so a password change no longer freezes the API while PBKDF2 runs.
- Motion search collected every decoded frame of a run before detecting, up to about 190 MB per run. Frames now stream through detection, and keyframe mode stops reading at the probed keyframe count before falling back to cadence.

* keep password hashing on the event loop

* run recording deletion off the event loop
2026-11-23 14:16:43 -07:00
13 changed files with 421 additions and 184 deletions
@@ -9,8 +9,8 @@ class MediaRecordingsSummaryQueryParams(BaseModel):
class MediaRecordingsAvailabilityQueryParams(BaseModel):
cameras: str = "all"
before: float | SkipJsonSchema[None] = None
after: float | SkipJsonSchema[None] = None
before: float | SkipJsonSchema[None] = Field(default=None, allow_inf_nan=False)
after: float | SkipJsonSchema[None] = Field(default=None, allow_inf_nan=False)
scale: int = Field(default=30, ge=1)
+8 -5
View File
@@ -166,10 +166,13 @@ def imagestream(
time.sleep(1 / fps)
frame = detected_frames_processor.get_current_frame(camera_name, draw_options)
if frame is None:
frame = np.zeros((height, int(height * 16 / 9), 3), np.uint8)
frame = np.zeros((360, 640, 3), np.uint8)
width = int(height * frame.shape[1] / frame.shape[0])
frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_LINEAR)
frame_height = min(height, frame.shape[0])
width = int(frame_height * frame.shape[1] / frame.shape[0])
frame = cv2.resize(
frame, dsize=(width, frame_height), interpolation=cv2.INTER_LINEAR
)
ret, jpg = cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), 70])
yield (
@@ -278,7 +281,7 @@ async def latest_frame(
status_code=500,
)
height = int(params.height or str(frame.shape[0]))
height = min(params.height or frame.shape[0], frame.shape[0])
width = int(height * frame.shape[1] / frame.shape[0])
if height < 1 or width < 1:
@@ -320,7 +323,7 @@ async def latest_frame(
frame = cv2.cvtColor(frame, cv2.COLOR_YUV2BGR_I420)
height = int(params.height or str(frame.shape[0]))
height = min(params.height or frame.shape[0], frame.shape[0])
width = int(height * frame.shape[1] / frame.shape[0])
frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_AREA)
+29 -35
View File
@@ -2,6 +2,7 @@
import datetime as dt
import logging
import math
from datetime import datetime, timedelta
from functools import reduce
from pathlib import Path
@@ -443,45 +444,38 @@ async def no_recordings(
else:
covered.append((rec_start, rec_end))
# Iterate through time segments and check if each has any recording
no_recording_segments = []
current = after
current_gap_start = None
idx = 0
covered_count = len(covered)
# A scale-sized bucket counts as empty when it fits inside a gap between
# covered intervals. Walking the gaps keeps the work proportional to the
# recordings found rather than to the requested span.
bucket_count = math.ceil((before - after) / scale)
gaps: list[list[float]] = []
free_start = -math.inf
while current < before:
segment_end = min(current + scale, before)
for rec_start, rec_end in covered + [(math.inf, math.inf)]:
first = 0 if free_start <= after else math.ceil((free_start - after) / scale)
# Advance past covered intervals that end before this segment begins;
# they cannot overlap this or any later segment.
while idx < covered_count and covered[idx][1] <= current:
idx += 1
# A covered interval overlaps the segment when it starts before the
# segment ends (its end is already known to be > current).
has_recording = idx < covered_count and covered[idx][0] < segment_end
if not has_recording:
# This segment has no recordings
if current_gap_start is None:
current_gap_start = current # Start a new gap
if rec_start >= before:
last = bucket_count - 1
else:
# This segment has recordings
if current_gap_start is not None:
# End the current gap and append it
no_recording_segments.append(
{"start_time": int(current_gap_start), "end_time": int(current)}
)
current_gap_start = None
last = min(math.floor((rec_start - after) / scale), bucket_count) - 1
current = segment_end
if first <= last:
gap_start = after + first * scale
gap_end = before if last == bucket_count - 1 else after + (last + 1) * scale
# Append the last gap if it exists
if current_gap_start is not None:
no_recording_segments.append(
{"start_time": int(current_gap_start), "end_time": int(before)}
)
if gaps and gaps[-1][1] == gap_start:
gaps[-1][1] = gap_end
else:
gaps.append([gap_start, gap_end])
free_start = rec_end
if free_start >= before:
break
no_recording_segments = [
{"start_time": int(gap_start), "end_time": int(gap_end)}
for gap_start, gap_end in gaps
]
return JSONResponse(content=no_recording_segments)
@@ -495,7 +489,7 @@ async def no_recordings(
Recordings can be filtered by cameras and kept based on motion, objects, or audio attributes.
""",
)
async def delete_recordings(
def delete_recordings(
start: float = PathParam(..., description="Start timestamp (unix)"),
end: float = PathParam(..., description="End timestamp (unix)"),
params: RecordingsDeleteQueryParams = Depends(),
+61 -80
View File
@@ -2,14 +2,11 @@
import datetime
import logging
import os
import threading
from multiprocessing.synchronize import Event as MpEvent
from pathlib import Path
from typing import Any
from frigate.config import FrigateConfig
from frigate.const import CLIPS_DIR
from frigate.db.sqlitevecq import SqliteVecQueueDatabase
from frigate.models import Event, Timeline
from frigate.util.file import delete_event_snapshot, delete_event_thumbnail
@@ -143,7 +140,7 @@ class EventCleanup(threading.Thread):
events_to_update = []
## Expire events from cameras based on the camera config
for name, camera in self.config.cameras.items():
for name, camera in list(self.config.cameras.items()):
retain_config = camera.snapshots.retain
# get distinct objects in database for this camera
@@ -205,54 +202,18 @@ class EventCleanup(threading.Thread):
self.config.record.effective_alert_days,
self.config.record.effective_detection_days,
)
file_extension = None # mp4 clips are no longer stored in /clips
update_params = {"has_clip": False}
# get expiration time for this label
expire_after = (
datetime.datetime.now() - datetime.timedelta(days=expire_days)
).timestamp()
# grab all events after specific time
expired_events: list[Event] = list(
Event.select(
Event.id,
Event.camera,
)
.where(
Event.camera.not_in(self.camera_keys),
Event.start_time < expire_after,
Event.retain_indefinitely == False,
)
.namedtuples()
.iterator()
)
logger.debug(f"{len(expired_events)} events can be expired")
# delete the media from disk
for expired in expired_events:
media_name = f"{expired.camera}-{expired.id}"
media_path = Path(f"{os.path.join(CLIPS_DIR, media_name)}.{file_extension}")
try:
media_path.unlink(missing_ok=True)
if file_extension == "jpg":
media_path = Path( # type: ignore[unreachable]
f"{os.path.join(CLIPS_DIR, media_name)}-clean.webp"
)
media_path.unlink(missing_ok=True)
# Also delete clean.png (legacy) for backward compatibility
media_path = Path(
f"{os.path.join(CLIPS_DIR, media_name)}-clean.png"
)
media_path.unlink(missing_ok=True)
except OSError as e:
logger.warning(f"Unable to delete event images: {e}")
# update the clips attribute for the db entry
query = Event.select(Event.id).where(
Event.camera.not_in(self.camera_keys),
Event.start_time < expire_after,
Event.retain_indefinitely == False,
Event.has_clip == True,
)
events_to_update = []
@@ -280,7 +241,7 @@ class EventCleanup(threading.Thread):
now = datetime.datetime.now()
## Expire events from cameras based on the camera config
for name, camera in self.config.cameras.items():
for name, camera in list(self.config.cameras.items()):
# effective days cover the sub window, keeping tracked objects
# in Explore while sub recordings and review items still exist
alert_expire_date = (
@@ -298,6 +259,7 @@ class EventCleanup(threading.Thread):
.where(
Event.camera == name,
Event.retain_indefinitely == False,
Event.has_clip == True,
(
(
(Event.data["max_severity"] != "detection")
@@ -335,43 +297,62 @@ class EventCleanup(threading.Thread):
# only expire events every 5 minutes
while not self.stop_event.wait(300):
events_with_expired_clips = self.expire_clips()
# delete timeline entries for events that have expired recordings
# delete up to 100,000 at a time
max_deletes = 100000
deleted_events_list = list(events_with_expired_clips)
for i in range(0, len(deleted_events_list), max_deletes):
Timeline.delete().where(
Timeline.source_id << deleted_events_list[i : i + max_deletes]
).execute()
self.expire_snapshots()
# drop events from db where has_clip and has_snapshot are false
events = (
Event.select()
.where(Event.has_clip == False, Event.has_snapshot == False)
.iterator()
)
events_to_delete: list[Event] = [e for e in events]
for e in events_to_delete:
delete_event_thumbnail(e)
logger.debug(f"Found {len(events_to_delete)} events that can be expired")
if len(events_to_delete) > 0:
ids_to_delete = [str(e.id) for e in events_to_delete]
for i in range(0, len(ids_to_delete), CHUNK_SIZE):
chunk = ids_to_delete[i : i + CHUNK_SIZE]
logger.debug(f"Deleting {len(chunk)} events from the database")
Event.delete().where(Event.id << chunk).execute()
Timeline.delete().where(Timeline.source_id << chunk).execute()
# embeddings are always cleaned up, even when semantic search
# is disabled, so that they don't outlive their events
self.db.delete_embeddings_description(event_ids=chunk)
self.db.delete_embeddings_thumbnail(event_ids=chunk)
logger.debug(f"Deleted {len(chunk)} embeddings")
try:
self.expire_events()
except Exception:
logger.exception("Event cleanup failed, retrying next cycle")
logger.info("Exiting event cleanup...")
def refresh_camera_keys(self) -> None:
"""Track cameras added or removed at runtime."""
camera_keys = list(self.config.cameras)
if set(camera_keys) != set(self.camera_keys):
self.camera_keys = camera_keys
self.removed_camera_labels = None
def expire_events(self) -> None:
"""Run one cleanup cycle: expire clips and snapshots, then drop dead events."""
self.refresh_camera_keys()
events_with_expired_clips = self.expire_clips()
# delete timeline entries for events that have expired recordings
# delete up to 100,000 at a time
max_deletes = 100000
deleted_events_list = list(events_with_expired_clips)
for i in range(0, len(deleted_events_list), max_deletes):
Timeline.delete().where(
Timeline.source_id << deleted_events_list[i : i + max_deletes]
).execute()
self.expire_snapshots()
# drop events from db where has_clip and has_snapshot are false
events = (
Event.select()
.where(Event.has_clip == False, Event.has_snapshot == False)
.iterator()
)
events_to_delete: list[Event] = [e for e in events]
for e in events_to_delete:
if not delete_event_thumbnail(e):
logger.warning(
f"Unable to delete event thumbnail for {e.camera}: {e.id}"
)
logger.debug(f"Found {len(events_to_delete)} events that can be expired")
if len(events_to_delete) > 0:
ids_to_delete = [str(e.id) for e in events_to_delete]
for i in range(0, len(ids_to_delete), CHUNK_SIZE):
chunk = ids_to_delete[i : i + CHUNK_SIZE]
logger.debug(f"Deleting {len(chunk)} events from the database")
Event.delete().where(Event.id << chunk).execute()
Timeline.delete().where(Timeline.source_id << chunk).execute()
# embeddings are always cleaned up, even when semantic search
# is disabled, so that they don't outlive their events
self.db.delete_embeddings_description(event_ids=chunk)
self.db.delete_embeddings_thumbnail(event_ids=chunk)
logger.debug(f"Deleted {len(chunk)} embeddings")
+46 -49
View File
@@ -6,8 +6,10 @@ import threading
import time
from collections.abc import Callable, Generator, Iterable
from concurrent.futures import Future, ThreadPoolExecutor, as_completed
from contextlib import closing
from dataclasses import asdict, dataclass, field
from datetime import datetime
from itertools import islice
from typing import Any
import cv2
@@ -611,24 +613,49 @@ class MotionSearchRunner(threading.Thread):
def _detect_with_progress(
self,
indexed_frames: list[tuple[int, np.ndarray]],
frames: Iterable[np.ndarray],
timestamp_fn: Callable[[int], float],
) -> list[MotionSearchResult]:
"""Run detection while firing throttled progress as frames are scanned."""
) -> tuple[list[MotionSearchResult], int]:
"""Run detection while firing throttled progress as frames are scanned.
Returns ``(results, frame_count)``.
"""
frame_count = 0
def _gen() -> Generator[tuple[int, np.ndarray], None, None]:
for i, frame in indexed_frames:
nonlocal frame_count
for i, frame in enumerate(frames):
frame_count = i + 1
if not self._should_stop():
self._emit_progress(timestamp_fn(i))
yield i, frame
return detect_motion_scaled(
results = detect_motion_scaled(
_gen(),
self.scaled_mask,
self.job.threshold,
self.job.min_area,
timestamp_fn,
)
return results, frame_count
def _decode_vod(
self, vod_url: str, keyframes: bool
) -> Generator[np.ndarray, None, None]:
return iter_vod_frames(
self.ffmpeg_path,
vod_url,
self.scaled[0],
self.scaled[1],
self.channels,
self.decode_args,
self.crop,
self.scaled,
True,
self._should_stop,
skip_nonkey=keyframes,
fps_rate=None if keyframes else self.fps_rate,
)
def _process_run(
self, run: list[Recordings]
@@ -639,7 +666,8 @@ class MotionSearchRunner(threading.Thread):
are all decoded anyway) paired with its probed PTS; if the decoded and
probed counts disagree (the decoder ignored ``-skip_frame nokey`` or the
stream is corrupt) this run re-runs in the fixed-cadence fallback.
Returns ``(results, frame_count)``.
Frames stream through detection, so a run never holds more than the
current and previous frame. Returns ``(results, frame_count)``.
"""
run_start: float = run[0].start_time # type: ignore[assignment]
run_end: float = run[-1].end_time # type: ignore[assignment]
@@ -650,35 +678,21 @@ class MotionSearchRunner(threading.Thread):
kf_pts = probe_vod_keyframe_pts(
self.ffprobe_path, vod_url, self._should_stop
)
frames = list(
iter_vod_frames(
self.ffmpeg_path,
vod_url,
self.scaled[0],
self.scaled[1],
self.channels,
self.decode_args,
self.crop,
self.scaled,
True,
self._should_stop,
skip_nonkey=True,
fps_rate=None,
)
)
if kf_pts and len(frames) == len(kf_pts):
if kf_pts:
abs_times = [stream_time_to_absolute(time_map, p) for p in kf_pts]
indexed = list(enumerate(frames))
def _ts_kf(i: int) -> float:
return abs_times[i]
with closing(self._decode_vod(vod_url, keyframes=True)) as frames:
results, frame_count = self._detect_with_progress(
islice(frames, len(abs_times)), abs_times.__getitem__
)
extra_frames = next(frames, None) is not None
results = self._detect_with_progress(indexed, _ts_kf)
return results, len(frames)
if frame_count == len(abs_times) and not extra_frames:
return results, frame_count
logger.debug(
"Keyframe count mismatch (%d decoded vs %d probed), using cadence",
len(frames),
"Keyframe decode did not match %d probed keyframes, using cadence",
len(kf_pts),
)
@@ -688,29 +702,12 @@ class MotionSearchRunner(threading.Thread):
self, vod_url: str, time_map: list[tuple[float, float, float]]
) -> tuple[list[MotionSearchResult], int]:
"""Fixed-cadence fallback: fps-filtered VOD decode, evenly spaced times."""
frames = list(
iter_vod_frames(
self.ffmpeg_path,
vod_url,
self.scaled[0],
self.scaled[1],
self.channels,
self.decode_args,
self.crop,
self.scaled,
True,
self._should_stop,
skip_nonkey=False,
fps_rate=self.fps_rate,
)
)
indexed = list(enumerate(frames))
def _ts_fps(i: int) -> float:
return stream_time_to_absolute(time_map, i / self.fps_rate)
results = self._detect_with_progress(indexed, _ts_fps)
return results, len(frames)
with closing(self._decode_vod(vod_url, keyframes=False)) as frames:
return self._detect_with_progress(frames, _ts_fps)
def _merge_run(
self,
+3 -6
View File
@@ -137,7 +137,7 @@ class StorageMaintainer(threading.Thread):
def calculate_camera_bandwidth(self) -> None:
"""Calculate an average MB/hr for each camera."""
for camera in self.config.cameras.keys():
for camera in list(self.config.cameras):
# Skip replay cameras
if camera.startswith(REPLAY_CAMERA_PREFIX):
continue
@@ -186,7 +186,7 @@ class StorageMaintainer(threading.Thread):
"""Calculate the storage usage of each camera."""
usages: dict[str, dict] = {}
for camera in self.config.cameras.keys():
for camera in list(self.config.cameras):
# Skip replay cameras
if camera.startswith(REPLAY_CAMERA_PREFIX):
continue
@@ -208,10 +208,7 @@ class StorageMaintainer(threading.Thread):
"bandwidth_by_stream", {}
)
camera_key = (
getattr(self.config.cameras[camera], "friendly_name", None) or camera
)
usages[camera_key] = {
usages[camera] = {
"usage": sum(stream_usages.values()),
"bandwidth": self.camera_storage_stats.get(camera, {}).get(
"bandwidth", 0
+44 -1
View File
@@ -4,9 +4,11 @@ import threading
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from unittest.mock import patch
from unittest.mock import MagicMock, patch
from zoneinfo import ZoneInfo
import cv2
import numpy as np
from fastapi import Request
from frigate.api.auth import get_allowed_cameras_for_filter, get_current_user
@@ -588,6 +590,47 @@ class TestHttpMedia(BaseTestHttp):
response = client.get("/recordings/unavailable", params={"scale": 0})
assert response.status_code == 422
def test_recordings_unavailable_large_span(self):
"""A wide span at a fine scale returns its gaps without stepping per bucket."""
with AuthTestClient(self.app) as client:
self._insert_recording("only", 1000, 1100)
response = client.get(
"/recordings/unavailable",
params={"after": 1, "before": 10**12, "scale": 1},
)
assert response.status_code == 200
assert response.json() == [
{"start_time": 1, "end_time": 1000},
{"start_time": 1100, "end_time": 10**12},
]
for param in ("before", "after"):
for bound in ("inf", "-inf", "nan"):
response = client.get(
"/recordings/unavailable", params={param: bound}
)
assert response.status_code == 422
def test_latest_frame_height_capped_at_source(self):
"""A requested height above the frame height returns the frame unscaled."""
frame = np.zeros((90, 160, 3), np.uint8)
processor = MagicMock()
processor.get_current_frame.return_value = frame
processor.get_current_frame_time.return_value = datetime.now().timestamp()
self.app.detected_frames_processor = processor
with AuthTestClient(self.app) as client:
for height, expected in ((45, (45, 80)), (5000, (90, 160))):
response = client.get(
"/front_door/latest.jpg", params={"height": height}
)
assert response.status_code == 200
image = cv2.imdecode(
np.frombuffer(response.content, np.uint8), cv2.IMREAD_COLOR
)
assert image.shape[:2] == expected
def test_recordings_summary_day_attribution_by_start_time(self):
"""
A recording spanning midnight marks only its start day.
+141
View File
@@ -0,0 +1,141 @@
"""Tests for the event cleanup cycle and runtime camera changes."""
import datetime
import unittest
from unittest.mock import MagicMock, patch
from peewee import SqliteDatabase
from frigate.config import FrigateConfig
from frigate.events.cleanup import EventCleanup
from frigate.models import Event, Timeline
from frigate.util.file import delete_event_thumbnail
def _camera(path: str, record_days: int) -> dict:
return {
"ffmpeg": {"inputs": [{"path": path, "roles": ["detect", "record"]}]},
"record": {
"enabled": True,
"alerts": {"retain": {"days": record_days}},
"detections": {"retain": {"days": record_days}},
},
}
class TestEventCleanup(unittest.TestCase):
def setUp(self):
self.db = SqliteDatabase(":memory:")
models = [Event, Timeline]
self.db.bind(models)
self.db.create_tables(models)
config = FrigateConfig(
**{
"mqtt": {"host": "mqtt"},
"record": {
"alerts": {"retain": {"days": 10}},
"detections": {"retain": {"days": 10}},
},
"cameras": {"front_door": _camera("rtsp://10.0.0.1:554/video", 10)},
}
)
self.config = config
self.cleanup = EventCleanup(config, MagicMock(), MagicMock())
def tearDown(self):
self.db.close()
def _insert_event(
self, id: str, camera: str, age_days: float, has_clip: bool = True
) -> None:
end_time = (
datetime.datetime.now() - datetime.timedelta(days=age_days)
).timestamp()
Event.create(
id=id,
label="person",
camera=camera,
start_time=end_time - 10,
end_time=end_time,
top_score=0.9,
score=0.9,
false_positive=False,
zones=[],
thumbnail="",
has_clip=has_clip,
has_snapshot=True,
region=[],
box=[],
area=0,
retain_indefinitely=False,
plus_id="",
model_hash="",
detector_type="cpu",
model_type="ssd",
data={"max_severity": "alert"},
)
def test_runtime_added_camera_keeps_its_own_retention(self):
added = FrigateConfig(
**{
"mqtt": {"host": "mqtt"},
"cameras": {"garage": _camera("rtsp://10.0.0.2:554/video", 30)},
}
).cameras["garage"]
self.config.cameras["garage"] = added
self._insert_event("garage-event", "garage", age_days=20)
self.cleanup.expire_events()
assert Event.get(Event.id == "garage-event").has_clip is True
def test_runtime_removed_camera_gets_global_retention(self):
self._insert_event("front-event", "front_door", age_days=20)
self.cleanup.camera_keys = ["front_door"]
self.cleanup.removed_camera_labels = []
del self.config.cameras["front_door"]
self.cleanup.expire_events()
# clip and snapshot both expire under the global retention
assert self.cleanup.camera_keys == []
assert not Event.select().where(Event.id == "front-event").exists()
def test_expired_clips_are_only_selected_once(self):
self._insert_event("pending", "front_door", age_days=20)
self._insert_event("expired", "front_door", age_days=20, has_clip=False)
self._insert_event("removed-pending", "removed", age_days=20)
self._insert_event("removed-expired", "removed", age_days=20, has_clip=False)
assert self.cleanup.expire_clips() == ["pending"]
assert not Event.select().where(Event.has_clip == True).exists()
with patch.object(Event, "update", wraps=Event.update) as update:
assert self.cleanup.expire_clips() == []
update.assert_not_called()
def test_cycle_failure_does_not_stop_the_thread(self):
self.cleanup.stop_event.wait.side_effect = [False, False, True]
with patch.object(
self.cleanup, "expire_events", side_effect=[RuntimeError, None]
) as expire_events:
self.cleanup.run()
assert expire_events.call_count == 2
def test_thumbnail_unlink_error_is_reported(self):
event = MagicMock(thumbnail="", camera="front_door", id="e1")
with patch(
"frigate.util.file.Path.unlink", side_effect=PermissionError
) as unlink:
assert delete_event_thumbnail(event) is False
unlink.assert_called_once()
if __name__ == "__main__":
unittest.main()
+30
View File
@@ -440,6 +440,36 @@ class TestHttp(unittest.TestCase):
assert usages["front_door"]["usage"] == 0
assert usages["front_door"]["streams"] == {}
def test_camera_usages_keyed_by_camera_id(self):
"""Cameras sharing a friendly name keep separate usage entries."""
self.double_cam_config["cameras"]["front_door"]["friendly_name"] = "Door"
self.double_cam_config["cameras"]["back_door"]["friendly_name"] = "Door"
config = FrigateConfig(**self.double_cam_config)
storage = StorageMaintainer(config, MagicMock())
time_keep = datetime.datetime.now().timestamp()
_insert_mock_recording(
"1234567.frontdoor",
os.path.join(self.test_dir, "front.tmp"),
time_keep,
time_keep + 10,
seg_size=20,
)
_insert_mock_recording(
"1234568.backdoor",
os.path.join(self.test_dir, "back.tmp"),
time_keep,
time_keep + 10,
camera="back_door",
seg_size=5,
)
storage.calculate_camera_bandwidth()
usages = storage.calculate_camera_usages()
assert usages["front_door"]["usage"] == 20
assert usages["back_door"]["usage"] == 5
def test_storage_cleanup(self):
"""Ensure that all recordings are cleaned up when necessary."""
config = FrigateConfig(**self.minimal_config)
+36
View File
@@ -0,0 +1,36 @@
import unittest
import cv2
import numpy as np
from frigate.util.image import get_snapshot_bytes
class TestSnapshotBytes(unittest.TestCase):
def snapshot_shape(self, height: int, crop: bool = False) -> tuple[int, int]:
jpg, _ = get_snapshot_bytes(
np.zeros((90, 160, 3), np.uint8),
0.0,
"jpg",
crop=crop,
height=height,
label="person",
box=(70, 35, 90, 55),
score=None,
area=None,
attributes=None,
color=(255, 255, 255),
)
image = cv2.imdecode(np.frombuffer(jpg, np.uint8), cv2.IMREAD_COLOR)
return image.shape[:2]
def test_height_capped_at_frame_height(self):
self.assertEqual(self.snapshot_shape(45), (45, 80))
self.assertEqual(self.snapshot_shape(5000), (90, 160))
def test_crop_can_scale_up_to_frame_height(self):
self.assertEqual(self.snapshot_shape(5000, crop=True)[0], 90)
if __name__ == "__main__":
unittest.main()
+6 -2
View File
@@ -262,11 +262,15 @@ def delete_event_snapshot(event: Event) -> bool:
def delete_event_thumbnail(event: Event) -> bool:
if event.thumbnail:
return True
else:
try:
Path(os.path.join(THUMB_DIR, event.camera, f"{event.id}.webp")).unlink(
missing_ok=True
)
return True
except OSError:
return False
return True
### Training Images
+9 -2
View File
@@ -458,6 +458,7 @@ def get_snapshot_bytes(
best_frame = best_frame[region[1] : region[3], region[0] : region[2]]
if height:
height = min(height, frame.shape[0])
width = int(height * best_frame.shape[1] / best_frame.shape[0])
best_frame = cv2.resize(
best_frame, dsize=(width, height), interpolation=cv2.INTER_AREA
@@ -1275,7 +1276,7 @@ def run_ffmpeg_snapshot(
if height is not None:
ffmpeg_cmd.insert(-3, "-vf")
ffmpeg_cmd.insert(-3, f"scale=-1:{height}")
ffmpeg_cmd.insert(-3, f"scale=-1:'min({height},ih)'")
try:
process = sp.run(
@@ -1298,11 +1299,17 @@ def get_image_from_recording(
relative_frame_time: float,
codec: str,
height: int | None = None,
timeout: int = 30,
) -> Any | None:
"""retrieve a frame from given time in recording file."""
image_data, _ = run_ffmpeg_snapshot(
ffmpeg, file_path, codec, seek_time=relative_frame_time, height=height
ffmpeg,
file_path,
codec,
seek_time=relative_frame_time,
height=height,
timeout=timeout,
)
return image_data
@@ -18,6 +18,9 @@ import {
} from "@/components/ui/popover";
import { getUnitSize } from "@/utils/storageUtil";
import { CameraStorage, StreamStorage } from "@/types/stats";
import { FrigateConfig } from "@/types/frigateConfig";
import { resolveCameraName } from "@/hooks/use-camera-friendly-name";
import useSWR from "swr";
import { CiCircleAlert } from "react-icons/ci";
import { useTranslation } from "react-i18next";
@@ -51,6 +54,7 @@ export function CombinedStorageGraph({
}: CombinedStorageGraphProps) {
const { t } = useTranslation(["views/system", "components/player"]);
const { data: config } = useSWR<FrigateConfig>("config");
const { theme, systemTheme } = useTheme();
const isDark = (systemTheme || theme) == "dark";
@@ -197,10 +201,10 @@ export function CombinedStorageGraph({
} else if (name == "Other") {
return t("label.other", { ns: "common" });
} else {
return name.replaceAll("_", " ");
return resolveCameraName(config, name);
}
},
[t],
[t, config],
);
const getStreamSplit = useCallback(