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