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