SurfaceFlinger.cpp revision 13233e067b8f71adc3a0ade5f442265e1f27084b
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
24#include <EGL/egl.h>
25#include <GLES/gl.h>
26
27#include <cutils/log.h>
28#include <cutils/properties.h>
29
30#include <binder/IPCThreadState.h>
31#include <binder/IServiceManager.h>
32#include <binder/MemoryHeapBase.h>
33#include <binder/PermissionCache.h>
34
35#include <ui/DisplayInfo.h>
36
37#include <gui/BitTube.h>
38#include <gui/BufferQueue.h>
39#include <gui/IDisplayEventConnection.h>
40#include <gui/SurfaceTextureClient.h>
41
42#include <ui/GraphicBufferAllocator.h>
43#include <ui/PixelFormat.h>
44
45#include <utils/String8.h>
46#include <utils/String16.h>
47#include <utils/StopWatch.h>
48#include <utils/Trace.h>
49
50#include <private/android_filesystem_config.h>
51
52#include "clz.h"
53#include "DdmConnection.h"
54#include "DisplayDevice.h"
55#include "Client.h"
56#include "EventThread.h"
57#include "GLExtensions.h"
58#include "Layer.h"
59#include "LayerDim.h"
60#include "LayerScreenshot.h"
61#include "SurfaceFlinger.h"
62
63#include "DisplayHardware/FramebufferSurface.h"
64#include "DisplayHardware/HWComposer.h"
65
66
67#define EGL_VERSION_HW_ANDROID  0x3143
68
69#define DISPLAY_COUNT       1
70
71namespace android {
72// ---------------------------------------------------------------------------
73
74const String16 sHardwareTest("android.permission.HARDWARE_TEST");
75const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
76const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
77const String16 sDump("android.permission.DUMP");
78
79// ---------------------------------------------------------------------------
80
81SurfaceFlinger::SurfaceFlinger()
82    :   BnSurfaceComposer(), Thread(false),
83        mTransactionFlags(0),
84        mTransationPending(false),
85        mLayersRemoved(false),
86        mRepaintEverything(0),
87        mBootTime(systemTime()),
88        mVisibleRegionsDirty(false),
89        mHwWorkListDirty(false),
90        mDebugRegion(0),
91        mDebugDDMS(0),
92        mDebugDisableHWC(0),
93        mDebugDisableTransformHint(0),
94        mDebugInSwapBuffers(0),
95        mLastSwapBufferTime(0),
96        mDebugInTransaction(0),
97        mLastTransactionTime(0),
98        mBootFinished(false),
99        mExternalDisplaySurface(EGL_NO_SURFACE)
100{
101    ALOGI("SurfaceFlinger is starting");
102
103    // debugging stuff...
104    char value[PROPERTY_VALUE_MAX];
105
106    property_get("debug.sf.showupdates", value, "0");
107    mDebugRegion = atoi(value);
108
109    property_get("debug.sf.ddms", value, "0");
110    mDebugDDMS = atoi(value);
111    if (mDebugDDMS) {
112        DdmConnection::start(getServiceName());
113    }
114
115    ALOGI_IF(mDebugRegion, "showupdates enabled");
116    ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
117}
118
119void SurfaceFlinger::onFirstRef()
120{
121    mEventQueue.init(this);
122
123    run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
124
125    // Wait for the main thread to be done with its initialization
126    mReadyToRunBarrier.wait();
127}
128
129
130SurfaceFlinger::~SurfaceFlinger()
131{
132    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
133    eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
134    eglTerminate(display);
135}
136
137void SurfaceFlinger::binderDied(const wp<IBinder>& who)
138{
139    // the window manager died on us. prepare its eulogy.
140
141    // reset screen orientation
142    Vector<ComposerState> state;
143    Vector<DisplayState> displays;
144    DisplayState d;
145    d.what = DisplayState::eTransformChanged;
146    d.token = mDefaultDisplays[DisplayDevice::DISPLAY_ID_MAIN];
147    d.orientation = DisplayState::eOrientationDefault;
148    displays.add(d);
149    setTransactionState(state, displays, 0);
150
151    // restart the boot-animation
152    startBootAnim();
153}
154
155sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
156{
157    sp<ISurfaceComposerClient> bclient;
158    sp<Client> client(new Client(this));
159    status_t err = client->initCheck();
160    if (err == NO_ERROR) {
161        bclient = client;
162    }
163    return bclient;
164}
165
166sp<IBinder> SurfaceFlinger::createDisplay()
167{
168    class DisplayToken : public BBinder {
169        sp<SurfaceFlinger> flinger;
170        virtual ~DisplayToken() {
171             // no more references, this display must be terminated
172             Mutex::Autolock _l(flinger->mStateLock);
173             flinger->mCurrentState.displays.removeItem(this);
174             flinger->setTransactionFlags(eDisplayTransactionNeeded);
175         }
176     public:
177        DisplayToken(const sp<SurfaceFlinger>& flinger)
178            : flinger(flinger) {
179        }
180    };
181
182    sp<BBinder> token = new DisplayToken(this);
183
184    Mutex::Autolock _l(mStateLock);
185    DisplayDeviceState info(intptr_t(token.get())); // FIXME: we shouldn't use the address for the id
186    mCurrentState.displays.add(token, info);
187
188    return token;
189}
190
191sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
192    if (uint32_t(id) >= DisplayDevice::DISPLAY_ID_COUNT) {
193        ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
194        return NULL;
195    }
196    return mDefaultDisplays[id];
197}
198
199sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
200{
201    sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
202    return gba;
203}
204
205void SurfaceFlinger::bootFinished()
206{
207    const nsecs_t now = systemTime();
208    const nsecs_t duration = now - mBootTime;
209    ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
210    mBootFinished = true;
211
212    // wait patiently for the window manager death
213    const String16 name("window");
214    sp<IBinder> window(defaultServiceManager()->getService(name));
215    if (window != 0) {
216        window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
217    }
218
219    // stop boot animation
220    // formerly we would just kill the process, but we now ask it to exit so it
221    // can choose where to stop the animation.
222    property_set("service.bootanim.exit", "1");
223}
224
225void SurfaceFlinger::deleteTextureAsync(GLuint texture) {
226    class MessageDestroyGLTexture : public MessageBase {
227        GLuint texture;
228    public:
229        MessageDestroyGLTexture(GLuint texture)
230            : texture(texture) {
231        }
232        virtual bool handler() {
233            glDeleteTextures(1, &texture);
234            return true;
235        }
236    };
237    postMessageAsync(new MessageDestroyGLTexture(texture));
238}
239
240status_t SurfaceFlinger::selectConfigForPixelFormat(
241        EGLDisplay dpy,
242        EGLint const* attrs,
243        PixelFormat format,
244        EGLConfig* outConfig)
245{
246    EGLConfig config = NULL;
247    EGLint numConfigs = -1, n=0;
248    eglGetConfigs(dpy, NULL, 0, &numConfigs);
249    EGLConfig* const configs = new EGLConfig[numConfigs];
250    eglChooseConfig(dpy, attrs, configs, numConfigs, &n);
251    for (int i=0 ; i<n ; i++) {
252        EGLint nativeVisualId = 0;
253        eglGetConfigAttrib(dpy, configs[i], EGL_NATIVE_VISUAL_ID, &nativeVisualId);
254        if (nativeVisualId>0 && format == nativeVisualId) {
255            *outConfig = configs[i];
256            delete [] configs;
257            return NO_ERROR;
258        }
259    }
260    delete [] configs;
261    return NAME_NOT_FOUND;
262}
263
264EGLConfig SurfaceFlinger::selectEGLConfig(EGLDisplay display, EGLint nativeVisualId) {
265    // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
266    // it is to be used with WIFI displays
267    EGLConfig config;
268    EGLint dummy;
269    status_t err;
270    EGLint attribs[] = {
271            EGL_SURFACE_TYPE,           EGL_WINDOW_BIT,
272            EGL_RECORDABLE_ANDROID,     EGL_TRUE,
273            EGL_NONE
274    };
275    err = selectConfigForPixelFormat(display, attribs, nativeVisualId, &config);
276    if (err) {
277        // maybe we failed because of EGL_RECORDABLE_ANDROID
278        ALOGW("couldn't find an EGLConfig with EGL_RECORDABLE_ANDROID");
279        attribs[2] = EGL_NONE;
280        err = selectConfigForPixelFormat(display, attribs, nativeVisualId, &config);
281    }
282    ALOGE_IF(err, "couldn't find an EGLConfig matching the screen format");
283    if (eglGetConfigAttrib(display, config, EGL_CONFIG_CAVEAT, &dummy) == EGL_TRUE) {
284        ALOGW_IF(dummy == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
285    }
286    return config;
287}
288
289EGLContext SurfaceFlinger::createGLContext(EGLDisplay display, EGLConfig config) {
290    // Also create our EGLContext
291    EGLint contextAttributes[] = {
292#ifdef EGL_IMG_context_priority
293#ifdef HAS_CONTEXT_PRIORITY
294#warning "using EGL_IMG_context_priority"
295            EGL_CONTEXT_PRIORITY_LEVEL_IMG, EGL_CONTEXT_PRIORITY_HIGH_IMG,
296#endif
297#endif
298            EGL_NONE, EGL_NONE
299    };
300    EGLContext ctxt = eglCreateContext(display, config, NULL, contextAttributes);
301    ALOGE_IF(ctxt==EGL_NO_CONTEXT, "EGLContext creation failed");
302    return ctxt;
303}
304
305void SurfaceFlinger::initializeGL(EGLDisplay display, EGLSurface surface) {
306    EGLBoolean result = eglMakeCurrent(display, surface, surface, mEGLContext);
307    if (!result) {
308        ALOGE("Couldn't create a working GLES context. check logs. exiting...");
309        exit(0);
310    }
311
312    GLExtensions& extensions(GLExtensions::getInstance());
313    extensions.initWithGLStrings(
314            glGetString(GL_VENDOR),
315            glGetString(GL_RENDERER),
316            glGetString(GL_VERSION),
317            glGetString(GL_EXTENSIONS),
318            eglQueryString(display, EGL_VENDOR),
319            eglQueryString(display, EGL_VERSION),
320            eglQueryString(display, EGL_EXTENSIONS));
321
322    EGLint w, h;
323    eglQuerySurface(display, surface, EGL_WIDTH,  &w);
324    eglQuerySurface(display, surface, EGL_HEIGHT, &h);
325
326    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
327    glGetIntegerv(GL_MAX_VIEWPORT_DIMS, mMaxViewportDims);
328
329    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
330    glPixelStorei(GL_PACK_ALIGNMENT, 4);
331    glEnableClientState(GL_VERTEX_ARRAY);
332    glShadeModel(GL_FLAT);
333    glDisable(GL_DITHER);
334    glDisable(GL_CULL_FACE);
335
336    struct pack565 {
337        inline uint16_t operator() (int r, int g, int b) const {
338            return (r<<11)|(g<<5)|b;
339        }
340    } pack565;
341
342    const uint16_t protTexData[] = { pack565(0x03, 0x03, 0x03) };
343    glGenTextures(1, &mProtectedTexName);
344    glBindTexture(GL_TEXTURE_2D, mProtectedTexName);
345    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
346    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
347    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
348    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
349    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0,
350            GL_RGB, GL_UNSIGNED_SHORT_5_6_5, protTexData);
351
352    glViewport(0, 0, w, h);
353    glMatrixMode(GL_PROJECTION);
354    glLoadIdentity();
355    // put the origin in the left-bottom corner
356    glOrthof(0, w, 0, h, 0, 1); // l=0, r=w ; b=0, t=h
357
358    // print some debugging info
359    EGLint r,g,b,a;
360    eglGetConfigAttrib(display, mEGLConfig, EGL_RED_SIZE,   &r);
361    eglGetConfigAttrib(display, mEGLConfig, EGL_GREEN_SIZE, &g);
362    eglGetConfigAttrib(display, mEGLConfig, EGL_BLUE_SIZE,  &b);
363    eglGetConfigAttrib(display, mEGLConfig, EGL_ALPHA_SIZE, &a);
364    ALOGI("EGL informations:");
365    ALOGI("vendor    : %s", extensions.getEglVendor());
366    ALOGI("version   : %s", extensions.getEglVersion());
367    ALOGI("extensions: %s", extensions.getEglExtension());
368    ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS)?:"Not Supported");
369    ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, mEGLConfig);
370    ALOGI("OpenGL ES informations:");
371    ALOGI("vendor    : %s", extensions.getVendor());
372    ALOGI("renderer  : %s", extensions.getRenderer());
373    ALOGI("version   : %s", extensions.getVersion());
374    ALOGI("extensions: %s", extensions.getExtension());
375    ALOGI("GL_MAX_TEXTURE_SIZE = %d", mMaxTextureSize);
376    ALOGI("GL_MAX_VIEWPORT_DIMS = %d x %d", mMaxViewportDims[0], mMaxViewportDims[1]);
377}
378
379status_t SurfaceFlinger::readyToRun()
380{
381    ALOGI(  "SurfaceFlinger's main thread ready to run. "
382            "Initializing graphics H/W...");
383
384    // initialize EGL
385    mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
386    eglInitialize(mEGLDisplay, NULL, NULL);
387
388    // Initialize the main display
389    // create native window to main display
390    sp<FramebufferSurface> fbs = FramebufferSurface::create();
391    if (fbs == NULL) {
392        ALOGE("Display subsystem failed to initialize. check logs. exiting...");
393        exit(0);
394    }
395
396    sp<SurfaceTextureClient> stc(new SurfaceTextureClient(
397            static_cast<sp<ISurfaceTexture> >(fbs->getBufferQueue())));
398
399    // initialize the config and context
400    int format;
401    ANativeWindow* const anw = stc.get();
402    anw->query(anw, NATIVE_WINDOW_FORMAT, &format);
403    mEGLConfig  = selectEGLConfig(mEGLDisplay, format);
404    mEGLContext = createGLContext(mEGLDisplay, mEGLConfig);
405
406    // initialize our main display hardware
407
408    for (size_t i=0 ; i<DisplayDevice::DISPLAY_ID_COUNT ; i++) {
409        mDefaultDisplays[i] = new BBinder();
410        mCurrentState.displays.add(mDefaultDisplays[i], DisplayDeviceState(i));
411    }
412    sp<DisplayDevice> hw = new DisplayDevice(this,
413            DisplayDevice::DISPLAY_ID_MAIN, anw, fbs, mEGLConfig);
414    mDisplays.add(hw->getDisplayId(), hw);
415
416    //  initialize OpenGL ES
417    EGLSurface surface = hw->getEGLSurface();
418    initializeGL(mEGLDisplay, surface);
419
420    // start the EventThread
421    mEventThread = new EventThread(this);
422    mEventQueue.setEventThread(mEventThread);
423
424    // initialize the H/W composer
425    mHwc = new HWComposer(this,
426            *static_cast<HWComposer::EventHandler *>(this),
427            fbs->getFbHal());
428
429    // initialize our drawing state
430    mDrawingState = mCurrentState;
431
432    // We're now ready to accept clients...
433    mReadyToRunBarrier.open();
434
435    // start boot animation
436    startBootAnim();
437
438    return NO_ERROR;
439}
440
441void SurfaceFlinger::startBootAnim() {
442    // start boot animation
443    property_set("service.bootanim.exit", "0");
444    property_set("ctl.start", "bootanim");
445}
446
447uint32_t SurfaceFlinger::getMaxTextureSize() const {
448    return mMaxTextureSize;
449}
450
451uint32_t SurfaceFlinger::getMaxViewportDims() const {
452    return mMaxViewportDims[0] < mMaxViewportDims[1] ?
453            mMaxViewportDims[0] : mMaxViewportDims[1];
454}
455
456// ----------------------------------------------------------------------------
457
458bool SurfaceFlinger::authenticateSurfaceTexture(
459        const sp<ISurfaceTexture>& surfaceTexture) const {
460    Mutex::Autolock _l(mStateLock);
461    sp<IBinder> surfaceTextureBinder(surfaceTexture->asBinder());
462
463    // Check the visible layer list for the ISurface
464    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
465    size_t count = currentLayers.size();
466    for (size_t i=0 ; i<count ; i++) {
467        const sp<LayerBase>& layer(currentLayers[i]);
468        sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
469        if (lbc != NULL) {
470            wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
471            if (lbcBinder == surfaceTextureBinder) {
472                return true;
473            }
474        }
475    }
476
477    // Check the layers in the purgatory.  This check is here so that if a
478    // SurfaceTexture gets destroyed before all the clients are done using it,
479    // the error will not be reported as "surface XYZ is not authenticated", but
480    // will instead fail later on when the client tries to use the surface,
481    // which should be reported as "surface XYZ returned an -ENODEV".  The
482    // purgatorized layers are no less authentic than the visible ones, so this
483    // should not cause any harm.
484    size_t purgatorySize =  mLayerPurgatory.size();
485    for (size_t i=0 ; i<purgatorySize ; i++) {
486        const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
487        sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
488        if (lbc != NULL) {
489            wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
490            if (lbcBinder == surfaceTextureBinder) {
491                return true;
492            }
493        }
494    }
495
496    return false;
497}
498
499status_t SurfaceFlinger::getDisplayInfo(DisplayID dpy, DisplayInfo* info) {
500    // TODO: this is here only for compatibility -- should go away eventually.
501    if (uint32_t(dpy) >= 1) {
502        return BAD_INDEX;
503    }
504
505    const HWComposer& hwc(getHwComposer());
506    float xdpi = hwc.getDpiX();
507    float ydpi = hwc.getDpiY();
508
509    // TODO: Not sure if display density should handled by SF any longer
510    class Density {
511        static int getDensityFromProperty(char const* propName) {
512            char property[PROPERTY_VALUE_MAX];
513            int density = 0;
514            if (property_get(propName, property, NULL) > 0) {
515                density = atoi(property);
516            }
517            return density;
518        }
519    public:
520        static int getEmuDensity() {
521            return getDensityFromProperty("qemu.sf.lcd_density"); }
522        static int getBuildDensity()  {
523            return getDensityFromProperty("ro.sf.lcd_density"); }
524    };
525    // The density of the device is provided by a build property
526    float density = Density::getBuildDensity() / 160.0f;
527    if (density == 0) {
528        // the build doesn't provide a density -- this is wrong!
529        // use xdpi instead
530        ALOGE("ro.sf.lcd_density must be defined as a build property");
531        density = xdpi / 160.0f;
532    }
533    if (Density::getEmuDensity()) {
534        // if "qemu.sf.lcd_density" is specified, it overrides everything
535        xdpi = ydpi = density = Density::getEmuDensity();
536        density /= 160.0f;
537    }
538
539    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
540    info->w = hw->getWidth();
541    info->h = hw->getHeight();
542    info->xdpi = xdpi;
543    info->ydpi = ydpi;
544    info->fps = float(1e9 / hwc.getRefreshPeriod());
545    info->density = density;
546    info->orientation = hw->getOrientation();
547    // TODO: this needs to go away (currently needed only by webkit)
548    getPixelFormatInfo(hw->getFormat(), &info->pixelFormatInfo);
549    return NO_ERROR;
550}
551
552// ----------------------------------------------------------------------------
553
554sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
555    return mEventThread->createEventConnection();
556}
557
558void SurfaceFlinger::connectDisplay(const sp<ISurfaceTexture> display) {
559    EGLSurface result = EGL_NO_SURFACE;
560    EGLSurface old_surface = EGL_NO_SURFACE;
561    sp<SurfaceTextureClient> stc;
562
563    if (display != NULL) {
564        stc = new SurfaceTextureClient(display);
565        result = eglCreateWindowSurface(mEGLDisplay,
566                mEGLConfig, (EGLNativeWindowType)stc.get(), NULL);
567        ALOGE_IF(result == EGL_NO_SURFACE,
568                "eglCreateWindowSurface failed (ISurfaceTexture=%p)",
569                display.get());
570    }
571
572    { // scope for the lock
573        Mutex::Autolock _l(mStateLock);
574        old_surface = mExternalDisplaySurface;
575        mExternalDisplayNativeWindow = stc;
576        mExternalDisplaySurface = result;
577        ALOGD("mExternalDisplaySurface = %p", result);
578    }
579
580    if (old_surface != EGL_NO_SURFACE) {
581        // Note: EGL allows to destroy an object while its current
582        // it will fail to become current next time though.
583        eglDestroySurface(mEGLDisplay, old_surface);
584    }
585}
586
587EGLSurface SurfaceFlinger::getExternalDisplaySurface() const {
588    Mutex::Autolock _l(mStateLock);
589    return mExternalDisplaySurface;
590}
591
592// ----------------------------------------------------------------------------
593
594void SurfaceFlinger::waitForEvent() {
595    mEventQueue.waitMessage();
596}
597
598void SurfaceFlinger::signalTransaction() {
599    mEventQueue.invalidate();
600}
601
602void SurfaceFlinger::signalLayerUpdate() {
603    mEventQueue.invalidate();
604}
605
606void SurfaceFlinger::signalRefresh() {
607    mEventQueue.refresh();
608}
609
610status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
611        nsecs_t reltime, uint32_t flags) {
612    return mEventQueue.postMessage(msg, reltime);
613}
614
615status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
616        nsecs_t reltime, uint32_t flags) {
617    status_t res = mEventQueue.postMessage(msg, reltime);
618    if (res == NO_ERROR) {
619        msg->wait();
620    }
621    return res;
622}
623
624bool SurfaceFlinger::threadLoop() {
625    waitForEvent();
626    return true;
627}
628
629void SurfaceFlinger::onVSyncReceived(int dpy, nsecs_t timestamp) {
630    mEventThread->onVSyncReceived(dpy, timestamp);
631}
632
633void SurfaceFlinger::eventControl(int event, int enabled) {
634    getHwComposer().eventControl(event, enabled);
635}
636
637void SurfaceFlinger::onMessageReceived(int32_t what) {
638    ATRACE_CALL();
639    switch (what) {
640    case MessageQueue::INVALIDATE:
641        handleMessageTransaction();
642        handleMessageInvalidate();
643        signalRefresh();
644        break;
645    case MessageQueue::REFRESH:
646        handleMessageRefresh();
647        break;
648    }
649}
650
651void SurfaceFlinger::handleMessageTransaction() {
652    uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
653    if (transactionFlags) {
654        handleTransaction(transactionFlags);
655    }
656}
657
658void SurfaceFlinger::handleMessageInvalidate() {
659    handlePageFlip();
660}
661
662void SurfaceFlinger::handleMessageRefresh() {
663    handleRefresh();
664
665    if (CC_UNLIKELY(mVisibleRegionsDirty)) {
666        mVisibleRegionsDirty = false;
667        invalidateHwcGeometry();
668
669        /*
670         *  rebuild the visible layer list per screen
671         */
672
673        const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
674        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
675            const sp<DisplayDevice>& hw(mDisplays[dpy]);
676            Region opaqueRegion;
677            Region dirtyRegion;
678            computeVisibleRegions(currentLayers,
679                    hw->getLayerStack(), dirtyRegion, opaqueRegion);
680            hw->dirtyRegion.orSelf(dirtyRegion);
681
682            Vector< sp<LayerBase> > layersSortedByZ;
683            const size_t count = currentLayers.size();
684            for (size_t i=0 ; i<count ; i++) {
685                const Layer::State& s(currentLayers[i]->drawingState());
686                if (s.layerStack == hw->getLayerStack()) {
687                    if (!currentLayers[i]->visibleRegion.isEmpty()) {
688                        layersSortedByZ.add(currentLayers[i]);
689                    }
690                }
691            }
692            hw->setVisibleLayersSortedByZ(layersSortedByZ);
693            hw->undefinedRegion.set(hw->getBounds());
694            hw->undefinedRegion.subtractSelf(hw->getTransform().transform(opaqueRegion));
695        }
696    }
697
698    HWComposer& hwc(getHwComposer());
699    if (hwc.initCheck() == NO_ERROR) {
700        // build the h/w work list
701        const bool workListsDirty = mHwWorkListDirty;
702        mHwWorkListDirty = false;
703        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
704            sp<const DisplayDevice> hw(mDisplays[dpy]);
705            const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ());
706            const size_t count = currentLayers.size();
707
708            const int32_t id = hw->getDisplayId();
709            if (hwc.createWorkList(id, count) >= 0) {
710                HWComposer::LayerListIterator cur = hwc.begin(id);
711                const HWComposer::LayerListIterator end = hwc.end(id);
712                for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
713                    const sp<LayerBase>& layer(currentLayers[i]);
714
715                    if (CC_UNLIKELY(workListsDirty)) {
716                        layer->setGeometry(hw, *cur);
717                        if (mDebugDisableHWC || mDebugRegion) {
718                            cur->setSkip(true);
719                        }
720                    }
721
722                    /*
723                     * update the per-frame h/w composer data for each layer
724                     * and build the transparent region of the FB
725                     */
726                    layer->setPerFrameData(hw, *cur);
727                }
728            }
729        }
730        status_t err = hwc.prepare();
731        ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
732    }
733
734    const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
735    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
736        const sp<DisplayDevice>& hw(mDisplays[dpy]);
737
738        // transform the dirty region into this screen's coordinate space
739        const Transform& planeTransform(hw->getTransform());
740        Region dirtyRegion;
741        if (repaintEverything) {
742            dirtyRegion.set(hw->bounds());
743        } else {
744            dirtyRegion = planeTransform.transform(hw->dirtyRegion);
745            dirtyRegion.andSelf(hw->bounds());
746        }
747        hw->dirtyRegion.clear();
748
749        if (!dirtyRegion.isEmpty()) {
750            if (hw->canDraw()) {
751                // repaint the framebuffer (if needed)
752                handleRepaint(hw, dirtyRegion);
753            }
754        }
755        // inform the h/w that we're done compositing
756        hw->compositionComplete();
757    }
758
759    postFramebuffer();
760
761
762#if 1
763    // render to the external display if we have one
764    EGLSurface externalDisplaySurface = getExternalDisplaySurface();
765    if (externalDisplaySurface != EGL_NO_SURFACE) {
766        EGLSurface cur = eglGetCurrentSurface(EGL_DRAW);
767        EGLBoolean success = eglMakeCurrent(eglGetCurrentDisplay(),
768                externalDisplaySurface, externalDisplaySurface,
769                eglGetCurrentContext());
770
771        ALOGE_IF(!success, "eglMakeCurrent -> external failed");
772
773        if (success) {
774            // redraw the screen entirely...
775            glDisable(GL_TEXTURE_EXTERNAL_OES);
776            glDisable(GL_TEXTURE_2D);
777            glClearColor(0,0,0,1);
778            glClear(GL_COLOR_BUFFER_BIT);
779            glMatrixMode(GL_MODELVIEW);
780            glLoadIdentity();
781
782            const sp<DisplayDevice>& hw(getDisplayDevice(0));
783            const Vector< sp<LayerBase> >& layers( hw->getVisibleLayersSortedByZ() );
784            const size_t count = layers.size();
785            for (size_t i=0 ; i<count ; ++i) {
786                const sp<LayerBase>& layer(layers[i]);
787                layer->draw(hw);
788            }
789
790            success = eglSwapBuffers(eglGetCurrentDisplay(), externalDisplaySurface);
791            ALOGE_IF(!success, "external display eglSwapBuffers failed");
792
793            hw->compositionComplete();
794        }
795
796        success = eglMakeCurrent(eglGetCurrentDisplay(),
797                cur, cur, eglGetCurrentContext());
798
799        ALOGE_IF(!success, "eglMakeCurrent -> internal failed");
800    }
801#endif
802
803}
804
805void SurfaceFlinger::postFramebuffer()
806{
807    ATRACE_CALL();
808
809    const nsecs_t now = systemTime();
810    mDebugInSwapBuffers = now;
811
812    HWComposer& hwc(getHwComposer());
813
814    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
815        const sp<DisplayDevice>& hw(mDisplays[dpy]);
816        if (hwc.initCheck() == NO_ERROR) {
817            const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ());
818            const size_t count = currentLayers.size();
819            const int32_t id = hw->getDisplayId();
820            HWComposer::LayerListIterator cur = hwc.begin(id);
821            const HWComposer::LayerListIterator end = hwc.end(id);
822            for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
823                const sp<LayerBase>& layer(currentLayers[i]);
824                layer->setAcquireFence(hw, *cur);
825            }
826        }
827        hw->flip(hw->swapRegion);
828        hw->swapRegion.clear();
829    }
830
831    if (hwc.initCheck() == NO_ERROR) {
832        // FIXME: eventually commit() won't take arguments
833        hwc.commit(mEGLDisplay, getDefaultDisplayDevice()->getEGLSurface());
834    }
835
836    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
837        sp<const DisplayDevice> hw(mDisplays[dpy]);
838        const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ());
839        const size_t count = currentLayers.size();
840        if (hwc.initCheck() == NO_ERROR) {
841            int32_t id = hw->getDisplayId();
842            HWComposer::LayerListIterator cur = hwc.begin(id);
843            const HWComposer::LayerListIterator end = hwc.end(id);
844            for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
845                currentLayers[i]->onLayerDisplayed(hw, &*cur);
846            }
847        } else {
848            eglSwapBuffers(mEGLDisplay, hw->getEGLSurface());
849            for (size_t i = 0; i < count; i++) {
850                currentLayers[i]->onLayerDisplayed(hw, NULL);
851            }
852        }
853
854        // FIXME: we need to call eglSwapBuffers() on displays that have GL composition
855    }
856
857    mLastSwapBufferTime = systemTime() - now;
858    mDebugInSwapBuffers = 0;
859}
860
861void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
862{
863    ATRACE_CALL();
864
865    Mutex::Autolock _l(mStateLock);
866    const nsecs_t now = systemTime();
867    mDebugInTransaction = now;
868
869    // Here we're guaranteed that some transaction flags are set
870    // so we can call handleTransactionLocked() unconditionally.
871    // We call getTransactionFlags(), which will also clear the flags,
872    // with mStateLock held to guarantee that mCurrentState won't change
873    // until the transaction is committed.
874
875    transactionFlags = getTransactionFlags(eTransactionMask);
876    handleTransactionLocked(transactionFlags);
877
878    mLastTransactionTime = systemTime() - now;
879    mDebugInTransaction = 0;
880    invalidateHwcGeometry();
881    // here the transaction has been committed
882}
883
884void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
885{
886    const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
887    const size_t count = currentLayers.size();
888
889    /*
890     * Traversal of the children
891     * (perform the transaction for each of them if needed)
892     */
893
894    if (transactionFlags & eTraversalNeeded) {
895        for (size_t i=0 ; i<count ; i++) {
896            const sp<LayerBase>& layer = currentLayers[i];
897            uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
898            if (!trFlags) continue;
899
900            const uint32_t flags = layer->doTransaction(0);
901            if (flags & Layer::eVisibleRegion)
902                mVisibleRegionsDirty = true;
903        }
904    }
905
906    /*
907     * Perform display own transactions if needed
908     */
909
910    if (transactionFlags & eDisplayTransactionNeeded) {
911        // here we take advantage of Vector's copy-on-write semantics to
912        // improve performance by skipping the transaction entirely when
913        // know that the lists are identical
914        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
915        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
916        if (!curr.isIdenticalTo(draw)) {
917            mVisibleRegionsDirty = true;
918            const size_t cc = curr.size();
919            const size_t dc = draw.size();
920
921            // find the displays that were removed
922            // (ie: in drawing state but not in current state)
923            // also handle displays that changed
924            // (ie: displays that are in both lists)
925            for (size_t i=0 ; i<dc ; i++) {
926                const ssize_t j = curr.indexOfKey(draw.keyAt(i));
927                if (j < 0) {
928                    // in drawing state but not in current state
929                    if (draw[i].id != DisplayDevice::DISPLAY_ID_MAIN) {
930                        mDisplays.removeItem(draw[i].id);
931                    } else {
932                        ALOGW("trying to remove the main display");
933                    }
934                } else {
935                    // this display is in both lists. see if something changed.
936                    const DisplayDeviceState& state(curr[j]);
937                    if (state.surface != draw[i].surface) {
938                        // changing the surface is like destroying and
939                        // recreating the DisplayDevice
940
941                        sp<SurfaceTextureClient> stc(
942                                new SurfaceTextureClient(state.surface));
943
944                        sp<DisplayDevice> disp = new DisplayDevice(this,
945                                state.id, stc, 0, mEGLConfig);
946
947                        disp->setLayerStack(state.layerStack);
948                        disp->setOrientation(state.orientation);
949                        // TODO: take viewport and frame into account
950                        mDisplays.replaceValueFor(state.id, disp);
951                    }
952                    if (state.layerStack != draw[i].layerStack) {
953                        const sp<DisplayDevice>& disp(getDisplayDevice(state.id));
954                        disp->setLayerStack(state.layerStack);
955                    }
956                    if (state.orientation != draw[i].orientation ||
957                        state.viewport != draw[i].viewport ||
958                        state.frame != draw[i].frame) {
959                        const sp<DisplayDevice>& disp(getDisplayDevice(state.id));
960                        disp->setOrientation(state.orientation);
961                        // TODO: take viewport and frame into account
962                    }
963                }
964            }
965
966            // find displays that were added
967            // (ie: in current state but not in drawing state)
968            for (size_t i=0 ; i<cc ; i++) {
969                if (draw.indexOfKey(curr.keyAt(i)) < 0) {
970                    // FIXME: we need to pass the surface here
971                    const DisplayDeviceState& state(curr[i]);
972                    sp<SurfaceTextureClient> stc(
973                            new SurfaceTextureClient(state.surface));
974                    sp<DisplayDevice> disp = new DisplayDevice(this, state.id,
975                            stc, 0, mEGLConfig);
976                    mDisplays.add(state.id, disp);
977                }
978            }
979        }
980    }
981
982    /*
983     * Perform our own transaction if needed
984     */
985
986    if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
987        // layers have been added
988        mVisibleRegionsDirty = true;
989    }
990
991    // some layers might have been removed, so
992    // we need to update the regions they're exposing.
993    if (mLayersRemoved) {
994        mLayersRemoved = false;
995        mVisibleRegionsDirty = true;
996        const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
997        const size_t count = previousLayers.size();
998        for (size_t i=0 ; i<count ; i++) {
999            const sp<LayerBase>& layer(previousLayers[i]);
1000            if (currentLayers.indexOf(layer) < 0) {
1001                // this layer is not visible anymore
1002                // TODO: we could traverse the tree from front to back and
1003                //       compute the actual visible region
1004                // TODO: we could cache the transformed region
1005                Layer::State front(layer->drawingState());
1006                Region visibleReg = front.transform.transform(
1007                        Region(Rect(front.active.w, front.active.h)));
1008                invalidateLayerStack(front.layerStack, visibleReg);
1009            }
1010        }
1011    }
1012
1013    commitTransaction();
1014}
1015
1016void SurfaceFlinger::commitTransaction()
1017{
1018    if (!mLayersPendingRemoval.isEmpty()) {
1019        // Notify removed layers now that they can't be drawn from
1020        for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1021            mLayersPendingRemoval[i]->onRemoved();
1022        }
1023        mLayersPendingRemoval.clear();
1024    }
1025
1026    mDrawingState = mCurrentState;
1027    mTransationPending = false;
1028    mTransactionCV.broadcast();
1029}
1030
1031void SurfaceFlinger::computeVisibleRegions(
1032        const LayerVector& currentLayers, uint32_t layerStack,
1033        Region& outDirtyRegion, Region& outOpaqueRegion)
1034{
1035    ATRACE_CALL();
1036
1037    Region aboveOpaqueLayers;
1038    Region aboveCoveredLayers;
1039    Region dirty;
1040
1041    outDirtyRegion.clear();
1042
1043    size_t i = currentLayers.size();
1044    while (i--) {
1045        const sp<LayerBase>& layer = currentLayers[i];
1046
1047        // start with the whole surface at its current location
1048        const Layer::State& s(layer->drawingState());
1049
1050        // only consider the layers on the given later stack
1051        if (s.layerStack != layerStack)
1052            continue;
1053
1054        /*
1055         * opaqueRegion: area of a surface that is fully opaque.
1056         */
1057        Region opaqueRegion;
1058
1059        /*
1060         * visibleRegion: area of a surface that is visible on screen
1061         * and not fully transparent. This is essentially the layer's
1062         * footprint minus the opaque regions above it.
1063         * Areas covered by a translucent surface are considered visible.
1064         */
1065        Region visibleRegion;
1066
1067        /*
1068         * coveredRegion: area of a surface that is covered by all
1069         * visible regions above it (which includes the translucent areas).
1070         */
1071        Region coveredRegion;
1072
1073
1074        // handle hidden surfaces by setting the visible region to empty
1075        if (CC_LIKELY(!(s.flags & layer_state_t::eLayerHidden) && s.alpha)) {
1076            const bool translucent = !layer->isOpaque();
1077            Rect bounds(layer->computeBounds());
1078            visibleRegion.set(bounds);
1079            if (!visibleRegion.isEmpty()) {
1080                // Remove the transparent area from the visible region
1081                if (translucent) {
1082                    Region transparentRegionScreen;
1083                    const Transform tr(s.transform);
1084                    if (tr.transformed()) {
1085                        if (tr.preserveRects()) {
1086                            // transform the transparent region
1087                            transparentRegionScreen = tr.transform(s.transparentRegion);
1088                        } else {
1089                            // transformation too complex, can't do the
1090                            // transparent region optimization.
1091                            transparentRegionScreen.clear();
1092                        }
1093                    } else {
1094                        transparentRegionScreen = s.transparentRegion;
1095                    }
1096                    visibleRegion.subtractSelf(transparentRegionScreen);
1097                }
1098
1099                // compute the opaque region
1100                const int32_t layerOrientation = s.transform.getOrientation();
1101                if (s.alpha==255 && !translucent &&
1102                        ((layerOrientation & Transform::ROT_INVALID) == false)) {
1103                    // the opaque region is the layer's footprint
1104                    opaqueRegion = visibleRegion;
1105                }
1106            }
1107        }
1108
1109        // Clip the covered region to the visible region
1110        coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1111
1112        // Update aboveCoveredLayers for next (lower) layer
1113        aboveCoveredLayers.orSelf(visibleRegion);
1114
1115        // subtract the opaque region covered by the layers above us
1116        visibleRegion.subtractSelf(aboveOpaqueLayers);
1117
1118        // compute this layer's dirty region
1119        if (layer->contentDirty) {
1120            // we need to invalidate the whole region
1121            dirty = visibleRegion;
1122            // as well, as the old visible region
1123            dirty.orSelf(layer->visibleRegion);
1124            layer->contentDirty = false;
1125        } else {
1126            /* compute the exposed region:
1127             *   the exposed region consists of two components:
1128             *   1) what's VISIBLE now and was COVERED before
1129             *   2) what's EXPOSED now less what was EXPOSED before
1130             *
1131             * note that (1) is conservative, we start with the whole
1132             * visible region but only keep what used to be covered by
1133             * something -- which mean it may have been exposed.
1134             *
1135             * (2) handles areas that were not covered by anything but got
1136             * exposed because of a resize.
1137             */
1138            const Region newExposed = visibleRegion - coveredRegion;
1139            const Region oldVisibleRegion = layer->visibleRegion;
1140            const Region oldCoveredRegion = layer->coveredRegion;
1141            const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1142            dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1143        }
1144        dirty.subtractSelf(aboveOpaqueLayers);
1145
1146        // accumulate to the screen dirty region
1147        outDirtyRegion.orSelf(dirty);
1148
1149        // Update aboveOpaqueLayers for next (lower) layer
1150        aboveOpaqueLayers.orSelf(opaqueRegion);
1151
1152        // Store the visible region is screen space
1153        layer->setVisibleRegion(visibleRegion);
1154        layer->setCoveredRegion(coveredRegion);
1155    }
1156
1157    outOpaqueRegion = aboveOpaqueLayers;
1158}
1159
1160void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1161        const Region& dirty) {
1162    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1163        const sp<DisplayDevice>& hw(mDisplays[dpy]);
1164        if (hw->getLayerStack() == layerStack) {
1165            hw->dirtyRegion.orSelf(dirty);
1166        }
1167    }
1168}
1169
1170void SurfaceFlinger::handlePageFlip()
1171{
1172    ATRACE_CALL();
1173    Region dirtyRegion;
1174
1175    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
1176
1177    bool visibleRegions = false;
1178    const size_t count = currentLayers.size();
1179    sp<LayerBase> const* layers = currentLayers.array();
1180    for (size_t i=0 ; i<count ; i++) {
1181        const sp<LayerBase>& layer(layers[i]);
1182        const Region dirty(layer->latchBuffer(visibleRegions));
1183        Layer::State s(layer->drawingState());
1184        invalidateLayerStack(s.layerStack, dirty);
1185    }
1186
1187    mVisibleRegionsDirty |= visibleRegions;
1188}
1189
1190void SurfaceFlinger::invalidateHwcGeometry()
1191{
1192    mHwWorkListDirty = true;
1193}
1194
1195void SurfaceFlinger::handleRefresh()
1196{
1197    bool needInvalidate = false;
1198    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
1199    const size_t count = currentLayers.size();
1200    for (size_t i=0 ; i<count ; i++) {
1201        const sp<LayerBase>& layer(currentLayers[i]);
1202        if (layer->onPreComposition()) {
1203            needInvalidate = true;
1204        }
1205    }
1206    if (needInvalidate) {
1207        signalLayerUpdate();
1208    }
1209}
1210
1211void SurfaceFlinger::handleRepaint(const sp<const DisplayDevice>& hw,
1212        const Region& inDirtyRegion)
1213{
1214    ATRACE_CALL();
1215
1216    Region dirtyRegion(inDirtyRegion);
1217
1218    // compute the invalid region
1219    hw->swapRegion.orSelf(dirtyRegion);
1220
1221    if (CC_UNLIKELY(mDebugRegion)) {
1222        debugFlashRegions(hw, dirtyRegion);
1223    }
1224
1225    uint32_t flags = hw->getFlags();
1226    if (flags & DisplayDevice::SWAP_RECTANGLE) {
1227        // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1228        // takes a rectangle, we must make sure to update that whole
1229        // rectangle in that case
1230        dirtyRegion.set(hw->swapRegion.bounds());
1231    } else {
1232        if (flags & DisplayDevice::PARTIAL_UPDATES) {
1233            // We need to redraw the rectangle that will be updated
1234            // (pushed to the framebuffer).
1235            // This is needed because PARTIAL_UPDATES only takes one
1236            // rectangle instead of a region (see DisplayDevice::flip())
1237            dirtyRegion.set(hw->swapRegion.bounds());
1238        } else {
1239            // we need to redraw everything (the whole screen)
1240            dirtyRegion.set(hw->bounds());
1241            hw->swapRegion = dirtyRegion;
1242        }
1243    }
1244
1245    composeSurfaces(hw, dirtyRegion);
1246
1247    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
1248    const size_t count = currentLayers.size();
1249    for (size_t i=0 ; i<count ; i++) {
1250        currentLayers[i]->onPostComposition();
1251    }
1252
1253    // update the swap region and clear the dirty region
1254    hw->swapRegion.orSelf(dirtyRegion);
1255}
1256
1257void SurfaceFlinger::composeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1258{
1259    HWComposer& hwc(getHwComposer());
1260    int32_t id = hw->getDisplayId();
1261    HWComposer::LayerListIterator cur = hwc.begin(id);
1262    const HWComposer::LayerListIterator end = hwc.end(id);
1263
1264    const size_t fbLayerCount = hwc.getLayerCount(id, HWC_FRAMEBUFFER);
1265    if (cur==end || fbLayerCount) {
1266
1267        DisplayDevice::makeCurrent(hw, mEGLContext);
1268
1269        // set the frame buffer
1270        glMatrixMode(GL_MODELVIEW);
1271        glLoadIdentity();
1272
1273        // Never touch the framebuffer if we don't have any framebuffer layers
1274        if (hwc.getLayerCount(id, HWC_OVERLAY)) {
1275            // when using overlays, we assume a fully transparent framebuffer
1276            // NOTE: we could reduce how much we need to clear, for instance
1277            // remove where there are opaque FB layers. however, on some
1278            // GPUs doing a "clean slate" glClear might be more efficient.
1279            // We'll revisit later if needed.
1280            glClearColor(0, 0, 0, 0);
1281            glClear(GL_COLOR_BUFFER_BIT);
1282        } else {
1283            const Region region(hw->undefinedRegion.intersect(dirty));
1284            // screen is already cleared here
1285            if (!region.isEmpty()) {
1286                // can happen with SurfaceView
1287                drawWormhole(region);
1288            }
1289        }
1290
1291        /*
1292         * and then, render the layers targeted at the framebuffer
1293         */
1294
1295        const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
1296        const size_t count = layers.size();
1297        const Transform& tr = hw->getTransform();
1298        for (size_t i=0 ; i<count ; ++i) {
1299            const sp<LayerBase>& layer(layers[i]);
1300            const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1301            if (!clip.isEmpty()) {
1302                if (cur != end && cur->getCompositionType() == HWC_OVERLAY) {
1303                    if (i && (cur->getHints() & HWC_HINT_CLEAR_FB)
1304                            && layer->isOpaque()) {
1305                        // never clear the very first layer since we're
1306                        // guaranteed the FB is already cleared
1307                        layer->clearWithOpenGL(hw, clip);
1308                    }
1309                    ++cur;
1310                    continue;
1311                }
1312                // render the layer
1313                layer->draw(hw, clip);
1314            }
1315            if (cur != end) {
1316                ++cur;
1317            }
1318        }
1319    }
1320}
1321
1322void SurfaceFlinger::debugFlashRegions(const sp<const DisplayDevice>& hw,
1323        const Region& dirtyRegion)
1324{
1325    const uint32_t flags = hw->getFlags();
1326    const int32_t height = hw->getHeight();
1327    if (hw->swapRegion.isEmpty()) {
1328        return;
1329    }
1330
1331    if (!(flags & DisplayDevice::SWAP_RECTANGLE)) {
1332        const Region repaint((flags & DisplayDevice::PARTIAL_UPDATES) ?
1333                dirtyRegion.bounds() : hw->bounds());
1334        composeSurfaces(hw, repaint);
1335    }
1336
1337    glDisable(GL_TEXTURE_EXTERNAL_OES);
1338    glDisable(GL_TEXTURE_2D);
1339    glDisable(GL_BLEND);
1340
1341    static int toggle = 0;
1342    toggle = 1 - toggle;
1343    if (toggle) {
1344        glColor4f(1, 0, 1, 1);
1345    } else {
1346        glColor4f(1, 1, 0, 1);
1347    }
1348
1349    Region::const_iterator it = dirtyRegion.begin();
1350    Region::const_iterator const end = dirtyRegion.end();
1351    while (it != end) {
1352        const Rect& r = *it++;
1353        GLfloat vertices[][2] = {
1354                { r.left,  height - r.top },
1355                { r.left,  height - r.bottom },
1356                { r.right, height - r.bottom },
1357                { r.right, height - r.top }
1358        };
1359        glVertexPointer(2, GL_FLOAT, 0, vertices);
1360        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1361    }
1362
1363    hw->flip(hw->swapRegion);
1364
1365    if (mDebugRegion > 1)
1366        usleep(mDebugRegion * 1000);
1367}
1368
1369void SurfaceFlinger::drawWormhole(const Region& region) const
1370{
1371    glDisable(GL_TEXTURE_EXTERNAL_OES);
1372    glDisable(GL_TEXTURE_2D);
1373    glDisable(GL_BLEND);
1374    glColor4f(0,0,0,0);
1375
1376    GLfloat vertices[4][2];
1377    glVertexPointer(2, GL_FLOAT, 0, vertices);
1378    Region::const_iterator it = region.begin();
1379    Region::const_iterator const end = region.end();
1380    while (it != end) {
1381        const Rect& r = *it++;
1382        vertices[0][0] = r.left;
1383        vertices[0][1] = r.top;
1384        vertices[1][0] = r.right;
1385        vertices[1][1] = r.top;
1386        vertices[2][0] = r.right;
1387        vertices[2][1] = r.bottom;
1388        vertices[3][0] = r.left;
1389        vertices[3][1] = r.bottom;
1390        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1391    }
1392}
1393
1394ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
1395        const sp<LayerBaseClient>& lbc)
1396{
1397    // attach this layer to the client
1398    size_t name = client->attachLayer(lbc);
1399
1400    // add this layer to the current state list
1401    Mutex::Autolock _l(mStateLock);
1402    mCurrentState.layersSortedByZ.add(lbc);
1403
1404    return ssize_t(name);
1405}
1406
1407status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
1408{
1409    Mutex::Autolock _l(mStateLock);
1410    status_t err = purgatorizeLayer_l(layer);
1411    if (err == NO_ERROR)
1412        setTransactionFlags(eTransactionNeeded);
1413    return err;
1414}
1415
1416status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
1417{
1418    ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1419    if (index >= 0) {
1420        mLayersRemoved = true;
1421        return NO_ERROR;
1422    }
1423    return status_t(index);
1424}
1425
1426status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1427{
1428    // First add the layer to the purgatory list, which makes sure it won't
1429    // go away, then remove it from the main list (through a transaction).
1430    ssize_t err = removeLayer_l(layerBase);
1431    if (err >= 0) {
1432        mLayerPurgatory.add(layerBase);
1433    }
1434
1435    mLayersPendingRemoval.push(layerBase);
1436
1437    // it's possible that we don't find a layer, because it might
1438    // have been destroyed already -- this is not technically an error
1439    // from the user because there is a race between Client::destroySurface(),
1440    // ~Client() and ~ISurface().
1441    return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1442}
1443
1444uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags)
1445{
1446    return android_atomic_release_load(&mTransactionFlags);
1447}
1448
1449uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1450{
1451    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1452}
1453
1454uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1455{
1456    uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1457    if ((old & flags)==0) { // wake the server up
1458        signalTransaction();
1459    }
1460    return old;
1461}
1462
1463void SurfaceFlinger::setTransactionState(
1464        const Vector<ComposerState>& state,
1465        const Vector<DisplayState>& displays,
1466        uint32_t flags)
1467{
1468    Mutex::Autolock _l(mStateLock);
1469    uint32_t transactionFlags = 0;
1470
1471    size_t count = displays.size();
1472    for (size_t i=0 ; i<count ; i++) {
1473        const DisplayState& s(displays[i]);
1474        transactionFlags |= setDisplayStateLocked(s);
1475    }
1476
1477    count = state.size();
1478    for (size_t i=0 ; i<count ; i++) {
1479        const ComposerState& s(state[i]);
1480        sp<Client> client( static_cast<Client *>(s.client.get()) );
1481        transactionFlags |= setClientStateLocked(client, s.state);
1482    }
1483
1484    if (transactionFlags) {
1485        // this triggers the transaction
1486        setTransactionFlags(transactionFlags);
1487
1488        // if this is a synchronous transaction, wait for it to take effect
1489        // before returning.
1490        if (flags & eSynchronous) {
1491            mTransationPending = true;
1492        }
1493        while (mTransationPending) {
1494            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1495            if (CC_UNLIKELY(err != NO_ERROR)) {
1496                // just in case something goes wrong in SF, return to the
1497                // called after a few seconds.
1498                ALOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!");
1499                mTransationPending = false;
1500                break;
1501            }
1502        }
1503    }
1504}
1505
1506uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
1507{
1508    uint32_t flags = 0;
1509    DisplayDeviceState& disp(mCurrentState.displays.editValueFor(s.token));
1510    if (disp.id >= 0) {
1511        const uint32_t what = s.what;
1512        if (what & DisplayState::eSurfaceChanged) {
1513            if (disp.surface->asBinder() != s.surface->asBinder()) {
1514                disp.surface = s.surface;
1515                flags |= eDisplayTransactionNeeded;
1516            }
1517        }
1518        if (what & DisplayState::eLayerStackChanged) {
1519            if (disp.layerStack != s.layerStack) {
1520                disp.layerStack = s.layerStack;
1521                flags |= eDisplayTransactionNeeded;
1522            }
1523        }
1524        if (what & DisplayState::eTransformChanged) {
1525            if (disp.orientation != s.orientation) {
1526                disp.orientation = s.orientation;
1527                flags |= eDisplayTransactionNeeded;
1528            }
1529            if (disp.frame != s.frame) {
1530                disp.frame = s.frame;
1531                flags |= eDisplayTransactionNeeded;
1532            }
1533            if (disp.viewport != s.viewport) {
1534                disp.viewport = s.viewport;
1535                flags |= eDisplayTransactionNeeded;
1536            }
1537        }
1538    }
1539    return flags;
1540}
1541
1542uint32_t SurfaceFlinger::setClientStateLocked(
1543        const sp<Client>& client,
1544        const layer_state_t& s)
1545{
1546    uint32_t flags = 0;
1547    sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
1548    if (layer != 0) {
1549        const uint32_t what = s.what;
1550        if (what & layer_state_t::ePositionChanged) {
1551            if (layer->setPosition(s.x, s.y))
1552                flags |= eTraversalNeeded;
1553        }
1554        if (what & layer_state_t::eLayerChanged) {
1555            // NOTE: index needs to be calculated before we update the state
1556            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1557            if (layer->setLayer(s.z)) {
1558                mCurrentState.layersSortedByZ.removeAt(idx);
1559                mCurrentState.layersSortedByZ.add(layer);
1560                // we need traversal (state changed)
1561                // AND transaction (list changed)
1562                flags |= eTransactionNeeded|eTraversalNeeded;
1563            }
1564        }
1565        if (what & layer_state_t::eSizeChanged) {
1566            if (layer->setSize(s.w, s.h)) {
1567                flags |= eTraversalNeeded;
1568            }
1569        }
1570        if (what & layer_state_t::eAlphaChanged) {
1571            if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1572                flags |= eTraversalNeeded;
1573        }
1574        if (what & layer_state_t::eMatrixChanged) {
1575            if (layer->setMatrix(s.matrix))
1576                flags |= eTraversalNeeded;
1577        }
1578        if (what & layer_state_t::eTransparentRegionChanged) {
1579            if (layer->setTransparentRegionHint(s.transparentRegion))
1580                flags |= eTraversalNeeded;
1581        }
1582        if (what & layer_state_t::eVisibilityChanged) {
1583            if (layer->setFlags(s.flags, s.mask))
1584                flags |= eTraversalNeeded;
1585        }
1586        if (what & layer_state_t::eCropChanged) {
1587            if (layer->setCrop(s.crop))
1588                flags |= eTraversalNeeded;
1589        }
1590        if (what & layer_state_t::eLayerStackChanged) {
1591            // NOTE: index needs to be calculated before we update the state
1592            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1593            if (layer->setLayerStack(s.layerStack)) {
1594                mCurrentState.layersSortedByZ.removeAt(idx);
1595                mCurrentState.layersSortedByZ.add(layer);
1596                // we need traversal (state changed)
1597                // AND transaction (list changed)
1598                flags |= eTransactionNeeded|eTraversalNeeded;
1599            }
1600        }
1601    }
1602    return flags;
1603}
1604
1605sp<ISurface> SurfaceFlinger::createLayer(
1606        ISurfaceComposerClient::surface_data_t* params,
1607        const String8& name,
1608        const sp<Client>& client,
1609        DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1610        uint32_t flags)
1611{
1612    sp<LayerBaseClient> layer;
1613    sp<ISurface> surfaceHandle;
1614
1615    if (int32_t(w|h) < 0) {
1616        ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
1617                int(w), int(h));
1618        return surfaceHandle;
1619    }
1620
1621    //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
1622    switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
1623        case ISurfaceComposerClient::eFXSurfaceNormal:
1624            layer = createNormalLayer(client, d, w, h, flags, format);
1625            break;
1626        case ISurfaceComposerClient::eFXSurfaceBlur:
1627        case ISurfaceComposerClient::eFXSurfaceDim:
1628            layer = createDimLayer(client, d, w, h, flags);
1629            break;
1630        case ISurfaceComposerClient::eFXSurfaceScreenshot:
1631            layer = createScreenshotLayer(client, d, w, h, flags);
1632            break;
1633    }
1634
1635    if (layer != 0) {
1636        layer->initStates(w, h, flags);
1637        layer->setName(name);
1638        ssize_t token = addClientLayer(client, layer);
1639        surfaceHandle = layer->getSurface();
1640        if (surfaceHandle != 0) {
1641            params->token = token;
1642            params->identity = layer->getIdentity();
1643        }
1644        setTransactionFlags(eTransactionNeeded);
1645    }
1646
1647    return surfaceHandle;
1648}
1649
1650sp<Layer> SurfaceFlinger::createNormalLayer(
1651        const sp<Client>& client, DisplayID display,
1652        uint32_t w, uint32_t h, uint32_t flags,
1653        PixelFormat& format)
1654{
1655    // initialize the surfaces
1656    switch (format) {
1657    case PIXEL_FORMAT_TRANSPARENT:
1658    case PIXEL_FORMAT_TRANSLUCENT:
1659        format = PIXEL_FORMAT_RGBA_8888;
1660        break;
1661    case PIXEL_FORMAT_OPAQUE:
1662#ifdef NO_RGBX_8888
1663        format = PIXEL_FORMAT_RGB_565;
1664#else
1665        format = PIXEL_FORMAT_RGBX_8888;
1666#endif
1667        break;
1668    }
1669
1670#ifdef NO_RGBX_8888
1671    if (format == PIXEL_FORMAT_RGBX_8888)
1672        format = PIXEL_FORMAT_RGBA_8888;
1673#endif
1674
1675    sp<Layer> layer = new Layer(this, display, client);
1676    status_t err = layer->setBuffers(w, h, format, flags);
1677    if (CC_LIKELY(err != NO_ERROR)) {
1678        ALOGE("createNormalLayer() failed (%s)", strerror(-err));
1679        layer.clear();
1680    }
1681    return layer;
1682}
1683
1684sp<LayerDim> SurfaceFlinger::createDimLayer(
1685        const sp<Client>& client, DisplayID display,
1686        uint32_t w, uint32_t h, uint32_t flags)
1687{
1688    sp<LayerDim> layer = new LayerDim(this, display, client);
1689    return layer;
1690}
1691
1692sp<LayerScreenshot> SurfaceFlinger::createScreenshotLayer(
1693        const sp<Client>& client, DisplayID display,
1694        uint32_t w, uint32_t h, uint32_t flags)
1695{
1696    sp<LayerScreenshot> layer = new LayerScreenshot(this, display, client);
1697    return layer;
1698}
1699
1700status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, SurfaceID sid)
1701{
1702    /*
1703     * called by the window manager, when a surface should be marked for
1704     * destruction.
1705     *
1706     * The surface is removed from the current and drawing lists, but placed
1707     * in the purgatory queue, so it's not destroyed right-away (we need
1708     * to wait for all client's references to go away first).
1709     */
1710
1711    status_t err = NAME_NOT_FOUND;
1712    Mutex::Autolock _l(mStateLock);
1713    sp<LayerBaseClient> layer = client->getLayerUser(sid);
1714
1715    if (layer != 0) {
1716        err = purgatorizeLayer_l(layer);
1717        if (err == NO_ERROR) {
1718            setTransactionFlags(eTransactionNeeded);
1719        }
1720    }
1721    return err;
1722}
1723
1724status_t SurfaceFlinger::onLayerDestroyed(const wp<LayerBaseClient>& layer)
1725{
1726    // called by ~ISurface() when all references are gone
1727    status_t err = NO_ERROR;
1728    sp<LayerBaseClient> l(layer.promote());
1729    if (l != NULL) {
1730        Mutex::Autolock _l(mStateLock);
1731        err = removeLayer_l(l);
1732        if (err == NAME_NOT_FOUND) {
1733            // The surface wasn't in the current list, which means it was
1734            // removed already, which means it is in the purgatory,
1735            // and need to be removed from there.
1736            ssize_t idx = mLayerPurgatory.remove(l);
1737            ALOGE_IF(idx < 0,
1738                    "layer=%p is not in the purgatory list", l.get());
1739        }
1740        ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
1741                "error removing layer=%p (%s)", l.get(), strerror(-err));
1742    }
1743    return err;
1744}
1745
1746// ---------------------------------------------------------------------------
1747
1748void SurfaceFlinger::onScreenAcquired() {
1749    ALOGD("Screen about to return, flinger = %p", this);
1750    sp<const DisplayDevice> hw(getDefaultDisplayDevice()); // XXX: this should be per DisplayDevice
1751    getHwComposer().acquire();
1752    hw->acquireScreen();
1753    mEventThread->onScreenAcquired();
1754    mVisibleRegionsDirty = true;
1755    repaintEverything();
1756}
1757
1758void SurfaceFlinger::onScreenReleased() {
1759    ALOGD("About to give-up screen, flinger = %p", this);
1760    sp<const DisplayDevice> hw(getDefaultDisplayDevice()); // XXX: this should be per DisplayDevice
1761    if (hw->isScreenAcquired()) {
1762        mEventThread->onScreenReleased();
1763        hw->releaseScreen();
1764        getHwComposer().release();
1765        // from this point on, SF will stop drawing
1766    }
1767}
1768
1769void SurfaceFlinger::unblank() {
1770    class MessageScreenAcquired : public MessageBase {
1771        SurfaceFlinger* flinger;
1772    public:
1773        MessageScreenAcquired(SurfaceFlinger* flinger) : flinger(flinger) { }
1774        virtual bool handler() {
1775            flinger->onScreenAcquired();
1776            return true;
1777        }
1778    };
1779    sp<MessageBase> msg = new MessageScreenAcquired(this);
1780    postMessageSync(msg);
1781}
1782
1783void SurfaceFlinger::blank() {
1784    class MessageScreenReleased : public MessageBase {
1785        SurfaceFlinger* flinger;
1786    public:
1787        MessageScreenReleased(SurfaceFlinger* flinger) : flinger(flinger) { }
1788        virtual bool handler() {
1789            flinger->onScreenReleased();
1790            return true;
1791        }
1792    };
1793    sp<MessageBase> msg = new MessageScreenReleased(this);
1794    postMessageSync(msg);
1795}
1796
1797// ---------------------------------------------------------------------------
1798
1799status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1800{
1801    const size_t SIZE = 4096;
1802    char buffer[SIZE];
1803    String8 result;
1804
1805    if (!PermissionCache::checkCallingPermission(sDump)) {
1806        snprintf(buffer, SIZE, "Permission Denial: "
1807                "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1808                IPCThreadState::self()->getCallingPid(),
1809                IPCThreadState::self()->getCallingUid());
1810        result.append(buffer);
1811    } else {
1812        // Try to get the main lock, but don't insist if we can't
1813        // (this would indicate SF is stuck, but we want to be able to
1814        // print something in dumpsys).
1815        int retry = 3;
1816        while (mStateLock.tryLock()<0 && --retry>=0) {
1817            usleep(1000000);
1818        }
1819        const bool locked(retry >= 0);
1820        if (!locked) {
1821            snprintf(buffer, SIZE,
1822                    "SurfaceFlinger appears to be unresponsive, "
1823                    "dumping anyways (no locks held)\n");
1824            result.append(buffer);
1825        }
1826
1827        bool dumpAll = true;
1828        size_t index = 0;
1829        size_t numArgs = args.size();
1830        if (numArgs) {
1831            if ((index < numArgs) &&
1832                    (args[index] == String16("--list"))) {
1833                index++;
1834                listLayersLocked(args, index, result, buffer, SIZE);
1835                dumpAll = false;
1836            }
1837
1838            if ((index < numArgs) &&
1839                    (args[index] == String16("--latency"))) {
1840                index++;
1841                dumpStatsLocked(args, index, result, buffer, SIZE);
1842                dumpAll = false;
1843            }
1844
1845            if ((index < numArgs) &&
1846                    (args[index] == String16("--latency-clear"))) {
1847                index++;
1848                clearStatsLocked(args, index, result, buffer, SIZE);
1849                dumpAll = false;
1850            }
1851        }
1852
1853        if (dumpAll) {
1854            dumpAllLocked(result, buffer, SIZE);
1855        }
1856
1857        if (locked) {
1858            mStateLock.unlock();
1859        }
1860    }
1861    write(fd, result.string(), result.size());
1862    return NO_ERROR;
1863}
1864
1865void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
1866        String8& result, char* buffer, size_t SIZE) const
1867{
1868    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1869    const size_t count = currentLayers.size();
1870    for (size_t i=0 ; i<count ; i++) {
1871        const sp<LayerBase>& layer(currentLayers[i]);
1872        snprintf(buffer, SIZE, "%s\n", layer->getName().string());
1873        result.append(buffer);
1874    }
1875}
1876
1877void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
1878        String8& result, char* buffer, size_t SIZE) const
1879{
1880    String8 name;
1881    if (index < args.size()) {
1882        name = String8(args[index]);
1883        index++;
1884    }
1885
1886    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1887    const size_t count = currentLayers.size();
1888    for (size_t i=0 ; i<count ; i++) {
1889        const sp<LayerBase>& layer(currentLayers[i]);
1890        if (name.isEmpty()) {
1891            snprintf(buffer, SIZE, "%s\n", layer->getName().string());
1892            result.append(buffer);
1893        }
1894        if (name.isEmpty() || (name == layer->getName())) {
1895            layer->dumpStats(result, buffer, SIZE);
1896        }
1897    }
1898}
1899
1900void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
1901        String8& result, char* buffer, size_t SIZE) const
1902{
1903    String8 name;
1904    if (index < args.size()) {
1905        name = String8(args[index]);
1906        index++;
1907    }
1908
1909    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1910    const size_t count = currentLayers.size();
1911    for (size_t i=0 ; i<count ; i++) {
1912        const sp<LayerBase>& layer(currentLayers[i]);
1913        if (name.isEmpty() || (name == layer->getName())) {
1914            layer->clearStats();
1915        }
1916    }
1917}
1918
1919void SurfaceFlinger::dumpAllLocked(
1920        String8& result, char* buffer, size_t SIZE) const
1921{
1922    // figure out if we're stuck somewhere
1923    const nsecs_t now = systemTime();
1924    const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
1925    const nsecs_t inTransaction(mDebugInTransaction);
1926    nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
1927    nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
1928
1929    /*
1930     * Dump the visible layer list
1931     */
1932    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1933    const size_t count = currentLayers.size();
1934    snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count);
1935    result.append(buffer);
1936    for (size_t i=0 ; i<count ; i++) {
1937        const sp<LayerBase>& layer(currentLayers[i]);
1938        layer->dump(result, buffer, SIZE);
1939    }
1940
1941    /*
1942     * Dump the layers in the purgatory
1943     */
1944
1945    const size_t purgatorySize = mLayerPurgatory.size();
1946    snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize);
1947    result.append(buffer);
1948    for (size_t i=0 ; i<purgatorySize ; i++) {
1949        const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
1950        layer->shortDump(result, buffer, SIZE);
1951    }
1952
1953    /*
1954     * Dump SurfaceFlinger global state
1955     */
1956
1957    snprintf(buffer, SIZE, "SurfaceFlinger global state:\n");
1958    result.append(buffer);
1959
1960    HWComposer& hwc(getHwComposer());
1961    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1962    const GLExtensions& extensions(GLExtensions::getInstance());
1963    snprintf(buffer, SIZE, "GLES: %s, %s, %s\n",
1964            extensions.getVendor(),
1965            extensions.getRenderer(),
1966            extensions.getVersion());
1967    result.append(buffer);
1968
1969    snprintf(buffer, SIZE, "EGL : %s\n",
1970            eglQueryString(mEGLDisplay, EGL_VERSION_HW_ANDROID));
1971    result.append(buffer);
1972
1973    snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension());
1974    result.append(buffer);
1975
1976    hw->undefinedRegion.dump(result, "undefinedRegion");
1977    snprintf(buffer, SIZE,
1978            "  orientation=%d, canDraw=%d\n",
1979            hw->getOrientation(), hw->canDraw());
1980    result.append(buffer);
1981    snprintf(buffer, SIZE,
1982            "  last eglSwapBuffers() time: %f us\n"
1983            "  last transaction time     : %f us\n"
1984            "  transaction-flags         : %08x\n"
1985            "  refresh-rate              : %f fps\n"
1986            "  x-dpi                     : %f\n"
1987            "  y-dpi                     : %f\n",
1988            mLastSwapBufferTime/1000.0,
1989            mLastTransactionTime/1000.0,
1990            mTransactionFlags,
1991            1e9 / hwc.getRefreshPeriod(),
1992            hwc.getDpiX(),
1993            hwc.getDpiY());
1994    result.append(buffer);
1995
1996    snprintf(buffer, SIZE, "  eglSwapBuffers time: %f us\n",
1997            inSwapBuffersDuration/1000.0);
1998    result.append(buffer);
1999
2000    snprintf(buffer, SIZE, "  transaction time: %f us\n",
2001            inTransactionDuration/1000.0);
2002    result.append(buffer);
2003
2004    /*
2005     * VSYNC state
2006     */
2007    mEventThread->dump(result, buffer, SIZE);
2008
2009    /*
2010     * Dump HWComposer state
2011     */
2012    snprintf(buffer, SIZE, "h/w composer state:\n");
2013    result.append(buffer);
2014    snprintf(buffer, SIZE, "  h/w composer %s and %s\n",
2015            hwc.initCheck()==NO_ERROR ? "present" : "not present",
2016                    (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled");
2017    result.append(buffer);
2018    hwc.dump(result, buffer, SIZE, hw->getVisibleLayersSortedByZ());
2019
2020    /*
2021     * Dump gralloc state
2022     */
2023    const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2024    alloc.dump(result);
2025    hw->dump(result);
2026}
2027
2028status_t SurfaceFlinger::onTransact(
2029    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2030{
2031    switch (code) {
2032        case CREATE_CONNECTION:
2033        case SET_TRANSACTION_STATE:
2034        case BOOT_FINISHED:
2035        case BLANK:
2036        case UNBLANK:
2037        {
2038            // codes that require permission check
2039            IPCThreadState* ipc = IPCThreadState::self();
2040            const int pid = ipc->getCallingPid();
2041            const int uid = ipc->getCallingUid();
2042            if ((uid != AID_GRAPHICS) &&
2043                    !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2044                ALOGE("Permission Denial: "
2045                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2046                return PERMISSION_DENIED;
2047            }
2048            break;
2049        }
2050        case CAPTURE_SCREEN:
2051        {
2052            // codes that require permission check
2053            IPCThreadState* ipc = IPCThreadState::self();
2054            const int pid = ipc->getCallingPid();
2055            const int uid = ipc->getCallingUid();
2056            if ((uid != AID_GRAPHICS) &&
2057                    !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2058                ALOGE("Permission Denial: "
2059                        "can't read framebuffer pid=%d, uid=%d", pid, uid);
2060                return PERMISSION_DENIED;
2061            }
2062            break;
2063        }
2064    }
2065
2066    status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2067    if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2068        CHECK_INTERFACE(ISurfaceComposer, data, reply);
2069        if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2070            IPCThreadState* ipc = IPCThreadState::self();
2071            const int pid = ipc->getCallingPid();
2072            const int uid = ipc->getCallingUid();
2073            ALOGE("Permission Denial: "
2074                    "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2075            return PERMISSION_DENIED;
2076        }
2077        int n;
2078        switch (code) {
2079            case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2080            case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2081                return NO_ERROR;
2082            case 1002:  // SHOW_UPDATES
2083                n = data.readInt32();
2084                mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2085                invalidateHwcGeometry();
2086                repaintEverything();
2087                return NO_ERROR;
2088            case 1004:{ // repaint everything
2089                repaintEverything();
2090                return NO_ERROR;
2091            }
2092            case 1005:{ // force transaction
2093                setTransactionFlags(
2094                        eTransactionNeeded|
2095                        eDisplayTransactionNeeded|
2096                        eTraversalNeeded);
2097                return NO_ERROR;
2098            }
2099            case 1006:{ // send empty update
2100                signalRefresh();
2101                return NO_ERROR;
2102            }
2103            case 1008:  // toggle use of hw composer
2104                n = data.readInt32();
2105                mDebugDisableHWC = n ? 1 : 0;
2106                invalidateHwcGeometry();
2107                repaintEverything();
2108                return NO_ERROR;
2109            case 1009:  // toggle use of transform hint
2110                n = data.readInt32();
2111                mDebugDisableTransformHint = n ? 1 : 0;
2112                invalidateHwcGeometry();
2113                repaintEverything();
2114                return NO_ERROR;
2115            case 1010:  // interrogate.
2116                reply->writeInt32(0);
2117                reply->writeInt32(0);
2118                reply->writeInt32(mDebugRegion);
2119                reply->writeInt32(0);
2120                reply->writeInt32(mDebugDisableHWC);
2121                return NO_ERROR;
2122            case 1013: {
2123                Mutex::Autolock _l(mStateLock);
2124                sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2125                reply->writeInt32(hw->getPageFlipCount());
2126            }
2127            return NO_ERROR;
2128        }
2129    }
2130    return err;
2131}
2132
2133void SurfaceFlinger::repaintEverything() {
2134    android_atomic_or(1, &mRepaintEverything);
2135    signalTransaction();
2136}
2137
2138// ---------------------------------------------------------------------------
2139
2140status_t SurfaceFlinger::renderScreenToTexture(DisplayID dpy,
2141        GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2142{
2143    Mutex::Autolock _l(mStateLock);
2144    return renderScreenToTextureLocked(dpy, textureName, uOut, vOut);
2145}
2146
2147status_t SurfaceFlinger::renderScreenToTextureLocked(DisplayID dpy,
2148        GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2149{
2150    ATRACE_CALL();
2151
2152    if (!GLExtensions::getInstance().haveFramebufferObject())
2153        return INVALID_OPERATION;
2154
2155    // get screen geometry
2156    sp<const DisplayDevice> hw(getDisplayDevice(dpy));
2157    const uint32_t hw_w = hw->getWidth();
2158    const uint32_t hw_h = hw->getHeight();
2159    GLfloat u = 1;
2160    GLfloat v = 1;
2161
2162    // make sure to clear all GL error flags
2163    while ( glGetError() != GL_NO_ERROR ) ;
2164
2165    // create a FBO
2166    GLuint name, tname;
2167    glGenTextures(1, &tname);
2168    glBindTexture(GL_TEXTURE_2D, tname);
2169    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2170    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2171    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2172            hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2173    if (glGetError() != GL_NO_ERROR) {
2174        while ( glGetError() != GL_NO_ERROR ) ;
2175        GLint tw = (2 << (31 - clz(hw_w)));
2176        GLint th = (2 << (31 - clz(hw_h)));
2177        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2178                tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2179        u = GLfloat(hw_w) / tw;
2180        v = GLfloat(hw_h) / th;
2181    }
2182    glGenFramebuffersOES(1, &name);
2183    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2184    glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES,
2185            GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0);
2186
2187    // redraw the screen entirely...
2188    glDisable(GL_TEXTURE_EXTERNAL_OES);
2189    glDisable(GL_TEXTURE_2D);
2190    glClearColor(0,0,0,1);
2191    glClear(GL_COLOR_BUFFER_BIT);
2192    glMatrixMode(GL_MODELVIEW);
2193    glLoadIdentity();
2194    const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
2195    const size_t count = layers.size();
2196    for (size_t i=0 ; i<count ; ++i) {
2197        const sp<LayerBase>& layer(layers[i]);
2198        layer->draw(hw);
2199    }
2200
2201    hw->compositionComplete();
2202
2203    // back to main framebuffer
2204    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2205    glDeleteFramebuffersOES(1, &name);
2206
2207    *textureName = tname;
2208    *uOut = u;
2209    *vOut = v;
2210    return NO_ERROR;
2211}
2212
2213// ---------------------------------------------------------------------------
2214
2215status_t SurfaceFlinger::captureScreenImplLocked(DisplayID dpy,
2216        sp<IMemoryHeap>* heap,
2217        uint32_t* w, uint32_t* h, PixelFormat* f,
2218        uint32_t sw, uint32_t sh,
2219        uint32_t minLayerZ, uint32_t maxLayerZ)
2220{
2221    ATRACE_CALL();
2222
2223    status_t result = PERMISSION_DENIED;
2224
2225    // only one display supported for now
2226    if (CC_UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) {
2227        ALOGE("invalid display %d", dpy);
2228        return BAD_VALUE;
2229    }
2230
2231    if (!GLExtensions::getInstance().haveFramebufferObject()) {
2232        return INVALID_OPERATION;
2233    }
2234
2235    // get screen geometry
2236    sp<const DisplayDevice> hw(getDisplayDevice(dpy));
2237    const uint32_t hw_w = hw->getWidth();
2238    const uint32_t hw_h = hw->getHeight();
2239
2240    // if we have secure windows on this display, never allow the screen capture
2241    if (hw->getSecureLayerVisible()) {
2242        ALOGW("FB is protected: PERMISSION_DENIED");
2243        return PERMISSION_DENIED;
2244    }
2245
2246    if ((sw > hw_w) || (sh > hw_h)) {
2247        ALOGE("size mismatch (%d, %d) > (%d, %d)", sw, sh, hw_w, hw_h);
2248        return BAD_VALUE;
2249    }
2250
2251    sw = (!sw) ? hw_w : sw;
2252    sh = (!sh) ? hw_h : sh;
2253    const size_t size = sw * sh * 4;
2254    const bool filtering = sw != hw_w || sh != hw_h;
2255
2256//    ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d",
2257//            sw, sh, minLayerZ, maxLayerZ);
2258
2259    // make sure to clear all GL error flags
2260    while ( glGetError() != GL_NO_ERROR ) ;
2261
2262    // create a FBO
2263    GLuint name, tname;
2264    glGenRenderbuffersOES(1, &tname);
2265    glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname);
2266    glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh);
2267
2268    glGenFramebuffersOES(1, &name);
2269    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2270    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
2271            GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname);
2272
2273    GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
2274
2275    if (status == GL_FRAMEBUFFER_COMPLETE_OES) {
2276
2277        // invert everything, b/c glReadPixel() below will invert the FB
2278        glViewport(0, 0, sw, sh);
2279        glMatrixMode(GL_PROJECTION);
2280        glPushMatrix();
2281        glLoadIdentity();
2282        glOrthof(0, hw_w, hw_h, 0, 0, 1);
2283        glMatrixMode(GL_MODELVIEW);
2284
2285        // redraw the screen entirely...
2286        glClearColor(0,0,0,1);
2287        glClear(GL_COLOR_BUFFER_BIT);
2288
2289        const LayerVector& layers(mDrawingState.layersSortedByZ);
2290        const size_t count = layers.size();
2291        for (size_t i=0 ; i<count ; ++i) {
2292            const sp<LayerBase>& layer(layers[i]);
2293            const uint32_t flags = layer->drawingState().flags;
2294            if (!(flags & layer_state_t::eLayerHidden)) {
2295                const uint32_t z = layer->drawingState().z;
2296                if (z >= minLayerZ && z <= maxLayerZ) {
2297                    if (filtering) layer->setFiltering(true);
2298                    layer->draw(hw);
2299                    if (filtering) layer->setFiltering(false);
2300                }
2301            }
2302        }
2303
2304        // check for errors and return screen capture
2305        if (glGetError() != GL_NO_ERROR) {
2306            // error while rendering
2307            result = INVALID_OPERATION;
2308        } else {
2309            // allocate shared memory large enough to hold the
2310            // screen capture
2311            sp<MemoryHeapBase> base(
2312                    new MemoryHeapBase(size, 0, "screen-capture") );
2313            void* const ptr = base->getBase();
2314            if (ptr) {
2315                // capture the screen with glReadPixels()
2316                ScopedTrace _t(ATRACE_TAG, "glReadPixels");
2317                glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
2318                if (glGetError() == GL_NO_ERROR) {
2319                    *heap = base;
2320                    *w = sw;
2321                    *h = sh;
2322                    *f = PIXEL_FORMAT_RGBA_8888;
2323                    result = NO_ERROR;
2324                }
2325            } else {
2326                result = NO_MEMORY;
2327            }
2328        }
2329        glViewport(0, 0, hw_w, hw_h);
2330        glMatrixMode(GL_PROJECTION);
2331        glPopMatrix();
2332        glMatrixMode(GL_MODELVIEW);
2333    } else {
2334        result = BAD_VALUE;
2335    }
2336
2337    // release FBO resources
2338    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2339    glDeleteRenderbuffersOES(1, &tname);
2340    glDeleteFramebuffersOES(1, &name);
2341
2342    hw->compositionComplete();
2343
2344//    ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK");
2345
2346    return result;
2347}
2348
2349
2350status_t SurfaceFlinger::captureScreen(DisplayID dpy,
2351        sp<IMemoryHeap>* heap,
2352        uint32_t* width, uint32_t* height, PixelFormat* format,
2353        uint32_t sw, uint32_t sh,
2354        uint32_t minLayerZ, uint32_t maxLayerZ)
2355{
2356    // only one display supported for now
2357    if (CC_UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
2358        return BAD_VALUE;
2359
2360    if (!GLExtensions::getInstance().haveFramebufferObject())
2361        return INVALID_OPERATION;
2362
2363    class MessageCaptureScreen : public MessageBase {
2364        SurfaceFlinger* flinger;
2365        DisplayID dpy;
2366        sp<IMemoryHeap>* heap;
2367        uint32_t* w;
2368        uint32_t* h;
2369        PixelFormat* f;
2370        uint32_t sw;
2371        uint32_t sh;
2372        uint32_t minLayerZ;
2373        uint32_t maxLayerZ;
2374        status_t result;
2375    public:
2376        MessageCaptureScreen(SurfaceFlinger* flinger, DisplayID dpy,
2377                sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f,
2378                uint32_t sw, uint32_t sh,
2379                uint32_t minLayerZ, uint32_t maxLayerZ)
2380            : flinger(flinger), dpy(dpy),
2381              heap(heap), w(w), h(h), f(f), sw(sw), sh(sh),
2382              minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2383              result(PERMISSION_DENIED)
2384        {
2385        }
2386        status_t getResult() const {
2387            return result;
2388        }
2389        virtual bool handler() {
2390            Mutex::Autolock _l(flinger->mStateLock);
2391            result = flinger->captureScreenImplLocked(dpy,
2392                    heap, w, h, f, sw, sh, minLayerZ, maxLayerZ);
2393            return true;
2394        }
2395    };
2396
2397    sp<MessageBase> msg = new MessageCaptureScreen(this,
2398            dpy, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ);
2399    status_t res = postMessageSync(msg);
2400    if (res == NO_ERROR) {
2401        res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult();
2402    }
2403    return res;
2404}
2405
2406// ---------------------------------------------------------------------------
2407
2408SurfaceFlinger::LayerVector::LayerVector() {
2409}
2410
2411SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
2412    : SortedVector<sp<LayerBase> >(rhs) {
2413}
2414
2415int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
2416    const void* rhs) const
2417{
2418    // sort layers per layer-stack, then by z-order and finally by sequence
2419    const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs));
2420    const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs));
2421
2422    uint32_t ls = l->currentState().layerStack;
2423    uint32_t rs = r->currentState().layerStack;
2424    if (ls != rs)
2425        return ls - rs;
2426
2427    uint32_t lz = l->currentState().z;
2428    uint32_t rz = r->currentState().z;
2429    if (lz != rz)
2430        return lz - rz;
2431
2432    return l->sequence - r->sequence;
2433}
2434
2435// ---------------------------------------------------------------------------
2436
2437SurfaceFlinger::DisplayDeviceState::DisplayDeviceState() : id(-1) {
2438}
2439
2440SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(int32_t id)
2441    : id(id), layerStack(0), orientation(0) {
2442}
2443
2444// ---------------------------------------------------------------------------
2445
2446GraphicBufferAlloc::GraphicBufferAlloc() {}
2447
2448GraphicBufferAlloc::~GraphicBufferAlloc() {}
2449
2450sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h,
2451        PixelFormat format, uint32_t usage, status_t* error) {
2452    sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage));
2453    status_t err = graphicBuffer->initCheck();
2454    *error = err;
2455    if (err != 0 || graphicBuffer->handle == 0) {
2456        if (err == NO_MEMORY) {
2457            GraphicBuffer::dumpAllocationsToSystemLog();
2458        }
2459        ALOGE("GraphicBufferAlloc::createGraphicBuffer(w=%d, h=%d) "
2460             "failed (%s), handle=%p",
2461                w, h, strerror(-err), graphicBuffer->handle);
2462        return 0;
2463    }
2464    return graphicBuffer;
2465}
2466
2467// ---------------------------------------------------------------------------
2468
2469}; // namespace android
2470