High-performance zero-copy inter-process communication library for video streaming
Project description
ZeroBuffer Python Implementation
Native Python implementation of the ZeroBuffer protocol for high-performance zero-copy inter-process communication.
Features
- True Zero-Copy: Uses memoryview and buffer protocol to avoid data copies
- Cross-Platform: Supports Linux, Windows, and macOS
- Protocol Compatible: Binary compatible with C++ and C# implementations
- Pythonic API: Clean, idiomatic Python interface
- Type Safe: Full type hints for better IDE support
- Thread Safe: Built-in synchronization for multi-threaded applications
Requirements
- Python 3.8 or later
posix-ipc(Linux/macOS only):pip install posix-ipcpywin32(Windows only):pip install pywin32
Installation
pip install -e .
Quick Start
Reader Example
from zerobuffer import Reader, BufferConfig
# Create a buffer
config = BufferConfig(metadata_size=1024, payload_size=1024*1024)
with Reader("my-buffer", config) as reader:
# Wait for writer to connect
print("Waiting for writer...")
# Read frames
while True:
frame = reader.read_frame(timeout=5.0)
if frame:
# Access data without copying
data = frame.data # This is a memoryview
print(f"Received frame {frame.sequence}: {len(data)} bytes")
# Process the frame...
# Must release frame to free buffer space
reader.release_frame(frame)
Writer Example
from zerobuffer import Writer
# Connect to existing buffer
with Writer("my-buffer") as writer:
# Write some metadata
metadata = b"{'format': 'raw', 'version': 1}"
writer.set_metadata(metadata)
# Write frames
for i in range(100):
data = f"Frame {i}".encode()
writer.write_frame(data)
print(f"Sent frame {i}")
Zero-Copy Advanced Usage
# True zero-copy writing with memoryview
import numpy as np
# Create numpy array
arr = np.arange(1000, dtype=np.float32)
# Get memoryview of array (no copy)
view = memoryview(arr)
# Write with zero-copy
writer.write_frame_zero_copy(view)
# Or use direct buffer access
buffer = writer.get_frame_buffer(size=4000)
# Write directly into shared memory
buffer[:] = arr.tobytes()
writer.commit_frame()
API Reference
Reader Class
Reader(name: str, config: Optional[BufferConfig] = None)
Creates a new buffer and prepares for reading.
Methods:
get_metadata() -> Optional[memoryview]: Get metadata as zero-copy memoryviewread_frame(timeout: Optional[float] = 5.0) -> Optional[Frame]: Read next framerelease_frame(frame: Frame) -> None: Release frame and free buffer spaceis_writer_connected() -> bool: Check if writer is connectedclose() -> None: Close reader and clean up resources
Writer Class
Writer(name: str)
Connects to an existing buffer for writing.
Methods:
set_metadata(data: Union[bytes, bytearray, memoryview]) -> None: Write metadata (once only)write_frame(data: Union[bytes, bytearray, memoryview]) -> None: Write a framewrite_frame_zero_copy(data: memoryview) -> None: Write frame with zero-copyget_frame_buffer(size: int) -> memoryview: Get buffer for direct writingcommit_frame() -> None: Commit frame after direct writingis_reader_connected() -> bool: Check if reader is connectedclose() -> None: Close writer
Frame Class
Represents a zero-copy reference to frame data.
Properties:
data -> memoryview: Zero-copy view of frame datasize -> int: Size of frame datasequence -> int: Sequence number
BufferConfig Class
BufferConfig(metadata_size: int = 1024, payload_size: int = 1024*1024)
Configuration for creating a buffer.
Zero-Copy Guarantees
The Python implementation provides true zero-copy access through:
- memoryview objects: No data copying when accessing frame data
- Buffer protocol: Direct memory access for compatible objects
- Shared memory: Direct mapping of shared memory into process space
When Copies Occur
- Converting memoryview to bytes:
bytes(frame.data) - Using non-buffer protocol objects with
write_frame() - String encoding:
"text".encode()
Avoiding Copies
- Use
memoryviewobjects whenever possible - Use
write_frame_zero_copy()for memoryview data - Use numpy arrays or other buffer protocol objects
- Access frame data directly via
frame.datamemoryview
Performance Considerations
- Pre-allocate buffers: Reuse buffers instead of creating new ones
- Batch operations: Process multiple frames before releasing
- Use appropriate buffer sizes: See capacity planning in main README
- Monitor buffer utilization: Avoid buffer full conditions
Error Handling
All operations may raise exceptions from zerobuffer.exceptions:
WriterDeadException: Writer process diedReaderDeadException: Reader process diedBufferFullException: Buffer is fullFrameTooLargeException: Frame exceeds buffer capacitySequenceError: Frame sequence validation failed
Thread Safety
The Reader and Writer classes are thread-safe. Multiple threads can:
- Call methods on the same Reader/Writer instance
- Read frames concurrently (with proper frame release)
- Write frames concurrently
However, only one Reader and one Writer can connect to a buffer at a time.
Platform Notes
Linux
- Uses POSIX shared memory (
/dev/shm) - Requires
posix-ipcpackage - File locks in
/tmp/zerobuffer/
Windows
- Uses Windows named shared memory
- Requires
pywin32package - File locks in temp directory
macOS
- Similar to Linux with BSD-specific handling
- Requires
posix-ipcpackage
Testing Utilities
The Python implementation includes testing utilities for cross-platform compatibility with C# and C++ implementations:
BufferNamingService
Ensures unique buffer names across test runs to prevent conflicts:
from zerobuffer_serve.services import BufferNamingService
# Creates unique buffer names for test isolation
naming_service = BufferNamingService(logger)
actual_name = naming_service.get_buffer_name("test-buffer")
# Returns: "test-buffer_<pid>_<timestamp>" or uses Harmony environment variables
TestDataPatterns
Provides consistent test data generation across all language implementations:
from zerobuffer_serve.test_data_patterns import TestDataPatterns
# Generate deterministic frame data
data = TestDataPatterns.generate_frame_data(size=1024, sequence=1)
# Generate simple pattern data
simple_data = TestDataPatterns.generate_simple_frame_data(size=1024)
# Verify data matches pattern
is_valid = TestDataPatterns.verify_simple_frame_data(data)
# Generate test metadata
metadata = TestDataPatterns.generate_metadata(size=256)
These utilities ensure that Python, C#, and C++ implementations can exchange data correctly in cross-platform tests.
Duplex Channel Support
The Python implementation includes full support for duplex channels (bidirectional request-response communication):
from zerobuffer.duplex import DuplexChannelFactory, ProcessingMode
from zerobuffer import BufferConfig
# Server side
factory = DuplexChannelFactory()
server = factory.create_immutable_server("my-service", BufferConfig(4096, 10*1024*1024))
def process_request(frame):
"""Process request and return response"""
# Frame is automatically disposed via RAII
data = bytes(frame.data)
result = process_data(data)
return result
server.start(process_request, ProcessingMode.SINGLE_THREAD)
# Client side
client = factory.create_client("my-service")
sequence = client.send_request(b"request data")
response = client.receive_response(timeout_ms=5000)
if response.is_valid and response.sequence == sequence:
with response: # Context manager for RAII
print(f"Response: {bytes(response.data)}")
See DUPLEX_CHANNEL.md for detailed documentation.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file zerobuffer_ipc-1.1.7.tar.gz.
File metadata
- Download URL: zerobuffer_ipc-1.1.7.tar.gz
- Upload date:
- Size: 101.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
022d593714eabc6860a75e51cbeca07aa88736bc7f8c846e6ac948f8cda6316a
|
|
| MD5 |
48e60987aeea6001705c6af84210c063
|
|
| BLAKE2b-256 |
7fbc5295c9fb8cb528bc9a2ac375c92b48a87dccfc76e664a10ef1a30ad9a8f8
|
File details
Details for the file zerobuffer_ipc-1.1.7-py3-none-any.whl.
File metadata
- Download URL: zerobuffer_ipc-1.1.7-py3-none-any.whl
- Upload date:
- Size: 103.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f9323cbf98c7a58e163a773dece381c09168d689a6161883dd636956e87fefd0
|
|
| MD5 |
0e0c564e7c109a85cc00e257649f2716
|
|
| BLAKE2b-256 |
77ad71b8d334ad93a493673ed9674ba18fb73a7215cf421c6adfe63ee5d3a795
|