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>
35 #include <binder/PermissionCache.h>
37 #include <utils/String8.h>
38 #include <utils/String16.h>
39 #include <utils/StopWatch.h>
41 #include <ui/GraphicBufferAllocator.h>
42 #include <ui/GraphicLog.h>
43 #include <ui/PixelFormat.h>
45 #include <pixelflinger/pixelflinger.h>
49 #include "GLExtensions.h"
50 #include "DdmConnection.h"
53 #include "LayerScreenshot.h"
54 #include "SurfaceFlinger.h"
56 #include "DisplayHardware/DisplayHardware.h"
57 #include "DisplayHardware/HWComposer.h"
59 #include <private/surfaceflinger/SharedBufferStack.h>
61 /* ideally AID_GRAPHICS would be in a semi-public header
62 * or there would be a way to map a user/group name to its id
65 #define AID_GRAPHICS 1003
68 #define DISPLAY_COUNT 1
71 // ---------------------------------------------------------------------------
73 const String16 sHardwareTest("android.permission.HARDWARE_TEST");
74 const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
75 const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
76 const String16 sDump("android.permission.DUMP");
78 // ---------------------------------------------------------------------------
80 SurfaceFlinger::SurfaceFlinger()
81 : BnSurfaceComposer(), Thread(false),
83 mTransationPending(false),
84 mLayersRemoved(false),
85 mBootTime(systemTime()),
86 mVisibleRegionsDirty(false),
87 mHwWorkListDirty(false),
88 mElectronBeamAnimationMode(0),
93 mDebugDisableTransformHint(0),
94 mDebugInSwapBuffers(0),
95 mLastSwapBufferTime(0),
96 mDebugInTransaction(0),
97 mLastTransactionTime(0),
100 mSecureFrameBuffer(0)
105 void SurfaceFlinger::init()
107 LOGI("SurfaceFlinger is starting");
109 // debugging stuff...
110 char value[PROPERTY_VALUE_MAX];
112 property_get("debug.sf.showupdates", value, "0");
113 mDebugRegion = atoi(value);
115 property_get("debug.sf.showbackground", value, "0");
116 mDebugBackground = atoi(value);
118 property_get("debug.sf.ddms", value, "0");
119 mDebugDDMS = atoi(value);
121 DdmConnection::start(getServiceName());
124 LOGI_IF(mDebugRegion, "showupdates enabled");
125 LOGI_IF(mDebugBackground, "showbackground enabled");
126 LOGI_IF(mDebugDDMS, "DDMS debugging enabled");
129 SurfaceFlinger::~SurfaceFlinger()
131 glDeleteTextures(1, &mWormholeTexName);
134 sp<IMemoryHeap> SurfaceFlinger::getCblk() const
139 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
141 sp<ISurfaceComposerClient> bclient;
142 sp<Client> client(new Client(this));
143 status_t err = client->initCheck();
144 if (err == NO_ERROR) {
150 sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
152 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
156 const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const
158 LOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy);
159 const GraphicPlane& plane(mGraphicPlanes[dpy]);
163 GraphicPlane& SurfaceFlinger::graphicPlane(int dpy)
165 return const_cast<GraphicPlane&>(
166 const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy));
169 void SurfaceFlinger::bootFinished()
171 const nsecs_t now = systemTime();
172 const nsecs_t duration = now - mBootTime;
173 LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
174 mBootFinished = true;
176 // wait patiently for the window manager death
177 const String16 name("window");
178 sp<IBinder> window(defaultServiceManager()->getService(name));
180 window->linkToDeath(this);
183 // stop boot animation
184 property_set("ctl.stop", "bootanim");
187 void SurfaceFlinger::binderDied(const wp<IBinder>& who)
189 // the window manager died on us. prepare its eulogy.
191 // reset screen orientation
192 setOrientation(0, eOrientationDefault, 0);
194 // restart the boot-animation
195 property_set("ctl.start", "bootanim");
198 void SurfaceFlinger::onFirstRef()
200 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
202 // Wait for the main thread to be done with its initialization
203 mReadyToRunBarrier.wait();
206 static inline uint16_t pack565(int r, int g, int b) {
207 return (r<<11)|(g<<5)|b;
210 status_t SurfaceFlinger::readyToRun()
212 LOGI( "SurfaceFlinger's main thread ready to run. "
213 "Initializing graphics H/W...");
215 // we only support one display currently
219 // initialize the main display
220 GraphicPlane& plane(graphicPlane(dpy));
221 DisplayHardware* const hw = new DisplayHardware(this, dpy);
222 plane.setDisplayHardware(hw);
225 // create the shared control-block
226 mServerHeap = new MemoryHeapBase(4096,
227 MemoryHeapBase::READ_ONLY, "SurfaceFlinger read-only heap");
228 LOGE_IF(mServerHeap==0, "can't create shared memory dealer");
230 mServerCblk = static_cast<surface_flinger_cblk_t*>(mServerHeap->getBase());
231 LOGE_IF(mServerCblk==0, "can't get to shared control block's address");
233 new(mServerCblk) surface_flinger_cblk_t;
235 // initialize primary screen
236 // (other display should be initialized in the same manner, but
237 // asynchronously, as they could come and go. None of this is supported
239 const GraphicPlane& plane(graphicPlane(dpy));
240 const DisplayHardware& hw = plane.displayHardware();
241 const uint32_t w = hw.getWidth();
242 const uint32_t h = hw.getHeight();
243 const uint32_t f = hw.getFormat();
246 // initialize the shared control block
247 mServerCblk->connected |= 1<<dpy;
248 display_cblk_t* dcblk = mServerCblk->displays + dpy;
249 memset(dcblk, 0, sizeof(display_cblk_t));
250 dcblk->w = plane.getWidth();
251 dcblk->h = plane.getHeight();
253 dcblk->orientation = ISurfaceComposer::eOrientationDefault;
254 dcblk->xdpi = hw.getDpiX();
255 dcblk->ydpi = hw.getDpiY();
256 dcblk->fps = hw.getRefreshRate();
257 dcblk->density = hw.getDensity();
259 // Initialize OpenGL|ES
260 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
261 glPixelStorei(GL_PACK_ALIGNMENT, 4);
262 glEnableClientState(GL_VERTEX_ARRAY);
263 glEnable(GL_SCISSOR_TEST);
264 glShadeModel(GL_FLAT);
265 glDisable(GL_DITHER);
266 glDisable(GL_CULL_FACE);
268 const uint16_t g0 = pack565(0x0F,0x1F,0x0F);
269 const uint16_t g1 = pack565(0x17,0x2f,0x17);
270 const uint16_t wormholeTexData[4] = { g0, g1, g1, g0 };
271 glGenTextures(1, &mWormholeTexName);
272 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
273 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
274 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
275 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
276 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
277 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0,
278 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, wormholeTexData);
280 const uint16_t protTexData[] = { pack565(0x03, 0x03, 0x03) };
281 glGenTextures(1, &mProtectedTexName);
282 glBindTexture(GL_TEXTURE_2D, mProtectedTexName);
283 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
284 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
285 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
286 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
287 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0,
288 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, protTexData);
290 glViewport(0, 0, w, h);
291 glMatrixMode(GL_PROJECTION);
293 // put the origin in the left-bottom corner
294 glOrthof(0, w, 0, h, 0, 1); // l=0, r=w ; b=0, t=h
296 mReadyToRunBarrier.open();
299 * We're now ready to accept clients...
302 // start boot animation
303 property_set("ctl.start", "bootanim");
308 // ----------------------------------------------------------------------------
311 #pragma mark Events Handler
314 void SurfaceFlinger::waitForEvent()
317 nsecs_t timeout = -1;
318 sp<MessageBase> msg = mEventQueue.waitMessage(timeout);
321 case MessageQueue::INVALIDATE:
322 // invalidate message, just return to the main loop
329 void SurfaceFlinger::signalEvent() {
330 mEventQueue.invalidate();
333 bool SurfaceFlinger::authenticateSurfaceTexture(
334 const sp<ISurfaceTexture>& surfaceTexture) const {
335 Mutex::Autolock _l(mStateLock);
336 sp<IBinder> surfaceTextureBinder(surfaceTexture->asBinder());
338 // Check the visible layer list for the ISurface
339 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
340 size_t count = currentLayers.size();
341 for (size_t i=0 ; i<count ; i++) {
342 const sp<LayerBase>& layer(currentLayers[i]);
343 sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
345 wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
346 if (lbcBinder == surfaceTextureBinder) {
352 // Check the layers in the purgatory. This check is here so that if a
353 // SurfaceTexture gets destroyed before all the clients are done using it,
354 // the error will not be reported as "surface XYZ is not authenticated", but
355 // will instead fail later on when the client tries to use the surface,
356 // which should be reported as "surface XYZ returned an -ENODEV". The
357 // purgatorized layers are no less authentic than the visible ones, so this
358 // should not cause any harm.
359 size_t purgatorySize = mLayerPurgatory.size();
360 for (size_t i=0 ; i<purgatorySize ; i++) {
361 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
362 sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
364 wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
365 if (lbcBinder == surfaceTextureBinder) {
374 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
375 nsecs_t reltime, uint32_t flags)
377 return mEventQueue.postMessage(msg, reltime, flags);
380 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
381 nsecs_t reltime, uint32_t flags)
383 status_t res = mEventQueue.postMessage(msg, reltime, flags);
384 if (res == NO_ERROR) {
390 // ----------------------------------------------------------------------------
393 #pragma mark Main loop
396 bool SurfaceFlinger::threadLoop()
400 // check for transactions
401 if (UNLIKELY(mConsoleSignals)) {
402 handleConsoleEvents();
405 // if we're in a global transaction, don't do anything.
406 const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
407 uint32_t transactionFlags = peekTransactionFlags(mask);
408 if (UNLIKELY(transactionFlags)) {
409 handleTransaction(transactionFlags);
412 // post surfaces (if needed)
415 if (mDirtyRegion.isEmpty()) {
416 // nothing new to do.
420 if (UNLIKELY(mHwWorkListDirty)) {
421 // build the h/w work list
425 const DisplayHardware& hw(graphicPlane(0).displayHardware());
426 if (LIKELY(hw.canDraw())) {
427 // repaint the framebuffer (if needed)
429 const int index = hw.getCurrentBufferIndex();
430 GraphicLog& logger(GraphicLog::getInstance());
432 logger.log(GraphicLog::SF_REPAINT, index);
435 // inform the h/w that we're done compositing
436 logger.log(GraphicLog::SF_COMPOSITION_COMPLETE, index);
437 hw.compositionComplete();
439 logger.log(GraphicLog::SF_SWAP_BUFFERS, index);
442 logger.log(GraphicLog::SF_REPAINT_DONE, index);
444 // pretend we did the post
445 hw.compositionComplete();
446 usleep(16667); // 60 fps period
451 void SurfaceFlinger::postFramebuffer()
453 // this should never happen. we do the flip anyways so we don't
454 // risk to cause a deadlock with hwc
455 LOGW_IF(mSwapRegion.isEmpty(), "mSwapRegion is empty");
456 const DisplayHardware& hw(graphicPlane(0).displayHardware());
457 const nsecs_t now = systemTime();
458 mDebugInSwapBuffers = now;
459 hw.flip(mSwapRegion);
460 mLastSwapBufferTime = systemTime() - now;
461 mDebugInSwapBuffers = 0;
465 void SurfaceFlinger::handleConsoleEvents()
467 // something to do with the console
468 const DisplayHardware& hw = graphicPlane(0).displayHardware();
470 int what = android_atomic_and(0, &mConsoleSignals);
471 if (what & eConsoleAcquired) {
473 // this is a temporary work-around, eventually this should be called
474 // by the power-manager
475 SurfaceFlinger::turnElectronBeamOn(mElectronBeamAnimationMode);
478 if (what & eConsoleReleased) {
479 if (hw.isScreenAcquired()) {
484 mDirtyRegion.set(hw.bounds());
487 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
489 Mutex::Autolock _l(mStateLock);
490 const nsecs_t now = systemTime();
491 mDebugInTransaction = now;
493 // Here we're guaranteed that some transaction flags are set
494 // so we can call handleTransactionLocked() unconditionally.
495 // We call getTransactionFlags(), which will also clear the flags,
496 // with mStateLock held to guarantee that mCurrentState won't change
497 // until the transaction is committed.
499 const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
500 transactionFlags = getTransactionFlags(mask);
501 handleTransactionLocked(transactionFlags);
503 mLastTransactionTime = systemTime() - now;
504 mDebugInTransaction = 0;
505 invalidateHwcGeometry();
506 // here the transaction has been committed
509 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
511 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
512 const size_t count = currentLayers.size();
515 * Traversal of the children
516 * (perform the transaction for each of them if needed)
519 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
520 if (layersNeedTransaction) {
521 for (size_t i=0 ; i<count ; i++) {
522 const sp<LayerBase>& layer = currentLayers[i];
523 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
524 if (!trFlags) continue;
526 const uint32_t flags = layer->doTransaction(0);
527 if (flags & Layer::eVisibleRegion)
528 mVisibleRegionsDirty = true;
533 * Perform our own transaction if needed
536 if (transactionFlags & eTransactionNeeded) {
537 if (mCurrentState.orientation != mDrawingState.orientation) {
538 // the orientation has changed, recompute all visible regions
539 // and invalidate everything.
542 const int orientation = mCurrentState.orientation;
543 // Currently unused: const uint32_t flags = mCurrentState.orientationFlags;
544 GraphicPlane& plane(graphicPlane(dpy));
545 plane.setOrientation(orientation);
547 // update the shared control block
548 const DisplayHardware& hw(plane.displayHardware());
549 volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
550 dcblk->orientation = orientation;
551 dcblk->w = plane.getWidth();
552 dcblk->h = plane.getHeight();
554 mVisibleRegionsDirty = true;
555 mDirtyRegion.set(hw.bounds());
558 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
559 // layers have been added
560 mVisibleRegionsDirty = true;
563 // some layers might have been removed, so
564 // we need to update the regions they're exposing.
565 if (mLayersRemoved) {
566 mLayersRemoved = false;
567 mVisibleRegionsDirty = true;
568 const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
569 const size_t count = previousLayers.size();
570 for (size_t i=0 ; i<count ; i++) {
571 const sp<LayerBase>& layer(previousLayers[i]);
572 if (currentLayers.indexOf( layer ) < 0) {
573 // this layer is not visible anymore
574 mDirtyRegionRemovedLayer.orSelf(layer->visibleRegionScreen);
583 void SurfaceFlinger::computeVisibleRegions(
584 const LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
586 const GraphicPlane& plane(graphicPlane(0));
587 const Transform& planeTransform(plane.transform());
588 const DisplayHardware& hw(plane.displayHardware());
589 const Region screenRegion(hw.bounds());
591 Region aboveOpaqueLayers;
592 Region aboveCoveredLayers;
595 bool secureFrameBuffer = false;
597 size_t i = currentLayers.size();
599 const sp<LayerBase>& layer = currentLayers[i];
600 layer->validateVisibility(planeTransform);
602 // start with the whole surface at its current location
603 const Layer::State& s(layer->drawingState());
606 * opaqueRegion: area of a surface that is fully opaque.
611 * visibleRegion: area of a surface that is visible on screen
612 * and not fully transparent. This is essentially the layer's
613 * footprint minus the opaque regions above it.
614 * Areas covered by a translucent surface are considered visible.
616 Region visibleRegion;
619 * coveredRegion: area of a surface that is covered by all
620 * visible regions above it (which includes the translucent areas).
622 Region coveredRegion;
625 // handle hidden surfaces by setting the visible region to empty
626 if (LIKELY(!(s.flags & ISurfaceComposer::eLayerHidden) && s.alpha)) {
627 const bool translucent = !layer->isOpaque();
628 const Rect bounds(layer->visibleBounds());
629 visibleRegion.set(bounds);
630 visibleRegion.andSelf(screenRegion);
631 if (!visibleRegion.isEmpty()) {
632 // Remove the transparent area from the visible region
634 visibleRegion.subtractSelf(layer->transparentRegionScreen);
637 // compute the opaque region
638 const int32_t layerOrientation = layer->getOrientation();
639 if (s.alpha==255 && !translucent &&
640 ((layerOrientation & Transform::ROT_INVALID) == false)) {
641 // the opaque region is the layer's footprint
642 opaqueRegion = visibleRegion;
647 // Clip the covered region to the visible region
648 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
650 // Update aboveCoveredLayers for next (lower) layer
651 aboveCoveredLayers.orSelf(visibleRegion);
653 // subtract the opaque region covered by the layers above us
654 visibleRegion.subtractSelf(aboveOpaqueLayers);
656 // compute this layer's dirty region
657 if (layer->contentDirty) {
658 // we need to invalidate the whole region
659 dirty = visibleRegion;
660 // as well, as the old visible region
661 dirty.orSelf(layer->visibleRegionScreen);
662 layer->contentDirty = false;
664 /* compute the exposed region:
665 * the exposed region consists of two components:
666 * 1) what's VISIBLE now and was COVERED before
667 * 2) what's EXPOSED now less what was EXPOSED before
669 * note that (1) is conservative, we start with the whole
670 * visible region but only keep what used to be covered by
671 * something -- which mean it may have been exposed.
673 * (2) handles areas that were not covered by anything but got
674 * exposed because of a resize.
676 const Region newExposed = visibleRegion - coveredRegion;
677 const Region oldVisibleRegion = layer->visibleRegionScreen;
678 const Region oldCoveredRegion = layer->coveredRegionScreen;
679 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
680 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
682 dirty.subtractSelf(aboveOpaqueLayers);
684 // accumulate to the screen dirty region
685 dirtyRegion.orSelf(dirty);
687 // Update aboveOpaqueLayers for next (lower) layer
688 aboveOpaqueLayers.orSelf(opaqueRegion);
690 // Store the visible region is screen space
691 layer->setVisibleRegion(visibleRegion);
692 layer->setCoveredRegion(coveredRegion);
694 // If a secure layer is partially visible, lock-down the screen!
695 if (layer->isSecure() && !visibleRegion.isEmpty()) {
696 secureFrameBuffer = true;
700 // invalidate the areas where a layer was removed
701 dirtyRegion.orSelf(mDirtyRegionRemovedLayer);
702 mDirtyRegionRemovedLayer.clear();
704 mSecureFrameBuffer = secureFrameBuffer;
705 opaqueRegion = aboveOpaqueLayers;
709 void SurfaceFlinger::commitTransaction()
711 mDrawingState = mCurrentState;
712 mTransationPending = false;
713 mTransactionCV.broadcast();
716 void SurfaceFlinger::handlePageFlip()
718 bool visibleRegions = mVisibleRegionsDirty;
719 const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
720 visibleRegions |= lockPageFlip(currentLayers);
722 const DisplayHardware& hw = graphicPlane(0).displayHardware();
723 const Region screenRegion(hw.bounds());
724 if (visibleRegions) {
726 computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
729 * rebuild the visible layer list
731 const size_t count = currentLayers.size();
732 mVisibleLayersSortedByZ.clear();
733 mVisibleLayersSortedByZ.setCapacity(count);
734 for (size_t i=0 ; i<count ; i++) {
735 if (!currentLayers[i]->visibleRegionScreen.isEmpty())
736 mVisibleLayersSortedByZ.add(currentLayers[i]);
739 mWormholeRegion = screenRegion.subtract(opaqueRegion);
740 mVisibleRegionsDirty = false;
741 invalidateHwcGeometry();
744 unlockPageFlip(currentLayers);
745 mDirtyRegion.andSelf(screenRegion);
748 void SurfaceFlinger::invalidateHwcGeometry()
750 mHwWorkListDirty = true;
753 bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
755 bool recomputeVisibleRegions = false;
756 size_t count = currentLayers.size();
757 sp<LayerBase> const* layers = currentLayers.array();
758 for (size_t i=0 ; i<count ; i++) {
759 const sp<LayerBase>& layer(layers[i]);
760 layer->lockPageFlip(recomputeVisibleRegions);
762 return recomputeVisibleRegions;
765 void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
767 const GraphicPlane& plane(graphicPlane(0));
768 const Transform& planeTransform(plane.transform());
769 size_t count = currentLayers.size();
770 sp<LayerBase> const* layers = currentLayers.array();
771 for (size_t i=0 ; i<count ; i++) {
772 const sp<LayerBase>& layer(layers[i]);
773 layer->unlockPageFlip(planeTransform, mDirtyRegion);
777 void SurfaceFlinger::handleWorkList()
779 mHwWorkListDirty = false;
780 HWComposer& hwc(graphicPlane(0).displayHardware().getHwComposer());
781 if (hwc.initCheck() == NO_ERROR) {
782 const Vector< sp<LayerBase> >& currentLayers(mVisibleLayersSortedByZ);
783 const size_t count = currentLayers.size();
784 hwc.createWorkList(count);
785 hwc_layer_t* const cur(hwc.getLayers());
786 for (size_t i=0 ; cur && i<count ; i++) {
787 currentLayers[i]->setGeometry(&cur[i]);
788 if (mDebugDisableHWC || mDebugRegion) {
789 cur[i].compositionType = HWC_FRAMEBUFFER;
790 cur[i].flags |= HWC_SKIP_LAYER;
796 void SurfaceFlinger::handleRepaint()
798 // compute the invalid region
799 mSwapRegion.orSelf(mDirtyRegion);
801 if (UNLIKELY(mDebugRegion)) {
805 // set the frame buffer
806 const DisplayHardware& hw(graphicPlane(0).displayHardware());
807 glMatrixMode(GL_MODELVIEW);
810 uint32_t flags = hw.getFlags();
811 if ((flags & DisplayHardware::SWAP_RECTANGLE) ||
812 (flags & DisplayHardware::BUFFER_PRESERVED))
814 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
815 // takes a rectangle, we must make sure to update that whole
816 // rectangle in that case
817 if (flags & DisplayHardware::SWAP_RECTANGLE) {
818 // TODO: we really should be able to pass a region to
819 // SWAP_RECTANGLE so that we don't have to redraw all this.
820 mDirtyRegion.set(mSwapRegion.bounds());
822 // in the BUFFER_PRESERVED case, obviously, we can update only
823 // what's needed and nothing more.
824 // NOTE: this is NOT a common case, as preserving the backbuffer
825 // is costly and usually involves copying the whole update back.
828 if (flags & DisplayHardware::PARTIAL_UPDATES) {
829 // We need to redraw the rectangle that will be updated
830 // (pushed to the framebuffer).
831 // This is needed because PARTIAL_UPDATES only takes one
832 // rectangle instead of a region (see DisplayHardware::flip())
833 mDirtyRegion.set(mSwapRegion.bounds());
835 // we need to redraw everything (the whole screen)
836 mDirtyRegion.set(hw.bounds());
837 mSwapRegion = mDirtyRegion;
841 setupHardwareComposer(mDirtyRegion);
842 composeSurfaces(mDirtyRegion);
844 // update the swap region and clear the dirty region
845 mSwapRegion.orSelf(mDirtyRegion);
846 mDirtyRegion.clear();
849 void SurfaceFlinger::setupHardwareComposer(Region& dirtyInOut)
851 const DisplayHardware& hw(graphicPlane(0).displayHardware());
852 HWComposer& hwc(hw.getHwComposer());
853 hwc_layer_t* const cur(hwc.getLayers());
858 const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
859 size_t count = layers.size();
861 LOGE_IF(hwc.getNumLayers() != count,
862 "HAL number of layers (%d) doesn't match surfaceflinger (%d)",
863 hwc.getNumLayers(), count);
865 // just to be extra-safe, use the smallest count
866 if (hwc.initCheck() == NO_ERROR) {
867 count = count < hwc.getNumLayers() ? count : hwc.getNumLayers();
871 * update the per-frame h/w composer data for each layer
872 * and build the transparent region of the FB
874 for (size_t i=0 ; i<count ; i++) {
875 const sp<LayerBase>& layer(layers[i]);
876 layer->setPerFrameData(&cur[i]);
878 const size_t fbLayerCount = hwc.getLayerCount(HWC_FRAMEBUFFER);
879 status_t err = hwc.prepare();
880 LOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
882 if (err == NO_ERROR) {
883 // what's happening here is tricky.
884 // we want to clear all the layers with the CLEAR_FB flags
886 // however, since some GPU are efficient at preserving
887 // the backbuffer, we want to take advantage of that so we do the
888 // clear only in the dirty region (other areas will be preserved
890 // NOTE: on non backbuffer preserving GPU, the dirty region
891 // has already been expanded as needed, so the code is correct
894 // However, the content of the framebuffer cannot be trusted when
895 // we switch to/from FB/OVERLAY, in which case we need to
896 // expand the dirty region to those areas too.
898 // Note also that there is a special case when switching from
899 // "no layers in FB" to "some layers in FB", where we need to redraw
900 // the entire FB, since some areas might contain uninitialized
903 // Also we want to make sure to not clear areas that belong to
904 // layers above that won't redraw (we would just be erasing them),
905 // that is, we can't erase anything outside the dirty region.
909 if (!fbLayerCount && hwc.getLayerCount(HWC_FRAMEBUFFER)) {
910 transparent.set(hw.getBounds());
911 dirtyInOut = transparent;
913 for (size_t i=0 ; i<count ; i++) {
914 const sp<LayerBase>& layer(layers[i]);
915 if ((cur[i].hints & HWC_HINT_CLEAR_FB) && layer->isOpaque()) {
916 transparent.orSelf(layer->visibleRegionScreen);
918 bool isOverlay = (cur[i].compositionType != HWC_FRAMEBUFFER);
919 if (isOverlay != layer->isOverlay()) {
920 // we transitioned to/from overlay, so add this layer
921 // to the dirty region so the framebuffer can be either
922 // cleared or redrawn.
923 dirtyInOut.orSelf(layer->visibleRegionScreen);
925 layer->setOverlay(isOverlay);
927 // don't erase stuff outside the dirty region
928 transparent.andSelf(dirtyInOut);
932 * clear the area of the FB that need to be transparent
934 if (!transparent.isEmpty()) {
935 glClearColor(0,0,0,0);
936 Region::const_iterator it = transparent.begin();
937 Region::const_iterator const end = transparent.end();
938 const int32_t height = hw.getHeight();
940 const Rect& r(*it++);
941 const GLint sy = height - (r.top + r.height());
942 glScissor(r.left, sy, r.width(), r.height());
943 glClear(GL_COLOR_BUFFER_BIT);
949 void SurfaceFlinger::composeSurfaces(const Region& dirty)
951 const DisplayHardware& hw(graphicPlane(0).displayHardware());
952 HWComposer& hwc(hw.getHwComposer());
954 const size_t fbLayerCount = hwc.getLayerCount(HWC_FRAMEBUFFER);
955 if (UNLIKELY(fbLayerCount && !mWormholeRegion.isEmpty())) {
956 // should never happen unless the window manager has a bug
962 * and then, render the layers targeted at the framebuffer
964 hwc_layer_t* const cur(hwc.getLayers());
965 const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
966 size_t count = layers.size();
967 for (size_t i=0 ; i<count ; i++) {
968 if (cur && (cur[i].compositionType != HWC_FRAMEBUFFER)) {
971 const sp<LayerBase>& layer(layers[i]);
972 const Region clip(dirty.intersect(layer->visibleRegionScreen));
973 if (!clip.isEmpty()) {
979 void SurfaceFlinger::debugFlashRegions()
981 const DisplayHardware& hw(graphicPlane(0).displayHardware());
982 const uint32_t flags = hw.getFlags();
983 const int32_t height = hw.getHeight();
984 if (mSwapRegion.isEmpty()) {
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);
995 glDisable(GL_TEXTURE_EXTERNAL_OES);
996 glDisable(GL_TEXTURE_2D);
998 glDisable(GL_SCISSOR_TEST);
1000 static int toggle = 0;
1001 toggle = 1 - toggle;
1003 glColor4f(1, 0, 1, 1);
1005 glColor4f(1, 1, 0, 1);
1008 Region::const_iterator it = mDirtyRegion.begin();
1009 Region::const_iterator const end = mDirtyRegion.end();
1011 const Rect& r = *it++;
1012 GLfloat vertices[][2] = {
1013 { r.left, height - r.top },
1014 { r.left, height - r.bottom },
1015 { r.right, height - r.bottom },
1016 { r.right, height - r.top }
1018 glVertexPointer(2, GL_FLOAT, 0, vertices);
1019 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1022 hw.flip(mSwapRegion);
1024 if (mDebugRegion > 1)
1025 usleep(mDebugRegion * 1000);
1027 glEnable(GL_SCISSOR_TEST);
1030 void SurfaceFlinger::drawWormhole() const
1032 const Region region(mWormholeRegion.intersect(mDirtyRegion));
1033 if (region.isEmpty())
1036 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1037 const int32_t width = hw.getWidth();
1038 const int32_t height = hw.getHeight();
1040 if (LIKELY(!mDebugBackground)) {
1041 glClearColor(0,0,0,0);
1042 Region::const_iterator it = region.begin();
1043 Region::const_iterator const end = region.end();
1045 const Rect& r = *it++;
1046 const GLint sy = height - (r.top + r.height());
1047 glScissor(r.left, sy, r.width(), r.height());
1048 glClear(GL_COLOR_BUFFER_BIT);
1051 const GLshort vertices[][2] = { { 0, 0 }, { width, 0 },
1052 { width, height }, { 0, height } };
1053 const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } };
1055 glVertexPointer(2, GL_SHORT, 0, vertices);
1056 glTexCoordPointer(2, GL_SHORT, 0, tcoords);
1057 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1059 glDisable(GL_TEXTURE_EXTERNAL_OES);
1060 glEnable(GL_TEXTURE_2D);
1061 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
1062 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1063 glMatrixMode(GL_TEXTURE);
1066 glDisable(GL_BLEND);
1068 glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
1069 Region::const_iterator it = region.begin();
1070 Region::const_iterator const end = region.end();
1072 const Rect& r = *it++;
1073 const GLint sy = height - (r.top + r.height());
1074 glScissor(r.left, sy, r.width(), r.height());
1075 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1077 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1078 glDisable(GL_TEXTURE_2D);
1080 glMatrixMode(GL_MODELVIEW);
1084 void SurfaceFlinger::debugShowFPS() const
1086 static int mFrameCount;
1087 static int mLastFrameCount = 0;
1088 static nsecs_t mLastFpsTime = 0;
1089 static float mFps = 0;
1091 nsecs_t now = systemTime();
1092 nsecs_t diff = now - mLastFpsTime;
1093 if (diff > ms2ns(250)) {
1094 mFps = ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
1096 mLastFrameCount = mFrameCount;
1098 // XXX: mFPS has the value we want
1101 status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
1103 Mutex::Autolock _l(mStateLock);
1105 setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1109 status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
1111 ssize_t i = mCurrentState.layersSortedByZ.add(layer);
1112 return (i < 0) ? status_t(i) : status_t(NO_ERROR);
1115 ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
1116 const sp<LayerBaseClient>& lbc)
1118 // attach this layer to the client
1119 size_t name = client->attachLayer(lbc);
1121 Mutex::Autolock _l(mStateLock);
1123 // add this layer to the current state list
1126 return ssize_t(name);
1129 status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
1131 Mutex::Autolock _l(mStateLock);
1132 status_t err = purgatorizeLayer_l(layer);
1133 if (err == NO_ERROR)
1134 setTransactionFlags(eTransactionNeeded);
1138 status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
1140 sp<LayerBaseClient> lbc(layerBase->getLayerBaseClient());
1142 mLayerMap.removeItem( lbc->getSurfaceBinder() );
1144 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1146 mLayersRemoved = true;
1149 return status_t(index);
1152 status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1154 // First add the layer to the purgatory list, which makes sure it won't
1155 // go away, then remove it from the main list (through a transaction).
1156 ssize_t err = removeLayer_l(layerBase);
1158 mLayerPurgatory.add(layerBase);
1161 layerBase->onRemoved();
1163 // it's possible that we don't find a layer, because it might
1164 // have been destroyed already -- this is not technically an error
1165 // from the user because there is a race between Client::destroySurface(),
1166 // ~Client() and ~ISurface().
1167 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1170 status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
1172 layer->forceVisibilityTransaction();
1173 setTransactionFlags(eTraversalNeeded);
1177 uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags)
1179 return android_atomic_release_load(&mTransactionFlags);
1182 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1184 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1187 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1189 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1190 if ((old & flags)==0) { // wake the server up
1197 void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& state,
1198 int orientation, uint32_t flags) {
1199 Mutex::Autolock _l(mStateLock);
1201 uint32_t transactionFlags = 0;
1202 if (mCurrentState.orientation != orientation) {
1203 if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
1204 mCurrentState.orientation = orientation;
1205 transactionFlags |= eTransactionNeeded;
1206 } else if (orientation != eOrientationUnchanged) {
1207 LOGW("setTransactionState: ignoring unrecognized orientation: %d",
1212 const size_t count = state.size();
1213 for (size_t i=0 ; i<count ; i++) {
1214 const ComposerState& s(state[i]);
1215 sp<Client> client( static_cast<Client *>(s.client.get()) );
1216 transactionFlags |= setClientStateLocked(client, s.state);
1218 if (transactionFlags) {
1219 setTransactionFlags(transactionFlags);
1222 // if this is a synchronous transaction, wait for it to take effect before
1224 if (flags & eSynchronous) {
1225 mTransationPending = true;
1227 while (mTransationPending) {
1228 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1229 if (CC_UNLIKELY(err != NO_ERROR)) {
1230 // just in case something goes wrong in SF, return to the
1231 // called after a few seconds.
1232 LOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!");
1233 mTransationPending = false;
1239 int SurfaceFlinger::setOrientation(DisplayID dpy,
1240 int orientation, uint32_t flags)
1242 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1245 Mutex::Autolock _l(mStateLock);
1246 if (mCurrentState.orientation != orientation) {
1247 if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
1248 mCurrentState.orientationFlags = flags;
1249 mCurrentState.orientation = orientation;
1250 setTransactionFlags(eTransactionNeeded);
1251 mTransactionCV.wait(mStateLock);
1253 orientation = BAD_VALUE;
1259 sp<ISurface> SurfaceFlinger::createSurface(
1260 ISurfaceComposerClient::surface_data_t* params,
1261 const String8& name,
1262 const sp<Client>& client,
1263 DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1266 sp<LayerBaseClient> layer;
1267 sp<ISurface> surfaceHandle;
1269 if (int32_t(w|h) < 0) {
1270 LOGE("createSurface() failed, w or h is negative (w=%d, h=%d)",
1272 return surfaceHandle;
1275 //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
1276 sp<Layer> normalLayer;
1277 switch (flags & eFXSurfaceMask) {
1278 case eFXSurfaceNormal:
1279 normalLayer = createNormalSurface(client, d, w, h, flags, format);
1280 layer = normalLayer;
1282 case eFXSurfaceBlur:
1283 // for now we treat Blur as Dim, until we can implement it
1286 layer = createDimSurface(client, d, w, h, flags);
1288 case eFXSurfaceScreenshot:
1289 layer = createScreenshotSurface(client, d, w, h, flags);
1294 layer->initStates(w, h, flags);
1295 layer->setName(name);
1296 ssize_t token = addClientLayer(client, layer);
1298 surfaceHandle = layer->getSurface();
1299 if (surfaceHandle != 0) {
1300 params->token = token;
1301 params->identity = layer->getIdentity();
1302 if (normalLayer != 0) {
1303 Mutex::Autolock _l(mStateLock);
1304 mLayerMap.add(layer->getSurfaceBinder(), normalLayer);
1308 setTransactionFlags(eTransactionNeeded);
1311 return surfaceHandle;
1314 sp<Layer> SurfaceFlinger::createNormalSurface(
1315 const sp<Client>& client, DisplayID display,
1316 uint32_t w, uint32_t h, uint32_t flags,
1317 PixelFormat& format)
1319 // initialize the surfaces
1320 switch (format) { // TODO: take h/w into account
1321 case PIXEL_FORMAT_TRANSPARENT:
1322 case PIXEL_FORMAT_TRANSLUCENT:
1323 format = PIXEL_FORMAT_RGBA_8888;
1325 case PIXEL_FORMAT_OPAQUE:
1327 format = PIXEL_FORMAT_RGB_565;
1329 format = PIXEL_FORMAT_RGBX_8888;
1335 if (format == PIXEL_FORMAT_RGBX_8888)
1336 format = PIXEL_FORMAT_RGBA_8888;
1339 sp<Layer> layer = new Layer(this, display, client);
1340 status_t err = layer->setBuffers(w, h, format, flags);
1341 if (LIKELY(err != NO_ERROR)) {
1342 LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
1348 sp<LayerDim> SurfaceFlinger::createDimSurface(
1349 const sp<Client>& client, DisplayID display,
1350 uint32_t w, uint32_t h, uint32_t flags)
1352 sp<LayerDim> layer = new LayerDim(this, display, client);
1356 sp<LayerScreenshot> SurfaceFlinger::createScreenshotSurface(
1357 const sp<Client>& client, DisplayID display,
1358 uint32_t w, uint32_t h, uint32_t flags)
1360 sp<LayerScreenshot> layer = new LayerScreenshot(this, display, client);
1361 status_t err = layer->capture();
1362 if (err != NO_ERROR) {
1364 LOGW("createScreenshotSurface failed (%s)", strerror(-err));
1369 status_t SurfaceFlinger::removeSurface(const sp<Client>& client, SurfaceID sid)
1372 * called by the window manager, when a surface should be marked for
1375 * The surface is removed from the current and drawing lists, but placed
1376 * in the purgatory queue, so it's not destroyed right-away (we need
1377 * to wait for all client's references to go away first).
1380 status_t err = NAME_NOT_FOUND;
1381 Mutex::Autolock _l(mStateLock);
1382 sp<LayerBaseClient> layer = client->getLayerUser(sid);
1384 err = purgatorizeLayer_l(layer);
1385 if (err == NO_ERROR) {
1386 setTransactionFlags(eTransactionNeeded);
1392 status_t SurfaceFlinger::destroySurface(const wp<LayerBaseClient>& layer)
1394 // called by ~ISurface() when all references are gone
1395 status_t err = NO_ERROR;
1396 sp<LayerBaseClient> l(layer.promote());
1398 Mutex::Autolock _l(mStateLock);
1399 err = removeLayer_l(l);
1400 if (err == NAME_NOT_FOUND) {
1401 // The surface wasn't in the current list, which means it was
1402 // removed already, which means it is in the purgatory,
1403 // and need to be removed from there.
1404 ssize_t idx = mLayerPurgatory.remove(l);
1406 "layer=%p is not in the purgatory list", l.get());
1408 LOGE_IF(err<0 && err != NAME_NOT_FOUND,
1409 "error removing layer=%p (%s)", l.get(), strerror(-err));
1414 uint32_t SurfaceFlinger::setClientStateLocked(
1415 const sp<Client>& client,
1416 const layer_state_t& s)
1419 sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
1421 const uint32_t what = s.what;
1422 if (what & ePositionChanged) {
1423 if (layer->setPosition(s.x, s.y))
1424 flags |= eTraversalNeeded;
1426 if (what & eLayerChanged) {
1427 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1428 if (layer->setLayer(s.z)) {
1429 mCurrentState.layersSortedByZ.removeAt(idx);
1430 mCurrentState.layersSortedByZ.add(layer);
1431 // we need traversal (state changed)
1432 // AND transaction (list changed)
1433 flags |= eTransactionNeeded|eTraversalNeeded;
1436 if (what & eSizeChanged) {
1437 if (layer->setSize(s.w, s.h)) {
1438 flags |= eTraversalNeeded;
1441 if (what & eAlphaChanged) {
1442 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1443 flags |= eTraversalNeeded;
1445 if (what & eMatrixChanged) {
1446 if (layer->setMatrix(s.matrix))
1447 flags |= eTraversalNeeded;
1449 if (what & eTransparentRegionChanged) {
1450 if (layer->setTransparentRegionHint(s.transparentRegion))
1451 flags |= eTraversalNeeded;
1453 if (what & eVisibilityChanged) {
1454 if (layer->setFlags(s.flags, s.mask))
1455 flags |= eTraversalNeeded;
1461 void SurfaceFlinger::screenReleased(int dpy)
1463 // this may be called by a signal handler, we can't do too much in here
1464 android_atomic_or(eConsoleReleased, &mConsoleSignals);
1468 void SurfaceFlinger::screenAcquired(int dpy)
1470 // this may be called by a signal handler, we can't do too much in here
1471 android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1475 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1477 const size_t SIZE = 4096;
1481 if (!PermissionCache::checkCallingPermission(sDump)) {
1482 snprintf(buffer, SIZE, "Permission Denial: "
1483 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1484 IPCThreadState::self()->getCallingPid(),
1485 IPCThreadState::self()->getCallingUid());
1486 result.append(buffer);
1489 // figure out if we're stuck somewhere
1490 const nsecs_t now = systemTime();
1491 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
1492 const nsecs_t inTransaction(mDebugInTransaction);
1493 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
1494 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
1496 // Try to get the main lock, but don't insist if we can't
1497 // (this would indicate SF is stuck, but we want to be able to
1498 // print something in dumpsys).
1500 while (mStateLock.tryLock()<0 && --retry>=0) {
1503 const bool locked(retry >= 0);
1505 snprintf(buffer, SIZE,
1506 "SurfaceFlinger appears to be unresponsive, "
1507 "dumping anyways (no locks held)\n");
1508 result.append(buffer);
1512 * Dump the visible layer list
1514 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1515 const size_t count = currentLayers.size();
1516 snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count);
1517 result.append(buffer);
1518 for (size_t i=0 ; i<count ; i++) {
1519 const sp<LayerBase>& layer(currentLayers[i]);
1520 layer->dump(result, buffer, SIZE);
1521 const Layer::State& s(layer->drawingState());
1522 s.transparentRegion.dump(result, "transparentRegion");
1523 layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1524 layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1528 * Dump the layers in the purgatory
1531 const size_t purgatorySize = mLayerPurgatory.size();
1532 snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize);
1533 result.append(buffer);
1534 for (size_t i=0 ; i<purgatorySize ; i++) {
1535 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
1536 layer->shortDump(result, buffer, SIZE);
1540 * Dump SurfaceFlinger global state
1543 snprintf(buffer, SIZE, "SurfaceFlinger global state:\n");
1544 result.append(buffer);
1546 const GLExtensions& extensions(GLExtensions::getInstance());
1547 snprintf(buffer, SIZE, "GLES: %s, %s, %s\n",
1548 extensions.getVendor(),
1549 extensions.getRenderer(),
1550 extensions.getVersion());
1551 result.append(buffer);
1552 snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension());
1553 result.append(buffer);
1555 mWormholeRegion.dump(result, "WormholeRegion");
1556 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1557 snprintf(buffer, SIZE,
1558 " orientation=%d, canDraw=%d\n",
1559 mCurrentState.orientation, hw.canDraw());
1560 result.append(buffer);
1561 snprintf(buffer, SIZE,
1562 " last eglSwapBuffers() time: %f us\n"
1563 " last transaction time : %f us\n",
1564 mLastSwapBufferTime/1000.0, mLastTransactionTime/1000.0);
1565 result.append(buffer);
1567 if (inSwapBuffersDuration || !locked) {
1568 snprintf(buffer, SIZE, " eglSwapBuffers time: %f us\n",
1569 inSwapBuffersDuration/1000.0);
1570 result.append(buffer);
1573 if (inTransactionDuration || !locked) {
1574 snprintf(buffer, SIZE, " transaction time: %f us\n",
1575 inTransactionDuration/1000.0);
1576 result.append(buffer);
1580 * Dump HWComposer state
1582 HWComposer& hwc(hw.getHwComposer());
1583 snprintf(buffer, SIZE, " h/w composer %s and %s\n",
1584 hwc.initCheck()==NO_ERROR ? "present" : "not present",
1585 (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled");
1586 result.append(buffer);
1587 hwc.dump(result, buffer, SIZE, mVisibleLayersSortedByZ);
1590 * Dump gralloc state
1592 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
1597 mStateLock.unlock();
1600 write(fd, result.string(), result.size());
1604 status_t SurfaceFlinger::onTransact(
1605 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1608 case CREATE_CONNECTION:
1609 case SET_TRANSACTION_STATE:
1610 case SET_ORIENTATION:
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) &&
1620 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
1621 LOGE("Permission Denial: "
1622 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1623 return PERMISSION_DENIED;
1627 case CAPTURE_SCREEN:
1629 // codes that require permission check
1630 IPCThreadState* ipc = IPCThreadState::self();
1631 const int pid = ipc->getCallingPid();
1632 const int uid = ipc->getCallingUid();
1633 if ((uid != AID_GRAPHICS) &&
1634 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
1635 LOGE("Permission Denial: "
1636 "can't read framebuffer pid=%d, uid=%d", pid, uid);
1637 return PERMISSION_DENIED;
1643 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1644 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
1645 CHECK_INTERFACE(ISurfaceComposer, data, reply);
1646 if (UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
1647 IPCThreadState* ipc = IPCThreadState::self();
1648 const int pid = ipc->getCallingPid();
1649 const int uid = ipc->getCallingUid();
1650 LOGE("Permission Denial: "
1651 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1652 return PERMISSION_DENIED;
1656 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
1657 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
1659 case 1002: // SHOW_UPDATES
1660 n = data.readInt32();
1661 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1662 invalidateHwcGeometry();
1663 repaintEverything();
1665 case 1003: // SHOW_BACKGROUND
1666 n = data.readInt32();
1667 mDebugBackground = n ? 1 : 0;
1669 case 1004:{ // repaint everything
1670 repaintEverything();
1673 case 1005:{ // force transaction
1674 setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1677 case 1006:{ // enable/disable GraphicLog
1678 int enabled = data.readInt32();
1679 GraphicLog::getInstance().setEnabled(enabled);
1682 case 1008: // toggle use of hw composer
1683 n = data.readInt32();
1684 mDebugDisableHWC = n ? 1 : 0;
1685 invalidateHwcGeometry();
1686 repaintEverything();
1688 case 1009: // toggle use of transform hint
1689 n = data.readInt32();
1690 mDebugDisableTransformHint = n ? 1 : 0;
1691 invalidateHwcGeometry();
1692 repaintEverything();
1694 case 1010: // interrogate.
1695 reply->writeInt32(0);
1696 reply->writeInt32(0);
1697 reply->writeInt32(mDebugRegion);
1698 reply->writeInt32(mDebugBackground);
1701 Mutex::Autolock _l(mStateLock);
1702 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1703 reply->writeInt32(hw.getPageFlipCount());
1711 void SurfaceFlinger::repaintEverything() {
1712 Mutex::Autolock _l(mStateLock);
1713 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1714 mDirtyRegion.set(hw.bounds());
1718 // ---------------------------------------------------------------------------
1720 status_t SurfaceFlinger::renderScreenToTexture(DisplayID dpy,
1721 GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
1723 Mutex::Autolock _l(mStateLock);
1724 return renderScreenToTextureLocked(dpy, textureName, uOut, vOut);
1727 status_t SurfaceFlinger::renderScreenToTextureLocked(DisplayID dpy,
1728 GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
1730 if (!GLExtensions::getInstance().haveFramebufferObject())
1731 return INVALID_OPERATION;
1733 // get screen geometry
1734 const DisplayHardware& hw(graphicPlane(dpy).displayHardware());
1735 const uint32_t hw_w = hw.getWidth();
1736 const uint32_t hw_h = hw.getHeight();
1740 // make sure to clear all GL error flags
1741 while ( glGetError() != GL_NO_ERROR ) ;
1745 glGenTextures(1, &tname);
1746 glBindTexture(GL_TEXTURE_2D, tname);
1747 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
1748 hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
1749 if (glGetError() != GL_NO_ERROR) {
1750 while ( glGetError() != GL_NO_ERROR ) ;
1751 GLint tw = (2 << (31 - clz(hw_w)));
1752 GLint th = (2 << (31 - clz(hw_h)));
1753 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
1754 tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
1755 u = GLfloat(hw_w) / tw;
1756 v = GLfloat(hw_h) / th;
1758 glGenFramebuffersOES(1, &name);
1759 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
1760 glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES,
1761 GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0);
1763 // redraw the screen entirely...
1764 glDisable(GL_TEXTURE_EXTERNAL_OES);
1765 glDisable(GL_TEXTURE_2D);
1766 glClearColor(0,0,0,1);
1767 glClear(GL_COLOR_BUFFER_BIT);
1768 glMatrixMode(GL_MODELVIEW);
1770 const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
1771 const size_t count = layers.size();
1772 for (size_t i=0 ; i<count ; ++i) {
1773 const sp<LayerBase>& layer(layers[i]);
1774 layer->drawForSreenShot();
1777 hw.compositionComplete();
1779 // back to main framebuffer
1780 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
1781 glDisable(GL_SCISSOR_TEST);
1782 glDeleteFramebuffersOES(1, &name);
1784 *textureName = tname;
1790 // ---------------------------------------------------------------------------
1792 status_t SurfaceFlinger::electronBeamOffAnimationImplLocked()
1794 // get screen geometry
1795 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1796 const uint32_t hw_w = hw.getWidth();
1797 const uint32_t hw_h = hw.getHeight();
1798 const Region screenBounds(hw.getBounds());
1802 status_t result = renderScreenToTextureLocked(0, &tname, &u, &v);
1803 if (result != NO_ERROR) {
1808 const GLfloat texCoords[4][2] = { {0,0}, {0,v}, {u,v}, {u,0} };
1809 glBindTexture(GL_TEXTURE_2D, tname);
1810 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1811 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1812 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1813 glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
1814 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1815 glVertexPointer(2, GL_FLOAT, 0, vtx);
1818 * Texture coordinate mapping
1821 * 1 +----------+---+
1822 * | | | | image is inverted
1823 * | V | | w.r.t. the texture
1824 * 1-v +----------+ | coordinates
1828 * 0 +--------------+
1833 class s_curve_interpolator {
1834 const float nbFrames, s, v;
1836 s_curve_interpolator(int nbFrames, float s)
1837 : nbFrames(1.0f / (nbFrames-1)), s(s),
1838 v(1.0f + expf(-s + 0.5f*s)) {
1840 float operator()(int f) {
1841 const float x = f * nbFrames;
1842 return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f;
1847 const GLfloat hw_w, hw_h;
1849 v_stretch(uint32_t hw_w, uint32_t hw_h)
1850 : hw_w(hw_w), hw_h(hw_h) {
1852 void operator()(GLfloat* vtx, float v) {
1853 const GLfloat w = hw_w + (hw_w * v);
1854 const GLfloat h = hw_h - (hw_h * v);
1855 const GLfloat x = (hw_w - w) * 0.5f;
1856 const GLfloat y = (hw_h - h) * 0.5f;
1857 vtx[0] = x; vtx[1] = y;
1858 vtx[2] = x; vtx[3] = y + h;
1859 vtx[4] = x + w; vtx[5] = y + h;
1860 vtx[6] = x + w; vtx[7] = y;
1865 const GLfloat hw_w, hw_h;
1867 h_stretch(uint32_t hw_w, uint32_t hw_h)
1868 : hw_w(hw_w), hw_h(hw_h) {
1870 void operator()(GLfloat* vtx, float v) {
1871 const GLfloat w = hw_w - (hw_w * v);
1872 const GLfloat h = 1.0f;
1873 const GLfloat x = (hw_w - w) * 0.5f;
1874 const GLfloat y = (hw_h - h) * 0.5f;
1875 vtx[0] = x; vtx[1] = y;
1876 vtx[2] = x; vtx[3] = y + h;
1877 vtx[4] = x + w; vtx[5] = y + h;
1878 vtx[6] = x + w; vtx[7] = y;
1882 // the full animation is 24 frames
1883 char value[PROPERTY_VALUE_MAX];
1884 property_get("debug.sf.electron_frames", value, "24");
1885 int nbFrames = (atoi(value) + 1) >> 1;
1886 if (nbFrames <= 0) // just in case
1889 s_curve_interpolator itr(nbFrames, 7.5f);
1890 s_curve_interpolator itg(nbFrames, 8.0f);
1891 s_curve_interpolator itb(nbFrames, 8.5f);
1893 v_stretch vverts(hw_w, hw_h);
1895 glMatrixMode(GL_TEXTURE);
1897 glMatrixMode(GL_MODELVIEW);
1901 glBlendFunc(GL_ONE, GL_ONE);
1902 for (int i=0 ; i<nbFrames ; i++) {
1904 const float vr = itr(i);
1905 const float vg = itg(i);
1906 const float vb = itb(i);
1909 glColorMask(1,1,1,1);
1910 glClear(GL_COLOR_BUFFER_BIT);
1911 glEnable(GL_TEXTURE_2D);
1913 // draw the red plane
1915 glColorMask(1,0,0,1);
1916 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1918 // draw the green plane
1920 glColorMask(0,1,0,1);
1921 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1923 // draw the blue plane
1925 glColorMask(0,0,1,1);
1926 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1928 // draw the white highlight (we use the last vertices)
1929 glDisable(GL_TEXTURE_2D);
1930 glColorMask(1,1,1,1);
1931 glColor4f(vg, vg, vg, 1);
1932 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1933 hw.flip(screenBounds);
1936 h_stretch hverts(hw_w, hw_h);
1937 glDisable(GL_BLEND);
1938 glDisable(GL_TEXTURE_2D);
1939 glColorMask(1,1,1,1);
1940 for (int i=0 ; i<nbFrames ; i++) {
1941 const float v = itg(i);
1943 glClear(GL_COLOR_BUFFER_BIT);
1944 glColor4f(1-v, 1-v, 1-v, 1);
1945 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1946 hw.flip(screenBounds);
1949 glColorMask(1,1,1,1);
1950 glEnable(GL_SCISSOR_TEST);
1951 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1952 glDeleteTextures(1, &tname);
1953 glDisable(GL_TEXTURE_2D);
1954 glDisable(GL_BLEND);
1958 status_t SurfaceFlinger::electronBeamOnAnimationImplLocked()
1960 status_t result = PERMISSION_DENIED;
1962 if (!GLExtensions::getInstance().haveFramebufferObject())
1963 return INVALID_OPERATION;
1966 // get screen geometry
1967 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1968 const uint32_t hw_w = hw.getWidth();
1969 const uint32_t hw_h = hw.getHeight();
1970 const Region screenBounds(hw.bounds());
1974 result = renderScreenToTextureLocked(0, &tname, &u, &v);
1975 if (result != NO_ERROR) {
1980 const GLfloat texCoords[4][2] = { {0,v}, {0,0}, {u,0}, {u,v} };
1981 glBindTexture(GL_TEXTURE_2D, tname);
1982 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
1983 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1984 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1985 glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
1986 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1987 glVertexPointer(2, GL_FLOAT, 0, vtx);
1989 class s_curve_interpolator {
1990 const float nbFrames, s, v;
1992 s_curve_interpolator(int nbFrames, float s)
1993 : nbFrames(1.0f / (nbFrames-1)), s(s),
1994 v(1.0f + expf(-s + 0.5f*s)) {
1996 float operator()(int f) {
1997 const float x = f * nbFrames;
1998 return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f;
2003 const GLfloat hw_w, hw_h;
2005 v_stretch(uint32_t hw_w, uint32_t hw_h)
2006 : hw_w(hw_w), hw_h(hw_h) {
2008 void operator()(GLfloat* vtx, float v) {
2009 const GLfloat w = hw_w + (hw_w * v);
2010 const GLfloat h = hw_h - (hw_h * v);
2011 const GLfloat x = (hw_w - w) * 0.5f;
2012 const GLfloat y = (hw_h - h) * 0.5f;
2013 vtx[0] = x; vtx[1] = y;
2014 vtx[2] = x; vtx[3] = y + h;
2015 vtx[4] = x + w; vtx[5] = y + h;
2016 vtx[6] = x + w; vtx[7] = y;
2021 const GLfloat hw_w, hw_h;
2023 h_stretch(uint32_t hw_w, uint32_t hw_h)
2024 : hw_w(hw_w), hw_h(hw_h) {
2026 void operator()(GLfloat* vtx, float v) {
2027 const GLfloat w = hw_w - (hw_w * v);
2028 const GLfloat h = 1.0f;
2029 const GLfloat x = (hw_w - w) * 0.5f;
2030 const GLfloat y = (hw_h - h) * 0.5f;
2031 vtx[0] = x; vtx[1] = y;
2032 vtx[2] = x; vtx[3] = y + h;
2033 vtx[4] = x + w; vtx[5] = y + h;
2034 vtx[6] = x + w; vtx[7] = y;
2038 // the full animation is 12 frames
2040 s_curve_interpolator itr(nbFrames, 7.5f);
2041 s_curve_interpolator itg(nbFrames, 8.0f);
2042 s_curve_interpolator itb(nbFrames, 8.5f);
2044 h_stretch hverts(hw_w, hw_h);
2045 glDisable(GL_BLEND);
2046 glDisable(GL_TEXTURE_2D);
2047 glColorMask(1,1,1,1);
2048 for (int i=nbFrames-1 ; i>=0 ; i--) {
2049 const float v = itg(i);
2051 glClear(GL_COLOR_BUFFER_BIT);
2052 glColor4f(1-v, 1-v, 1-v, 1);
2053 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2054 hw.flip(screenBounds);
2058 v_stretch vverts(hw_w, hw_h);
2060 glBlendFunc(GL_ONE, GL_ONE);
2061 for (int i=nbFrames-1 ; i>=0 ; i--) {
2063 const float vr = itr(i);
2064 const float vg = itg(i);
2065 const float vb = itb(i);
2068 glColorMask(1,1,1,1);
2069 glClear(GL_COLOR_BUFFER_BIT);
2070 glEnable(GL_TEXTURE_2D);
2072 // draw the red plane
2074 glColorMask(1,0,0,1);
2075 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2077 // draw the green plane
2079 glColorMask(0,1,0,1);
2080 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2082 // draw the blue plane
2084 glColorMask(0,0,1,1);
2085 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2087 hw.flip(screenBounds);
2090 glColorMask(1,1,1,1);
2091 glEnable(GL_SCISSOR_TEST);
2092 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
2093 glDeleteTextures(1, &tname);
2094 glDisable(GL_TEXTURE_2D);
2095 glDisable(GL_BLEND);
2100 // ---------------------------------------------------------------------------
2102 status_t SurfaceFlinger::turnElectronBeamOffImplLocked(int32_t mode)
2104 DisplayHardware& hw(graphicPlane(0).editDisplayHardware());
2105 if (!hw.canDraw()) {
2106 // we're already off
2110 // turn off hwc while we're doing the animation
2111 hw.getHwComposer().disable();
2112 // and make sure to turn it back on (if needed) next time we compose
2113 invalidateHwcGeometry();
2115 if (mode & ISurfaceComposer::eElectronBeamAnimationOff) {
2116 electronBeamOffAnimationImplLocked();
2119 // always clear the whole screen at the end of the animation
2120 glClearColor(0,0,0,1);
2121 glDisable(GL_SCISSOR_TEST);
2122 glClear(GL_COLOR_BUFFER_BIT);
2123 glEnable(GL_SCISSOR_TEST);
2124 hw.flip( Region(hw.bounds()) );
2129 status_t SurfaceFlinger::turnElectronBeamOff(int32_t mode)
2131 class MessageTurnElectronBeamOff : public MessageBase {
2132 SurfaceFlinger* flinger;
2136 MessageTurnElectronBeamOff(SurfaceFlinger* flinger, int32_t mode)
2137 : flinger(flinger), mode(mode), result(PERMISSION_DENIED) {
2139 status_t getResult() const {
2142 virtual bool handler() {
2143 Mutex::Autolock _l(flinger->mStateLock);
2144 result = flinger->turnElectronBeamOffImplLocked(mode);
2149 sp<MessageBase> msg = new MessageTurnElectronBeamOff(this, mode);
2150 status_t res = postMessageSync(msg);
2151 if (res == NO_ERROR) {
2152 res = static_cast<MessageTurnElectronBeamOff*>( msg.get() )->getResult();
2154 // work-around: when the power-manager calls us we activate the
2155 // animation. eventually, the "on" animation will be called
2156 // by the power-manager itself
2157 mElectronBeamAnimationMode = mode;
2162 // ---------------------------------------------------------------------------
2164 status_t SurfaceFlinger::turnElectronBeamOnImplLocked(int32_t mode)
2166 DisplayHardware& hw(graphicPlane(0).editDisplayHardware());
2171 if (mode & ISurfaceComposer::eElectronBeamAnimationOn) {
2172 electronBeamOnAnimationImplLocked();
2175 // make sure to redraw the whole screen when the animation is done
2176 mDirtyRegion.set(hw.bounds());
2182 status_t SurfaceFlinger::turnElectronBeamOn(int32_t mode)
2184 class MessageTurnElectronBeamOn : public MessageBase {
2185 SurfaceFlinger* flinger;
2189 MessageTurnElectronBeamOn(SurfaceFlinger* flinger, int32_t mode)
2190 : flinger(flinger), mode(mode), result(PERMISSION_DENIED) {
2192 status_t getResult() const {
2195 virtual bool handler() {
2196 Mutex::Autolock _l(flinger->mStateLock);
2197 result = flinger->turnElectronBeamOnImplLocked(mode);
2202 postMessageAsync( new MessageTurnElectronBeamOn(this, mode) );
2206 // ---------------------------------------------------------------------------
2208 status_t SurfaceFlinger::captureScreenImplLocked(DisplayID dpy,
2209 sp<IMemoryHeap>* heap,
2210 uint32_t* w, uint32_t* h, PixelFormat* f,
2211 uint32_t sw, uint32_t sh,
2212 uint32_t minLayerZ, uint32_t maxLayerZ)
2214 status_t result = PERMISSION_DENIED;
2216 // only one display supported for now
2217 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
2220 if (!GLExtensions::getInstance().haveFramebufferObject())
2221 return INVALID_OPERATION;
2223 // get screen geometry
2224 const DisplayHardware& hw(graphicPlane(dpy).displayHardware());
2225 const uint32_t hw_w = hw.getWidth();
2226 const uint32_t hw_h = hw.getHeight();
2228 if ((sw > hw_w) || (sh > hw_h))
2231 sw = (!sw) ? hw_w : sw;
2232 sh = (!sh) ? hw_h : sh;
2233 const size_t size = sw * sh * 4;
2235 //LOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d",
2236 // sw, sh, minLayerZ, maxLayerZ);
2238 // make sure to clear all GL error flags
2239 while ( glGetError() != GL_NO_ERROR ) ;
2243 glGenRenderbuffersOES(1, &tname);
2244 glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname);
2245 glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh);
2246 glGenFramebuffersOES(1, &name);
2247 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2248 glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
2249 GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname);
2251 GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
2253 if (status == GL_FRAMEBUFFER_COMPLETE_OES) {
2255 // invert everything, b/c glReadPixel() below will invert the FB
2256 glViewport(0, 0, sw, sh);
2257 glScissor(0, 0, sw, sh);
2258 glEnable(GL_SCISSOR_TEST);
2259 glMatrixMode(GL_PROJECTION);
2262 glOrthof(0, hw_w, hw_h, 0, 0, 1);
2263 glMatrixMode(GL_MODELVIEW);
2265 // redraw the screen entirely...
2266 glClearColor(0,0,0,1);
2267 glClear(GL_COLOR_BUFFER_BIT);
2269 const LayerVector& layers(mDrawingState.layersSortedByZ);
2270 const size_t count = layers.size();
2271 for (size_t i=0 ; i<count ; ++i) {
2272 const sp<LayerBase>& layer(layers[i]);
2273 const uint32_t flags = layer->drawingState().flags;
2274 if (!(flags & ISurfaceComposer::eLayerHidden)) {
2275 const uint32_t z = layer->drawingState().z;
2276 if (z >= minLayerZ && z <= maxLayerZ) {
2277 layer->drawForSreenShot();
2282 // XXX: this is needed on tegra
2283 glEnable(GL_SCISSOR_TEST);
2284 glScissor(0, 0, sw, sh);
2286 // check for errors and return screen capture
2287 if (glGetError() != GL_NO_ERROR) {
2288 // error while rendering
2289 result = INVALID_OPERATION;
2291 // allocate shared memory large enough to hold the
2293 sp<MemoryHeapBase> base(
2294 new MemoryHeapBase(size, 0, "screen-capture") );
2295 void* const ptr = base->getBase();
2297 // capture the screen with glReadPixels()
2298 glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
2299 if (glGetError() == GL_NO_ERROR) {
2303 *f = PIXEL_FORMAT_RGBA_8888;
2310 glEnable(GL_SCISSOR_TEST);
2311 glViewport(0, 0, hw_w, hw_h);
2312 glMatrixMode(GL_PROJECTION);
2314 glMatrixMode(GL_MODELVIEW);
2319 // release FBO resources
2320 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2321 glDeleteRenderbuffersOES(1, &tname);
2322 glDeleteFramebuffersOES(1, &name);
2324 hw.compositionComplete();
2326 // LOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK");
2332 status_t SurfaceFlinger::captureScreen(DisplayID dpy,
2333 sp<IMemoryHeap>* heap,
2334 uint32_t* width, uint32_t* height, PixelFormat* format,
2335 uint32_t sw, uint32_t sh,
2336 uint32_t minLayerZ, uint32_t maxLayerZ)
2338 // only one display supported for now
2339 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
2342 if (!GLExtensions::getInstance().haveFramebufferObject())
2343 return INVALID_OPERATION;
2345 class MessageCaptureScreen : public MessageBase {
2346 SurfaceFlinger* flinger;
2348 sp<IMemoryHeap>* heap;
2358 MessageCaptureScreen(SurfaceFlinger* flinger, DisplayID dpy,
2359 sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f,
2360 uint32_t sw, uint32_t sh,
2361 uint32_t minLayerZ, uint32_t maxLayerZ)
2362 : flinger(flinger), dpy(dpy),
2363 heap(heap), w(w), h(h), f(f), sw(sw), sh(sh),
2364 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2365 result(PERMISSION_DENIED)
2368 status_t getResult() const {
2371 virtual bool handler() {
2372 Mutex::Autolock _l(flinger->mStateLock);
2374 // if we have secure windows, never allow the screen capture
2375 if (flinger->mSecureFrameBuffer)
2378 result = flinger->captureScreenImplLocked(dpy,
2379 heap, w, h, f, sw, sh, minLayerZ, maxLayerZ);
2385 sp<MessageBase> msg = new MessageCaptureScreen(this,
2386 dpy, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ);
2387 status_t res = postMessageSync(msg);
2388 if (res == NO_ERROR) {
2389 res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult();
2394 // ---------------------------------------------------------------------------
2396 sp<Layer> SurfaceFlinger::getLayer(const sp<ISurface>& sur) const
2399 Mutex::Autolock _l(mStateLock);
2400 result = mLayerMap.valueFor( sur->asBinder() ).promote();
2404 // ---------------------------------------------------------------------------
2406 Client::Client(const sp<SurfaceFlinger>& flinger)
2407 : mFlinger(flinger), mNameGenerator(1)
2413 const size_t count = mLayers.size();
2414 for (size_t i=0 ; i<count ; i++) {
2415 sp<LayerBaseClient> layer(mLayers.valueAt(i).promote());
2417 mFlinger->removeLayer(layer);
2422 status_t Client::initCheck() const {
2426 size_t Client::attachLayer(const sp<LayerBaseClient>& layer)
2428 Mutex::Autolock _l(mLock);
2429 size_t name = mNameGenerator++;
2430 mLayers.add(name, layer);
2434 void Client::detachLayer(const LayerBaseClient* layer)
2436 Mutex::Autolock _l(mLock);
2437 // we do a linear search here, because this doesn't happen often
2438 const size_t count = mLayers.size();
2439 for (size_t i=0 ; i<count ; i++) {
2440 if (mLayers.valueAt(i) == layer) {
2441 mLayers.removeItemsAt(i, 1);
2446 sp<LayerBaseClient> Client::getLayerUser(int32_t i) const
2448 Mutex::Autolock _l(mLock);
2449 sp<LayerBaseClient> lbc;
2450 wp<LayerBaseClient> layer(mLayers.valueFor(i));
2452 lbc = layer.promote();
2453 LOGE_IF(lbc==0, "getLayerUser(name=%d) is dead", int(i));
2459 status_t Client::onTransact(
2460 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2462 // these must be checked
2463 IPCThreadState* ipc = IPCThreadState::self();
2464 const int pid = ipc->getCallingPid();
2465 const int uid = ipc->getCallingUid();
2466 const int self_pid = getpid();
2467 if (UNLIKELY(pid != self_pid && uid != AID_GRAPHICS && uid != 0)) {
2468 // we're called from a different process, do the real check
2469 if (!PermissionCache::checkCallingPermission(sAccessSurfaceFlinger))
2471 LOGE("Permission Denial: "
2472 "can't openGlobalTransaction pid=%d, uid=%d", pid, uid);
2473 return PERMISSION_DENIED;
2476 return BnSurfaceComposerClient::onTransact(code, data, reply, flags);
2480 sp<ISurface> Client::createSurface(
2481 ISurfaceComposerClient::surface_data_t* params,
2482 const String8& name,
2483 DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
2487 * createSurface must be called from the GL thread so that it can
2488 * have access to the GL context.
2491 class MessageCreateSurface : public MessageBase {
2492 sp<ISurface> result;
2493 SurfaceFlinger* flinger;
2494 ISurfaceComposerClient::surface_data_t* params;
2496 const String8& name;
2502 MessageCreateSurface(SurfaceFlinger* flinger,
2503 ISurfaceComposerClient::surface_data_t* params,
2504 const String8& name, Client* client,
2505 DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
2507 : flinger(flinger), params(params), client(client), name(name),
2508 display(display), w(w), h(h), format(format), flags(flags)
2511 sp<ISurface> getResult() const { return result; }
2512 virtual bool handler() {
2513 result = flinger->createSurface(params, name, client,
2514 display, w, h, format, flags);
2519 sp<MessageBase> msg = new MessageCreateSurface(mFlinger.get(),
2520 params, name, this, display, w, h, format, flags);
2521 mFlinger->postMessageSync(msg);
2522 return static_cast<MessageCreateSurface*>( msg.get() )->getResult();
2524 status_t Client::destroySurface(SurfaceID sid) {
2525 return mFlinger->removeSurface(this, sid);
2528 // ---------------------------------------------------------------------------
2530 GraphicBufferAlloc::GraphicBufferAlloc() {}
2532 GraphicBufferAlloc::~GraphicBufferAlloc() {}
2534 sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h,
2535 PixelFormat format, uint32_t usage, status_t* error) {
2536 sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage));
2537 status_t err = graphicBuffer->initCheck();
2539 if (err != 0 || graphicBuffer->handle == 0) {
2540 if (err == NO_MEMORY) {
2541 GraphicBuffer::dumpAllocationsToSystemLog();
2543 LOGE("GraphicBufferAlloc::createGraphicBuffer(w=%d, h=%d) "
2544 "failed (%s), handle=%p",
2545 w, h, strerror(-err), graphicBuffer->handle);
2548 return graphicBuffer;
2551 // ---------------------------------------------------------------------------
2553 GraphicPlane::GraphicPlane()
2558 GraphicPlane::~GraphicPlane() {
2562 bool GraphicPlane::initialized() const {
2563 return mHw ? true : false;
2566 int GraphicPlane::getWidth() const {
2570 int GraphicPlane::getHeight() const {
2574 void GraphicPlane::setDisplayHardware(DisplayHardware *hw)
2578 // initialize the display orientation transform.
2579 // it's a constant that should come from the display driver.
2580 int displayOrientation = ISurfaceComposer::eOrientationDefault;
2581 char property[PROPERTY_VALUE_MAX];
2582 if (property_get("ro.sf.hwrotation", property, NULL) > 0) {
2583 //displayOrientation
2584 switch (atoi(property)) {
2586 displayOrientation = ISurfaceComposer::eOrientation90;
2589 displayOrientation = ISurfaceComposer::eOrientation270;
2594 const float w = hw->getWidth();
2595 const float h = hw->getHeight();
2596 GraphicPlane::orientationToTransfrom(displayOrientation, w, h,
2597 &mDisplayTransform);
2598 if (displayOrientation & ISurfaceComposer::eOrientationSwapMask) {
2606 setOrientation(ISurfaceComposer::eOrientationDefault);
2609 status_t GraphicPlane::orientationToTransfrom(
2610 int orientation, int w, int h, Transform* tr)
2613 switch (orientation) {
2614 case ISurfaceComposer::eOrientationDefault:
2615 flags = Transform::ROT_0;
2617 case ISurfaceComposer::eOrientation90:
2618 flags = Transform::ROT_90;
2620 case ISurfaceComposer::eOrientation180:
2621 flags = Transform::ROT_180;
2623 case ISurfaceComposer::eOrientation270:
2624 flags = Transform::ROT_270;
2629 tr->set(flags, w, h);
2633 status_t GraphicPlane::setOrientation(int orientation)
2635 // If the rotation can be handled in hardware, this is where
2636 // the magic should happen.
2638 const DisplayHardware& hw(displayHardware());
2639 const float w = mDisplayWidth;
2640 const float h = mDisplayHeight;
2644 Transform orientationTransform;
2645 GraphicPlane::orientationToTransfrom(orientation, w, h,
2646 &orientationTransform);
2647 if (orientation & ISurfaceComposer::eOrientationSwapMask) {
2652 mOrientation = orientation;
2653 mGlobalTransform = mDisplayTransform * orientationTransform;
2657 const DisplayHardware& GraphicPlane::displayHardware() const {
2661 DisplayHardware& GraphicPlane::editDisplayHardware() {
2665 const Transform& GraphicPlane::transform() const {
2666 return mGlobalTransform;
2669 EGLDisplay GraphicPlane::getEGLDisplay() const {
2670 return mHw->getEGLDisplay();
2673 // ---------------------------------------------------------------------------
2675 }; // namespace android