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