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