Files
opencv-MIRROR/modules/videoio/misc/python/pyopencv_videoio.hpp
Tianyu Guo 3e1cb2371a Merge pull request #30798 from gty111:fix/python-video-stream-seek
videoio: fix large Python stream seeks and callback failures 🤖🤖🤖 - #30798

Opening an MP4 from a Python stream can segfault when its `moov` box requires an absolute seek beyond 2 GiB. `PythonStreamReader::seek()` narrows the 64-bit offset to `int`; a resulting Python exception is followed by operations on a null callback result. This was reproduced independently of a model runtime and through the unmodified video decoder class from vLLM main.

This patch preserves 64-bit read/seek arguments using the Python C API's `L` format, checks callback and conversion results before using them, and uses `PyEnsureGIL`/`PySafeObject` for cleanup. It also holds the GIL when releasing the stream's last Python reference. FFmpeg read callbacks now return `AVERROR(EIO)` on exceptions: returning zero caused an endless retry loop once callback exceptions were handled safely.

Regression tests cover a virtual MP4 larger than 2 GiB, exceptions and invalid results from read/seek callbacks, oversized reads, overflowing seek results, and releasing the last stream reference. The large-stream test reuses the existing 6.6 KB `highgui/video/sample_23976fps.mp4` fixture and moves its metadata into virtual free space; it does not allocate or add a multi-gigabyte asset.

Related reports: https://github.com/vllm-project/vllm/issues/46589 and https://github.com/vllm-project/vllm/issues/35285. The affected stream interface was introduced in https://github.com/opencv/opencv/pull/25584. Searches for open PythonStreamReader / Python seek fixes did not find another PR addressing this issue.

### Validation

Built unmodified and patched OpenCV from `4.x` at `38af4e35d7e6e001fa89c26b74a24232375afc1e`, using CMake/Ninja with `BUILD_LIST=core,imgproc,imgcodecs,videoio,python3` and FFmpeg enabled.

Environment: Linux aarch64, GCC 13.3, CPython 3.12.3, NumPy 2.2.6, system FFmpeg 6.1.1.

- Added standalone C++ regression `Videoio.stream_capture_ffmpeg_read_exception` next to `stream_capture_ffmpeg`: an `IStreamReader` whose `read()` throws is exercised, and `open()` returns false with `isOpened() == false`. It reuses the neighbouring backend/plugin ABI/API skips and needs neither Python bindings nor video fixtures.
- Built `opencv_test_videoio` with `BUILD_TESTS=ON` and `BUILD_LIST=core,imgproc,imgcodecs,videoio,highgui,ts,python3`. The C++ regression passed with both test-data environment variables unset. With the same test binary loading unpatched `38af4e3` libraries, opening the stream hung until an external 5-second timeout terminated it (exit 124); patched libraries completed immediately. Disabling FFmpeg verified the backend skip.
- Patched `modules/videoio/misc/python/test/test_videoio.py -v`: **8 tests passed**, including all eight invalid-callback subcases.
- Each of the four new test methods, run in a separate process against the unmodified source build, terminated with **SIGSEGV (-11)**. The four existing methods passed against that build.
- vLLM main `c07d58dc82d75f7d1a947b3264b460384ec3e18d`: the unmodified `OpenCVVideoBackendMixin` class was extracted and executed on a generated, valid 2,147,549,184-byte MP4. Unmodified OpenCV segfaulted during open; patched OpenCV opened/decoded a frame, released the capture, and retrieved correct metadata (4 frames, 2 fps, 2 seconds).
- `git diff --check`: passed.

Example test command after configuring/building the Python module:

```sh
PYTHONPATH="$PWD/build/lib/python3:$PWD/modules/python/test" \
OPENCV_TEST_DATA_PATH=/path/to/opencv_extra/testdata \
python3 modules/videoio/misc/python/test/test_videoio.py -v
```

This is decoder-level validation; a full Qwen model server was not started. Windows, macOS and MSMF have not been validated locally.

Prepared with AI assistance (Codex); native builds and the reported tests were run locally.

### Pull Request Readiness Checklist

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV.
- [x] The PR is proposed to the proper branch (`4.x`).
- [x] There is a reference to the original bug report and related work.
- [x] Regression tests reuse existing opencv_extra data; no companion data PR is needed.
- [x] The patch builds with CMake. No public API is added.
2026-11-18 14:28:37 +03:00

158 lines
4.4 KiB
C++

