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