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