diff --git a/scenedetect/backends/opencv.py b/scenedetect/backends/opencv.py index 25b36044..509fd37d 100644 --- a/scenedetect/backends/opencv.py +++ b/scenedetect/backends/opencv.py @@ -396,6 +396,17 @@ def _open_capture(self, frame_rate: FrameRate | None = None): "Ensure file is valid video and system dependencies are up to date.\n" ) + # On Windows, MSMF can open inputs without a video stream (e.g. audio only) as 0x0, and + # reading from them hangs (https://github.com/opencv/opencv/issues/31215). Other backends + # can also report 0x0, but for valid videos (e.g. if the video starts late). + if ( + not self._is_device + and cap.getBackendName() == "MSMF" + and (cap.get(cv2.CAP_PROP_FRAME_WIDTH) <= 0 or cap.get(cv2.CAP_PROP_FRAME_HEIGHT) <= 0) + ): + cap.release() + raise VideoOpenFailure("No video stream found in input.") + # Display an error if the video codec type seems unsupported (#86) as this indicates # potential video corruption, or may explain missing frames. We only perform this check # for video files on-disk (skipped for devices, image sequences, streams, etc...). diff --git a/scenedetect/backends/pyav.py b/scenedetect/backends/pyav.py index d173869f..a38ca728 100644 --- a/scenedetect/backends/pyav.py +++ b/scenedetect/backends/pyav.py @@ -182,11 +182,13 @@ def __init__( self._io = path_or_io self._container: av.container.InputContainer = self._open_container() # type: ignore[attr-defined] + if not self._container.streams.video: + raise VideoOpenFailure("No video stream found in input file.") if self._threading_mode is not None: self._video_stream.thread_type = self._threading_mode self._reopened = False logger.debug("Threading mode set: %s", self._threading_mode) - except OSError: + except (OSError, VideoOpenFailure): raise except Exception as ex: raise VideoOpenFailure(str(ex)) from ex diff --git a/tests/test_backend_opencv.py b/tests/test_backend_opencv.py index d3c6e6e7..026bd9f6 100644 --- a/tests/test_backend_opencv.py +++ b/tests/test_backend_opencv.py @@ -24,6 +24,7 @@ from scenedetect import ContentDetector, SceneManager from scenedetect.backends.opencv import VideoCaptureAdapter, VideoStreamCv2 +from scenedetect.video_stream import VideoOpenFailure GROUND_TRUTH_CAPTURE_ADAPTER_TEST = [1, 90, 210] GROUND_TRUTH_CAPTURE_ADAPTER_CALLBACK_TEST = [180, 394] @@ -62,6 +63,49 @@ def spy(*args): assert sequence.read() is not False +@pytest.mark.parametrize("backend", ["MSMF", "FFMPEG"]) +@pytest.mark.parametrize("name", ["video.mp4", "100% video.mp4", "http://a/video.mp4"]) +def test_zero_frame_size_is_only_rejected_with_msmf(name: str, backend: str, monkeypatch, tmp_path): + """MSMF reports a frame size of 0x0 if there is no video stream, and reading from it hangs. + Other backends can report 0x0 for valid videos, so they must not be rejected. + + See https://github.com/opencv/opencv/issues/31215 for details.""" + + class FakeCapture: + released = False + + def __init__(self, *args): + pass + + def isOpened(self): + return True + + def getBackendName(self): + return backend + + def get(self, prop): + return 0.0 if prop in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT) else 25.0 + + def set(self, prop, value): + return True + + def release(self): + FakeCapture.released = True + + path = name + if "://" not in name: + (tmp_path / name).touch() + path = str(tmp_path / name) + monkeypatch.setattr(cv2, "VideoCapture", FakeCapture) + if backend == "MSMF": + with pytest.raises(VideoOpenFailure, match="No video stream"): + VideoStreamCv2(path) + assert FakeCapture.released + else: + assert VideoStreamCv2(path).frame_size == (0, 0) + assert not FakeCapture.released + + def test_capture_adapter(test_movie_clip: str): """Test that the VideoCaptureAdapter works with SceneManager.""" cap = cv2.VideoCapture(test_movie_clip) diff --git a/tests/test_video_stream.py b/tests/test_video_stream.py index fba7e966..09cab3e7 100644 --- a/tests/test_video_stream.py +++ b/tests/test_video_stream.py @@ -18,6 +18,7 @@ import os.path import typing as ty +import wave from dataclasses import dataclass import numpy @@ -26,7 +27,7 @@ from scenedetect import open_video from scenedetect.backends import VideoStreamAv, VideoStreamMoviePy from scenedetect.backends.opencv import VideoStreamCv2 -from scenedetect.video_stream import SeekError, VideoStream +from scenedetect.video_stream import SeekError, VideoOpenFailure, VideoStream # Accuracy a framerate is checked to for testing purposes. FRAMERATE_TOLERANCE = 0.001 @@ -359,6 +360,23 @@ def test_invalid_path(vs_type: ty.Callable[..., VideoStream]): _ = vs_type("this_path_should_not_exist.mp4") +def test_no_video_stream(vs_type: ty.Callable[..., VideoStream], tmp_path): + """Opening a file with only an audio stream must raise VideoOpenFailure.""" + if vs_type is VideoStreamMoviePy: + pytest.skip("MoviePy already rejects this file with an OSError.") + # OpenCV opens this file with MSMF on Windows: https://github.com/opencv/opencv/issues/31215 + if vs_type is VideoStreamCv2 and os.name == "nt": + pytest.skip("MSMF opens audio-only files (opencv/opencv#31215).") + path = str(tmp_path / "audio_only.wav") + with wave.open(path, "wb") as audio: + audio.setnchannels(1) + audio.setsampwidth(2) + audio.setframerate(8000) + audio.writeframes(bytes(1600)) + with pytest.raises(VideoOpenFailure): + _ = vs_type(path) + + def test_framerate_legacy_alias(vs_type: ty.Callable[..., VideoStream], auto_close): """`framerate=` is the deprecated alias for `frame_rate=` (issue #548). All backends must accept both forms and produce the same `frame_rate`.""" diff --git a/website/pages/changelog.md b/website/pages/changelog.md index 3bb82505..376b7497 100644 --- a/website/pages/changelog.md +++ b/website/pages/changelog.md @@ -882,5 +882,6 @@ Major breaking release that overhauls how time is managed. Rather than assigning - [bugfix] Config files are now read as UTF-8 on all platforms, with or without a byte order mark [#633](https://github.com/Breakthrough/PySceneDetect/pull/633) - Previously, Windows defaulted to using the system code page on Python <= 3.14, so a config file with non-ASCII text would fail to load depending on the encoding/system locale - Non-ASCII text saved in a different encoding (e.g. ANSI on Windows) now fails to load. The config file can be saved as UTF-8 to resolve this. + - [bugfix] The PyAV backend now raises `VideoOpenFailure` instead of `IndexError` if the input has no video stream (e.g. audio only) [#630](https://github.com/Breakthrough/PySceneDetect/issues/630) - [general] Updates to Windows distributions: - Python 3.13 -> Python 3.14