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