blob: 82e5d4633cb6e02bfb4c2212ba24b5d9b18b8d69 [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
17//#define LOG_NDEBUG 0
18#undef LOG_TAG
19#define LOG_TAG "BufferStateLayer"
20#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
Lloyd Pique9755fb72019-03-26 14:44:40 -070022#include "BufferStateLayer.h"
23
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080024#include <limits>
Marissa Wall61c58622018-07-18 10:12:20 -070025
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +000026#include <FrameTimeline/FrameTimeline.h>
Lloyd Pique9755fb72019-03-26 14:44:40 -070027#include <compositionengine/LayerFECompositionState.h>
Marissa Wall947d34e2019-03-29 14:03:53 -070028#include <gui/BufferQueue.h>
Marissa Wall61c58622018-07-18 10:12:20 -070029#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070030#include <renderengine/Image.h>
Robert Carr38d25002021-06-11 14:30:09 -070031#include "TunnelModeEnabledReporter.h"
Marissa Wall61c58622018-07-18 10:12:20 -070032
Vishnu Nairfa247b12020-02-11 08:58:26 -080033#include "EffectLayer.h"
Adithya Srinivasanb238cd52021-02-04 17:54:05 +000034#include "FrameTracer/FrameTracer.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080035#include "TimeStats/TimeStats.h"
Valerie Hau0bc09152018-12-20 07:42:47 -080036
Marissa Wall61c58622018-07-18 10:12:20 -070037namespace android {
38
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +000039using PresentState = frametimeline::SurfaceFrame::PresentState;
Vishnu Nair1506b182021-02-22 14:35:15 -080040namespace {
41void callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -070042 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
43 const sp<Fence>& releaseFence, uint32_t transformHint,
44 uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -080045 if (!listener) {
46 return;
47 }
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -070048 listener->onReleaseBuffer({buffer->getId(), framenumber},
49 releaseFence ? releaseFence : Fence::NO_FENCE, transformHint,
50 currentMaxAcquiredBufferCount);
Vishnu Nair1506b182021-02-22 14:35:15 -080051}
52} // namespace
53
Marissa Wall947d34e2019-03-29 14:03:53 -070054BufferStateLayer::BufferStateLayer(const LayerCreationArgs& args)
55 : BufferLayer(args), mHwcSlotGenerator(new HwcSlotGenerator()) {
Robert Carr6a160312021-05-17 12:08:20 -070056 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nair60356342018-11-13 13:00:45 -080057}
Marissa Wall61c58622018-07-18 10:12:20 -070058
Alec Mouri4545a8a2019-08-08 20:05:32 -070059BufferStateLayer::~BufferStateLayer() {
chaviwb4c6e582019-08-16 14:35:07 -070060 // The original layer and the clone layer share the same texture and buffer. Therefore, only
61 // one of the layers, in this case the original layer, needs to handle the deletion. The
62 // original layer and the clone should be removed at the same time so there shouldn't be any
63 // issue with the clone layer trying to use the texture.
64 if (mBufferInfo.mBuffer != nullptr && !isClone()) {
Alec Mouria90a5702021-04-16 16:36:21 +000065 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -070066 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
67 mBufferInfo.mFence, mTransformHint,
Ady Abraham899dcdb2021-06-15 16:56:21 -070068 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
69 mOwnerUid));
Alec Mouri4545a8a2019-08-08 20:05:32 -070070 }
71}
72
Robert Carr8d958532020-11-10 14:09:16 -080073status_t BufferStateLayer::addReleaseFence(const sp<CallbackHandle>& ch,
74 const sp<Fence>& fence) {
75 if (ch == nullptr) {
76 return OK;
77 }
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -070078 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
Robert Carr8d958532020-11-10 14:09:16 -080079 if (!ch->previousReleaseFence.get()) {
80 ch->previousReleaseFence = fence;
81 return OK;
82 }
83
84 // Below logic is lifted from ConsumerBase.cpp:
85 // Check status of fences first because merging is expensive.
86 // Merging an invalid fence with any other fence results in an
87 // invalid fence.
88 auto currentStatus = ch->previousReleaseFence->getStatus();
89 if (currentStatus == Fence::Status::Invalid) {
90 ALOGE("Existing fence has invalid state, layer: %s", mName.c_str());
91 return BAD_VALUE;
92 }
93
94 auto incomingStatus = fence->getStatus();
95 if (incomingStatus == Fence::Status::Invalid) {
96 ALOGE("New fence has invalid state, layer: %s", mName.c_str());
97 ch->previousReleaseFence = fence;
98 return BAD_VALUE;
99 }
100
101 // If both fences are signaled or both are unsignaled, we need to merge
102 // them to get an accurate timestamp.
103 if (currentStatus == incomingStatus) {
104 char fenceName[32] = {};
105 snprintf(fenceName, 32, "%.28s", mName.c_str());
106 sp<Fence> mergedFence = Fence::merge(
107 fenceName, ch->previousReleaseFence, fence);
108 if (!mergedFence.get()) {
109 ALOGE("failed to merge release fences, layer: %s", mName.c_str());
110 // synchronization is broken, the best we can do is hope fences
111 // signal in order so the new fence will act like a union
112 ch->previousReleaseFence = fence;
113 return BAD_VALUE;
114 }
115 ch->previousReleaseFence = mergedFence;
116 } else if (incomingStatus == Fence::Status::Unsignaled) {
117 // If one fence has signaled and the other hasn't, the unsignaled
118 // fence will approximately correspond with the correct timestamp.
119 // There's a small race if both fences signal at about the same time
120 // and their statuses are retrieved with unfortunate timing. However,
121 // by this point, they will have both signaled and only the timestamp
122 // will be slightly off; any dependencies after this point will
123 // already have been met.
124 ch->previousReleaseFence = fence;
125 }
126 // else if (currentStatus == Fence::Status::Unsignaled) is a no-op.
127
128 return OK;
129}
130
Marissa Wall61c58622018-07-18 10:12:20 -0700131// -----------------------------------------------------------------------
132// Interface implementation for Layer
133// -----------------------------------------------------------------------
Marissa Wallfda30bb2018-10-12 11:34:28 -0700134void BufferStateLayer::onLayerDisplayed(const sp<Fence>& releaseFence) {
Robert Carr8d958532020-11-10 14:09:16 -0800135 if (!releaseFence->isValid()) {
136 return;
137 }
Marissa Wall5a68a772018-12-22 17:43:42 -0800138 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
139 // buffer that was presented on this layer. The first transaction that came in this frame that
140 // replaced the previous buffer on this layer needs this release fence, because the fence will
141 // let the client know when that previous buffer is removed from the screen.
142 //
143 // Every other transaction on this layer does not need a release fence because no other
144 // Transactions that were set on this layer this frame are going to have their preceeding buffer
145 // removed from the display this frame.
146 //
147 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
148 // buffer so it doesn't need a previous release fence because the layer still needs the previous
149 // buffer. The second transaction contains a buffer so it needs a previous release fence because
150 // the previous buffer will be released this frame. The third transaction also contains a
151 // buffer. It replaces the buffer in the second transaction. The buffer in the second
152 // transaction will now no longer be presented so it is released immediately and the third
153 // transaction doesn't need a previous release fence.
Robert Carr8d958532020-11-10 14:09:16 -0800154 sp<CallbackHandle> ch;
Marissa Wall5a68a772018-12-22 17:43:42 -0800155 for (auto& handle : mDrawingState.callbackHandles) {
chaviw0b06a8d2021-08-06 11:49:08 -0500156 if (handle->releasePreviousBuffer &&
157 mDrawingState.releaseBufferEndpoint == handle->listener) {
Robert Carr8d958532020-11-10 14:09:16 -0800158 ch = handle;
Marissa Wall5a68a772018-12-22 17:43:42 -0800159 break;
160 }
161 }
Robert Carr8d958532020-11-10 14:09:16 -0800162 auto status = addReleaseFence(ch, releaseFence);
163 if (status != OK) {
164 ALOGE("Failed to add release fence for layer %s", getName().c_str());
165 }
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700166
Valerie Haubf784642020-01-29 07:25:23 -0800167 mPreviousReleaseFence = releaseFence;
168
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700169 // Prevent tracing the same release multiple times.
170 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700171 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
172 }
Marissa Wall61c58622018-07-18 10:12:20 -0700173}
174
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100175void BufferStateLayer::onSurfaceFrameCreated(
176 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasand17c7da2021-03-05 20:43:32 +0000177 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
178 // Too many SurfaceFrames pending classification. The front of the deque is probably not
179 // tracked by FrameTimeline and will never be presented. This will only result in a memory
180 // leak.
181 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
182 mName.c_str());
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000183 std::string miniDump = mPendingJankClassifications.front()->miniDump();
184 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
Adithya Srinivasand17c7da2021-03-05 20:43:32 +0000185 mPendingJankClassifications.pop_front();
186 }
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100187 mPendingJankClassifications.emplace_back(surfaceFrame);
188}
189
Valerie Haubf784642020-01-29 07:25:23 -0800190void BufferStateLayer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700191 for (const auto& handle : mDrawingState.callbackHandles) {
192 handle->transformHint = mTransformHint;
Valerie Hau871d6352020-01-29 08:44:02 -0800193 handle->dequeueReadyTime = dequeueReadyTime;
Ady Abraham899dcdb2021-06-15 16:56:21 -0700194 handle->currentMaxAcquiredBufferCount =
195 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700196 }
197
Vishnu Nair1506b182021-02-22 14:35:15 -0800198 for (auto& handle : mDrawingState.callbackHandles) {
chaviw0b06a8d2021-08-06 11:49:08 -0500199 if (handle->releasePreviousBuffer &&
200 mDrawingState.releaseBufferEndpoint == handle->listener) {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700201 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
Vishnu Nair1506b182021-02-22 14:35:15 -0800202 break;
203 }
204 }
205
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100206 std::vector<JankData> jankData;
207 jankData.reserve(mPendingJankClassifications.size());
208 while (!mPendingJankClassifications.empty()
209 && mPendingJankClassifications.front()->getJankType()) {
210 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
211 mPendingJankClassifications.front();
212 mPendingJankClassifications.pop_front();
213 jankData.emplace_back(
214 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
215 }
216
Robert Carr9a803c32021-01-14 16:57:58 -0800217 mFlinger->getTransactionCallbackInvoker().finalizePendingCallbackHandles(
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100218 mDrawingState.callbackHandles, jankData);
Marissa Wall5a68a772018-12-22 17:43:42 -0800219
220 mDrawingState.callbackHandles = {};
Valerie Haubf784642020-01-29 07:25:23 -0800221
222 const sp<Fence>& releaseFence(mPreviousReleaseFence);
223 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(releaseFence);
224 {
225 Mutex::Autolock lock(mFrameEventHistoryMutex);
226 if (mPreviousFrameNumber != 0) {
227 mFrameEventHistory.addRelease(mPreviousFrameNumber, dequeueReadyTime,
228 std::move(releaseFenceTime));
229 }
230 }
Marissa Wall61c58622018-07-18 10:12:20 -0700231}
232
Valerie Hau871d6352020-01-29 08:44:02 -0800233void BufferStateLayer::finalizeFrameEventHistory(const std::shared_ptr<FenceTime>& glDoneFence,
234 const CompositorTiming& compositorTiming) {
235 for (const auto& handle : mDrawingState.callbackHandles) {
236 handle->gpuCompositionDoneFence = glDoneFence;
237 handle->compositorTiming = compositorTiming;
238 }
239}
240
Marissa Walle2ffb422018-10-12 11:33:52 -0700241bool BufferStateLayer::willPresentCurrentTransaction() const {
242 // Returns true if the most recent Transaction applied to CurrentState will be presented.
Robert Carr321e83c2019-08-19 15:49:30 -0700243 return (getSidebandStreamChanged() || getAutoRefresh() ||
Robert Carr6a160312021-05-17 12:08:20 -0700244 (mDrawingState.modified &&
245 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
Marissa Wall61c58622018-07-18 10:12:20 -0700246}
247
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000248Rect BufferStateLayer::getCrop(const Layer::State& s) const {
249 return s.crop;
Marissa Wall61c58622018-07-18 10:12:20 -0700250}
251
252bool BufferStateLayer::setTransform(uint32_t transform) {
Robert Carr6a160312021-05-17 12:08:20 -0700253 if (mDrawingState.bufferTransform == transform) return false;
254 mDrawingState.bufferTransform = transform;
255 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700256 setTransactionFlags(eTransactionNeeded);
257 return true;
258}
259
260bool BufferStateLayer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
Robert Carr6a160312021-05-17 12:08:20 -0700261 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
262 mDrawingState.sequence++;
263 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
264 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700265 setTransactionFlags(eTransactionNeeded);
266 return true;
267}
268
269bool BufferStateLayer::setCrop(const Rect& crop) {
Robert Carr6a160312021-05-17 12:08:20 -0700270 if (mDrawingState.crop == crop) return false;
271 mDrawingState.sequence++;
272 mDrawingState.crop = crop;
Marissa Wall290ad082019-03-06 13:23:47 -0800273
Robert Carr6a160312021-05-17 12:08:20 -0700274 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700275 setTransactionFlags(eTransactionNeeded);
276 return true;
277}
278
chaviwf3f40fe2021-04-27 15:54:02 -0500279bool BufferStateLayer::setBufferCrop(const Rect& bufferCrop) {
Robert Carr6a160312021-05-17 12:08:20 -0700280 if (mDrawingState.bufferCrop == bufferCrop) return false;
chaviwf3f40fe2021-04-27 15:54:02 -0500281
Robert Carr6a160312021-05-17 12:08:20 -0700282 mDrawingState.sequence++;
283 mDrawingState.bufferCrop = bufferCrop;
chaviwf3f40fe2021-04-27 15:54:02 -0500284
Robert Carr6a160312021-05-17 12:08:20 -0700285 mDrawingState.modified = true;
chaviwf3f40fe2021-04-27 15:54:02 -0500286 setTransactionFlags(eTransactionNeeded);
287 return true;
288}
289
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700290bool BufferStateLayer::setDestinationFrame(const Rect& destinationFrame) {
Robert Carr6a160312021-05-17 12:08:20 -0700291 if (mDrawingState.destinationFrame == destinationFrame) return false;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700292
Robert Carr6a160312021-05-17 12:08:20 -0700293 mDrawingState.sequence++;
294 mDrawingState.destinationFrame = destinationFrame;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700295
Robert Carr6a160312021-05-17 12:08:20 -0700296 mDrawingState.modified = true;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700297 setTransactionFlags(eTransactionNeeded);
298 return true;
299}
300
Robert Carr6a160312021-05-17 12:08:20 -0700301static bool assignTransform(ui::Transform* dst, ui::Transform& from) {
302 if (*dst == from) {
303 return false;
304 }
305 *dst = from;
306 return true;
307}
308
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700309// Translate destination frame into scale and position. If a destination frame is not set, use the
310// provided scale and position
Robert Carr6a160312021-05-17 12:08:20 -0700311bool BufferStateLayer::updateGeometry() {
312 if (mDrawingState.destinationFrame.isEmpty()) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700313 // If destination frame is not set, use the requested transform set via
314 // BufferStateLayer::setPosition and BufferStateLayer::setMatrix.
Robert Carr6a160312021-05-17 12:08:20 -0700315 return assignTransform(&mDrawingState.transform, mRequestedTransform);
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700316 }
317
Robert Carr6a160312021-05-17 12:08:20 -0700318 Rect destRect = mDrawingState.destinationFrame;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700319 int32_t destW = destRect.width();
320 int32_t destH = destRect.height();
321 if (destRect.left < 0) {
322 destRect.left = 0;
323 destRect.right = destW;
324 }
325 if (destRect.top < 0) {
326 destRect.top = 0;
327 destRect.bottom = destH;
328 }
329
Robert Carr6a160312021-05-17 12:08:20 -0700330 if (!mDrawingState.buffer) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700331 ui::Transform t;
332 t.set(destRect.left, destRect.top);
Robert Carr6a160312021-05-17 12:08:20 -0700333 return assignTransform(&mDrawingState.transform, t);
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700334 }
335
Robert Carr6a160312021-05-17 12:08:20 -0700336 uint32_t bufferWidth = mDrawingState.buffer->getBuffer()->getWidth();
337 uint32_t bufferHeight = mDrawingState.buffer->getBuffer()->getHeight();
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700338 // Undo any transformations on the buffer.
Robert Carr6a160312021-05-17 12:08:20 -0700339 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700340 std::swap(bufferWidth, bufferHeight);
341 }
342 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
Robert Carr6a160312021-05-17 12:08:20 -0700343 if (mDrawingState.transformToDisplayInverse) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700344 if (invTransform & ui::Transform::ROT_90) {
345 std::swap(bufferWidth, bufferHeight);
346 }
347 }
348
349 float sx = destW / static_cast<float>(bufferWidth);
350 float sy = destH / static_cast<float>(bufferHeight);
351 ui::Transform t;
352 t.set(sx, 0, 0, sy);
353 t.set(destRect.left, destRect.top);
Robert Carr6a160312021-05-17 12:08:20 -0700354 return assignTransform(&mDrawingState.transform, t);
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700355}
356
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000357bool BufferStateLayer::setMatrix(const layer_state_t::matrix22_t& matrix,
358 bool allowNonRectPreservingTransforms) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700359 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
360 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
Marissa Wall861616d2018-10-22 12:52:23 -0700361 return false;
362 }
363
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000364 ui::Transform t;
365 t.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
366
367 if (!allowNonRectPreservingTransforms && !t.preserveRects()) {
368 ALOGW("Attempt to set rotation matrix without permission ACCESS_SURFACE_FLINGER nor "
369 "ROTATE_SURFACE_FLINGER ignored");
370 return false;
Marissa Wall861616d2018-10-22 12:52:23 -0700371 }
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000372
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700373 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
chaviw9a93ea62021-03-11 16:44:42 -0600374
Robert Carr6a160312021-05-17 12:08:20 -0700375 mDrawingState.sequence++;
376 mDrawingState.modified = true;
chaviw9a93ea62021-03-11 16:44:42 -0600377 setTransactionFlags(eTransactionNeeded);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000378
379 return true;
380}
381
382bool BufferStateLayer::setPosition(float x, float y) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700383 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000384 return false;
385 }
386
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700387 mRequestedTransform.set(x, y);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000388
Robert Carr6a160312021-05-17 12:08:20 -0700389 mDrawingState.sequence++;
390 mDrawingState.modified = true;
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000391 setTransactionFlags(eTransactionNeeded);
392
Marissa Wall861616d2018-10-22 12:52:23 -0700393 return true;
394}
395
Valerie Hau871d6352020-01-29 08:44:02 -0800396bool BufferStateLayer::addFrameEvent(const sp<Fence>& acquireFence, nsecs_t postedTime,
397 nsecs_t desiredPresentTime) {
Valerie Haubf784642020-01-29 07:25:23 -0800398 Mutex::Autolock lock(mFrameEventHistoryMutex);
399 mAcquireTimeline.updateSignalTimes();
400 std::shared_ptr<FenceTime> acquireFenceTime =
401 std::make_shared<FenceTime>((acquireFence ? acquireFence : Fence::NO_FENCE));
Robert Carr6a160312021-05-17 12:08:20 -0700402 NewFrameEventsEntry newTimestamps = {mDrawingState.frameNumber, postedTime, desiredPresentTime,
Valerie Haubf784642020-01-29 07:25:23 -0800403 acquireFenceTime};
Valerie Hau871d6352020-01-29 08:44:02 -0800404 mFrameEventHistory.setProducerWantsEvents();
Valerie Haubf784642020-01-29 07:25:23 -0800405 mFrameEventHistory.addQueue(newTimestamps);
406 return true;
407}
408
chaviwba4320c2021-09-15 15:20:53 -0500409std::shared_ptr<renderengine::ExternalTexture> BufferStateLayer::getBufferFromBufferData(
410 const BufferData& bufferData) {
411 bool cacheIdChanged = bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
412 bool bufferSizeExceedsLimit = false;
413 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
414 if (cacheIdChanged && bufferData.buffer != nullptr) {
415 bufferSizeExceedsLimit =
416 mFlinger->exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
417 bufferData.buffer->getHeight());
418 if (!bufferSizeExceedsLimit) {
419 ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
420 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
421 }
422 } else if (cacheIdChanged) {
423 buffer = ClientCache::getInstance().get(bufferData.cachedBuffer);
424 } else if (bufferData.buffer != nullptr) {
425 bufferSizeExceedsLimit =
426 mFlinger->exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(),
427 bufferData.buffer->getHeight());
428 if (!bufferSizeExceedsLimit) {
429 buffer = std::make_shared<
430 renderengine::ExternalTexture>(bufferData.buffer, mFlinger->getRenderEngine(),
431 renderengine::ExternalTexture::Usage::READABLE);
432 }
433 }
434 ALOGE_IF(bufferSizeExceedsLimit,
435 "Attempted to create an ExternalTexture for layer %s that exceeds render target size "
436 "limit.",
437 getDebugName());
438 return buffer;
439}
440
441bool BufferStateLayer::setBuffer(const BufferData& bufferData, nsecs_t postTime,
Alec Mouria90a5702021-04-16 16:36:21 +0000442 nsecs_t desiredPresentTime, bool isAutoTimestamp,
chaviwba4320c2021-09-15 15:20:53 -0500443 std::optional<nsecs_t> dequeueTime,
444 const FrameTimelineInfo& info) {
Robert Carr0c1966e2020-10-19 12:12:08 -0700445 ATRACE_CALL();
446
chaviwba4320c2021-09-15 15:20:53 -0500447 const std::shared_ptr<renderengine::ExternalTexture>& buffer =
448 getBufferFromBufferData(bufferData);
449 if (!buffer) {
450 return false;
451 }
452
453 const bool frameNumberChanged =
454 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
455 const uint64_t frameNumber =
456 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
457
Robert Carr6a160312021-05-17 12:08:20 -0700458 if (mDrawingState.buffer) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700459 mReleasePreviousBuffer = true;
Vishnu Nair52846cd2021-08-05 16:12:48 -0700460 if (mDrawingState.buffer != mBufferInfo.mBuffer ||
461 mDrawingState.frameNumber != mBufferInfo.mFrameNumber) {
Robert Carr6a160312021-05-17 12:08:20 -0700462 // If mDrawingState has a buffer, and we are about to update again
Robert Carr7121caf2020-12-15 13:07:32 -0800463 // before swapping to drawing state, then the first buffer will be
Vishnu Nair1506b182021-02-22 14:35:15 -0800464 // dropped and we should decrement the pending buffer count and
465 // call any release buffer callbacks if set.
Robert Carr6a160312021-05-17 12:08:20 -0700466 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700467 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
468 mDrawingState.acquireFence, mTransformHint,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700469 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
470 mOwnerUid));
Robert Carr7121caf2020-12-15 13:07:32 -0800471 decrementPendingBufferCount();
Robert Carr6a160312021-05-17 12:08:20 -0700472 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
473 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
474 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
475 mDrawingState.bufferSurfaceFrameTX.reset();
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000476 }
Robert Carr7121caf2020-12-15 13:07:32 -0800477 }
Marissa Wallfda30bb2018-10-12 11:34:28 -0700478 }
Robert Carr6a160312021-05-17 12:08:20 -0700479
480 mDrawingState.frameNumber = frameNumber;
chaviwba4320c2021-09-15 15:20:53 -0500481 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
Robert Carr6a160312021-05-17 12:08:20 -0700482 mDrawingState.buffer = buffer;
chaviwba4320c2021-09-15 15:20:53 -0500483 mDrawingState.clientCacheId = bufferData.cachedBuffer;
484
485 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
486 ? bufferData.acquireFence
487 : Fence::NO_FENCE;
488 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
489 // The acquire fences of BufferStateLayers have already signaled before they are set
490 mCallbackHandleAcquireTime = mDrawingState.acquireFenceTime->getSignalTime();
491
Robert Carr6a160312021-05-17 12:08:20 -0700492 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700493 setTransactionFlags(eTransactionNeeded);
Ady Abraham09bd3922019-04-08 10:44:56 -0700494
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800495 const int32_t layerId = getSequence();
Robert Carr6a160312021-05-17 12:08:20 -0700496 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000497 mOwnerUid, postTime, getGameMode());
Robert Carr6a160312021-05-17 12:08:20 -0700498 mDrawingState.desiredPresentTime = desiredPresentTime;
499 mDrawingState.isAutoTimestamp = isAutoTimestamp;
Ady Abraham09bd3922019-04-08 10:44:56 -0700500
Ady Abrahamb7f15562021-03-15 18:34:08 -0700501 const nsecs_t presentTime = [&] {
502 if (!isAutoTimestamp) return desiredPresentTime;
503
504 const auto prediction =
505 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
506 if (prediction.has_value()) return prediction->presentTime;
507
508 return static_cast<nsecs_t>(0);
509 }();
510 mFlinger->mScheduler->recordLayerHistory(this, presentTime,
Ady Abraham5def7332020-05-29 16:13:47 -0700511 LayerHistory::LayerUpdateType::Buffer);
Ady Abraham09bd3922019-04-08 10:44:56 -0700512
chaviwba4320c2021-09-15 15:20:53 -0500513 addFrameEvent(mDrawingState.acquireFence, postTime, isAutoTimestamp ? 0 : desiredPresentTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000514
Adithya Srinivasan891004e2021-02-12 20:20:47 +0000515 setFrameTimelineVsyncForBufferTransaction(info, postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000516
Alec Mouria90a5702021-04-16 16:36:21 +0000517 if (buffer && dequeueTime && *dequeueTime != 0) {
518 const uint64_t bufferId = buffer->getBuffer()->getId();
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000519 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
520 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
521 FrameTracer::FrameEvent::DEQUEUE);
522 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
523 FrameTracer::FrameEvent::QUEUE);
524 }
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000525
Robert Carr6a160312021-05-17 12:08:20 -0700526 mDrawingState.width = mDrawingState.buffer->getBuffer()->getWidth();
527 mDrawingState.height = mDrawingState.buffer->getBuffer()->getHeight();
chaviwba4320c2021-09-15 15:20:53 -0500528 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
Marissa Wall61c58622018-07-18 10:12:20 -0700529 return true;
530}
531
532bool BufferStateLayer::setDataspace(ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700533 if (mDrawingState.dataspace == dataspace) return false;
534 mDrawingState.dataspace = dataspace;
535 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700536 setTransactionFlags(eTransactionNeeded);
537 return true;
538}
539
540bool BufferStateLayer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
Robert Carr6a160312021-05-17 12:08:20 -0700541 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
542 mDrawingState.hdrMetadata = hdrMetadata;
543 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700544 setTransactionFlags(eTransactionNeeded);
545 return true;
546}
547
548bool BufferStateLayer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Robert Carr6a160312021-05-17 12:08:20 -0700549 mDrawingState.surfaceDamageRegion = surfaceDamage;
550 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700551 setTransactionFlags(eTransactionNeeded);
552 return true;
553}
554
555bool BufferStateLayer::setApi(int32_t api) {
Robert Carr6a160312021-05-17 12:08:20 -0700556 if (mDrawingState.api == api) return false;
557 mDrawingState.api = api;
558 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700559 setTransactionFlags(eTransactionNeeded);
560 return true;
561}
562
563bool BufferStateLayer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
Robert Carr6a160312021-05-17 12:08:20 -0700564 if (mDrawingState.sidebandStream == sidebandStream) return false;
Robert Carr3e2a2992021-06-11 13:42:55 -0700565
566 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
567 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
568 } else if (sidebandStream != nullptr) {
569 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
570 }
571
Robert Carr6a160312021-05-17 12:08:20 -0700572 mDrawingState.sidebandStream = sidebandStream;
573 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700574 setTransactionFlags(eTransactionNeeded);
Marissa Wall61c58622018-07-18 10:12:20 -0700575 if (!mSidebandStreamChanged.exchange(true)) {
576 // mSidebandStreamChanged was false
577 mFlinger->signalLayerUpdate();
578 }
579 return true;
580}
581
Marissa Walle2ffb422018-10-12 11:33:52 -0700582bool BufferStateLayer::setTransactionCompletedListeners(
583 const std::vector<sp<CallbackHandle>>& handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700584 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
Marissa Walle2ffb422018-10-12 11:33:52 -0700585 if (handles.empty()) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700586 mReleasePreviousBuffer = false;
Marissa Walle2ffb422018-10-12 11:33:52 -0700587 return false;
588 }
589
590 const bool willPresent = willPresentCurrentTransaction();
591
592 for (const auto& handle : handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700593 // If this transaction set a buffer on this layer, release its previous buffer
594 handle->releasePreviousBuffer = mReleasePreviousBuffer;
595
Marissa Walle2ffb422018-10-12 11:33:52 -0700596 // If this layer will be presented in this frame
597 if (willPresent) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700598 // If this transaction set an acquire fence on this layer, set its acquire time
599 handle->acquireTime = mCallbackHandleAcquireTime;
Robert Carr6a160312021-05-17 12:08:20 -0700600 handle->frameNumber = mDrawingState.frameNumber;
Marissa Wallfda30bb2018-10-12 11:34:28 -0700601
Marissa Walle2ffb422018-10-12 11:33:52 -0700602 // Notify the transaction completed thread that there is a pending latched callback
603 // handle
Robert Carr9a803c32021-01-14 16:57:58 -0800604 mFlinger->getTransactionCallbackInvoker().registerPendingCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700605
606 // Store so latched time and release fence can be set
Robert Carr6a160312021-05-17 12:08:20 -0700607 mDrawingState.callbackHandles.push_back(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700608
609 } else { // If this layer will NOT need to be relatched and presented this frame
610 // Notify the transaction completed thread this handle is done
Robert Carr9a803c32021-01-14 16:57:58 -0800611 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700612 }
613 }
614
Marissa Wallfda30bb2018-10-12 11:34:28 -0700615 mReleasePreviousBuffer = false;
616 mCallbackHandleAcquireTime = -1;
617
Marissa Walle2ffb422018-10-12 11:33:52 -0700618 return willPresent;
619}
620
Marissa Wall61c58622018-07-18 10:12:20 -0700621bool BufferStateLayer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nair27e3ed52021-07-08 18:24:25 -0700622 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -0700623 mDrawingState.transparentRegionHint = transparent;
624 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700625 setTransactionFlags(eTransactionNeeded);
626 return true;
627}
628
rnleeed20fa42021-08-10 18:00:03 -0700629Rect BufferStateLayer::getBufferSize(const State& /*s*/) const {
Marissa Wall861616d2018-10-22 12:52:23 -0700630 // for buffer state layers we use the display frame size as the buffer size.
Marissa Wall61c58622018-07-18 10:12:20 -0700631
chaviw7e72caf2020-12-02 16:50:43 -0800632 if (mBufferInfo.mBuffer == nullptr) {
633 return Rect::INVALID_RECT;
634 }
635
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700636 uint32_t bufWidth = mBufferInfo.mBuffer->getBuffer()->getWidth();
637 uint32_t bufHeight = mBufferInfo.mBuffer->getBuffer()->getHeight();
638
639 // Undo any transformations on the buffer and return the result.
640 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
641 std::swap(bufWidth, bufHeight);
642 }
643
644 if (getTransformToDisplayInverse()) {
645 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
646 if (invTransform & ui::Transform::ROT_90) {
647 std::swap(bufWidth, bufHeight);
Marissa Wall861616d2018-10-22 12:52:23 -0700648 }
649 }
650
rnleeed20fa42021-08-10 18:00:03 -0700651 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
Marissa Wall61c58622018-07-18 10:12:20 -0700652}
Vishnu Nair4351ad52019-02-11 14:13:02 -0800653
654FloatRect BufferStateLayer::computeSourceBounds(const FloatRect& parentBounds) const {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700655 if (mBufferInfo.mBuffer == nullptr) {
656 return parentBounds;
Vishnu Nair4351ad52019-02-11 14:13:02 -0800657 }
658
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700659 return getBufferSize(getDrawingState()).toFloatRect();
Vishnu Nair4351ad52019-02-11 14:13:02 -0800660}
661
Marissa Wall61c58622018-07-18 10:12:20 -0700662// -----------------------------------------------------------------------
663
664// -----------------------------------------------------------------------
665// Interface implementation for BufferLayer
666// -----------------------------------------------------------------------
667bool BufferStateLayer::fenceHasSignaled() const {
Huihong Luo86c80e32021-06-16 15:41:07 -0700668 if (SurfaceFlinger::enableLatchUnsignaled) {
669 return true;
670 }
671
Alec Mouri91f6df32020-01-30 08:48:58 -0800672 const bool fenceSignaled =
673 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
674 if (!fenceSignaled) {
675 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
676 TimeStats::LatchSkipReason::LateAcquire);
677 }
678
679 return fenceSignaled;
Marissa Wall61c58622018-07-18 10:12:20 -0700680}
681
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700682bool BufferStateLayer::framePresentTimeIsCurrent(nsecs_t expectedPresentTime) const {
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700683 if (!hasFrameUpdate() || isRemovedFromCurrentState()) {
684 return true;
685 }
686
Robert Carr6a160312021-05-17 12:08:20 -0700687 return mDrawingState.isAutoTimestamp || mDrawingState.desiredPresentTime <= expectedPresentTime;
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700688}
689
Valerie Hau871d6352020-01-29 08:44:02 -0800690bool BufferStateLayer::onPreComposition(nsecs_t refreshStartTime) {
691 for (const auto& handle : mDrawingState.callbackHandles) {
692 handle->refreshStartTime = refreshStartTime;
693 }
694 return BufferLayer::onPreComposition(refreshStartTime);
695}
696
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800697void BufferStateLayer::setAutoRefresh(bool autoRefresh) {
698 if (!mAutoRefresh.exchange(autoRefresh)) {
699 mFlinger->signalLayerUpdate();
700 }
Marissa Wall61c58622018-07-18 10:12:20 -0700701}
702
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800703bool BufferStateLayer::latchSidebandStream(bool& recomputeVisibleRegions) {
baocheng suna663c2b2021-05-13 18:51:28 +0800704 // We need to update the sideband stream if the layer has both a buffer and a sideband stream.
baocheng sun9691b9c2021-08-03 19:27:06 +0800705 editCompositionState()->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
baocheng suna663c2b2021-05-13 18:51:28 +0800706
baocheng sun9691b9c2021-08-03 19:27:06 +0800707 if (mSidebandStreamChanged.exchange(false)) {
Marissa Wall61c58622018-07-18 10:12:20 -0700708 const State& s(getDrawingState());
709 // mSidebandStreamChanged was true
Lloyd Pique0b785d82018-12-04 17:25:27 -0800710 mSidebandStream = s.sidebandStream;
Lloyd Piquede196652020-01-22 17:29:58 -0800711 editCompositionState()->sidebandStream = mSidebandStream;
Lloyd Pique0b785d82018-12-04 17:25:27 -0800712 if (mSidebandStream != nullptr) {
Marissa Wall61c58622018-07-18 10:12:20 -0700713 setTransactionFlags(eTransactionNeeded);
714 mFlinger->setTransactionFlags(eTraversalNeeded);
715 }
716 recomputeVisibleRegions = true;
717
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800718 return true;
Marissa Wall61c58622018-07-18 10:12:20 -0700719 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800720 return false;
Marissa Wall61c58622018-07-18 10:12:20 -0700721}
722
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800723bool BufferStateLayer::hasFrameUpdate() const {
Robert Carr6a160312021-05-17 12:08:20 -0700724 const State& c(getDrawingState());
Robert Carr315f3c72021-06-24 21:58:09 -0700725 return (mDrawingStateModified || mDrawingState.modified) && (c.buffer != nullptr || c.bgColorLayer != nullptr);
Marissa Wall61c58622018-07-18 10:12:20 -0700726}
727
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700728status_t BufferStateLayer::updateTexImage(bool& /*recomputeVisibleRegions*/, nsecs_t latchTime,
729 nsecs_t /*expectedPresentTime*/) {
Marissa Wall61c58622018-07-18 10:12:20 -0700730 const State& s(getDrawingState());
731
732 if (!s.buffer) {
Valerie Hauaa194562019-02-05 16:21:38 -0800733 if (s.bgColorLayer) {
734 for (auto& handle : mDrawingState.callbackHandles) {
735 handle->latchTime = latchTime;
736 }
737 }
Marissa Wall61c58622018-07-18 10:12:20 -0700738 return NO_ERROR;
739 }
740
Marissa Wall5a68a772018-12-22 17:43:42 -0800741 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair935590e2021-02-10 13:05:52 -0800742 if (handle->frameNumber == mDrawingState.frameNumber) {
743 handle->latchTime = latchTime;
744 }
Marissa Wall5a68a772018-12-22 17:43:42 -0800745 }
Marissa Walle2ffb422018-10-12 11:33:52 -0700746
Vishnu Nairea0de002020-11-17 17:42:37 -0800747 const int32_t layerId = getSequence();
Alec Mouria90a5702021-04-16 16:36:21 +0000748 const uint64_t bufferId = mDrawingState.buffer->getBuffer()->getId();
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000749 const uint64_t frameNumber = mDrawingState.frameNumber;
750 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
751 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
752 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
753
754 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
755 FrameTracer::FrameEvent::ACQUIRE_FENCE);
756 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
757 FrameTracer::FrameEvent::LATCH);
Marissa Wall61c58622018-07-18 10:12:20 -0700758
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000759 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
760 if (bufferSurfaceFrame != nullptr &&
761 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
762 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
763 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
764 // are processing the next state.
765 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
Ady Abraham6c1b7ac2021-03-31 16:56:03 -0700766 mDrawingState.acquireFenceTime->getSignalTime(),
767 latchTime);
Robert Carr6a160312021-05-17 12:08:20 -0700768 mDrawingState.bufferSurfaceFrameTX.reset();
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000769 }
770
Vishnu Nairfc46c1e2021-04-21 08:31:32 -0700771 std::deque<sp<CallbackHandle>> remainingHandles;
772 mFlinger->getTransactionCallbackInvoker()
773 .finalizeOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
774 mDrawingState.callbackHandles = remainingHandles;
775
Robert Carr6a160312021-05-17 12:08:20 -0700776 mDrawingStateModified = false;
Marissa Wall16c112d2019-03-20 13:21:13 -0700777
Marissa Wall61c58622018-07-18 10:12:20 -0700778 return NO_ERROR;
779}
780
781status_t BufferStateLayer::updateActiveBuffer() {
782 const State& s(getDrawingState());
783
784 if (s.buffer == nullptr) {
785 return BAD_VALUE;
786 }
chaviwdf3c5e82021-01-07 13:00:37 -0800787
Alec Mouria90a5702021-04-16 16:36:21 +0000788 if (!mBufferInfo.mBuffer || s.buffer->getBuffer() != mBufferInfo.mBuffer->getBuffer()) {
chaviwdf3c5e82021-01-07 13:00:37 -0800789 decrementPendingBufferCount();
790 }
Marissa Wall61c58622018-07-18 10:12:20 -0700791
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700792 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
chaviwd62d3062019-09-04 14:48:02 -0700793 mBufferInfo.mBuffer = s.buffer;
794 mBufferInfo.mFence = s.acquireFence;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700795 mBufferInfo.mFrameNumber = s.frameNumber;
Marissa Wall61c58622018-07-18 10:12:20 -0700796
797 return NO_ERROR;
798}
799
Valerie Haubf784642020-01-29 07:25:23 -0800800status_t BufferStateLayer::updateFrameNumber(nsecs_t latchTime) {
Marissa Wall61c58622018-07-18 10:12:20 -0700801 // TODO(marissaw): support frame history events
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700802 mPreviousFrameNumber = mCurrentFrameNumber;
Valerie Hau134651a2020-01-28 16:21:22 -0800803 mCurrentFrameNumber = mDrawingState.frameNumber;
Valerie Haubf784642020-01-29 07:25:23 -0800804 {
805 Mutex::Autolock lock(mFrameEventHistoryMutex);
806 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
807 }
Marissa Wall61c58622018-07-18 10:12:20 -0700808 return NO_ERROR;
809}
810
Marissa Wall947d34e2019-03-29 14:03:53 -0700811void BufferStateLayer::HwcSlotGenerator::bufferErased(const client_cache_t& clientCacheId) {
812 std::lock_guard lock(mMutex);
813 if (!clientCacheId.isValid()) {
814 ALOGE("invalid process, failed to erase buffer");
815 return;
816 }
817 eraseBufferLocked(clientCacheId);
818}
819
rnleeed20fa42021-08-10 18:00:03 -0700820int BufferStateLayer::HwcSlotGenerator::getHwcCacheSlot(const client_cache_t& clientCacheId) {
Marissa Wall947d34e2019-03-29 14:03:53 -0700821 std::lock_guard<std::mutex> lock(mMutex);
822 auto itr = mCachedBuffers.find(clientCacheId);
823 if (itr == mCachedBuffers.end()) {
824 return addCachedBuffer(clientCacheId);
825 }
826 auto& [hwcCacheSlot, counter] = itr->second;
827 counter = mCounter++;
828 return hwcCacheSlot;
829}
830
rnleeed20fa42021-08-10 18:00:03 -0700831int BufferStateLayer::HwcSlotGenerator::addCachedBuffer(const client_cache_t& clientCacheId)
Marissa Wall947d34e2019-03-29 14:03:53 -0700832 REQUIRES(mMutex) {
833 if (!clientCacheId.isValid()) {
834 ALOGE("invalid process, returning invalid slot");
835 return BufferQueue::INVALID_BUFFER_SLOT;
836 }
837
838 ClientCache::getInstance().registerErasedRecipient(clientCacheId, wp<ErasedRecipient>(this));
839
rnleeed20fa42021-08-10 18:00:03 -0700840 int hwcCacheSlot = getFreeHwcCacheSlot();
Marissa Wall947d34e2019-03-29 14:03:53 -0700841 mCachedBuffers[clientCacheId] = {hwcCacheSlot, mCounter++};
842 return hwcCacheSlot;
843}
844
rnleeed20fa42021-08-10 18:00:03 -0700845int BufferStateLayer::HwcSlotGenerator::getFreeHwcCacheSlot() REQUIRES(mMutex) {
Marissa Wall947d34e2019-03-29 14:03:53 -0700846 if (mFreeHwcCacheSlots.empty()) {
847 evictLeastRecentlyUsed();
848 }
849
rnleeed20fa42021-08-10 18:00:03 -0700850 int hwcCacheSlot = mFreeHwcCacheSlots.top();
Marissa Wall947d34e2019-03-29 14:03:53 -0700851 mFreeHwcCacheSlots.pop();
852 return hwcCacheSlot;
853}
854
855void BufferStateLayer::HwcSlotGenerator::evictLeastRecentlyUsed() REQUIRES(mMutex) {
856 uint64_t minCounter = UINT_MAX;
857 client_cache_t minClientCacheId = {};
858 for (const auto& [clientCacheId, slotCounter] : mCachedBuffers) {
859 const auto& [hwcCacheSlot, counter] = slotCounter;
860 if (counter < minCounter) {
861 minCounter = counter;
862 minClientCacheId = clientCacheId;
863 }
864 }
865 eraseBufferLocked(minClientCacheId);
866
867 ClientCache::getInstance().unregisterErasedRecipient(minClientCacheId, this);
868}
869
870void BufferStateLayer::HwcSlotGenerator::eraseBufferLocked(const client_cache_t& clientCacheId)
871 REQUIRES(mMutex) {
872 auto itr = mCachedBuffers.find(clientCacheId);
873 if (itr == mCachedBuffers.end()) {
874 return;
875 }
876 auto& [hwcCacheSlot, counter] = itr->second;
877
878 // TODO send to hwc cache and resources
879
880 mFreeHwcCacheSlots.push(hwcCacheSlot);
881 mCachedBuffers.erase(clientCacheId);
882}
chaviw4244e032019-09-04 11:27:49 -0700883
884void BufferStateLayer::gatherBufferInfo() {
chaviwdebadb82020-03-26 14:57:24 -0700885 BufferLayer::gatherBufferInfo();
chaviw4244e032019-09-04 11:27:49 -0700886
chaviwdebadb82020-03-26 14:57:24 -0700887 const State& s(getDrawingState());
chaviw4244e032019-09-04 11:27:49 -0700888 mBufferInfo.mDesiredPresentTime = s.desiredPresentTime;
889 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(s.acquireFence);
890 mBufferInfo.mFence = s.acquireFence;
chaviw766c9c52021-02-10 17:36:47 -0800891 mBufferInfo.mTransform = s.bufferTransform;
Robert Carr167bdde2021-07-28 11:26:51 -0700892 auto lastDataspace = mBufferInfo.mDataspace;
chaviw4244e032019-09-04 11:27:49 -0700893 mBufferInfo.mDataspace = translateDataspace(s.dataspace);
Robert Carr167bdde2021-07-28 11:26:51 -0700894 if (lastDataspace != mBufferInfo.mDataspace) {
895 mFlinger->mSomeDataspaceChanged = true;
896 }
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700897 mBufferInfo.mCrop = computeBufferCrop(s);
chaviw4244e032019-09-04 11:27:49 -0700898 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
899 mBufferInfo.mSurfaceDamage = s.surfaceDamageRegion;
900 mBufferInfo.mHdrMetadata = s.hdrMetadata;
901 mBufferInfo.mApi = s.api;
chaviw4244e032019-09-04 11:27:49 -0700902 mBufferInfo.mTransformToDisplayInverse = s.transformToDisplayInverse;
chaviwf83ce182019-09-12 14:43:08 -0700903 mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(s.clientCacheId);
chaviw4244e032019-09-04 11:27:49 -0700904}
905
Robert Carr916b0362020-10-06 13:53:03 -0700906uint32_t BufferStateLayer::getEffectiveScalingMode() const {
907 return NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
908}
909
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700910Rect BufferStateLayer::computeBufferCrop(const State& s) {
chaviwf3f40fe2021-04-27 15:54:02 -0500911 if (s.buffer && !s.bufferCrop.isEmpty()) {
912 Rect bufferCrop;
913 s.buffer->getBuffer()->getBounds().intersect(s.bufferCrop, &bufferCrop);
914 return bufferCrop;
915 } else if (s.buffer) {
Alec Mouria90a5702021-04-16 16:36:21 +0000916 return s.buffer->getBuffer()->getBounds();
chaviwf3f40fe2021-04-27 15:54:02 -0500917 } else {
918 return s.bufferCrop;
chaviw4244e032019-09-04 11:27:49 -0700919 }
chaviw4244e032019-09-04 11:27:49 -0700920}
921
chaviwb4c6e582019-08-16 14:35:07 -0700922sp<Layer> BufferStateLayer::createClone() {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700923 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, 0, 0, LayerMetadata());
chaviwb4c6e582019-08-16 14:35:07 -0700924 args.textureName = mTextureName;
Lloyd Pique1c3a5eb2019-10-03 13:07:08 -0700925 sp<BufferStateLayer> layer = mFlinger->getFactory().createBufferStateLayer(args);
chaviwb4c6e582019-08-16 14:35:07 -0700926 layer->mHwcSlotGenerator = mHwcSlotGenerator;
927 layer->setInitialValuesForClone(this);
928 return layer;
929}
Valerie Hau92bf5482020-02-10 09:49:08 -0800930
Vishnu Naire7f79c52020-10-29 14:45:03 -0700931bool BufferStateLayer::bufferNeedsFiltering() const {
932 const State& s(getDrawingState());
933 if (!s.buffer) {
934 return false;
935 }
936
rnleeed20fa42021-08-10 18:00:03 -0700937 int32_t bufferWidth = s.buffer->getBuffer()->width;
938 int32_t bufferHeight = s.buffer->getBuffer()->height;
Vishnu Naire7f79c52020-10-29 14:45:03 -0700939
940 // Undo any transformations on the buffer and return the result.
chaviw766c9c52021-02-10 17:36:47 -0800941 if (s.bufferTransform & ui::Transform::ROT_90) {
Vishnu Naire7f79c52020-10-29 14:45:03 -0700942 std::swap(bufferWidth, bufferHeight);
943 }
944
945 if (s.transformToDisplayInverse) {
946 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
947 if (invTransform & ui::Transform::ROT_90) {
948 std::swap(bufferWidth, bufferHeight);
949 }
950 }
951
952 const Rect layerSize{getBounds()};
953 return layerSize.width() != bufferWidth || layerSize.height() != bufferHeight;
954}
Robert Carr7121caf2020-12-15 13:07:32 -0800955
Robert Carr7121caf2020-12-15 13:07:32 -0800956void BufferStateLayer::decrementPendingBufferCount() {
Vishnu Nair8eda69e2021-02-26 10:42:10 -0800957 int32_t pendingBuffers = --mPendingBufferTransactions;
958 tracePendingBufferCount(pendingBuffers);
Robert Carr7121caf2020-12-15 13:07:32 -0800959}
960
Vishnu Nair8eda69e2021-02-26 10:42:10 -0800961void BufferStateLayer::tracePendingBufferCount(int32_t pendingBuffers) {
962 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
Robert Carr7121caf2020-12-15 13:07:32 -0800963}
964
Robert Carr7121caf2020-12-15 13:07:32 -0800965
chaviw39d01472021-04-08 14:26:24 -0500966/*
967 * We don't want to send the layer's transform to input, but rather the
968 * parent's transform. This is because BufferStateLayer's transform is
969 * information about how the buffer is placed on screen. The parent's
970 * transform makes more sense to send since it's information about how the
971 * layer is placed on screen. This transform is used by input to determine
972 * how to go from screen space back to window space.
973 */
974ui::Transform BufferStateLayer::getInputTransform() const {
975 sp<Layer> parent = mDrawingParent.promote();
976 if (parent == nullptr) {
977 return ui::Transform();
978 }
979
980 return parent->getTransform();
981}
982
983/**
984 * Similar to getInputTransform, we need to update the bounds to include the transform.
985 * This is because bounds for BSL doesn't include buffer transform, where the input assumes
986 * that's already included.
987 */
988Rect BufferStateLayer::getInputBounds() const {
989 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
990 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
991 return bufferBounds;
992 }
993 return mDrawingState.transform.transform(bufferBounds);
994}
995
Marissa Wall61c58622018-07-18 10:12:20 -0700996} // namespace android