detect_objects.py 18 KB

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