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