blob: 4c3844e1300718a8c261d243025d7a91272ab6b3 [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 Sodman0cc69182017-11-17 12:12:07 -0800101 const sp<GraphicBuffer>& buffer(getBE().compositionInfo.mBuffer);
David Sodman5b4cffc2017-11-23 13:20:29 -0800102 return (buffer != 0) &&
103 (buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
David Sodman0c69cad2017-08-21 12:12:51 -0700104}
105
106bool BufferLayer::isVisible() const {
107 return !(isHiddenByPolicy()) && getAlpha() > 0.0f &&
Peiyong Lin566a3b42018-01-09 18:22:43 -0800108 (getBE().compositionInfo.mBuffer != nullptr ||
109 getBE().compositionInfo.hwc.sidebandStream != nullptr);
David Sodman0c69cad2017-08-21 12:12:51 -0700110}
111
112bool BufferLayer::isFixedSize() const {
113 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
114}
115
116status_t BufferLayer::setBuffers(uint32_t w, uint32_t h, PixelFormat format, uint32_t flags) {
117 uint32_t const maxSurfaceDims =
118 min(mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
119
120 // never allow a surface larger than what our underlying GL implementation
121 // can handle.
122 if ((uint32_t(w) > maxSurfaceDims) || (uint32_t(h) > maxSurfaceDims)) {
123 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
124 return BAD_VALUE;
125 }
126
127 mFormat = format;
128
129 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
130 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
131 mCurrentOpacity = getOpacityForFormat(format);
132
Chia-I Wub28c6742017-12-27 10:59:54 -0800133 mConsumer->setDefaultBufferSize(w, h);
134 mConsumer->setDefaultBufferFormat(format);
135 mConsumer->setConsumerUsageBits(getEffectiveUsage(0));
David Sodman0c69cad2017-08-21 12:12:51 -0700136
137 return NO_ERROR;
138}
139
140static constexpr mat4 inverseOrientation(uint32_t transform) {
David Sodman41fdfc92017-11-06 16:09:56 -0800141 const mat4 flipH(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
142 const mat4 flipV(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
143 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 -0700144 mat4 tr;
145
146 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
147 tr = tr * rot90;
148 }
149 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
150 tr = tr * flipH;
151 }
152 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
153 tr = tr * flipV;
154 }
155 return inverse(tr);
156}
157
158/*
159 * onDraw will draw the current layer onto the presentable buffer
160 */
161void BufferLayer::onDraw(const RenderArea& renderArea, const Region& clip,
162 bool useIdentityTransform) const {
163 ATRACE_CALL();
164
David Sodman0cc69182017-11-17 12:12:07 -0800165 if (CC_UNLIKELY(getBE().compositionInfo.mBuffer == 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 Sodman0cc69182017-11-17 12:12:07 -0800243 mTexture.setDimensions(getBE().compositionInfo.mBuffer->getWidth(),
244 getBE().compositionInfo.mBuffer->getHeight());
David Sodman0c69cad2017-08-21 12:12:51 -0700245 mTexture.setFiltering(useFiltering);
246 mTexture.setMatrix(textureMatrix);
247
248 engine.setupLayerTexturing(mTexture);
249 } else {
250 engine.setupLayerBlackedOut();
251 }
252 drawWithOpenGL(renderArea, useIdentityTransform);
253 engine.disableTexturing();
254}
255
David Sodmaneb085e02017-10-05 18:49:04 -0700256void BufferLayer::onLayerDisplayed(const sp<Fence>& releaseFence) {
Chia-I Wub28c6742017-12-27 10:59:54 -0800257 mConsumer->setReleaseFence(releaseFence);
David Sodmaneb085e02017-10-05 18:49:04 -0700258}
David Sodmaneb085e02017-10-05 18:49:04 -0700259
260void BufferLayer::abandon() {
Chia-I Wub28c6742017-12-27 10:59:54 -0800261 mConsumer->abandon();
David Sodmaneb085e02017-10-05 18:49:04 -0700262}
263
264bool BufferLayer::shouldPresentNow(const DispSync& dispSync) const {
265 if (mSidebandStreamChanged || mAutoRefresh) {
266 return true;
267 }
268
269 Mutex::Autolock lock(mQueueItemLock);
270 if (mQueueItems.empty()) {
271 return false;
272 }
273 auto timestamp = mQueueItems[0].mTimestamp;
Chia-I Wub28c6742017-12-27 10:59:54 -0800274 nsecs_t expectedPresent = mConsumer->computeExpectedPresent(dispSync);
David Sodmaneb085e02017-10-05 18:49:04 -0700275
276 // Ignore timestamps more than a second in the future
277 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
278 ALOGW_IF(!isPlausible,
279 "[%s] Timestamp %" PRId64 " seems implausible "
280 "relative to expectedPresent %" PRId64,
281 mName.string(), timestamp, expectedPresent);
282
283 bool isDue = timestamp < expectedPresent;
284 return isDue || !isPlausible;
285}
286
287void BufferLayer::setTransformHint(uint32_t orientation) const {
Chia-I Wub28c6742017-12-27 10:59:54 -0800288 mConsumer->setTransformHint(orientation);
David Sodmaneb085e02017-10-05 18:49:04 -0700289}
290
David Sodman0c69cad2017-08-21 12:12:51 -0700291bool BufferLayer::onPreComposition(nsecs_t refreshStartTime) {
292 if (mBufferLatched) {
293 Mutex::Autolock lock(mFrameEventHistoryMutex);
David Sodman9eeae692017-11-02 10:53:32 -0700294 mFrameEventHistory.addPreComposition(mCurrentFrameNumber,
295 refreshStartTime);
David Sodman0c69cad2017-08-21 12:12:51 -0700296 }
297 mRefreshPending = false;
David Sodman9eeae692017-11-02 10:53:32 -0700298 return mQueuedFrames > 0 || mSidebandStreamChanged ||
299 mAutoRefresh;
David Sodman0c69cad2017-08-21 12:12:51 -0700300}
David Sodmaneb085e02017-10-05 18:49:04 -0700301bool BufferLayer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
302 const std::shared_ptr<FenceTime>& presentFence,
303 const CompositorTiming& compositorTiming) {
304 // mFrameLatencyNeeded is true when a new frame was latched for the
305 // composition.
306 if (!mFrameLatencyNeeded) return false;
307
308 // Update mFrameEventHistory.
309 {
310 Mutex::Autolock lock(mFrameEventHistoryMutex);
David Sodman9eeae692017-11-02 10:53:32 -0700311 mFrameEventHistory.addPostComposition(mCurrentFrameNumber, glDoneFence,
312 presentFence, compositorTiming);
David Sodmaneb085e02017-10-05 18:49:04 -0700313 }
314
315 // Update mFrameTracker.
Chia-I Wub28c6742017-12-27 10:59:54 -0800316 nsecs_t desiredPresentTime = mConsumer->getTimestamp();
David Sodmaneb085e02017-10-05 18:49:04 -0700317 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
318
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700319 const std::string layerName(getName().c_str());
320 mTimeStats.setDesiredTime(layerName, mCurrentFrameNumber, desiredPresentTime);
321
Chia-I Wub28c6742017-12-27 10:59:54 -0800322 std::shared_ptr<FenceTime> frameReadyFence = mConsumer->getCurrentFenceTime();
David Sodmaneb085e02017-10-05 18:49:04 -0700323 if (frameReadyFence->isValid()) {
324 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
325 } else {
326 // There was no fence for this frame, so assume that it was ready
327 // to be presented at the desired present time.
328 mFrameTracker.setFrameReadyTime(desiredPresentTime);
329 }
330
331 if (presentFence->isValid()) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700332 mTimeStats.setPresentFence(layerName, mCurrentFrameNumber, presentFence);
David Sodmaneb085e02017-10-05 18:49:04 -0700333 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
334 } else {
335 // The HWC doesn't support present fences, so use the refresh
336 // timestamp instead.
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700337 const nsecs_t actualPresentTime =
338 mFlinger->getHwComposer().getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
339 mTimeStats.setPresentTime(layerName, mCurrentFrameNumber, actualPresentTime);
340 mFrameTracker.setActualPresentTime(actualPresentTime);
David Sodmaneb085e02017-10-05 18:49:04 -0700341 }
342
343 mFrameTracker.advanceFrame();
344 mFrameLatencyNeeded = false;
345 return true;
346}
347
348std::vector<OccupancyTracker::Segment> BufferLayer::getOccupancyHistory(bool forceFlush) {
349 std::vector<OccupancyTracker::Segment> history;
Chia-I Wub28c6742017-12-27 10:59:54 -0800350 status_t result = mConsumer->getOccupancyHistory(forceFlush, &history);
David Sodmaneb085e02017-10-05 18:49:04 -0700351 if (result != NO_ERROR) {
352 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(), result);
353 return {};
354 }
355 return history;
356}
357
358bool BufferLayer::getTransformToDisplayInverse() const {
Chia-I Wub28c6742017-12-27 10:59:54 -0800359 return mConsumer->getTransformToDisplayInverse();
David Sodmaneb085e02017-10-05 18:49:04 -0700360}
David Sodman0c69cad2017-08-21 12:12:51 -0700361
David Sodman0c69cad2017-08-21 12:12:51 -0700362void BufferLayer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Chia-I Wub28c6742017-12-27 10:59:54 -0800363 if (!mConsumer->releasePendingBuffer()) {
David Sodman0c69cad2017-08-21 12:12:51 -0700364 return;
365 }
366
367 auto releaseFenceTime =
Chia-I Wub28c6742017-12-27 10:59:54 -0800368 std::make_shared<FenceTime>(mConsumer->getPrevFinalReleaseFence());
David Sodman0c69cad2017-08-21 12:12:51 -0700369 mReleaseTimeline.updateSignalTimes();
370 mReleaseTimeline.push(releaseFenceTime);
371
372 Mutex::Autolock lock(mFrameEventHistoryMutex);
373 if (mPreviousFrameNumber != 0) {
374 mFrameEventHistory.addRelease(mPreviousFrameNumber, dequeueReadyTime,
375 std::move(releaseFenceTime));
376 }
377}
David Sodman0c69cad2017-08-21 12:12:51 -0700378
379Region BufferLayer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
380 ATRACE_CALL();
381
382 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
383 // mSidebandStreamChanged was true
Chia-I Wub28c6742017-12-27 10:59:54 -0800384 mSidebandStream = mConsumer->getSidebandStream();
David Sodman386c22e2017-11-09 16:34:46 -0800385 // replicated in LayerBE until FE/BE is ready to be synchronized
David Sodman0cc69182017-11-17 12:12:07 -0800386 getBE().compositionInfo.hwc.sidebandStream = mSidebandStream;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800387 if (getBE().compositionInfo.hwc.sidebandStream != nullptr) {
David Sodman0c69cad2017-08-21 12:12:51 -0700388 setTransactionFlags(eTransactionNeeded);
389 mFlinger->setTransactionFlags(eTraversalNeeded);
390 }
391 recomputeVisibleRegions = true;
392
393 const State& s(getDrawingState());
394 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
395 }
396
397 Region outDirtyRegion;
398 if (mQueuedFrames <= 0 && !mAutoRefresh) {
399 return outDirtyRegion;
400 }
401
402 // if we've already called updateTexImage() without going through
403 // a composition step, we have to skip this layer at this point
404 // because we cannot call updateTeximage() without a corresponding
405 // compositionComplete() call.
406 // we'll trigger an update in onPreComposition().
407 if (mRefreshPending) {
408 return outDirtyRegion;
409 }
410
411 // If the head buffer's acquire fence hasn't signaled yet, return and
412 // try again later
413 if (!headFenceHasSignaled()) {
414 mFlinger->signalLayerUpdate();
415 return outDirtyRegion;
416 }
417
418 // Capture the old state of the layer for comparisons later
419 const State& s(getDrawingState());
420 const bool oldOpacity = isOpaque(s);
David Sodman0cc69182017-11-17 12:12:07 -0800421 sp<GraphicBuffer> oldBuffer = getBE().compositionInfo.mBuffer;
David Sodman0c69cad2017-08-21 12:12:51 -0700422
423 if (!allTransactionsSignaled()) {
424 mFlinger->signalLayerUpdate();
425 return outDirtyRegion;
426 }
427
428 // This boolean is used to make sure that SurfaceFlinger's shadow copy
429 // of the buffer queue isn't modified when the buffer queue is returning
430 // BufferItem's that weren't actually queued. This can happen in shared
431 // buffer mode.
432 bool queuedBuffer = false;
433 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
David Sodman9eeae692017-11-02 10:53:32 -0700434 getProducerStickyTransform() != 0, mName.string(),
435 mOverrideScalingMode, mFreezeGeometryUpdates);
David Sodman0c69cad2017-08-21 12:12:51 -0700436 status_t updateResult =
Chia-I Wub28c6742017-12-27 10:59:54 -0800437 mConsumer->updateTexImage(&r, mFlinger->mPrimaryDispSync,
David Sodman9eeae692017-11-02 10:53:32 -0700438 &mAutoRefresh, &queuedBuffer,
439 mLastFrameNumberReceived);
David Sodman0c69cad2017-08-21 12:12:51 -0700440 if (updateResult == BufferQueue::PRESENT_LATER) {
441 // Producer doesn't want buffer to be displayed yet. Signal a
442 // layer update so we check again at the next opportunity.
443 mFlinger->signalLayerUpdate();
444 return outDirtyRegion;
Chia-I Wu0cb75ac2017-11-27 15:56:04 -0800445 } else if (updateResult == BufferLayerConsumer::BUFFER_REJECTED) {
David Sodman0c69cad2017-08-21 12:12:51 -0700446 // If the buffer has been rejected, remove it from the shadow queue
447 // and return early
448 if (queuedBuffer) {
449 Mutex::Autolock lock(mQueueItemLock);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700450 mTimeStats.removeTimeRecord(getName().c_str(), mQueueItems[0].mFrameNumber);
David Sodman0c69cad2017-08-21 12:12:51 -0700451 mQueueItems.removeAt(0);
452 android_atomic_dec(&mQueuedFrames);
453 }
454 return outDirtyRegion;
455 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
456 // This can occur if something goes wrong when trying to create the
457 // EGLImage for this buffer. If this happens, the buffer has already
458 // been released, so we need to clean up the queue and bug out
459 // early.
460 if (queuedBuffer) {
461 Mutex::Autolock lock(mQueueItemLock);
462 mQueueItems.clear();
463 android_atomic_and(0, &mQueuedFrames);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700464 mTimeStats.clearLayerRecord(getName().c_str());
David Sodman0c69cad2017-08-21 12:12:51 -0700465 }
466
467 // Once we have hit this state, the shadow queue may no longer
468 // correctly reflect the incoming BufferQueue's contents, so even if
469 // updateTexImage starts working, the only safe course of action is
470 // to continue to ignore updates.
471 mUpdateTexImageFailed = true;
472
473 return outDirtyRegion;
474 }
475
476 if (queuedBuffer) {
477 // Autolock scope
Chia-I Wub28c6742017-12-27 10:59:54 -0800478 auto currentFrameNumber = mConsumer->getFrameNumber();
David Sodman0c69cad2017-08-21 12:12:51 -0700479
480 Mutex::Autolock lock(mQueueItemLock);
481
482 // Remove any stale buffers that have been dropped during
483 // updateTexImage
484 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700485 mTimeStats.removeTimeRecord(getName().c_str(), mQueueItems[0].mFrameNumber);
David Sodman0c69cad2017-08-21 12:12:51 -0700486 mQueueItems.removeAt(0);
487 android_atomic_dec(&mQueuedFrames);
488 }
489
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700490 const std::string layerName(getName().c_str());
491 mTimeStats.setAcquireFence(layerName, currentFrameNumber, mQueueItems[0].mFenceTime);
492 mTimeStats.setLatchTime(layerName, currentFrameNumber, latchTime);
493
David Sodman0c69cad2017-08-21 12:12:51 -0700494 mQueueItems.removeAt(0);
495 }
496
497 // Decrement the queued-frames count. Signal another event if we
498 // have more frames pending.
David Sodman9eeae692017-11-02 10:53:32 -0700499 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1) ||
500 mAutoRefresh) {
David Sodman0c69cad2017-08-21 12:12:51 -0700501 mFlinger->signalLayerUpdate();
502 }
503
504 // update the active buffer
David Sodman0cc69182017-11-17 12:12:07 -0800505 getBE().compositionInfo.mBuffer =
Chia-I Wub28c6742017-12-27 10:59:54 -0800506 mConsumer->getCurrentBuffer(&getBE().compositionInfo.mBufferSlot);
David Sodman5b4cffc2017-11-23 13:20:29 -0800507 // replicated in LayerBE until FE/BE is ready to be synchronized
David Sodman0cc69182017-11-17 12:12:07 -0800508 mActiveBuffer = getBE().compositionInfo.mBuffer;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800509 if (getBE().compositionInfo.mBuffer == nullptr) {
David Sodman0c69cad2017-08-21 12:12:51 -0700510 // this can only happen if the very first buffer was rejected.
511 return outDirtyRegion;
512 }
513
514 mBufferLatched = true;
515 mPreviousFrameNumber = mCurrentFrameNumber;
Chia-I Wub28c6742017-12-27 10:59:54 -0800516 mCurrentFrameNumber = mConsumer->getFrameNumber();
David Sodman0c69cad2017-08-21 12:12:51 -0700517
518 {
519 Mutex::Autolock lock(mFrameEventHistoryMutex);
520 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
David Sodman0c69cad2017-08-21 12:12:51 -0700521 }
522
523 mRefreshPending = true;
524 mFrameLatencyNeeded = true;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800525 if (oldBuffer == nullptr) {
David Sodman0c69cad2017-08-21 12:12:51 -0700526 // the first time we receive a buffer, we need to trigger a
527 // geometry invalidation.
528 recomputeVisibleRegions = true;
529 }
530
Peiyong Lin923e7c52018-04-16 14:16:37 -0700531 // Dataspace::V0_SRGB and Dataspace::V0_SRGB_LINEAR are not legacy
532 // data space, however since framework doesn't distinguish them out of
533 // legacy SRGB, we have to treat them as the same for now.
534 // UNKNOWN is treated as legacy SRGB when the connected api is EGL.
535 ui::Dataspace dataSpace = mConsumer->getCurrentDataSpace();
536 switch (dataSpace) {
537 case ui::Dataspace::V0_SRGB:
538 dataSpace = ui::Dataspace::SRGB;
539 break;
540 case ui::Dataspace::V0_SRGB_LINEAR:
541 dataSpace = ui::Dataspace::SRGB_LINEAR;
542 break;
543 case ui::Dataspace::UNKNOWN:
544 if (mConsumer->getCurrentApi() == NATIVE_WINDOW_API_EGL) {
545 dataSpace = ui::Dataspace::SRGB;
546 }
547 break;
548 default:
549 break;
550 }
551 setDataSpace(dataSpace);
David Sodman0c69cad2017-08-21 12:12:51 -0700552
Chia-I Wub28c6742017-12-27 10:59:54 -0800553 Rect crop(mConsumer->getCurrentCrop());
554 const uint32_t transform(mConsumer->getCurrentTransform());
555 const uint32_t scalingMode(mConsumer->getCurrentScalingMode());
David Sodman9eeae692017-11-02 10:53:32 -0700556 if ((crop != mCurrentCrop) ||
557 (transform != mCurrentTransform) ||
David Sodman0c69cad2017-08-21 12:12:51 -0700558 (scalingMode != mCurrentScalingMode)) {
559 mCurrentCrop = crop;
560 mCurrentTransform = transform;
561 mCurrentScalingMode = scalingMode;
562 recomputeVisibleRegions = true;
563 }
564
Peiyong Lin566a3b42018-01-09 18:22:43 -0800565 if (oldBuffer != nullptr) {
David Sodman0cc69182017-11-17 12:12:07 -0800566 uint32_t bufWidth = getBE().compositionInfo.mBuffer->getWidth();
567 uint32_t bufHeight = getBE().compositionInfo.mBuffer->getHeight();
David Sodman5b4cffc2017-11-23 13:20:29 -0800568 if (bufWidth != uint32_t(oldBuffer->width) ||
569 bufHeight != uint32_t(oldBuffer->height)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700570 recomputeVisibleRegions = true;
571 }
572 }
573
David Sodman0cc69182017-11-17 12:12:07 -0800574 mCurrentOpacity = getOpacityForFormat(getBE().compositionInfo.mBuffer->format);
David Sodman0c69cad2017-08-21 12:12:51 -0700575 if (oldOpacity != isOpaque(s)) {
576 recomputeVisibleRegions = true;
577 }
578
579 // Remove any sync points corresponding to the buffer which was just
580 // latched
581 {
582 Mutex::Autolock lock(mLocalSyncPointMutex);
583 auto point = mLocalSyncPoints.begin();
584 while (point != mLocalSyncPoints.end()) {
585 if (!(*point)->frameIsAvailable() || !(*point)->transactionIsApplied()) {
586 // This sync point must have been added since we started
587 // latching. Don't drop it yet.
588 ++point;
589 continue;
590 }
591
592 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
593 point = mLocalSyncPoints.erase(point);
594 } else {
595 ++point;
596 }
597 }
598 }
599
600 // FIXME: postedRegion should be dirty & bounds
601 Region dirtyRegion(Rect(s.active.w, s.active.h));
602
603 // transform the dirty region to window-manager space
604 outDirtyRegion = (getTransform().transform(dirtyRegion));
605
606 return outDirtyRegion;
607}
608
David Sodmaneb085e02017-10-05 18:49:04 -0700609void BufferLayer::setDefaultBufferSize(uint32_t w, uint32_t h) {
Chia-I Wub28c6742017-12-27 10:59:54 -0800610 mConsumer->setDefaultBufferSize(w, h);
David Sodmaneb085e02017-10-05 18:49:04 -0700611}
612
David Sodman0c69cad2017-08-21 12:12:51 -0700613void BufferLayer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
614 // Apply this display's projection's viewport to the visible region
615 // before giving it to the HWC HAL.
616 const Transform& tr = displayDevice->getTransform();
617 const auto& viewport = displayDevice->getViewport();
618 Region visible = tr.transform(visibleRegion.intersect(viewport));
619 auto hwcId = displayDevice->getHwcDisplayId();
David Sodman6f65f3e2017-11-03 14:28:09 -0700620 auto& hwcInfo = getBE().mHwcLayers[hwcId];
David Sodman0c69cad2017-08-21 12:12:51 -0700621 auto& hwcLayer = hwcInfo.layer;
622 auto error = hwcLayer->setVisibleRegion(visible);
623 if (error != HWC2::Error::None) {
624 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
625 to_string(error).c_str(), static_cast<int32_t>(error));
626 visible.dump(LOG_TAG);
627 }
628
629 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
630 if (error != HWC2::Error::None) {
631 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
632 to_string(error).c_str(), static_cast<int32_t>(error));
633 surfaceDamageRegion.dump(LOG_TAG);
634 }
635
636 // Sideband layers
David Sodman0cc69182017-11-17 12:12:07 -0800637 if (getBE().compositionInfo.hwc.sidebandStream.get()) {
David Sodman0c69cad2017-08-21 12:12:51 -0700638 setCompositionType(hwcId, HWC2::Composition::Sideband);
639 ALOGV("[%s] Requesting Sideband composition", mName.string());
David Sodman0cc69182017-11-17 12:12:07 -0800640 error = hwcLayer->setSidebandStream(getBE().compositionInfo.hwc.sidebandStream->handle());
David Sodman0c69cad2017-08-21 12:12:51 -0700641 if (error != HWC2::Error::None) {
642 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", mName.string(),
David Sodman0cc69182017-11-17 12:12:07 -0800643 getBE().compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
David Sodman9eeae692017-11-02 10:53:32 -0700644 static_cast<int32_t>(error));
David Sodman0c69cad2017-08-21 12:12:51 -0700645 }
646 return;
647 }
648
David Sodman0c69cad2017-08-21 12:12:51 -0700649 // Device or Cursor layers
650 if (mPotentialCursor) {
651 ALOGV("[%s] Requesting Cursor composition", mName.string());
652 setCompositionType(hwcId, HWC2::Composition::Cursor);
653 } else {
654 ALOGV("[%s] Requesting Device composition", mName.string());
655 setCompositionType(hwcId, HWC2::Composition::Device);
656 }
657
Peiyong Lin13170c82018-01-22 18:55:51 -0800658 ALOGV("setPerFrameData: dataspace = %d", mDrawingState.dataSpace);
659 error = hwcLayer->setDataspace(mDrawingState.dataSpace);
David Sodman0c69cad2017-08-21 12:12:51 -0700660 if (error != HWC2::Error::None) {
Peiyong Lin13170c82018-01-22 18:55:51 -0800661 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(), mDrawingState.dataSpace,
David Sodman0c69cad2017-08-21 12:12:51 -0700662 to_string(error).c_str(), static_cast<int32_t>(error));
663 }
664
Courtney Goeltzenleuchterf9c98e52018-02-12 07:23:17 -0700665 const HdrMetadata& metadata = mConsumer->getCurrentHdrMetadata();
Peiyong Lin2c327ac2018-04-19 22:06:34 -0700666 error = hwcLayer->setPerFrameMetadata(displayDevice->getSupportedPerFrameMetadata(), metadata);
Courtney Goeltzenleuchter301bb302018-03-12 11:12:42 -0600667 if (error != HWC2::Error::None && error != HWC2::Error::Unsupported) {
Courtney Goeltzenleuchterf9c98e52018-02-12 07:23:17 -0700668 ALOGE("[%s] Failed to set hdrMetadata: %s (%d)", mName.string(),
669 to_string(error).c_str(), static_cast<int32_t>(error));
670 }
671
David Sodman0c69cad2017-08-21 12:12:51 -0700672 uint32_t hwcSlot = 0;
673 sp<GraphicBuffer> hwcBuffer;
David Sodman0cc69182017-11-17 12:12:07 -0800674 hwcInfo.bufferCache.getHwcBuffer(getBE().compositionInfo.mBufferSlot,
675 getBE().compositionInfo.mBuffer, &hwcSlot, &hwcBuffer);
David Sodman0c69cad2017-08-21 12:12:51 -0700676
Chia-I Wub28c6742017-12-27 10:59:54 -0800677 auto acquireFence = mConsumer->getCurrentFence();
David Sodman0c69cad2017-08-21 12:12:51 -0700678 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
679 if (error != HWC2::Error::None) {
David Sodman9eeae692017-11-02 10:53:32 -0700680 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
David Sodman0cc69182017-11-17 12:12:07 -0800681 getBE().compositionInfo.mBuffer->handle, to_string(error).c_str(),
David Sodman9eeae692017-11-02 10:53:32 -0700682 static_cast<int32_t>(error));
David Sodman0c69cad2017-08-21 12:12:51 -0700683 }
684}
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 Sodman0cc69182017-11-17 12:12:07 -0800689 if ((getBE().compositionInfo.hwc.sidebandStream == nullptr) && (getBE().compositionInfo.mBuffer == 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);
Chia-I Wub28c6742017-12-27 10:59:54 -0800704 mConsumer = new BufferLayerConsumer(consumer,
Chia-I Wu9f2db772017-11-30 21:06:50 -0800705 mFlinger->getRenderEngine(), mTextureName, this);
Chia-I Wub28c6742017-12-27 10:59:54 -0800706 mConsumer->setConsumerUsageBits(getEffectiveUsage(0));
707 mConsumer->setContentsChangedListener(this);
708 mConsumer->setName(mName);
David Sodman0c69cad2017-08-21 12:12:51 -0700709
710 if (mFlinger->isLayerTripleBufferingDisabled()) {
711 mProducer->setMaxDequeuedBufferCount(2);
712 }
713
714 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
715 updateTransformHint(hw);
716}
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 Pique4d234852018-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 Sodman9eeae692017-11-02 10:53:32 -0700737 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
738 ms2ns(500));
David Sodman0c69cad2017-08-21 12:12:51 -0700739 if (result != NO_ERROR) {
740 ALOGE("[%s] Timed out waiting on callback", mName.string());
741 }
742 }
743
744 mQueueItems.push_back(item);
745 android_atomic_inc(&mQueuedFrames);
746
747 // Wake up any pending callbacks
748 mLastFrameNumberReceived = item.mFrameNumber;
749 mQueueItemCondition.broadcast();
750 }
751
752 mFlinger->signalLayerUpdate();
753}
754
755void BufferLayer::onFrameReplaced(const BufferItem& item) {
756 { // Autolock scope
757 Mutex::Autolock lock(mQueueItemLock);
758
759 // Ensure that callbacks are handled in order
760 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
David Sodman9eeae692017-11-02 10:53:32 -0700761 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
762 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 if (mQueueItems.empty()) {
769 ALOGE("Can't replace a frame on an empty queue");
770 return;
771 }
772 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
773
774 // Wake up any pending callbacks
775 mLastFrameNumberReceived = item.mFrameNumber;
776 mQueueItemCondition.broadcast();
777 }
778}
779
780void BufferLayer::onSidebandStreamChanged() {
781 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
782 // mSidebandStreamChanged was false
783 mFlinger->signalLayerUpdate();
784 }
785}
786
787bool BufferLayer::needsFiltering(const RenderArea& renderArea) const {
788 return mNeedsFiltering || renderArea.needsFiltering();
789}
790
791// As documented in libhardware header, formats in the range
792// 0x100 - 0x1FF are specific to the HAL implementation, and
793// are known to have no alpha channel
794// TODO: move definition for device-specific range into
795// hardware.h, instead of using hard-coded values here.
796#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
797
798bool BufferLayer::getOpacityForFormat(uint32_t format) {
799 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
800 return true;
801 }
802 switch (format) {
803 case HAL_PIXEL_FORMAT_RGBA_8888:
804 case HAL_PIXEL_FORMAT_BGRA_8888:
805 case HAL_PIXEL_FORMAT_RGBA_FP16:
806 case HAL_PIXEL_FORMAT_RGBA_1010102:
807 return false;
808 }
809 // in all other case, we have no blending (also for unknown formats)
810 return true;
811}
812
David Sodman41fdfc92017-11-06 16:09:56 -0800813void BufferLayer::drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const {
Dan Stoza2713c302018-03-28 17:07:36 -0700814 ATRACE_CALL();
David Sodman0c69cad2017-08-21 12:12:51 -0700815 const State& s(getDrawingState());
816
David Sodman9eeae692017-11-02 10:53:32 -0700817 computeGeometry(renderArea, getBE().mMesh, useIdentityTransform);
David Sodman0c69cad2017-08-21 12:12:51 -0700818
819 /*
820 * NOTE: the way we compute the texture coordinates here produces
821 * different results than when we take the HWC path -- in the later case
822 * the "source crop" is rounded to texel boundaries.
823 * This can produce significantly different results when the texture
824 * is scaled by a large amount.
825 *
826 * The GL code below is more logical (imho), and the difference with
827 * HWC is due to a limitation of the HWC API to integers -- a question
828 * is suspend is whether we should ignore this problem or revert to
829 * GL composition when a buffer scaling is applied (maybe with some
830 * minimal value)? Or, we could make GL behave like HWC -- but this feel
831 * like more of a hack.
832 */
Dan Stoza80d61162017-12-20 15:57:52 -0800833 const Rect bounds{computeBounds()}; // Rounds from FloatRect
David Sodman0c69cad2017-08-21 12:12:51 -0700834
835 Transform t = getTransform();
Dan Stoza80d61162017-12-20 15:57:52 -0800836 Rect win = bounds;
David Sodman0c69cad2017-08-21 12:12:51 -0700837 if (!s.finalCrop.isEmpty()) {
838 win = t.transform(win);
839 if (!win.intersect(s.finalCrop, &win)) {
840 win.clear();
841 }
842 win = t.inverse().transform(win);
Dan Stoza80d61162017-12-20 15:57:52 -0800843 if (!win.intersect(bounds, &win)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700844 win.clear();
845 }
846 }
847
848 float left = float(win.left) / float(s.active.w);
849 float top = float(win.top) / float(s.active.h);
850 float right = float(win.right) / float(s.active.w);
851 float bottom = float(win.bottom) / float(s.active.h);
852
853 // TODO: we probably want to generate the texture coords with the mesh
854 // here we assume that we only have 4 vertices
David Sodman9eeae692017-11-02 10:53:32 -0700855 Mesh::VertexArray<vec2> texCoords(getBE().mMesh.getTexCoordArray<vec2>());
David Sodman0c69cad2017-08-21 12:12:51 -0700856 texCoords[0] = vec2(left, 1.0f - top);
857 texCoords[1] = vec2(left, 1.0f - bottom);
858 texCoords[2] = vec2(right, 1.0f - bottom);
859 texCoords[3] = vec2(right, 1.0f - top);
860
Lloyd Pique144e1162017-12-20 16:44:52 -0800861 auto& engine(mFlinger->getRenderEngine());
David Sodman0c69cad2017-08-21 12:12:51 -0700862 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), false /* disableTexture */,
863 getColor());
David Sodman0c69cad2017-08-21 12:12:51 -0700864 engine.setSourceDataSpace(mCurrentState.dataSpace);
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800865
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700866 if (mCurrentState.dataSpace == ui::Dataspace::BT2020_ITU_PQ &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800867 mConsumer->getCurrentApi() == NATIVE_WINDOW_API_MEDIA &&
868 getBE().compositionInfo.mBuffer->getPixelFormat() == HAL_PIXEL_FORMAT_RGBA_1010102) {
869 engine.setSourceY410BT2020(true);
870 }
871
David Sodman9eeae692017-11-02 10:53:32 -0700872 engine.drawMesh(getBE().mMesh);
David Sodman0c69cad2017-08-21 12:12:51 -0700873 engine.disableBlending();
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800874
875 engine.setSourceY410BT2020(false);
David Sodman0c69cad2017-08-21 12:12:51 -0700876}
877
878uint32_t BufferLayer::getProducerStickyTransform() const {
879 int producerStickyTransform = 0;
880 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
881 if (ret != OK) {
882 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
883 strerror(-ret), ret);
884 return 0;
885 }
886 return static_cast<uint32_t>(producerStickyTransform);
887}
888
889bool BufferLayer::latchUnsignaledBuffers() {
890 static bool propertyLoaded = false;
891 static bool latch = false;
892 static std::mutex mutex;
893 std::lock_guard<std::mutex> lock(mutex);
894 if (!propertyLoaded) {
895 char value[PROPERTY_VALUE_MAX] = {};
896 property_get("debug.sf.latch_unsignaled", value, "0");
897 latch = atoi(value);
898 propertyLoaded = true;
899 }
900 return latch;
901}
902
903uint64_t BufferLayer::getHeadFrameNumber() const {
904 Mutex::Autolock lock(mQueueItemLock);
905 if (!mQueueItems.empty()) {
906 return mQueueItems[0].mFrameNumber;
907 } else {
908 return mCurrentFrameNumber;
909 }
910}
911
912bool BufferLayer::headFenceHasSignaled() const {
David Sodman0c69cad2017-08-21 12:12:51 -0700913 if (latchUnsignaledBuffers()) {
914 return true;
915 }
916
917 Mutex::Autolock lock(mQueueItemLock);
918 if (mQueueItems.empty()) {
919 return true;
920 }
921 if (mQueueItems[0].mIsDroppable) {
922 // Even though this buffer's fence may not have signaled yet, it could
923 // be replaced by another buffer before it has a chance to, which means
924 // that it's possible to get into a situation where a buffer is never
925 // able to be latched. To avoid this, grab this buffer anyway.
926 return true;
927 }
David Sodman9eeae692017-11-02 10:53:32 -0700928 return mQueueItems[0].mFenceTime->getSignalTime() !=
929 Fence::SIGNAL_TIME_PENDING;
David Sodman0c69cad2017-08-21 12:12:51 -0700930}
931
932uint32_t BufferLayer::getEffectiveScalingMode() const {
933 if (mOverrideScalingMode >= 0) {
934 return mOverrideScalingMode;
935 }
936 return mCurrentScalingMode;
937}
938
939// ----------------------------------------------------------------------------
940// transaction
941// ----------------------------------------------------------------------------
942
943void BufferLayer::notifyAvailableFrames() {
944 auto headFrameNumber = getHeadFrameNumber();
945 bool headFenceSignaled = headFenceHasSignaled();
946 Mutex::Autolock lock(mLocalSyncPointMutex);
947 for (auto& point : mLocalSyncPoints) {
948 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
949 point->setFrameAvailable();
950 }
951 }
952}
953
954sp<IGraphicBufferProducer> BufferLayer::getProducer() const {
955 return mProducer;
956}
957
958// ---------------------------------------------------------------------------
959// h/w composer set-up
960// ---------------------------------------------------------------------------
961
962bool BufferLayer::allTransactionsSignaled() {
963 auto headFrameNumber = getHeadFrameNumber();
964 bool matchingFramesFound = false;
965 bool allTransactionsApplied = true;
966 Mutex::Autolock lock(mLocalSyncPointMutex);
967
968 for (auto& point : mLocalSyncPoints) {
969 if (point->getFrameNumber() > headFrameNumber) {
970 break;
971 }
972 matchingFramesFound = true;
973
974 if (!point->frameIsAvailable()) {
975 // We haven't notified the remote layer that the frame for
976 // this point is available yet. Notify it now, and then
977 // abort this attempt to latch.
978 point->setFrameAvailable();
979 allTransactionsApplied = false;
980 break;
981 }
982
983 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
984 }
985 return !matchingFramesFound || allTransactionsApplied;
986}
987
988} // namespace android
989
990#if defined(__gl_h_)
991#error "don't include gl/gl.h in this file"
992#endif
993
994#if defined(__gl2_h_)
995#error "don't include gl2/gl2.h in this file"
996#endif