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 {
221 std::scoped_lock<std::mutex> l(mMutex);
222 bool stopped = mStopped;
223 mStopped = false;
224 if (generation == mGeneration) {
225 // case of old BlockPool destruction
226 C2SyncVariables *var = mSyncMem ? mSyncMem->mem() : nullptr;
227 if (syncObj && var) {
228 *syncObj = std::make_shared<V1_2::SurfaceSyncObj>();
229 (*syncObj)->bqId = bqId;
230 (*syncObj)->syncMemory = mSyncMem->handle();
231 (*syncObj)->generationId = generation;
232 (*syncObj)->consumerUsage = consumerUsage;
233 mMaxDequeueBufferCount = maxDequeueBufferCount;
234 var->lock();
235 var->setSyncStatusLocked(C2SyncVariables::STATUS_INIT);
236 var->setInitialDequeueCountLocked(mMaxDequeueBufferCount, 0);
237 var->unlock();
238 }
239 return false;
240 }
241 std::shared_ptr<C2SurfaceSyncMemory> oldMem = mSyncMem;
242 C2SyncVariables *oldSync = mSyncMem ? mSyncMem->mem() : nullptr;
243 if (oldSync) {
244 oldSync->lock();
245 oldSync->setSyncStatusLocked(C2SyncVariables::STATUS_SWITCHING);
246 oldSync->unlock();
247 }
248 mSyncMem.reset();
249 if (syncMem) {
250 mSyncMem = syncMem;
251 }
252 C2SyncVariables *newSync = mSyncMem ? mSyncMem->mem() : nullptr;
253
254 mIgbp = igbp;
255 mGeneration = generation;
256 mBqId = bqId;
257 mOwner = std::make_shared<int>(0);
258 mMaxDequeueBufferCount = maxDequeueBufferCount;
259 if (igbp == nullptr) {
260 return false;
261 }
262 for (int i = 0; i < BufferQueueDefs::NUM_BUFFER_SLOTS; ++i) {
263 if (mBqId == 0 || !mBuffers[i] || stopped) {
264 continue;
265 }
266 std::shared_ptr<_C2BlockPoolData> data = mPoolDatas[i].lock();
267 if (!data ||
268 !_C2BlockFactory::BeginAttachBlockToBufferQueue(data)) {
269 continue;
270 }
271 ++tryNum;
272 int bqSlot;
273
274 // Update buffer's generation and usage.
275 if ((mBuffers[i]->getUsage() & consumerUsage) != consumerUsage) {
276 mBuffers[i] = new GraphicBuffer(
277 mBuffers[i]->handle, GraphicBuffer::CLONE_HANDLE,
278 mBuffers[i]->width, mBuffers[i]->height,
279 mBuffers[i]->format, mBuffers[i]->layerCount,
280 mBuffers[i]->getUsage() | consumerUsage,
281 mBuffers[i]->stride);
282 if (mBuffers[i]->initCheck() != OK) {
283 ALOGW("%s() failed to update usage, original usage=%" PRIx64
284 ", consumer usage=%" PRIx64,
285 __func__, mBuffers[i]->getUsage(), consumerUsage);
286 continue;
287 }
288 }
289 mBuffers[i]->setGenerationNumber(generation);
290
291 status_t result = igbp->attachBuffer(&bqSlot, mBuffers[i]);
292 if (result != OK) {
293 continue;
294 }
295 bool attach =
296 _C2BlockFactory::EndAttachBlockToBufferQueue(
297 data, mOwner, getHgbp(mIgbp), mSyncMem,
298 generation, bqId, bqSlot);
299 if (!attach) {
300 igbp->cancelBuffer(bqSlot, Fence::NO_FENCE);
301 continue;
302 }
303 buffers[bqSlot] = mBuffers[i];
304 poolDatas[bqSlot] = data;
305 ++success;
306 }
307 for (int i = 0; i < BufferQueueDefs::NUM_BUFFER_SLOTS; ++i) {
308 mBuffers[i] = buffers[i];
309 mPoolDatas[i] = poolDatas[i];
310 }
311 if (newSync) {
312 newSync->lock();
313 newSync->setInitialDequeueCountLocked(mMaxDequeueBufferCount, success);
314 newSync->unlock();
315 }
316 }
317 ALOGD("remote graphic buffer migration %zu/%zu",
318 success, tryNum);
319 return true;
320 }
321
stop()322 void OutputBufferQueue::stop() {
323 std::scoped_lock<std::mutex> l(mMutex);
324 mStopped = true;
325 mOwner.reset(); // destructor of the block will not triger IGBP::cancel()
326 }
327
registerBuffer(const C2ConstGraphicBlock & block)328 bool OutputBufferQueue::registerBuffer(const C2ConstGraphicBlock& block) {
329 std::shared_ptr<_C2BlockPoolData> data =
330 _C2BlockFactory::GetGraphicBlockPoolData(block);
331 if (!data) {
332 return false;
333 }
334 std::scoped_lock<std::mutex> l(mMutex);
335
336 if (!mIgbp || mStopped) {
337 return false;
338 }
339
340 uint32_t oldGeneration;
341 uint64_t oldId;
342 int32_t oldSlot;
343 // If the block is not bufferqueue-based, do nothing.
344 if (!_C2BlockFactory::GetBufferQueueData(
345 data, &oldGeneration, &oldId, &oldSlot) || (oldId == 0)) {
346 return false;
347 }
348 // If the block's bqId is the same as the desired bqId, just hold.
349 if ((oldId == mBqId) && (oldGeneration == mGeneration)) {
350 LOG(VERBOSE) << "holdBufferQueueBlock -- import without attaching:"
351 << " bqId " << oldId
352 << ", bqSlot " << oldSlot
353 << ", generation " << mGeneration
354 << ".";
355 _C2BlockFactory::HoldBlockFromBufferQueue(data, mOwner, getHgbp(mIgbp), mSyncMem);
356 mPoolDatas[oldSlot] = data;
357 mBuffers[oldSlot] = createGraphicBuffer(block);
358 mBuffers[oldSlot]->setGenerationNumber(mGeneration);
359 return true;
360 }
361 int32_t d = (int32_t) mGeneration - (int32_t) oldGeneration;
362 LOG(WARNING) << "receiving stale buffer: generation "
363 << mGeneration << " , diff " << d << " : slot "
364 << oldSlot;
365 return false;
366 }
367
outputBuffer(const C2ConstGraphicBlock & block,const BnGraphicBufferProducer::QueueBufferInput & input,BnGraphicBufferProducer::QueueBufferOutput * output)368 status_t OutputBufferQueue::outputBuffer(
369 const C2ConstGraphicBlock& block,
370 const BnGraphicBufferProducer::QueueBufferInput& input,
371 BnGraphicBufferProducer::QueueBufferOutput* output) {
372 uint32_t generation;
373 uint64_t bqId;
374 int32_t bqSlot;
375 bool display = V1_0::utils::displayBufferQueueBlock(block);
376 if (!getBufferQueueAssignment(block, &generation, &bqId, &bqSlot) ||
377 bqId == 0) {
378 // Block not from bufferqueue -- it must be attached before queuing.
379
380 std::shared_ptr<C2SurfaceSyncMemory> syncMem;
381 mMutex.lock();
382 bool stopped = mStopped;
383 sp<IGraphicBufferProducer> outputIgbp = mIgbp;
384 uint32_t outputGeneration = mGeneration;
385 syncMem = mSyncMem;
386 mMutex.unlock();
387
388 if (stopped) {
389 LOG(INFO) << "outputBuffer -- already stopped.";
390 return DEAD_OBJECT;
391 }
392
393 status_t status = attachToBufferQueue(
394 block, outputIgbp, outputGeneration, &bqSlot, syncMem);
395
396 if (status != OK) {
397 LOG(WARNING) << "outputBuffer -- attaching failed.";
398 return INVALID_OPERATION;
399 }
400
401 auto syncVar = syncMem ? syncMem->mem() : nullptr;
402 if(syncVar) {
403 syncVar->lock();
404 status = outputIgbp->queueBuffer(static_cast<int>(bqSlot),
405 input, output);
406 if (status == OK) {
407 syncVar->notifyQueuedLocked();
408 }
409 syncVar->unlock();
410 } else {
411 status = outputIgbp->queueBuffer(static_cast<int>(bqSlot),
412 input, output);
413 }
414 if (status != OK) {
415 LOG(ERROR) << "outputBuffer -- queueBuffer() failed "
416 "on non-bufferqueue-based block. "
417 "Error = " << status << ".";
418 return status;
419 }
420 return OK;
421 }
422
423 std::shared_ptr<C2SurfaceSyncMemory> syncMem;
424 mMutex.lock();
425 bool stopped = mStopped;
426 sp<IGraphicBufferProducer> outputIgbp = mIgbp;
427 uint32_t outputGeneration = mGeneration;
428 uint64_t outputBqId = mBqId;
429 syncMem = mSyncMem;
430 mMutex.unlock();
431
432 if (stopped) {
433 LOG(INFO) << "outputBuffer -- already stopped.";
434 return DEAD_OBJECT;
435 }
436
437 if (!outputIgbp) {
438 LOG(VERBOSE) << "outputBuffer -- output surface is null.";
439 return NO_INIT;
440 }
441
442 if (!display) {
443 LOG(WARNING) << "outputBuffer -- cannot display "
444 "bufferqueue-based block to the bufferqueue.";
445 return UNKNOWN_ERROR;
446 }
447 if (bqId != outputBqId || generation != outputGeneration) {
448 int32_t diff = (int32_t) outputGeneration - (int32_t) generation;
449 LOG(WARNING) << "outputBuffer -- buffers from old generation to "
450 << outputGeneration << " , diff: " << diff
451 << " , slot: " << bqSlot;
452 return DEAD_OBJECT;
453 }
454
455 auto syncVar = syncMem ? syncMem->mem() : nullptr;
456 status_t status = OK;
457 if (syncVar) {
458 syncVar->lock();
459 status = outputIgbp->queueBuffer(static_cast<int>(bqSlot),
460 input, output);
461 if (status == OK) {
462 syncVar->notifyQueuedLocked();
463 }
464 syncVar->unlock();
465 } else {
466 status = outputIgbp->queueBuffer(static_cast<int>(bqSlot),
467 input, output);
468 }
469
470 if (status != OK) {
471 LOG(ERROR) << "outputBuffer -- queueBuffer() failed "
472 "on bufferqueue-based block. "
473 "Error = " << status << ".";
474 return status;
475 }
476 return OK;
477 }
478
holdBufferQueueBlocks(const std::list<std::unique_ptr<C2Work>> & workList)479 void OutputBufferQueue::holdBufferQueueBlocks(
480 const std::list<std::unique_ptr<C2Work>>& workList) {
481 forEachBlock(workList,
482 std::bind(&OutputBufferQueue::registerBuffer,
483 this, std::placeholders::_1));
484 }
485
updateMaxDequeueBufferCount(int maxDequeueBufferCount)486 void OutputBufferQueue::updateMaxDequeueBufferCount(int maxDequeueBufferCount) {
487 mMutex.lock();
488 mMaxDequeueBufferCount = maxDequeueBufferCount;
489 auto syncVar = mSyncMem ? mSyncMem->mem() : nullptr;
490 if (syncVar && !mStopped) {
491 syncVar->lock();
492 syncVar->updateMaxDequeueCountLocked(maxDequeueBufferCount);
493 syncVar->unlock();
494 }
495 mMutex.unlock();
496 ALOGD("set max dequeue count %d from update", maxDequeueBufferCount);
497 }
498
499 } // namespace c2
500 } // namespace media
501 } // namespace hardware
502 } // namespace android
503
504