config.py 30 KB

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