| 1 |
import cython |
| 2 |
from cython.cimports.av.codec.context import CodecContext, wrap_codec_context |
| 3 |
from cython.cimports.av.container.streams import StreamContainer |
| 4 |
from cython.cimports.av.dictionary import Dictionary |
| 5 |
from cython.cimports.av.error import err_check |
| 6 |
from cython.cimports.av.packet import Packet |
| 7 |
from cython.cimports.av.stream import Stream, wrap_stream |
| 8 |
from cython.cimports.av.utils import avdict_to_dict |
| 9 |
from cython.cimports.libc.stdint import int64_t, uint8_t |
| 10 |
from cython.cimports.libc.stdlib import free, malloc |
| 11 |
|
| 12 |
|
| 13 |
@cython.cfunc |
| 14 |
def close_input(self: InputContainer): |
| 15 |
self.streams = StreamContainer() |
| 16 |
with cython.nogil: |
| 17 |
if self._myflag & 2: |
| 18 |
# This causes `self.ptr` to be set to NULL. |
| 19 |
lib.avformat_close_input(cython.address(self.ptr)) |
| 20 |
self._myflag &= ~2 # enum.input_was_opened = False |
| 21 |
|
| 22 |
|
| 23 |
@cython.final |
| 24 |
@cython.cclass |
| 25 |
class InputContainer(Container): |
| 26 |
def __cinit__(self, *args, **kwargs): |
| 27 |
py_codec_context: CodecContext |
| 28 |
i: cython.uint |
| 29 |
stream: cython.pointer[lib.AVStream] |
| 30 |
codec: cython.pointer[cython.const[lib.AVCodec]] |
| 31 |
codec_context: cython.pointer[lib.AVCodecContext] |
| 32 |
|
| 33 |
# If we have either the global `options`, or a `stream_options`, prepare |
| 34 |
# a mashup of those options for each stream. |
| 35 |
c_options: cython.pointer[cython.pointer[lib.AVDictionary]] = cython.NULL |
| 36 |
base_dict: Dictionary |
| 37 |
stream_dict: Dictionary |
| 38 |
nb_streams_before: cython.uint = self.ptr.nb_streams |
| 39 |
if self.stream_options and nb_streams_before == 0: |
| 40 |
raise ValueError( |
| 41 |
"stream_options were provided, but this format does not expose " |
| 42 |
"its streams before avformat_find_stream_info (e.g. MPEG). " |
| 43 |
"Per-stream options cannot be applied." |
| 44 |
) |
| 45 |
# Only allocate c_options when streams are already known. |
| 46 |
if (self.options or self.stream_options) and nb_streams_before > 0: |
| 47 |
base_dict = Dictionary(self.options) |
| 48 |
c_options = cython.cast( |
| 49 |
cython.pointer[cython.pointer[lib.AVDictionary]], |
| 50 |
malloc(nb_streams_before * cython.sizeof(cython.p_void)), |
| 51 |
) |
| 52 |
for i in range(nb_streams_before): |
| 53 |
c_options[i] = cython.NULL |
| 54 |
if i < len(self.stream_options) and self.stream_options: |
| 55 |
stream_dict = base_dict.copy() |
| 56 |
stream_dict.update(self.stream_options[i]) |
| 57 |
lib.av_dict_copy(cython.address(c_options[i]), stream_dict.ptr, 0) |
| 58 |
else: |
| 59 |
lib.av_dict_copy(cython.address(c_options[i]), base_dict.ptr, 0) |
| 60 |
|
| 61 |
self.set_timeout(self.open_timeout) |
| 62 |
self.start_timeout() |
| 63 |
with cython.nogil: |
| 64 |
ret = lib.avformat_find_stream_info(self.ptr, c_options) |
| 65 |
self.set_timeout(None) |
| 66 |
self.err_check(ret) |
| 67 |
|
| 68 |
if c_options: |
| 69 |
for i in range(nb_streams_before): |
| 70 |
lib.av_dict_free(cython.address(c_options[i])) |
| 71 |
free(c_options) |
| 72 |
|
| 73 |
at_least_one_accelerated_context = False |
| 74 |
|
| 75 |
self.streams = StreamContainer() |
| 76 |
for i in range(self.ptr.nb_streams): |
| 77 |
stream = self.ptr.streams[i] |
| 78 |
codec = lib.avcodec_find_decoder(stream.codecpar.codec_id) |
| 79 |
if codec: |
| 80 |
codec_context = lib.avcodec_alloc_context3(codec) |
| 81 |
err_check( |
| 82 |
lib.avcodec_parameters_to_context(codec_context, stream.codecpar) |
| 83 |
) |
| 84 |
codec_context.pkt_timebase = stream.time_base |
| 85 |
py_codec_context = wrap_codec_context( |
| 86 |
codec_context, codec, self.hwaccel |
| 87 |
) |
| 88 |
if py_codec_context.is_hwaccel: |
| 89 |
at_least_one_accelerated_context = True |
| 90 |
else: |
| 91 |
# no decoder is available |
| 92 |
py_codec_context = None |
| 93 |
self.streams.add_stream(wrap_stream(self, stream, py_codec_context)) |
| 94 |
|
| 95 |
if ( |
| 96 |
self.hwaccel |
| 97 |
and not self.hwaccel.allow_software_fallback |
| 98 |
and not at_least_one_accelerated_context |
| 99 |
): |
| 100 |
raise RuntimeError( |
| 101 |
"Hardware accelerated decode requested but no stream is compatible" |
| 102 |
) |
| 103 |
|
| 104 |
self.metadata = avdict_to_dict( |
| 105 |
self.ptr.metadata, self.metadata_encoding, self.metadata_errors |
| 106 |
) |
| 107 |
|
| 108 |
def __dealloc__(self): |
| 109 |
close_input(self) |
| 110 |
|
| 111 |
@property |
| 112 |
def start_time(self): |
| 113 |
self._assert_open() |
| 114 |
if self.ptr.start_time != lib.AV_NOPTS_VALUE: |
| 115 |
return self.ptr.start_time |
| 116 |
|
| 117 |
@property |
| 118 |
def duration(self): |
| 119 |
self._assert_open() |
| 120 |
if self.ptr.duration != lib.AV_NOPTS_VALUE: |
| 121 |
return self.ptr.duration |
| 122 |
|
| 123 |
@property |
| 124 |
def bit_rate(self): |
| 125 |
self._assert_open() |
| 126 |
return self.ptr.bit_rate |
| 127 |
|
| 128 |
@property |
| 129 |
def size(self): |
| 130 |
self._assert_open() |
| 131 |
return lib.avio_size(self.ptr.pb) |
| 132 |
|
| 133 |
def close(self): |
| 134 |
close_input(self) |
| 135 |
|
| 136 |
def demux(self, *args, **kwargs): |
| 137 |
"""demux(streams=None, video=None, audio=None, subtitles=None, data=None) |
| 138 |
|
| 139 |
Yields a series of :class:`.Packet` from the given set of :class:`.Stream`:: |
| 140 |
|
| 141 |
for packet in container.demux(): |
| 142 |
# Do something with `packet`, often: |
| 143 |
for frame in packet.decode(): |
| 144 |
# Do something with `frame`. |
| 145 |
|
| 146 |
.. seealso:: :meth:`.StreamContainer.get` for the interpretation of |
| 147 |
the arguments. |
| 148 |
|
| 149 |
.. note:: The last packets are dummy packets that when decoded will flush the buffers. |
| 150 |
|
| 151 |
""" |
| 152 |
self._assert_open() |
| 153 |
|
| 154 |
streams: list[Stream] = self.streams.get(*args, **kwargs) |
| 155 |
if self.ptr.nb_streams == 0: |
| 156 |
return |
| 157 |
include_stream: cython.pointer[uint8_t] = cython.cast( |
| 158 |
cython.pointer[uint8_t], |
| 159 |
malloc(self.ptr.nb_streams * cython.sizeof(uint8_t)), |
| 160 |
) |
| 161 |
if include_stream == cython.NULL: |
| 162 |
raise MemoryError() |
| 163 |
|
| 164 |
i: cython.uint |
| 165 |
packet: Packet |
| 166 |
read_packet: cython.pointer[lib.AVPacket] |
| 167 |
ret: cython.int |
| 168 |
|
| 169 |
self.set_timeout(self.read_timeout) |
| 170 |
try: |
| 171 |
for i in range(self.ptr.nb_streams): |
| 172 |
include_stream[i] = 0 |
| 173 |
for stream in streams: |
| 174 |
i = stream.index |
| 175 |
if i >= self.ptr.nb_streams: |
| 176 |
raise ValueError(f"stream index {i} out of range") |
| 177 |
include_stream[i] = 1 |
| 178 |
|
| 179 |
# Pre-allocate a AVPacket that is reused as the read buffer. |
| 180 |
with cython.nogil: |
| 181 |
read_packet = lib.av_packet_alloc() |
| 182 |
if read_packet == cython.NULL: |
| 183 |
raise MemoryError("Could not allocate packet") |
| 184 |
|
| 185 |
while True: |
| 186 |
# Reset the read buffer |
| 187 |
with cython.nogil: |
| 188 |
lib.av_packet_unref(read_packet) |
| 189 |
try: |
| 190 |
self.start_timeout() |
| 191 |
with cython.nogil: |
| 192 |
ret = lib.av_read_frame(self.ptr, read_packet) |
| 193 |
self.err_check(ret) |
| 194 |
except EOFError: |
| 195 |
break |
| 196 |
|
| 197 |
if include_stream[read_packet.stream_index]: |
| 198 |
# If AVFMTCTX_NOHEADER is set in ctx_flags, then new streams |
| 199 |
# may also appear in av_read_frame(). |
| 200 |
# http://ffmpeg.org/doxygen/trunk/structAVFormatContext.html |
| 201 |
# TODO: find better way to handle this |
| 202 |
if read_packet.stream_index < len(self.streams): |
| 203 |
# Move the encoded data out of the read buffer into a |
| 204 |
# fresh Packet for the caller. |
| 205 |
packet = Packet() |
| 206 |
with cython.nogil: |
| 207 |
lib.av_packet_move_ref(packet.ptr, read_packet) |
| 208 |
packet._stream = self.streams[packet.ptr.stream_index] |
| 209 |
# Keep track of this so that remuxing is easier. |
| 210 |
packet.ptr.time_base = packet._stream.ptr.time_base |
| 211 |
yield packet |
| 212 |
|
| 213 |
# Flush! |
| 214 |
for i in range(self.ptr.nb_streams): |
| 215 |
if include_stream[i]: |
| 216 |
packet = Packet() |
| 217 |
packet._stream = self.streams[i] |
| 218 |
packet.ptr.time_base = packet._stream.ptr.time_base |
| 219 |
yield packet |
| 220 |
|
| 221 |
finally: |
| 222 |
self.set_timeout(None) |
| 223 |
free(include_stream) |
| 224 |
if read_packet != cython.NULL: |
| 225 |
lib.av_packet_free(cython.address(read_packet)) |
| 226 |
|
| 227 |
def decode(self, *args, **kwargs): |
| 228 |
"""decode(streams=None, video=None, audio=None, subtitles=None, data=None) |
| 229 |
|
| 230 |
Yields a series of :class:`.Frame` from the given set of streams:: |
| 231 |
|
| 232 |
for frame in container.decode(): |
| 233 |
# Do something with `frame`. |
| 234 |
|
| 235 |
.. seealso:: :meth:`.StreamContainer.get` for the interpretation of |
| 236 |
the arguments. |
| 237 |
|
| 238 |
""" |
| 239 |
self._assert_open() |
| 240 |
for packet in self.demux(*args, **kwargs): |
| 241 |
for frame in packet.decode(): |
| 242 |
yield frame |
| 243 |
|
| 244 |
def seek( |
| 245 |
self, |
| 246 |
offset, |
| 247 |
*, |
| 248 |
backward: cython.bint = True, |
| 249 |
any_frame: cython.bint = False, |
| 250 |
stream: Stream | None = None, |
| 251 |
unsupported_frame_offset: cython.bint = False, |
| 252 |
unsupported_byte_offset: cython.bint = False, |
| 253 |
): |
| 254 |
"""seek(offset, *, backward=True, any_frame=False, stream=None) |
| 255 |
|
| 256 |
Seek to a (key)frame nearest to the given timestamp. |
| 257 |
|
| 258 |
:param int offset: Time to seek to, expressed in``stream.time_base`` if ``stream`` |
| 259 |
is given, otherwise in :data:`av.time_base`. |
| 260 |
:param bool backward: If there is not a (key)frame at the given offset, |
| 261 |
look backwards for it. |
| 262 |
:param bool any_frame: Seek to any frame, not just a keyframe. |
| 263 |
:param Stream stream: The stream who's ``time_base`` the ``offset`` is in. |
| 264 |
|
| 265 |
:param bool unsupported_frame_offset: ``offset`` is a frame |
| 266 |
index instead of a time; not supported by any known format. |
| 267 |
:param bool unsupported_byte_offset: ``offset`` is a byte |
| 268 |
location in the file; not supported by any known format. |
| 269 |
|
| 270 |
After seeking, packets that you demux should correspond (roughly) to |
| 271 |
the position you requested. |
| 272 |
|
| 273 |
In most cases, the defaults of ``backwards = True`` and ``any_frame = False`` |
| 274 |
are the best course of action, followed by you demuxing/decoding to |
| 275 |
the position that you want. This is because to properly decode video frames |
| 276 |
you need to start from the previous keyframe. |
| 277 |
|
| 278 |
.. seealso:: :ffmpeg:`avformat_seek_file` for discussion of the flags. |
| 279 |
|
| 280 |
""" |
| 281 |
self._assert_open() |
| 282 |
|
| 283 |
if not isinstance(offset, int): |
| 284 |
raise TypeError("Container.seek only accepts integer offset.", type(offset)) |
| 285 |
|
| 286 |
c_offset: int64_t = offset |
| 287 |
flags: cython.int = 0 |
| 288 |
ret: cython.int |
| 289 |
|
| 290 |
if backward: |
| 291 |
flags |= lib.AVSEEK_FLAG_BACKWARD |
| 292 |
if any_frame: |
| 293 |
flags |= lib.AVSEEK_FLAG_ANY |
| 294 |
|
| 295 |
# If someone really wants (and to experiment), expose these. |
| 296 |
if unsupported_frame_offset: |
| 297 |
flags |= lib.AVSEEK_FLAG_FRAME |
| 298 |
if unsupported_byte_offset: |
| 299 |
flags |= lib.AVSEEK_FLAG_BYTE |
| 300 |
|
| 301 |
stream_index: cython.int = stream.index if stream else -1 |
| 302 |
with cython.nogil: |
| 303 |
ret = lib.av_seek_frame(self.ptr, stream_index, c_offset, flags) |
| 304 |
err_check(ret) |
| 305 |
|
| 306 |
self.flush_buffers() |
| 307 |
|
| 308 |
@cython.cfunc |
| 309 |
def flush_buffers(self): |
| 310 |
self._assert_open() |
| 311 |
|
| 312 |
stream: Stream |
| 313 |
codec_context: CodecContext |
| 314 |
|
| 315 |
for stream in self.streams: |
| 316 |
codec_context = stream.codec_context |
| 317 |
if codec_context: |
| 318 |
codec_context.flush_buffers() |