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