SurfaceFlinger.cpp revision d05a17fbb3772051d287f1f8830a7f00964f7ec2
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 27#include <cutils/log.h> 28#include <cutils/properties.h> 29 30#include <binder/IPCThreadState.h> 31#include <binder/IServiceManager.h> 32#include <binder/MemoryHeapBase.h> 33#include <binder/PermissionCache.h> 34 35#include <ui/DisplayInfo.h> 36 37#include <gui/BitTube.h> 38#include <gui/BufferQueue.h> 39#include <gui/GuiConfig.h> 40#include <gui/IDisplayEventConnection.h> 41#include <gui/Surface.h> 42#include <gui/GraphicBufferAlloc.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#include <private/gui/SyncFeatures.h> 56 57#include "Client.h" 58#include "clz.h" 59#include "Colorizer.h" 60#include "DdmConnection.h" 61#include "DisplayDevice.h" 62#include "EventThread.h" 63#include "Layer.h" 64#include "LayerDim.h" 65#include "SurfaceFlinger.h" 66 67#include "DisplayHardware/FramebufferSurface.h" 68#include "DisplayHardware/HWComposer.h" 69#include "DisplayHardware/VirtualDisplaySurface.h" 70 71#include "Effects/Daltonizer.h" 72 73#include "RenderEngine/RenderEngine.h" 74#include <cutils/compiler.h> 75 76#define DISPLAY_COUNT 1 77 78/* 79 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all 80 * black pixels. 81 */ 82#define DEBUG_SCREENSHOTS false 83 84EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name); 85 86namespace android { 87// --------------------------------------------------------------------------- 88 89const String16 sHardwareTest("android.permission.HARDWARE_TEST"); 90const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER"); 91const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER"); 92const String16 sDump("android.permission.DUMP"); 93 94// --------------------------------------------------------------------------- 95 96SurfaceFlinger::SurfaceFlinger() 97 : BnSurfaceComposer(), 98 mTransactionFlags(0), 99 mTransactionPending(false), 100 mAnimTransactionPending(false), 101 mLayersRemoved(false), 102 mRepaintEverything(0), 103 mRenderEngine(NULL), 104 mBootTime(systemTime()), 105 mVisibleRegionsDirty(false), 106 mHwWorkListDirty(false), 107 mAnimCompositionPending(false), 108 mDebugRegion(0), 109 mDebugDDMS(0), 110 mDebugDisableHWC(0), 111 mDebugDisableTransformHint(0), 112 mDebugInSwapBuffers(0), 113 mLastSwapBufferTime(0), 114 mDebugInTransaction(0), 115 mLastTransactionTime(0), 116 mBootFinished(false), 117 mDaltonize(false) 118{ 119 ALOGI("SurfaceFlinger is starting"); 120 121 // debugging stuff... 122 char value[PROPERTY_VALUE_MAX]; 123 124 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0"); 125 mGpuToCpuSupported = !atoi(value); 126 127 property_get("debug.sf.showupdates", value, "0"); 128 mDebugRegion = atoi(value); 129 130 property_get("debug.sf.ddms", value, "0"); 131 mDebugDDMS = atoi(value); 132 if (mDebugDDMS) { 133 if (!startDdmConnection()) { 134 // start failed, and DDMS debugging not enabled 135 mDebugDDMS = 0; 136 } 137 } 138 ALOGI_IF(mDebugRegion, "showupdates enabled"); 139 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled"); 140} 141 142void SurfaceFlinger::onFirstRef() 143{ 144 mEventQueue.init(this); 145} 146 147SurfaceFlinger::~SurfaceFlinger() 148{ 149 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); 150 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); 151 eglTerminate(display); 152} 153 154void SurfaceFlinger::binderDied(const wp<IBinder>& who) 155{ 156 // the window manager died on us. prepare its eulogy. 157 158 // restore initial conditions (default device unblank, etc) 159 initializeDisplays(); 160 161 // restart the boot-animation 162 startBootAnim(); 163} 164 165sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() 166{ 167 sp<ISurfaceComposerClient> bclient; 168 sp<Client> client(new Client(this)); 169 status_t err = client->initCheck(); 170 if (err == NO_ERROR) { 171 bclient = client; 172 } 173 return bclient; 174} 175 176sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, 177 bool secure) 178{ 179 class DisplayToken : public BBinder { 180 sp<SurfaceFlinger> flinger; 181 virtual ~DisplayToken() { 182 // no more references, this display must be terminated 183 Mutex::Autolock _l(flinger->mStateLock); 184 flinger->mCurrentState.displays.removeItem(this); 185 flinger->setTransactionFlags(eDisplayTransactionNeeded); 186 } 187 public: 188 DisplayToken(const sp<SurfaceFlinger>& flinger) 189 : flinger(flinger) { 190 } 191 }; 192 193 sp<BBinder> token = new DisplayToken(this); 194 195 Mutex::Autolock _l(mStateLock); 196 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL); 197 info.displayName = displayName; 198 info.isSecure = secure; 199 mCurrentState.displays.add(token, info); 200 201 return token; 202} 203 204void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) { 205 Mutex::Autolock _l(mStateLock); 206 207 ssize_t idx = mCurrentState.displays.indexOfKey(display); 208 if (idx < 0) { 209 ALOGW("destroyDisplay: invalid display token"); 210 return; 211 } 212 213 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx)); 214 if (!info.isVirtualDisplay()) { 215 ALOGE("destroyDisplay called for non-virtual display"); 216 return; 217 } 218 219 mCurrentState.displays.removeItemsAt(idx); 220 setTransactionFlags(eDisplayTransactionNeeded); 221} 222 223void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) { 224 ALOGW_IF(mBuiltinDisplays[type], 225 "Overwriting display token for display type %d", type); 226 mBuiltinDisplays[type] = new BBinder(); 227 DisplayDeviceState info(type); 228 // All non-virtual displays are currently considered secure. 229 info.isSecure = true; 230 mCurrentState.displays.add(mBuiltinDisplays[type], info); 231} 232 233sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) { 234 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) { 235 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id); 236 return NULL; 237 } 238 return mBuiltinDisplays[id]; 239} 240 241sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc() 242{ 243 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc()); 244 return gba; 245} 246 247void SurfaceFlinger::bootFinished() 248{ 249 const nsecs_t now = systemTime(); 250 const nsecs_t duration = now - mBootTime; 251 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) ); 252 mBootFinished = true; 253 254 // wait patiently for the window manager death 255 const String16 name("window"); 256 sp<IBinder> window(defaultServiceManager()->getService(name)); 257 if (window != 0) { 258 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this)); 259 } 260 261 // stop boot animation 262 // formerly we would just kill the process, but we now ask it to exit so it 263 // can choose where to stop the animation. 264 property_set("service.bootanim.exit", "1"); 265} 266 267void SurfaceFlinger::deleteTextureAsync(uint32_t texture) { 268 class MessageDestroyGLTexture : public MessageBase { 269 RenderEngine& engine; 270 uint32_t texture; 271 public: 272 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture) 273 : engine(engine), texture(texture) { 274 } 275 virtual bool handler() { 276 engine.deleteTextures(1, &texture); 277 return true; 278 } 279 }; 280 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture)); 281} 282 283status_t SurfaceFlinger::selectConfigForAttribute( 284 EGLDisplay dpy, 285 EGLint const* attrs, 286 EGLint attribute, EGLint wanted, 287 EGLConfig* outConfig) 288{ 289 EGLConfig config = NULL; 290 EGLint numConfigs = -1, n=0; 291 eglGetConfigs(dpy, NULL, 0, &numConfigs); 292 EGLConfig* const configs = new EGLConfig[numConfigs]; 293 eglChooseConfig(dpy, attrs, configs, numConfigs, &n); 294 295 if (n) { 296 if (attribute != EGL_NONE) { 297 for (int i=0 ; i<n ; i++) { 298 EGLint value = 0; 299 eglGetConfigAttrib(dpy, configs[i], attribute, &value); 300 if (wanted == value) { 301 *outConfig = configs[i]; 302 delete [] configs; 303 return NO_ERROR; 304 } 305 } 306 } else { 307 // just pick the first one 308 *outConfig = configs[0]; 309 delete [] configs; 310 return NO_ERROR; 311 } 312 } 313 delete [] configs; 314 return NAME_NOT_FOUND; 315} 316 317class EGLAttributeVector { 318 struct Attribute; 319 class Adder; 320 friend class Adder; 321 KeyedVector<Attribute, EGLint> mList; 322 struct Attribute { 323 Attribute() {}; 324 Attribute(EGLint v) : v(v) { } 325 EGLint v; 326 bool operator < (const Attribute& other) const { 327 // this places EGL_NONE at the end 328 EGLint lhs(v); 329 EGLint rhs(other.v); 330 if (lhs == EGL_NONE) lhs = 0x7FFFFFFF; 331 if (rhs == EGL_NONE) rhs = 0x7FFFFFFF; 332 return lhs < rhs; 333 } 334 }; 335 class Adder { 336 friend class EGLAttributeVector; 337 EGLAttributeVector& v; 338 EGLint attribute; 339 Adder(EGLAttributeVector& v, EGLint attribute) 340 : v(v), attribute(attribute) { 341 } 342 public: 343 void operator = (EGLint value) { 344 if (attribute != EGL_NONE) { 345 v.mList.add(attribute, value); 346 } 347 } 348 operator EGLint () const { return v.mList[attribute]; } 349 }; 350public: 351 EGLAttributeVector() { 352 mList.add(EGL_NONE, EGL_NONE); 353 } 354 void remove(EGLint attribute) { 355 if (attribute != EGL_NONE) { 356 mList.removeItem(attribute); 357 } 358 } 359 Adder operator [] (EGLint attribute) { 360 return Adder(*this, attribute); 361 } 362 EGLint operator [] (EGLint attribute) const { 363 return mList[attribute]; 364 } 365 // cast-operator to (EGLint const*) 366 operator EGLint const* () const { return &mList.keyAt(0).v; } 367}; 368 369EGLConfig SurfaceFlinger::selectEGLConfig(EGLDisplay display, EGLint nativeVisualId, 370 EGLint renderableType) { 371 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if 372 // it is to be used with WIFI displays 373 EGLConfig config; 374 EGLint dummy; 375 status_t err; 376 EGLint wantedAttribute; 377 EGLint wantedAttributeValue; 378 379 EGLAttributeVector attribs; 380 if (renderableType) { 381 attribs[EGL_RENDERABLE_TYPE] = renderableType; 382 attribs[EGL_RECORDABLE_ANDROID] = EGL_TRUE; 383 attribs[EGL_SURFACE_TYPE] = EGL_WINDOW_BIT|EGL_PBUFFER_BIT; 384 attribs[EGL_FRAMEBUFFER_TARGET_ANDROID] = EGL_TRUE; 385 attribs[EGL_RED_SIZE] = 8; 386 attribs[EGL_GREEN_SIZE] = 8; 387 attribs[EGL_BLUE_SIZE] = 8; 388 wantedAttribute = EGL_NONE; 389 wantedAttributeValue = EGL_NONE; 390 391 } else { 392 // if no renderable type specified, fallback to a simplified query 393 attribs[EGL_RECORDABLE_ANDROID] = EGL_TRUE; 394 wantedAttribute = EGL_NATIVE_VISUAL_ID; 395 wantedAttributeValue = nativeVisualId; 396 } 397 398 err = selectConfigForAttribute(display, attribs, wantedAttribute, 399 wantedAttributeValue, &config); 400 if (!err) 401 goto success; 402 403 return 0; 404 405success: 406 if (eglGetConfigAttrib(display, config, EGL_CONFIG_CAVEAT, &dummy)) 407 ALOGW_IF(dummy == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!"); 408 return config; 409} 410 411void SurfaceFlinger::init() { 412 413 ALOGI( "SurfaceFlinger's main thread ready to run. " 414 "Initializing graphics H/W..."); 415 416 Mutex::Autolock _l(mStateLock); 417 418 // initialize EGL for the default display 419 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY); 420 eglInitialize(mEGLDisplay, NULL, NULL); 421 422 // Initialize the H/W composer object. There may or may not be an 423 // actual hardware composer underneath. 424 mHwc = new HWComposer(this, 425 *static_cast<HWComposer::EventHandler *>(this)); 426 427 // First try to get an ES2 config 428 mEGLConfig = selectEGLConfig(mEGLDisplay, mHwc->getVisualID(), EGL_OPENGL_ES2_BIT); 429 430 if (!mEGLConfig) { 431 // If ES2 fails, try ES1 432 mEGLConfig = selectEGLConfig(mEGLDisplay, mHwc->getVisualID(), EGL_OPENGL_ES_BIT); 433 } 434 435 if (!mEGLConfig) { 436 // still didn't work, probably because we're on the emulator... 437 // try a simplified query 438 ALOGW("no suitable EGLConfig found, trying a simpler query"); 439 mEGLConfig = selectEGLConfig(mEGLDisplay, mHwc->getVisualID(), 0); 440 } 441 442 if (!mEGLConfig) { 443 // this EGL is too lame for android 444 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up"); 445 } 446 447 // print some debugging info 448 EGLint r,g,b,a; 449 eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_RED_SIZE, &r); 450 eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_GREEN_SIZE, &g); 451 eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_BLUE_SIZE, &b); 452 eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_ALPHA_SIZE, &a); 453 ALOGI("EGL informations:"); 454 ALOGI("vendor : %s", eglQueryString(mEGLDisplay, EGL_VENDOR)); 455 ALOGI("version : %s", eglQueryString(mEGLDisplay, EGL_VERSION)); 456 ALOGI("extensions: %s", eglQueryString(mEGLDisplay, EGL_EXTENSIONS)); 457 ALOGI("Client API: %s", eglQueryString(mEGLDisplay, EGL_CLIENT_APIS)?:"Not Supported"); 458 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, mEGLConfig); 459 460 // get a RenderEngine for the given display / config (can't fail) 461 mRenderEngine = RenderEngine::create(mEGLDisplay, mEGLConfig); 462 463 // retrieve the EGL context that was selected/created 464 mEGLContext = mRenderEngine->getEGLContext(); 465 466 // figure out which format we got 467 eglGetConfigAttrib(mEGLDisplay, mEGLConfig, 468 EGL_NATIVE_VISUAL_ID, &mEGLNativeVisualId); 469 470 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT, 471 "couldn't create EGLContext"); 472 473 // initialize our non-virtual displays 474 for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) { 475 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i); 476 // set-up the displays that are already connected 477 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) { 478 // All non-virtual displays are currently considered secure. 479 bool isSecure = true; 480 createBuiltinDisplayLocked(type); 481 wp<IBinder> token = mBuiltinDisplays[i]; 482 483 sp<BufferQueue> bq = new BufferQueue(new GraphicBufferAlloc()); 484 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i, bq); 485 sp<DisplayDevice> hw = new DisplayDevice(this, 486 type, allocateHwcDisplayId(type), isSecure, token, 487 fbs, bq, 488 mEGLConfig); 489 if (i > DisplayDevice::DISPLAY_PRIMARY) { 490 // FIXME: currently we don't get blank/unblank requests 491 // for displays other than the main display, so we always 492 // assume a connected display is unblanked. 493 ALOGD("marking display %d as acquired/unblanked", i); 494 hw->acquireScreen(); 495 } 496 mDisplays.add(token, hw); 497 } 498 } 499 500 // make the GLContext current so that we can create textures when creating Layers 501 // (which may happens before we render something) 502 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext); 503 504 // start the EventThread 505 mEventThread = new EventThread(this); 506 mEventQueue.setEventThread(mEventThread); 507 508 // initialize our drawing state 509 mDrawingState = mCurrentState; 510 511 // set initial conditions (e.g. unblank default device) 512 initializeDisplays(); 513 514 // start boot animation 515 startBootAnim(); 516} 517 518int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) { 519 return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ? 520 type : mHwc->allocateDisplayId(); 521} 522 523void SurfaceFlinger::startBootAnim() { 524 // start boot animation 525 property_set("service.bootanim.exit", "0"); 526 property_set("ctl.start", "bootanim"); 527} 528 529size_t SurfaceFlinger::getMaxTextureSize() const { 530 return mRenderEngine->getMaxTextureSize(); 531} 532 533size_t SurfaceFlinger::getMaxViewportDims() const { 534 return mRenderEngine->getMaxViewportDims(); 535} 536 537// ---------------------------------------------------------------------------- 538 539bool SurfaceFlinger::authenticateSurfaceTexture( 540 const sp<IGraphicBufferProducer>& bufferProducer) const { 541 Mutex::Autolock _l(mStateLock); 542 sp<IBinder> surfaceTextureBinder(bufferProducer->asBinder()); 543 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0; 544} 545 546status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info) { 547 int32_t type = NAME_NOT_FOUND; 548 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) { 549 if (display == mBuiltinDisplays[i]) { 550 type = i; 551 break; 552 } 553 } 554 555 if (type < 0) { 556 return type; 557 } 558 559 const HWComposer& hwc(getHwComposer()); 560 float xdpi = hwc.getDpiX(type); 561 float ydpi = hwc.getDpiY(type); 562 563 // TODO: Not sure if display density should handled by SF any longer 564 class Density { 565 static int getDensityFromProperty(char const* propName) { 566 char property[PROPERTY_VALUE_MAX]; 567 int density = 0; 568 if (property_get(propName, property, NULL) > 0) { 569 density = atoi(property); 570 } 571 return density; 572 } 573 public: 574 static int getEmuDensity() { 575 return getDensityFromProperty("qemu.sf.lcd_density"); } 576 static int getBuildDensity() { 577 return getDensityFromProperty("ro.sf.lcd_density"); } 578 }; 579 580 if (type == DisplayDevice::DISPLAY_PRIMARY) { 581 // The density of the device is provided by a build property 582 float density = Density::getBuildDensity() / 160.0f; 583 if (density == 0) { 584 // the build doesn't provide a density -- this is wrong! 585 // use xdpi instead 586 ALOGE("ro.sf.lcd_density must be defined as a build property"); 587 density = xdpi / 160.0f; 588 } 589 if (Density::getEmuDensity()) { 590 // if "qemu.sf.lcd_density" is specified, it overrides everything 591 xdpi = ydpi = density = Density::getEmuDensity(); 592 density /= 160.0f; 593 } 594 info->density = density; 595 596 // TODO: this needs to go away (currently needed only by webkit) 597 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 598 info->orientation = hw->getOrientation(); 599 } else { 600 // TODO: where should this value come from? 601 static const int TV_DENSITY = 213; 602 info->density = TV_DENSITY / 160.0f; 603 info->orientation = 0; 604 } 605 606 info->w = hwc.getWidth(type); 607 info->h = hwc.getHeight(type); 608 info->xdpi = xdpi; 609 info->ydpi = ydpi; 610 info->fps = float(1e9 / hwc.getRefreshPeriod(type)); 611 612 // All non-virtual displays are currently considered secure. 613 info->secure = true; 614 615 return NO_ERROR; 616} 617 618// ---------------------------------------------------------------------------- 619 620sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() { 621 return mEventThread->createEventConnection(); 622} 623 624// ---------------------------------------------------------------------------- 625 626void SurfaceFlinger::waitForEvent() { 627 mEventQueue.waitMessage(); 628} 629 630void SurfaceFlinger::signalTransaction() { 631 mEventQueue.invalidate(); 632} 633 634void SurfaceFlinger::signalLayerUpdate() { 635 mEventQueue.invalidate(); 636} 637 638void SurfaceFlinger::signalRefresh() { 639 mEventQueue.refresh(); 640} 641 642status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg, 643 nsecs_t reltime, uint32_t flags) { 644 return mEventQueue.postMessage(msg, reltime); 645} 646 647status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg, 648 nsecs_t reltime, uint32_t flags) { 649 status_t res = mEventQueue.postMessage(msg, reltime); 650 if (res == NO_ERROR) { 651 msg->wait(); 652 } 653 return res; 654} 655 656void SurfaceFlinger::run() { 657 do { 658 waitForEvent(); 659 } while (true); 660} 661 662void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) { 663 if (mEventThread == NULL) { 664 // This is a temporary workaround for b/7145521. A non-null pointer 665 // does not mean EventThread has finished initializing, so this 666 // is not a correct fix. 667 ALOGW("WARNING: EventThread not started, ignoring vsync"); 668 return; 669 } 670 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) { 671 // we should only receive DisplayDevice::DisplayType from the vsync callback 672 mEventThread->onVSyncReceived(type, timestamp); 673 } 674} 675 676void SurfaceFlinger::onHotplugReceived(int type, bool connected) { 677 if (mEventThread == NULL) { 678 // This is a temporary workaround for b/7145521. A non-null pointer 679 // does not mean EventThread has finished initializing, so this 680 // is not a correct fix. 681 ALOGW("WARNING: EventThread not started, ignoring hotplug"); 682 return; 683 } 684 685 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) { 686 Mutex::Autolock _l(mStateLock); 687 if (connected) { 688 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type); 689 } else { 690 mCurrentState.displays.removeItem(mBuiltinDisplays[type]); 691 mBuiltinDisplays[type].clear(); 692 } 693 setTransactionFlags(eDisplayTransactionNeeded); 694 695 // Defer EventThread notification until SF has updated mDisplays. 696 } 697} 698 699void SurfaceFlinger::eventControl(int disp, int event, int enabled) { 700 getHwComposer().eventControl(disp, event, enabled); 701} 702 703void SurfaceFlinger::onMessageReceived(int32_t what) { 704 ATRACE_CALL(); 705 switch (what) { 706 case MessageQueue::TRANSACTION: 707 handleMessageTransaction(); 708 break; 709 case MessageQueue::INVALIDATE: 710 handleMessageTransaction(); 711 handleMessageInvalidate(); 712 signalRefresh(); 713 break; 714 case MessageQueue::REFRESH: 715 handleMessageRefresh(); 716 break; 717 } 718} 719 720void SurfaceFlinger::handleMessageTransaction() { 721 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask); 722 if (transactionFlags) { 723 handleTransaction(transactionFlags); 724 } 725} 726 727void SurfaceFlinger::handleMessageInvalidate() { 728 ATRACE_CALL(); 729 handlePageFlip(); 730} 731 732void SurfaceFlinger::handleMessageRefresh() { 733 ATRACE_CALL(); 734 preComposition(); 735 rebuildLayerStacks(); 736 setUpHWComposer(); 737 doDebugFlashRegions(); 738 doComposition(); 739 postComposition(); 740} 741 742void SurfaceFlinger::doDebugFlashRegions() 743{ 744 // is debugging enabled 745 if (CC_LIKELY(!mDebugRegion)) 746 return; 747 748 const bool repaintEverything = mRepaintEverything; 749 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 750 const sp<DisplayDevice>& hw(mDisplays[dpy]); 751 if (hw->canDraw()) { 752 // transform the dirty region into this screen's coordinate space 753 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything)); 754 if (!dirtyRegion.isEmpty()) { 755 // redraw the whole screen 756 doComposeSurfaces(hw, Region(hw->bounds())); 757 758 // and draw the dirty region 759 const int32_t height = hw->getHeight(); 760 RenderEngine& engine(getRenderEngine()); 761 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1); 762 763 hw->compositionComplete(); 764 hw->swapBuffers(getHwComposer()); 765 } 766 } 767 } 768 769 postFramebuffer(); 770 771 if (mDebugRegion > 1) { 772 usleep(mDebugRegion * 1000); 773 } 774 775 HWComposer& hwc(getHwComposer()); 776 if (hwc.initCheck() == NO_ERROR) { 777 status_t err = hwc.prepare(); 778 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err)); 779 } 780} 781 782void SurfaceFlinger::preComposition() 783{ 784 bool needExtraInvalidate = false; 785 const LayerVector& layers(mDrawingState.layersSortedByZ); 786 const size_t count = layers.size(); 787 for (size_t i=0 ; i<count ; i++) { 788 if (layers[i]->onPreComposition()) { 789 needExtraInvalidate = true; 790 } 791 } 792 if (needExtraInvalidate) { 793 signalLayerUpdate(); 794 } 795} 796 797void SurfaceFlinger::postComposition() 798{ 799 const LayerVector& layers(mDrawingState.layersSortedByZ); 800 const size_t count = layers.size(); 801 for (size_t i=0 ; i<count ; i++) { 802 layers[i]->onPostComposition(); 803 } 804 805 if (mAnimCompositionPending) { 806 mAnimCompositionPending = false; 807 808 const HWComposer& hwc = getHwComposer(); 809 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY); 810 if (presentFence->isValid()) { 811 mAnimFrameTracker.setActualPresentFence(presentFence); 812 } else { 813 // The HWC doesn't support present fences, so use the refresh 814 // timestamp instead. 815 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY); 816 mAnimFrameTracker.setActualPresentTime(presentTime); 817 } 818 mAnimFrameTracker.advanceFrame(); 819 } 820} 821 822void SurfaceFlinger::rebuildLayerStacks() { 823 // rebuild the visible layer list per screen 824 if (CC_UNLIKELY(mVisibleRegionsDirty)) { 825 ATRACE_CALL(); 826 mVisibleRegionsDirty = false; 827 invalidateHwcGeometry(); 828 829 const LayerVector& layers(mDrawingState.layersSortedByZ); 830 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 831 Region opaqueRegion; 832 Region dirtyRegion; 833 Vector< sp<Layer> > layersSortedByZ; 834 const sp<DisplayDevice>& hw(mDisplays[dpy]); 835 const Transform& tr(hw->getTransform()); 836 const Rect bounds(hw->getBounds()); 837 if (hw->canDraw()) { 838 SurfaceFlinger::computeVisibleRegions(layers, 839 hw->getLayerStack(), dirtyRegion, opaqueRegion); 840 841 const size_t count = layers.size(); 842 for (size_t i=0 ; i<count ; i++) { 843 const sp<Layer>& layer(layers[i]); 844 const Layer::State& s(layer->getDrawingState()); 845 if (s.layerStack == hw->getLayerStack()) { 846 Region drawRegion(tr.transform( 847 layer->visibleNonTransparentRegion)); 848 drawRegion.andSelf(bounds); 849 if (!drawRegion.isEmpty()) { 850 layersSortedByZ.add(layer); 851 } 852 } 853 } 854 } 855 hw->setVisibleLayersSortedByZ(layersSortedByZ); 856 hw->undefinedRegion.set(bounds); 857 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion)); 858 hw->dirtyRegion.orSelf(dirtyRegion); 859 } 860 } 861} 862 863void SurfaceFlinger::setUpHWComposer() { 864 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 865 mDisplays[dpy]->beginFrame(); 866 } 867 868 HWComposer& hwc(getHwComposer()); 869 if (hwc.initCheck() == NO_ERROR) { 870 // build the h/w work list 871 if (CC_UNLIKELY(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<Layer> >& currentLayers( 878 hw->getVisibleLayersSortedByZ()); 879 const size_t count = currentLayers.size(); 880 if (hwc.createWorkList(id, count) == NO_ERROR) { 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<Layer>& layer(currentLayers[i]); 885 layer->setGeometry(hw, *cur); 886 if (mDebugDisableHWC || mDebugRegion || mDaltonize) { 887 cur->setSkip(true); 888 } 889 } 890 } 891 } 892 } 893 } 894 895 // set the per-frame data 896 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 897 sp<const DisplayDevice> hw(mDisplays[dpy]); 898 const int32_t id = hw->getHwcDisplayId(); 899 if (id >= 0) { 900 const Vector< sp<Layer> >& currentLayers( 901 hw->getVisibleLayersSortedByZ()); 902 const size_t count = currentLayers.size(); 903 HWComposer::LayerListIterator cur = hwc.begin(id); 904 const HWComposer::LayerListIterator end = hwc.end(id); 905 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) { 906 /* 907 * update the per-frame h/w composer data for each layer 908 * and build the transparent region of the FB 909 */ 910 const sp<Layer>& layer(currentLayers[i]); 911 layer->setPerFrameData(hw, *cur); 912 } 913 } 914 } 915 916 status_t err = hwc.prepare(); 917 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err)); 918 919 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 920 sp<const DisplayDevice> hw(mDisplays[dpy]); 921 hw->prepareFrame(hwc); 922 } 923 } 924} 925 926void SurfaceFlinger::doComposition() { 927 ATRACE_CALL(); 928 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything); 929 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 930 const sp<DisplayDevice>& hw(mDisplays[dpy]); 931 if (hw->canDraw()) { 932 // transform the dirty region into this screen's coordinate space 933 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything)); 934 935 // repaint the framebuffer (if needed) 936 doDisplayComposition(hw, dirtyRegion); 937 938 hw->dirtyRegion.clear(); 939 hw->flip(hw->swapRegion); 940 hw->swapRegion.clear(); 941 } 942 // inform the h/w that we're done compositing 943 hw->compositionComplete(); 944 } 945 postFramebuffer(); 946} 947 948void SurfaceFlinger::postFramebuffer() 949{ 950 ATRACE_CALL(); 951 952 const nsecs_t now = systemTime(); 953 mDebugInSwapBuffers = now; 954 955 HWComposer& hwc(getHwComposer()); 956 if (hwc.initCheck() == NO_ERROR) { 957 if (!hwc.supportsFramebufferTarget()) { 958 // EGL spec says: 959 // "surface must be bound to the calling thread's current context, 960 // for the current rendering API." 961 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext); 962 } 963 hwc.commit(); 964 } 965 966 // make the default display current because the VirtualDisplayDevice code cannot 967 // deal with dequeueBuffer() being called outside of the composition loop; however 968 // the code below can call glFlush() which is allowed (and does in some case) call 969 // dequeueBuffer(). 970 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext); 971 972 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 973 sp<const DisplayDevice> hw(mDisplays[dpy]); 974 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ()); 975 hw->onSwapBuffersCompleted(hwc); 976 const size_t count = currentLayers.size(); 977 int32_t id = hw->getHwcDisplayId(); 978 if (id >=0 && hwc.initCheck() == NO_ERROR) { 979 HWComposer::LayerListIterator cur = hwc.begin(id); 980 const HWComposer::LayerListIterator end = hwc.end(id); 981 for (size_t i = 0; cur != end && i < count; ++i, ++cur) { 982 currentLayers[i]->onLayerDisplayed(hw, &*cur); 983 } 984 } else { 985 for (size_t i = 0; i < count; i++) { 986 currentLayers[i]->onLayerDisplayed(hw, NULL); 987 } 988 } 989 } 990 991 mLastSwapBufferTime = systemTime() - now; 992 mDebugInSwapBuffers = 0; 993 994 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount(); 995 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) { 996 logFrameStats(); 997 } 998} 999 1000void SurfaceFlinger::handleTransaction(uint32_t transactionFlags) 1001{ 1002 ATRACE_CALL(); 1003 1004 // here we keep a copy of the drawing state (that is the state that's 1005 // going to be overwritten by handleTransactionLocked()) outside of 1006 // mStateLock so that the side-effects of the State assignment 1007 // don't happen with mStateLock held (which can cause deadlocks). 1008 State drawingState(mDrawingState); 1009 1010 Mutex::Autolock _l(mStateLock); 1011 const nsecs_t now = systemTime(); 1012 mDebugInTransaction = now; 1013 1014 // Here we're guaranteed that some transaction flags are set 1015 // so we can call handleTransactionLocked() unconditionally. 1016 // We call getTransactionFlags(), which will also clear the flags, 1017 // with mStateLock held to guarantee that mCurrentState won't change 1018 // until the transaction is committed. 1019 1020 transactionFlags = getTransactionFlags(eTransactionMask); 1021 handleTransactionLocked(transactionFlags); 1022 1023 mLastTransactionTime = systemTime() - now; 1024 mDebugInTransaction = 0; 1025 invalidateHwcGeometry(); 1026 // here the transaction has been committed 1027} 1028 1029void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags) 1030{ 1031 const LayerVector& currentLayers(mCurrentState.layersSortedByZ); 1032 const size_t count = currentLayers.size(); 1033 1034 /* 1035 * Traversal of the children 1036 * (perform the transaction for each of them if needed) 1037 */ 1038 1039 if (transactionFlags & eTraversalNeeded) { 1040 for (size_t i=0 ; i<count ; i++) { 1041 const sp<Layer>& layer(currentLayers[i]); 1042 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded); 1043 if (!trFlags) continue; 1044 1045 const uint32_t flags = layer->doTransaction(0); 1046 if (flags & Layer::eVisibleRegion) 1047 mVisibleRegionsDirty = true; 1048 } 1049 } 1050 1051 /* 1052 * Perform display own transactions if needed 1053 */ 1054 1055 if (transactionFlags & eDisplayTransactionNeeded) { 1056 // here we take advantage of Vector's copy-on-write semantics to 1057 // improve performance by skipping the transaction entirely when 1058 // know that the lists are identical 1059 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays); 1060 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays); 1061 if (!curr.isIdenticalTo(draw)) { 1062 mVisibleRegionsDirty = true; 1063 const size_t cc = curr.size(); 1064 size_t dc = draw.size(); 1065 1066 // find the displays that were removed 1067 // (ie: in drawing state but not in current state) 1068 // also handle displays that changed 1069 // (ie: displays that are in both lists) 1070 for (size_t i=0 ; i<dc ; i++) { 1071 const ssize_t j = curr.indexOfKey(draw.keyAt(i)); 1072 if (j < 0) { 1073 // in drawing state but not in current state 1074 if (!draw[i].isMainDisplay()) { 1075 // Call makeCurrent() on the primary display so we can 1076 // be sure that nothing associated with this display 1077 // is current. 1078 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice()); 1079 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext); 1080 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i))); 1081 if (hw != NULL) 1082 hw->disconnect(getHwComposer()); 1083 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) 1084 mEventThread->onHotplugReceived(draw[i].type, false); 1085 mDisplays.removeItem(draw.keyAt(i)); 1086 } else { 1087 ALOGW("trying to remove the main display"); 1088 } 1089 } else { 1090 // this display is in both lists. see if something changed. 1091 const DisplayDeviceState& state(curr[j]); 1092 const wp<IBinder>& display(curr.keyAt(j)); 1093 if (state.surface->asBinder() != draw[i].surface->asBinder()) { 1094 // changing the surface is like destroying and 1095 // recreating the DisplayDevice, so we just remove it 1096 // from the drawing state, so that it get re-added 1097 // below. 1098 sp<DisplayDevice> hw(getDisplayDevice(display)); 1099 if (hw != NULL) 1100 hw->disconnect(getHwComposer()); 1101 mDisplays.removeItem(display); 1102 mDrawingState.displays.removeItemsAt(i); 1103 dc--; i--; 1104 // at this point we must loop to the next item 1105 continue; 1106 } 1107 1108 const sp<DisplayDevice> disp(getDisplayDevice(display)); 1109 if (disp != NULL) { 1110 if (state.layerStack != draw[i].layerStack) { 1111 disp->setLayerStack(state.layerStack); 1112 } 1113 if ((state.orientation != draw[i].orientation) 1114 || (state.viewport != draw[i].viewport) 1115 || (state.frame != draw[i].frame)) 1116 { 1117 disp->setProjection(state.orientation, 1118 state.viewport, state.frame); 1119 } 1120 } 1121 } 1122 } 1123 1124 // find displays that were added 1125 // (ie: in current state but not in drawing state) 1126 for (size_t i=0 ; i<cc ; i++) { 1127 if (draw.indexOfKey(curr.keyAt(i)) < 0) { 1128 const DisplayDeviceState& state(curr[i]); 1129 1130 sp<DisplaySurface> dispSurface; 1131 sp<IGraphicBufferProducer> producer; 1132 sp<BufferQueue> bq = new BufferQueue(new GraphicBufferAlloc()); 1133 1134 int32_t hwcDisplayId = -1; 1135 if (state.isVirtualDisplay()) { 1136 // Virtual displays without a surface are dormant: 1137 // they have external state (layer stack, projection, 1138 // etc.) but no internal state (i.e. a DisplayDevice). 1139 if (state.surface != NULL) { 1140 1141 hwcDisplayId = allocateHwcDisplayId(state.type); 1142 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface( 1143 *mHwc, hwcDisplayId, state.surface, bq, 1144 state.displayName); 1145 1146 dispSurface = vds; 1147 if (hwcDisplayId >= 0) { 1148 producer = vds; 1149 } else { 1150 // There won't be any interaction with HWC for this virtual display, 1151 // so the GLES driver can pass buffers directly to the sink. 1152 producer = state.surface; 1153 } 1154 } 1155 } else { 1156 ALOGE_IF(state.surface!=NULL, 1157 "adding a supported display, but rendering " 1158 "surface is provided (%p), ignoring it", 1159 state.surface.get()); 1160 hwcDisplayId = allocateHwcDisplayId(state.type); 1161 // for supported (by hwc) displays we provide our 1162 // own rendering surface 1163 dispSurface = new FramebufferSurface(*mHwc, state.type, bq); 1164 producer = bq; 1165 } 1166 1167 const wp<IBinder>& display(curr.keyAt(i)); 1168 if (dispSurface != NULL) { 1169 sp<DisplayDevice> hw = new DisplayDevice(this, 1170 state.type, hwcDisplayId, state.isSecure, 1171 display, dispSurface, producer, mEGLConfig); 1172 hw->setLayerStack(state.layerStack); 1173 hw->setProjection(state.orientation, 1174 state.viewport, state.frame); 1175 hw->setDisplayName(state.displayName); 1176 mDisplays.add(display, hw); 1177 if (state.isVirtualDisplay()) { 1178 if (hwcDisplayId >= 0) { 1179 mHwc->setVirtualDisplayProperties(hwcDisplayId, 1180 hw->getWidth(), hw->getHeight(), 1181 hw->getFormat()); 1182 } 1183 } else { 1184 mEventThread->onHotplugReceived(state.type, true); 1185 } 1186 } 1187 } 1188 } 1189 } 1190 } 1191 1192 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) { 1193 // The transform hint might have changed for some layers 1194 // (either because a display has changed, or because a layer 1195 // as changed). 1196 // 1197 // Walk through all the layers in currentLayers, 1198 // and update their transform hint. 1199 // 1200 // If a layer is visible only on a single display, then that 1201 // display is used to calculate the hint, otherwise we use the 1202 // default display. 1203 // 1204 // NOTE: we do this here, rather than in rebuildLayerStacks() so that 1205 // the hint is set before we acquire a buffer from the surface texture. 1206 // 1207 // NOTE: layer transactions have taken place already, so we use their 1208 // drawing state. However, SurfaceFlinger's own transaction has not 1209 // happened yet, so we must use the current state layer list 1210 // (soon to become the drawing state list). 1211 // 1212 sp<const DisplayDevice> disp; 1213 uint32_t currentlayerStack = 0; 1214 for (size_t i=0; i<count; i++) { 1215 // NOTE: we rely on the fact that layers are sorted by 1216 // layerStack first (so we don't have to traverse the list 1217 // of displays for every layer). 1218 const sp<Layer>& layer(currentLayers[i]); 1219 uint32_t layerStack = layer->getDrawingState().layerStack; 1220 if (i==0 || currentlayerStack != layerStack) { 1221 currentlayerStack = layerStack; 1222 // figure out if this layerstack is mirrored 1223 // (more than one display) if so, pick the default display, 1224 // if not, pick the only display it's on. 1225 disp.clear(); 1226 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 1227 sp<const DisplayDevice> hw(mDisplays[dpy]); 1228 if (hw->getLayerStack() == currentlayerStack) { 1229 if (disp == NULL) { 1230 disp = hw; 1231 } else { 1232 disp = NULL; 1233 break; 1234 } 1235 } 1236 } 1237 } 1238 if (disp == NULL) { 1239 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to 1240 // redraw after transform hint changes. See bug 8508397. 1241 1242 // could be null when this layer is using a layerStack 1243 // that is not visible on any display. Also can occur at 1244 // screen off/on times. 1245 disp = getDefaultDisplayDevice(); 1246 } 1247 layer->updateTransformHint(disp); 1248 } 1249 } 1250 1251 1252 /* 1253 * Perform our own transaction if needed 1254 */ 1255 1256 const LayerVector& layers(mDrawingState.layersSortedByZ); 1257 if (currentLayers.size() > layers.size()) { 1258 // layers have been added 1259 mVisibleRegionsDirty = true; 1260 } 1261 1262 // some layers might have been removed, so 1263 // we need to update the regions they're exposing. 1264 if (mLayersRemoved) { 1265 mLayersRemoved = false; 1266 mVisibleRegionsDirty = true; 1267 const size_t count = layers.size(); 1268 for (size_t i=0 ; i<count ; i++) { 1269 const sp<Layer>& layer(layers[i]); 1270 if (currentLayers.indexOf(layer) < 0) { 1271 // this layer is not visible anymore 1272 // TODO: we could traverse the tree from front to back and 1273 // compute the actual visible region 1274 // TODO: we could cache the transformed region 1275 const Layer::State& s(layer->getDrawingState()); 1276 Region visibleReg = s.transform.transform( 1277 Region(Rect(s.active.w, s.active.h))); 1278 invalidateLayerStack(s.layerStack, visibleReg); 1279 } 1280 } 1281 } 1282 1283 commitTransaction(); 1284} 1285 1286void SurfaceFlinger::commitTransaction() 1287{ 1288 if (!mLayersPendingRemoval.isEmpty()) { 1289 // Notify removed layers now that they can't be drawn from 1290 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) { 1291 mLayersPendingRemoval[i]->onRemoved(); 1292 } 1293 mLayersPendingRemoval.clear(); 1294 } 1295 1296 // If this transaction is part of a window animation then the next frame 1297 // we composite should be considered an animation as well. 1298 mAnimCompositionPending = mAnimTransactionPending; 1299 1300 mDrawingState = mCurrentState; 1301 mTransactionPending = false; 1302 mAnimTransactionPending = false; 1303 mTransactionCV.broadcast(); 1304} 1305 1306void SurfaceFlinger::computeVisibleRegions( 1307 const LayerVector& currentLayers, uint32_t layerStack, 1308 Region& outDirtyRegion, Region& outOpaqueRegion) 1309{ 1310 ATRACE_CALL(); 1311 1312 Region aboveOpaqueLayers; 1313 Region aboveCoveredLayers; 1314 Region dirty; 1315 1316 outDirtyRegion.clear(); 1317 1318 size_t i = currentLayers.size(); 1319 while (i--) { 1320 const sp<Layer>& layer = currentLayers[i]; 1321 1322 // start with the whole surface at its current location 1323 const Layer::State& s(layer->getDrawingState()); 1324 1325 // only consider the layers on the given layer stack 1326 if (s.layerStack != layerStack) 1327 continue; 1328 1329 /* 1330 * opaqueRegion: area of a surface that is fully opaque. 1331 */ 1332 Region opaqueRegion; 1333 1334 /* 1335 * visibleRegion: area of a surface that is visible on screen 1336 * and not fully transparent. This is essentially the layer's 1337 * footprint minus the opaque regions above it. 1338 * Areas covered by a translucent surface are considered visible. 1339 */ 1340 Region visibleRegion; 1341 1342 /* 1343 * coveredRegion: area of a surface that is covered by all 1344 * visible regions above it (which includes the translucent areas). 1345 */ 1346 Region coveredRegion; 1347 1348 /* 1349 * transparentRegion: area of a surface that is hinted to be completely 1350 * transparent. This is only used to tell when the layer has no visible 1351 * non-transparent regions and can be removed from the layer list. It 1352 * does not affect the visibleRegion of this layer or any layers 1353 * beneath it. The hint may not be correct if apps don't respect the 1354 * SurfaceView restrictions (which, sadly, some don't). 1355 */ 1356 Region transparentRegion; 1357 1358 1359 // handle hidden surfaces by setting the visible region to empty 1360 if (CC_LIKELY(layer->isVisible())) { 1361 const bool translucent = !layer->isOpaque(); 1362 Rect bounds(s.transform.transform(layer->computeBounds())); 1363 visibleRegion.set(bounds); 1364 if (!visibleRegion.isEmpty()) { 1365 // Remove the transparent area from the visible region 1366 if (translucent) { 1367 const Transform tr(s.transform); 1368 if (tr.transformed()) { 1369 if (tr.preserveRects()) { 1370 // transform the transparent region 1371 transparentRegion = tr.transform(s.activeTransparentRegion); 1372 } else { 1373 // transformation too complex, can't do the 1374 // transparent region optimization. 1375 transparentRegion.clear(); 1376 } 1377 } else { 1378 transparentRegion = s.activeTransparentRegion; 1379 } 1380 } 1381 1382 // compute the opaque region 1383 const int32_t layerOrientation = s.transform.getOrientation(); 1384 if (s.alpha==255 && !translucent && 1385 ((layerOrientation & Transform::ROT_INVALID) == false)) { 1386 // the opaque region is the layer's footprint 1387 opaqueRegion = visibleRegion; 1388 } 1389 } 1390 } 1391 1392 // Clip the covered region to the visible region 1393 coveredRegion = aboveCoveredLayers.intersect(visibleRegion); 1394 1395 // Update aboveCoveredLayers for next (lower) layer 1396 aboveCoveredLayers.orSelf(visibleRegion); 1397 1398 // subtract the opaque region covered by the layers above us 1399 visibleRegion.subtractSelf(aboveOpaqueLayers); 1400 1401 // compute this layer's dirty region 1402 if (layer->contentDirty) { 1403 // we need to invalidate the whole region 1404 dirty = visibleRegion; 1405 // as well, as the old visible region 1406 dirty.orSelf(layer->visibleRegion); 1407 layer->contentDirty = false; 1408 } else { 1409 /* compute the exposed region: 1410 * the exposed region consists of two components: 1411 * 1) what's VISIBLE now and was COVERED before 1412 * 2) what's EXPOSED now less what was EXPOSED before 1413 * 1414 * note that (1) is conservative, we start with the whole 1415 * visible region but only keep what used to be covered by 1416 * something -- which mean it may have been exposed. 1417 * 1418 * (2) handles areas that were not covered by anything but got 1419 * exposed because of a resize. 1420 */ 1421 const Region newExposed = visibleRegion - coveredRegion; 1422 const Region oldVisibleRegion = layer->visibleRegion; 1423 const Region oldCoveredRegion = layer->coveredRegion; 1424 const Region oldExposed = oldVisibleRegion - oldCoveredRegion; 1425 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed); 1426 } 1427 dirty.subtractSelf(aboveOpaqueLayers); 1428 1429 // accumulate to the screen dirty region 1430 outDirtyRegion.orSelf(dirty); 1431 1432 // Update aboveOpaqueLayers for next (lower) layer 1433 aboveOpaqueLayers.orSelf(opaqueRegion); 1434 1435 // Store the visible region in screen space 1436 layer->setVisibleRegion(visibleRegion); 1437 layer->setCoveredRegion(coveredRegion); 1438 layer->setVisibleNonTransparentRegion( 1439 visibleRegion.subtract(transparentRegion)); 1440 } 1441 1442 outOpaqueRegion = aboveOpaqueLayers; 1443} 1444 1445void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack, 1446 const Region& dirty) { 1447 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 1448 const sp<DisplayDevice>& hw(mDisplays[dpy]); 1449 if (hw->getLayerStack() == layerStack) { 1450 hw->dirtyRegion.orSelf(dirty); 1451 } 1452 } 1453} 1454 1455void SurfaceFlinger::handlePageFlip() 1456{ 1457 Region dirtyRegion; 1458 1459 bool visibleRegions = false; 1460 const LayerVector& layers(mDrawingState.layersSortedByZ); 1461 const size_t count = layers.size(); 1462 for (size_t i=0 ; i<count ; i++) { 1463 const sp<Layer>& layer(layers[i]); 1464 const Region dirty(layer->latchBuffer(visibleRegions)); 1465 const Layer::State& s(layer->getDrawingState()); 1466 invalidateLayerStack(s.layerStack, dirty); 1467 } 1468 1469 mVisibleRegionsDirty |= visibleRegions; 1470} 1471 1472void SurfaceFlinger::invalidateHwcGeometry() 1473{ 1474 mHwWorkListDirty = true; 1475} 1476 1477 1478void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw, 1479 const Region& inDirtyRegion) 1480{ 1481 Region dirtyRegion(inDirtyRegion); 1482 1483 // compute the invalid region 1484 hw->swapRegion.orSelf(dirtyRegion); 1485 1486 uint32_t flags = hw->getFlags(); 1487 if (flags & DisplayDevice::SWAP_RECTANGLE) { 1488 // we can redraw only what's dirty, but since SWAP_RECTANGLE only 1489 // takes a rectangle, we must make sure to update that whole 1490 // rectangle in that case 1491 dirtyRegion.set(hw->swapRegion.bounds()); 1492 } else { 1493 if (flags & DisplayDevice::PARTIAL_UPDATES) { 1494 // We need to redraw the rectangle that will be updated 1495 // (pushed to the framebuffer). 1496 // This is needed because PARTIAL_UPDATES only takes one 1497 // rectangle instead of a region (see DisplayDevice::flip()) 1498 dirtyRegion.set(hw->swapRegion.bounds()); 1499 } else { 1500 // we need to redraw everything (the whole screen) 1501 dirtyRegion.set(hw->bounds()); 1502 hw->swapRegion = dirtyRegion; 1503 } 1504 } 1505 1506 if (CC_LIKELY(!mDaltonize)) { 1507 doComposeSurfaces(hw, dirtyRegion); 1508 } else { 1509 RenderEngine& engine(getRenderEngine()); 1510 engine.beginGroup(mDaltonizer()); 1511 doComposeSurfaces(hw, dirtyRegion); 1512 engine.endGroup(); 1513 } 1514 1515 // update the swap region and clear the dirty region 1516 hw->swapRegion.orSelf(dirtyRegion); 1517 1518 // swap buffers (presentation) 1519 hw->swapBuffers(getHwComposer()); 1520} 1521 1522void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty) 1523{ 1524 RenderEngine& engine(getRenderEngine()); 1525 const int32_t id = hw->getHwcDisplayId(); 1526 HWComposer& hwc(getHwComposer()); 1527 HWComposer::LayerListIterator cur = hwc.begin(id); 1528 const HWComposer::LayerListIterator end = hwc.end(id); 1529 1530 bool hasGlesComposition = hwc.hasGlesComposition(id); 1531 if (hasGlesComposition) { 1532 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) { 1533 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s", 1534 hw->getDisplayName().string()); 1535 return; 1536 } 1537 1538 // Never touch the framebuffer if we don't have any framebuffer layers 1539 const bool hasHwcComposition = hwc.hasHwcComposition(id); 1540 if (hasHwcComposition) { 1541 // when using overlays, we assume a fully transparent framebuffer 1542 // NOTE: we could reduce how much we need to clear, for instance 1543 // remove where there are opaque FB layers. however, on some 1544 // GPUs doing a "clean slate" clear might be more efficient. 1545 // We'll revisit later if needed. 1546 engine.clearWithColor(0, 0, 0, 0); 1547 } else { 1548 // we start with the whole screen area 1549 const Region bounds(hw->getBounds()); 1550 1551 // we remove the scissor part 1552 // we're left with the letterbox region 1553 // (common case is that letterbox ends-up being empty) 1554 const Region letterbox(bounds.subtract(hw->getScissor())); 1555 1556 // compute the area to clear 1557 Region region(hw->undefinedRegion.merge(letterbox)); 1558 1559 // but limit it to the dirty region 1560 region.andSelf(dirty); 1561 1562 // screen is already cleared here 1563 if (!region.isEmpty()) { 1564 // can happen with SurfaceView 1565 drawWormhole(hw, region); 1566 } 1567 } 1568 1569 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) { 1570 // just to be on the safe side, we don't set the 1571 // scissor on the main display. It should never be needed 1572 // anyways (though in theory it could since the API allows it). 1573 const Rect& bounds(hw->getBounds()); 1574 const Rect& scissor(hw->getScissor()); 1575 if (scissor != bounds) { 1576 // scissor doesn't match the screen's dimensions, so we 1577 // need to clear everything outside of it and enable 1578 // the GL scissor so we don't draw anything where we shouldn't 1579 1580 // enable scissor for this frame 1581 const uint32_t height = hw->getHeight(); 1582 engine.setScissor(scissor.left, height - scissor.bottom, 1583 scissor.getWidth(), scissor.getHeight()); 1584 } 1585 } 1586 } 1587 1588 /* 1589 * and then, render the layers targeted at the framebuffer 1590 */ 1591 1592 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ()); 1593 const size_t count = layers.size(); 1594 const Transform& tr = hw->getTransform(); 1595 if (cur != end) { 1596 // we're using h/w composer 1597 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) { 1598 const sp<Layer>& layer(layers[i]); 1599 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion))); 1600 if (!clip.isEmpty()) { 1601 switch (cur->getCompositionType()) { 1602 case HWC_OVERLAY: { 1603 if ((cur->getHints() & HWC_HINT_CLEAR_FB) 1604 && i 1605 && layer->isOpaque() 1606 && hasGlesComposition) { 1607 // never clear the very first layer since we're 1608 // guaranteed the FB is already cleared 1609 layer->clearWithOpenGL(hw, clip); 1610 } 1611 break; 1612 } 1613 case HWC_FRAMEBUFFER: { 1614 layer->draw(hw, clip); 1615 break; 1616 } 1617 case HWC_FRAMEBUFFER_TARGET: { 1618 // this should not happen as the iterator shouldn't 1619 // let us get there. 1620 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%d)", i); 1621 break; 1622 } 1623 } 1624 } 1625 layer->setAcquireFence(hw, *cur); 1626 } 1627 } else { 1628 // we're not using h/w composer 1629 for (size_t i=0 ; i<count ; ++i) { 1630 const sp<Layer>& layer(layers[i]); 1631 const Region clip(dirty.intersect( 1632 tr.transform(layer->visibleRegion))); 1633 if (!clip.isEmpty()) { 1634 layer->draw(hw, clip); 1635 } 1636 } 1637 } 1638 1639 // disable scissor at the end of the frame 1640 engine.disableScissor(); 1641} 1642 1643void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const { 1644 const int32_t height = hw->getHeight(); 1645 RenderEngine& engine(getRenderEngine()); 1646 engine.fillRegionWithColor(region, height, 0, 0, 0, 0); 1647} 1648 1649void SurfaceFlinger::addClientLayer(const sp<Client>& client, 1650 const sp<IBinder>& handle, 1651 const sp<IGraphicBufferProducer>& gbc, 1652 const sp<Layer>& lbc) 1653{ 1654 // attach this layer to the client 1655 client->attachLayer(handle, lbc); 1656 1657 // add this layer to the current state list 1658 Mutex::Autolock _l(mStateLock); 1659 mCurrentState.layersSortedByZ.add(lbc); 1660 mGraphicBufferProducerList.add(gbc->asBinder()); 1661} 1662 1663status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) { 1664 Mutex::Autolock _l(mStateLock); 1665 ssize_t index = mCurrentState.layersSortedByZ.remove(layer); 1666 if (index >= 0) { 1667 mLayersPendingRemoval.push(layer); 1668 mLayersRemoved = true; 1669 setTransactionFlags(eTransactionNeeded); 1670 return NO_ERROR; 1671 } 1672 return status_t(index); 1673} 1674 1675uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags) { 1676 return android_atomic_release_load(&mTransactionFlags); 1677} 1678 1679uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) { 1680 return android_atomic_and(~flags, &mTransactionFlags) & flags; 1681} 1682 1683uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) { 1684 uint32_t old = android_atomic_or(flags, &mTransactionFlags); 1685 if ((old & flags)==0) { // wake the server up 1686 signalTransaction(); 1687 } 1688 return old; 1689} 1690 1691void SurfaceFlinger::setTransactionState( 1692 const Vector<ComposerState>& state, 1693 const Vector<DisplayState>& displays, 1694 uint32_t flags) 1695{ 1696 ATRACE_CALL(); 1697 Mutex::Autolock _l(mStateLock); 1698 uint32_t transactionFlags = 0; 1699 1700 if (flags & eAnimation) { 1701 // For window updates that are part of an animation we must wait for 1702 // previous animation "frames" to be handled. 1703 while (mAnimTransactionPending) { 1704 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5)); 1705 if (CC_UNLIKELY(err != NO_ERROR)) { 1706 // just in case something goes wrong in SF, return to the 1707 // caller after a few seconds. 1708 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out " 1709 "waiting for previous animation frame"); 1710 mAnimTransactionPending = false; 1711 break; 1712 } 1713 } 1714 } 1715 1716 size_t count = displays.size(); 1717 for (size_t i=0 ; i<count ; i++) { 1718 const DisplayState& s(displays[i]); 1719 transactionFlags |= setDisplayStateLocked(s); 1720 } 1721 1722 count = state.size(); 1723 for (size_t i=0 ; i<count ; i++) { 1724 const ComposerState& s(state[i]); 1725 // Here we need to check that the interface we're given is indeed 1726 // one of our own. A malicious client could give us a NULL 1727 // IInterface, or one of its own or even one of our own but a 1728 // different type. All these situations would cause us to crash. 1729 // 1730 // NOTE: it would be better to use RTTI as we could directly check 1731 // that we have a Client*. however, RTTI is disabled in Android. 1732 if (s.client != NULL) { 1733 sp<IBinder> binder = s.client->asBinder(); 1734 if (binder != NULL) { 1735 String16 desc(binder->getInterfaceDescriptor()); 1736 if (desc == ISurfaceComposerClient::descriptor) { 1737 sp<Client> client( static_cast<Client *>(s.client.get()) ); 1738 transactionFlags |= setClientStateLocked(client, s.state); 1739 } 1740 } 1741 } 1742 } 1743 1744 if (transactionFlags) { 1745 // this triggers the transaction 1746 setTransactionFlags(transactionFlags); 1747 1748 // if this is a synchronous transaction, wait for it to take effect 1749 // before returning. 1750 if (flags & eSynchronous) { 1751 mTransactionPending = true; 1752 } 1753 if (flags & eAnimation) { 1754 mAnimTransactionPending = true; 1755 } 1756 while (mTransactionPending) { 1757 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5)); 1758 if (CC_UNLIKELY(err != NO_ERROR)) { 1759 // just in case something goes wrong in SF, return to the 1760 // called after a few seconds. 1761 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!"); 1762 mTransactionPending = false; 1763 break; 1764 } 1765 } 1766 } 1767} 1768 1769uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) 1770{ 1771 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token); 1772 if (dpyIdx < 0) 1773 return 0; 1774 1775 uint32_t flags = 0; 1776 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx)); 1777 if (disp.isValid()) { 1778 const uint32_t what = s.what; 1779 if (what & DisplayState::eSurfaceChanged) { 1780 if (disp.surface->asBinder() != s.surface->asBinder()) { 1781 disp.surface = s.surface; 1782 flags |= eDisplayTransactionNeeded; 1783 } 1784 } 1785 if (what & DisplayState::eLayerStackChanged) { 1786 if (disp.layerStack != s.layerStack) { 1787 disp.layerStack = s.layerStack; 1788 flags |= eDisplayTransactionNeeded; 1789 } 1790 } 1791 if (what & DisplayState::eDisplayProjectionChanged) { 1792 if (disp.orientation != s.orientation) { 1793 disp.orientation = s.orientation; 1794 flags |= eDisplayTransactionNeeded; 1795 } 1796 if (disp.frame != s.frame) { 1797 disp.frame = s.frame; 1798 flags |= eDisplayTransactionNeeded; 1799 } 1800 if (disp.viewport != s.viewport) { 1801 disp.viewport = s.viewport; 1802 flags |= eDisplayTransactionNeeded; 1803 } 1804 } 1805 } 1806 return flags; 1807} 1808 1809uint32_t SurfaceFlinger::setClientStateLocked( 1810 const sp<Client>& client, 1811 const layer_state_t& s) 1812{ 1813 uint32_t flags = 0; 1814 sp<Layer> layer(client->getLayerUser(s.surface)); 1815 if (layer != 0) { 1816 const uint32_t what = s.what; 1817 if (what & layer_state_t::ePositionChanged) { 1818 if (layer->setPosition(s.x, s.y)) 1819 flags |= eTraversalNeeded; 1820 } 1821 if (what & layer_state_t::eLayerChanged) { 1822 // NOTE: index needs to be calculated before we update the state 1823 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); 1824 if (layer->setLayer(s.z)) { 1825 mCurrentState.layersSortedByZ.removeAt(idx); 1826 mCurrentState.layersSortedByZ.add(layer); 1827 // we need traversal (state changed) 1828 // AND transaction (list changed) 1829 flags |= eTransactionNeeded|eTraversalNeeded; 1830 } 1831 } 1832 if (what & layer_state_t::eSizeChanged) { 1833 if (layer->setSize(s.w, s.h)) { 1834 flags |= eTraversalNeeded; 1835 } 1836 } 1837 if (what & layer_state_t::eAlphaChanged) { 1838 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f))) 1839 flags |= eTraversalNeeded; 1840 } 1841 if (what & layer_state_t::eMatrixChanged) { 1842 if (layer->setMatrix(s.matrix)) 1843 flags |= eTraversalNeeded; 1844 } 1845 if (what & layer_state_t::eTransparentRegionChanged) { 1846 if (layer->setTransparentRegionHint(s.transparentRegion)) 1847 flags |= eTraversalNeeded; 1848 } 1849 if (what & layer_state_t::eVisibilityChanged) { 1850 if (layer->setFlags(s.flags, s.mask)) 1851 flags |= eTraversalNeeded; 1852 } 1853 if (what & layer_state_t::eCropChanged) { 1854 if (layer->setCrop(s.crop)) 1855 flags |= eTraversalNeeded; 1856 } 1857 if (what & layer_state_t::eLayerStackChanged) { 1858 // NOTE: index needs to be calculated before we update the state 1859 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); 1860 if (layer->setLayerStack(s.layerStack)) { 1861 mCurrentState.layersSortedByZ.removeAt(idx); 1862 mCurrentState.layersSortedByZ.add(layer); 1863 // we need traversal (state changed) 1864 // AND transaction (list changed) 1865 flags |= eTransactionNeeded|eTraversalNeeded; 1866 } 1867 } 1868 } 1869 return flags; 1870} 1871 1872status_t SurfaceFlinger::createLayer( 1873 const String8& name, 1874 const sp<Client>& client, 1875 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags, 1876 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp) 1877{ 1878 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string()); 1879 if (int32_t(w|h) < 0) { 1880 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)", 1881 int(w), int(h)); 1882 return BAD_VALUE; 1883 } 1884 1885 status_t result = NO_ERROR; 1886 1887 sp<Layer> layer; 1888 1889 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) { 1890 case ISurfaceComposerClient::eFXSurfaceNormal: 1891 result = createNormalLayer(client, 1892 name, w, h, flags, format, 1893 handle, gbp, &layer); 1894 break; 1895 case ISurfaceComposerClient::eFXSurfaceDim: 1896 result = createDimLayer(client, 1897 name, w, h, flags, 1898 handle, gbp, &layer); 1899 break; 1900 default: 1901 result = BAD_VALUE; 1902 break; 1903 } 1904 1905 if (result == NO_ERROR) { 1906 addClientLayer(client, *handle, *gbp, layer); 1907 setTransactionFlags(eTransactionNeeded); 1908 } 1909 return result; 1910} 1911 1912status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client, 1913 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format, 1914 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer) 1915{ 1916 // initialize the surfaces 1917 switch (format) { 1918 case PIXEL_FORMAT_TRANSPARENT: 1919 case PIXEL_FORMAT_TRANSLUCENT: 1920 format = PIXEL_FORMAT_RGBA_8888; 1921 break; 1922 case PIXEL_FORMAT_OPAQUE: 1923#ifdef NO_RGBX_8888 1924 format = PIXEL_FORMAT_RGB_565; 1925#else 1926 format = PIXEL_FORMAT_RGBX_8888; 1927#endif 1928 break; 1929 } 1930 1931#ifdef NO_RGBX_8888 1932 if (format == PIXEL_FORMAT_RGBX_8888) 1933 format = PIXEL_FORMAT_RGBA_8888; 1934#endif 1935 1936 *outLayer = new Layer(this, client, name, w, h, flags); 1937 status_t err = (*outLayer)->setBuffers(w, h, format, flags); 1938 if (err == NO_ERROR) { 1939 *handle = (*outLayer)->getHandle(); 1940 *gbp = (*outLayer)->getBufferQueue(); 1941 } 1942 1943 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err)); 1944 return err; 1945} 1946 1947status_t SurfaceFlinger::createDimLayer(const sp<Client>& client, 1948 const String8& name, uint32_t w, uint32_t h, uint32_t flags, 1949 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer) 1950{ 1951 *outLayer = new LayerDim(this, client, name, w, h, flags); 1952 *handle = (*outLayer)->getHandle(); 1953 *gbp = (*outLayer)->getBufferQueue(); 1954 return NO_ERROR; 1955} 1956 1957status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle) 1958{ 1959 // called by the window manager when it wants to remove a Layer 1960 status_t err = NO_ERROR; 1961 sp<Layer> l(client->getLayerUser(handle)); 1962 if (l != NULL) { 1963 err = removeLayer(l); 1964 ALOGE_IF(err<0 && err != NAME_NOT_FOUND, 1965 "error removing layer=%p (%s)", l.get(), strerror(-err)); 1966 } 1967 return err; 1968} 1969 1970status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer) 1971{ 1972 // called by ~LayerCleaner() when all references to the IBinder (handle) 1973 // are gone 1974 status_t err = NO_ERROR; 1975 sp<Layer> l(layer.promote()); 1976 if (l != NULL) { 1977 err = removeLayer(l); 1978 ALOGE_IF(err<0 && err != NAME_NOT_FOUND, 1979 "error removing layer=%p (%s)", l.get(), strerror(-err)); 1980 } 1981 return err; 1982} 1983 1984// --------------------------------------------------------------------------- 1985 1986void SurfaceFlinger::onInitializeDisplays() { 1987 // reset screen orientation and use primary layer stack 1988 Vector<ComposerState> state; 1989 Vector<DisplayState> displays; 1990 DisplayState d; 1991 d.what = DisplayState::eDisplayProjectionChanged | 1992 DisplayState::eLayerStackChanged; 1993 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]; 1994 d.layerStack = 0; 1995 d.orientation = DisplayState::eOrientationDefault; 1996 d.frame.makeInvalid(); 1997 d.viewport.makeInvalid(); 1998 displays.add(d); 1999 setTransactionState(state, displays, 0); 2000 onScreenAcquired(getDefaultDisplayDevice()); 2001 2002 const nsecs_t period = 2003 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY); 2004 mAnimFrameTracker.setDisplayRefreshPeriod(period); 2005} 2006 2007void SurfaceFlinger::initializeDisplays() { 2008 class MessageScreenInitialized : public MessageBase { 2009 SurfaceFlinger* flinger; 2010 public: 2011 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { } 2012 virtual bool handler() { 2013 flinger->onInitializeDisplays(); 2014 return true; 2015 } 2016 }; 2017 sp<MessageBase> msg = new MessageScreenInitialized(this); 2018 postMessageAsync(msg); // we may be called from main thread, use async message 2019} 2020 2021 2022void SurfaceFlinger::onScreenAcquired(const sp<const DisplayDevice>& hw) { 2023 ALOGD("Screen acquired, type=%d flinger=%p", hw->getDisplayType(), this); 2024 if (hw->isScreenAcquired()) { 2025 // this is expected, e.g. when power manager wakes up during boot 2026 ALOGD(" screen was previously acquired"); 2027 return; 2028 } 2029 2030 hw->acquireScreen(); 2031 int32_t type = hw->getDisplayType(); 2032 if (type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) { 2033 // built-in display, tell the HWC 2034 getHwComposer().acquire(type); 2035 2036 if (type == DisplayDevice::DISPLAY_PRIMARY) { 2037 // FIXME: eventthread only knows about the main display right now 2038 mEventThread->onScreenAcquired(); 2039 } 2040 } 2041 mVisibleRegionsDirty = true; 2042 repaintEverything(); 2043} 2044 2045void SurfaceFlinger::onScreenReleased(const sp<const DisplayDevice>& hw) { 2046 ALOGD("Screen released, type=%d flinger=%p", hw->getDisplayType(), this); 2047 if (!hw->isScreenAcquired()) { 2048 ALOGD(" screen was previously released"); 2049 return; 2050 } 2051 2052 hw->releaseScreen(); 2053 int32_t type = hw->getDisplayType(); 2054 if (type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) { 2055 if (type == DisplayDevice::DISPLAY_PRIMARY) { 2056 // FIXME: eventthread only knows about the main display right now 2057 mEventThread->onScreenReleased(); 2058 } 2059 2060 // built-in display, tell the HWC 2061 getHwComposer().release(type); 2062 } 2063 mVisibleRegionsDirty = true; 2064 // from this point on, SF will stop drawing on this display 2065} 2066 2067void SurfaceFlinger::unblank(const sp<IBinder>& display) { 2068 class MessageScreenAcquired : public MessageBase { 2069 SurfaceFlinger& mFlinger; 2070 sp<IBinder> mDisplay; 2071 public: 2072 MessageScreenAcquired(SurfaceFlinger& flinger, 2073 const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { } 2074 virtual bool handler() { 2075 const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay)); 2076 if (hw == NULL) { 2077 ALOGE("Attempt to unblank null display %p", mDisplay.get()); 2078 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) { 2079 ALOGW("Attempt to unblank virtual display"); 2080 } else { 2081 mFlinger.onScreenAcquired(hw); 2082 } 2083 return true; 2084 } 2085 }; 2086 sp<MessageBase> msg = new MessageScreenAcquired(*this, display); 2087 postMessageSync(msg); 2088} 2089 2090void SurfaceFlinger::blank(const sp<IBinder>& display) { 2091 class MessageScreenReleased : public MessageBase { 2092 SurfaceFlinger& mFlinger; 2093 sp<IBinder> mDisplay; 2094 public: 2095 MessageScreenReleased(SurfaceFlinger& flinger, 2096 const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { } 2097 virtual bool handler() { 2098 const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay)); 2099 if (hw == NULL) { 2100 ALOGE("Attempt to blank null display %p", mDisplay.get()); 2101 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) { 2102 ALOGW("Attempt to blank virtual display"); 2103 } else { 2104 mFlinger.onScreenReleased(hw); 2105 } 2106 return true; 2107 } 2108 }; 2109 sp<MessageBase> msg = new MessageScreenReleased(*this, display); 2110 postMessageSync(msg); 2111} 2112 2113// --------------------------------------------------------------------------- 2114 2115status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args) 2116{ 2117 String8 result; 2118 2119 IPCThreadState* ipc = IPCThreadState::self(); 2120 const int pid = ipc->getCallingPid(); 2121 const int uid = ipc->getCallingUid(); 2122 if ((uid != AID_SHELL) && 2123 !PermissionCache::checkPermission(sDump, pid, uid)) { 2124 result.appendFormat("Permission Denial: " 2125 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid); 2126 } else { 2127 // Try to get the main lock, but don't insist if we can't 2128 // (this would indicate SF is stuck, but we want to be able to 2129 // print something in dumpsys). 2130 int retry = 3; 2131 while (mStateLock.tryLock()<0 && --retry>=0) { 2132 usleep(1000000); 2133 } 2134 const bool locked(retry >= 0); 2135 if (!locked) { 2136 result.append( 2137 "SurfaceFlinger appears to be unresponsive, " 2138 "dumping anyways (no locks held)\n"); 2139 } 2140 2141 bool dumpAll = true; 2142 size_t index = 0; 2143 size_t numArgs = args.size(); 2144 if (numArgs) { 2145 if ((index < numArgs) && 2146 (args[index] == String16("--list"))) { 2147 index++; 2148 listLayersLocked(args, index, result); 2149 dumpAll = false; 2150 } 2151 2152 if ((index < numArgs) && 2153 (args[index] == String16("--latency"))) { 2154 index++; 2155 dumpStatsLocked(args, index, result); 2156 dumpAll = false; 2157 } 2158 2159 if ((index < numArgs) && 2160 (args[index] == String16("--latency-clear"))) { 2161 index++; 2162 clearStatsLocked(args, index, result); 2163 dumpAll = false; 2164 } 2165 } 2166 2167 if (dumpAll) { 2168 dumpAllLocked(args, index, result); 2169 } 2170 2171 if (locked) { 2172 mStateLock.unlock(); 2173 } 2174 } 2175 write(fd, result.string(), result.size()); 2176 return NO_ERROR; 2177} 2178 2179void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index, 2180 String8& result) const 2181{ 2182 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2183 const size_t count = currentLayers.size(); 2184 for (size_t i=0 ; i<count ; i++) { 2185 const sp<Layer>& layer(currentLayers[i]); 2186 result.appendFormat("%s\n", layer->getName().string()); 2187 } 2188} 2189 2190void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index, 2191 String8& result) const 2192{ 2193 String8 name; 2194 if (index < args.size()) { 2195 name = String8(args[index]); 2196 index++; 2197 } 2198 2199 const nsecs_t period = 2200 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY); 2201 result.appendFormat("%lld\n", period); 2202 2203 if (name.isEmpty()) { 2204 mAnimFrameTracker.dump(result); 2205 } else { 2206 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2207 const size_t count = currentLayers.size(); 2208 for (size_t i=0 ; i<count ; i++) { 2209 const sp<Layer>& layer(currentLayers[i]); 2210 if (name == layer->getName()) { 2211 layer->dumpStats(result); 2212 } 2213 } 2214 } 2215} 2216 2217void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index, 2218 String8& result) 2219{ 2220 String8 name; 2221 if (index < args.size()) { 2222 name = String8(args[index]); 2223 index++; 2224 } 2225 2226 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2227 const size_t count = currentLayers.size(); 2228 for (size_t i=0 ; i<count ; i++) { 2229 const sp<Layer>& layer(currentLayers[i]); 2230 if (name.isEmpty() || (name == layer->getName())) { 2231 layer->clearStats(); 2232 } 2233 } 2234 2235 mAnimFrameTracker.clear(); 2236} 2237 2238// This should only be called from the main thread. Otherwise it would need 2239// the lock and should use mCurrentState rather than mDrawingState. 2240void SurfaceFlinger::logFrameStats() { 2241 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ; 2242 const size_t count = drawingLayers.size(); 2243 for (size_t i=0 ; i<count ; i++) { 2244 const sp<Layer>& layer(drawingLayers[i]); 2245 layer->logFrameStats(); 2246 } 2247 2248 mAnimFrameTracker.logAndResetStats(String8("<win-anim>")); 2249} 2250 2251/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result) 2252{ 2253 static const char* config = 2254 " [sf" 2255#ifdef NO_RGBX_8888 2256 " NO_RGBX_8888" 2257#endif 2258#ifdef HAS_CONTEXT_PRIORITY 2259 " HAS_CONTEXT_PRIORITY" 2260#endif 2261#ifdef NEVER_DEFAULT_TO_ASYNC_MODE 2262 " NEVER_DEFAULT_TO_ASYNC_MODE" 2263#endif 2264#ifdef TARGET_DISABLE_TRIPLE_BUFFERING 2265 " TARGET_DISABLE_TRIPLE_BUFFERING" 2266#endif 2267 "]"; 2268 result.append(config); 2269} 2270 2271void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index, 2272 String8& result) const 2273{ 2274 bool colorize = false; 2275 if (index < args.size() 2276 && (args[index] == String16("--color"))) { 2277 colorize = true; 2278 index++; 2279 } 2280 2281 Colorizer colorizer(colorize); 2282 2283 // figure out if we're stuck somewhere 2284 const nsecs_t now = systemTime(); 2285 const nsecs_t inSwapBuffers(mDebugInSwapBuffers); 2286 const nsecs_t inTransaction(mDebugInTransaction); 2287 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0; 2288 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0; 2289 2290 /* 2291 * Dump library configuration. 2292 */ 2293 2294 colorizer.bold(result); 2295 result.append("Build configuration:"); 2296 colorizer.reset(result); 2297 appendSfConfigString(result); 2298 appendUiConfigString(result); 2299 appendGuiConfigString(result); 2300 result.append("\n"); 2301 2302 colorizer.bold(result); 2303 result.append("Sync configuration: "); 2304 colorizer.reset(result); 2305 result.append(SyncFeatures::getInstance().toString()); 2306 result.append("\n"); 2307 2308 /* 2309 * Dump the visible layer list 2310 */ 2311 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2312 const size_t count = currentLayers.size(); 2313 colorizer.bold(result); 2314 result.appendFormat("Visible layers (count = %d)\n", count); 2315 colorizer.reset(result); 2316 for (size_t i=0 ; i<count ; i++) { 2317 const sp<Layer>& layer(currentLayers[i]); 2318 layer->dump(result, colorizer); 2319 } 2320 2321 /* 2322 * Dump Display state 2323 */ 2324 2325 colorizer.bold(result); 2326 result.appendFormat("Displays (%d entries)\n", mDisplays.size()); 2327 colorizer.reset(result); 2328 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 2329 const sp<const DisplayDevice>& hw(mDisplays[dpy]); 2330 hw->dump(result); 2331 } 2332 2333 /* 2334 * Dump SurfaceFlinger global state 2335 */ 2336 2337 colorizer.bold(result); 2338 result.append("SurfaceFlinger global state:\n"); 2339 colorizer.reset(result); 2340 2341 HWComposer& hwc(getHwComposer()); 2342 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 2343 2344 colorizer.bold(result); 2345 result.appendFormat("EGL implementation : %s\n", 2346 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION)); 2347 colorizer.reset(result); 2348 result.appendFormat("%s\n", 2349 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS)); 2350 2351 mRenderEngine->dump(result); 2352 2353 hw->undefinedRegion.dump(result, "undefinedRegion"); 2354 result.appendFormat(" orientation=%d, canDraw=%d\n", 2355 hw->getOrientation(), hw->canDraw()); 2356 result.appendFormat( 2357 " last eglSwapBuffers() time: %f us\n" 2358 " last transaction time : %f us\n" 2359 " transaction-flags : %08x\n" 2360 " refresh-rate : %f fps\n" 2361 " x-dpi : %f\n" 2362 " y-dpi : %f\n" 2363 " EGL_NATIVE_VISUAL_ID : %d\n" 2364 " gpu_to_cpu_unsupported : %d\n" 2365 , 2366 mLastSwapBufferTime/1000.0, 2367 mLastTransactionTime/1000.0, 2368 mTransactionFlags, 2369 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY), 2370 hwc.getDpiX(HWC_DISPLAY_PRIMARY), 2371 hwc.getDpiY(HWC_DISPLAY_PRIMARY), 2372 mEGLNativeVisualId, 2373 !mGpuToCpuSupported); 2374 2375 result.appendFormat(" eglSwapBuffers time: %f us\n", 2376 inSwapBuffersDuration/1000.0); 2377 2378 result.appendFormat(" transaction time: %f us\n", 2379 inTransactionDuration/1000.0); 2380 2381 /* 2382 * VSYNC state 2383 */ 2384 mEventThread->dump(result); 2385 2386 /* 2387 * Dump HWComposer state 2388 */ 2389 colorizer.bold(result); 2390 result.append("h/w composer state:\n"); 2391 colorizer.reset(result); 2392 result.appendFormat(" h/w composer %s and %s\n", 2393 hwc.initCheck()==NO_ERROR ? "present" : "not present", 2394 (mDebugDisableHWC || mDebugRegion || mDaltonize) ? "disabled" : "enabled"); 2395 hwc.dump(result); 2396 2397 /* 2398 * Dump gralloc state 2399 */ 2400 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get()); 2401 alloc.dump(result); 2402} 2403 2404const Vector< sp<Layer> >& 2405SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) { 2406 // Note: mStateLock is held here 2407 wp<IBinder> dpy; 2408 for (size_t i=0 ; i<mDisplays.size() ; i++) { 2409 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) { 2410 dpy = mDisplays.keyAt(i); 2411 break; 2412 } 2413 } 2414 if (dpy == NULL) { 2415 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id); 2416 // Just use the primary display so we have something to return 2417 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY); 2418 } 2419 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ(); 2420} 2421 2422bool SurfaceFlinger::startDdmConnection() 2423{ 2424 void* libddmconnection_dso = 2425 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW); 2426 if (!libddmconnection_dso) { 2427 return false; 2428 } 2429 void (*DdmConnection_start)(const char* name); 2430 DdmConnection_start = 2431 (typeof DdmConnection_start)dlsym(libddmconnection_dso, "DdmConnection_start"); 2432 if (!DdmConnection_start) { 2433 dlclose(libddmconnection_dso); 2434 return false; 2435 } 2436 (*DdmConnection_start)(getServiceName()); 2437 return true; 2438} 2439 2440status_t SurfaceFlinger::onTransact( 2441 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 2442{ 2443 switch (code) { 2444 case CREATE_CONNECTION: 2445 case CREATE_DISPLAY: 2446 case SET_TRANSACTION_STATE: 2447 case BOOT_FINISHED: 2448 case BLANK: 2449 case UNBLANK: 2450 { 2451 // codes that require permission check 2452 IPCThreadState* ipc = IPCThreadState::self(); 2453 const int pid = ipc->getCallingPid(); 2454 const int uid = ipc->getCallingUid(); 2455 if ((uid != AID_GRAPHICS) && 2456 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) { 2457 ALOGE("Permission Denial: " 2458 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 2459 return PERMISSION_DENIED; 2460 } 2461 break; 2462 } 2463 case CAPTURE_SCREEN: 2464 { 2465 // codes that require permission check 2466 IPCThreadState* ipc = IPCThreadState::self(); 2467 const int pid = ipc->getCallingPid(); 2468 const int uid = ipc->getCallingUid(); 2469 if ((uid != AID_GRAPHICS) && 2470 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) { 2471 ALOGE("Permission Denial: " 2472 "can't read framebuffer pid=%d, uid=%d", pid, uid); 2473 return PERMISSION_DENIED; 2474 } 2475 break; 2476 } 2477 } 2478 2479 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags); 2480 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) { 2481 CHECK_INTERFACE(ISurfaceComposer, data, reply); 2482 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) { 2483 IPCThreadState* ipc = IPCThreadState::self(); 2484 const int pid = ipc->getCallingPid(); 2485 const int uid = ipc->getCallingUid(); 2486 ALOGE("Permission Denial: " 2487 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 2488 return PERMISSION_DENIED; 2489 } 2490 int n; 2491 switch (code) { 2492 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE 2493 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE 2494 return NO_ERROR; 2495 case 1002: // SHOW_UPDATES 2496 n = data.readInt32(); 2497 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1); 2498 invalidateHwcGeometry(); 2499 repaintEverything(); 2500 return NO_ERROR; 2501 case 1004:{ // repaint everything 2502 repaintEverything(); 2503 return NO_ERROR; 2504 } 2505 case 1005:{ // force transaction 2506 setTransactionFlags( 2507 eTransactionNeeded| 2508 eDisplayTransactionNeeded| 2509 eTraversalNeeded); 2510 return NO_ERROR; 2511 } 2512 case 1006:{ // send empty update 2513 signalRefresh(); 2514 return NO_ERROR; 2515 } 2516 case 1008: // toggle use of hw composer 2517 n = data.readInt32(); 2518 mDebugDisableHWC = n ? 1 : 0; 2519 invalidateHwcGeometry(); 2520 repaintEverything(); 2521 return NO_ERROR; 2522 case 1009: // toggle use of transform hint 2523 n = data.readInt32(); 2524 mDebugDisableTransformHint = n ? 1 : 0; 2525 invalidateHwcGeometry(); 2526 repaintEverything(); 2527 return NO_ERROR; 2528 case 1010: // interrogate. 2529 reply->writeInt32(0); 2530 reply->writeInt32(0); 2531 reply->writeInt32(mDebugRegion); 2532 reply->writeInt32(0); 2533 reply->writeInt32(mDebugDisableHWC); 2534 return NO_ERROR; 2535 case 1013: { 2536 Mutex::Autolock _l(mStateLock); 2537 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 2538 reply->writeInt32(hw->getPageFlipCount()); 2539 return NO_ERROR; 2540 } 2541 case 1014: { 2542 // daltonize 2543 n = data.readInt32(); 2544 switch (n % 10) { 2545 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break; 2546 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break; 2547 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break; 2548 } 2549 if (n >= 10) { 2550 mDaltonizer.setMode(Daltonizer::correction); 2551 } else { 2552 mDaltonizer.setMode(Daltonizer::simulation); 2553 } 2554 mDaltonize = n > 0; 2555 invalidateHwcGeometry(); 2556 repaintEverything(); 2557 } 2558 return NO_ERROR; 2559 } 2560 } 2561 return err; 2562} 2563 2564void SurfaceFlinger::repaintEverything() { 2565 android_atomic_or(1, &mRepaintEverything); 2566 signalTransaction(); 2567} 2568 2569// --------------------------------------------------------------------------- 2570// Capture screen into an IGraphiBufferProducer 2571// --------------------------------------------------------------------------- 2572 2573/* The code below is here to handle b/8734824 2574 * 2575 * We create a IGraphicBufferProducer wrapper that forwards all calls 2576 * to the calling binder thread, where they are executed. This allows 2577 * the calling thread to be reused (on the other side) and not 2578 * depend on having "enough" binder threads to handle the requests. 2579 * 2580 */ 2581 2582class GraphicProducerWrapper : public BBinder, public MessageHandler { 2583 sp<IGraphicBufferProducer> impl; 2584 sp<Looper> looper; 2585 status_t result; 2586 bool exitPending; 2587 bool exitRequested; 2588 mutable Barrier barrier; 2589 volatile int32_t memoryBarrier; 2590 uint32_t code; 2591 Parcel const* data; 2592 Parcel* reply; 2593 2594 enum { 2595 MSG_API_CALL, 2596 MSG_EXIT 2597 }; 2598 2599 /* 2600 * this is called by our "fake" BpGraphicBufferProducer. We package the 2601 * data and reply Parcel and forward them to the calling thread. 2602 */ 2603 virtual status_t transact(uint32_t code, 2604 const Parcel& data, Parcel* reply, uint32_t flags) { 2605 this->code = code; 2606 this->data = &data; 2607 this->reply = reply; 2608 android_atomic_acquire_store(0, &memoryBarrier); 2609 if (exitPending) { 2610 // if we've exited, we run the message synchronously right here 2611 handleMessage(Message(MSG_API_CALL)); 2612 } else { 2613 barrier.close(); 2614 looper->sendMessage(this, Message(MSG_API_CALL)); 2615 barrier.wait(); 2616 } 2617 return NO_ERROR; 2618 } 2619 2620 /* 2621 * here we run on the binder calling thread. All we've got to do is 2622 * call the real BpGraphicBufferProducer. 2623 */ 2624 virtual void handleMessage(const Message& message) { 2625 android_atomic_release_load(&memoryBarrier); 2626 if (message.what == MSG_API_CALL) { 2627 impl->asBinder()->transact(code, data[0], reply); 2628 barrier.open(); 2629 } else if (message.what == MSG_EXIT) { 2630 exitRequested = true; 2631 } 2632 } 2633 2634public: 2635 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl) : 2636 impl(impl), looper(new Looper(true)), result(NO_ERROR), 2637 exitPending(false), exitRequested(false) { 2638 } 2639 2640 status_t waitForResponse() { 2641 do { 2642 looper->pollOnce(-1); 2643 } while (!exitRequested); 2644 return result; 2645 } 2646 2647 void exit(status_t result) { 2648 this->result = result; 2649 exitPending = true; 2650 looper->sendMessage(this, Message(MSG_EXIT)); 2651 } 2652}; 2653 2654 2655status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, 2656 const sp<IGraphicBufferProducer>& producer, 2657 uint32_t reqWidth, uint32_t reqHeight, 2658 uint32_t minLayerZ, uint32_t maxLayerZ) { 2659 2660 if (CC_UNLIKELY(display == 0)) 2661 return BAD_VALUE; 2662 2663 if (CC_UNLIKELY(producer == 0)) 2664 return BAD_VALUE; 2665 2666 // if we have secure windows on this display, never allow the screen capture 2667 // unless the producer interface is local (i.e.: we can take a screenshot for 2668 // ourselves). 2669 if (!producer->asBinder()->localBinder()) { 2670 Mutex::Autolock _l(mStateLock); 2671 sp<const DisplayDevice> hw(getDisplayDevice(display)); 2672 if (hw->getSecureLayerVisible()) { 2673 ALOGW("FB is protected: PERMISSION_DENIED"); 2674 return PERMISSION_DENIED; 2675 } 2676 } 2677 2678 class MessageCaptureScreen : public MessageBase { 2679 SurfaceFlinger* flinger; 2680 sp<IBinder> display; 2681 sp<IGraphicBufferProducer> producer; 2682 uint32_t reqWidth, reqHeight; 2683 uint32_t minLayerZ,maxLayerZ; 2684 status_t result; 2685 public: 2686 MessageCaptureScreen(SurfaceFlinger* flinger, 2687 const sp<IBinder>& display, 2688 const sp<IGraphicBufferProducer>& producer, 2689 uint32_t reqWidth, uint32_t reqHeight, 2690 uint32_t minLayerZ, uint32_t maxLayerZ) 2691 : flinger(flinger), display(display), producer(producer), 2692 reqWidth(reqWidth), reqHeight(reqHeight), 2693 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ), 2694 result(PERMISSION_DENIED) 2695 { 2696 } 2697 status_t getResult() const { 2698 return result; 2699 } 2700 virtual bool handler() { 2701 Mutex::Autolock _l(flinger->mStateLock); 2702 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display)); 2703 result = flinger->captureScreenImplLocked(hw, 2704 producer, reqWidth, reqHeight, minLayerZ, maxLayerZ); 2705 static_cast<GraphicProducerWrapper*>(producer->asBinder().get())->exit(result); 2706 return true; 2707 } 2708 }; 2709 2710 // make sure to process transactions before screenshots -- a transaction 2711 // might already be pending but scheduled for VSYNC; this guarantees we 2712 // will handle it before the screenshot. When VSYNC finally arrives 2713 // the scheduled transaction will be a no-op. If no transactions are 2714 // scheduled at this time, this will end-up being a no-op as well. 2715 mEventQueue.invalidateTransactionNow(); 2716 2717 // this creates a "fake" BBinder which will serve as a "fake" remote 2718 // binder to receive the marshaled calls and forward them to the 2719 // real remote (a BpGraphicBufferProducer) 2720 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer); 2721 2722 // the asInterface() call below creates our "fake" BpGraphicBufferProducer 2723 // which does the marshaling work forwards to our "fake remote" above. 2724 sp<MessageBase> msg = new MessageCaptureScreen(this, 2725 display, IGraphicBufferProducer::asInterface( wrapper ), 2726 reqWidth, reqHeight, minLayerZ, maxLayerZ); 2727 2728 status_t res = postMessageAsync(msg); 2729 if (res == NO_ERROR) { 2730 res = wrapper->waitForResponse(); 2731 } 2732 return res; 2733} 2734 2735 2736void SurfaceFlinger::renderScreenImplLocked( 2737 const sp<const DisplayDevice>& hw, 2738 uint32_t reqWidth, uint32_t reqHeight, 2739 uint32_t minLayerZ, uint32_t maxLayerZ, 2740 bool yswap) 2741{ 2742 ATRACE_CALL(); 2743 RenderEngine& engine(getRenderEngine()); 2744 2745 // get screen geometry 2746 const uint32_t hw_w = hw->getWidth(); 2747 const uint32_t hw_h = hw->getHeight(); 2748 const bool filtering = reqWidth != hw_w || reqWidth != hw_h; 2749 2750 // make sure to clear all GL error flags 2751 engine.checkErrors(); 2752 2753 // set-up our viewport 2754 engine.setViewportAndProjection(reqWidth, reqHeight, hw_w, hw_h, yswap); 2755 engine.disableTexturing(); 2756 2757 // redraw the screen entirely... 2758 engine.clearWithColor(0, 0, 0, 1); 2759 2760 const LayerVector& layers( mDrawingState.layersSortedByZ ); 2761 const size_t count = layers.size(); 2762 for (size_t i=0 ; i<count ; ++i) { 2763 const sp<Layer>& layer(layers[i]); 2764 const Layer::State& state(layer->getDrawingState()); 2765 if (state.layerStack == hw->getLayerStack()) { 2766 if (state.z >= minLayerZ && state.z <= maxLayerZ) { 2767 if (layer->isVisible()) { 2768 if (filtering) layer->setFiltering(true); 2769 layer->draw(hw); 2770 if (filtering) layer->setFiltering(false); 2771 } 2772 } 2773 } 2774 } 2775 2776 // compositionComplete is needed for older driver 2777 hw->compositionComplete(); 2778 hw->setViewportAndProjection(); 2779} 2780 2781 2782status_t SurfaceFlinger::captureScreenImplLocked( 2783 const sp<const DisplayDevice>& hw, 2784 const sp<IGraphicBufferProducer>& producer, 2785 uint32_t reqWidth, uint32_t reqHeight, 2786 uint32_t minLayerZ, uint32_t maxLayerZ) 2787{ 2788 ATRACE_CALL(); 2789 2790 // get screen geometry 2791 const uint32_t hw_w = hw->getWidth(); 2792 const uint32_t hw_h = hw->getHeight(); 2793 2794 if ((reqWidth > hw_w) || (reqHeight > hw_h)) { 2795 ALOGE("size mismatch (%d, %d) > (%d, %d)", 2796 reqWidth, reqHeight, hw_w, hw_h); 2797 return BAD_VALUE; 2798 } 2799 2800 reqWidth = (!reqWidth) ? hw_w : reqWidth; 2801 reqHeight = (!reqHeight) ? hw_h : reqHeight; 2802 2803 // create a surface (because we're a producer, and we need to 2804 // dequeue/queue a buffer) 2805 sp<Surface> sur = new Surface(producer, false); 2806 ANativeWindow* window = sur.get(); 2807 2808 status_t result = NO_ERROR; 2809 if (native_window_api_connect(window, NATIVE_WINDOW_API_EGL) == NO_ERROR) { 2810 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN | 2811 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE; 2812 2813 int err = 0; 2814 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight); 2815 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW); 2816 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888); 2817 err |= native_window_set_usage(window, usage); 2818 2819 if (err == NO_ERROR) { 2820 ANativeWindowBuffer* buffer; 2821 /* TODO: Once we have the sync framework everywhere this can use 2822 * server-side waits on the fence that dequeueBuffer returns. 2823 */ 2824 result = native_window_dequeue_buffer_and_wait(window, &buffer); 2825 if (result == NO_ERROR) { 2826 // create an EGLImage from the buffer so we can later 2827 // turn it into a texture 2828 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT, 2829 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL); 2830 if (image != EGL_NO_IMAGE_KHR) { 2831 // this binds the given EGLImage as a framebuffer for the 2832 // duration of this scope. 2833 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image); 2834 if (imageBond.getStatus() == NO_ERROR) { 2835 // this will in fact render into our dequeued buffer 2836 // via an FBO, which means we didn't have to create 2837 // an EGLSurface and therefore we're not 2838 // dependent on the context's EGLConfig. 2839 renderScreenImplLocked(hw, reqWidth, reqHeight, 2840 minLayerZ, maxLayerZ, true); 2841 2842 if (DEBUG_SCREENSHOTS) { 2843 uint32_t* pixels = new uint32_t[reqWidth*reqHeight]; 2844 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels); 2845 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, 2846 hw, minLayerZ, maxLayerZ); 2847 delete [] pixels; 2848 } 2849 2850 } else { 2851 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot"); 2852 result = INVALID_OPERATION; 2853 } 2854 // destroy our image 2855 eglDestroyImageKHR(mEGLDisplay, image); 2856 } else { 2857 result = BAD_VALUE; 2858 } 2859 window->queueBuffer(window, buffer, -1); 2860 } 2861 } else { 2862 result = BAD_VALUE; 2863 } 2864 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL); 2865 } 2866 2867 return result; 2868} 2869 2870void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr, 2871 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) { 2872 if (DEBUG_SCREENSHOTS) { 2873 for (size_t y=0 ; y<h ; y++) { 2874 uint32_t const * p = (uint32_t const *)vaddr + y*s; 2875 for (size_t x=0 ; x<w ; x++) { 2876 if (p[x] != 0xFF000000) return; 2877 } 2878 } 2879 ALOGE("*** we just took a black screenshot ***\n" 2880 "requested minz=%d, maxz=%d, layerStack=%d", 2881 minLayerZ, maxLayerZ, hw->getLayerStack()); 2882 const LayerVector& layers( mDrawingState.layersSortedByZ ); 2883 const size_t count = layers.size(); 2884 for (size_t i=0 ; i<count ; ++i) { 2885 const sp<Layer>& layer(layers[i]); 2886 const Layer::State& state(layer->getDrawingState()); 2887 const bool visible = (state.layerStack == hw->getLayerStack()) 2888 && (state.z >= minLayerZ && state.z <= maxLayerZ) 2889 && (layer->isVisible()); 2890 ALOGE("%c index=%d, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x", 2891 visible ? '+' : '-', 2892 i, layer->getName().string(), state.layerStack, state.z, 2893 layer->isVisible(), state.flags, state.alpha); 2894 } 2895 } 2896} 2897 2898// --------------------------------------------------------------------------- 2899 2900SurfaceFlinger::LayerVector::LayerVector() { 2901} 2902 2903SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs) 2904 : SortedVector<sp<Layer> >(rhs) { 2905} 2906 2907int SurfaceFlinger::LayerVector::do_compare(const void* lhs, 2908 const void* rhs) const 2909{ 2910 // sort layers per layer-stack, then by z-order and finally by sequence 2911 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs)); 2912 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs)); 2913 2914 uint32_t ls = l->getCurrentState().layerStack; 2915 uint32_t rs = r->getCurrentState().layerStack; 2916 if (ls != rs) 2917 return ls - rs; 2918 2919 uint32_t lz = l->getCurrentState().z; 2920 uint32_t rz = r->getCurrentState().z; 2921 if (lz != rz) 2922 return lz - rz; 2923 2924 return l->sequence - r->sequence; 2925} 2926 2927// --------------------------------------------------------------------------- 2928 2929SurfaceFlinger::DisplayDeviceState::DisplayDeviceState() 2930 : type(DisplayDevice::DISPLAY_ID_INVALID) { 2931} 2932 2933SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type) 2934 : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0) { 2935 viewport.makeInvalid(); 2936 frame.makeInvalid(); 2937} 2938 2939// --------------------------------------------------------------------------- 2940 2941}; // namespace android 2942 2943 2944#if defined(__gl_h_) 2945#error "don't include gl/gl.h in this file" 2946#endif 2947 2948#if defined(__gl2_h_) 2949#error "don't include gl2/gl2.h in this file" 2950#endif 2951