SurfaceFlinger.cpp revision 20128300e0cb7f459a60cfbcddb48190ce6545ed
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 24#include <EGL/egl.h> 25#include <GLES/gl.h> 26 27#include <cutils/log.h> 28#include <cutils/properties.h> 29 30#include <binder/IPCThreadState.h> 31#include <binder/IServiceManager.h> 32#include <binder/MemoryHeapBase.h> 33#include <binder/PermissionCache.h> 34 35#include <ui/DisplayInfo.h> 36 37#include <gui/BitTube.h> 38#include <gui/BufferQueue.h> 39#include <gui/IDisplayEventConnection.h> 40#include <gui/SurfaceTextureClient.h> 41 42#include <ui/GraphicBufferAllocator.h> 43#include <ui/PixelFormat.h> 44 45#include <utils/String8.h> 46#include <utils/String16.h> 47#include <utils/StopWatch.h> 48#include <utils/Trace.h> 49 50#include <private/android_filesystem_config.h> 51 52#include "clz.h" 53#include "DdmConnection.h" 54#include "DisplayDevice.h" 55#include "Client.h" 56#include "EventThread.h" 57#include "GLExtensions.h" 58#include "Layer.h" 59#include "LayerDim.h" 60#include "LayerScreenshot.h" 61#include "SurfaceFlinger.h" 62 63#include "DisplayHardware/FramebufferSurface.h" 64#include "DisplayHardware/HWComposer.h" 65 66 67#define EGL_VERSION_HW_ANDROID 0x3143 68 69#define DISPLAY_COUNT 1 70 71namespace android { 72// --------------------------------------------------------------------------- 73 74const String16 sHardwareTest("android.permission.HARDWARE_TEST"); 75const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER"); 76const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER"); 77const String16 sDump("android.permission.DUMP"); 78 79// --------------------------------------------------------------------------- 80 81SurfaceFlinger::SurfaceFlinger() 82 : BnSurfaceComposer(), Thread(false), 83 mTransactionFlags(0), 84 mTransationPending(false), 85 mLayersRemoved(false), 86 mRepaintEverything(0), 87 mBootTime(systemTime()), 88 mVisibleRegionsDirty(false), 89 mHwWorkListDirty(false), 90 mDebugRegion(0), 91 mDebugDDMS(0), 92 mDebugDisableHWC(0), 93 mDebugDisableTransformHint(0), 94 mDebugInSwapBuffers(0), 95 mLastSwapBufferTime(0), 96 mDebugInTransaction(0), 97 mLastTransactionTime(0), 98 mBootFinished(false), 99 mExternalDisplaySurface(EGL_NO_SURFACE) 100{ 101 ALOGI("SurfaceFlinger is starting"); 102 103 // debugging stuff... 104 char value[PROPERTY_VALUE_MAX]; 105 106 property_get("debug.sf.showupdates", value, "0"); 107 mDebugRegion = atoi(value); 108 109 property_get("debug.sf.ddms", value, "0"); 110 mDebugDDMS = atoi(value); 111 if (mDebugDDMS) { 112 DdmConnection::start(getServiceName()); 113 } 114 115 ALOGI_IF(mDebugRegion, "showupdates enabled"); 116 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled"); 117} 118 119void SurfaceFlinger::onFirstRef() 120{ 121 mEventQueue.init(this); 122 123 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY); 124 125 // Wait for the main thread to be done with its initialization 126 mReadyToRunBarrier.wait(); 127} 128 129 130SurfaceFlinger::~SurfaceFlinger() 131{ 132 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); 133 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); 134 eglTerminate(display); 135} 136 137void SurfaceFlinger::binderDied(const wp<IBinder>& who) 138{ 139 // the window manager died on us. prepare its eulogy. 140 141 // reset screen orientation 142 Vector<ComposerState> state; 143 Vector<DisplayState> displays; 144 DisplayState d; 145 d.orientation = DisplayState::eOrientationDefault; 146 displays.add(d); 147 setTransactionState(state, displays, 0); 148 149 // restart the boot-animation 150 startBootAnim(); 151} 152 153sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() 154{ 155 sp<ISurfaceComposerClient> bclient; 156 sp<Client> client(new Client(this)); 157 status_t err = client->initCheck(); 158 if (err == NO_ERROR) { 159 bclient = client; 160 } 161 return bclient; 162} 163 164sp<IBinder> SurfaceFlinger::createDisplay() 165{ 166 class DisplayToken : public BBinder { 167 sp<SurfaceFlinger> flinger; 168 virtual ~DisplayToken() { 169 // no more references, this display must be terminated 170 Mutex::Autolock _l(flinger->mStateLock); 171 flinger->mCurrentState.displays.removeItem(this); 172 flinger->setTransactionFlags(eDisplayTransactionNeeded); 173 } 174 public: 175 DisplayToken(const sp<SurfaceFlinger>& flinger) 176 : flinger(flinger) { 177 } 178 }; 179 180 sp<BBinder> token = new DisplayToken(this); 181 182 Mutex::Autolock _l(mStateLock); 183 DisplayDeviceState info(intptr_t(token.get())); // FIXME: we shouldn't use the address for the id 184 mCurrentState.displays.add(token, info); 185 186 return token; 187} 188 189sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) { 190 if (uint32_t(id) >= DisplayDevice::DISPLAY_ID_COUNT) { 191 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id); 192 return NULL; 193 } 194 return mDefaultDisplays[id]; 195} 196 197sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc() 198{ 199 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc()); 200 return gba; 201} 202 203void SurfaceFlinger::bootFinished() 204{ 205 const nsecs_t now = systemTime(); 206 const nsecs_t duration = now - mBootTime; 207 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) ); 208 mBootFinished = true; 209 210 // wait patiently for the window manager death 211 const String16 name("window"); 212 sp<IBinder> window(defaultServiceManager()->getService(name)); 213 if (window != 0) { 214 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this)); 215 } 216 217 // stop boot animation 218 // formerly we would just kill the process, but we now ask it to exit so it 219 // can choose where to stop the animation. 220 property_set("service.bootanim.exit", "1"); 221} 222 223void SurfaceFlinger::deleteTextureAsync(GLuint texture) { 224 class MessageDestroyGLTexture : public MessageBase { 225 GLuint texture; 226 public: 227 MessageDestroyGLTexture(GLuint texture) 228 : texture(texture) { 229 } 230 virtual bool handler() { 231 glDeleteTextures(1, &texture); 232 return true; 233 } 234 }; 235 postMessageAsync(new MessageDestroyGLTexture(texture)); 236} 237 238status_t SurfaceFlinger::selectConfigForPixelFormat( 239 EGLDisplay dpy, 240 EGLint const* attrs, 241 PixelFormat format, 242 EGLConfig* outConfig) 243{ 244 EGLConfig config = NULL; 245 EGLint numConfigs = -1, n=0; 246 eglGetConfigs(dpy, NULL, 0, &numConfigs); 247 EGLConfig* const configs = new EGLConfig[numConfigs]; 248 eglChooseConfig(dpy, attrs, configs, numConfigs, &n); 249 for (int i=0 ; i<n ; i++) { 250 EGLint nativeVisualId = 0; 251 eglGetConfigAttrib(dpy, configs[i], EGL_NATIVE_VISUAL_ID, &nativeVisualId); 252 if (nativeVisualId>0 && format == nativeVisualId) { 253 *outConfig = configs[i]; 254 delete [] configs; 255 return NO_ERROR; 256 } 257 } 258 delete [] configs; 259 return NAME_NOT_FOUND; 260} 261 262EGLConfig SurfaceFlinger::selectEGLConfig(EGLDisplay display, EGLint nativeVisualId) { 263 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if 264 // it is to be used with WIFI displays 265 EGLConfig config; 266 EGLint dummy; 267 status_t err; 268 EGLint attribs[] = { 269 EGL_SURFACE_TYPE, EGL_WINDOW_BIT, 270 EGL_RECORDABLE_ANDROID, EGL_TRUE, 271 EGL_NONE 272 }; 273 err = selectConfigForPixelFormat(display, attribs, nativeVisualId, &config); 274 if (err) { 275 // maybe we failed because of EGL_RECORDABLE_ANDROID 276 ALOGW("couldn't find an EGLConfig with EGL_RECORDABLE_ANDROID"); 277 attribs[2] = EGL_NONE; 278 err = selectConfigForPixelFormat(display, attribs, nativeVisualId, &config); 279 } 280 ALOGE_IF(err, "couldn't find an EGLConfig matching the screen format"); 281 if (eglGetConfigAttrib(display, config, EGL_CONFIG_CAVEAT, &dummy) == EGL_TRUE) { 282 ALOGW_IF(dummy == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!"); 283 } 284 return config; 285} 286 287EGLContext SurfaceFlinger::createGLContext(EGLDisplay display, EGLConfig config) { 288 // Also create our EGLContext 289 EGLint contextAttributes[] = { 290#ifdef EGL_IMG_context_priority 291#ifdef HAS_CONTEXT_PRIORITY 292#warning "using EGL_IMG_context_priority" 293 EGL_CONTEXT_PRIORITY_LEVEL_IMG, EGL_CONTEXT_PRIORITY_HIGH_IMG, 294#endif 295#endif 296 EGL_NONE, EGL_NONE 297 }; 298 EGLContext ctxt = eglCreateContext(display, config, NULL, contextAttributes); 299 ALOGE_IF(ctxt==EGL_NO_CONTEXT, "EGLContext creation failed"); 300 return ctxt; 301} 302 303void SurfaceFlinger::initializeGL(EGLDisplay display, EGLSurface surface) { 304 EGLBoolean result = eglMakeCurrent(display, surface, surface, mEGLContext); 305 if (!result) { 306 ALOGE("Couldn't create a working GLES context. check logs. exiting..."); 307 exit(0); 308 } 309 310 GLExtensions& extensions(GLExtensions::getInstance()); 311 extensions.initWithGLStrings( 312 glGetString(GL_VENDOR), 313 glGetString(GL_RENDERER), 314 glGetString(GL_VERSION), 315 glGetString(GL_EXTENSIONS), 316 eglQueryString(display, EGL_VENDOR), 317 eglQueryString(display, EGL_VERSION), 318 eglQueryString(display, EGL_EXTENSIONS)); 319 320 EGLint w, h; 321 eglQuerySurface(display, surface, EGL_WIDTH, &w); 322 eglQuerySurface(display, surface, EGL_HEIGHT, &h); 323 324 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize); 325 glGetIntegerv(GL_MAX_VIEWPORT_DIMS, mMaxViewportDims); 326 327 glPixelStorei(GL_UNPACK_ALIGNMENT, 4); 328 glPixelStorei(GL_PACK_ALIGNMENT, 4); 329 glEnableClientState(GL_VERTEX_ARRAY); 330 glShadeModel(GL_FLAT); 331 glDisable(GL_DITHER); 332 glDisable(GL_CULL_FACE); 333 334 struct pack565 { 335 inline uint16_t operator() (int r, int g, int b) const { 336 return (r<<11)|(g<<5)|b; 337 } 338 } pack565; 339 340 const uint16_t protTexData[] = { pack565(0x03, 0x03, 0x03) }; 341 glGenTextures(1, &mProtectedTexName); 342 glBindTexture(GL_TEXTURE_2D, mProtectedTexName); 343 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); 344 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); 345 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); 346 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); 347 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0, 348 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, protTexData); 349 350 glViewport(0, 0, w, h); 351 glMatrixMode(GL_PROJECTION); 352 glLoadIdentity(); 353 // put the origin in the left-bottom corner 354 glOrthof(0, w, 0, h, 0, 1); // l=0, r=w ; b=0, t=h 355 356 // print some debugging info 357 EGLint r,g,b,a; 358 eglGetConfigAttrib(display, mEGLConfig, EGL_RED_SIZE, &r); 359 eglGetConfigAttrib(display, mEGLConfig, EGL_GREEN_SIZE, &g); 360 eglGetConfigAttrib(display, mEGLConfig, EGL_BLUE_SIZE, &b); 361 eglGetConfigAttrib(display, mEGLConfig, EGL_ALPHA_SIZE, &a); 362 ALOGI("EGL informations:"); 363 ALOGI("vendor : %s", extensions.getEglVendor()); 364 ALOGI("version : %s", extensions.getEglVersion()); 365 ALOGI("extensions: %s", extensions.getEglExtension()); 366 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS)?:"Not Supported"); 367 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, mEGLConfig); 368 ALOGI("OpenGL ES informations:"); 369 ALOGI("vendor : %s", extensions.getVendor()); 370 ALOGI("renderer : %s", extensions.getRenderer()); 371 ALOGI("version : %s", extensions.getVersion()); 372 ALOGI("extensions: %s", extensions.getExtension()); 373 ALOGI("GL_MAX_TEXTURE_SIZE = %d", mMaxTextureSize); 374 ALOGI("GL_MAX_VIEWPORT_DIMS = %d x %d", mMaxViewportDims[0], mMaxViewportDims[1]); 375} 376 377status_t SurfaceFlinger::readyToRun() 378{ 379 ALOGI( "SurfaceFlinger's main thread ready to run. " 380 "Initializing graphics H/W..."); 381 382 // initialize EGL 383 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY); 384 eglInitialize(mEGLDisplay, NULL, NULL); 385 386 // Initialize the main display 387 // create native window to main display 388 sp<FramebufferSurface> fbs = FramebufferSurface::create(); 389 if (fbs == NULL) { 390 ALOGE("Display subsystem failed to initialize. check logs. exiting..."); 391 exit(0); 392 } 393 394 sp<SurfaceTextureClient> stc(new SurfaceTextureClient( 395 static_cast<sp<ISurfaceTexture> >(fbs->getBufferQueue()))); 396 397 // initialize the config and context 398 int format; 399 ANativeWindow* const anw = stc.get(); 400 anw->query(anw, NATIVE_WINDOW_FORMAT, &format); 401 mEGLConfig = selectEGLConfig(mEGLDisplay, format); 402 mEGLContext = createGLContext(mEGLDisplay, mEGLConfig); 403 404 // initialize our main display hardware 405 406 for (size_t i=0 ; i<DisplayDevice::DISPLAY_ID_COUNT ; i++) { 407 mDefaultDisplays[i] = new BBinder(); 408 mCurrentState.displays.add(mDefaultDisplays[i], DisplayDeviceState(i)); 409 } 410 sp<DisplayDevice> hw = new DisplayDevice(this, 411 DisplayDevice::DISPLAY_ID_MAIN, anw, fbs, mEGLConfig); 412 mDisplays.add(hw->getDisplayId(), hw); 413 414 // initialize OpenGL ES 415 EGLSurface surface = hw->getEGLSurface(); 416 initializeGL(mEGLDisplay, surface); 417 418 // start the EventThread 419 mEventThread = new EventThread(this); 420 mEventQueue.setEventThread(mEventThread); 421 422 // initialize the H/W composer 423 mHwc = new HWComposer(this, 424 *static_cast<HWComposer::EventHandler *>(this), 425 fbs->getFbHal()); 426 427 // initialize our drawing state 428 mDrawingState = mCurrentState; 429 430 // We're now ready to accept clients... 431 mReadyToRunBarrier.open(); 432 433 // start boot animation 434 startBootAnim(); 435 436 return NO_ERROR; 437} 438 439void SurfaceFlinger::startBootAnim() { 440 // start boot animation 441 property_set("service.bootanim.exit", "0"); 442 property_set("ctl.start", "bootanim"); 443} 444 445uint32_t SurfaceFlinger::getMaxTextureSize() const { 446 return mMaxTextureSize; 447} 448 449uint32_t SurfaceFlinger::getMaxViewportDims() const { 450 return mMaxViewportDims[0] < mMaxViewportDims[1] ? 451 mMaxViewportDims[0] : mMaxViewportDims[1]; 452} 453 454// ---------------------------------------------------------------------------- 455 456bool SurfaceFlinger::authenticateSurfaceTexture( 457 const sp<ISurfaceTexture>& surfaceTexture) const { 458 Mutex::Autolock _l(mStateLock); 459 sp<IBinder> surfaceTextureBinder(surfaceTexture->asBinder()); 460 461 // Check the visible layer list for the ISurface 462 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 463 size_t count = currentLayers.size(); 464 for (size_t i=0 ; i<count ; i++) { 465 const sp<LayerBase>& layer(currentLayers[i]); 466 sp<LayerBaseClient> lbc(layer->getLayerBaseClient()); 467 if (lbc != NULL) { 468 wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder(); 469 if (lbcBinder == surfaceTextureBinder) { 470 return true; 471 } 472 } 473 } 474 475 // Check the layers in the purgatory. This check is here so that if a 476 // SurfaceTexture gets destroyed before all the clients are done using it, 477 // the error will not be reported as "surface XYZ is not authenticated", but 478 // will instead fail later on when the client tries to use the surface, 479 // which should be reported as "surface XYZ returned an -ENODEV". The 480 // purgatorized layers are no less authentic than the visible ones, so this 481 // should not cause any harm. 482 size_t purgatorySize = mLayerPurgatory.size(); 483 for (size_t i=0 ; i<purgatorySize ; i++) { 484 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i)); 485 sp<LayerBaseClient> lbc(layer->getLayerBaseClient()); 486 if (lbc != NULL) { 487 wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder(); 488 if (lbcBinder == surfaceTextureBinder) { 489 return true; 490 } 491 } 492 } 493 494 return false; 495} 496 497status_t SurfaceFlinger::getDisplayInfo(DisplayID dpy, DisplayInfo* info) { 498 // TODO: this is here only for compatibility -- should go away eventually. 499 if (uint32_t(dpy) >= 1) { 500 return BAD_INDEX; 501 } 502 503 const HWComposer& hwc(getHwComposer()); 504 float xdpi = hwc.getDpiX(); 505 float ydpi = hwc.getDpiY(); 506 507 // TODO: Not sure if display density should handled by SF any longer 508 class Density { 509 static int getDensityFromProperty(char const* propName) { 510 char property[PROPERTY_VALUE_MAX]; 511 int density = 0; 512 if (property_get(propName, property, NULL) > 0) { 513 density = atoi(property); 514 } 515 return density; 516 } 517 public: 518 static int getEmuDensity() { 519 return getDensityFromProperty("qemu.sf.lcd_density"); } 520 static int getBuildDensity() { 521 return getDensityFromProperty("ro.sf.lcd_density"); } 522 }; 523 // The density of the device is provided by a build property 524 float density = Density::getBuildDensity() / 160.0f; 525 if (density == 0) { 526 // the build doesn't provide a density -- this is wrong! 527 // use xdpi instead 528 ALOGE("ro.sf.lcd_density must be defined as a build property"); 529 density = xdpi / 160.0f; 530 } 531 if (Density::getEmuDensity()) { 532 // if "qemu.sf.lcd_density" is specified, it overrides everything 533 xdpi = ydpi = density = Density::getEmuDensity(); 534 density /= 160.0f; 535 } 536 537 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 538 info->w = hw->getWidth(); 539 info->h = hw->getHeight(); 540 info->xdpi = xdpi; 541 info->ydpi = ydpi; 542 info->fps = float(1e9 / hwc.getRefreshPeriod()); 543 info->density = density; 544 info->orientation = hw->getOrientation(); 545 // TODO: this needs to go away (currently needed only by webkit) 546 getPixelFormatInfo(hw->getFormat(), &info->pixelFormatInfo); 547 return NO_ERROR; 548} 549 550// ---------------------------------------------------------------------------- 551 552sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() { 553 return mEventThread->createEventConnection(); 554} 555 556void SurfaceFlinger::connectDisplay(const sp<ISurfaceTexture> display) { 557 EGLSurface result = EGL_NO_SURFACE; 558 EGLSurface old_surface = EGL_NO_SURFACE; 559 sp<SurfaceTextureClient> stc; 560 561 if (display != NULL) { 562 stc = new SurfaceTextureClient(display); 563 result = eglCreateWindowSurface(mEGLDisplay, 564 mEGLConfig, (EGLNativeWindowType)stc.get(), NULL); 565 ALOGE_IF(result == EGL_NO_SURFACE, 566 "eglCreateWindowSurface failed (ISurfaceTexture=%p)", 567 display.get()); 568 } 569 570 { // scope for the lock 571 Mutex::Autolock _l(mStateLock); 572 old_surface = mExternalDisplaySurface; 573 mExternalDisplayNativeWindow = stc; 574 mExternalDisplaySurface = result; 575 ALOGD("mExternalDisplaySurface = %p", result); 576 } 577 578 if (old_surface != EGL_NO_SURFACE) { 579 // Note: EGL allows to destroy an object while its current 580 // it will fail to become current next time though. 581 eglDestroySurface(mEGLDisplay, old_surface); 582 } 583} 584 585EGLSurface SurfaceFlinger::getExternalDisplaySurface() const { 586 Mutex::Autolock _l(mStateLock); 587 return mExternalDisplaySurface; 588} 589 590// ---------------------------------------------------------------------------- 591 592void SurfaceFlinger::waitForEvent() { 593 mEventQueue.waitMessage(); 594} 595 596void SurfaceFlinger::signalTransaction() { 597 mEventQueue.invalidate(); 598} 599 600void SurfaceFlinger::signalLayerUpdate() { 601 mEventQueue.invalidate(); 602} 603 604void SurfaceFlinger::signalRefresh() { 605 mEventQueue.refresh(); 606} 607 608status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg, 609 nsecs_t reltime, uint32_t flags) { 610 return mEventQueue.postMessage(msg, reltime); 611} 612 613status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg, 614 nsecs_t reltime, uint32_t flags) { 615 status_t res = mEventQueue.postMessage(msg, reltime); 616 if (res == NO_ERROR) { 617 msg->wait(); 618 } 619 return res; 620} 621 622bool SurfaceFlinger::threadLoop() { 623 waitForEvent(); 624 return true; 625} 626 627void SurfaceFlinger::onVSyncReceived(int dpy, nsecs_t timestamp) { 628 mEventThread->onVSyncReceived(dpy, timestamp); 629} 630 631void SurfaceFlinger::eventControl(int event, int enabled) { 632 getHwComposer().eventControl(event, enabled); 633} 634 635void SurfaceFlinger::onMessageReceived(int32_t what) { 636 ATRACE_CALL(); 637 switch (what) { 638 case MessageQueue::INVALIDATE: 639 handleMessageTransaction(); 640 handleMessageInvalidate(); 641 signalRefresh(); 642 break; 643 case MessageQueue::REFRESH: 644 handleMessageRefresh(); 645 break; 646 } 647} 648 649void SurfaceFlinger::handleMessageTransaction() { 650 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask); 651 if (transactionFlags) { 652 handleTransaction(transactionFlags); 653 } 654} 655 656void SurfaceFlinger::handleMessageInvalidate() { 657 handlePageFlip(); 658} 659 660void SurfaceFlinger::handleMessageRefresh() { 661 handleRefresh(); 662 663 if (CC_UNLIKELY(mVisibleRegionsDirty)) { 664 mVisibleRegionsDirty = false; 665 invalidateHwcGeometry(); 666 667 /* 668 * rebuild the visible layer list per screen 669 */ 670 671 const LayerVector& currentLayers(mDrawingState.layersSortedByZ); 672 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 673 const sp<DisplayDevice>& hw(mDisplays[dpy]); 674 Region opaqueRegion; 675 Region dirtyRegion; 676 computeVisibleRegions(currentLayers, 677 hw->getLayerStack(), dirtyRegion, opaqueRegion); 678 hw->dirtyRegion.orSelf(dirtyRegion); 679 680 Vector< sp<LayerBase> > layersSortedByZ; 681 const size_t count = currentLayers.size(); 682 for (size_t i=0 ; i<count ; i++) { 683 const Layer::State& s(currentLayers[i]->drawingState()); 684 if (s.layerStack == hw->getLayerStack()) { 685 if (!currentLayers[i]->visibleRegion.isEmpty()) { 686 layersSortedByZ.add(currentLayers[i]); 687 } 688 } 689 } 690 hw->setVisibleLayersSortedByZ(layersSortedByZ); 691 hw->undefinedRegion.set(hw->getBounds()); 692 hw->undefinedRegion.subtractSelf(hw->getTransform().transform(opaqueRegion)); 693 } 694 } 695 696 HWComposer& hwc(getHwComposer()); 697 if (hwc.initCheck() == NO_ERROR) { 698 // build the h/w work list 699 const bool workListsDirty = mHwWorkListDirty; 700 mHwWorkListDirty = false; 701 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 702 sp<const DisplayDevice> hw(mDisplays[dpy]); 703 const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ()); 704 const size_t count = currentLayers.size(); 705 706 const int32_t id = hw->getDisplayId(); 707 if (hwc.createWorkList(id, count) >= 0) { 708 HWComposer::LayerListIterator cur = hwc.begin(id); 709 const HWComposer::LayerListIterator end = hwc.end(id); 710 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) { 711 const sp<LayerBase>& layer(currentLayers[i]); 712 713 if (CC_UNLIKELY(workListsDirty)) { 714 layer->setGeometry(hw, *cur); 715 if (mDebugDisableHWC || mDebugRegion) { 716 cur->setSkip(true); 717 } 718 } 719 720 /* 721 * update the per-frame h/w composer data for each layer 722 * and build the transparent region of the FB 723 */ 724 layer->setPerFrameData(hw, *cur); 725 } 726 } 727 } 728 status_t err = hwc.prepare(); 729 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err)); 730 } 731 732 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything); 733 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 734 const sp<DisplayDevice>& hw(mDisplays[dpy]); 735 736 // transform the dirty region into this screen's coordinate space 737 const Transform& planeTransform(hw->getTransform()); 738 Region dirtyRegion; 739 if (repaintEverything) { 740 dirtyRegion.set(hw->bounds()); 741 } else { 742 dirtyRegion = planeTransform.transform(hw->dirtyRegion); 743 dirtyRegion.andSelf(hw->bounds()); 744 } 745 hw->dirtyRegion.clear(); 746 747 if (!dirtyRegion.isEmpty()) { 748 if (hw->canDraw()) { 749 // repaint the framebuffer (if needed) 750 handleRepaint(hw, dirtyRegion); 751 } 752 } 753 // inform the h/w that we're done compositing 754 hw->compositionComplete(); 755 } 756 757 postFramebuffer(); 758 759 760#if 1 761 // render to the external display if we have one 762 EGLSurface externalDisplaySurface = getExternalDisplaySurface(); 763 if (externalDisplaySurface != EGL_NO_SURFACE) { 764 EGLSurface cur = eglGetCurrentSurface(EGL_DRAW); 765 EGLBoolean success = eglMakeCurrent(eglGetCurrentDisplay(), 766 externalDisplaySurface, externalDisplaySurface, 767 eglGetCurrentContext()); 768 769 ALOGE_IF(!success, "eglMakeCurrent -> external failed"); 770 771 if (success) { 772 // redraw the screen entirely... 773 glDisable(GL_TEXTURE_EXTERNAL_OES); 774 glDisable(GL_TEXTURE_2D); 775 glClearColor(0,0,0,1); 776 glClear(GL_COLOR_BUFFER_BIT); 777 glMatrixMode(GL_MODELVIEW); 778 glLoadIdentity(); 779 780 const sp<DisplayDevice>& hw(getDisplayDevice(0)); 781 const Vector< sp<LayerBase> >& layers( hw->getVisibleLayersSortedByZ() ); 782 const size_t count = layers.size(); 783 for (size_t i=0 ; i<count ; ++i) { 784 const sp<LayerBase>& layer(layers[i]); 785 layer->draw(hw); 786 } 787 788 success = eglSwapBuffers(eglGetCurrentDisplay(), externalDisplaySurface); 789 ALOGE_IF(!success, "external display eglSwapBuffers failed"); 790 791 hw->compositionComplete(); 792 } 793 794 success = eglMakeCurrent(eglGetCurrentDisplay(), 795 cur, cur, eglGetCurrentContext()); 796 797 ALOGE_IF(!success, "eglMakeCurrent -> internal failed"); 798 } 799#endif 800 801} 802 803void SurfaceFlinger::postFramebuffer() 804{ 805 ATRACE_CALL(); 806 807 const nsecs_t now = systemTime(); 808 mDebugInSwapBuffers = now; 809 810 HWComposer& hwc(getHwComposer()); 811 812 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 813 const sp<DisplayDevice>& hw(mDisplays[dpy]); 814 if (hwc.initCheck() == NO_ERROR) { 815 const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ()); 816 const size_t count = currentLayers.size(); 817 const int32_t id = hw->getDisplayId(); 818 HWComposer::LayerListIterator cur = hwc.begin(id); 819 const HWComposer::LayerListIterator end = hwc.end(id); 820 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) { 821 const sp<LayerBase>& layer(currentLayers[i]); 822 layer->setAcquireFence(hw, *cur); 823 } 824 } 825 hw->flip(hw->swapRegion); 826 hw->swapRegion.clear(); 827 } 828 829 if (hwc.initCheck() == NO_ERROR) { 830 // FIXME: eventually commit() won't take arguments 831 hwc.commit(mEGLDisplay, getDefaultDisplayDevice()->getEGLSurface()); 832 } 833 834 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 835 sp<const DisplayDevice> hw(mDisplays[dpy]); 836 const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ()); 837 const size_t count = currentLayers.size(); 838 if (hwc.initCheck() == NO_ERROR) { 839 int32_t id = hw->getDisplayId(); 840 HWComposer::LayerListIterator cur = hwc.begin(id); 841 const HWComposer::LayerListIterator end = hwc.end(id); 842 for (size_t i = 0; cur != end && i < count; ++i, ++cur) { 843 currentLayers[i]->onLayerDisplayed(hw, &*cur); 844 } 845 } else { 846 eglSwapBuffers(mEGLDisplay, hw->getEGLSurface()); 847 for (size_t i = 0; i < count; i++) { 848 currentLayers[i]->onLayerDisplayed(hw, NULL); 849 } 850 } 851 852 // FIXME: we need to call eglSwapBuffers() on displays that have GL composition 853 } 854 855 mLastSwapBufferTime = systemTime() - now; 856 mDebugInSwapBuffers = 0; 857} 858 859void SurfaceFlinger::handleTransaction(uint32_t transactionFlags) 860{ 861 ATRACE_CALL(); 862 863 Mutex::Autolock _l(mStateLock); 864 const nsecs_t now = systemTime(); 865 mDebugInTransaction = now; 866 867 // Here we're guaranteed that some transaction flags are set 868 // so we can call handleTransactionLocked() unconditionally. 869 // We call getTransactionFlags(), which will also clear the flags, 870 // with mStateLock held to guarantee that mCurrentState won't change 871 // until the transaction is committed. 872 873 transactionFlags = getTransactionFlags(eTransactionMask); 874 handleTransactionLocked(transactionFlags); 875 876 mLastTransactionTime = systemTime() - now; 877 mDebugInTransaction = 0; 878 invalidateHwcGeometry(); 879 // here the transaction has been committed 880} 881 882void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags) 883{ 884 const LayerVector& currentLayers(mCurrentState.layersSortedByZ); 885 const size_t count = currentLayers.size(); 886 887 /* 888 * Traversal of the children 889 * (perform the transaction for each of them if needed) 890 */ 891 892 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded; 893 if (layersNeedTransaction) { 894 for (size_t i=0 ; i<count ; i++) { 895 const sp<LayerBase>& layer = currentLayers[i]; 896 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded); 897 if (!trFlags) continue; 898 899 const uint32_t flags = layer->doTransaction(0); 900 if (flags & Layer::eVisibleRegion) 901 mVisibleRegionsDirty = true; 902 } 903 } 904 905 /* 906 * Perform our own transaction if needed 907 */ 908 909 if (transactionFlags & eDisplayTransactionNeeded) { 910 // here we take advantage of Vector's copy-on-write semantics to 911 // improve performance by skipping the transaction entirely when 912 // know that the lists are identical 913 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays); 914 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays); 915 if (!curr.isIdenticalTo(draw)) { 916 mVisibleRegionsDirty = true; 917 const size_t cc = curr.size(); 918 const size_t dc = draw.size(); 919 920 // find the displays that were removed 921 // (ie: in drawing state but not in current state) 922 // also handle displays that changed 923 // (ie: displays that are in both lists) 924 for (size_t i=0 ; i<dc ; i++) { 925 const ssize_t j = curr.indexOfKey(draw.keyAt(i)); 926 if (j < 0) { 927 // in drawing state but not in current state 928 if (draw[i].id != DisplayDevice::DISPLAY_ID_MAIN) { 929 mDisplays.removeItem(draw[i].id); 930 } else { 931 ALOGW("trying to remove the main display"); 932 } 933 } else { 934 // this display is in both lists. see if something changed. 935 const DisplayDeviceState& state(curr[j]); 936 if (state.surface != draw[i].surface) { 937 // changing the surface is like destroying and 938 // recreating the DisplayDevice 939 940 sp<SurfaceTextureClient> stc( 941 new SurfaceTextureClient(state.surface)); 942 943 sp<DisplayDevice> disp = new DisplayDevice(this, 944 state.id, stc, 0, mEGLConfig); 945 946 disp->setLayerStack(state.layerStack); 947 disp->setOrientation(state.orientation); 948 // TODO: take viewport and frame into account 949 mDisplays.replaceValueFor(state.id, disp); 950 } 951 if (state.layerStack != draw[i].layerStack) { 952 const sp<DisplayDevice>& disp(getDisplayDevice(state.id)); 953 disp->setLayerStack(state.layerStack); 954 } 955 if (state.orientation != draw[i].orientation || 956 state.viewport != draw[i].viewport || 957 state.frame != draw[i].frame) { 958 const sp<DisplayDevice>& disp(getDisplayDevice(state.id)); 959 disp->setOrientation(state.orientation); 960 // TODO: take viewport and frame into account 961 } 962 } 963 } 964 965 // find displays that were added 966 // (ie: in current state but not in drawing state) 967 for (size_t i=0 ; i<cc ; i++) { 968 if (draw.indexOfKey(curr.keyAt(i)) < 0) { 969 // FIXME: we need to pass the surface here 970 const DisplayDeviceState& state(curr[i]); 971 sp<SurfaceTextureClient> stc( 972 new SurfaceTextureClient(state.surface)); 973 sp<DisplayDevice> disp = new DisplayDevice(this, state.id, 974 stc, 0, mEGLConfig); 975 mDisplays.add(state.id, disp); 976 } 977 } 978 } 979 980 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) { 981 // layers have been added 982 mVisibleRegionsDirty = true; 983 } 984 985 // some layers might have been removed, so 986 // we need to update the regions they're exposing. 987 if (mLayersRemoved) { 988 mLayersRemoved = false; 989 mVisibleRegionsDirty = true; 990 const LayerVector& previousLayers(mDrawingState.layersSortedByZ); 991 const size_t count = previousLayers.size(); 992 for (size_t i=0 ; i<count ; i++) { 993 const sp<LayerBase>& layer(previousLayers[i]); 994 if (currentLayers.indexOf(layer) < 0) { 995 // this layer is not visible anymore 996 // TODO: we could traverse the tree from front to back and 997 // compute the actual visible region 998 // TODO: we could cache the transformed region 999 Layer::State front(layer->drawingState()); 1000 Region visibleReg = front.transform.transform( 1001 Region(Rect(front.active.w, front.active.h))); 1002 invalidateLayerStack(front.layerStack, visibleReg); 1003 } 1004 } 1005 } 1006 } 1007 1008 commitTransaction(); 1009} 1010 1011void SurfaceFlinger::commitTransaction() 1012{ 1013 if (!mLayersPendingRemoval.isEmpty()) { 1014 // Notify removed layers now that they can't be drawn from 1015 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) { 1016 mLayersPendingRemoval[i]->onRemoved(); 1017 } 1018 mLayersPendingRemoval.clear(); 1019 } 1020 1021 mDrawingState = mCurrentState; 1022 mTransationPending = false; 1023 mTransactionCV.broadcast(); 1024} 1025 1026void SurfaceFlinger::computeVisibleRegions( 1027 const LayerVector& currentLayers, uint32_t layerStack, 1028 Region& outDirtyRegion, Region& outOpaqueRegion) 1029{ 1030 ATRACE_CALL(); 1031 1032 Region aboveOpaqueLayers; 1033 Region aboveCoveredLayers; 1034 Region dirty; 1035 1036 outDirtyRegion.clear(); 1037 1038 size_t i = currentLayers.size(); 1039 while (i--) { 1040 const sp<LayerBase>& layer = currentLayers[i]; 1041 1042 // start with the whole surface at its current location 1043 const Layer::State& s(layer->drawingState()); 1044 1045 // only consider the layers on the given later stack 1046 if (s.layerStack != layerStack) 1047 continue; 1048 1049 /* 1050 * opaqueRegion: area of a surface that is fully opaque. 1051 */ 1052 Region opaqueRegion; 1053 1054 /* 1055 * visibleRegion: area of a surface that is visible on screen 1056 * and not fully transparent. This is essentially the layer's 1057 * footprint minus the opaque regions above it. 1058 * Areas covered by a translucent surface are considered visible. 1059 */ 1060 Region visibleRegion; 1061 1062 /* 1063 * coveredRegion: area of a surface that is covered by all 1064 * visible regions above it (which includes the translucent areas). 1065 */ 1066 Region coveredRegion; 1067 1068 1069 // handle hidden surfaces by setting the visible region to empty 1070 if (CC_LIKELY(!(s.flags & layer_state_t::eLayerHidden) && s.alpha)) { 1071 const bool translucent = !layer->isOpaque(); 1072 Rect bounds(layer->computeBounds()); 1073 visibleRegion.set(bounds); 1074 if (!visibleRegion.isEmpty()) { 1075 // Remove the transparent area from the visible region 1076 if (translucent) { 1077 Region transparentRegionScreen; 1078 const Transform tr(s.transform); 1079 if (tr.transformed()) { 1080 if (tr.preserveRects()) { 1081 // transform the transparent region 1082 transparentRegionScreen = tr.transform(s.transparentRegion); 1083 } else { 1084 // transformation too complex, can't do the 1085 // transparent region optimization. 1086 transparentRegionScreen.clear(); 1087 } 1088 } else { 1089 transparentRegionScreen = s.transparentRegion; 1090 } 1091 visibleRegion.subtractSelf(transparentRegionScreen); 1092 } 1093 1094 // compute the opaque region 1095 const int32_t layerOrientation = s.transform.getOrientation(); 1096 if (s.alpha==255 && !translucent && 1097 ((layerOrientation & Transform::ROT_INVALID) == false)) { 1098 // the opaque region is the layer's footprint 1099 opaqueRegion = visibleRegion; 1100 } 1101 } 1102 } 1103 1104 // Clip the covered region to the visible region 1105 coveredRegion = aboveCoveredLayers.intersect(visibleRegion); 1106 1107 // Update aboveCoveredLayers for next (lower) layer 1108 aboveCoveredLayers.orSelf(visibleRegion); 1109 1110 // subtract the opaque region covered by the layers above us 1111 visibleRegion.subtractSelf(aboveOpaqueLayers); 1112 1113 // compute this layer's dirty region 1114 if (layer->contentDirty) { 1115 // we need to invalidate the whole region 1116 dirty = visibleRegion; 1117 // as well, as the old visible region 1118 dirty.orSelf(layer->visibleRegion); 1119 layer->contentDirty = false; 1120 } else { 1121 /* compute the exposed region: 1122 * the exposed region consists of two components: 1123 * 1) what's VISIBLE now and was COVERED before 1124 * 2) what's EXPOSED now less what was EXPOSED before 1125 * 1126 * note that (1) is conservative, we start with the whole 1127 * visible region but only keep what used to be covered by 1128 * something -- which mean it may have been exposed. 1129 * 1130 * (2) handles areas that were not covered by anything but got 1131 * exposed because of a resize. 1132 */ 1133 const Region newExposed = visibleRegion - coveredRegion; 1134 const Region oldVisibleRegion = layer->visibleRegion; 1135 const Region oldCoveredRegion = layer->coveredRegion; 1136 const Region oldExposed = oldVisibleRegion - oldCoveredRegion; 1137 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed); 1138 } 1139 dirty.subtractSelf(aboveOpaqueLayers); 1140 1141 // accumulate to the screen dirty region 1142 outDirtyRegion.orSelf(dirty); 1143 1144 // Update aboveOpaqueLayers for next (lower) layer 1145 aboveOpaqueLayers.orSelf(opaqueRegion); 1146 1147 // Store the visible region is screen space 1148 layer->setVisibleRegion(visibleRegion); 1149 layer->setCoveredRegion(coveredRegion); 1150 } 1151 1152 outOpaqueRegion = aboveOpaqueLayers; 1153} 1154 1155void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack, 1156 const Region& dirty) { 1157 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 1158 const sp<DisplayDevice>& hw(mDisplays[dpy]); 1159 if (hw->getLayerStack() == layerStack) { 1160 hw->dirtyRegion.orSelf(dirty); 1161 } 1162 } 1163} 1164 1165void SurfaceFlinger::handlePageFlip() 1166{ 1167 ATRACE_CALL(); 1168 Region dirtyRegion; 1169 1170 const LayerVector& currentLayers(mDrawingState.layersSortedByZ); 1171 1172 bool visibleRegions = false; 1173 const size_t count = currentLayers.size(); 1174 sp<LayerBase> const* layers = currentLayers.array(); 1175 for (size_t i=0 ; i<count ; i++) { 1176 const sp<LayerBase>& layer(layers[i]); 1177 const Region dirty(layer->latchBuffer(visibleRegions)); 1178 Layer::State s(layer->drawingState()); 1179 invalidateLayerStack(s.layerStack, dirty); 1180 } 1181 1182 mVisibleRegionsDirty |= visibleRegions; 1183} 1184 1185void SurfaceFlinger::invalidateHwcGeometry() 1186{ 1187 mHwWorkListDirty = true; 1188} 1189 1190void SurfaceFlinger::handleRefresh() 1191{ 1192 bool needInvalidate = false; 1193 const LayerVector& currentLayers(mDrawingState.layersSortedByZ); 1194 const size_t count = currentLayers.size(); 1195 for (size_t i=0 ; i<count ; i++) { 1196 const sp<LayerBase>& layer(currentLayers[i]); 1197 if (layer->onPreComposition()) { 1198 needInvalidate = true; 1199 } 1200 } 1201 if (needInvalidate) { 1202 signalLayerUpdate(); 1203 } 1204} 1205 1206void SurfaceFlinger::handleRepaint(const sp<const DisplayDevice>& hw, 1207 const Region& inDirtyRegion) 1208{ 1209 ATRACE_CALL(); 1210 1211 Region dirtyRegion(inDirtyRegion); 1212 1213 // compute the invalid region 1214 hw->swapRegion.orSelf(dirtyRegion); 1215 1216 if (CC_UNLIKELY(mDebugRegion)) { 1217 debugFlashRegions(hw, dirtyRegion); 1218 } 1219 1220 uint32_t flags = hw->getFlags(); 1221 if (flags & DisplayDevice::SWAP_RECTANGLE) { 1222 // we can redraw only what's dirty, but since SWAP_RECTANGLE only 1223 // takes a rectangle, we must make sure to update that whole 1224 // rectangle in that case 1225 dirtyRegion.set(hw->swapRegion.bounds()); 1226 } else { 1227 if (flags & DisplayDevice::PARTIAL_UPDATES) { 1228 // We need to redraw the rectangle that will be updated 1229 // (pushed to the framebuffer). 1230 // This is needed because PARTIAL_UPDATES only takes one 1231 // rectangle instead of a region (see DisplayDevice::flip()) 1232 dirtyRegion.set(hw->swapRegion.bounds()); 1233 } else { 1234 // we need to redraw everything (the whole screen) 1235 dirtyRegion.set(hw->bounds()); 1236 hw->swapRegion = dirtyRegion; 1237 } 1238 } 1239 1240 composeSurfaces(hw, dirtyRegion); 1241 1242 const LayerVector& currentLayers(mDrawingState.layersSortedByZ); 1243 const size_t count = currentLayers.size(); 1244 for (size_t i=0 ; i<count ; i++) { 1245 currentLayers[i]->onPostComposition(); 1246 } 1247 1248 // update the swap region and clear the dirty region 1249 hw->swapRegion.orSelf(dirtyRegion); 1250} 1251 1252void SurfaceFlinger::composeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty) 1253{ 1254 HWComposer& hwc(getHwComposer()); 1255 int32_t id = hw->getDisplayId(); 1256 HWComposer::LayerListIterator cur = hwc.begin(id); 1257 const HWComposer::LayerListIterator end = hwc.end(id); 1258 1259 const size_t fbLayerCount = hwc.getLayerCount(id, HWC_FRAMEBUFFER); 1260 if (cur==end || fbLayerCount) { 1261 1262 DisplayDevice::makeCurrent(hw, mEGLContext); 1263 1264 // set the frame buffer 1265 glMatrixMode(GL_MODELVIEW); 1266 glLoadIdentity(); 1267 1268 // Never touch the framebuffer if we don't have any framebuffer layers 1269 if (hwc.getLayerCount(id, HWC_OVERLAY)) { 1270 // when using overlays, we assume a fully transparent framebuffer 1271 // NOTE: we could reduce how much we need to clear, for instance 1272 // remove where there are opaque FB layers. however, on some 1273 // GPUs doing a "clean slate" glClear might be more efficient. 1274 // We'll revisit later if needed. 1275 glClearColor(0, 0, 0, 0); 1276 glClear(GL_COLOR_BUFFER_BIT); 1277 } else { 1278 const Region region(hw->undefinedRegion.intersect(dirty)); 1279 // screen is already cleared here 1280 if (!region.isEmpty()) { 1281 // can happen with SurfaceView 1282 drawWormhole(region); 1283 } 1284 } 1285 1286 /* 1287 * and then, render the layers targeted at the framebuffer 1288 */ 1289 1290 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ()); 1291 const size_t count = layers.size(); 1292 const Transform& tr = hw->getTransform(); 1293 for (size_t i=0 ; i<count ; ++i) { 1294 const sp<LayerBase>& layer(layers[i]); 1295 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion))); 1296 if (!clip.isEmpty()) { 1297 if (cur != end && cur->getCompositionType() == HWC_OVERLAY) { 1298 if (i && (cur->getHints() & HWC_HINT_CLEAR_FB) 1299 && layer->isOpaque()) { 1300 // never clear the very first layer since we're 1301 // guaranteed the FB is already cleared 1302 layer->clearWithOpenGL(hw, clip); 1303 } 1304 ++cur; 1305 continue; 1306 } 1307 // render the layer 1308 layer->draw(hw, clip); 1309 } 1310 if (cur != end) { 1311 ++cur; 1312 } 1313 } 1314 } 1315} 1316 1317void SurfaceFlinger::debugFlashRegions(const sp<const DisplayDevice>& hw, 1318 const Region& dirtyRegion) 1319{ 1320 const uint32_t flags = hw->getFlags(); 1321 const int32_t height = hw->getHeight(); 1322 if (hw->swapRegion.isEmpty()) { 1323 return; 1324 } 1325 1326 if (!(flags & DisplayDevice::SWAP_RECTANGLE)) { 1327 const Region repaint((flags & DisplayDevice::PARTIAL_UPDATES) ? 1328 dirtyRegion.bounds() : hw->bounds()); 1329 composeSurfaces(hw, repaint); 1330 } 1331 1332 glDisable(GL_TEXTURE_EXTERNAL_OES); 1333 glDisable(GL_TEXTURE_2D); 1334 glDisable(GL_BLEND); 1335 1336 static int toggle = 0; 1337 toggle = 1 - toggle; 1338 if (toggle) { 1339 glColor4f(1, 0, 1, 1); 1340 } else { 1341 glColor4f(1, 1, 0, 1); 1342 } 1343 1344 Region::const_iterator it = dirtyRegion.begin(); 1345 Region::const_iterator const end = dirtyRegion.end(); 1346 while (it != end) { 1347 const Rect& r = *it++; 1348 GLfloat vertices[][2] = { 1349 { r.left, height - r.top }, 1350 { r.left, height - r.bottom }, 1351 { r.right, height - r.bottom }, 1352 { r.right, height - r.top } 1353 }; 1354 glVertexPointer(2, GL_FLOAT, 0, vertices); 1355 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1356 } 1357 1358 hw->flip(hw->swapRegion); 1359 1360 if (mDebugRegion > 1) 1361 usleep(mDebugRegion * 1000); 1362} 1363 1364void SurfaceFlinger::drawWormhole(const Region& region) const 1365{ 1366 glDisable(GL_TEXTURE_EXTERNAL_OES); 1367 glDisable(GL_TEXTURE_2D); 1368 glDisable(GL_BLEND); 1369 glColor4f(0,0,0,0); 1370 1371 GLfloat vertices[4][2]; 1372 glVertexPointer(2, GL_FLOAT, 0, vertices); 1373 Region::const_iterator it = region.begin(); 1374 Region::const_iterator const end = region.end(); 1375 while (it != end) { 1376 const Rect& r = *it++; 1377 vertices[0][0] = r.left; 1378 vertices[0][1] = r.top; 1379 vertices[1][0] = r.right; 1380 vertices[1][1] = r.top; 1381 vertices[2][0] = r.right; 1382 vertices[2][1] = r.bottom; 1383 vertices[3][0] = r.left; 1384 vertices[3][1] = r.bottom; 1385 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1386 } 1387} 1388 1389ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client, 1390 const sp<LayerBaseClient>& lbc) 1391{ 1392 // attach this layer to the client 1393 size_t name = client->attachLayer(lbc); 1394 1395 // add this layer to the current state list 1396 Mutex::Autolock _l(mStateLock); 1397 mCurrentState.layersSortedByZ.add(lbc); 1398 1399 return ssize_t(name); 1400} 1401 1402status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer) 1403{ 1404 Mutex::Autolock _l(mStateLock); 1405 status_t err = purgatorizeLayer_l(layer); 1406 if (err == NO_ERROR) 1407 setTransactionFlags(eTransactionNeeded); 1408 return err; 1409} 1410 1411status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase) 1412{ 1413 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase); 1414 if (index >= 0) { 1415 mLayersRemoved = true; 1416 return NO_ERROR; 1417 } 1418 return status_t(index); 1419} 1420 1421status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase) 1422{ 1423 // First add the layer to the purgatory list, which makes sure it won't 1424 // go away, then remove it from the main list (through a transaction). 1425 ssize_t err = removeLayer_l(layerBase); 1426 if (err >= 0) { 1427 mLayerPurgatory.add(layerBase); 1428 } 1429 1430 mLayersPendingRemoval.push(layerBase); 1431 1432 // it's possible that we don't find a layer, because it might 1433 // have been destroyed already -- this is not technically an error 1434 // from the user because there is a race between Client::destroySurface(), 1435 // ~Client() and ~ISurface(). 1436 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err; 1437} 1438 1439uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags) 1440{ 1441 return android_atomic_release_load(&mTransactionFlags); 1442} 1443 1444uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) 1445{ 1446 return android_atomic_and(~flags, &mTransactionFlags) & flags; 1447} 1448 1449uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) 1450{ 1451 uint32_t old = android_atomic_or(flags, &mTransactionFlags); 1452 if ((old & flags)==0) { // wake the server up 1453 signalTransaction(); 1454 } 1455 return old; 1456} 1457 1458void SurfaceFlinger::setTransactionState( 1459 const Vector<ComposerState>& state, 1460 const Vector<DisplayState>& displays, 1461 uint32_t flags) 1462{ 1463 Mutex::Autolock _l(mStateLock); 1464 uint32_t transactionFlags = 0; 1465 1466 size_t count = displays.size(); 1467 for (size_t i=0 ; i<count ; i++) { 1468 const DisplayState& s(displays[i]); 1469 transactionFlags |= setDisplayStateLocked(s); 1470 } 1471 1472 count = state.size(); 1473 for (size_t i=0 ; i<count ; i++) { 1474 const ComposerState& s(state[i]); 1475 sp<Client> client( static_cast<Client *>(s.client.get()) ); 1476 transactionFlags |= setClientStateLocked(client, s.state); 1477 } 1478 1479 if (transactionFlags) { 1480 // this triggers the transaction 1481 setTransactionFlags(transactionFlags); 1482 1483 // if this is a synchronous transaction, wait for it to take effect 1484 // before returning. 1485 if (flags & eSynchronous) { 1486 mTransationPending = true; 1487 } 1488 while (mTransationPending) { 1489 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5)); 1490 if (CC_UNLIKELY(err != NO_ERROR)) { 1491 // just in case something goes wrong in SF, return to the 1492 // called after a few seconds. 1493 ALOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!"); 1494 mTransationPending = false; 1495 break; 1496 } 1497 } 1498 } 1499} 1500 1501uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) 1502{ 1503 uint32_t flags = 0; 1504 DisplayDeviceState& disp(mCurrentState.displays.editValueFor(s.token)); 1505 if (disp.id >= 0) { 1506 const uint32_t what = s.what; 1507 if (what & DisplayState::eSurfaceChanged) { 1508 if (disp.surface->asBinder() != s.surface->asBinder()) { 1509 disp.surface = s.surface; 1510 flags |= eDisplayTransactionNeeded; 1511 } 1512 } 1513 if (what & DisplayState::eLayerStackChanged) { 1514 if (disp.layerStack != s.layerStack) { 1515 disp.layerStack = s.layerStack; 1516 flags |= eDisplayTransactionNeeded; 1517 } 1518 } 1519 if (what & DisplayState::eTransformChanged) { 1520 if (disp.orientation != s.orientation) { 1521 disp.orientation = s.orientation; 1522 flags |= eDisplayTransactionNeeded; 1523 } 1524 if (disp.frame != s.frame) { 1525 disp.frame = s.frame; 1526 flags |= eDisplayTransactionNeeded; 1527 } 1528 if (disp.viewport != s.viewport) { 1529 disp.viewport = s.viewport; 1530 flags |= eDisplayTransactionNeeded; 1531 } 1532 } 1533 } 1534 return flags; 1535} 1536 1537uint32_t SurfaceFlinger::setClientStateLocked( 1538 const sp<Client>& client, 1539 const layer_state_t& s) 1540{ 1541 uint32_t flags = 0; 1542 sp<LayerBaseClient> layer(client->getLayerUser(s.surface)); 1543 if (layer != 0) { 1544 const uint32_t what = s.what; 1545 if (what & layer_state_t::ePositionChanged) { 1546 if (layer->setPosition(s.x, s.y)) 1547 flags |= eTraversalNeeded; 1548 } 1549 if (what & layer_state_t::eLayerChanged) { 1550 // NOTE: index needs to be calculated before we update the state 1551 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); 1552 if (layer->setLayer(s.z)) { 1553 mCurrentState.layersSortedByZ.removeAt(idx); 1554 mCurrentState.layersSortedByZ.add(layer); 1555 // we need traversal (state changed) 1556 // AND transaction (list changed) 1557 flags |= eTransactionNeeded|eTraversalNeeded; 1558 } 1559 } 1560 if (what & layer_state_t::eSizeChanged) { 1561 if (layer->setSize(s.w, s.h)) { 1562 flags |= eTraversalNeeded; 1563 } 1564 } 1565 if (what & layer_state_t::eAlphaChanged) { 1566 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f))) 1567 flags |= eTraversalNeeded; 1568 } 1569 if (what & layer_state_t::eMatrixChanged) { 1570 if (layer->setMatrix(s.matrix)) 1571 flags |= eTraversalNeeded; 1572 } 1573 if (what & layer_state_t::eTransparentRegionChanged) { 1574 if (layer->setTransparentRegionHint(s.transparentRegion)) 1575 flags |= eTraversalNeeded; 1576 } 1577 if (what & layer_state_t::eVisibilityChanged) { 1578 if (layer->setFlags(s.flags, s.mask)) 1579 flags |= eTraversalNeeded; 1580 } 1581 if (what & layer_state_t::eCropChanged) { 1582 if (layer->setCrop(s.crop)) 1583 flags |= eTraversalNeeded; 1584 } 1585 if (what & layer_state_t::eLayerStackChanged) { 1586 // NOTE: index needs to be calculated before we update the state 1587 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); 1588 if (layer->setLayerStack(s.layerStack)) { 1589 mCurrentState.layersSortedByZ.removeAt(idx); 1590 mCurrentState.layersSortedByZ.add(layer); 1591 // we need traversal (state changed) 1592 // AND transaction (list changed) 1593 flags |= eTransactionNeeded|eTraversalNeeded; 1594 } 1595 } 1596 } 1597 return flags; 1598} 1599 1600sp<ISurface> SurfaceFlinger::createLayer( 1601 ISurfaceComposerClient::surface_data_t* params, 1602 const String8& name, 1603 const sp<Client>& client, 1604 DisplayID d, uint32_t w, uint32_t h, PixelFormat format, 1605 uint32_t flags) 1606{ 1607 sp<LayerBaseClient> layer; 1608 sp<ISurface> surfaceHandle; 1609 1610 if (int32_t(w|h) < 0) { 1611 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)", 1612 int(w), int(h)); 1613 return surfaceHandle; 1614 } 1615 1616 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string()); 1617 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) { 1618 case ISurfaceComposerClient::eFXSurfaceNormal: 1619 layer = createNormalLayer(client, d, w, h, flags, format); 1620 break; 1621 case ISurfaceComposerClient::eFXSurfaceBlur: 1622 case ISurfaceComposerClient::eFXSurfaceDim: 1623 layer = createDimLayer(client, d, w, h, flags); 1624 break; 1625 case ISurfaceComposerClient::eFXSurfaceScreenshot: 1626 layer = createScreenshotLayer(client, d, w, h, flags); 1627 break; 1628 } 1629 1630 if (layer != 0) { 1631 layer->initStates(w, h, flags); 1632 layer->setName(name); 1633 ssize_t token = addClientLayer(client, layer); 1634 surfaceHandle = layer->getSurface(); 1635 if (surfaceHandle != 0) { 1636 params->token = token; 1637 params->identity = layer->getIdentity(); 1638 } 1639 setTransactionFlags(eTransactionNeeded); 1640 } 1641 1642 return surfaceHandle; 1643} 1644 1645sp<Layer> SurfaceFlinger::createNormalLayer( 1646 const sp<Client>& client, DisplayID display, 1647 uint32_t w, uint32_t h, uint32_t flags, 1648 PixelFormat& format) 1649{ 1650 // initialize the surfaces 1651 switch (format) { 1652 case PIXEL_FORMAT_TRANSPARENT: 1653 case PIXEL_FORMAT_TRANSLUCENT: 1654 format = PIXEL_FORMAT_RGBA_8888; 1655 break; 1656 case PIXEL_FORMAT_OPAQUE: 1657#ifdef NO_RGBX_8888 1658 format = PIXEL_FORMAT_RGB_565; 1659#else 1660 format = PIXEL_FORMAT_RGBX_8888; 1661#endif 1662 break; 1663 } 1664 1665#ifdef NO_RGBX_8888 1666 if (format == PIXEL_FORMAT_RGBX_8888) 1667 format = PIXEL_FORMAT_RGBA_8888; 1668#endif 1669 1670 sp<Layer> layer = new Layer(this, display, client); 1671 status_t err = layer->setBuffers(w, h, format, flags); 1672 if (CC_LIKELY(err != NO_ERROR)) { 1673 ALOGE("createNormalLayer() failed (%s)", strerror(-err)); 1674 layer.clear(); 1675 } 1676 return layer; 1677} 1678 1679sp<LayerDim> SurfaceFlinger::createDimLayer( 1680 const sp<Client>& client, DisplayID display, 1681 uint32_t w, uint32_t h, uint32_t flags) 1682{ 1683 sp<LayerDim> layer = new LayerDim(this, display, client); 1684 return layer; 1685} 1686 1687sp<LayerScreenshot> SurfaceFlinger::createScreenshotLayer( 1688 const sp<Client>& client, DisplayID display, 1689 uint32_t w, uint32_t h, uint32_t flags) 1690{ 1691 sp<LayerScreenshot> layer = new LayerScreenshot(this, display, client); 1692 return layer; 1693} 1694 1695status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, SurfaceID sid) 1696{ 1697 /* 1698 * called by the window manager, when a surface should be marked for 1699 * destruction. 1700 * 1701 * The surface is removed from the current and drawing lists, but placed 1702 * in the purgatory queue, so it's not destroyed right-away (we need 1703 * to wait for all client's references to go away first). 1704 */ 1705 1706 status_t err = NAME_NOT_FOUND; 1707 Mutex::Autolock _l(mStateLock); 1708 sp<LayerBaseClient> layer = client->getLayerUser(sid); 1709 1710 if (layer != 0) { 1711 err = purgatorizeLayer_l(layer); 1712 if (err == NO_ERROR) { 1713 setTransactionFlags(eTransactionNeeded); 1714 } 1715 } 1716 return err; 1717} 1718 1719status_t SurfaceFlinger::onLayerDestroyed(const wp<LayerBaseClient>& layer) 1720{ 1721 // called by ~ISurface() when all references are gone 1722 status_t err = NO_ERROR; 1723 sp<LayerBaseClient> l(layer.promote()); 1724 if (l != NULL) { 1725 Mutex::Autolock _l(mStateLock); 1726 err = removeLayer_l(l); 1727 if (err == NAME_NOT_FOUND) { 1728 // The surface wasn't in the current list, which means it was 1729 // removed already, which means it is in the purgatory, 1730 // and need to be removed from there. 1731 ssize_t idx = mLayerPurgatory.remove(l); 1732 ALOGE_IF(idx < 0, 1733 "layer=%p is not in the purgatory list", l.get()); 1734 } 1735 ALOGE_IF(err<0 && err != NAME_NOT_FOUND, 1736 "error removing layer=%p (%s)", l.get(), strerror(-err)); 1737 } 1738 return err; 1739} 1740 1741// --------------------------------------------------------------------------- 1742 1743void SurfaceFlinger::onScreenAcquired() { 1744 ALOGD("Screen about to return, flinger = %p", this); 1745 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); // XXX: this should be per DisplayDevice 1746 getHwComposer().acquire(); 1747 hw->acquireScreen(); 1748 mEventThread->onScreenAcquired(); 1749 mVisibleRegionsDirty = true; 1750 repaintEverything(); 1751} 1752 1753void SurfaceFlinger::onScreenReleased() { 1754 ALOGD("About to give-up screen, flinger = %p", this); 1755 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); // XXX: this should be per DisplayDevice 1756 if (hw->isScreenAcquired()) { 1757 mEventThread->onScreenReleased(); 1758 hw->releaseScreen(); 1759 getHwComposer().release(); 1760 // from this point on, SF will stop drawing 1761 } 1762} 1763 1764void SurfaceFlinger::unblank() { 1765 class MessageScreenAcquired : public MessageBase { 1766 SurfaceFlinger* flinger; 1767 public: 1768 MessageScreenAcquired(SurfaceFlinger* flinger) : flinger(flinger) { } 1769 virtual bool handler() { 1770 flinger->onScreenAcquired(); 1771 return true; 1772 } 1773 }; 1774 sp<MessageBase> msg = new MessageScreenAcquired(this); 1775 postMessageSync(msg); 1776} 1777 1778void SurfaceFlinger::blank() { 1779 class MessageScreenReleased : public MessageBase { 1780 SurfaceFlinger* flinger; 1781 public: 1782 MessageScreenReleased(SurfaceFlinger* flinger) : flinger(flinger) { } 1783 virtual bool handler() { 1784 flinger->onScreenReleased(); 1785 return true; 1786 } 1787 }; 1788 sp<MessageBase> msg = new MessageScreenReleased(this); 1789 postMessageSync(msg); 1790} 1791 1792// --------------------------------------------------------------------------- 1793 1794status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args) 1795{ 1796 const size_t SIZE = 4096; 1797 char buffer[SIZE]; 1798 String8 result; 1799 1800 if (!PermissionCache::checkCallingPermission(sDump)) { 1801 snprintf(buffer, SIZE, "Permission Denial: " 1802 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", 1803 IPCThreadState::self()->getCallingPid(), 1804 IPCThreadState::self()->getCallingUid()); 1805 result.append(buffer); 1806 } else { 1807 // Try to get the main lock, but don't insist if we can't 1808 // (this would indicate SF is stuck, but we want to be able to 1809 // print something in dumpsys). 1810 int retry = 3; 1811 while (mStateLock.tryLock()<0 && --retry>=0) { 1812 usleep(1000000); 1813 } 1814 const bool locked(retry >= 0); 1815 if (!locked) { 1816 snprintf(buffer, SIZE, 1817 "SurfaceFlinger appears to be unresponsive, " 1818 "dumping anyways (no locks held)\n"); 1819 result.append(buffer); 1820 } 1821 1822 bool dumpAll = true; 1823 size_t index = 0; 1824 size_t numArgs = args.size(); 1825 if (numArgs) { 1826 if ((index < numArgs) && 1827 (args[index] == String16("--list"))) { 1828 index++; 1829 listLayersLocked(args, index, result, buffer, SIZE); 1830 dumpAll = false; 1831 } 1832 1833 if ((index < numArgs) && 1834 (args[index] == String16("--latency"))) { 1835 index++; 1836 dumpStatsLocked(args, index, result, buffer, SIZE); 1837 dumpAll = false; 1838 } 1839 1840 if ((index < numArgs) && 1841 (args[index] == String16("--latency-clear"))) { 1842 index++; 1843 clearStatsLocked(args, index, result, buffer, SIZE); 1844 dumpAll = false; 1845 } 1846 } 1847 1848 if (dumpAll) { 1849 dumpAllLocked(result, buffer, SIZE); 1850 } 1851 1852 if (locked) { 1853 mStateLock.unlock(); 1854 } 1855 } 1856 write(fd, result.string(), result.size()); 1857 return NO_ERROR; 1858} 1859 1860void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index, 1861 String8& result, char* buffer, size_t SIZE) const 1862{ 1863 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 1864 const size_t count = currentLayers.size(); 1865 for (size_t i=0 ; i<count ; i++) { 1866 const sp<LayerBase>& layer(currentLayers[i]); 1867 snprintf(buffer, SIZE, "%s\n", layer->getName().string()); 1868 result.append(buffer); 1869 } 1870} 1871 1872void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index, 1873 String8& result, char* buffer, size_t SIZE) const 1874{ 1875 String8 name; 1876 if (index < args.size()) { 1877 name = String8(args[index]); 1878 index++; 1879 } 1880 1881 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 1882 const size_t count = currentLayers.size(); 1883 for (size_t i=0 ; i<count ; i++) { 1884 const sp<LayerBase>& layer(currentLayers[i]); 1885 if (name.isEmpty()) { 1886 snprintf(buffer, SIZE, "%s\n", layer->getName().string()); 1887 result.append(buffer); 1888 } 1889 if (name.isEmpty() || (name == layer->getName())) { 1890 layer->dumpStats(result, buffer, SIZE); 1891 } 1892 } 1893} 1894 1895void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index, 1896 String8& result, char* buffer, size_t SIZE) const 1897{ 1898 String8 name; 1899 if (index < args.size()) { 1900 name = String8(args[index]); 1901 index++; 1902 } 1903 1904 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 1905 const size_t count = currentLayers.size(); 1906 for (size_t i=0 ; i<count ; i++) { 1907 const sp<LayerBase>& layer(currentLayers[i]); 1908 if (name.isEmpty() || (name == layer->getName())) { 1909 layer->clearStats(); 1910 } 1911 } 1912} 1913 1914void SurfaceFlinger::dumpAllLocked( 1915 String8& result, char* buffer, size_t SIZE) const 1916{ 1917 // figure out if we're stuck somewhere 1918 const nsecs_t now = systemTime(); 1919 const nsecs_t inSwapBuffers(mDebugInSwapBuffers); 1920 const nsecs_t inTransaction(mDebugInTransaction); 1921 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0; 1922 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0; 1923 1924 /* 1925 * Dump the visible layer list 1926 */ 1927 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 1928 const size_t count = currentLayers.size(); 1929 snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count); 1930 result.append(buffer); 1931 for (size_t i=0 ; i<count ; i++) { 1932 const sp<LayerBase>& layer(currentLayers[i]); 1933 layer->dump(result, buffer, SIZE); 1934 } 1935 1936 /* 1937 * Dump the layers in the purgatory 1938 */ 1939 1940 const size_t purgatorySize = mLayerPurgatory.size(); 1941 snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize); 1942 result.append(buffer); 1943 for (size_t i=0 ; i<purgatorySize ; i++) { 1944 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i)); 1945 layer->shortDump(result, buffer, SIZE); 1946 } 1947 1948 /* 1949 * Dump SurfaceFlinger global state 1950 */ 1951 1952 snprintf(buffer, SIZE, "SurfaceFlinger global state:\n"); 1953 result.append(buffer); 1954 1955 HWComposer& hwc(getHwComposer()); 1956 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 1957 const GLExtensions& extensions(GLExtensions::getInstance()); 1958 snprintf(buffer, SIZE, "GLES: %s, %s, %s\n", 1959 extensions.getVendor(), 1960 extensions.getRenderer(), 1961 extensions.getVersion()); 1962 result.append(buffer); 1963 1964 snprintf(buffer, SIZE, "EGL : %s\n", 1965 eglQueryString(mEGLDisplay, EGL_VERSION_HW_ANDROID)); 1966 result.append(buffer); 1967 1968 snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension()); 1969 result.append(buffer); 1970 1971 hw->undefinedRegion.dump(result, "undefinedRegion"); 1972 snprintf(buffer, SIZE, 1973 " orientation=%d, canDraw=%d\n", 1974 hw->getOrientation(), hw->canDraw()); 1975 result.append(buffer); 1976 snprintf(buffer, SIZE, 1977 " last eglSwapBuffers() time: %f us\n" 1978 " last transaction time : %f us\n" 1979 " transaction-flags : %08x\n" 1980 " refresh-rate : %f fps\n" 1981 " x-dpi : %f\n" 1982 " y-dpi : %f\n", 1983 mLastSwapBufferTime/1000.0, 1984 mLastTransactionTime/1000.0, 1985 mTransactionFlags, 1986 1e9 / hwc.getRefreshPeriod(), 1987 hwc.getDpiX(), 1988 hwc.getDpiY()); 1989 result.append(buffer); 1990 1991 snprintf(buffer, SIZE, " eglSwapBuffers time: %f us\n", 1992 inSwapBuffersDuration/1000.0); 1993 result.append(buffer); 1994 1995 snprintf(buffer, SIZE, " transaction time: %f us\n", 1996 inTransactionDuration/1000.0); 1997 result.append(buffer); 1998 1999 /* 2000 * VSYNC state 2001 */ 2002 mEventThread->dump(result, buffer, SIZE); 2003 2004 /* 2005 * Dump HWComposer state 2006 */ 2007 snprintf(buffer, SIZE, "h/w composer state:\n"); 2008 result.append(buffer); 2009 snprintf(buffer, SIZE, " h/w composer %s and %s\n", 2010 hwc.initCheck()==NO_ERROR ? "present" : "not present", 2011 (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled"); 2012 result.append(buffer); 2013 hwc.dump(result, buffer, SIZE, hw->getVisibleLayersSortedByZ()); 2014 2015 /* 2016 * Dump gralloc state 2017 */ 2018 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get()); 2019 alloc.dump(result); 2020 hw->dump(result); 2021} 2022 2023status_t SurfaceFlinger::onTransact( 2024 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 2025{ 2026 switch (code) { 2027 case CREATE_CONNECTION: 2028 case SET_TRANSACTION_STATE: 2029 case BOOT_FINISHED: 2030 case BLANK: 2031 case UNBLANK: 2032 { 2033 // codes that require permission check 2034 IPCThreadState* ipc = IPCThreadState::self(); 2035 const int pid = ipc->getCallingPid(); 2036 const int uid = ipc->getCallingUid(); 2037 if ((uid != AID_GRAPHICS) && 2038 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) { 2039 ALOGE("Permission Denial: " 2040 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 2041 return PERMISSION_DENIED; 2042 } 2043 break; 2044 } 2045 case CAPTURE_SCREEN: 2046 { 2047 // codes that require permission check 2048 IPCThreadState* ipc = IPCThreadState::self(); 2049 const int pid = ipc->getCallingPid(); 2050 const int uid = ipc->getCallingUid(); 2051 if ((uid != AID_GRAPHICS) && 2052 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) { 2053 ALOGE("Permission Denial: " 2054 "can't read framebuffer pid=%d, uid=%d", pid, uid); 2055 return PERMISSION_DENIED; 2056 } 2057 break; 2058 } 2059 } 2060 2061 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags); 2062 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) { 2063 CHECK_INTERFACE(ISurfaceComposer, data, reply); 2064 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) { 2065 IPCThreadState* ipc = IPCThreadState::self(); 2066 const int pid = ipc->getCallingPid(); 2067 const int uid = ipc->getCallingUid(); 2068 ALOGE("Permission Denial: " 2069 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 2070 return PERMISSION_DENIED; 2071 } 2072 int n; 2073 switch (code) { 2074 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE 2075 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE 2076 return NO_ERROR; 2077 case 1002: // SHOW_UPDATES 2078 n = data.readInt32(); 2079 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1); 2080 invalidateHwcGeometry(); 2081 repaintEverything(); 2082 return NO_ERROR; 2083 case 1004:{ // repaint everything 2084 repaintEverything(); 2085 return NO_ERROR; 2086 } 2087 case 1005:{ // force transaction 2088 setTransactionFlags( 2089 eTransactionNeeded| 2090 eDisplayTransactionNeeded| 2091 eTraversalNeeded); 2092 return NO_ERROR; 2093 } 2094 case 1006:{ // send empty update 2095 signalRefresh(); 2096 return NO_ERROR; 2097 } 2098 case 1008: // toggle use of hw composer 2099 n = data.readInt32(); 2100 mDebugDisableHWC = n ? 1 : 0; 2101 invalidateHwcGeometry(); 2102 repaintEverything(); 2103 return NO_ERROR; 2104 case 1009: // toggle use of transform hint 2105 n = data.readInt32(); 2106 mDebugDisableTransformHint = n ? 1 : 0; 2107 invalidateHwcGeometry(); 2108 repaintEverything(); 2109 return NO_ERROR; 2110 case 1010: // interrogate. 2111 reply->writeInt32(0); 2112 reply->writeInt32(0); 2113 reply->writeInt32(mDebugRegion); 2114 reply->writeInt32(0); 2115 reply->writeInt32(mDebugDisableHWC); 2116 return NO_ERROR; 2117 case 1013: { 2118 Mutex::Autolock _l(mStateLock); 2119 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 2120 reply->writeInt32(hw->getPageFlipCount()); 2121 } 2122 return NO_ERROR; 2123 } 2124 } 2125 return err; 2126} 2127 2128void SurfaceFlinger::repaintEverything() { 2129 android_atomic_or(1, &mRepaintEverything); 2130 signalTransaction(); 2131} 2132 2133// --------------------------------------------------------------------------- 2134 2135status_t SurfaceFlinger::renderScreenToTexture(DisplayID dpy, 2136 GLuint* textureName, GLfloat* uOut, GLfloat* vOut) 2137{ 2138 Mutex::Autolock _l(mStateLock); 2139 return renderScreenToTextureLocked(dpy, textureName, uOut, vOut); 2140} 2141 2142status_t SurfaceFlinger::renderScreenToTextureLocked(DisplayID dpy, 2143 GLuint* textureName, GLfloat* uOut, GLfloat* vOut) 2144{ 2145 ATRACE_CALL(); 2146 2147 if (!GLExtensions::getInstance().haveFramebufferObject()) 2148 return INVALID_OPERATION; 2149 2150 // get screen geometry 2151 sp<const DisplayDevice> hw(getDisplayDevice(dpy)); 2152 const uint32_t hw_w = hw->getWidth(); 2153 const uint32_t hw_h = hw->getHeight(); 2154 GLfloat u = 1; 2155 GLfloat v = 1; 2156 2157 // make sure to clear all GL error flags 2158 while ( glGetError() != GL_NO_ERROR ) ; 2159 2160 // create a FBO 2161 GLuint name, tname; 2162 glGenTextures(1, &tname); 2163 glBindTexture(GL_TEXTURE_2D, tname); 2164 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 2165 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 2166 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2167 hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); 2168 if (glGetError() != GL_NO_ERROR) { 2169 while ( glGetError() != GL_NO_ERROR ) ; 2170 GLint tw = (2 << (31 - clz(hw_w))); 2171 GLint th = (2 << (31 - clz(hw_h))); 2172 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2173 tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); 2174 u = GLfloat(hw_w) / tw; 2175 v = GLfloat(hw_h) / th; 2176 } 2177 glGenFramebuffersOES(1, &name); 2178 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name); 2179 glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES, 2180 GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0); 2181 2182 // redraw the screen entirely... 2183 glDisable(GL_TEXTURE_EXTERNAL_OES); 2184 glDisable(GL_TEXTURE_2D); 2185 glClearColor(0,0,0,1); 2186 glClear(GL_COLOR_BUFFER_BIT); 2187 glMatrixMode(GL_MODELVIEW); 2188 glLoadIdentity(); 2189 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ()); 2190 const size_t count = layers.size(); 2191 for (size_t i=0 ; i<count ; ++i) { 2192 const sp<LayerBase>& layer(layers[i]); 2193 layer->draw(hw); 2194 } 2195 2196 hw->compositionComplete(); 2197 2198 // back to main framebuffer 2199 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); 2200 glDeleteFramebuffersOES(1, &name); 2201 2202 *textureName = tname; 2203 *uOut = u; 2204 *vOut = v; 2205 return NO_ERROR; 2206} 2207 2208// --------------------------------------------------------------------------- 2209 2210status_t SurfaceFlinger::captureScreenImplLocked(DisplayID dpy, 2211 sp<IMemoryHeap>* heap, 2212 uint32_t* w, uint32_t* h, PixelFormat* f, 2213 uint32_t sw, uint32_t sh, 2214 uint32_t minLayerZ, uint32_t maxLayerZ) 2215{ 2216 ATRACE_CALL(); 2217 2218 status_t result = PERMISSION_DENIED; 2219 2220 // only one display supported for now 2221 if (CC_UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) { 2222 ALOGE("invalid display %d", dpy); 2223 return BAD_VALUE; 2224 } 2225 2226 if (!GLExtensions::getInstance().haveFramebufferObject()) { 2227 return INVALID_OPERATION; 2228 } 2229 2230 // get screen geometry 2231 sp<const DisplayDevice> hw(getDisplayDevice(dpy)); 2232 const uint32_t hw_w = hw->getWidth(); 2233 const uint32_t hw_h = hw->getHeight(); 2234 2235 // if we have secure windows on this display, never allow the screen capture 2236 if (hw->getSecureLayerVisible()) { 2237 ALOGW("FB is protected: PERMISSION_DENIED"); 2238 return PERMISSION_DENIED; 2239 } 2240 2241 if ((sw > hw_w) || (sh > hw_h)) { 2242 ALOGE("size mismatch (%d, %d) > (%d, %d)", sw, sh, hw_w, hw_h); 2243 return BAD_VALUE; 2244 } 2245 2246 sw = (!sw) ? hw_w : sw; 2247 sh = (!sh) ? hw_h : sh; 2248 const size_t size = sw * sh * 4; 2249 const bool filtering = sw != hw_w || sh != hw_h; 2250 2251// ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d", 2252// sw, sh, minLayerZ, maxLayerZ); 2253 2254 // make sure to clear all GL error flags 2255 while ( glGetError() != GL_NO_ERROR ) ; 2256 2257 // create a FBO 2258 GLuint name, tname; 2259 glGenRenderbuffersOES(1, &tname); 2260 glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname); 2261 glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh); 2262 2263 glGenFramebuffersOES(1, &name); 2264 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name); 2265 glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, 2266 GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname); 2267 2268 GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES); 2269 2270 if (status == GL_FRAMEBUFFER_COMPLETE_OES) { 2271 2272 // invert everything, b/c glReadPixel() below will invert the FB 2273 glViewport(0, 0, sw, sh); 2274 glMatrixMode(GL_PROJECTION); 2275 glPushMatrix(); 2276 glLoadIdentity(); 2277 glOrthof(0, hw_w, hw_h, 0, 0, 1); 2278 glMatrixMode(GL_MODELVIEW); 2279 2280 // redraw the screen entirely... 2281 glClearColor(0,0,0,1); 2282 glClear(GL_COLOR_BUFFER_BIT); 2283 2284 const LayerVector& layers(mDrawingState.layersSortedByZ); 2285 const size_t count = layers.size(); 2286 for (size_t i=0 ; i<count ; ++i) { 2287 const sp<LayerBase>& layer(layers[i]); 2288 const uint32_t flags = layer->drawingState().flags; 2289 if (!(flags & layer_state_t::eLayerHidden)) { 2290 const uint32_t z = layer->drawingState().z; 2291 if (z >= minLayerZ && z <= maxLayerZ) { 2292 if (filtering) layer->setFiltering(true); 2293 layer->draw(hw); 2294 if (filtering) layer->setFiltering(false); 2295 } 2296 } 2297 } 2298 2299 // check for errors and return screen capture 2300 if (glGetError() != GL_NO_ERROR) { 2301 // error while rendering 2302 result = INVALID_OPERATION; 2303 } else { 2304 // allocate shared memory large enough to hold the 2305 // screen capture 2306 sp<MemoryHeapBase> base( 2307 new MemoryHeapBase(size, 0, "screen-capture") ); 2308 void* const ptr = base->getBase(); 2309 if (ptr) { 2310 // capture the screen with glReadPixels() 2311 ScopedTrace _t(ATRACE_TAG, "glReadPixels"); 2312 glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr); 2313 if (glGetError() == GL_NO_ERROR) { 2314 *heap = base; 2315 *w = sw; 2316 *h = sh; 2317 *f = PIXEL_FORMAT_RGBA_8888; 2318 result = NO_ERROR; 2319 } 2320 } else { 2321 result = NO_MEMORY; 2322 } 2323 } 2324 glViewport(0, 0, hw_w, hw_h); 2325 glMatrixMode(GL_PROJECTION); 2326 glPopMatrix(); 2327 glMatrixMode(GL_MODELVIEW); 2328 } else { 2329 result = BAD_VALUE; 2330 } 2331 2332 // release FBO resources 2333 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); 2334 glDeleteRenderbuffersOES(1, &tname); 2335 glDeleteFramebuffersOES(1, &name); 2336 2337 hw->compositionComplete(); 2338 2339// ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK"); 2340 2341 return result; 2342} 2343 2344 2345status_t SurfaceFlinger::captureScreen(DisplayID dpy, 2346 sp<IMemoryHeap>* heap, 2347 uint32_t* width, uint32_t* height, PixelFormat* format, 2348 uint32_t sw, uint32_t sh, 2349 uint32_t minLayerZ, uint32_t maxLayerZ) 2350{ 2351 // only one display supported for now 2352 if (CC_UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) 2353 return BAD_VALUE; 2354 2355 if (!GLExtensions::getInstance().haveFramebufferObject()) 2356 return INVALID_OPERATION; 2357 2358 class MessageCaptureScreen : public MessageBase { 2359 SurfaceFlinger* flinger; 2360 DisplayID dpy; 2361 sp<IMemoryHeap>* heap; 2362 uint32_t* w; 2363 uint32_t* h; 2364 PixelFormat* f; 2365 uint32_t sw; 2366 uint32_t sh; 2367 uint32_t minLayerZ; 2368 uint32_t maxLayerZ; 2369 status_t result; 2370 public: 2371 MessageCaptureScreen(SurfaceFlinger* flinger, DisplayID dpy, 2372 sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f, 2373 uint32_t sw, uint32_t sh, 2374 uint32_t minLayerZ, uint32_t maxLayerZ) 2375 : flinger(flinger), dpy(dpy), 2376 heap(heap), w(w), h(h), f(f), sw(sw), sh(sh), 2377 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ), 2378 result(PERMISSION_DENIED) 2379 { 2380 } 2381 status_t getResult() const { 2382 return result; 2383 } 2384 virtual bool handler() { 2385 Mutex::Autolock _l(flinger->mStateLock); 2386 result = flinger->captureScreenImplLocked(dpy, 2387 heap, w, h, f, sw, sh, minLayerZ, maxLayerZ); 2388 return true; 2389 } 2390 }; 2391 2392 sp<MessageBase> msg = new MessageCaptureScreen(this, 2393 dpy, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ); 2394 status_t res = postMessageSync(msg); 2395 if (res == NO_ERROR) { 2396 res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult(); 2397 } 2398 return res; 2399} 2400 2401// --------------------------------------------------------------------------- 2402 2403SurfaceFlinger::LayerVector::LayerVector() { 2404} 2405 2406SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs) 2407 : SortedVector<sp<LayerBase> >(rhs) { 2408} 2409 2410int SurfaceFlinger::LayerVector::do_compare(const void* lhs, 2411 const void* rhs) const 2412{ 2413 // sort layers per layer-stack, then by z-order and finally by sequence 2414 const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs)); 2415 const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs)); 2416 2417 uint32_t ls = l->currentState().layerStack; 2418 uint32_t rs = r->currentState().layerStack; 2419 if (ls != rs) 2420 return ls - rs; 2421 2422 uint32_t lz = l->currentState().z; 2423 uint32_t rz = r->currentState().z; 2424 if (lz != rz) 2425 return lz - rz; 2426 2427 return l->sequence - r->sequence; 2428} 2429 2430// --------------------------------------------------------------------------- 2431 2432SurfaceFlinger::DisplayDeviceState::DisplayDeviceState() : id(-1) { 2433} 2434 2435SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(int32_t id) 2436 : id(id), layerStack(0), orientation(0) { 2437} 2438 2439// --------------------------------------------------------------------------- 2440 2441GraphicBufferAlloc::GraphicBufferAlloc() {} 2442 2443GraphicBufferAlloc::~GraphicBufferAlloc() {} 2444 2445sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h, 2446 PixelFormat format, uint32_t usage, status_t* error) { 2447 sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage)); 2448 status_t err = graphicBuffer->initCheck(); 2449 *error = err; 2450 if (err != 0 || graphicBuffer->handle == 0) { 2451 if (err == NO_MEMORY) { 2452 GraphicBuffer::dumpAllocationsToSystemLog(); 2453 } 2454 ALOGE("GraphicBufferAlloc::createGraphicBuffer(w=%d, h=%d) " 2455 "failed (%s), handle=%p", 2456 w, h, strerror(-err), graphicBuffer->handle); 2457 return 0; 2458 } 2459 return graphicBuffer; 2460} 2461 2462// --------------------------------------------------------------------------- 2463 2464}; // namespace android 2465