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