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