detect_objects.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. TENSORFLOW_DEVICE = CONFIG.get('tensorflow_device')
  58. class CameraWatchdog(threading.Thread):
  59. def __init__(self, camera_processes, config, tflite_process, tracked_objects_queue, stop_event):
  60. threading.Thread.__init__(self)
  61. self.camera_processes = camera_processes
  62. self.config = config
  63. self.tflite_process = tflite_process
  64. self.tracked_objects_queue = tracked_objects_queue
  65. self.stop_event = stop_event
  66. def run(self):
  67. time.sleep(10)
  68. while True:
  69. # wait a bit before checking
  70. time.sleep(10)
  71. if self.stop_event.is_set():
  72. print(f"Exiting watchdog...")
  73. break
  74. now = datetime.datetime.now().timestamp()
  75. # check the detection process
  76. detection_start = self.tflite_process.detection_start.value
  77. if (detection_start > 0.0 and
  78. now - detection_start > 10):
  79. print("Detection appears to be stuck. Restarting detection process")
  80. self.tflite_process.start_or_restart()
  81. elif not self.tflite_process.detect_process.is_alive():
  82. print("Detection appears to have stopped. Restarting detection process")
  83. self.tflite_process.start_or_restart()
  84. # check the camera processes
  85. for name, camera_process in self.camera_processes.items():
  86. process = camera_process['process']
  87. if not process.is_alive():
  88. print(f"Track process for {name} is not alive. Starting again...")
  89. camera_process['process_fps'].value = 0.0
  90. camera_process['detection_fps'].value = 0.0
  91. camera_process['read_start'].value = 0.0
  92. process = mp.Process(target=track_camera, args=(name, self.config[name], camera_process['frame_queue'],
  93. camera_process['frame_shape'], self.tflite_process.detection_queue, self.tracked_objects_queue,
  94. camera_process['process_fps'], camera_process['detection_fps'],
  95. camera_process['read_start'], camera_process['detection_frame'], self.stop_event))
  96. process.daemon = True
  97. camera_process['process'] = process
  98. process.start()
  99. print(f"Track process started for {name}: {process.pid}")
  100. if not camera_process['capture_thread'].is_alive():
  101. frame_shape = camera_process['frame_shape']
  102. frame_size = frame_shape[0] * frame_shape[1] * frame_shape[2]
  103. ffmpeg_process = start_or_restart_ffmpeg(camera_process['ffmpeg_cmd'], frame_size)
  104. camera_capture = CameraCapture(name, ffmpeg_process, frame_shape, camera_process['frame_queue'],
  105. camera_process['take_frame'], camera_process['camera_fps'], camera_process['detection_frame'], self.stop_event)
  106. camera_capture.start()
  107. camera_process['ffmpeg_process'] = ffmpeg_process
  108. camera_process['capture_thread'] = camera_capture
  109. elif now - camera_process['capture_thread'].current_frame.value > 5:
  110. print(f"No frames received from {name} in 5 seconds. Exiting ffmpeg...")
  111. ffmpeg_process = camera_process['ffmpeg_process']
  112. ffmpeg_process.terminate()
  113. try:
  114. print("Waiting for ffmpeg to exit gracefully...")
  115. ffmpeg_process.communicate(timeout=30)
  116. except sp.TimeoutExpired:
  117. print("FFmpeg didnt exit. Force killing...")
  118. ffmpeg_process.kill()
  119. ffmpeg_process.communicate()
  120. def main():
  121. stop_event = threading.Event()
  122. # connect to mqtt and setup last will
  123. def on_connect(client, userdata, flags, rc):
  124. print("On connect called")
  125. if rc != 0:
  126. if rc == 3:
  127. print ("MQTT Server unavailable")
  128. elif rc == 4:
  129. print ("MQTT Bad username or password")
  130. elif rc == 5:
  131. print ("MQTT Not authorized")
  132. else:
  133. print ("Unable to connect to MQTT: Connection refused. Error code: " + str(rc))
  134. # publish a message to signal that the service is running
  135. client.publish(MQTT_TOPIC_PREFIX+'/available', 'online', retain=True)
  136. client = mqtt.Client(client_id=MQTT_CLIENT_ID)
  137. client.on_connect = on_connect
  138. client.will_set(MQTT_TOPIC_PREFIX+'/available', payload='offline', qos=1, retain=True)
  139. if not MQTT_USER is None:
  140. client.username_pw_set(MQTT_USER, password=MQTT_PASS)
  141. client.connect(MQTT_HOST, MQTT_PORT, 60)
  142. client.loop_start()
  143. ##
  144. # Setup config defaults for cameras
  145. ##
  146. for name, config in CONFIG['cameras'].items():
  147. config['snapshots'] = {
  148. 'show_timestamp': config.get('snapshots', {}).get('show_timestamp', True),
  149. 'draw_zones': config.get('snapshots', {}).get('draw_zones', False)
  150. }
  151. config['zones'] = config.get('zones', {})
  152. # Queue for cameras to push tracked objects to
  153. tracked_objects_queue = mp.Queue()
  154. # Queue for clip processing
  155. event_queue = mp.Queue()
  156. # create the detection pipes
  157. detection_pipes = {}
  158. for name in CONFIG['cameras'].keys():
  159. detection_pipes[name] = mp.Pipe(duplex=False)
  160. # Start the shared tflite process
  161. tflite_process = EdgeTPUProcess(result_connections={ key:value[1] for (key,value) in detection_pipes.items() }, tf_device=TENSORFLOW_DEVICE)
  162. # create the camera processes
  163. camera_processes = {}
  164. for name, config in CONFIG['cameras'].items():
  165. # Merge the ffmpeg config with the global config
  166. ffmpeg = config.get('ffmpeg', {})
  167. ffmpeg_input = get_ffmpeg_input(ffmpeg['input'])
  168. ffmpeg_global_args = ffmpeg.get('global_args', FFMPEG_DEFAULT_CONFIG['global_args'])
  169. ffmpeg_hwaccel_args = ffmpeg.get('hwaccel_args', FFMPEG_DEFAULT_CONFIG['hwaccel_args'])
  170. ffmpeg_input_args = ffmpeg.get('input_args', FFMPEG_DEFAULT_CONFIG['input_args'])
  171. ffmpeg_output_args = ffmpeg.get('output_args', FFMPEG_DEFAULT_CONFIG['output_args'])
  172. if not config.get('fps') is None:
  173. ffmpeg_output_args = ["-r", str(config.get('fps'))] + ffmpeg_output_args
  174. if config.get('save_clips', {}).get('enabled', False):
  175. ffmpeg_output_args = [
  176. "-f",
  177. "segment",
  178. "-segment_time",
  179. "10",
  180. "-segment_format",
  181. "mp4",
  182. "-reset_timestamps",
  183. "1",
  184. "-strftime",
  185. "1",
  186. "-c",
  187. "copy",
  188. "-an",
  189. "-map",
  190. "0",
  191. f"/cache/{name}-%Y%m%d%H%M%S.mp4"
  192. ] + ffmpeg_output_args
  193. ffmpeg_cmd = (['ffmpeg'] +
  194. ffmpeg_global_args +
  195. ffmpeg_hwaccel_args +
  196. ffmpeg_input_args +
  197. ['-i', ffmpeg_input] +
  198. ffmpeg_output_args +
  199. ['pipe:'])
  200. if 'width' in config and 'height' in config:
  201. frame_shape = (config['height'], config['width'], 3)
  202. else:
  203. frame_shape = get_frame_shape(ffmpeg_input)
  204. config['frame_shape'] = frame_shape
  205. frame_size = frame_shape[0] * frame_shape[1] * frame_shape[2]
  206. take_frame = config.get('take_frame', 1)
  207. detection_frame = mp.Value('d', 0.0)
  208. ffmpeg_process = start_or_restart_ffmpeg(ffmpeg_cmd, frame_size)
  209. frame_queue = mp.Queue()
  210. camera_fps = EventsPerSecond()
  211. camera_fps.start()
  212. camera_capture = CameraCapture(name, ffmpeg_process, frame_shape, frame_queue, take_frame, camera_fps, detection_frame, stop_event)
  213. camera_capture.start()
  214. camera_processes[name] = {
  215. 'camera_fps': camera_fps,
  216. 'take_frame': take_frame,
  217. 'process_fps': mp.Value('d', 0.0),
  218. 'detection_fps': mp.Value('d', 0.0),
  219. 'detection_frame': detection_frame,
  220. 'read_start': mp.Value('d', 0.0),
  221. 'ffmpeg_process': ffmpeg_process,
  222. 'ffmpeg_cmd': ffmpeg_cmd,
  223. 'frame_queue': frame_queue,
  224. 'frame_shape': frame_shape,
  225. 'capture_thread': camera_capture
  226. }
  227. # merge global object config into camera object config
  228. camera_objects_config = config.get('objects', {})
  229. # get objects to track for camera
  230. objects_to_track = camera_objects_config.get('track', GLOBAL_OBJECT_CONFIG.get('track', ['person']))
  231. # get object filters
  232. object_filters = camera_objects_config.get('filters', GLOBAL_OBJECT_CONFIG.get('filters', {}))
  233. config['objects'] = {
  234. 'track': objects_to_track,
  235. 'filters': object_filters
  236. }
  237. camera_process = mp.Process(target=track_camera, args=(name, config, frame_queue, frame_shape,
  238. tflite_process.detection_queue, detection_pipes[name][0], tracked_objects_queue, camera_processes[name]['process_fps'],
  239. camera_processes[name]['detection_fps'],
  240. camera_processes[name]['read_start'], camera_processes[name]['detection_frame'], stop_event))
  241. camera_process.daemon = True
  242. camera_processes[name]['process'] = camera_process
  243. # start the camera_processes
  244. for name, camera_process in camera_processes.items():
  245. camera_process['process'].start()
  246. print(f"Camera_process started for {name}: {camera_process['process'].pid}")
  247. event_processor = EventProcessor(CONFIG, camera_processes, '/cache', '/clips', event_queue, stop_event)
  248. event_processor.start()
  249. object_processor = TrackedObjectProcessor(CONFIG['cameras'], client, MQTT_TOPIC_PREFIX, tracked_objects_queue, event_queue, stop_event)
  250. object_processor.start()
  251. camera_watchdog = CameraWatchdog(camera_processes, CONFIG['cameras'], tflite_process, tracked_objects_queue, stop_event)
  252. camera_watchdog.start()
  253. def receiveSignal(signalNumber, frame):
  254. print('Received:', signalNumber)
  255. stop_event.set()
  256. event_processor.join()
  257. object_processor.join()
  258. camera_watchdog.join()
  259. for camera_process in camera_processes.values():
  260. camera_process['capture_thread'].join()
  261. tflite_process.stop()
  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_processes.items():
  293. total_detection_fps += camera_stats['detection_fps'].value
  294. capture_thread = camera_stats['capture_thread']
  295. stats[name] = {
  296. 'camera_fps': round(capture_thread.fps.eps(), 2),
  297. 'process_fps': round(camera_stats['process_fps'].value, 2),
  298. 'skipped_fps': round(capture_thread.skipped_fps.eps(), 2),
  299. 'detection_fps': round(camera_stats['detection_fps'].value, 2),
  300. 'read_start': camera_stats['read_start'].value,
  301. 'pid': camera_stats['process'].pid,
  302. 'ffmpeg_pid': camera_stats['ffmpeg_process'].pid,
  303. 'frame_info': {
  304. 'read': capture_thread.current_frame.value,
  305. 'detect': camera_stats['detection_frame'].value,
  306. 'process': object_processor.camera_data[name]['current_frame_time']
  307. }
  308. }
  309. stats['coral'] = {
  310. 'fps': round(total_detection_fps, 2),
  311. 'inference_speed': round(tflite_process.avg_inference_speed.value*1000, 2),
  312. 'detection_start': tflite_process.detection_start.value,
  313. 'pid': tflite_process.detect_process.pid
  314. }
  315. return jsonify(stats)
  316. @app.route('/<camera_name>/<label>/best.jpg')
  317. def best(camera_name, label):
  318. if camera_name in CONFIG['cameras']:
  319. best_object = object_processor.get_best(camera_name, label)
  320. best_frame = best_object.get('frame', np.zeros((720,1280,3), np.uint8))
  321. crop = bool(request.args.get('crop', 0, type=int))
  322. if crop:
  323. region = best_object.get('region', [0,0,300,300])
  324. best_frame = best_frame[region[1]:region[3], region[0]:region[2]]
  325. height = int(request.args.get('h', str(best_frame.shape[0])))
  326. width = int(height*best_frame.shape[1]/best_frame.shape[0])
  327. best_frame = cv2.resize(best_frame, dsize=(width, height), interpolation=cv2.INTER_AREA)
  328. best_frame = cv2.cvtColor(best_frame, cv2.COLOR_RGB2BGR)
  329. ret, jpg = cv2.imencode('.jpg', best_frame)
  330. response = make_response(jpg.tobytes())
  331. response.headers['Content-Type'] = 'image/jpg'
  332. return response
  333. else:
  334. return "Camera named {} not found".format(camera_name), 404
  335. @app.route('/<camera_name>')
  336. def mjpeg_feed(camera_name):
  337. fps = int(request.args.get('fps', '3'))
  338. height = int(request.args.get('h', '360'))
  339. if camera_name in CONFIG['cameras']:
  340. # return a multipart response
  341. return Response(imagestream(camera_name, fps, height),
  342. mimetype='multipart/x-mixed-replace; boundary=frame')
  343. else:
  344. return "Camera named {} not found".format(camera_name), 404
  345. @app.route('/<camera_name>/latest.jpg')
  346. def latest_frame(camera_name):
  347. if camera_name in CONFIG['cameras']:
  348. # max out at specified FPS
  349. frame = object_processor.get_current_frame(camera_name)
  350. if frame is None:
  351. frame = np.zeros((720,1280,3), np.uint8)
  352. height = int(request.args.get('h', str(frame.shape[0])))
  353. width = int(height*frame.shape[1]/frame.shape[0])
  354. frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_AREA)
  355. frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
  356. ret, jpg = cv2.imencode('.jpg', frame)
  357. response = make_response(jpg.tobytes())
  358. response.headers['Content-Type'] = 'image/jpg'
  359. return response
  360. else:
  361. return "Camera named {} not found".format(camera_name), 404
  362. def imagestream(camera_name, fps, height):
  363. while True:
  364. # max out at specified FPS
  365. time.sleep(1/fps)
  366. frame = object_processor.get_current_frame(camera_name)
  367. if frame is None:
  368. frame = np.zeros((height,int(height*16/9),3), np.uint8)
  369. width = int(height*frame.shape[1]/frame.shape[0])
  370. frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_LINEAR)
  371. frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
  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()