config.py 26 KB

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