Skip to content

Commit

Permalink
ImagingComponent: Align the memory when allocating the buffer.
Browse files Browse the repository at this point in the history
Essentially a reimplementation of cv::fastMalloc using std::align in C++11.
  • Loading branch information
CrossVR committed Sep 20, 2015
1 parent 86d510a commit 31da52d
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion src/osvr/Common/ImagingComponent.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,12 @@
#include <osvr/Util/Verbosity.h>

// Standard includes
#include <stdlib.h>
#include <sstream>
#include <utility>

#define OSVR_ALIGN_SIZE 16

namespace osvr {
namespace common {
static inline uint32_t getBufferSize(OSVR_ImagingMetadata const &meta) {
Expand Down Expand Up @@ -67,14 +70,27 @@ namespace common {

template <typename T>
void allocateBuffer(T &, size_t bytes, std::true_type const &) {
m_imgBuf.reset(reinterpret_cast<OSVR_ImageBufferElement *>(malloc(bytes)));
// Allocate a memory pointed aligned to a boundary.
size_t space = bytes + sizeof(void*) + OSVR_ALIGN_SIZE;
void* buffer = malloc(space);
void* aligned = std::align(OSVR_ALIGN_SIZE, bytes, buffer, space);

// Store the buffer pointer for the delete call.
((void **)aligned)[-1] = buffer;

m_imgBuf.reset(reinterpret_cast<OSVR_ImageBufferElement *>(aligned, deleteBuffer));
}

template <typename T>
void allocateBuffer(T &, size_t, std::false_type const &) {
// Does nothing if we're serializing.
}

static void deleteBuffer(void* p) {
if (p)
free(((void **)p)[-1]);
}

template <typename T> void processMessage(T &p) {
process(m_meta, p);
auto bytes = getBufferSize(m_meta);
Expand Down

0 comments on commit 31da52d

Please sign in to comment.