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