detect_objects.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. import os
  2. import sys
  3. import traceback
  4. import signal
  5. import cv2
  6. import time
  7. import datetime
  8. import queue
  9. import yaml
  10. import threading
  11. import multiprocessing as mp
  12. import subprocess as sp
  13. import numpy as np
  14. import logging
  15. from flask import Flask, Response, make_response, jsonify, request
  16. import paho.mqtt.client as mqtt
  17. from frigate.video import track_camera
  18. from frigate.object_processing import TrackedObjectProcessor
  19. from frigate.util import EventsPerSecond
  20. from frigate.edgetpu import EdgeTPUProcess
  21. FRIGATE_VARS = {k: v for k, v in os.environ.items() if k.startswith('FRIGATE_')}
  22. with open('/config/config.yml') as f:
  23. CONFIG = yaml.safe_load(f)
  24. MQTT_HOST = CONFIG['mqtt']['host']
  25. MQTT_PORT = CONFIG.get('mqtt', {}).get('port', 1883)
  26. MQTT_TOPIC_PREFIX = CONFIG.get('mqtt', {}).get('topic_prefix', 'frigate')
  27. MQTT_USER = CONFIG.get('mqtt', {}).get('user')
  28. MQTT_PASS = CONFIG.get('mqtt', {}).get('password')
  29. if not MQTT_PASS is None:
  30. MQTT_PASS = MQTT_PASS.format(**FRIGATE_VARS)
  31. MQTT_CLIENT_ID = CONFIG.get('mqtt', {}).get('client_id', 'frigate')
  32. # Set the default FFmpeg config
  33. FFMPEG_CONFIG = CONFIG.get('ffmpeg', {})
  34. FFMPEG_DEFAULT_CONFIG = {
  35. 'global_args': FFMPEG_CONFIG.get('global_args',
  36. ['-hide_banner','-loglevel','panic']),
  37. 'hwaccel_args': FFMPEG_CONFIG.get('hwaccel_args',
  38. []),
  39. 'input_args': FFMPEG_CONFIG.get('input_args',
  40. ['-avoid_negative_ts', 'make_zero',
  41. '-fflags', 'nobuffer',
  42. '-flags', 'low_delay',
  43. '-strict', 'experimental',
  44. '-fflags', '+genpts+discardcorrupt',
  45. '-vsync', 'drop',
  46. '-rtsp_transport', 'tcp',
  47. '-stimeout', '5000000',
  48. '-use_wallclock_as_timestamps', '1']),
  49. 'output_args': FFMPEG_CONFIG.get('output_args',
  50. ['-f', 'rawvideo',
  51. '-pix_fmt', 'rgb24'])
  52. }
  53. GLOBAL_OBJECT_CONFIG = CONFIG.get('objects', {})
  54. WEB_PORT = CONFIG.get('web_port', 5000)
  55. DEBUG = (CONFIG.get('debug', '0') == '1')
  56. def start_plasma_store():
  57. plasma_cmd = ['plasma_store', '-m', '400000000', '-s', '/tmp/plasma']
  58. plasma_process = sp.Popen(plasma_cmd, stdout=sp.DEVNULL)
  59. time.sleep(1)
  60. rc = plasma_process.poll()
  61. if rc is not None:
  62. return None
  63. return plasma_process
  64. class CameraWatchdog(threading.Thread):
  65. def __init__(self, camera_processes, config, tflite_process, tracked_objects_queue, object_processor, plasma_process):
  66. threading.Thread.__init__(self)
  67. self.camera_processes = camera_processes
  68. self.config = config
  69. self.tflite_process = tflite_process
  70. self.tracked_objects_queue = tracked_objects_queue
  71. self.object_processor = object_processor
  72. self.plasma_process = plasma_process
  73. def run(self):
  74. time.sleep(10)
  75. while True:
  76. # wait a bit before checking
  77. time.sleep(30)
  78. # check the plasma process
  79. rc = self.plasma_process.poll()
  80. if rc != None:
  81. print(f"plasma_process exited unexpectedly with {rc}")
  82. self.plasma_process = start_plasma_store()
  83. time.sleep(10)
  84. # check the detection process
  85. if (self.tflite_process.detection_start.value > 0.0 and
  86. datetime.datetime.now().timestamp() - self.tflite_process.detection_start.value > 10):
  87. print("Detection appears to be stuck. Restarting detection process")
  88. self.tflite_process.start_or_restart()
  89. time.sleep(30)
  90. elif not self.tflite_process.detect_process.is_alive():
  91. print("Detection appears to have stopped. Restarting detection process")
  92. self.tflite_process.start_or_restart()
  93. time.sleep(30)
  94. # check the camera processes
  95. for name, camera_process in self.camera_processes.items():
  96. process = camera_process['process']
  97. if not process.is_alive():
  98. print(f"Process for {name} is not alive. Starting again...")
  99. camera_process['fps'].value = float(self.config[name]['fps'])
  100. camera_process['skipped_fps'].value = 0.0
  101. camera_process['detection_fps'].value = 0.0
  102. camera_process['read_start'].value = 0.0
  103. camera_process['ffmpeg_pid'].value = 0
  104. process = mp.Process(target=track_camera, args=(name, self.config[name], FFMPEG_DEFAULT_CONFIG, GLOBAL_OBJECT_CONFIG,
  105. self.tflite_process.detection_queue, self.tracked_objects_queue,
  106. camera_process['fps'], camera_process['skipped_fps'], camera_process['detection_fps'],
  107. camera_process['read_start'], camera_process['ffmpeg_pid']))
  108. process.daemon = True
  109. camera_process['process'] = process
  110. process.start()
  111. print(f"Camera_process started for {name}: {process.pid}")
  112. if (camera_process['read_start'].value > 0.0 and
  113. datetime.datetime.now().timestamp() - camera_process['read_start'].value > 10):
  114. print(f"Process for {name} has been reading from ffmpeg for over 10 seconds long. Killing ffmpeg...")
  115. ffmpeg_pid = camera_process['ffmpeg_pid'].value
  116. if ffmpeg_pid != 0:
  117. try:
  118. os.kill(ffmpeg_pid, signal.SIGTERM)
  119. except OSError:
  120. print(f"Unable to terminate ffmpeg with pid {ffmpeg_pid}")
  121. time.sleep(10)
  122. try:
  123. os.kill(ffmpeg_pid, signal.SIGKILL)
  124. print(f"Unable to kill ffmpeg with pid {ffmpeg_pid}")
  125. except OSError:
  126. pass
  127. def main():
  128. # connect to mqtt and setup last will
  129. def on_connect(client, userdata, flags, rc):
  130. print("On connect called")
  131. if rc != 0:
  132. if rc == 3:
  133. print ("MQTT Server unavailable")
  134. elif rc == 4:
  135. print ("MQTT Bad username or password")
  136. elif rc == 5:
  137. print ("MQTT Not authorized")
  138. else:
  139. print ("Unable to connect to MQTT: Connection refused. Error code: " + str(rc))
  140. # publish a message to signal that the service is running
  141. client.publish(MQTT_TOPIC_PREFIX+'/available', 'online', retain=True)
  142. client = mqtt.Client(client_id=MQTT_CLIENT_ID)
  143. client.on_connect = on_connect
  144. client.will_set(MQTT_TOPIC_PREFIX+'/available', payload='offline', qos=1, retain=True)
  145. if not MQTT_USER is None:
  146. client.username_pw_set(MQTT_USER, password=MQTT_PASS)
  147. client.connect(MQTT_HOST, MQTT_PORT, 60)
  148. client.loop_start()
  149. plasma_process = start_plasma_store()
  150. ##
  151. # Setup config defaults for cameras
  152. ##
  153. for name, config in CONFIG['cameras'].items():
  154. config['snapshots'] = {
  155. 'show_timestamp': config.get('snapshots', {}).get('show_timestamp', True)
  156. }
  157. # Queue for cameras to push tracked objects to
  158. tracked_objects_queue = mp.SimpleQueue()
  159. # Start the shared tflite process
  160. tflite_process = EdgeTPUProcess()
  161. # start the camera processes
  162. camera_processes = {}
  163. for name, config in CONFIG['cameras'].items():
  164. camera_processes[name] = {
  165. 'fps': mp.Value('d', float(config['fps'])),
  166. 'skipped_fps': mp.Value('d', 0.0),
  167. 'detection_fps': mp.Value('d', 0.0),
  168. 'read_start': mp.Value('d', 0.0),
  169. 'ffmpeg_pid': mp.Value('i', 0)
  170. }
  171. camera_process = mp.Process(target=track_camera, args=(name, config, FFMPEG_DEFAULT_CONFIG, GLOBAL_OBJECT_CONFIG,
  172. tflite_process.detection_queue, tracked_objects_queue, camera_processes[name]['fps'],
  173. camera_processes[name]['skipped_fps'], camera_processes[name]['detection_fps'],
  174. camera_processes[name]['read_start'], camera_processes[name]['ffmpeg_pid']))
  175. camera_process.daemon = True
  176. camera_processes[name]['process'] = camera_process
  177. for name, camera_process in camera_processes.items():
  178. camera_process['process'].start()
  179. print(f"Camera_process started for {name}: {camera_process['process'].pid}")
  180. object_processor = TrackedObjectProcessor(CONFIG['cameras'], client, MQTT_TOPIC_PREFIX, tracked_objects_queue)
  181. object_processor.start()
  182. camera_watchdog = CameraWatchdog(camera_processes, CONFIG['cameras'], tflite_process, tracked_objects_queue, object_processor, plasma_process)
  183. camera_watchdog.start()
  184. # create a flask app that encodes frames a mjpeg on demand
  185. app = Flask(__name__)
  186. log = logging.getLogger('werkzeug')
  187. log.setLevel(logging.ERROR)
  188. @app.route('/')
  189. def ishealthy():
  190. # return a healh
  191. return "Frigate is running. Alive and healthy!"
  192. @app.route('/debug/stack')
  193. def processor_stack():
  194. frame = sys._current_frames().get(object_processor.ident, None)
  195. if frame:
  196. return "<br>".join(traceback.format_stack(frame)), 200
  197. else:
  198. return "no frame found", 200
  199. @app.route('/debug/print_stack')
  200. def print_stack():
  201. pid = int(request.args.get('pid', 0))
  202. if pid == 0:
  203. return "missing pid", 200
  204. else:
  205. os.kill(pid, signal.SIGUSR1)
  206. return "check logs", 200
  207. @app.route('/debug/stats')
  208. def stats():
  209. stats = {}
  210. total_detection_fps = 0
  211. for name, camera_stats in camera_processes.items():
  212. total_detection_fps += camera_stats['detection_fps'].value
  213. stats[name] = {
  214. 'fps': round(camera_stats['fps'].value, 2),
  215. 'skipped_fps': round(camera_stats['skipped_fps'].value, 2),
  216. 'detection_fps': round(camera_stats['detection_fps'].value, 2),
  217. 'read_start': camera_stats['read_start'].value,
  218. 'pid': camera_stats['process'].pid,
  219. 'ffmpeg_pid': camera_stats['ffmpeg_pid'].value
  220. }
  221. stats['coral'] = {
  222. 'fps': round(total_detection_fps, 2),
  223. 'inference_speed': round(tflite_process.avg_inference_speed.value*1000, 2),
  224. 'detection_start': tflite_process.detection_start.value,
  225. 'pid': tflite_process.detect_process.pid
  226. }
  227. rc = camera_watchdog.plasma_process.poll()
  228. stats['plasma_store_rc'] = rc
  229. return jsonify(stats)
  230. @app.route('/<camera_name>/<label>/best.jpg')
  231. def best(camera_name, label):
  232. if camera_name in CONFIG['cameras']:
  233. best_frame = object_processor.get_best(camera_name, label)
  234. if best_frame is None:
  235. best_frame = np.zeros((720,1280,3), np.uint8)
  236. best_frame = cv2.cvtColor(best_frame, cv2.COLOR_RGB2BGR)
  237. ret, jpg = cv2.imencode('.jpg', best_frame)
  238. response = make_response(jpg.tobytes())
  239. response.headers['Content-Type'] = 'image/jpg'
  240. return response
  241. else:
  242. return "Camera named {} not found".format(camera_name), 404
  243. @app.route('/<camera_name>')
  244. def mjpeg_feed(camera_name):
  245. fps = int(request.args.get('fps', '3'))
  246. height = int(request.args.get('h', '360'))
  247. if camera_name in CONFIG['cameras']:
  248. # return a multipart response
  249. return Response(imagestream(camera_name, fps, height),
  250. mimetype='multipart/x-mixed-replace; boundary=frame')
  251. else:
  252. return "Camera named {} not found".format(camera_name), 404
  253. def imagestream(camera_name, fps, height):
  254. while True:
  255. # max out at specified FPS
  256. time.sleep(1/fps)
  257. frame = object_processor.get_current_frame(camera_name)
  258. if frame is None:
  259. frame = np.zeros((height,int(height*16/9),3), np.uint8)
  260. frame = cv2.resize(frame, dsize=(int(height*16/9), height), interpolation=cv2.INTER_LINEAR)
  261. frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
  262. ret, jpg = cv2.imencode('.jpg', frame)
  263. yield (b'--frame\r\n'
  264. b'Content-Type: image/jpeg\r\n\r\n' + jpg.tobytes() + b'\r\n\r\n')
  265. app.run(host='0.0.0.0', port=WEB_PORT, debug=False)
  266. camera_watchdog.join()
  267. plasma_process.terminate()
  268. if __name__ == '__main__':
  269. main()