video.py 22 KB

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