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