blob: 579130a380c5ade06e90b733eefd57f4e9fb94c9 [file] [log] [blame]
Marissa Wall61c58622018-07-18 10:12:20 -07001/*
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
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010020#pragma clang diagnostic ignored "-Wextra"
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080021
Marissa Wall61c58622018-07-18 10:12:20 -070022//#define LOG_NDEBUG 0
23#undef LOG_TAG
24#define LOG_TAG "BufferStateLayer"
25#define ATRACE_TAG ATRACE_TAG_GRAPHICS
26
Lloyd Pique9755fb72019-03-26 14:44:40 -070027#include "BufferStateLayer.h"
28
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080029#include <limits>
Marissa Wall61c58622018-07-18 10:12:20 -070030
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +000031#include <FrameTimeline/FrameTimeline.h>
Lloyd Pique9755fb72019-03-26 14:44:40 -070032#include <compositionengine/LayerFECompositionState.h>
Marissa Wall947d34e2019-03-29 14:03:53 -070033#include <gui/BufferQueue.h>
Marissa Wall61c58622018-07-18 10:12:20 -070034#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070035#include <renderengine/Image.h>
Marissa Wall61c58622018-07-18 10:12:20 -070036
Vishnu Nairfa247b12020-02-11 08:58:26 -080037#include "EffectLayer.h"
Adithya Srinivasanb238cd52021-02-04 17:54:05 +000038#include "FrameTracer/FrameTracer.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080039#include "TimeStats/TimeStats.h"
Valerie Hau0bc09152018-12-20 07:42:47 -080040
Marissa Wall61c58622018-07-18 10:12:20 -070041namespace android {
42
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +000043using PresentState = frametimeline::SurfaceFrame::PresentState;
Lloyd Pique42ab75e2018-09-12 20:46:03 -070044// clang-format off
45const std::array<float, 16> BufferStateLayer::IDENTITY_MATRIX{
46 1, 0, 0, 0,
47 0, 1, 0, 0,
48 0, 0, 1, 0,
49 0, 0, 0, 1
50};
51// clang-format on
Marissa Wall61c58622018-07-18 10:12:20 -070052
Marissa Wall947d34e2019-03-29 14:03:53 -070053BufferStateLayer::BufferStateLayer(const LayerCreationArgs& args)
54 : BufferLayer(args), mHwcSlotGenerator(new HwcSlotGenerator()) {
Marissa Wall3ff826c2019-02-07 11:58:25 -080055 mCurrentState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nair60356342018-11-13 13:00:45 -080056}
Marissa Wall61c58622018-07-18 10:12:20 -070057
Alec Mouri4545a8a2019-08-08 20:05:32 -070058BufferStateLayer::~BufferStateLayer() {
chaviwb4c6e582019-08-16 14:35:07 -070059 // The original layer and the clone layer share the same texture and buffer. Therefore, only
60 // one of the layers, in this case the original layer, needs to handle the deletion. The
61 // original layer and the clone should be removed at the same time so there shouldn't be any
62 // issue with the clone layer trying to use the texture.
63 if (mBufferInfo.mBuffer != nullptr && !isClone()) {
chaviwd62d3062019-09-04 14:48:02 -070064 // Ensure that mBuffer is uncached from RenderEngine here, as
Alec Mouri4545a8a2019-08-08 20:05:32 -070065 // RenderEngine may have been using the buffer as an external texture
66 // after the client uncached the buffer.
67 auto& engine(mFlinger->getRenderEngine());
chaviwd62d3062019-09-04 14:48:02 -070068 engine.unbindExternalTextureBuffer(mBufferInfo.mBuffer->getId());
Alec Mouri4545a8a2019-08-08 20:05:32 -070069 }
70}
71
Robert Carr8d958532020-11-10 14:09:16 -080072status_t BufferStateLayer::addReleaseFence(const sp<CallbackHandle>& ch,
73 const sp<Fence>& fence) {
74 if (ch == nullptr) {
75 return OK;
76 }
77 if (!ch->previousReleaseFence.get()) {
78 ch->previousReleaseFence = fence;
79 return OK;
80 }
81
82 // Below logic is lifted from ConsumerBase.cpp:
83 // Check status of fences first because merging is expensive.
84 // Merging an invalid fence with any other fence results in an
85 // invalid fence.
86 auto currentStatus = ch->previousReleaseFence->getStatus();
87 if (currentStatus == Fence::Status::Invalid) {
88 ALOGE("Existing fence has invalid state, layer: %s", mName.c_str());
89 return BAD_VALUE;
90 }
91
92 auto incomingStatus = fence->getStatus();
93 if (incomingStatus == Fence::Status::Invalid) {
94 ALOGE("New fence has invalid state, layer: %s", mName.c_str());
95 ch->previousReleaseFence = fence;
96 return BAD_VALUE;
97 }
98
99 // If both fences are signaled or both are unsignaled, we need to merge
100 // them to get an accurate timestamp.
101 if (currentStatus == incomingStatus) {
102 char fenceName[32] = {};
103 snprintf(fenceName, 32, "%.28s", mName.c_str());
104 sp<Fence> mergedFence = Fence::merge(
105 fenceName, ch->previousReleaseFence, fence);
106 if (!mergedFence.get()) {
107 ALOGE("failed to merge release fences, layer: %s", mName.c_str());
108 // synchronization is broken, the best we can do is hope fences
109 // signal in order so the new fence will act like a union
110 ch->previousReleaseFence = fence;
111 return BAD_VALUE;
112 }
113 ch->previousReleaseFence = mergedFence;
114 } else if (incomingStatus == Fence::Status::Unsignaled) {
115 // If one fence has signaled and the other hasn't, the unsignaled
116 // fence will approximately correspond with the correct timestamp.
117 // There's a small race if both fences signal at about the same time
118 // and their statuses are retrieved with unfortunate timing. However,
119 // by this point, they will have both signaled and only the timestamp
120 // will be slightly off; any dependencies after this point will
121 // already have been met.
122 ch->previousReleaseFence = fence;
123 }
124 // else if (currentStatus == Fence::Status::Unsignaled) is a no-op.
125
126 return OK;
127}
128
Marissa Wall61c58622018-07-18 10:12:20 -0700129// -----------------------------------------------------------------------
130// Interface implementation for Layer
131// -----------------------------------------------------------------------
Marissa Wallfda30bb2018-10-12 11:34:28 -0700132void BufferStateLayer::onLayerDisplayed(const sp<Fence>& releaseFence) {
Robert Carr8d958532020-11-10 14:09:16 -0800133 if (!releaseFence->isValid()) {
134 return;
135 }
Marissa Wall5a68a772018-12-22 17:43:42 -0800136 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
137 // buffer that was presented on this layer. The first transaction that came in this frame that
138 // replaced the previous buffer on this layer needs this release fence, because the fence will
139 // let the client know when that previous buffer is removed from the screen.
140 //
141 // Every other transaction on this layer does not need a release fence because no other
142 // Transactions that were set on this layer this frame are going to have their preceeding buffer
143 // removed from the display this frame.
144 //
145 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
146 // buffer so it doesn't need a previous release fence because the layer still needs the previous
147 // buffer. The second transaction contains a buffer so it needs a previous release fence because
148 // the previous buffer will be released this frame. The third transaction also contains a
149 // buffer. It replaces the buffer in the second transaction. The buffer in the second
150 // transaction will now no longer be presented so it is released immediately and the third
151 // transaction doesn't need a previous release fence.
Robert Carr8d958532020-11-10 14:09:16 -0800152 sp<CallbackHandle> ch;
Marissa Wall5a68a772018-12-22 17:43:42 -0800153 for (auto& handle : mDrawingState.callbackHandles) {
154 if (handle->releasePreviousBuffer) {
Robert Carr8d958532020-11-10 14:09:16 -0800155 ch = handle;
Marissa Wall5a68a772018-12-22 17:43:42 -0800156 break;
157 }
158 }
Robert Carr8d958532020-11-10 14:09:16 -0800159 auto status = addReleaseFence(ch, releaseFence);
160 if (status != OK) {
161 ALOGE("Failed to add release fence for layer %s", getName().c_str());
162 }
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700163
Valerie Haubf784642020-01-29 07:25:23 -0800164 mPreviousReleaseFence = releaseFence;
165
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700166 // Prevent tracing the same release multiple times.
167 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700168 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
169 }
Marissa Wall61c58622018-07-18 10:12:20 -0700170}
171
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100172void BufferStateLayer::onSurfaceFrameCreated(
173 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
174 mPendingJankClassifications.emplace_back(surfaceFrame);
175}
176
Valerie Haubf784642020-01-29 07:25:23 -0800177void BufferStateLayer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700178 for (const auto& handle : mDrawingState.callbackHandles) {
179 handle->transformHint = mTransformHint;
Valerie Hau871d6352020-01-29 08:44:02 -0800180 handle->dequeueReadyTime = dequeueReadyTime;
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700181 }
182
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100183 std::vector<JankData> jankData;
184 jankData.reserve(mPendingJankClassifications.size());
185 while (!mPendingJankClassifications.empty()
186 && mPendingJankClassifications.front()->getJankType()) {
187 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
188 mPendingJankClassifications.front();
189 mPendingJankClassifications.pop_front();
190 jankData.emplace_back(
191 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
192 }
193
Robert Carr9a803c32021-01-14 16:57:58 -0800194 mFlinger->getTransactionCallbackInvoker().finalizePendingCallbackHandles(
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100195 mDrawingState.callbackHandles, jankData);
Marissa Wall5a68a772018-12-22 17:43:42 -0800196
197 mDrawingState.callbackHandles = {};
Valerie Haubf784642020-01-29 07:25:23 -0800198
199 const sp<Fence>& releaseFence(mPreviousReleaseFence);
200 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(releaseFence);
201 {
202 Mutex::Autolock lock(mFrameEventHistoryMutex);
203 if (mPreviousFrameNumber != 0) {
204 mFrameEventHistory.addRelease(mPreviousFrameNumber, dequeueReadyTime,
205 std::move(releaseFenceTime));
206 }
207 }
Marissa Wall61c58622018-07-18 10:12:20 -0700208}
209
Valerie Hau871d6352020-01-29 08:44:02 -0800210void BufferStateLayer::finalizeFrameEventHistory(const std::shared_ptr<FenceTime>& glDoneFence,
211 const CompositorTiming& compositorTiming) {
212 for (const auto& handle : mDrawingState.callbackHandles) {
213 handle->gpuCompositionDoneFence = glDoneFence;
214 handle->compositorTiming = compositorTiming;
215 }
216}
217
Marissa Walle2ffb422018-10-12 11:33:52 -0700218bool BufferStateLayer::willPresentCurrentTransaction() const {
219 // Returns true if the most recent Transaction applied to CurrentState will be presented.
Robert Carr321e83c2019-08-19 15:49:30 -0700220 return (getSidebandStreamChanged() || getAutoRefresh() ||
Valerie Hauaa194562019-02-05 16:21:38 -0800221 (mCurrentState.modified &&
chaviw8ba8b072021-01-25 14:55:46 -0800222 (mCurrentState.buffer != nullptr || mCurrentState.bgColorLayer != nullptr)));
Marissa Wall61c58622018-07-18 10:12:20 -0700223}
224
Valerie Hau3282b3c2020-02-03 15:37:27 -0800225/* TODO: vhau uncomment once deferred transaction migration complete in
226 * WindowManager
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800227void BufferStateLayer::pushPendingState() {
228 if (!mCurrentState.modified) {
Marissa Wall61c58622018-07-18 10:12:20 -0700229 return;
230 }
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800231 mPendingStates.push_back(mCurrentState);
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700232 ATRACE_INT(mTransactionName.c_str(), mPendingStates.size());
Marissa Wall61c58622018-07-18 10:12:20 -0700233}
Valerie Hau3282b3c2020-02-03 15:37:27 -0800234*/
Marissa Wall61c58622018-07-18 10:12:20 -0700235
236bool BufferStateLayer::applyPendingStates(Layer::State* stateToCommit) {
Valerie Hau3282b3c2020-02-03 15:37:27 -0800237 mCurrentStateModified = mCurrentState.modified;
238 bool stateUpdateAvailable = Layer::applyPendingStates(stateToCommit);
Ady Abraham22c7b5c2020-09-22 19:33:40 -0700239 if (stateUpdateAvailable && mCallbackHandleAcquireTime != -1) {
Ady Abraham7f8a1e62020-09-28 16:09:35 -0700240 // Update the acquire fence time if we have a buffer
241 mSurfaceFrame->setAcquireFenceTime(mCallbackHandleAcquireTime);
Ady Abraham22c7b5c2020-09-22 19:33:40 -0700242 }
Valerie Hau3282b3c2020-02-03 15:37:27 -0800243 mCurrentStateModified = stateUpdateAvailable && mCurrentStateModified;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800244 mCurrentState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700245 return stateUpdateAvailable;
246}
247
Marissa Wall861616d2018-10-22 12:52:23 -0700248// Crop that applies to the window
249Rect BufferStateLayer::getCrop(const Layer::State& /*s*/) const {
250 return Rect::INVALID_RECT;
Marissa Wall61c58622018-07-18 10:12:20 -0700251}
252
253bool BufferStateLayer::setTransform(uint32_t transform) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800254 if (mCurrentState.transform == transform) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800255 mCurrentState.transform = transform;
256 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700257 setTransactionFlags(eTransactionNeeded);
258 return true;
259}
260
261bool BufferStateLayer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800262 if (mCurrentState.transformToDisplayInverse == transformToDisplayInverse) return false;
263 mCurrentState.sequence++;
264 mCurrentState.transformToDisplayInverse = transformToDisplayInverse;
265 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700266 setTransactionFlags(eTransactionNeeded);
267 return true;
268}
269
270bool BufferStateLayer::setCrop(const Rect& crop) {
Marissa Wall290ad082019-03-06 13:23:47 -0800271 Rect c = crop;
272 if (c.left < 0) {
273 c.left = 0;
274 }
275 if (c.top < 0) {
276 c.top = 0;
277 }
278 // If the width and/or height are < 0, make it [0, 0, -1, -1] so the equality comparision below
279 // treats all invalid rectangles the same.
280 if (!c.isValid()) {
281 c.makeInvalid();
282 }
283
284 if (mCurrentState.crop == c) return false;
Marissa Wall290ad082019-03-06 13:23:47 -0800285 mCurrentState.crop = c;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800286 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700287 setTransactionFlags(eTransactionNeeded);
288 return true;
289}
290
Marissa Wall861616d2018-10-22 12:52:23 -0700291bool BufferStateLayer::setFrame(const Rect& frame) {
292 int x = frame.left;
293 int y = frame.top;
294 int w = frame.getWidth();
295 int h = frame.getHeight();
296
Marissa Wall0f3242d2018-12-20 15:10:22 -0800297 if (x < 0) {
298 x = 0;
299 w = frame.right;
300 }
301
302 if (y < 0) {
303 y = 0;
304 h = frame.bottom;
305 }
306
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800307 if (mCurrentState.active.transform.tx() == x && mCurrentState.active.transform.ty() == y &&
308 mCurrentState.active.w == w && mCurrentState.active.h == h) {
Marissa Wall861616d2018-10-22 12:52:23 -0700309 return false;
310 }
311
312 if (!frame.isValid()) {
313 x = y = w = h = 0;
314 }
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800315 mCurrentState.active.transform.set(x, y);
316 mCurrentState.active.w = w;
317 mCurrentState.active.h = h;
Marissa Wall861616d2018-10-22 12:52:23 -0700318
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800319 mCurrentState.sequence++;
320 mCurrentState.modified = true;
Marissa Wall861616d2018-10-22 12:52:23 -0700321 setTransactionFlags(eTransactionNeeded);
322 return true;
323}
324
Valerie Hau871d6352020-01-29 08:44:02 -0800325bool BufferStateLayer::addFrameEvent(const sp<Fence>& acquireFence, nsecs_t postedTime,
326 nsecs_t desiredPresentTime) {
Valerie Haubf784642020-01-29 07:25:23 -0800327 Mutex::Autolock lock(mFrameEventHistoryMutex);
328 mAcquireTimeline.updateSignalTimes();
329 std::shared_ptr<FenceTime> acquireFenceTime =
330 std::make_shared<FenceTime>((acquireFence ? acquireFence : Fence::NO_FENCE));
331 NewFrameEventsEntry newTimestamps = {mCurrentState.frameNumber, postedTime, desiredPresentTime,
332 acquireFenceTime};
Valerie Hau871d6352020-01-29 08:44:02 -0800333 mFrameEventHistory.setProducerWantsEvents();
Valerie Haubf784642020-01-29 07:25:23 -0800334 mFrameEventHistory.addQueue(newTimestamps);
335 return true;
336}
337
338bool BufferStateLayer::setBuffer(const sp<GraphicBuffer>& buffer, const sp<Fence>& acquireFence,
Ady Abrahamf0c56492020-12-17 18:04:15 -0800339 nsecs_t postTime, nsecs_t desiredPresentTime, bool isAutoTimestamp,
Vishnu Nairadf632b2021-01-07 14:05:08 -0800340 const client_cache_t& clientCacheId, uint64_t frameNumber,
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000341 std::optional<nsecs_t> dequeueTime,
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000342 const FrameTimelineInfo& info) {
Robert Carr0c1966e2020-10-19 12:12:08 -0700343 ATRACE_CALL();
344
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800345 if (mCurrentState.buffer) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700346 mReleasePreviousBuffer = true;
Robert Carr7121caf2020-12-15 13:07:32 -0800347 if (mCurrentState.buffer != mDrawingState.buffer) {
348 // If mCurrentState has a buffer, and we are about to update again
349 // before swapping to drawing state, then the first buffer will be
350 // dropped and we should decrement the pending buffer count.
351 decrementPendingBufferCount();
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000352 if (mCurrentState.bufferSurfaceFrameTX != nullptr) {
353 addSurfaceFrameDroppedForBuffer(mCurrentState.bufferSurfaceFrameTX);
354 mCurrentState.bufferSurfaceFrameTX.reset();
355 }
Robert Carr7121caf2020-12-15 13:07:32 -0800356 }
Marissa Wallfda30bb2018-10-12 11:34:28 -0700357 }
358
Vishnu Nair6b7c5c92020-09-29 17:27:05 -0700359 mCurrentState.frameNumber = frameNumber;
Valerie Hau2f54d642020-01-22 09:37:03 -0800360
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800361 mCurrentState.buffer = buffer;
Marissa Wall947d34e2019-03-29 14:03:53 -0700362 mCurrentState.clientCacheId = clientCacheId;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800363 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700364 setTransactionFlags(eTransactionNeeded);
Ady Abraham09bd3922019-04-08 10:44:56 -0700365
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800366 const int32_t layerId = getSequence();
Valerie Hau134651a2020-01-28 16:21:22 -0800367 mFlinger->mTimeStats->setPostTime(layerId, mCurrentState.frameNumber, getName().c_str(),
Alec Mouri9a29e672020-09-14 12:39:14 -0700368 mOwnerUid, postTime);
chaviwfa67b552019-08-12 16:51:55 -0700369 mCurrentState.desiredPresentTime = desiredPresentTime;
Ady Abrahamf0c56492020-12-17 18:04:15 -0800370 mCurrentState.isAutoTimestamp = isAutoTimestamp;
Ady Abraham09bd3922019-04-08 10:44:56 -0700371
Ady Abrahamf0c56492020-12-17 18:04:15 -0800372 mFlinger->mScheduler->recordLayerHistory(this, isAutoTimestamp ? 0 : desiredPresentTime,
Ady Abraham5def7332020-05-29 16:13:47 -0700373 LayerHistory::LayerUpdateType::Buffer);
Ady Abraham09bd3922019-04-08 10:44:56 -0700374
Ady Abrahamf0c56492020-12-17 18:04:15 -0800375 addFrameEvent(acquireFence, postTime, isAutoTimestamp ? 0 : desiredPresentTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000376
377 if (info.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
378 setFrameTimelineVsyncForBufferTransaction(info, postTime);
379 }
380
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000381 if (dequeueTime && *dequeueTime != 0) {
382 const uint64_t bufferId = buffer->getId();
383 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
384 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
385 FrameTracer::FrameEvent::DEQUEUE);
386 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
387 FrameTracer::FrameEvent::QUEUE);
388 }
Marissa Wall61c58622018-07-18 10:12:20 -0700389 return true;
390}
391
392bool BufferStateLayer::setAcquireFence(const sp<Fence>& fence) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700393 // The acquire fences of BufferStateLayers have already signaled before they are set
394 mCallbackHandleAcquireTime = fence->getSignalTime();
395
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800396 mCurrentState.acquireFence = fence;
397 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700398 setTransactionFlags(eTransactionNeeded);
399 return true;
400}
401
402bool BufferStateLayer::setDataspace(ui::Dataspace dataspace) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800403 if (mCurrentState.dataspace == dataspace) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800404 mCurrentState.dataspace = dataspace;
405 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700406 setTransactionFlags(eTransactionNeeded);
407 return true;
408}
409
410bool BufferStateLayer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800411 if (mCurrentState.hdrMetadata == hdrMetadata) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800412 mCurrentState.hdrMetadata = hdrMetadata;
413 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700414 setTransactionFlags(eTransactionNeeded);
415 return true;
416}
417
418bool BufferStateLayer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800419 mCurrentState.surfaceDamageRegion = surfaceDamage;
420 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700421 setTransactionFlags(eTransactionNeeded);
422 return true;
423}
424
425bool BufferStateLayer::setApi(int32_t api) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800426 if (mCurrentState.api == api) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800427 mCurrentState.api = api;
428 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700429 setTransactionFlags(eTransactionNeeded);
430 return true;
431}
432
433bool BufferStateLayer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800434 if (mCurrentState.sidebandStream == sidebandStream) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800435 mCurrentState.sidebandStream = sidebandStream;
436 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700437 setTransactionFlags(eTransactionNeeded);
438
439 if (!mSidebandStreamChanged.exchange(true)) {
440 // mSidebandStreamChanged was false
441 mFlinger->signalLayerUpdate();
442 }
443 return true;
444}
445
Marissa Walle2ffb422018-10-12 11:33:52 -0700446bool BufferStateLayer::setTransactionCompletedListeners(
447 const std::vector<sp<CallbackHandle>>& handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700448 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
Marissa Walle2ffb422018-10-12 11:33:52 -0700449 if (handles.empty()) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700450 mReleasePreviousBuffer = false;
Marissa Walle2ffb422018-10-12 11:33:52 -0700451 return false;
452 }
453
454 const bool willPresent = willPresentCurrentTransaction();
455
456 for (const auto& handle : handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700457 // If this transaction set a buffer on this layer, release its previous buffer
458 handle->releasePreviousBuffer = mReleasePreviousBuffer;
459
Marissa Walle2ffb422018-10-12 11:33:52 -0700460 // If this layer will be presented in this frame
461 if (willPresent) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700462 // If this transaction set an acquire fence on this layer, set its acquire time
463 handle->acquireTime = mCallbackHandleAcquireTime;
Vishnu Nair935590e2021-02-10 13:05:52 -0800464 handle->frameNumber = mCurrentState.frameNumber;
Marissa Wallfda30bb2018-10-12 11:34:28 -0700465
Marissa Walle2ffb422018-10-12 11:33:52 -0700466 // Notify the transaction completed thread that there is a pending latched callback
467 // handle
Robert Carr9a803c32021-01-14 16:57:58 -0800468 mFlinger->getTransactionCallbackInvoker().registerPendingCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700469
470 // Store so latched time and release fence can be set
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800471 mCurrentState.callbackHandles.push_back(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700472
473 } else { // If this layer will NOT need to be relatched and presented this frame
474 // Notify the transaction completed thread this handle is done
Robert Carr9a803c32021-01-14 16:57:58 -0800475 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700476 }
477 }
478
Marissa Wallfda30bb2018-10-12 11:34:28 -0700479 mReleasePreviousBuffer = false;
480 mCallbackHandleAcquireTime = -1;
481
Marissa Walle2ffb422018-10-12 11:33:52 -0700482 return willPresent;
483}
484
Marissa Wall61c58622018-07-18 10:12:20 -0700485bool BufferStateLayer::setTransparentRegionHint(const Region& transparent) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800486 mCurrentState.transparentRegionHint = transparent;
487 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700488 setTransactionFlags(eTransactionNeeded);
489 return true;
490}
491
Marissa Wall861616d2018-10-22 12:52:23 -0700492Rect BufferStateLayer::getBufferSize(const State& s) const {
493 // for buffer state layers we use the display frame size as the buffer size.
494 if (getActiveWidth(s) < UINT32_MAX && getActiveHeight(s) < UINT32_MAX) {
495 return Rect(getActiveWidth(s), getActiveHeight(s));
Marissa Wall61c58622018-07-18 10:12:20 -0700496 }
497
chaviw7e72caf2020-12-02 16:50:43 -0800498 if (mBufferInfo.mBuffer == nullptr) {
499 return Rect::INVALID_RECT;
500 }
501
Marissa Wall861616d2018-10-22 12:52:23 -0700502 // if the display frame is not defined, use the parent bounds as the buffer size.
503 const auto& p = mDrawingParent.promote();
504 if (p != nullptr) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800505 Rect parentBounds = Rect(p->getBounds(Region()));
Marissa Wall861616d2018-10-22 12:52:23 -0700506 if (!parentBounds.isEmpty()) {
507 return parentBounds;
508 }
509 }
510
Marissa Wall861616d2018-10-22 12:52:23 -0700511 return Rect::INVALID_RECT;
Marissa Wall61c58622018-07-18 10:12:20 -0700512}
Vishnu Nair4351ad52019-02-11 14:13:02 -0800513
514FloatRect BufferStateLayer::computeSourceBounds(const FloatRect& parentBounds) const {
515 const State& s(getDrawingState());
516 // for buffer state layers we use the display frame size as the buffer size.
517 if (getActiveWidth(s) < UINT32_MAX && getActiveHeight(s) < UINT32_MAX) {
518 return FloatRect(0, 0, getActiveWidth(s), getActiveHeight(s));
519 }
520
521 // if the display frame is not defined, use the parent bounds as the buffer size.
522 return parentBounds;
523}
524
Marissa Wall61c58622018-07-18 10:12:20 -0700525// -----------------------------------------------------------------------
526
527// -----------------------------------------------------------------------
528// Interface implementation for BufferLayer
529// -----------------------------------------------------------------------
530bool BufferStateLayer::fenceHasSignaled() const {
Alec Mouri91f6df32020-01-30 08:48:58 -0800531 const bool fenceSignaled =
532 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
533 if (!fenceSignaled) {
534 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
535 TimeStats::LatchSkipReason::LateAcquire);
536 }
537
538 return fenceSignaled;
Marissa Wall61c58622018-07-18 10:12:20 -0700539}
540
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700541bool BufferStateLayer::framePresentTimeIsCurrent(nsecs_t expectedPresentTime) const {
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700542 if (!hasFrameUpdate() || isRemovedFromCurrentState()) {
543 return true;
544 }
545
Ady Abrahamf0c56492020-12-17 18:04:15 -0800546 return mCurrentState.isAutoTimestamp || mCurrentState.desiredPresentTime <= expectedPresentTime;
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700547}
548
Valerie Hau871d6352020-01-29 08:44:02 -0800549bool BufferStateLayer::onPreComposition(nsecs_t refreshStartTime) {
550 for (const auto& handle : mDrawingState.callbackHandles) {
551 handle->refreshStartTime = refreshStartTime;
552 }
553 return BufferLayer::onPreComposition(refreshStartTime);
554}
555
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700556uint64_t BufferStateLayer::getFrameNumber(nsecs_t /*expectedPresentTime*/) const {
Valerie Hau134651a2020-01-28 16:21:22 -0800557 return mDrawingState.frameNumber;
Marissa Wall61c58622018-07-18 10:12:20 -0700558}
559
Robert Carrfe1209c2020-02-11 12:25:35 -0800560/**
561 * This is the frameNumber used for deferred transaction signalling. We need to use this because
562 * of cases where we defer a transaction for a surface to itself. In the BLAST world this
563 * may not make a huge amount of sense (Why not just merge the Buffer transaction with the
564 * deferred transaction?) but this is an important legacy use case, for example moving
565 * a window at the same time it draws makes use of this kind of technique. So anyway
566 * imagine we have something like this:
567 *
568 * Transaction { // containing
569 * Buffer -> frameNumber = 2
570 * DeferTransactionUntil -> frameNumber = 2
571 * Random other stuff
572 * }
573 * Now imagine getHeadFrameNumber returned mDrawingState.mFrameNumber (or mCurrentFrameNumber).
574 * Prior to doTransaction SurfaceFlinger will call notifyAvailableFrames, but because we
575 * haven't swapped mCurrentState to mDrawingState yet we will think the sync point
576 * is not ready. So we will return false from applyPendingState and not swap
577 * current state to drawing state. But because we don't swap current state
578 * to drawing state the number will never update and we will be stuck. This way
579 * we can see we need to return the frame number for the buffer we are about
580 * to apply.
581 */
582uint64_t BufferStateLayer::getHeadFrameNumber(nsecs_t /* expectedPresentTime */) const {
583 return mCurrentState.frameNumber;
584}
585
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800586void BufferStateLayer::setAutoRefresh(bool autoRefresh) {
587 if (!mAutoRefresh.exchange(autoRefresh)) {
588 mFlinger->signalLayerUpdate();
589 }
Marissa Wall61c58622018-07-18 10:12:20 -0700590}
591
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800592bool BufferStateLayer::latchSidebandStream(bool& recomputeVisibleRegions) {
Marissa Wall61c58622018-07-18 10:12:20 -0700593 if (mSidebandStreamChanged.exchange(false)) {
594 const State& s(getDrawingState());
595 // mSidebandStreamChanged was true
Lloyd Pique0b785d82018-12-04 17:25:27 -0800596 mSidebandStream = s.sidebandStream;
Lloyd Piquede196652020-01-22 17:29:58 -0800597 editCompositionState()->sidebandStream = mSidebandStream;
Lloyd Pique0b785d82018-12-04 17:25:27 -0800598 if (mSidebandStream != nullptr) {
Marissa Wall61c58622018-07-18 10:12:20 -0700599 setTransactionFlags(eTransactionNeeded);
600 mFlinger->setTransactionFlags(eTraversalNeeded);
601 }
602 recomputeVisibleRegions = true;
603
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800604 return true;
Marissa Wall61c58622018-07-18 10:12:20 -0700605 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800606 return false;
Marissa Wall61c58622018-07-18 10:12:20 -0700607}
608
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800609bool BufferStateLayer::hasFrameUpdate() const {
Valerie Hauaa194562019-02-05 16:21:38 -0800610 const State& c(getCurrentState());
611 return mCurrentStateModified && (c.buffer != nullptr || c.bgColorLayer != nullptr);
Marissa Wall61c58622018-07-18 10:12:20 -0700612}
613
Ady Abraham63a3e592021-01-06 10:47:15 -0800614std::optional<nsecs_t> BufferStateLayer::nextPredictedPresentTime() const {
Ady Abrahamce4adf12020-12-15 18:45:12 -0800615 if (!getDrawingState().isAutoTimestamp || !mSurfaceFrame) {
Ady Abraham63a3e592021-01-06 10:47:15 -0800616 return std::nullopt;
Ady Abrahamce4adf12020-12-15 18:45:12 -0800617 }
618
619 return mSurfaceFrame->getPredictions().presentTime;
620}
621
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700622status_t BufferStateLayer::updateTexImage(bool& /*recomputeVisibleRegions*/, nsecs_t latchTime,
623 nsecs_t /*expectedPresentTime*/) {
Marissa Wall61c58622018-07-18 10:12:20 -0700624 const State& s(getDrawingState());
625
626 if (!s.buffer) {
Valerie Hauaa194562019-02-05 16:21:38 -0800627 if (s.bgColorLayer) {
628 for (auto& handle : mDrawingState.callbackHandles) {
629 handle->latchTime = latchTime;
630 }
631 }
Marissa Wall61c58622018-07-18 10:12:20 -0700632 return NO_ERROR;
633 }
634
Marissa Wall5a68a772018-12-22 17:43:42 -0800635 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair935590e2021-02-10 13:05:52 -0800636 if (handle->frameNumber == mDrawingState.frameNumber) {
637 handle->latchTime = latchTime;
638 }
Marissa Wall5a68a772018-12-22 17:43:42 -0800639 }
Marissa Walle2ffb422018-10-12 11:33:52 -0700640
Vishnu Nairea0de002020-11-17 17:42:37 -0800641 const int32_t layerId = getSequence();
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000642 const uint64_t bufferId = mDrawingState.buffer->getId();
643 const uint64_t frameNumber = mDrawingState.frameNumber;
644 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
645 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
646 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
647
648 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
649 FrameTracer::FrameEvent::ACQUIRE_FENCE);
650 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
651 FrameTracer::FrameEvent::LATCH);
Marissa Wall61c58622018-07-18 10:12:20 -0700652
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000653 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
654 if (bufferSurfaceFrame != nullptr &&
655 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
656 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
657 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
658 // are processing the next state.
659 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
660 mDrawingState.acquireFence->getSignalTime(), latchTime);
661 bufferSurfaceFrame.reset();
662 }
663
Marissa Wall16c112d2019-03-20 13:21:13 -0700664 mCurrentStateModified = false;
665
Marissa Wall61c58622018-07-18 10:12:20 -0700666 return NO_ERROR;
667}
668
669status_t BufferStateLayer::updateActiveBuffer() {
670 const State& s(getDrawingState());
671
672 if (s.buffer == nullptr) {
673 return BAD_VALUE;
674 }
chaviwdf3c5e82021-01-07 13:00:37 -0800675
676 if (s.buffer != mBufferInfo.mBuffer) {
677 decrementPendingBufferCount();
678 }
Marissa Wall61c58622018-07-18 10:12:20 -0700679
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700680 mPreviousBufferId = getCurrentBufferId();
chaviwd62d3062019-09-04 14:48:02 -0700681 mBufferInfo.mBuffer = s.buffer;
682 mBufferInfo.mFence = s.acquireFence;
Marissa Wall61c58622018-07-18 10:12:20 -0700683
684 return NO_ERROR;
685}
686
Valerie Haubf784642020-01-29 07:25:23 -0800687status_t BufferStateLayer::updateFrameNumber(nsecs_t latchTime) {
Marissa Wall61c58622018-07-18 10:12:20 -0700688 // TODO(marissaw): support frame history events
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700689 mPreviousFrameNumber = mCurrentFrameNumber;
Valerie Hau134651a2020-01-28 16:21:22 -0800690 mCurrentFrameNumber = mDrawingState.frameNumber;
Valerie Haubf784642020-01-29 07:25:23 -0800691 {
692 Mutex::Autolock lock(mFrameEventHistoryMutex);
693 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
694 }
Marissa Wall61c58622018-07-18 10:12:20 -0700695 return NO_ERROR;
696}
697
Marissa Wall947d34e2019-03-29 14:03:53 -0700698void BufferStateLayer::HwcSlotGenerator::bufferErased(const client_cache_t& clientCacheId) {
699 std::lock_guard lock(mMutex);
700 if (!clientCacheId.isValid()) {
701 ALOGE("invalid process, failed to erase buffer");
702 return;
703 }
704 eraseBufferLocked(clientCacheId);
705}
706
707uint32_t BufferStateLayer::HwcSlotGenerator::getHwcCacheSlot(const client_cache_t& clientCacheId) {
708 std::lock_guard<std::mutex> lock(mMutex);
709 auto itr = mCachedBuffers.find(clientCacheId);
710 if (itr == mCachedBuffers.end()) {
711 return addCachedBuffer(clientCacheId);
712 }
713 auto& [hwcCacheSlot, counter] = itr->second;
714 counter = mCounter++;
715 return hwcCacheSlot;
716}
717
718uint32_t BufferStateLayer::HwcSlotGenerator::addCachedBuffer(const client_cache_t& clientCacheId)
719 REQUIRES(mMutex) {
720 if (!clientCacheId.isValid()) {
721 ALOGE("invalid process, returning invalid slot");
722 return BufferQueue::INVALID_BUFFER_SLOT;
723 }
724
725 ClientCache::getInstance().registerErasedRecipient(clientCacheId, wp<ErasedRecipient>(this));
726
727 uint32_t hwcCacheSlot = getFreeHwcCacheSlot();
728 mCachedBuffers[clientCacheId] = {hwcCacheSlot, mCounter++};
729 return hwcCacheSlot;
730}
731
732uint32_t BufferStateLayer::HwcSlotGenerator::getFreeHwcCacheSlot() REQUIRES(mMutex) {
733 if (mFreeHwcCacheSlots.empty()) {
734 evictLeastRecentlyUsed();
735 }
736
737 uint32_t hwcCacheSlot = mFreeHwcCacheSlots.top();
738 mFreeHwcCacheSlots.pop();
739 return hwcCacheSlot;
740}
741
742void BufferStateLayer::HwcSlotGenerator::evictLeastRecentlyUsed() REQUIRES(mMutex) {
743 uint64_t minCounter = UINT_MAX;
744 client_cache_t minClientCacheId = {};
745 for (const auto& [clientCacheId, slotCounter] : mCachedBuffers) {
746 const auto& [hwcCacheSlot, counter] = slotCounter;
747 if (counter < minCounter) {
748 minCounter = counter;
749 minClientCacheId = clientCacheId;
750 }
751 }
752 eraseBufferLocked(minClientCacheId);
753
754 ClientCache::getInstance().unregisterErasedRecipient(minClientCacheId, this);
755}
756
757void BufferStateLayer::HwcSlotGenerator::eraseBufferLocked(const client_cache_t& clientCacheId)
758 REQUIRES(mMutex) {
759 auto itr = mCachedBuffers.find(clientCacheId);
760 if (itr == mCachedBuffers.end()) {
761 return;
762 }
763 auto& [hwcCacheSlot, counter] = itr->second;
764
765 // TODO send to hwc cache and resources
766
767 mFreeHwcCacheSlots.push(hwcCacheSlot);
768 mCachedBuffers.erase(clientCacheId);
769}
chaviw4244e032019-09-04 11:27:49 -0700770
771void BufferStateLayer::gatherBufferInfo() {
chaviwdebadb82020-03-26 14:57:24 -0700772 BufferLayer::gatherBufferInfo();
chaviw4244e032019-09-04 11:27:49 -0700773
chaviwdebadb82020-03-26 14:57:24 -0700774 const State& s(getDrawingState());
chaviw4244e032019-09-04 11:27:49 -0700775 mBufferInfo.mDesiredPresentTime = s.desiredPresentTime;
776 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(s.acquireFence);
777 mBufferInfo.mFence = s.acquireFence;
chaviw4244e032019-09-04 11:27:49 -0700778 mBufferInfo.mTransform = s.transform;
779 mBufferInfo.mDataspace = translateDataspace(s.dataspace);
780 mBufferInfo.mCrop = computeCrop(s);
781 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
782 mBufferInfo.mSurfaceDamage = s.surfaceDamageRegion;
783 mBufferInfo.mHdrMetadata = s.hdrMetadata;
784 mBufferInfo.mApi = s.api;
chaviw4244e032019-09-04 11:27:49 -0700785 mBufferInfo.mTransformToDisplayInverse = s.transformToDisplayInverse;
chaviwf83ce182019-09-12 14:43:08 -0700786 mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(s.clientCacheId);
chaviw4244e032019-09-04 11:27:49 -0700787}
788
Robert Carr916b0362020-10-06 13:53:03 -0700789uint32_t BufferStateLayer::getEffectiveScalingMode() const {
790 return NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
791}
792
chaviw4244e032019-09-04 11:27:49 -0700793Rect BufferStateLayer::computeCrop(const State& s) {
794 if (s.crop.isEmpty() && s.buffer) {
795 return s.buffer->getBounds();
796 } else if (s.buffer) {
797 Rect crop = s.crop;
798 crop.left = std::max(crop.left, 0);
799 crop.top = std::max(crop.top, 0);
800 uint32_t bufferWidth = s.buffer->getWidth();
801 uint32_t bufferHeight = s.buffer->getHeight();
802 if (bufferHeight <= std::numeric_limits<int32_t>::max() &&
803 bufferWidth <= std::numeric_limits<int32_t>::max()) {
804 crop.right = std::min(crop.right, static_cast<int32_t>(bufferWidth));
805 crop.bottom = std::min(crop.bottom, static_cast<int32_t>(bufferHeight));
806 }
807 if (!crop.isValid()) {
808 // Crop rect is out of bounds, return whole buffer
809 return s.buffer->getBounds();
810 }
811 return crop;
812 }
813 return s.crop;
814}
815
chaviwb4c6e582019-08-16 14:35:07 -0700816sp<Layer> BufferStateLayer::createClone() {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700817 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, 0, 0, LayerMetadata());
chaviwb4c6e582019-08-16 14:35:07 -0700818 args.textureName = mTextureName;
Lloyd Pique1c3a5eb2019-10-03 13:07:08 -0700819 sp<BufferStateLayer> layer = mFlinger->getFactory().createBufferStateLayer(args);
chaviwb4c6e582019-08-16 14:35:07 -0700820 layer->mHwcSlotGenerator = mHwcSlotGenerator;
821 layer->setInitialValuesForClone(this);
822 return layer;
823}
Valerie Hau92bf5482020-02-10 09:49:08 -0800824
825Layer::RoundedCornerState BufferStateLayer::getRoundedCornerState() const {
826 const auto& p = mDrawingParent.promote();
827 if (p != nullptr) {
828 RoundedCornerState parentState = p->getRoundedCornerState();
829 if (parentState.radius > 0) {
830 ui::Transform t = getActiveTransform(getDrawingState());
831 t = t.inverse();
832 parentState.cropRect = t.transform(parentState.cropRect);
833 // The rounded corners shader only accepts 1 corner radius for performance reasons,
834 // but a transform matrix can define horizontal and vertical scales.
835 // Let's take the average between both of them and pass into the shader, practically we
836 // never do this type of transformation on windows anyway.
837 parentState.radius *= (t[0][0] + t[1][1]) / 2.0f;
838 return parentState;
839 }
840 }
841 const float radius = getDrawingState().cornerRadius;
842 const State& s(getDrawingState());
843 if (radius <= 0 || (getActiveWidth(s) == UINT32_MAX && getActiveHeight(s) == UINT32_MAX))
844 return RoundedCornerState();
845 return RoundedCornerState(FloatRect(static_cast<float>(s.active.transform.tx()),
846 static_cast<float>(s.active.transform.ty()),
847 static_cast<float>(s.active.transform.tx() + s.active.w),
848 static_cast<float>(s.active.transform.ty() + s.active.h)),
849 radius);
850}
Vishnu Naire7f79c52020-10-29 14:45:03 -0700851
852bool BufferStateLayer::bufferNeedsFiltering() const {
853 const State& s(getDrawingState());
854 if (!s.buffer) {
855 return false;
856 }
857
858 uint32_t bufferWidth = s.buffer->width;
859 uint32_t bufferHeight = s.buffer->height;
860
861 // Undo any transformations on the buffer and return the result.
862 if (s.transform & ui::Transform::ROT_90) {
863 std::swap(bufferWidth, bufferHeight);
864 }
865
866 if (s.transformToDisplayInverse) {
867 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
868 if (invTransform & ui::Transform::ROT_90) {
869 std::swap(bufferWidth, bufferHeight);
870 }
871 }
872
873 const Rect layerSize{getBounds()};
874 return layerSize.width() != bufferWidth || layerSize.height() != bufferHeight;
875}
Robert Carr7121caf2020-12-15 13:07:32 -0800876
877void BufferStateLayer::incrementPendingBufferCount() {
878 mPendingBufferTransactions++;
879 tracePendingBufferCount();
880}
881
882void BufferStateLayer::decrementPendingBufferCount() {
883 mPendingBufferTransactions--;
884 tracePendingBufferCount();
885}
886
887void BufferStateLayer::tracePendingBufferCount() {
888 ATRACE_INT(mBlastTransactionName.c_str(), mPendingBufferTransactions);
889}
890
891uint32_t BufferStateLayer::doTransaction(uint32_t flags) {
892 if (mDrawingState.buffer != nullptr && mDrawingState.buffer != mBufferInfo.mBuffer) {
893 // If we are about to update mDrawingState.buffer but it has not yet latched
894 // then we will drop a buffer and should decrement the pending buffer count.
895 // This logic may not work perfectly in the face of a BufferStateLayer being the
896 // deferred side of a deferred transaction, but we don't expect this use case.
897 decrementPendingBufferCount();
898 }
899 return Layer::doTransaction(flags);
900}
901
Marissa Wall61c58622018-07-18 10:12:20 -0700902} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800903
904// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100905#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"