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