Skip to content

Fix memory growth when remuxing with add_stream_from_template(opaque=…#2182

Merged
WyattBlue merged 1 commit intomainfrom
patch
Mar 10, 2026
Merged

Fix memory growth when remuxing with add_stream_from_template(opaque=…#2182
WyattBlue merged 1 commit intomainfrom
patch

Conversation

@WyattBlue
Copy link
Member

…False)

start_encoding() was calling avcodec_open2() on encoder codec contexts created by add_stream_from_template(), fully initializing the encoder (e.g. libx264 allocates x264_t, thread pools, reference frames) even when the stream is only used for remuxing and never calls encode(). After freeing, the C heap retains this memory, causing RSS to grow with each output segment.

Add a _template_initialized flag to CodecContext, set by add_stream_from_template(). In start_encoding(), encoder contexts with this flag skip avcodec_open2() — the encoder opens lazily via encode() if actually needed for re-encoding.

Fixes #2135

start_encoding() was calling avcodec_open2() on codec contexts created
by add_stream_from_template(), fully initializing the codec (e.g.
libx264 allocates x264_t, thread pools, reference frames) even when
the stream is only used for remuxing and never calls encode()/decode().
After freeing, the C heap retains this memory, causing RSS to grow with
each output segment.

Add a _template_initialized flag to CodecContext, set by
add_stream_from_template(). In start_encoding(), contexts with this
flag skip avcodec_open2() — the codec opens lazily via encode() or
decode() if actually needed.

Fixes #2135

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@WyattBlue WyattBlue merged commit 7ac99aa into main Mar 10, 2026
6 checks passed
@WyattBlue WyattBlue deleted the patch branch March 10, 2026 04:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Memory leak when remuxing segments with add_stream_from_template(..., opaque=False)

1 participant