blob: 37f4b0f0070a09ff5807bf11664ca08d41e452e3 [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
Dan Stoza436ccf32018-06-21 12:10:12 -070066 mTextureName = mFlinger->getNewTexture();
David Sodman0c69cad2017-08-21 12:12:51 -070067 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 Sodmanca10ed22018-04-16 14:10:25 -0700163 CompositionInfo& compositionInfo = getBE().compositionInfo;
164
David Sodman0cf8f8d2017-12-20 18:19:45 -0800165 if (CC_UNLIKELY(mActiveBuffer == 0)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700166 // the texture has not been created yet, this Layer has
167 // in fact never been drawn into. This happens frequently with
168 // SurfaceView because the WindowManager can't know when the client
169 // has drawn the first time.
170
171 // If there is nothing under us, we paint the screen in black, otherwise
172 // we just skip this update.
173
174 // figure out if there is something below us
175 Region under;
176 bool finished = false;
177 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
178 if (finished || layer == static_cast<BufferLayer const*>(this)) {
179 finished = true;
180 return;
181 }
182 under.orSelf(renderArea.getTransform().transform(layer->visibleRegion));
183 });
184 // if not everything below us is covered, we plug the holes!
185 Region holes(clip.subtract(under));
186 if (!holes.isEmpty()) {
187 clearWithOpenGL(renderArea, 0, 0, 0, 1);
188 }
189 return;
190 }
191
192 // Bind the current buffer to the GL texture, and wait for it to be
193 // ready for us to draw into.
Chia-I Wub28c6742017-12-27 10:59:54 -0800194 status_t err = mConsumer->bindTextureImage();
David Sodman0c69cad2017-08-21 12:12:51 -0700195 if (err != NO_ERROR) {
196 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
197 // Go ahead and draw the buffer anyway; no matter what we do the screen
198 // is probably going to have something visibly wrong.
199 }
200
201 bool blackOutLayer = isProtected() || (isSecure() && !renderArea.isSecure());
202
Lloyd Pique144e1162017-12-20 16:44:52 -0800203 auto& engine(mFlinger->getRenderEngine());
David Sodman0c69cad2017-08-21 12:12:51 -0700204
205 if (!blackOutLayer) {
206 // TODO: we could be more subtle with isFixedSize()
207 const bool useFiltering = getFiltering() || needsFiltering(renderArea) || isFixedSize();
208
209 // Query the texture matrix given our current filtering mode.
210 float textureMatrix[16];
Chia-I Wub28c6742017-12-27 10:59:54 -0800211 mConsumer->setFilteringEnabled(useFiltering);
212 mConsumer->getTransformMatrix(textureMatrix);
David Sodman0c69cad2017-08-21 12:12:51 -0700213
214 if (getTransformToDisplayInverse()) {
215 /*
216 * the code below applies the primary display's inverse transform to
217 * the texture transform
218 */
219 uint32_t transform = DisplayDevice::getPrimaryDisplayOrientationTransform();
220 mat4 tr = inverseOrientation(transform);
221
222 /**
223 * TODO(b/36727915): This is basically a hack.
224 *
225 * Ensure that regardless of the parent transformation,
226 * this buffer is always transformed from native display
227 * orientation to display orientation. For example, in the case
228 * of a camera where the buffer remains in native orientation,
229 * we want the pixels to always be upright.
230 */
231 sp<Layer> p = mDrawingParent.promote();
232 if (p != nullptr) {
233 const auto parentTransform = p->getTransform();
234 tr = tr * inverseOrientation(parentTransform.getOrientation());
235 }
236
237 // and finally apply it to the original texture matrix
238 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
239 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
240 }
241
242 // Set things up for texturing.
David Sodman0cf8f8d2017-12-20 18:19:45 -0800243 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
David Sodman0c69cad2017-08-21 12:12:51 -0700244 mTexture.setFiltering(useFiltering);
245 mTexture.setMatrix(textureMatrix);
David Sodmanca10ed22018-04-16 14:10:25 -0700246 compositionInfo.re.texture = mTexture;
David Sodman0c69cad2017-08-21 12:12:51 -0700247
248 engine.setupLayerTexturing(mTexture);
249 } else {
250 engine.setupLayerBlackedOut();
251 }
252 drawWithOpenGL(renderArea, useIdentityTransform);
253 engine.disableTexturing();
254}
255
David Sodmanca10ed22018-04-16 14:10:25 -0700256void BufferLayer::drawNow(const RenderArea& renderArea, bool useIdentityTransform) const {
257 CompositionInfo& compositionInfo = getBE().compositionInfo;
258 auto& engine(mFlinger->getRenderEngine());
259
260 draw(renderArea, useIdentityTransform);
261
262 engine.setupLayerTexturing(compositionInfo.re.texture);
263 engine.setupLayerBlending(compositionInfo.re.preMultipliedAlpha, compositionInfo.re.opaque,
264 false, compositionInfo.re.color);
265 engine.setSourceDataSpace(compositionInfo.hwc.dataspace);
266 engine.setSourceY410BT2020(compositionInfo.re.Y410BT2020);
267 engine.drawMesh(getBE().getMesh());
268 engine.disableBlending();
269 engine.disableTexturing();
270 engine.setSourceY410BT2020(false);
271}
272
David Sodmaneb085e02017-10-05 18:49:04 -0700273void BufferLayer::onLayerDisplayed(const sp<Fence>& releaseFence) {
Chia-I Wub28c6742017-12-27 10:59:54 -0800274 mConsumer->setReleaseFence(releaseFence);
David Sodmaneb085e02017-10-05 18:49:04 -0700275}
David Sodmaneb085e02017-10-05 18:49:04 -0700276
277void BufferLayer::abandon() {
Chia-I Wub28c6742017-12-27 10:59:54 -0800278 mConsumer->abandon();
David Sodmaneb085e02017-10-05 18:49:04 -0700279}
280
281bool BufferLayer::shouldPresentNow(const DispSync& dispSync) const {
282 if (mSidebandStreamChanged || mAutoRefresh) {
283 return true;
284 }
285
286 Mutex::Autolock lock(mQueueItemLock);
287 if (mQueueItems.empty()) {
288 return false;
289 }
290 auto timestamp = mQueueItems[0].mTimestamp;
Chia-I Wub28c6742017-12-27 10:59:54 -0800291 nsecs_t expectedPresent = mConsumer->computeExpectedPresent(dispSync);
David Sodmaneb085e02017-10-05 18:49:04 -0700292
293 // Ignore timestamps more than a second in the future
294 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
295 ALOGW_IF(!isPlausible,
296 "[%s] Timestamp %" PRId64 " seems implausible "
297 "relative to expectedPresent %" PRId64,
298 mName.string(), timestamp, expectedPresent);
299
300 bool isDue = timestamp < expectedPresent;
301 return isDue || !isPlausible;
302}
303
304void BufferLayer::setTransformHint(uint32_t orientation) const {
Chia-I Wub28c6742017-12-27 10:59:54 -0800305 mConsumer->setTransformHint(orientation);
David Sodmaneb085e02017-10-05 18:49:04 -0700306}
307
David Sodman0c69cad2017-08-21 12:12:51 -0700308bool BufferLayer::onPreComposition(nsecs_t refreshStartTime) {
309 if (mBufferLatched) {
310 Mutex::Autolock lock(mFrameEventHistoryMutex);
David Sodman0cf8f8d2017-12-20 18:19:45 -0800311 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
David Sodman0c69cad2017-08-21 12:12:51 -0700312 }
313 mRefreshPending = false;
David Sodman0cf8f8d2017-12-20 18:19:45 -0800314 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
David Sodman0c69cad2017-08-21 12:12:51 -0700315}
David Sodmaneb085e02017-10-05 18:49:04 -0700316bool BufferLayer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
317 const std::shared_ptr<FenceTime>& presentFence,
318 const CompositorTiming& compositorTiming) {
319 // mFrameLatencyNeeded is true when a new frame was latched for the
320 // composition.
321 if (!mFrameLatencyNeeded) return false;
322
323 // Update mFrameEventHistory.
324 {
325 Mutex::Autolock lock(mFrameEventHistoryMutex);
David Sodman0cf8f8d2017-12-20 18:19:45 -0800326 mFrameEventHistory.addPostComposition(mCurrentFrameNumber, glDoneFence, presentFence,
327 compositorTiming);
David Sodmaneb085e02017-10-05 18:49:04 -0700328 }
329
330 // Update mFrameTracker.
Chia-I Wub28c6742017-12-27 10:59:54 -0800331 nsecs_t desiredPresentTime = mConsumer->getTimestamp();
David Sodmaneb085e02017-10-05 18:49:04 -0700332 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
333
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -0700334 const std::string layerName(getName().c_str());
335 mTimeStats.setDesiredTime(layerName, mCurrentFrameNumber, desiredPresentTime);
336
Chia-I Wub28c6742017-12-27 10:59:54 -0800337 std::shared_ptr<FenceTime> frameReadyFence = mConsumer->getCurrentFenceTime();
David Sodmaneb085e02017-10-05 18:49:04 -0700338 if (frameReadyFence->isValid()) {
339 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
340 } else {
341 // There was no fence for this frame, so assume that it was ready
342 // to be presented at the desired present time.
343 mFrameTracker.setFrameReadyTime(desiredPresentTime);
344 }
345
346 if (presentFence->isValid()) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -0700347 mTimeStats.setPresentFence(layerName, mCurrentFrameNumber, presentFence);
David Sodmaneb085e02017-10-05 18:49:04 -0700348 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700349 } else if (mFlinger->getHwComposer().isConnected(HWC_DISPLAY_PRIMARY)) {
David Sodmaneb085e02017-10-05 18:49:04 -0700350 // The HWC doesn't support present fences, so use the refresh
351 // timestamp instead.
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -0700352 const nsecs_t actualPresentTime =
353 mFlinger->getHwComposer().getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
354 mTimeStats.setPresentTime(layerName, mCurrentFrameNumber, actualPresentTime);
355 mFrameTracker.setActualPresentTime(actualPresentTime);
David Sodmaneb085e02017-10-05 18:49:04 -0700356 }
357
358 mFrameTracker.advanceFrame();
359 mFrameLatencyNeeded = false;
360 return true;
361}
362
363std::vector<OccupancyTracker::Segment> BufferLayer::getOccupancyHistory(bool forceFlush) {
364 std::vector<OccupancyTracker::Segment> history;
Chia-I Wub28c6742017-12-27 10:59:54 -0800365 status_t result = mConsumer->getOccupancyHistory(forceFlush, &history);
David Sodmaneb085e02017-10-05 18:49:04 -0700366 if (result != NO_ERROR) {
367 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(), result);
368 return {};
369 }
370 return history;
371}
372
373bool BufferLayer::getTransformToDisplayInverse() const {
Chia-I Wub28c6742017-12-27 10:59:54 -0800374 return mConsumer->getTransformToDisplayInverse();
David Sodmaneb085e02017-10-05 18:49:04 -0700375}
David Sodman0c69cad2017-08-21 12:12:51 -0700376
David Sodman0c69cad2017-08-21 12:12:51 -0700377void BufferLayer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Chia-I Wub28c6742017-12-27 10:59:54 -0800378 if (!mConsumer->releasePendingBuffer()) {
David Sodman0c69cad2017-08-21 12:12:51 -0700379 return;
380 }
381
David Sodman0cf8f8d2017-12-20 18:19:45 -0800382 auto releaseFenceTime = std::make_shared<FenceTime>(mConsumer->getPrevFinalReleaseFence());
David Sodman0c69cad2017-08-21 12:12:51 -0700383 mReleaseTimeline.updateSignalTimes();
384 mReleaseTimeline.push(releaseFenceTime);
385
386 Mutex::Autolock lock(mFrameEventHistoryMutex);
387 if (mPreviousFrameNumber != 0) {
388 mFrameEventHistory.addRelease(mPreviousFrameNumber, dequeueReadyTime,
389 std::move(releaseFenceTime));
390 }
391}
David Sodman0c69cad2017-08-21 12:12:51 -0700392
393Region BufferLayer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
394 ATRACE_CALL();
395
396 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
397 // mSidebandStreamChanged was true
Chia-I Wub28c6742017-12-27 10:59:54 -0800398 mSidebandStream = mConsumer->getSidebandStream();
David Sodman386c22e2017-11-09 16:34:46 -0800399 // replicated in LayerBE until FE/BE is ready to be synchronized
David Sodman0cc69182017-11-17 12:12:07 -0800400 getBE().compositionInfo.hwc.sidebandStream = mSidebandStream;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800401 if (getBE().compositionInfo.hwc.sidebandStream != nullptr) {
David Sodman0c69cad2017-08-21 12:12:51 -0700402 setTransactionFlags(eTransactionNeeded);
403 mFlinger->setTransactionFlags(eTraversalNeeded);
404 }
405 recomputeVisibleRegions = true;
406
407 const State& s(getDrawingState());
408 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
409 }
410
411 Region outDirtyRegion;
412 if (mQueuedFrames <= 0 && !mAutoRefresh) {
413 return outDirtyRegion;
414 }
415
416 // if we've already called updateTexImage() without going through
417 // a composition step, we have to skip this layer at this point
418 // because we cannot call updateTeximage() without a corresponding
419 // compositionComplete() call.
420 // we'll trigger an update in onPreComposition().
421 if (mRefreshPending) {
422 return outDirtyRegion;
423 }
424
425 // If the head buffer's acquire fence hasn't signaled yet, return and
426 // try again later
427 if (!headFenceHasSignaled()) {
428 mFlinger->signalLayerUpdate();
429 return outDirtyRegion;
430 }
431
432 // Capture the old state of the layer for comparisons later
433 const State& s(getDrawingState());
434 const bool oldOpacity = isOpaque(s);
David Sodman0cf8f8d2017-12-20 18:19:45 -0800435 sp<GraphicBuffer> oldBuffer = mActiveBuffer;
David Sodman0c69cad2017-08-21 12:12:51 -0700436
437 if (!allTransactionsSignaled()) {
438 mFlinger->signalLayerUpdate();
439 return outDirtyRegion;
440 }
441
442 // This boolean is used to make sure that SurfaceFlinger's shadow copy
443 // of the buffer queue isn't modified when the buffer queue is returning
444 // BufferItem's that weren't actually queued. This can happen in shared
445 // buffer mode.
446 bool queuedBuffer = false;
447 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
David Sodman0cf8f8d2017-12-20 18:19:45 -0800448 getProducerStickyTransform() != 0, mName.string(), mOverrideScalingMode,
Robert Carr35f0dda2018-05-03 15:47:23 -0700449 getTransformToDisplayInverse(), mFreezeGeometryUpdates);
450
David Sodman0cf8f8d2017-12-20 18:19:45 -0800451 status_t updateResult = mConsumer->updateTexImage(&r, mFlinger->mPrimaryDispSync, &mAutoRefresh,
452 &queuedBuffer, mLastFrameNumberReceived);
Robert Carr35f0dda2018-05-03 15:47:23 -0700453
David Sodman0c69cad2017-08-21 12:12:51 -0700454 if (updateResult == BufferQueue::PRESENT_LATER) {
455 // Producer doesn't want buffer to be displayed yet. Signal a
456 // layer update so we check again at the next opportunity.
457 mFlinger->signalLayerUpdate();
458 return outDirtyRegion;
Chia-I Wu0cb75ac2017-11-27 15:56:04 -0800459 } else if (updateResult == BufferLayerConsumer::BUFFER_REJECTED) {
David Sodman0c69cad2017-08-21 12:12:51 -0700460 // If the buffer has been rejected, remove it from the shadow queue
461 // and return early
462 if (queuedBuffer) {
463 Mutex::Autolock lock(mQueueItemLock);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -0700464 mTimeStats.removeTimeRecord(getName().c_str(), mQueueItems[0].mFrameNumber);
David Sodman0c69cad2017-08-21 12:12:51 -0700465 mQueueItems.removeAt(0);
466 android_atomic_dec(&mQueuedFrames);
467 }
468 return outDirtyRegion;
469 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
470 // This can occur if something goes wrong when trying to create the
471 // EGLImage for this buffer. If this happens, the buffer has already
472 // been released, so we need to clean up the queue and bug out
473 // early.
474 if (queuedBuffer) {
475 Mutex::Autolock lock(mQueueItemLock);
476 mQueueItems.clear();
477 android_atomic_and(0, &mQueuedFrames);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -0700478 mTimeStats.clearLayerRecord(getName().c_str());
David Sodman0c69cad2017-08-21 12:12:51 -0700479 }
480
481 // Once we have hit this state, the shadow queue may no longer
482 // correctly reflect the incoming BufferQueue's contents, so even if
483 // updateTexImage starts working, the only safe course of action is
484 // to continue to ignore updates.
485 mUpdateTexImageFailed = true;
486
487 return outDirtyRegion;
488 }
489
490 if (queuedBuffer) {
491 // Autolock scope
Chia-I Wub28c6742017-12-27 10:59:54 -0800492 auto currentFrameNumber = mConsumer->getFrameNumber();
David Sodman0c69cad2017-08-21 12:12:51 -0700493
494 Mutex::Autolock lock(mQueueItemLock);
495
496 // Remove any stale buffers that have been dropped during
497 // updateTexImage
498 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -0700499 mTimeStats.removeTimeRecord(getName().c_str(), mQueueItems[0].mFrameNumber);
David Sodman0c69cad2017-08-21 12:12:51 -0700500 mQueueItems.removeAt(0);
501 android_atomic_dec(&mQueuedFrames);
502 }
503
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -0700504 const std::string layerName(getName().c_str());
505 mTimeStats.setAcquireFence(layerName, currentFrameNumber, mQueueItems[0].mFenceTime);
506 mTimeStats.setLatchTime(layerName, currentFrameNumber, latchTime);
507
David Sodman0c69cad2017-08-21 12:12:51 -0700508 mQueueItems.removeAt(0);
509 }
510
511 // Decrement the queued-frames count. Signal another event if we
512 // have more frames pending.
David Sodman0cf8f8d2017-12-20 18:19:45 -0800513 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1) || mAutoRefresh) {
David Sodman0c69cad2017-08-21 12:12:51 -0700514 mFlinger->signalLayerUpdate();
515 }
516
517 // update the active buffer
David Sodman0cf8f8d2017-12-20 18:19:45 -0800518 mActiveBuffer = mConsumer->getCurrentBuffer(&mActiveBufferSlot);
519 getBE().compositionInfo.mBuffer = mActiveBuffer;
520 getBE().compositionInfo.mBufferSlot = mActiveBufferSlot;
521
522 if (mActiveBuffer == nullptr) {
David Sodman0c69cad2017-08-21 12:12:51 -0700523 // this can only happen if the very first buffer was rejected.
524 return outDirtyRegion;
525 }
526
527 mBufferLatched = true;
528 mPreviousFrameNumber = mCurrentFrameNumber;
Chia-I Wub28c6742017-12-27 10:59:54 -0800529 mCurrentFrameNumber = mConsumer->getFrameNumber();
David Sodman0c69cad2017-08-21 12:12:51 -0700530
531 {
532 Mutex::Autolock lock(mFrameEventHistoryMutex);
533 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
David Sodman0c69cad2017-08-21 12:12:51 -0700534 }
535
536 mRefreshPending = true;
537 mFrameLatencyNeeded = true;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800538 if (oldBuffer == nullptr) {
David Sodman0c69cad2017-08-21 12:12:51 -0700539 // the first time we receive a buffer, we need to trigger a
540 // geometry invalidation.
541 recomputeVisibleRegions = true;
542 }
543
Peiyong Lin923e7c52018-04-16 14:16:37 -0700544 ui::Dataspace dataSpace = mConsumer->getCurrentDataSpace();
Chia-I Wu11481472018-05-04 10:43:19 -0700545 // treat modern dataspaces as legacy dataspaces whenever possible, until
546 // we can trust the buffer producers
Peiyong Lin923e7c52018-04-16 14:16:37 -0700547 switch (dataSpace) {
548 case ui::Dataspace::V0_SRGB:
549 dataSpace = ui::Dataspace::SRGB;
550 break;
551 case ui::Dataspace::V0_SRGB_LINEAR:
552 dataSpace = ui::Dataspace::SRGB_LINEAR;
553 break;
Chia-I Wu11481472018-05-04 10:43:19 -0700554 case ui::Dataspace::V0_JFIF:
555 dataSpace = ui::Dataspace::JFIF;
556 break;
557 case ui::Dataspace::V0_BT601_625:
558 dataSpace = ui::Dataspace::BT601_625;
559 break;
560 case ui::Dataspace::V0_BT601_525:
561 dataSpace = ui::Dataspace::BT601_525;
562 break;
563 case ui::Dataspace::V0_BT709:
564 dataSpace = ui::Dataspace::BT709;
Peiyong Lin923e7c52018-04-16 14:16:37 -0700565 break;
566 default:
567 break;
568 }
Chia-I Wu01591c92018-05-22 12:03:00 -0700569 mCurrentDataSpace = dataSpace;
David Sodman0c69cad2017-08-21 12:12:51 -0700570
Chia-I Wub28c6742017-12-27 10:59:54 -0800571 Rect crop(mConsumer->getCurrentCrop());
572 const uint32_t transform(mConsumer->getCurrentTransform());
573 const uint32_t scalingMode(mConsumer->getCurrentScalingMode());
David Sodman0cf8f8d2017-12-20 18:19:45 -0800574 if ((crop != mCurrentCrop) || (transform != mCurrentTransform) ||
David Sodman0c69cad2017-08-21 12:12:51 -0700575 (scalingMode != mCurrentScalingMode)) {
576 mCurrentCrop = crop;
577 mCurrentTransform = transform;
578 mCurrentScalingMode = scalingMode;
579 recomputeVisibleRegions = true;
580 }
581
Peiyong Lin566a3b42018-01-09 18:22:43 -0800582 if (oldBuffer != nullptr) {
David Sodman0cf8f8d2017-12-20 18:19:45 -0800583 uint32_t bufWidth = mActiveBuffer->getWidth();
584 uint32_t bufHeight = mActiveBuffer->getHeight();
585 if (bufWidth != uint32_t(oldBuffer->width) || bufHeight != uint32_t(oldBuffer->height)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700586 recomputeVisibleRegions = true;
587 }
588 }
589
David Sodman0cf8f8d2017-12-20 18:19:45 -0800590 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
David Sodman0c69cad2017-08-21 12:12:51 -0700591 if (oldOpacity != isOpaque(s)) {
592 recomputeVisibleRegions = true;
593 }
594
595 // Remove any sync points corresponding to the buffer which was just
596 // latched
597 {
598 Mutex::Autolock lock(mLocalSyncPointMutex);
599 auto point = mLocalSyncPoints.begin();
600 while (point != mLocalSyncPoints.end()) {
601 if (!(*point)->frameIsAvailable() || !(*point)->transactionIsApplied()) {
602 // This sync point must have been added since we started
603 // latching. Don't drop it yet.
604 ++point;
605 continue;
606 }
607
608 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
609 point = mLocalSyncPoints.erase(point);
610 } else {
611 ++point;
612 }
613 }
614 }
615
616 // FIXME: postedRegion should be dirty & bounds
617 Region dirtyRegion(Rect(s.active.w, s.active.h));
618
619 // transform the dirty region to window-manager space
620 outDirtyRegion = (getTransform().transform(dirtyRegion));
621
622 return outDirtyRegion;
623}
624
David Sodmaneb085e02017-10-05 18:49:04 -0700625void BufferLayer::setDefaultBufferSize(uint32_t w, uint32_t h) {
Chia-I Wub28c6742017-12-27 10:59:54 -0800626 mConsumer->setDefaultBufferSize(w, h);
David Sodmaneb085e02017-10-05 18:49:04 -0700627}
628
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700629void BufferLayer::setPerFrameData(const sp<const DisplayDevice>& display) {
David Sodman0c69cad2017-08-21 12:12:51 -0700630 // Apply this display's projection's viewport to the visible region
631 // before giving it to the HWC HAL.
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700632 const Transform& tr = display->getTransform();
633 const auto& viewport = display->getViewport();
David Sodman0c69cad2017-08-21 12:12:51 -0700634 Region visible = tr.transform(visibleRegion.intersect(viewport));
Dominik Laskowski7e045462018-05-30 13:02:02 -0700635 const auto displayId = display->getId();
Peiyong Lin91b1df22018-06-18 18:00:16 -0700636 if (!hasHwcLayer(displayId)) {
637 ALOGE("[%s] failed to setPerFrameData: no HWC layer found (%d)",
638 mName.string(), displayId);
639 return;
640 }
Dominik Laskowski7e045462018-05-30 13:02:02 -0700641 auto& hwcInfo = getBE().mHwcLayers[displayId];
Chia-I Wu30505fb2018-03-26 16:20:31 -0700642 auto& hwcLayer = hwcInfo.layer;
David Sodmanf6a38932018-05-25 15:27:50 -0700643 auto error = hwcLayer->setVisibleRegion(visible);
Chia-I Wu30505fb2018-03-26 16:20:31 -0700644 if (error != HWC2::Error::None) {
645 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
646 to_string(error).c_str(), static_cast<int32_t>(error));
647 visible.dump(LOG_TAG);
648 }
David Sodman0c69cad2017-08-21 12:12:51 -0700649
David Sodmanf6a38932018-05-25 15:27:50 -0700650 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
Chia-I Wu30505fb2018-03-26 16:20:31 -0700651 if (error != HWC2::Error::None) {
652 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
653 to_string(error).c_str(), static_cast<int32_t>(error));
654 surfaceDamageRegion.dump(LOG_TAG);
655 }
David Sodman0c69cad2017-08-21 12:12:51 -0700656
657 // Sideband layers
David Sodman0cc69182017-11-17 12:12:07 -0800658 if (getBE().compositionInfo.hwc.sidebandStream.get()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -0700659 setCompositionType(displayId, HWC2::Composition::Sideband);
Chia-I Wu30505fb2018-03-26 16:20:31 -0700660 ALOGV("[%s] Requesting Sideband composition", mName.string());
David Sodmanf6a38932018-05-25 15:27:50 -0700661 error = hwcLayer->setSidebandStream(getBE().compositionInfo.hwc.sidebandStream->handle());
Chia-I Wu30505fb2018-03-26 16:20:31 -0700662 if (error != HWC2::Error::None) {
663 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", mName.string(),
664 getBE().compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
665 static_cast<int32_t>(error));
666 }
David Sodman0c69cad2017-08-21 12:12:51 -0700667 return;
668 }
669
David Sodman0c69cad2017-08-21 12:12:51 -0700670 // Device or Cursor layers
671 if (mPotentialCursor) {
672 ALOGV("[%s] Requesting Cursor composition", mName.string());
Dominik Laskowski7e045462018-05-30 13:02:02 -0700673 setCompositionType(displayId, HWC2::Composition::Cursor);
David Sodman0c69cad2017-08-21 12:12:51 -0700674 } else {
675 ALOGV("[%s] Requesting Device composition", mName.string());
Dominik Laskowski7e045462018-05-30 13:02:02 -0700676 setCompositionType(displayId, HWC2::Composition::Device);
David Sodman0c69cad2017-08-21 12:12:51 -0700677 }
678
Chia-I Wu01591c92018-05-22 12:03:00 -0700679 ALOGV("setPerFrameData: dataspace = %d", mCurrentDataSpace);
David Sodmanf6a38932018-05-25 15:27:50 -0700680 error = hwcLayer->setDataspace(mCurrentDataSpace);
Chia-I Wu30505fb2018-03-26 16:20:31 -0700681 if (error != HWC2::Error::None) {
Chia-I Wu01591c92018-05-22 12:03:00 -0700682 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(), mCurrentDataSpace,
Chia-I Wu30505fb2018-03-26 16:20:31 -0700683 to_string(error).c_str(), static_cast<int32_t>(error));
684 }
685
686 const HdrMetadata& metadata = mConsumer->getCurrentHdrMetadata();
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700687 error = hwcLayer->setPerFrameMetadata(display->getSupportedPerFrameMetadata(), metadata);
Chia-I Wu30505fb2018-03-26 16:20:31 -0700688 if (error != HWC2::Error::None && error != HWC2::Error::Unsupported) {
689 ALOGE("[%s] Failed to set hdrMetadata: %s (%d)", mName.string(),
690 to_string(error).c_str(), static_cast<int32_t>(error));
691 }
692
693 uint32_t hwcSlot = 0;
694 sp<GraphicBuffer> hwcBuffer;
Peiyong Lin91b1df22018-06-18 18:00:16 -0700695 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer, &hwcSlot, &hwcBuffer);
David Sodman0c69cad2017-08-21 12:12:51 -0700696
Chia-I Wub28c6742017-12-27 10:59:54 -0800697 auto acquireFence = mConsumer->getCurrentFence();
David Sodmanf6a38932018-05-25 15:27:50 -0700698 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
Chia-I Wu30505fb2018-03-26 16:20:31 -0700699 if (error != HWC2::Error::None) {
700 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
701 getBE().compositionInfo.mBuffer->handle, to_string(error).c_str(),
702 static_cast<int32_t>(error));
703 }
David Sodman0c69cad2017-08-21 12:12:51 -0700704}
705
David Sodman41fdfc92017-11-06 16:09:56 -0800706bool BufferLayer::isOpaque(const Layer::State& s) const {
David Sodman0c69cad2017-08-21 12:12:51 -0700707 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
708 // layer's opaque flag.
David Sodman0cf8f8d2017-12-20 18:19:45 -0800709 if ((getBE().compositionInfo.hwc.sidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700710 return false;
711 }
712
713 // if the layer has the opaque flag, then we're always opaque,
714 // otherwise we use the current buffer's format.
715 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
716}
717
718void BufferLayer::onFirstRef() {
719 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
720 sp<IGraphicBufferProducer> producer;
721 sp<IGraphicBufferConsumer> consumer;
722 BufferQueue::createBufferQueue(&producer, &consumer, true);
723 mProducer = new MonitoredProducer(producer, mFlinger, this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700724 {
725 // Grab the SF state lock during this since it's the only safe way to access RenderEngine
726 Mutex::Autolock lock(mFlinger->mStateLock);
727 mConsumer = new BufferLayerConsumer(consumer, mFlinger->getRenderEngine(), mTextureName,
728 this);
729 }
Chia-I Wub28c6742017-12-27 10:59:54 -0800730 mConsumer->setConsumerUsageBits(getEffectiveUsage(0));
731 mConsumer->setContentsChangedListener(this);
732 mConsumer->setName(mName);
David Sodman0c69cad2017-08-21 12:12:51 -0700733
734 if (mFlinger->isLayerTripleBufferingDisabled()) {
735 mProducer->setMaxDequeuedBufferCount(2);
736 }
737
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700738 if (const auto display = mFlinger->getDefaultDisplayDevice()) {
739 updateTransformHint(display);
740 }
David Sodman0c69cad2017-08-21 12:12:51 -0700741}
742
743// ---------------------------------------------------------------------------
744// Interface implementation for SurfaceFlingerConsumer::ContentsChangedListener
745// ---------------------------------------------------------------------------
746
747void BufferLayer::onFrameAvailable(const BufferItem& item) {
748 // Add this buffer from our internal queue tracker
749 { // Autolock scope
750 Mutex::Autolock lock(mQueueItemLock);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800751 mFlinger->mInterceptor->saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
752 item.mGraphicBuffer->getHeight(),
753 item.mFrameNumber);
David Sodman0c69cad2017-08-21 12:12:51 -0700754 // Reset the frame number tracker when we receive the first buffer after
755 // a frame number reset
756 if (item.mFrameNumber == 1) {
757 mLastFrameNumberReceived = 0;
758 }
759
760 // Ensure that callbacks are handled in order
761 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
David Sodman0cf8f8d2017-12-20 18:19:45 -0800762 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock, ms2ns(500));
David Sodman0c69cad2017-08-21 12:12:51 -0700763 if (result != NO_ERROR) {
764 ALOGE("[%s] Timed out waiting on callback", mName.string());
765 }
766 }
767
768 mQueueItems.push_back(item);
769 android_atomic_inc(&mQueuedFrames);
770
771 // Wake up any pending callbacks
772 mLastFrameNumberReceived = item.mFrameNumber;
773 mQueueItemCondition.broadcast();
774 }
775
776 mFlinger->signalLayerUpdate();
777}
778
779void BufferLayer::onFrameReplaced(const BufferItem& item) {
780 { // Autolock scope
781 Mutex::Autolock lock(mQueueItemLock);
782
783 // Ensure that callbacks are handled in order
784 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
David Sodman0cf8f8d2017-12-20 18:19:45 -0800785 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock, ms2ns(500));
David Sodman0c69cad2017-08-21 12:12:51 -0700786 if (result != NO_ERROR) {
787 ALOGE("[%s] Timed out waiting on callback", mName.string());
788 }
789 }
790
791 if (mQueueItems.empty()) {
792 ALOGE("Can't replace a frame on an empty queue");
793 return;
794 }
795 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
796
797 // Wake up any pending callbacks
798 mLastFrameNumberReceived = item.mFrameNumber;
799 mQueueItemCondition.broadcast();
800 }
801}
802
803void BufferLayer::onSidebandStreamChanged() {
804 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
805 // mSidebandStreamChanged was false
806 mFlinger->signalLayerUpdate();
807 }
808}
809
810bool BufferLayer::needsFiltering(const RenderArea& renderArea) const {
811 return mNeedsFiltering || renderArea.needsFiltering();
812}
813
814// As documented in libhardware header, formats in the range
815// 0x100 - 0x1FF are specific to the HAL implementation, and
816// are known to have no alpha channel
817// TODO: move definition for device-specific range into
818// hardware.h, instead of using hard-coded values here.
819#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
820
821bool BufferLayer::getOpacityForFormat(uint32_t format) {
822 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
823 return true;
824 }
825 switch (format) {
826 case HAL_PIXEL_FORMAT_RGBA_8888:
827 case HAL_PIXEL_FORMAT_BGRA_8888:
828 case HAL_PIXEL_FORMAT_RGBA_FP16:
829 case HAL_PIXEL_FORMAT_RGBA_1010102:
830 return false;
831 }
832 // in all other case, we have no blending (also for unknown formats)
833 return true;
834}
835
Chia-I Wu692e0832018-06-05 15:46:58 -0700836bool BufferLayer::isHdrY410() const {
837 // pixel format is HDR Y410 masquerading as RGBA_1010102
838 return (mCurrentDataSpace == ui::Dataspace::BT2020_ITU_PQ &&
839 mConsumer->getCurrentApi() == NATIVE_WINDOW_API_MEDIA &&
840 getBE().compositionInfo.mBuffer->getPixelFormat() == HAL_PIXEL_FORMAT_RGBA_1010102);
841}
842
David Sodman41fdfc92017-11-06 16:09:56 -0800843void BufferLayer::drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const {
Dan Stoza84d619e2018-03-28 17:07:36 -0700844 ATRACE_CALL();
David Sodman0c69cad2017-08-21 12:12:51 -0700845 const State& s(getDrawingState());
846
David Sodman9eeae692017-11-02 10:53:32 -0700847 computeGeometry(renderArea, getBE().mMesh, useIdentityTransform);
David Sodman0c69cad2017-08-21 12:12:51 -0700848
849 /*
850 * NOTE: the way we compute the texture coordinates here produces
851 * different results than when we take the HWC path -- in the later case
852 * the "source crop" is rounded to texel boundaries.
853 * This can produce significantly different results when the texture
854 * is scaled by a large amount.
855 *
856 * The GL code below is more logical (imho), and the difference with
857 * HWC is due to a limitation of the HWC API to integers -- a question
858 * is suspend is whether we should ignore this problem or revert to
859 * GL composition when a buffer scaling is applied (maybe with some
860 * minimal value)? Or, we could make GL behave like HWC -- but this feel
861 * like more of a hack.
862 */
Dan Stoza80d61162017-12-20 15:57:52 -0800863 const Rect bounds{computeBounds()}; // Rounds from FloatRect
David Sodman0c69cad2017-08-21 12:12:51 -0700864
865 Transform t = getTransform();
Dan Stoza80d61162017-12-20 15:57:52 -0800866 Rect win = bounds;
David Sodman0c69cad2017-08-21 12:12:51 -0700867 if (!s.finalCrop.isEmpty()) {
868 win = t.transform(win);
869 if (!win.intersect(s.finalCrop, &win)) {
870 win.clear();
871 }
872 win = t.inverse().transform(win);
Dan Stoza80d61162017-12-20 15:57:52 -0800873 if (!win.intersect(bounds, &win)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700874 win.clear();
875 }
876 }
877
878 float left = float(win.left) / float(s.active.w);
879 float top = float(win.top) / float(s.active.h);
880 float right = float(win.right) / float(s.active.w);
881 float bottom = float(win.bottom) / float(s.active.h);
882
883 // TODO: we probably want to generate the texture coords with the mesh
884 // here we assume that we only have 4 vertices
David Sodman9eeae692017-11-02 10:53:32 -0700885 Mesh::VertexArray<vec2> texCoords(getBE().mMesh.getTexCoordArray<vec2>());
David Sodman0c69cad2017-08-21 12:12:51 -0700886 texCoords[0] = vec2(left, 1.0f - top);
887 texCoords[1] = vec2(left, 1.0f - bottom);
888 texCoords[2] = vec2(right, 1.0f - bottom);
889 texCoords[3] = vec2(right, 1.0f - top);
890
bohu21566132018-03-27 14:36:34 -0700891 auto& engine(mFlinger->getRenderEngine());
892 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), false /* disableTexture */,
893 getColor());
Chia-I Wu01591c92018-05-22 12:03:00 -0700894 engine.setSourceDataSpace(mCurrentDataSpace);
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800895
Chia-I Wu692e0832018-06-05 15:46:58 -0700896 if (isHdrY410()) {
bohu21566132018-03-27 14:36:34 -0700897 engine.setSourceY410BT2020(true);
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800898 }
bohu21566132018-03-27 14:36:34 -0700899
900 engine.drawMesh(getBE().mMesh);
901 engine.disableBlending();
902
903 engine.setSourceY410BT2020(false);
David Sodman0c69cad2017-08-21 12:12:51 -0700904}
905
906uint32_t BufferLayer::getProducerStickyTransform() const {
907 int producerStickyTransform = 0;
908 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
909 if (ret != OK) {
910 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
911 strerror(-ret), ret);
912 return 0;
913 }
914 return static_cast<uint32_t>(producerStickyTransform);
915}
916
917bool BufferLayer::latchUnsignaledBuffers() {
918 static bool propertyLoaded = false;
919 static bool latch = false;
920 static std::mutex mutex;
921 std::lock_guard<std::mutex> lock(mutex);
922 if (!propertyLoaded) {
923 char value[PROPERTY_VALUE_MAX] = {};
924 property_get("debug.sf.latch_unsignaled", value, "0");
925 latch = atoi(value);
926 propertyLoaded = true;
927 }
928 return latch;
929}
930
931uint64_t BufferLayer::getHeadFrameNumber() const {
932 Mutex::Autolock lock(mQueueItemLock);
933 if (!mQueueItems.empty()) {
934 return mQueueItems[0].mFrameNumber;
935 } else {
936 return mCurrentFrameNumber;
937 }
938}
939
940bool BufferLayer::headFenceHasSignaled() const {
David Sodman0c69cad2017-08-21 12:12:51 -0700941 if (latchUnsignaledBuffers()) {
942 return true;
943 }
944
945 Mutex::Autolock lock(mQueueItemLock);
946 if (mQueueItems.empty()) {
947 return true;
948 }
949 if (mQueueItems[0].mIsDroppable) {
950 // Even though this buffer's fence may not have signaled yet, it could
951 // be replaced by another buffer before it has a chance to, which means
952 // that it's possible to get into a situation where a buffer is never
953 // able to be latched. To avoid this, grab this buffer anyway.
954 return true;
955 }
David Sodman0cf8f8d2017-12-20 18:19:45 -0800956 return mQueueItems[0].mFenceTime->getSignalTime() != Fence::SIGNAL_TIME_PENDING;
David Sodman0c69cad2017-08-21 12:12:51 -0700957}
958
959uint32_t BufferLayer::getEffectiveScalingMode() const {
960 if (mOverrideScalingMode >= 0) {
961 return mOverrideScalingMode;
962 }
963 return mCurrentScalingMode;
964}
965
966// ----------------------------------------------------------------------------
967// transaction
968// ----------------------------------------------------------------------------
969
970void BufferLayer::notifyAvailableFrames() {
971 auto headFrameNumber = getHeadFrameNumber();
972 bool headFenceSignaled = headFenceHasSignaled();
973 Mutex::Autolock lock(mLocalSyncPointMutex);
974 for (auto& point : mLocalSyncPoints) {
975 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
976 point->setFrameAvailable();
977 }
978 }
979}
980
981sp<IGraphicBufferProducer> BufferLayer::getProducer() const {
982 return mProducer;
983}
984
985// ---------------------------------------------------------------------------
986// h/w composer set-up
987// ---------------------------------------------------------------------------
988
989bool BufferLayer::allTransactionsSignaled() {
990 auto headFrameNumber = getHeadFrameNumber();
991 bool matchingFramesFound = false;
992 bool allTransactionsApplied = true;
993 Mutex::Autolock lock(mLocalSyncPointMutex);
994
995 for (auto& point : mLocalSyncPoints) {
996 if (point->getFrameNumber() > headFrameNumber) {
997 break;
998 }
999 matchingFramesFound = true;
1000
1001 if (!point->frameIsAvailable()) {
1002 // We haven't notified the remote layer that the frame for
1003 // this point is available yet. Notify it now, and then
1004 // abort this attempt to latch.
1005 point->setFrameAvailable();
1006 allTransactionsApplied = false;
1007 break;
1008 }
1009
1010 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
1011 }
1012 return !matchingFramesFound || allTransactionsApplied;
1013}
1014
1015} // namespace android
1016
1017#if defined(__gl_h_)
1018#error "don't include gl/gl.h in this file"
1019#endif
1020
1021#if defined(__gl2_h_)
1022#error "don't include gl2/gl2.h in this file"
1023#endif