2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
20 #include <sys/types.h>
28 #include <cutils/log.h>
29 #include <cutils/properties.h>
31 #include <binder/IPCThreadState.h>
32 #include <binder/IServiceManager.h>
33 #include <binder/MemoryHeapBase.h>
34 #include <binder/PermissionCache.h>
36 #include <ui/DisplayInfo.h>
38 #include <gui/BitTube.h>
39 #include <gui/BufferQueue.h>
40 #include <gui/IDisplayEventConnection.h>
41 #include <gui/SurfaceTextureClient.h>
43 #include <ui/GraphicBufferAllocator.h>
44 #include <ui/PixelFormat.h>
46 #include <utils/String8.h>
47 #include <utils/String16.h>
48 #include <utils/StopWatch.h>
49 #include <utils/Trace.h>
51 #include <private/android_filesystem_config.h>
54 #include "DdmConnection.h"
55 #include "DisplayDevice.h"
57 #include "EventThread.h"
58 #include "GLExtensions.h"
61 #include "LayerScreenshot.h"
62 #include "SurfaceFlinger.h"
64 #include "DisplayHardware/FramebufferSurface.h"
65 #include "DisplayHardware/HWComposer.h"
68 #define EGL_VERSION_HW_ANDROID 0x3143
70 #define DISPLAY_COUNT 1
73 // ---------------------------------------------------------------------------
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");
80 // ---------------------------------------------------------------------------
82 SurfaceFlinger::SurfaceFlinger()
83 : BnSurfaceComposer(), Thread(false),
85 mTransationPending(false),
86 mLayersRemoved(false),
87 mRepaintEverything(0),
88 mBootTime(systemTime()),
89 mVisibleRegionsDirty(false),
90 mHwWorkListDirty(false),
94 mDebugDisableTransformHint(0),
95 mDebugInSwapBuffers(0),
96 mLastSwapBufferTime(0),
97 mDebugInTransaction(0),
98 mLastTransactionTime(0),
101 ALOGI("SurfaceFlinger is starting");
103 // debugging stuff...
104 char value[PROPERTY_VALUE_MAX];
106 property_get("debug.sf.showupdates", value, "0");
107 mDebugRegion = atoi(value);
109 property_get("debug.sf.ddms", value, "0");
110 mDebugDDMS = atoi(value);
112 if (!startDdmConnection()) {
113 // start failed, and DDMS debugging not enabled
117 ALOGI_IF(mDebugRegion, "showupdates enabled");
118 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
121 void SurfaceFlinger::onFirstRef()
123 mEventQueue.init(this);
125 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
127 // Wait for the main thread to be done with its initialization
128 mReadyToRunBarrier.wait();
132 SurfaceFlinger::~SurfaceFlinger()
134 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
135 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
136 eglTerminate(display);
139 void SurfaceFlinger::binderDied(const wp<IBinder>& who)
141 // the window manager died on us. prepare its eulogy.
143 // restore initial conditions (default device unblank, etc)
144 initializeDisplays();
146 // restart the boot-animation
150 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
152 sp<ISurfaceComposerClient> bclient;
153 sp<Client> client(new Client(this));
154 status_t err = client->initCheck();
155 if (err == NO_ERROR) {
161 sp<IBinder> SurfaceFlinger::createDisplay()
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);
172 DisplayToken(const sp<SurfaceFlinger>& flinger)
177 sp<BBinder> token = new DisplayToken(this);
179 Mutex::Autolock _l(mStateLock);
180 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
181 mCurrentState.displays.add(token, info);
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);
191 return mDefaultDisplays[id];
194 sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
196 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
200 void SurfaceFlinger::bootFinished()
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;
207 // wait patiently for the window manager death
208 const String16 name("window");
209 sp<IBinder> window(defaultServiceManager()->getService(name));
211 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
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");
220 void SurfaceFlinger::deleteTextureAsync(GLuint texture) {
221 class MessageDestroyGLTexture : public MessageBase {
224 MessageDestroyGLTexture(GLuint texture)
227 virtual bool handler() {
228 glDeleteTextures(1, &texture);
232 postMessageAsync(new MessageDestroyGLTexture(texture));
235 status_t SurfaceFlinger::selectConfigForPixelFormat(
239 EGLConfig* outConfig)
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];
256 return NAME_NOT_FOUND;
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
266 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
267 EGL_RECORDABLE_ANDROID, EGL_TRUE,
270 err = selectConfigForPixelFormat(display, attribs, nativeVisualId, &config);
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);
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!");
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,
295 EGLContext ctxt = eglCreateContext(display, config, NULL, contextAttributes);
296 ALOGE_IF(ctxt==EGL_NO_CONTEXT, "EGLContext creation failed");
300 void SurfaceFlinger::initializeGL(EGLDisplay display, const sp<DisplayDevice>& hw) {
301 EGLBoolean result = DisplayDevice::makeCurrent(display, hw, mEGLContext);
303 ALOGE("Couldn't create a working GLES context. check logs. exiting...");
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));
317 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
318 glGetIntegerv(GL_MAX_VIEWPORT_DIMS, mMaxViewportDims);
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);
328 inline uint16_t operator() (int r, int g, int b) const {
329 return (r<<11)|(g<<5)|b;
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);
343 // print some debugging info
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]);
364 status_t SurfaceFlinger::readyToRun()
366 ALOGI( "SurfaceFlinger's main thread ready to run. "
367 "Initializing graphics H/W...");
370 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
371 eglInitialize(mEGLDisplay, NULL, NULL);
373 // Initialize the main display
374 // create native window to main display
375 sp<FramebufferSurface> fbs = FramebufferSurface::create();
377 ALOGE("Display subsystem failed to initialize. check logs. exiting...");
381 sp<SurfaceTextureClient> stc(new SurfaceTextureClient(
382 static_cast<sp<ISurfaceTexture> >(fbs->getBufferQueue())));
384 // initialize the config and context
386 ANativeWindow* const anw = stc.get();
387 anw->query(anw, NATIVE_WINDOW_FORMAT, &format);
388 mEGLConfig = selectEGLConfig(mEGLDisplay, format);
389 mEGLContext = createGLContext(mEGLDisplay, mEGLConfig);
391 // initialize our main display hardware
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));
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);
404 // initialize OpenGL ES
405 initializeGL(mEGLDisplay, hw);
407 // start the EventThread
408 mEventThread = new EventThread(this);
409 mEventQueue.setEventThread(mEventThread);
411 // initialize the H/W composer
412 mHwc = new HWComposer(this,
413 *static_cast<HWComposer::EventHandler *>(this),
416 // initialize our drawing state
417 mDrawingState = mCurrentState;
419 // We're now ready to accept clients...
420 mReadyToRunBarrier.open();
422 // set initial conditions (e.g. unblank default device)
423 initializeDisplays();
425 // start boot animation
431 int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
432 return (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) ?
433 type : mHwc->allocateDisplayId();
436 void SurfaceFlinger::startBootAnim() {
437 // start boot animation
438 property_set("service.bootanim.exit", "0");
439 property_set("ctl.start", "bootanim");
442 uint32_t SurfaceFlinger::getMaxTextureSize() const {
443 return mMaxTextureSize;
446 uint32_t SurfaceFlinger::getMaxViewportDims() const {
447 return mMaxViewportDims[0] < mMaxViewportDims[1] ?
448 mMaxViewportDims[0] : mMaxViewportDims[1];
451 // ----------------------------------------------------------------------------
453 bool SurfaceFlinger::authenticateSurfaceTexture(
454 const sp<ISurfaceTexture>& surfaceTexture) const {
455 Mutex::Autolock _l(mStateLock);
456 sp<IBinder> surfaceTextureBinder(surfaceTexture->asBinder());
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());
465 wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
466 if (lbcBinder == surfaceTextureBinder) {
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());
484 wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
485 if (lbcBinder == surfaceTextureBinder) {
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
502 const HWComposer& hwc(getHwComposer());
503 float xdpi = hwc.getDpiX();
504 float ydpi = hwc.getDpiY();
506 // TODO: Not sure if display density should handled by SF any longer
508 static int getDensityFromProperty(char const* propName) {
509 char property[PROPERTY_VALUE_MAX];
511 if (property_get(propName, property, NULL) > 0) {
512 density = atoi(property);
517 static int getEmuDensity() {
518 return getDensityFromProperty("qemu.sf.lcd_density"); }
519 static int getBuildDensity() {
520 return getDensityFromProperty("ro.sf.lcd_density"); }
522 // The density of the device is provided by a build property
523 float density = Density::getBuildDensity() / 160.0f;
525 // the build doesn't provide a density -- this is wrong!
527 ALOGE("ro.sf.lcd_density must be defined as a build property");
528 density = xdpi / 160.0f;
530 if (Density::getEmuDensity()) {
531 // if "qemu.sf.lcd_density" is specified, it overrides everything
532 xdpi = ydpi = density = Density::getEmuDensity();
536 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
537 info->w = hw->getWidth();
538 info->h = hw->getHeight();
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);
549 // ----------------------------------------------------------------------------
551 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
552 return mEventThread->createEventConnection();
555 void SurfaceFlinger::connectDisplay(const sp<ISurfaceTexture>& surface) {
558 { // scope for the lock
559 Mutex::Autolock _l(mStateLock);
560 token = mExtDisplayToken;
564 token = createDisplay();
567 { // scope for the lock
568 Mutex::Autolock _l(mStateLock);
570 // release our current display. we're guarantee to have
571 // a reference to it (token), while we hold the lock
572 mExtDisplayToken = 0;
574 mExtDisplayToken = token;
577 DisplayDeviceState& info(mCurrentState.displays.editValueFor(token));
578 info.surface = surface;
579 setTransactionFlags(eDisplayTransactionNeeded);
583 // ----------------------------------------------------------------------------
585 void SurfaceFlinger::waitForEvent() {
586 mEventQueue.waitMessage();
589 void SurfaceFlinger::signalTransaction() {
590 mEventQueue.invalidate();
593 void SurfaceFlinger::signalLayerUpdate() {
594 mEventQueue.invalidate();
597 void SurfaceFlinger::signalRefresh() {
598 mEventQueue.refresh();
601 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
602 nsecs_t reltime, uint32_t flags) {
603 return mEventQueue.postMessage(msg, reltime);
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) {
615 bool SurfaceFlinger::threadLoop() {
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);
628 void SurfaceFlinger::eventControl(int event, int enabled) {
629 getHwComposer().eventControl(event, enabled);
632 void SurfaceFlinger::onMessageReceived(int32_t what) {
635 case MessageQueue::INVALIDATE:
636 handleMessageTransaction();
637 handleMessageInvalidate();
640 case MessageQueue::REFRESH:
641 handleMessageRefresh();
646 void SurfaceFlinger::handleMessageTransaction() {
647 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
648 if (transactionFlags) {
649 handleTransaction(transactionFlags);
653 void SurfaceFlinger::handleMessageInvalidate() {
658 void SurfaceFlinger::handleMessageRefresh() {
661 rebuildLayerStacks();
663 doDebugFlashRegions();
668 void SurfaceFlinger::doDebugFlashRegions()
670 // is debugging enabled
671 if (CC_LIKELY(!mDebugRegion))
674 const bool repaintEverything = mRepaintEverything;
675 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
676 const sp<DisplayDevice>& hw(mDisplays[dpy]);
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()));
684 // and draw the dirty region
685 glDisable(GL_TEXTURE_EXTERNAL_OES);
686 glDisable(GL_TEXTURE_2D);
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();
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 }
700 glVertexPointer(2, GL_FLOAT, 0, vertices);
701 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
703 hw->compositionComplete();
705 if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
706 eglSwapBuffers(mEGLDisplay, hw->getEGLSurface());
714 if (mDebugRegion > 1) {
715 usleep(mDebugRegion * 1000);
719 void SurfaceFlinger::preComposition()
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;
729 if (needExtraInvalidate) {
734 void SurfaceFlinger::postComposition()
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();
743 void SurfaceFlinger::rebuildLayerStacks() {
744 // rebuild the visible layer list per screen
745 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
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());
757 computeVisibleRegions(currentLayers,
758 hw->getLayerStack(), dirtyRegion, opaqueRegion);
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);
773 hw->setVisibleLayersSortedByZ(layersSortedByZ);
774 hw->undefinedRegion.set(bounds);
775 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
776 hw->dirtyRegion.orSelf(dirtyRegion);
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();
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]);
800 if (CC_UNLIKELY(workListsDirty)) {
801 layer->setGeometry(hw, *cur);
802 if (mDebugDisableHWC || mDebugRegion) {
808 * update the per-frame h/w composer data for each layer
809 * and build the transparent region of the FB
811 layer->setPerFrameData(hw, *cur);
816 status_t err = hwc.prepare();
817 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
821 void SurfaceFlinger::doComposition() {
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]);
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);
833 hw->dirtyRegion.clear();
834 hw->flip(hw->swapRegion);
835 hw->swapRegion.clear();
837 // inform the h/w that we're done compositing
838 hw->compositionComplete();
843 void SurfaceFlinger::postFramebuffer()
847 const nsecs_t now = systemTime();
848 mDebugInSwapBuffers = now;
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);
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);
871 for (size_t i = 0; i < count; i++) {
872 currentLayers[i]->onLayerDisplayed(hw, NULL);
877 mLastSwapBufferTime = systemTime() - now;
878 mDebugInSwapBuffers = 0;
881 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
885 Mutex::Autolock _l(mStateLock);
886 const nsecs_t now = systemTime();
887 mDebugInTransaction = now;
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.
895 transactionFlags = getTransactionFlags(eTransactionMask);
896 handleTransactionLocked(transactionFlags);
898 mLastTransactionTime = systemTime() - now;
899 mDebugInTransaction = 0;
900 invalidateHwcGeometry();
901 // here the transaction has been committed
904 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
906 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
907 const size_t count = currentLayers.size();
910 * Traversal of the children
911 * (perform the transaction for each of them if needed)
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;
920 const uint32_t flags = layer->doTransaction(0);
921 if (flags & Layer::eVisibleRegion)
922 mVisibleRegionsDirty = true;
927 * Perform display own transactions if needed
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();
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));
948 // in drawing state but not in current state
949 if (!draw[i].isMainDisplay()) {
950 mDisplays.removeItem(draw.keyAt(i));
952 ALOGW("trying to remove the main display");
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
963 mDisplays.removeItem(display);
964 mDrawingState.displays.removeItemsAt(i);
966 // at this point we must loop to the next item
970 const sp<DisplayDevice>& disp(getDisplayDevice(display));
972 if (state.layerStack != draw[i].layerStack) {
973 disp->setLayerStack(state.layerStack);
975 if (state.orientation != draw[i].orientation) {
976 disp->setOrientation(state.orientation);
978 if (state.viewport != draw[i].viewport) {
979 disp->setViewport(state.viewport);
981 if (state.frame != draw[i].frame) {
982 disp->setFrame(state.frame);
988 // find displays that were added
989 // (ie: in current state but not in drawing state)
990 for (size_t i=0 ; i<cc ; i++) {
991 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
992 const DisplayDeviceState& state(curr[i]);
993 if (state.surface != NULL) {
994 sp<SurfaceTextureClient> stc(
995 new SurfaceTextureClient(state.surface));
996 const wp<IBinder>& display(curr.keyAt(i));
997 sp<DisplayDevice> disp = new DisplayDevice(this,
998 state.type, display, stc, 0, mEGLConfig);
999 disp->setLayerStack(state.layerStack);
1000 disp->setOrientation(state.orientation);
1001 disp->setViewport(state.viewport);
1002 disp->setFrame(state.frame);
1003 mDisplays.add(display, disp);
1011 * Perform our own transaction if needed
1014 const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
1015 if (currentLayers.size() > previousLayers.size()) {
1016 // layers have been added
1017 mVisibleRegionsDirty = true;
1020 // some layers might have been removed, so
1021 // we need to update the regions they're exposing.
1022 if (mLayersRemoved) {
1023 mLayersRemoved = false;
1024 mVisibleRegionsDirty = true;
1025 const size_t count = previousLayers.size();
1026 for (size_t i=0 ; i<count ; i++) {
1027 const sp<LayerBase>& layer(previousLayers[i]);
1028 if (currentLayers.indexOf(layer) < 0) {
1029 // this layer is not visible anymore
1030 // TODO: we could traverse the tree from front to back and
1031 // compute the actual visible region
1032 // TODO: we could cache the transformed region
1033 Layer::State front(layer->drawingState());
1034 Region visibleReg = front.transform.transform(
1035 Region(Rect(front.active.w, front.active.h)));
1036 invalidateLayerStack(front.layerStack, visibleReg);
1041 commitTransaction();
1044 void SurfaceFlinger::commitTransaction()
1046 if (!mLayersPendingRemoval.isEmpty()) {
1047 // Notify removed layers now that they can't be drawn from
1048 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1049 mLayersPendingRemoval[i]->onRemoved();
1051 mLayersPendingRemoval.clear();
1054 mDrawingState = mCurrentState;
1055 mTransationPending = false;
1056 mTransactionCV.broadcast();
1059 void SurfaceFlinger::computeVisibleRegions(
1060 const LayerVector& currentLayers, uint32_t layerStack,
1061 Region& outDirtyRegion, Region& outOpaqueRegion)
1065 Region aboveOpaqueLayers;
1066 Region aboveCoveredLayers;
1069 outDirtyRegion.clear();
1071 size_t i = currentLayers.size();
1073 const sp<LayerBase>& layer = currentLayers[i];
1075 // start with the whole surface at its current location
1076 const Layer::State& s(layer->drawingState());
1078 // only consider the layers on the given later stack
1079 if (s.layerStack != layerStack)
1083 * opaqueRegion: area of a surface that is fully opaque.
1085 Region opaqueRegion;
1088 * visibleRegion: area of a surface that is visible on screen
1089 * and not fully transparent. This is essentially the layer's
1090 * footprint minus the opaque regions above it.
1091 * Areas covered by a translucent surface are considered visible.
1093 Region visibleRegion;
1096 * coveredRegion: area of a surface that is covered by all
1097 * visible regions above it (which includes the translucent areas).
1099 Region coveredRegion;
1102 // handle hidden surfaces by setting the visible region to empty
1103 if (CC_LIKELY(!(s.flags & layer_state_t::eLayerHidden) && s.alpha)) {
1104 const bool translucent = !layer->isOpaque();
1105 Rect bounds(layer->computeBounds());
1106 visibleRegion.set(bounds);
1107 if (!visibleRegion.isEmpty()) {
1108 // Remove the transparent area from the visible region
1110 Region transparentRegionScreen;
1111 const Transform tr(s.transform);
1112 if (tr.transformed()) {
1113 if (tr.preserveRects()) {
1114 // transform the transparent region
1115 transparentRegionScreen = tr.transform(s.transparentRegion);
1117 // transformation too complex, can't do the
1118 // transparent region optimization.
1119 transparentRegionScreen.clear();
1122 transparentRegionScreen = s.transparentRegion;
1124 visibleRegion.subtractSelf(transparentRegionScreen);
1127 // compute the opaque region
1128 const int32_t layerOrientation = s.transform.getOrientation();
1129 if (s.alpha==255 && !translucent &&
1130 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1131 // the opaque region is the layer's footprint
1132 opaqueRegion = visibleRegion;
1137 // Clip the covered region to the visible region
1138 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1140 // Update aboveCoveredLayers for next (lower) layer
1141 aboveCoveredLayers.orSelf(visibleRegion);
1143 // subtract the opaque region covered by the layers above us
1144 visibleRegion.subtractSelf(aboveOpaqueLayers);
1146 // compute this layer's dirty region
1147 if (layer->contentDirty) {
1148 // we need to invalidate the whole region
1149 dirty = visibleRegion;
1150 // as well, as the old visible region
1151 dirty.orSelf(layer->visibleRegion);
1152 layer->contentDirty = false;
1154 /* compute the exposed region:
1155 * the exposed region consists of two components:
1156 * 1) what's VISIBLE now and was COVERED before
1157 * 2) what's EXPOSED now less what was EXPOSED before
1159 * note that (1) is conservative, we start with the whole
1160 * visible region but only keep what used to be covered by
1161 * something -- which mean it may have been exposed.
1163 * (2) handles areas that were not covered by anything but got
1164 * exposed because of a resize.
1166 const Region newExposed = visibleRegion - coveredRegion;
1167 const Region oldVisibleRegion = layer->visibleRegion;
1168 const Region oldCoveredRegion = layer->coveredRegion;
1169 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1170 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1172 dirty.subtractSelf(aboveOpaqueLayers);
1174 // accumulate to the screen dirty region
1175 outDirtyRegion.orSelf(dirty);
1177 // Update aboveOpaqueLayers for next (lower) layer
1178 aboveOpaqueLayers.orSelf(opaqueRegion);
1180 // Store the visible region is screen space
1181 layer->setVisibleRegion(visibleRegion);
1182 layer->setCoveredRegion(coveredRegion);
1185 outOpaqueRegion = aboveOpaqueLayers;
1188 void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1189 const Region& dirty) {
1190 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1191 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1192 if (hw->getLayerStack() == layerStack) {
1193 hw->dirtyRegion.orSelf(dirty);
1198 void SurfaceFlinger::handlePageFlip()
1202 bool visibleRegions = false;
1203 const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
1204 const size_t count = currentLayers.size();
1205 for (size_t i=0 ; i<count ; i++) {
1206 const sp<LayerBase>& layer(currentLayers[i]);
1207 const Region dirty(layer->latchBuffer(visibleRegions));
1208 Layer::State s(layer->drawingState());
1209 invalidateLayerStack(s.layerStack, dirty);
1212 mVisibleRegionsDirty |= visibleRegions;
1215 void SurfaceFlinger::invalidateHwcGeometry()
1217 mHwWorkListDirty = true;
1221 void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1222 const Region& inDirtyRegion)
1224 Region dirtyRegion(inDirtyRegion);
1226 // compute the invalid region
1227 hw->swapRegion.orSelf(dirtyRegion);
1229 uint32_t flags = hw->getFlags();
1230 if (flags & DisplayDevice::SWAP_RECTANGLE) {
1231 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1232 // takes a rectangle, we must make sure to update that whole
1233 // rectangle in that case
1234 dirtyRegion.set(hw->swapRegion.bounds());
1236 if (flags & DisplayDevice::PARTIAL_UPDATES) {
1237 // We need to redraw the rectangle that will be updated
1238 // (pushed to the framebuffer).
1239 // This is needed because PARTIAL_UPDATES only takes one
1240 // rectangle instead of a region (see DisplayDevice::flip())
1241 dirtyRegion.set(hw->swapRegion.bounds());
1243 // we need to redraw everything (the whole screen)
1244 dirtyRegion.set(hw->bounds());
1245 hw->swapRegion = dirtyRegion;
1249 doComposeSurfaces(hw, dirtyRegion);
1251 // FIXME: we need to call eglSwapBuffers() on displays that have
1252 // GL composition and only on those.
1253 // however, currently hwc.commit() already does that for the main
1254 // display (if there is a hwc) and never for the other ones
1255 if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL ||
1256 getHwComposer().initCheck() != NO_ERROR) {
1257 // FIXME: EGL spec says:
1258 // "surface must be bound to the calling thread's current context,
1259 // for the current rendering API."
1260 eglSwapBuffers(mEGLDisplay, hw->getEGLSurface());
1263 // update the swap region and clear the dirty region
1264 hw->swapRegion.orSelf(dirtyRegion);
1267 void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1269 const int32_t id = hw->getHwcDisplayId();
1270 HWComposer& hwc(getHwComposer());
1271 HWComposer::LayerListIterator cur = hwc.begin(id);
1272 const HWComposer::LayerListIterator end = hwc.end(id);
1274 const bool hasGlesComposition = hwc.hasGlesComposition(id) || (cur==end);
1275 if (hasGlesComposition) {
1276 DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext);
1278 // set the frame buffer
1279 glMatrixMode(GL_MODELVIEW);
1282 // Never touch the framebuffer if we don't have any framebuffer layers
1283 const bool hasHwcComposition = hwc.hasHwcComposition(id);
1284 if (hasHwcComposition) {
1285 // when using overlays, we assume a fully transparent framebuffer
1286 // NOTE: we could reduce how much we need to clear, for instance
1287 // remove where there are opaque FB layers. however, on some
1288 // GPUs doing a "clean slate" glClear might be more efficient.
1289 // We'll revisit later if needed.
1290 glClearColor(0, 0, 0, 0);
1291 glClear(GL_COLOR_BUFFER_BIT);
1293 const Region region(hw->undefinedRegion.intersect(dirty));
1294 // screen is already cleared here
1295 if (!region.isEmpty()) {
1296 // can happen with SurfaceView
1297 drawWormhole(hw, region);
1303 * and then, render the layers targeted at the framebuffer
1306 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
1307 const size_t count = layers.size();
1308 const Transform& tr = hw->getTransform();
1310 // we're using h/w composer
1311 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1312 const sp<LayerBase>& layer(layers[i]);
1313 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1314 if (!clip.isEmpty()) {
1315 switch (cur->getCompositionType()) {
1317 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1319 && layer->isOpaque()
1320 && hasGlesComposition) {
1321 // never clear the very first layer since we're
1322 // guaranteed the FB is already cleared
1323 layer->clearWithOpenGL(hw, clip);
1327 case HWC_FRAMEBUFFER: {
1328 layer->draw(hw, clip);
1333 layer->setAcquireFence(hw, *cur);
1336 // we're not using h/w composer
1337 for (size_t i=0 ; i<count ; ++i) {
1338 const sp<LayerBase>& layer(layers[i]);
1339 const Region clip(dirty.intersect(
1340 tr.transform(layer->visibleRegion)));
1341 if (!clip.isEmpty()) {
1342 layer->draw(hw, clip);
1348 void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw,
1349 const Region& region) const
1351 glDisable(GL_TEXTURE_EXTERNAL_OES);
1352 glDisable(GL_TEXTURE_2D);
1353 glDisable(GL_BLEND);
1356 const int32_t height = hw->getHeight();
1357 Region::const_iterator it = region.begin();
1358 Region::const_iterator const end = region.end();
1360 const Rect& r = *it++;
1361 GLfloat vertices[][2] = {
1362 { r.left, height - r.top },
1363 { r.left, height - r.bottom },
1364 { r.right, height - r.bottom },
1365 { r.right, height - r.top }
1367 glVertexPointer(2, GL_FLOAT, 0, vertices);
1368 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1372 ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
1373 const sp<LayerBaseClient>& lbc)
1375 // attach this layer to the client
1376 size_t name = client->attachLayer(lbc);
1378 // add this layer to the current state list
1379 Mutex::Autolock _l(mStateLock);
1380 mCurrentState.layersSortedByZ.add(lbc);
1382 return ssize_t(name);
1385 status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
1387 Mutex::Autolock _l(mStateLock);
1388 status_t err = purgatorizeLayer_l(layer);
1389 if (err == NO_ERROR)
1390 setTransactionFlags(eTransactionNeeded);
1394 status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
1396 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1398 mLayersRemoved = true;
1401 return status_t(index);
1404 status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1406 // First add the layer to the purgatory list, which makes sure it won't
1407 // go away, then remove it from the main list (through a transaction).
1408 ssize_t err = removeLayer_l(layerBase);
1410 mLayerPurgatory.add(layerBase);
1413 mLayersPendingRemoval.push(layerBase);
1415 // it's possible that we don't find a layer, because it might
1416 // have been destroyed already -- this is not technically an error
1417 // from the user because there is a race between Client::destroySurface(),
1418 // ~Client() and ~ISurface().
1419 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1422 uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags)
1424 return android_atomic_release_load(&mTransactionFlags);
1427 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1429 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1432 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1434 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1435 if ((old & flags)==0) { // wake the server up
1436 signalTransaction();
1441 void SurfaceFlinger::setTransactionState(
1442 const Vector<ComposerState>& state,
1443 const Vector<DisplayState>& displays,
1446 Mutex::Autolock _l(mStateLock);
1447 uint32_t transactionFlags = 0;
1449 size_t count = displays.size();
1450 for (size_t i=0 ; i<count ; i++) {
1451 const DisplayState& s(displays[i]);
1452 transactionFlags |= setDisplayStateLocked(s);
1455 count = state.size();
1456 for (size_t i=0 ; i<count ; i++) {
1457 const ComposerState& s(state[i]);
1458 sp<Client> client( static_cast<Client *>(s.client.get()) );
1459 transactionFlags |= setClientStateLocked(client, s.state);
1462 if (transactionFlags) {
1463 // this triggers the transaction
1464 setTransactionFlags(transactionFlags);
1466 // if this is a synchronous transaction, wait for it to take effect
1467 // before returning.
1468 if (flags & eSynchronous) {
1469 mTransationPending = true;
1471 while (mTransationPending) {
1472 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1473 if (CC_UNLIKELY(err != NO_ERROR)) {
1474 // just in case something goes wrong in SF, return to the
1475 // called after a few seconds.
1476 ALOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!");
1477 mTransationPending = false;
1484 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
1487 DisplayDeviceState& disp(mCurrentState.displays.editValueFor(s.token));
1488 if (disp.isValid()) {
1489 const uint32_t what = s.what;
1490 if (what & DisplayState::eSurfaceChanged) {
1491 if (disp.surface->asBinder() != s.surface->asBinder()) {
1492 disp.surface = s.surface;
1493 flags |= eDisplayTransactionNeeded;
1496 if (what & DisplayState::eLayerStackChanged) {
1497 if (disp.layerStack != s.layerStack) {
1498 disp.layerStack = s.layerStack;
1499 flags |= eDisplayTransactionNeeded;
1502 if (what & DisplayState::eOrientationChanged) {
1503 if (disp.orientation != s.orientation) {
1504 disp.orientation = s.orientation;
1505 flags |= eDisplayTransactionNeeded;
1508 if (what & DisplayState::eFrameChanged) {
1509 if (disp.frame != s.frame) {
1510 disp.frame = s.frame;
1511 flags |= eDisplayTransactionNeeded;
1514 if (what & DisplayState::eViewportChanged) {
1515 if (disp.viewport != s.viewport) {
1516 disp.viewport = s.viewport;
1517 flags |= eDisplayTransactionNeeded;
1524 uint32_t SurfaceFlinger::setClientStateLocked(
1525 const sp<Client>& client,
1526 const layer_state_t& s)
1529 sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
1531 const uint32_t what = s.what;
1532 if (what & layer_state_t::ePositionChanged) {
1533 if (layer->setPosition(s.x, s.y))
1534 flags |= eTraversalNeeded;
1536 if (what & layer_state_t::eLayerChanged) {
1537 // NOTE: index needs to be calculated before we update the state
1538 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1539 if (layer->setLayer(s.z)) {
1540 mCurrentState.layersSortedByZ.removeAt(idx);
1541 mCurrentState.layersSortedByZ.add(layer);
1542 // we need traversal (state changed)
1543 // AND transaction (list changed)
1544 flags |= eTransactionNeeded|eTraversalNeeded;
1547 if (what & layer_state_t::eSizeChanged) {
1548 if (layer->setSize(s.w, s.h)) {
1549 flags |= eTraversalNeeded;
1552 if (what & layer_state_t::eAlphaChanged) {
1553 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1554 flags |= eTraversalNeeded;
1556 if (what & layer_state_t::eMatrixChanged) {
1557 if (layer->setMatrix(s.matrix))
1558 flags |= eTraversalNeeded;
1560 if (what & layer_state_t::eTransparentRegionChanged) {
1561 if (layer->setTransparentRegionHint(s.transparentRegion))
1562 flags |= eTraversalNeeded;
1564 if (what & layer_state_t::eVisibilityChanged) {
1565 if (layer->setFlags(s.flags, s.mask))
1566 flags |= eTraversalNeeded;
1568 if (what & layer_state_t::eCropChanged) {
1569 if (layer->setCrop(s.crop))
1570 flags |= eTraversalNeeded;
1572 if (what & layer_state_t::eLayerStackChanged) {
1573 // NOTE: index needs to be calculated before we update the state
1574 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1575 if (layer->setLayerStack(s.layerStack)) {
1576 mCurrentState.layersSortedByZ.removeAt(idx);
1577 mCurrentState.layersSortedByZ.add(layer);
1578 // we need traversal (state changed)
1579 // AND transaction (list changed)
1580 flags |= eTransactionNeeded|eTraversalNeeded;
1587 sp<ISurface> SurfaceFlinger::createLayer(
1588 ISurfaceComposerClient::surface_data_t* params,
1589 const String8& name,
1590 const sp<Client>& client,
1591 uint32_t w, uint32_t h, PixelFormat format,
1594 sp<LayerBaseClient> layer;
1595 sp<ISurface> surfaceHandle;
1597 if (int32_t(w|h) < 0) {
1598 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
1600 return surfaceHandle;
1603 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
1604 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
1605 case ISurfaceComposerClient::eFXSurfaceNormal:
1606 layer = createNormalLayer(client, w, h, flags, format);
1608 case ISurfaceComposerClient::eFXSurfaceBlur:
1609 case ISurfaceComposerClient::eFXSurfaceDim:
1610 layer = createDimLayer(client, w, h, flags);
1612 case ISurfaceComposerClient::eFXSurfaceScreenshot:
1613 layer = createScreenshotLayer(client, w, h, flags);
1618 layer->initStates(w, h, flags);
1619 layer->setName(name);
1620 ssize_t token = addClientLayer(client, layer);
1621 surfaceHandle = layer->getSurface();
1622 if (surfaceHandle != 0) {
1623 params->token = token;
1624 params->identity = layer->getIdentity();
1626 setTransactionFlags(eTransactionNeeded);
1629 return surfaceHandle;
1632 sp<Layer> SurfaceFlinger::createNormalLayer(
1633 const sp<Client>& client,
1634 uint32_t w, uint32_t h, uint32_t flags,
1635 PixelFormat& format)
1637 // initialize the surfaces
1639 case PIXEL_FORMAT_TRANSPARENT:
1640 case PIXEL_FORMAT_TRANSLUCENT:
1641 format = PIXEL_FORMAT_RGBA_8888;
1643 case PIXEL_FORMAT_OPAQUE:
1645 format = PIXEL_FORMAT_RGB_565;
1647 format = PIXEL_FORMAT_RGBX_8888;
1653 if (format == PIXEL_FORMAT_RGBX_8888)
1654 format = PIXEL_FORMAT_RGBA_8888;
1657 sp<Layer> layer = new Layer(this, client);
1658 status_t err = layer->setBuffers(w, h, format, flags);
1659 if (CC_LIKELY(err != NO_ERROR)) {
1660 ALOGE("createNormalLayer() failed (%s)", strerror(-err));
1666 sp<LayerDim> SurfaceFlinger::createDimLayer(
1667 const sp<Client>& client,
1668 uint32_t w, uint32_t h, uint32_t flags)
1670 sp<LayerDim> layer = new LayerDim(this, client);
1674 sp<LayerScreenshot> SurfaceFlinger::createScreenshotLayer(
1675 const sp<Client>& client,
1676 uint32_t w, uint32_t h, uint32_t flags)
1678 sp<LayerScreenshot> layer = new LayerScreenshot(this, client);
1682 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, SurfaceID sid)
1685 * called by the window manager, when a surface should be marked for
1688 * The surface is removed from the current and drawing lists, but placed
1689 * in the purgatory queue, so it's not destroyed right-away (we need
1690 * to wait for all client's references to go away first).
1693 status_t err = NAME_NOT_FOUND;
1694 Mutex::Autolock _l(mStateLock);
1695 sp<LayerBaseClient> layer = client->getLayerUser(sid);
1698 err = purgatorizeLayer_l(layer);
1699 if (err == NO_ERROR) {
1700 setTransactionFlags(eTransactionNeeded);
1706 status_t SurfaceFlinger::onLayerDestroyed(const wp<LayerBaseClient>& layer)
1708 // called by ~ISurface() when all references are gone
1709 status_t err = NO_ERROR;
1710 sp<LayerBaseClient> l(layer.promote());
1712 Mutex::Autolock _l(mStateLock);
1713 err = removeLayer_l(l);
1714 if (err == NAME_NOT_FOUND) {
1715 // The surface wasn't in the current list, which means it was
1716 // removed already, which means it is in the purgatory,
1717 // and need to be removed from there.
1718 ssize_t idx = mLayerPurgatory.remove(l);
1720 "layer=%p is not in the purgatory list", l.get());
1722 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
1723 "error removing layer=%p (%s)", l.get(), strerror(-err));
1728 // ---------------------------------------------------------------------------
1730 void SurfaceFlinger::onInitializeDisplays() {
1731 // reset screen orientation
1732 Vector<ComposerState> state;
1733 Vector<DisplayState> displays;
1735 d.what = DisplayState::eOrientationChanged;
1736 d.token = mDefaultDisplays[DisplayDevice::DISPLAY_PRIMARY];
1737 d.orientation = DisplayState::eOrientationDefault;
1739 setTransactionState(state, displays, 0);
1741 // XXX: this should init default device to "unblank" and all other devices to "blank"
1745 void SurfaceFlinger::initializeDisplays() {
1746 class MessageScreenInitialized : public MessageBase {
1747 SurfaceFlinger* flinger;
1749 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
1750 virtual bool handler() {
1751 flinger->onInitializeDisplays();
1755 sp<MessageBase> msg = new MessageScreenInitialized(this);
1756 postMessageAsync(msg); // we may be called from main thread, use async message
1760 void SurfaceFlinger::onScreenAcquired() {
1761 ALOGD("Screen about to return, flinger = %p", this);
1762 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); // XXX: this should be per DisplayDevice
1763 getHwComposer().acquire();
1764 hw->acquireScreen();
1765 mEventThread->onScreenAcquired();
1766 mVisibleRegionsDirty = true;
1767 repaintEverything();
1770 void SurfaceFlinger::onScreenReleased() {
1771 ALOGD("About to give-up screen, flinger = %p", this);
1772 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); // XXX: this should be per DisplayDevice
1773 if (hw->isScreenAcquired()) {
1774 mEventThread->onScreenReleased();
1775 hw->releaseScreen();
1776 getHwComposer().release();
1777 // from this point on, SF will stop drawing
1781 void SurfaceFlinger::unblank() {
1782 class MessageScreenAcquired : public MessageBase {
1783 SurfaceFlinger* flinger;
1785 MessageScreenAcquired(SurfaceFlinger* flinger) : flinger(flinger) { }
1786 virtual bool handler() {
1787 flinger->onScreenAcquired();
1791 sp<MessageBase> msg = new MessageScreenAcquired(this);
1792 postMessageSync(msg);
1795 void SurfaceFlinger::blank() {
1796 class MessageScreenReleased : public MessageBase {
1797 SurfaceFlinger* flinger;
1799 MessageScreenReleased(SurfaceFlinger* flinger) : flinger(flinger) { }
1800 virtual bool handler() {
1801 flinger->onScreenReleased();
1805 sp<MessageBase> msg = new MessageScreenReleased(this);
1806 postMessageSync(msg);
1809 // ---------------------------------------------------------------------------
1811 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1813 const size_t SIZE = 4096;
1817 if (!PermissionCache::checkCallingPermission(sDump)) {
1818 snprintf(buffer, SIZE, "Permission Denial: "
1819 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1820 IPCThreadState::self()->getCallingPid(),
1821 IPCThreadState::self()->getCallingUid());
1822 result.append(buffer);
1824 // Try to get the main lock, but don't insist if we can't
1825 // (this would indicate SF is stuck, but we want to be able to
1826 // print something in dumpsys).
1828 while (mStateLock.tryLock()<0 && --retry>=0) {
1831 const bool locked(retry >= 0);
1833 snprintf(buffer, SIZE,
1834 "SurfaceFlinger appears to be unresponsive, "
1835 "dumping anyways (no locks held)\n");
1836 result.append(buffer);
1839 bool dumpAll = true;
1841 size_t numArgs = args.size();
1843 if ((index < numArgs) &&
1844 (args[index] == String16("--list"))) {
1846 listLayersLocked(args, index, result, buffer, SIZE);
1850 if ((index < numArgs) &&
1851 (args[index] == String16("--latency"))) {
1853 dumpStatsLocked(args, index, result, buffer, SIZE);
1857 if ((index < numArgs) &&
1858 (args[index] == String16("--latency-clear"))) {
1860 clearStatsLocked(args, index, result, buffer, SIZE);
1866 dumpAllLocked(result, buffer, SIZE);
1870 mStateLock.unlock();
1873 write(fd, result.string(), result.size());
1877 void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
1878 String8& result, char* buffer, size_t SIZE) const
1880 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1881 const size_t count = currentLayers.size();
1882 for (size_t i=0 ; i<count ; i++) {
1883 const sp<LayerBase>& layer(currentLayers[i]);
1884 snprintf(buffer, SIZE, "%s\n", layer->getName().string());
1885 result.append(buffer);
1889 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
1890 String8& result, char* buffer, size_t SIZE) const
1893 if (index < args.size()) {
1894 name = String8(args[index]);
1898 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1899 const size_t count = currentLayers.size();
1900 for (size_t i=0 ; i<count ; i++) {
1901 const sp<LayerBase>& layer(currentLayers[i]);
1902 if (name.isEmpty()) {
1903 snprintf(buffer, SIZE, "%s\n", layer->getName().string());
1904 result.append(buffer);
1906 if (name.isEmpty() || (name == layer->getName())) {
1907 layer->dumpStats(result, buffer, SIZE);
1912 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
1913 String8& result, char* buffer, size_t SIZE) const
1916 if (index < args.size()) {
1917 name = String8(args[index]);
1921 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1922 const size_t count = currentLayers.size();
1923 for (size_t i=0 ; i<count ; i++) {
1924 const sp<LayerBase>& layer(currentLayers[i]);
1925 if (name.isEmpty() || (name == layer->getName())) {
1926 layer->clearStats();
1931 void SurfaceFlinger::dumpAllLocked(
1932 String8& result, char* buffer, size_t SIZE) const
1934 // figure out if we're stuck somewhere
1935 const nsecs_t now = systemTime();
1936 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
1937 const nsecs_t inTransaction(mDebugInTransaction);
1938 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
1939 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
1942 * Dump the visible layer list
1944 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1945 const size_t count = currentLayers.size();
1946 snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count);
1947 result.append(buffer);
1948 for (size_t i=0 ; i<count ; i++) {
1949 const sp<LayerBase>& layer(currentLayers[i]);
1950 layer->dump(result, buffer, SIZE);
1954 * Dump the layers in the purgatory
1957 const size_t purgatorySize = mLayerPurgatory.size();
1958 snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize);
1959 result.append(buffer);
1960 for (size_t i=0 ; i<purgatorySize ; i++) {
1961 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
1962 layer->shortDump(result, buffer, SIZE);
1966 * Dump Display state
1969 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1970 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
1971 snprintf(buffer, SIZE,
1972 "+ DisplayDevice[%u]\n"
1973 " id=%x, layerStack=%u, (%4dx%4d), orient=%2d (type=%08x), "
1974 "flips=%u, secure=%d, numLayers=%u, v:[%d,%d,%d,%d], f:[%d,%d,%d,%d]\n",
1976 hw->getDisplayType(), hw->getLayerStack(),
1977 hw->getWidth(), hw->getHeight(),
1978 hw->getOrientation(), hw->getTransform().getType(),
1979 hw->getPageFlipCount(),
1980 hw->getSecureLayerVisible(),
1981 hw->getVisibleLayersSortedByZ().size(),
1982 hw->getViewport().left, hw->getViewport().top, hw->getViewport().right, hw->getViewport().bottom,
1983 hw->getFrame().left, hw->getFrame().top, hw->getFrame().right, hw->getFrame().bottom);
1985 result.append(buffer);
1989 * Dump SurfaceFlinger global state
1992 snprintf(buffer, SIZE, "SurfaceFlinger global state:\n");
1993 result.append(buffer);
1995 HWComposer& hwc(getHwComposer());
1996 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1997 const GLExtensions& extensions(GLExtensions::getInstance());
1998 snprintf(buffer, SIZE, "GLES: %s, %s, %s\n",
1999 extensions.getVendor(),
2000 extensions.getRenderer(),
2001 extensions.getVersion());
2002 result.append(buffer);
2004 snprintf(buffer, SIZE, "EGL : %s\n",
2005 eglQueryString(mEGLDisplay, EGL_VERSION_HW_ANDROID));
2006 result.append(buffer);
2008 snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension());
2009 result.append(buffer);
2011 hw->undefinedRegion.dump(result, "undefinedRegion");
2012 snprintf(buffer, SIZE,
2013 " orientation=%d, canDraw=%d\n",
2014 hw->getOrientation(), hw->canDraw());
2015 result.append(buffer);
2016 snprintf(buffer, SIZE,
2017 " last eglSwapBuffers() time: %f us\n"
2018 " last transaction time : %f us\n"
2019 " transaction-flags : %08x\n"
2020 " refresh-rate : %f fps\n"
2023 mLastSwapBufferTime/1000.0,
2024 mLastTransactionTime/1000.0,
2026 1e9 / hwc.getRefreshPeriod(),
2029 result.append(buffer);
2031 snprintf(buffer, SIZE, " eglSwapBuffers time: %f us\n",
2032 inSwapBuffersDuration/1000.0);
2033 result.append(buffer);
2035 snprintf(buffer, SIZE, " transaction time: %f us\n",
2036 inTransactionDuration/1000.0);
2037 result.append(buffer);
2042 mEventThread->dump(result, buffer, SIZE);
2045 * Dump HWComposer state
2047 snprintf(buffer, SIZE, "h/w composer state:\n");
2048 result.append(buffer);
2049 snprintf(buffer, SIZE, " h/w composer %s and %s\n",
2050 hwc.initCheck()==NO_ERROR ? "present" : "not present",
2051 (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled");
2052 result.append(buffer);
2053 hwc.dump(result, buffer, SIZE, hw->getVisibleLayersSortedByZ());
2056 * Dump gralloc state
2058 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2063 bool SurfaceFlinger::startDdmConnection()
2065 void* libddmconnection_dso =
2066 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2067 if (!libddmconnection_dso) {
2070 void (*DdmConnection_start)(const char* name);
2071 DdmConnection_start =
2072 (typeof DdmConnection_start)dlsym(libddmconnection_dso, "DdmConnection_start");
2073 if (!DdmConnection_start) {
2074 dlclose(libddmconnection_dso);
2077 (*DdmConnection_start)(getServiceName());
2081 status_t SurfaceFlinger::onTransact(
2082 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2085 case CREATE_CONNECTION:
2086 case SET_TRANSACTION_STATE:
2091 // codes that require permission check
2092 IPCThreadState* ipc = IPCThreadState::self();
2093 const int pid = ipc->getCallingPid();
2094 const int uid = ipc->getCallingUid();
2095 if ((uid != AID_GRAPHICS) &&
2096 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2097 ALOGE("Permission Denial: "
2098 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2099 return PERMISSION_DENIED;
2103 case CAPTURE_SCREEN:
2105 // codes that require permission check
2106 IPCThreadState* ipc = IPCThreadState::self();
2107 const int pid = ipc->getCallingPid();
2108 const int uid = ipc->getCallingUid();
2109 if ((uid != AID_GRAPHICS) &&
2110 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2111 ALOGE("Permission Denial: "
2112 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2113 return PERMISSION_DENIED;
2119 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2120 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2121 CHECK_INTERFACE(ISurfaceComposer, data, reply);
2122 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2123 IPCThreadState* ipc = IPCThreadState::self();
2124 const int pid = ipc->getCallingPid();
2125 const int uid = ipc->getCallingUid();
2126 ALOGE("Permission Denial: "
2127 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2128 return PERMISSION_DENIED;
2132 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2133 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2135 case 1002: // SHOW_UPDATES
2136 n = data.readInt32();
2137 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2138 invalidateHwcGeometry();
2139 repaintEverything();
2141 case 1004:{ // repaint everything
2142 repaintEverything();
2145 case 1005:{ // force transaction
2146 setTransactionFlags(
2148 eDisplayTransactionNeeded|
2152 case 1006:{ // send empty update
2156 case 1008: // toggle use of hw composer
2157 n = data.readInt32();
2158 mDebugDisableHWC = n ? 1 : 0;
2159 invalidateHwcGeometry();
2160 repaintEverything();
2162 case 1009: // toggle use of transform hint
2163 n = data.readInt32();
2164 mDebugDisableTransformHint = n ? 1 : 0;
2165 invalidateHwcGeometry();
2166 repaintEverything();
2168 case 1010: // interrogate.
2169 reply->writeInt32(0);
2170 reply->writeInt32(0);
2171 reply->writeInt32(mDebugRegion);
2172 reply->writeInt32(0);
2173 reply->writeInt32(mDebugDisableHWC);
2176 Mutex::Autolock _l(mStateLock);
2177 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2178 reply->writeInt32(hw->getPageFlipCount());
2186 void SurfaceFlinger::repaintEverything() {
2187 android_atomic_or(1, &mRepaintEverything);
2188 signalTransaction();
2191 // ---------------------------------------------------------------------------
2193 status_t SurfaceFlinger::renderScreenToTexture(uint32_t layerStack,
2194 GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2196 Mutex::Autolock _l(mStateLock);
2197 return renderScreenToTextureLocked(layerStack, textureName, uOut, vOut);
2200 status_t SurfaceFlinger::renderScreenToTextureLocked(uint32_t layerStack,
2201 GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2205 if (!GLExtensions::getInstance().haveFramebufferObject())
2206 return INVALID_OPERATION;
2208 // get screen geometry
2209 // FIXME: figure out what it means to have a screenshot texture w/ multi-display
2210 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2211 const uint32_t hw_w = hw->getWidth();
2212 const uint32_t hw_h = hw->getHeight();
2216 // make sure to clear all GL error flags
2217 while ( glGetError() != GL_NO_ERROR ) ;
2221 glGenTextures(1, &tname);
2222 glBindTexture(GL_TEXTURE_2D, tname);
2223 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2224 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2225 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2226 hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2227 if (glGetError() != GL_NO_ERROR) {
2228 while ( glGetError() != GL_NO_ERROR ) ;
2229 GLint tw = (2 << (31 - clz(hw_w)));
2230 GLint th = (2 << (31 - clz(hw_h)));
2231 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2232 tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2233 u = GLfloat(hw_w) / tw;
2234 v = GLfloat(hw_h) / th;
2236 glGenFramebuffersOES(1, &name);
2237 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2238 glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES,
2239 GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0);
2241 // redraw the screen entirely...
2242 glDisable(GL_TEXTURE_EXTERNAL_OES);
2243 glDisable(GL_TEXTURE_2D);
2244 glClearColor(0,0,0,1);
2245 glClear(GL_COLOR_BUFFER_BIT);
2246 glMatrixMode(GL_MODELVIEW);
2248 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
2249 const size_t count = layers.size();
2250 for (size_t i=0 ; i<count ; ++i) {
2251 const sp<LayerBase>& layer(layers[i]);
2255 hw->compositionComplete();
2257 // back to main framebuffer
2258 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2259 glDeleteFramebuffersOES(1, &name);
2261 *textureName = tname;
2267 // ---------------------------------------------------------------------------
2269 status_t SurfaceFlinger::captureScreenImplLocked(const sp<IBinder>& display,
2270 sp<IMemoryHeap>* heap,
2271 uint32_t* w, uint32_t* h, PixelFormat* f,
2272 uint32_t sw, uint32_t sh,
2273 uint32_t minLayerZ, uint32_t maxLayerZ)
2277 status_t result = PERMISSION_DENIED;
2279 if (!GLExtensions::getInstance().haveFramebufferObject()) {
2280 return INVALID_OPERATION;
2283 // get screen geometry
2284 sp<const DisplayDevice> hw(getDisplayDevice(display));
2285 const uint32_t hw_w = hw->getWidth();
2286 const uint32_t hw_h = hw->getHeight();
2288 // if we have secure windows on this display, never allow the screen capture
2289 if (hw->getSecureLayerVisible()) {
2290 ALOGW("FB is protected: PERMISSION_DENIED");
2291 return PERMISSION_DENIED;
2294 if ((sw > hw_w) || (sh > hw_h)) {
2295 ALOGE("size mismatch (%d, %d) > (%d, %d)", sw, sh, hw_w, hw_h);
2299 sw = (!sw) ? hw_w : sw;
2300 sh = (!sh) ? hw_h : sh;
2301 const size_t size = sw * sh * 4;
2302 const bool filtering = sw != hw_w || sh != hw_h;
2304 // ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d",
2305 // sw, sh, minLayerZ, maxLayerZ);
2307 // make sure to clear all GL error flags
2308 while ( glGetError() != GL_NO_ERROR ) ;
2312 glGenRenderbuffersOES(1, &tname);
2313 glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname);
2314 glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh);
2316 glGenFramebuffersOES(1, &name);
2317 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2318 glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
2319 GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname);
2321 GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
2323 if (status == GL_FRAMEBUFFER_COMPLETE_OES) {
2325 // invert everything, b/c glReadPixel() below will invert the FB
2326 glViewport(0, 0, sw, sh);
2327 glMatrixMode(GL_PROJECTION);
2330 glOrthof(0, hw_w, hw_h, 0, 0, 1);
2331 glMatrixMode(GL_MODELVIEW);
2333 // redraw the screen entirely...
2334 glClearColor(0,0,0,1);
2335 glClear(GL_COLOR_BUFFER_BIT);
2337 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
2338 const size_t count = layers.size();
2339 for (size_t i=0 ; i<count ; ++i) {
2340 const sp<LayerBase>& layer(layers[i]);
2341 const uint32_t z = layer->drawingState().z;
2342 if (z >= minLayerZ && z <= maxLayerZ) {
2343 if (filtering) layer->setFiltering(true);
2345 if (filtering) layer->setFiltering(false);
2349 // check for errors and return screen capture
2350 if (glGetError() != GL_NO_ERROR) {
2351 // error while rendering
2352 result = INVALID_OPERATION;
2354 // allocate shared memory large enough to hold the
2356 sp<MemoryHeapBase> base(
2357 new MemoryHeapBase(size, 0, "screen-capture") );
2358 void* const ptr = base->getBase();
2360 // capture the screen with glReadPixels()
2361 ScopedTrace _t(ATRACE_TAG, "glReadPixels");
2362 glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
2363 if (glGetError() == GL_NO_ERROR) {
2367 *f = PIXEL_FORMAT_RGBA_8888;
2374 glViewport(0, 0, hw_w, hw_h);
2375 glMatrixMode(GL_PROJECTION);
2377 glMatrixMode(GL_MODELVIEW);
2382 // release FBO resources
2383 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2384 glDeleteRenderbuffersOES(1, &tname);
2385 glDeleteFramebuffersOES(1, &name);
2387 hw->compositionComplete();
2389 // ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK");
2395 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
2396 sp<IMemoryHeap>* heap,
2397 uint32_t* width, uint32_t* height, PixelFormat* format,
2398 uint32_t sw, uint32_t sh,
2399 uint32_t minLayerZ, uint32_t maxLayerZ)
2401 if (CC_UNLIKELY(display == 0))
2404 if (!GLExtensions::getInstance().haveFramebufferObject())
2405 return INVALID_OPERATION;
2407 class MessageCaptureScreen : public MessageBase {
2408 SurfaceFlinger* flinger;
2409 sp<IBinder> display;
2410 sp<IMemoryHeap>* heap;
2420 MessageCaptureScreen(SurfaceFlinger* flinger, const sp<IBinder>& display,
2421 sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f,
2422 uint32_t sw, uint32_t sh,
2423 uint32_t minLayerZ, uint32_t maxLayerZ)
2424 : flinger(flinger), display(display),
2425 heap(heap), w(w), h(h), f(f), sw(sw), sh(sh),
2426 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2427 result(PERMISSION_DENIED)
2430 status_t getResult() const {
2433 virtual bool handler() {
2434 Mutex::Autolock _l(flinger->mStateLock);
2435 result = flinger->captureScreenImplLocked(display,
2436 heap, w, h, f, sw, sh, minLayerZ, maxLayerZ);
2441 sp<MessageBase> msg = new MessageCaptureScreen(this,
2442 display, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ);
2443 status_t res = postMessageSync(msg);
2444 if (res == NO_ERROR) {
2445 res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult();
2450 // ---------------------------------------------------------------------------
2452 SurfaceFlinger::LayerVector::LayerVector() {
2455 SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
2456 : SortedVector<sp<LayerBase> >(rhs) {
2459 int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
2460 const void* rhs) const
2462 // sort layers per layer-stack, then by z-order and finally by sequence
2463 const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs));
2464 const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs));
2466 uint32_t ls = l->currentState().layerStack;
2467 uint32_t rs = r->currentState().layerStack;
2471 uint32_t lz = l->currentState().z;
2472 uint32_t rz = r->currentState().z;
2476 return l->sequence - r->sequence;
2479 // ---------------------------------------------------------------------------
2481 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
2482 : type(DisplayDevice::DISPLAY_ID_INVALID) {
2485 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
2486 : type(type), layerStack(0), orientation(0) {
2487 viewport.makeInvalid();
2488 frame.makeInvalid();
2491 // ---------------------------------------------------------------------------
2493 GraphicBufferAlloc::GraphicBufferAlloc() {}
2495 GraphicBufferAlloc::~GraphicBufferAlloc() {}
2497 sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h,
2498 PixelFormat format, uint32_t usage, status_t* error) {
2499 sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage));
2500 status_t err = graphicBuffer->initCheck();
2502 if (err != 0 || graphicBuffer->handle == 0) {
2503 if (err == NO_MEMORY) {
2504 GraphicBuffer::dumpAllocationsToSystemLog();
2506 ALOGE("GraphicBufferAlloc::createGraphicBuffer(w=%d, h=%d) "
2507 "failed (%s), handle=%p",
2508 w, h, strerror(-err), graphicBuffer->handle);
2511 return graphicBuffer;
2514 // ---------------------------------------------------------------------------
2516 }; // namespace android