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