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