SurfaceFlinger.cpp revision bae92d0d605e99a14731add4f11b72413b2835e5
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#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
19#include <stdint.h>
20#include <sys/types.h>
21#include <errno.h>
22#include <math.h>
23#include <dlfcn.h>
24
25#include <EGL/egl.h>
26#include <GLES/gl.h>
27
28#include <cutils/log.h>
29#include <cutils/properties.h>
30
31#include <binder/IPCThreadState.h>
32#include <binder/IServiceManager.h>
33#include <binder/MemoryHeapBase.h>
34#include <binder/PermissionCache.h>
35
36#include <ui/DisplayInfo.h>
37
38#include <gui/BitTube.h>
39#include <gui/BufferQueue.h>
40#include <gui/GuiConfig.h>
41#include <gui/IDisplayEventConnection.h>
42#include <gui/SurfaceTextureClient.h>
43
44#include <ui/GraphicBufferAllocator.h>
45#include <ui/PixelFormat.h>
46#include <ui/UiConfig.h>
47
48#include <utils/misc.h>
49#include <utils/String8.h>
50#include <utils/String16.h>
51#include <utils/StopWatch.h>
52#include <utils/Trace.h>
53
54#include <private/android_filesystem_config.h>
55
56#include "clz.h"
57#include "DdmConnection.h"
58#include "DisplayDevice.h"
59#include "Client.h"
60#include "EventThread.h"
61#include "GLExtensions.h"
62#include "Layer.h"
63#include "LayerDim.h"
64#include "LayerScreenshot.h"
65#include "SurfaceFlinger.h"
66
67#include "DisplayHardware/FramebufferSurface.h"
68#include "DisplayHardware/GraphicBufferAlloc.h"
69#include "DisplayHardware/HWComposer.h"
70
71
72#define EGL_VERSION_HW_ANDROID  0x3143
73
74#define DISPLAY_COUNT       1
75
76namespace android {
77// ---------------------------------------------------------------------------
78
79const String16 sHardwareTest("android.permission.HARDWARE_TEST");
80const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
81const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
82const String16 sDump("android.permission.DUMP");
83
84// ---------------------------------------------------------------------------
85
86SurfaceFlinger::SurfaceFlinger()
87    :   BnSurfaceComposer(), Thread(false),
88        mTransactionFlags(0),
89        mTransationPending(false),
90        mLayersRemoved(false),
91        mRepaintEverything(0),
92        mBootTime(systemTime()),
93        mVisibleRegionsDirty(false),
94        mHwWorkListDirty(false),
95        mDebugRegion(0),
96        mDebugDDMS(0),
97        mDebugDisableHWC(0),
98        mDebugDisableTransformHint(0),
99        mDebugInSwapBuffers(0),
100        mLastSwapBufferTime(0),
101        mDebugInTransaction(0),
102        mLastTransactionTime(0),
103        mBootFinished(false)
104{
105    ALOGI("SurfaceFlinger is starting");
106
107    // debugging stuff...
108    char value[PROPERTY_VALUE_MAX];
109
110    property_get("debug.sf.showupdates", value, "0");
111    mDebugRegion = atoi(value);
112
113    property_get("debug.sf.ddms", value, "0");
114    mDebugDDMS = atoi(value);
115    if (mDebugDDMS) {
116        if (!startDdmConnection()) {
117            // start failed, and DDMS debugging not enabled
118            mDebugDDMS = 0;
119        }
120    }
121    ALOGI_IF(mDebugRegion, "showupdates enabled");
122    ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
123}
124
125void SurfaceFlinger::onFirstRef()
126{
127    mEventQueue.init(this);
128
129    run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
130
131    // Wait for the main thread to be done with its initialization
132    mReadyToRunBarrier.wait();
133}
134
135
136SurfaceFlinger::~SurfaceFlinger()
137{
138    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
139    eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
140    eglTerminate(display);
141}
142
143void SurfaceFlinger::binderDied(const wp<IBinder>& who)
144{
145    // the window manager died on us. prepare its eulogy.
146
147    // restore initial conditions (default device unblank, etc)
148    initializeDisplays();
149
150    // restart the boot-animation
151    startBootAnim();
152}
153
154sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
155{
156    sp<ISurfaceComposerClient> bclient;
157    sp<Client> client(new Client(this));
158    status_t err = client->initCheck();
159    if (err == NO_ERROR) {
160        bclient = client;
161    }
162    return bclient;
163}
164
165sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName)
166{
167    class DisplayToken : public BBinder {
168        sp<SurfaceFlinger> flinger;
169        virtual ~DisplayToken() {
170             // no more references, this display must be terminated
171             Mutex::Autolock _l(flinger->mStateLock);
172             flinger->mCurrentState.displays.removeItem(this);
173             flinger->setTransactionFlags(eDisplayTransactionNeeded);
174         }
175     public:
176        DisplayToken(const sp<SurfaceFlinger>& flinger)
177            : flinger(flinger) {
178        }
179    };
180
181    sp<BBinder> token = new DisplayToken(this);
182
183    Mutex::Autolock _l(mStateLock);
184    DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
185    info.displayName = displayName;
186    mCurrentState.displays.add(token, info);
187
188    return token;
189}
190
191sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
192    if (uint32_t(id) >= DisplayDevice::NUM_DISPLAY_TYPES) {
193        ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
194        return NULL;
195    }
196    return mDefaultDisplays[id];
197}
198
199sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
200{
201    sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
202    return gba;
203}
204
205void SurfaceFlinger::bootFinished()
206{
207    const nsecs_t now = systemTime();
208    const nsecs_t duration = now - mBootTime;
209    ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
210    mBootFinished = true;
211
212    // wait patiently for the window manager death
213    const String16 name("window");
214    sp<IBinder> window(defaultServiceManager()->getService(name));
215    if (window != 0) {
216        window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
217    }
218
219    // stop boot animation
220    // formerly we would just kill the process, but we now ask it to exit so it
221    // can choose where to stop the animation.
222    property_set("service.bootanim.exit", "1");
223}
224
225void SurfaceFlinger::deleteTextureAsync(GLuint texture) {
226    class MessageDestroyGLTexture : public MessageBase {
227        GLuint texture;
228    public:
229        MessageDestroyGLTexture(GLuint texture)
230            : texture(texture) {
231        }
232        virtual bool handler() {
233            glDeleteTextures(1, &texture);
234            return true;
235        }
236    };
237    postMessageAsync(new MessageDestroyGLTexture(texture));
238}
239
240status_t SurfaceFlinger::selectConfigForAttribute(
241        EGLDisplay dpy,
242        EGLint const* attrs,
243        EGLint attribute, EGLint wanted,
244        EGLConfig* outConfig)
245{
246    EGLConfig config = NULL;
247    EGLint numConfigs = -1, n=0;
248    eglGetConfigs(dpy, NULL, 0, &numConfigs);
249    EGLConfig* const configs = new EGLConfig[numConfigs];
250    eglChooseConfig(dpy, attrs, configs, numConfigs, &n);
251
252    if (n) {
253        if (attribute != EGL_NONE) {
254            for (int i=0 ; i<n ; i++) {
255                EGLint value = 0;
256                eglGetConfigAttrib(dpy, configs[i], attribute, &value);
257                if (wanted == value) {
258                    *outConfig = configs[i];
259                    delete [] configs;
260                    return NO_ERROR;
261                }
262            }
263        } else {
264            // just pick the first one
265            *outConfig = configs[0];
266            delete [] configs;
267            return NO_ERROR;
268        }
269    }
270    delete [] configs;
271    return NAME_NOT_FOUND;
272}
273
274class EGLAttributeVector {
275    struct Attribute;
276    class Adder;
277    friend class Adder;
278    KeyedVector<Attribute, EGLint> mList;
279    struct Attribute {
280        Attribute() {};
281        Attribute(EGLint v) : v(v) { }
282        EGLint v;
283        bool operator < (const Attribute& other) const {
284            // this places EGL_NONE at the end
285            EGLint lhs(v);
286            EGLint rhs(other.v);
287            if (lhs == EGL_NONE) lhs = 0x7FFFFFFF;
288            if (rhs == EGL_NONE) rhs = 0x7FFFFFFF;
289            return lhs < rhs;
290        }
291    };
292    class Adder {
293        friend class EGLAttributeVector;
294        EGLAttributeVector& v;
295        EGLint attribute;
296        Adder(EGLAttributeVector& v, EGLint attribute)
297            : v(v), attribute(attribute) {
298        }
299    public:
300        void operator = (EGLint value) {
301            if (attribute != EGL_NONE) {
302                v.mList.add(attribute, value);
303            }
304        }
305        operator EGLint () const { return v.mList[attribute]; }
306    };
307public:
308    EGLAttributeVector() {
309        mList.add(EGL_NONE, EGL_NONE);
310    }
311    void remove(EGLint attribute) {
312        if (attribute != EGL_NONE) {
313            mList.removeItem(attribute);
314        }
315    }
316    Adder operator [] (EGLint attribute) {
317        return Adder(*this, attribute);
318    }
319    EGLint operator [] (EGLint attribute) const {
320       return mList[attribute];
321    }
322    // cast-operator to (EGLint const*)
323    operator EGLint const* () const { return &mList.keyAt(0).v; }
324};
325
326EGLConfig SurfaceFlinger::selectEGLConfig(EGLDisplay display, EGLint nativeVisualId) {
327    // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
328    // it is to be used with WIFI displays
329    EGLConfig config;
330    EGLint dummy;
331    status_t err;
332
333    EGLAttributeVector attribs;
334    attribs[EGL_SURFACE_TYPE]               = EGL_WINDOW_BIT;
335    attribs[EGL_RECORDABLE_ANDROID]         = EGL_TRUE;
336    attribs[EGL_FRAMEBUFFER_TARGET_ANDROID] = EGL_TRUE;
337    attribs[EGL_RED_SIZE]                   = 8;
338    attribs[EGL_GREEN_SIZE]                 = 8;
339    attribs[EGL_BLUE_SIZE]                  = 8;
340
341    err = selectConfigForAttribute(display, attribs, EGL_NONE, EGL_NONE, &config);
342    if (!err)
343        goto success;
344
345    // maybe we failed because of EGL_FRAMEBUFFER_TARGET_ANDROID
346    ALOGW("no suitable EGLConfig found, trying without EGL_FRAMEBUFFER_TARGET_ANDROID");
347    attribs.remove(EGL_FRAMEBUFFER_TARGET_ANDROID);
348    err = selectConfigForAttribute(display, attribs,
349            EGL_NATIVE_VISUAL_ID, nativeVisualId, &config);
350    if (!err)
351        goto success;
352
353    // maybe we failed because of EGL_RECORDABLE_ANDROID
354    ALOGW("no suitable EGLConfig found, trying without EGL_RECORDABLE_ANDROID");
355    attribs.remove(EGL_RECORDABLE_ANDROID);
356    err = selectConfigForAttribute(display, attribs,
357            EGL_NATIVE_VISUAL_ID, nativeVisualId, &config);
358    if (!err)
359        goto success;
360
361    // allow less than 24-bit color; the non-gpu-accelerated emulator only
362    // supports 16-bit color
363    ALOGW("no suitable EGLConfig found, trying with 16-bit color allowed");
364    attribs.remove(EGL_RED_SIZE);
365    attribs.remove(EGL_GREEN_SIZE);
366    attribs.remove(EGL_BLUE_SIZE);
367    err = selectConfigForAttribute(display, attribs,
368            EGL_NATIVE_VISUAL_ID, nativeVisualId, &config);
369    if (!err)
370        goto success;
371
372    // this EGL is too lame for Android
373    ALOGE("no suitable EGLConfig found, giving up");
374
375    return 0;
376
377success:
378    if (eglGetConfigAttrib(display, config, EGL_CONFIG_CAVEAT, &dummy))
379        ALOGW_IF(dummy == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
380    return config;
381}
382
383EGLContext SurfaceFlinger::createGLContext(EGLDisplay display, EGLConfig config) {
384    // Also create our EGLContext
385    EGLint contextAttributes[] = {
386#ifdef EGL_IMG_context_priority
387#ifdef HAS_CONTEXT_PRIORITY
388#warning "using EGL_IMG_context_priority"
389            EGL_CONTEXT_PRIORITY_LEVEL_IMG, EGL_CONTEXT_PRIORITY_HIGH_IMG,
390#endif
391#endif
392            EGL_NONE, EGL_NONE
393    };
394    EGLContext ctxt = eglCreateContext(display, config, NULL, contextAttributes);
395    ALOGE_IF(ctxt==EGL_NO_CONTEXT, "EGLContext creation failed");
396    return ctxt;
397}
398
399void SurfaceFlinger::initializeGL(EGLDisplay display) {
400    GLExtensions& extensions(GLExtensions::getInstance());
401    extensions.initWithGLStrings(
402            glGetString(GL_VENDOR),
403            glGetString(GL_RENDERER),
404            glGetString(GL_VERSION),
405            glGetString(GL_EXTENSIONS),
406            eglQueryString(display, EGL_VENDOR),
407            eglQueryString(display, EGL_VERSION),
408            eglQueryString(display, EGL_EXTENSIONS));
409
410    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
411    glGetIntegerv(GL_MAX_VIEWPORT_DIMS, mMaxViewportDims);
412
413    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
414    glPixelStorei(GL_PACK_ALIGNMENT, 4);
415    glEnableClientState(GL_VERTEX_ARRAY);
416    glShadeModel(GL_FLAT);
417    glDisable(GL_DITHER);
418    glDisable(GL_CULL_FACE);
419
420    struct pack565 {
421        inline uint16_t operator() (int r, int g, int b) const {
422            return (r<<11)|(g<<5)|b;
423        }
424    } pack565;
425
426    const uint16_t protTexData[] = { pack565(0x03, 0x03, 0x03) };
427    glGenTextures(1, &mProtectedTexName);
428    glBindTexture(GL_TEXTURE_2D, mProtectedTexName);
429    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
430    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
431    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
432    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
433    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0,
434            GL_RGB, GL_UNSIGNED_SHORT_5_6_5, protTexData);
435
436    // print some debugging info
437    EGLint r,g,b,a;
438    eglGetConfigAttrib(display, mEGLConfig, EGL_RED_SIZE,   &r);
439    eglGetConfigAttrib(display, mEGLConfig, EGL_GREEN_SIZE, &g);
440    eglGetConfigAttrib(display, mEGLConfig, EGL_BLUE_SIZE,  &b);
441    eglGetConfigAttrib(display, mEGLConfig, EGL_ALPHA_SIZE, &a);
442    ALOGI("EGL informations:");
443    ALOGI("vendor    : %s", extensions.getEglVendor());
444    ALOGI("version   : %s", extensions.getEglVersion());
445    ALOGI("extensions: %s", extensions.getEglExtension());
446    ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS)?:"Not Supported");
447    ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, mEGLConfig);
448    ALOGI("OpenGL ES informations:");
449    ALOGI("vendor    : %s", extensions.getVendor());
450    ALOGI("renderer  : %s", extensions.getRenderer());
451    ALOGI("version   : %s", extensions.getVersion());
452    ALOGI("extensions: %s", extensions.getExtension());
453    ALOGI("GL_MAX_TEXTURE_SIZE = %d", mMaxTextureSize);
454    ALOGI("GL_MAX_VIEWPORT_DIMS = %d x %d", mMaxViewportDims[0], mMaxViewportDims[1]);
455}
456
457status_t SurfaceFlinger::readyToRun()
458{
459    ALOGI(  "SurfaceFlinger's main thread ready to run. "
460            "Initializing graphics H/W...");
461
462    // initialize EGL for the default display
463    mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
464    eglInitialize(mEGLDisplay, NULL, NULL);
465
466    // Initialize the H/W composer object.  There may or may not be an
467    // actual hardware composer underneath.
468    mHwc = new HWComposer(this,
469            *static_cast<HWComposer::EventHandler *>(this));
470
471    // initialize the config and context
472    EGLint format = mHwc->getVisualID();
473    mEGLConfig  = selectEGLConfig(mEGLDisplay, format);
474    mEGLContext = createGLContext(mEGLDisplay, mEGLConfig);
475
476    LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
477            "couldn't create EGLContext");
478
479    // initialize our non-virtual displays
480    for (size_t i=0 ; i<DisplayDevice::NUM_DISPLAY_TYPES ; i++) {
481        DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
482        mDefaultDisplays[i] = new BBinder();
483        wp<IBinder> token = mDefaultDisplays[i];
484
485        // set-up the displays that are already connected
486        if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
487            mCurrentState.displays.add(token, DisplayDeviceState(type));
488            sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i);
489            sp<SurfaceTextureClient> stc = new SurfaceTextureClient(
490                        static_cast< sp<ISurfaceTexture> >(fbs->getBufferQueue()));
491            sp<DisplayDevice> hw = new DisplayDevice(this,
492                    type, token, stc, fbs, mEGLConfig);
493            if (i > DisplayDevice::DISPLAY_PRIMARY) {
494                // FIXME: currently we don't get blank/unblank requests
495                // for displays other than the main display, so we always
496                // assume a connected display is unblanked.
497                ALOGD("marking display %d as acquired/unblanked", i);
498                hw->acquireScreen();
499            }
500            mDisplays.add(token, hw);
501        }
502    }
503
504    //  we need a GL context current in a few places, when initializing
505    //  OpenGL ES (see below), or creating a layer,
506    //  or when a texture is (asynchronously) destroyed, and for that
507    //  we need a valid surface, so it's convenient to use the main display
508    //  for that.
509    sp<const DisplayDevice> hw = getDefaultDisplayDevice();
510
511    //  initialize OpenGL ES
512    DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext);
513    initializeGL(mEGLDisplay);
514
515    // start the EventThread
516    mEventThread = new EventThread(this);
517    mEventQueue.setEventThread(mEventThread);
518
519    // initialize our drawing state
520    mDrawingState = mCurrentState;
521
522
523    // We're now ready to accept clients...
524    mReadyToRunBarrier.open();
525
526    // set initial conditions (e.g. unblank default device)
527    initializeDisplays();
528
529    // start boot animation
530    startBootAnim();
531
532    return NO_ERROR;
533}
534
535int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
536    return (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) ?
537            type : mHwc->allocateDisplayId();
538}
539
540void SurfaceFlinger::startBootAnim() {
541    // start boot animation
542    property_set("service.bootanim.exit", "0");
543    property_set("ctl.start", "bootanim");
544}
545
546uint32_t SurfaceFlinger::getMaxTextureSize() const {
547    return mMaxTextureSize;
548}
549
550uint32_t SurfaceFlinger::getMaxViewportDims() const {
551    return mMaxViewportDims[0] < mMaxViewportDims[1] ?
552            mMaxViewportDims[0] : mMaxViewportDims[1];
553}
554
555// ----------------------------------------------------------------------------
556
557bool SurfaceFlinger::authenticateSurfaceTexture(
558        const sp<ISurfaceTexture>& surfaceTexture) const {
559    Mutex::Autolock _l(mStateLock);
560    sp<IBinder> surfaceTextureBinder(surfaceTexture->asBinder());
561
562    // Check the visible layer list for the ISurface
563    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
564    size_t count = currentLayers.size();
565    for (size_t i=0 ; i<count ; i++) {
566        const sp<LayerBase>& layer(currentLayers[i]);
567        sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
568        if (lbc != NULL) {
569            wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
570            if (lbcBinder == surfaceTextureBinder) {
571                return true;
572            }
573        }
574    }
575
576    // Check the layers in the purgatory.  This check is here so that if a
577    // SurfaceTexture gets destroyed before all the clients are done using it,
578    // the error will not be reported as "surface XYZ is not authenticated", but
579    // will instead fail later on when the client tries to use the surface,
580    // which should be reported as "surface XYZ returned an -ENODEV".  The
581    // purgatorized layers are no less authentic than the visible ones, so this
582    // should not cause any harm.
583    size_t purgatorySize =  mLayerPurgatory.size();
584    for (size_t i=0 ; i<purgatorySize ; i++) {
585        const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
586        sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
587        if (lbc != NULL) {
588            wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
589            if (lbcBinder == surfaceTextureBinder) {
590                return true;
591            }
592        }
593    }
594
595    return false;
596}
597
598status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info) {
599    int32_t type = BAD_VALUE;
600    for (int i=0 ; i<DisplayDevice::NUM_DISPLAY_TYPES ; i++) {
601        if (display == mDefaultDisplays[i]) {
602            type = i;
603            break;
604        }
605    }
606
607    if (type < 0) {
608        return type;
609    }
610
611    const HWComposer& hwc(getHwComposer());
612    if (!hwc.isConnected(type)) {
613        return NAME_NOT_FOUND;
614    }
615
616    float xdpi = hwc.getDpiX(type);
617    float ydpi = hwc.getDpiY(type);
618
619    // TODO: Not sure if display density should handled by SF any longer
620    class Density {
621        static int getDensityFromProperty(char const* propName) {
622            char property[PROPERTY_VALUE_MAX];
623            int density = 0;
624            if (property_get(propName, property, NULL) > 0) {
625                density = atoi(property);
626            }
627            return density;
628        }
629    public:
630        static int getEmuDensity() {
631            return getDensityFromProperty("qemu.sf.lcd_density"); }
632        static int getBuildDensity()  {
633            return getDensityFromProperty("ro.sf.lcd_density"); }
634    };
635
636    if (type == DisplayDevice::DISPLAY_PRIMARY) {
637        // The density of the device is provided by a build property
638        float density = Density::getBuildDensity() / 160.0f;
639        if (density == 0) {
640            // the build doesn't provide a density -- this is wrong!
641            // use xdpi instead
642            ALOGE("ro.sf.lcd_density must be defined as a build property");
643            density = xdpi / 160.0f;
644        }
645        if (Density::getEmuDensity()) {
646            // if "qemu.sf.lcd_density" is specified, it overrides everything
647            xdpi = ydpi = density = Density::getEmuDensity();
648            density /= 160.0f;
649        }
650        info->density = density;
651
652        // TODO: this needs to go away (currently needed only by webkit)
653        sp<const DisplayDevice> hw(getDefaultDisplayDevice());
654        info->orientation = hw->getOrientation();
655        getPixelFormatInfo(hw->getFormat(), &info->pixelFormatInfo);
656    } else {
657        // TODO: where should this value come from?
658        static const int TV_DENSITY = 213;
659        info->density = TV_DENSITY / 160.0f;
660        info->orientation = 0;
661    }
662
663    info->w = hwc.getWidth(type);
664    info->h = hwc.getHeight(type);
665    info->xdpi = xdpi;
666    info->ydpi = ydpi;
667    info->fps = float(1e9 / hwc.getRefreshPeriod(type));
668    return NO_ERROR;
669}
670
671// ----------------------------------------------------------------------------
672
673sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
674    return mEventThread->createEventConnection();
675}
676
677void SurfaceFlinger::connectDisplay(const sp<ISurfaceTexture>& surface) {
678
679    sp<IBinder> token;
680    { // scope for the lock
681        Mutex::Autolock _l(mStateLock);
682        token = mExtDisplayToken;
683    }
684
685    if (token == 0) {
686        token = createDisplay(String8("Display from connectDisplay"));
687    }
688
689    { // scope for the lock
690        Mutex::Autolock _l(mStateLock);
691        if (surface == 0) {
692            // release our current display. we're guarantee to have
693            // a reference to it (token), while we hold the lock
694            mExtDisplayToken = 0;
695        } else {
696            mExtDisplayToken = token;
697        }
698
699        DisplayDeviceState& info(mCurrentState.displays.editValueFor(token));
700        info.surface = surface;
701        setTransactionFlags(eDisplayTransactionNeeded);
702    }
703}
704
705// ----------------------------------------------------------------------------
706
707void SurfaceFlinger::waitForEvent() {
708    mEventQueue.waitMessage();
709}
710
711void SurfaceFlinger::signalTransaction() {
712    mEventQueue.invalidate();
713}
714
715void SurfaceFlinger::signalLayerUpdate() {
716    mEventQueue.invalidate();
717}
718
719void SurfaceFlinger::signalRefresh() {
720    mEventQueue.refresh();
721}
722
723status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
724        nsecs_t reltime, uint32_t flags) {
725    return mEventQueue.postMessage(msg, reltime);
726}
727
728status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
729        nsecs_t reltime, uint32_t flags) {
730    status_t res = mEventQueue.postMessage(msg, reltime);
731    if (res == NO_ERROR) {
732        msg->wait();
733    }
734    return res;
735}
736
737bool SurfaceFlinger::threadLoop() {
738    waitForEvent();
739    return true;
740}
741
742void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
743    if (mEventThread == NULL) {
744        // This is a temporary workaround for b/7145521.  A non-null pointer
745        // does not mean EventThread has finished initializing, so this
746        // is not a correct fix.
747        ALOGW("WARNING: EventThread not started, ignoring vsync");
748        return;
749    }
750    if (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) {
751        // we should only receive DisplayDevice::DisplayType from the vsync callback
752        mEventThread->onVSyncReceived(type, timestamp);
753    }
754}
755
756void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
757    if (mEventThread == NULL) {
758        // This is a temporary workaround for b/7145521.  A non-null pointer
759        // does not mean EventThread has finished initializing, so this
760        // is not a correct fix.
761        ALOGW("WARNING: EventThread not started, ignoring hotplug");
762        return;
763    }
764
765    if (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) {
766        Mutex::Autolock _l(mStateLock);
767        if (connected == false) {
768            mCurrentState.displays.removeItem(mDefaultDisplays[type]);
769        } else {
770            DisplayDeviceState info((DisplayDevice::DisplayType)type);
771            mCurrentState.displays.add(mDefaultDisplays[type], info);
772        }
773        setTransactionFlags(eDisplayTransactionNeeded);
774
775        // we should only receive DisplayDevice::DisplayType from the vsync callback
776        mEventThread->onHotplugReceived(type, connected);
777    }
778}
779
780void SurfaceFlinger::eventControl(int event, int enabled) {
781    getHwComposer().eventControl(event, enabled);
782}
783
784void SurfaceFlinger::onMessageReceived(int32_t what) {
785    ATRACE_CALL();
786    switch (what) {
787    case MessageQueue::INVALIDATE:
788        handleMessageTransaction();
789        handleMessageInvalidate();
790        signalRefresh();
791        break;
792    case MessageQueue::REFRESH:
793        handleMessageRefresh();
794        break;
795    }
796}
797
798void SurfaceFlinger::handleMessageTransaction() {
799    uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
800    if (transactionFlags) {
801        handleTransaction(transactionFlags);
802    }
803}
804
805void SurfaceFlinger::handleMessageInvalidate() {
806    ATRACE_CALL();
807    handlePageFlip();
808}
809
810void SurfaceFlinger::handleMessageRefresh() {
811    ATRACE_CALL();
812    preComposition();
813    rebuildLayerStacks();
814    setUpHWComposer();
815    doDebugFlashRegions();
816    doComposition();
817    postComposition();
818}
819
820void SurfaceFlinger::doDebugFlashRegions()
821{
822    // is debugging enabled
823    if (CC_LIKELY(!mDebugRegion))
824        return;
825
826    const bool repaintEverything = mRepaintEverything;
827    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
828        const sp<DisplayDevice>& hw(mDisplays[dpy]);
829        if (hw->canDraw()) {
830            // transform the dirty region into this screen's coordinate space
831            const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
832            if (!dirtyRegion.isEmpty()) {
833                // redraw the whole screen
834                doComposeSurfaces(hw, Region(hw->bounds()));
835
836                // and draw the dirty region
837                glDisable(GL_TEXTURE_EXTERNAL_OES);
838                glDisable(GL_TEXTURE_2D);
839                glDisable(GL_BLEND);
840                glColor4f(1, 0, 1, 1);
841                const int32_t height = hw->getHeight();
842                Region::const_iterator it = dirtyRegion.begin();
843                Region::const_iterator const end = dirtyRegion.end();
844                while (it != end) {
845                    const Rect& r = *it++;
846                    GLfloat vertices[][2] = {
847                            { r.left,  height - r.top },
848                            { r.left,  height - r.bottom },
849                            { r.right, height - r.bottom },
850                            { r.right, height - r.top }
851                    };
852                    glVertexPointer(2, GL_FLOAT, 0, vertices);
853                    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
854                }
855                hw->compositionComplete();
856                hw->swapBuffers(getHwComposer());
857            }
858        }
859    }
860
861    postFramebuffer();
862
863    if (mDebugRegion > 1) {
864        usleep(mDebugRegion * 1000);
865    }
866
867    HWComposer& hwc(getHwComposer());
868    if (hwc.initCheck() == NO_ERROR) {
869        status_t err = hwc.prepare();
870        ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
871    }
872}
873
874void SurfaceFlinger::preComposition()
875{
876    bool needExtraInvalidate = false;
877    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
878    const size_t count = currentLayers.size();
879    for (size_t i=0 ; i<count ; i++) {
880        if (currentLayers[i]->onPreComposition()) {
881            needExtraInvalidate = true;
882        }
883    }
884    if (needExtraInvalidate) {
885        signalLayerUpdate();
886    }
887}
888
889void SurfaceFlinger::postComposition()
890{
891    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
892    const size_t count = currentLayers.size();
893    for (size_t i=0 ; i<count ; i++) {
894        currentLayers[i]->onPostComposition();
895    }
896}
897
898void SurfaceFlinger::rebuildLayerStacks() {
899    // rebuild the visible layer list per screen
900    if (CC_UNLIKELY(mVisibleRegionsDirty)) {
901        ATRACE_CALL();
902        mVisibleRegionsDirty = false;
903        invalidateHwcGeometry();
904
905        const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
906        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
907            Region opaqueRegion;
908            Region dirtyRegion;
909            Vector< sp<LayerBase> > layersSortedByZ;
910            const sp<DisplayDevice>& hw(mDisplays[dpy]);
911            const Transform& tr(hw->getTransform());
912            const Rect bounds(hw->getBounds());
913            if (hw->canDraw()) {
914                SurfaceFlinger::computeVisibleRegions(currentLayers,
915                        hw->getLayerStack(), dirtyRegion, opaqueRegion);
916
917                const size_t count = currentLayers.size();
918                for (size_t i=0 ; i<count ; i++) {
919                    const sp<LayerBase>& layer(currentLayers[i]);
920                    const Layer::State& s(layer->drawingState());
921                    if (s.layerStack == hw->getLayerStack()) {
922                        Region drawRegion(tr.transform(
923                                layer->visibleNonTransparentRegion));
924                        drawRegion.andSelf(bounds);
925                        if (!drawRegion.isEmpty()) {
926                            layersSortedByZ.add(layer);
927                        }
928                    }
929                }
930            }
931            hw->setVisibleLayersSortedByZ(layersSortedByZ);
932            hw->undefinedRegion.set(bounds);
933            hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
934            hw->dirtyRegion.orSelf(dirtyRegion);
935        }
936    }
937}
938
939void SurfaceFlinger::setUpHWComposer() {
940    HWComposer& hwc(getHwComposer());
941    if (hwc.initCheck() == NO_ERROR) {
942        // build the h/w work list
943        if (CC_UNLIKELY(mHwWorkListDirty)) {
944            mHwWorkListDirty = false;
945            for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
946                sp<const DisplayDevice> hw(mDisplays[dpy]);
947                const int32_t id = hw->getHwcDisplayId();
948                if (id >= 0) {
949                    const Vector< sp<LayerBase> >& currentLayers(
950                        hw->getVisibleLayersSortedByZ());
951                    const size_t count = currentLayers.size();
952                    if (hwc.createWorkList(id, count) == NO_ERROR) {
953                        HWComposer::LayerListIterator cur = hwc.begin(id);
954                        const HWComposer::LayerListIterator end = hwc.end(id);
955                        for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
956                            const sp<LayerBase>& layer(currentLayers[i]);
957                            layer->setGeometry(hw, *cur);
958                            if (mDebugDisableHWC || mDebugRegion) {
959                                cur->setSkip(true);
960                            }
961                        }
962                    }
963                }
964            }
965        }
966
967        // set the per-frame data
968        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
969            sp<const DisplayDevice> hw(mDisplays[dpy]);
970            const int32_t id = hw->getHwcDisplayId();
971            if (id >= 0) {
972                const Vector< sp<LayerBase> >& currentLayers(
973                    hw->getVisibleLayersSortedByZ());
974                const size_t count = currentLayers.size();
975                HWComposer::LayerListIterator cur = hwc.begin(id);
976                const HWComposer::LayerListIterator end = hwc.end(id);
977                for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
978                    /*
979                     * update the per-frame h/w composer data for each layer
980                     * and build the transparent region of the FB
981                     */
982                    const sp<LayerBase>& layer(currentLayers[i]);
983                    layer->setPerFrameData(hw, *cur);
984                }
985            }
986        }
987
988        status_t err = hwc.prepare();
989        ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
990    }
991}
992
993void SurfaceFlinger::doComposition() {
994    ATRACE_CALL();
995    const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
996    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
997        const sp<DisplayDevice>& hw(mDisplays[dpy]);
998        if (hw->canDraw()) {
999            // transform the dirty region into this screen's coordinate space
1000            const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1001            if (!dirtyRegion.isEmpty()) {
1002                // repaint the framebuffer (if needed)
1003                doDisplayComposition(hw, dirtyRegion);
1004            }
1005            hw->dirtyRegion.clear();
1006            hw->flip(hw->swapRegion);
1007            hw->swapRegion.clear();
1008        }
1009        // inform the h/w that we're done compositing
1010        hw->compositionComplete();
1011    }
1012    postFramebuffer();
1013}
1014
1015void SurfaceFlinger::postFramebuffer()
1016{
1017    ATRACE_CALL();
1018
1019    const nsecs_t now = systemTime();
1020    mDebugInSwapBuffers = now;
1021
1022    HWComposer& hwc(getHwComposer());
1023    if (hwc.initCheck() == NO_ERROR) {
1024        if (!hwc.supportsFramebufferTarget()) {
1025            // EGL spec says:
1026            //   "surface must be bound to the calling thread's current context,
1027            //    for the current rendering API."
1028            DisplayDevice::makeCurrent(mEGLDisplay,
1029                    getDefaultDisplayDevice(), mEGLContext);
1030        }
1031        hwc.commit();
1032    }
1033
1034    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1035        sp<const DisplayDevice> hw(mDisplays[dpy]);
1036        const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ());
1037        hw->onSwapBuffersCompleted(hwc);
1038        const size_t count = currentLayers.size();
1039        int32_t id = hw->getHwcDisplayId();
1040        if (id >=0 && hwc.initCheck() == NO_ERROR) {
1041            HWComposer::LayerListIterator cur = hwc.begin(id);
1042            const HWComposer::LayerListIterator end = hwc.end(id);
1043            for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1044                currentLayers[i]->onLayerDisplayed(hw, &*cur);
1045            }
1046        } else {
1047            for (size_t i = 0; i < count; i++) {
1048                currentLayers[i]->onLayerDisplayed(hw, NULL);
1049            }
1050        }
1051    }
1052
1053    mLastSwapBufferTime = systemTime() - now;
1054    mDebugInSwapBuffers = 0;
1055}
1056
1057void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1058{
1059    ATRACE_CALL();
1060
1061    Mutex::Autolock _l(mStateLock);
1062    const nsecs_t now = systemTime();
1063    mDebugInTransaction = now;
1064
1065    // Here we're guaranteed that some transaction flags are set
1066    // so we can call handleTransactionLocked() unconditionally.
1067    // We call getTransactionFlags(), which will also clear the flags,
1068    // with mStateLock held to guarantee that mCurrentState won't change
1069    // until the transaction is committed.
1070
1071    transactionFlags = getTransactionFlags(eTransactionMask);
1072    handleTransactionLocked(transactionFlags);
1073
1074    mLastTransactionTime = systemTime() - now;
1075    mDebugInTransaction = 0;
1076    invalidateHwcGeometry();
1077    // here the transaction has been committed
1078}
1079
1080void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1081{
1082    const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1083    const size_t count = currentLayers.size();
1084
1085    /*
1086     * Traversal of the children
1087     * (perform the transaction for each of them if needed)
1088     */
1089
1090    if (transactionFlags & eTraversalNeeded) {
1091        for (size_t i=0 ; i<count ; i++) {
1092            const sp<LayerBase>& layer = currentLayers[i];
1093            uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1094            if (!trFlags) continue;
1095
1096            const uint32_t flags = layer->doTransaction(0);
1097            if (flags & Layer::eVisibleRegion)
1098                mVisibleRegionsDirty = true;
1099        }
1100    }
1101
1102    /*
1103     * Perform display own transactions if needed
1104     */
1105
1106    if (transactionFlags & eDisplayTransactionNeeded) {
1107        // here we take advantage of Vector's copy-on-write semantics to
1108        // improve performance by skipping the transaction entirely when
1109        // know that the lists are identical
1110        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1111        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1112        if (!curr.isIdenticalTo(draw)) {
1113            mVisibleRegionsDirty = true;
1114            const size_t cc = curr.size();
1115                  size_t dc = draw.size();
1116
1117            // find the displays that were removed
1118            // (ie: in drawing state but not in current state)
1119            // also handle displays that changed
1120            // (ie: displays that are in both lists)
1121            for (size_t i=0 ; i<dc ; i++) {
1122                const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1123                if (j < 0) {
1124                    // in drawing state but not in current state
1125                    if (!draw[i].isMainDisplay()) {
1126                        mDisplays.removeItem(draw.keyAt(i));
1127                    } else {
1128                        ALOGW("trying to remove the main display");
1129                    }
1130                } else {
1131                    // this display is in both lists. see if something changed.
1132                    const DisplayDeviceState& state(curr[j]);
1133                    const wp<IBinder>& display(curr.keyAt(j));
1134                    if (state.surface->asBinder() != draw[i].surface->asBinder()) {
1135                        // changing the surface is like destroying and
1136                        // recreating the DisplayDevice, so we just remove it
1137                        // from the drawing state, so that it get re-added
1138                        // below.
1139                        mDisplays.removeItem(display);
1140                        mDrawingState.displays.removeItemsAt(i);
1141                        dc--; i--;
1142                        // at this point we must loop to the next item
1143                        continue;
1144                    }
1145
1146                    const sp<DisplayDevice>& disp(getDisplayDevice(display));
1147                    if (disp != NULL) {
1148                        if (state.layerStack != draw[i].layerStack) {
1149                            disp->setLayerStack(state.layerStack);
1150                        }
1151                        if ((state.orientation != draw[i].orientation)
1152                                || (state.viewport != draw[i].viewport)
1153                                || (state.frame != draw[i].frame))
1154                        {
1155                            disp->setProjection(state.orientation,
1156                                    state.viewport, state.frame);
1157                        }
1158
1159                        // Walk through all the layers in currentLayers,
1160                        // and update their transform hint.
1161                        //
1162                        // TODO: we could be much more clever about which
1163                        // layers we touch and how often we do these updates
1164                        // (e.g. only touch the layers associated with this
1165                        // display, and only on a rotation).
1166                        for (size_t i = 0; i < count; i++) {
1167                            const sp<LayerBase>& layerBase = currentLayers[i];
1168                            layerBase->updateTransformHint();
1169                        }
1170                    }
1171                }
1172            }
1173
1174            // find displays that were added
1175            // (ie: in current state but not in drawing state)
1176            for (size_t i=0 ; i<cc ; i++) {
1177                if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1178                    const DisplayDeviceState& state(curr[i]);
1179
1180                    sp<FramebufferSurface> fbs;
1181                    sp<SurfaceTextureClient> stc;
1182                    if (!state.isVirtualDisplay()) {
1183
1184                        ALOGE_IF(state.surface!=NULL,
1185                                "adding a supported display, but rendering "
1186                                "surface is provided (%p), ignoring it",
1187                                state.surface.get());
1188
1189                        // for supported (by hwc) displays we provide our
1190                        // own rendering surface
1191                        fbs = new FramebufferSurface(*mHwc, state.type);
1192                        stc = new SurfaceTextureClient(
1193                                static_cast< sp<ISurfaceTexture> >(fbs->getBufferQueue()));
1194                    } else {
1195                        if (state.surface != NULL) {
1196                            stc = new SurfaceTextureClient(state.surface);
1197                        }
1198                    }
1199
1200                    const wp<IBinder>& display(curr.keyAt(i));
1201                    if (stc != NULL) {
1202                        sp<DisplayDevice> hw = new DisplayDevice(this,
1203                                state.type, display, stc, fbs, mEGLConfig);
1204                        hw->setLayerStack(state.layerStack);
1205                        hw->setProjection(state.orientation,
1206                                state.viewport, state.frame);
1207                        hw->setDisplayName(state.displayName);
1208                        mDisplays.add(display, hw);
1209                        if (hw->getDisplayType() < DisplayDevice::NUM_DISPLAY_TYPES) {
1210                            // notify the system that this display is now up
1211                            // (note onScreenAcquired() is safe to call from
1212                            // here because we're in the main thread)
1213                            onScreenAcquired(hw);
1214                        }
1215                    }
1216                }
1217            }
1218        }
1219    }
1220
1221    /*
1222     * Perform our own transaction if needed
1223     */
1224
1225    const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
1226    if (currentLayers.size() > previousLayers.size()) {
1227        // layers have been added
1228        mVisibleRegionsDirty = true;
1229    }
1230
1231    // some layers might have been removed, so
1232    // we need to update the regions they're exposing.
1233    if (mLayersRemoved) {
1234        mLayersRemoved = false;
1235        mVisibleRegionsDirty = true;
1236        const size_t count = previousLayers.size();
1237        for (size_t i=0 ; i<count ; i++) {
1238            const sp<LayerBase>& layer(previousLayers[i]);
1239            if (currentLayers.indexOf(layer) < 0) {
1240                // this layer is not visible anymore
1241                // TODO: we could traverse the tree from front to back and
1242                //       compute the actual visible region
1243                // TODO: we could cache the transformed region
1244                const Layer::State& s(layer->drawingState());
1245                Region visibleReg = s.transform.transform(
1246                        Region(Rect(s.active.w, s.active.h)));
1247                invalidateLayerStack(s.layerStack, visibleReg);
1248            }
1249        }
1250    }
1251
1252    commitTransaction();
1253}
1254
1255void SurfaceFlinger::commitTransaction()
1256{
1257    if (!mLayersPendingRemoval.isEmpty()) {
1258        // Notify removed layers now that they can't be drawn from
1259        for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1260            mLayersPendingRemoval[i]->onRemoved();
1261        }
1262        mLayersPendingRemoval.clear();
1263    }
1264
1265    mDrawingState = mCurrentState;
1266    mTransationPending = false;
1267    mTransactionCV.broadcast();
1268}
1269
1270void SurfaceFlinger::computeVisibleRegions(
1271        const LayerVector& currentLayers, uint32_t layerStack,
1272        Region& outDirtyRegion, Region& outOpaqueRegion)
1273{
1274    ATRACE_CALL();
1275
1276    Region aboveOpaqueLayers;
1277    Region aboveCoveredLayers;
1278    Region dirty;
1279
1280    outDirtyRegion.clear();
1281
1282    size_t i = currentLayers.size();
1283    while (i--) {
1284        const sp<LayerBase>& layer = currentLayers[i];
1285
1286        // start with the whole surface at its current location
1287        const Layer::State& s(layer->drawingState());
1288
1289        // only consider the layers on the given later stack
1290        if (s.layerStack != layerStack)
1291            continue;
1292
1293        /*
1294         * opaqueRegion: area of a surface that is fully opaque.
1295         */
1296        Region opaqueRegion;
1297
1298        /*
1299         * visibleRegion: area of a surface that is visible on screen
1300         * and not fully transparent. This is essentially the layer's
1301         * footprint minus the opaque regions above it.
1302         * Areas covered by a translucent surface are considered visible.
1303         */
1304        Region visibleRegion;
1305
1306        /*
1307         * coveredRegion: area of a surface that is covered by all
1308         * visible regions above it (which includes the translucent areas).
1309         */
1310        Region coveredRegion;
1311
1312        /*
1313         * transparentRegion: area of a surface that is hinted to be completely
1314         * transparent. This is only used to tell when the layer has no visible
1315         * non-transparent regions and can be removed from the layer list. It
1316         * does not affect the visibleRegion of this layer or any layers
1317         * beneath it. The hint may not be correct if apps don't respect the
1318         * SurfaceView restrictions (which, sadly, some don't).
1319         */
1320        Region transparentRegion;
1321
1322
1323        // handle hidden surfaces by setting the visible region to empty
1324        if (CC_LIKELY(layer->isVisible())) {
1325            const bool translucent = !layer->isOpaque();
1326            Rect bounds(layer->computeBounds());
1327            visibleRegion.set(bounds);
1328            if (!visibleRegion.isEmpty()) {
1329                // Remove the transparent area from the visible region
1330                if (translucent) {
1331                    const Transform tr(s.transform);
1332                    if (tr.transformed()) {
1333                        if (tr.preserveRects()) {
1334                            // transform the transparent region
1335                            transparentRegion = tr.transform(s.transparentRegion);
1336                        } else {
1337                            // transformation too complex, can't do the
1338                            // transparent region optimization.
1339                            transparentRegion.clear();
1340                        }
1341                    } else {
1342                        transparentRegion = s.transparentRegion;
1343                    }
1344                }
1345
1346                // compute the opaque region
1347                const int32_t layerOrientation = s.transform.getOrientation();
1348                if (s.alpha==255 && !translucent &&
1349                        ((layerOrientation & Transform::ROT_INVALID) == false)) {
1350                    // the opaque region is the layer's footprint
1351                    opaqueRegion = visibleRegion;
1352                }
1353            }
1354        }
1355
1356        // Clip the covered region to the visible region
1357        coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1358
1359        // Update aboveCoveredLayers for next (lower) layer
1360        aboveCoveredLayers.orSelf(visibleRegion);
1361
1362        // subtract the opaque region covered by the layers above us
1363        visibleRegion.subtractSelf(aboveOpaqueLayers);
1364
1365        // compute this layer's dirty region
1366        if (layer->contentDirty) {
1367            // we need to invalidate the whole region
1368            dirty = visibleRegion;
1369            // as well, as the old visible region
1370            dirty.orSelf(layer->visibleRegion);
1371            layer->contentDirty = false;
1372        } else {
1373            /* compute the exposed region:
1374             *   the exposed region consists of two components:
1375             *   1) what's VISIBLE now and was COVERED before
1376             *   2) what's EXPOSED now less what was EXPOSED before
1377             *
1378             * note that (1) is conservative, we start with the whole
1379             * visible region but only keep what used to be covered by
1380             * something -- which mean it may have been exposed.
1381             *
1382             * (2) handles areas that were not covered by anything but got
1383             * exposed because of a resize.
1384             */
1385            const Region newExposed = visibleRegion - coveredRegion;
1386            const Region oldVisibleRegion = layer->visibleRegion;
1387            const Region oldCoveredRegion = layer->coveredRegion;
1388            const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1389            dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1390        }
1391        dirty.subtractSelf(aboveOpaqueLayers);
1392
1393        // accumulate to the screen dirty region
1394        outDirtyRegion.orSelf(dirty);
1395
1396        // Update aboveOpaqueLayers for next (lower) layer
1397        aboveOpaqueLayers.orSelf(opaqueRegion);
1398
1399        // Store the visible region in screen space
1400        layer->setVisibleRegion(visibleRegion);
1401        layer->setCoveredRegion(coveredRegion);
1402        layer->setVisibleNonTransparentRegion(
1403                visibleRegion.subtract(transparentRegion));
1404    }
1405
1406    outOpaqueRegion = aboveOpaqueLayers;
1407}
1408
1409void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1410        const Region& dirty) {
1411    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1412        const sp<DisplayDevice>& hw(mDisplays[dpy]);
1413        if (hw->getLayerStack() == layerStack) {
1414            hw->dirtyRegion.orSelf(dirty);
1415        }
1416    }
1417}
1418
1419void SurfaceFlinger::handlePageFlip()
1420{
1421    Region dirtyRegion;
1422
1423    bool visibleRegions = false;
1424    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
1425    const size_t count = currentLayers.size();
1426    for (size_t i=0 ; i<count ; i++) {
1427        const sp<LayerBase>& layer(currentLayers[i]);
1428        const Region dirty(layer->latchBuffer(visibleRegions));
1429        const Layer::State& s(layer->drawingState());
1430        invalidateLayerStack(s.layerStack, dirty);
1431    }
1432
1433    mVisibleRegionsDirty |= visibleRegions;
1434}
1435
1436void SurfaceFlinger::invalidateHwcGeometry()
1437{
1438    mHwWorkListDirty = true;
1439}
1440
1441
1442void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1443        const Region& inDirtyRegion)
1444{
1445    Region dirtyRegion(inDirtyRegion);
1446
1447    // compute the invalid region
1448    hw->swapRegion.orSelf(dirtyRegion);
1449
1450    uint32_t flags = hw->getFlags();
1451    if (flags & DisplayDevice::SWAP_RECTANGLE) {
1452        // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1453        // takes a rectangle, we must make sure to update that whole
1454        // rectangle in that case
1455        dirtyRegion.set(hw->swapRegion.bounds());
1456    } else {
1457        if (flags & DisplayDevice::PARTIAL_UPDATES) {
1458            // We need to redraw the rectangle that will be updated
1459            // (pushed to the framebuffer).
1460            // This is needed because PARTIAL_UPDATES only takes one
1461            // rectangle instead of a region (see DisplayDevice::flip())
1462            dirtyRegion.set(hw->swapRegion.bounds());
1463        } else {
1464            // we need to redraw everything (the whole screen)
1465            dirtyRegion.set(hw->bounds());
1466            hw->swapRegion = dirtyRegion;
1467        }
1468    }
1469
1470    doComposeSurfaces(hw, dirtyRegion);
1471
1472    // update the swap region and clear the dirty region
1473    hw->swapRegion.orSelf(dirtyRegion);
1474
1475    // swap buffers (presentation)
1476    hw->swapBuffers(getHwComposer());
1477}
1478
1479void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1480{
1481    const int32_t id = hw->getHwcDisplayId();
1482    HWComposer& hwc(getHwComposer());
1483    HWComposer::LayerListIterator cur = hwc.begin(id);
1484    const HWComposer::LayerListIterator end = hwc.end(id);
1485
1486    const bool hasGlesComposition = hwc.hasGlesComposition(id) || (cur==end);
1487    if (hasGlesComposition) {
1488        DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext);
1489
1490        // set the frame buffer
1491        glMatrixMode(GL_MODELVIEW);
1492        glLoadIdentity();
1493
1494        // Never touch the framebuffer if we don't have any framebuffer layers
1495        const bool hasHwcComposition = hwc.hasHwcComposition(id);
1496        if (hasHwcComposition) {
1497            // when using overlays, we assume a fully transparent framebuffer
1498            // NOTE: we could reduce how much we need to clear, for instance
1499            // remove where there are opaque FB layers. however, on some
1500            // GPUs doing a "clean slate" glClear might be more efficient.
1501            // We'll revisit later if needed.
1502            glClearColor(0, 0, 0, 0);
1503            glClear(GL_COLOR_BUFFER_BIT);
1504        } else {
1505            const Region region(hw->undefinedRegion.intersect(dirty));
1506            // screen is already cleared here
1507            if (!region.isEmpty()) {
1508                // can happen with SurfaceView
1509                drawWormhole(hw, region);
1510            }
1511        }
1512    }
1513
1514    /*
1515     * and then, render the layers targeted at the framebuffer
1516     */
1517
1518    const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
1519    const size_t count = layers.size();
1520    const Transform& tr = hw->getTransform();
1521    if (cur != end) {
1522        // we're using h/w composer
1523        for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1524            const sp<LayerBase>& layer(layers[i]);
1525            const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1526            if (!clip.isEmpty()) {
1527                switch (cur->getCompositionType()) {
1528                    case HWC_OVERLAY: {
1529                        if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1530                                && i
1531                                && layer->isOpaque()
1532                                && hasGlesComposition) {
1533                            // never clear the very first layer since we're
1534                            // guaranteed the FB is already cleared
1535                            layer->clearWithOpenGL(hw, clip);
1536                        }
1537                        break;
1538                    }
1539                    case HWC_FRAMEBUFFER: {
1540                        layer->draw(hw, clip);
1541                        break;
1542                    }
1543                    case HWC_FRAMEBUFFER_TARGET: {
1544                        // this should not happen as the iterator shouldn't
1545                        // let us get there.
1546                        ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%d)", i);
1547                        break;
1548                    }
1549                }
1550            }
1551            layer->setAcquireFence(hw, *cur);
1552        }
1553    } else {
1554        // we're not using h/w composer
1555        for (size_t i=0 ; i<count ; ++i) {
1556            const sp<LayerBase>& layer(layers[i]);
1557            const Region clip(dirty.intersect(
1558                    tr.transform(layer->visibleRegion)));
1559            if (!clip.isEmpty()) {
1560                layer->draw(hw, clip);
1561            }
1562        }
1563    }
1564}
1565
1566void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw,
1567        const Region& region) const
1568{
1569    glDisable(GL_TEXTURE_EXTERNAL_OES);
1570    glDisable(GL_TEXTURE_2D);
1571    glDisable(GL_BLEND);
1572    glColor4f(0,0,0,0);
1573
1574    const int32_t height = hw->getHeight();
1575    Region::const_iterator it = region.begin();
1576    Region::const_iterator const end = region.end();
1577    while (it != end) {
1578        const Rect& r = *it++;
1579        GLfloat vertices[][2] = {
1580                { r.left,  height - r.top },
1581                { r.left,  height - r.bottom },
1582                { r.right, height - r.bottom },
1583                { r.right, height - r.top }
1584        };
1585        glVertexPointer(2, GL_FLOAT, 0, vertices);
1586        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1587    }
1588}
1589
1590ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
1591        const sp<LayerBaseClient>& lbc)
1592{
1593    // attach this layer to the client
1594    size_t name = client->attachLayer(lbc);
1595
1596    // add this layer to the current state list
1597    Mutex::Autolock _l(mStateLock);
1598    mCurrentState.layersSortedByZ.add(lbc);
1599
1600    return ssize_t(name);
1601}
1602
1603status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
1604{
1605    Mutex::Autolock _l(mStateLock);
1606    status_t err = purgatorizeLayer_l(layer);
1607    if (err == NO_ERROR)
1608        setTransactionFlags(eTransactionNeeded);
1609    return err;
1610}
1611
1612status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
1613{
1614    ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1615    if (index >= 0) {
1616        mLayersRemoved = true;
1617        return NO_ERROR;
1618    }
1619    return status_t(index);
1620}
1621
1622status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1623{
1624    // First add the layer to the purgatory list, which makes sure it won't
1625    // go away, then remove it from the main list (through a transaction).
1626    ssize_t err = removeLayer_l(layerBase);
1627    if (err >= 0) {
1628        mLayerPurgatory.add(layerBase);
1629    }
1630
1631    mLayersPendingRemoval.push(layerBase);
1632
1633    // it's possible that we don't find a layer, because it might
1634    // have been destroyed already -- this is not technically an error
1635    // from the user because there is a race between Client::destroySurface(),
1636    // ~Client() and ~ISurface().
1637    return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1638}
1639
1640uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags)
1641{
1642    return android_atomic_release_load(&mTransactionFlags);
1643}
1644
1645uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1646{
1647    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1648}
1649
1650uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1651{
1652    uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1653    if ((old & flags)==0) { // wake the server up
1654        signalTransaction();
1655    }
1656    return old;
1657}
1658
1659void SurfaceFlinger::setTransactionState(
1660        const Vector<ComposerState>& state,
1661        const Vector<DisplayState>& displays,
1662        uint32_t flags)
1663{
1664    Mutex::Autolock _l(mStateLock);
1665    uint32_t transactionFlags = 0;
1666
1667    size_t count = displays.size();
1668    for (size_t i=0 ; i<count ; i++) {
1669        const DisplayState& s(displays[i]);
1670        transactionFlags |= setDisplayStateLocked(s);
1671    }
1672
1673    count = state.size();
1674    for (size_t i=0 ; i<count ; i++) {
1675        const ComposerState& s(state[i]);
1676        sp<Client> client( static_cast<Client *>(s.client.get()) );
1677        transactionFlags |= setClientStateLocked(client, s.state);
1678    }
1679
1680    if (transactionFlags) {
1681        // this triggers the transaction
1682        setTransactionFlags(transactionFlags);
1683
1684        // if this is a synchronous transaction, wait for it to take effect
1685        // before returning.
1686        if (flags & eSynchronous) {
1687            mTransationPending = true;
1688        }
1689        while (mTransationPending) {
1690            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1691            if (CC_UNLIKELY(err != NO_ERROR)) {
1692                // just in case something goes wrong in SF, return to the
1693                // called after a few seconds.
1694                ALOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!");
1695                mTransationPending = false;
1696                break;
1697            }
1698        }
1699    }
1700}
1701
1702uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
1703{
1704    uint32_t flags = 0;
1705    DisplayDeviceState& disp(mCurrentState.displays.editValueFor(s.token));
1706    if (disp.isValid()) {
1707        const uint32_t what = s.what;
1708        if (what & DisplayState::eSurfaceChanged) {
1709            if (disp.surface->asBinder() != s.surface->asBinder()) {
1710                disp.surface = s.surface;
1711                flags |= eDisplayTransactionNeeded;
1712            }
1713        }
1714        if (what & DisplayState::eLayerStackChanged) {
1715            if (disp.layerStack != s.layerStack) {
1716                disp.layerStack = s.layerStack;
1717                flags |= eDisplayTransactionNeeded;
1718            }
1719        }
1720        if (what & DisplayState::eDisplayProjectionChanged) {
1721            if (disp.orientation != s.orientation) {
1722                disp.orientation = s.orientation;
1723                flags |= eDisplayTransactionNeeded;
1724            }
1725            if (disp.frame != s.frame) {
1726                disp.frame = s.frame;
1727                flags |= eDisplayTransactionNeeded;
1728            }
1729            if (disp.viewport != s.viewport) {
1730                disp.viewport = s.viewport;
1731                flags |= eDisplayTransactionNeeded;
1732            }
1733        }
1734    }
1735    return flags;
1736}
1737
1738uint32_t SurfaceFlinger::setClientStateLocked(
1739        const sp<Client>& client,
1740        const layer_state_t& s)
1741{
1742    uint32_t flags = 0;
1743    sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
1744    if (layer != 0) {
1745        const uint32_t what = s.what;
1746        if (what & layer_state_t::ePositionChanged) {
1747            if (layer->setPosition(s.x, s.y))
1748                flags |= eTraversalNeeded;
1749        }
1750        if (what & layer_state_t::eLayerChanged) {
1751            // NOTE: index needs to be calculated before we update the state
1752            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1753            if (layer->setLayer(s.z)) {
1754                mCurrentState.layersSortedByZ.removeAt(idx);
1755                mCurrentState.layersSortedByZ.add(layer);
1756                // we need traversal (state changed)
1757                // AND transaction (list changed)
1758                flags |= eTransactionNeeded|eTraversalNeeded;
1759            }
1760        }
1761        if (what & layer_state_t::eSizeChanged) {
1762            if (layer->setSize(s.w, s.h)) {
1763                flags |= eTraversalNeeded;
1764            }
1765        }
1766        if (what & layer_state_t::eAlphaChanged) {
1767            if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1768                flags |= eTraversalNeeded;
1769        }
1770        if (what & layer_state_t::eMatrixChanged) {
1771            if (layer->setMatrix(s.matrix))
1772                flags |= eTraversalNeeded;
1773        }
1774        if (what & layer_state_t::eTransparentRegionChanged) {
1775            if (layer->setTransparentRegionHint(s.transparentRegion))
1776                flags |= eTraversalNeeded;
1777        }
1778        if (what & layer_state_t::eVisibilityChanged) {
1779            if (layer->setFlags(s.flags, s.mask))
1780                flags |= eTraversalNeeded;
1781        }
1782        if (what & layer_state_t::eCropChanged) {
1783            if (layer->setCrop(s.crop))
1784                flags |= eTraversalNeeded;
1785        }
1786        if (what & layer_state_t::eLayerStackChanged) {
1787            // NOTE: index needs to be calculated before we update the state
1788            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1789            if (layer->setLayerStack(s.layerStack)) {
1790                mCurrentState.layersSortedByZ.removeAt(idx);
1791                mCurrentState.layersSortedByZ.add(layer);
1792                // we need traversal (state changed)
1793                // AND transaction (list changed)
1794                flags |= eTransactionNeeded|eTraversalNeeded;
1795            }
1796        }
1797    }
1798    return flags;
1799}
1800
1801sp<ISurface> SurfaceFlinger::createLayer(
1802        ISurfaceComposerClient::surface_data_t* params,
1803        const String8& name,
1804        const sp<Client>& client,
1805       uint32_t w, uint32_t h, PixelFormat format,
1806        uint32_t flags)
1807{
1808    sp<LayerBaseClient> layer;
1809    sp<ISurface> surfaceHandle;
1810
1811    if (int32_t(w|h) < 0) {
1812        ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
1813                int(w), int(h));
1814        return surfaceHandle;
1815    }
1816
1817    //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
1818    switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
1819        case ISurfaceComposerClient::eFXSurfaceNormal:
1820            layer = createNormalLayer(client, w, h, flags, format);
1821            break;
1822        case ISurfaceComposerClient::eFXSurfaceBlur:
1823        case ISurfaceComposerClient::eFXSurfaceDim:
1824            layer = createDimLayer(client, w, h, flags);
1825            break;
1826        case ISurfaceComposerClient::eFXSurfaceScreenshot:
1827            layer = createScreenshotLayer(client, w, h, flags);
1828            break;
1829    }
1830
1831    if (layer != 0) {
1832        layer->initStates(w, h, flags);
1833        layer->setName(name);
1834        ssize_t token = addClientLayer(client, layer);
1835        surfaceHandle = layer->getSurface();
1836        if (surfaceHandle != 0) {
1837            params->token = token;
1838            params->identity = layer->getIdentity();
1839        }
1840        setTransactionFlags(eTransactionNeeded);
1841    }
1842
1843    return surfaceHandle;
1844}
1845
1846sp<Layer> SurfaceFlinger::createNormalLayer(
1847        const sp<Client>& client,
1848        uint32_t w, uint32_t h, uint32_t flags,
1849        PixelFormat& format)
1850{
1851    // initialize the surfaces
1852    switch (format) {
1853    case PIXEL_FORMAT_TRANSPARENT:
1854    case PIXEL_FORMAT_TRANSLUCENT:
1855        format = PIXEL_FORMAT_RGBA_8888;
1856        break;
1857    case PIXEL_FORMAT_OPAQUE:
1858#ifdef NO_RGBX_8888
1859        format = PIXEL_FORMAT_RGB_565;
1860#else
1861        format = PIXEL_FORMAT_RGBX_8888;
1862#endif
1863        break;
1864    }
1865
1866#ifdef NO_RGBX_8888
1867    if (format == PIXEL_FORMAT_RGBX_8888)
1868        format = PIXEL_FORMAT_RGBA_8888;
1869#endif
1870
1871    sp<Layer> layer = new Layer(this, client);
1872    status_t err = layer->setBuffers(w, h, format, flags);
1873    if (CC_LIKELY(err != NO_ERROR)) {
1874        ALOGE("createNormalLayer() failed (%s)", strerror(-err));
1875        layer.clear();
1876    }
1877    return layer;
1878}
1879
1880sp<LayerDim> SurfaceFlinger::createDimLayer(
1881        const sp<Client>& client,
1882        uint32_t w, uint32_t h, uint32_t flags)
1883{
1884    sp<LayerDim> layer = new LayerDim(this, client);
1885    return layer;
1886}
1887
1888sp<LayerScreenshot> SurfaceFlinger::createScreenshotLayer(
1889        const sp<Client>& client,
1890        uint32_t w, uint32_t h, uint32_t flags)
1891{
1892    sp<LayerScreenshot> layer = new LayerScreenshot(this, client);
1893    return layer;
1894}
1895
1896status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, SurfaceID sid)
1897{
1898    /*
1899     * called by the window manager, when a surface should be marked for
1900     * destruction.
1901     *
1902     * The surface is removed from the current and drawing lists, but placed
1903     * in the purgatory queue, so it's not destroyed right-away (we need
1904     * to wait for all client's references to go away first).
1905     */
1906
1907    status_t err = NAME_NOT_FOUND;
1908    Mutex::Autolock _l(mStateLock);
1909    sp<LayerBaseClient> layer = client->getLayerUser(sid);
1910
1911    if (layer != 0) {
1912        err = purgatorizeLayer_l(layer);
1913        if (err == NO_ERROR) {
1914            setTransactionFlags(eTransactionNeeded);
1915        }
1916    }
1917    return err;
1918}
1919
1920status_t SurfaceFlinger::onLayerDestroyed(const wp<LayerBaseClient>& layer)
1921{
1922    // called by ~ISurface() when all references are gone
1923    status_t err = NO_ERROR;
1924    sp<LayerBaseClient> l(layer.promote());
1925    if (l != NULL) {
1926        Mutex::Autolock _l(mStateLock);
1927        err = removeLayer_l(l);
1928        if (err == NAME_NOT_FOUND) {
1929            // The surface wasn't in the current list, which means it was
1930            // removed already, which means it is in the purgatory,
1931            // and need to be removed from there.
1932            ssize_t idx = mLayerPurgatory.remove(l);
1933            ALOGE_IF(idx < 0,
1934                    "layer=%p is not in the purgatory list", l.get());
1935        }
1936        ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
1937                "error removing layer=%p (%s)", l.get(), strerror(-err));
1938    }
1939    return err;
1940}
1941
1942// ---------------------------------------------------------------------------
1943
1944void SurfaceFlinger::onInitializeDisplays() {
1945    // reset screen orientation
1946    Vector<ComposerState> state;
1947    Vector<DisplayState> displays;
1948    DisplayState d;
1949    d.what = DisplayState::eDisplayProjectionChanged;
1950    d.token = mDefaultDisplays[DisplayDevice::DISPLAY_PRIMARY];
1951    d.orientation = DisplayState::eOrientationDefault;
1952    d.frame.makeInvalid();
1953    d.viewport.makeInvalid();
1954    displays.add(d);
1955    setTransactionState(state, displays, 0);
1956    onScreenAcquired(getDefaultDisplayDevice());
1957}
1958
1959void SurfaceFlinger::initializeDisplays() {
1960    class MessageScreenInitialized : public MessageBase {
1961        SurfaceFlinger* flinger;
1962    public:
1963        MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
1964        virtual bool handler() {
1965            flinger->onInitializeDisplays();
1966            return true;
1967        }
1968    };
1969    sp<MessageBase> msg = new MessageScreenInitialized(this);
1970    postMessageAsync(msg);  // we may be called from main thread, use async message
1971}
1972
1973
1974void SurfaceFlinger::onScreenAcquired(const sp<const DisplayDevice>& hw) {
1975    ALOGD("Screen acquired, type=%d flinger=%p", hw->getDisplayType(), this);
1976    if (hw->isScreenAcquired()) {
1977        // this is expected, e.g. when power manager wakes up during boot
1978        ALOGD(" screen was previously acquired");
1979        return;
1980    }
1981
1982    hw->acquireScreen();
1983    int32_t type = hw->getDisplayType();
1984    if (type < DisplayDevice::NUM_DISPLAY_TYPES) {
1985        // built-in display, tell the HWC
1986        getHwComposer().acquire(type);
1987
1988        if (type == DisplayDevice::DISPLAY_PRIMARY) {
1989            // FIXME: eventthread only knows about the main display right now
1990            mEventThread->onScreenAcquired();
1991        }
1992    }
1993    mVisibleRegionsDirty = true;
1994    repaintEverything();
1995}
1996
1997void SurfaceFlinger::onScreenReleased(const sp<const DisplayDevice>& hw) {
1998    ALOGD("Screen released, type=%d flinger=%p", hw->getDisplayType(), this);
1999    if (!hw->isScreenAcquired()) {
2000        ALOGD(" screen was previously released");
2001        return;
2002    }
2003
2004    hw->releaseScreen();
2005    int32_t type = hw->getDisplayType();
2006    if (type < DisplayDevice::NUM_DISPLAY_TYPES) {
2007        if (type == DisplayDevice::DISPLAY_PRIMARY) {
2008            // FIXME: eventthread only knows about the main display right now
2009            mEventThread->onScreenReleased();
2010        }
2011
2012        // built-in display, tell the HWC
2013        getHwComposer().release(type);
2014    }
2015    mVisibleRegionsDirty = true;
2016    // from this point on, SF will stop drawing on this display
2017}
2018
2019void SurfaceFlinger::unblank(const sp<IBinder>& display) {
2020    class MessageScreenAcquired : public MessageBase {
2021        SurfaceFlinger* mFlinger;
2022        const sp<DisplayDevice>& mHw;
2023    public:
2024        MessageScreenAcquired(SurfaceFlinger* flinger,
2025                const sp<DisplayDevice>& hw) : mFlinger(flinger), mHw(hw) { }
2026        virtual bool handler() {
2027            mFlinger->onScreenAcquired(mHw);
2028            return true;
2029        }
2030    };
2031    const sp<DisplayDevice>& hw = getDisplayDevice(display);
2032    if (hw == NULL) {
2033        ALOGE("Attempt to unblank null display %p", display.get());
2034    } else if (hw->getDisplayType() >= DisplayDevice::NUM_DISPLAY_TYPES) {
2035        ALOGW("Attempt to unblank virtual display");
2036    } else {
2037        sp<MessageBase> msg = new MessageScreenAcquired(this, hw);
2038        postMessageSync(msg);
2039    }
2040}
2041
2042void SurfaceFlinger::blank(const sp<IBinder>& display) {
2043    class MessageScreenReleased : public MessageBase {
2044        SurfaceFlinger* mFlinger;
2045        const sp<DisplayDevice>& mHw;
2046    public:
2047        MessageScreenReleased(SurfaceFlinger* flinger,
2048                const sp<DisplayDevice>& hw) : mFlinger(flinger), mHw(hw) { }
2049        virtual bool handler() {
2050            mFlinger->onScreenReleased(mHw);
2051            return true;
2052        }
2053    };
2054    const sp<DisplayDevice>& hw = getDisplayDevice(display);
2055    if (hw == NULL) {
2056        ALOGE("Attempt to blank null display %p", display.get());
2057    } else if (hw->getDisplayType() >= DisplayDevice::NUM_DISPLAY_TYPES) {
2058        ALOGW("Attempt to blank virtual display");
2059    } else {
2060        sp<MessageBase> msg = new MessageScreenReleased(this, hw);
2061        postMessageSync(msg);
2062    }
2063}
2064
2065// ---------------------------------------------------------------------------
2066
2067status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2068{
2069    const size_t SIZE = 4096;
2070    char buffer[SIZE];
2071    String8 result;
2072
2073    if (!PermissionCache::checkCallingPermission(sDump)) {
2074        snprintf(buffer, SIZE, "Permission Denial: "
2075                "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
2076                IPCThreadState::self()->getCallingPid(),
2077                IPCThreadState::self()->getCallingUid());
2078        result.append(buffer);
2079    } else {
2080        // Try to get the main lock, but don't insist if we can't
2081        // (this would indicate SF is stuck, but we want to be able to
2082        // print something in dumpsys).
2083        int retry = 3;
2084        while (mStateLock.tryLock()<0 && --retry>=0) {
2085            usleep(1000000);
2086        }
2087        const bool locked(retry >= 0);
2088        if (!locked) {
2089            snprintf(buffer, SIZE,
2090                    "SurfaceFlinger appears to be unresponsive, "
2091                    "dumping anyways (no locks held)\n");
2092            result.append(buffer);
2093        }
2094
2095        bool dumpAll = true;
2096        size_t index = 0;
2097        size_t numArgs = args.size();
2098        if (numArgs) {
2099            if ((index < numArgs) &&
2100                    (args[index] == String16("--list"))) {
2101                index++;
2102                listLayersLocked(args, index, result, buffer, SIZE);
2103                dumpAll = false;
2104            }
2105
2106            if ((index < numArgs) &&
2107                    (args[index] == String16("--latency"))) {
2108                index++;
2109                dumpStatsLocked(args, index, result, buffer, SIZE);
2110                dumpAll = false;
2111            }
2112
2113            if ((index < numArgs) &&
2114                    (args[index] == String16("--latency-clear"))) {
2115                index++;
2116                clearStatsLocked(args, index, result, buffer, SIZE);
2117                dumpAll = false;
2118            }
2119        }
2120
2121        if (dumpAll) {
2122            dumpAllLocked(result, buffer, SIZE);
2123        }
2124
2125        if (locked) {
2126            mStateLock.unlock();
2127        }
2128    }
2129    write(fd, result.string(), result.size());
2130    return NO_ERROR;
2131}
2132
2133void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
2134        String8& result, char* buffer, size_t SIZE) const
2135{
2136    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2137    const size_t count = currentLayers.size();
2138    for (size_t i=0 ; i<count ; i++) {
2139        const sp<LayerBase>& layer(currentLayers[i]);
2140        snprintf(buffer, SIZE, "%s\n", layer->getName().string());
2141        result.append(buffer);
2142    }
2143}
2144
2145void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2146        String8& result, char* buffer, size_t SIZE) const
2147{
2148    String8 name;
2149    if (index < args.size()) {
2150        name = String8(args[index]);
2151        index++;
2152    }
2153
2154    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2155    const size_t count = currentLayers.size();
2156    for (size_t i=0 ; i<count ; i++) {
2157        const sp<LayerBase>& layer(currentLayers[i]);
2158        if (name.isEmpty()) {
2159            snprintf(buffer, SIZE, "%s\n", layer->getName().string());
2160            result.append(buffer);
2161        }
2162        if (name.isEmpty() || (name == layer->getName())) {
2163            layer->dumpStats(result, buffer, SIZE);
2164        }
2165    }
2166}
2167
2168void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2169        String8& result, char* buffer, size_t SIZE) const
2170{
2171    String8 name;
2172    if (index < args.size()) {
2173        name = String8(args[index]);
2174        index++;
2175    }
2176
2177    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2178    const size_t count = currentLayers.size();
2179    for (size_t i=0 ; i<count ; i++) {
2180        const sp<LayerBase>& layer(currentLayers[i]);
2181        if (name.isEmpty() || (name == layer->getName())) {
2182            layer->clearStats();
2183        }
2184    }
2185}
2186
2187/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2188{
2189    static const char* config =
2190            " [sf"
2191#ifdef NO_RGBX_8888
2192            " NO_RGBX_8888"
2193#endif
2194#ifdef HAS_CONTEXT_PRIORITY
2195            " HAS_CONTEXT_PRIORITY"
2196#endif
2197#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2198            " NEVER_DEFAULT_TO_ASYNC_MODE"
2199#endif
2200#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2201            " TARGET_DISABLE_TRIPLE_BUFFERING"
2202#endif
2203            "]";
2204    result.append(config);
2205}
2206
2207void SurfaceFlinger::dumpAllLocked(
2208        String8& result, char* buffer, size_t SIZE) const
2209{
2210    // figure out if we're stuck somewhere
2211    const nsecs_t now = systemTime();
2212    const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2213    const nsecs_t inTransaction(mDebugInTransaction);
2214    nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2215    nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2216
2217    /*
2218     * Dump library configuration.
2219     */
2220    result.append("Build configuration:");
2221    appendSfConfigString(result);
2222    appendUiConfigString(result);
2223    appendGuiConfigString(result);
2224    result.append("\n");
2225
2226    /*
2227     * Dump the visible layer list
2228     */
2229    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2230    const size_t count = currentLayers.size();
2231    snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count);
2232    result.append(buffer);
2233    for (size_t i=0 ; i<count ; i++) {
2234        const sp<LayerBase>& layer(currentLayers[i]);
2235        layer->dump(result, buffer, SIZE);
2236    }
2237
2238    /*
2239     * Dump the layers in the purgatory
2240     */
2241
2242    const size_t purgatorySize = mLayerPurgatory.size();
2243    snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize);
2244    result.append(buffer);
2245    for (size_t i=0 ; i<purgatorySize ; i++) {
2246        const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
2247        layer->shortDump(result, buffer, SIZE);
2248    }
2249
2250    /*
2251     * Dump Display state
2252     */
2253
2254    snprintf(buffer, SIZE, "Displays (%d entries)\n", mDisplays.size());
2255    result.append(buffer);
2256    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2257        const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2258        hw->dump(result, buffer, SIZE);
2259    }
2260
2261    /*
2262     * Dump SurfaceFlinger global state
2263     */
2264
2265    snprintf(buffer, SIZE, "SurfaceFlinger global state:\n");
2266    result.append(buffer);
2267
2268    HWComposer& hwc(getHwComposer());
2269    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2270    const GLExtensions& extensions(GLExtensions::getInstance());
2271    snprintf(buffer, SIZE, "GLES: %s, %s, %s\n",
2272            extensions.getVendor(),
2273            extensions.getRenderer(),
2274            extensions.getVersion());
2275    result.append(buffer);
2276
2277    snprintf(buffer, SIZE, "EGL : %s\n",
2278            eglQueryString(mEGLDisplay, EGL_VERSION_HW_ANDROID));
2279    result.append(buffer);
2280
2281    snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension());
2282    result.append(buffer);
2283
2284    hw->undefinedRegion.dump(result, "undefinedRegion");
2285    snprintf(buffer, SIZE,
2286            "  orientation=%d, canDraw=%d\n",
2287            hw->getOrientation(), hw->canDraw());
2288    result.append(buffer);
2289    snprintf(buffer, SIZE,
2290            "  last eglSwapBuffers() time: %f us\n"
2291            "  last transaction time     : %f us\n"
2292            "  transaction-flags         : %08x\n"
2293            "  refresh-rate              : %f fps\n"
2294            "  x-dpi                     : %f\n"
2295            "  y-dpi                     : %f\n",
2296            mLastSwapBufferTime/1000.0,
2297            mLastTransactionTime/1000.0,
2298            mTransactionFlags,
2299            1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2300            hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2301            hwc.getDpiY(HWC_DISPLAY_PRIMARY));
2302    result.append(buffer);
2303
2304    snprintf(buffer, SIZE, "  eglSwapBuffers time: %f us\n",
2305            inSwapBuffersDuration/1000.0);
2306    result.append(buffer);
2307
2308    snprintf(buffer, SIZE, "  transaction time: %f us\n",
2309            inTransactionDuration/1000.0);
2310    result.append(buffer);
2311
2312    /*
2313     * VSYNC state
2314     */
2315    mEventThread->dump(result, buffer, SIZE);
2316
2317    /*
2318     * Dump HWComposer state
2319     */
2320    snprintf(buffer, SIZE, "h/w composer state:\n");
2321    result.append(buffer);
2322    snprintf(buffer, SIZE, "  h/w composer %s and %s\n",
2323            hwc.initCheck()==NO_ERROR ? "present" : "not present",
2324                    (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled");
2325    result.append(buffer);
2326    hwc.dump(result, buffer, SIZE, hw->getVisibleLayersSortedByZ());
2327
2328    /*
2329     * Dump gralloc state
2330     */
2331    const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2332    alloc.dump(result);
2333}
2334
2335bool SurfaceFlinger::startDdmConnection()
2336{
2337    void* libddmconnection_dso =
2338            dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2339    if (!libddmconnection_dso) {
2340        return false;
2341    }
2342    void (*DdmConnection_start)(const char* name);
2343    DdmConnection_start =
2344            (typeof DdmConnection_start)dlsym(libddmconnection_dso, "DdmConnection_start");
2345    if (!DdmConnection_start) {
2346        dlclose(libddmconnection_dso);
2347        return false;
2348    }
2349    (*DdmConnection_start)(getServiceName());
2350    return true;
2351}
2352
2353status_t SurfaceFlinger::onTransact(
2354    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2355{
2356    switch (code) {
2357        case CREATE_CONNECTION:
2358        case SET_TRANSACTION_STATE:
2359        case BOOT_FINISHED:
2360        case BLANK:
2361        case UNBLANK:
2362        {
2363            // codes that require permission check
2364            IPCThreadState* ipc = IPCThreadState::self();
2365            const int pid = ipc->getCallingPid();
2366            const int uid = ipc->getCallingUid();
2367            if ((uid != AID_GRAPHICS) &&
2368                    !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2369                ALOGE("Permission Denial: "
2370                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2371                return PERMISSION_DENIED;
2372            }
2373            break;
2374        }
2375        case CAPTURE_SCREEN:
2376        {
2377            // codes that require permission check
2378            IPCThreadState* ipc = IPCThreadState::self();
2379            const int pid = ipc->getCallingPid();
2380            const int uid = ipc->getCallingUid();
2381            if ((uid != AID_GRAPHICS) &&
2382                    !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2383                ALOGE("Permission Denial: "
2384                        "can't read framebuffer pid=%d, uid=%d", pid, uid);
2385                return PERMISSION_DENIED;
2386            }
2387            break;
2388        }
2389    }
2390
2391    status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2392    if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2393        CHECK_INTERFACE(ISurfaceComposer, data, reply);
2394        if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2395            IPCThreadState* ipc = IPCThreadState::self();
2396            const int pid = ipc->getCallingPid();
2397            const int uid = ipc->getCallingUid();
2398            ALOGE("Permission Denial: "
2399                    "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2400            return PERMISSION_DENIED;
2401        }
2402        int n;
2403        switch (code) {
2404            case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2405            case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2406                return NO_ERROR;
2407            case 1002:  // SHOW_UPDATES
2408                n = data.readInt32();
2409                mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2410                invalidateHwcGeometry();
2411                repaintEverything();
2412                return NO_ERROR;
2413            case 1004:{ // repaint everything
2414                repaintEverything();
2415                return NO_ERROR;
2416            }
2417            case 1005:{ // force transaction
2418                setTransactionFlags(
2419                        eTransactionNeeded|
2420                        eDisplayTransactionNeeded|
2421                        eTraversalNeeded);
2422                return NO_ERROR;
2423            }
2424            case 1006:{ // send empty update
2425                signalRefresh();
2426                return NO_ERROR;
2427            }
2428            case 1008:  // toggle use of hw composer
2429                n = data.readInt32();
2430                mDebugDisableHWC = n ? 1 : 0;
2431                invalidateHwcGeometry();
2432                repaintEverything();
2433                return NO_ERROR;
2434            case 1009:  // toggle use of transform hint
2435                n = data.readInt32();
2436                mDebugDisableTransformHint = n ? 1 : 0;
2437                invalidateHwcGeometry();
2438                repaintEverything();
2439                return NO_ERROR;
2440            case 1010:  // interrogate.
2441                reply->writeInt32(0);
2442                reply->writeInt32(0);
2443                reply->writeInt32(mDebugRegion);
2444                reply->writeInt32(0);
2445                reply->writeInt32(mDebugDisableHWC);
2446                return NO_ERROR;
2447            case 1013: {
2448                Mutex::Autolock _l(mStateLock);
2449                sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2450                reply->writeInt32(hw->getPageFlipCount());
2451            }
2452            return NO_ERROR;
2453        }
2454    }
2455    return err;
2456}
2457
2458void SurfaceFlinger::repaintEverything() {
2459    android_atomic_or(1, &mRepaintEverything);
2460    signalTransaction();
2461}
2462
2463// ---------------------------------------------------------------------------
2464
2465status_t SurfaceFlinger::renderScreenToTexture(uint32_t layerStack,
2466        GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2467{
2468    Mutex::Autolock _l(mStateLock);
2469    return renderScreenToTextureLocked(layerStack, textureName, uOut, vOut);
2470}
2471
2472status_t SurfaceFlinger::renderScreenToTextureLocked(uint32_t layerStack,
2473        GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2474{
2475    ATRACE_CALL();
2476
2477    if (!GLExtensions::getInstance().haveFramebufferObject())
2478        return INVALID_OPERATION;
2479
2480    // get screen geometry
2481    // FIXME: figure out what it means to have a screenshot texture w/ multi-display
2482    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2483    const uint32_t hw_w = hw->getWidth();
2484    const uint32_t hw_h = hw->getHeight();
2485    GLfloat u = 1;
2486    GLfloat v = 1;
2487
2488    // make sure to clear all GL error flags
2489    while ( glGetError() != GL_NO_ERROR ) ;
2490
2491    // create a FBO
2492    GLuint name, tname;
2493    glGenTextures(1, &tname);
2494    glBindTexture(GL_TEXTURE_2D, tname);
2495    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2496    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2497    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2498            hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2499    if (glGetError() != GL_NO_ERROR) {
2500        while ( glGetError() != GL_NO_ERROR ) ;
2501        GLint tw = (2 << (31 - clz(hw_w)));
2502        GLint th = (2 << (31 - clz(hw_h)));
2503        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2504                tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2505        u = GLfloat(hw_w) / tw;
2506        v = GLfloat(hw_h) / th;
2507    }
2508    glGenFramebuffersOES(1, &name);
2509    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2510    glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES,
2511            GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0);
2512
2513    DisplayDevice::setViewportAndProjection(hw);
2514
2515    // redraw the screen entirely...
2516    glDisable(GL_TEXTURE_EXTERNAL_OES);
2517    glDisable(GL_TEXTURE_2D);
2518    glClearColor(0,0,0,1);
2519    glClear(GL_COLOR_BUFFER_BIT);
2520    glMatrixMode(GL_MODELVIEW);
2521    glLoadIdentity();
2522    const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
2523    const size_t count = layers.size();
2524    for (size_t i=0 ; i<count ; ++i) {
2525        const sp<LayerBase>& layer(layers[i]);
2526        layer->draw(hw);
2527    }
2528
2529    hw->compositionComplete();
2530
2531    // back to main framebuffer
2532    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2533    glDeleteFramebuffersOES(1, &name);
2534
2535    *textureName = tname;
2536    *uOut = u;
2537    *vOut = v;
2538    return NO_ERROR;
2539}
2540
2541// ---------------------------------------------------------------------------
2542
2543status_t SurfaceFlinger::captureScreenImplLocked(const sp<IBinder>& display,
2544        sp<IMemoryHeap>* heap,
2545        uint32_t* w, uint32_t* h, PixelFormat* f,
2546        uint32_t sw, uint32_t sh,
2547        uint32_t minLayerZ, uint32_t maxLayerZ)
2548{
2549    ATRACE_CALL();
2550
2551    status_t result = PERMISSION_DENIED;
2552
2553    if (!GLExtensions::getInstance().haveFramebufferObject()) {
2554        return INVALID_OPERATION;
2555    }
2556
2557    // get screen geometry
2558    sp<const DisplayDevice> hw(getDisplayDevice(display));
2559    const uint32_t hw_w = hw->getWidth();
2560    const uint32_t hw_h = hw->getHeight();
2561
2562    // if we have secure windows on this display, never allow the screen capture
2563    if (hw->getSecureLayerVisible()) {
2564        ALOGW("FB is protected: PERMISSION_DENIED");
2565        return PERMISSION_DENIED;
2566    }
2567
2568    if ((sw > hw_w) || (sh > hw_h)) {
2569        ALOGE("size mismatch (%d, %d) > (%d, %d)", sw, sh, hw_w, hw_h);
2570        return BAD_VALUE;
2571    }
2572
2573    sw = (!sw) ? hw_w : sw;
2574    sh = (!sh) ? hw_h : sh;
2575    const size_t size = sw * sh * 4;
2576    const bool filtering = sw != hw_w || sh != hw_h;
2577
2578//    ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d",
2579//            sw, sh, minLayerZ, maxLayerZ);
2580
2581    // make sure to clear all GL error flags
2582    while ( glGetError() != GL_NO_ERROR ) ;
2583
2584    // create a FBO
2585    GLuint name, tname;
2586    glGenRenderbuffersOES(1, &tname);
2587    glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname);
2588    glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh);
2589
2590    glGenFramebuffersOES(1, &name);
2591    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2592    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
2593            GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname);
2594
2595    GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
2596
2597    if (status == GL_FRAMEBUFFER_COMPLETE_OES) {
2598
2599        // invert everything, b/c glReadPixel() below will invert the FB
2600        glViewport(0, 0, sw, sh);
2601        glMatrixMode(GL_PROJECTION);
2602        glPushMatrix();
2603        glLoadIdentity();
2604        glOrthof(0, hw_w, hw_h, 0, 0, 1);
2605        glMatrixMode(GL_MODELVIEW);
2606
2607        // redraw the screen entirely...
2608        glClearColor(0,0,0,1);
2609        glClear(GL_COLOR_BUFFER_BIT);
2610
2611        const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
2612        const size_t count = layers.size();
2613        for (size_t i=0 ; i<count ; ++i) {
2614            const sp<LayerBase>& layer(layers[i]);
2615            const uint32_t z = layer->drawingState().z;
2616            if (z >= minLayerZ && z <= maxLayerZ) {
2617                if (filtering) layer->setFiltering(true);
2618                layer->draw(hw);
2619                if (filtering) layer->setFiltering(false);
2620            }
2621        }
2622
2623        // check for errors and return screen capture
2624        if (glGetError() != GL_NO_ERROR) {
2625            // error while rendering
2626            result = INVALID_OPERATION;
2627        } else {
2628            // allocate shared memory large enough to hold the
2629            // screen capture
2630            sp<MemoryHeapBase> base(
2631                    new MemoryHeapBase(size, 0, "screen-capture") );
2632            void* const ptr = base->getBase();
2633            if (ptr != MAP_FAILED) {
2634                // capture the screen with glReadPixels()
2635                ScopedTrace _t(ATRACE_TAG, "glReadPixels");
2636                glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
2637                if (glGetError() == GL_NO_ERROR) {
2638                    *heap = base;
2639                    *w = sw;
2640                    *h = sh;
2641                    *f = PIXEL_FORMAT_RGBA_8888;
2642                    result = NO_ERROR;
2643                }
2644            } else {
2645                result = NO_MEMORY;
2646            }
2647        }
2648        glViewport(0, 0, hw_w, hw_h);
2649        glMatrixMode(GL_PROJECTION);
2650        glPopMatrix();
2651        glMatrixMode(GL_MODELVIEW);
2652    } else {
2653        result = BAD_VALUE;
2654    }
2655
2656    // release FBO resources
2657    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2658    glDeleteRenderbuffersOES(1, &tname);
2659    glDeleteFramebuffersOES(1, &name);
2660
2661    hw->compositionComplete();
2662
2663//    ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK");
2664
2665    return result;
2666}
2667
2668
2669status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
2670        sp<IMemoryHeap>* heap,
2671        uint32_t* width, uint32_t* height, PixelFormat* format,
2672        uint32_t sw, uint32_t sh,
2673        uint32_t minLayerZ, uint32_t maxLayerZ)
2674{
2675    if (CC_UNLIKELY(display == 0))
2676        return BAD_VALUE;
2677
2678    if (!GLExtensions::getInstance().haveFramebufferObject())
2679        return INVALID_OPERATION;
2680
2681    class MessageCaptureScreen : public MessageBase {
2682        SurfaceFlinger* flinger;
2683        sp<IBinder> display;
2684        sp<IMemoryHeap>* heap;
2685        uint32_t* w;
2686        uint32_t* h;
2687        PixelFormat* f;
2688        uint32_t sw;
2689        uint32_t sh;
2690        uint32_t minLayerZ;
2691        uint32_t maxLayerZ;
2692        status_t result;
2693    public:
2694        MessageCaptureScreen(SurfaceFlinger* flinger, const sp<IBinder>& display,
2695                sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f,
2696                uint32_t sw, uint32_t sh,
2697                uint32_t minLayerZ, uint32_t maxLayerZ)
2698            : flinger(flinger), display(display),
2699              heap(heap), w(w), h(h), f(f), sw(sw), sh(sh),
2700              minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2701              result(PERMISSION_DENIED)
2702        {
2703        }
2704        status_t getResult() const {
2705            return result;
2706        }
2707        virtual bool handler() {
2708            Mutex::Autolock _l(flinger->mStateLock);
2709            result = flinger->captureScreenImplLocked(display,
2710                    heap, w, h, f, sw, sh, minLayerZ, maxLayerZ);
2711            return true;
2712        }
2713    };
2714
2715    sp<MessageBase> msg = new MessageCaptureScreen(this,
2716            display, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ);
2717    status_t res = postMessageSync(msg);
2718    if (res == NO_ERROR) {
2719        res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult();
2720    }
2721    return res;
2722}
2723
2724// ---------------------------------------------------------------------------
2725
2726SurfaceFlinger::LayerVector::LayerVector() {
2727}
2728
2729SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
2730    : SortedVector<sp<LayerBase> >(rhs) {
2731}
2732
2733int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
2734    const void* rhs) const
2735{
2736    // sort layers per layer-stack, then by z-order and finally by sequence
2737    const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs));
2738    const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs));
2739
2740    uint32_t ls = l->currentState().layerStack;
2741    uint32_t rs = r->currentState().layerStack;
2742    if (ls != rs)
2743        return ls - rs;
2744
2745    uint32_t lz = l->currentState().z;
2746    uint32_t rz = r->currentState().z;
2747    if (lz != rz)
2748        return lz - rz;
2749
2750    return l->sequence - r->sequence;
2751}
2752
2753// ---------------------------------------------------------------------------
2754
2755SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
2756    : type(DisplayDevice::DISPLAY_ID_INVALID) {
2757}
2758
2759SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
2760    : type(type), layerStack(0), orientation(0) {
2761    viewport.makeInvalid();
2762    frame.makeInvalid();
2763}
2764
2765// ---------------------------------------------------------------------------
2766
2767}; // namespace android
2768