blob: 4e214d1b745e207242e3a3612b109e3d05a3ae95 [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) {
David Sodmaneb085e02017-10-05 18:49:04 -0700265 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
266}
David Sodmaneb085e02017-10-05 18:49:04 -0700267
268void BufferLayer::abandon() {
269 mSurfaceFlingerConsumer->abandon();
270}
271
272bool BufferLayer::shouldPresentNow(const DispSync& dispSync) const {
273 if (mSidebandStreamChanged || mAutoRefresh) {
274 return true;
275 }
276
277 Mutex::Autolock lock(mQueueItemLock);
278 if (mQueueItems.empty()) {
279 return false;
280 }
281 auto timestamp = mQueueItems[0].mTimestamp;
282 nsecs_t expectedPresent = mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
283
284 // Ignore timestamps more than a second in the future
285 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
286 ALOGW_IF(!isPlausible,
287 "[%s] Timestamp %" PRId64 " seems implausible "
288 "relative to expectedPresent %" PRId64,
289 mName.string(), timestamp, expectedPresent);
290
291 bool isDue = timestamp < expectedPresent;
292 return isDue || !isPlausible;
293}
294
295void BufferLayer::setTransformHint(uint32_t orientation) const {
296 mSurfaceFlingerConsumer->setTransformHint(orientation);
297}
298
David Sodman0c69cad2017-08-21 12:12:51 -0700299bool BufferLayer::onPreComposition(nsecs_t refreshStartTime) {
300 if (mBufferLatched) {
301 Mutex::Autolock lock(mFrameEventHistoryMutex);
302 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
303 }
304 mRefreshPending = false;
305 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
306}
David Sodmaneb085e02017-10-05 18:49:04 -0700307bool BufferLayer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
308 const std::shared_ptr<FenceTime>& presentFence,
309 const CompositorTiming& compositorTiming) {
310 // mFrameLatencyNeeded is true when a new frame was latched for the
311 // composition.
312 if (!mFrameLatencyNeeded) return false;
313
314 // Update mFrameEventHistory.
315 {
316 Mutex::Autolock lock(mFrameEventHistoryMutex);
317 mFrameEventHistory.addPostComposition(mCurrentFrameNumber, glDoneFence, presentFence,
318 compositorTiming);
319 }
320
321 // Update mFrameTracker.
322 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
323 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
324
325 std::shared_ptr<FenceTime> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFenceTime();
326 if (frameReadyFence->isValid()) {
327 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
328 } else {
329 // There was no fence for this frame, so assume that it was ready
330 // to be presented at the desired present time.
331 mFrameTracker.setFrameReadyTime(desiredPresentTime);
332 }
333
334 if (presentFence->isValid()) {
335 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
336 } else {
337 // The HWC doesn't support present fences, so use the refresh
338 // timestamp instead.
339 mFrameTracker.setActualPresentTime(
340 mFlinger->getHwComposer().getRefreshTimestamp(HWC_DISPLAY_PRIMARY));
341 }
342
343 mFrameTracker.advanceFrame();
344 mFrameLatencyNeeded = false;
345 return true;
346}
347
348std::vector<OccupancyTracker::Segment> BufferLayer::getOccupancyHistory(bool forceFlush) {
349 std::vector<OccupancyTracker::Segment> history;
350 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush, &history);
351 if (result != NO_ERROR) {
352 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(), result);
353 return {};
354 }
355 return history;
356}
357
358bool BufferLayer::getTransformToDisplayInverse() const {
359 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
360}
David Sodman0c69cad2017-08-21 12:12:51 -0700361
David Sodman0c69cad2017-08-21 12:12:51 -0700362void BufferLayer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
363 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
364 return;
365 }
366
367 auto releaseFenceTime =
368 std::make_shared<FenceTime>(mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
369 mReleaseTimeline.updateSignalTimes();
370 mReleaseTimeline.push(releaseFenceTime);
371
372 Mutex::Autolock lock(mFrameEventHistoryMutex);
373 if (mPreviousFrameNumber != 0) {
374 mFrameEventHistory.addRelease(mPreviousFrameNumber, dequeueReadyTime,
375 std::move(releaseFenceTime));
376 }
377}
David Sodman0c69cad2017-08-21 12:12:51 -0700378
379Region BufferLayer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
380 ATRACE_CALL();
381
382 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
383 // mSidebandStreamChanged was true
384 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
385 if (mSidebandStream != NULL) {
386 setTransactionFlags(eTransactionNeeded);
387 mFlinger->setTransactionFlags(eTraversalNeeded);
388 }
389 recomputeVisibleRegions = true;
390
391 const State& s(getDrawingState());
392 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
393 }
394
395 Region outDirtyRegion;
396 if (mQueuedFrames <= 0 && !mAutoRefresh) {
397 return outDirtyRegion;
398 }
399
400 // if we've already called updateTexImage() without going through
401 // a composition step, we have to skip this layer at this point
402 // because we cannot call updateTeximage() without a corresponding
403 // compositionComplete() call.
404 // we'll trigger an update in onPreComposition().
405 if (mRefreshPending) {
406 return outDirtyRegion;
407 }
408
409 // If the head buffer's acquire fence hasn't signaled yet, return and
410 // try again later
411 if (!headFenceHasSignaled()) {
412 mFlinger->signalLayerUpdate();
413 return outDirtyRegion;
414 }
415
416 // Capture the old state of the layer for comparisons later
417 const State& s(getDrawingState());
418 const bool oldOpacity = isOpaque(s);
419 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
420
421 if (!allTransactionsSignaled()) {
422 mFlinger->signalLayerUpdate();
423 return outDirtyRegion;
424 }
425
426 // This boolean is used to make sure that SurfaceFlinger's shadow copy
427 // of the buffer queue isn't modified when the buffer queue is returning
428 // BufferItem's that weren't actually queued. This can happen in shared
429 // buffer mode.
430 bool queuedBuffer = false;
431 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
432 getProducerStickyTransform() != 0, mName.string(), mOverrideScalingMode,
433 mFreezeGeometryUpdates);
434 status_t updateResult =
435 mSurfaceFlingerConsumer->updateTexImage(&r, mFlinger->mPrimaryDispSync, &mAutoRefresh,
436 &queuedBuffer, mLastFrameNumberReceived);
437 if (updateResult == BufferQueue::PRESENT_LATER) {
438 // Producer doesn't want buffer to be displayed yet. Signal a
439 // layer update so we check again at the next opportunity.
440 mFlinger->signalLayerUpdate();
441 return outDirtyRegion;
442 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
443 // If the buffer has been rejected, remove it from the shadow queue
444 // and return early
445 if (queuedBuffer) {
446 Mutex::Autolock lock(mQueueItemLock);
447 mQueueItems.removeAt(0);
448 android_atomic_dec(&mQueuedFrames);
449 }
450 return outDirtyRegion;
451 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
452 // This can occur if something goes wrong when trying to create the
453 // EGLImage for this buffer. If this happens, the buffer has already
454 // been released, so we need to clean up the queue and bug out
455 // early.
456 if (queuedBuffer) {
457 Mutex::Autolock lock(mQueueItemLock);
458 mQueueItems.clear();
459 android_atomic_and(0, &mQueuedFrames);
460 }
461
462 // Once we have hit this state, the shadow queue may no longer
463 // correctly reflect the incoming BufferQueue's contents, so even if
464 // updateTexImage starts working, the only safe course of action is
465 // to continue to ignore updates.
466 mUpdateTexImageFailed = true;
467
468 return outDirtyRegion;
469 }
470
471 if (queuedBuffer) {
472 // Autolock scope
473 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
474
475 Mutex::Autolock lock(mQueueItemLock);
476
477 // Remove any stale buffers that have been dropped during
478 // updateTexImage
479 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
480 mQueueItems.removeAt(0);
481 android_atomic_dec(&mQueuedFrames);
482 }
483
484 mQueueItems.removeAt(0);
485 }
486
487 // Decrement the queued-frames count. Signal another event if we
488 // have more frames pending.
489 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1) || mAutoRefresh) {
490 mFlinger->signalLayerUpdate();
491 }
492
493 // update the active buffer
494 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(&mActiveBufferSlot);
495 if (mActiveBuffer == NULL) {
496 // this can only happen if the very first buffer was rejected.
497 return outDirtyRegion;
498 }
499
500 mBufferLatched = true;
501 mPreviousFrameNumber = mCurrentFrameNumber;
502 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
503
504 {
505 Mutex::Autolock lock(mFrameEventHistoryMutex);
506 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
David Sodman0c69cad2017-08-21 12:12:51 -0700507 }
508
509 mRefreshPending = true;
510 mFrameLatencyNeeded = true;
511 if (oldActiveBuffer == NULL) {
512 // the first time we receive a buffer, we need to trigger a
513 // geometry invalidation.
514 recomputeVisibleRegions = true;
515 }
516
517 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
518
519 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
520 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
521 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
522 if ((crop != mCurrentCrop) || (transform != mCurrentTransform) ||
523 (scalingMode != mCurrentScalingMode)) {
524 mCurrentCrop = crop;
525 mCurrentTransform = transform;
526 mCurrentScalingMode = scalingMode;
527 recomputeVisibleRegions = true;
528 }
529
530 if (oldActiveBuffer != NULL) {
531 uint32_t bufWidth = mActiveBuffer->getWidth();
532 uint32_t bufHeight = mActiveBuffer->getHeight();
533 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
534 bufHeight != uint32_t(oldActiveBuffer->height)) {
535 recomputeVisibleRegions = true;
536 }
537 }
538
539 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
540 if (oldOpacity != isOpaque(s)) {
541 recomputeVisibleRegions = true;
542 }
543
544 // Remove any sync points corresponding to the buffer which was just
545 // latched
546 {
547 Mutex::Autolock lock(mLocalSyncPointMutex);
548 auto point = mLocalSyncPoints.begin();
549 while (point != mLocalSyncPoints.end()) {
550 if (!(*point)->frameIsAvailable() || !(*point)->transactionIsApplied()) {
551 // This sync point must have been added since we started
552 // latching. Don't drop it yet.
553 ++point;
554 continue;
555 }
556
557 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
558 point = mLocalSyncPoints.erase(point);
559 } else {
560 ++point;
561 }
562 }
563 }
564
565 // FIXME: postedRegion should be dirty & bounds
566 Region dirtyRegion(Rect(s.active.w, s.active.h));
567
568 // transform the dirty region to window-manager space
569 outDirtyRegion = (getTransform().transform(dirtyRegion));
570
571 return outDirtyRegion;
572}
573
David Sodmaneb085e02017-10-05 18:49:04 -0700574void BufferLayer::setDefaultBufferSize(uint32_t w, uint32_t h) {
575 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
576}
577
David Sodman0c69cad2017-08-21 12:12:51 -0700578void BufferLayer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
579 // Apply this display's projection's viewport to the visible region
580 // before giving it to the HWC HAL.
581 const Transform& tr = displayDevice->getTransform();
582 const auto& viewport = displayDevice->getViewport();
583 Region visible = tr.transform(visibleRegion.intersect(viewport));
584 auto hwcId = displayDevice->getHwcDisplayId();
585 auto& hwcInfo = mHwcLayers[hwcId];
586 auto& hwcLayer = hwcInfo.layer;
587 auto error = hwcLayer->setVisibleRegion(visible);
588 if (error != HWC2::Error::None) {
589 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
590 to_string(error).c_str(), static_cast<int32_t>(error));
591 visible.dump(LOG_TAG);
592 }
593
594 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
595 if (error != HWC2::Error::None) {
596 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
597 to_string(error).c_str(), static_cast<int32_t>(error));
598 surfaceDamageRegion.dump(LOG_TAG);
599 }
600
601 // Sideband layers
602 if (mSidebandStream.get()) {
603 setCompositionType(hwcId, HWC2::Composition::Sideband);
604 ALOGV("[%s] Requesting Sideband composition", mName.string());
605 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
606 if (error != HWC2::Error::None) {
607 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", mName.string(),
608 mSidebandStream->handle(), to_string(error).c_str(), static_cast<int32_t>(error));
609 }
610 return;
611 }
612
David Sodman0c69cad2017-08-21 12:12:51 -0700613 // Device or Cursor layers
614 if (mPotentialCursor) {
615 ALOGV("[%s] Requesting Cursor composition", mName.string());
616 setCompositionType(hwcId, HWC2::Composition::Cursor);
617 } else {
618 ALOGV("[%s] Requesting Device composition", mName.string());
619 setCompositionType(hwcId, HWC2::Composition::Device);
620 }
621
622 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
623 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
624 if (error != HWC2::Error::None) {
625 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(), mCurrentState.dataSpace,
626 to_string(error).c_str(), static_cast<int32_t>(error));
627 }
628
629 uint32_t hwcSlot = 0;
630 sp<GraphicBuffer> hwcBuffer;
631 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer, &hwcSlot, &hwcBuffer);
632
633 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
634 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
635 if (error != HWC2::Error::None) {
636 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(), mActiveBuffer->handle,
637 to_string(error).c_str(), static_cast<int32_t>(error));
638 }
639}
640
David Sodman41fdfc92017-11-06 16:09:56 -0800641bool BufferLayer::isOpaque(const Layer::State& s) const {
David Sodman0c69cad2017-08-21 12:12:51 -0700642 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
643 // layer's opaque flag.
644 if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
645 return false;
646 }
647
648 // if the layer has the opaque flag, then we're always opaque,
649 // otherwise we use the current buffer's format.
650 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
651}
652
653void BufferLayer::onFirstRef() {
654 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
655 sp<IGraphicBufferProducer> producer;
656 sp<IGraphicBufferConsumer> consumer;
657 BufferQueue::createBufferQueue(&producer, &consumer, true);
658 mProducer = new MonitoredProducer(producer, mFlinger, this);
659 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
660 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
661 mSurfaceFlingerConsumer->setContentsChangedListener(this);
662 mSurfaceFlingerConsumer->setName(mName);
663
664 if (mFlinger->isLayerTripleBufferingDisabled()) {
665 mProducer->setMaxDequeuedBufferCount(2);
666 }
667
668 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
669 updateTransformHint(hw);
670}
671
672// ---------------------------------------------------------------------------
673// Interface implementation for SurfaceFlingerConsumer::ContentsChangedListener
674// ---------------------------------------------------------------------------
675
676void BufferLayer::onFrameAvailable(const BufferItem& item) {
677 // Add this buffer from our internal queue tracker
678 { // Autolock scope
679 Mutex::Autolock lock(mQueueItemLock);
680 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
681 item.mGraphicBuffer->getHeight(),
682 item.mFrameNumber);
683 // Reset the frame number tracker when we receive the first buffer after
684 // a frame number reset
685 if (item.mFrameNumber == 1) {
686 mLastFrameNumberReceived = 0;
687 }
688
689 // Ensure that callbacks are handled in order
690 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
691 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock, ms2ns(500));
692 if (result != NO_ERROR) {
693 ALOGE("[%s] Timed out waiting on callback", mName.string());
694 }
695 }
696
697 mQueueItems.push_back(item);
698 android_atomic_inc(&mQueuedFrames);
699
700 // Wake up any pending callbacks
701 mLastFrameNumberReceived = item.mFrameNumber;
702 mQueueItemCondition.broadcast();
703 }
704
705 mFlinger->signalLayerUpdate();
706}
707
708void BufferLayer::onFrameReplaced(const BufferItem& item) {
709 { // Autolock scope
710 Mutex::Autolock lock(mQueueItemLock);
711
712 // Ensure that callbacks are handled in order
713 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
714 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock, ms2ns(500));
715 if (result != NO_ERROR) {
716 ALOGE("[%s] Timed out waiting on callback", mName.string());
717 }
718 }
719
720 if (mQueueItems.empty()) {
721 ALOGE("Can't replace a frame on an empty queue");
722 return;
723 }
724 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
725
726 // Wake up any pending callbacks
727 mLastFrameNumberReceived = item.mFrameNumber;
728 mQueueItemCondition.broadcast();
729 }
730}
731
732void BufferLayer::onSidebandStreamChanged() {
733 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
734 // mSidebandStreamChanged was false
735 mFlinger->signalLayerUpdate();
736 }
737}
738
739bool BufferLayer::needsFiltering(const RenderArea& renderArea) const {
740 return mNeedsFiltering || renderArea.needsFiltering();
741}
742
743// As documented in libhardware header, formats in the range
744// 0x100 - 0x1FF are specific to the HAL implementation, and
745// are known to have no alpha channel
746// TODO: move definition for device-specific range into
747// hardware.h, instead of using hard-coded values here.
748#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
749
750bool BufferLayer::getOpacityForFormat(uint32_t format) {
751 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
752 return true;
753 }
754 switch (format) {
755 case HAL_PIXEL_FORMAT_RGBA_8888:
756 case HAL_PIXEL_FORMAT_BGRA_8888:
757 case HAL_PIXEL_FORMAT_RGBA_FP16:
758 case HAL_PIXEL_FORMAT_RGBA_1010102:
759 return false;
760 }
761 // in all other case, we have no blending (also for unknown formats)
762 return true;
763}
764
David Sodman41fdfc92017-11-06 16:09:56 -0800765void BufferLayer::drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const {
David Sodman0c69cad2017-08-21 12:12:51 -0700766 const State& s(getDrawingState());
767
768 computeGeometry(renderArea, mMesh, useIdentityTransform);
769
770 /*
771 * NOTE: the way we compute the texture coordinates here produces
772 * different results than when we take the HWC path -- in the later case
773 * the "source crop" is rounded to texel boundaries.
774 * This can produce significantly different results when the texture
775 * is scaled by a large amount.
776 *
777 * The GL code below is more logical (imho), and the difference with
778 * HWC is due to a limitation of the HWC API to integers -- a question
779 * is suspend is whether we should ignore this problem or revert to
780 * GL composition when a buffer scaling is applied (maybe with some
781 * minimal value)? Or, we could make GL behave like HWC -- but this feel
782 * like more of a hack.
783 */
784 Rect win(computeBounds());
785
786 Transform t = getTransform();
787 if (!s.finalCrop.isEmpty()) {
788 win = t.transform(win);
789 if (!win.intersect(s.finalCrop, &win)) {
790 win.clear();
791 }
792 win = t.inverse().transform(win);
793 if (!win.intersect(computeBounds(), &win)) {
794 win.clear();
795 }
796 }
797
798 float left = float(win.left) / float(s.active.w);
799 float top = float(win.top) / float(s.active.h);
800 float right = float(win.right) / float(s.active.w);
801 float bottom = float(win.bottom) / float(s.active.h);
802
803 // TODO: we probably want to generate the texture coords with the mesh
804 // here we assume that we only have 4 vertices
805 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
806 texCoords[0] = vec2(left, 1.0f - top);
807 texCoords[1] = vec2(left, 1.0f - bottom);
808 texCoords[2] = vec2(right, 1.0f - bottom);
809 texCoords[3] = vec2(right, 1.0f - top);
810
811 RenderEngine& engine(mFlinger->getRenderEngine());
812 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), false /* disableTexture */,
813 getColor());
David Sodman0c69cad2017-08-21 12:12:51 -0700814 engine.setSourceDataSpace(mCurrentState.dataSpace);
David Sodman0c69cad2017-08-21 12:12:51 -0700815 engine.drawMesh(mMesh);
816 engine.disableBlending();
817}
818
819uint32_t BufferLayer::getProducerStickyTransform() const {
820 int producerStickyTransform = 0;
821 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
822 if (ret != OK) {
823 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
824 strerror(-ret), ret);
825 return 0;
826 }
827 return static_cast<uint32_t>(producerStickyTransform);
828}
829
830bool BufferLayer::latchUnsignaledBuffers() {
831 static bool propertyLoaded = false;
832 static bool latch = false;
833 static std::mutex mutex;
834 std::lock_guard<std::mutex> lock(mutex);
835 if (!propertyLoaded) {
836 char value[PROPERTY_VALUE_MAX] = {};
837 property_get("debug.sf.latch_unsignaled", value, "0");
838 latch = atoi(value);
839 propertyLoaded = true;
840 }
841 return latch;
842}
843
844uint64_t BufferLayer::getHeadFrameNumber() const {
845 Mutex::Autolock lock(mQueueItemLock);
846 if (!mQueueItems.empty()) {
847 return mQueueItems[0].mFrameNumber;
848 } else {
849 return mCurrentFrameNumber;
850 }
851}
852
853bool BufferLayer::headFenceHasSignaled() const {
David Sodman0c69cad2017-08-21 12:12:51 -0700854 if (latchUnsignaledBuffers()) {
855 return true;
856 }
857
858 Mutex::Autolock lock(mQueueItemLock);
859 if (mQueueItems.empty()) {
860 return true;
861 }
862 if (mQueueItems[0].mIsDroppable) {
863 // Even though this buffer's fence may not have signaled yet, it could
864 // be replaced by another buffer before it has a chance to, which means
865 // that it's possible to get into a situation where a buffer is never
866 // able to be latched. To avoid this, grab this buffer anyway.
867 return true;
868 }
869 return mQueueItems[0].mFenceTime->getSignalTime() != Fence::SIGNAL_TIME_PENDING;
David Sodman0c69cad2017-08-21 12:12:51 -0700870}
871
872uint32_t BufferLayer::getEffectiveScalingMode() const {
873 if (mOverrideScalingMode >= 0) {
874 return mOverrideScalingMode;
875 }
876 return mCurrentScalingMode;
877}
878
879// ----------------------------------------------------------------------------
880// transaction
881// ----------------------------------------------------------------------------
882
883void BufferLayer::notifyAvailableFrames() {
884 auto headFrameNumber = getHeadFrameNumber();
885 bool headFenceSignaled = headFenceHasSignaled();
886 Mutex::Autolock lock(mLocalSyncPointMutex);
887 for (auto& point : mLocalSyncPoints) {
888 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
889 point->setFrameAvailable();
890 }
891 }
892}
893
894sp<IGraphicBufferProducer> BufferLayer::getProducer() const {
895 return mProducer;
896}
897
898// ---------------------------------------------------------------------------
899// h/w composer set-up
900// ---------------------------------------------------------------------------
901
902bool BufferLayer::allTransactionsSignaled() {
903 auto headFrameNumber = getHeadFrameNumber();
904 bool matchingFramesFound = false;
905 bool allTransactionsApplied = true;
906 Mutex::Autolock lock(mLocalSyncPointMutex);
907
908 for (auto& point : mLocalSyncPoints) {
909 if (point->getFrameNumber() > headFrameNumber) {
910 break;
911 }
912 matchingFramesFound = true;
913
914 if (!point->frameIsAvailable()) {
915 // We haven't notified the remote layer that the frame for
916 // this point is available yet. Notify it now, and then
917 // abort this attempt to latch.
918 point->setFrameAvailable();
919 allTransactionsApplied = false;
920 break;
921 }
922
923 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
924 }
925 return !matchingFramesFound || allTransactionsApplied;
926}
927
928} // namespace android
929
930#if defined(__gl_h_)
931#error "don't include gl/gl.h in this file"
932#endif
933
934#if defined(__gl2_h_)
935#error "don't include gl2/gl2.h in this file"
936#endif