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