Layer.cpp revision 3d8063b02e06020c8062addcc9ec49048d3bdb9a
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
47template <typename T> inline T min(T a, T b) {
48    return a<b ? a : b;
49}
50
51// ---------------------------------------------------------------------------
52
53Layer::Layer(SurfaceFlinger* flinger,
54        DisplayID display, const sp<Client>& client)
55    :   LayerBaseClient(flinger, display, client),
56        mTextureName(-1U),
57        mQueuedFrames(0),
58        mCurrentTransform(0),
59        mCurrentOpacity(true),
60        mFormat(PIXEL_FORMAT_NONE),
61        mGLExtensions(GLExtensions::getInstance()),
62        mOpaqueLayer(true),
63        mNeedsDithering(false),
64        mSecure(false),
65        mProtectedByApp(false),
66        mFixedSize(false)
67{
68    mCurrentCrop.makeInvalid();
69    glGenTextures(1, &mTextureName);
70}
71
72void Layer::destroy(RefBase const* base) {
73    mFlinger->destroyLayer(static_cast<LayerBase const*>(base));
74}
75
76void Layer::onFirstRef()
77{
78    LayerBaseClient::onFirstRef();
79    setDestroyer(this);
80
81    struct FrameQueuedListener : public SurfaceTexture::FrameAvailableListener {
82        FrameQueuedListener(Layer* layer) : mLayer(layer) { }
83    private:
84        wp<Layer> mLayer;
85        virtual void onFrameAvailable() {
86            sp<Layer> that(mLayer.promote());
87            if (that != 0) {
88                that->onFrameQueued();
89            }
90        }
91    };
92    mSurfaceTexture = new SurfaceTextureLayer(mTextureName, this);
93    mSurfaceTexture->setFrameAvailableListener(new FrameQueuedListener(this));
94    mSurfaceTexture->setSynchronousMode(true);
95    mSurfaceTexture->setBufferCountServer(2);
96}
97
98Layer::~Layer()
99{
100    glDeleteTextures(1, &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}
113
114sp<ISurface> Layer::createSurface()
115{
116    class BSurface : public BnSurface, public LayerCleaner {
117        wp<const Layer> mOwner;
118        virtual sp<ISurfaceTexture> getSurfaceTexture() const {
119            sp<ISurfaceTexture> res;
120            sp<const Layer> that( mOwner.promote() );
121            if (that != NULL) {
122                res = that->mSurfaceTexture;
123            }
124            return res;
125        }
126    public:
127        BSurface(const sp<SurfaceFlinger>& flinger,
128                const sp<Layer>& layer)
129            : LayerCleaner(flinger, layer), mOwner(layer) { }
130    };
131    sp<ISurface> sur(new BSurface(mFlinger, this));
132    return sur;
133}
134
135status_t Layer::setBuffers( uint32_t w, uint32_t h,
136                            PixelFormat format, uint32_t flags)
137{
138    // this surfaces pixel format
139    PixelFormatInfo info;
140    status_t err = getPixelFormatInfo(format, &info);
141    if (err) return err;
142
143    // the display's pixel format
144    const DisplayHardware& hw(graphicPlane(0).displayHardware());
145    uint32_t const maxSurfaceDims = min(
146            hw.getMaxTextureSize(), hw.getMaxViewportDims());
147
148    // never allow a surface larger than what our underlying GL implementation
149    // can handle.
150    if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
151        return BAD_VALUE;
152    }
153
154    PixelFormatInfo displayInfo;
155    getPixelFormatInfo(hw.getFormat(), &displayInfo);
156    const uint32_t hwFlags = hw.getFlags();
157
158    mFormat = format;
159
160    mSecure = (flags & ISurfaceComposer::eSecure) ? true : false;
161    mProtectedByApp = (flags & ISurfaceComposer::eProtectedByApp) ? true : false;
162    mOpaqueLayer = (flags & ISurfaceComposer::eOpaque);
163    mCurrentOpacity = getOpacityForFormat(format);
164
165    mSurfaceTexture->setDefaultBufferSize(w, h);
166    mSurfaceTexture->setDefaultBufferFormat(format);
167
168    // we use the red index
169    int displayRedSize = displayInfo.getSize(PixelFormatInfo::INDEX_RED);
170    int layerRedsize = info.getSize(PixelFormatInfo::INDEX_RED);
171    mNeedsDithering = layerRedsize > displayRedSize;
172
173    return NO_ERROR;
174}
175
176void Layer::setGeometry(hwc_layer_t* hwcl)
177{
178    hwcl->compositionType = HWC_FRAMEBUFFER;
179    hwcl->hints = 0;
180    hwcl->flags = 0;
181    hwcl->transform = 0;
182    hwcl->blending = HWC_BLENDING_NONE;
183
184    // we can't do alpha-fade with the hwc HAL
185    const State& s(drawingState());
186    if (s.alpha < 0xFF) {
187        hwcl->flags = HWC_SKIP_LAYER;
188        return;
189    }
190
191    // we can only handle simple transformation
192    if (mOrientation & Transform::ROT_INVALID) {
193        hwcl->flags = HWC_SKIP_LAYER;
194        return;
195    }
196
197    // FIXME: shouldn't we take the state's transform into account here?
198
199    Transform tr(Transform(mOrientation) * Transform(mCurrentTransform));
200    hwcl->transform = tr.getOrientation();
201
202    if (!isOpaque()) {
203        hwcl->blending = mPremultipliedAlpha ?
204                HWC_BLENDING_PREMULT : HWC_BLENDING_COVERAGE;
205    }
206
207    hwcl->displayFrame.left   = mTransformedBounds.left;
208    hwcl->displayFrame.top    = mTransformedBounds.top;
209    hwcl->displayFrame.right  = mTransformedBounds.right;
210    hwcl->displayFrame.bottom = mTransformedBounds.bottom;
211
212    hwcl->visibleRegionScreen.rects =
213            reinterpret_cast<hwc_rect_t const *>(
214                    visibleRegionScreen.getArray(
215                            &hwcl->visibleRegionScreen.numRects));
216}
217
218void Layer::setPerFrameData(hwc_layer_t* hwcl) {
219    const sp<GraphicBuffer>& buffer(mActiveBuffer);
220    if (buffer == NULL) {
221        // this can happen if the client never drew into this layer yet,
222        // or if we ran out of memory. In that case, don't let
223        // HWC handle it.
224        hwcl->flags |= HWC_SKIP_LAYER;
225        hwcl->handle = NULL;
226        return;
227    }
228    hwcl->handle = buffer->handle;
229
230    if (isCropped()) {
231        hwcl->sourceCrop.left   = mCurrentCrop.left;
232        hwcl->sourceCrop.top    = mCurrentCrop.top;
233        hwcl->sourceCrop.right  = mCurrentCrop.right;
234        hwcl->sourceCrop.bottom = mCurrentCrop.bottom;
235    } else {
236        hwcl->sourceCrop.left   = 0;
237        hwcl->sourceCrop.top    = 0;
238        hwcl->sourceCrop.right  = buffer->width;
239        hwcl->sourceCrop.bottom = buffer->height;
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    // if the layer has the opaque flag, then we're always opaque,
322    // otherwise we use the current buffer's format.
323    return mOpaqueLayer || mCurrentOpacity;
324}
325
326bool Layer::isProtected() const
327{
328    const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
329    return (activeBuffer != 0) &&
330            (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
331}
332
333uint32_t Layer::doTransaction(uint32_t flags)
334{
335    const Layer::State& front(drawingState());
336    const Layer::State& temp(currentState());
337
338    const bool sizeChanged = (front.requested_w != temp.requested_w) ||
339            (front.requested_h != temp.requested_h);
340
341    if (sizeChanged) {
342        // the size changed, we need to ask our client to request a new buffer
343        LOGD_IF(DEBUG_RESIZE,
344                "resize (layer=%p), requested (%dx%d), drawing (%d,%d), "
345                "fixedSize=%d",
346                this,
347                int(temp.requested_w), int(temp.requested_h),
348                int(front.requested_w), int(front.requested_h),
349                isFixedSize());
350
351        if (!isFixedSize()) {
352            // we're being resized and there is a freeze display request,
353            // acquire a freeze lock, so that the screen stays put
354            // until we've redrawn at the new size; this is to avoid
355            // glitches upon orientation changes.
356            if (mFlinger->hasFreezeRequest()) {
357                // if the surface is hidden, don't try to acquire the
358                // freeze lock, since hidden surfaces may never redraw
359                if (!(front.flags & ISurfaceComposer::eLayerHidden)) {
360                    mFreezeLock = mFlinger->getFreezeLock();
361                }
362            }
363
364            // this will make sure LayerBase::doTransaction doesn't update
365            // the drawing state's size
366            Layer::State& editDraw(mDrawingState);
367            editDraw.requested_w = temp.requested_w;
368            editDraw.requested_h = temp.requested_h;
369
370            // record the new size, form this point on, when the client request
371            // a buffer, it'll get the new size.
372            mSurfaceTexture->setDefaultBufferSize(temp.requested_w, temp.requested_h);
373        }
374    }
375
376    if (temp.sequence != front.sequence) {
377        if (temp.flags & ISurfaceComposer::eLayerHidden || temp.alpha == 0) {
378            // this surface is now hidden, so it shouldn't hold a freeze lock
379            // (it may never redraw, which is fine if it is hidden)
380            mFreezeLock.clear();
381        }
382    }
383
384    return LayerBase::doTransaction(flags);
385}
386
387bool Layer::isFixedSize() const {
388    Mutex::Autolock _l(mLock);
389    return mFixedSize;
390}
391
392void Layer::setFixedSize(bool fixedSize)
393{
394    Mutex::Autolock _l(mLock);
395    mFixedSize = fixedSize;
396}
397
398bool Layer::isCropped() const {
399    return !mCurrentCrop.isEmpty();
400}
401
402// ----------------------------------------------------------------------------
403// pageflip handling...
404// ----------------------------------------------------------------------------
405
406void Layer::lockPageFlip(bool& recomputeVisibleRegions)
407{
408    if (mQueuedFrames > 0) {
409        // signal another event if we have more frames pending
410        if (android_atomic_dec(&mQueuedFrames) > 1) {
411            mFlinger->signalEvent();
412        }
413
414        if (mSurfaceTexture->updateTexImage() < NO_ERROR) {
415            // something happened!
416            recomputeVisibleRegions = true;
417            return;
418        }
419
420        mActiveBuffer = mSurfaceTexture->getCurrentBuffer();
421        mSurfaceTexture->getTransformMatrix(mTextureMatrix);
422
423        const Rect crop(mSurfaceTexture->getCurrentCrop());
424        const uint32_t transform(mSurfaceTexture->getCurrentTransform());
425        if ((crop != mCurrentCrop) || (transform != mCurrentTransform)) {
426            mCurrentCrop = crop;
427            mCurrentTransform = transform;
428            mFlinger->invalidateHwcGeometry();
429        }
430
431        const bool opacity(getOpacityForFormat(mActiveBuffer->format));
432        if (opacity != mCurrentOpacity) {
433            mCurrentOpacity = opacity;
434            recomputeVisibleRegions = true;
435        }
436
437        const GLenum target(mSurfaceTexture->getCurrentTextureTarget());
438        glTexParameterx(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
439        glTexParameterx(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
440
441        // update the layer size and release freeze-lock
442        const Layer::State& front(drawingState());
443
444        // FIXME: mPostedDirtyRegion = dirty & bounds
445        mPostedDirtyRegion.set(front.w, front.h);
446
447        sp<GraphicBuffer> newFrontBuffer(mActiveBuffer);
448        if ((newFrontBuffer->getWidth()  == front.requested_w &&
449            newFrontBuffer->getHeight() == front.requested_h) ||
450            isFixedSize())
451        {
452            if ((front.w != front.requested_w) ||
453                (front.h != front.requested_h))
454            {
455                // Here we pretend the transaction happened by updating the
456                // current and drawing states. Drawing state is only accessed
457                // in this thread, no need to have it locked
458                Layer::State& editDraw(mDrawingState);
459                editDraw.w = editDraw.requested_w;
460                editDraw.h = editDraw.requested_h;
461
462                // We also need to update the current state so that we don't
463                // end-up doing too much work during the next transaction.
464                // NOTE: We actually don't need hold the transaction lock here
465                // because State::w and State::h are only accessed from
466                // this thread
467                Layer::State& editTemp(currentState());
468                editTemp.w = editDraw.w;
469                editTemp.h = editDraw.h;
470
471                // recompute visible region
472                recomputeVisibleRegions = true;
473            }
474
475            // we now have the correct size, unfreeze the screen
476            mFreezeLock.clear();
477        }
478    }
479}
480
481void Layer::unlockPageFlip(
482        const Transform& planeTransform, Region& outDirtyRegion)
483{
484    Region dirtyRegion(mPostedDirtyRegion);
485    if (!dirtyRegion.isEmpty()) {
486        mPostedDirtyRegion.clear();
487        // The dirty region is given in the layer's coordinate space
488        // transform the dirty region by the surface's transformation
489        // and the global transformation.
490        const Layer::State& s(drawingState());
491        const Transform tr(planeTransform * s.transform);
492        dirtyRegion = tr.transform(dirtyRegion);
493
494        // At this point, the dirty region is in screen space.
495        // Make sure it's constrained by the visible region (which
496        // is in screen space as well).
497        dirtyRegion.andSelf(visibleRegionScreen);
498        outDirtyRegion.orSelf(dirtyRegion);
499    }
500    if (visibleRegionScreen.isEmpty()) {
501        // an invisible layer should not hold a freeze-lock
502        // (because it may never be updated and therefore never release it)
503        mFreezeLock.clear();
504    }
505}
506
507void Layer::dump(String8& result, char* buffer, size_t SIZE) const
508{
509    LayerBaseClient::dump(result, buffer, SIZE);
510
511    sp<const GraphicBuffer> buf0(mActiveBuffer);
512    uint32_t w0=0, h0=0, s0=0, f0=0;
513    if (buf0 != 0) {
514        w0 = buf0->getWidth();
515        h0 = buf0->getHeight();
516        s0 = buf0->getStride();
517        f0 = buf0->format;
518    }
519    snprintf(buffer, SIZE,
520            "      "
521            "format=%2d, activeBuffer=[%3ux%3u:%3u,%3u],"
522            " freezeLock=%p, queued-frames=%d\n",
523            mFormat, w0, h0, s0,f0,
524            getFreezeLock().get(), mQueuedFrames);
525
526    result.append(buffer);
527
528    if (mSurfaceTexture != 0) {
529        mSurfaceTexture->dump(result, "            ", buffer, SIZE);
530    }
531}
532
533uint32_t Layer::getEffectiveUsage(uint32_t usage) const
534{
535    // TODO: should we do something special if mSecure is set?
536    if (mProtectedByApp) {
537        // need a hardware-protected path to external video sink
538        usage |= GraphicBuffer::USAGE_PROTECTED;
539    }
540    return usage;
541}
542
543// ---------------------------------------------------------------------------
544
545
546}; // namespace android
547