SurfaceFlinger.cpp revision 2a23184e4109060ec772763e80dae2132cf9d2eb
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 if (!hwc.supportsFramebufferTarget()) { 931 // EGL spec says: 932 // "surface must be bound to the calling thread's current context, 933 // for the current rendering API." 934 DisplayDevice::makeCurrent(mEGLDisplay, 935 getDefaultDisplayDevice(), mEGLContext); 936 } 937 hwc.commit(); 938 } 939 940 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 941 sp<const DisplayDevice> hw(mDisplays[dpy]); 942 const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ()); 943 hw->onSwapBuffersCompleted(hwc); 944 const size_t count = currentLayers.size(); 945 int32_t id = hw->getHwcDisplayId(); 946 if (id >=0 && hwc.initCheck() == NO_ERROR) { 947 HWComposer::LayerListIterator cur = hwc.begin(id); 948 const HWComposer::LayerListIterator end = hwc.end(id); 949 for (size_t i = 0; cur != end && i < count; ++i, ++cur) { 950 currentLayers[i]->onLayerDisplayed(hw, &*cur); 951 } 952 } else { 953 for (size_t i = 0; i < count; i++) { 954 currentLayers[i]->onLayerDisplayed(hw, NULL); 955 } 956 } 957 } 958 959 mLastSwapBufferTime = systemTime() - now; 960 mDebugInSwapBuffers = 0; 961} 962 963void SurfaceFlinger::handleTransaction(uint32_t transactionFlags) 964{ 965 ATRACE_CALL(); 966 967 Mutex::Autolock _l(mStateLock); 968 const nsecs_t now = systemTime(); 969 mDebugInTransaction = now; 970 971 // Here we're guaranteed that some transaction flags are set 972 // so we can call handleTransactionLocked() unconditionally. 973 // We call getTransactionFlags(), which will also clear the flags, 974 // with mStateLock held to guarantee that mCurrentState won't change 975 // until the transaction is committed. 976 977 transactionFlags = getTransactionFlags(eTransactionMask); 978 handleTransactionLocked(transactionFlags); 979 980 mLastTransactionTime = systemTime() - now; 981 mDebugInTransaction = 0; 982 invalidateHwcGeometry(); 983 // here the transaction has been committed 984} 985 986void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags) 987{ 988 const LayerVector& currentLayers(mCurrentState.layersSortedByZ); 989 const size_t count = currentLayers.size(); 990 991 /* 992 * Traversal of the children 993 * (perform the transaction for each of them if needed) 994 */ 995 996 if (transactionFlags & eTraversalNeeded) { 997 for (size_t i=0 ; i<count ; i++) { 998 const sp<LayerBase>& layer = currentLayers[i]; 999 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded); 1000 if (!trFlags) continue; 1001 1002 const uint32_t flags = layer->doTransaction(0); 1003 if (flags & Layer::eVisibleRegion) 1004 mVisibleRegionsDirty = true; 1005 } 1006 } 1007 1008 /* 1009 * Perform display own transactions if needed 1010 */ 1011 1012 if (transactionFlags & eDisplayTransactionNeeded) { 1013 // here we take advantage of Vector's copy-on-write semantics to 1014 // improve performance by skipping the transaction entirely when 1015 // know that the lists are identical 1016 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays); 1017 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays); 1018 if (!curr.isIdenticalTo(draw)) { 1019 mVisibleRegionsDirty = true; 1020 const size_t cc = curr.size(); 1021 size_t dc = draw.size(); 1022 1023 // find the displays that were removed 1024 // (ie: in drawing state but not in current state) 1025 // also handle displays that changed 1026 // (ie: displays that are in both lists) 1027 for (size_t i=0 ; i<dc ; i++) { 1028 const ssize_t j = curr.indexOfKey(draw.keyAt(i)); 1029 if (j < 0) { 1030 // in drawing state but not in current state 1031 if (!draw[i].isMainDisplay()) { 1032 mDisplays.removeItem(draw.keyAt(i)); 1033 } else { 1034 ALOGW("trying to remove the main display"); 1035 } 1036 } else { 1037 // this display is in both lists. see if something changed. 1038 const DisplayDeviceState& state(curr[j]); 1039 const wp<IBinder>& display(curr.keyAt(j)); 1040 if (state.surface->asBinder() != draw[i].surface->asBinder()) { 1041 // changing the surface is like destroying and 1042 // recreating the DisplayDevice, so we just remove it 1043 // from the drawing state, so that it get re-added 1044 // below. 1045 mDisplays.removeItem(display); 1046 mDrawingState.displays.removeItemsAt(i); 1047 dc--; i--; 1048 // at this point we must loop to the next item 1049 continue; 1050 } 1051 1052 const sp<DisplayDevice>& disp(getDisplayDevice(display)); 1053 if (disp != NULL) { 1054 if (state.layerStack != draw[i].layerStack) { 1055 disp->setLayerStack(state.layerStack); 1056 } 1057 if ((state.orientation != draw[i].orientation) 1058 || (state.viewport != draw[i].viewport) 1059 || (state.frame != draw[i].frame)) 1060 { 1061 disp->setProjection(state.orientation, 1062 state.viewport, state.frame); 1063 } 1064 1065 // Walk through all the layers in currentLayers, 1066 // and update their transform hint. 1067 // 1068 // TODO: we could be much more clever about which 1069 // layers we touch and how often we do these updates 1070 // (e.g. only touch the layers associated with this 1071 // display, and only on a rotation). 1072 for (size_t i = 0; i < count; i++) { 1073 const sp<LayerBase>& layerBase = currentLayers[i]; 1074 layerBase->updateTransformHint(); 1075 } 1076 } 1077 } 1078 } 1079 1080 // find displays that were added 1081 // (ie: in current state but not in drawing state) 1082 for (size_t i=0 ; i<cc ; i++) { 1083 if (draw.indexOfKey(curr.keyAt(i)) < 0) { 1084 const DisplayDeviceState& state(curr[i]); 1085 1086 sp<FramebufferSurface> fbs; 1087 sp<SurfaceTextureClient> stc; 1088 if (!state.isVirtualDisplay()) { 1089 1090 ALOGE_IF(state.surface!=NULL, 1091 "adding a supported display, but rendering " 1092 "surface is provided (%p), ignoring it", 1093 state.surface.get()); 1094 1095 // for supported (by hwc) displays we provide our 1096 // own rendering surface 1097 fbs = new FramebufferSurface(*mHwc, state.type); 1098 stc = new SurfaceTextureClient( 1099 static_cast< sp<ISurfaceTexture> >(fbs->getBufferQueue())); 1100 } else { 1101 if (state.surface != NULL) { 1102 stc = new SurfaceTextureClient(state.surface); 1103 } 1104 } 1105 1106 const wp<IBinder>& display(curr.keyAt(i)); 1107 if (stc != NULL) { 1108 sp<DisplayDevice> hw = new DisplayDevice(this, 1109 state.type, display, stc, fbs, mEGLConfig); 1110 hw->setLayerStack(state.layerStack); 1111 hw->setProjection(state.orientation, 1112 state.viewport, state.frame); 1113 hw->setDisplayName(state.displayName); 1114 mDisplays.add(display, hw); 1115 if (hw->getDisplayType() < DisplayDevice::NUM_DISPLAY_TYPES) { 1116 // notify the system that this display is now up 1117 // (note onScreenAcquired() is safe to call from 1118 // here because we're in the main thread) 1119 onScreenAcquired(hw); 1120 } 1121 } 1122 } 1123 } 1124 } 1125 } 1126 1127 /* 1128 * Perform our own transaction if needed 1129 */ 1130 1131 const LayerVector& previousLayers(mDrawingState.layersSortedByZ); 1132 if (currentLayers.size() > previousLayers.size()) { 1133 // layers have been added 1134 mVisibleRegionsDirty = true; 1135 } 1136 1137 // some layers might have been removed, so 1138 // we need to update the regions they're exposing. 1139 if (mLayersRemoved) { 1140 mLayersRemoved = false; 1141 mVisibleRegionsDirty = true; 1142 const size_t count = previousLayers.size(); 1143 for (size_t i=0 ; i<count ; i++) { 1144 const sp<LayerBase>& layer(previousLayers[i]); 1145 if (currentLayers.indexOf(layer) < 0) { 1146 // this layer is not visible anymore 1147 // TODO: we could traverse the tree from front to back and 1148 // compute the actual visible region 1149 // TODO: we could cache the transformed region 1150 const Layer::State& s(layer->drawingState()); 1151 Region visibleReg = s.transform.transform( 1152 Region(Rect(s.active.w, s.active.h))); 1153 invalidateLayerStack(s.layerStack, visibleReg); 1154 } 1155 } 1156 } 1157 1158 commitTransaction(); 1159} 1160 1161void SurfaceFlinger::commitTransaction() 1162{ 1163 if (!mLayersPendingRemoval.isEmpty()) { 1164 // Notify removed layers now that they can't be drawn from 1165 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) { 1166 mLayersPendingRemoval[i]->onRemoved(); 1167 } 1168 mLayersPendingRemoval.clear(); 1169 } 1170 1171 mDrawingState = mCurrentState; 1172 mTransationPending = false; 1173 mTransactionCV.broadcast(); 1174} 1175 1176void SurfaceFlinger::computeVisibleRegions( 1177 const LayerVector& currentLayers, uint32_t layerStack, 1178 Region& outDirtyRegion, Region& outOpaqueRegion) 1179{ 1180 ATRACE_CALL(); 1181 1182 Region aboveOpaqueLayers; 1183 Region aboveCoveredLayers; 1184 Region dirty; 1185 1186 outDirtyRegion.clear(); 1187 1188 size_t i = currentLayers.size(); 1189 while (i--) { 1190 const sp<LayerBase>& layer = currentLayers[i]; 1191 1192 // start with the whole surface at its current location 1193 const Layer::State& s(layer->drawingState()); 1194 1195 // only consider the layers on the given later stack 1196 if (s.layerStack != layerStack) 1197 continue; 1198 1199 /* 1200 * opaqueRegion: area of a surface that is fully opaque. 1201 */ 1202 Region opaqueRegion; 1203 1204 /* 1205 * visibleRegion: area of a surface that is visible on screen 1206 * and not fully transparent. This is essentially the layer's 1207 * footprint minus the opaque regions above it. 1208 * Areas covered by a translucent surface are considered visible. 1209 */ 1210 Region visibleRegion; 1211 1212 /* 1213 * coveredRegion: area of a surface that is covered by all 1214 * visible regions above it (which includes the translucent areas). 1215 */ 1216 Region coveredRegion; 1217 1218 1219 // handle hidden surfaces by setting the visible region to empty 1220 if (CC_LIKELY(layer->isVisible())) { 1221 const bool translucent = !layer->isOpaque(); 1222 Rect bounds(layer->computeBounds()); 1223 visibleRegion.set(bounds); 1224 if (!visibleRegion.isEmpty()) { 1225 // Remove the transparent area from the visible region 1226 if (translucent) { 1227 Region transparentRegionScreen; 1228 const Transform tr(s.transform); 1229 if (tr.transformed()) { 1230 if (tr.preserveRects()) { 1231 // transform the transparent region 1232 transparentRegionScreen = tr.transform(s.transparentRegion); 1233 } else { 1234 // transformation too complex, can't do the 1235 // transparent region optimization. 1236 transparentRegionScreen.clear(); 1237 } 1238 } else { 1239 transparentRegionScreen = s.transparentRegion; 1240 } 1241 visibleRegion.subtractSelf(transparentRegionScreen); 1242 } 1243 1244 // compute the opaque region 1245 const int32_t layerOrientation = s.transform.getOrientation(); 1246 if (s.alpha==255 && !translucent && 1247 ((layerOrientation & Transform::ROT_INVALID) == false)) { 1248 // the opaque region is the layer's footprint 1249 opaqueRegion = visibleRegion; 1250 } 1251 } 1252 } 1253 1254 // Clip the covered region to the visible region 1255 coveredRegion = aboveCoveredLayers.intersect(visibleRegion); 1256 1257 // Update aboveCoveredLayers for next (lower) layer 1258 aboveCoveredLayers.orSelf(visibleRegion); 1259 1260 // subtract the opaque region covered by the layers above us 1261 visibleRegion.subtractSelf(aboveOpaqueLayers); 1262 1263 // compute this layer's dirty region 1264 if (layer->contentDirty) { 1265 // we need to invalidate the whole region 1266 dirty = visibleRegion; 1267 // as well, as the old visible region 1268 dirty.orSelf(layer->visibleRegion); 1269 layer->contentDirty = false; 1270 } else { 1271 /* compute the exposed region: 1272 * the exposed region consists of two components: 1273 * 1) what's VISIBLE now and was COVERED before 1274 * 2) what's EXPOSED now less what was EXPOSED before 1275 * 1276 * note that (1) is conservative, we start with the whole 1277 * visible region but only keep what used to be covered by 1278 * something -- which mean it may have been exposed. 1279 * 1280 * (2) handles areas that were not covered by anything but got 1281 * exposed because of a resize. 1282 */ 1283 const Region newExposed = visibleRegion - coveredRegion; 1284 const Region oldVisibleRegion = layer->visibleRegion; 1285 const Region oldCoveredRegion = layer->coveredRegion; 1286 const Region oldExposed = oldVisibleRegion - oldCoveredRegion; 1287 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed); 1288 } 1289 dirty.subtractSelf(aboveOpaqueLayers); 1290 1291 // accumulate to the screen dirty region 1292 outDirtyRegion.orSelf(dirty); 1293 1294 // Update aboveOpaqueLayers for next (lower) layer 1295 aboveOpaqueLayers.orSelf(opaqueRegion); 1296 1297 // Store the visible region is screen space 1298 layer->setVisibleRegion(visibleRegion); 1299 layer->setCoveredRegion(coveredRegion); 1300 } 1301 1302 outOpaqueRegion = aboveOpaqueLayers; 1303} 1304 1305void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack, 1306 const Region& dirty) { 1307 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 1308 const sp<DisplayDevice>& hw(mDisplays[dpy]); 1309 if (hw->getLayerStack() == layerStack) { 1310 hw->dirtyRegion.orSelf(dirty); 1311 } 1312 } 1313} 1314 1315void SurfaceFlinger::handlePageFlip() 1316{ 1317 Region dirtyRegion; 1318 1319 bool visibleRegions = false; 1320 const LayerVector& currentLayers(mDrawingState.layersSortedByZ); 1321 const size_t count = currentLayers.size(); 1322 for (size_t i=0 ; i<count ; i++) { 1323 const sp<LayerBase>& layer(currentLayers[i]); 1324 const Region dirty(layer->latchBuffer(visibleRegions)); 1325 const Layer::State& s(layer->drawingState()); 1326 invalidateLayerStack(s.layerStack, dirty); 1327 } 1328 1329 mVisibleRegionsDirty |= visibleRegions; 1330} 1331 1332void SurfaceFlinger::invalidateHwcGeometry() 1333{ 1334 mHwWorkListDirty = true; 1335} 1336 1337 1338void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw, 1339 const Region& inDirtyRegion) 1340{ 1341 Region dirtyRegion(inDirtyRegion); 1342 1343 // compute the invalid region 1344 hw->swapRegion.orSelf(dirtyRegion); 1345 1346 uint32_t flags = hw->getFlags(); 1347 if (flags & DisplayDevice::SWAP_RECTANGLE) { 1348 // we can redraw only what's dirty, but since SWAP_RECTANGLE only 1349 // takes a rectangle, we must make sure to update that whole 1350 // rectangle in that case 1351 dirtyRegion.set(hw->swapRegion.bounds()); 1352 } else { 1353 if (flags & DisplayDevice::PARTIAL_UPDATES) { 1354 // We need to redraw the rectangle that will be updated 1355 // (pushed to the framebuffer). 1356 // This is needed because PARTIAL_UPDATES only takes one 1357 // rectangle instead of a region (see DisplayDevice::flip()) 1358 dirtyRegion.set(hw->swapRegion.bounds()); 1359 } else { 1360 // we need to redraw everything (the whole screen) 1361 dirtyRegion.set(hw->bounds()); 1362 hw->swapRegion = dirtyRegion; 1363 } 1364 } 1365 1366 doComposeSurfaces(hw, dirtyRegion); 1367 1368 // update the swap region and clear the dirty region 1369 hw->swapRegion.orSelf(dirtyRegion); 1370 1371 // swap buffers (presentation) 1372 hw->swapBuffers(getHwComposer()); 1373} 1374 1375void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty) 1376{ 1377 const int32_t id = hw->getHwcDisplayId(); 1378 HWComposer& hwc(getHwComposer()); 1379 HWComposer::LayerListIterator cur = hwc.begin(id); 1380 const HWComposer::LayerListIterator end = hwc.end(id); 1381 1382 const bool hasGlesComposition = hwc.hasGlesComposition(id) || (cur==end); 1383 if (hasGlesComposition) { 1384 DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext); 1385 1386 // set the frame buffer 1387 glMatrixMode(GL_MODELVIEW); 1388 glLoadIdentity(); 1389 1390 // Never touch the framebuffer if we don't have any framebuffer layers 1391 const bool hasHwcComposition = hwc.hasHwcComposition(id); 1392 if (hasHwcComposition) { 1393 // when using overlays, we assume a fully transparent framebuffer 1394 // NOTE: we could reduce how much we need to clear, for instance 1395 // remove where there are opaque FB layers. however, on some 1396 // GPUs doing a "clean slate" glClear might be more efficient. 1397 // We'll revisit later if needed. 1398 glClearColor(0, 0, 0, 0); 1399 glClear(GL_COLOR_BUFFER_BIT); 1400 } else { 1401 const Region region(hw->undefinedRegion.intersect(dirty)); 1402 // screen is already cleared here 1403 if (!region.isEmpty()) { 1404 // can happen with SurfaceView 1405 drawWormhole(hw, region); 1406 } 1407 } 1408 } 1409 1410 /* 1411 * and then, render the layers targeted at the framebuffer 1412 */ 1413 1414 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ()); 1415 const size_t count = layers.size(); 1416 const Transform& tr = hw->getTransform(); 1417 if (cur != end) { 1418 // we're using h/w composer 1419 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) { 1420 const sp<LayerBase>& layer(layers[i]); 1421 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion))); 1422 if (!clip.isEmpty()) { 1423 switch (cur->getCompositionType()) { 1424 case HWC_OVERLAY: { 1425 if ((cur->getHints() & HWC_HINT_CLEAR_FB) 1426 && i 1427 && layer->isOpaque() 1428 && hasGlesComposition) { 1429 // never clear the very first layer since we're 1430 // guaranteed the FB is already cleared 1431 layer->clearWithOpenGL(hw, clip); 1432 } 1433 break; 1434 } 1435 case HWC_FRAMEBUFFER: { 1436 layer->draw(hw, clip); 1437 break; 1438 } 1439 case HWC_FRAMEBUFFER_TARGET: { 1440 // this should not happen as the iterator shouldn't 1441 // let us get there. 1442 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%d)", i); 1443 break; 1444 } 1445 } 1446 } 1447 layer->setAcquireFence(hw, *cur); 1448 } 1449 } else { 1450 // we're not using h/w composer 1451 for (size_t i=0 ; i<count ; ++i) { 1452 const sp<LayerBase>& layer(layers[i]); 1453 const Region clip(dirty.intersect( 1454 tr.transform(layer->visibleRegion))); 1455 if (!clip.isEmpty()) { 1456 layer->draw(hw, clip); 1457 } 1458 } 1459 } 1460} 1461 1462void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, 1463 const Region& region) const 1464{ 1465 glDisable(GL_TEXTURE_EXTERNAL_OES); 1466 glDisable(GL_TEXTURE_2D); 1467 glDisable(GL_BLEND); 1468 glColor4f(0,0,0,0); 1469 1470 const int32_t height = hw->getHeight(); 1471 Region::const_iterator it = region.begin(); 1472 Region::const_iterator const end = region.end(); 1473 while (it != end) { 1474 const Rect& r = *it++; 1475 GLfloat vertices[][2] = { 1476 { r.left, height - r.top }, 1477 { r.left, height - r.bottom }, 1478 { r.right, height - r.bottom }, 1479 { r.right, height - r.top } 1480 }; 1481 glVertexPointer(2, GL_FLOAT, 0, vertices); 1482 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1483 } 1484} 1485 1486ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client, 1487 const sp<LayerBaseClient>& lbc) 1488{ 1489 // attach this layer to the client 1490 size_t name = client->attachLayer(lbc); 1491 1492 // add this layer to the current state list 1493 Mutex::Autolock _l(mStateLock); 1494 mCurrentState.layersSortedByZ.add(lbc); 1495 1496 return ssize_t(name); 1497} 1498 1499status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer) 1500{ 1501 Mutex::Autolock _l(mStateLock); 1502 status_t err = purgatorizeLayer_l(layer); 1503 if (err == NO_ERROR) 1504 setTransactionFlags(eTransactionNeeded); 1505 return err; 1506} 1507 1508status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase) 1509{ 1510 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase); 1511 if (index >= 0) { 1512 mLayersRemoved = true; 1513 return NO_ERROR; 1514 } 1515 return status_t(index); 1516} 1517 1518status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase) 1519{ 1520 // First add the layer to the purgatory list, which makes sure it won't 1521 // go away, then remove it from the main list (through a transaction). 1522 ssize_t err = removeLayer_l(layerBase); 1523 if (err >= 0) { 1524 mLayerPurgatory.add(layerBase); 1525 } 1526 1527 mLayersPendingRemoval.push(layerBase); 1528 1529 // it's possible that we don't find a layer, because it might 1530 // have been destroyed already -- this is not technically an error 1531 // from the user because there is a race between Client::destroySurface(), 1532 // ~Client() and ~ISurface(). 1533 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err; 1534} 1535 1536uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags) 1537{ 1538 return android_atomic_release_load(&mTransactionFlags); 1539} 1540 1541uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) 1542{ 1543 return android_atomic_and(~flags, &mTransactionFlags) & flags; 1544} 1545 1546uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) 1547{ 1548 uint32_t old = android_atomic_or(flags, &mTransactionFlags); 1549 if ((old & flags)==0) { // wake the server up 1550 signalTransaction(); 1551 } 1552 return old; 1553} 1554 1555void SurfaceFlinger::setTransactionState( 1556 const Vector<ComposerState>& state, 1557 const Vector<DisplayState>& displays, 1558 uint32_t flags) 1559{ 1560 Mutex::Autolock _l(mStateLock); 1561 uint32_t transactionFlags = 0; 1562 1563 size_t count = displays.size(); 1564 for (size_t i=0 ; i<count ; i++) { 1565 const DisplayState& s(displays[i]); 1566 transactionFlags |= setDisplayStateLocked(s); 1567 } 1568 1569 count = state.size(); 1570 for (size_t i=0 ; i<count ; i++) { 1571 const ComposerState& s(state[i]); 1572 sp<Client> client( static_cast<Client *>(s.client.get()) ); 1573 transactionFlags |= setClientStateLocked(client, s.state); 1574 } 1575 1576 if (transactionFlags) { 1577 // this triggers the transaction 1578 setTransactionFlags(transactionFlags); 1579 1580 // if this is a synchronous transaction, wait for it to take effect 1581 // before returning. 1582 if (flags & eSynchronous) { 1583 mTransationPending = true; 1584 } 1585 while (mTransationPending) { 1586 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5)); 1587 if (CC_UNLIKELY(err != NO_ERROR)) { 1588 // just in case something goes wrong in SF, return to the 1589 // called after a few seconds. 1590 ALOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!"); 1591 mTransationPending = false; 1592 break; 1593 } 1594 } 1595 } 1596} 1597 1598uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) 1599{ 1600 uint32_t flags = 0; 1601 DisplayDeviceState& disp(mCurrentState.displays.editValueFor(s.token)); 1602 if (disp.isValid()) { 1603 const uint32_t what = s.what; 1604 if (what & DisplayState::eSurfaceChanged) { 1605 if (disp.surface->asBinder() != s.surface->asBinder()) { 1606 disp.surface = s.surface; 1607 flags |= eDisplayTransactionNeeded; 1608 } 1609 } 1610 if (what & DisplayState::eLayerStackChanged) { 1611 if (disp.layerStack != s.layerStack) { 1612 disp.layerStack = s.layerStack; 1613 flags |= eDisplayTransactionNeeded; 1614 } 1615 } 1616 if (what & DisplayState::eDisplayProjectionChanged) { 1617 if (disp.orientation != s.orientation) { 1618 disp.orientation = s.orientation; 1619 flags |= eDisplayTransactionNeeded; 1620 } 1621 if (disp.frame != s.frame) { 1622 disp.frame = s.frame; 1623 flags |= eDisplayTransactionNeeded; 1624 } 1625 if (disp.viewport != s.viewport) { 1626 disp.viewport = s.viewport; 1627 flags |= eDisplayTransactionNeeded; 1628 } 1629 } 1630 } 1631 return flags; 1632} 1633 1634uint32_t SurfaceFlinger::setClientStateLocked( 1635 const sp<Client>& client, 1636 const layer_state_t& s) 1637{ 1638 uint32_t flags = 0; 1639 sp<LayerBaseClient> layer(client->getLayerUser(s.surface)); 1640 if (layer != 0) { 1641 const uint32_t what = s.what; 1642 if (what & layer_state_t::ePositionChanged) { 1643 if (layer->setPosition(s.x, s.y)) 1644 flags |= eTraversalNeeded; 1645 } 1646 if (what & layer_state_t::eLayerChanged) { 1647 // NOTE: index needs to be calculated before we update the state 1648 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); 1649 if (layer->setLayer(s.z)) { 1650 mCurrentState.layersSortedByZ.removeAt(idx); 1651 mCurrentState.layersSortedByZ.add(layer); 1652 // we need traversal (state changed) 1653 // AND transaction (list changed) 1654 flags |= eTransactionNeeded|eTraversalNeeded; 1655 } 1656 } 1657 if (what & layer_state_t::eSizeChanged) { 1658 if (layer->setSize(s.w, s.h)) { 1659 flags |= eTraversalNeeded; 1660 } 1661 } 1662 if (what & layer_state_t::eAlphaChanged) { 1663 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f))) 1664 flags |= eTraversalNeeded; 1665 } 1666 if (what & layer_state_t::eMatrixChanged) { 1667 if (layer->setMatrix(s.matrix)) 1668 flags |= eTraversalNeeded; 1669 } 1670 if (what & layer_state_t::eTransparentRegionChanged) { 1671 if (layer->setTransparentRegionHint(s.transparentRegion)) 1672 flags |= eTraversalNeeded; 1673 } 1674 if (what & layer_state_t::eVisibilityChanged) { 1675 if (layer->setFlags(s.flags, s.mask)) 1676 flags |= eTraversalNeeded; 1677 } 1678 if (what & layer_state_t::eCropChanged) { 1679 if (layer->setCrop(s.crop)) 1680 flags |= eTraversalNeeded; 1681 } 1682 if (what & layer_state_t::eLayerStackChanged) { 1683 // NOTE: index needs to be calculated before we update the state 1684 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); 1685 if (layer->setLayerStack(s.layerStack)) { 1686 mCurrentState.layersSortedByZ.removeAt(idx); 1687 mCurrentState.layersSortedByZ.add(layer); 1688 // we need traversal (state changed) 1689 // AND transaction (list changed) 1690 flags |= eTransactionNeeded|eTraversalNeeded; 1691 } 1692 } 1693 } 1694 return flags; 1695} 1696 1697sp<ISurface> SurfaceFlinger::createLayer( 1698 ISurfaceComposerClient::surface_data_t* params, 1699 const String8& name, 1700 const sp<Client>& client, 1701 uint32_t w, uint32_t h, PixelFormat format, 1702 uint32_t flags) 1703{ 1704 sp<LayerBaseClient> layer; 1705 sp<ISurface> surfaceHandle; 1706 1707 if (int32_t(w|h) < 0) { 1708 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)", 1709 int(w), int(h)); 1710 return surfaceHandle; 1711 } 1712 1713 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string()); 1714 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) { 1715 case ISurfaceComposerClient::eFXSurfaceNormal: 1716 layer = createNormalLayer(client, w, h, flags, format); 1717 break; 1718 case ISurfaceComposerClient::eFXSurfaceBlur: 1719 case ISurfaceComposerClient::eFXSurfaceDim: 1720 layer = createDimLayer(client, w, h, flags); 1721 break; 1722 case ISurfaceComposerClient::eFXSurfaceScreenshot: 1723 layer = createScreenshotLayer(client, w, h, flags); 1724 break; 1725 } 1726 1727 if (layer != 0) { 1728 layer->initStates(w, h, flags); 1729 layer->setName(name); 1730 ssize_t token = addClientLayer(client, layer); 1731 surfaceHandle = layer->getSurface(); 1732 if (surfaceHandle != 0) { 1733 params->token = token; 1734 params->identity = layer->getIdentity(); 1735 } 1736 setTransactionFlags(eTransactionNeeded); 1737 } 1738 1739 return surfaceHandle; 1740} 1741 1742sp<Layer> SurfaceFlinger::createNormalLayer( 1743 const sp<Client>& client, 1744 uint32_t w, uint32_t h, uint32_t flags, 1745 PixelFormat& format) 1746{ 1747 // initialize the surfaces 1748 switch (format) { 1749 case PIXEL_FORMAT_TRANSPARENT: 1750 case PIXEL_FORMAT_TRANSLUCENT: 1751 format = PIXEL_FORMAT_RGBA_8888; 1752 break; 1753 case PIXEL_FORMAT_OPAQUE: 1754#ifdef NO_RGBX_8888 1755 format = PIXEL_FORMAT_RGB_565; 1756#else 1757 format = PIXEL_FORMAT_RGBX_8888; 1758#endif 1759 break; 1760 } 1761 1762#ifdef NO_RGBX_8888 1763 if (format == PIXEL_FORMAT_RGBX_8888) 1764 format = PIXEL_FORMAT_RGBA_8888; 1765#endif 1766 1767 sp<Layer> layer = new Layer(this, client); 1768 status_t err = layer->setBuffers(w, h, format, flags); 1769 if (CC_LIKELY(err != NO_ERROR)) { 1770 ALOGE("createNormalLayer() failed (%s)", strerror(-err)); 1771 layer.clear(); 1772 } 1773 return layer; 1774} 1775 1776sp<LayerDim> SurfaceFlinger::createDimLayer( 1777 const sp<Client>& client, 1778 uint32_t w, uint32_t h, uint32_t flags) 1779{ 1780 sp<LayerDim> layer = new LayerDim(this, client); 1781 return layer; 1782} 1783 1784sp<LayerScreenshot> SurfaceFlinger::createScreenshotLayer( 1785 const sp<Client>& client, 1786 uint32_t w, uint32_t h, uint32_t flags) 1787{ 1788 sp<LayerScreenshot> layer = new LayerScreenshot(this, client); 1789 return layer; 1790} 1791 1792status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, SurfaceID sid) 1793{ 1794 /* 1795 * called by the window manager, when a surface should be marked for 1796 * destruction. 1797 * 1798 * The surface is removed from the current and drawing lists, but placed 1799 * in the purgatory queue, so it's not destroyed right-away (we need 1800 * to wait for all client's references to go away first). 1801 */ 1802 1803 status_t err = NAME_NOT_FOUND; 1804 Mutex::Autolock _l(mStateLock); 1805 sp<LayerBaseClient> layer = client->getLayerUser(sid); 1806 1807 if (layer != 0) { 1808 err = purgatorizeLayer_l(layer); 1809 if (err == NO_ERROR) { 1810 setTransactionFlags(eTransactionNeeded); 1811 } 1812 } 1813 return err; 1814} 1815 1816status_t SurfaceFlinger::onLayerDestroyed(const wp<LayerBaseClient>& layer) 1817{ 1818 // called by ~ISurface() when all references are gone 1819 status_t err = NO_ERROR; 1820 sp<LayerBaseClient> l(layer.promote()); 1821 if (l != NULL) { 1822 Mutex::Autolock _l(mStateLock); 1823 err = removeLayer_l(l); 1824 if (err == NAME_NOT_FOUND) { 1825 // The surface wasn't in the current list, which means it was 1826 // removed already, which means it is in the purgatory, 1827 // and need to be removed from there. 1828 ssize_t idx = mLayerPurgatory.remove(l); 1829 ALOGE_IF(idx < 0, 1830 "layer=%p is not in the purgatory list", l.get()); 1831 } 1832 ALOGE_IF(err<0 && err != NAME_NOT_FOUND, 1833 "error removing layer=%p (%s)", l.get(), strerror(-err)); 1834 } 1835 return err; 1836} 1837 1838// --------------------------------------------------------------------------- 1839 1840void SurfaceFlinger::onInitializeDisplays() { 1841 // reset screen orientation 1842 Vector<ComposerState> state; 1843 Vector<DisplayState> displays; 1844 DisplayState d; 1845 d.what = DisplayState::eDisplayProjectionChanged; 1846 d.token = mDefaultDisplays[DisplayDevice::DISPLAY_PRIMARY]; 1847 d.orientation = DisplayState::eOrientationDefault; 1848 d.frame.makeInvalid(); 1849 d.viewport.makeInvalid(); 1850 displays.add(d); 1851 setTransactionState(state, displays, 0); 1852 onScreenAcquired(getDefaultDisplayDevice()); 1853} 1854 1855void SurfaceFlinger::initializeDisplays() { 1856 class MessageScreenInitialized : public MessageBase { 1857 SurfaceFlinger* flinger; 1858 public: 1859 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { } 1860 virtual bool handler() { 1861 flinger->onInitializeDisplays(); 1862 return true; 1863 } 1864 }; 1865 sp<MessageBase> msg = new MessageScreenInitialized(this); 1866 postMessageAsync(msg); // we may be called from main thread, use async message 1867} 1868 1869 1870void SurfaceFlinger::onScreenAcquired(const sp<const DisplayDevice>& hw) { 1871 ALOGD("Screen about to return, flinger = %p", this); 1872 getHwComposer().acquire(); 1873 hw->acquireScreen(); 1874 if (hw->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) { 1875 // FIXME: eventthread only knows about the main display right now 1876 mEventThread->onScreenAcquired(); 1877 } 1878 mVisibleRegionsDirty = true; 1879 repaintEverything(); 1880} 1881 1882void SurfaceFlinger::onScreenReleased(const sp<const DisplayDevice>& hw) { 1883 ALOGD("About to give-up screen, flinger = %p", this); 1884 if (hw->isScreenAcquired()) { 1885 if (hw->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) { 1886 // FIXME: eventthread only knows about the main display right now 1887 mEventThread->onScreenReleased(); 1888 } 1889 hw->releaseScreen(); 1890 getHwComposer().release(); 1891 mVisibleRegionsDirty = true; 1892 // from this point on, SF will stop drawing 1893 } 1894} 1895 1896void SurfaceFlinger::unblank() { 1897 class MessageScreenAcquired : public MessageBase { 1898 SurfaceFlinger* flinger; 1899 public: 1900 MessageScreenAcquired(SurfaceFlinger* flinger) : flinger(flinger) { } 1901 virtual bool handler() { 1902 // FIXME: should this be per-display? 1903 flinger->onScreenAcquired(flinger->getDefaultDisplayDevice()); 1904 return true; 1905 } 1906 }; 1907 sp<MessageBase> msg = new MessageScreenAcquired(this); 1908 postMessageSync(msg); 1909} 1910 1911void SurfaceFlinger::blank() { 1912 class MessageScreenReleased : public MessageBase { 1913 SurfaceFlinger* flinger; 1914 public: 1915 MessageScreenReleased(SurfaceFlinger* flinger) : flinger(flinger) { } 1916 virtual bool handler() { 1917 // FIXME: should this be per-display? 1918 flinger->onScreenReleased(flinger->getDefaultDisplayDevice()); 1919 return true; 1920 } 1921 }; 1922 sp<MessageBase> msg = new MessageScreenReleased(this); 1923 postMessageSync(msg); 1924} 1925 1926// --------------------------------------------------------------------------- 1927 1928status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args) 1929{ 1930 const size_t SIZE = 4096; 1931 char buffer[SIZE]; 1932 String8 result; 1933 1934 if (!PermissionCache::checkCallingPermission(sDump)) { 1935 snprintf(buffer, SIZE, "Permission Denial: " 1936 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", 1937 IPCThreadState::self()->getCallingPid(), 1938 IPCThreadState::self()->getCallingUid()); 1939 result.append(buffer); 1940 } else { 1941 // Try to get the main lock, but don't insist if we can't 1942 // (this would indicate SF is stuck, but we want to be able to 1943 // print something in dumpsys). 1944 int retry = 3; 1945 while (mStateLock.tryLock()<0 && --retry>=0) { 1946 usleep(1000000); 1947 } 1948 const bool locked(retry >= 0); 1949 if (!locked) { 1950 snprintf(buffer, SIZE, 1951 "SurfaceFlinger appears to be unresponsive, " 1952 "dumping anyways (no locks held)\n"); 1953 result.append(buffer); 1954 } 1955 1956 bool dumpAll = true; 1957 size_t index = 0; 1958 size_t numArgs = args.size(); 1959 if (numArgs) { 1960 if ((index < numArgs) && 1961 (args[index] == String16("--list"))) { 1962 index++; 1963 listLayersLocked(args, index, result, buffer, SIZE); 1964 dumpAll = false; 1965 } 1966 1967 if ((index < numArgs) && 1968 (args[index] == String16("--latency"))) { 1969 index++; 1970 dumpStatsLocked(args, index, result, buffer, SIZE); 1971 dumpAll = false; 1972 } 1973 1974 if ((index < numArgs) && 1975 (args[index] == String16("--latency-clear"))) { 1976 index++; 1977 clearStatsLocked(args, index, result, buffer, SIZE); 1978 dumpAll = false; 1979 } 1980 } 1981 1982 if (dumpAll) { 1983 dumpAllLocked(result, buffer, SIZE); 1984 } 1985 1986 if (locked) { 1987 mStateLock.unlock(); 1988 } 1989 } 1990 write(fd, result.string(), result.size()); 1991 return NO_ERROR; 1992} 1993 1994void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index, 1995 String8& result, char* buffer, size_t SIZE) const 1996{ 1997 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 1998 const size_t count = currentLayers.size(); 1999 for (size_t i=0 ; i<count ; i++) { 2000 const sp<LayerBase>& layer(currentLayers[i]); 2001 snprintf(buffer, SIZE, "%s\n", layer->getName().string()); 2002 result.append(buffer); 2003 } 2004} 2005 2006void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index, 2007 String8& result, char* buffer, size_t SIZE) const 2008{ 2009 String8 name; 2010 if (index < args.size()) { 2011 name = String8(args[index]); 2012 index++; 2013 } 2014 2015 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2016 const size_t count = currentLayers.size(); 2017 for (size_t i=0 ; i<count ; i++) { 2018 const sp<LayerBase>& layer(currentLayers[i]); 2019 if (name.isEmpty()) { 2020 snprintf(buffer, SIZE, "%s\n", layer->getName().string()); 2021 result.append(buffer); 2022 } 2023 if (name.isEmpty() || (name == layer->getName())) { 2024 layer->dumpStats(result, buffer, SIZE); 2025 } 2026 } 2027} 2028 2029void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index, 2030 String8& result, char* buffer, size_t SIZE) const 2031{ 2032 String8 name; 2033 if (index < args.size()) { 2034 name = String8(args[index]); 2035 index++; 2036 } 2037 2038 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2039 const size_t count = currentLayers.size(); 2040 for (size_t i=0 ; i<count ; i++) { 2041 const sp<LayerBase>& layer(currentLayers[i]); 2042 if (name.isEmpty() || (name == layer->getName())) { 2043 layer->clearStats(); 2044 } 2045 } 2046} 2047 2048void SurfaceFlinger::dumpAllLocked( 2049 String8& result, char* buffer, size_t SIZE) const 2050{ 2051 // figure out if we're stuck somewhere 2052 const nsecs_t now = systemTime(); 2053 const nsecs_t inSwapBuffers(mDebugInSwapBuffers); 2054 const nsecs_t inTransaction(mDebugInTransaction); 2055 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0; 2056 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0; 2057 2058 /* 2059 * Dump the visible layer list 2060 */ 2061 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2062 const size_t count = currentLayers.size(); 2063 snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count); 2064 result.append(buffer); 2065 for (size_t i=0 ; i<count ; i++) { 2066 const sp<LayerBase>& layer(currentLayers[i]); 2067 layer->dump(result, buffer, SIZE); 2068 } 2069 2070 /* 2071 * Dump the layers in the purgatory 2072 */ 2073 2074 const size_t purgatorySize = mLayerPurgatory.size(); 2075 snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize); 2076 result.append(buffer); 2077 for (size_t i=0 ; i<purgatorySize ; i++) { 2078 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i)); 2079 layer->shortDump(result, buffer, SIZE); 2080 } 2081 2082 /* 2083 * Dump Display state 2084 */ 2085 2086 snprintf(buffer, SIZE, "Displays (%d entries)\n", mDisplays.size()); 2087 result.append(buffer); 2088 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 2089 const sp<const DisplayDevice>& hw(mDisplays[dpy]); 2090 hw->dump(result, buffer, SIZE); 2091 } 2092 2093 /* 2094 * Dump SurfaceFlinger global state 2095 */ 2096 2097 snprintf(buffer, SIZE, "SurfaceFlinger global state:\n"); 2098 result.append(buffer); 2099 2100 HWComposer& hwc(getHwComposer()); 2101 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 2102 const GLExtensions& extensions(GLExtensions::getInstance()); 2103 snprintf(buffer, SIZE, "GLES: %s, %s, %s\n", 2104 extensions.getVendor(), 2105 extensions.getRenderer(), 2106 extensions.getVersion()); 2107 result.append(buffer); 2108 2109 snprintf(buffer, SIZE, "EGL : %s\n", 2110 eglQueryString(mEGLDisplay, EGL_VERSION_HW_ANDROID)); 2111 result.append(buffer); 2112 2113 snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension()); 2114 result.append(buffer); 2115 2116 hw->undefinedRegion.dump(result, "undefinedRegion"); 2117 snprintf(buffer, SIZE, 2118 " orientation=%d, canDraw=%d\n", 2119 hw->getOrientation(), hw->canDraw()); 2120 result.append(buffer); 2121 snprintf(buffer, SIZE, 2122 " last eglSwapBuffers() time: %f us\n" 2123 " last transaction time : %f us\n" 2124 " transaction-flags : %08x\n" 2125 " refresh-rate : %f fps\n" 2126 " x-dpi : %f\n" 2127 " y-dpi : %f\n", 2128 mLastSwapBufferTime/1000.0, 2129 mLastTransactionTime/1000.0, 2130 mTransactionFlags, 2131 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY), 2132 hwc.getDpiX(HWC_DISPLAY_PRIMARY), 2133 hwc.getDpiY(HWC_DISPLAY_PRIMARY)); 2134 result.append(buffer); 2135 2136 snprintf(buffer, SIZE, " eglSwapBuffers time: %f us\n", 2137 inSwapBuffersDuration/1000.0); 2138 result.append(buffer); 2139 2140 snprintf(buffer, SIZE, " transaction time: %f us\n", 2141 inTransactionDuration/1000.0); 2142 result.append(buffer); 2143 2144 /* 2145 * VSYNC state 2146 */ 2147 mEventThread->dump(result, buffer, SIZE); 2148 2149 /* 2150 * Dump HWComposer state 2151 */ 2152 snprintf(buffer, SIZE, "h/w composer state:\n"); 2153 result.append(buffer); 2154 snprintf(buffer, SIZE, " h/w composer %s and %s\n", 2155 hwc.initCheck()==NO_ERROR ? "present" : "not present", 2156 (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled"); 2157 result.append(buffer); 2158 hwc.dump(result, buffer, SIZE, hw->getVisibleLayersSortedByZ()); 2159 2160 /* 2161 * Dump gralloc state 2162 */ 2163 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get()); 2164 alloc.dump(result); 2165} 2166 2167bool SurfaceFlinger::startDdmConnection() 2168{ 2169 void* libddmconnection_dso = 2170 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW); 2171 if (!libddmconnection_dso) { 2172 return false; 2173 } 2174 void (*DdmConnection_start)(const char* name); 2175 DdmConnection_start = 2176 (typeof DdmConnection_start)dlsym(libddmconnection_dso, "DdmConnection_start"); 2177 if (!DdmConnection_start) { 2178 dlclose(libddmconnection_dso); 2179 return false; 2180 } 2181 (*DdmConnection_start)(getServiceName()); 2182 return true; 2183} 2184 2185status_t SurfaceFlinger::onTransact( 2186 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 2187{ 2188 switch (code) { 2189 case CREATE_CONNECTION: 2190 case SET_TRANSACTION_STATE: 2191 case BOOT_FINISHED: 2192 case BLANK: 2193 case UNBLANK: 2194 { 2195 // codes that require permission check 2196 IPCThreadState* ipc = IPCThreadState::self(); 2197 const int pid = ipc->getCallingPid(); 2198 const int uid = ipc->getCallingUid(); 2199 if ((uid != AID_GRAPHICS) && 2200 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) { 2201 ALOGE("Permission Denial: " 2202 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 2203 return PERMISSION_DENIED; 2204 } 2205 break; 2206 } 2207 case CAPTURE_SCREEN: 2208 { 2209 // codes that require permission check 2210 IPCThreadState* ipc = IPCThreadState::self(); 2211 const int pid = ipc->getCallingPid(); 2212 const int uid = ipc->getCallingUid(); 2213 if ((uid != AID_GRAPHICS) && 2214 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) { 2215 ALOGE("Permission Denial: " 2216 "can't read framebuffer pid=%d, uid=%d", pid, uid); 2217 return PERMISSION_DENIED; 2218 } 2219 break; 2220 } 2221 } 2222 2223 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags); 2224 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) { 2225 CHECK_INTERFACE(ISurfaceComposer, data, reply); 2226 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) { 2227 IPCThreadState* ipc = IPCThreadState::self(); 2228 const int pid = ipc->getCallingPid(); 2229 const int uid = ipc->getCallingUid(); 2230 ALOGE("Permission Denial: " 2231 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 2232 return PERMISSION_DENIED; 2233 } 2234 int n; 2235 switch (code) { 2236 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE 2237 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE 2238 return NO_ERROR; 2239 case 1002: // SHOW_UPDATES 2240 n = data.readInt32(); 2241 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1); 2242 invalidateHwcGeometry(); 2243 repaintEverything(); 2244 return NO_ERROR; 2245 case 1004:{ // repaint everything 2246 repaintEverything(); 2247 return NO_ERROR; 2248 } 2249 case 1005:{ // force transaction 2250 setTransactionFlags( 2251 eTransactionNeeded| 2252 eDisplayTransactionNeeded| 2253 eTraversalNeeded); 2254 return NO_ERROR; 2255 } 2256 case 1006:{ // send empty update 2257 signalRefresh(); 2258 return NO_ERROR; 2259 } 2260 case 1008: // toggle use of hw composer 2261 n = data.readInt32(); 2262 mDebugDisableHWC = n ? 1 : 0; 2263 invalidateHwcGeometry(); 2264 repaintEverything(); 2265 return NO_ERROR; 2266 case 1009: // toggle use of transform hint 2267 n = data.readInt32(); 2268 mDebugDisableTransformHint = n ? 1 : 0; 2269 invalidateHwcGeometry(); 2270 repaintEverything(); 2271 return NO_ERROR; 2272 case 1010: // interrogate. 2273 reply->writeInt32(0); 2274 reply->writeInt32(0); 2275 reply->writeInt32(mDebugRegion); 2276 reply->writeInt32(0); 2277 reply->writeInt32(mDebugDisableHWC); 2278 return NO_ERROR; 2279 case 1013: { 2280 Mutex::Autolock _l(mStateLock); 2281 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 2282 reply->writeInt32(hw->getPageFlipCount()); 2283 } 2284 return NO_ERROR; 2285 } 2286 } 2287 return err; 2288} 2289 2290void SurfaceFlinger::repaintEverything() { 2291 android_atomic_or(1, &mRepaintEverything); 2292 signalTransaction(); 2293} 2294 2295// --------------------------------------------------------------------------- 2296 2297status_t SurfaceFlinger::renderScreenToTexture(uint32_t layerStack, 2298 GLuint* textureName, GLfloat* uOut, GLfloat* vOut) 2299{ 2300 Mutex::Autolock _l(mStateLock); 2301 return renderScreenToTextureLocked(layerStack, textureName, uOut, vOut); 2302} 2303 2304status_t SurfaceFlinger::renderScreenToTextureLocked(uint32_t layerStack, 2305 GLuint* textureName, GLfloat* uOut, GLfloat* vOut) 2306{ 2307 ATRACE_CALL(); 2308 2309 if (!GLExtensions::getInstance().haveFramebufferObject()) 2310 return INVALID_OPERATION; 2311 2312 // get screen geometry 2313 // FIXME: figure out what it means to have a screenshot texture w/ multi-display 2314 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 2315 const uint32_t hw_w = hw->getWidth(); 2316 const uint32_t hw_h = hw->getHeight(); 2317 GLfloat u = 1; 2318 GLfloat v = 1; 2319 2320 // make sure to clear all GL error flags 2321 while ( glGetError() != GL_NO_ERROR ) ; 2322 2323 // create a FBO 2324 GLuint name, tname; 2325 glGenTextures(1, &tname); 2326 glBindTexture(GL_TEXTURE_2D, tname); 2327 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 2328 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 2329 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2330 hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); 2331 if (glGetError() != GL_NO_ERROR) { 2332 while ( glGetError() != GL_NO_ERROR ) ; 2333 GLint tw = (2 << (31 - clz(hw_w))); 2334 GLint th = (2 << (31 - clz(hw_h))); 2335 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2336 tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); 2337 u = GLfloat(hw_w) / tw; 2338 v = GLfloat(hw_h) / th; 2339 } 2340 glGenFramebuffersOES(1, &name); 2341 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name); 2342 glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES, 2343 GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0); 2344 2345 // redraw the screen entirely... 2346 glDisable(GL_TEXTURE_EXTERNAL_OES); 2347 glDisable(GL_TEXTURE_2D); 2348 glClearColor(0,0,0,1); 2349 glClear(GL_COLOR_BUFFER_BIT); 2350 glMatrixMode(GL_MODELVIEW); 2351 glLoadIdentity(); 2352 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ()); 2353 const size_t count = layers.size(); 2354 for (size_t i=0 ; i<count ; ++i) { 2355 const sp<LayerBase>& layer(layers[i]); 2356 layer->draw(hw); 2357 } 2358 2359 hw->compositionComplete(); 2360 2361 // back to main framebuffer 2362 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); 2363 glDeleteFramebuffersOES(1, &name); 2364 2365 *textureName = tname; 2366 *uOut = u; 2367 *vOut = v; 2368 return NO_ERROR; 2369} 2370 2371// --------------------------------------------------------------------------- 2372 2373status_t SurfaceFlinger::captureScreenImplLocked(const sp<IBinder>& display, 2374 sp<IMemoryHeap>* heap, 2375 uint32_t* w, uint32_t* h, PixelFormat* f, 2376 uint32_t sw, uint32_t sh, 2377 uint32_t minLayerZ, uint32_t maxLayerZ) 2378{ 2379 ATRACE_CALL(); 2380 2381 status_t result = PERMISSION_DENIED; 2382 2383 if (!GLExtensions::getInstance().haveFramebufferObject()) { 2384 return INVALID_OPERATION; 2385 } 2386 2387 // get screen geometry 2388 sp<const DisplayDevice> hw(getDisplayDevice(display)); 2389 const uint32_t hw_w = hw->getWidth(); 2390 const uint32_t hw_h = hw->getHeight(); 2391 2392 // if we have secure windows on this display, never allow the screen capture 2393 if (hw->getSecureLayerVisible()) { 2394 ALOGW("FB is protected: PERMISSION_DENIED"); 2395 return PERMISSION_DENIED; 2396 } 2397 2398 if ((sw > hw_w) || (sh > hw_h)) { 2399 ALOGE("size mismatch (%d, %d) > (%d, %d)", sw, sh, hw_w, hw_h); 2400 return BAD_VALUE; 2401 } 2402 2403 sw = (!sw) ? hw_w : sw; 2404 sh = (!sh) ? hw_h : sh; 2405 const size_t size = sw * sh * 4; 2406 const bool filtering = sw != hw_w || sh != hw_h; 2407 2408// ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d", 2409// sw, sh, minLayerZ, maxLayerZ); 2410 2411 // make sure to clear all GL error flags 2412 while ( glGetError() != GL_NO_ERROR ) ; 2413 2414 // create a FBO 2415 GLuint name, tname; 2416 glGenRenderbuffersOES(1, &tname); 2417 glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname); 2418 glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh); 2419 2420 glGenFramebuffersOES(1, &name); 2421 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name); 2422 glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, 2423 GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname); 2424 2425 GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES); 2426 2427 if (status == GL_FRAMEBUFFER_COMPLETE_OES) { 2428 2429 // invert everything, b/c glReadPixel() below will invert the FB 2430 glViewport(0, 0, sw, sh); 2431 glMatrixMode(GL_PROJECTION); 2432 glPushMatrix(); 2433 glLoadIdentity(); 2434 glOrthof(0, hw_w, hw_h, 0, 0, 1); 2435 glMatrixMode(GL_MODELVIEW); 2436 2437 // redraw the screen entirely... 2438 glClearColor(0,0,0,1); 2439 glClear(GL_COLOR_BUFFER_BIT); 2440 2441 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ()); 2442 const size_t count = layers.size(); 2443 for (size_t i=0 ; i<count ; ++i) { 2444 const sp<LayerBase>& layer(layers[i]); 2445 const uint32_t z = layer->drawingState().z; 2446 if (z >= minLayerZ && z <= maxLayerZ) { 2447 if (filtering) layer->setFiltering(true); 2448 layer->draw(hw); 2449 if (filtering) layer->setFiltering(false); 2450 } 2451 } 2452 2453 // check for errors and return screen capture 2454 if (glGetError() != GL_NO_ERROR) { 2455 // error while rendering 2456 result = INVALID_OPERATION; 2457 } else { 2458 // allocate shared memory large enough to hold the 2459 // screen capture 2460 sp<MemoryHeapBase> base( 2461 new MemoryHeapBase(size, 0, "screen-capture") ); 2462 void* const ptr = base->getBase(); 2463 if (ptr) { 2464 // capture the screen with glReadPixels() 2465 ScopedTrace _t(ATRACE_TAG, "glReadPixels"); 2466 glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr); 2467 if (glGetError() == GL_NO_ERROR) { 2468 *heap = base; 2469 *w = sw; 2470 *h = sh; 2471 *f = PIXEL_FORMAT_RGBA_8888; 2472 result = NO_ERROR; 2473 } 2474 } else { 2475 result = NO_MEMORY; 2476 } 2477 } 2478 glViewport(0, 0, hw_w, hw_h); 2479 glMatrixMode(GL_PROJECTION); 2480 glPopMatrix(); 2481 glMatrixMode(GL_MODELVIEW); 2482 } else { 2483 result = BAD_VALUE; 2484 } 2485 2486 // release FBO resources 2487 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); 2488 glDeleteRenderbuffersOES(1, &tname); 2489 glDeleteFramebuffersOES(1, &name); 2490 2491 hw->compositionComplete(); 2492 2493// ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK"); 2494 2495 return result; 2496} 2497 2498 2499status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, 2500 sp<IMemoryHeap>* heap, 2501 uint32_t* width, uint32_t* height, PixelFormat* format, 2502 uint32_t sw, uint32_t sh, 2503 uint32_t minLayerZ, uint32_t maxLayerZ) 2504{ 2505 if (CC_UNLIKELY(display == 0)) 2506 return BAD_VALUE; 2507 2508 if (!GLExtensions::getInstance().haveFramebufferObject()) 2509 return INVALID_OPERATION; 2510 2511 class MessageCaptureScreen : public MessageBase { 2512 SurfaceFlinger* flinger; 2513 sp<IBinder> display; 2514 sp<IMemoryHeap>* heap; 2515 uint32_t* w; 2516 uint32_t* h; 2517 PixelFormat* f; 2518 uint32_t sw; 2519 uint32_t sh; 2520 uint32_t minLayerZ; 2521 uint32_t maxLayerZ; 2522 status_t result; 2523 public: 2524 MessageCaptureScreen(SurfaceFlinger* flinger, const sp<IBinder>& display, 2525 sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f, 2526 uint32_t sw, uint32_t sh, 2527 uint32_t minLayerZ, uint32_t maxLayerZ) 2528 : flinger(flinger), display(display), 2529 heap(heap), w(w), h(h), f(f), sw(sw), sh(sh), 2530 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ), 2531 result(PERMISSION_DENIED) 2532 { 2533 } 2534 status_t getResult() const { 2535 return result; 2536 } 2537 virtual bool handler() { 2538 Mutex::Autolock _l(flinger->mStateLock); 2539 result = flinger->captureScreenImplLocked(display, 2540 heap, w, h, f, sw, sh, minLayerZ, maxLayerZ); 2541 return true; 2542 } 2543 }; 2544 2545 sp<MessageBase> msg = new MessageCaptureScreen(this, 2546 display, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ); 2547 status_t res = postMessageSync(msg); 2548 if (res == NO_ERROR) { 2549 res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult(); 2550 } 2551 return res; 2552} 2553 2554// --------------------------------------------------------------------------- 2555 2556SurfaceFlinger::LayerVector::LayerVector() { 2557} 2558 2559SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs) 2560 : SortedVector<sp<LayerBase> >(rhs) { 2561} 2562 2563int SurfaceFlinger::LayerVector::do_compare(const void* lhs, 2564 const void* rhs) const 2565{ 2566 // sort layers per layer-stack, then by z-order and finally by sequence 2567 const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs)); 2568 const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs)); 2569 2570 uint32_t ls = l->currentState().layerStack; 2571 uint32_t rs = r->currentState().layerStack; 2572 if (ls != rs) 2573 return ls - rs; 2574 2575 uint32_t lz = l->currentState().z; 2576 uint32_t rz = r->currentState().z; 2577 if (lz != rz) 2578 return lz - rz; 2579 2580 return l->sequence - r->sequence; 2581} 2582 2583// --------------------------------------------------------------------------- 2584 2585SurfaceFlinger::DisplayDeviceState::DisplayDeviceState() 2586 : type(DisplayDevice::DISPLAY_ID_INVALID) { 2587} 2588 2589SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type) 2590 : type(type), layerStack(0), orientation(0) { 2591 viewport.makeInvalid(); 2592 frame.makeInvalid(); 2593} 2594 2595// --------------------------------------------------------------------------- 2596 2597}; // namespace android 2598