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