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