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