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