blob: c477a3b1907557ff9ee6bc3113fcb2b0c98748a5 [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.
252 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
253 mTexture.setFiltering(useFiltering);
254 mTexture.setMatrix(textureMatrix);
255
256 engine.setupLayerTexturing(mTexture);
257 } else {
258 engine.setupLayerBlackedOut();
259 }
260 drawWithOpenGL(renderArea, useIdentityTransform);
261 engine.disableTexturing();
262}
263
David Sodmaneb085e02017-10-05 18:49:04 -0700264void BufferLayer::onLayerDisplayed(const sp<Fence>& releaseFence) {
265 if (mHwcLayers.empty()) {
266 return;
267 }
268 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
269}
David Sodmaneb085e02017-10-05 18:49:04 -0700270
271void BufferLayer::abandon() {
272 mSurfaceFlingerConsumer->abandon();
273}
274
275bool BufferLayer::shouldPresentNow(const DispSync& dispSync) const {
276 if (mSidebandStreamChanged || mAutoRefresh) {
277 return true;
278 }
279
280 Mutex::Autolock lock(mQueueItemLock);
281 if (mQueueItems.empty()) {
282 return false;
283 }
284 auto timestamp = mQueueItems[0].mTimestamp;
285 nsecs_t expectedPresent = mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
286
287 // Ignore timestamps more than a second in the future
288 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
289 ALOGW_IF(!isPlausible,
290 "[%s] Timestamp %" PRId64 " seems implausible "
291 "relative to expectedPresent %" PRId64,
292 mName.string(), timestamp, expectedPresent);
293
294 bool isDue = timestamp < expectedPresent;
295 return isDue || !isPlausible;
296}
297
298void BufferLayer::setTransformHint(uint32_t orientation) const {
299 mSurfaceFlingerConsumer->setTransformHint(orientation);
300}
301
David Sodman0c69cad2017-08-21 12:12:51 -0700302bool BufferLayer::onPreComposition(nsecs_t refreshStartTime) {
303 if (mBufferLatched) {
304 Mutex::Autolock lock(mFrameEventHistoryMutex);
305 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
306 }
307 mRefreshPending = false;
308 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
309}
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);
320 mFrameEventHistory.addPostComposition(mCurrentFrameNumber, glDoneFence, presentFence,
321 compositorTiming);
322 }
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,
435 getProducerStickyTransform() != 0, mName.string(), mOverrideScalingMode,
436 mFreezeGeometryUpdates);
437 status_t updateResult =
438 mSurfaceFlingerConsumer->updateTexImage(&r, mFlinger->mPrimaryDispSync, &mAutoRefresh,
439 &queuedBuffer, mLastFrameNumberReceived);
440 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;
445 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
446 // If the buffer has been rejected, remove it from the shadow queue
447 // and return early
448 if (queuedBuffer) {
449 Mutex::Autolock lock(mQueueItemLock);
450 mQueueItems.removeAt(0);
451 android_atomic_dec(&mQueuedFrames);
452 }
453 return outDirtyRegion;
454 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
455 // This can occur if something goes wrong when trying to create the
456 // EGLImage for this buffer. If this happens, the buffer has already
457 // been released, so we need to clean up the queue and bug out
458 // early.
459 if (queuedBuffer) {
460 Mutex::Autolock lock(mQueueItemLock);
461 mQueueItems.clear();
462 android_atomic_and(0, &mQueuedFrames);
463 }
464
465 // Once we have hit this state, the shadow queue may no longer
466 // correctly reflect the incoming BufferQueue's contents, so even if
467 // updateTexImage starts working, the only safe course of action is
468 // to continue to ignore updates.
469 mUpdateTexImageFailed = true;
470
471 return outDirtyRegion;
472 }
473
474 if (queuedBuffer) {
475 // Autolock scope
476 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
477
478 Mutex::Autolock lock(mQueueItemLock);
479
480 // Remove any stale buffers that have been dropped during
481 // updateTexImage
482 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
483 mQueueItems.removeAt(0);
484 android_atomic_dec(&mQueuedFrames);
485 }
486
487 mQueueItems.removeAt(0);
488 }
489
490 // Decrement the queued-frames count. Signal another event if we
491 // have more frames pending.
492 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1) || mAutoRefresh) {
493 mFlinger->signalLayerUpdate();
494 }
495
496 // update the active buffer
497 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(&mActiveBufferSlot);
498 if (mActiveBuffer == NULL) {
499 // this can only happen if the very first buffer was rejected.
500 return outDirtyRegion;
501 }
502
503 mBufferLatched = true;
504 mPreviousFrameNumber = mCurrentFrameNumber;
505 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
506
507 {
508 Mutex::Autolock lock(mFrameEventHistoryMutex);
509 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
David Sodman0c69cad2017-08-21 12:12:51 -0700510 }
511
512 mRefreshPending = true;
513 mFrameLatencyNeeded = true;
514 if (oldActiveBuffer == NULL) {
515 // the first time we receive a buffer, we need to trigger a
516 // geometry invalidation.
517 recomputeVisibleRegions = true;
518 }
519
520 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
521
522 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
523 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
524 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
525 if ((crop != mCurrentCrop) || (transform != mCurrentTransform) ||
526 (scalingMode != mCurrentScalingMode)) {
527 mCurrentCrop = crop;
528 mCurrentTransform = transform;
529 mCurrentScalingMode = scalingMode;
530 recomputeVisibleRegions = true;
531 }
532
533 if (oldActiveBuffer != NULL) {
534 uint32_t bufWidth = mActiveBuffer->getWidth();
535 uint32_t bufHeight = mActiveBuffer->getHeight();
536 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
537 bufHeight != uint32_t(oldActiveBuffer->height)) {
538 recomputeVisibleRegions = true;
539 }
540 }
541
542 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
543 if (oldOpacity != isOpaque(s)) {
544 recomputeVisibleRegions = true;
545 }
546
547 // Remove any sync points corresponding to the buffer which was just
548 // latched
549 {
550 Mutex::Autolock lock(mLocalSyncPointMutex);
551 auto point = mLocalSyncPoints.begin();
552 while (point != mLocalSyncPoints.end()) {
553 if (!(*point)->frameIsAvailable() || !(*point)->transactionIsApplied()) {
554 // This sync point must have been added since we started
555 // latching. Don't drop it yet.
556 ++point;
557 continue;
558 }
559
560 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
561 point = mLocalSyncPoints.erase(point);
562 } else {
563 ++point;
564 }
565 }
566 }
567
568 // FIXME: postedRegion should be dirty & bounds
569 Region dirtyRegion(Rect(s.active.w, s.active.h));
570
571 // transform the dirty region to window-manager space
572 outDirtyRegion = (getTransform().transform(dirtyRegion));
573
574 return outDirtyRegion;
575}
576
David Sodmaneb085e02017-10-05 18:49:04 -0700577void BufferLayer::setDefaultBufferSize(uint32_t w, uint32_t h) {
578 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
579}
580
David Sodman0c69cad2017-08-21 12:12:51 -0700581void BufferLayer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
582 // Apply this display's projection's viewport to the visible region
583 // before giving it to the HWC HAL.
584 const Transform& tr = displayDevice->getTransform();
585 const auto& viewport = displayDevice->getViewport();
586 Region visible = tr.transform(visibleRegion.intersect(viewport));
587 auto hwcId = displayDevice->getHwcDisplayId();
588 auto& hwcInfo = mHwcLayers[hwcId];
589 auto& hwcLayer = hwcInfo.layer;
590 auto error = hwcLayer->setVisibleRegion(visible);
591 if (error != HWC2::Error::None) {
592 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
593 to_string(error).c_str(), static_cast<int32_t>(error));
594 visible.dump(LOG_TAG);
595 }
596
597 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
598 if (error != HWC2::Error::None) {
599 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
600 to_string(error).c_str(), static_cast<int32_t>(error));
601 surfaceDamageRegion.dump(LOG_TAG);
602 }
603
604 // Sideband layers
605 if (mSidebandStream.get()) {
606 setCompositionType(hwcId, HWC2::Composition::Sideband);
607 ALOGV("[%s] Requesting Sideband composition", mName.string());
608 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
609 if (error != HWC2::Error::None) {
610 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", mName.string(),
611 mSidebandStream->handle(), to_string(error).c_str(), static_cast<int32_t>(error));
612 }
613 return;
614 }
615
David Sodman0c69cad2017-08-21 12:12:51 -0700616 // Device or Cursor layers
617 if (mPotentialCursor) {
618 ALOGV("[%s] Requesting Cursor composition", mName.string());
619 setCompositionType(hwcId, HWC2::Composition::Cursor);
620 } else {
621 ALOGV("[%s] Requesting Device composition", mName.string());
622 setCompositionType(hwcId, HWC2::Composition::Device);
623 }
624
625 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
626 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
627 if (error != HWC2::Error::None) {
628 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(), mCurrentState.dataSpace,
629 to_string(error).c_str(), static_cast<int32_t>(error));
630 }
631
632 uint32_t hwcSlot = 0;
633 sp<GraphicBuffer> hwcBuffer;
634 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer, &hwcSlot, &hwcBuffer);
635
636 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
637 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
638 if (error != HWC2::Error::None) {
639 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(), mActiveBuffer->handle,
640 to_string(error).c_str(), static_cast<int32_t>(error));
641 }
642}
643
David Sodman41fdfc92017-11-06 16:09:56 -0800644bool BufferLayer::isOpaque(const Layer::State& s) const {
David Sodman0c69cad2017-08-21 12:12:51 -0700645 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
646 // layer's opaque flag.
647 if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
648 return false;
649 }
650
651 // if the layer has the opaque flag, then we're always opaque,
652 // otherwise we use the current buffer's format.
653 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
654}
655
656void BufferLayer::onFirstRef() {
657 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
658 sp<IGraphicBufferProducer> producer;
659 sp<IGraphicBufferConsumer> consumer;
660 BufferQueue::createBufferQueue(&producer, &consumer, true);
661 mProducer = new MonitoredProducer(producer, mFlinger, this);
662 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
663 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
664 mSurfaceFlingerConsumer->setContentsChangedListener(this);
665 mSurfaceFlingerConsumer->setName(mName);
666
667 if (mFlinger->isLayerTripleBufferingDisabled()) {
668 mProducer->setMaxDequeuedBufferCount(2);
669 }
670
671 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
672 updateTransformHint(hw);
673}
674
675// ---------------------------------------------------------------------------
676// Interface implementation for SurfaceFlingerConsumer::ContentsChangedListener
677// ---------------------------------------------------------------------------
678
679void BufferLayer::onFrameAvailable(const BufferItem& item) {
680 // Add this buffer from our internal queue tracker
681 { // Autolock scope
682 Mutex::Autolock lock(mQueueItemLock);
683 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
684 item.mGraphicBuffer->getHeight(),
685 item.mFrameNumber);
686 // Reset the frame number tracker when we receive the first buffer after
687 // a frame number reset
688 if (item.mFrameNumber == 1) {
689 mLastFrameNumberReceived = 0;
690 }
691
692 // Ensure that callbacks are handled in order
693 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
694 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock, ms2ns(500));
695 if (result != NO_ERROR) {
696 ALOGE("[%s] Timed out waiting on callback", mName.string());
697 }
698 }
699
700 mQueueItems.push_back(item);
701 android_atomic_inc(&mQueuedFrames);
702
703 // Wake up any pending callbacks
704 mLastFrameNumberReceived = item.mFrameNumber;
705 mQueueItemCondition.broadcast();
706 }
707
708 mFlinger->signalLayerUpdate();
709}
710
711void BufferLayer::onFrameReplaced(const BufferItem& item) {
712 { // Autolock scope
713 Mutex::Autolock lock(mQueueItemLock);
714
715 // Ensure that callbacks are handled in order
716 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
717 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock, ms2ns(500));
718 if (result != NO_ERROR) {
719 ALOGE("[%s] Timed out waiting on callback", mName.string());
720 }
721 }
722
723 if (mQueueItems.empty()) {
724 ALOGE("Can't replace a frame on an empty queue");
725 return;
726 }
727 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
728
729 // Wake up any pending callbacks
730 mLastFrameNumberReceived = item.mFrameNumber;
731 mQueueItemCondition.broadcast();
732 }
733}
734
735void BufferLayer::onSidebandStreamChanged() {
736 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
737 // mSidebandStreamChanged was false
738 mFlinger->signalLayerUpdate();
739 }
740}
741
742bool BufferLayer::needsFiltering(const RenderArea& renderArea) const {
743 return mNeedsFiltering || renderArea.needsFiltering();
744}
745
746// As documented in libhardware header, formats in the range
747// 0x100 - 0x1FF are specific to the HAL implementation, and
748// are known to have no alpha channel
749// TODO: move definition for device-specific range into
750// hardware.h, instead of using hard-coded values here.
751#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
752
753bool BufferLayer::getOpacityForFormat(uint32_t format) {
754 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
755 return true;
756 }
757 switch (format) {
758 case HAL_PIXEL_FORMAT_RGBA_8888:
759 case HAL_PIXEL_FORMAT_BGRA_8888:
760 case HAL_PIXEL_FORMAT_RGBA_FP16:
761 case HAL_PIXEL_FORMAT_RGBA_1010102:
762 return false;
763 }
764 // in all other case, we have no blending (also for unknown formats)
765 return true;
766}
767
David Sodman41fdfc92017-11-06 16:09:56 -0800768void BufferLayer::drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const {
David Sodman0c69cad2017-08-21 12:12:51 -0700769 const State& s(getDrawingState());
770
771 computeGeometry(renderArea, mMesh, useIdentityTransform);
772
773 /*
774 * NOTE: the way we compute the texture coordinates here produces
775 * different results than when we take the HWC path -- in the later case
776 * the "source crop" is rounded to texel boundaries.
777 * This can produce significantly different results when the texture
778 * is scaled by a large amount.
779 *
780 * The GL code below is more logical (imho), and the difference with
781 * HWC is due to a limitation of the HWC API to integers -- a question
782 * is suspend is whether we should ignore this problem or revert to
783 * GL composition when a buffer scaling is applied (maybe with some
784 * minimal value)? Or, we could make GL behave like HWC -- but this feel
785 * like more of a hack.
786 */
787 Rect win(computeBounds());
788
789 Transform t = getTransform();
790 if (!s.finalCrop.isEmpty()) {
791 win = t.transform(win);
792 if (!win.intersect(s.finalCrop, &win)) {
793 win.clear();
794 }
795 win = t.inverse().transform(win);
796 if (!win.intersect(computeBounds(), &win)) {
797 win.clear();
798 }
799 }
800
801 float left = float(win.left) / float(s.active.w);
802 float top = float(win.top) / float(s.active.h);
803 float right = float(win.right) / float(s.active.w);
804 float bottom = float(win.bottom) / float(s.active.h);
805
806 // TODO: we probably want to generate the texture coords with the mesh
807 // here we assume that we only have 4 vertices
808 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
809 texCoords[0] = vec2(left, 1.0f - top);
810 texCoords[1] = vec2(left, 1.0f - bottom);
811 texCoords[2] = vec2(right, 1.0f - bottom);
812 texCoords[3] = vec2(right, 1.0f - top);
813
814 RenderEngine& engine(mFlinger->getRenderEngine());
815 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), false /* disableTexture */,
816 getColor());
David Sodman0c69cad2017-08-21 12:12:51 -0700817 engine.setSourceDataSpace(mCurrentState.dataSpace);
David Sodman0c69cad2017-08-21 12:12:51 -0700818 engine.drawMesh(mMesh);
819 engine.disableBlending();
820}
821
822uint32_t BufferLayer::getProducerStickyTransform() const {
823 int producerStickyTransform = 0;
824 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
825 if (ret != OK) {
826 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
827 strerror(-ret), ret);
828 return 0;
829 }
830 return static_cast<uint32_t>(producerStickyTransform);
831}
832
833bool BufferLayer::latchUnsignaledBuffers() {
834 static bool propertyLoaded = false;
835 static bool latch = false;
836 static std::mutex mutex;
837 std::lock_guard<std::mutex> lock(mutex);
838 if (!propertyLoaded) {
839 char value[PROPERTY_VALUE_MAX] = {};
840 property_get("debug.sf.latch_unsignaled", value, "0");
841 latch = atoi(value);
842 propertyLoaded = true;
843 }
844 return latch;
845}
846
847uint64_t BufferLayer::getHeadFrameNumber() const {
848 Mutex::Autolock lock(mQueueItemLock);
849 if (!mQueueItems.empty()) {
850 return mQueueItems[0].mFrameNumber;
851 } else {
852 return mCurrentFrameNumber;
853 }
854}
855
856bool BufferLayer::headFenceHasSignaled() const {
David Sodman0c69cad2017-08-21 12:12:51 -0700857 if (latchUnsignaledBuffers()) {
858 return true;
859 }
860
861 Mutex::Autolock lock(mQueueItemLock);
862 if (mQueueItems.empty()) {
863 return true;
864 }
865 if (mQueueItems[0].mIsDroppable) {
866 // Even though this buffer's fence may not have signaled yet, it could
867 // be replaced by another buffer before it has a chance to, which means
868 // that it's possible to get into a situation where a buffer is never
869 // able to be latched. To avoid this, grab this buffer anyway.
870 return true;
871 }
872 return mQueueItems[0].mFenceTime->getSignalTime() != Fence::SIGNAL_TIME_PENDING;
David Sodman0c69cad2017-08-21 12:12:51 -0700873}
874
875uint32_t BufferLayer::getEffectiveScalingMode() const {
876 if (mOverrideScalingMode >= 0) {
877 return mOverrideScalingMode;
878 }
879 return mCurrentScalingMode;
880}
881
882// ----------------------------------------------------------------------------
883// transaction
884// ----------------------------------------------------------------------------
885
886void BufferLayer::notifyAvailableFrames() {
887 auto headFrameNumber = getHeadFrameNumber();
888 bool headFenceSignaled = headFenceHasSignaled();
889 Mutex::Autolock lock(mLocalSyncPointMutex);
890 for (auto& point : mLocalSyncPoints) {
891 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
892 point->setFrameAvailable();
893 }
894 }
895}
896
897sp<IGraphicBufferProducer> BufferLayer::getProducer() const {
898 return mProducer;
899}
900
901// ---------------------------------------------------------------------------
902// h/w composer set-up
903// ---------------------------------------------------------------------------
904
905bool BufferLayer::allTransactionsSignaled() {
906 auto headFrameNumber = getHeadFrameNumber();
907 bool matchingFramesFound = false;
908 bool allTransactionsApplied = true;
909 Mutex::Autolock lock(mLocalSyncPointMutex);
910
911 for (auto& point : mLocalSyncPoints) {
912 if (point->getFrameNumber() > headFrameNumber) {
913 break;
914 }
915 matchingFramesFound = true;
916
917 if (!point->frameIsAvailable()) {
918 // We haven't notified the remote layer that the frame for
919 // this point is available yet. Notify it now, and then
920 // abort this attempt to latch.
921 point->setFrameAvailable();
922 allTransactionsApplied = false;
923 break;
924 }
925
926 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
927 }
928 return !matchingFramesFound || allTransactionsApplied;
929}
930
931} // namespace android
932
933#if defined(__gl_h_)
934#error "don't include gl/gl.h in this file"
935#endif
936
937#if defined(__gl2_h_)
938#error "don't include gl2/gl2.h in this file"
939#endif