Skip to content
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
11 changes: 11 additions & 0 deletions scenedetect/backends/opencv.py
Original file line number Diff line number Diff line change
Expand Up @@ -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...).
Expand Down
4 changes: 3 additions & 1 deletion scenedetect/backends/pyav.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
44 changes: 44 additions & 0 deletions tests/test_backend_opencv.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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)
Expand Down
20 changes: 19 additions & 1 deletion tests/test_video_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import os.path
import typing as ty
import wave
from dataclasses import dataclass

import numpy
Expand All @@ -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
Expand Down Expand Up @@ -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):

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Once the OpenCV check is removed, MSMF on Windows will probably open this file again. Can you:

Thanks for addressing this, other than this LGTM!

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, VideoStreamCv2 is now skipped here on Windows, with a link to opencv/opencv#31215, and the changelog only covers PyAV

I kept the OpenCV check only for MSMF, like you said in #630. Without it, audio-only files opened with PyAV fall back to OpenCV and hang on Windows

Since this test is skipped there, I also added one with a mocked capture. It checks that 0x0 is rejected with MSMF but not with FFmpeg

"""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`."""
Expand Down
1 change: 1 addition & 0 deletions website/pages/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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