2023-06-08 13:32:35 +02:00
|
|
|
"""Export recordings to storage."""
|
|
|
|
|
|
|
|
import datetime
|
|
|
|
import logging
|
|
|
|
import os
|
2024-04-20 00:11:41 +02:00
|
|
|
import random
|
|
|
|
import shutil
|
|
|
|
import string
|
2023-06-08 13:32:35 +02:00
|
|
|
import subprocess as sp
|
|
|
|
import threading
|
|
|
|
from enum import Enum
|
2023-10-31 01:24:11 +01:00
|
|
|
from pathlib import Path
|
2024-08-12 16:26:54 +02:00
|
|
|
from typing import Optional
|
2023-06-08 13:32:35 +02:00
|
|
|
|
2024-06-04 17:10:19 +02:00
|
|
|
from peewee import DoesNotExist
|
|
|
|
|
2024-09-13 22:14:51 +02:00
|
|
|
from frigate.config import FfmpegConfig, FrigateConfig
|
2024-04-20 00:11:41 +02:00
|
|
|
from frigate.const import (
|
|
|
|
CACHE_DIR,
|
|
|
|
CLIPS_DIR,
|
|
|
|
EXPORT_DIR,
|
|
|
|
MAX_PLAYLIST_SECONDS,
|
|
|
|
PREVIEW_FRAME_TYPE,
|
|
|
|
)
|
2023-06-08 13:32:35 +02:00
|
|
|
from frigate.ffmpeg_presets import (
|
|
|
|
EncodeTypeEnum,
|
|
|
|
parse_preset_hardware_acceleration_encode,
|
|
|
|
)
|
2024-04-20 00:11:41 +02:00
|
|
|
from frigate.models import Export, Previews, Recordings
|
2023-06-08 13:32:35 +02:00
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2023-09-21 14:20:05 +02:00
|
|
|
TIMELAPSE_DATA_INPUT_ARGS = "-an -skip_frame nokey"
|
|
|
|
|
|
|
|
|
2023-09-21 12:22:35 +02:00
|
|
|
def lower_priority():
|
|
|
|
os.nice(10)
|
|
|
|
|
|
|
|
|
2023-06-08 13:32:35 +02:00
|
|
|
class PlaybackFactorEnum(str, Enum):
|
|
|
|
realtime = "realtime"
|
|
|
|
timelapse_25x = "timelapse_25x"
|
|
|
|
|
|
|
|
|
2024-10-23 15:36:52 +02:00
|
|
|
class PlaybackSourceEnum(str, Enum):
|
|
|
|
recordings = "recordings"
|
|
|
|
preview = "preview"
|
|
|
|
|
|
|
|
|
2023-06-08 13:32:35 +02:00
|
|
|
class RecordingExporter(threading.Thread):
|
|
|
|
"""Exports a specific set of recordings for a camera to storage as a single file."""
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
config: FrigateConfig,
|
2024-09-30 23:55:44 +02:00
|
|
|
id: str,
|
2023-06-08 13:32:35 +02:00
|
|
|
camera: str,
|
2024-08-12 16:26:54 +02:00
|
|
|
name: Optional[str],
|
|
|
|
image: Optional[str],
|
2023-06-08 13:32:35 +02:00
|
|
|
start_time: int,
|
|
|
|
end_time: int,
|
|
|
|
playback_factor: PlaybackFactorEnum,
|
2024-10-23 15:36:52 +02:00
|
|
|
playback_source: PlaybackSourceEnum,
|
2023-06-08 13:32:35 +02:00
|
|
|
) -> None:
|
2024-10-03 03:35:46 +02:00
|
|
|
super().__init__()
|
2023-06-08 13:32:35 +02:00
|
|
|
self.config = config
|
2024-09-30 23:55:44 +02:00
|
|
|
self.export_id = id
|
2023-06-08 13:32:35 +02:00
|
|
|
self.camera = camera
|
2024-03-26 22:37:45 +01:00
|
|
|
self.user_provided_name = name
|
2024-08-12 16:26:54 +02:00
|
|
|
self.user_provided_image = image
|
2023-06-08 13:32:35 +02:00
|
|
|
self.start_time = start_time
|
|
|
|
self.end_time = end_time
|
|
|
|
self.playback_factor = playback_factor
|
2024-10-23 15:36:52 +02:00
|
|
|
self.playback_source = playback_source
|
2023-06-08 13:32:35 +02:00
|
|
|
|
2024-04-20 00:11:41 +02:00
|
|
|
# ensure export thumb dir
|
|
|
|
Path(os.path.join(CLIPS_DIR, "export")).mkdir(exist_ok=True)
|
|
|
|
|
2023-06-08 13:32:35 +02:00
|
|
|
def get_datetime_from_timestamp(self, timestamp: int) -> str:
|
|
|
|
"""Convenience fun to get a simple date time from timestamp."""
|
2024-04-20 00:11:41 +02:00
|
|
|
return datetime.datetime.fromtimestamp(timestamp).strftime("%Y/%m/%d %H:%M")
|
|
|
|
|
|
|
|
def save_thumbnail(self, id: str) -> str:
|
|
|
|
thumb_path = os.path.join(CLIPS_DIR, f"export/{id}.webp")
|
|
|
|
|
2024-08-12 16:26:54 +02:00
|
|
|
if self.user_provided_image is not None and os.path.isfile(
|
|
|
|
self.user_provided_image
|
|
|
|
):
|
|
|
|
shutil.copy(self.user_provided_image, thumb_path)
|
|
|
|
return thumb_path
|
|
|
|
|
2024-06-06 22:34:31 +02:00
|
|
|
if (
|
2024-06-06 22:10:46 +02:00
|
|
|
self.start_time
|
2024-06-06 22:34:31 +02:00
|
|
|
< datetime.datetime.now(datetime.timezone.utc)
|
|
|
|
.replace(minute=0, second=0, microsecond=0)
|
|
|
|
.timestamp()
|
2024-06-06 22:10:46 +02:00
|
|
|
):
|
2024-04-20 00:11:41 +02:00
|
|
|
# has preview mp4
|
2024-06-04 17:10:19 +02:00
|
|
|
try:
|
|
|
|
preview: Previews = (
|
|
|
|
Previews.select(
|
|
|
|
Previews.camera,
|
|
|
|
Previews.path,
|
|
|
|
Previews.duration,
|
|
|
|
Previews.start_time,
|
|
|
|
Previews.end_time,
|
2024-04-20 00:11:41 +02:00
|
|
|
)
|
2024-06-04 17:10:19 +02:00
|
|
|
.where(
|
|
|
|
Previews.start_time.between(self.start_time, self.end_time)
|
|
|
|
| Previews.end_time.between(self.start_time, self.end_time)
|
|
|
|
| (
|
|
|
|
(self.start_time > Previews.start_time)
|
|
|
|
& (self.end_time < Previews.end_time)
|
|
|
|
)
|
|
|
|
)
|
|
|
|
.where(Previews.camera == self.camera)
|
|
|
|
.limit(1)
|
|
|
|
.get()
|
2024-04-20 00:11:41 +02:00
|
|
|
)
|
2024-06-04 17:10:19 +02:00
|
|
|
except DoesNotExist:
|
2024-04-20 00:11:41 +02:00
|
|
|
return ""
|
|
|
|
|
|
|
|
diff = self.start_time - preview.start_time
|
|
|
|
minutes = int(diff / 60)
|
|
|
|
seconds = int(diff % 60)
|
|
|
|
ffmpeg_cmd = [
|
2024-09-13 22:14:51 +02:00
|
|
|
self.config.ffmpeg.ffmpeg_path,
|
2024-04-20 00:11:41 +02:00
|
|
|
"-hide_banner",
|
|
|
|
"-loglevel",
|
|
|
|
"warning",
|
|
|
|
"-ss",
|
|
|
|
f"00:{minutes}:{seconds}",
|
|
|
|
"-i",
|
|
|
|
preview.path,
|
2024-04-29 23:23:24 +02:00
|
|
|
"-frames",
|
|
|
|
"1",
|
2024-04-20 00:11:41 +02:00
|
|
|
"-c:v",
|
|
|
|
"libwebp",
|
|
|
|
thumb_path,
|
|
|
|
]
|
|
|
|
|
|
|
|
process = sp.run(
|
|
|
|
ffmpeg_cmd,
|
|
|
|
capture_output=True,
|
|
|
|
)
|
|
|
|
|
|
|
|
if process.returncode != 0:
|
|
|
|
logger.error(process.stderr)
|
|
|
|
return ""
|
|
|
|
|
|
|
|
else:
|
|
|
|
# need to generate from existing images
|
|
|
|
preview_dir = os.path.join(CACHE_DIR, "preview_frames")
|
|
|
|
file_start = f"preview_{self.camera}"
|
|
|
|
start_file = f"{file_start}-{self.start_time}.{PREVIEW_FRAME_TYPE}"
|
|
|
|
end_file = f"{file_start}-{self.end_time}.{PREVIEW_FRAME_TYPE}"
|
|
|
|
selected_preview = None
|
|
|
|
|
|
|
|
for file in sorted(os.listdir(preview_dir)):
|
|
|
|
if not file.startswith(file_start):
|
|
|
|
continue
|
|
|
|
|
|
|
|
if file < start_file:
|
|
|
|
continue
|
|
|
|
|
|
|
|
if file > end_file:
|
|
|
|
break
|
|
|
|
|
|
|
|
selected_preview = os.path.join(preview_dir, file)
|
|
|
|
break
|
|
|
|
|
|
|
|
if not selected_preview:
|
|
|
|
return ""
|
|
|
|
|
|
|
|
shutil.copyfile(selected_preview, thumb_path)
|
|
|
|
|
|
|
|
return thumb_path
|
2023-06-08 13:32:35 +02:00
|
|
|
|
2024-10-23 15:36:52 +02:00
|
|
|
def get_record_export_command(self, video_path: str) -> list[str]:
|
2023-06-08 13:32:35 +02:00
|
|
|
if (self.end_time - self.start_time) <= MAX_PLAYLIST_SECONDS:
|
|
|
|
playlist_lines = f"http://127.0.0.1:5000/vod/{self.camera}/start/{self.start_time}/end/{self.end_time}/index.m3u8"
|
|
|
|
ffmpeg_input = (
|
|
|
|
f"-y -protocol_whitelist pipe,file,http,tcp -i {playlist_lines}"
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
playlist_lines = []
|
|
|
|
|
2023-09-21 12:24:49 +02:00
|
|
|
# get full set of recordings
|
|
|
|
export_recordings = (
|
2024-10-23 15:36:52 +02:00
|
|
|
Recordings.select(
|
|
|
|
Recordings.start_time,
|
|
|
|
Recordings.end_time,
|
|
|
|
)
|
2023-09-21 12:24:49 +02:00
|
|
|
.where(
|
|
|
|
Recordings.start_time.between(self.start_time, self.end_time)
|
|
|
|
| Recordings.end_time.between(self.start_time, self.end_time)
|
|
|
|
| (
|
|
|
|
(self.start_time > Recordings.start_time)
|
|
|
|
& (self.end_time < Recordings.end_time)
|
|
|
|
)
|
|
|
|
)
|
|
|
|
.where(Recordings.camera == self.camera)
|
|
|
|
.order_by(Recordings.start_time.asc())
|
|
|
|
)
|
|
|
|
|
|
|
|
# Use pagination to process records in chunks
|
|
|
|
page_size = 1000
|
|
|
|
num_pages = (export_recordings.count() + page_size - 1) // page_size
|
|
|
|
|
|
|
|
for page in range(1, num_pages + 1):
|
|
|
|
playlist = export_recordings.paginate(page, page_size)
|
2023-06-08 13:32:35 +02:00
|
|
|
playlist_lines.append(
|
2023-09-21 12:24:49 +02:00
|
|
|
f"file 'http://127.0.0.1:5000/vod/{self.camera}/start/{float(playlist[0].start_time)}/end/{float(playlist[-1].end_time)}/index.m3u8'"
|
2023-06-08 13:32:35 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
ffmpeg_input = "-y -protocol_whitelist pipe,file,http,tcp -f concat -safe 0 -i /dev/stdin"
|
|
|
|
|
2024-10-23 15:36:52 +02:00
|
|
|
if self.playback_factor == PlaybackFactorEnum.realtime:
|
|
|
|
ffmpeg_cmd = (
|
|
|
|
f"{self.config.ffmpeg.ffmpeg_path} -hide_banner {ffmpeg_input} -c copy -movflags +faststart {video_path}"
|
|
|
|
).split(" ")
|
|
|
|
elif self.playback_factor == PlaybackFactorEnum.timelapse_25x:
|
|
|
|
ffmpeg_cmd = (
|
|
|
|
parse_preset_hardware_acceleration_encode(
|
|
|
|
self.config.ffmpeg.ffmpeg_path,
|
|
|
|
self.config.ffmpeg.hwaccel_args,
|
|
|
|
f"-an {ffmpeg_input}",
|
|
|
|
f"{self.config.cameras[self.camera].record.export.timelapse_args} -movflags +faststart {video_path}",
|
|
|
|
EncodeTypeEnum.timelapse,
|
|
|
|
)
|
|
|
|
).split(" ")
|
|
|
|
|
|
|
|
return ffmpeg_cmd, playlist_lines
|
|
|
|
|
|
|
|
def get_preview_export_command(self, video_path: str) -> list[str]:
|
|
|
|
playlist_lines = []
|
|
|
|
|
|
|
|
# get full set of previews
|
|
|
|
export_previews = (
|
|
|
|
Previews.select(
|
|
|
|
Previews.path,
|
|
|
|
Previews.start_time,
|
|
|
|
Previews.end_time,
|
|
|
|
)
|
|
|
|
.where(
|
|
|
|
Previews.start_time.between(self.start_time, self.end_time)
|
|
|
|
| Previews.end_time.between(self.start_time, self.end_time)
|
|
|
|
| (
|
|
|
|
(self.start_time > Previews.start_time)
|
|
|
|
& (self.end_time < Previews.end_time)
|
|
|
|
)
|
|
|
|
)
|
|
|
|
.where(Previews.camera == self.camera)
|
|
|
|
.order_by(Previews.start_time.asc())
|
|
|
|
.namedtuples()
|
|
|
|
.iterator()
|
|
|
|
)
|
|
|
|
|
|
|
|
preview: Previews
|
|
|
|
for preview in export_previews:
|
|
|
|
playlist_lines.append(f"file '{preview.path}'")
|
|
|
|
|
|
|
|
if preview.start_time < self.start_time:
|
|
|
|
playlist_lines.append(
|
|
|
|
f"inpoint {int(self.start_time - preview.start_time)}"
|
|
|
|
)
|
|
|
|
|
|
|
|
if preview.end_time > self.end_time:
|
|
|
|
playlist_lines.append(
|
|
|
|
f"outpoint {int(preview.end_time - self.end_time)}"
|
|
|
|
)
|
|
|
|
|
|
|
|
ffmpeg_input = (
|
|
|
|
"-y -protocol_whitelist pipe,file,tcp -f concat -safe 0 -i /dev/stdin"
|
|
|
|
)
|
|
|
|
|
2023-06-08 13:32:35 +02:00
|
|
|
if self.playback_factor == PlaybackFactorEnum.realtime:
|
|
|
|
ffmpeg_cmd = (
|
2024-09-13 22:14:51 +02:00
|
|
|
f"{self.config.ffmpeg.ffmpeg_path} -hide_banner {ffmpeg_input} -c copy -movflags +faststart {video_path}"
|
2023-06-08 13:32:35 +02:00
|
|
|
).split(" ")
|
|
|
|
elif self.playback_factor == PlaybackFactorEnum.timelapse_25x:
|
|
|
|
ffmpeg_cmd = (
|
|
|
|
parse_preset_hardware_acceleration_encode(
|
2024-09-13 22:14:51 +02:00
|
|
|
self.config.ffmpeg.ffmpeg_path,
|
2023-06-08 13:32:35 +02:00
|
|
|
self.config.ffmpeg.hwaccel_args,
|
2023-09-21 14:20:05 +02:00
|
|
|
f"{TIMELAPSE_DATA_INPUT_ARGS} {ffmpeg_input}",
|
2024-04-20 00:11:41 +02:00
|
|
|
f"{self.config.cameras[self.camera].record.export.timelapse_args} -movflags +faststart {video_path}",
|
2023-06-08 13:32:35 +02:00
|
|
|
EncodeTypeEnum.timelapse,
|
|
|
|
)
|
|
|
|
).split(" ")
|
|
|
|
|
2024-10-23 15:36:52 +02:00
|
|
|
return ffmpeg_cmd, playlist_lines
|
|
|
|
|
|
|
|
def run(self) -> None:
|
|
|
|
logger.debug(
|
|
|
|
f"Beginning export for {self.camera} from {self.start_time} to {self.end_time}"
|
|
|
|
)
|
|
|
|
export_name = (
|
|
|
|
self.user_provided_name
|
|
|
|
or f"{self.camera.replace('_', ' ')} {self.get_datetime_from_timestamp(self.start_time)} {self.get_datetime_from_timestamp(self.end_time)}"
|
|
|
|
)
|
|
|
|
video_path = f"{EXPORT_DIR}/{self.export_id}.mp4"
|
|
|
|
thumb_path = self.save_thumbnail(self.export_id)
|
|
|
|
|
|
|
|
Export.insert(
|
|
|
|
{
|
|
|
|
Export.id: self.export_id,
|
|
|
|
Export.camera: self.camera,
|
|
|
|
Export.name: export_name,
|
|
|
|
Export.date: self.start_time,
|
|
|
|
Export.video_path: video_path,
|
|
|
|
Export.thumb_path: thumb_path,
|
|
|
|
Export.in_progress: True,
|
|
|
|
}
|
|
|
|
).execute()
|
|
|
|
|
|
|
|
if self.playback_source == PlaybackSourceEnum.recordings:
|
|
|
|
ffmpeg_cmd, playlist_lines = self.get_record_export_command(video_path)
|
|
|
|
else:
|
|
|
|
ffmpeg_cmd, playlist_lines = self.get_preview_export_command(video_path)
|
|
|
|
|
2023-06-08 13:32:35 +02:00
|
|
|
p = sp.run(
|
|
|
|
ffmpeg_cmd,
|
|
|
|
input="\n".join(playlist_lines),
|
|
|
|
encoding="ascii",
|
2023-09-21 12:22:35 +02:00
|
|
|
preexec_fn=lower_priority,
|
2023-06-08 13:32:35 +02:00
|
|
|
capture_output=True,
|
|
|
|
)
|
|
|
|
|
|
|
|
if p.returncode != 0:
|
|
|
|
logger.error(
|
2024-10-23 15:36:52 +02:00
|
|
|
f"Failed to export {self.playback_source.value} for command {' '.join(ffmpeg_cmd)}"
|
2023-06-08 13:32:35 +02:00
|
|
|
)
|
|
|
|
logger.error(p.stderr)
|
2024-04-20 00:11:41 +02:00
|
|
|
Path(video_path).unlink(missing_ok=True)
|
2024-09-30 23:55:44 +02:00
|
|
|
Export.delete().where(Export.id == self.export_id).execute()
|
2024-04-20 00:11:41 +02:00
|
|
|
Path(thumb_path).unlink(missing_ok=True)
|
2023-06-08 13:32:35 +02:00
|
|
|
return
|
2024-04-20 00:11:41 +02:00
|
|
|
else:
|
|
|
|
Export.update({Export.in_progress: False}).where(
|
2024-09-30 23:55:44 +02:00
|
|
|
Export.id == self.export_id
|
2024-04-20 00:11:41 +02:00
|
|
|
).execute()
|
|
|
|
|
|
|
|
logger.debug(f"Finished exporting {video_path}")
|
|
|
|
|
|
|
|
|
2024-09-13 22:14:51 +02:00
|
|
|
def migrate_exports(ffmpeg: FfmpegConfig, camera_names: list[str]):
|
2024-04-20 00:11:41 +02:00
|
|
|
Path(os.path.join(CLIPS_DIR, "export")).mkdir(exist_ok=True)
|
|
|
|
|
|
|
|
exports = []
|
|
|
|
for export_file in os.listdir(EXPORT_DIR):
|
|
|
|
camera = "unknown"
|
|
|
|
|
|
|
|
for cam_name in camera_names:
|
|
|
|
if cam_name in export_file:
|
|
|
|
camera = cam_name
|
|
|
|
break
|
|
|
|
|
|
|
|
id = f"{camera}_{''.join(random.choices(string.ascii_lowercase + string.digits, k=6))}"
|
|
|
|
video_path = os.path.join(EXPORT_DIR, export_file)
|
|
|
|
thumb_path = os.path.join(
|
|
|
|
CLIPS_DIR, f"export/{id}.jpg"
|
|
|
|
) # use jpg because webp encoder can't get quality low enough
|
|
|
|
|
|
|
|
ffmpeg_cmd = [
|
2024-09-13 22:14:51 +02:00
|
|
|
ffmpeg.ffmpeg_path,
|
2024-04-20 00:11:41 +02:00
|
|
|
"-hide_banner",
|
|
|
|
"-loglevel",
|
|
|
|
"warning",
|
|
|
|
"-i",
|
|
|
|
video_path,
|
|
|
|
"-vf",
|
|
|
|
"scale=-1:180",
|
|
|
|
"-frames",
|
|
|
|
"1",
|
|
|
|
"-q:v",
|
|
|
|
"8",
|
|
|
|
thumb_path,
|
|
|
|
]
|
|
|
|
|
|
|
|
process = sp.run(
|
|
|
|
ffmpeg_cmd,
|
|
|
|
capture_output=True,
|
|
|
|
)
|
|
|
|
|
|
|
|
if process.returncode != 0:
|
|
|
|
logger.error(process.stderr)
|
|
|
|
continue
|
|
|
|
|
|
|
|
exports.append(
|
|
|
|
{
|
|
|
|
Export.id: id,
|
|
|
|
Export.camera: camera,
|
|
|
|
Export.name: export_file.replace(".mp4", ""),
|
|
|
|
Export.date: os.path.getctime(video_path),
|
|
|
|
Export.video_path: video_path,
|
|
|
|
Export.thumb_path: thumb_path,
|
|
|
|
Export.in_progress: False,
|
|
|
|
}
|
|
|
|
)
|
2023-06-08 13:32:35 +02:00
|
|
|
|
2024-04-20 00:11:41 +02:00
|
|
|
Export.insert_many(exports).execute()
|