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>
27 #include <cutils/log.h>
28 #include <cutils/properties.h>
30 #include <binder/IPCThreadState.h>
31 #include <binder/IServiceManager.h>
32 #include <binder/MemoryHeapBase.h>
33 #include <binder/PermissionCache.h>
35 #include <ui/DisplayInfo.h>
37 #include <gui/BitTube.h>
38 #include <gui/BufferQueue.h>
39 #include <gui/GuiConfig.h>
40 #include <gui/IDisplayEventConnection.h>
41 #include <gui/Surface.h>
42 #include <gui/GraphicBufferAlloc.h>
44 #include <ui/GraphicBufferAllocator.h>
45 #include <ui/PixelFormat.h>
46 #include <ui/UiConfig.h>
48 #include <utils/misc.h>
49 #include <utils/String8.h>
50 #include <utils/String16.h>
51 #include <utils/StopWatch.h>
52 #include <utils/Trace.h>
54 #include <private/android_filesystem_config.h>
55 #include <private/gui/SyncFeatures.h>
59 #include "Colorizer.h"
60 #include "DdmConnection.h"
61 #include "DisplayDevice.h"
63 #include "EventControlThread.h"
64 #include "EventThread.h"
67 #include "SurfaceFlinger.h"
69 #include "DisplayHardware/FramebufferSurface.h"
70 #include "DisplayHardware/HWComposer.h"
71 #include "DisplayHardware/VirtualDisplaySurface.h"
73 #include "Effects/Daltonizer.h"
75 #include "RenderEngine/RenderEngine.h"
76 #include <cutils/compiler.h>
78 #define DISPLAY_COUNT 1
81 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
84 #define DEBUG_SCREENSHOTS false
86 EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
90 // This works around the lack of support for the sync framework on some
92 #ifdef RUNNING_WITHOUT_SYNC_FRAMEWORK
93 static const bool runningWithoutSyncFramework = true;
95 static const bool runningWithoutSyncFramework = false;
98 // This is the phase offset in nanoseconds of the software vsync event
99 // relative to the vsync event reported by HWComposer. The software vsync
100 // event is when SurfaceFlinger and Choreographer-based applications run each
103 // This phase offset allows adjustment of the minimum latency from application
104 // wake-up (by Choregographer) time to the time at which the resulting window
105 // image is displayed. This value may be either positive (after the HW vsync)
106 // or negative (before the HW vsync). Setting it to 0 will result in a
107 // minimum latency of two vsync periods because the app and SurfaceFlinger
108 // will run just after the HW vsync. Setting it to a positive number will
109 // result in the minimum latency being:
111 // (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
113 // Note that reducing this latency makes it more likely for the applications
114 // to not have their window content image ready in time. When this happens
115 // the latency will end up being an additional vsync period, and animations
116 // will hiccup. Therefore, this latency should be tuned somewhat
117 // conservatively (or at least with awareness of the trade-off being made).
118 static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
120 // This is the phase offset at which SurfaceFlinger's composition runs.
121 static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
123 // ---------------------------------------------------------------------------
125 const String16 sHardwareTest("android.permission.HARDWARE_TEST");
126 const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
127 const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
128 const String16 sDump("android.permission.DUMP");
130 // ---------------------------------------------------------------------------
132 SurfaceFlinger::SurfaceFlinger()
133 : BnSurfaceComposer(),
134 mTransactionFlags(0),
135 mTransactionPending(false),
136 mAnimTransactionPending(false),
137 mLayersRemoved(false),
138 mRepaintEverything(0),
140 mBootTime(systemTime()),
141 mVisibleRegionsDirty(false),
142 mHwWorkListDirty(false),
143 mAnimCompositionPending(false),
147 mDebugDisableTransformHint(0),
148 mDebugInSwapBuffers(0),
149 mLastSwapBufferTime(0),
150 mDebugInTransaction(0),
151 mLastTransactionTime(0),
152 mBootFinished(false),
153 mPrimaryHWVsyncEnabled(false),
154 mHWVsyncAvailable(false),
157 ALOGI("SurfaceFlinger is starting");
159 // debugging stuff...
160 char value[PROPERTY_VALUE_MAX];
162 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
163 mGpuToCpuSupported = !atoi(value);
165 property_get("debug.sf.showupdates", value, "0");
166 mDebugRegion = atoi(value);
168 property_get("debug.sf.ddms", value, "0");
169 mDebugDDMS = atoi(value);
171 if (!startDdmConnection()) {
172 // start failed, and DDMS debugging not enabled
176 ALOGI_IF(mDebugRegion, "showupdates enabled");
177 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
180 void SurfaceFlinger::onFirstRef()
182 mEventQueue.init(this);
185 SurfaceFlinger::~SurfaceFlinger()
187 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
188 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
189 eglTerminate(display);
192 void SurfaceFlinger::binderDied(const wp<IBinder>& who)
194 // the window manager died on us. prepare its eulogy.
196 // restore initial conditions (default device unblank, etc)
197 initializeDisplays();
199 // restart the boot-animation
203 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
205 sp<ISurfaceComposerClient> bclient;
206 sp<Client> client(new Client(this));
207 status_t err = client->initCheck();
208 if (err == NO_ERROR) {
214 sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
217 class DisplayToken : public BBinder {
218 sp<SurfaceFlinger> flinger;
219 virtual ~DisplayToken() {
220 // no more references, this display must be terminated
221 Mutex::Autolock _l(flinger->mStateLock);
222 flinger->mCurrentState.displays.removeItem(this);
223 flinger->setTransactionFlags(eDisplayTransactionNeeded);
226 DisplayToken(const sp<SurfaceFlinger>& flinger)
231 sp<BBinder> token = new DisplayToken(this);
233 Mutex::Autolock _l(mStateLock);
234 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
235 info.displayName = displayName;
236 info.isSecure = secure;
237 mCurrentState.displays.add(token, info);
242 void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
243 Mutex::Autolock _l(mStateLock);
245 ssize_t idx = mCurrentState.displays.indexOfKey(display);
247 ALOGW("destroyDisplay: invalid display token");
251 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
252 if (!info.isVirtualDisplay()) {
253 ALOGE("destroyDisplay called for non-virtual display");
257 mCurrentState.displays.removeItemsAt(idx);
258 setTransactionFlags(eDisplayTransactionNeeded);
261 void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
262 ALOGW_IF(mBuiltinDisplays[type],
263 "Overwriting display token for display type %d", type);
264 mBuiltinDisplays[type] = new BBinder();
265 DisplayDeviceState info(type);
266 // All non-virtual displays are currently considered secure.
267 info.isSecure = true;
268 mCurrentState.displays.add(mBuiltinDisplays[type], info);
271 sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
272 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
273 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
276 return mBuiltinDisplays[id];
279 sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
281 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
285 void SurfaceFlinger::bootFinished()
287 const nsecs_t now = systemTime();
288 const nsecs_t duration = now - mBootTime;
289 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
290 mBootFinished = true;
292 // wait patiently for the window manager death
293 const String16 name("window");
294 sp<IBinder> window(defaultServiceManager()->getService(name));
296 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
299 // stop boot animation
300 // formerly we would just kill the process, but we now ask it to exit so it
301 // can choose where to stop the animation.
302 property_set("service.bootanim.exit", "1");
305 void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
306 class MessageDestroyGLTexture : public MessageBase {
307 RenderEngine& engine;
310 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
311 : engine(engine), texture(texture) {
313 virtual bool handler() {
314 engine.deleteTextures(1, &texture);
318 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
321 status_t SurfaceFlinger::selectConfigForAttribute(
324 EGLint attribute, EGLint wanted,
325 EGLConfig* outConfig)
327 EGLConfig config = NULL;
328 EGLint numConfigs = -1, n=0;
329 eglGetConfigs(dpy, NULL, 0, &numConfigs);
330 EGLConfig* const configs = new EGLConfig[numConfigs];
331 eglChooseConfig(dpy, attrs, configs, numConfigs, &n);
334 if (attribute != EGL_NONE) {
335 for (int i=0 ; i<n ; i++) {
337 eglGetConfigAttrib(dpy, configs[i], attribute, &value);
338 if (wanted == value) {
339 *outConfig = configs[i];
345 // just pick the first one
346 *outConfig = configs[0];
352 return NAME_NOT_FOUND;
355 class EGLAttributeVector {
359 KeyedVector<Attribute, EGLint> mList;
362 Attribute(EGLint v) : v(v) { }
364 bool operator < (const Attribute& other) const {
365 // this places EGL_NONE at the end
368 if (lhs == EGL_NONE) lhs = 0x7FFFFFFF;
369 if (rhs == EGL_NONE) rhs = 0x7FFFFFFF;
374 friend class EGLAttributeVector;
375 EGLAttributeVector& v;
377 Adder(EGLAttributeVector& v, EGLint attribute)
378 : v(v), attribute(attribute) {
381 void operator = (EGLint value) {
382 if (attribute != EGL_NONE) {
383 v.mList.add(attribute, value);
386 operator EGLint () const { return v.mList[attribute]; }
389 EGLAttributeVector() {
390 mList.add(EGL_NONE, EGL_NONE);
392 void remove(EGLint attribute) {
393 if (attribute != EGL_NONE) {
394 mList.removeItem(attribute);
397 Adder operator [] (EGLint attribute) {
398 return Adder(*this, attribute);
400 EGLint operator [] (EGLint attribute) const {
401 return mList[attribute];
403 // cast-operator to (EGLint const*)
404 operator EGLint const* () const { return &mList.keyAt(0).v; }
407 status_t SurfaceFlinger::selectEGLConfig(EGLDisplay display, EGLint nativeVisualId,
408 EGLint renderableType, EGLConfig* config) {
409 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
410 // it is to be used with WIFI displays
412 EGLint wantedAttribute;
413 EGLint wantedAttributeValue;
415 EGLAttributeVector attribs;
416 if (renderableType) {
417 attribs[EGL_RENDERABLE_TYPE] = renderableType;
418 attribs[EGL_RECORDABLE_ANDROID] = EGL_TRUE;
419 attribs[EGL_SURFACE_TYPE] = EGL_WINDOW_BIT|EGL_PBUFFER_BIT;
420 attribs[EGL_FRAMEBUFFER_TARGET_ANDROID] = EGL_TRUE;
421 attribs[EGL_RED_SIZE] = 8;
422 attribs[EGL_GREEN_SIZE] = 8;
423 attribs[EGL_BLUE_SIZE] = 8;
424 wantedAttribute = EGL_NONE;
425 wantedAttributeValue = EGL_NONE;
428 // if no renderable type specified, fallback to a simplified query
429 wantedAttribute = EGL_NATIVE_VISUAL_ID;
430 wantedAttributeValue = nativeVisualId;
433 err = selectConfigForAttribute(display, attribs, wantedAttribute,
434 wantedAttributeValue, config);
435 if (err == NO_ERROR) {
437 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
438 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
443 class DispSyncSource : public VSyncSource, private DispSync::Callback {
445 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync) :
447 mPhaseOffset(phaseOffset),
448 mTraceVsync(traceVsync),
449 mDispSync(dispSync) {}
451 virtual ~DispSyncSource() {}
453 virtual void setVSyncEnabled(bool enable) {
454 // Do NOT lock the mutex here so as to avoid any mutex ordering issues
455 // with locking it in the onDispSyncEvent callback.
457 status_t err = mDispSync->addEventListener(mPhaseOffset,
458 static_cast<DispSync::Callback*>(this));
459 if (err != NO_ERROR) {
460 ALOGE("error registering vsync callback: %s (%d)",
461 strerror(-err), err);
463 ATRACE_INT("VsyncOn", 1);
465 status_t err = mDispSync->removeEventListener(
466 static_cast<DispSync::Callback*>(this));
467 if (err != NO_ERROR) {
468 ALOGE("error unregistering vsync callback: %s (%d)",
469 strerror(-err), err);
471 ATRACE_INT("VsyncOn", 0);
475 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
476 Mutex::Autolock lock(mMutex);
477 mCallback = callback;
481 virtual void onDispSyncEvent(nsecs_t when) {
482 sp<VSyncSource::Callback> callback;
484 Mutex::Autolock lock(mMutex);
485 callback = mCallback;
488 mValue = (mValue + 1) % 2;
489 ATRACE_INT("VSYNC", mValue);
493 if (callback != NULL) {
494 callback->onVSyncEvent(when);
500 const nsecs_t mPhaseOffset;
501 const bool mTraceVsync;
504 sp<VSyncSource::Callback> mCallback;
508 void SurfaceFlinger::init() {
509 ALOGI( "SurfaceFlinger's main thread ready to run. "
510 "Initializing graphics H/W...");
513 Mutex::Autolock _l(mStateLock);
515 // initialize EGL for the default display
516 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
517 eglInitialize(mEGLDisplay, NULL, NULL);
519 // Initialize the H/W composer object. There may or may not be an
520 // actual hardware composer underneath.
521 mHwc = new HWComposer(this,
522 *static_cast<HWComposer::EventHandler *>(this));
524 // First try to get an ES2 config
525 err = selectEGLConfig(mEGLDisplay, mHwc->getVisualID(), EGL_OPENGL_ES2_BIT,
528 if (err != NO_ERROR) {
529 // If ES2 fails, try ES1
530 err = selectEGLConfig(mEGLDisplay, mHwc->getVisualID(),
531 EGL_OPENGL_ES_BIT, &mEGLConfig);
534 if (err != NO_ERROR) {
535 // still didn't work, probably because we're on the emulator...
536 // try a simplified query
537 ALOGW("no suitable EGLConfig found, trying a simpler query");
538 err = selectEGLConfig(mEGLDisplay, mHwc->getVisualID(), 0, &mEGLConfig);
541 if (err != NO_ERROR) {
542 // this EGL is too lame for android
543 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
546 // print some debugging info
548 eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_RED_SIZE, &r);
549 eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_GREEN_SIZE, &g);
550 eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_BLUE_SIZE, &b);
551 eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_ALPHA_SIZE, &a);
552 ALOGI("EGL informations:");
553 ALOGI("vendor : %s", eglQueryString(mEGLDisplay, EGL_VENDOR));
554 ALOGI("version : %s", eglQueryString(mEGLDisplay, EGL_VERSION));
555 ALOGI("extensions: %s", eglQueryString(mEGLDisplay, EGL_EXTENSIONS));
556 ALOGI("Client API: %s", eglQueryString(mEGLDisplay, EGL_CLIENT_APIS)?:"Not Supported");
557 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, mEGLConfig);
559 // get a RenderEngine for the given display / config (can't fail)
560 mRenderEngine = RenderEngine::create(mEGLDisplay, mEGLConfig);
562 // retrieve the EGL context that was selected/created
563 mEGLContext = mRenderEngine->getEGLContext();
565 // figure out which format we got
566 eglGetConfigAttrib(mEGLDisplay, mEGLConfig,
567 EGL_NATIVE_VISUAL_ID, &mEGLNativeVisualId);
569 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
570 "couldn't create EGLContext");
572 // initialize our non-virtual displays
573 for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
574 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
575 // set-up the displays that are already connected
576 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
577 // All non-virtual displays are currently considered secure.
578 bool isSecure = true;
579 createBuiltinDisplayLocked(type);
580 wp<IBinder> token = mBuiltinDisplays[i];
582 sp<BufferQueue> bq = new BufferQueue(new GraphicBufferAlloc());
583 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i, bq);
584 sp<DisplayDevice> hw = new DisplayDevice(this,
585 type, allocateHwcDisplayId(type), isSecure, token,
588 if (i > DisplayDevice::DISPLAY_PRIMARY) {
589 // FIXME: currently we don't get blank/unblank requests
590 // for displays other than the main display, so we always
591 // assume a connected display is unblanked.
592 ALOGD("marking display %d as acquired/unblanked", i);
595 mDisplays.add(token, hw);
599 // make the GLContext current so that we can create textures when creating Layers
600 // (which may happens before we render something)
601 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
603 // start the EventThread
604 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
605 vsyncPhaseOffsetNs, true);
606 mEventThread = new EventThread(vsyncSrc);
607 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
608 sfVsyncPhaseOffsetNs, false);
609 mSFEventThread = new EventThread(sfVsyncSrc);
610 mEventQueue.setEventThread(mSFEventThread);
612 mEventControlThread = new EventControlThread(this);
613 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
615 // set a fake vsync period if there is no HWComposer
616 if (mHwc->initCheck() != NO_ERROR) {
617 mPrimaryDispSync.setPeriod(16666667);
620 // initialize our drawing state
621 mDrawingState = mCurrentState;
623 // set initial conditions (e.g. unblank default device)
624 initializeDisplays();
626 // start boot animation
630 int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
631 return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
632 type : mHwc->allocateDisplayId();
635 void SurfaceFlinger::startBootAnim() {
636 // start boot animation
637 property_set("service.bootanim.exit", "0");
638 property_set("ctl.start", "bootanim");
641 size_t SurfaceFlinger::getMaxTextureSize() const {
642 return mRenderEngine->getMaxTextureSize();
645 size_t SurfaceFlinger::getMaxViewportDims() const {
646 return mRenderEngine->getMaxViewportDims();
649 // ----------------------------------------------------------------------------
651 bool SurfaceFlinger::authenticateSurfaceTexture(
652 const sp<IGraphicBufferProducer>& bufferProducer) const {
653 Mutex::Autolock _l(mStateLock);
654 sp<IBinder> surfaceTextureBinder(bufferProducer->asBinder());
655 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
658 status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info) {
659 int32_t type = NAME_NOT_FOUND;
660 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
661 if (display == mBuiltinDisplays[i]) {
671 const HWComposer& hwc(getHwComposer());
672 float xdpi = hwc.getDpiX(type);
673 float ydpi = hwc.getDpiY(type);
675 // TODO: Not sure if display density should handled by SF any longer
677 static int getDensityFromProperty(char const* propName) {
678 char property[PROPERTY_VALUE_MAX];
680 if (property_get(propName, property, NULL) > 0) {
681 density = atoi(property);
686 static int getEmuDensity() {
687 return getDensityFromProperty("qemu.sf.lcd_density"); }
688 static int getBuildDensity() {
689 return getDensityFromProperty("ro.sf.lcd_density"); }
692 if (type == DisplayDevice::DISPLAY_PRIMARY) {
693 // The density of the device is provided by a build property
694 float density = Density::getBuildDensity() / 160.0f;
696 // the build doesn't provide a density -- this is wrong!
698 ALOGE("ro.sf.lcd_density must be defined as a build property");
699 density = xdpi / 160.0f;
701 if (Density::getEmuDensity()) {
702 // if "qemu.sf.lcd_density" is specified, it overrides everything
703 xdpi = ydpi = density = Density::getEmuDensity();
706 info->density = density;
708 // TODO: this needs to go away (currently needed only by webkit)
709 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
710 info->orientation = hw->getOrientation();
712 // TODO: where should this value come from?
713 static const int TV_DENSITY = 213;
714 info->density = TV_DENSITY / 160.0f;
715 info->orientation = 0;
718 info->w = hwc.getWidth(type);
719 info->h = hwc.getHeight(type);
722 info->fps = float(1e9 / hwc.getRefreshPeriod(type));
724 // All non-virtual displays are currently considered secure.
730 // ----------------------------------------------------------------------------
732 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
733 return mEventThread->createEventConnection();
736 // ----------------------------------------------------------------------------
738 void SurfaceFlinger::waitForEvent() {
739 mEventQueue.waitMessage();
742 void SurfaceFlinger::signalTransaction() {
743 mEventQueue.invalidate();
746 void SurfaceFlinger::signalLayerUpdate() {
747 mEventQueue.invalidate();
750 void SurfaceFlinger::signalRefresh() {
751 mEventQueue.refresh();
754 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
755 nsecs_t reltime, uint32_t flags) {
756 return mEventQueue.postMessage(msg, reltime);
759 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
760 nsecs_t reltime, uint32_t flags) {
761 status_t res = mEventQueue.postMessage(msg, reltime);
762 if (res == NO_ERROR) {
768 void SurfaceFlinger::run() {
774 void SurfaceFlinger::enableHardwareVsync() {
775 Mutex::Autolock _l(mHWVsyncLock);
776 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
777 mPrimaryDispSync.beginResync();
778 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
779 mEventControlThread->setVsyncEnabled(true);
780 mPrimaryHWVsyncEnabled = true;
784 void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
785 Mutex::Autolock _l(mHWVsyncLock);
788 mHWVsyncAvailable = true;
789 } else if (!mHWVsyncAvailable) {
790 ALOGE("resyncToHardwareVsync called when HW vsync unavailable");
794 const nsecs_t period =
795 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
797 mPrimaryDispSync.reset();
798 mPrimaryDispSync.setPeriod(period);
800 if (!mPrimaryHWVsyncEnabled) {
801 mPrimaryDispSync.beginResync();
802 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
803 mEventControlThread->setVsyncEnabled(true);
804 mPrimaryHWVsyncEnabled = true;
808 void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
809 Mutex::Autolock _l(mHWVsyncLock);
810 if (mPrimaryHWVsyncEnabled) {
811 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
812 mEventControlThread->setVsyncEnabled(false);
813 mPrimaryDispSync.endResync();
814 mPrimaryHWVsyncEnabled = false;
816 if (makeUnavailable) {
817 mHWVsyncAvailable = false;
821 void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
822 bool needsHwVsync = false;
824 { // Scope for the lock
825 Mutex::Autolock _l(mHWVsyncLock);
826 if (type == 0 && mPrimaryHWVsyncEnabled) {
827 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
832 enableHardwareVsync();
834 disableHardwareVsync(false);
838 void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
839 if (mEventThread == NULL) {
840 // This is a temporary workaround for b/7145521. A non-null pointer
841 // does not mean EventThread has finished initializing, so this
842 // is not a correct fix.
843 ALOGW("WARNING: EventThread not started, ignoring hotplug");
847 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
848 Mutex::Autolock _l(mStateLock);
850 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
852 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
853 mBuiltinDisplays[type].clear();
855 setTransactionFlags(eDisplayTransactionNeeded);
857 // Defer EventThread notification until SF has updated mDisplays.
861 void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
863 getHwComposer().eventControl(disp, event, enabled);
866 void SurfaceFlinger::onMessageReceived(int32_t what) {
869 case MessageQueue::TRANSACTION:
870 handleMessageTransaction();
872 case MessageQueue::INVALIDATE:
873 handleMessageTransaction();
874 handleMessageInvalidate();
877 case MessageQueue::REFRESH:
878 handleMessageRefresh();
883 void SurfaceFlinger::handleMessageTransaction() {
884 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
885 if (transactionFlags) {
886 handleTransaction(transactionFlags);
890 void SurfaceFlinger::handleMessageInvalidate() {
895 void SurfaceFlinger::handleMessageRefresh() {
898 rebuildLayerStacks();
900 doDebugFlashRegions();
905 void SurfaceFlinger::doDebugFlashRegions()
907 // is debugging enabled
908 if (CC_LIKELY(!mDebugRegion))
911 const bool repaintEverything = mRepaintEverything;
912 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
913 const sp<DisplayDevice>& hw(mDisplays[dpy]);
915 // transform the dirty region into this screen's coordinate space
916 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
917 if (!dirtyRegion.isEmpty()) {
918 // redraw the whole screen
919 doComposeSurfaces(hw, Region(hw->bounds()));
921 // and draw the dirty region
922 const int32_t height = hw->getHeight();
923 RenderEngine& engine(getRenderEngine());
924 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
926 hw->compositionComplete();
927 hw->swapBuffers(getHwComposer());
934 if (mDebugRegion > 1) {
935 usleep(mDebugRegion * 1000);
938 HWComposer& hwc(getHwComposer());
939 if (hwc.initCheck() == NO_ERROR) {
940 status_t err = hwc.prepare();
941 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
945 void SurfaceFlinger::preComposition()
947 bool needExtraInvalidate = false;
948 const LayerVector& layers(mDrawingState.layersSortedByZ);
949 const size_t count = layers.size();
950 for (size_t i=0 ; i<count ; i++) {
951 if (layers[i]->onPreComposition()) {
952 needExtraInvalidate = true;
955 if (needExtraInvalidate) {
960 void SurfaceFlinger::postComposition()
962 const LayerVector& layers(mDrawingState.layersSortedByZ);
963 const size_t count = layers.size();
964 for (size_t i=0 ; i<count ; i++) {
965 layers[i]->onPostComposition();
968 const HWComposer& hwc = getHwComposer();
969 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
971 if (presentFence->isValid()) {
972 if (mPrimaryDispSync.addPresentFence(presentFence)) {
973 enableHardwareVsync();
975 disableHardwareVsync(false);
979 if (runningWithoutSyncFramework) {
980 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
981 if (hw->isScreenAcquired()) {
982 enableHardwareVsync();
986 if (mAnimCompositionPending) {
987 mAnimCompositionPending = false;
989 if (presentFence->isValid()) {
990 mAnimFrameTracker.setActualPresentFence(presentFence);
992 // The HWC doesn't support present fences, so use the refresh
993 // timestamp instead.
994 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
995 mAnimFrameTracker.setActualPresentTime(presentTime);
997 mAnimFrameTracker.advanceFrame();
1001 void SurfaceFlinger::rebuildLayerStacks() {
1002 // rebuild the visible layer list per screen
1003 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1005 mVisibleRegionsDirty = false;
1006 invalidateHwcGeometry();
1008 const LayerVector& layers(mDrawingState.layersSortedByZ);
1009 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1010 Region opaqueRegion;
1012 Vector< sp<Layer> > layersSortedByZ;
1013 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1014 const Transform& tr(hw->getTransform());
1015 const Rect bounds(hw->getBounds());
1016 if (hw->canDraw()) {
1017 SurfaceFlinger::computeVisibleRegions(layers,
1018 hw->getLayerStack(), dirtyRegion, opaqueRegion);
1020 const size_t count = layers.size();
1021 for (size_t i=0 ; i<count ; i++) {
1022 const sp<Layer>& layer(layers[i]);
1023 const Layer::State& s(layer->getDrawingState());
1024 if (s.layerStack == hw->getLayerStack()) {
1025 Region drawRegion(tr.transform(
1026 layer->visibleNonTransparentRegion));
1027 drawRegion.andSelf(bounds);
1028 if (!drawRegion.isEmpty()) {
1029 layersSortedByZ.add(layer);
1034 hw->setVisibleLayersSortedByZ(layersSortedByZ);
1035 hw->undefinedRegion.set(bounds);
1036 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1037 hw->dirtyRegion.orSelf(dirtyRegion);
1042 void SurfaceFlinger::setUpHWComposer() {
1043 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1044 mDisplays[dpy]->beginFrame();
1047 HWComposer& hwc(getHwComposer());
1048 if (hwc.initCheck() == NO_ERROR) {
1049 // build the h/w work list
1050 if (CC_UNLIKELY(mHwWorkListDirty)) {
1051 mHwWorkListDirty = false;
1052 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1053 sp<const DisplayDevice> hw(mDisplays[dpy]);
1054 const int32_t id = hw->getHwcDisplayId();
1056 const Vector< sp<Layer> >& currentLayers(
1057 hw->getVisibleLayersSortedByZ());
1058 const size_t count = currentLayers.size();
1059 if (hwc.createWorkList(id, count) == NO_ERROR) {
1060 HWComposer::LayerListIterator cur = hwc.begin(id);
1061 const HWComposer::LayerListIterator end = hwc.end(id);
1062 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1063 const sp<Layer>& layer(currentLayers[i]);
1064 layer->setGeometry(hw, *cur);
1065 if (mDebugDisableHWC || mDebugRegion || mDaltonize) {
1074 // set the per-frame data
1075 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1076 sp<const DisplayDevice> hw(mDisplays[dpy]);
1077 const int32_t id = hw->getHwcDisplayId();
1079 const Vector< sp<Layer> >& currentLayers(
1080 hw->getVisibleLayersSortedByZ());
1081 const size_t count = currentLayers.size();
1082 HWComposer::LayerListIterator cur = hwc.begin(id);
1083 const HWComposer::LayerListIterator end = hwc.end(id);
1084 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1086 * update the per-frame h/w composer data for each layer
1087 * and build the transparent region of the FB
1089 const sp<Layer>& layer(currentLayers[i]);
1090 layer->setPerFrameData(hw, *cur);
1095 status_t err = hwc.prepare();
1096 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1098 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1099 sp<const DisplayDevice> hw(mDisplays[dpy]);
1100 hw->prepareFrame(hwc);
1105 void SurfaceFlinger::doComposition() {
1107 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1108 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1109 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1110 if (hw->canDraw()) {
1111 // transform the dirty region into this screen's coordinate space
1112 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1114 // repaint the framebuffer (if needed)
1115 doDisplayComposition(hw, dirtyRegion);
1117 hw->dirtyRegion.clear();
1118 hw->flip(hw->swapRegion);
1119 hw->swapRegion.clear();
1121 // inform the h/w that we're done compositing
1122 hw->compositionComplete();
1127 void SurfaceFlinger::postFramebuffer()
1131 const nsecs_t now = systemTime();
1132 mDebugInSwapBuffers = now;
1134 HWComposer& hwc(getHwComposer());
1135 if (hwc.initCheck() == NO_ERROR) {
1136 if (!hwc.supportsFramebufferTarget()) {
1138 // "surface must be bound to the calling thread's current context,
1139 // for the current rendering API."
1140 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1145 // make the default display current because the VirtualDisplayDevice code cannot
1146 // deal with dequeueBuffer() being called outside of the composition loop; however
1147 // the code below can call glFlush() which is allowed (and does in some case) call
1149 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1151 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1152 sp<const DisplayDevice> hw(mDisplays[dpy]);
1153 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1154 hw->onSwapBuffersCompleted(hwc);
1155 const size_t count = currentLayers.size();
1156 int32_t id = hw->getHwcDisplayId();
1157 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1158 HWComposer::LayerListIterator cur = hwc.begin(id);
1159 const HWComposer::LayerListIterator end = hwc.end(id);
1160 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1161 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1164 for (size_t i = 0; i < count; i++) {
1165 currentLayers[i]->onLayerDisplayed(hw, NULL);
1170 mLastSwapBufferTime = systemTime() - now;
1171 mDebugInSwapBuffers = 0;
1173 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1174 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1179 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1183 // here we keep a copy of the drawing state (that is the state that's
1184 // going to be overwritten by handleTransactionLocked()) outside of
1185 // mStateLock so that the side-effects of the State assignment
1186 // don't happen with mStateLock held (which can cause deadlocks).
1187 State drawingState(mDrawingState);
1189 Mutex::Autolock _l(mStateLock);
1190 const nsecs_t now = systemTime();
1191 mDebugInTransaction = now;
1193 // Here we're guaranteed that some transaction flags are set
1194 // so we can call handleTransactionLocked() unconditionally.
1195 // We call getTransactionFlags(), which will also clear the flags,
1196 // with mStateLock held to guarantee that mCurrentState won't change
1197 // until the transaction is committed.
1199 transactionFlags = getTransactionFlags(eTransactionMask);
1200 handleTransactionLocked(transactionFlags);
1202 mLastTransactionTime = systemTime() - now;
1203 mDebugInTransaction = 0;
1204 invalidateHwcGeometry();
1205 // here the transaction has been committed
1208 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1210 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1211 const size_t count = currentLayers.size();
1214 * Traversal of the children
1215 * (perform the transaction for each of them if needed)
1218 if (transactionFlags & eTraversalNeeded) {
1219 for (size_t i=0 ; i<count ; i++) {
1220 const sp<Layer>& layer(currentLayers[i]);
1221 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1222 if (!trFlags) continue;
1224 const uint32_t flags = layer->doTransaction(0);
1225 if (flags & Layer::eVisibleRegion)
1226 mVisibleRegionsDirty = true;
1231 * Perform display own transactions if needed
1234 if (transactionFlags & eDisplayTransactionNeeded) {
1235 // here we take advantage of Vector's copy-on-write semantics to
1236 // improve performance by skipping the transaction entirely when
1237 // know that the lists are identical
1238 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1239 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1240 if (!curr.isIdenticalTo(draw)) {
1241 mVisibleRegionsDirty = true;
1242 const size_t cc = curr.size();
1243 size_t dc = draw.size();
1245 // find the displays that were removed
1246 // (ie: in drawing state but not in current state)
1247 // also handle displays that changed
1248 // (ie: displays that are in both lists)
1249 for (size_t i=0 ; i<dc ; i++) {
1250 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1252 // in drawing state but not in current state
1253 if (!draw[i].isMainDisplay()) {
1254 // Call makeCurrent() on the primary display so we can
1255 // be sure that nothing associated with this display
1257 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1258 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1259 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1261 hw->disconnect(getHwComposer());
1262 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1263 mEventThread->onHotplugReceived(draw[i].type, false);
1264 mDisplays.removeItem(draw.keyAt(i));
1266 ALOGW("trying to remove the main display");
1269 // this display is in both lists. see if something changed.
1270 const DisplayDeviceState& state(curr[j]);
1271 const wp<IBinder>& display(curr.keyAt(j));
1272 if (state.surface->asBinder() != draw[i].surface->asBinder()) {
1273 // changing the surface is like destroying and
1274 // recreating the DisplayDevice, so we just remove it
1275 // from the drawing state, so that it get re-added
1277 sp<DisplayDevice> hw(getDisplayDevice(display));
1279 hw->disconnect(getHwComposer());
1280 mDisplays.removeItem(display);
1281 mDrawingState.displays.removeItemsAt(i);
1283 // at this point we must loop to the next item
1287 const sp<DisplayDevice> disp(getDisplayDevice(display));
1289 if (state.layerStack != draw[i].layerStack) {
1290 disp->setLayerStack(state.layerStack);
1292 if ((state.orientation != draw[i].orientation)
1293 || (state.viewport != draw[i].viewport)
1294 || (state.frame != draw[i].frame))
1296 disp->setProjection(state.orientation,
1297 state.viewport, state.frame);
1303 // find displays that were added
1304 // (ie: in current state but not in drawing state)
1305 for (size_t i=0 ; i<cc ; i++) {
1306 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1307 const DisplayDeviceState& state(curr[i]);
1309 sp<DisplaySurface> dispSurface;
1310 sp<IGraphicBufferProducer> producer;
1311 sp<BufferQueue> bq = new BufferQueue(new GraphicBufferAlloc());
1313 int32_t hwcDisplayId = -1;
1314 if (state.isVirtualDisplay()) {
1315 // Virtual displays without a surface are dormant:
1316 // they have external state (layer stack, projection,
1317 // etc.) but no internal state (i.e. a DisplayDevice).
1318 if (state.surface != NULL) {
1320 hwcDisplayId = allocateHwcDisplayId(state.type);
1321 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1322 *mHwc, hwcDisplayId, state.surface, bq,
1326 if (hwcDisplayId >= 0) {
1329 // There won't be any interaction with HWC for this virtual display,
1330 // so the GLES driver can pass buffers directly to the sink.
1331 producer = state.surface;
1335 ALOGE_IF(state.surface!=NULL,
1336 "adding a supported display, but rendering "
1337 "surface is provided (%p), ignoring it",
1338 state.surface.get());
1339 hwcDisplayId = allocateHwcDisplayId(state.type);
1340 // for supported (by hwc) displays we provide our
1341 // own rendering surface
1342 dispSurface = new FramebufferSurface(*mHwc, state.type, bq);
1346 const wp<IBinder>& display(curr.keyAt(i));
1347 if (dispSurface != NULL) {
1348 sp<DisplayDevice> hw = new DisplayDevice(this,
1349 state.type, hwcDisplayId, state.isSecure,
1350 display, dispSurface, producer, mEGLConfig);
1351 hw->setLayerStack(state.layerStack);
1352 hw->setProjection(state.orientation,
1353 state.viewport, state.frame);
1354 hw->setDisplayName(state.displayName);
1355 mDisplays.add(display, hw);
1356 if (state.isVirtualDisplay()) {
1357 if (hwcDisplayId >= 0) {
1358 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1359 hw->getWidth(), hw->getHeight(),
1363 mEventThread->onHotplugReceived(state.type, true);
1371 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1372 // The transform hint might have changed for some layers
1373 // (either because a display has changed, or because a layer
1376 // Walk through all the layers in currentLayers,
1377 // and update their transform hint.
1379 // If a layer is visible only on a single display, then that
1380 // display is used to calculate the hint, otherwise we use the
1383 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1384 // the hint is set before we acquire a buffer from the surface texture.
1386 // NOTE: layer transactions have taken place already, so we use their
1387 // drawing state. However, SurfaceFlinger's own transaction has not
1388 // happened yet, so we must use the current state layer list
1389 // (soon to become the drawing state list).
1391 sp<const DisplayDevice> disp;
1392 uint32_t currentlayerStack = 0;
1393 for (size_t i=0; i<count; i++) {
1394 // NOTE: we rely on the fact that layers are sorted by
1395 // layerStack first (so we don't have to traverse the list
1396 // of displays for every layer).
1397 const sp<Layer>& layer(currentLayers[i]);
1398 uint32_t layerStack = layer->getDrawingState().layerStack;
1399 if (i==0 || currentlayerStack != layerStack) {
1400 currentlayerStack = layerStack;
1401 // figure out if this layerstack is mirrored
1402 // (more than one display) if so, pick the default display,
1403 // if not, pick the only display it's on.
1405 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1406 sp<const DisplayDevice> hw(mDisplays[dpy]);
1407 if (hw->getLayerStack() == currentlayerStack) {
1418 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1419 // redraw after transform hint changes. See bug 8508397.
1421 // could be null when this layer is using a layerStack
1422 // that is not visible on any display. Also can occur at
1423 // screen off/on times.
1424 disp = getDefaultDisplayDevice();
1426 layer->updateTransformHint(disp);
1432 * Perform our own transaction if needed
1435 const LayerVector& layers(mDrawingState.layersSortedByZ);
1436 if (currentLayers.size() > layers.size()) {
1437 // layers have been added
1438 mVisibleRegionsDirty = true;
1441 // some layers might have been removed, so
1442 // we need to update the regions they're exposing.
1443 if (mLayersRemoved) {
1444 mLayersRemoved = false;
1445 mVisibleRegionsDirty = true;
1446 const size_t count = layers.size();
1447 for (size_t i=0 ; i<count ; i++) {
1448 const sp<Layer>& layer(layers[i]);
1449 if (currentLayers.indexOf(layer) < 0) {
1450 // this layer is not visible anymore
1451 // TODO: we could traverse the tree from front to back and
1452 // compute the actual visible region
1453 // TODO: we could cache the transformed region
1454 const Layer::State& s(layer->getDrawingState());
1455 Region visibleReg = s.transform.transform(
1456 Region(Rect(s.active.w, s.active.h)));
1457 invalidateLayerStack(s.layerStack, visibleReg);
1462 commitTransaction();
1465 void SurfaceFlinger::commitTransaction()
1467 if (!mLayersPendingRemoval.isEmpty()) {
1468 // Notify removed layers now that they can't be drawn from
1469 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1470 mLayersPendingRemoval[i]->onRemoved();
1472 mLayersPendingRemoval.clear();
1475 // If this transaction is part of a window animation then the next frame
1476 // we composite should be considered an animation as well.
1477 mAnimCompositionPending = mAnimTransactionPending;
1479 mDrawingState = mCurrentState;
1480 mTransactionPending = false;
1481 mAnimTransactionPending = false;
1482 mTransactionCV.broadcast();
1485 void SurfaceFlinger::computeVisibleRegions(
1486 const LayerVector& currentLayers, uint32_t layerStack,
1487 Region& outDirtyRegion, Region& outOpaqueRegion)
1491 Region aboveOpaqueLayers;
1492 Region aboveCoveredLayers;
1495 outDirtyRegion.clear();
1497 size_t i = currentLayers.size();
1499 const sp<Layer>& layer = currentLayers[i];
1501 // start with the whole surface at its current location
1502 const Layer::State& s(layer->getDrawingState());
1504 // only consider the layers on the given layer stack
1505 if (s.layerStack != layerStack)
1509 * opaqueRegion: area of a surface that is fully opaque.
1511 Region opaqueRegion;
1514 * visibleRegion: area of a surface that is visible on screen
1515 * and not fully transparent. This is essentially the layer's
1516 * footprint minus the opaque regions above it.
1517 * Areas covered by a translucent surface are considered visible.
1519 Region visibleRegion;
1522 * coveredRegion: area of a surface that is covered by all
1523 * visible regions above it (which includes the translucent areas).
1525 Region coveredRegion;
1528 * transparentRegion: area of a surface that is hinted to be completely
1529 * transparent. This is only used to tell when the layer has no visible
1530 * non-transparent regions and can be removed from the layer list. It
1531 * does not affect the visibleRegion of this layer or any layers
1532 * beneath it. The hint may not be correct if apps don't respect the
1533 * SurfaceView restrictions (which, sadly, some don't).
1535 Region transparentRegion;
1538 // handle hidden surfaces by setting the visible region to empty
1539 if (CC_LIKELY(layer->isVisible())) {
1540 const bool translucent = !layer->isOpaque();
1541 Rect bounds(s.transform.transform(layer->computeBounds()));
1542 visibleRegion.set(bounds);
1543 if (!visibleRegion.isEmpty()) {
1544 // Remove the transparent area from the visible region
1546 const Transform tr(s.transform);
1547 if (tr.transformed()) {
1548 if (tr.preserveRects()) {
1549 // transform the transparent region
1550 transparentRegion = tr.transform(s.activeTransparentRegion);
1552 // transformation too complex, can't do the
1553 // transparent region optimization.
1554 transparentRegion.clear();
1557 transparentRegion = s.activeTransparentRegion;
1561 // compute the opaque region
1562 const int32_t layerOrientation = s.transform.getOrientation();
1563 if (s.alpha==255 && !translucent &&
1564 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1565 // the opaque region is the layer's footprint
1566 opaqueRegion = visibleRegion;
1571 // Clip the covered region to the visible region
1572 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1574 // Update aboveCoveredLayers for next (lower) layer
1575 aboveCoveredLayers.orSelf(visibleRegion);
1577 // subtract the opaque region covered by the layers above us
1578 visibleRegion.subtractSelf(aboveOpaqueLayers);
1580 // compute this layer's dirty region
1581 if (layer->contentDirty) {
1582 // we need to invalidate the whole region
1583 dirty = visibleRegion;
1584 // as well, as the old visible region
1585 dirty.orSelf(layer->visibleRegion);
1586 layer->contentDirty = false;
1588 /* compute the exposed region:
1589 * the exposed region consists of two components:
1590 * 1) what's VISIBLE now and was COVERED before
1591 * 2) what's EXPOSED now less what was EXPOSED before
1593 * note that (1) is conservative, we start with the whole
1594 * visible region but only keep what used to be covered by
1595 * something -- which mean it may have been exposed.
1597 * (2) handles areas that were not covered by anything but got
1598 * exposed because of a resize.
1600 const Region newExposed = visibleRegion - coveredRegion;
1601 const Region oldVisibleRegion = layer->visibleRegion;
1602 const Region oldCoveredRegion = layer->coveredRegion;
1603 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1604 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1606 dirty.subtractSelf(aboveOpaqueLayers);
1608 // accumulate to the screen dirty region
1609 outDirtyRegion.orSelf(dirty);
1611 // Update aboveOpaqueLayers for next (lower) layer
1612 aboveOpaqueLayers.orSelf(opaqueRegion);
1614 // Store the visible region in screen space
1615 layer->setVisibleRegion(visibleRegion);
1616 layer->setCoveredRegion(coveredRegion);
1617 layer->setVisibleNonTransparentRegion(
1618 visibleRegion.subtract(transparentRegion));
1621 outOpaqueRegion = aboveOpaqueLayers;
1624 void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1625 const Region& dirty) {
1626 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1627 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1628 if (hw->getLayerStack() == layerStack) {
1629 hw->dirtyRegion.orSelf(dirty);
1634 void SurfaceFlinger::handlePageFlip()
1638 bool visibleRegions = false;
1639 const LayerVector& layers(mDrawingState.layersSortedByZ);
1640 const size_t count = layers.size();
1641 for (size_t i=0 ; i<count ; i++) {
1642 const sp<Layer>& layer(layers[i]);
1643 const Region dirty(layer->latchBuffer(visibleRegions));
1644 const Layer::State& s(layer->getDrawingState());
1645 invalidateLayerStack(s.layerStack, dirty);
1648 mVisibleRegionsDirty |= visibleRegions;
1651 void SurfaceFlinger::invalidateHwcGeometry()
1653 mHwWorkListDirty = true;
1657 void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1658 const Region& inDirtyRegion)
1660 Region dirtyRegion(inDirtyRegion);
1662 // compute the invalid region
1663 hw->swapRegion.orSelf(dirtyRegion);
1665 uint32_t flags = hw->getFlags();
1666 if (flags & DisplayDevice::SWAP_RECTANGLE) {
1667 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1668 // takes a rectangle, we must make sure to update that whole
1669 // rectangle in that case
1670 dirtyRegion.set(hw->swapRegion.bounds());
1672 if (flags & DisplayDevice::PARTIAL_UPDATES) {
1673 // We need to redraw the rectangle that will be updated
1674 // (pushed to the framebuffer).
1675 // This is needed because PARTIAL_UPDATES only takes one
1676 // rectangle instead of a region (see DisplayDevice::flip())
1677 dirtyRegion.set(hw->swapRegion.bounds());
1679 // we need to redraw everything (the whole screen)
1680 dirtyRegion.set(hw->bounds());
1681 hw->swapRegion = dirtyRegion;
1685 if (CC_LIKELY(!mDaltonize)) {
1686 doComposeSurfaces(hw, dirtyRegion);
1688 RenderEngine& engine(getRenderEngine());
1689 engine.beginGroup(mDaltonizer());
1690 doComposeSurfaces(hw, dirtyRegion);
1694 // update the swap region and clear the dirty region
1695 hw->swapRegion.orSelf(dirtyRegion);
1697 // swap buffers (presentation)
1698 hw->swapBuffers(getHwComposer());
1701 void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1703 RenderEngine& engine(getRenderEngine());
1704 const int32_t id = hw->getHwcDisplayId();
1705 HWComposer& hwc(getHwComposer());
1706 HWComposer::LayerListIterator cur = hwc.begin(id);
1707 const HWComposer::LayerListIterator end = hwc.end(id);
1709 bool hasGlesComposition = hwc.hasGlesComposition(id);
1710 if (hasGlesComposition) {
1711 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
1712 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1713 hw->getDisplayName().string());
1717 // Never touch the framebuffer if we don't have any framebuffer layers
1718 const bool hasHwcComposition = hwc.hasHwcComposition(id);
1719 if (hasHwcComposition) {
1720 // when using overlays, we assume a fully transparent framebuffer
1721 // NOTE: we could reduce how much we need to clear, for instance
1722 // remove where there are opaque FB layers. however, on some
1723 // GPUs doing a "clean slate" clear might be more efficient.
1724 // We'll revisit later if needed.
1725 engine.clearWithColor(0, 0, 0, 0);
1727 // we start with the whole screen area
1728 const Region bounds(hw->getBounds());
1730 // we remove the scissor part
1731 // we're left with the letterbox region
1732 // (common case is that letterbox ends-up being empty)
1733 const Region letterbox(bounds.subtract(hw->getScissor()));
1735 // compute the area to clear
1736 Region region(hw->undefinedRegion.merge(letterbox));
1738 // but limit it to the dirty region
1739 region.andSelf(dirty);
1741 // screen is already cleared here
1742 if (!region.isEmpty()) {
1743 // can happen with SurfaceView
1744 drawWormhole(hw, region);
1748 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
1749 // just to be on the safe side, we don't set the
1750 // scissor on the main display. It should never be needed
1751 // anyways (though in theory it could since the API allows it).
1752 const Rect& bounds(hw->getBounds());
1753 const Rect& scissor(hw->getScissor());
1754 if (scissor != bounds) {
1755 // scissor doesn't match the screen's dimensions, so we
1756 // need to clear everything outside of it and enable
1757 // the GL scissor so we don't draw anything where we shouldn't
1759 // enable scissor for this frame
1760 const uint32_t height = hw->getHeight();
1761 engine.setScissor(scissor.left, height - scissor.bottom,
1762 scissor.getWidth(), scissor.getHeight());
1768 * and then, render the layers targeted at the framebuffer
1771 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
1772 const size_t count = layers.size();
1773 const Transform& tr = hw->getTransform();
1775 // we're using h/w composer
1776 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1777 const sp<Layer>& layer(layers[i]);
1778 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1779 if (!clip.isEmpty()) {
1780 switch (cur->getCompositionType()) {
1782 const Layer::State& state(layer->getDrawingState());
1783 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1785 && layer->isOpaque() && (state.alpha == 0xFF)
1786 && hasGlesComposition) {
1787 // never clear the very first layer since we're
1788 // guaranteed the FB is already cleared
1789 layer->clearWithOpenGL(hw, clip);
1793 case HWC_FRAMEBUFFER: {
1794 layer->draw(hw, clip);
1797 case HWC_FRAMEBUFFER_TARGET: {
1798 // this should not happen as the iterator shouldn't
1799 // let us get there.
1800 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%d)", i);
1805 layer->setAcquireFence(hw, *cur);
1808 // we're not using h/w composer
1809 for (size_t i=0 ; i<count ; ++i) {
1810 const sp<Layer>& layer(layers[i]);
1811 const Region clip(dirty.intersect(
1812 tr.transform(layer->visibleRegion)));
1813 if (!clip.isEmpty()) {
1814 layer->draw(hw, clip);
1819 // disable scissor at the end of the frame
1820 engine.disableScissor();
1823 void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
1824 const int32_t height = hw->getHeight();
1825 RenderEngine& engine(getRenderEngine());
1826 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
1829 void SurfaceFlinger::addClientLayer(const sp<Client>& client,
1830 const sp<IBinder>& handle,
1831 const sp<IGraphicBufferProducer>& gbc,
1832 const sp<Layer>& lbc)
1834 // attach this layer to the client
1835 client->attachLayer(handle, lbc);
1837 // add this layer to the current state list
1838 Mutex::Autolock _l(mStateLock);
1839 mCurrentState.layersSortedByZ.add(lbc);
1840 mGraphicBufferProducerList.add(gbc->asBinder());
1843 status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
1844 Mutex::Autolock _l(mStateLock);
1845 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
1847 mLayersPendingRemoval.push(layer);
1848 mLayersRemoved = true;
1849 setTransactionFlags(eTransactionNeeded);
1852 return status_t(index);
1855 uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags) {
1856 return android_atomic_release_load(&mTransactionFlags);
1859 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
1860 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1863 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
1864 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1865 if ((old & flags)==0) { // wake the server up
1866 signalTransaction();
1871 void SurfaceFlinger::setTransactionState(
1872 const Vector<ComposerState>& state,
1873 const Vector<DisplayState>& displays,
1877 Mutex::Autolock _l(mStateLock);
1878 uint32_t transactionFlags = 0;
1880 if (flags & eAnimation) {
1881 // For window updates that are part of an animation we must wait for
1882 // previous animation "frames" to be handled.
1883 while (mAnimTransactionPending) {
1884 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1885 if (CC_UNLIKELY(err != NO_ERROR)) {
1886 // just in case something goes wrong in SF, return to the
1887 // caller after a few seconds.
1888 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
1889 "waiting for previous animation frame");
1890 mAnimTransactionPending = false;
1896 size_t count = displays.size();
1897 for (size_t i=0 ; i<count ; i++) {
1898 const DisplayState& s(displays[i]);
1899 transactionFlags |= setDisplayStateLocked(s);
1902 count = state.size();
1903 for (size_t i=0 ; i<count ; i++) {
1904 const ComposerState& s(state[i]);
1905 // Here we need to check that the interface we're given is indeed
1906 // one of our own. A malicious client could give us a NULL
1907 // IInterface, or one of its own or even one of our own but a
1908 // different type. All these situations would cause us to crash.
1910 // NOTE: it would be better to use RTTI as we could directly check
1911 // that we have a Client*. however, RTTI is disabled in Android.
1912 if (s.client != NULL) {
1913 sp<IBinder> binder = s.client->asBinder();
1914 if (binder != NULL) {
1915 String16 desc(binder->getInterfaceDescriptor());
1916 if (desc == ISurfaceComposerClient::descriptor) {
1917 sp<Client> client( static_cast<Client *>(s.client.get()) );
1918 transactionFlags |= setClientStateLocked(client, s.state);
1924 if (transactionFlags) {
1925 // this triggers the transaction
1926 setTransactionFlags(transactionFlags);
1928 // if this is a synchronous transaction, wait for it to take effect
1929 // before returning.
1930 if (flags & eSynchronous) {
1931 mTransactionPending = true;
1933 if (flags & eAnimation) {
1934 mAnimTransactionPending = true;
1936 while (mTransactionPending) {
1937 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1938 if (CC_UNLIKELY(err != NO_ERROR)) {
1939 // just in case something goes wrong in SF, return to the
1940 // called after a few seconds.
1941 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
1942 mTransactionPending = false;
1949 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
1951 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
1956 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
1957 if (disp.isValid()) {
1958 const uint32_t what = s.what;
1959 if (what & DisplayState::eSurfaceChanged) {
1960 if (disp.surface->asBinder() != s.surface->asBinder()) {
1961 disp.surface = s.surface;
1962 flags |= eDisplayTransactionNeeded;
1965 if (what & DisplayState::eLayerStackChanged) {
1966 if (disp.layerStack != s.layerStack) {
1967 disp.layerStack = s.layerStack;
1968 flags |= eDisplayTransactionNeeded;
1971 if (what & DisplayState::eDisplayProjectionChanged) {
1972 if (disp.orientation != s.orientation) {
1973 disp.orientation = s.orientation;
1974 flags |= eDisplayTransactionNeeded;
1976 if (disp.frame != s.frame) {
1977 disp.frame = s.frame;
1978 flags |= eDisplayTransactionNeeded;
1980 if (disp.viewport != s.viewport) {
1981 disp.viewport = s.viewport;
1982 flags |= eDisplayTransactionNeeded;
1989 uint32_t SurfaceFlinger::setClientStateLocked(
1990 const sp<Client>& client,
1991 const layer_state_t& s)
1994 sp<Layer> layer(client->getLayerUser(s.surface));
1996 const uint32_t what = s.what;
1997 if (what & layer_state_t::ePositionChanged) {
1998 if (layer->setPosition(s.x, s.y))
1999 flags |= eTraversalNeeded;
2001 if (what & layer_state_t::eLayerChanged) {
2002 // NOTE: index needs to be calculated before we update the state
2003 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2004 if (layer->setLayer(s.z)) {
2005 mCurrentState.layersSortedByZ.removeAt(idx);
2006 mCurrentState.layersSortedByZ.add(layer);
2007 // we need traversal (state changed)
2008 // AND transaction (list changed)
2009 flags |= eTransactionNeeded|eTraversalNeeded;
2012 if (what & layer_state_t::eSizeChanged) {
2013 if (layer->setSize(s.w, s.h)) {
2014 flags |= eTraversalNeeded;
2017 if (what & layer_state_t::eAlphaChanged) {
2018 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2019 flags |= eTraversalNeeded;
2021 if (what & layer_state_t::eMatrixChanged) {
2022 if (layer->setMatrix(s.matrix))
2023 flags |= eTraversalNeeded;
2025 if (what & layer_state_t::eTransparentRegionChanged) {
2026 if (layer->setTransparentRegionHint(s.transparentRegion))
2027 flags |= eTraversalNeeded;
2029 if (what & layer_state_t::eVisibilityChanged) {
2030 if (layer->setFlags(s.flags, s.mask))
2031 flags |= eTraversalNeeded;
2033 if (what & layer_state_t::eCropChanged) {
2034 if (layer->setCrop(s.crop))
2035 flags |= eTraversalNeeded;
2037 if (what & layer_state_t::eLayerStackChanged) {
2038 // NOTE: index needs to be calculated before we update the state
2039 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2040 if (layer->setLayerStack(s.layerStack)) {
2041 mCurrentState.layersSortedByZ.removeAt(idx);
2042 mCurrentState.layersSortedByZ.add(layer);
2043 // we need traversal (state changed)
2044 // AND transaction (list changed)
2045 flags |= eTransactionNeeded|eTraversalNeeded;
2052 status_t SurfaceFlinger::createLayer(
2053 const String8& name,
2054 const sp<Client>& client,
2055 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2056 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
2058 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
2059 if (int32_t(w|h) < 0) {
2060 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2065 status_t result = NO_ERROR;
2069 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2070 case ISurfaceComposerClient::eFXSurfaceNormal:
2071 result = createNormalLayer(client,
2072 name, w, h, flags, format,
2073 handle, gbp, &layer);
2075 case ISurfaceComposerClient::eFXSurfaceDim:
2076 result = createDimLayer(client,
2078 handle, gbp, &layer);
2085 if (result == NO_ERROR) {
2086 addClientLayer(client, *handle, *gbp, layer);
2087 setTransactionFlags(eTransactionNeeded);
2092 status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2093 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2094 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2096 // initialize the surfaces
2098 case PIXEL_FORMAT_TRANSPARENT:
2099 case PIXEL_FORMAT_TRANSLUCENT:
2100 format = PIXEL_FORMAT_RGBA_8888;
2102 case PIXEL_FORMAT_OPAQUE:
2104 format = PIXEL_FORMAT_RGB_565;
2106 format = PIXEL_FORMAT_RGBX_8888;
2112 if (format == PIXEL_FORMAT_RGBX_8888)
2113 format = PIXEL_FORMAT_RGBA_8888;
2116 *outLayer = new Layer(this, client, name, w, h, flags);
2117 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2118 if (err == NO_ERROR) {
2119 *handle = (*outLayer)->getHandle();
2120 *gbp = (*outLayer)->getBufferQueue();
2123 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2127 status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2128 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2129 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2131 *outLayer = new LayerDim(this, client, name, w, h, flags);
2132 *handle = (*outLayer)->getHandle();
2133 *gbp = (*outLayer)->getBufferQueue();
2137 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2139 // called by the window manager when it wants to remove a Layer
2140 status_t err = NO_ERROR;
2141 sp<Layer> l(client->getLayerUser(handle));
2143 err = removeLayer(l);
2144 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2145 "error removing layer=%p (%s)", l.get(), strerror(-err));
2150 status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2152 // called by ~LayerCleaner() when all references to the IBinder (handle)
2154 status_t err = NO_ERROR;
2155 sp<Layer> l(layer.promote());
2157 err = removeLayer(l);
2158 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2159 "error removing layer=%p (%s)", l.get(), strerror(-err));
2164 // ---------------------------------------------------------------------------
2166 void SurfaceFlinger::onInitializeDisplays() {
2167 // reset screen orientation and use primary layer stack
2168 Vector<ComposerState> state;
2169 Vector<DisplayState> displays;
2171 d.what = DisplayState::eDisplayProjectionChanged |
2172 DisplayState::eLayerStackChanged;
2173 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2175 d.orientation = DisplayState::eOrientationDefault;
2176 d.frame.makeInvalid();
2177 d.viewport.makeInvalid();
2179 setTransactionState(state, displays, 0);
2180 onScreenAcquired(getDefaultDisplayDevice());
2182 const nsecs_t period =
2183 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2184 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2187 void SurfaceFlinger::initializeDisplays() {
2188 class MessageScreenInitialized : public MessageBase {
2189 SurfaceFlinger* flinger;
2191 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2192 virtual bool handler() {
2193 flinger->onInitializeDisplays();
2197 sp<MessageBase> msg = new MessageScreenInitialized(this);
2198 postMessageAsync(msg); // we may be called from main thread, use async message
2202 void SurfaceFlinger::onScreenAcquired(const sp<const DisplayDevice>& hw) {
2203 ALOGD("Screen acquired, type=%d flinger=%p", hw->getDisplayType(), this);
2204 if (hw->isScreenAcquired()) {
2205 // this is expected, e.g. when power manager wakes up during boot
2206 ALOGD(" screen was previously acquired");
2210 hw->acquireScreen();
2211 int32_t type = hw->getDisplayType();
2212 if (type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2213 // built-in display, tell the HWC
2214 getHwComposer().acquire(type);
2216 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2217 // FIXME: eventthread only knows about the main display right now
2218 mEventThread->onScreenAcquired();
2220 resyncToHardwareVsync(true);
2223 mVisibleRegionsDirty = true;
2224 repaintEverything();
2227 void SurfaceFlinger::onScreenReleased(const sp<const DisplayDevice>& hw) {
2228 ALOGD("Screen released, type=%d flinger=%p", hw->getDisplayType(), this);
2229 if (!hw->isScreenAcquired()) {
2230 ALOGD(" screen was previously released");
2234 hw->releaseScreen();
2235 int32_t type = hw->getDisplayType();
2236 if (type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2237 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2238 disableHardwareVsync(true); // also cancels any in-progress resync
2240 // FIXME: eventthread only knows about the main display right now
2241 mEventThread->onScreenReleased();
2244 // built-in display, tell the HWC
2245 getHwComposer().release(type);
2247 mVisibleRegionsDirty = true;
2248 // from this point on, SF will stop drawing on this display
2251 void SurfaceFlinger::unblank(const sp<IBinder>& display) {
2252 class MessageScreenAcquired : public MessageBase {
2253 SurfaceFlinger& mFlinger;
2254 sp<IBinder> mDisplay;
2256 MessageScreenAcquired(SurfaceFlinger& flinger,
2257 const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { }
2258 virtual bool handler() {
2259 const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2261 ALOGE("Attempt to unblank null display %p", mDisplay.get());
2262 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2263 ALOGW("Attempt to unblank virtual display");
2265 mFlinger.onScreenAcquired(hw);
2270 sp<MessageBase> msg = new MessageScreenAcquired(*this, display);
2271 postMessageSync(msg);
2274 void SurfaceFlinger::blank(const sp<IBinder>& display) {
2275 class MessageScreenReleased : public MessageBase {
2276 SurfaceFlinger& mFlinger;
2277 sp<IBinder> mDisplay;
2279 MessageScreenReleased(SurfaceFlinger& flinger,
2280 const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { }
2281 virtual bool handler() {
2282 const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2284 ALOGE("Attempt to blank null display %p", mDisplay.get());
2285 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2286 ALOGW("Attempt to blank virtual display");
2288 mFlinger.onScreenReleased(hw);
2293 sp<MessageBase> msg = new MessageScreenReleased(*this, display);
2294 postMessageSync(msg);
2297 // ---------------------------------------------------------------------------
2299 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2303 IPCThreadState* ipc = IPCThreadState::self();
2304 const int pid = ipc->getCallingPid();
2305 const int uid = ipc->getCallingUid();
2306 if ((uid != AID_SHELL) &&
2307 !PermissionCache::checkPermission(sDump, pid, uid)) {
2308 result.appendFormat("Permission Denial: "
2309 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2311 // Try to get the main lock, but don't insist if we can't
2312 // (this would indicate SF is stuck, but we want to be able to
2313 // print something in dumpsys).
2315 while (mStateLock.tryLock()<0 && --retry>=0) {
2318 const bool locked(retry >= 0);
2321 "SurfaceFlinger appears to be unresponsive, "
2322 "dumping anyways (no locks held)\n");
2325 bool dumpAll = true;
2327 size_t numArgs = args.size();
2329 if ((index < numArgs) &&
2330 (args[index] == String16("--list"))) {
2332 listLayersLocked(args, index, result);
2336 if ((index < numArgs) &&
2337 (args[index] == String16("--latency"))) {
2339 dumpStatsLocked(args, index, result);
2343 if ((index < numArgs) &&
2344 (args[index] == String16("--latency-clear"))) {
2346 clearStatsLocked(args, index, result);
2352 dumpAllLocked(args, index, result);
2356 mStateLock.unlock();
2359 write(fd, result.string(), result.size());
2363 void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
2364 String8& result) const
2366 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2367 const size_t count = currentLayers.size();
2368 for (size_t i=0 ; i<count ; i++) {
2369 const sp<Layer>& layer(currentLayers[i]);
2370 result.appendFormat("%s\n", layer->getName().string());
2374 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2375 String8& result) const
2378 if (index < args.size()) {
2379 name = String8(args[index]);
2383 const nsecs_t period =
2384 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2385 result.appendFormat("%lld\n", period);
2387 if (name.isEmpty()) {
2388 mAnimFrameTracker.dump(result);
2390 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2391 const size_t count = currentLayers.size();
2392 for (size_t i=0 ; i<count ; i++) {
2393 const sp<Layer>& layer(currentLayers[i]);
2394 if (name == layer->getName()) {
2395 layer->dumpStats(result);
2401 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2405 if (index < args.size()) {
2406 name = String8(args[index]);
2410 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2411 const size_t count = currentLayers.size();
2412 for (size_t i=0 ; i<count ; i++) {
2413 const sp<Layer>& layer(currentLayers[i]);
2414 if (name.isEmpty() || (name == layer->getName())) {
2415 layer->clearStats();
2419 mAnimFrameTracker.clear();
2422 // This should only be called from the main thread. Otherwise it would need
2423 // the lock and should use mCurrentState rather than mDrawingState.
2424 void SurfaceFlinger::logFrameStats() {
2425 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2426 const size_t count = drawingLayers.size();
2427 for (size_t i=0 ; i<count ; i++) {
2428 const sp<Layer>& layer(drawingLayers[i]);
2429 layer->logFrameStats();
2432 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2435 /*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2437 static const char* config =
2442 #ifdef HAS_CONTEXT_PRIORITY
2443 " HAS_CONTEXT_PRIORITY"
2445 #ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2446 " NEVER_DEFAULT_TO_ASYNC_MODE"
2448 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2449 " TARGET_DISABLE_TRIPLE_BUFFERING"
2452 result.append(config);
2455 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2456 String8& result) const
2458 bool colorize = false;
2459 if (index < args.size()
2460 && (args[index] == String16("--color"))) {
2465 Colorizer colorizer(colorize);
2467 // figure out if we're stuck somewhere
2468 const nsecs_t now = systemTime();
2469 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2470 const nsecs_t inTransaction(mDebugInTransaction);
2471 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2472 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2475 * Dump library configuration.
2478 colorizer.bold(result);
2479 result.append("Build configuration:");
2480 colorizer.reset(result);
2481 appendSfConfigString(result);
2482 appendUiConfigString(result);
2483 appendGuiConfigString(result);
2484 result.append("\n");
2486 colorizer.bold(result);
2487 result.append("Sync configuration: ");
2488 colorizer.reset(result);
2489 result.append(SyncFeatures::getInstance().toString());
2490 result.append("\n");
2493 * Dump the visible layer list
2495 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2496 const size_t count = currentLayers.size();
2497 colorizer.bold(result);
2498 result.appendFormat("Visible layers (count = %d)\n", count);
2499 colorizer.reset(result);
2500 for (size_t i=0 ; i<count ; i++) {
2501 const sp<Layer>& layer(currentLayers[i]);
2502 layer->dump(result, colorizer);
2506 * Dump Display state
2509 colorizer.bold(result);
2510 result.appendFormat("Displays (%d entries)\n", mDisplays.size());
2511 colorizer.reset(result);
2512 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2513 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2518 * Dump SurfaceFlinger global state
2521 colorizer.bold(result);
2522 result.append("SurfaceFlinger global state:\n");
2523 colorizer.reset(result);
2525 HWComposer& hwc(getHwComposer());
2526 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2528 colorizer.bold(result);
2529 result.appendFormat("EGL implementation : %s\n",
2530 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2531 colorizer.reset(result);
2532 result.appendFormat("%s\n",
2533 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2535 mRenderEngine->dump(result);
2537 hw->undefinedRegion.dump(result, "undefinedRegion");
2538 result.appendFormat(" orientation=%d, canDraw=%d\n",
2539 hw->getOrientation(), hw->canDraw());
2540 result.appendFormat(
2541 " last eglSwapBuffers() time: %f us\n"
2542 " last transaction time : %f us\n"
2543 " transaction-flags : %08x\n"
2544 " refresh-rate : %f fps\n"
2547 " EGL_NATIVE_VISUAL_ID : %d\n"
2548 " gpu_to_cpu_unsupported : %d\n"
2550 mLastSwapBufferTime/1000.0,
2551 mLastTransactionTime/1000.0,
2553 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2554 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2555 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2557 !mGpuToCpuSupported);
2559 result.appendFormat(" eglSwapBuffers time: %f us\n",
2560 inSwapBuffersDuration/1000.0);
2562 result.appendFormat(" transaction time: %f us\n",
2563 inTransactionDuration/1000.0);
2568 mEventThread->dump(result);
2571 * Dump HWComposer state
2573 colorizer.bold(result);
2574 result.append("h/w composer state:\n");
2575 colorizer.reset(result);
2576 result.appendFormat(" h/w composer %s and %s\n",
2577 hwc.initCheck()==NO_ERROR ? "present" : "not present",
2578 (mDebugDisableHWC || mDebugRegion || mDaltonize) ? "disabled" : "enabled");
2582 * Dump gralloc state
2584 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2588 const Vector< sp<Layer> >&
2589 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2590 // Note: mStateLock is held here
2592 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2593 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2594 dpy = mDisplays.keyAt(i);
2599 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2600 // Just use the primary display so we have something to return
2601 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2603 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2606 bool SurfaceFlinger::startDdmConnection()
2608 void* libddmconnection_dso =
2609 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2610 if (!libddmconnection_dso) {
2613 void (*DdmConnection_start)(const char* name);
2614 DdmConnection_start =
2615 (typeof DdmConnection_start)dlsym(libddmconnection_dso, "DdmConnection_start");
2616 if (!DdmConnection_start) {
2617 dlclose(libddmconnection_dso);
2620 (*DdmConnection_start)(getServiceName());
2624 status_t SurfaceFlinger::onTransact(
2625 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2628 case CREATE_CONNECTION:
2629 case CREATE_DISPLAY:
2630 case SET_TRANSACTION_STATE:
2635 // codes that require permission check
2636 IPCThreadState* ipc = IPCThreadState::self();
2637 const int pid = ipc->getCallingPid();
2638 const int uid = ipc->getCallingUid();
2639 if ((uid != AID_GRAPHICS) &&
2640 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2641 ALOGE("Permission Denial: "
2642 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2643 return PERMISSION_DENIED;
2647 case CAPTURE_SCREEN:
2649 // codes that require permission check
2650 IPCThreadState* ipc = IPCThreadState::self();
2651 const int pid = ipc->getCallingPid();
2652 const int uid = ipc->getCallingUid();
2653 if ((uid != AID_GRAPHICS) &&
2654 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2655 ALOGE("Permission Denial: "
2656 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2657 return PERMISSION_DENIED;
2663 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2664 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2665 CHECK_INTERFACE(ISurfaceComposer, data, reply);
2666 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2667 IPCThreadState* ipc = IPCThreadState::self();
2668 const int pid = ipc->getCallingPid();
2669 const int uid = ipc->getCallingUid();
2670 ALOGE("Permission Denial: "
2671 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2672 return PERMISSION_DENIED;
2676 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2677 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2679 case 1002: // SHOW_UPDATES
2680 n = data.readInt32();
2681 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2682 invalidateHwcGeometry();
2683 repaintEverything();
2685 case 1004:{ // repaint everything
2686 repaintEverything();
2689 case 1005:{ // force transaction
2690 setTransactionFlags(
2692 eDisplayTransactionNeeded|
2696 case 1006:{ // send empty update
2700 case 1008: // toggle use of hw composer
2701 n = data.readInt32();
2702 mDebugDisableHWC = n ? 1 : 0;
2703 invalidateHwcGeometry();
2704 repaintEverything();
2706 case 1009: // toggle use of transform hint
2707 n = data.readInt32();
2708 mDebugDisableTransformHint = n ? 1 : 0;
2709 invalidateHwcGeometry();
2710 repaintEverything();
2712 case 1010: // interrogate.
2713 reply->writeInt32(0);
2714 reply->writeInt32(0);
2715 reply->writeInt32(mDebugRegion);
2716 reply->writeInt32(0);
2717 reply->writeInt32(mDebugDisableHWC);
2720 Mutex::Autolock _l(mStateLock);
2721 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2722 reply->writeInt32(hw->getPageFlipCount());
2727 n = data.readInt32();
2729 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
2730 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
2731 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
2734 mDaltonizer.setMode(Daltonizer::correction);
2736 mDaltonizer.setMode(Daltonizer::simulation);
2739 invalidateHwcGeometry();
2740 repaintEverything();
2748 void SurfaceFlinger::repaintEverything() {
2749 android_atomic_or(1, &mRepaintEverything);
2750 signalTransaction();
2753 // ---------------------------------------------------------------------------
2754 // Capture screen into an IGraphiBufferProducer
2755 // ---------------------------------------------------------------------------
2757 /* The code below is here to handle b/8734824
2759 * We create a IGraphicBufferProducer wrapper that forwards all calls
2760 * to the calling binder thread, where they are executed. This allows
2761 * the calling thread to be reused (on the other side) and not
2762 * depend on having "enough" binder threads to handle the requests.
2766 class GraphicProducerWrapper : public BBinder, public MessageHandler {
2767 sp<IGraphicBufferProducer> impl;
2772 mutable Barrier barrier;
2773 volatile int32_t memoryBarrier;
2784 * this is called by our "fake" BpGraphicBufferProducer. We package the
2785 * data and reply Parcel and forward them to the calling thread.
2787 virtual status_t transact(uint32_t code,
2788 const Parcel& data, Parcel* reply, uint32_t flags) {
2791 this->reply = reply;
2792 android_atomic_acquire_store(0, &memoryBarrier);
2794 // if we've exited, we run the message synchronously right here
2795 handleMessage(Message(MSG_API_CALL));
2798 looper->sendMessage(this, Message(MSG_API_CALL));
2805 * here we run on the binder calling thread. All we've got to do is
2806 * call the real BpGraphicBufferProducer.
2808 virtual void handleMessage(const Message& message) {
2809 android_atomic_release_load(&memoryBarrier);
2810 if (message.what == MSG_API_CALL) {
2811 impl->asBinder()->transact(code, data[0], reply);
2813 } else if (message.what == MSG_EXIT) {
2814 exitRequested = true;
2819 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl) :
2820 impl(impl), looper(new Looper(true)), result(NO_ERROR),
2821 exitPending(false), exitRequested(false) {
2824 status_t waitForResponse() {
2826 looper->pollOnce(-1);
2827 } while (!exitRequested);
2831 void exit(status_t result) {
2832 this->result = result;
2834 looper->sendMessage(this, Message(MSG_EXIT));
2839 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
2840 const sp<IGraphicBufferProducer>& producer,
2841 uint32_t reqWidth, uint32_t reqHeight,
2842 uint32_t minLayerZ, uint32_t maxLayerZ) {
2844 if (CC_UNLIKELY(display == 0))
2847 if (CC_UNLIKELY(producer == 0))
2850 // if we have secure windows on this display, never allow the screen capture
2851 // unless the producer interface is local (i.e.: we can take a screenshot for
2853 if (!producer->asBinder()->localBinder()) {
2854 Mutex::Autolock _l(mStateLock);
2855 sp<const DisplayDevice> hw(getDisplayDevice(display));
2856 if (hw->getSecureLayerVisible()) {
2857 ALOGW("FB is protected: PERMISSION_DENIED");
2858 return PERMISSION_DENIED;
2862 class MessageCaptureScreen : public MessageBase {
2863 SurfaceFlinger* flinger;
2864 sp<IBinder> display;
2865 sp<IGraphicBufferProducer> producer;
2866 uint32_t reqWidth, reqHeight;
2867 uint32_t minLayerZ,maxLayerZ;
2870 MessageCaptureScreen(SurfaceFlinger* flinger,
2871 const sp<IBinder>& display,
2872 const sp<IGraphicBufferProducer>& producer,
2873 uint32_t reqWidth, uint32_t reqHeight,
2874 uint32_t minLayerZ, uint32_t maxLayerZ)
2875 : flinger(flinger), display(display), producer(producer),
2876 reqWidth(reqWidth), reqHeight(reqHeight),
2877 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2878 result(PERMISSION_DENIED)
2881 status_t getResult() const {
2884 virtual bool handler() {
2885 Mutex::Autolock _l(flinger->mStateLock);
2886 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
2887 result = flinger->captureScreenImplLocked(hw,
2888 producer, reqWidth, reqHeight, minLayerZ, maxLayerZ);
2889 static_cast<GraphicProducerWrapper*>(producer->asBinder().get())->exit(result);
2894 // make sure to process transactions before screenshots -- a transaction
2895 // might already be pending but scheduled for VSYNC; this guarantees we
2896 // will handle it before the screenshot. When VSYNC finally arrives
2897 // the scheduled transaction will be a no-op. If no transactions are
2898 // scheduled at this time, this will end-up being a no-op as well.
2899 mEventQueue.invalidateTransactionNow();
2901 // this creates a "fake" BBinder which will serve as a "fake" remote
2902 // binder to receive the marshaled calls and forward them to the
2903 // real remote (a BpGraphicBufferProducer)
2904 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
2906 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
2907 // which does the marshaling work forwards to our "fake remote" above.
2908 sp<MessageBase> msg = new MessageCaptureScreen(this,
2909 display, IGraphicBufferProducer::asInterface( wrapper ),
2910 reqWidth, reqHeight, minLayerZ, maxLayerZ);
2912 status_t res = postMessageAsync(msg);
2913 if (res == NO_ERROR) {
2914 res = wrapper->waitForResponse();
2920 void SurfaceFlinger::renderScreenImplLocked(
2921 const sp<const DisplayDevice>& hw,
2922 uint32_t reqWidth, uint32_t reqHeight,
2923 uint32_t minLayerZ, uint32_t maxLayerZ,
2927 RenderEngine& engine(getRenderEngine());
2929 // get screen geometry
2930 const uint32_t hw_w = hw->getWidth();
2931 const uint32_t hw_h = hw->getHeight();
2932 const bool filtering = reqWidth != hw_w || reqWidth != hw_h;
2934 // make sure to clear all GL error flags
2935 engine.checkErrors();
2937 // set-up our viewport
2938 engine.setViewportAndProjection(reqWidth, reqHeight, hw_w, hw_h, yswap);
2939 engine.disableTexturing();
2941 // redraw the screen entirely...
2942 engine.clearWithColor(0, 0, 0, 1);
2944 const LayerVector& layers( mDrawingState.layersSortedByZ );
2945 const size_t count = layers.size();
2946 for (size_t i=0 ; i<count ; ++i) {
2947 const sp<Layer>& layer(layers[i]);
2948 const Layer::State& state(layer->getDrawingState());
2949 if (state.layerStack == hw->getLayerStack()) {
2950 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
2951 if (layer->isVisible()) {
2952 if (filtering) layer->setFiltering(true);
2954 if (filtering) layer->setFiltering(false);
2960 // compositionComplete is needed for older driver
2961 hw->compositionComplete();
2962 hw->setViewportAndProjection();
2966 status_t SurfaceFlinger::captureScreenImplLocked(
2967 const sp<const DisplayDevice>& hw,
2968 const sp<IGraphicBufferProducer>& producer,
2969 uint32_t reqWidth, uint32_t reqHeight,
2970 uint32_t minLayerZ, uint32_t maxLayerZ)
2974 // get screen geometry
2975 const uint32_t hw_w = hw->getWidth();
2976 const uint32_t hw_h = hw->getHeight();
2978 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
2979 ALOGE("size mismatch (%d, %d) > (%d, %d)",
2980 reqWidth, reqHeight, hw_w, hw_h);
2984 reqWidth = (!reqWidth) ? hw_w : reqWidth;
2985 reqHeight = (!reqHeight) ? hw_h : reqHeight;
2987 // create a surface (because we're a producer, and we need to
2988 // dequeue/queue a buffer)
2989 sp<Surface> sur = new Surface(producer, false);
2990 ANativeWindow* window = sur.get();
2992 status_t result = NO_ERROR;
2993 if (native_window_api_connect(window, NATIVE_WINDOW_API_EGL) == NO_ERROR) {
2994 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
2995 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
2998 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
2999 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3000 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3001 err |= native_window_set_usage(window, usage);
3003 if (err == NO_ERROR) {
3004 ANativeWindowBuffer* buffer;
3005 /* TODO: Once we have the sync framework everywhere this can use
3006 * server-side waits on the fence that dequeueBuffer returns.
3008 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3009 if (result == NO_ERROR) {
3010 // create an EGLImage from the buffer so we can later
3011 // turn it into a texture
3012 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3013 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3014 if (image != EGL_NO_IMAGE_KHR) {
3015 // this binds the given EGLImage as a framebuffer for the
3016 // duration of this scope.
3017 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3018 if (imageBond.getStatus() == NO_ERROR) {
3019 // this will in fact render into our dequeued buffer
3020 // via an FBO, which means we didn't have to create
3021 // an EGLSurface and therefore we're not
3022 // dependent on the context's EGLConfig.
3023 renderScreenImplLocked(hw, reqWidth, reqHeight,
3024 minLayerZ, maxLayerZ, true);
3026 // Create a sync point and wait on it, so we know the buffer is
3027 // ready before we pass it along. We can't trivially call glFlush(),
3028 // so we use a wait flag instead.
3029 // TODO: pass a sync fd to queueBuffer() and let the consumer wait.
3030 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3031 if (sync != EGL_NO_SYNC_KHR) {
3032 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3033 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3034 EGLint eglErr = eglGetError();
3035 eglDestroySyncKHR(mEGLDisplay, sync);
3036 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3037 ALOGW("captureScreen: fence wait timed out");
3039 ALOGW_IF(eglErr != EGL_SUCCESS,
3040 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3043 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3047 if (DEBUG_SCREENSHOTS) {
3048 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3049 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3050 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3051 hw, minLayerZ, maxLayerZ);
3056 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3057 result = INVALID_OPERATION;
3059 // destroy our image
3060 eglDestroyImageKHR(mEGLDisplay, image);
3064 window->queueBuffer(window, buffer, -1);
3069 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3075 void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3076 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3077 if (DEBUG_SCREENSHOTS) {
3078 for (size_t y=0 ; y<h ; y++) {
3079 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3080 for (size_t x=0 ; x<w ; x++) {
3081 if (p[x] != 0xFF000000) return;
3084 ALOGE("*** we just took a black screenshot ***\n"
3085 "requested minz=%d, maxz=%d, layerStack=%d",
3086 minLayerZ, maxLayerZ, hw->getLayerStack());
3087 const LayerVector& layers( mDrawingState.layersSortedByZ );
3088 const size_t count = layers.size();
3089 for (size_t i=0 ; i<count ; ++i) {
3090 const sp<Layer>& layer(layers[i]);
3091 const Layer::State& state(layer->getDrawingState());
3092 const bool visible = (state.layerStack == hw->getLayerStack())
3093 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3094 && (layer->isVisible());
3095 ALOGE("%c index=%d, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3096 visible ? '+' : '-',
3097 i, layer->getName().string(), state.layerStack, state.z,
3098 layer->isVisible(), state.flags, state.alpha);
3103 // ---------------------------------------------------------------------------
3105 SurfaceFlinger::LayerVector::LayerVector() {
3108 SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3109 : SortedVector<sp<Layer> >(rhs) {
3112 int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3113 const void* rhs) const
3115 // sort layers per layer-stack, then by z-order and finally by sequence
3116 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3117 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3119 uint32_t ls = l->getCurrentState().layerStack;
3120 uint32_t rs = r->getCurrentState().layerStack;
3124 uint32_t lz = l->getCurrentState().z;
3125 uint32_t rz = r->getCurrentState().z;
3129 return l->sequence - r->sequence;
3132 // ---------------------------------------------------------------------------
3134 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3135 : type(DisplayDevice::DISPLAY_ID_INVALID) {
3138 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
3139 : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0) {
3140 viewport.makeInvalid();
3141 frame.makeInvalid();
3144 // ---------------------------------------------------------------------------
3146 }; // namespace android
3149 #if defined(__gl_h_)
3150 #error "don't include gl/gl.h in this file"
3153 #if defined(__gl2_h_)
3154 #error "don't include gl2/gl2.h in this file"