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