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