好久没有写博客了,前段时间做项目需要一个缓冲机制用来缓存视频帧。下面是自己实现的视频缓冲类。在此类中用循环队列实现了视频帧数据的入队、出队。在类中使用互斥对象避免出入队出现错误。下面是代码。
/*****************头文件****************/
using namespace std; #define MAXSIZE 50 typedef struct { int iSize;//数据的大小 char *cdata; }bufData; typedef struct { bufData mdata[MAXSIZE]; int iRead;//队头 int iWrite;//队尾 }bufferPara; class CycleBuffer { public: CycleBuffer(void); ~CycleBuffer(void); BOOL push(bufferPara *Q,char* src,int strLen);//缓冲区存入 char* pop(bufferPara *Q,long &dsLen);//弹出数据 BOOL InitQueue(bufferPara *Q);//初始化队列 bufferPara mbufferPara; char *dest; private: HANDLE mutexHandle; char *item; };
/**************************实现*******************/
#include "StdAfx.h" #include "CycleBuffer.h" CycleBuffer::CycleBuffer(void) { InitQueue(&mbufferPara); dest = new char[1024*500]; memset(dest,0,1024*500); mutexHandle = CreateMutex(NULL,FALSE,NULL ); } CycleBuffer::~CycleBuffer(void) { CloseHandle(mutexHandle); for (int i=0;i<MAXSIZE;i++) { delete[] mbufferPara.mdata[i].cdata; } } BOOL CycleBuffer::push(bufferPara *Q,char* src,int srcLen) { WaitForSingleObject(mutexHandle,INFINITE); if ((Q->iWrite+1)%MAXSIZE!=Q->iRead) { memcpy(Q->mdata[Q->iWrite].cdata,src,srcLen); //Q->mdata[Q->iWrite].cdata = src; Q->mdata[Q->iWrite].iSize = srcLen; Q->iWrite = (Q->iWrite+1)%MAXSIZE; ReleaseMutex(mutexHandle); return TRUE; } else { ReleaseMutex(mutexHandle); return FALSE; } } char* CycleBuffer::pop(bufferPara *Q,long &dstLen) { WaitForSingleObject(mutexHandle,INFINITE); if (Q->iRead!=Q->iWrite) { dest = Q->mdata[Q->iRead].cdata; dstLen = Q->mdata[Q->iRead].iSize; memcpy(dest,Q->mdata[Q->iRead].cdata,dstLen); Q->iRead = (Q->iRead+1)%MAXSIZE; ReleaseMutex(mutexHandle); return dest; } else { ReleaseMutex(mutexHandle); return NULL; } } BOOL CycleBuffer::InitQueue(bufferPara * Q) { Q->iRead =0; Q->iWrite=0; for (int i=0;i<MAXSIZE;i++) { Q->mdata[i].cdata = new char[1024*500]; memset(Q->mdata[i].cdata,0,1024*500); Q->mdata[i].iSize = 0; } return TRUE; }
注意头文件中的两个结构体,结构体bufferPara定义的是基本的队列的结构,bufferData结构体中定义的是要存入队列的数据。此类还不完善,日后有时间完善再上传。请各位大牛们提出宝贵意见。