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>
25 #include <stdatomic.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 <ui/DisplayInfo.h>
38 #include <ui/DisplayStatInfo.h>
40 #include <gui/BitTube.h>
41 #include <gui/BufferQueue.h>
42 #include <gui/GuiConfig.h>
43 #include <gui/IDisplayEventConnection.h>
44 #include <gui/Surface.h>
45 #include <gui/GraphicBufferAlloc.h>
47 #include <ui/GraphicBufferAllocator.h>
48 #include <ui/PixelFormat.h>
49 #include <ui/UiConfig.h>
51 #include <utils/misc.h>
52 #include <utils/String8.h>
53 #include <utils/String16.h>
54 #include <utils/StopWatch.h>
55 #include <utils/Trace.h>
57 #include <private/android_filesystem_config.h>
58 #include <private/gui/SyncFeatures.h>
62 #include "Colorizer.h"
63 #include "DdmConnection.h"
64 #include "DisplayDevice.h"
66 #include "EventControlThread.h"
67 #include "EventThread.h"
70 #include "SurfaceFlinger.h"
72 #include "DisplayHardware/FramebufferSurface.h"
73 #include "DisplayHardware/HWComposer.h"
74 #include "DisplayHardware/VirtualDisplaySurface.h"
76 #include "Effects/Daltonizer.h"
78 #include "RenderEngine/RenderEngine.h"
79 #include <cutils/compiler.h>
81 #define DISPLAY_COUNT 1
84 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
87 #define DEBUG_SCREENSHOTS false
89 EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
93 // This is the phase offset in nanoseconds of the software vsync event
94 // relative to the vsync event reported by HWComposer. The software vsync
95 // event is when SurfaceFlinger and Choreographer-based applications run each
98 // This phase offset allows adjustment of the minimum latency from application
99 // wake-up (by Choregographer) time to the time at which the resulting window
100 // image is displayed. This value may be either positive (after the HW vsync)
101 // or negative (before the HW vsync). Setting it to 0 will result in a
102 // minimum latency of two vsync periods because the app and SurfaceFlinger
103 // will run just after the HW vsync. Setting it to a positive number will
104 // result in the minimum latency being:
106 // (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
108 // Note that reducing this latency makes it more likely for the applications
109 // to not have their window content image ready in time. When this happens
110 // the latency will end up being an additional vsync period, and animations
111 // will hiccup. Therefore, this latency should be tuned somewhat
112 // conservatively (or at least with awareness of the trade-off being made).
113 static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
115 // This is the phase offset at which SurfaceFlinger's composition runs.
116 static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
118 // ---------------------------------------------------------------------------
120 const String16 sHardwareTest("android.permission.HARDWARE_TEST");
121 const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
122 const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
123 const String16 sDump("android.permission.DUMP");
125 // ---------------------------------------------------------------------------
127 SurfaceFlinger::SurfaceFlinger()
128 : BnSurfaceComposer(),
129 mTransactionFlags(0),
130 mTransactionPending(false),
131 mAnimTransactionPending(false),
132 mLayersRemoved(false),
133 mRepaintEverything(0),
135 mBootTime(systemTime()),
136 mVisibleRegionsDirty(false),
137 mHwWorkListDirty(false),
138 mAnimCompositionPending(false),
142 mDebugDisableTransformHint(0),
143 mDebugInSwapBuffers(0),
144 mLastSwapBufferTime(0),
145 mDebugInTransaction(0),
146 mLastTransactionTime(0),
147 mBootFinished(false),
148 mPrimaryHWVsyncEnabled(false),
149 mHWVsyncAvailable(false),
151 mHasColorMatrix(false)
153 ALOGI("SurfaceFlinger is starting");
155 // debugging stuff...
156 char value[PROPERTY_VALUE_MAX];
158 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
159 mGpuToCpuSupported = !atoi(value);
161 property_get("debug.sf.showupdates", value, "0");
162 mDebugRegion = atoi(value);
164 property_get("debug.sf.ddms", value, "0");
165 mDebugDDMS = atoi(value);
167 if (!startDdmConnection()) {
168 // start failed, and DDMS debugging not enabled
172 ALOGI_IF(mDebugRegion, "showupdates enabled");
173 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
176 void SurfaceFlinger::onFirstRef()
178 mEventQueue.init(this);
181 SurfaceFlinger::~SurfaceFlinger()
183 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
184 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
185 eglTerminate(display);
188 void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
190 // the window manager died on us. prepare its eulogy.
192 // restore initial conditions (default device unblank, etc)
193 initializeDisplays();
195 // restart the boot-animation
199 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
201 sp<ISurfaceComposerClient> bclient;
202 sp<Client> client(new Client(this));
203 status_t err = client->initCheck();
204 if (err == NO_ERROR) {
210 sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
213 class DisplayToken : public BBinder {
214 sp<SurfaceFlinger> flinger;
215 virtual ~DisplayToken() {
216 // no more references, this display must be terminated
217 Mutex::Autolock _l(flinger->mStateLock);
218 flinger->mCurrentState.displays.removeItem(this);
219 flinger->setTransactionFlags(eDisplayTransactionNeeded);
222 DisplayToken(const sp<SurfaceFlinger>& flinger)
227 sp<BBinder> token = new DisplayToken(this);
229 Mutex::Autolock _l(mStateLock);
230 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
231 info.displayName = displayName;
232 info.isSecure = secure;
233 mCurrentState.displays.add(token, info);
238 void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
239 Mutex::Autolock _l(mStateLock);
241 ssize_t idx = mCurrentState.displays.indexOfKey(display);
243 ALOGW("destroyDisplay: invalid display token");
247 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
248 if (!info.isVirtualDisplay()) {
249 ALOGE("destroyDisplay called for non-virtual display");
253 mCurrentState.displays.removeItemsAt(idx);
254 setTransactionFlags(eDisplayTransactionNeeded);
257 void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
258 ALOGW_IF(mBuiltinDisplays[type],
259 "Overwriting display token for display type %d", type);
260 mBuiltinDisplays[type] = new BBinder();
261 DisplayDeviceState info(type);
262 // All non-virtual displays are currently considered secure.
263 info.isSecure = true;
264 mCurrentState.displays.add(mBuiltinDisplays[type], info);
267 sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
268 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
269 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
272 return mBuiltinDisplays[id];
275 sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
277 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
281 void SurfaceFlinger::bootFinished()
283 const nsecs_t now = systemTime();
284 const nsecs_t duration = now - mBootTime;
285 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
286 mBootFinished = true;
288 // wait patiently for the window manager death
289 const String16 name("window");
290 sp<IBinder> window(defaultServiceManager()->getService(name));
292 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
295 // stop boot animation
296 // formerly we would just kill the process, but we now ask it to exit so it
297 // can choose where to stop the animation.
298 property_set("service.bootanim.exit", "1");
301 void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
302 class MessageDestroyGLTexture : public MessageBase {
303 RenderEngine& engine;
306 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
307 : engine(engine), texture(texture) {
309 virtual bool handler() {
310 engine.deleteTextures(1, &texture);
314 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
317 class DispSyncSource : public VSyncSource, private DispSync::Callback {
319 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
322 mPhaseOffset(phaseOffset),
323 mTraceVsync(traceVsync),
324 mVsyncOnLabel(String8::format("VsyncOn-%s", label)),
325 mVsyncEventLabel(String8::format("VSYNC-%s", label)),
326 mDispSync(dispSync) {}
328 virtual ~DispSyncSource() {}
330 virtual void setVSyncEnabled(bool enable) {
331 // Do NOT lock the mutex here so as to avoid any mutex ordering issues
332 // with locking it in the onDispSyncEvent callback.
334 status_t err = mDispSync->addEventListener(mPhaseOffset,
335 static_cast<DispSync::Callback*>(this));
336 if (err != NO_ERROR) {
337 ALOGE("error registering vsync callback: %s (%d)",
338 strerror(-err), err);
340 //ATRACE_INT(mVsyncOnLabel.string(), 1);
342 status_t err = mDispSync->removeEventListener(
343 static_cast<DispSync::Callback*>(this));
344 if (err != NO_ERROR) {
345 ALOGE("error unregistering vsync callback: %s (%d)",
346 strerror(-err), err);
348 //ATRACE_INT(mVsyncOnLabel.string(), 0);
352 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
353 Mutex::Autolock lock(mMutex);
354 mCallback = callback;
358 virtual void onDispSyncEvent(nsecs_t when) {
359 sp<VSyncSource::Callback> callback;
361 Mutex::Autolock lock(mMutex);
362 callback = mCallback;
365 mValue = (mValue + 1) % 2;
366 ATRACE_INT(mVsyncEventLabel.string(), mValue);
370 if (callback != NULL) {
371 callback->onVSyncEvent(when);
377 const nsecs_t mPhaseOffset;
378 const bool mTraceVsync;
379 const String8 mVsyncOnLabel;
380 const String8 mVsyncEventLabel;
383 sp<VSyncSource::Callback> mCallback;
387 void SurfaceFlinger::init() {
388 ALOGI( "SurfaceFlinger's main thread ready to run. "
389 "Initializing graphics H/W...");
392 Mutex::Autolock _l(mStateLock);
394 // initialize EGL for the default display
395 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
396 eglInitialize(mEGLDisplay, NULL, NULL);
398 // Initialize the H/W composer object. There may or may not be an
399 // actual hardware composer underneath.
400 mHwc = new HWComposer(this,
401 *static_cast<HWComposer::EventHandler *>(this));
403 // get a RenderEngine for the given display / config (can't fail)
404 mRenderEngine = RenderEngine::create(mEGLDisplay, mHwc->getVisualID());
406 // retrieve the EGL context that was selected/created
407 mEGLContext = mRenderEngine->getEGLContext();
409 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
410 "couldn't create EGLContext");
412 // initialize our non-virtual displays
413 for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
414 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
415 // set-up the displays that are already connected
416 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
417 // All non-virtual displays are currently considered secure.
418 bool isSecure = true;
419 createBuiltinDisplayLocked(type);
420 wp<IBinder> token = mBuiltinDisplays[i];
422 sp<IGraphicBufferProducer> producer;
423 sp<IGraphicBufferConsumer> consumer;
424 BufferQueue::createBufferQueue(&producer, &consumer,
425 new GraphicBufferAlloc());
427 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i,
429 int32_t hwcId = allocateHwcDisplayId(type);
430 sp<DisplayDevice> hw = new DisplayDevice(this,
431 type, hwcId, mHwc->getFormat(hwcId), isSecure, token,
433 mRenderEngine->getEGLConfig());
434 if (i > DisplayDevice::DISPLAY_PRIMARY) {
435 // FIXME: currently we don't get blank/unblank requests
436 // for displays other than the main display, so we always
437 // assume a connected display is unblanked.
438 ALOGD("marking display %zu as acquired/unblanked", i);
439 hw->setPowerMode(HWC_POWER_MODE_NORMAL);
441 mDisplays.add(token, hw);
445 // make the GLContext current so that we can create textures when creating Layers
446 // (which may happens before we render something)
447 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
449 // start the EventThread
450 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
451 vsyncPhaseOffsetNs, true, "app");
452 mEventThread = new EventThread(vsyncSrc);
453 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
454 sfVsyncPhaseOffsetNs, true, "sf");
455 mSFEventThread = new EventThread(sfVsyncSrc);
456 mEventQueue.setEventThread(mSFEventThread);
458 mEventControlThread = new EventControlThread(this);
459 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
461 // set a fake vsync period if there is no HWComposer
462 if (mHwc->initCheck() != NO_ERROR) {
463 mPrimaryDispSync.setPeriod(16666667);
466 // initialize our drawing state
467 mDrawingState = mCurrentState;
469 // set initial conditions (e.g. unblank default device)
470 initializeDisplays();
472 // start boot animation
476 int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
477 return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
478 type : mHwc->allocateDisplayId();
481 void SurfaceFlinger::startBootAnim() {
482 // start boot animation
483 property_set("service.bootanim.exit", "0");
484 property_set("ctl.start", "bootanim");
487 size_t SurfaceFlinger::getMaxTextureSize() const {
488 return mRenderEngine->getMaxTextureSize();
491 size_t SurfaceFlinger::getMaxViewportDims() const {
492 return mRenderEngine->getMaxViewportDims();
495 // ----------------------------------------------------------------------------
497 bool SurfaceFlinger::authenticateSurfaceTexture(
498 const sp<IGraphicBufferProducer>& bufferProducer) const {
499 Mutex::Autolock _l(mStateLock);
500 sp<IBinder> surfaceTextureBinder(bufferProducer->asBinder());
501 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
504 status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
505 Vector<DisplayInfo>* configs) {
506 if (configs == NULL) {
510 int32_t type = NAME_NOT_FOUND;
511 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
512 if (display == mBuiltinDisplays[i]) {
522 // TODO: Not sure if display density should handled by SF any longer
524 static int getDensityFromProperty(char const* propName) {
525 char property[PROPERTY_VALUE_MAX];
527 if (property_get(propName, property, NULL) > 0) {
528 density = atoi(property);
533 static int getEmuDensity() {
534 return getDensityFromProperty("qemu.sf.lcd_density"); }
535 static int getBuildDensity() {
536 return getDensityFromProperty("ro.sf.lcd_density"); }
541 const Vector<HWComposer::DisplayConfig>& hwConfigs =
542 getHwComposer().getConfigs(type);
543 for (size_t c = 0; c < hwConfigs.size(); ++c) {
544 const HWComposer::DisplayConfig& hwConfig = hwConfigs[c];
545 DisplayInfo info = DisplayInfo();
547 float xdpi = hwConfig.xdpi;
548 float ydpi = hwConfig.ydpi;
550 if (type == DisplayDevice::DISPLAY_PRIMARY) {
551 // The density of the device is provided by a build property
552 float density = Density::getBuildDensity() / 160.0f;
554 // the build doesn't provide a density -- this is wrong!
556 ALOGE("ro.sf.lcd_density must be defined as a build property");
557 density = xdpi / 160.0f;
559 if (Density::getEmuDensity()) {
560 // if "qemu.sf.lcd_density" is specified, it overrides everything
561 xdpi = ydpi = density = Density::getEmuDensity();
564 info.density = density;
566 // TODO: this needs to go away (currently needed only by webkit)
567 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
568 info.orientation = hw->getOrientation();
570 // TODO: where should this value come from?
571 static const int TV_DENSITY = 213;
572 info.density = TV_DENSITY / 160.0f;
573 info.orientation = 0;
576 info.w = hwConfig.width;
577 info.h = hwConfig.height;
580 info.fps = float(1e9 / hwConfig.refresh);
581 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
583 // This is how far in advance a buffer must be queued for
584 // presentation at a given time. If you want a buffer to appear
585 // on the screen at time N, you must submit the buffer before
586 // (N - presentationDeadline).
588 // Normally it's one full refresh period (to give SF a chance to
589 // latch the buffer), but this can be reduced by configuring a
590 // DispSync offset. Any additional delays introduced by the hardware
591 // composer or panel must be accounted for here.
593 // We add an additional 1ms to allow for processing time and
594 // differences between the ideal and actual refresh rate.
595 info.presentationDeadline =
596 hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
598 // All non-virtual displays are currently considered secure.
601 configs->push_back(info);
607 status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& display,
608 DisplayStatInfo* stats) {
613 // FIXME for now we always return stats for the primary display
614 memset(stats, 0, sizeof(*stats));
615 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
616 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
620 int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
621 return getDisplayDevice(display)->getActiveConfig();
624 void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
625 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
627 int32_t type = hw->getDisplayType();
628 int currentMode = hw->getActiveConfig();
630 if (mode == currentMode) {
631 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
635 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
636 ALOGW("Trying to set config for virtual display");
640 hw->setActiveConfig(mode);
641 getHwComposer().setActiveConfig(type, mode);
644 status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
645 class MessageSetActiveConfig: public MessageBase {
646 SurfaceFlinger& mFlinger;
647 sp<IBinder> mDisplay;
650 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
652 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
653 virtual bool handler() {
654 Vector<DisplayInfo> configs;
655 mFlinger.getDisplayConfigs(mDisplay, &configs);
656 if(mMode < 0 || mMode >= configs.size()) {
657 ALOGE("Attempt to set active config = %d for display with %zu configs",
658 mMode, configs.size());
660 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
662 ALOGE("Attempt to set active config = %d for null display %p",
663 mMode, mDisplay.get());
664 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
665 ALOGW("Attempt to set active config = %d for virtual display",
668 mFlinger.setActiveConfigInternal(hw, mMode);
673 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
674 postMessageSync(msg);
678 status_t SurfaceFlinger::clearAnimationFrameStats() {
679 Mutex::Autolock _l(mStateLock);
680 mAnimFrameTracker.clearStats();
684 status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
685 Mutex::Autolock _l(mStateLock);
686 mAnimFrameTracker.getStats(outStats);
690 // ----------------------------------------------------------------------------
692 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
693 return mEventThread->createEventConnection();
696 // ----------------------------------------------------------------------------
698 void SurfaceFlinger::waitForEvent() {
699 mEventQueue.waitMessage();
702 void SurfaceFlinger::signalTransaction() {
703 mEventQueue.invalidate();
706 void SurfaceFlinger::signalLayerUpdate() {
707 mEventQueue.invalidate();
710 void SurfaceFlinger::signalRefresh() {
711 mEventQueue.refresh();
714 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
715 nsecs_t reltime, uint32_t /* flags */) {
716 return mEventQueue.postMessage(msg, reltime);
719 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
720 nsecs_t reltime, uint32_t /* flags */) {
721 status_t res = mEventQueue.postMessage(msg, reltime);
722 if (res == NO_ERROR) {
728 void SurfaceFlinger::run() {
734 void SurfaceFlinger::enableHardwareVsync() {
735 Mutex::Autolock _l(mHWVsyncLock);
736 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
737 mPrimaryDispSync.beginResync();
738 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
739 mEventControlThread->setVsyncEnabled(true);
740 mPrimaryHWVsyncEnabled = true;
744 void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
745 Mutex::Autolock _l(mHWVsyncLock);
748 mHWVsyncAvailable = true;
749 } else if (!mHWVsyncAvailable) {
750 ALOGE("resyncToHardwareVsync called when HW vsync unavailable");
754 const nsecs_t period =
755 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
757 mPrimaryDispSync.reset();
758 mPrimaryDispSync.setPeriod(period);
760 if (!mPrimaryHWVsyncEnabled) {
761 mPrimaryDispSync.beginResync();
762 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
763 mEventControlThread->setVsyncEnabled(true);
764 mPrimaryHWVsyncEnabled = true;
768 void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
769 Mutex::Autolock _l(mHWVsyncLock);
770 if (mPrimaryHWVsyncEnabled) {
771 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
772 mEventControlThread->setVsyncEnabled(false);
773 mPrimaryDispSync.endResync();
774 mPrimaryHWVsyncEnabled = false;
776 if (makeUnavailable) {
777 mHWVsyncAvailable = false;
781 void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
782 bool needsHwVsync = false;
784 { // Scope for the lock
785 Mutex::Autolock _l(mHWVsyncLock);
786 if (type == 0 && mPrimaryHWVsyncEnabled) {
787 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
792 enableHardwareVsync();
794 disableHardwareVsync(false);
798 void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
799 if (mEventThread == NULL) {
800 // This is a temporary workaround for b/7145521. A non-null pointer
801 // does not mean EventThread has finished initializing, so this
802 // is not a correct fix.
803 ALOGW("WARNING: EventThread not started, ignoring hotplug");
807 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
808 Mutex::Autolock _l(mStateLock);
810 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
812 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
813 mBuiltinDisplays[type].clear();
815 setTransactionFlags(eDisplayTransactionNeeded);
817 // Defer EventThread notification until SF has updated mDisplays.
821 void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
823 getHwComposer().eventControl(disp, event, enabled);
826 void SurfaceFlinger::onMessageReceived(int32_t what) {
829 case MessageQueue::TRANSACTION:
830 handleMessageTransaction();
832 case MessageQueue::INVALIDATE:
833 handleMessageTransaction();
834 handleMessageInvalidate();
837 case MessageQueue::REFRESH:
838 handleMessageRefresh();
843 void SurfaceFlinger::handleMessageTransaction() {
844 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
845 if (transactionFlags) {
846 handleTransaction(transactionFlags);
850 void SurfaceFlinger::handleMessageInvalidate() {
855 void SurfaceFlinger::handleMessageRefresh() {
858 rebuildLayerStacks();
860 doDebugFlashRegions();
865 void SurfaceFlinger::doDebugFlashRegions()
867 // is debugging enabled
868 if (CC_LIKELY(!mDebugRegion))
871 const bool repaintEverything = mRepaintEverything;
872 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
873 const sp<DisplayDevice>& hw(mDisplays[dpy]);
874 if (hw->isDisplayOn()) {
875 // transform the dirty region into this screen's coordinate space
876 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
877 if (!dirtyRegion.isEmpty()) {
878 // redraw the whole screen
879 doComposeSurfaces(hw, Region(hw->bounds()));
881 // and draw the dirty region
882 const int32_t height = hw->getHeight();
883 RenderEngine& engine(getRenderEngine());
884 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
886 hw->compositionComplete();
887 hw->swapBuffers(getHwComposer());
894 if (mDebugRegion > 1) {
895 usleep(mDebugRegion * 1000);
898 HWComposer& hwc(getHwComposer());
899 if (hwc.initCheck() == NO_ERROR) {
900 status_t err = hwc.prepare();
901 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
905 void SurfaceFlinger::preComposition()
907 bool needExtraInvalidate = false;
908 const LayerVector& layers(mDrawingState.layersSortedByZ);
909 const size_t count = layers.size();
910 for (size_t i=0 ; i<count ; i++) {
911 if (layers[i]->onPreComposition()) {
912 needExtraInvalidate = true;
915 if (needExtraInvalidate) {
920 void SurfaceFlinger::postComposition()
922 const LayerVector& layers(mDrawingState.layersSortedByZ);
923 const size_t count = layers.size();
924 for (size_t i=0 ; i<count ; i++) {
925 layers[i]->onPostComposition();
928 const HWComposer& hwc = getHwComposer();
929 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
931 if (presentFence->isValid()) {
932 if (mPrimaryDispSync.addPresentFence(presentFence)) {
933 enableHardwareVsync();
935 disableHardwareVsync(false);
939 if (kIgnorePresentFences) {
940 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
941 if (hw->isDisplayOn()) {
942 enableHardwareVsync();
946 if (mAnimCompositionPending) {
947 mAnimCompositionPending = false;
949 if (presentFence->isValid()) {
950 mAnimFrameTracker.setActualPresentFence(presentFence);
952 // The HWC doesn't support present fences, so use the refresh
953 // timestamp instead.
954 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
955 mAnimFrameTracker.setActualPresentTime(presentTime);
957 mAnimFrameTracker.advanceFrame();
961 void SurfaceFlinger::rebuildLayerStacks() {
962 // rebuild the visible layer list per screen
963 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
965 mVisibleRegionsDirty = false;
966 invalidateHwcGeometry();
968 const LayerVector& layers(mDrawingState.layersSortedByZ);
969 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
972 Vector< sp<Layer> > layersSortedByZ;
973 const sp<DisplayDevice>& hw(mDisplays[dpy]);
974 const Transform& tr(hw->getTransform());
975 const Rect bounds(hw->getBounds());
976 if (hw->isDisplayOn()) {
977 SurfaceFlinger::computeVisibleRegions(layers,
978 hw->getLayerStack(), dirtyRegion, opaqueRegion);
980 const size_t count = layers.size();
981 for (size_t i=0 ; i<count ; i++) {
982 const sp<Layer>& layer(layers[i]);
983 const Layer::State& s(layer->getDrawingState());
984 if (s.layerStack == hw->getLayerStack()) {
985 Region drawRegion(tr.transform(
986 layer->visibleNonTransparentRegion));
987 drawRegion.andSelf(bounds);
988 if (!drawRegion.isEmpty()) {
989 layersSortedByZ.add(layer);
994 hw->setVisibleLayersSortedByZ(layersSortedByZ);
995 hw->undefinedRegion.set(bounds);
996 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
997 hw->dirtyRegion.orSelf(dirtyRegion);
1002 void SurfaceFlinger::setUpHWComposer() {
1003 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1004 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1005 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1006 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1008 // If nothing has changed (!dirty), don't recompose.
1009 // If something changed, but we don't currently have any visible layers,
1010 // and didn't when we last did a composition, then skip it this time.
1011 // The second rule does two things:
1012 // - When all layers are removed from a display, we'll emit one black
1013 // frame, then nothing more until we get new layers.
1014 // - When a display is created with a private layer stack, we won't
1015 // emit any black frames until a layer is added to the layer stack.
1016 bool mustRecompose = dirty && !(empty && wasEmpty);
1018 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1019 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1020 mustRecompose ? "doing" : "skipping",
1023 wasEmpty ? "+" : "-");
1025 mDisplays[dpy]->beginFrame(mustRecompose);
1027 if (mustRecompose) {
1028 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1032 HWComposer& hwc(getHwComposer());
1033 if (hwc.initCheck() == NO_ERROR) {
1034 // build the h/w work list
1035 if (CC_UNLIKELY(mHwWorkListDirty)) {
1036 mHwWorkListDirty = false;
1037 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1038 sp<const DisplayDevice> hw(mDisplays[dpy]);
1039 const int32_t id = hw->getHwcDisplayId();
1041 const Vector< sp<Layer> >& currentLayers(
1042 hw->getVisibleLayersSortedByZ());
1043 const size_t count = currentLayers.size();
1044 if (hwc.createWorkList(id, count) == NO_ERROR) {
1045 HWComposer::LayerListIterator cur = hwc.begin(id);
1046 const HWComposer::LayerListIterator end = hwc.end(id);
1047 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1048 const sp<Layer>& layer(currentLayers[i]);
1049 layer->setGeometry(hw, *cur);
1050 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
1059 // set the per-frame data
1060 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1061 sp<const DisplayDevice> hw(mDisplays[dpy]);
1062 const int32_t id = hw->getHwcDisplayId();
1064 const Vector< sp<Layer> >& currentLayers(
1065 hw->getVisibleLayersSortedByZ());
1066 const size_t count = currentLayers.size();
1067 HWComposer::LayerListIterator cur = hwc.begin(id);
1068 const HWComposer::LayerListIterator end = hwc.end(id);
1069 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1071 * update the per-frame h/w composer data for each layer
1072 * and build the transparent region of the FB
1074 const sp<Layer>& layer(currentLayers[i]);
1075 layer->setPerFrameData(hw, *cur);
1080 // If possible, attempt to use the cursor overlay on each display.
1081 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1082 sp<const DisplayDevice> hw(mDisplays[dpy]);
1083 const int32_t id = hw->getHwcDisplayId();
1085 const Vector< sp<Layer> >& currentLayers(
1086 hw->getVisibleLayersSortedByZ());
1087 const size_t count = currentLayers.size();
1088 HWComposer::LayerListIterator cur = hwc.begin(id);
1089 const HWComposer::LayerListIterator end = hwc.end(id);
1090 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1091 const sp<Layer>& layer(currentLayers[i]);
1092 if (layer->isPotentialCursor()) {
1093 cur->setIsCursorLayerHint();
1100 status_t err = hwc.prepare();
1101 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1103 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1104 sp<const DisplayDevice> hw(mDisplays[dpy]);
1105 hw->prepareFrame(hwc);
1110 void SurfaceFlinger::doComposition() {
1112 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1113 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1114 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1115 if (hw->isDisplayOn()) {
1116 // transform the dirty region into this screen's coordinate space
1117 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1119 // repaint the framebuffer (if needed)
1120 doDisplayComposition(hw, dirtyRegion);
1122 hw->dirtyRegion.clear();
1123 hw->flip(hw->swapRegion);
1124 hw->swapRegion.clear();
1126 // inform the h/w that we're done compositing
1127 hw->compositionComplete();
1132 void SurfaceFlinger::postFramebuffer()
1136 const nsecs_t now = systemTime();
1137 mDebugInSwapBuffers = now;
1139 HWComposer& hwc(getHwComposer());
1140 if (hwc.initCheck() == NO_ERROR) {
1141 if (!hwc.supportsFramebufferTarget()) {
1143 // "surface must be bound to the calling thread's current context,
1144 // for the current rendering API."
1145 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1150 // make the default display current because the VirtualDisplayDevice code cannot
1151 // deal with dequeueBuffer() being called outside of the composition loop; however
1152 // the code below can call glFlush() which is allowed (and does in some case) call
1154 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1156 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1157 sp<const DisplayDevice> hw(mDisplays[dpy]);
1158 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1159 hw->onSwapBuffersCompleted(hwc);
1160 const size_t count = currentLayers.size();
1161 int32_t id = hw->getHwcDisplayId();
1162 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1163 HWComposer::LayerListIterator cur = hwc.begin(id);
1164 const HWComposer::LayerListIterator end = hwc.end(id);
1165 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1166 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1169 for (size_t i = 0; i < count; i++) {
1170 currentLayers[i]->onLayerDisplayed(hw, NULL);
1175 mLastSwapBufferTime = systemTime() - now;
1176 mDebugInSwapBuffers = 0;
1178 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1179 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1184 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1188 // here we keep a copy of the drawing state (that is the state that's
1189 // going to be overwritten by handleTransactionLocked()) outside of
1190 // mStateLock so that the side-effects of the State assignment
1191 // don't happen with mStateLock held (which can cause deadlocks).
1192 State drawingState(mDrawingState);
1194 Mutex::Autolock _l(mStateLock);
1195 const nsecs_t now = systemTime();
1196 mDebugInTransaction = now;
1198 // Here we're guaranteed that some transaction flags are set
1199 // so we can call handleTransactionLocked() unconditionally.
1200 // We call getTransactionFlags(), which will also clear the flags,
1201 // with mStateLock held to guarantee that mCurrentState won't change
1202 // until the transaction is committed.
1204 transactionFlags = getTransactionFlags(eTransactionMask);
1205 handleTransactionLocked(transactionFlags);
1207 mLastTransactionTime = systemTime() - now;
1208 mDebugInTransaction = 0;
1209 invalidateHwcGeometry();
1210 // here the transaction has been committed
1213 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1215 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1216 const size_t count = currentLayers.size();
1219 * Traversal of the children
1220 * (perform the transaction for each of them if needed)
1223 if (transactionFlags & eTraversalNeeded) {
1224 for (size_t i=0 ; i<count ; i++) {
1225 const sp<Layer>& layer(currentLayers[i]);
1226 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1227 if (!trFlags) continue;
1229 const uint32_t flags = layer->doTransaction(0);
1230 if (flags & Layer::eVisibleRegion)
1231 mVisibleRegionsDirty = true;
1236 * Perform display own transactions if needed
1239 if (transactionFlags & eDisplayTransactionNeeded) {
1240 // here we take advantage of Vector's copy-on-write semantics to
1241 // improve performance by skipping the transaction entirely when
1242 // know that the lists are identical
1243 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1244 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1245 if (!curr.isIdenticalTo(draw)) {
1246 mVisibleRegionsDirty = true;
1247 const size_t cc = curr.size();
1248 size_t dc = draw.size();
1250 // find the displays that were removed
1251 // (ie: in drawing state but not in current state)
1252 // also handle displays that changed
1253 // (ie: displays that are in both lists)
1254 for (size_t i=0 ; i<dc ; i++) {
1255 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1257 // in drawing state but not in current state
1258 if (!draw[i].isMainDisplay()) {
1259 // Call makeCurrent() on the primary display so we can
1260 // be sure that nothing associated with this display
1262 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1263 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1264 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1266 hw->disconnect(getHwComposer());
1267 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1268 mEventThread->onHotplugReceived(draw[i].type, false);
1269 mDisplays.removeItem(draw.keyAt(i));
1271 ALOGW("trying to remove the main display");
1274 // this display is in both lists. see if something changed.
1275 const DisplayDeviceState& state(curr[j]);
1276 const wp<IBinder>& display(curr.keyAt(j));
1277 if (state.surface->asBinder() != draw[i].surface->asBinder()) {
1278 // changing the surface is like destroying and
1279 // recreating the DisplayDevice, so we just remove it
1280 // from the drawing state, so that it get re-added
1282 sp<DisplayDevice> hw(getDisplayDevice(display));
1284 hw->disconnect(getHwComposer());
1285 mDisplays.removeItem(display);
1286 mDrawingState.displays.removeItemsAt(i);
1288 // at this point we must loop to the next item
1292 const sp<DisplayDevice> disp(getDisplayDevice(display));
1294 if (state.layerStack != draw[i].layerStack) {
1295 disp->setLayerStack(state.layerStack);
1297 if ((state.orientation != draw[i].orientation)
1298 || (state.viewport != draw[i].viewport)
1299 || (state.frame != draw[i].frame))
1301 disp->setProjection(state.orientation,
1302 state.viewport, state.frame);
1304 if (state.width != draw[i].width || state.height != draw[i].height) {
1305 disp->setDisplaySize(state.width, state.height);
1311 // find displays that were added
1312 // (ie: in current state but not in drawing state)
1313 for (size_t i=0 ; i<cc ; i++) {
1314 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1315 const DisplayDeviceState& state(curr[i]);
1317 sp<DisplaySurface> dispSurface;
1318 sp<IGraphicBufferProducer> producer;
1319 sp<IGraphicBufferProducer> bqProducer;
1320 sp<IGraphicBufferConsumer> bqConsumer;
1321 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1322 new GraphicBufferAlloc());
1324 int32_t hwcDisplayId = -1;
1325 if (state.isVirtualDisplay()) {
1326 // Virtual displays without a surface are dormant:
1327 // they have external state (layer stack, projection,
1328 // etc.) but no internal state (i.e. a DisplayDevice).
1329 if (state.surface != NULL) {
1331 hwcDisplayId = allocateHwcDisplayId(state.type);
1332 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1333 *mHwc, hwcDisplayId, state.surface,
1334 bqProducer, bqConsumer, state.displayName);
1340 ALOGE_IF(state.surface!=NULL,
1341 "adding a supported display, but rendering "
1342 "surface is provided (%p), ignoring it",
1343 state.surface.get());
1344 hwcDisplayId = allocateHwcDisplayId(state.type);
1345 // for supported (by hwc) displays we provide our
1346 // own rendering surface
1347 dispSurface = new FramebufferSurface(*mHwc, state.type,
1349 producer = bqProducer;
1352 const wp<IBinder>& display(curr.keyAt(i));
1353 if (dispSurface != NULL) {
1354 sp<DisplayDevice> hw = new DisplayDevice(this,
1355 state.type, hwcDisplayId,
1356 mHwc->getFormat(hwcDisplayId), state.isSecure,
1357 display, dispSurface, producer,
1358 mRenderEngine->getEGLConfig());
1359 hw->setLayerStack(state.layerStack);
1360 hw->setProjection(state.orientation,
1361 state.viewport, state.frame);
1362 hw->setDisplayName(state.displayName);
1363 mDisplays.add(display, hw);
1364 if (state.isVirtualDisplay()) {
1365 if (hwcDisplayId >= 0) {
1366 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1367 hw->getWidth(), hw->getHeight(),
1371 mEventThread->onHotplugReceived(state.type, true);
1379 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1380 // The transform hint might have changed for some layers
1381 // (either because a display has changed, or because a layer
1384 // Walk through all the layers in currentLayers,
1385 // and update their transform hint.
1387 // If a layer is visible only on a single display, then that
1388 // display is used to calculate the hint, otherwise we use the
1391 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1392 // the hint is set before we acquire a buffer from the surface texture.
1394 // NOTE: layer transactions have taken place already, so we use their
1395 // drawing state. However, SurfaceFlinger's own transaction has not
1396 // happened yet, so we must use the current state layer list
1397 // (soon to become the drawing state list).
1399 sp<const DisplayDevice> disp;
1400 uint32_t currentlayerStack = 0;
1401 for (size_t i=0; i<count; i++) {
1402 // NOTE: we rely on the fact that layers are sorted by
1403 // layerStack first (so we don't have to traverse the list
1404 // of displays for every layer).
1405 const sp<Layer>& layer(currentLayers[i]);
1406 uint32_t layerStack = layer->getDrawingState().layerStack;
1407 if (i==0 || currentlayerStack != layerStack) {
1408 currentlayerStack = layerStack;
1409 // figure out if this layerstack is mirrored
1410 // (more than one display) if so, pick the default display,
1411 // if not, pick the only display it's on.
1413 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1414 sp<const DisplayDevice> hw(mDisplays[dpy]);
1415 if (hw->getLayerStack() == currentlayerStack) {
1426 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1427 // redraw after transform hint changes. See bug 8508397.
1429 // could be null when this layer is using a layerStack
1430 // that is not visible on any display. Also can occur at
1431 // screen off/on times.
1432 disp = getDefaultDisplayDevice();
1434 layer->updateTransformHint(disp);
1440 * Perform our own transaction if needed
1443 const LayerVector& layers(mDrawingState.layersSortedByZ);
1444 if (currentLayers.size() > layers.size()) {
1445 // layers have been added
1446 mVisibleRegionsDirty = true;
1449 // some layers might have been removed, so
1450 // we need to update the regions they're exposing.
1451 if (mLayersRemoved) {
1452 mLayersRemoved = false;
1453 mVisibleRegionsDirty = true;
1454 const size_t count = layers.size();
1455 for (size_t i=0 ; i<count ; i++) {
1456 const sp<Layer>& layer(layers[i]);
1457 if (currentLayers.indexOf(layer) < 0) {
1458 // this layer is not visible anymore
1459 // TODO: we could traverse the tree from front to back and
1460 // compute the actual visible region
1461 // TODO: we could cache the transformed region
1462 const Layer::State& s(layer->getDrawingState());
1463 Region visibleReg = s.transform.transform(
1464 Region(Rect(s.active.w, s.active.h)));
1465 invalidateLayerStack(s.layerStack, visibleReg);
1470 commitTransaction();
1472 updateCursorAsync();
1475 void SurfaceFlinger::updateCursorAsync()
1477 HWComposer& hwc(getHwComposer());
1478 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1479 sp<const DisplayDevice> hw(mDisplays[dpy]);
1480 const int32_t id = hw->getHwcDisplayId();
1484 const Vector< sp<Layer> >& currentLayers(
1485 hw->getVisibleLayersSortedByZ());
1486 const size_t count = currentLayers.size();
1487 HWComposer::LayerListIterator cur = hwc.begin(id);
1488 const HWComposer::LayerListIterator end = hwc.end(id);
1489 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1490 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1493 const sp<Layer>& layer(currentLayers[i]);
1494 Rect cursorPos = layer->getPosition(hw);
1495 hwc.setCursorPositionAsync(id, cursorPos);
1501 void SurfaceFlinger::commitTransaction()
1503 if (!mLayersPendingRemoval.isEmpty()) {
1504 // Notify removed layers now that they can't be drawn from
1505 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1506 mLayersPendingRemoval[i]->onRemoved();
1508 mLayersPendingRemoval.clear();
1511 // If this transaction is part of a window animation then the next frame
1512 // we composite should be considered an animation as well.
1513 mAnimCompositionPending = mAnimTransactionPending;
1515 mDrawingState = mCurrentState;
1516 mTransactionPending = false;
1517 mAnimTransactionPending = false;
1518 mTransactionCV.broadcast();
1521 void SurfaceFlinger::computeVisibleRegions(
1522 const LayerVector& currentLayers, uint32_t layerStack,
1523 Region& outDirtyRegion, Region& outOpaqueRegion)
1527 Region aboveOpaqueLayers;
1528 Region aboveCoveredLayers;
1531 outDirtyRegion.clear();
1533 size_t i = currentLayers.size();
1535 const sp<Layer>& layer = currentLayers[i];
1537 // start with the whole surface at its current location
1538 const Layer::State& s(layer->getDrawingState());
1540 // only consider the layers on the given layer stack
1541 if (s.layerStack != layerStack)
1545 * opaqueRegion: area of a surface that is fully opaque.
1547 Region opaqueRegion;
1550 * visibleRegion: area of a surface that is visible on screen
1551 * and not fully transparent. This is essentially the layer's
1552 * footprint minus the opaque regions above it.
1553 * Areas covered by a translucent surface are considered visible.
1555 Region visibleRegion;
1558 * coveredRegion: area of a surface that is covered by all
1559 * visible regions above it (which includes the translucent areas).
1561 Region coveredRegion;
1564 * transparentRegion: area of a surface that is hinted to be completely
1565 * transparent. This is only used to tell when the layer has no visible
1566 * non-transparent regions and can be removed from the layer list. It
1567 * does not affect the visibleRegion of this layer or any layers
1568 * beneath it. The hint may not be correct if apps don't respect the
1569 * SurfaceView restrictions (which, sadly, some don't).
1571 Region transparentRegion;
1574 // handle hidden surfaces by setting the visible region to empty
1575 if (CC_LIKELY(layer->isVisible())) {
1576 const bool translucent = !layer->isOpaque(s);
1577 Rect bounds(s.transform.transform(layer->computeBounds()));
1578 visibleRegion.set(bounds);
1579 if (!visibleRegion.isEmpty()) {
1580 // Remove the transparent area from the visible region
1582 const Transform tr(s.transform);
1583 if (tr.transformed()) {
1584 if (tr.preserveRects()) {
1585 // transform the transparent region
1586 transparentRegion = tr.transform(s.activeTransparentRegion);
1588 // transformation too complex, can't do the
1589 // transparent region optimization.
1590 transparentRegion.clear();
1593 transparentRegion = s.activeTransparentRegion;
1597 // compute the opaque region
1598 const int32_t layerOrientation = s.transform.getOrientation();
1599 if (s.alpha==255 && !translucent &&
1600 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1601 // the opaque region is the layer's footprint
1602 opaqueRegion = visibleRegion;
1607 // Clip the covered region to the visible region
1608 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1610 // Update aboveCoveredLayers for next (lower) layer
1611 aboveCoveredLayers.orSelf(visibleRegion);
1613 // subtract the opaque region covered by the layers above us
1614 visibleRegion.subtractSelf(aboveOpaqueLayers);
1616 // compute this layer's dirty region
1617 if (layer->contentDirty) {
1618 // we need to invalidate the whole region
1619 dirty = visibleRegion;
1620 // as well, as the old visible region
1621 dirty.orSelf(layer->visibleRegion);
1622 layer->contentDirty = false;
1624 /* compute the exposed region:
1625 * the exposed region consists of two components:
1626 * 1) what's VISIBLE now and was COVERED before
1627 * 2) what's EXPOSED now less what was EXPOSED before
1629 * note that (1) is conservative, we start with the whole
1630 * visible region but only keep what used to be covered by
1631 * something -- which mean it may have been exposed.
1633 * (2) handles areas that were not covered by anything but got
1634 * exposed because of a resize.
1636 const Region newExposed = visibleRegion - coveredRegion;
1637 const Region oldVisibleRegion = layer->visibleRegion;
1638 const Region oldCoveredRegion = layer->coveredRegion;
1639 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1640 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1642 dirty.subtractSelf(aboveOpaqueLayers);
1644 // accumulate to the screen dirty region
1645 outDirtyRegion.orSelf(dirty);
1647 // Update aboveOpaqueLayers for next (lower) layer
1648 aboveOpaqueLayers.orSelf(opaqueRegion);
1650 // Store the visible region in screen space
1651 layer->setVisibleRegion(visibleRegion);
1652 layer->setCoveredRegion(coveredRegion);
1653 layer->setVisibleNonTransparentRegion(
1654 visibleRegion.subtract(transparentRegion));
1657 outOpaqueRegion = aboveOpaqueLayers;
1660 void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1661 const Region& dirty) {
1662 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1663 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1664 if (hw->getLayerStack() == layerStack) {
1665 hw->dirtyRegion.orSelf(dirty);
1670 void SurfaceFlinger::handlePageFlip()
1674 bool visibleRegions = false;
1675 const LayerVector& layers(mDrawingState.layersSortedByZ);
1677 // Store the set of layers that need updates. This set must not change as
1678 // buffers are being latched, as this could result in a deadlock.
1679 // Example: Two producers share the same command stream and:
1680 // 1.) Layer 0 is latched
1681 // 2.) Layer 0 gets a new frame
1682 // 2.) Layer 1 gets a new frame
1683 // 3.) Layer 1 is latched.
1684 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1685 // second frame. But layer 0's second frame could be waiting on display.
1686 Vector<Layer*> layersWithQueuedFrames;
1687 for (size_t i = 0, count = layers.size(); i<count ; i++) {
1688 const sp<Layer>& layer(layers[i]);
1689 if (layer->hasQueuedFrame())
1690 layersWithQueuedFrames.push_back(layer.get());
1692 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
1693 Layer* layer = layersWithQueuedFrames[i];
1694 const Region dirty(layer->latchBuffer(visibleRegions));
1695 const Layer::State& s(layer->getDrawingState());
1696 invalidateLayerStack(s.layerStack, dirty);
1699 mVisibleRegionsDirty |= visibleRegions;
1702 void SurfaceFlinger::invalidateHwcGeometry()
1704 mHwWorkListDirty = true;
1708 void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1709 const Region& inDirtyRegion)
1711 // We only need to actually compose the display if:
1712 // 1) It is being handled by hardware composer, which may need this to
1713 // keep its virtual display state machine in sync, or
1714 // 2) There is work to be done (the dirty region isn't empty)
1715 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1716 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
1720 Region dirtyRegion(inDirtyRegion);
1722 // compute the invalid region
1723 hw->swapRegion.orSelf(dirtyRegion);
1725 uint32_t flags = hw->getFlags();
1726 if (flags & DisplayDevice::SWAP_RECTANGLE) {
1727 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1728 // takes a rectangle, we must make sure to update that whole
1729 // rectangle in that case
1730 dirtyRegion.set(hw->swapRegion.bounds());
1732 if (flags & DisplayDevice::PARTIAL_UPDATES) {
1733 // We need to redraw the rectangle that will be updated
1734 // (pushed to the framebuffer).
1735 // This is needed because PARTIAL_UPDATES only takes one
1736 // rectangle instead of a region (see DisplayDevice::flip())
1737 dirtyRegion.set(hw->swapRegion.bounds());
1739 // we need to redraw everything (the whole screen)
1740 dirtyRegion.set(hw->bounds());
1741 hw->swapRegion = dirtyRegion;
1745 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
1746 if (!doComposeSurfaces(hw, dirtyRegion)) return;
1748 RenderEngine& engine(getRenderEngine());
1749 mat4 colorMatrix = mColorMatrix;
1751 colorMatrix = colorMatrix * mDaltonizer();
1753 engine.beginGroup(colorMatrix);
1754 doComposeSurfaces(hw, dirtyRegion);
1758 // update the swap region and clear the dirty region
1759 hw->swapRegion.orSelf(dirtyRegion);
1761 // swap buffers (presentation)
1762 hw->swapBuffers(getHwComposer());
1765 bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1767 RenderEngine& engine(getRenderEngine());
1768 const int32_t id = hw->getHwcDisplayId();
1769 HWComposer& hwc(getHwComposer());
1770 HWComposer::LayerListIterator cur = hwc.begin(id);
1771 const HWComposer::LayerListIterator end = hwc.end(id);
1773 bool hasGlesComposition = hwc.hasGlesComposition(id);
1774 if (hasGlesComposition) {
1775 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
1776 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1777 hw->getDisplayName().string());
1778 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1779 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1780 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1785 // Never touch the framebuffer if we don't have any framebuffer layers
1786 const bool hasHwcComposition = hwc.hasHwcComposition(id);
1787 if (hasHwcComposition) {
1788 // when using overlays, we assume a fully transparent framebuffer
1789 // NOTE: we could reduce how much we need to clear, for instance
1790 // remove where there are opaque FB layers. however, on some
1791 // GPUs doing a "clean slate" clear might be more efficient.
1792 // We'll revisit later if needed.
1793 engine.clearWithColor(0, 0, 0, 0);
1795 // we start with the whole screen area
1796 const Region bounds(hw->getBounds());
1798 // we remove the scissor part
1799 // we're left with the letterbox region
1800 // (common case is that letterbox ends-up being empty)
1801 const Region letterbox(bounds.subtract(hw->getScissor()));
1803 // compute the area to clear
1804 Region region(hw->undefinedRegion.merge(letterbox));
1806 // but limit it to the dirty region
1807 region.andSelf(dirty);
1809 // screen is already cleared here
1810 if (!region.isEmpty()) {
1811 // can happen with SurfaceView
1812 drawWormhole(hw, region);
1816 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
1817 // just to be on the safe side, we don't set the
1818 // scissor on the main display. It should never be needed
1819 // anyways (though in theory it could since the API allows it).
1820 const Rect& bounds(hw->getBounds());
1821 const Rect& scissor(hw->getScissor());
1822 if (scissor != bounds) {
1823 // scissor doesn't match the screen's dimensions, so we
1824 // need to clear everything outside of it and enable
1825 // the GL scissor so we don't draw anything where we shouldn't
1827 // enable scissor for this frame
1828 const uint32_t height = hw->getHeight();
1829 engine.setScissor(scissor.left, height - scissor.bottom,
1830 scissor.getWidth(), scissor.getHeight());
1836 * and then, render the layers targeted at the framebuffer
1839 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
1840 const size_t count = layers.size();
1841 const Transform& tr = hw->getTransform();
1843 // we're using h/w composer
1844 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1845 const sp<Layer>& layer(layers[i]);
1846 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1847 if (!clip.isEmpty()) {
1848 switch (cur->getCompositionType()) {
1849 case HWC_CURSOR_OVERLAY:
1851 const Layer::State& state(layer->getDrawingState());
1852 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1854 && layer->isOpaque(state) && (state.alpha == 0xFF)
1855 && hasGlesComposition) {
1856 // never clear the very first layer since we're
1857 // guaranteed the FB is already cleared
1858 layer->clearWithOpenGL(hw, clip);
1862 case HWC_FRAMEBUFFER: {
1863 layer->draw(hw, clip);
1866 case HWC_FRAMEBUFFER_TARGET: {
1867 // this should not happen as the iterator shouldn't
1868 // let us get there.
1869 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
1874 layer->setAcquireFence(hw, *cur);
1877 // we're not using h/w composer
1878 for (size_t i=0 ; i<count ; ++i) {
1879 const sp<Layer>& layer(layers[i]);
1880 const Region clip(dirty.intersect(
1881 tr.transform(layer->visibleRegion)));
1882 if (!clip.isEmpty()) {
1883 layer->draw(hw, clip);
1888 // disable scissor at the end of the frame
1889 engine.disableScissor();
1893 void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
1894 const int32_t height = hw->getHeight();
1895 RenderEngine& engine(getRenderEngine());
1896 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
1899 void SurfaceFlinger::addClientLayer(const sp<Client>& client,
1900 const sp<IBinder>& handle,
1901 const sp<IGraphicBufferProducer>& gbc,
1902 const sp<Layer>& lbc)
1904 // attach this layer to the client
1905 client->attachLayer(handle, lbc);
1907 // add this layer to the current state list
1908 Mutex::Autolock _l(mStateLock);
1909 mCurrentState.layersSortedByZ.add(lbc);
1910 mGraphicBufferProducerList.add(gbc->asBinder());
1913 status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
1914 Mutex::Autolock _l(mStateLock);
1915 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
1917 mLayersPendingRemoval.push(layer);
1918 mLayersRemoved = true;
1919 setTransactionFlags(eTransactionNeeded);
1922 return status_t(index);
1925 uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
1926 return android_atomic_release_load(&mTransactionFlags);
1929 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
1930 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1933 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
1934 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1935 if ((old & flags)==0) { // wake the server up
1936 signalTransaction();
1941 void SurfaceFlinger::setTransactionState(
1942 const Vector<ComposerState>& state,
1943 const Vector<DisplayState>& displays,
1947 Mutex::Autolock _l(mStateLock);
1948 uint32_t transactionFlags = 0;
1950 if (flags & eAnimation) {
1951 // For window updates that are part of an animation we must wait for
1952 // previous animation "frames" to be handled.
1953 while (mAnimTransactionPending) {
1954 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1955 if (CC_UNLIKELY(err != NO_ERROR)) {
1956 // just in case something goes wrong in SF, return to the
1957 // caller after a few seconds.
1958 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
1959 "waiting for previous animation frame");
1960 mAnimTransactionPending = false;
1966 size_t count = displays.size();
1967 for (size_t i=0 ; i<count ; i++) {
1968 const DisplayState& s(displays[i]);
1969 transactionFlags |= setDisplayStateLocked(s);
1972 count = state.size();
1973 for (size_t i=0 ; i<count ; i++) {
1974 const ComposerState& s(state[i]);
1975 // Here we need to check that the interface we're given is indeed
1976 // one of our own. A malicious client could give us a NULL
1977 // IInterface, or one of its own or even one of our own but a
1978 // different type. All these situations would cause us to crash.
1980 // NOTE: it would be better to use RTTI as we could directly check
1981 // that we have a Client*. however, RTTI is disabled in Android.
1982 if (s.client != NULL) {
1983 sp<IBinder> binder = s.client->asBinder();
1984 if (binder != NULL) {
1985 String16 desc(binder->getInterfaceDescriptor());
1986 if (desc == ISurfaceComposerClient::descriptor) {
1987 sp<Client> client( static_cast<Client *>(s.client.get()) );
1988 transactionFlags |= setClientStateLocked(client, s.state);
1994 if (transactionFlags) {
1995 // this triggers the transaction
1996 setTransactionFlags(transactionFlags);
1998 // if this is a synchronous transaction, wait for it to take effect
1999 // before returning.
2000 if (flags & eSynchronous) {
2001 mTransactionPending = true;
2003 if (flags & eAnimation) {
2004 mAnimTransactionPending = true;
2006 while (mTransactionPending) {
2007 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2008 if (CC_UNLIKELY(err != NO_ERROR)) {
2009 // just in case something goes wrong in SF, return to the
2010 // called after a few seconds.
2011 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2012 mTransactionPending = false;
2019 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2021 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2026 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2027 if (disp.isValid()) {
2028 const uint32_t what = s.what;
2029 if (what & DisplayState::eSurfaceChanged) {
2030 if (disp.surface->asBinder() != s.surface->asBinder()) {
2031 disp.surface = s.surface;
2032 flags |= eDisplayTransactionNeeded;
2035 if (what & DisplayState::eLayerStackChanged) {
2036 if (disp.layerStack != s.layerStack) {
2037 disp.layerStack = s.layerStack;
2038 flags |= eDisplayTransactionNeeded;
2041 if (what & DisplayState::eDisplayProjectionChanged) {
2042 if (disp.orientation != s.orientation) {
2043 disp.orientation = s.orientation;
2044 flags |= eDisplayTransactionNeeded;
2046 if (disp.frame != s.frame) {
2047 disp.frame = s.frame;
2048 flags |= eDisplayTransactionNeeded;
2050 if (disp.viewport != s.viewport) {
2051 disp.viewport = s.viewport;
2052 flags |= eDisplayTransactionNeeded;
2055 if (what & DisplayState::eDisplaySizeChanged) {
2056 if (disp.width != s.width) {
2057 disp.width = s.width;
2058 flags |= eDisplayTransactionNeeded;
2060 if (disp.height != s.height) {
2061 disp.height = s.height;
2062 flags |= eDisplayTransactionNeeded;
2069 uint32_t SurfaceFlinger::setClientStateLocked(
2070 const sp<Client>& client,
2071 const layer_state_t& s)
2074 sp<Layer> layer(client->getLayerUser(s.surface));
2076 const uint32_t what = s.what;
2077 if (what & layer_state_t::ePositionChanged) {
2078 if (layer->setPosition(s.x, s.y))
2079 flags |= eTraversalNeeded;
2081 if (what & layer_state_t::eLayerChanged) {
2082 // NOTE: index needs to be calculated before we update the state
2083 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2084 if (layer->setLayer(s.z)) {
2085 mCurrentState.layersSortedByZ.removeAt(idx);
2086 mCurrentState.layersSortedByZ.add(layer);
2087 // we need traversal (state changed)
2088 // AND transaction (list changed)
2089 flags |= eTransactionNeeded|eTraversalNeeded;
2092 if (what & layer_state_t::eSizeChanged) {
2093 if (layer->setSize(s.w, s.h)) {
2094 flags |= eTraversalNeeded;
2097 if (what & layer_state_t::eAlphaChanged) {
2098 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2099 flags |= eTraversalNeeded;
2101 if (what & layer_state_t::eMatrixChanged) {
2102 if (layer->setMatrix(s.matrix))
2103 flags |= eTraversalNeeded;
2105 if (what & layer_state_t::eTransparentRegionChanged) {
2106 if (layer->setTransparentRegionHint(s.transparentRegion))
2107 flags |= eTraversalNeeded;
2109 if ((what & layer_state_t::eVisibilityChanged) ||
2110 (what & layer_state_t::eOpacityChanged)) {
2111 // TODO: should we just use an eFlagsChanged for this?
2112 if (layer->setFlags(s.flags, s.mask))
2113 flags |= eTraversalNeeded;
2115 if (what & layer_state_t::eCropChanged) {
2116 if (layer->setCrop(s.crop))
2117 flags |= eTraversalNeeded;
2119 if (what & layer_state_t::eLayerStackChanged) {
2120 // NOTE: index needs to be calculated before we update the state
2121 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2122 if (layer->setLayerStack(s.layerStack)) {
2123 mCurrentState.layersSortedByZ.removeAt(idx);
2124 mCurrentState.layersSortedByZ.add(layer);
2125 // we need traversal (state changed)
2126 // AND transaction (list changed)
2127 flags |= eTransactionNeeded|eTraversalNeeded;
2134 status_t SurfaceFlinger::createLayer(
2135 const String8& name,
2136 const sp<Client>& client,
2137 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2138 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
2140 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
2141 if (int32_t(w|h) < 0) {
2142 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2147 status_t result = NO_ERROR;
2151 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2152 case ISurfaceComposerClient::eFXSurfaceNormal:
2153 result = createNormalLayer(client,
2154 name, w, h, flags, format,
2155 handle, gbp, &layer);
2157 case ISurfaceComposerClient::eFXSurfaceDim:
2158 result = createDimLayer(client,
2160 handle, gbp, &layer);
2167 if (result == NO_ERROR) {
2168 addClientLayer(client, *handle, *gbp, layer);
2169 setTransactionFlags(eTransactionNeeded);
2174 status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2175 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2176 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2178 // initialize the surfaces
2180 case PIXEL_FORMAT_TRANSPARENT:
2181 case PIXEL_FORMAT_TRANSLUCENT:
2182 format = PIXEL_FORMAT_RGBA_8888;
2184 case PIXEL_FORMAT_OPAQUE:
2185 format = PIXEL_FORMAT_RGBX_8888;
2189 *outLayer = new Layer(this, client, name, w, h, flags);
2190 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2191 if (err == NO_ERROR) {
2192 *handle = (*outLayer)->getHandle();
2193 *gbp = (*outLayer)->getProducer();
2196 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2200 status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2201 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2202 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2204 *outLayer = new LayerDim(this, client, name, w, h, flags);
2205 *handle = (*outLayer)->getHandle();
2206 *gbp = (*outLayer)->getProducer();
2210 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2212 // called by the window manager when it wants to remove a Layer
2213 status_t err = NO_ERROR;
2214 sp<Layer> l(client->getLayerUser(handle));
2216 err = removeLayer(l);
2217 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2218 "error removing layer=%p (%s)", l.get(), strerror(-err));
2223 status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2225 // called by ~LayerCleaner() when all references to the IBinder (handle)
2227 status_t err = NO_ERROR;
2228 sp<Layer> l(layer.promote());
2230 err = removeLayer(l);
2231 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2232 "error removing layer=%p (%s)", l.get(), strerror(-err));
2237 // ---------------------------------------------------------------------------
2239 void SurfaceFlinger::onInitializeDisplays() {
2240 // reset screen orientation and use primary layer stack
2241 Vector<ComposerState> state;
2242 Vector<DisplayState> displays;
2244 d.what = DisplayState::eDisplayProjectionChanged |
2245 DisplayState::eLayerStackChanged;
2246 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2248 d.orientation = DisplayState::eOrientationDefault;
2249 d.frame.makeInvalid();
2250 d.viewport.makeInvalid();
2254 setTransactionState(state, displays, 0);
2255 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2257 const nsecs_t period =
2258 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2259 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2262 void SurfaceFlinger::initializeDisplays() {
2263 class MessageScreenInitialized : public MessageBase {
2264 SurfaceFlinger* flinger;
2266 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2267 virtual bool handler() {
2268 flinger->onInitializeDisplays();
2272 sp<MessageBase> msg = new MessageScreenInitialized(this);
2273 postMessageAsync(msg); // we may be called from main thread, use async message
2276 void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2278 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2280 int32_t type = hw->getDisplayType();
2281 int currentMode = hw->getPowerMode();
2283 if (mode == currentMode) {
2284 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2288 hw->setPowerMode(mode);
2289 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2290 ALOGW("Trying to set power mode for virtual display");
2294 if (currentMode == HWC_POWER_MODE_OFF) {
2295 getHwComposer().setPowerMode(type, mode);
2296 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2297 // FIXME: eventthread only knows about the main display right now
2298 mEventThread->onScreenAcquired();
2299 resyncToHardwareVsync(true);
2302 mVisibleRegionsDirty = true;
2303 repaintEverything();
2304 } else if (mode == HWC_POWER_MODE_OFF) {
2305 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2306 disableHardwareVsync(true); // also cancels any in-progress resync
2308 // FIXME: eventthread only knows about the main display right now
2309 mEventThread->onScreenReleased();
2312 getHwComposer().setPowerMode(type, mode);
2313 mVisibleRegionsDirty = true;
2314 // from this point on, SF will stop drawing on this display
2316 getHwComposer().setPowerMode(type, mode);
2320 void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2321 class MessageSetPowerMode: public MessageBase {
2322 SurfaceFlinger& mFlinger;
2323 sp<IBinder> mDisplay;
2326 MessageSetPowerMode(SurfaceFlinger& flinger,
2327 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2328 mDisplay(disp) { mMode = mode; }
2329 virtual bool handler() {
2330 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2332 ALOGE("Attempt to set power mode = %d for null display %p",
2333 mMode, mDisplay.get());
2334 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2335 ALOGW("Attempt to set power mode = %d for virtual display",
2338 mFlinger.setPowerModeInternal(hw, mMode);
2343 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2344 postMessageSync(msg);
2347 // ---------------------------------------------------------------------------
2349 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2353 IPCThreadState* ipc = IPCThreadState::self();
2354 const int pid = ipc->getCallingPid();
2355 const int uid = ipc->getCallingUid();
2356 if ((uid != AID_SHELL) &&
2357 !PermissionCache::checkPermission(sDump, pid, uid)) {
2358 result.appendFormat("Permission Denial: "
2359 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2361 // Try to get the main lock, but don't insist if we can't
2362 // (this would indicate SF is stuck, but we want to be able to
2363 // print something in dumpsys).
2365 while (mStateLock.tryLock()<0 && --retry>=0) {
2368 const bool locked(retry >= 0);
2371 "SurfaceFlinger appears to be unresponsive, "
2372 "dumping anyways (no locks held)\n");
2375 bool dumpAll = true;
2377 size_t numArgs = args.size();
2379 if ((index < numArgs) &&
2380 (args[index] == String16("--list"))) {
2382 listLayersLocked(args, index, result);
2386 if ((index < numArgs) &&
2387 (args[index] == String16("--latency"))) {
2389 dumpStatsLocked(args, index, result);
2393 if ((index < numArgs) &&
2394 (args[index] == String16("--latency-clear"))) {
2396 clearStatsLocked(args, index, result);
2400 if ((index < numArgs) &&
2401 (args[index] == String16("--dispsync"))) {
2403 mPrimaryDispSync.dump(result);
2409 dumpAllLocked(args, index, result);
2413 mStateLock.unlock();
2416 write(fd, result.string(), result.size());
2420 void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2421 size_t& /* index */, String8& result) const
2423 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2424 const size_t count = currentLayers.size();
2425 for (size_t i=0 ; i<count ; i++) {
2426 const sp<Layer>& layer(currentLayers[i]);
2427 result.appendFormat("%s\n", layer->getName().string());
2431 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2432 String8& result) const
2435 if (index < args.size()) {
2436 name = String8(args[index]);
2440 const nsecs_t period =
2441 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2442 result.appendFormat("%" PRId64 "\n", period);
2444 if (name.isEmpty()) {
2445 mAnimFrameTracker.dumpStats(result);
2447 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2448 const size_t count = currentLayers.size();
2449 for (size_t i=0 ; i<count ; i++) {
2450 const sp<Layer>& layer(currentLayers[i]);
2451 if (name == layer->getName()) {
2452 layer->dumpFrameStats(result);
2458 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2459 String8& /* result */)
2462 if (index < args.size()) {
2463 name = String8(args[index]);
2467 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2468 const size_t count = currentLayers.size();
2469 for (size_t i=0 ; i<count ; i++) {
2470 const sp<Layer>& layer(currentLayers[i]);
2471 if (name.isEmpty() || (name == layer->getName())) {
2472 layer->clearFrameStats();
2476 mAnimFrameTracker.clearStats();
2479 // This should only be called from the main thread. Otherwise it would need
2480 // the lock and should use mCurrentState rather than mDrawingState.
2481 void SurfaceFlinger::logFrameStats() {
2482 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2483 const size_t count = drawingLayers.size();
2484 for (size_t i=0 ; i<count ; i++) {
2485 const sp<Layer>& layer(drawingLayers[i]);
2486 layer->logFrameStats();
2489 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2492 /*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2494 static const char* config =
2496 #ifdef HAS_CONTEXT_PRIORITY
2497 " HAS_CONTEXT_PRIORITY"
2499 #ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2500 " NEVER_DEFAULT_TO_ASYNC_MODE"
2502 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2503 " TARGET_DISABLE_TRIPLE_BUFFERING"
2506 result.append(config);
2509 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2510 String8& result) const
2512 bool colorize = false;
2513 if (index < args.size()
2514 && (args[index] == String16("--color"))) {
2519 Colorizer colorizer(colorize);
2521 // figure out if we're stuck somewhere
2522 const nsecs_t now = systemTime();
2523 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2524 const nsecs_t inTransaction(mDebugInTransaction);
2525 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2526 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2529 * Dump library configuration.
2532 colorizer.bold(result);
2533 result.append("Build configuration:");
2534 colorizer.reset(result);
2535 appendSfConfigString(result);
2536 appendUiConfigString(result);
2537 appendGuiConfigString(result);
2538 result.append("\n");
2540 colorizer.bold(result);
2541 result.append("Sync configuration: ");
2542 colorizer.reset(result);
2543 result.append(SyncFeatures::getInstance().toString());
2544 result.append("\n");
2546 colorizer.bold(result);
2547 result.append("DispSync configuration: ");
2548 colorizer.reset(result);
2549 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2550 "present offset %d ns (refresh %" PRId64 " ns)",
2551 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
2552 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
2553 result.append("\n");
2556 * Dump the visible layer list
2558 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2559 const size_t count = currentLayers.size();
2560 colorizer.bold(result);
2561 result.appendFormat("Visible layers (count = %zu)\n", count);
2562 colorizer.reset(result);
2563 for (size_t i=0 ; i<count ; i++) {
2564 const sp<Layer>& layer(currentLayers[i]);
2565 layer->dump(result, colorizer);
2569 * Dump Display state
2572 colorizer.bold(result);
2573 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
2574 colorizer.reset(result);
2575 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2576 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2581 * Dump SurfaceFlinger global state
2584 colorizer.bold(result);
2585 result.append("SurfaceFlinger global state:\n");
2586 colorizer.reset(result);
2588 HWComposer& hwc(getHwComposer());
2589 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2591 colorizer.bold(result);
2592 result.appendFormat("EGL implementation : %s\n",
2593 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2594 colorizer.reset(result);
2595 result.appendFormat("%s\n",
2596 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2598 mRenderEngine->dump(result);
2600 hw->undefinedRegion.dump(result, "undefinedRegion");
2601 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2602 hw->getOrientation(), hw->isDisplayOn());
2603 result.appendFormat(
2604 " last eglSwapBuffers() time: %f us\n"
2605 " last transaction time : %f us\n"
2606 " transaction-flags : %08x\n"
2607 " refresh-rate : %f fps\n"
2610 " gpu_to_cpu_unsupported : %d\n"
2612 mLastSwapBufferTime/1000.0,
2613 mLastTransactionTime/1000.0,
2615 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2616 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2617 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2618 !mGpuToCpuSupported);
2620 result.appendFormat(" eglSwapBuffers time: %f us\n",
2621 inSwapBuffersDuration/1000.0);
2623 result.appendFormat(" transaction time: %f us\n",
2624 inTransactionDuration/1000.0);
2629 mEventThread->dump(result);
2632 * Dump HWComposer state
2634 colorizer.bold(result);
2635 result.append("h/w composer state:\n");
2636 colorizer.reset(result);
2637 result.appendFormat(" h/w composer %s and %s\n",
2638 hwc.initCheck()==NO_ERROR ? "present" : "not present",
2639 (mDebugDisableHWC || mDebugRegion || mDaltonize
2640 || mHasColorMatrix) ? "disabled" : "enabled");
2644 * Dump gralloc state
2646 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2650 const Vector< sp<Layer> >&
2651 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2652 // Note: mStateLock is held here
2654 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2655 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2656 dpy = mDisplays.keyAt(i);
2661 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2662 // Just use the primary display so we have something to return
2663 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2665 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2668 bool SurfaceFlinger::startDdmConnection()
2670 void* libddmconnection_dso =
2671 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2672 if (!libddmconnection_dso) {
2675 void (*DdmConnection_start)(const char* name);
2676 DdmConnection_start =
2677 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
2678 if (!DdmConnection_start) {
2679 dlclose(libddmconnection_dso);
2682 (*DdmConnection_start)(getServiceName());
2686 status_t SurfaceFlinger::onTransact(
2687 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2690 case CREATE_CONNECTION:
2691 case CREATE_DISPLAY:
2692 case SET_TRANSACTION_STATE:
2694 case CLEAR_ANIMATION_FRAME_STATS:
2695 case GET_ANIMATION_FRAME_STATS:
2696 case SET_POWER_MODE:
2698 // codes that require permission check
2699 IPCThreadState* ipc = IPCThreadState::self();
2700 const int pid = ipc->getCallingPid();
2701 const int uid = ipc->getCallingUid();
2702 if ((uid != AID_GRAPHICS) &&
2703 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2704 ALOGE("Permission Denial: "
2705 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2706 return PERMISSION_DENIED;
2710 case CAPTURE_SCREEN:
2712 // codes that require permission check
2713 IPCThreadState* ipc = IPCThreadState::self();
2714 const int pid = ipc->getCallingPid();
2715 const int uid = ipc->getCallingUid();
2716 if ((uid != AID_GRAPHICS) &&
2717 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2718 ALOGE("Permission Denial: "
2719 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2720 return PERMISSION_DENIED;
2726 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2727 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2728 CHECK_INTERFACE(ISurfaceComposer, data, reply);
2729 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2730 IPCThreadState* ipc = IPCThreadState::self();
2731 const int pid = ipc->getCallingPid();
2732 const int uid = ipc->getCallingUid();
2733 ALOGE("Permission Denial: "
2734 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2735 return PERMISSION_DENIED;
2739 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2740 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2742 case 1002: // SHOW_UPDATES
2743 n = data.readInt32();
2744 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2745 invalidateHwcGeometry();
2746 repaintEverything();
2748 case 1004:{ // repaint everything
2749 repaintEverything();
2752 case 1005:{ // force transaction
2753 setTransactionFlags(
2755 eDisplayTransactionNeeded|
2759 case 1006:{ // send empty update
2763 case 1008: // toggle use of hw composer
2764 n = data.readInt32();
2765 mDebugDisableHWC = n ? 1 : 0;
2766 invalidateHwcGeometry();
2767 repaintEverything();
2769 case 1009: // toggle use of transform hint
2770 n = data.readInt32();
2771 mDebugDisableTransformHint = n ? 1 : 0;
2772 invalidateHwcGeometry();
2773 repaintEverything();
2775 case 1010: // interrogate.
2776 reply->writeInt32(0);
2777 reply->writeInt32(0);
2778 reply->writeInt32(mDebugRegion);
2779 reply->writeInt32(0);
2780 reply->writeInt32(mDebugDisableHWC);
2783 Mutex::Autolock _l(mStateLock);
2784 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2785 reply->writeInt32(hw->getPageFlipCount());
2790 n = data.readInt32();
2792 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
2793 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
2794 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
2797 mDaltonizer.setMode(Daltonizer::correction);
2799 mDaltonizer.setMode(Daltonizer::simulation);
2802 invalidateHwcGeometry();
2803 repaintEverything();
2807 // apply a color matrix
2808 n = data.readInt32();
2809 mHasColorMatrix = n ? 1 : 0;
2811 // color matrix is sent as mat3 matrix followed by vec3
2812 // offset, then packed into a mat4 where the last row is
2813 // the offset and extra values are 0
2814 for (size_t i = 0 ; i < 4; i++) {
2815 for (size_t j = 0; j < 4; j++) {
2816 mColorMatrix[i][j] = data.readFloat();
2820 mColorMatrix = mat4();
2822 invalidateHwcGeometry();
2823 repaintEverything();
2826 // This is an experimental interface
2827 // Needs to be shifted to proper binder interface when we productize
2829 n = data.readInt32();
2830 mPrimaryDispSync.setRefreshSkipCount(n);
2838 void SurfaceFlinger::repaintEverything() {
2839 android_atomic_or(1, &mRepaintEverything);
2840 signalTransaction();
2843 // ---------------------------------------------------------------------------
2844 // Capture screen into an IGraphiBufferProducer
2845 // ---------------------------------------------------------------------------
2847 /* The code below is here to handle b/8734824
2849 * We create a IGraphicBufferProducer wrapper that forwards all calls
2850 * from the surfaceflinger thread to the calling binder thread, where they
2851 * are executed. This allows the calling thread in the calling process to be
2852 * reused and not depend on having "enough" binder threads to handle the
2855 class GraphicProducerWrapper : public BBinder, public MessageHandler {
2856 /* Parts of GraphicProducerWrapper are run on two different threads,
2857 * communicating by sending messages via Looper but also by shared member
2858 * data. Coherence maintenance is subtle and in places implicit (ugh).
2860 * Don't rely on Looper's sendMessage/handleMessage providing
2861 * release/acquire semantics for any data not actually in the Message.
2862 * Data going from surfaceflinger to binder threads needs to be
2863 * synchronized explicitly.
2865 * Barrier open/wait do provide release/acquire semantics. This provides
2866 * implicit synchronization for data coming back from binder to
2867 * surfaceflinger threads.
2870 sp<IGraphicBufferProducer> impl;
2886 * Called on surfaceflinger thread. This is called by our "fake"
2887 * BpGraphicBufferProducer. We package the data and reply Parcel and
2888 * forward them to the binder thread.
2890 virtual status_t transact(uint32_t code,
2891 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
2894 this->reply = reply;
2896 // if we've exited, we run the message synchronously right here.
2897 // note (JH): as far as I can tell from looking at the code, this
2898 // never actually happens. if it does, i'm not sure if it happens
2899 // on the surfaceflinger or binder thread.
2900 handleMessage(Message(MSG_API_CALL));
2903 // Prevent stores to this->{code, data, reply} from being
2904 // reordered later than the construction of Message.
2905 atomic_thread_fence(memory_order_release);
2906 looper->sendMessage(this, Message(MSG_API_CALL));
2913 * here we run on the binder thread. All we've got to do is
2914 * call the real BpGraphicBufferProducer.
2916 virtual void handleMessage(const Message& message) {
2917 int what = message.what;
2918 // Prevent reads below from happening before the read from Message
2919 atomic_thread_fence(memory_order_acquire);
2920 if (what == MSG_API_CALL) {
2921 result = impl->asBinder()->transact(code, data[0], reply);
2923 } else if (what == MSG_EXIT) {
2924 exitRequested = true;
2929 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
2931 looper(new Looper(true)),
2933 exitRequested(false)
2937 status_t waitForResponse() {
2939 looper->pollOnce(-1);
2940 } while (!exitRequested);
2945 void exit(status_t result) {
2946 this->result = result;
2948 // Ensure this->result is visible to the binder thread before it
2949 // handles the message.
2950 atomic_thread_fence(memory_order_release);
2951 looper->sendMessage(this, Message(MSG_EXIT));
2956 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
2957 const sp<IGraphicBufferProducer>& producer,
2958 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
2959 uint32_t minLayerZ, uint32_t maxLayerZ,
2960 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
2962 if (CC_UNLIKELY(display == 0))
2965 if (CC_UNLIKELY(producer == 0))
2968 // if we have secure windows on this display, never allow the screen capture
2969 // unless the producer interface is local (i.e.: we can take a screenshot for
2971 if (!producer->asBinder()->localBinder()) {
2972 Mutex::Autolock _l(mStateLock);
2973 sp<const DisplayDevice> hw(getDisplayDevice(display));
2974 if (hw->getSecureLayerVisible()) {
2975 ALOGW("FB is protected: PERMISSION_DENIED");
2976 return PERMISSION_DENIED;
2980 // Convert to surfaceflinger's internal rotation type.
2981 Transform::orientation_flags rotationFlags;
2983 case ISurfaceComposer::eRotateNone:
2984 rotationFlags = Transform::ROT_0;
2986 case ISurfaceComposer::eRotate90:
2987 rotationFlags = Transform::ROT_90;
2989 case ISurfaceComposer::eRotate180:
2990 rotationFlags = Transform::ROT_180;
2992 case ISurfaceComposer::eRotate270:
2993 rotationFlags = Transform::ROT_270;
2996 rotationFlags = Transform::ROT_0;
2997 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3001 class MessageCaptureScreen : public MessageBase {
3002 SurfaceFlinger* flinger;
3003 sp<IBinder> display;
3004 sp<IGraphicBufferProducer> producer;
3006 uint32_t reqWidth, reqHeight;
3007 uint32_t minLayerZ,maxLayerZ;
3008 bool useIdentityTransform;
3009 Transform::orientation_flags rotation;
3012 MessageCaptureScreen(SurfaceFlinger* flinger,
3013 const sp<IBinder>& display,
3014 const sp<IGraphicBufferProducer>& producer,
3015 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3016 uint32_t minLayerZ, uint32_t maxLayerZ,
3017 bool useIdentityTransform, Transform::orientation_flags rotation)
3018 : flinger(flinger), display(display), producer(producer),
3019 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3020 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3021 useIdentityTransform(useIdentityTransform),
3023 result(PERMISSION_DENIED)
3026 status_t getResult() const {
3029 virtual bool handler() {
3030 Mutex::Autolock _l(flinger->mStateLock);
3031 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3032 result = flinger->captureScreenImplLocked(hw, producer,
3033 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3034 useIdentityTransform, rotation);
3035 static_cast<GraphicProducerWrapper*>(producer->asBinder().get())->exit(result);
3040 // make sure to process transactions before screenshots -- a transaction
3041 // might already be pending but scheduled for VSYNC; this guarantees we
3042 // will handle it before the screenshot. When VSYNC finally arrives
3043 // the scheduled transaction will be a no-op. If no transactions are
3044 // scheduled at this time, this will end-up being a no-op as well.
3045 mEventQueue.invalidateTransactionNow();
3047 // this creates a "fake" BBinder which will serve as a "fake" remote
3048 // binder to receive the marshaled calls and forward them to the
3049 // real remote (a BpGraphicBufferProducer)
3050 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3052 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3053 // which does the marshaling work forwards to our "fake remote" above.
3054 sp<MessageBase> msg = new MessageCaptureScreen(this,
3055 display, IGraphicBufferProducer::asInterface( wrapper ),
3056 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3057 useIdentityTransform, rotationFlags);
3059 status_t res = postMessageAsync(msg);
3060 if (res == NO_ERROR) {
3061 res = wrapper->waitForResponse();
3067 void SurfaceFlinger::renderScreenImplLocked(
3068 const sp<const DisplayDevice>& hw,
3069 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3070 uint32_t minLayerZ, uint32_t maxLayerZ,
3071 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3074 RenderEngine& engine(getRenderEngine());
3076 // get screen geometry
3077 const uint32_t hw_w = hw->getWidth();
3078 const uint32_t hw_h = hw->getHeight();
3079 const bool filtering = reqWidth != hw_w || reqWidth != hw_h;
3081 // if a default or invalid sourceCrop is passed in, set reasonable values
3082 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3083 !sourceCrop.isValid()) {
3084 sourceCrop.setLeftTop(Point(0, 0));
3085 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3088 // ensure that sourceCrop is inside screen
3089 if (sourceCrop.left < 0) {
3090 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3092 if (sourceCrop.right > hw_w) {
3093 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3095 if (sourceCrop.top < 0) {
3096 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3098 if (sourceCrop.bottom > hw_h) {
3099 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3102 // make sure to clear all GL error flags
3103 engine.checkErrors();
3105 // set-up our viewport
3106 engine.setViewportAndProjection(
3107 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3108 engine.disableTexturing();
3110 // redraw the screen entirely...
3111 engine.clearWithColor(0, 0, 0, 1);
3113 const LayerVector& layers( mDrawingState.layersSortedByZ );
3114 const size_t count = layers.size();
3115 for (size_t i=0 ; i<count ; ++i) {
3116 const sp<Layer>& layer(layers[i]);
3117 const Layer::State& state(layer->getDrawingState());
3118 if (state.layerStack == hw->getLayerStack()) {
3119 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3120 if (layer->isVisible()) {
3121 if (filtering) layer->setFiltering(true);
3122 layer->draw(hw, useIdentityTransform);
3123 if (filtering) layer->setFiltering(false);
3129 // compositionComplete is needed for older driver
3130 hw->compositionComplete();
3131 hw->setViewportAndProjection();
3135 status_t SurfaceFlinger::captureScreenImplLocked(
3136 const sp<const DisplayDevice>& hw,
3137 const sp<IGraphicBufferProducer>& producer,
3138 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3139 uint32_t minLayerZ, uint32_t maxLayerZ,
3140 bool useIdentityTransform, Transform::orientation_flags rotation)
3144 // get screen geometry
3145 const uint32_t hw_w = hw->getWidth();
3146 const uint32_t hw_h = hw->getHeight();
3148 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3149 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3150 reqWidth, reqHeight, hw_w, hw_h);
3154 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3155 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3157 // create a surface (because we're a producer, and we need to
3158 // dequeue/queue a buffer)
3159 sp<Surface> sur = new Surface(producer, false);
3160 ANativeWindow* window = sur.get();
3162 status_t result = NO_ERROR;
3163 if (native_window_api_connect(window, NATIVE_WINDOW_API_EGL) == NO_ERROR) {
3164 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3165 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3168 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3169 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3170 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3171 err |= native_window_set_usage(window, usage);
3173 if (err == NO_ERROR) {
3174 ANativeWindowBuffer* buffer;
3175 /* TODO: Once we have the sync framework everywhere this can use
3176 * server-side waits on the fence that dequeueBuffer returns.
3178 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3179 if (result == NO_ERROR) {
3181 // create an EGLImage from the buffer so we can later
3182 // turn it into a texture
3183 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3184 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3185 if (image != EGL_NO_IMAGE_KHR) {
3186 // this binds the given EGLImage as a framebuffer for the
3187 // duration of this scope.
3188 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3189 if (imageBond.getStatus() == NO_ERROR) {
3190 // this will in fact render into our dequeued buffer
3191 // via an FBO, which means we didn't have to create
3192 // an EGLSurface and therefore we're not
3193 // dependent on the context's EGLConfig.
3194 renderScreenImplLocked(
3195 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3196 useIdentityTransform, rotation);
3198 // Attempt to create a sync khr object that can produce a sync point. If that
3199 // isn't available, create a non-dupable sync object in the fallback path and
3200 // wait on it directly.
3202 if (!DEBUG_SCREENSHOTS) {
3203 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3205 sync = EGL_NO_SYNC_KHR;
3207 if (sync != EGL_NO_SYNC_KHR) {
3209 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3210 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3211 ALOGW("captureScreen: failed to dup sync khr object");
3214 eglDestroySyncKHR(mEGLDisplay, sync);
3217 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3218 if (sync != EGL_NO_SYNC_KHR) {
3219 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3220 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3221 EGLint eglErr = eglGetError();
3222 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3223 ALOGW("captureScreen: fence wait timed out");
3225 ALOGW_IF(eglErr != EGL_SUCCESS,
3226 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3228 eglDestroySyncKHR(mEGLDisplay, sync);
3230 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3233 if (DEBUG_SCREENSHOTS) {
3234 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3235 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3236 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3237 hw, minLayerZ, maxLayerZ);
3242 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3243 result = INVALID_OPERATION;
3245 // destroy our image
3246 eglDestroyImageKHR(mEGLDisplay, image);
3250 // queueBuffer takes ownership of syncFd
3251 window->queueBuffer(window, buffer, syncFd);
3256 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3262 void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3263 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3264 if (DEBUG_SCREENSHOTS) {
3265 for (size_t y=0 ; y<h ; y++) {
3266 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3267 for (size_t x=0 ; x<w ; x++) {
3268 if (p[x] != 0xFF000000) return;
3271 ALOGE("*** we just took a black screenshot ***\n"
3272 "requested minz=%d, maxz=%d, layerStack=%d",
3273 minLayerZ, maxLayerZ, hw->getLayerStack());
3274 const LayerVector& layers( mDrawingState.layersSortedByZ );
3275 const size_t count = layers.size();
3276 for (size_t i=0 ; i<count ; ++i) {
3277 const sp<Layer>& layer(layers[i]);
3278 const Layer::State& state(layer->getDrawingState());
3279 const bool visible = (state.layerStack == hw->getLayerStack())
3280 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3281 && (layer->isVisible());
3282 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3283 visible ? '+' : '-',
3284 i, layer->getName().string(), state.layerStack, state.z,
3285 layer->isVisible(), state.flags, state.alpha);
3290 // ---------------------------------------------------------------------------
3292 SurfaceFlinger::LayerVector::LayerVector() {
3295 SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3296 : SortedVector<sp<Layer> >(rhs) {
3299 int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3300 const void* rhs) const
3302 // sort layers per layer-stack, then by z-order and finally by sequence
3303 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3304 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3306 uint32_t ls = l->getCurrentState().layerStack;
3307 uint32_t rs = r->getCurrentState().layerStack;
3311 uint32_t lz = l->getCurrentState().z;
3312 uint32_t rz = r->getCurrentState().z;
3316 return l->sequence - r->sequence;
3319 // ---------------------------------------------------------------------------
3321 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3322 : type(DisplayDevice::DISPLAY_ID_INVALID), width(0), height(0) {
3325 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
3326 : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0), width(0), height(0) {
3327 viewport.makeInvalid();
3328 frame.makeInvalid();
3331 // ---------------------------------------------------------------------------
3333 }; // namespace android
3336 #if defined(__gl_h_)
3337 #error "don't include gl/gl.h in this file"
3340 #if defined(__gl2_h_)
3341 #error "don't include gl2/gl2.h in this file"