Skip to content

Instantly share code, notes, and snippets.

@mansourmoufid
Created March 15, 2023 02:41
Show Gist options
  • Save mansourmoufid/8c58d14fa3cc5e3b02748ab87ab62e87 to your computer and use it in GitHub Desktop.
Save mansourmoufid/8c58d14fa3cc5e3b02748ab87ab62e87 to your computer and use it in GitHub Desktop.
CVPixelBufferCreate in Python
import ctypes
import ctypes.util
import objc
# MacTypes.h
# typedef UInt32 FourCharCode
FourCharCode = ctypes.c_uint32
# typedef FourCharCode OSType;
OSType = FourCharCode
# Core Foundation
CF = ctypes.CDLL(ctypes.util.find_library('CoreFoundation'))
class __CFAllocator(ctypes.Structure):
pass
CF.CFAllocatorRef = ctypes.POINTER(__CFAllocator)
CF.kCFAllocatorDefault = None
class __CFDictionary(ctypes.Structure):
pass
CF.CFDictionaryRef = ctypes.POINTER(__CFDictionary)
# Core Video
CV = ctypes.CDLL(ctypes.util.find_library('CoreVideo'))
CV.CVReturn = ctypes.c_int32
CV.kCVReturnSuccess = 0
CV.kCVPixelFormatType_32BGRA = 0x42475241 # 'ARGB'
class __CVBuffer(ctypes.Structure):
pass
CV.CVBufferRef = ctypes.POINTER(__CVBuffer)
CV.CVImageBufferRef = CV.CVBufferRef
CV.CVPixelBufferRef = CV.CVImageBufferRef
# CVReturn CVPixelBufferCreate(
# CFAllocatorRef allocator,
# size_t width,
# size_t height,
# OSType pixelFormatType,
# CFDictionaryRef pixelBufferAttributes,
# CVPixelBufferRef _Nullable *pixelBufferOut
# );
CV.CVPixelBufferCreate.restype = CV.CVReturn
CV.CVPixelBufferCreate.argtypes = [
CF.CFAllocatorRef,
ctypes.c_size_t,
ctypes.c_size_t,
OSType,
CF.CFDictionaryRef,
ctypes.POINTER(CV.CVPixelBufferRef),
]
# CVPixelBufferRef CVPixelBufferRetain(CVPixelBufferRef texture);
CV.CVPixelBufferRetain.restype = CV.CVPixelBufferRef
CV.CVPixelBufferRetain.argtypes = [CV.CVPixelBufferRef]
# void CVPixelBufferRelease(CVPixelBufferRef texture);
CV.CVPixelBufferRelease.restype = None
CV.CVPixelBufferRelease.argtypes = [CV.CVPixelBufferRef]
def cv_pixel_buffer_create(
width: int,
height: int,
pixel_format_type: OSType,
) -> CV.CVPixelBufferRef:
pixel_buffer_ref = CV.CVPixelBufferRef()
status = CV.CVPixelBufferCreate(
CF.kCFAllocatorDefault,
width,
height,
pixel_format_type,
None,
ctypes.byref(pixel_buffer_ref)
)
CV.CVPixelBufferRetain(pixel_buffer_ref)
if status == CV.kCVReturnSuccess:
return objc.objc_object(
c_void_p=ctypes.cast(pixel_buffer_ref, ctypes.c_void_p)
)
return None
def cv_pixel_buffer_release(self: CV.CVPixelBufferRef) -> None:
CV.CVPixelBufferRelease(self)
CV.CVPixelBufferRef.__del__ = cv_pixel_buffer_release
if __name__ == '__main__':
while True:
pixel_buffer = cv_pixel_buffer_create(
640,
480,
CV.kCVPixelFormatType_32BGRA,
)
print('***', pixel_buffer)
del pixel_buffer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment