| 1 |
# type:ignore |
| 2 |
import cython |
| 3 |
import cython.cimports.libav as lib |
| 4 |
from cython import NULL, sizeof |
| 5 |
from cython.cimports.libc.stdint import uint8_t, uintptr_t |
| 6 |
from cython.cimports.libc.string import memcpy |
| 7 |
|
| 8 |
u8ptr = cython.typedef(cython.pointer[uint8_t]) |
| 9 |
|
| 10 |
|
| 11 |
@cython.cfunc |
| 12 |
@cython.exceptval(check=False) |
| 13 |
@cython.nogil |
| 14 |
def key_free(opaque: cython.p_void, data: u8ptr) -> cython.void: |
| 15 |
name: cython.p_char = cython.cast(cython.p_char, data) |
| 16 |
with cython.gil: |
| 17 |
opaque_container.pop(name) |
| 18 |
lib.av_free(data) |
| 19 |
|
| 20 |
|
| 21 |
@cython.final |
| 22 |
@cython.cclass |
| 23 |
class OpaqueContainer: |
| 24 |
def __cinit__(self): |
| 25 |
self._objects = {} |
| 26 |
|
| 27 |
@cython.cfunc |
| 28 |
def add(self, v: object) -> cython.pointer[lib.AVBufferRef]: |
| 29 |
# Use object's memory address as key |
| 30 |
key: uintptr_t = cython.cast(cython.longlong, id(v)) |
| 31 |
self._objects[key] = v |
| 32 |
|
| 33 |
data: u8ptr = cython.cast(u8ptr, lib.av_malloc(sizeof(uintptr_t))) |
| 34 |
if data == NULL: |
| 35 |
raise MemoryError("Failed to allocate memory for key") |
| 36 |
|
| 37 |
memcpy(data, cython.address(key), sizeof(uintptr_t)) |
| 38 |
|
| 39 |
# Create the buffer with our free callback |
| 40 |
buffer_ref: cython.pointer[lib.AVBufferRef] = lib.av_buffer_create( |
| 41 |
data, sizeof(uintptr_t), key_free, NULL, 0 |
| 42 |
) |
| 43 |
|
| 44 |
if buffer_ref == NULL: |
| 45 |
raise MemoryError("Failed to create AVBufferRef") |
| 46 |
|
| 47 |
return buffer_ref |
| 48 |
|
| 49 |
def get(self, name) -> object: |
| 50 |
key: uintptr_t = cython.cast(cython.pointer[uintptr_t], name)[0] |
| 51 |
return self._objects.get(key) |
| 52 |
|
| 53 |
def pop(self, name) -> object: |
| 54 |
key: uintptr_t = cython.cast(cython.pointer[uintptr_t], name)[0] |
| 55 |
return self._objects.pop(key, None) |
| 56 |
|
| 57 |
|
| 58 |
opaque_container: OpaqueContainer = OpaqueContainer() |