1 /*
2 * Copyright (C) 2017 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 #undef LOG_TAG
19 #define LOG_TAG "BufferStateLayer"
20 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
22 #include <limits>
23
24 #include <compositionengine/Display.h>
25 #include <compositionengine/Layer.h>
26 #include <compositionengine/OutputLayer.h>
27 #include <compositionengine/impl/LayerCompositionState.h>
28 #include <compositionengine/impl/OutputLayerCompositionState.h>
29 #include <gui/BufferQueue.h>
30 #include <private/gui/SyncFeatures.h>
31 #include <renderengine/Image.h>
32
33 #include "BufferStateLayer.h"
34 #include "ColorLayer.h"
35 #include "TimeStats/TimeStats.h"
36
37 namespace android {
38
39 // clang-format off
40 const std::array<float, 16> BufferStateLayer::IDENTITY_MATRIX{
41 1, 0, 0, 0,
42 0, 1, 0, 0,
43 0, 0, 1, 0,
44 0, 0, 0, 1
45 };
46 // clang-format on
47
BufferStateLayer(const LayerCreationArgs & args)48 BufferStateLayer::BufferStateLayer(const LayerCreationArgs& args)
49 : BufferLayer(args), mHwcSlotGenerator(new HwcSlotGenerator()) {
50 mOverrideScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
51 mCurrentState.dataspace = ui::Dataspace::V0_SRGB;
52 }
53
~BufferStateLayer()54 BufferStateLayer::~BufferStateLayer() {
55 if (mActiveBuffer != nullptr) {
56 // Ensure that mActiveBuffer is uncached from RenderEngine here, as
57 // RenderEngine may have been using the buffer as an external texture
58 // after the client uncached the buffer.
59 auto& engine(mFlinger->getRenderEngine());
60 engine.unbindExternalTextureBuffer(mActiveBuffer->getId());
61 }
62 }
63
64 // -----------------------------------------------------------------------
65 // Interface implementation for Layer
66 // -----------------------------------------------------------------------
onLayerDisplayed(const sp<Fence> & releaseFence)67 void BufferStateLayer::onLayerDisplayed(const sp<Fence>& releaseFence) {
68 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
69 // buffer that was presented on this layer. The first transaction that came in this frame that
70 // replaced the previous buffer on this layer needs this release fence, because the fence will
71 // let the client know when that previous buffer is removed from the screen.
72 //
73 // Every other transaction on this layer does not need a release fence because no other
74 // Transactions that were set on this layer this frame are going to have their preceeding buffer
75 // removed from the display this frame.
76 //
77 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
78 // buffer so it doesn't need a previous release fence because the layer still needs the previous
79 // buffer. The second transaction contains a buffer so it needs a previous release fence because
80 // the previous buffer will be released this frame. The third transaction also contains a
81 // buffer. It replaces the buffer in the second transaction. The buffer in the second
82 // transaction will now no longer be presented so it is released immediately and the third
83 // transaction doesn't need a previous release fence.
84 for (auto& handle : mDrawingState.callbackHandles) {
85 if (handle->releasePreviousBuffer) {
86 handle->previousReleaseFence = releaseFence;
87 break;
88 }
89 }
90 }
91
setTransformHint(uint32_t) const92 void BufferStateLayer::setTransformHint(uint32_t /*orientation*/) const {
93 // TODO(marissaw): send the transform hint to buffer owner
94 return;
95 }
96
releasePendingBuffer(nsecs_t)97 void BufferStateLayer::releasePendingBuffer(nsecs_t /*dequeueReadyTime*/) {
98 mFlinger->getTransactionCompletedThread().addPresentedCallbackHandles(
99 mDrawingState.callbackHandles);
100
101 mDrawingState.callbackHandles = {};
102 }
103
shouldPresentNow(nsecs_t) const104 bool BufferStateLayer::shouldPresentNow(nsecs_t /*expectedPresentTime*/) const {
105 if (getSidebandStreamChanged() || getAutoRefresh()) {
106 return true;
107 }
108
109 return hasFrameUpdate();
110 }
111
willPresentCurrentTransaction() const112 bool BufferStateLayer::willPresentCurrentTransaction() const {
113 // Returns true if the most recent Transaction applied to CurrentState will be presented.
114 return getSidebandStreamChanged() || getAutoRefresh() ||
115 (mCurrentState.modified &&
116 (mCurrentState.buffer != nullptr || mCurrentState.bgColorLayer != nullptr));
117 }
118
getTransformToDisplayInverse() const119 bool BufferStateLayer::getTransformToDisplayInverse() const {
120 return mCurrentState.transformToDisplayInverse;
121 }
122
pushPendingState()123 void BufferStateLayer::pushPendingState() {
124 if (!mCurrentState.modified) {
125 return;
126 }
127 mPendingStates.push_back(mCurrentState);
128 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
129 }
130
applyPendingStates(Layer::State * stateToCommit)131 bool BufferStateLayer::applyPendingStates(Layer::State* stateToCommit) {
132 const bool stateUpdateAvailable = !mPendingStates.empty();
133 while (!mPendingStates.empty()) {
134 popPendingState(stateToCommit);
135 }
136 mCurrentStateModified = stateUpdateAvailable && mCurrentState.modified;
137 mCurrentState.modified = false;
138 return stateUpdateAvailable;
139 }
140
141 // Crop that applies to the window
getCrop(const Layer::State &) const142 Rect BufferStateLayer::getCrop(const Layer::State& /*s*/) const {
143 return Rect::INVALID_RECT;
144 }
145
setTransform(uint32_t transform)146 bool BufferStateLayer::setTransform(uint32_t transform) {
147 if (mCurrentState.transform == transform) return false;
148 mCurrentState.transform = transform;
149 mCurrentState.modified = true;
150 setTransactionFlags(eTransactionNeeded);
151 return true;
152 }
153
setTransformToDisplayInverse(bool transformToDisplayInverse)154 bool BufferStateLayer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
155 if (mCurrentState.transformToDisplayInverse == transformToDisplayInverse) return false;
156 mCurrentState.sequence++;
157 mCurrentState.transformToDisplayInverse = transformToDisplayInverse;
158 mCurrentState.modified = true;
159 setTransactionFlags(eTransactionNeeded);
160 return true;
161 }
162
setCrop(const Rect & crop)163 bool BufferStateLayer::setCrop(const Rect& crop) {
164 Rect c = crop;
165 if (c.left < 0) {
166 c.left = 0;
167 }
168 if (c.top < 0) {
169 c.top = 0;
170 }
171 // If the width and/or height are < 0, make it [0, 0, -1, -1] so the equality comparision below
172 // treats all invalid rectangles the same.
173 if (!c.isValid()) {
174 c.makeInvalid();
175 }
176
177 if (mCurrentState.crop == c) return false;
178 mCurrentState.crop = c;
179 mCurrentState.modified = true;
180 setTransactionFlags(eTransactionNeeded);
181 return true;
182 }
183
setFrame(const Rect & frame)184 bool BufferStateLayer::setFrame(const Rect& frame) {
185 int x = frame.left;
186 int y = frame.top;
187 int w = frame.getWidth();
188 int h = frame.getHeight();
189
190 if (x < 0) {
191 x = 0;
192 w = frame.right;
193 }
194
195 if (y < 0) {
196 y = 0;
197 h = frame.bottom;
198 }
199
200 if (mCurrentState.active.transform.tx() == x && mCurrentState.active.transform.ty() == y &&
201 mCurrentState.active.w == w && mCurrentState.active.h == h) {
202 return false;
203 }
204
205 if (!frame.isValid()) {
206 x = y = w = h = 0;
207 }
208 mCurrentState.active.transform.set(x, y);
209 mCurrentState.active.w = w;
210 mCurrentState.active.h = h;
211
212 mCurrentState.sequence++;
213 mCurrentState.modified = true;
214 setTransactionFlags(eTransactionNeeded);
215 return true;
216 }
217
setBuffer(const sp<GraphicBuffer> & buffer,nsecs_t postTime,nsecs_t desiredPresentTime,const client_cache_t & clientCacheId)218 bool BufferStateLayer::setBuffer(const sp<GraphicBuffer>& buffer, nsecs_t postTime,
219 nsecs_t desiredPresentTime, const client_cache_t& clientCacheId) {
220 if (mCurrentState.buffer) {
221 mReleasePreviousBuffer = true;
222 }
223
224 mCurrentState.buffer = buffer;
225 mCurrentState.clientCacheId = clientCacheId;
226 mCurrentState.modified = true;
227 setTransactionFlags(eTransactionNeeded);
228
229 mFlinger->mTimeStats->setPostTime(getSequence(), getFrameNumber(), getName().c_str(), postTime);
230 mDesiredPresentTime = desiredPresentTime;
231
232 if (mFlinger->mUseSmart90ForVideo) {
233 const nsecs_t presentTime = (mDesiredPresentTime == -1) ? 0 : mDesiredPresentTime;
234 mFlinger->mScheduler->addLayerPresentTimeAndHDR(mSchedulerLayerHandle, presentTime,
235 mCurrentState.hdrMetadata.validTypes != 0);
236 }
237
238 return true;
239 }
240
setAcquireFence(const sp<Fence> & fence)241 bool BufferStateLayer::setAcquireFence(const sp<Fence>& fence) {
242 // The acquire fences of BufferStateLayers have already signaled before they are set
243 mCallbackHandleAcquireTime = fence->getSignalTime();
244
245 mCurrentState.acquireFence = fence;
246 mCurrentState.modified = true;
247 setTransactionFlags(eTransactionNeeded);
248 return true;
249 }
250
setDataspace(ui::Dataspace dataspace)251 bool BufferStateLayer::setDataspace(ui::Dataspace dataspace) {
252 if (mCurrentState.dataspace == dataspace) return false;
253 mCurrentState.dataspace = dataspace;
254 mCurrentState.modified = true;
255 setTransactionFlags(eTransactionNeeded);
256 return true;
257 }
258
setHdrMetadata(const HdrMetadata & hdrMetadata)259 bool BufferStateLayer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
260 if (mCurrentState.hdrMetadata == hdrMetadata) return false;
261 mCurrentState.hdrMetadata = hdrMetadata;
262 mCurrentState.modified = true;
263 setTransactionFlags(eTransactionNeeded);
264 return true;
265 }
266
setSurfaceDamageRegion(const Region & surfaceDamage)267 bool BufferStateLayer::setSurfaceDamageRegion(const Region& surfaceDamage) {
268 mCurrentState.surfaceDamageRegion = surfaceDamage;
269 mCurrentState.modified = true;
270 setTransactionFlags(eTransactionNeeded);
271 return true;
272 }
273
setApi(int32_t api)274 bool BufferStateLayer::setApi(int32_t api) {
275 if (mCurrentState.api == api) return false;
276 mCurrentState.api = api;
277 mCurrentState.modified = true;
278 setTransactionFlags(eTransactionNeeded);
279 return true;
280 }
281
setSidebandStream(const sp<NativeHandle> & sidebandStream)282 bool BufferStateLayer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
283 if (mCurrentState.sidebandStream == sidebandStream) return false;
284 mCurrentState.sidebandStream = sidebandStream;
285 mCurrentState.modified = true;
286 setTransactionFlags(eTransactionNeeded);
287
288 if (!mSidebandStreamChanged.exchange(true)) {
289 // mSidebandStreamChanged was false
290 mFlinger->signalLayerUpdate();
291 }
292 return true;
293 }
294
setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>> & handles)295 bool BufferStateLayer::setTransactionCompletedListeners(
296 const std::vector<sp<CallbackHandle>>& handles) {
297 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
298 if (handles.empty()) {
299 mReleasePreviousBuffer = false;
300 return false;
301 }
302
303 const bool willPresent = willPresentCurrentTransaction();
304
305 for (const auto& handle : handles) {
306 // If this transaction set a buffer on this layer, release its previous buffer
307 handle->releasePreviousBuffer = mReleasePreviousBuffer;
308
309 // If this layer will be presented in this frame
310 if (willPresent) {
311 // If this transaction set an acquire fence on this layer, set its acquire time
312 handle->acquireTime = mCallbackHandleAcquireTime;
313
314 // Notify the transaction completed thread that there is a pending latched callback
315 // handle
316 mFlinger->getTransactionCompletedThread().registerPendingCallbackHandle(handle);
317
318 // Store so latched time and release fence can be set
319 mCurrentState.callbackHandles.push_back(handle);
320
321 } else { // If this layer will NOT need to be relatched and presented this frame
322 // Notify the transaction completed thread this handle is done
323 mFlinger->getTransactionCompletedThread().addUnpresentedCallbackHandle(handle);
324 }
325 }
326
327 mReleasePreviousBuffer = false;
328 mCallbackHandleAcquireTime = -1;
329
330 return willPresent;
331 }
332
setTransparentRegionHint(const Region & transparent)333 bool BufferStateLayer::setTransparentRegionHint(const Region& transparent) {
334 mCurrentState.transparentRegionHint = transparent;
335 mCurrentState.modified = true;
336 setTransactionFlags(eTransactionNeeded);
337 return true;
338 }
339
getBufferSize(const State & s) const340 Rect BufferStateLayer::getBufferSize(const State& s) const {
341 // for buffer state layers we use the display frame size as the buffer size.
342 if (getActiveWidth(s) < UINT32_MAX && getActiveHeight(s) < UINT32_MAX) {
343 return Rect(getActiveWidth(s), getActiveHeight(s));
344 }
345
346 // if the display frame is not defined, use the parent bounds as the buffer size.
347 const auto& p = mDrawingParent.promote();
348 if (p != nullptr) {
349 Rect parentBounds = Rect(p->getBounds(Region()));
350 if (!parentBounds.isEmpty()) {
351 return parentBounds;
352 }
353 }
354
355 return Rect::INVALID_RECT;
356 }
357
computeSourceBounds(const FloatRect & parentBounds) const358 FloatRect BufferStateLayer::computeSourceBounds(const FloatRect& parentBounds) const {
359 const State& s(getDrawingState());
360 // for buffer state layers we use the display frame size as the buffer size.
361 if (getActiveWidth(s) < UINT32_MAX && getActiveHeight(s) < UINT32_MAX) {
362 return FloatRect(0, 0, getActiveWidth(s), getActiveHeight(s));
363 }
364
365 // if the display frame is not defined, use the parent bounds as the buffer size.
366 return parentBounds;
367 }
368
369 // -----------------------------------------------------------------------
370
371 // -----------------------------------------------------------------------
372 // Interface implementation for BufferLayer
373 // -----------------------------------------------------------------------
fenceHasSignaled() const374 bool BufferStateLayer::fenceHasSignaled() const {
375 if (latchUnsignaledBuffers()) {
376 return true;
377 }
378
379 return getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
380 }
381
framePresentTimeIsCurrent() const382 bool BufferStateLayer::framePresentTimeIsCurrent() const {
383 if (!hasFrameUpdate() || isRemovedFromCurrentState()) {
384 return true;
385 }
386
387 return mDesiredPresentTime <= mFlinger->getExpectedPresentTime();
388 }
389
getDesiredPresentTime()390 nsecs_t BufferStateLayer::getDesiredPresentTime() {
391 return mDesiredPresentTime;
392 }
393
getCurrentFenceTime() const394 std::shared_ptr<FenceTime> BufferStateLayer::getCurrentFenceTime() const {
395 return std::make_shared<FenceTime>(getDrawingState().acquireFence);
396 }
397
getDrawingTransformMatrix(float * matrix)398 void BufferStateLayer::getDrawingTransformMatrix(float *matrix) {
399 std::copy(std::begin(mTransformMatrix), std::end(mTransformMatrix), matrix);
400 }
401
getDrawingTransform() const402 uint32_t BufferStateLayer::getDrawingTransform() const {
403 return getDrawingState().transform;
404 }
405
getDrawingDataSpace() const406 ui::Dataspace BufferStateLayer::getDrawingDataSpace() const {
407 return getDrawingState().dataspace;
408 }
409
410 // Crop that applies to the buffer
getDrawingCrop() const411 Rect BufferStateLayer::getDrawingCrop() const {
412 const State& s(getDrawingState());
413
414 if (s.crop.isEmpty() && s.buffer) {
415 return s.buffer->getBounds();
416 } else if (s.buffer) {
417 Rect crop = s.crop;
418 crop.left = std::max(crop.left, 0);
419 crop.top = std::max(crop.top, 0);
420 uint32_t bufferWidth = s.buffer->getWidth();
421 uint32_t bufferHeight = s.buffer->getHeight();
422 if (bufferHeight <= std::numeric_limits<int32_t>::max() &&
423 bufferWidth <= std::numeric_limits<int32_t>::max()) {
424 crop.right = std::min(crop.right, static_cast<int32_t>(bufferWidth));
425 crop.bottom = std::min(crop.bottom, static_cast<int32_t>(bufferHeight));
426 }
427 if (!crop.isValid()) {
428 // Crop rect is out of bounds, return whole buffer
429 return s.buffer->getBounds();
430 }
431 return crop;
432 }
433 return s.crop;
434 }
435
getDrawingScalingMode() const436 uint32_t BufferStateLayer::getDrawingScalingMode() const {
437 return NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
438 }
439
getDrawingSurfaceDamage() const440 Region BufferStateLayer::getDrawingSurfaceDamage() const {
441 return getDrawingState().surfaceDamageRegion;
442 }
443
getDrawingHdrMetadata() const444 const HdrMetadata& BufferStateLayer::getDrawingHdrMetadata() const {
445 return getDrawingState().hdrMetadata;
446 }
447
getDrawingApi() const448 int BufferStateLayer::getDrawingApi() const {
449 return getDrawingState().api;
450 }
451
getFrameNumber() const452 uint64_t BufferStateLayer::getFrameNumber() const {
453 return mFrameNumber;
454 }
455
getAutoRefresh() const456 bool BufferStateLayer::getAutoRefresh() const {
457 // TODO(marissaw): support shared buffer mode
458 return false;
459 }
460
getSidebandStreamChanged() const461 bool BufferStateLayer::getSidebandStreamChanged() const {
462 return mSidebandStreamChanged.load();
463 }
464
latchSidebandStream(bool & recomputeVisibleRegions)465 bool BufferStateLayer::latchSidebandStream(bool& recomputeVisibleRegions) {
466 if (mSidebandStreamChanged.exchange(false)) {
467 const State& s(getDrawingState());
468 // mSidebandStreamChanged was true
469 LOG_ALWAYS_FATAL_IF(!getCompositionLayer());
470 mSidebandStream = s.sidebandStream;
471 getCompositionLayer()->editState().frontEnd.sidebandStream = mSidebandStream;
472 if (mSidebandStream != nullptr) {
473 setTransactionFlags(eTransactionNeeded);
474 mFlinger->setTransactionFlags(eTraversalNeeded);
475 }
476 recomputeVisibleRegions = true;
477
478 return true;
479 }
480 return false;
481 }
482
hasFrameUpdate() const483 bool BufferStateLayer::hasFrameUpdate() const {
484 const State& c(getCurrentState());
485 return mCurrentStateModified && (c.buffer != nullptr || c.bgColorLayer != nullptr);
486 }
487
setFilteringEnabled(bool enabled)488 void BufferStateLayer::setFilteringEnabled(bool enabled) {
489 GLConsumer::computeTransformMatrix(mTransformMatrix.data(), mActiveBuffer, mCurrentCrop,
490 mCurrentTransform, enabled);
491 }
492
bindTextureImage()493 status_t BufferStateLayer::bindTextureImage() {
494 const State& s(getDrawingState());
495 auto& engine(mFlinger->getRenderEngine());
496
497 return engine.bindExternalTextureBuffer(mTextureName, s.buffer, s.acquireFence);
498 }
499
updateTexImage(bool &,nsecs_t latchTime)500 status_t BufferStateLayer::updateTexImage(bool& /*recomputeVisibleRegions*/, nsecs_t latchTime) {
501 const State& s(getDrawingState());
502
503 if (!s.buffer) {
504 if (s.bgColorLayer) {
505 for (auto& handle : mDrawingState.callbackHandles) {
506 handle->latchTime = latchTime;
507 }
508 }
509 return NO_ERROR;
510 }
511
512 const int32_t layerID = getSequence();
513
514 // Reject if the layer is invalid
515 uint32_t bufferWidth = s.buffer->width;
516 uint32_t bufferHeight = s.buffer->height;
517
518 if (s.transform & ui::Transform::ROT_90) {
519 std::swap(bufferWidth, bufferHeight);
520 }
521
522 if (s.transformToDisplayInverse) {
523 uint32_t invTransform = DisplayDevice::getPrimaryDisplayOrientationTransform();
524 if (invTransform & ui::Transform::ROT_90) {
525 std::swap(bufferWidth, bufferHeight);
526 }
527 }
528
529 if (getEffectiveScalingMode() == NATIVE_WINDOW_SCALING_MODE_FREEZE &&
530 (s.active.w != bufferWidth || s.active.h != bufferHeight)) {
531 ALOGE("[%s] rejecting buffer: "
532 "bufferWidth=%d, bufferHeight=%d, front.active.{w=%d, h=%d}",
533 mName.string(), bufferWidth, bufferHeight, s.active.w, s.active.h);
534 mFlinger->mTimeStats->removeTimeRecord(layerID, getFrameNumber());
535 return BAD_VALUE;
536 }
537
538 for (auto& handle : mDrawingState.callbackHandles) {
539 handle->latchTime = latchTime;
540 }
541
542 if (!SyncFeatures::getInstance().useNativeFenceSync()) {
543 // Bind the new buffer to the GL texture.
544 //
545 // Older devices require the "implicit" synchronization provided
546 // by glEGLImageTargetTexture2DOES, which this method calls. Newer
547 // devices will either call this in Layer::onDraw, or (if it's not
548 // a GL-composited layer) not at all.
549 status_t err = bindTextureImage();
550 if (err != NO_ERROR) {
551 mFlinger->mTimeStats->onDestroy(layerID);
552 return BAD_VALUE;
553 }
554 }
555
556 mFlinger->mTimeStats->setAcquireFence(layerID, getFrameNumber(), getCurrentFenceTime());
557 mFlinger->mTimeStats->setLatchTime(layerID, getFrameNumber(), latchTime);
558
559 mCurrentStateModified = false;
560
561 return NO_ERROR;
562 }
563
updateActiveBuffer()564 status_t BufferStateLayer::updateActiveBuffer() {
565 const State& s(getDrawingState());
566
567 if (s.buffer == nullptr) {
568 return BAD_VALUE;
569 }
570
571 mActiveBuffer = s.buffer;
572 mActiveBufferFence = s.acquireFence;
573 auto& layerCompositionState = getCompositionLayer()->editState().frontEnd;
574 layerCompositionState.buffer = mActiveBuffer;
575 layerCompositionState.bufferSlot = 0;
576
577 return NO_ERROR;
578 }
579
updateFrameNumber(nsecs_t)580 status_t BufferStateLayer::updateFrameNumber(nsecs_t /*latchTime*/) {
581 // TODO(marissaw): support frame history events
582 mCurrentFrameNumber = mFrameNumber;
583 return NO_ERROR;
584 }
585
setHwcLayerBuffer(const sp<const DisplayDevice> & display)586 void BufferStateLayer::setHwcLayerBuffer(const sp<const DisplayDevice>& display) {
587 const auto outputLayer = findOutputLayerForDisplay(display);
588 LOG_FATAL_IF(!outputLayer || !outputLayer->getState().hwc);
589 auto& hwcInfo = *outputLayer->editState().hwc;
590 auto& hwcLayer = hwcInfo.hwcLayer;
591
592 const State& s(getDrawingState());
593
594 uint32_t hwcSlot;
595 sp<GraphicBuffer> buffer;
596 hwcInfo.hwcBufferCache.getHwcBuffer(mHwcSlotGenerator->getHwcCacheSlot(s.clientCacheId),
597 s.buffer, &hwcSlot, &buffer);
598
599 auto error = hwcLayer->setBuffer(hwcSlot, buffer, s.acquireFence);
600 if (error != HWC2::Error::None) {
601 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
602 s.buffer->handle, to_string(error).c_str(), static_cast<int32_t>(error));
603 }
604
605 mFrameNumber++;
606 }
607
onFirstRef()608 void BufferStateLayer::onFirstRef() {
609 BufferLayer::onFirstRef();
610
611 if (const auto display = mFlinger->getDefaultDisplayDevice()) {
612 updateTransformHint(display);
613 }
614 }
615
bufferErased(const client_cache_t & clientCacheId)616 void BufferStateLayer::HwcSlotGenerator::bufferErased(const client_cache_t& clientCacheId) {
617 std::lock_guard lock(mMutex);
618 if (!clientCacheId.isValid()) {
619 ALOGE("invalid process, failed to erase buffer");
620 return;
621 }
622 eraseBufferLocked(clientCacheId);
623 }
624
getHwcCacheSlot(const client_cache_t & clientCacheId)625 uint32_t BufferStateLayer::HwcSlotGenerator::getHwcCacheSlot(const client_cache_t& clientCacheId) {
626 std::lock_guard<std::mutex> lock(mMutex);
627 auto itr = mCachedBuffers.find(clientCacheId);
628 if (itr == mCachedBuffers.end()) {
629 return addCachedBuffer(clientCacheId);
630 }
631 auto& [hwcCacheSlot, counter] = itr->second;
632 counter = mCounter++;
633 return hwcCacheSlot;
634 }
635
addCachedBuffer(const client_cache_t & clientCacheId)636 uint32_t BufferStateLayer::HwcSlotGenerator::addCachedBuffer(const client_cache_t& clientCacheId)
637 REQUIRES(mMutex) {
638 if (!clientCacheId.isValid()) {
639 ALOGE("invalid process, returning invalid slot");
640 return BufferQueue::INVALID_BUFFER_SLOT;
641 }
642
643 ClientCache::getInstance().registerErasedRecipient(clientCacheId, wp<ErasedRecipient>(this));
644
645 uint32_t hwcCacheSlot = getFreeHwcCacheSlot();
646 mCachedBuffers[clientCacheId] = {hwcCacheSlot, mCounter++};
647 return hwcCacheSlot;
648 }
649
getFreeHwcCacheSlot()650 uint32_t BufferStateLayer::HwcSlotGenerator::getFreeHwcCacheSlot() REQUIRES(mMutex) {
651 if (mFreeHwcCacheSlots.empty()) {
652 evictLeastRecentlyUsed();
653 }
654
655 uint32_t hwcCacheSlot = mFreeHwcCacheSlots.top();
656 mFreeHwcCacheSlots.pop();
657 return hwcCacheSlot;
658 }
659
evictLeastRecentlyUsed()660 void BufferStateLayer::HwcSlotGenerator::evictLeastRecentlyUsed() REQUIRES(mMutex) {
661 uint64_t minCounter = UINT_MAX;
662 client_cache_t minClientCacheId = {};
663 for (const auto& [clientCacheId, slotCounter] : mCachedBuffers) {
664 const auto& [hwcCacheSlot, counter] = slotCounter;
665 if (counter < minCounter) {
666 minCounter = counter;
667 minClientCacheId = clientCacheId;
668 }
669 }
670 eraseBufferLocked(minClientCacheId);
671
672 ClientCache::getInstance().unregisterErasedRecipient(minClientCacheId, this);
673 }
674
eraseBufferLocked(const client_cache_t & clientCacheId)675 void BufferStateLayer::HwcSlotGenerator::eraseBufferLocked(const client_cache_t& clientCacheId)
676 REQUIRES(mMutex) {
677 auto itr = mCachedBuffers.find(clientCacheId);
678 if (itr == mCachedBuffers.end()) {
679 return;
680 }
681 auto& [hwcCacheSlot, counter] = itr->second;
682
683 // TODO send to hwc cache and resources
684
685 mFreeHwcCacheSlots.push(hwcCacheSlot);
686 mCachedBuffers.erase(clientCacheId);
687 }
688 } // namespace android
689