mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-12-03 02:37:06 +03:00
Recording fixes (#24072)
* pin genai review frames to the main stream * retain previews as long as either stream has recordings * watch sub stream recording health separately from main * reject record_sub on the same input as record and document the role * derive recording paths from the cache segment timestamp Recording paths carry one second of resolution, but since sub stream recording start times are resolved to fractional wall clock, anchored to the cache file mtime and chained to the previous segment's end. A stream cutting segments faster than once a second resolves consecutive segments into the same second, so two rows collide on the unique path index and the batch insert fails. The cache segment name is unique per camera stream and second by construction because ffmpeg names segments with strftime, so the recording path is now built from that timestamp while the row keeps the resolved start time. This also restores the path semantics from before sub stream recording, when start times came straight from the cache filename. Nothing derives times from recording paths: playback offsets, stream switching, and export all use the row's start time, which is unchanged, and the recordings sync matches files by exact path string. * keep the rest of a recording batch when one row conflicts * only publish record_sub status when a sub stream is configured * don't shadow camera_cfg when publishing empty cache streams * back off restarts when a recording stream goes stale * give the shared sub stream grace on any capture thread reset * include segment details in recording discard warnings
This commit is contained in:
committed by
Nicolas Mowen
parent
40793b8478
commit
53fb6c8daa
@@ -149,8 +149,12 @@ class RecordingCleanup(threading.Thread):
|
||||
detections_retain_mode: RetainModeEnum,
|
||||
config: CameraConfig,
|
||||
reviews: list[Any],
|
||||
) -> set[Path]:
|
||||
"""Delete recordings for existing camera based on retention config."""
|
||||
) -> tuple[set[Path], list[tuple[float, float]]]:
|
||||
"""Delete recordings for one stream of an existing camera based on retention config.
|
||||
|
||||
Returns the directories to check for emptiness and the segments that
|
||||
were kept, which the caller feeds to expire_camera_previews.
|
||||
"""
|
||||
# Get the timestamp for cutoff of retained days
|
||||
|
||||
# Get recordings to check for expiration
|
||||
@@ -257,9 +261,23 @@ class RecordingCleanup(threading.Thread):
|
||||
Recordings.id << deleted_recordings_list[i : i + max_deletes]
|
||||
).execute()
|
||||
|
||||
# previews follow main retention, so only the main pass expires them
|
||||
if stream_type != STREAM_TYPE_MAIN:
|
||||
return maybe_empty_dirs
|
||||
return maybe_empty_dirs, kept_recordings
|
||||
|
||||
def expire_camera_previews(
|
||||
self,
|
||||
config: CameraConfig,
|
||||
continuous_expire_date: float,
|
||||
motion_expire_date: float,
|
||||
kept_recordings: list[tuple[float, float]],
|
||||
) -> set[Path]:
|
||||
"""Delete previews that no longer have recordings on any stream.
|
||||
|
||||
Previews aren't recorded per stream, so the cutoffs must be the oldest
|
||||
of the per stream values and kept_recordings must cover every stream,
|
||||
sorted by start time. Otherwise a short main retention expires previews
|
||||
the sub recordings still need.
|
||||
"""
|
||||
maybe_empty_dirs: set[Path] = set()
|
||||
|
||||
previews = (
|
||||
Previews.select(
|
||||
@@ -438,7 +456,7 @@ class RecordingCleanup(threading.Thread):
|
||||
.namedtuples()
|
||||
)
|
||||
|
||||
maybe_empty_dirs |= self.expire_existing_camera_recordings(
|
||||
main_dirs, main_kept = self.expire_existing_camera_recordings(
|
||||
STREAM_TYPE_MAIN,
|
||||
continuous_expire_date,
|
||||
motion_expire_date,
|
||||
@@ -452,10 +470,11 @@ class RecordingCleanup(threading.Thread):
|
||||
config.record.detections.retain.days,
|
||||
),
|
||||
)
|
||||
maybe_empty_dirs |= main_dirs
|
||||
|
||||
# runs even when sub recording is disabled so old rows still
|
||||
# expire
|
||||
maybe_empty_dirs |= self.expire_existing_camera_recordings(
|
||||
sub_dirs, sub_kept = self.expire_existing_camera_recordings(
|
||||
STREAM_TYPE_SUB,
|
||||
sub_continuous_expire_date,
|
||||
sub_motion_expire_date,
|
||||
@@ -469,6 +488,14 @@ class RecordingCleanup(threading.Thread):
|
||||
config.record.sub.detections.days,
|
||||
),
|
||||
)
|
||||
maybe_empty_dirs |= sub_dirs
|
||||
|
||||
maybe_empty_dirs |= self.expire_camera_previews(
|
||||
config,
|
||||
min(continuous_expire_date, sub_continuous_expire_date),
|
||||
min(motion_expire_date, sub_motion_expire_date),
|
||||
sorted(main_kept + sub_kept),
|
||||
)
|
||||
logger.debug(f"End camera: {camera}.")
|
||||
|
||||
logger.debug("End all cameras.")
|
||||
|
||||
@@ -79,6 +79,54 @@ def parse_cache_segment_name(basename: str) -> tuple[str, str, str] | None:
|
||||
return (prefix, STREAM_TYPE_MAIN, date)
|
||||
|
||||
|
||||
def format_segment_details(cache_path: str, segment_info: dict[str, Any]) -> str:
|
||||
"""Comma separated facts about a segment, for discard warnings."""
|
||||
details: list[str] = []
|
||||
|
||||
duration = segment_info.get("duration", -1)
|
||||
|
||||
if duration != -1:
|
||||
details.append(f"duration: {duration:.2f}s")
|
||||
|
||||
try:
|
||||
details.append(f"size: {os.path.getsize(cache_path) / 1024:.1f} KB")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
details.append(f"video: {segment_info.get('video_codec') or 'none'}")
|
||||
|
||||
if segment_info.get("has_audio"):
|
||||
audio = segment_info.get("audio_codec") or "unknown"
|
||||
rate = segment_info.get("audio_rate")
|
||||
details.append(f"audio: {audio} {rate}Hz" if rate else f"audio: {audio}")
|
||||
else:
|
||||
details.append("audio: none")
|
||||
|
||||
return ", ".join(details)
|
||||
|
||||
|
||||
def segment_path_time(cache_path: str) -> datetime.datetime | None:
|
||||
"""Timestamp a segment's recording path is built from, or None if unparsable.
|
||||
|
||||
Recording paths carry one second of resolution, and so does ffmpeg's cache
|
||||
segment template, which makes a cache file name unique per camera stream
|
||||
and second. Resolved start times are not: a stream cutting segments faster
|
||||
than once a second resolves consecutive segments into the same second, and
|
||||
building the path from those collides on the unique path index.
|
||||
"""
|
||||
parsed = parse_cache_segment_name(Path(cache_path).stem)
|
||||
|
||||
if parsed is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
return datetime.datetime.strptime(parsed[2], CACHE_SEGMENT_FORMAT).astimezone(
|
||||
datetime.UTC
|
||||
)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
class SegmentInfo:
|
||||
def __init__(
|
||||
self,
|
||||
@@ -241,51 +289,55 @@ class RecordingMaintainer(threading.Thread):
|
||||
and not d.startswith("preview_")
|
||||
]
|
||||
|
||||
# publish newest cached segment per camera (including in use files)
|
||||
newest_cache_segments: dict[str, dict[str, Any]] = {}
|
||||
# publish newest cached segment per camera stream (including in use files)
|
||||
newest_cache_segments: dict[tuple[str, str], dict[str, Any]] = {}
|
||||
for cache in cache_files:
|
||||
cache_path = os.path.join(CACHE_DIR, cache)
|
||||
basename = os.path.splitext(cache)[0]
|
||||
parsed = parse_cache_segment_name(basename)
|
||||
if parsed is None:
|
||||
if not self.unexpected_cache_files_logged:
|
||||
logger.warning("Skipping unexpected files in cache")
|
||||
logger.warning(f"Skipping unexpected files in cache, e.g. {cache}")
|
||||
self.unexpected_cache_files_logged = True
|
||||
continue
|
||||
camera, stream_type, date = parsed
|
||||
|
||||
# this topic feeds main-stream health/sync consumers only
|
||||
if stream_type == STREAM_TYPE_SUB:
|
||||
continue
|
||||
|
||||
start_time = datetime.datetime.strptime(
|
||||
date, CACHE_SEGMENT_FORMAT
|
||||
).astimezone(datetime.UTC)
|
||||
key = (camera, stream_type)
|
||||
if (
|
||||
camera not in newest_cache_segments
|
||||
or start_time > newest_cache_segments[camera]["start_time"]
|
||||
key not in newest_cache_segments
|
||||
or start_time > newest_cache_segments[key]["start_time"]
|
||||
):
|
||||
newest_cache_segments[camera] = {
|
||||
newest_cache_segments[key] = {
|
||||
"start_time": start_time,
|
||||
"cache_path": cache_path,
|
||||
}
|
||||
|
||||
for camera, newest in newest_cache_segments.items():
|
||||
for (camera, stream_type), newest in newest_cache_segments.items():
|
||||
self.recordings_publisher.publish(
|
||||
(
|
||||
camera,
|
||||
stream_type,
|
||||
newest["start_time"].timestamp(),
|
||||
newest["cache_path"],
|
||||
),
|
||||
RecordingsDataTypeEnum.latest.value,
|
||||
)
|
||||
# publish None for cameras with no cache files (but only if we know the camera exists)
|
||||
for camera_name in self.config.cameras:
|
||||
if camera_name not in newest_cache_segments:
|
||||
self.recordings_publisher.publish(
|
||||
(camera_name, None, None),
|
||||
RecordingsDataTypeEnum.latest.value,
|
||||
)
|
||||
# publish None for streams with no cache files (but only if we know the camera exists)
|
||||
for camera_name, camera_config in self.config.cameras.items():
|
||||
stream_types = [STREAM_TYPE_MAIN]
|
||||
|
||||
if camera_config.record.sub.enabled:
|
||||
stream_types.append(STREAM_TYPE_SUB)
|
||||
|
||||
for stream_type in stream_types:
|
||||
if (camera_name, stream_type) not in newest_cache_segments:
|
||||
self.recordings_publisher.publish(
|
||||
(camera_name, stream_type, None, None),
|
||||
RecordingsDataTypeEnum.latest.value,
|
||||
)
|
||||
|
||||
files_in_use = []
|
||||
for process in psutil.process_iter():
|
||||
@@ -314,7 +366,7 @@ class RecordingMaintainer(threading.Thread):
|
||||
parsed = parse_cache_segment_name(basename)
|
||||
if parsed is None:
|
||||
if not self.unexpected_cache_files_logged:
|
||||
logger.warning("Skipping unexpected files in cache")
|
||||
logger.warning(f"Skipping unexpected files in cache, e.g. {cache}")
|
||||
self.unexpected_cache_files_logged = True
|
||||
continue
|
||||
camera, stream_type, date = parsed
|
||||
@@ -447,6 +499,7 @@ class RecordingMaintainer(threading.Thread):
|
||||
self.recordings_publisher.publish(
|
||||
(
|
||||
camera,
|
||||
stream_type,
|
||||
recordings[0]["start_time"].timestamp()
|
||||
if camera_cfg and camera_cfg.record.enabled
|
||||
else None,
|
||||
@@ -540,13 +593,13 @@ class RecordingMaintainer(threading.Thread):
|
||||
|
||||
if not segment_info.get("has_valid_video", False):
|
||||
logger.warning(
|
||||
f"Invalid or missing video stream in segment {cache_path}. Discarding."
|
||||
f"Invalid or missing video stream in segment {cache_path} "
|
||||
f"({format_segment_details(cache_path, segment_info)}). Discarding."
|
||||
)
|
||||
self.recordings_publisher.publish(
|
||||
(camera, stream_type, start_time.timestamp(), cache_path),
|
||||
RecordingsDataTypeEnum.invalid.value,
|
||||
)
|
||||
if stream_type == STREAM_TYPE_MAIN:
|
||||
self.recordings_publisher.publish(
|
||||
(camera, start_time.timestamp(), cache_path),
|
||||
RecordingsDataTypeEnum.invalid.value,
|
||||
)
|
||||
self.drop_segment(cache_path)
|
||||
return None
|
||||
|
||||
@@ -583,21 +636,22 @@ class RecordingMaintainer(threading.Thread):
|
||||
if duration == -1:
|
||||
logger.warning(f"Failed to probe corrupt segment {cache_path}")
|
||||
|
||||
logger.warning(f"Discarding a corrupt recording segment: {cache_path}")
|
||||
if stream_type == STREAM_TYPE_MAIN:
|
||||
self.recordings_publisher.publish(
|
||||
(camera, start_time.timestamp(), cache_path),
|
||||
RecordingsDataTypeEnum.invalid.value,
|
||||
)
|
||||
logger.warning(
|
||||
f"Discarding a corrupt recording segment: {cache_path} "
|
||||
f"({format_segment_details(cache_path, segment_info)})"
|
||||
)
|
||||
self.recordings_publisher.publish(
|
||||
(camera, stream_type, start_time.timestamp(), cache_path),
|
||||
RecordingsDataTypeEnum.invalid.value,
|
||||
)
|
||||
self.drop_segment(cache_path)
|
||||
return None
|
||||
|
||||
# this segment has a valid duration and has video data, so publish an update
|
||||
if stream_type == STREAM_TYPE_MAIN:
|
||||
self.recordings_publisher.publish(
|
||||
(camera, start_time.timestamp(), cache_path),
|
||||
RecordingsDataTypeEnum.valid.value,
|
||||
)
|
||||
self.recordings_publisher.publish(
|
||||
(camera, stream_type, start_time.timestamp(), cache_path),
|
||||
RecordingsDataTypeEnum.valid.value,
|
||||
)
|
||||
|
||||
record_config = self.config.cameras[camera].record
|
||||
|
||||
@@ -863,18 +917,20 @@ class RecordingMaintainer(threading.Thread):
|
||||
video_codec: str | None = None,
|
||||
keyframes: list[int] | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
# directory will be in utc due to start_time being in utc
|
||||
path_time = segment_path_time(cache_path) or start_time
|
||||
|
||||
# directory will be in utc due to path_time being in utc
|
||||
# sub segments get a tagged directory to avoid filename collisions
|
||||
directory = os.path.join(
|
||||
RECORD_DIR,
|
||||
start_time.strftime("%Y-%m-%d/%H"),
|
||||
path_time.strftime("%Y-%m-%d/%H"),
|
||||
camera if stream_type == STREAM_TYPE_MAIN else f"{camera}{SUB_CACHE_TAG}",
|
||||
)
|
||||
|
||||
os.makedirs(directory, exist_ok=True)
|
||||
|
||||
# file will be in utc due to start_time being in utc
|
||||
file_name = f"{start_time.strftime('%M.%S.mp4')}"
|
||||
# file will be in utc due to path_time being in utc
|
||||
file_name = f"{path_time.strftime('%M.%S.mp4')}"
|
||||
file_path = os.path.join(directory, file_name)
|
||||
|
||||
try:
|
||||
@@ -946,10 +1002,9 @@ class RecordingMaintainer(threading.Thread):
|
||||
Recordings.video_codec.name: video_codec,
|
||||
Recordings.keyframes.name: keyframes,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"Unable to store recording segment {cache_path}")
|
||||
except Exception:
|
||||
logger.exception(f"Unable to store recording segment {cache_path}")
|
||||
Path(cache_path).unlink(missing_ok=True)
|
||||
logger.error(e)
|
||||
|
||||
# clear end_time cache
|
||||
self.end_time_cache.pop(cache_path, None)
|
||||
|
||||
Reference in New Issue
Block a user