Layer.cpp revision ddc31c3e2bc6ffe66695c385d23e8ccc3c6dad06
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    if (android_atomic_or(1, &mQueuedFrames) == 0) {
105        mFlinger->signalEvent();
106    }
107}
108
109// called with SurfaceFlinger::mStateLock as soon as the layer is entered
110// in the purgatory list
111void Layer::onRemoved()
112{
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    hwcl->compositionType = HWC_FRAMEBUFFER;
180    hwcl->hints = 0;
181    hwcl->flags = 0;
182    hwcl->transform = 0;
183    hwcl->blending = HWC_BLENDING_NONE;
184
185    // we can't do alpha-fade with the hwc HAL
186    const State& s(drawingState());
187    if (s.alpha < 0xFF) {
188        hwcl->flags = HWC_SKIP_LAYER;
189        return;
190    }
191
192    // we can only handle simple transformation
193    if (mOrientation & Transform::ROT_INVALID) {
194        hwcl->flags = HWC_SKIP_LAYER;
195        return;
196    }
197
198    // FIXME: shouldn't we take the state's transform into account here?
199
200    Transform tr(Transform(mOrientation) * Transform(mCurrentTransform));
201    hwcl->transform = tr.getOrientation();
202
203    if (!isOpaque()) {
204        hwcl->blending = mPremultipliedAlpha ?
205                HWC_BLENDING_PREMULT : HWC_BLENDING_COVERAGE;
206    }
207
208    hwcl->displayFrame.left   = mTransformedBounds.left;
209    hwcl->displayFrame.top    = mTransformedBounds.top;
210    hwcl->displayFrame.right  = mTransformedBounds.right;
211    hwcl->displayFrame.bottom = mTransformedBounds.bottom;
212
213    hwcl->visibleRegionScreen.rects =
214            reinterpret_cast<hwc_rect_t const *>(
215                    visibleRegionScreen.getArray(
216                            &hwcl->visibleRegionScreen.numRects));
217}
218
219void Layer::setPerFrameData(hwc_layer_t* hwcl) {
220    const sp<GraphicBuffer>& buffer(mActiveBuffer);
221    if (buffer == NULL) {
222        // this can happen if the client never drew into this layer yet,
223        // or if we ran out of memory. In that case, don't let
224        // HWC handle it.
225        hwcl->flags |= HWC_SKIP_LAYER;
226        hwcl->handle = NULL;
227        return;
228    }
229    hwcl->handle = buffer->handle;
230
231    if (isCropped()) {
232        hwcl->sourceCrop.left   = mCurrentCrop.left;
233        hwcl->sourceCrop.top    = mCurrentCrop.top;
234        hwcl->sourceCrop.right  = mCurrentCrop.right;
235        hwcl->sourceCrop.bottom = mCurrentCrop.bottom;
236    } else {
237        hwcl->sourceCrop.left   = 0;
238        hwcl->sourceCrop.top    = 0;
239        hwcl->sourceCrop.right  = buffer->width;
240        hwcl->sourceCrop.bottom = buffer->height;
241    }
242}
243
244static inline uint16_t pack565(int r, int g, int b) {
245    return (r<<11)|(g<<5)|b;
246}
247void Layer::onDraw(const Region& clip) const
248{
249    if (CC_UNLIKELY(mActiveBuffer == 0)) {
250        // the texture has not been created yet, this Layer has
251        // in fact never been drawn into. This happens frequently with
252        // SurfaceView because the WindowManager can't know when the client
253        // has drawn the first time.
254
255        // If there is nothing under us, we paint the screen in black, otherwise
256        // we just skip this update.
257
258        // figure out if there is something below us
259        Region under;
260        const SurfaceFlinger::LayerVector& drawingLayers(mFlinger->mDrawingState.layersSortedByZ);
261        const size_t count = drawingLayers.size();
262        for (size_t i=0 ; i<count ; ++i) {
263            const sp<LayerBase>& layer(drawingLayers[i]);
264            if (layer.get() == static_cast<LayerBase const*>(this))
265                break;
266            under.orSelf(layer->visibleRegionScreen);
267        }
268        // if not everything below us is covered, we plug the holes!
269        Region holes(clip.subtract(under));
270        if (!holes.isEmpty()) {
271            clearWithOpenGL(holes, 0, 0, 0, 1);
272        }
273        return;
274    }
275
276    GLenum target = mSurfaceTexture->getCurrentTextureTarget();
277    glBindTexture(target, mTextureName);
278    if (getFiltering() || needsFiltering() || isFixedSize() || isCropped()) {
279        // TODO: we could be more subtle with isFixedSize()
280        glTexParameterx(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
281        glTexParameterx(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
282    } else {
283        glTexParameterx(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
284        glTexParameterx(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
285    }
286    glEnable(target);
287    glMatrixMode(GL_TEXTURE);
288    glLoadMatrixf(mTextureMatrix);
289    glMatrixMode(GL_MODELVIEW);
290
291    drawWithOpenGL(clip);
292
293    glDisable(target);
294}
295
296// As documented in libhardware header, formats in the range
297// 0x100 - 0x1FF are specific to the HAL implementation, and
298// are known to have no alpha channel
299// TODO: move definition for device-specific range into
300// hardware.h, instead of using hard-coded values here.
301#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
302
303bool Layer::getOpacityForFormat(uint32_t format)
304{
305    if (HARDWARE_IS_DEVICE_FORMAT(format)) {
306        return true;
307    }
308    PixelFormatInfo info;
309    status_t err = getPixelFormatInfo(PixelFormat(format), &info);
310    // in case of error (unknown format), we assume no blending
311    return (err || info.h_alpha <= info.l_alpha);
312}
313
314
315bool Layer::isOpaque() const
316{
317    // if we don't have a buffer yet, we're translucent regardless of the
318    // layer's opaque flag.
319    if (mActiveBuffer == 0)
320        return false;
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                "resize (layer=%p), requested (%dx%d), drawing (%d,%d), "
346                "fixedSize=%d",
347                this,
348                int(temp.requested_w), int(temp.requested_h),
349                int(front.requested_w), int(front.requested_h),
350                isFixedSize());
351
352        if (!isFixedSize()) {
353            // we're being resized and there is a freeze display request,
354            // acquire a freeze lock, so that the screen stays put
355            // until we've redrawn at the new size; this is to avoid
356            // glitches upon orientation changes.
357            if (mFlinger->hasFreezeRequest()) {
358                // if the surface is hidden, don't try to acquire the
359                // freeze lock, since hidden surfaces may never redraw
360                if (!(front.flags & ISurfaceComposer::eLayerHidden)) {
361                    mFreezeLock = mFlinger->getFreezeLock();
362                }
363            }
364
365            // this will make sure LayerBase::doTransaction doesn't update
366            // the drawing state's size
367            Layer::State& editDraw(mDrawingState);
368            editDraw.requested_w = temp.requested_w;
369            editDraw.requested_h = temp.requested_h;
370
371            // record the new size, form this point on, when the client request
372            // a buffer, it'll get the new size.
373            mSurfaceTexture->setDefaultBufferSize(temp.requested_w, temp.requested_h);
374        }
375    }
376
377    if (temp.sequence != front.sequence) {
378        if (temp.flags & ISurfaceComposer::eLayerHidden || temp.alpha == 0) {
379            // this surface is now hidden, so it shouldn't hold a freeze lock
380            // (it may never redraw, which is fine if it is hidden)
381            mFreezeLock.clear();
382        }
383    }
384
385    return LayerBase::doTransaction(flags);
386}
387
388bool Layer::isFixedSize() const {
389    Mutex::Autolock _l(mLock);
390    return mFixedSize;
391}
392
393void Layer::setFixedSize(bool fixedSize)
394{
395    Mutex::Autolock _l(mLock);
396    mFixedSize = fixedSize;
397}
398
399bool Layer::isCropped() const {
400    return !mCurrentCrop.isEmpty();
401}
402
403// ----------------------------------------------------------------------------
404// pageflip handling...
405// ----------------------------------------------------------------------------
406
407void Layer::lockPageFlip(bool& recomputeVisibleRegions)
408{
409    if (android_atomic_and(0, &mQueuedFrames)) {
410        if (mSurfaceTexture->updateTexImage() < NO_ERROR) {
411            // something happened!
412            recomputeVisibleRegions = true;
413            return;
414        }
415
416        // signal another event if we have more frames waiting
417        if (mSurfaceTexture->getQueuedCount()) {
418            if (android_atomic_or(1, &mQueuedFrames) == 0) {
419                mFlinger->signalEvent();
420            }
421        }
422
423        mActiveBuffer = mSurfaceTexture->getCurrentBuffer();
424        mSurfaceTexture->getTransformMatrix(mTextureMatrix);
425
426        const Rect crop(mSurfaceTexture->getCurrentCrop());
427        const uint32_t transform(mSurfaceTexture->getCurrentTransform());
428        if ((crop != mCurrentCrop) || (transform != mCurrentTransform)) {
429            mCurrentCrop = crop;
430            mCurrentTransform = transform;
431            mFlinger->invalidateHwcGeometry();
432        }
433
434        const bool opacity(getOpacityForFormat(mActiveBuffer->format));
435        if (opacity != mCurrentOpacity) {
436            mCurrentOpacity = opacity;
437            recomputeVisibleRegions = true;
438        }
439
440        const GLenum target(mSurfaceTexture->getCurrentTextureTarget());
441        glTexParameterx(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
442        glTexParameterx(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
443
444        // update the layer size and release freeze-lock
445        const Layer::State& front(drawingState());
446
447        // FIXME: mPostedDirtyRegion = dirty & bounds
448        mPostedDirtyRegion.set(front.w, front.h);
449
450        sp<GraphicBuffer> newFrontBuffer(mActiveBuffer);
451        if ((newFrontBuffer->getWidth()  == front.requested_w &&
452            newFrontBuffer->getHeight() == front.requested_h) ||
453            isFixedSize())
454        {
455            if ((front.w != front.requested_w) ||
456                (front.h != front.requested_h))
457            {
458                // Here we pretend the transaction happened by updating the
459                // current and drawing states. Drawing state is only accessed
460                // in this thread, no need to have it locked
461                Layer::State& editDraw(mDrawingState);
462                editDraw.w = editDraw.requested_w;
463                editDraw.h = editDraw.requested_h;
464
465                // We also need to update the current state so that we don't
466                // end-up doing too much work during the next transaction.
467                // NOTE: We actually don't need hold the transaction lock here
468                // because State::w and State::h are only accessed from
469                // this thread
470                Layer::State& editTemp(currentState());
471                editTemp.w = editDraw.w;
472                editTemp.h = editDraw.h;
473
474                // recompute visible region
475                recomputeVisibleRegions = true;
476            }
477
478            // we now have the correct size, unfreeze the screen
479            mFreezeLock.clear();
480        }
481    }
482}
483
484void Layer::unlockPageFlip(
485        const Transform& planeTransform, Region& outDirtyRegion)
486{
487    Region dirtyRegion(mPostedDirtyRegion);
488    if (!dirtyRegion.isEmpty()) {
489        mPostedDirtyRegion.clear();
490        // The dirty region is given in the layer's coordinate space
491        // transform the dirty region by the surface's transformation
492        // and the global transformation.
493        const Layer::State& s(drawingState());
494        const Transform tr(planeTransform * s.transform);
495        dirtyRegion = tr.transform(dirtyRegion);
496
497        // At this point, the dirty region is in screen space.
498        // Make sure it's constrained by the visible region (which
499        // is in screen space as well).
500        dirtyRegion.andSelf(visibleRegionScreen);
501        outDirtyRegion.orSelf(dirtyRegion);
502    }
503    if (visibleRegionScreen.isEmpty()) {
504        // an invisible layer should not hold a freeze-lock
505        // (because it may never be updated and therefore never release it)
506        mFreezeLock.clear();
507    }
508}
509
510void Layer::dump(String8& result, char* buffer, size_t SIZE) const
511{
512    LayerBaseClient::dump(result, buffer, SIZE);
513
514    sp<const GraphicBuffer> buf0(mActiveBuffer);
515    uint32_t w0=0, h0=0, s0=0, f0=0;
516    if (buf0 != 0) {
517        w0 = buf0->getWidth();
518        h0 = buf0->getHeight();
519        s0 = buf0->getStride();
520        f0 = buf0->format;
521    }
522    snprintf(buffer, SIZE,
523            "      "
524            "format=%2d, activeBuffer=[%3ux%3u:%3u,%3u],"
525            " freezeLock=%p, queued-frames=%d\n",
526            mFormat, w0, h0, s0,f0,
527            getFreezeLock().get(), mQueuedFrames);
528
529    result.append(buffer);
530
531    if (mSurfaceTexture != 0) {
532        mSurfaceTexture->dump(result, "            ", buffer, SIZE);
533    }
534}
535
536uint32_t Layer::getEffectiveUsage(uint32_t usage) const
537{
538    // TODO: should we do something special if mSecure is set?
539    if (mProtectedByApp) {
540        // need a hardware-protected path to external video sink
541        usage |= GraphicBuffer::USAGE_PROTECTED;
542    }
543    return usage;
544}
545
546// ---------------------------------------------------------------------------
547
548
549}; // namespace android
550