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