OSDN Git Service

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