本示例代码使用BufferQueue最基本的操作接口,演示了BufferQueue操作的基本流程。
Android版本:8.1
void main(void)
{
createBufferQueue();
consumerConnect()
connect();
dequeueBuffer();
requestBuffer();
queueBuffer();
acquireBuffer();
releaseBuffer();
}
mytest.cpp:
#define LOG_TAG "MyTest"
#include
#include
#include
#include
#include
using namespace android;
struct DummyConsumer : public BnConsumerListener {
void onFrameAvailable(const BufferItem& /* item */) override {}
void onBuffersReleased() override {}
void onSidebandStreamChanged() override {}
};
int main(int argc, char** argv)
{
sp<IGraphicBufferProducer> producer;
sp<IGraphicBufferConsumer> consumer;
BufferQueue::createBufferQueue(&producer, &consumer);
consumer->consumerConnect(new DummyConsumer, false);
IGraphicBufferProducer::QueueBufferOutput output;
producer->connect(new DummyProducerListener, NATIVE_WINDOW_API_CPU, false, &output);
/****************** Producer ***********************/
int slot;
sp<Fence> fence;
sp<GraphicBuffer> buffer;
producer->dequeueBuffer(&slot, &fence, 0, 0, 0,
GRALLOC_USAGE_SW_WRITE_OFTEN, nullptr, nullptr);
producer->requestBuffer(slot, &buffer);
uint32_t* dataIn;
buffer->lock(GraphicBuffer::USAGE_SW_WRITE_OFTEN,
reinterpret_cast<void**>(&dataIn));
*dataIn = 0x12345678u;
buffer->unlock();
IGraphicBufferProducer::QueueBufferInput input(0, false, HAL_DATASPACE_UNKNOWN, Rect(1, 1),
NATIVE_WINDOW_SCALING_MODE_FREEZE, 0, Fence::NO_FENCE);
producer->queueBuffer(slot, input, &output);
/****************** Consumer ***********************/
BufferItem item;
consumer->acquireBuffer(&item, static_cast<nsecs_t>(0));
uint32_t* dataOut;
item.mGraphicBuffer->lock(GraphicBuffer::USAGE_SW_READ_OFTEN,
reinterpret_cast<void**>(&dataOut));
printf("data out is 0x%08x\n", *dataOut);
item.mGraphicBuffer->unlock();
consumer->releaseBuffer(item.mSlot, item.mFrameNumber, EGL_NO_DISPLAY,
EGL_NO_SYNC_KHR, Fence::NO_FENCE);
return 0;
}
Android.bp:
cc_test {
name: "mytest",
srcs: ["mytest.cpp"],
clang: true,
shared_libs: [
"liblog",
"libbinder",
"libgui",
"libui",
"libutils",
],
}
- 从BufferQueue中申请一块1x1大小的buffer;
- 向该buffer中写入0x12345678,然后放入BufferQueue队列中;
- 从队列中取出该buffer,并读取该buffer的内容;
- 释放该buffer。
$ adb shell /data/mytest
data out is 0x12345678
GitHub: mytest
Android BufferQueue自测试程序:BufferQueue_test.cpp —— MoveFromConsumerToProducer