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