From 550276e430587d39f46ebc0226ff5e7eb8d42377 Mon Sep 17 00:00:00 2001 From: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:30:18 -0600 Subject: [PATCH] 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. --- frigate/api/media.py | 9 +- frigate/api/preview.py | 3 +- frigate/record/export.py | 2 +- .../test/http_api/test_http_preview_frames.py | 96 +++++++++++++++++++ frigate/test/test_export_progress.py | 37 +++++++ 5 files changed, 142 insertions(+), 5 deletions(-) create mode 100644 frigate/test/http_api/test_http_preview_frames.py diff --git a/frigate/api/media.py b/frigate/api/media.py index a5243a1c67..6616391bbb 100644 --- a/frigate/api/media.py +++ b/frigate/api/media.py @@ -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() diff --git a/frigate/api/preview.py b/frigate/api/preview.py index 81de23d003..71bb24900c 100644 --- a/frigate/api/preview.py +++ b/frigate/api/preview.py @@ -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( diff --git a/frigate/record/export.py b/frigate/record/export.py index 9bfe64e4ac..4562e03fb1 100644 --- a/frigate/record/export.py +++ b/frigate/record/export.py @@ -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: diff --git a/frigate/test/http_api/test_http_preview_frames.py b/frigate/test/http_api/test_http_preview_frames.py new file mode 100644 index 0000000000..7a65b64106 --- /dev/null +++ b/frigate/test/http_api/test_http_preview_frames.py @@ -0,0 +1,96 @@ +"""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) + + self.start_ts = time.time() + 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) diff --git a/frigate/test/test_export_progress.py b/frigate/test/test_export_progress.py index bdb6a2fd5b..7ca259554b 100644 --- a/frigate/test/test_export_progress.py +++ b/frigate/test/test_export_progress.py @@ -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()