config.py 31 KB

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