Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FIX: PyAVReaderTimed.close does not close container #447

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions pims/pyav_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,12 @@ def __init__(self, file, cache_size=16, fast_forward_thresh=32,

self._reset_demuxer()

self._is_container_closed = False

def __del__(self):
if not self._is_container_closed:
self._container.close()

def __len__(self):
return int(self._duration * self._frame_rate)

Expand All @@ -151,6 +157,10 @@ def _reset_demuxer(self):
self._frame_generator = _gen_frames(demuxer, self._stream.time_base,
self._frame_rate, self._first_pts)

def close(self):
self._container.close()
self._is_container_closed = True

@property
def duration(self):
"""The video duration in seconds."""
Expand All @@ -175,6 +185,10 @@ def get_frame(self, i):
if cached_i == i:
return cached_frame.to_frame()

# Stop before seeking to frame, to avoid crashing
if self._is_container_closed:
raise ValueError("Cannot read uncached frame from closed file. Try other frame index or re-open file.")

# check if we will have to seek to the frame
if self._last_frame >= i or \
self._last_frame < i - self._fast_forward_thresh:
Expand Down
22 changes: 22 additions & 0 deletions pims/tests/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,28 @@ def setUp(self):
self.expected_shape = (424, 640, 3)
self.expected_len = 480

def test_close(self):
vid = self.klass(self.filename)

assert vid[10].shape == self.expected_shape

vid.close()

assert vid[9].shape == self.expected_shape

with self.assertRaises(ValueError):
vid[11].shape

def test_context_manager(self):

with self.klass(self.filename) as vid:
assert vid[10].shape == self.expected_shape

assert vid[9].shape == self.expected_shape

with self.assertRaises(ValueError):
vid[11].shape


class TestVideo_PyAV_indexed(_image_series, unittest.TestCase):
def check_skip(self):
Expand Down