File: opaque.pyx

package info (click to toggle)
python-av 16.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,684 kB
  • sloc: python: 7,607; sh: 182; ansic: 174; makefile: 135
file content (46 lines) | stat: -rw-r--r-- 1,321 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
cimport libav as lib
from libc.stdint cimport intptr_t, uint8_t
from libc.string cimport memcpy


cdef void key_free(void *opaque, uint8_t *data) noexcept nogil:
    cdef char *name = <char *>data
    with gil:
        opaque_container.pop(name)


cdef class OpaqueContainer:
    def __cinit__(self):
        self._objects = {}

    cdef lib.AVBufferRef *add(self, object v):
        # Use object's memory address as key
        cdef intptr_t key = id(v)
        self._objects[key] = v

        cdef uint8_t *data = <uint8_t *>lib.av_malloc(sizeof(intptr_t))
        if data == NULL:
            raise MemoryError("Failed to allocate memory for key")

        memcpy(data, &key, sizeof(intptr_t))

        # Create the buffer with our free callback
        cdef lib.AVBufferRef *buffer_ref = lib.av_buffer_create(
            data, sizeof(intptr_t), key_free, NULL, 0
        )

        if buffer_ref == NULL:
            raise MemoryError("Failed to create AVBufferRef")

        return buffer_ref

    cdef object get(self, char *name):
        cdef intptr_t key = (<intptr_t *>name)[0]
        return self._objects.get(key)

    cdef object pop(self, char *name):
        cdef intptr_t key = (<intptr_t *>name)[0]
        return self._objects.pop(key, None)


cdef OpaqueContainer opaque_container = OpaqueContainer()