1 /*
2 * Copyright (C) 2010 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 // TODO(b/129481165): remove the #pragma below and fix conversion issues
18 #pragma clang diagnostic push
19 #pragma clang diagnostic ignored "-Wconversion"
20
21 #undef LOG_TAG
22 #define LOG_TAG "BufferLayerConsumer"
23 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
24 //#define LOG_NDEBUG 0
25
26 #include "BufferLayerConsumer.h"
27 #include "Layer.h"
28 #include "Scheduler/VsyncController.h"
29
30 #include <inttypes.h>
31
32 #include <cutils/compiler.h>
33
34 #include <hardware/hardware.h>
35
36 #include <math/mat4.h>
37
38 #include <gui/BufferItem.h>
39 #include <gui/GLConsumer.h>
40 #include <gui/ISurfaceComposer.h>
41 #include <gui/SurfaceComposerClient.h>
42 #include <private/gui/ComposerService.h>
43 #include <renderengine/RenderEngine.h>
44 #include <utils/Log.h>
45 #include <utils/String8.h>
46 #include <utils/Trace.h>
47
48 namespace android {
49
50 // Macros for including the BufferLayerConsumer name in log messages
51 #define BLC_LOGV(x, ...) ALOGV("[%s] " x, mName.string(), ##__VA_ARGS__)
52 #define BLC_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
53 //#define BLC_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
54 #define BLC_LOGW(x, ...) ALOGW("[%s] " x, mName.string(), ##__VA_ARGS__)
55 #define BLC_LOGE(x, ...) ALOGE("[%s] " x, mName.string(), ##__VA_ARGS__)
56
57 static const mat4 mtxIdentity;
58
BufferLayerConsumer(const sp<IGraphicBufferConsumer> & bq,renderengine::RenderEngine & engine,uint32_t tex,Layer * layer)59 BufferLayerConsumer::BufferLayerConsumer(const sp<IGraphicBufferConsumer>& bq,
60 renderengine::RenderEngine& engine, uint32_t tex,
61 Layer* layer)
62 : ConsumerBase(bq, false),
63 mCurrentCrop(Rect::EMPTY_RECT),
64 mCurrentTransform(0),
65 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
66 mCurrentFence(Fence::NO_FENCE),
67 mCurrentTimestamp(0),
68 mCurrentDataSpace(ui::Dataspace::UNKNOWN),
69 mCurrentFrameNumber(0),
70 mCurrentTransformToDisplayInverse(false),
71 mCurrentSurfaceDamage(),
72 mCurrentApi(0),
73 mDefaultWidth(1),
74 mDefaultHeight(1),
75 mFilteringEnabled(true),
76 mRE(engine),
77 mTexName(tex),
78 mLayer(layer),
79 mCurrentTexture(BufferQueue::INVALID_BUFFER_SLOT) {
80 BLC_LOGV("BufferLayerConsumer");
81
82 memcpy(mCurrentTransformMatrix, mtxIdentity.asArray(), sizeof(mCurrentTransformMatrix));
83
84 mConsumer->setConsumerUsageBits(DEFAULT_USAGE_FLAGS);
85 }
86
setDefaultBufferSize(uint32_t w,uint32_t h)87 status_t BufferLayerConsumer::setDefaultBufferSize(uint32_t w, uint32_t h) {
88 Mutex::Autolock lock(mMutex);
89 if (mAbandoned) {
90 BLC_LOGE("setDefaultBufferSize: BufferLayerConsumer is abandoned!");
91 return NO_INIT;
92 }
93 mDefaultWidth = w;
94 mDefaultHeight = h;
95 return mConsumer->setDefaultBufferSize(w, h);
96 }
97
setContentsChangedListener(const wp<ContentsChangedListener> & listener)98 void BufferLayerConsumer::setContentsChangedListener(const wp<ContentsChangedListener>& listener) {
99 setFrameAvailableListener(listener);
100 Mutex::Autolock lock(mMutex);
101 mContentsChangedListener = listener;
102 }
103
updateTexImage(BufferRejecter * rejecter,nsecs_t expectedPresentTime,bool * autoRefresh,bool * queuedBuffer,uint64_t maxFrameNumber)104 status_t BufferLayerConsumer::updateTexImage(BufferRejecter* rejecter, nsecs_t expectedPresentTime,
105 bool* autoRefresh, bool* queuedBuffer,
106 uint64_t maxFrameNumber) {
107 ATRACE_CALL();
108 BLC_LOGV("updateTexImage");
109 Mutex::Autolock lock(mMutex);
110
111 if (mAbandoned) {
112 BLC_LOGE("updateTexImage: BufferLayerConsumer is abandoned!");
113 return NO_INIT;
114 }
115
116 BufferItem item;
117
118 // Acquire the next buffer.
119 // In asynchronous mode the list is guaranteed to be one buffer
120 // deep, while in synchronous mode we use the oldest buffer.
121 status_t err = acquireBufferLocked(&item, expectedPresentTime, maxFrameNumber);
122 if (err != NO_ERROR) {
123 if (err == BufferQueue::NO_BUFFER_AVAILABLE) {
124 err = NO_ERROR;
125 } else if (err == BufferQueue::PRESENT_LATER) {
126 // return the error, without logging
127 } else {
128 BLC_LOGE("updateTexImage: acquire failed: %s (%d)", strerror(-err), err);
129 }
130 return err;
131 }
132
133 if (autoRefresh) {
134 *autoRefresh = item.mAutoRefresh;
135 }
136
137 if (queuedBuffer) {
138 *queuedBuffer = item.mQueuedBuffer;
139 }
140
141 // We call the rejecter here, in case the caller has a reason to
142 // not accept this buffer. This is used by SurfaceFlinger to
143 // reject buffers which have the wrong size
144 int slot = item.mSlot;
145 if (rejecter && rejecter->reject(mSlots[slot].mGraphicBuffer, item)) {
146 releaseBufferLocked(slot, mSlots[slot].mGraphicBuffer);
147 return BUFFER_REJECTED;
148 }
149
150 // Release the previous buffer.
151 err = updateAndReleaseLocked(item, &mPendingRelease);
152 if (err != NO_ERROR) {
153 return err;
154 }
155 return err;
156 }
157
setReleaseFence(const sp<Fence> & fence)158 void BufferLayerConsumer::setReleaseFence(const sp<Fence>& fence) {
159 if (!fence->isValid()) {
160 return;
161 }
162
163 auto slot = mPendingRelease.isPending ? mPendingRelease.currentTexture : mCurrentTexture;
164 if (slot == BufferQueue::INVALID_BUFFER_SLOT) {
165 return;
166 }
167
168 auto buffer = mPendingRelease.isPending ? mPendingRelease.graphicBuffer
169 : mCurrentTextureBuffer->getBuffer();
170 auto err = addReleaseFence(slot, buffer, fence);
171 if (err != OK) {
172 BLC_LOGE("setReleaseFence: failed to add the fence: %s (%d)", strerror(-err), err);
173 }
174 }
175
releasePendingBuffer()176 bool BufferLayerConsumer::releasePendingBuffer() {
177 if (!mPendingRelease.isPending) {
178 BLC_LOGV("Pending buffer already released");
179 return false;
180 }
181 BLC_LOGV("Releasing pending buffer");
182 Mutex::Autolock lock(mMutex);
183 status_t result =
184 releaseBufferLocked(mPendingRelease.currentTexture, mPendingRelease.graphicBuffer);
185 if (result < NO_ERROR) {
186 BLC_LOGE("releasePendingBuffer failed: %s (%d)", strerror(-result), result);
187 }
188 mPendingRelease = PendingRelease();
189 return true;
190 }
191
getPrevFinalReleaseFence() const192 sp<Fence> BufferLayerConsumer::getPrevFinalReleaseFence() const {
193 Mutex::Autolock lock(mMutex);
194 return ConsumerBase::mPrevFinalReleaseFence;
195 }
196
acquireBufferLocked(BufferItem * item,nsecs_t presentWhen,uint64_t maxFrameNumber)197 status_t BufferLayerConsumer::acquireBufferLocked(BufferItem* item, nsecs_t presentWhen,
198 uint64_t maxFrameNumber) {
199 status_t err = ConsumerBase::acquireBufferLocked(item, presentWhen, maxFrameNumber);
200 if (err != NO_ERROR) {
201 return err;
202 }
203
204 // If item->mGraphicBuffer is not null, this buffer has not been acquired
205 // before, so we need to clean up old references.
206 if (item->mGraphicBuffer != nullptr) {
207 std::lock_guard<std::mutex> lock(mImagesMutex);
208 if (mImages[item->mSlot] == nullptr || mImages[item->mSlot]->getBuffer() == nullptr ||
209 mImages[item->mSlot]->getBuffer()->getId() != item->mGraphicBuffer->getId()) {
210 mImages[item->mSlot] = std::make_shared<
211 renderengine::ExternalTexture>(item->mGraphicBuffer, mRE,
212 renderengine::ExternalTexture::Usage::READABLE);
213 }
214 }
215
216 return NO_ERROR;
217 }
218
updateAndReleaseLocked(const BufferItem & item,PendingRelease * pendingRelease)219 status_t BufferLayerConsumer::updateAndReleaseLocked(const BufferItem& item,
220 PendingRelease* pendingRelease) {
221 status_t err = NO_ERROR;
222
223 int slot = item.mSlot;
224
225 BLC_LOGV("updateAndRelease: (slot=%d buf=%p) -> (slot=%d buf=%p)", mCurrentTexture,
226 (mCurrentTextureBuffer != nullptr && mCurrentTextureBuffer->getBuffer() != nullptr)
227 ? mCurrentTextureBuffer->getBuffer()->handle
228 : 0,
229 slot, mSlots[slot].mGraphicBuffer->handle);
230
231 // Hang onto the pointer so that it isn't freed in the call to
232 // releaseBufferLocked() if we're in shared buffer mode and both buffers are
233 // the same.
234
235 std::shared_ptr<renderengine::ExternalTexture> nextTextureBuffer;
236 {
237 std::lock_guard<std::mutex> lock(mImagesMutex);
238 nextTextureBuffer = mImages[slot];
239 }
240
241 // release old buffer
242 if (mCurrentTexture != BufferQueue::INVALID_BUFFER_SLOT) {
243 if (pendingRelease == nullptr) {
244 status_t status =
245 releaseBufferLocked(mCurrentTexture, mCurrentTextureBuffer->getBuffer());
246 if (status < NO_ERROR) {
247 BLC_LOGE("updateAndRelease: failed to release buffer: %s (%d)", strerror(-status),
248 status);
249 err = status;
250 // keep going, with error raised [?]
251 }
252 } else {
253 pendingRelease->currentTexture = mCurrentTexture;
254 pendingRelease->graphicBuffer = mCurrentTextureBuffer->getBuffer();
255 pendingRelease->isPending = true;
256 }
257 }
258
259 // Update the BufferLayerConsumer state.
260 mCurrentTexture = slot;
261 mCurrentTextureBuffer = nextTextureBuffer;
262 mCurrentCrop = item.mCrop;
263 mCurrentTransform = item.mTransform;
264 mCurrentScalingMode = item.mScalingMode;
265 mCurrentTimestamp = item.mTimestamp;
266 mCurrentDataSpace = static_cast<ui::Dataspace>(item.mDataSpace);
267 mCurrentHdrMetadata = item.mHdrMetadata;
268 mCurrentFence = item.mFence;
269 mCurrentFenceTime = item.mFenceTime;
270 mCurrentFrameNumber = item.mFrameNumber;
271 mCurrentTransformToDisplayInverse = item.mTransformToDisplayInverse;
272 mCurrentSurfaceDamage = item.mSurfaceDamage;
273 mCurrentApi = item.mApi;
274
275 computeCurrentTransformMatrixLocked();
276
277 return err;
278 }
279
getTransformMatrix(float mtx[16])280 void BufferLayerConsumer::getTransformMatrix(float mtx[16]) {
281 Mutex::Autolock lock(mMutex);
282 memcpy(mtx, mCurrentTransformMatrix, sizeof(mCurrentTransformMatrix));
283 }
284
setFilteringEnabled(bool enabled)285 void BufferLayerConsumer::setFilteringEnabled(bool enabled) {
286 Mutex::Autolock lock(mMutex);
287 if (mAbandoned) {
288 BLC_LOGE("setFilteringEnabled: BufferLayerConsumer is abandoned!");
289 return;
290 }
291 bool needsRecompute = mFilteringEnabled != enabled;
292 mFilteringEnabled = enabled;
293
294 if (needsRecompute && mCurrentTextureBuffer == nullptr) {
295 BLC_LOGD("setFilteringEnabled called with mCurrentTextureBuffer == nullptr");
296 }
297
298 if (needsRecompute && mCurrentTextureBuffer != nullptr) {
299 computeCurrentTransformMatrixLocked();
300 }
301 }
302
computeCurrentTransformMatrixLocked()303 void BufferLayerConsumer::computeCurrentTransformMatrixLocked() {
304 BLC_LOGV("computeCurrentTransformMatrixLocked");
305 if (mCurrentTextureBuffer == nullptr || mCurrentTextureBuffer->getBuffer() == nullptr) {
306 BLC_LOGD("computeCurrentTransformMatrixLocked: "
307 "mCurrentTextureBuffer is nullptr");
308 }
309 GLConsumer::computeTransformMatrix(mCurrentTransformMatrix,
310 mCurrentTextureBuffer == nullptr
311 ? nullptr
312 : mCurrentTextureBuffer->getBuffer(),
313 getCurrentCropLocked(), mCurrentTransform,
314 mFilteringEnabled);
315 }
316
getTimestamp()317 nsecs_t BufferLayerConsumer::getTimestamp() {
318 BLC_LOGV("getTimestamp");
319 Mutex::Autolock lock(mMutex);
320 return mCurrentTimestamp;
321 }
322
getCurrentDataSpace()323 ui::Dataspace BufferLayerConsumer::getCurrentDataSpace() {
324 BLC_LOGV("getCurrentDataSpace");
325 Mutex::Autolock lock(mMutex);
326 return mCurrentDataSpace;
327 }
328
getCurrentHdrMetadata() const329 const HdrMetadata& BufferLayerConsumer::getCurrentHdrMetadata() const {
330 BLC_LOGV("getCurrentHdrMetadata");
331 Mutex::Autolock lock(mMutex);
332 return mCurrentHdrMetadata;
333 }
334
getFrameNumber()335 uint64_t BufferLayerConsumer::getFrameNumber() {
336 BLC_LOGV("getFrameNumber");
337 Mutex::Autolock lock(mMutex);
338 return mCurrentFrameNumber;
339 }
340
getTransformToDisplayInverse() const341 bool BufferLayerConsumer::getTransformToDisplayInverse() const {
342 Mutex::Autolock lock(mMutex);
343 return mCurrentTransformToDisplayInverse;
344 }
345
getSurfaceDamage() const346 const Region& BufferLayerConsumer::getSurfaceDamage() const {
347 return mCurrentSurfaceDamage;
348 }
349
mergeSurfaceDamage(const Region & damage)350 void BufferLayerConsumer::mergeSurfaceDamage(const Region& damage) {
351 if (damage.bounds() == Rect::INVALID_RECT ||
352 mCurrentSurfaceDamage.bounds() == Rect::INVALID_RECT) {
353 mCurrentSurfaceDamage = Region::INVALID_REGION;
354 } else {
355 mCurrentSurfaceDamage |= damage;
356 }
357 }
358
getCurrentApi() const359 int BufferLayerConsumer::getCurrentApi() const {
360 Mutex::Autolock lock(mMutex);
361 return mCurrentApi;
362 }
363
getCurrentBuffer(int * outSlot,sp<Fence> * outFence) const364 std::shared_ptr<renderengine::ExternalTexture> BufferLayerConsumer::getCurrentBuffer(
365 int* outSlot, sp<Fence>* outFence) const {
366 Mutex::Autolock lock(mMutex);
367
368 if (outSlot != nullptr) {
369 *outSlot = mCurrentTexture;
370 }
371
372 if (outFence != nullptr) {
373 *outFence = mCurrentFence;
374 }
375
376 return mCurrentTextureBuffer == nullptr ? nullptr : mCurrentTextureBuffer;
377 }
378
getCurrentCrop() const379 Rect BufferLayerConsumer::getCurrentCrop() const {
380 Mutex::Autolock lock(mMutex);
381 return getCurrentCropLocked();
382 }
383
getCurrentCropLocked() const384 Rect BufferLayerConsumer::getCurrentCropLocked() const {
385 uint32_t width = mDefaultWidth;
386 uint32_t height = mDefaultHeight;
387 // If the buffer comes with a rotated bit for 90 (or 270) degrees, switch width/height in order
388 // to scale and crop correctly.
389 if (mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
390 width = mDefaultHeight;
391 height = mDefaultWidth;
392 }
393
394 return (mCurrentScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP)
395 ? GLConsumer::scaleDownCrop(mCurrentCrop, width, height)
396 : mCurrentCrop;
397 }
398
getCurrentTransform() const399 uint32_t BufferLayerConsumer::getCurrentTransform() const {
400 Mutex::Autolock lock(mMutex);
401 return mCurrentTransform;
402 }
403
getCurrentScalingMode() const404 uint32_t BufferLayerConsumer::getCurrentScalingMode() const {
405 Mutex::Autolock lock(mMutex);
406 return mCurrentScalingMode;
407 }
408
getCurrentFence() const409 sp<Fence> BufferLayerConsumer::getCurrentFence() const {
410 Mutex::Autolock lock(mMutex);
411 return mCurrentFence;
412 }
413
getCurrentFenceTime() const414 std::shared_ptr<FenceTime> BufferLayerConsumer::getCurrentFenceTime() const {
415 Mutex::Autolock lock(mMutex);
416 return mCurrentFenceTime;
417 }
418
freeBufferLocked(int slotIndex)419 void BufferLayerConsumer::freeBufferLocked(int slotIndex) {
420 BLC_LOGV("freeBufferLocked: slotIndex=%d", slotIndex);
421 std::lock_guard<std::mutex> lock(mImagesMutex);
422 if (slotIndex == mCurrentTexture) {
423 mCurrentTexture = BufferQueue::INVALID_BUFFER_SLOT;
424 }
425 mImages[slotIndex] = nullptr;
426 ConsumerBase::freeBufferLocked(slotIndex);
427 }
428
onDisconnect()429 void BufferLayerConsumer::onDisconnect() {
430 Mutex::Autolock lock(mMutex);
431
432 if (mAbandoned) {
433 // Nothing to do if we're already abandoned.
434 return;
435 }
436
437 mLayer->onDisconnect();
438 }
439
onSidebandStreamChanged()440 void BufferLayerConsumer::onSidebandStreamChanged() {
441 FrameAvailableListener* unsafeFrameAvailableListener = nullptr;
442 {
443 Mutex::Autolock lock(mFrameAvailableMutex);
444 unsafeFrameAvailableListener = mFrameAvailableListener.unsafe_get();
445 }
446 sp<ContentsChangedListener> listener;
447 { // scope for the lock
448 Mutex::Autolock lock(mMutex);
449 ALOG_ASSERT(unsafeFrameAvailableListener == mContentsChangedListener.unsafe_get());
450 listener = mContentsChangedListener.promote();
451 }
452
453 if (listener != nullptr) {
454 listener->onSidebandStreamChanged();
455 }
456 }
457
onBufferAvailable(const BufferItem & item)458 void BufferLayerConsumer::onBufferAvailable(const BufferItem& item) {
459 if (item.mGraphicBuffer != nullptr && item.mSlot != BufferQueue::INVALID_BUFFER_SLOT) {
460 std::lock_guard<std::mutex> lock(mImagesMutex);
461 const std::shared_ptr<renderengine::ExternalTexture>& oldImage = mImages[item.mSlot];
462 if (oldImage == nullptr || oldImage->getBuffer() == nullptr ||
463 oldImage->getBuffer()->getId() != item.mGraphicBuffer->getId()) {
464 mImages[item.mSlot] = std::make_shared<
465 renderengine::ExternalTexture>(item.mGraphicBuffer, mRE,
466 renderengine::ExternalTexture::Usage::READABLE);
467 }
468 }
469 }
470
addAndGetFrameTimestamps(const NewFrameEventsEntry * newTimestamps,FrameEventHistoryDelta * outDelta)471 void BufferLayerConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
472 FrameEventHistoryDelta* outDelta) {
473 Mutex::Autolock lock(mMutex);
474
475 if (mAbandoned) {
476 // Nothing to do if we're already abandoned.
477 return;
478 }
479
480 mLayer->addAndGetFrameTimestamps(newTimestamps, outDelta);
481 }
482
abandonLocked()483 void BufferLayerConsumer::abandonLocked() {
484 BLC_LOGV("abandonLocked");
485 mCurrentTextureBuffer = nullptr;
486 for (int i = 0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) {
487 std::lock_guard<std::mutex> lock(mImagesMutex);
488 mImages[i] = nullptr;
489 }
490 ConsumerBase::abandonLocked();
491 }
492
setConsumerUsageBits(uint64_t usage)493 status_t BufferLayerConsumer::setConsumerUsageBits(uint64_t usage) {
494 return ConsumerBase::setConsumerUsageBits(usage | DEFAULT_USAGE_FLAGS);
495 }
496
dumpLocked(String8 & result,const char * prefix) const497 void BufferLayerConsumer::dumpLocked(String8& result, const char* prefix) const {
498 result.appendFormat("%smTexName=%d mCurrentTexture=%d\n"
499 "%smCurrentCrop=[%d,%d,%d,%d] mCurrentTransform=%#x\n",
500 prefix, mTexName, mCurrentTexture, prefix, mCurrentCrop.left,
501 mCurrentCrop.top, mCurrentCrop.right, mCurrentCrop.bottom,
502 mCurrentTransform);
503
504 ConsumerBase::dumpLocked(result, prefix);
505 }
506 }; // namespace android
507
508 // TODO(b/129481165): remove the #pragma below and fix conversion issues
509 #pragma clang diagnostic pop // ignored "-Wconversion"
510