Skip to content

Commit b2d322d

Browse files
committed
Check container output's allocations
1 parent 105afd4 commit b2d322d

1 file changed

Lines changed: 17 additions & 7 deletions

File tree

av/container/output.py

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@ def __cinit__(self, *args, **kwargs):
8787
self._buffered_packets = []
8888
with cython.nogil:
8989
self.packet_ptr = lib.av_packet_alloc()
90+
if self.packet_ptr == cython.NULL:
91+
raise MemoryError("Could not allocate packet")
9092

9193
def __del__(self):
9294
close_output(self)
@@ -336,8 +338,13 @@ def add_stream_from_template(
336338
)
337339

338340
# Create new stream in the AVFormatContext, set AVCodecContext values.
339-
stream: cython.pointer[lib.AVStream] = lib.avformat_new_stream(self.ptr, codec)
340341
ctx: cython.pointer[lib.AVCodecContext] = lib.avcodec_alloc_context3(codec)
342+
if ctx == cython.NULL:
343+
raise MemoryError("Could not allocate codec context")
344+
stream: cython.pointer[lib.AVStream] = lib.avformat_new_stream(self.ptr, codec)
345+
if stream == cython.NULL:
346+
lib.avcodec_free_context(cython.address(ctx))
347+
raise MemoryError("Could not allocate stream")
341348

342349
err_check(lib.avcodec_parameters_to_context(ctx, template.ptr.codecpar))
343350
# Reset the codec tag assuming we are remuxing.
@@ -482,18 +489,21 @@ def add_data_stream(self, codec_name=None, options: dict | None = None):
482489
f"{self.format.name!r} format does not support {codec_name!r} codec"
483490
)
484491

485-
# Create new stream in the AVFormatContext
486-
stream: cython.pointer[lib.AVStream] = lib.avformat_new_stream(self.ptr, codec)
487-
if stream == cython.NULL:
488-
raise MemoryError("Could not allocate stream")
489-
490-
# Set up codec context and parameters
492+
# The context first, so a failure here does not orphan a stream.
491493
ctx: cython.pointer[lib.AVCodecContext] = cython.NULL
492494
if codec != cython.NULL:
493495
ctx = lib.avcodec_alloc_context3(codec)
494496
if ctx == cython.NULL:
495497
raise MemoryError("Could not allocate codec context")
496498

499+
# Create new stream in the AVFormatContext
500+
stream: cython.pointer[lib.AVStream] = lib.avformat_new_stream(self.ptr, codec)
501+
if stream == cython.NULL:
502+
if ctx != cython.NULL:
503+
lib.avcodec_free_context(cython.address(ctx))
504+
raise MemoryError("Could not allocate stream")
505+
506+
if codec != cython.NULL:
497507
# Some formats want stream headers to be separate
498508
if self.ptr.oformat.flags & lib.AVFMT_GLOBALHEADER:
499509
ctx.flags |= lib.AV_CODEC_FLAG_GLOBAL_HEADER

0 commit comments

Comments
 (0)