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