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.
17 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
20 #include <sys/types.h>
28 #include <cutils/log.h>
29 #include <cutils/properties.h>
31 #include <binder/IPCThreadState.h>
32 #include <binder/IServiceManager.h>
33 #include <binder/MemoryHeapBase.h>
34 #include <binder/PermissionCache.h>
36 #include <ui/DisplayInfo.h>
38 #include <gui/BitTube.h>
39 #include <gui/BufferQueue.h>
40 #include <gui/GuiConfig.h>
41 #include <gui/IDisplayEventConnection.h>
42 #include <gui/Surface.h>
43 #include <gui/GraphicBufferAlloc.h>
45 #include <ui/GraphicBufferAllocator.h>
46 #include <ui/PixelFormat.h>
47 #include <ui/UiConfig.h>
49 #include <utils/misc.h>
50 #include <utils/String8.h>
51 #include <utils/String16.h>
52 #include <utils/StopWatch.h>
53 #include <utils/Trace.h>
55 #include <private/android_filesystem_config.h>
56 #include <private/gui/SyncFeatures.h>
60 #include "Colorizer.h"
61 #include "DdmConnection.h"
62 #include "DisplayDevice.h"
64 #include "EventControlThread.h"
65 #include "EventThread.h"
68 #include "SurfaceFlinger.h"
70 #include "DisplayHardware/FramebufferSurface.h"
71 #include "DisplayHardware/HWComposer.h"
72 #include "DisplayHardware/VirtualDisplaySurface.h"
74 #include "Effects/Daltonizer.h"
76 #include "RenderEngine/RenderEngine.h"
77 #include <cutils/compiler.h>
79 #define DISPLAY_COUNT 1
82 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
85 #define DEBUG_SCREENSHOTS false
87 EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
91 // This is the phase offset in nanoseconds of the software vsync event
92 // relative to the vsync event reported by HWComposer. The software vsync
93 // event is when SurfaceFlinger and Choreographer-based applications run each
96 // This phase offset allows adjustment of the minimum latency from application
97 // wake-up (by Choregographer) time to the time at which the resulting window
98 // image is displayed. This value may be either positive (after the HW vsync)
99 // or negative (before the HW vsync). Setting it to 0 will result in a
100 // minimum latency of two vsync periods because the app and SurfaceFlinger
101 // will run just after the HW vsync. Setting it to a positive number will
102 // result in the minimum latency being:
104 // (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
106 // Note that reducing this latency makes it more likely for the applications
107 // to not have their window content image ready in time. When this happens
108 // the latency will end up being an additional vsync period, and animations
109 // will hiccup. Therefore, this latency should be tuned somewhat
110 // conservatively (or at least with awareness of the trade-off being made).
111 static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
113 // This is the phase offset at which SurfaceFlinger's composition runs.
114 static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
116 // ---------------------------------------------------------------------------
118 const String16 sHardwareTest("android.permission.HARDWARE_TEST");
119 const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
120 const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
121 const String16 sDump("android.permission.DUMP");
123 // ---------------------------------------------------------------------------
125 SurfaceFlinger::SurfaceFlinger()
126 : BnSurfaceComposer(),
127 mTransactionFlags(0),
128 mTransactionPending(false),
129 mAnimTransactionPending(false),
130 mLayersRemoved(false),
131 mRepaintEverything(0),
133 mBootTime(systemTime()),
134 mVisibleRegionsDirty(false),
135 mHwWorkListDirty(false),
136 mAnimCompositionPending(false),
140 mDebugDisableTransformHint(0),
141 mDebugInSwapBuffers(0),
142 mLastSwapBufferTime(0),
143 mDebugInTransaction(0),
144 mLastTransactionTime(0),
145 mBootFinished(false),
146 mPrimaryHWVsyncEnabled(false),
147 mHWVsyncAvailable(false),
149 mHasColorMatrix(false)
151 ALOGI("SurfaceFlinger is starting");
153 // debugging stuff...
154 char value[PROPERTY_VALUE_MAX];
156 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
157 mGpuToCpuSupported = !atoi(value);
159 property_get("debug.sf.showupdates", value, "0");
160 mDebugRegion = atoi(value);
162 property_get("debug.sf.ddms", value, "0");
163 mDebugDDMS = atoi(value);
165 if (!startDdmConnection()) {
166 // start failed, and DDMS debugging not enabled
170 ALOGI_IF(mDebugRegion, "showupdates enabled");
171 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
174 void SurfaceFlinger::onFirstRef()
176 mEventQueue.init(this);
179 SurfaceFlinger::~SurfaceFlinger()
181 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
182 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
183 eglTerminate(display);
186 void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
188 // the window manager died on us. prepare its eulogy.
190 // restore initial conditions (default device unblank, etc)
191 initializeDisplays();
193 // restart the boot-animation
197 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
199 sp<ISurfaceComposerClient> bclient;
200 sp<Client> client(new Client(this));
201 status_t err = client->initCheck();
202 if (err == NO_ERROR) {
208 sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
211 class DisplayToken : public BBinder {
212 sp<SurfaceFlinger> flinger;
213 virtual ~DisplayToken() {
214 // no more references, this display must be terminated
215 Mutex::Autolock _l(flinger->mStateLock);
216 flinger->mCurrentState.displays.removeItem(this);
217 flinger->setTransactionFlags(eDisplayTransactionNeeded);
220 DisplayToken(const sp<SurfaceFlinger>& flinger)
225 sp<BBinder> token = new DisplayToken(this);
227 Mutex::Autolock _l(mStateLock);
228 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
229 info.displayName = displayName;
230 info.isSecure = secure;
231 mCurrentState.displays.add(token, info);
236 void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
237 Mutex::Autolock _l(mStateLock);
239 ssize_t idx = mCurrentState.displays.indexOfKey(display);
241 ALOGW("destroyDisplay: invalid display token");
245 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
246 if (!info.isVirtualDisplay()) {
247 ALOGE("destroyDisplay called for non-virtual display");
251 mCurrentState.displays.removeItemsAt(idx);
252 setTransactionFlags(eDisplayTransactionNeeded);
255 void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
256 ALOGW_IF(mBuiltinDisplays[type],
257 "Overwriting display token for display type %d", type);
258 mBuiltinDisplays[type] = new BBinder();
259 DisplayDeviceState info(type);
260 // All non-virtual displays are currently considered secure.
261 info.isSecure = true;
262 mCurrentState.displays.add(mBuiltinDisplays[type], info);
265 sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
266 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
267 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
270 return mBuiltinDisplays[id];
273 sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
275 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
279 void SurfaceFlinger::bootFinished()
281 const nsecs_t now = systemTime();
282 const nsecs_t duration = now - mBootTime;
283 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
284 mBootFinished = true;
286 // wait patiently for the window manager death
287 const String16 name("window");
288 sp<IBinder> window(defaultServiceManager()->getService(name));
290 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
293 // stop boot animation
294 // formerly we would just kill the process, but we now ask it to exit so it
295 // can choose where to stop the animation.
296 property_set("service.bootanim.exit", "1");
299 void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
300 class MessageDestroyGLTexture : public MessageBase {
301 RenderEngine& engine;
304 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
305 : engine(engine), texture(texture) {
307 virtual bool handler() {
308 engine.deleteTextures(1, &texture);
312 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
315 class DispSyncSource : public VSyncSource, private DispSync::Callback {
317 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
320 mPhaseOffset(phaseOffset),
321 mTraceVsync(traceVsync),
322 mVsyncOnLabel(String8::format("VsyncOn-%s", label)),
323 mVsyncEventLabel(String8::format("VSYNC-%s", label)),
324 mDispSync(dispSync) {}
326 virtual ~DispSyncSource() {}
328 virtual void setVSyncEnabled(bool enable) {
329 // Do NOT lock the mutex here so as to avoid any mutex ordering issues
330 // with locking it in the onDispSyncEvent callback.
332 status_t err = mDispSync->addEventListener(mPhaseOffset,
333 static_cast<DispSync::Callback*>(this));
334 if (err != NO_ERROR) {
335 ALOGE("error registering vsync callback: %s (%d)",
336 strerror(-err), err);
338 //ATRACE_INT(mVsyncOnLabel.string(), 1);
340 status_t err = mDispSync->removeEventListener(
341 static_cast<DispSync::Callback*>(this));
342 if (err != NO_ERROR) {
343 ALOGE("error unregistering vsync callback: %s (%d)",
344 strerror(-err), err);
346 //ATRACE_INT(mVsyncOnLabel.string(), 0);
350 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
351 Mutex::Autolock lock(mMutex);
352 mCallback = callback;
356 virtual void onDispSyncEvent(nsecs_t when) {
357 sp<VSyncSource::Callback> callback;
359 Mutex::Autolock lock(mMutex);
360 callback = mCallback;
363 mValue = (mValue + 1) % 2;
364 ATRACE_INT(mVsyncEventLabel.string(), mValue);
368 if (callback != NULL) {
369 callback->onVSyncEvent(when);
375 const nsecs_t mPhaseOffset;
376 const bool mTraceVsync;
377 const String8 mVsyncOnLabel;
378 const String8 mVsyncEventLabel;
381 sp<VSyncSource::Callback> mCallback;
385 void SurfaceFlinger::init() {
386 ALOGI( "SurfaceFlinger's main thread ready to run. "
387 "Initializing graphics H/W...");
390 Mutex::Autolock _l(mStateLock);
392 // initialize EGL for the default display
393 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
394 eglInitialize(mEGLDisplay, NULL, NULL);
396 // Initialize the H/W composer object. There may or may not be an
397 // actual hardware composer underneath.
398 mHwc = new HWComposer(this,
399 *static_cast<HWComposer::EventHandler *>(this));
401 // get a RenderEngine for the given display / config (can't fail)
402 mRenderEngine = RenderEngine::create(mEGLDisplay, mHwc->getVisualID());
404 // retrieve the EGL context that was selected/created
405 mEGLContext = mRenderEngine->getEGLContext();
407 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
408 "couldn't create EGLContext");
410 // initialize our non-virtual displays
411 for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
412 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
413 // set-up the displays that are already connected
414 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
415 // All non-virtual displays are currently considered secure.
416 bool isSecure = true;
417 createBuiltinDisplayLocked(type);
418 wp<IBinder> token = mBuiltinDisplays[i];
420 sp<IGraphicBufferProducer> producer;
421 sp<IGraphicBufferConsumer> consumer;
422 BufferQueue::createBufferQueue(&producer, &consumer,
423 new GraphicBufferAlloc());
425 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i,
427 int32_t hwcId = allocateHwcDisplayId(type);
428 sp<DisplayDevice> hw = new DisplayDevice(this,
429 type, hwcId, mHwc->getFormat(hwcId), isSecure, token,
431 mRenderEngine->getEGLConfig());
432 if (i > DisplayDevice::DISPLAY_PRIMARY) {
433 // FIXME: currently we don't get blank/unblank requests
434 // for displays other than the main display, so we always
435 // assume a connected display is unblanked.
436 ALOGD("marking display %zu as acquired/unblanked", i);
437 hw->setPowerMode(HWC_POWER_MODE_NORMAL);
439 mDisplays.add(token, hw);
443 // make the GLContext current so that we can create textures when creating Layers
444 // (which may happens before we render something)
445 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
447 // start the EventThread
448 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
449 vsyncPhaseOffsetNs, true, "app");
450 mEventThread = new EventThread(vsyncSrc);
451 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
452 sfVsyncPhaseOffsetNs, true, "sf");
453 mSFEventThread = new EventThread(sfVsyncSrc);
454 mEventQueue.setEventThread(mSFEventThread);
456 mEventControlThread = new EventControlThread(this);
457 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
459 // set a fake vsync period if there is no HWComposer
460 if (mHwc->initCheck() != NO_ERROR) {
461 mPrimaryDispSync.setPeriod(16666667);
464 // initialize our drawing state
465 mDrawingState = mCurrentState;
467 // set initial conditions (e.g. unblank default device)
468 initializeDisplays();
470 // start boot animation
474 int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
475 return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
476 type : mHwc->allocateDisplayId();
479 void SurfaceFlinger::startBootAnim() {
480 // start boot animation
481 property_set("service.bootanim.exit", "0");
482 property_set("ctl.start", "bootanim");
485 size_t SurfaceFlinger::getMaxTextureSize() const {
486 return mRenderEngine->getMaxTextureSize();
489 size_t SurfaceFlinger::getMaxViewportDims() const {
490 return mRenderEngine->getMaxViewportDims();
493 // ----------------------------------------------------------------------------
495 bool SurfaceFlinger::authenticateSurfaceTexture(
496 const sp<IGraphicBufferProducer>& bufferProducer) const {
497 Mutex::Autolock _l(mStateLock);
498 sp<IBinder> surfaceTextureBinder(bufferProducer->asBinder());
499 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
502 status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
503 Vector<DisplayInfo>* configs) {
504 if (configs == NULL) {
508 int32_t type = NAME_NOT_FOUND;
509 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
510 if (display == mBuiltinDisplays[i]) {
520 // TODO: Not sure if display density should handled by SF any longer
522 static int getDensityFromProperty(char const* propName) {
523 char property[PROPERTY_VALUE_MAX];
525 if (property_get(propName, property, NULL) > 0) {
526 density = atoi(property);
531 static int getEmuDensity() {
532 return getDensityFromProperty("qemu.sf.lcd_density"); }
533 static int getBuildDensity() {
534 return getDensityFromProperty("ro.sf.lcd_density"); }
539 const Vector<HWComposer::DisplayConfig>& hwConfigs =
540 getHwComposer().getConfigs(type);
541 for (size_t c = 0; c < hwConfigs.size(); ++c) {
542 const HWComposer::DisplayConfig& hwConfig = hwConfigs[c];
543 DisplayInfo info = DisplayInfo();
545 float xdpi = hwConfig.xdpi;
546 float ydpi = hwConfig.ydpi;
548 if (type == DisplayDevice::DISPLAY_PRIMARY) {
549 // The density of the device is provided by a build property
550 float density = Density::getBuildDensity() / 160.0f;
552 // the build doesn't provide a density -- this is wrong!
554 ALOGE("ro.sf.lcd_density must be defined as a build property");
555 density = xdpi / 160.0f;
557 if (Density::getEmuDensity()) {
558 // if "qemu.sf.lcd_density" is specified, it overrides everything
559 xdpi = ydpi = density = Density::getEmuDensity();
562 info.density = density;
564 // TODO: this needs to go away (currently needed only by webkit)
565 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
566 info.orientation = hw->getOrientation();
568 // TODO: where should this value come from?
569 static const int TV_DENSITY = 213;
570 info.density = TV_DENSITY / 160.0f;
571 info.orientation = 0;
574 info.w = hwConfig.width;
575 info.h = hwConfig.height;
578 info.fps = float(1e9 / hwConfig.refresh);
579 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
581 // This is how far in advance a buffer must be queued for
582 // presentation at a given time. If you want a buffer to appear
583 // on the screen at time N, you must submit the buffer before
584 // (N - presentationDeadline).
586 // Normally it's one full refresh period (to give SF a chance to
587 // latch the buffer), but this can be reduced by configuring a
588 // DispSync offset. Any additional delays introduced by the hardware
589 // composer or panel must be accounted for here.
591 // We add an additional 1ms to allow for processing time and
592 // differences between the ideal and actual refresh rate.
593 info.presentationDeadline =
594 hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
596 // All non-virtual displays are currently considered secure.
599 configs->push_back(info);
605 int SurfaceFlinger::getActiveConfig(const sp<IBinder>&) {
609 status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>&, int) {
613 status_t SurfaceFlinger::clearAnimationFrameStats() {
614 Mutex::Autolock _l(mStateLock);
615 mAnimFrameTracker.clearStats();
619 status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
620 Mutex::Autolock _l(mStateLock);
621 mAnimFrameTracker.getStats(outStats);
625 // ----------------------------------------------------------------------------
627 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
628 return mEventThread->createEventConnection();
631 // ----------------------------------------------------------------------------
633 void SurfaceFlinger::waitForEvent() {
634 mEventQueue.waitMessage();
637 void SurfaceFlinger::signalTransaction() {
638 mEventQueue.invalidate();
641 void SurfaceFlinger::signalLayerUpdate() {
642 mEventQueue.invalidate();
645 void SurfaceFlinger::signalRefresh() {
646 mEventQueue.refresh();
649 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
650 nsecs_t reltime, uint32_t /* flags */) {
651 return mEventQueue.postMessage(msg, reltime);
654 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
655 nsecs_t reltime, uint32_t /* flags */) {
656 status_t res = mEventQueue.postMessage(msg, reltime);
657 if (res == NO_ERROR) {
663 void SurfaceFlinger::run() {
669 void SurfaceFlinger::enableHardwareVsync() {
670 Mutex::Autolock _l(mHWVsyncLock);
671 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
672 mPrimaryDispSync.beginResync();
673 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
674 mEventControlThread->setVsyncEnabled(true);
675 mPrimaryHWVsyncEnabled = true;
679 void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
680 Mutex::Autolock _l(mHWVsyncLock);
683 mHWVsyncAvailable = true;
684 } else if (!mHWVsyncAvailable) {
685 ALOGE("resyncToHardwareVsync called when HW vsync unavailable");
689 const nsecs_t period =
690 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
692 mPrimaryDispSync.reset();
693 mPrimaryDispSync.setPeriod(period);
695 if (!mPrimaryHWVsyncEnabled) {
696 mPrimaryDispSync.beginResync();
697 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
698 mEventControlThread->setVsyncEnabled(true);
699 mPrimaryHWVsyncEnabled = true;
703 void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
704 Mutex::Autolock _l(mHWVsyncLock);
705 if (mPrimaryHWVsyncEnabled) {
706 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
707 mEventControlThread->setVsyncEnabled(false);
708 mPrimaryDispSync.endResync();
709 mPrimaryHWVsyncEnabled = false;
711 if (makeUnavailable) {
712 mHWVsyncAvailable = false;
716 void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
717 bool needsHwVsync = false;
719 { // Scope for the lock
720 Mutex::Autolock _l(mHWVsyncLock);
721 if (type == 0 && mPrimaryHWVsyncEnabled) {
722 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
727 enableHardwareVsync();
729 disableHardwareVsync(false);
733 void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
734 if (mEventThread == NULL) {
735 // This is a temporary workaround for b/7145521. A non-null pointer
736 // does not mean EventThread has finished initializing, so this
737 // is not a correct fix.
738 ALOGW("WARNING: EventThread not started, ignoring hotplug");
742 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
743 Mutex::Autolock _l(mStateLock);
745 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
747 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
748 mBuiltinDisplays[type].clear();
750 setTransactionFlags(eDisplayTransactionNeeded);
752 // Defer EventThread notification until SF has updated mDisplays.
756 void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
758 getHwComposer().eventControl(disp, event, enabled);
761 void SurfaceFlinger::onMessageReceived(int32_t what) {
764 case MessageQueue::TRANSACTION:
765 handleMessageTransaction();
767 case MessageQueue::INVALIDATE:
768 handleMessageTransaction();
769 handleMessageInvalidate();
772 case MessageQueue::REFRESH:
773 handleMessageRefresh();
778 void SurfaceFlinger::handleMessageTransaction() {
779 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
780 if (transactionFlags) {
781 handleTransaction(transactionFlags);
785 void SurfaceFlinger::handleMessageInvalidate() {
790 void SurfaceFlinger::handleMessageRefresh() {
793 rebuildLayerStacks();
795 doDebugFlashRegions();
800 void SurfaceFlinger::doDebugFlashRegions()
802 // is debugging enabled
803 if (CC_LIKELY(!mDebugRegion))
806 const bool repaintEverything = mRepaintEverything;
807 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
808 const sp<DisplayDevice>& hw(mDisplays[dpy]);
809 if (hw->isDisplayOn()) {
810 // transform the dirty region into this screen's coordinate space
811 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
812 if (!dirtyRegion.isEmpty()) {
813 // redraw the whole screen
814 doComposeSurfaces(hw, Region(hw->bounds()));
816 // and draw the dirty region
817 const int32_t height = hw->getHeight();
818 RenderEngine& engine(getRenderEngine());
819 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
821 hw->compositionComplete();
822 hw->swapBuffers(getHwComposer());
829 if (mDebugRegion > 1) {
830 usleep(mDebugRegion * 1000);
833 HWComposer& hwc(getHwComposer());
834 if (hwc.initCheck() == NO_ERROR) {
835 status_t err = hwc.prepare();
836 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
840 void SurfaceFlinger::preComposition()
842 bool needExtraInvalidate = false;
843 const LayerVector& layers(mDrawingState.layersSortedByZ);
844 const size_t count = layers.size();
845 for (size_t i=0 ; i<count ; i++) {
846 if (layers[i]->onPreComposition()) {
847 needExtraInvalidate = true;
850 if (needExtraInvalidate) {
855 void SurfaceFlinger::postComposition()
857 const LayerVector& layers(mDrawingState.layersSortedByZ);
858 const size_t count = layers.size();
859 for (size_t i=0 ; i<count ; i++) {
860 layers[i]->onPostComposition();
863 const HWComposer& hwc = getHwComposer();
864 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
866 if (presentFence->isValid()) {
867 if (mPrimaryDispSync.addPresentFence(presentFence)) {
868 enableHardwareVsync();
870 disableHardwareVsync(false);
874 if (kIgnorePresentFences) {
875 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
876 if (hw->isDisplayOn()) {
877 enableHardwareVsync();
881 if (mAnimCompositionPending) {
882 mAnimCompositionPending = false;
884 if (presentFence->isValid()) {
885 mAnimFrameTracker.setActualPresentFence(presentFence);
887 // The HWC doesn't support present fences, so use the refresh
888 // timestamp instead.
889 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
890 mAnimFrameTracker.setActualPresentTime(presentTime);
892 mAnimFrameTracker.advanceFrame();
896 void SurfaceFlinger::rebuildLayerStacks() {
897 // rebuild the visible layer list per screen
898 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
900 mVisibleRegionsDirty = false;
901 invalidateHwcGeometry();
903 const LayerVector& layers(mDrawingState.layersSortedByZ);
904 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
907 Vector< sp<Layer> > layersSortedByZ;
908 const sp<DisplayDevice>& hw(mDisplays[dpy]);
909 const Transform& tr(hw->getTransform());
910 const Rect bounds(hw->getBounds());
911 if (hw->isDisplayOn()) {
912 SurfaceFlinger::computeVisibleRegions(layers,
913 hw->getLayerStack(), dirtyRegion, opaqueRegion);
915 const size_t count = layers.size();
916 for (size_t i=0 ; i<count ; i++) {
917 const sp<Layer>& layer(layers[i]);
918 const Layer::State& s(layer->getDrawingState());
919 if (s.layerStack == hw->getLayerStack()) {
920 Region drawRegion(tr.transform(
921 layer->visibleNonTransparentRegion));
922 drawRegion.andSelf(bounds);
923 if (!drawRegion.isEmpty()) {
924 layersSortedByZ.add(layer);
929 hw->setVisibleLayersSortedByZ(layersSortedByZ);
930 hw->undefinedRegion.set(bounds);
931 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
932 hw->dirtyRegion.orSelf(dirtyRegion);
937 void SurfaceFlinger::setUpHWComposer() {
938 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
940 !(mDisplays[dpy]->getDirtyRegion(false).isEmpty());
941 mDisplays[dpy]->beginFrame(mustRecompose);
944 HWComposer& hwc(getHwComposer());
945 if (hwc.initCheck() == NO_ERROR) {
946 // build the h/w work list
947 if (CC_UNLIKELY(mHwWorkListDirty)) {
948 mHwWorkListDirty = false;
949 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
950 sp<const DisplayDevice> hw(mDisplays[dpy]);
951 const int32_t id = hw->getHwcDisplayId();
953 const Vector< sp<Layer> >& currentLayers(
954 hw->getVisibleLayersSortedByZ());
955 const size_t count = currentLayers.size();
956 if (hwc.createWorkList(id, count) == NO_ERROR) {
957 HWComposer::LayerListIterator cur = hwc.begin(id);
958 const HWComposer::LayerListIterator end = hwc.end(id);
959 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
960 const sp<Layer>& layer(currentLayers[i]);
961 layer->setGeometry(hw, *cur);
962 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
971 // set the per-frame data
972 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
973 sp<const DisplayDevice> hw(mDisplays[dpy]);
974 const int32_t id = hw->getHwcDisplayId();
976 const Vector< sp<Layer> >& currentLayers(
977 hw->getVisibleLayersSortedByZ());
978 const size_t count = currentLayers.size();
979 HWComposer::LayerListIterator cur = hwc.begin(id);
980 const HWComposer::LayerListIterator end = hwc.end(id);
981 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
983 * update the per-frame h/w composer data for each layer
984 * and build the transparent region of the FB
986 const sp<Layer>& layer(currentLayers[i]);
987 layer->setPerFrameData(hw, *cur);
992 status_t err = hwc.prepare();
993 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
995 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
996 sp<const DisplayDevice> hw(mDisplays[dpy]);
997 hw->prepareFrame(hwc);
1002 void SurfaceFlinger::doComposition() {
1004 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1005 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1006 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1007 if (hw->isDisplayOn()) {
1008 // transform the dirty region into this screen's coordinate space
1009 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1011 // repaint the framebuffer (if needed)
1012 doDisplayComposition(hw, dirtyRegion);
1014 hw->dirtyRegion.clear();
1015 hw->flip(hw->swapRegion);
1016 hw->swapRegion.clear();
1018 // inform the h/w that we're done compositing
1019 hw->compositionComplete();
1024 void SurfaceFlinger::postFramebuffer()
1028 const nsecs_t now = systemTime();
1029 mDebugInSwapBuffers = now;
1031 HWComposer& hwc(getHwComposer());
1032 if (hwc.initCheck() == NO_ERROR) {
1033 if (!hwc.supportsFramebufferTarget()) {
1035 // "surface must be bound to the calling thread's current context,
1036 // for the current rendering API."
1037 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1042 // make the default display current because the VirtualDisplayDevice code cannot
1043 // deal with dequeueBuffer() being called outside of the composition loop; however
1044 // the code below can call glFlush() which is allowed (and does in some case) call
1046 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1048 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1049 sp<const DisplayDevice> hw(mDisplays[dpy]);
1050 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1051 hw->onSwapBuffersCompleted(hwc);
1052 const size_t count = currentLayers.size();
1053 int32_t id = hw->getHwcDisplayId();
1054 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1055 HWComposer::LayerListIterator cur = hwc.begin(id);
1056 const HWComposer::LayerListIterator end = hwc.end(id);
1057 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1058 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1061 for (size_t i = 0; i < count; i++) {
1062 currentLayers[i]->onLayerDisplayed(hw, NULL);
1067 mLastSwapBufferTime = systemTime() - now;
1068 mDebugInSwapBuffers = 0;
1070 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1071 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1076 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1080 // here we keep a copy of the drawing state (that is the state that's
1081 // going to be overwritten by handleTransactionLocked()) outside of
1082 // mStateLock so that the side-effects of the State assignment
1083 // don't happen with mStateLock held (which can cause deadlocks).
1084 State drawingState(mDrawingState);
1086 Mutex::Autolock _l(mStateLock);
1087 const nsecs_t now = systemTime();
1088 mDebugInTransaction = now;
1090 // Here we're guaranteed that some transaction flags are set
1091 // so we can call handleTransactionLocked() unconditionally.
1092 // We call getTransactionFlags(), which will also clear the flags,
1093 // with mStateLock held to guarantee that mCurrentState won't change
1094 // until the transaction is committed.
1096 transactionFlags = getTransactionFlags(eTransactionMask);
1097 handleTransactionLocked(transactionFlags);
1099 mLastTransactionTime = systemTime() - now;
1100 mDebugInTransaction = 0;
1101 invalidateHwcGeometry();
1102 // here the transaction has been committed
1105 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1107 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1108 const size_t count = currentLayers.size();
1111 * Traversal of the children
1112 * (perform the transaction for each of them if needed)
1115 if (transactionFlags & eTraversalNeeded) {
1116 for (size_t i=0 ; i<count ; i++) {
1117 const sp<Layer>& layer(currentLayers[i]);
1118 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1119 if (!trFlags) continue;
1121 const uint32_t flags = layer->doTransaction(0);
1122 if (flags & Layer::eVisibleRegion)
1123 mVisibleRegionsDirty = true;
1128 * Perform display own transactions if needed
1131 if (transactionFlags & eDisplayTransactionNeeded) {
1132 // here we take advantage of Vector's copy-on-write semantics to
1133 // improve performance by skipping the transaction entirely when
1134 // know that the lists are identical
1135 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1136 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1137 if (!curr.isIdenticalTo(draw)) {
1138 mVisibleRegionsDirty = true;
1139 const size_t cc = curr.size();
1140 size_t dc = draw.size();
1142 // find the displays that were removed
1143 // (ie: in drawing state but not in current state)
1144 // also handle displays that changed
1145 // (ie: displays that are in both lists)
1146 for (size_t i=0 ; i<dc ; i++) {
1147 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1149 // in drawing state but not in current state
1150 if (!draw[i].isMainDisplay()) {
1151 // Call makeCurrent() on the primary display so we can
1152 // be sure that nothing associated with this display
1154 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1155 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1156 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1158 hw->disconnect(getHwComposer());
1159 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1160 mEventThread->onHotplugReceived(draw[i].type, false);
1161 mDisplays.removeItem(draw.keyAt(i));
1163 ALOGW("trying to remove the main display");
1166 // this display is in both lists. see if something changed.
1167 const DisplayDeviceState& state(curr[j]);
1168 const wp<IBinder>& display(curr.keyAt(j));
1169 if (state.surface->asBinder() != draw[i].surface->asBinder()) {
1170 // changing the surface is like destroying and
1171 // recreating the DisplayDevice, so we just remove it
1172 // from the drawing state, so that it get re-added
1174 sp<DisplayDevice> hw(getDisplayDevice(display));
1176 hw->disconnect(getHwComposer());
1177 mDisplays.removeItem(display);
1178 mDrawingState.displays.removeItemsAt(i);
1180 // at this point we must loop to the next item
1184 const sp<DisplayDevice> disp(getDisplayDevice(display));
1186 if (state.layerStack != draw[i].layerStack) {
1187 disp->setLayerStack(state.layerStack);
1189 if ((state.orientation != draw[i].orientation)
1190 || (state.viewport != draw[i].viewport)
1191 || (state.frame != draw[i].frame))
1193 disp->setProjection(state.orientation,
1194 state.viewport, state.frame);
1200 // find displays that were added
1201 // (ie: in current state but not in drawing state)
1202 for (size_t i=0 ; i<cc ; i++) {
1203 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1204 const DisplayDeviceState& state(curr[i]);
1206 sp<DisplaySurface> dispSurface;
1207 sp<IGraphicBufferProducer> producer;
1208 sp<IGraphicBufferProducer> bqProducer;
1209 sp<IGraphicBufferConsumer> bqConsumer;
1210 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1211 new GraphicBufferAlloc());
1213 int32_t hwcDisplayId = -1;
1214 if (state.isVirtualDisplay()) {
1215 // Virtual displays without a surface are dormant:
1216 // they have external state (layer stack, projection,
1217 // etc.) but no internal state (i.e. a DisplayDevice).
1218 if (state.surface != NULL) {
1220 hwcDisplayId = allocateHwcDisplayId(state.type);
1221 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1222 *mHwc, hwcDisplayId, state.surface,
1223 bqProducer, bqConsumer, state.displayName);
1226 if (hwcDisplayId >= 0) {
1229 // There won't be any interaction with HWC for this virtual display,
1230 // so the GLES driver can pass buffers directly to the sink.
1231 producer = state.surface;
1235 ALOGE_IF(state.surface!=NULL,
1236 "adding a supported display, but rendering "
1237 "surface is provided (%p), ignoring it",
1238 state.surface.get());
1239 hwcDisplayId = allocateHwcDisplayId(state.type);
1240 // for supported (by hwc) displays we provide our
1241 // own rendering surface
1242 dispSurface = new FramebufferSurface(*mHwc, state.type,
1244 producer = bqProducer;
1247 const wp<IBinder>& display(curr.keyAt(i));
1248 if (dispSurface != NULL) {
1249 sp<DisplayDevice> hw = new DisplayDevice(this,
1250 state.type, hwcDisplayId,
1251 mHwc->getFormat(hwcDisplayId), state.isSecure,
1252 display, dispSurface, producer,
1253 mRenderEngine->getEGLConfig());
1254 hw->setLayerStack(state.layerStack);
1255 hw->setProjection(state.orientation,
1256 state.viewport, state.frame);
1257 hw->setDisplayName(state.displayName);
1258 mDisplays.add(display, hw);
1259 if (state.isVirtualDisplay()) {
1260 if (hwcDisplayId >= 0) {
1261 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1262 hw->getWidth(), hw->getHeight(),
1266 mEventThread->onHotplugReceived(state.type, true);
1274 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1275 // The transform hint might have changed for some layers
1276 // (either because a display has changed, or because a layer
1279 // Walk through all the layers in currentLayers,
1280 // and update their transform hint.
1282 // If a layer is visible only on a single display, then that
1283 // display is used to calculate the hint, otherwise we use the
1286 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1287 // the hint is set before we acquire a buffer from the surface texture.
1289 // NOTE: layer transactions have taken place already, so we use their
1290 // drawing state. However, SurfaceFlinger's own transaction has not
1291 // happened yet, so we must use the current state layer list
1292 // (soon to become the drawing state list).
1294 sp<const DisplayDevice> disp;
1295 uint32_t currentlayerStack = 0;
1296 for (size_t i=0; i<count; i++) {
1297 // NOTE: we rely on the fact that layers are sorted by
1298 // layerStack first (so we don't have to traverse the list
1299 // of displays for every layer).
1300 const sp<Layer>& layer(currentLayers[i]);
1301 uint32_t layerStack = layer->getDrawingState().layerStack;
1302 if (i==0 || currentlayerStack != layerStack) {
1303 currentlayerStack = layerStack;
1304 // figure out if this layerstack is mirrored
1305 // (more than one display) if so, pick the default display,
1306 // if not, pick the only display it's on.
1308 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1309 sp<const DisplayDevice> hw(mDisplays[dpy]);
1310 if (hw->getLayerStack() == currentlayerStack) {
1321 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1322 // redraw after transform hint changes. See bug 8508397.
1324 // could be null when this layer is using a layerStack
1325 // that is not visible on any display. Also can occur at
1326 // screen off/on times.
1327 disp = getDefaultDisplayDevice();
1329 layer->updateTransformHint(disp);
1335 * Perform our own transaction if needed
1338 const LayerVector& layers(mDrawingState.layersSortedByZ);
1339 if (currentLayers.size() > layers.size()) {
1340 // layers have been added
1341 mVisibleRegionsDirty = true;
1344 // some layers might have been removed, so
1345 // we need to update the regions they're exposing.
1346 if (mLayersRemoved) {
1347 mLayersRemoved = false;
1348 mVisibleRegionsDirty = true;
1349 const size_t count = layers.size();
1350 for (size_t i=0 ; i<count ; i++) {
1351 const sp<Layer>& layer(layers[i]);
1352 if (currentLayers.indexOf(layer) < 0) {
1353 // this layer is not visible anymore
1354 // TODO: we could traverse the tree from front to back and
1355 // compute the actual visible region
1356 // TODO: we could cache the transformed region
1357 const Layer::State& s(layer->getDrawingState());
1358 Region visibleReg = s.transform.transform(
1359 Region(Rect(s.active.w, s.active.h)));
1360 invalidateLayerStack(s.layerStack, visibleReg);
1365 commitTransaction();
1368 void SurfaceFlinger::commitTransaction()
1370 if (!mLayersPendingRemoval.isEmpty()) {
1371 // Notify removed layers now that they can't be drawn from
1372 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1373 mLayersPendingRemoval[i]->onRemoved();
1375 mLayersPendingRemoval.clear();
1378 // If this transaction is part of a window animation then the next frame
1379 // we composite should be considered an animation as well.
1380 mAnimCompositionPending = mAnimTransactionPending;
1382 mDrawingState = mCurrentState;
1383 mTransactionPending = false;
1384 mAnimTransactionPending = false;
1385 mTransactionCV.broadcast();
1388 void SurfaceFlinger::computeVisibleRegions(
1389 const LayerVector& currentLayers, uint32_t layerStack,
1390 Region& outDirtyRegion, Region& outOpaqueRegion)
1394 Region aboveOpaqueLayers;
1395 Region aboveCoveredLayers;
1398 outDirtyRegion.clear();
1400 size_t i = currentLayers.size();
1402 const sp<Layer>& layer = currentLayers[i];
1404 // start with the whole surface at its current location
1405 const Layer::State& s(layer->getDrawingState());
1407 // only consider the layers on the given layer stack
1408 if (s.layerStack != layerStack)
1412 * opaqueRegion: area of a surface that is fully opaque.
1414 Region opaqueRegion;
1417 * visibleRegion: area of a surface that is visible on screen
1418 * and not fully transparent. This is essentially the layer's
1419 * footprint minus the opaque regions above it.
1420 * Areas covered by a translucent surface are considered visible.
1422 Region visibleRegion;
1425 * coveredRegion: area of a surface that is covered by all
1426 * visible regions above it (which includes the translucent areas).
1428 Region coveredRegion;
1431 * transparentRegion: area of a surface that is hinted to be completely
1432 * transparent. This is only used to tell when the layer has no visible
1433 * non-transparent regions and can be removed from the layer list. It
1434 * does not affect the visibleRegion of this layer or any layers
1435 * beneath it. The hint may not be correct if apps don't respect the
1436 * SurfaceView restrictions (which, sadly, some don't).
1438 Region transparentRegion;
1441 // handle hidden surfaces by setting the visible region to empty
1442 if (CC_LIKELY(layer->isVisible())) {
1443 const bool translucent = !layer->isOpaque(s);
1444 Rect bounds(s.transform.transform(layer->computeBounds()));
1445 visibleRegion.set(bounds);
1446 if (!visibleRegion.isEmpty()) {
1447 // Remove the transparent area from the visible region
1449 const Transform tr(s.transform);
1450 if (tr.transformed()) {
1451 if (tr.preserveRects()) {
1452 // transform the transparent region
1453 transparentRegion = tr.transform(s.activeTransparentRegion);
1455 // transformation too complex, can't do the
1456 // transparent region optimization.
1457 transparentRegion.clear();
1460 transparentRegion = s.activeTransparentRegion;
1464 // compute the opaque region
1465 const int32_t layerOrientation = s.transform.getOrientation();
1466 if (s.alpha==255 && !translucent &&
1467 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1468 // the opaque region is the layer's footprint
1469 opaqueRegion = visibleRegion;
1474 // Clip the covered region to the visible region
1475 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1477 // Update aboveCoveredLayers for next (lower) layer
1478 aboveCoveredLayers.orSelf(visibleRegion);
1480 // subtract the opaque region covered by the layers above us
1481 visibleRegion.subtractSelf(aboveOpaqueLayers);
1483 // compute this layer's dirty region
1484 if (layer->contentDirty) {
1485 // we need to invalidate the whole region
1486 dirty = visibleRegion;
1487 // as well, as the old visible region
1488 dirty.orSelf(layer->visibleRegion);
1489 layer->contentDirty = false;
1491 /* compute the exposed region:
1492 * the exposed region consists of two components:
1493 * 1) what's VISIBLE now and was COVERED before
1494 * 2) what's EXPOSED now less what was EXPOSED before
1496 * note that (1) is conservative, we start with the whole
1497 * visible region but only keep what used to be covered by
1498 * something -- which mean it may have been exposed.
1500 * (2) handles areas that were not covered by anything but got
1501 * exposed because of a resize.
1503 const Region newExposed = visibleRegion - coveredRegion;
1504 const Region oldVisibleRegion = layer->visibleRegion;
1505 const Region oldCoveredRegion = layer->coveredRegion;
1506 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1507 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1509 dirty.subtractSelf(aboveOpaqueLayers);
1511 // accumulate to the screen dirty region
1512 outDirtyRegion.orSelf(dirty);
1514 // Update aboveOpaqueLayers for next (lower) layer
1515 aboveOpaqueLayers.orSelf(opaqueRegion);
1517 // Store the visible region in screen space
1518 layer->setVisibleRegion(visibleRegion);
1519 layer->setCoveredRegion(coveredRegion);
1520 layer->setVisibleNonTransparentRegion(
1521 visibleRegion.subtract(transparentRegion));
1524 outOpaqueRegion = aboveOpaqueLayers;
1527 void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1528 const Region& dirty) {
1529 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1530 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1531 if (hw->getLayerStack() == layerStack) {
1532 hw->dirtyRegion.orSelf(dirty);
1537 void SurfaceFlinger::handlePageFlip()
1541 bool visibleRegions = false;
1542 const LayerVector& layers(mDrawingState.layersSortedByZ);
1543 const size_t count = layers.size();
1544 for (size_t i=0 ; i<count ; i++) {
1545 const sp<Layer>& layer(layers[i]);
1546 const Region dirty(layer->latchBuffer(visibleRegions));
1547 const Layer::State& s(layer->getDrawingState());
1548 invalidateLayerStack(s.layerStack, dirty);
1551 mVisibleRegionsDirty |= visibleRegions;
1554 void SurfaceFlinger::invalidateHwcGeometry()
1556 mHwWorkListDirty = true;
1560 void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1561 const Region& inDirtyRegion)
1563 // We only need to actually compose the display if:
1564 // 1) It is being handled by hardware composer, which may need this to
1565 // keep its virtual display state machine in sync, or
1566 // 2) There is work to be done (the dirty region isn't empty)
1567 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1568 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
1572 Region dirtyRegion(inDirtyRegion);
1574 // compute the invalid region
1575 hw->swapRegion.orSelf(dirtyRegion);
1577 uint32_t flags = hw->getFlags();
1578 if (flags & DisplayDevice::SWAP_RECTANGLE) {
1579 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1580 // takes a rectangle, we must make sure to update that whole
1581 // rectangle in that case
1582 dirtyRegion.set(hw->swapRegion.bounds());
1584 if (flags & DisplayDevice::PARTIAL_UPDATES) {
1585 // We need to redraw the rectangle that will be updated
1586 // (pushed to the framebuffer).
1587 // This is needed because PARTIAL_UPDATES only takes one
1588 // rectangle instead of a region (see DisplayDevice::flip())
1589 dirtyRegion.set(hw->swapRegion.bounds());
1591 // we need to redraw everything (the whole screen)
1592 dirtyRegion.set(hw->bounds());
1593 hw->swapRegion = dirtyRegion;
1597 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
1598 doComposeSurfaces(hw, dirtyRegion);
1600 RenderEngine& engine(getRenderEngine());
1601 mat4 colorMatrix = mColorMatrix;
1603 colorMatrix = colorMatrix * mDaltonizer();
1605 engine.beginGroup(colorMatrix);
1606 doComposeSurfaces(hw, dirtyRegion);
1610 // update the swap region and clear the dirty region
1611 hw->swapRegion.orSelf(dirtyRegion);
1613 // swap buffers (presentation)
1614 hw->swapBuffers(getHwComposer());
1617 void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1619 RenderEngine& engine(getRenderEngine());
1620 const int32_t id = hw->getHwcDisplayId();
1621 HWComposer& hwc(getHwComposer());
1622 HWComposer::LayerListIterator cur = hwc.begin(id);
1623 const HWComposer::LayerListIterator end = hwc.end(id);
1625 bool hasGlesComposition = hwc.hasGlesComposition(id);
1626 if (hasGlesComposition) {
1627 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
1628 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1629 hw->getDisplayName().string());
1633 // Never touch the framebuffer if we don't have any framebuffer layers
1634 const bool hasHwcComposition = hwc.hasHwcComposition(id);
1635 if (hasHwcComposition) {
1636 // when using overlays, we assume a fully transparent framebuffer
1637 // NOTE: we could reduce how much we need to clear, for instance
1638 // remove where there are opaque FB layers. however, on some
1639 // GPUs doing a "clean slate" clear might be more efficient.
1640 // We'll revisit later if needed.
1641 engine.clearWithColor(0, 0, 0, 0);
1643 // we start with the whole screen area
1644 const Region bounds(hw->getBounds());
1646 // we remove the scissor part
1647 // we're left with the letterbox region
1648 // (common case is that letterbox ends-up being empty)
1649 const Region letterbox(bounds.subtract(hw->getScissor()));
1651 // compute the area to clear
1652 Region region(hw->undefinedRegion.merge(letterbox));
1654 // but limit it to the dirty region
1655 region.andSelf(dirty);
1657 // screen is already cleared here
1658 if (!region.isEmpty()) {
1659 // can happen with SurfaceView
1660 drawWormhole(hw, region);
1664 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
1665 // just to be on the safe side, we don't set the
1666 // scissor on the main display. It should never be needed
1667 // anyways (though in theory it could since the API allows it).
1668 const Rect& bounds(hw->getBounds());
1669 const Rect& scissor(hw->getScissor());
1670 if (scissor != bounds) {
1671 // scissor doesn't match the screen's dimensions, so we
1672 // need to clear everything outside of it and enable
1673 // the GL scissor so we don't draw anything where we shouldn't
1675 // enable scissor for this frame
1676 const uint32_t height = hw->getHeight();
1677 engine.setScissor(scissor.left, height - scissor.bottom,
1678 scissor.getWidth(), scissor.getHeight());
1684 * and then, render the layers targeted at the framebuffer
1687 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
1688 const size_t count = layers.size();
1689 const Transform& tr = hw->getTransform();
1691 // we're using h/w composer
1692 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1693 const sp<Layer>& layer(layers[i]);
1694 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1695 if (!clip.isEmpty()) {
1696 switch (cur->getCompositionType()) {
1698 const Layer::State& state(layer->getDrawingState());
1699 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1701 && layer->isOpaque(state) && (state.alpha == 0xFF)
1702 && hasGlesComposition) {
1703 // never clear the very first layer since we're
1704 // guaranteed the FB is already cleared
1705 layer->clearWithOpenGL(hw, clip);
1709 case HWC_FRAMEBUFFER: {
1710 layer->draw(hw, clip);
1713 case HWC_FRAMEBUFFER_TARGET: {
1714 // this should not happen as the iterator shouldn't
1715 // let us get there.
1716 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
1721 layer->setAcquireFence(hw, *cur);
1724 // we're not using h/w composer
1725 for (size_t i=0 ; i<count ; ++i) {
1726 const sp<Layer>& layer(layers[i]);
1727 const Region clip(dirty.intersect(
1728 tr.transform(layer->visibleRegion)));
1729 if (!clip.isEmpty()) {
1730 layer->draw(hw, clip);
1735 // disable scissor at the end of the frame
1736 engine.disableScissor();
1739 void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
1740 const int32_t height = hw->getHeight();
1741 RenderEngine& engine(getRenderEngine());
1742 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
1745 void SurfaceFlinger::addClientLayer(const sp<Client>& client,
1746 const sp<IBinder>& handle,
1747 const sp<IGraphicBufferProducer>& gbc,
1748 const sp<Layer>& lbc)
1750 // attach this layer to the client
1751 client->attachLayer(handle, lbc);
1753 // add this layer to the current state list
1754 Mutex::Autolock _l(mStateLock);
1755 mCurrentState.layersSortedByZ.add(lbc);
1756 mGraphicBufferProducerList.add(gbc->asBinder());
1759 status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
1760 Mutex::Autolock _l(mStateLock);
1761 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
1763 mLayersPendingRemoval.push(layer);
1764 mLayersRemoved = true;
1765 setTransactionFlags(eTransactionNeeded);
1768 return status_t(index);
1771 uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
1772 return android_atomic_release_load(&mTransactionFlags);
1775 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
1776 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1779 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
1780 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1781 if ((old & flags)==0) { // wake the server up
1782 signalTransaction();
1787 void SurfaceFlinger::setTransactionState(
1788 const Vector<ComposerState>& state,
1789 const Vector<DisplayState>& displays,
1793 Mutex::Autolock _l(mStateLock);
1794 uint32_t transactionFlags = 0;
1796 if (flags & eAnimation) {
1797 // For window updates that are part of an animation we must wait for
1798 // previous animation "frames" to be handled.
1799 while (mAnimTransactionPending) {
1800 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1801 if (CC_UNLIKELY(err != NO_ERROR)) {
1802 // just in case something goes wrong in SF, return to the
1803 // caller after a few seconds.
1804 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
1805 "waiting for previous animation frame");
1806 mAnimTransactionPending = false;
1812 size_t count = displays.size();
1813 for (size_t i=0 ; i<count ; i++) {
1814 const DisplayState& s(displays[i]);
1815 transactionFlags |= setDisplayStateLocked(s);
1818 count = state.size();
1819 for (size_t i=0 ; i<count ; i++) {
1820 const ComposerState& s(state[i]);
1821 // Here we need to check that the interface we're given is indeed
1822 // one of our own. A malicious client could give us a NULL
1823 // IInterface, or one of its own or even one of our own but a
1824 // different type. All these situations would cause us to crash.
1826 // NOTE: it would be better to use RTTI as we could directly check
1827 // that we have a Client*. however, RTTI is disabled in Android.
1828 if (s.client != NULL) {
1829 sp<IBinder> binder = s.client->asBinder();
1830 if (binder != NULL) {
1831 String16 desc(binder->getInterfaceDescriptor());
1832 if (desc == ISurfaceComposerClient::descriptor) {
1833 sp<Client> client( static_cast<Client *>(s.client.get()) );
1834 transactionFlags |= setClientStateLocked(client, s.state);
1840 if (transactionFlags) {
1841 // this triggers the transaction
1842 setTransactionFlags(transactionFlags);
1844 // if this is a synchronous transaction, wait for it to take effect
1845 // before returning.
1846 if (flags & eSynchronous) {
1847 mTransactionPending = true;
1849 if (flags & eAnimation) {
1850 mAnimTransactionPending = true;
1852 while (mTransactionPending) {
1853 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1854 if (CC_UNLIKELY(err != NO_ERROR)) {
1855 // just in case something goes wrong in SF, return to the
1856 // called after a few seconds.
1857 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
1858 mTransactionPending = false;
1865 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
1867 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
1872 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
1873 if (disp.isValid()) {
1874 const uint32_t what = s.what;
1875 if (what & DisplayState::eSurfaceChanged) {
1876 if (disp.surface->asBinder() != s.surface->asBinder()) {
1877 disp.surface = s.surface;
1878 flags |= eDisplayTransactionNeeded;
1881 if (what & DisplayState::eLayerStackChanged) {
1882 if (disp.layerStack != s.layerStack) {
1883 disp.layerStack = s.layerStack;
1884 flags |= eDisplayTransactionNeeded;
1887 if (what & DisplayState::eDisplayProjectionChanged) {
1888 if (disp.orientation != s.orientation) {
1889 disp.orientation = s.orientation;
1890 flags |= eDisplayTransactionNeeded;
1892 if (disp.frame != s.frame) {
1893 disp.frame = s.frame;
1894 flags |= eDisplayTransactionNeeded;
1896 if (disp.viewport != s.viewport) {
1897 disp.viewport = s.viewport;
1898 flags |= eDisplayTransactionNeeded;
1905 uint32_t SurfaceFlinger::setClientStateLocked(
1906 const sp<Client>& client,
1907 const layer_state_t& s)
1910 sp<Layer> layer(client->getLayerUser(s.surface));
1912 const uint32_t what = s.what;
1913 if (what & layer_state_t::ePositionChanged) {
1914 if (layer->setPosition(s.x, s.y))
1915 flags |= eTraversalNeeded;
1917 if (what & layer_state_t::eLayerChanged) {
1918 // NOTE: index needs to be calculated before we update the state
1919 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1920 if (layer->setLayer(s.z)) {
1921 mCurrentState.layersSortedByZ.removeAt(idx);
1922 mCurrentState.layersSortedByZ.add(layer);
1923 // we need traversal (state changed)
1924 // AND transaction (list changed)
1925 flags |= eTransactionNeeded|eTraversalNeeded;
1928 if (what & layer_state_t::eSizeChanged) {
1929 if (layer->setSize(s.w, s.h)) {
1930 flags |= eTraversalNeeded;
1933 if (what & layer_state_t::eAlphaChanged) {
1934 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1935 flags |= eTraversalNeeded;
1937 if (what & layer_state_t::eMatrixChanged) {
1938 if (layer->setMatrix(s.matrix))
1939 flags |= eTraversalNeeded;
1941 if (what & layer_state_t::eTransparentRegionChanged) {
1942 if (layer->setTransparentRegionHint(s.transparentRegion))
1943 flags |= eTraversalNeeded;
1945 if ((what & layer_state_t::eVisibilityChanged) ||
1946 (what & layer_state_t::eOpacityChanged)) {
1947 // TODO: should we just use an eFlagsChanged for this?
1948 if (layer->setFlags(s.flags, s.mask))
1949 flags |= eTraversalNeeded;
1951 if (what & layer_state_t::eCropChanged) {
1952 if (layer->setCrop(s.crop))
1953 flags |= eTraversalNeeded;
1955 if (what & layer_state_t::eLayerStackChanged) {
1956 // NOTE: index needs to be calculated before we update the state
1957 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1958 if (layer->setLayerStack(s.layerStack)) {
1959 mCurrentState.layersSortedByZ.removeAt(idx);
1960 mCurrentState.layersSortedByZ.add(layer);
1961 // we need traversal (state changed)
1962 // AND transaction (list changed)
1963 flags |= eTransactionNeeded|eTraversalNeeded;
1970 status_t SurfaceFlinger::createLayer(
1971 const String8& name,
1972 const sp<Client>& client,
1973 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
1974 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
1976 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
1977 if (int32_t(w|h) < 0) {
1978 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
1983 status_t result = NO_ERROR;
1987 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
1988 case ISurfaceComposerClient::eFXSurfaceNormal:
1989 result = createNormalLayer(client,
1990 name, w, h, flags, format,
1991 handle, gbp, &layer);
1993 case ISurfaceComposerClient::eFXSurfaceDim:
1994 result = createDimLayer(client,
1996 handle, gbp, &layer);
2003 if (result == NO_ERROR) {
2004 addClientLayer(client, *handle, *gbp, layer);
2005 setTransactionFlags(eTransactionNeeded);
2010 status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2011 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2012 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2014 // initialize the surfaces
2016 case PIXEL_FORMAT_TRANSPARENT:
2017 case PIXEL_FORMAT_TRANSLUCENT:
2018 format = PIXEL_FORMAT_RGBA_8888;
2020 case PIXEL_FORMAT_OPAQUE:
2021 format = PIXEL_FORMAT_RGBX_8888;
2025 *outLayer = new Layer(this, client, name, w, h, flags);
2026 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2027 if (err == NO_ERROR) {
2028 *handle = (*outLayer)->getHandle();
2029 *gbp = (*outLayer)->getProducer();
2032 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2036 status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2037 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2038 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2040 *outLayer = new LayerDim(this, client, name, w, h, flags);
2041 *handle = (*outLayer)->getHandle();
2042 *gbp = (*outLayer)->getProducer();
2046 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2048 // called by the window manager when it wants to remove a Layer
2049 status_t err = NO_ERROR;
2050 sp<Layer> l(client->getLayerUser(handle));
2052 err = removeLayer(l);
2053 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2054 "error removing layer=%p (%s)", l.get(), strerror(-err));
2059 status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2061 // called by ~LayerCleaner() when all references to the IBinder (handle)
2063 status_t err = NO_ERROR;
2064 sp<Layer> l(layer.promote());
2066 err = removeLayer(l);
2067 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2068 "error removing layer=%p (%s)", l.get(), strerror(-err));
2073 // ---------------------------------------------------------------------------
2075 void SurfaceFlinger::onInitializeDisplays() {
2076 // reset screen orientation and use primary layer stack
2077 Vector<ComposerState> state;
2078 Vector<DisplayState> displays;
2080 d.what = DisplayState::eDisplayProjectionChanged |
2081 DisplayState::eLayerStackChanged;
2082 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2084 d.orientation = DisplayState::eOrientationDefault;
2085 d.frame.makeInvalid();
2086 d.viewport.makeInvalid();
2088 setTransactionState(state, displays, 0);
2089 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2091 const nsecs_t period =
2092 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2093 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2096 void SurfaceFlinger::initializeDisplays() {
2097 class MessageScreenInitialized : public MessageBase {
2098 SurfaceFlinger* flinger;
2100 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2101 virtual bool handler() {
2102 flinger->onInitializeDisplays();
2106 sp<MessageBase> msg = new MessageScreenInitialized(this);
2107 postMessageAsync(msg); // we may be called from main thread, use async message
2110 void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2112 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2114 int32_t type = hw->getDisplayType();
2115 int currentMode = hw->getPowerMode();
2117 if (mode == currentMode) {
2118 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2122 hw->setPowerMode(mode);
2123 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2124 ALOGW("Trying to set power mode for virtual display");
2128 if (currentMode == HWC_POWER_MODE_OFF) {
2129 getHwComposer().setPowerMode(type, mode);
2130 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2131 // FIXME: eventthread only knows about the main display right now
2132 mEventThread->onScreenAcquired();
2133 resyncToHardwareVsync(true);
2136 mVisibleRegionsDirty = true;
2137 repaintEverything();
2138 } else if (mode == HWC_POWER_MODE_OFF) {
2139 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2140 disableHardwareVsync(true); // also cancels any in-progress resync
2142 // FIXME: eventthread only knows about the main display right now
2143 mEventThread->onScreenReleased();
2146 getHwComposer().setPowerMode(type, mode);
2147 mVisibleRegionsDirty = true;
2148 // from this point on, SF will stop drawing on this display
2150 getHwComposer().setPowerMode(type, mode);
2154 void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2155 class MessageSetPowerMode: public MessageBase {
2156 SurfaceFlinger& mFlinger;
2157 sp<IBinder> mDisplay;
2160 MessageSetPowerMode(SurfaceFlinger& flinger,
2161 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2162 mDisplay(disp) { mMode = mode; }
2163 virtual bool handler() {
2164 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2166 ALOGE("Attempt to set power mode = %d for null display %p",
2167 mDisplay.get(), mMode);
2168 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2169 ALOGW("Attempt to set power mode = %d for virtual display",
2172 mFlinger.setPowerModeInternal(hw, mMode);
2177 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2178 postMessageSync(msg);
2181 // ---------------------------------------------------------------------------
2183 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2187 IPCThreadState* ipc = IPCThreadState::self();
2188 const int pid = ipc->getCallingPid();
2189 const int uid = ipc->getCallingUid();
2190 if ((uid != AID_SHELL) &&
2191 !PermissionCache::checkPermission(sDump, pid, uid)) {
2192 result.appendFormat("Permission Denial: "
2193 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2195 // Try to get the main lock, but don't insist if we can't
2196 // (this would indicate SF is stuck, but we want to be able to
2197 // print something in dumpsys).
2199 while (mStateLock.tryLock()<0 && --retry>=0) {
2202 const bool locked(retry >= 0);
2205 "SurfaceFlinger appears to be unresponsive, "
2206 "dumping anyways (no locks held)\n");
2209 bool dumpAll = true;
2211 size_t numArgs = args.size();
2213 if ((index < numArgs) &&
2214 (args[index] == String16("--list"))) {
2216 listLayersLocked(args, index, result);
2220 if ((index < numArgs) &&
2221 (args[index] == String16("--latency"))) {
2223 dumpStatsLocked(args, index, result);
2227 if ((index < numArgs) &&
2228 (args[index] == String16("--latency-clear"))) {
2230 clearStatsLocked(args, index, result);
2234 if ((index < numArgs) &&
2235 (args[index] == String16("--dispsync"))) {
2237 mPrimaryDispSync.dump(result);
2243 dumpAllLocked(args, index, result);
2247 mStateLock.unlock();
2250 write(fd, result.string(), result.size());
2254 void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2255 size_t& /* index */, String8& result) const
2257 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2258 const size_t count = currentLayers.size();
2259 for (size_t i=0 ; i<count ; i++) {
2260 const sp<Layer>& layer(currentLayers[i]);
2261 result.appendFormat("%s\n", layer->getName().string());
2265 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2266 String8& result) const
2269 if (index < args.size()) {
2270 name = String8(args[index]);
2274 const nsecs_t period =
2275 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2276 result.appendFormat("%" PRId64 "\n", period);
2278 if (name.isEmpty()) {
2279 mAnimFrameTracker.dumpStats(result);
2281 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2282 const size_t count = currentLayers.size();
2283 for (size_t i=0 ; i<count ; i++) {
2284 const sp<Layer>& layer(currentLayers[i]);
2285 if (name == layer->getName()) {
2286 layer->dumpFrameStats(result);
2292 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2293 String8& /* result */)
2296 if (index < args.size()) {
2297 name = String8(args[index]);
2301 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2302 const size_t count = currentLayers.size();
2303 for (size_t i=0 ; i<count ; i++) {
2304 const sp<Layer>& layer(currentLayers[i]);
2305 if (name.isEmpty() || (name == layer->getName())) {
2306 layer->clearFrameStats();
2310 mAnimFrameTracker.clearStats();
2313 // This should only be called from the main thread. Otherwise it would need
2314 // the lock and should use mCurrentState rather than mDrawingState.
2315 void SurfaceFlinger::logFrameStats() {
2316 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2317 const size_t count = drawingLayers.size();
2318 for (size_t i=0 ; i<count ; i++) {
2319 const sp<Layer>& layer(drawingLayers[i]);
2320 layer->logFrameStats();
2323 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2326 /*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2328 static const char* config =
2330 #ifdef HAS_CONTEXT_PRIORITY
2331 " HAS_CONTEXT_PRIORITY"
2333 #ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2334 " NEVER_DEFAULT_TO_ASYNC_MODE"
2336 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2337 " TARGET_DISABLE_TRIPLE_BUFFERING"
2340 result.append(config);
2343 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2344 String8& result) const
2346 bool colorize = false;
2347 if (index < args.size()
2348 && (args[index] == String16("--color"))) {
2353 Colorizer colorizer(colorize);
2355 // figure out if we're stuck somewhere
2356 const nsecs_t now = systemTime();
2357 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2358 const nsecs_t inTransaction(mDebugInTransaction);
2359 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2360 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2363 * Dump library configuration.
2366 colorizer.bold(result);
2367 result.append("Build configuration:");
2368 colorizer.reset(result);
2369 appendSfConfigString(result);
2370 appendUiConfigString(result);
2371 appendGuiConfigString(result);
2372 result.append("\n");
2374 colorizer.bold(result);
2375 result.append("Sync configuration: ");
2376 colorizer.reset(result);
2377 result.append(SyncFeatures::getInstance().toString());
2378 result.append("\n");
2380 colorizer.bold(result);
2381 result.append("DispSync configuration: ");
2382 colorizer.reset(result);
2383 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2384 "present offset %d ns (refresh %" PRId64 " ns)",
2385 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
2386 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
2387 result.append("\n");
2390 * Dump the visible layer list
2392 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2393 const size_t count = currentLayers.size();
2394 colorizer.bold(result);
2395 result.appendFormat("Visible layers (count = %zu)\n", count);
2396 colorizer.reset(result);
2397 for (size_t i=0 ; i<count ; i++) {
2398 const sp<Layer>& layer(currentLayers[i]);
2399 layer->dump(result, colorizer);
2403 * Dump Display state
2406 colorizer.bold(result);
2407 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
2408 colorizer.reset(result);
2409 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2410 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2415 * Dump SurfaceFlinger global state
2418 colorizer.bold(result);
2419 result.append("SurfaceFlinger global state:\n");
2420 colorizer.reset(result);
2422 HWComposer& hwc(getHwComposer());
2423 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2425 colorizer.bold(result);
2426 result.appendFormat("EGL implementation : %s\n",
2427 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2428 colorizer.reset(result);
2429 result.appendFormat("%s\n",
2430 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2432 mRenderEngine->dump(result);
2434 hw->undefinedRegion.dump(result, "undefinedRegion");
2435 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2436 hw->getOrientation(), hw->isDisplayOn());
2437 result.appendFormat(
2438 " last eglSwapBuffers() time: %f us\n"
2439 " last transaction time : %f us\n"
2440 " transaction-flags : %08x\n"
2441 " refresh-rate : %f fps\n"
2444 " gpu_to_cpu_unsupported : %d\n"
2446 mLastSwapBufferTime/1000.0,
2447 mLastTransactionTime/1000.0,
2449 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2450 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2451 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2452 !mGpuToCpuSupported);
2454 result.appendFormat(" eglSwapBuffers time: %f us\n",
2455 inSwapBuffersDuration/1000.0);
2457 result.appendFormat(" transaction time: %f us\n",
2458 inTransactionDuration/1000.0);
2463 mEventThread->dump(result);
2466 * Dump HWComposer state
2468 colorizer.bold(result);
2469 result.append("h/w composer state:\n");
2470 colorizer.reset(result);
2471 result.appendFormat(" h/w composer %s and %s\n",
2472 hwc.initCheck()==NO_ERROR ? "present" : "not present",
2473 (mDebugDisableHWC || mDebugRegion || mDaltonize
2474 || mHasColorMatrix) ? "disabled" : "enabled");
2478 * Dump gralloc state
2480 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2484 const Vector< sp<Layer> >&
2485 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2486 // Note: mStateLock is held here
2488 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2489 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2490 dpy = mDisplays.keyAt(i);
2495 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2496 // Just use the primary display so we have something to return
2497 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2499 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2502 bool SurfaceFlinger::startDdmConnection()
2504 void* libddmconnection_dso =
2505 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2506 if (!libddmconnection_dso) {
2509 void (*DdmConnection_start)(const char* name);
2510 DdmConnection_start =
2511 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
2512 if (!DdmConnection_start) {
2513 dlclose(libddmconnection_dso);
2516 (*DdmConnection_start)(getServiceName());
2520 status_t SurfaceFlinger::onTransact(
2521 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2524 case CREATE_CONNECTION:
2525 case CREATE_DISPLAY:
2526 case SET_TRANSACTION_STATE:
2528 case CLEAR_ANIMATION_FRAME_STATS:
2529 case GET_ANIMATION_FRAME_STATS:
2530 case SET_POWER_MODE:
2532 // codes that require permission check
2533 IPCThreadState* ipc = IPCThreadState::self();
2534 const int pid = ipc->getCallingPid();
2535 const int uid = ipc->getCallingUid();
2536 if ((uid != AID_GRAPHICS) &&
2537 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2538 ALOGE("Permission Denial: "
2539 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2540 return PERMISSION_DENIED;
2544 case CAPTURE_SCREEN:
2546 // codes that require permission check
2547 IPCThreadState* ipc = IPCThreadState::self();
2548 const int pid = ipc->getCallingPid();
2549 const int uid = ipc->getCallingUid();
2550 if ((uid != AID_GRAPHICS) &&
2551 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2552 ALOGE("Permission Denial: "
2553 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2554 return PERMISSION_DENIED;
2560 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2561 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2562 CHECK_INTERFACE(ISurfaceComposer, data, reply);
2563 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2564 IPCThreadState* ipc = IPCThreadState::self();
2565 const int pid = ipc->getCallingPid();
2566 const int uid = ipc->getCallingUid();
2567 ALOGE("Permission Denial: "
2568 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2569 return PERMISSION_DENIED;
2573 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2574 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2576 case 1002: // SHOW_UPDATES
2577 n = data.readInt32();
2578 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2579 invalidateHwcGeometry();
2580 repaintEverything();
2582 case 1004:{ // repaint everything
2583 repaintEverything();
2586 case 1005:{ // force transaction
2587 setTransactionFlags(
2589 eDisplayTransactionNeeded|
2593 case 1006:{ // send empty update
2597 case 1008: // toggle use of hw composer
2598 n = data.readInt32();
2599 mDebugDisableHWC = n ? 1 : 0;
2600 invalidateHwcGeometry();
2601 repaintEverything();
2603 case 1009: // toggle use of transform hint
2604 n = data.readInt32();
2605 mDebugDisableTransformHint = n ? 1 : 0;
2606 invalidateHwcGeometry();
2607 repaintEverything();
2609 case 1010: // interrogate.
2610 reply->writeInt32(0);
2611 reply->writeInt32(0);
2612 reply->writeInt32(mDebugRegion);
2613 reply->writeInt32(0);
2614 reply->writeInt32(mDebugDisableHWC);
2617 Mutex::Autolock _l(mStateLock);
2618 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2619 reply->writeInt32(hw->getPageFlipCount());
2624 n = data.readInt32();
2626 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
2627 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
2628 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
2631 mDaltonizer.setMode(Daltonizer::correction);
2633 mDaltonizer.setMode(Daltonizer::simulation);
2636 invalidateHwcGeometry();
2637 repaintEverything();
2641 // apply a color matrix
2642 n = data.readInt32();
2643 mHasColorMatrix = n ? 1 : 0;
2645 // color matrix is sent as mat3 matrix followed by vec3
2646 // offset, then packed into a mat4 where the last row is
2647 // the offset and extra values are 0
2648 for (size_t i = 0 ; i < 4; i++) {
2649 for (size_t j = 0; j < 4; j++) {
2650 mColorMatrix[i][j] = data.readFloat();
2654 mColorMatrix = mat4();
2656 invalidateHwcGeometry();
2657 repaintEverything();
2660 // This is an experimental interface
2661 // Needs to be shifted to proper binder interface when we productize
2663 n = data.readInt32();
2664 mPrimaryDispSync.setRefreshSkipCount(n);
2672 void SurfaceFlinger::repaintEverything() {
2673 android_atomic_or(1, &mRepaintEverything);
2674 signalTransaction();
2677 // ---------------------------------------------------------------------------
2678 // Capture screen into an IGraphiBufferProducer
2679 // ---------------------------------------------------------------------------
2681 /* The code below is here to handle b/8734824
2683 * We create a IGraphicBufferProducer wrapper that forwards all calls
2684 * to the calling binder thread, where they are executed. This allows
2685 * the calling thread to be reused (on the other side) and not
2686 * depend on having "enough" binder threads to handle the requests.
2690 class GraphicProducerWrapper : public BBinder, public MessageHandler {
2691 sp<IGraphicBufferProducer> impl;
2696 mutable Barrier barrier;
2697 volatile int32_t memoryBarrier;
2708 * this is called by our "fake" BpGraphicBufferProducer. We package the
2709 * data and reply Parcel and forward them to the calling thread.
2711 virtual status_t transact(uint32_t code,
2712 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
2715 this->reply = reply;
2716 android_atomic_acquire_store(0, &memoryBarrier);
2718 // if we've exited, we run the message synchronously right here
2719 handleMessage(Message(MSG_API_CALL));
2722 looper->sendMessage(this, Message(MSG_API_CALL));
2729 * here we run on the binder calling thread. All we've got to do is
2730 * call the real BpGraphicBufferProducer.
2732 virtual void handleMessage(const Message& message) {
2733 android_atomic_release_load(&memoryBarrier);
2734 if (message.what == MSG_API_CALL) {
2735 result = impl->asBinder()->transact(code, data[0], reply);
2737 } else if (message.what == MSG_EXIT) {
2738 exitRequested = true;
2743 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl) :
2744 impl(impl), looper(new Looper(true)), result(NO_ERROR),
2745 exitPending(false), exitRequested(false) {
2748 status_t waitForResponse() {
2750 looper->pollOnce(-1);
2751 } while (!exitRequested);
2755 void exit(status_t result) {
2756 this->result = result;
2758 looper->sendMessage(this, Message(MSG_EXIT));
2763 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
2764 const sp<IGraphicBufferProducer>& producer,
2765 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
2766 uint32_t minLayerZ, uint32_t maxLayerZ,
2767 bool useIdentityTransform) {
2769 if (CC_UNLIKELY(display == 0))
2772 if (CC_UNLIKELY(producer == 0))
2775 // if we have secure windows on this display, never allow the screen capture
2776 // unless the producer interface is local (i.e.: we can take a screenshot for
2778 if (!producer->asBinder()->localBinder()) {
2779 Mutex::Autolock _l(mStateLock);
2780 sp<const DisplayDevice> hw(getDisplayDevice(display));
2781 if (hw->getSecureLayerVisible()) {
2782 ALOGW("FB is protected: PERMISSION_DENIED");
2783 return PERMISSION_DENIED;
2787 class MessageCaptureScreen : public MessageBase {
2788 SurfaceFlinger* flinger;
2789 sp<IBinder> display;
2790 sp<IGraphicBufferProducer> producer;
2792 uint32_t reqWidth, reqHeight;
2793 uint32_t minLayerZ,maxLayerZ;
2794 bool useIdentityTransform;
2797 MessageCaptureScreen(SurfaceFlinger* flinger,
2798 const sp<IBinder>& display,
2799 const sp<IGraphicBufferProducer>& producer,
2800 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
2801 uint32_t minLayerZ, uint32_t maxLayerZ,
2802 bool useIdentityTransform)
2803 : flinger(flinger), display(display), producer(producer),
2804 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
2805 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2806 useIdentityTransform(useIdentityTransform),
2807 result(PERMISSION_DENIED)
2810 status_t getResult() const {
2813 virtual bool handler() {
2814 Mutex::Autolock _l(flinger->mStateLock);
2815 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
2816 result = flinger->captureScreenImplLocked(hw, producer,
2817 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
2818 useIdentityTransform);
2819 static_cast<GraphicProducerWrapper*>(producer->asBinder().get())->exit(result);
2824 // make sure to process transactions before screenshots -- a transaction
2825 // might already be pending but scheduled for VSYNC; this guarantees we
2826 // will handle it before the screenshot. When VSYNC finally arrives
2827 // the scheduled transaction will be a no-op. If no transactions are
2828 // scheduled at this time, this will end-up being a no-op as well.
2829 mEventQueue.invalidateTransactionNow();
2831 // this creates a "fake" BBinder which will serve as a "fake" remote
2832 // binder to receive the marshaled calls and forward them to the
2833 // real remote (a BpGraphicBufferProducer)
2834 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
2836 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
2837 // which does the marshaling work forwards to our "fake remote" above.
2838 sp<MessageBase> msg = new MessageCaptureScreen(this,
2839 display, IGraphicBufferProducer::asInterface( wrapper ),
2840 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
2841 useIdentityTransform);
2843 status_t res = postMessageAsync(msg);
2844 if (res == NO_ERROR) {
2845 res = wrapper->waitForResponse();
2851 void SurfaceFlinger::renderScreenImplLocked(
2852 const sp<const DisplayDevice>& hw,
2853 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
2854 uint32_t minLayerZ, uint32_t maxLayerZ,
2855 bool yswap, bool useIdentityTransform)
2858 RenderEngine& engine(getRenderEngine());
2860 // get screen geometry
2861 const uint32_t hw_w = hw->getWidth();
2862 const uint32_t hw_h = hw->getHeight();
2863 const bool filtering = reqWidth != hw_w || reqWidth != hw_h;
2865 // if a default or invalid sourceCrop is passed in, set reasonable values
2866 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
2867 !sourceCrop.isValid()) {
2868 sourceCrop.setLeftTop(Point(0, 0));
2869 sourceCrop.setRightBottom(Point(hw_w, hw_h));
2872 // ensure that sourceCrop is inside screen
2873 if (sourceCrop.left < 0) {
2874 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
2876 if (sourceCrop.right > hw_w) {
2877 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
2879 if (sourceCrop.top < 0) {
2880 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
2882 if (sourceCrop.bottom > hw_h) {
2883 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
2886 // make sure to clear all GL error flags
2887 engine.checkErrors();
2889 // set-up our viewport
2890 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, hw_h, yswap);
2891 engine.disableTexturing();
2893 // redraw the screen entirely...
2894 engine.clearWithColor(0, 0, 0, 1);
2896 const LayerVector& layers( mDrawingState.layersSortedByZ );
2897 const size_t count = layers.size();
2898 for (size_t i=0 ; i<count ; ++i) {
2899 const sp<Layer>& layer(layers[i]);
2900 const Layer::State& state(layer->getDrawingState());
2901 if (state.layerStack == hw->getLayerStack()) {
2902 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
2903 if (layer->isVisible()) {
2904 if (filtering) layer->setFiltering(true);
2905 layer->draw(hw, useIdentityTransform);
2906 if (filtering) layer->setFiltering(false);
2912 // compositionComplete is needed for older driver
2913 hw->compositionComplete();
2914 hw->setViewportAndProjection();
2918 status_t SurfaceFlinger::captureScreenImplLocked(
2919 const sp<const DisplayDevice>& hw,
2920 const sp<IGraphicBufferProducer>& producer,
2921 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
2922 uint32_t minLayerZ, uint32_t maxLayerZ,
2923 bool useIdentityTransform)
2927 // get screen geometry
2928 const uint32_t hw_w = hw->getWidth();
2929 const uint32_t hw_h = hw->getHeight();
2931 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
2932 ALOGE("size mismatch (%d, %d) > (%d, %d)",
2933 reqWidth, reqHeight, hw_w, hw_h);
2937 reqWidth = (!reqWidth) ? hw_w : reqWidth;
2938 reqHeight = (!reqHeight) ? hw_h : reqHeight;
2940 // create a surface (because we're a producer, and we need to
2941 // dequeue/queue a buffer)
2942 sp<Surface> sur = new Surface(producer, false);
2943 ANativeWindow* window = sur.get();
2945 status_t result = NO_ERROR;
2946 if (native_window_api_connect(window, NATIVE_WINDOW_API_EGL) == NO_ERROR) {
2947 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
2948 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
2951 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
2952 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
2953 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
2954 err |= native_window_set_usage(window, usage);
2956 if (err == NO_ERROR) {
2957 ANativeWindowBuffer* buffer;
2958 /* TODO: Once we have the sync framework everywhere this can use
2959 * server-side waits on the fence that dequeueBuffer returns.
2961 result = native_window_dequeue_buffer_and_wait(window, &buffer);
2962 if (result == NO_ERROR) {
2963 // create an EGLImage from the buffer so we can later
2964 // turn it into a texture
2965 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
2966 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
2967 if (image != EGL_NO_IMAGE_KHR) {
2968 // this binds the given EGLImage as a framebuffer for the
2969 // duration of this scope.
2970 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
2971 if (imageBond.getStatus() == NO_ERROR) {
2972 // this will in fact render into our dequeued buffer
2973 // via an FBO, which means we didn't have to create
2974 // an EGLSurface and therefore we're not
2975 // dependent on the context's EGLConfig.
2976 renderScreenImplLocked(hw, sourceCrop, reqWidth, reqHeight,
2977 minLayerZ, maxLayerZ, true, useIdentityTransform);
2979 // Create a sync point and wait on it, so we know the buffer is
2980 // ready before we pass it along. We can't trivially call glFlush(),
2981 // so we use a wait flag instead.
2982 // TODO: pass a sync fd to queueBuffer() and let the consumer wait.
2983 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
2984 if (sync != EGL_NO_SYNC_KHR) {
2985 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
2986 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
2987 EGLint eglErr = eglGetError();
2988 eglDestroySyncKHR(mEGLDisplay, sync);
2989 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
2990 ALOGW("captureScreen: fence wait timed out");
2992 ALOGW_IF(eglErr != EGL_SUCCESS,
2993 "captureScreen: error waiting on EGL fence: %#x", eglErr);
2996 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3000 if (DEBUG_SCREENSHOTS) {
3001 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3002 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3003 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3004 hw, minLayerZ, maxLayerZ);
3009 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3010 result = INVALID_OPERATION;
3012 // destroy our image
3013 eglDestroyImageKHR(mEGLDisplay, image);
3017 window->queueBuffer(window, buffer, -1);
3022 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3028 void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3029 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3030 if (DEBUG_SCREENSHOTS) {
3031 for (size_t y=0 ; y<h ; y++) {
3032 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3033 for (size_t x=0 ; x<w ; x++) {
3034 if (p[x] != 0xFF000000) return;
3037 ALOGE("*** we just took a black screenshot ***\n"
3038 "requested minz=%d, maxz=%d, layerStack=%d",
3039 minLayerZ, maxLayerZ, hw->getLayerStack());
3040 const LayerVector& layers( mDrawingState.layersSortedByZ );
3041 const size_t count = layers.size();
3042 for (size_t i=0 ; i<count ; ++i) {
3043 const sp<Layer>& layer(layers[i]);
3044 const Layer::State& state(layer->getDrawingState());
3045 const bool visible = (state.layerStack == hw->getLayerStack())
3046 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3047 && (layer->isVisible());
3048 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3049 visible ? '+' : '-',
3050 i, layer->getName().string(), state.layerStack, state.z,
3051 layer->isVisible(), state.flags, state.alpha);
3056 // ---------------------------------------------------------------------------
3058 SurfaceFlinger::LayerVector::LayerVector() {
3061 SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3062 : SortedVector<sp<Layer> >(rhs) {
3065 int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3066 const void* rhs) const
3068 // sort layers per layer-stack, then by z-order and finally by sequence
3069 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3070 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3072 uint32_t ls = l->getCurrentState().layerStack;
3073 uint32_t rs = r->getCurrentState().layerStack;
3077 uint32_t lz = l->getCurrentState().z;
3078 uint32_t rz = r->getCurrentState().z;
3082 return l->sequence - r->sequence;
3085 // ---------------------------------------------------------------------------
3087 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3088 : type(DisplayDevice::DISPLAY_ID_INVALID) {
3091 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
3092 : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0) {
3093 viewport.makeInvalid();
3094 frame.makeInvalid();
3097 // ---------------------------------------------------------------------------
3099 }; // namespace android
3102 #if defined(__gl_h_)
3103 #error "don't include gl/gl.h in this file"
3106 #if defined(__gl2_h_)
3107 #error "don't include gl2/gl2.h in this file"