videoio: add IStreamReader support to the Java bindings
Tier 2 easy cpp · local · real merged PR from opencv/opencv #27284
Ground-truth defects
The new Java stream-reader adapter stores the `JNIEnv*` it is handed in its constructor and reuses it from `read`, `seek` and its destructor. A `JNIEnv*` is only valid on the thread that obtained it, but these callbacks run on other threads: the generated Java wrapper's `finalize()` deletes the native object on the JVM finalizer thread, and a capture opened on one Java thread can be read from another. JNI calls then go through an env pointer that is invalid on the calling thread, which is undefined behavior and can abort or crash the JVM.
The change under review
diff
@@ -65,6 +65,7 @@ type_dict = { "char" : { "j_type" : "char", "jn_type" : "char", "jni_type" : "jchar", "suffix" : "C" }, "int" : { "j_type" : "int", "jn_type" : "int", "jni_type" : "jint", "suffix" : "I" }, "long" : { "j_type" : "int", "jn_type" : "int", "jni_type" : "jint", "suffix" : "I" }, + "long long" : { "j_type" : "long", "jn_type" : "long", "jni_type" : "jlong", "suffix" : "J" }, "float" : { "j_type" : "float", "jn_type" : "float", "jni_type" : "jfloat", "suffix" : "F" }, "double" : { "j_type" : "double", "jn_type" : "double", "jni_type" : "jdouble", "suffix" : "D" }, "size_t" : { "j_type" : "long", "jn_type" : "long", "jni_type" : "jlong", "suffix" : "J" }, @@ -89,6 +90,13 @@ type_dict = { 'v_type': 'string', 'j_import': 'java.lang.String' }, + "byte[]": { + "j_type" : "byte[]", + "jn_type": "byte[]", + "jni_type": "jbyteArray", + "jni_name": "n_%(n)s", + "jni_var": "char* n_%(n)s = reinterpret_cast<char*>(env->GetByteArrayElements(%(n)s, NULL))", + }, } # Defines a rule to add extra prefixes for names from specific namespaces. @@ -511,14 +519,14 @@ class JavaWrapperGenerator(object): if classinfo.base: classinfo.addImports(classinfo.base) - type_dict.setdefault("Ptr_"+name, {}).update( - { "j_type" : classinfo.jname, - "jn_type" : "long", "jn_args" : (("__int64", ".getNativeObjAddr()"),), - "jni_name" : "*((Ptr<"+classinfo.fullNameCPP()+">*)%(n)s_nativeObj)", "jni_type" : "jlong", - "suffix" : "J", - "j_import" : "org.opencv.%s.%s" % (self.module, classinfo.jname) + if ("Ptr_"+name) not in type_dict: + type_dict["Ptr_"+name] = { + "j_type" : classinfo.jname, + "jn_type" : "long", "jn_args" : (("__int64", ".getNativeObjAddr()"),), + "jni_name" : "*((Ptr<"+classinfo.fullNameCPP()+">*)%(n)s_nativeObj)", "jni_type" : "jlong", + "suffix" : "J", + "j_import" : "org.opencv.%s.%s" % (self.module, classinfo.jname) } - ) logging.info('ok: class %s, name: %s, base: %s', classinfo, name, classinfo.base) def add_const(self, decl, enumType=None): # [ "const cname", val, [], [] ] @@ -182,6 +182,29 @@ struct PyOpenCV_Converter } }; +// There is conflict between "long long" and "int64". +// They are the same type on some 32-bit platforms. +template<typename T> +struct PyOpenCV_Converter + < T, typename std::enable_if< std::is_same<long long, T>::value && !std::is_same<long long, int64>::value >::type > +{ + static inline PyObject* from(const long long& value) + { + return PyLong_FromLongLong(value); + } + + static inline bool to(PyObject* obj, long long& value, const ArgInfo& info) + { + CV_UNUSED(info); + if(!obj || obj == Py_None) + return true; + else if(PyLong_Check(obj)) + value = PyLong_AsLongLong(obj); + else + return false; + return value != (long long)-1 || !PyErr_Occurred(); + } +}; // --- uchar template<> bool pyopencv_to(PyObject* obj, uchar& value, const ArgInfo& info); @@ -190,6 +190,8 @@ class CppHeaderParser(object): angle_stack[-1] += 1 elif arg_type == "struct": arg_type += " " + w + elif prev_w in ["signed", "unsigned", "short", "long"] and w in ["char", "short", "int", "long"]: + arg_type += " " + w elif arg_type and arg_type != "~": arg_name = " ".join(word_list[wi:]) break @@ -28,6 +28,7 @@ _PREDEFINED_TYPES = ( PrimitiveTypeNode.int_("uint32_t"), PrimitiveTypeNode.int_("size_t"), PrimitiveTypeNode.int_("int64_t"), + PrimitiveTypeNode.int_("long long"), PrimitiveTypeNode.float_("float"), PrimitiveTypeNode.float_("double"), PrimitiveTypeNode.bool_("bool"), @@ -727,7 +727,7 @@ public: virtual ~IStreamReader(); /** @brief Read bytes from stream */ - virtual long long read(char* buffer, long long size) = 0; + CV_WRAP virtual long long read(char* buffer, long long size) = 0; /** @brief Sets the stream position * @@ -736,7 +736,7 @@ public: * * @see fseek */ - virtual long long seek(long long offset, int origin) = 0; + CV_WRAP virtual long long seek(long long offset, int origin) = 0; }; class IVideoCapture; new file mode 100644 @@ -0,0 +1 @@ +misc/java/src/cpp/videoio_converters.hpp new file mode 100644 @@ -0,0 +1,23 @@ +{ + "func_arg_fix" : { + "read": { "buffer": {"ctype" : "byte[]"} } + }, + "type_dict": { + "Ptr_IStreamReader": { + "j_type": "IStreamReader", + "jn_type": "IStreamReader", + "jni_name": "n_%(n)s", + "jni_type": "jobject", + "jni_var": "auto n_%(n)s = makePtr<JavaStreamReader>(env, source)", + "j_import": "org.opencv.videoio.IStreamReader" + }, + "vector_VideoCaptureAPIs": { + "j_type": "List<Integer>", + "jn_type": "List<Integer>", + "jni_type": "jobject", + "jni_var": "std::vector< cv::VideoCaptureAPIs > %(n)s", + "suffix": "Ljava_util_List", + "v_type": "vector_VideoCaptureAPIs" + } + } +} new file mode 100644 @@ -0,0 +1,54 @@ +#include "videoio_converters.hpp" + +JavaStreamReader::JavaStreamReader(JNIEnv* _env, jobject _obj) : env(_env) +{ + obj = env->NewGlobalRef(_obj); + jclass cls = env->GetObjectClass(obj); + m_read = env->GetMethodID(cls, "read", "([BJ)J"); + m_seek = env->GetMethodID(cls, "seek", "(JI)J"); +} + +JavaStreamReader::~JavaStreamReader() +{ + env->DeleteGlobalRef(obj); +} + +long long JavaStreamReader::read(char* buffer, long long size) +{ + if (!m_read) + return 0; + jbyteArray jBuffer = env->NewByteArray(static_cast<jsize>(size)); + if (!jBuffer) + return 0; + jlong res = env->CallLongMethod(obj, m_read, jBuffer, size); + env->GetByteArrayRegion(jBuffer, 0, static_cast<jsize>(size), reinterpret_cast<jbyte*>(buffer)); + env->DeleteLocalRef(jBuffer); + return res; +} + +long long JavaStreamReader::seek(long long offset, int way) +{ + if (!m_seek) + return 0; + return env->CallLongMethod(obj, m_seek, offset, way); +} + +// Same as dnn::vector_Target_to_List +jobject vector_VideoCaptureAPIs_to_List(JNIEnv* env, std::vector<cv::VideoCaptureAPIs>& vs) +{ + static jclass juArrayList = ARRAYLIST(env); + static jmethodID m_create = CONSTRUCTOR(env, juArrayList); + jmethodID m_add = LIST_ADD(env, juArrayList); + + static jclass jInteger = env->FindClass("java/lang/Integer"); + static jmethodID m_create_Integer = env->GetMethodID(jInteger, "<init>", "(I)V"); + + jobject result = env->NewObject(juArrayList, m_create, vs.size()); + for (size_t i = 0; i < vs.size(); ++i) + { + jobject element = env->NewObject(jInteger, m_create_Integer, vs[i]); + env->CallBooleanMethod(result, m_add, element); + env->DeleteLocalRef(element); + } + return result; +} new file mode 100644 @@ -0,0 +1,25 @@ +#ifndef VIDEOIO_CONVERTERS_HPP +#define VIDEOIO_CONVERTERS_HPP + +#include <jni.h> +#include "opencv_java.hpp" +#include "opencv2/core.hpp" +#include "opencv2/videoio/videoio.hpp" + +class JavaStreamReader : public cv::IStreamReader +{ +public: + JavaStreamReader(JNIEnv* env, jobject obj); + ~JavaStreamReader(); + long long read(char* buffer, long long size) CV_OVERRIDE; + long long seek(long long offset, int way) CV_OVERRIDE; + +private: + JNIEnv* env; + jobject obj; + jmethodID m_read, m_seek; +}; + +jobject vector_VideoCaptureAPIs_to_List(JNIEnv* env, std::vector<cv::VideoCaptureAPIs>& vs); + +#endif
Leaderboard for this case
easy · 9 of 9 bots fully caught it (100% solve rate) · 100% avg coverage.
| # | Bot | Result | Caught | Coverage | Findings | False alarms |
|---|---|---|---|---|---|---|
| 1 | cursor | solved | 1/1 | 100.0% | 3 | 0 |
| 2 | Drape (Review) | solved | 1/1 | 100.0% | 5 | 0 |
| 3 | greptile | solved | 1/1 | 100.0% | 3 | 0 |
| 4 | Mjolnir (Opus 5.5) | solved | 1/1 | 100.0% | 6 | 0 |
| 5 | Mjolnir (Sonnet 5.5) | solved | 1/1 | 100.0% | 3 | 0 |
| 6 | qodo | solved | 1/1 | 100.0% | 3 | 0 |
| 7 | Drape (Deep Review) | solved | 1/1 | 100.0% | 7 | 1 |
| 8 | Cubic | solved | 1/1 | 100.0% | 8 | 1 |
| 9 | Claude Code (Opus 5.5) | solved | 1/1 | 100.0% | 5 | 1 |
Bot results
Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | exact |
The finding says open() names its parameter `stream`, but the header names it `source`, the same as the constructor. So the hardcoded `source` resolves in both generated wrappers. [invalid: contradiction] [consensus 3/3: invalid=3]
The new read() calls GetByteArrayRegion and DeleteLocalRef right after CallLongMethod with no ExceptionCheck. It copies the full `size` whatever the result was, and seek() also returns the call result without checking for an exception. [grounded: tree modules/videoio/misc/java/src/cpp/videoio_converters.cpp] [consensus 3/3: valid=3]
The new byte[] type mapping gets the array elements but no matching ReleaseByteArrayElements is ever generated. The elements leak or stay pinned, and if the JVM handed back a copy, the data written is never copied back to the Java array. [grounded: diff] [consensus 3/3: valid=3]
The parser behaviour does change, but a grep of wrapped declarations finds only the new `long long` ones; no existing CV_WRAP/CV_PROP uses `unsigned int` and similar types. Under the old parsing such declarations would also have produced a broken arg name, so a real break is unproven. [uncertain: no evidence quoted] [consensus 3/3: uncertain=3]
raw comments (5)
The `jni_var` for `Ptr_IStreamReader` hardcodes the JNI argument name as `source` (`makePtr<JavaStreamReader>(env, source)`) instead of using `%(n)s`. That works for `VideoCapture(const Ptr<IStreamReader>& source, ...)`. But `VideoCapture::open(const Ptr<IStreamReader>& stream, ...)` names the parameter `stream` (videoio.hpp:893), so the generated JNI wrapper for `open` refers to an undeclared identifier `source` and the Java bindings fail to compile. It should be `makePtr<JavaStreamReader>(env, %(n)s)`.
`JavaStreamReader` keeps the `JNIEnv*` it receives in the constructor and uses it later in `read`, `seek` and the destructor. A `JNIEnv` is only valid on the thread that created it. The reader is held by the capture backend through a `Ptr`, so it can be used or destroyed on another thread. For example, the VideoCapture may be released by the GC/finalizer thread or by a user worker thread, and `DeleteGlobalRef` or `CallLongMethod` then runs with the wrong env, which is undefined behaviour and usually crashes the JVM. It should store a `JavaVM*` (from `GetJavaVM`) and call `AttachCurrentThread`/`GetEnv` on each call.
There is no `ExceptionCheck` after `CallLongMethod`. If the Java `read()` throws, the code still calls `GetByteArrayRegion` and `DeleteLocalRef` with an exception pending, which JNI does not allow. It also returns a garbage result to FFmpeg instead of an error. `seek()` has the same problem. The code also copies the full `size` bytes regardless of `res`. After an exception it should clear or propagate it and return -1/0.
The new `byte[]` type takes the array with `GetByteArrayElements` but never calls `ReleaseByteArrayElements`. Each call to the generated `IStreamReader.read` native wrapper leaks the buffer (or keeps it pinned). If the JVM handed back a copy, the bytes written by the C++ `read` are never copied back into the Java array, so the caller gets no data.
The parser now joins `signed`/`unsigned`/`short`/`long` with the following word for every header, not just `long long`. Existing declarations that use types like `unsigned int` or `unsigned char` will now parse to different type names (for example `unsigned int` instead of `unsigned`). This can silently change or break existing Python, Java and JS bindings and stubs that depended on the old type strings.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | exact |
The new byte[] type gets its elements with GetByteArrayElements, and the generator has no matching ReleaseByteArrayElements call. So each call leaks or pins the array, and writes into a copied buffer never reach the Java array. [grounded: diff] [consensus 5/5: valid=5]
FindClass returns a local reference, which becomes invalid once the native call returns. Caching it in a static without NewGlobalRef leaves a stale reference that later calls to NewObject use. [grounded: diff] [consensus 5/5: valid=5]
PyLong_Check accepts bool, which is a subclass of int, and rejects NumPy integer scalars, which are not PyLong objects. This applies on platforms where long long and int64 are different types. [grounded: diff] [consensus 5/5: valid=5]
With CV_WRAP, read() is exposed to Python with char* mapped to c_string, an input string. But IStreamReader is abstract and the shown code gives Python no way to get an instance to call read on, so it is unclear whether the memory corruption can actually happen. [uncertain: no evidence quoted] [consensus 2/5: uncertain=2, valid=2, invalid=1]
The new branch builds the type 'unsigned char', and the existing '*' handling then produces 'unsigned c_string'. Before the change this input was already parsed wrongly, just differently, so the impact is low. [grounded: tree modules/python/src2/hdr_parser.py] [consensus 5/5: valid=5]
The missing <vector> include is a style point; the header gets std::vector through opencv2/core.hpp and compiles. [consensus 5/5: minor=5]
Every current Ptr<IStreamReader> parameter is named 'source', and the JNI parameter has the same name, so the generated code is correct today. The breakage only happens if a parameter with a different name is added later. [invalid: contradiction] [consensus 4/5: invalid=4, minor=1]
raw comments (9)
<!-- cubic:v=de33fc5c-3515-4d8f-b074-699976b27185 -->
<!-- cubic:review-run=43251a1f-8562-5b89-87fd-b927d2a09dc1 -->
<!-- metadata:{"confidence":10} -->
P1: When the JVM returns a copy from `GetByteArrayElements`, generated `byte[]` wrappers never release it. `IStreamReader.read` can therefore lose bytes written to the Java buffer and leak or pin one array per call; add post-call cleanup with mode `0`, including exception paths.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At modules/java/generator/gen_java.py, line 98:
<comment>When the JVM returns a copy from `GetByteArrayElements`, generated `byte[]` wrappers never release it. `IStreamReader.read` can therefore lose bytes written to the Java buffer and leak or pin one array per call; add post-call cleanup with mode `0`, including exception paths.</comment>
<file context>
@@ -89,6 +90,13 @@ def checkFileRemap(path):
+ "jn_type": "byte[]",
+ "jni_type": "jbyteArray",
+ "jni_name": "n_%(n)s",
+ "jni_var": "char* n_%(n)s = reinterpret_cast<char*>(env->GetByteArrayElements(%(n)s, NULL))",
+ },
}
</file context>
```
</details>
<!-- cubic:v=92764b69-05f9-4f6f-a03f-1b5625020781 -->
<!-- cubic:review-run=43251a1f-8562-5b89-87fd-b927d2a09dc1 -->
<!-- metadata:{"confidence":8} -->
P1: When a `VideoCapture` is used or released from a different Java thread, this cached `JNIEnv*` is invalid because `JNIEnv` is thread-local. Store the `JavaVM*` instead and obtain the current thread’s `JNIEnv*` for each callback and cleanup operation.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At modules/videoio/misc/java/src/cpp/videoio_converters.cpp, line 3:
<comment>When a `VideoCapture` is used or released from a different Java thread, this cached `JNIEnv*` is invalid because `JNIEnv` is thread-local. Store the `JavaVM*` instead and obtain the current thread’s `JNIEnv*` for each callback and cleanup operation.</comment>
<file context>
@@ -0,0 +1,54 @@
+#include "videoio_converters.hpp"
+
+JavaStreamReader::JavaStreamReader(JNIEnv* _env, jobject _obj) : env(_env)
+{
+ obj = env->NewGlobalRef(_obj);
</file context>
```
</details>
<!-- cubic:v=132e5468-7473-4b10-92e9-d84558c473cd -->
<!-- cubic:review-run=43251a1f-8562-5b89-87fd-b927d2a09dc1 -->
<!-- metadata:{"confidence":10} -->
P1: On the second and later invocation, `jInteger` is a stale local JNI reference and `NewObject` can abort with an invalid-reference error. Promote the class reference to a global reference before caching it.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At modules/videoio/misc/java/src/cpp/videoio_converters.cpp, line 43:
<comment>On the second and later invocation, `jInteger` is a stale local JNI reference and `NewObject` can abort with an invalid-reference error. Promote the class reference to a global reference before caching it.</comment>
<file context>
@@ -0,0 +1,54 @@
+ static jmethodID m_create = CONSTRUCTOR(env, juArrayList);
+ jmethodID m_add = LIST_ADD(env, juArrayList);
+
+ static jclass jInteger = env->FindClass("java/lang/Integer");
+ static jmethodID m_create_Integer = env->GetMethodID(jInteger, "<init>", "(I)V");
+
</file context>
```
</details>
```suggestion
static jclass jInteger = static_cast<jclass>(env->NewGlobalRef(env->FindClass("java/lang/Integer")));
```
<!-- cubic:v=e7eb2b17-7b5e-4c25-8f8a-f7d48d584616 -->
<!-- cubic:review-run=43251a1f-8562-5b89-87fd-b927d2a09dc1 -->
<!-- metadata:{"confidence":9} -->
P2: When a Python 2 `int` or NumPy integer is passed to a wrapped `long long` parameter, this check rejects it; on Python 3 it also accepts `bool`. Use the existing integer-scalar predicate and reject `isBool`, matching the `int64` converter.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At modules/python/src2/cv2_convert.hpp, line 201:
<comment>When a Python 2 `int` or NumPy integer is passed to a wrapped `long long` parameter, this check rejects it; on Python 3 it also accepts `bool`. Use the existing integer-scalar predicate and reject `isBool`, matching the `int64` converter.</comment>
<file context>
@@ -182,6 +182,29 @@ struct PyOpenCV_Converter
+ CV_UNUSED(info);
+ if(!obj || obj == Py_None)
+ return true;
+ else if(PyLong_Check(obj))
+ value = PyLong_AsLongLong(obj);
+ else
</file context>
```
</details>
```suggestion
else if(!isBool(obj) && PyArray_IsIntegerScalar(obj))
```
<!-- cubic:v=8d720268-7c40-4be1-9adb-9e37a6407be1 -->
<!-- cubic:review-run=43251a1f-8562-5b89-87fd-b927d2a09dc1 -->
<!-- metadata:{"confidence":7} -->
P2: Adding CV_WRAP to `read()` also exposes it in the Python bindings, where the generated signature treats `buffer` as an input. hdr_parser.py:168 maps `char*` to `c_string`, and gen2.py's simple_argtype_mapping turns `c_string` into a `char*` input formatted as `str`, so Python sees `read(buffer: str, size: int) -> int`. But the C++ method *writes* `size` bytes into `buffer` (the Java bridge in `videoio_converters.cpp` even copies them back out of the jbyteArray), so a Python caller passes a Python-owned immutable string and the bytes read are written into Python memory — data is lost at best, interpreter memory is corrupted at worst. The Java binding handles this buffer via gen_dict.json's `func_arg_fix`/byte[] mapping, but nothing equivalent exists for Python. Mark `buffer` as an output parameter (`CV_OUT`) with a Python converter exposing it as `bytearray`, or exclude `read` (and `seek`) from the generated Python bindings while keeping them wrapped for Java.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At modules/videoio/include/opencv2/videoio.hpp, line 730:
<comment>Adding CV_WRAP to `read()` also exposes it in the Python bindings, where the generated signature treats `buffer` as an input. hdr_parser.py:168 maps `char*` to `c_string`, and gen2.py's simple_argtype_mapping turns `c_string` into a `char*` input formatted as `str`, so Python sees `read(buffer: str, size: int) -> int`. But the C++ method *writes* `size` bytes into `buffer` (the Java bridge in `videoio_converters.cpp` even copies them back out of the jbyteArray), so a Python caller passes a Python-owned immutable string and the bytes read are written into Python memory — data is lost at best, interpreter memory is corrupted at worst. The Java binding handles this buffer via gen_dict.json's `func_arg_fix`/byte[] mapping, but nothing equivalent exists for Python. Mark `buffer` as an output parameter (`CV_OUT`) with a Python converter exposing it as `bytearray`, or exclude `read` (and `seek`) from the generated Python bindings while keeping them wrapped for Java.</comment>
<file context>
@@ -727,7 +727,7 @@ class CV_EXPORTS_W IStreamReader
/** @brief Read bytes from stream */
- virtual long long read(char* buffer, long long size) = 0;
+ CV_WRAP virtual long long read(char* buffer, long long size) = 0;
/** @brief Sets the stream position
</file context>
```
</details>
<!-- cubic:v=b02cd264-08ac-41c0-b657-f916a71449ec -->
<!-- cubic:review-run=43251a1f-8562-5b89-87fd-b927d2a09dc1 -->
<!-- metadata:{"confidence":7} -->
P2: When the new branch accumulates `unsigned char`/`signed char`, a following `*` triggers the existing c_string conversion in the `w == "*"` branch, which does `arg_type[:-len("char")] + "c_string"`. With the accumulated multi-word type this yields "unsigned c_string"/"signed c_string" — an invalid type string that fails type resolution in gen2.py/gen_java.py (verified: parse_arg("unsigned char* p") returns type "unsigned c_string"). The conversion should only fire when the whole accumulated type is exactly "char", e.g. guard with `arg_type == "char"`; then "unsigned char*" correctly stays "unsigned char*".
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At modules/python/src2/hdr_parser.py, line 193:
<comment>When the new branch accumulates `unsigned char`/`signed char`, a following `*` triggers the existing c_string conversion in the `w == "*"` branch, which does `arg_type[:-len("char")] + "c_string"`. With the accumulated multi-word type this yields "unsigned c_string"/"signed c_string" — an invalid type string that fails type resolution in gen2.py/gen_java.py (verified: parse_arg("unsigned char* p") returns type "unsigned c_string"). The conversion should only fire when the whole accumulated type is exactly "char", e.g. guard with `arg_type == "char"`; then "unsigned char*" correctly stays "unsigned char*".</comment>
<file context>
@@ -190,6 +190,8 @@ def parse_arg(self, arg_str, argno):
angle_stack[-1] += 1
elif arg_type == "struct":
arg_type += " " + w
+ elif prev_w in ["signed", "unsigned", "short", "long"] and w in ["char", "short", "int", "long"]:
+ arg_type += " " + w
elif arg_type and arg_type != "~":
</file context>
```
</details>
<!-- cubic:v=9a39ab0d-5114-46d2-a7f0-8ab1d51dae3d -->
<!-- cubic:review-run=43251a1f-8562-5b89-87fd-b927d2a09dc1 -->
<!-- metadata:{"confidence":9} -->
P3: The header uses std::vector but never includes <vector>, relying on it being pulled in transitively by opencv2/videoio.hpp. It compiles today, but the header should include what it uses so it stays self-contained if the include chain changes.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At modules/videoio/misc/java/src/cpp/videoio_converters.hpp, line 23:
<comment>The header uses std::vector but never includes <vector>, relying on it being pulled in transitively by opencv2/videoio.hpp. It compiles today, but the header should include what it uses so it stays self-contained if the include chain changes.</comment>
<file context>
@@ -0,0 +1,25 @@
+ jmethodID m_read, m_seek;
+};
+
+jobject vector_VideoCaptureAPIs_to_List(JNIEnv* env, std::vector<cv::VideoCaptureAPIs>& vs);
+
+#endif
</file context>
```
</details>
<!-- cubic:v=37d873a6-6fbc-4208-9e2d-13a36436f0d6 -->
<!-- cubic:review-run=43251a1f-8562-5b89-87fd-b927d2a09dc1 -->
<!-- metadata:{"confidence":8} -->
P3: The `jni_var` template for `Ptr_IStreamReader` hardcodes the C++ parameter name `source` instead of referencing it via `%(n)s`. The generator substitutes only `%(n)s` occurrences (gen_java.py: `type_dict[a.ctype]["jni_var"] % {"n": a.name}`), so every other entry in type_dict/func_arg_fix uses `%(n)s` for argument references. It compiles today only because the two CV_WRAP functions that take `Ptr<IStreamReader>` happen to name their parameter `source` (`VideoCapture(const Ptr<IStreamReader>& source, ...)` and `open(const Ptr<IStreamReader>& source, ...)` in modules/videoio/include/opencv2/videoio.hpp). Any future function with a differently named parameter will silently generate broken JNI code (`makePtr<JavaStreamReader>(env, <othername>)`). Use `%(n)s` so the entry stays generic; it resolves to `source` today and keeps working for other parameter names.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At modules/videoio/misc/java/gen_dict.json, line 11:
<comment>The `jni_var` template for `Ptr_IStreamReader` hardcodes the C++ parameter name `source` instead of referencing it via `%(n)s`. The generator substitutes only `%(n)s` occurrences (gen_java.py: `type_dict[a.ctype]["jni_var"] % {"n": a.name}`), so every other entry in type_dict/func_arg_fix uses `%(n)s` for argument references. It compiles today only because the two CV_WRAP functions that take `Ptr<IStreamReader>` happen to name their parameter `source` (`VideoCapture(const Ptr<IStreamReader>& source, ...)` and `open(const Ptr<IStreamReader>& source, ...)` in modules/videoio/include/opencv2/videoio.hpp). Any future function with a differently named parameter will silently generate broken JNI code (`makePtr<JavaStreamReader>(env, <othername>)`). Use `%(n)s` so the entry stays generic; it resolves to `source` today and keeps working for other parameter names.</comment>
<file context>
@@ -0,0 +1,23 @@
+ "jn_type": "IStreamReader",
+ "jni_name": "n_%(n)s",
+ "jni_type": "jobject",
+ "jni_var": "auto n_%(n)s = makePtr<JavaStreamReader>(env, source)",
+ "j_import": "org.opencv.videoio.IStreamReader"
+ },
</file context>
```
</details>
```suggestion
"jni_var": "auto n_%(n)s = makePtr<JavaStreamReader>(env, %(n)s)",
```
<!-- cubic:review-summary:start -->
**8 issues found** across 9 files
<!-- cubic:review-summary:end -->
<details>
<summary>Prompt for AI agents (unresolved issues)</summary>
```text
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="modules/java/generator/gen_java.py">
<violation number="1" location="modules/java/generator/gen_java.py:98">
P1: When the JVM returns a copy from `GetByteArrayElements`, generated `byte[]` wrappers never release it. `IStreamReader.read` can therefore lose bytes written to the Java buffer and leak or pin one array per call; add post-call cleanup with mode `0`, including exception paths.</violation>
</file>
<file name="modules/python/src2/cv2_convert.hpp">
<violation number="1" location="modules/python/src2/cv2_convert.hpp:201">
P2: When a Python 2 `int` or NumPy integer is passed to a wrapped `long long` parameter, this check rejects it; on Python 3 it also accepts `bool`. Use the existing integer-scalar predicate and reject `isBool`, matching the `int64` converter.</violation>
</file>
<file name="modules/videoio/misc/java/src/cpp/videoio_converters.cpp">
<violation number="1" location="modules/videoio/misc/java/src/cpp/videoio_converters.cpp:3">
P1: When a `VideoCapture` is used or released from a different Java thread, this cached `JNIEnv*` is invalid because `JNIEnv` is thread-local. Store the `JavaVM*` instead and obtain the current thread’s `JNIEnv*` for each callback and cleanup operation.</violation>
<violation number="2" location="modules/videoio/misc/java/src/cpp/videoio_converters.cpp:43">
P1: On the second and later invocation, `jInteger` is a stale local JNI reference and `NewObject` can abort with an invalid-reference error. Promote the class reference to a global reference before caching it.</violation>
</file>
<file name="modules/videoio/misc/java/src/cpp/videoio_converters.hpp">
<violation number="1" location="modules/videoio/misc/java/src/cpp/videoio_converters.hpp:23">
P3: The header uses std::vector but never includes <vector>, relying on it being pulled in transitively by opencv2/videoio.hpp. It compiles today, but the header should include what it uses so it stays self-contained if the include chain changes.</violation>
</file>
<file name="modules/videoio/include/opencv2/videoio.hpp">
<violation number="1" location="modules/videoio/include/opencv2/videoio.hpp:730">
P2: Adding CV_WRAP to `read()` also exposes it in the Python bindings, where the generated signature treats `buffer` as an input. hdr_parser.py:168 maps `char*` to `c_string`, and gen2.py's simple_argtype_mapping turns `c_string` into a `char*` input formatted as `str`, so Python sees `read(buffer: str, size: int) -> int`. But the C++ method *writes* `size` bytes into `buffer` (the Java bridge in `videoio_converters.cpp` even copies them back out of the jbyteArray), so a Python caller passes a Python-owned immutable string and the bytes read are written into Python memory — data is lost at best, interpreter memory is corrupted at worst. The Java binding handles this buffer via gen_dict.json's `func_arg_fix`/byte[] mapping, but nothing equivalent exists for Python. Mark `buffer` as an output parameter (`CV_OUT`) with a Python converter exposing it as `bytearray`, or exclude `read` (and `seek`) from the generated Python bindings while keeping them wrapped for Java.</violation>
</file>
<file name="modules/videoio/misc/java/gen_dict.json">
<violation number="1" location="modules/videoio/misc/java/gen_dict.json:11">
P3: The `jni_var` template for `Ptr_IStreamReader` hardcodes the C++ parameter name `source` instead of referencing it via `%(n)s`. The generator substitutes only `%(n)s` occurrences (gen_java.py: `type_dict[a.ctype]["jni_var"] % {"n": a.name}`), so every other entry in type_dict/func_arg_fix uses `%(n)s` for argument references. It compiles today only because the two CV_WRAP functions that take `Ptr<IStreamReader>` happen to name their parameter `source` (`VideoCapture(const Ptr<IStreamReader>& source, ...)` and `open(const Ptr<IStreamReader>& source, ...)` in modules/videoio/include/opencv2/videoio.hpp). Any future function with a differently named parameter will silently generate broken JNI code (`makePtr<JavaStreamReader>(env, <othername>)`). Use `%(n)s` so the entry stays generic; it resolves to `source` today and keeps working for other parameter names.</violation>
</file>
<file name="modules/python/src2/hdr_parser.py">
<violation number="1" location="modules/python/src2/hdr_parser.py:193">
P2: When the new branch accumulates `unsigned char`/`signed char`, a following `*` triggers the existing c_string conversion in the `w == "*"` branch, which does `arg_type[:-len("char")] + "c_string"`. With the accumulated multi-word type this yields "unsigned c_string"/"signed c_string" — an invalid type string that fails type resolution in gen2.py/gen_java.py (verified: parse_arg("unsigned char* p") returns type "unsigned c_string"). The conversion should only fire when the whole accumulated type is exactly "char", e.g. guard with `arg_type == "char"`; then "unsigned char*" correctly stays "unsigned char*".</violation>
</file>
```
</details>
<sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/108/ai_pr_review_github_delivery_a9f2948e3c5552f6c25225c5603b5ca6271c6c40d10464932c89b41c0e2e188b?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F108)</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_a9f2948e3c5552f6c25225c5603b5ca6271c6c40d10464932c89b41c0e2e188b:a5e186e87a6cd2762ec4589e7aab5a2a5a7f721e:43251a1f-8562-5b89-87fd-b927d2a09dc1 -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | exact |
The generator adds jni_var only to c_prologue and has no epilogue that releases the array. As a result, the generated read wrapper never calls ReleaseByteArrayElements. Any bytes written into a copied buffer are never committed back to the Java array, and the buffer leaks or stays pinned. [grounded: diff] [consensus 5/5: valid=5]
After CallLongMethod the code never calls ExceptionCheck. It then calls GetByteArrayRegion unconditionally, which JNI does not allow while an exception is pending. It also copies the full size whatever res is. The short-read copy stays in bounds, so it does little harm. The missing exception check is a real JNI misuse added by this new code. [grounded: diff] [consensus 5/5: valid=5]
raw comments (4)
### Cached JNIEnv used across threads
**High Severity**
<!-- DESCRIPTION START -->
`JavaStreamReader` stores the constructing `JNIEnv*` and later uses it in `read`, `seek`, and the destructor. A `JNIEnv` is valid only on the thread that created it, but `VideoCapture` can invoke the stream (and destroy the `Ptr`) on another thread, including a finalizer or a backend worker. Those calls use a stale environment and can abort the JVM.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: 2853e650-d42e-4c40-88d3-bc40c3909052 -->
<!-- LOCATIONS START
modules/videoio/misc/java/src/cpp/videoio_converters.hpp#L17-L18
modules/videoio/misc/java/src/cpp/videoio_converters.cpp#L2-L34
LOCATIONS END -->
<details>
<summary>Additional Locations (1)</summary>
- [`modules/videoio/misc/java/src/cpp/videoio_converters.cpp#L2-L34`](https://github.com/drape-io/crbench-cursor-2026-09/blob/91fa3776f62ff8faae6b580401cef5e680876539/modules/videoio/misc/java/src/cpp/videoio_converters.cpp#L2-L34)
</details>
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmFiN2UxZjgxLWVkMWMtNGYwMy05NzJjLWY1NTYyN2EzNTE2MCIsImVuY3J5cHRpb25LZXkiOiJyaHQ5aGp5X2JSOS1STy1QVGhGTHo4aFdscENGeDMzZ0o5ZElKTU5XQWtjIiwiYnJhbmNoIjoicHItZTg0YjlhOTViMyIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmFiN2UxZjgxLWVkMWMtNGYwMy05NzJjLWY1NTYyN2EzNTE2MCIsImVuY3J5cHRpb25LZXkiOiJyaHQ5aGp5X2JSOS1STy1QVGhGTHo4aFdscENGeDMzZ0o5ZElKTU5XQWtjIiwiYnJhbmNoIjoicHItZTg0YjlhOTViMyIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjEwOCwiY29tbWl0U2hhIjoiOTFmYTM3NzZmNjJmZjhmYWFlNmI1ODA0MDFjZWY1ZTY4MDg3NjUzOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 91fa3776f62ff8faae6b580401cef5e680876539. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
### Byte array elements never released
**High Severity**
<!-- DESCRIPTION START -->
The new `byte[]` mapping calls `GetByteArrayElements` in `jni_var` and never calls `ReleaseByteArrayElements`. Generated `IStreamReader.read` JNI therefore may not copy filled bytes back into the Java array and can leak or pin the buffer for the lifetime of the process.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: 5d36ca1c-ec7b-4b09-915e-6d6f0d4c3f77 -->
<!-- LOCATIONS START
modules/java/generator/gen_java.py#L92-L99
LOCATIONS END -->
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90Ojc4NDU3NDVhLTQ0NDUtNDhkNS05M2Y4LWZmYTFhOTE2MjZhNCIsImVuY3J5cHRpb25LZXkiOiJnQnVveEI2a2RPR1FzQ0k5ZGxCTmxZQ1BTRzFEQVJHMVNfeVFNb0hmTUM4IiwiYnJhbmNoIjoicHItZTg0YjlhOTViMyIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90Ojc4NDU3NDVhLTQ0NDUtNDhkNS05M2Y4LWZmYTFhOTE2MjZhNCIsImVuY3J5cHRpb25LZXkiOiJnQnVveEI2a2RPR1FzQ0k5ZGxCTmxZQ1BTRzFEQVJHMVNfeVFNb0hmTUM4IiwiYnJhbmNoIjoicHItZTg0YjlhOTViMyIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjEwOCwiY29tbWl0U2hhIjoiOTFmYTM3NzZmNjJmZjhmYWFlNmI1ODA0MDFjZWY1ZTY4MDg3NjUzOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 91fa3776f62ff8faae6b580401cef5e680876539. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
### Read copies unread buffer bytes
**Medium Severity**
<!-- DESCRIPTION START -->
`JavaStreamReader::read` always copies `size` bytes from the Java array after the callback, and it does not check for a pending exception. Short reads (the normal stream case) and errors still copy the full request; a thrown Java `read` leaves a pending exception and then performs more JNI calls.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: f7172134-37af-44f3-9764-914b6779d06a -->
<!-- LOCATIONS START
modules/videoio/misc/java/src/cpp/videoio_converters.cpp#L15-L26
LOCATIONS END -->
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90Ojg3OTgwYzNjLWU2OGItNDkyMy1iMTBhLWNhNjk5Mzk0MDJiZCIsImVuY3J5cHRpb25LZXkiOiJzM213VndITXpfWVBYSTRRbThibmlGZHllVnYzVFppUnlFLW1Zd2lJbV9ZIiwiYnJhbmNoIjoicHItZTg0YjlhOTViMyIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90Ojg3OTgwYzNjLWU2OGItNDkyMy1iMTBhLWNhNjk5Mzk0MDJiZCIsImVuY3J5cHRpb25LZXkiOiJzM213VndITXpfWVBYSTRRbThibmlGZHllVnYzVFppUnlFLW1Zd2lJbV9ZIiwiYnJhbmNoIjoicHItZTg0YjlhOTViMyIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjEwOCwiY29tbWl0U2hhIjoiOTFmYTM3NzZmNjJmZjhmYWFlNmI1ODA0MDFjZWY1ZTY4MDg3NjUzOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 91fa3776f62ff8faae6b580401cef5e680876539. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_REVIEW -->
Cursor Bugbot has reviewed your changes using default effort and found 3 potential issues.
<!-- BUGBOT_FIX_ALL -->
<a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTo3Y2ZjODkxZC0xYjBlLTQ1MGYtYWJlOC04NWFiYTA0Mzg5ZWQiLCJlbmNyeXB0aW9uS2V5IjoiN3QxSWpDN0RKc2RxdHBmZUo2ZTRLS29McW9vSlpsSTZBaGNPMEwzTDNvRSIsImJyYW5jaCI6InByLWU4NGI5YTk1YjMiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>
<!-- /BUGBOT_FIX_ALL -->
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN -->
<sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END -->
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 91fa3776f62ff8faae6b580401cef5e680876539. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | exact |
There is no ExceptionCheck after CallLongMethod. If the Java read() throws, GetByteArrayRegion is called while an exception is pending, which JNI does not allow, and the undefined result is returned as a byte count. [grounded: tree modules/videoio/misc/java/src/cpp/videoio_converters.cpp] [consensus 3/3: valid=3]
res comes from user Java code and is returned without being checked against size, so a negative value or one larger than size reaches the native caller. [grounded: tree modules/videoio/misc/java/src/cpp/videoio_converters.cpp] [consensus 3/3: valid=3]
The new byte[] mapping, which the read() buffer uses through func_arg_fix, never calls ReleaseByteArrayElements. The buffer leaks on every call, and native writes are lost when the JVM hands out a copy. [grounded: tree modules/java/generator/gen_java.py] [consensus 3/3: valid=3]
A null Java source becomes a null global ref and is passed to GetObjectClass with no check, which crashes natively. Java callers can pass null. [grounded: tree modules/videoio/misc/java/src/cpp/videoio_converters.cpp] [consensus 3/3: valid=3]
FindClass returns a local reference, and it is cached in a static without NewGlobalRef, unlike the ARRAYLIST macro. Later calls use a stale reference. [grounded: tree modules/videoio/misc/java/src/cpp/videoio_converters.cpp] [consensus 3/3: valid=3]
Both wrapped uses of Ptr<IStreamReader> (the constructor and open) name the argument `source`, so the hardcoded name generates correct code today. The failure only happens with a hypothetical future argument that has a different name. [invalid: contradiction] [consensus 3/3: invalid=3]
raw comments (7)
**Java exception from read() is ignored**
If the Java `read` throws, `GetByteArrayRegion` is still called with an exception pending and the undefined return value is passed back as a byte count. Unlike the Python reader, no error is raised. Call env->ExceptionCheck() after CallLongMethod; if it is set, clear it and return an error.
```
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:23 jlong res = env->CallLongMethod(obj, m_read, jBuffer, size);
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:24 env->GetByteArrayRegion(jBuffer, 0, static_cast<jsize>(size), reinterpret_cast<jbyte*>(buffer));
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:25 env->DeleteLocalRef(jBuffer);
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:26 return res;
modules/videoio/misc/python/pyopencv_videoio.hpp:62 bool hasPyReadError = PyErr_Occurred() != nullptr;
modules/videoio/misc/python/pyopencv_videoio.hpp:63 char* src = PyBytes_AsString(res);
modules/videoio/misc/python/pyopencv_videoio.hpp:64 size_t len = static_cast<size_t>(PyBytes_Size(res));
modules/videoio/misc/python/pyopencv_videoio.hpp:65 bool hasPyBytesError = PyErr_Occurred() != nullptr;
modules/videoio/misc/python/pyopencv_videoio.hpp:66 if (src && len <= static_cast<size_t>(size))
modules/videoio/misc/python/pyopencv_videoio.hpp:67 {
```
**read() result not checked against buffer size**
Whatever the Java `read` returns is passed straight to the caller, even when it is larger than `size` or negative. The Python reader checks `len <= size`. Reject results greater than `size`, and only copy `res` bytes.
```
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:23 jlong res = env->CallLongMethod(obj, m_read, jBuffer, size);
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:24 env->GetByteArrayRegion(jBuffer, 0, static_cast<jsize>(size), reinterpret_cast<jbyte*>(buffer));
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:25 env->DeleteLocalRef(jBuffer);
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:26 return res;
modules/videoio/misc/python/pyopencv_videoio.hpp:80 CV_CheckLE(len, static_cast<size_t>(size), "Stream chunk size should be less or equal than requested size");
```
**JNIEnv cached and reused on other threads**
`read`, `seek` and the destructor reuse the constructor's `JNIEnv*`. A JNIEnv only works on its own thread, and capture reads or the finalizer's delete can run on other threads. Store the `JavaVM*` and get or attach the current thread's env in each method.
```
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:3 JavaStreamReader::JavaStreamReader(JNIEnv* _env, jobject _obj) : env(_env)
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:4 {
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:5 obj = env->NewGlobalRef(_obj);
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:6 jclass cls = env->GetObjectClass(obj);
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:7 m_read = env->GetMethodID(cls, "read", "([BJ)J");
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:8 m_seek = env->GetMethodID(cls, "seek", "(JI)J");
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:9 }
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:11 JavaStreamReader::~JavaStreamReader()
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:12 {
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:13 env->DeleteGlobalRef(obj);
```
**byte[] arguments leak and never write back**
The new `byte[]` mapping calls `GetByteArrayElements` but never calls `ReleaseByteArrayElements`. The pinned or copied buffer leaks on every call, and bytes the native `read` writes never reach the Java array when the JVM handed out a copy. Add an epilogue that calls ReleaseByteArrayElements(%(n)s, (jbyte*)n_%(n)s, 0).
```
modules/java/generator/gen_java.py:93 "byte[]": {
modules/java/generator/gen_java.py:94 "j_type" : "byte[]",
modules/java/generator/gen_java.py:95 "jn_type": "byte[]",
modules/java/generator/gen_java.py:96 "jni_type": "jbyteArray",
modules/java/generator/gen_java.py:80 'jni_var': 'const char* utf_%(n)s = env->GetStringUTFChars(%(n)s, 0); std::string n_%(n)s( utf_%(n)s ? utf_%(n)s : "" ); env->ReleaseStringUTFChars(%(n)s, utf_%(n)s)',
modules/java/generator/gen_java.py:98 "jni_var": "char* n_%(n)s = reinterpret_cast<char*>(env->GetByteArrayElements(%(n)s, NULL))",
```
**Null Java stream reader crashes natively**
The `jni_var` passes the Java argument straight to `JavaStreamReader`, and its constructor calls `GetObjectClass` on it with no null check. Check for a null object, and throw or return an empty Ptr.
```
modules/videoio/misc/java/gen_dict.json:11 "jni_var": "auto n_%(n)s = makePtr<JavaStreamReader>(env, source)",
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:5 obj = env->NewGlobalRef(_obj);
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:6 jclass cls = env->GetObjectClass(obj);
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:7 m_read = env->GetMethodID(cls, "read", "([BJ)J");
```
**Integer class cached as a local reference**
`jInteger` stores the result of `FindClass` in a static without `NewGlobalRef`, so the cached class reference stops being valid once the first native call returns. Every later call then uses a dead reference. Wrap the FindClass result in NewGlobalRef.
```
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:44 static jmethodID m_create_Integer = env->GetMethodID(jInteger, "<init>", "(I)V");
modules/java/generator/src/cpp/opencv_java.hpp:30 #define ARRAYLIST(ENV) static_cast<jclass>(ENV->NewGlobalRef(ENV->FindClass("java/util/ArrayList")))
```
**Ptr_IStreamReader conversion hardcodes `source`**
The `jni_var` for `Ptr_IStreamReader` passes the literal name `source` instead of `%(n)s`. Any wrapped function whose stream argument has a different name will generate C++ that refers to the wrong variable or doesn't compile. Use `makePtr<JavaStreamReader>(env, %(n)s)`.
```
modules/videoio/misc/java/gen_dict.json:11 "jni_var": "auto n_%(n)s = makePtr<JavaStreamReader>(env, source)",
```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | off by one |
After CallLongMethod there is no ExceptionCheck. GetByteArrayRegion is then called while an exception may be pending, which JNI does not allow, and res is returned without being checked or clamped. This is new code. [grounded: tree modules/videoio/misc/java/src/cpp/videoio_converters.cpp] [consensus 3/3: valid=3]
The new converter accepts only PyLong, and bool is a PyLong subclass, so bool gets through. numpy integer scalars are rejected and no failmsg is set. The int64 converter in cv2_convert.cpp rejects bool and uses PyArray_IsIntegerScalar, so the two behave inconsistently. [grounded: diff] [consensus 3/3: valid=3]
The byte[] jni_var calls GetByteArrayElements but the generator never emits a matching ReleaseByteArrayElements. The elements leak or stay pinned, and if the JVM handed back a copy, writes to it are never copied back to the Java array. [grounded: tree modules/java/generator/gen_java.py] [consensus 3/3: valid=3]
The jni_var hardcodes source where it should use %(n)s. Both wrapped functions today name the parameter source, so the generated code compiles now; the failure only shows up for a differently named parameter. This is a latent issue. [grounded: tree modules/videoio/misc/java/gen_dict.json] [consensus 3/4: valid=3, invalid=1]
raw comments (5)
**Java exceptions ignored in stream read**
`read()` does not check for a pending Java exception after `CallLongMethod`. It also always copies `size` bytes back and returns `res` unchecked. Check ExceptionCheck() after the call, clear it, and return 0 or -1; clamp the result to the requested size.
```
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:19 return 0;
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:20 jbyteArray jBuffer = env->NewByteArray(static_cast<jsize>(size));
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:21 if (!jBuffer)
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:22 return 0;
```
**long long converter rejects numpy ints, accepts bool**
The new `long long` converter only accepts exact Python `PyLong` objects. The existing `int64` converter accepts any integer scalar, including numpy ints, and rejects bool. This one does the reverse and sets no error message. Mirror the int64 converter: reject bool, accept PyArray_IsIntegerScalar, and call failmsg on errors.
```
modules/python/src2/cv2_convert.hpp:196 static inline bool to(PyObject* obj, long long& value, const ArgInfo& info)
modules/python/src2/cv2_convert.hpp:197 {
modules/python/src2/cv2_convert.hpp:198 CV_UNUSED(info);
modules/python/src2/cv2_convert.hpp:199 if(!obj || obj == Py_None)
```
**Pinned Java byte array is never released**
The `byte[]` jni_var pins the Java array with `GetByteArrayElements` but nothing ever calls `ReleaseByteArrayElements`. Add a matching release after the native call, or use `GetByteArrayRegion` and `SetByteArrayRegion` into a buffer.
```
modules/java/generator/gen_java.py:93 "byte[]": {
modules/java/generator/gen_java.py:94 "j_type" : "byte[]",
modules/java/generator/gen_java.py:95 "jn_type": "byte[]",
modules/java/generator/gen_java.py:96 "jni_type": "jbyteArray",
```
**Cached JNIEnv reused across threads and calls**
`JavaStreamReader` stores the `JNIEnv*` from the constructing call and reuses it in `read`, `seek` and the destructor. A `JNIEnv*` is valid only on its own thread and for the duration of that native call. Cache `JavaVM*` and obtain a per-thread `JNIEnv` on every callback and in the destructor.
```
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:3 JavaStreamReader::JavaStreamReader(JNIEnv* _env, jobject _obj) : env(_env)
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:4 {
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:5 obj = env->NewGlobalRef(_obj);
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:6 jclass cls = env->GetObjectClass(obj);
```
**Stream reader conversion hardcodes parameter name**
The Ptr_IStreamReader jni_var hardcodes `source`, so any wrapped Ptr<IStreamReader> parameter with a different name generates code that does not compile. Today's two wrapped functions both use `source`. Use %(n)s instead.
```
modules/videoio/misc/java/gen_dict.json:5 "type_dict": {
modules/videoio/misc/java/gen_dict.json:6 "Ptr_IStreamReader": {
modules/videoio/misc/java/gen_dict.json:7 "j_type": "IStreamReader",
modules/videoio/misc/java/gen_dict.json:8 "jn_type": "IStreamReader",
```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | exact |
The new read() returns the Java callback's result without checking it against 0..size. A callback that returns more than size makes the caller treat bytes beyond its buffer as valid data. [grounded: tree modules/videoio/misc/java/src/cpp/videoio_converters.cpp] [consensus 3/3: valid=3]
FindClass returns a local reference. Storing it in a static without NewGlobalRef leaves it dangling after the first native call returns, and later calls pass it to NewObject. [grounded: tree modules/videoio/misc/java/src/cpp/videoio_converters.cpp] [consensus 3/3: valid=3]
raw comments (4)
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **JNI environment crosses threads**
`JavaStreamReader` retains the constructor thread's `JNIEnv*` and reuses it for callbacks and destruction. If the retained `VideoCapture` is later read or released from another Java thread, calls such as `NewByteArray`, `CallLongMethod`, and `DeleteGlobalRef` use an environment belonging to a different thread, which can crash or cause undefined behavior. Store the `JavaVM` and obtain or attach the current thread's environment for each operation instead.
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Read count exceeds buffer**
The Java callback's returned byte count is passed through without checking that it is between zero and `size`. If an `IStreamReader.read` implementation returns more bytes than fit in `jBuffer`, FFmpeg treats that value as the valid length of its `buf_size`-byte native buffer, allowing downstream code to read past the buffer. Validate the result before copying or returning it, as the Python stream adapter already does.
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Local class reference expires**
`jInteger` is cached as a static JNI local reference. That reference is valid only for the native invocation and thread that created it, but this converter is used by repeated backend-list calls. After the first invocation returns, later calls can pass an invalid class reference to `NewObject`, causing conversion failures or crashes. Promote the class to a global reference, as the code already does for `juArrayList`.
<!-- greptile_summary -->
<h2><a href="https://app.greptile.com/api/retrigger?id=66790249"><picture><source media="(prefers-color-scheme: dark)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/RetriggerDark.svg?v=2"><source media="(prefers-color-scheme: light)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2"><img alt="Retrigger" src="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2" align="right"></picture></a>Confidence Score: 2/5</h2>
The PR is not safe to merge until the new Java video-stream bridge handles JNI environments and references correctly and bounds callback byte counts.
<h2>Findings</h2>
1. <img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"> **JNI environment crosses threads** <a href="https://github.com/drape-io/crbench-greptile-2026-09/pull/108#discussion_r4059126906">▶</a>
2. <img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"> **Read count exceeds buffer** <a href="https://github.com/drape-io/crbench-greptile-2026-09/pull/108#discussion_r4059126910">▶</a>
3. <img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"> **Local class reference expires** <a href="https://github.com/drape-io/crbench-greptile-2026-09/pull/108#discussion_r4059126913">▶</a>
<h3>Summary</h3>
This PR extends Python and Java binding generation to support `long long`, exposes `IStreamReader` to Java, and adds Java converters for stream callbacks and video-backend lists.
- Adds multiword integer parsing and Python conversion/stub support.
- Adds custom Java mappings for stream readers and `VideoCaptureAPIs` vectors.
- Introduces a JNI-backed `JavaStreamReader` used by `VideoCapture`.
- The new JNI adapters require fixes for thread-local environment handling, callback length validation, and class-reference lifetime.
<details open><summary>Diagram</summary>
```mermaid
sequenceDiagram
participant J as Java application
participant JNI as Generated VideoCapture JNI
participant R as JavaStreamReader
participant F as FFmpeg AVIO
J->>JNI: VideoCapture(IStreamReader, ...)
JNI->>R: construct and retain Java callback
JNI->>F: "open with Ptr<IStreamReader>"
J->>JNI: read frame (possibly another thread)
JNI->>F: demux/read
F->>R: read(native buffer, size)
R->>J: read(byte[], size)
J-->>R: returned byte count
R-->>F: copied bytes and count
```
</details>
<sub>Reviews (1) · Last reviewed commit: ["Update modules/java/generator/gen\_java.p..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/a36219c9a51ea078cb0291db885ba06786584721)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | exact |
The new class stores the JNIEnv* from the constructing call. read, seek and the destructor use it later, possibly on other threads such as capture worker threads or the finalizer thread. JNIEnv is only valid on its own thread. [grounded: tree modules/videoio/misc/java/src/cpp/videoio_converters.cpp] [consensus 3/3: valid=3]
The byte[] mapping gets the elements but nothing in gen_func adds a matching ReleaseByteArrayElements. Each call leaks or pins the buffer, and writes are lost when the JVM returns a copy. [grounded: tree modules/java/generator/gen_java.py] [consensus 3/3: valid=3]
No ExceptionCheck runs after CallLongMethod. GetByteArrayRegion then runs with an exception pending, and the result is returned as if it were a normal read. [grounded: tree modules/videoio/misc/java/src/cpp/videoio_converters.cpp] [consensus 3/3: valid=3]
Same as finding 2: an exception from the Java callback is never checked, and JNI calls keep running with it pending. [grounded: tree modules/videoio/misc/java/src/cpp/videoio_converters.cpp] [consensus 3/3: valid=3]
Same as finding 1: the byte[] conversion has no release, so memory leaks and output data is lost when the JVM returns a copy. [grounded: tree modules/java/generator/gen_java.py] [consensus 3/3: valid=3]
raw comments (6)
[P1] JavaStreamReader caches a thread-local JNIEnv and uses it after the JNI call returns
The reader saves the `JNIEnv*` from the `VideoCapture(IStreamReader, ...)`/`open(...)` JNI call and later uses it in `read`, `seek` and the destructor. But the `Ptr‹IStreamReader›` lives inside the capture backend after that call returns. A `JNIEnv` is only valid on the thread it belongs to, so this is undefined behaviour (usually a JNI abort or a crash) in common cases: the capture is created on one thread and `read()`/`grab()` runs on another (typical on Android worker threads), or the capture is released or finalized on the GC/finalizer thread, where `DeleteGlobalRef` runs with the wrong env. The fix is to store the `JavaVM*` (`env-›GetJavaVM`) and get or attach the current thread's env in each callback and in the destructor.
[P2] The new `byte[]` type mapping pins/copies the array and never releases it
The `byte[]` `jni_var` calls `GetByteArrayElements`, but there is no matching `ReleaseByteArrayElements` in the epilogue, and the generator has no epilogue for this type at all. Every call of a generated wrapper that takes `byte[]` (the new `IStreamReader.read` native wrapper, selected through `func_arg_fix` in gen_dict.json) leaks the pinned or copied buffer. Also, when the JVM hands back a copy, the bytes the C++ side writes into `buffer` never reach the Java array, so the caller sees no data even though a byte count comes back.
[P3] Java exceptions thrown from `read`/`seek` are not checked
If the user's Java `read()` throws, `CallLongMethod` returns with an exception pending. The code then calls `GetByteArrayRegion`, which JNI does not allow while an exception is pending, and returns 0 as if it were a valid read. The pending exception also stays and fires later at some unrelated point in Java. Checking `env-›ExceptionCheck()` and returning an error before touching the array would avoid this (the same applies to `seek`).
[P1] JavaStreamReader keeps a JNIEnv* and uses it from other threads
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:3-14 The constructor saves the `JNIEnv*` of the thread that built the reader, and `read`, `seek` and the destructor all reuse it later. A `JNIEnv` is only valid on the thread it belongs to. The destructor runs when the owning `VideoCapture` frees its `Ptr‹IStreamReader›`, and that can happen on another thread: `VideoCapture.finalize()` runs on the Java finalizer thread, and `release()`/`delete` can be called from any thread. In that case `DeleteGlobalRef` is called through the wrong thread's env, which is undefined behavior and typically crashes the JVM. `read()`/`grab()` called from a different thread than the one that opened the capture has the same problem. The usual fix is to store the `JavaVM*` (from `env-›GetJavaVM`) and get or attach the current thread's env with `GetEnv`/`AttachCurrentThread` on each call.
[P2] Exceptions thrown by the Java read/seek callbacks are not handled
modules/videoio/misc/java/src/cpp/videoio_converters.cpp:23-24 If the user's Java `read(byte[], long)` throws, `CallLongMethod` returns 0 and leaves the exception pending. The code then calls `GetByteArrayRegion` and `DeleteLocalRef` anyway, and JNI does not allow most calls while an exception is pending. The backend also gets a normal-looking result, and the exception later surfaces in an unrelated Java call. `seek` has the same problem. The code should check `env-›ExceptionCheck()` right after each `CallLongMethod`, clear or describe the exception, and return an error value (e.g. -1/0) without touching the array.
[P2] The new `byte[]` argument conversion never releases the array, so data is lost and memory leaks
modules/java/generator/gen_java.py:93-99 The `byte[]` `jni_var` calls `GetByteArrayElements` but nothing calls `ReleaseByteArrayElements`. It is used for the output buffer of `IStreamReader.read`. When the JVM hands back a copy (common on HotSpot/ART), the bytes the native `read` writes never reach the Java array, so Java code calling the wrapped native `read` gets an unchanged buffer. Each call also leaks the copy, or leaves the array pinned. The array needs to be released with mode 0 after the call, for example through a post-call cleanup like the one other array types use.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | off by one |
The new class stores the constructor's JNIEnv* and reuses it in read/seek/destructor. A JNIEnv* is only valid on the thread that obtained it, so using the reader from another thread (or destroying it in a finalizer) is undefined behaviour. [grounded: tree modules/videoio/misc/java/src/cpp/videoio_converters.cpp] [consensus 3/3: valid=3]
The byte[] type entry acquires the array elements, but the generator emits no matching ReleaseByteArrayElements for it. The array leaks or stays pinned, and when the JVM made a copy, native writes in read() are never copied back to the Java array. [grounded: diff] [consensus 3/3: valid=3]
raw comments (3)
[P2] JNIEnv* cached across calls and threads
`JavaStreamReader` stores the `JNIEnv*` that was passed to the constructor and reuses it in `read()`, `seek()` and the destructor. A `JNIEnv*` is only valid on the thread that obtained it. It breaks if the reader is used from another thread. Examples are `VideoCapture.read()` called from a different Java or Android thread than the one that opened it, or the native object being released on the finalizer or another thread, where the destructor calls `DeleteGlobalRef`. In those cases the JNI calls are undefined behaviour and can crash the JVM. The code should keep a `JavaVM*` and obtain the env per call with `GetEnv`/`AttachCurrentThread`.
[P3] byte[] buffer pinned but never released
The new `byte[]` type_dict entry sets `jni_var` to `GetByteArrayElements(..., NULL)`. Nothing releases the array with `ReleaseByteArrayElements`, and no epilogue is emitted. The generated native wrapper for `IStreamReader.read(byte[] buffer, long size)` therefore leaks or pins the array. For a copy, data the native code writes into the buffer is never committed back to the Java array. The entry needs a matching release with mode 0 on the generated side, or use of the region APIs.
[P2] Cached `JNIEnv*` reused across calls and threads
`JavaStreamReader` stores the `JNIEnv*` from the JNI call that constructed it (`makePtr‹JavaStreamReader›(env, source)`). It then uses that pointer in `read()`, `seek()` and the destructor. A `JNIEnv*` is valid only on the thread it was obtained on. The reader outlives the constructor call: it is held by the `VideoCapture`, and the destructor runs when the native `VideoCapture` is released. In OpenCV's Java bindings that release can run on a finalizer or cleaner thread, or on a different thread from the one that opened or read the capture. In those cases `DeleteGlobalRef`, `CallLongMethod` and `GetByteArrayRegion` use a stale or foreign `JNIEnv*`, which is undefined behavior and can crash the JVM. The fix is to cache the `JavaVM*` and attach the current thread (`GetEnv` / `AttachCurrentThread`) whenever the reader needs an env.
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | exact |
The generator only adds jni_var to c_prologue, and nothing in gen_func emits a release for the byte[] type. So the array is never released (mode 0), which means native writes to a copied buffer never reach Java and the elements leak or stay pinned. [grounded: diff] [consensus 3/3: valid=3]
FindClass returns a local reference. Storing it in a function-level static without NewGlobalRef means later calls use a reference that is no longer valid. This is new code added by the change. [grounded: diff] [consensus 3/3: valid=3]
raw comments (5)
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
1\. Java buffers miss native reads <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
The new <b><i>byte[]</i></b> mapping obtains its native pointer with <b><i>GetByteArrayElements</i></b> but the generator
emits no matching <b><i>ReleaseByteArrayElements</i></b> after the C++ call. When JNI supplies a copied array,
<b><i>IStreamReader.read</i></b> writes only to that copy, so Java receives unchanged bytes and the unreleased
array storage may remain pinned or allocated.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
The `byte[]` conversion acquires array elements but never releases them, preventing guaranteed copy-back of native writes and leaking or pinning JNI resources.
## Fix Focus Areas
- modules/java/generator/gen_java.py[93-99]
- modules/java/generator/gen_java.py[1047-1110]
## Recommended Fix
Add argument epilogue support to the Java generator and configure `byte[]` arguments to call `ReleaseByteArrayElements` with mode `0` after the native method returns. Also handle a null result from `GetByteArrayElements` before invoking C++.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
2\. Cross-thread streams use invalid jni <code>🐞 Bug</code> <code>☼ Reliability</code>
<pre>
<b><i>JavaStreamReader</i></b> stores the constructor's <b><i>JNIEnv*</i></b> and later reuses it in <b><i>read</i></b>, <b><i>seek</i></b>, and
destruction, although that pointer belongs only to its originating thread. A capture retained in
native code can be operated or released from another Java or backend thread, where these JNI calls
have undefined behavior and can crash.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
`JavaStreamReader` retains a thread-local `JNIEnv*` for callbacks and destruction that may execute on another thread.
## Fix Focus Areas
- modules/videoio/misc/java/src/cpp/videoio_converters.hpp[12-20]
- modules/videoio/misc/java/src/cpp/videoio_converters.cpp[3-34]
## Recommended Fix
Store a `JavaVM*` obtained during construction instead of storing `JNIEnv*`. In every callback and in the destructor, obtain the current thread's environment through `GetEnv`, attach when necessary, perform the JNI operations, and detach only threads attached by the bridge.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
3\. Repeated queries use invalid class <code>🐞 Bug</code> <code>☼ Reliability</code>
<pre>
<b><i>vector_VideoCaptureAPIs_to_List</i></b> stores the local reference returned by <b><i>FindClass</i></b> in a static
<b><i>jclass</i></b>. That reference expires when the first native invocation returns, so later backend-list
queries pass an invalid class reference to <b><i>NewObject</i></b>.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
The converter caches a JNI local class reference across native invocations, although local references are valid only for their creating native frame.
## Fix Focus Areas
- modules/videoio/misc/java/src/cpp/videoio_converters.cpp[37-50]
## Recommended Fix
Convert the result of `FindClass("java/lang/Integer")` into a global reference before storing it statically, following the existing `ARRAYLIST(env)` pattern. Check class and method lookup failures before constructing list elements.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<h3>PR Summary by Qodo</h3>
Add Java IStreamReader bindings for VideoCapture
<code>✨ Enhancement</code> <code>🐞 Bug fix</code> <code>🕐 40+ Minutes</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<details>
<summary>AI Description</summary>
<dl>
<dd>
<br/>
><pre>
>• Exposes IStreamReader callbacks for Java-backed VideoCapture input streams.
>• Extends generators and parsers to handle long long and byte arrays.
>• Preserves custom pointer mappings and converts VideoCapture API lists for Java.
></pre>
</dd>
</dl>
</details>
<details>
<summary>Diagram</summary>
<dl>
<dd>
<br/>
```mermaid
sequenceDiagram
actor App as Java App
participant API as Java VideoCapture
participant JNI as Generated JNI
participant Capture as Native Capture
participant Adapter as Stream Adapter
participant Reader as Java Reader
App->>API: Open stream
API->>JNI: Pass reader
JNI->>Adapter: Create global adapter
JNI->>Capture: Open adapter
Capture->>Adapter: Read or seek
Adapter->>Reader: Invoke callback
Reader-->>Adapter: Return data
Adapter-->>Capture: Bytes or position
```
</dd>
</dl>
</details>
<details>
<summary>High-Level Assessment</summary>
<dl>
<dd>
<br/>
>The following are alternative approaches to this PR:
<details>
<summary><b>1. Use direct ByteBuffer callbacks</b></summary>
<dl>
<dd>
- ➕ Could avoid allocating and copying a byte array for every read
- ➕ Better suited to high-throughput video streams
- ➖ Requires more specialized generator and JNI mappings
- ➖ Exposes native-memory lifetime and bounds concerns to Java callers
- ➖ Would diverge from conventional Java byte-array APIs
</dd>
</dl>
</details>
>**Recommendation:** Keep the byte[]-based adapter because it integrates cleanly with generated bindings and presents a conventional Java interface. A direct ByteBuffer path should only be considered as a separate optimization after profiling demonstrates callback allocation or copying is a bottleneck.
</dd>
</dl>
</details>
<details>
<summary> Files changed (9) <code> +146 / -9 </code> </summary>
<dl>
<dd>
<br/>
<details>
<summary>Enhancement (5) <code> +97 / -9 </code></summary>
<dl>
<dd>
<details>
<summary>gen_java.py<code>Support 64-bit integers, byte arrays, and custom pointer mappings</code> <code>+15/-7</code></summary>
<br/>
>Support 64-bit integers, byte arrays, and custom pointer mappings
>
><pre>
>• Adds Java/JNI mappings for long long and byte[] values. Preserves module-defined Ptr mappings instead of overwriting them when wrapped classes are registered.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/108/files#diff-af32351bd78c431d8acc34ccc1ad279ff8ea649f0445582692a9a5051314e74b'>modules/java/generator/gen_java.py</a>
</details>
<details>
<summary>predefined_types.py<code>Recognize long long in generated Python stubs</code> <code>+1/-0</code></summary>
<br/>
>Recognize long long in generated Python stubs
>
><pre>
>• Registers long long as a predefined integer type so generated typing stubs resolve wrapped declarations correctly.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/108/files#diff-d7f280d2a075f044f0b9720fa39e3fff9a6346c3a8eccb0cf588f0b7e52a9f6b'>modules/python/src2/typing_stubs_generation/predefined_types.py</a>
</details>
<details>
<summary>videoio.hpp<code>Expose IStreamReader callbacks to binding generators</code> <code>+2/-2</code></summary>
<br/>
>Expose IStreamReader callbacks to binding generators
>
><pre>
>• Marks the read and seek virtual methods with CV_WRAP, enabling generated language bindings to represent stream-reader implementations.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/108/files#diff-702e7efcf6bd7a4c265fcdbc0cc4c4e47e8ea12325bf28d18524c194c9ab4759'>modules/videoio/include/opencv2/videoio.hpp</a>
</details>
<details>
<summary>videoio_converters.cpp<code>Implement Java stream callbacks and API list conversion</code> <code>+54/-0</code></summary>
<br/>
>Implement Java stream callbacks and API list conversion
>
><pre>
>• Implements the native IStreamReader adapter that retains a Java object and invokes its read and seek methods. Adds conversion from native VideoCaptureAPIs vectors to Java ArrayList<Integer>.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/108/files#diff-e8b5ff2b63f235f84ac7e9f9306eabc69fd39fe052a965742964fdc4b221927d'>modules/videoio/misc/java/src/cpp/videoio_converters.cpp</a>
</details>
<details>
<summary>videoio_converters.hpp<code>Declare the Java IStreamReader native adapter</code> <code>+25/-0</code></summary>
<br/>
>Declare the Java IStreamReader native adapter
>
><pre>
>• Defines JavaStreamReader as a cv::IStreamReader implementation with cached JNI callback handles. Declares the VideoCaptureAPIs list converter used by generated bindings.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/108/files#diff-09dd5a1b930e076b621002f4acd549799ee30ae3928d36c841812c1e642e85c9'>modules/videoio/misc/java/src/cpp/videoio_converters.hpp</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Bug fix (2) <code> +25 / -0 </code></summary>
<dl>
<dd>
<details>
<summary>cv2_convert.hpp<code>Add portable long long Python conversion</code> <code>+23/-0</code></summary>
<br/>
>Add portable long long Python conversion
>
><pre>
>• Adds a conditional converter using Python's signed 64-bit integer APIs. The type-trait guard avoids specialization conflicts where long long and int64 are aliases.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/108/files#diff-891deee8b0d86f2e05018a64d4402dda2e68ee3a3845d85118bb63efbbaf25d4'>modules/python/src2/cv2_convert.hpp</a>
</details>
<details>
<summary>hdr_parser.py<code>Parse multi-token integral type names</code> <code>+2/-0</code></summary>
<br/>
>Parse multi-token integral type names
>
><pre>
>• Keeps signed, unsigned, short, and long qualifiers together while parsing arguments, allowing declarations such as long long to be recognized correctly.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/108/files#diff-7f54bd4fb64a6fa4a8290dc77bae4ff0e300a9c904e98d7a2ad75731e37b42bf'>modules/python/src2/hdr_parser.py</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Other (2) <code> +24 / -0 </code></summary>
<dl>
<dd>
<details>
<summary>filelist_common<code>Register the videoio Java converter header</code> <code>+1/-0</code></summary>
<br/>
>Register the videoio Java converter header
>
><pre>
>• Adds the custom videoio converter header to the Java binding generation file list.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/108/files#diff-d77355725e322286a39a6eb6c787dbd47c5175515fa9b6dd55b6fb0aec602336'>modules/videoio/misc/java/filelist_common</a>
</details>
<details>
<summary>gen_dict.json<code>Configure Java videoio stream and enum conversions</code> <code>+23/-0</code></summary>
<br/>
>Configure Java videoio stream and enum conversions
>
><pre>
>• Maps read buffers to byte[] and converts Java IStreamReader objects into native JavaStreamReader instances. It also configures VideoCaptureAPIs vectors as Java integer lists.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/108/files#diff-a026c4beea462c783aeb4e5aee47ae47f56ee5d4c6e01501b1a954de001dff0a'>modules/videoio/misc/java/gen_dict.json</a>
</details>
</dd>
</dl>
</details>
</dd>
</dl>
</details>
<h3>Code Review by Qodo</h3>
<code>🐞 Bugs (3)</code> <code>📘 Rule violations (0)</code> <code>📜 Skill insights (0)</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<br/>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
<details>
<summary> 1. Java buffers miss native reads <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
>The new <b><i>byte[]</i></b> mapping obtains its native pointer with <b><i>GetByteArrayElements</i></b> but the generator
>emits no matching <b><i>ReleaseByteArrayElements</i></b> after the C++ call. When JNI supplies a copied array,
><b><i>IStreamReader.read</i></b> writes only to that copy, so Java receives unchanged bytes and the unreleased
>array storage may remain pinned or allocated.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[modules/java/generator/gen_java.py[98]](https://github.com/drape-io/crbench-qodo-2026-09/pull/108/files#diff-af32351bd78c431d8acc34ccc1ad279ff8ea649f0445582692a9a5051314e74bR98-R98)</code>
>
>```diff
>+ "jni_var": "char* n_%(n)s = reinterpret_cast<char*>(env->GetByteArrayElements(%(n)s, NULL))",
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>VideoIO remaps the writable <b><i>char*</i></b> argument to this new <b><i>byte[]</i></b> conversion, while the generated
>wrapper emits the acquisition before the C++ call without any release or copy-back afterward.
></pre>
>
> <code>[modules/videoio/misc/java/gen_dict.json[2-4]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3059d305c90b6bab83ac3b08a85aba5236e3b2e5/modules/videoio/misc/java/gen_dict.json/#L2-L4)</code>
> <code>[modules/videoio/include/opencv2/videoio.hpp[724-730]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3059d305c90b6bab83ac3b08a85aba5236e3b2e5/modules/videoio/include/opencv2/videoio.hpp/#L724-L730)</code>
> <code>[modules/java/generator/gen_java.py[1047-1059]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3059d305c90b6bab83ac3b08a85aba5236e3b2e5/modules/java/generator/gen_java.py/#L1047-L1059)</code>
> <code>[modules/java/generator/gen_java.py[1090-1110]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3059d305c90b6bab83ac3b08a85aba5236e3b2e5/modules/java/generator/gen_java.py/#L1090-L1110)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>The `byte[]` conversion acquires array elements but never releases them, preventing guaranteed copy-back of native writes and leaking or pinning JNI resources.
>
>## Fix Focus Areas
>- modules/java/generator/gen_java.py[93-99]
>- modules/java/generator/gen_java.py[1047-1110]
>
>## Recommended Fix
>Add argument epilogue support to the Java generator and configure `byte[]` arguments to call `ReleaseByteArrayElements` with mode `0` after the native method returns. Also handle a null result from `GetByteArrayElements` before invoking C++.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<details>
<summary> 2. Cross-thread streams use invalid JNI <code>🐞 Bug</code> <code>☼ Reliability</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
><b><i>JavaStreamReader</i></b> stores the constructor's <b><i>JNIEnv*</i></b> and later reuses it in <b><i>read</i></b>, <b><i>seek</i></b>, and
>destruction, although that pointer belongs only to its originating thread. A capture retained in
>native code can be operated or released from another Java or backend thread, where these JNI calls
>have undefined behavior and can crash.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[modules/videoio/misc/java/src/cpp/videoio_converters.hpp[R17-20]](https://github.com/drape-io/crbench-qodo-2026-09/pull/108/files#diff-09dd5a1b930e076b621002f4acd549799ee30ae3928d36c841812c1e642e85c9R17-R20)</code>
>
>```diff
>+private:
>+ JNIEnv* env;
>+ jobject obj;
>+ jmethodID m_read, m_seek;
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The adapter stores one environment pointer at construction and every later JNI operation uses it,
>while the native capture retains the stream beyond the creating call and invokes it through backend
>callbacks.
></pre>
>
> <code>[modules/videoio/misc/java/src/cpp/videoio_converters.cpp[3-13]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3059d305c90b6bab83ac3b08a85aba5236e3b2e5/modules/videoio/misc/java/src/cpp/videoio_converters.cpp/#L3-L13)</code>
> <code>[modules/videoio/misc/java/src/cpp/videoio_converters.cpp[16-34]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3059d305c90b6bab83ac3b08a85aba5236e3b2e5/modules/videoio/misc/java/src/cpp/videoio_converters.cpp/#L16-L34)</code>
> <code>[modules/videoio/src/cap_ffmpeg.cpp[125-154]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3059d305c90b6bab83ac3b08a85aba5236e3b2e5/modules/videoio/src/cap_ffmpeg.cpp/#L125-L154)</code>
> <code>[modules/videoio/src/backend_plugin.cpp[451-490]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3059d305c90b6bab83ac3b08a85aba5236e3b2e5/modules/videoio/src/backend_plugin.cpp/#L451-L490)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>`JavaStreamReader` retains a thread-local `JNIEnv*` for callbacks and destruction that may execute on another thread.
>
>## Fix Focus Areas
>- modules/videoio/misc/java/src/cpp/videoio_converters.hpp[12-20]
>- modules/videoio/misc/java/src/cpp/videoio_converters.cpp[3-34]
>
>## Recommended Fix
>Store a `JavaVM*` obtained during construction instead of storing `JNIEnv*`. In every callback and in the destructor, obtain the current thread's environment through `GetEnv`, attach when necessary, perform the JNI operations, and detach only threads attached by the bridge.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<br/>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
<details>
<summary> 3. Repeated queries use invalid class <code>🐞 Bug</code> <code>☼ Reliability</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
><b><i>vector_VideoCaptureAPIs_to_List</i></b> stores the local reference returned by <b><i>FindClass</i></b> in a static
><b><i>jclass</i></b>. That reference expires when the first native invocation returns, so later backend-list
>queries pass an invalid class reference to <b><i>NewObject</i></b>.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[modules/videoio/misc/java/src/cpp/videoio_converters.cpp[R43-44]](https://github.com/drape-io/crbench-qodo-2026-09/pull/108/files#diff-e8b5ff2b63f235f84ac7e9f9306eabc69fd39fe052a965742964fdc4b221927dR43-R44)</code>
>
>```diff
>+ static jclass jInteger = env->FindClass("java/lang/Integer");
>+ static jmethodID m_create_Integer = env->GetMethodID(jInteger, "<init>", "(I)V");
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The new converter exposes several repeatable registry APIs through one function, but unlike the
>ArrayList cache it saves <b><i>FindClass</i></b> directly without creating a global reference.
></pre>
>
> <code>[modules/videoio/misc/java/src/cpp/videoio_converters.cpp[37-50]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3059d305c90b6bab83ac3b08a85aba5236e3b2e5/modules/videoio/misc/java/src/cpp/videoio_converters.cpp/#L37-L50)</code>
> <code>[modules/java/generator/src/cpp/opencv_java.hpp[30-30]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3059d305c90b6bab83ac3b08a85aba5236e3b2e5/modules/java/generator/src/cpp/opencv_java.hpp/#L30-L30)</code>
> <code>[modules/videoio/include/opencv2/videoio/registry.hpp[30-42]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3059d305c90b6bab83ac3b08a85aba5236e3b2e5/modules/videoio/include/opencv2/videoio/registry.hpp/#L30-L42)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>The converter caches a JNI local class reference across native invocations, although local references are valid only for their creating native frame.
>
>## Fix Focus Areas
>- modules/videoio/misc/java/src/cpp/videoio_converters.cpp[37-50]
>
>## Recommended Fix
>Convert the result of `FindClass("java/lang/Integer")` into a global reference before storing it statically, following the existing `ARRAYLIST(env)` pattern. Check class and method lookup failures before constructing list elements.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-context:start -->
<details><summary><strong>Context sources</strong></summary>
<div>Review mode: <code>⚖️ Balanced</code>: Downgraded extended -> standard: change is below the extended eligibility bar (hunks 12/18, lines 155/200; both must reach the floor). Router rationale: This is a cross-language, behavior-changing integration spanning Java generation, Python parsing/conversion, public videoio APIs, JNI lifetime/call handling, and custom type conversions, with multiple independent defect-prone paths.</div>
<!-- qodo-context:end -->
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-daily-tip:start -->
<details>
<summary><strong>Tip of the day</strong></summary>
<br/>
<pre>💡 Did you know, you can add REVIEW.md to your repo root and Qodo follows it on every PR</pre>
<a href="https://docs.qodo.ai/tips-and-tricks">More tips ↗</a> | <a href="https://app.qodo.ai/configurations?tab=display-preferences">Customize Qodo ↗</a> | <a href="https://docs.qodo.ai">Qodo docs ↗</a>
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-daily-tip:end -->
<!-- https://github.com/drape-io/crbench-qodo-2026-09/commit/3059d305c90b6bab83ac3b08a85aba5236e3b2e5 -->
<a href="https://www.qodo.ai"><img src="https://www.qodo.ai/wp-content/uploads/2025/03/qodo-logo.svg" width="80" alt="Qodo Logo"></a>