video.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. import datetime
  2. import itertools
  3. import logging
  4. import multiprocessing as mp
  5. import queue
  6. import subprocess as sp
  7. import signal
  8. import threading
  9. import time
  10. from collections import defaultdict
  11. from setproctitle import setproctitle
  12. from typing import Dict, List
  13. from cv2 import cv2
  14. import numpy as np
  15. from frigate.config import CameraConfig
  16. from frigate.edgetpu import RemoteObjectDetector
  17. from frigate.log import LogPipe
  18. from frigate.motion import MotionDetector
  19. from frigate.objects import ObjectTracker
  20. from frigate.util import (
  21. EventsPerSecond,
  22. FrameManager,
  23. SharedMemoryFrameManager,
  24. calculate_region,
  25. clipped,
  26. listen,
  27. yuv_region_2_rgb,
  28. )
  29. logger = logging.getLogger(__name__)
  30. def filtered(obj, objects_to_track, object_filters):
  31. object_name = obj[0]
  32. if not object_name in objects_to_track:
  33. return True
  34. if object_name in object_filters:
  35. obj_settings = object_filters[object_name]
  36. # if the min area is larger than the
  37. # detected object, don't add it to detected objects
  38. if obj_settings.min_area > obj[3]:
  39. return True
  40. # if the detected object is larger than the
  41. # max area, don't add it to detected objects
  42. if obj_settings.max_area < obj[3]:
  43. return True
  44. # if the score is lower than the min_score, skip
  45. if obj_settings.min_score > obj[1]:
  46. return True
  47. if not obj_settings.mask is None:
  48. # compute the coordinates of the object and make sure
  49. # the location isnt outside the bounds of the image (can happen from rounding)
  50. y_location = min(int(obj[2][3]), len(obj_settings.mask) - 1)
  51. x_location = min(
  52. int((obj[2][2] - obj[2][0]) / 2.0) + obj[2][0],
  53. len(obj_settings.mask[0]) - 1,
  54. )
  55. # if the object is in a masked location, don't add it to detected objects
  56. if obj_settings.mask[y_location][x_location] == 0:
  57. return True
  58. return False
  59. def create_tensor_input(frame, model_shape, region):
  60. cropped_frame = yuv_region_2_rgb(frame, region)
  61. # Resize to 300x300 if needed
  62. if cropped_frame.shape != (model_shape[0], model_shape[1], 3):
  63. cropped_frame = cv2.resize(
  64. cropped_frame, dsize=model_shape, interpolation=cv2.INTER_LINEAR
  65. )
  66. # Expand dimensions since the model expects images to have shape: [1, height, width, 3]
  67. return np.expand_dims(cropped_frame, axis=0)
  68. def stop_ffmpeg(ffmpeg_process, logger):
  69. logger.info("Terminating the existing ffmpeg process...")
  70. ffmpeg_process.terminate()
  71. try:
  72. logger.info("Waiting for ffmpeg to exit gracefully...")
  73. ffmpeg_process.communicate(timeout=30)
  74. except sp.TimeoutExpired:
  75. logger.info("FFmpeg didnt exit. Force killing...")
  76. ffmpeg_process.kill()
  77. ffmpeg_process.communicate()
  78. ffmpeg_process = None
  79. def start_or_restart_ffmpeg(
  80. ffmpeg_cmd, logger, logpipe: LogPipe, frame_size=None, ffmpeg_process=None
  81. ):
  82. if ffmpeg_process is not None:
  83. stop_ffmpeg(ffmpeg_process, logger)
  84. if frame_size is None:
  85. process = sp.Popen(
  86. ffmpeg_cmd,
  87. stdout=sp.DEVNULL,
  88. stderr=logpipe,
  89. stdin=sp.DEVNULL,
  90. start_new_session=True,
  91. )
  92. else:
  93. process = sp.Popen(
  94. ffmpeg_cmd,
  95. stdout=sp.PIPE,
  96. stderr=logpipe,
  97. stdin=sp.DEVNULL,
  98. bufsize=frame_size * 10,
  99. start_new_session=True,
  100. )
  101. return process
  102. def capture_frames(
  103. ffmpeg_process,
  104. camera_name,
  105. frame_shape,
  106. frame_manager: FrameManager,
  107. frame_queue,
  108. fps: mp.Value,
  109. skipped_fps: mp.Value,
  110. current_frame: mp.Value,
  111. ):
  112. frame_size = frame_shape[0] * frame_shape[1]
  113. frame_rate = EventsPerSecond()
  114. frame_rate.start()
  115. skipped_eps = EventsPerSecond()
  116. skipped_eps.start()
  117. while True:
  118. fps.value = frame_rate.eps()
  119. skipped_fps = skipped_eps.eps()
  120. current_frame.value = datetime.datetime.now().timestamp()
  121. frame_name = f"{camera_name}{current_frame.value}"
  122. frame_buffer = frame_manager.create(frame_name, frame_size)
  123. try:
  124. frame_buffer[:] = ffmpeg_process.stdout.read(frame_size)
  125. except Exception as e:
  126. logger.info(f"{camera_name}: ffmpeg sent a broken frame. {e}")
  127. if ffmpeg_process.poll() != None:
  128. logger.info(
  129. f"{camera_name}: ffmpeg process is not running. exiting capture thread..."
  130. )
  131. frame_manager.delete(frame_name)
  132. break
  133. continue
  134. frame_rate.update()
  135. # if the queue is full, skip this frame
  136. if frame_queue.full():
  137. skipped_eps.update()
  138. frame_manager.delete(frame_name)
  139. continue
  140. # close the frame
  141. frame_manager.close(frame_name)
  142. # add to the queue
  143. frame_queue.put(current_frame.value)
  144. class CameraWatchdog(threading.Thread):
  145. def __init__(
  146. self, camera_name, config, frame_queue, camera_fps, ffmpeg_pid, stop_event
  147. ):
  148. threading.Thread.__init__(self)
  149. self.logger = logging.getLogger(f"watchdog.{camera_name}")
  150. self.camera_name = camera_name
  151. self.config = config
  152. self.capture_thread = None
  153. self.ffmpeg_detect_process = None
  154. self.logpipe = LogPipe(f"ffmpeg.{self.camera_name}.detect", logging.ERROR)
  155. self.ffmpeg_other_processes = []
  156. self.camera_fps = camera_fps
  157. self.ffmpeg_pid = ffmpeg_pid
  158. self.frame_queue = frame_queue
  159. self.frame_shape = self.config.frame_shape_yuv
  160. self.frame_size = self.frame_shape[0] * self.frame_shape[1]
  161. self.stop_event = stop_event
  162. def run(self):
  163. self.start_ffmpeg_detect()
  164. for c in self.config.ffmpeg_cmds:
  165. if "detect" in c["roles"]:
  166. continue
  167. logpipe = LogPipe(
  168. f"ffmpeg.{self.camera_name}.{'_'.join(sorted(c['roles']))}",
  169. logging.ERROR,
  170. )
  171. self.ffmpeg_other_processes.append(
  172. {
  173. "cmd": c["cmd"],
  174. "logpipe": logpipe,
  175. "process": start_or_restart_ffmpeg(c["cmd"], self.logger, logpipe),
  176. }
  177. )
  178. time.sleep(10)
  179. while not self.stop_event.wait(10):
  180. now = datetime.datetime.now().timestamp()
  181. if not self.capture_thread.is_alive():
  182. self.logpipe.dump()
  183. self.start_ffmpeg_detect()
  184. elif now - self.capture_thread.current_frame.value > 20:
  185. self.logger.info(
  186. f"No frames received from {self.camera_name} in 20 seconds. Exiting ffmpeg..."
  187. )
  188. self.ffmpeg_detect_process.terminate()
  189. try:
  190. self.logger.info("Waiting for ffmpeg to exit gracefully...")
  191. self.ffmpeg_detect_process.communicate(timeout=30)
  192. except sp.TimeoutExpired:
  193. self.logger.info("FFmpeg didnt exit. Force killing...")
  194. self.ffmpeg_detect_process.kill()
  195. self.ffmpeg_detect_process.communicate()
  196. for p in self.ffmpeg_other_processes:
  197. poll = p["process"].poll()
  198. if poll == None:
  199. continue
  200. p["logpipe"].dump()
  201. p["process"] = start_or_restart_ffmpeg(
  202. p["cmd"], self.logger, p["logpipe"], ffmpeg_process=p["process"]
  203. )
  204. stop_ffmpeg(self.ffmpeg_detect_process, self.logger)
  205. for p in self.ffmpeg_other_processes:
  206. stop_ffmpeg(p["process"], self.logger)
  207. p["logpipe"].close()
  208. self.logpipe.close()
  209. def start_ffmpeg_detect(self):
  210. ffmpeg_cmd = [
  211. c["cmd"] for c in self.config.ffmpeg_cmds if "detect" in c["roles"]
  212. ][0]
  213. self.ffmpeg_detect_process = start_or_restart_ffmpeg(
  214. ffmpeg_cmd, self.logger, self.logpipe, self.frame_size
  215. )
  216. self.ffmpeg_pid.value = self.ffmpeg_detect_process.pid
  217. self.capture_thread = CameraCapture(
  218. self.camera_name,
  219. self.ffmpeg_detect_process,
  220. self.frame_shape,
  221. self.frame_queue,
  222. self.camera_fps,
  223. )
  224. self.capture_thread.start()
  225. class CameraCapture(threading.Thread):
  226. def __init__(self, camera_name, ffmpeg_process, frame_shape, frame_queue, fps):
  227. threading.Thread.__init__(self)
  228. self.name = f"capture:{camera_name}"
  229. self.camera_name = camera_name
  230. self.frame_shape = frame_shape
  231. self.frame_queue = frame_queue
  232. self.fps = fps
  233. self.skipped_fps = EventsPerSecond()
  234. self.frame_manager = SharedMemoryFrameManager()
  235. self.ffmpeg_process = ffmpeg_process
  236. self.current_frame = mp.Value("d", 0.0)
  237. self.last_frame = 0
  238. def run(self):
  239. self.skipped_fps.start()
  240. capture_frames(
  241. self.ffmpeg_process,
  242. self.camera_name,
  243. self.frame_shape,
  244. self.frame_manager,
  245. self.frame_queue,
  246. self.fps,
  247. self.skipped_fps,
  248. self.current_frame,
  249. )
  250. def capture_camera(name, config: CameraConfig, process_info):
  251. stop_event = mp.Event()
  252. def receiveSignal(signalNumber, frame):
  253. stop_event.set()
  254. signal.signal(signal.SIGTERM, receiveSignal)
  255. signal.signal(signal.SIGINT, receiveSignal)
  256. frame_queue = process_info["frame_queue"]
  257. camera_watchdog = CameraWatchdog(
  258. name,
  259. config,
  260. frame_queue,
  261. process_info["camera_fps"],
  262. process_info["ffmpeg_pid"],
  263. stop_event,
  264. )
  265. camera_watchdog.start()
  266. camera_watchdog.join()
  267. def track_camera(
  268. name,
  269. config: CameraConfig,
  270. model_shape,
  271. detection_queue,
  272. result_connection,
  273. detected_objects_queue,
  274. process_info,
  275. ):
  276. stop_event = mp.Event()
  277. def receiveSignal(signalNumber, frame):
  278. stop_event.set()
  279. signal.signal(signal.SIGTERM, receiveSignal)
  280. signal.signal(signal.SIGINT, receiveSignal)
  281. threading.current_thread().name = f"process:{name}"
  282. setproctitle(f"frigate.process:{name}")
  283. listen()
  284. frame_queue = process_info["frame_queue"]
  285. detection_enabled = process_info["detection_enabled"]
  286. frame_shape = config.frame_shape
  287. objects_to_track = config.objects.track
  288. object_filters = config.objects.filters
  289. motion_detector = MotionDetector(frame_shape, config.motion)
  290. object_detector = RemoteObjectDetector(
  291. name, "/labelmap.txt", detection_queue, result_connection, model_shape
  292. )
  293. object_tracker = ObjectTracker(config.detect)
  294. frame_manager = SharedMemoryFrameManager()
  295. process_frames(
  296. name,
  297. frame_queue,
  298. frame_shape,
  299. model_shape,
  300. frame_manager,
  301. motion_detector,
  302. object_detector,
  303. object_tracker,
  304. detected_objects_queue,
  305. process_info,
  306. objects_to_track,
  307. object_filters,
  308. detection_enabled,
  309. stop_event,
  310. )
  311. logger.info(f"{name}: exiting subprocess")
  312. def reduce_boxes(boxes):
  313. if len(boxes) == 0:
  314. return []
  315. reduced_boxes = cv2.groupRectangles(
  316. [list(b) for b in itertools.chain(boxes, boxes)], 1, 0.2
  317. )[0]
  318. return [tuple(b) for b in reduced_boxes]
  319. # modified from https://stackoverflow.com/a/40795835
  320. def intersects_any(box_a, boxes):
  321. for box in boxes:
  322. if (
  323. box_a[2] < box[0]
  324. or box_a[0] > box[2]
  325. or box_a[1] > box[3]
  326. or box_a[3] < box[1]
  327. ):
  328. continue
  329. return True
  330. def detect(
  331. object_detector, frame, model_shape, region, objects_to_track, object_filters
  332. ):
  333. tensor_input = create_tensor_input(frame, model_shape, region)
  334. detections = []
  335. region_detections = object_detector.detect(tensor_input)
  336. for d in region_detections:
  337. box = d[2]
  338. size = region[2] - region[0]
  339. x_min = int((box[1] * size) + region[0])
  340. y_min = int((box[0] * size) + region[1])
  341. x_max = int((box[3] * size) + region[0])
  342. y_max = int((box[2] * size) + region[1])
  343. det = (
  344. d[0],
  345. d[1],
  346. (x_min, y_min, x_max, y_max),
  347. (x_max - x_min) * (y_max - y_min),
  348. region,
  349. )
  350. # apply object filters
  351. if filtered(det, objects_to_track, object_filters):
  352. continue
  353. detections.append(det)
  354. return detections
  355. def process_frames(
  356. camera_name: str,
  357. frame_queue: mp.Queue,
  358. frame_shape,
  359. model_shape,
  360. frame_manager: FrameManager,
  361. motion_detector: MotionDetector,
  362. object_detector: RemoteObjectDetector,
  363. object_tracker: ObjectTracker,
  364. detected_objects_queue: mp.Queue,
  365. process_info: Dict,
  366. objects_to_track: List[str],
  367. object_filters,
  368. detection_enabled: mp.Value,
  369. stop_event,
  370. exit_on_empty: bool = False,
  371. ):
  372. fps = process_info["process_fps"]
  373. detection_fps = process_info["detection_fps"]
  374. current_frame_time = process_info["detection_frame"]
  375. fps_tracker = EventsPerSecond()
  376. fps_tracker.start()
  377. while not stop_event.is_set():
  378. if exit_on_empty and frame_queue.empty():
  379. logger.info(f"Exiting track_objects...")
  380. break
  381. try:
  382. frame_time = frame_queue.get(True, 10)
  383. except queue.Empty:
  384. continue
  385. current_frame_time.value = frame_time
  386. frame = frame_manager.get(
  387. f"{camera_name}{frame_time}", (frame_shape[0] * 3 // 2, frame_shape[1])
  388. )
  389. if frame is None:
  390. logger.info(f"{camera_name}: frame {frame_time} is not in memory store.")
  391. continue
  392. if not detection_enabled.value:
  393. fps.value = fps_tracker.eps()
  394. object_tracker.match_and_update(frame_time, [])
  395. detected_objects_queue.put(
  396. (camera_name, frame_time, object_tracker.tracked_objects, [], [])
  397. )
  398. detection_fps.value = object_detector.fps.eps()
  399. frame_manager.close(f"{camera_name}{frame_time}")
  400. continue
  401. # look for motion
  402. motion_boxes = motion_detector.detect(frame)
  403. # only get the tracked object boxes that intersect with motion
  404. tracked_object_boxes = [
  405. obj["box"]
  406. for obj in object_tracker.tracked_objects.values()
  407. if intersects_any(obj["box"], motion_boxes)
  408. ]
  409. # combine motion boxes with known locations of existing objects
  410. combined_boxes = reduce_boxes(motion_boxes + tracked_object_boxes)
  411. # compute regions
  412. regions = [
  413. calculate_region(frame_shape, a[0], a[1], a[2], a[3], 1.2)
  414. for a in combined_boxes
  415. ]
  416. # combine overlapping regions
  417. combined_regions = reduce_boxes(regions)
  418. # re-compute regions
  419. regions = [
  420. calculate_region(frame_shape, a[0], a[1], a[2], a[3], 1.0)
  421. for a in combined_regions
  422. ]
  423. # resize regions and detect
  424. detections = []
  425. for region in regions:
  426. detections.extend(
  427. detect(
  428. object_detector,
  429. frame,
  430. model_shape,
  431. region,
  432. objects_to_track,
  433. object_filters,
  434. )
  435. )
  436. #########
  437. # merge objects, check for clipped objects and look again up to 4 times
  438. #########
  439. refining = True
  440. refine_count = 0
  441. while refining and refine_count < 4:
  442. refining = False
  443. # group by name
  444. detected_object_groups = defaultdict(lambda: [])
  445. for detection in detections:
  446. detected_object_groups[detection[0]].append(detection)
  447. selected_objects = []
  448. for group in detected_object_groups.values():
  449. # apply non-maxima suppression to suppress weak, overlapping bounding boxes
  450. boxes = [
  451. (o[2][0], o[2][1], o[2][2] - o[2][0], o[2][3] - o[2][1])
  452. for o in group
  453. ]
  454. confidences = [o[1] for o in group]
  455. idxs = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
  456. for index in idxs:
  457. obj = group[index[0]]
  458. if clipped(obj, frame_shape):
  459. box = obj[2]
  460. # calculate a new region that will hopefully get the entire object
  461. region = calculate_region(
  462. frame_shape, box[0], box[1], box[2], box[3]
  463. )
  464. regions.append(region)
  465. selected_objects.extend(
  466. detect(
  467. object_detector,
  468. frame,
  469. model_shape,
  470. region,
  471. objects_to_track,
  472. object_filters,
  473. )
  474. )
  475. refining = True
  476. else:
  477. selected_objects.append(obj)
  478. # set the detections list to only include top, complete objects
  479. # and new detections
  480. detections = selected_objects
  481. if refining:
  482. refine_count += 1
  483. # Limit to the detections overlapping with motion areas
  484. # to avoid picking up stationary background objects
  485. detections_with_motion = [
  486. d for d in detections if intersects_any(d[2], motion_boxes)
  487. ]
  488. # now that we have refined our detections, we need to track objects
  489. object_tracker.match_and_update(frame_time, detections_with_motion)
  490. # add to the queue if not full
  491. if detected_objects_queue.full():
  492. frame_manager.delete(f"{camera_name}{frame_time}")
  493. continue
  494. else:
  495. fps_tracker.update()
  496. fps.value = fps_tracker.eps()
  497. detected_objects_queue.put(
  498. (
  499. camera_name,
  500. frame_time,
  501. object_tracker.tracked_objects,
  502. motion_boxes,
  503. regions,
  504. )
  505. )
  506. detection_fps.value = object_detector.fps.eps()
  507. frame_manager.close(f"{camera_name}{frame_time}")