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"
62 #include "EventThread.h"
65 #include "SurfaceFlinger.h"
67 #include "DisplayHardware/FramebufferSurface.h"
68 #include "DisplayHardware/HWComposer.h"
69 #include "DisplayHardware/VirtualDisplaySurface.h"
71 #include "Effects/Daltonizer.h"
73 #include "RenderEngine/RenderEngine.h"
74 #include <cutils/compiler.h>
76 #define DISPLAY_COUNT 1
79 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
82 #define DEBUG_SCREENSHOTS false
84 EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
87 // ---------------------------------------------------------------------------
89 const String16 sHardwareTest("android.permission.HARDWARE_TEST");
90 const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
91 const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
92 const String16 sDump("android.permission.DUMP");
94 // ---------------------------------------------------------------------------
96 SurfaceFlinger::SurfaceFlinger()
97 : BnSurfaceComposer(),
99 mTransactionPending(false),
100 mAnimTransactionPending(false),
101 mLayersRemoved(false),
102 mRepaintEverything(0),
104 mBootTime(systemTime()),
105 mVisibleRegionsDirty(false),
106 mHwWorkListDirty(false),
107 mAnimCompositionPending(false),
111 mDebugDisableTransformHint(0),
112 mDebugInSwapBuffers(0),
113 mLastSwapBufferTime(0),
114 mDebugInTransaction(0),
115 mLastTransactionTime(0),
116 mBootFinished(false),
119 ALOGI("SurfaceFlinger is starting");
121 // debugging stuff...
122 char value[PROPERTY_VALUE_MAX];
124 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
125 mGpuToCpuSupported = !atoi(value);
127 property_get("debug.sf.showupdates", value, "0");
128 mDebugRegion = atoi(value);
130 property_get("debug.sf.ddms", value, "0");
131 mDebugDDMS = atoi(value);
133 if (!startDdmConnection()) {
134 // start failed, and DDMS debugging not enabled
138 ALOGI_IF(mDebugRegion, "showupdates enabled");
139 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
142 void SurfaceFlinger::onFirstRef()
144 mEventQueue.init(this);
147 SurfaceFlinger::~SurfaceFlinger()
149 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
150 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
151 eglTerminate(display);
154 void SurfaceFlinger::binderDied(const wp<IBinder>& who)
156 // the window manager died on us. prepare its eulogy.
158 // restore initial conditions (default device unblank, etc)
159 initializeDisplays();
161 // restart the boot-animation
165 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
167 sp<ISurfaceComposerClient> bclient;
168 sp<Client> client(new Client(this));
169 status_t err = client->initCheck();
170 if (err == NO_ERROR) {
176 sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
179 class DisplayToken : public BBinder {
180 sp<SurfaceFlinger> flinger;
181 virtual ~DisplayToken() {
182 // no more references, this display must be terminated
183 Mutex::Autolock _l(flinger->mStateLock);
184 flinger->mCurrentState.displays.removeItem(this);
185 flinger->setTransactionFlags(eDisplayTransactionNeeded);
188 DisplayToken(const sp<SurfaceFlinger>& flinger)
193 sp<BBinder> token = new DisplayToken(this);
195 Mutex::Autolock _l(mStateLock);
196 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
197 info.displayName = displayName;
198 info.isSecure = secure;
199 mCurrentState.displays.add(token, info);
204 void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
205 Mutex::Autolock _l(mStateLock);
207 ssize_t idx = mCurrentState.displays.indexOfKey(display);
209 ALOGW("destroyDisplay: invalid display token");
213 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
214 if (!info.isVirtualDisplay()) {
215 ALOGE("destroyDisplay called for non-virtual display");
219 mCurrentState.displays.removeItemsAt(idx);
220 setTransactionFlags(eDisplayTransactionNeeded);
223 void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
224 ALOGW_IF(mBuiltinDisplays[type],
225 "Overwriting display token for display type %d", type);
226 mBuiltinDisplays[type] = new BBinder();
227 DisplayDeviceState info(type);
228 // All non-virtual displays are currently considered secure.
229 info.isSecure = true;
230 mCurrentState.displays.add(mBuiltinDisplays[type], info);
233 sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
234 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
235 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
238 return mBuiltinDisplays[id];
241 sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
243 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
247 void SurfaceFlinger::bootFinished()
249 const nsecs_t now = systemTime();
250 const nsecs_t duration = now - mBootTime;
251 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
252 mBootFinished = true;
254 // wait patiently for the window manager death
255 const String16 name("window");
256 sp<IBinder> window(defaultServiceManager()->getService(name));
258 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
261 // stop boot animation
262 // formerly we would just kill the process, but we now ask it to exit so it
263 // can choose where to stop the animation.
264 property_set("service.bootanim.exit", "1");
267 void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
268 class MessageDestroyGLTexture : public MessageBase {
269 RenderEngine& engine;
272 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
273 : engine(engine), texture(texture) {
275 virtual bool handler() {
276 engine.deleteTextures(1, &texture);
280 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
283 status_t SurfaceFlinger::selectConfigForAttribute(
286 EGLint attribute, EGLint wanted,
287 EGLConfig* outConfig)
289 EGLConfig config = NULL;
290 EGLint numConfigs = -1, n=0;
291 eglGetConfigs(dpy, NULL, 0, &numConfigs);
292 EGLConfig* const configs = new EGLConfig[numConfigs];
293 eglChooseConfig(dpy, attrs, configs, numConfigs, &n);
296 if (attribute != EGL_NONE) {
297 for (int i=0 ; i<n ; i++) {
299 eglGetConfigAttrib(dpy, configs[i], attribute, &value);
300 if (wanted == value) {
301 *outConfig = configs[i];
307 // just pick the first one
308 *outConfig = configs[0];
314 return NAME_NOT_FOUND;
317 class EGLAttributeVector {
321 KeyedVector<Attribute, EGLint> mList;
324 Attribute(EGLint v) : v(v) { }
326 bool operator < (const Attribute& other) const {
327 // this places EGL_NONE at the end
330 if (lhs == EGL_NONE) lhs = 0x7FFFFFFF;
331 if (rhs == EGL_NONE) rhs = 0x7FFFFFFF;
336 friend class EGLAttributeVector;
337 EGLAttributeVector& v;
339 Adder(EGLAttributeVector& v, EGLint attribute)
340 : v(v), attribute(attribute) {
343 void operator = (EGLint value) {
344 if (attribute != EGL_NONE) {
345 v.mList.add(attribute, value);
348 operator EGLint () const { return v.mList[attribute]; }
351 EGLAttributeVector() {
352 mList.add(EGL_NONE, EGL_NONE);
354 void remove(EGLint attribute) {
355 if (attribute != EGL_NONE) {
356 mList.removeItem(attribute);
359 Adder operator [] (EGLint attribute) {
360 return Adder(*this, attribute);
362 EGLint operator [] (EGLint attribute) const {
363 return mList[attribute];
365 // cast-operator to (EGLint const*)
366 operator EGLint const* () const { return &mList.keyAt(0).v; }
369 status_t SurfaceFlinger::selectEGLConfig(EGLDisplay display, EGLint nativeVisualId,
370 EGLint renderableType, EGLConfig* config) {
371 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
372 // it is to be used with WIFI displays
374 EGLint wantedAttribute;
375 EGLint wantedAttributeValue;
377 EGLAttributeVector attribs;
378 if (renderableType) {
379 attribs[EGL_RENDERABLE_TYPE] = renderableType;
380 attribs[EGL_RECORDABLE_ANDROID] = EGL_TRUE;
381 attribs[EGL_SURFACE_TYPE] = EGL_WINDOW_BIT|EGL_PBUFFER_BIT;
382 attribs[EGL_FRAMEBUFFER_TARGET_ANDROID] = EGL_TRUE;
383 attribs[EGL_RED_SIZE] = 8;
384 attribs[EGL_GREEN_SIZE] = 8;
385 attribs[EGL_BLUE_SIZE] = 8;
386 wantedAttribute = EGL_NONE;
387 wantedAttributeValue = EGL_NONE;
390 // if no renderable type specified, fallback to a simplified query
391 wantedAttribute = EGL_NATIVE_VISUAL_ID;
392 wantedAttributeValue = nativeVisualId;
395 err = selectConfigForAttribute(display, attribs, wantedAttribute,
396 wantedAttributeValue, config);
397 if (err == NO_ERROR) {
399 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
400 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
405 void SurfaceFlinger::init() {
407 ALOGI( "SurfaceFlinger's main thread ready to run. "
408 "Initializing graphics H/W...");
411 Mutex::Autolock _l(mStateLock);
413 // initialize EGL for the default display
414 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
415 eglInitialize(mEGLDisplay, NULL, NULL);
417 // Initialize the H/W composer object. There may or may not be an
418 // actual hardware composer underneath.
419 mHwc = new HWComposer(this,
420 *static_cast<HWComposer::EventHandler *>(this));
422 // First try to get an ES2 config
423 err = selectEGLConfig(mEGLDisplay, mHwc->getVisualID(), EGL_OPENGL_ES2_BIT,
426 if (err != NO_ERROR) {
427 // If ES2 fails, try ES1
428 err = selectEGLConfig(mEGLDisplay, mHwc->getVisualID(),
429 EGL_OPENGL_ES_BIT, &mEGLConfig);
432 if (err != NO_ERROR) {
433 // still didn't work, probably because we're on the emulator...
434 // try a simplified query
435 ALOGW("no suitable EGLConfig found, trying a simpler query");
436 err = selectEGLConfig(mEGLDisplay, mHwc->getVisualID(), 0, &mEGLConfig);
439 if (err != NO_ERROR) {
440 // this EGL is too lame for android
441 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
444 // print some debugging info
446 eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_RED_SIZE, &r);
447 eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_GREEN_SIZE, &g);
448 eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_BLUE_SIZE, &b);
449 eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_ALPHA_SIZE, &a);
450 ALOGI("EGL informations:");
451 ALOGI("vendor : %s", eglQueryString(mEGLDisplay, EGL_VENDOR));
452 ALOGI("version : %s", eglQueryString(mEGLDisplay, EGL_VERSION));
453 ALOGI("extensions: %s", eglQueryString(mEGLDisplay, EGL_EXTENSIONS));
454 ALOGI("Client API: %s", eglQueryString(mEGLDisplay, EGL_CLIENT_APIS)?:"Not Supported");
455 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, mEGLConfig);
457 // get a RenderEngine for the given display / config (can't fail)
458 mRenderEngine = RenderEngine::create(mEGLDisplay, mEGLConfig);
460 // retrieve the EGL context that was selected/created
461 mEGLContext = mRenderEngine->getEGLContext();
463 // figure out which format we got
464 eglGetConfigAttrib(mEGLDisplay, mEGLConfig,
465 EGL_NATIVE_VISUAL_ID, &mEGLNativeVisualId);
467 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
468 "couldn't create EGLContext");
470 // initialize our non-virtual displays
471 for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
472 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
473 // set-up the displays that are already connected
474 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
475 // All non-virtual displays are currently considered secure.
476 bool isSecure = true;
477 createBuiltinDisplayLocked(type);
478 wp<IBinder> token = mBuiltinDisplays[i];
480 sp<BufferQueue> bq = new BufferQueue(new GraphicBufferAlloc());
481 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i, bq);
482 sp<DisplayDevice> hw = new DisplayDevice(this,
483 type, allocateHwcDisplayId(type), isSecure, token,
486 if (i > DisplayDevice::DISPLAY_PRIMARY) {
487 // FIXME: currently we don't get blank/unblank requests
488 // for displays other than the main display, so we always
489 // assume a connected display is unblanked.
490 ALOGD("marking display %d as acquired/unblanked", i);
493 mDisplays.add(token, hw);
497 // make the GLContext current so that we can create textures when creating Layers
498 // (which may happens before we render something)
499 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
501 // start the EventThread
502 mEventThread = new EventThread(this);
503 mEventQueue.setEventThread(mEventThread);
505 // initialize our drawing state
506 mDrawingState = mCurrentState;
508 // set initial conditions (e.g. unblank default device)
509 initializeDisplays();
511 // start boot animation
515 int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
516 return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
517 type : mHwc->allocateDisplayId();
520 void SurfaceFlinger::startBootAnim() {
521 // start boot animation
522 property_set("service.bootanim.exit", "0");
523 property_set("ctl.start", "bootanim");
526 size_t SurfaceFlinger::getMaxTextureSize() const {
527 return mRenderEngine->getMaxTextureSize();
530 size_t SurfaceFlinger::getMaxViewportDims() const {
531 return mRenderEngine->getMaxViewportDims();
534 // ----------------------------------------------------------------------------
536 bool SurfaceFlinger::authenticateSurfaceTexture(
537 const sp<IGraphicBufferProducer>& bufferProducer) const {
538 Mutex::Autolock _l(mStateLock);
539 sp<IBinder> surfaceTextureBinder(bufferProducer->asBinder());
540 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
543 status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info) {
544 int32_t type = NAME_NOT_FOUND;
545 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
546 if (display == mBuiltinDisplays[i]) {
556 const HWComposer& hwc(getHwComposer());
557 float xdpi = hwc.getDpiX(type);
558 float ydpi = hwc.getDpiY(type);
560 // TODO: Not sure if display density should handled by SF any longer
562 static int getDensityFromProperty(char const* propName) {
563 char property[PROPERTY_VALUE_MAX];
565 if (property_get(propName, property, NULL) > 0) {
566 density = atoi(property);
571 static int getEmuDensity() {
572 return getDensityFromProperty("qemu.sf.lcd_density"); }
573 static int getBuildDensity() {
574 return getDensityFromProperty("ro.sf.lcd_density"); }
577 if (type == DisplayDevice::DISPLAY_PRIMARY) {
578 // The density of the device is provided by a build property
579 float density = Density::getBuildDensity() / 160.0f;
581 // the build doesn't provide a density -- this is wrong!
583 ALOGE("ro.sf.lcd_density must be defined as a build property");
584 density = xdpi / 160.0f;
586 if (Density::getEmuDensity()) {
587 // if "qemu.sf.lcd_density" is specified, it overrides everything
588 xdpi = ydpi = density = Density::getEmuDensity();
591 info->density = density;
593 // TODO: this needs to go away (currently needed only by webkit)
594 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
595 info->orientation = hw->getOrientation();
597 // TODO: where should this value come from?
598 static const int TV_DENSITY = 213;
599 info->density = TV_DENSITY / 160.0f;
600 info->orientation = 0;
603 info->w = hwc.getWidth(type);
604 info->h = hwc.getHeight(type);
607 info->fps = float(1e9 / hwc.getRefreshPeriod(type));
609 // All non-virtual displays are currently considered secure.
615 // ----------------------------------------------------------------------------
617 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
618 return mEventThread->createEventConnection();
621 // ----------------------------------------------------------------------------
623 void SurfaceFlinger::waitForEvent() {
624 mEventQueue.waitMessage();
627 void SurfaceFlinger::signalTransaction() {
628 mEventQueue.invalidate();
631 void SurfaceFlinger::signalLayerUpdate() {
632 mEventQueue.invalidate();
635 void SurfaceFlinger::signalRefresh() {
636 mEventQueue.refresh();
639 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
640 nsecs_t reltime, uint32_t flags) {
641 return mEventQueue.postMessage(msg, reltime);
644 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
645 nsecs_t reltime, uint32_t flags) {
646 status_t res = mEventQueue.postMessage(msg, reltime);
647 if (res == NO_ERROR) {
653 void SurfaceFlinger::run() {
659 void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
660 if (mEventThread == NULL) {
661 // This is a temporary workaround for b/7145521. A non-null pointer
662 // does not mean EventThread has finished initializing, so this
663 // is not a correct fix.
664 ALOGW("WARNING: EventThread not started, ignoring vsync");
667 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
668 // we should only receive DisplayDevice::DisplayType from the vsync callback
669 mEventThread->onVSyncReceived(type, timestamp);
673 void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
674 if (mEventThread == NULL) {
675 // This is a temporary workaround for b/7145521. A non-null pointer
676 // does not mean EventThread has finished initializing, so this
677 // is not a correct fix.
678 ALOGW("WARNING: EventThread not started, ignoring hotplug");
682 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
683 Mutex::Autolock _l(mStateLock);
685 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
687 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
688 mBuiltinDisplays[type].clear();
690 setTransactionFlags(eDisplayTransactionNeeded);
692 // Defer EventThread notification until SF has updated mDisplays.
696 void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
697 getHwComposer().eventControl(disp, event, enabled);
700 void SurfaceFlinger::onMessageReceived(int32_t what) {
703 case MessageQueue::TRANSACTION:
704 handleMessageTransaction();
706 case MessageQueue::INVALIDATE:
707 handleMessageTransaction();
708 handleMessageInvalidate();
711 case MessageQueue::REFRESH:
712 handleMessageRefresh();
717 void SurfaceFlinger::handleMessageTransaction() {
718 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
719 if (transactionFlags) {
720 handleTransaction(transactionFlags);
724 void SurfaceFlinger::handleMessageInvalidate() {
729 void SurfaceFlinger::handleMessageRefresh() {
732 rebuildLayerStacks();
734 doDebugFlashRegions();
739 void SurfaceFlinger::doDebugFlashRegions()
741 // is debugging enabled
742 if (CC_LIKELY(!mDebugRegion))
745 const bool repaintEverything = mRepaintEverything;
746 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
747 const sp<DisplayDevice>& hw(mDisplays[dpy]);
749 // transform the dirty region into this screen's coordinate space
750 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
751 if (!dirtyRegion.isEmpty()) {
752 // redraw the whole screen
753 doComposeSurfaces(hw, Region(hw->bounds()));
755 // and draw the dirty region
756 const int32_t height = hw->getHeight();
757 RenderEngine& engine(getRenderEngine());
758 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
760 hw->compositionComplete();
761 hw->swapBuffers(getHwComposer());
768 if (mDebugRegion > 1) {
769 usleep(mDebugRegion * 1000);
772 HWComposer& hwc(getHwComposer());
773 if (hwc.initCheck() == NO_ERROR) {
774 status_t err = hwc.prepare();
775 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
779 void SurfaceFlinger::preComposition()
781 bool needExtraInvalidate = false;
782 const LayerVector& layers(mDrawingState.layersSortedByZ);
783 const size_t count = layers.size();
784 for (size_t i=0 ; i<count ; i++) {
785 if (layers[i]->onPreComposition()) {
786 needExtraInvalidate = true;
789 if (needExtraInvalidate) {
794 void SurfaceFlinger::postComposition()
796 const LayerVector& layers(mDrawingState.layersSortedByZ);
797 const size_t count = layers.size();
798 for (size_t i=0 ; i<count ; i++) {
799 layers[i]->onPostComposition();
802 if (mAnimCompositionPending) {
803 mAnimCompositionPending = false;
805 const HWComposer& hwc = getHwComposer();
806 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
807 if (presentFence->isValid()) {
808 mAnimFrameTracker.setActualPresentFence(presentFence);
810 // The HWC doesn't support present fences, so use the refresh
811 // timestamp instead.
812 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
813 mAnimFrameTracker.setActualPresentTime(presentTime);
815 mAnimFrameTracker.advanceFrame();
819 void SurfaceFlinger::rebuildLayerStacks() {
820 // rebuild the visible layer list per screen
821 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
823 mVisibleRegionsDirty = false;
824 invalidateHwcGeometry();
826 const LayerVector& layers(mDrawingState.layersSortedByZ);
827 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
830 Vector< sp<Layer> > layersSortedByZ;
831 const sp<DisplayDevice>& hw(mDisplays[dpy]);
832 const Transform& tr(hw->getTransform());
833 const Rect bounds(hw->getBounds());
835 SurfaceFlinger::computeVisibleRegions(layers,
836 hw->getLayerStack(), dirtyRegion, opaqueRegion);
838 const size_t count = layers.size();
839 for (size_t i=0 ; i<count ; i++) {
840 const sp<Layer>& layer(layers[i]);
841 const Layer::State& s(layer->getDrawingState());
842 if (s.layerStack == hw->getLayerStack()) {
843 Region drawRegion(tr.transform(
844 layer->visibleNonTransparentRegion));
845 drawRegion.andSelf(bounds);
846 if (!drawRegion.isEmpty()) {
847 layersSortedByZ.add(layer);
852 hw->setVisibleLayersSortedByZ(layersSortedByZ);
853 hw->undefinedRegion.set(bounds);
854 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
855 hw->dirtyRegion.orSelf(dirtyRegion);
860 void SurfaceFlinger::setUpHWComposer() {
861 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
862 mDisplays[dpy]->beginFrame();
865 HWComposer& hwc(getHwComposer());
866 if (hwc.initCheck() == NO_ERROR) {
867 // build the h/w work list
868 if (CC_UNLIKELY(mHwWorkListDirty)) {
869 mHwWorkListDirty = false;
870 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
871 sp<const DisplayDevice> hw(mDisplays[dpy]);
872 const int32_t id = hw->getHwcDisplayId();
874 const Vector< sp<Layer> >& currentLayers(
875 hw->getVisibleLayersSortedByZ());
876 const size_t count = currentLayers.size();
877 if (hwc.createWorkList(id, count) == NO_ERROR) {
878 HWComposer::LayerListIterator cur = hwc.begin(id);
879 const HWComposer::LayerListIterator end = hwc.end(id);
880 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
881 const sp<Layer>& layer(currentLayers[i]);
882 layer->setGeometry(hw, *cur);
883 if (mDebugDisableHWC || mDebugRegion || mDaltonize) {
892 // set the per-frame data
893 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
894 sp<const DisplayDevice> hw(mDisplays[dpy]);
895 const int32_t id = hw->getHwcDisplayId();
897 const Vector< sp<Layer> >& currentLayers(
898 hw->getVisibleLayersSortedByZ());
899 const size_t count = currentLayers.size();
900 HWComposer::LayerListIterator cur = hwc.begin(id);
901 const HWComposer::LayerListIterator end = hwc.end(id);
902 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
904 * update the per-frame h/w composer data for each layer
905 * and build the transparent region of the FB
907 const sp<Layer>& layer(currentLayers[i]);
908 layer->setPerFrameData(hw, *cur);
913 status_t err = hwc.prepare();
914 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
916 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
917 sp<const DisplayDevice> hw(mDisplays[dpy]);
918 hw->prepareFrame(hwc);
923 void SurfaceFlinger::doComposition() {
925 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
926 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
927 const sp<DisplayDevice>& hw(mDisplays[dpy]);
929 // transform the dirty region into this screen's coordinate space
930 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
932 // repaint the framebuffer (if needed)
933 doDisplayComposition(hw, dirtyRegion);
935 hw->dirtyRegion.clear();
936 hw->flip(hw->swapRegion);
937 hw->swapRegion.clear();
939 // inform the h/w that we're done compositing
940 hw->compositionComplete();
945 void SurfaceFlinger::postFramebuffer()
949 const nsecs_t now = systemTime();
950 mDebugInSwapBuffers = now;
952 HWComposer& hwc(getHwComposer());
953 if (hwc.initCheck() == NO_ERROR) {
954 if (!hwc.supportsFramebufferTarget()) {
956 // "surface must be bound to the calling thread's current context,
957 // for the current rendering API."
958 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
963 // make the default display current because the VirtualDisplayDevice code cannot
964 // deal with dequeueBuffer() being called outside of the composition loop; however
965 // the code below can call glFlush() which is allowed (and does in some case) call
967 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
969 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
970 sp<const DisplayDevice> hw(mDisplays[dpy]);
971 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
972 hw->onSwapBuffersCompleted(hwc);
973 const size_t count = currentLayers.size();
974 int32_t id = hw->getHwcDisplayId();
975 if (id >=0 && hwc.initCheck() == NO_ERROR) {
976 HWComposer::LayerListIterator cur = hwc.begin(id);
977 const HWComposer::LayerListIterator end = hwc.end(id);
978 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
979 currentLayers[i]->onLayerDisplayed(hw, &*cur);
982 for (size_t i = 0; i < count; i++) {
983 currentLayers[i]->onLayerDisplayed(hw, NULL);
988 mLastSwapBufferTime = systemTime() - now;
989 mDebugInSwapBuffers = 0;
991 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
992 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
997 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1001 // here we keep a copy of the drawing state (that is the state that's
1002 // going to be overwritten by handleTransactionLocked()) outside of
1003 // mStateLock so that the side-effects of the State assignment
1004 // don't happen with mStateLock held (which can cause deadlocks).
1005 State drawingState(mDrawingState);
1007 Mutex::Autolock _l(mStateLock);
1008 const nsecs_t now = systemTime();
1009 mDebugInTransaction = now;
1011 // Here we're guaranteed that some transaction flags are set
1012 // so we can call handleTransactionLocked() unconditionally.
1013 // We call getTransactionFlags(), which will also clear the flags,
1014 // with mStateLock held to guarantee that mCurrentState won't change
1015 // until the transaction is committed.
1017 transactionFlags = getTransactionFlags(eTransactionMask);
1018 handleTransactionLocked(transactionFlags);
1020 mLastTransactionTime = systemTime() - now;
1021 mDebugInTransaction = 0;
1022 invalidateHwcGeometry();
1023 // here the transaction has been committed
1026 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1028 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1029 const size_t count = currentLayers.size();
1032 * Traversal of the children
1033 * (perform the transaction for each of them if needed)
1036 if (transactionFlags & eTraversalNeeded) {
1037 for (size_t i=0 ; i<count ; i++) {
1038 const sp<Layer>& layer(currentLayers[i]);
1039 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1040 if (!trFlags) continue;
1042 const uint32_t flags = layer->doTransaction(0);
1043 if (flags & Layer::eVisibleRegion)
1044 mVisibleRegionsDirty = true;
1049 * Perform display own transactions if needed
1052 if (transactionFlags & eDisplayTransactionNeeded) {
1053 // here we take advantage of Vector's copy-on-write semantics to
1054 // improve performance by skipping the transaction entirely when
1055 // know that the lists are identical
1056 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1057 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1058 if (!curr.isIdenticalTo(draw)) {
1059 mVisibleRegionsDirty = true;
1060 const size_t cc = curr.size();
1061 size_t dc = draw.size();
1063 // find the displays that were removed
1064 // (ie: in drawing state but not in current state)
1065 // also handle displays that changed
1066 // (ie: displays that are in both lists)
1067 for (size_t i=0 ; i<dc ; i++) {
1068 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1070 // in drawing state but not in current state
1071 if (!draw[i].isMainDisplay()) {
1072 // Call makeCurrent() on the primary display so we can
1073 // be sure that nothing associated with this display
1075 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1076 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1077 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1079 hw->disconnect(getHwComposer());
1080 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1081 mEventThread->onHotplugReceived(draw[i].type, false);
1082 mDisplays.removeItem(draw.keyAt(i));
1084 ALOGW("trying to remove the main display");
1087 // this display is in both lists. see if something changed.
1088 const DisplayDeviceState& state(curr[j]);
1089 const wp<IBinder>& display(curr.keyAt(j));
1090 if (state.surface->asBinder() != draw[i].surface->asBinder()) {
1091 // changing the surface is like destroying and
1092 // recreating the DisplayDevice, so we just remove it
1093 // from the drawing state, so that it get re-added
1095 sp<DisplayDevice> hw(getDisplayDevice(display));
1097 hw->disconnect(getHwComposer());
1098 mDisplays.removeItem(display);
1099 mDrawingState.displays.removeItemsAt(i);
1101 // at this point we must loop to the next item
1105 const sp<DisplayDevice> disp(getDisplayDevice(display));
1107 if (state.layerStack != draw[i].layerStack) {
1108 disp->setLayerStack(state.layerStack);
1110 if ((state.orientation != draw[i].orientation)
1111 || (state.viewport != draw[i].viewport)
1112 || (state.frame != draw[i].frame))
1114 disp->setProjection(state.orientation,
1115 state.viewport, state.frame);
1121 // find displays that were added
1122 // (ie: in current state but not in drawing state)
1123 for (size_t i=0 ; i<cc ; i++) {
1124 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1125 const DisplayDeviceState& state(curr[i]);
1127 sp<DisplaySurface> dispSurface;
1128 sp<IGraphicBufferProducer> producer;
1129 sp<BufferQueue> bq = new BufferQueue(new GraphicBufferAlloc());
1131 int32_t hwcDisplayId = -1;
1132 if (state.isVirtualDisplay()) {
1133 // Virtual displays without a surface are dormant:
1134 // they have external state (layer stack, projection,
1135 // etc.) but no internal state (i.e. a DisplayDevice).
1136 if (state.surface != NULL) {
1138 hwcDisplayId = allocateHwcDisplayId(state.type);
1139 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1140 *mHwc, hwcDisplayId, state.surface, bq,
1144 if (hwcDisplayId >= 0) {
1147 // There won't be any interaction with HWC for this virtual display,
1148 // so the GLES driver can pass buffers directly to the sink.
1149 producer = state.surface;
1153 ALOGE_IF(state.surface!=NULL,
1154 "adding a supported display, but rendering "
1155 "surface is provided (%p), ignoring it",
1156 state.surface.get());
1157 hwcDisplayId = allocateHwcDisplayId(state.type);
1158 // for supported (by hwc) displays we provide our
1159 // own rendering surface
1160 dispSurface = new FramebufferSurface(*mHwc, state.type, bq);
1164 const wp<IBinder>& display(curr.keyAt(i));
1165 if (dispSurface != NULL) {
1166 sp<DisplayDevice> hw = new DisplayDevice(this,
1167 state.type, hwcDisplayId, state.isSecure,
1168 display, dispSurface, producer, mEGLConfig);
1169 hw->setLayerStack(state.layerStack);
1170 hw->setProjection(state.orientation,
1171 state.viewport, state.frame);
1172 hw->setDisplayName(state.displayName);
1173 mDisplays.add(display, hw);
1174 if (state.isVirtualDisplay()) {
1175 if (hwcDisplayId >= 0) {
1176 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1177 hw->getWidth(), hw->getHeight(),
1181 mEventThread->onHotplugReceived(state.type, true);
1189 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1190 // The transform hint might have changed for some layers
1191 // (either because a display has changed, or because a layer
1194 // Walk through all the layers in currentLayers,
1195 // and update their transform hint.
1197 // If a layer is visible only on a single display, then that
1198 // display is used to calculate the hint, otherwise we use the
1201 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1202 // the hint is set before we acquire a buffer from the surface texture.
1204 // NOTE: layer transactions have taken place already, so we use their
1205 // drawing state. However, SurfaceFlinger's own transaction has not
1206 // happened yet, so we must use the current state layer list
1207 // (soon to become the drawing state list).
1209 sp<const DisplayDevice> disp;
1210 uint32_t currentlayerStack = 0;
1211 for (size_t i=0; i<count; i++) {
1212 // NOTE: we rely on the fact that layers are sorted by
1213 // layerStack first (so we don't have to traverse the list
1214 // of displays for every layer).
1215 const sp<Layer>& layer(currentLayers[i]);
1216 uint32_t layerStack = layer->getDrawingState().layerStack;
1217 if (i==0 || currentlayerStack != layerStack) {
1218 currentlayerStack = layerStack;
1219 // figure out if this layerstack is mirrored
1220 // (more than one display) if so, pick the default display,
1221 // if not, pick the only display it's on.
1223 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1224 sp<const DisplayDevice> hw(mDisplays[dpy]);
1225 if (hw->getLayerStack() == currentlayerStack) {
1236 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1237 // redraw after transform hint changes. See bug 8508397.
1239 // could be null when this layer is using a layerStack
1240 // that is not visible on any display. Also can occur at
1241 // screen off/on times.
1242 disp = getDefaultDisplayDevice();
1244 layer->updateTransformHint(disp);
1250 * Perform our own transaction if needed
1253 const LayerVector& layers(mDrawingState.layersSortedByZ);
1254 if (currentLayers.size() > layers.size()) {
1255 // layers have been added
1256 mVisibleRegionsDirty = true;
1259 // some layers might have been removed, so
1260 // we need to update the regions they're exposing.
1261 if (mLayersRemoved) {
1262 mLayersRemoved = false;
1263 mVisibleRegionsDirty = true;
1264 const size_t count = layers.size();
1265 for (size_t i=0 ; i<count ; i++) {
1266 const sp<Layer>& layer(layers[i]);
1267 if (currentLayers.indexOf(layer) < 0) {
1268 // this layer is not visible anymore
1269 // TODO: we could traverse the tree from front to back and
1270 // compute the actual visible region
1271 // TODO: we could cache the transformed region
1272 const Layer::State& s(layer->getDrawingState());
1273 Region visibleReg = s.transform.transform(
1274 Region(Rect(s.active.w, s.active.h)));
1275 invalidateLayerStack(s.layerStack, visibleReg);
1280 commitTransaction();
1283 void SurfaceFlinger::commitTransaction()
1285 if (!mLayersPendingRemoval.isEmpty()) {
1286 // Notify removed layers now that they can't be drawn from
1287 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1288 mLayersPendingRemoval[i]->onRemoved();
1290 mLayersPendingRemoval.clear();
1293 // If this transaction is part of a window animation then the next frame
1294 // we composite should be considered an animation as well.
1295 mAnimCompositionPending = mAnimTransactionPending;
1297 mDrawingState = mCurrentState;
1298 mTransactionPending = false;
1299 mAnimTransactionPending = false;
1300 mTransactionCV.broadcast();
1303 void SurfaceFlinger::computeVisibleRegions(
1304 const LayerVector& currentLayers, uint32_t layerStack,
1305 Region& outDirtyRegion, Region& outOpaqueRegion)
1309 Region aboveOpaqueLayers;
1310 Region aboveCoveredLayers;
1313 outDirtyRegion.clear();
1315 size_t i = currentLayers.size();
1317 const sp<Layer>& layer = currentLayers[i];
1319 // start with the whole surface at its current location
1320 const Layer::State& s(layer->getDrawingState());
1322 // only consider the layers on the given layer stack
1323 if (s.layerStack != layerStack)
1327 * opaqueRegion: area of a surface that is fully opaque.
1329 Region opaqueRegion;
1332 * visibleRegion: area of a surface that is visible on screen
1333 * and not fully transparent. This is essentially the layer's
1334 * footprint minus the opaque regions above it.
1335 * Areas covered by a translucent surface are considered visible.
1337 Region visibleRegion;
1340 * coveredRegion: area of a surface that is covered by all
1341 * visible regions above it (which includes the translucent areas).
1343 Region coveredRegion;
1346 * transparentRegion: area of a surface that is hinted to be completely
1347 * transparent. This is only used to tell when the layer has no visible
1348 * non-transparent regions and can be removed from the layer list. It
1349 * does not affect the visibleRegion of this layer or any layers
1350 * beneath it. The hint may not be correct if apps don't respect the
1351 * SurfaceView restrictions (which, sadly, some don't).
1353 Region transparentRegion;
1356 // handle hidden surfaces by setting the visible region to empty
1357 if (CC_LIKELY(layer->isVisible())) {
1358 const bool translucent = !layer->isOpaque();
1359 Rect bounds(s.transform.transform(layer->computeBounds()));
1360 visibleRegion.set(bounds);
1361 if (!visibleRegion.isEmpty()) {
1362 // Remove the transparent area from the visible region
1364 const Transform tr(s.transform);
1365 if (tr.transformed()) {
1366 if (tr.preserveRects()) {
1367 // transform the transparent region
1368 transparentRegion = tr.transform(s.activeTransparentRegion);
1370 // transformation too complex, can't do the
1371 // transparent region optimization.
1372 transparentRegion.clear();
1375 transparentRegion = s.activeTransparentRegion;
1379 // compute the opaque region
1380 const int32_t layerOrientation = s.transform.getOrientation();
1381 if (s.alpha==255 && !translucent &&
1382 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1383 // the opaque region is the layer's footprint
1384 opaqueRegion = visibleRegion;
1389 // Clip the covered region to the visible region
1390 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1392 // Update aboveCoveredLayers for next (lower) layer
1393 aboveCoveredLayers.orSelf(visibleRegion);
1395 // subtract the opaque region covered by the layers above us
1396 visibleRegion.subtractSelf(aboveOpaqueLayers);
1398 // compute this layer's dirty region
1399 if (layer->contentDirty) {
1400 // we need to invalidate the whole region
1401 dirty = visibleRegion;
1402 // as well, as the old visible region
1403 dirty.orSelf(layer->visibleRegion);
1404 layer->contentDirty = false;
1406 /* compute the exposed region:
1407 * the exposed region consists of two components:
1408 * 1) what's VISIBLE now and was COVERED before
1409 * 2) what's EXPOSED now less what was EXPOSED before
1411 * note that (1) is conservative, we start with the whole
1412 * visible region but only keep what used to be covered by
1413 * something -- which mean it may have been exposed.
1415 * (2) handles areas that were not covered by anything but got
1416 * exposed because of a resize.
1418 const Region newExposed = visibleRegion - coveredRegion;
1419 const Region oldVisibleRegion = layer->visibleRegion;
1420 const Region oldCoveredRegion = layer->coveredRegion;
1421 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1422 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1424 dirty.subtractSelf(aboveOpaqueLayers);
1426 // accumulate to the screen dirty region
1427 outDirtyRegion.orSelf(dirty);
1429 // Update aboveOpaqueLayers for next (lower) layer
1430 aboveOpaqueLayers.orSelf(opaqueRegion);
1432 // Store the visible region in screen space
1433 layer->setVisibleRegion(visibleRegion);
1434 layer->setCoveredRegion(coveredRegion);
1435 layer->setVisibleNonTransparentRegion(
1436 visibleRegion.subtract(transparentRegion));
1439 outOpaqueRegion = aboveOpaqueLayers;
1442 void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1443 const Region& dirty) {
1444 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1445 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1446 if (hw->getLayerStack() == layerStack) {
1447 hw->dirtyRegion.orSelf(dirty);
1452 void SurfaceFlinger::handlePageFlip()
1456 bool visibleRegions = false;
1457 const LayerVector& layers(mDrawingState.layersSortedByZ);
1458 const size_t count = layers.size();
1459 for (size_t i=0 ; i<count ; i++) {
1460 const sp<Layer>& layer(layers[i]);
1461 const Region dirty(layer->latchBuffer(visibleRegions));
1462 const Layer::State& s(layer->getDrawingState());
1463 invalidateLayerStack(s.layerStack, dirty);
1466 mVisibleRegionsDirty |= visibleRegions;
1469 void SurfaceFlinger::invalidateHwcGeometry()
1471 mHwWorkListDirty = true;
1475 void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1476 const Region& inDirtyRegion)
1478 Region dirtyRegion(inDirtyRegion);
1480 // compute the invalid region
1481 hw->swapRegion.orSelf(dirtyRegion);
1483 uint32_t flags = hw->getFlags();
1484 if (flags & DisplayDevice::SWAP_RECTANGLE) {
1485 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1486 // takes a rectangle, we must make sure to update that whole
1487 // rectangle in that case
1488 dirtyRegion.set(hw->swapRegion.bounds());
1490 if (flags & DisplayDevice::PARTIAL_UPDATES) {
1491 // We need to redraw the rectangle that will be updated
1492 // (pushed to the framebuffer).
1493 // This is needed because PARTIAL_UPDATES only takes one
1494 // rectangle instead of a region (see DisplayDevice::flip())
1495 dirtyRegion.set(hw->swapRegion.bounds());
1497 // we need to redraw everything (the whole screen)
1498 dirtyRegion.set(hw->bounds());
1499 hw->swapRegion = dirtyRegion;
1503 if (CC_LIKELY(!mDaltonize)) {
1504 doComposeSurfaces(hw, dirtyRegion);
1506 RenderEngine& engine(getRenderEngine());
1507 engine.beginGroup(mDaltonizer());
1508 doComposeSurfaces(hw, dirtyRegion);
1512 // update the swap region and clear the dirty region
1513 hw->swapRegion.orSelf(dirtyRegion);
1515 // swap buffers (presentation)
1516 hw->swapBuffers(getHwComposer());
1519 void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1521 RenderEngine& engine(getRenderEngine());
1522 const int32_t id = hw->getHwcDisplayId();
1523 HWComposer& hwc(getHwComposer());
1524 HWComposer::LayerListIterator cur = hwc.begin(id);
1525 const HWComposer::LayerListIterator end = hwc.end(id);
1527 const bool hasGlesComposition = hwc.hasGlesComposition(id) || (cur==end);
1528 if (hasGlesComposition) {
1529 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
1530 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1531 hw->getDisplayName().string());
1535 // Never touch the framebuffer if we don't have any framebuffer layers
1536 const bool hasHwcComposition = hwc.hasHwcComposition(id);
1537 if (hasHwcComposition) {
1538 // when using overlays, we assume a fully transparent framebuffer
1539 // NOTE: we could reduce how much we need to clear, for instance
1540 // remove where there are opaque FB layers. however, on some
1541 // GPUs doing a "clean slate" clear might be more efficient.
1542 // We'll revisit later if needed.
1543 engine.clearWithColor(0, 0, 0, 0);
1545 // we start with the whole screen area
1546 const Region bounds(hw->getBounds());
1548 // we remove the scissor part
1549 // we're left with the letterbox region
1550 // (common case is that letterbox ends-up being empty)
1551 const Region letterbox(bounds.subtract(hw->getScissor()));
1553 // compute the area to clear
1554 Region region(hw->undefinedRegion.merge(letterbox));
1556 // but limit it to the dirty region
1557 region.andSelf(dirty);
1559 // screen is already cleared here
1560 if (!region.isEmpty()) {
1561 // can happen with SurfaceView
1562 drawWormhole(hw, region);
1566 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
1567 // just to be on the safe side, we don't set the
1568 // scissor on the main display. It should never be needed
1569 // anyways (though in theory it could since the API allows it).
1570 const Rect& bounds(hw->getBounds());
1571 const Rect& scissor(hw->getScissor());
1572 if (scissor != bounds) {
1573 // scissor doesn't match the screen's dimensions, so we
1574 // need to clear everything outside of it and enable
1575 // the GL scissor so we don't draw anything where we shouldn't
1577 // enable scissor for this frame
1578 const uint32_t height = hw->getHeight();
1579 engine.setScissor(scissor.left, height - scissor.bottom,
1580 scissor.getWidth(), scissor.getHeight());
1586 * and then, render the layers targeted at the framebuffer
1589 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
1590 const size_t count = layers.size();
1591 const Transform& tr = hw->getTransform();
1593 // we're using h/w composer
1594 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1595 const sp<Layer>& layer(layers[i]);
1596 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1597 if (!clip.isEmpty()) {
1598 switch (cur->getCompositionType()) {
1600 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1602 && layer->isOpaque()
1603 && hasGlesComposition) {
1604 // never clear the very first layer since we're
1605 // guaranteed the FB is already cleared
1606 layer->clearWithOpenGL(hw, clip);
1610 case HWC_FRAMEBUFFER: {
1611 layer->draw(hw, clip);
1614 case HWC_FRAMEBUFFER_TARGET: {
1615 // this should not happen as the iterator shouldn't
1616 // let us get there.
1617 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%d)", i);
1622 layer->setAcquireFence(hw, *cur);
1625 // we're not using h/w composer
1626 for (size_t i=0 ; i<count ; ++i) {
1627 const sp<Layer>& layer(layers[i]);
1628 const Region clip(dirty.intersect(
1629 tr.transform(layer->visibleRegion)));
1630 if (!clip.isEmpty()) {
1631 layer->draw(hw, clip);
1636 // disable scissor at the end of the frame
1637 engine.disableScissor();
1640 void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
1641 const int32_t height = hw->getHeight();
1642 RenderEngine& engine(getRenderEngine());
1643 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
1646 void SurfaceFlinger::addClientLayer(const sp<Client>& client,
1647 const sp<IBinder>& handle,
1648 const sp<IGraphicBufferProducer>& gbc,
1649 const sp<Layer>& lbc)
1651 // attach this layer to the client
1652 client->attachLayer(handle, lbc);
1654 // add this layer to the current state list
1655 Mutex::Autolock _l(mStateLock);
1656 mCurrentState.layersSortedByZ.add(lbc);
1657 mGraphicBufferProducerList.add(gbc->asBinder());
1660 status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
1661 Mutex::Autolock _l(mStateLock);
1662 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
1664 mLayersPendingRemoval.push(layer);
1665 mLayersRemoved = true;
1666 setTransactionFlags(eTransactionNeeded);
1669 return status_t(index);
1672 uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags) {
1673 return android_atomic_release_load(&mTransactionFlags);
1676 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
1677 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1680 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
1681 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1682 if ((old & flags)==0) { // wake the server up
1683 signalTransaction();
1688 void SurfaceFlinger::setTransactionState(
1689 const Vector<ComposerState>& state,
1690 const Vector<DisplayState>& displays,
1694 Mutex::Autolock _l(mStateLock);
1695 uint32_t transactionFlags = 0;
1697 if (flags & eAnimation) {
1698 // For window updates that are part of an animation we must wait for
1699 // previous animation "frames" to be handled.
1700 while (mAnimTransactionPending) {
1701 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1702 if (CC_UNLIKELY(err != NO_ERROR)) {
1703 // just in case something goes wrong in SF, return to the
1704 // caller after a few seconds.
1705 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
1706 "waiting for previous animation frame");
1707 mAnimTransactionPending = false;
1713 size_t count = displays.size();
1714 for (size_t i=0 ; i<count ; i++) {
1715 const DisplayState& s(displays[i]);
1716 transactionFlags |= setDisplayStateLocked(s);
1719 count = state.size();
1720 for (size_t i=0 ; i<count ; i++) {
1721 const ComposerState& s(state[i]);
1722 // Here we need to check that the interface we're given is indeed
1723 // one of our own. A malicious client could give us a NULL
1724 // IInterface, or one of its own or even one of our own but a
1725 // different type. All these situations would cause us to crash.
1727 // NOTE: it would be better to use RTTI as we could directly check
1728 // that we have a Client*. however, RTTI is disabled in Android.
1729 if (s.client != NULL) {
1730 sp<IBinder> binder = s.client->asBinder();
1731 if (binder != NULL) {
1732 String16 desc(binder->getInterfaceDescriptor());
1733 if (desc == ISurfaceComposerClient::descriptor) {
1734 sp<Client> client( static_cast<Client *>(s.client.get()) );
1735 transactionFlags |= setClientStateLocked(client, s.state);
1741 if (transactionFlags) {
1742 // this triggers the transaction
1743 setTransactionFlags(transactionFlags);
1745 // if this is a synchronous transaction, wait for it to take effect
1746 // before returning.
1747 if (flags & eSynchronous) {
1748 mTransactionPending = true;
1750 if (flags & eAnimation) {
1751 mAnimTransactionPending = true;
1753 while (mTransactionPending) {
1754 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1755 if (CC_UNLIKELY(err != NO_ERROR)) {
1756 // just in case something goes wrong in SF, return to the
1757 // called after a few seconds.
1758 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
1759 mTransactionPending = false;
1766 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
1768 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
1773 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
1774 if (disp.isValid()) {
1775 const uint32_t what = s.what;
1776 if (what & DisplayState::eSurfaceChanged) {
1777 if (disp.surface->asBinder() != s.surface->asBinder()) {
1778 disp.surface = s.surface;
1779 flags |= eDisplayTransactionNeeded;
1782 if (what & DisplayState::eLayerStackChanged) {
1783 if (disp.layerStack != s.layerStack) {
1784 disp.layerStack = s.layerStack;
1785 flags |= eDisplayTransactionNeeded;
1788 if (what & DisplayState::eDisplayProjectionChanged) {
1789 if (disp.orientation != s.orientation) {
1790 disp.orientation = s.orientation;
1791 flags |= eDisplayTransactionNeeded;
1793 if (disp.frame != s.frame) {
1794 disp.frame = s.frame;
1795 flags |= eDisplayTransactionNeeded;
1797 if (disp.viewport != s.viewport) {
1798 disp.viewport = s.viewport;
1799 flags |= eDisplayTransactionNeeded;
1806 uint32_t SurfaceFlinger::setClientStateLocked(
1807 const sp<Client>& client,
1808 const layer_state_t& s)
1811 sp<Layer> layer(client->getLayerUser(s.surface));
1813 const uint32_t what = s.what;
1814 if (what & layer_state_t::ePositionChanged) {
1815 if (layer->setPosition(s.x, s.y))
1816 flags |= eTraversalNeeded;
1818 if (what & layer_state_t::eLayerChanged) {
1819 // NOTE: index needs to be calculated before we update the state
1820 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1821 if (layer->setLayer(s.z)) {
1822 mCurrentState.layersSortedByZ.removeAt(idx);
1823 mCurrentState.layersSortedByZ.add(layer);
1824 // we need traversal (state changed)
1825 // AND transaction (list changed)
1826 flags |= eTransactionNeeded|eTraversalNeeded;
1829 if (what & layer_state_t::eSizeChanged) {
1830 if (layer->setSize(s.w, s.h)) {
1831 flags |= eTraversalNeeded;
1834 if (what & layer_state_t::eAlphaChanged) {
1835 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1836 flags |= eTraversalNeeded;
1838 if (what & layer_state_t::eMatrixChanged) {
1839 if (layer->setMatrix(s.matrix))
1840 flags |= eTraversalNeeded;
1842 if (what & layer_state_t::eTransparentRegionChanged) {
1843 if (layer->setTransparentRegionHint(s.transparentRegion))
1844 flags |= eTraversalNeeded;
1846 if (what & layer_state_t::eVisibilityChanged) {
1847 if (layer->setFlags(s.flags, s.mask))
1848 flags |= eTraversalNeeded;
1850 if (what & layer_state_t::eCropChanged) {
1851 if (layer->setCrop(s.crop))
1852 flags |= eTraversalNeeded;
1854 if (what & layer_state_t::eLayerStackChanged) {
1855 // NOTE: index needs to be calculated before we update the state
1856 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1857 if (layer->setLayerStack(s.layerStack)) {
1858 mCurrentState.layersSortedByZ.removeAt(idx);
1859 mCurrentState.layersSortedByZ.add(layer);
1860 // we need traversal (state changed)
1861 // AND transaction (list changed)
1862 flags |= eTransactionNeeded|eTraversalNeeded;
1869 status_t SurfaceFlinger::createLayer(
1870 const String8& name,
1871 const sp<Client>& client,
1872 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
1873 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
1875 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
1876 if (int32_t(w|h) < 0) {
1877 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
1882 status_t result = NO_ERROR;
1886 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
1887 case ISurfaceComposerClient::eFXSurfaceNormal:
1888 result = createNormalLayer(client,
1889 name, w, h, flags, format,
1890 handle, gbp, &layer);
1892 case ISurfaceComposerClient::eFXSurfaceDim:
1893 result = createDimLayer(client,
1895 handle, gbp, &layer);
1902 if (result == NO_ERROR) {
1903 addClientLayer(client, *handle, *gbp, layer);
1904 setTransactionFlags(eTransactionNeeded);
1909 status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
1910 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
1911 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
1913 // initialize the surfaces
1915 case PIXEL_FORMAT_TRANSPARENT:
1916 case PIXEL_FORMAT_TRANSLUCENT:
1917 format = PIXEL_FORMAT_RGBA_8888;
1919 case PIXEL_FORMAT_OPAQUE:
1921 format = PIXEL_FORMAT_RGB_565;
1923 format = PIXEL_FORMAT_RGBX_8888;
1929 if (format == PIXEL_FORMAT_RGBX_8888)
1930 format = PIXEL_FORMAT_RGBA_8888;
1933 *outLayer = new Layer(this, client, name, w, h, flags);
1934 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
1935 if (err == NO_ERROR) {
1936 *handle = (*outLayer)->getHandle();
1937 *gbp = (*outLayer)->getBufferQueue();
1940 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
1944 status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
1945 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
1946 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
1948 *outLayer = new LayerDim(this, client, name, w, h, flags);
1949 *handle = (*outLayer)->getHandle();
1950 *gbp = (*outLayer)->getBufferQueue();
1954 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
1956 // called by the window manager when it wants to remove a Layer
1957 status_t err = NO_ERROR;
1958 sp<Layer> l(client->getLayerUser(handle));
1960 err = removeLayer(l);
1961 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
1962 "error removing layer=%p (%s)", l.get(), strerror(-err));
1967 status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
1969 // called by ~LayerCleaner() when all references to the IBinder (handle)
1971 status_t err = NO_ERROR;
1972 sp<Layer> l(layer.promote());
1974 err = removeLayer(l);
1975 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
1976 "error removing layer=%p (%s)", l.get(), strerror(-err));
1981 // ---------------------------------------------------------------------------
1983 void SurfaceFlinger::onInitializeDisplays() {
1984 // reset screen orientation and use primary layer stack
1985 Vector<ComposerState> state;
1986 Vector<DisplayState> displays;
1988 d.what = DisplayState::eDisplayProjectionChanged |
1989 DisplayState::eLayerStackChanged;
1990 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
1992 d.orientation = DisplayState::eOrientationDefault;
1993 d.frame.makeInvalid();
1994 d.viewport.makeInvalid();
1996 setTransactionState(state, displays, 0);
1997 onScreenAcquired(getDefaultDisplayDevice());
1999 const nsecs_t period =
2000 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2001 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2004 void SurfaceFlinger::initializeDisplays() {
2005 class MessageScreenInitialized : public MessageBase {
2006 SurfaceFlinger* flinger;
2008 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2009 virtual bool handler() {
2010 flinger->onInitializeDisplays();
2014 sp<MessageBase> msg = new MessageScreenInitialized(this);
2015 postMessageAsync(msg); // we may be called from main thread, use async message
2019 void SurfaceFlinger::onScreenAcquired(const sp<const DisplayDevice>& hw) {
2020 ALOGD("Screen acquired, type=%d flinger=%p", hw->getDisplayType(), this);
2021 if (hw->isScreenAcquired()) {
2022 // this is expected, e.g. when power manager wakes up during boot
2023 ALOGD(" screen was previously acquired");
2027 hw->acquireScreen();
2028 int32_t type = hw->getDisplayType();
2029 if (type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2030 // built-in display, tell the HWC
2031 getHwComposer().acquire(type);
2033 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2034 // FIXME: eventthread only knows about the main display right now
2035 mEventThread->onScreenAcquired();
2038 mVisibleRegionsDirty = true;
2039 repaintEverything();
2042 void SurfaceFlinger::onScreenReleased(const sp<const DisplayDevice>& hw) {
2043 ALOGD("Screen released, type=%d flinger=%p", hw->getDisplayType(), this);
2044 if (!hw->isScreenAcquired()) {
2045 ALOGD(" screen was previously released");
2049 hw->releaseScreen();
2050 int32_t type = hw->getDisplayType();
2051 if (type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2052 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2053 // FIXME: eventthread only knows about the main display right now
2054 mEventThread->onScreenReleased();
2057 // built-in display, tell the HWC
2058 getHwComposer().release(type);
2060 mVisibleRegionsDirty = true;
2061 // from this point on, SF will stop drawing on this display
2064 void SurfaceFlinger::unblank(const sp<IBinder>& display) {
2065 class MessageScreenAcquired : public MessageBase {
2066 SurfaceFlinger& mFlinger;
2067 sp<IBinder> mDisplay;
2069 MessageScreenAcquired(SurfaceFlinger& flinger,
2070 const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { }
2071 virtual bool handler() {
2072 const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2074 ALOGE("Attempt to unblank null display %p", mDisplay.get());
2075 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2076 ALOGW("Attempt to unblank virtual display");
2078 mFlinger.onScreenAcquired(hw);
2083 sp<MessageBase> msg = new MessageScreenAcquired(*this, display);
2084 postMessageSync(msg);
2087 void SurfaceFlinger::blank(const sp<IBinder>& display) {
2088 class MessageScreenReleased : public MessageBase {
2089 SurfaceFlinger& mFlinger;
2090 sp<IBinder> mDisplay;
2092 MessageScreenReleased(SurfaceFlinger& flinger,
2093 const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { }
2094 virtual bool handler() {
2095 const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2097 ALOGE("Attempt to blank null display %p", mDisplay.get());
2098 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2099 ALOGW("Attempt to blank virtual display");
2101 mFlinger.onScreenReleased(hw);
2106 sp<MessageBase> msg = new MessageScreenReleased(*this, display);
2107 postMessageSync(msg);
2110 // ---------------------------------------------------------------------------
2112 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2116 IPCThreadState* ipc = IPCThreadState::self();
2117 const int pid = ipc->getCallingPid();
2118 const int uid = ipc->getCallingUid();
2119 if ((uid != AID_SHELL) &&
2120 !PermissionCache::checkPermission(sDump, pid, uid)) {
2121 result.appendFormat("Permission Denial: "
2122 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2124 // Try to get the main lock, but don't insist if we can't
2125 // (this would indicate SF is stuck, but we want to be able to
2126 // print something in dumpsys).
2128 while (mStateLock.tryLock()<0 && --retry>=0) {
2131 const bool locked(retry >= 0);
2134 "SurfaceFlinger appears to be unresponsive, "
2135 "dumping anyways (no locks held)\n");
2138 bool dumpAll = true;
2140 size_t numArgs = args.size();
2142 if ((index < numArgs) &&
2143 (args[index] == String16("--list"))) {
2145 listLayersLocked(args, index, result);
2149 if ((index < numArgs) &&
2150 (args[index] == String16("--latency"))) {
2152 dumpStatsLocked(args, index, result);
2156 if ((index < numArgs) &&
2157 (args[index] == String16("--latency-clear"))) {
2159 clearStatsLocked(args, index, result);
2165 dumpAllLocked(args, index, result);
2169 mStateLock.unlock();
2172 write(fd, result.string(), result.size());
2176 void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
2177 String8& result) const
2179 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2180 const size_t count = currentLayers.size();
2181 for (size_t i=0 ; i<count ; i++) {
2182 const sp<Layer>& layer(currentLayers[i]);
2183 result.appendFormat("%s\n", layer->getName().string());
2187 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2188 String8& result) const
2191 if (index < args.size()) {
2192 name = String8(args[index]);
2196 const nsecs_t period =
2197 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2198 result.appendFormat("%lld\n", period);
2200 if (name.isEmpty()) {
2201 mAnimFrameTracker.dump(result);
2203 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2204 const size_t count = currentLayers.size();
2205 for (size_t i=0 ; i<count ; i++) {
2206 const sp<Layer>& layer(currentLayers[i]);
2207 if (name == layer->getName()) {
2208 layer->dumpStats(result);
2214 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2218 if (index < args.size()) {
2219 name = String8(args[index]);
2223 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2224 const size_t count = currentLayers.size();
2225 for (size_t i=0 ; i<count ; i++) {
2226 const sp<Layer>& layer(currentLayers[i]);
2227 if (name.isEmpty() || (name == layer->getName())) {
2228 layer->clearStats();
2232 mAnimFrameTracker.clear();
2235 // This should only be called from the main thread. Otherwise it would need
2236 // the lock and should use mCurrentState rather than mDrawingState.
2237 void SurfaceFlinger::logFrameStats() {
2238 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2239 const size_t count = drawingLayers.size();
2240 for (size_t i=0 ; i<count ; i++) {
2241 const sp<Layer>& layer(drawingLayers[i]);
2242 layer->logFrameStats();
2245 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2248 /*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2250 static const char* config =
2255 #ifdef HAS_CONTEXT_PRIORITY
2256 " HAS_CONTEXT_PRIORITY"
2258 #ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2259 " NEVER_DEFAULT_TO_ASYNC_MODE"
2261 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2262 " TARGET_DISABLE_TRIPLE_BUFFERING"
2265 result.append(config);
2268 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2269 String8& result) const
2271 bool colorize = false;
2272 if (index < args.size()
2273 && (args[index] == String16("--color"))) {
2278 Colorizer colorizer(colorize);
2280 // figure out if we're stuck somewhere
2281 const nsecs_t now = systemTime();
2282 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2283 const nsecs_t inTransaction(mDebugInTransaction);
2284 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2285 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2288 * Dump library configuration.
2291 colorizer.bold(result);
2292 result.append("Build configuration:");
2293 colorizer.reset(result);
2294 appendSfConfigString(result);
2295 appendUiConfigString(result);
2296 appendGuiConfigString(result);
2297 result.append("\n");
2299 colorizer.bold(result);
2300 result.append("Sync configuration: ");
2301 colorizer.reset(result);
2302 result.append(SyncFeatures::getInstance().toString());
2303 result.append("\n");
2306 * Dump the visible layer list
2308 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2309 const size_t count = currentLayers.size();
2310 colorizer.bold(result);
2311 result.appendFormat("Visible layers (count = %d)\n", count);
2312 colorizer.reset(result);
2313 for (size_t i=0 ; i<count ; i++) {
2314 const sp<Layer>& layer(currentLayers[i]);
2315 layer->dump(result, colorizer);
2319 * Dump Display state
2322 colorizer.bold(result);
2323 result.appendFormat("Displays (%d entries)\n", mDisplays.size());
2324 colorizer.reset(result);
2325 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2326 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2331 * Dump SurfaceFlinger global state
2334 colorizer.bold(result);
2335 result.append("SurfaceFlinger global state:\n");
2336 colorizer.reset(result);
2338 HWComposer& hwc(getHwComposer());
2339 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2341 colorizer.bold(result);
2342 result.appendFormat("EGL implementation : %s\n",
2343 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2344 colorizer.reset(result);
2345 result.appendFormat("%s\n",
2346 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2348 mRenderEngine->dump(result);
2350 hw->undefinedRegion.dump(result, "undefinedRegion");
2351 result.appendFormat(" orientation=%d, canDraw=%d\n",
2352 hw->getOrientation(), hw->canDraw());
2353 result.appendFormat(
2354 " last eglSwapBuffers() time: %f us\n"
2355 " last transaction time : %f us\n"
2356 " transaction-flags : %08x\n"
2357 " refresh-rate : %f fps\n"
2360 " EGL_NATIVE_VISUAL_ID : %d\n"
2361 " gpu_to_cpu_unsupported : %d\n"
2363 mLastSwapBufferTime/1000.0,
2364 mLastTransactionTime/1000.0,
2366 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2367 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2368 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2370 !mGpuToCpuSupported);
2372 result.appendFormat(" eglSwapBuffers time: %f us\n",
2373 inSwapBuffersDuration/1000.0);
2375 result.appendFormat(" transaction time: %f us\n",
2376 inTransactionDuration/1000.0);
2381 mEventThread->dump(result);
2384 * Dump HWComposer state
2386 colorizer.bold(result);
2387 result.append("h/w composer state:\n");
2388 colorizer.reset(result);
2389 result.appendFormat(" h/w composer %s and %s\n",
2390 hwc.initCheck()==NO_ERROR ? "present" : "not present",
2391 (mDebugDisableHWC || mDebugRegion || mDaltonize) ? "disabled" : "enabled");
2395 * Dump gralloc state
2397 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2401 const Vector< sp<Layer> >&
2402 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2403 // Note: mStateLock is held here
2405 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2406 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2407 dpy = mDisplays.keyAt(i);
2412 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2413 // Just use the primary display so we have something to return
2414 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2416 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2419 bool SurfaceFlinger::startDdmConnection()
2421 void* libddmconnection_dso =
2422 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2423 if (!libddmconnection_dso) {
2426 void (*DdmConnection_start)(const char* name);
2427 DdmConnection_start =
2428 (typeof DdmConnection_start)dlsym(libddmconnection_dso, "DdmConnection_start");
2429 if (!DdmConnection_start) {
2430 dlclose(libddmconnection_dso);
2433 (*DdmConnection_start)(getServiceName());
2437 status_t SurfaceFlinger::onTransact(
2438 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2441 case CREATE_CONNECTION:
2442 case CREATE_DISPLAY:
2443 case SET_TRANSACTION_STATE:
2448 // codes that require permission check
2449 IPCThreadState* ipc = IPCThreadState::self();
2450 const int pid = ipc->getCallingPid();
2451 const int uid = ipc->getCallingUid();
2452 if ((uid != AID_GRAPHICS) &&
2453 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2454 ALOGE("Permission Denial: "
2455 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2456 return PERMISSION_DENIED;
2460 case CAPTURE_SCREEN:
2462 // codes that require permission check
2463 IPCThreadState* ipc = IPCThreadState::self();
2464 const int pid = ipc->getCallingPid();
2465 const int uid = ipc->getCallingUid();
2466 if ((uid != AID_GRAPHICS) &&
2467 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2468 ALOGE("Permission Denial: "
2469 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2470 return PERMISSION_DENIED;
2476 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2477 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2478 CHECK_INTERFACE(ISurfaceComposer, data, reply);
2479 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2480 IPCThreadState* ipc = IPCThreadState::self();
2481 const int pid = ipc->getCallingPid();
2482 const int uid = ipc->getCallingUid();
2483 ALOGE("Permission Denial: "
2484 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2485 return PERMISSION_DENIED;
2489 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2490 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2492 case 1002: // SHOW_UPDATES
2493 n = data.readInt32();
2494 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2495 invalidateHwcGeometry();
2496 repaintEverything();
2498 case 1004:{ // repaint everything
2499 repaintEverything();
2502 case 1005:{ // force transaction
2503 setTransactionFlags(
2505 eDisplayTransactionNeeded|
2509 case 1006:{ // send empty update
2513 case 1008: // toggle use of hw composer
2514 n = data.readInt32();
2515 mDebugDisableHWC = n ? 1 : 0;
2516 invalidateHwcGeometry();
2517 repaintEverything();
2519 case 1009: // toggle use of transform hint
2520 n = data.readInt32();
2521 mDebugDisableTransformHint = n ? 1 : 0;
2522 invalidateHwcGeometry();
2523 repaintEverything();
2525 case 1010: // interrogate.
2526 reply->writeInt32(0);
2527 reply->writeInt32(0);
2528 reply->writeInt32(mDebugRegion);
2529 reply->writeInt32(0);
2530 reply->writeInt32(mDebugDisableHWC);
2533 Mutex::Autolock _l(mStateLock);
2534 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2535 reply->writeInt32(hw->getPageFlipCount());
2540 n = data.readInt32();
2542 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
2543 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
2544 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
2547 mDaltonizer.setMode(Daltonizer::correction);
2549 mDaltonizer.setMode(Daltonizer::simulation);
2552 invalidateHwcGeometry();
2553 repaintEverything();
2561 void SurfaceFlinger::repaintEverything() {
2562 android_atomic_or(1, &mRepaintEverything);
2563 signalTransaction();
2566 // ---------------------------------------------------------------------------
2567 // Capture screen into an IGraphiBufferProducer
2568 // ---------------------------------------------------------------------------
2570 /* The code below is here to handle b/8734824
2572 * We create a IGraphicBufferProducer wrapper that forwards all calls
2573 * to the calling binder thread, where they are executed. This allows
2574 * the calling thread to be reused (on the other side) and not
2575 * depend on having "enough" binder threads to handle the requests.
2579 class GraphicProducerWrapper : public BBinder, public MessageHandler {
2580 sp<IGraphicBufferProducer> impl;
2585 mutable Barrier barrier;
2586 volatile int32_t memoryBarrier;
2597 * this is called by our "fake" BpGraphicBufferProducer. We package the
2598 * data and reply Parcel and forward them to the calling thread.
2600 virtual status_t transact(uint32_t code,
2601 const Parcel& data, Parcel* reply, uint32_t flags) {
2604 this->reply = reply;
2605 android_atomic_acquire_store(0, &memoryBarrier);
2607 // if we've exited, we run the message synchronously right here
2608 handleMessage(Message(MSG_API_CALL));
2611 looper->sendMessage(this, Message(MSG_API_CALL));
2618 * here we run on the binder calling thread. All we've got to do is
2619 * call the real BpGraphicBufferProducer.
2621 virtual void handleMessage(const Message& message) {
2622 android_atomic_release_load(&memoryBarrier);
2623 if (message.what == MSG_API_CALL) {
2624 impl->asBinder()->transact(code, data[0], reply);
2626 } else if (message.what == MSG_EXIT) {
2627 exitRequested = true;
2632 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl) :
2633 impl(impl), looper(new Looper(true)), result(NO_ERROR),
2634 exitPending(false), exitRequested(false) {
2637 status_t waitForResponse() {
2639 looper->pollOnce(-1);
2640 } while (!exitRequested);
2644 void exit(status_t result) {
2645 this->result = result;
2647 looper->sendMessage(this, Message(MSG_EXIT));
2652 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
2653 const sp<IGraphicBufferProducer>& producer,
2654 uint32_t reqWidth, uint32_t reqHeight,
2655 uint32_t minLayerZ, uint32_t maxLayerZ) {
2657 if (CC_UNLIKELY(display == 0))
2660 if (CC_UNLIKELY(producer == 0))
2663 // if we have secure windows on this display, never allow the screen capture
2664 // unless the producer interface is local (i.e.: we can take a screenshot for
2666 if (!producer->asBinder()->localBinder()) {
2667 Mutex::Autolock _l(mStateLock);
2668 sp<const DisplayDevice> hw(getDisplayDevice(display));
2669 if (hw->getSecureLayerVisible()) {
2670 ALOGW("FB is protected: PERMISSION_DENIED");
2671 return PERMISSION_DENIED;
2675 class MessageCaptureScreen : public MessageBase {
2676 SurfaceFlinger* flinger;
2677 sp<IBinder> display;
2678 sp<IGraphicBufferProducer> producer;
2679 uint32_t reqWidth, reqHeight;
2680 uint32_t minLayerZ,maxLayerZ;
2683 MessageCaptureScreen(SurfaceFlinger* flinger,
2684 const sp<IBinder>& display,
2685 const sp<IGraphicBufferProducer>& producer,
2686 uint32_t reqWidth, uint32_t reqHeight,
2687 uint32_t minLayerZ, uint32_t maxLayerZ)
2688 : flinger(flinger), display(display), producer(producer),
2689 reqWidth(reqWidth), reqHeight(reqHeight),
2690 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2691 result(PERMISSION_DENIED)
2694 status_t getResult() const {
2697 virtual bool handler() {
2698 Mutex::Autolock _l(flinger->mStateLock);
2699 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
2700 result = flinger->captureScreenImplLocked(hw,
2701 producer, reqWidth, reqHeight, minLayerZ, maxLayerZ);
2702 static_cast<GraphicProducerWrapper*>(producer->asBinder().get())->exit(result);
2707 // make sure to process transactions before screenshots -- a transaction
2708 // might already be pending but scheduled for VSYNC; this guarantees we
2709 // will handle it before the screenshot. When VSYNC finally arrives
2710 // the scheduled transaction will be a no-op. If no transactions are
2711 // scheduled at this time, this will end-up being a no-op as well.
2712 mEventQueue.invalidateTransactionNow();
2714 // this creates a "fake" BBinder which will serve as a "fake" remote
2715 // binder to receive the marshaled calls and forward them to the
2716 // real remote (a BpGraphicBufferProducer)
2717 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
2719 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
2720 // which does the marshaling work forwards to our "fake remote" above.
2721 sp<MessageBase> msg = new MessageCaptureScreen(this,
2722 display, IGraphicBufferProducer::asInterface( wrapper ),
2723 reqWidth, reqHeight, minLayerZ, maxLayerZ);
2725 status_t res = postMessageAsync(msg);
2726 if (res == NO_ERROR) {
2727 res = wrapper->waitForResponse();
2733 void SurfaceFlinger::renderScreenImplLocked(
2734 const sp<const DisplayDevice>& hw,
2735 uint32_t reqWidth, uint32_t reqHeight,
2736 uint32_t minLayerZ, uint32_t maxLayerZ,
2740 RenderEngine& engine(getRenderEngine());
2742 // get screen geometry
2743 const uint32_t hw_w = hw->getWidth();
2744 const uint32_t hw_h = hw->getHeight();
2745 const bool filtering = reqWidth != hw_w || reqWidth != hw_h;
2747 // make sure to clear all GL error flags
2748 engine.checkErrors();
2750 // set-up our viewport
2751 engine.setViewportAndProjection(reqWidth, reqHeight, hw_w, hw_h, yswap);
2752 engine.disableTexturing();
2754 // redraw the screen entirely...
2755 engine.clearWithColor(0, 0, 0, 1);
2757 const LayerVector& layers( mDrawingState.layersSortedByZ );
2758 const size_t count = layers.size();
2759 for (size_t i=0 ; i<count ; ++i) {
2760 const sp<Layer>& layer(layers[i]);
2761 const Layer::State& state(layer->getDrawingState());
2762 if (state.layerStack == hw->getLayerStack()) {
2763 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
2764 if (layer->isVisible()) {
2765 if (filtering) layer->setFiltering(true);
2767 if (filtering) layer->setFiltering(false);
2773 // compositionComplete is needed for older driver
2774 hw->compositionComplete();
2775 hw->setViewportAndProjection();
2779 status_t SurfaceFlinger::captureScreenImplLocked(
2780 const sp<const DisplayDevice>& hw,
2781 const sp<IGraphicBufferProducer>& producer,
2782 uint32_t reqWidth, uint32_t reqHeight,
2783 uint32_t minLayerZ, uint32_t maxLayerZ)
2787 // get screen geometry
2788 const uint32_t hw_w = hw->getWidth();
2789 const uint32_t hw_h = hw->getHeight();
2791 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
2792 ALOGE("size mismatch (%d, %d) > (%d, %d)",
2793 reqWidth, reqHeight, hw_w, hw_h);
2797 reqWidth = (!reqWidth) ? hw_w : reqWidth;
2798 reqHeight = (!reqHeight) ? hw_h : reqHeight;
2800 // create a surface (because we're a producer, and we need to
2801 // dequeue/queue a buffer)
2802 sp<Surface> sur = new Surface(producer, false);
2803 ANativeWindow* window = sur.get();
2805 status_t result = NO_ERROR;
2806 if (native_window_api_connect(window, NATIVE_WINDOW_API_EGL) == NO_ERROR) {
2807 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
2808 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
2811 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
2812 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
2813 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
2814 err |= native_window_set_usage(window, usage);
2816 if (err == NO_ERROR) {
2817 ANativeWindowBuffer* buffer;
2818 /* TODO: Once we have the sync framework everywhere this can use
2819 * server-side waits on the fence that dequeueBuffer returns.
2821 result = native_window_dequeue_buffer_and_wait(window, &buffer);
2822 if (result == NO_ERROR) {
2823 // create an EGLImage from the buffer so we can later
2824 // turn it into a texture
2825 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
2826 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
2827 if (image != EGL_NO_IMAGE_KHR) {
2828 // this binds the given EGLImage as a framebuffer for the
2829 // duration of this scope.
2830 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
2831 if (imageBond.getStatus() == NO_ERROR) {
2832 // this will in fact render into our dequeued buffer
2833 // via an FBO, which means we didn't have to create
2834 // an EGLSurface and therefore we're not
2835 // dependent on the context's EGLConfig.
2836 renderScreenImplLocked(hw, reqWidth, reqHeight,
2837 minLayerZ, maxLayerZ, true);
2839 if (DEBUG_SCREENSHOTS) {
2840 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
2841 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
2842 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
2843 hw, minLayerZ, maxLayerZ);
2848 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
2849 result = INVALID_OPERATION;
2851 // destroy our image
2852 eglDestroyImageKHR(mEGLDisplay, image);
2856 window->queueBuffer(window, buffer, -1);
2861 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
2867 void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
2868 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
2869 if (DEBUG_SCREENSHOTS) {
2870 for (size_t y=0 ; y<h ; y++) {
2871 uint32_t const * p = (uint32_t const *)vaddr + y*s;
2872 for (size_t x=0 ; x<w ; x++) {
2873 if (p[x] != 0xFF000000) return;
2876 ALOGE("*** we just took a black screenshot ***\n"
2877 "requested minz=%d, maxz=%d, layerStack=%d",
2878 minLayerZ, maxLayerZ, hw->getLayerStack());
2879 const LayerVector& layers( mDrawingState.layersSortedByZ );
2880 const size_t count = layers.size();
2881 for (size_t i=0 ; i<count ; ++i) {
2882 const sp<Layer>& layer(layers[i]);
2883 const Layer::State& state(layer->getDrawingState());
2884 const bool visible = (state.layerStack == hw->getLayerStack())
2885 && (state.z >= minLayerZ && state.z <= maxLayerZ)
2886 && (layer->isVisible());
2887 ALOGE("%c index=%d, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
2888 visible ? '+' : '-',
2889 i, layer->getName().string(), state.layerStack, state.z,
2890 layer->isVisible(), state.flags, state.alpha);
2895 // ---------------------------------------------------------------------------
2897 SurfaceFlinger::LayerVector::LayerVector() {
2900 SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
2901 : SortedVector<sp<Layer> >(rhs) {
2904 int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
2905 const void* rhs) const
2907 // sort layers per layer-stack, then by z-order and finally by sequence
2908 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
2909 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
2911 uint32_t ls = l->getCurrentState().layerStack;
2912 uint32_t rs = r->getCurrentState().layerStack;
2916 uint32_t lz = l->getCurrentState().z;
2917 uint32_t rz = r->getCurrentState().z;
2921 return l->sequence - r->sequence;
2924 // ---------------------------------------------------------------------------
2926 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
2927 : type(DisplayDevice::DISPLAY_ID_INVALID) {
2930 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
2931 : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0) {
2932 viewport.makeInvalid();
2933 frame.makeInvalid();
2936 // ---------------------------------------------------------------------------
2938 }; // namespace android
2941 #if defined(__gl_h_)
2942 #error "don't include gl/gl.h in this file"
2945 #if defined(__gl2_h_)
2946 #error "don't include gl2/gl2.h in this file"