Debian Codegraph @

av/utils.py

raw
1 # type: ignore
2 from fractions import Fraction
3
4 import cython
5 from cython.cimports import libav as lib
6 from cython.cimports.av.error import err_check
7
8
9 @cython.cfunc
10 def _decode(s: cython.pointer[cython.char], encoding, errors) -> str:
11 return cython.cast(bytes, s).decode(encoding, errors)
12
13
14 @cython.cfunc
15 def avdict_to_dict(
16 input: cython.pointer[lib.AVDictionary], encoding: str, errors: str
17 ) -> dict:
18 element: cython.pointer[lib.AVDictionaryEntry] = cython.NULL
19 output: dict = {}
20 while True:
21 element = lib.av_dict_get(input, "", element, lib.AV_DICT_IGNORE_SUFFIX)
22 if element == cython.NULL:
23 break
24 output[_decode(element.key, encoding, errors)] = _decode(
25 element.value, encoding, errors
26 )
27
28 return output
29
30
31 @cython.cfunc
32 def dict_to_avdict(
33 dst: cython.pointer[cython.pointer[lib.AVDictionary]],
34 src: dict,
35 encoding: str,
36 errors: str,
37 ):
38 lib.av_dict_free(dst)
39 for key, value in src.items():
40 err_check(
41 lib.av_dict_set(
42 dst, key.encode(encoding, errors), value.encode(encoding, errors), 0
43 )
44 )
45
46
47 @cython.cfunc
48 def avrational_to_fraction(
49 input: cython.pointer[cython.const[lib.AVRational]],
50 ) -> object:
51 if input.num and input.den:
52 return Fraction(input.num, input.den)
53 return None
54
55
56 @cython.cfunc
57 def to_avrational(frac: object, input: cython.pointer[lib.AVRational]) -> cython.void:
58 input.num = frac.numerator
59 input.den = frac.denominator
60
61
62 @cython.cfunc
63 def check_ndarray(array: object, dtype: object, ndim: cython.int) -> cython.void:
64 """
65 Check a numpy array has the expected data type and number of dimensions.
66 """
67 if array.dtype != dtype:
68 raise ValueError(
69 f"Expected numpy array with dtype `{dtype}` but got `{array.dtype}`"
70 )
71 if array.ndim != ndim:
72 raise ValueError(
73 f"Expected numpy array with ndim `{ndim}` but got `{array.ndim}`"
74 )