Home | History | Annotate | Download | only in surfaceflinger
      1 /*
      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 
     24 #include <compositionengine/CompositionEngine.h>
     25 #include <compositionengine/Display.h>
     26 #include <compositionengine/Layer.h>
     27 #include <compositionengine/LayerCreationArgs.h>
     28 #include <compositionengine/OutputLayer.h>
     29 #include <compositionengine/impl/LayerCompositionState.h>
     30 #include <compositionengine/impl/OutputLayerCompositionState.h>
     31 #include <cutils/compiler.h>
     32 #include <cutils/native_handle.h>
     33 #include <cutils/properties.h>
     34 #include <gui/BufferItem.h>
     35 #include <gui/BufferQueue.h>
     36 #include <gui/LayerDebugInfo.h>
     37 #include <gui/Surface.h>
     38 #include <renderengine/RenderEngine.h>
     39 #include <ui/DebugUtils.h>
     40 #include <utils/Errors.h>
     41 #include <utils/Log.h>
     42 #include <utils/NativeHandle.h>
     43 #include <utils/StopWatch.h>
     44 #include <utils/Trace.h>
     45 
     46 #include <cmath>
     47 #include <cstdlib>
     48 #include <mutex>
     49 #include <sstream>
     50 
     51 #include "Colorizer.h"
     52 #include "DisplayDevice.h"
     53 #include "LayerRejecter.h"
     54 #include "TimeStats/TimeStats.h"
     55 
     56 namespace android {
     57 
     58 BufferLayer::BufferLayer(const LayerCreationArgs& args)
     59       : Layer(args),
     60         mTextureName(args.flinger->getNewTexture()),
     61         mCompositionLayer{mFlinger->getCompositionEngine().createLayer(
     62                 compositionengine::LayerCreationArgs{this})} {
     63     ALOGV("Creating Layer %s", args.name.string());
     64 
     65     mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
     66 
     67     mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
     68     mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
     69 }
     70 
     71 BufferLayer::~BufferLayer() {
     72     mFlinger->deleteTextureAsync(mTextureName);
     73     mFlinger->mTimeStats->onDestroy(getSequence());
     74 }
     75 
     76 void BufferLayer::useSurfaceDamage() {
     77     if (mFlinger->mForceFullDamage) {
     78         surfaceDamageRegion = Region::INVALID_REGION;
     79     } else {
     80         surfaceDamageRegion = getDrawingSurfaceDamage();
     81     }
     82 }
     83 
     84 void BufferLayer::useEmptyDamage() {
     85     surfaceDamageRegion.clear();
     86 }
     87 
     88 bool BufferLayer::isOpaque(const Layer::State& s) const {
     89     // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
     90     // layer's opaque flag.
     91     if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
     92         return false;
     93     }
     94 
     95     // if the layer has the opaque flag, then we're always opaque,
     96     // otherwise we use the current buffer's format.
     97     return ((s.flags & layer_state_t::eLayerOpaque) != 0) || getOpacityForFormat(getPixelFormat());
     98 }
     99 
    100 bool BufferLayer::isVisible() const {
    101     bool visible = !(isHiddenByPolicy()) && getAlpha() > 0.0f &&
    102             (mActiveBuffer != nullptr || mSidebandStream != nullptr);
    103     mFlinger->mScheduler->setLayerVisibility(mSchedulerLayerHandle, visible);
    104 
    105     return visible;
    106 }
    107 
    108 bool BufferLayer::isFixedSize() const {
    109     return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
    110 }
    111 
    112 bool BufferLayer::usesSourceCrop() const {
    113     return true;
    114 }
    115 
    116 static constexpr mat4 inverseOrientation(uint32_t transform) {
    117     const mat4 flipH(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
    118     const mat4 flipV(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
    119     const mat4 rot90(0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
    120     mat4 tr;
    121 
    122     if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
    123         tr = tr * rot90;
    124     }
    125     if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
    126         tr = tr * flipH;
    127     }
    128     if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
    129         tr = tr * flipV;
    130     }
    131     return inverse(tr);
    132 }
    133 
    134 bool BufferLayer::prepareClientLayer(const RenderArea& renderArea, const Region& clip,
    135                                      bool useIdentityTransform, Region& clearRegion,
    136                                      const bool supportProtectedContent,
    137                                      renderengine::LayerSettings& layer) {
    138     ATRACE_CALL();
    139     Layer::prepareClientLayer(renderArea, clip, useIdentityTransform, clearRegion,
    140                               supportProtectedContent, layer);
    141     if (CC_UNLIKELY(mActiveBuffer == 0)) {
    142         // the texture has not been created yet, this Layer has
    143         // in fact never been drawn into. This happens frequently with
    144         // SurfaceView because the WindowManager can't know when the client
    145         // has drawn the first time.
    146 
    147         // If there is nothing under us, we paint the screen in black, otherwise
    148         // we just skip this update.
    149 
    150         // figure out if there is something below us
    151         Region under;
    152         bool finished = false;
    153         mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
    154             if (finished || layer == static_cast<BufferLayer const*>(this)) {
    155                 finished = true;
    156                 return;
    157             }
    158             under.orSelf(layer->visibleRegion);
    159         });
    160         // if not everything below us is covered, we plug the holes!
    161         Region holes(clip.subtract(under));
    162         if (!holes.isEmpty()) {
    163             clearRegion.orSelf(holes);
    164         }
    165         return false;
    166     }
    167     bool blackOutLayer =
    168             (isProtected() && !supportProtectedContent) || (isSecure() && !renderArea.isSecure());
    169     const State& s(getDrawingState());
    170     if (!blackOutLayer) {
    171         layer.source.buffer.buffer = mActiveBuffer;
    172         layer.source.buffer.isOpaque = isOpaque(s);
    173         layer.source.buffer.fence = mActiveBufferFence;
    174         layer.source.buffer.textureName = mTextureName;
    175         layer.source.buffer.usePremultipliedAlpha = getPremultipledAlpha();
    176         layer.source.buffer.isY410BT2020 = isHdrY410();
    177         // TODO: we could be more subtle with isFixedSize()
    178         const bool useFiltering = needsFiltering(renderArea.getDisplayDevice()) ||
    179                 renderArea.needsFiltering() || isFixedSize();
    180 
    181         // Query the texture matrix given our current filtering mode.
    182         float textureMatrix[16];
    183         setFilteringEnabled(useFiltering);
    184         getDrawingTransformMatrix(textureMatrix);
    185 
    186         if (getTransformToDisplayInverse()) {
    187             /*
    188              * the code below applies the primary display's inverse transform to
    189              * the texture transform
    190              */
    191             uint32_t transform = DisplayDevice::getPrimaryDisplayOrientationTransform();
    192             mat4 tr = inverseOrientation(transform);
    193 
    194             /**
    195              * TODO(b/36727915): This is basically a hack.
    196              *
    197              * Ensure that regardless of the parent transformation,
    198              * this buffer is always transformed from native display
    199              * orientation to display orientation. For example, in the case
    200              * of a camera where the buffer remains in native orientation,
    201              * we want the pixels to always be upright.
    202              */
    203             sp<Layer> p = mDrawingParent.promote();
    204             if (p != nullptr) {
    205                 const auto parentTransform = p->getTransform();
    206                 tr = tr * inverseOrientation(parentTransform.getOrientation());
    207             }
    208 
    209             // and finally apply it to the original texture matrix
    210             const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
    211             memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
    212         }
    213 
    214         const Rect win{getBounds()};
    215         float bufferWidth = getBufferSize(s).getWidth();
    216         float bufferHeight = getBufferSize(s).getHeight();
    217 
    218         // BufferStateLayers can have a "buffer size" of [0, 0, -1, -1] when no display frame has
    219         // been set and there is no parent layer bounds. In that case, the scale is meaningless so
    220         // ignore them.
    221         if (!getBufferSize(s).isValid()) {
    222             bufferWidth = float(win.right) - float(win.left);
    223             bufferHeight = float(win.bottom) - float(win.top);
    224         }
    225 
    226         const float scaleHeight = (float(win.bottom) - float(win.top)) / bufferHeight;
    227         const float scaleWidth = (float(win.right) - float(win.left)) / bufferWidth;
    228         const float translateY = float(win.top) / bufferHeight;
    229         const float translateX = float(win.left) / bufferWidth;
    230 
    231         // Flip y-coordinates because GLConsumer expects OpenGL convention.
    232         mat4 tr = mat4::translate(vec4(.5, .5, 0, 1)) * mat4::scale(vec4(1, -1, 1, 1)) *
    233                 mat4::translate(vec4(-.5, -.5, 0, 1)) *
    234                 mat4::translate(vec4(translateX, translateY, 0, 1)) *
    235                 mat4::scale(vec4(scaleWidth, scaleHeight, 1.0, 1.0));
    236 
    237         layer.source.buffer.useTextureFiltering = useFiltering;
    238         layer.source.buffer.textureTransform = mat4(static_cast<const float*>(textureMatrix)) * tr;
    239     } else {
    240         // If layer is blacked out, force alpha to 1 so that we draw a black color
    241         // layer.
    242         layer.source.buffer.buffer = nullptr;
    243         layer.alpha = 1.0;
    244     }
    245 
    246     return true;
    247 }
    248 
    249 bool BufferLayer::isHdrY410() const {
    250     // pixel format is HDR Y410 masquerading as RGBA_1010102
    251     return (mCurrentDataSpace == ui::Dataspace::BT2020_ITU_PQ &&
    252             getDrawingApi() == NATIVE_WINDOW_API_MEDIA &&
    253             mActiveBuffer->getPixelFormat() == HAL_PIXEL_FORMAT_RGBA_1010102);
    254 }
    255 
    256 void BufferLayer::setPerFrameData(const sp<const DisplayDevice>& displayDevice,
    257                                   const ui::Transform& transform, const Rect& viewport,
    258                                   int32_t supportedPerFrameMetadata,
    259                                   const ui::Dataspace targetDataspace) {
    260     RETURN_IF_NO_HWC_LAYER(displayDevice);
    261 
    262     // Apply this display's projection's viewport to the visible region
    263     // before giving it to the HWC HAL.
    264     Region visible = transform.transform(visibleRegion.intersect(viewport));
    265 
    266     const auto outputLayer = findOutputLayerForDisplay(displayDevice);
    267     LOG_FATAL_IF(!outputLayer || !outputLayer->getState().hwc);
    268 
    269     auto& hwcLayer = (*outputLayer->getState().hwc).hwcLayer;
    270     auto error = hwcLayer->setVisibleRegion(visible);
    271     if (error != HWC2::Error::None) {
    272         ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
    273               to_string(error).c_str(), static_cast<int32_t>(error));
    274         visible.dump(LOG_TAG);
    275     }
    276     outputLayer->editState().visibleRegion = visible;
    277 
    278     auto& layerCompositionState = getCompositionLayer()->editState().frontEnd;
    279 
    280     error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
    281     if (error != HWC2::Error::None) {
    282         ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
    283               to_string(error).c_str(), static_cast<int32_t>(error));
    284         surfaceDamageRegion.dump(LOG_TAG);
    285     }
    286     layerCompositionState.surfaceDamage = surfaceDamageRegion;
    287 
    288     // Sideband layers
    289     if (layerCompositionState.sidebandStream.get()) {
    290         setCompositionType(displayDevice, Hwc2::IComposerClient::Composition::SIDEBAND);
    291         ALOGV("[%s] Requesting Sideband composition", mName.string());
    292         error = hwcLayer->setSidebandStream(layerCompositionState.sidebandStream->handle());
    293         if (error != HWC2::Error::None) {
    294             ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", mName.string(),
    295                   layerCompositionState.sidebandStream->handle(), to_string(error).c_str(),
    296                   static_cast<int32_t>(error));
    297         }
    298         layerCompositionState.compositionType = Hwc2::IComposerClient::Composition::SIDEBAND;
    299         return;
    300     }
    301 
    302     // Device or Cursor layers
    303     if (mPotentialCursor) {
    304         ALOGV("[%s] Requesting Cursor composition", mName.string());
    305         setCompositionType(displayDevice, Hwc2::IComposerClient::Composition::CURSOR);
    306     } else {
    307         ALOGV("[%s] Requesting Device composition", mName.string());
    308         setCompositionType(displayDevice, Hwc2::IComposerClient::Composition::DEVICE);
    309     }
    310 
    311     ui::Dataspace dataspace = isColorSpaceAgnostic() && targetDataspace != ui::Dataspace::UNKNOWN
    312             ? targetDataspace
    313             : mCurrentDataSpace;
    314     error = hwcLayer->setDataspace(dataspace);
    315     if (error != HWC2::Error::None) {
    316         ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(), dataspace,
    317               to_string(error).c_str(), static_cast<int32_t>(error));
    318     }
    319 
    320     const HdrMetadata& metadata = getDrawingHdrMetadata();
    321     error = hwcLayer->setPerFrameMetadata(supportedPerFrameMetadata, metadata);
    322     if (error != HWC2::Error::None && error != HWC2::Error::Unsupported) {
    323         ALOGE("[%s] Failed to set hdrMetadata: %s (%d)", mName.string(),
    324               to_string(error).c_str(), static_cast<int32_t>(error));
    325     }
    326 
    327     error = hwcLayer->setColorTransform(getColorTransform());
    328     if (error == HWC2::Error::Unsupported) {
    329         // If per layer color transform is not supported, we use GPU composition.
    330         setCompositionType(displayDevice, Hwc2::IComposerClient::Composition::CLIENT);
    331     } else if (error != HWC2::Error::None) {
    332         ALOGE("[%s] Failed to setColorTransform: %s (%d)", mName.string(),
    333                 to_string(error).c_str(), static_cast<int32_t>(error));
    334     }
    335     layerCompositionState.dataspace = mCurrentDataSpace;
    336     layerCompositionState.colorTransform = getColorTransform();
    337     layerCompositionState.hdrMetadata = metadata;
    338 
    339     setHwcLayerBuffer(displayDevice);
    340 }
    341 
    342 bool BufferLayer::onPreComposition(nsecs_t refreshStartTime) {
    343     if (mBufferLatched) {
    344         Mutex::Autolock lock(mFrameEventHistoryMutex);
    345         mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
    346     }
    347     mRefreshPending = false;
    348     return hasReadyFrame();
    349 }
    350 
    351 bool BufferLayer::onPostComposition(const std::optional<DisplayId>& displayId,
    352                                     const std::shared_ptr<FenceTime>& glDoneFence,
    353                                     const std::shared_ptr<FenceTime>& presentFence,
    354                                     const CompositorTiming& compositorTiming) {
    355     // mFrameLatencyNeeded is true when a new frame was latched for the
    356     // composition.
    357     if (!mFrameLatencyNeeded) return false;
    358 
    359     // Update mFrameEventHistory.
    360     {
    361         Mutex::Autolock lock(mFrameEventHistoryMutex);
    362         mFrameEventHistory.addPostComposition(mCurrentFrameNumber, glDoneFence, presentFence,
    363                                               compositorTiming);
    364     }
    365 
    366     // Update mFrameTracker.
    367     nsecs_t desiredPresentTime = getDesiredPresentTime();
    368     mFrameTracker.setDesiredPresentTime(desiredPresentTime);
    369 
    370     const int32_t layerID = getSequence();
    371     mFlinger->mTimeStats->setDesiredTime(layerID, mCurrentFrameNumber, desiredPresentTime);
    372 
    373     std::shared_ptr<FenceTime> frameReadyFence = getCurrentFenceTime();
    374     if (frameReadyFence->isValid()) {
    375         mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
    376     } else {
    377         // There was no fence for this frame, so assume that it was ready
    378         // to be presented at the desired present time.
    379         mFrameTracker.setFrameReadyTime(desiredPresentTime);
    380     }
    381 
    382     if (presentFence->isValid()) {
    383         mFlinger->mTimeStats->setPresentFence(layerID, mCurrentFrameNumber, presentFence);
    384         mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
    385     } else if (displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
    386         // The HWC doesn't support present fences, so use the refresh
    387         // timestamp instead.
    388         const nsecs_t actualPresentTime = mFlinger->getHwComposer().getRefreshTimestamp(*displayId);
    389         mFlinger->mTimeStats->setPresentTime(layerID, mCurrentFrameNumber, actualPresentTime);
    390         mFrameTracker.setActualPresentTime(actualPresentTime);
    391     }
    392 
    393     mFrameTracker.advanceFrame();
    394     mFrameLatencyNeeded = false;
    395     return true;
    396 }
    397 
    398 bool BufferLayer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
    399     ATRACE_CALL();
    400 
    401     bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
    402 
    403     if (refreshRequired) {
    404         return refreshRequired;
    405     }
    406 
    407     if (!hasReadyFrame()) {
    408         return false;
    409     }
    410 
    411     // if we've already called updateTexImage() without going through
    412     // a composition step, we have to skip this layer at this point
    413     // because we cannot call updateTeximage() without a corresponding
    414     // compositionComplete() call.
    415     // we'll trigger an update in onPreComposition().
    416     if (mRefreshPending) {
    417         return false;
    418     }
    419 
    420     // If the head buffer's acquire fence hasn't signaled yet, return and
    421     // try again later
    422     if (!fenceHasSignaled()) {
    423         ATRACE_NAME("!fenceHasSignaled()");
    424         mFlinger->signalLayerUpdate();
    425         return false;
    426     }
    427 
    428     // Capture the old state of the layer for comparisons later
    429     const State& s(getDrawingState());
    430     const bool oldOpacity = isOpaque(s);
    431     sp<GraphicBuffer> oldBuffer = mActiveBuffer;
    432 
    433     if (!allTransactionsSignaled()) {
    434         mFlinger->setTransactionFlags(eTraversalNeeded);
    435         return false;
    436     }
    437 
    438     status_t err = updateTexImage(recomputeVisibleRegions, latchTime);
    439     if (err != NO_ERROR) {
    440         return false;
    441     }
    442 
    443     err = updateActiveBuffer();
    444     if (err != NO_ERROR) {
    445         return false;
    446     }
    447 
    448     mBufferLatched = true;
    449 
    450     err = updateFrameNumber(latchTime);
    451     if (err != NO_ERROR) {
    452         return false;
    453     }
    454 
    455     mRefreshPending = true;
    456     mFrameLatencyNeeded = true;
    457     if (oldBuffer == nullptr) {
    458         // the first time we receive a buffer, we need to trigger a
    459         // geometry invalidation.
    460         recomputeVisibleRegions = true;
    461     }
    462 
    463     ui::Dataspace dataSpace = getDrawingDataSpace();
    464     // translate legacy dataspaces to modern dataspaces
    465     switch (dataSpace) {
    466         case ui::Dataspace::SRGB:
    467             dataSpace = ui::Dataspace::V0_SRGB;
    468             break;
    469         case ui::Dataspace::SRGB_LINEAR:
    470             dataSpace = ui::Dataspace::V0_SRGB_LINEAR;
    471             break;
    472         case ui::Dataspace::JFIF:
    473             dataSpace = ui::Dataspace::V0_JFIF;
    474             break;
    475         case ui::Dataspace::BT601_625:
    476             dataSpace = ui::Dataspace::V0_BT601_625;
    477             break;
    478         case ui::Dataspace::BT601_525:
    479             dataSpace = ui::Dataspace::V0_BT601_525;
    480             break;
    481         case ui::Dataspace::BT709:
    482             dataSpace = ui::Dataspace::V0_BT709;
    483             break;
    484         default:
    485             break;
    486     }
    487     mCurrentDataSpace = dataSpace;
    488 
    489     Rect crop(getDrawingCrop());
    490     const uint32_t transform(getDrawingTransform());
    491     const uint32_t scalingMode(getDrawingScalingMode());
    492     const bool transformToDisplayInverse(getTransformToDisplayInverse());
    493     if ((crop != mCurrentCrop) || (transform != mCurrentTransform) ||
    494         (scalingMode != mCurrentScalingMode) ||
    495         (transformToDisplayInverse != mTransformToDisplayInverse)) {
    496         mCurrentCrop = crop;
    497         mCurrentTransform = transform;
    498         mCurrentScalingMode = scalingMode;
    499         mTransformToDisplayInverse = transformToDisplayInverse;
    500         recomputeVisibleRegions = true;
    501     }
    502 
    503     if (oldBuffer != nullptr) {
    504         uint32_t bufWidth = mActiveBuffer->getWidth();
    505         uint32_t bufHeight = mActiveBuffer->getHeight();
    506         if (bufWidth != uint32_t(oldBuffer->width) || bufHeight != uint32_t(oldBuffer->height)) {
    507             recomputeVisibleRegions = true;
    508         }
    509     }
    510 
    511     if (oldOpacity != isOpaque(s)) {
    512         recomputeVisibleRegions = true;
    513     }
    514 
    515     // Remove any sync points corresponding to the buffer which was just
    516     // latched
    517     {
    518         Mutex::Autolock lock(mLocalSyncPointMutex);
    519         auto point = mLocalSyncPoints.begin();
    520         while (point != mLocalSyncPoints.end()) {
    521             if (!(*point)->frameIsAvailable() || !(*point)->transactionIsApplied()) {
    522                 // This sync point must have been added since we started
    523                 // latching. Don't drop it yet.
    524                 ++point;
    525                 continue;
    526             }
    527 
    528             if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
    529                 std::stringstream ss;
    530                 ss << "Dropping sync point " << (*point)->getFrameNumber();
    531                 ATRACE_NAME(ss.str().c_str());
    532                 point = mLocalSyncPoints.erase(point);
    533             } else {
    534                 ++point;
    535             }
    536         }
    537     }
    538 
    539     return true;
    540 }
    541 
    542 // transaction
    543 void BufferLayer::notifyAvailableFrames() {
    544     const auto headFrameNumber = getHeadFrameNumber();
    545     const bool headFenceSignaled = fenceHasSignaled();
    546     const bool presentTimeIsCurrent = framePresentTimeIsCurrent();
    547     Mutex::Autolock lock(mLocalSyncPointMutex);
    548     for (auto& point : mLocalSyncPoints) {
    549         if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled &&
    550             presentTimeIsCurrent) {
    551             point->setFrameAvailable();
    552             sp<Layer> requestedSyncLayer = point->getRequestedSyncLayer();
    553             if (requestedSyncLayer) {
    554                 // Need to update the transaction flag to ensure the layer's pending transaction
    555                 // gets applied.
    556                 requestedSyncLayer->setTransactionFlags(eTransactionNeeded);
    557             }
    558         }
    559     }
    560 }
    561 
    562 bool BufferLayer::hasReadyFrame() const {
    563     return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
    564 }
    565 
    566 uint32_t BufferLayer::getEffectiveScalingMode() const {
    567     if (mOverrideScalingMode >= 0) {
    568         return mOverrideScalingMode;
    569     }
    570 
    571     return mCurrentScalingMode;
    572 }
    573 
    574 bool BufferLayer::isProtected() const {
    575     const sp<GraphicBuffer>& buffer(mActiveBuffer);
    576     return (buffer != 0) && (buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
    577 }
    578 
    579 bool BufferLayer::latchUnsignaledBuffers() {
    580     static bool propertyLoaded = false;
    581     static bool latch = false;
    582     static std::mutex mutex;
    583     std::lock_guard<std::mutex> lock(mutex);
    584     if (!propertyLoaded) {
    585         char value[PROPERTY_VALUE_MAX] = {};
    586         property_get("debug.sf.latch_unsignaled", value, "0");
    587         latch = atoi(value);
    588         propertyLoaded = true;
    589     }
    590     return latch;
    591 }
    592 
    593 // h/w composer set-up
    594 bool BufferLayer::allTransactionsSignaled() {
    595     auto headFrameNumber = getHeadFrameNumber();
    596     bool matchingFramesFound = false;
    597     bool allTransactionsApplied = true;
    598     Mutex::Autolock lock(mLocalSyncPointMutex);
    599 
    600     for (auto& point : mLocalSyncPoints) {
    601         if (point->getFrameNumber() > headFrameNumber) {
    602             break;
    603         }
    604         matchingFramesFound = true;
    605 
    606         if (!point->frameIsAvailable()) {
    607             // We haven't notified the remote layer that the frame for
    608             // this point is available yet. Notify it now, and then
    609             // abort this attempt to latch.
    610             point->setFrameAvailable();
    611             allTransactionsApplied = false;
    612             break;
    613         }
    614 
    615         allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
    616     }
    617     return !matchingFramesFound || allTransactionsApplied;
    618 }
    619 
    620 // As documented in libhardware header, formats in the range
    621 // 0x100 - 0x1FF are specific to the HAL implementation, and
    622 // are known to have no alpha channel
    623 // TODO: move definition for device-specific range into
    624 // hardware.h, instead of using hard-coded values here.
    625 #define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
    626 
    627 bool BufferLayer::getOpacityForFormat(uint32_t format) {
    628     if (HARDWARE_IS_DEVICE_FORMAT(format)) {
    629         return true;
    630     }
    631     switch (format) {
    632         case HAL_PIXEL_FORMAT_RGBA_8888:
    633         case HAL_PIXEL_FORMAT_BGRA_8888:
    634         case HAL_PIXEL_FORMAT_RGBA_FP16:
    635         case HAL_PIXEL_FORMAT_RGBA_1010102:
    636             return false;
    637     }
    638     // in all other case, we have no blending (also for unknown formats)
    639     return true;
    640 }
    641 
    642 bool BufferLayer::needsFiltering(const sp<const DisplayDevice>& displayDevice) const {
    643     // If we are not capturing based on the state of a known display device, we
    644     // only return mNeedsFiltering
    645     if (displayDevice == nullptr) {
    646         return mNeedsFiltering;
    647     }
    648 
    649     const auto outputLayer = findOutputLayerForDisplay(displayDevice);
    650     if (outputLayer == nullptr) {
    651         return mNeedsFiltering;
    652     }
    653 
    654     const auto& compositionState = outputLayer->getState();
    655     const auto displayFrame = compositionState.displayFrame;
    656     const auto sourceCrop = compositionState.sourceCrop;
    657     return mNeedsFiltering || sourceCrop.getHeight() != displayFrame.getHeight() ||
    658             sourceCrop.getWidth() != displayFrame.getWidth();
    659 }
    660 
    661 uint64_t BufferLayer::getHeadFrameNumber() const {
    662     if (hasFrameUpdate()) {
    663         return getFrameNumber();
    664     } else {
    665         return mCurrentFrameNumber;
    666     }
    667 }
    668 
    669 Rect BufferLayer::getBufferSize(const State& s) const {
    670     // If we have a sideband stream, or we are scaling the buffer then return the layer size since
    671     // we cannot determine the buffer size.
    672     if ((s.sidebandStream != nullptr) ||
    673         (getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE)) {
    674         return Rect(getActiveWidth(s), getActiveHeight(s));
    675     }
    676 
    677     if (mActiveBuffer == nullptr) {
    678         return Rect::INVALID_RECT;
    679     }
    680 
    681     uint32_t bufWidth = mActiveBuffer->getWidth();
    682     uint32_t bufHeight = mActiveBuffer->getHeight();
    683 
    684     // Undo any transformations on the buffer and return the result.
    685     if (mCurrentTransform & ui::Transform::ROT_90) {
    686         std::swap(bufWidth, bufHeight);
    687     }
    688 
    689     if (getTransformToDisplayInverse()) {
    690         uint32_t invTransform = DisplayDevice::getPrimaryDisplayOrientationTransform();
    691         if (invTransform & ui::Transform::ROT_90) {
    692             std::swap(bufWidth, bufHeight);
    693         }
    694     }
    695 
    696     return Rect(bufWidth, bufHeight);
    697 }
    698 
    699 std::shared_ptr<compositionengine::Layer> BufferLayer::getCompositionLayer() const {
    700     return mCompositionLayer;
    701 }
    702 
    703 FloatRect BufferLayer::computeSourceBounds(const FloatRect& parentBounds) const {
    704     const State& s(getDrawingState());
    705 
    706     // If we have a sideband stream, or we are scaling the buffer then return the layer size since
    707     // we cannot determine the buffer size.
    708     if ((s.sidebandStream != nullptr) ||
    709         (getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE)) {
    710         return FloatRect(0, 0, getActiveWidth(s), getActiveHeight(s));
    711     }
    712 
    713     if (mActiveBuffer == nullptr) {
    714         return parentBounds;
    715     }
    716 
    717     uint32_t bufWidth = mActiveBuffer->getWidth();
    718     uint32_t bufHeight = mActiveBuffer->getHeight();
    719 
    720     // Undo any transformations on the buffer and return the result.
    721     if (mCurrentTransform & ui::Transform::ROT_90) {
    722         std::swap(bufWidth, bufHeight);
    723     }
    724 
    725     if (getTransformToDisplayInverse()) {
    726         uint32_t invTransform = DisplayDevice::getPrimaryDisplayOrientationTransform();
    727         if (invTransform & ui::Transform::ROT_90) {
    728             std::swap(bufWidth, bufHeight);
    729         }
    730     }
    731 
    732     return FloatRect(0, 0, bufWidth, bufHeight);
    733 }
    734 
    735 } // namespace android
    736 
    737 #if defined(__gl_h_)
    738 #error "don't include gl/gl.h in this file"
    739 #endif
    740 
    741 #if defined(__gl2_h_)
    742 #error "don't include gl2/gl2.h in this file"
    743 #endif
    744