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