Static memory pool
alternative to malloc()
In a recent project working with the FFMpeg API, I needed a way of allocating memory blocks and freeing them from a static block of memory. The main requirement was that when I closed the stream, I could clean up everything much easier.
When working with FFMpeg you really need to do a lot of memory management manually for video buffers, audio buffers and subtitle buffers. By using a static memory pool for each section, you reduce the chance of memory fragmentation.
After finishing this, I am now using this in other areas too. I will get round to optimising the code so that one version will not rely on the c++ vector class and will just use standard ansi c.
This class can be used as an alternative to malloc() and free(). And there’s no need to worry about freeing up the blocks when it comes to finishing up using the memory.
The simple test to show how it is used:
#include "memorymanager.h" // written off the cuff (hopefully it helps) void test_mm() { char my_buffer[2 * MBYTE]; MemoryManager mem; mem.init(my_buffer, sizeof(my_buffer)); char *block1 = (char*)mem.alloc(60000); char *block2 = (char*)mem.alloc(12000); mem.free(block1); mem.clean(); }
The header file:
// // Created by wlgfx on 5/18/16. // #ifndef FFPLAYER2_MEMORYMANAGER_H #define FFPLAYER2_MEMORYMANAGER_H #define MBYTE 1048576 #include#include #include // use a mutex lock is using multi threaded #define MM_USE_MUTEX struct MBlock { uint ptr; uint size; MBlock(uint p, uint s) {ptr = p; size = s;} }; class MemoryManager { public: void init(void* ptr, uint size); // Initialise the static block of memory void* alloc(uint size); // return address or NULL if no memory available void free(void* ptr); // return the block back to the pool void clean(); // resets the memory pool uint total_free(); uint total_used(); void debug(); private: std::vector free_blocks; std::vector used_blocks; uint data; // pointer to static block uint size; // size of static block int last; // last pos allocated from #ifdef MM_USE_MUTEX pthread_mutex_t mem_mutex = PTHREAD_MUTEX_INITIALIZER; // TODO: swap for std::mutex #endif }; #endif //FFPLAYER2_MEMORYMANAGER_H
The cpp file:
// // Created by wlgfx on 5/18/16. // #include "MemoryManager.h" #include// Remove the Android stuff if not using the platform #include #define LOG_TAG "WLGFX" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) void MemoryManager::init(void* in, uint size) { pthread_mutex_init(&mem_mutex, NULL); uint ptr = (uint)in; data = ptr; this->size = size; clean(); } void *MemoryManager::alloc(uint size) { #ifdef MM_USE_MUTEX while (!pthread_mutex_trylock(&mem_mutex)) sched_yield(); //pthread_mutex_lock(&mem_mutex); #endif bool found = false; int l = 0; // first try last position to allocate from if (free_blocks[last].ptr + size <= free_blocks[last].ptr + free_blocks[last].size) { l = last; found = true; } else { // scan through free blocks do { if (free_blocks[l].ptr + size <= free_blocks[l].ptr + free_blocks[l].size) { found = true; } else { l++; } } while (!found && l < free_blocks.size()); } if (found) { used_blocks.push_back(MBlock(free_blocks[l].ptr, size)); free_blocks[l].size -= size; free_blocks[l].ptr += size; if (free_blocks[l].size <= 0) { // need to remove block? free_blocks.erase(free_blocks.begin() + l); if (free_blocks.size() == l) l = 0; } last = l; // set last position as next marker void *result = (void*)used_blocks[used_blocks.size() - 1].ptr; #ifdef MM_USE_MUTEX pthread_mutex_unlock(&mem_mutex); #endif return result; } #ifdef MM_USE_MUTEX pthread_mutex_unlock(&mem_mutex); #endif return nullptr; // to be checked by the user } void MemoryManager::free(void *in) { uint ptr = (uint)in; int used = 0; bool got = false; #ifdef MM_USE_MUTEX while (!pthread_mutex_trylock(&mem_mutex)) sched_yield(); //pthread_mutex_lock(&mem_mutex); #endif size_t usize = used_blocks.size(); // locate which used block to free while (used < usize) { if (used_blocks[used].ptr == ptr) { got = true; break; } used++; } if (!got) { #ifdef MM_USE_MUTEX pthread_mutex_unlock(&mem_mutex); #endif return; } // block not found int c = free_blocks.size(); // current free block to test against uint ub_beg = used_blocks[used].ptr; // used blocks beginning uint ub_siz = used_blocks[used].size; // used blocks size uint ub_end = ub_beg + ub_siz; // used blocks end while (c) { c--; // reverse through list bool done = false; // flagged if merged with free block uint fb_beg = free_blocks[c].ptr; // free blocks beginning uint fb_siz = free_blocks[c].size; // free blocks size uint fb_end = fb_beg + fb_siz; // free blocks end // used_end == free_begin? merge with free blocks beginning if (ub_end == fb_beg) { fb_beg -= ub_siz; // move free blocks pointer backwards fb_siz += ub_siz; // increase free blocks size (fb_end stays same) ub_end = fb_end; ub_siz = fb_siz; // increase used blocks size done = true; } // used beginning == free end? merge at end of free block if (ub_beg == fb_end) { fb_end += ub_siz; // move end pointer fb_siz += ub_siz; ub_beg = fb_beg; ub_siz = fb_siz; done = true; } // if a merge has occurred then clean up free blocks data if (done) free_blocks.erase(free_blocks.begin() + c); } // add the finished with block to free list free_blocks.push_back(MBlock(ub_beg, ub_siz)); // remove from used blocks list used_blocks.erase(used_blocks.begin() + used); #ifdef MM_USE_MUTEX pthread_mutex_unlock(&mem_mutex); #endif } // puts the memory block back to beginning invalidating previous allocations void MemoryManager::clean() { while (!pthread_mutex_trylock(&mem_mutex)) sched_yield(); //pthread_mutex_lock(&mem_mutex); free_blocks.clear(); used_blocks.clear(); free_blocks.push_back(MBlock(data, size)); last = 0; pthread_mutex_unlock(&mem_mutex); } uint MemoryManager::total_free() { while (!pthread_mutex_trylock(&mem_mutex)) sched_yield(); //pthread_mutex_lock(&mem_mutex); uint result = 0; size_t pos = 0; size_t size = free_blocks.size(); while (pos < size) result += free_blocks[pos++].size; pthread_mutex_unlock(&mem_mutex); return result; } uint MemoryManager::total_used() { while (!pthread_mutex_trylock(&mem_mutex)) sched_yield(); //pthread_mutex_lock(&mem_mutex); uint result = 0; size_t pos = 0; size_t size = used_blocks.size(); while (pos < size) result += used_blocks[pos++].size; pthread_mutex_unlock(&mem_mutex); return result; } void MemoryManager::debug() { LOGD("MEMORY MANAGER"); while (!pthread_mutex_trylock(&mem_mutex)) sched_yield(); //pthread_mutex_lock(&mem_mutex); std::stringstream ss; ss << "Free Blocks: " << total_free() << " - "; for (size_t c = 0; c < free_blocks.size(); c++) { ss << "(" << free_blocks[c].ptr - data << ", " << free_blocks[c].size << ") "; } LOGD(ss.str().c_str()); std::stringstream ts; ts.clear(); ts << "Used Blocks: " << total_used() << " - "; for (size_t c = 0; c < used_blocks.size(); c++) { ts << "(" << used_blocks[c].ptr - data << ", " << used_blocks[c].size << ") "; } pthread_mutex_unlock(&mem_mutex); LOGD(ts.str().c_str()); }