blob: a2915c903fea7a67cb719f5809880a6e4b594c4e [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()) {
Alec Mouria90a5702021-04-16 16:36:21 +000074 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
75 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFence);
Alec Mouri4545a8a2019-08-08 20:05:32 -070076 }
77}
78
Robert Carr8d958532020-11-10 14:09:16 -080079status_t BufferStateLayer::addReleaseFence(const sp<CallbackHandle>& ch,
80 const sp<Fence>& fence) {
81 if (ch == nullptr) {
82 return OK;
83 }
Vishnu Nair1506b182021-02-22 14:35:15 -080084 ch->previousBufferId = mPreviousBufferId;
Robert Carr8d958532020-11-10 14:09:16 -080085 if (!ch->previousReleaseFence.get()) {
86 ch->previousReleaseFence = fence;
87 return OK;
88 }
89
90 // Below logic is lifted from ConsumerBase.cpp:
91 // Check status of fences first because merging is expensive.
92 // Merging an invalid fence with any other fence results in an
93 // invalid fence.
94 auto currentStatus = ch->previousReleaseFence->getStatus();
95 if (currentStatus == Fence::Status::Invalid) {
96 ALOGE("Existing fence has invalid state, layer: %s", mName.c_str());
97 return BAD_VALUE;
98 }
99
100 auto incomingStatus = fence->getStatus();
101 if (incomingStatus == Fence::Status::Invalid) {
102 ALOGE("New fence has invalid state, layer: %s", mName.c_str());
103 ch->previousReleaseFence = fence;
104 return BAD_VALUE;
105 }
106
107 // If both fences are signaled or both are unsignaled, we need to merge
108 // them to get an accurate timestamp.
109 if (currentStatus == incomingStatus) {
110 char fenceName[32] = {};
111 snprintf(fenceName, 32, "%.28s", mName.c_str());
112 sp<Fence> mergedFence = Fence::merge(
113 fenceName, ch->previousReleaseFence, fence);
114 if (!mergedFence.get()) {
115 ALOGE("failed to merge release fences, layer: %s", mName.c_str());
116 // synchronization is broken, the best we can do is hope fences
117 // signal in order so the new fence will act like a union
118 ch->previousReleaseFence = fence;
119 return BAD_VALUE;
120 }
121 ch->previousReleaseFence = mergedFence;
122 } else if (incomingStatus == Fence::Status::Unsignaled) {
123 // If one fence has signaled and the other hasn't, the unsignaled
124 // fence will approximately correspond with the correct timestamp.
125 // There's a small race if both fences signal at about the same time
126 // and their statuses are retrieved with unfortunate timing. However,
127 // by this point, they will have both signaled and only the timestamp
128 // will be slightly off; any dependencies after this point will
129 // already have been met.
130 ch->previousReleaseFence = fence;
131 }
132 // else if (currentStatus == Fence::Status::Unsignaled) is a no-op.
133
134 return OK;
135}
136
Marissa Wall61c58622018-07-18 10:12:20 -0700137// -----------------------------------------------------------------------
138// Interface implementation for Layer
139// -----------------------------------------------------------------------
Marissa Wallfda30bb2018-10-12 11:34:28 -0700140void BufferStateLayer::onLayerDisplayed(const sp<Fence>& releaseFence) {
Robert Carr8d958532020-11-10 14:09:16 -0800141 if (!releaseFence->isValid()) {
142 return;
143 }
Marissa Wall5a68a772018-12-22 17:43:42 -0800144 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
145 // buffer that was presented on this layer. The first transaction that came in this frame that
146 // replaced the previous buffer on this layer needs this release fence, because the fence will
147 // let the client know when that previous buffer is removed from the screen.
148 //
149 // Every other transaction on this layer does not need a release fence because no other
150 // Transactions that were set on this layer this frame are going to have their preceeding buffer
151 // removed from the display this frame.
152 //
153 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
154 // buffer so it doesn't need a previous release fence because the layer still needs the previous
155 // buffer. The second transaction contains a buffer so it needs a previous release fence because
156 // the previous buffer will be released this frame. The third transaction also contains a
157 // buffer. It replaces the buffer in the second transaction. The buffer in the second
158 // transaction will now no longer be presented so it is released immediately and the third
159 // transaction doesn't need a previous release fence.
Robert Carr8d958532020-11-10 14:09:16 -0800160 sp<CallbackHandle> ch;
Marissa Wall5a68a772018-12-22 17:43:42 -0800161 for (auto& handle : mDrawingState.callbackHandles) {
162 if (handle->releasePreviousBuffer) {
Robert Carr8d958532020-11-10 14:09:16 -0800163 ch = handle;
Marissa Wall5a68a772018-12-22 17:43:42 -0800164 break;
165 }
166 }
Robert Carr8d958532020-11-10 14:09:16 -0800167 auto status = addReleaseFence(ch, releaseFence);
168 if (status != OK) {
169 ALOGE("Failed to add release fence for layer %s", getName().c_str());
170 }
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700171
Valerie Haubf784642020-01-29 07:25:23 -0800172 mPreviousReleaseFence = releaseFence;
173
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700174 // Prevent tracing the same release multiple times.
175 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700176 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
177 }
Marissa Wall61c58622018-07-18 10:12:20 -0700178}
179
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100180void BufferStateLayer::onSurfaceFrameCreated(
181 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasand17c7da2021-03-05 20:43:32 +0000182 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
183 // Too many SurfaceFrames pending classification. The front of the deque is probably not
184 // tracked by FrameTimeline and will never be presented. This will only result in a memory
185 // leak.
186 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
187 mName.c_str());
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000188 std::string miniDump = mPendingJankClassifications.front()->miniDump();
189 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
Adithya Srinivasand17c7da2021-03-05 20:43:32 +0000190 mPendingJankClassifications.pop_front();
191 }
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100192 mPendingJankClassifications.emplace_back(surfaceFrame);
193}
194
Valerie Haubf784642020-01-29 07:25:23 -0800195void BufferStateLayer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700196 for (const auto& handle : mDrawingState.callbackHandles) {
197 handle->transformHint = mTransformHint;
Valerie Hau871d6352020-01-29 08:44:02 -0800198 handle->dequeueReadyTime = dequeueReadyTime;
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700199 }
200
Vishnu Nair1506b182021-02-22 14:35:15 -0800201 // If there are multiple transactions in this frame, set the previous id on the earliest
202 // transacton. We don't need to pass in the released buffer id to multiple transactions.
203 // The buffer id does not have to correspond to any particular transaction as long as the
204 // listening end point is the same but the client expects the first transaction callback that
205 // replaces the presented buffer to contain the release fence. This follows the same logic.
206 // see BufferStateLayer::onLayerDisplayed.
207 for (auto& handle : mDrawingState.callbackHandles) {
208 if (handle->releasePreviousBuffer) {
209 handle->previousBufferId = mPreviousBufferId;
210 break;
211 }
212 }
213
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100214 std::vector<JankData> jankData;
215 jankData.reserve(mPendingJankClassifications.size());
216 while (!mPendingJankClassifications.empty()
217 && mPendingJankClassifications.front()->getJankType()) {
218 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
219 mPendingJankClassifications.front();
220 mPendingJankClassifications.pop_front();
221 jankData.emplace_back(
222 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
223 }
224
Robert Carr9a803c32021-01-14 16:57:58 -0800225 mFlinger->getTransactionCallbackInvoker().finalizePendingCallbackHandles(
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100226 mDrawingState.callbackHandles, jankData);
Marissa Wall5a68a772018-12-22 17:43:42 -0800227
228 mDrawingState.callbackHandles = {};
Valerie Haubf784642020-01-29 07:25:23 -0800229
230 const sp<Fence>& releaseFence(mPreviousReleaseFence);
231 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(releaseFence);
232 {
233 Mutex::Autolock lock(mFrameEventHistoryMutex);
234 if (mPreviousFrameNumber != 0) {
235 mFrameEventHistory.addRelease(mPreviousFrameNumber, dequeueReadyTime,
236 std::move(releaseFenceTime));
237 }
238 }
Marissa Wall61c58622018-07-18 10:12:20 -0700239}
240
Valerie Hau871d6352020-01-29 08:44:02 -0800241void BufferStateLayer::finalizeFrameEventHistory(const std::shared_ptr<FenceTime>& glDoneFence,
242 const CompositorTiming& compositorTiming) {
243 for (const auto& handle : mDrawingState.callbackHandles) {
244 handle->gpuCompositionDoneFence = glDoneFence;
245 handle->compositorTiming = compositorTiming;
246 }
247}
248
Marissa Walle2ffb422018-10-12 11:33:52 -0700249bool BufferStateLayer::willPresentCurrentTransaction() const {
250 // Returns true if the most recent Transaction applied to CurrentState will be presented.
Robert Carr321e83c2019-08-19 15:49:30 -0700251 return (getSidebandStreamChanged() || getAutoRefresh() ||
Valerie Hauaa194562019-02-05 16:21:38 -0800252 (mCurrentState.modified &&
chaviw8ba8b072021-01-25 14:55:46 -0800253 (mCurrentState.buffer != nullptr || mCurrentState.bgColorLayer != nullptr)));
Marissa Wall61c58622018-07-18 10:12:20 -0700254}
255
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000256Rect BufferStateLayer::getCrop(const Layer::State& s) const {
257 return s.crop;
Marissa Wall61c58622018-07-18 10:12:20 -0700258}
259
260bool BufferStateLayer::setTransform(uint32_t transform) {
chaviw766c9c52021-02-10 17:36:47 -0800261 if (mCurrentState.bufferTransform == transform) return false;
262 mCurrentState.bufferTransform = transform;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800263 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700264 setTransactionFlags(eTransactionNeeded);
265 return true;
266}
267
268bool BufferStateLayer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800269 if (mCurrentState.transformToDisplayInverse == transformToDisplayInverse) return false;
270 mCurrentState.sequence++;
271 mCurrentState.transformToDisplayInverse = transformToDisplayInverse;
272 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700273 setTransactionFlags(eTransactionNeeded);
274 return true;
275}
276
277bool BufferStateLayer::setCrop(const Rect& crop) {
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000278 if (mCurrentState.crop == crop) return false;
279 mCurrentState.sequence++;
280 mCurrentState.crop = crop;
Marissa Wall290ad082019-03-06 13:23:47 -0800281
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800282 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700283 setTransactionFlags(eTransactionNeeded);
284 return true;
285}
286
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000287bool BufferStateLayer::setMatrix(const layer_state_t::matrix22_t& matrix,
288 bool allowNonRectPreservingTransforms) {
289 if (mCurrentState.transform.dsdx() == matrix.dsdx &&
290 mCurrentState.transform.dtdy() == matrix.dtdy &&
291 mCurrentState.transform.dtdx() == matrix.dtdx &&
292 mCurrentState.transform.dsdy() == matrix.dsdy) {
Marissa Wall861616d2018-10-22 12:52:23 -0700293 return false;
294 }
295
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000296 ui::Transform t;
297 t.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
298
299 if (!allowNonRectPreservingTransforms && !t.preserveRects()) {
300 ALOGW("Attempt to set rotation matrix without permission ACCESS_SURFACE_FLINGER nor "
301 "ROTATE_SURFACE_FLINGER ignored");
302 return false;
Marissa Wall861616d2018-10-22 12:52:23 -0700303 }
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000304
305 mCurrentState.transform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
chaviw9a93ea62021-03-11 16:44:42 -0600306
307 mCurrentState.sequence++;
308 mCurrentState.modified = true;
309 setTransactionFlags(eTransactionNeeded);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000310
311 return true;
312}
313
314bool BufferStateLayer::setPosition(float x, float y) {
315 if (mCurrentState.transform.tx() == x && mCurrentState.transform.ty() == y) {
316 return false;
317 }
318
319 mCurrentState.transform.set(x, y);
320
321 mCurrentState.sequence++;
322 mCurrentState.modified = true;
323 setTransactionFlags(eTransactionNeeded);
324
Marissa Wall861616d2018-10-22 12:52:23 -0700325 return true;
326}
327
Valerie Hau871d6352020-01-29 08:44:02 -0800328bool BufferStateLayer::addFrameEvent(const sp<Fence>& acquireFence, nsecs_t postedTime,
329 nsecs_t desiredPresentTime) {
Valerie Haubf784642020-01-29 07:25:23 -0800330 Mutex::Autolock lock(mFrameEventHistoryMutex);
331 mAcquireTimeline.updateSignalTimes();
332 std::shared_ptr<FenceTime> acquireFenceTime =
333 std::make_shared<FenceTime>((acquireFence ? acquireFence : Fence::NO_FENCE));
334 NewFrameEventsEntry newTimestamps = {mCurrentState.frameNumber, postedTime, desiredPresentTime,
335 acquireFenceTime};
Valerie Hau871d6352020-01-29 08:44:02 -0800336 mFrameEventHistory.setProducerWantsEvents();
Valerie Haubf784642020-01-29 07:25:23 -0800337 mFrameEventHistory.addQueue(newTimestamps);
338 return true;
339}
340
Alec Mouria90a5702021-04-16 16:36:21 +0000341bool BufferStateLayer::setBuffer(const std::shared_ptr<renderengine::ExternalTexture>& buffer,
342 const sp<Fence>& acquireFence, nsecs_t postTime,
343 nsecs_t desiredPresentTime, bool isAutoTimestamp,
Vishnu Nairadf632b2021-01-07 14:05:08 -0800344 const client_cache_t& clientCacheId, uint64_t frameNumber,
Vishnu Nair1506b182021-02-22 14:35:15 -0800345 std::optional<nsecs_t> dequeueTime, const FrameTimelineInfo& info,
346 const sp<ITransactionCompletedListener>& releaseBufferListener) {
Robert Carr0c1966e2020-10-19 12:12:08 -0700347 ATRACE_CALL();
348
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800349 if (mCurrentState.buffer) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700350 mReleasePreviousBuffer = true;
Alec Mouria90a5702021-04-16 16:36:21 +0000351 if (!mDrawingState.buffer ||
352 mCurrentState.buffer->getBuffer() != mDrawingState.buffer->getBuffer()) {
Robert Carr7121caf2020-12-15 13:07:32 -0800353 // If mCurrentState has a buffer, and we are about to update again
354 // before swapping to drawing state, then the first buffer will be
Vishnu Nair1506b182021-02-22 14:35:15 -0800355 // dropped and we should decrement the pending buffer count and
356 // call any release buffer callbacks if set.
Alec Mouria90a5702021-04-16 16:36:21 +0000357 callReleaseBufferCallback(mCurrentState.releaseBufferListener,
358 mCurrentState.buffer->getBuffer(),
Vishnu Nair1506b182021-02-22 14:35:15 -0800359 mCurrentState.acquireFence);
Robert Carr7121caf2020-12-15 13:07:32 -0800360 decrementPendingBufferCount();
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000361 if (mCurrentState.bufferSurfaceFrameTX != nullptr) {
362 addSurfaceFrameDroppedForBuffer(mCurrentState.bufferSurfaceFrameTX);
363 mCurrentState.bufferSurfaceFrameTX.reset();
364 }
Robert Carr7121caf2020-12-15 13:07:32 -0800365 }
Marissa Wallfda30bb2018-10-12 11:34:28 -0700366 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -0700367 mCurrentState.frameNumber = frameNumber;
Vishnu Nair1506b182021-02-22 14:35:15 -0800368 mCurrentState.releaseBufferListener = releaseBufferListener;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800369 mCurrentState.buffer = buffer;
Marissa Wall947d34e2019-03-29 14:03:53 -0700370 mCurrentState.clientCacheId = clientCacheId;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800371 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700372 setTransactionFlags(eTransactionNeeded);
Ady Abraham09bd3922019-04-08 10:44:56 -0700373
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800374 const int32_t layerId = getSequence();
Valerie Hau134651a2020-01-28 16:21:22 -0800375 mFlinger->mTimeStats->setPostTime(layerId, mCurrentState.frameNumber, getName().c_str(),
Alec Mouri9a29e672020-09-14 12:39:14 -0700376 mOwnerUid, postTime);
chaviwfa67b552019-08-12 16:51:55 -0700377 mCurrentState.desiredPresentTime = desiredPresentTime;
Ady Abrahamf0c56492020-12-17 18:04:15 -0800378 mCurrentState.isAutoTimestamp = isAutoTimestamp;
Ady Abraham09bd3922019-04-08 10:44:56 -0700379
Ady Abrahamb7f15562021-03-15 18:34:08 -0700380 const nsecs_t presentTime = [&] {
381 if (!isAutoTimestamp) return desiredPresentTime;
382
383 const auto prediction =
384 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
385 if (prediction.has_value()) return prediction->presentTime;
386
387 return static_cast<nsecs_t>(0);
388 }();
389 mFlinger->mScheduler->recordLayerHistory(this, presentTime,
Ady Abraham5def7332020-05-29 16:13:47 -0700390 LayerHistory::LayerUpdateType::Buffer);
Ady Abraham09bd3922019-04-08 10:44:56 -0700391
Ady Abrahamf0c56492020-12-17 18:04:15 -0800392 addFrameEvent(acquireFence, postTime, isAutoTimestamp ? 0 : desiredPresentTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000393
Adithya Srinivasan891004e2021-02-12 20:20:47 +0000394 setFrameTimelineVsyncForBufferTransaction(info, postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000395
Alec Mouria90a5702021-04-16 16:36:21 +0000396 if (buffer && dequeueTime && *dequeueTime != 0) {
397 const uint64_t bufferId = buffer->getBuffer()->getId();
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000398 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
399 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
400 FrameTracer::FrameEvent::DEQUEUE);
401 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
402 FrameTracer::FrameEvent::QUEUE);
403 }
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000404
Alec Mouria90a5702021-04-16 16:36:21 +0000405 mCurrentState.width = mCurrentState.buffer->getBuffer()->getWidth();
406 mCurrentState.height = mCurrentState.buffer->getBuffer()->getHeight();
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000407
Marissa Wall61c58622018-07-18 10:12:20 -0700408 return true;
409}
410
411bool BufferStateLayer::setAcquireFence(const sp<Fence>& fence) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800412 mCurrentState.acquireFence = fence;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -0700413 mCurrentState.acquireFenceTime = std::make_unique<FenceTime>(fence);
414
415 // The acquire fences of BufferStateLayers have already signaled before they are set
416 mCallbackHandleAcquireTime = mCurrentState.acquireFenceTime->getSignalTime();
417
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800418 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700419 setTransactionFlags(eTransactionNeeded);
420 return true;
421}
422
423bool BufferStateLayer::setDataspace(ui::Dataspace dataspace) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800424 if (mCurrentState.dataspace == dataspace) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800425 mCurrentState.dataspace = dataspace;
426 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700427 setTransactionFlags(eTransactionNeeded);
428 return true;
429}
430
431bool BufferStateLayer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800432 if (mCurrentState.hdrMetadata == hdrMetadata) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800433 mCurrentState.hdrMetadata = hdrMetadata;
434 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700435 setTransactionFlags(eTransactionNeeded);
436 return true;
437}
438
439bool BufferStateLayer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800440 mCurrentState.surfaceDamageRegion = surfaceDamage;
441 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700442 setTransactionFlags(eTransactionNeeded);
443 return true;
444}
445
446bool BufferStateLayer::setApi(int32_t api) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800447 if (mCurrentState.api == api) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800448 mCurrentState.api = api;
449 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700450 setTransactionFlags(eTransactionNeeded);
451 return true;
452}
453
454bool BufferStateLayer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800455 if (mCurrentState.sidebandStream == sidebandStream) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800456 mCurrentState.sidebandStream = sidebandStream;
457 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700458 setTransactionFlags(eTransactionNeeded);
459
460 if (!mSidebandStreamChanged.exchange(true)) {
461 // mSidebandStreamChanged was false
462 mFlinger->signalLayerUpdate();
463 }
464 return true;
465}
466
Marissa Walle2ffb422018-10-12 11:33:52 -0700467bool BufferStateLayer::setTransactionCompletedListeners(
468 const std::vector<sp<CallbackHandle>>& handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700469 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
Marissa Walle2ffb422018-10-12 11:33:52 -0700470 if (handles.empty()) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700471 mReleasePreviousBuffer = false;
Marissa Walle2ffb422018-10-12 11:33:52 -0700472 return false;
473 }
474
475 const bool willPresent = willPresentCurrentTransaction();
476
477 for (const auto& handle : handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700478 // If this transaction set a buffer on this layer, release its previous buffer
479 handle->releasePreviousBuffer = mReleasePreviousBuffer;
480
Marissa Walle2ffb422018-10-12 11:33:52 -0700481 // If this layer will be presented in this frame
482 if (willPresent) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700483 // If this transaction set an acquire fence on this layer, set its acquire time
484 handle->acquireTime = mCallbackHandleAcquireTime;
Vishnu Nair935590e2021-02-10 13:05:52 -0800485 handle->frameNumber = mCurrentState.frameNumber;
Marissa Wallfda30bb2018-10-12 11:34:28 -0700486
Marissa Walle2ffb422018-10-12 11:33:52 -0700487 // Notify the transaction completed thread that there is a pending latched callback
488 // handle
Robert Carr9a803c32021-01-14 16:57:58 -0800489 mFlinger->getTransactionCallbackInvoker().registerPendingCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700490
491 // Store so latched time and release fence can be set
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800492 mCurrentState.callbackHandles.push_back(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700493
494 } else { // If this layer will NOT need to be relatched and presented this frame
495 // Notify the transaction completed thread this handle is done
Robert Carr9a803c32021-01-14 16:57:58 -0800496 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700497 }
498 }
499
Marissa Wallfda30bb2018-10-12 11:34:28 -0700500 mReleasePreviousBuffer = false;
501 mCallbackHandleAcquireTime = -1;
502
Marissa Walle2ffb422018-10-12 11:33:52 -0700503 return willPresent;
504}
505
Marissa Wall61c58622018-07-18 10:12:20 -0700506bool BufferStateLayer::setTransparentRegionHint(const Region& transparent) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800507 mCurrentState.transparentRegionHint = transparent;
508 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700509 setTransactionFlags(eTransactionNeeded);
510 return true;
511}
512
Marissa Wall861616d2018-10-22 12:52:23 -0700513Rect BufferStateLayer::getBufferSize(const State& s) const {
514 // for buffer state layers we use the display frame size as the buffer size.
515 if (getActiveWidth(s) < UINT32_MAX && getActiveHeight(s) < UINT32_MAX) {
516 return Rect(getActiveWidth(s), getActiveHeight(s));
Marissa Wall61c58622018-07-18 10:12:20 -0700517 }
518
chaviw7e72caf2020-12-02 16:50:43 -0800519 if (mBufferInfo.mBuffer == nullptr) {
520 return Rect::INVALID_RECT;
521 }
522
Marissa Wall861616d2018-10-22 12:52:23 -0700523 // if the display frame is not defined, use the parent bounds as the buffer size.
524 const auto& p = mDrawingParent.promote();
525 if (p != nullptr) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800526 Rect parentBounds = Rect(p->getBounds(Region()));
Marissa Wall861616d2018-10-22 12:52:23 -0700527 if (!parentBounds.isEmpty()) {
528 return parentBounds;
529 }
530 }
531
Marissa Wall861616d2018-10-22 12:52:23 -0700532 return Rect::INVALID_RECT;
Marissa Wall61c58622018-07-18 10:12:20 -0700533}
Vishnu Nair4351ad52019-02-11 14:13:02 -0800534
535FloatRect BufferStateLayer::computeSourceBounds(const FloatRect& parentBounds) const {
536 const State& s(getDrawingState());
537 // for buffer state layers we use the display frame size as the buffer size.
538 if (getActiveWidth(s) < UINT32_MAX && getActiveHeight(s) < UINT32_MAX) {
539 return FloatRect(0, 0, getActiveWidth(s), getActiveHeight(s));
540 }
541
542 // if the display frame is not defined, use the parent bounds as the buffer size.
543 return parentBounds;
544}
545
Marissa Wall61c58622018-07-18 10:12:20 -0700546// -----------------------------------------------------------------------
547
548// -----------------------------------------------------------------------
549// Interface implementation for BufferLayer
550// -----------------------------------------------------------------------
551bool BufferStateLayer::fenceHasSignaled() const {
Alec Mouri91f6df32020-01-30 08:48:58 -0800552 const bool fenceSignaled =
553 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
554 if (!fenceSignaled) {
555 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
556 TimeStats::LatchSkipReason::LateAcquire);
557 }
558
559 return fenceSignaled;
Marissa Wall61c58622018-07-18 10:12:20 -0700560}
561
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700562bool BufferStateLayer::framePresentTimeIsCurrent(nsecs_t expectedPresentTime) const {
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700563 if (!hasFrameUpdate() || isRemovedFromCurrentState()) {
564 return true;
565 }
566
Ady Abrahamf0c56492020-12-17 18:04:15 -0800567 return mCurrentState.isAutoTimestamp || mCurrentState.desiredPresentTime <= expectedPresentTime;
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700568}
569
Valerie Hau871d6352020-01-29 08:44:02 -0800570bool BufferStateLayer::onPreComposition(nsecs_t refreshStartTime) {
571 for (const auto& handle : mDrawingState.callbackHandles) {
572 handle->refreshStartTime = refreshStartTime;
573 }
574 return BufferLayer::onPreComposition(refreshStartTime);
575}
576
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700577uint64_t BufferStateLayer::getFrameNumber(nsecs_t /*expectedPresentTime*/) const {
Valerie Hau134651a2020-01-28 16:21:22 -0800578 return mDrawingState.frameNumber;
Marissa Wall61c58622018-07-18 10:12:20 -0700579}
580
Robert Carrfe1209c2020-02-11 12:25:35 -0800581/**
582 * This is the frameNumber used for deferred transaction signalling. We need to use this because
583 * of cases where we defer a transaction for a surface to itself. In the BLAST world this
584 * may not make a huge amount of sense (Why not just merge the Buffer transaction with the
585 * deferred transaction?) but this is an important legacy use case, for example moving
586 * a window at the same time it draws makes use of this kind of technique. So anyway
587 * imagine we have something like this:
588 *
589 * Transaction { // containing
590 * Buffer -> frameNumber = 2
591 * DeferTransactionUntil -> frameNumber = 2
592 * Random other stuff
593 * }
594 * Now imagine getHeadFrameNumber returned mDrawingState.mFrameNumber (or mCurrentFrameNumber).
595 * Prior to doTransaction SurfaceFlinger will call notifyAvailableFrames, but because we
596 * haven't swapped mCurrentState to mDrawingState yet we will think the sync point
597 * is not ready. So we will return false from applyPendingState and not swap
598 * current state to drawing state. But because we don't swap current state
599 * to drawing state the number will never update and we will be stuck. This way
600 * we can see we need to return the frame number for the buffer we are about
601 * to apply.
602 */
603uint64_t BufferStateLayer::getHeadFrameNumber(nsecs_t /* expectedPresentTime */) const {
604 return mCurrentState.frameNumber;
605}
606
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800607void BufferStateLayer::setAutoRefresh(bool autoRefresh) {
608 if (!mAutoRefresh.exchange(autoRefresh)) {
609 mFlinger->signalLayerUpdate();
610 }
Marissa Wall61c58622018-07-18 10:12:20 -0700611}
612
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800613bool BufferStateLayer::latchSidebandStream(bool& recomputeVisibleRegions) {
Marissa Wall61c58622018-07-18 10:12:20 -0700614 if (mSidebandStreamChanged.exchange(false)) {
615 const State& s(getDrawingState());
616 // mSidebandStreamChanged was true
Lloyd Pique0b785d82018-12-04 17:25:27 -0800617 mSidebandStream = s.sidebandStream;
Lloyd Piquede196652020-01-22 17:29:58 -0800618 editCompositionState()->sidebandStream = mSidebandStream;
Lloyd Pique0b785d82018-12-04 17:25:27 -0800619 if (mSidebandStream != nullptr) {
Marissa Wall61c58622018-07-18 10:12:20 -0700620 setTransactionFlags(eTransactionNeeded);
621 mFlinger->setTransactionFlags(eTraversalNeeded);
622 }
623 recomputeVisibleRegions = true;
624
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800625 return true;
Marissa Wall61c58622018-07-18 10:12:20 -0700626 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800627 return false;
Marissa Wall61c58622018-07-18 10:12:20 -0700628}
629
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800630bool BufferStateLayer::hasFrameUpdate() const {
Valerie Hauaa194562019-02-05 16:21:38 -0800631 const State& c(getCurrentState());
632 return mCurrentStateModified && (c.buffer != nullptr || c.bgColorLayer != nullptr);
Marissa Wall61c58622018-07-18 10:12:20 -0700633}
634
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700635status_t BufferStateLayer::updateTexImage(bool& /*recomputeVisibleRegions*/, nsecs_t latchTime,
636 nsecs_t /*expectedPresentTime*/) {
Marissa Wall61c58622018-07-18 10:12:20 -0700637 const State& s(getDrawingState());
638
639 if (!s.buffer) {
Valerie Hauaa194562019-02-05 16:21:38 -0800640 if (s.bgColorLayer) {
641 for (auto& handle : mDrawingState.callbackHandles) {
642 handle->latchTime = latchTime;
643 }
644 }
Marissa Wall61c58622018-07-18 10:12:20 -0700645 return NO_ERROR;
646 }
647
Marissa Wall5a68a772018-12-22 17:43:42 -0800648 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair935590e2021-02-10 13:05:52 -0800649 if (handle->frameNumber == mDrawingState.frameNumber) {
650 handle->latchTime = latchTime;
651 }
Marissa Wall5a68a772018-12-22 17:43:42 -0800652 }
Marissa Walle2ffb422018-10-12 11:33:52 -0700653
Vishnu Nairea0de002020-11-17 17:42:37 -0800654 const int32_t layerId = getSequence();
Alec Mouria90a5702021-04-16 16:36:21 +0000655 const uint64_t bufferId = mDrawingState.buffer->getBuffer()->getId();
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000656 const uint64_t frameNumber = mDrawingState.frameNumber;
657 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
658 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
659 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
660
661 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
662 FrameTracer::FrameEvent::ACQUIRE_FENCE);
663 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
664 FrameTracer::FrameEvent::LATCH);
Marissa Wall61c58622018-07-18 10:12:20 -0700665
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000666 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
667 if (bufferSurfaceFrame != nullptr &&
668 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
669 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
670 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
671 // are processing the next state.
672 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
Ady Abraham6c1b7ac2021-03-31 16:56:03 -0700673 mDrawingState.acquireFenceTime->getSignalTime(),
674 latchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000675 }
676
Marissa Wall16c112d2019-03-20 13:21:13 -0700677 mCurrentStateModified = false;
678
Marissa Wall61c58622018-07-18 10:12:20 -0700679 return NO_ERROR;
680}
681
682status_t BufferStateLayer::updateActiveBuffer() {
683 const State& s(getDrawingState());
684
685 if (s.buffer == nullptr) {
686 return BAD_VALUE;
687 }
chaviwdf3c5e82021-01-07 13:00:37 -0800688
Alec Mouria90a5702021-04-16 16:36:21 +0000689 if (!mBufferInfo.mBuffer || s.buffer->getBuffer() != mBufferInfo.mBuffer->getBuffer()) {
chaviwdf3c5e82021-01-07 13:00:37 -0800690 decrementPendingBufferCount();
691 }
Marissa Wall61c58622018-07-18 10:12:20 -0700692
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700693 mPreviousBufferId = getCurrentBufferId();
chaviwd62d3062019-09-04 14:48:02 -0700694 mBufferInfo.mBuffer = s.buffer;
695 mBufferInfo.mFence = s.acquireFence;
Marissa Wall61c58622018-07-18 10:12:20 -0700696
697 return NO_ERROR;
698}
699
Valerie Haubf784642020-01-29 07:25:23 -0800700status_t BufferStateLayer::updateFrameNumber(nsecs_t latchTime) {
Marissa Wall61c58622018-07-18 10:12:20 -0700701 // TODO(marissaw): support frame history events
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700702 mPreviousFrameNumber = mCurrentFrameNumber;
Valerie Hau134651a2020-01-28 16:21:22 -0800703 mCurrentFrameNumber = mDrawingState.frameNumber;
Valerie Haubf784642020-01-29 07:25:23 -0800704 {
705 Mutex::Autolock lock(mFrameEventHistoryMutex);
706 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
707 }
Marissa Wall61c58622018-07-18 10:12:20 -0700708 return NO_ERROR;
709}
710
Marissa Wall947d34e2019-03-29 14:03:53 -0700711void BufferStateLayer::HwcSlotGenerator::bufferErased(const client_cache_t& clientCacheId) {
712 std::lock_guard lock(mMutex);
713 if (!clientCacheId.isValid()) {
714 ALOGE("invalid process, failed to erase buffer");
715 return;
716 }
717 eraseBufferLocked(clientCacheId);
718}
719
720uint32_t BufferStateLayer::HwcSlotGenerator::getHwcCacheSlot(const client_cache_t& clientCacheId) {
721 std::lock_guard<std::mutex> lock(mMutex);
722 auto itr = mCachedBuffers.find(clientCacheId);
723 if (itr == mCachedBuffers.end()) {
724 return addCachedBuffer(clientCacheId);
725 }
726 auto& [hwcCacheSlot, counter] = itr->second;
727 counter = mCounter++;
728 return hwcCacheSlot;
729}
730
731uint32_t BufferStateLayer::HwcSlotGenerator::addCachedBuffer(const client_cache_t& clientCacheId)
732 REQUIRES(mMutex) {
733 if (!clientCacheId.isValid()) {
734 ALOGE("invalid process, returning invalid slot");
735 return BufferQueue::INVALID_BUFFER_SLOT;
736 }
737
738 ClientCache::getInstance().registerErasedRecipient(clientCacheId, wp<ErasedRecipient>(this));
739
740 uint32_t hwcCacheSlot = getFreeHwcCacheSlot();
741 mCachedBuffers[clientCacheId] = {hwcCacheSlot, mCounter++};
742 return hwcCacheSlot;
743}
744
745uint32_t BufferStateLayer::HwcSlotGenerator::getFreeHwcCacheSlot() REQUIRES(mMutex) {
746 if (mFreeHwcCacheSlots.empty()) {
747 evictLeastRecentlyUsed();
748 }
749
750 uint32_t hwcCacheSlot = mFreeHwcCacheSlots.top();
751 mFreeHwcCacheSlots.pop();
752 return hwcCacheSlot;
753}
754
755void BufferStateLayer::HwcSlotGenerator::evictLeastRecentlyUsed() REQUIRES(mMutex) {
756 uint64_t minCounter = UINT_MAX;
757 client_cache_t minClientCacheId = {};
758 for (const auto& [clientCacheId, slotCounter] : mCachedBuffers) {
759 const auto& [hwcCacheSlot, counter] = slotCounter;
760 if (counter < minCounter) {
761 minCounter = counter;
762 minClientCacheId = clientCacheId;
763 }
764 }
765 eraseBufferLocked(minClientCacheId);
766
767 ClientCache::getInstance().unregisterErasedRecipient(minClientCacheId, this);
768}
769
770void BufferStateLayer::HwcSlotGenerator::eraseBufferLocked(const client_cache_t& clientCacheId)
771 REQUIRES(mMutex) {
772 auto itr = mCachedBuffers.find(clientCacheId);
773 if (itr == mCachedBuffers.end()) {
774 return;
775 }
776 auto& [hwcCacheSlot, counter] = itr->second;
777
778 // TODO send to hwc cache and resources
779
780 mFreeHwcCacheSlots.push(hwcCacheSlot);
781 mCachedBuffers.erase(clientCacheId);
782}
chaviw4244e032019-09-04 11:27:49 -0700783
784void BufferStateLayer::gatherBufferInfo() {
chaviwdebadb82020-03-26 14:57:24 -0700785 BufferLayer::gatherBufferInfo();
chaviw4244e032019-09-04 11:27:49 -0700786
chaviwdebadb82020-03-26 14:57:24 -0700787 const State& s(getDrawingState());
chaviw4244e032019-09-04 11:27:49 -0700788 mBufferInfo.mDesiredPresentTime = s.desiredPresentTime;
789 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(s.acquireFence);
790 mBufferInfo.mFence = s.acquireFence;
chaviw766c9c52021-02-10 17:36:47 -0800791 mBufferInfo.mTransform = s.bufferTransform;
chaviw4244e032019-09-04 11:27:49 -0700792 mBufferInfo.mDataspace = translateDataspace(s.dataspace);
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700793 mBufferInfo.mCrop = computeBufferCrop(s);
chaviw4244e032019-09-04 11:27:49 -0700794 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
795 mBufferInfo.mSurfaceDamage = s.surfaceDamageRegion;
796 mBufferInfo.mHdrMetadata = s.hdrMetadata;
797 mBufferInfo.mApi = s.api;
chaviw4244e032019-09-04 11:27:49 -0700798 mBufferInfo.mTransformToDisplayInverse = s.transformToDisplayInverse;
chaviwf83ce182019-09-12 14:43:08 -0700799 mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(s.clientCacheId);
chaviw4244e032019-09-04 11:27:49 -0700800}
801
Robert Carr916b0362020-10-06 13:53:03 -0700802uint32_t BufferStateLayer::getEffectiveScalingMode() const {
803 return NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
804}
805
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700806Rect BufferStateLayer::computeBufferCrop(const State& s) {
807 if (s.buffer) {
Alec Mouria90a5702021-04-16 16:36:21 +0000808 return s.buffer->getBuffer()->getBounds();
chaviw4244e032019-09-04 11:27:49 -0700809 }
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700810 return Rect::INVALID_RECT;
chaviw4244e032019-09-04 11:27:49 -0700811}
812
chaviwb4c6e582019-08-16 14:35:07 -0700813sp<Layer> BufferStateLayer::createClone() {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700814 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, 0, 0, LayerMetadata());
chaviwb4c6e582019-08-16 14:35:07 -0700815 args.textureName = mTextureName;
Lloyd Pique1c3a5eb2019-10-03 13:07:08 -0700816 sp<BufferStateLayer> layer = mFlinger->getFactory().createBufferStateLayer(args);
chaviwb4c6e582019-08-16 14:35:07 -0700817 layer->mHwcSlotGenerator = mHwcSlotGenerator;
818 layer->setInitialValuesForClone(this);
819 return layer;
820}
Valerie Hau92bf5482020-02-10 09:49:08 -0800821
Vishnu Naire7f79c52020-10-29 14:45:03 -0700822bool BufferStateLayer::bufferNeedsFiltering() const {
823 const State& s(getDrawingState());
824 if (!s.buffer) {
825 return false;
826 }
827
Alec Mouria90a5702021-04-16 16:36:21 +0000828 uint32_t bufferWidth = s.buffer->getBuffer()->width;
829 uint32_t bufferHeight = s.buffer->getBuffer()->height;
Vishnu Naire7f79c52020-10-29 14:45:03 -0700830
831 // Undo any transformations on the buffer and return the result.
chaviw766c9c52021-02-10 17:36:47 -0800832 if (s.bufferTransform & ui::Transform::ROT_90) {
Vishnu Naire7f79c52020-10-29 14:45:03 -0700833 std::swap(bufferWidth, bufferHeight);
834 }
835
836 if (s.transformToDisplayInverse) {
837 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
838 if (invTransform & ui::Transform::ROT_90) {
839 std::swap(bufferWidth, bufferHeight);
840 }
841 }
842
843 const Rect layerSize{getBounds()};
844 return layerSize.width() != bufferWidth || layerSize.height() != bufferHeight;
845}
Robert Carr7121caf2020-12-15 13:07:32 -0800846
Robert Carr7121caf2020-12-15 13:07:32 -0800847void BufferStateLayer::decrementPendingBufferCount() {
Vishnu Nair8eda69e2021-02-26 10:42:10 -0800848 int32_t pendingBuffers = --mPendingBufferTransactions;
849 tracePendingBufferCount(pendingBuffers);
Robert Carr7121caf2020-12-15 13:07:32 -0800850}
851
Vishnu Nair8eda69e2021-02-26 10:42:10 -0800852void BufferStateLayer::tracePendingBufferCount(int32_t pendingBuffers) {
853 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
Robert Carr7121caf2020-12-15 13:07:32 -0800854}
855
Alec Mouria90a5702021-04-16 16:36:21 +0000856void BufferStateLayer::bufferMayChange(const sp<GraphicBuffer>& newBuffer) {
857 if (mDrawingState.buffer != nullptr &&
858 (!mBufferInfo.mBuffer ||
859 mDrawingState.buffer->getBuffer() != mBufferInfo.mBuffer->getBuffer()) &&
860 newBuffer != mDrawingState.buffer->getBuffer()) {
Robert Carr7121caf2020-12-15 13:07:32 -0800861 // If we are about to update mDrawingState.buffer but it has not yet latched
Vishnu Nair1506b182021-02-22 14:35:15 -0800862 // then we will drop a buffer and should decrement the pending buffer count and
863 // call any release buffer callbacks if set.
Alec Mouria90a5702021-04-16 16:36:21 +0000864 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
865 mDrawingState.buffer->getBuffer(), mDrawingState.acquireFence);
Robert Carr7121caf2020-12-15 13:07:32 -0800866 decrementPendingBufferCount();
867 }
Robert Carr7121caf2020-12-15 13:07:32 -0800868}
869
chaviw39d01472021-04-08 14:26:24 -0500870/*
871 * We don't want to send the layer's transform to input, but rather the
872 * parent's transform. This is because BufferStateLayer's transform is
873 * information about how the buffer is placed on screen. The parent's
874 * transform makes more sense to send since it's information about how the
875 * layer is placed on screen. This transform is used by input to determine
876 * how to go from screen space back to window space.
877 */
878ui::Transform BufferStateLayer::getInputTransform() const {
879 sp<Layer> parent = mDrawingParent.promote();
880 if (parent == nullptr) {
881 return ui::Transform();
882 }
883
884 return parent->getTransform();
885}
886
887/**
888 * Similar to getInputTransform, we need to update the bounds to include the transform.
889 * This is because bounds for BSL doesn't include buffer transform, where the input assumes
890 * that's already included.
891 */
892Rect BufferStateLayer::getInputBounds() const {
893 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
894 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
895 return bufferBounds;
896 }
897 return mDrawingState.transform.transform(bufferBounds);
898}
899
Marissa Wall61c58622018-07-18 10:12:20 -0700900} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800901
902// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100903#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"