Compare commits

..
Author SHA1 Message Date
Josh Hawkins 297ec2ace9 start preview frame tests ahead of now 2026-11-23 12:37:15 -06:00
Josh Hawkins 550276e430 match preview frames to the exact camera
Current-hour preview frames were selected with a "preview_{camera}-" prefix match, so a camera whose name extends another with "-" (front and front-door, cam and cam-2) had its frames included in the other camera's frame listing, preview GIF and MP4, and preview export. The frames listing, the GIF and MP4 routes, and the preview export now filter with is_camera_preview_frame.
2026-11-23 12:30:18 -06:00
12 changed files with 239 additions and 185 deletions
+2 -7
View File
@@ -1,6 +1,5 @@
"""Auth apis."""
import asyncio
import base64
import hashlib
import ipaddress
@@ -1139,9 +1138,7 @@ async def update_password(
content={"message": "Current password is required"},
status_code=400,
)
if not await asyncio.to_thread(
verify_password, body.old_password, user.password_hash
):
if not verify_password(body.old_password, user.password_hash):
return JSONResponse(
content={"message": "Current password is incorrect"},
status_code=401,
@@ -1155,9 +1152,7 @@ async def update_password(
status_code=400,
)
password_hash = await asyncio.to_thread(
hash_password, body.password, iterations=HASH_ITERATIONS
)
password_hash = hash_password(body.password, iterations=HASH_ITERATIONS)
User.update(
{
User.password_hash: password_hash,
@@ -9,8 +9,8 @@ class MediaRecordingsSummaryQueryParams(BaseModel):
class MediaRecordingsAvailabilityQueryParams(BaseModel):
cameras: str = "all"
before: float | SkipJsonSchema[None] = Field(default=None, allow_inf_nan=False)
after: float | SkipJsonSchema[None] = Field(default=None, allow_inf_nan=False)
before: float | SkipJsonSchema[None] = None
after: float | SkipJsonSchema[None] = None
scale: int = Field(default=30, ge=1)
+11 -11
View File
@@ -47,7 +47,10 @@ from frigate.const import (
STREAM_TYPE_SUB,
)
from frigate.models import Event, Previews, Recordings, Regions, ReviewSegment
from frigate.output.preview import get_most_recent_preview_frame
from frigate.output.preview import (
get_most_recent_preview_frame,
is_camera_preview_frame,
)
from frigate.track.object_processing import TrackedObjectProcessor
from frigate.util.ffmpeg import terminate_ffmpeg_stream
from frigate.util.file import (
@@ -166,13 +169,10 @@ def imagestream(
time.sleep(1 / fps)
frame = detected_frames_processor.get_current_frame(camera_name, draw_options)
if frame is None:
frame = np.zeros((360, 640, 3), np.uint8)
frame = np.zeros((height, int(height * 16 / 9), 3), np.uint8)
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
)
width = int(height * frame.shape[1] / frame.shape[0])
frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_LINEAR)
ret, jpg = cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), 70])
yield (
@@ -281,7 +281,7 @@ async def latest_frame(
status_code=500,
)
height = min(params.height or frame.shape[0], frame.shape[0])
height = int(params.height or str(frame.shape[0]))
width = int(height * frame.shape[1] / frame.shape[0])
if height < 1 or width < 1:
@@ -323,7 +323,7 @@ async def latest_frame(
frame = cv2.cvtColor(frame, cv2.COLOR_YUV2BGR_I420)
height = min(params.height or frame.shape[0], frame.shape[0])
height = int(params.height or str(frame.shape[0]))
width = int(height * frame.shape[1] / frame.shape[0])
frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_AREA)
@@ -1606,7 +1606,7 @@ async def preview_gif(
camera_files = [
entry.name
for entry in os.scandir(preview_dir)
if entry.name.startswith(file_start)
if is_camera_preview_frame(entry.name, camera_name)
]
camera_files.sort()
@@ -1797,7 +1797,7 @@ async def preview_mp4(
camera_files = [
entry.name
for entry in os.scandir(preview_dir)
if entry.name.startswith(file_start)
if is_camera_preview_frame(entry.name, camera_name)
]
camera_files.sort()
+2 -1
View File
@@ -22,6 +22,7 @@ from frigate.api.defs.response.preview_response import (
from frigate.api.defs.tags import Tags
from frigate.const import BASE_DIR, CACHE_DIR, PREVIEW_FRAME_TYPE
from frigate.models import Previews
from frigate.output.preview import is_camera_preview_frame
from frigate.util.time import get_normalized_tz_name
logger = logging.getLogger(__name__)
@@ -187,7 +188,7 @@ def get_preview_frames_from_cache(camera_name: str, start_ts: float, end_ts: flo
left = bisect.bisect_left(files, start_file)
right = bisect.bisect_right(files, end_file)
selected_previews = [
file for file in files[left:right] if file.startswith(file_start)
file for file in files[left:right] if is_camera_preview_frame(file, camera_name)
]
return JSONResponse(
+34 -28
View File
@@ -2,7 +2,6 @@
import datetime as dt
import logging
import math
from datetime import datetime, timedelta
from functools import reduce
from pathlib import Path
@@ -444,38 +443,45 @@ async def no_recordings(
else:
covered.append((rec_start, rec_end))
# 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
# 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)
for rec_start, rec_end in covered + [(math.inf, math.inf)]:
first = 0 if free_start <= after else math.ceil((free_start - after) / scale)
while current < before:
segment_end = min(current + scale, before)
if rec_start >= before:
last = bucket_count - 1
# 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
else:
last = min(math.floor((rec_start - after) / scale), bucket_count) - 1
# 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
if first <= last:
gap_start = after + first * scale
gap_end = before if last == bucket_count - 1 else after + (last + 1) * scale
current = segment_end
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
]
# 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)}
)
return JSONResponse(content=no_recording_segments)
+49 -46
View File
@@ -6,10 +6,8 @@ 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
@@ -613,49 +611,24 @@ class MotionSearchRunner(threading.Thread):
def _detect_with_progress(
self,
frames: Iterable[np.ndarray],
indexed_frames: list[tuple[int, np.ndarray]],
timestamp_fn: Callable[[int], float],
) -> tuple[list[MotionSearchResult], int]:
"""Run detection while firing throttled progress as frames are scanned.
Returns ``(results, frame_count)``.
"""
frame_count = 0
) -> list[MotionSearchResult]:
"""Run detection while firing throttled progress as frames are scanned."""
def _gen() -> Generator[tuple[int, np.ndarray], None, None]:
nonlocal frame_count
for i, frame in enumerate(frames):
frame_count = i + 1
for i, frame in indexed_frames:
if not self._should_stop():
self._emit_progress(timestamp_fn(i))
yield i, frame
results = detect_motion_scaled(
return 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]
@@ -666,8 +639,7 @@ 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.
Frames stream through detection, so a run never holds more than the
current and previous frame. Returns ``(results, frame_count)``.
Returns ``(results, frame_count)``.
"""
run_start: float = run[0].start_time # type: ignore[assignment]
run_end: float = run[-1].end_time # type: ignore[assignment]
@@ -678,21 +650,35 @@ class MotionSearchRunner(threading.Thread):
kf_pts = probe_vod_keyframe_pts(
self.ffprobe_path, vod_url, self._should_stop
)
if kf_pts:
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):
abs_times = [stream_time_to_absolute(time_map, p) for p in kf_pts]
indexed = list(enumerate(frames))
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
def _ts_kf(i: int) -> float:
return abs_times[i]
if frame_count == len(abs_times) and not extra_frames:
return results, frame_count
results = self._detect_with_progress(indexed, _ts_kf)
return results, len(frames)
logger.debug(
"Keyframe decode did not match %d probed keyframes, using cadence",
"Keyframe count mismatch (%d decoded vs %d probed), using cadence",
len(frames),
len(kf_pts),
)
@@ -702,12 +688,29 @@ 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)
with closing(self._decode_vod(vod_url, keyframes=False)) as frames:
return self._detect_with_progress(frames, _ts_fps)
results = self._detect_with_progress(indexed, _ts_fps)
return results, len(frames)
def _merge_run(
self,
+1 -1
View File
@@ -1333,7 +1333,7 @@ class RecordingExporter(threading.Thread):
end_file = f"{file_start}{self.end_time}.{PREVIEW_FRAME_TYPE}"
for file in sorted(os.listdir(preview_dir)):
if not file.startswith(file_start):
if not is_camera_preview_frame(file, self.camera):
continue
if file < start_file:
+1 -44
View File
@@ -4,11 +4,9 @@ import threading
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from unittest.mock import MagicMock, patch
from unittest.mock import 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
@@ -590,47 +588,6 @@ 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.
@@ -0,0 +1,98 @@
"""Current-hour preview frame routes only return the requested camera's frames."""
import os
import shutil
import tempfile
import time
from unittest.mock import MagicMock, patch
from frigate.const import PREVIEW_FRAME_TYPE
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
CAMERA = "front_door"
# camera names that extend CAMERA with "-" share its file name prefix
SIBLINGS = (f"{CAMERA}-2", f"{CAMERA}-door")
class TestHttpPreviewFrames(BaseTestHttp):
def setUp(self):
super().setUp([])
self.app = super().create_app()
self.cache_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.cache_dir, ignore_errors=True)
self.preview_dir = os.path.join(self.cache_dir, "preview_frames")
os.makedirs(self.preview_dir)
for target, value in (
("frigate.api.media.CACHE_DIR", self.cache_dir),
("frigate.api.preview.CACHE_DIR", self.cache_dir),
("frigate.api.preview._preview_listing_cache", (-1.0, [])),
):
patcher = patch(target, value)
patcher.start()
self.addCleanup(patcher.stop)
# ahead of now so the media routes never fall back to stored previews
self.start_ts = time.time() + 60
self._write_frame(CAMERA, self.start_ts - 10)
self.own_frames = [self._write_frame(CAMERA, self.start_ts + 1)]
for sibling in SIBLINGS:
self._write_frame(sibling, self.start_ts + 1)
def _write_frame(self, camera: str, frame_time: float) -> str:
name = f"preview_{camera}-{frame_time}.{PREVIEW_FRAME_TYPE}"
with open(os.path.join(self.preview_dir, name), "wb") as f:
f.write(b"frame")
return name
def _concat_files(self, mock_run: MagicMock) -> set[str]:
concat = mock_run.call_args.kwargs["input"].decode()
return {
os.path.basename(line.split("'")[1])
for line in concat.splitlines()
if line.startswith("file ")
}
def test_frames_listing_excludes_sibling_camera(self):
with AuthTestClient(self.app) as client:
response = client.get(
f"/preview/{CAMERA}/start/{self.start_ts}/end/inf/frames"
)
assert response.status_code == 200
assert response.json() == self.own_frames
def test_preview_gif_excludes_sibling_camera(self):
result = MagicMock(returncode=0, stdout=b"GIF89a")
with (
patch("frigate.api.media.sp.run", return_value=result) as mock_run,
AuthTestClient(self.app) as client,
):
response = client.get(
f"/{CAMERA}/start/{self.start_ts}/end/inf/preview.gif"
)
assert response.status_code == 200
assert self._concat_files(mock_run) == set(self.own_frames)
def test_preview_mp4_excludes_sibling_camera(self):
def fake_run(cmd, **kwargs):
with open(cmd[-1], "wb") as f:
f.write(b"mp4")
return MagicMock(returncode=0)
with (
patch("frigate.api.media.sp.run", side_effect=fake_run) as mock_run,
AuthTestClient(self.app) as client,
):
response = client.get(
f"/{CAMERA}/start/{self.start_ts}/end/inf/preview.mp4"
)
assert response.status_code == 200
assert self._concat_files(mock_run) == set(self.own_frames)
+37
View File
@@ -1,5 +1,6 @@
"""Tests for export progress tracking, broadcast, and FFmpeg parsing."""
import datetime
import io
import os
import shutil
@@ -7,11 +8,14 @@ import tempfile
import unittest
from unittest.mock import MagicMock, patch
from peewee import SqliteDatabase
from frigate.jobs.export import (
PROGRESS_BROADCAST_MIN_INTERVAL,
ExportJob,
ExportJobManager,
)
from frigate.models import Previews
from frigate.record.export import (
ExportStreamEnum,
PlaybackSourceEnum,
@@ -557,5 +561,38 @@ class TestChapterMetadataInProgressReview(unittest.TestCase):
assert "title=Alert: person" in content
class TestPreviewExportCommandCameraMatch(unittest.TestCase):
def setUp(self) -> None:
self.cache_dir = tempfile.mkdtemp(prefix="frigate_preview_export_test_")
self.addCleanup(shutil.rmtree, self.cache_dir, ignore_errors=True)
self.preview_dir = os.path.join(self.cache_dir, "preview_frames")
os.makedirs(self.preview_dir)
def _write_frame(self, camera: str, frame_time: float) -> str:
path = os.path.join(self.preview_dir, f"preview_{camera}-{frame_time}.webp")
with open(path, "wb") as f:
f.write(b"fake-webp-bytes")
return path
def test_current_hour_playlist_excludes_sibling_camera(self) -> None:
exporter = _make_exporter()
exporter.playback_source = PlaybackSourceEnum.preview
exporter.start_time = datetime.datetime.now(datetime.UTC).timestamp()
exporter.end_time = 9_999_999_999
own = self._write_frame(exporter.camera, exporter.start_time + 1)
self._write_frame(f"{exporter.camera}-2", exporter.start_time + 1)
db = SqliteDatabase(":memory:")
with (
patch("frigate.record.export.CACHE_DIR", self.cache_dir),
db.bind_ctx([Previews]),
):
Previews.create_table()
_, playlist_lines = exporter.get_preview_export_command("out.mp4")
files = {line for line in playlist_lines if line.startswith("file ")}
assert files == {f"file '{own}'"}
if __name__ == "__main__":
unittest.main()
-36
View File
@@ -1,36 +0,0 @@
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()
+2 -9
View File
@@ -458,7 +458,6 @@ 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
@@ -1276,7 +1275,7 @@ def run_ffmpeg_snapshot(
if height is not None:
ffmpeg_cmd.insert(-3, "-vf")
ffmpeg_cmd.insert(-3, f"scale=-1:'min({height},ih)'")
ffmpeg_cmd.insert(-3, f"scale=-1:{height}")
try:
process = sp.run(
@@ -1299,17 +1298,11 @@ 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,
timeout=timeout,
ffmpeg, file_path, codec, seek_time=relative_frame_time, height=height
)
return image_data