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