detect_objects.py 19 KB

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