blob: aae393155a6c1f5f3a69b87913ae7407c723eb32 [file] [log] [blame]
David Sodman0c69cad2017-08-21 12:12:51 -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 "BufferLayer"
20#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
22#include "BufferLayer.h"
23#include "Colorizer.h"
24#include "DisplayDevice.h"
25#include "LayerRejecter.h"
26#include "clz.h"
27
28#include "RenderEngine/RenderEngine.h"
29
30#include <gui/BufferItem.h>
31#include <gui/BufferQueue.h>
32#include <gui/LayerDebugInfo.h>
33#include <gui/Surface.h>
34
35#include <ui/DebugUtils.h>
36
37#include <utils/Errors.h>
38#include <utils/Log.h>
39#include <utils/NativeHandle.h>
40#include <utils/StopWatch.h>
41#include <utils/Trace.h>
42
43#include <cutils/compiler.h>
44#include <cutils/native_handle.h>
45#include <cutils/properties.h>
46
47#include <math.h>
48#include <stdlib.h>
49#include <mutex>
50
51namespace android {
52
53BufferLayer::BufferLayer(SurfaceFlinger* flinger, const sp<Client>& client, const String8& name,
54 uint32_t w, uint32_t h, uint32_t flags)
55 : Layer(flinger, client, name, w, h, flags),
Chia-I Wub28c6742017-12-27 10:59:54 -080056 mConsumer(nullptr),
Ivan Lozanoeb13f9e2017-11-09 12:39:31 -080057 mTextureName(UINT32_MAX),
David Sodman0c69cad2017-08-21 12:12:51 -070058 mFormat(PIXEL_FORMAT_NONE),
59 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
60 mBufferLatched(false),
61 mPreviousFrameNumber(0),
62 mUpdateTexImageFailed(false),
63 mRefreshPending(false) {
David Sodman0c69cad2017-08-21 12:12:51 -070064 ALOGV("Creating Layer %s", name.string());
David Sodman0c69cad2017-08-21 12:12:51 -070065
66 mFlinger->getRenderEngine().genTextures(1, &mTextureName);
67 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
68
69 if (flags & ISurfaceComposerClient::eNonPremultiplied) mPremultipliedAlpha = false;
70
71 mCurrentState.requested = mCurrentState.active;
72
73 // drawing state & current state are identical
74 mDrawingState = mCurrentState;
75}
76
77BufferLayer::~BufferLayer() {
David Sodman0c69cad2017-08-21 12:12:51 -070078 mFlinger->deleteTextureAsync(mTextureName);
79
David Sodman6f65f3e2017-11-03 14:28:09 -070080 if (!getBE().mHwcLayers.empty()) {
David Sodman0c69cad2017-08-21 12:12:51 -070081 ALOGE("Found stale hardware composer layers when destroying "
82 "surface flinger layer %s",
83 mName.string());
84 destroyAllHwcLayers();
85 }
David Sodman0c69cad2017-08-21 12:12:51 -070086}
87
David Sodmaneb085e02017-10-05 18:49:04 -070088void BufferLayer::useSurfaceDamage() {
89 if (mFlinger->mForceFullDamage) {
90 surfaceDamageRegion = Region::INVALID_REGION;
91 } else {
Chia-I Wub28c6742017-12-27 10:59:54 -080092 surfaceDamageRegion = mConsumer->getSurfaceDamage();
David Sodmaneb085e02017-10-05 18:49:04 -070093 }
94}
95
96void BufferLayer::useEmptyDamage() {
97 surfaceDamageRegion.clear();
98}
99
David Sodman41fdfc92017-11-06 16:09:56 -0800100bool BufferLayer::isProtected() const {
David Sodman0cf8f8d2017-12-20 18:19:45 -0800101 const sp<GraphicBuffer>& buffer(mActiveBuffer);
102 return (buffer != 0) && (buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
David Sodman0c69cad2017-08-21 12:12:51 -0700103}
104
105bool BufferLayer::isVisible() const {
106 return !(isHiddenByPolicy()) && getAlpha() > 0.0f &&
David Sodman0cf8f8d2017-12-20 18:19:45 -0800107 (mActiveBuffer != nullptr || getBE().compositionInfo.hwc.sidebandStream != nullptr);
David Sodman0c69cad2017-08-21 12:12:51 -0700108}
109
110bool BufferLayer::isFixedSize() const {
111 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
112}
113
114status_t BufferLayer::setBuffers(uint32_t w, uint32_t h, PixelFormat format, uint32_t flags) {
115 uint32_t const maxSurfaceDims =
116 min(mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
117
118 // never allow a surface larger than what our underlying GL implementation
119 // can handle.
120 if ((uint32_t(w) > maxSurfaceDims) || (uint32_t(h) > maxSurfaceDims)) {
121 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
122 return BAD_VALUE;
123 }
124
125 mFormat = format;
126
127 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
128 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
129 mCurrentOpacity = getOpacityForFormat(format);
130
Chia-I Wub28c6742017-12-27 10:59:54 -0800131 mConsumer->setDefaultBufferSize(w, h);
132 mConsumer->setDefaultBufferFormat(format);
133 mConsumer->setConsumerUsageBits(getEffectiveUsage(0));
David Sodman0c69cad2017-08-21 12:12:51 -0700134
135 return NO_ERROR;
136}
137
138static constexpr mat4 inverseOrientation(uint32_t transform) {
David Sodman41fdfc92017-11-06 16:09:56 -0800139 const mat4 flipH(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
140 const mat4 flipV(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
141 const mat4 rot90(0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
David Sodman0c69cad2017-08-21 12:12:51 -0700142 mat4 tr;
143
144 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
145 tr = tr * rot90;
146 }
147 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
148 tr = tr * flipH;
149 }
150 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
151 tr = tr * flipV;
152 }
153 return inverse(tr);
154}
155
156/*
157 * onDraw will draw the current layer onto the presentable buffer
158 */
159void BufferLayer::onDraw(const RenderArea& renderArea, const Region& clip,
160 bool useIdentityTransform) const {
161 ATRACE_CALL();
162
David Sodman0cf8f8d2017-12-20 18:19:45 -0800163 if (CC_UNLIKELY(mActiveBuffer == 0)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700164 // the texture has not been created yet, this Layer has
165 // in fact never been drawn into. This happens frequently with
166 // SurfaceView because the WindowManager can't know when the client
167 // has drawn the first time.
168
169 // If there is nothing under us, we paint the screen in black, otherwise
170 // we just skip this update.
171
172 // figure out if there is something below us
173 Region under;
174 bool finished = false;
175 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
176 if (finished || layer == static_cast<BufferLayer const*>(this)) {
177 finished = true;
178 return;
179 }
180 under.orSelf(renderArea.getTransform().transform(layer->visibleRegion));
181 });
182 // if not everything below us is covered, we plug the holes!
183 Region holes(clip.subtract(under));
184 if (!holes.isEmpty()) {
185 clearWithOpenGL(renderArea, 0, 0, 0, 1);
186 }
187 return;
188 }
189
190 // Bind the current buffer to the GL texture, and wait for it to be
191 // ready for us to draw into.
Chia-I Wub28c6742017-12-27 10:59:54 -0800192 status_t err = mConsumer->bindTextureImage();
David Sodman0c69cad2017-08-21 12:12:51 -0700193 if (err != NO_ERROR) {
194 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
195 // Go ahead and draw the buffer anyway; no matter what we do the screen
196 // is probably going to have something visibly wrong.
197 }
198
199 bool blackOutLayer = isProtected() || (isSecure() && !renderArea.isSecure());
200
Lloyd Pique144e1162017-12-20 16:44:52 -0800201 auto& engine(mFlinger->getRenderEngine());
David Sodman0c69cad2017-08-21 12:12:51 -0700202
203 if (!blackOutLayer) {
204 // TODO: we could be more subtle with isFixedSize()
205 const bool useFiltering = getFiltering() || needsFiltering(renderArea) || isFixedSize();
206
207 // Query the texture matrix given our current filtering mode.
208 float textureMatrix[16];
Chia-I Wub28c6742017-12-27 10:59:54 -0800209 mConsumer->setFilteringEnabled(useFiltering);
210 mConsumer->getTransformMatrix(textureMatrix);
David Sodman0c69cad2017-08-21 12:12:51 -0700211
212 if (getTransformToDisplayInverse()) {
213 /*
214 * the code below applies the primary display's inverse transform to
215 * the texture transform
216 */
217 uint32_t transform = DisplayDevice::getPrimaryDisplayOrientationTransform();
218 mat4 tr = inverseOrientation(transform);
219
220 /**
221 * TODO(b/36727915): This is basically a hack.
222 *
223 * Ensure that regardless of the parent transformation,
224 * this buffer is always transformed from native display
225 * orientation to display orientation. For example, in the case
226 * of a camera where the buffer remains in native orientation,
227 * we want the pixels to always be upright.
228 */
229 sp<Layer> p = mDrawingParent.promote();
230 if (p != nullptr) {
231 const auto parentTransform = p->getTransform();
232 tr = tr * inverseOrientation(parentTransform.getOrientation());
233 }
234
235 // and finally apply it to the original texture matrix
236 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
237 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
238 }
239
240 // Set things up for texturing.
David Sodman0cf8f8d2017-12-20 18:19:45 -0800241 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
David Sodman0c69cad2017-08-21 12:12:51 -0700242 mTexture.setFiltering(useFiltering);
243 mTexture.setMatrix(textureMatrix);
244
245 engine.setupLayerTexturing(mTexture);
246 } else {
247 engine.setupLayerBlackedOut();
248 }
249 drawWithOpenGL(renderArea, useIdentityTransform);
250 engine.disableTexturing();
251}
252
David Sodmaneb085e02017-10-05 18:49:04 -0700253void BufferLayer::onLayerDisplayed(const sp<Fence>& releaseFence) {
Chia-I Wub28c6742017-12-27 10:59:54 -0800254 mConsumer->setReleaseFence(releaseFence);
David Sodmaneb085e02017-10-05 18:49:04 -0700255}
David Sodmaneb085e02017-10-05 18:49:04 -0700256
257void BufferLayer::abandon() {
Chia-I Wub28c6742017-12-27 10:59:54 -0800258 mConsumer->abandon();
David Sodmaneb085e02017-10-05 18:49:04 -0700259}
260
261bool BufferLayer::shouldPresentNow(const DispSync& dispSync) const {
262 if (mSidebandStreamChanged || mAutoRefresh) {
263 return true;
264 }
265
266 Mutex::Autolock lock(mQueueItemLock);
267 if (mQueueItems.empty()) {
268 return false;
269 }
270 auto timestamp = mQueueItems[0].mTimestamp;
Chia-I Wub28c6742017-12-27 10:59:54 -0800271 nsecs_t expectedPresent = mConsumer->computeExpectedPresent(dispSync);
David Sodmaneb085e02017-10-05 18:49:04 -0700272
273 // Ignore timestamps more than a second in the future
274 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
275 ALOGW_IF(!isPlausible,
276 "[%s] Timestamp %" PRId64 " seems implausible "
277 "relative to expectedPresent %" PRId64,
278 mName.string(), timestamp, expectedPresent);
279
280 bool isDue = timestamp < expectedPresent;
281 return isDue || !isPlausible;
282}
283
284void BufferLayer::setTransformHint(uint32_t orientation) const {
Chia-I Wub28c6742017-12-27 10:59:54 -0800285 mConsumer->setTransformHint(orientation);
David Sodmaneb085e02017-10-05 18:49:04 -0700286}
287
David Sodman0c69cad2017-08-21 12:12:51 -0700288bool BufferLayer::onPreComposition(nsecs_t refreshStartTime) {
289 if (mBufferLatched) {
290 Mutex::Autolock lock(mFrameEventHistoryMutex);
David Sodman0cf8f8d2017-12-20 18:19:45 -0800291 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
David Sodman0c69cad2017-08-21 12:12:51 -0700292 }
293 mRefreshPending = false;
David Sodman0cf8f8d2017-12-20 18:19:45 -0800294 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
David Sodman0c69cad2017-08-21 12:12:51 -0700295}
David Sodmaneb085e02017-10-05 18:49:04 -0700296bool BufferLayer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
297 const std::shared_ptr<FenceTime>& presentFence,
298 const CompositorTiming& compositorTiming) {
299 // mFrameLatencyNeeded is true when a new frame was latched for the
300 // composition.
301 if (!mFrameLatencyNeeded) return false;
302
303 // Update mFrameEventHistory.
304 {
305 Mutex::Autolock lock(mFrameEventHistoryMutex);
David Sodman0cf8f8d2017-12-20 18:19:45 -0800306 mFrameEventHistory.addPostComposition(mCurrentFrameNumber, glDoneFence, presentFence,
307 compositorTiming);
David Sodmaneb085e02017-10-05 18:49:04 -0700308 }
309
310 // Update mFrameTracker.
Chia-I Wub28c6742017-12-27 10:59:54 -0800311 nsecs_t desiredPresentTime = mConsumer->getTimestamp();
David Sodmaneb085e02017-10-05 18:49:04 -0700312 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
313
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -0700314 const std::string layerName(getName().c_str());
315 mTimeStats.setDesiredTime(layerName, mCurrentFrameNumber, desiredPresentTime);
316
Chia-I Wub28c6742017-12-27 10:59:54 -0800317 std::shared_ptr<FenceTime> frameReadyFence = mConsumer->getCurrentFenceTime();
David Sodmaneb085e02017-10-05 18:49:04 -0700318 if (frameReadyFence->isValid()) {
319 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
320 } else {
321 // There was no fence for this frame, so assume that it was ready
322 // to be presented at the desired present time.
323 mFrameTracker.setFrameReadyTime(desiredPresentTime);
324 }
325
326 if (presentFence->isValid()) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -0700327 mTimeStats.setPresentFence(layerName, mCurrentFrameNumber, presentFence);
David Sodmaneb085e02017-10-05 18:49:04 -0700328 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700329 } else if (mFlinger->getHwComposer().isConnected(HWC_DISPLAY_PRIMARY)) {
David Sodmaneb085e02017-10-05 18:49:04 -0700330 // The HWC doesn't support present fences, so use the refresh
331 // timestamp instead.
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -0700332 const nsecs_t actualPresentTime =
333 mFlinger->getHwComposer().getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
334 mTimeStats.setPresentTime(layerName, mCurrentFrameNumber, actualPresentTime);
335 mFrameTracker.setActualPresentTime(actualPresentTime);
David Sodmaneb085e02017-10-05 18:49:04 -0700336 }
337
338 mFrameTracker.advanceFrame();
339 mFrameLatencyNeeded = false;
340 return true;
341}
342
343std::vector<OccupancyTracker::Segment> BufferLayer::getOccupancyHistory(bool forceFlush) {
344 std::vector<OccupancyTracker::Segment> history;
Chia-I Wub28c6742017-12-27 10:59:54 -0800345 status_t result = mConsumer->getOccupancyHistory(forceFlush, &history);
David Sodmaneb085e02017-10-05 18:49:04 -0700346 if (result != NO_ERROR) {
347 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(), result);
348 return {};
349 }
350 return history;
351}
352
353bool BufferLayer::getTransformToDisplayInverse() const {
Chia-I Wub28c6742017-12-27 10:59:54 -0800354 return mConsumer->getTransformToDisplayInverse();
David Sodmaneb085e02017-10-05 18:49:04 -0700355}
David Sodman0c69cad2017-08-21 12:12:51 -0700356
David Sodman0c69cad2017-08-21 12:12:51 -0700357void BufferLayer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Chia-I Wub28c6742017-12-27 10:59:54 -0800358 if (!mConsumer->releasePendingBuffer()) {
David Sodman0c69cad2017-08-21 12:12:51 -0700359 return;
360 }
361
David Sodman0cf8f8d2017-12-20 18:19:45 -0800362 auto releaseFenceTime = std::make_shared<FenceTime>(mConsumer->getPrevFinalReleaseFence());
David Sodman0c69cad2017-08-21 12:12:51 -0700363 mReleaseTimeline.updateSignalTimes();
364 mReleaseTimeline.push(releaseFenceTime);
365
366 Mutex::Autolock lock(mFrameEventHistoryMutex);
367 if (mPreviousFrameNumber != 0) {
368 mFrameEventHistory.addRelease(mPreviousFrameNumber, dequeueReadyTime,
369 std::move(releaseFenceTime));
370 }
371}
David Sodman0c69cad2017-08-21 12:12:51 -0700372
373Region BufferLayer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
374 ATRACE_CALL();
375
376 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
377 // mSidebandStreamChanged was true
Chia-I Wub28c6742017-12-27 10:59:54 -0800378 mSidebandStream = mConsumer->getSidebandStream();
David Sodman386c22e2017-11-09 16:34:46 -0800379 // replicated in LayerBE until FE/BE is ready to be synchronized
David Sodman0cc69182017-11-17 12:12:07 -0800380 getBE().compositionInfo.hwc.sidebandStream = mSidebandStream;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800381 if (getBE().compositionInfo.hwc.sidebandStream != nullptr) {
David Sodman0c69cad2017-08-21 12:12:51 -0700382 setTransactionFlags(eTransactionNeeded);
383 mFlinger->setTransactionFlags(eTraversalNeeded);
384 }
385 recomputeVisibleRegions = true;
386
387 const State& s(getDrawingState());
388 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
389 }
390
391 Region outDirtyRegion;
392 if (mQueuedFrames <= 0 && !mAutoRefresh) {
393 return outDirtyRegion;
394 }
395
396 // if we've already called updateTexImage() without going through
397 // a composition step, we have to skip this layer at this point
398 // because we cannot call updateTeximage() without a corresponding
399 // compositionComplete() call.
400 // we'll trigger an update in onPreComposition().
401 if (mRefreshPending) {
402 return outDirtyRegion;
403 }
404
405 // If the head buffer's acquire fence hasn't signaled yet, return and
406 // try again later
407 if (!headFenceHasSignaled()) {
408 mFlinger->signalLayerUpdate();
409 return outDirtyRegion;
410 }
411
412 // Capture the old state of the layer for comparisons later
413 const State& s(getDrawingState());
414 const bool oldOpacity = isOpaque(s);
David Sodman0cf8f8d2017-12-20 18:19:45 -0800415 sp<GraphicBuffer> oldBuffer = mActiveBuffer;
David Sodman0c69cad2017-08-21 12:12:51 -0700416
417 if (!allTransactionsSignaled()) {
418 mFlinger->signalLayerUpdate();
419 return outDirtyRegion;
420 }
421
422 // This boolean is used to make sure that SurfaceFlinger's shadow copy
423 // of the buffer queue isn't modified when the buffer queue is returning
424 // BufferItem's that weren't actually queued. This can happen in shared
425 // buffer mode.
426 bool queuedBuffer = false;
427 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
David Sodman0cf8f8d2017-12-20 18:19:45 -0800428 getProducerStickyTransform() != 0, mName.string(), mOverrideScalingMode,
Robert Carr35f0dda2018-05-03 15:47:23 -0700429 getTransformToDisplayInverse(), mFreezeGeometryUpdates);
430
David Sodman0cf8f8d2017-12-20 18:19:45 -0800431 status_t updateResult = mConsumer->updateTexImage(&r, mFlinger->mPrimaryDispSync, &mAutoRefresh,
432 &queuedBuffer, mLastFrameNumberReceived);
Robert Carr35f0dda2018-05-03 15:47:23 -0700433
David Sodman0c69cad2017-08-21 12:12:51 -0700434 if (updateResult == BufferQueue::PRESENT_LATER) {
435 // Producer doesn't want buffer to be displayed yet. Signal a
436 // layer update so we check again at the next opportunity.
437 mFlinger->signalLayerUpdate();
438 return outDirtyRegion;
Chia-I Wu0cb75ac2017-11-27 15:56:04 -0800439 } else if (updateResult == BufferLayerConsumer::BUFFER_REJECTED) {
David Sodman0c69cad2017-08-21 12:12:51 -0700440 // If the buffer has been rejected, remove it from the shadow queue
441 // and return early
442 if (queuedBuffer) {
443 Mutex::Autolock lock(mQueueItemLock);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -0700444 mTimeStats.removeTimeRecord(getName().c_str(), mQueueItems[0].mFrameNumber);
David Sodman0c69cad2017-08-21 12:12:51 -0700445 mQueueItems.removeAt(0);
446 android_atomic_dec(&mQueuedFrames);
447 }
448 return outDirtyRegion;
449 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
450 // This can occur if something goes wrong when trying to create the
451 // EGLImage for this buffer. If this happens, the buffer has already
452 // been released, so we need to clean up the queue and bug out
453 // early.
454 if (queuedBuffer) {
455 Mutex::Autolock lock(mQueueItemLock);
456 mQueueItems.clear();
457 android_atomic_and(0, &mQueuedFrames);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -0700458 mTimeStats.clearLayerRecord(getName().c_str());
David Sodman0c69cad2017-08-21 12:12:51 -0700459 }
460
461 // Once we have hit this state, the shadow queue may no longer
462 // correctly reflect the incoming BufferQueue's contents, so even if
463 // updateTexImage starts working, the only safe course of action is
464 // to continue to ignore updates.
465 mUpdateTexImageFailed = true;
466
467 return outDirtyRegion;
468 }
469
470 if (queuedBuffer) {
471 // Autolock scope
Chia-I Wub28c6742017-12-27 10:59:54 -0800472 auto currentFrameNumber = mConsumer->getFrameNumber();
David Sodman0c69cad2017-08-21 12:12:51 -0700473
474 Mutex::Autolock lock(mQueueItemLock);
475
476 // Remove any stale buffers that have been dropped during
477 // updateTexImage
478 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -0700479 mTimeStats.removeTimeRecord(getName().c_str(), mQueueItems[0].mFrameNumber);
David Sodman0c69cad2017-08-21 12:12:51 -0700480 mQueueItems.removeAt(0);
481 android_atomic_dec(&mQueuedFrames);
482 }
483
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -0700484 const std::string layerName(getName().c_str());
485 mTimeStats.setAcquireFence(layerName, currentFrameNumber, mQueueItems[0].mFenceTime);
486 mTimeStats.setLatchTime(layerName, currentFrameNumber, latchTime);
487
David Sodman0c69cad2017-08-21 12:12:51 -0700488 mQueueItems.removeAt(0);
489 }
490
491 // Decrement the queued-frames count. Signal another event if we
492 // have more frames pending.
David Sodman0cf8f8d2017-12-20 18:19:45 -0800493 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1) || mAutoRefresh) {
David Sodman0c69cad2017-08-21 12:12:51 -0700494 mFlinger->signalLayerUpdate();
495 }
496
497 // update the active buffer
David Sodman0cf8f8d2017-12-20 18:19:45 -0800498 mActiveBuffer = mConsumer->getCurrentBuffer(&mActiveBufferSlot);
499 getBE().compositionInfo.mBuffer = mActiveBuffer;
500 getBE().compositionInfo.mBufferSlot = mActiveBufferSlot;
501
502 if (mActiveBuffer == nullptr) {
David Sodman0c69cad2017-08-21 12:12:51 -0700503 // this can only happen if the very first buffer was rejected.
504 return outDirtyRegion;
505 }
506
507 mBufferLatched = true;
508 mPreviousFrameNumber = mCurrentFrameNumber;
Chia-I Wub28c6742017-12-27 10:59:54 -0800509 mCurrentFrameNumber = mConsumer->getFrameNumber();
David Sodman0c69cad2017-08-21 12:12:51 -0700510
511 {
512 Mutex::Autolock lock(mFrameEventHistoryMutex);
513 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
David Sodman0c69cad2017-08-21 12:12:51 -0700514 }
515
516 mRefreshPending = true;
517 mFrameLatencyNeeded = true;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800518 if (oldBuffer == nullptr) {
David Sodman0c69cad2017-08-21 12:12:51 -0700519 // the first time we receive a buffer, we need to trigger a
520 // geometry invalidation.
521 recomputeVisibleRegions = true;
522 }
523
Peiyong Lin923e7c52018-04-16 14:16:37 -0700524 ui::Dataspace dataSpace = mConsumer->getCurrentDataSpace();
Chia-I Wu11481472018-05-04 10:43:19 -0700525 // treat modern dataspaces as legacy dataspaces whenever possible, until
526 // we can trust the buffer producers
Peiyong Lin923e7c52018-04-16 14:16:37 -0700527 switch (dataSpace) {
528 case ui::Dataspace::V0_SRGB:
529 dataSpace = ui::Dataspace::SRGB;
530 break;
531 case ui::Dataspace::V0_SRGB_LINEAR:
532 dataSpace = ui::Dataspace::SRGB_LINEAR;
533 break;
Chia-I Wu11481472018-05-04 10:43:19 -0700534 case ui::Dataspace::V0_JFIF:
535 dataSpace = ui::Dataspace::JFIF;
536 break;
537 case ui::Dataspace::V0_BT601_625:
538 dataSpace = ui::Dataspace::BT601_625;
539 break;
540 case ui::Dataspace::V0_BT601_525:
541 dataSpace = ui::Dataspace::BT601_525;
542 break;
543 case ui::Dataspace::V0_BT709:
544 dataSpace = ui::Dataspace::BT709;
Peiyong Lin923e7c52018-04-16 14:16:37 -0700545 break;
546 default:
547 break;
548 }
Chia-I Wu01591c92018-05-22 12:03:00 -0700549 mCurrentDataSpace = dataSpace;
David Sodman0c69cad2017-08-21 12:12:51 -0700550
Chia-I Wub28c6742017-12-27 10:59:54 -0800551 Rect crop(mConsumer->getCurrentCrop());
552 const uint32_t transform(mConsumer->getCurrentTransform());
553 const uint32_t scalingMode(mConsumer->getCurrentScalingMode());
David Sodman0cf8f8d2017-12-20 18:19:45 -0800554 if ((crop != mCurrentCrop) || (transform != mCurrentTransform) ||
David Sodman0c69cad2017-08-21 12:12:51 -0700555 (scalingMode != mCurrentScalingMode)) {
556 mCurrentCrop = crop;
557 mCurrentTransform = transform;
558 mCurrentScalingMode = scalingMode;
559 recomputeVisibleRegions = true;
560 }
561
Peiyong Lin566a3b42018-01-09 18:22:43 -0800562 if (oldBuffer != nullptr) {
David Sodman0cf8f8d2017-12-20 18:19:45 -0800563 uint32_t bufWidth = mActiveBuffer->getWidth();
564 uint32_t bufHeight = mActiveBuffer->getHeight();
565 if (bufWidth != uint32_t(oldBuffer->width) || bufHeight != uint32_t(oldBuffer->height)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700566 recomputeVisibleRegions = true;
567 }
568 }
569
David Sodman0cf8f8d2017-12-20 18:19:45 -0800570 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
David Sodman0c69cad2017-08-21 12:12:51 -0700571 if (oldOpacity != isOpaque(s)) {
572 recomputeVisibleRegions = true;
573 }
574
575 // Remove any sync points corresponding to the buffer which was just
576 // latched
577 {
578 Mutex::Autolock lock(mLocalSyncPointMutex);
579 auto point = mLocalSyncPoints.begin();
580 while (point != mLocalSyncPoints.end()) {
581 if (!(*point)->frameIsAvailable() || !(*point)->transactionIsApplied()) {
582 // This sync point must have been added since we started
583 // latching. Don't drop it yet.
584 ++point;
585 continue;
586 }
587
588 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
589 point = mLocalSyncPoints.erase(point);
590 } else {
591 ++point;
592 }
593 }
594 }
595
596 // FIXME: postedRegion should be dirty & bounds
597 Region dirtyRegion(Rect(s.active.w, s.active.h));
598
599 // transform the dirty region to window-manager space
600 outDirtyRegion = (getTransform().transform(dirtyRegion));
601
602 return outDirtyRegion;
603}
604
David Sodmaneb085e02017-10-05 18:49:04 -0700605void BufferLayer::setDefaultBufferSize(uint32_t w, uint32_t h) {
Chia-I Wub28c6742017-12-27 10:59:54 -0800606 mConsumer->setDefaultBufferSize(w, h);
David Sodmaneb085e02017-10-05 18:49:04 -0700607}
608
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700609void BufferLayer::setPerFrameData(const sp<const DisplayDevice>& display) {
David Sodman0c69cad2017-08-21 12:12:51 -0700610 // Apply this display's projection's viewport to the visible region
611 // before giving it to the HWC HAL.
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700612 const Transform& tr = display->getTransform();
613 const auto& viewport = display->getViewport();
David Sodman0c69cad2017-08-21 12:12:51 -0700614 Region visible = tr.transform(visibleRegion.intersect(viewport));
Dominik Laskowski7e045462018-05-30 13:02:02 -0700615 const auto displayId = display->getId();
Peiyong Lin91b1df22018-06-18 18:00:16 -0700616 if (!hasHwcLayer(displayId)) {
617 ALOGE("[%s] failed to setPerFrameData: no HWC layer found (%d)",
618 mName.string(), displayId);
619 return;
620 }
Dominik Laskowski7e045462018-05-30 13:02:02 -0700621 auto& hwcInfo = getBE().mHwcLayers[displayId];
Chia-I Wu30505fb2018-03-26 16:20:31 -0700622 auto& hwcLayer = hwcInfo.layer;
David Sodmanf6a38932018-05-25 15:27:50 -0700623 auto error = hwcLayer->setVisibleRegion(visible);
Chia-I Wu30505fb2018-03-26 16:20:31 -0700624 if (error != HWC2::Error::None) {
625 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
626 to_string(error).c_str(), static_cast<int32_t>(error));
627 visible.dump(LOG_TAG);
628 }
David Sodman0c69cad2017-08-21 12:12:51 -0700629
David Sodmanf6a38932018-05-25 15:27:50 -0700630 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
Chia-I Wu30505fb2018-03-26 16:20:31 -0700631 if (error != HWC2::Error::None) {
632 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
633 to_string(error).c_str(), static_cast<int32_t>(error));
634 surfaceDamageRegion.dump(LOG_TAG);
635 }
David Sodman0c69cad2017-08-21 12:12:51 -0700636
637 // Sideband layers
David Sodman0cc69182017-11-17 12:12:07 -0800638 if (getBE().compositionInfo.hwc.sidebandStream.get()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -0700639 setCompositionType(displayId, HWC2::Composition::Sideband);
Chia-I Wu30505fb2018-03-26 16:20:31 -0700640 ALOGV("[%s] Requesting Sideband composition", mName.string());
David Sodmanf6a38932018-05-25 15:27:50 -0700641 error = hwcLayer->setSidebandStream(getBE().compositionInfo.hwc.sidebandStream->handle());
Chia-I Wu30505fb2018-03-26 16:20:31 -0700642 if (error != HWC2::Error::None) {
643 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", mName.string(),
644 getBE().compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
645 static_cast<int32_t>(error));
646 }
David Sodman0c69cad2017-08-21 12:12:51 -0700647 return;
648 }
649
David Sodman0c69cad2017-08-21 12:12:51 -0700650 // Device or Cursor layers
651 if (mPotentialCursor) {
652 ALOGV("[%s] Requesting Cursor composition", mName.string());
Dominik Laskowski7e045462018-05-30 13:02:02 -0700653 setCompositionType(displayId, HWC2::Composition::Cursor);
David Sodman0c69cad2017-08-21 12:12:51 -0700654 } else {
655 ALOGV("[%s] Requesting Device composition", mName.string());
Dominik Laskowski7e045462018-05-30 13:02:02 -0700656 setCompositionType(displayId, HWC2::Composition::Device);
David Sodman0c69cad2017-08-21 12:12:51 -0700657 }
658
Chia-I Wu01591c92018-05-22 12:03:00 -0700659 ALOGV("setPerFrameData: dataspace = %d", mCurrentDataSpace);
David Sodmanf6a38932018-05-25 15:27:50 -0700660 error = hwcLayer->setDataspace(mCurrentDataSpace);
Chia-I Wu30505fb2018-03-26 16:20:31 -0700661 if (error != HWC2::Error::None) {
Chia-I Wu01591c92018-05-22 12:03:00 -0700662 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(), mCurrentDataSpace,
Chia-I Wu30505fb2018-03-26 16:20:31 -0700663 to_string(error).c_str(), static_cast<int32_t>(error));
664 }
665
666 const HdrMetadata& metadata = mConsumer->getCurrentHdrMetadata();
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700667 error = hwcLayer->setPerFrameMetadata(display->getSupportedPerFrameMetadata(), metadata);
Chia-I Wu30505fb2018-03-26 16:20:31 -0700668 if (error != HWC2::Error::None && error != HWC2::Error::Unsupported) {
669 ALOGE("[%s] Failed to set hdrMetadata: %s (%d)", mName.string(),
670 to_string(error).c_str(), static_cast<int32_t>(error));
671 }
672
673 uint32_t hwcSlot = 0;
674 sp<GraphicBuffer> hwcBuffer;
Peiyong Lin91b1df22018-06-18 18:00:16 -0700675 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer, &hwcSlot, &hwcBuffer);
David Sodman0c69cad2017-08-21 12:12:51 -0700676
Chia-I Wub28c6742017-12-27 10:59:54 -0800677 auto acquireFence = mConsumer->getCurrentFence();
David Sodmanf6a38932018-05-25 15:27:50 -0700678 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
Chia-I Wu30505fb2018-03-26 16:20:31 -0700679 if (error != HWC2::Error::None) {
680 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
681 getBE().compositionInfo.mBuffer->handle, to_string(error).c_str(),
682 static_cast<int32_t>(error));
683 }
David Sodman0c69cad2017-08-21 12:12:51 -0700684}
685
David Sodman41fdfc92017-11-06 16:09:56 -0800686bool BufferLayer::isOpaque(const Layer::State& s) const {
David Sodman0c69cad2017-08-21 12:12:51 -0700687 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
688 // layer's opaque flag.
David Sodman0cf8f8d2017-12-20 18:19:45 -0800689 if ((getBE().compositionInfo.hwc.sidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700690 return false;
691 }
692
693 // if the layer has the opaque flag, then we're always opaque,
694 // otherwise we use the current buffer's format.
695 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
696}
697
698void BufferLayer::onFirstRef() {
699 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
700 sp<IGraphicBufferProducer> producer;
701 sp<IGraphicBufferConsumer> consumer;
702 BufferQueue::createBufferQueue(&producer, &consumer, true);
703 mProducer = new MonitoredProducer(producer, mFlinger, this);
David Sodman0cf8f8d2017-12-20 18:19:45 -0800704 mConsumer = new BufferLayerConsumer(consumer, mFlinger->getRenderEngine(), mTextureName, this);
Chia-I Wub28c6742017-12-27 10:59:54 -0800705 mConsumer->setConsumerUsageBits(getEffectiveUsage(0));
706 mConsumer->setContentsChangedListener(this);
707 mConsumer->setName(mName);
David Sodman0c69cad2017-08-21 12:12:51 -0700708
709 if (mFlinger->isLayerTripleBufferingDisabled()) {
710 mProducer->setMaxDequeuedBufferCount(2);
711 }
712
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700713 if (const auto display = mFlinger->getDefaultDisplayDevice()) {
714 updateTransformHint(display);
715 }
David Sodman0c69cad2017-08-21 12:12:51 -0700716}
717
718// ---------------------------------------------------------------------------
719// Interface implementation for SurfaceFlingerConsumer::ContentsChangedListener
720// ---------------------------------------------------------------------------
721
722void BufferLayer::onFrameAvailable(const BufferItem& item) {
723 // Add this buffer from our internal queue tracker
724 { // Autolock scope
725 Mutex::Autolock lock(mQueueItemLock);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800726 mFlinger->mInterceptor->saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
727 item.mGraphicBuffer->getHeight(),
728 item.mFrameNumber);
David Sodman0c69cad2017-08-21 12:12:51 -0700729 // Reset the frame number tracker when we receive the first buffer after
730 // a frame number reset
731 if (item.mFrameNumber == 1) {
732 mLastFrameNumberReceived = 0;
733 }
734
735 // Ensure that callbacks are handled in order
736 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
David Sodman0cf8f8d2017-12-20 18:19:45 -0800737 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock, ms2ns(500));
David Sodman0c69cad2017-08-21 12:12:51 -0700738 if (result != NO_ERROR) {
739 ALOGE("[%s] Timed out waiting on callback", mName.string());
740 }
741 }
742
743 mQueueItems.push_back(item);
744 android_atomic_inc(&mQueuedFrames);
745
746 // Wake up any pending callbacks
747 mLastFrameNumberReceived = item.mFrameNumber;
748 mQueueItemCondition.broadcast();
749 }
750
751 mFlinger->signalLayerUpdate();
752}
753
754void BufferLayer::onFrameReplaced(const BufferItem& item) {
755 { // Autolock scope
756 Mutex::Autolock lock(mQueueItemLock);
757
758 // Ensure that callbacks are handled in order
759 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
David Sodman0cf8f8d2017-12-20 18:19:45 -0800760 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock, ms2ns(500));
David Sodman0c69cad2017-08-21 12:12:51 -0700761 if (result != NO_ERROR) {
762 ALOGE("[%s] Timed out waiting on callback", mName.string());
763 }
764 }
765
766 if (mQueueItems.empty()) {
767 ALOGE("Can't replace a frame on an empty queue");
768 return;
769 }
770 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
771
772 // Wake up any pending callbacks
773 mLastFrameNumberReceived = item.mFrameNumber;
774 mQueueItemCondition.broadcast();
775 }
776}
777
778void BufferLayer::onSidebandStreamChanged() {
779 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
780 // mSidebandStreamChanged was false
781 mFlinger->signalLayerUpdate();
782 }
783}
784
785bool BufferLayer::needsFiltering(const RenderArea& renderArea) const {
786 return mNeedsFiltering || renderArea.needsFiltering();
787}
788
789// As documented in libhardware header, formats in the range
790// 0x100 - 0x1FF are specific to the HAL implementation, and
791// are known to have no alpha channel
792// TODO: move definition for device-specific range into
793// hardware.h, instead of using hard-coded values here.
794#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
795
796bool BufferLayer::getOpacityForFormat(uint32_t format) {
797 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
798 return true;
799 }
800 switch (format) {
801 case HAL_PIXEL_FORMAT_RGBA_8888:
802 case HAL_PIXEL_FORMAT_BGRA_8888:
803 case HAL_PIXEL_FORMAT_RGBA_FP16:
804 case HAL_PIXEL_FORMAT_RGBA_1010102:
805 return false;
806 }
807 // in all other case, we have no blending (also for unknown formats)
808 return true;
809}
810
Chia-I Wu692e0832018-06-05 15:46:58 -0700811bool BufferLayer::isHdrY410() const {
812 // pixel format is HDR Y410 masquerading as RGBA_1010102
813 return (mCurrentDataSpace == ui::Dataspace::BT2020_ITU_PQ &&
814 mConsumer->getCurrentApi() == NATIVE_WINDOW_API_MEDIA &&
815 getBE().compositionInfo.mBuffer->getPixelFormat() == HAL_PIXEL_FORMAT_RGBA_1010102);
816}
817
David Sodman41fdfc92017-11-06 16:09:56 -0800818void BufferLayer::drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const {
Dan Stoza84d619e2018-03-28 17:07:36 -0700819 ATRACE_CALL();
David Sodman0c69cad2017-08-21 12:12:51 -0700820 const State& s(getDrawingState());
821
David Sodman9eeae692017-11-02 10:53:32 -0700822 computeGeometry(renderArea, getBE().mMesh, useIdentityTransform);
David Sodman0c69cad2017-08-21 12:12:51 -0700823
824 /*
825 * NOTE: the way we compute the texture coordinates here produces
826 * different results than when we take the HWC path -- in the later case
827 * the "source crop" is rounded to texel boundaries.
828 * This can produce significantly different results when the texture
829 * is scaled by a large amount.
830 *
831 * The GL code below is more logical (imho), and the difference with
832 * HWC is due to a limitation of the HWC API to integers -- a question
833 * is suspend is whether we should ignore this problem or revert to
834 * GL composition when a buffer scaling is applied (maybe with some
835 * minimal value)? Or, we could make GL behave like HWC -- but this feel
836 * like more of a hack.
837 */
Dan Stoza80d61162017-12-20 15:57:52 -0800838 const Rect bounds{computeBounds()}; // Rounds from FloatRect
David Sodman0c69cad2017-08-21 12:12:51 -0700839
840 Transform t = getTransform();
Dan Stoza80d61162017-12-20 15:57:52 -0800841 Rect win = bounds;
David Sodman0c69cad2017-08-21 12:12:51 -0700842 if (!s.finalCrop.isEmpty()) {
843 win = t.transform(win);
844 if (!win.intersect(s.finalCrop, &win)) {
845 win.clear();
846 }
847 win = t.inverse().transform(win);
Dan Stoza80d61162017-12-20 15:57:52 -0800848 if (!win.intersect(bounds, &win)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700849 win.clear();
850 }
851 }
852
853 float left = float(win.left) / float(s.active.w);
854 float top = float(win.top) / float(s.active.h);
855 float right = float(win.right) / float(s.active.w);
856 float bottom = float(win.bottom) / float(s.active.h);
857
858 // TODO: we probably want to generate the texture coords with the mesh
859 // here we assume that we only have 4 vertices
David Sodman9eeae692017-11-02 10:53:32 -0700860 Mesh::VertexArray<vec2> texCoords(getBE().mMesh.getTexCoordArray<vec2>());
David Sodman0c69cad2017-08-21 12:12:51 -0700861 texCoords[0] = vec2(left, 1.0f - top);
862 texCoords[1] = vec2(left, 1.0f - bottom);
863 texCoords[2] = vec2(right, 1.0f - bottom);
864 texCoords[3] = vec2(right, 1.0f - top);
865
bohu21566132018-03-27 14:36:34 -0700866 auto& engine(mFlinger->getRenderEngine());
867 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), false /* disableTexture */,
868 getColor());
Chia-I Wu01591c92018-05-22 12:03:00 -0700869 engine.setSourceDataSpace(mCurrentDataSpace);
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800870
Chia-I Wu692e0832018-06-05 15:46:58 -0700871 if (isHdrY410()) {
bohu21566132018-03-27 14:36:34 -0700872 engine.setSourceY410BT2020(true);
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800873 }
bohu21566132018-03-27 14:36:34 -0700874
875 engine.drawMesh(getBE().mMesh);
876 engine.disableBlending();
877
878 engine.setSourceY410BT2020(false);
David Sodman0c69cad2017-08-21 12:12:51 -0700879}
880
881uint32_t BufferLayer::getProducerStickyTransform() const {
882 int producerStickyTransform = 0;
883 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
884 if (ret != OK) {
885 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
886 strerror(-ret), ret);
887 return 0;
888 }
889 return static_cast<uint32_t>(producerStickyTransform);
890}
891
892bool BufferLayer::latchUnsignaledBuffers() {
893 static bool propertyLoaded = false;
894 static bool latch = false;
895 static std::mutex mutex;
896 std::lock_guard<std::mutex> lock(mutex);
897 if (!propertyLoaded) {
898 char value[PROPERTY_VALUE_MAX] = {};
899 property_get("debug.sf.latch_unsignaled", value, "0");
900 latch = atoi(value);
901 propertyLoaded = true;
902 }
903 return latch;
904}
905
906uint64_t BufferLayer::getHeadFrameNumber() const {
907 Mutex::Autolock lock(mQueueItemLock);
908 if (!mQueueItems.empty()) {
909 return mQueueItems[0].mFrameNumber;
910 } else {
911 return mCurrentFrameNumber;
912 }
913}
914
915bool BufferLayer::headFenceHasSignaled() const {
David Sodman0c69cad2017-08-21 12:12:51 -0700916 if (latchUnsignaledBuffers()) {
917 return true;
918 }
919
920 Mutex::Autolock lock(mQueueItemLock);
921 if (mQueueItems.empty()) {
922 return true;
923 }
924 if (mQueueItems[0].mIsDroppable) {
925 // Even though this buffer's fence may not have signaled yet, it could
926 // be replaced by another buffer before it has a chance to, which means
927 // that it's possible to get into a situation where a buffer is never
928 // able to be latched. To avoid this, grab this buffer anyway.
929 return true;
930 }
David Sodman0cf8f8d2017-12-20 18:19:45 -0800931 return mQueueItems[0].mFenceTime->getSignalTime() != Fence::SIGNAL_TIME_PENDING;
David Sodman0c69cad2017-08-21 12:12:51 -0700932}
933
934uint32_t BufferLayer::getEffectiveScalingMode() const {
935 if (mOverrideScalingMode >= 0) {
936 return mOverrideScalingMode;
937 }
938 return mCurrentScalingMode;
939}
940
941// ----------------------------------------------------------------------------
942// transaction
943// ----------------------------------------------------------------------------
944
945void BufferLayer::notifyAvailableFrames() {
946 auto headFrameNumber = getHeadFrameNumber();
947 bool headFenceSignaled = headFenceHasSignaled();
948 Mutex::Autolock lock(mLocalSyncPointMutex);
949 for (auto& point : mLocalSyncPoints) {
950 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
951 point->setFrameAvailable();
952 }
953 }
954}
955
956sp<IGraphicBufferProducer> BufferLayer::getProducer() const {
957 return mProducer;
958}
959
960// ---------------------------------------------------------------------------
961// h/w composer set-up
962// ---------------------------------------------------------------------------
963
964bool BufferLayer::allTransactionsSignaled() {
965 auto headFrameNumber = getHeadFrameNumber();
966 bool matchingFramesFound = false;
967 bool allTransactionsApplied = true;
968 Mutex::Autolock lock(mLocalSyncPointMutex);
969
970 for (auto& point : mLocalSyncPoints) {
971 if (point->getFrameNumber() > headFrameNumber) {
972 break;
973 }
974 matchingFramesFound = true;
975
976 if (!point->frameIsAvailable()) {
977 // We haven't notified the remote layer that the frame for
978 // this point is available yet. Notify it now, and then
979 // abort this attempt to latch.
980 point->setFrameAvailable();
981 allTransactionsApplied = false;
982 break;
983 }
984
985 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
986 }
987 return !matchingFramesFound || allTransactionsApplied;
988}
989
990} // namespace android
991
992#if defined(__gl_h_)
993#error "don't include gl/gl.h in this file"
994#endif
995
996#if defined(__gl2_h_)
997#error "don't include gl2/gl2.h in this file"
998#endif