Debian Codegraph @

av/codec/codec.py

raw
1 from enum import Flag, IntEnum
2
3 import cython
4 from cython.cimports import libav as lib
5 from cython.cimports.av.audio.format import get_audio_format
6 from cython.cimports.av.codec.hwaccel import wrap_hwconfig
7 from cython.cimports.av.utils import avrational_to_fraction
8 from cython.cimports.av.video.format import VideoFormat, get_pix_fmt, get_video_format
9 from cython.cimports.libc.stdlib import free, malloc
10
11 _cinit_sentinel = cython.declare(object, object())
12
13
14 @cython.cfunc
15 def wrap_codec(ptr: cython.pointer[cython.const[lib.AVCodec]]) -> Codec:
16 codec: Codec = Codec(_cinit_sentinel)
17 codec.ptr = ptr
18 codec.is_encoder = lib.av_codec_is_encoder(ptr)
19 codec._init()
20 return codec
21
22
23 class Properties(Flag):
24 NONE = 0
25 INTRA_ONLY = lib.AV_CODEC_PROP_INTRA_ONLY
26 LOSSY = lib.AV_CODEC_PROP_LOSSY
27 LOSSLESS = lib.AV_CODEC_PROP_LOSSLESS
28 REORDER = lib.AV_CODEC_PROP_REORDER
29 BITMAP_SUB = lib.AV_CODEC_PROP_BITMAP_SUB
30 TEXT_SUB = lib.AV_CODEC_PROP_TEXT_SUB
31
32
33 class Capabilities(IntEnum):
34 none = 0
35 draw_horiz_band = lib.AV_CODEC_CAP_DRAW_HORIZ_BAND
36 dr1 = lib.AV_CODEC_CAP_DR1
37 hwaccel = 1 << 4
38 delay = lib.AV_CODEC_CAP_DELAY
39 small_last_frame = lib.AV_CODEC_CAP_SMALL_LAST_FRAME
40 hwaccel_vdpau = 1 << 7
41 experimental = lib.AV_CODEC_CAP_EXPERIMENTAL
42 channel_conf = lib.AV_CODEC_CAP_CHANNEL_CONF
43 neg_linesizes = 1 << 11
44 frame_threads = lib.AV_CODEC_CAP_FRAME_THREADS
45 slice_threads = lib.AV_CODEC_CAP_SLICE_THREADS
46 param_change = lib.AV_CODEC_CAP_PARAM_CHANGE
47 auto_threads = lib.AV_CODEC_CAP_OTHER_THREADS
48 variable_frame_size = lib.AV_CODEC_CAP_VARIABLE_FRAME_SIZE
49 avoid_probing = lib.AV_CODEC_CAP_AVOID_PROBING
50 hardware = lib.AV_CODEC_CAP_HARDWARE
51 hybrid = lib.AV_CODEC_CAP_HYBRID
52 encoder_reordered_opaque = 1 << 20
53 encoder_flush = 1 << 21
54 encoder_recon_frame = 1 << 22
55
56
57 class UnknownCodecError(ValueError):
58 pass
59
60
61 @cython.final
62 @cython.cclass
63 class Codec:
64 """Codec(name, mode='r')
65
66 :param str name: The codec name.
67 :param str mode: ``'r'`` for decoding or ``'w'`` for encoding.
68
69 This object exposes information about an available codec, and an avenue to
70 create a :class:`.CodecContext` to encode/decode directly.
71
72 ::
73
74 >>> codec = Codec('mpeg4', 'r')
75 >>> codec.name
76 'mpeg4'
77 >>> codec.type
78 'video'
79 >>> codec.is_encoder
80 False
81
82 """
83
84 def __cinit__(self, name, mode="r"):
85 if name is _cinit_sentinel:
86 return
87
88 if mode == "w":
89 self.ptr = lib.avcodec_find_encoder_by_name(name)
90 if not self.ptr:
91 self.desc = lib.avcodec_descriptor_get_by_name(name)
92 if self.desc:
93 self.ptr = lib.avcodec_find_encoder(self.desc.id)
94
95 elif mode == "r":
96 self.ptr = lib.avcodec_find_decoder_by_name(name)
97 if not self.ptr:
98 self.desc = lib.avcodec_descriptor_get_by_name(name)
99 if self.desc:
100 self.ptr = lib.avcodec_find_decoder(self.desc.id)
101
102 else:
103 raise ValueError('Invalid mode; must be "r" or "w".', mode)
104
105 self._init(name)
106
107 # Sanity check.
108 if (mode == "w") != self.is_encoder:
109 raise RuntimeError("Found codec does not match mode.", name, mode)
110
111 @cython.cfunc
112 def _init(self, name=None):
113 if not self.ptr:
114 raise UnknownCodecError(name)
115
116 if not self.desc:
117 self.desc = lib.avcodec_descriptor_get(self.ptr.id)
118 if not self.desc:
119 raise RuntimeError("No codec descriptor for %r." % name)
120
121 self.is_encoder = lib.av_codec_is_encoder(self.ptr)
122
123 # Sanity check.
124 if self.is_encoder and lib.av_codec_is_decoder(self.ptr):
125 raise RuntimeError("%s is both encoder and decoder.")
126
127 def __repr__(self):
128 mode = self.mode
129 return f"<av.{self.__class__.__name__} {self.name} {mode=}>"
130
131 def create(self, kind=None):
132 """Create a :class:`.CodecContext` for this codec.
133
134 :param str kind: Gives a hint to static type checkers for what exact CodecContext is used.
135 """
136 from .context import CodecContext
137
138 return CodecContext.create(self)
139
140 @property
141 def mode(self):
142 return "w" if self.is_encoder else "r"
143
144 @property
145 def is_decoder(self):
146 return not self.is_encoder
147
148 @property
149 def name(self):
150 return self.ptr.name or ""
151
152 @property
153 def canonical_name(self):
154 """
155 Returns the name of the codec, not a specific encoder.
156 """
157 return lib.avcodec_get_name(self.ptr.id)
158
159 @property
160 def long_name(self):
161 return self.ptr.long_name or ""
162
163 @property
164 def type(self):
165 """
166 The media type of this codec.
167
168 E.g: ``'audio'``, ``'video'``, ``'subtitle'``.
169
170 """
171 media_type = lib.av_get_media_type_string(self.ptr.type)
172 return "unknown" if media_type == cython.NULL else media_type
173
174 @property
175 def id(self):
176 return self.ptr.id
177
178 @property
179 def frame_rates(self):
180 """A list of supported frame rates (:class:`fractions.Fraction`), or ``None``."""
181 out: cython.pointer[cython.const[cython.void]] = cython.NULL
182 num: cython.int = 0
183 lib.avcodec_get_supported_config(
184 cython.NULL,
185 self.ptr,
186 lib.AV_CODEC_CONFIG_FRAME_RATE,
187 0,
188 cython.address(out),
189 cython.address(num),
190 )
191 if not out:
192 return
193 rates = cython.cast(cython.pointer[lib.AVRational], out)
194 return [avrational_to_fraction(cython.address(rates[i])) for i in range(num)]
195
196 @property
197 def audio_rates(self):
198 """A list of supported audio sample rates (``int``), or ``None``."""
199 out: cython.pointer[cython.const[cython.void]] = cython.NULL
200 num: cython.int = 0
201 lib.avcodec_get_supported_config(
202 cython.NULL,
203 self.ptr,
204 lib.AV_CODEC_CONFIG_SAMPLE_RATE,
205 0,
206 cython.address(out),
207 cython.address(num),
208 )
209 if not out:
210 return
211 rates = cython.cast(cython.pointer[cython.int], out)
212 return [rates[i] for i in range(num)]
213
214 @property
215 def video_formats(self):
216 """A list of supported :class:`.VideoFormat`, or ``None``."""
217 out: cython.pointer[cython.const[cython.void]] = cython.NULL
218 num: cython.int = 0
219 lib.avcodec_get_supported_config(
220 cython.NULL,
221 self.ptr,
222 lib.AV_CODEC_CONFIG_PIX_FORMAT,
223 0,
224 cython.address(out),
225 cython.address(num),
226 )
227 if not out:
228 return
229 fmts = cython.cast(cython.pointer[lib.AVPixelFormat], out)
230 return [get_video_format(fmts[i], 0, 0) for i in range(num)]
231
232 @property
233 def audio_formats(self):
234 """A list of supported :class:`.AudioFormat`, or ``None``."""
235 out: cython.pointer[cython.const[cython.void]] = cython.NULL
236 num: cython.int = 0
237 lib.avcodec_get_supported_config(
238 cython.NULL,
239 self.ptr,
240 lib.AV_CODEC_CONFIG_SAMPLE_FORMAT,
241 0,
242 cython.address(out),
243 cython.address(num),
244 )
245 if not out:
246 return
247 fmts = cython.cast(cython.pointer[lib.AVSampleFormat], out)
248 return [get_audio_format(fmts[i]) for i in range(num)]
249
250 @property
251 def hardware_configs(self):
252 if self._hardware_configs:
253 return self._hardware_configs
254 ret: list = []
255 i: cython.int = 0
256 ptr: cython.pointer[cython.const[lib.AVCodecHWConfig]]
257 while True:
258 ptr = lib.avcodec_get_hw_config(self.ptr, i)
259 if not ptr:
260 break
261 ret.append(wrap_hwconfig(ptr))
262 i += 1
263 self._hardware_configs = tuple(ret)
264 return self._hardware_configs
265
266 @property
267 def properties(self):
268 return self.desc.props
269
270 @property
271 def intra_only(self):
272 return bool(self.desc.props & lib.AV_CODEC_PROP_INTRA_ONLY)
273
274 @property
275 def lossy(self):
276 return bool(self.desc.props & lib.AV_CODEC_PROP_LOSSY)
277
278 @property
279 def lossless(self):
280 return bool(self.desc.props & lib.AV_CODEC_PROP_LOSSLESS)
281
282 @property
283 def reorder(self):
284 return bool(self.desc.props & lib.AV_CODEC_PROP_REORDER)
285
286 @property
287 def bitmap_sub(self):
288 return bool(self.desc.props & lib.AV_CODEC_PROP_BITMAP_SUB)
289
290 @property
291 def text_sub(self):
292 return bool(self.desc.props & lib.AV_CODEC_PROP_TEXT_SUB)
293
294 @property
295 def capabilities(self):
296 """
297 Get the capabilities bitmask of the codec.
298
299 This method returns an integer representing the codec capabilities bitmask,
300 which can be used to check specific codec features by performing bitwise
301 operations with the Capabilities enum values.
302
303 :example:
304
305 .. code-block:: python
306
307 from av.codec import Codec, Capabilities
308
309 codec = Codec("h264", "w")
310
311 # Check if the codec can be fed a final frame with a smaller size.
312 # This can be used to prevent truncation of the last audio samples.
313 small_last_frame = bool(codec.capabilities & Capabilities.small_last_frame)
314
315 :rtype: int
316 """
317 return self.ptr.capabilities
318
319 @property
320 def experimental(self):
321 """
322 Check if codec is experimental and is thus avoided in favor of non experimental encoders.
323
324 :rtype: bool
325 """
326 return bool(self.ptr.capabilities & lib.AV_CODEC_CAP_EXPERIMENTAL)
327
328 @property
329 def delay(self):
330 """
331 If true, encoder or decoder requires flushing with `None` at the end in order to give the complete and correct output.
332
333 :rtype: bool
334 """
335 return bool(self.ptr.capabilities & lib.AV_CODEC_CAP_DELAY)
336
337
338 @cython.cfunc
339 def get_codec_names():
340 names: cython.set = set()
341 ptr = cython.declare(cython.pointer[cython.const[lib.AVCodec]])
342 opaque: cython.p_void = cython.NULL
343 while True:
344 ptr = lib.av_codec_iterate(cython.address(opaque))
345 if ptr:
346 names.add(ptr.name)
347 else:
348 break
349 return names
350
351
352 codecs_available = get_codec_names()
353
354
355 def dump_codecs():
356 """Print information about available codecs."""
357
358 print(
359 """Codecs:
360 D..... = Decoding supported
361 .E.... = Encoding supported
362 ..V... = Video codec
363 ..A... = Audio codec
364 ..S... = Subtitle codec
365 ...I.. = Intra frame-only codec
366 ....L. = Lossy compression
367 .....S = Lossless compression
368 ------"""
369 )
370
371 for name in sorted(codecs_available):
372 try:
373 e_codec = Codec(name, "w")
374 except ValueError:
375 e_codec = None
376
377 try:
378 d_codec = Codec(name, "r")
379 except ValueError:
380 d_codec = None
381
382 # TODO: Assert these always have the same properties.
383 codec = e_codec or d_codec
384
385 try:
386 print(
387 " %s%s%s%s%s%s %-18s %s"
388 % (
389 ".D"[bool(d_codec)],
390 ".E"[bool(e_codec)],
391 codec.type[0].upper(),
392 ".I"[codec.intra_only],
393 ".L"[codec.lossy],
394 ".S"[codec.lossless],
395 codec.name,
396 codec.long_name,
397 )
398 )
399 except Exception as e:
400 print(f"...... {codec.name:<18} ERROR: {e}")
401
402
403 def dump_hwconfigs():
404 print("Hardware configs:")
405 for name in sorted(codecs_available):
406 try:
407 codec = Codec(name, "r")
408 except ValueError:
409 continue
410
411 configs = codec.hardware_configs
412 if not configs:
413 continue
414
415 print(" ", codec.name)
416 for config in configs:
417 print(" ", config)
418
419
420 def find_best_pix_fmt_of_list(pix_fmts, src_pix_fmt, has_alpha=False):
421 """
422 Find the best pixel format to convert to given a source format.
423
424 Wraps :ffmpeg:`avcodec_find_best_pix_fmt_of_list`.
425
426 :param pix_fmts: Iterable of pixel formats to choose from (str or VideoFormat).
427 :param src_pix_fmt: Source pixel format (str or VideoFormat).
428 :param bool has_alpha: Whether the source alpha channel is used.
429 :return: (best_format, loss)
430 :rtype: (VideoFormat | None, int)
431 """
432 src: lib.AVPixelFormat
433 best: lib.AVPixelFormat
434 c_list: cython.pointer[lib.AVPixelFormat] = cython.NULL
435 n: cython.Py_ssize_t
436 i: cython.Py_ssize_t
437 item: object
438 c_loss: cython.int
439
440 if pix_fmts is None:
441 raise TypeError("pix_fmts must not be None")
442
443 pix_fmts = tuple(pix_fmts)
444 if not pix_fmts:
445 return None, 0
446
447 if isinstance(src_pix_fmt, VideoFormat):
448 src = cython.cast(VideoFormat, src_pix_fmt).pix_fmt
449 else:
450 src = get_pix_fmt(cython.cast(str, src_pix_fmt))
451
452 n = len(pix_fmts)
453 c_list = cython.cast(
454 cython.pointer[lib.AVPixelFormat],
455 malloc((n + 1) * cython.sizeof(lib.AVPixelFormat)),
456 )
457 if c_list == cython.NULL:
458 raise MemoryError()
459
460 try:
461 for i in range(n):
462 item = pix_fmts[i]
463 if isinstance(item, VideoFormat):
464 c_list[i] = cython.cast(VideoFormat, item).pix_fmt
465 else:
466 c_list[i] = get_pix_fmt(cython.cast(str, item))
467 c_list[n] = lib.AV_PIX_FMT_NONE
468
469 c_loss = 0
470 best = lib.avcodec_find_best_pix_fmt_of_list(
471 c_list, src, 1 if has_alpha else 0, cython.address(c_loss)
472 )
473 return get_video_format(best, 0, 0), c_loss
474 finally:
475 if c_list != cython.NULL:
476 free(c_list)