blob: 0b0654cf8610462354e9431298247d135bfaed0c [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));
329 } else {
330 // 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();
616 auto& hwcInfo = getBE().mHwcLayers[displayId];
Chia-I Wu30505fb2018-03-26 16:20:31 -0700617 auto& hwcLayer = hwcInfo.layer;
David Sodmanf6a38932018-05-25 15:27:50 -0700618 auto error = hwcLayer->setVisibleRegion(visible);
Chia-I Wu30505fb2018-03-26 16:20:31 -0700619 if (error != HWC2::Error::None) {
620 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
621 to_string(error).c_str(), static_cast<int32_t>(error));
622 visible.dump(LOG_TAG);
623 }
David Sodman0c69cad2017-08-21 12:12:51 -0700624
David Sodmanf6a38932018-05-25 15:27:50 -0700625 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
Chia-I Wu30505fb2018-03-26 16:20:31 -0700626 if (error != HWC2::Error::None) {
627 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
628 to_string(error).c_str(), static_cast<int32_t>(error));
629 surfaceDamageRegion.dump(LOG_TAG);
630 }
David Sodman0c69cad2017-08-21 12:12:51 -0700631
632 // Sideband layers
David Sodman0cc69182017-11-17 12:12:07 -0800633 if (getBE().compositionInfo.hwc.sidebandStream.get()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -0700634 setCompositionType(displayId, HWC2::Composition::Sideband);
Chia-I Wu30505fb2018-03-26 16:20:31 -0700635 ALOGV("[%s] Requesting Sideband composition", mName.string());
David Sodmanf6a38932018-05-25 15:27:50 -0700636 error = hwcLayer->setSidebandStream(getBE().compositionInfo.hwc.sidebandStream->handle());
Chia-I Wu30505fb2018-03-26 16:20:31 -0700637 if (error != HWC2::Error::None) {
638 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", mName.string(),
639 getBE().compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
640 static_cast<int32_t>(error));
641 }
David Sodman0c69cad2017-08-21 12:12:51 -0700642 return;
643 }
644
David Sodman0c69cad2017-08-21 12:12:51 -0700645 // Device or Cursor layers
646 if (mPotentialCursor) {
647 ALOGV("[%s] Requesting Cursor composition", mName.string());
Dominik Laskowski7e045462018-05-30 13:02:02 -0700648 setCompositionType(displayId, HWC2::Composition::Cursor);
David Sodman0c69cad2017-08-21 12:12:51 -0700649 } else {
650 ALOGV("[%s] Requesting Device composition", mName.string());
Dominik Laskowski7e045462018-05-30 13:02:02 -0700651 setCompositionType(displayId, HWC2::Composition::Device);
David Sodman0c69cad2017-08-21 12:12:51 -0700652 }
653
Chia-I Wu01591c92018-05-22 12:03:00 -0700654 ALOGV("setPerFrameData: dataspace = %d", mCurrentDataSpace);
David Sodmanf6a38932018-05-25 15:27:50 -0700655 error = hwcLayer->setDataspace(mCurrentDataSpace);
Chia-I Wu30505fb2018-03-26 16:20:31 -0700656 if (error != HWC2::Error::None) {
Chia-I Wu01591c92018-05-22 12:03:00 -0700657 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(), mCurrentDataSpace,
Chia-I Wu30505fb2018-03-26 16:20:31 -0700658 to_string(error).c_str(), static_cast<int32_t>(error));
659 }
660
661 const HdrMetadata& metadata = mConsumer->getCurrentHdrMetadata();
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700662 error = hwcLayer->setPerFrameMetadata(display->getSupportedPerFrameMetadata(), metadata);
Chia-I Wu30505fb2018-03-26 16:20:31 -0700663 if (error != HWC2::Error::None && error != HWC2::Error::Unsupported) {
664 ALOGE("[%s] Failed to set hdrMetadata: %s (%d)", mName.string(),
665 to_string(error).c_str(), static_cast<int32_t>(error));
666 }
667
668 uint32_t hwcSlot = 0;
669 sp<GraphicBuffer> hwcBuffer;
Dominik Laskowski7e045462018-05-30 13:02:02 -0700670 getBE().mHwcLayers[displayId].bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
671 &hwcSlot, &hwcBuffer);
David Sodman0c69cad2017-08-21 12:12:51 -0700672
Chia-I Wub28c6742017-12-27 10:59:54 -0800673 auto acquireFence = mConsumer->getCurrentFence();
David Sodmanf6a38932018-05-25 15:27:50 -0700674 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
Chia-I Wu30505fb2018-03-26 16:20:31 -0700675 if (error != HWC2::Error::None) {
676 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
677 getBE().compositionInfo.mBuffer->handle, to_string(error).c_str(),
678 static_cast<int32_t>(error));
679 }
David Sodman0c69cad2017-08-21 12:12:51 -0700680}
681
David Sodman41fdfc92017-11-06 16:09:56 -0800682bool BufferLayer::isOpaque(const Layer::State& s) const {
David Sodman0c69cad2017-08-21 12:12:51 -0700683 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
684 // layer's opaque flag.
David Sodman0cf8f8d2017-12-20 18:19:45 -0800685 if ((getBE().compositionInfo.hwc.sidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700686 return false;
687 }
688
689 // if the layer has the opaque flag, then we're always opaque,
690 // otherwise we use the current buffer's format.
691 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
692}
693
694void BufferLayer::onFirstRef() {
695 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
696 sp<IGraphicBufferProducer> producer;
697 sp<IGraphicBufferConsumer> consumer;
698 BufferQueue::createBufferQueue(&producer, &consumer, true);
699 mProducer = new MonitoredProducer(producer, mFlinger, this);
David Sodman0cf8f8d2017-12-20 18:19:45 -0800700 mConsumer = new BufferLayerConsumer(consumer, mFlinger->getRenderEngine(), mTextureName, this);
Chia-I Wub28c6742017-12-27 10:59:54 -0800701 mConsumer->setConsumerUsageBits(getEffectiveUsage(0));
702 mConsumer->setContentsChangedListener(this);
703 mConsumer->setName(mName);
David Sodman0c69cad2017-08-21 12:12:51 -0700704
705 if (mFlinger->isLayerTripleBufferingDisabled()) {
706 mProducer->setMaxDequeuedBufferCount(2);
707 }
708
709 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
710 updateTransformHint(hw);
711}
712
713// ---------------------------------------------------------------------------
714// Interface implementation for SurfaceFlingerConsumer::ContentsChangedListener
715// ---------------------------------------------------------------------------
716
717void BufferLayer::onFrameAvailable(const BufferItem& item) {
718 // Add this buffer from our internal queue tracker
719 { // Autolock scope
720 Mutex::Autolock lock(mQueueItemLock);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800721 mFlinger->mInterceptor->saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
722 item.mGraphicBuffer->getHeight(),
723 item.mFrameNumber);
David Sodman0c69cad2017-08-21 12:12:51 -0700724 // Reset the frame number tracker when we receive the first buffer after
725 // a frame number reset
726 if (item.mFrameNumber == 1) {
727 mLastFrameNumberReceived = 0;
728 }
729
730 // Ensure that callbacks are handled in order
731 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
David Sodman0cf8f8d2017-12-20 18:19:45 -0800732 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock, ms2ns(500));
David Sodman0c69cad2017-08-21 12:12:51 -0700733 if (result != NO_ERROR) {
734 ALOGE("[%s] Timed out waiting on callback", mName.string());
735 }
736 }
737
738 mQueueItems.push_back(item);
739 android_atomic_inc(&mQueuedFrames);
740
741 // Wake up any pending callbacks
742 mLastFrameNumberReceived = item.mFrameNumber;
743 mQueueItemCondition.broadcast();
744 }
745
746 mFlinger->signalLayerUpdate();
747}
748
749void BufferLayer::onFrameReplaced(const BufferItem& item) {
750 { // Autolock scope
751 Mutex::Autolock lock(mQueueItemLock);
752
753 // Ensure that callbacks are handled in order
754 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
David Sodman0cf8f8d2017-12-20 18:19:45 -0800755 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock, ms2ns(500));
David Sodman0c69cad2017-08-21 12:12:51 -0700756 if (result != NO_ERROR) {
757 ALOGE("[%s] Timed out waiting on callback", mName.string());
758 }
759 }
760
761 if (mQueueItems.empty()) {
762 ALOGE("Can't replace a frame on an empty queue");
763 return;
764 }
765 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
766
767 // Wake up any pending callbacks
768 mLastFrameNumberReceived = item.mFrameNumber;
769 mQueueItemCondition.broadcast();
770 }
771}
772
773void BufferLayer::onSidebandStreamChanged() {
774 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
775 // mSidebandStreamChanged was false
776 mFlinger->signalLayerUpdate();
777 }
778}
779
780bool BufferLayer::needsFiltering(const RenderArea& renderArea) const {
781 return mNeedsFiltering || renderArea.needsFiltering();
782}
783
784// As documented in libhardware header, formats in the range
785// 0x100 - 0x1FF are specific to the HAL implementation, and
786// are known to have no alpha channel
787// TODO: move definition for device-specific range into
788// hardware.h, instead of using hard-coded values here.
789#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
790
791bool BufferLayer::getOpacityForFormat(uint32_t format) {
792 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
793 return true;
794 }
795 switch (format) {
796 case HAL_PIXEL_FORMAT_RGBA_8888:
797 case HAL_PIXEL_FORMAT_BGRA_8888:
798 case HAL_PIXEL_FORMAT_RGBA_FP16:
799 case HAL_PIXEL_FORMAT_RGBA_1010102:
800 return false;
801 }
802 // in all other case, we have no blending (also for unknown formats)
803 return true;
804}
805
David Sodman41fdfc92017-11-06 16:09:56 -0800806void BufferLayer::drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const {
Dan Stoza84d619e2018-03-28 17:07:36 -0700807 ATRACE_CALL();
David Sodman0c69cad2017-08-21 12:12:51 -0700808 const State& s(getDrawingState());
809
David Sodman9eeae692017-11-02 10:53:32 -0700810 computeGeometry(renderArea, getBE().mMesh, useIdentityTransform);
David Sodman0c69cad2017-08-21 12:12:51 -0700811
812 /*
813 * NOTE: the way we compute the texture coordinates here produces
814 * different results than when we take the HWC path -- in the later case
815 * the "source crop" is rounded to texel boundaries.
816 * This can produce significantly different results when the texture
817 * is scaled by a large amount.
818 *
819 * The GL code below is more logical (imho), and the difference with
820 * HWC is due to a limitation of the HWC API to integers -- a question
821 * is suspend is whether we should ignore this problem or revert to
822 * GL composition when a buffer scaling is applied (maybe with some
823 * minimal value)? Or, we could make GL behave like HWC -- but this feel
824 * like more of a hack.
825 */
Dan Stoza80d61162017-12-20 15:57:52 -0800826 const Rect bounds{computeBounds()}; // Rounds from FloatRect
David Sodman0c69cad2017-08-21 12:12:51 -0700827
828 Transform t = getTransform();
Dan Stoza80d61162017-12-20 15:57:52 -0800829 Rect win = bounds;
David Sodman0c69cad2017-08-21 12:12:51 -0700830 if (!s.finalCrop.isEmpty()) {
831 win = t.transform(win);
832 if (!win.intersect(s.finalCrop, &win)) {
833 win.clear();
834 }
835 win = t.inverse().transform(win);
Dan Stoza80d61162017-12-20 15:57:52 -0800836 if (!win.intersect(bounds, &win)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700837 win.clear();
838 }
839 }
840
841 float left = float(win.left) / float(s.active.w);
842 float top = float(win.top) / float(s.active.h);
843 float right = float(win.right) / float(s.active.w);
844 float bottom = float(win.bottom) / float(s.active.h);
845
846 // TODO: we probably want to generate the texture coords with the mesh
847 // here we assume that we only have 4 vertices
David Sodman9eeae692017-11-02 10:53:32 -0700848 Mesh::VertexArray<vec2> texCoords(getBE().mMesh.getTexCoordArray<vec2>());
David Sodman0c69cad2017-08-21 12:12:51 -0700849 texCoords[0] = vec2(left, 1.0f - top);
850 texCoords[1] = vec2(left, 1.0f - bottom);
851 texCoords[2] = vec2(right, 1.0f - bottom);
852 texCoords[3] = vec2(right, 1.0f - top);
853
bohu21566132018-03-27 14:36:34 -0700854 auto& engine(mFlinger->getRenderEngine());
855 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), false /* disableTexture */,
856 getColor());
Chia-I Wu01591c92018-05-22 12:03:00 -0700857 engine.setSourceDataSpace(mCurrentDataSpace);
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800858
Chia-I Wu01591c92018-05-22 12:03:00 -0700859 if (mCurrentDataSpace == ui::Dataspace::BT2020_ITU_PQ &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800860 mConsumer->getCurrentApi() == NATIVE_WINDOW_API_MEDIA &&
861 getBE().compositionInfo.mBuffer->getPixelFormat() == HAL_PIXEL_FORMAT_RGBA_1010102) {
bohu21566132018-03-27 14:36:34 -0700862 engine.setSourceY410BT2020(true);
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800863 }
bohu21566132018-03-27 14:36:34 -0700864
865 engine.drawMesh(getBE().mMesh);
866 engine.disableBlending();
867
868 engine.setSourceY410BT2020(false);
David Sodman0c69cad2017-08-21 12:12:51 -0700869}
870
871uint32_t BufferLayer::getProducerStickyTransform() const {
872 int producerStickyTransform = 0;
873 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
874 if (ret != OK) {
875 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
876 strerror(-ret), ret);
877 return 0;
878 }
879 return static_cast<uint32_t>(producerStickyTransform);
880}
881
882bool BufferLayer::latchUnsignaledBuffers() {
883 static bool propertyLoaded = false;
884 static bool latch = false;
885 static std::mutex mutex;
886 std::lock_guard<std::mutex> lock(mutex);
887 if (!propertyLoaded) {
888 char value[PROPERTY_VALUE_MAX] = {};
889 property_get("debug.sf.latch_unsignaled", value, "0");
890 latch = atoi(value);
891 propertyLoaded = true;
892 }
893 return latch;
894}
895
896uint64_t BufferLayer::getHeadFrameNumber() const {
897 Mutex::Autolock lock(mQueueItemLock);
898 if (!mQueueItems.empty()) {
899 return mQueueItems[0].mFrameNumber;
900 } else {
901 return mCurrentFrameNumber;
902 }
903}
904
905bool BufferLayer::headFenceHasSignaled() const {
David Sodman0c69cad2017-08-21 12:12:51 -0700906 if (latchUnsignaledBuffers()) {
907 return true;
908 }
909
910 Mutex::Autolock lock(mQueueItemLock);
911 if (mQueueItems.empty()) {
912 return true;
913 }
914 if (mQueueItems[0].mIsDroppable) {
915 // Even though this buffer's fence may not have signaled yet, it could
916 // be replaced by another buffer before it has a chance to, which means
917 // that it's possible to get into a situation where a buffer is never
918 // able to be latched. To avoid this, grab this buffer anyway.
919 return true;
920 }
David Sodman0cf8f8d2017-12-20 18:19:45 -0800921 return mQueueItems[0].mFenceTime->getSignalTime() != Fence::SIGNAL_TIME_PENDING;
David Sodman0c69cad2017-08-21 12:12:51 -0700922}
923
924uint32_t BufferLayer::getEffectiveScalingMode() const {
925 if (mOverrideScalingMode >= 0) {
926 return mOverrideScalingMode;
927 }
928 return mCurrentScalingMode;
929}
930
931// ----------------------------------------------------------------------------
932// transaction
933// ----------------------------------------------------------------------------
934
935void BufferLayer::notifyAvailableFrames() {
936 auto headFrameNumber = getHeadFrameNumber();
937 bool headFenceSignaled = headFenceHasSignaled();
938 Mutex::Autolock lock(mLocalSyncPointMutex);
939 for (auto& point : mLocalSyncPoints) {
940 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
941 point->setFrameAvailable();
942 }
943 }
944}
945
946sp<IGraphicBufferProducer> BufferLayer::getProducer() const {
947 return mProducer;
948}
949
950// ---------------------------------------------------------------------------
951// h/w composer set-up
952// ---------------------------------------------------------------------------
953
954bool BufferLayer::allTransactionsSignaled() {
955 auto headFrameNumber = getHeadFrameNumber();
956 bool matchingFramesFound = false;
957 bool allTransactionsApplied = true;
958 Mutex::Autolock lock(mLocalSyncPointMutex);
959
960 for (auto& point : mLocalSyncPoints) {
961 if (point->getFrameNumber() > headFrameNumber) {
962 break;
963 }
964 matchingFramesFound = true;
965
966 if (!point->frameIsAvailable()) {
967 // We haven't notified the remote layer that the frame for
968 // this point is available yet. Notify it now, and then
969 // abort this attempt to latch.
970 point->setFrameAvailable();
971 allTransactionsApplied = false;
972 break;
973 }
974
975 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
976 }
977 return !matchingFramesFound || allTransactionsApplied;
978}
979
980} // namespace android
981
982#if defined(__gl_h_)
983#error "don't include gl/gl.h in this file"
984#endif
985
986#if defined(__gl2_h_)
987#error "don't include gl2/gl2.h in this file"
988#endif