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