Skip to content

Commit 1746ef4

Browse files
committed
Make av/opaque pure
1 parent a388589 commit 1746ef4

File tree

2 files changed

+63
-50
lines changed

2 files changed

+63
-50
lines changed

av/opaque.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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 noop_free(opaque: cython.p_void, data: u8ptr) -> cython.void:
15+
pass
16+
17+
18+
@cython.cfunc
19+
@cython.exceptval(check=False)
20+
@cython.nogil
21+
def key_free(opaque: cython.p_void, data: u8ptr) -> cython.void:
22+
name: cython.p_char = cython.cast(cython.p_char, data)
23+
with cython.gil:
24+
opaque_container.pop(name)
25+
26+
27+
@cython.cclass
28+
class OpaqueContainer:
29+
def __cinit__(self):
30+
self._objects = {}
31+
32+
@cython.cfunc
33+
def add(self, v: object) -> cython.pointer[lib.AVBufferRef]:
34+
# Use object's memory address as key
35+
key: uintptr_t = cython.cast(cython.longlong, id(v))
36+
self._objects[key] = v
37+
38+
data: u8ptr = cython.cast(u8ptr, lib.av_malloc(sizeof(uintptr_t)))
39+
if data == NULL:
40+
raise MemoryError("Failed to allocate memory for key")
41+
42+
memcpy(data, cython.address(key), sizeof(uintptr_t))
43+
44+
# Create the buffer with our free callback
45+
buffer_ref: cython.pointer[lib.AVBufferRef] = lib.av_buffer_create(
46+
data, sizeof(uintptr_t), key_free, NULL, 0
47+
)
48+
49+
if buffer_ref == NULL:
50+
raise MemoryError("Failed to create AVBufferRef")
51+
52+
return buffer_ref
53+
54+
def get(self, name) -> object:
55+
key: uintptr_t = cython.cast(cython.pointer[uintptr_t], name)[0]
56+
return self._objects.get(key)
57+
58+
def pop(self, name) -> object:
59+
key: uintptr_t = cython.cast(cython.pointer[uintptr_t], name)[0]
60+
return self._objects.pop(key, None)
61+
62+
63+
opaque_container: OpaqueContainer = OpaqueContainer()

av/opaque.pyx

Lines changed: 0 additions & 50 deletions
This file was deleted.

0 commit comments

Comments
 (0)