config.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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, Extra, 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 FrigateBaseModel(BaseModel):
  24. class Config:
  25. extra = Extra.forbid
  26. class DetectorTypeEnum(str, Enum):
  27. edgetpu = "edgetpu"
  28. cpu = "cpu"
  29. class DetectorConfig(FrigateBaseModel):
  30. type: DetectorTypeEnum = Field(default=DetectorTypeEnum.cpu, title="Detector Type")
  31. device: str = Field(default="usb", title="Device Type")
  32. num_threads: int = Field(default=3, title="Number of detection threads")
  33. class MqttConfig(FrigateBaseModel):
  34. host: str = Field(title="MQTT Host")
  35. port: int = Field(default=1883, title="MQTT Port")
  36. topic_prefix: str = Field(default="frigate", title="MQTT Topic Prefix")
  37. client_id: str = Field(default="frigate", title="MQTT Client ID")
  38. stats_interval: int = Field(default=60, title="MQTT Camera Stats Interval")
  39. user: Optional[str] = Field(title="MQTT Username")
  40. password: Optional[str] = Field(title="MQTT Password")
  41. tls_ca_certs: Optional[str] = Field(title="MQTT TLS CA Certificates")
  42. tls_client_cert: Optional[str] = Field(title="MQTT TLS Client Certificate")
  43. tls_client_key: Optional[str] = Field(title="MQTT TLS Client Key")
  44. tls_insecure: Optional[bool] = Field(title="MQTT TLS Insecure")
  45. @validator("password", pre=True, always=True)
  46. def validate_password(cls, v, values):
  47. if (v is None) != (values["user"] is None):
  48. raise ValueError("Password must be provided with username.")
  49. return v
  50. class RetainConfig(FrigateBaseModel):
  51. default: float = Field(default=10, title="Default retention period.")
  52. objects: Dict[str, float] = Field(
  53. default_factory=dict, title="Object retention period."
  54. )
  55. class EventsConfig(FrigateBaseModel):
  56. max_seconds: int = Field(default=300, title="Maximum event duration.")
  57. pre_capture: int = Field(default=5, title="Seconds to retain before event starts.")
  58. post_capture: int = Field(default=5, title="Seconds to retain after event ends.")
  59. required_zones: List[str] = Field(
  60. default_factory=list,
  61. title="List of required zones to be entered in order to save the event.",
  62. )
  63. objects: Optional[List[str]] = Field(
  64. title="List of objects to be detected in order to save the event.",
  65. )
  66. retain: RetainConfig = Field(
  67. default_factory=RetainConfig, title="Event retention settings."
  68. )
  69. class RecordConfig(FrigateBaseModel):
  70. enabled: bool = Field(default=False, title="Enable record on all cameras.")
  71. retain_days: float = Field(default=0, title="Recording retention period in days.")
  72. events: EventsConfig = Field(
  73. default_factory=EventsConfig, title="Event specific settings."
  74. )
  75. class MotionConfig(FrigateBaseModel):
  76. threshold: int = Field(
  77. default=25,
  78. title="Motion detection threshold (1-255).",
  79. ge=1,
  80. le=255,
  81. )
  82. contour_area: Optional[int] = Field(default=30, title="Contour Area")
  83. delta_alpha: float = Field(default=0.2, title="Delta Alpha")
  84. frame_alpha: float = Field(default=0.2, title="Frame Alpha")
  85. frame_height: Optional[int] = Field(default=50, title="Frame Height")
  86. mask: Union[str, List[str]] = Field(
  87. default="", title="Coordinates polygon for the motion mask."
  88. )
  89. class RuntimeMotionConfig(MotionConfig):
  90. raw_mask: Union[str, List[str]] = ""
  91. mask: np.ndarray = None
  92. def __init__(self, **config):
  93. frame_shape = config.get("frame_shape", (1, 1))
  94. mask = config.get("mask", "")
  95. config["raw_mask"] = mask
  96. if mask:
  97. config["mask"] = create_mask(frame_shape, mask)
  98. else:
  99. empty_mask = np.zeros(frame_shape, np.uint8)
  100. empty_mask[:] = 255
  101. config["mask"] = empty_mask
  102. super().__init__(**config)
  103. def dict(self, **kwargs):
  104. ret = super().dict(**kwargs)
  105. if "mask" in ret:
  106. ret["mask"] = ret["raw_mask"]
  107. ret.pop("raw_mask")
  108. return ret
  109. class Config:
  110. arbitrary_types_allowed = True
  111. extra = Extra.ignore
  112. class DetectConfig(FrigateBaseModel):
  113. height: int = Field(default=720, title="Height of the stream for the detect role.")
  114. width: int = Field(default=1280, title="Width of the stream for the detect role.")
  115. fps: int = Field(
  116. default=5, title="Number of frames per second to process through detection."
  117. )
  118. enabled: bool = Field(default=True, title="Detection Enabled.")
  119. max_disappeared: Optional[int] = Field(
  120. title="Maximum number of frames the object can dissapear before detection ends."
  121. )
  122. stationary_interval: Optional[int] = Field(
  123. title="Frame interval for checking stationary objects."
  124. )
  125. class FilterConfig(FrigateBaseModel):
  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. extra = Extra.ignore
  160. # this uses the base model because the color is an extra attribute
  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(FrigateBaseModel):
  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(FrigateBaseModel):
  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(FrigateBaseModel):
  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(FrigateBaseModel):
  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(FrigateBaseModel):
  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(FrigateBaseModel):
  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(FrigateBaseModel):
  327. red: int = Field(default=255, ge=0, le=255, title="Red")
  328. green: int = Field(default=255, ge=0, le=255, title="Green")
  329. blue: int = Field(default=255, ge=0, le=255, title="Blue")
  330. class TimestampPositionEnum(str, Enum):
  331. tl = "tl"
  332. tr = "tr"
  333. bl = "bl"
  334. br = "br"
  335. class TimestampEffectEnum(str, Enum):
  336. solid = "solid"
  337. shadow = "shadow"
  338. class TimestampStyleConfig(FrigateBaseModel):
  339. position: TimestampPositionEnum = Field(
  340. default=TimestampPositionEnum.tl, title="Timestamp position."
  341. )
  342. format: str = Field(default=DEFAULT_TIME_FORMAT, title="Timestamp format.")
  343. color: ColorConfig = Field(default_factory=ColorConfig, title="Timestamp color.")
  344. thickness: int = Field(default=2, title="Timestamp thickness.")
  345. effect: Optional[TimestampEffectEnum] = Field(title="Timestamp effect.")
  346. class CameraMqttConfig(FrigateBaseModel):
  347. enabled: bool = Field(default=True, title="Send image over MQTT.")
  348. timestamp: bool = Field(default=True, title="Add timestamp to MQTT image.")
  349. bounding_box: bool = Field(default=True, title="Add bounding box to MQTT image.")
  350. crop: bool = Field(default=True, title="Crop MQTT image to detected object.")
  351. height: int = Field(default=270, title="MQTT image height.")
  352. required_zones: List[str] = Field(
  353. default_factory=list,
  354. title="List of required zones to be entered in order to send the image.",
  355. )
  356. quality: int = Field(
  357. default=70,
  358. title="Quality of the encoded jpeg (0-100).",
  359. ge=0,
  360. le=100,
  361. )
  362. class RtmpConfig(FrigateBaseModel):
  363. enabled: bool = Field(default=True, title="RTMP restreaming enabled.")
  364. class CameraLiveConfig(FrigateBaseModel):
  365. height: int = Field(default=720, title="Live camera view height")
  366. quality: int = Field(default=8, ge=1, le=31, title="Live camera view quality")
  367. class CameraConfig(FrigateBaseModel):
  368. name: Optional[str] = Field(title="Camera name.")
  369. ffmpeg: CameraFfmpegConfig = Field(title="FFmpeg configuration for the camera.")
  370. best_image_timeout: int = Field(
  371. default=60,
  372. title="How long to wait for the image with the highest confidence score.",
  373. )
  374. zones: Dict[str, ZoneConfig] = Field(
  375. default_factory=dict, title="Zone configuration."
  376. )
  377. record: RecordConfig = Field(
  378. default_factory=RecordConfig, title="Record configuration."
  379. )
  380. rtmp: RtmpConfig = Field(
  381. default_factory=RtmpConfig, title="RTMP restreaming configuration."
  382. )
  383. live: CameraLiveConfig = Field(
  384. default_factory=CameraLiveConfig, title="Live playback settings."
  385. )
  386. snapshots: SnapshotsConfig = Field(
  387. default_factory=SnapshotsConfig, title="Snapshot configuration."
  388. )
  389. mqtt: CameraMqttConfig = Field(
  390. default_factory=CameraMqttConfig, title="MQTT configuration."
  391. )
  392. objects: ObjectConfig = Field(
  393. default_factory=ObjectConfig, title="Object configuration."
  394. )
  395. motion: Optional[MotionConfig] = Field(title="Motion detection configuration.")
  396. detect: DetectConfig = Field(
  397. default_factory=DetectConfig, title="Object detection configuration."
  398. )
  399. timestamp_style: TimestampStyleConfig = Field(
  400. default_factory=TimestampStyleConfig, title="Timestamp style configuration."
  401. )
  402. def __init__(self, **config):
  403. # Set zone colors
  404. if "zones" in config:
  405. colors = plt.cm.get_cmap("tab10", len(config["zones"]))
  406. config["zones"] = {
  407. name: {**z, "color": tuple(round(255 * c) for c in colors(idx)[:3])}
  408. for idx, (name, z) in enumerate(config["zones"].items())
  409. }
  410. # add roles to the input if there is only one
  411. if len(config["ffmpeg"]["inputs"]) == 1:
  412. config["ffmpeg"]["inputs"][0]["roles"] = ["record", "rtmp", "detect"]
  413. super().__init__(**config)
  414. @property
  415. def frame_shape(self) -> Tuple[int, int]:
  416. return self.detect.height, self.detect.width
  417. @property
  418. def frame_shape_yuv(self) -> Tuple[int, int]:
  419. return self.detect.height * 3 // 2, self.detect.width
  420. @property
  421. def ffmpeg_cmds(self) -> List[Dict[str, List[str]]]:
  422. ffmpeg_cmds = []
  423. for ffmpeg_input in self.ffmpeg.inputs:
  424. ffmpeg_cmd = self._get_ffmpeg_cmd(ffmpeg_input)
  425. if ffmpeg_cmd is None:
  426. continue
  427. ffmpeg_cmds.append({"roles": ffmpeg_input.roles, "cmd": ffmpeg_cmd})
  428. return ffmpeg_cmds
  429. def _get_ffmpeg_cmd(self, ffmpeg_input: CameraInput):
  430. ffmpeg_output_args = []
  431. if "detect" in ffmpeg_input.roles:
  432. detect_args = (
  433. self.ffmpeg.output_args.detect
  434. if isinstance(self.ffmpeg.output_args.detect, list)
  435. else self.ffmpeg.output_args.detect.split(" ")
  436. )
  437. ffmpeg_output_args = (
  438. [
  439. "-r",
  440. str(self.detect.fps),
  441. "-s",
  442. f"{self.detect.width}x{self.detect.height}",
  443. ]
  444. + detect_args
  445. + ffmpeg_output_args
  446. + ["pipe:"]
  447. )
  448. if "rtmp" in ffmpeg_input.roles and self.rtmp.enabled:
  449. rtmp_args = (
  450. self.ffmpeg.output_args.rtmp
  451. if isinstance(self.ffmpeg.output_args.rtmp, list)
  452. else self.ffmpeg.output_args.rtmp.split(" ")
  453. )
  454. ffmpeg_output_args = (
  455. rtmp_args + [f"rtmp://127.0.0.1/live/{self.name}"] + ffmpeg_output_args
  456. )
  457. if "record" in ffmpeg_input.roles and self.record.enabled:
  458. record_args = (
  459. self.ffmpeg.output_args.record
  460. if isinstance(self.ffmpeg.output_args.record, list)
  461. else self.ffmpeg.output_args.record.split(" ")
  462. )
  463. ffmpeg_output_args = (
  464. record_args
  465. + [f"{os.path.join(CACHE_DIR, self.name)}-%Y%m%d%H%M%S.mp4"]
  466. + ffmpeg_output_args
  467. )
  468. # if there arent any outputs enabled for this input
  469. if len(ffmpeg_output_args) == 0:
  470. return None
  471. global_args = ffmpeg_input.global_args or self.ffmpeg.global_args
  472. hwaccel_args = ffmpeg_input.hwaccel_args or self.ffmpeg.hwaccel_args
  473. input_args = ffmpeg_input.input_args or self.ffmpeg.input_args
  474. global_args = (
  475. global_args if isinstance(global_args, list) else global_args.split(" ")
  476. )
  477. hwaccel_args = (
  478. hwaccel_args if isinstance(hwaccel_args, list) else hwaccel_args.split(" ")
  479. )
  480. input_args = (
  481. input_args if isinstance(input_args, list) else input_args.split(" ")
  482. )
  483. cmd = (
  484. ["ffmpeg"]
  485. + global_args
  486. + hwaccel_args
  487. + input_args
  488. + ["-i", ffmpeg_input.path]
  489. + ffmpeg_output_args
  490. )
  491. return [part for part in cmd if part != ""]
  492. class DatabaseConfig(FrigateBaseModel):
  493. path: str = Field(
  494. default=os.path.join(BASE_DIR, "frigate.db"), title="Database path."
  495. )
  496. class ModelConfig(FrigateBaseModel):
  497. path: Optional[str] = Field(title="Custom Object detection model path.")
  498. labelmap_path: Optional[str] = Field(title="Label map for custom object detector.")
  499. width: int = Field(default=320, title="Object detection model input width.")
  500. height: int = Field(default=320, title="Object detection model input height.")
  501. labelmap: Dict[int, str] = Field(
  502. default_factory=dict, title="Labelmap customization."
  503. )
  504. _merged_labelmap: Optional[Dict[int, str]] = PrivateAttr()
  505. _colormap: Dict[int, Tuple[int, int, int]] = PrivateAttr()
  506. @property
  507. def merged_labelmap(self) -> Dict[int, str]:
  508. return self._merged_labelmap
  509. @property
  510. def colormap(self) -> Dict[int, tuple[int, int, int]]:
  511. return self._colormap
  512. def __init__(self, **config):
  513. super().__init__(**config)
  514. self._merged_labelmap = {
  515. **load_labels(config.get("labelmap_path", "/labelmap.txt")),
  516. **config.get("labelmap", {}),
  517. }
  518. cmap = plt.cm.get_cmap("tab10", len(self._merged_labelmap.keys()))
  519. self._colormap = {}
  520. for key, val in self._merged_labelmap.items():
  521. self._colormap[val] = tuple(int(round(255 * c)) for c in cmap(key)[:3])
  522. class LogLevelEnum(str, Enum):
  523. debug = "debug"
  524. info = "info"
  525. warning = "warning"
  526. error = "error"
  527. critical = "critical"
  528. class LoggerConfig(FrigateBaseModel):
  529. default: LogLevelEnum = Field(
  530. default=LogLevelEnum.info, title="Default logging level."
  531. )
  532. logs: Dict[str, LogLevelEnum] = Field(
  533. default_factory=dict, title="Log level for specified processes."
  534. )
  535. class FrigateConfig(FrigateBaseModel):
  536. mqtt: MqttConfig = Field(title="MQTT Configuration.")
  537. database: DatabaseConfig = Field(
  538. default_factory=DatabaseConfig, title="Database configuration."
  539. )
  540. environment_vars: Dict[str, str] = Field(
  541. default_factory=dict, title="Frigate environment variables."
  542. )
  543. model: ModelConfig = Field(
  544. default_factory=ModelConfig, title="Detection model configuration."
  545. )
  546. detectors: Dict[str, DetectorConfig] = Field(
  547. default={name: DetectorConfig(**d) for name, d in DEFAULT_DETECTORS.items()},
  548. title="Detector hardware configuration.",
  549. )
  550. logger: LoggerConfig = Field(
  551. default_factory=LoggerConfig, title="Logging configuration."
  552. )
  553. record: RecordConfig = Field(
  554. default_factory=RecordConfig, title="Global record configuration."
  555. )
  556. snapshots: SnapshotsConfig = Field(
  557. default_factory=SnapshotsConfig, title="Global snapshots configuration."
  558. )
  559. live: CameraLiveConfig = Field(
  560. default_factory=CameraLiveConfig, title="Global live configuration."
  561. )
  562. rtmp: RtmpConfig = Field(
  563. default_factory=RtmpConfig, title="Global RTMP restreaming configuration."
  564. )
  565. birdseye: BirdseyeConfig = Field(
  566. default_factory=BirdseyeConfig, title="Birdseye configuration."
  567. )
  568. ffmpeg: FfmpegConfig = Field(
  569. default_factory=FfmpegConfig, title="Global FFmpeg configuration."
  570. )
  571. objects: ObjectConfig = Field(
  572. default_factory=ObjectConfig, title="Global object configuration."
  573. )
  574. motion: Optional[MotionConfig] = Field(
  575. title="Global motion detection configuration."
  576. )
  577. detect: DetectConfig = Field(
  578. default_factory=DetectConfig, title="Global object tracking configuration."
  579. )
  580. cameras: Dict[str, CameraConfig] = Field(title="Camera configuration.")
  581. timestamp_style: TimestampStyleConfig = Field(
  582. default_factory=TimestampStyleConfig,
  583. title="Global timestamp style configuration.",
  584. )
  585. @property
  586. def runtime_config(self) -> FrigateConfig:
  587. """Merge camera config with globals."""
  588. config = self.copy(deep=True)
  589. # MQTT password substitution
  590. if config.mqtt.password:
  591. config.mqtt.password = config.mqtt.password.format(**FRIGATE_ENV_VARS)
  592. # Global config to propegate down to camera level
  593. global_config = config.dict(
  594. include={
  595. "record": ...,
  596. "snapshots": ...,
  597. "live": ...,
  598. "rtmp": ...,
  599. "objects": ...,
  600. "motion": ...,
  601. "detect": ...,
  602. "ffmpeg": ...,
  603. "timestamp_style": ...,
  604. },
  605. exclude_unset=True,
  606. )
  607. for name, camera in config.cameras.items():
  608. merged_config = deep_merge(camera.dict(exclude_unset=True), global_config)
  609. camera_config: CameraConfig = CameraConfig.parse_obj(
  610. {"name": name, **merged_config}
  611. )
  612. # Default max_disappeared configuration
  613. max_disappeared = camera_config.detect.fps * 5
  614. if camera_config.detect.max_disappeared is None:
  615. camera_config.detect.max_disappeared = max_disappeared
  616. # Default stationary_interval configuration
  617. stationary_interval = camera_config.detect.fps * 10
  618. if camera_config.detect.stationary_interval is None:
  619. camera_config.detect.stationary_interval = stationary_interval
  620. # FFMPEG input substitution
  621. for input in camera_config.ffmpeg.inputs:
  622. input.path = input.path.format(**FRIGATE_ENV_VARS)
  623. # Add default filters
  624. object_keys = camera_config.objects.track
  625. if camera_config.objects.filters is None:
  626. camera_config.objects.filters = {}
  627. object_keys = object_keys - camera_config.objects.filters.keys()
  628. for key in object_keys:
  629. camera_config.objects.filters[key] = FilterConfig()
  630. # Apply global object masks and convert masks to numpy array
  631. for object, filter in camera_config.objects.filters.items():
  632. if camera_config.objects.mask:
  633. filter_mask = []
  634. if filter.mask is not None:
  635. filter_mask = (
  636. filter.mask
  637. if isinstance(filter.mask, list)
  638. else [filter.mask]
  639. )
  640. object_mask = (
  641. camera_config.objects.mask
  642. if isinstance(camera_config.objects.mask, list)
  643. else [camera_config.objects.mask]
  644. )
  645. filter.mask = filter_mask + object_mask
  646. # Set runtime filter to create masks
  647. camera_config.objects.filters[object] = RuntimeFilterConfig(
  648. frame_shape=camera_config.frame_shape,
  649. **filter.dict(exclude_unset=True),
  650. )
  651. # Convert motion configuration
  652. if camera_config.motion is None:
  653. camera_config.motion = RuntimeMotionConfig(
  654. frame_shape=camera_config.frame_shape
  655. )
  656. else:
  657. camera_config.motion = RuntimeMotionConfig(
  658. frame_shape=camera_config.frame_shape,
  659. raw_mask=camera_config.motion.mask,
  660. **camera_config.motion.dict(exclude_unset=True),
  661. )
  662. # check runtime config
  663. assigned_roles = list(
  664. set([r for i in camera_config.ffmpeg.inputs for r in i.roles])
  665. )
  666. if camera_config.record.enabled and not "record" in assigned_roles:
  667. raise ValueError(
  668. f"Camera {name} has record enabled, but record is not assigned to an input."
  669. )
  670. if camera_config.rtmp.enabled and not "rtmp" in assigned_roles:
  671. raise ValueError(
  672. f"Camera {name} has rtmp enabled, but rtmp is not assigned to an input."
  673. )
  674. config.cameras[name] = camera_config
  675. return config
  676. @validator("cameras")
  677. def ensure_zones_and_cameras_have_different_names(cls, v: Dict[str, CameraConfig]):
  678. zones = [zone for camera in v.values() for zone in camera.zones.keys()]
  679. for zone in zones:
  680. if zone in v.keys():
  681. raise ValueError("Zones cannot share names with cameras")
  682. return v
  683. @classmethod
  684. def parse_file(cls, config_file):
  685. with open(config_file) as f:
  686. raw_config = f.read()
  687. if config_file.endswith(".yml"):
  688. config = yaml.safe_load(raw_config)
  689. elif config_file.endswith(".json"):
  690. config = json.loads(raw_config)
  691. return cls.parse_obj(config)