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