From 362840a231544b6d0343bb7a6da5943781496de0 Mon Sep 17 00:00:00 2001 From: WyattBlue Date: Wed, 18 Nov 2026 16:42:00 -0500 Subject: [PATCH] Release the GIL when opening a codec, fixes #2517 Hardware encoders can take seconds in avcodec_open2(), and every other Python thread stopped for that time. Also release it around creating a hardware device and the encoder's hardware frame pool. --- CHANGELOG.rst | 1 + av/codec/context.py | 14 +++++++++++--- av/codec/hwaccel.py | 22 ++++++++++++++-------- 3 files changed, 26 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index d92389458..002fe9fc6 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`. +- :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/codec/context.py b/av/codec/context.py index 121e516b6..b99a0a0a8 100644 --- a/av/codec/context.py +++ b/av/codec/context.py @@ -446,9 +446,14 @@ def open(self, strict: cython.bint = True): # AVCodec structs are static globals, so holding the pointer across the # call is safe. codec: cython.pointer[cython.const[lib.AVCodec]] = self.ptr.codec - ret: cython.int = lib.avcodec_open2( - self.ptr, codec, cython.address(options.ptr) + ctx: cython.pointer[lib.AVCodecContext] = self.ptr + options_ptr: cython.pointer[cython.pointer[lib.AVDictionary]] = cython.address( + options.ptr ) + ret: cython.int + # Hardware encoders can take seconds to open, so let other threads run. + with cython.nogil: + ret = lib.avcodec_open2(ctx, codec, options_ptr) if ret < 0: self.ptr.codec = codec err_check(ret, f'avcodec_open2("{codec.name}", {self.options})') @@ -618,6 +623,7 @@ def _setup_encode_hwframes(self) -> cython.void: if frames_ref == cython.NULL: raise MemoryError("av_hwframe_ctx_alloc() failed") + ret: cython.int try: frames_ctx: cython.pointer[lib.AVHWFramesContext] = cython.cast( cython.pointer[lib.AVHWFramesContext], frames_ref.data @@ -627,7 +633,9 @@ def _setup_encode_hwframes(self) -> cython.void: frames_ctx.width = self.ptr.width frames_ctx.height = self.ptr.height frames_ctx.initial_pool_size = 32 - 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 diff --git a/av/codec/hwaccel.py b/av/codec/hwaccel.py index 5aaf8ac3e..6ef4e9d77 100644 --- a/av/codec/hwaccel.py +++ b/av/codec/hwaccel.py @@ -152,15 +152,19 @@ def __init__(self, device_type, device=None, options=None, flags=None): c_device = device_bytes c_options: Dictionary = Dictionary(self.options) - err_check( - lib.av_hwdevice_ctx_create( + c_device_type: lib.AVHWDeviceType = cython.cast( + lib.AVHWDeviceType, self._device_type + ) + ret: cython.int + with cython.nogil: + ret = lib.av_hwdevice_ctx_create( cython.address(self.ptr), - cython.cast(lib.AVHWDeviceType, self._device_type), + c_device_type, c_device, c_options.ptr, self.flags, ) - ) + err_check(ret) @property def device_type(self): @@ -255,15 +259,17 @@ def _initialize_hw_context(self, codec: Codec, for_encoding: bool = False): c_device = device_bytes c_options: Dictionary = Dictionary(self.options) - err_check( - lib.av_hwdevice_ctx_create( + c_device_type: lib.AVHWDeviceType = config.ptr.device_type + ret: cython.int + with cython.nogil: + ret = lib.av_hwdevice_ctx_create( cython.address(self.ptr), - config.ptr.device_type, + c_device_type, c_device, c_options.ptr, self.flags, ) - ) + err_check(ret) def create(self, codec: Codec, for_encoding: bool = False) -> HWAccel: """Create a new hardware accelerator context with the given codec"""