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