| 1 |
from enum import Flag, IntEnum |
| 2 |
|
| 3 |
import cython |
| 4 |
from cython.cimports import libav as lib |
| 5 |
from cython.cimports.av.buffer import ByteSource, bytesource |
| 6 |
from cython.cimports.av.codec.codec import Codec, wrap_codec |
| 7 |
from cython.cimports.av.dictionary import Dictionary |
| 8 |
from cython.cimports.av.error import err_check |
| 9 |
from cython.cimports.av.packet import Packet |
| 10 |
from cython.cimports.av.utils import avrational_to_fraction, to_avrational |
| 11 |
from cython.cimports.libc.errno import EAGAIN |
| 12 |
from cython.cimports.libc.stdint import uint8_t |
| 13 |
from cython.cimports.libc.string import memcpy |
| 14 |
|
| 15 |
_cinit_sentinel = cython.declare(object, object()) |
| 16 |
|
| 17 |
|
| 18 |
@cython.cfunc |
| 19 |
def wrap_codec_context( |
| 20 |
c_ctx: cython.pointer[lib.AVCodecContext], |
| 21 |
c_codec: cython.pointer[cython.const[lib.AVCodec]], |
| 22 |
hwaccel: HWAccel, |
| 23 |
) -> CodecContext: |
| 24 |
"""Build an bv.CodecContext for an existing AVCodecContext.""" |
| 25 |
py_ctx: CodecContext |
| 26 |
|
| 27 |
if c_ctx.codec_type == lib.AVMEDIA_TYPE_VIDEO: |
| 28 |
from av.video.codeccontext import VideoCodecContext |
| 29 |
|
| 30 |
py_ctx = VideoCodecContext(_cinit_sentinel) |
| 31 |
elif c_ctx.codec_type == lib.AVMEDIA_TYPE_AUDIO: |
| 32 |
from av.audio.codeccontext import AudioCodecContext |
| 33 |
|
| 34 |
py_ctx = AudioCodecContext(_cinit_sentinel) |
| 35 |
elif c_ctx.codec_type == lib.AVMEDIA_TYPE_SUBTITLE: |
| 36 |
from av.subtitles.codeccontext import SubtitleCodecContext |
| 37 |
|
| 38 |
py_ctx = SubtitleCodecContext(_cinit_sentinel) |
| 39 |
else: |
| 40 |
py_ctx = CodecContext(_cinit_sentinel) |
| 41 |
|
| 42 |
py_ctx._init(c_ctx, c_codec, hwaccel) |
| 43 |
|
| 44 |
return py_ctx |
| 45 |
|
| 46 |
|
| 47 |
class ThreadType(Flag): |
| 48 |
NONE = 0 |
| 49 |
FRAME: "Decode more than one frame at once" = lib.FF_THREAD_FRAME |
| 50 |
SLICE: "Decode more than one part of a single frame at once" = lib.FF_THREAD_SLICE |
| 51 |
AUTO: "Decode using both FRAME and SLICE methods." = ( |
| 52 |
lib.FF_THREAD_SLICE | lib.FF_THREAD_FRAME |
| 53 |
) |
| 54 |
|
| 55 |
|
| 56 |
class Flags(IntEnum): |
| 57 |
unaligned = lib.AV_CODEC_FLAG_UNALIGNED |
| 58 |
qscale = lib.AV_CODEC_FLAG_QSCALE |
| 59 |
four_mv = lib.AV_CODEC_FLAG_4MV |
| 60 |
output_corrupt = lib.AV_CODEC_FLAG_OUTPUT_CORRUPT |
| 61 |
qpel = lib.AV_CODEC_FLAG_QPEL |
| 62 |
recon_frame = lib.AV_CODEC_FLAG_RECON_FRAME |
| 63 |
copy_opaque = lib.AV_CODEC_FLAG_COPY_OPAQUE |
| 64 |
frame_duration = lib.AV_CODEC_FLAG_FRAME_DURATION |
| 65 |
pass1 = lib.AV_CODEC_FLAG_PASS1 |
| 66 |
pass2 = lib.AV_CODEC_FLAG_PASS2 |
| 67 |
loop_filter = lib.AV_CODEC_FLAG_LOOP_FILTER |
| 68 |
gray = lib.AV_CODEC_FLAG_GRAY |
| 69 |
psnr = lib.AV_CODEC_FLAG_PSNR |
| 70 |
interlaced_dct = lib.AV_CODEC_FLAG_INTERLACED_DCT |
| 71 |
low_delay = lib.AV_CODEC_FLAG_LOW_DELAY |
| 72 |
global_header = lib.AV_CODEC_FLAG_GLOBAL_HEADER |
| 73 |
bitexact = lib.AV_CODEC_FLAG_BITEXACT |
| 74 |
ac_pred = lib.AV_CODEC_FLAG_AC_PRED |
| 75 |
interlaced_me = lib.AV_CODEC_FLAG_INTERLACED_ME |
| 76 |
closed_gop = lib.AV_CODEC_FLAG_CLOSED_GOP |
| 77 |
|
| 78 |
|
| 79 |
class Flags2(IntEnum): |
| 80 |
fast = lib.AV_CODEC_FLAG2_FAST |
| 81 |
no_output = lib.AV_CODEC_FLAG2_NO_OUTPUT |
| 82 |
local_header = lib.AV_CODEC_FLAG2_LOCAL_HEADER |
| 83 |
chunks = lib.AV_CODEC_FLAG2_CHUNKS |
| 84 |
ignore_crop = lib.AV_CODEC_FLAG2_IGNORE_CROP |
| 85 |
show_all = lib.AV_CODEC_FLAG2_SHOW_ALL |
| 86 |
export_mvs = lib.AV_CODEC_FLAG2_EXPORT_MVS |
| 87 |
skip_manual = lib.AV_CODEC_FLAG2_SKIP_MANUAL |
| 88 |
ro_flush_noop = lib.AV_CODEC_FLAG2_RO_FLUSH_NOOP |
| 89 |
|
| 90 |
|
| 91 |
@cython.cclass |
| 92 |
class CodecContext: |
| 93 |
@staticmethod |
| 94 |
def create(codec, mode=None, hwaccel=None): |
| 95 |
cy_codec: Codec = codec if isinstance(codec, Codec) else Codec(codec, mode) |
| 96 |
c_ctx: cython.pointer[lib.AVCodecContext] = lib.avcodec_alloc_context3( |
| 97 |
cy_codec.ptr |
| 98 |
) |
| 99 |
return wrap_codec_context(c_ctx, cy_codec.ptr, hwaccel) |
| 100 |
|
| 101 |
def __cinit__(self, sentinel=None, *args, **kwargs): |
| 102 |
if sentinel is not _cinit_sentinel: |
| 103 |
raise RuntimeError("Cannot instantiate CodecContext") |
| 104 |
|
| 105 |
self.options = {} |
| 106 |
self.stream_index = -1 # This is set by the container immediately. |
| 107 |
self.is_open = False |
| 108 |
|
| 109 |
@cython.cfunc |
| 110 |
def _init( |
| 111 |
self, |
| 112 |
ptr: cython.pointer[lib.AVCodecContext], |
| 113 |
codec: cython.pointer[cython.const[lib.AVCodec]], |
| 114 |
hwaccel: HWAccel, |
| 115 |
): |
| 116 |
self.ptr = ptr |
| 117 |
if self.ptr.codec and codec and self.ptr.codec != codec: |
| 118 |
raise RuntimeError("Wrapping CodecContext with mismatched codec.") |
| 119 |
self.codec = wrap_codec(codec if codec != cython.NULL else self.ptr.codec) |
| 120 |
self.hwaccel = hwaccel |
| 121 |
|
| 122 |
# Set reasonable threading defaults. |
| 123 |
self.ptr.thread_count = 0 # use as many threads as there are CPUs. |
| 124 |
self.ptr.thread_type = 0x02 # thread within a frame. Does not change the API. |
| 125 |
|
| 126 |
@property |
| 127 |
def flags(self): |
| 128 |
""" |
| 129 |
Get and set the flags bitmask of CodecContext. |
| 130 |
|
| 131 |
:rtype: int |
| 132 |
""" |
| 133 |
return self.ptr.flags |
| 134 |
|
| 135 |
@flags.setter |
| 136 |
def flags(self, value: cython.int): |
| 137 |
self.ptr.flags = value |
| 138 |
|
| 139 |
@property |
| 140 |
def qscale(self): |
| 141 |
""" |
| 142 |
Use fixed qscale. |
| 143 |
|
| 144 |
:rtype: bool |
| 145 |
""" |
| 146 |
return bool(self.ptr.flags & lib.AV_CODEC_FLAG_QSCALE) |
| 147 |
|
| 148 |
@qscale.setter |
| 149 |
def qscale(self, value): |
| 150 |
if value: |
| 151 |
self.ptr.flags |= lib.AV_CODEC_FLAG_QSCALE |
| 152 |
else: |
| 153 |
self.ptr.flags &= ~lib.AV_CODEC_FLAG_QSCALE |
| 154 |
|
| 155 |
@property |
| 156 |
def copy_opaque(self): |
| 157 |
return bool(self.ptr.flags & lib.AV_CODEC_FLAG_COPY_OPAQUE) |
| 158 |
|
| 159 |
@copy_opaque.setter |
| 160 |
def copy_opaque(self, value): |
| 161 |
if value: |
| 162 |
self.ptr.flags |= lib.AV_CODEC_FLAG_COPY_OPAQUE |
| 163 |
else: |
| 164 |
self.ptr.flags &= ~lib.AV_CODEC_FLAG_COPY_OPAQUE |
| 165 |
|
| 166 |
@property |
| 167 |
def flags2(self): |
| 168 |
""" |
| 169 |
Get and set the flags2 bitmask of CodecContext. |
| 170 |
|
| 171 |
:rtype: int |
| 172 |
""" |
| 173 |
return self.ptr.flags2 |
| 174 |
|
| 175 |
@flags2.setter |
| 176 |
def flags2(self, value: cython.int): |
| 177 |
self.ptr.flags2 = value |
| 178 |
|
| 179 |
@property |
| 180 |
def extradata(self): |
| 181 |
if self.ptr is cython.NULL: |
| 182 |
return None |
| 183 |
if self.ptr.extradata_size > 0: |
| 184 |
return cython.cast( |
| 185 |
bytes, |
| 186 |
cython.cast(cython.pointer[uint8_t], self.ptr.extradata)[ |
| 187 |
: self.ptr.extradata_size |
| 188 |
], |
| 189 |
) |
| 190 |
return None |
| 191 |
|
| 192 |
@extradata.setter |
| 193 |
def extradata(self, data): |
| 194 |
if data is None: |
| 195 |
lib.av_freep(cython.address(self.ptr.extradata)) |
| 196 |
self.ptr.extradata_size = 0 |
| 197 |
else: |
| 198 |
source = bytesource(data) |
| 199 |
self.ptr.extradata = cython.cast( |
| 200 |
cython.pointer[uint8_t], |
| 201 |
lib.av_realloc( |
| 202 |
self.ptr.extradata, source.length + lib.AV_INPUT_BUFFER_PADDING_SIZE |
| 203 |
), |
| 204 |
) |
| 205 |
if not self.ptr.extradata: |
| 206 |
raise MemoryError("Cannot allocate extradata") |
| 207 |
memcpy(self.ptr.extradata, source.ptr, source.length) |
| 208 |
self.ptr.extradata_size = source.length |
| 209 |
|
| 210 |
@property |
| 211 |
def extradata_size(self): |
| 212 |
return self.ptr.extradata_size |
| 213 |
|
| 214 |
@property |
| 215 |
def is_encoder(self): |
| 216 |
if self.ptr is cython.NULL: |
| 217 |
return False |
| 218 |
return lib.av_codec_is_encoder(self.ptr.codec) |
| 219 |
|
| 220 |
@property |
| 221 |
def is_decoder(self): |
| 222 |
if self.ptr is cython.NULL: |
| 223 |
return False |
| 224 |
return lib.av_codec_is_decoder(self.ptr.codec) |
| 225 |
|
| 226 |
@cython.ccall |
| 227 |
def open(self, strict: cython.bint = True): |
| 228 |
if self.is_open: |
| 229 |
if strict: |
| 230 |
raise ValueError("CodecContext is already open.") |
| 231 |
return |
| 232 |
|
| 233 |
options: Dictionary = Dictionary() |
| 234 |
options.update(self.options or {}) |
| 235 |
|
| 236 |
if not self.ptr.time_base.num and self.is_encoder: |
| 237 |
if self.type == "video": |
| 238 |
self.ptr.time_base.num = self.ptr.framerate.den or 1 |
| 239 |
self.ptr.time_base.den = self.ptr.framerate.num or lib.AV_TIME_BASE |
| 240 |
elif self.type == "audio": |
| 241 |
self.ptr.time_base.num = 1 |
| 242 |
self.ptr.time_base.den = self.ptr.sample_rate |
| 243 |
else: |
| 244 |
self.ptr.time_base.num = 1 |
| 245 |
self.ptr.time_base.den = lib.AV_TIME_BASE |
| 246 |
|
| 247 |
err_check( |
| 248 |
lib.avcodec_open2(self.ptr, self.codec.ptr, cython.address(options.ptr)), |
| 249 |
f'avcodec_open2("{self.codec.name}", {self.options})', |
| 250 |
) |
| 251 |
self.is_open = True |
| 252 |
self.options = dict(options) |
| 253 |
|
| 254 |
def __dealloc__(self): |
| 255 |
if self.ptr: |
| 256 |
lib.av_freep(cython.address(self.ptr.extradata)) |
| 257 |
lib.avcodec_free_context(cython.address(self.ptr)) |
| 258 |
if self.parser: |
| 259 |
lib.av_parser_close(self.parser) |
| 260 |
|
| 261 |
def __repr__(self): |
| 262 |
_type = self.type or "<notype>" |
| 263 |
name = self.name or "<nocodec>" |
| 264 |
return f"<av.{self.__class__.__name__} {_type}/{name} at 0x{id(self):x}>" |
| 265 |
|
| 266 |
def parse(self, raw_input=None): |
| 267 |
"""Split up a byte stream into list of :class:`.Packet`. |
| 268 |
|
| 269 |
This is only effectively splitting up a byte stream, and does no |
| 270 |
actual interpretation of the data. |
| 271 |
|
| 272 |
It will return all packets that are fully contained within the given |
| 273 |
input, and will buffer partial packets until they are complete. |
| 274 |
|
| 275 |
Any timing information the parser is able to infer (``pts``, ``dts``, |
| 276 |
``duration``, ``pos`` and the keyframe flag) is assigned onto the |
| 277 |
returned packets. Fields the parser cannot determine are left unset. |
| 278 |
|
| 279 |
:param ByteSource raw_input: A chunk of a byte-stream to process. |
| 280 |
Anything that can be turned into a :class:`.ByteSource` is fine. |
| 281 |
``None`` or empty inputs will flush the parser's buffers. |
| 282 |
|
| 283 |
:return: ``list`` of :class:`.Packet` newly available. |
| 284 |
|
| 285 |
""" |
| 286 |
|
| 287 |
if not self.parser: |
| 288 |
self.parser = lib.av_parser_init(self.codec.ptr.id) |
| 289 |
if not self.parser: |
| 290 |
raise ValueError(f"No parser for {self.codec.name}") |
| 291 |
|
| 292 |
source: ByteSource = bytesource(raw_input, allow_none=True) |
| 293 |
|
| 294 |
in_data: cython.p_uchar = source.ptr if source is not None else cython.NULL |
| 295 |
in_size: cython.int = source.length if source is not None else 0 |
| 296 |
|
| 297 |
out_data: cython.p_uchar |
| 298 |
out_size: cython.int |
| 299 |
consumed: cython.int |
| 300 |
packet: Packet = None |
| 301 |
packets: list = [] |
| 302 |
|
| 303 |
while True: |
| 304 |
with cython.nogil: |
| 305 |
consumed = lib.av_parser_parse2( |
| 306 |
self.parser, |
| 307 |
self.ptr, |
| 308 |
cython.address(out_data), |
| 309 |
cython.address(out_size), |
| 310 |
in_data, |
| 311 |
in_size, |
| 312 |
lib.AV_NOPTS_VALUE, |
| 313 |
lib.AV_NOPTS_VALUE, |
| 314 |
0, |
| 315 |
) |
| 316 |
err_check(consumed) |
| 317 |
|
| 318 |
if out_size: |
| 319 |
# We copy the data immediately, as we have yet to figure out |
| 320 |
# the expected lifetime of the buffer we get back. All of the |
| 321 |
# examples decode it immediately. |
| 322 |
# |
| 323 |
# We've also tried: |
| 324 |
# packet = Packet() |
| 325 |
# packet.data = out_data |
| 326 |
# packet.size = out_size |
| 327 |
# packet.source = source |
| 328 |
# |
| 329 |
# ... but this results in corruption. |
| 330 |
|
| 331 |
packet = Packet(out_size) |
| 332 |
memcpy(packet.ptr.data, out_data, out_size) |
| 333 |
|
| 334 |
# Propagate the timing information the parser inferred for |
| 335 |
# this frame onto the packet (mirrors FFmpeg's parse_packet). |
| 336 |
packet.ptr.pts = self.parser.pts |
| 337 |
packet.ptr.dts = self.parser.dts |
| 338 |
packet.ptr.pos = self.parser.pos |
| 339 |
if self.parser.duration: |
| 340 |
packet.ptr.duration = self.parser.duration |
| 341 |
if self.parser.key_frame == 1: |
| 342 |
packet.ptr.flags |= lib.AV_PKT_FLAG_KEY |
| 343 |
|
| 344 |
packets.append(packet) |
| 345 |
|
| 346 |
if not in_size: |
| 347 |
# This was a flush. Only one packet should ever be returned. |
| 348 |
break |
| 349 |
|
| 350 |
in_data += consumed |
| 351 |
in_size -= consumed |
| 352 |
|
| 353 |
if not in_size: |
| 354 |
break |
| 355 |
|
| 356 |
return packets |
| 357 |
|
| 358 |
@property |
| 359 |
def is_hwaccel(self): |
| 360 |
""" |
| 361 |
Returns ``True`` if this codec context is hardware accelerated, ``False`` otherwise. |
| 362 |
""" |
| 363 |
return self.hwaccel_ctx is not None |
| 364 |
|
| 365 |
def _send_frame_and_recv(self, frame: Frame | None): |
| 366 |
packet: Packet |
| 367 |
res: cython.int |
| 368 |
with cython.nogil: |
| 369 |
res = lib.avcodec_send_frame( |
| 370 |
self.ptr, frame.ptr if frame is not None else cython.NULL |
| 371 |
) |
| 372 |
err_check(res, "avcodec_send_frame()") |
| 373 |
|
| 374 |
packet = self._recv_packet() |
| 375 |
while packet: |
| 376 |
yield packet |
| 377 |
packet = self._recv_packet() |
| 378 |
|
| 379 |
@cython.cfunc |
| 380 |
def _prepare_frames_for_encode(self, frame: Frame | None) -> list: |
| 381 |
return [frame] |
| 382 |
|
| 383 |
@cython.cfunc |
| 384 |
def _alloc_next_frame(self) -> Frame: |
| 385 |
raise NotImplementedError("Base CodecContext cannot decode.") |
| 386 |
|
| 387 |
@cython.cfunc |
| 388 |
def _recv_frame(self): |
| 389 |
if not self._next_frame: |
| 390 |
self._next_frame = self._alloc_next_frame() |
| 391 |
|
| 392 |
frame: Frame = self._next_frame |
| 393 |
res: cython.int |
| 394 |
|
| 395 |
with cython.nogil: |
| 396 |
res = lib.avcodec_receive_frame(self.ptr, frame.ptr) |
| 397 |
|
| 398 |
if res == -EAGAIN or res == lib.AVERROR_EOF: |
| 399 |
return |
| 400 |
|
| 401 |
err_check(res, "avcodec_receive_frame()") |
| 402 |
frame = self._transfer_hwframe(frame) |
| 403 |
|
| 404 |
if not res: |
| 405 |
self._next_frame = None |
| 406 |
return frame |
| 407 |
|
| 408 |
@cython.cfunc |
| 409 |
def _transfer_hwframe(self, frame: Frame): |
| 410 |
return frame |
| 411 |
|
| 412 |
@cython.cfunc |
| 413 |
def _recv_packet(self): |
| 414 |
packet: Packet = Packet() |
| 415 |
res: cython.int |
| 416 |
|
| 417 |
with cython.nogil: |
| 418 |
res = lib.avcodec_receive_packet(self.ptr, packet.ptr) |
| 419 |
|
| 420 |
if res == -EAGAIN or res == lib.AVERROR_EOF: |
| 421 |
return |
| 422 |
|
| 423 |
err_check(res, "avcodec_receive_packet()") |
| 424 |
if not res: |
| 425 |
return packet |
| 426 |
|
| 427 |
@cython.cfunc |
| 428 |
def _prepare_and_time_rebase_frames_for_encode(self, frame: Frame): |
| 429 |
if self.ptr.codec_type not in [lib.AVMEDIA_TYPE_VIDEO, lib.AVMEDIA_TYPE_AUDIO]: |
| 430 |
raise NotImplementedError("Encoding is only supported for audio and video.") |
| 431 |
|
| 432 |
self.open(strict=False) |
| 433 |
|
| 434 |
frames = self._prepare_frames_for_encode(frame) |
| 435 |
|
| 436 |
# Assert the frames are in our time base. |
| 437 |
# TODO: Don't mutate time. |
| 438 |
for frame in frames: |
| 439 |
if frame is not None: |
| 440 |
frame._rebase_time(self.ptr.time_base) |
| 441 |
|
| 442 |
return frames |
| 443 |
|
| 444 |
@cython.ccall |
| 445 |
def encode(self, frame: Frame | None = None): |
| 446 |
"""Encode a list of :class:`.Packet` from the given :class:`.Frame`.""" |
| 447 |
res = [] |
| 448 |
for frame in self._prepare_and_time_rebase_frames_for_encode(frame): |
| 449 |
for packet in self._send_frame_and_recv(frame): |
| 450 |
self._setup_encoded_packet(packet) |
| 451 |
res.append(packet) |
| 452 |
return res |
| 453 |
|
| 454 |
def encode_lazy(self, frame: Frame | None = None): |
| 455 |
for frame in self._prepare_and_time_rebase_frames_for_encode(frame): |
| 456 |
for packet in self._send_frame_and_recv(frame): |
| 457 |
self._setup_encoded_packet(packet) |
| 458 |
yield packet |
| 459 |
|
| 460 |
@cython.cfunc |
| 461 |
def _setup_encoded_packet(self, packet: Packet): |
| 462 |
# We coerced the frame's time_base into the CodecContext's during encoding, |
| 463 |
# and FFmpeg copied the frame's pts/dts to the packet, so keep track of |
| 464 |
# this time_base in case the frame needs to be muxed to a container with |
| 465 |
# a different time_base. |
| 466 |
# |
| 467 |
# NOTE: if the CodecContext's time_base is altered during encoding, all bets |
| 468 |
# are off! |
| 469 |
packet.ptr.time_base = self.ptr.time_base |
| 470 |
|
| 471 |
@cython.ccall |
| 472 |
def decode(self, packet: Packet | None = None): |
| 473 |
"""Decode a list of :class:`.Frame` from the given :class:`.Packet`. |
| 474 |
|
| 475 |
If the packet is None, the buffers will be flushed. This is useful if |
| 476 |
you do not want the library to automatically re-order frames for you |
| 477 |
(if they are encoded with a codec that has B-frames). |
| 478 |
|
| 479 |
.. warning:: |
| 480 |
|
| 481 |
This method is **not thread-safe**. Calling :meth:`decode` concurrently |
| 482 |
from multiple threads on the same :class:`CodecContext` will corrupt |
| 483 |
internal FFmpeg state and likely cause a crash (segfault). FFmpeg 8.1 |
| 484 |
enforces this more strictly than earlier releases. If you need to decode |
| 485 |
from multiple threads, give each thread its own :class:`CodecContext`. |
| 486 |
|
| 487 |
""" |
| 488 |
if not self.codec.ptr: |
| 489 |
raise ValueError("cannot decode unknown codec") |
| 490 |
|
| 491 |
self.open(strict=False) |
| 492 |
|
| 493 |
res: cython.int |
| 494 |
with cython.nogil: |
| 495 |
res = lib.avcodec_send_packet( |
| 496 |
self.ptr, packet.ptr if packet is not None else cython.NULL |
| 497 |
) |
| 498 |
err_check(res, "avcodec_send_packet()") |
| 499 |
|
| 500 |
out: list = [] |
| 501 |
frame = self._recv_frame() |
| 502 |
while frame: |
| 503 |
self._setup_decoded_frame(frame, packet) |
| 504 |
out.append(frame) |
| 505 |
frame = self._recv_frame() |
| 506 |
return out |
| 507 |
|
| 508 |
@cython.ccall |
| 509 |
def flush_buffers(self): |
| 510 |
"""Reset the internal codec state and discard all internal buffers. |
| 511 |
|
| 512 |
Should be called before you start decoding from a new position e.g. |
| 513 |
when seeking or when switching to a different stream. |
| 514 |
|
| 515 |
""" |
| 516 |
if self.is_open: |
| 517 |
with cython.nogil: |
| 518 |
lib.avcodec_flush_buffers(self.ptr) |
| 519 |
|
| 520 |
@cython.cfunc |
| 521 |
def _setup_decoded_frame(self, frame: Frame, packet: Packet | None): |
| 522 |
# Propagate our manual times. |
| 523 |
# While decoding, frame times are in stream time_base, which PyAV |
| 524 |
# is carrying around. |
| 525 |
# TODO: Somehow get this from the stream so we can not pass the |
| 526 |
# packet here (because flushing packets are bogus). |
| 527 |
if packet is not None: |
| 528 |
frame._time_base = packet.ptr.time_base |
| 529 |
|
| 530 |
@property |
| 531 |
def name(self): |
| 532 |
return self.codec.name |
| 533 |
|
| 534 |
@property |
| 535 |
def type(self): |
| 536 |
return self.codec.type |
| 537 |
|
| 538 |
@property |
| 539 |
def profiles(self): |
| 540 |
""" |
| 541 |
List the available profiles for this stream. |
| 542 |
|
| 543 |
:type: list[str] |
| 544 |
""" |
| 545 |
ret: list = [] |
| 546 |
if not self.ptr.codec or not self.codec.desc or not self.codec.desc.profiles: |
| 547 |
return ret |
| 548 |
|
| 549 |
# Profiles are always listed in the codec descriptor, but not necessarily in |
| 550 |
# the codec itself. So use the descriptor here. |
| 551 |
desc = self.codec.desc |
| 552 |
i: cython.int = 0 |
| 553 |
while desc.profiles[i].profile != lib.AV_PROFILE_UNKNOWN: |
| 554 |
ret.append(desc.profiles[i].name) |
| 555 |
i += 1 |
| 556 |
|
| 557 |
return ret |
| 558 |
|
| 559 |
@property |
| 560 |
def profile(self): |
| 561 |
if not self.ptr.codec or not self.codec.desc or not self.codec.desc.profiles: |
| 562 |
return |
| 563 |
|
| 564 |
# Profiles are always listed in the codec descriptor, but not necessarily in |
| 565 |
# the codec itself. So use the descriptor here. |
| 566 |
desc = self.codec.desc |
| 567 |
i: cython.int = 0 |
| 568 |
while desc.profiles[i].profile != lib.AV_PROFILE_UNKNOWN: |
| 569 |
if desc.profiles[i].profile == self.ptr.profile: |
| 570 |
return desc.profiles[i].name |
| 571 |
i += 1 |
| 572 |
|
| 573 |
@profile.setter |
| 574 |
def profile(self, value): |
| 575 |
if not self.codec or not self.codec.desc or not self.codec.desc.profiles: |
| 576 |
return |
| 577 |
|
| 578 |
# Profiles are always listed in the codec descriptor, but not necessarily in |
| 579 |
# the codec itself. So use the descriptor here. |
| 580 |
desc = self.codec.desc |
| 581 |
i: cython.int = 0 |
| 582 |
while desc.profiles[i].profile != lib.AV_PROFILE_UNKNOWN: |
| 583 |
if desc.profiles[i].name == value: |
| 584 |
self.ptr.profile = desc.profiles[i].profile |
| 585 |
return |
| 586 |
i += 1 |
| 587 |
|
| 588 |
@property |
| 589 |
def time_base(self): |
| 590 |
if self.is_decoder: |
| 591 |
raise RuntimeError("Cannot access 'time_base' as a decoder") |
| 592 |
return avrational_to_fraction(cython.address(self.ptr.time_base)) |
| 593 |
|
| 594 |
@time_base.setter |
| 595 |
def time_base(self, value): |
| 596 |
if self.is_decoder: |
| 597 |
raise RuntimeError("Cannot access 'time_base' as a decoder") |
| 598 |
to_avrational(value, cython.address(self.ptr.time_base)) |
| 599 |
|
| 600 |
@property |
| 601 |
def codec_tag(self): |
| 602 |
return self.ptr.codec_tag.to_bytes(4, byteorder="little", signed=False).decode( |
| 603 |
encoding="ascii" |
| 604 |
) |
| 605 |
|
| 606 |
@codec_tag.setter |
| 607 |
def codec_tag(self, value): |
| 608 |
if isinstance(value, str) and len(value) == 4: |
| 609 |
self.ptr.codec_tag = int.from_bytes( |
| 610 |
value.encode(encoding="ascii"), byteorder="little", signed=False |
| 611 |
) |
| 612 |
else: |
| 613 |
raise ValueError("Codec tag should be a 4 character string.") |
| 614 |
|
| 615 |
@property |
| 616 |
@cython.cdivision(True) |
| 617 |
def global_quality(self): |
| 618 |
"""Global quality for codecs which cannot change it per frame. |
| 619 |
|
| 620 |
Stored internally in lambda units; this property converts to/from |
| 621 |
QP units using ``FF_QP2LAMBDA``. |
| 622 |
|
| 623 |
Wraps :ffmpeg:`AVCodecContext.global_quality`. |
| 624 |
|
| 625 |
""" |
| 626 |
return self.ptr.global_quality // lib.FF_QP2LAMBDA |
| 627 |
|
| 628 |
@global_quality.setter |
| 629 |
def global_quality(self, value: cython.int): |
| 630 |
self.ptr.global_quality = value * lib.FF_QP2LAMBDA |
| 631 |
|
| 632 |
@property |
| 633 |
def bit_rate(self): |
| 634 |
return self.ptr.bit_rate if self.ptr.bit_rate > 0 else None |
| 635 |
|
| 636 |
@bit_rate.setter |
| 637 |
def bit_rate(self, value: cython.int): |
| 638 |
self.ptr.bit_rate = value |
| 639 |
|
| 640 |
@property |
| 641 |
def max_bit_rate(self): |
| 642 |
if self.ptr.rc_max_rate > 0: |
| 643 |
return self.ptr.rc_max_rate |
| 644 |
else: |
| 645 |
return None |
| 646 |
|
| 647 |
@property |
| 648 |
def bit_rate_tolerance(self): |
| 649 |
self.ptr.bit_rate_tolerance |
| 650 |
|
| 651 |
@bit_rate_tolerance.setter |
| 652 |
def bit_rate_tolerance(self, value: cython.int): |
| 653 |
self.ptr.bit_rate_tolerance = value |
| 654 |
|
| 655 |
@property |
| 656 |
def thread_count(self): |
| 657 |
"""How many threads to use; 0 means auto. |
| 658 |
|
| 659 |
Wraps :ffmpeg:`AVCodecContext.thread_count`. |
| 660 |
|
| 661 |
""" |
| 662 |
return self.ptr.thread_count |
| 663 |
|
| 664 |
@thread_count.setter |
| 665 |
def thread_count(self, value: cython.int): |
| 666 |
if self.is_open: |
| 667 |
raise RuntimeError("Cannot change thread_count after codec is open.") |
| 668 |
self.ptr.thread_count = value |
| 669 |
|
| 670 |
@property |
| 671 |
def thread_type(self): |
| 672 |
"""One of :class:`.ThreadType`. |
| 673 |
|
| 674 |
Wraps :ffmpeg:`AVCodecContext.thread_type`. |
| 675 |
|
| 676 |
""" |
| 677 |
return ThreadType(self.ptr.thread_type) |
| 678 |
|
| 679 |
@thread_type.setter |
| 680 |
def thread_type(self, value): |
| 681 |
if self.is_open: |
| 682 |
raise RuntimeError("Cannot change thread_type after codec is open.") |
| 683 |
if type(value) is int: |
| 684 |
self.ptr.thread_type = value |
| 685 |
elif type(value) is str: |
| 686 |
self.ptr.thread_type = ThreadType[value].value |
| 687 |
else: |
| 688 |
self.ptr.thread_type = value.value |
| 689 |
|
| 690 |
@property |
| 691 |
def skip_frame(self): |
| 692 |
"""Returns one of the following str literals: |
| 693 |
|
| 694 |
"NONE" Discard nothing |
| 695 |
"DEFAULT" Discard useless packets like 0 size packets in AVI |
| 696 |
"NONREF" Discard all non reference |
| 697 |
"BIDIR" Discard all bidirectional frames |
| 698 |
"NONINTRA" Discard all non intra frames |
| 699 |
"NONKEY Discard all frames except keyframes |
| 700 |
"ALL" Discard all |
| 701 |
|
| 702 |
Wraps :ffmpeg:`AVCodecContext.skip_frame`. |
| 703 |
""" |
| 704 |
value = self.ptr.skip_frame |
| 705 |
if value == lib.AVDISCARD_NONE: |
| 706 |
return "NONE" |
| 707 |
if value == lib.AVDISCARD_DEFAULT: |
| 708 |
return "DEFAULT" |
| 709 |
if value == lib.AVDISCARD_NONREF: |
| 710 |
return "NONREF" |
| 711 |
if value == lib.AVDISCARD_BIDIR: |
| 712 |
return "BIDIR" |
| 713 |
if value == lib.AVDISCARD_NONINTRA: |
| 714 |
return "NONINTRA" |
| 715 |
if value == lib.AVDISCARD_NONKEY: |
| 716 |
return "NONKEY" |
| 717 |
if value == lib.AVDISCARD_ALL: |
| 718 |
return "ALL" |
| 719 |
return f"{value}" |
| 720 |
|
| 721 |
@skip_frame.setter |
| 722 |
def skip_frame(self, value): |
| 723 |
if value == "NONE": |
| 724 |
self.ptr.skip_frame = lib.AVDISCARD_NONE |
| 725 |
elif value == "DEFAULT": |
| 726 |
self.ptr.skip_frame = lib.AVDISCARD_DEFAULT |
| 727 |
elif value == "NONREF": |
| 728 |
self.ptr.skip_frame = lib.AVDISCARD_NONREF |
| 729 |
elif value == "BIDIR": |
| 730 |
self.ptr.skip_frame = lib.AVDISCARD_BIDIR |
| 731 |
elif value == "NONINTRA": |
| 732 |
self.ptr.skip_frame = lib.AVDISCARD_NONINTRA |
| 733 |
elif value == "NONKEY": |
| 734 |
self.ptr.skip_frame = lib.AVDISCARD_NONKEY |
| 735 |
elif value == "ALL": |
| 736 |
self.ptr.skip_frame = lib.AVDISCARD_ALL |
| 737 |
else: |
| 738 |
raise ValueError("Invalid skip_frame type") |
| 739 |
|
| 740 |
@property |
| 741 |
def delay(self): |
| 742 |
"""Codec delay. |
| 743 |
|
| 744 |
Wraps :ffmpeg:`AVCodecContext.delay`. |
| 745 |
|
| 746 |
""" |
| 747 |
return self.ptr.delay |