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