NVR with realtime local object detection for IP cameras
TypeScript aicameragoogle-coralhome-assistanthome-automationhomeautomationmqttnvrobject-detectionrealtimertsptensorflow
Merge remote-tracking branch 'origin/master' into dev
Blake Blackshear59f570f4360b
diff --cc docs/docs/configuration/genai/config.mdindex 67bbb9fe44,cde503e8b1..4026158b7e--- a/docs/docs/configuration/genai/config.md+++ b/docs/docs/configuration/genai/config.md@@@ -220,7 -142,30 +220,30 @@@ genaimodel: gpt-4o```+ :::note++ To use a different OpenAI-compatible API endpoint, set the `OPENAI_BASE_URL` environment variable to your provider's API URL.++ :::++ :::tip++ For OpenAI-compatible servers (such as llama.cpp) that don't expose the configured context size in the API response, you can manually specify the context size in `provider_options`:++ ```yaml {5,6}+ genai:+ provider: openai+ base_url: http://your-llama-server+ model: your-model-name+ provider_options:+ context_size: 8192 # Specify the configured context size+ ```++ This ensures Frigate uses the correct context window size when generating prompts.++ :::+-## Azure OpenAI+### Azure OpenAIMicrosoft offers several vision models through Azure OpenAI. A subscription is required.diff --cc docs/docs/guides/configuring_go2rtc.mdindex 8b01de3e7a,2dbbccada6..4d632fdd6c--- a/docs/docs/guides/configuring_go2rtc.md+++ b/docs/docs/guides/configuring_go2rtc.md@@@ -45,10 -43,9 +43,9 @@@ After adding this to the config, restar- Click `stream` for the specific camera to see if the camera's stream is being received.- Check Video Codec:-- If the camera stream works in go2rtc but not in your browser, the video codec might be unsupported.- - If using H265, switch to H264. Refer to [video codec compatibility](https://github.com/AlexxIT/go2rtc/tree/v1.9.10#codecs-madness) in go2rtc documentation.- - If unable to switch from H265 to H264, or if the stream format is different (e.g., MJPEG), re-encode the video using [FFmpeg parameters](https://github.com/AlexxIT/go2rtc/tree/v1.9.10#source-ffmpeg). It supports rotating and resizing video feeds and hardware acceleration. Keep in mind that transcoding video from one format to another is a resource intensive task and you may be better off using the built-in jsmpeg view.+ - If using H265, switch to H264. Refer to [video codec compatibility](https://github.com/AlexxIT/go2rtc/tree/v1.9.13#codecs-madness) in go2rtc documentation.+ - If unable to switch from H265 to H264, or if the stream format is different (e.g., MJPEG), re-encode the video using [FFmpeg parameters](https://github.com/AlexxIT/go2rtc/tree/v1.9.13#source-ffmpeg). It supports rotating and resizing video feeds and hardware acceleration. Keep in mind that transcoding video from one format to another is a resource intensive task and you may be better off using the built-in jsmpeg view.```yamlgo2rtc:streams:diff --cc frigate/api/camera.pyindex c99126e64e,a94486d8c2..e79864d66f--- a/frigate/api/camera.py+++ b/frigate/api/camera.py@@@ -20,19 -17,12 +20,19 @@@ from zeep.transports import AsyncTranspfrom frigate.api.auth import (allow_any_authenticated,- require_camera_access,+ require_go2rtc_stream_access,require_role,)+from frigate.api.defs.request.app_body import CameraSetBodyfrom frigate.api.defs.tags import Tags-from frigate.config.config import FrigateConfig+from frigate.config import FrigateConfig+from frigate.config.camera.updater import (+ CameraConfigUpdateEnum,+ CameraConfigUpdateTopic,+)from frigate.util.builtin import clean_camera_user_pass+from frigate.util.camera_cleanup import cleanup_camera_db, cleanup_camera_files+from frigate.util.config import find_config_filefrom frigate.util.image import run_ffmpeg_snapshotfrom frigate.util.services import ffprobe_streamdiff --cc frigate/api/media.pyindex 7d6c162696,dad7a3d87d..28585bdd55--- a/frigate/api/media.py+++ b/frigate/api/media.py@@@ -41,17 -43,15 +41,18 @@@ from frigate.const importINSTALL_DIR,MAX_SEGMENT_DURATION,PREVIEW_FRAME_TYPE,- RECORD_DIR,)from frigate.models import Event, Previews, Recordings, Regions, ReviewSegment+from frigate.output.preview import get_most_recent_preview_framefrom frigate.track.object_processing import TrackedObjectProcessor-from frigate.util.file import get_event_thumbnail_bytes-from frigate.util.image import get_image_from_recording+from frigate.util.file import (+ get_event_snapshot_bytes,+ get_event_snapshot_path,+ get_event_thumbnail_bytes,+ load_event_snapshot_image,+)+from frigate.util.image import get_image_from_recording, get_image_quality_params+ from frigate.util.media import get_keyframe_before-from frigate.util.time import get_dst_transitionslogger = logging.getLogger(__name__)@@@ -1034,33 -1341,14 +1065,33 @@@ def grid_snapshot)+ "/{camera_name}/region_grid", dependencies=[Depends(require_role("admin"))]+)+def clear_region_grid(request: Request, camera_name: str):+ """Clear the region grid for a camera."""+ if camera_name not in request.app.frigate_config.cameras:+ return JSONResponse(+ content={"success": False, "message": "Camera not found"},+ status_code=404,+ )++ Regions.delete().where(Regions.camera == camera_name).execute()+ return JSONResponse(+ content={"success": True, "message": "Region grid cleared"},+ )++@router.get("/events/{event_id}/snapshot-clean.webp",- dependencies=[Depends(require_camera_access)],)- def event_snapshot_clean(request: Request, event_id: str, download: bool = False):+ async def event_snapshot_clean(request: Request, event_id: str, download: bool = False):webp_bytes = None+ event_complete = Falsetry:event = Event.get(Event.id == event_id)+ event_complete = event.end_time is not None+ await require_camera_access(event.camera, request=request)snapshot_config = request.app.frigate_config.cameras[event.camera].snapshotsif not (snapshot_config.enabled and event.has_snapshot):return JSONResponse(diff --cc frigate/config/camera/onvif.pyindex c5f1e19f33,fd35fa5377..eb21e24bd1--- a/frigate/config/camera/onvif.py+++ b/frigate/config/camera/onvif.py@@@ -92,35 -72,14 +92,35 @@@ class PtzAutotrackConfig(FrigateBaseModclass OnvifConfig(FrigateBaseModel):- host: str = Field(- host: EnvString = Field(default="", title="Onvif Host")- port: int = Field(default=8000, title="Onvif Port")- user: Optional[EnvString] = Field(default=None, title="Onvif Username")- password: Optional[EnvString] = Field(default=None, title="Onvif Password")- tls_insecure: bool = Field(default=False, title="Onvif Disable TLS verification")++ host: EnvString = Field(+ default="",+ title="ONVIF host",+ description="Host (and optional scheme) for the ONVIF service for this camera.",+ )+ port: int = Field(+ default=8000,+ title="ONVIF port",+ description="Port number for the ONVIF service.",+ )+ user: Optional[EnvString] = Field(+ default=None,+ title="ONVIF username",+ description="Username for ONVIF authentication; some devices require admin user for ONVIF.",+ )+ password: Optional[EnvString] = Field(+ default=None,+ title="ONVIF password",+ description="Password for ONVIF authentication.",+ )+ tls_insecure: bool = Field(+ default=False,+ title="Disable TLS verify",+ description="Skip TLS verification and disable digest auth for ONVIF (unsafe; use in safe networks only).",+ )autotracking: PtzAutotrackConfig = Field(default_factory=PtzAutotrackConfig,- title="PTZ auto tracking config.",+ title="Autotracking",+ description="Automatically track moving objects and keep them centered in the frame using PTZ camera movements.",)ignore_time_mismatch: bool = Field(default=False,diff --cc frigate/config/mqtt.pyindex abd5c74b28,3e2f992949..becbe7e69a--- a/frigate/config/mqtt.py+++ b/frigate/config/mqtt.py@@@ -12,73 -12,25 +12,73 @@@ __all__ = ["MqttConfig"class MqttConfig(FrigateBaseModel):- enabled: bool = Field(default=True, title="Enable MQTT Communication.")- host: EnvString = Field(default="", title="MQTT Host")- port: int = Field(default=1883, title="MQTT Port")- topic_prefix: str = Field(default="frigate", title="MQTT Topic Prefix")- client_id: str = Field(default="frigate", title="MQTT Client ID")+ enabled: bool = Field(+ default=True,+ title="Enable MQTT",+ description="Enable or disable MQTT integration for state, events, and snapshots.",+ )- host: str = Field(++ host: EnvString = Field(+ default="",+ title="MQTT host",+ description="Hostname or IP address of the MQTT broker.",+ )+ port: int = Field(+ default=1883,+ title="MQTT port",+ description="Port of the MQTT broker (usually 1883 for plain MQTT).",+ )+ topic_prefix: str = Field(+ default="frigate",+ title="Topic prefix",+ description="MQTT topic prefix for all Frigate topics; must be unique if running multiple instances.",+ )+ client_id: str = Field(+ default="frigate",+ title="Client ID",+ description="Client identifier used when connecting to the MQTT broker; should be unique per instance.",+ )stats_interval: int = Field(- default=60, ge=FREQUENCY_STATS_POINTS, title="MQTT Camera Stats Interval"+ default=60,+ ge=FREQUENCY_STATS_POINTS,+ title="Stats interval",+ description="Interval in seconds for publishing system and camera stats to MQTT.",+ )+ user: Optional[EnvString] = Field(+ default=None,+ title="MQTT username",+ description="Optional MQTT username; can be provided via environment variables or secrets.",)- user: Optional[EnvString] = Field(default=None, title="MQTT Username")password: Optional[EnvString] = Field(- default=None, title="MQTT Password", validate_default=True+ default=None,+ title="MQTT password",+ description="Optional MQTT password; can be provided via environment variables or secrets.",+ validate_default=True,+ )+ tls_ca_certs: Optional[str] = Field(+ default=None,+ title="TLS CA certs",+ description="Path to CA certificate for TLS connections to the broker (for self-signed certs).",)- tls_ca_certs: Optional[str] = Field(default=None, title="MQTT TLS CA Certificates")tls_client_cert: Optional[str] = Field(- default=None, title="MQTT TLS Client Certificate"+ default=None,+ title="Client cert",+ description="Client certificate path for TLS mutual authentication; do not set user/password when using client certs.",+ )+ tls_client_key: Optional[str] = Field(+ default=None,+ title="Client key",+ description="Private key path for the client certificate.",+ )+ tls_insecure: Optional[bool] = Field(+ default=None,+ title="TLS insecure",+ description="Allow insecure TLS connections by skipping hostname verification (not recommended).",+ )+ qos: int = Field(+ default=0,+ title="MQTT QoS",+ description="Quality of Service level for MQTT publishes/subscriptions (0, 1, or 2).",)- tls_client_key: Optional[str] = Field(default=None, title="MQTT TLS Client Key")- tls_insecure: Optional[bool] = Field(default=None, title="MQTT TLS Insecure")- qos: int = Field(default=0, title="MQTT QoS")@model_validator(mode="after")def user_requires_pass(self, info: ValidationInfo) -> Self:diff --cc frigate/record/cleanup.pyindex 15a0ba7e81,0e401e8fff..9122934a17--- a/frigate/record/cleanup.py+++ b/frigate/record/cleanup.py@@@ -365,9 -349,16 +365,14 @@@ class RecordingCleanup(threading.Threadlogger.debug("End all cameras.")logger.debug("End expire recordings.")+ return maybe_empty_dirs+def run(self) -> None:+++ if self.config.safe_mode:+ logger.info("Safe mode enabled, skipping recording cleanup")+ return+- # on startup sync recordings with disk if enabled- if self.config.record.sync_recordings:- sync_recordings(limited=False)- next_sync = get_tomorrow_at_time(3)-# Expire tmp clips every minute, recordings and clean directories every hour.for counter in itertools.cycle(range(self.config.record.expire_interval)):if self.stop_event.wait(60):diff --cc frigate/util/media.pyindex f6103a2881,406d51cf3c..f3701f4008--- a/frigate/util/media.py+++ b/frigate/util/media.py@@@ -1,810 -1,61 +1,873 @@@-"""Utilities for media file inspection."""+"""Recordings Utilities."""+import datetime+import errno+import logging+import os+ import subprocess as sp+from dataclasses import dataclass, field+from pathlib import Path+from typing import Iterable-from frigate.const import DEFAULT_FFMPEG_VERSION+from peewee import DatabaseError, chunked+- from frigate.const import CLIPS_DIR, EXPORT_DIR, RECORD_DIR, THUMB_DIR++from frigate.const import (++ CLIPS_DIR,++ DEFAULT_FFMPEG_VERSION,++ EXPORT_DIR,++ RECORD_DIR,++ THUMB_DIR,++)+from frigate.models import (+ Event,+ Export,+ Previews,+ Recordings,+ RecordingsToDelete,+ ReviewSegment,+)++logger = logging.getLogger(__name__)+++# Safety threshold - abort if more than 50% of files would be deleted+SAFETY_THRESHOLD = 0.5+ FFPROBE_PATH = (+ f"/usr/lib/ffmpeg/{DEFAULT_FFMPEG_VERSION}/bin/ffprobe"+ if DEFAULT_FFMPEG_VERSION+ else "ffprobe"+ )++@dataclass+class SyncResult:+ """Result of a sync operation."""++ media_type: str+ files_checked: int = 0+ orphans_found: int = 0+ orphans_deleted: int = 0+ orphan_paths: list[str] = field(default_factory=list)+ aborted: bool = False+ error: str | None = None++ def to_dict(self) -> dict:+ return {+ "media_type": self.media_type,+ "files_checked": self.files_checked,+ "orphans_found": self.orphans_found,+ "orphans_deleted": self.orphans_deleted,+ "aborted": self.aborted,+ "error": self.error,+ }+++def remove_empty_directories(root: Path, paths: Iterable[Path]) -> None:+ """+ Remove directories if they exist and are empty.+ Silently ignores non-existent and non-empty directories.+ Attempts to remove parent directories as well, stopping at the given root.+ """+ count = 0+ while True:+ parents = set()+ for path in paths:+ if path == root:+ continue++ try:+ path.rmdir()+ count += 1+ except FileNotFoundError:+ pass+ except OSError as e:+ if e.errno == errno.ENOTEMPTY:+ continue+ raise++ parents.add(path.parent)++ if not parents:+ break++ paths = parents++ logger.debug("Removed {count} empty directories")+++def sync_recordings(+ limited: bool = False, dry_run: bool = False, force: bool = False+) -> SyncResult:+ """Sync recordings between the database and disk using the SyncResult format."""++ result = SyncResult(media_type="recordings")++ try:+ logger.debug("Start sync recordings.")++ # start checking on the hour 36 hours ago+ check_point = datetime.datetime.now().replace(+ minute=0, second=0, microsecond=0+ ).astimezone(datetime.timezone.utc) - datetime.timedelta(hours=36)++ # Gather DB recordings to inspect+ if limited:+ recordings_query = Recordings.select(Recordings.id, Recordings.path).where(+ Recordings.start_time >= check_point.timestamp()+ )+ else:+ recordings_query = Recordings.select(Recordings.id, Recordings.path)++ recordings_count = recordings_query.count()+ page_size = 1000+ num_pages = (recordings_count + page_size - 1) // page_size+ recordings_to_delete: list[dict] = []++ for page in range(num_pages):+ for recording in recordings_query.paginate(page, page_size):+ if not os.path.exists(recording.path):+ recordings_to_delete.append(+ {"id": recording.id, "path": recording.path}+ )++ result.orphans_found += len(recordings_to_delete)+ result.orphan_paths.extend(+ [+ recording["path"]+ for recording in recordings_to_delete+ if recording.get("path")+ ]+ )++ if (+ recordings_count+ and len(recordings_to_delete) / recordings_count > SAFETY_THRESHOLD+ ):+ if force:+ logger.warning(+ f"Deleting {(len(recordings_to_delete) / max(1, recordings_count) * 100):.2f}% of recordings DB entries (force=True, bypassing safety threshold)"+ )+ else:+ logger.warning(+ f"Deleting {(len(recordings_to_delete) / max(1, recordings_count) * 100):.2f}% of recordings DB entries, could be due to configuration error. Aborting..."+ )+ result.aborted = True+ return result++ if recordings_to_delete and not dry_run:+ logger.info(+ f"Deleting {len(recordings_to_delete)} recording DB entries with missing files"+ )++ RecordingsToDelete.create_table(temporary=True)++ max_inserts = 1000+ for batch in chunked(recordings_to_delete, max_inserts):+ RecordingsToDelete.insert_many(+ [{"id": r["id"]} for r in batch]+ ).execute()++ try:+ deleted = (+ Recordings.delete()+ .where(+ Recordings.id.in_(+ RecordingsToDelete.select(RecordingsToDelete.id)+ )+ )+ .execute()+ )+ result.orphans_deleted += int(deleted)+ except DatabaseError as e:+ logger.error(f"Database error during recordings db cleanup: {e}")+ result.error = str(e)+ result.aborted = True+ return result++ if result.aborted:+ logger.warning("Recording DB sync aborted; skipping file cleanup.")+ return result++ # Only try to cleanup files if db cleanup was successful or dry_run+ if limited:+ # get recording files from last 36 hours+ hour_check = f"{RECORD_DIR}/{check_point.strftime('%Y-%m-%d/%H')}"+ files_on_disk = {+ os.path.join(root, file)+ for root, _, files in os.walk(RECORD_DIR)+ for file in files+ if root > hour_check+ }+ else:+ # get all recordings files on disk and put them in a set+ files_on_disk = {+ os.path.join(root, file)+ for root, _, files in os.walk(RECORD_DIR)+ for file in files+ }++ result.files_checked = len(files_on_disk)++ files_to_delete: list[str] = []+ for file in files_on_disk:+ if not Recordings.select().where(Recordings.path == file).exists():+ files_to_delete.append(file)++ result.orphans_found += len(files_to_delete)+ result.orphan_paths.extend(files_to_delete)++ if (+ files_on_disk+ and len(files_to_delete) / len(files_on_disk) > SAFETY_THRESHOLD+ ):+ if force:+ logger.warning(+ f"Deleting {(len(files_to_delete) / max(1, len(files_on_disk)) * 100):.2f}% of recordings files (force=True, bypassing safety threshold)"+ )+ else:+ logger.warning(+ f"Deleting {(len(files_to_delete) / max(1, len(files_on_disk)) * 100):.2f}% of recordings files, could be due to configuration error. Aborting..."+ )+ result.aborted = True+ return result++ if dry_run:+ logger.info(+ f"Recordings sync (dry run): Found {len(files_to_delete)} orphaned files"+ )+ return result++ # Delete orphans+ logger.info(f"Deleting {len(files_to_delete)} orphaned recordings files")+ for file in files_to_delete:+ try:+ os.unlink(file)+ result.orphans_deleted += 1+ except OSError as e:+ logger.error(f"Failed to delete {file}: {e}")++ logger.debug("End sync recordings.")++ except Exception as e:+ logger.error(f"Error syncing recordings: {e}")+ result.error = str(e)++ return result+++def sync_event_snapshots(dry_run: bool = False, force: bool = False) -> SyncResult:+ """Sync event snapshots - delete files not referenced by any event.++ Event snapshots are stored at: CLIPS_DIR/{camera}-{event_id}-clean.webp+ Also checks legacy variants: {camera}-{event_id}.jpg and -clean.png+ """+ result = SyncResult(media_type="event_snapshots")++ try:+ # Get all event IDs with snapshots from DB+ events_with_snapshots = set(+ f"{e.camera}-{e.id}"+ for e in Event.select(Event.id, Event.camera).where(+ Event.has_snapshot == True+ )+ )++ # Find snapshot files on disk (directly in CLIPS_DIR, not subdirectories)+ snapshot_files: list[tuple[str, str]] = [] # (full_path, base_name)+ if os.path.isdir(CLIPS_DIR):+ for file in os.listdir(CLIPS_DIR):+ file_path = os.path.join(CLIPS_DIR, file)+ if os.path.isfile(file_path) and file.endswith(+ (".jpg", "-clean.webp", "-clean.png")+ ):+ # Extract base name (camera-event_id) from filename+ base_name = file+ for suffix in ["-clean.webp", "-clean.png", ".jpg"]:+ if file.endswith(suffix):+ base_name = file[: -len(suffix)]+ break+ snapshot_files.append((file_path, base_name))++ result.files_checked = len(snapshot_files)++ # Find orphans+ orphans: list[str] = []+ for file_path, base_name in snapshot_files:+ if base_name not in events_with_snapshots:+ orphans.append(file_path)++ result.orphans_found = len(orphans)+ result.orphan_paths = orphans++ if len(orphans) == 0:+ return result++ # Safety check+ if (+ result.files_checked > 0+ and len(orphans) / result.files_checked > SAFETY_THRESHOLD+ ):+ if force:+ logger.warning(+ f"Event snapshots sync: Would delete {len(orphans)}/{result.files_checked} "+ f"({len(orphans) / result.files_checked * 100:.2f}%) files (force=True, bypassing safety threshold)."+ )+ else:+ logger.warning(+ f"Event snapshots sync: Would delete {len(orphans)}/{result.files_checked} "+ f"({len(orphans) / result.files_checked * 100:.2f}%) files. "+ "Aborting due to safety threshold."+ )+ result.aborted = True+ return result++ if dry_run:+ logger.info(+ f"Event snapshots sync (dry run): Found {len(orphans)} orphaned files"+ )+ return result++ # Delete orphans+ logger.info(f"Deleting {len(orphans)} orphaned event snapshot files")+ for file_path in orphans:+ try:+ os.unlink(file_path)+ result.orphans_deleted += 1+ except OSError as e:+ logger.error(f"Failed to delete {file_path}: {e}")++ except Exception as e:+ logger.error(f"Error syncing event snapshots: {e}")+ result.error = str(e)++ return result+++def sync_event_thumbnails(dry_run: bool = False, force: bool = False) -> SyncResult:+ """Sync event thumbnails - delete files not referenced by any event.++ Event thumbnails are stored at: THUMB_DIR/{camera}/{event_id}.webp+ Only events without inline thumbnail (thumbnail field is None/empty) use files.+ """+ result = SyncResult(media_type="event_thumbnails")++ try:+ # Get all events that use file-based thumbnails+ # Events with thumbnail field populated don't need files+ events_with_file_thumbs = set(+ (e.camera, e.id)+ for e in Event.select(Event.id, Event.camera, Event.thumbnail).where(+ (Event.thumbnail.is_null(True)) | (Event.thumbnail == "")+ )+ )++ # Find thumbnail files on disk+ thumbnail_files: list[+ tuple[str, str, str]+ ] = [] # (full_path, camera, event_id)+ if os.path.isdir(THUMB_DIR):+ for camera_dir in os.listdir(THUMB_DIR):+ camera_path = os.path.join(THUMB_DIR, camera_dir)+ if not os.path.isdir(camera_path):+ continue+ for file in os.listdir(camera_path):+ if file.endswith(".webp"):+ event_id = file[:-5] # Remove .webp+ file_path = os.path.join(camera_path, file)+ thumbnail_files.append((file_path, camera_dir, event_id))++ result.files_checked = len(thumbnail_files)++ # Find orphans - files where event doesn't exist or event has inline thumbnail+ orphans: list[str] = []+ for file_path, camera, event_id in thumbnail_files:+ if (camera, event_id) not in events_with_file_thumbs:+ # Check if event exists with inline thumbnail+ event_exists = Event.select().where(Event.id == event_id).exists()+ if not event_exists:+ orphans.append(file_path)+ # If event exists with inline thumbnail, the file is also orphaned+ elif event_exists:+ event = Event.get_or_none(Event.id == event_id)+ if event and event.thumbnail:+ orphans.append(file_path)++ result.orphans_found = len(orphans)+ result.orphan_paths = orphans++ if len(orphans) == 0:+ return result++ # Safety check+ if (+ result.files_checked > 0+ and len(orphans) / result.files_checked > SAFETY_THRESHOLD+ ):+ if force:+ logger.warning(+ f"Event thumbnails sync: Would delete {len(orphans)}/{result.files_checked} "+ f"({len(orphans) / result.files_checked * 100:.2f}%) files (force=True, bypassing safety threshold)."+ )+ else:+ logger.warning(+ f"Event thumbnails sync: Would delete {len(orphans)}/{result.files_checked} "+ f"({len(orphans) / result.files_checked * 100:.2f}%) files. "+ "Aborting due to safety threshold."+ )+ result.aborted = True+ return result++ if dry_run:+ logger.info(+ f"Event thumbnails sync (dry run): Found {len(orphans)} orphaned files"+ )+ return result++ # Delete orphans+ logger.info(f"Deleting {len(orphans)} orphaned event thumbnail files")+ for file_path in orphans:+ try:+ os.unlink(file_path)+ result.orphans_deleted += 1+ except OSError as e:+ logger.error(f"Failed to delete {file_path}: {e}")++ except Exception as e:+ logger.error(f"Error syncing event thumbnails: {e}")+ result.error = str(e)++ return result+++def sync_review_thumbnails(dry_run: bool = False, force: bool = False) -> SyncResult:+ """Sync review segment thumbnails - delete files not referenced by any review segment.++ Review thumbnails are stored at: CLIPS_DIR/review/thumb-{camera}-{review_id}.webp+ The full path is stored in ReviewSegment.thumb_path+ """+ result = SyncResult(media_type="review_thumbnails")++ try:+ # Get all thumb paths from DB+ review_thumb_paths = set(+ r.thumb_path+ for r in ReviewSegment.select(ReviewSegment.thumb_path)+ if r.thumb_path+ )++ # Find review thumbnail files on disk+ review_dir = os.path.join(CLIPS_DIR, "review")+ thumbnail_files: list[str] = []+ if os.path.isdir(review_dir):+ for file in os.listdir(review_dir):+ if file.startswith("thumb-") and file.endswith(".webp"):+ file_path = os.path.join(review_dir, file)+ thumbnail_files.append(file_path)++ result.files_checked = len(thumbnail_files)++ # Find orphans+ orphans: list[str] = []+ for file_path in thumbnail_files:+ if file_path not in review_thumb_paths:+ orphans.append(file_path)++ result.orphans_found = len(orphans)+ result.orphan_paths = orphans++ if len(orphans) == 0:+ return result++ # Safety check+ if (+ result.files_checked > 0+ and len(orphans) / result.files_checked > SAFETY_THRESHOLD+ ):+ if force:+ logger.warning(+ f"Review thumbnails sync: Would delete {len(orphans)}/{result.files_checked} "+ f"({len(orphans) / result.files_checked * 100:.2f}%) files (force=True, bypassing safety threshold)."+ )+ else:+ logger.warning(+ f"Review thumbnails sync: Would delete {len(orphans)}/{result.files_checked} "+ f"({len(orphans) / result.files_checked * 100:.2f}%) files. "+ "Aborting due to safety threshold."+ )+ result.aborted = True+ return result++ if dry_run:+ logger.info(+ f"Review thumbnails sync (dry run): Found {len(orphans)} orphaned files"+ )+ return result++ # Delete orphans+ logger.info(f"Deleting {len(orphans)} orphaned review thumbnail files")+ for file_path in orphans:+ try:+ os.unlink(file_path)+ result.orphans_deleted += 1+ except OSError as e:+ logger.error(f"Failed to delete {file_path}: {e}")++ except Exception as e:+ logger.error(f"Error syncing review thumbnails: {e}")+ result.error = str(e)++ return result+++def sync_previews(dry_run: bool = False, force: bool = False) -> SyncResult:+ """Sync preview files - delete files not referenced by any preview record.++ Previews are stored at: CLIPS_DIR/previews/{camera}/*.mp4+ The full path is stored in Previews.path+ """+ result = SyncResult(media_type="previews")++ try:+ # Get all preview paths from DB+ preview_paths = set(p.path for p in Previews.select(Previews.path) if p.path)++ # Find preview files on disk+ previews_dir = os.path.join(CLIPS_DIR, "previews")+ preview_files: list[str] = []+ if os.path.isdir(previews_dir):+ for camera_dir in os.listdir(previews_dir):+ camera_path = os.path.join(previews_dir, camera_dir)+ if not os.path.isdir(camera_path):+ continue+ for file in os.listdir(camera_path):+ if file.endswith(".mp4"):+ file_path = os.path.join(camera_path, file)+ preview_files.append(file_path)++ result.files_checked = len(preview_files)++ # Find orphans+ orphans: list[str] = []+ for file_path in preview_files:+ if file_path not in preview_paths:+ orphans.append(file_path)++ result.orphans_found = len(orphans)+ result.orphan_paths = orphans++ if len(orphans) == 0:+ return result++ # Safety check+ if (+ result.files_checked > 0+ and len(orphans) / result.files_checked > SAFETY_THRESHOLD+ ):+ if force:+ logger.warning(+ f"Previews sync: Would delete {len(orphans)}/{result.files_checked} "+ f"({len(orphans) / result.files_checked * 100:.2f}%) files (force=True, bypassing safety threshold)."+ )+ else:+ logger.warning(+ f"Previews sync: Would delete {len(orphans)}/{result.files_checked} "+ f"({len(orphans) / result.files_checked * 100:.2f}%) files. "+ "Aborting due to safety threshold."+ )+ result.aborted = True+ return result++ if dry_run:+ logger.info(f"Previews sync (dry run): Found {len(orphans)} orphaned files")+ return result++ # Delete orphans+ logger.info(f"Deleting {len(orphans)} orphaned preview files")+ for file_path in orphans:+ try:+ os.unlink(file_path)+ result.orphans_deleted += 1+ except OSError as e:+ logger.error(f"Failed to delete {file_path}: {e}")++ except Exception as e:+ logger.error(f"Error syncing previews: {e}")+ result.error = str(e)++ return result+++def sync_exports(dry_run: bool = False, force: bool = False) -> SyncResult:+ """Sync export files - delete files not referenced by any export record.++ Export videos are stored at: EXPORT_DIR/*.mp4+ Export thumbnails are stored at: CLIPS_DIR/export/*.jpg+ The paths are stored in Export.video_path and Export.thumb_path+ """+ result = SyncResult(media_type="exports")++ try:+ # Get all export paths from DB+ export_video_paths = set()+ export_thumb_paths = set()+ for e in Export.select(Export.video_path, Export.thumb_path):+ if e.video_path:+ export_video_paths.add(e.video_path)+ if e.thumb_path:+ export_thumb_paths.add(e.thumb_path)++ # Find export video files on disk+ export_files: list[str] = []+ if os.path.isdir(EXPORT_DIR):+ for file in os.listdir(EXPORT_DIR):+ if file.endswith(".mp4"):+ file_path = os.path.join(EXPORT_DIR, file)+ export_files.append(file_path)++ # Find export thumbnail files on disk+ export_thumb_dir = os.path.join(CLIPS_DIR, "export")+ thumb_files: list[str] = []+ if os.path.isdir(export_thumb_dir):+ for file in os.listdir(export_thumb_dir):+ if file.endswith(".jpg"):+ file_path = os.path.join(export_thumb_dir, file)+ thumb_files.append(file_path)++ result.files_checked = len(export_files) + len(thumb_files)++ # Find orphans+ orphans: list[str] = []+ for file_path in export_files:+ if file_path not in export_video_paths:+ orphans.append(file_path)+ for file_path in thumb_files:+ if file_path not in export_thumb_paths:+ orphans.append(file_path)++ result.orphans_found = len(orphans)+ result.orphan_paths = orphans++ if len(orphans) == 0:+ return result++ # Safety check+ if (+ result.files_checked > 0+ and len(orphans) / result.files_checked > SAFETY_THRESHOLD+ ):+ if force:+ logger.warning(+ f"Exports sync: Would delete {len(orphans)}/{result.files_checked} "+ f"({len(orphans) / result.files_checked * 100:.2f}%) files (force=True, bypassing safety threshold)."+ )+ else:+ logger.warning(+ f"Exports sync: Would delete {len(orphans)}/{result.files_checked} "+ f"({len(orphans) / result.files_checked * 100:.2f}%) files. "+ "Aborting due to safety threshold."+ )+ result.aborted = True+ return result++ if dry_run:+ logger.info(f"Exports sync (dry run): Found {len(orphans)} orphaned files")+ return result++ # Delete orphans+ logger.info(f"Deleting {len(orphans)} orphaned export files")+ for file_path in orphans:+ try:+ os.unlink(file_path)+ result.orphans_deleted += 1+ except OSError as e:+ logger.error(f"Failed to delete {file_path}: {e}")++ except Exception as e:+ logger.error(f"Error syncing exports: {e}")+ result.error = str(e)++ return result+++@dataclass+class MediaSyncResults:+ """Combined results from all media sync operations."""++ event_snapshots: SyncResult | None = None+ event_thumbnails: SyncResult | None = None+ review_thumbnails: SyncResult | None = None+ previews: SyncResult | None = None+ exports: SyncResult | None = None+ recordings: SyncResult | None = None++ @property+ def total_files_checked(self) -> int:+ total = 0+ for result in [+ self.event_snapshots,+ self.event_thumbnails,+ self.review_thumbnails,+ self.previews,+ self.exports,+ self.recordings,+ ]:+ if result:+ total += result.files_checked+ return total++ @property+ def total_orphans_found(self) -> int:+ total = 0+ for result in [+ self.event_snapshots,+ self.event_thumbnails,+ self.review_thumbnails,+ self.previews,+ self.exports,+ self.recordings,+ ]:+ if result:+ total += result.orphans_found+ return total++ @property+ def total_orphans_deleted(self) -> int:+ total = 0+ for result in [+ self.event_snapshots,+ self.event_thumbnails,+ self.review_thumbnails,+ self.previews,+ self.exports,+ self.recordings,+ ]:+ if result:+ total += result.orphans_deleted+ return total++ def to_dict(self) -> dict:+ """Convert results to dictionary for API response."""+ results = {}+ for name, result in [+ ("event_snapshots", self.event_snapshots),+ ("event_thumbnails", self.event_thumbnails),+ ("review_thumbnails", self.review_thumbnails),+ ("previews", self.previews),+ ("exports", self.exports),+ ("recordings", self.recordings),+ ]:+ if result:+ results[name] = {+ "files_checked": result.files_checked,+ "orphans_found": result.orphans_found,+ "orphans_deleted": result.orphans_deleted,+ "aborted": result.aborted,+ "error": result.error,+ }+ results["totals"] = {+ "files_checked": self.total_files_checked,+ "orphans_found": self.total_orphans_found,+ "orphans_deleted": self.total_orphans_deleted,+ }+ return results+++def sync_all_media(+ dry_run: bool = False, media_types: list[str] = ["all"], force: bool = False+) -> MediaSyncResults:+ """Sync specified media types with the database.++ Args:+ dry_run: If True, only report orphans without deleting them.+ media_types: List of media types to sync. Can include: 'all', 'event_snapshots',+ 'event_thumbnails', 'review_thumbnails', 'previews', 'exports', 'recordings'+ force: If True, bypass safety threshold checks.++ Returns:+ MediaSyncResults with details of each sync operation.+ """+ logger.debug(+ f"Starting media sync (dry_run={dry_run}, media_types={media_types}, force={force})"+ )++ results = MediaSyncResults()++ # Determine which media types to sync+ sync_all = "all" in media_types++ if sync_all or "event_snapshots" in media_types:+ results.event_snapshots = sync_event_snapshots(dry_run=dry_run, force=force)++ if sync_all or "event_thumbnails" in media_types:+ results.event_thumbnails = sync_event_thumbnails(dry_run=dry_run, force=force)++ if sync_all or "review_thumbnails" in media_types:+ results.review_thumbnails = sync_review_thumbnails(dry_run=dry_run, force=force)++ if sync_all or "previews" in media_types:+ results.previews = sync_previews(dry_run=dry_run, force=force)++ if sync_all or "exports" in media_types:+ results.exports = sync_exports(dry_run=dry_run, force=force)++ if sync_all or "recordings" in media_types:+ results.recordings = sync_recordings(dry_run=dry_run, force=force)++ logger.info(+ f"Media sync complete: checked {results.total_files_checked} files, "+ f"found {results.total_orphans_found} orphans, "+ f"deleted {results.total_orphans_deleted}"+ )++ return results+++++ def get_keyframe_before(path: str, offset_ms: int) -> int | None:+ """Get the timestamp (ms) of the last keyframe at or before offset_ms.++ Uses ffprobe packet index to read keyframe positions from the mp4 file.+ Returns None if ffprobe fails or no keyframe is found before the offset.+ """+ try:+ result = sp.run(+ [+ FFPROBE_PATH,+ "-select_streams",+ "v:0",+ "-show_entries",+ "packet=pts_time,flags",+ "-of",+ "csv=p=0",+ "-loglevel",+ "error",+ path,+ ],+ capture_output=True,+ timeout=5,+ )+ except (sp.TimeoutExpired, FileNotFoundError):+ return None++ if result.returncode != 0:+ return None++ offset_s = offset_ms / 1000.0+ best_ms = None+ for line in result.stdout.decode().strip().splitlines():+ parts = line.strip().split(",")+ if len(parts) != 2:+ continue+ ts_str, flags = parts+ if "K" not in flags:+ continue+ try:+ ts = float(ts_str)+ except ValueError:+ continue+ if ts <= offset_s:+ best_ms = int(ts * 1000)+ else:+ break++ return best_msdiff --cc web/src/components/player/HlsVideoPlayer.tsxindex b91efd84b1,9261032a38..7d762912ca--- a/web/src/components/player/HlsVideoPlayer.tsx+++ b/web/src/components/player/HlsVideoPlayer.tsx@@@ -353,162 -350,157 +353,162 @@@ export default function HlsVideoPlayer(height: isMobile ? "100%" : undefined,}}>- {isDetailMode &&- camera &&- currentTime != null &&- loadedMetadata &&- videoDimensions.width > 0 &&- videoDimensions.height > 0 && (- <div- className={cn(- "absolute inset-0 z-50",- isDesktop- ? "size-full"- : "mx-auto flex items-center justify-center portrait:max-h-[50dvh]",- )}- style={{- aspectRatio: `${videoDimensions.width} / ${videoDimensions.height}`,- }}- >- <ObjectTrackOverlay- key={`overlay-${currentTime}`}- camera={camera}- showBoundingBoxes={!isPlaying}- currentTime={currentTime}- videoWidth={videoDimensions.width}- videoHeight={videoDimensions.height}- className="absolute inset-0 z-10"- onSeekToTime={(timestamp, play) => {- if (onSeekToTime) {- onSeekToTime(timestamp, play);- }+ <div className="relative size-full">+ {transformedOverlay}+ {isDetailMode &&+ camera &&- currentTime &&++ currentTime != null &&+ loadedMetadata &&+ videoDimensions.width > 0 &&+ videoDimensions.height > 0 && (+ <div+ className={cn(+ "absolute inset-0 z-50",+ isDesktop+ ? "size-full"+ : "mx-auto flex items-center justify-center portrait:max-h-[50dvh]",+ )}+ style={{+ aspectRatio: `${videoDimensions.width} / ${videoDimensions.height}`,}}- />- </div>- )}- <video- ref={videoRef}- className={`size-full rounded-lg bg-black md:rounded-2xl ${loadedMetadata ? "" : "invisible"} cursor-pointer`}- preload="auto"- autoPlay- controls={!frigateControls}- playsInline- muted={muted}- onClick={- isDesktop- ? () => {- if (zoomScale == 1.0) onPlayPause(!isPlaying);- }- : undefined- }- onVolumeChange={() => {- setVolume(videoRef.current?.volume ?? 1.0, true);- if (!frigateControls) {- setMuted(videoRef.current?.muted);- }- }}- onPlay={() => {- setIsPlaying(true);-- if (isMobile) {- setControls(true);- setMobileCtrlTimeout(setTimeout(() => setControls(false), 4000));- }- }}- onPlaying={onPlaying}- onPause={() => {- setIsPlaying(false);- clearTimeout(bufferTimeout);-- if (isMobile && mobileCtrlTimeout) {- clearTimeout(mobileCtrlTimeout);- }- }}- onWaiting={() => {- if (onError != undefined) {- if (videoRef.current?.paused) {- return;- }-- setBufferTimeout(- setTimeout(() => {- if (- document.visibilityState === "visible" &&- videoRef.current- ) {- onError("stalled");+ >+ <ObjectTrackOverlay+ key={`overlay-${currentTime}`}+ camera={camera}+ showBoundingBoxes={!isPlaying}+ currentTime={currentTime}+ videoWidth={videoDimensions.width}+ videoHeight={videoDimensions.height}+ className="absolute inset-0 z-10"+ onSeekToTime={(timestamp, play) => {+ if (onSeekToTime) {+ onSeekToTime(timestamp, play);+ }+ }}+ />+ </div>+ )}+ <video+ ref={videoRef}+ className={`size-full rounded-lg bg-black md:rounded-2xl ${loadedMetadata ? "" : "invisible"} cursor-pointer`}+ preload="auto"+ autoPlay+ controls={!frigateControls}+ playsInline+ muted={muted}+ onClick={+ isDesktop+ ? () => {+ if (zoomScale == 1.0) onPlayPause(!isPlaying);}- }, 3000),- );+ : undefined}- }}- onProgress={() => {- if (onError != undefined) {- if (videoRef.current?.paused) {- return;+ onVolumeChange={() => {+ setVolume(videoRef.current?.volume ?? 1.0, true);+ if (!frigateControls) {+ setMuted(videoRef.current?.muted);+ }+ }}+ onPlay={() => {+ setIsPlaying(true);++ if (isMobile) {+ setControls(true);+ setMobileCtrlTimeout(+ setTimeout(() => setControls(false), 4000),+ );}+ }}+ onPlaying={onPlaying}+ onPause={() => {+ setIsPlaying(false);+ clearTimeout(bufferTimeout);++ if (isMobile && mobileCtrlTimeout) {+ clearTimeout(mobileCtrlTimeout);+ }+ }}+ onWaiting={() => {+ if (onError != undefined) {+ if (videoRef.current?.paused) {+ return;+ }- if (bufferTimeout) {- clearTimeout(bufferTimeout);- setBufferTimeout(undefined);+ setBufferTimeout(+ setTimeout(() => {+ if (+ document.visibilityState === "visible" &&+ videoRef.current+ ) {+ onError("stalled");+ }+ }, 3000),+ );}- }- }}- onTimeUpdate={() => {- if (!onTimeUpdate) {- return;- }+ }}+ onProgress={() => {+ if (onError != undefined) {+ if (videoRef.current?.paused) {+ return;+ }- const frameTime = getVideoTime();+ if (bufferTimeout) {+ clearTimeout(bufferTimeout);+ setBufferTimeout(undefined);+ }+ }+ }}+ onTimeUpdate={() => {+ if (!onTimeUpdate) {+ return;+ }- if (frameTime) {- onTimeUpdate(frameTime);- }- }}- onLoadedData={() => {- onPlayerLoaded?.();- handleLoadedMetadata();+ const frameTime = getVideoTime();- if (videoRef.current) {- if (playbackRate) {- videoRef.current.playbackRate = playbackRate;+ if (frameTime) {+ onTimeUpdate(frameTime);}+ }}+ onLoadedData={() => {+ onPlayerLoaded?.();+ handleLoadedMetadata();++ if (videoRef.current) {+ if (playbackRate) {+ videoRef.current.playbackRate = playbackRate;+ }- if (volume) {- videoRef.current.volume = volume;+ if (volume) {+ videoRef.current.volume = volume;+ }}- }- }}- onEnded={() => {- if (onClipEnded) {- onClipEnded(getVideoTime() ?? 0);- }- }}- onError={(e) => {- if (- !hlsRef.current &&- // @ts-expect-error code does exist- unsupportedErrorCodes.includes(e.target.error.code) &&- videoRef.current- ) {- setLoadedMetadata(false);- setUseHlsCompat(true);- } else {- toast.error(+ }}+ onEnded={() => {+ if (onClipEnded) {+ onClipEnded(getVideoTime() ?? 0);+ }+ }}+ onError={(e) => {+ if (+ !hlsRef.current &&// @ts-expect-error code does exist- `Failed to play recordings (error ${e.target.error.code}): ${e.target.error.message}`,- {- position: "top-center",- },- );- }- }}- />+ unsupportedErrorCodes.includes(e.target.error.code) &&+ videoRef.current+ ) {+ setLoadedMetadata(false);+ setUseHlsCompat(true);+ } else {+ toast.error(+ // @ts-expect-error code does exist+ `Failed to play recordings (error ${e.target.error.code}): ${e.target.error.message}`,+ {+ position: "top-center",+ },+ );+ }+ }}+ />+ </div></TransformComponent></TransformWrapper>);