diff --git a/av/container/core.pxd b/av/container/core.pxd index 2ccf9fe28..9d820b1c9 100644 --- a/av/container/core.pxd +++ b/av/container/core.pxd @@ -5,24 +5,18 @@ from av.dictionary cimport _Dictionary from av.format cimport ContainerFormat from av.stream cimport Stream -# Since there are multiple objects that need to refer to a valid context, we -# need this intermediate proxy object so that there aren't any reference cycles -# and the pointer can be freed when everything that depends upon it is deleted. -cdef class ContainerProxy(object): - cdef bint writeable - cdef lib.AVFormatContext *ptr +cdef class Container(object): - cdef seek(self, int stream_index, offset, str whence, bint backward, bint any_frame) - cdef flush_buffers(self) + cdef readonly bint writeable + cdef lib.AVFormatContext *ptr - # Copies from Container. - cdef object name - cdef str metadata_encoding - cdef str metadata_errors + cdef readonly object name + cdef readonly str metadata_encoding + cdef readonly str metadata_errors # File-like source. - cdef object file + cdef readonly object file cdef object fread cdef object fwrite cdef object fseek @@ -36,27 +30,13 @@ cdef class ContainerProxy(object): cdef bint pos_is_valid cdef bint input_was_opened - cdef int err_check(self, int value) except -1 - - -cdef class Container(object): - - cdef readonly object name - cdef readonly object file - - cdef readonly bint writeable - cdef readonly ContainerFormat format cdef readonly dict options cdef readonly dict container_options cdef readonly list stream_options - cdef ContainerProxy proxy - cdef object __weakref__ - cdef readonly StreamContainer streams cdef readonly dict metadata - cdef readonly str metadata_encoding - cdef readonly str metadata_errors + cdef int err_check(self, int value) except -1 diff --git a/av/container/core.pyx b/av/container/core.pyx index 443e51dc6..eedd97935 100644 --- a/av/container/core.pyx +++ b/av/container/core.pyx @@ -30,22 +30,37 @@ ctypedef int64_t (*seek_func_t)(void *opaque, int64_t offset, int whence) nogil cdef object _cinit_sentinel = object() -cdef class ContainerProxy(object): - - def __init__(self, sentinel, Container container): +cdef class Container(object): - self.input_was_opened = False - cdef int res + def __cinit__(self, sentinel, file_, format_name, options, container_options, stream_options, metadata_encoding, metadata_errors): if sentinel is not _cinit_sentinel: - raise RuntimeError('cannot construct ContainerProxy') + raise RuntimeError('cannot construct base Container') + + self.writeable = isinstance(self, OutputContainer) + if not self.writeable and not isinstance(self, InputContainer): + raise RuntimeError('Container cannot be directly extended.') + + if isinstance(file_, basestring): + self.name = file_ + else: + self.name = getattr(file_, 'name', '') + if not isinstance(self.name, basestring): + raise TypeError("File's name attribute must be string-like.") + self.file = file_ + + self.options = dict(options or ()) + self.container_options = dict(container_options or ()) + self.stream_options = [dict(x) for x in stream_options or ()] + + self.metadata_encoding = metadata_encoding + self.metadata_errors = metadata_errors + + if format_name is not None: + self.format = ContainerFormat(format_name) - # Copy key attributes. - self.file = container.file - self.metadata_encoding = container.metadata_encoding - self.metadata_errors = container.metadata_errors - self.name = container.name - self.writeable = container.writeable + self.input_was_opened = False + cdef int res cdef bytes name_obj = fsencode(self.name) if isinstance(self.name, unicode) else self.name cdef char *name = name_obj @@ -54,7 +69,7 @@ cdef class ContainerProxy(object): cdef lib.AVOutputFormat *ofmt if self.writeable: - ofmt = container.format.optr if container.format else lib.av_guess_format(NULL, name, NULL) + ofmt = self.format.optr if self.format else lib.av_guess_format(NULL, name, NULL) if ofmt == NULL: raise ValueError("Could not determine output format") @@ -115,22 +130,27 @@ cdef class ContainerProxy(object): self.ptr.pb = self.iocontext cdef lib.AVInputFormat *ifmt - cdef _Dictionary options + cdef _Dictionary c_options if not self.writeable: - ifmt = container.format.iptr if container.format else NULL - options = Dictionary(container.options, container.container_options) + ifmt = self.format.iptr if self.format else NULL + + c_options = Dictionary(self.options, self.container_options) with nogil: res = lib.avformat_open_input( &self.ptr, name, ifmt, - &options.ptr + &c_options.ptr ) self.err_check(res) self.input_was_opened = True + if format_name is None: + self.format = build_container_format(self.ptr.iformat, self.ptr.oformat) + def __dealloc__(self): + with nogil: # Let FFmpeg close input if it was fully opened. @@ -151,89 +171,15 @@ cdef class ContainerProxy(object): # Finish releasing the whole structure. lib.avformat_free_context(self.ptr) - cdef seek(self, int stream_index, offset, str whence, bint backward, bint any_frame): - - # We used to take floats here and assume they were in seconds. This - # was super confusing, so lets go in the complete opposite direction. - if not isinstance(offset, (int, long)): - raise TypeError('Container.seek only accepts integer offset.', type(offset)) - cdef int64_t c_offset = offset - - cdef int flags = 0 - cdef int ret - - if whence == 'frame': - flags |= lib.AVSEEK_FLAG_FRAME - elif whence == 'byte': - flags |= lib.AVSEEK_FLAG_BYTE - elif whence != 'time': - raise ValueError("whence must be one of 'frame', 'byte', or 'time'.", whence) - - if backward: - flags |= lib.AVSEEK_FLAG_BACKWARD - - if any_frame: - flags |= lib.AVSEEK_FLAG_ANY - - with nogil: - ret = lib.av_seek_frame(self.ptr, stream_index, c_offset, flags) - err_check(ret) - - self.flush_buffers() - - cdef flush_buffers(self): - cdef unsigned int i - cdef lib.AVStream *stream - - with nogil: - for i in range(self.ptr.nb_streams): - stream = self.ptr.streams[i] - if stream.codec and stream.codec.codec and stream.codec.codec_id != lib.AV_CODEC_ID_NONE: - lib.avcodec_flush_buffers(stream.codec) + def __repr__(self): + return '' % (self.__class__.__name__, self.file or self.name) cdef int err_check(self, int value) except -1: return err_check(value, filename=self.name) - -cdef class Container(object): - - def __cinit__(self, sentinel, file_, format_name, options, container_options, stream_options, metadata_encoding, metadata_errors): - - if sentinel is not _cinit_sentinel: - raise RuntimeError('cannot construct base Container') - - self.writeable = isinstance(self, OutputContainer) - if not self.writeable and not isinstance(self, InputContainer): - raise RuntimeError('Container cannot be extended except') - - if isinstance(file_, basestring): - self.name = file_ - else: - self.name = getattr(file_, 'name', '') - if not isinstance(self.name, basestring): - raise TypeError("File's name attribute must be string-like.") - self.file = file_ - - if format_name is not None: - self.format = ContainerFormat(format_name) - - self.options = dict(options or ()) - self.container_options = dict(container_options or ()) - self.stream_options = [dict(x) for x in stream_options or ()] - - self.metadata_encoding = metadata_encoding - self.metadata_errors = metadata_errors - self.proxy = ContainerProxy(_cinit_sentinel, self) - - if format_name is None: - self.format = build_container_format(self.proxy.ptr.iformat, self.proxy.ptr.oformat) - - def __repr__(self): - return '' % (self.__class__.__name__, self.file or self.name) - def dumps_format(self): with LogCapture() as logs: - lib.av_dump_format(self.proxy.ptr, 0, "", isinstance(self, OutputContainer)) + lib.av_dump_format(self.ptr, 0, "", isinstance(self, OutputContainer)) return ''.join(log[2] for log in logs) diff --git a/av/container/input.pxd b/av/container/input.pxd index 1a1554902..8c369d8ad 100644 --- a/av/container/input.pxd +++ b/av/container/input.pxd @@ -5,4 +5,5 @@ from av.stream cimport Stream cdef class InputContainer(Container): - pass + + cdef flush_buffers(self) diff --git a/av/container/input.pyx b/av/container/input.pyx index 77b0a608c..58602947c 100644 --- a/av/container/input.pyx +++ b/av/container/input.pyx @@ -1,3 +1,4 @@ +from libc.stdint cimport int64_t from libc.stdlib cimport malloc, free from av.container.streams cimport StreamContainer @@ -22,8 +23,8 @@ cdef class InputContainer(Container): cdef _Dictionary base_dict, stream_dict if self.options or self.stream_options: base_dict = Dictionary(self.options) - c_options = malloc(self.proxy.ptr.nb_streams * sizeof(void*)) - for i in range(self.proxy.ptr.nb_streams): + c_options = malloc(self.ptr.nb_streams * sizeof(void*)) + for i in range(self.ptr.nb_streams): c_options[i] = NULL if i < len(self.stream_options) and self.stream_options: stream_dict = base_dict.copy() @@ -41,34 +42,34 @@ cdef class InputContainer(Container): # - set stream.r_frame_rate to average value; # - open and closes codecs with the options provided. ret = lib.avformat_find_stream_info( - self.proxy.ptr, + self.ptr, c_options ) - self.proxy.err_check(ret) + self.err_check(ret) # Cleanup all of our options. if c_options: - for i in range(self.proxy.ptr.nb_streams): + for i in range(self.ptr.nb_streams): lib.av_dict_free(&c_options[i]) free(c_options) self.streams = StreamContainer() - for i in range(self.proxy.ptr.nb_streams): - self.streams.add_stream(wrap_stream(self, self.proxy.ptr.streams[i])) + for i in range(self.ptr.nb_streams): + self.streams.add_stream(wrap_stream(self, self.ptr.streams[i])) - self.metadata = avdict_to_dict(self.proxy.ptr.metadata, self.metadata_encoding, self.metadata_errors) + self.metadata = avdict_to_dict(self.ptr.metadata, self.metadata_encoding, self.metadata_errors) property start_time: - def __get__(self): return self.proxy.ptr.start_time + def __get__(self): return self.ptr.start_time property duration: - def __get__(self): return self.proxy.ptr.duration + def __get__(self): return self.ptr.duration property bit_rate: - def __get__(self): return self.proxy.ptr.bit_rate + def __get__(self): return self.ptr.bit_rate property size: - def __get__(self): return lib.avio_size(self.proxy.ptr.pb) + def __get__(self): return lib.avio_size(self.ptr.pb) def demux(self, *args, **kwargs): """demux(streams=None, video=None, audio=None, subtitles=None, data=None) @@ -96,7 +97,7 @@ cdef class InputContainer(Container): streams = self.streams.get(*args, **kwargs) - cdef bint *include_stream = malloc(self.proxy.ptr.nb_streams * sizeof(bint)) + cdef bint *include_stream = malloc(self.ptr.nb_streams * sizeof(bint)) if include_stream == NULL: raise MemoryError() @@ -106,11 +107,11 @@ cdef class InputContainer(Container): try: - for i in range(self.proxy.ptr.nb_streams): + for i in range(self.ptr.nb_streams): include_stream[i] = False for stream in streams: i = stream.index - if i >= self.proxy.ptr.nb_streams: + if i >= self.ptr.nb_streams: raise ValueError('stream index %d out of range' % i) include_stream[i] = True @@ -119,8 +120,8 @@ cdef class InputContainer(Container): packet = Packet() try: with nogil: - ret = lib.av_read_frame(self.proxy.ptr, &packet.struct) - self.proxy.err_check(ret) + ret = lib.av_read_frame(self.ptr, &packet.struct) + self.err_check(ret) except AVError: break @@ -136,7 +137,7 @@ cdef class InputContainer(Container): yield packet # Flush! - for i in range(self.proxy.ptr.nb_streams): + for i in range(self.ptr.nb_streams): if include_stream[i]: packet = Packet() packet._stream = self.streams[i] @@ -163,7 +164,7 @@ cdef class InputContainer(Container): for frame in packet.decode(): yield frame - def seek(self, offset, whence='time', backward=True, any_frame=False, stream=None): + def seek(self, offset, str whence='time', bint backward=True, bint any_frame=False, Stream stream=None): """Seek to a (key)frame nearsest to the given timestamp. :param int offset: Location to seek to. Interpretation depends on ``whence``. @@ -182,4 +183,42 @@ cdef class InputContainer(Container): .. warning:: Not all formats support all options, and may fail silently. """ - self.proxy.seek(stream.index if stream else -1, offset, whence, backward, any_frame) + + # We used to take floats here and assume they were in seconds. This + # was super confusing, so lets go in the complete opposite direction. + if not isinstance(offset, (int, long)): + raise TypeError('Container.seek only accepts integer offset.', type(offset)) + cdef int64_t c_offset = offset + + cdef int flags = 0 + cdef int ret + + if whence == 'frame': + flags |= lib.AVSEEK_FLAG_FRAME + elif whence == 'byte': + flags |= lib.AVSEEK_FLAG_BYTE + elif whence != 'time': + raise ValueError("whence must be one of 'frame', 'byte', or 'time'.", whence) + + if backward: + flags |= lib.AVSEEK_FLAG_BACKWARD + + if any_frame: + flags |= lib.AVSEEK_FLAG_ANY + + cdef int stream_index = stream.index if stream else -1 + with nogil: + ret = lib.av_seek_frame(self.ptr, stream_index, c_offset, flags) + err_check(ret) + + self.flush_buffers() + + cdef flush_buffers(self): + cdef unsigned int i + cdef lib.AVStream *stream + + with nogil: + for i in range(self.ptr.nb_streams): + stream = self.ptr.streams[i] + if stream.codec and stream.codec.codec and stream.codec.codec_id != lib.AV_CODEC_ID_NONE: + lib.avcodec_flush_buffers(stream.codec) diff --git a/av/container/output.pyx b/av/container/output.pyx index 702e7e0b0..b6dd77119 100644 --- a/av/container/output.pyx +++ b/av/container/output.pyx @@ -56,7 +56,7 @@ cdef class OutputContainer(Container): # Assert that this format supports the requested codec. if not lib.avformat_query_codec( - self.proxy.ptr.oformat, + self.ptr.oformat, codec.id, lib.FF_COMPLIANCE_NORMAL, ): @@ -66,8 +66,8 @@ cdef class OutputContainer(Container): # As of last check, avformat_new_stream only calls avcodec_alloc_context3 to create # the context, but doesn't modify it in any other way. Ergo, we can allow CodecContext # to finish initializing it. - lib.avformat_new_stream(self.proxy.ptr, codec) - cdef lib.AVStream *stream = self.proxy.ptr.streams[self.proxy.ptr.nb_streams - 1] + lib.avformat_new_stream(self.ptr, codec) + cdef lib.AVStream *stream = self.ptr.streams[self.ptr.nb_streams - 1] cdef lib.AVCodecContext *codec_context = stream.codec # For readability. # Copy from the template. @@ -102,7 +102,7 @@ cdef class OutputContainer(Container): codec_context.channel_layout = lib.AV_CH_LAYOUT_STEREO # Some formats want stream headers to be separate - if self.proxy.ptr.oformat.flags & lib.AVFMT_GLOBALHEADER: + if self.ptr.oformat.flags & lib.AVFMT_GLOBALHEADER: codec_context.flags |= lib.AV_CODEC_FLAG_GLOBAL_HEADER # Construct the user-land stream @@ -146,18 +146,18 @@ cdef class OutputContainer(Container): stream._finalize_for_output() # Open the output file, if needed. - cdef char *name = "" if self.proxy.file is not None else self.name - if self.proxy.ptr.pb == NULL and not self.proxy.ptr.oformat.flags & lib.AVFMT_NOFILE: - err_check(lib.avio_open(&self.proxy.ptr.pb, name, lib.AVIO_FLAG_WRITE)) + cdef char *name = "" if self.file is not None else self.name + if self.ptr.pb == NULL and not self.ptr.oformat.flags & lib.AVFMT_NOFILE: + err_check(lib.avio_open(&self.ptr.pb, name, lib.AVIO_FLAG_WRITE)) # Copy the metadata dict. - dict_to_avdict(&self.proxy.ptr.metadata, self.metadata, clear=True, + dict_to_avdict(&self.ptr.metadata, self.metadata, clear=True, encoding=self.metadata_encoding, errors=self.metadata_errors) cdef _Dictionary all_options = Dictionary(self.options, self.container_options) cdef _Dictionary options = all_options.copy() - self.proxy.err_check(lib.avformat_write_header( - self.proxy.ptr, + self.err_check(lib.avformat_write_header( + self.ptr, &options.ptr )) @@ -184,13 +184,13 @@ cdef class OutputContainer(Container): raise ValueError("Encoding hasn't started.") return - self.proxy.err_check(lib.av_write_trailer(self.proxy.ptr)) + self.err_check(lib.av_write_trailer(self.ptr)) cdef Stream stream for stream in self.streams: stream.codec_context.close() - if self.file is None and not self.proxy.ptr.oformat.flags & lib.AVFMT_NOFILE: - lib.avio_closep(&self.proxy.ptr.pb) + if self.file is None and not self.ptr.oformat.flags & lib.AVFMT_NOFILE: + lib.avio_closep(&self.ptr.pb) self._done = True @@ -208,18 +208,18 @@ cdef class OutputContainer(Container): self.start_encoding() # Assert the packet is in stream time. - if packet.struct.stream_index < 0 or packet.struct.stream_index >= self.proxy.ptr.nb_streams: + if packet.struct.stream_index < 0 or packet.struct.stream_index >= self.ptr.nb_streams: raise ValueError('Bad Packet stream_index.') - cdef lib.AVStream *stream = self.proxy.ptr.streams[packet.struct.stream_index] + cdef lib.AVStream *stream = self.ptr.streams[packet.struct.stream_index] packet._rebase_time(stream.time_base) # Make another reference to the packet, as av_interleaved_write_frame # takes ownership of it. cdef lib.AVPacket packet_ref lib.av_init_packet(&packet_ref) - self.proxy.err_check(lib.av_packet_ref(&packet_ref, &packet.struct)) + self.err_check(lib.av_packet_ref(&packet_ref, &packet.struct)) cdef int ret with nogil: - ret = lib.av_interleaved_write_frame(self.proxy.ptr, &packet_ref) - self.proxy.err_check(ret) + ret = lib.av_interleaved_write_frame(self.ptr, &packet_ref) + self.err_check(ret) diff --git a/av/container/pyio.pyx b/av/container/pyio.pyx index e2453cd28..c35931d01 100644 --- a/av/container/pyio.pyx +++ b/av/container/pyio.pyx @@ -2,7 +2,7 @@ from libc.string cimport memcpy cimport libav as lib -from av.container.core cimport ContainerProxy +from av.container.core cimport Container from av.utils cimport stash_exception @@ -11,10 +11,10 @@ cdef int pyio_read(void *opaque, uint8_t *buf, int buf_size) nogil: return pyio_read_gil(opaque, buf, buf_size) cdef int pyio_read_gil(void *opaque, uint8_t *buf, int buf_size): - cdef ContainerProxy self + cdef Container self cdef bytes res try: - self = opaque + self = opaque res = self.fread(buf_size) memcpy(buf, res, len(res)) self.pos += len(res) @@ -30,11 +30,11 @@ cdef int pyio_write(void *opaque, uint8_t *buf, int buf_size) nogil: return pyio_write_gil(opaque, buf, buf_size) cdef int pyio_write_gil(void *opaque, uint8_t *buf, int buf_size): - cdef ContainerProxy self + cdef Container self cdef bytes bytes_to_write cdef int bytes_written try: - self = opaque + self = opaque bytes_to_write = buf[:buf_size] ret_value = self.fwrite(bytes_to_write) bytes_written = ret_value if isinstance(ret_value, int) else buf_size @@ -54,9 +54,9 @@ cdef int64_t pyio_seek(void *opaque, int64_t offset, int whence) nogil: return pyio_seek_gil(opaque, offset, whence) cdef int64_t pyio_seek_gil(void *opaque, int64_t offset, int whence): - cdef ContainerProxy self + cdef Container self try: - self = opaque + self = opaque res = self.fseek(offset, whence) # Track the position for the user. diff --git a/av/stream.pxd b/av/stream.pxd index b2b54cf3b..61a65034d 100644 --- a/av/stream.pxd +++ b/av/stream.pxd @@ -3,7 +3,7 @@ from libc.stdint cimport int64_t cimport libav as lib from av.codec.context cimport CodecContext -from av.container.core cimport Container, ContainerProxy +from av.container.core cimport Container from av.frame cimport Frame from av.packet cimport Packet @@ -11,8 +11,7 @@ from av.packet cimport Packet cdef class Stream(object): # Stream attributes. - cdef ContainerProxy _container - cdef _weak_container + cdef readonly Container container cdef lib.AVStream *_stream cdef readonly dict metadata @@ -20,7 +19,6 @@ cdef class Stream(object): # CodecContext attributes. cdef lib.AVCodecContext *_codec_context cdef const lib.AVCodec *_codec - cdef lib.AVDictionary *_codec_options cdef readonly CodecContext codec_context diff --git a/av/stream.pyx b/av/stream.pyx index d25555f32..66810f74f 100644 --- a/av/stream.pyx +++ b/av/stream.pyx @@ -24,7 +24,7 @@ cdef Stream wrap_stream(Container container, lib.AVStream *c_stream): """ # This better be the right one... - assert container.proxy.ptr.streams[c_stream.index] == c_stream + assert container.ptr.streams[c_stream.index] == c_stream cdef Stream py_stream @@ -59,20 +59,19 @@ cdef class Stream(object): cdef _init(self, Container container, lib.AVStream *stream): - self._container = container.proxy - self._weak_container = PyWeakref_NewRef(container, None) + self.container = container self._stream = stream self._codec_context = stream.codec self.metadata = avdict_to_dict( stream.metadata, - encoding=self._container.metadata_encoding, - errors=self._container.metadata_errors, + encoding=self.container.metadata_encoding, + errors=self.container.metadata_errors, ) # This is an input container! - if self._container.ptr.iformat: + if self.container.ptr.iformat: # Find the codec. self._codec = lib.avcodec_find_decoder(self._codec_context.codec_id) @@ -88,10 +87,6 @@ cdef class Stream(object): self.codec_context = wrap_codec_context(self._codec_context, self._codec, False) self.codec_context.stream_index = stream.index - def __dealloc__(self): - if self._codec_options: - lib.av_dict_free(&self._codec_options) - def __repr__(self): return '' % ( self.__class__.__name__, @@ -121,8 +116,8 @@ cdef class Stream(object): dict_to_avdict( &self._stream.metadata, self.metadata, clear=True, - encoding=self._container.metadata_encoding, - errors=self._container.metadata_errors, + encoding=self.container.metadata_encoding, + errors=self.container.metadata_errors, ) if not self._stream.time_base.num: self._stream.time_base = self._codec_context.time_base @@ -157,7 +152,7 @@ cdef class Stream(object): Use :meth:`.InputContainer.seek` with ``stream`` argument instead. """ - self._container.seek(self._stream.index, offset, whence, backward, any_frame) + self.container.seek(offset, whence, backward, any_frame, stream=self) property id: """ diff --git a/scratchpad/container-gc.py b/scratchpad/container-gc.py new file mode 100644 index 000000000..a5bd2130d --- /dev/null +++ b/scratchpad/container-gc.py @@ -0,0 +1,44 @@ +import resource +import gc + + +import av +import av.datasets + +path = av.datasets.curated('pexels/time-lapse-video-of-night-sky-857195.mp4') + + +def format_bytes(n): + order = 0 + while n > 1024: + order += 1 + n //= 1024 + return '%d%sB' % (n, ('', 'k', 'M', 'G', 'T', 'P')[order]) + +after = resource.getrusage(resource.RUSAGE_SELF) + +count = 0 + +streams = [] + +while True: + + container = av.open(path) + # streams.append(container.streams.video[0]) + + del container + gc.collect() + + count += 1 + if not count % 100: + pass + # streams.clear() + # gc.collect() + + before = after + after = resource.getrusage(resource.RUSAGE_SELF) + print('{:6d} {} ({})'.format( + count, + format_bytes(after.ru_maxrss), + format_bytes(after.ru_maxrss - before.ru_maxrss), + ))