Layer.cpp revision db66e627ad8904491e384c64f82fc77a939b9705
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/BufferQueue.h>
42#include <gui/Surface.h>
43
44#include "clz.h"
45#include "Colorizer.h"
46#include "DisplayDevice.h"
47#include "Layer.h"
48#include "LayerRejecter.h"
49#include "MonitoredProducer.h"
50#include "SurfaceFlinger.h"
51
52#include "DisplayHardware/HWComposer.h"
53
54#include "RenderEngine/RenderEngine.h"
55
56#include <mutex>
57
58#define DEBUG_RESIZE    0
59
60namespace android {
61
62// ---------------------------------------------------------------------------
63
64int32_t Layer::sSequence = 1;
65
66Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
67        const String8& name, uint32_t w, uint32_t h, uint32_t flags)
68    :   contentDirty(false),
69        sequence(uint32_t(android_atomic_inc(&sSequence))),
70        mFlinger(flinger),
71        mTextureName(-1U),
72        mPremultipliedAlpha(true),
73        mName("unnamed"),
74        mFormat(PIXEL_FORMAT_NONE),
75        mTransactionFlags(0),
76        mPendingStateMutex(),
77        mPendingStates(),
78        mQueuedFrames(0),
79        mSidebandStreamChanged(false),
80        mActiveBufferSlot(BufferQueue::INVALID_BUFFER_SLOT),
81        mCurrentTransform(0),
82        mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
83        mOverrideScalingMode(-1),
84        mCurrentOpacity(true),
85        mBufferLatched(false),
86        mCurrentFrameNumber(0),
87        mPreviousFrameNumber(0),
88        mRefreshPending(false),
89        mFrameLatencyNeeded(false),
90        mFiltering(false),
91        mNeedsFiltering(false),
92        mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
93#ifndef USE_HWC2
94        mIsGlesComposition(false),
95#endif
96        mProtectedByApp(false),
97        mHasSurface(false),
98        mClientRef(client),
99        mPotentialCursor(false),
100        mQueueItemLock(),
101        mQueueItemCondition(),
102        mQueueItems(),
103        mLastFrameNumberReceived(0),
104        mUpdateTexImageFailed(false),
105        mAutoRefresh(false),
106        mFreezePositionUpdates(false)
107{
108#ifdef USE_HWC2
109    ALOGV("Creating Layer %s", name.string());
110#endif
111
112    mCurrentCrop.makeInvalid();
113    mFlinger->getRenderEngine().genTextures(1, &mTextureName);
114    mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
115
116    uint32_t layerFlags = 0;
117    if (flags & ISurfaceComposerClient::eHidden)
118        layerFlags |= layer_state_t::eLayerHidden;
119    if (flags & ISurfaceComposerClient::eOpaque)
120        layerFlags |= layer_state_t::eLayerOpaque;
121    if (flags & ISurfaceComposerClient::eSecure)
122        layerFlags |= layer_state_t::eLayerSecure;
123
124    if (flags & ISurfaceComposerClient::eNonPremultiplied)
125        mPremultipliedAlpha = false;
126
127    mName = name;
128
129    mCurrentState.active.w = w;
130    mCurrentState.active.h = h;
131    mCurrentState.active.transform.set(0, 0);
132    mCurrentState.crop.makeInvalid();
133    mCurrentState.finalCrop.makeInvalid();
134    mCurrentState.z = 0;
135#ifdef USE_HWC2
136    mCurrentState.alpha = 1.0f;
137#else
138    mCurrentState.alpha = 0xFF;
139#endif
140    mCurrentState.layerStack = 0;
141    mCurrentState.flags = layerFlags;
142    mCurrentState.sequence = 0;
143    mCurrentState.requested = mCurrentState.active;
144    mCurrentState.dataSpace = HAL_DATASPACE_UNKNOWN;
145    mCurrentState.appId = 0;
146    mCurrentState.type = 0;
147
148    // drawing state & current state are identical
149    mDrawingState = mCurrentState;
150
151#ifdef USE_HWC2
152    const auto& hwc = flinger->getHwComposer();
153    const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
154    nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
155#else
156    nsecs_t displayPeriod =
157            flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
158#endif
159    mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
160
161    CompositorTiming compositorTiming;
162    flinger->getCompositorTiming(&compositorTiming);
163    mFrameEventHistory.initializeCompositorTiming(compositorTiming);
164}
165
166void Layer::onFirstRef() {
167    // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
168    sp<IGraphicBufferProducer> producer;
169    sp<IGraphicBufferConsumer> consumer;
170    BufferQueue::createBufferQueue(&producer, &consumer, nullptr, true);
171    mProducer = new MonitoredProducer(producer, mFlinger, this);
172    mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
173    mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
174    mSurfaceFlingerConsumer->setContentsChangedListener(this);
175    mSurfaceFlingerConsumer->setName(mName);
176
177    if (mFlinger->isLayerTripleBufferingDisabled()) {
178        mProducer->setMaxDequeuedBufferCount(2);
179    }
180
181    const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
182    updateTransformHint(hw);
183}
184
185Layer::~Layer() {
186  sp<Client> c(mClientRef.promote());
187    if (c != 0) {
188        c->detachLayer(this);
189    }
190
191    for (auto& point : mRemoteSyncPoints) {
192        point->setTransactionApplied();
193    }
194    for (auto& point : mLocalSyncPoints) {
195        point->setFrameAvailable();
196    }
197    mFlinger->deleteTextureAsync(mTextureName);
198    mFrameTracker.logAndResetStats(mName);
199}
200
201// ---------------------------------------------------------------------------
202// callbacks
203// ---------------------------------------------------------------------------
204
205#ifdef USE_HWC2
206void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
207    if (mHwcLayers.empty()) {
208        return;
209    }
210    mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
211}
212#else
213void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
214        HWComposer::HWCLayerInterface* layer) {
215    if (layer) {
216        layer->onDisplayed();
217        mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
218    }
219}
220#endif
221
222void Layer::onFrameAvailable(const BufferItem& item) {
223    // Add this buffer from our internal queue tracker
224    { // Autolock scope
225        Mutex::Autolock lock(mQueueItemLock);
226        mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
227                item.mGraphicBuffer->getHeight(), item.mFrameNumber);
228        // Reset the frame number tracker when we receive the first buffer after
229        // a frame number reset
230        if (item.mFrameNumber == 1) {
231            mLastFrameNumberReceived = 0;
232        }
233
234        // Ensure that callbacks are handled in order
235        while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
236            status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
237                    ms2ns(500));
238            if (result != NO_ERROR) {
239                ALOGE("[%s] Timed out waiting on callback", mName.string());
240            }
241        }
242
243        mQueueItems.push_back(item);
244        android_atomic_inc(&mQueuedFrames);
245
246        // Wake up any pending callbacks
247        mLastFrameNumberReceived = item.mFrameNumber;
248        mQueueItemCondition.broadcast();
249    }
250
251    mFlinger->signalLayerUpdate();
252}
253
254void Layer::onFrameReplaced(const BufferItem& item) {
255    { // Autolock scope
256        Mutex::Autolock lock(mQueueItemLock);
257
258        // Ensure that callbacks are handled in order
259        while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
260            status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
261                    ms2ns(500));
262            if (result != NO_ERROR) {
263                ALOGE("[%s] Timed out waiting on callback", mName.string());
264            }
265        }
266
267        if (mQueueItems.empty()) {
268            ALOGE("Can't replace a frame on an empty queue");
269            return;
270        }
271        mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
272
273        // Wake up any pending callbacks
274        mLastFrameNumberReceived = item.mFrameNumber;
275        mQueueItemCondition.broadcast();
276    }
277}
278
279void Layer::onSidebandStreamChanged() {
280    if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
281        // mSidebandStreamChanged was false
282        mFlinger->signalLayerUpdate();
283    }
284}
285
286// called with SurfaceFlinger::mStateLock from the drawing thread after
287// the layer has been remove from the current state list (and just before
288// it's removed from the drawing state list)
289void Layer::onRemoved() {
290    mSurfaceFlingerConsumer->abandon();
291    for (const auto& child : mCurrentChildren) {
292        child->onRemoved();
293    }
294}
295
296// ---------------------------------------------------------------------------
297// set-up
298// ---------------------------------------------------------------------------
299
300const String8& Layer::getName() const {
301    return mName;
302}
303
304status_t Layer::setBuffers( uint32_t w, uint32_t h,
305                            PixelFormat format, uint32_t flags)
306{
307    uint32_t const maxSurfaceDims = min(
308            mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
309
310    // never allow a surface larger than what our underlying GL implementation
311    // can handle.
312    if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
313        ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
314        return BAD_VALUE;
315    }
316
317    mFormat = format;
318
319    mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
320    mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
321    mCurrentOpacity = getOpacityForFormat(format);
322
323    mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
324    mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
325    mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
326
327    return NO_ERROR;
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::computeScreenBounds(bool reduceTransparentRegion) const {
377    const Layer::State& s(getDrawingState());
378    Rect win(s.active.w, s.active.h);
379
380    if (!s.crop.isEmpty()) {
381        win.intersect(s.crop, &win);
382    }
383
384    Transform t = getTransform();
385    win = t.transform(win);
386
387    const sp<Layer>& p = getParent();
388    // Now we need to calculate the parent bounds, so we can clip ourselves to those.
389    // When calculating the parent bounds for purposes of clipping,
390    // we don't need to constrain the parent to its transparent region.
391    // The transparent region is an optimization based on the
392    // buffer contents of the layer, but does not affect the space allocated to
393    // it by policy, and thus children should be allowed to extend into the
394    // parent's transparent region. In fact one of the main uses, is to reduce
395    // buffer allocation size in cases where a child window sits behind a main window
396    // (by marking the hole in the parent window as a transparent region)
397    if (p != nullptr) {
398        Rect bounds = p->computeScreenBounds(false);
399        bounds.intersect(win, &win);
400    }
401
402    if (reduceTransparentRegion) {
403        auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
404        win = reduce(win, screenTransparentRegion);
405    }
406
407    return win;
408}
409
410Rect Layer::computeBounds() const {
411    const Layer::State& s(getDrawingState());
412    return computeBounds(s.activeTransparentRegion);
413}
414
415Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
416    const Layer::State& s(getDrawingState());
417    Rect win(s.active.w, s.active.h);
418
419    if (!s.crop.isEmpty()) {
420        win.intersect(s.crop, &win);
421    }
422
423    Rect bounds = win;
424    const auto& p = getParent();
425    if (p != nullptr) {
426        // Look in computeScreenBounds recursive call for explanation of
427        // why we pass false here.
428        bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
429    }
430
431    Transform t = getTransform();
432    if (p != nullptr) {
433        win = t.transform(win);
434        win.intersect(bounds, &win);
435        win = t.inverse().transform(win);
436    }
437
438    // subtract the transparent region and snap to the bounds
439    return reduce(win, activeTransparentRegion);
440}
441
442Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
443    // the crop is the area of the window that gets cropped, but not
444    // scaled in any ways.
445    const State& s(getDrawingState());
446
447    // apply the projection's clipping to the window crop in
448    // layerstack space, and convert-back to layer space.
449    // if there are no window scaling involved, this operation will map to full
450    // pixels in the buffer.
451    // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
452    // a viewport clipping and a window transform. we should use floating point to fix this.
453
454    Rect activeCrop(s.active.w, s.active.h);
455    if (!s.crop.isEmpty()) {
456        activeCrop = s.crop;
457    }
458
459    Transform t = getTransform();
460    activeCrop = t.transform(activeCrop);
461    if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
462        activeCrop.clear();
463    }
464    if (!s.finalCrop.isEmpty()) {
465        if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
466            activeCrop.clear();
467        }
468    }
469    return activeCrop;
470}
471
472FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
473    // the content crop is the area of the content that gets scaled to the
474    // layer's size. This is in buffer space.
475    FloatRect crop = getContentCrop().toFloatRect();
476
477    // In addition there is a WM-specified crop we pull from our drawing state.
478    const State& s(getDrawingState());
479
480    // Screen space to make reduction to parent crop clearer.
481    Rect activeCrop = computeInitialCrop(hw);
482    const auto& p = getParent();
483    if (p != nullptr) {
484        auto parentCrop = p->computeInitialCrop(hw);
485        activeCrop.intersect(parentCrop, &activeCrop);
486    }
487    Transform t = getTransform();
488    // Back to layer space to work with the content crop.
489    activeCrop = t.inverse().transform(activeCrop);
490
491    // This needs to be here as transform.transform(Rect) computes the
492    // transformed rect and then takes the bounding box of the result before
493    // returning. This means
494    // transform.inverse().transform(transform.transform(Rect)) != Rect
495    // in which case we need to make sure the final rect is clipped to the
496    // display bounds.
497    if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
498        activeCrop.clear();
499    }
500
501    // subtract the transparent region and snap to the bounds
502    activeCrop = reduce(activeCrop, s.activeTransparentRegion);
503
504    // Transform the window crop to match the buffer coordinate system,
505    // which means using the inverse of the current transform set on the
506    // SurfaceFlingerConsumer.
507    uint32_t invTransform = mCurrentTransform;
508    if (getTransformToDisplayInverse()) {
509        /*
510         * the code below applies the primary display's inverse transform to the
511         * buffer
512         */
513        uint32_t invTransformOrient =
514                DisplayDevice::getPrimaryDisplayOrientationTransform();
515        // calculate the inverse transform
516        if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
517            invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
518                    NATIVE_WINDOW_TRANSFORM_FLIP_H;
519        }
520        // and apply to the current transform
521        invTransform = (Transform(invTransformOrient) * Transform(invTransform))
522                .getOrientation();
523    }
524
525    int winWidth = s.active.w;
526    int winHeight = s.active.h;
527    if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
528        // If the activeCrop has been rotate the ends are rotated but not
529        // the space itself so when transforming ends back we can't rely on
530        // a modification of the axes of rotation. To account for this we
531        // need to reorient the inverse rotation in terms of the current
532        // axes of rotation.
533        bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
534        bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
535        if (is_h_flipped == is_v_flipped) {
536            invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
537                    NATIVE_WINDOW_TRANSFORM_FLIP_H;
538        }
539        winWidth = s.active.h;
540        winHeight = s.active.w;
541    }
542    const Rect winCrop = activeCrop.transform(
543            invTransform, s.active.w, s.active.h);
544
545    // below, crop is intersected with winCrop expressed in crop's coordinate space
546    float xScale = crop.getWidth()  / float(winWidth);
547    float yScale = crop.getHeight() / float(winHeight);
548
549    float insetL = winCrop.left                 * xScale;
550    float insetT = winCrop.top                  * yScale;
551    float insetR = (winWidth - winCrop.right )  * xScale;
552    float insetB = (winHeight - winCrop.bottom) * yScale;
553
554    crop.left   += insetL;
555    crop.top    += insetT;
556    crop.right  -= insetR;
557    crop.bottom -= insetB;
558
559    return crop;
560}
561
562#ifdef USE_HWC2
563void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
564#else
565void Layer::setGeometry(
566    const sp<const DisplayDevice>& hw,
567        HWComposer::HWCLayerInterface& layer)
568#endif
569{
570#ifdef USE_HWC2
571    const auto hwcId = displayDevice->getHwcDisplayId();
572    auto& hwcInfo = mHwcLayers[hwcId];
573#else
574    layer.setDefaultState();
575#endif
576
577    // enable this layer
578#ifdef USE_HWC2
579    hwcInfo.forceClientComposition = false;
580
581    if (isSecure() && !displayDevice->isSecure()) {
582        hwcInfo.forceClientComposition = true;
583    }
584
585    auto& hwcLayer = hwcInfo.layer;
586#else
587    layer.setSkip(false);
588
589    if (isSecure() && !hw->isSecure()) {
590        layer.setSkip(true);
591    }
592#endif
593
594    // this gives us only the "orientation" component of the transform
595    const State& s(getDrawingState());
596#ifdef USE_HWC2
597    auto blendMode = HWC2::BlendMode::None;
598    if (!isOpaque(s) || getAlpha() != 1.0f) {
599        blendMode = mPremultipliedAlpha ?
600                HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
601    }
602    auto error = hwcLayer->setBlendMode(blendMode);
603    ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
604             " %s (%d)", mName.string(), to_string(blendMode).c_str(),
605             to_string(error).c_str(), static_cast<int32_t>(error));
606#else
607    if (!isOpaque(s) || getAlpha() != 0xFF) {
608        layer.setBlending(mPremultipliedAlpha ?
609                HWC_BLENDING_PREMULT :
610                HWC_BLENDING_COVERAGE);
611    }
612#endif
613
614    // apply the layer's transform, followed by the display's global transform
615    // here we're guaranteed that the layer's transform preserves rects
616    Region activeTransparentRegion(s.activeTransparentRegion);
617    Transform t = getTransform();
618    if (!s.crop.isEmpty()) {
619        Rect activeCrop(s.crop);
620        activeCrop = t.transform(activeCrop);
621#ifdef USE_HWC2
622        if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
623#else
624        if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
625#endif
626            activeCrop.clear();
627        }
628        activeCrop = t.inverse().transform(activeCrop, true);
629        // This needs to be here as transform.transform(Rect) computes the
630        // transformed rect and then takes the bounding box of the result before
631        // returning. This means
632        // transform.inverse().transform(transform.transform(Rect)) != Rect
633        // in which case we need to make sure the final rect is clipped to the
634        // display bounds.
635        if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
636            activeCrop.clear();
637        }
638        // mark regions outside the crop as transparent
639        activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
640        activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
641                s.active.w, s.active.h));
642        activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
643                activeCrop.left, activeCrop.bottom));
644        activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
645                s.active.w, activeCrop.bottom));
646    }
647
648    Rect frame(t.transform(computeBounds(activeTransparentRegion)));
649    if (!s.finalCrop.isEmpty()) {
650        if(!frame.intersect(s.finalCrop, &frame)) {
651            frame.clear();
652        }
653    }
654#ifdef USE_HWC2
655    if (!frame.intersect(displayDevice->getViewport(), &frame)) {
656        frame.clear();
657    }
658    const Transform& tr(displayDevice->getTransform());
659    Rect transformedFrame = tr.transform(frame);
660    error = hwcLayer->setDisplayFrame(transformedFrame);
661    if (error != HWC2::Error::None) {
662        ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
663                mName.string(), transformedFrame.left, transformedFrame.top,
664                transformedFrame.right, transformedFrame.bottom,
665                to_string(error).c_str(), static_cast<int32_t>(error));
666    } else {
667        hwcInfo.displayFrame = transformedFrame;
668    }
669
670    FloatRect sourceCrop = computeCrop(displayDevice);
671    error = hwcLayer->setSourceCrop(sourceCrop);
672    if (error != HWC2::Error::None) {
673        ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
674                "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
675                sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
676                static_cast<int32_t>(error));
677    } else {
678        hwcInfo.sourceCrop = sourceCrop;
679    }
680
681    float alpha = getAlpha();
682    error = hwcLayer->setPlaneAlpha(alpha);
683    ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
684            "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
685            static_cast<int32_t>(error));
686
687    error = hwcLayer->setZOrder(z);
688    ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
689            mName.string(), z, to_string(error).c_str(),
690            static_cast<int32_t>(error));
691
692    error = hwcLayer->setInfo(s.type, s.appId);
693    ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
694             mName.string(), static_cast<int32_t>(error));
695#else
696    if (!frame.intersect(hw->getViewport(), &frame)) {
697        frame.clear();
698    }
699    const Transform& tr(hw->getTransform());
700    layer.setFrame(tr.transform(frame));
701    layer.setCrop(computeCrop(hw));
702    layer.setPlaneAlpha(getAlpha());
703#endif
704
705    /*
706     * Transformations are applied in this order:
707     * 1) buffer orientation/flip/mirror
708     * 2) state transformation (window manager)
709     * 3) layer orientation (screen orientation)
710     * (NOTE: the matrices are multiplied in reverse order)
711     */
712
713    const Transform bufferOrientation(mCurrentTransform);
714    Transform transform(tr * t * bufferOrientation);
715
716    if (getTransformToDisplayInverse()) {
717        /*
718         * the code below applies the primary display's inverse transform to the
719         * buffer
720         */
721        uint32_t invTransform =
722                DisplayDevice::getPrimaryDisplayOrientationTransform();
723        // calculate the inverse transform
724        if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
725            invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
726                    NATIVE_WINDOW_TRANSFORM_FLIP_H;
727        }
728
729        /*
730         * Here we cancel out the orientation component of the WM transform.
731         * The scaling and translate components are already included in our bounds
732         * computation so it's enough to just omit it in the composition.
733         * See comment in onDraw with ref to b/36727915 for why.
734         */
735        transform = Transform(invTransform) * tr * bufferOrientation;
736    }
737
738    // this gives us only the "orientation" component of the transform
739    const uint32_t orientation = transform.getOrientation();
740#ifdef USE_HWC2
741    if (orientation & Transform::ROT_INVALID) {
742        // we can only handle simple transformation
743        hwcInfo.forceClientComposition = true;
744    } else {
745        auto transform = static_cast<HWC2::Transform>(orientation);
746        auto error = hwcLayer->setTransform(transform);
747        ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
748                "%s (%d)", mName.string(), to_string(transform).c_str(),
749                to_string(error).c_str(), static_cast<int32_t>(error));
750    }
751#else
752    if (orientation & Transform::ROT_INVALID) {
753        // we can only handle simple transformation
754        layer.setSkip(true);
755    } else {
756        layer.setTransform(orientation);
757    }
758#endif
759}
760
761#ifdef USE_HWC2
762void Layer::forceClientComposition(int32_t hwcId) {
763    if (mHwcLayers.count(hwcId) == 0) {
764        ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
765        return;
766    }
767
768    mHwcLayers[hwcId].forceClientComposition = true;
769}
770
771void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
772    // Apply this display's projection's viewport to the visible region
773    // before giving it to the HWC HAL.
774    const Transform& tr = displayDevice->getTransform();
775    const auto& viewport = displayDevice->getViewport();
776    Region visible = tr.transform(visibleRegion.intersect(viewport));
777    auto hwcId = displayDevice->getHwcDisplayId();
778    auto& hwcInfo = mHwcLayers[hwcId];
779    auto& hwcLayer = hwcInfo.layer;
780    auto error = hwcLayer->setVisibleRegion(visible);
781    if (error != HWC2::Error::None) {
782        ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
783                to_string(error).c_str(), static_cast<int32_t>(error));
784        visible.dump(LOG_TAG);
785    }
786
787    error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
788    if (error != HWC2::Error::None) {
789        ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
790                to_string(error).c_str(), static_cast<int32_t>(error));
791        surfaceDamageRegion.dump(LOG_TAG);
792    }
793
794    // Sideband layers
795    if (mSidebandStream.get()) {
796        setCompositionType(hwcId, HWC2::Composition::Sideband);
797        ALOGV("[%s] Requesting Sideband composition", mName.string());
798        error = hwcLayer->setSidebandStream(mSidebandStream->handle());
799        if (error != HWC2::Error::None) {
800            ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
801                    mName.string(), mSidebandStream->handle(),
802                    to_string(error).c_str(), static_cast<int32_t>(error));
803        }
804        return;
805    }
806
807    // Client layers
808    if (hwcInfo.forceClientComposition ||
809            (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
810        ALOGV("[%s] Requesting Client composition", mName.string());
811        setCompositionType(hwcId, HWC2::Composition::Client);
812        return;
813    }
814
815    // SolidColor layers
816    if (mActiveBuffer == nullptr) {
817        setCompositionType(hwcId, HWC2::Composition::SolidColor);
818
819        // For now, we only support black for DimLayer
820        error = hwcLayer->setColor({0, 0, 0, 255});
821        if (error != HWC2::Error::None) {
822            ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
823                    to_string(error).c_str(), static_cast<int32_t>(error));
824        }
825
826        // Clear out the transform, because it doesn't make sense absent a
827        // source buffer
828        error = hwcLayer->setTransform(HWC2::Transform::None);
829        if (error != HWC2::Error::None) {
830            ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
831                    to_string(error).c_str(), static_cast<int32_t>(error));
832        }
833
834        return;
835    }
836
837    // Device or Cursor layers
838    if (mPotentialCursor) {
839        ALOGV("[%s] Requesting Cursor composition", mName.string());
840        setCompositionType(hwcId, HWC2::Composition::Cursor);
841    } else {
842        ALOGV("[%s] Requesting Device composition", mName.string());
843        setCompositionType(hwcId, HWC2::Composition::Device);
844    }
845
846    ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
847    error = hwcLayer->setDataspace(mCurrentState.dataSpace);
848    if (error != HWC2::Error::None) {
849        ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
850              mCurrentState.dataSpace, to_string(error).c_str(),
851              static_cast<int32_t>(error));
852    }
853
854    uint32_t hwcSlot = 0;
855    buffer_handle_t hwcHandle = nullptr;
856    {
857        sp<GraphicBuffer> hwcBuffer;
858        hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
859                &hwcSlot, &hwcBuffer);
860        if (hwcBuffer != nullptr) {
861            hwcHandle = hwcBuffer->handle;
862        }
863    }
864
865    auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
866    error = hwcLayer->setBuffer(hwcSlot, hwcHandle, acquireFence);
867    if (error != HWC2::Error::None) {
868        ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
869                mActiveBuffer->handle, to_string(error).c_str(),
870                static_cast<int32_t>(error));
871    }
872}
873
874android_dataspace Layer::getDataSpace() const {
875    return mCurrentState.dataSpace;
876}
877#else
878void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
879        HWComposer::HWCLayerInterface& layer) {
880    // we have to set the visible region on every frame because
881    // we currently free it during onLayerDisplayed(), which is called
882    // after HWComposer::commit() -- every frame.
883    // Apply this display's projection's viewport to the visible region
884    // before giving it to the HWC HAL.
885    const Transform& tr = hw->getTransform();
886    Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
887    layer.setVisibleRegionScreen(visible);
888    layer.setSurfaceDamage(surfaceDamageRegion);
889    mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
890
891    if (mSidebandStream.get()) {
892        layer.setSidebandStream(mSidebandStream);
893    } else {
894        // NOTE: buffer can be NULL if the client never drew into this
895        // layer yet, or if we ran out of memory
896        layer.setBuffer(mActiveBuffer);
897    }
898}
899#endif
900
901#ifdef USE_HWC2
902void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
903    auto hwcId = displayDevice->getHwcDisplayId();
904    if (mHwcLayers.count(hwcId) == 0 ||
905            getCompositionType(hwcId) != HWC2::Composition::Cursor) {
906        return;
907    }
908
909    // This gives us only the "orientation" component of the transform
910    const State& s(getCurrentState());
911
912    // Apply the layer's transform, followed by the display's global transform
913    // Here we're guaranteed that the layer's transform preserves rects
914    Rect win(s.active.w, s.active.h);
915    if (!s.crop.isEmpty()) {
916        win.intersect(s.crop, &win);
917    }
918    // Subtract the transparent region and snap to the bounds
919    Rect bounds = reduce(win, s.activeTransparentRegion);
920    Rect frame(getTransform().transform(bounds));
921    frame.intersect(displayDevice->getViewport(), &frame);
922    if (!s.finalCrop.isEmpty()) {
923        frame.intersect(s.finalCrop, &frame);
924    }
925    auto& displayTransform(displayDevice->getTransform());
926    auto position = displayTransform.transform(frame);
927
928    auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
929            position.top);
930    ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
931            "to (%d, %d): %s (%d)", mName.string(), position.left,
932            position.top, to_string(error).c_str(),
933            static_cast<int32_t>(error));
934}
935#else
936void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
937        HWComposer::HWCLayerInterface& layer) {
938    int fenceFd = -1;
939
940    // TODO: there is a possible optimization here: we only need to set the
941    // acquire fence the first time a new buffer is acquired on EACH display.
942
943    if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
944        sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
945        if (fence->isValid()) {
946            fenceFd = fence->dup();
947            if (fenceFd == -1) {
948                ALOGW("failed to dup layer fence, skipping sync: %d", errno);
949            }
950        }
951    }
952    layer.setAcquireFenceFd(fenceFd);
953}
954
955Rect Layer::getPosition(
956    const sp<const DisplayDevice>& hw)
957{
958    // this gives us only the "orientation" component of the transform
959    const State& s(getCurrentState());
960
961    // apply the layer's transform, followed by the display's global transform
962    // here we're guaranteed that the layer's transform preserves rects
963    Rect win(s.active.w, s.active.h);
964    if (!s.crop.isEmpty()) {
965        win.intersect(s.crop, &win);
966    }
967    // subtract the transparent region and snap to the bounds
968    Rect bounds = reduce(win, s.activeTransparentRegion);
969    Rect frame(getTransform().transform(bounds));
970    frame.intersect(hw->getViewport(), &frame);
971    if (!s.finalCrop.isEmpty()) {
972        frame.intersect(s.finalCrop, &frame);
973    }
974    const Transform& tr(hw->getTransform());
975    return Rect(tr.transform(frame));
976}
977#endif
978
979// ---------------------------------------------------------------------------
980// drawing...
981// ---------------------------------------------------------------------------
982
983void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
984    onDraw(hw, clip, false);
985}
986
987void Layer::draw(const sp<const DisplayDevice>& hw,
988        bool useIdentityTransform) const {
989    onDraw(hw, Region(hw->bounds()), useIdentityTransform);
990}
991
992void Layer::draw(const sp<const DisplayDevice>& hw) const {
993    onDraw(hw, Region(hw->bounds()), false);
994}
995
996static constexpr mat4 inverseOrientation(uint32_t transform) {
997    const mat4 flipH(-1,0,0,0,  0,1,0,0, 0,0,1,0, 1,0,0,1);
998    const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
999    const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1000    mat4 tr;
1001
1002    if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1003        tr = tr * rot90;
1004    }
1005    if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1006        tr = tr * flipH;
1007    }
1008    if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1009        tr = tr * flipV;
1010    }
1011    return inverse(tr);
1012}
1013
1014/*
1015 * onDraw will draw the current layer onto the presentable buffer
1016 */
1017void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1018        bool useIdentityTransform) const
1019{
1020    ATRACE_CALL();
1021
1022    if (CC_UNLIKELY(mActiveBuffer == 0)) {
1023        // the texture has not been created yet, this Layer has
1024        // in fact never been drawn into. This happens frequently with
1025        // SurfaceView because the WindowManager can't know when the client
1026        // has drawn the first time.
1027
1028        // If there is nothing under us, we paint the screen in black, otherwise
1029        // we just skip this update.
1030
1031        // figure out if there is something below us
1032        Region under;
1033        bool finished = false;
1034        mFlinger->mDrawingState.layersSortedByZ.traverseInZOrder([&](Layer* layer) {
1035            if (finished || layer == static_cast<Layer const*>(this)) {
1036                finished = true;
1037                return;
1038            }
1039            under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
1040        });
1041        // if not everything below us is covered, we plug the holes!
1042        Region holes(clip.subtract(under));
1043        if (!holes.isEmpty()) {
1044            clearWithOpenGL(hw, 0, 0, 0, 1);
1045        }
1046        return;
1047    }
1048
1049    // Bind the current buffer to the GL texture, and wait for it to be
1050    // ready for us to draw into.
1051    status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1052    if (err != NO_ERROR) {
1053        ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
1054        // Go ahead and draw the buffer anyway; no matter what we do the screen
1055        // is probably going to have something visibly wrong.
1056    }
1057
1058    bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1059
1060    RenderEngine& engine(mFlinger->getRenderEngine());
1061
1062    if (!blackOutLayer) {
1063        // TODO: we could be more subtle with isFixedSize()
1064        const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
1065
1066        // Query the texture matrix given our current filtering mode.
1067        float textureMatrix[16];
1068        mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1069        mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
1070
1071        if (getTransformToDisplayInverse()) {
1072
1073            /*
1074             * the code below applies the primary display's inverse transform to
1075             * the texture transform
1076             */
1077            uint32_t transform =
1078                    DisplayDevice::getPrimaryDisplayOrientationTransform();
1079            mat4 tr = inverseOrientation(transform);
1080
1081            /**
1082             * TODO(b/36727915): This is basically a hack.
1083             *
1084             * Ensure that regardless of the parent transformation,
1085             * this buffer is always transformed from native display
1086             * orientation to display orientation. For example, in the case
1087             * of a camera where the buffer remains in native orientation,
1088             * we want the pixels to always be upright.
1089             */
1090            if (getParent() != nullptr) {
1091                const auto parentTransform = getParent()->getTransform();
1092                tr = tr * inverseOrientation(parentTransform.getOrientation());
1093            }
1094
1095            // and finally apply it to the original texture matrix
1096            const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1097            memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1098        }
1099
1100        // Set things up for texturing.
1101        mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1102        mTexture.setFiltering(useFiltering);
1103        mTexture.setMatrix(textureMatrix);
1104
1105        engine.setupLayerTexturing(mTexture);
1106    } else {
1107        engine.setupLayerBlackedOut();
1108    }
1109    drawWithOpenGL(hw, useIdentityTransform);
1110    engine.disableTexturing();
1111}
1112
1113
1114void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
1115        float red, float green, float blue,
1116        float alpha) const
1117{
1118    RenderEngine& engine(mFlinger->getRenderEngine());
1119    computeGeometry(hw, mMesh, false);
1120    engine.setupFillWithColor(red, green, blue, alpha);
1121    engine.drawMesh(mMesh);
1122}
1123
1124void Layer::clearWithOpenGL(
1125        const sp<const DisplayDevice>& hw) const {
1126    clearWithOpenGL(hw, 0,0,0,0);
1127}
1128
1129void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
1130        bool useIdentityTransform) const {
1131    const State& s(getDrawingState());
1132
1133    computeGeometry(hw, mMesh, useIdentityTransform);
1134
1135    /*
1136     * NOTE: the way we compute the texture coordinates here produces
1137     * different results than when we take the HWC path -- in the later case
1138     * the "source crop" is rounded to texel boundaries.
1139     * This can produce significantly different results when the texture
1140     * is scaled by a large amount.
1141     *
1142     * The GL code below is more logical (imho), and the difference with
1143     * HWC is due to a limitation of the HWC API to integers -- a question
1144     * is suspend is whether we should ignore this problem or revert to
1145     * GL composition when a buffer scaling is applied (maybe with some
1146     * minimal value)? Or, we could make GL behave like HWC -- but this feel
1147     * like more of a hack.
1148     */
1149    Rect win(computeBounds());
1150
1151    Transform t = getTransform();
1152    if (!s.finalCrop.isEmpty()) {
1153        win = t.transform(win);
1154        if (!win.intersect(s.finalCrop, &win)) {
1155            win.clear();
1156        }
1157        win = t.inverse().transform(win);
1158        if (!win.intersect(computeBounds(), &win)) {
1159            win.clear();
1160        }
1161    }
1162
1163    float left   = float(win.left)   / float(s.active.w);
1164    float top    = float(win.top)    / float(s.active.h);
1165    float right  = float(win.right)  / float(s.active.w);
1166    float bottom = float(win.bottom) / float(s.active.h);
1167
1168    // TODO: we probably want to generate the texture coords with the mesh
1169    // here we assume that we only have 4 vertices
1170    Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1171    texCoords[0] = vec2(left, 1.0f - top);
1172    texCoords[1] = vec2(left, 1.0f - bottom);
1173    texCoords[2] = vec2(right, 1.0f - bottom);
1174    texCoords[3] = vec2(right, 1.0f - top);
1175
1176    RenderEngine& engine(mFlinger->getRenderEngine());
1177    engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
1178#ifdef USE_HWC2
1179    engine.setSourceDataSpace(mCurrentState.dataSpace);
1180#endif
1181    engine.drawMesh(mMesh);
1182    engine.disableBlending();
1183}
1184
1185#ifdef USE_HWC2
1186void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1187        bool callIntoHwc) {
1188    if (mHwcLayers.count(hwcId) == 0) {
1189        ALOGE("setCompositionType called without a valid HWC layer");
1190        return;
1191    }
1192    auto& hwcInfo = mHwcLayers[hwcId];
1193    auto& hwcLayer = hwcInfo.layer;
1194    ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1195            to_string(type).c_str(), static_cast<int>(callIntoHwc));
1196    if (hwcInfo.compositionType != type) {
1197        ALOGV("    actually setting");
1198        hwcInfo.compositionType = type;
1199        if (callIntoHwc) {
1200            auto error = hwcLayer->setCompositionType(type);
1201            ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1202                    "composition type %s: %s (%d)", mName.string(),
1203                    to_string(type).c_str(), to_string(error).c_str(),
1204                    static_cast<int32_t>(error));
1205        }
1206    }
1207}
1208
1209HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
1210    if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1211        // If we're querying the composition type for a display that does not
1212        // have a HWC counterpart, then it will always be Client
1213        return HWC2::Composition::Client;
1214    }
1215    if (mHwcLayers.count(hwcId) == 0) {
1216        ALOGE("getCompositionType called with an invalid HWC layer");
1217        return HWC2::Composition::Invalid;
1218    }
1219    return mHwcLayers.at(hwcId).compositionType;
1220}
1221
1222void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1223    if (mHwcLayers.count(hwcId) == 0) {
1224        ALOGE("setClearClientTarget called without a valid HWC layer");
1225        return;
1226    }
1227    mHwcLayers[hwcId].clearClientTarget = clear;
1228}
1229
1230bool Layer::getClearClientTarget(int32_t hwcId) const {
1231    if (mHwcLayers.count(hwcId) == 0) {
1232        ALOGE("getClearClientTarget called without a valid HWC layer");
1233        return false;
1234    }
1235    return mHwcLayers.at(hwcId).clearClientTarget;
1236}
1237#endif
1238
1239uint32_t Layer::getProducerStickyTransform() const {
1240    int producerStickyTransform = 0;
1241    int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1242    if (ret != OK) {
1243        ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1244                strerror(-ret), ret);
1245        return 0;
1246    }
1247    return static_cast<uint32_t>(producerStickyTransform);
1248}
1249
1250bool Layer::latchUnsignaledBuffers() {
1251    static bool propertyLoaded = false;
1252    static bool latch = false;
1253    static std::mutex mutex;
1254    std::lock_guard<std::mutex> lock(mutex);
1255    if (!propertyLoaded) {
1256        char value[PROPERTY_VALUE_MAX] = {};
1257        property_get("debug.sf.latch_unsignaled", value, "0");
1258        latch = atoi(value);
1259        propertyLoaded = true;
1260    }
1261    return latch;
1262}
1263
1264uint64_t Layer::getHeadFrameNumber() const {
1265    Mutex::Autolock lock(mQueueItemLock);
1266    if (!mQueueItems.empty()) {
1267        return mQueueItems[0].mFrameNumber;
1268    } else {
1269        return mCurrentFrameNumber;
1270    }
1271}
1272
1273bool Layer::headFenceHasSignaled() const {
1274#ifdef USE_HWC2
1275    if (latchUnsignaledBuffers()) {
1276        return true;
1277    }
1278
1279    Mutex::Autolock lock(mQueueItemLock);
1280    if (mQueueItems.empty()) {
1281        return true;
1282    }
1283    if (mQueueItems[0].mIsDroppable) {
1284        // Even though this buffer's fence may not have signaled yet, it could
1285        // be replaced by another buffer before it has a chance to, which means
1286        // that it's possible to get into a situation where a buffer is never
1287        // able to be latched. To avoid this, grab this buffer anyway.
1288        return true;
1289    }
1290    return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
1291#else
1292    return true;
1293#endif
1294}
1295
1296bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1297    if (point->getFrameNumber() <= mCurrentFrameNumber) {
1298        // Don't bother with a SyncPoint, since we've already latched the
1299        // relevant frame
1300        return false;
1301    }
1302
1303    Mutex::Autolock lock(mLocalSyncPointMutex);
1304    mLocalSyncPoints.push_back(point);
1305    return true;
1306}
1307
1308void Layer::setFiltering(bool filtering) {
1309    mFiltering = filtering;
1310}
1311
1312bool Layer::getFiltering() const {
1313    return mFiltering;
1314}
1315
1316// As documented in libhardware header, formats in the range
1317// 0x100 - 0x1FF are specific to the HAL implementation, and
1318// are known to have no alpha channel
1319// TODO: move definition for device-specific range into
1320// hardware.h, instead of using hard-coded values here.
1321#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1322
1323bool Layer::getOpacityForFormat(uint32_t format) {
1324    if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1325        return true;
1326    }
1327    switch (format) {
1328        case HAL_PIXEL_FORMAT_RGBA_8888:
1329        case HAL_PIXEL_FORMAT_BGRA_8888:
1330        case HAL_PIXEL_FORMAT_RGBA_FP16:
1331        case HAL_PIXEL_FORMAT_RGBA_1010102:
1332            return false;
1333    }
1334    // in all other case, we have no blending (also for unknown formats)
1335    return true;
1336}
1337
1338// ----------------------------------------------------------------------------
1339// local state
1340// ----------------------------------------------------------------------------
1341
1342static void boundPoint(vec2* point, const Rect& crop) {
1343    if (point->x < crop.left) {
1344        point->x = crop.left;
1345    }
1346    if (point->x > crop.right) {
1347        point->x = crop.right;
1348    }
1349    if (point->y < crop.top) {
1350        point->y = crop.top;
1351    }
1352    if (point->y > crop.bottom) {
1353        point->y = crop.bottom;
1354    }
1355}
1356
1357void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1358        bool useIdentityTransform) const
1359{
1360    const Layer::State& s(getDrawingState());
1361    const Transform hwTransform(hw->getTransform());
1362    const uint32_t hw_h = hw->getHeight();
1363    Rect win = computeBounds();
1364
1365    vec2 lt = vec2(win.left, win.top);
1366    vec2 lb = vec2(win.left, win.bottom);
1367    vec2 rb = vec2(win.right, win.bottom);
1368    vec2 rt = vec2(win.right, win.top);
1369
1370    Transform layerTransform = getTransform();
1371    if (!useIdentityTransform) {
1372        lt = layerTransform.transform(lt);
1373        lb = layerTransform.transform(lb);
1374        rb = layerTransform.transform(rb);
1375        rt = layerTransform.transform(rt);
1376    }
1377
1378    if (!s.finalCrop.isEmpty()) {
1379        boundPoint(&lt, s.finalCrop);
1380        boundPoint(&lb, s.finalCrop);
1381        boundPoint(&rb, s.finalCrop);
1382        boundPoint(&rt, s.finalCrop);
1383    }
1384
1385    Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
1386    position[0] = hwTransform.transform(lt);
1387    position[1] = hwTransform.transform(lb);
1388    position[2] = hwTransform.transform(rb);
1389    position[3] = hwTransform.transform(rt);
1390    for (size_t i=0 ; i<4 ; i++) {
1391        position[i].y = hw_h - position[i].y;
1392    }
1393}
1394
1395bool Layer::isOpaque(const Layer::State& s) const
1396{
1397    // if we don't have a buffer yet, we're translucent regardless of the
1398    // layer's opaque flag.
1399    if (mActiveBuffer == 0) {
1400        return false;
1401    }
1402
1403    // if the layer has the opaque flag, then we're always opaque,
1404    // otherwise we use the current buffer's format.
1405    return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
1406}
1407
1408bool Layer::isSecure() const
1409{
1410    const Layer::State& s(mDrawingState);
1411    return (s.flags & layer_state_t::eLayerSecure);
1412}
1413
1414bool Layer::isProtected() const
1415{
1416    const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
1417    return (activeBuffer != 0) &&
1418            (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1419}
1420
1421bool Layer::isFixedSize() const {
1422    return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1423}
1424
1425bool Layer::isCropped() const {
1426    return !mCurrentCrop.isEmpty();
1427}
1428
1429bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1430    return mNeedsFiltering || hw->needsFiltering();
1431}
1432
1433void Layer::setVisibleRegion(const Region& visibleRegion) {
1434    // always called from main thread
1435    this->visibleRegion = visibleRegion;
1436}
1437
1438void Layer::setCoveredRegion(const Region& coveredRegion) {
1439    // always called from main thread
1440    this->coveredRegion = coveredRegion;
1441}
1442
1443void Layer::setVisibleNonTransparentRegion(const Region&
1444        setVisibleNonTransparentRegion) {
1445    // always called from main thread
1446    this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1447}
1448
1449// ----------------------------------------------------------------------------
1450// transaction
1451// ----------------------------------------------------------------------------
1452
1453void Layer::pushPendingState() {
1454    if (!mCurrentState.modified) {
1455        return;
1456    }
1457
1458    // If this transaction is waiting on the receipt of a frame, generate a sync
1459    // point and send it to the remote layer.
1460    if (mCurrentState.barrierLayer != nullptr) {
1461        sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1462        if (barrierLayer == nullptr) {
1463            ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
1464            // If we can't promote the layer we are intended to wait on,
1465            // then it is expired or otherwise invalid. Allow this transaction
1466            // to be applied as per normal (no synchronization).
1467            mCurrentState.barrierLayer = nullptr;
1468        } else {
1469            auto syncPoint = std::make_shared<SyncPoint>(
1470                    mCurrentState.frameNumber);
1471            if (barrierLayer->addSyncPoint(syncPoint)) {
1472                mRemoteSyncPoints.push_back(std::move(syncPoint));
1473            } else {
1474                // We already missed the frame we're supposed to synchronize
1475                // on, so go ahead and apply the state update
1476                mCurrentState.barrierLayer = nullptr;
1477            }
1478        }
1479
1480        // Wake us up to check if the frame has been received
1481        setTransactionFlags(eTransactionNeeded);
1482        mFlinger->setTransactionFlags(eTraversalNeeded);
1483    }
1484    mPendingStates.push_back(mCurrentState);
1485}
1486
1487void Layer::popPendingState(State* stateToCommit) {
1488    auto oldFlags = stateToCommit->flags;
1489    *stateToCommit = mPendingStates[0];
1490    stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1491            (stateToCommit->flags & stateToCommit->mask);
1492
1493    mPendingStates.removeAt(0);
1494}
1495
1496bool Layer::applyPendingStates(State* stateToCommit) {
1497    bool stateUpdateAvailable = false;
1498    while (!mPendingStates.empty()) {
1499        if (mPendingStates[0].barrierLayer != nullptr) {
1500            if (mRemoteSyncPoints.empty()) {
1501                // If we don't have a sync point for this, apply it anyway. It
1502                // will be visually wrong, but it should keep us from getting
1503                // into too much trouble.
1504                ALOGE("[%s] No local sync point found", mName.string());
1505                popPendingState(stateToCommit);
1506                stateUpdateAvailable = true;
1507                continue;
1508            }
1509
1510            if (mRemoteSyncPoints.front()->getFrameNumber() !=
1511                    mPendingStates[0].frameNumber) {
1512                ALOGE("[%s] Unexpected sync point frame number found",
1513                        mName.string());
1514
1515                // Signal our end of the sync point and then dispose of it
1516                mRemoteSyncPoints.front()->setTransactionApplied();
1517                mRemoteSyncPoints.pop_front();
1518                continue;
1519            }
1520
1521            if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1522                // Apply the state update
1523                popPendingState(stateToCommit);
1524                stateUpdateAvailable = true;
1525
1526                // Signal our end of the sync point and then dispose of it
1527                mRemoteSyncPoints.front()->setTransactionApplied();
1528                mRemoteSyncPoints.pop_front();
1529            } else {
1530                break;
1531            }
1532        } else {
1533            popPendingState(stateToCommit);
1534            stateUpdateAvailable = true;
1535        }
1536    }
1537
1538    // If we still have pending updates, wake SurfaceFlinger back up and point
1539    // it at this layer so we can process them
1540    if (!mPendingStates.empty()) {
1541        setTransactionFlags(eTransactionNeeded);
1542        mFlinger->setTransactionFlags(eTraversalNeeded);
1543    }
1544
1545    mCurrentState.modified = false;
1546    return stateUpdateAvailable;
1547}
1548
1549void Layer::notifyAvailableFrames() {
1550    auto headFrameNumber = getHeadFrameNumber();
1551    bool headFenceSignaled = headFenceHasSignaled();
1552    Mutex::Autolock lock(mLocalSyncPointMutex);
1553    for (auto& point : mLocalSyncPoints) {
1554        if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
1555            point->setFrameAvailable();
1556        }
1557    }
1558}
1559
1560uint32_t Layer::doTransaction(uint32_t flags) {
1561    ATRACE_CALL();
1562
1563    pushPendingState();
1564    Layer::State c = getCurrentState();
1565    if (!applyPendingStates(&c)) {
1566        return 0;
1567    }
1568
1569    const Layer::State& s(getDrawingState());
1570
1571    const bool sizeChanged = (c.requested.w != s.requested.w) ||
1572                             (c.requested.h != s.requested.h);
1573
1574    if (sizeChanged) {
1575        // the size changed, we need to ask our client to request a new buffer
1576        ALOGD_IF(DEBUG_RESIZE,
1577                "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
1578                "  current={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1579                "            requested={ wh={%4u,%4u} }}\n"
1580                "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1581                "            requested={ wh={%4u,%4u} }}\n",
1582                this, getName().string(), mCurrentTransform,
1583                getEffectiveScalingMode(),
1584                c.active.w, c.active.h,
1585                c.crop.left,
1586                c.crop.top,
1587                c.crop.right,
1588                c.crop.bottom,
1589                c.crop.getWidth(),
1590                c.crop.getHeight(),
1591                c.requested.w, c.requested.h,
1592                s.active.w, s.active.h,
1593                s.crop.left,
1594                s.crop.top,
1595                s.crop.right,
1596                s.crop.bottom,
1597                s.crop.getWidth(),
1598                s.crop.getHeight(),
1599                s.requested.w, s.requested.h);
1600
1601        // record the new size, form this point on, when the client request
1602        // a buffer, it'll get the new size.
1603        mSurfaceFlingerConsumer->setDefaultBufferSize(
1604                c.requested.w, c.requested.h);
1605    }
1606
1607    const bool resizePending = (c.requested.w != c.active.w) ||
1608            (c.requested.h != c.active.h);
1609    if (!isFixedSize()) {
1610        if (resizePending && mSidebandStream == NULL) {
1611            // don't let Layer::doTransaction update the drawing state
1612            // if we have a pending resize, unless we are in fixed-size mode.
1613            // the drawing state will be updated only once we receive a buffer
1614            // with the correct size.
1615            //
1616            // in particular, we want to make sure the clip (which is part
1617            // of the geometry state) is latched together with the size but is
1618            // latched immediately when no resizing is involved.
1619            //
1620            // If a sideband stream is attached, however, we want to skip this
1621            // optimization so that transactions aren't missed when a buffer
1622            // never arrives
1623
1624            flags |= eDontUpdateGeometryState;
1625        }
1626    }
1627
1628    // always set active to requested, unless we're asked not to
1629    // this is used by Layer, which special cases resizes.
1630    if (flags & eDontUpdateGeometryState)  {
1631    } else {
1632        Layer::State& editCurrentState(getCurrentState());
1633        if (mFreezePositionUpdates) {
1634            float tx = c.active.transform.tx();
1635            float ty = c.active.transform.ty();
1636            c.active = c.requested;
1637            c.active.transform.set(tx, ty);
1638            editCurrentState.active = c.active;
1639        } else {
1640            editCurrentState.active = editCurrentState.requested;
1641            c.active = c.requested;
1642        }
1643    }
1644
1645    if (s.active != c.active) {
1646        // invalidate and recompute the visible regions if needed
1647        flags |= Layer::eVisibleRegion;
1648    }
1649
1650    if (c.sequence != s.sequence) {
1651        // invalidate and recompute the visible regions if needed
1652        flags |= eVisibleRegion;
1653        this->contentDirty = true;
1654
1655        // we may use linear filtering, if the matrix scales us
1656        const uint8_t type = c.active.transform.getType();
1657        mNeedsFiltering = (!c.active.transform.preserveRects() ||
1658                (type >= Transform::SCALE));
1659    }
1660
1661    // If the layer is hidden, signal and clear out all local sync points so
1662    // that transactions for layers depending on this layer's frames becoming
1663    // visible are not blocked
1664    if (c.flags & layer_state_t::eLayerHidden) {
1665        clearSyncPoints();
1666    }
1667
1668    // Commit the transaction
1669    commitTransaction(c);
1670    return flags;
1671}
1672
1673void Layer::commitTransaction(const State& stateToCommit) {
1674    mDrawingState = stateToCommit;
1675}
1676
1677uint32_t Layer::getTransactionFlags(uint32_t flags) {
1678    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1679}
1680
1681uint32_t Layer::setTransactionFlags(uint32_t flags) {
1682    return android_atomic_or(flags, &mTransactionFlags);
1683}
1684
1685bool Layer::setPosition(float x, float y, bool immediate) {
1686    if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
1687        return false;
1688    mCurrentState.sequence++;
1689
1690    // We update the requested and active position simultaneously because
1691    // we want to apply the position portion of the transform matrix immediately,
1692    // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
1693    mCurrentState.requested.transform.set(x, y);
1694    if (immediate && !mFreezePositionUpdates) {
1695        mCurrentState.active.transform.set(x, y);
1696    }
1697    mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
1698
1699    mCurrentState.modified = true;
1700    setTransactionFlags(eTransactionNeeded);
1701    return true;
1702}
1703
1704bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1705    ssize_t idx = mCurrentChildren.indexOf(childLayer);
1706    if (idx < 0) {
1707        return false;
1708    }
1709    if (childLayer->setLayer(z)) {
1710        mCurrentChildren.removeAt(idx);
1711        mCurrentChildren.add(childLayer);
1712    }
1713    return true;
1714}
1715
1716bool Layer::setLayer(int32_t z) {
1717    if (mCurrentState.z == z)
1718        return false;
1719    mCurrentState.sequence++;
1720    mCurrentState.z = z;
1721    mCurrentState.modified = true;
1722
1723    // Discard all relative layering.
1724    if (mCurrentState.zOrderRelativeOf != nullptr) {
1725        sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1726        if (strongRelative != nullptr) {
1727            strongRelative->removeZOrderRelative(this);
1728        }
1729        mCurrentState.zOrderRelativeOf = nullptr;
1730    }
1731    setTransactionFlags(eTransactionNeeded);
1732    return true;
1733}
1734
1735void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1736    mCurrentState.zOrderRelatives.remove(relative);
1737    mCurrentState.sequence++;
1738    mCurrentState.modified = true;
1739    setTransactionFlags(eTransactionNeeded);
1740}
1741
1742void Layer::addZOrderRelative(const wp<Layer>& relative) {
1743    mCurrentState.zOrderRelatives.add(relative);
1744    mCurrentState.modified = true;
1745    mCurrentState.sequence++;
1746    setTransactionFlags(eTransactionNeeded);
1747}
1748
1749bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1750    sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1751    if (handle == nullptr) {
1752        return false;
1753    }
1754    sp<Layer> relative = handle->owner.promote();
1755    if (relative == nullptr) {
1756        return false;
1757    }
1758
1759    mCurrentState.sequence++;
1760    mCurrentState.modified = true;
1761    mCurrentState.z = z;
1762
1763    mCurrentState.zOrderRelativeOf = relative;
1764    relative->addZOrderRelative(this);
1765
1766    setTransactionFlags(eTransactionNeeded);
1767
1768    return true;
1769}
1770
1771bool Layer::setSize(uint32_t w, uint32_t h) {
1772    if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1773        return false;
1774    mCurrentState.requested.w = w;
1775    mCurrentState.requested.h = h;
1776    mCurrentState.modified = true;
1777    setTransactionFlags(eTransactionNeeded);
1778    return true;
1779}
1780#ifdef USE_HWC2
1781bool Layer::setAlpha(float alpha) {
1782#else
1783bool Layer::setAlpha(uint8_t alpha) {
1784#endif
1785    if (mCurrentState.alpha == alpha)
1786        return false;
1787    mCurrentState.sequence++;
1788    mCurrentState.alpha = alpha;
1789    mCurrentState.modified = true;
1790    setTransactionFlags(eTransactionNeeded);
1791    return true;
1792}
1793bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1794    mCurrentState.sequence++;
1795    mCurrentState.requested.transform.set(
1796            matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
1797    mCurrentState.modified = true;
1798    setTransactionFlags(eTransactionNeeded);
1799    return true;
1800}
1801bool Layer::setTransparentRegionHint(const Region& transparent) {
1802    mCurrentState.requestedTransparentRegion = transparent;
1803    mCurrentState.modified = true;
1804    setTransactionFlags(eTransactionNeeded);
1805    return true;
1806}
1807bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1808    const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1809    if (mCurrentState.flags == newFlags)
1810        return false;
1811    mCurrentState.sequence++;
1812    mCurrentState.flags = newFlags;
1813    mCurrentState.mask = mask;
1814    mCurrentState.modified = true;
1815    setTransactionFlags(eTransactionNeeded);
1816    return true;
1817}
1818
1819bool Layer::setCrop(const Rect& crop, bool immediate) {
1820    if (mCurrentState.crop == crop)
1821        return false;
1822    mCurrentState.sequence++;
1823    mCurrentState.requestedCrop = crop;
1824    if (immediate) {
1825        mCurrentState.crop = crop;
1826    }
1827    mCurrentState.modified = true;
1828    setTransactionFlags(eTransactionNeeded);
1829    return true;
1830}
1831
1832bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
1833    if (mCurrentState.finalCrop == crop)
1834        return false;
1835    mCurrentState.sequence++;
1836    mCurrentState.requestedFinalCrop = crop;
1837    if (immediate) {
1838        mCurrentState.finalCrop = crop;
1839    }
1840    mCurrentState.modified = true;
1841    setTransactionFlags(eTransactionNeeded);
1842    return true;
1843}
1844
1845bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1846    if (scalingMode == mOverrideScalingMode)
1847        return false;
1848    mOverrideScalingMode = scalingMode;
1849    setTransactionFlags(eTransactionNeeded);
1850    return true;
1851}
1852
1853void Layer::setInfo(uint32_t type, uint32_t appId) {
1854  mCurrentState.appId = appId;
1855  mCurrentState.type = type;
1856  mCurrentState.modified = true;
1857  setTransactionFlags(eTransactionNeeded);
1858}
1859
1860uint32_t Layer::getEffectiveScalingMode() const {
1861    if (mOverrideScalingMode >= 0) {
1862      return mOverrideScalingMode;
1863    }
1864    return mCurrentScalingMode;
1865}
1866
1867bool Layer::setLayerStack(uint32_t layerStack) {
1868    if (mCurrentState.layerStack == layerStack)
1869        return false;
1870    mCurrentState.sequence++;
1871    mCurrentState.layerStack = layerStack;
1872    mCurrentState.modified = true;
1873    setTransactionFlags(eTransactionNeeded);
1874    return true;
1875}
1876
1877bool Layer::setDataSpace(android_dataspace dataSpace) {
1878    if (mCurrentState.dataSpace == dataSpace)
1879        return false;
1880    mCurrentState.sequence++;
1881    mCurrentState.dataSpace = dataSpace;
1882    mCurrentState.modified = true;
1883    setTransactionFlags(eTransactionNeeded);
1884    return true;
1885}
1886
1887uint32_t Layer::getLayerStack() const {
1888    auto p = getParent();
1889    if (p == nullptr) {
1890        return getDrawingState().layerStack;
1891    }
1892    return p->getLayerStack();
1893}
1894
1895void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
1896        uint64_t frameNumber) {
1897    mCurrentState.barrierLayer = barrierLayer;
1898    mCurrentState.frameNumber = frameNumber;
1899    // We don't set eTransactionNeeded, because just receiving a deferral
1900    // request without any other state updates shouldn't actually induce a delay
1901    mCurrentState.modified = true;
1902    pushPendingState();
1903    mCurrentState.barrierLayer = nullptr;
1904    mCurrentState.frameNumber = 0;
1905    mCurrentState.modified = false;
1906    ALOGE("Deferred transaction");
1907}
1908
1909void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
1910        uint64_t frameNumber) {
1911    sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1912    deferTransactionUntil(handle->owner.promote(), frameNumber);
1913}
1914
1915void Layer::useSurfaceDamage() {
1916    if (mFlinger->mForceFullDamage) {
1917        surfaceDamageRegion = Region::INVALID_REGION;
1918    } else {
1919        surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1920    }
1921}
1922
1923void Layer::useEmptyDamage() {
1924    surfaceDamageRegion.clear();
1925}
1926
1927// ----------------------------------------------------------------------------
1928// pageflip handling...
1929// ----------------------------------------------------------------------------
1930
1931bool Layer::shouldPresentNow(const DispSync& dispSync) const {
1932    if (mSidebandStreamChanged || mAutoRefresh) {
1933        return true;
1934    }
1935
1936    Mutex::Autolock lock(mQueueItemLock);
1937    if (mQueueItems.empty()) {
1938        return false;
1939    }
1940    auto timestamp = mQueueItems[0].mTimestamp;
1941    nsecs_t expectedPresent =
1942            mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
1943
1944    // Ignore timestamps more than a second in the future
1945    bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1946    ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1947            "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1948            expectedPresent);
1949
1950    bool isDue = timestamp < expectedPresent;
1951    return isDue || !isPlausible;
1952}
1953
1954bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1955    if (mBufferLatched) {
1956        Mutex::Autolock lock(mFrameEventHistoryMutex);
1957        mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
1958    }
1959    mRefreshPending = false;
1960    return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
1961}
1962
1963bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
1964        const std::shared_ptr<FenceTime>& presentFence,
1965        const CompositorTiming& compositorTiming) {
1966    mAcquireTimeline.updateSignalTimes();
1967    mReleaseTimeline.updateSignalTimes();
1968
1969    // mFrameLatencyNeeded is true when a new frame was latched for the
1970    // composition.
1971    if (!mFrameLatencyNeeded)
1972        return false;
1973
1974    // Update mFrameEventHistory.
1975    {
1976        Mutex::Autolock lock(mFrameEventHistoryMutex);
1977        mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
1978                glDoneFence, presentFence, compositorTiming);
1979    }
1980
1981    // Update mFrameTracker.
1982    nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1983    mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1984
1985    std::shared_ptr<FenceTime> frameReadyFence =
1986            mSurfaceFlingerConsumer->getCurrentFenceTime();
1987    if (frameReadyFence->isValid()) {
1988        mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
1989    } else {
1990        // There was no fence for this frame, so assume that it was ready
1991        // to be presented at the desired present time.
1992        mFrameTracker.setFrameReadyTime(desiredPresentTime);
1993    }
1994
1995    if (presentFence->isValid()) {
1996        mFrameTracker.setActualPresentFence(
1997                std::shared_ptr<FenceTime>(presentFence));
1998    } else {
1999        // The HWC doesn't support present fences, so use the refresh
2000        // timestamp instead.
2001        mFrameTracker.setActualPresentTime(
2002            mFlinger->getHwComposer().getRefreshTimestamp(
2003                HWC_DISPLAY_PRIMARY));
2004    }
2005
2006    mFrameTracker.advanceFrame();
2007    mFrameLatencyNeeded = false;
2008    return true;
2009}
2010
2011#ifdef USE_HWC2
2012void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2013    if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2014        return;
2015    }
2016
2017    auto releaseFenceTime = std::make_shared<FenceTime>(
2018            mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
2019    mReleaseTimeline.push(releaseFenceTime);
2020
2021    Mutex::Autolock lock(mFrameEventHistoryMutex);
2022    if (mPreviousFrameNumber != 0) {
2023        mFrameEventHistory.addRelease(mPreviousFrameNumber,
2024                dequeueReadyTime, std::move(releaseFenceTime));
2025    }
2026}
2027#endif
2028
2029bool Layer::isHiddenByPolicy() const {
2030    const Layer::State& s(mDrawingState);
2031    const auto& parent = getParent();
2032    if (parent != nullptr && parent->isHiddenByPolicy()) {
2033        return true;
2034    }
2035    return s.flags & layer_state_t::eLayerHidden;
2036}
2037
2038bool Layer::isVisible() const {
2039#ifdef USE_HWC2
2040    return !(isHiddenByPolicy()) && getAlpha() > 0.0f
2041            && (mActiveBuffer != NULL || mSidebandStream != NULL);
2042#else
2043    return !(isHiddenByPolicy()) && getAlpha()
2044            && (mActiveBuffer != NULL || mSidebandStream != NULL);
2045#endif
2046}
2047
2048bool Layer::allTransactionsSignaled() {
2049    auto headFrameNumber = getHeadFrameNumber();
2050    bool matchingFramesFound = false;
2051    bool allTransactionsApplied = true;
2052    Mutex::Autolock lock(mLocalSyncPointMutex);
2053
2054    for (auto& point : mLocalSyncPoints) {
2055        if (point->getFrameNumber() > headFrameNumber) {
2056            break;
2057        }
2058        matchingFramesFound = true;
2059
2060        if (!point->frameIsAvailable()) {
2061           // We haven't notified the remote layer that the frame for
2062           // this point is available yet. Notify it now, and then
2063           // abort this attempt to latch.
2064           point->setFrameAvailable();
2065           allTransactionsApplied = false;
2066           break;
2067        }
2068
2069        allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2070    }
2071    return !matchingFramesFound || allTransactionsApplied;
2072}
2073
2074Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
2075{
2076    ATRACE_CALL();
2077
2078    if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2079        // mSidebandStreamChanged was true
2080        mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
2081        if (mSidebandStream != NULL) {
2082            setTransactionFlags(eTransactionNeeded);
2083            mFlinger->setTransactionFlags(eTraversalNeeded);
2084        }
2085        recomputeVisibleRegions = true;
2086
2087        const State& s(getDrawingState());
2088        return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
2089    }
2090
2091    Region outDirtyRegion;
2092    if (mQueuedFrames <= 0 && !mAutoRefresh) {
2093        return outDirtyRegion;
2094    }
2095
2096    // if we've already called updateTexImage() without going through
2097    // a composition step, we have to skip this layer at this point
2098    // because we cannot call updateTeximage() without a corresponding
2099    // compositionComplete() call.
2100    // we'll trigger an update in onPreComposition().
2101    if (mRefreshPending) {
2102        return outDirtyRegion;
2103    }
2104
2105    // If the head buffer's acquire fence hasn't signaled yet, return and
2106    // try again later
2107    if (!headFenceHasSignaled()) {
2108        mFlinger->signalLayerUpdate();
2109        return outDirtyRegion;
2110    }
2111
2112    // Capture the old state of the layer for comparisons later
2113    const State& s(getDrawingState());
2114    const bool oldOpacity = isOpaque(s);
2115    sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2116
2117    if (!allTransactionsSignaled()) {
2118        mFlinger->signalLayerUpdate();
2119        return outDirtyRegion;
2120    }
2121
2122    // This boolean is used to make sure that SurfaceFlinger's shadow copy
2123    // of the buffer queue isn't modified when the buffer queue is returning
2124    // BufferItem's that weren't actually queued. This can happen in shared
2125    // buffer mode.
2126    bool queuedBuffer = false;
2127    LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2128                    getProducerStickyTransform() != 0, mName.string(),
2129                    mOverrideScalingMode, mFreezePositionUpdates);
2130    status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2131            mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2132            mLastFrameNumberReceived);
2133    if (updateResult == BufferQueue::PRESENT_LATER) {
2134        // Producer doesn't want buffer to be displayed yet.  Signal a
2135        // layer update so we check again at the next opportunity.
2136        mFlinger->signalLayerUpdate();
2137        return outDirtyRegion;
2138    } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2139        // If the buffer has been rejected, remove it from the shadow queue
2140        // and return early
2141        if (queuedBuffer) {
2142            Mutex::Autolock lock(mQueueItemLock);
2143            mQueueItems.removeAt(0);
2144            android_atomic_dec(&mQueuedFrames);
2145        }
2146        return outDirtyRegion;
2147    } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2148        // This can occur if something goes wrong when trying to create the
2149        // EGLImage for this buffer. If this happens, the buffer has already
2150        // been released, so we need to clean up the queue and bug out
2151        // early.
2152        if (queuedBuffer) {
2153            Mutex::Autolock lock(mQueueItemLock);
2154            mQueueItems.clear();
2155            android_atomic_and(0, &mQueuedFrames);
2156        }
2157
2158        // Once we have hit this state, the shadow queue may no longer
2159        // correctly reflect the incoming BufferQueue's contents, so even if
2160        // updateTexImage starts working, the only safe course of action is
2161        // to continue to ignore updates.
2162        mUpdateTexImageFailed = true;
2163
2164        return outDirtyRegion;
2165    }
2166
2167    if (queuedBuffer) {
2168        // Autolock scope
2169        auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2170
2171        Mutex::Autolock lock(mQueueItemLock);
2172
2173        // Remove any stale buffers that have been dropped during
2174        // updateTexImage
2175        while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2176            mQueueItems.removeAt(0);
2177            android_atomic_dec(&mQueuedFrames);
2178        }
2179
2180        mQueueItems.removeAt(0);
2181    }
2182
2183
2184    // Decrement the queued-frames count.  Signal another event if we
2185    // have more frames pending.
2186    if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2187            || mAutoRefresh) {
2188        mFlinger->signalLayerUpdate();
2189    }
2190
2191    // update the active buffer
2192    mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2193            &mActiveBufferSlot);
2194    if (mActiveBuffer == NULL) {
2195        // this can only happen if the very first buffer was rejected.
2196        return outDirtyRegion;
2197    }
2198
2199    mBufferLatched = true;
2200    mPreviousFrameNumber = mCurrentFrameNumber;
2201    mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2202
2203    {
2204        Mutex::Autolock lock(mFrameEventHistoryMutex);
2205        mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2206#ifndef USE_HWC2
2207        auto releaseFenceTime = std::make_shared<FenceTime>(
2208                mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
2209        mReleaseTimeline.push(releaseFenceTime);
2210        if (mPreviousFrameNumber != 0) {
2211            mFrameEventHistory.addRelease(mPreviousFrameNumber,
2212                    latchTime, std::move(releaseFenceTime));
2213        }
2214#endif
2215    }
2216
2217    mRefreshPending = true;
2218    mFrameLatencyNeeded = true;
2219    if (oldActiveBuffer == NULL) {
2220         // the first time we receive a buffer, we need to trigger a
2221         // geometry invalidation.
2222        recomputeVisibleRegions = true;
2223     }
2224
2225    setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2226
2227    Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2228    const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2229    const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2230    if ((crop != mCurrentCrop) ||
2231        (transform != mCurrentTransform) ||
2232        (scalingMode != mCurrentScalingMode))
2233    {
2234        mCurrentCrop = crop;
2235        mCurrentTransform = transform;
2236        mCurrentScalingMode = scalingMode;
2237        recomputeVisibleRegions = true;
2238    }
2239
2240    if (oldActiveBuffer != NULL) {
2241        uint32_t bufWidth  = mActiveBuffer->getWidth();
2242        uint32_t bufHeight = mActiveBuffer->getHeight();
2243        if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2244            bufHeight != uint32_t(oldActiveBuffer->height)) {
2245            recomputeVisibleRegions = true;
2246        }
2247    }
2248
2249    mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2250    if (oldOpacity != isOpaque(s)) {
2251        recomputeVisibleRegions = true;
2252    }
2253
2254    // Remove any sync points corresponding to the buffer which was just
2255    // latched
2256    {
2257        Mutex::Autolock lock(mLocalSyncPointMutex);
2258        auto point = mLocalSyncPoints.begin();
2259        while (point != mLocalSyncPoints.end()) {
2260            if (!(*point)->frameIsAvailable() ||
2261                    !(*point)->transactionIsApplied()) {
2262                // This sync point must have been added since we started
2263                // latching. Don't drop it yet.
2264                ++point;
2265                continue;
2266            }
2267
2268            if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2269                point = mLocalSyncPoints.erase(point);
2270            } else {
2271                ++point;
2272            }
2273        }
2274    }
2275
2276    // FIXME: postedRegion should be dirty & bounds
2277    Region dirtyRegion(Rect(s.active.w, s.active.h));
2278
2279    // transform the dirty region to window-manager space
2280    outDirtyRegion = (getTransform().transform(dirtyRegion));
2281
2282    return outDirtyRegion;
2283}
2284
2285uint32_t Layer::getEffectiveUsage(uint32_t usage) const
2286{
2287    // TODO: should we do something special if mSecure is set?
2288    if (mProtectedByApp) {
2289        // need a hardware-protected path to external video sink
2290        usage |= GraphicBuffer::USAGE_PROTECTED;
2291    }
2292    if (mPotentialCursor) {
2293        usage |= GraphicBuffer::USAGE_CURSOR;
2294    }
2295    usage |= GraphicBuffer::USAGE_HW_COMPOSER;
2296    return usage;
2297}
2298
2299void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
2300    uint32_t orientation = 0;
2301    if (!mFlinger->mDebugDisableTransformHint) {
2302        // The transform hint is used to improve performance, but we can
2303        // only have a single transform hint, it cannot
2304        // apply to all displays.
2305        const Transform& planeTransform(hw->getTransform());
2306        orientation = planeTransform.getOrientation();
2307        if (orientation & Transform::ROT_INVALID) {
2308            orientation = 0;
2309        }
2310    }
2311    mSurfaceFlingerConsumer->setTransformHint(orientation);
2312}
2313
2314// ----------------------------------------------------------------------------
2315// debugging
2316// ----------------------------------------------------------------------------
2317
2318void Layer::dump(String8& result, Colorizer& colorizer) const
2319{
2320    const Layer::State& s(getDrawingState());
2321
2322    colorizer.colorize(result, Colorizer::GREEN);
2323    result.appendFormat(
2324            "+ %s %p (%s)\n",
2325            getTypeId(), this, getName().string());
2326    colorizer.reset(result);
2327
2328    s.activeTransparentRegion.dump(result, "transparentRegion");
2329    visibleRegion.dump(result, "visibleRegion");
2330    surfaceDamageRegion.dump(result, "surfaceDamageRegion");
2331    sp<Client> client(mClientRef.promote());
2332
2333    result.appendFormat(            "      "
2334            "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2335            "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
2336            "isOpaque=%1d, invalidate=%1d, "
2337#ifdef USE_HWC2
2338            "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2339#else
2340            "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2341#endif
2342            "      client=%p\n",
2343            getLayerStack(), s.z,
2344            s.active.transform.tx(), s.active.transform.ty(),
2345            s.active.w, s.active.h,
2346            s.crop.left, s.crop.top,
2347            s.crop.right, s.crop.bottom,
2348            s.finalCrop.left, s.finalCrop.top,
2349            s.finalCrop.right, s.finalCrop.bottom,
2350            isOpaque(s), contentDirty,
2351            s.alpha, s.flags,
2352            s.active.transform[0][0], s.active.transform[0][1],
2353            s.active.transform[1][0], s.active.transform[1][1],
2354            client.get());
2355
2356    sp<const GraphicBuffer> buf0(mActiveBuffer);
2357    uint32_t w0=0, h0=0, s0=0, f0=0;
2358    if (buf0 != 0) {
2359        w0 = buf0->getWidth();
2360        h0 = buf0->getHeight();
2361        s0 = buf0->getStride();
2362        f0 = buf0->format;
2363    }
2364    result.appendFormat(
2365            "      "
2366            "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2367            " queued-frames=%d, mRefreshPending=%d\n",
2368            mFormat, w0, h0, s0,f0,
2369            mQueuedFrames, mRefreshPending);
2370
2371    if (mSurfaceFlingerConsumer != 0) {
2372        mSurfaceFlingerConsumer->dumpState(result, "            ");
2373    }
2374}
2375
2376#ifdef USE_HWC2
2377void Layer::miniDumpHeader(String8& result) {
2378    result.append("----------------------------------------");
2379    result.append("---------------------------------------\n");
2380    result.append(" Layer name\n");
2381    result.append("           Z | ");
2382    result.append(" Comp Type | ");
2383    result.append("  Disp Frame (LTRB) | ");
2384    result.append("         Source Crop (LTRB)\n");
2385    result.append("----------------------------------------");
2386    result.append("---------------------------------------\n");
2387}
2388
2389void Layer::miniDump(String8& result, int32_t hwcId) const {
2390    if (mHwcLayers.count(hwcId) == 0) {
2391        return;
2392    }
2393
2394    String8 name;
2395    if (mName.length() > 77) {
2396        std::string shortened;
2397        shortened.append(mName.string(), 36);
2398        shortened.append("[...]");
2399        shortened.append(mName.string() + (mName.length() - 36), 36);
2400        name = shortened.c_str();
2401    } else {
2402        name = mName;
2403    }
2404
2405    result.appendFormat(" %s\n", name.string());
2406
2407    const Layer::State& layerState(getDrawingState());
2408    const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2409    result.appendFormat("  %10u | ", layerState.z);
2410    result.appendFormat("%10s | ",
2411            to_string(getCompositionType(hwcId)).c_str());
2412    const Rect& frame = hwcInfo.displayFrame;
2413    result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2414            frame.right, frame.bottom);
2415    const FloatRect& crop = hwcInfo.sourceCrop;
2416    result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2417            crop.right, crop.bottom);
2418
2419    result.append("- - - - - - - - - - - - - - - - - - - - ");
2420    result.append("- - - - - - - - - - - - - - - - - - - -\n");
2421}
2422#endif
2423
2424void Layer::dumpFrameStats(String8& result) const {
2425    mFrameTracker.dumpStats(result);
2426}
2427
2428void Layer::clearFrameStats() {
2429    mFrameTracker.clearStats();
2430}
2431
2432void Layer::logFrameStats() {
2433    mFrameTracker.logAndResetStats(mName);
2434}
2435
2436void Layer::getFrameStats(FrameStats* outStats) const {
2437    mFrameTracker.getStats(outStats);
2438}
2439
2440void Layer::dumpFrameEvents(String8& result) {
2441    result.appendFormat("- Layer %s (%s, %p)\n",
2442            getName().string(), getTypeId(), this);
2443    Mutex::Autolock lock(mFrameEventHistoryMutex);
2444    mFrameEventHistory.checkFencesForCompletion();
2445    mFrameEventHistory.dump(result);
2446}
2447
2448void Layer::onDisconnect() {
2449    Mutex::Autolock lock(mFrameEventHistoryMutex);
2450    mFrameEventHistory.onDisconnect();
2451}
2452
2453void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2454        FrameEventHistoryDelta *outDelta) {
2455    Mutex::Autolock lock(mFrameEventHistoryMutex);
2456    if (newTimestamps) {
2457        mAcquireTimeline.push(newTimestamps->acquireFence);
2458        mFrameEventHistory.addQueue(*newTimestamps);
2459    }
2460
2461    if (outDelta) {
2462        mFrameEventHistory.getAndResetDelta(outDelta);
2463    }
2464}
2465
2466std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2467        bool forceFlush) {
2468    std::vector<OccupancyTracker::Segment> history;
2469    status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2470            &history);
2471    if (result != NO_ERROR) {
2472        ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2473                result);
2474        return {};
2475    }
2476    return history;
2477}
2478
2479bool Layer::getTransformToDisplayInverse() const {
2480    return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2481}
2482
2483void Layer::addChild(const sp<Layer>& layer) {
2484    mCurrentChildren.add(layer);
2485    layer->setParent(this);
2486}
2487
2488ssize_t Layer::removeChild(const sp<Layer>& layer) {
2489    layer->setParent(nullptr);
2490    return mCurrentChildren.remove(layer);
2491}
2492
2493bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2494    sp<Handle> handle = nullptr;
2495    sp<Layer> newParent = nullptr;
2496    if (newParentHandle == nullptr) {
2497        return false;
2498    }
2499    handle = static_cast<Handle*>(newParentHandle.get());
2500    newParent = handle->owner.promote();
2501    if (newParent == nullptr) {
2502        ALOGE("Unable to promote Layer handle");
2503        return false;
2504    }
2505
2506    for (const sp<Layer>& child : mCurrentChildren) {
2507        newParent->addChild(child);
2508
2509        sp<Client> client(child->mClientRef.promote());
2510        if (client != nullptr) {
2511            client->setParentLayer(newParent);
2512        }
2513    }
2514    mCurrentChildren.clear();
2515
2516    return true;
2517}
2518
2519bool Layer::detachChildren() {
2520    traverseInZOrder([this](Layer* child) {
2521        if (child == this) {
2522            return;
2523        }
2524
2525        sp<Client> client(child->mClientRef.promote());
2526        if (client != nullptr) {
2527            client->detachLayer(child);
2528        }
2529    });
2530
2531    return true;
2532}
2533
2534void Layer::setParent(const sp<Layer>& layer) {
2535    mParent = layer;
2536}
2537
2538void Layer::clearSyncPoints() {
2539    for (const auto& child : mCurrentChildren) {
2540        child->clearSyncPoints();
2541    }
2542
2543    Mutex::Autolock lock(mLocalSyncPointMutex);
2544    for (auto& point : mLocalSyncPoints) {
2545        point->setFrameAvailable();
2546    }
2547    mLocalSyncPoints.clear();
2548}
2549
2550int32_t Layer::getZ() const {
2551    return mDrawingState.z;
2552}
2553
2554LayerVector Layer::makeTraversalList() {
2555    if (mDrawingState.zOrderRelatives.size() == 0) {
2556        return mDrawingChildren;
2557    }
2558    LayerVector traverse;
2559
2560    for (const wp<Layer>& weakRelative : mDrawingState.zOrderRelatives) {
2561        sp<Layer> strongRelative = weakRelative.promote();
2562        if (strongRelative != nullptr) {
2563            traverse.add(strongRelative);
2564        } else {
2565            // We need to erase from current state instead of drawing
2566            // state so we don't overwrite when copying
2567            // the current state to the drawing state.
2568            mCurrentState.zOrderRelatives.remove(weakRelative);
2569        }
2570    }
2571
2572    for (const sp<Layer>& child : mDrawingChildren) {
2573        traverse.add(child);
2574    }
2575
2576    return traverse;
2577}
2578
2579/**
2580 * Negatively signed relatives are before 'this' in Z-order.
2581 */
2582void Layer::traverseInZOrder(const std::function<void(Layer*)>& exec) {
2583    LayerVector list = makeTraversalList();
2584
2585    size_t i = 0;
2586    for (; i < list.size(); i++) {
2587        const auto& relative = list[i];
2588        if (relative->getZ() >= 0) {
2589            break;
2590        }
2591        relative->traverseInZOrder(exec);
2592    }
2593    exec(this);
2594    for (; i < list.size(); i++) {
2595        const auto& relative = list[i];
2596        relative->traverseInZOrder(exec);
2597    }
2598}
2599
2600/**
2601 * Positively signed relatives are before 'this' in reverse Z-order.
2602 */
2603void Layer::traverseInReverseZOrder(const std::function<void(Layer*)>& exec) {
2604    LayerVector list = makeTraversalList();
2605
2606    int32_t i = 0;
2607    for (i = list.size()-1; i>=0; i--) {
2608        const auto& relative = list[i];
2609        if (relative->getZ() < 0) {
2610            break;
2611        }
2612        relative->traverseInReverseZOrder(exec);
2613    }
2614    exec(this);
2615    for (; i>=0; i--) {
2616        const auto& relative = list[i];
2617        relative->traverseInReverseZOrder(exec);
2618    }
2619}
2620
2621Transform Layer::getTransform() const {
2622    Transform t;
2623    const auto& p = getParent();
2624    if (p != nullptr) {
2625        t = p->getTransform();
2626    }
2627    return t * getDrawingState().active.transform;
2628}
2629
2630#ifdef USE_HWC2
2631float Layer::getAlpha() const {
2632    const auto& p = getParent();
2633
2634    float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2635    return parentAlpha * getDrawingState().alpha;
2636}
2637#else
2638uint8_t Layer::getAlpha() const {
2639    const auto& p = getParent();
2640
2641    float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2642    float drawingAlpha = getDrawingState().alpha / 255.0f;
2643    drawingAlpha = drawingAlpha * parentAlpha;
2644    return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2645}
2646#endif
2647
2648void Layer::commitChildList() {
2649    for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2650        const auto& child = mCurrentChildren[i];
2651        child->commitChildList();
2652    }
2653    mDrawingChildren = mCurrentChildren;
2654}
2655
2656// ---------------------------------------------------------------------------
2657
2658}; // namespace android
2659
2660#if defined(__gl_h_)
2661#error "don't include gl/gl.h in this file"
2662#endif
2663
2664#if defined(__gl2_h_)
2665#error "don't include gl2/gl2.h in this file"
2666#endif
2667