events.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import datetime
  2. import json
  3. import logging
  4. import os
  5. import queue
  6. import subprocess as sp
  7. import threading
  8. import time
  9. from collections import defaultdict
  10. from pathlib import Path
  11. import psutil
  12. from frigate.config import FrigateConfig
  13. from frigate.const import RECORD_DIR, CLIPS_DIR, CACHE_DIR
  14. from frigate.models import Event
  15. from peewee import fn
  16. logger = logging.getLogger(__name__)
  17. class EventProcessor(threading.Thread):
  18. def __init__(self, config, camera_processes, event_queue, event_processed_queue, stop_event):
  19. threading.Thread.__init__(self)
  20. self.name = 'event_processor'
  21. self.config = config
  22. self.camera_processes = camera_processes
  23. self.cached_clips = {}
  24. self.event_queue = event_queue
  25. self.event_processed_queue = event_processed_queue
  26. self.events_in_process = {}
  27. self.stop_event = stop_event
  28. def refresh_cache(self):
  29. cached_files = os.listdir(CACHE_DIR)
  30. files_in_use = []
  31. for process in psutil.process_iter():
  32. try:
  33. if process.name() != 'ffmpeg':
  34. continue
  35. flist = process.open_files()
  36. if flist:
  37. for nt in flist:
  38. if nt.path.startswith(CACHE_DIR):
  39. files_in_use.append(nt.path.split('/')[-1])
  40. except:
  41. continue
  42. for f in cached_files:
  43. if f in files_in_use or f in self.cached_clips:
  44. continue
  45. camera = '-'.join(f.split('-')[:-1])
  46. start_time = datetime.datetime.strptime(f.split('-')[-1].split('.')[0], '%Y%m%d%H%M%S')
  47. ffprobe_cmd = " ".join([
  48. 'ffprobe',
  49. '-v',
  50. 'error',
  51. '-show_entries',
  52. 'format=duration',
  53. '-of',
  54. 'default=noprint_wrappers=1:nokey=1',
  55. f"{os.path.join(CACHE_DIR,f)}"
  56. ])
  57. p = sp.Popen(ffprobe_cmd, stdout=sp.PIPE, shell=True)
  58. (output, err) = p.communicate()
  59. p_status = p.wait()
  60. if p_status == 0:
  61. duration = float(output.decode('utf-8').strip())
  62. else:
  63. logger.info(f"bad file: {f}")
  64. os.remove(os.path.join(CACHE_DIR,f))
  65. continue
  66. self.cached_clips[f] = {
  67. 'path': f,
  68. 'camera': camera,
  69. 'start_time': start_time.timestamp(),
  70. 'duration': duration
  71. }
  72. if len(self.events_in_process) > 0:
  73. earliest_event = min(self.events_in_process.values(), key=lambda x:x['start_time'])['start_time']
  74. else:
  75. earliest_event = datetime.datetime.now().timestamp()
  76. # if the earliest event exceeds the max seconds, cap it
  77. max_seconds = self.config.clips.max_seconds
  78. if datetime.datetime.now().timestamp()-earliest_event > max_seconds:
  79. earliest_event = datetime.datetime.now().timestamp()-max_seconds
  80. for f, data in list(self.cached_clips.items()):
  81. if earliest_event-90 > data['start_time']+data['duration']:
  82. del self.cached_clips[f]
  83. os.remove(os.path.join(CACHE_DIR,f))
  84. def create_clip(self, camera, event_data, pre_capture, post_capture):
  85. # get all clips from the camera with the event sorted
  86. sorted_clips = sorted([c for c in self.cached_clips.values() if c['camera'] == camera], key = lambda i: i['start_time'])
  87. while len(sorted_clips) == 0 or sorted_clips[-1]['start_time'] + sorted_clips[-1]['duration'] < event_data['end_time']+post_capture:
  88. logger.debug(f"No cache clips for {camera}. Waiting...")
  89. time.sleep(5)
  90. self.refresh_cache()
  91. # get all clips from the camera with the event sorted
  92. sorted_clips = sorted([c for c in self.cached_clips.values() if c['camera'] == camera], key = lambda i: i['start_time'])
  93. playlist_start = event_data['start_time']-pre_capture
  94. playlist_end = event_data['end_time']+post_capture
  95. playlist_lines = []
  96. for clip in sorted_clips:
  97. # clip ends before playlist start time, skip
  98. if clip['start_time']+clip['duration'] < playlist_start:
  99. continue
  100. # clip starts after playlist ends, finish
  101. if clip['start_time'] > playlist_end:
  102. break
  103. playlist_lines.append(f"file '{os.path.join(CACHE_DIR,clip['path'])}'")
  104. # if this is the starting clip, add an inpoint
  105. if clip['start_time'] < playlist_start:
  106. playlist_lines.append(f"inpoint {int(playlist_start-clip['start_time'])}")
  107. # if this is the ending clip, add an outpoint
  108. if clip['start_time']+clip['duration'] > playlist_end:
  109. playlist_lines.append(f"outpoint {int(playlist_end-clip['start_time'])}")
  110. clip_name = f"{camera}-{event_data['id']}"
  111. ffmpeg_cmd = [
  112. 'ffmpeg',
  113. '-y',
  114. '-protocol_whitelist',
  115. 'pipe,file',
  116. '-f',
  117. 'concat',
  118. '-safe',
  119. '0',
  120. '-i',
  121. '-',
  122. '-c',
  123. 'copy',
  124. '-movflags',
  125. '+faststart',
  126. f"{os.path.join(CLIPS_DIR, clip_name)}.mp4"
  127. ]
  128. p = sp.run(ffmpeg_cmd, input="\n".join(playlist_lines), encoding='ascii', capture_output=True)
  129. if p.returncode != 0:
  130. logger.error(p.stderr)
  131. return False
  132. return True
  133. def run(self):
  134. while True:
  135. if self.stop_event.is_set():
  136. logger.info(f"Exiting event processor...")
  137. break
  138. try:
  139. event_type, camera, event_data = self.event_queue.get(timeout=10)
  140. except queue.Empty:
  141. if not self.stop_event.is_set():
  142. self.refresh_cache()
  143. continue
  144. logger.debug(f"Event received: {event_type} {camera} {event_data['id']}")
  145. self.refresh_cache()
  146. if event_type == 'start':
  147. self.events_in_process[event_data['id']] = event_data
  148. if event_type == 'end':
  149. clips_config = self.config.cameras[camera].clips
  150. if not event_data['false_positive']:
  151. clip_created = False
  152. if clips_config.enabled and (clips_config.objects is None or event_data['label'] in clips_config.objects):
  153. clip_created = self.create_clip(camera, event_data, clips_config.pre_capture, clips_config.post_capture)
  154. Event.create(
  155. id=event_data['id'],
  156. label=event_data['label'],
  157. camera=camera,
  158. start_time=event_data['start_time'],
  159. end_time=event_data['end_time'],
  160. top_score=event_data['top_score'],
  161. false_positive=event_data['false_positive'],
  162. zones=list(event_data['entered_zones']),
  163. thumbnail=event_data['thumbnail'],
  164. has_clip=clip_created,
  165. has_snapshot=event_data['has_snapshot'],
  166. )
  167. del self.events_in_process[event_data['id']]
  168. self.event_processed_queue.put((event_data['id'], camera))
  169. class EventCleanup(threading.Thread):
  170. def __init__(self, config: FrigateConfig, stop_event):
  171. threading.Thread.__init__(self)
  172. self.name = 'event_cleanup'
  173. self.config = config
  174. self.stop_event = stop_event
  175. self.camera_keys = list(self.config.cameras.keys())
  176. def expire(self, media):
  177. ## Expire events from unlisted cameras based on the global config
  178. if media == 'clips':
  179. retain_config = self.config.clips.retain
  180. file_extension = 'mp4'
  181. update_params = {'has_clip': False}
  182. else:
  183. retain_config = self.config.snapshots.retain
  184. file_extension = 'jpg'
  185. update_params = {'has_snapshot': False}
  186. distinct_labels = (Event.select(Event.label)
  187. .where(Event.camera.not_in(self.camera_keys))
  188. .distinct())
  189. # loop over object types in db
  190. for l in distinct_labels:
  191. # get expiration time for this label
  192. expire_days = retain_config.objects.get(l.label, retain_config.default)
  193. expire_after = (datetime.datetime.now() - datetime.timedelta(days=expire_days)).timestamp()
  194. # grab all events after specific time
  195. expired_events = (
  196. Event.select()
  197. .where(Event.camera.not_in(self.camera_keys),
  198. Event.start_time < expire_after,
  199. Event.label == l.label)
  200. )
  201. # delete the media from disk
  202. for event in expired_events:
  203. media_name = f"{event.camera}-{event.id}"
  204. media = Path(f"{os.path.join(CLIPS_DIR, media_name)}.{file_extension}")
  205. media.unlink(missing_ok=True)
  206. # update the clips attribute for the db entry
  207. update_query = (
  208. Event.update(update_params)
  209. .where(Event.camera.not_in(self.camera_keys),
  210. Event.start_time < expire_after,
  211. Event.label == l.label)
  212. )
  213. update_query.execute()
  214. ## Expire events from cameras based on the camera config
  215. for name, camera in self.config.cameras.items():
  216. if media == 'clips':
  217. retain_config = camera.clips.retain
  218. else:
  219. retain_config = camera.snapshots.retain
  220. # get distinct objects in database for this camera
  221. distinct_labels = (Event.select(Event.label)
  222. .where(Event.camera == name)
  223. .distinct())
  224. # loop over object types in db
  225. for l in distinct_labels:
  226. # get expiration time for this label
  227. expire_days = retain_config.objects.get(l.label, retain_config.default)
  228. expire_after = (datetime.datetime.now() - datetime.timedelta(days=expire_days)).timestamp()
  229. # grab all events after specific time
  230. expired_events = (
  231. Event.select()
  232. .where(Event.camera == name,
  233. Event.start_time < expire_after,
  234. Event.label == l.label)
  235. )
  236. # delete the grabbed clips from disk
  237. for event in expired_events:
  238. media_name = f"{event.camera}-{event.id}"
  239. media = Path(f"{os.path.join(CLIPS_DIR, media_name)}.{file_extension}")
  240. media.unlink(missing_ok=True)
  241. # update the clips attribute for the db entry
  242. update_query = (
  243. Event.update(update_params)
  244. .where( Event.camera == name,
  245. Event.start_time < expire_after,
  246. Event.label == l.label)
  247. )
  248. update_query.execute()
  249. def run(self):
  250. counter = 0
  251. while(True):
  252. if self.stop_event.is_set():
  253. logger.info(f"Exiting event cleanup...")
  254. break
  255. # only expire events every 10 minutes, but check for stop events every 10 seconds
  256. time.sleep(10)
  257. counter = counter + 1
  258. if counter < 60:
  259. continue
  260. counter = 0
  261. self.expire('clips')
  262. self.expire('snapshots')
  263. # drop events from db where has_clip and has_snapshot are false
  264. delete_query = (
  265. Event.delete()
  266. .where( Event.has_clip == False,
  267. Event.has_snapshot == False)
  268. )
  269. delete_query.execute()