Skip to content

Release the GIL in CodecContext.open() (avcodec_open2): hardware encoders block all Python threads for up to seconds #2517

Closed

Description

@bjudkewitz

CodecContext.open() calls avcodec_open2 with the GIL held. For most software codecs that takes milliseconds, but hardware encoders can take much longer. While the call runs, every other Python thread stops.

With PyAV 19.0.2 (Python 3.12, Windows 11, Intel UHD 770), opening hevc_qsv takes ~0.4 s in a bare process and up to 2.5 s in our application. FFmpeg's log shows nearly all of that time is spent creating the MFX session. The longest pause of any other Python thread equals the open time.

In a multi-camera recording application this freezes the GUI, camera capture threads and audio callbacks whenever a recording starts. Camera driver buffers and audio input buffers overflow, and frames and samples are lost. With two cameras the opens add up.

Minimal reproduction:

import threading, time
from fractions import Fraction
import av

ticks, stop = [], threading.Event()
def ticker():
    while not stop.is_set():
        ticks.append(time.perf_counter()); time.sleep(0.002)
threading.Thread(target=ticker, daemon=True).start()
time.sleep(0.1)

cc = av.CodecContext.create("hevc_qsv", "w")   # or h264_nvenc, any slow-opening encoder
cc.width, cc.height, cc.pix_fmt = 1920, 1080, "nv12"
cc.time_base = Fraction(1, 25)
t0 = time.perf_counter(); cc.open(); t1 = time.perf_counter()
stop.set()
pause = max(b - a for a, b in zip(ticks, ticks[1:]) if b >= t0 and a <= t1)
print(f"open {t1 - t0:.2f} s, longest pause of another thread {pause:.2f} s")  # the two are equal

Proposal: release the GIL around the call, as recently done for muxer I/O (#2412) and for avcodec_free_context (#2480):

ctx = self.ptr
codec = self.ptr.codec
opts = cython.address(options.ptr)
with cython.nogil:
    res = lib.avcodec_open2(ctx, codec, opts)
err_check(res, f'avcodec_open2("{self.ptr.codec.name}", {self.options})')

We tested the equivalent from Python by calling avcodec_open2 through ctypes, which releases the GIL, on PyAV's own AVCodecContext. With hevc_qsv, h264_qsv and libx264, other threads then paused at most ~6 ms and the output files were correct. FFmpeg's log callback takes the GIL itself, as it does for the existing nogil calls such as avcodec_send_frame.

Related, possibly a separate issue: opening a Quick Sync encoder on an existing QSV device (hw_device_ctx, system-memory input frames) takes ~0.1 s, because the MFX loader is reused. With add_stream(hwaccel=...), every encoder creates a new device (with the GIL held) and requires a 32-surface GPU frame pool. On this machine that pool failed: "Could not create the texture (80070057)". Being able to pass an existing HWDevice to an encoder, without a frame pool, would help.

Activity

  1. added a commit that references this issue on Nov 18, 2026
    ee2f2e1
  2. added a commit that references this issue on Nov 19, 2026
    ba113e6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions