Compare commits

..
Author SHA1 Message Date
Josh Hawkins 16784d055c normalize whitespace in custom export ffmpeg args
The custom export validator tokenized args on any whitespace, but the export command was built by splitting on single spaces, so repeated spaces, tabs, or newlines produced a different argv than the one that was validated. The exporter now rejoins custom args with single spaces so ffmpeg receives exactly the tokens the validator checked.
2026-11-23 09:38:33 -06:00
9 changed files with 139 additions and 176 deletions
@@ -9,8 +9,8 @@ class MediaRecordingsSummaryQueryParams(BaseModel):
class MediaRecordingsAvailabilityQueryParams(BaseModel): class MediaRecordingsAvailabilityQueryParams(BaseModel):
cameras: str = "all" cameras: str = "all"
before: float | SkipJsonSchema[None] = Field(default=None, allow_inf_nan=False) before: float | SkipJsonSchema[None] = None
after: float | SkipJsonSchema[None] = Field(default=None, allow_inf_nan=False) after: float | SkipJsonSchema[None] = None
scale: int = Field(default=30, ge=1) scale: int = Field(default=30, ge=1)
+5 -8
View File
@@ -166,13 +166,10 @@ def imagestream(
time.sleep(1 / fps) time.sleep(1 / fps)
frame = detected_frames_processor.get_current_frame(camera_name, draw_options) frame = detected_frames_processor.get_current_frame(camera_name, draw_options)
if frame is None: 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(height * frame.shape[1] / frame.shape[0])
width = int(frame_height * frame.shape[1] / frame.shape[0]) frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_LINEAR)
frame = cv2.resize(
frame, dsize=(width, frame_height), interpolation=cv2.INTER_LINEAR
)
ret, jpg = cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), 70]) ret, jpg = cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), 70])
yield ( yield (
@@ -281,7 +278,7 @@ async def latest_frame(
status_code=500, 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]) width = int(height * frame.shape[1] / frame.shape[0])
if height < 1 or width < 1: if height < 1 or width < 1:
@@ -323,7 +320,7 @@ async def latest_frame(
frame = cv2.cvtColor(frame, cv2.COLOR_YUV2BGR_I420) 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]) width = int(height * frame.shape[1] / frame.shape[0])
frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_AREA) frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_AREA)
+35 -29
View File
@@ -2,7 +2,6 @@
import datetime as dt import datetime as dt
import logging import logging
import math
from datetime import datetime, timedelta from datetime import datetime, timedelta
from functools import reduce from functools import reduce
from pathlib import Path from pathlib import Path
@@ -444,38 +443,45 @@ async def no_recordings(
else: else:
covered.append((rec_start, rec_end)) covered.append((rec_start, rec_end))
# A scale-sized bucket counts as empty when it fits inside a gap between # Iterate through time segments and check if each has any recording
# covered intervals. Walking the gaps keeps the work proportional to the no_recording_segments = []
# recordings found rather than to the requested span. current = after
bucket_count = math.ceil((before - after) / scale) current_gap_start = None
gaps: list[list[float]] = [] idx = 0
free_start = -math.inf covered_count = len(covered)
for rec_start, rec_end in covered + [(math.inf, math.inf)]: while current < before:
first = 0 if free_start <= after else math.ceil((free_start - after) / scale) segment_end = min(current + scale, before)
if rec_start >= before: # Advance past covered intervals that end before this segment begins;
last = bucket_count - 1 # 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: 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: current = segment_end
gap_start = after + first * scale
gap_end = before if last == bucket_count - 1 else after + (last + 1) * scale
if gaps and gaps[-1][1] == gap_start: # Append the last gap if it exists
gaps[-1][1] = gap_end if current_gap_start is not None:
else: no_recording_segments.append(
gaps.append([gap_start, gap_end]) {"start_time": int(current_gap_start), "end_time": int(before)}
)
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) return JSONResponse(content=no_recording_segments)
@@ -489,7 +495,7 @@ async def no_recordings(
Recordings can be filtered by cameras and kept based on motion, objects, or audio attributes. Recordings can be filtered by cameras and kept based on motion, objects, or audio attributes.
""", """,
) )
def delete_recordings( async def delete_recordings(
start: float = PathParam(..., description="Start timestamp (unix)"), start: float = PathParam(..., description="Start timestamp (unix)"),
end: float = PathParam(..., description="End timestamp (unix)"), end: float = PathParam(..., description="End timestamp (unix)"),
params: RecordingsDeleteQueryParams = Depends(), params: RecordingsDeleteQueryParams = Depends(),
+49 -46
View File
@@ -6,10 +6,8 @@ import threading
import time import time
from collections.abc import Callable, Generator, Iterable from collections.abc import Callable, Generator, Iterable
from concurrent.futures import Future, ThreadPoolExecutor, as_completed from concurrent.futures import Future, ThreadPoolExecutor, as_completed
from contextlib import closing
from dataclasses import asdict, dataclass, field from dataclasses import asdict, dataclass, field
from datetime import datetime from datetime import datetime
from itertools import islice
from typing import Any from typing import Any
import cv2 import cv2
@@ -613,49 +611,24 @@ class MotionSearchRunner(threading.Thread):
def _detect_with_progress( def _detect_with_progress(
self, self,
frames: Iterable[np.ndarray], indexed_frames: list[tuple[int, np.ndarray]],
timestamp_fn: Callable[[int], float], timestamp_fn: Callable[[int], float],
) -> tuple[list[MotionSearchResult], int]: ) -> list[MotionSearchResult]:
"""Run detection while firing throttled progress as frames are scanned. """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]: def _gen() -> Generator[tuple[int, np.ndarray], None, None]:
nonlocal frame_count for i, frame in indexed_frames:
for i, frame in enumerate(frames):
frame_count = i + 1
if not self._should_stop(): if not self._should_stop():
self._emit_progress(timestamp_fn(i)) self._emit_progress(timestamp_fn(i))
yield i, frame yield i, frame
results = detect_motion_scaled( return detect_motion_scaled(
_gen(), _gen(),
self.scaled_mask, self.scaled_mask,
self.job.threshold, self.job.threshold,
self.job.min_area, self.job.min_area,
timestamp_fn, 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( def _process_run(
self, run: list[Recordings] 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 are all decoded anyway) paired with its probed PTS; if the decoded and
probed counts disagree (the decoder ignored ``-skip_frame nokey`` or the probed counts disagree (the decoder ignored ``-skip_frame nokey`` or the
stream is corrupt) this run re-runs in the fixed-cadence fallback. stream is corrupt) this run re-runs in the fixed-cadence fallback.
Frames stream through detection, so a run never holds more than the Returns ``(results, frame_count)``.
current and previous frame. Returns ``(results, frame_count)``.
""" """
run_start: float = run[0].start_time # type: ignore[assignment] run_start: float = run[0].start_time # type: ignore[assignment]
run_end: float = run[-1].end_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( kf_pts = probe_vod_keyframe_pts(
self.ffprobe_path, vod_url, self._should_stop self.ffprobe_path, vod_url, self._should_stop
) )
frames = list(
if kf_pts: 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] 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: def _ts_kf(i: int) -> float:
results, frame_count = self._detect_with_progress( return abs_times[i]
islice(frames, len(abs_times)), abs_times.__getitem__
)
extra_frames = next(frames, None) is not None
if frame_count == len(abs_times) and not extra_frames: results = self._detect_with_progress(indexed, _ts_kf)
return results, frame_count return results, len(frames)
logger.debug( 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), len(kf_pts),
) )
@@ -702,12 +688,29 @@ class MotionSearchRunner(threading.Thread):
self, vod_url: str, time_map: list[tuple[float, float, float]] self, vod_url: str, time_map: list[tuple[float, float, float]]
) -> tuple[list[MotionSearchResult], int]: ) -> tuple[list[MotionSearchResult], int]:
"""Fixed-cadence fallback: fps-filtered VOD decode, evenly spaced times.""" """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: def _ts_fps(i: int) -> float:
return stream_time_to_absolute(time_map, i / self.fps_rate) return stream_time_to_absolute(time_map, i / self.fps_rate)
with closing(self._decode_vod(vod_url, keyframes=False)) as frames: results = self._detect_with_progress(indexed, _ts_fps)
return self._detect_with_progress(frames, _ts_fps) return results, len(frames)
def _merge_run( def _merge_run(
self, self,
+14 -2
View File
@@ -261,6 +261,18 @@ def validate_ffmpeg_args(args: str) -> tuple[bool, str]:
return True, "" return True, ""
def normalize_ffmpeg_args(args: str | None) -> str | None:
"""Rejoin args with single spaces.
validate_ffmpeg_args tokenizes on any whitespace, while export commands are
built with split(" "). Normalizing keeps the two token lists identical.
"""
if args is None:
return None
return " ".join(args.split())
class PlaybackSourceEnum(str, Enum): class PlaybackSourceEnum(str, Enum):
recordings = "recordings" recordings = "recordings"
preview = "preview" preview = "preview"
@@ -327,8 +339,8 @@ class RecordingExporter(threading.Thread):
self.end_time = end_time self.end_time = end_time
self.playback_source = playback_source self.playback_source = playback_source
self.export_case_id = export_case_id self.export_case_id = export_case_id
self.ffmpeg_input_args = ffmpeg_input_args self.ffmpeg_input_args = normalize_ffmpeg_args(ffmpeg_input_args)
self.ffmpeg_output_args = ffmpeg_output_args self.ffmpeg_output_args = normalize_ffmpeg_args(ffmpeg_output_args)
self.cpu_fallback = cpu_fallback self.cpu_fallback = cpu_fallback
self.chapters = chapters self.chapters = chapters
self.stream = stream self.stream = stream
+1 -44
View File
@@ -4,11 +4,9 @@ import threading
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass from dataclasses import dataclass
from datetime import UTC, datetime, timedelta from datetime import UTC, datetime, timedelta
from unittest.mock import MagicMock, patch from unittest.mock import patch
from zoneinfo import ZoneInfo from zoneinfo import ZoneInfo
import cv2
import numpy as np
from fastapi import Request from fastapi import Request
from frigate.api.auth import get_allowed_cameras_for_filter, get_current_user 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}) response = client.get("/recordings/unavailable", params={"scale": 0})
assert response.status_code == 422 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): def test_recordings_summary_day_attribution_by_start_time(self):
""" """
A recording spanning midnight marks only its start day. A recording spanning midnight marks only its start day.
+31
View File
@@ -143,6 +143,37 @@ class TestValidateFfmpegArgs(unittest.TestCase):
self.assertRejected("-metadata comment=x") self.assertRejected("-metadata comment=x")
class TestCustomArgsTokenization(unittest.TestCase):
"""The built command must contain exactly the tokens the validator checked."""
def test_irregular_whitespace_does_not_shift_tokens(self) -> None:
output_args = "-c:v libx264\t-crf 23\n -r 25 "
self.assertTrue(validate_ffmpeg_args(output_args)[0])
with patch("frigate.record.export.Path.mkdir"):
exporter = RecordingExporter(
MagicMock(),
"front_abc123",
"front",
None,
None,
1_000,
2_000,
PlaybackSourceEnum.recordings,
ffmpeg_input_args=" -an ",
ffmpeg_output_args=output_args,
)
exporter.config.ffmpeg.ffmpeg_path = "ffmpeg"
exporter.staged_runs = ["/cache/stage_0.mp4"]
cmd, _ = exporter.get_record_export_command("/exports/out.mp4")
for token in cmd[: cmd.index("-metadata")]:
self.assertNotEqual(token, "")
self.assertEqual(token.split(), [token])
self.assertIn("-c:v libx264 -crf 23 -r 25", " ".join(cmd))
class TestExportVideoPath(unittest.TestCase): class TestExportVideoPath(unittest.TestCase):
"""Tests for the file path an export takes once the user names it.""" """Tests for the file path an export takes once the user names it."""
-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]] best_frame = best_frame[region[1] : region[3], region[0] : region[2]]
if height: if height:
height = min(height, frame.shape[0])
width = int(height * best_frame.shape[1] / best_frame.shape[0]) width = int(height * best_frame.shape[1] / best_frame.shape[0])
best_frame = cv2.resize( best_frame = cv2.resize(
best_frame, dsize=(width, height), interpolation=cv2.INTER_AREA best_frame, dsize=(width, height), interpolation=cv2.INTER_AREA
@@ -1276,7 +1275,7 @@ def run_ffmpeg_snapshot(
if height is not None: if height is not None:
ffmpeg_cmd.insert(-3, "-vf") ffmpeg_cmd.insert(-3, "-vf")
ffmpeg_cmd.insert(-3, f"scale=-1:'min({height},ih)'") ffmpeg_cmd.insert(-3, f"scale=-1:{height}")
try: try:
process = sp.run( process = sp.run(
@@ -1299,17 +1298,11 @@ def get_image_from_recording(
relative_frame_time: float, relative_frame_time: float,
codec: str, codec: str,
height: int | None = None, height: int | None = None,
timeout: int = 30,
) -> Any | None: ) -> Any | None:
"""retrieve a frame from given time in recording file.""" """retrieve a frame from given time in recording file."""
image_data, _ = run_ffmpeg_snapshot( image_data, _ = run_ffmpeg_snapshot(
ffmpeg, ffmpeg, file_path, codec, seek_time=relative_frame_time, height=height
file_path,
codec,
seek_time=relative_frame_time,
height=height,
timeout=timeout,
) )
return image_data return image_data