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