#include #include #include #include #include #include #include class DmaBuffer { public: int fd; void* vaddr; // 虚拟地址(仅供调试或CPU必须介入时使用,如画字) size_t size; DmaBuffer(size_t size, const std::string& heap_name = "/dev/dma_heap/system") { this->size = size; this->vaddr = MAP_FAILED; this->fd = -1; int heap_fd = open(heap_name.c_str(), O_RDONLY | O_CLOEXEC); if (heap_fd < 0) { perror("Failed to open dma heap"); return; } struct dma_heap_allocation_data data = {0}; data.len = size; data.fd_flags = O_RDWR | O_CLOEXEC; if (ioctl(heap_fd, DMA_HEAP_IOCTL_ALLOC, &data) < 0) { perror("dma heap alloc failed"); close(heap_fd); return; } this->fd = data.fd; close(heap_fd); // 如果需要CPU访问(例如写OSD文字),则映射,否则可以不映射 this->vaddr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, this->fd, 0); if (this->vaddr == MAP_FAILED) { perror("mmap failed"); } } ~DmaBuffer() { if (vaddr != MAP_FAILED) munmap(vaddr, size); if (fd >= 0) close(fd); } };