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
5 changed files with 144 additions and 5 deletions
+6 -3
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 (
@@ -1603,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()
@@ -1794,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(
+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:
@@ -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()