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