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