blob: 8b772f055db6dc13183f463d472c7d32f9b0eb62 [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"
20
Marissa Wall61c58622018-07-18 10:12:20 -070021//#define LOG_NDEBUG 0
22#undef LOG_TAG
23#define LOG_TAG "BufferStateLayer"
24#define ATRACE_TAG ATRACE_TAG_GRAPHICS
25
Lloyd Pique9755fb72019-03-26 14:44:40 -070026#include "BufferStateLayer.h"
27
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080028#include <limits>
Marissa Wall61c58622018-07-18 10:12:20 -070029
Lloyd Pique9755fb72019-03-26 14:44:40 -070030#include <compositionengine/LayerFECompositionState.h>
Marissa Wall947d34e2019-03-29 14:03:53 -070031#include <gui/BufferQueue.h>
Marissa Wall61c58622018-07-18 10:12:20 -070032#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070033#include <renderengine/Image.h>
Marissa Wall61c58622018-07-18 10:12:20 -070034
Vishnu Nairfa247b12020-02-11 08:58:26 -080035#include "EffectLayer.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080036#include "TimeStats/TimeStats.h"
Valerie Hau0bc09152018-12-20 07:42:47 -080037
Marissa Wall61c58622018-07-18 10:12:20 -070038namespace android {
39
Lloyd Pique42ab75e2018-09-12 20:46:03 -070040// clang-format off
41const std::array<float, 16> BufferStateLayer::IDENTITY_MATRIX{
42 1, 0, 0, 0,
43 0, 1, 0, 0,
44 0, 0, 1, 0,
45 0, 0, 0, 1
46};
47// clang-format on
Marissa Wall61c58622018-07-18 10:12:20 -070048
Marissa Wall947d34e2019-03-29 14:03:53 -070049BufferStateLayer::BufferStateLayer(const LayerCreationArgs& args)
50 : BufferLayer(args), mHwcSlotGenerator(new HwcSlotGenerator()) {
Marissa Wall3ff826c2019-02-07 11:58:25 -080051 mCurrentState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nair60356342018-11-13 13:00:45 -080052}
Marissa Wall61c58622018-07-18 10:12:20 -070053
Alec Mouri4545a8a2019-08-08 20:05:32 -070054BufferStateLayer::~BufferStateLayer() {
chaviwb4c6e582019-08-16 14:35:07 -070055 // The original layer and the clone layer share the same texture and buffer. Therefore, only
56 // one of the layers, in this case the original layer, needs to handle the deletion. The
57 // original layer and the clone should be removed at the same time so there shouldn't be any
58 // issue with the clone layer trying to use the texture.
59 if (mBufferInfo.mBuffer != nullptr && !isClone()) {
chaviwd62d3062019-09-04 14:48:02 -070060 // Ensure that mBuffer is uncached from RenderEngine here, as
Alec Mouri4545a8a2019-08-08 20:05:32 -070061 // RenderEngine may have been using the buffer as an external texture
62 // after the client uncached the buffer.
63 auto& engine(mFlinger->getRenderEngine());
chaviwd62d3062019-09-04 14:48:02 -070064 engine.unbindExternalTextureBuffer(mBufferInfo.mBuffer->getId());
Alec Mouri4545a8a2019-08-08 20:05:32 -070065 }
66}
67
Robert Carr8d958532020-11-10 14:09:16 -080068status_t BufferStateLayer::addReleaseFence(const sp<CallbackHandle>& ch,
69 const sp<Fence>& fence) {
70 if (ch == nullptr) {
71 return OK;
72 }
73 if (!ch->previousReleaseFence.get()) {
74 ch->previousReleaseFence = fence;
75 return OK;
76 }
77
78 // Below logic is lifted from ConsumerBase.cpp:
79 // Check status of fences first because merging is expensive.
80 // Merging an invalid fence with any other fence results in an
81 // invalid fence.
82 auto currentStatus = ch->previousReleaseFence->getStatus();
83 if (currentStatus == Fence::Status::Invalid) {
84 ALOGE("Existing fence has invalid state, layer: %s", mName.c_str());
85 return BAD_VALUE;
86 }
87
88 auto incomingStatus = fence->getStatus();
89 if (incomingStatus == Fence::Status::Invalid) {
90 ALOGE("New fence has invalid state, layer: %s", mName.c_str());
91 ch->previousReleaseFence = fence;
92 return BAD_VALUE;
93 }
94
95 // If both fences are signaled or both are unsignaled, we need to merge
96 // them to get an accurate timestamp.
97 if (currentStatus == incomingStatus) {
98 char fenceName[32] = {};
99 snprintf(fenceName, 32, "%.28s", mName.c_str());
100 sp<Fence> mergedFence = Fence::merge(
101 fenceName, ch->previousReleaseFence, fence);
102 if (!mergedFence.get()) {
103 ALOGE("failed to merge release fences, layer: %s", mName.c_str());
104 // synchronization is broken, the best we can do is hope fences
105 // signal in order so the new fence will act like a union
106 ch->previousReleaseFence = fence;
107 return BAD_VALUE;
108 }
109 ch->previousReleaseFence = mergedFence;
110 } else if (incomingStatus == Fence::Status::Unsignaled) {
111 // If one fence has signaled and the other hasn't, the unsignaled
112 // fence will approximately correspond with the correct timestamp.
113 // There's a small race if both fences signal at about the same time
114 // and their statuses are retrieved with unfortunate timing. However,
115 // by this point, they will have both signaled and only the timestamp
116 // will be slightly off; any dependencies after this point will
117 // already have been met.
118 ch->previousReleaseFence = fence;
119 }
120 // else if (currentStatus == Fence::Status::Unsignaled) is a no-op.
121
122 return OK;
123}
124
Marissa Wall61c58622018-07-18 10:12:20 -0700125// -----------------------------------------------------------------------
126// Interface implementation for Layer
127// -----------------------------------------------------------------------
Marissa Wallfda30bb2018-10-12 11:34:28 -0700128void BufferStateLayer::onLayerDisplayed(const sp<Fence>& releaseFence) {
Robert Carr8d958532020-11-10 14:09:16 -0800129 if (!releaseFence->isValid()) {
130 return;
131 }
Marissa Wall5a68a772018-12-22 17:43:42 -0800132 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
133 // buffer that was presented on this layer. The first transaction that came in this frame that
134 // replaced the previous buffer on this layer needs this release fence, because the fence will
135 // let the client know when that previous buffer is removed from the screen.
136 //
137 // Every other transaction on this layer does not need a release fence because no other
138 // Transactions that were set on this layer this frame are going to have their preceeding buffer
139 // removed from the display this frame.
140 //
141 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
142 // buffer so it doesn't need a previous release fence because the layer still needs the previous
143 // buffer. The second transaction contains a buffer so it needs a previous release fence because
144 // the previous buffer will be released this frame. The third transaction also contains a
145 // buffer. It replaces the buffer in the second transaction. The buffer in the second
146 // transaction will now no longer be presented so it is released immediately and the third
147 // transaction doesn't need a previous release fence.
Robert Carr8d958532020-11-10 14:09:16 -0800148 sp<CallbackHandle> ch;
Marissa Wall5a68a772018-12-22 17:43:42 -0800149 for (auto& handle : mDrawingState.callbackHandles) {
150 if (handle->releasePreviousBuffer) {
Robert Carr8d958532020-11-10 14:09:16 -0800151 ch = handle;
Marissa Wall5a68a772018-12-22 17:43:42 -0800152 break;
153 }
154 }
Robert Carr8d958532020-11-10 14:09:16 -0800155 auto status = addReleaseFence(ch, releaseFence);
156 if (status != OK) {
157 ALOGE("Failed to add release fence for layer %s", getName().c_str());
158 }
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700159
Valerie Haubf784642020-01-29 07:25:23 -0800160 mPreviousReleaseFence = releaseFence;
161
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700162 // Prevent tracing the same release multiple times.
163 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700164 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
165 }
Marissa Wall61c58622018-07-18 10:12:20 -0700166}
167
Valerie Haubf784642020-01-29 07:25:23 -0800168void BufferStateLayer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700169 for (const auto& handle : mDrawingState.callbackHandles) {
170 handle->transformHint = mTransformHint;
Valerie Hau871d6352020-01-29 08:44:02 -0800171 handle->dequeueReadyTime = dequeueReadyTime;
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700172 }
173
Marissa Wallefb71af2019-06-27 14:45:53 -0700174 mFlinger->getTransactionCompletedThread().finalizePendingCallbackHandles(
Marissa Wall5a68a772018-12-22 17:43:42 -0800175 mDrawingState.callbackHandles);
176
177 mDrawingState.callbackHandles = {};
Valerie Haubf784642020-01-29 07:25:23 -0800178
179 const sp<Fence>& releaseFence(mPreviousReleaseFence);
180 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(releaseFence);
181 {
182 Mutex::Autolock lock(mFrameEventHistoryMutex);
183 if (mPreviousFrameNumber != 0) {
184 mFrameEventHistory.addRelease(mPreviousFrameNumber, dequeueReadyTime,
185 std::move(releaseFenceTime));
186 }
187 }
Marissa Wall61c58622018-07-18 10:12:20 -0700188}
189
Valerie Hau871d6352020-01-29 08:44:02 -0800190void BufferStateLayer::finalizeFrameEventHistory(const std::shared_ptr<FenceTime>& glDoneFence,
191 const CompositorTiming& compositorTiming) {
192 for (const auto& handle : mDrawingState.callbackHandles) {
193 handle->gpuCompositionDoneFence = glDoneFence;
194 handle->compositorTiming = compositorTiming;
195 }
196}
197
Ana Krulec010d2192018-10-08 06:29:54 -0700198bool BufferStateLayer::shouldPresentNow(nsecs_t /*expectedPresentTime*/) const {
Marissa Wall61c58622018-07-18 10:12:20 -0700199 if (getSidebandStreamChanged() || getAutoRefresh()) {
200 return true;
201 }
202
Marissa Wall024a1912018-08-13 13:55:35 -0700203 return hasFrameUpdate();
Marissa Wall61c58622018-07-18 10:12:20 -0700204}
205
Marissa Walle2ffb422018-10-12 11:33:52 -0700206bool BufferStateLayer::willPresentCurrentTransaction() const {
207 // Returns true if the most recent Transaction applied to CurrentState will be presented.
Robert Carr321e83c2019-08-19 15:49:30 -0700208 return (getSidebandStreamChanged() || getAutoRefresh() ||
Valerie Hauaa194562019-02-05 16:21:38 -0800209 (mCurrentState.modified &&
Robert Carr321e83c2019-08-19 15:49:30 -0700210 (mCurrentState.buffer != nullptr || mCurrentState.bgColorLayer != nullptr))) &&
211 !mLayerDetached;
Marissa Wall61c58622018-07-18 10:12:20 -0700212}
213
Valerie Hau3282b3c2020-02-03 15:37:27 -0800214/* TODO: vhau uncomment once deferred transaction migration complete in
215 * WindowManager
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800216void BufferStateLayer::pushPendingState() {
217 if (!mCurrentState.modified) {
Marissa Wall61c58622018-07-18 10:12:20 -0700218 return;
219 }
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800220 mPendingStates.push_back(mCurrentState);
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700221 ATRACE_INT(mTransactionName.c_str(), mPendingStates.size());
Marissa Wall61c58622018-07-18 10:12:20 -0700222}
Valerie Hau3282b3c2020-02-03 15:37:27 -0800223*/
Marissa Wall61c58622018-07-18 10:12:20 -0700224
225bool BufferStateLayer::applyPendingStates(Layer::State* stateToCommit) {
Valerie Hau3282b3c2020-02-03 15:37:27 -0800226 mCurrentStateModified = mCurrentState.modified;
227 bool stateUpdateAvailable = Layer::applyPendingStates(stateToCommit);
Ady Abraham22c7b5c2020-09-22 19:33:40 -0700228 if (stateUpdateAvailable && mCallbackHandleAcquireTime != -1) {
Ady Abraham7f8a1e62020-09-28 16:09:35 -0700229 // Update the acquire fence time if we have a buffer
230 mSurfaceFrame->setAcquireFenceTime(mCallbackHandleAcquireTime);
Ady Abraham22c7b5c2020-09-22 19:33:40 -0700231 }
Valerie Hau3282b3c2020-02-03 15:37:27 -0800232 mCurrentStateModified = stateUpdateAvailable && mCurrentStateModified;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800233 mCurrentState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700234 return stateUpdateAvailable;
235}
236
Marissa Wall861616d2018-10-22 12:52:23 -0700237// Crop that applies to the window
238Rect BufferStateLayer::getCrop(const Layer::State& /*s*/) const {
239 return Rect::INVALID_RECT;
Marissa Wall61c58622018-07-18 10:12:20 -0700240}
241
242bool BufferStateLayer::setTransform(uint32_t transform) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800243 if (mCurrentState.transform == transform) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800244 mCurrentState.transform = transform;
245 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700246 setTransactionFlags(eTransactionNeeded);
247 return true;
248}
249
250bool BufferStateLayer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800251 if (mCurrentState.transformToDisplayInverse == transformToDisplayInverse) return false;
252 mCurrentState.sequence++;
253 mCurrentState.transformToDisplayInverse = transformToDisplayInverse;
254 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700255 setTransactionFlags(eTransactionNeeded);
256 return true;
257}
258
259bool BufferStateLayer::setCrop(const Rect& crop) {
Marissa Wall290ad082019-03-06 13:23:47 -0800260 Rect c = crop;
261 if (c.left < 0) {
262 c.left = 0;
263 }
264 if (c.top < 0) {
265 c.top = 0;
266 }
267 // If the width and/or height are < 0, make it [0, 0, -1, -1] so the equality comparision below
268 // treats all invalid rectangles the same.
269 if (!c.isValid()) {
270 c.makeInvalid();
271 }
272
273 if (mCurrentState.crop == c) return false;
Marissa Wall290ad082019-03-06 13:23:47 -0800274 mCurrentState.crop = c;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800275 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700276 setTransactionFlags(eTransactionNeeded);
277 return true;
278}
279
Marissa Wall861616d2018-10-22 12:52:23 -0700280bool BufferStateLayer::setFrame(const Rect& frame) {
281 int x = frame.left;
282 int y = frame.top;
283 int w = frame.getWidth();
284 int h = frame.getHeight();
285
Marissa Wall0f3242d2018-12-20 15:10:22 -0800286 if (x < 0) {
287 x = 0;
288 w = frame.right;
289 }
290
291 if (y < 0) {
292 y = 0;
293 h = frame.bottom;
294 }
295
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800296 if (mCurrentState.active.transform.tx() == x && mCurrentState.active.transform.ty() == y &&
297 mCurrentState.active.w == w && mCurrentState.active.h == h) {
Marissa Wall861616d2018-10-22 12:52:23 -0700298 return false;
299 }
300
301 if (!frame.isValid()) {
302 x = y = w = h = 0;
303 }
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800304 mCurrentState.active.transform.set(x, y);
305 mCurrentState.active.w = w;
306 mCurrentState.active.h = h;
Marissa Wall861616d2018-10-22 12:52:23 -0700307
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800308 mCurrentState.sequence++;
309 mCurrentState.modified = true;
Marissa Wall861616d2018-10-22 12:52:23 -0700310 setTransactionFlags(eTransactionNeeded);
311 return true;
312}
313
Valerie Hau871d6352020-01-29 08:44:02 -0800314bool BufferStateLayer::addFrameEvent(const sp<Fence>& acquireFence, nsecs_t postedTime,
315 nsecs_t desiredPresentTime) {
Valerie Haubf784642020-01-29 07:25:23 -0800316 Mutex::Autolock lock(mFrameEventHistoryMutex);
317 mAcquireTimeline.updateSignalTimes();
318 std::shared_ptr<FenceTime> acquireFenceTime =
319 std::make_shared<FenceTime>((acquireFence ? acquireFence : Fence::NO_FENCE));
320 NewFrameEventsEntry newTimestamps = {mCurrentState.frameNumber, postedTime, desiredPresentTime,
321 acquireFenceTime};
Valerie Hau871d6352020-01-29 08:44:02 -0800322 mFrameEventHistory.setProducerWantsEvents();
Valerie Haubf784642020-01-29 07:25:23 -0800323 mFrameEventHistory.addQueue(newTimestamps);
324 return true;
325}
326
327bool BufferStateLayer::setBuffer(const sp<GraphicBuffer>& buffer, const sp<Fence>& acquireFence,
328 nsecs_t postTime, nsecs_t desiredPresentTime,
Vishnu Nair6b7c5c92020-09-29 17:27:05 -0700329 const client_cache_t& clientCacheId, uint64_t frameNumber) {
Robert Carr0c1966e2020-10-19 12:12:08 -0700330 ATRACE_CALL();
331
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800332 if (mCurrentState.buffer) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700333 mReleasePreviousBuffer = true;
334 }
335
Vishnu Nair6b7c5c92020-09-29 17:27:05 -0700336 mCurrentState.frameNumber = frameNumber;
Valerie Hau2f54d642020-01-22 09:37:03 -0800337
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800338 mCurrentState.buffer = buffer;
Marissa Wall947d34e2019-03-29 14:03:53 -0700339 mCurrentState.clientCacheId = clientCacheId;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800340 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700341 setTransactionFlags(eTransactionNeeded);
Ady Abraham09bd3922019-04-08 10:44:56 -0700342
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800343 const int32_t layerId = getSequence();
Valerie Hau134651a2020-01-28 16:21:22 -0800344 mFlinger->mTimeStats->setPostTime(layerId, mCurrentState.frameNumber, getName().c_str(),
Alec Mouri9a29e672020-09-14 12:39:14 -0700345 mOwnerUid, postTime);
Valerie Hau871d6352020-01-29 08:44:02 -0800346 desiredPresentTime = desiredPresentTime <= 0 ? 0 : desiredPresentTime;
chaviwfa67b552019-08-12 16:51:55 -0700347 mCurrentState.desiredPresentTime = desiredPresentTime;
Ady Abraham09bd3922019-04-08 10:44:56 -0700348
Ady Abraham5def7332020-05-29 16:13:47 -0700349 mFlinger->mScheduler->recordLayerHistory(this, desiredPresentTime,
350 LayerHistory::LayerUpdateType::Buffer);
Ady Abraham09bd3922019-04-08 10:44:56 -0700351
Valerie Hau871d6352020-01-29 08:44:02 -0800352 addFrameEvent(acquireFence, postTime, desiredPresentTime);
Marissa Wall61c58622018-07-18 10:12:20 -0700353 return true;
354}
355
356bool BufferStateLayer::setAcquireFence(const sp<Fence>& fence) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700357 // The acquire fences of BufferStateLayers have already signaled before they are set
358 mCallbackHandleAcquireTime = fence->getSignalTime();
359
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800360 mCurrentState.acquireFence = fence;
361 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700362 setTransactionFlags(eTransactionNeeded);
363 return true;
364}
365
366bool BufferStateLayer::setDataspace(ui::Dataspace dataspace) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800367 if (mCurrentState.dataspace == dataspace) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800368 mCurrentState.dataspace = dataspace;
369 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700370 setTransactionFlags(eTransactionNeeded);
371 return true;
372}
373
374bool BufferStateLayer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800375 if (mCurrentState.hdrMetadata == hdrMetadata) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800376 mCurrentState.hdrMetadata = hdrMetadata;
377 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700378 setTransactionFlags(eTransactionNeeded);
379 return true;
380}
381
382bool BufferStateLayer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800383 mCurrentState.surfaceDamageRegion = surfaceDamage;
384 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700385 setTransactionFlags(eTransactionNeeded);
386 return true;
387}
388
389bool BufferStateLayer::setApi(int32_t api) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800390 if (mCurrentState.api == api) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800391 mCurrentState.api = api;
392 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700393 setTransactionFlags(eTransactionNeeded);
394 return true;
395}
396
397bool BufferStateLayer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800398 if (mCurrentState.sidebandStream == sidebandStream) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800399 mCurrentState.sidebandStream = sidebandStream;
400 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700401 setTransactionFlags(eTransactionNeeded);
402
403 if (!mSidebandStreamChanged.exchange(true)) {
404 // mSidebandStreamChanged was false
405 mFlinger->signalLayerUpdate();
406 }
407 return true;
408}
409
Marissa Walle2ffb422018-10-12 11:33:52 -0700410bool BufferStateLayer::setTransactionCompletedListeners(
411 const std::vector<sp<CallbackHandle>>& handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700412 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
Marissa Walle2ffb422018-10-12 11:33:52 -0700413 if (handles.empty()) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700414 mReleasePreviousBuffer = false;
Marissa Walle2ffb422018-10-12 11:33:52 -0700415 return false;
416 }
417
418 const bool willPresent = willPresentCurrentTransaction();
419
420 for (const auto& handle : handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700421 // If this transaction set a buffer on this layer, release its previous buffer
422 handle->releasePreviousBuffer = mReleasePreviousBuffer;
423
Marissa Walle2ffb422018-10-12 11:33:52 -0700424 // If this layer will be presented in this frame
425 if (willPresent) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700426 // If this transaction set an acquire fence on this layer, set its acquire time
427 handle->acquireTime = mCallbackHandleAcquireTime;
428
Marissa Walle2ffb422018-10-12 11:33:52 -0700429 // Notify the transaction completed thread that there is a pending latched callback
430 // handle
Marissa Wall5a68a772018-12-22 17:43:42 -0800431 mFlinger->getTransactionCompletedThread().registerPendingCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700432
433 // Store so latched time and release fence can be set
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800434 mCurrentState.callbackHandles.push_back(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700435
436 } else { // If this layer will NOT need to be relatched and presented this frame
437 // Notify the transaction completed thread this handle is done
Marissa Wallefb71af2019-06-27 14:45:53 -0700438 mFlinger->getTransactionCompletedThread().registerUnpresentedCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700439 }
440 }
441
Marissa Wallfda30bb2018-10-12 11:34:28 -0700442 mReleasePreviousBuffer = false;
443 mCallbackHandleAcquireTime = -1;
444
Marissa Walle2ffb422018-10-12 11:33:52 -0700445 return willPresent;
446}
447
Valerie Hau7618b232020-01-09 16:03:08 -0800448void BufferStateLayer::forceSendCallbacks() {
449 mFlinger->getTransactionCompletedThread().finalizePendingCallbackHandles(
450 mCurrentState.callbackHandles);
451}
452
Marissa Wall61c58622018-07-18 10:12:20 -0700453bool BufferStateLayer::setTransparentRegionHint(const Region& transparent) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800454 mCurrentState.transparentRegionHint = transparent;
455 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700456 setTransactionFlags(eTransactionNeeded);
457 return true;
458}
459
Marissa Wall861616d2018-10-22 12:52:23 -0700460Rect BufferStateLayer::getBufferSize(const State& s) const {
461 // for buffer state layers we use the display frame size as the buffer size.
462 if (getActiveWidth(s) < UINT32_MAX && getActiveHeight(s) < UINT32_MAX) {
463 return Rect(getActiveWidth(s), getActiveHeight(s));
Marissa Wall61c58622018-07-18 10:12:20 -0700464 }
465
Marissa Wall861616d2018-10-22 12:52:23 -0700466 // if the display frame is not defined, use the parent bounds as the buffer size.
467 const auto& p = mDrawingParent.promote();
468 if (p != nullptr) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800469 Rect parentBounds = Rect(p->getBounds(Region()));
Marissa Wall861616d2018-10-22 12:52:23 -0700470 if (!parentBounds.isEmpty()) {
471 return parentBounds;
472 }
473 }
474
Marissa Wall861616d2018-10-22 12:52:23 -0700475 return Rect::INVALID_RECT;
Marissa Wall61c58622018-07-18 10:12:20 -0700476}
Vishnu Nair4351ad52019-02-11 14:13:02 -0800477
478FloatRect BufferStateLayer::computeSourceBounds(const FloatRect& parentBounds) const {
479 const State& s(getDrawingState());
480 // for buffer state layers we use the display frame size as the buffer size.
481 if (getActiveWidth(s) < UINT32_MAX && getActiveHeight(s) < UINT32_MAX) {
482 return FloatRect(0, 0, getActiveWidth(s), getActiveHeight(s));
483 }
484
485 // if the display frame is not defined, use the parent bounds as the buffer size.
486 return parentBounds;
487}
488
Marissa Wall61c58622018-07-18 10:12:20 -0700489// -----------------------------------------------------------------------
490
491// -----------------------------------------------------------------------
492// Interface implementation for BufferLayer
493// -----------------------------------------------------------------------
494bool BufferStateLayer::fenceHasSignaled() const {
Alec Mouri91f6df32020-01-30 08:48:58 -0800495 const bool fenceSignaled =
496 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
497 if (!fenceSignaled) {
498 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
499 TimeStats::LatchSkipReason::LateAcquire);
500 }
501
502 return fenceSignaled;
Marissa Wall61c58622018-07-18 10:12:20 -0700503}
504
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700505bool BufferStateLayer::framePresentTimeIsCurrent(nsecs_t expectedPresentTime) const {
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700506 if (!hasFrameUpdate() || isRemovedFromCurrentState()) {
507 return true;
508 }
509
chaviwfa67b552019-08-12 16:51:55 -0700510 return mCurrentState.desiredPresentTime <= expectedPresentTime;
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700511}
512
Valerie Hau871d6352020-01-29 08:44:02 -0800513bool BufferStateLayer::onPreComposition(nsecs_t refreshStartTime) {
514 for (const auto& handle : mDrawingState.callbackHandles) {
515 handle->refreshStartTime = refreshStartTime;
516 }
517 return BufferLayer::onPreComposition(refreshStartTime);
518}
519
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700520uint64_t BufferStateLayer::getFrameNumber(nsecs_t /*expectedPresentTime*/) const {
Valerie Hau134651a2020-01-28 16:21:22 -0800521 return mDrawingState.frameNumber;
Marissa Wall61c58622018-07-18 10:12:20 -0700522}
523
Robert Carrfe1209c2020-02-11 12:25:35 -0800524/**
525 * This is the frameNumber used for deferred transaction signalling. We need to use this because
526 * of cases where we defer a transaction for a surface to itself. In the BLAST world this
527 * may not make a huge amount of sense (Why not just merge the Buffer transaction with the
528 * deferred transaction?) but this is an important legacy use case, for example moving
529 * a window at the same time it draws makes use of this kind of technique. So anyway
530 * imagine we have something like this:
531 *
532 * Transaction { // containing
533 * Buffer -> frameNumber = 2
534 * DeferTransactionUntil -> frameNumber = 2
535 * Random other stuff
536 * }
537 * Now imagine getHeadFrameNumber returned mDrawingState.mFrameNumber (or mCurrentFrameNumber).
538 * Prior to doTransaction SurfaceFlinger will call notifyAvailableFrames, but because we
539 * haven't swapped mCurrentState to mDrawingState yet we will think the sync point
540 * is not ready. So we will return false from applyPendingState and not swap
541 * current state to drawing state. But because we don't swap current state
542 * to drawing state the number will never update and we will be stuck. This way
543 * we can see we need to return the frame number for the buffer we are about
544 * to apply.
545 */
546uint64_t BufferStateLayer::getHeadFrameNumber(nsecs_t /* expectedPresentTime */) const {
547 return mCurrentState.frameNumber;
548}
549
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800550void BufferStateLayer::setAutoRefresh(bool autoRefresh) {
551 if (!mAutoRefresh.exchange(autoRefresh)) {
552 mFlinger->signalLayerUpdate();
553 }
Marissa Wall61c58622018-07-18 10:12:20 -0700554}
555
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800556bool BufferStateLayer::latchSidebandStream(bool& recomputeVisibleRegions) {
Marissa Wall61c58622018-07-18 10:12:20 -0700557 if (mSidebandStreamChanged.exchange(false)) {
558 const State& s(getDrawingState());
559 // mSidebandStreamChanged was true
Lloyd Pique0b785d82018-12-04 17:25:27 -0800560 mSidebandStream = s.sidebandStream;
Lloyd Piquede196652020-01-22 17:29:58 -0800561 editCompositionState()->sidebandStream = mSidebandStream;
Lloyd Pique0b785d82018-12-04 17:25:27 -0800562 if (mSidebandStream != nullptr) {
Marissa Wall61c58622018-07-18 10:12:20 -0700563 setTransactionFlags(eTransactionNeeded);
564 mFlinger->setTransactionFlags(eTraversalNeeded);
565 }
566 recomputeVisibleRegions = true;
567
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800568 return true;
Marissa Wall61c58622018-07-18 10:12:20 -0700569 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800570 return false;
Marissa Wall61c58622018-07-18 10:12:20 -0700571}
572
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800573bool BufferStateLayer::hasFrameUpdate() const {
Valerie Hauaa194562019-02-05 16:21:38 -0800574 const State& c(getCurrentState());
575 return mCurrentStateModified && (c.buffer != nullptr || c.bgColorLayer != nullptr);
Marissa Wall61c58622018-07-18 10:12:20 -0700576}
577
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700578status_t BufferStateLayer::updateTexImage(bool& /*recomputeVisibleRegions*/, nsecs_t latchTime,
579 nsecs_t /*expectedPresentTime*/) {
Marissa Wall61c58622018-07-18 10:12:20 -0700580 const State& s(getDrawingState());
581
582 if (!s.buffer) {
Valerie Hauaa194562019-02-05 16:21:38 -0800583 if (s.bgColorLayer) {
584 for (auto& handle : mDrawingState.callbackHandles) {
585 handle->latchTime = latchTime;
586 }
587 }
Marissa Wall61c58622018-07-18 10:12:20 -0700588 return NO_ERROR;
589 }
590
Marissa Wall5a68a772018-12-22 17:43:42 -0800591 for (auto& handle : mDrawingState.callbackHandles) {
592 handle->latchTime = latchTime;
Valerie Hau871d6352020-01-29 08:44:02 -0800593 handle->frameNumber = mDrawingState.frameNumber;
Marissa Wall5a68a772018-12-22 17:43:42 -0800594 }
Marissa Walle2ffb422018-10-12 11:33:52 -0700595
Vishnu Nairea0de002020-11-17 17:42:37 -0800596 const int32_t layerId = getSequence();
Valerie Hau134651a2020-01-28 16:21:22 -0800597 mFlinger->mTimeStats->setAcquireFence(layerId, mDrawingState.frameNumber,
chaviw95631e32020-06-09 13:43:32 -0700598 std::make_shared<FenceTime>(mDrawingState.acquireFence));
Valerie Hau134651a2020-01-28 16:21:22 -0800599 mFlinger->mTimeStats->setLatchTime(layerId, mDrawingState.frameNumber, latchTime);
Marissa Wall61c58622018-07-18 10:12:20 -0700600
Marissa Wall16c112d2019-03-20 13:21:13 -0700601 mCurrentStateModified = false;
602
Marissa Wall61c58622018-07-18 10:12:20 -0700603 return NO_ERROR;
604}
605
606status_t BufferStateLayer::updateActiveBuffer() {
607 const State& s(getDrawingState());
608
609 if (s.buffer == nullptr) {
610 return BAD_VALUE;
611 }
612
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700613 mPreviousBufferId = getCurrentBufferId();
chaviwd62d3062019-09-04 14:48:02 -0700614 mBufferInfo.mBuffer = s.buffer;
615 mBufferInfo.mFence = s.acquireFence;
Marissa Wall61c58622018-07-18 10:12:20 -0700616
617 return NO_ERROR;
618}
619
Valerie Haubf784642020-01-29 07:25:23 -0800620status_t BufferStateLayer::updateFrameNumber(nsecs_t latchTime) {
Marissa Wall61c58622018-07-18 10:12:20 -0700621 // TODO(marissaw): support frame history events
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700622 mPreviousFrameNumber = mCurrentFrameNumber;
Valerie Hau134651a2020-01-28 16:21:22 -0800623 mCurrentFrameNumber = mDrawingState.frameNumber;
Valerie Haubf784642020-01-29 07:25:23 -0800624 {
625 Mutex::Autolock lock(mFrameEventHistoryMutex);
626 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
627 }
Marissa Wall61c58622018-07-18 10:12:20 -0700628 return NO_ERROR;
629}
630
Marissa Wall947d34e2019-03-29 14:03:53 -0700631void BufferStateLayer::HwcSlotGenerator::bufferErased(const client_cache_t& clientCacheId) {
632 std::lock_guard lock(mMutex);
633 if (!clientCacheId.isValid()) {
634 ALOGE("invalid process, failed to erase buffer");
635 return;
636 }
637 eraseBufferLocked(clientCacheId);
638}
639
640uint32_t BufferStateLayer::HwcSlotGenerator::getHwcCacheSlot(const client_cache_t& clientCacheId) {
641 std::lock_guard<std::mutex> lock(mMutex);
642 auto itr = mCachedBuffers.find(clientCacheId);
643 if (itr == mCachedBuffers.end()) {
644 return addCachedBuffer(clientCacheId);
645 }
646 auto& [hwcCacheSlot, counter] = itr->second;
647 counter = mCounter++;
648 return hwcCacheSlot;
649}
650
651uint32_t BufferStateLayer::HwcSlotGenerator::addCachedBuffer(const client_cache_t& clientCacheId)
652 REQUIRES(mMutex) {
653 if (!clientCacheId.isValid()) {
654 ALOGE("invalid process, returning invalid slot");
655 return BufferQueue::INVALID_BUFFER_SLOT;
656 }
657
658 ClientCache::getInstance().registerErasedRecipient(clientCacheId, wp<ErasedRecipient>(this));
659
660 uint32_t hwcCacheSlot = getFreeHwcCacheSlot();
661 mCachedBuffers[clientCacheId] = {hwcCacheSlot, mCounter++};
662 return hwcCacheSlot;
663}
664
665uint32_t BufferStateLayer::HwcSlotGenerator::getFreeHwcCacheSlot() REQUIRES(mMutex) {
666 if (mFreeHwcCacheSlots.empty()) {
667 evictLeastRecentlyUsed();
668 }
669
670 uint32_t hwcCacheSlot = mFreeHwcCacheSlots.top();
671 mFreeHwcCacheSlots.pop();
672 return hwcCacheSlot;
673}
674
675void BufferStateLayer::HwcSlotGenerator::evictLeastRecentlyUsed() REQUIRES(mMutex) {
676 uint64_t minCounter = UINT_MAX;
677 client_cache_t minClientCacheId = {};
678 for (const auto& [clientCacheId, slotCounter] : mCachedBuffers) {
679 const auto& [hwcCacheSlot, counter] = slotCounter;
680 if (counter < minCounter) {
681 minCounter = counter;
682 minClientCacheId = clientCacheId;
683 }
684 }
685 eraseBufferLocked(minClientCacheId);
686
687 ClientCache::getInstance().unregisterErasedRecipient(minClientCacheId, this);
688}
689
690void BufferStateLayer::HwcSlotGenerator::eraseBufferLocked(const client_cache_t& clientCacheId)
691 REQUIRES(mMutex) {
692 auto itr = mCachedBuffers.find(clientCacheId);
693 if (itr == mCachedBuffers.end()) {
694 return;
695 }
696 auto& [hwcCacheSlot, counter] = itr->second;
697
698 // TODO send to hwc cache and resources
699
700 mFreeHwcCacheSlots.push(hwcCacheSlot);
701 mCachedBuffers.erase(clientCacheId);
702}
chaviw4244e032019-09-04 11:27:49 -0700703
704void BufferStateLayer::gatherBufferInfo() {
chaviwdebadb82020-03-26 14:57:24 -0700705 BufferLayer::gatherBufferInfo();
chaviw4244e032019-09-04 11:27:49 -0700706
chaviwdebadb82020-03-26 14:57:24 -0700707 const State& s(getDrawingState());
chaviw4244e032019-09-04 11:27:49 -0700708 mBufferInfo.mDesiredPresentTime = s.desiredPresentTime;
709 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(s.acquireFence);
710 mBufferInfo.mFence = s.acquireFence;
chaviw4244e032019-09-04 11:27:49 -0700711 mBufferInfo.mTransform = s.transform;
712 mBufferInfo.mDataspace = translateDataspace(s.dataspace);
713 mBufferInfo.mCrop = computeCrop(s);
714 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
715 mBufferInfo.mSurfaceDamage = s.surfaceDamageRegion;
716 mBufferInfo.mHdrMetadata = s.hdrMetadata;
717 mBufferInfo.mApi = s.api;
chaviw4244e032019-09-04 11:27:49 -0700718 mBufferInfo.mTransformToDisplayInverse = s.transformToDisplayInverse;
chaviwf83ce182019-09-12 14:43:08 -0700719 mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(s.clientCacheId);
chaviw4244e032019-09-04 11:27:49 -0700720}
721
Robert Carr916b0362020-10-06 13:53:03 -0700722uint32_t BufferStateLayer::getEffectiveScalingMode() const {
723 return NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
724}
725
chaviw4244e032019-09-04 11:27:49 -0700726Rect BufferStateLayer::computeCrop(const State& s) {
727 if (s.crop.isEmpty() && s.buffer) {
728 return s.buffer->getBounds();
729 } else if (s.buffer) {
730 Rect crop = s.crop;
731 crop.left = std::max(crop.left, 0);
732 crop.top = std::max(crop.top, 0);
733 uint32_t bufferWidth = s.buffer->getWidth();
734 uint32_t bufferHeight = s.buffer->getHeight();
735 if (bufferHeight <= std::numeric_limits<int32_t>::max() &&
736 bufferWidth <= std::numeric_limits<int32_t>::max()) {
737 crop.right = std::min(crop.right, static_cast<int32_t>(bufferWidth));
738 crop.bottom = std::min(crop.bottom, static_cast<int32_t>(bufferHeight));
739 }
740 if (!crop.isValid()) {
741 // Crop rect is out of bounds, return whole buffer
742 return s.buffer->getBounds();
743 }
744 return crop;
745 }
746 return s.crop;
747}
748
chaviwb4c6e582019-08-16 14:35:07 -0700749sp<Layer> BufferStateLayer::createClone() {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700750 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, 0, 0, LayerMetadata());
chaviwb4c6e582019-08-16 14:35:07 -0700751 args.textureName = mTextureName;
Lloyd Pique1c3a5eb2019-10-03 13:07:08 -0700752 sp<BufferStateLayer> layer = mFlinger->getFactory().createBufferStateLayer(args);
chaviwb4c6e582019-08-16 14:35:07 -0700753 layer->mHwcSlotGenerator = mHwcSlotGenerator;
754 layer->setInitialValuesForClone(this);
755 return layer;
756}
Valerie Hau92bf5482020-02-10 09:49:08 -0800757
758Layer::RoundedCornerState BufferStateLayer::getRoundedCornerState() const {
759 const auto& p = mDrawingParent.promote();
760 if (p != nullptr) {
761 RoundedCornerState parentState = p->getRoundedCornerState();
762 if (parentState.radius > 0) {
763 ui::Transform t = getActiveTransform(getDrawingState());
764 t = t.inverse();
765 parentState.cropRect = t.transform(parentState.cropRect);
766 // The rounded corners shader only accepts 1 corner radius for performance reasons,
767 // but a transform matrix can define horizontal and vertical scales.
768 // Let's take the average between both of them and pass into the shader, practically we
769 // never do this type of transformation on windows anyway.
770 parentState.radius *= (t[0][0] + t[1][1]) / 2.0f;
771 return parentState;
772 }
773 }
774 const float radius = getDrawingState().cornerRadius;
775 const State& s(getDrawingState());
776 if (radius <= 0 || (getActiveWidth(s) == UINT32_MAX && getActiveHeight(s) == UINT32_MAX))
777 return RoundedCornerState();
778 return RoundedCornerState(FloatRect(static_cast<float>(s.active.transform.tx()),
779 static_cast<float>(s.active.transform.ty()),
780 static_cast<float>(s.active.transform.tx() + s.active.w),
781 static_cast<float>(s.active.transform.ty() + s.active.h)),
782 radius);
783}
Vishnu Naire7f79c52020-10-29 14:45:03 -0700784
785bool BufferStateLayer::bufferNeedsFiltering() const {
786 const State& s(getDrawingState());
787 if (!s.buffer) {
788 return false;
789 }
790
791 uint32_t bufferWidth = s.buffer->width;
792 uint32_t bufferHeight = s.buffer->height;
793
794 // Undo any transformations on the buffer and return the result.
795 if (s.transform & ui::Transform::ROT_90) {
796 std::swap(bufferWidth, bufferHeight);
797 }
798
799 if (s.transformToDisplayInverse) {
800 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
801 if (invTransform & ui::Transform::ROT_90) {
802 std::swap(bufferWidth, bufferHeight);
803 }
804 }
805
806 const Rect layerSize{getBounds()};
807 return layerSize.width() != bufferWidth || layerSize.height() != bufferHeight;
808}
Marissa Wall61c58622018-07-18 10:12:20 -0700809} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800810
811// TODO(b/129481165): remove the #pragma below and fix conversion issues
812#pragma clang diagnostic pop // ignored "-Wconversion"