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