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