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