1 /*
2 * Copyright 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 //#define LOG_NDEBUG 0
18 #define LOG_TAG "Codec2-OutputBufferQueue"
19 #include <android-base/logging.h>
20
21 #include <android/hardware/graphics/bufferqueue/2.0/IGraphicBufferProducer.h>
22 #include <codec2/hidl/output.h>
23 #include <cutils/ashmem.h>
24 #include <gui/bufferqueue/2.0/B2HGraphicBufferProducer.h>
25 #include <sys/mman.h>
26
27 #include <C2AllocatorGralloc.h>
28 #include <C2BlockInternal.h>
29 #include <C2Buffer.h>
30 #include <C2PlatformSupport.h>
31 #include <C2SurfaceSyncObj.h>
32
33 #include <iomanip>
34
35 namespace android {
36 namespace hardware {
37 namespace media {
38 namespace c2 {
39
40 using HGraphicBufferProducer = ::android::hardware::graphics::bufferqueue::
41 V2_0::IGraphicBufferProducer;
42 using B2HGraphicBufferProducer = ::android::hardware::graphics::bufferqueue::
43 V2_0::utils::B2HGraphicBufferProducer;
44
45 namespace /* unnamed */ {
46
47 // Create a GraphicBuffer object from a graphic block.
createGraphicBuffer(const C2ConstGraphicBlock & block)48 sp<GraphicBuffer> createGraphicBuffer(const C2ConstGraphicBlock& block) {
49 uint32_t width;
50 uint32_t height;
51 uint32_t format;
52 uint64_t usage;
53 uint32_t stride;
54 uint32_t generation;
55 uint64_t bqId;
56 int32_t bqSlot;
57 _UnwrapNativeCodec2GrallocMetadata(
58 block.handle(), &width, &height, &format, &usage,
59 &stride, &generation, &bqId, reinterpret_cast<uint32_t*>(&bqSlot));
60 native_handle_t *grallocHandle =
61 UnwrapNativeCodec2GrallocHandle(block.handle());
62 sp<GraphicBuffer> graphicBuffer =
63 new GraphicBuffer(grallocHandle,
64 GraphicBuffer::CLONE_HANDLE,
65 width, height, format,
66 1, usage, stride);
67 native_handle_delete(grallocHandle);
68 return graphicBuffer;
69 }
70
71 template <typename BlockProcessor>
forEachBlock(C2FrameData & frameData,BlockProcessor process)72 void forEachBlock(C2FrameData& frameData,
73 BlockProcessor process) {
74 for (const std::shared_ptr<C2Buffer>& buffer : frameData.buffers) {
75 if (buffer) {
76 for (const C2ConstGraphicBlock& block :
77 buffer->data().graphicBlocks()) {
78 process(block);
79 }
80 }
81 }
82 }
83
84 template <typename BlockProcessor>
forEachBlock(const std::list<std::unique_ptr<C2Work>> & workList,BlockProcessor process)85 void forEachBlock(const std::list<std::unique_ptr<C2Work>>& workList,
86 BlockProcessor process) {
87 for (const std::unique_ptr<C2Work>& work : workList) {
88 if (!work) {
89 continue;
90 }
91 for (const std::unique_ptr<C2Worklet>& worklet : work->worklets) {
92 if (worklet) {
93 forEachBlock(worklet->output, process);
94 }
95 }
96 }
97 }
98
getHgbp(const sp<IGraphicBufferProducer> & igbp)99 sp<HGraphicBufferProducer> getHgbp(const sp<IGraphicBufferProducer>& igbp) {
100 sp<HGraphicBufferProducer> hgbp =
101 igbp->getHalInterface<HGraphicBufferProducer>();
102 return hgbp ? hgbp :
103 new B2HGraphicBufferProducer(igbp);
104 }
105
attachToBufferQueue(const C2ConstGraphicBlock & block,const sp<IGraphicBufferProducer> & igbp,uint32_t generation,int32_t * bqSlot,std::shared_ptr<C2SurfaceSyncMemory> syncMem)106 status_t attachToBufferQueue(const C2ConstGraphicBlock& block,
107 const sp<IGraphicBufferProducer>& igbp,
108 uint32_t generation,
109 int32_t* bqSlot,
110 std::shared_ptr<C2SurfaceSyncMemory> syncMem) {
111 if (!igbp) {
112 LOG(WARNING) << "attachToBufferQueue -- null producer.";
113 return NO_INIT;
114 }
115
116 sp<GraphicBuffer> graphicBuffer = createGraphicBuffer(block);
117 graphicBuffer->setGenerationNumber(generation);
118
119 LOG(VERBOSE) << "attachToBufferQueue -- attaching buffer:"
120 << " block dimension " << block.width() << "x"
121 << block.height()
122 << ", graphicBuffer dimension " << graphicBuffer->getWidth() << "x"
123 << graphicBuffer->getHeight()
124 << std::hex << std::setfill('0')
125 << ", format 0x" << std::setw(8) << graphicBuffer->getPixelFormat()
126 << ", usage 0x" << std::setw(16) << graphicBuffer->getUsage()
127 << std::dec << std::setfill(' ')
128 << ", stride " << graphicBuffer->getStride()
129 << ", generation " << graphicBuffer->getGenerationNumber();
130
131 C2SyncVariables *syncVar = syncMem ? syncMem->mem() : nullptr;
132 status_t result = OK;
133 if (syncVar) {
134 syncVar->lock();
135 if (!syncVar->isDequeueableLocked() ||
136 syncVar->getSyncStatusLocked() == C2SyncVariables::STATUS_SWITCHING) {
137 syncVar->unlock();
138 LOG(WARNING) << "attachToBufferQueue -- attachBuffer failed: "
139 "status = " << INVALID_OPERATION << ".";
140 return INVALID_OPERATION;
141 }
142 result = igbp->attachBuffer(bqSlot, graphicBuffer);
143 if (result == OK) {
144 syncVar->notifyDequeuedLocked();
145 }
146 syncVar->unlock();
147 } else {
148 result = igbp->attachBuffer(bqSlot, graphicBuffer);
149 }
150 if (result != OK) {
151 LOG(WARNING) << "attachToBufferQueue -- attachBuffer failed: "
152 "status = " << result << ".";
153 return result;
154 }
155 LOG(VERBOSE) << "attachToBufferQueue -- attachBuffer returned slot #"
156 << *bqSlot << ".";
157 return OK;
158 }
159
getBufferQueueAssignment(const C2ConstGraphicBlock & block,uint32_t * generation,uint64_t * bqId,int32_t * bqSlot)160 bool getBufferQueueAssignment(const C2ConstGraphicBlock& block,
161 uint32_t* generation,
162 uint64_t* bqId,
163 int32_t* bqSlot) {
164 return _C2BlockFactory::GetBufferQueueData(
165 _C2BlockFactory::GetGraphicBlockPoolData(block),
166 generation, bqId, bqSlot);
167 }
168
169 } // unnamed namespace
170
OutputBufferQueue()171 OutputBufferQueue::OutputBufferQueue()
172 : mGeneration{0}, mBqId{0}, mStopped{false} {
173 }
174
~OutputBufferQueue()175 OutputBufferQueue::~OutputBufferQueue() {
176 }
177
configure(const sp<IGraphicBufferProducer> & igbp,uint32_t generation,uint64_t bqId,int maxDequeueBufferCount,std::shared_ptr<V1_2::SurfaceSyncObj> * syncObj)178 bool OutputBufferQueue::configure(const sp<IGraphicBufferProducer>& igbp,
179 uint32_t generation,
180 uint64_t bqId,
181 int maxDequeueBufferCount,
182 std::shared_ptr<V1_2::SurfaceSyncObj> *syncObj) {
183 uint64_t consumerUsage = 0;
184 if (igbp && igbp->getConsumerUsage(&consumerUsage) != OK) {
185 ALOGW("failed to get consumer usage");
186 }
187
188 // TODO : Abstract creation process into C2SurfaceSyncMemory class.
189 // use C2LinearBlock instead ashmem.
190 std::shared_ptr<C2SurfaceSyncMemory> syncMem;
191 if (syncObj && igbp) {
192 bool mapped = false;
193 int memFd = ashmem_create_region("C2SurfaceMem", sizeof(C2SyncVariables));
194 size_t memSize = memFd < 0 ? 0 : ashmem_get_size_region(memFd);
195 if (memSize > 0) {
196 syncMem = C2SurfaceSyncMemory::Create(memFd, memSize);
197 if (syncMem) {
198 mapped = true;
199 *syncObj = std::make_shared<V1_2::SurfaceSyncObj>();
200 (*syncObj)->syncMemory = syncMem->handle();
201 (*syncObj)->bqId = bqId;
202 (*syncObj)->generationId = generation;
203 (*syncObj)->consumerUsage = consumerUsage;
204 ALOGD("C2SurfaceSyncMemory created %zu(%zu)", sizeof(C2SyncVariables), memSize);
205 }
206 }
207 if (!mapped) {
208 if (memFd >= 0) {
209 ::close(memFd);
210 }
211 ALOGW("SurfaceSyncObj creation failure");
212 }
213 }
214
215 size_t tryNum = 0;
216 size_t success = 0;
217 sp<GraphicBuffer> buffers[BufferQueueDefs::NUM_BUFFER_SLOTS];
218 std::weak_ptr<_C2BlockPoolData>
219 poolDatas[BufferQueueDefs::NUM_BUFFER_SLOTS];
220 std::shared_ptr<C2SurfaceSyncMemory> oldMem;
221 {
222 std::scoped_lock<std::mutex> l(mMutex);
223 bool stopped = mStopped;
224 mStopped = false;
225 if (generation == mGeneration) {
226 // case of old BlockPool destruction
227 C2SyncVariables *var = mSyncMem ? mSyncMem->mem() : nullptr;
228 if (syncObj && var) {
229 *syncObj = std::make_shared<V1_2::SurfaceSyncObj>();
230 (*syncObj)->bqId = bqId;
231 (*syncObj)->syncMemory = mSyncMem->handle();
232 (*syncObj)->generationId = generation;
233 (*syncObj)->consumerUsage = consumerUsage;
234 mMaxDequeueBufferCount = maxDequeueBufferCount;
235 var->lock();
236 var->setSyncStatusLocked(C2SyncVariables::STATUS_INIT);
237 var->setInitialDequeueCountLocked(mMaxDequeueBufferCount, 0);
238 var->unlock();
239 }
240 return false;
241 }
242 oldMem = mSyncMem;
243 C2SyncVariables *oldSync = mSyncMem ? mSyncMem->mem() : nullptr;
244 if (oldSync) {
245 oldSync->lock();
246 oldSync->setSyncStatusLocked(C2SyncVariables::STATUS_SWITCHING);
247 oldSync->unlock();
248 }
249 mSyncMem.reset();
250 if (syncMem) {
251 mSyncMem = syncMem;
252 }
253 C2SyncVariables *newSync = mSyncMem ? mSyncMem->mem() : nullptr;
254
255 mIgbp = igbp;
256 mGeneration = generation;
257 mBqId = bqId;
258 mOwner = std::make_shared<int>(0);
259 mMaxDequeueBufferCount = maxDequeueBufferCount;
260 if (igbp == nullptr) {
261 return false;
262 }
263 for (int i = 0; i < BufferQueueDefs::NUM_BUFFER_SLOTS; ++i) {
264 if (mBqId == 0 || !mBuffers[i] || stopped) {
265 continue;
266 }
267 std::shared_ptr<_C2BlockPoolData> data = mPoolDatas[i].lock();
268 if (!data ||
269 !_C2BlockFactory::BeginAttachBlockToBufferQueue(data)) {
270 continue;
271 }
272 ++tryNum;
273 int bqSlot;
274
275 // Update buffer's generation and usage.
276 if ((mBuffers[i]->getUsage() & consumerUsage) != consumerUsage) {
277 mBuffers[i] = new GraphicBuffer(
278 mBuffers[i]->handle, GraphicBuffer::CLONE_HANDLE,
279 mBuffers[i]->width, mBuffers[i]->height,
280 mBuffers[i]->format, mBuffers[i]->layerCount,
281 mBuffers[i]->getUsage() | consumerUsage,
282 mBuffers[i]->stride);
283 if (mBuffers[i]->initCheck() != OK) {
284 ALOGW("%s() failed to update usage, original usage=%" PRIx64
285 ", consumer usage=%" PRIx64,
286 __func__, mBuffers[i]->getUsage(), consumerUsage);
287 continue;
288 }
289 }
290 mBuffers[i]->setGenerationNumber(generation);
291
292 status_t result = igbp->attachBuffer(&bqSlot, mBuffers[i]);
293 if (result != OK) {
294 continue;
295 }
296 bool attach =
297 _C2BlockFactory::EndAttachBlockToBufferQueue(
298 data, mOwner, getHgbp(mIgbp), mSyncMem,
299 generation, bqId, bqSlot);
300 if (!attach) {
301 igbp->cancelBuffer(bqSlot, Fence::NO_FENCE);
302 continue;
303 }
304 buffers[bqSlot] = mBuffers[i];
305 poolDatas[bqSlot] = data;
306 ++success;
307 }
308 for (int i = 0; i < BufferQueueDefs::NUM_BUFFER_SLOTS; ++i) {
309 mBuffers[i] = buffers[i];
310 mPoolDatas[i] = poolDatas[i];
311 }
312 if (newSync) {
313 newSync->lock();
314 newSync->setInitialDequeueCountLocked(mMaxDequeueBufferCount, success);
315 newSync->unlock();
316 }
317 }
318 {
319 std::scoped_lock<std::mutex> l(mOldMutex);
320 mOldMem = oldMem;
321 }
322 ALOGD("remote graphic buffer migration %zu/%zu",
323 success, tryNum);
324 return true;
325 }
326
expireOldWaiters()327 void OutputBufferQueue::expireOldWaiters() {
328 std::scoped_lock<std::mutex> l(mOldMutex);
329 if (mOldMem) {
330 C2SyncVariables *oldSync = mOldMem->mem();
331 if (oldSync) {
332 oldSync->notifyAll();
333 }
334 mOldMem.reset();
335 }
336 }
337
stop()338 void OutputBufferQueue::stop() {
339 std::scoped_lock<std::mutex> l(mMutex);
340 mStopped = true;
341 mOwner.reset(); // destructor of the block will not triger IGBP::cancel()
342 }
343
registerBuffer(const C2ConstGraphicBlock & block)344 bool OutputBufferQueue::registerBuffer(const C2ConstGraphicBlock& block) {
345 std::shared_ptr<_C2BlockPoolData> data =
346 _C2BlockFactory::GetGraphicBlockPoolData(block);
347 if (!data) {
348 return false;
349 }
350 std::scoped_lock<std::mutex> l(mMutex);
351
352 if (!mIgbp || mStopped) {
353 return false;
354 }
355
356 uint32_t oldGeneration;
357 uint64_t oldId;
358 int32_t oldSlot;
359 // If the block is not bufferqueue-based, do nothing.
360 if (!_C2BlockFactory::GetBufferQueueData(
361 data, &oldGeneration, &oldId, &oldSlot) || (oldId == 0)) {
362 return false;
363 }
364 // If the block's bqId is the same as the desired bqId, just hold.
365 if ((oldId == mBqId) && (oldGeneration == mGeneration)) {
366 LOG(VERBOSE) << "holdBufferQueueBlock -- import without attaching:"
367 << " bqId " << oldId
368 << ", bqSlot " << oldSlot
369 << ", generation " << mGeneration
370 << ".";
371 _C2BlockFactory::HoldBlockFromBufferQueue(data, mOwner, getHgbp(mIgbp), mSyncMem);
372 mPoolDatas[oldSlot] = data;
373 mBuffers[oldSlot] = createGraphicBuffer(block);
374 mBuffers[oldSlot]->setGenerationNumber(mGeneration);
375 return true;
376 }
377 int32_t d = (int32_t) mGeneration - (int32_t) oldGeneration;
378 LOG(WARNING) << "receiving stale buffer: generation "
379 << mGeneration << " , diff " << d << " : slot "
380 << oldSlot;
381 return false;
382 }
383
outputBuffer(const C2ConstGraphicBlock & block,const BnGraphicBufferProducer::QueueBufferInput & input,BnGraphicBufferProducer::QueueBufferOutput * output)384 status_t OutputBufferQueue::outputBuffer(
385 const C2ConstGraphicBlock& block,
386 const BnGraphicBufferProducer::QueueBufferInput& input,
387 BnGraphicBufferProducer::QueueBufferOutput* output) {
388 uint32_t generation;
389 uint64_t bqId;
390 int32_t bqSlot;
391 bool display = V1_0::utils::displayBufferQueueBlock(block);
392 if (!getBufferQueueAssignment(block, &generation, &bqId, &bqSlot) ||
393 bqId == 0) {
394 // Block not from bufferqueue -- it must be attached before queuing.
395
396 std::shared_ptr<C2SurfaceSyncMemory> syncMem;
397 mMutex.lock();
398 bool stopped = mStopped;
399 sp<IGraphicBufferProducer> outputIgbp = mIgbp;
400 uint32_t outputGeneration = mGeneration;
401 syncMem = mSyncMem;
402 mMutex.unlock();
403
404 if (stopped) {
405 LOG(INFO) << "outputBuffer -- already stopped.";
406 return DEAD_OBJECT;
407 }
408
409 status_t status = attachToBufferQueue(
410 block, outputIgbp, outputGeneration, &bqSlot, syncMem);
411
412 if (status != OK) {
413 LOG(WARNING) << "outputBuffer -- attaching failed.";
414 return INVALID_OPERATION;
415 }
416
417 auto syncVar = syncMem ? syncMem->mem() : nullptr;
418 if(syncVar) {
419 syncVar->lock();
420 status = outputIgbp->queueBuffer(static_cast<int>(bqSlot),
421 input, output);
422 if (status == OK) {
423 syncVar->notifyQueuedLocked();
424 }
425 syncVar->unlock();
426 } else {
427 status = outputIgbp->queueBuffer(static_cast<int>(bqSlot),
428 input, output);
429 }
430 if (status != OK) {
431 LOG(ERROR) << "outputBuffer -- queueBuffer() failed "
432 "on non-bufferqueue-based block. "
433 "Error = " << status << ".";
434 return status;
435 }
436 return OK;
437 }
438
439 std::shared_ptr<C2SurfaceSyncMemory> syncMem;
440 mMutex.lock();
441 bool stopped = mStopped;
442 sp<IGraphicBufferProducer> outputIgbp = mIgbp;
443 uint32_t outputGeneration = mGeneration;
444 uint64_t outputBqId = mBqId;
445 syncMem = mSyncMem;
446 mMutex.unlock();
447
448 if (stopped) {
449 LOG(INFO) << "outputBuffer -- already stopped.";
450 return DEAD_OBJECT;
451 }
452
453 if (!outputIgbp) {
454 LOG(VERBOSE) << "outputBuffer -- output surface is null.";
455 return NO_INIT;
456 }
457
458 if (!display) {
459 LOG(WARNING) << "outputBuffer -- cannot display "
460 "bufferqueue-based block to the bufferqueue.";
461 return UNKNOWN_ERROR;
462 }
463 if (bqId != outputBqId || generation != outputGeneration) {
464 int32_t diff = (int32_t) outputGeneration - (int32_t) generation;
465 LOG(WARNING) << "outputBuffer -- buffers from old generation to "
466 << outputGeneration << " , diff: " << diff
467 << " , slot: " << bqSlot;
468 return DEAD_OBJECT;
469 }
470
471 auto syncVar = syncMem ? syncMem->mem() : nullptr;
472 status_t status = OK;
473 if (syncVar) {
474 syncVar->lock();
475 status = outputIgbp->queueBuffer(static_cast<int>(bqSlot),
476 input, output);
477 if (status == OK) {
478 syncVar->notifyQueuedLocked();
479 }
480 syncVar->unlock();
481 } else {
482 status = outputIgbp->queueBuffer(static_cast<int>(bqSlot),
483 input, output);
484 }
485
486 if (status != OK) {
487 LOG(ERROR) << "outputBuffer -- queueBuffer() failed "
488 "on bufferqueue-based block. "
489 "Error = " << status << ".";
490 return status;
491 }
492 return OK;
493 }
494
pollForRenderedFrames(FrameEventHistoryDelta * delta)495 void OutputBufferQueue::pollForRenderedFrames(FrameEventHistoryDelta* delta) {
496 if (mIgbp) {
497 mIgbp->getFrameTimestamps(delta);
498 }
499 }
500
holdBufferQueueBlocks(const std::list<std::unique_ptr<C2Work>> & workList)501 void OutputBufferQueue::holdBufferQueueBlocks(
502 const std::list<std::unique_ptr<C2Work>>& workList) {
503 forEachBlock(workList,
504 std::bind(&OutputBufferQueue::registerBuffer,
505 this, std::placeholders::_1));
506 }
507
updateMaxDequeueBufferCount(int maxDequeueBufferCount)508 void OutputBufferQueue::updateMaxDequeueBufferCount(int maxDequeueBufferCount) {
509 mMutex.lock();
510 mMaxDequeueBufferCount = maxDequeueBufferCount;
511 auto syncVar = mSyncMem ? mSyncMem->mem() : nullptr;
512 if (syncVar && !mStopped) {
513 syncVar->lock();
514 syncVar->updateMaxDequeueCountLocked(maxDequeueBufferCount);
515 syncVar->unlock();
516 }
517 mMutex.unlock();
518 ALOGD("set max dequeue count %d from update", maxDequeueBufferCount);
519 }
520
521 } // namespace c2
522 } // namespace media
523 } // namespace hardware
524 } // namespace android
525