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