2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
25 #include <sys/types.h>
27 #include <sys/ioctl.h>
29 #include <cutils/log.h>
30 #include <cutils/properties.h>
32 #include <binder/IPCThreadState.h>
33 #include <binder/IServiceManager.h>
34 #include <binder/MemoryHeapBase.h>
36 #include <utils/String8.h>
37 #include <utils/String16.h>
38 #include <utils/StopWatch.h>
40 #include <ui/GraphicBufferAllocator.h>
41 #include <ui/GraphicLog.h>
42 #include <ui/PixelFormat.h>
44 #include <pixelflinger/pixelflinger.h>
48 #include "GLExtensions.h"
51 #include "SurfaceFlinger.h"
53 #include "DisplayHardware/DisplayHardware.h"
54 #include "DisplayHardware/HWComposer.h"
56 /* ideally AID_GRAPHICS would be in a semi-public header
57 * or there would be a way to map a user/group name to its id
60 #define AID_GRAPHICS 1003
63 #define DISPLAY_COUNT 1
66 // ---------------------------------------------------------------------------
68 SurfaceFlinger::SurfaceFlinger()
69 : BnSurfaceComposer(), Thread(false),
72 mResizeTransationPending(false),
73 mLayersRemoved(false),
74 mBootTime(systemTime()),
75 mHardwareTest("android.permission.HARDWARE_TEST"),
76 mAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER"),
77 mReadFramebuffer("android.permission.READ_FRAME_BUFFER"),
78 mDump("android.permission.DUMP"),
79 mVisibleRegionsDirty(false),
80 mHwWorkListDirty(false),
81 mDeferReleaseConsole(false),
82 mFreezeDisplay(false),
83 mElectronBeamAnimationMode(0),
85 mFreezeDisplayTime(0),
89 mDebugInSwapBuffers(0),
90 mLastSwapBufferTime(0),
91 mDebugInTransaction(0),
92 mLastTransactionTime(0),
100 void SurfaceFlinger::init()
102 LOGI("SurfaceFlinger is starting");
104 // debugging stuff...
105 char value[PROPERTY_VALUE_MAX];
106 property_get("debug.sf.showupdates", value, "0");
107 mDebugRegion = atoi(value);
108 property_get("debug.sf.showbackground", value, "0");
109 mDebugBackground = atoi(value);
111 LOGI_IF(mDebugRegion, "showupdates enabled");
112 LOGI_IF(mDebugBackground, "showbackground enabled");
115 SurfaceFlinger::~SurfaceFlinger()
117 glDeleteTextures(1, &mWormholeTexName);
120 sp<IMemoryHeap> SurfaceFlinger::getCblk() const
125 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
127 sp<ISurfaceComposerClient> bclient;
128 sp<Client> client(new Client(this));
129 status_t err = client->initCheck();
130 if (err == NO_ERROR) {
136 sp<ISurfaceComposerClient> SurfaceFlinger::createClientConnection()
138 sp<ISurfaceComposerClient> bclient;
139 sp<UserClient> client(new UserClient(this));
140 status_t err = client->initCheck();
141 if (err == NO_ERROR) {
147 sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
149 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
153 const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const
155 LOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy);
156 const GraphicPlane& plane(mGraphicPlanes[dpy]);
160 GraphicPlane& SurfaceFlinger::graphicPlane(int dpy)
162 return const_cast<GraphicPlane&>(
163 const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy));
166 void SurfaceFlinger::bootFinished()
168 const nsecs_t now = systemTime();
169 const nsecs_t duration = now - mBootTime;
170 LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
171 mBootFinished = true;
172 property_set("ctl.stop", "bootanim");
175 void SurfaceFlinger::onFirstRef()
177 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
179 // Wait for the main thread to be done with its initialization
180 mReadyToRunBarrier.wait();
183 static inline uint16_t pack565(int r, int g, int b) {
184 return (r<<11)|(g<<5)|b;
187 status_t SurfaceFlinger::readyToRun()
189 LOGI( "SurfaceFlinger's main thread ready to run. "
190 "Initializing graphics H/W...");
192 // we only support one display currently
196 // initialize the main display
197 GraphicPlane& plane(graphicPlane(dpy));
198 DisplayHardware* const hw = new DisplayHardware(this, dpy);
199 plane.setDisplayHardware(hw);
202 // create the shared control-block
203 mServerHeap = new MemoryHeapBase(4096,
204 MemoryHeapBase::READ_ONLY, "SurfaceFlinger read-only heap");
205 LOGE_IF(mServerHeap==0, "can't create shared memory dealer");
207 mServerCblk = static_cast<surface_flinger_cblk_t*>(mServerHeap->getBase());
208 LOGE_IF(mServerCblk==0, "can't get to shared control block's address");
210 new(mServerCblk) surface_flinger_cblk_t;
212 // initialize primary screen
213 // (other display should be initialized in the same manner, but
214 // asynchronously, as they could come and go. None of this is supported
216 const GraphicPlane& plane(graphicPlane(dpy));
217 const DisplayHardware& hw = plane.displayHardware();
218 const uint32_t w = hw.getWidth();
219 const uint32_t h = hw.getHeight();
220 const uint32_t f = hw.getFormat();
223 // initialize the shared control block
224 mServerCblk->connected |= 1<<dpy;
225 display_cblk_t* dcblk = mServerCblk->displays + dpy;
226 memset(dcblk, 0, sizeof(display_cblk_t));
227 dcblk->w = plane.getWidth();
228 dcblk->h = plane.getHeight();
230 dcblk->orientation = ISurfaceComposer::eOrientationDefault;
231 dcblk->xdpi = hw.getDpiX();
232 dcblk->ydpi = hw.getDpiY();
233 dcblk->fps = hw.getRefreshRate();
234 dcblk->density = hw.getDensity();
236 // Initialize OpenGL|ES
237 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
238 glPixelStorei(GL_PACK_ALIGNMENT, 4);
239 glEnableClientState(GL_VERTEX_ARRAY);
240 glEnable(GL_SCISSOR_TEST);
241 glShadeModel(GL_FLAT);
242 glDisable(GL_DITHER);
243 glDisable(GL_CULL_FACE);
245 const uint16_t g0 = pack565(0x0F,0x1F,0x0F);
246 const uint16_t g1 = pack565(0x17,0x2f,0x17);
247 const uint16_t textureData[4] = { g0, g1, g1, g0 };
248 glGenTextures(1, &mWormholeTexName);
249 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
250 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
251 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
252 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
253 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
254 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0,
255 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textureData);
257 glViewport(0, 0, w, h);
258 glMatrixMode(GL_PROJECTION);
260 glOrthof(0, w, h, 0, 0, 1);
262 mReadyToRunBarrier.open();
265 * We're now ready to accept clients...
268 // start boot animation
269 property_set("ctl.start", "bootanim");
274 // ----------------------------------------------------------------------------
277 #pragma mark Events Handler
280 void SurfaceFlinger::waitForEvent()
283 nsecs_t timeout = -1;
284 const nsecs_t freezeDisplayTimeout = ms2ns(5000);
285 if (UNLIKELY(isFrozen())) {
287 const nsecs_t now = systemTime();
288 if (mFreezeDisplayTime == 0) {
289 mFreezeDisplayTime = now;
291 nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime);
292 timeout = waitTime>0 ? waitTime : 0;
295 sp<MessageBase> msg = mEventQueue.waitMessage(timeout);
297 // see if we timed out
299 const nsecs_t now = systemTime();
300 nsecs_t frozenTime = (now - mFreezeDisplayTime);
301 if (frozenTime >= freezeDisplayTimeout) {
302 // we timed out and are still frozen
303 LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d",
304 mFreezeDisplay, mFreezeCount);
305 mFreezeDisplayTime = 0;
307 mFreezeDisplay = false;
313 case MessageQueue::INVALIDATE:
314 // invalidate message, just return to the main loop
321 void SurfaceFlinger::signalEvent() {
322 mEventQueue.invalidate();
325 void SurfaceFlinger::signal() const {
326 // this is the IPC call
327 const_cast<SurfaceFlinger*>(this)->signalEvent();
330 bool SurfaceFlinger::authenticateSurface(const sp<ISurface>& surface) const {
331 Mutex::Autolock _l(mStateLock);
332 sp<IBinder> surfBinder(surface->asBinder());
334 // Check the visible layer list for the ISurface
335 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
336 size_t count = currentLayers.size();
337 for (size_t i=0 ; i<count ; i++) {
338 const sp<LayerBase>& layer(currentLayers[i]);
339 sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
340 if (lbc != NULL && lbc->getSurfaceBinder() == surfBinder) {
345 // Check the layers in the purgatory. This check is here so that if a
346 // Surface gets destroyed before all the clients are done using it, the
347 // error will not be reported as "surface XYZ is not authenticated", but
348 // will instead fail later on when the client tries to use the surface,
349 // which should be reported as "surface XYZ returned an -ENODEV". The
350 // purgatorized layers are no less authentic than the visible ones, so this
351 // should not cause any harm.
352 size_t purgatorySize = mLayerPurgatory.size();
353 for (size_t i=0 ; i<purgatorySize ; i++) {
354 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
355 sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
356 if (lbc != NULL && lbc->getSurfaceBinder() == surfBinder) {
364 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
365 nsecs_t reltime, uint32_t flags)
367 return mEventQueue.postMessage(msg, reltime, flags);
370 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
371 nsecs_t reltime, uint32_t flags)
373 status_t res = mEventQueue.postMessage(msg, reltime, flags);
374 if (res == NO_ERROR) {
380 // ----------------------------------------------------------------------------
383 #pragma mark Main loop
386 bool SurfaceFlinger::threadLoop()
390 // check for transactions
391 if (UNLIKELY(mConsoleSignals)) {
392 handleConsoleEvents();
395 if (LIKELY(mTransactionCount == 0)) {
396 // if we're in a global transaction, don't do anything.
397 const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
398 uint32_t transactionFlags = getTransactionFlags(mask);
399 if (LIKELY(transactionFlags)) {
400 handleTransaction(transactionFlags);
404 // post surfaces (if needed)
407 if (UNLIKELY(mHwWorkListDirty)) {
408 // build the h/w work list
412 const DisplayHardware& hw(graphicPlane(0).displayHardware());
413 if (LIKELY(hw.canDraw() && !isFrozen())) {
414 // repaint the framebuffer (if needed)
416 const int index = hw.getCurrentBufferIndex();
417 GraphicLog& logger(GraphicLog::getInstance());
419 logger.log(GraphicLog::SF_REPAINT, index);
422 // inform the h/w that we're done compositing
423 logger.log(GraphicLog::SF_COMPOSITION_COMPLETE, index);
424 hw.compositionComplete();
426 logger.log(GraphicLog::SF_SWAP_BUFFERS, index);
429 logger.log(GraphicLog::SF_REPAINT_DONE, index);
431 // pretend we did the post
432 hw.compositionComplete();
433 usleep(16667); // 60 fps period
438 void SurfaceFlinger::postFramebuffer()
440 if (!mInvalidRegion.isEmpty()) {
441 const DisplayHardware& hw(graphicPlane(0).displayHardware());
442 const nsecs_t now = systemTime();
443 mDebugInSwapBuffers = now;
444 hw.flip(mInvalidRegion);
445 mLastSwapBufferTime = systemTime() - now;
446 mDebugInSwapBuffers = 0;
447 mInvalidRegion.clear();
451 void SurfaceFlinger::handleConsoleEvents()
453 // something to do with the console
454 const DisplayHardware& hw = graphicPlane(0).displayHardware();
456 int what = android_atomic_and(0, &mConsoleSignals);
457 if (what & eConsoleAcquired) {
459 // this is a temporary work-around, eventually this should be called
460 // by the power-manager
461 SurfaceFlinger::turnElectronBeamOn(mElectronBeamAnimationMode);
464 if (mDeferReleaseConsole && hw.isScreenAcquired()) {
465 // We got the release signal before the acquire signal
466 mDeferReleaseConsole = false;
470 if (what & eConsoleReleased) {
471 if (hw.isScreenAcquired()) {
474 mDeferReleaseConsole = true;
478 mDirtyRegion.set(hw.bounds());
481 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
483 Vector< sp<LayerBase> > ditchedLayers;
486 * Perform and commit the transaction
489 { // scope for the lock
490 Mutex::Autolock _l(mStateLock);
491 const nsecs_t now = systemTime();
492 mDebugInTransaction = now;
493 handleTransactionLocked(transactionFlags, ditchedLayers);
494 mLastTransactionTime = systemTime() - now;
495 mDebugInTransaction = 0;
496 invalidateHwcGeometry();
497 // here the transaction has been committed
501 * Clean-up all layers that went away
502 * (do this without the lock held)
505 const size_t count = ditchedLayers.size();
506 for (size_t i=0 ; i<count ; i++) {
507 if (ditchedLayers[i] != 0) {
508 //LOGD("ditching layer %p", ditchedLayers[i].get());
509 ditchedLayers[i]->ditch();
514 void SurfaceFlinger::handleTransactionLocked(
515 uint32_t transactionFlags, Vector< sp<LayerBase> >& ditchedLayers)
517 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
518 const size_t count = currentLayers.size();
521 * Traversal of the children
522 * (perform the transaction for each of them if needed)
525 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
526 if (layersNeedTransaction) {
527 for (size_t i=0 ; i<count ; i++) {
528 const sp<LayerBase>& layer = currentLayers[i];
529 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
530 if (!trFlags) continue;
532 const uint32_t flags = layer->doTransaction(0);
533 if (flags & Layer::eVisibleRegion)
534 mVisibleRegionsDirty = true;
539 * Perform our own transaction if needed
542 if (transactionFlags & eTransactionNeeded) {
543 if (mCurrentState.orientation != mDrawingState.orientation) {
544 // the orientation has changed, recompute all visible regions
545 // and invalidate everything.
548 const int orientation = mCurrentState.orientation;
549 const uint32_t type = mCurrentState.orientationType;
550 GraphicPlane& plane(graphicPlane(dpy));
551 plane.setOrientation(orientation);
553 // update the shared control block
554 const DisplayHardware& hw(plane.displayHardware());
555 volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
556 dcblk->orientation = orientation;
557 dcblk->w = plane.getWidth();
558 dcblk->h = plane.getHeight();
560 mVisibleRegionsDirty = true;
561 mDirtyRegion.set(hw.bounds());
564 if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
565 // freezing or unfreezing the display -> trigger animation if needed
566 mFreezeDisplay = mCurrentState.freezeDisplay;
568 mFreezeDisplayTime = 0;
571 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
572 // layers have been added
573 mVisibleRegionsDirty = true;
576 // some layers might have been removed, so
577 // we need to update the regions they're exposing.
578 if (mLayersRemoved) {
579 mLayersRemoved = false;
580 mVisibleRegionsDirty = true;
581 const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
582 const size_t count = previousLayers.size();
583 for (size_t i=0 ; i<count ; i++) {
584 const sp<LayerBase>& layer(previousLayers[i]);
585 if (currentLayers.indexOf( layer ) < 0) {
586 // this layer is not visible anymore
587 ditchedLayers.add(layer);
588 mDirtyRegionRemovedLayer.orSelf(layer->visibleRegionScreen);
597 sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
599 return new FreezeLock(const_cast<SurfaceFlinger *>(this));
602 void SurfaceFlinger::computeVisibleRegions(
603 LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
605 const GraphicPlane& plane(graphicPlane(0));
606 const Transform& planeTransform(plane.transform());
607 const DisplayHardware& hw(plane.displayHardware());
608 const Region screenRegion(hw.bounds());
610 Region aboveOpaqueLayers;
611 Region aboveCoveredLayers;
614 bool secureFrameBuffer = false;
616 size_t i = currentLayers.size();
618 const sp<LayerBase>& layer = currentLayers[i];
619 layer->validateVisibility(planeTransform);
621 // start with the whole surface at its current location
622 const Layer::State& s(layer->drawingState());
625 * opaqueRegion: area of a surface that is fully opaque.
630 * visibleRegion: area of a surface that is visible on screen
631 * and not fully transparent. This is essentially the layer's
632 * footprint minus the opaque regions above it.
633 * Areas covered by a translucent surface are considered visible.
635 Region visibleRegion;
638 * coveredRegion: area of a surface that is covered by all
639 * visible regions above it (which includes the translucent areas).
641 Region coveredRegion;
644 // handle hidden surfaces by setting the visible region to empty
645 if (LIKELY(!(s.flags & ISurfaceComposer::eLayerHidden) && s.alpha)) {
646 const bool translucent = layer->needsBlending();
647 const Rect bounds(layer->visibleBounds());
648 visibleRegion.set(bounds);
649 visibleRegion.andSelf(screenRegion);
650 if (!visibleRegion.isEmpty()) {
651 // Remove the transparent area from the visible region
653 visibleRegion.subtractSelf(layer->transparentRegionScreen);
656 // compute the opaque region
657 const int32_t layerOrientation = layer->getOrientation();
658 if (s.alpha==255 && !translucent &&
659 ((layerOrientation & Transform::ROT_INVALID) == false)) {
660 // the opaque region is the layer's footprint
661 opaqueRegion = visibleRegion;
666 // Clip the covered region to the visible region
667 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
669 // Update aboveCoveredLayers for next (lower) layer
670 aboveCoveredLayers.orSelf(visibleRegion);
672 // subtract the opaque region covered by the layers above us
673 visibleRegion.subtractSelf(aboveOpaqueLayers);
675 // compute this layer's dirty region
676 if (layer->contentDirty) {
677 // we need to invalidate the whole region
678 dirty = visibleRegion;
679 // as well, as the old visible region
680 dirty.orSelf(layer->visibleRegionScreen);
681 layer->contentDirty = false;
683 /* compute the exposed region:
684 * the exposed region consists of two components:
685 * 1) what's VISIBLE now and was COVERED before
686 * 2) what's EXPOSED now less what was EXPOSED before
688 * note that (1) is conservative, we start with the whole
689 * visible region but only keep what used to be covered by
690 * something -- which mean it may have been exposed.
692 * (2) handles areas that were not covered by anything but got
693 * exposed because of a resize.
695 const Region newExposed = visibleRegion - coveredRegion;
696 const Region oldVisibleRegion = layer->visibleRegionScreen;
697 const Region oldCoveredRegion = layer->coveredRegionScreen;
698 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
699 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
701 dirty.subtractSelf(aboveOpaqueLayers);
703 // accumulate to the screen dirty region
704 dirtyRegion.orSelf(dirty);
706 // Update aboveOpaqueLayers for next (lower) layer
707 aboveOpaqueLayers.orSelf(opaqueRegion);
709 // Store the visible region is screen space
710 layer->setVisibleRegion(visibleRegion);
711 layer->setCoveredRegion(coveredRegion);
713 // If a secure layer is partially visible, lock-down the screen!
714 if (layer->isSecure() && !visibleRegion.isEmpty()) {
715 secureFrameBuffer = true;
719 // invalidate the areas where a layer was removed
720 dirtyRegion.orSelf(mDirtyRegionRemovedLayer);
721 mDirtyRegionRemovedLayer.clear();
723 mSecureFrameBuffer = secureFrameBuffer;
724 opaqueRegion = aboveOpaqueLayers;
728 void SurfaceFlinger::commitTransaction()
730 mDrawingState = mCurrentState;
731 mResizeTransationPending = false;
732 mTransactionCV.broadcast();
735 void SurfaceFlinger::handlePageFlip()
737 bool visibleRegions = mVisibleRegionsDirty;
738 LayerVector& currentLayers(
739 const_cast<LayerVector&>(mDrawingState.layersSortedByZ));
740 visibleRegions |= lockPageFlip(currentLayers);
742 const DisplayHardware& hw = graphicPlane(0).displayHardware();
743 const Region screenRegion(hw.bounds());
744 if (visibleRegions) {
746 computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
749 * rebuild the visible layer list
751 mVisibleLayersSortedByZ.clear();
752 const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
753 size_t count = currentLayers.size();
754 mVisibleLayersSortedByZ.setCapacity(count);
755 for (size_t i=0 ; i<count ; i++) {
756 if (!currentLayers[i]->visibleRegionScreen.isEmpty())
757 mVisibleLayersSortedByZ.add(currentLayers[i]);
760 mWormholeRegion = screenRegion.subtract(opaqueRegion);
761 mVisibleRegionsDirty = false;
762 invalidateHwcGeometry();
765 unlockPageFlip(currentLayers);
766 mDirtyRegion.andSelf(screenRegion);
769 void SurfaceFlinger::invalidateHwcGeometry()
771 mHwWorkListDirty = true;
774 bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
776 bool recomputeVisibleRegions = false;
777 size_t count = currentLayers.size();
778 sp<LayerBase> const* layers = currentLayers.array();
779 for (size_t i=0 ; i<count ; i++) {
780 const sp<LayerBase>& layer(layers[i]);
781 layer->lockPageFlip(recomputeVisibleRegions);
783 return recomputeVisibleRegions;
786 void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
788 const GraphicPlane& plane(graphicPlane(0));
789 const Transform& planeTransform(plane.transform());
790 size_t count = currentLayers.size();
791 sp<LayerBase> const* layers = currentLayers.array();
792 for (size_t i=0 ; i<count ; i++) {
793 const sp<LayerBase>& layer(layers[i]);
794 layer->unlockPageFlip(planeTransform, mDirtyRegion);
798 void SurfaceFlinger::handleWorkList()
800 mHwWorkListDirty = false;
801 HWComposer& hwc(graphicPlane(0).displayHardware().getHwComposer());
802 if (hwc.initCheck() == NO_ERROR) {
803 const Vector< sp<LayerBase> >& currentLayers(mVisibleLayersSortedByZ);
804 const size_t count = currentLayers.size();
805 hwc.createWorkList(count);
806 hwc_layer_t* const cur(hwc.getLayers());
807 for (size_t i=0 ; cur && i<count ; i++) {
808 currentLayers[i]->setGeometry(&cur[i]);
809 if (mDebugDisableHWC) {
810 cur[i].compositionType = HWC_FRAMEBUFFER;
811 cur[i].flags |= HWC_SKIP_LAYER;
817 void SurfaceFlinger::handleRepaint()
819 // compute the invalid region
820 mInvalidRegion.orSelf(mDirtyRegion);
822 if (UNLIKELY(mDebugRegion)) {
826 // set the frame buffer
827 const DisplayHardware& hw(graphicPlane(0).displayHardware());
828 glMatrixMode(GL_MODELVIEW);
831 uint32_t flags = hw.getFlags();
832 if ((flags & DisplayHardware::SWAP_RECTANGLE) ||
833 (flags & DisplayHardware::BUFFER_PRESERVED))
835 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
836 // takes a rectangle, we must make sure to update that whole
837 // rectangle in that case
838 if (flags & DisplayHardware::SWAP_RECTANGLE) {
839 // TODO: we really should be able to pass a region to
840 // SWAP_RECTANGLE so that we don't have to redraw all this.
841 mDirtyRegion.set(mInvalidRegion.bounds());
843 // in the BUFFER_PRESERVED case, obviously, we can update only
844 // what's needed and nothing more.
845 // NOTE: this is NOT a common case, as preserving the backbuffer
846 // is costly and usually involves copying the whole update back.
849 if (flags & DisplayHardware::PARTIAL_UPDATES) {
850 // We need to redraw the rectangle that will be updated
851 // (pushed to the framebuffer).
852 // This is needed because PARTIAL_UPDATES only takes one
853 // rectangle instead of a region (see DisplayHardware::flip())
854 mDirtyRegion.set(mInvalidRegion.bounds());
856 // we need to redraw everything (the whole screen)
857 mDirtyRegion.set(hw.bounds());
858 mInvalidRegion = mDirtyRegion;
862 // compose all surfaces
863 composeSurfaces(mDirtyRegion);
865 // clear the dirty regions
866 mDirtyRegion.clear();
869 void SurfaceFlinger::composeSurfaces(const Region& dirty)
871 if (UNLIKELY(!mWormholeRegion.isEmpty())) {
872 // should never happen unless the window manager has a bug
877 status_t err = NO_ERROR;
878 const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
879 size_t count = layers.size();
881 const DisplayHardware& hw(graphicPlane(0).displayHardware());
882 HWComposer& hwc(hw.getHwComposer());
883 hwc_layer_t* const cur(hwc.getLayers());
885 LOGE_IF(cur && hwc.getNumLayers() != count,
886 "HAL number of layers (%d) doesn't match surfaceflinger (%d)",
887 hwc.getNumLayers(), count);
889 // just to be extra-safe, use the smallest count
890 if (hwc.initCheck() == NO_ERROR) {
891 count = count < hwc.getNumLayers() ? count : hwc.getNumLayers();
895 * update the per-frame h/w composer data for each layer
896 * and build the transparent region of the FB
900 for (size_t i=0 ; i<count ; i++) {
901 const sp<LayerBase>& layer(layers[i]);
902 layer->setPerFrameData(&cur[i]);
905 LOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
907 if (err == NO_ERROR) {
908 for (size_t i=0 ; i<count ; i++) {
909 if (cur[i].hints & HWC_HINT_CLEAR_FB) {
910 const sp<LayerBase>& layer(layers[i]);
911 if (!(layer->needsBlending())) {
912 transparent.orSelf(layer->visibleRegionScreen);
918 * clear the area of the FB that need to be transparent
920 transparent.andSelf(dirty);
921 if (!transparent.isEmpty()) {
922 glClearColor(0,0,0,0);
923 Region::const_iterator it = transparent.begin();
924 Region::const_iterator const end = transparent.end();
925 const int32_t height = hw.getHeight();
927 const Rect& r(*it++);
928 const GLint sy = height - (r.top + r.height());
929 glScissor(r.left, sy, r.width(), r.height());
930 glClear(GL_COLOR_BUFFER_BIT);
938 * and then, render the layers targeted at the framebuffer
940 for (size_t i=0 ; i<count ; i++) {
942 if ((cur[i].compositionType != HWC_FRAMEBUFFER) &&
943 !(cur[i].flags & HWC_SKIP_LAYER)) {
944 // skip layers handled by the HAL
949 const sp<LayerBase>& layer(layers[i]);
950 const Region clip(dirty.intersect(layer->visibleRegionScreen));
951 if (!clip.isEmpty()) {
957 void SurfaceFlinger::debugFlashRegions()
959 const DisplayHardware& hw(graphicPlane(0).displayHardware());
960 const uint32_t flags = hw.getFlags();
962 if (!((flags & DisplayHardware::SWAP_RECTANGLE) ||
963 (flags & DisplayHardware::BUFFER_PRESERVED))) {
964 const Region repaint((flags & DisplayHardware::PARTIAL_UPDATES) ?
965 mDirtyRegion.bounds() : hw.bounds());
966 composeSurfaces(repaint);
969 TextureManager::deactivateTextures();
972 glDisable(GL_DITHER);
973 glDisable(GL_SCISSOR_TEST);
975 static int toggle = 0;
978 glColor4f(1, 0, 1, 1);
980 glColor4f(1, 1, 0, 1);
983 Region::const_iterator it = mDirtyRegion.begin();
984 Region::const_iterator const end = mDirtyRegion.end();
986 const Rect& r = *it++;
987 GLfloat vertices[][2] = {
989 { r.left, r.bottom },
990 { r.right, r.bottom },
993 glVertexPointer(2, GL_FLOAT, 0, vertices);
994 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
997 if (mInvalidRegion.isEmpty()) {
998 mDirtyRegion.dump("mDirtyRegion");
999 mInvalidRegion.dump("mInvalidRegion");
1001 hw.flip(mInvalidRegion);
1003 if (mDebugRegion > 1)
1004 usleep(mDebugRegion * 1000);
1006 glEnable(GL_SCISSOR_TEST);
1007 //mDirtyRegion.dump("mDirtyRegion");
1010 void SurfaceFlinger::drawWormhole() const
1012 const Region region(mWormholeRegion.intersect(mDirtyRegion));
1013 if (region.isEmpty())
1016 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1017 const int32_t width = hw.getWidth();
1018 const int32_t height = hw.getHeight();
1020 glDisable(GL_BLEND);
1021 glDisable(GL_DITHER);
1023 if (LIKELY(!mDebugBackground)) {
1024 glClearColor(0,0,0,0);
1025 Region::const_iterator it = region.begin();
1026 Region::const_iterator const end = region.end();
1028 const Rect& r = *it++;
1029 const GLint sy = height - (r.top + r.height());
1030 glScissor(r.left, sy, r.width(), r.height());
1031 glClear(GL_COLOR_BUFFER_BIT);
1034 const GLshort vertices[][2] = { { 0, 0 }, { width, 0 },
1035 { width, height }, { 0, height } };
1036 const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } };
1037 glVertexPointer(2, GL_SHORT, 0, vertices);
1038 glTexCoordPointer(2, GL_SHORT, 0, tcoords);
1039 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1040 #if defined(GL_OES_EGL_image_external)
1041 if (GLExtensions::getInstance().haveTextureExternal()) {
1042 glDisable(GL_TEXTURE_EXTERNAL_OES);
1045 glEnable(GL_TEXTURE_2D);
1046 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
1047 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1048 glMatrixMode(GL_TEXTURE);
1050 glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
1051 Region::const_iterator it = region.begin();
1052 Region::const_iterator const end = region.end();
1054 const Rect& r = *it++;
1055 const GLint sy = height - (r.top + r.height());
1056 glScissor(r.left, sy, r.width(), r.height());
1057 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1059 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1061 glMatrixMode(GL_MODELVIEW);
1065 void SurfaceFlinger::debugShowFPS() const
1067 static int mFrameCount;
1068 static int mLastFrameCount = 0;
1069 static nsecs_t mLastFpsTime = 0;
1070 static float mFps = 0;
1072 nsecs_t now = systemTime();
1073 nsecs_t diff = now - mLastFpsTime;
1074 if (diff > ms2ns(250)) {
1075 mFps = ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
1077 mLastFrameCount = mFrameCount;
1079 // XXX: mFPS has the value we want
1082 status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
1084 Mutex::Autolock _l(mStateLock);
1086 setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1090 status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
1092 ssize_t i = mCurrentState.layersSortedByZ.add(layer);
1093 return (i < 0) ? status_t(i) : status_t(NO_ERROR);
1096 ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
1097 const sp<LayerBaseClient>& lbc)
1099 Mutex::Autolock _l(mStateLock);
1101 // attach this layer to the client
1102 ssize_t name = client->attachLayer(lbc);
1104 // add this layer to the current state list
1110 status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
1112 Mutex::Autolock _l(mStateLock);
1113 status_t err = purgatorizeLayer_l(layer);
1114 if (err == NO_ERROR)
1115 setTransactionFlags(eTransactionNeeded);
1119 status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
1121 sp<LayerBaseClient> lbc(layerBase->getLayerBaseClient());
1123 mLayerMap.removeItem( lbc->getSurfaceBinder() );
1125 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1127 mLayersRemoved = true;
1130 return status_t(index);
1133 status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1135 // First add the layer to the purgatory list, which makes sure it won't
1136 // go away, then remove it from the main list (through a transaction).
1137 ssize_t err = removeLayer_l(layerBase);
1139 mLayerPurgatory.add(layerBase);
1142 layerBase->onRemoved();
1144 // it's possible that we don't find a layer, because it might
1145 // have been destroyed already -- this is not technically an error
1146 // from the user because there is a race between Client::destroySurface(),
1147 // ~Client() and ~ISurface().
1148 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1151 status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
1153 layer->forceVisibilityTransaction();
1154 setTransactionFlags(eTraversalNeeded);
1158 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1160 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1163 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1165 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1166 if ((old & flags)==0) { // wake the server up
1172 void SurfaceFlinger::openGlobalTransaction()
1174 android_atomic_inc(&mTransactionCount);
1177 void SurfaceFlinger::closeGlobalTransaction()
1179 if (android_atomic_dec(&mTransactionCount) == 1) {
1182 // if there is a transaction with a resize, wait for it to
1183 // take effect before returning.
1184 Mutex::Autolock _l(mStateLock);
1185 while (mResizeTransationPending) {
1186 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1187 if (CC_UNLIKELY(err != NO_ERROR)) {
1188 // just in case something goes wrong in SF, return to the
1189 // called after a few seconds.
1190 LOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!");
1191 mResizeTransationPending = false;
1198 status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags)
1200 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1203 Mutex::Autolock _l(mStateLock);
1204 mCurrentState.freezeDisplay = 1;
1205 setTransactionFlags(eTransactionNeeded);
1207 // flags is intended to communicate some sort of animation behavior
1208 // (for instance fading)
1212 status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
1214 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1217 Mutex::Autolock _l(mStateLock);
1218 mCurrentState.freezeDisplay = 0;
1219 setTransactionFlags(eTransactionNeeded);
1221 // flags is intended to communicate some sort of animation behavior
1222 // (for instance fading)
1226 int SurfaceFlinger::setOrientation(DisplayID dpy,
1227 int orientation, uint32_t flags)
1229 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1232 Mutex::Autolock _l(mStateLock);
1233 if (mCurrentState.orientation != orientation) {
1234 if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
1235 mCurrentState.orientationType = flags;
1236 mCurrentState.orientation = orientation;
1237 setTransactionFlags(eTransactionNeeded);
1238 mTransactionCV.wait(mStateLock);
1240 orientation = BAD_VALUE;
1246 sp<ISurface> SurfaceFlinger::createSurface(const sp<Client>& client, int pid,
1247 const String8& name, ISurfaceComposerClient::surface_data_t* params,
1248 DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1251 sp<LayerBaseClient> layer;
1252 sp<LayerBaseClient::Surface> surfaceHandle;
1254 if (int32_t(w|h) < 0) {
1255 LOGE("createSurface() failed, w or h is negative (w=%d, h=%d)",
1257 return surfaceHandle;
1260 //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
1261 sp<Layer> normalLayer;
1262 switch (flags & eFXSurfaceMask) {
1263 case eFXSurfaceNormal:
1264 normalLayer = createNormalSurface(client, d, w, h, flags, format);
1265 layer = normalLayer;
1267 case eFXSurfaceBlur:
1268 // for now we treat Blur as Dim, until we can implement it
1271 layer = createDimSurface(client, d, w, h, flags);
1276 layer->initStates(w, h, flags);
1277 layer->setName(name);
1278 ssize_t token = addClientLayer(client, layer);
1280 surfaceHandle = layer->getSurface();
1281 if (surfaceHandle != 0) {
1282 params->token = token;
1283 params->identity = surfaceHandle->getIdentity();
1286 params->format = format;
1287 if (normalLayer != 0) {
1288 Mutex::Autolock _l(mStateLock);
1289 mLayerMap.add(surfaceHandle->asBinder(), normalLayer);
1293 setTransactionFlags(eTransactionNeeded);
1296 return surfaceHandle;
1299 sp<Layer> SurfaceFlinger::createNormalSurface(
1300 const sp<Client>& client, DisplayID display,
1301 uint32_t w, uint32_t h, uint32_t flags,
1302 PixelFormat& format)
1304 // initialize the surfaces
1305 switch (format) { // TODO: take h/w into account
1306 case PIXEL_FORMAT_TRANSPARENT:
1307 case PIXEL_FORMAT_TRANSLUCENT:
1308 format = PIXEL_FORMAT_RGBA_8888;
1310 case PIXEL_FORMAT_OPAQUE:
1312 format = PIXEL_FORMAT_RGB_565;
1314 format = PIXEL_FORMAT_RGBX_8888;
1320 if (format == PIXEL_FORMAT_RGBX_8888)
1321 format = PIXEL_FORMAT_RGBA_8888;
1324 sp<Layer> layer = new Layer(this, display, client);
1325 status_t err = layer->setBuffers(w, h, format, flags);
1326 if (LIKELY(err != NO_ERROR)) {
1327 LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
1333 sp<LayerDim> SurfaceFlinger::createDimSurface(
1334 const sp<Client>& client, DisplayID display,
1335 uint32_t w, uint32_t h, uint32_t flags)
1337 sp<LayerDim> layer = new LayerDim(this, display, client);
1338 layer->initStates(w, h, flags);
1342 status_t SurfaceFlinger::removeSurface(const sp<Client>& client, SurfaceID sid)
1345 * called by the window manager, when a surface should be marked for
1348 * The surface is removed from the current and drawing lists, but placed
1349 * in the purgatory queue, so it's not destroyed right-away (we need
1350 * to wait for all client's references to go away first).
1353 status_t err = NAME_NOT_FOUND;
1354 Mutex::Autolock _l(mStateLock);
1355 sp<LayerBaseClient> layer = client->getLayerUser(sid);
1357 err = purgatorizeLayer_l(layer);
1358 if (err == NO_ERROR) {
1359 setTransactionFlags(eTransactionNeeded);
1365 status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer)
1367 // called by ~ISurface() when all references are gone
1369 class MessageDestroySurface : public MessageBase {
1370 SurfaceFlinger* flinger;
1371 sp<LayerBaseClient> layer;
1373 MessageDestroySurface(
1374 SurfaceFlinger* flinger, const sp<LayerBaseClient>& layer)
1375 : flinger(flinger), layer(layer) { }
1376 virtual bool handler() {
1377 sp<LayerBaseClient> l(layer);
1378 layer.clear(); // clear it outside of the lock;
1379 Mutex::Autolock _l(flinger->mStateLock);
1381 * remove the layer from the current list -- chances are that it's
1382 * not in the list anyway, because it should have been removed
1383 * already upon request of the client (eg: window manager).
1384 * However, a buggy client could have not done that.
1385 * Since we know we don't have any more clients, we don't need
1386 * to use the purgatory.
1388 status_t err = flinger->removeLayer_l(l);
1389 if (err == NAME_NOT_FOUND) {
1390 // The surface wasn't in the current list, which means it was
1391 // removed already, which means it is in the purgatory,
1392 // and need to be removed from there.
1393 // This needs to happen from the main thread since its dtor
1394 // must run from there (b/c of OpenGL ES). Additionally, we
1395 // can't really acquire our internal lock from
1396 // destroySurface() -- see postMessage() below.
1397 ssize_t idx = flinger->mLayerPurgatory.remove(l);
1399 "layer=%p is not in the purgatory list", l.get());
1402 LOGE_IF(err<0 && err != NAME_NOT_FOUND,
1403 "error removing layer=%p (%s)", l.get(), strerror(-err));
1408 postMessageAsync( new MessageDestroySurface(this, layer) );
1412 status_t SurfaceFlinger::setClientState(
1413 const sp<Client>& client,
1415 const layer_state_t* states)
1417 Mutex::Autolock _l(mStateLock);
1419 for (int i=0 ; i<count ; i++) {
1420 const layer_state_t& s(states[i]);
1421 sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
1423 const uint32_t what = s.what;
1424 if (what & ePositionChanged) {
1425 if (layer->setPosition(s.x, s.y))
1426 flags |= eTraversalNeeded;
1428 if (what & eLayerChanged) {
1429 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1430 if (layer->setLayer(s.z)) {
1431 mCurrentState.layersSortedByZ.removeAt(idx);
1432 mCurrentState.layersSortedByZ.add(layer);
1433 // we need traversal (state changed)
1434 // AND transaction (list changed)
1435 flags |= eTransactionNeeded|eTraversalNeeded;
1438 if (what & eSizeChanged) {
1439 if (layer->setSize(s.w, s.h)) {
1440 flags |= eTraversalNeeded;
1441 mResizeTransationPending = true;
1444 if (what & eAlphaChanged) {
1445 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1446 flags |= eTraversalNeeded;
1448 if (what & eMatrixChanged) {
1449 if (layer->setMatrix(s.matrix))
1450 flags |= eTraversalNeeded;
1452 if (what & eTransparentRegionChanged) {
1453 if (layer->setTransparentRegionHint(s.transparentRegion))
1454 flags |= eTraversalNeeded;
1456 if (what & eVisibilityChanged) {
1457 if (layer->setFlags(s.flags, s.mask))
1458 flags |= eTraversalNeeded;
1463 setTransactionFlags(flags);
1468 void SurfaceFlinger::screenReleased(int dpy)
1470 // this may be called by a signal handler, we can't do too much in here
1471 android_atomic_or(eConsoleReleased, &mConsoleSignals);
1475 void SurfaceFlinger::screenAcquired(int dpy)
1477 // this may be called by a signal handler, we can't do too much in here
1478 android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1482 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1484 const size_t SIZE = 4096;
1487 if (!mDump.checkCalling()) {
1488 snprintf(buffer, SIZE, "Permission Denial: "
1489 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1490 IPCThreadState::self()->getCallingPid(),
1491 IPCThreadState::self()->getCallingUid());
1492 result.append(buffer);
1495 // figure out if we're stuck somewhere
1496 const nsecs_t now = systemTime();
1497 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
1498 const nsecs_t inTransaction(mDebugInTransaction);
1499 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
1500 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
1502 // Try to get the main lock, but don't insist if we can't
1503 // (this would indicate SF is stuck, but we want to be able to
1504 // print something in dumpsys).
1506 while (mStateLock.tryLock()<0 && --retry>=0) {
1509 const bool locked(retry >= 0);
1511 snprintf(buffer, SIZE,
1512 "SurfaceFlinger appears to be unresponsive, "
1513 "dumping anyways (no locks held)\n");
1514 result.append(buffer);
1518 * Dump the visible layer list
1520 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1521 const size_t count = currentLayers.size();
1522 snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count);
1523 result.append(buffer);
1524 for (size_t i=0 ; i<count ; i++) {
1525 const sp<LayerBase>& layer(currentLayers[i]);
1526 layer->dump(result, buffer, SIZE);
1527 const Layer::State& s(layer->drawingState());
1528 s.transparentRegion.dump(result, "transparentRegion");
1529 layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1530 layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1534 * Dump the layers in the purgatory
1537 const size_t purgatorySize = mLayerPurgatory.size();
1538 snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize);
1539 result.append(buffer);
1540 for (size_t i=0 ; i<purgatorySize ; i++) {
1541 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
1542 layer->shortDump(result, buffer, SIZE);
1546 * Dump SurfaceFlinger global state
1549 snprintf(buffer, SIZE, "SurfaceFlinger global state\n");
1550 result.append(buffer);
1551 mWormholeRegion.dump(result, "WormholeRegion");
1552 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1553 snprintf(buffer, SIZE,
1554 " display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
1555 mFreezeDisplay?"yes":"no", mFreezeCount,
1556 mCurrentState.orientation, hw.canDraw());
1557 result.append(buffer);
1558 snprintf(buffer, SIZE,
1559 " last eglSwapBuffers() time: %f us\n"
1560 " last transaction time : %f us\n",
1561 mLastSwapBufferTime/1000.0, mLastTransactionTime/1000.0);
1562 result.append(buffer);
1564 if (inSwapBuffersDuration || !locked) {
1565 snprintf(buffer, SIZE, " eglSwapBuffers time: %f us\n",
1566 inSwapBuffersDuration/1000.0);
1567 result.append(buffer);
1570 if (inTransactionDuration || !locked) {
1571 snprintf(buffer, SIZE, " transaction time: %f us\n",
1572 inTransactionDuration/1000.0);
1573 result.append(buffer);
1577 * Dump HWComposer state
1579 HWComposer& hwc(hw.getHwComposer());
1580 snprintf(buffer, SIZE, " h/w composer %s and %s\n",
1581 hwc.initCheck()==NO_ERROR ? "present" : "not present",
1582 mDebugDisableHWC ? "disabled" : "enabled");
1583 result.append(buffer);
1584 hwc.dump(result, buffer, SIZE);
1587 * Dump gralloc state
1589 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
1594 mStateLock.unlock();
1597 write(fd, result.string(), result.size());
1601 status_t SurfaceFlinger::onTransact(
1602 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1605 case CREATE_CONNECTION:
1606 case OPEN_GLOBAL_TRANSACTION:
1607 case CLOSE_GLOBAL_TRANSACTION:
1608 case SET_ORIENTATION:
1609 case FREEZE_DISPLAY:
1610 case UNFREEZE_DISPLAY:
1612 case TURN_ELECTRON_BEAM_OFF:
1613 case TURN_ELECTRON_BEAM_ON:
1615 // codes that require permission check
1616 IPCThreadState* ipc = IPCThreadState::self();
1617 const int pid = ipc->getCallingPid();
1618 const int uid = ipc->getCallingUid();
1619 if ((uid != AID_GRAPHICS) && !mAccessSurfaceFlinger.check(pid, uid)) {
1620 LOGE("Permission Denial: "
1621 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1622 return PERMISSION_DENIED;
1626 case CAPTURE_SCREEN:
1628 // codes that require permission check
1629 IPCThreadState* ipc = IPCThreadState::self();
1630 const int pid = ipc->getCallingPid();
1631 const int uid = ipc->getCallingUid();
1632 if ((uid != AID_GRAPHICS) && !mReadFramebuffer.check(pid, uid)) {
1633 LOGE("Permission Denial: "
1634 "can't read framebuffer pid=%d, uid=%d", pid, uid);
1635 return PERMISSION_DENIED;
1641 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1642 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
1643 CHECK_INTERFACE(ISurfaceComposer, data, reply);
1644 if (UNLIKELY(!mHardwareTest.checkCalling())) {
1645 IPCThreadState* ipc = IPCThreadState::self();
1646 const int pid = ipc->getCallingPid();
1647 const int uid = ipc->getCallingUid();
1648 LOGE("Permission Denial: "
1649 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1650 return PERMISSION_DENIED;
1654 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
1655 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
1657 case 1002: // SHOW_UPDATES
1658 n = data.readInt32();
1659 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1661 case 1003: // SHOW_BACKGROUND
1662 n = data.readInt32();
1663 mDebugBackground = n ? 1 : 0;
1665 case 1008: // toggle use of hw composer
1666 n = data.readInt32();
1667 mDebugDisableHWC = n ? 1 : 0;
1668 invalidateHwcGeometry();
1670 case 1004:{ // repaint everything
1671 Mutex::Autolock _l(mStateLock);
1672 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1673 mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe
1677 case 1005:{ // force transaction
1678 setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1681 case 1006:{ // enable/disable GraphicLog
1682 int enabled = data.readInt32();
1683 GraphicLog::getInstance().setEnabled(enabled);
1686 case 1007: // set mFreezeCount
1687 mFreezeCount = data.readInt32();
1688 mFreezeDisplayTime = 0;
1690 case 1010: // interrogate.
1691 reply->writeInt32(0);
1692 reply->writeInt32(0);
1693 reply->writeInt32(mDebugRegion);
1694 reply->writeInt32(mDebugBackground);
1697 Mutex::Autolock _l(mStateLock);
1698 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1699 reply->writeInt32(hw.getPageFlipCount());
1707 // ---------------------------------------------------------------------------
1709 status_t SurfaceFlinger::renderScreenToTextureLocked(DisplayID dpy,
1710 GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
1712 if (!GLExtensions::getInstance().haveFramebufferObject())
1713 return INVALID_OPERATION;
1715 // get screen geometry
1716 const DisplayHardware& hw(graphicPlane(dpy).displayHardware());
1717 const uint32_t hw_w = hw.getWidth();
1718 const uint32_t hw_h = hw.getHeight();
1722 // make sure to clear all GL error flags
1723 while ( glGetError() != GL_NO_ERROR ) ;
1727 glGenTextures(1, &tname);
1728 glBindTexture(GL_TEXTURE_2D, tname);
1729 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
1730 hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
1731 if (glGetError() != GL_NO_ERROR) {
1732 while ( glGetError() != GL_NO_ERROR ) ;
1733 GLint tw = (2 << (31 - clz(hw_w)));
1734 GLint th = (2 << (31 - clz(hw_h)));
1735 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
1736 tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
1737 u = GLfloat(hw_w) / tw;
1738 v = GLfloat(hw_h) / th;
1740 glGenFramebuffersOES(1, &name);
1741 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
1742 glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES,
1743 GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0);
1745 // redraw the screen entirely...
1746 glClearColor(0,0,0,1);
1747 glClear(GL_COLOR_BUFFER_BIT);
1748 const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
1749 const size_t count = layers.size();
1750 for (size_t i=0 ; i<count ; ++i) {
1751 const sp<LayerBase>& layer(layers[i]);
1752 layer->drawForSreenShot();
1755 // back to main framebuffer
1756 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
1757 glDisable(GL_SCISSOR_TEST);
1758 glDeleteFramebuffersOES(1, &name);
1760 *textureName = tname;
1766 // ---------------------------------------------------------------------------
1768 status_t SurfaceFlinger::electronBeamOffAnimationImplLocked()
1770 status_t result = PERMISSION_DENIED;
1772 if (!GLExtensions::getInstance().haveFramebufferObject())
1773 return INVALID_OPERATION;
1775 // get screen geometry
1776 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1777 const uint32_t hw_w = hw.getWidth();
1778 const uint32_t hw_h = hw.getHeight();
1779 const Region screenBounds(hw.bounds());
1783 result = renderScreenToTextureLocked(0, &tname, &u, &v);
1784 if (result != NO_ERROR) {
1789 const GLfloat texCoords[4][2] = { {0,v}, {0,0}, {u,0}, {u,v} };
1790 glEnable(GL_TEXTURE_2D);
1791 glBindTexture(GL_TEXTURE_2D, tname);
1792 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1793 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1794 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1795 glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
1796 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1797 glVertexPointer(2, GL_FLOAT, 0, vtx);
1799 class s_curve_interpolator {
1800 const float nbFrames, s, v;
1802 s_curve_interpolator(int nbFrames, float s)
1803 : nbFrames(1.0f / (nbFrames-1)), s(s),
1804 v(1.0f + expf(-s + 0.5f*s)) {
1806 float operator()(int f) {
1807 const float x = f * nbFrames;
1808 return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f;
1813 const GLfloat hw_w, hw_h;
1815 v_stretch(uint32_t hw_w, uint32_t hw_h)
1816 : hw_w(hw_w), hw_h(hw_h) {
1818 void operator()(GLfloat* vtx, float v) {
1819 const GLfloat w = hw_w + (hw_w * v);
1820 const GLfloat h = hw_h - (hw_h * v);
1821 const GLfloat x = (hw_w - w) * 0.5f;
1822 const GLfloat y = (hw_h - h) * 0.5f;
1823 vtx[0] = x; vtx[1] = y;
1824 vtx[2] = x; vtx[3] = y + h;
1825 vtx[4] = x + w; vtx[5] = y + h;
1826 vtx[6] = x + w; vtx[7] = y;
1831 const GLfloat hw_w, hw_h;
1833 h_stretch(uint32_t hw_w, uint32_t hw_h)
1834 : hw_w(hw_w), hw_h(hw_h) {
1836 void operator()(GLfloat* vtx, float v) {
1837 const GLfloat w = hw_w - (hw_w * v);
1838 const GLfloat h = 1.0f;
1839 const GLfloat x = (hw_w - w) * 0.5f;
1840 const GLfloat y = (hw_h - h) * 0.5f;
1841 vtx[0] = x; vtx[1] = y;
1842 vtx[2] = x; vtx[3] = y + h;
1843 vtx[4] = x + w; vtx[5] = y + h;
1844 vtx[6] = x + w; vtx[7] = y;
1848 // the full animation is 24 frames
1849 const int nbFrames = 12;
1850 s_curve_interpolator itr(nbFrames, 7.5f);
1851 s_curve_interpolator itg(nbFrames, 8.0f);
1852 s_curve_interpolator itb(nbFrames, 8.5f);
1854 v_stretch vverts(hw_w, hw_h);
1856 glBlendFunc(GL_ONE, GL_ONE);
1857 for (int i=0 ; i<nbFrames ; i++) {
1859 const float vr = itr(i);
1860 const float vg = itg(i);
1861 const float vb = itb(i);
1864 glColorMask(1,1,1,1);
1865 glClear(GL_COLOR_BUFFER_BIT);
1866 glEnable(GL_TEXTURE_2D);
1868 // draw the red plane
1870 glColorMask(1,0,0,1);
1871 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1873 // draw the green plane
1875 glColorMask(0,1,0,1);
1876 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1878 // draw the blue plane
1880 glColorMask(0,0,1,1);
1881 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1883 // draw the white highlight (we use the last vertices)
1884 glDisable(GL_TEXTURE_2D);
1885 glColorMask(1,1,1,1);
1886 glColor4f(vg, vg, vg, 1);
1887 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1888 hw.flip(screenBounds);
1891 h_stretch hverts(hw_w, hw_h);
1892 glDisable(GL_BLEND);
1893 glDisable(GL_TEXTURE_2D);
1894 glColorMask(1,1,1,1);
1895 for (int i=0 ; i<nbFrames ; i++) {
1896 const float v = itg(i);
1898 glClear(GL_COLOR_BUFFER_BIT);
1899 glColor4f(1-v, 1-v, 1-v, 1);
1900 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1901 hw.flip(screenBounds);
1904 glColorMask(1,1,1,1);
1905 glEnable(GL_SCISSOR_TEST);
1906 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1907 glDeleteTextures(1, &tname);
1911 status_t SurfaceFlinger::electronBeamOnAnimationImplLocked()
1913 status_t result = PERMISSION_DENIED;
1915 if (!GLExtensions::getInstance().haveFramebufferObject())
1916 return INVALID_OPERATION;
1919 // get screen geometry
1920 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1921 const uint32_t hw_w = hw.getWidth();
1922 const uint32_t hw_h = hw.getHeight();
1923 const Region screenBounds(hw.bounds());
1927 result = renderScreenToTextureLocked(0, &tname, &u, &v);
1928 if (result != NO_ERROR) {
1932 // back to main framebuffer
1933 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
1934 glDisable(GL_SCISSOR_TEST);
1937 const GLfloat texCoords[4][2] = { {0,v}, {0,0}, {u,0}, {u,v} };
1938 glEnable(GL_TEXTURE_2D);
1939 glBindTexture(GL_TEXTURE_2D, tname);
1940 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
1941 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1942 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1943 glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
1944 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1945 glVertexPointer(2, GL_FLOAT, 0, vtx);
1947 class s_curve_interpolator {
1948 const float nbFrames, s, v;
1950 s_curve_interpolator(int nbFrames, float s)
1951 : nbFrames(1.0f / (nbFrames-1)), s(s),
1952 v(1.0f + expf(-s + 0.5f*s)) {
1954 float operator()(int f) {
1955 const float x = f * nbFrames;
1956 return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f;
1961 const GLfloat hw_w, hw_h;
1963 v_stretch(uint32_t hw_w, uint32_t hw_h)
1964 : hw_w(hw_w), hw_h(hw_h) {
1966 void operator()(GLfloat* vtx, float v) {
1967 const GLfloat w = hw_w + (hw_w * v);
1968 const GLfloat h = hw_h - (hw_h * v);
1969 const GLfloat x = (hw_w - w) * 0.5f;
1970 const GLfloat y = (hw_h - h) * 0.5f;
1971 vtx[0] = x; vtx[1] = y;
1972 vtx[2] = x; vtx[3] = y + h;
1973 vtx[4] = x + w; vtx[5] = y + h;
1974 vtx[6] = x + w; vtx[7] = y;
1979 const GLfloat hw_w, hw_h;
1981 h_stretch(uint32_t hw_w, uint32_t hw_h)
1982 : hw_w(hw_w), hw_h(hw_h) {
1984 void operator()(GLfloat* vtx, float v) {
1985 const GLfloat w = hw_w - (hw_w * v);
1986 const GLfloat h = 1.0f;
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;
1996 // the full animation is 12 frames
1998 s_curve_interpolator itr(nbFrames, 7.5f);
1999 s_curve_interpolator itg(nbFrames, 8.0f);
2000 s_curve_interpolator itb(nbFrames, 8.5f);
2002 h_stretch hverts(hw_w, hw_h);
2003 glDisable(GL_BLEND);
2004 glDisable(GL_TEXTURE_2D);
2005 glColorMask(1,1,1,1);
2006 for (int i=nbFrames-1 ; i>=0 ; i--) {
2007 const float v = itg(i);
2009 glClear(GL_COLOR_BUFFER_BIT);
2010 glColor4f(1-v, 1-v, 1-v, 1);
2011 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2012 hw.flip(screenBounds);
2016 v_stretch vverts(hw_w, hw_h);
2018 glBlendFunc(GL_ONE, GL_ONE);
2019 for (int i=nbFrames-1 ; i>=0 ; i--) {
2021 const float vr = itr(i);
2022 const float vg = itg(i);
2023 const float vb = itb(i);
2026 glColorMask(1,1,1,1);
2027 glClear(GL_COLOR_BUFFER_BIT);
2028 glEnable(GL_TEXTURE_2D);
2030 // draw the red plane
2032 glColorMask(1,0,0,1);
2033 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2035 // draw the green plane
2037 glColorMask(0,1,0,1);
2038 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2040 // draw the blue plane
2042 glColorMask(0,0,1,1);
2043 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2045 hw.flip(screenBounds);
2048 glColorMask(1,1,1,1);
2049 glEnable(GL_SCISSOR_TEST);
2050 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
2051 glDeleteTextures(1, &tname);
2056 // ---------------------------------------------------------------------------
2058 status_t SurfaceFlinger::turnElectronBeamOffImplLocked(int32_t mode)
2060 DisplayHardware& hw(graphicPlane(0).editDisplayHardware());
2061 if (!hw.canDraw()) {
2062 // we're already off
2065 if (mode & ISurfaceComposer::eElectronBeamAnimationOff) {
2066 electronBeamOffAnimationImplLocked();
2069 // always clear the whole screen at the end of the animation
2070 glClearColor(0,0,0,1);
2071 glDisable(GL_SCISSOR_TEST);
2072 glClear(GL_COLOR_BUFFER_BIT);
2073 glEnable(GL_SCISSOR_TEST);
2074 hw.flip( Region(hw.bounds()) );
2076 hw.setCanDraw(false);
2080 status_t SurfaceFlinger::turnElectronBeamOff(int32_t mode)
2082 class MessageTurnElectronBeamOff : public MessageBase {
2083 SurfaceFlinger* flinger;
2087 MessageTurnElectronBeamOff(SurfaceFlinger* flinger, int32_t mode)
2088 : flinger(flinger), mode(mode), result(PERMISSION_DENIED) {
2090 status_t getResult() const {
2093 virtual bool handler() {
2094 Mutex::Autolock _l(flinger->mStateLock);
2095 result = flinger->turnElectronBeamOffImplLocked(mode);
2100 sp<MessageBase> msg = new MessageTurnElectronBeamOff(this, mode);
2101 status_t res = postMessageSync(msg);
2102 if (res == NO_ERROR) {
2103 res = static_cast<MessageTurnElectronBeamOff*>( msg.get() )->getResult();
2105 // work-around: when the power-manager calls us we activate the
2106 // animation. eventually, the "on" animation will be called
2107 // by the power-manager itself
2108 mElectronBeamAnimationMode = mode;
2113 // ---------------------------------------------------------------------------
2115 status_t SurfaceFlinger::turnElectronBeamOnImplLocked(int32_t mode)
2117 DisplayHardware& hw(graphicPlane(0).editDisplayHardware());
2122 if (mode & ISurfaceComposer::eElectronBeamAnimationOn) {
2123 electronBeamOnAnimationImplLocked();
2125 hw.setCanDraw(true);
2127 // make sure to redraw the whole screen when the animation is done
2128 mDirtyRegion.set(hw.bounds());
2134 status_t SurfaceFlinger::turnElectronBeamOn(int32_t mode)
2136 class MessageTurnElectronBeamOn : public MessageBase {
2137 SurfaceFlinger* flinger;
2141 MessageTurnElectronBeamOn(SurfaceFlinger* flinger, int32_t mode)
2142 : flinger(flinger), mode(mode), result(PERMISSION_DENIED) {
2144 status_t getResult() const {
2147 virtual bool handler() {
2148 Mutex::Autolock _l(flinger->mStateLock);
2149 result = flinger->turnElectronBeamOnImplLocked(mode);
2154 postMessageAsync( new MessageTurnElectronBeamOn(this, mode) );
2158 // ---------------------------------------------------------------------------
2160 status_t SurfaceFlinger::captureScreenImplLocked(DisplayID dpy,
2161 sp<IMemoryHeap>* heap,
2162 uint32_t* w, uint32_t* h, PixelFormat* f,
2163 uint32_t sw, uint32_t sh,
2164 uint32_t minLayerZ, uint32_t maxLayerZ)
2166 status_t result = PERMISSION_DENIED;
2168 // only one display supported for now
2169 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
2172 // make sure none of the layers are protected
2173 const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
2174 const size_t count = layers.size();
2175 for (size_t i=0 ; i<count ; ++i) {
2176 const sp<LayerBase>& layer(layers[i]);
2177 const uint32_t z = layer->drawingState().z;
2178 if (z >= minLayerZ && z <= maxLayerZ) {
2179 if (layer->isProtected()) {
2180 return INVALID_OPERATION;
2185 if (!GLExtensions::getInstance().haveFramebufferObject())
2186 return INVALID_OPERATION;
2188 // get screen geometry
2189 const DisplayHardware& hw(graphicPlane(dpy).displayHardware());
2190 const uint32_t hw_w = hw.getWidth();
2191 const uint32_t hw_h = hw.getHeight();
2193 if ((sw > hw_w) || (sh > hw_h))
2196 sw = (!sw) ? hw_w : sw;
2197 sh = (!sh) ? hw_h : sh;
2198 const size_t size = sw * sh * 4;
2200 //LOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d",
2201 // sw, sh, minLayerZ, maxLayerZ);
2203 // make sure to clear all GL error flags
2204 while ( glGetError() != GL_NO_ERROR ) ;
2208 glGenRenderbuffersOES(1, &tname);
2209 glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname);
2210 glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh);
2211 glGenFramebuffersOES(1, &name);
2212 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2213 glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
2214 GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname);
2216 GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
2218 if (status == GL_FRAMEBUFFER_COMPLETE_OES) {
2220 // invert everything, b/c glReadPixel() below will invert the FB
2221 glViewport(0, 0, sw, sh);
2222 glScissor(0, 0, sw, sh);
2223 glMatrixMode(GL_PROJECTION);
2226 glOrthof(0, hw_w, 0, hw_h, 0, 1);
2227 glMatrixMode(GL_MODELVIEW);
2229 // redraw the screen entirely...
2230 glClearColor(0,0,0,1);
2231 glClear(GL_COLOR_BUFFER_BIT);
2233 for (size_t i=0 ; i<count ; ++i) {
2234 const sp<LayerBase>& layer(layers[i]);
2235 const uint32_t z = layer->drawingState().z;
2236 if (z >= minLayerZ && z <= maxLayerZ) {
2237 layer->drawForSreenShot();
2241 // XXX: this is needed on tegra
2242 glScissor(0, 0, sw, sh);
2244 // check for errors and return screen capture
2245 if (glGetError() != GL_NO_ERROR) {
2246 // error while rendering
2247 result = INVALID_OPERATION;
2249 // allocate shared memory large enough to hold the
2251 sp<MemoryHeapBase> base(
2252 new MemoryHeapBase(size, 0, "screen-capture") );
2253 void* const ptr = base->getBase();
2255 // capture the screen with glReadPixels()
2256 glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
2257 if (glGetError() == GL_NO_ERROR) {
2261 *f = PIXEL_FORMAT_RGBA_8888;
2268 glEnable(GL_SCISSOR_TEST);
2269 glViewport(0, 0, hw_w, hw_h);
2270 glMatrixMode(GL_PROJECTION);
2272 glMatrixMode(GL_MODELVIEW);
2277 // release FBO resources
2278 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2279 glDeleteRenderbuffersOES(1, &tname);
2280 glDeleteFramebuffersOES(1, &name);
2282 hw.compositionComplete();
2284 // LOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK");
2290 status_t SurfaceFlinger::captureScreen(DisplayID dpy,
2291 sp<IMemoryHeap>* heap,
2292 uint32_t* width, uint32_t* height, PixelFormat* format,
2293 uint32_t sw, uint32_t sh,
2294 uint32_t minLayerZ, uint32_t maxLayerZ)
2296 // only one display supported for now
2297 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
2300 if (!GLExtensions::getInstance().haveFramebufferObject())
2301 return INVALID_OPERATION;
2303 class MessageCaptureScreen : public MessageBase {
2304 SurfaceFlinger* flinger;
2306 sp<IMemoryHeap>* heap;
2316 MessageCaptureScreen(SurfaceFlinger* flinger, DisplayID dpy,
2317 sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f,
2318 uint32_t sw, uint32_t sh,
2319 uint32_t minLayerZ, uint32_t maxLayerZ)
2320 : flinger(flinger), dpy(dpy),
2321 heap(heap), w(w), h(h), f(f), sw(sw), sh(sh),
2322 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2323 result(PERMISSION_DENIED)
2326 status_t getResult() const {
2329 virtual bool handler() {
2330 Mutex::Autolock _l(flinger->mStateLock);
2332 // if we have secure windows, never allow the screen capture
2333 if (flinger->mSecureFrameBuffer)
2336 result = flinger->captureScreenImplLocked(dpy,
2337 heap, w, h, f, sw, sh, minLayerZ, maxLayerZ);
2343 sp<MessageBase> msg = new MessageCaptureScreen(this,
2344 dpy, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ);
2345 status_t res = postMessageSync(msg);
2346 if (res == NO_ERROR) {
2347 res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult();
2352 // ---------------------------------------------------------------------------
2354 sp<Layer> SurfaceFlinger::getLayer(const sp<ISurface>& sur) const
2357 Mutex::Autolock _l(mStateLock);
2358 result = mLayerMap.valueFor( sur->asBinder() ).promote();
2362 // ---------------------------------------------------------------------------
2364 Client::Client(const sp<SurfaceFlinger>& flinger)
2365 : mFlinger(flinger), mNameGenerator(1)
2371 const size_t count = mLayers.size();
2372 for (size_t i=0 ; i<count ; i++) {
2373 sp<LayerBaseClient> layer(mLayers.valueAt(i).promote());
2375 mFlinger->removeLayer(layer);
2380 status_t Client::initCheck() const {
2384 ssize_t Client::attachLayer(const sp<LayerBaseClient>& layer)
2386 int32_t name = android_atomic_inc(&mNameGenerator);
2387 mLayers.add(name, layer);
2391 void Client::detachLayer(const LayerBaseClient* layer)
2393 // we do a linear search here, because this doesn't happen often
2394 const size_t count = mLayers.size();
2395 for (size_t i=0 ; i<count ; i++) {
2396 if (mLayers.valueAt(i) == layer) {
2397 mLayers.removeItemsAt(i, 1);
2402 sp<LayerBaseClient> Client::getLayerUser(int32_t i) const {
2403 sp<LayerBaseClient> lbc;
2404 const wp<LayerBaseClient>& layer(mLayers.valueFor(i));
2406 lbc = layer.promote();
2407 LOGE_IF(lbc==0, "getLayerUser(name=%d) is dead", int(i));
2412 sp<IMemoryHeap> Client::getControlBlock() const {
2415 ssize_t Client::getTokenForSurface(const sp<ISurface>& sur) const {
2418 sp<ISurface> Client::createSurface(
2419 ISurfaceComposerClient::surface_data_t* params, int pid,
2420 const String8& name,
2421 DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
2424 return mFlinger->createSurface(this, pid, name, params,
2425 display, w, h, format, flags);
2427 status_t Client::destroySurface(SurfaceID sid) {
2428 return mFlinger->removeSurface(this, sid);
2430 status_t Client::setState(int32_t count, const layer_state_t* states) {
2431 return mFlinger->setClientState(this, count, states);
2434 // ---------------------------------------------------------------------------
2436 UserClient::UserClient(const sp<SurfaceFlinger>& flinger)
2437 : ctrlblk(0), mBitmap(0), mFlinger(flinger)
2439 const int pgsize = getpagesize();
2440 const int cblksize = ((sizeof(SharedClient)+(pgsize-1))&~(pgsize-1));
2442 mCblkHeap = new MemoryHeapBase(cblksize, 0,
2443 "SurfaceFlinger Client control-block");
2445 ctrlblk = static_cast<SharedClient *>(mCblkHeap->getBase());
2446 if (ctrlblk) { // construct the shared structure in-place.
2447 new(ctrlblk) SharedClient;
2451 UserClient::~UserClient()
2454 ctrlblk->~SharedClient(); // destroy our shared-structure.
2458 * When a UserClient dies, it's unclear what to do exactly.
2459 * We could go ahead and destroy all surfaces linked to that client
2460 * however, it wouldn't be fair to the main Client
2461 * (usually the the window-manager), which might want to re-target
2462 * the layer to another UserClient.
2463 * I think the best is to do nothing, or not much; in most cases the
2464 * WM itself will go ahead and clean things up when it detects a client of
2466 * The remaining question is what to display? currently we keep
2467 * just keep the current buffer.
2471 status_t UserClient::initCheck() const {
2472 return ctrlblk == 0 ? NO_INIT : NO_ERROR;
2475 void UserClient::detachLayer(const Layer* layer)
2477 int32_t name = layer->getToken();
2479 int32_t mask = 1LU<<name;
2480 if ((android_atomic_and(~mask, &mBitmap) & mask) == 0) {
2481 LOGW("token %d wasn't marked as used %08x", name, int(mBitmap));
2486 sp<IMemoryHeap> UserClient::getControlBlock() const {
2490 ssize_t UserClient::getTokenForSurface(const sp<ISurface>& sur) const
2492 int32_t name = NAME_NOT_FOUND;
2493 sp<Layer> layer(mFlinger->getLayer(sur));
2498 // if this layer already has a token, just return it
2499 name = layer->getToken();
2500 if ((name >= 0) && (layer->getClient() == this)) {
2506 int32_t mask = 1LU<<name;
2507 if ((android_atomic_or(mask, &mBitmap) & mask) == 0) {
2508 // we found and locked that name
2509 status_t err = layer->setToken(
2510 const_cast<UserClient*>(this), ctrlblk, name);
2511 if (err != NO_ERROR) {
2513 android_atomic_and(~mask, &mBitmap);
2518 if (++name >= SharedBufferStack::NUM_LAYERS_MAX)
2522 //LOGD("getTokenForSurface(%p) => %d (client=%p, bitmap=%08lx)",
2523 // sur->asBinder().get(), name, this, mBitmap);
2527 sp<ISurface> UserClient::createSurface(
2528 ISurfaceComposerClient::surface_data_t* params, int pid,
2529 const String8& name,
2530 DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
2534 status_t UserClient::destroySurface(SurfaceID sid) {
2535 return INVALID_OPERATION;
2537 status_t UserClient::setState(int32_t count, const layer_state_t* states) {
2538 return INVALID_OPERATION;
2541 // ---------------------------------------------------------------------------
2543 GraphicBufferAlloc::GraphicBufferAlloc() {}
2545 GraphicBufferAlloc::~GraphicBufferAlloc() {}
2547 sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h,
2548 PixelFormat format, uint32_t usage) {
2549 sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage));
2550 status_t err = graphicBuffer->initCheck();
2552 LOGE("createGraphicBuffer: init check failed: %d", err);
2554 } else if (graphicBuffer->handle == 0) {
2555 LOGE("createGraphicBuffer: unable to create GraphicBuffer");
2558 Mutex::Autolock _l(mLock);
2559 mBuffers.add(graphicBuffer);
2560 return graphicBuffer;
2563 void GraphicBufferAlloc::freeAllGraphicBuffersExcept(int bufIdx) {
2564 Mutex::Autolock _l(mLock);
2565 if (0 <= bufIdx && bufIdx < mBuffers.size()) {
2566 sp<GraphicBuffer> b(mBuffers[bufIdx]);
2574 // ---------------------------------------------------------------------------
2576 GraphicPlane::GraphicPlane()
2581 GraphicPlane::~GraphicPlane() {
2585 bool GraphicPlane::initialized() const {
2586 return mHw ? true : false;
2589 int GraphicPlane::getWidth() const {
2593 int GraphicPlane::getHeight() const {
2597 void GraphicPlane::setDisplayHardware(DisplayHardware *hw)
2601 // initialize the display orientation transform.
2602 // it's a constant that should come from the display driver.
2603 int displayOrientation = ISurfaceComposer::eOrientationDefault;
2604 char property[PROPERTY_VALUE_MAX];
2605 if (property_get("ro.sf.hwrotation", property, NULL) > 0) {
2606 //displayOrientation
2607 switch (atoi(property)) {
2609 displayOrientation = ISurfaceComposer::eOrientation90;
2612 displayOrientation = ISurfaceComposer::eOrientation270;
2617 const float w = hw->getWidth();
2618 const float h = hw->getHeight();
2619 GraphicPlane::orientationToTransfrom(displayOrientation, w, h,
2620 &mDisplayTransform);
2621 if (displayOrientation & ISurfaceComposer::eOrientationSwapMask) {
2629 setOrientation(ISurfaceComposer::eOrientationDefault);
2632 status_t GraphicPlane::orientationToTransfrom(
2633 int orientation, int w, int h, Transform* tr)
2636 switch (orientation) {
2637 case ISurfaceComposer::eOrientationDefault:
2638 flags = Transform::ROT_0;
2640 case ISurfaceComposer::eOrientation90:
2641 flags = Transform::ROT_90;
2643 case ISurfaceComposer::eOrientation180:
2644 flags = Transform::ROT_180;
2646 case ISurfaceComposer::eOrientation270:
2647 flags = Transform::ROT_270;
2652 tr->set(flags, w, h);
2656 status_t GraphicPlane::setOrientation(int orientation)
2658 // If the rotation can be handled in hardware, this is where
2659 // the magic should happen.
2661 const DisplayHardware& hw(displayHardware());
2662 const float w = mDisplayWidth;
2663 const float h = mDisplayHeight;
2667 Transform orientationTransform;
2668 GraphicPlane::orientationToTransfrom(orientation, w, h,
2669 &orientationTransform);
2670 if (orientation & ISurfaceComposer::eOrientationSwapMask) {
2675 mOrientation = orientation;
2676 mGlobalTransform = mDisplayTransform * orientationTransform;
2680 const DisplayHardware& GraphicPlane::displayHardware() const {
2684 DisplayHardware& GraphicPlane::editDisplayHardware() {
2688 const Transform& GraphicPlane::transform() const {
2689 return mGlobalTransform;
2692 EGLDisplay GraphicPlane::getEGLDisplay() const {
2693 return mHw->getEGLDisplay();
2696 // ---------------------------------------------------------------------------
2698 }; // namespace android