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