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