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