Layer.cpp revision c5953904ad6b6db1f48cf6d208ecf940f6a656d4
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#include <stdlib.h>
18#include <stdint.h>
19#include <sys/types.h>
20
21#include <cutils/compiler.h>
22#include <cutils/native_handle.h>
23#include <cutils/properties.h>
24
25#include <utils/Errors.h>
26#include <utils/Log.h>
27#include <utils/StopWatch.h>
28
29#include <ui/GraphicBuffer.h>
30#include <ui/PixelFormat.h>
31
32#include <surfaceflinger/Surface.h>
33
34#include "clz.h"
35#include "DisplayHardware/DisplayHardware.h"
36#include "DisplayHardware/HWComposer.h"
37#include "GLExtensions.h"
38#include "Layer.h"
39#include "SurfaceFlinger.h"
40#include "SurfaceTextureLayer.h"
41
42#define DEBUG_RESIZE    0
43
44
45namespace android {
46
47// ---------------------------------------------------------------------------
48
49Layer::Layer(SurfaceFlinger* flinger,
50        DisplayID display, const sp<Client>& client)
51    :   LayerBaseClient(flinger, display, client),
52        mTextureName(-1U),
53        mQueuedFrames(0),
54        mCurrentTransform(0),
55        mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
56        mCurrentOpacity(true),
57        mFormat(PIXEL_FORMAT_NONE),
58        mGLExtensions(GLExtensions::getInstance()),
59        mOpaqueLayer(true),
60        mNeedsDithering(false),
61        mSecure(false),
62        mProtectedByApp(false)
63{
64    mCurrentCrop.makeInvalid();
65    glGenTextures(1, &mTextureName);
66}
67
68void Layer::onFirstRef()
69{
70    LayerBaseClient::onFirstRef();
71
72    struct FrameQueuedListener : public SurfaceTexture::FrameAvailableListener {
73        FrameQueuedListener(Layer* layer) : mLayer(layer) { }
74    private:
75        wp<Layer> mLayer;
76        virtual void onFrameAvailable() {
77            sp<Layer> that(mLayer.promote());
78            if (that != 0) {
79                that->onFrameQueued();
80            }
81        }
82    };
83    mSurfaceTexture = new SurfaceTextureLayer(mTextureName, this);
84    mSurfaceTexture->setFrameAvailableListener(new FrameQueuedListener(this));
85    mSurfaceTexture->setSynchronousMode(true);
86    mSurfaceTexture->setBufferCountServer(2);
87}
88
89Layer::~Layer()
90{
91    class MessageDestroyGLState : public MessageBase {
92        GLuint texture;
93    public:
94        MessageDestroyGLState(GLuint texture) : texture(texture) { }
95        virtual bool handler() {
96            glDeleteTextures(1, &texture);
97            return true;
98        }
99    };
100    mFlinger->postMessageAsync( new MessageDestroyGLState(mTextureName) );
101}
102
103void Layer::onFrameQueued() {
104    android_atomic_inc(&mQueuedFrames);
105    mFlinger->signalEvent();
106}
107
108// called with SurfaceFlinger::mStateLock as soon as the layer is entered
109// in the purgatory list
110void Layer::onRemoved()
111{
112    mSurfaceTexture->abandon();
113}
114
115sp<ISurface> Layer::createSurface()
116{
117    class BSurface : public BnSurface, public LayerCleaner {
118        wp<const Layer> mOwner;
119        virtual sp<ISurfaceTexture> getSurfaceTexture() const {
120            sp<ISurfaceTexture> res;
121            sp<const Layer> that( mOwner.promote() );
122            if (that != NULL) {
123                res = that->mSurfaceTexture;
124            }
125            return res;
126        }
127    public:
128        BSurface(const sp<SurfaceFlinger>& flinger,
129                const sp<Layer>& layer)
130            : LayerCleaner(flinger, layer), mOwner(layer) { }
131    };
132    sp<ISurface> sur(new BSurface(mFlinger, this));
133    return sur;
134}
135
136status_t Layer::setBuffers( uint32_t w, uint32_t h,
137                            PixelFormat format, uint32_t flags)
138{
139    // this surfaces pixel format
140    PixelFormatInfo info;
141    status_t err = getPixelFormatInfo(format, &info);
142    if (err) return err;
143
144    // the display's pixel format
145    const DisplayHardware& hw(graphicPlane(0).displayHardware());
146    uint32_t const maxSurfaceDims = min(
147            hw.getMaxTextureSize(), hw.getMaxViewportDims());
148
149    // never allow a surface larger than what our underlying GL implementation
150    // can handle.
151    if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
152        return BAD_VALUE;
153    }
154
155    PixelFormatInfo displayInfo;
156    getPixelFormatInfo(hw.getFormat(), &displayInfo);
157    const uint32_t hwFlags = hw.getFlags();
158
159    mFormat = format;
160
161    mSecure = (flags & ISurfaceComposer::eSecure) ? true : false;
162    mProtectedByApp = (flags & ISurfaceComposer::eProtectedByApp) ? true : false;
163    mOpaqueLayer = (flags & ISurfaceComposer::eOpaque);
164    mCurrentOpacity = getOpacityForFormat(format);
165
166    mSurfaceTexture->setDefaultBufferSize(w, h);
167    mSurfaceTexture->setDefaultBufferFormat(format);
168
169    // we use the red index
170    int displayRedSize = displayInfo.getSize(PixelFormatInfo::INDEX_RED);
171    int layerRedsize = info.getSize(PixelFormatInfo::INDEX_RED);
172    mNeedsDithering = layerRedsize > displayRedSize;
173
174    return NO_ERROR;
175}
176
177void Layer::setGeometry(hwc_layer_t* hwcl)
178{
179    LayerBaseClient::setGeometry(hwcl);
180
181    hwcl->flags &= ~HWC_SKIP_LAYER;
182
183    // we can't do alpha-fade with the hwc HAL
184    const State& s(drawingState());
185    if (s.alpha < 0xFF) {
186        hwcl->flags = HWC_SKIP_LAYER;
187    }
188
189    /*
190     * Transformations are applied in this order:
191     * 1) buffer orientation/flip/mirror
192     * 2) state transformation (window manager)
193     * 3) layer orientation (screen orientation)
194     * mOrientation is already the composition of (2) and (3)
195     * (NOTE: the matrices are multiplied in reverse order)
196     */
197
198    const Transform bufferOrientation(mCurrentTransform);
199    const Transform layerOrientation(mOrientation);
200    const Transform tr(layerOrientation * bufferOrientation);
201
202    // this gives us only the "orientation" component of the transform
203    const uint32_t finalTransform = tr.getOrientation();
204
205    // we can only handle simple transformation
206    if (finalTransform & Transform::ROT_INVALID) {
207        hwcl->flags = HWC_SKIP_LAYER;
208    } else {
209        hwcl->transform = finalTransform;
210    }
211}
212
213void Layer::setPerFrameData(hwc_layer_t* hwcl) {
214    const sp<GraphicBuffer>& buffer(mActiveBuffer);
215    if (buffer == NULL) {
216        // this can happen if the client never drew into this layer yet,
217        // or if we ran out of memory. In that case, don't let
218        // HWC handle it.
219        hwcl->flags |= HWC_SKIP_LAYER;
220        hwcl->handle = NULL;
221    } else {
222        hwcl->handle = buffer->handle;
223    }
224
225    if (isCropped()) {
226        hwcl->sourceCrop.left   = mCurrentCrop.left;
227        hwcl->sourceCrop.top    = mCurrentCrop.top;
228        hwcl->sourceCrop.right  = mCurrentCrop.right;
229        hwcl->sourceCrop.bottom = mCurrentCrop.bottom;
230    } else {
231        hwcl->sourceCrop.left   = 0;
232        hwcl->sourceCrop.top    = 0;
233        if (buffer != NULL) {
234            hwcl->sourceCrop.right  = buffer->width;
235            hwcl->sourceCrop.bottom = buffer->height;
236        } else {
237            hwcl->sourceCrop.right  = mTransformedBounds.width();
238            hwcl->sourceCrop.bottom = mTransformedBounds.height();
239        }
240    }
241}
242
243static inline uint16_t pack565(int r, int g, int b) {
244    return (r<<11)|(g<<5)|b;
245}
246void Layer::onDraw(const Region& clip) const
247{
248    if (CC_UNLIKELY(mActiveBuffer == 0)) {
249        // the texture has not been created yet, this Layer has
250        // in fact never been drawn into. This happens frequently with
251        // SurfaceView because the WindowManager can't know when the client
252        // has drawn the first time.
253
254        // If there is nothing under us, we paint the screen in black, otherwise
255        // we just skip this update.
256
257        // figure out if there is something below us
258        Region under;
259        const SurfaceFlinger::LayerVector& drawingLayers(mFlinger->mDrawingState.layersSortedByZ);
260        const size_t count = drawingLayers.size();
261        for (size_t i=0 ; i<count ; ++i) {
262            const sp<LayerBase>& layer(drawingLayers[i]);
263            if (layer.get() == static_cast<LayerBase const*>(this))
264                break;
265            under.orSelf(layer->visibleRegionScreen);
266        }
267        // if not everything below us is covered, we plug the holes!
268        Region holes(clip.subtract(under));
269        if (!holes.isEmpty()) {
270            clearWithOpenGL(holes, 0, 0, 0, 1);
271        }
272        return;
273    }
274
275    GLenum target = mSurfaceTexture->getCurrentTextureTarget();
276    glBindTexture(target, mTextureName);
277    if (getFiltering() || needsFiltering() || isFixedSize() || isCropped()) {
278        // TODO: we could be more subtle with isFixedSize()
279        glTexParameterx(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
280        glTexParameterx(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
281    } else {
282        glTexParameterx(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
283        glTexParameterx(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
284    }
285    glEnable(target);
286    glMatrixMode(GL_TEXTURE);
287    glLoadMatrixf(mTextureMatrix);
288    glMatrixMode(GL_MODELVIEW);
289
290    drawWithOpenGL(clip);
291
292    glDisable(target);
293}
294
295// As documented in libhardware header, formats in the range
296// 0x100 - 0x1FF are specific to the HAL implementation, and
297// are known to have no alpha channel
298// TODO: move definition for device-specific range into
299// hardware.h, instead of using hard-coded values here.
300#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
301
302bool Layer::getOpacityForFormat(uint32_t format)
303{
304    if (HARDWARE_IS_DEVICE_FORMAT(format)) {
305        return true;
306    }
307    PixelFormatInfo info;
308    status_t err = getPixelFormatInfo(PixelFormat(format), &info);
309    // in case of error (unknown format), we assume no blending
310    return (err || info.h_alpha <= info.l_alpha);
311}
312
313
314bool Layer::isOpaque() const
315{
316    // if we don't have a buffer yet, we're translucent regardless of the
317    // layer's opaque flag.
318    if (mActiveBuffer == 0) {
319        return false;
320    }
321
322    // if the layer has the opaque flag, then we're always opaque,
323    // otherwise we use the current buffer's format.
324    return mOpaqueLayer || mCurrentOpacity;
325}
326
327bool Layer::isProtected() const
328{
329    const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
330    return (activeBuffer != 0) &&
331            (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
332}
333
334uint32_t Layer::doTransaction(uint32_t flags)
335{
336    const Layer::State& front(drawingState());
337    const Layer::State& temp(currentState());
338
339    const bool sizeChanged = (front.requested_w != temp.requested_w) ||
340            (front.requested_h != temp.requested_h);
341
342    if (sizeChanged) {
343        // the size changed, we need to ask our client to request a new buffer
344        LOGD_IF(DEBUG_RESIZE,
345                "doTransaction: "
346                "resize (layer=%p), requested (%dx%d), drawing (%d,%d), "
347                "scalingMode=%d",
348                this,
349                int(temp.requested_w), int(temp.requested_h),
350                int(front.requested_w), int(front.requested_h),
351                mCurrentScalingMode);
352
353        if (!isFixedSize()) {
354            // we're being resized and there is a freeze display request,
355            // acquire a freeze lock, so that the screen stays put
356            // until we've redrawn at the new size; this is to avoid
357            // glitches upon orientation changes.
358            if (mFlinger->hasFreezeRequest()) {
359                // if the surface is hidden, don't try to acquire the
360                // freeze lock, since hidden surfaces may never redraw
361                if (!(front.flags & ISurfaceComposer::eLayerHidden)) {
362                    mFreezeLock = mFlinger->getFreezeLock();
363                }
364            }
365
366            // this will make sure LayerBase::doTransaction doesn't update
367            // the drawing state's size
368            Layer::State& editDraw(mDrawingState);
369            editDraw.requested_w = temp.requested_w;
370            editDraw.requested_h = temp.requested_h;
371
372            // record the new size, form this point on, when the client request
373            // a buffer, it'll get the new size.
374            mSurfaceTexture->setDefaultBufferSize(temp.requested_w, temp.requested_h);
375        }
376    }
377
378    if (temp.sequence != front.sequence) {
379        if (temp.flags & ISurfaceComposer::eLayerHidden || temp.alpha == 0) {
380            // this surface is now hidden, so it shouldn't hold a freeze lock
381            // (it may never redraw, which is fine if it is hidden)
382            mFreezeLock.clear();
383        }
384    }
385
386    return LayerBase::doTransaction(flags);
387}
388
389bool Layer::isFixedSize() const {
390    return mCurrentScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE;
391}
392
393bool Layer::isCropped() const {
394    return !mCurrentCrop.isEmpty();
395}
396
397// ----------------------------------------------------------------------------
398// pageflip handling...
399// ----------------------------------------------------------------------------
400
401void Layer::lockPageFlip(bool& recomputeVisibleRegions)
402{
403    if (mQueuedFrames > 0) {
404        const bool oldOpacity = isOpaque();
405
406        // signal another event if we have more frames pending
407        if (android_atomic_dec(&mQueuedFrames) > 1) {
408            mFlinger->signalEvent();
409        }
410
411        if (mSurfaceTexture->updateTexImage() < NO_ERROR) {
412            // something happened!
413            recomputeVisibleRegions = true;
414            return;
415        }
416
417        mActiveBuffer = mSurfaceTexture->getCurrentBuffer();
418        mSurfaceTexture->getTransformMatrix(mTextureMatrix);
419
420        const Rect crop(mSurfaceTexture->getCurrentCrop());
421        const uint32_t transform(mSurfaceTexture->getCurrentTransform());
422        const uint32_t scalingMode(mSurfaceTexture->getCurrentScalingMode());
423        if ((crop != mCurrentCrop) ||
424            (transform != mCurrentTransform) ||
425            (scalingMode != mCurrentScalingMode))
426        {
427            mCurrentCrop = crop;
428            mCurrentTransform = transform;
429            mCurrentScalingMode = scalingMode;
430            mFlinger->invalidateHwcGeometry();
431        }
432
433        mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
434        if (oldOpacity != isOpaque()) {
435            recomputeVisibleRegions = true;
436        }
437
438        const GLenum target(mSurfaceTexture->getCurrentTextureTarget());
439        glTexParameterx(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
440        glTexParameterx(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
441
442        // update the layer size and release freeze-lock
443        const Layer::State& front(drawingState());
444
445        // FIXME: mPostedDirtyRegion = dirty & bounds
446        mPostedDirtyRegion.set(front.w, front.h);
447
448
449        if ((front.w != front.requested_w) ||
450            (front.h != front.requested_h))
451        {
452            // check that we received a buffer of the right size
453            // (Take the buffer's orientation into account)
454            sp<GraphicBuffer> newFrontBuffer(mActiveBuffer);
455            uint32_t bufWidth  = newFrontBuffer->getWidth();
456            uint32_t bufHeight = newFrontBuffer->getHeight();
457            if (mCurrentTransform & Transform::ROT_90) {
458                swap(bufWidth, bufHeight);
459            }
460
461            if (isFixedSize() ||
462                    (bufWidth == front.requested_w &&
463                    bufHeight == front.requested_h))
464            {
465                // Here we pretend the transaction happened by updating the
466                // current and drawing states. Drawing state is only accessed
467                // in this thread, no need to have it locked
468                Layer::State& editDraw(mDrawingState);
469                editDraw.w = editDraw.requested_w;
470                editDraw.h = editDraw.requested_h;
471
472                // We also need to update the current state so that we don't
473                // end-up doing too much work during the next transaction.
474                // NOTE: We actually don't need hold the transaction lock here
475                // because State::w and State::h are only accessed from
476                // this thread
477                Layer::State& editTemp(currentState());
478                editTemp.w = editDraw.w;
479                editTemp.h = editDraw.h;
480
481                // recompute visible region
482                recomputeVisibleRegions = true;
483
484                // we now have the correct size, unfreeze the screen
485                mFreezeLock.clear();
486            }
487
488            LOGD_IF(DEBUG_RESIZE,
489                    "lockPageFlip : "
490                    "       (layer=%p), buffer (%ux%u, tr=%02x), "
491                    "requested (%dx%d)",
492                    this,
493                    bufWidth, bufHeight, mCurrentTransform,
494                    front.requested_w, front.requested_h);
495        }
496    }
497}
498
499void Layer::unlockPageFlip(
500        const Transform& planeTransform, Region& outDirtyRegion)
501{
502    Region dirtyRegion(mPostedDirtyRegion);
503    if (!dirtyRegion.isEmpty()) {
504        mPostedDirtyRegion.clear();
505        // The dirty region is given in the layer's coordinate space
506        // transform the dirty region by the surface's transformation
507        // and the global transformation.
508        const Layer::State& s(drawingState());
509        const Transform tr(planeTransform * s.transform);
510        dirtyRegion = tr.transform(dirtyRegion);
511
512        // At this point, the dirty region is in screen space.
513        // Make sure it's constrained by the visible region (which
514        // is in screen space as well).
515        dirtyRegion.andSelf(visibleRegionScreen);
516        outDirtyRegion.orSelf(dirtyRegion);
517    }
518    if (visibleRegionScreen.isEmpty()) {
519        // an invisible layer should not hold a freeze-lock
520        // (because it may never be updated and therefore never release it)
521        mFreezeLock.clear();
522    }
523}
524
525void Layer::dump(String8& result, char* buffer, size_t SIZE) const
526{
527    LayerBaseClient::dump(result, buffer, SIZE);
528
529    sp<const GraphicBuffer> buf0(mActiveBuffer);
530    uint32_t w0=0, h0=0, s0=0, f0=0;
531    if (buf0 != 0) {
532        w0 = buf0->getWidth();
533        h0 = buf0->getHeight();
534        s0 = buf0->getStride();
535        f0 = buf0->format;
536    }
537    snprintf(buffer, SIZE,
538            "      "
539            "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
540            " freezeLock=%p, queued-frames=%d\n",
541            mFormat, w0, h0, s0,f0,
542            getFreezeLock().get(), mQueuedFrames);
543
544    result.append(buffer);
545
546    if (mSurfaceTexture != 0) {
547        mSurfaceTexture->dump(result, "            ", buffer, SIZE);
548    }
549}
550
551uint32_t Layer::getEffectiveUsage(uint32_t usage) const
552{
553    // TODO: should we do something special if mSecure is set?
554    if (mProtectedByApp) {
555        // need a hardware-protected path to external video sink
556        usage |= GraphicBuffer::USAGE_PROTECTED;
557    }
558    return usage;
559}
560
561// ---------------------------------------------------------------------------
562
563
564}; // namespace android
565