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