Skip to content

Commit

Permalink
Cleanup error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
tyler-romero committed Dec 18, 2024
1 parent 9c69308 commit a93ceef
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 26 deletions.
42 changes: 17 additions & 25 deletions src/framegrab/grabber.py
Original file line number Diff line number Diff line change
Expand Up @@ -1271,32 +1271,24 @@ def __init__(self, config: dict):
raise ValueError(f"Target FPS cannot be negative: {self.fps_target}")
self.remainder = 0.0

try:
self.capture = cv2.VideoCapture(filename)
try:
backend = self.capture.getBackendName()
except cv2.error:
raise ValueError(f"Could not open file {filename}. Is it a valid video file?")
logger.debug(f"Initialized video capture with {backend=}")

ret, _ = self.capture.read()
if not ret:
raise RuntimeError("Could not read first frame")

self.fps_source = round(self.capture.get(cv2.CAP_PROP_FPS), 2)
if self.fps_source <= 0.1:
logger.warning(f"Captured framerate is very low or zero: {self.fps_source} FPS")
self.should_drop_frames = self.fps_target > 0 and self.fps_target < self.fps_source
logger.debug(
f"Source FPS: {self.fps_source}, Target FPS: {self.fps_target}, Drop Frames: {self.should_drop_frames}"
)
self.capture = cv2.VideoCapture(filename)
if not self.capture.isOpened():
raise ValueError(f"Could not open file {filename}. Is it a valid video file?")
backend = self.capture.getBackendName()
logger.debug(f"Initialized video capture with {backend=}")

except (cv2.error, RuntimeError) as e:
logger.error(f"Could not initialize FileStreamFrameGrabber: {filename} is invalid or read error: {str(e)}")
raise
except OSError as e:
logger.error(f"Could not open file {filename}: {str(e)}")
raise
ret, _ = self.capture.read()
if not ret:
self.capture.release()
raise ValueError(f"Could not read first frame of file {filename}. Is it a valid video file?")

self.fps_source = round(self.capture.get(cv2.CAP_PROP_FPS), 2)
if self.fps_source <= 0.1:
logger.warning(f"Captured framerate is very low or zero: {self.fps_source} FPS")
self.should_drop_frames = self.fps_target > 0 and self.fps_target < self.fps_source
logger.debug(
f"Source FPS: {self.fps_source}, Target FPS: {self.fps_target}, Drop Frames: {self.should_drop_frames}"
)

def _grab_implementation(self) -> np.ndarray:
"""Grab a frame from the video file, decimating if needed to match target FPS.
Expand Down
2 changes: 1 addition & 1 deletion test/test_framegrab_with_filestream.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def test_invalid_file(self):
config = self.base_config_mp4.copy()
config["id"]["filename"] = "nonexistent.mp4"

with self.assertRaises(OSError):
with self.assertRaises(ValueError):
FileStreamFrameGrabber(config)

def test_invalid_resolution_option(self):
Expand Down

0 comments on commit a93ceef

Please sign in to comment.