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