blob: a33ef2cd94081cc6f6d0e0545ef6a0edf7401c18 [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),
David Sodmaneb085e02017-10-05 18:49:04 -070056 mSurfaceFlingerConsumer(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() {
78 sp<Client> c(mClientRef.promote());
79 if (c != 0) {
80 c->detachLayer(this);
81 }
82
83 for (auto& point : mRemoteSyncPoints) {
84 point->setTransactionApplied();
85 }
86 for (auto& point : mLocalSyncPoints) {
87 point->setFrameAvailable();
88 }
89 mFlinger->deleteTextureAsync(mTextureName);
90
David Sodman0c69cad2017-08-21 12:12:51 -070091 if (!mHwcLayers.empty()) {
92 ALOGE("Found stale hardware composer layers when destroying "
93 "surface flinger layer %s",
94 mName.string());
95 destroyAllHwcLayers();
96 }
David Sodman0c69cad2017-08-21 12:12:51 -070097}
98
David Sodmaneb085e02017-10-05 18:49:04 -070099void BufferLayer::useSurfaceDamage() {
100 if (mFlinger->mForceFullDamage) {
101 surfaceDamageRegion = Region::INVALID_REGION;
102 } else {
103 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
104 }
105}
106
107void BufferLayer::useEmptyDamage() {
108 surfaceDamageRegion.clear();
109}
110
David Sodman41fdfc92017-11-06 16:09:56 -0800111bool BufferLayer::isProtected() const {
David Sodman0c69cad2017-08-21 12:12:51 -0700112 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
David Sodman41fdfc92017-11-06 16:09:56 -0800113 return (activeBuffer != 0) && (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
David Sodman0c69cad2017-08-21 12:12:51 -0700114}
115
116bool BufferLayer::isVisible() const {
117 return !(isHiddenByPolicy()) && getAlpha() > 0.0f &&
118 (mActiveBuffer != NULL || mSidebandStream != NULL);
119}
120
121bool BufferLayer::isFixedSize() const {
122 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
123}
124
125status_t BufferLayer::setBuffers(uint32_t w, uint32_t h, PixelFormat format, uint32_t flags) {
126 uint32_t const maxSurfaceDims =
127 min(mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
128
129 // never allow a surface larger than what our underlying GL implementation
130 // can handle.
131 if ((uint32_t(w) > maxSurfaceDims) || (uint32_t(h) > maxSurfaceDims)) {
132 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
133 return BAD_VALUE;
134 }
135
136 mFormat = format;
137
138 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
139 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
140 mCurrentOpacity = getOpacityForFormat(format);
141
142 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
143 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
144 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
145
146 return NO_ERROR;
147}
148
149static constexpr mat4 inverseOrientation(uint32_t transform) {
David Sodman41fdfc92017-11-06 16:09:56 -0800150 const mat4 flipH(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
151 const mat4 flipV(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
152 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 -0700153 mat4 tr;
154
155 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
156 tr = tr * rot90;
157 }
158 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
159 tr = tr * flipH;
160 }
161 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
162 tr = tr * flipV;
163 }
164 return inverse(tr);
165}
166
167/*
168 * onDraw will draw the current layer onto the presentable buffer
169 */
170void BufferLayer::onDraw(const RenderArea& renderArea, const Region& clip,
171 bool useIdentityTransform) const {
172 ATRACE_CALL();
173
174 if (CC_UNLIKELY(mActiveBuffer == 0)) {
175 // the texture has not been created yet, this Layer has
176 // in fact never been drawn into. This happens frequently with
177 // SurfaceView because the WindowManager can't know when the client
178 // has drawn the first time.
179
180 // If there is nothing under us, we paint the screen in black, otherwise
181 // we just skip this update.
182
183 // figure out if there is something below us
184 Region under;
185 bool finished = false;
186 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
187 if (finished || layer == static_cast<BufferLayer const*>(this)) {
188 finished = true;
189 return;
190 }
191 under.orSelf(renderArea.getTransform().transform(layer->visibleRegion));
192 });
193 // if not everything below us is covered, we plug the holes!
194 Region holes(clip.subtract(under));
195 if (!holes.isEmpty()) {
196 clearWithOpenGL(renderArea, 0, 0, 0, 1);
197 }
198 return;
199 }
200
201 // Bind the current buffer to the GL texture, and wait for it to be
202 // ready for us to draw into.
203 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
204 if (err != NO_ERROR) {
205 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
206 // Go ahead and draw the buffer anyway; no matter what we do the screen
207 // is probably going to have something visibly wrong.
208 }
209
210 bool blackOutLayer = isProtected() || (isSecure() && !renderArea.isSecure());
211
212 RenderEngine& engine(mFlinger->getRenderEngine());
213
214 if (!blackOutLayer) {
215 // TODO: we could be more subtle with isFixedSize()
216 const bool useFiltering = getFiltering() || needsFiltering(renderArea) || isFixedSize();
217
218 // Query the texture matrix given our current filtering mode.
219 float textureMatrix[16];
220 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
221 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
222
223 if (getTransformToDisplayInverse()) {
224 /*
225 * the code below applies the primary display's inverse transform to
226 * the texture transform
227 */
228 uint32_t transform = DisplayDevice::getPrimaryDisplayOrientationTransform();
229 mat4 tr = inverseOrientation(transform);
230
231 /**
232 * TODO(b/36727915): This is basically a hack.
233 *
234 * Ensure that regardless of the parent transformation,
235 * this buffer is always transformed from native display
236 * orientation to display orientation. For example, in the case
237 * of a camera where the buffer remains in native orientation,
238 * we want the pixels to always be upright.
239 */
240 sp<Layer> p = mDrawingParent.promote();
241 if (p != nullptr) {
242 const auto parentTransform = p->getTransform();
243 tr = tr * inverseOrientation(parentTransform.getOrientation());
244 }
245
246 // and finally apply it to the original texture matrix
247 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
248 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
249 }
250
251 // Set things up for texturing.
David Sodman9eeae692017-11-02 10:53:32 -0700252 mTexture.setDimensions(mActiveBuffer->getWidth(),
253 mActiveBuffer->getHeight());
David Sodman0c69cad2017-08-21 12:12:51 -0700254 mTexture.setFiltering(useFiltering);
255 mTexture.setMatrix(textureMatrix);
256
257 engine.setupLayerTexturing(mTexture);
258 } else {
259 engine.setupLayerBlackedOut();
260 }
261 drawWithOpenGL(renderArea, useIdentityTransform);
262 engine.disableTexturing();
263}
264
David Sodmaneb085e02017-10-05 18:49:04 -0700265void BufferLayer::onLayerDisplayed(const sp<Fence>& releaseFence) {
David Sodmaneb085e02017-10-05 18:49:04 -0700266 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
267}
David Sodmaneb085e02017-10-05 18:49:04 -0700268
269void BufferLayer::abandon() {
270 mSurfaceFlingerConsumer->abandon();
271}
272
273bool BufferLayer::shouldPresentNow(const DispSync& dispSync) const {
274 if (mSidebandStreamChanged || mAutoRefresh) {
275 return true;
276 }
277
278 Mutex::Autolock lock(mQueueItemLock);
279 if (mQueueItems.empty()) {
280 return false;
281 }
282 auto timestamp = mQueueItems[0].mTimestamp;
283 nsecs_t expectedPresent = mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
284
285 // Ignore timestamps more than a second in the future
286 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
287 ALOGW_IF(!isPlausible,
288 "[%s] Timestamp %" PRId64 " seems implausible "
289 "relative to expectedPresent %" PRId64,
290 mName.string(), timestamp, expectedPresent);
291
292 bool isDue = timestamp < expectedPresent;
293 return isDue || !isPlausible;
294}
295
296void BufferLayer::setTransformHint(uint32_t orientation) const {
297 mSurfaceFlingerConsumer->setTransformHint(orientation);
298}
299
David Sodman0c69cad2017-08-21 12:12:51 -0700300bool BufferLayer::onPreComposition(nsecs_t refreshStartTime) {
301 if (mBufferLatched) {
302 Mutex::Autolock lock(mFrameEventHistoryMutex);
David Sodman9eeae692017-11-02 10:53:32 -0700303 mFrameEventHistory.addPreComposition(mCurrentFrameNumber,
304 refreshStartTime);
David Sodman0c69cad2017-08-21 12:12:51 -0700305 }
306 mRefreshPending = false;
David Sodman9eeae692017-11-02 10:53:32 -0700307 return mQueuedFrames > 0 || mSidebandStreamChanged ||
308 mAutoRefresh;
David Sodman0c69cad2017-08-21 12:12:51 -0700309}
David Sodmaneb085e02017-10-05 18:49:04 -0700310bool BufferLayer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
311 const std::shared_ptr<FenceTime>& presentFence,
312 const CompositorTiming& compositorTiming) {
313 // mFrameLatencyNeeded is true when a new frame was latched for the
314 // composition.
315 if (!mFrameLatencyNeeded) return false;
316
317 // Update mFrameEventHistory.
318 {
319 Mutex::Autolock lock(mFrameEventHistoryMutex);
David Sodman9eeae692017-11-02 10:53:32 -0700320 mFrameEventHistory.addPostComposition(mCurrentFrameNumber, glDoneFence,
321 presentFence, compositorTiming);
David Sodmaneb085e02017-10-05 18:49:04 -0700322 }
323
324 // Update mFrameTracker.
325 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
326 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
327
328 std::shared_ptr<FenceTime> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFenceTime();
329 if (frameReadyFence->isValid()) {
330 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
331 } else {
332 // There was no fence for this frame, so assume that it was ready
333 // to be presented at the desired present time.
334 mFrameTracker.setFrameReadyTime(desiredPresentTime);
335 }
336
337 if (presentFence->isValid()) {
338 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
339 } else {
340 // The HWC doesn't support present fences, so use the refresh
341 // timestamp instead.
342 mFrameTracker.setActualPresentTime(
343 mFlinger->getHwComposer().getRefreshTimestamp(HWC_DISPLAY_PRIMARY));
344 }
345
346 mFrameTracker.advanceFrame();
347 mFrameLatencyNeeded = false;
348 return true;
349}
350
351std::vector<OccupancyTracker::Segment> BufferLayer::getOccupancyHistory(bool forceFlush) {
352 std::vector<OccupancyTracker::Segment> history;
353 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush, &history);
354 if (result != NO_ERROR) {
355 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(), result);
356 return {};
357 }
358 return history;
359}
360
361bool BufferLayer::getTransformToDisplayInverse() const {
362 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
363}
David Sodman0c69cad2017-08-21 12:12:51 -0700364
David Sodman0c69cad2017-08-21 12:12:51 -0700365void BufferLayer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
366 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
367 return;
368 }
369
370 auto releaseFenceTime =
371 std::make_shared<FenceTime>(mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
372 mReleaseTimeline.updateSignalTimes();
373 mReleaseTimeline.push(releaseFenceTime);
374
375 Mutex::Autolock lock(mFrameEventHistoryMutex);
376 if (mPreviousFrameNumber != 0) {
377 mFrameEventHistory.addRelease(mPreviousFrameNumber, dequeueReadyTime,
378 std::move(releaseFenceTime));
379 }
380}
David Sodman0c69cad2017-08-21 12:12:51 -0700381
382Region BufferLayer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
383 ATRACE_CALL();
384
385 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
386 // mSidebandStreamChanged was true
387 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
388 if (mSidebandStream != NULL) {
389 setTransactionFlags(eTransactionNeeded);
390 mFlinger->setTransactionFlags(eTraversalNeeded);
391 }
392 recomputeVisibleRegions = true;
393
394 const State& s(getDrawingState());
395 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
396 }
397
398 Region outDirtyRegion;
399 if (mQueuedFrames <= 0 && !mAutoRefresh) {
400 return outDirtyRegion;
401 }
402
403 // if we've already called updateTexImage() without going through
404 // a composition step, we have to skip this layer at this point
405 // because we cannot call updateTeximage() without a corresponding
406 // compositionComplete() call.
407 // we'll trigger an update in onPreComposition().
408 if (mRefreshPending) {
409 return outDirtyRegion;
410 }
411
412 // If the head buffer's acquire fence hasn't signaled yet, return and
413 // try again later
414 if (!headFenceHasSignaled()) {
415 mFlinger->signalLayerUpdate();
416 return outDirtyRegion;
417 }
418
419 // Capture the old state of the layer for comparisons later
420 const State& s(getDrawingState());
421 const bool oldOpacity = isOpaque(s);
422 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
423
424 if (!allTransactionsSignaled()) {
425 mFlinger->signalLayerUpdate();
426 return outDirtyRegion;
427 }
428
429 // This boolean is used to make sure that SurfaceFlinger's shadow copy
430 // of the buffer queue isn't modified when the buffer queue is returning
431 // BufferItem's that weren't actually queued. This can happen in shared
432 // buffer mode.
433 bool queuedBuffer = false;
434 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
David Sodman9eeae692017-11-02 10:53:32 -0700435 getProducerStickyTransform() != 0, mName.string(),
436 mOverrideScalingMode, mFreezeGeometryUpdates);
David Sodman0c69cad2017-08-21 12:12:51 -0700437 status_t updateResult =
David Sodman9eeae692017-11-02 10:53:32 -0700438 mSurfaceFlingerConsumer->updateTexImage(&r, mFlinger->mPrimaryDispSync,
439 &mAutoRefresh, &queuedBuffer,
440 mLastFrameNumberReceived);
David Sodman0c69cad2017-08-21 12:12:51 -0700441 if (updateResult == BufferQueue::PRESENT_LATER) {
442 // Producer doesn't want buffer to be displayed yet. Signal a
443 // layer update so we check again at the next opportunity.
444 mFlinger->signalLayerUpdate();
445 return outDirtyRegion;
446 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
447 // If the buffer has been rejected, remove it from the shadow queue
448 // and return early
449 if (queuedBuffer) {
450 Mutex::Autolock lock(mQueueItemLock);
451 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);
464 }
465
466 // Once we have hit this state, the shadow queue may no longer
467 // correctly reflect the incoming BufferQueue's contents, so even if
468 // updateTexImage starts working, the only safe course of action is
469 // to continue to ignore updates.
470 mUpdateTexImageFailed = true;
471
472 return outDirtyRegion;
473 }
474
475 if (queuedBuffer) {
476 // Autolock scope
477 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
478
479 Mutex::Autolock lock(mQueueItemLock);
480
481 // Remove any stale buffers that have been dropped during
482 // updateTexImage
483 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
484 mQueueItems.removeAt(0);
485 android_atomic_dec(&mQueuedFrames);
486 }
487
488 mQueueItems.removeAt(0);
489 }
490
491 // Decrement the queued-frames count. Signal another event if we
492 // have more frames pending.
David Sodman9eeae692017-11-02 10:53:32 -0700493 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1) ||
494 mAutoRefresh) {
David Sodman0c69cad2017-08-21 12:12:51 -0700495 mFlinger->signalLayerUpdate();
496 }
497
498 // update the active buffer
David Sodman9eeae692017-11-02 10:53:32 -0700499 mActiveBuffer =
500 mSurfaceFlingerConsumer->getCurrentBuffer(&mActiveBufferSlot);
David Sodman0c69cad2017-08-21 12:12:51 -0700501 if (mActiveBuffer == NULL) {
502 // this can only happen if the very first buffer was rejected.
503 return outDirtyRegion;
504 }
505
506 mBufferLatched = true;
507 mPreviousFrameNumber = mCurrentFrameNumber;
508 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
509
510 {
511 Mutex::Autolock lock(mFrameEventHistoryMutex);
512 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
David Sodman0c69cad2017-08-21 12:12:51 -0700513 }
514
515 mRefreshPending = true;
516 mFrameLatencyNeeded = true;
517 if (oldActiveBuffer == NULL) {
518 // the first time we receive a buffer, we need to trigger a
519 // geometry invalidation.
520 recomputeVisibleRegions = true;
521 }
522
523 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
524
525 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
526 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
527 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
David Sodman9eeae692017-11-02 10:53:32 -0700528 if ((crop != mCurrentCrop) ||
529 (transform != mCurrentTransform) ||
David Sodman0c69cad2017-08-21 12:12:51 -0700530 (scalingMode != mCurrentScalingMode)) {
531 mCurrentCrop = crop;
532 mCurrentTransform = transform;
533 mCurrentScalingMode = scalingMode;
534 recomputeVisibleRegions = true;
535 }
536
537 if (oldActiveBuffer != NULL) {
538 uint32_t bufWidth = mActiveBuffer->getWidth();
539 uint32_t bufHeight = mActiveBuffer->getHeight();
540 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
541 bufHeight != uint32_t(oldActiveBuffer->height)) {
542 recomputeVisibleRegions = true;
543 }
544 }
545
546 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
547 if (oldOpacity != isOpaque(s)) {
548 recomputeVisibleRegions = true;
549 }
550
551 // Remove any sync points corresponding to the buffer which was just
552 // latched
553 {
554 Mutex::Autolock lock(mLocalSyncPointMutex);
555 auto point = mLocalSyncPoints.begin();
556 while (point != mLocalSyncPoints.end()) {
557 if (!(*point)->frameIsAvailable() || !(*point)->transactionIsApplied()) {
558 // This sync point must have been added since we started
559 // latching. Don't drop it yet.
560 ++point;
561 continue;
562 }
563
564 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
565 point = mLocalSyncPoints.erase(point);
566 } else {
567 ++point;
568 }
569 }
570 }
571
572 // FIXME: postedRegion should be dirty & bounds
573 Region dirtyRegion(Rect(s.active.w, s.active.h));
574
575 // transform the dirty region to window-manager space
576 outDirtyRegion = (getTransform().transform(dirtyRegion));
577
578 return outDirtyRegion;
579}
580
David Sodmaneb085e02017-10-05 18:49:04 -0700581void BufferLayer::setDefaultBufferSize(uint32_t w, uint32_t h) {
582 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
583}
584
David Sodman0c69cad2017-08-21 12:12:51 -0700585void BufferLayer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
586 // Apply this display's projection's viewport to the visible region
587 // before giving it to the HWC HAL.
588 const Transform& tr = displayDevice->getTransform();
589 const auto& viewport = displayDevice->getViewport();
590 Region visible = tr.transform(visibleRegion.intersect(viewport));
591 auto hwcId = displayDevice->getHwcDisplayId();
592 auto& hwcInfo = mHwcLayers[hwcId];
593 auto& hwcLayer = hwcInfo.layer;
594 auto error = hwcLayer->setVisibleRegion(visible);
595 if (error != HWC2::Error::None) {
596 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
597 to_string(error).c_str(), static_cast<int32_t>(error));
598 visible.dump(LOG_TAG);
599 }
600
601 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
602 if (error != HWC2::Error::None) {
603 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
604 to_string(error).c_str(), static_cast<int32_t>(error));
605 surfaceDamageRegion.dump(LOG_TAG);
606 }
607
608 // Sideband layers
609 if (mSidebandStream.get()) {
610 setCompositionType(hwcId, HWC2::Composition::Sideband);
611 ALOGV("[%s] Requesting Sideband composition", mName.string());
612 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
613 if (error != HWC2::Error::None) {
614 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", mName.string(),
David Sodman9eeae692017-11-02 10:53:32 -0700615 mSidebandStream->handle(), to_string(error).c_str(),
616 static_cast<int32_t>(error));
David Sodman0c69cad2017-08-21 12:12:51 -0700617 }
618 return;
619 }
620
David Sodman0c69cad2017-08-21 12:12:51 -0700621 // Device or Cursor layers
622 if (mPotentialCursor) {
623 ALOGV("[%s] Requesting Cursor composition", mName.string());
624 setCompositionType(hwcId, HWC2::Composition::Cursor);
625 } else {
626 ALOGV("[%s] Requesting Device composition", mName.string());
627 setCompositionType(hwcId, HWC2::Composition::Device);
628 }
629
630 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
631 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
632 if (error != HWC2::Error::None) {
633 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(), mCurrentState.dataSpace,
634 to_string(error).c_str(), static_cast<int32_t>(error));
635 }
636
637 uint32_t hwcSlot = 0;
638 sp<GraphicBuffer> hwcBuffer;
David Sodman9eeae692017-11-02 10:53:32 -0700639 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot,
640 mActiveBuffer, &hwcSlot, &hwcBuffer);
David Sodman0c69cad2017-08-21 12:12:51 -0700641
642 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
643 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
644 if (error != HWC2::Error::None) {
David Sodman9eeae692017-11-02 10:53:32 -0700645 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
646 mActiveBuffer->handle, to_string(error).c_str(),
647 static_cast<int32_t>(error));
David Sodman0c69cad2017-08-21 12:12:51 -0700648 }
649}
650
David Sodman41fdfc92017-11-06 16:09:56 -0800651bool BufferLayer::isOpaque(const Layer::State& s) const {
David Sodman0c69cad2017-08-21 12:12:51 -0700652 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
653 // layer's opaque flag.
654 if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
655 return false;
656 }
657
658 // if the layer has the opaque flag, then we're always opaque,
659 // otherwise we use the current buffer's format.
660 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
661}
662
663void BufferLayer::onFirstRef() {
664 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
665 sp<IGraphicBufferProducer> producer;
666 sp<IGraphicBufferConsumer> consumer;
667 BufferQueue::createBufferQueue(&producer, &consumer, true);
668 mProducer = new MonitoredProducer(producer, mFlinger, this);
669 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
670 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
671 mSurfaceFlingerConsumer->setContentsChangedListener(this);
672 mSurfaceFlingerConsumer->setName(mName);
673
674 if (mFlinger->isLayerTripleBufferingDisabled()) {
675 mProducer->setMaxDequeuedBufferCount(2);
676 }
677
678 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
679 updateTransformHint(hw);
680}
681
682// ---------------------------------------------------------------------------
683// Interface implementation for SurfaceFlingerConsumer::ContentsChangedListener
684// ---------------------------------------------------------------------------
685
686void BufferLayer::onFrameAvailable(const BufferItem& item) {
687 // Add this buffer from our internal queue tracker
688 { // Autolock scope
689 Mutex::Autolock lock(mQueueItemLock);
690 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
691 item.mGraphicBuffer->getHeight(),
692 item.mFrameNumber);
693 // Reset the frame number tracker when we receive the first buffer after
694 // a frame number reset
695 if (item.mFrameNumber == 1) {
696 mLastFrameNumberReceived = 0;
697 }
698
699 // Ensure that callbacks are handled in order
700 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
David Sodman9eeae692017-11-02 10:53:32 -0700701 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
702 ms2ns(500));
David Sodman0c69cad2017-08-21 12:12:51 -0700703 if (result != NO_ERROR) {
704 ALOGE("[%s] Timed out waiting on callback", mName.string());
705 }
706 }
707
708 mQueueItems.push_back(item);
709 android_atomic_inc(&mQueuedFrames);
710
711 // Wake up any pending callbacks
712 mLastFrameNumberReceived = item.mFrameNumber;
713 mQueueItemCondition.broadcast();
714 }
715
716 mFlinger->signalLayerUpdate();
717}
718
719void BufferLayer::onFrameReplaced(const BufferItem& item) {
720 { // Autolock scope
721 Mutex::Autolock lock(mQueueItemLock);
722
723 // Ensure that callbacks are handled in order
724 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
David Sodman9eeae692017-11-02 10:53:32 -0700725 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
726 ms2ns(500));
David Sodman0c69cad2017-08-21 12:12:51 -0700727 if (result != NO_ERROR) {
728 ALOGE("[%s] Timed out waiting on callback", mName.string());
729 }
730 }
731
732 if (mQueueItems.empty()) {
733 ALOGE("Can't replace a frame on an empty queue");
734 return;
735 }
736 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
737
738 // Wake up any pending callbacks
739 mLastFrameNumberReceived = item.mFrameNumber;
740 mQueueItemCondition.broadcast();
741 }
742}
743
744void BufferLayer::onSidebandStreamChanged() {
745 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
746 // mSidebandStreamChanged was false
747 mFlinger->signalLayerUpdate();
748 }
749}
750
751bool BufferLayer::needsFiltering(const RenderArea& renderArea) const {
752 return mNeedsFiltering || renderArea.needsFiltering();
753}
754
755// As documented in libhardware header, formats in the range
756// 0x100 - 0x1FF are specific to the HAL implementation, and
757// are known to have no alpha channel
758// TODO: move definition for device-specific range into
759// hardware.h, instead of using hard-coded values here.
760#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
761
762bool BufferLayer::getOpacityForFormat(uint32_t format) {
763 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
764 return true;
765 }
766 switch (format) {
767 case HAL_PIXEL_FORMAT_RGBA_8888:
768 case HAL_PIXEL_FORMAT_BGRA_8888:
769 case HAL_PIXEL_FORMAT_RGBA_FP16:
770 case HAL_PIXEL_FORMAT_RGBA_1010102:
771 return false;
772 }
773 // in all other case, we have no blending (also for unknown formats)
774 return true;
775}
776
David Sodman41fdfc92017-11-06 16:09:56 -0800777void BufferLayer::drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const {
David Sodman0c69cad2017-08-21 12:12:51 -0700778 const State& s(getDrawingState());
779
David Sodman9eeae692017-11-02 10:53:32 -0700780 computeGeometry(renderArea, getBE().mMesh, useIdentityTransform);
David Sodman0c69cad2017-08-21 12:12:51 -0700781
782 /*
783 * NOTE: the way we compute the texture coordinates here produces
784 * different results than when we take the HWC path -- in the later case
785 * the "source crop" is rounded to texel boundaries.
786 * This can produce significantly different results when the texture
787 * is scaled by a large amount.
788 *
789 * The GL code below is more logical (imho), and the difference with
790 * HWC is due to a limitation of the HWC API to integers -- a question
791 * is suspend is whether we should ignore this problem or revert to
792 * GL composition when a buffer scaling is applied (maybe with some
793 * minimal value)? Or, we could make GL behave like HWC -- but this feel
794 * like more of a hack.
795 */
796 Rect win(computeBounds());
797
798 Transform t = getTransform();
799 if (!s.finalCrop.isEmpty()) {
800 win = t.transform(win);
801 if (!win.intersect(s.finalCrop, &win)) {
802 win.clear();
803 }
804 win = t.inverse().transform(win);
805 if (!win.intersect(computeBounds(), &win)) {
806 win.clear();
807 }
808 }
809
810 float left = float(win.left) / float(s.active.w);
811 float top = float(win.top) / float(s.active.h);
812 float right = float(win.right) / float(s.active.w);
813 float bottom = float(win.bottom) / float(s.active.h);
814
815 // TODO: we probably want to generate the texture coords with the mesh
816 // here we assume that we only have 4 vertices
David Sodman9eeae692017-11-02 10:53:32 -0700817 Mesh::VertexArray<vec2> texCoords(getBE().mMesh.getTexCoordArray<vec2>());
David Sodman0c69cad2017-08-21 12:12:51 -0700818 texCoords[0] = vec2(left, 1.0f - top);
819 texCoords[1] = vec2(left, 1.0f - bottom);
820 texCoords[2] = vec2(right, 1.0f - bottom);
821 texCoords[3] = vec2(right, 1.0f - top);
822
823 RenderEngine& engine(mFlinger->getRenderEngine());
824 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), false /* disableTexture */,
825 getColor());
David Sodman0c69cad2017-08-21 12:12:51 -0700826 engine.setSourceDataSpace(mCurrentState.dataSpace);
David Sodman9eeae692017-11-02 10:53:32 -0700827 engine.drawMesh(getBE().mMesh);
David Sodman0c69cad2017-08-21 12:12:51 -0700828 engine.disableBlending();
829}
830
831uint32_t BufferLayer::getProducerStickyTransform() const {
832 int producerStickyTransform = 0;
833 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
834 if (ret != OK) {
835 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
836 strerror(-ret), ret);
837 return 0;
838 }
839 return static_cast<uint32_t>(producerStickyTransform);
840}
841
842bool BufferLayer::latchUnsignaledBuffers() {
843 static bool propertyLoaded = false;
844 static bool latch = false;
845 static std::mutex mutex;
846 std::lock_guard<std::mutex> lock(mutex);
847 if (!propertyLoaded) {
848 char value[PROPERTY_VALUE_MAX] = {};
849 property_get("debug.sf.latch_unsignaled", value, "0");
850 latch = atoi(value);
851 propertyLoaded = true;
852 }
853 return latch;
854}
855
856uint64_t BufferLayer::getHeadFrameNumber() const {
857 Mutex::Autolock lock(mQueueItemLock);
858 if (!mQueueItems.empty()) {
859 return mQueueItems[0].mFrameNumber;
860 } else {
861 return mCurrentFrameNumber;
862 }
863}
864
865bool BufferLayer::headFenceHasSignaled() const {
David Sodman0c69cad2017-08-21 12:12:51 -0700866 if (latchUnsignaledBuffers()) {
867 return true;
868 }
869
870 Mutex::Autolock lock(mQueueItemLock);
871 if (mQueueItems.empty()) {
872 return true;
873 }
874 if (mQueueItems[0].mIsDroppable) {
875 // Even though this buffer's fence may not have signaled yet, it could
876 // be replaced by another buffer before it has a chance to, which means
877 // that it's possible to get into a situation where a buffer is never
878 // able to be latched. To avoid this, grab this buffer anyway.
879 return true;
880 }
David Sodman9eeae692017-11-02 10:53:32 -0700881 return mQueueItems[0].mFenceTime->getSignalTime() !=
882 Fence::SIGNAL_TIME_PENDING;
David Sodman0c69cad2017-08-21 12:12:51 -0700883}
884
885uint32_t BufferLayer::getEffectiveScalingMode() const {
886 if (mOverrideScalingMode >= 0) {
887 return mOverrideScalingMode;
888 }
889 return mCurrentScalingMode;
890}
891
892// ----------------------------------------------------------------------------
893// transaction
894// ----------------------------------------------------------------------------
895
896void BufferLayer::notifyAvailableFrames() {
897 auto headFrameNumber = getHeadFrameNumber();
898 bool headFenceSignaled = headFenceHasSignaled();
899 Mutex::Autolock lock(mLocalSyncPointMutex);
900 for (auto& point : mLocalSyncPoints) {
901 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
902 point->setFrameAvailable();
903 }
904 }
905}
906
907sp<IGraphicBufferProducer> BufferLayer::getProducer() const {
908 return mProducer;
909}
910
911// ---------------------------------------------------------------------------
912// h/w composer set-up
913// ---------------------------------------------------------------------------
914
915bool BufferLayer::allTransactionsSignaled() {
916 auto headFrameNumber = getHeadFrameNumber();
917 bool matchingFramesFound = false;
918 bool allTransactionsApplied = true;
919 Mutex::Autolock lock(mLocalSyncPointMutex);
920
921 for (auto& point : mLocalSyncPoints) {
922 if (point->getFrameNumber() > headFrameNumber) {
923 break;
924 }
925 matchingFramesFound = true;
926
927 if (!point->frameIsAvailable()) {
928 // We haven't notified the remote layer that the frame for
929 // this point is available yet. Notify it now, and then
930 // abort this attempt to latch.
931 point->setFrameAvailable();
932 allTransactionsApplied = false;
933 break;
934 }
935
936 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
937 }
938 return !matchingFramesFound || allTransactionsApplied;
939}
940
941} // namespace android
942
943#if defined(__gl_h_)
944#error "don't include gl/gl.h in this file"
945#endif
946
947#if defined(__gl2_h_)
948#error "don't include gl2/gl2.h in this file"
949#endif