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