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