Layer.cpp revision f3e85d432749ca77ad707bec523b67d741d43e6e
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 ATRACE_TAG ATRACE_TAG_GRAPHICS
18
19#include <stdlib.h>
20#include <stdint.h>
21#include <sys/types.h>
22#include <math.h>
23
24#include <cutils/compiler.h>
25#include <cutils/native_handle.h>
26#include <cutils/properties.h>
27
28#include <utils/Errors.h>
29#include <utils/Log.h>
30#include <utils/StopWatch.h>
31#include <utils/Trace.h>
32
33#include <ui/GraphicBuffer.h>
34#include <ui/PixelFormat.h>
35
36#include <gui/Surface.h>
37
38#include "clz.h"
39#include "Colorizer.h"
40#include "DisplayDevice.h"
41#include "GLExtensions.h"
42#include "Layer.h"
43#include "SurfaceFlinger.h"
44#include "SurfaceTextureLayer.h"
45
46#include "DisplayHardware/HWComposer.h"
47
48#define DEBUG_RESIZE    0
49
50namespace android {
51
52// ---------------------------------------------------------------------------
53
54int32_t Layer::sSequence = 1;
55
56Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
57        const String8& name, uint32_t w, uint32_t h, uint32_t flags)
58    :   contentDirty(false),
59        sequence(uint32_t(android_atomic_inc(&sSequence))),
60        mFlinger(flinger),
61        mTextureName(-1U),
62        mPremultipliedAlpha(true),
63        mName("unnamed"),
64        mDebug(false),
65        mFormat(PIXEL_FORMAT_NONE),
66        mGLExtensions(GLExtensions::getInstance()),
67        mOpaqueLayer(true),
68        mTransactionFlags(0),
69        mQueuedFrames(0),
70        mCurrentTransform(0),
71        mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
72        mCurrentOpacity(true),
73        mRefreshPending(false),
74        mFrameLatencyNeeded(false),
75        mFiltering(false),
76        mNeedsFiltering(false),
77        mSecure(false),
78        mProtectedByApp(false),
79        mHasSurface(false),
80        mClientRef(client)
81{
82    mCurrentCrop.makeInvalid();
83    glGenTextures(1, &mTextureName);
84
85    uint32_t layerFlags = 0;
86    if (flags & ISurfaceComposerClient::eHidden)
87        layerFlags = layer_state_t::eLayerHidden;
88
89    if (flags & ISurfaceComposerClient::eNonPremultiplied)
90        mPremultipliedAlpha = false;
91
92    mName = name;
93
94    mCurrentState.active.w = w;
95    mCurrentState.active.h = h;
96    mCurrentState.active.crop.makeInvalid();
97    mCurrentState.z = 0;
98    mCurrentState.alpha = 0xFF;
99    mCurrentState.layerStack = 0;
100    mCurrentState.flags = layerFlags;
101    mCurrentState.sequence = 0;
102    mCurrentState.transform.set(0, 0);
103    mCurrentState.requested = mCurrentState.active;
104
105    // drawing state & current state are identical
106    mDrawingState = mCurrentState;
107}
108
109void Layer::onFirstRef()
110{
111    // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
112    sp<BufferQueue> bq = new SurfaceTextureLayer(mFlinger);
113    mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(mTextureName, true,
114            GL_TEXTURE_EXTERNAL_OES, false, bq);
115
116    mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
117    mSurfaceFlingerConsumer->setFrameAvailableListener(this);
118    mSurfaceFlingerConsumer->setSynchronousMode(true);
119    mSurfaceFlingerConsumer->setName(mName);
120
121#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
122#warning "disabling triple buffering"
123    mSurfaceFlingerConsumer->setDefaultMaxBufferCount(2);
124#else
125    mSurfaceFlingerConsumer->setDefaultMaxBufferCount(3);
126#endif
127
128    const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
129    updateTransformHint(hw);
130}
131
132Layer::~Layer() {
133    sp<Client> c(mClientRef.promote());
134    if (c != 0) {
135        c->detachLayer(this);
136    }
137    mFlinger->deleteTextureAsync(mTextureName);
138}
139
140// ---------------------------------------------------------------------------
141// callbacks
142// ---------------------------------------------------------------------------
143
144void Layer::onLayerDisplayed(const sp<const DisplayDevice>& hw,
145        HWComposer::HWCLayerInterface* layer) {
146    if (layer) {
147        layer->onDisplayed();
148        mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
149    }
150}
151
152void Layer::onFrameAvailable() {
153    android_atomic_inc(&mQueuedFrames);
154    mFlinger->signalLayerUpdate();
155}
156
157// called with SurfaceFlinger::mStateLock from the drawing thread after
158// the layer has been remove from the current state list (and just before
159// it's removed from the drawing state list)
160void Layer::onRemoved() {
161    mSurfaceFlingerConsumer->abandon();
162}
163
164// ---------------------------------------------------------------------------
165// set-up
166// ---------------------------------------------------------------------------
167
168String8 Layer::getName() const {
169    return mName;
170}
171
172status_t Layer::setBuffers( uint32_t w, uint32_t h,
173                            PixelFormat format, uint32_t flags)
174{
175    // this surfaces pixel format
176    PixelFormatInfo info;
177    status_t err = getPixelFormatInfo(format, &info);
178    if (err) {
179        ALOGE("unsupported pixelformat %d", format);
180        return err;
181    }
182
183    uint32_t const maxSurfaceDims = min(
184            mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
185
186    // never allow a surface larger than what our underlying GL implementation
187    // can handle.
188    if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
189        ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
190        return BAD_VALUE;
191    }
192
193    mFormat = format;
194
195    mSecure = (flags & ISurfaceComposerClient::eSecure) ? true : false;
196    mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
197    mOpaqueLayer = (flags & ISurfaceComposerClient::eOpaque);
198    mCurrentOpacity = getOpacityForFormat(format);
199
200    mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
201    mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
202    mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
203
204    return NO_ERROR;
205}
206
207sp<IBinder> Layer::getHandle() {
208    Mutex::Autolock _l(mLock);
209
210    LOG_ALWAYS_FATAL_IF(mHasSurface,
211            "Layer::getHandle() has already been called");
212
213    mHasSurface = true;
214
215    /*
216     * The layer handle is just a BBinder object passed to the client
217     * (remote process) -- we don't keep any reference on our side such that
218     * the dtor is called when the remote side let go of its reference.
219     *
220     * LayerCleaner ensures that mFlinger->onLayerDestroyed() is called for
221     * this layer when the handle is destroyed.
222     */
223
224    class Handle : public BBinder, public LayerCleaner {
225        wp<const Layer> mOwner;
226    public:
227        Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer)
228            : LayerCleaner(flinger, layer), mOwner(layer) {
229        }
230    };
231
232    return new Handle(mFlinger, this);
233}
234
235sp<BufferQueue> Layer::getBufferQueue() const {
236    return mSurfaceFlingerConsumer->getBufferQueue();
237}
238
239//virtual sp<IGraphicBufferProducer> getSurfaceTexture() const {
240//    sp<IGraphicBufferProducer> res;
241//    sp<const Layer> that( mOwner.promote() );
242//    if (that != NULL) {
243//        res = that->mSurfaceFlingerConsumer->getBufferQueue();
244//    }
245//    return res;
246//}
247
248// ---------------------------------------------------------------------------
249// h/w composer set-up
250// ---------------------------------------------------------------------------
251
252Rect Layer::getContentCrop() const {
253    // this is the crop rectangle that applies to the buffer
254    // itself (as opposed to the window)
255    Rect crop;
256    if (!mCurrentCrop.isEmpty()) {
257        // if the buffer crop is defined, we use that
258        crop = mCurrentCrop;
259    } else if (mActiveBuffer != NULL) {
260        // otherwise we use the whole buffer
261        crop = mActiveBuffer->getBounds();
262    } else {
263        // if we don't have a buffer yet, we use an empty/invalid crop
264        crop.makeInvalid();
265    }
266    return crop;
267}
268
269uint32_t Layer::getContentTransform() const {
270    return mCurrentTransform;
271}
272
273static Rect reduce(const Rect& win, const Region& exclude) {
274    if (CC_LIKELY(exclude.isEmpty())) {
275        return win;
276    }
277    if (exclude.isRect()) {
278        return win.reduce(exclude.getBounds());
279    }
280    return Region(win).subtract(exclude).getBounds();
281}
282
283Rect Layer::computeBounds() const {
284    const Layer::State& s(drawingState());
285    Rect win(s.active.w, s.active.h);
286    if (!s.active.crop.isEmpty()) {
287        win.intersect(s.active.crop, &win);
288    }
289    // subtract the transparent region and snap to the bounds
290    return reduce(win, s.activeTransparentRegion);
291}
292
293Rect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
294    /*
295     * The way we compute the crop (aka. texture coordinates when we have a
296     * Layer) produces a different output from the GL code in
297     * drawWithOpenGL() due to HWC being limited to integers. The difference
298     * can be large if getContentTransform() contains a large scale factor.
299     * See comments in drawWithOpenGL() for more details.
300     */
301
302    // the content crop is the area of the content that gets scaled to the
303    // layer's size.
304    Rect crop(getContentCrop());
305
306    // the active.crop is the area of the window that gets cropped, but not
307    // scaled in any ways.
308    const State& s(drawingState());
309
310    // apply the projection's clipping to the window crop in
311    // layerstack space, and convert-back to layer space.
312    // if there are no window scaling (or content scaling) involved,
313    // this operation will map to full pixels in the buffer.
314    // NOTE: should we revert to GL composition if a scaling is involved
315    // since it cannot be represented in the HWC API?
316    Rect activeCrop(s.transform.transform(s.active.crop));
317    activeCrop.intersect(hw->getViewport(), &activeCrop);
318    activeCrop = s.transform.inverse().transform(activeCrop);
319
320    // paranoia: make sure the window-crop is constrained in the
321    // window's bounds
322    activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop);
323
324    // subtract the transparent region and snap to the bounds
325    activeCrop = reduce(activeCrop, s.activeTransparentRegion);
326
327    if (!activeCrop.isEmpty()) {
328        // Transform the window crop to match the buffer coordinate system,
329        // which means using the inverse of the current transform set on the
330        // SurfaceFlingerConsumer.
331        uint32_t invTransform = getContentTransform();
332        int winWidth = s.active.w;
333        int winHeight = s.active.h;
334        if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
335            invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
336                    NATIVE_WINDOW_TRANSFORM_FLIP_H;
337            winWidth = s.active.h;
338            winHeight = s.active.w;
339        }
340        const Rect winCrop = activeCrop.transform(
341                invTransform, s.active.w, s.active.h);
342
343        // the code below essentially performs a scaled intersection
344        // of crop and winCrop
345        float xScale = float(crop.width()) / float(winWidth);
346        float yScale = float(crop.height()) / float(winHeight);
347
348        int insetL = int(ceilf( winCrop.left                * xScale));
349        int insetT = int(ceilf( winCrop.top                 * yScale));
350        int insetR = int(ceilf((winWidth  - winCrop.right ) * xScale));
351        int insetB = int(ceilf((winHeight - winCrop.bottom) * yScale));
352
353        crop.left   += insetL;
354        crop.top    += insetT;
355        crop.right  -= insetR;
356        crop.bottom -= insetB;
357    }
358    return crop;
359}
360
361void Layer::setGeometry(
362    const sp<const DisplayDevice>& hw,
363        HWComposer::HWCLayerInterface& layer)
364{
365    layer.setDefaultState();
366
367    // enable this layer
368    layer.setSkip(false);
369
370    if (isSecure() && !hw->isSecure()) {
371        layer.setSkip(true);
372    }
373
374    // this gives us only the "orientation" component of the transform
375    const State& s(drawingState());
376    if (!isOpaque() || s.alpha != 0xFF) {
377        layer.setBlending(mPremultipliedAlpha ?
378                HWC_BLENDING_PREMULT :
379                HWC_BLENDING_COVERAGE);
380    }
381
382    // apply the layer's transform, followed by the display's global transform
383    // here we're guaranteed that the layer's transform preserves rects
384    Rect frame(s.transform.transform(computeBounds()));
385    frame.intersect(hw->getViewport(), &frame);
386    const Transform& tr(hw->getTransform());
387    layer.setFrame(tr.transform(frame));
388    layer.setCrop(computeCrop(hw));
389    layer.setPlaneAlpha(s.alpha);
390
391    /*
392     * Transformations are applied in this order:
393     * 1) buffer orientation/flip/mirror
394     * 2) state transformation (window manager)
395     * 3) layer orientation (screen orientation)
396     * (NOTE: the matrices are multiplied in reverse order)
397     */
398
399    const Transform bufferOrientation(mCurrentTransform);
400    const Transform transform(tr * s.transform * bufferOrientation);
401
402    // this gives us only the "orientation" component of the transform
403    const uint32_t orientation = transform.getOrientation();
404    if (orientation & Transform::ROT_INVALID) {
405        // we can only handle simple transformation
406        layer.setSkip(true);
407    } else {
408        layer.setTransform(orientation);
409    }
410}
411
412void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
413        HWComposer::HWCLayerInterface& layer) {
414    // we have to set the visible region on every frame because
415    // we currently free it during onLayerDisplayed(), which is called
416    // after HWComposer::commit() -- every frame.
417    // Apply this display's projection's viewport to the visible region
418    // before giving it to the HWC HAL.
419    const Transform& tr = hw->getTransform();
420    Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
421    layer.setVisibleRegionScreen(visible);
422
423    // NOTE: buffer can be NULL if the client never drew into this
424    // layer yet, or if we ran out of memory
425    layer.setBuffer(mActiveBuffer);
426}
427
428void Layer::setAcquireFence(const sp<const DisplayDevice>& hw,
429        HWComposer::HWCLayerInterface& layer) {
430    int fenceFd = -1;
431
432    // TODO: there is a possible optimization here: we only need to set the
433    // acquire fence the first time a new buffer is acquired on EACH display.
434
435    if (layer.getCompositionType() == HWC_OVERLAY) {
436        sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
437        if (fence->isValid()) {
438            fenceFd = fence->dup();
439            if (fenceFd == -1) {
440                ALOGW("failed to dup layer fence, skipping sync: %d", errno);
441            }
442        }
443    }
444    layer.setAcquireFenceFd(fenceFd);
445}
446
447// ---------------------------------------------------------------------------
448// drawing...
449// ---------------------------------------------------------------------------
450
451void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
452    onDraw(hw, clip);
453}
454
455void Layer::draw(const sp<const DisplayDevice>& hw) {
456    onDraw( hw, Region(hw->bounds()) );
457}
458
459void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip) const
460{
461    ATRACE_CALL();
462
463    if (CC_UNLIKELY(mActiveBuffer == 0)) {
464        // the texture has not been created yet, this Layer has
465        // in fact never been drawn into. This happens frequently with
466        // SurfaceView because the WindowManager can't know when the client
467        // has drawn the first time.
468
469        // If there is nothing under us, we paint the screen in black, otherwise
470        // we just skip this update.
471
472        // figure out if there is something below us
473        Region under;
474        const SurfaceFlinger::LayerVector& drawingLayers(
475                mFlinger->mDrawingState.layersSortedByZ);
476        const size_t count = drawingLayers.size();
477        for (size_t i=0 ; i<count ; ++i) {
478            const sp<Layer>& layer(drawingLayers[i]);
479            if (layer.get() == static_cast<Layer const*>(this))
480                break;
481            under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
482        }
483        // if not everything below us is covered, we plug the holes!
484        Region holes(clip.subtract(under));
485        if (!holes.isEmpty()) {
486            clearWithOpenGL(hw, holes, 0, 0, 0, 1);
487        }
488        return;
489    }
490
491    // Bind the current buffer to the GL texture, and wait for it to be
492    // ready for us to draw into.
493    status_t err = mSurfaceFlingerConsumer->bindTextureImage();
494    if (err != NO_ERROR) {
495        ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
496        // Go ahead and draw the buffer anyway; no matter what we do the screen
497        // is probably going to have something visibly wrong.
498    }
499
500    bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
501
502    if (!blackOutLayer) {
503        // TODO: we could be more subtle with isFixedSize()
504        const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
505
506        // Query the texture matrix given our current filtering mode.
507        float textureMatrix[16];
508        mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
509        mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
510
511        // Set things up for texturing.
512        glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureName);
513        GLenum filter = GL_NEAREST;
514        if (useFiltering) {
515            filter = GL_LINEAR;
516        }
517        glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, filter);
518        glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, filter);
519        glMatrixMode(GL_TEXTURE);
520        glLoadMatrixf(textureMatrix);
521        glMatrixMode(GL_MODELVIEW);
522        glDisable(GL_TEXTURE_2D);
523        glEnable(GL_TEXTURE_EXTERNAL_OES);
524    } else {
525        glBindTexture(GL_TEXTURE_2D, mFlinger->getProtectedTexName());
526        glMatrixMode(GL_TEXTURE);
527        glLoadIdentity();
528        glMatrixMode(GL_MODELVIEW);
529        glDisable(GL_TEXTURE_EXTERNAL_OES);
530        glEnable(GL_TEXTURE_2D);
531    }
532
533    drawWithOpenGL(hw, clip);
534
535    glDisable(GL_TEXTURE_EXTERNAL_OES);
536    glDisable(GL_TEXTURE_2D);
537}
538
539
540void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw, const Region& clip,
541        GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) const
542{
543    const uint32_t fbHeight = hw->getHeight();
544    glColor4f(red,green,blue,alpha);
545
546    glDisable(GL_TEXTURE_EXTERNAL_OES);
547    glDisable(GL_TEXTURE_2D);
548    glDisable(GL_BLEND);
549
550    LayerMesh mesh;
551    computeGeometry(hw, &mesh);
552
553    glVertexPointer(2, GL_FLOAT, 0, mesh.getVertices());
554    glDrawArrays(GL_TRIANGLE_FAN, 0, mesh.getVertexCount());
555}
556
557void Layer::clearWithOpenGL(
558        const sp<const DisplayDevice>& hw, const Region& clip) const {
559    clearWithOpenGL(hw, clip, 0,0,0,0);
560}
561
562void Layer::drawWithOpenGL(
563        const sp<const DisplayDevice>& hw, const Region& clip) const {
564    const uint32_t fbHeight = hw->getHeight();
565    const State& s(drawingState());
566
567    GLenum src = mPremultipliedAlpha ? GL_ONE : GL_SRC_ALPHA;
568    if (CC_UNLIKELY(s.alpha < 0xFF)) {
569        const GLfloat alpha = s.alpha * (1.0f/255.0f);
570        if (mPremultipliedAlpha) {
571            glColor4f(alpha, alpha, alpha, alpha);
572        } else {
573            glColor4f(1, 1, 1, alpha);
574        }
575        glEnable(GL_BLEND);
576        glBlendFunc(src, GL_ONE_MINUS_SRC_ALPHA);
577        glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
578    } else {
579        glColor4f(1, 1, 1, 1);
580        glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
581        if (!isOpaque()) {
582            glEnable(GL_BLEND);
583            glBlendFunc(src, GL_ONE_MINUS_SRC_ALPHA);
584        } else {
585            glDisable(GL_BLEND);
586        }
587    }
588
589    LayerMesh mesh;
590    computeGeometry(hw, &mesh);
591
592    // TODO: we probably want to generate the texture coords with the mesh
593    // here we assume that we only have 4 vertices
594
595    struct TexCoords {
596        GLfloat u;
597        GLfloat v;
598    };
599
600
601    /*
602     * NOTE: the way we compute the texture coordinates here produces
603     * different results than when we take the HWC path -- in the later case
604     * the "source crop" is rounded to texel boundaries.
605     * This can produce significantly different results when the texture
606     * is scaled by a large amount.
607     *
608     * The GL code below is more logical (imho), and the difference with
609     * HWC is due to a limitation of the HWC API to integers -- a question
610     * is suspend is wether we should ignore this problem or revert to
611     * GL composition when a buffer scaling is applied (maybe with some
612     * minimal value)? Or, we could make GL behave like HWC -- but this feel
613     * like more of a hack.
614     */
615    const Rect win(computeBounds());
616
617    GLfloat left   = GLfloat(win.left)   / GLfloat(s.active.w);
618    GLfloat top    = GLfloat(win.top)    / GLfloat(s.active.h);
619    GLfloat right  = GLfloat(win.right)  / GLfloat(s.active.w);
620    GLfloat bottom = GLfloat(win.bottom) / GLfloat(s.active.h);
621
622    TexCoords texCoords[4];
623    texCoords[0].u = left;
624    texCoords[0].v = top;
625    texCoords[1].u = left;
626    texCoords[1].v = bottom;
627    texCoords[2].u = right;
628    texCoords[2].v = bottom;
629    texCoords[3].u = right;
630    texCoords[3].v = top;
631    for (int i = 0; i < 4; i++) {
632        texCoords[i].v = 1.0f - texCoords[i].v;
633    }
634
635    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
636    glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
637    glVertexPointer(2, GL_FLOAT, 0, mesh.getVertices());
638    glDrawArrays(GL_TRIANGLE_FAN, 0, mesh.getVertexCount());
639
640    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
641    glDisable(GL_BLEND);
642}
643
644void Layer::setFiltering(bool filtering) {
645    mFiltering = filtering;
646}
647
648bool Layer::getFiltering() const {
649    return mFiltering;
650}
651
652// As documented in libhardware header, formats in the range
653// 0x100 - 0x1FF are specific to the HAL implementation, and
654// are known to have no alpha channel
655// TODO: move definition for device-specific range into
656// hardware.h, instead of using hard-coded values here.
657#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
658
659bool Layer::getOpacityForFormat(uint32_t format)
660{
661    if (HARDWARE_IS_DEVICE_FORMAT(format)) {
662        return true;
663    }
664    PixelFormatInfo info;
665    status_t err = getPixelFormatInfo(PixelFormat(format), &info);
666    // in case of error (unknown format), we assume no blending
667    return (err || info.h_alpha <= info.l_alpha);
668}
669
670// ----------------------------------------------------------------------------
671// local state
672// ----------------------------------------------------------------------------
673
674void Layer::computeGeometry(const sp<const DisplayDevice>& hw, LayerMesh* mesh) const
675{
676    const Layer::State& s(drawingState());
677    const Transform tr(hw->getTransform() * s.transform);
678    const uint32_t hw_h = hw->getHeight();
679    Rect win(s.active.w, s.active.h);
680    if (!s.active.crop.isEmpty()) {
681        win.intersect(s.active.crop, &win);
682    }
683    // subtract the transparent region and snap to the bounds
684    win = reduce(win, s.activeTransparentRegion);
685    if (mesh) {
686        tr.transform(mesh->mVertices[0], win.left,  win.top);
687        tr.transform(mesh->mVertices[1], win.left,  win.bottom);
688        tr.transform(mesh->mVertices[2], win.right, win.bottom);
689        tr.transform(mesh->mVertices[3], win.right, win.top);
690        for (size_t i=0 ; i<4 ; i++) {
691            mesh->mVertices[i][1] = hw_h - mesh->mVertices[i][1];
692        }
693    }
694}
695
696bool Layer::isOpaque() const
697{
698    // if we don't have a buffer yet, we're translucent regardless of the
699    // layer's opaque flag.
700    if (mActiveBuffer == 0) {
701        return false;
702    }
703
704    // if the layer has the opaque flag, then we're always opaque,
705    // otherwise we use the current buffer's format.
706    return mOpaqueLayer || mCurrentOpacity;
707}
708
709bool Layer::isProtected() const
710{
711    const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
712    return (activeBuffer != 0) &&
713            (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
714}
715
716bool Layer::isFixedSize() const {
717    return mCurrentScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE;
718}
719
720bool Layer::isCropped() const {
721    return !mCurrentCrop.isEmpty();
722}
723
724bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
725    return mNeedsFiltering || hw->needsFiltering();
726}
727
728void Layer::setVisibleRegion(const Region& visibleRegion) {
729    // always called from main thread
730    this->visibleRegion = visibleRegion;
731}
732
733void Layer::setCoveredRegion(const Region& coveredRegion) {
734    // always called from main thread
735    this->coveredRegion = coveredRegion;
736}
737
738void Layer::setVisibleNonTransparentRegion(const Region&
739        setVisibleNonTransparentRegion) {
740    // always called from main thread
741    this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
742}
743
744// ----------------------------------------------------------------------------
745// transaction
746// ----------------------------------------------------------------------------
747
748uint32_t Layer::doTransaction(uint32_t flags) {
749    ATRACE_CALL();
750
751    const Layer::State& front(drawingState());
752    const Layer::State& temp(currentState());
753
754    const bool sizeChanged = (temp.requested.w != front.requested.w) ||
755                             (temp.requested.h != front.requested.h);
756
757    if (sizeChanged) {
758        // the size changed, we need to ask our client to request a new buffer
759        ALOGD_IF(DEBUG_RESIZE,
760                "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
761                "  current={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
762                "            requested={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }}\n"
763                "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
764                "            requested={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }}\n",
765                this, (const char*) getName(), mCurrentTransform, mCurrentScalingMode,
766                temp.active.w, temp.active.h,
767                temp.active.crop.left,
768                temp.active.crop.top,
769                temp.active.crop.right,
770                temp.active.crop.bottom,
771                temp.active.crop.getWidth(),
772                temp.active.crop.getHeight(),
773                temp.requested.w, temp.requested.h,
774                temp.requested.crop.left,
775                temp.requested.crop.top,
776                temp.requested.crop.right,
777                temp.requested.crop.bottom,
778                temp.requested.crop.getWidth(),
779                temp.requested.crop.getHeight(),
780                front.active.w, front.active.h,
781                front.active.crop.left,
782                front.active.crop.top,
783                front.active.crop.right,
784                front.active.crop.bottom,
785                front.active.crop.getWidth(),
786                front.active.crop.getHeight(),
787                front.requested.w, front.requested.h,
788                front.requested.crop.left,
789                front.requested.crop.top,
790                front.requested.crop.right,
791                front.requested.crop.bottom,
792                front.requested.crop.getWidth(),
793                front.requested.crop.getHeight());
794
795        // record the new size, form this point on, when the client request
796        // a buffer, it'll get the new size.
797        mSurfaceFlingerConsumer->setDefaultBufferSize(
798                temp.requested.w, temp.requested.h);
799    }
800
801    if (!isFixedSize()) {
802
803        const bool resizePending = (temp.requested.w != temp.active.w) ||
804                                   (temp.requested.h != temp.active.h);
805
806        if (resizePending) {
807            // don't let Layer::doTransaction update the drawing state
808            // if we have a pending resize, unless we are in fixed-size mode.
809            // the drawing state will be updated only once we receive a buffer
810            // with the correct size.
811            //
812            // in particular, we want to make sure the clip (which is part
813            // of the geometry state) is latched together with the size but is
814            // latched immediately when no resizing is involved.
815
816            flags |= eDontUpdateGeometryState;
817        }
818    }
819
820    // always set active to requested, unless we're asked not to
821    // this is used by Layer, which special cases resizes.
822    if (flags & eDontUpdateGeometryState)  {
823    } else {
824        Layer::State& editTemp(currentState());
825        editTemp.active = temp.requested;
826    }
827
828    if (front.active != temp.active) {
829        // invalidate and recompute the visible regions if needed
830        flags |= Layer::eVisibleRegion;
831    }
832
833    if (temp.sequence != front.sequence) {
834        // invalidate and recompute the visible regions if needed
835        flags |= eVisibleRegion;
836        this->contentDirty = true;
837
838        // we may use linear filtering, if the matrix scales us
839        const uint8_t type = temp.transform.getType();
840        mNeedsFiltering = (!temp.transform.preserveRects() ||
841                (type >= Transform::SCALE));
842    }
843
844    // Commit the transaction
845    commitTransaction();
846    return flags;
847}
848
849void Layer::commitTransaction() {
850    mDrawingState = mCurrentState;
851}
852
853uint32_t Layer::getTransactionFlags(uint32_t flags) {
854    return android_atomic_and(~flags, &mTransactionFlags) & flags;
855}
856
857uint32_t Layer::setTransactionFlags(uint32_t flags) {
858    return android_atomic_or(flags, &mTransactionFlags);
859}
860
861bool Layer::setPosition(float x, float y) {
862    if (mCurrentState.transform.tx() == x && mCurrentState.transform.ty() == y)
863        return false;
864    mCurrentState.sequence++;
865    mCurrentState.transform.set(x, y);
866    setTransactionFlags(eTransactionNeeded);
867    return true;
868}
869bool Layer::setLayer(uint32_t z) {
870    if (mCurrentState.z == z)
871        return false;
872    mCurrentState.sequence++;
873    mCurrentState.z = z;
874    setTransactionFlags(eTransactionNeeded);
875    return true;
876}
877bool Layer::setSize(uint32_t w, uint32_t h) {
878    if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
879        return false;
880    mCurrentState.requested.w = w;
881    mCurrentState.requested.h = h;
882    setTransactionFlags(eTransactionNeeded);
883    return true;
884}
885bool Layer::setAlpha(uint8_t alpha) {
886    if (mCurrentState.alpha == alpha)
887        return false;
888    mCurrentState.sequence++;
889    mCurrentState.alpha = alpha;
890    setTransactionFlags(eTransactionNeeded);
891    return true;
892}
893bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
894    mCurrentState.sequence++;
895    mCurrentState.transform.set(
896            matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
897    setTransactionFlags(eTransactionNeeded);
898    return true;
899}
900bool Layer::setTransparentRegionHint(const Region& transparent) {
901    mCurrentState.requestedTransparentRegion = transparent;
902    setTransactionFlags(eTransactionNeeded);
903    return true;
904}
905bool Layer::setFlags(uint8_t flags, uint8_t mask) {
906    const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
907    if (mCurrentState.flags == newFlags)
908        return false;
909    mCurrentState.sequence++;
910    mCurrentState.flags = newFlags;
911    setTransactionFlags(eTransactionNeeded);
912    return true;
913}
914bool Layer::setCrop(const Rect& crop) {
915    if (mCurrentState.requested.crop == crop)
916        return false;
917    mCurrentState.sequence++;
918    mCurrentState.requested.crop = crop;
919    setTransactionFlags(eTransactionNeeded);
920    return true;
921}
922
923bool Layer::setLayerStack(uint32_t layerStack) {
924    if (mCurrentState.layerStack == layerStack)
925        return false;
926    mCurrentState.sequence++;
927    mCurrentState.layerStack = layerStack;
928    setTransactionFlags(eTransactionNeeded);
929    return true;
930}
931
932// ----------------------------------------------------------------------------
933// pageflip handling...
934// ----------------------------------------------------------------------------
935
936bool Layer::onPreComposition() {
937    mRefreshPending = false;
938    return mQueuedFrames > 0;
939}
940
941void Layer::onPostComposition() {
942    if (mFrameLatencyNeeded) {
943        nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
944        mFrameTracker.setDesiredPresentTime(desiredPresentTime);
945
946        sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence();
947        if (frameReadyFence->isValid()) {
948            mFrameTracker.setFrameReadyFence(frameReadyFence);
949        } else {
950            // There was no fence for this frame, so assume that it was ready
951            // to be presented at the desired present time.
952            mFrameTracker.setFrameReadyTime(desiredPresentTime);
953        }
954
955        const HWComposer& hwc = mFlinger->getHwComposer();
956        sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
957        if (presentFence->isValid()) {
958            mFrameTracker.setActualPresentFence(presentFence);
959        } else {
960            // The HWC doesn't support present fences, so use the refresh
961            // timestamp instead.
962            nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
963            mFrameTracker.setActualPresentTime(presentTime);
964        }
965
966        mFrameTracker.advanceFrame();
967        mFrameLatencyNeeded = false;
968    }
969}
970
971bool Layer::isVisible() const {
972    const Layer::State& s(mDrawingState);
973    return !(s.flags & layer_state_t::eLayerHidden) && s.alpha
974            && (mActiveBuffer != NULL);
975}
976
977Region Layer::latchBuffer(bool& recomputeVisibleRegions)
978{
979    ATRACE_CALL();
980
981    Region outDirtyRegion;
982    if (mQueuedFrames > 0) {
983
984        // if we've already called updateTexImage() without going through
985        // a composition step, we have to skip this layer at this point
986        // because we cannot call updateTeximage() without a corresponding
987        // compositionComplete() call.
988        // we'll trigger an update in onPreComposition().
989        if (mRefreshPending) {
990            return outDirtyRegion;
991        }
992
993        // Capture the old state of the layer for comparisons later
994        const bool oldOpacity = isOpaque();
995        sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
996
997        // signal another event if we have more frames pending
998        if (android_atomic_dec(&mQueuedFrames) > 1) {
999            mFlinger->signalLayerUpdate();
1000        }
1001
1002        struct Reject : public SurfaceFlingerConsumer::BufferRejecter {
1003            Layer::State& front;
1004            Layer::State& current;
1005            bool& recomputeVisibleRegions;
1006            Reject(Layer::State& front, Layer::State& current,
1007                    bool& recomputeVisibleRegions)
1008                : front(front), current(current),
1009                  recomputeVisibleRegions(recomputeVisibleRegions) {
1010            }
1011
1012            virtual bool reject(const sp<GraphicBuffer>& buf,
1013                    const BufferQueue::BufferItem& item) {
1014                if (buf == NULL) {
1015                    return false;
1016                }
1017
1018                uint32_t bufWidth  = buf->getWidth();
1019                uint32_t bufHeight = buf->getHeight();
1020
1021                // check that we received a buffer of the right size
1022                // (Take the buffer's orientation into account)
1023                if (item.mTransform & Transform::ROT_90) {
1024                    swap(bufWidth, bufHeight);
1025                }
1026
1027                bool isFixedSize = item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1028                if (front.active != front.requested) {
1029
1030                    if (isFixedSize ||
1031                            (bufWidth == front.requested.w &&
1032                             bufHeight == front.requested.h))
1033                    {
1034                        // Here we pretend the transaction happened by updating the
1035                        // current and drawing states. Drawing state is only accessed
1036                        // in this thread, no need to have it locked
1037                        front.active = front.requested;
1038
1039                        // We also need to update the current state so that
1040                        // we don't end-up overwriting the drawing state with
1041                        // this stale current state during the next transaction
1042                        //
1043                        // NOTE: We don't need to hold the transaction lock here
1044                        // because State::active is only accessed from this thread.
1045                        current.active = front.active;
1046
1047                        // recompute visible region
1048                        recomputeVisibleRegions = true;
1049                    }
1050
1051                    ALOGD_IF(DEBUG_RESIZE,
1052                            "latchBuffer/reject: buffer (%ux%u, tr=%02x), scalingMode=%d\n"
1053                            "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1054                            "            requested={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }}\n",
1055                            bufWidth, bufHeight, item.mTransform, item.mScalingMode,
1056                            front.active.w, front.active.h,
1057                            front.active.crop.left,
1058                            front.active.crop.top,
1059                            front.active.crop.right,
1060                            front.active.crop.bottom,
1061                            front.active.crop.getWidth(),
1062                            front.active.crop.getHeight(),
1063                            front.requested.w, front.requested.h,
1064                            front.requested.crop.left,
1065                            front.requested.crop.top,
1066                            front.requested.crop.right,
1067                            front.requested.crop.bottom,
1068                            front.requested.crop.getWidth(),
1069                            front.requested.crop.getHeight());
1070                }
1071
1072                if (!isFixedSize) {
1073                    if (front.active.w != bufWidth ||
1074                        front.active.h != bufHeight) {
1075                        // reject this buffer
1076                        return true;
1077                    }
1078                }
1079
1080                // if the transparent region has changed (this test is
1081                // conservative, but that's fine, worst case we're doing
1082                // a bit of extra work), we latch the new one and we
1083                // trigger a visible-region recompute.
1084                if (!front.activeTransparentRegion.isTriviallyEqual(
1085                        front.requestedTransparentRegion)) {
1086                    front.activeTransparentRegion = front.requestedTransparentRegion;
1087
1088                    // We also need to update the current state so that
1089                    // we don't end-up overwriting the drawing state with
1090                    // this stale current state during the next transaction
1091                    //
1092                    // NOTE: We don't need to hold the transaction lock here
1093                    // because State::active is only accessed from this thread.
1094                    current.activeTransparentRegion = front.activeTransparentRegion;
1095
1096                    // recompute visible region
1097                    recomputeVisibleRegions = true;
1098                }
1099
1100                return false;
1101            }
1102        };
1103
1104
1105        Reject r(mDrawingState, currentState(), recomputeVisibleRegions);
1106
1107        if (mSurfaceFlingerConsumer->updateTexImage(&r) != NO_ERROR) {
1108            // something happened!
1109            recomputeVisibleRegions = true;
1110            return outDirtyRegion;
1111        }
1112
1113        // update the active buffer
1114        mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer();
1115        if (mActiveBuffer == NULL) {
1116            // this can only happen if the very first buffer was rejected.
1117            return outDirtyRegion;
1118        }
1119
1120        mRefreshPending = true;
1121        mFrameLatencyNeeded = true;
1122        if (oldActiveBuffer == NULL) {
1123             // the first time we receive a buffer, we need to trigger a
1124             // geometry invalidation.
1125            recomputeVisibleRegions = true;
1126         }
1127
1128        Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
1129        const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
1130        const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
1131        if ((crop != mCurrentCrop) ||
1132            (transform != mCurrentTransform) ||
1133            (scalingMode != mCurrentScalingMode))
1134        {
1135            mCurrentCrop = crop;
1136            mCurrentTransform = transform;
1137            mCurrentScalingMode = scalingMode;
1138            recomputeVisibleRegions = true;
1139        }
1140
1141        if (oldActiveBuffer != NULL) {
1142            uint32_t bufWidth  = mActiveBuffer->getWidth();
1143            uint32_t bufHeight = mActiveBuffer->getHeight();
1144            if (bufWidth != uint32_t(oldActiveBuffer->width) ||
1145                bufHeight != uint32_t(oldActiveBuffer->height)) {
1146                recomputeVisibleRegions = true;
1147            }
1148        }
1149
1150        mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
1151        if (oldOpacity != isOpaque()) {
1152            recomputeVisibleRegions = true;
1153        }
1154
1155        glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1156        glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1157
1158        // FIXME: postedRegion should be dirty & bounds
1159        const Layer::State& front(drawingState());
1160        Region dirtyRegion(Rect(front.active.w, front.active.h));
1161
1162        // transform the dirty region to window-manager space
1163        outDirtyRegion = (front.transform.transform(dirtyRegion));
1164    }
1165    return outDirtyRegion;
1166}
1167
1168uint32_t Layer::getEffectiveUsage(uint32_t usage) const
1169{
1170    // TODO: should we do something special if mSecure is set?
1171    if (mProtectedByApp) {
1172        // need a hardware-protected path to external video sink
1173        usage |= GraphicBuffer::USAGE_PROTECTED;
1174    }
1175    usage |= GraphicBuffer::USAGE_HW_COMPOSER;
1176    return usage;
1177}
1178
1179void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
1180    uint32_t orientation = 0;
1181    if (!mFlinger->mDebugDisableTransformHint) {
1182        // The transform hint is used to improve performance, but we can
1183        // only have a single transform hint, it cannot
1184        // apply to all displays.
1185        const Transform& planeTransform(hw->getTransform());
1186        orientation = planeTransform.getOrientation();
1187        if (orientation & Transform::ROT_INVALID) {
1188            orientation = 0;
1189        }
1190    }
1191    mSurfaceFlingerConsumer->setTransformHint(orientation);
1192}
1193
1194// ----------------------------------------------------------------------------
1195// debugging
1196// ----------------------------------------------------------------------------
1197
1198void Layer::dump(String8& result, Colorizer& colorizer) const
1199{
1200    const Layer::State& s(drawingState());
1201
1202    colorizer.colorize(result, Colorizer::GREEN);
1203    result.appendFormat(
1204            "+ %s %p (%s)\n",
1205            getTypeId(), this, getName().string());
1206    colorizer.reset(result);
1207
1208    s.activeTransparentRegion.dump(result, "transparentRegion");
1209    visibleRegion.dump(result, "visibleRegion");
1210    sp<Client> client(mClientRef.promote());
1211
1212    result.appendFormat(            "      "
1213            "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), crop=(%4d,%4d,%4d,%4d), "
1214            "isOpaque=%1d, invalidate=%1d, "
1215            "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
1216            "      client=%p\n",
1217            s.layerStack, s.z, s.transform.tx(), s.transform.ty(), s.active.w, s.active.h,
1218            s.active.crop.left, s.active.crop.top,
1219            s.active.crop.right, s.active.crop.bottom,
1220            isOpaque(), contentDirty,
1221            s.alpha, s.flags,
1222            s.transform[0][0], s.transform[0][1],
1223            s.transform[1][0], s.transform[1][1],
1224            client.get());
1225
1226    sp<const GraphicBuffer> buf0(mActiveBuffer);
1227    uint32_t w0=0, h0=0, s0=0, f0=0;
1228    if (buf0 != 0) {
1229        w0 = buf0->getWidth();
1230        h0 = buf0->getHeight();
1231        s0 = buf0->getStride();
1232        f0 = buf0->format;
1233    }
1234    result.appendFormat(
1235            "      "
1236            "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
1237            " queued-frames=%d, mRefreshPending=%d\n",
1238            mFormat, w0, h0, s0,f0,
1239            mQueuedFrames, mRefreshPending);
1240
1241    if (mSurfaceFlingerConsumer != 0) {
1242        mSurfaceFlingerConsumer->dump(result, "            ");
1243    }
1244}
1245
1246void Layer::dumpStats(String8& result) const {
1247    mFrameTracker.dump(result);
1248}
1249
1250void Layer::clearStats() {
1251    mFrameTracker.clear();
1252}
1253
1254// ---------------------------------------------------------------------------
1255
1256Layer::LayerCleaner::LayerCleaner(const sp<SurfaceFlinger>& flinger,
1257        const sp<Layer>& layer)
1258    : mFlinger(flinger), mLayer(layer) {
1259}
1260
1261Layer::LayerCleaner::~LayerCleaner() {
1262    // destroy client resources
1263    mFlinger->onLayerDestroyed(mLayer);
1264}
1265
1266// ---------------------------------------------------------------------------
1267
1268
1269}; // namespace android
1270