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