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