mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-24 06:17:12 +03:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0e76645ea | ||
|
|
47fcb90893 |
@@ -102,7 +102,7 @@ proxy:
|
||||
# Optional: Auth secret that is checked against the X-Proxy-Secret header sent from
|
||||
# the proxy. If not set, all requests are trusted regardless of origin.
|
||||
auth_secret: None
|
||||
# Optional: The default role to use for proxy auth. Must be "admin" or "viewer"
|
||||
# Optional: The default role to use for proxy auth. Must be "admin", "viewer", a custom role, or "none" to deny
|
||||
default_role: viewer
|
||||
# Optional: The character used to separate multiple values in the proxy headers. (default: shown below)
|
||||
separator: ","
|
||||
|
||||
@@ -234,6 +234,8 @@ proxy:
|
||||
|
||||
Setting `default_role` to `none` denies access instead of falling back to a role. Any proxy-authenticated user whose headers do not match an explicit `role_map` entry receives a 403 response. This is useful when the upstream proxy authenticates a broader set of users than should reach Frigate, so that only mapped groups are allowed in.
|
||||
|
||||
A `default_role` that does not name a configured role is treated as `none`.
|
||||
|
||||
```yaml
|
||||
proxy:
|
||||
...
|
||||
@@ -266,7 +268,8 @@ In this example:
|
||||
- If the proxy passes a role header containing `camera-viewer`, the user is assigned the `viewer` role.
|
||||
- If the proxy passes a role header containing `operators`, the user is assigned the `operator` custom role.
|
||||
- If no mapping matches, Frigate falls back to `default_role` if configured, or denies access if `default_role` is `none`.
|
||||
- If `role_map` is not defined, Frigate assumes the role header directly contains `admin`, `viewer`, or a custom role name.
|
||||
- If a group matches but its mapped role no longer exists (for example, a deleted custom role), access is denied.
|
||||
- If `role_map` is not defined, Frigate assumes the role header directly contains `admin`, `viewer`, or a custom role name, matched without regard to case.
|
||||
|
||||
**Note on matching semantics:**
|
||||
|
||||
|
||||
+13
-16
@@ -580,8 +580,9 @@ def resolve_role(
|
||||
(split by proxy_config.separator) and map to roles.
|
||||
Admin matches short-circuit to admin.
|
||||
- If no role_map is configured, treat the header as role names directly.
|
||||
2. If no valid role is found, return proxy_config.default_role if it's valid in config_roles, else 'viewer'.
|
||||
The literal value 'none' is a valid default and means access should be denied.
|
||||
2. If no valid role is found, return proxy_config.default_role if it's valid in config_roles, else 'none'.
|
||||
The literal value 'none' means access should be denied.
|
||||
A role_map match whose mapped roles no longer exist in config_roles also resolves to 'none'.
|
||||
|
||||
Args:
|
||||
headers (dict): Incoming request headers (case-insensitive).
|
||||
@@ -594,17 +595,11 @@ def resolve_role(
|
||||
default_role = proxy_config.default_role
|
||||
role_header = proxy_config.header_map.role
|
||||
|
||||
# Validate default_role against config; fallback to 'viewer' if invalid.
|
||||
# "none" is a sentinel meaning "deny access when no mapping matches"; it is
|
||||
# reserved in AuthConfig.validate_roles so it is never a configured role.
|
||||
validated_default = (
|
||||
default_role
|
||||
if default_role in config_roles or default_role == "none"
|
||||
else "viewer"
|
||||
)
|
||||
if not config_roles:
|
||||
# Edge case: no roles defined
|
||||
validated_default = "none" if default_role == "none" else "viewer"
|
||||
# Role names match case-insensitively, as header values are lowercased.
|
||||
# "none" is the deny sentinel; an unknown or missing default also denies,
|
||||
# since falling back to viewer would grant every camera.
|
||||
roles_by_name = {r.lower(): r for r in config_roles}
|
||||
validated_default = roles_by_name.get((default_role or "").lower(), "none")
|
||||
|
||||
if not role_header:
|
||||
logger.debug(
|
||||
@@ -631,7 +626,7 @@ def resolve_role(
|
||||
logger.debug("Parsed groups from role header: %s", groups)
|
||||
|
||||
matched_roles = {
|
||||
role_name
|
||||
role_name.lower()
|
||||
for role_name, required_groups in proxy_config.header_map.role_map.items()
|
||||
if any(group in groups for group in required_groups)
|
||||
}
|
||||
@@ -643,9 +638,11 @@ def resolve_role(
|
||||
logger.debug("Resolved role (with role_map) to 'admin'.")
|
||||
return "admin"
|
||||
|
||||
# A mapped role that was deleted or renamed denies rather than
|
||||
# widening to the default role
|
||||
if matched_roles:
|
||||
resolved = next(
|
||||
(r for r in config_roles if r in matched_roles), validated_default
|
||||
(r for r in config_roles if r.lower() in matched_roles), "none"
|
||||
)
|
||||
logger.debug("Resolved role (with role_map) to '%s'.", resolved)
|
||||
return resolved
|
||||
@@ -664,7 +661,7 @@ def resolve_role(
|
||||
logger.debug("Parsed roles directly from header: %s", roles_from_header)
|
||||
|
||||
resolved = next(
|
||||
(r for r in config_roles if r in roles_from_header),
|
||||
(r for r in config_roles if r.lower() in roles_from_header),
|
||||
validated_default,
|
||||
)
|
||||
if resolved == validated_default and roles_from_header:
|
||||
|
||||
@@ -41,9 +41,6 @@ def swap_runtime_config(app: FastAPI, config: FrigateConfig) -> None:
|
||||
"""
|
||||
app.frigate_config = config
|
||||
|
||||
if app.replay_manager is not None:
|
||||
app.replay_manager.update_config(config)
|
||||
|
||||
if app.config_holder is not None:
|
||||
app.config_holder.set(config)
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ def create_fastapi_app(
|
||||
logger.info("FastAPI started")
|
||||
asyncio.create_task(
|
||||
debug_replay_auto_stop_watchdog(
|
||||
replay_manager, lambda: app.frigate_config, config_publisher
|
||||
replay_manager, frigate_config, config_publisher
|
||||
)
|
||||
)
|
||||
yield
|
||||
|
||||
@@ -166,13 +166,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 +278,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 +320,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)
|
||||
|
||||
+35
-29
@@ -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)
|
||||
|
||||
@@ -489,7 +495,7 @@ async def no_recordings(
|
||||
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)"),
|
||||
end: float = PathParam(..., description="End timestamp (unix)"),
|
||||
params: RecordingsDeleteQueryParams = Depends(),
|
||||
|
||||
@@ -88,16 +88,17 @@ class AuthConfig(FrigateBaseModel):
|
||||
f"Invalid role name '{role}'. Must be alphanumeric with underscores."
|
||||
)
|
||||
|
||||
# 'none' is the deny sentinel for proxy.default_role, where it is matched
|
||||
# case-insensitively, so every casing of it has to be reserved here
|
||||
used_reserved = sorted(
|
||||
r for r in v if r in ("admin", "viewer") or r.lower() == "none"
|
||||
)
|
||||
# Proxy role headers match role names case-insensitively, so reserved
|
||||
# names are reserved in every casing and names must differ beyond case
|
||||
used_reserved = sorted(r for r in v if r.lower() in ("admin", "viewer", "none"))
|
||||
if used_reserved:
|
||||
raise ValueError(
|
||||
f"Reserved role name(s) {', '.join(used_reserved)} cannot be used as custom roles."
|
||||
)
|
||||
|
||||
if len({r.lower() for r in v}) != len(v):
|
||||
raise ValueError("Role names must be unique regardless of letter case.")
|
||||
|
||||
# Ensure no role has an empty camera list
|
||||
for role, allowed_cameras in v.items():
|
||||
if not allowed_cameras:
|
||||
|
||||
@@ -1041,6 +1041,15 @@ class FrigateConfig(FrigateBaseModel):
|
||||
# set notifications state
|
||||
self.notifications.enabled_in_config = self.notifications.enabled
|
||||
|
||||
default_role = (self.proxy.default_role or "").lower()
|
||||
if default_role != "none" and default_role not in {
|
||||
r.lower() for r in self.auth.roles
|
||||
}:
|
||||
logger.warning(
|
||||
"proxy.default_role '%s' is not a configured role, so proxy users without a matching role are denied",
|
||||
self.proxy.default_role,
|
||||
)
|
||||
|
||||
# validate genai: each role (chat, descriptions, embeddings, transcribe) at most once
|
||||
role_to_name: dict[GenAIRoleEnum, str] = {}
|
||||
for name, genai_cfg in self.genai.items():
|
||||
|
||||
@@ -55,10 +55,9 @@ class ProxyConfig(FrigateBaseModel):
|
||||
@field_validator("default_role", mode="before")
|
||||
@classmethod
|
||||
def normalize_deny_sentinel(cls, v):
|
||||
# Fail closed on capitalization: an unnormalized "None" would miss the
|
||||
# sentinel and fall back to viewer, granting the access it was meant to
|
||||
# deny. Other role names stay case-sensitive.
|
||||
if isinstance(v, str) and v.strip().lower() == "none":
|
||||
# Fail closed: "none" in any casing and a null default both deny.
|
||||
# Normalizing null keeps the value through /config, which drops nulls
|
||||
if v is None or (isinstance(v, str) and v.strip().lower() == "none"):
|
||||
return "none"
|
||||
return v
|
||||
|
||||
|
||||
+14
-31
@@ -11,11 +11,10 @@ import os
|
||||
import shutil
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
|
||||
from ruamel.yaml import YAML
|
||||
|
||||
from frigate.config import CameraConfig, FrigateConfig
|
||||
from frigate.config import FrigateConfig
|
||||
from frigate.config.camera.updater import (
|
||||
CameraConfigUpdateEnum,
|
||||
CameraConfigUpdatePublisher,
|
||||
@@ -62,7 +61,6 @@ class DebugReplayManager:
|
||||
self.start_ts: float | None = None
|
||||
self.end_ts: float | None = None
|
||||
self.session_started_at: float | None = None
|
||||
self._published_camera: CameraConfig | None = None
|
||||
self._job_state_publisher = JobStatePublisher()
|
||||
|
||||
@property
|
||||
@@ -111,13 +109,6 @@ class DebugReplayManager:
|
||||
self.start_ts = None
|
||||
self.end_ts = None
|
||||
self.session_started_at = None
|
||||
self._published_camera = None
|
||||
|
||||
def update_config(self, config: FrigateConfig) -> None:
|
||||
"""Carry the published replay camera into a newly swapped-in config."""
|
||||
with self._lock:
|
||||
if self._published_camera is not None and self.replay_camera_name:
|
||||
config.cameras[self.replay_camera_name] = self._published_camera
|
||||
|
||||
def publish_camera(
|
||||
self,
|
||||
@@ -126,11 +117,10 @@ class DebugReplayManager:
|
||||
clip_path: str,
|
||||
frigate_config: FrigateConfig,
|
||||
config_publisher: CameraConfigUpdatePublisher,
|
||||
) -> bool:
|
||||
) -> None:
|
||||
"""Build the in-memory replay camera config and publish the add event.
|
||||
|
||||
Called by the job runner during the starting_camera phase. Returns
|
||||
False without publishing if the session was stopped meanwhile.
|
||||
Called by the job runner during the starting_camera phase.
|
||||
"""
|
||||
source_config = frigate_config.cameras[source_camera]
|
||||
camera_dict = self._build_camera_config_dict(
|
||||
@@ -150,21 +140,12 @@ class DebugReplayManager:
|
||||
new_config = FrigateConfig.parse_object(config_data)
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Failed to validate replay camera config: {e}") from e
|
||||
frigate_config.cameras[replay_name] = new_config.cameras[replay_name]
|
||||
|
||||
camera_config = new_config.cameras[replay_name]
|
||||
|
||||
with self._lock:
|
||||
if self.replay_camera_name != replay_name:
|
||||
return False
|
||||
|
||||
frigate_config.cameras[replay_name] = camera_config
|
||||
self._published_camera = camera_config
|
||||
config_publisher.publish_update(
|
||||
CameraConfigUpdateTopic(CameraConfigUpdateEnum.add, replay_name),
|
||||
camera_config,
|
||||
)
|
||||
|
||||
return True
|
||||
config_publisher.publish_update(
|
||||
CameraConfigUpdateTopic(CameraConfigUpdateEnum.add, replay_name),
|
||||
new_config.cameras[replay_name],
|
||||
)
|
||||
|
||||
def stop(
|
||||
self,
|
||||
@@ -186,10 +167,12 @@ class DebugReplayManager:
|
||||
replay_name = self.replay_camera_name
|
||||
source_camera = self.source_camera
|
||||
|
||||
if replay_name is not None and self._published_camera is not None:
|
||||
# Only publish remove if the camera was actually added to the live
|
||||
# config (i.e. the runner reached the starting_camera phase).
|
||||
if replay_name is not None and replay_name in frigate_config.cameras:
|
||||
config_publisher.publish_update(
|
||||
CameraConfigUpdateTopic(CameraConfigUpdateEnum.remove, replay_name),
|
||||
self._published_camera,
|
||||
frigate_config.cameras[replay_name],
|
||||
)
|
||||
frigate_config.cameras.pop(replay_name, None)
|
||||
|
||||
@@ -379,7 +362,7 @@ def cleanup_replay_cameras() -> None:
|
||||
|
||||
async def debug_replay_auto_stop_watchdog(
|
||||
manager: DebugReplayManager,
|
||||
get_config: Callable[[], FrigateConfig],
|
||||
frigate_config: FrigateConfig,
|
||||
config_publisher: CameraConfigUpdatePublisher,
|
||||
) -> None:
|
||||
"""Auto-stop debug replay sessions that exceed MAX_SESSION_DURATION_SECONDS.
|
||||
@@ -401,7 +384,7 @@ async def debug_replay_auto_stop_watchdog(
|
||||
replay_name = manager.replay_camera_name
|
||||
await asyncio.to_thread(
|
||||
manager.stop,
|
||||
frigate_config=get_config(),
|
||||
frigate_config=frigate_config,
|
||||
config_publisher=config_publisher,
|
||||
)
|
||||
logger.info(
|
||||
|
||||
@@ -376,16 +376,13 @@ class DebugReplayJobRunner(threading.Thread):
|
||||
self._finalize_cancelled(clip_path)
|
||||
return
|
||||
|
||||
if not self.replay_manager.publish_camera(
|
||||
self.replay_manager.publish_camera(
|
||||
source_camera=self.job.source_camera,
|
||||
replay_name=replay_name,
|
||||
clip_path=clip_path,
|
||||
frigate_config=self.frigate_config,
|
||||
config_publisher=self.config_publisher,
|
||||
):
|
||||
self._finalize_cancelled(clip_path)
|
||||
return
|
||||
|
||||
)
|
||||
self.replay_manager.mark_session_ready(clip_path)
|
||||
|
||||
self.job.status = JobStatusTypesEnum.success
|
||||
|
||||
@@ -487,9 +487,6 @@ def get_export_job_manager(config: FrigateConfig) -> ExportJobManager:
|
||||
with _job_manager_lock:
|
||||
if _job_manager is None:
|
||||
_job_manager = ExportJobManager(config, _get_max_concurrent(config))
|
||||
|
||||
# callers pass the live config, which a save replaces
|
||||
_job_manager.config = config
|
||||
_job_manager.ensure_started()
|
||||
return _job_manager
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
+10
-14
@@ -789,16 +789,16 @@ class BirdsEyeFrameManager:
|
||||
force_update = True
|
||||
else:
|
||||
return False, False
|
||||
else:
|
||||
# update the last active frame for the camera
|
||||
camera_state["current_frame"] = frame.copy()
|
||||
camera_state["current_frame_time"] = frame_time
|
||||
modes = camera_config.birdseye.modes
|
||||
|
||||
if self.camera_threshold_active(modes, activity):
|
||||
camera_state["last_active_frame"] = frame_time
|
||||
# update the last active frame for the camera
|
||||
camera_state["current_frame"] = frame.copy()
|
||||
camera_state["current_frame_time"] = frame_time
|
||||
modes = camera_config.birdseye.modes
|
||||
|
||||
camera_state["live_active"] = self.camera_live_active(modes, activity)
|
||||
if self.camera_threshold_active(modes, activity):
|
||||
camera_state["last_active_frame"] = frame_time
|
||||
|
||||
camera_state["live_active"] = self.camera_live_active(modes, activity)
|
||||
|
||||
# monotonic so a backward wall clock step can't freeze the output
|
||||
now = time.monotonic()
|
||||
@@ -865,10 +865,7 @@ class Birdseye:
|
||||
(1.0 / self.idle_fps) if self.idle_fps > 0 else None
|
||||
)
|
||||
|
||||
# restream changes need a restart, so the buffer exists only if it did at init
|
||||
self.restream = config.birdseye.restream
|
||||
|
||||
if self.restream:
|
||||
if config.birdseye.restream:
|
||||
self.birdseye_buffer: Any = self.frame_manager.create(
|
||||
"birdseye",
|
||||
self.birdseye_manager.yuv_shape[0] * self.birdseye_manager.yuv_shape[1],
|
||||
@@ -880,7 +877,7 @@ class Birdseye:
|
||||
def __send_new_frame(self) -> None:
|
||||
frame_bytes = self.birdseye_manager.frame.tobytes()
|
||||
|
||||
if self.restream:
|
||||
if self.config.birdseye.restream:
|
||||
self.birdseye_buffer[:] = frame_bytes
|
||||
|
||||
try:
|
||||
@@ -957,7 +954,6 @@ class Birdseye:
|
||||
>= self._idle_interval
|
||||
):
|
||||
self.__send_new_frame()
|
||||
self.birdseye_manager.last_output_time = now
|
||||
|
||||
def stop(self) -> None:
|
||||
self.review_subscriber.stop()
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -2,9 +2,7 @@
|
||||
|
||||
import multiprocessing as mp
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import numpy as np
|
||||
from unittest.mock import Mock
|
||||
|
||||
from frigate.config import (
|
||||
BirdseyeModeEnum,
|
||||
@@ -609,72 +607,6 @@ class TestBirdseyeModePayload(unittest.TestCase):
|
||||
assert birdseye_modes_from_mqtt_payload(payload) is None
|
||||
|
||||
|
||||
class TestBirdseyeRuntimeToggles(unittest.TestCase):
|
||||
"""Runtime config changes must not crash or overdrive Birdseye."""
|
||||
|
||||
def setUp(self):
|
||||
config = {
|
||||
"mqtt": {"enabled": False},
|
||||
"birdseye": {"enabled": True, "modes": ["continuous"]},
|
||||
"cameras": {
|
||||
"front": {
|
||||
"ffmpeg": {
|
||||
"inputs": [
|
||||
{"path": "rtsp://10.0.0.1:554/video", "roles": ["detect"]}
|
||||
]
|
||||
},
|
||||
"detect": {"height": 1080, "width": 1920, "fps": 5},
|
||||
}
|
||||
},
|
||||
}
|
||||
self.config = FrigateConfig(**config)
|
||||
self.manager = BirdsEyeFrameManager(self.config, mp.Event())
|
||||
self.frame = np.zeros((1620, 1920), np.uint8)
|
||||
self.activity = BirdseyeActivity(
|
||||
has_object=True, has_motion=True, severity=None
|
||||
)
|
||||
|
||||
def test_disabled_camera_forces_one_update_only(self):
|
||||
self.manager.update("front", self.activity, 1000.0, self.frame)
|
||||
self.config.cameras["front"].birdseye.enabled = False
|
||||
|
||||
changed, _ = self.manager.update("front", self.activity, 1000.2, self.frame)
|
||||
assert changed
|
||||
|
||||
changed, _ = self.manager.update("front", self.activity, 1000.4, self.frame)
|
||||
assert not changed
|
||||
|
||||
def test_enabling_restream_at_runtime_does_not_write_missing_buffer(self):
|
||||
birdseye = Birdseye.__new__(Birdseye)
|
||||
birdseye.restream = False
|
||||
birdseye.config = self.config
|
||||
birdseye.birdseye_manager = self.manager
|
||||
birdseye.input = Mock()
|
||||
self.config.birdseye.restream = True
|
||||
|
||||
birdseye._Birdseye__send_new_frame()
|
||||
|
||||
birdseye.input.put_nowait.assert_called_once()
|
||||
|
||||
def test_idle_heartbeat_waits_a_full_interval_between_sends(self):
|
||||
birdseye = Birdseye.__new__(Birdseye)
|
||||
birdseye.review_severity = {}
|
||||
birdseye.birdseye_manager = Mock()
|
||||
birdseye.birdseye_manager.update.return_value = (False, False)
|
||||
birdseye.birdseye_manager.camera_layout = []
|
||||
birdseye.birdseye_manager.last_output_time = 0.0
|
||||
birdseye._idle_interval = 0.2
|
||||
|
||||
with (
|
||||
patch.object(Birdseye, "_Birdseye__send_new_frame") as send,
|
||||
patch("frigate.output.birdseye.time.monotonic", side_effect=[10.0, 10.1]),
|
||||
):
|
||||
birdseye.write_data("front", [], [], 1.0, Mock())
|
||||
birdseye.write_data("front", [], [], 1.1, Mock())
|
||||
|
||||
assert send.call_count == 1
|
||||
|
||||
|
||||
class TestBirdseyeReviewSeverity(unittest.TestCase):
|
||||
"""Test that review updates drive the per-camera severity map."""
|
||||
|
||||
|
||||
@@ -24,7 +24,6 @@ class TestSwapRuntimeConfig(unittest.TestCase):
|
||||
|
||||
self.assertIs(app.frigate_config, config)
|
||||
app.genai_manager.update_config.assert_called_once_with(config)
|
||||
app.replay_manager.update_config.assert_called_once_with(config)
|
||||
app.profile_manager.update_config.assert_called_once_with(config)
|
||||
self.assertIs(app.stats_emitter.config, config)
|
||||
app.stats_emitter.hardware_stats.set_config.assert_called_once_with(config)
|
||||
|
||||
@@ -101,7 +101,6 @@ class TestDebugReplayManagerStop(unittest.TestCase):
|
||||
manager.mark_session_ready("/tmp/replay/_replay_front.mp4")
|
||||
|
||||
camera_config = MagicMock()
|
||||
manager._published_camera = camera_config
|
||||
frigate_config = MagicMock()
|
||||
frigate_config.cameras = {"_replay_front": camera_config}
|
||||
publisher = MagicMock()
|
||||
@@ -170,7 +169,6 @@ class TestDebugReplayManagerPublishCamera(unittest.TestCase):
|
||||
from frigate.debug_replay import DebugReplayManager
|
||||
|
||||
manager = DebugReplayManager()
|
||||
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
|
||||
|
||||
source_config = MagicMock()
|
||||
new_camera_config = MagicMock()
|
||||
@@ -248,103 +246,5 @@ class TestDebugReplayManagerPublishCamera(unittest.TestCase):
|
||||
publisher.publish_update.assert_not_called()
|
||||
|
||||
|
||||
class TestDebugReplayManagerLifecycle(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
patcher = patch("frigate.debug_replay.JobStatePublisher")
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def _publish(self, manager, frigate_config, publisher) -> bool:
|
||||
from frigate.debug_replay import DebugReplayManager
|
||||
|
||||
parsed = MagicMock()
|
||||
parsed.cameras = {"_replay_front": MagicMock(name="replay_camera")}
|
||||
|
||||
with (
|
||||
patch.object(
|
||||
DebugReplayManager,
|
||||
"_build_camera_config_dict",
|
||||
return_value={"enabled": True},
|
||||
),
|
||||
patch("frigate.debug_replay.find_config_file", return_value="/cfg.yml"),
|
||||
patch("frigate.debug_replay.YAML") as yaml_cls,
|
||||
patch(
|
||||
"frigate.debug_replay.FrigateConfig.parse_object",
|
||||
return_value=parsed,
|
||||
),
|
||||
patch("builtins.open", unittest.mock.mock_open(read_data="cameras:\n")),
|
||||
):
|
||||
yaml_cls.return_value.load.return_value = {"cameras": {}}
|
||||
return manager.publish_camera(
|
||||
source_camera="front",
|
||||
replay_name="_replay_front",
|
||||
clip_path="/tmp/clip.mp4",
|
||||
frigate_config=frigate_config,
|
||||
config_publisher=publisher,
|
||||
)
|
||||
|
||||
def _config(self, name: str) -> MagicMock:
|
||||
config = MagicMock(name=name)
|
||||
config.cameras = {"front": MagicMock()}
|
||||
return config
|
||||
|
||||
def _stop(self, manager, frigate_config, publisher) -> None:
|
||||
with (
|
||||
patch.object(manager, "_cleanup_db"),
|
||||
patch.object(manager, "_cleanup_files"),
|
||||
patch("frigate.debug_replay.cancel_debug_replay_job", return_value=False),
|
||||
):
|
||||
manager.stop(frigate_config=frigate_config, config_publisher=publisher)
|
||||
|
||||
def test_publish_after_stop_is_skipped(self) -> None:
|
||||
from frigate.debug_replay import DebugReplayManager
|
||||
|
||||
manager = DebugReplayManager()
|
||||
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
|
||||
config = self._config("live")
|
||||
publisher = MagicMock()
|
||||
|
||||
self._stop(manager, config, publisher)
|
||||
|
||||
self.assertFalse(self._publish(manager, config, publisher))
|
||||
self.assertNotIn("_replay_front", config.cameras)
|
||||
publisher.publish_update.assert_not_called()
|
||||
|
||||
def test_config_swap_keeps_replay_camera_and_stop_removes_it(self) -> None:
|
||||
from frigate.config.camera.updater import CameraConfigUpdateEnum
|
||||
from frigate.debug_replay import DebugReplayManager
|
||||
|
||||
manager = DebugReplayManager()
|
||||
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
|
||||
boot = self._config("boot")
|
||||
publisher = MagicMock()
|
||||
self.assertTrue(self._publish(manager, boot, publisher))
|
||||
|
||||
swapped = self._config("swapped")
|
||||
manager.update_config(swapped)
|
||||
self.assertIn("_replay_front", swapped.cameras)
|
||||
|
||||
self._stop(manager, swapped, publisher)
|
||||
|
||||
topic = publisher.publish_update.call_args.args[0]
|
||||
self.assertEqual(topic.update_type, CameraConfigUpdateEnum.remove)
|
||||
self.assertNotIn("_replay_front", swapped.cameras)
|
||||
|
||||
def test_stop_with_stale_config_still_publishes_remove(self) -> None:
|
||||
from frigate.config.camera.updater import CameraConfigUpdateEnum
|
||||
from frigate.debug_replay import DebugReplayManager
|
||||
|
||||
manager = DebugReplayManager()
|
||||
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
|
||||
live = self._config("live")
|
||||
publisher = MagicMock()
|
||||
self.assertTrue(self._publish(manager, live, publisher))
|
||||
|
||||
self._stop(manager, self._config("stale"), publisher)
|
||||
|
||||
topic = publisher.publish_update.call_args.args[0]
|
||||
self.assertEqual(topic.update_type, CameraConfigUpdateEnum.remove)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -302,7 +302,7 @@ class TestRunnerHappyPath(unittest.TestCase):
|
||||
patch.object(
|
||||
self.manager,
|
||||
"publish_camera",
|
||||
side_effect=lambda *a, **kw: captured.append("published") or True,
|
||||
side_effect=lambda *a, **kw: captured.append("published"),
|
||||
),
|
||||
patch("os.path.exists", return_value=True),
|
||||
patch("os.makedirs"),
|
||||
|
||||
@@ -221,24 +221,6 @@ class TestFfmpegProgressParsing(unittest.TestCase):
|
||||
assert any(abs(p - (30 / 90 * 100)) < 0.01 for p in encoding_percents)
|
||||
|
||||
|
||||
class TestExportJobManagerConfig(unittest.TestCase):
|
||||
def test_manager_follows_the_config_passed_by_callers(self) -> None:
|
||||
import frigate.jobs.export as export_jobs
|
||||
|
||||
boot = MagicMock(name="boot")
|
||||
swapped = MagicMock(name="swapped")
|
||||
|
||||
with (
|
||||
patch.object(export_jobs, "_job_manager", None),
|
||||
patch.object(export_jobs.ExportJobManager, "ensure_started"),
|
||||
patch.object(export_jobs, "_get_max_concurrent", return_value=1),
|
||||
):
|
||||
export_jobs.get_export_job_manager(boot)
|
||||
manager = export_jobs.get_export_job_manager(swapped)
|
||||
|
||||
self.assertIs(manager.config, swapped)
|
||||
|
||||
|
||||
class TestBroadcastAggregation(unittest.TestCase):
|
||||
"""Verify ExportJobManager broadcast payload shape and throttling."""
|
||||
|
||||
|
||||
@@ -95,6 +95,42 @@ class TestProxyRoleResolution(unittest.TestCase):
|
||||
role = resolve_role(headers, self.proxy_config, self.config_roles)
|
||||
self.assertEqual(role, self.proxy_config.default_role)
|
||||
|
||||
def test_custom_role_direct_header_ignores_case(self):
|
||||
config = self.proxy_config
|
||||
config.header_map.role_map = None
|
||||
headers = {"x-remote-role": "garage"}
|
||||
role = resolve_role(headers, config, ["admin", "viewer", "Garage"])
|
||||
self.assertEqual(role, "Garage")
|
||||
|
||||
def test_role_map_to_missing_role_denies(self):
|
||||
"""A group mapped to a deleted role must not widen to default_role."""
|
||||
self.proxy_config.header_map.role_map = {"garage": ["group_garage"]}
|
||||
headers = {"x-remote-role": "group_garage"}
|
||||
role = resolve_role(headers, self.proxy_config, self.config_roles)
|
||||
self.assertEqual(role, "none")
|
||||
|
||||
def test_unknown_default_role_denies(self):
|
||||
for default in ("operatr", None):
|
||||
with self.subTest(default_role=default):
|
||||
config = ProxyConfig(
|
||||
default_role=default,
|
||||
header_map=HeaderMappingConfig(role="x-remote-role"),
|
||||
)
|
||||
role = resolve_role({}, config, self.config_roles)
|
||||
self.assertEqual(role, "none")
|
||||
|
||||
def test_default_role_and_role_map_ignore_case(self):
|
||||
roles = ["admin", "viewer", "Garage"]
|
||||
config = ProxyConfig(
|
||||
default_role="garage",
|
||||
header_map=HeaderMappingConfig(
|
||||
role="x-remote-role", role_map={"GARAGE": ["group_garage"]}
|
||||
),
|
||||
)
|
||||
self.assertEqual(resolve_role({}, config, roles), "Garage")
|
||||
headers = {"x-remote-role": "group_garage"}
|
||||
self.assertEqual(resolve_role(headers, config, roles), "Garage")
|
||||
|
||||
|
||||
class TestDefaultRoleNone(unittest.TestCase):
|
||||
def setUp(self):
|
||||
@@ -190,6 +226,9 @@ class TestDefaultRoleNone(unittest.TestCase):
|
||||
)
|
||||
self.assertEqual(role, "none")
|
||||
|
||||
def test_null_default_role_normalizes_to_none(self):
|
||||
self.assertEqual(ProxyConfig(default_role=None).default_role, "none")
|
||||
|
||||
def test_other_role_names_stay_case_sensitive(self):
|
||||
"""Only the deny sentinel is normalized; role names are untouched."""
|
||||
config = ProxyConfig(default_role="Operator")
|
||||
@@ -221,8 +260,18 @@ class TestReservedRoleNames(unittest.TestCase):
|
||||
with self.assertRaises(ValidationError):
|
||||
AuthConfig(roles={name: ["front_door"]})
|
||||
|
||||
def test_admin_and_viewer_reserved_in_every_casing(self):
|
||||
for name in ("Admin", "VIEWER"):
|
||||
with self.subTest(role=name):
|
||||
with self.assertRaises(ValidationError):
|
||||
AuthConfig(roles={name: ["front_door"]})
|
||||
|
||||
def test_role_names_differing_only_by_case_rejected(self):
|
||||
with self.assertRaises(ValidationError):
|
||||
AuthConfig(roles={"garage": ["front_door"], "Garage": ["back"]})
|
||||
|
||||
def test_case_variant_of_a_normal_role_still_allowed(self):
|
||||
"""Only 'none' folds case; other role names are untouched."""
|
||||
"""A mixed-case custom name is fine when it is not reserved."""
|
||||
config = AuthConfig(roles={"Operator": ["front_door"]})
|
||||
self.assertEqual(config.roles["Operator"], ["front_door"])
|
||||
|
||||
|
||||
@@ -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()
|
||||
@@ -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
|
||||
|
||||
@@ -61,7 +61,9 @@ export default function CreateRoleDialog({
|
||||
(config.cameras[b]?.ui?.order ?? 0),
|
||||
);
|
||||
|
||||
const existingRoles = Object.keys(config.auth?.roles || {});
|
||||
const existingRoles = Object.keys(config.auth?.roles || {}).map((role) =>
|
||||
role.toLowerCase(),
|
||||
);
|
||||
|
||||
const formSchema = z.object({
|
||||
role: z
|
||||
@@ -70,7 +72,7 @@ export default function CreateRoleDialog({
|
||||
.regex(/^[A-Za-z0-9._]+$/, {
|
||||
message: t("roles.dialog.form.role.roleOnlyInclude"),
|
||||
})
|
||||
.refine((role) => !existingRoles.includes(role), {
|
||||
.refine((role) => !existingRoles.includes(role.toLowerCase()), {
|
||||
message: t("roles.dialog.form.role.roleExists"),
|
||||
}),
|
||||
cameras: z
|
||||
|
||||
@@ -16,8 +16,7 @@ export function processCameraName(userInput: string): {
|
||||
} {
|
||||
const normalizedInput = userInput.replace(/\s+/g, "_").toLowerCase();
|
||||
|
||||
// debug replay owns this prefix and deletes data for cameras that use it
|
||||
if (isValidId(normalizedInput) && !isReplayCamera(normalizedInput)) {
|
||||
if (isValidId(normalizedInput)) {
|
||||
return {
|
||||
finalCameraName: normalizedInput,
|
||||
friendlyName: userInput.includes(" ") ? userInput : undefined,
|
||||
|
||||
Reference in New Issue
Block a user