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