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