config.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  1. from __future__ import annotations
  2. import json
  3. import logging
  4. import os
  5. from enum import Enum
  6. from typing import Dict, List, Optional, Tuple, Union
  7. import matplotlib.pyplot as plt
  8. import numpy as np
  9. import yaml
  10. from pydantic import BaseModel, Field, validator
  11. from pydantic.fields import PrivateAttr
  12. from frigate.const import BASE_DIR, CACHE_DIR, RECORD_DIR
  13. from frigate.edgetpu import load_labels
  14. from frigate.util import create_mask, deep_merge
  15. logger = logging.getLogger(__name__)
  16. # TODO: Identify what the default format to display timestamps is
  17. DEFAULT_TIME_FORMAT = "%m/%d/%Y %H:%M:%S"
  18. # German Style:
  19. # DEFAULT_TIME_FORMAT = "%d.%m.%Y %H:%M:%S"
  20. FRIGATE_ENV_VARS = {k: v for k, v in os.environ.items() if k.startswith("FRIGATE_")}
  21. DEFAULT_TRACKED_OBJECTS = ["person"]
  22. DEFAULT_DETECTORS = {"cpu": {"type": "cpu"}}
  23. class DetectorTypeEnum(str, Enum):
  24. edgetpu = "edgetpu"
  25. cpu = "cpu"
  26. class DetectorConfig(BaseModel):
  27. type: DetectorTypeEnum = Field(default=DetectorTypeEnum.cpu, title="Detector Type")
  28. device: str = Field(default="usb", title="Device Type")
  29. num_threads: int = Field(default=3, title="Number of detection threads")
  30. class MqttConfig(BaseModel):
  31. host: str = Field(title="MQTT Host")
  32. port: int = Field(default=1883, title="MQTT Port")
  33. topic_prefix: str = Field(default="frigate", title="MQTT Topic Prefix")
  34. client_id: str = Field(default="frigate", title="MQTT Client ID")
  35. stats_interval: int = Field(default=60, title="MQTT Camera Stats Interval")
  36. user: Optional[str] = Field(title="MQTT Username")
  37. password: Optional[str] = Field(title="MQTT Password")
  38. tls_ca_certs: Optional[str] = Field(title="MQTT TLS CA Certificates")
  39. tls_client_cert: Optional[str] = Field(title="MQTT TLS Client Certificate")
  40. tls_client_key: Optional[str] = Field(title="MQTT TLS Client Key")
  41. tls_insecure: Optional[bool] = Field(title="MQTT TLS Insecure")
  42. @validator("password", pre=True, always=True)
  43. def validate_password(cls, v, values):
  44. if (v is None) != (values["user"] is None):
  45. raise ValueError("Password must be provided with username.")
  46. return v
  47. class RetainConfig(BaseModel):
  48. default: int = Field(default=10, title="Default retention period.")
  49. objects: Dict[str, int] = Field(
  50. default_factory=dict, title="Object retention period."
  51. )
  52. # DEPRECATED: Will eventually be removed
  53. class ClipsConfig(BaseModel):
  54. enabled: bool = Field(default=False, title="Save clips.")
  55. max_seconds: int = Field(default=300, title="Maximum clip duration.")
  56. pre_capture: int = Field(default=5, title="Seconds to capture before event starts.")
  57. post_capture: int = Field(default=5, title="Seconds to capture after event ends.")
  58. required_zones: List[str] = Field(
  59. default_factory=list,
  60. title="List of required zones to be entered in order to save the clip.",
  61. )
  62. objects: Optional[List[str]] = Field(
  63. title="List of objects to be detected in order to save the clip.",
  64. )
  65. retain: RetainConfig = Field(
  66. default_factory=RetainConfig, title="Clip retention settings."
  67. )
  68. class RecordConfig(BaseModel):
  69. enabled: bool = Field(default=False, title="Enable record on all cameras.")
  70. retain_days: int = Field(default=0, title="Recording retention period in days.")
  71. events: ClipsConfig = Field(
  72. default_factory=ClipsConfig, title="Event specific settings."
  73. )
  74. class MotionConfig(BaseModel):
  75. threshold: int = Field(
  76. default=25,
  77. title="Motion detection threshold (1-255).",
  78. ge=1,
  79. le=255,
  80. )
  81. contour_area: Optional[int] = Field(title="Contour Area")
  82. delta_alpha: float = Field(default=0.2, title="Delta Alpha")
  83. frame_alpha: float = Field(default=0.2, title="Frame Alpha")
  84. frame_height: Optional[int] = Field(title="Frame Height")
  85. mask: Union[str, List[str]] = Field(
  86. default="", title="Coordinates polygon for the motion mask."
  87. )
  88. class RuntimeMotionConfig(MotionConfig):
  89. raw_mask: Union[str, List[str]] = ""
  90. mask: np.ndarray = None
  91. def __init__(self, **config):
  92. frame_shape = config.get("frame_shape", (1, 1))
  93. if "frame_height" not in config:
  94. config["frame_height"] = max(frame_shape[0] // 6, 180)
  95. if "contour_area" not in config:
  96. frame_width = frame_shape[1] * config["frame_height"] / frame_shape[0]
  97. config["contour_area"] = (
  98. config["frame_height"] * frame_width * 0.00173611111
  99. )
  100. mask = config.get("mask", "")
  101. config["raw_mask"] = mask
  102. if mask:
  103. config["mask"] = create_mask(frame_shape, mask)
  104. else:
  105. empty_mask = np.zeros(frame_shape, np.uint8)
  106. empty_mask[:] = 255
  107. config["mask"] = empty_mask
  108. super().__init__(**config)
  109. def dict(self, **kwargs):
  110. ret = super().dict(**kwargs)
  111. if "mask" in ret:
  112. ret["mask"] = ret["raw_mask"]
  113. ret.pop("raw_mask")
  114. return ret
  115. class Config:
  116. arbitrary_types_allowed = True
  117. class DetectConfig(BaseModel):
  118. height: int = Field(title="Height of the stream for the detect role.")
  119. width: int = Field(title="Width of the stream for the detect role.")
  120. fps: int = Field(title="Number of frames per second to process through detection.")
  121. enabled: bool = Field(default=True, title="Detection Enabled.")
  122. max_disappeared: Optional[int] = Field(
  123. title="Maximum number of frames the object can dissapear before detection ends."
  124. )
  125. class FilterConfig(BaseModel):
  126. min_area: int = Field(
  127. default=0, title="Minimum area of bounding box for object to be counted."
  128. )
  129. max_area: int = Field(
  130. default=24000000, title="Maximum area of bounding box for object to be counted."
  131. )
  132. threshold: float = Field(
  133. default=0.7,
  134. title="Average detection confidence threshold for object to be counted.",
  135. )
  136. min_score: float = Field(
  137. default=0.5, title="Minimum detection confidence for object to be counted."
  138. )
  139. mask: Optional[Union[str, List[str]]] = Field(
  140. title="Detection area polygon mask for this filter configuration.",
  141. )
  142. class RuntimeFilterConfig(FilterConfig):
  143. mask: Optional[np.ndarray]
  144. raw_mask: Optional[Union[str, List[str]]]
  145. def __init__(self, **config):
  146. mask = config.get("mask")
  147. config["raw_mask"] = mask
  148. if mask is not None:
  149. config["mask"] = create_mask(config.get("frame_shape", (1, 1)), mask)
  150. super().__init__(**config)
  151. def dict(self, **kwargs):
  152. ret = super().dict(**kwargs)
  153. if "mask" in ret:
  154. ret["mask"] = ret["raw_mask"]
  155. ret.pop("raw_mask")
  156. return ret
  157. class Config:
  158. arbitrary_types_allowed = True
  159. class ZoneConfig(BaseModel):
  160. filters: Dict[str, FilterConfig] = Field(
  161. default_factory=dict, title="Zone filters."
  162. )
  163. coordinates: Union[str, List[str]] = Field(
  164. title="Coordinates polygon for the defined zone."
  165. )
  166. objects: List[str] = Field(
  167. default_factory=list,
  168. title="List of objects that can trigger the zone.",
  169. )
  170. _color: Optional[Tuple[int, int, int]] = PrivateAttr()
  171. _contour: np.ndarray = PrivateAttr()
  172. @property
  173. def color(self) -> Tuple[int, int, int]:
  174. return self._color
  175. @property
  176. def contour(self) -> np.ndarray:
  177. return self._contour
  178. def __init__(self, **config):
  179. super().__init__(**config)
  180. self._color = config.get("color", (0, 0, 0))
  181. coordinates = config["coordinates"]
  182. if isinstance(coordinates, list):
  183. self._contour = np.array(
  184. [[int(p.split(",")[0]), int(p.split(",")[1])] for p in coordinates]
  185. )
  186. elif isinstance(coordinates, str):
  187. points = coordinates.split(",")
  188. self._contour = np.array(
  189. [[int(points[i]), int(points[i + 1])] for i in range(0, len(points), 2)]
  190. )
  191. else:
  192. self._contour = np.array([])
  193. class ObjectConfig(BaseModel):
  194. track: List[str] = Field(default=DEFAULT_TRACKED_OBJECTS, title="Objects to track.")
  195. filters: Optional[Dict[str, FilterConfig]] = Field(title="Object filters.")
  196. mask: Union[str, List[str]] = Field(default="", title="Object mask.")
  197. class BirdseyeModeEnum(str, Enum):
  198. objects = "objects"
  199. motion = "motion"
  200. continuous = "continuous"
  201. class BirdseyeConfig(BaseModel):
  202. enabled: bool = Field(default=True, title="Enable birdseye view.")
  203. width: int = Field(default=1280, title="Birdseye width.")
  204. height: int = Field(default=720, title="Birdseye height.")
  205. quality: int = Field(
  206. default=8,
  207. title="Encoding quality.",
  208. ge=1,
  209. le=31,
  210. )
  211. mode: BirdseyeModeEnum = Field(
  212. default=BirdseyeModeEnum.objects, title="Tracking mode."
  213. )
  214. FFMPEG_GLOBAL_ARGS_DEFAULT = ["-hide_banner", "-loglevel", "warning"]
  215. FFMPEG_INPUT_ARGS_DEFAULT = [
  216. "-avoid_negative_ts",
  217. "make_zero",
  218. "-fflags",
  219. "+genpts+discardcorrupt",
  220. "-rtsp_transport",
  221. "tcp",
  222. "-stimeout",
  223. "5000000",
  224. "-use_wallclock_as_timestamps",
  225. "1",
  226. ]
  227. DETECT_FFMPEG_OUTPUT_ARGS_DEFAULT = ["-f", "rawvideo", "-pix_fmt", "yuv420p"]
  228. RTMP_FFMPEG_OUTPUT_ARGS_DEFAULT = ["-c", "copy", "-f", "flv"]
  229. RECORD_FFMPEG_OUTPUT_ARGS_DEFAULT = [
  230. "-f",
  231. "segment",
  232. "-segment_time",
  233. "10",
  234. "-segment_format",
  235. "mp4",
  236. "-reset_timestamps",
  237. "1",
  238. "-strftime",
  239. "1",
  240. "-c",
  241. "copy",
  242. "-an",
  243. ]
  244. class FfmpegOutputArgsConfig(BaseModel):
  245. detect: Union[str, List[str]] = Field(
  246. default=DETECT_FFMPEG_OUTPUT_ARGS_DEFAULT,
  247. title="Detect role FFmpeg output arguments.",
  248. )
  249. record: Union[str, List[str]] = Field(
  250. default=RECORD_FFMPEG_OUTPUT_ARGS_DEFAULT,
  251. title="Record role FFmpeg output arguments.",
  252. )
  253. rtmp: Union[str, List[str]] = Field(
  254. default=RTMP_FFMPEG_OUTPUT_ARGS_DEFAULT,
  255. title="RTMP role FFmpeg output arguments.",
  256. )
  257. class FfmpegConfig(BaseModel):
  258. global_args: Union[str, List[str]] = Field(
  259. default=FFMPEG_GLOBAL_ARGS_DEFAULT, title="Global FFmpeg arguments."
  260. )
  261. hwaccel_args: Union[str, List[str]] = Field(
  262. default_factory=list, title="FFmpeg hardware acceleration arguments."
  263. )
  264. input_args: Union[str, List[str]] = Field(
  265. default=FFMPEG_INPUT_ARGS_DEFAULT, title="FFmpeg input arguments."
  266. )
  267. output_args: FfmpegOutputArgsConfig = Field(
  268. default_factory=FfmpegOutputArgsConfig,
  269. title="FFmpeg output arguments per role.",
  270. )
  271. class CameraInput(BaseModel):
  272. path: str = Field(title="Camera input path.")
  273. roles: List[str] = Field(title="Roles assigned to this input.")
  274. global_args: Union[str, List[str]] = Field(
  275. default_factory=list, title="FFmpeg global arguments."
  276. )
  277. hwaccel_args: Union[str, List[str]] = Field(
  278. default_factory=list, title="FFmpeg hardware acceleration arguments."
  279. )
  280. input_args: Union[str, List[str]] = Field(
  281. default_factory=list, title="FFmpeg input arguments."
  282. )
  283. class CameraFfmpegConfig(FfmpegConfig):
  284. inputs: List[CameraInput] = Field(title="Camera inputs.")
  285. @validator("inputs")
  286. def validate_roles(cls, v):
  287. roles = [role for i in v for role in i.roles]
  288. roles_set = set(roles)
  289. if len(roles) > len(roles_set):
  290. raise ValueError("Each input role may only be used once.")
  291. if not "detect" in roles:
  292. raise ValueError("The detect role is required.")
  293. return v
  294. class CameraSnapshotsConfig(BaseModel):
  295. enabled: bool = Field(default=False, title="Snapshots enabled.")
  296. clean_copy: bool = Field(
  297. default=True, title="Create a clean copy of the snapshot image."
  298. )
  299. timestamp: bool = Field(
  300. default=False, title="Add a timestamp overlay on the snapshot."
  301. )
  302. bounding_box: bool = Field(
  303. default=True, title="Add a bounding box overlay on the snapshot."
  304. )
  305. crop: bool = Field(default=False, title="Crop the snapshot to the detected object.")
  306. required_zones: List[str] = Field(
  307. default_factory=list,
  308. title="List of required zones to be entered in order to save a snapshot.",
  309. )
  310. height: Optional[int] = Field(title="Snapshot image height.")
  311. retain: RetainConfig = Field(
  312. default_factory=RetainConfig, title="Snapshot retention."
  313. )
  314. quality: int = Field(
  315. default=70,
  316. title="Quality of the encoded jpeg (0-100).",
  317. ge=0,
  318. le=100,
  319. )
  320. class ColorConfig(BaseModel):
  321. red: int = Field(default=255, le=0, ge=255, title="Red")
  322. green: int = Field(default=255, le=0, ge=255, title="Green")
  323. blue: int = Field(default=255, le=0, ge=255, title="Blue")
  324. class TimestampStyleConfig(BaseModel):
  325. position: str = Field(default="tl", title="Timestamp position.")
  326. format: str = Field(default=DEFAULT_TIME_FORMAT, title="Timestamp format.")
  327. color: ColorConfig = Field(default_factory=ColorConfig, title="Timestamp color.")
  328. scale: float = Field(default=1.0, title="Timestamp scale.")
  329. thickness: int = Field(default=2, title="Timestamp thickness.")
  330. effect: Optional[str] = Field(title="Timestamp effect.")
  331. class CameraMqttConfig(BaseModel):
  332. enabled: bool = Field(default=True, title="Send image over MQTT.")
  333. timestamp: bool = Field(default=True, title="Add timestamp to MQTT image.")
  334. bounding_box: bool = Field(default=True, title="Add bounding box to MQTT image.")
  335. crop: bool = Field(default=True, title="Crop MQTT image to detected object.")
  336. height: int = Field(default=270, title="MQTT image height.")
  337. required_zones: List[str] = Field(
  338. default_factory=list,
  339. title="List of required zones to be entered in order to send the image.",
  340. )
  341. quality: int = Field(
  342. default=70,
  343. title="Quality of the encoded jpeg (0-100).",
  344. ge=0,
  345. le=100,
  346. )
  347. class CameraRtmpConfig(BaseModel):
  348. enabled: bool = Field(default=True, title="RTMP restreaming enabled.")
  349. class CameraLiveConfig(BaseModel):
  350. height: int = Field(default=720, title="Live camera view height")
  351. quality: int = Field(default=8, ge=1, le=31, title="Live camera view quality")
  352. class CameraConfig(BaseModel):
  353. name: Optional[str] = Field(title="Camera name.")
  354. ffmpeg: CameraFfmpegConfig = Field(title="FFmpeg configuration for the camera.")
  355. best_image_timeout: int = Field(
  356. default=60,
  357. title="How long to wait for the image with the highest confidence score.",
  358. )
  359. zones: Dict[str, ZoneConfig] = Field(
  360. default_factory=dict, title="Zone configuration."
  361. )
  362. record: RecordConfig = Field(
  363. default_factory=RecordConfig, title="Record configuration."
  364. )
  365. rtmp: CameraRtmpConfig = Field(
  366. default_factory=CameraRtmpConfig, title="RTMP restreaming configuration."
  367. )
  368. live: Optional[CameraLiveConfig] = Field(title="Live playback settings.")
  369. snapshots: CameraSnapshotsConfig = Field(
  370. default_factory=CameraSnapshotsConfig, title="Snapshot configuration."
  371. )
  372. mqtt: CameraMqttConfig = Field(
  373. default_factory=CameraMqttConfig, title="MQTT configuration."
  374. )
  375. objects: ObjectConfig = Field(
  376. default_factory=ObjectConfig, title="Object configuration."
  377. )
  378. motion: Optional[MotionConfig] = Field(title="Motion detection configuration.")
  379. detect: DetectConfig = Field(title="Object detection configuration.")
  380. timestamp_style: TimestampStyleConfig = Field(
  381. default_factory=TimestampStyleConfig, title="Timestamp style configuration."
  382. )
  383. def __init__(self, **config):
  384. # Set zone colors
  385. if "zones" in config:
  386. colors = plt.cm.get_cmap("tab10", len(config["zones"]))
  387. config["zones"] = {
  388. name: {**z, "color": tuple(round(255 * c) for c in colors(idx)[:3])}
  389. for idx, (name, z) in enumerate(config["zones"].items())
  390. }
  391. super().__init__(**config)
  392. @property
  393. def frame_shape(self) -> Tuple[int, int]:
  394. return self.detect.height, self.detect.width
  395. @property
  396. def frame_shape_yuv(self) -> Tuple[int, int]:
  397. return self.detect.height * 3 // 2, self.detect.width
  398. @property
  399. def ffmpeg_cmds(self) -> List[Dict[str, List[str]]]:
  400. ffmpeg_cmds = []
  401. for ffmpeg_input in self.ffmpeg.inputs:
  402. ffmpeg_cmd = self._get_ffmpeg_cmd(ffmpeg_input)
  403. if ffmpeg_cmd is None:
  404. continue
  405. ffmpeg_cmds.append({"roles": ffmpeg_input.roles, "cmd": ffmpeg_cmd})
  406. return ffmpeg_cmds
  407. def _get_ffmpeg_cmd(self, ffmpeg_input: CameraInput):
  408. ffmpeg_output_args = []
  409. if "detect" in ffmpeg_input.roles:
  410. detect_args = (
  411. self.ffmpeg.output_args.detect
  412. if isinstance(self.ffmpeg.output_args.detect, list)
  413. else self.ffmpeg.output_args.detect.split(" ")
  414. )
  415. ffmpeg_output_args = (
  416. [
  417. "-r",
  418. str(self.detect.fps),
  419. "-s",
  420. f"{self.detect.width}x{self.detect.height}",
  421. ]
  422. + detect_args
  423. + ffmpeg_output_args
  424. + ["pipe:"]
  425. )
  426. if "rtmp" in ffmpeg_input.roles and self.rtmp.enabled:
  427. rtmp_args = (
  428. self.ffmpeg.output_args.rtmp
  429. if isinstance(self.ffmpeg.output_args.rtmp, list)
  430. else self.ffmpeg.output_args.rtmp.split(" ")
  431. )
  432. ffmpeg_output_args = (
  433. rtmp_args + [f"rtmp://127.0.0.1/live/{self.name}"] + ffmpeg_output_args
  434. )
  435. if "record" in ffmpeg_input.roles and self.record.enabled:
  436. record_args = (
  437. self.ffmpeg.output_args.record
  438. if isinstance(self.ffmpeg.output_args.record, list)
  439. else self.ffmpeg.output_args.record.split(" ")
  440. )
  441. ffmpeg_output_args = (
  442. record_args
  443. + [f"{os.path.join(CACHE_DIR, self.name)}-%Y%m%d%H%M%S.mp4"]
  444. + ffmpeg_output_args
  445. )
  446. # if there arent any outputs enabled for this input
  447. if len(ffmpeg_output_args) == 0:
  448. return None
  449. global_args = ffmpeg_input.global_args or self.ffmpeg.global_args
  450. hwaccel_args = ffmpeg_input.hwaccel_args or self.ffmpeg.hwaccel_args
  451. input_args = ffmpeg_input.input_args or self.ffmpeg.input_args
  452. global_args = (
  453. global_args if isinstance(global_args, list) else global_args.split(" ")
  454. )
  455. hwaccel_args = (
  456. hwaccel_args if isinstance(hwaccel_args, list) else hwaccel_args.split(" ")
  457. )
  458. input_args = (
  459. input_args if isinstance(input_args, list) else input_args.split(" ")
  460. )
  461. cmd = (
  462. ["ffmpeg"]
  463. + global_args
  464. + hwaccel_args
  465. + input_args
  466. + ["-i", ffmpeg_input.path]
  467. + ffmpeg_output_args
  468. )
  469. return [part for part in cmd if part != ""]
  470. class DatabaseConfig(BaseModel):
  471. path: str = Field(
  472. default=os.path.join(BASE_DIR, "frigate.db"), title="Database path."
  473. )
  474. class ModelConfig(BaseModel):
  475. width: int = Field(default=320, title="Object detection model input width.")
  476. height: int = Field(default=320, title="Object detection model input height.")
  477. labelmap: Dict[int, str] = Field(
  478. default_factory=dict, title="Labelmap customization."
  479. )
  480. _merged_labelmap: Optional[Dict[int, str]] = PrivateAttr()
  481. _colormap: Dict[int, Tuple[int, int, int]] = PrivateAttr()
  482. @property
  483. def merged_labelmap(self) -> Dict[int, str]:
  484. return self._merged_labelmap
  485. @property
  486. def colormap(self) -> Dict[int, tuple[int, int, int]]:
  487. return self._colormap
  488. def __init__(self, **config):
  489. super().__init__(**config)
  490. self._merged_labelmap = {
  491. **load_labels("/labelmap.txt"),
  492. **config.get("labelmap", {}),
  493. }
  494. cmap = plt.cm.get_cmap("tab10", len(self._merged_labelmap.keys()))
  495. self._colormap = {}
  496. for key, val in self._merged_labelmap.items():
  497. self._colormap[val] = tuple(int(round(255 * c)) for c in cmap(key)[:3])
  498. class LogLevelEnum(str, Enum):
  499. debug = "debug"
  500. info = "info"
  501. warning = "warning"
  502. error = "error"
  503. critical = "critical"
  504. class LoggerConfig(BaseModel):
  505. default: LogLevelEnum = Field(
  506. default=LogLevelEnum.info, title="Default logging level."
  507. )
  508. logs: Dict[str, LogLevelEnum] = Field(
  509. default_factory=dict, title="Log level for specified processes."
  510. )
  511. class SnapshotsConfig(BaseModel):
  512. retain: RetainConfig = Field(
  513. default_factory=RetainConfig, title="Global snapshot retention configuration."
  514. )
  515. class FrigateConfig(BaseModel):
  516. mqtt: MqttConfig = Field(title="MQTT Configuration.")
  517. database: DatabaseConfig = Field(
  518. default_factory=DatabaseConfig, title="Database configuration."
  519. )
  520. environment_vars: Dict[str, str] = Field(
  521. default_factory=dict, title="Frigate environment variables."
  522. )
  523. model: ModelConfig = Field(
  524. default_factory=ModelConfig, title="Detection model configuration."
  525. )
  526. detectors: Dict[str, DetectorConfig] = Field(
  527. default={name: DetectorConfig(**d) for name, d in DEFAULT_DETECTORS.items()},
  528. title="Detector hardware configuration.",
  529. )
  530. logger: LoggerConfig = Field(
  531. default_factory=LoggerConfig, title="Logging configuration."
  532. )
  533. record: RecordConfig = Field(
  534. default_factory=RecordConfig, title="Global record configuration."
  535. )
  536. snapshots: SnapshotsConfig = Field(
  537. default_factory=SnapshotsConfig, title="Global snapshots configuration."
  538. )
  539. birdseye: BirdseyeConfig = Field(
  540. default_factory=BirdseyeConfig, title="Birdseye configuration."
  541. )
  542. ffmpeg: FfmpegConfig = Field(
  543. default_factory=FfmpegConfig, title="Global FFmpeg configuration."
  544. )
  545. objects: ObjectConfig = Field(
  546. default_factory=ObjectConfig, title="Global object configuration."
  547. )
  548. motion: Optional[MotionConfig] = Field(
  549. title="Global motion detection configuration."
  550. )
  551. detect: Optional[DetectConfig] = Field(
  552. title="Global object tracking configuration."
  553. )
  554. cameras: Dict[str, CameraConfig] = Field(title="Camera configuration.")
  555. @property
  556. def runtime_config(self) -> FrigateConfig:
  557. """Merge camera config with globals."""
  558. config = self.copy(deep=True)
  559. # MQTT password substitution
  560. if config.mqtt.password:
  561. config.mqtt.password = config.mqtt.password.format(**FRIGATE_ENV_VARS)
  562. # Global config to propegate down to camera level
  563. global_config = config.dict(
  564. include={
  565. "record": ...,
  566. "snapshots": ...,
  567. "objects": ...,
  568. "motion": ...,
  569. "detect": ...,
  570. "ffmpeg": ...,
  571. },
  572. exclude_unset=True,
  573. )
  574. for name, camera in config.cameras.items():
  575. merged_config = deep_merge(camera.dict(exclude_unset=True), global_config)
  576. camera_config: CameraConfig = CameraConfig.parse_obj(
  577. {"name": name, **merged_config}
  578. )
  579. # FFMPEG input substitution
  580. for input in camera_config.ffmpeg.inputs:
  581. input.path = input.path.format(**FRIGATE_ENV_VARS)
  582. # Add default filters
  583. object_keys = camera_config.objects.track
  584. if camera_config.objects.filters is None:
  585. camera_config.objects.filters = {}
  586. object_keys = object_keys - camera_config.objects.filters.keys()
  587. for key in object_keys:
  588. camera_config.objects.filters[key] = FilterConfig()
  589. # Apply global object masks and convert masks to numpy array
  590. for object, filter in camera_config.objects.filters.items():
  591. if camera_config.objects.mask:
  592. filter_mask = []
  593. if filter.mask is not None:
  594. filter_mask = (
  595. filter.mask
  596. if isinstance(filter.mask, list)
  597. else [filter.mask]
  598. )
  599. object_mask = (
  600. camera_config.objects.mask
  601. if isinstance(camera_config.objects.mask, list)
  602. else [camera_config.objects.mask]
  603. )
  604. filter.mask = filter_mask + object_mask
  605. # Set runtime filter to create masks
  606. camera_config.objects.filters[object] = RuntimeFilterConfig(
  607. frame_shape=camera_config.frame_shape,
  608. **filter.dict(exclude_unset=True),
  609. )
  610. # Convert motion configuration
  611. if camera_config.motion is None:
  612. camera_config.motion = RuntimeMotionConfig(
  613. frame_shape=camera_config.frame_shape
  614. )
  615. else:
  616. camera_config.motion = RuntimeMotionConfig(
  617. frame_shape=camera_config.frame_shape,
  618. raw_mask=camera_config.motion.mask,
  619. **camera_config.motion.dict(exclude_unset=True),
  620. )
  621. # Default detect configuration
  622. max_disappeared = camera_config.detect.fps * 5
  623. if camera_config.detect.max_disappeared is None:
  624. camera_config.detect.max_disappeared = max_disappeared
  625. # Default live configuration
  626. if camera_config.live is None:
  627. camera_config.live = CameraLiveConfig()
  628. config.cameras[name] = camera_config
  629. return config
  630. @validator("cameras")
  631. def ensure_zones_and_cameras_have_different_names(cls, v: Dict[str, CameraConfig]):
  632. zones = [zone for camera in v.values() for zone in camera.zones.keys()]
  633. for zone in zones:
  634. if zone in v.keys():
  635. raise ValueError("Zones cannot share names with cameras")
  636. return v
  637. @classmethod
  638. def parse_file(cls, config_file):
  639. with open(config_file) as f:
  640. raw_config = f.read()
  641. if config_file.endswith(".yml"):
  642. config = yaml.safe_load(raw_config)
  643. elif config_file.endswith(".json"):
  644. config = json.loads(raw_config)
  645. return cls.parse_obj(config)