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