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