#ifdef HAVE_OPENCV_VIDEOIO
typedef std::vector<VideoCaptureAPIs> vector_VideoCaptureAPIs;
typedef std::vector<VideoCapture> vector_VideoCapture;
template<> struct pyopencvVecConverter<cv::VideoCaptureAPIs>
{
static bool to(PyObject* obj, std::vector<cv::VideoCaptureAPIs>& value, const ArgInfo& info)
{
return pyopencv_to_generic_vec(obj, value, info);
}
static PyObject* from(const std::vector<cv::VideoCaptureAPIs>& value)
{
return pyopencv_from_generic_vec(value);
}
};
template<>
bool pyopencv_to(PyObject *o, std::vector<cv::VideoCaptureAPIs>& apis, const ArgInfo& info)
{
return pyopencvVecConverter<cv::VideoCaptureAPIs>::to(o, apis, info);
}
template<> bool pyopencv_to(PyObject* obj, cv::VideoCapture& stream, const ArgInfo& info)
{
Ptr<VideoCapture> * obj_getp = nullptr;
if (!pyopencv_VideoCapture_getp(obj, obj_getp))
return (failmsgp("Incorrect type of self (must be 'VideoCapture' or its derivative)") != nullptr);
stream = **obj_getp;
return true;
}
class PythonStreamReader : public cv::IStreamReader
{
public:
PythonStreamReader(PyObject* _obj = nullptr) : obj(_obj)
{
if (obj)
Py_INCREF(obj);
}
~PythonStreamReader()
{
PyEnsureGIL gil;
if (obj)
Py_DECREF(obj);
}
long long read(char* buffer, long long size) CV_OVERRIDE
{
if (!obj)
return 0;
PyEnsureGIL gil;
PySafeObject res(PyObject_CallMethod(obj, "read", "L", size));
if (!res)
{
PyErr_Clear();
CV_Error(cv::Error::StsError, "Python .read() call error");
}
char* src = NULL;
Py_ssize_t len = 0;
if (PyBytes_AsStringAndSize(res, &src, &len) < 0)
{
PyErr_Clear();
CV_Error(cv::Error::StsError, "Python buffer access error");
}
CV_CheckLE(static_cast<size_t>(len), static_cast<size_t>(size), "Stream chunk size should be less or equal than requested size");
std::memcpy(buffer, src, static_cast<size_t>(len));
return len;
}
long long seek(long long offset, int way) CV_OVERRIDE
{
if (!obj)
return 0;
PyEnsureGIL gil;
PySafeObject res(PyObject_CallMethod(obj, "seek", "Li", offset, way));
if (!res)
{
PyErr_Clear();
CV_Error(cv::Error::StsError, "Python .seek() call error");
}
long long pos = PyLong_AsLongLong(res);
if (PyErr_Occurred())
{
PyErr_Clear();
CV_Error(cv::Error::StsError, "Python .seek() result => long long conversion error");
}
return pos;
}
private:
PyObject* obj;
};
template<>
bool pyopencv_to(PyObject* obj, Ptr<cv::IStreamReader>& p, const ArgInfo&)
{
if (!obj)
return false;
PyObject* ioModule = PyImport_ImportModule("io");
PyObject* type = PyObject_GetAttrString(ioModule, "BufferedIOBase");
Py_DECREF(ioModule);
bool isValidPyType = PyObject_IsInstance(obj, type) == 1;
Py_DECREF(type);
if (!isValidPyType)
{
PyErr_SetString(PyExc_TypeError, "Input stream should be derived from io.BufferedIOBase");
return false;
}
if (!PyErr_Occurred()) {
p = makePtr<PythonStreamReader>(obj);
return true;
}
return false;
}
static PyObject* pycvVideoEnter(PyObject* self, PyObject* /*args*/, PyObject* /*kw*/) {
Py_INCREF(self);
return self;
}
static PyObject* pycvVideoCaptureExit(PyObject* self, PyObject* /*args*/, PyObject* /*kw*/) {
Ptr<cv::VideoCapture>* obj_getp = nullptr;
if (pyopencv_VideoCapture_getp(self, obj_getp) && obj_getp && *obj_getp) {
(*obj_getp)->release();
}
Py_RETURN_NONE;
}
static PyObject* pycvVideoWriterExit(PyObject* self, PyObject* /*args*/, PyObject* /*kw*/) {
Ptr<cv::VideoWriter>* obj_getp = nullptr;
if (pyopencv_VideoWriter_getp(self, obj_getp) && obj_getp && *obj_getp) {
(*obj_getp)->release();
}
Py_RETURN_NONE;
}
#define PYOPENCV_EXTRA_METHODS_VideoCapture \
{"__enter__", CV_PY_FN_WITH_KW(pycvVideoEnter), "Context manager enter"}, \
{"__exit__", CV_PY_FN_WITH_KW(pycvVideoCaptureExit), "Context manager exit"},
#define PYOPENCV_EXTRA_METHODS_VideoWriter \
{"__enter__", CV_PY_FN_WITH_KW(pycvVideoEnter), "Context manager enter"}, \
{"__exit__", CV_PY_FN_WITH_KW(pycvVideoWriterExit), "Context manager exit"},
#endif // HAVE_OPENCV_VIDEOIO