From 3b4b4ebdce78d3d6a740be28b9fb885fbae540a2 Mon Sep 17 00:00:00 2001 From: WyattBlue Date: Wed, 18 Nov 2026 17:12:37 -0500 Subject: [PATCH] Release the GIL during slow setup calls Filter init and graph configuration can load models (whisper, dnn_*), device listing probes drivers, and creating a CUDA device or frame pool can take hundreds of milliseconds. All of these held the GIL, stopping every other Python thread. --- CHANGELOG.rst | 1 + av/device.py | 23 ++++++++++++++--------- av/filter/context.py | 12 ++++++++++-- av/filter/graph.py | 6 +++++- av/video/frame.py | 12 ++++++++---- 5 files changed, 38 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 002fe9fc6..602771170 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -58,6 +58,7 @@ Fixes: - ``AudioFifo.write()`` now raises ``ValueError`` for a frame whose channel layout differs from the first frame's, instead of reading the wrong number of channels and scrambling or over-reading the samples. By :gh-user:`ChandraChaan` in (:pr:`2505`). - A failed ``CodecContext.open()`` no longer clears the selected codec, so ``codec``, ``name``, ``is_encoder``, and ``is_decoder`` keep working and the context can be reused after fixing the offending parameters. - :class:`.BitStreamFilterContext` now passes ``in_stream``'s time base to the filter, so filters that read it, such as ``setts`` with ``TB`` and ``pcm_rechunk``, no longer return ``None`` timestamps. By :gh-user:`NotAFlightRisk`. +- Release the GIL while initializing filters, configuring filter graphs, listing devices, and creating the CUDA device and frame pool used by ``VideoFrame.from_dlpack()``, so slow setup such as loading a ``whisper`` model or probing capture devices no longer stops other Python threads. - :meth:`.CodecContext.open` releases the GIL while the codec opens, as do creating a hardware device and its encoder frame pool, so other Python threads keep running while a hardware encoder takes seconds to start (:issue:`2517`). v19.0.2 diff --git a/av/device.py b/av/device.py index 6ef9d13ba..e3848a573 100644 --- a/av/device.py +++ b/av/device.py @@ -96,9 +96,12 @@ def _enumerate_via_log_fallback(format_name: str) -> list[DeviceInfo]: devices: list[DeviceInfo] = [] try: with avlogging.Capture() as logs: - lib.avformat_open_input(cython.address(ctx), b"", fmt, cython.address(opts)) - if ctx: - lib.avformat_close_input(cython.address(ctx)) + with cython.nogil: + lib.avformat_open_input( + cython.address(ctx), b"", fmt, cython.address(opts) + ) + if ctx: + lib.avformat_close_input(cython.address(ctx)) current_media_type = "video" for _level, _name, message in logs: @@ -146,12 +149,13 @@ def enumerate_input_devices(format_name: str) -> list[DeviceInfo]: raise ValueError(f"no such input format: {format_name!r}") device_list: cython.pointer[lib.AVDeviceInfoList] = cython.NULL + ret: cython.int try: - err_check( - lib.avdevice_list_input_sources( + with cython.nogil: + ret = lib.avdevice_list_input_sources( fmt, cython.NULL, cython.NULL, cython.address(device_list) ) - ) + err_check(ret) return _build_device_list(device_list) except NotImplementedError: # Format doesn't implement get_device_list (e.g. avfoundation). @@ -177,11 +181,12 @@ def enumerate_output_devices(format_name: str) -> list[DeviceInfo]: raise ValueError(f"no such output format: {format_name!r}") device_list: cython.pointer[lib.AVDeviceInfoList] = cython.NULL - err_check( - lib.avdevice_list_output_sinks( + ret: cython.int + with cython.nogil: + ret = lib.avdevice_list_output_sinks( fmt, cython.NULL, cython.NULL, cython.address(device_list) ) - ) + err_check(ret) try: return _build_device_list(device_list) diff --git a/av/filter/context.py b/av/filter/context.py index c04719216..75b1be00e 100644 --- a/av/filter/context.py +++ b/av/filter/context.py @@ -78,13 +78,21 @@ def init(self, args=None, **kwargs): dict_: Dictionary = None c_args: cython.p_char = cython.NULL + ctx: cython.pointer[lib.AVFilterContext] = self.ptr + ret: cython.int if args or not kwargs: if args: c_args = args - err_check(lib.avfilter_init_str(self.ptr, c_args)) + with cython.nogil: + ret = lib.avfilter_init_str(ctx, c_args) else: dict_ = Dictionary(kwargs) - err_check(lib.avfilter_init_dict(self.ptr, cython.address(dict_.ptr))) + dict_ptr: cython.pointer[cython.pointer[lib.AVDictionary]] = cython.address( + dict_.ptr + ) + with cython.nogil: + ret = lib.avfilter_init_dict(ctx, dict_ptr) + err_check(ret) self.inited = True if dict_: diff --git a/av/filter/graph.py b/av/filter/graph.py index 76f140e53..bde6c64e6 100644 --- a/av/filter/graph.py +++ b/av/filter/graph.py @@ -91,7 +91,11 @@ def configure(self, auto_buffer: cython.bint = True, force: cython.bint = False) if self.configured and not force: return - err_check(lib.avfilter_graph_config(self.ptr, cython.NULL)) + graph: cython.pointer[lib.AVFilterGraph] = self.ptr + ret: cython.int + with cython.nogil: + ret = lib.avfilter_graph_config(graph, cython.NULL) + err_check(ret) self.configured = True # We get auto-inserted stuff here. diff --git a/av/video/frame.py b/av/video/frame.py index cbf541c62..579de0a2c 100644 --- a/av/video/frame.py +++ b/av/video/frame.py @@ -113,15 +113,16 @@ def _get_device_ref(self) -> cython.pointer[lib.AVBufferRef]: if self.current_ctx: options_dict["current_ctx"] = "1" options: Dictionary = Dictionary(options_dict) - err_check( - lib.av_hwdevice_ctx_create( + ret: cython.int + with cython.nogil: + ret = lib.av_hwdevice_ctx_create( cython.address(owner_ref), lib.AV_HWDEVICE_TYPE_CUDA, c_device, options.ptr, 0, ) - ) + err_check(ret) if not self.cuda_stream: self._device_ref = owner_ref return owner_ref @@ -169,6 +170,7 @@ def get_frames_ctx( cached = self._frames_cache.get(key) cached_ref: cython.pointer[lib.AVBufferRef] out_ref: cython.pointer[lib.AVBufferRef] + ret: cython.int if cached is not None: cached_ref = cython.cast( @@ -196,7 +198,9 @@ def get_frames_ctx( frames_ctx.sw_format = sw_fmt frames_ctx.width = int(width) frames_ctx.height = int(height) - err_check(lib.av_hwframe_ctx_init(frames_ref)) + with cython.nogil: + ret = lib.av_hwframe_ctx_init(frames_ref) + err_check(ret) except Exception: lib.av_buffer_unref(cython.address(frames_ref)) raise