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 #ifndef ANDROID_SURFACE_FLINGER_H
18 #define ANDROID_SURFACE_FLINGER_H
21 #include <sys/types.h>
26 * NOTE: Make sure this file doesn't include anything from <gl/ > or <gl2/ >
29 #include <cutils/compiler.h>
31 #include <utils/Atomic.h>
32 #include <utils/Errors.h>
33 #include <utils/KeyedVector.h>
34 #include <utils/RefBase.h>
35 #include <utils/SortedVector.h>
36 #include <utils/threads.h>
38 #include <binder/IMemory.h>
40 #include <ui/PixelFormat.h>
43 #include <gui/ISurfaceComposer.h>
44 #include <gui/ISurfaceComposerClient.h>
46 #include <hardware/hwcomposer_defs.h>
48 #include <private/gui/LayerState.h>
51 #include "DisplayDevice.h"
53 #include "FrameTracker.h"
54 #include "MessageQueue.h"
56 #include "DisplayHardware/HWComposer.h"
57 #include "Effects/Daltonizer.h"
61 // ---------------------------------------------------------------------------
64 class DisplayEventConnection;
66 class IGraphicBufferAlloc;
71 class EventControlThread;
73 // ---------------------------------------------------------------------------
76 eTransactionNeeded = 0x01,
77 eTraversalNeeded = 0x02,
78 eDisplayTransactionNeeded = 0x04,
79 eTransactionMask = 0x07
82 class SurfaceFlinger : public BnSurfaceComposer,
83 private IBinder::DeathRecipient,
84 private HWComposer::EventHandler
87 static char const* getServiceName() ANDROID_API {
88 return "SurfaceFlinger";
91 SurfaceFlinger() ANDROID_API;
93 // must be called before clients can connect
94 void init() ANDROID_API;
96 // starts SurfaceFlinger main loop in the current thread
97 void run() ANDROID_API;
100 EVENT_VSYNC = HWC_EVENT_VSYNC
103 // post an asynchronous message to the main thread
104 status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
106 // post a synchronous message to the main thread
107 status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
109 // force full composition on all displays
110 void repaintEverything();
112 // returns the default Display
113 sp<const DisplayDevice> getDefaultDisplayDevice() const {
114 return getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]);
117 // utility function to delete a texture on the main thread
118 void deleteTextureAsync(uint32_t texture);
120 // enable/disable h/w composer event
121 // TODO: this should be made accessible only to EventThread
122 void eventControl(int disp, int event, int enabled);
124 // called on the main thread by MessageQueue when an internal message
126 // TODO: this should be made accessible only to MessageQueue
127 void onMessageReceived(int32_t what);
129 // for debugging only
130 // TODO: this should be made accessible only to HWComposer
131 const Vector< sp<Layer> >& getLayerSortedByZForHwcDisplay(int id);
133 RenderEngine& getRenderEngine() const {
134 return *mRenderEngine;
139 friend class DisplayEventConnection;
141 friend class MonitoredProducer;
143 // This value is specified in number of frames. Log frame stats at most
145 enum { LOG_FRAME_STATS_PERIOD = 30*60*60 };
147 static const size_t MAX_LAYERS = 4096;
149 // We're reference counted, never destroy SurfaceFlinger directly
150 virtual ~SurfaceFlinger();
152 /* ------------------------------------------------------------------------
153 * Internal data structures
156 class LayerVector : public SortedVector< sp<Layer> > {
159 LayerVector(const LayerVector& rhs);
160 virtual int do_compare(const void* lhs, const void* rhs) const;
163 struct DisplayDeviceState {
164 DisplayDeviceState();
165 DisplayDeviceState(DisplayDevice::DisplayType type);
166 bool isValid() const { return type >= 0; }
167 bool isMainDisplay() const { return type == DisplayDevice::DISPLAY_PRIMARY; }
168 bool isVirtualDisplay() const { return type >= DisplayDevice::DISPLAY_VIRTUAL; }
169 DisplayDevice::DisplayType type;
170 sp<IGraphicBufferProducer> surface;
175 uint32_t width, height;
181 LayerVector layersSortedByZ;
182 DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
185 /* ------------------------------------------------------------------------
188 virtual status_t onTransact(uint32_t code, const Parcel& data,
189 Parcel* reply, uint32_t flags);
190 virtual status_t dump(int fd, const Vector<String16>& args);
192 /* ------------------------------------------------------------------------
193 * ISurfaceComposer interface
195 virtual sp<ISurfaceComposerClient> createConnection();
196 virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc();
197 virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
198 virtual void destroyDisplay(const sp<IBinder>& display);
199 virtual sp<IBinder> getBuiltInDisplay(int32_t id);
200 virtual void setTransactionState(const Vector<ComposerState>& state,
201 const Vector<DisplayState>& displays, uint32_t flags);
202 virtual void bootFinished();
203 virtual bool authenticateSurfaceTexture(
204 const sp<IGraphicBufferProducer>& bufferProducer) const;
205 virtual sp<IDisplayEventConnection> createDisplayEventConnection();
206 virtual status_t captureScreen(const sp<IBinder>& display,
207 const sp<IGraphicBufferProducer>& producer,
208 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
209 uint32_t minLayerZ, uint32_t maxLayerZ,
210 bool useIdentityTransform, ISurfaceComposer::Rotation rotation);
211 virtual status_t getDisplayStats(const sp<IBinder>& display,
212 DisplayStatInfo* stats);
213 virtual status_t getDisplayConfigs(const sp<IBinder>& display,
214 Vector<DisplayInfo>* configs);
215 virtual int getActiveConfig(const sp<IBinder>& display);
216 virtual void setPowerMode(const sp<IBinder>& display, int mode);
217 virtual status_t setActiveConfig(const sp<IBinder>& display, int id);
218 virtual status_t clearAnimationFrameStats();
219 virtual status_t getAnimationFrameStats(FrameStats* outStats) const;
221 /* ------------------------------------------------------------------------
222 * DeathRecipient interface
224 virtual void binderDied(const wp<IBinder>& who);
226 /* ------------------------------------------------------------------------
229 virtual void onFirstRef();
231 /* ------------------------------------------------------------------------
232 * HWComposer::EventHandler interface
234 virtual void onVSyncReceived(int type, nsecs_t timestamp);
235 virtual void onHotplugReceived(int disp, bool connected);
237 /* ------------------------------------------------------------------------
241 void signalTransaction();
242 void signalLayerUpdate();
243 void signalRefresh();
245 // called on the main thread in response to initializeDisplays()
246 void onInitializeDisplays();
247 // called on the main thread in response to setActiveConfig()
248 void setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode);
249 // called on the main thread in response to setPowerMode()
250 void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode);
252 // Returns whether the transaction actually modified any state
253 bool handleMessageTransaction();
255 // Returns whether a new buffer has been latched (see handlePageFlip())
256 bool handleMessageInvalidate();
258 void handleMessageRefresh();
260 void handleTransaction(uint32_t transactionFlags);
261 void handleTransactionLocked(uint32_t transactionFlags);
263 void updateCursorAsync();
265 /* handlePageFlip - latch a new buffer if available and compute the dirty
266 * region. Returns whether a new buffer has been latched, i.e., whether it
267 * is necessary to perform a refresh during this vsync.
269 bool handlePageFlip();
271 /* ------------------------------------------------------------------------
274 uint32_t getTransactionFlags(uint32_t flags);
275 uint32_t peekTransactionFlags(uint32_t flags);
276 uint32_t setTransactionFlags(uint32_t flags);
277 void commitTransaction();
278 uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s);
279 uint32_t setDisplayStateLocked(const DisplayState& s);
281 /* ------------------------------------------------------------------------
284 status_t createLayer(const String8& name, const sp<Client>& client,
285 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
286 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp);
288 status_t createNormalLayer(const sp<Client>& client, const String8& name,
289 uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
290 sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp,
291 sp<Layer>* outLayer);
293 status_t createDimLayer(const sp<Client>& client, const String8& name,
294 uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
295 sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
297 // called in response to the window-manager calling
298 // ISurfaceComposerClient::destroySurface()
299 status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
301 // called when all clients have released all their references to
302 // this layer meaning it is entirely safe to destroy all
303 // resources associated to this layer.
304 status_t onLayerDestroyed(const wp<Layer>& layer);
306 // remove a layer from SurfaceFlinger immediately
307 status_t removeLayer(const sp<Layer>& layer);
309 // add a layer to SurfaceFlinger
310 status_t addClientLayer(const sp<Client>& client,
311 const sp<IBinder>& handle,
312 const sp<IGraphicBufferProducer>& gbc,
313 const sp<Layer>& lbc);
315 /* ------------------------------------------------------------------------
316 * Boot animation, on/off animations and screen capture
319 void startBootAnim();
321 void renderScreenImplLocked(
322 const sp<const DisplayDevice>& hw,
323 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
324 uint32_t minLayerZ, uint32_t maxLayerZ,
325 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation);
327 status_t captureScreenImplLocked(
328 const sp<const DisplayDevice>& hw,
329 const sp<IGraphicBufferProducer>& producer,
330 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
331 uint32_t minLayerZ, uint32_t maxLayerZ,
332 bool useIdentityTransform, Transform::orientation_flags rotation);
334 /* ------------------------------------------------------------------------
337 size_t getMaxTextureSize() const;
338 size_t getMaxViewportDims() const;
340 /* ------------------------------------------------------------------------
341 * Display and layer stack management
343 // called when starting, or restarting after system_server death
344 void initializeDisplays();
346 // Create an IBinder for a builtin display and add it to current state
347 void createBuiltinDisplayLocked(DisplayDevice::DisplayType type);
349 // NOTE: can only be called from the main thread or with mStateLock held
350 sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
351 return mDisplays.valueFor(dpy);
354 // NOTE: can only be called from the main thread or with mStateLock held
355 sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
356 return mDisplays.valueFor(dpy);
359 // mark a region of a layer stack dirty. this updates the dirty
360 // region of all screens presenting this layer stack.
361 void invalidateLayerStack(uint32_t layerStack, const Region& dirty);
363 // allocate a h/w composer display id
364 int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type);
366 /* ------------------------------------------------------------------------
370 HWComposer& getHwComposer() const { return *mHwc; }
372 /* ------------------------------------------------------------------------
375 void invalidateHwcGeometry();
376 static void computeVisibleRegions(
377 const LayerVector& currentLayers, uint32_t layerStack,
378 Region& dirtyRegion, Region& opaqueRegion);
380 void preComposition();
381 void postComposition();
382 void rebuildLayerStacks();
383 void setUpHWComposer();
384 void doComposition();
385 void doDebugFlashRegions();
386 void doDisplayComposition(const sp<const DisplayDevice>& hw, const Region& dirtyRegion);
388 // compose surfaces for display hw. this fails if using GL and the surface
389 // has been destroyed and is no longer valid.
390 bool doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty);
392 void postFramebuffer();
393 void drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const;
395 /* ------------------------------------------------------------------------
399 /* ------------------------------------------------------------------------
402 void enableHardwareVsync();
403 void disableHardwareVsync(bool makeUnavailable);
404 void resyncToHardwareVsync(bool makeAvailable);
406 /* ------------------------------------------------------------------------
407 * Debugging & dumpsys
409 void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
410 void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
411 void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
412 void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
413 bool startDdmConnection();
414 static void appendSfConfigString(String8& result);
415 void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
416 const sp<const DisplayDevice>& hw,
417 uint32_t minLayerZ, uint32_t maxLayerZ);
419 void logFrameStats();
421 void dumpStaticScreenStats(String8& result) const;
423 /* ------------------------------------------------------------------------
427 // access must be protected by mStateLock
428 mutable Mutex mStateLock;
430 volatile int32_t mTransactionFlags;
431 Condition mTransactionCV;
432 bool mTransactionPending;
433 bool mAnimTransactionPending;
434 Vector< sp<Layer> > mLayersPendingRemoval;
435 SortedVector< wp<IBinder> > mGraphicBufferProducerList;
437 // protected by mStateLock (but we could use another lock)
440 // access must be protected by mInvalidateLock
441 volatile int32_t mRepaintEverything;
443 // constant members (no synchronization needed for access)
445 RenderEngine* mRenderEngine;
447 bool mGpuToCpuSupported;
448 sp<EventThread> mEventThread;
449 sp<EventThread> mSFEventThread;
450 sp<EventControlThread> mEventControlThread;
451 EGLContext mEGLContext;
452 EGLDisplay mEGLDisplay;
453 sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES];
455 // Can only accessed from the main thread, these members
456 // don't need synchronization
458 bool mVisibleRegionsDirty;
459 bool mHwWorkListDirty;
460 bool mAnimCompositionPending;
462 // this may only be written from the main thread with mStateLock held
463 // it may be read from other threads with mStateLock held
464 DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
466 // don't use a lock for these, we don't care
469 int mDebugDisableHWC;
470 int mDebugDisableTransformHint;
471 volatile nsecs_t mDebugInSwapBuffers;
472 nsecs_t mLastSwapBufferTime;
473 volatile nsecs_t mDebugInTransaction;
474 nsecs_t mLastTransactionTime;
476 bool mForceFullDamage;
478 // these are thread safe
479 mutable MessageQueue mEventQueue;
480 FrameTracker mAnimFrameTracker;
481 DispSync mPrimaryDispSync;
483 // protected by mDestroyedLayerLock;
484 mutable Mutex mDestroyedLayerLock;
485 Vector<Layer const *> mDestroyedLayers;
487 // protected by mHWVsyncLock
489 bool mPrimaryHWVsyncEnabled;
490 bool mHWVsyncAvailable;
492 /* ------------------------------------------------------------------------
493 * Feature prototyping
496 Daltonizer mDaltonizer;
500 bool mHasColorMatrix;
502 // Static screen stats
504 static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
505 nsecs_t mFrameBuckets[NUM_BUCKETS];
507 nsecs_t mLastSwapTime;
510 }; // namespace android
512 #endif // ANDROID_SURFACE_FLINGER_H