blob: ed826a01009fa7a9ff2ac55e2d2987035db7f7d6 [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;
Vishnu Nair1506b182021-02-22 14:35:15 -080044namespace {
45void callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
46 const sp<GraphicBuffer>& buffer, const sp<Fence>& releaseFence) {
47 if (!listener) {
48 return;
49 }
50 listener->onReleaseBuffer(buffer->getId(), releaseFence ? releaseFence : Fence::NO_FENCE);
51}
52} // namespace
53
Lloyd Pique42ab75e2018-09-12 20:46:03 -070054// clang-format off
55const std::array<float, 16> BufferStateLayer::IDENTITY_MATRIX{
56 1, 0, 0, 0,
57 0, 1, 0, 0,
58 0, 0, 1, 0,
59 0, 0, 0, 1
60};
61// clang-format on
Marissa Wall61c58622018-07-18 10:12:20 -070062
Marissa Wall947d34e2019-03-29 14:03:53 -070063BufferStateLayer::BufferStateLayer(const LayerCreationArgs& args)
64 : BufferLayer(args), mHwcSlotGenerator(new HwcSlotGenerator()) {
Marissa Wall3ff826c2019-02-07 11:58:25 -080065 mCurrentState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nair60356342018-11-13 13:00:45 -080066}
Marissa Wall61c58622018-07-18 10:12:20 -070067
Alec Mouri4545a8a2019-08-08 20:05:32 -070068BufferStateLayer::~BufferStateLayer() {
chaviwb4c6e582019-08-16 14:35:07 -070069 // The original layer and the clone layer share the same texture and buffer. Therefore, only
70 // one of the layers, in this case the original layer, needs to handle the deletion. The
71 // original layer and the clone should be removed at the same time so there shouldn't be any
72 // issue with the clone layer trying to use the texture.
73 if (mBufferInfo.mBuffer != nullptr && !isClone()) {
chaviwd62d3062019-09-04 14:48:02 -070074 // Ensure that mBuffer is uncached from RenderEngine here, as
Alec Mouri4545a8a2019-08-08 20:05:32 -070075 // RenderEngine may have been using the buffer as an external texture
76 // after the client uncached the buffer.
77 auto& engine(mFlinger->getRenderEngine());
Vishnu Nair1506b182021-02-22 14:35:15 -080078 const uint64_t bufferId = mBufferInfo.mBuffer->getId();
79 engine.unbindExternalTextureBuffer(bufferId);
80 callReleaseBufferCallback(mDrawingState.releaseBufferListener, mBufferInfo.mBuffer,
81 mBufferInfo.mFence);
Alec Mouri4545a8a2019-08-08 20:05:32 -070082 }
83}
84
Robert Carr8d958532020-11-10 14:09:16 -080085status_t BufferStateLayer::addReleaseFence(const sp<CallbackHandle>& ch,
86 const sp<Fence>& fence) {
87 if (ch == nullptr) {
88 return OK;
89 }
Vishnu Nair1506b182021-02-22 14:35:15 -080090 ch->previousBufferId = mPreviousBufferId;
Robert Carr8d958532020-11-10 14:09:16 -080091 if (!ch->previousReleaseFence.get()) {
92 ch->previousReleaseFence = fence;
93 return OK;
94 }
95
96 // Below logic is lifted from ConsumerBase.cpp:
97 // Check status of fences first because merging is expensive.
98 // Merging an invalid fence with any other fence results in an
99 // invalid fence.
100 auto currentStatus = ch->previousReleaseFence->getStatus();
101 if (currentStatus == Fence::Status::Invalid) {
102 ALOGE("Existing fence has invalid state, layer: %s", mName.c_str());
103 return BAD_VALUE;
104 }
105
106 auto incomingStatus = fence->getStatus();
107 if (incomingStatus == Fence::Status::Invalid) {
108 ALOGE("New fence has invalid state, layer: %s", mName.c_str());
109 ch->previousReleaseFence = fence;
110 return BAD_VALUE;
111 }
112
113 // If both fences are signaled or both are unsignaled, we need to merge
114 // them to get an accurate timestamp.
115 if (currentStatus == incomingStatus) {
116 char fenceName[32] = {};
117 snprintf(fenceName, 32, "%.28s", mName.c_str());
118 sp<Fence> mergedFence = Fence::merge(
119 fenceName, ch->previousReleaseFence, fence);
120 if (!mergedFence.get()) {
121 ALOGE("failed to merge release fences, layer: %s", mName.c_str());
122 // synchronization is broken, the best we can do is hope fences
123 // signal in order so the new fence will act like a union
124 ch->previousReleaseFence = fence;
125 return BAD_VALUE;
126 }
127 ch->previousReleaseFence = mergedFence;
128 } else if (incomingStatus == Fence::Status::Unsignaled) {
129 // If one fence has signaled and the other hasn't, the unsignaled
130 // fence will approximately correspond with the correct timestamp.
131 // There's a small race if both fences signal at about the same time
132 // and their statuses are retrieved with unfortunate timing. However,
133 // by this point, they will have both signaled and only the timestamp
134 // will be slightly off; any dependencies after this point will
135 // already have been met.
136 ch->previousReleaseFence = fence;
137 }
138 // else if (currentStatus == Fence::Status::Unsignaled) is a no-op.
139
140 return OK;
141}
142
Marissa Wall61c58622018-07-18 10:12:20 -0700143// -----------------------------------------------------------------------
144// Interface implementation for Layer
145// -----------------------------------------------------------------------
Marissa Wallfda30bb2018-10-12 11:34:28 -0700146void BufferStateLayer::onLayerDisplayed(const sp<Fence>& releaseFence) {
Robert Carr8d958532020-11-10 14:09:16 -0800147 if (!releaseFence->isValid()) {
148 return;
149 }
Marissa Wall5a68a772018-12-22 17:43:42 -0800150 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
151 // buffer that was presented on this layer. The first transaction that came in this frame that
152 // replaced the previous buffer on this layer needs this release fence, because the fence will
153 // let the client know when that previous buffer is removed from the screen.
154 //
155 // Every other transaction on this layer does not need a release fence because no other
156 // Transactions that were set on this layer this frame are going to have their preceeding buffer
157 // removed from the display this frame.
158 //
159 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
160 // buffer so it doesn't need a previous release fence because the layer still needs the previous
161 // buffer. The second transaction contains a buffer so it needs a previous release fence because
162 // the previous buffer will be released this frame. The third transaction also contains a
163 // buffer. It replaces the buffer in the second transaction. The buffer in the second
164 // transaction will now no longer be presented so it is released immediately and the third
165 // transaction doesn't need a previous release fence.
Robert Carr8d958532020-11-10 14:09:16 -0800166 sp<CallbackHandle> ch;
Marissa Wall5a68a772018-12-22 17:43:42 -0800167 for (auto& handle : mDrawingState.callbackHandles) {
168 if (handle->releasePreviousBuffer) {
Robert Carr8d958532020-11-10 14:09:16 -0800169 ch = handle;
Marissa Wall5a68a772018-12-22 17:43:42 -0800170 break;
171 }
172 }
Robert Carr8d958532020-11-10 14:09:16 -0800173 auto status = addReleaseFence(ch, releaseFence);
174 if (status != OK) {
175 ALOGE("Failed to add release fence for layer %s", getName().c_str());
176 }
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700177
Valerie Haubf784642020-01-29 07:25:23 -0800178 mPreviousReleaseFence = releaseFence;
179
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700180 // Prevent tracing the same release multiple times.
181 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700182 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
183 }
Marissa Wall61c58622018-07-18 10:12:20 -0700184}
185
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100186void BufferStateLayer::onSurfaceFrameCreated(
187 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasand17c7da2021-03-05 20:43:32 +0000188 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
189 // Too many SurfaceFrames pending classification. The front of the deque is probably not
190 // tracked by FrameTimeline and will never be presented. This will only result in a memory
191 // leak.
192 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
193 mName.c_str());
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000194 std::string miniDump = mPendingJankClassifications.front()->miniDump();
195 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
Adithya Srinivasand17c7da2021-03-05 20:43:32 +0000196 mPendingJankClassifications.pop_front();
197 }
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100198 mPendingJankClassifications.emplace_back(surfaceFrame);
199}
200
Valerie Haubf784642020-01-29 07:25:23 -0800201void BufferStateLayer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700202 for (const auto& handle : mDrawingState.callbackHandles) {
203 handle->transformHint = mTransformHint;
Valerie Hau871d6352020-01-29 08:44:02 -0800204 handle->dequeueReadyTime = dequeueReadyTime;
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700205 }
206
Vishnu Nair1506b182021-02-22 14:35:15 -0800207 // If there are multiple transactions in this frame, set the previous id on the earliest
208 // transacton. We don't need to pass in the released buffer id to multiple transactions.
209 // The buffer id does not have to correspond to any particular transaction as long as the
210 // listening end point is the same but the client expects the first transaction callback that
211 // replaces the presented buffer to contain the release fence. This follows the same logic.
212 // see BufferStateLayer::onLayerDisplayed.
213 for (auto& handle : mDrawingState.callbackHandles) {
214 if (handle->releasePreviousBuffer) {
215 handle->previousBufferId = mPreviousBufferId;
216 break;
217 }
218 }
219
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100220 std::vector<JankData> jankData;
221 jankData.reserve(mPendingJankClassifications.size());
222 while (!mPendingJankClassifications.empty()
223 && mPendingJankClassifications.front()->getJankType()) {
224 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
225 mPendingJankClassifications.front();
226 mPendingJankClassifications.pop_front();
227 jankData.emplace_back(
228 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
229 }
230
Robert Carr9a803c32021-01-14 16:57:58 -0800231 mFlinger->getTransactionCallbackInvoker().finalizePendingCallbackHandles(
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100232 mDrawingState.callbackHandles, jankData);
Marissa Wall5a68a772018-12-22 17:43:42 -0800233
234 mDrawingState.callbackHandles = {};
Valerie Haubf784642020-01-29 07:25:23 -0800235
236 const sp<Fence>& releaseFence(mPreviousReleaseFence);
237 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(releaseFence);
238 {
239 Mutex::Autolock lock(mFrameEventHistoryMutex);
240 if (mPreviousFrameNumber != 0) {
241 mFrameEventHistory.addRelease(mPreviousFrameNumber, dequeueReadyTime,
242 std::move(releaseFenceTime));
243 }
244 }
Marissa Wall61c58622018-07-18 10:12:20 -0700245}
246
Valerie Hau871d6352020-01-29 08:44:02 -0800247void BufferStateLayer::finalizeFrameEventHistory(const std::shared_ptr<FenceTime>& glDoneFence,
248 const CompositorTiming& compositorTiming) {
249 for (const auto& handle : mDrawingState.callbackHandles) {
250 handle->gpuCompositionDoneFence = glDoneFence;
251 handle->compositorTiming = compositorTiming;
252 }
253}
254
Marissa Walle2ffb422018-10-12 11:33:52 -0700255bool BufferStateLayer::willPresentCurrentTransaction() const {
256 // Returns true if the most recent Transaction applied to CurrentState will be presented.
Robert Carr321e83c2019-08-19 15:49:30 -0700257 return (getSidebandStreamChanged() || getAutoRefresh() ||
Valerie Hauaa194562019-02-05 16:21:38 -0800258 (mCurrentState.modified &&
chaviw8ba8b072021-01-25 14:55:46 -0800259 (mCurrentState.buffer != nullptr || mCurrentState.bgColorLayer != nullptr)));
Marissa Wall61c58622018-07-18 10:12:20 -0700260}
261
Valerie Hau3282b3c2020-02-03 15:37:27 -0800262/* TODO: vhau uncomment once deferred transaction migration complete in
263 * WindowManager
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800264void BufferStateLayer::pushPendingState() {
265 if (!mCurrentState.modified) {
Marissa Wall61c58622018-07-18 10:12:20 -0700266 return;
267 }
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800268 mPendingStates.push_back(mCurrentState);
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700269 ATRACE_INT(mTransactionName.c_str(), mPendingStates.size());
Marissa Wall61c58622018-07-18 10:12:20 -0700270}
Valerie Hau3282b3c2020-02-03 15:37:27 -0800271*/
Marissa Wall61c58622018-07-18 10:12:20 -0700272
273bool BufferStateLayer::applyPendingStates(Layer::State* stateToCommit) {
Valerie Hau3282b3c2020-02-03 15:37:27 -0800274 mCurrentStateModified = mCurrentState.modified;
275 bool stateUpdateAvailable = Layer::applyPendingStates(stateToCommit);
276 mCurrentStateModified = stateUpdateAvailable && mCurrentStateModified;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800277 mCurrentState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700278 return stateUpdateAvailable;
279}
280
chaviw9a93ea62021-03-11 16:44:42 -0600281Rect BufferStateLayer::getCrop(const Layer::State& s) const {
282 return s.crop;
Marissa Wall61c58622018-07-18 10:12:20 -0700283}
284
285bool BufferStateLayer::setTransform(uint32_t transform) {
chaviw766c9c52021-02-10 17:36:47 -0800286 if (mCurrentState.bufferTransform == transform) return false;
287 mCurrentState.bufferTransform = transform;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800288 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700289 setTransactionFlags(eTransactionNeeded);
290 return true;
291}
292
293bool BufferStateLayer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800294 if (mCurrentState.transformToDisplayInverse == transformToDisplayInverse) return false;
295 mCurrentState.sequence++;
296 mCurrentState.transformToDisplayInverse = transformToDisplayInverse;
297 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700298 setTransactionFlags(eTransactionNeeded);
299 return true;
300}
301
302bool BufferStateLayer::setCrop(const Rect& crop) {
chaviw9a93ea62021-03-11 16:44:42 -0600303 if (mCurrentState.crop == crop) return false;
304 mCurrentState.sequence++;
305 mCurrentState.crop = crop;
Marissa Wall290ad082019-03-06 13:23:47 -0800306
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800307 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700308 setTransactionFlags(eTransactionNeeded);
309 return true;
310}
311
chaviw9a93ea62021-03-11 16:44:42 -0600312bool BufferStateLayer::setMatrix(const layer_state_t::matrix22_t& matrix,
313 bool allowNonRectPreservingTransforms) {
314 if (mCurrentState.transform.dsdx() == matrix.dsdx &&
315 mCurrentState.transform.dtdy() == matrix.dtdy &&
316 mCurrentState.transform.dtdx() == matrix.dtdx &&
317 mCurrentState.transform.dsdy() == matrix.dsdy) {
Marissa Wall861616d2018-10-22 12:52:23 -0700318 return false;
319 }
320
chaviw9a93ea62021-03-11 16:44:42 -0600321 ui::Transform t;
322 t.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
323
324 if (!allowNonRectPreservingTransforms && !t.preserveRects()) {
325 ALOGW("Attempt to set rotation matrix without permission ACCESS_SURFACE_FLINGER nor "
326 "ROTATE_SURFACE_FLINGER ignored");
327 return false;
Marissa Wall861616d2018-10-22 12:52:23 -0700328 }
chaviw9a93ea62021-03-11 16:44:42 -0600329
330 mCurrentState.transform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
Marissa Wall861616d2018-10-22 12:52:23 -0700331
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800332 mCurrentState.sequence++;
333 mCurrentState.modified = true;
Marissa Wall861616d2018-10-22 12:52:23 -0700334 setTransactionFlags(eTransactionNeeded);
chaviw9a93ea62021-03-11 16:44:42 -0600335
336 return true;
337}
338
339bool BufferStateLayer::setPosition(float x, float y) {
340 if (mCurrentState.transform.tx() == x && mCurrentState.transform.ty() == y) {
341 return false;
342 }
343
344 mCurrentState.transform.set(x, y);
345
346 mCurrentState.sequence++;
347 mCurrentState.modified = true;
348 setTransactionFlags(eTransactionNeeded);
349
Marissa Wall861616d2018-10-22 12:52:23 -0700350 return true;
351}
352
Valerie Hau871d6352020-01-29 08:44:02 -0800353bool BufferStateLayer::addFrameEvent(const sp<Fence>& acquireFence, nsecs_t postedTime,
354 nsecs_t desiredPresentTime) {
Valerie Haubf784642020-01-29 07:25:23 -0800355 Mutex::Autolock lock(mFrameEventHistoryMutex);
356 mAcquireTimeline.updateSignalTimes();
357 std::shared_ptr<FenceTime> acquireFenceTime =
358 std::make_shared<FenceTime>((acquireFence ? acquireFence : Fence::NO_FENCE));
359 NewFrameEventsEntry newTimestamps = {mCurrentState.frameNumber, postedTime, desiredPresentTime,
360 acquireFenceTime};
Valerie Hau871d6352020-01-29 08:44:02 -0800361 mFrameEventHistory.setProducerWantsEvents();
Valerie Haubf784642020-01-29 07:25:23 -0800362 mFrameEventHistory.addQueue(newTimestamps);
363 return true;
364}
365
366bool BufferStateLayer::setBuffer(const sp<GraphicBuffer>& buffer, const sp<Fence>& acquireFence,
Ady Abrahamf0c56492020-12-17 18:04:15 -0800367 nsecs_t postTime, nsecs_t desiredPresentTime, bool isAutoTimestamp,
Vishnu Nairadf632b2021-01-07 14:05:08 -0800368 const client_cache_t& clientCacheId, uint64_t frameNumber,
Vishnu Nair1506b182021-02-22 14:35:15 -0800369 std::optional<nsecs_t> dequeueTime, const FrameTimelineInfo& info,
370 const sp<ITransactionCompletedListener>& releaseBufferListener) {
Robert Carr0c1966e2020-10-19 12:12:08 -0700371 ATRACE_CALL();
372
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800373 if (mCurrentState.buffer) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700374 mReleasePreviousBuffer = true;
Robert Carr7121caf2020-12-15 13:07:32 -0800375 if (mCurrentState.buffer != mDrawingState.buffer) {
376 // If mCurrentState has a buffer, and we are about to update again
377 // before swapping to drawing state, then the first buffer will be
Vishnu Nair1506b182021-02-22 14:35:15 -0800378 // dropped and we should decrement the pending buffer count and
379 // call any release buffer callbacks if set.
380 callReleaseBufferCallback(mCurrentState.releaseBufferListener, mCurrentState.buffer,
381 mCurrentState.acquireFence);
Robert Carr7121caf2020-12-15 13:07:32 -0800382 decrementPendingBufferCount();
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000383 if (mCurrentState.bufferSurfaceFrameTX != nullptr) {
384 addSurfaceFrameDroppedForBuffer(mCurrentState.bufferSurfaceFrameTX);
385 mCurrentState.bufferSurfaceFrameTX.reset();
386 }
Robert Carr7121caf2020-12-15 13:07:32 -0800387 }
Marissa Wallfda30bb2018-10-12 11:34:28 -0700388 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -0700389 mCurrentState.frameNumber = frameNumber;
Vishnu Nair1506b182021-02-22 14:35:15 -0800390 mCurrentState.releaseBufferListener = releaseBufferListener;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800391 mCurrentState.buffer = buffer;
Marissa Wall947d34e2019-03-29 14:03:53 -0700392 mCurrentState.clientCacheId = clientCacheId;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800393 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700394 setTransactionFlags(eTransactionNeeded);
Ady Abraham09bd3922019-04-08 10:44:56 -0700395
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800396 const int32_t layerId = getSequence();
Valerie Hau134651a2020-01-28 16:21:22 -0800397 mFlinger->mTimeStats->setPostTime(layerId, mCurrentState.frameNumber, getName().c_str(),
Alec Mouri9a29e672020-09-14 12:39:14 -0700398 mOwnerUid, postTime);
chaviwfa67b552019-08-12 16:51:55 -0700399 mCurrentState.desiredPresentTime = desiredPresentTime;
Ady Abrahamf0c56492020-12-17 18:04:15 -0800400 mCurrentState.isAutoTimestamp = isAutoTimestamp;
Ady Abraham09bd3922019-04-08 10:44:56 -0700401
Ady Abrahamb7f15562021-03-15 18:34:08 -0700402 const nsecs_t presentTime = [&] {
403 if (!isAutoTimestamp) return desiredPresentTime;
404
405 const auto prediction =
406 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
407 if (prediction.has_value()) return prediction->presentTime;
408
409 return static_cast<nsecs_t>(0);
410 }();
411 mFlinger->mScheduler->recordLayerHistory(this, presentTime,
Ady Abraham5def7332020-05-29 16:13:47 -0700412 LayerHistory::LayerUpdateType::Buffer);
Ady Abraham09bd3922019-04-08 10:44:56 -0700413
Ady Abrahamf0c56492020-12-17 18:04:15 -0800414 addFrameEvent(acquireFence, postTime, isAutoTimestamp ? 0 : desiredPresentTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000415
Adithya Srinivasan891004e2021-02-12 20:20:47 +0000416 setFrameTimelineVsyncForBufferTransaction(info, postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000417
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000418 if (dequeueTime && *dequeueTime != 0) {
419 const uint64_t bufferId = buffer->getId();
420 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
421 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
422 FrameTracer::FrameEvent::DEQUEUE);
423 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
424 FrameTracer::FrameEvent::QUEUE);
425 }
chaviw9a93ea62021-03-11 16:44:42 -0600426
427 mCurrentState.width = mCurrentState.buffer->width;
428 mCurrentState.height = mCurrentState.buffer->height;
429
Marissa Wall61c58622018-07-18 10:12:20 -0700430 return true;
431}
432
433bool BufferStateLayer::setAcquireFence(const sp<Fence>& fence) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800434 mCurrentState.acquireFence = fence;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -0700435 mCurrentState.acquireFenceTime = std::make_unique<FenceTime>(fence);
436
437 // The acquire fences of BufferStateLayers have already signaled before they are set
438 mCallbackHandleAcquireTime = mCurrentState.acquireFenceTime->getSignalTime();
439
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800440 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700441 setTransactionFlags(eTransactionNeeded);
442 return true;
443}
444
445bool BufferStateLayer::setDataspace(ui::Dataspace dataspace) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800446 if (mCurrentState.dataspace == dataspace) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800447 mCurrentState.dataspace = dataspace;
448 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700449 setTransactionFlags(eTransactionNeeded);
450 return true;
451}
452
453bool BufferStateLayer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800454 if (mCurrentState.hdrMetadata == hdrMetadata) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800455 mCurrentState.hdrMetadata = hdrMetadata;
456 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700457 setTransactionFlags(eTransactionNeeded);
458 return true;
459}
460
461bool BufferStateLayer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800462 mCurrentState.surfaceDamageRegion = surfaceDamage;
463 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700464 setTransactionFlags(eTransactionNeeded);
465 return true;
466}
467
468bool BufferStateLayer::setApi(int32_t api) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800469 if (mCurrentState.api == api) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800470 mCurrentState.api = api;
471 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700472 setTransactionFlags(eTransactionNeeded);
473 return true;
474}
475
476bool BufferStateLayer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800477 if (mCurrentState.sidebandStream == sidebandStream) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800478 mCurrentState.sidebandStream = sidebandStream;
479 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700480 setTransactionFlags(eTransactionNeeded);
481
482 if (!mSidebandStreamChanged.exchange(true)) {
483 // mSidebandStreamChanged was false
484 mFlinger->signalLayerUpdate();
485 }
486 return true;
487}
488
Marissa Walle2ffb422018-10-12 11:33:52 -0700489bool BufferStateLayer::setTransactionCompletedListeners(
490 const std::vector<sp<CallbackHandle>>& handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700491 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
Marissa Walle2ffb422018-10-12 11:33:52 -0700492 if (handles.empty()) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700493 mReleasePreviousBuffer = false;
Marissa Walle2ffb422018-10-12 11:33:52 -0700494 return false;
495 }
496
497 const bool willPresent = willPresentCurrentTransaction();
498
499 for (const auto& handle : handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700500 // If this transaction set a buffer on this layer, release its previous buffer
501 handle->releasePreviousBuffer = mReleasePreviousBuffer;
502
Marissa Walle2ffb422018-10-12 11:33:52 -0700503 // If this layer will be presented in this frame
504 if (willPresent) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700505 // If this transaction set an acquire fence on this layer, set its acquire time
506 handle->acquireTime = mCallbackHandleAcquireTime;
Vishnu Nair935590e2021-02-10 13:05:52 -0800507 handle->frameNumber = mCurrentState.frameNumber;
Marissa Wallfda30bb2018-10-12 11:34:28 -0700508
Marissa Walle2ffb422018-10-12 11:33:52 -0700509 // Notify the transaction completed thread that there is a pending latched callback
510 // handle
Robert Carr9a803c32021-01-14 16:57:58 -0800511 mFlinger->getTransactionCallbackInvoker().registerPendingCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700512
513 // Store so latched time and release fence can be set
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800514 mCurrentState.callbackHandles.push_back(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700515
516 } else { // If this layer will NOT need to be relatched and presented this frame
517 // Notify the transaction completed thread this handle is done
Robert Carr9a803c32021-01-14 16:57:58 -0800518 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700519 }
520 }
521
Marissa Wallfda30bb2018-10-12 11:34:28 -0700522 mReleasePreviousBuffer = false;
523 mCallbackHandleAcquireTime = -1;
524
Marissa Walle2ffb422018-10-12 11:33:52 -0700525 return willPresent;
526}
527
Marissa Wall61c58622018-07-18 10:12:20 -0700528bool BufferStateLayer::setTransparentRegionHint(const Region& transparent) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800529 mCurrentState.transparentRegionHint = transparent;
530 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700531 setTransactionFlags(eTransactionNeeded);
532 return true;
533}
534
Marissa Wall861616d2018-10-22 12:52:23 -0700535Rect BufferStateLayer::getBufferSize(const State& s) const {
536 // for buffer state layers we use the display frame size as the buffer size.
537 if (getActiveWidth(s) < UINT32_MAX && getActiveHeight(s) < UINT32_MAX) {
538 return Rect(getActiveWidth(s), getActiveHeight(s));
Marissa Wall61c58622018-07-18 10:12:20 -0700539 }
540
chaviw7e72caf2020-12-02 16:50:43 -0800541 if (mBufferInfo.mBuffer == nullptr) {
542 return Rect::INVALID_RECT;
543 }
544
Marissa Wall861616d2018-10-22 12:52:23 -0700545 // if the display frame is not defined, use the parent bounds as the buffer size.
546 const auto& p = mDrawingParent.promote();
547 if (p != nullptr) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800548 Rect parentBounds = Rect(p->getBounds(Region()));
Marissa Wall861616d2018-10-22 12:52:23 -0700549 if (!parentBounds.isEmpty()) {
550 return parentBounds;
551 }
552 }
553
Marissa Wall861616d2018-10-22 12:52:23 -0700554 return Rect::INVALID_RECT;
Marissa Wall61c58622018-07-18 10:12:20 -0700555}
Vishnu Nair4351ad52019-02-11 14:13:02 -0800556
557FloatRect BufferStateLayer::computeSourceBounds(const FloatRect& parentBounds) const {
558 const State& s(getDrawingState());
559 // for buffer state layers we use the display frame size as the buffer size.
560 if (getActiveWidth(s) < UINT32_MAX && getActiveHeight(s) < UINT32_MAX) {
561 return FloatRect(0, 0, getActiveWidth(s), getActiveHeight(s));
562 }
563
564 // if the display frame is not defined, use the parent bounds as the buffer size.
565 return parentBounds;
566}
567
Marissa Wall61c58622018-07-18 10:12:20 -0700568// -----------------------------------------------------------------------
569
570// -----------------------------------------------------------------------
571// Interface implementation for BufferLayer
572// -----------------------------------------------------------------------
573bool BufferStateLayer::fenceHasSignaled() const {
Alec Mouri91f6df32020-01-30 08:48:58 -0800574 const bool fenceSignaled =
575 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
576 if (!fenceSignaled) {
577 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
578 TimeStats::LatchSkipReason::LateAcquire);
579 }
580
581 return fenceSignaled;
Marissa Wall61c58622018-07-18 10:12:20 -0700582}
583
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700584bool BufferStateLayer::framePresentTimeIsCurrent(nsecs_t expectedPresentTime) const {
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700585 if (!hasFrameUpdate() || isRemovedFromCurrentState()) {
586 return true;
587 }
588
Ady Abrahamf0c56492020-12-17 18:04:15 -0800589 return mCurrentState.isAutoTimestamp || mCurrentState.desiredPresentTime <= expectedPresentTime;
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700590}
591
Valerie Hau871d6352020-01-29 08:44:02 -0800592bool BufferStateLayer::onPreComposition(nsecs_t refreshStartTime) {
593 for (const auto& handle : mDrawingState.callbackHandles) {
594 handle->refreshStartTime = refreshStartTime;
595 }
596 return BufferLayer::onPreComposition(refreshStartTime);
597}
598
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700599uint64_t BufferStateLayer::getFrameNumber(nsecs_t /*expectedPresentTime*/) const {
Valerie Hau134651a2020-01-28 16:21:22 -0800600 return mDrawingState.frameNumber;
Marissa Wall61c58622018-07-18 10:12:20 -0700601}
602
Robert Carrfe1209c2020-02-11 12:25:35 -0800603/**
604 * This is the frameNumber used for deferred transaction signalling. We need to use this because
605 * of cases where we defer a transaction for a surface to itself. In the BLAST world this
606 * may not make a huge amount of sense (Why not just merge the Buffer transaction with the
607 * deferred transaction?) but this is an important legacy use case, for example moving
608 * a window at the same time it draws makes use of this kind of technique. So anyway
609 * imagine we have something like this:
610 *
611 * Transaction { // containing
612 * Buffer -> frameNumber = 2
613 * DeferTransactionUntil -> frameNumber = 2
614 * Random other stuff
615 * }
616 * Now imagine getHeadFrameNumber returned mDrawingState.mFrameNumber (or mCurrentFrameNumber).
617 * Prior to doTransaction SurfaceFlinger will call notifyAvailableFrames, but because we
618 * haven't swapped mCurrentState to mDrawingState yet we will think the sync point
619 * is not ready. So we will return false from applyPendingState and not swap
620 * current state to drawing state. But because we don't swap current state
621 * to drawing state the number will never update and we will be stuck. This way
622 * we can see we need to return the frame number for the buffer we are about
623 * to apply.
624 */
625uint64_t BufferStateLayer::getHeadFrameNumber(nsecs_t /* expectedPresentTime */) const {
626 return mCurrentState.frameNumber;
627}
628
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800629void BufferStateLayer::setAutoRefresh(bool autoRefresh) {
630 if (!mAutoRefresh.exchange(autoRefresh)) {
631 mFlinger->signalLayerUpdate();
632 }
Marissa Wall61c58622018-07-18 10:12:20 -0700633}
634
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800635bool BufferStateLayer::latchSidebandStream(bool& recomputeVisibleRegions) {
Marissa Wall61c58622018-07-18 10:12:20 -0700636 if (mSidebandStreamChanged.exchange(false)) {
637 const State& s(getDrawingState());
638 // mSidebandStreamChanged was true
Lloyd Pique0b785d82018-12-04 17:25:27 -0800639 mSidebandStream = s.sidebandStream;
Lloyd Piquede196652020-01-22 17:29:58 -0800640 editCompositionState()->sidebandStream = mSidebandStream;
Lloyd Pique0b785d82018-12-04 17:25:27 -0800641 if (mSidebandStream != nullptr) {
Marissa Wall61c58622018-07-18 10:12:20 -0700642 setTransactionFlags(eTransactionNeeded);
643 mFlinger->setTransactionFlags(eTraversalNeeded);
644 }
645 recomputeVisibleRegions = true;
646
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800647 return true;
Marissa Wall61c58622018-07-18 10:12:20 -0700648 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800649 return false;
Marissa Wall61c58622018-07-18 10:12:20 -0700650}
651
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800652bool BufferStateLayer::hasFrameUpdate() const {
Valerie Hauaa194562019-02-05 16:21:38 -0800653 const State& c(getCurrentState());
654 return mCurrentStateModified && (c.buffer != nullptr || c.bgColorLayer != nullptr);
Marissa Wall61c58622018-07-18 10:12:20 -0700655}
656
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700657status_t BufferStateLayer::updateTexImage(bool& /*recomputeVisibleRegions*/, nsecs_t latchTime,
658 nsecs_t /*expectedPresentTime*/) {
Marissa Wall61c58622018-07-18 10:12:20 -0700659 const State& s(getDrawingState());
660
661 if (!s.buffer) {
Valerie Hauaa194562019-02-05 16:21:38 -0800662 if (s.bgColorLayer) {
663 for (auto& handle : mDrawingState.callbackHandles) {
664 handle->latchTime = latchTime;
665 }
666 }
Marissa Wall61c58622018-07-18 10:12:20 -0700667 return NO_ERROR;
668 }
669
Marissa Wall5a68a772018-12-22 17:43:42 -0800670 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair935590e2021-02-10 13:05:52 -0800671 if (handle->frameNumber == mDrawingState.frameNumber) {
672 handle->latchTime = latchTime;
673 }
Marissa Wall5a68a772018-12-22 17:43:42 -0800674 }
Marissa Walle2ffb422018-10-12 11:33:52 -0700675
Vishnu Nairea0de002020-11-17 17:42:37 -0800676 const int32_t layerId = getSequence();
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000677 const uint64_t bufferId = mDrawingState.buffer->getId();
678 const uint64_t frameNumber = mDrawingState.frameNumber;
679 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
680 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
681 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
682
683 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
684 FrameTracer::FrameEvent::ACQUIRE_FENCE);
685 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
686 FrameTracer::FrameEvent::LATCH);
Marissa Wall61c58622018-07-18 10:12:20 -0700687
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000688 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
689 if (bufferSurfaceFrame != nullptr &&
690 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
691 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
692 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
693 // are processing the next state.
694 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
Ady Abraham6c1b7ac2021-03-31 16:56:03 -0700695 mDrawingState.acquireFenceTime->getSignalTime(),
696 latchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000697 }
698
Marissa Wall16c112d2019-03-20 13:21:13 -0700699 mCurrentStateModified = false;
700
Marissa Wall61c58622018-07-18 10:12:20 -0700701 return NO_ERROR;
702}
703
704status_t BufferStateLayer::updateActiveBuffer() {
705 const State& s(getDrawingState());
706
707 if (s.buffer == nullptr) {
708 return BAD_VALUE;
709 }
chaviwdf3c5e82021-01-07 13:00:37 -0800710
711 if (s.buffer != mBufferInfo.mBuffer) {
712 decrementPendingBufferCount();
713 }
Marissa Wall61c58622018-07-18 10:12:20 -0700714
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700715 mPreviousBufferId = getCurrentBufferId();
chaviwd62d3062019-09-04 14:48:02 -0700716 mBufferInfo.mBuffer = s.buffer;
717 mBufferInfo.mFence = s.acquireFence;
Marissa Wall61c58622018-07-18 10:12:20 -0700718
719 return NO_ERROR;
720}
721
Valerie Haubf784642020-01-29 07:25:23 -0800722status_t BufferStateLayer::updateFrameNumber(nsecs_t latchTime) {
Marissa Wall61c58622018-07-18 10:12:20 -0700723 // TODO(marissaw): support frame history events
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700724 mPreviousFrameNumber = mCurrentFrameNumber;
Valerie Hau134651a2020-01-28 16:21:22 -0800725 mCurrentFrameNumber = mDrawingState.frameNumber;
Valerie Haubf784642020-01-29 07:25:23 -0800726 {
727 Mutex::Autolock lock(mFrameEventHistoryMutex);
728 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
729 }
Marissa Wall61c58622018-07-18 10:12:20 -0700730 return NO_ERROR;
731}
732
Marissa Wall947d34e2019-03-29 14:03:53 -0700733void BufferStateLayer::HwcSlotGenerator::bufferErased(const client_cache_t& clientCacheId) {
734 std::lock_guard lock(mMutex);
735 if (!clientCacheId.isValid()) {
736 ALOGE("invalid process, failed to erase buffer");
737 return;
738 }
739 eraseBufferLocked(clientCacheId);
740}
741
742uint32_t BufferStateLayer::HwcSlotGenerator::getHwcCacheSlot(const client_cache_t& clientCacheId) {
743 std::lock_guard<std::mutex> lock(mMutex);
744 auto itr = mCachedBuffers.find(clientCacheId);
745 if (itr == mCachedBuffers.end()) {
746 return addCachedBuffer(clientCacheId);
747 }
748 auto& [hwcCacheSlot, counter] = itr->second;
749 counter = mCounter++;
750 return hwcCacheSlot;
751}
752
753uint32_t BufferStateLayer::HwcSlotGenerator::addCachedBuffer(const client_cache_t& clientCacheId)
754 REQUIRES(mMutex) {
755 if (!clientCacheId.isValid()) {
756 ALOGE("invalid process, returning invalid slot");
757 return BufferQueue::INVALID_BUFFER_SLOT;
758 }
759
760 ClientCache::getInstance().registerErasedRecipient(clientCacheId, wp<ErasedRecipient>(this));
761
762 uint32_t hwcCacheSlot = getFreeHwcCacheSlot();
763 mCachedBuffers[clientCacheId] = {hwcCacheSlot, mCounter++};
764 return hwcCacheSlot;
765}
766
767uint32_t BufferStateLayer::HwcSlotGenerator::getFreeHwcCacheSlot() REQUIRES(mMutex) {
768 if (mFreeHwcCacheSlots.empty()) {
769 evictLeastRecentlyUsed();
770 }
771
772 uint32_t hwcCacheSlot = mFreeHwcCacheSlots.top();
773 mFreeHwcCacheSlots.pop();
774 return hwcCacheSlot;
775}
776
777void BufferStateLayer::HwcSlotGenerator::evictLeastRecentlyUsed() REQUIRES(mMutex) {
778 uint64_t minCounter = UINT_MAX;
779 client_cache_t minClientCacheId = {};
780 for (const auto& [clientCacheId, slotCounter] : mCachedBuffers) {
781 const auto& [hwcCacheSlot, counter] = slotCounter;
782 if (counter < minCounter) {
783 minCounter = counter;
784 minClientCacheId = clientCacheId;
785 }
786 }
787 eraseBufferLocked(minClientCacheId);
788
789 ClientCache::getInstance().unregisterErasedRecipient(minClientCacheId, this);
790}
791
792void BufferStateLayer::HwcSlotGenerator::eraseBufferLocked(const client_cache_t& clientCacheId)
793 REQUIRES(mMutex) {
794 auto itr = mCachedBuffers.find(clientCacheId);
795 if (itr == mCachedBuffers.end()) {
796 return;
797 }
798 auto& [hwcCacheSlot, counter] = itr->second;
799
800 // TODO send to hwc cache and resources
801
802 mFreeHwcCacheSlots.push(hwcCacheSlot);
803 mCachedBuffers.erase(clientCacheId);
804}
chaviw4244e032019-09-04 11:27:49 -0700805
806void BufferStateLayer::gatherBufferInfo() {
chaviwdebadb82020-03-26 14:57:24 -0700807 BufferLayer::gatherBufferInfo();
chaviw4244e032019-09-04 11:27:49 -0700808
chaviwdebadb82020-03-26 14:57:24 -0700809 const State& s(getDrawingState());
chaviw4244e032019-09-04 11:27:49 -0700810 mBufferInfo.mDesiredPresentTime = s.desiredPresentTime;
811 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(s.acquireFence);
812 mBufferInfo.mFence = s.acquireFence;
chaviw766c9c52021-02-10 17:36:47 -0800813 mBufferInfo.mTransform = s.bufferTransform;
chaviw4244e032019-09-04 11:27:49 -0700814 mBufferInfo.mDataspace = translateDataspace(s.dataspace);
815 mBufferInfo.mCrop = computeCrop(s);
816 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
817 mBufferInfo.mSurfaceDamage = s.surfaceDamageRegion;
818 mBufferInfo.mHdrMetadata = s.hdrMetadata;
819 mBufferInfo.mApi = s.api;
chaviw4244e032019-09-04 11:27:49 -0700820 mBufferInfo.mTransformToDisplayInverse = s.transformToDisplayInverse;
chaviwf83ce182019-09-12 14:43:08 -0700821 mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(s.clientCacheId);
chaviw4244e032019-09-04 11:27:49 -0700822}
823
Robert Carr916b0362020-10-06 13:53:03 -0700824uint32_t BufferStateLayer::getEffectiveScalingMode() const {
825 return NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
826}
827
chaviw4244e032019-09-04 11:27:49 -0700828Rect BufferStateLayer::computeCrop(const State& s) {
829 if (s.crop.isEmpty() && s.buffer) {
830 return s.buffer->getBounds();
831 } else if (s.buffer) {
832 Rect crop = s.crop;
833 crop.left = std::max(crop.left, 0);
834 crop.top = std::max(crop.top, 0);
835 uint32_t bufferWidth = s.buffer->getWidth();
836 uint32_t bufferHeight = s.buffer->getHeight();
837 if (bufferHeight <= std::numeric_limits<int32_t>::max() &&
838 bufferWidth <= std::numeric_limits<int32_t>::max()) {
839 crop.right = std::min(crop.right, static_cast<int32_t>(bufferWidth));
840 crop.bottom = std::min(crop.bottom, static_cast<int32_t>(bufferHeight));
841 }
842 if (!crop.isValid()) {
843 // Crop rect is out of bounds, return whole buffer
844 return s.buffer->getBounds();
845 }
846 return crop;
847 }
848 return s.crop;
849}
850
chaviwb4c6e582019-08-16 14:35:07 -0700851sp<Layer> BufferStateLayer::createClone() {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700852 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, 0, 0, LayerMetadata());
chaviwb4c6e582019-08-16 14:35:07 -0700853 args.textureName = mTextureName;
Lloyd Pique1c3a5eb2019-10-03 13:07:08 -0700854 sp<BufferStateLayer> layer = mFlinger->getFactory().createBufferStateLayer(args);
chaviwb4c6e582019-08-16 14:35:07 -0700855 layer->mHwcSlotGenerator = mHwcSlotGenerator;
856 layer->setInitialValuesForClone(this);
857 return layer;
858}
Valerie Hau92bf5482020-02-10 09:49:08 -0800859
Vishnu Naire7f79c52020-10-29 14:45:03 -0700860bool BufferStateLayer::bufferNeedsFiltering() const {
861 const State& s(getDrawingState());
862 if (!s.buffer) {
863 return false;
864 }
865
866 uint32_t bufferWidth = s.buffer->width;
867 uint32_t bufferHeight = s.buffer->height;
868
869 // Undo any transformations on the buffer and return the result.
chaviw766c9c52021-02-10 17:36:47 -0800870 if (s.bufferTransform & ui::Transform::ROT_90) {
Vishnu Naire7f79c52020-10-29 14:45:03 -0700871 std::swap(bufferWidth, bufferHeight);
872 }
873
874 if (s.transformToDisplayInverse) {
875 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
876 if (invTransform & ui::Transform::ROT_90) {
877 std::swap(bufferWidth, bufferHeight);
878 }
879 }
880
881 const Rect layerSize{getBounds()};
882 return layerSize.width() != bufferWidth || layerSize.height() != bufferHeight;
883}
Robert Carr7121caf2020-12-15 13:07:32 -0800884
Robert Carr7121caf2020-12-15 13:07:32 -0800885void BufferStateLayer::decrementPendingBufferCount() {
Vishnu Nair8eda69e2021-02-26 10:42:10 -0800886 int32_t pendingBuffers = --mPendingBufferTransactions;
887 tracePendingBufferCount(pendingBuffers);
Robert Carr7121caf2020-12-15 13:07:32 -0800888}
889
Vishnu Nair8eda69e2021-02-26 10:42:10 -0800890void BufferStateLayer::tracePendingBufferCount(int32_t pendingBuffers) {
891 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
Robert Carr7121caf2020-12-15 13:07:32 -0800892}
893
Vishnu Nair1506b182021-02-22 14:35:15 -0800894void BufferStateLayer::bufferMayChange(sp<GraphicBuffer>& newBuffer) {
895 if (mDrawingState.buffer != nullptr && mDrawingState.buffer != mBufferInfo.mBuffer &&
896 newBuffer != mDrawingState.buffer) {
Robert Carr7121caf2020-12-15 13:07:32 -0800897 // If we are about to update mDrawingState.buffer but it has not yet latched
Vishnu Nair1506b182021-02-22 14:35:15 -0800898 // then we will drop a buffer and should decrement the pending buffer count and
899 // call any release buffer callbacks if set.
900 callReleaseBufferCallback(mDrawingState.releaseBufferListener, mDrawingState.buffer,
901 mDrawingState.acquireFence);
Robert Carr7121caf2020-12-15 13:07:32 -0800902 decrementPendingBufferCount();
903 }
Robert Carr7121caf2020-12-15 13:07:32 -0800904}
905
chaviw39d01472021-04-08 14:26:24 -0500906/*
907 * We don't want to send the layer's transform to input, but rather the
908 * parent's transform. This is because BufferStateLayer's transform is
909 * information about how the buffer is placed on screen. The parent's
910 * transform makes more sense to send since it's information about how the
911 * layer is placed on screen. This transform is used by input to determine
912 * how to go from screen space back to window space.
913 */
914ui::Transform BufferStateLayer::getInputTransform() const {
915 sp<Layer> parent = mDrawingParent.promote();
916 if (parent == nullptr) {
917 return ui::Transform();
918 }
919
920 return parent->getTransform();
921}
922
923/**
924 * Similar to getInputTransform, we need to update the bounds to include the transform.
925 * This is because bounds for BSL doesn't include buffer transform, where the input assumes
926 * that's already included.
927 */
928Rect BufferStateLayer::getInputBounds() const {
929 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
930 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
931 return bufferBounds;
932 }
933 return mDrawingState.transform.transform(bufferBounds);
934}
935
Marissa Wall61c58622018-07-18 10:12:20 -0700936} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800937
938// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100939#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"