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