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