Files
vizionStreamer/include/vizionstreamer/SharedMemoryWriter.h
2026-01-29 09:51:45 +01:00

63 lines
2.3 KiB
C++

/*
* VizionStreamer - Shared Memory Writer Interface
* Copyright (c) 2025 Maik Jurischka
*
* Licensed under CC BY-NC-SA 4.0
* https://creativecommons.org/licenses/by-nc-sa/4.0/
*/
#pragma once
#include <string>
#include <cstdint>
#include <atomic>
// Shared memory header structure for lock-free synchronization
struct SharedMemoryHeader {
uint32_t magic; // Magic number for validation (0x56495A4E = "VIZN")
uint32_t width; // Frame width in pixels
uint32_t height; // Frame height in pixels
uint32_t format; // Format enum (matches VX_IMAGE_FORMAT)
uint32_t data_size; // Actual frame data size in bytes
uint64_t timestamp_ns; // Timestamp in nanoseconds
uint32_t frame_sequence; // Monotonic frame counter
std::atomic<uint32_t> write_sequence; // Lock-free synchronization counter
char format_str[16]; // Format string ("YUY2", "MJPG", etc.)
uint8_t reserved[72]; // Reserved for future expansion (padding to 128 bytes)
};
static_assert(sizeof(SharedMemoryHeader) == 128, "SharedMemoryHeader must be exactly 128 bytes");
class SharedMemoryWriter {
public:
explicit SharedMemoryWriter(std::string name);
~SharedMemoryWriter();
// Initialize shared memory region with given buffer size
bool create(size_t frame_buffer_size);
// Write frame to shared memory with lock-free protocol
bool writeFrame(const uint8_t* data, size_t size,
int width, int height,
const std::string& format,
uint64_t timestamp_ns = 0);
// Cleanup shared memory
void destroy();
// Status queries
bool isCreated() const { return shm_fd_ >= 0; }
std::string getName() const { return shm_name_; }
size_t getBufferSize() const { return buffer_size_; }
uint32_t getFrameCount() const { return frame_counter_; }
private:
SharedMemoryHeader* getHeader();
std::string shm_name_; // Shared memory object name
int shm_fd_; // File descriptor from shm_open
void* shm_ptr_; // Mapped memory pointer
size_t buffer_size_; // Total size (header + frame data)
uint32_t frame_counter_; // Frame sequence counter
};