SurfaceFlinger.cpp revision a4310c8be2dc3406a668ee99020d52187173232f
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 if (CC_UNLIKELY(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) == NO_ERROR) { 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 layer->setGeometry(hw, *cur); 958 if (mDebugDisableHWC || mDebugRegion) { 959 cur->setSkip(true); 960 } 961 } 962 } 963 } 964 } 965 } 966 967 // set the per-frame data 968 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 969 sp<const DisplayDevice> hw(mDisplays[dpy]); 970 const int32_t id = hw->getHwcDisplayId(); 971 if (id >= 0) { 972 const Vector< sp<LayerBase> >& currentLayers( 973 hw->getVisibleLayersSortedByZ()); 974 const size_t count = currentLayers.size(); 975 HWComposer::LayerListIterator cur = hwc.begin(id); 976 const HWComposer::LayerListIterator end = hwc.end(id); 977 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) { 978 /* 979 * update the per-frame h/w composer data for each layer 980 * and build the transparent region of the FB 981 */ 982 const sp<LayerBase>& layer(currentLayers[i]); 983 layer->setPerFrameData(hw, *cur); 984 } 985 } 986 } 987 988 status_t err = hwc.prepare(); 989 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err)); 990 } 991} 992 993void SurfaceFlinger::doComposition() { 994 ATRACE_CALL(); 995 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything); 996 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 997 const sp<DisplayDevice>& hw(mDisplays[dpy]); 998 if (hw->canDraw()) { 999 // transform the dirty region into this screen's coordinate space 1000 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything)); 1001 if (!dirtyRegion.isEmpty()) { 1002 // repaint the framebuffer (if needed) 1003 doDisplayComposition(hw, dirtyRegion); 1004 } 1005 hw->dirtyRegion.clear(); 1006 hw->flip(hw->swapRegion); 1007 hw->swapRegion.clear(); 1008 } 1009 // inform the h/w that we're done compositing 1010 hw->compositionComplete(); 1011 } 1012 postFramebuffer(); 1013} 1014 1015void SurfaceFlinger::postFramebuffer() 1016{ 1017 ATRACE_CALL(); 1018 1019 const nsecs_t now = systemTime(); 1020 mDebugInSwapBuffers = now; 1021 1022 HWComposer& hwc(getHwComposer()); 1023 if (hwc.initCheck() == NO_ERROR) { 1024 if (!hwc.supportsFramebufferTarget()) { 1025 // EGL spec says: 1026 // "surface must be bound to the calling thread's current context, 1027 // for the current rendering API." 1028 DisplayDevice::makeCurrent(mEGLDisplay, 1029 getDefaultDisplayDevice(), mEGLContext); 1030 } 1031 hwc.commit(); 1032 } 1033 1034 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 1035 sp<const DisplayDevice> hw(mDisplays[dpy]); 1036 const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ()); 1037 hw->onSwapBuffersCompleted(hwc); 1038 const size_t count = currentLayers.size(); 1039 int32_t id = hw->getHwcDisplayId(); 1040 if (id >=0 && hwc.initCheck() == NO_ERROR) { 1041 HWComposer::LayerListIterator cur = hwc.begin(id); 1042 const HWComposer::LayerListIterator end = hwc.end(id); 1043 for (size_t i = 0; cur != end && i < count; ++i, ++cur) { 1044 currentLayers[i]->onLayerDisplayed(hw, &*cur); 1045 } 1046 } else { 1047 for (size_t i = 0; i < count; i++) { 1048 currentLayers[i]->onLayerDisplayed(hw, NULL); 1049 } 1050 } 1051 } 1052 1053 mLastSwapBufferTime = systemTime() - now; 1054 mDebugInSwapBuffers = 0; 1055} 1056 1057void SurfaceFlinger::handleTransaction(uint32_t transactionFlags) 1058{ 1059 ATRACE_CALL(); 1060 1061 Mutex::Autolock _l(mStateLock); 1062 const nsecs_t now = systemTime(); 1063 mDebugInTransaction = now; 1064 1065 // Here we're guaranteed that some transaction flags are set 1066 // so we can call handleTransactionLocked() unconditionally. 1067 // We call getTransactionFlags(), which will also clear the flags, 1068 // with mStateLock held to guarantee that mCurrentState won't change 1069 // until the transaction is committed. 1070 1071 transactionFlags = getTransactionFlags(eTransactionMask); 1072 handleTransactionLocked(transactionFlags); 1073 1074 mLastTransactionTime = systemTime() - now; 1075 mDebugInTransaction = 0; 1076 invalidateHwcGeometry(); 1077 // here the transaction has been committed 1078} 1079 1080void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags) 1081{ 1082 const LayerVector& currentLayers(mCurrentState.layersSortedByZ); 1083 const size_t count = currentLayers.size(); 1084 1085 /* 1086 * Traversal of the children 1087 * (perform the transaction for each of them if needed) 1088 */ 1089 1090 if (transactionFlags & eTraversalNeeded) { 1091 for (size_t i=0 ; i<count ; i++) { 1092 const sp<LayerBase>& layer = currentLayers[i]; 1093 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded); 1094 if (!trFlags) continue; 1095 1096 const uint32_t flags = layer->doTransaction(0); 1097 if (flags & Layer::eVisibleRegion) 1098 mVisibleRegionsDirty = true; 1099 } 1100 } 1101 1102 /* 1103 * Perform display own transactions if needed 1104 */ 1105 1106 if (transactionFlags & eDisplayTransactionNeeded) { 1107 // here we take advantage of Vector's copy-on-write semantics to 1108 // improve performance by skipping the transaction entirely when 1109 // know that the lists are identical 1110 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays); 1111 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays); 1112 if (!curr.isIdenticalTo(draw)) { 1113 mVisibleRegionsDirty = true; 1114 const size_t cc = curr.size(); 1115 size_t dc = draw.size(); 1116 1117 // find the displays that were removed 1118 // (ie: in drawing state but not in current state) 1119 // also handle displays that changed 1120 // (ie: displays that are in both lists) 1121 for (size_t i=0 ; i<dc ; i++) { 1122 const ssize_t j = curr.indexOfKey(draw.keyAt(i)); 1123 if (j < 0) { 1124 // in drawing state but not in current state 1125 if (!draw[i].isMainDisplay()) { 1126 mDisplays.removeItem(draw.keyAt(i)); 1127 } else { 1128 ALOGW("trying to remove the main display"); 1129 } 1130 } else { 1131 // this display is in both lists. see if something changed. 1132 const DisplayDeviceState& state(curr[j]); 1133 const wp<IBinder>& display(curr.keyAt(j)); 1134 if (state.surface->asBinder() != draw[i].surface->asBinder()) { 1135 // changing the surface is like destroying and 1136 // recreating the DisplayDevice, so we just remove it 1137 // from the drawing state, so that it get re-added 1138 // below. 1139 mDisplays.removeItem(display); 1140 mDrawingState.displays.removeItemsAt(i); 1141 dc--; i--; 1142 // at this point we must loop to the next item 1143 continue; 1144 } 1145 1146 const sp<DisplayDevice>& disp(getDisplayDevice(display)); 1147 if (disp != NULL) { 1148 if (state.layerStack != draw[i].layerStack) { 1149 disp->setLayerStack(state.layerStack); 1150 } 1151 if ((state.orientation != draw[i].orientation) 1152 || (state.viewport != draw[i].viewport) 1153 || (state.frame != draw[i].frame)) 1154 { 1155 disp->setProjection(state.orientation, 1156 state.viewport, state.frame); 1157 } 1158 1159 // Walk through all the layers in currentLayers, 1160 // and update their transform hint. 1161 // 1162 // TODO: we could be much more clever about which 1163 // layers we touch and how often we do these updates 1164 // (e.g. only touch the layers associated with this 1165 // display, and only on a rotation). 1166 for (size_t i = 0; i < count; i++) { 1167 const sp<LayerBase>& layerBase = currentLayers[i]; 1168 layerBase->updateTransformHint(); 1169 } 1170 } 1171 } 1172 } 1173 1174 // find displays that were added 1175 // (ie: in current state but not in drawing state) 1176 for (size_t i=0 ; i<cc ; i++) { 1177 if (draw.indexOfKey(curr.keyAt(i)) < 0) { 1178 const DisplayDeviceState& state(curr[i]); 1179 1180 sp<FramebufferSurface> fbs; 1181 sp<SurfaceTextureClient> stc; 1182 if (!state.isVirtualDisplay()) { 1183 1184 ALOGE_IF(state.surface!=NULL, 1185 "adding a supported display, but rendering " 1186 "surface is provided (%p), ignoring it", 1187 state.surface.get()); 1188 1189 // for supported (by hwc) displays we provide our 1190 // own rendering surface 1191 fbs = new FramebufferSurface(*mHwc, state.type); 1192 stc = new SurfaceTextureClient( 1193 static_cast< sp<ISurfaceTexture> >(fbs->getBufferQueue())); 1194 } else { 1195 if (state.surface != NULL) { 1196 stc = new SurfaceTextureClient(state.surface); 1197 } 1198 } 1199 1200 const wp<IBinder>& display(curr.keyAt(i)); 1201 if (stc != NULL) { 1202 sp<DisplayDevice> hw = new DisplayDevice(this, 1203 state.type, display, stc, fbs, mEGLConfig); 1204 hw->setLayerStack(state.layerStack); 1205 hw->setProjection(state.orientation, 1206 state.viewport, state.frame); 1207 hw->setDisplayName(state.displayName); 1208 mDisplays.add(display, hw); 1209 if (hw->getDisplayType() < DisplayDevice::NUM_DISPLAY_TYPES) { 1210 // notify the system that this display is now up 1211 // (note onScreenAcquired() is safe to call from 1212 // here because we're in the main thread) 1213 onScreenAcquired(hw); 1214 } 1215 } 1216 } 1217 } 1218 } 1219 } 1220 1221 /* 1222 * Perform our own transaction if needed 1223 */ 1224 1225 const LayerVector& previousLayers(mDrawingState.layersSortedByZ); 1226 if (currentLayers.size() > previousLayers.size()) { 1227 // layers have been added 1228 mVisibleRegionsDirty = true; 1229 } 1230 1231 // some layers might have been removed, so 1232 // we need to update the regions they're exposing. 1233 if (mLayersRemoved) { 1234 mLayersRemoved = false; 1235 mVisibleRegionsDirty = true; 1236 const size_t count = previousLayers.size(); 1237 for (size_t i=0 ; i<count ; i++) { 1238 const sp<LayerBase>& layer(previousLayers[i]); 1239 if (currentLayers.indexOf(layer) < 0) { 1240 // this layer is not visible anymore 1241 // TODO: we could traverse the tree from front to back and 1242 // compute the actual visible region 1243 // TODO: we could cache the transformed region 1244 const Layer::State& s(layer->drawingState()); 1245 Region visibleReg = s.transform.transform( 1246 Region(Rect(s.active.w, s.active.h))); 1247 invalidateLayerStack(s.layerStack, visibleReg); 1248 } 1249 } 1250 } 1251 1252 commitTransaction(); 1253} 1254 1255void SurfaceFlinger::commitTransaction() 1256{ 1257 if (!mLayersPendingRemoval.isEmpty()) { 1258 // Notify removed layers now that they can't be drawn from 1259 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) { 1260 mLayersPendingRemoval[i]->onRemoved(); 1261 } 1262 mLayersPendingRemoval.clear(); 1263 } 1264 1265 mDrawingState = mCurrentState; 1266 mTransationPending = false; 1267 mTransactionCV.broadcast(); 1268} 1269 1270void SurfaceFlinger::computeVisibleRegions( 1271 const LayerVector& currentLayers, uint32_t layerStack, 1272 Region& outDirtyRegion, Region& outOpaqueRegion) 1273{ 1274 ATRACE_CALL(); 1275 1276 Region aboveOpaqueLayers; 1277 Region aboveCoveredLayers; 1278 Region dirty; 1279 1280 outDirtyRegion.clear(); 1281 1282 size_t i = currentLayers.size(); 1283 while (i--) { 1284 const sp<LayerBase>& layer = currentLayers[i]; 1285 1286 // start with the whole surface at its current location 1287 const Layer::State& s(layer->drawingState()); 1288 1289 // only consider the layers on the given later stack 1290 if (s.layerStack != layerStack) 1291 continue; 1292 1293 /* 1294 * opaqueRegion: area of a surface that is fully opaque. 1295 */ 1296 Region opaqueRegion; 1297 1298 /* 1299 * visibleRegion: area of a surface that is visible on screen 1300 * and not fully transparent. This is essentially the layer's 1301 * footprint minus the opaque regions above it. 1302 * Areas covered by a translucent surface are considered visible. 1303 */ 1304 Region visibleRegion; 1305 1306 /* 1307 * coveredRegion: area of a surface that is covered by all 1308 * visible regions above it (which includes the translucent areas). 1309 */ 1310 Region coveredRegion; 1311 1312 /* 1313 * transparentRegion: area of a surface that is hinted to be completely 1314 * transparent. This is only used to tell when the layer has no visible 1315 * non-transparent regions and can be removed from the layer list. It 1316 * does not affect the visibleRegion of this layer or any layers 1317 * beneath it. The hint may not be correct if apps don't respect the 1318 * SurfaceView restrictions (which, sadly, some don't). 1319 */ 1320 Region transparentRegion; 1321 1322 1323 // handle hidden surfaces by setting the visible region to empty 1324 if (CC_LIKELY(layer->isVisible())) { 1325 const bool translucent = !layer->isOpaque(); 1326 Rect bounds(layer->computeBounds()); 1327 visibleRegion.set(bounds); 1328 if (!visibleRegion.isEmpty()) { 1329 // Remove the transparent area from the visible region 1330 if (translucent) { 1331 const Transform tr(s.transform); 1332 if (tr.transformed()) { 1333 if (tr.preserveRects()) { 1334 // transform the transparent region 1335 transparentRegion = tr.transform(s.transparentRegion); 1336 } else { 1337 // transformation too complex, can't do the 1338 // transparent region optimization. 1339 transparentRegion.clear(); 1340 } 1341 } else { 1342 transparentRegion = s.transparentRegion; 1343 } 1344 } 1345 1346 // compute the opaque region 1347 const int32_t layerOrientation = s.transform.getOrientation(); 1348 if (s.alpha==255 && !translucent && 1349 ((layerOrientation & Transform::ROT_INVALID) == false)) { 1350 // the opaque region is the layer's footprint 1351 opaqueRegion = visibleRegion; 1352 } 1353 } 1354 } 1355 1356 // Clip the covered region to the visible region 1357 coveredRegion = aboveCoveredLayers.intersect(visibleRegion); 1358 1359 // Update aboveCoveredLayers for next (lower) layer 1360 aboveCoveredLayers.orSelf(visibleRegion); 1361 1362 // subtract the opaque region covered by the layers above us 1363 visibleRegion.subtractSelf(aboveOpaqueLayers); 1364 1365 // compute this layer's dirty region 1366 if (layer->contentDirty) { 1367 // we need to invalidate the whole region 1368 dirty = visibleRegion; 1369 // as well, as the old visible region 1370 dirty.orSelf(layer->visibleRegion); 1371 layer->contentDirty = false; 1372 } else { 1373 /* compute the exposed region: 1374 * the exposed region consists of two components: 1375 * 1) what's VISIBLE now and was COVERED before 1376 * 2) what's EXPOSED now less what was EXPOSED before 1377 * 1378 * note that (1) is conservative, we start with the whole 1379 * visible region but only keep what used to be covered by 1380 * something -- which mean it may have been exposed. 1381 * 1382 * (2) handles areas that were not covered by anything but got 1383 * exposed because of a resize. 1384 */ 1385 const Region newExposed = visibleRegion - coveredRegion; 1386 const Region oldVisibleRegion = layer->visibleRegion; 1387 const Region oldCoveredRegion = layer->coveredRegion; 1388 const Region oldExposed = oldVisibleRegion - oldCoveredRegion; 1389 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed); 1390 } 1391 dirty.subtractSelf(aboveOpaqueLayers); 1392 1393 // accumulate to the screen dirty region 1394 outDirtyRegion.orSelf(dirty); 1395 1396 // Update aboveOpaqueLayers for next (lower) layer 1397 aboveOpaqueLayers.orSelf(opaqueRegion); 1398 1399 // Store the visible region in screen space 1400 layer->setVisibleRegion(visibleRegion); 1401 layer->setCoveredRegion(coveredRegion); 1402 layer->setVisibleNonTransparentRegion( 1403 visibleRegion.subtract(transparentRegion)); 1404 } 1405 1406 outOpaqueRegion = aboveOpaqueLayers; 1407} 1408 1409void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack, 1410 const Region& dirty) { 1411 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 1412 const sp<DisplayDevice>& hw(mDisplays[dpy]); 1413 if (hw->getLayerStack() == layerStack) { 1414 hw->dirtyRegion.orSelf(dirty); 1415 } 1416 } 1417} 1418 1419void SurfaceFlinger::handlePageFlip() 1420{ 1421 Region dirtyRegion; 1422 1423 bool visibleRegions = false; 1424 const LayerVector& currentLayers(mDrawingState.layersSortedByZ); 1425 const size_t count = currentLayers.size(); 1426 for (size_t i=0 ; i<count ; i++) { 1427 const sp<LayerBase>& layer(currentLayers[i]); 1428 const Region dirty(layer->latchBuffer(visibleRegions)); 1429 const Layer::State& s(layer->drawingState()); 1430 invalidateLayerStack(s.layerStack, dirty); 1431 } 1432 1433 mVisibleRegionsDirty |= visibleRegions; 1434} 1435 1436void SurfaceFlinger::invalidateHwcGeometry() 1437{ 1438 mHwWorkListDirty = true; 1439} 1440 1441 1442void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw, 1443 const Region& inDirtyRegion) 1444{ 1445 Region dirtyRegion(inDirtyRegion); 1446 1447 // compute the invalid region 1448 hw->swapRegion.orSelf(dirtyRegion); 1449 1450 uint32_t flags = hw->getFlags(); 1451 if (flags & DisplayDevice::SWAP_RECTANGLE) { 1452 // we can redraw only what's dirty, but since SWAP_RECTANGLE only 1453 // takes a rectangle, we must make sure to update that whole 1454 // rectangle in that case 1455 dirtyRegion.set(hw->swapRegion.bounds()); 1456 } else { 1457 if (flags & DisplayDevice::PARTIAL_UPDATES) { 1458 // We need to redraw the rectangle that will be updated 1459 // (pushed to the framebuffer). 1460 // This is needed because PARTIAL_UPDATES only takes one 1461 // rectangle instead of a region (see DisplayDevice::flip()) 1462 dirtyRegion.set(hw->swapRegion.bounds()); 1463 } else { 1464 // we need to redraw everything (the whole screen) 1465 dirtyRegion.set(hw->bounds()); 1466 hw->swapRegion = dirtyRegion; 1467 } 1468 } 1469 1470 doComposeSurfaces(hw, dirtyRegion); 1471 1472 // update the swap region and clear the dirty region 1473 hw->swapRegion.orSelf(dirtyRegion); 1474 1475 // swap buffers (presentation) 1476 hw->swapBuffers(getHwComposer()); 1477} 1478 1479void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty) 1480{ 1481 const int32_t id = hw->getHwcDisplayId(); 1482 HWComposer& hwc(getHwComposer()); 1483 HWComposer::LayerListIterator cur = hwc.begin(id); 1484 const HWComposer::LayerListIterator end = hwc.end(id); 1485 1486 const bool hasGlesComposition = hwc.hasGlesComposition(id) || (cur==end); 1487 if (hasGlesComposition) { 1488 DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext); 1489 1490 // set the frame buffer 1491 glMatrixMode(GL_MODELVIEW); 1492 glLoadIdentity(); 1493 1494 // Never touch the framebuffer if we don't have any framebuffer layers 1495 const bool hasHwcComposition = hwc.hasHwcComposition(id); 1496 if (hasHwcComposition) { 1497 // when using overlays, we assume a fully transparent framebuffer 1498 // NOTE: we could reduce how much we need to clear, for instance 1499 // remove where there are opaque FB layers. however, on some 1500 // GPUs doing a "clean slate" glClear might be more efficient. 1501 // We'll revisit later if needed. 1502 glClearColor(0, 0, 0, 0); 1503 glClear(GL_COLOR_BUFFER_BIT); 1504 } else { 1505 const Region region(hw->undefinedRegion.intersect(dirty)); 1506 // screen is already cleared here 1507 if (!region.isEmpty()) { 1508 // can happen with SurfaceView 1509 drawWormhole(hw, region); 1510 } 1511 } 1512 } 1513 1514 /* 1515 * and then, render the layers targeted at the framebuffer 1516 */ 1517 1518 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ()); 1519 const size_t count = layers.size(); 1520 const Transform& tr = hw->getTransform(); 1521 if (cur != end) { 1522 // we're using h/w composer 1523 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) { 1524 const sp<LayerBase>& layer(layers[i]); 1525 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion))); 1526 if (!clip.isEmpty()) { 1527 switch (cur->getCompositionType()) { 1528 case HWC_OVERLAY: { 1529 if ((cur->getHints() & HWC_HINT_CLEAR_FB) 1530 && i 1531 && layer->isOpaque() 1532 && hasGlesComposition) { 1533 // never clear the very first layer since we're 1534 // guaranteed the FB is already cleared 1535 layer->clearWithOpenGL(hw, clip); 1536 } 1537 break; 1538 } 1539 case HWC_FRAMEBUFFER: { 1540 layer->draw(hw, clip); 1541 break; 1542 } 1543 case HWC_FRAMEBUFFER_TARGET: { 1544 // this should not happen as the iterator shouldn't 1545 // let us get there. 1546 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%d)", i); 1547 break; 1548 } 1549 } 1550 } 1551 layer->setAcquireFence(hw, *cur); 1552 } 1553 } else { 1554 // we're not using h/w composer 1555 for (size_t i=0 ; i<count ; ++i) { 1556 const sp<LayerBase>& layer(layers[i]); 1557 const Region clip(dirty.intersect( 1558 tr.transform(layer->visibleRegion))); 1559 if (!clip.isEmpty()) { 1560 layer->draw(hw, clip); 1561 } 1562 } 1563 } 1564} 1565 1566void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, 1567 const Region& region) const 1568{ 1569 glDisable(GL_TEXTURE_EXTERNAL_OES); 1570 glDisable(GL_TEXTURE_2D); 1571 glDisable(GL_BLEND); 1572 glColor4f(0,0,0,0); 1573 1574 const int32_t height = hw->getHeight(); 1575 Region::const_iterator it = region.begin(); 1576 Region::const_iterator const end = region.end(); 1577 while (it != end) { 1578 const Rect& r = *it++; 1579 GLfloat vertices[][2] = { 1580 { r.left, height - r.top }, 1581 { r.left, height - r.bottom }, 1582 { r.right, height - r.bottom }, 1583 { r.right, height - r.top } 1584 }; 1585 glVertexPointer(2, GL_FLOAT, 0, vertices); 1586 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1587 } 1588} 1589 1590ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client, 1591 const sp<LayerBaseClient>& lbc) 1592{ 1593 // attach this layer to the client 1594 size_t name = client->attachLayer(lbc); 1595 1596 // add this layer to the current state list 1597 Mutex::Autolock _l(mStateLock); 1598 mCurrentState.layersSortedByZ.add(lbc); 1599 1600 return ssize_t(name); 1601} 1602 1603status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer) 1604{ 1605 Mutex::Autolock _l(mStateLock); 1606 status_t err = purgatorizeLayer_l(layer); 1607 if (err == NO_ERROR) 1608 setTransactionFlags(eTransactionNeeded); 1609 return err; 1610} 1611 1612status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase) 1613{ 1614 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase); 1615 if (index >= 0) { 1616 mLayersRemoved = true; 1617 return NO_ERROR; 1618 } 1619 return status_t(index); 1620} 1621 1622status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase) 1623{ 1624 // First add the layer to the purgatory list, which makes sure it won't 1625 // go away, then remove it from the main list (through a transaction). 1626 ssize_t err = removeLayer_l(layerBase); 1627 if (err >= 0) { 1628 mLayerPurgatory.add(layerBase); 1629 } 1630 1631 mLayersPendingRemoval.push(layerBase); 1632 1633 // it's possible that we don't find a layer, because it might 1634 // have been destroyed already -- this is not technically an error 1635 // from the user because there is a race between Client::destroySurface(), 1636 // ~Client() and ~ISurface(). 1637 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err; 1638} 1639 1640uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags) 1641{ 1642 return android_atomic_release_load(&mTransactionFlags); 1643} 1644 1645uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) 1646{ 1647 return android_atomic_and(~flags, &mTransactionFlags) & flags; 1648} 1649 1650uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) 1651{ 1652 uint32_t old = android_atomic_or(flags, &mTransactionFlags); 1653 if ((old & flags)==0) { // wake the server up 1654 signalTransaction(); 1655 } 1656 return old; 1657} 1658 1659void SurfaceFlinger::setTransactionState( 1660 const Vector<ComposerState>& state, 1661 const Vector<DisplayState>& displays, 1662 uint32_t flags) 1663{ 1664 Mutex::Autolock _l(mStateLock); 1665 uint32_t transactionFlags = 0; 1666 1667 size_t count = displays.size(); 1668 for (size_t i=0 ; i<count ; i++) { 1669 const DisplayState& s(displays[i]); 1670 transactionFlags |= setDisplayStateLocked(s); 1671 } 1672 1673 count = state.size(); 1674 for (size_t i=0 ; i<count ; i++) { 1675 const ComposerState& s(state[i]); 1676 sp<Client> client( static_cast<Client *>(s.client.get()) ); 1677 transactionFlags |= setClientStateLocked(client, s.state); 1678 } 1679 1680 if (transactionFlags) { 1681 // this triggers the transaction 1682 setTransactionFlags(transactionFlags); 1683 1684 // if this is a synchronous transaction, wait for it to take effect 1685 // before returning. 1686 if (flags & eSynchronous) { 1687 mTransationPending = true; 1688 } 1689 while (mTransationPending) { 1690 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5)); 1691 if (CC_UNLIKELY(err != NO_ERROR)) { 1692 // just in case something goes wrong in SF, return to the 1693 // called after a few seconds. 1694 ALOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!"); 1695 mTransationPending = false; 1696 break; 1697 } 1698 } 1699 } 1700} 1701 1702uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) 1703{ 1704 uint32_t flags = 0; 1705 DisplayDeviceState& disp(mCurrentState.displays.editValueFor(s.token)); 1706 if (disp.isValid()) { 1707 const uint32_t what = s.what; 1708 if (what & DisplayState::eSurfaceChanged) { 1709 if (disp.surface->asBinder() != s.surface->asBinder()) { 1710 disp.surface = s.surface; 1711 flags |= eDisplayTransactionNeeded; 1712 } 1713 } 1714 if (what & DisplayState::eLayerStackChanged) { 1715 if (disp.layerStack != s.layerStack) { 1716 disp.layerStack = s.layerStack; 1717 flags |= eDisplayTransactionNeeded; 1718 } 1719 } 1720 if (what & DisplayState::eDisplayProjectionChanged) { 1721 if (disp.orientation != s.orientation) { 1722 disp.orientation = s.orientation; 1723 flags |= eDisplayTransactionNeeded; 1724 } 1725 if (disp.frame != s.frame) { 1726 disp.frame = s.frame; 1727 flags |= eDisplayTransactionNeeded; 1728 } 1729 if (disp.viewport != s.viewport) { 1730 disp.viewport = s.viewport; 1731 flags |= eDisplayTransactionNeeded; 1732 } 1733 } 1734 } 1735 return flags; 1736} 1737 1738uint32_t SurfaceFlinger::setClientStateLocked( 1739 const sp<Client>& client, 1740 const layer_state_t& s) 1741{ 1742 uint32_t flags = 0; 1743 sp<LayerBaseClient> layer(client->getLayerUser(s.surface)); 1744 if (layer != 0) { 1745 const uint32_t what = s.what; 1746 if (what & layer_state_t::ePositionChanged) { 1747 if (layer->setPosition(s.x, s.y)) 1748 flags |= eTraversalNeeded; 1749 } 1750 if (what & layer_state_t::eLayerChanged) { 1751 // NOTE: index needs to be calculated before we update the state 1752 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); 1753 if (layer->setLayer(s.z)) { 1754 mCurrentState.layersSortedByZ.removeAt(idx); 1755 mCurrentState.layersSortedByZ.add(layer); 1756 // we need traversal (state changed) 1757 // AND transaction (list changed) 1758 flags |= eTransactionNeeded|eTraversalNeeded; 1759 } 1760 } 1761 if (what & layer_state_t::eSizeChanged) { 1762 if (layer->setSize(s.w, s.h)) { 1763 flags |= eTraversalNeeded; 1764 } 1765 } 1766 if (what & layer_state_t::eAlphaChanged) { 1767 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f))) 1768 flags |= eTraversalNeeded; 1769 } 1770 if (what & layer_state_t::eMatrixChanged) { 1771 if (layer->setMatrix(s.matrix)) 1772 flags |= eTraversalNeeded; 1773 } 1774 if (what & layer_state_t::eTransparentRegionChanged) { 1775 if (layer->setTransparentRegionHint(s.transparentRegion)) 1776 flags |= eTraversalNeeded; 1777 } 1778 if (what & layer_state_t::eVisibilityChanged) { 1779 if (layer->setFlags(s.flags, s.mask)) 1780 flags |= eTraversalNeeded; 1781 } 1782 if (what & layer_state_t::eCropChanged) { 1783 if (layer->setCrop(s.crop)) 1784 flags |= eTraversalNeeded; 1785 } 1786 if (what & layer_state_t::eLayerStackChanged) { 1787 // NOTE: index needs to be calculated before we update the state 1788 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); 1789 if (layer->setLayerStack(s.layerStack)) { 1790 mCurrentState.layersSortedByZ.removeAt(idx); 1791 mCurrentState.layersSortedByZ.add(layer); 1792 // we need traversal (state changed) 1793 // AND transaction (list changed) 1794 flags |= eTransactionNeeded|eTraversalNeeded; 1795 } 1796 } 1797 } 1798 return flags; 1799} 1800 1801sp<ISurface> SurfaceFlinger::createLayer( 1802 ISurfaceComposerClient::surface_data_t* params, 1803 const String8& name, 1804 const sp<Client>& client, 1805 uint32_t w, uint32_t h, PixelFormat format, 1806 uint32_t flags) 1807{ 1808 sp<LayerBaseClient> layer; 1809 sp<ISurface> surfaceHandle; 1810 1811 if (int32_t(w|h) < 0) { 1812 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)", 1813 int(w), int(h)); 1814 return surfaceHandle; 1815 } 1816 1817 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string()); 1818 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) { 1819 case ISurfaceComposerClient::eFXSurfaceNormal: 1820 layer = createNormalLayer(client, w, h, flags, format); 1821 break; 1822 case ISurfaceComposerClient::eFXSurfaceBlur: 1823 case ISurfaceComposerClient::eFXSurfaceDim: 1824 layer = createDimLayer(client, w, h, flags); 1825 break; 1826 case ISurfaceComposerClient::eFXSurfaceScreenshot: 1827 layer = createScreenshotLayer(client, w, h, flags); 1828 break; 1829 } 1830 1831 if (layer != 0) { 1832 layer->initStates(w, h, flags); 1833 layer->setName(name); 1834 ssize_t token = addClientLayer(client, layer); 1835 surfaceHandle = layer->getSurface(); 1836 if (surfaceHandle != 0) { 1837 params->token = token; 1838 params->identity = layer->getIdentity(); 1839 } 1840 setTransactionFlags(eTransactionNeeded); 1841 } 1842 1843 return surfaceHandle; 1844} 1845 1846sp<Layer> SurfaceFlinger::createNormalLayer( 1847 const sp<Client>& client, 1848 uint32_t w, uint32_t h, uint32_t flags, 1849 PixelFormat& format) 1850{ 1851 // initialize the surfaces 1852 switch (format) { 1853 case PIXEL_FORMAT_TRANSPARENT: 1854 case PIXEL_FORMAT_TRANSLUCENT: 1855 format = PIXEL_FORMAT_RGBA_8888; 1856 break; 1857 case PIXEL_FORMAT_OPAQUE: 1858#ifdef NO_RGBX_8888 1859 format = PIXEL_FORMAT_RGB_565; 1860#else 1861 format = PIXEL_FORMAT_RGBX_8888; 1862#endif 1863 break; 1864 } 1865 1866#ifdef NO_RGBX_8888 1867 if (format == PIXEL_FORMAT_RGBX_8888) 1868 format = PIXEL_FORMAT_RGBA_8888; 1869#endif 1870 1871 sp<Layer> layer = new Layer(this, client); 1872 status_t err = layer->setBuffers(w, h, format, flags); 1873 if (CC_LIKELY(err != NO_ERROR)) { 1874 ALOGE("createNormalLayer() failed (%s)", strerror(-err)); 1875 layer.clear(); 1876 } 1877 return layer; 1878} 1879 1880sp<LayerDim> SurfaceFlinger::createDimLayer( 1881 const sp<Client>& client, 1882 uint32_t w, uint32_t h, uint32_t flags) 1883{ 1884 sp<LayerDim> layer = new LayerDim(this, client); 1885 return layer; 1886} 1887 1888sp<LayerScreenshot> SurfaceFlinger::createScreenshotLayer( 1889 const sp<Client>& client, 1890 uint32_t w, uint32_t h, uint32_t flags) 1891{ 1892 sp<LayerScreenshot> layer = new LayerScreenshot(this, client); 1893 return layer; 1894} 1895 1896status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, SurfaceID sid) 1897{ 1898 /* 1899 * called by the window manager, when a surface should be marked for 1900 * destruction. 1901 * 1902 * The surface is removed from the current and drawing lists, but placed 1903 * in the purgatory queue, so it's not destroyed right-away (we need 1904 * to wait for all client's references to go away first). 1905 */ 1906 1907 status_t err = NAME_NOT_FOUND; 1908 Mutex::Autolock _l(mStateLock); 1909 sp<LayerBaseClient> layer = client->getLayerUser(sid); 1910 1911 if (layer != 0) { 1912 err = purgatorizeLayer_l(layer); 1913 if (err == NO_ERROR) { 1914 setTransactionFlags(eTransactionNeeded); 1915 } 1916 } 1917 return err; 1918} 1919 1920status_t SurfaceFlinger::onLayerDestroyed(const wp<LayerBaseClient>& layer) 1921{ 1922 // called by ~ISurface() when all references are gone 1923 status_t err = NO_ERROR; 1924 sp<LayerBaseClient> l(layer.promote()); 1925 if (l != NULL) { 1926 Mutex::Autolock _l(mStateLock); 1927 err = removeLayer_l(l); 1928 if (err == NAME_NOT_FOUND) { 1929 // The surface wasn't in the current list, which means it was 1930 // removed already, which means it is in the purgatory, 1931 // and need to be removed from there. 1932 ssize_t idx = mLayerPurgatory.remove(l); 1933 ALOGE_IF(idx < 0, 1934 "layer=%p is not in the purgatory list", l.get()); 1935 } 1936 ALOGE_IF(err<0 && err != NAME_NOT_FOUND, 1937 "error removing layer=%p (%s)", l.get(), strerror(-err)); 1938 } 1939 return err; 1940} 1941 1942// --------------------------------------------------------------------------- 1943 1944void SurfaceFlinger::onInitializeDisplays() { 1945 // reset screen orientation 1946 Vector<ComposerState> state; 1947 Vector<DisplayState> displays; 1948 DisplayState d; 1949 d.what = DisplayState::eDisplayProjectionChanged; 1950 d.token = mDefaultDisplays[DisplayDevice::DISPLAY_PRIMARY]; 1951 d.orientation = DisplayState::eOrientationDefault; 1952 d.frame.makeInvalid(); 1953 d.viewport.makeInvalid(); 1954 displays.add(d); 1955 setTransactionState(state, displays, 0); 1956 onScreenAcquired(getDefaultDisplayDevice()); 1957} 1958 1959void SurfaceFlinger::initializeDisplays() { 1960 class MessageScreenInitialized : public MessageBase { 1961 SurfaceFlinger* flinger; 1962 public: 1963 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { } 1964 virtual bool handler() { 1965 flinger->onInitializeDisplays(); 1966 return true; 1967 } 1968 }; 1969 sp<MessageBase> msg = new MessageScreenInitialized(this); 1970 postMessageAsync(msg); // we may be called from main thread, use async message 1971} 1972 1973 1974void SurfaceFlinger::onScreenAcquired(const sp<const DisplayDevice>& hw) { 1975 ALOGD("Screen about to return, flinger = %p", this); 1976 getHwComposer().acquire(); 1977 hw->acquireScreen(); 1978 if (hw->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) { 1979 // FIXME: eventthread only knows about the main display right now 1980 mEventThread->onScreenAcquired(); 1981 } 1982 mVisibleRegionsDirty = true; 1983 repaintEverything(); 1984} 1985 1986void SurfaceFlinger::onScreenReleased(const sp<const DisplayDevice>& hw) { 1987 ALOGD("About to give-up screen, flinger = %p", this); 1988 if (hw->isScreenAcquired()) { 1989 if (hw->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) { 1990 // FIXME: eventthread only knows about the main display right now 1991 mEventThread->onScreenReleased(); 1992 } 1993 hw->releaseScreen(); 1994 getHwComposer().release(); 1995 mVisibleRegionsDirty = true; 1996 // from this point on, SF will stop drawing 1997 } 1998} 1999 2000void SurfaceFlinger::unblank() { 2001 class MessageScreenAcquired : public MessageBase { 2002 SurfaceFlinger* flinger; 2003 public: 2004 MessageScreenAcquired(SurfaceFlinger* flinger) : flinger(flinger) { } 2005 virtual bool handler() { 2006 // FIXME: should this be per-display? 2007 flinger->onScreenAcquired(flinger->getDefaultDisplayDevice()); 2008 return true; 2009 } 2010 }; 2011 sp<MessageBase> msg = new MessageScreenAcquired(this); 2012 postMessageSync(msg); 2013} 2014 2015void SurfaceFlinger::blank() { 2016 class MessageScreenReleased : public MessageBase { 2017 SurfaceFlinger* flinger; 2018 public: 2019 MessageScreenReleased(SurfaceFlinger* flinger) : flinger(flinger) { } 2020 virtual bool handler() { 2021 // FIXME: should this be per-display? 2022 flinger->onScreenReleased(flinger->getDefaultDisplayDevice()); 2023 return true; 2024 } 2025 }; 2026 sp<MessageBase> msg = new MessageScreenReleased(this); 2027 postMessageSync(msg); 2028} 2029 2030// --------------------------------------------------------------------------- 2031 2032status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args) 2033{ 2034 const size_t SIZE = 4096; 2035 char buffer[SIZE]; 2036 String8 result; 2037 2038 if (!PermissionCache::checkCallingPermission(sDump)) { 2039 snprintf(buffer, SIZE, "Permission Denial: " 2040 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", 2041 IPCThreadState::self()->getCallingPid(), 2042 IPCThreadState::self()->getCallingUid()); 2043 result.append(buffer); 2044 } else { 2045 // Try to get the main lock, but don't insist if we can't 2046 // (this would indicate SF is stuck, but we want to be able to 2047 // print something in dumpsys). 2048 int retry = 3; 2049 while (mStateLock.tryLock()<0 && --retry>=0) { 2050 usleep(1000000); 2051 } 2052 const bool locked(retry >= 0); 2053 if (!locked) { 2054 snprintf(buffer, SIZE, 2055 "SurfaceFlinger appears to be unresponsive, " 2056 "dumping anyways (no locks held)\n"); 2057 result.append(buffer); 2058 } 2059 2060 bool dumpAll = true; 2061 size_t index = 0; 2062 size_t numArgs = args.size(); 2063 if (numArgs) { 2064 if ((index < numArgs) && 2065 (args[index] == String16("--list"))) { 2066 index++; 2067 listLayersLocked(args, index, result, buffer, SIZE); 2068 dumpAll = false; 2069 } 2070 2071 if ((index < numArgs) && 2072 (args[index] == String16("--latency"))) { 2073 index++; 2074 dumpStatsLocked(args, index, result, buffer, SIZE); 2075 dumpAll = false; 2076 } 2077 2078 if ((index < numArgs) && 2079 (args[index] == String16("--latency-clear"))) { 2080 index++; 2081 clearStatsLocked(args, index, result, buffer, SIZE); 2082 dumpAll = false; 2083 } 2084 } 2085 2086 if (dumpAll) { 2087 dumpAllLocked(result, buffer, SIZE); 2088 } 2089 2090 if (locked) { 2091 mStateLock.unlock(); 2092 } 2093 } 2094 write(fd, result.string(), result.size()); 2095 return NO_ERROR; 2096} 2097 2098void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index, 2099 String8& result, char* buffer, size_t SIZE) const 2100{ 2101 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2102 const size_t count = currentLayers.size(); 2103 for (size_t i=0 ; i<count ; i++) { 2104 const sp<LayerBase>& layer(currentLayers[i]); 2105 snprintf(buffer, SIZE, "%s\n", layer->getName().string()); 2106 result.append(buffer); 2107 } 2108} 2109 2110void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index, 2111 String8& result, char* buffer, size_t SIZE) const 2112{ 2113 String8 name; 2114 if (index < args.size()) { 2115 name = String8(args[index]); 2116 index++; 2117 } 2118 2119 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2120 const size_t count = currentLayers.size(); 2121 for (size_t i=0 ; i<count ; i++) { 2122 const sp<LayerBase>& layer(currentLayers[i]); 2123 if (name.isEmpty()) { 2124 snprintf(buffer, SIZE, "%s\n", layer->getName().string()); 2125 result.append(buffer); 2126 } 2127 if (name.isEmpty() || (name == layer->getName())) { 2128 layer->dumpStats(result, buffer, SIZE); 2129 } 2130 } 2131} 2132 2133void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index, 2134 String8& result, char* buffer, size_t SIZE) const 2135{ 2136 String8 name; 2137 if (index < args.size()) { 2138 name = String8(args[index]); 2139 index++; 2140 } 2141 2142 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2143 const size_t count = currentLayers.size(); 2144 for (size_t i=0 ; i<count ; i++) { 2145 const sp<LayerBase>& layer(currentLayers[i]); 2146 if (name.isEmpty() || (name == layer->getName())) { 2147 layer->clearStats(); 2148 } 2149 } 2150} 2151 2152/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result) 2153{ 2154 static const char* config = 2155 " [sf" 2156#ifdef NO_RGBX_8888 2157 " NO_RGBX_8888" 2158#endif 2159#ifdef HAS_CONTEXT_PRIORITY 2160 " HAS_CONTEXT_PRIORITY" 2161#endif 2162#ifdef NEVER_DEFAULT_TO_ASYNC_MODE 2163 " NEVER_DEFAULT_TO_ASYNC_MODE" 2164#endif 2165#ifdef TARGET_DISABLE_TRIPLE_BUFFERING 2166 " TARGET_DISABLE_TRIPLE_BUFFERING" 2167#endif 2168 "]"; 2169 result.append(config); 2170} 2171 2172void SurfaceFlinger::dumpAllLocked( 2173 String8& result, char* buffer, size_t SIZE) const 2174{ 2175 // figure out if we're stuck somewhere 2176 const nsecs_t now = systemTime(); 2177 const nsecs_t inSwapBuffers(mDebugInSwapBuffers); 2178 const nsecs_t inTransaction(mDebugInTransaction); 2179 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0; 2180 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0; 2181 2182 /* 2183 * Dump library configuration. 2184 */ 2185 result.append("Build configuration:"); 2186 appendSfConfigString(result); 2187 appendUiConfigString(result); 2188 appendGuiConfigString(result); 2189 result.append("\n"); 2190 2191 /* 2192 * Dump the visible layer list 2193 */ 2194 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2195 const size_t count = currentLayers.size(); 2196 snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count); 2197 result.append(buffer); 2198 for (size_t i=0 ; i<count ; i++) { 2199 const sp<LayerBase>& layer(currentLayers[i]); 2200 layer->dump(result, buffer, SIZE); 2201 } 2202 2203 /* 2204 * Dump the layers in the purgatory 2205 */ 2206 2207 const size_t purgatorySize = mLayerPurgatory.size(); 2208 snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize); 2209 result.append(buffer); 2210 for (size_t i=0 ; i<purgatorySize ; i++) { 2211 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i)); 2212 layer->shortDump(result, buffer, SIZE); 2213 } 2214 2215 /* 2216 * Dump Display state 2217 */ 2218 2219 snprintf(buffer, SIZE, "Displays (%d entries)\n", mDisplays.size()); 2220 result.append(buffer); 2221 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 2222 const sp<const DisplayDevice>& hw(mDisplays[dpy]); 2223 hw->dump(result, buffer, SIZE); 2224 } 2225 2226 /* 2227 * Dump SurfaceFlinger global state 2228 */ 2229 2230 snprintf(buffer, SIZE, "SurfaceFlinger global state:\n"); 2231 result.append(buffer); 2232 2233 HWComposer& hwc(getHwComposer()); 2234 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 2235 const GLExtensions& extensions(GLExtensions::getInstance()); 2236 snprintf(buffer, SIZE, "GLES: %s, %s, %s\n", 2237 extensions.getVendor(), 2238 extensions.getRenderer(), 2239 extensions.getVersion()); 2240 result.append(buffer); 2241 2242 snprintf(buffer, SIZE, "EGL : %s\n", 2243 eglQueryString(mEGLDisplay, EGL_VERSION_HW_ANDROID)); 2244 result.append(buffer); 2245 2246 snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension()); 2247 result.append(buffer); 2248 2249 hw->undefinedRegion.dump(result, "undefinedRegion"); 2250 snprintf(buffer, SIZE, 2251 " orientation=%d, canDraw=%d\n", 2252 hw->getOrientation(), hw->canDraw()); 2253 result.append(buffer); 2254 snprintf(buffer, SIZE, 2255 " last eglSwapBuffers() time: %f us\n" 2256 " last transaction time : %f us\n" 2257 " transaction-flags : %08x\n" 2258 " refresh-rate : %f fps\n" 2259 " x-dpi : %f\n" 2260 " y-dpi : %f\n", 2261 mLastSwapBufferTime/1000.0, 2262 mLastTransactionTime/1000.0, 2263 mTransactionFlags, 2264 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY), 2265 hwc.getDpiX(HWC_DISPLAY_PRIMARY), 2266 hwc.getDpiY(HWC_DISPLAY_PRIMARY)); 2267 result.append(buffer); 2268 2269 snprintf(buffer, SIZE, " eglSwapBuffers time: %f us\n", 2270 inSwapBuffersDuration/1000.0); 2271 result.append(buffer); 2272 2273 snprintf(buffer, SIZE, " transaction time: %f us\n", 2274 inTransactionDuration/1000.0); 2275 result.append(buffer); 2276 2277 /* 2278 * VSYNC state 2279 */ 2280 mEventThread->dump(result, buffer, SIZE); 2281 2282 /* 2283 * Dump HWComposer state 2284 */ 2285 snprintf(buffer, SIZE, "h/w composer state:\n"); 2286 result.append(buffer); 2287 snprintf(buffer, SIZE, " h/w composer %s and %s\n", 2288 hwc.initCheck()==NO_ERROR ? "present" : "not present", 2289 (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled"); 2290 result.append(buffer); 2291 hwc.dump(result, buffer, SIZE, hw->getVisibleLayersSortedByZ()); 2292 2293 /* 2294 * Dump gralloc state 2295 */ 2296 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get()); 2297 alloc.dump(result); 2298} 2299 2300bool SurfaceFlinger::startDdmConnection() 2301{ 2302 void* libddmconnection_dso = 2303 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW); 2304 if (!libddmconnection_dso) { 2305 return false; 2306 } 2307 void (*DdmConnection_start)(const char* name); 2308 DdmConnection_start = 2309 (typeof DdmConnection_start)dlsym(libddmconnection_dso, "DdmConnection_start"); 2310 if (!DdmConnection_start) { 2311 dlclose(libddmconnection_dso); 2312 return false; 2313 } 2314 (*DdmConnection_start)(getServiceName()); 2315 return true; 2316} 2317 2318status_t SurfaceFlinger::onTransact( 2319 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 2320{ 2321 switch (code) { 2322 case CREATE_CONNECTION: 2323 case SET_TRANSACTION_STATE: 2324 case BOOT_FINISHED: 2325 case BLANK: 2326 case UNBLANK: 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(sAccessSurfaceFlinger, pid, uid)) { 2334 ALOGE("Permission Denial: " 2335 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 2336 return PERMISSION_DENIED; 2337 } 2338 break; 2339 } 2340 case CAPTURE_SCREEN: 2341 { 2342 // codes that require permission check 2343 IPCThreadState* ipc = IPCThreadState::self(); 2344 const int pid = ipc->getCallingPid(); 2345 const int uid = ipc->getCallingUid(); 2346 if ((uid != AID_GRAPHICS) && 2347 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) { 2348 ALOGE("Permission Denial: " 2349 "can't read framebuffer pid=%d, uid=%d", pid, uid); 2350 return PERMISSION_DENIED; 2351 } 2352 break; 2353 } 2354 } 2355 2356 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags); 2357 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) { 2358 CHECK_INTERFACE(ISurfaceComposer, data, reply); 2359 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) { 2360 IPCThreadState* ipc = IPCThreadState::self(); 2361 const int pid = ipc->getCallingPid(); 2362 const int uid = ipc->getCallingUid(); 2363 ALOGE("Permission Denial: " 2364 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 2365 return PERMISSION_DENIED; 2366 } 2367 int n; 2368 switch (code) { 2369 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE 2370 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE 2371 return NO_ERROR; 2372 case 1002: // SHOW_UPDATES 2373 n = data.readInt32(); 2374 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1); 2375 invalidateHwcGeometry(); 2376 repaintEverything(); 2377 return NO_ERROR; 2378 case 1004:{ // repaint everything 2379 repaintEverything(); 2380 return NO_ERROR; 2381 } 2382 case 1005:{ // force transaction 2383 setTransactionFlags( 2384 eTransactionNeeded| 2385 eDisplayTransactionNeeded| 2386 eTraversalNeeded); 2387 return NO_ERROR; 2388 } 2389 case 1006:{ // send empty update 2390 signalRefresh(); 2391 return NO_ERROR; 2392 } 2393 case 1008: // toggle use of hw composer 2394 n = data.readInt32(); 2395 mDebugDisableHWC = n ? 1 : 0; 2396 invalidateHwcGeometry(); 2397 repaintEverything(); 2398 return NO_ERROR; 2399 case 1009: // toggle use of transform hint 2400 n = data.readInt32(); 2401 mDebugDisableTransformHint = n ? 1 : 0; 2402 invalidateHwcGeometry(); 2403 repaintEverything(); 2404 return NO_ERROR; 2405 case 1010: // interrogate. 2406 reply->writeInt32(0); 2407 reply->writeInt32(0); 2408 reply->writeInt32(mDebugRegion); 2409 reply->writeInt32(0); 2410 reply->writeInt32(mDebugDisableHWC); 2411 return NO_ERROR; 2412 case 1013: { 2413 Mutex::Autolock _l(mStateLock); 2414 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 2415 reply->writeInt32(hw->getPageFlipCount()); 2416 } 2417 return NO_ERROR; 2418 } 2419 } 2420 return err; 2421} 2422 2423void SurfaceFlinger::repaintEverything() { 2424 android_atomic_or(1, &mRepaintEverything); 2425 signalTransaction(); 2426} 2427 2428// --------------------------------------------------------------------------- 2429 2430status_t SurfaceFlinger::renderScreenToTexture(uint32_t layerStack, 2431 GLuint* textureName, GLfloat* uOut, GLfloat* vOut) 2432{ 2433 Mutex::Autolock _l(mStateLock); 2434 return renderScreenToTextureLocked(layerStack, textureName, uOut, vOut); 2435} 2436 2437status_t SurfaceFlinger::renderScreenToTextureLocked(uint32_t layerStack, 2438 GLuint* textureName, GLfloat* uOut, GLfloat* vOut) 2439{ 2440 ATRACE_CALL(); 2441 2442 if (!GLExtensions::getInstance().haveFramebufferObject()) 2443 return INVALID_OPERATION; 2444 2445 // get screen geometry 2446 // FIXME: figure out what it means to have a screenshot texture w/ multi-display 2447 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 2448 const uint32_t hw_w = hw->getWidth(); 2449 const uint32_t hw_h = hw->getHeight(); 2450 GLfloat u = 1; 2451 GLfloat v = 1; 2452 2453 // make sure to clear all GL error flags 2454 while ( glGetError() != GL_NO_ERROR ) ; 2455 2456 // create a FBO 2457 GLuint name, tname; 2458 glGenTextures(1, &tname); 2459 glBindTexture(GL_TEXTURE_2D, tname); 2460 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 2461 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 2462 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2463 hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); 2464 if (glGetError() != GL_NO_ERROR) { 2465 while ( glGetError() != GL_NO_ERROR ) ; 2466 GLint tw = (2 << (31 - clz(hw_w))); 2467 GLint th = (2 << (31 - clz(hw_h))); 2468 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2469 tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); 2470 u = GLfloat(hw_w) / tw; 2471 v = GLfloat(hw_h) / th; 2472 } 2473 glGenFramebuffersOES(1, &name); 2474 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name); 2475 glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES, 2476 GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0); 2477 2478 // redraw the screen entirely... 2479 glDisable(GL_TEXTURE_EXTERNAL_OES); 2480 glDisable(GL_TEXTURE_2D); 2481 glClearColor(0,0,0,1); 2482 glClear(GL_COLOR_BUFFER_BIT); 2483 glMatrixMode(GL_MODELVIEW); 2484 glLoadIdentity(); 2485 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ()); 2486 const size_t count = layers.size(); 2487 for (size_t i=0 ; i<count ; ++i) { 2488 const sp<LayerBase>& layer(layers[i]); 2489 layer->draw(hw); 2490 } 2491 2492 hw->compositionComplete(); 2493 2494 // back to main framebuffer 2495 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); 2496 glDeleteFramebuffersOES(1, &name); 2497 2498 *textureName = tname; 2499 *uOut = u; 2500 *vOut = v; 2501 return NO_ERROR; 2502} 2503 2504// --------------------------------------------------------------------------- 2505 2506status_t SurfaceFlinger::captureScreenImplLocked(const sp<IBinder>& display, 2507 sp<IMemoryHeap>* heap, 2508 uint32_t* w, uint32_t* h, PixelFormat* f, 2509 uint32_t sw, uint32_t sh, 2510 uint32_t minLayerZ, uint32_t maxLayerZ) 2511{ 2512 ATRACE_CALL(); 2513 2514 status_t result = PERMISSION_DENIED; 2515 2516 if (!GLExtensions::getInstance().haveFramebufferObject()) { 2517 return INVALID_OPERATION; 2518 } 2519 2520 // get screen geometry 2521 sp<const DisplayDevice> hw(getDisplayDevice(display)); 2522 const uint32_t hw_w = hw->getWidth(); 2523 const uint32_t hw_h = hw->getHeight(); 2524 2525 // if we have secure windows on this display, never allow the screen capture 2526 if (hw->getSecureLayerVisible()) { 2527 ALOGW("FB is protected: PERMISSION_DENIED"); 2528 return PERMISSION_DENIED; 2529 } 2530 2531 if ((sw > hw_w) || (sh > hw_h)) { 2532 ALOGE("size mismatch (%d, %d) > (%d, %d)", sw, sh, hw_w, hw_h); 2533 return BAD_VALUE; 2534 } 2535 2536 sw = (!sw) ? hw_w : sw; 2537 sh = (!sh) ? hw_h : sh; 2538 const size_t size = sw * sh * 4; 2539 const bool filtering = sw != hw_w || sh != hw_h; 2540 2541// ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d", 2542// sw, sh, minLayerZ, maxLayerZ); 2543 2544 // make sure to clear all GL error flags 2545 while ( glGetError() != GL_NO_ERROR ) ; 2546 2547 // create a FBO 2548 GLuint name, tname; 2549 glGenRenderbuffersOES(1, &tname); 2550 glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname); 2551 glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh); 2552 2553 glGenFramebuffersOES(1, &name); 2554 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name); 2555 glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, 2556 GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname); 2557 2558 GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES); 2559 2560 if (status == GL_FRAMEBUFFER_COMPLETE_OES) { 2561 2562 // invert everything, b/c glReadPixel() below will invert the FB 2563 glViewport(0, 0, sw, sh); 2564 glMatrixMode(GL_PROJECTION); 2565 glPushMatrix(); 2566 glLoadIdentity(); 2567 glOrthof(0, hw_w, hw_h, 0, 0, 1); 2568 glMatrixMode(GL_MODELVIEW); 2569 2570 // redraw the screen entirely... 2571 glClearColor(0,0,0,1); 2572 glClear(GL_COLOR_BUFFER_BIT); 2573 2574 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ()); 2575 const size_t count = layers.size(); 2576 for (size_t i=0 ; i<count ; ++i) { 2577 const sp<LayerBase>& layer(layers[i]); 2578 const uint32_t z = layer->drawingState().z; 2579 if (z >= minLayerZ && z <= maxLayerZ) { 2580 if (filtering) layer->setFiltering(true); 2581 layer->draw(hw); 2582 if (filtering) layer->setFiltering(false); 2583 } 2584 } 2585 2586 // check for errors and return screen capture 2587 if (glGetError() != GL_NO_ERROR) { 2588 // error while rendering 2589 result = INVALID_OPERATION; 2590 } else { 2591 // allocate shared memory large enough to hold the 2592 // screen capture 2593 sp<MemoryHeapBase> base( 2594 new MemoryHeapBase(size, 0, "screen-capture") ); 2595 void* const ptr = base->getBase(); 2596 if (ptr != MAP_FAILED) { 2597 // capture the screen with glReadPixels() 2598 ScopedTrace _t(ATRACE_TAG, "glReadPixels"); 2599 glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr); 2600 if (glGetError() == GL_NO_ERROR) { 2601 *heap = base; 2602 *w = sw; 2603 *h = sh; 2604 *f = PIXEL_FORMAT_RGBA_8888; 2605 result = NO_ERROR; 2606 } 2607 } else { 2608 result = NO_MEMORY; 2609 } 2610 } 2611 glViewport(0, 0, hw_w, hw_h); 2612 glMatrixMode(GL_PROJECTION); 2613 glPopMatrix(); 2614 glMatrixMode(GL_MODELVIEW); 2615 } else { 2616 result = BAD_VALUE; 2617 } 2618 2619 // release FBO resources 2620 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); 2621 glDeleteRenderbuffersOES(1, &tname); 2622 glDeleteFramebuffersOES(1, &name); 2623 2624 hw->compositionComplete(); 2625 2626// ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK"); 2627 2628 return result; 2629} 2630 2631 2632status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, 2633 sp<IMemoryHeap>* heap, 2634 uint32_t* width, uint32_t* height, PixelFormat* format, 2635 uint32_t sw, uint32_t sh, 2636 uint32_t minLayerZ, uint32_t maxLayerZ) 2637{ 2638 if (CC_UNLIKELY(display == 0)) 2639 return BAD_VALUE; 2640 2641 if (!GLExtensions::getInstance().haveFramebufferObject()) 2642 return INVALID_OPERATION; 2643 2644 class MessageCaptureScreen : public MessageBase { 2645 SurfaceFlinger* flinger; 2646 sp<IBinder> display; 2647 sp<IMemoryHeap>* heap; 2648 uint32_t* w; 2649 uint32_t* h; 2650 PixelFormat* f; 2651 uint32_t sw; 2652 uint32_t sh; 2653 uint32_t minLayerZ; 2654 uint32_t maxLayerZ; 2655 status_t result; 2656 public: 2657 MessageCaptureScreen(SurfaceFlinger* flinger, const sp<IBinder>& display, 2658 sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f, 2659 uint32_t sw, uint32_t sh, 2660 uint32_t minLayerZ, uint32_t maxLayerZ) 2661 : flinger(flinger), display(display), 2662 heap(heap), w(w), h(h), f(f), sw(sw), sh(sh), 2663 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ), 2664 result(PERMISSION_DENIED) 2665 { 2666 } 2667 status_t getResult() const { 2668 return result; 2669 } 2670 virtual bool handler() { 2671 Mutex::Autolock _l(flinger->mStateLock); 2672 result = flinger->captureScreenImplLocked(display, 2673 heap, w, h, f, sw, sh, minLayerZ, maxLayerZ); 2674 return true; 2675 } 2676 }; 2677 2678 sp<MessageBase> msg = new MessageCaptureScreen(this, 2679 display, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ); 2680 status_t res = postMessageSync(msg); 2681 if (res == NO_ERROR) { 2682 res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult(); 2683 } 2684 return res; 2685} 2686 2687// --------------------------------------------------------------------------- 2688 2689SurfaceFlinger::LayerVector::LayerVector() { 2690} 2691 2692SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs) 2693 : SortedVector<sp<LayerBase> >(rhs) { 2694} 2695 2696int SurfaceFlinger::LayerVector::do_compare(const void* lhs, 2697 const void* rhs) const 2698{ 2699 // sort layers per layer-stack, then by z-order and finally by sequence 2700 const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs)); 2701 const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs)); 2702 2703 uint32_t ls = l->currentState().layerStack; 2704 uint32_t rs = r->currentState().layerStack; 2705 if (ls != rs) 2706 return ls - rs; 2707 2708 uint32_t lz = l->currentState().z; 2709 uint32_t rz = r->currentState().z; 2710 if (lz != rz) 2711 return lz - rz; 2712 2713 return l->sequence - r->sequence; 2714} 2715 2716// --------------------------------------------------------------------------- 2717 2718SurfaceFlinger::DisplayDeviceState::DisplayDeviceState() 2719 : type(DisplayDevice::DISPLAY_ID_INVALID) { 2720} 2721 2722SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type) 2723 : type(type), layerStack(0), orientation(0) { 2724 viewport.makeInvalid(); 2725 frame.makeInvalid(); 2726} 2727 2728// --------------------------------------------------------------------------- 2729 2730}; // namespace android 2731