Layer.cpp revision e31564d8eb0ab67e167a888eccce20f5b4e4ef45
10ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong/*
20ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong * Copyright (C) 2007 The Android Open Source Project
30ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong *
40ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong * Licensed under the Apache License, Version 2.0 (the "License");
50ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong * you may not use this file except in compliance with the License.
60ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong * You may obtain a copy of the License at
70ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong *
80ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong *      http://www.apache.org/licenses/LICENSE-2.0
90ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong *
100ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong * Unless required by applicable law or agreed to in writing, software
110ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong * distributed under the License is distributed on an "AS IS" BASIS,
120ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
130ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong * See the License for the specific language governing permissions and
140ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong * limitations under the License.
150ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong */
160ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
170ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#define ATRACE_TAG ATRACE_TAG_GRAPHICS
180ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
190ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include <stdlib.h>
200ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include <stdint.h>
210ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include <sys/types.h>
220ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include <math.h>
230ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
240ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include <cutils/compiler.h>
250ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include <cutils/native_handle.h>
260ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include <cutils/properties.h>
270ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
280ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include <utils/Errors.h>
290ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include <utils/Log.h>
300ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include <utils/StopWatch.h>
310ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include <utils/Trace.h>
320ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
330ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include <ui/GraphicBuffer.h>
340ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include <ui/PixelFormat.h>
350ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
360ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include <gui/Surface.h>
370ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
380ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "clz.h"
390ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "DisplayHardware/DisplayHardware.h"
400ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "DisplayHardware/HWComposer.h"
410ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "GLExtensions.h"
420ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "Layer.h"
430ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "SurfaceFlinger.h"
440ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "SurfaceTextureLayer.h"
450ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
460ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#define DEBUG_RESIZE    0
470ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
480ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kongnamespace android {
490ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
500ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong// ---------------------------------------------------------------------------
510ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
520ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus KongLayer::Layer(SurfaceFlinger* flinger,
530ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        DisplayID display, const sp<Client>& client)
540ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    :   LayerBaseClient(flinger, display, client),
550ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mTextureName(-1U),
560ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mQueuedFrames(0),
570ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mCurrentTransform(0),
580ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
590ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mCurrentOpacity(true),
600ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mRefreshPending(false),
610ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mFrameLatencyNeeded(false),
620ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mFrameLatencyOffset(0),
630ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mFormat(PIXEL_FORMAT_NONE),
640ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mGLExtensions(GLExtensions::getInstance()),
650ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mOpaqueLayer(true),
660ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mNeedsDithering(false),
670ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mSecure(false),
680ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mProtectedByApp(false)
690ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong{
700ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mCurrentCrop.makeInvalid();
710ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    glGenTextures(1, &mTextureName);
720ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong}
730ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
740ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kongvoid Layer::onLayerDisplayed() {
750ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    if (mFrameLatencyNeeded) {
760ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        const DisplayHardware& hw(graphicPlane(0).displayHardware());
770ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mFrameStats[mFrameLatencyOffset].timestamp = mSurfaceTexture->getTimestamp();
780ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mFrameStats[mFrameLatencyOffset].set = systemTime();
790ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mFrameStats[mFrameLatencyOffset].vsync = hw.getRefreshTimestamp();
800ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mFrameLatencyOffset = (mFrameLatencyOffset + 1) % 128;
810ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        mFrameLatencyNeeded = false;
820ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    }
830ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong}
840ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
850ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kongvoid Layer::onFirstRef()
860ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong{
870ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    LayerBaseClient::onFirstRef();
880ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
890ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    struct FrameQueuedListener : public SurfaceTexture::FrameAvailableListener {
900ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        FrameQueuedListener(Layer* layer) : mLayer(layer) { }
910ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    private:
920ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        wp<Layer> mLayer;
930ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        virtual void onFrameAvailable() {
940ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong            sp<Layer> that(mLayer.promote());
950ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong            if (that != 0) {
960ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong                that->onFrameQueued();
970ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong            }
980ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        }
990ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    };
1000ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
1010ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    // Creates a custom BufferQueue for SurfaceTexture to use
1020ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    sp<BufferQueue> bq = new SurfaceTextureLayer();
1030ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mSurfaceTexture = new SurfaceTexture(mTextureName, true,
1040ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong            GL_TEXTURE_EXTERNAL_OES, false, bq);
1050ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
1060ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mSurfaceTexture->setConsumerUsageBits(getEffectiveUsage(0));
1070ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mSurfaceTexture->setFrameAvailableListener(new FrameQueuedListener(this));
1080ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mSurfaceTexture->setSynchronousMode(true);
1090ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
1100ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
1110ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#warning "disabling triple buffering"
1120ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mSurfaceTexture->setBufferCountServer(2);
1130ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#else
1140ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mSurfaceTexture->setBufferCountServer(3);
1150ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#endif
1160ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong}
1170ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
1180ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus KongLayer::~Layer()
1190ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong{
1200ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mFlinger->postMessageAsync(
1210ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong            new SurfaceFlinger::MessageDestroyGLTexture(mTextureName) );
1220ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong}
1230ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
1240ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kongvoid Layer::onFrameQueued() {
1250ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    android_atomic_inc(&mQueuedFrames);
1260ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mFlinger->signalLayerUpdate();
1270ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong}
1280ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
1290ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong// called with SurfaceFlinger::mStateLock as soon as the layer is entered
1300ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong// in the purgatory list
1310ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kongvoid Layer::onRemoved()
1320ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong{
1330ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mSurfaceTexture->abandon();
1340ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong}
1350ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
1360ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kongvoid Layer::setName(const String8& name) {
1370ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    LayerBase::setName(name);
1380ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mSurfaceTexture->setName(name);
1390ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong}
1400ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
1410ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kongvoid Layer::validateVisibility(const Transform& globalTransform) {
1420ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    LayerBase::validateVisibility(globalTransform);
1430ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
1440ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    // This optimization allows the SurfaceTexture to bake in
1450ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    // the rotation so hardware overlays can be used
1460ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mSurfaceTexture->setTransformHint(getTransformHint());
1470ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong}
1480ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
1490ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kongsp<ISurface> Layer::createSurface()
1500ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong{
1510ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    class BSurface : public BnSurface, public LayerCleaner {
1520ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        wp<const Layer> mOwner;
1530ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        virtual sp<ISurfaceTexture> getSurfaceTexture() const {
1540ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong            sp<ISurfaceTexture> res;
1550ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong            sp<const Layer> that( mOwner.promote() );
1560ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong            if (that != NULL) {
1570ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong                res = that->mSurfaceTexture->getBufferQueue();
1580ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong            }
1590ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong            return res;
1600ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        }
1610ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    public:
1620ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        BSurface(const sp<SurfaceFlinger>& flinger,
1631d2624a10e2c559f8ba9ef89eaa30832c0a83a96Sascha Haeberling                const sp<Layer>& layer)
1641d2624a10e2c559f8ba9ef89eaa30832c0a83a96Sascha Haeberling            : LayerCleaner(flinger, layer), mOwner(layer) { }
1651d2624a10e2c559f8ba9ef89eaa30832c0a83a96Sascha Haeberling    };
1661d2624a10e2c559f8ba9ef89eaa30832c0a83a96Sascha Haeberling    sp<ISurface> sur(new BSurface(mFlinger, this));
1671d2624a10e2c559f8ba9ef89eaa30832c0a83a96Sascha Haeberling    return sur;
1681d2624a10e2c559f8ba9ef89eaa30832c0a83a96Sascha Haeberling}
1691d2624a10e2c559f8ba9ef89eaa30832c0a83a96Sascha Haeberling
1701d2624a10e2c559f8ba9ef89eaa30832c0a83a96Sascha Haeberlingwp<IBinder> Layer::getSurfaceTextureBinder() const
1710ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong{
1720ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    return mSurfaceTexture->getBufferQueue()->asBinder();
1730ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong}
1740ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
1750ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kongstatus_t Layer::setBuffers( uint32_t w, uint32_t h,
1760ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong                            PixelFormat format, uint32_t flags)
1770ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong{
1780ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    // this surfaces pixel format
1790ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    PixelFormatInfo info;
1800ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    status_t err = getPixelFormatInfo(format, &info);
1810ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    if (err) {
1820ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        ALOGE("unsupported pixelformat %d", format);
1830ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        return err;
1840ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    }
1850ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
1860ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    // the display's pixel format
1870ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    const DisplayHardware& hw(graphicPlane(0).displayHardware());
1881d2624a10e2c559f8ba9ef89eaa30832c0a83a96Sascha Haeberling    uint32_t const maxSurfaceDims = min(
1891d2624a10e2c559f8ba9ef89eaa30832c0a83a96Sascha Haeberling            hw.getMaxTextureSize(), hw.getMaxViewportDims());
1900ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
1910ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    // never allow a surface larger than what our underlying GL implementation
1920ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    // can handle.
1930ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
1940ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
1950ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong        return BAD_VALUE;
1960ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    }
1970ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
1981d2624a10e2c559f8ba9ef89eaa30832c0a83a96Sascha Haeberling    PixelFormatInfo displayInfo;
1991d2624a10e2c559f8ba9ef89eaa30832c0a83a96Sascha Haeberling    getPixelFormatInfo(hw.getFormat(), &displayInfo);
2001d2624a10e2c559f8ba9ef89eaa30832c0a83a96Sascha Haeberling    const uint32_t hwFlags = hw.getFlags();
2010ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
2020ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mFormat = format;
2030ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
2040ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mSecure = (flags & ISurfaceComposer::eSecure) ? true : false;
2050ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mProtectedByApp = (flags & ISurfaceComposer::eProtectedByApp) ? true : false;
2060ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mOpaqueLayer = (flags & ISurfaceComposer::eOpaque);
2070ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mCurrentOpacity = getOpacityForFormat(format);
2080ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
2090ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mSurfaceTexture->setDefaultBufferSize(w, h);
2100ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mSurfaceTexture->setDefaultBufferFormat(format);
2110ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mSurfaceTexture->setConsumerUsageBits(getEffectiveUsage(0));
2120ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
2130ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    // we use the red index
2140ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    int displayRedSize = displayInfo.getSize(PixelFormatInfo::INDEX_RED);
2150ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    int layerRedsize = info.getSize(PixelFormatInfo::INDEX_RED);
2160ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    mNeedsDithering = layerRedsize > displayRedSize;
2170ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
2180ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    return NO_ERROR;
219}
220
221Rect Layer::computeBufferCrop() const {
222    // Start with the SurfaceTexture's buffer crop...
223    Rect crop;
224    if (!mCurrentCrop.isEmpty()) {
225        crop = mCurrentCrop;
226    } else  if (mActiveBuffer != NULL){
227        crop = Rect(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
228    } else {
229        crop = Rect(mTransformedBounds.width(), mTransformedBounds.height());
230    }
231
232    // ... then reduce that in the same proportions as the window crop reduces
233    // the window size.
234    const State& s(drawingState());
235    if (!s.active.crop.isEmpty()) {
236        // Transform the window crop to match the buffer coordinate system,
237        // which means using the inverse of the current transform set on the
238        // SurfaceTexture.
239        uint32_t invTransform = mCurrentTransform;
240        int winWidth = s.active.w;
241        int winHeight = s.active.h;
242        if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
243            invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
244                    NATIVE_WINDOW_TRANSFORM_FLIP_H;
245            winWidth = s.active.h;
246            winHeight = s.active.w;
247        }
248        Rect winCrop = s.active.crop.transform(invTransform,
249                s.active.w, s.active.h);
250
251        float xScale = float(crop.width()) / float(winWidth);
252        float yScale = float(crop.height()) / float(winHeight);
253        crop.left += int(ceilf(float(winCrop.left) * xScale));
254        crop.top += int(ceilf(float(winCrop.top) * yScale));
255        crop.right -= int(ceilf(float(winWidth - winCrop.right) * xScale));
256        crop.bottom -= int(ceilf(float(winHeight - winCrop.bottom) * yScale));
257    }
258
259    return crop;
260}
261
262void Layer::setGeometry(hwc_layer_t* hwcl)
263{
264    LayerBaseClient::setGeometry(hwcl);
265
266    hwcl->flags &= ~HWC_SKIP_LAYER;
267
268    // we can't do alpha-fade with the hwc HAL
269    const State& s(drawingState());
270    if (s.alpha < 0xFF) {
271        hwcl->flags = HWC_SKIP_LAYER;
272    }
273
274    /*
275     * Transformations are applied in this order:
276     * 1) buffer orientation/flip/mirror
277     * 2) state transformation (window manager)
278     * 3) layer orientation (screen orientation)
279     * mTransform is already the composition of (2) and (3)
280     * (NOTE: the matrices are multiplied in reverse order)
281     */
282
283    const Transform bufferOrientation(mCurrentTransform);
284    const Transform tr(mTransform * bufferOrientation);
285
286    // this gives us only the "orientation" component of the transform
287    const uint32_t finalTransform = tr.getOrientation();
288
289    // we can only handle simple transformation
290    if (finalTransform & Transform::ROT_INVALID) {
291        hwcl->flags = HWC_SKIP_LAYER;
292    } else {
293        hwcl->transform = finalTransform;
294    }
295
296    Rect crop = computeBufferCrop();
297    hwcl->sourceCrop.left   = crop.left;
298    hwcl->sourceCrop.top    = crop.top;
299    hwcl->sourceCrop.right  = crop.right;
300    hwcl->sourceCrop.bottom = crop.bottom;
301}
302
303void Layer::setPerFrameData(hwc_layer_t* hwcl) {
304    const sp<GraphicBuffer>& buffer(mActiveBuffer);
305    if (buffer == NULL) {
306        // this can happen if the client never drew into this layer yet,
307        // or if we ran out of memory. In that case, don't let
308        // HWC handle it.
309        hwcl->flags |= HWC_SKIP_LAYER;
310        hwcl->handle = NULL;
311    } else {
312        hwcl->handle = buffer->handle;
313    }
314}
315
316void Layer::onDraw(const Region& clip) const
317{
318    ATRACE_CALL();
319
320    if (CC_UNLIKELY(mActiveBuffer == 0)) {
321        // the texture has not been created yet, this Layer has
322        // in fact never been drawn into. This happens frequently with
323        // SurfaceView because the WindowManager can't know when the client
324        // has drawn the first time.
325
326        // If there is nothing under us, we paint the screen in black, otherwise
327        // we just skip this update.
328
329        // figure out if there is something below us
330        Region under;
331        const SurfaceFlinger::LayerVector& drawingLayers(
332                mFlinger->mDrawingState.layersSortedByZ);
333        const size_t count = drawingLayers.size();
334        for (size_t i=0 ; i<count ; ++i) {
335            const sp<LayerBase>& layer(drawingLayers[i]);
336            if (layer.get() == static_cast<LayerBase const*>(this))
337                break;
338            under.orSelf(layer->visibleRegionScreen);
339        }
340        // if not everything below us is covered, we plug the holes!
341        Region holes(clip.subtract(under));
342        if (!holes.isEmpty()) {
343            clearWithOpenGL(holes, 0, 0, 0, 1);
344        }
345        return;
346    }
347
348    if (!isProtected()) {
349        // TODO: we could be more subtle with isFixedSize()
350        const bool useFiltering = getFiltering() || needsFiltering() || isFixedSize();
351
352        // Query the texture matrix given our current filtering mode.
353        float textureMatrix[16];
354        mSurfaceTexture->setFilteringEnabled(useFiltering);
355        mSurfaceTexture->getTransformMatrix(textureMatrix);
356
357        // Set things up for texturing.
358        glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureName);
359        GLenum filter = GL_NEAREST;
360        if (useFiltering) {
361            filter = GL_LINEAR;
362        }
363        glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, filter);
364        glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, filter);
365        glMatrixMode(GL_TEXTURE);
366        glLoadMatrixf(textureMatrix);
367        glMatrixMode(GL_MODELVIEW);
368        glDisable(GL_TEXTURE_2D);
369        glEnable(GL_TEXTURE_EXTERNAL_OES);
370    } else {
371        glBindTexture(GL_TEXTURE_2D, mFlinger->getProtectedTexName());
372        glMatrixMode(GL_TEXTURE);
373        glLoadIdentity();
374        glMatrixMode(GL_MODELVIEW);
375        glDisable(GL_TEXTURE_EXTERNAL_OES);
376        glEnable(GL_TEXTURE_2D);
377    }
378
379    drawWithOpenGL(clip);
380
381    glDisable(GL_TEXTURE_EXTERNAL_OES);
382    glDisable(GL_TEXTURE_2D);
383}
384
385// As documented in libhardware header, formats in the range
386// 0x100 - 0x1FF are specific to the HAL implementation, and
387// are known to have no alpha channel
388// TODO: move definition for device-specific range into
389// hardware.h, instead of using hard-coded values here.
390#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
391
392bool Layer::getOpacityForFormat(uint32_t format)
393{
394    if (HARDWARE_IS_DEVICE_FORMAT(format)) {
395        return true;
396    }
397    PixelFormatInfo info;
398    status_t err = getPixelFormatInfo(PixelFormat(format), &info);
399    // in case of error (unknown format), we assume no blending
400    return (err || info.h_alpha <= info.l_alpha);
401}
402
403
404bool Layer::isOpaque() const
405{
406    // if we don't have a buffer yet, we're translucent regardless of the
407    // layer's opaque flag.
408    if (mActiveBuffer == 0) {
409        return false;
410    }
411
412    // if the layer has the opaque flag, then we're always opaque,
413    // otherwise we use the current buffer's format.
414    return mOpaqueLayer || mCurrentOpacity;
415}
416
417bool Layer::isProtected() const
418{
419    const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
420    return (activeBuffer != 0) &&
421            (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
422}
423
424uint32_t Layer::doTransaction(uint32_t flags)
425{
426    ATRACE_CALL();
427
428    const Layer::State& front(drawingState());
429    const Layer::State& temp(currentState());
430
431    const bool sizeChanged = (temp.requested.w != front.active.w) ||
432                             (temp.requested.h != front.active.h);
433
434    if (sizeChanged) {
435        // the size changed, we need to ask our client to request a new buffer
436        ALOGD_IF(DEBUG_RESIZE,
437                "doTransaction: geometry (layer=%p), scalingMode=%d\n"
438                "  current={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
439                "            requested={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }}\n"
440                "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
441                "            requested={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }}\n",
442                this, mCurrentScalingMode,
443                temp.active.w, temp.active.h,
444                temp.active.crop.left,
445                temp.active.crop.top,
446                temp.active.crop.right,
447                temp.active.crop.bottom,
448                temp.active.crop.getWidth(),
449                temp.active.crop.getHeight(),
450                temp.requested.w, temp.requested.h,
451                temp.requested.crop.left,
452                temp.requested.crop.top,
453                temp.requested.crop.right,
454                temp.requested.crop.bottom,
455                temp.requested.crop.getWidth(),
456                temp.requested.crop.getHeight(),
457                front.active.w, front.active.h,
458                front.active.crop.left,
459                front.active.crop.top,
460                front.active.crop.right,
461                front.active.crop.bottom,
462                front.active.crop.getWidth(),
463                front.active.crop.getHeight(),
464                front.requested.w, front.requested.h,
465                front.requested.crop.left,
466                front.requested.crop.top,
467                front.requested.crop.right,
468                front.requested.crop.bottom,
469                front.requested.crop.getWidth(),
470                front.requested.crop.getHeight());
471
472        if (!isFixedSize()) {
473            // this will make sure LayerBase::doTransaction doesn't update
474            // the drawing state's geometry
475            flags |= eDontUpdateGeometryState;
476        }
477
478        // record the new size, form this point on, when the client request
479        // a buffer, it'll get the new size.
480        mSurfaceTexture->setDefaultBufferSize(
481                temp.requested.w, temp.requested.h);
482    }
483
484    return LayerBase::doTransaction(flags);
485}
486
487bool Layer::isFixedSize() const {
488    return mCurrentScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE;
489}
490
491bool Layer::isCropped() const {
492    return !mCurrentCrop.isEmpty();
493}
494
495// ----------------------------------------------------------------------------
496// pageflip handling...
497// ----------------------------------------------------------------------------
498
499bool Layer::onPreComposition() {
500    mRefreshPending = false;
501    return mQueuedFrames > 0;
502}
503
504void Layer::lockPageFlip(bool& recomputeVisibleRegions)
505{
506    ATRACE_CALL();
507
508    if (mQueuedFrames > 0) {
509
510        // if we've already called updateTexImage() without going through
511        // a composition step, we have to skip this layer at this point
512        // because we cannot call updateTeximage() without a corresponding
513        // compositionComplete() call.
514        // we'll trigger an update in onPreComposition().
515        if (mRefreshPending) {
516            mPostedDirtyRegion.clear();
517            return;
518        }
519        mRefreshPending = true;
520
521        // Capture the old state of the layer for comparisons later
522        const bool oldOpacity = isOpaque();
523        sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
524
525        // signal another event if we have more frames pending
526        if (android_atomic_dec(&mQueuedFrames) > 1) {
527            mFlinger->signalLayerUpdate();
528        }
529
530        struct Reject : public SurfaceTexture::BufferRejecter {
531            Layer::State& front;
532            Layer::State& current;
533            bool& recomputeVisibleRegions;
534            Reject(Layer::State& front, Layer::State& current,
535                    bool& recomputeVisibleRegions)
536                : front(front), current(current),
537                  recomputeVisibleRegions(recomputeVisibleRegions) {
538            }
539
540            virtual bool reject(const sp<GraphicBuffer>& buf,
541                    const BufferQueue::BufferItem& item) {
542                if (buf == NULL) {
543                    return false;
544                }
545
546                uint32_t bufWidth  = buf->getWidth();
547                uint32_t bufHeight = buf->getHeight();
548
549                // check that we received a buffer of the right size
550                // (Take the buffer's orientation into account)
551                if (item.mTransform & Transform::ROT_90) {
552                    swap(bufWidth, bufHeight);
553                }
554
555
556                bool isFixedSize = item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE;
557                if (front.active != front.requested) {
558
559                    if (isFixedSize ||
560                            (bufWidth == front.requested.w &&
561                             bufHeight == front.requested.h))
562                    {
563                        // Here we pretend the transaction happened by updating the
564                        // current and drawing states. Drawing state is only accessed
565                        // in this thread, no need to have it locked
566                        front.active = front.requested;
567
568                        // We also need to update the current state so that
569                        // we don't end-up overwriting the drawing state with
570                        // this stale current state during the next transaction
571                        //
572                        // NOTE: We don't need to hold the transaction lock here
573                        // because State::active is only accessed from this thread.
574                        current.active = front.active;
575
576                        // recompute visible region
577                        recomputeVisibleRegions = true;
578                    }
579
580                    ALOGD_IF(DEBUG_RESIZE,
581                            "lockPageFlip: (layer=%p), buffer (%ux%u, tr=%02x), scalingMode=%d\n"
582                            "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
583                            "            requested={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }}\n",
584                            this, bufWidth, bufHeight, item.mTransform, item.mScalingMode,
585                            front.active.w, front.active.h,
586                            front.active.crop.left,
587                            front.active.crop.top,
588                            front.active.crop.right,
589                            front.active.crop.bottom,
590                            front.active.crop.getWidth(),
591                            front.active.crop.getHeight(),
592                            front.requested.w, front.requested.h,
593                            front.requested.crop.left,
594                            front.requested.crop.top,
595                            front.requested.crop.right,
596                            front.requested.crop.bottom,
597                            front.requested.crop.getWidth(),
598                            front.requested.crop.getHeight());
599                }
600
601                if (!isFixedSize) {
602                    if (front.active.w != bufWidth ||
603                        front.active.h != bufHeight) {
604                        return true;
605                    }
606                }
607                return false;
608            }
609        };
610
611
612        Reject r(mDrawingState, currentState(), recomputeVisibleRegions);
613
614        if (mSurfaceTexture->updateTexImage(&r) < NO_ERROR) {
615            // something happened!
616            recomputeVisibleRegions = true;
617            return;
618        }
619
620        // update the active buffer
621        mActiveBuffer = mSurfaceTexture->getCurrentBuffer();
622        if (mActiveBuffer == NULL) {
623            // this can only happen if the very first buffer was rejected.
624            return;
625        }
626
627        mFrameLatencyNeeded = true;
628        if (oldActiveBuffer == NULL) {
629             // the first time we receive a buffer, we need to trigger a
630             // geometry invalidation.
631             mFlinger->invalidateHwcGeometry();
632         }
633
634        Rect crop(mSurfaceTexture->getCurrentCrop());
635        const uint32_t transform(mSurfaceTexture->getCurrentTransform());
636        const uint32_t scalingMode(mSurfaceTexture->getCurrentScalingMode());
637        if ((crop != mCurrentCrop) ||
638            (transform != mCurrentTransform) ||
639            (scalingMode != mCurrentScalingMode))
640        {
641            mCurrentCrop = crop;
642            mCurrentTransform = transform;
643            mCurrentScalingMode = scalingMode;
644            mFlinger->invalidateHwcGeometry();
645        }
646
647        if (oldActiveBuffer != NULL) {
648            uint32_t bufWidth  = mActiveBuffer->getWidth();
649            uint32_t bufHeight = mActiveBuffer->getHeight();
650            if (bufWidth != uint32_t(oldActiveBuffer->width) ||
651                bufHeight != uint32_t(oldActiveBuffer->height)) {
652                mFlinger->invalidateHwcGeometry();
653            }
654        }
655
656        mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
657        if (oldOpacity != isOpaque()) {
658            recomputeVisibleRegions = true;
659        }
660
661        // FIXME: mPostedDirtyRegion = dirty & bounds
662        const Layer::State& front(drawingState());
663        mPostedDirtyRegion.set(front.active.w, front.active.h);
664
665        glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
666        glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
667    }
668}
669
670void Layer::unlockPageFlip(
671        const Transform& planeTransform, Region& outDirtyRegion)
672{
673    ATRACE_CALL();
674
675    Region postedRegion(mPostedDirtyRegion);
676    if (!postedRegion.isEmpty()) {
677        mPostedDirtyRegion.clear();
678        if (!visibleRegionScreen.isEmpty()) {
679            // The dirty region is given in the layer's coordinate space
680            // transform the dirty region by the surface's transformation
681            // and the global transformation.
682            const Layer::State& s(drawingState());
683            const Transform tr(planeTransform * s.transform);
684            postedRegion = tr.transform(postedRegion);
685
686            // At this point, the dirty region is in screen space.
687            // Make sure it's constrained by the visible region (which
688            // is in screen space as well).
689            postedRegion.andSelf(visibleRegionScreen);
690            outDirtyRegion.orSelf(postedRegion);
691        }
692    }
693}
694
695void Layer::dump(String8& result, char* buffer, size_t SIZE) const
696{
697    LayerBaseClient::dump(result, buffer, SIZE);
698
699    sp<const GraphicBuffer> buf0(mActiveBuffer);
700    uint32_t w0=0, h0=0, s0=0, f0=0;
701    if (buf0 != 0) {
702        w0 = buf0->getWidth();
703        h0 = buf0->getHeight();
704        s0 = buf0->getStride();
705        f0 = buf0->format;
706    }
707    snprintf(buffer, SIZE,
708            "      "
709            "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
710            " transform-hint=0x%02x, queued-frames=%d, mRefreshPending=%d\n",
711            mFormat, w0, h0, s0,f0,
712            getTransformHint(), mQueuedFrames, mRefreshPending);
713
714    result.append(buffer);
715
716    if (mSurfaceTexture != 0) {
717        mSurfaceTexture->dump(result, "            ", buffer, SIZE);
718    }
719}
720
721void Layer::dumpStats(String8& result, char* buffer, size_t SIZE) const
722{
723    LayerBaseClient::dumpStats(result, buffer, SIZE);
724    const size_t o = mFrameLatencyOffset;
725    const DisplayHardware& hw(graphicPlane(0).displayHardware());
726    const nsecs_t period = hw.getRefreshPeriod();
727    result.appendFormat("%lld\n", period);
728    for (size_t i=0 ; i<128 ; i++) {
729        const size_t index = (o+i) % 128;
730        const nsecs_t time_app   = mFrameStats[index].timestamp;
731        const nsecs_t time_set   = mFrameStats[index].set;
732        const nsecs_t time_vsync = mFrameStats[index].vsync;
733        result.appendFormat("%lld\t%lld\t%lld\n",
734                time_app,
735                time_vsync,
736                time_set);
737    }
738    result.append("\n");
739}
740
741void Layer::clearStats()
742{
743    LayerBaseClient::clearStats();
744    memset(mFrameStats, 0, sizeof(mFrameStats));
745}
746
747uint32_t Layer::getEffectiveUsage(uint32_t usage) const
748{
749    // TODO: should we do something special if mSecure is set?
750    if (mProtectedByApp) {
751        // need a hardware-protected path to external video sink
752        usage |= GraphicBuffer::USAGE_PROTECTED;
753    }
754    usage |= GraphicBuffer::USAGE_HW_COMPOSER;
755    return usage;
756}
757
758uint32_t Layer::getTransformHint() const {
759    uint32_t orientation = 0;
760    if (!mFlinger->mDebugDisableTransformHint) {
761        orientation = getPlaneOrientation();
762        if (orientation & Transform::ROT_INVALID) {
763            orientation = 0;
764        }
765    }
766    return orientation;
767}
768
769// ---------------------------------------------------------------------------
770
771
772}; // namespace android
773