Layer.cpp revision 257b6578930fd93814bcb34cd7541796bf9ca5d0
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#include <mutex>
55
56#define DEBUG_RESIZE    0
57
58namespace android {
59
60// ---------------------------------------------------------------------------
61
62int32_t Layer::sSequence = 1;
63
64Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
65        const String8& name, uint32_t w, uint32_t h, uint32_t flags)
66    :   contentDirty(false),
67        sequence(uint32_t(android_atomic_inc(&sSequence))),
68        mFlinger(flinger),
69        mTextureName(-1U),
70        mPremultipliedAlpha(true),
71        mName("unnamed"),
72        mFormat(PIXEL_FORMAT_NONE),
73        mTransactionFlags(0),
74        mPendingStateMutex(),
75        mPendingStates(),
76        mQueuedFrames(0),
77        mSidebandStreamChanged(false),
78        mCurrentTransform(0),
79        mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
80        mOverrideScalingMode(-1),
81        mCurrentOpacity(true),
82        mCurrentFrameNumber(0),
83        mRefreshPending(false),
84        mFrameLatencyNeeded(false),
85        mFiltering(false),
86        mNeedsFiltering(false),
87        mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
88#ifndef USE_HWC2
89        mIsGlesComposition(false),
90#endif
91        mProtectedByApp(false),
92        mHasSurface(false),
93        mClientRef(client),
94        mPotentialCursor(false),
95        mQueueItemLock(),
96        mQueueItemCondition(),
97        mQueueItems(),
98        mLastFrameNumberReceived(0),
99        mUpdateTexImageFailed(false),
100        mAutoRefresh(false),
101        mFreezePositionUpdates(false)
102{
103#ifdef USE_HWC2
104    ALOGV("Creating Layer %s", name.string());
105#endif
106
107    mCurrentCrop.makeInvalid();
108    mFlinger->getRenderEngine().genTextures(1, &mTextureName);
109    mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
110
111    uint32_t layerFlags = 0;
112    if (flags & ISurfaceComposerClient::eHidden)
113        layerFlags |= layer_state_t::eLayerHidden;
114    if (flags & ISurfaceComposerClient::eOpaque)
115        layerFlags |= layer_state_t::eLayerOpaque;
116    if (flags & ISurfaceComposerClient::eSecure)
117        layerFlags |= layer_state_t::eLayerSecure;
118
119    if (flags & ISurfaceComposerClient::eNonPremultiplied)
120        mPremultipliedAlpha = false;
121
122    mName = name;
123
124    mCurrentState.active.w = w;
125    mCurrentState.active.h = h;
126    mCurrentState.active.transform.set(0, 0);
127    mCurrentState.crop.makeInvalid();
128    mCurrentState.finalCrop.makeInvalid();
129    mCurrentState.z = 0;
130#ifdef USE_HWC2
131    mCurrentState.alpha = 1.0f;
132#else
133    mCurrentState.alpha = 0xFF;
134#endif
135    mCurrentState.layerStack = 0;
136    mCurrentState.flags = layerFlags;
137    mCurrentState.sequence = 0;
138    mCurrentState.requested = mCurrentState.active;
139
140    // drawing state & current state are identical
141    mDrawingState = mCurrentState;
142
143#ifdef USE_HWC2
144    const auto& hwc = flinger->getHwComposer();
145    const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
146    nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
147#else
148    nsecs_t displayPeriod =
149            flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
150#endif
151    mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
152}
153
154void Layer::onFirstRef() {
155    // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
156    sp<IGraphicBufferProducer> producer;
157    sp<IGraphicBufferConsumer> consumer;
158    BufferQueue::createBufferQueue(&producer, &consumer);
159    mProducer = new MonitoredProducer(producer, mFlinger);
160    mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName,
161            this);
162    mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
163    mSurfaceFlingerConsumer->setContentsChangedListener(this);
164    mSurfaceFlingerConsumer->setName(mName);
165
166#ifndef TARGET_DISABLE_TRIPLE_BUFFERING
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 layers
723    if (mHwcLayers[hwcId].forceClientComposition ||
724            (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
725        ALOGV("[%s] Requesting Client composition", mName.string());
726        setCompositionType(hwcId, HWC2::Composition::Client);
727        return;
728    }
729
730    // SolidColor layers
731    if (mActiveBuffer == nullptr) {
732        setCompositionType(hwcId, HWC2::Composition::SolidColor);
733        error = hwcLayer->setColor({0, 0, 0, 255});
734        if (error != HWC2::Error::None) {
735            ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
736                    to_string(error).c_str(), static_cast<int32_t>(error));
737        }
738        return;
739    }
740
741    // Device or Cursor layers
742    if (mPotentialCursor) {
743        ALOGV("[%s] Requesting Cursor composition", mName.string());
744        setCompositionType(hwcId, HWC2::Composition::Cursor);
745    } else {
746        ALOGV("[%s] Requesting Device composition", mName.string());
747        setCompositionType(hwcId, HWC2::Composition::Device);
748    }
749
750    auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
751    error = hwcLayer->setBuffer(mActiveBuffer->handle, acquireFence);
752    if (error != HWC2::Error::None) {
753        ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
754                mActiveBuffer->handle, to_string(error).c_str(),
755                static_cast<int32_t>(error));
756    }
757}
758#else
759void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
760        HWComposer::HWCLayerInterface& layer) {
761    // we have to set the visible region on every frame because
762    // we currently free it during onLayerDisplayed(), which is called
763    // after HWComposer::commit() -- every frame.
764    // Apply this display's projection's viewport to the visible region
765    // before giving it to the HWC HAL.
766    const Transform& tr = hw->getTransform();
767    Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
768    layer.setVisibleRegionScreen(visible);
769    layer.setSurfaceDamage(surfaceDamageRegion);
770    mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
771
772    if (mSidebandStream.get()) {
773        layer.setSidebandStream(mSidebandStream);
774    } else {
775        // NOTE: buffer can be NULL if the client never drew into this
776        // layer yet, or if we ran out of memory
777        layer.setBuffer(mActiveBuffer);
778    }
779}
780#endif
781
782#ifdef USE_HWC2
783void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
784    auto hwcId = displayDevice->getHwcDisplayId();
785    if (mHwcLayers.count(hwcId) == 0 ||
786            getCompositionType(hwcId) != HWC2::Composition::Cursor) {
787        return;
788    }
789
790    // This gives us only the "orientation" component of the transform
791    const State& s(getCurrentState());
792
793    // Apply the layer's transform, followed by the display's global transform
794    // Here we're guaranteed that the layer's transform preserves rects
795    Rect win(s.active.w, s.active.h);
796    if (!s.crop.isEmpty()) {
797        win.intersect(s.crop, &win);
798    }
799    // Subtract the transparent region and snap to the bounds
800    Rect bounds = reduce(win, s.activeTransparentRegion);
801    Rect frame(s.active.transform.transform(bounds));
802    frame.intersect(displayDevice->getViewport(), &frame);
803    if (!s.finalCrop.isEmpty()) {
804        frame.intersect(s.finalCrop, &frame);
805    }
806    auto& displayTransform(displayDevice->getTransform());
807    auto position = displayTransform.transform(frame);
808
809    auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
810            position.top);
811    ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
812            "to (%d, %d): %s (%d)", mName.string(), position.left,
813            position.top, to_string(error).c_str(),
814            static_cast<int32_t>(error));
815}
816#else
817void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
818        HWComposer::HWCLayerInterface& layer) {
819    int fenceFd = -1;
820
821    // TODO: there is a possible optimization here: we only need to set the
822    // acquire fence the first time a new buffer is acquired on EACH display.
823
824    if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
825        sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
826        if (fence->isValid()) {
827            fenceFd = fence->dup();
828            if (fenceFd == -1) {
829                ALOGW("failed to dup layer fence, skipping sync: %d", errno);
830            }
831        }
832    }
833    layer.setAcquireFenceFd(fenceFd);
834}
835
836Rect Layer::getPosition(
837    const sp<const DisplayDevice>& hw)
838{
839    // this gives us only the "orientation" component of the transform
840    const State& s(getCurrentState());
841
842    // apply the layer's transform, followed by the display's global transform
843    // here we're guaranteed that the layer's transform preserves rects
844    Rect win(s.active.w, s.active.h);
845    if (!s.crop.isEmpty()) {
846        win.intersect(s.crop, &win);
847    }
848    // subtract the transparent region and snap to the bounds
849    Rect bounds = reduce(win, s.activeTransparentRegion);
850    Rect frame(s.active.transform.transform(bounds));
851    frame.intersect(hw->getViewport(), &frame);
852    if (!s.finalCrop.isEmpty()) {
853        frame.intersect(s.finalCrop, &frame);
854    }
855    const Transform& tr(hw->getTransform());
856    return Rect(tr.transform(frame));
857}
858#endif
859
860// ---------------------------------------------------------------------------
861// drawing...
862// ---------------------------------------------------------------------------
863
864void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
865    onDraw(hw, clip, false);
866}
867
868void Layer::draw(const sp<const DisplayDevice>& hw,
869        bool useIdentityTransform) const {
870    onDraw(hw, Region(hw->bounds()), useIdentityTransform);
871}
872
873void Layer::draw(const sp<const DisplayDevice>& hw) const {
874    onDraw(hw, Region(hw->bounds()), false);
875}
876
877void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
878        bool useIdentityTransform) const
879{
880    ATRACE_CALL();
881
882    if (CC_UNLIKELY(mActiveBuffer == 0)) {
883        // the texture has not been created yet, this Layer has
884        // in fact never been drawn into. This happens frequently with
885        // SurfaceView because the WindowManager can't know when the client
886        // has drawn the first time.
887
888        // If there is nothing under us, we paint the screen in black, otherwise
889        // we just skip this update.
890
891        // figure out if there is something below us
892        Region under;
893        const SurfaceFlinger::LayerVector& drawingLayers(
894                mFlinger->mDrawingState.layersSortedByZ);
895        const size_t count = drawingLayers.size();
896        for (size_t i=0 ; i<count ; ++i) {
897            const sp<Layer>& layer(drawingLayers[i]);
898            if (layer.get() == static_cast<Layer const*>(this))
899                break;
900            under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
901        }
902        // if not everything below us is covered, we plug the holes!
903        Region holes(clip.subtract(under));
904        if (!holes.isEmpty()) {
905            clearWithOpenGL(hw, holes, 0, 0, 0, 1);
906        }
907        return;
908    }
909
910    // Bind the current buffer to the GL texture, and wait for it to be
911    // ready for us to draw into.
912    status_t err = mSurfaceFlingerConsumer->bindTextureImage();
913    if (err != NO_ERROR) {
914        ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
915        // Go ahead and draw the buffer anyway; no matter what we do the screen
916        // is probably going to have something visibly wrong.
917    }
918
919    bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
920
921    RenderEngine& engine(mFlinger->getRenderEngine());
922
923    if (!blackOutLayer) {
924        // TODO: we could be more subtle with isFixedSize()
925        const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
926
927        // Query the texture matrix given our current filtering mode.
928        float textureMatrix[16];
929        mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
930        mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
931
932        if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
933
934            /*
935             * the code below applies the primary display's inverse transform to
936             * the texture transform
937             */
938
939            // create a 4x4 transform matrix from the display transform flags
940            const mat4 flipH(-1,0,0,0,  0,1,0,0, 0,0,1,0, 1,0,0,1);
941            const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
942            const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
943
944            mat4 tr;
945            uint32_t transform =
946                    DisplayDevice::getPrimaryDisplayOrientationTransform();
947            if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90)
948                tr = tr * rot90;
949            if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H)
950                tr = tr * flipH;
951            if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V)
952                tr = tr * flipV;
953
954            // calculate the inverse
955            tr = inverse(tr);
956
957            // and finally apply it to the original texture matrix
958            const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
959            memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
960        }
961
962        // Set things up for texturing.
963        mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
964        mTexture.setFiltering(useFiltering);
965        mTexture.setMatrix(textureMatrix);
966
967        engine.setupLayerTexturing(mTexture);
968    } else {
969        engine.setupLayerBlackedOut();
970    }
971    drawWithOpenGL(hw, clip, useIdentityTransform);
972    engine.disableTexturing();
973}
974
975
976void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
977        const Region& /* clip */, float red, float green, float blue,
978        float alpha) const
979{
980    RenderEngine& engine(mFlinger->getRenderEngine());
981    computeGeometry(hw, mMesh, false);
982    engine.setupFillWithColor(red, green, blue, alpha);
983    engine.drawMesh(mMesh);
984}
985
986void Layer::clearWithOpenGL(
987        const sp<const DisplayDevice>& hw, const Region& clip) const {
988    clearWithOpenGL(hw, clip, 0,0,0,0);
989}
990
991void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
992        const Region& /* clip */, bool useIdentityTransform) const {
993    const State& s(getDrawingState());
994
995    computeGeometry(hw, mMesh, useIdentityTransform);
996
997    /*
998     * NOTE: the way we compute the texture coordinates here produces
999     * different results than when we take the HWC path -- in the later case
1000     * the "source crop" is rounded to texel boundaries.
1001     * This can produce significantly different results when the texture
1002     * is scaled by a large amount.
1003     *
1004     * The GL code below is more logical (imho), and the difference with
1005     * HWC is due to a limitation of the HWC API to integers -- a question
1006     * is suspend is whether we should ignore this problem or revert to
1007     * GL composition when a buffer scaling is applied (maybe with some
1008     * minimal value)? Or, we could make GL behave like HWC -- but this feel
1009     * like more of a hack.
1010     */
1011    Rect win(computeBounds());
1012
1013    if (!s.finalCrop.isEmpty()) {
1014        win = s.active.transform.transform(win);
1015        if (!win.intersect(s.finalCrop, &win)) {
1016            win.clear();
1017        }
1018        win = s.active.transform.inverse().transform(win);
1019        if (!win.intersect(computeBounds(), &win)) {
1020            win.clear();
1021        }
1022    }
1023
1024    float left   = float(win.left)   / float(s.active.w);
1025    float top    = float(win.top)    / float(s.active.h);
1026    float right  = float(win.right)  / float(s.active.w);
1027    float bottom = float(win.bottom) / float(s.active.h);
1028
1029    // TODO: we probably want to generate the texture coords with the mesh
1030    // here we assume that we only have 4 vertices
1031    Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1032    texCoords[0] = vec2(left, 1.0f - top);
1033    texCoords[1] = vec2(left, 1.0f - bottom);
1034    texCoords[2] = vec2(right, 1.0f - bottom);
1035    texCoords[3] = vec2(right, 1.0f - top);
1036
1037    RenderEngine& engine(mFlinger->getRenderEngine());
1038    engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha);
1039    engine.drawMesh(mMesh);
1040    engine.disableBlending();
1041}
1042
1043#ifdef USE_HWC2
1044void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1045        bool callIntoHwc) {
1046    if (mHwcLayers.count(hwcId) == 0) {
1047        ALOGE("setCompositionType called without a valid HWC layer");
1048        return;
1049    }
1050    auto& hwcInfo = mHwcLayers[hwcId];
1051    auto& hwcLayer = hwcInfo.layer;
1052    ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1053            to_string(type).c_str(), static_cast<int>(callIntoHwc));
1054    if (hwcInfo.compositionType != type) {
1055        ALOGV("    actually setting");
1056        hwcInfo.compositionType = type;
1057        if (callIntoHwc) {
1058            auto error = hwcLayer->setCompositionType(type);
1059            ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1060                    "composition type %s: %s (%d)", mName.string(),
1061                    to_string(type).c_str(), to_string(error).c_str(),
1062                    static_cast<int32_t>(error));
1063        }
1064    }
1065}
1066
1067HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
1068    if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1069        // If we're querying the composition type for a display that does not
1070        // have a HWC counterpart, then it will always be Client
1071        return HWC2::Composition::Client;
1072    }
1073    if (mHwcLayers.count(hwcId) == 0) {
1074        ALOGE("getCompositionType called with an invalid HWC layer");
1075        return HWC2::Composition::Invalid;
1076    }
1077    return mHwcLayers.at(hwcId).compositionType;
1078}
1079
1080void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1081    if (mHwcLayers.count(hwcId) == 0) {
1082        ALOGE("setClearClientTarget called without a valid HWC layer");
1083        return;
1084    }
1085    mHwcLayers[hwcId].clearClientTarget = clear;
1086}
1087
1088bool Layer::getClearClientTarget(int32_t hwcId) const {
1089    if (mHwcLayers.count(hwcId) == 0) {
1090        ALOGE("getClearClientTarget called without a valid HWC layer");
1091        return false;
1092    }
1093    return mHwcLayers.at(hwcId).clearClientTarget;
1094}
1095#endif
1096
1097uint32_t Layer::getProducerStickyTransform() const {
1098    int producerStickyTransform = 0;
1099    int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1100    if (ret != OK) {
1101        ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1102                strerror(-ret), ret);
1103        return 0;
1104    }
1105    return static_cast<uint32_t>(producerStickyTransform);
1106}
1107
1108bool Layer::latchUnsignaledBuffers() {
1109    static bool propertyLoaded = false;
1110    static bool latch = false;
1111    static std::mutex mutex;
1112    std::lock_guard<std::mutex> lock(mutex);
1113    if (!propertyLoaded) {
1114        char value[PROPERTY_VALUE_MAX] = {};
1115        property_get("debug.sf.latch_unsignaled", value, "0");
1116        latch = atoi(value);
1117        propertyLoaded = true;
1118    }
1119    return latch;
1120}
1121
1122uint64_t Layer::getHeadFrameNumber() const {
1123    Mutex::Autolock lock(mQueueItemLock);
1124    if (!mQueueItems.empty()) {
1125        return mQueueItems[0].mFrameNumber;
1126    } else {
1127        return mCurrentFrameNumber;
1128    }
1129}
1130
1131bool Layer::headFenceHasSignaled() const {
1132#ifdef USE_HWC2
1133    if (latchUnsignaledBuffers()) {
1134        return true;
1135    }
1136
1137    Mutex::Autolock lock(mQueueItemLock);
1138    if (mQueueItems.empty()) {
1139        return true;
1140    }
1141    if (mQueueItems[0].mIsDroppable) {
1142        // Even though this buffer's fence may not have signaled yet, it could
1143        // be replaced by another buffer before it has a chance to, which means
1144        // that it's possible to get into a situation where a buffer is never
1145        // able to be latched. To avoid this, grab this buffer anyway.
1146        return true;
1147    }
1148    return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
1149#else
1150    return true;
1151#endif
1152}
1153
1154bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1155    if (point->getFrameNumber() <= mCurrentFrameNumber) {
1156        // Don't bother with a SyncPoint, since we've already latched the
1157        // relevant frame
1158        return false;
1159    }
1160
1161    Mutex::Autolock lock(mLocalSyncPointMutex);
1162    mLocalSyncPoints.push_back(point);
1163    return true;
1164}
1165
1166void Layer::setFiltering(bool filtering) {
1167    mFiltering = filtering;
1168}
1169
1170bool Layer::getFiltering() const {
1171    return mFiltering;
1172}
1173
1174// As documented in libhardware header, formats in the range
1175// 0x100 - 0x1FF are specific to the HAL implementation, and
1176// are known to have no alpha channel
1177// TODO: move definition for device-specific range into
1178// hardware.h, instead of using hard-coded values here.
1179#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1180
1181bool Layer::getOpacityForFormat(uint32_t format) {
1182    if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1183        return true;
1184    }
1185    switch (format) {
1186        case HAL_PIXEL_FORMAT_RGBA_8888:
1187        case HAL_PIXEL_FORMAT_BGRA_8888:
1188            return false;
1189    }
1190    // in all other case, we have no blending (also for unknown formats)
1191    return true;
1192}
1193
1194// ----------------------------------------------------------------------------
1195// local state
1196// ----------------------------------------------------------------------------
1197
1198static void boundPoint(vec2* point, const Rect& crop) {
1199    if (point->x < crop.left) {
1200        point->x = crop.left;
1201    }
1202    if (point->x > crop.right) {
1203        point->x = crop.right;
1204    }
1205    if (point->y < crop.top) {
1206        point->y = crop.top;
1207    }
1208    if (point->y > crop.bottom) {
1209        point->y = crop.bottom;
1210    }
1211}
1212
1213void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1214        bool useIdentityTransform) const
1215{
1216    const Layer::State& s(getDrawingState());
1217    const Transform tr(hw->getTransform());
1218    const uint32_t hw_h = hw->getHeight();
1219    Rect win(s.active.w, s.active.h);
1220    if (!s.crop.isEmpty()) {
1221        win.intersect(s.crop, &win);
1222    }
1223    // subtract the transparent region and snap to the bounds
1224    win = reduce(win, s.activeTransparentRegion);
1225
1226    vec2 lt = vec2(win.left, win.top);
1227    vec2 lb = vec2(win.left, win.bottom);
1228    vec2 rb = vec2(win.right, win.bottom);
1229    vec2 rt = vec2(win.right, win.top);
1230
1231    if (!useIdentityTransform) {
1232        lt = s.active.transform.transform(lt);
1233        lb = s.active.transform.transform(lb);
1234        rb = s.active.transform.transform(rb);
1235        rt = s.active.transform.transform(rt);
1236    }
1237
1238    if (!s.finalCrop.isEmpty()) {
1239        boundPoint(&lt, s.finalCrop);
1240        boundPoint(&lb, s.finalCrop);
1241        boundPoint(&rb, s.finalCrop);
1242        boundPoint(&rt, s.finalCrop);
1243    }
1244
1245    Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
1246    position[0] = tr.transform(lt);
1247    position[1] = tr.transform(lb);
1248    position[2] = tr.transform(rb);
1249    position[3] = tr.transform(rt);
1250    for (size_t i=0 ; i<4 ; i++) {
1251        position[i].y = hw_h - position[i].y;
1252    }
1253}
1254
1255bool Layer::isOpaque(const Layer::State& s) const
1256{
1257    // if we don't have a buffer yet, we're translucent regardless of the
1258    // layer's opaque flag.
1259    if (mActiveBuffer == 0) {
1260        return false;
1261    }
1262
1263    // if the layer has the opaque flag, then we're always opaque,
1264    // otherwise we use the current buffer's format.
1265    return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
1266}
1267
1268bool Layer::isSecure() const
1269{
1270    const Layer::State& s(mDrawingState);
1271    return (s.flags & layer_state_t::eLayerSecure);
1272}
1273
1274bool Layer::isProtected() const
1275{
1276    const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
1277    return (activeBuffer != 0) &&
1278            (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1279}
1280
1281bool Layer::isFixedSize() const {
1282    return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1283}
1284
1285bool Layer::isCropped() const {
1286    return !mCurrentCrop.isEmpty();
1287}
1288
1289bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1290    return mNeedsFiltering || hw->needsFiltering();
1291}
1292
1293void Layer::setVisibleRegion(const Region& visibleRegion) {
1294    // always called from main thread
1295    this->visibleRegion = visibleRegion;
1296}
1297
1298void Layer::setCoveredRegion(const Region& coveredRegion) {
1299    // always called from main thread
1300    this->coveredRegion = coveredRegion;
1301}
1302
1303void Layer::setVisibleNonTransparentRegion(const Region&
1304        setVisibleNonTransparentRegion) {
1305    // always called from main thread
1306    this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1307}
1308
1309// ----------------------------------------------------------------------------
1310// transaction
1311// ----------------------------------------------------------------------------
1312
1313void Layer::pushPendingState() {
1314    if (!mCurrentState.modified) {
1315        return;
1316    }
1317
1318    // If this transaction is waiting on the receipt of a frame, generate a sync
1319    // point and send it to the remote layer.
1320    if (mCurrentState.handle != nullptr) {
1321        sp<Handle> handle = static_cast<Handle*>(mCurrentState.handle.get());
1322        sp<Layer> handleLayer = handle->owner.promote();
1323        if (handleLayer == nullptr) {
1324            ALOGE("[%s] Unable to promote Layer handle", mName.string());
1325            // If we can't promote the layer we are intended to wait on,
1326            // then it is expired or otherwise invalid. Allow this transaction
1327            // to be applied as per normal (no synchronization).
1328            mCurrentState.handle = nullptr;
1329        } else {
1330            auto syncPoint = std::make_shared<SyncPoint>(
1331                    mCurrentState.frameNumber);
1332            if (handleLayer->addSyncPoint(syncPoint)) {
1333                mRemoteSyncPoints.push_back(std::move(syncPoint));
1334            } else {
1335                // We already missed the frame we're supposed to synchronize
1336                // on, so go ahead and apply the state update
1337                mCurrentState.handle = nullptr;
1338            }
1339        }
1340
1341        // Wake us up to check if the frame has been received
1342        setTransactionFlags(eTransactionNeeded);
1343    }
1344    mPendingStates.push_back(mCurrentState);
1345}
1346
1347void Layer::popPendingState(State* stateToCommit) {
1348    auto oldFlags = stateToCommit->flags;
1349    *stateToCommit = mPendingStates[0];
1350    stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1351            (stateToCommit->flags & stateToCommit->mask);
1352
1353    mPendingStates.removeAt(0);
1354}
1355
1356bool Layer::applyPendingStates(State* stateToCommit) {
1357    bool stateUpdateAvailable = false;
1358    while (!mPendingStates.empty()) {
1359        if (mPendingStates[0].handle != nullptr) {
1360            if (mRemoteSyncPoints.empty()) {
1361                // If we don't have a sync point for this, apply it anyway. It
1362                // will be visually wrong, but it should keep us from getting
1363                // into too much trouble.
1364                ALOGE("[%s] No local sync point found", mName.string());
1365                popPendingState(stateToCommit);
1366                stateUpdateAvailable = true;
1367                continue;
1368            }
1369
1370            if (mRemoteSyncPoints.front()->getFrameNumber() !=
1371                    mPendingStates[0].frameNumber) {
1372                ALOGE("[%s] Unexpected sync point frame number found",
1373                        mName.string());
1374
1375                // Signal our end of the sync point and then dispose of it
1376                mRemoteSyncPoints.front()->setTransactionApplied();
1377                mRemoteSyncPoints.pop_front();
1378                continue;
1379            }
1380
1381            if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1382                // Apply the state update
1383                popPendingState(stateToCommit);
1384                stateUpdateAvailable = true;
1385
1386                // Signal our end of the sync point and then dispose of it
1387                mRemoteSyncPoints.front()->setTransactionApplied();
1388                mRemoteSyncPoints.pop_front();
1389            } else {
1390                break;
1391            }
1392        } else {
1393            popPendingState(stateToCommit);
1394            stateUpdateAvailable = true;
1395        }
1396    }
1397
1398    // If we still have pending updates, wake SurfaceFlinger back up and point
1399    // it at this layer so we can process them
1400    if (!mPendingStates.empty()) {
1401        setTransactionFlags(eTransactionNeeded);
1402        mFlinger->setTransactionFlags(eTraversalNeeded);
1403    }
1404
1405    mCurrentState.modified = false;
1406    return stateUpdateAvailable;
1407}
1408
1409void Layer::notifyAvailableFrames() {
1410    auto headFrameNumber = getHeadFrameNumber();
1411    bool headFenceSignaled = headFenceHasSignaled();
1412    Mutex::Autolock lock(mLocalSyncPointMutex);
1413    for (auto& point : mLocalSyncPoints) {
1414        if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
1415            point->setFrameAvailable();
1416        }
1417    }
1418}
1419
1420uint32_t Layer::doTransaction(uint32_t flags) {
1421    ATRACE_CALL();
1422
1423    pushPendingState();
1424    Layer::State c = getCurrentState();
1425    if (!applyPendingStates(&c)) {
1426        return 0;
1427    }
1428
1429    const Layer::State& s(getDrawingState());
1430
1431    const bool sizeChanged = (c.requested.w != s.requested.w) ||
1432                             (c.requested.h != s.requested.h);
1433
1434    if (sizeChanged) {
1435        // the size changed, we need to ask our client to request a new buffer
1436        ALOGD_IF(DEBUG_RESIZE,
1437                "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
1438                "  current={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1439                "            requested={ wh={%4u,%4u} }}\n"
1440                "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1441                "            requested={ wh={%4u,%4u} }}\n",
1442                this, getName().string(), mCurrentTransform,
1443                getEffectiveScalingMode(),
1444                c.active.w, c.active.h,
1445                c.crop.left,
1446                c.crop.top,
1447                c.crop.right,
1448                c.crop.bottom,
1449                c.crop.getWidth(),
1450                c.crop.getHeight(),
1451                c.requested.w, c.requested.h,
1452                s.active.w, s.active.h,
1453                s.crop.left,
1454                s.crop.top,
1455                s.crop.right,
1456                s.crop.bottom,
1457                s.crop.getWidth(),
1458                s.crop.getHeight(),
1459                s.requested.w, s.requested.h);
1460
1461        // record the new size, form this point on, when the client request
1462        // a buffer, it'll get the new size.
1463        mSurfaceFlingerConsumer->setDefaultBufferSize(
1464                c.requested.w, c.requested.h);
1465    }
1466
1467    const bool resizePending = (c.requested.w != c.active.w) ||
1468            (c.requested.h != c.active.h);
1469    if (!isFixedSize()) {
1470        if (resizePending && mSidebandStream == NULL) {
1471            // don't let Layer::doTransaction update the drawing state
1472            // if we have a pending resize, unless we are in fixed-size mode.
1473            // the drawing state will be updated only once we receive a buffer
1474            // with the correct size.
1475            //
1476            // in particular, we want to make sure the clip (which is part
1477            // of the geometry state) is latched together with the size but is
1478            // latched immediately when no resizing is involved.
1479            //
1480            // If a sideband stream is attached, however, we want to skip this
1481            // optimization so that transactions aren't missed when a buffer
1482            // never arrives
1483
1484            flags |= eDontUpdateGeometryState;
1485        }
1486    }
1487
1488    // always set active to requested, unless we're asked not to
1489    // this is used by Layer, which special cases resizes.
1490    if (flags & eDontUpdateGeometryState)  {
1491    } else {
1492        Layer::State& editCurrentState(getCurrentState());
1493        if (mFreezePositionUpdates) {
1494            float tx = c.active.transform.tx();
1495            float ty = c.active.transform.ty();
1496            c.active = c.requested;
1497            c.active.transform.set(tx, ty);
1498            editCurrentState.active = c.active;
1499        } else {
1500            editCurrentState.active = editCurrentState.requested;
1501            c.active = c.requested;
1502        }
1503    }
1504
1505    if (s.active != c.active) {
1506        // invalidate and recompute the visible regions if needed
1507        flags |= Layer::eVisibleRegion;
1508    }
1509
1510    if (c.sequence != s.sequence) {
1511        // invalidate and recompute the visible regions if needed
1512        flags |= eVisibleRegion;
1513        this->contentDirty = true;
1514
1515        // we may use linear filtering, if the matrix scales us
1516        const uint8_t type = c.active.transform.getType();
1517        mNeedsFiltering = (!c.active.transform.preserveRects() ||
1518                (type >= Transform::SCALE));
1519    }
1520
1521    // If the layer is hidden, signal and clear out all local sync points so
1522    // that transactions for layers depending on this layer's frames becoming
1523    // visible are not blocked
1524    if (c.flags & layer_state_t::eLayerHidden) {
1525        Mutex::Autolock lock(mLocalSyncPointMutex);
1526        for (auto& point : mLocalSyncPoints) {
1527            point->setFrameAvailable();
1528        }
1529        mLocalSyncPoints.clear();
1530    }
1531
1532    // Commit the transaction
1533    commitTransaction(c);
1534    return flags;
1535}
1536
1537void Layer::commitTransaction(const State& stateToCommit) {
1538    mDrawingState = stateToCommit;
1539}
1540
1541uint32_t Layer::getTransactionFlags(uint32_t flags) {
1542    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1543}
1544
1545uint32_t Layer::setTransactionFlags(uint32_t flags) {
1546    return android_atomic_or(flags, &mTransactionFlags);
1547}
1548
1549bool Layer::setPosition(float x, float y, bool immediate) {
1550    if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
1551        return false;
1552    mCurrentState.sequence++;
1553
1554    // We update the requested and active position simultaneously because
1555    // we want to apply the position portion of the transform matrix immediately,
1556    // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
1557    mCurrentState.requested.transform.set(x, y);
1558    if (immediate && !mFreezePositionUpdates) {
1559        mCurrentState.active.transform.set(x, y);
1560    }
1561    mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
1562
1563    mCurrentState.modified = true;
1564    setTransactionFlags(eTransactionNeeded);
1565    return true;
1566}
1567
1568bool Layer::setLayer(uint32_t z) {
1569    if (mCurrentState.z == z)
1570        return false;
1571    mCurrentState.sequence++;
1572    mCurrentState.z = z;
1573    mCurrentState.modified = true;
1574    setTransactionFlags(eTransactionNeeded);
1575    return true;
1576}
1577bool Layer::setSize(uint32_t w, uint32_t h) {
1578    if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1579        return false;
1580    mCurrentState.requested.w = w;
1581    mCurrentState.requested.h = h;
1582    mCurrentState.modified = true;
1583    setTransactionFlags(eTransactionNeeded);
1584    return true;
1585}
1586#ifdef USE_HWC2
1587bool Layer::setAlpha(float alpha) {
1588#else
1589bool Layer::setAlpha(uint8_t alpha) {
1590#endif
1591    if (mCurrentState.alpha == alpha)
1592        return false;
1593    mCurrentState.sequence++;
1594    mCurrentState.alpha = alpha;
1595    mCurrentState.modified = true;
1596    setTransactionFlags(eTransactionNeeded);
1597    return true;
1598}
1599bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1600    mCurrentState.sequence++;
1601    mCurrentState.requested.transform.set(
1602            matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
1603    mCurrentState.modified = true;
1604    setTransactionFlags(eTransactionNeeded);
1605    return true;
1606}
1607bool Layer::setTransparentRegionHint(const Region& transparent) {
1608    mCurrentState.requestedTransparentRegion = transparent;
1609    mCurrentState.modified = true;
1610    setTransactionFlags(eTransactionNeeded);
1611    return true;
1612}
1613bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1614    const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1615    if (mCurrentState.flags == newFlags)
1616        return false;
1617    mCurrentState.sequence++;
1618    mCurrentState.flags = newFlags;
1619    mCurrentState.mask = mask;
1620    mCurrentState.modified = true;
1621    setTransactionFlags(eTransactionNeeded);
1622    return true;
1623}
1624
1625bool Layer::setCrop(const Rect& crop, bool immediate) {
1626    if (mCurrentState.crop == crop)
1627        return false;
1628    mCurrentState.sequence++;
1629    mCurrentState.requestedCrop = crop;
1630    if (immediate) {
1631        mCurrentState.crop = crop;
1632    }
1633    mCurrentState.modified = true;
1634    setTransactionFlags(eTransactionNeeded);
1635    return true;
1636}
1637bool Layer::setFinalCrop(const Rect& crop) {
1638    if (mCurrentState.finalCrop == crop)
1639        return false;
1640    mCurrentState.sequence++;
1641    mCurrentState.finalCrop = crop;
1642    mCurrentState.modified = true;
1643    setTransactionFlags(eTransactionNeeded);
1644    return true;
1645}
1646
1647bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1648    if (scalingMode == mOverrideScalingMode)
1649        return false;
1650    mOverrideScalingMode = scalingMode;
1651    setTransactionFlags(eTransactionNeeded);
1652    return true;
1653}
1654
1655uint32_t Layer::getEffectiveScalingMode() const {
1656    if (mOverrideScalingMode >= 0) {
1657      return mOverrideScalingMode;
1658    }
1659    return mCurrentScalingMode;
1660}
1661
1662bool Layer::setLayerStack(uint32_t layerStack) {
1663    if (mCurrentState.layerStack == layerStack)
1664        return false;
1665    mCurrentState.sequence++;
1666    mCurrentState.layerStack = layerStack;
1667    mCurrentState.modified = true;
1668    setTransactionFlags(eTransactionNeeded);
1669    return true;
1670}
1671
1672void Layer::deferTransactionUntil(const sp<IBinder>& handle,
1673        uint64_t frameNumber) {
1674    mCurrentState.handle = handle;
1675    mCurrentState.frameNumber = frameNumber;
1676    // We don't set eTransactionNeeded, because just receiving a deferral
1677    // request without any other state updates shouldn't actually induce a delay
1678    mCurrentState.modified = true;
1679    pushPendingState();
1680    mCurrentState.handle = nullptr;
1681    mCurrentState.frameNumber = 0;
1682    mCurrentState.modified = false;
1683}
1684
1685void Layer::useSurfaceDamage() {
1686    if (mFlinger->mForceFullDamage) {
1687        surfaceDamageRegion = Region::INVALID_REGION;
1688    } else {
1689        surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1690    }
1691}
1692
1693void Layer::useEmptyDamage() {
1694    surfaceDamageRegion.clear();
1695}
1696
1697// ----------------------------------------------------------------------------
1698// pageflip handling...
1699// ----------------------------------------------------------------------------
1700
1701bool Layer::shouldPresentNow(const DispSync& dispSync) const {
1702    if (mSidebandStreamChanged || mAutoRefresh) {
1703        return true;
1704    }
1705
1706    Mutex::Autolock lock(mQueueItemLock);
1707    if (mQueueItems.empty()) {
1708        return false;
1709    }
1710    auto timestamp = mQueueItems[0].mTimestamp;
1711    nsecs_t expectedPresent =
1712            mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
1713
1714    // Ignore timestamps more than a second in the future
1715    bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1716    ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1717            "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1718            expectedPresent);
1719
1720    bool isDue = timestamp < expectedPresent;
1721    return isDue || !isPlausible;
1722}
1723
1724bool Layer::onPreComposition() {
1725    mRefreshPending = false;
1726    return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
1727}
1728
1729bool Layer::onPostComposition() {
1730    bool frameLatencyNeeded = mFrameLatencyNeeded;
1731    if (mFrameLatencyNeeded) {
1732        nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1733        mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1734
1735        sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence();
1736        if (frameReadyFence->isValid()) {
1737            mFrameTracker.setFrameReadyFence(frameReadyFence);
1738        } else {
1739            // There was no fence for this frame, so assume that it was ready
1740            // to be presented at the desired present time.
1741            mFrameTracker.setFrameReadyTime(desiredPresentTime);
1742        }
1743
1744        const HWComposer& hwc = mFlinger->getHwComposer();
1745#ifdef USE_HWC2
1746        sp<Fence> presentFence = hwc.getRetireFence(HWC_DISPLAY_PRIMARY);
1747#else
1748        sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1749#endif
1750        if (presentFence->isValid()) {
1751            mFrameTracker.setActualPresentFence(presentFence);
1752        } else {
1753            // The HWC doesn't support present fences, so use the refresh
1754            // timestamp instead.
1755            nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1756            mFrameTracker.setActualPresentTime(presentTime);
1757        }
1758
1759        mFrameTracker.advanceFrame();
1760        mFrameLatencyNeeded = false;
1761    }
1762    return frameLatencyNeeded;
1763}
1764
1765#ifdef USE_HWC2
1766void Layer::releasePendingBuffer() {
1767    mSurfaceFlingerConsumer->releasePendingBuffer();
1768}
1769#endif
1770
1771bool Layer::isVisible() const {
1772    const Layer::State& s(mDrawingState);
1773#ifdef USE_HWC2
1774    return !(s.flags & layer_state_t::eLayerHidden) && s.alpha > 0.0f
1775            && (mActiveBuffer != NULL || mSidebandStream != NULL);
1776#else
1777    return !(s.flags & layer_state_t::eLayerHidden) && s.alpha
1778            && (mActiveBuffer != NULL || mSidebandStream != NULL);
1779#endif
1780}
1781
1782Region Layer::latchBuffer(bool& recomputeVisibleRegions)
1783{
1784    ATRACE_CALL();
1785
1786    if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
1787        // mSidebandStreamChanged was true
1788        mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
1789        if (mSidebandStream != NULL) {
1790            setTransactionFlags(eTransactionNeeded);
1791            mFlinger->setTransactionFlags(eTraversalNeeded);
1792        }
1793        recomputeVisibleRegions = true;
1794
1795        const State& s(getDrawingState());
1796        return s.active.transform.transform(Region(Rect(s.active.w, s.active.h)));
1797    }
1798
1799    Region outDirtyRegion;
1800    if (mQueuedFrames > 0 || mAutoRefresh) {
1801
1802        // if we've already called updateTexImage() without going through
1803        // a composition step, we have to skip this layer at this point
1804        // because we cannot call updateTeximage() without a corresponding
1805        // compositionComplete() call.
1806        // we'll trigger an update in onPreComposition().
1807        if (mRefreshPending) {
1808            return outDirtyRegion;
1809        }
1810
1811        // If the head buffer's acquire fence hasn't signaled yet, return and
1812        // try again later
1813        if (!headFenceHasSignaled()) {
1814            mFlinger->signalLayerUpdate();
1815            return outDirtyRegion;
1816        }
1817
1818        // Capture the old state of the layer for comparisons later
1819        const State& s(getDrawingState());
1820        const bool oldOpacity = isOpaque(s);
1821        sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
1822
1823        struct Reject : public SurfaceFlingerConsumer::BufferRejecter {
1824            Layer::State& front;
1825            Layer::State& current;
1826            bool& recomputeVisibleRegions;
1827            bool stickyTransformSet;
1828            const char* name;
1829            int32_t overrideScalingMode;
1830            bool& freezePositionUpdates;
1831
1832            Reject(Layer::State& front, Layer::State& current,
1833                    bool& recomputeVisibleRegions, bool stickySet,
1834                    const char* name,
1835                    int32_t overrideScalingMode,
1836                    bool& freezePositionUpdates)
1837                : front(front), current(current),
1838                  recomputeVisibleRegions(recomputeVisibleRegions),
1839                  stickyTransformSet(stickySet),
1840                  name(name),
1841                  overrideScalingMode(overrideScalingMode),
1842                  freezePositionUpdates(freezePositionUpdates) {
1843            }
1844
1845            virtual bool reject(const sp<GraphicBuffer>& buf,
1846                    const BufferItem& item) {
1847                if (buf == NULL) {
1848                    return false;
1849                }
1850
1851                uint32_t bufWidth  = buf->getWidth();
1852                uint32_t bufHeight = buf->getHeight();
1853
1854                // check that we received a buffer of the right size
1855                // (Take the buffer's orientation into account)
1856                if (item.mTransform & Transform::ROT_90) {
1857                    swap(bufWidth, bufHeight);
1858                }
1859
1860                int actualScalingMode = overrideScalingMode >= 0 ?
1861                        overrideScalingMode : item.mScalingMode;
1862                bool isFixedSize = actualScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1863                if (front.active != front.requested) {
1864
1865                    if (isFixedSize ||
1866                            (bufWidth == front.requested.w &&
1867                             bufHeight == front.requested.h))
1868                    {
1869                        // Here we pretend the transaction happened by updating the
1870                        // current and drawing states. Drawing state is only accessed
1871                        // in this thread, no need to have it locked
1872                        front.active = front.requested;
1873
1874                        // We also need to update the current state so that
1875                        // we don't end-up overwriting the drawing state with
1876                        // this stale current state during the next transaction
1877                        //
1878                        // NOTE: We don't need to hold the transaction lock here
1879                        // because State::active is only accessed from this thread.
1880                        current.active = front.active;
1881                        current.modified = true;
1882
1883                        // recompute visible region
1884                        recomputeVisibleRegions = true;
1885                    }
1886
1887                    ALOGD_IF(DEBUG_RESIZE,
1888                            "[%s] latchBuffer/reject: buffer (%ux%u, tr=%02x), scalingMode=%d\n"
1889                            "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1890                            "            requested={ wh={%4u,%4u} }}\n",
1891                            name,
1892                            bufWidth, bufHeight, item.mTransform, item.mScalingMode,
1893                            front.active.w, front.active.h,
1894                            front.crop.left,
1895                            front.crop.top,
1896                            front.crop.right,
1897                            front.crop.bottom,
1898                            front.crop.getWidth(),
1899                            front.crop.getHeight(),
1900                            front.requested.w, front.requested.h);
1901                }
1902
1903                if (!isFixedSize && !stickyTransformSet) {
1904                    if (front.active.w != bufWidth ||
1905                        front.active.h != bufHeight) {
1906                        // reject this buffer
1907                        ALOGE("[%s] rejecting buffer: "
1908                                "bufWidth=%d, bufHeight=%d, front.active.{w=%d, h=%d}",
1909                                name, bufWidth, bufHeight, front.active.w, front.active.h);
1910                        return true;
1911                    }
1912                }
1913
1914                // if the transparent region has changed (this test is
1915                // conservative, but that's fine, worst case we're doing
1916                // a bit of extra work), we latch the new one and we
1917                // trigger a visible-region recompute.
1918                if (!front.activeTransparentRegion.isTriviallyEqual(
1919                        front.requestedTransparentRegion)) {
1920                    front.activeTransparentRegion = front.requestedTransparentRegion;
1921
1922                    // We also need to update the current state so that
1923                    // we don't end-up overwriting the drawing state with
1924                    // this stale current state during the next transaction
1925                    //
1926                    // NOTE: We don't need to hold the transaction lock here
1927                    // because State::active is only accessed from this thread.
1928                    current.activeTransparentRegion = front.activeTransparentRegion;
1929
1930                    // recompute visible region
1931                    recomputeVisibleRegions = true;
1932                }
1933
1934                if (front.crop != front.requestedCrop) {
1935                    front.crop = front.requestedCrop;
1936                    current.crop = front.requestedCrop;
1937                    recomputeVisibleRegions = true;
1938                }
1939                freezePositionUpdates = false;
1940
1941                return false;
1942            }
1943        };
1944
1945        Reject r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
1946                getProducerStickyTransform() != 0, mName.string(),
1947                mOverrideScalingMode, mFreezePositionUpdates);
1948
1949
1950        // Check all of our local sync points to ensure that all transactions
1951        // which need to have been applied prior to the frame which is about to
1952        // be latched have signaled
1953
1954        auto headFrameNumber = getHeadFrameNumber();
1955        bool matchingFramesFound = false;
1956        bool allTransactionsApplied = true;
1957        {
1958            Mutex::Autolock lock(mLocalSyncPointMutex);
1959            for (auto& point : mLocalSyncPoints) {
1960                if (point->getFrameNumber() > headFrameNumber) {
1961                    break;
1962                }
1963
1964                matchingFramesFound = true;
1965
1966                if (!point->frameIsAvailable()) {
1967                    // We haven't notified the remote layer that the frame for
1968                    // this point is available yet. Notify it now, and then
1969                    // abort this attempt to latch.
1970                    point->setFrameAvailable();
1971                    allTransactionsApplied = false;
1972                    break;
1973                }
1974
1975                allTransactionsApplied &= point->transactionIsApplied();
1976            }
1977        }
1978
1979        if (matchingFramesFound && !allTransactionsApplied) {
1980            mFlinger->signalLayerUpdate();
1981            return outDirtyRegion;
1982        }
1983
1984        // This boolean is used to make sure that SurfaceFlinger's shadow copy
1985        // of the buffer queue isn't modified when the buffer queue is returning
1986        // BufferItem's that weren't actually queued. This can happen in shared
1987        // buffer mode.
1988        bool queuedBuffer = false;
1989        status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
1990                mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
1991                mLastFrameNumberReceived);
1992        if (updateResult == BufferQueue::PRESENT_LATER) {
1993            // Producer doesn't want buffer to be displayed yet.  Signal a
1994            // layer update so we check again at the next opportunity.
1995            mFlinger->signalLayerUpdate();
1996            return outDirtyRegion;
1997        } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
1998            // If the buffer has been rejected, remove it from the shadow queue
1999            // and return early
2000            if (queuedBuffer) {
2001                Mutex::Autolock lock(mQueueItemLock);
2002                mQueueItems.removeAt(0);
2003                android_atomic_dec(&mQueuedFrames);
2004            }
2005            return outDirtyRegion;
2006        } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2007            // This can occur if something goes wrong when trying to create the
2008            // EGLImage for this buffer. If this happens, the buffer has already
2009            // been released, so we need to clean up the queue and bug out
2010            // early.
2011            if (queuedBuffer) {
2012                Mutex::Autolock lock(mQueueItemLock);
2013                mQueueItems.clear();
2014                android_atomic_and(0, &mQueuedFrames);
2015            }
2016
2017            // Once we have hit this state, the shadow queue may no longer
2018            // correctly reflect the incoming BufferQueue's contents, so even if
2019            // updateTexImage starts working, the only safe course of action is
2020            // to continue to ignore updates.
2021            mUpdateTexImageFailed = true;
2022
2023            return outDirtyRegion;
2024        }
2025
2026        if (queuedBuffer) {
2027            // Autolock scope
2028            auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2029
2030            Mutex::Autolock lock(mQueueItemLock);
2031
2032            // Remove any stale buffers that have been dropped during
2033            // updateTexImage
2034            while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2035                mQueueItems.removeAt(0);
2036                android_atomic_dec(&mQueuedFrames);
2037            }
2038
2039            mQueueItems.removeAt(0);
2040        }
2041
2042
2043        // Decrement the queued-frames count.  Signal another event if we
2044        // have more frames pending.
2045        if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2046                || mAutoRefresh) {
2047            mFlinger->signalLayerUpdate();
2048        }
2049
2050        if (updateResult != NO_ERROR) {
2051            // something happened!
2052            recomputeVisibleRegions = true;
2053            return outDirtyRegion;
2054        }
2055
2056        // update the active buffer
2057        mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer();
2058        if (mActiveBuffer == NULL) {
2059            // this can only happen if the very first buffer was rejected.
2060            return outDirtyRegion;
2061        }
2062
2063        mRefreshPending = true;
2064        mFrameLatencyNeeded = true;
2065        if (oldActiveBuffer == NULL) {
2066             // the first time we receive a buffer, we need to trigger a
2067             // geometry invalidation.
2068            recomputeVisibleRegions = true;
2069         }
2070
2071        Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2072        const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2073        const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2074        if ((crop != mCurrentCrop) ||
2075            (transform != mCurrentTransform) ||
2076            (scalingMode != mCurrentScalingMode))
2077        {
2078            mCurrentCrop = crop;
2079            mCurrentTransform = transform;
2080            mCurrentScalingMode = scalingMode;
2081            recomputeVisibleRegions = true;
2082        }
2083
2084        if (oldActiveBuffer != NULL) {
2085            uint32_t bufWidth  = mActiveBuffer->getWidth();
2086            uint32_t bufHeight = mActiveBuffer->getHeight();
2087            if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2088                bufHeight != uint32_t(oldActiveBuffer->height)) {
2089                recomputeVisibleRegions = true;
2090            }
2091        }
2092
2093        mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2094        if (oldOpacity != isOpaque(s)) {
2095            recomputeVisibleRegions = true;
2096        }
2097
2098        mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2099
2100        // Remove any sync points corresponding to the buffer which was just
2101        // latched
2102        {
2103            Mutex::Autolock lock(mLocalSyncPointMutex);
2104            auto point = mLocalSyncPoints.begin();
2105            while (point != mLocalSyncPoints.end()) {
2106                if (!(*point)->frameIsAvailable() ||
2107                        !(*point)->transactionIsApplied()) {
2108                    // This sync point must have been added since we started
2109                    // latching. Don't drop it yet.
2110                    ++point;
2111                    continue;
2112                }
2113
2114                if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2115                    point = mLocalSyncPoints.erase(point);
2116                } else {
2117                    ++point;
2118                }
2119            }
2120        }
2121
2122        // FIXME: postedRegion should be dirty & bounds
2123        Region dirtyRegion(Rect(s.active.w, s.active.h));
2124
2125        // transform the dirty region to window-manager space
2126        outDirtyRegion = (s.active.transform.transform(dirtyRegion));
2127    }
2128    return outDirtyRegion;
2129}
2130
2131uint32_t Layer::getEffectiveUsage(uint32_t usage) const
2132{
2133    // TODO: should we do something special if mSecure is set?
2134    if (mProtectedByApp) {
2135        // need a hardware-protected path to external video sink
2136        usage |= GraphicBuffer::USAGE_PROTECTED;
2137    }
2138    if (mPotentialCursor) {
2139        usage |= GraphicBuffer::USAGE_CURSOR;
2140    }
2141    usage |= GraphicBuffer::USAGE_HW_COMPOSER;
2142    return usage;
2143}
2144
2145void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
2146    uint32_t orientation = 0;
2147    if (!mFlinger->mDebugDisableTransformHint) {
2148        // The transform hint is used to improve performance, but we can
2149        // only have a single transform hint, it cannot
2150        // apply to all displays.
2151        const Transform& planeTransform(hw->getTransform());
2152        orientation = planeTransform.getOrientation();
2153        if (orientation & Transform::ROT_INVALID) {
2154            orientation = 0;
2155        }
2156    }
2157    mSurfaceFlingerConsumer->setTransformHint(orientation);
2158}
2159
2160// ----------------------------------------------------------------------------
2161// debugging
2162// ----------------------------------------------------------------------------
2163
2164void Layer::dump(String8& result, Colorizer& colorizer) const
2165{
2166    const Layer::State& s(getDrawingState());
2167
2168    colorizer.colorize(result, Colorizer::GREEN);
2169    result.appendFormat(
2170            "+ %s %p (%s)\n",
2171            getTypeId(), this, getName().string());
2172    colorizer.reset(result);
2173
2174    s.activeTransparentRegion.dump(result, "transparentRegion");
2175    visibleRegion.dump(result, "visibleRegion");
2176    surfaceDamageRegion.dump(result, "surfaceDamageRegion");
2177    sp<Client> client(mClientRef.promote());
2178
2179    result.appendFormat(            "      "
2180            "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2181            "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
2182            "isOpaque=%1d, invalidate=%1d, "
2183#ifdef USE_HWC2
2184            "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2185#else
2186            "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2187#endif
2188            "      client=%p\n",
2189            s.layerStack, s.z, s.active.transform.tx(), s.active.transform.ty(), s.active.w, s.active.h,
2190            s.crop.left, s.crop.top,
2191            s.crop.right, s.crop.bottom,
2192            s.finalCrop.left, s.finalCrop.top,
2193            s.finalCrop.right, s.finalCrop.bottom,
2194            isOpaque(s), contentDirty,
2195            s.alpha, s.flags,
2196            s.active.transform[0][0], s.active.transform[0][1],
2197            s.active.transform[1][0], s.active.transform[1][1],
2198            client.get());
2199
2200    sp<const GraphicBuffer> buf0(mActiveBuffer);
2201    uint32_t w0=0, h0=0, s0=0, f0=0;
2202    if (buf0 != 0) {
2203        w0 = buf0->getWidth();
2204        h0 = buf0->getHeight();
2205        s0 = buf0->getStride();
2206        f0 = buf0->format;
2207    }
2208    result.appendFormat(
2209            "      "
2210            "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2211            " queued-frames=%d, mRefreshPending=%d\n",
2212            mFormat, w0, h0, s0,f0,
2213            mQueuedFrames, mRefreshPending);
2214
2215    if (mSurfaceFlingerConsumer != 0) {
2216        mSurfaceFlingerConsumer->dump(result, "            ");
2217    }
2218}
2219
2220void Layer::dumpFrameStats(String8& result) const {
2221    mFrameTracker.dumpStats(result);
2222}
2223
2224void Layer::clearFrameStats() {
2225    mFrameTracker.clearStats();
2226}
2227
2228void Layer::logFrameStats() {
2229    mFrameTracker.logAndResetStats(mName);
2230}
2231
2232void Layer::getFrameStats(FrameStats* outStats) const {
2233    mFrameTracker.getStats(outStats);
2234}
2235
2236void Layer::getFenceData(String8* outName, uint64_t* outFrameNumber,
2237        bool* outIsGlesComposition, nsecs_t* outPostedTime,
2238        sp<Fence>* outAcquireFence, sp<Fence>* outPrevReleaseFence) const {
2239    *outName = mName;
2240    *outFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2241
2242#ifdef USE_HWC2
2243    *outIsGlesComposition = mHwcLayers.count(HWC_DISPLAY_PRIMARY) ?
2244            mHwcLayers.at(HWC_DISPLAY_PRIMARY).compositionType ==
2245            HWC2::Composition::Client : true;
2246#else
2247    *outIsGlesComposition = mIsGlesComposition;
2248#endif
2249    *outPostedTime = mSurfaceFlingerConsumer->getTimestamp();
2250    *outAcquireFence = mSurfaceFlingerConsumer->getCurrentFence();
2251    *outPrevReleaseFence = mSurfaceFlingerConsumer->getPrevReleaseFence();
2252}
2253
2254std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2255        bool forceFlush) {
2256    std::vector<OccupancyTracker::Segment> history;
2257    status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2258            &history);
2259    if (result != NO_ERROR) {
2260        ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2261                result);
2262        return {};
2263    }
2264    return history;
2265}
2266
2267bool Layer::getTransformToDisplayInverse() const {
2268    return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2269}
2270
2271// ---------------------------------------------------------------------------
2272
2273Layer::LayerCleaner::LayerCleaner(const sp<SurfaceFlinger>& flinger,
2274        const sp<Layer>& layer)
2275    : mFlinger(flinger), mLayer(layer) {
2276}
2277
2278Layer::LayerCleaner::~LayerCleaner() {
2279    // destroy client resources
2280    mFlinger->onLayerDestroyed(mLayer);
2281}
2282
2283// ---------------------------------------------------------------------------
2284}; // namespace android
2285
2286#if defined(__gl_h_)
2287#error "don't include gl/gl.h in this file"
2288#endif
2289
2290#if defined(__gl2_h_)
2291#error "don't include gl2/gl2.h in this file"
2292#endif
2293