detect_objects.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. import faulthandler; faulthandler.enable()
  2. import os
  3. import signal
  4. import sys
  5. import traceback
  6. import signal
  7. import cv2
  8. import time
  9. import datetime
  10. import queue
  11. import yaml
  12. import json
  13. import threading
  14. import multiprocessing as mp
  15. import subprocess as sp
  16. import numpy as np
  17. import logging
  18. from flask import Flask, Response, make_response, jsonify, request
  19. import paho.mqtt.client as mqtt
  20. from frigate.video import capture_camera, track_camera, get_ffmpeg_input, get_frame_shape, CameraCapture, start_or_restart_ffmpeg
  21. from frigate.object_processing import TrackedObjectProcessor
  22. from frigate.events import EventProcessor
  23. from frigate.util import EventsPerSecond
  24. from frigate.edgetpu import EdgeTPUProcess
  25. FRIGATE_VARS = {k: v for k, v in os.environ.items() if k.startswith('FRIGATE_')}
  26. CONFIG_FILE = os.environ.get('CONFIG_FILE', '/config/config.yml')
  27. if CONFIG_FILE.endswith(".yml"):
  28. with open(CONFIG_FILE) as f:
  29. CONFIG = yaml.safe_load(f)
  30. elif CONFIG_FILE.endswith(".json"):
  31. with open(CONFIG_FILE) as f:
  32. CONFIG = json.load(f)
  33. CACHE_DIR = CONFIG.get('save_clips', {}).get('cache_dir', '/cache')
  34. CLIPS_DIR = CONFIG.get('save_clips', {}).get('clips_dir', '/clips')
  35. if not os.path.exists(CACHE_DIR) and not os.path.islink(CACHE_DIR):
  36. os.makedirs(CACHE_DIR)
  37. if not os.path.exists(CLIPS_DIR) and not os.path.islink(CLIPS_DIR):
  38. os.makedirs(CLIPS_DIR)
  39. MQTT_HOST = CONFIG['mqtt']['host']
  40. MQTT_PORT = CONFIG.get('mqtt', {}).get('port', 1883)
  41. MQTT_TOPIC_PREFIX = CONFIG.get('mqtt', {}).get('topic_prefix', 'frigate')
  42. MQTT_USER = CONFIG.get('mqtt', {}).get('user')
  43. MQTT_PASS = CONFIG.get('mqtt', {}).get('password')
  44. if not MQTT_PASS is None:
  45. MQTT_PASS = MQTT_PASS.format(**FRIGATE_VARS)
  46. MQTT_CLIENT_ID = CONFIG.get('mqtt', {}).get('client_id', 'frigate')
  47. # Set the default FFmpeg config
  48. FFMPEG_CONFIG = CONFIG.get('ffmpeg', {})
  49. FFMPEG_DEFAULT_CONFIG = {
  50. 'global_args': FFMPEG_CONFIG.get('global_args',
  51. ['-hide_banner','-loglevel','panic']),
  52. 'hwaccel_args': FFMPEG_CONFIG.get('hwaccel_args',
  53. []),
  54. 'input_args': FFMPEG_CONFIG.get('input_args',
  55. ['-avoid_negative_ts', 'make_zero',
  56. '-fflags', 'nobuffer',
  57. '-flags', 'low_delay',
  58. '-strict', 'experimental',
  59. '-fflags', '+genpts+discardcorrupt',
  60. '-rtsp_transport', 'tcp',
  61. '-stimeout', '5000000',
  62. '-use_wallclock_as_timestamps', '1']),
  63. 'output_args': FFMPEG_CONFIG.get('output_args',
  64. ['-f', 'rawvideo',
  65. '-pix_fmt', 'yuv420p'])
  66. }
  67. GLOBAL_OBJECT_CONFIG = CONFIG.get('objects', {})
  68. WEB_PORT = CONFIG.get('web_port', 5000)
  69. DETECTORS = CONFIG.get('detectors', {'coral': {'type': 'edgetpu', 'device': 'usb'}})
  70. class FrigateWatchdog(threading.Thread):
  71. def __init__(self, camera_processes, config, detectors, detection_queue, out_events, tracked_objects_queue, stop_event):
  72. threading.Thread.__init__(self)
  73. self.camera_processes = camera_processes
  74. self.config = config
  75. self.detectors = detectors
  76. self.detection_queue = detection_queue
  77. self.out_events = out_events
  78. self.tracked_objects_queue = tracked_objects_queue
  79. self.stop_event = stop_event
  80. def run(self):
  81. time.sleep(10)
  82. while True:
  83. # wait a bit before checking
  84. time.sleep(10)
  85. if self.stop_event.is_set():
  86. print(f"Exiting watchdog...")
  87. break
  88. now = datetime.datetime.now().timestamp()
  89. # check the detection processes
  90. for detector in self.detectors.values():
  91. detection_start = detector.detection_start.value
  92. if (detection_start > 0.0 and
  93. now - detection_start > 10):
  94. print("Detection appears to be stuck. Restarting detection process")
  95. detector.start_or_restart()
  96. elif not detector.detect_process.is_alive():
  97. print("Detection appears to have stopped. Restarting detection process")
  98. detector.start_or_restart()
  99. # check the camera processes
  100. for name, camera_process in self.camera_processes.items():
  101. process = camera_process['process']
  102. if not process.is_alive():
  103. print(f"Track process for {name} is not alive. Starting again...")
  104. camera_process['camera_fps'].value = 0.0
  105. camera_process['process_fps'].value = 0.0
  106. camera_process['detection_fps'].value = 0.0
  107. camera_process['read_start'].value = 0.0
  108. process = mp.Process(target=track_camera, args=(name, self.config,
  109. self.detection_queue, self.out_events[name], self.tracked_objects_queue, camera_process, self.stop_event))
  110. process.daemon = True
  111. camera_process['process'] = process
  112. process.start()
  113. print(f"Track process started for {name}: {process.pid}")
  114. def main():
  115. stop_event = threading.Event()
  116. # connect to mqtt and setup last will
  117. def on_connect(client, userdata, flags, rc):
  118. print("On connect called")
  119. if rc != 0:
  120. if rc == 3:
  121. print ("MQTT Server unavailable")
  122. elif rc == 4:
  123. print ("MQTT Bad username or password")
  124. elif rc == 5:
  125. print ("MQTT Not authorized")
  126. else:
  127. print ("Unable to connect to MQTT: Connection refused. Error code: " + str(rc))
  128. # publish a message to signal that the service is running
  129. client.publish(MQTT_TOPIC_PREFIX+'/available', 'online', retain=True)
  130. client = mqtt.Client(client_id=MQTT_CLIENT_ID)
  131. client.on_connect = on_connect
  132. client.will_set(MQTT_TOPIC_PREFIX+'/available', payload='offline', qos=1, retain=True)
  133. if not MQTT_USER is None:
  134. client.username_pw_set(MQTT_USER, password=MQTT_PASS)
  135. client.connect(MQTT_HOST, MQTT_PORT, 60)
  136. client.loop_start()
  137. ##
  138. # Setup config defaults for cameras
  139. ##
  140. for name, config in CONFIG['cameras'].items():
  141. config['snapshots'] = {
  142. 'show_timestamp': config.get('snapshots', {}).get('show_timestamp', True),
  143. 'draw_zones': config.get('snapshots', {}).get('draw_zones', False),
  144. 'draw_bounding_boxes': config.get('snapshots', {}).get('draw_bounding_boxes', True)
  145. }
  146. config['zones'] = config.get('zones', {})
  147. # Queue for cameras to push tracked objects to
  148. tracked_objects_queue = mp.Queue(maxsize=len(CONFIG['cameras'].keys())*2)
  149. # Queue for clip processing
  150. event_queue = mp.Queue()
  151. # create the detection pipes and shms
  152. out_events = {}
  153. camera_shms = []
  154. for name in CONFIG['cameras'].keys():
  155. out_events[name] = mp.Event()
  156. shm_in = mp.shared_memory.SharedMemory(name=name, create=True, size=300*300*3)
  157. shm_out = mp.shared_memory.SharedMemory(name=f"out-{name}", create=True, size=20*6*4)
  158. camera_shms.append(shm_in)
  159. camera_shms.append(shm_out)
  160. detection_queue = mp.Queue()
  161. detectors = {}
  162. for name, detector in DETECTORS.items():
  163. if detector['type'] == 'cpu':
  164. detectors[name] = EdgeTPUProcess(detection_queue, out_events=out_events, tf_device='cpu')
  165. if detector['type'] == 'edgetpu':
  166. detectors[name] = EdgeTPUProcess(detection_queue, out_events=out_events, tf_device=detector['device'])
  167. # create the camera processes
  168. camera_process_info = {}
  169. for name, config in CONFIG['cameras'].items():
  170. # Merge the ffmpeg config with the global config
  171. ffmpeg = config.get('ffmpeg', {})
  172. ffmpeg_input = get_ffmpeg_input(ffmpeg['input'])
  173. ffmpeg_global_args = ffmpeg.get('global_args', FFMPEG_DEFAULT_CONFIG['global_args'])
  174. ffmpeg_hwaccel_args = ffmpeg.get('hwaccel_args', FFMPEG_DEFAULT_CONFIG['hwaccel_args'])
  175. ffmpeg_input_args = ffmpeg.get('input_args', FFMPEG_DEFAULT_CONFIG['input_args'])
  176. ffmpeg_output_args = ffmpeg.get('output_args', FFMPEG_DEFAULT_CONFIG['output_args'])
  177. if not config.get('fps') is None:
  178. ffmpeg_output_args = ["-r", str(config.get('fps'))] + ffmpeg_output_args
  179. if config.get('save_clips', {}).get('enabled', False):
  180. ffmpeg_output_args = [
  181. "-f",
  182. "segment",
  183. "-segment_time",
  184. "10",
  185. "-segment_format",
  186. "mp4",
  187. "-reset_timestamps",
  188. "1",
  189. "-strftime",
  190. "1",
  191. "-c",
  192. "copy",
  193. "-an",
  194. "-map",
  195. "0",
  196. f"{os.path.join(CACHE_DIR, name)}-%Y%m%d%H%M%S.mp4"
  197. ] + ffmpeg_output_args
  198. ffmpeg_cmd = (['ffmpeg'] +
  199. ffmpeg_global_args +
  200. ffmpeg_hwaccel_args +
  201. ffmpeg_input_args +
  202. ['-i', ffmpeg_input] +
  203. ffmpeg_output_args +
  204. ['pipe:'])
  205. config['ffmpeg_cmd'] = ffmpeg_cmd
  206. if 'width' in config and 'height' in config:
  207. frame_shape = (config['height'], config['width'], 3)
  208. else:
  209. frame_shape = get_frame_shape(ffmpeg_input)
  210. config['frame_shape'] = frame_shape
  211. config['take_frame'] = config.get('take_frame', 1)
  212. camera_process_info[name] = {
  213. 'camera_fps': mp.Value('d', 0.0),
  214. 'skipped_fps': mp.Value('d', 0.0),
  215. 'process_fps': mp.Value('d', 0.0),
  216. 'detection_fps': mp.Value('d', 0.0),
  217. 'detection_frame': mp.Value('d', 0.0),
  218. 'read_start': mp.Value('d', 0.0),
  219. 'frame_queue': mp.Queue(maxsize=2)
  220. }
  221. # merge global object config into camera object config
  222. camera_objects_config = config.get('objects', {})
  223. # get objects to track for camera
  224. objects_to_track = camera_objects_config.get('track', GLOBAL_OBJECT_CONFIG.get('track', ['person']))
  225. # get object filters
  226. object_filters = camera_objects_config.get('filters', GLOBAL_OBJECT_CONFIG.get('filters', {}))
  227. config['objects'] = {
  228. 'track': objects_to_track,
  229. 'filters': object_filters
  230. }
  231. capture_process = mp.Process(target=capture_camera, args=(name, config,
  232. camera_process_info[name], stop_event))
  233. capture_process.daemon = True
  234. camera_process_info[name]['capture_process'] = capture_process
  235. camera_process = mp.Process(target=track_camera, args=(name, config,
  236. detection_queue, out_events[name], tracked_objects_queue, camera_process_info[name], stop_event))
  237. camera_process.daemon = True
  238. camera_process_info[name]['process'] = camera_process
  239. # start the camera_processes
  240. for name, camera_process in camera_process_info.items():
  241. camera_process['capture_process'].start()
  242. print(f"Camera capture process started for {name}: {camera_process['capture_process'].pid}")
  243. camera_process['process'].start()
  244. print(f"Camera process started for {name}: {camera_process['process'].pid}")
  245. event_processor = EventProcessor(CONFIG, camera_process_info, CACHE_DIR, CLIPS_DIR, event_queue, stop_event)
  246. event_processor.start()
  247. object_processor = TrackedObjectProcessor(CONFIG['cameras'], client, MQTT_TOPIC_PREFIX, tracked_objects_queue, event_queue, stop_event)
  248. object_processor.start()
  249. frigate_watchdog = FrigateWatchdog(camera_process_info, CONFIG['cameras'], detectors, detection_queue, out_events, tracked_objects_queue, stop_event)
  250. frigate_watchdog.start()
  251. def receiveSignal(signalNumber, frame):
  252. print('Received:', signalNumber)
  253. stop_event.set()
  254. event_processor.join()
  255. object_processor.join()
  256. frigate_watchdog.join()
  257. for detector in detectors.values():
  258. detector.stop()
  259. for shm in camera_shms:
  260. shm.close()
  261. shm.unlink()
  262. sys.exit()
  263. signal.signal(signal.SIGTERM, receiveSignal)
  264. signal.signal(signal.SIGINT, receiveSignal)
  265. # create a flask app that encodes frames a mjpeg on demand
  266. app = Flask(__name__)
  267. log = logging.getLogger('werkzeug')
  268. log.setLevel(logging.ERROR)
  269. @app.route('/')
  270. def ishealthy():
  271. # return a healh
  272. return "Frigate is running. Alive and healthy!"
  273. @app.route('/debug/stack')
  274. def processor_stack():
  275. frame = sys._current_frames().get(object_processor.ident, None)
  276. if frame:
  277. return "<br>".join(traceback.format_stack(frame)), 200
  278. else:
  279. return "no frame found", 200
  280. @app.route('/debug/print_stack')
  281. def print_stack():
  282. pid = int(request.args.get('pid', 0))
  283. if pid == 0:
  284. return "missing pid", 200
  285. else:
  286. os.kill(pid, signal.SIGUSR1)
  287. return "check logs", 200
  288. @app.route('/debug/stats')
  289. def stats():
  290. stats = {}
  291. total_detection_fps = 0
  292. for name, camera_stats in camera_process_info.items():
  293. total_detection_fps += camera_stats['detection_fps'].value
  294. stats[name] = {
  295. 'camera_fps': round(camera_stats['camera_fps'].value, 2),
  296. 'process_fps': round(camera_stats['process_fps'].value, 2),
  297. 'skipped_fps': round(camera_stats['skipped_fps'].value, 2),
  298. 'detection_fps': round(camera_stats['detection_fps'].value, 2),
  299. 'pid': camera_stats['process'].pid,
  300. 'capture_pid': camera_stats['capture_process'].pid,
  301. 'frame_info': {
  302. 'detect': camera_stats['detection_frame'].value,
  303. 'process': object_processor.camera_data[name]['current_frame_time']
  304. }
  305. }
  306. stats['detectors'] = {}
  307. for name, detector in detectors.items():
  308. stats['detectors'][name] = {
  309. 'inference_speed': round(detector.avg_inference_speed.value*1000, 2),
  310. 'detection_start': detector.detection_start.value,
  311. 'pid': detector.detect_process.pid
  312. }
  313. stats['detection_fps'] = round(total_detection_fps, 2)
  314. return jsonify(stats)
  315. @app.route('/<camera_name>/<label>/best.jpg')
  316. def best(camera_name, label):
  317. if camera_name in CONFIG['cameras']:
  318. best_object = object_processor.get_best(camera_name, label)
  319. best_frame = best_object.get('frame')
  320. if best_frame is None:
  321. best_frame = np.zeros((720,1280,3), np.uint8)
  322. else:
  323. best_frame = cv2.cvtColor(best_frame, cv2.COLOR_YUV2BGR_I420)
  324. crop = bool(request.args.get('crop', 0, type=int))
  325. if crop:
  326. region = best_object.get('region', [0,0,300,300])
  327. best_frame = best_frame[region[1]:region[3], region[0]:region[2]]
  328. height = int(request.args.get('h', str(best_frame.shape[0])))
  329. width = int(height*best_frame.shape[1]/best_frame.shape[0])
  330. best_frame = cv2.resize(best_frame, dsize=(width, height), interpolation=cv2.INTER_AREA)
  331. ret, jpg = cv2.imencode('.jpg', best_frame)
  332. response = make_response(jpg.tobytes())
  333. response.headers['Content-Type'] = 'image/jpg'
  334. return response
  335. else:
  336. return "Camera named {} not found".format(camera_name), 404
  337. @app.route('/<camera_name>')
  338. def mjpeg_feed(camera_name):
  339. fps = int(request.args.get('fps', '3'))
  340. height = int(request.args.get('h', '360'))
  341. if camera_name in CONFIG['cameras']:
  342. # return a multipart response
  343. return Response(imagestream(camera_name, fps, height),
  344. mimetype='multipart/x-mixed-replace; boundary=frame')
  345. else:
  346. return "Camera named {} not found".format(camera_name), 404
  347. @app.route('/<camera_name>/latest.jpg')
  348. def latest_frame(camera_name):
  349. if camera_name in CONFIG['cameras']:
  350. # max out at specified FPS
  351. frame = object_processor.get_current_frame(camera_name)
  352. if frame is None:
  353. frame = np.zeros((720,1280,3), np.uint8)
  354. height = int(request.args.get('h', str(frame.shape[0])))
  355. width = int(height*frame.shape[1]/frame.shape[0])
  356. frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_AREA)
  357. ret, jpg = cv2.imencode('.jpg', frame)
  358. response = make_response(jpg.tobytes())
  359. response.headers['Content-Type'] = 'image/jpg'
  360. return response
  361. else:
  362. return "Camera named {} not found".format(camera_name), 404
  363. def imagestream(camera_name, fps, height):
  364. while True:
  365. # max out at specified FPS
  366. time.sleep(1/fps)
  367. frame = object_processor.get_current_frame(camera_name, draw=True)
  368. if frame is None:
  369. frame = np.zeros((height,int(height*16/9),3), np.uint8)
  370. width = int(height*frame.shape[1]/frame.shape[0])
  371. frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_LINEAR)
  372. ret, jpg = cv2.imencode('.jpg', frame)
  373. yield (b'--frame\r\n'
  374. b'Content-Type: image/jpeg\r\n\r\n' + jpg.tobytes() + b'\r\n\r\n')
  375. app.run(host='0.0.0.0', port=WEB_PORT, debug=False)
  376. object_processor.join()
  377. if __name__ == '__main__':
  378. main()