blob: 0c1693b53b04bfbb11830d08eae2220411f17c81 [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
616 // Client layers
617 if (hwcInfo.forceClientComposition ||
618 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
619 ALOGV("[%s] Requesting Client composition", mName.string());
620 setCompositionType(hwcId, HWC2::Composition::Client);
621 return;
622 }
623
David Sodman0c69cad2017-08-21 12:12:51 -0700624 // Device or Cursor layers
625 if (mPotentialCursor) {
626 ALOGV("[%s] Requesting Cursor composition", mName.string());
627 setCompositionType(hwcId, HWC2::Composition::Cursor);
628 } else {
629 ALOGV("[%s] Requesting Device composition", mName.string());
630 setCompositionType(hwcId, HWC2::Composition::Device);
631 }
632
633 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
634 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
635 if (error != HWC2::Error::None) {
636 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(), mCurrentState.dataSpace,
637 to_string(error).c_str(), static_cast<int32_t>(error));
638 }
639
640 uint32_t hwcSlot = 0;
641 sp<GraphicBuffer> hwcBuffer;
642 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer, &hwcSlot, &hwcBuffer);
643
644 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
645 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
646 if (error != HWC2::Error::None) {
647 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(), mActiveBuffer->handle,
648 to_string(error).c_str(), static_cast<int32_t>(error));
649 }
650}
651
David Sodman41fdfc92017-11-06 16:09:56 -0800652bool BufferLayer::isOpaque(const Layer::State& s) const {
David Sodman0c69cad2017-08-21 12:12:51 -0700653 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
654 // layer's opaque flag.
655 if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
656 return false;
657 }
658
659 // if the layer has the opaque flag, then we're always opaque,
660 // otherwise we use the current buffer's format.
661 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
662}
663
664void BufferLayer::onFirstRef() {
665 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
666 sp<IGraphicBufferProducer> producer;
667 sp<IGraphicBufferConsumer> consumer;
668 BufferQueue::createBufferQueue(&producer, &consumer, true);
669 mProducer = new MonitoredProducer(producer, mFlinger, this);
670 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
671 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
672 mSurfaceFlingerConsumer->setContentsChangedListener(this);
673 mSurfaceFlingerConsumer->setName(mName);
674
675 if (mFlinger->isLayerTripleBufferingDisabled()) {
676 mProducer->setMaxDequeuedBufferCount(2);
677 }
678
679 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
680 updateTransformHint(hw);
681}
682
683// ---------------------------------------------------------------------------
684// Interface implementation for SurfaceFlingerConsumer::ContentsChangedListener
685// ---------------------------------------------------------------------------
686
687void BufferLayer::onFrameAvailable(const BufferItem& item) {
688 // Add this buffer from our internal queue tracker
689 { // Autolock scope
690 Mutex::Autolock lock(mQueueItemLock);
691 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
692 item.mGraphicBuffer->getHeight(),
693 item.mFrameNumber);
694 // Reset the frame number tracker when we receive the first buffer after
695 // a frame number reset
696 if (item.mFrameNumber == 1) {
697 mLastFrameNumberReceived = 0;
698 }
699
700 // Ensure that callbacks are handled in order
701 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
702 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock, ms2ns(500));
703 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) {
725 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock, ms2ns(500));
726 if (result != NO_ERROR) {
727 ALOGE("[%s] Timed out waiting on callback", mName.string());
728 }
729 }
730
731 if (mQueueItems.empty()) {
732 ALOGE("Can't replace a frame on an empty queue");
733 return;
734 }
735 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
736
737 // Wake up any pending callbacks
738 mLastFrameNumberReceived = item.mFrameNumber;
739 mQueueItemCondition.broadcast();
740 }
741}
742
743void BufferLayer::onSidebandStreamChanged() {
744 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
745 // mSidebandStreamChanged was false
746 mFlinger->signalLayerUpdate();
747 }
748}
749
750bool BufferLayer::needsFiltering(const RenderArea& renderArea) const {
751 return mNeedsFiltering || renderArea.needsFiltering();
752}
753
754// As documented in libhardware header, formats in the range
755// 0x100 - 0x1FF are specific to the HAL implementation, and
756// are known to have no alpha channel
757// TODO: move definition for device-specific range into
758// hardware.h, instead of using hard-coded values here.
759#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
760
761bool BufferLayer::getOpacityForFormat(uint32_t format) {
762 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
763 return true;
764 }
765 switch (format) {
766 case HAL_PIXEL_FORMAT_RGBA_8888:
767 case HAL_PIXEL_FORMAT_BGRA_8888:
768 case HAL_PIXEL_FORMAT_RGBA_FP16:
769 case HAL_PIXEL_FORMAT_RGBA_1010102:
770 return false;
771 }
772 // in all other case, we have no blending (also for unknown formats)
773 return true;
774}
775
David Sodman41fdfc92017-11-06 16:09:56 -0800776void BufferLayer::drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const {
David Sodman0c69cad2017-08-21 12:12:51 -0700777 const State& s(getDrawingState());
778
779 computeGeometry(renderArea, mMesh, useIdentityTransform);
780
781 /*
782 * NOTE: the way we compute the texture coordinates here produces
783 * different results than when we take the HWC path -- in the later case
784 * the "source crop" is rounded to texel boundaries.
785 * This can produce significantly different results when the texture
786 * is scaled by a large amount.
787 *
788 * The GL code below is more logical (imho), and the difference with
789 * HWC is due to a limitation of the HWC API to integers -- a question
790 * is suspend is whether we should ignore this problem or revert to
791 * GL composition when a buffer scaling is applied (maybe with some
792 * minimal value)? Or, we could make GL behave like HWC -- but this feel
793 * like more of a hack.
794 */
795 Rect win(computeBounds());
796
797 Transform t = getTransform();
798 if (!s.finalCrop.isEmpty()) {
799 win = t.transform(win);
800 if (!win.intersect(s.finalCrop, &win)) {
801 win.clear();
802 }
803 win = t.inverse().transform(win);
804 if (!win.intersect(computeBounds(), &win)) {
805 win.clear();
806 }
807 }
808
809 float left = float(win.left) / float(s.active.w);
810 float top = float(win.top) / float(s.active.h);
811 float right = float(win.right) / float(s.active.w);
812 float bottom = float(win.bottom) / float(s.active.h);
813
814 // TODO: we probably want to generate the texture coords with the mesh
815 // here we assume that we only have 4 vertices
816 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
817 texCoords[0] = vec2(left, 1.0f - top);
818 texCoords[1] = vec2(left, 1.0f - bottom);
819 texCoords[2] = vec2(right, 1.0f - bottom);
820 texCoords[3] = vec2(right, 1.0f - top);
821
822 RenderEngine& engine(mFlinger->getRenderEngine());
823 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), false /* disableTexture */,
824 getColor());
David Sodman0c69cad2017-08-21 12:12:51 -0700825 engine.setSourceDataSpace(mCurrentState.dataSpace);
David Sodman0c69cad2017-08-21 12:12:51 -0700826 engine.drawMesh(mMesh);
827 engine.disableBlending();
828}
829
830uint32_t BufferLayer::getProducerStickyTransform() const {
831 int producerStickyTransform = 0;
832 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
833 if (ret != OK) {
834 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
835 strerror(-ret), ret);
836 return 0;
837 }
838 return static_cast<uint32_t>(producerStickyTransform);
839}
840
841bool BufferLayer::latchUnsignaledBuffers() {
842 static bool propertyLoaded = false;
843 static bool latch = false;
844 static std::mutex mutex;
845 std::lock_guard<std::mutex> lock(mutex);
846 if (!propertyLoaded) {
847 char value[PROPERTY_VALUE_MAX] = {};
848 property_get("debug.sf.latch_unsignaled", value, "0");
849 latch = atoi(value);
850 propertyLoaded = true;
851 }
852 return latch;
853}
854
855uint64_t BufferLayer::getHeadFrameNumber() const {
856 Mutex::Autolock lock(mQueueItemLock);
857 if (!mQueueItems.empty()) {
858 return mQueueItems[0].mFrameNumber;
859 } else {
860 return mCurrentFrameNumber;
861 }
862}
863
864bool BufferLayer::headFenceHasSignaled() const {
David Sodman0c69cad2017-08-21 12:12:51 -0700865 if (latchUnsignaledBuffers()) {
866 return true;
867 }
868
869 Mutex::Autolock lock(mQueueItemLock);
870 if (mQueueItems.empty()) {
871 return true;
872 }
873 if (mQueueItems[0].mIsDroppable) {
874 // Even though this buffer's fence may not have signaled yet, it could
875 // be replaced by another buffer before it has a chance to, which means
876 // that it's possible to get into a situation where a buffer is never
877 // able to be latched. To avoid this, grab this buffer anyway.
878 return true;
879 }
880 return mQueueItems[0].mFenceTime->getSignalTime() != Fence::SIGNAL_TIME_PENDING;
David Sodman0c69cad2017-08-21 12:12:51 -0700881}
882
883uint32_t BufferLayer::getEffectiveScalingMode() const {
884 if (mOverrideScalingMode >= 0) {
885 return mOverrideScalingMode;
886 }
887 return mCurrentScalingMode;
888}
889
890// ----------------------------------------------------------------------------
891// transaction
892// ----------------------------------------------------------------------------
893
894void BufferLayer::notifyAvailableFrames() {
895 auto headFrameNumber = getHeadFrameNumber();
896 bool headFenceSignaled = headFenceHasSignaled();
897 Mutex::Autolock lock(mLocalSyncPointMutex);
898 for (auto& point : mLocalSyncPoints) {
899 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
900 point->setFrameAvailable();
901 }
902 }
903}
904
905sp<IGraphicBufferProducer> BufferLayer::getProducer() const {
906 return mProducer;
907}
908
909// ---------------------------------------------------------------------------
910// h/w composer set-up
911// ---------------------------------------------------------------------------
912
913bool BufferLayer::allTransactionsSignaled() {
914 auto headFrameNumber = getHeadFrameNumber();
915 bool matchingFramesFound = false;
916 bool allTransactionsApplied = true;
917 Mutex::Autolock lock(mLocalSyncPointMutex);
918
919 for (auto& point : mLocalSyncPoints) {
920 if (point->getFrameNumber() > headFrameNumber) {
921 break;
922 }
923 matchingFramesFound = true;
924
925 if (!point->frameIsAvailable()) {
926 // We haven't notified the remote layer that the frame for
927 // this point is available yet. Notify it now, and then
928 // abort this attempt to latch.
929 point->setFrameAvailable();
930 allTransactionsApplied = false;
931 break;
932 }
933
934 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
935 }
936 return !matchingFramesFound || allTransactionsApplied;
937}
938
939} // namespace android
940
941#if defined(__gl_h_)
942#error "don't include gl/gl.h in this file"
943#endif
944
945#if defined(__gl2_h_)
946#error "don't include gl2/gl2.h in this file"
947#endif