From 3f3688379e943a66dafef9596c874bad5a67a8f1 Mon Sep 17 00:00:00 2001 From: C-Achard Date: Tue, 24 Nov 2026 10:08:06 +0100 Subject: [PATCH 1/8] Copy video reader --- dlccore/io/video.py | 159 +++++++++++++++++++++++++ tests/io/test_video.py | 261 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 420 insertions(+) create mode 100644 dlccore/io/video.py create mode 100644 tests/io/test_video.py diff --git a/dlccore/io/video.py b/dlccore/io/video.py new file mode 100644 index 0000000..e11a55a --- /dev/null +++ b/dlccore/io/video.py @@ -0,0 +1,159 @@ +"""Video frames through OpenCV, lifted from napari-deeplabcut's ``Video``: RGB ``uint8`` frames by index.""" + +from __future__ import annotations + +from pathlib import Path +from types import TracebackType + +import cv2 +import numpy as np + +_MAX_FORWARD_DECODE = 8 + + +class Video: + """Random access to a video's frames, keeping decoder state between reads. + + A forward jump of at most eight frames decodes forward instead of seeking. + """ + + def __init__(self, video_path: str | Path) -> None: + """Open a video. + + Args: + video_path: The video file. + + Raises: + ValueError: If ``video_path`` is not a file. + OSError: If OpenCV cannot open it. + """ + + if not Path(video_path).is_file(): + raise ValueError(f'Video path "{video_path}" does not point to a file.') + + self._path = str(video_path) + self._stream = cv2.VideoCapture(self._path) + if not self._stream.isOpened(): + raise OSError("Video could not be opened.") + + self._n_frames = int(self._stream.get(cv2.CAP_PROP_FRAME_COUNT)) + self._width = int(self._stream.get(cv2.CAP_PROP_FRAME_WIDTH)) + self._height = int(self._stream.get(cv2.CAP_PROP_FRAME_HEIGHT)) + self._fps = float(self._stream.get(cv2.CAP_PROP_FPS)) + self._pos = 0 # next frame to read + + def __len__(self) -> int: + """Return the frame count OpenCV reports.""" + + return self._n_frames + + def __enter__(self) -> Video: + """Return this video, to close on leaving the block.""" + + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + traceback: TracebackType | None, + ) -> None: + """Release the stream.""" + + self.close() + + @property + def width(self) -> int: + return self._width + + @property + def height(self) -> int: + return self._height + + @property + def fps(self) -> float: + """Frame rate the container reports.""" + + return self._fps + + def _seek(self, ind: int) -> None: + """Position the stream so the next read returns frame ``ind``, clamped to the video. + + Raises: + OSError: If OpenCV refuses the seek. + """ + + ind = max(0, min(ind, len(self) - 1)) + if ind != self._pos: + ok = self._stream.set(cv2.CAP_PROP_POS_FRAMES, ind) + if not ok: + raise OSError(f"Failed to seek to frame {ind}") + self._pos = ind + + def _read_next(self) -> np.ndarray: + """Decode the next frame as RGB. + + Raises: + IndexError: If no frame could be read. + """ + + ok, frame = self._stream.read() + if not ok: + raise IndexError("Could not read frame") + self._pos += 1 + return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + + def _grab_next(self) -> bool: + """Advance one frame without converting it. + + Raises: + IndexError: If no frame could be grabbed. + """ + + ok = self._stream.grab() + if not ok: + raise IndexError("Could not grab frame") + self._pos += 1 + return ok + + def read_frame(self, ind: int) -> np.ndarray: + """Return frame ``ind`` as an RGB ``uint8`` array of shape ``(height, width, 3)``. + + Raises: + IndexError: If ``ind`` is outside the video. + """ + + if ind < 0 or ind >= len(self): + raise IndexError(f"Frame index {ind} out of bounds for video with {len(self)} frames.") + + if ind == self._pos: + return self._read_next() + + if ind > self._pos and (ind - self._pos) <= _MAX_FORWARD_DECODE: + while self._pos < ind: + self._grab_next() + return self._read_next() + + self._seek(ind) + return self._read_next() + + def read_frames(self, start: int, stop: int) -> np.ndarray: + """Return frames ``start`` to ``stop`` (exclusive), clamped to the video, as ``(n, height, width, 3)``.""" + + start = max(0, start) + stop = min(stop, len(self)) + if stop <= start: + return np.empty((0, self.height, self.width, 3), dtype=np.uint8) + + self._seek(start) + out = np.empty((stop - start, self.height, self.width, 3), dtype=np.uint8) + + for i in range(stop - start): + out[i] = self._read_next() + + return out + + def close(self) -> None: + """Release the stream.""" + + self._stream.release() diff --git a/tests/io/test_video.py b/tests/io/test_video.py new file mode 100644 index 0000000..5b52155 --- /dev/null +++ b/tests/io/test_video.py @@ -0,0 +1,261 @@ +import shutil +import subprocess +from pathlib import Path + +import cv2 +import numpy as np +import pytest +from deeplabcut.utils.auxfun_videos import VideoReader + +from dlc_octopus.io import Video + +N_FRAMES = 60 +WIDTH, HEIGHT = 128, 96 +FPS = 10 +BASE, LEVEL_OFFSET, LEVEL_STEP = 8, 16, 32 +DIGIT = 32 # side of each digit's square, in pixels + +# First, small forward jump, large forward jump to the last, backward, sequential, small forward, large forward. +# With OpenCV's mp4v writer, keyframes fall every 12 frames; 17, 50 and 59 are inter frames. +ACCESS_ORDER = [0, 5, N_FRAMES - 1, 17, 18, 25, 50] + +CODECS = {"MJPG": ".avi", "mp4v": ".mp4"} + +# A fixed textured background keeps most of each frame static, so mp4v writes inter frames rather than all keyframes. +_BACKGROUND = cv2.GaussianBlur(np.random.default_rng(0).integers(0, 256, (HEIGHT, WIDTH, 3), dtype=np.uint8), (9, 9), 3) + + +def _encoded(index: int) -> np.ndarray: + """Frame ``index``: its two base-8 digits as flat grey squares, levels far apart to survive lossy codecs.""" + + frame = _BACKGROUND.copy() + frame[:DIGIT, :DIGIT] = LEVEL_OFFSET + LEVEL_STEP * (index // BASE) + frame[:DIGIT, DIGIT : 2 * DIGIT] = LEVEL_OFFSET + LEVEL_STEP * (index % BASE) + return frame + + +def _index_of(frame: np.ndarray) -> int: + """Map a decoded frame back to the index it was written at, reading each square away from its edges.""" + + def digit(square: np.ndarray) -> int: + return round((float(square.mean()) - LEVEL_OFFSET) / LEVEL_STEP) + + inner = slice(8, DIGIT - 8) + high = frame[inner, inner] + low = frame[inner, DIGIT + 8 : 2 * DIGIT - 8] + return BASE * digit(high) + digit(low) + + +def _write_video(path: Path, fourcc: str) -> bool: + writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*fourcc), FPS, (WIDTH, HEIGHT)) + if not writer.isOpened(): + return False + for index in range(N_FRAMES): + writer.write(_encoded(index)) + writer.release() + + capture = cv2.VideoCapture(str(path)) + decoded = [] + while True: + ok, frame = capture.read() + if not ok: + break + decoded.append(_index_of(frame)) + capture.release() + return decoded == list(range(N_FRAMES)) + + +@pytest.fixture(scope="module", params=list(CODECS)) +def video_path(request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory) -> Path: + fourcc = request.param + path = tmp_path_factory.mktemp(f"video_{fourcc}") / f"indexed{CODECS[fourcc]}" + if not _write_video(path, fourcc): + pytest.skip(f"This OpenCV build cannot write and decode back a {fourcc} video.") + return path + + +def test_the_fixture_encodes_each_index_distinctly() -> None: + # Control: without compression, every index round-trips. + assert [_index_of(_encoded(index)) for index in range(N_FRAMES)] == list(range(N_FRAMES)) + + +def test_the_mp4v_fixture_has_inter_frames_at_the_accessed_indices(video_path: Path) -> None: + # Control: otherwise the mp4v equivalence tests would only ever land on keyframes. + if video_path.suffix != ".mp4": + pytest.skip("Only the mp4v fixture is meant to have inter frames.") + ffprobe = shutil.which("ffprobe") + if ffprobe is None: + pytest.skip("ffprobe is not on PATH.") + arguments = ["-v", "error", "-select_streams", "v:0", "-show_entries", "frame=pict_type", "-of", "csv=p=0"] + probed = subprocess.run( + [ffprobe, *arguments, str(video_path)], + capture_output=True, + text=True, + check=True, + ) + picture_types = [line.strip().strip(",") for line in probed.stdout.splitlines() if line.strip()] + + assert len(picture_types) == N_FRAMES + assert [index for index in ACCESS_ORDER if picture_types[index] == "I"] == [0] + + +def test_video_properties(video_path: Path) -> None: + video = Video(video_path) + + assert (len(video), video.width, video.height, video.fps) == (N_FRAMES, WIDTH, HEIGHT, FPS) + + video.close() + assert not video._stream.isOpened() + + +def test_a_context_manager_closes_the_video(video_path: Path) -> None: + with Video(video_path) as video: + assert video._stream.isOpened() + + assert not video._stream.isOpened() + + +def test_a_frame_is_rgb_uint8_of_the_video_shape(video_path: Path) -> None: + with Video(video_path) as video: + frame = video.read_frame(0) + + assert (frame.shape, frame.dtype) == ((HEIGHT, WIDTH, 3), np.uint8) + + +def test_frames_are_rgb(tmp_path: Path) -> None: + path = tmp_path / "blue.avi" + writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"MJPG"), FPS, (WIDTH, HEIGHT)) + if not writer.isOpened(): + pytest.skip("This OpenCV build cannot write MJPG.") + bgr_blue = np.zeros((HEIGHT, WIDTH, 3), dtype=np.uint8) + bgr_blue[..., 0] = 255 + writer.write(bgr_blue) + writer.release() + + with Video(path) as video: + red, _green, blue = video.read_frame(0).reshape(-1, 3).mean(axis=0) + + assert (blue > 200, red < 50) == (True, True) + + +@pytest.mark.parametrize("index", [N_FRAMES, -1]) +def test_a_frame_outside_the_video_is_an_index_error(video_path: Path, index: int) -> None: + with Video(video_path) as video, pytest.raises(IndexError): + video.read_frame(index) + + +def test_sequential_reads_return_consecutive_frames(video_path: Path) -> None: + with Video(video_path) as video: + indices = [_index_of(video.read_frame(index)) for index in range(N_FRAMES)] + + assert indices == list(range(N_FRAMES)) + + +def test_a_block_read_returns_the_frames_in_range(video_path: Path) -> None: + with Video(video_path) as video: + video.read_frame(30) + block = video.read_frames(10, 20) + + assert (block.shape, block.dtype) == ((10, HEIGHT, WIDTH, 3), np.uint8) + assert [_index_of(frame) for frame in block] == list(range(10, 20)) + + +def test_a_block_read_is_clamped_to_the_video(video_path: Path) -> None: + with Video(video_path) as video: + assert video.read_frames(N_FRAMES - 2, N_FRAMES + 5).shape[0] == 2 + assert video.read_frames(5, 5).shape == (0, HEIGHT, WIDTH, 3) + + +def test_a_path_that_is_not_a_file_is_a_value_error(tmp_path: Path) -> None: + with pytest.raises(ValueError, match="does not point to a file"): + Video(tmp_path) + + +def test_a_file_opencv_cannot_open_is_an_os_error(tmp_path: Path) -> None: + path = tmp_path / "not_a_video.mp4" + path.write_bytes(b"not a video") + + with pytest.raises(OSError, match="could not be opened"): + Video(path) + + +class _Refusing: + """The real stream, with one decoder call failing as OpenCV reports it: a false ``ok``.""" + + def __init__(self, stream: cv2.VideoCapture, refused: str) -> None: + self._stream = stream + self._refused = refused + + def set(self, *args: object) -> bool: + return False if self._refused == "set" else self._stream.set(*args) + + def read(self) -> tuple[bool, np.ndarray | None]: + return (False, None) if self._refused == "read" else self._stream.read() + + def grab(self) -> bool: + return False if self._refused == "grab" else self._stream.grab() + + def release(self) -> None: + self._stream.release() + + +@pytest.mark.parametrize( + ("refused", "index", "error", "message"), + [ + ("set", N_FRAMES - 1, OSError, "seek to frame"), + ("read", 0, IndexError, "read frame"), + ("grab", 3, IndexError, "grab frame"), + ], + ids=["seek", "read", "grab"], +) +def test_a_decoder_failure_is_raised_not_returned_as_a_frame( + video_path: Path, refused: str, index: int, error: type[Exception], message: str +) -> None: + with Video(video_path) as video: + video._stream = _Refusing(video._stream, refused) + + with pytest.raises(error, match=message): + video.read_frame(index) + + +def test_read_frame_decodes_the_requested_frame(video_path: Path) -> None: + with Video(video_path) as video: + decoded = [_index_of(video.read_frame(index)) for index in ACCESS_ORDER] + + assert decoded == ACCESS_ORDER + + +def test_read_frame_equals_deeplabcut_opencv_extraction(video_path: Path) -> None: + # DeepLabCut's extract_frames(opencv=True): set_to_frame, then read_frame(crop=True); it returns RGB. + reader = VideoReader(str(video_path)) + try: + expected = [_extract_with_deeplabcut(reader, index) for index in ACCESS_ORDER] + finally: + reader.close() + + with Video(video_path) as video: + for index, frame in zip(ACCESS_ORDER, expected, strict=True): + np.testing.assert_array_equal(video.read_frame(index), frame, err_msg=f"frame {index}") + + +def test_read_frame_equals_moviepy_extraction(video_path: Path) -> None: + # DeepLabCut's extract_frames(opencv=False): VideoFileClip.get_frame(index / fps), moviepy 1.x. + editor = pytest.importorskip("moviepy.editor") + + clip = editor.VideoFileClip(str(video_path)) + try: + expected = [_index_of(clip.get_frame(index * 1.0 / clip.fps)) for index in ACCESS_ORDER] + finally: + clip.close() + + with Video(video_path) as video: + decoded = [_index_of(video.read_frame(index)) for index in ACCESS_ORDER] + + assert decoded == expected == ACCESS_ORDER + + +def _extract_with_deeplabcut(reader: VideoReader, index: int) -> np.ndarray: + reader.set_to_frame(index) + frame = reader.read_frame(crop=True) + assert frame is not None, f"DeepLabCut read no frame at {index}" + return frame From fc8d96f428eba3f1c53a97b78893840fda39dd21 Mon Sep 17 00:00:00 2001 From: C-Achard Date: Tue, 24 Nov 2026 10:20:32 +0100 Subject: [PATCH 2/8] Adapt video reader to dlccore - Rename the package to dlccore.io and add the dlccore license header - Add the optional `video` extra (opencv-python-headless>=5) and an `all` extra listing every extra; dlccore.io does not re-export Video, so OpenCV loads only with dlccore.io.video - test_video skips without OpenCV, and its DeepLabCut comparison skips without DeepLabCut - CI installs .[all] for the test, weekly and wheel jobs; the dependency-floor job stays on the core install so numpy's floor stays tested --- .github/workflows/build_release.yml | 2 +- .github/workflows/test_package.yml | 2 +- .github/workflows/weekly_checks.yml | 2 +- dlccore/io/video.py | 11 +++++++++++ pyproject.toml | 2 ++ tests/io/test_video.py | 26 ++++++++++++++++++++++---- 6 files changed, 38 insertions(+), 7 deletions(-) diff --git a/.github/workflows/build_release.yml b/.github/workflows/build_release.yml index ffbbadb..03f53b5 100644 --- a/.github/workflows/build_release.yml +++ b/.github/workflows/build_release.yml @@ -42,7 +42,7 @@ jobs: ls dist - name: Install the wheel - run: python -m pip install "$(ls dist/*.whl)" "pytest>=8" + run: python -m pip install "$(ls dist/*.whl)[all]" "pytest>=8" - name: Test the wheel outside the source tree run: | diff --git a/.github/workflows/test_package.yml b/.github/workflows/test_package.yml index 3795484..adf147d 100644 --- a/.github/workflows/test_package.yml +++ b/.github/workflows/test_package.yml @@ -35,7 +35,7 @@ jobs: activate-environment: true - name: Install - run: uv pip install . "pytest>=8" + run: uv pip install ".[all]" "pytest>=8" - name: Test the installed package run: pytest tests diff --git a/.github/workflows/weekly_checks.yml b/.github/workflows/weekly_checks.yml index 989d147..e708715 100644 --- a/.github/workflows/weekly_checks.yml +++ b/.github/workflows/weekly_checks.yml @@ -29,7 +29,7 @@ jobs: activate-environment: true - name: Install with pre-releases allowed - run: uv pip install --prerelease allow . "pytest>=8" + run: uv pip install --prerelease allow ".[all]" "pytest>=8" # `-o filterwarnings`, not `-W`: `-W` matches the module name exactly and would miss every submodule - name: Test diff --git a/dlccore/io/video.py b/dlccore/io/video.py index e11a55a..9a02ede 100644 --- a/dlccore/io/video.py +++ b/dlccore/io/video.py @@ -1,3 +1,14 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + """Video frames through OpenCV, lifted from napari-deeplabcut's ``Video``: RGB ``uint8`` frames by index.""" from __future__ import annotations diff --git a/pyproject.toml b/pyproject.toml index 9510f6d..b3d9e80 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -27,6 +27,8 @@ dependencies = [ "ruamel-yaml>=0.16", "typing-extensions", ] +optional-dependencies.all = [ "dlccore[video]" ] +optional-dependencies.video = [ "opencv-python-headless>=5" ] urls.Homepage = "https://github.com/DeepLabCut/dlccore" urls.Repository = "https://github.com/DeepLabCut/dlccore" diff --git a/tests/io/test_video.py b/tests/io/test_video.py index 5b52155..96cf0b1 100644 --- a/tests/io/test_video.py +++ b/tests/io/test_video.py @@ -1,13 +1,30 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +from __future__ import annotations + import shutil import subprocess from pathlib import Path +from typing import TYPE_CHECKING -import cv2 import numpy as np import pytest -from deeplabcut.utils.auxfun_videos import VideoReader -from dlc_octopus.io import Video +cv2 = pytest.importorskip("cv2", reason="OpenCV comes with the optional 'video' extra") + +from dlccore.io.video import Video # noqa: E402 + +if TYPE_CHECKING: + from deeplabcut.utils.auxfun_videos import VideoReader N_FRAMES = 60 WIDTH, HEIGHT = 128, 96 @@ -227,7 +244,8 @@ def test_read_frame_decodes_the_requested_frame(video_path: Path) -> None: def test_read_frame_equals_deeplabcut_opencv_extraction(video_path: Path) -> None: # DeepLabCut's extract_frames(opencv=True): set_to_frame, then read_frame(crop=True); it returns RGB. - reader = VideoReader(str(video_path)) + auxfun_videos = pytest.importorskip("deeplabcut.utils.auxfun_videos") + reader = auxfun_videos.VideoReader(str(video_path)) try: expected = [_extract_with_deeplabcut(reader, index) for index in ACCESS_ORDER] finally: From c3d5122ecd80ecd14bddb78eb2681bafe92b98fb Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Fri, 27 Nov 2026 12:39:57 +0100 Subject: [PATCH 3/8] Adjust OpenCV version --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index b3d9e80..2fab704 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,7 +28,7 @@ dependencies = [ "typing-extensions", ] optional-dependencies.all = [ "dlccore[video]" ] -optional-dependencies.video = [ "opencv-python-headless>=5" ] +optional-dependencies.video = [ "opencv-python-headless>=4.10.0.84" ] urls.Homepage = "https://github.com/DeepLabCut/dlccore" urls.Repository = "https://github.com/DeepLabCut/dlccore" From 098db9f9a95a48813591757e4b7eff8ba74c2092 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Fri, 27 Nov 2026 12:43:45 +0100 Subject: [PATCH 4/8] Improve video error types and diagnostics Raise FileNotFoundError for invalid paths and include video paths and frame indices in decoding errors. Clarify reported frame-count limitations and update error tests. --- dlccore/io/video.py | 20 ++++++++++++-------- tests/io/test_video.py | 8 +++++--- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/dlccore/io/video.py b/dlccore/io/video.py index 9a02ede..b132164 100644 --- a/dlccore/io/video.py +++ b/dlccore/io/video.py @@ -35,17 +35,17 @@ def __init__(self, video_path: str | Path) -> None: video_path: The video file. Raises: - ValueError: If ``video_path`` is not a file. + FileNotFoundError: If ``video_path`` is not a file. OSError: If OpenCV cannot open it. """ if not Path(video_path).is_file(): - raise ValueError(f'Video path "{video_path}" does not point to a file.') + raise FileNotFoundError(f'Video path "{video_path}" does not point to a file.') self._path = str(video_path) self._stream = cv2.VideoCapture(self._path) if not self._stream.isOpened(): - raise OSError("Video could not be opened.") + raise OSError(f"{self._path}: video could not be opened by OpenCV.") self._n_frames = int(self._stream.get(cv2.CAP_PROP_FRAME_COUNT)) self._width = int(self._stream.get(cv2.CAP_PROP_FRAME_WIDTH)) @@ -54,7 +54,11 @@ def __init__(self, video_path: str | Path) -> None: self._pos = 0 # next frame to read def __len__(self) -> int: - """Return the frame count OpenCV reports.""" + """Return the frame count the container reports. + + This uses the ``CAP_PROP_FRAME_COUNT`` estimate for some containers: frames past it cannot be + read, and reading a frame before it can still raise ``IndexError``. + """ return self._n_frames @@ -98,7 +102,7 @@ def _seek(self, ind: int) -> None: if ind != self._pos: ok = self._stream.set(cv2.CAP_PROP_POS_FRAMES, ind) if not ok: - raise OSError(f"Failed to seek to frame {ind}") + raise OSError(f"{self._path}: failed to seek to frame {ind}") self._pos = ind def _read_next(self) -> np.ndarray: @@ -110,7 +114,7 @@ def _read_next(self) -> np.ndarray: ok, frame = self._stream.read() if not ok: - raise IndexError("Could not read frame") + raise IndexError(f"{self._path}: could not read frame {self._pos}") self._pos += 1 return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) @@ -123,7 +127,7 @@ def _grab_next(self) -> bool: ok = self._stream.grab() if not ok: - raise IndexError("Could not grab frame") + raise IndexError(f"{self._path}: could not grab frame {self._pos}") self._pos += 1 return ok @@ -131,7 +135,7 @@ def read_frame(self, ind: int) -> np.ndarray: """Return frame ``ind`` as an RGB ``uint8`` array of shape ``(height, width, 3)``. Raises: - IndexError: If ``ind`` is outside the video. + IndexError: If ``ind`` is outside the reported frame count, or the frame cannot be decoded. """ if ind < 0 or ind >= len(self): diff --git a/tests/io/test_video.py b/tests/io/test_video.py index 96cf0b1..a2c74c3 100644 --- a/tests/io/test_video.py +++ b/tests/io/test_video.py @@ -183,8 +183,8 @@ def test_a_block_read_is_clamped_to_the_video(video_path: Path) -> None: assert video.read_frames(5, 5).shape == (0, HEIGHT, WIDTH, 3) -def test_a_path_that_is_not_a_file_is_a_value_error(tmp_path: Path) -> None: - with pytest.raises(ValueError, match="does not point to a file"): +def test_a_path_that_is_not_a_file_is_a_file_not_found_error(tmp_path: Path) -> None: + with pytest.raises(FileNotFoundError, match="does not point to a file"): Video(tmp_path) @@ -192,9 +192,11 @@ def test_a_file_opencv_cannot_open_is_an_os_error(tmp_path: Path) -> None: path = tmp_path / "not_a_video.mp4" path.write_bytes(b"not a video") - with pytest.raises(OSError, match="could not be opened"): + with pytest.raises(OSError, match="could not be opened") as raised: Video(path) + assert str(path) in str(raised.value) + class _Refusing: """The real stream, with one decoder call failing as OpenCV reports it: a false ``ok``.""" From 5e1feda14c34ca21c82f8581a533dd3f25936ad4 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Fri, 27 Nov 2026 13:32:22 +0100 Subject: [PATCH 5/8] Honor video rotation metadata Enable OpenCV's automatic rotation and report unsupported rotation metadata. Expand video tests to cover rotated frames and H.264, and install video dependencies in the lowest-version CI job. --- .github/workflows/test_package.yml | 2 +- dlccore/io/video.py | 10 +++- tests/io/test_video.py | 82 ++++++++++++++++++++++++++---- 3 files changed, 82 insertions(+), 12 deletions(-) diff --git a/.github/workflows/test_package.yml b/.github/workflows/test_package.yml index adf147d..d15242e 100644 --- a/.github/workflows/test_package.yml +++ b/.github/workflows/test_package.yml @@ -53,7 +53,7 @@ jobs: activate-environment: true - name: Install the lowest version each dependency declares - run: uv pip install --resolution lowest-direct . "pytest>=8" + run: uv pip install --resolution lowest-direct ".[video]" "pytest>=8" - name: Test run: pytest tests diff --git a/dlccore/io/video.py b/dlccore/io/video.py index b132164..0aaf590 100644 --- a/dlccore/io/video.py +++ b/dlccore/io/video.py @@ -25,7 +25,8 @@ class Video: """Random access to a video's frames, keeping decoder state between reads. - A forward jump of at most eight frames decodes forward instead of seeking. + A forward jump of at most eight frames decodes forward instead of seeking. Frames are rotated by the video's + rotation metadata, as video players show them, and ``width`` and ``height`` are those of the rotated frames. """ def __init__(self, video_path: str | Path) -> None: @@ -36,7 +37,7 @@ def __init__(self, video_path: str | Path) -> None: Raises: FileNotFoundError: If ``video_path`` is not a file. - OSError: If OpenCV cannot open it. + OSError: If OpenCV cannot open it, or it has rotation metadata OpenCV cannot apply. """ if not Path(video_path).is_file(): @@ -46,6 +47,11 @@ def __init__(self, video_path: str | Path) -> None: self._stream = cv2.VideoCapture(self._path) if not self._stream.isOpened(): raise OSError(f"{self._path}: video could not be opened by OpenCV.") + # OpenCV 4.11.0 alone defaults to off; 4.10 and 4.12 onwards default to on + rotates = self._stream.set(cv2.CAP_PROP_ORIENTATION_AUTO, 1) + if not rotates and int(self._stream.get(cv2.CAP_PROP_ORIENTATION_META)) % 360 != 0: + self._stream.release() + raise OSError(f"{self._path}: OpenCV cannot rotate this video's frames by its rotation metadata.") self._n_frames = int(self._stream.get(cv2.CAP_PROP_FRAME_COUNT)) self._width = int(self._stream.get(cv2.CAP_PROP_FRAME_WIDTH)) diff --git a/tests/io/test_video.py b/tests/io/test_video.py index a2c74c3..4bcce3f 100644 --- a/tests/io/test_video.py +++ b/tests/io/test_video.py @@ -33,10 +33,13 @@ DIGIT = 32 # side of each digit's square, in pixels # First, small forward jump, large forward jump to the last, backward, sequential, small forward, large forward. -# With OpenCV's mp4v writer, keyframes fall every 12 frames; 17, 50 and 59 are inter frames. +# With OpenCV's mp4v writer, keyframes fall every 12 frames; in the H.264 fixture, every 30. Either way 17, 50 and 59 +# are inter frames. ACCESS_ORDER = [0, 5, N_FRAMES - 1, 17, 18, 25, 50] CODECS = {"MJPG": ".avi", "mp4v": ".mp4"} +# Encoded by the ffmpeg command line from the mp4v fixture, as OpenCV's wheels cannot write it; with B-frames +H264_ARGUMENTS = ["-c:v", "libx264", "-x264-params", "keyint=30:min-keyint=30:scenecut=0", "-bf", "2", "-crf", "10"] # A fixed textured background keeps most of each frame static, so mp4v writes inter frames rather than all keyframes. _BACKGROUND = cv2.GaussianBlur(np.random.default_rng(0).integers(0, 256, (HEIGHT, WIDTH, 3), dtype=np.uint8), (9, 9), 3) @@ -70,7 +73,10 @@ def _write_video(path: Path, fourcc: str) -> bool: for index in range(N_FRAMES): writer.write(_encoded(index)) writer.release() + return _decodes_every_index(path) + +def _decodes_every_index(path: Path) -> bool: capture = cv2.VideoCapture(str(path)) decoded = [] while True: @@ -82,12 +88,37 @@ def _write_video(path: Path, fourcc: str) -> bool: return decoded == list(range(N_FRAMES)) -@pytest.fixture(scope="module", params=list(CODECS)) +def _mp4v_video(directory: Path) -> Path: + path = directory / "indexed.mp4" + if not _write_video(path, "mp4v"): + pytest.skip("This OpenCV build cannot write and decode back a mp4v video.") + return path + + +def _ffmpeg(*arguments: str) -> None: + """Run the ffmpeg command line, skipping the test if it is missing or refuses.""" + + ffmpeg = shutil.which("ffmpeg") + if ffmpeg is None: + pytest.skip("ffmpeg is not on PATH.") + completed = subprocess.run([ffmpeg, "-y", "-v", "error", *arguments], capture_output=True, text=True, check=False) + if completed.returncode != 0: + pytest.skip(f"ffmpeg refused {arguments}: {completed.stderr.strip()}") + + +@pytest.fixture(scope="module", params=[*CODECS, "h264"]) def video_path(request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory) -> Path: - fourcc = request.param - path = tmp_path_factory.mktemp(f"video_{fourcc}") / f"indexed{CODECS[fourcc]}" - if not _write_video(path, fourcc): - pytest.skip(f"This OpenCV build cannot write and decode back a {fourcc} video.") + codec = request.param + directory = tmp_path_factory.mktemp(f"video_{codec}") + if codec == "h264": + path = directory / "indexed_h264.mp4" + _ffmpeg("-i", str(_mp4v_video(directory)), *H264_ARGUMENTS, str(path)) + if not _decodes_every_index(path): + pytest.skip("This OpenCV build cannot decode back the H.264 video.") + return path + path = directory / f"indexed{CODECS[codec]}" + if not _write_video(path, codec): + pytest.skip(f"This OpenCV build cannot write and decode back a {codec} video.") return path @@ -96,10 +127,10 @@ def test_the_fixture_encodes_each_index_distinctly() -> None: assert [_index_of(_encoded(index)) for index in range(N_FRAMES)] == list(range(N_FRAMES)) -def test_the_mp4v_fixture_has_inter_frames_at_the_accessed_indices(video_path: Path) -> None: - # Control: otherwise the mp4v equivalence tests would only ever land on keyframes. +def test_the_mp4_fixtures_have_inter_frames_at_the_accessed_indices(video_path: Path) -> None: + # Control: otherwise the mp4v and H.264 equivalence tests would only ever land on keyframes. if video_path.suffix != ".mp4": - pytest.skip("Only the mp4v fixture is meant to have inter frames.") + pytest.skip("Only the mp4v and H.264 fixtures are meant to have inter frames.") ffprobe = shutil.which("ffprobe") if ffprobe is None: pytest.skip("ffprobe is not on PATH.") @@ -125,6 +156,39 @@ def test_video_properties(video_path: Path) -> None: assert not video._stream.isOpened() +@pytest.fixture(scope="module") +def upright_and_rotated(tmp_path_factory: pytest.TempPathFactory) -> tuple[Path, Path]: + """The mp4v fixture, and the same stream with display-matrix metadata rotating it 90 degrees counterclockwise.""" + + directory = tmp_path_factory.mktemp("video_rotated") + upright = _mp4v_video(directory) + rotated = directory / "rotated.mp4" + _ffmpeg("-display_rotation", "90", "-i", str(upright), "-c", "copy", str(rotated)) + return upright, rotated + + +def test_frames_are_rotated_by_the_rotation_metadata( + upright_and_rotated: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch +) -> None: + # Every capture opens with OpenCV 4.11.0's default, no rotation, so the test holds on any OpenCV version. + open_capture = cv2.VideoCapture + + def opened_without_rotation(*args: object) -> cv2.VideoCapture: + capture = open_capture(*args) + capture.set(cv2.CAP_PROP_ORIENTATION_AUTO, 0) + return capture + + monkeypatch.setattr(cv2, "VideoCapture", opened_without_rotation) + upright_path, rotated_path = upright_and_rotated + + with Video(upright_path) as upright, Video(rotated_path) as rotated: + assert (rotated.width, rotated.height) == (HEIGHT, WIDTH) + for index in ACCESS_ORDER: + np.testing.assert_array_equal( + rotated.read_frame(index), np.rot90(upright.read_frame(index)), err_msg=f"frame {index}" + ) + + def test_a_context_manager_closes_the_video(video_path: Path) -> None: with Video(video_path) as video: assert video._stream.isOpened() From 90a015b4d7055e13359b0462c6b9b4ed084d8db9 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Fri, 27 Nov 2026 13:48:41 +0100 Subject: [PATCH 6/8] Add sequential video frame iteration Add Video.frames(start) and iterator support to yield RGB frames until the decoder ends, regardless of reported frame counts. Validate start bounds and cover iteration order, seeking, and inaccurate counts with tests. --- dlccore/io/video.py | 33 ++++++++++++++++++++++++++++++++- tests/io/test_video.py | 24 ++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/dlccore/io/video.py b/dlccore/io/video.py index 0aaf590..b5fbec4 100644 --- a/dlccore/io/video.py +++ b/dlccore/io/video.py @@ -13,6 +13,7 @@ from __future__ import annotations +from collections.abc import Iterator from pathlib import Path from types import TracebackType @@ -63,7 +64,8 @@ def __len__(self) -> int: """Return the frame count the container reports. This uses the ``CAP_PROP_FRAME_COUNT`` estimate for some containers: frames past it cannot be - read, and reading a frame before it can still raise ``IndexError``. + read by index, and reading a frame before it can still raise ``IndexError``. ``frames()`` reads to the + decoder's actual end. """ return self._n_frames @@ -174,6 +176,35 @@ def read_frames(self, start: int, stop: int) -> np.ndarray: return out + def frames(self, start: int = 0) -> Iterator[np.ndarray]: + """Yield frames from ``start`` in order, as RGB ``uint8`` arrays of shape ``(height, width, 3)``. + + Stops at the first frame the decoder cannot return, not at ``len()``: yields every frame of a video whose + reported frame count is too low, and ends early instead of raising on one that is too high. The stream is + positioned on the first ``next()``; other reads from this video during the iteration move it. + + Raises: + IndexError: If ``start`` is outside the reported frame count. + """ + + if start < 0 or start >= len(self): + raise IndexError(f"Start frame {start} out of bounds for video with {len(self)} frames.") + return self._frames_from(start) + + def _frames_from(self, start: int) -> Iterator[np.ndarray]: + self._seek(start) + while True: + ok, frame = self._stream.read() + if not ok: + return + self._pos += 1 + yield cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + + def __iter__(self) -> Iterator[np.ndarray]: + """Yield every frame from the first, as ``frames()`` does.""" + + return self.frames() + def close(self) -> None: """Release the stream.""" diff --git a/tests/io/test_video.py b/tests/io/test_video.py index 4bcce3f..2c080f7 100644 --- a/tests/io/test_video.py +++ b/tests/io/test_video.py @@ -247,6 +247,30 @@ def test_a_block_read_is_clamped_to_the_video(video_path: Path) -> None: assert video.read_frames(5, 5).shape == (0, HEIGHT, WIDTH, 3) +def test_iterating_yields_every_frame_in_order(video_path: Path) -> None: + with Video(video_path) as video: + assert [_index_of(frame) for frame in video] == list(range(N_FRAMES)) + + +def test_frames_start_at_the_given_frame_after_other_reads(video_path: Path) -> None: + with Video(video_path) as video: + video.read_frame(50) + assert [_index_of(frame) for frame in video.frames(17)] == list(range(17, N_FRAMES)) + + +@pytest.mark.parametrize("reported", [N_FRAMES - 5, N_FRAMES + 5], ids=["too-low", "too-high"]) +def test_frames_end_where_the_decoder_ends_not_at_the_reported_count(video_path: Path, reported: int) -> None: + with Video(video_path) as video: + video._n_frames = reported + assert [_index_of(frame) for frame in video.frames()] == list(range(N_FRAMES)) + + +@pytest.mark.parametrize("start", [-1, N_FRAMES]) +def test_frames_from_outside_the_video_is_an_index_error(video_path: Path, start: int) -> None: + with Video(video_path) as video, pytest.raises(IndexError, match="out of bounds"): + video.frames(start) + + def test_a_path_that_is_not_a_file_is_a_file_not_found_error(tmp_path: Path) -> None: with pytest.raises(FileNotFoundError, match="does not point to a file"): Video(tmp_path) From b00b2b383b1bd64bac6b6af0a05a7484cc2035d4 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Fri, 27 Nov 2026 13:51:42 +0100 Subject: [PATCH 7/8] Reset video position after decoder failures Mark stream position unknown after failed reads, grabs, or seeks so subsequent access seeks instead of decoding from stale state. Add a damaged-video regression test. --- dlccore/io/video.py | 33 ++++++++++++++++++++++++--------- tests/io/test_video.py | 40 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 63 insertions(+), 10 deletions(-) diff --git a/dlccore/io/video.py b/dlccore/io/video.py index b5fbec4..39dcdf0 100644 --- a/dlccore/io/video.py +++ b/dlccore/io/video.py @@ -26,8 +26,9 @@ class Video: """Random access to a video's frames, keeping decoder state between reads. - A forward jump of at most eight frames decodes forward instead of seeking. Frames are rotated by the video's - rotation metadata, as video players show them, and ``width`` and ``height`` are those of the rotated frames. + A forward jump of at most eight frames decodes forward instead of seeking, unless the previous read failed. Frames + are rotated by the video's rotation metadata, as video players show them, and ``width`` and ``height`` are those of + the rotated frames. """ def __init__(self, video_path: str | Path) -> None: @@ -58,7 +59,7 @@ def __init__(self, video_path: str | Path) -> None: self._width = int(self._stream.get(cv2.CAP_PROP_FRAME_WIDTH)) self._height = int(self._stream.get(cv2.CAP_PROP_FRAME_HEIGHT)) self._fps = float(self._stream.get(cv2.CAP_PROP_FPS)) - self._pos = 0 # next frame to read + self._pos: int | None = 0 # next frame to read; None after a failure, until the next seek def __len__(self) -> int: """Return the frame count the container reports. @@ -110,9 +111,17 @@ def _seek(self, ind: int) -> None: if ind != self._pos: ok = self._stream.set(cv2.CAP_PROP_POS_FRAMES, ind) if not ok: + self._pos = None raise OSError(f"{self._path}: failed to seek to frame {ind}") self._pos = ind + def _known_position(self) -> int: + """Return the next frame to read; only called once a seek has set it.""" + + if self._pos is None: + raise RuntimeError(f"{self._path}: stream position unknown after a failed read; seek first.") + return self._pos + def _read_next(self) -> np.ndarray: """Decode the next frame as RGB. @@ -120,10 +129,12 @@ def _read_next(self) -> np.ndarray: IndexError: If no frame could be read. """ + position = self._known_position() ok, frame = self._stream.read() if not ok: - raise IndexError(f"{self._path}: could not read frame {self._pos}") - self._pos += 1 + self._pos = None + raise IndexError(f"{self._path}: could not read frame {position}") + self._pos = position + 1 return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) def _grab_next(self) -> bool: @@ -133,10 +144,12 @@ def _grab_next(self) -> bool: IndexError: If no frame could be grabbed. """ + position = self._known_position() ok = self._stream.grab() if not ok: - raise IndexError(f"{self._path}: could not grab frame {self._pos}") - self._pos += 1 + self._pos = None + raise IndexError(f"{self._path}: could not grab frame {position}") + self._pos = position + 1 return ok def read_frame(self, ind: int) -> np.ndarray: @@ -152,7 +165,7 @@ def read_frame(self, ind: int) -> np.ndarray: if ind == self._pos: return self._read_next() - if ind > self._pos and (ind - self._pos) <= _MAX_FORWARD_DECODE: + if self._pos is not None and self._pos < ind <= self._pos + _MAX_FORWARD_DECODE: while self._pos < ind: self._grab_next() return self._read_next() @@ -194,10 +207,12 @@ def frames(self, start: int = 0) -> Iterator[np.ndarray]: def _frames_from(self, start: int) -> Iterator[np.ndarray]: self._seek(start) while True: + position = self._known_position() ok, frame = self._stream.read() if not ok: + self._pos = None return - self._pos += 1 + self._pos = position + 1 yield cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) def __iter__(self) -> Iterator[np.ndarray]: diff --git a/tests/io/test_video.py b/tests/io/test_video.py index 2c080f7..c35b115 100644 --- a/tests/io/test_video.py +++ b/tests/io/test_video.py @@ -21,7 +21,7 @@ cv2 = pytest.importorskip("cv2", reason="OpenCV comes with the optional 'video' extra") -from dlccore.io.video import Video # noqa: E402 +from dlccore.io.video import _MAX_FORWARD_DECODE, Video # noqa: E402 if TYPE_CHECKING: from deeplabcut.utils.auxfun_videos import VideoReader @@ -271,6 +271,44 @@ def test_frames_from_outside_the_video_is_an_index_error(video_path: Path, start video.frames(start) +@pytest.fixture +def damaged_path(video_path: Path, tmp_path: Path) -> Path: + """The fixture with a block of zeros mid-file, so some frames in the middle cannot be decoded.""" + + data = bytearray(video_path.read_bytes()) + middle = len(data) // 2 + data[middle : middle + 400] = bytes(400) + path = tmp_path / f"damaged{video_path.suffix}" + path.write_bytes(data) + return path + + +def _outcome(video: Video, index: int) -> int | str: + try: + return _index_of(video.read_frame(index)) + except IndexError: + return "IndexError" + + +def test_a_read_after_a_failed_read_returns_no_frame_a_fresh_seek_would_not(damaged_path: Path) -> None: + # The stream position is unknown after a failure, so a short forward jump must seek, not decode forward from it. + # A fresh seek's frame is allowed too: OpenCV's own seek can land on another frame in damage. + with Video(damaged_path) as video: + failed = next((index for index in range(N_FRAMES) if _outcome(video, index) == "IndexError"), None) + if failed is None: + pytest.skip("The damage left every frame decodable.") + ahead = range(failed + 1, min(failed + 1 + _MAX_FORWARD_DECODE, N_FRAMES)) + after_failure = [_outcome(video, index) for index in ahead] + + fresh = [] + for index in ahead: + with Video(damaged_path) as video: + fresh.append(_outcome(video, index)) + + for index, got, expected in zip(ahead, after_failure, fresh, strict=True): + assert got in (index, "IndexError", expected), f"frame {index}" + + def test_a_path_that_is_not_a_file_is_a_file_not_found_error(tmp_path: Path) -> None: with pytest.raises(FileNotFoundError, match="does not point to a file"): Video(tmp_path) From f03ecbc8a8ceaca12e9a4ca9323534487880c857 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Fri, 27 Nov 2026 16:50:04 +0100 Subject: [PATCH 8/8] Add ffmpeg to CI --- .github/workflows/test_package.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/workflows/test_package.yml b/.github/workflows/test_package.yml index d15242e..930e21f 100644 --- a/.github/workflows/test_package.yml +++ b/.github/workflows/test_package.yml @@ -34,6 +34,11 @@ jobs: python-version: ${{ matrix.python-version }} activate-environment: true + # Video tests that encode fixtures with ffmpeg skip without it; one OS is enough to run them + - name: Install ffmpeg + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y ffmpeg + - name: Install run: uv pip install ".[all]" "pytest>=8" @@ -52,6 +57,9 @@ jobs: python-version: "3.10" activate-environment: true + - name: Install ffmpeg + run: sudo apt-get update && sudo apt-get install -y ffmpeg + - name: Install the lowest version each dependency declares run: uv pip install --resolution lowest-direct ".[video]" "pytest>=8"