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