Layer.cpp revision 3bfd2e196d248536207bf1e0acfe86bd4d786d1d
1/*
2 * Copyright (C) 2007 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 "Layer"
20#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
22#include <stdlib.h>
23#include <stdint.h>
24#include <sys/types.h>
25#include <math.h>
26
27#include <cutils/compiler.h>
28#include <cutils/native_handle.h>
29#include <cutils/properties.h>
30
31#include <utils/Errors.h>
32#include <utils/Log.h>
33#include <utils/NativeHandle.h>
34#include <utils/StopWatch.h>
35#include <utils/Trace.h>
36
37#include <ui/GraphicBuffer.h>
38#include <ui/PixelFormat.h>
39
40#include <gui/BufferItem.h>
41#include <gui/Surface.h>
42
43#include "clz.h"
44#include "Colorizer.h"
45#include "DisplayDevice.h"
46#include "Layer.h"
47#include "MonitoredProducer.h"
48#include "SurfaceFlinger.h"
49
50#include "DisplayHardware/HWComposer.h"
51
52#include "RenderEngine/RenderEngine.h"
53
54#define DEBUG_RESIZE    0
55
56namespace android {
57
58// ---------------------------------------------------------------------------
59
60int32_t Layer::sSequence = 1;
61
62Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
63        const String8& name, uint32_t w, uint32_t h, uint32_t flags)
64    :   contentDirty(false),
65        sequence(uint32_t(android_atomic_inc(&sSequence))),
66        mFlinger(flinger),
67        mTextureName(-1U),
68        mPremultipliedAlpha(true),
69        mName("unnamed"),
70        mFormat(PIXEL_FORMAT_NONE),
71        mTransactionFlags(0),
72        mPendingStateMutex(),
73        mPendingStates(),
74        mQueuedFrames(0),
75        mSidebandStreamChanged(false),
76        mCurrentTransform(0),
77        mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
78        mOverrideScalingMode(-1),
79        mCurrentOpacity(true),
80        mCurrentFrameNumber(0),
81        mRefreshPending(false),
82        mFrameLatencyNeeded(false),
83        mFiltering(false),
84        mNeedsFiltering(false),
85        mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
86#ifndef USE_HWC2
87        mIsGlesComposition(false),
88#endif
89        mProtectedByApp(false),
90        mHasSurface(false),
91        mClientRef(client),
92        mPotentialCursor(false),
93        mQueueItemLock(),
94        mQueueItemCondition(),
95        mQueueItems(),
96        mLastFrameNumberReceived(0),
97        mUpdateTexImageFailed(false),
98        mAutoRefresh(false)
99{
100#ifdef USE_HWC2
101    ALOGV("Creating Layer %s", name.string());
102#endif
103
104    mCurrentCrop.makeInvalid();
105    mFlinger->getRenderEngine().genTextures(1, &mTextureName);
106    mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
107
108    uint32_t layerFlags = 0;
109    if (flags & ISurfaceComposerClient::eHidden)
110        layerFlags |= layer_state_t::eLayerHidden;
111    if (flags & ISurfaceComposerClient::eOpaque)
112        layerFlags |= layer_state_t::eLayerOpaque;
113    if (flags & ISurfaceComposerClient::eSecure)
114        layerFlags |= layer_state_t::eLayerSecure;
115
116    if (flags & ISurfaceComposerClient::eNonPremultiplied)
117        mPremultipliedAlpha = false;
118
119    mName = name;
120
121    mCurrentState.active.w = w;
122    mCurrentState.active.h = h;
123    mCurrentState.active.transform.set(0, 0);
124    mCurrentState.crop.makeInvalid();
125    mCurrentState.finalCrop.makeInvalid();
126    mCurrentState.z = 0;
127#ifdef USE_HWC2
128    mCurrentState.alpha = 1.0f;
129#else
130    mCurrentState.alpha = 0xFF;
131#endif
132    mCurrentState.layerStack = 0;
133    mCurrentState.flags = layerFlags;
134    mCurrentState.sequence = 0;
135    mCurrentState.requested = mCurrentState.active;
136
137    // drawing state & current state are identical
138    mDrawingState = mCurrentState;
139
140#ifdef USE_HWC2
141    const auto& hwc = flinger->getHwComposer();
142    const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
143    nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
144#else
145    nsecs_t displayPeriod =
146            flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
147#endif
148    mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
149}
150
151void Layer::onFirstRef() {
152    // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
153    sp<IGraphicBufferProducer> producer;
154    sp<IGraphicBufferConsumer> consumer;
155    BufferQueue::createBufferQueue(&producer, &consumer);
156    mProducer = new MonitoredProducer(producer, mFlinger);
157    mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName);
158    mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
159    mSurfaceFlingerConsumer->setContentsChangedListener(this);
160    mSurfaceFlingerConsumer->setName(mName);
161
162#ifndef TARGET_DISABLE_TRIPLE_BUFFERING
163    mProducer->setMaxDequeuedBufferCount(2);
164#endif
165
166    const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
167    updateTransformHint(hw);
168}
169
170Layer::~Layer() {
171  sp<Client> c(mClientRef.promote());
172    if (c != 0) {
173        c->detachLayer(this);
174    }
175
176    for (auto& point : mRemoteSyncPoints) {
177        point->setTransactionApplied();
178    }
179    for (auto& point : mLocalSyncPoints) {
180        point->setFrameAvailable();
181    }
182    mFlinger->deleteTextureAsync(mTextureName);
183    mFrameTracker.logAndResetStats(mName);
184}
185
186// ---------------------------------------------------------------------------
187// callbacks
188// ---------------------------------------------------------------------------
189
190#ifdef USE_HWC2
191void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
192    if (mHwcLayers.empty()) {
193        return;
194    }
195    mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
196}
197#else
198void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
199        HWComposer::HWCLayerInterface* layer) {
200    if (layer) {
201        layer->onDisplayed();
202        mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
203    }
204}
205#endif
206
207void Layer::onFrameAvailable(const BufferItem& item) {
208    // Add this buffer from our internal queue tracker
209    { // Autolock scope
210        Mutex::Autolock lock(mQueueItemLock);
211
212        // Reset the frame number tracker when we receive the first buffer after
213        // a frame number reset
214        if (item.mFrameNumber == 1) {
215            mLastFrameNumberReceived = 0;
216        }
217
218        // Ensure that callbacks are handled in order
219        while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
220            status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
221                    ms2ns(500));
222            if (result != NO_ERROR) {
223                ALOGE("[%s] Timed out waiting on callback", mName.string());
224            }
225        }
226
227        mQueueItems.push_back(item);
228        android_atomic_inc(&mQueuedFrames);
229
230        // Wake up any pending callbacks
231        mLastFrameNumberReceived = item.mFrameNumber;
232        mQueueItemCondition.broadcast();
233    }
234
235    mFlinger->signalLayerUpdate();
236}
237
238void Layer::onFrameReplaced(const BufferItem& item) {
239    { // Autolock scope
240        Mutex::Autolock lock(mQueueItemLock);
241
242        // Ensure that callbacks are handled in order
243        while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
244            status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
245                    ms2ns(500));
246            if (result != NO_ERROR) {
247                ALOGE("[%s] Timed out waiting on callback", mName.string());
248            }
249        }
250
251        if (mQueueItems.empty()) {
252            ALOGE("Can't replace a frame on an empty queue");
253            return;
254        }
255        mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
256
257        // Wake up any pending callbacks
258        mLastFrameNumberReceived = item.mFrameNumber;
259        mQueueItemCondition.broadcast();
260    }
261}
262
263void Layer::onSidebandStreamChanged() {
264    if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
265        // mSidebandStreamChanged was false
266        mFlinger->signalLayerUpdate();
267    }
268}
269
270// called with SurfaceFlinger::mStateLock from the drawing thread after
271// the layer has been remove from the current state list (and just before
272// it's removed from the drawing state list)
273void Layer::onRemoved() {
274    mSurfaceFlingerConsumer->abandon();
275}
276
277// ---------------------------------------------------------------------------
278// set-up
279// ---------------------------------------------------------------------------
280
281const String8& Layer::getName() const {
282    return mName;
283}
284
285status_t Layer::setBuffers( uint32_t w, uint32_t h,
286                            PixelFormat format, uint32_t flags)
287{
288    uint32_t const maxSurfaceDims = min(
289            mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
290
291    // never allow a surface larger than what our underlying GL implementation
292    // can handle.
293    if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
294        ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
295        return BAD_VALUE;
296    }
297
298    mFormat = format;
299
300    mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
301    mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
302    mCurrentOpacity = getOpacityForFormat(format);
303
304    mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
305    mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
306    mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
307
308    return NO_ERROR;
309}
310
311/*
312 * The layer handle is just a BBinder object passed to the client
313 * (remote process) -- we don't keep any reference on our side such that
314 * the dtor is called when the remote side let go of its reference.
315 *
316 * LayerCleaner ensures that mFlinger->onLayerDestroyed() is called for
317 * this layer when the handle is destroyed.
318 */
319class Layer::Handle : public BBinder, public LayerCleaner {
320    public:
321        Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer)
322            : LayerCleaner(flinger, layer), owner(layer) {}
323
324        wp<Layer> owner;
325};
326
327sp<IBinder> Layer::getHandle() {
328    Mutex::Autolock _l(mLock);
329
330    LOG_ALWAYS_FATAL_IF(mHasSurface,
331            "Layer::getHandle() has already been called");
332
333    mHasSurface = true;
334
335    return new Handle(mFlinger, this);
336}
337
338sp<IGraphicBufferProducer> Layer::getProducer() const {
339    return mProducer;
340}
341
342// ---------------------------------------------------------------------------
343// h/w composer set-up
344// ---------------------------------------------------------------------------
345
346Rect Layer::getContentCrop() const {
347    // this is the crop rectangle that applies to the buffer
348    // itself (as opposed to the window)
349    Rect crop;
350    if (!mCurrentCrop.isEmpty()) {
351        // if the buffer crop is defined, we use that
352        crop = mCurrentCrop;
353    } else if (mActiveBuffer != NULL) {
354        // otherwise we use the whole buffer
355        crop = mActiveBuffer->getBounds();
356    } else {
357        // if we don't have a buffer yet, we use an empty/invalid crop
358        crop.makeInvalid();
359    }
360    return crop;
361}
362
363static Rect reduce(const Rect& win, const Region& exclude) {
364    if (CC_LIKELY(exclude.isEmpty())) {
365        return win;
366    }
367    if (exclude.isRect()) {
368        return win.reduce(exclude.getBounds());
369    }
370    return Region(win).subtract(exclude).getBounds();
371}
372
373Rect Layer::computeBounds() const {
374    const Layer::State& s(getDrawingState());
375    return computeBounds(s.activeTransparentRegion);
376}
377
378Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
379    const Layer::State& s(getDrawingState());
380    Rect win(s.active.w, s.active.h);
381
382    if (!s.crop.isEmpty()) {
383        win.intersect(s.crop, &win);
384    }
385    // subtract the transparent region and snap to the bounds
386    return reduce(win, activeTransparentRegion);
387}
388
389FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
390    // the content crop is the area of the content that gets scaled to the
391    // layer's size.
392    FloatRect crop(getContentCrop());
393
394    // the crop is the area of the window that gets cropped, but not
395    // scaled in any ways.
396    const State& s(getDrawingState());
397
398    // apply the projection's clipping to the window crop in
399    // layerstack space, and convert-back to layer space.
400    // if there are no window scaling involved, this operation will map to full
401    // pixels in the buffer.
402    // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
403    // a viewport clipping and a window transform. we should use floating point to fix this.
404
405    Rect activeCrop(s.active.w, s.active.h);
406    if (!s.crop.isEmpty()) {
407        activeCrop = s.crop;
408    }
409
410    activeCrop = s.active.transform.transform(activeCrop);
411    if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
412        activeCrop.clear();
413    }
414    if (!s.finalCrop.isEmpty()) {
415        if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
416            activeCrop.clear();
417        }
418    }
419    activeCrop = s.active.transform.inverse().transform(activeCrop);
420
421    // This needs to be here as transform.transform(Rect) computes the
422    // transformed rect and then takes the bounding box of the result before
423    // returning. This means
424    // transform.inverse().transform(transform.transform(Rect)) != Rect
425    // in which case we need to make sure the final rect is clipped to the
426    // display bounds.
427    if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
428        activeCrop.clear();
429    }
430
431    // subtract the transparent region and snap to the bounds
432    activeCrop = reduce(activeCrop, s.activeTransparentRegion);
433
434    // Transform the window crop to match the buffer coordinate system,
435    // which means using the inverse of the current transform set on the
436    // SurfaceFlingerConsumer.
437    uint32_t invTransform = mCurrentTransform;
438    if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
439        /*
440         * the code below applies the primary display's inverse transform to the
441         * buffer
442         */
443        uint32_t invTransformOrient =
444                DisplayDevice::getPrimaryDisplayOrientationTransform();
445        // calculate the inverse transform
446        if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
447            invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
448                    NATIVE_WINDOW_TRANSFORM_FLIP_H;
449        }
450        // and apply to the current transform
451        invTransform = (Transform(invTransformOrient) * Transform(invTransform))
452                .getOrientation();
453    }
454
455    int winWidth = s.active.w;
456    int winHeight = s.active.h;
457    if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
458        // If the activeCrop has been rotate the ends are rotated but not
459        // the space itself so when transforming ends back we can't rely on
460        // a modification of the axes of rotation. To account for this we
461        // need to reorient the inverse rotation in terms of the current
462        // axes of rotation.
463        bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
464        bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
465        if (is_h_flipped == is_v_flipped) {
466            invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
467                    NATIVE_WINDOW_TRANSFORM_FLIP_H;
468        }
469        winWidth = s.active.h;
470        winHeight = s.active.w;
471    }
472    const Rect winCrop = activeCrop.transform(
473            invTransform, s.active.w, s.active.h);
474
475    // below, crop is intersected with winCrop expressed in crop's coordinate space
476    float xScale = crop.getWidth()  / float(winWidth);
477    float yScale = crop.getHeight() / float(winHeight);
478
479    float insetL = winCrop.left                 * xScale;
480    float insetT = winCrop.top                  * yScale;
481    float insetR = (winWidth - winCrop.right )  * xScale;
482    float insetB = (winHeight - winCrop.bottom) * yScale;
483
484    crop.left   += insetL;
485    crop.top    += insetT;
486    crop.right  -= insetR;
487    crop.bottom -= insetB;
488
489    return crop;
490}
491
492#ifdef USE_HWC2
493void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice)
494#else
495void Layer::setGeometry(
496    const sp<const DisplayDevice>& hw,
497        HWComposer::HWCLayerInterface& layer)
498#endif
499{
500#ifdef USE_HWC2
501    const auto hwcId = displayDevice->getHwcDisplayId();
502    auto& hwcInfo = mHwcLayers[hwcId];
503#else
504    layer.setDefaultState();
505#endif
506
507    // enable this layer
508#ifdef USE_HWC2
509    hwcInfo.forceClientComposition = false;
510
511    if (isSecure() && !displayDevice->isSecure()) {
512        hwcInfo.forceClientComposition = true;
513    }
514
515    auto& hwcLayer = hwcInfo.layer;
516#else
517    layer.setSkip(false);
518
519    if (isSecure() && !hw->isSecure()) {
520        layer.setSkip(true);
521    }
522#endif
523
524    // this gives us only the "orientation" component of the transform
525    const State& s(getDrawingState());
526#ifdef USE_HWC2
527    if (!isOpaque(s) || s.alpha != 1.0f) {
528        auto blendMode = mPremultipliedAlpha ?
529                HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
530        auto error = hwcLayer->setBlendMode(blendMode);
531        ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
532                " %s (%d)", mName.string(), to_string(blendMode).c_str(),
533                to_string(error).c_str(), static_cast<int32_t>(error));
534    }
535#else
536    if (!isOpaque(s) || s.alpha != 0xFF) {
537        layer.setBlending(mPremultipliedAlpha ?
538                HWC_BLENDING_PREMULT :
539                HWC_BLENDING_COVERAGE);
540    }
541#endif
542
543    // apply the layer's transform, followed by the display's global transform
544    // here we're guaranteed that the layer's transform preserves rects
545    Region activeTransparentRegion(s.activeTransparentRegion);
546    if (!s.crop.isEmpty()) {
547        Rect activeCrop(s.crop);
548        activeCrop = s.active.transform.transform(activeCrop);
549#ifdef USE_HWC2
550        if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
551#else
552        if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
553#endif
554            activeCrop.clear();
555        }
556        activeCrop = s.active.transform.inverse().transform(activeCrop);
557        // This needs to be here as transform.transform(Rect) computes the
558        // transformed rect and then takes the bounding box of the result before
559        // returning. This means
560        // transform.inverse().transform(transform.transform(Rect)) != Rect
561        // in which case we need to make sure the final rect is clipped to the
562        // display bounds.
563        if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
564            activeCrop.clear();
565        }
566        // mark regions outside the crop as transparent
567        activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
568        activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
569                s.active.w, s.active.h));
570        activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
571                activeCrop.left, activeCrop.bottom));
572        activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
573                s.active.w, activeCrop.bottom));
574    }
575    Rect frame(s.active.transform.transform(computeBounds(activeTransparentRegion)));
576    if (!s.finalCrop.isEmpty()) {
577        if(!frame.intersect(s.finalCrop, &frame)) {
578            frame.clear();
579        }
580    }
581#ifdef USE_HWC2
582    if (!frame.intersect(displayDevice->getViewport(), &frame)) {
583        frame.clear();
584    }
585    const Transform& tr(displayDevice->getTransform());
586    Rect transformedFrame = tr.transform(frame);
587    auto error = hwcLayer->setDisplayFrame(transformedFrame);
588    ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set display frame "
589            "[%d, %d, %d, %d]: %s (%d)", mName.string(), transformedFrame.left,
590            transformedFrame.top, transformedFrame.right,
591            transformedFrame.bottom, to_string(error).c_str(),
592            static_cast<int32_t>(error));
593
594    FloatRect sourceCrop = computeCrop(displayDevice);
595    error = hwcLayer->setSourceCrop(sourceCrop);
596    ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set source crop "
597            "[%.3f, %.3f, %.3f, %.3f]: %s (%d)", mName.string(),
598            sourceCrop.left, sourceCrop.top, sourceCrop.right,
599            sourceCrop.bottom, to_string(error).c_str(),
600            static_cast<int32_t>(error));
601
602    error = hwcLayer->setPlaneAlpha(s.alpha);
603    ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
604            "%s (%d)", mName.string(), s.alpha, to_string(error).c_str(),
605            static_cast<int32_t>(error));
606
607    error = hwcLayer->setZOrder(s.z);
608    ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
609            mName.string(), s.z, to_string(error).c_str(),
610            static_cast<int32_t>(error));
611#else
612    if (!frame.intersect(hw->getViewport(), &frame)) {
613        frame.clear();
614    }
615    const Transform& tr(hw->getTransform());
616    layer.setFrame(tr.transform(frame));
617    layer.setCrop(computeCrop(hw));
618    layer.setPlaneAlpha(s.alpha);
619#endif
620
621    /*
622     * Transformations are applied in this order:
623     * 1) buffer orientation/flip/mirror
624     * 2) state transformation (window manager)
625     * 3) layer orientation (screen orientation)
626     * (NOTE: the matrices are multiplied in reverse order)
627     */
628
629    const Transform bufferOrientation(mCurrentTransform);
630    Transform transform(tr * s.active.transform * bufferOrientation);
631
632    if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
633        /*
634         * the code below applies the primary display's inverse transform to the
635         * buffer
636         */
637        uint32_t invTransform =
638                DisplayDevice::getPrimaryDisplayOrientationTransform();
639        // calculate the inverse transform
640        if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
641            invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
642                    NATIVE_WINDOW_TRANSFORM_FLIP_H;
643        }
644        // and apply to the current transform
645        transform = Transform(invTransform) * transform;
646    }
647
648    // this gives us only the "orientation" component of the transform
649    const uint32_t orientation = transform.getOrientation();
650#ifdef USE_HWC2
651    if (orientation & Transform::ROT_INVALID) {
652        // we can only handle simple transformation
653        hwcInfo.forceClientComposition = true;
654    } else {
655        auto transform = static_cast<HWC2::Transform>(orientation);
656        auto error = hwcLayer->setTransform(transform);
657        ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
658                "%s (%d)", mName.string(), to_string(transform).c_str(),
659                to_string(error).c_str(), static_cast<int32_t>(error));
660    }
661#else
662    if (orientation & Transform::ROT_INVALID) {
663        // we can only handle simple transformation
664        layer.setSkip(true);
665    } else {
666        layer.setTransform(orientation);
667    }
668#endif
669}
670
671#ifdef USE_HWC2
672void Layer::forceClientComposition(int32_t hwcId) {
673    if (mHwcLayers.count(hwcId) == 0) {
674        ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
675        return;
676    }
677
678    mHwcLayers[hwcId].forceClientComposition = true;
679}
680#endif
681
682#ifdef USE_HWC2
683void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
684    // Apply this display's projection's viewport to the visible region
685    // before giving it to the HWC HAL.
686    const Transform& tr = displayDevice->getTransform();
687    const auto& viewport = displayDevice->getViewport();
688    Region visible = tr.transform(visibleRegion.intersect(viewport));
689    auto hwcId = displayDevice->getHwcDisplayId();
690    auto& hwcLayer = mHwcLayers[hwcId].layer;
691    auto error = hwcLayer->setVisibleRegion(visible);
692    if (error != HWC2::Error::None) {
693        ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
694                to_string(error).c_str(), static_cast<int32_t>(error));
695        visible.dump(LOG_TAG);
696    }
697
698    error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
699    if (error != HWC2::Error::None) {
700        ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
701                to_string(error).c_str(), static_cast<int32_t>(error));
702        surfaceDamageRegion.dump(LOG_TAG);
703    }
704
705    // Sideband layers
706    if (mSidebandStream.get()) {
707        setCompositionType(hwcId, HWC2::Composition::Sideband);
708        ALOGV("[%s] Requesting Sideband composition", mName.string());
709        error = hwcLayer->setSidebandStream(mSidebandStream->handle());
710        if (error != HWC2::Error::None) {
711            ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
712                    mName.string(), mSidebandStream->handle(),
713                    to_string(error).c_str(), static_cast<int32_t>(error));
714        }
715        return;
716    }
717
718    // Client or SolidColor layers
719    if (mActiveBuffer == nullptr || mActiveBuffer->handle == nullptr ||
720            mHwcLayers[hwcId].forceClientComposition) {
721        // TODO: This also includes solid color layers, but no API exists to
722        // setup a solid color layer yet
723        ALOGV("[%s] Requesting Client composition", mName.string());
724        setCompositionType(hwcId, HWC2::Composition::Client);
725        error = hwcLayer->setBuffer(nullptr, Fence::NO_FENCE);
726        if (error != HWC2::Error::None) {
727            ALOGE("[%s] Failed to set null buffer: %s (%d)", mName.string(),
728                    to_string(error).c_str(), static_cast<int32_t>(error));
729        }
730        return;
731    }
732
733    // Device or Cursor layers
734    if (mPotentialCursor) {
735        ALOGV("[%s] Requesting Cursor composition", mName.string());
736        setCompositionType(hwcId, HWC2::Composition::Cursor);
737    } else {
738        ALOGV("[%s] Requesting Device composition", mName.string());
739        setCompositionType(hwcId, HWC2::Composition::Device);
740    }
741
742    auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
743    error = hwcLayer->setBuffer(mActiveBuffer->handle, acquireFence);
744    if (error != HWC2::Error::None) {
745        ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
746                mActiveBuffer->handle, to_string(error).c_str(),
747                static_cast<int32_t>(error));
748    }
749}
750#else
751void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
752        HWComposer::HWCLayerInterface& layer) {
753    // we have to set the visible region on every frame because
754    // we currently free it during onLayerDisplayed(), which is called
755    // after HWComposer::commit() -- every frame.
756    // Apply this display's projection's viewport to the visible region
757    // before giving it to the HWC HAL.
758    const Transform& tr = hw->getTransform();
759    Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
760    layer.setVisibleRegionScreen(visible);
761    layer.setSurfaceDamage(surfaceDamageRegion);
762    mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
763
764    if (mSidebandStream.get()) {
765        layer.setSidebandStream(mSidebandStream);
766    } else {
767        // NOTE: buffer can be NULL if the client never drew into this
768        // layer yet, or if we ran out of memory
769        layer.setBuffer(mActiveBuffer);
770    }
771}
772#endif
773
774#ifdef USE_HWC2
775void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
776    auto hwcId = displayDevice->getHwcDisplayId();
777    if (mHwcLayers.count(hwcId) == 0 ||
778            getCompositionType(hwcId) != HWC2::Composition::Cursor) {
779        return;
780    }
781
782    // This gives us only the "orientation" component of the transform
783    const State& s(getCurrentState());
784
785    // Apply the layer's transform, followed by the display's global transform
786    // Here we're guaranteed that the layer's transform preserves rects
787    Rect win(s.active.w, s.active.h);
788    if (!s.crop.isEmpty()) {
789        win.intersect(s.crop, &win);
790    }
791    // Subtract the transparent region and snap to the bounds
792    Rect bounds = reduce(win, s.activeTransparentRegion);
793    Rect frame(s.active.transform.transform(bounds));
794    frame.intersect(displayDevice->getViewport(), &frame);
795    if (!s.finalCrop.isEmpty()) {
796        frame.intersect(s.finalCrop, &frame);
797    }
798    auto& displayTransform(displayDevice->getTransform());
799    auto position = displayTransform.transform(frame);
800
801    auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
802            position.top);
803    ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
804            "to (%d, %d): %s (%d)", mName.string(), position.left,
805            position.top, to_string(error).c_str(),
806            static_cast<int32_t>(error));
807}
808#else
809void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
810        HWComposer::HWCLayerInterface& layer) {
811    int fenceFd = -1;
812
813    // TODO: there is a possible optimization here: we only need to set the
814    // acquire fence the first time a new buffer is acquired on EACH display.
815
816    if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
817        sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
818        if (fence->isValid()) {
819            fenceFd = fence->dup();
820            if (fenceFd == -1) {
821                ALOGW("failed to dup layer fence, skipping sync: %d", errno);
822            }
823        }
824    }
825    layer.setAcquireFenceFd(fenceFd);
826}
827
828Rect Layer::getPosition(
829    const sp<const DisplayDevice>& hw)
830{
831    // this gives us only the "orientation" component of the transform
832    const State& s(getCurrentState());
833
834    // apply the layer's transform, followed by the display's global transform
835    // here we're guaranteed that the layer's transform preserves rects
836    Rect win(s.active.w, s.active.h);
837    if (!s.crop.isEmpty()) {
838        win.intersect(s.crop, &win);
839    }
840    // subtract the transparent region and snap to the bounds
841    Rect bounds = reduce(win, s.activeTransparentRegion);
842    Rect frame(s.active.transform.transform(bounds));
843    frame.intersect(hw->getViewport(), &frame);
844    if (!s.finalCrop.isEmpty()) {
845        frame.intersect(s.finalCrop, &frame);
846    }
847    const Transform& tr(hw->getTransform());
848    return Rect(tr.transform(frame));
849}
850#endif
851
852// ---------------------------------------------------------------------------
853// drawing...
854// ---------------------------------------------------------------------------
855
856void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
857    onDraw(hw, clip, false);
858}
859
860void Layer::draw(const sp<const DisplayDevice>& hw,
861        bool useIdentityTransform) const {
862    onDraw(hw, Region(hw->bounds()), useIdentityTransform);
863}
864
865void Layer::draw(const sp<const DisplayDevice>& hw) const {
866    onDraw(hw, Region(hw->bounds()), false);
867}
868
869void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
870        bool useIdentityTransform) const
871{
872    ATRACE_CALL();
873
874    if (CC_UNLIKELY(mActiveBuffer == 0)) {
875        // the texture has not been created yet, this Layer has
876        // in fact never been drawn into. This happens frequently with
877        // SurfaceView because the WindowManager can't know when the client
878        // has drawn the first time.
879
880        // If there is nothing under us, we paint the screen in black, otherwise
881        // we just skip this update.
882
883        // figure out if there is something below us
884        Region under;
885        const SurfaceFlinger::LayerVector& drawingLayers(
886                mFlinger->mDrawingState.layersSortedByZ);
887        const size_t count = drawingLayers.size();
888        for (size_t i=0 ; i<count ; ++i) {
889            const sp<Layer>& layer(drawingLayers[i]);
890            if (layer.get() == static_cast<Layer const*>(this))
891                break;
892            under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
893        }
894        // if not everything below us is covered, we plug the holes!
895        Region holes(clip.subtract(under));
896        if (!holes.isEmpty()) {
897            clearWithOpenGL(hw, holes, 0, 0, 0, 1);
898        }
899        return;
900    }
901
902    // Bind the current buffer to the GL texture, and wait for it to be
903    // ready for us to draw into.
904    status_t err = mSurfaceFlingerConsumer->bindTextureImage();
905    if (err != NO_ERROR) {
906        ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
907        // Go ahead and draw the buffer anyway; no matter what we do the screen
908        // is probably going to have something visibly wrong.
909    }
910
911    bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
912
913    RenderEngine& engine(mFlinger->getRenderEngine());
914
915    if (!blackOutLayer) {
916        // TODO: we could be more subtle with isFixedSize()
917        const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
918
919        // Query the texture matrix given our current filtering mode.
920        float textureMatrix[16];
921        mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
922        mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
923
924        if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
925
926            /*
927             * the code below applies the primary display's inverse transform to
928             * the texture transform
929             */
930
931            // create a 4x4 transform matrix from the display transform flags
932            const mat4 flipH(-1,0,0,0,  0,1,0,0, 0,0,1,0, 1,0,0,1);
933            const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
934            const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
935
936            mat4 tr;
937            uint32_t transform =
938                    DisplayDevice::getPrimaryDisplayOrientationTransform();
939            if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90)
940                tr = tr * rot90;
941            if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H)
942                tr = tr * flipH;
943            if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V)
944                tr = tr * flipV;
945
946            // calculate the inverse
947            tr = inverse(tr);
948
949            // and finally apply it to the original texture matrix
950            const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
951            memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
952        }
953
954        // Set things up for texturing.
955        mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
956        mTexture.setFiltering(useFiltering);
957        mTexture.setMatrix(textureMatrix);
958
959        engine.setupLayerTexturing(mTexture);
960    } else {
961        engine.setupLayerBlackedOut();
962    }
963    drawWithOpenGL(hw, clip, useIdentityTransform);
964    engine.disableTexturing();
965}
966
967
968void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
969        const Region& /* clip */, float red, float green, float blue,
970        float alpha) const
971{
972    RenderEngine& engine(mFlinger->getRenderEngine());
973    computeGeometry(hw, mMesh, false);
974    engine.setupFillWithColor(red, green, blue, alpha);
975    engine.drawMesh(mMesh);
976}
977
978void Layer::clearWithOpenGL(
979        const sp<const DisplayDevice>& hw, const Region& clip) const {
980    clearWithOpenGL(hw, clip, 0,0,0,0);
981}
982
983void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
984        const Region& /* clip */, bool useIdentityTransform) const {
985    const State& s(getDrawingState());
986
987    computeGeometry(hw, mMesh, useIdentityTransform);
988
989    /*
990     * NOTE: the way we compute the texture coordinates here produces
991     * different results than when we take the HWC path -- in the later case
992     * the "source crop" is rounded to texel boundaries.
993     * This can produce significantly different results when the texture
994     * is scaled by a large amount.
995     *
996     * The GL code below is more logical (imho), and the difference with
997     * HWC is due to a limitation of the HWC API to integers -- a question
998     * is suspend is whether we should ignore this problem or revert to
999     * GL composition when a buffer scaling is applied (maybe with some
1000     * minimal value)? Or, we could make GL behave like HWC -- but this feel
1001     * like more of a hack.
1002     */
1003    Rect win(computeBounds());
1004
1005    if (!s.finalCrop.isEmpty()) {
1006        win = s.active.transform.transform(win);
1007        if (!win.intersect(s.finalCrop, &win)) {
1008            win.clear();
1009        }
1010        win = s.active.transform.inverse().transform(win);
1011        if (!win.intersect(computeBounds(), &win)) {
1012            win.clear();
1013        }
1014    }
1015
1016    float left   = float(win.left)   / float(s.active.w);
1017    float top    = float(win.top)    / float(s.active.h);
1018    float right  = float(win.right)  / float(s.active.w);
1019    float bottom = float(win.bottom) / float(s.active.h);
1020
1021    // TODO: we probably want to generate the texture coords with the mesh
1022    // here we assume that we only have 4 vertices
1023    Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1024    texCoords[0] = vec2(left, 1.0f - top);
1025    texCoords[1] = vec2(left, 1.0f - bottom);
1026    texCoords[2] = vec2(right, 1.0f - bottom);
1027    texCoords[3] = vec2(right, 1.0f - top);
1028
1029    RenderEngine& engine(mFlinger->getRenderEngine());
1030    engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha);
1031    engine.drawMesh(mMesh);
1032    engine.disableBlending();
1033}
1034
1035#ifdef USE_HWC2
1036void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1037        bool callIntoHwc) {
1038    if (mHwcLayers.count(hwcId) == 0) {
1039        ALOGE("setCompositionType called without a valid HWC layer");
1040        return;
1041    }
1042    auto& hwcInfo = mHwcLayers[hwcId];
1043    auto& hwcLayer = hwcInfo.layer;
1044    ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1045            to_string(type).c_str(), static_cast<int>(callIntoHwc));
1046    if (hwcInfo.compositionType != type) {
1047        ALOGV("    actually setting");
1048        hwcInfo.compositionType = type;
1049        if (callIntoHwc) {
1050            auto error = hwcLayer->setCompositionType(type);
1051            ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1052                    "composition type %s: %s (%d)", mName.string(),
1053                    to_string(type).c_str(), to_string(error).c_str(),
1054                    static_cast<int32_t>(error));
1055        }
1056    }
1057}
1058
1059HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
1060    if (mHwcLayers.count(hwcId) == 0) {
1061        ALOGE("getCompositionType called without a valid HWC layer");
1062        return HWC2::Composition::Invalid;
1063    }
1064    return mHwcLayers.at(hwcId).compositionType;
1065}
1066
1067void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1068    if (mHwcLayers.count(hwcId) == 0) {
1069        ALOGE("setClearClientTarget called without a valid HWC layer");
1070        return;
1071    }
1072    mHwcLayers[hwcId].clearClientTarget = clear;
1073}
1074
1075bool Layer::getClearClientTarget(int32_t hwcId) const {
1076    if (mHwcLayers.count(hwcId) == 0) {
1077        ALOGE("getClearClientTarget called without a valid HWC layer");
1078        return false;
1079    }
1080    return mHwcLayers.at(hwcId).clearClientTarget;
1081}
1082#endif
1083
1084uint32_t Layer::getProducerStickyTransform() const {
1085    int producerStickyTransform = 0;
1086    int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1087    if (ret != OK) {
1088        ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1089                strerror(-ret), ret);
1090        return 0;
1091    }
1092    return static_cast<uint32_t>(producerStickyTransform);
1093}
1094
1095uint64_t Layer::getHeadFrameNumber() const {
1096    Mutex::Autolock lock(mQueueItemLock);
1097    if (!mQueueItems.empty()) {
1098        return mQueueItems[0].mFrameNumber;
1099    } else {
1100        return mCurrentFrameNumber;
1101    }
1102}
1103
1104bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1105    if (point->getFrameNumber() <= mCurrentFrameNumber) {
1106        // Don't bother with a SyncPoint, since we've already latched the
1107        // relevant frame
1108        return false;
1109    }
1110
1111    Mutex::Autolock lock(mLocalSyncPointMutex);
1112    mLocalSyncPoints.push_back(point);
1113    return true;
1114}
1115
1116void Layer::setFiltering(bool filtering) {
1117    mFiltering = filtering;
1118}
1119
1120bool Layer::getFiltering() const {
1121    return mFiltering;
1122}
1123
1124// As documented in libhardware header, formats in the range
1125// 0x100 - 0x1FF are specific to the HAL implementation, and
1126// are known to have no alpha channel
1127// TODO: move definition for device-specific range into
1128// hardware.h, instead of using hard-coded values here.
1129#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1130
1131bool Layer::getOpacityForFormat(uint32_t format) {
1132    if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1133        return true;
1134    }
1135    switch (format) {
1136        case HAL_PIXEL_FORMAT_RGBA_8888:
1137        case HAL_PIXEL_FORMAT_BGRA_8888:
1138            return false;
1139    }
1140    // in all other case, we have no blending (also for unknown formats)
1141    return true;
1142}
1143
1144// ----------------------------------------------------------------------------
1145// local state
1146// ----------------------------------------------------------------------------
1147
1148static void boundPoint(vec2* point, const Rect& crop) {
1149    if (point->x < crop.left) {
1150        point->x = crop.left;
1151    }
1152    if (point->x > crop.right) {
1153        point->x = crop.right;
1154    }
1155    if (point->y < crop.top) {
1156        point->y = crop.top;
1157    }
1158    if (point->y > crop.bottom) {
1159        point->y = crop.bottom;
1160    }
1161}
1162
1163void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1164        bool useIdentityTransform) const
1165{
1166    const Layer::State& s(getDrawingState());
1167    const Transform tr(hw->getTransform());
1168    const uint32_t hw_h = hw->getHeight();
1169    Rect win(s.active.w, s.active.h);
1170    if (!s.crop.isEmpty()) {
1171        win.intersect(s.crop, &win);
1172    }
1173    // subtract the transparent region and snap to the bounds
1174    win = reduce(win, s.activeTransparentRegion);
1175
1176    vec2 lt = vec2(win.left, win.top);
1177    vec2 lb = vec2(win.left, win.bottom);
1178    vec2 rb = vec2(win.right, win.bottom);
1179    vec2 rt = vec2(win.right, win.top);
1180
1181    if (!useIdentityTransform) {
1182        lt = s.active.transform.transform(lt);
1183        lb = s.active.transform.transform(lb);
1184        rb = s.active.transform.transform(rb);
1185        rt = s.active.transform.transform(rt);
1186    }
1187
1188    if (!s.finalCrop.isEmpty()) {
1189        boundPoint(&lt, s.finalCrop);
1190        boundPoint(&lb, s.finalCrop);
1191        boundPoint(&rb, s.finalCrop);
1192        boundPoint(&rt, s.finalCrop);
1193    }
1194
1195    Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
1196    position[0] = tr.transform(lt);
1197    position[1] = tr.transform(lb);
1198    position[2] = tr.transform(rb);
1199    position[3] = tr.transform(rt);
1200    for (size_t i=0 ; i<4 ; i++) {
1201        position[i].y = hw_h - position[i].y;
1202    }
1203}
1204
1205bool Layer::isOpaque(const Layer::State& s) const
1206{
1207    // if we don't have a buffer yet, we're translucent regardless of the
1208    // layer's opaque flag.
1209    if (mActiveBuffer == 0) {
1210        return false;
1211    }
1212
1213    // if the layer has the opaque flag, then we're always opaque,
1214    // otherwise we use the current buffer's format.
1215    return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
1216}
1217
1218bool Layer::isSecure() const
1219{
1220    const Layer::State& s(mDrawingState);
1221    return (s.flags & layer_state_t::eLayerSecure);
1222}
1223
1224bool Layer::isProtected() const
1225{
1226    const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
1227    return (activeBuffer != 0) &&
1228            (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1229}
1230
1231bool Layer::isFixedSize() const {
1232    return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1233}
1234
1235bool Layer::isCropped() const {
1236    return !mCurrentCrop.isEmpty();
1237}
1238
1239bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1240    return mNeedsFiltering || hw->needsFiltering();
1241}
1242
1243void Layer::setVisibleRegion(const Region& visibleRegion) {
1244    // always called from main thread
1245    this->visibleRegion = visibleRegion;
1246}
1247
1248void Layer::setCoveredRegion(const Region& coveredRegion) {
1249    // always called from main thread
1250    this->coveredRegion = coveredRegion;
1251}
1252
1253void Layer::setVisibleNonTransparentRegion(const Region&
1254        setVisibleNonTransparentRegion) {
1255    // always called from main thread
1256    this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1257}
1258
1259// ----------------------------------------------------------------------------
1260// transaction
1261// ----------------------------------------------------------------------------
1262
1263void Layer::pushPendingState() {
1264    if (!mCurrentState.modified) {
1265        return;
1266    }
1267
1268    // If this transaction is waiting on the receipt of a frame, generate a sync
1269    // point and send it to the remote layer.
1270    if (mCurrentState.handle != nullptr) {
1271        sp<Handle> handle = static_cast<Handle*>(mCurrentState.handle.get());
1272        sp<Layer> handleLayer = handle->owner.promote();
1273        if (handleLayer == nullptr) {
1274            ALOGE("[%s] Unable to promote Layer handle", mName.string());
1275            // If we can't promote the layer we are intended to wait on,
1276            // then it is expired or otherwise invalid. Allow this transaction
1277            // to be applied as per normal (no synchronization).
1278            mCurrentState.handle = nullptr;
1279        } else {
1280            auto syncPoint = std::make_shared<SyncPoint>(
1281                    mCurrentState.frameNumber);
1282            if (handleLayer->addSyncPoint(syncPoint)) {
1283                mRemoteSyncPoints.push_back(std::move(syncPoint));
1284            } else {
1285                // We already missed the frame we're supposed to synchronize
1286                // on, so go ahead and apply the state update
1287                mCurrentState.handle = nullptr;
1288            }
1289        }
1290
1291        // Wake us up to check if the frame has been received
1292        setTransactionFlags(eTransactionNeeded);
1293    }
1294    mPendingStates.push_back(mCurrentState);
1295}
1296
1297void Layer::popPendingState(State* stateToCommit) {
1298    auto oldFlags = stateToCommit->flags;
1299    *stateToCommit = mPendingStates[0];
1300    stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1301            (stateToCommit->flags & stateToCommit->mask);
1302
1303    mPendingStates.removeAt(0);
1304}
1305
1306bool Layer::applyPendingStates(State* stateToCommit) {
1307    bool stateUpdateAvailable = false;
1308    while (!mPendingStates.empty()) {
1309        if (mPendingStates[0].handle != nullptr) {
1310            if (mRemoteSyncPoints.empty()) {
1311                // If we don't have a sync point for this, apply it anyway. It
1312                // will be visually wrong, but it should keep us from getting
1313                // into too much trouble.
1314                ALOGE("[%s] No local sync point found", mName.string());
1315                popPendingState(stateToCommit);
1316                stateUpdateAvailable = true;
1317                continue;
1318            }
1319
1320            if (mRemoteSyncPoints.front()->getFrameNumber() !=
1321                    mPendingStates[0].frameNumber) {
1322                ALOGE("[%s] Unexpected sync point frame number found",
1323                        mName.string());
1324
1325                // Signal our end of the sync point and then dispose of it
1326                mRemoteSyncPoints.front()->setTransactionApplied();
1327                mRemoteSyncPoints.pop_front();
1328                continue;
1329            }
1330
1331            if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1332                // Apply the state update
1333                popPendingState(stateToCommit);
1334                stateUpdateAvailable = true;
1335
1336                // Signal our end of the sync point and then dispose of it
1337                mRemoteSyncPoints.front()->setTransactionApplied();
1338                mRemoteSyncPoints.pop_front();
1339            } else {
1340                break;
1341            }
1342        } else {
1343            popPendingState(stateToCommit);
1344            stateUpdateAvailable = true;
1345        }
1346    }
1347
1348    // If we still have pending updates, wake SurfaceFlinger back up and point
1349    // it at this layer so we can process them
1350    if (!mPendingStates.empty()) {
1351        setTransactionFlags(eTransactionNeeded);
1352        mFlinger->setTransactionFlags(eTraversalNeeded);
1353    }
1354
1355    mCurrentState.modified = false;
1356    return stateUpdateAvailable;
1357}
1358
1359void Layer::notifyAvailableFrames() {
1360    auto headFrameNumber = getHeadFrameNumber();
1361    Mutex::Autolock lock(mLocalSyncPointMutex);
1362    for (auto& point : mLocalSyncPoints) {
1363        if (headFrameNumber >= point->getFrameNumber()) {
1364            point->setFrameAvailable();
1365        }
1366    }
1367}
1368
1369uint32_t Layer::doTransaction(uint32_t flags) {
1370    ATRACE_CALL();
1371
1372    pushPendingState();
1373    Layer::State c = getCurrentState();
1374    if (!applyPendingStates(&c)) {
1375        return 0;
1376    }
1377
1378    const Layer::State& s(getDrawingState());
1379
1380    const bool sizeChanged = (c.requested.w != s.requested.w) ||
1381                             (c.requested.h != s.requested.h);
1382
1383    if (sizeChanged) {
1384        // the size changed, we need to ask our client to request a new buffer
1385        ALOGD_IF(DEBUG_RESIZE,
1386                "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
1387                "  current={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1388                "            requested={ wh={%4u,%4u} }}\n"
1389                "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1390                "            requested={ wh={%4u,%4u} }}\n",
1391                this, getName().string(), mCurrentTransform,
1392                getEffectiveScalingMode(),
1393                c.active.w, c.active.h,
1394                c.crop.left,
1395                c.crop.top,
1396                c.crop.right,
1397                c.crop.bottom,
1398                c.crop.getWidth(),
1399                c.crop.getHeight(),
1400                c.requested.w, c.requested.h,
1401                s.active.w, s.active.h,
1402                s.crop.left,
1403                s.crop.top,
1404                s.crop.right,
1405                s.crop.bottom,
1406                s.crop.getWidth(),
1407                s.crop.getHeight(),
1408                s.requested.w, s.requested.h);
1409
1410        // record the new size, form this point on, when the client request
1411        // a buffer, it'll get the new size.
1412        mSurfaceFlingerConsumer->setDefaultBufferSize(
1413                c.requested.w, c.requested.h);
1414    }
1415
1416    if (!isFixedSize()) {
1417
1418        const bool resizePending = (c.requested.w != c.active.w) ||
1419                                   (c.requested.h != c.active.h);
1420
1421        if (resizePending && mSidebandStream == NULL) {
1422            // don't let Layer::doTransaction update the drawing state
1423            // if we have a pending resize, unless we are in fixed-size mode.
1424            // the drawing state will be updated only once we receive a buffer
1425            // with the correct size.
1426            //
1427            // in particular, we want to make sure the clip (which is part
1428            // of the geometry state) is latched together with the size but is
1429            // latched immediately when no resizing is involved.
1430            //
1431            // If a sideband stream is attached, however, we want to skip this
1432            // optimization so that transactions aren't missed when a buffer
1433            // never arrives
1434
1435            flags |= eDontUpdateGeometryState;
1436        }
1437    }
1438
1439    // always set active to requested, unless we're asked not to
1440    // this is used by Layer, which special cases resizes.
1441    if (flags & eDontUpdateGeometryState)  {
1442    } else {
1443        c.active = c.requested;
1444    }
1445
1446    if (s.active != c.active) {
1447        // invalidate and recompute the visible regions if needed
1448        flags |= Layer::eVisibleRegion;
1449    }
1450
1451    if (c.sequence != s.sequence) {
1452        // invalidate and recompute the visible regions if needed
1453        flags |= eVisibleRegion;
1454        this->contentDirty = true;
1455
1456        // we may use linear filtering, if the matrix scales us
1457        const uint8_t type = c.active.transform.getType();
1458        mNeedsFiltering = (!c.active.transform.preserveRects() ||
1459                (type >= Transform::SCALE));
1460    }
1461
1462    // If the layer is hidden, signal and clear out all local sync points so
1463    // that transactions for layers depending on this layer's frames becoming
1464    // visible are not blocked
1465    if (c.flags & layer_state_t::eLayerHidden) {
1466        Mutex::Autolock lock(mLocalSyncPointMutex);
1467        for (auto& point : mLocalSyncPoints) {
1468            point->setFrameAvailable();
1469        }
1470        mLocalSyncPoints.clear();
1471    }
1472
1473    // Commit the transaction
1474    commitTransaction(c);
1475    return flags;
1476}
1477
1478void Layer::commitTransaction(const State& stateToCommit) {
1479    mDrawingState = stateToCommit;
1480}
1481
1482uint32_t Layer::getTransactionFlags(uint32_t flags) {
1483    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1484}
1485
1486uint32_t Layer::setTransactionFlags(uint32_t flags) {
1487    return android_atomic_or(flags, &mTransactionFlags);
1488}
1489
1490bool Layer::setPosition(float x, float y) {
1491    if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
1492        return false;
1493    mCurrentState.sequence++;
1494
1495    // We update the requested and active position simultaneously because
1496    // we want to apply the position portion of the transform matrix immediately,
1497    // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
1498    mCurrentState.requested.transform.set(x, y);
1499    mCurrentState.active.transform.set(x, y);
1500
1501    mCurrentState.modified = true;
1502    setTransactionFlags(eTransactionNeeded);
1503    return true;
1504}
1505bool Layer::setLayer(uint32_t z) {
1506    if (mCurrentState.z == z)
1507        return false;
1508    mCurrentState.sequence++;
1509    mCurrentState.z = z;
1510    mCurrentState.modified = true;
1511    setTransactionFlags(eTransactionNeeded);
1512    return true;
1513}
1514bool Layer::setSize(uint32_t w, uint32_t h) {
1515    if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1516        return false;
1517    mCurrentState.requested.w = w;
1518    mCurrentState.requested.h = h;
1519    mCurrentState.modified = true;
1520    setTransactionFlags(eTransactionNeeded);
1521    return true;
1522}
1523#ifdef USE_HWC2
1524bool Layer::setAlpha(float alpha) {
1525#else
1526bool Layer::setAlpha(uint8_t alpha) {
1527#endif
1528    if (mCurrentState.alpha == alpha)
1529        return false;
1530    mCurrentState.sequence++;
1531    mCurrentState.alpha = alpha;
1532    mCurrentState.modified = true;
1533    setTransactionFlags(eTransactionNeeded);
1534    return true;
1535}
1536bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1537    mCurrentState.sequence++;
1538    mCurrentState.requested.transform.set(
1539            matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
1540    mCurrentState.modified = true;
1541    setTransactionFlags(eTransactionNeeded);
1542    return true;
1543}
1544bool Layer::setTransparentRegionHint(const Region& transparent) {
1545    mCurrentState.requestedTransparentRegion = transparent;
1546    mCurrentState.modified = true;
1547    setTransactionFlags(eTransactionNeeded);
1548    return true;
1549}
1550bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1551    const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1552    if (mCurrentState.flags == newFlags)
1553        return false;
1554    mCurrentState.sequence++;
1555    mCurrentState.flags = newFlags;
1556    mCurrentState.mask = mask;
1557    mCurrentState.modified = true;
1558    setTransactionFlags(eTransactionNeeded);
1559    return true;
1560}
1561bool Layer::setCrop(const Rect& crop) {
1562    if (mCurrentState.crop == crop)
1563        return false;
1564    mCurrentState.sequence++;
1565    mCurrentState.crop = crop;
1566    mCurrentState.modified = true;
1567    setTransactionFlags(eTransactionNeeded);
1568    return true;
1569}
1570bool Layer::setFinalCrop(const Rect& crop) {
1571    if (mCurrentState.finalCrop == crop)
1572        return false;
1573    mCurrentState.sequence++;
1574    mCurrentState.finalCrop = crop;
1575    mCurrentState.modified = true;
1576    setTransactionFlags(eTransactionNeeded);
1577    return true;
1578}
1579
1580bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1581    if (scalingMode == mOverrideScalingMode)
1582        return false;
1583    mOverrideScalingMode = scalingMode;
1584    return true;
1585}
1586
1587uint32_t Layer::getEffectiveScalingMode() const {
1588    if (mOverrideScalingMode >= 0) {
1589      return mOverrideScalingMode;
1590    }
1591    return mCurrentScalingMode;
1592}
1593
1594bool Layer::setLayerStack(uint32_t layerStack) {
1595    if (mCurrentState.layerStack == layerStack)
1596        return false;
1597    mCurrentState.sequence++;
1598    mCurrentState.layerStack = layerStack;
1599    mCurrentState.modified = true;
1600    setTransactionFlags(eTransactionNeeded);
1601    return true;
1602}
1603
1604void Layer::deferTransactionUntil(const sp<IBinder>& handle,
1605        uint64_t frameNumber) {
1606    mCurrentState.handle = handle;
1607    mCurrentState.frameNumber = frameNumber;
1608    // We don't set eTransactionNeeded, because just receiving a deferral
1609    // request without any other state updates shouldn't actually induce a delay
1610    mCurrentState.modified = true;
1611    pushPendingState();
1612    mCurrentState.handle = nullptr;
1613    mCurrentState.frameNumber = 0;
1614    mCurrentState.modified = false;
1615}
1616
1617void Layer::useSurfaceDamage() {
1618    if (mFlinger->mForceFullDamage) {
1619        surfaceDamageRegion = Region::INVALID_REGION;
1620    } else {
1621        surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1622    }
1623}
1624
1625void Layer::useEmptyDamage() {
1626    surfaceDamageRegion.clear();
1627}
1628
1629// ----------------------------------------------------------------------------
1630// pageflip handling...
1631// ----------------------------------------------------------------------------
1632
1633bool Layer::shouldPresentNow(const DispSync& dispSync) const {
1634    if (mSidebandStreamChanged || mAutoRefresh) {
1635        return true;
1636    }
1637
1638    Mutex::Autolock lock(mQueueItemLock);
1639    if (mQueueItems.empty()) {
1640        return false;
1641    }
1642    auto timestamp = mQueueItems[0].mTimestamp;
1643    nsecs_t expectedPresent =
1644            mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
1645
1646    // Ignore timestamps more than a second in the future
1647    bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1648    ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1649            "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1650            expectedPresent);
1651
1652    bool isDue = timestamp < expectedPresent;
1653    return isDue || !isPlausible;
1654}
1655
1656bool Layer::onPreComposition() {
1657    mRefreshPending = false;
1658    return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
1659}
1660
1661bool Layer::onPostComposition() {
1662    bool frameLatencyNeeded = mFrameLatencyNeeded;
1663    if (mFrameLatencyNeeded) {
1664        nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1665        mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1666
1667        sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence();
1668        if (frameReadyFence->isValid()) {
1669            mFrameTracker.setFrameReadyFence(frameReadyFence);
1670        } else {
1671            // There was no fence for this frame, so assume that it was ready
1672            // to be presented at the desired present time.
1673            mFrameTracker.setFrameReadyTime(desiredPresentTime);
1674        }
1675
1676        const HWComposer& hwc = mFlinger->getHwComposer();
1677#ifdef USE_HWC2
1678        sp<Fence> presentFence = hwc.getRetireFence(HWC_DISPLAY_PRIMARY);
1679#else
1680        sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1681#endif
1682        if (presentFence->isValid()) {
1683            mFrameTracker.setActualPresentFence(presentFence);
1684        } else {
1685            // The HWC doesn't support present fences, so use the refresh
1686            // timestamp instead.
1687            nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1688            mFrameTracker.setActualPresentTime(presentTime);
1689        }
1690
1691        mFrameTracker.advanceFrame();
1692        mFrameLatencyNeeded = false;
1693    }
1694    return frameLatencyNeeded;
1695}
1696
1697#ifdef USE_HWC2
1698void Layer::releasePendingBuffer() {
1699    mSurfaceFlingerConsumer->releasePendingBuffer();
1700}
1701#endif
1702
1703bool Layer::isVisible() const {
1704    const Layer::State& s(mDrawingState);
1705#ifdef USE_HWC2
1706    return !(s.flags & layer_state_t::eLayerHidden) && s.alpha > 0.0f
1707            && (mActiveBuffer != NULL || mSidebandStream != NULL);
1708#else
1709    return !(s.flags & layer_state_t::eLayerHidden) && s.alpha
1710            && (mActiveBuffer != NULL || mSidebandStream != NULL);
1711#endif
1712}
1713
1714Region Layer::latchBuffer(bool& recomputeVisibleRegions)
1715{
1716    ATRACE_CALL();
1717
1718    if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
1719        // mSidebandStreamChanged was true
1720        mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
1721        if (mSidebandStream != NULL) {
1722            setTransactionFlags(eTransactionNeeded);
1723            mFlinger->setTransactionFlags(eTraversalNeeded);
1724        }
1725        recomputeVisibleRegions = true;
1726
1727        const State& s(getDrawingState());
1728        return s.active.transform.transform(Region(Rect(s.active.w, s.active.h)));
1729    }
1730
1731    Region outDirtyRegion;
1732    if (mQueuedFrames > 0 || mAutoRefresh) {
1733
1734        // if we've already called updateTexImage() without going through
1735        // a composition step, we have to skip this layer at this point
1736        // because we cannot call updateTeximage() without a corresponding
1737        // compositionComplete() call.
1738        // we'll trigger an update in onPreComposition().
1739        if (mRefreshPending) {
1740            return outDirtyRegion;
1741        }
1742
1743        // Capture the old state of the layer for comparisons later
1744        const State& s(getDrawingState());
1745        const bool oldOpacity = isOpaque(s);
1746        sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
1747
1748        struct Reject : public SurfaceFlingerConsumer::BufferRejecter {
1749            Layer::State& front;
1750            Layer::State& current;
1751            bool& recomputeVisibleRegions;
1752            bool stickyTransformSet;
1753            const char* name;
1754            int32_t overrideScalingMode;
1755
1756            Reject(Layer::State& front, Layer::State& current,
1757                    bool& recomputeVisibleRegions, bool stickySet,
1758                    const char* name,
1759                    int32_t overrideScalingMode)
1760                : front(front), current(current),
1761                  recomputeVisibleRegions(recomputeVisibleRegions),
1762                  stickyTransformSet(stickySet),
1763                  name(name),
1764                  overrideScalingMode(overrideScalingMode) {
1765            }
1766
1767            virtual bool reject(const sp<GraphicBuffer>& buf,
1768                    const BufferItem& item) {
1769                if (buf == NULL) {
1770                    return false;
1771                }
1772
1773                uint32_t bufWidth  = buf->getWidth();
1774                uint32_t bufHeight = buf->getHeight();
1775
1776                // check that we received a buffer of the right size
1777                // (Take the buffer's orientation into account)
1778                if (item.mTransform & Transform::ROT_90) {
1779                    swap(bufWidth, bufHeight);
1780                }
1781
1782                int actualScalingMode = overrideScalingMode >= 0 ?
1783                        overrideScalingMode : item.mScalingMode;
1784                bool isFixedSize = actualScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1785                if (front.active != front.requested) {
1786
1787                    if (isFixedSize ||
1788                            (bufWidth == front.requested.w &&
1789                             bufHeight == front.requested.h))
1790                    {
1791                        // Here we pretend the transaction happened by updating the
1792                        // current and drawing states. Drawing state is only accessed
1793                        // in this thread, no need to have it locked
1794                        front.active = front.requested;
1795
1796                        // We also need to update the current state so that
1797                        // we don't end-up overwriting the drawing state with
1798                        // this stale current state during the next transaction
1799                        //
1800                        // NOTE: We don't need to hold the transaction lock here
1801                        // because State::active is only accessed from this thread.
1802                        current.active = front.active;
1803                        current.modified = true;
1804
1805                        // recompute visible region
1806                        recomputeVisibleRegions = true;
1807                    }
1808
1809                    ALOGD_IF(DEBUG_RESIZE,
1810                            "[%s] latchBuffer/reject: buffer (%ux%u, tr=%02x), scalingMode=%d\n"
1811                            "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1812                            "            requested={ wh={%4u,%4u} }}\n",
1813                            name,
1814                            bufWidth, bufHeight, item.mTransform, item.mScalingMode,
1815                            front.active.w, front.active.h,
1816                            front.crop.left,
1817                            front.crop.top,
1818                            front.crop.right,
1819                            front.crop.bottom,
1820                            front.crop.getWidth(),
1821                            front.crop.getHeight(),
1822                            front.requested.w, front.requested.h);
1823                }
1824
1825                if (!isFixedSize && !stickyTransformSet) {
1826                    if (front.active.w != bufWidth ||
1827                        front.active.h != bufHeight) {
1828                        // reject this buffer
1829                        ALOGE("[%s] rejecting buffer: "
1830                                "bufWidth=%d, bufHeight=%d, front.active.{w=%d, h=%d}",
1831                                name, bufWidth, bufHeight, front.active.w, front.active.h);
1832                        return true;
1833                    }
1834                }
1835
1836                // if the transparent region has changed (this test is
1837                // conservative, but that's fine, worst case we're doing
1838                // a bit of extra work), we latch the new one and we
1839                // trigger a visible-region recompute.
1840                if (!front.activeTransparentRegion.isTriviallyEqual(
1841                        front.requestedTransparentRegion)) {
1842                    front.activeTransparentRegion = front.requestedTransparentRegion;
1843
1844                    // We also need to update the current state so that
1845                    // we don't end-up overwriting the drawing state with
1846                    // this stale current state during the next transaction
1847                    //
1848                    // NOTE: We don't need to hold the transaction lock here
1849                    // because State::active is only accessed from this thread.
1850                    current.activeTransparentRegion = front.activeTransparentRegion;
1851
1852                    // recompute visible region
1853                    recomputeVisibleRegions = true;
1854                }
1855
1856                return false;
1857            }
1858        };
1859
1860        Reject r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
1861                getProducerStickyTransform() != 0, mName.string(),
1862                mOverrideScalingMode);
1863
1864
1865        // Check all of our local sync points to ensure that all transactions
1866        // which need to have been applied prior to the frame which is about to
1867        // be latched have signaled
1868
1869        auto headFrameNumber = getHeadFrameNumber();
1870        bool matchingFramesFound = false;
1871        bool allTransactionsApplied = true;
1872        {
1873            Mutex::Autolock lock(mLocalSyncPointMutex);
1874            for (auto& point : mLocalSyncPoints) {
1875                if (point->getFrameNumber() > headFrameNumber) {
1876                    break;
1877                }
1878
1879                matchingFramesFound = true;
1880
1881                if (!point->frameIsAvailable()) {
1882                    // We haven't notified the remote layer that the frame for
1883                    // this point is available yet. Notify it now, and then
1884                    // abort this attempt to latch.
1885                    point->setFrameAvailable();
1886                    allTransactionsApplied = false;
1887                    break;
1888                }
1889
1890                allTransactionsApplied &= point->transactionIsApplied();
1891            }
1892        }
1893
1894        if (matchingFramesFound && !allTransactionsApplied) {
1895            mFlinger->signalLayerUpdate();
1896            return outDirtyRegion;
1897        }
1898
1899        // This boolean is used to make sure that SurfaceFlinger's shadow copy
1900        // of the buffer queue isn't modified when the buffer queue is returning
1901        // BufferItem's that weren't actually queued. This can happen in shared
1902        // buffer mode.
1903        bool queuedBuffer = false;
1904        status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
1905                mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
1906                mLastFrameNumberReceived);
1907        if (updateResult == BufferQueue::PRESENT_LATER) {
1908            // Producer doesn't want buffer to be displayed yet.  Signal a
1909            // layer update so we check again at the next opportunity.
1910            mFlinger->signalLayerUpdate();
1911            return outDirtyRegion;
1912        } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
1913            // If the buffer has been rejected, remove it from the shadow queue
1914            // and return early
1915            if (queuedBuffer) {
1916                Mutex::Autolock lock(mQueueItemLock);
1917                mQueueItems.removeAt(0);
1918                android_atomic_dec(&mQueuedFrames);
1919            }
1920            return outDirtyRegion;
1921        } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
1922            // This can occur if something goes wrong when trying to create the
1923            // EGLImage for this buffer. If this happens, the buffer has already
1924            // been released, so we need to clean up the queue and bug out
1925            // early.
1926            if (queuedBuffer) {
1927                Mutex::Autolock lock(mQueueItemLock);
1928                mQueueItems.clear();
1929                android_atomic_and(0, &mQueuedFrames);
1930            }
1931
1932            // Once we have hit this state, the shadow queue may no longer
1933            // correctly reflect the incoming BufferQueue's contents, so even if
1934            // updateTexImage starts working, the only safe course of action is
1935            // to continue to ignore updates.
1936            mUpdateTexImageFailed = true;
1937
1938            return outDirtyRegion;
1939        }
1940
1941        if (queuedBuffer) {
1942            // Autolock scope
1943            auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
1944
1945            Mutex::Autolock lock(mQueueItemLock);
1946
1947            // Remove any stale buffers that have been dropped during
1948            // updateTexImage
1949            while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
1950                mQueueItems.removeAt(0);
1951                android_atomic_dec(&mQueuedFrames);
1952            }
1953
1954            mQueueItems.removeAt(0);
1955        }
1956
1957
1958        // Decrement the queued-frames count.  Signal another event if we
1959        // have more frames pending.
1960        if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
1961                || mAutoRefresh) {
1962            mFlinger->signalLayerUpdate();
1963        }
1964
1965        if (updateResult != NO_ERROR) {
1966            // something happened!
1967            recomputeVisibleRegions = true;
1968            return outDirtyRegion;
1969        }
1970
1971        // update the active buffer
1972        mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer();
1973        if (mActiveBuffer == NULL) {
1974            // this can only happen if the very first buffer was rejected.
1975            return outDirtyRegion;
1976        }
1977
1978        mRefreshPending = true;
1979        mFrameLatencyNeeded = true;
1980        if (oldActiveBuffer == NULL) {
1981             // the first time we receive a buffer, we need to trigger a
1982             // geometry invalidation.
1983            recomputeVisibleRegions = true;
1984         }
1985
1986        Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
1987        const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
1988        const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
1989        if ((crop != mCurrentCrop) ||
1990            (transform != mCurrentTransform) ||
1991            (scalingMode != mCurrentScalingMode))
1992        {
1993            mCurrentCrop = crop;
1994            mCurrentTransform = transform;
1995            mCurrentScalingMode = scalingMode;
1996            recomputeVisibleRegions = true;
1997        }
1998
1999        if (oldActiveBuffer != NULL) {
2000            uint32_t bufWidth  = mActiveBuffer->getWidth();
2001            uint32_t bufHeight = mActiveBuffer->getHeight();
2002            if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2003                bufHeight != uint32_t(oldActiveBuffer->height)) {
2004                recomputeVisibleRegions = true;
2005            }
2006        }
2007
2008        mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2009        if (oldOpacity != isOpaque(s)) {
2010            recomputeVisibleRegions = true;
2011        }
2012
2013        mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2014
2015        // Remove any sync points corresponding to the buffer which was just
2016        // latched
2017        {
2018            Mutex::Autolock lock(mLocalSyncPointMutex);
2019            auto point = mLocalSyncPoints.begin();
2020            while (point != mLocalSyncPoints.end()) {
2021                if (!(*point)->frameIsAvailable() ||
2022                        !(*point)->transactionIsApplied()) {
2023                    // This sync point must have been added since we started
2024                    // latching. Don't drop it yet.
2025                    ++point;
2026                    continue;
2027                }
2028
2029                if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2030                    point = mLocalSyncPoints.erase(point);
2031                } else {
2032                    ++point;
2033                }
2034            }
2035        }
2036
2037        // FIXME: postedRegion should be dirty & bounds
2038        Region dirtyRegion(Rect(s.active.w, s.active.h));
2039
2040        // transform the dirty region to window-manager space
2041        outDirtyRegion = (s.active.transform.transform(dirtyRegion));
2042    }
2043    return outDirtyRegion;
2044}
2045
2046uint32_t Layer::getEffectiveUsage(uint32_t usage) const
2047{
2048    // TODO: should we do something special if mSecure is set?
2049    if (mProtectedByApp) {
2050        // need a hardware-protected path to external video sink
2051        usage |= GraphicBuffer::USAGE_PROTECTED;
2052    }
2053    if (mPotentialCursor) {
2054        usage |= GraphicBuffer::USAGE_CURSOR;
2055    }
2056    usage |= GraphicBuffer::USAGE_HW_COMPOSER;
2057    return usage;
2058}
2059
2060void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
2061    uint32_t orientation = 0;
2062    if (!mFlinger->mDebugDisableTransformHint) {
2063        // The transform hint is used to improve performance, but we can
2064        // only have a single transform hint, it cannot
2065        // apply to all displays.
2066        const Transform& planeTransform(hw->getTransform());
2067        orientation = planeTransform.getOrientation();
2068        if (orientation & Transform::ROT_INVALID) {
2069            orientation = 0;
2070        }
2071    }
2072    mSurfaceFlingerConsumer->setTransformHint(orientation);
2073}
2074
2075// ----------------------------------------------------------------------------
2076// debugging
2077// ----------------------------------------------------------------------------
2078
2079void Layer::dump(String8& result, Colorizer& colorizer) const
2080{
2081    const Layer::State& s(getDrawingState());
2082
2083    colorizer.colorize(result, Colorizer::GREEN);
2084    result.appendFormat(
2085            "+ %s %p (%s)\n",
2086            getTypeId(), this, getName().string());
2087    colorizer.reset(result);
2088
2089    s.activeTransparentRegion.dump(result, "transparentRegion");
2090    visibleRegion.dump(result, "visibleRegion");
2091    surfaceDamageRegion.dump(result, "surfaceDamageRegion");
2092    sp<Client> client(mClientRef.promote());
2093
2094    result.appendFormat(            "      "
2095            "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2096            "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
2097            "isOpaque=%1d, invalidate=%1d, "
2098#ifdef USE_HWC2
2099            "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2100#else
2101            "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2102#endif
2103            "      client=%p\n",
2104            s.layerStack, s.z, s.active.transform.tx(), s.active.transform.ty(), s.active.w, s.active.h,
2105            s.crop.left, s.crop.top,
2106            s.crop.right, s.crop.bottom,
2107            s.finalCrop.left, s.finalCrop.top,
2108            s.finalCrop.right, s.finalCrop.bottom,
2109            isOpaque(s), contentDirty,
2110            s.alpha, s.flags,
2111            s.active.transform[0][0], s.active.transform[0][1],
2112            s.active.transform[1][0], s.active.transform[1][1],
2113            client.get());
2114
2115    sp<const GraphicBuffer> buf0(mActiveBuffer);
2116    uint32_t w0=0, h0=0, s0=0, f0=0;
2117    if (buf0 != 0) {
2118        w0 = buf0->getWidth();
2119        h0 = buf0->getHeight();
2120        s0 = buf0->getStride();
2121        f0 = buf0->format;
2122    }
2123    result.appendFormat(
2124            "      "
2125            "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2126            " queued-frames=%d, mRefreshPending=%d\n",
2127            mFormat, w0, h0, s0,f0,
2128            mQueuedFrames, mRefreshPending);
2129
2130    if (mSurfaceFlingerConsumer != 0) {
2131        mSurfaceFlingerConsumer->dump(result, "            ");
2132    }
2133}
2134
2135void Layer::dumpFrameStats(String8& result) const {
2136    mFrameTracker.dumpStats(result);
2137}
2138
2139void Layer::clearFrameStats() {
2140    mFrameTracker.clearStats();
2141}
2142
2143void Layer::logFrameStats() {
2144    mFrameTracker.logAndResetStats(mName);
2145}
2146
2147void Layer::getFrameStats(FrameStats* outStats) const {
2148    mFrameTracker.getStats(outStats);
2149}
2150
2151void Layer::getFenceData(String8* outName, uint64_t* outFrameNumber,
2152        bool* outIsGlesComposition, nsecs_t* outPostedTime,
2153        sp<Fence>* outAcquireFence, sp<Fence>* outPrevReleaseFence) const {
2154    *outName = mName;
2155    *outFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2156
2157#ifdef USE_HWC2
2158    *outIsGlesComposition = mHwcLayers.count(HWC_DISPLAY_PRIMARY) ?
2159            mHwcLayers.at(HWC_DISPLAY_PRIMARY).compositionType ==
2160            HWC2::Composition::Client : true;
2161#else
2162    *outIsGlesComposition = mIsGlesComposition;
2163#endif
2164    *outPostedTime = mSurfaceFlingerConsumer->getTimestamp();
2165    *outAcquireFence = mSurfaceFlingerConsumer->getCurrentFence();
2166    *outPrevReleaseFence = mSurfaceFlingerConsumer->getPrevReleaseFence();
2167}
2168
2169std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2170        bool forceFlush) {
2171    std::vector<OccupancyTracker::Segment> history;
2172    status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2173            &history);
2174    if (result != NO_ERROR) {
2175        ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2176                result);
2177        return {};
2178    }
2179    return history;
2180}
2181
2182// ---------------------------------------------------------------------------
2183
2184Layer::LayerCleaner::LayerCleaner(const sp<SurfaceFlinger>& flinger,
2185        const sp<Layer>& layer)
2186    : mFlinger(flinger), mLayer(layer) {
2187}
2188
2189Layer::LayerCleaner::~LayerCleaner() {
2190    // destroy client resources
2191    mFlinger->onLayerDestroyed(mLayer);
2192}
2193
2194// ---------------------------------------------------------------------------
2195}; // namespace android
2196
2197#if defined(__gl_h_)
2198#error "don't include gl/gl.h in this file"
2199#endif
2200
2201#if defined(__gl2_h_)
2202#error "don't include gl2/gl2.h in this file"
2203#endif
2204