blob: 462e274c55785cded7c246f040fbb49baca0ef1f [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) {
Adithya Srinivasand17c7da2021-03-05 20:43:32 +0000174 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
175 // Too many SurfaceFrames pending classification. The front of the deque is probably not
176 // tracked by FrameTimeline and will never be presented. This will only result in a memory
177 // leak.
178 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
179 mName.c_str());
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000180 std::string miniDump = mPendingJankClassifications.front()->miniDump();
181 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
Adithya Srinivasand17c7da2021-03-05 20:43:32 +0000182 mPendingJankClassifications.pop_front();
183 }
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100184 mPendingJankClassifications.emplace_back(surfaceFrame);
185}
186
Valerie Haubf784642020-01-29 07:25:23 -0800187void BufferStateLayer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700188 for (const auto& handle : mDrawingState.callbackHandles) {
189 handle->transformHint = mTransformHint;
Valerie Hau871d6352020-01-29 08:44:02 -0800190 handle->dequeueReadyTime = dequeueReadyTime;
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700191 }
192
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100193 std::vector<JankData> jankData;
194 jankData.reserve(mPendingJankClassifications.size());
195 while (!mPendingJankClassifications.empty()
196 && mPendingJankClassifications.front()->getJankType()) {
197 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
198 mPendingJankClassifications.front();
199 mPendingJankClassifications.pop_front();
200 jankData.emplace_back(
201 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
202 }
203
Robert Carr9a803c32021-01-14 16:57:58 -0800204 mFlinger->getTransactionCallbackInvoker().finalizePendingCallbackHandles(
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100205 mDrawingState.callbackHandles, jankData);
Marissa Wall5a68a772018-12-22 17:43:42 -0800206
207 mDrawingState.callbackHandles = {};
Valerie Haubf784642020-01-29 07:25:23 -0800208
209 const sp<Fence>& releaseFence(mPreviousReleaseFence);
210 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(releaseFence);
211 {
212 Mutex::Autolock lock(mFrameEventHistoryMutex);
213 if (mPreviousFrameNumber != 0) {
214 mFrameEventHistory.addRelease(mPreviousFrameNumber, dequeueReadyTime,
215 std::move(releaseFenceTime));
216 }
217 }
Marissa Wall61c58622018-07-18 10:12:20 -0700218}
219
Valerie Hau871d6352020-01-29 08:44:02 -0800220void BufferStateLayer::finalizeFrameEventHistory(const std::shared_ptr<FenceTime>& glDoneFence,
221 const CompositorTiming& compositorTiming) {
222 for (const auto& handle : mDrawingState.callbackHandles) {
223 handle->gpuCompositionDoneFence = glDoneFence;
224 handle->compositorTiming = compositorTiming;
225 }
226}
227
Marissa Walle2ffb422018-10-12 11:33:52 -0700228bool BufferStateLayer::willPresentCurrentTransaction() const {
229 // Returns true if the most recent Transaction applied to CurrentState will be presented.
Robert Carr321e83c2019-08-19 15:49:30 -0700230 return (getSidebandStreamChanged() || getAutoRefresh() ||
Valerie Hauaa194562019-02-05 16:21:38 -0800231 (mCurrentState.modified &&
chaviw8ba8b072021-01-25 14:55:46 -0800232 (mCurrentState.buffer != nullptr || mCurrentState.bgColorLayer != nullptr)));
Marissa Wall61c58622018-07-18 10:12:20 -0700233}
234
Valerie Hau3282b3c2020-02-03 15:37:27 -0800235/* TODO: vhau uncomment once deferred transaction migration complete in
236 * WindowManager
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800237void BufferStateLayer::pushPendingState() {
238 if (!mCurrentState.modified) {
Marissa Wall61c58622018-07-18 10:12:20 -0700239 return;
240 }
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800241 mPendingStates.push_back(mCurrentState);
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700242 ATRACE_INT(mTransactionName.c_str(), mPendingStates.size());
Marissa Wall61c58622018-07-18 10:12:20 -0700243}
Valerie Hau3282b3c2020-02-03 15:37:27 -0800244*/
Marissa Wall61c58622018-07-18 10:12:20 -0700245
246bool BufferStateLayer::applyPendingStates(Layer::State* stateToCommit) {
Valerie Hau3282b3c2020-02-03 15:37:27 -0800247 mCurrentStateModified = mCurrentState.modified;
248 bool stateUpdateAvailable = Layer::applyPendingStates(stateToCommit);
249 mCurrentStateModified = stateUpdateAvailable && mCurrentStateModified;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800250 mCurrentState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700251 return stateUpdateAvailable;
252}
253
Marissa Wall861616d2018-10-22 12:52:23 -0700254// Crop that applies to the window
255Rect BufferStateLayer::getCrop(const Layer::State& /*s*/) const {
256 return Rect::INVALID_RECT;
Marissa Wall61c58622018-07-18 10:12:20 -0700257}
258
259bool BufferStateLayer::setTransform(uint32_t transform) {
chaviw766c9c52021-02-10 17:36:47 -0800260 if (mCurrentState.bufferTransform == transform) return false;
261 mCurrentState.bufferTransform = transform;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800262 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700263 setTransactionFlags(eTransactionNeeded);
264 return true;
265}
266
267bool BufferStateLayer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800268 if (mCurrentState.transformToDisplayInverse == transformToDisplayInverse) return false;
269 mCurrentState.sequence++;
270 mCurrentState.transformToDisplayInverse = transformToDisplayInverse;
271 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700272 setTransactionFlags(eTransactionNeeded);
273 return true;
274}
275
276bool BufferStateLayer::setCrop(const Rect& crop) {
Marissa Wall290ad082019-03-06 13:23:47 -0800277 Rect c = crop;
278 if (c.left < 0) {
279 c.left = 0;
280 }
281 if (c.top < 0) {
282 c.top = 0;
283 }
284 // If the width and/or height are < 0, make it [0, 0, -1, -1] so the equality comparision below
285 // treats all invalid rectangles the same.
286 if (!c.isValid()) {
287 c.makeInvalid();
288 }
289
290 if (mCurrentState.crop == c) return false;
Marissa Wall290ad082019-03-06 13:23:47 -0800291 mCurrentState.crop = c;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800292 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700293 setTransactionFlags(eTransactionNeeded);
294 return true;
295}
296
Marissa Wall861616d2018-10-22 12:52:23 -0700297bool BufferStateLayer::setFrame(const Rect& frame) {
298 int x = frame.left;
299 int y = frame.top;
300 int w = frame.getWidth();
301 int h = frame.getHeight();
302
Marissa Wall0f3242d2018-12-20 15:10:22 -0800303 if (x < 0) {
304 x = 0;
305 w = frame.right;
306 }
307
308 if (y < 0) {
309 y = 0;
310 h = frame.bottom;
311 }
312
chaviw766c9c52021-02-10 17:36:47 -0800313 if (mCurrentState.transform.tx() == x && mCurrentState.transform.ty() == y &&
314 mCurrentState.width == w && mCurrentState.height == h) {
Marissa Wall861616d2018-10-22 12:52:23 -0700315 return false;
316 }
317
318 if (!frame.isValid()) {
319 x = y = w = h = 0;
320 }
chaviw766c9c52021-02-10 17:36:47 -0800321 mCurrentState.transform.set(x, y);
322 mCurrentState.width = w;
323 mCurrentState.height = h;
Marissa Wall861616d2018-10-22 12:52:23 -0700324
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800325 mCurrentState.sequence++;
326 mCurrentState.modified = true;
Marissa Wall861616d2018-10-22 12:52:23 -0700327 setTransactionFlags(eTransactionNeeded);
328 return true;
329}
330
Valerie Hau871d6352020-01-29 08:44:02 -0800331bool BufferStateLayer::addFrameEvent(const sp<Fence>& acquireFence, nsecs_t postedTime,
332 nsecs_t desiredPresentTime) {
Valerie Haubf784642020-01-29 07:25:23 -0800333 Mutex::Autolock lock(mFrameEventHistoryMutex);
334 mAcquireTimeline.updateSignalTimes();
335 std::shared_ptr<FenceTime> acquireFenceTime =
336 std::make_shared<FenceTime>((acquireFence ? acquireFence : Fence::NO_FENCE));
337 NewFrameEventsEntry newTimestamps = {mCurrentState.frameNumber, postedTime, desiredPresentTime,
338 acquireFenceTime};
Valerie Hau871d6352020-01-29 08:44:02 -0800339 mFrameEventHistory.setProducerWantsEvents();
Valerie Haubf784642020-01-29 07:25:23 -0800340 mFrameEventHistory.addQueue(newTimestamps);
341 return true;
342}
343
344bool BufferStateLayer::setBuffer(const sp<GraphicBuffer>& buffer, const sp<Fence>& acquireFence,
Ady Abrahamf0c56492020-12-17 18:04:15 -0800345 nsecs_t postTime, nsecs_t desiredPresentTime, bool isAutoTimestamp,
Vishnu Nairadf632b2021-01-07 14:05:08 -0800346 const client_cache_t& clientCacheId, uint64_t frameNumber,
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000347 std::optional<nsecs_t> dequeueTime,
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000348 const FrameTimelineInfo& info) {
Robert Carr0c1966e2020-10-19 12:12:08 -0700349 ATRACE_CALL();
350
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800351 if (mCurrentState.buffer) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700352 mReleasePreviousBuffer = true;
Robert Carr7121caf2020-12-15 13:07:32 -0800353 if (mCurrentState.buffer != mDrawingState.buffer) {
354 // If mCurrentState has a buffer, and we are about to update again
355 // before swapping to drawing state, then the first buffer will be
356 // dropped and we should decrement the pending buffer count.
357 decrementPendingBufferCount();
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000358 if (mCurrentState.bufferSurfaceFrameTX != nullptr) {
359 addSurfaceFrameDroppedForBuffer(mCurrentState.bufferSurfaceFrameTX);
360 mCurrentState.bufferSurfaceFrameTX.reset();
361 }
Robert Carr7121caf2020-12-15 13:07:32 -0800362 }
Marissa Wallfda30bb2018-10-12 11:34:28 -0700363 }
364
Vishnu Nair6b7c5c92020-09-29 17:27:05 -0700365 mCurrentState.frameNumber = frameNumber;
Valerie Hau2f54d642020-01-22 09:37:03 -0800366
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800367 mCurrentState.buffer = buffer;
Marissa Wall947d34e2019-03-29 14:03:53 -0700368 mCurrentState.clientCacheId = clientCacheId;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800369 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700370 setTransactionFlags(eTransactionNeeded);
Ady Abraham09bd3922019-04-08 10:44:56 -0700371
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800372 const int32_t layerId = getSequence();
Valerie Hau134651a2020-01-28 16:21:22 -0800373 mFlinger->mTimeStats->setPostTime(layerId, mCurrentState.frameNumber, getName().c_str(),
Alec Mouri9a29e672020-09-14 12:39:14 -0700374 mOwnerUid, postTime);
chaviwfa67b552019-08-12 16:51:55 -0700375 mCurrentState.desiredPresentTime = desiredPresentTime;
Ady Abrahamf0c56492020-12-17 18:04:15 -0800376 mCurrentState.isAutoTimestamp = isAutoTimestamp;
Ady Abraham09bd3922019-04-08 10:44:56 -0700377
Ady Abrahamb7f15562021-03-15 18:34:08 -0700378 const nsecs_t presentTime = [&] {
379 if (!isAutoTimestamp) return desiredPresentTime;
380
381 const auto prediction =
382 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
383 if (prediction.has_value()) return prediction->presentTime;
384
385 return static_cast<nsecs_t>(0);
386 }();
387 mFlinger->mScheduler->recordLayerHistory(this, presentTime,
Ady Abraham5def7332020-05-29 16:13:47 -0700388 LayerHistory::LayerUpdateType::Buffer);
Ady Abraham09bd3922019-04-08 10:44:56 -0700389
Ady Abrahamf0c56492020-12-17 18:04:15 -0800390 addFrameEvent(acquireFence, postTime, isAutoTimestamp ? 0 : desiredPresentTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000391
Adithya Srinivasan891004e2021-02-12 20:20:47 +0000392 setFrameTimelineVsyncForBufferTransaction(info, postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000393
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000394 if (dequeueTime && *dequeueTime != 0) {
395 const uint64_t bufferId = buffer->getId();
396 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
397 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
398 FrameTracer::FrameEvent::DEQUEUE);
399 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
400 FrameTracer::FrameEvent::QUEUE);
401 }
Marissa Wall61c58622018-07-18 10:12:20 -0700402 return true;
403}
404
405bool BufferStateLayer::setAcquireFence(const sp<Fence>& fence) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700406 // The acquire fences of BufferStateLayers have already signaled before they are set
407 mCallbackHandleAcquireTime = fence->getSignalTime();
408
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800409 mCurrentState.acquireFence = fence;
410 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700411 setTransactionFlags(eTransactionNeeded);
412 return true;
413}
414
415bool BufferStateLayer::setDataspace(ui::Dataspace dataspace) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800416 if (mCurrentState.dataspace == dataspace) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800417 mCurrentState.dataspace = dataspace;
418 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700419 setTransactionFlags(eTransactionNeeded);
420 return true;
421}
422
423bool BufferStateLayer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800424 if (mCurrentState.hdrMetadata == hdrMetadata) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800425 mCurrentState.hdrMetadata = hdrMetadata;
426 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700427 setTransactionFlags(eTransactionNeeded);
428 return true;
429}
430
431bool BufferStateLayer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800432 mCurrentState.surfaceDamageRegion = surfaceDamage;
433 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700434 setTransactionFlags(eTransactionNeeded);
435 return true;
436}
437
438bool BufferStateLayer::setApi(int32_t api) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800439 if (mCurrentState.api == api) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800440 mCurrentState.api = api;
441 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700442 setTransactionFlags(eTransactionNeeded);
443 return true;
444}
445
446bool BufferStateLayer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800447 if (mCurrentState.sidebandStream == sidebandStream) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800448 mCurrentState.sidebandStream = sidebandStream;
449 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700450 setTransactionFlags(eTransactionNeeded);
451
452 if (!mSidebandStreamChanged.exchange(true)) {
453 // mSidebandStreamChanged was false
454 mFlinger->signalLayerUpdate();
455 }
456 return true;
457}
458
Marissa Walle2ffb422018-10-12 11:33:52 -0700459bool BufferStateLayer::setTransactionCompletedListeners(
460 const std::vector<sp<CallbackHandle>>& handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700461 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
Marissa Walle2ffb422018-10-12 11:33:52 -0700462 if (handles.empty()) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700463 mReleasePreviousBuffer = false;
Marissa Walle2ffb422018-10-12 11:33:52 -0700464 return false;
465 }
466
467 const bool willPresent = willPresentCurrentTransaction();
468
469 for (const auto& handle : handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700470 // If this transaction set a buffer on this layer, release its previous buffer
471 handle->releasePreviousBuffer = mReleasePreviousBuffer;
472
Marissa Walle2ffb422018-10-12 11:33:52 -0700473 // If this layer will be presented in this frame
474 if (willPresent) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700475 // If this transaction set an acquire fence on this layer, set its acquire time
476 handle->acquireTime = mCallbackHandleAcquireTime;
Vishnu Nair935590e2021-02-10 13:05:52 -0800477 handle->frameNumber = mCurrentState.frameNumber;
Marissa Wallfda30bb2018-10-12 11:34:28 -0700478
Marissa Walle2ffb422018-10-12 11:33:52 -0700479 // Notify the transaction completed thread that there is a pending latched callback
480 // handle
Robert Carr9a803c32021-01-14 16:57:58 -0800481 mFlinger->getTransactionCallbackInvoker().registerPendingCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700482
483 // Store so latched time and release fence can be set
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800484 mCurrentState.callbackHandles.push_back(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700485
486 } else { // If this layer will NOT need to be relatched and presented this frame
487 // Notify the transaction completed thread this handle is done
Robert Carr9a803c32021-01-14 16:57:58 -0800488 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700489 }
490 }
491
Marissa Wallfda30bb2018-10-12 11:34:28 -0700492 mReleasePreviousBuffer = false;
493 mCallbackHandleAcquireTime = -1;
494
Marissa Walle2ffb422018-10-12 11:33:52 -0700495 return willPresent;
496}
497
Marissa Wall61c58622018-07-18 10:12:20 -0700498bool BufferStateLayer::setTransparentRegionHint(const Region& transparent) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800499 mCurrentState.transparentRegionHint = transparent;
500 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700501 setTransactionFlags(eTransactionNeeded);
502 return true;
503}
504
Marissa Wall861616d2018-10-22 12:52:23 -0700505Rect BufferStateLayer::getBufferSize(const State& s) const {
506 // for buffer state layers we use the display frame size as the buffer size.
507 if (getActiveWidth(s) < UINT32_MAX && getActiveHeight(s) < UINT32_MAX) {
508 return Rect(getActiveWidth(s), getActiveHeight(s));
Marissa Wall61c58622018-07-18 10:12:20 -0700509 }
510
chaviw7e72caf2020-12-02 16:50:43 -0800511 if (mBufferInfo.mBuffer == nullptr) {
512 return Rect::INVALID_RECT;
513 }
514
Marissa Wall861616d2018-10-22 12:52:23 -0700515 // if the display frame is not defined, use the parent bounds as the buffer size.
516 const auto& p = mDrawingParent.promote();
517 if (p != nullptr) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800518 Rect parentBounds = Rect(p->getBounds(Region()));
Marissa Wall861616d2018-10-22 12:52:23 -0700519 if (!parentBounds.isEmpty()) {
520 return parentBounds;
521 }
522 }
523
Marissa Wall861616d2018-10-22 12:52:23 -0700524 return Rect::INVALID_RECT;
Marissa Wall61c58622018-07-18 10:12:20 -0700525}
Vishnu Nair4351ad52019-02-11 14:13:02 -0800526
527FloatRect BufferStateLayer::computeSourceBounds(const FloatRect& parentBounds) const {
528 const State& s(getDrawingState());
529 // for buffer state layers we use the display frame size as the buffer size.
530 if (getActiveWidth(s) < UINT32_MAX && getActiveHeight(s) < UINT32_MAX) {
531 return FloatRect(0, 0, getActiveWidth(s), getActiveHeight(s));
532 }
533
534 // if the display frame is not defined, use the parent bounds as the buffer size.
535 return parentBounds;
536}
537
Marissa Wall61c58622018-07-18 10:12:20 -0700538// -----------------------------------------------------------------------
539
540// -----------------------------------------------------------------------
541// Interface implementation for BufferLayer
542// -----------------------------------------------------------------------
543bool BufferStateLayer::fenceHasSignaled() const {
Alec Mouri91f6df32020-01-30 08:48:58 -0800544 const bool fenceSignaled =
545 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
546 if (!fenceSignaled) {
547 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
548 TimeStats::LatchSkipReason::LateAcquire);
549 }
550
551 return fenceSignaled;
Marissa Wall61c58622018-07-18 10:12:20 -0700552}
553
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700554bool BufferStateLayer::framePresentTimeIsCurrent(nsecs_t expectedPresentTime) const {
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700555 if (!hasFrameUpdate() || isRemovedFromCurrentState()) {
556 return true;
557 }
558
Ady Abrahamf0c56492020-12-17 18:04:15 -0800559 return mCurrentState.isAutoTimestamp || mCurrentState.desiredPresentTime <= expectedPresentTime;
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700560}
561
Valerie Hau871d6352020-01-29 08:44:02 -0800562bool BufferStateLayer::onPreComposition(nsecs_t refreshStartTime) {
563 for (const auto& handle : mDrawingState.callbackHandles) {
564 handle->refreshStartTime = refreshStartTime;
565 }
566 return BufferLayer::onPreComposition(refreshStartTime);
567}
568
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700569uint64_t BufferStateLayer::getFrameNumber(nsecs_t /*expectedPresentTime*/) const {
Valerie Hau134651a2020-01-28 16:21:22 -0800570 return mDrawingState.frameNumber;
Marissa Wall61c58622018-07-18 10:12:20 -0700571}
572
Robert Carrfe1209c2020-02-11 12:25:35 -0800573/**
574 * This is the frameNumber used for deferred transaction signalling. We need to use this because
575 * of cases where we defer a transaction for a surface to itself. In the BLAST world this
576 * may not make a huge amount of sense (Why not just merge the Buffer transaction with the
577 * deferred transaction?) but this is an important legacy use case, for example moving
578 * a window at the same time it draws makes use of this kind of technique. So anyway
579 * imagine we have something like this:
580 *
581 * Transaction { // containing
582 * Buffer -> frameNumber = 2
583 * DeferTransactionUntil -> frameNumber = 2
584 * Random other stuff
585 * }
586 * Now imagine getHeadFrameNumber returned mDrawingState.mFrameNumber (or mCurrentFrameNumber).
587 * Prior to doTransaction SurfaceFlinger will call notifyAvailableFrames, but because we
588 * haven't swapped mCurrentState to mDrawingState yet we will think the sync point
589 * is not ready. So we will return false from applyPendingState and not swap
590 * current state to drawing state. But because we don't swap current state
591 * to drawing state the number will never update and we will be stuck. This way
592 * we can see we need to return the frame number for the buffer we are about
593 * to apply.
594 */
595uint64_t BufferStateLayer::getHeadFrameNumber(nsecs_t /* expectedPresentTime */) const {
596 return mCurrentState.frameNumber;
597}
598
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800599void BufferStateLayer::setAutoRefresh(bool autoRefresh) {
600 if (!mAutoRefresh.exchange(autoRefresh)) {
601 mFlinger->signalLayerUpdate();
602 }
Marissa Wall61c58622018-07-18 10:12:20 -0700603}
604
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800605bool BufferStateLayer::latchSidebandStream(bool& recomputeVisibleRegions) {
Marissa Wall61c58622018-07-18 10:12:20 -0700606 if (mSidebandStreamChanged.exchange(false)) {
607 const State& s(getDrawingState());
608 // mSidebandStreamChanged was true
Lloyd Pique0b785d82018-12-04 17:25:27 -0800609 mSidebandStream = s.sidebandStream;
Lloyd Piquede196652020-01-22 17:29:58 -0800610 editCompositionState()->sidebandStream = mSidebandStream;
Lloyd Pique0b785d82018-12-04 17:25:27 -0800611 if (mSidebandStream != nullptr) {
Marissa Wall61c58622018-07-18 10:12:20 -0700612 setTransactionFlags(eTransactionNeeded);
613 mFlinger->setTransactionFlags(eTraversalNeeded);
614 }
615 recomputeVisibleRegions = true;
616
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800617 return true;
Marissa Wall61c58622018-07-18 10:12:20 -0700618 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800619 return false;
Marissa Wall61c58622018-07-18 10:12:20 -0700620}
621
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800622bool BufferStateLayer::hasFrameUpdate() const {
Valerie Hauaa194562019-02-05 16:21:38 -0800623 const State& c(getCurrentState());
624 return mCurrentStateModified && (c.buffer != nullptr || c.bgColorLayer != nullptr);
Marissa Wall61c58622018-07-18 10:12:20 -0700625}
626
Ady Abraham43752eb2021-03-04 16:24:25 -0800627std::optional<nsecs_t> BufferStateLayer::nextPredictedPresentTime(int64_t vsyncId) const {
628 const auto prediction =
629 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(vsyncId);
630 if (!prediction.has_value()) {
Ady Abraham63a3e592021-01-06 10:47:15 -0800631 return std::nullopt;
Ady Abrahamce4adf12020-12-15 18:45:12 -0800632 }
633
Ady Abraham43752eb2021-03-04 16:24:25 -0800634 return prediction->presentTime;
Ady Abrahamce4adf12020-12-15 18:45:12 -0800635}
636
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700637status_t BufferStateLayer::updateTexImage(bool& /*recomputeVisibleRegions*/, nsecs_t latchTime,
638 nsecs_t /*expectedPresentTime*/) {
Marissa Wall61c58622018-07-18 10:12:20 -0700639 const State& s(getDrawingState());
640
641 if (!s.buffer) {
Valerie Hauaa194562019-02-05 16:21:38 -0800642 if (s.bgColorLayer) {
643 for (auto& handle : mDrawingState.callbackHandles) {
644 handle->latchTime = latchTime;
645 }
646 }
Marissa Wall61c58622018-07-18 10:12:20 -0700647 return NO_ERROR;
648 }
649
Marissa Wall5a68a772018-12-22 17:43:42 -0800650 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair935590e2021-02-10 13:05:52 -0800651 if (handle->frameNumber == mDrawingState.frameNumber) {
652 handle->latchTime = latchTime;
653 }
Marissa Wall5a68a772018-12-22 17:43:42 -0800654 }
Marissa Walle2ffb422018-10-12 11:33:52 -0700655
Vishnu Nairea0de002020-11-17 17:42:37 -0800656 const int32_t layerId = getSequence();
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000657 const uint64_t bufferId = mDrawingState.buffer->getId();
658 const uint64_t frameNumber = mDrawingState.frameNumber;
659 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
660 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
661 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
662
663 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
664 FrameTracer::FrameEvent::ACQUIRE_FENCE);
665 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
666 FrameTracer::FrameEvent::LATCH);
Marissa Wall61c58622018-07-18 10:12:20 -0700667
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000668 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
669 if (bufferSurfaceFrame != nullptr &&
670 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
671 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
672 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
673 // are processing the next state.
674 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
675 mDrawingState.acquireFence->getSignalTime(), latchTime);
676 bufferSurfaceFrame.reset();
677 }
678
Marissa Wall16c112d2019-03-20 13:21:13 -0700679 mCurrentStateModified = false;
680
Marissa Wall61c58622018-07-18 10:12:20 -0700681 return NO_ERROR;
682}
683
684status_t BufferStateLayer::updateActiveBuffer() {
685 const State& s(getDrawingState());
686
687 if (s.buffer == nullptr) {
688 return BAD_VALUE;
689 }
chaviwdf3c5e82021-01-07 13:00:37 -0800690
691 if (s.buffer != mBufferInfo.mBuffer) {
692 decrementPendingBufferCount();
693 }
Marissa Wall61c58622018-07-18 10:12:20 -0700694
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700695 mPreviousBufferId = getCurrentBufferId();
chaviwd62d3062019-09-04 14:48:02 -0700696 mBufferInfo.mBuffer = s.buffer;
697 mBufferInfo.mFence = s.acquireFence;
Marissa Wall61c58622018-07-18 10:12:20 -0700698
699 return NO_ERROR;
700}
701
Valerie Haubf784642020-01-29 07:25:23 -0800702status_t BufferStateLayer::updateFrameNumber(nsecs_t latchTime) {
Marissa Wall61c58622018-07-18 10:12:20 -0700703 // TODO(marissaw): support frame history events
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700704 mPreviousFrameNumber = mCurrentFrameNumber;
Valerie Hau134651a2020-01-28 16:21:22 -0800705 mCurrentFrameNumber = mDrawingState.frameNumber;
Valerie Haubf784642020-01-29 07:25:23 -0800706 {
707 Mutex::Autolock lock(mFrameEventHistoryMutex);
708 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
709 }
Marissa Wall61c58622018-07-18 10:12:20 -0700710 return NO_ERROR;
711}
712
Marissa Wall947d34e2019-03-29 14:03:53 -0700713void BufferStateLayer::HwcSlotGenerator::bufferErased(const client_cache_t& clientCacheId) {
714 std::lock_guard lock(mMutex);
715 if (!clientCacheId.isValid()) {
716 ALOGE("invalid process, failed to erase buffer");
717 return;
718 }
719 eraseBufferLocked(clientCacheId);
720}
721
722uint32_t BufferStateLayer::HwcSlotGenerator::getHwcCacheSlot(const client_cache_t& clientCacheId) {
723 std::lock_guard<std::mutex> lock(mMutex);
724 auto itr = mCachedBuffers.find(clientCacheId);
725 if (itr == mCachedBuffers.end()) {
726 return addCachedBuffer(clientCacheId);
727 }
728 auto& [hwcCacheSlot, counter] = itr->second;
729 counter = mCounter++;
730 return hwcCacheSlot;
731}
732
733uint32_t BufferStateLayer::HwcSlotGenerator::addCachedBuffer(const client_cache_t& clientCacheId)
734 REQUIRES(mMutex) {
735 if (!clientCacheId.isValid()) {
736 ALOGE("invalid process, returning invalid slot");
737 return BufferQueue::INVALID_BUFFER_SLOT;
738 }
739
740 ClientCache::getInstance().registerErasedRecipient(clientCacheId, wp<ErasedRecipient>(this));
741
742 uint32_t hwcCacheSlot = getFreeHwcCacheSlot();
743 mCachedBuffers[clientCacheId] = {hwcCacheSlot, mCounter++};
744 return hwcCacheSlot;
745}
746
747uint32_t BufferStateLayer::HwcSlotGenerator::getFreeHwcCacheSlot() REQUIRES(mMutex) {
748 if (mFreeHwcCacheSlots.empty()) {
749 evictLeastRecentlyUsed();
750 }
751
752 uint32_t hwcCacheSlot = mFreeHwcCacheSlots.top();
753 mFreeHwcCacheSlots.pop();
754 return hwcCacheSlot;
755}
756
757void BufferStateLayer::HwcSlotGenerator::evictLeastRecentlyUsed() REQUIRES(mMutex) {
758 uint64_t minCounter = UINT_MAX;
759 client_cache_t minClientCacheId = {};
760 for (const auto& [clientCacheId, slotCounter] : mCachedBuffers) {
761 const auto& [hwcCacheSlot, counter] = slotCounter;
762 if (counter < minCounter) {
763 minCounter = counter;
764 minClientCacheId = clientCacheId;
765 }
766 }
767 eraseBufferLocked(minClientCacheId);
768
769 ClientCache::getInstance().unregisterErasedRecipient(minClientCacheId, this);
770}
771
772void BufferStateLayer::HwcSlotGenerator::eraseBufferLocked(const client_cache_t& clientCacheId)
773 REQUIRES(mMutex) {
774 auto itr = mCachedBuffers.find(clientCacheId);
775 if (itr == mCachedBuffers.end()) {
776 return;
777 }
778 auto& [hwcCacheSlot, counter] = itr->second;
779
780 // TODO send to hwc cache and resources
781
782 mFreeHwcCacheSlots.push(hwcCacheSlot);
783 mCachedBuffers.erase(clientCacheId);
784}
chaviw4244e032019-09-04 11:27:49 -0700785
786void BufferStateLayer::gatherBufferInfo() {
chaviwdebadb82020-03-26 14:57:24 -0700787 BufferLayer::gatherBufferInfo();
chaviw4244e032019-09-04 11:27:49 -0700788
chaviwdebadb82020-03-26 14:57:24 -0700789 const State& s(getDrawingState());
chaviw4244e032019-09-04 11:27:49 -0700790 mBufferInfo.mDesiredPresentTime = s.desiredPresentTime;
791 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(s.acquireFence);
792 mBufferInfo.mFence = s.acquireFence;
chaviw766c9c52021-02-10 17:36:47 -0800793 mBufferInfo.mTransform = s.bufferTransform;
chaviw4244e032019-09-04 11:27:49 -0700794 mBufferInfo.mDataspace = translateDataspace(s.dataspace);
795 mBufferInfo.mCrop = computeCrop(s);
796 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
797 mBufferInfo.mSurfaceDamage = s.surfaceDamageRegion;
798 mBufferInfo.mHdrMetadata = s.hdrMetadata;
799 mBufferInfo.mApi = s.api;
chaviw4244e032019-09-04 11:27:49 -0700800 mBufferInfo.mTransformToDisplayInverse = s.transformToDisplayInverse;
chaviwf83ce182019-09-12 14:43:08 -0700801 mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(s.clientCacheId);
chaviw4244e032019-09-04 11:27:49 -0700802}
803
Robert Carr916b0362020-10-06 13:53:03 -0700804uint32_t BufferStateLayer::getEffectiveScalingMode() const {
805 return NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
806}
807
chaviw4244e032019-09-04 11:27:49 -0700808Rect BufferStateLayer::computeCrop(const State& s) {
809 if (s.crop.isEmpty() && s.buffer) {
810 return s.buffer->getBounds();
811 } else if (s.buffer) {
812 Rect crop = s.crop;
813 crop.left = std::max(crop.left, 0);
814 crop.top = std::max(crop.top, 0);
815 uint32_t bufferWidth = s.buffer->getWidth();
816 uint32_t bufferHeight = s.buffer->getHeight();
817 if (bufferHeight <= std::numeric_limits<int32_t>::max() &&
818 bufferWidth <= std::numeric_limits<int32_t>::max()) {
819 crop.right = std::min(crop.right, static_cast<int32_t>(bufferWidth));
820 crop.bottom = std::min(crop.bottom, static_cast<int32_t>(bufferHeight));
821 }
822 if (!crop.isValid()) {
823 // Crop rect is out of bounds, return whole buffer
824 return s.buffer->getBounds();
825 }
826 return crop;
827 }
828 return s.crop;
829}
830
chaviwb4c6e582019-08-16 14:35:07 -0700831sp<Layer> BufferStateLayer::createClone() {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700832 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, 0, 0, LayerMetadata());
chaviwb4c6e582019-08-16 14:35:07 -0700833 args.textureName = mTextureName;
Lloyd Pique1c3a5eb2019-10-03 13:07:08 -0700834 sp<BufferStateLayer> layer = mFlinger->getFactory().createBufferStateLayer(args);
chaviwb4c6e582019-08-16 14:35:07 -0700835 layer->mHwcSlotGenerator = mHwcSlotGenerator;
836 layer->setInitialValuesForClone(this);
837 return layer;
838}
Valerie Hau92bf5482020-02-10 09:49:08 -0800839
840Layer::RoundedCornerState BufferStateLayer::getRoundedCornerState() const {
841 const auto& p = mDrawingParent.promote();
842 if (p != nullptr) {
843 RoundedCornerState parentState = p->getRoundedCornerState();
844 if (parentState.radius > 0) {
845 ui::Transform t = getActiveTransform(getDrawingState());
846 t = t.inverse();
847 parentState.cropRect = t.transform(parentState.cropRect);
848 // The rounded corners shader only accepts 1 corner radius for performance reasons,
849 // but a transform matrix can define horizontal and vertical scales.
850 // Let's take the average between both of them and pass into the shader, practically we
851 // never do this type of transformation on windows anyway.
852 parentState.radius *= (t[0][0] + t[1][1]) / 2.0f;
853 return parentState;
854 }
855 }
856 const float radius = getDrawingState().cornerRadius;
857 const State& s(getDrawingState());
858 if (radius <= 0 || (getActiveWidth(s) == UINT32_MAX && getActiveHeight(s) == UINT32_MAX))
859 return RoundedCornerState();
chaviw766c9c52021-02-10 17:36:47 -0800860 return RoundedCornerState(FloatRect(static_cast<float>(s.transform.tx()),
861 static_cast<float>(s.transform.ty()),
862 static_cast<float>(s.transform.tx() + s.width),
863 static_cast<float>(s.transform.ty() + s.height)),
Valerie Hau92bf5482020-02-10 09:49:08 -0800864 radius);
865}
Vishnu Naire7f79c52020-10-29 14:45:03 -0700866
867bool BufferStateLayer::bufferNeedsFiltering() const {
868 const State& s(getDrawingState());
869 if (!s.buffer) {
870 return false;
871 }
872
873 uint32_t bufferWidth = s.buffer->width;
874 uint32_t bufferHeight = s.buffer->height;
875
876 // Undo any transformations on the buffer and return the result.
chaviw766c9c52021-02-10 17:36:47 -0800877 if (s.bufferTransform & ui::Transform::ROT_90) {
Vishnu Naire7f79c52020-10-29 14:45:03 -0700878 std::swap(bufferWidth, bufferHeight);
879 }
880
881 if (s.transformToDisplayInverse) {
882 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
883 if (invTransform & ui::Transform::ROT_90) {
884 std::swap(bufferWidth, bufferHeight);
885 }
886 }
887
888 const Rect layerSize{getBounds()};
889 return layerSize.width() != bufferWidth || layerSize.height() != bufferHeight;
890}
Robert Carr7121caf2020-12-15 13:07:32 -0800891
Robert Carr7121caf2020-12-15 13:07:32 -0800892void BufferStateLayer::decrementPendingBufferCount() {
Vishnu Nair8eda69e2021-02-26 10:42:10 -0800893 int32_t pendingBuffers = --mPendingBufferTransactions;
894 tracePendingBufferCount(pendingBuffers);
Robert Carr7121caf2020-12-15 13:07:32 -0800895}
896
Vishnu Nair8eda69e2021-02-26 10:42:10 -0800897void BufferStateLayer::tracePendingBufferCount(int32_t pendingBuffers) {
898 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
Robert Carr7121caf2020-12-15 13:07:32 -0800899}
900
901uint32_t BufferStateLayer::doTransaction(uint32_t flags) {
902 if (mDrawingState.buffer != nullptr && mDrawingState.buffer != mBufferInfo.mBuffer) {
903 // If we are about to update mDrawingState.buffer but it has not yet latched
904 // then we will drop a buffer and should decrement the pending buffer count.
905 // This logic may not work perfectly in the face of a BufferStateLayer being the
906 // deferred side of a deferred transaction, but we don't expect this use case.
907 decrementPendingBufferCount();
908 }
909 return Layer::doTransaction(flags);
910}
911
Marissa Wall61c58622018-07-18 10:12:20 -0700912} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800913
914// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100915#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"