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