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