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