SurfaceFlinger.cpp revision 81cd5d3b94d21253a0be925f4ae58cc7f4afeef7
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 disp, int event, int enabled) {
781    getHwComposer().eventControl(disp, 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                        // Call makeCurrent() on the primary display so we can
1127                        // be sure that nothing associated with this display
1128                        // is current.
1129                        const sp<const DisplayDevice>& hw(getDefaultDisplayDevice());
1130                        DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext);
1131                        mDisplays.removeItem(draw.keyAt(i));
1132                        getHwComposer().disconnectDisplay(draw[i].type);
1133                    } else {
1134                        ALOGW("trying to remove the main display");
1135                    }
1136                } else {
1137                    // this display is in both lists. see if something changed.
1138                    const DisplayDeviceState& state(curr[j]);
1139                    const wp<IBinder>& display(curr.keyAt(j));
1140                    if (state.surface->asBinder() != draw[i].surface->asBinder()) {
1141                        // changing the surface is like destroying and
1142                        // recreating the DisplayDevice, so we just remove it
1143                        // from the drawing state, so that it get re-added
1144                        // below.
1145                        mDisplays.removeItem(display);
1146                        mDrawingState.displays.removeItemsAt(i);
1147                        dc--; i--;
1148                        // at this point we must loop to the next item
1149                        continue;
1150                    }
1151
1152                    const sp<DisplayDevice>& disp(getDisplayDevice(display));
1153                    if (disp != NULL) {
1154                        if (state.layerStack != draw[i].layerStack) {
1155                            disp->setLayerStack(state.layerStack);
1156                        }
1157                        if ((state.orientation != draw[i].orientation)
1158                                || (state.viewport != draw[i].viewport)
1159                                || (state.frame != draw[i].frame))
1160                        {
1161                            disp->setProjection(state.orientation,
1162                                    state.viewport, state.frame);
1163                        }
1164
1165                        // Walk through all the layers in currentLayers,
1166                        // and update their transform hint.
1167                        //
1168                        // TODO: we could be much more clever about which
1169                        // layers we touch and how often we do these updates
1170                        // (e.g. only touch the layers associated with this
1171                        // display, and only on a rotation).
1172                        for (size_t i = 0; i < count; i++) {
1173                            const sp<LayerBase>& layerBase = currentLayers[i];
1174                            layerBase->updateTransformHint();
1175                        }
1176                    }
1177                }
1178            }
1179
1180            // find displays that were added
1181            // (ie: in current state but not in drawing state)
1182            for (size_t i=0 ; i<cc ; i++) {
1183                if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1184                    const DisplayDeviceState& state(curr[i]);
1185
1186                    sp<FramebufferSurface> fbs;
1187                    sp<SurfaceTextureClient> stc;
1188                    if (!state.isVirtualDisplay()) {
1189
1190                        ALOGE_IF(state.surface!=NULL,
1191                                "adding a supported display, but rendering "
1192                                "surface is provided (%p), ignoring it",
1193                                state.surface.get());
1194
1195                        // for supported (by hwc) displays we provide our
1196                        // own rendering surface
1197                        fbs = new FramebufferSurface(*mHwc, state.type);
1198                        stc = new SurfaceTextureClient(
1199                                static_cast< sp<ISurfaceTexture> >(fbs->getBufferQueue()));
1200                    } else {
1201                        if (state.surface != NULL) {
1202                            stc = new SurfaceTextureClient(state.surface);
1203                        }
1204                    }
1205
1206                    const wp<IBinder>& display(curr.keyAt(i));
1207                    if (stc != NULL) {
1208                        sp<DisplayDevice> hw = new DisplayDevice(this,
1209                                state.type, display, stc, fbs, mEGLConfig);
1210                        hw->setLayerStack(state.layerStack);
1211                        hw->setProjection(state.orientation,
1212                                state.viewport, state.frame);
1213                        hw->setDisplayName(state.displayName);
1214                        mDisplays.add(display, hw);
1215                        if (hw->getDisplayType() < DisplayDevice::NUM_DISPLAY_TYPES) {
1216                            // notify the system that this display is now up
1217                            // (note onScreenAcquired() is safe to call from
1218                            // here because we're in the main thread)
1219                            onScreenAcquired(hw);
1220                        }
1221                    }
1222                }
1223            }
1224        }
1225    }
1226
1227    /*
1228     * Perform our own transaction if needed
1229     */
1230
1231    const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
1232    if (currentLayers.size() > previousLayers.size()) {
1233        // layers have been added
1234        mVisibleRegionsDirty = true;
1235    }
1236
1237    // some layers might have been removed, so
1238    // we need to update the regions they're exposing.
1239    if (mLayersRemoved) {
1240        mLayersRemoved = false;
1241        mVisibleRegionsDirty = true;
1242        const size_t count = previousLayers.size();
1243        for (size_t i=0 ; i<count ; i++) {
1244            const sp<LayerBase>& layer(previousLayers[i]);
1245            if (currentLayers.indexOf(layer) < 0) {
1246                // this layer is not visible anymore
1247                // TODO: we could traverse the tree from front to back and
1248                //       compute the actual visible region
1249                // TODO: we could cache the transformed region
1250                const Layer::State& s(layer->drawingState());
1251                Region visibleReg = s.transform.transform(
1252                        Region(Rect(s.active.w, s.active.h)));
1253                invalidateLayerStack(s.layerStack, visibleReg);
1254            }
1255        }
1256    }
1257
1258    commitTransaction();
1259}
1260
1261void SurfaceFlinger::commitTransaction()
1262{
1263    if (!mLayersPendingRemoval.isEmpty()) {
1264        // Notify removed layers now that they can't be drawn from
1265        for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1266            mLayersPendingRemoval[i]->onRemoved();
1267        }
1268        mLayersPendingRemoval.clear();
1269    }
1270
1271    mDrawingState = mCurrentState;
1272    mTransationPending = false;
1273    mTransactionCV.broadcast();
1274}
1275
1276void SurfaceFlinger::computeVisibleRegions(
1277        const LayerVector& currentLayers, uint32_t layerStack,
1278        Region& outDirtyRegion, Region& outOpaqueRegion)
1279{
1280    ATRACE_CALL();
1281
1282    Region aboveOpaqueLayers;
1283    Region aboveCoveredLayers;
1284    Region dirty;
1285
1286    outDirtyRegion.clear();
1287
1288    size_t i = currentLayers.size();
1289    while (i--) {
1290        const sp<LayerBase>& layer = currentLayers[i];
1291
1292        // start with the whole surface at its current location
1293        const Layer::State& s(layer->drawingState());
1294
1295        // only consider the layers on the given later stack
1296        if (s.layerStack != layerStack)
1297            continue;
1298
1299        /*
1300         * opaqueRegion: area of a surface that is fully opaque.
1301         */
1302        Region opaqueRegion;
1303
1304        /*
1305         * visibleRegion: area of a surface that is visible on screen
1306         * and not fully transparent. This is essentially the layer's
1307         * footprint minus the opaque regions above it.
1308         * Areas covered by a translucent surface are considered visible.
1309         */
1310        Region visibleRegion;
1311
1312        /*
1313         * coveredRegion: area of a surface that is covered by all
1314         * visible regions above it (which includes the translucent areas).
1315         */
1316        Region coveredRegion;
1317
1318        /*
1319         * transparentRegion: area of a surface that is hinted to be completely
1320         * transparent. This is only used to tell when the layer has no visible
1321         * non-transparent regions and can be removed from the layer list. It
1322         * does not affect the visibleRegion of this layer or any layers
1323         * beneath it. The hint may not be correct if apps don't respect the
1324         * SurfaceView restrictions (which, sadly, some don't).
1325         */
1326        Region transparentRegion;
1327
1328
1329        // handle hidden surfaces by setting the visible region to empty
1330        if (CC_LIKELY(layer->isVisible())) {
1331            const bool translucent = !layer->isOpaque();
1332            Rect bounds(layer->computeBounds());
1333            visibleRegion.set(bounds);
1334            if (!visibleRegion.isEmpty()) {
1335                // Remove the transparent area from the visible region
1336                if (translucent) {
1337                    const Transform tr(s.transform);
1338                    if (tr.transformed()) {
1339                        if (tr.preserveRects()) {
1340                            // transform the transparent region
1341                            transparentRegion = tr.transform(s.transparentRegion);
1342                        } else {
1343                            // transformation too complex, can't do the
1344                            // transparent region optimization.
1345                            transparentRegion.clear();
1346                        }
1347                    } else {
1348                        transparentRegion = s.transparentRegion;
1349                    }
1350                }
1351
1352                // compute the opaque region
1353                const int32_t layerOrientation = s.transform.getOrientation();
1354                if (s.alpha==255 && !translucent &&
1355                        ((layerOrientation & Transform::ROT_INVALID) == false)) {
1356                    // the opaque region is the layer's footprint
1357                    opaqueRegion = visibleRegion;
1358                }
1359            }
1360        }
1361
1362        // Clip the covered region to the visible region
1363        coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1364
1365        // Update aboveCoveredLayers for next (lower) layer
1366        aboveCoveredLayers.orSelf(visibleRegion);
1367
1368        // subtract the opaque region covered by the layers above us
1369        visibleRegion.subtractSelf(aboveOpaqueLayers);
1370
1371        // compute this layer's dirty region
1372        if (layer->contentDirty) {
1373            // we need to invalidate the whole region
1374            dirty = visibleRegion;
1375            // as well, as the old visible region
1376            dirty.orSelf(layer->visibleRegion);
1377            layer->contentDirty = false;
1378        } else {
1379            /* compute the exposed region:
1380             *   the exposed region consists of two components:
1381             *   1) what's VISIBLE now and was COVERED before
1382             *   2) what's EXPOSED now less what was EXPOSED before
1383             *
1384             * note that (1) is conservative, we start with the whole
1385             * visible region but only keep what used to be covered by
1386             * something -- which mean it may have been exposed.
1387             *
1388             * (2) handles areas that were not covered by anything but got
1389             * exposed because of a resize.
1390             */
1391            const Region newExposed = visibleRegion - coveredRegion;
1392            const Region oldVisibleRegion = layer->visibleRegion;
1393            const Region oldCoveredRegion = layer->coveredRegion;
1394            const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1395            dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1396        }
1397        dirty.subtractSelf(aboveOpaqueLayers);
1398
1399        // accumulate to the screen dirty region
1400        outDirtyRegion.orSelf(dirty);
1401
1402        // Update aboveOpaqueLayers for next (lower) layer
1403        aboveOpaqueLayers.orSelf(opaqueRegion);
1404
1405        // Store the visible region in screen space
1406        layer->setVisibleRegion(visibleRegion);
1407        layer->setCoveredRegion(coveredRegion);
1408        layer->setVisibleNonTransparentRegion(
1409                visibleRegion.subtract(transparentRegion));
1410    }
1411
1412    outOpaqueRegion = aboveOpaqueLayers;
1413}
1414
1415void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1416        const Region& dirty) {
1417    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1418        const sp<DisplayDevice>& hw(mDisplays[dpy]);
1419        if (hw->getLayerStack() == layerStack) {
1420            hw->dirtyRegion.orSelf(dirty);
1421        }
1422    }
1423}
1424
1425void SurfaceFlinger::handlePageFlip()
1426{
1427    Region dirtyRegion;
1428
1429    bool visibleRegions = false;
1430    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
1431    const size_t count = currentLayers.size();
1432    for (size_t i=0 ; i<count ; i++) {
1433        const sp<LayerBase>& layer(currentLayers[i]);
1434        const Region dirty(layer->latchBuffer(visibleRegions));
1435        const Layer::State& s(layer->drawingState());
1436        invalidateLayerStack(s.layerStack, dirty);
1437    }
1438
1439    mVisibleRegionsDirty |= visibleRegions;
1440}
1441
1442void SurfaceFlinger::invalidateHwcGeometry()
1443{
1444    mHwWorkListDirty = true;
1445}
1446
1447
1448void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1449        const Region& inDirtyRegion)
1450{
1451    Region dirtyRegion(inDirtyRegion);
1452
1453    // compute the invalid region
1454    hw->swapRegion.orSelf(dirtyRegion);
1455
1456    uint32_t flags = hw->getFlags();
1457    if (flags & DisplayDevice::SWAP_RECTANGLE) {
1458        // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1459        // takes a rectangle, we must make sure to update that whole
1460        // rectangle in that case
1461        dirtyRegion.set(hw->swapRegion.bounds());
1462    } else {
1463        if (flags & DisplayDevice::PARTIAL_UPDATES) {
1464            // We need to redraw the rectangle that will be updated
1465            // (pushed to the framebuffer).
1466            // This is needed because PARTIAL_UPDATES only takes one
1467            // rectangle instead of a region (see DisplayDevice::flip())
1468            dirtyRegion.set(hw->swapRegion.bounds());
1469        } else {
1470            // we need to redraw everything (the whole screen)
1471            dirtyRegion.set(hw->bounds());
1472            hw->swapRegion = dirtyRegion;
1473        }
1474    }
1475
1476    doComposeSurfaces(hw, dirtyRegion);
1477
1478    // update the swap region and clear the dirty region
1479    hw->swapRegion.orSelf(dirtyRegion);
1480
1481    // swap buffers (presentation)
1482    hw->swapBuffers(getHwComposer());
1483}
1484
1485void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1486{
1487    const int32_t id = hw->getHwcDisplayId();
1488    HWComposer& hwc(getHwComposer());
1489    HWComposer::LayerListIterator cur = hwc.begin(id);
1490    const HWComposer::LayerListIterator end = hwc.end(id);
1491
1492    const bool hasGlesComposition = hwc.hasGlesComposition(id) || (cur==end);
1493    if (hasGlesComposition) {
1494        DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext);
1495
1496        // set the frame buffer
1497        glMatrixMode(GL_MODELVIEW);
1498        glLoadIdentity();
1499
1500        // Never touch the framebuffer if we don't have any framebuffer layers
1501        const bool hasHwcComposition = hwc.hasHwcComposition(id);
1502        if (hasHwcComposition) {
1503            // when using overlays, we assume a fully transparent framebuffer
1504            // NOTE: we could reduce how much we need to clear, for instance
1505            // remove where there are opaque FB layers. however, on some
1506            // GPUs doing a "clean slate" glClear might be more efficient.
1507            // We'll revisit later if needed.
1508            glClearColor(0, 0, 0, 0);
1509            glClear(GL_COLOR_BUFFER_BIT);
1510        } else {
1511            const Region region(hw->undefinedRegion.intersect(dirty));
1512            // screen is already cleared here
1513            if (!region.isEmpty()) {
1514                // can happen with SurfaceView
1515                drawWormhole(hw, region);
1516            }
1517        }
1518    }
1519
1520    /*
1521     * and then, render the layers targeted at the framebuffer
1522     */
1523
1524    const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
1525    const size_t count = layers.size();
1526    const Transform& tr = hw->getTransform();
1527    if (cur != end) {
1528        // we're using h/w composer
1529        for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1530            const sp<LayerBase>& layer(layers[i]);
1531            const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1532            if (!clip.isEmpty()) {
1533                switch (cur->getCompositionType()) {
1534                    case HWC_OVERLAY: {
1535                        if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1536                                && i
1537                                && layer->isOpaque()
1538                                && hasGlesComposition) {
1539                            // never clear the very first layer since we're
1540                            // guaranteed the FB is already cleared
1541                            layer->clearWithOpenGL(hw, clip);
1542                        }
1543                        break;
1544                    }
1545                    case HWC_FRAMEBUFFER: {
1546                        layer->draw(hw, clip);
1547                        break;
1548                    }
1549                    case HWC_FRAMEBUFFER_TARGET: {
1550                        // this should not happen as the iterator shouldn't
1551                        // let us get there.
1552                        ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%d)", i);
1553                        break;
1554                    }
1555                }
1556            }
1557            layer->setAcquireFence(hw, *cur);
1558        }
1559    } else {
1560        // we're not using h/w composer
1561        for (size_t i=0 ; i<count ; ++i) {
1562            const sp<LayerBase>& layer(layers[i]);
1563            const Region clip(dirty.intersect(
1564                    tr.transform(layer->visibleRegion)));
1565            if (!clip.isEmpty()) {
1566                layer->draw(hw, clip);
1567            }
1568        }
1569    }
1570}
1571
1572void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw,
1573        const Region& region) const
1574{
1575    glDisable(GL_TEXTURE_EXTERNAL_OES);
1576    glDisable(GL_TEXTURE_2D);
1577    glDisable(GL_BLEND);
1578    glColor4f(0,0,0,0);
1579
1580    const int32_t height = hw->getHeight();
1581    Region::const_iterator it = region.begin();
1582    Region::const_iterator const end = region.end();
1583    while (it != end) {
1584        const Rect& r = *it++;
1585        GLfloat vertices[][2] = {
1586                { r.left,  height - r.top },
1587                { r.left,  height - r.bottom },
1588                { r.right, height - r.bottom },
1589                { r.right, height - r.top }
1590        };
1591        glVertexPointer(2, GL_FLOAT, 0, vertices);
1592        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1593    }
1594}
1595
1596ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
1597        const sp<LayerBaseClient>& lbc)
1598{
1599    // attach this layer to the client
1600    size_t name = client->attachLayer(lbc);
1601
1602    // add this layer to the current state list
1603    Mutex::Autolock _l(mStateLock);
1604    mCurrentState.layersSortedByZ.add(lbc);
1605
1606    return ssize_t(name);
1607}
1608
1609status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
1610{
1611    Mutex::Autolock _l(mStateLock);
1612    status_t err = purgatorizeLayer_l(layer);
1613    if (err == NO_ERROR)
1614        setTransactionFlags(eTransactionNeeded);
1615    return err;
1616}
1617
1618status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
1619{
1620    ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1621    if (index >= 0) {
1622        mLayersRemoved = true;
1623        return NO_ERROR;
1624    }
1625    return status_t(index);
1626}
1627
1628status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1629{
1630    // First add the layer to the purgatory list, which makes sure it won't
1631    // go away, then remove it from the main list (through a transaction).
1632    ssize_t err = removeLayer_l(layerBase);
1633    if (err >= 0) {
1634        mLayerPurgatory.add(layerBase);
1635    }
1636
1637    mLayersPendingRemoval.push(layerBase);
1638
1639    // it's possible that we don't find a layer, because it might
1640    // have been destroyed already -- this is not technically an error
1641    // from the user because there is a race between Client::destroySurface(),
1642    // ~Client() and ~ISurface().
1643    return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1644}
1645
1646uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags)
1647{
1648    return android_atomic_release_load(&mTransactionFlags);
1649}
1650
1651uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1652{
1653    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1654}
1655
1656uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1657{
1658    uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1659    if ((old & flags)==0) { // wake the server up
1660        signalTransaction();
1661    }
1662    return old;
1663}
1664
1665void SurfaceFlinger::setTransactionState(
1666        const Vector<ComposerState>& state,
1667        const Vector<DisplayState>& displays,
1668        uint32_t flags)
1669{
1670    Mutex::Autolock _l(mStateLock);
1671    uint32_t transactionFlags = 0;
1672
1673    size_t count = displays.size();
1674    for (size_t i=0 ; i<count ; i++) {
1675        const DisplayState& s(displays[i]);
1676        transactionFlags |= setDisplayStateLocked(s);
1677    }
1678
1679    count = state.size();
1680    for (size_t i=0 ; i<count ; i++) {
1681        const ComposerState& s(state[i]);
1682        sp<Client> client( static_cast<Client *>(s.client.get()) );
1683        transactionFlags |= setClientStateLocked(client, s.state);
1684    }
1685
1686    if (transactionFlags) {
1687        // this triggers the transaction
1688        setTransactionFlags(transactionFlags);
1689
1690        // if this is a synchronous transaction, wait for it to take effect
1691        // before returning.
1692        if (flags & eSynchronous) {
1693            mTransationPending = true;
1694        }
1695        while (mTransationPending) {
1696            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1697            if (CC_UNLIKELY(err != NO_ERROR)) {
1698                // just in case something goes wrong in SF, return to the
1699                // called after a few seconds.
1700                ALOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!");
1701                mTransationPending = false;
1702                break;
1703            }
1704        }
1705    }
1706}
1707
1708uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
1709{
1710    uint32_t flags = 0;
1711    DisplayDeviceState& disp(mCurrentState.displays.editValueFor(s.token));
1712    if (disp.isValid()) {
1713        const uint32_t what = s.what;
1714        if (what & DisplayState::eSurfaceChanged) {
1715            if (disp.surface->asBinder() != s.surface->asBinder()) {
1716                disp.surface = s.surface;
1717                flags |= eDisplayTransactionNeeded;
1718            }
1719        }
1720        if (what & DisplayState::eLayerStackChanged) {
1721            if (disp.layerStack != s.layerStack) {
1722                disp.layerStack = s.layerStack;
1723                flags |= eDisplayTransactionNeeded;
1724            }
1725        }
1726        if (what & DisplayState::eDisplayProjectionChanged) {
1727            if (disp.orientation != s.orientation) {
1728                disp.orientation = s.orientation;
1729                flags |= eDisplayTransactionNeeded;
1730            }
1731            if (disp.frame != s.frame) {
1732                disp.frame = s.frame;
1733                flags |= eDisplayTransactionNeeded;
1734            }
1735            if (disp.viewport != s.viewport) {
1736                disp.viewport = s.viewport;
1737                flags |= eDisplayTransactionNeeded;
1738            }
1739        }
1740    }
1741    return flags;
1742}
1743
1744uint32_t SurfaceFlinger::setClientStateLocked(
1745        const sp<Client>& client,
1746        const layer_state_t& s)
1747{
1748    uint32_t flags = 0;
1749    sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
1750    if (layer != 0) {
1751        const uint32_t what = s.what;
1752        if (what & layer_state_t::ePositionChanged) {
1753            if (layer->setPosition(s.x, s.y))
1754                flags |= eTraversalNeeded;
1755        }
1756        if (what & layer_state_t::eLayerChanged) {
1757            // NOTE: index needs to be calculated before we update the state
1758            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1759            if (layer->setLayer(s.z)) {
1760                mCurrentState.layersSortedByZ.removeAt(idx);
1761                mCurrentState.layersSortedByZ.add(layer);
1762                // we need traversal (state changed)
1763                // AND transaction (list changed)
1764                flags |= eTransactionNeeded|eTraversalNeeded;
1765            }
1766        }
1767        if (what & layer_state_t::eSizeChanged) {
1768            if (layer->setSize(s.w, s.h)) {
1769                flags |= eTraversalNeeded;
1770            }
1771        }
1772        if (what & layer_state_t::eAlphaChanged) {
1773            if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1774                flags |= eTraversalNeeded;
1775        }
1776        if (what & layer_state_t::eMatrixChanged) {
1777            if (layer->setMatrix(s.matrix))
1778                flags |= eTraversalNeeded;
1779        }
1780        if (what & layer_state_t::eTransparentRegionChanged) {
1781            if (layer->setTransparentRegionHint(s.transparentRegion))
1782                flags |= eTraversalNeeded;
1783        }
1784        if (what & layer_state_t::eVisibilityChanged) {
1785            if (layer->setFlags(s.flags, s.mask))
1786                flags |= eTraversalNeeded;
1787        }
1788        if (what & layer_state_t::eCropChanged) {
1789            if (layer->setCrop(s.crop))
1790                flags |= eTraversalNeeded;
1791        }
1792        if (what & layer_state_t::eLayerStackChanged) {
1793            // NOTE: index needs to be calculated before we update the state
1794            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1795            if (layer->setLayerStack(s.layerStack)) {
1796                mCurrentState.layersSortedByZ.removeAt(idx);
1797                mCurrentState.layersSortedByZ.add(layer);
1798                // we need traversal (state changed)
1799                // AND transaction (list changed)
1800                flags |= eTransactionNeeded|eTraversalNeeded;
1801            }
1802        }
1803    }
1804    return flags;
1805}
1806
1807sp<ISurface> SurfaceFlinger::createLayer(
1808        ISurfaceComposerClient::surface_data_t* params,
1809        const String8& name,
1810        const sp<Client>& client,
1811       uint32_t w, uint32_t h, PixelFormat format,
1812        uint32_t flags)
1813{
1814    sp<LayerBaseClient> layer;
1815    sp<ISurface> surfaceHandle;
1816
1817    if (int32_t(w|h) < 0) {
1818        ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
1819                int(w), int(h));
1820        return surfaceHandle;
1821    }
1822
1823    //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
1824    switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
1825        case ISurfaceComposerClient::eFXSurfaceNormal:
1826            layer = createNormalLayer(client, w, h, flags, format);
1827            break;
1828        case ISurfaceComposerClient::eFXSurfaceBlur:
1829        case ISurfaceComposerClient::eFXSurfaceDim:
1830            layer = createDimLayer(client, w, h, flags);
1831            break;
1832        case ISurfaceComposerClient::eFXSurfaceScreenshot:
1833            layer = createScreenshotLayer(client, w, h, flags);
1834            break;
1835    }
1836
1837    if (layer != 0) {
1838        layer->initStates(w, h, flags);
1839        layer->setName(name);
1840        ssize_t token = addClientLayer(client, layer);
1841        surfaceHandle = layer->getSurface();
1842        if (surfaceHandle != 0) {
1843            params->token = token;
1844            params->identity = layer->getIdentity();
1845        }
1846        setTransactionFlags(eTransactionNeeded);
1847    }
1848
1849    return surfaceHandle;
1850}
1851
1852sp<Layer> SurfaceFlinger::createNormalLayer(
1853        const sp<Client>& client,
1854        uint32_t w, uint32_t h, uint32_t flags,
1855        PixelFormat& format)
1856{
1857    // initialize the surfaces
1858    switch (format) {
1859    case PIXEL_FORMAT_TRANSPARENT:
1860    case PIXEL_FORMAT_TRANSLUCENT:
1861        format = PIXEL_FORMAT_RGBA_8888;
1862        break;
1863    case PIXEL_FORMAT_OPAQUE:
1864#ifdef NO_RGBX_8888
1865        format = PIXEL_FORMAT_RGB_565;
1866#else
1867        format = PIXEL_FORMAT_RGBX_8888;
1868#endif
1869        break;
1870    }
1871
1872#ifdef NO_RGBX_8888
1873    if (format == PIXEL_FORMAT_RGBX_8888)
1874        format = PIXEL_FORMAT_RGBA_8888;
1875#endif
1876
1877    sp<Layer> layer = new Layer(this, client);
1878    status_t err = layer->setBuffers(w, h, format, flags);
1879    if (CC_LIKELY(err != NO_ERROR)) {
1880        ALOGE("createNormalLayer() failed (%s)", strerror(-err));
1881        layer.clear();
1882    }
1883    return layer;
1884}
1885
1886sp<LayerDim> SurfaceFlinger::createDimLayer(
1887        const sp<Client>& client,
1888        uint32_t w, uint32_t h, uint32_t flags)
1889{
1890    sp<LayerDim> layer = new LayerDim(this, client);
1891    return layer;
1892}
1893
1894sp<LayerScreenshot> SurfaceFlinger::createScreenshotLayer(
1895        const sp<Client>& client,
1896        uint32_t w, uint32_t h, uint32_t flags)
1897{
1898    sp<LayerScreenshot> layer = new LayerScreenshot(this, client);
1899    return layer;
1900}
1901
1902status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, SurfaceID sid)
1903{
1904    /*
1905     * called by the window manager, when a surface should be marked for
1906     * destruction.
1907     *
1908     * The surface is removed from the current and drawing lists, but placed
1909     * in the purgatory queue, so it's not destroyed right-away (we need
1910     * to wait for all client's references to go away first).
1911     */
1912
1913    status_t err = NAME_NOT_FOUND;
1914    Mutex::Autolock _l(mStateLock);
1915    sp<LayerBaseClient> layer = client->getLayerUser(sid);
1916
1917    if (layer != 0) {
1918        err = purgatorizeLayer_l(layer);
1919        if (err == NO_ERROR) {
1920            setTransactionFlags(eTransactionNeeded);
1921        }
1922    }
1923    return err;
1924}
1925
1926status_t SurfaceFlinger::onLayerDestroyed(const wp<LayerBaseClient>& layer)
1927{
1928    // called by ~ISurface() when all references are gone
1929    status_t err = NO_ERROR;
1930    sp<LayerBaseClient> l(layer.promote());
1931    if (l != NULL) {
1932        Mutex::Autolock _l(mStateLock);
1933        err = removeLayer_l(l);
1934        if (err == NAME_NOT_FOUND) {
1935            // The surface wasn't in the current list, which means it was
1936            // removed already, which means it is in the purgatory,
1937            // and need to be removed from there.
1938            ssize_t idx = mLayerPurgatory.remove(l);
1939            ALOGE_IF(idx < 0,
1940                    "layer=%p is not in the purgatory list", l.get());
1941        }
1942        ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
1943                "error removing layer=%p (%s)", l.get(), strerror(-err));
1944    }
1945    return err;
1946}
1947
1948// ---------------------------------------------------------------------------
1949
1950void SurfaceFlinger::onInitializeDisplays() {
1951    // reset screen orientation
1952    Vector<ComposerState> state;
1953    Vector<DisplayState> displays;
1954    DisplayState d;
1955    d.what = DisplayState::eDisplayProjectionChanged;
1956    d.token = mDefaultDisplays[DisplayDevice::DISPLAY_PRIMARY];
1957    d.orientation = DisplayState::eOrientationDefault;
1958    d.frame.makeInvalid();
1959    d.viewport.makeInvalid();
1960    displays.add(d);
1961    setTransactionState(state, displays, 0);
1962    onScreenAcquired(getDefaultDisplayDevice());
1963}
1964
1965void SurfaceFlinger::initializeDisplays() {
1966    class MessageScreenInitialized : public MessageBase {
1967        SurfaceFlinger* flinger;
1968    public:
1969        MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
1970        virtual bool handler() {
1971            flinger->onInitializeDisplays();
1972            return true;
1973        }
1974    };
1975    sp<MessageBase> msg = new MessageScreenInitialized(this);
1976    postMessageAsync(msg);  // we may be called from main thread, use async message
1977}
1978
1979
1980void SurfaceFlinger::onScreenAcquired(const sp<const DisplayDevice>& hw) {
1981    ALOGD("Screen acquired, type=%d flinger=%p", hw->getDisplayType(), this);
1982    if (hw->isScreenAcquired()) {
1983        // this is expected, e.g. when power manager wakes up during boot
1984        ALOGD(" screen was previously acquired");
1985        return;
1986    }
1987
1988    hw->acquireScreen();
1989    int32_t type = hw->getDisplayType();
1990    if (type < DisplayDevice::NUM_DISPLAY_TYPES) {
1991        // built-in display, tell the HWC
1992        getHwComposer().acquire(type);
1993
1994        if (type == DisplayDevice::DISPLAY_PRIMARY) {
1995            // FIXME: eventthread only knows about the main display right now
1996            mEventThread->onScreenAcquired();
1997        }
1998    }
1999    mVisibleRegionsDirty = true;
2000    repaintEverything();
2001}
2002
2003void SurfaceFlinger::onScreenReleased(const sp<const DisplayDevice>& hw) {
2004    ALOGD("Screen released, type=%d flinger=%p", hw->getDisplayType(), this);
2005    if (!hw->isScreenAcquired()) {
2006        ALOGD(" screen was previously released");
2007        return;
2008    }
2009
2010    hw->releaseScreen();
2011    int32_t type = hw->getDisplayType();
2012    if (type < DisplayDevice::NUM_DISPLAY_TYPES) {
2013        if (type == DisplayDevice::DISPLAY_PRIMARY) {
2014            // FIXME: eventthread only knows about the main display right now
2015            mEventThread->onScreenReleased();
2016        }
2017
2018        // built-in display, tell the HWC
2019        getHwComposer().release(type);
2020    }
2021    mVisibleRegionsDirty = true;
2022    // from this point on, SF will stop drawing on this display
2023}
2024
2025void SurfaceFlinger::unblank(const sp<IBinder>& display) {
2026    class MessageScreenAcquired : public MessageBase {
2027        SurfaceFlinger* mFlinger;
2028        const sp<DisplayDevice>& mHw;
2029    public:
2030        MessageScreenAcquired(SurfaceFlinger* flinger,
2031                const sp<DisplayDevice>& hw) : mFlinger(flinger), mHw(hw) { }
2032        virtual bool handler() {
2033            mFlinger->onScreenAcquired(mHw);
2034            return true;
2035        }
2036    };
2037    const sp<DisplayDevice>& hw = getDisplayDevice(display);
2038    if (hw == NULL) {
2039        ALOGE("Attempt to unblank null display %p", display.get());
2040    } else if (hw->getDisplayType() >= DisplayDevice::NUM_DISPLAY_TYPES) {
2041        ALOGW("Attempt to unblank virtual display");
2042    } else {
2043        sp<MessageBase> msg = new MessageScreenAcquired(this, hw);
2044        postMessageSync(msg);
2045    }
2046}
2047
2048void SurfaceFlinger::blank(const sp<IBinder>& display) {
2049    class MessageScreenReleased : public MessageBase {
2050        SurfaceFlinger* mFlinger;
2051        const sp<DisplayDevice>& mHw;
2052    public:
2053        MessageScreenReleased(SurfaceFlinger* flinger,
2054                const sp<DisplayDevice>& hw) : mFlinger(flinger), mHw(hw) { }
2055        virtual bool handler() {
2056            mFlinger->onScreenReleased(mHw);
2057            return true;
2058        }
2059    };
2060    const sp<DisplayDevice>& hw = getDisplayDevice(display);
2061    if (hw == NULL) {
2062        ALOGE("Attempt to blank null display %p", display.get());
2063    } else if (hw->getDisplayType() >= DisplayDevice::NUM_DISPLAY_TYPES) {
2064        ALOGW("Attempt to blank virtual display");
2065    } else {
2066        sp<MessageBase> msg = new MessageScreenReleased(this, hw);
2067        postMessageSync(msg);
2068    }
2069}
2070
2071// ---------------------------------------------------------------------------
2072
2073status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2074{
2075    const size_t SIZE = 4096;
2076    char buffer[SIZE];
2077    String8 result;
2078
2079    if (!PermissionCache::checkCallingPermission(sDump)) {
2080        snprintf(buffer, SIZE, "Permission Denial: "
2081                "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
2082                IPCThreadState::self()->getCallingPid(),
2083                IPCThreadState::self()->getCallingUid());
2084        result.append(buffer);
2085    } else {
2086        // Try to get the main lock, but don't insist if we can't
2087        // (this would indicate SF is stuck, but we want to be able to
2088        // print something in dumpsys).
2089        int retry = 3;
2090        while (mStateLock.tryLock()<0 && --retry>=0) {
2091            usleep(1000000);
2092        }
2093        const bool locked(retry >= 0);
2094        if (!locked) {
2095            snprintf(buffer, SIZE,
2096                    "SurfaceFlinger appears to be unresponsive, "
2097                    "dumping anyways (no locks held)\n");
2098            result.append(buffer);
2099        }
2100
2101        bool dumpAll = true;
2102        size_t index = 0;
2103        size_t numArgs = args.size();
2104        if (numArgs) {
2105            if ((index < numArgs) &&
2106                    (args[index] == String16("--list"))) {
2107                index++;
2108                listLayersLocked(args, index, result, buffer, SIZE);
2109                dumpAll = false;
2110            }
2111
2112            if ((index < numArgs) &&
2113                    (args[index] == String16("--latency"))) {
2114                index++;
2115                dumpStatsLocked(args, index, result, buffer, SIZE);
2116                dumpAll = false;
2117            }
2118
2119            if ((index < numArgs) &&
2120                    (args[index] == String16("--latency-clear"))) {
2121                index++;
2122                clearStatsLocked(args, index, result, buffer, SIZE);
2123                dumpAll = false;
2124            }
2125        }
2126
2127        if (dumpAll) {
2128            dumpAllLocked(result, buffer, SIZE);
2129        }
2130
2131        if (locked) {
2132            mStateLock.unlock();
2133        }
2134    }
2135    write(fd, result.string(), result.size());
2136    return NO_ERROR;
2137}
2138
2139void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
2140        String8& result, char* buffer, size_t SIZE) const
2141{
2142    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2143    const size_t count = currentLayers.size();
2144    for (size_t i=0 ; i<count ; i++) {
2145        const sp<LayerBase>& layer(currentLayers[i]);
2146        snprintf(buffer, SIZE, "%s\n", layer->getName().string());
2147        result.append(buffer);
2148    }
2149}
2150
2151void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2152        String8& result, char* buffer, size_t SIZE) const
2153{
2154    String8 name;
2155    if (index < args.size()) {
2156        name = String8(args[index]);
2157        index++;
2158    }
2159
2160    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2161    const size_t count = currentLayers.size();
2162    for (size_t i=0 ; i<count ; i++) {
2163        const sp<LayerBase>& layer(currentLayers[i]);
2164        if (name.isEmpty()) {
2165            snprintf(buffer, SIZE, "%s\n", layer->getName().string());
2166            result.append(buffer);
2167        }
2168        if (name.isEmpty() || (name == layer->getName())) {
2169            layer->dumpStats(result, buffer, SIZE);
2170        }
2171    }
2172}
2173
2174void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2175        String8& result, char* buffer, size_t SIZE) const
2176{
2177    String8 name;
2178    if (index < args.size()) {
2179        name = String8(args[index]);
2180        index++;
2181    }
2182
2183    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2184    const size_t count = currentLayers.size();
2185    for (size_t i=0 ; i<count ; i++) {
2186        const sp<LayerBase>& layer(currentLayers[i]);
2187        if (name.isEmpty() || (name == layer->getName())) {
2188            layer->clearStats();
2189        }
2190    }
2191}
2192
2193/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2194{
2195    static const char* config =
2196            " [sf"
2197#ifdef NO_RGBX_8888
2198            " NO_RGBX_8888"
2199#endif
2200#ifdef HAS_CONTEXT_PRIORITY
2201            " HAS_CONTEXT_PRIORITY"
2202#endif
2203#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2204            " NEVER_DEFAULT_TO_ASYNC_MODE"
2205#endif
2206#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2207            " TARGET_DISABLE_TRIPLE_BUFFERING"
2208#endif
2209            "]";
2210    result.append(config);
2211}
2212
2213void SurfaceFlinger::dumpAllLocked(
2214        String8& result, char* buffer, size_t SIZE) const
2215{
2216    // figure out if we're stuck somewhere
2217    const nsecs_t now = systemTime();
2218    const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2219    const nsecs_t inTransaction(mDebugInTransaction);
2220    nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2221    nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2222
2223    /*
2224     * Dump library configuration.
2225     */
2226    result.append("Build configuration:");
2227    appendSfConfigString(result);
2228    appendUiConfigString(result);
2229    appendGuiConfigString(result);
2230    result.append("\n");
2231
2232    /*
2233     * Dump the visible layer list
2234     */
2235    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2236    const size_t count = currentLayers.size();
2237    snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count);
2238    result.append(buffer);
2239    for (size_t i=0 ; i<count ; i++) {
2240        const sp<LayerBase>& layer(currentLayers[i]);
2241        layer->dump(result, buffer, SIZE);
2242    }
2243
2244    /*
2245     * Dump the layers in the purgatory
2246     */
2247
2248    const size_t purgatorySize = mLayerPurgatory.size();
2249    snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize);
2250    result.append(buffer);
2251    for (size_t i=0 ; i<purgatorySize ; i++) {
2252        const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
2253        layer->shortDump(result, buffer, SIZE);
2254    }
2255
2256    /*
2257     * Dump Display state
2258     */
2259
2260    snprintf(buffer, SIZE, "Displays (%d entries)\n", mDisplays.size());
2261    result.append(buffer);
2262    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2263        const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2264        hw->dump(result, buffer, SIZE);
2265    }
2266
2267    /*
2268     * Dump SurfaceFlinger global state
2269     */
2270
2271    snprintf(buffer, SIZE, "SurfaceFlinger global state:\n");
2272    result.append(buffer);
2273
2274    HWComposer& hwc(getHwComposer());
2275    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2276    const GLExtensions& extensions(GLExtensions::getInstance());
2277    snprintf(buffer, SIZE, "GLES: %s, %s, %s\n",
2278            extensions.getVendor(),
2279            extensions.getRenderer(),
2280            extensions.getVersion());
2281    result.append(buffer);
2282
2283    snprintf(buffer, SIZE, "EGL : %s\n",
2284            eglQueryString(mEGLDisplay, EGL_VERSION_HW_ANDROID));
2285    result.append(buffer);
2286
2287    snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension());
2288    result.append(buffer);
2289
2290    hw->undefinedRegion.dump(result, "undefinedRegion");
2291    snprintf(buffer, SIZE,
2292            "  orientation=%d, canDraw=%d\n",
2293            hw->getOrientation(), hw->canDraw());
2294    result.append(buffer);
2295    snprintf(buffer, SIZE,
2296            "  last eglSwapBuffers() time: %f us\n"
2297            "  last transaction time     : %f us\n"
2298            "  transaction-flags         : %08x\n"
2299            "  refresh-rate              : %f fps\n"
2300            "  x-dpi                     : %f\n"
2301            "  y-dpi                     : %f\n",
2302            mLastSwapBufferTime/1000.0,
2303            mLastTransactionTime/1000.0,
2304            mTransactionFlags,
2305            1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2306            hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2307            hwc.getDpiY(HWC_DISPLAY_PRIMARY));
2308    result.append(buffer);
2309
2310    snprintf(buffer, SIZE, "  eglSwapBuffers time: %f us\n",
2311            inSwapBuffersDuration/1000.0);
2312    result.append(buffer);
2313
2314    snprintf(buffer, SIZE, "  transaction time: %f us\n",
2315            inTransactionDuration/1000.0);
2316    result.append(buffer);
2317
2318    /*
2319     * VSYNC state
2320     */
2321    mEventThread->dump(result, buffer, SIZE);
2322
2323    /*
2324     * Dump HWComposer state
2325     */
2326    snprintf(buffer, SIZE, "h/w composer state:\n");
2327    result.append(buffer);
2328    snprintf(buffer, SIZE, "  h/w composer %s and %s\n",
2329            hwc.initCheck()==NO_ERROR ? "present" : "not present",
2330                    (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled");
2331    result.append(buffer);
2332    hwc.dump(result, buffer, SIZE, hw->getVisibleLayersSortedByZ());
2333
2334    /*
2335     * Dump gralloc state
2336     */
2337    const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2338    alloc.dump(result);
2339}
2340
2341bool SurfaceFlinger::startDdmConnection()
2342{
2343    void* libddmconnection_dso =
2344            dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2345    if (!libddmconnection_dso) {
2346        return false;
2347    }
2348    void (*DdmConnection_start)(const char* name);
2349    DdmConnection_start =
2350            (typeof DdmConnection_start)dlsym(libddmconnection_dso, "DdmConnection_start");
2351    if (!DdmConnection_start) {
2352        dlclose(libddmconnection_dso);
2353        return false;
2354    }
2355    (*DdmConnection_start)(getServiceName());
2356    return true;
2357}
2358
2359status_t SurfaceFlinger::onTransact(
2360    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2361{
2362    switch (code) {
2363        case CREATE_CONNECTION:
2364        case SET_TRANSACTION_STATE:
2365        case BOOT_FINISHED:
2366        case BLANK:
2367        case UNBLANK:
2368        {
2369            // codes that require permission check
2370            IPCThreadState* ipc = IPCThreadState::self();
2371            const int pid = ipc->getCallingPid();
2372            const int uid = ipc->getCallingUid();
2373            if ((uid != AID_GRAPHICS) &&
2374                    !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2375                ALOGE("Permission Denial: "
2376                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2377                return PERMISSION_DENIED;
2378            }
2379            break;
2380        }
2381        case CAPTURE_SCREEN:
2382        {
2383            // codes that require permission check
2384            IPCThreadState* ipc = IPCThreadState::self();
2385            const int pid = ipc->getCallingPid();
2386            const int uid = ipc->getCallingUid();
2387            if ((uid != AID_GRAPHICS) &&
2388                    !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2389                ALOGE("Permission Denial: "
2390                        "can't read framebuffer pid=%d, uid=%d", pid, uid);
2391                return PERMISSION_DENIED;
2392            }
2393            break;
2394        }
2395    }
2396
2397    status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2398    if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2399        CHECK_INTERFACE(ISurfaceComposer, data, reply);
2400        if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2401            IPCThreadState* ipc = IPCThreadState::self();
2402            const int pid = ipc->getCallingPid();
2403            const int uid = ipc->getCallingUid();
2404            ALOGE("Permission Denial: "
2405                    "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2406            return PERMISSION_DENIED;
2407        }
2408        int n;
2409        switch (code) {
2410            case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2411            case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2412                return NO_ERROR;
2413            case 1002:  // SHOW_UPDATES
2414                n = data.readInt32();
2415                mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2416                invalidateHwcGeometry();
2417                repaintEverything();
2418                return NO_ERROR;
2419            case 1004:{ // repaint everything
2420                repaintEverything();
2421                return NO_ERROR;
2422            }
2423            case 1005:{ // force transaction
2424                setTransactionFlags(
2425                        eTransactionNeeded|
2426                        eDisplayTransactionNeeded|
2427                        eTraversalNeeded);
2428                return NO_ERROR;
2429            }
2430            case 1006:{ // send empty update
2431                signalRefresh();
2432                return NO_ERROR;
2433            }
2434            case 1008:  // toggle use of hw composer
2435                n = data.readInt32();
2436                mDebugDisableHWC = n ? 1 : 0;
2437                invalidateHwcGeometry();
2438                repaintEverything();
2439                return NO_ERROR;
2440            case 1009:  // toggle use of transform hint
2441                n = data.readInt32();
2442                mDebugDisableTransformHint = n ? 1 : 0;
2443                invalidateHwcGeometry();
2444                repaintEverything();
2445                return NO_ERROR;
2446            case 1010:  // interrogate.
2447                reply->writeInt32(0);
2448                reply->writeInt32(0);
2449                reply->writeInt32(mDebugRegion);
2450                reply->writeInt32(0);
2451                reply->writeInt32(mDebugDisableHWC);
2452                return NO_ERROR;
2453            case 1013: {
2454                Mutex::Autolock _l(mStateLock);
2455                sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2456                reply->writeInt32(hw->getPageFlipCount());
2457            }
2458            return NO_ERROR;
2459        }
2460    }
2461    return err;
2462}
2463
2464void SurfaceFlinger::repaintEverything() {
2465    android_atomic_or(1, &mRepaintEverything);
2466    signalTransaction();
2467}
2468
2469// ---------------------------------------------------------------------------
2470
2471status_t SurfaceFlinger::renderScreenToTexture(uint32_t layerStack,
2472        GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2473{
2474    Mutex::Autolock _l(mStateLock);
2475    return renderScreenToTextureLocked(layerStack, textureName, uOut, vOut);
2476}
2477
2478status_t SurfaceFlinger::renderScreenToTextureLocked(uint32_t layerStack,
2479        GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2480{
2481    ATRACE_CALL();
2482
2483    if (!GLExtensions::getInstance().haveFramebufferObject())
2484        return INVALID_OPERATION;
2485
2486    // get screen geometry
2487    // FIXME: figure out what it means to have a screenshot texture w/ multi-display
2488    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2489    const uint32_t hw_w = hw->getWidth();
2490    const uint32_t hw_h = hw->getHeight();
2491    GLfloat u = 1;
2492    GLfloat v = 1;
2493
2494    // make sure to clear all GL error flags
2495    while ( glGetError() != GL_NO_ERROR ) ;
2496
2497    // create a FBO
2498    GLuint name, tname;
2499    glGenTextures(1, &tname);
2500    glBindTexture(GL_TEXTURE_2D, tname);
2501    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2502    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2503    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2504            hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2505    if (glGetError() != GL_NO_ERROR) {
2506        while ( glGetError() != GL_NO_ERROR ) ;
2507        GLint tw = (2 << (31 - clz(hw_w)));
2508        GLint th = (2 << (31 - clz(hw_h)));
2509        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2510                tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2511        u = GLfloat(hw_w) / tw;
2512        v = GLfloat(hw_h) / th;
2513    }
2514    glGenFramebuffersOES(1, &name);
2515    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2516    glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES,
2517            GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0);
2518
2519    DisplayDevice::setViewportAndProjection(hw);
2520
2521    // redraw the screen entirely...
2522    glDisable(GL_TEXTURE_EXTERNAL_OES);
2523    glDisable(GL_TEXTURE_2D);
2524    glClearColor(0,0,0,1);
2525    glClear(GL_COLOR_BUFFER_BIT);
2526    glMatrixMode(GL_MODELVIEW);
2527    glLoadIdentity();
2528    const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
2529    const size_t count = layers.size();
2530    for (size_t i=0 ; i<count ; ++i) {
2531        const sp<LayerBase>& layer(layers[i]);
2532        layer->draw(hw);
2533    }
2534
2535    hw->compositionComplete();
2536
2537    // back to main framebuffer
2538    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2539    glDeleteFramebuffersOES(1, &name);
2540
2541    *textureName = tname;
2542    *uOut = u;
2543    *vOut = v;
2544    return NO_ERROR;
2545}
2546
2547// ---------------------------------------------------------------------------
2548
2549status_t SurfaceFlinger::captureScreenImplLocked(const sp<IBinder>& display,
2550        sp<IMemoryHeap>* heap,
2551        uint32_t* w, uint32_t* h, PixelFormat* f,
2552        uint32_t sw, uint32_t sh,
2553        uint32_t minLayerZ, uint32_t maxLayerZ)
2554{
2555    ATRACE_CALL();
2556
2557    status_t result = PERMISSION_DENIED;
2558
2559    if (!GLExtensions::getInstance().haveFramebufferObject()) {
2560        return INVALID_OPERATION;
2561    }
2562
2563    // get screen geometry
2564    sp<const DisplayDevice> hw(getDisplayDevice(display));
2565    const uint32_t hw_w = hw->getWidth();
2566    const uint32_t hw_h = hw->getHeight();
2567
2568    // if we have secure windows on this display, never allow the screen capture
2569    if (hw->getSecureLayerVisible()) {
2570        ALOGW("FB is protected: PERMISSION_DENIED");
2571        return PERMISSION_DENIED;
2572    }
2573
2574    if ((sw > hw_w) || (sh > hw_h)) {
2575        ALOGE("size mismatch (%d, %d) > (%d, %d)", sw, sh, hw_w, hw_h);
2576        return BAD_VALUE;
2577    }
2578
2579    sw = (!sw) ? hw_w : sw;
2580    sh = (!sh) ? hw_h : sh;
2581    const size_t size = sw * sh * 4;
2582    const bool filtering = sw != hw_w || sh != hw_h;
2583
2584//    ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d",
2585//            sw, sh, minLayerZ, maxLayerZ);
2586
2587    // make sure to clear all GL error flags
2588    while ( glGetError() != GL_NO_ERROR ) ;
2589
2590    // create a FBO
2591    GLuint name, tname;
2592    glGenRenderbuffersOES(1, &tname);
2593    glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname);
2594    glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh);
2595
2596    glGenFramebuffersOES(1, &name);
2597    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2598    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
2599            GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname);
2600
2601    GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
2602
2603    if (status == GL_FRAMEBUFFER_COMPLETE_OES) {
2604
2605        // invert everything, b/c glReadPixel() below will invert the FB
2606        GLint  viewport[4];
2607        glGetIntegerv(GL_VIEWPORT, viewport);
2608        glViewport(0, 0, sw, sh);
2609        glMatrixMode(GL_PROJECTION);
2610        glPushMatrix();
2611        glLoadIdentity();
2612        glOrthof(0, hw_w, hw_h, 0, 0, 1);
2613        glMatrixMode(GL_MODELVIEW);
2614
2615        // redraw the screen entirely...
2616        glClearColor(0,0,0,1);
2617        glClear(GL_COLOR_BUFFER_BIT);
2618
2619        const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
2620        const size_t count = layers.size();
2621        for (size_t i=0 ; i<count ; ++i) {
2622            const sp<LayerBase>& layer(layers[i]);
2623            const uint32_t z = layer->drawingState().z;
2624            if (z >= minLayerZ && z <= maxLayerZ) {
2625                if (filtering) layer->setFiltering(true);
2626                layer->draw(hw);
2627                if (filtering) layer->setFiltering(false);
2628            }
2629        }
2630
2631        // check for errors and return screen capture
2632        if (glGetError() != GL_NO_ERROR) {
2633            // error while rendering
2634            result = INVALID_OPERATION;
2635        } else {
2636            // allocate shared memory large enough to hold the
2637            // screen capture
2638            sp<MemoryHeapBase> base(
2639                    new MemoryHeapBase(size, 0, "screen-capture") );
2640            void* const ptr = base->getBase();
2641            if (ptr != MAP_FAILED) {
2642                // capture the screen with glReadPixels()
2643                ScopedTrace _t(ATRACE_TAG, "glReadPixels");
2644                glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
2645                if (glGetError() == GL_NO_ERROR) {
2646                    *heap = base;
2647                    *w = sw;
2648                    *h = sh;
2649                    *f = PIXEL_FORMAT_RGBA_8888;
2650                    result = NO_ERROR;
2651                }
2652            } else {
2653                result = NO_MEMORY;
2654            }
2655        }
2656        glViewport(viewport[0], viewport[1], viewport[2], viewport[3]);
2657        glMatrixMode(GL_PROJECTION);
2658        glPopMatrix();
2659        glMatrixMode(GL_MODELVIEW);
2660    } else {
2661        result = BAD_VALUE;
2662    }
2663
2664    // release FBO resources
2665    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2666    glDeleteRenderbuffersOES(1, &tname);
2667    glDeleteFramebuffersOES(1, &name);
2668
2669    hw->compositionComplete();
2670
2671//    ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK");
2672
2673    return result;
2674}
2675
2676
2677status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
2678        sp<IMemoryHeap>* heap,
2679        uint32_t* width, uint32_t* height, PixelFormat* format,
2680        uint32_t sw, uint32_t sh,
2681        uint32_t minLayerZ, uint32_t maxLayerZ)
2682{
2683    if (CC_UNLIKELY(display == 0))
2684        return BAD_VALUE;
2685
2686    if (!GLExtensions::getInstance().haveFramebufferObject())
2687        return INVALID_OPERATION;
2688
2689    class MessageCaptureScreen : public MessageBase {
2690        SurfaceFlinger* flinger;
2691        sp<IBinder> display;
2692        sp<IMemoryHeap>* heap;
2693        uint32_t* w;
2694        uint32_t* h;
2695        PixelFormat* f;
2696        uint32_t sw;
2697        uint32_t sh;
2698        uint32_t minLayerZ;
2699        uint32_t maxLayerZ;
2700        status_t result;
2701    public:
2702        MessageCaptureScreen(SurfaceFlinger* flinger, const sp<IBinder>& display,
2703                sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f,
2704                uint32_t sw, uint32_t sh,
2705                uint32_t minLayerZ, uint32_t maxLayerZ)
2706            : flinger(flinger), display(display),
2707              heap(heap), w(w), h(h), f(f), sw(sw), sh(sh),
2708              minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2709              result(PERMISSION_DENIED)
2710        {
2711        }
2712        status_t getResult() const {
2713            return result;
2714        }
2715        virtual bool handler() {
2716            Mutex::Autolock _l(flinger->mStateLock);
2717            result = flinger->captureScreenImplLocked(display,
2718                    heap, w, h, f, sw, sh, minLayerZ, maxLayerZ);
2719            return true;
2720        }
2721    };
2722
2723    sp<MessageBase> msg = new MessageCaptureScreen(this,
2724            display, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ);
2725    status_t res = postMessageSync(msg);
2726    if (res == NO_ERROR) {
2727        res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult();
2728    }
2729    return res;
2730}
2731
2732// ---------------------------------------------------------------------------
2733
2734SurfaceFlinger::LayerVector::LayerVector() {
2735}
2736
2737SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
2738    : SortedVector<sp<LayerBase> >(rhs) {
2739}
2740
2741int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
2742    const void* rhs) const
2743{
2744    // sort layers per layer-stack, then by z-order and finally by sequence
2745    const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs));
2746    const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs));
2747
2748    uint32_t ls = l->currentState().layerStack;
2749    uint32_t rs = r->currentState().layerStack;
2750    if (ls != rs)
2751        return ls - rs;
2752
2753    uint32_t lz = l->currentState().z;
2754    uint32_t rz = r->currentState().z;
2755    if (lz != rz)
2756        return lz - rz;
2757
2758    return l->sequence - r->sequence;
2759}
2760
2761// ---------------------------------------------------------------------------
2762
2763SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
2764    : type(DisplayDevice::DISPLAY_ID_INVALID) {
2765}
2766
2767SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
2768    : type(type), layerStack(0), orientation(0) {
2769    viewport.makeInvalid();
2770    frame.makeInvalid();
2771}
2772
2773// ---------------------------------------------------------------------------
2774
2775}; // namespace android
2776