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