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
|
2023-06-08 13:32:35 +02:00
|
|
|
|
2024-06-04 17:10:19 +02:00
|
|
|
from peewee import DoesNotExist
|
|
|
|
|
2023-06-08 13:32:35 +02:00
|
|
|
from frigate.config import 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"
|
|
|
|
|
|
|
|
|
|
|
|
class RecordingExporter(threading.Thread):
|
|
|
|
"""Exports a specific set of recordings for a camera to storage as a single file."""
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
config: FrigateConfig,
|
|
|
|
camera: str,
|
2024-03-26 22:37:45 +01:00
|
|
|
name: str,
|
2023-06-08 13:32:35 +02:00
|
|
|
start_time: int,
|
|
|
|
end_time: int,
|
|
|
|
playback_factor: PlaybackFactorEnum,
|
|
|
|
) -> None:
|
|
|
|
threading.Thread.__init__(self)
|
|
|
|
self.config = config
|
|
|
|
self.camera = camera
|
2024-03-26 22:37:45 +01:00
|
|
|
self.user_provided_name = name
|
2023-06-08 13:32:35 +02:00
|
|
|
self.start_time = start_time
|
|
|
|
self.end_time = end_time
|
|
|
|
self.playback_factor = playback_factor
|
|
|
|
|
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")
|
|
|
|
|
|
|
|
if datetime.datetime.fromtimestamp(
|
|
|
|
self.start_time
|
2024-06-04 17:10:19 +02:00
|
|
|
) < datetime.datetime.now().astimezone(datetime.timezone.dst).replace(
|
|
|
|
minute=0, second=0, microsecond=0
|
|
|
|
):
|
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 = [
|
|
|
|
"ffmpeg",
|
|
|
|
"-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
|
|
|
|
|
|
|
def run(self) -> None:
|
|
|
|
logger.debug(
|
|
|
|
f"Beginning export for {self.camera} from {self.start_time} to {self.end_time}"
|
|
|
|
)
|
2024-04-20 00:11:41 +02:00
|
|
|
export_id = f"{self.camera}_{''.join(random.choices(string.ascii_lowercase + string.digits, k=6))}"
|
|
|
|
export_name = (
|
2024-03-26 22:37:45 +01:00
|
|
|
self.user_provided_name
|
2024-04-20 00:11:41 +02:00
|
|
|
or f"{self.camera.replace('_', ' ')} {self.get_datetime_from_timestamp(self.start_time)} {self.get_datetime_from_timestamp(self.end_time)}"
|
2024-03-26 22:37:45 +01:00
|
|
|
)
|
2024-04-20 00:11:41 +02:00
|
|
|
video_path = f"{EXPORT_DIR}/{export_id}.mp4"
|
|
|
|
|
|
|
|
thumb_path = self.save_thumbnail(export_id)
|
|
|
|
|
|
|
|
Export.insert(
|
|
|
|
{
|
|
|
|
Export.id: 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()
|
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 = (
|
|
|
|
Recordings.select()
|
|
|
|
.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"
|
|
|
|
|
|
|
|
if self.playback_factor == PlaybackFactorEnum.realtime:
|
|
|
|
ffmpeg_cmd = (
|
2024-04-20 00:11:41 +02:00
|
|
|
f"ffmpeg -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(
|
|
|
|
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(" ")
|
|
|
|
|
|
|
|
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(
|
|
|
|
f"Failed to export recording for command {' '.join(ffmpeg_cmd)}"
|
|
|
|
)
|
|
|
|
logger.error(p.stderr)
|
2024-04-20 00:11:41 +02:00
|
|
|
Path(video_path).unlink(missing_ok=True)
|
|
|
|
Export.delete().where(Export.id == export_id).execute()
|
|
|
|
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(
|
|
|
|
Export.id == export_id
|
|
|
|
).execute()
|
|
|
|
|
|
|
|
logger.debug(f"Finished exporting {video_path}")
|
|
|
|
|
|
|
|
|
|
|
|
def migrate_exports(camera_names: list[str]):
|
|
|
|
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 = [
|
|
|
|
"ffmpeg",
|
|
|
|
"-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()
|