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 "FenceTracker.h"
54 #include "FrameTracker.h"
55 #include "MessageQueue.h"
57 #include "DisplayHardware/HWComposer.h"
58 #include "Effects/Daltonizer.h"
62 // ---------------------------------------------------------------------------
65 class DisplayEventConnection;
67 class IGraphicBufferAlloc;
72 class EventControlThread;
74 // ---------------------------------------------------------------------------
77 eTransactionNeeded = 0x01,
78 eTraversalNeeded = 0x02,
79 eDisplayTransactionNeeded = 0x04,
80 eTransactionMask = 0x07
83 class SurfaceFlinger : public BnSurfaceComposer,
84 private IBinder::DeathRecipient,
85 private HWComposer::EventHandler
88 static char const* getServiceName() ANDROID_API {
89 return "SurfaceFlinger";
92 SurfaceFlinger() ANDROID_API;
94 // must be called before clients can connect
95 void init() ANDROID_API;
97 // starts SurfaceFlinger main loop in the current thread
98 void run() ANDROID_API;
101 EVENT_VSYNC = HWC_EVENT_VSYNC
104 // post an asynchronous message to the main thread
105 status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
107 // post a synchronous message to the main thread
108 status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
110 // force full composition on all displays
111 void repaintEverything();
113 // returns the default Display
114 sp<const DisplayDevice> getDefaultDisplayDevice() const {
115 return getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]);
118 // utility function to delete a texture on the main thread
119 void deleteTextureAsync(uint32_t texture);
121 // enable/disable h/w composer event
122 // TODO: this should be made accessible only to EventThread
124 void setVsyncEnabled(int disp, int enabled);
126 void eventControl(int disp, int event, int enabled);
129 // called on the main thread by MessageQueue when an internal message
131 // TODO: this should be made accessible only to MessageQueue
132 void onMessageReceived(int32_t what);
134 // for debugging only
135 // TODO: this should be made accessible only to HWComposer
136 const Vector< sp<Layer> >& getLayerSortedByZForHwcDisplay(int id);
138 RenderEngine& getRenderEngine() const {
139 return *mRenderEngine;
144 friend class DisplayEventConnection;
146 friend class MonitoredProducer;
148 // This value is specified in number of frames. Log frame stats at most
150 enum { LOG_FRAME_STATS_PERIOD = 30*60*60 };
152 static const size_t MAX_LAYERS = 4096;
154 // We're reference counted, never destroy SurfaceFlinger directly
155 virtual ~SurfaceFlinger();
157 /* ------------------------------------------------------------------------
158 * Internal data structures
161 class LayerVector : public SortedVector< sp<Layer> > {
164 LayerVector(const LayerVector& rhs);
165 virtual int do_compare(const void* lhs, const void* rhs) const;
168 struct DisplayDeviceState {
169 DisplayDeviceState();
170 DisplayDeviceState(DisplayDevice::DisplayType type, bool isSecure);
171 bool isValid() const { return type >= 0; }
172 bool isMainDisplay() const { return type == DisplayDevice::DISPLAY_PRIMARY; }
173 bool isVirtualDisplay() const { return type >= DisplayDevice::DISPLAY_VIRTUAL; }
174 DisplayDevice::DisplayType type;
175 sp<IGraphicBufferProducer> surface;
180 uint32_t width, height;
186 LayerVector layersSortedByZ;
187 DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
190 /* ------------------------------------------------------------------------
193 virtual status_t onTransact(uint32_t code, const Parcel& data,
194 Parcel* reply, uint32_t flags);
195 virtual status_t dump(int fd, const Vector<String16>& args);
197 /* ------------------------------------------------------------------------
198 * ISurfaceComposer interface
200 virtual sp<ISurfaceComposerClient> createConnection();
201 virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc();
202 virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
203 virtual void destroyDisplay(const sp<IBinder>& display);
204 virtual sp<IBinder> getBuiltInDisplay(int32_t id);
205 virtual void setTransactionState(const Vector<ComposerState>& state,
206 const Vector<DisplayState>& displays, uint32_t flags);
207 virtual void bootFinished();
208 virtual bool authenticateSurfaceTexture(
209 const sp<IGraphicBufferProducer>& bufferProducer) const;
210 virtual sp<IDisplayEventConnection> createDisplayEventConnection();
211 virtual status_t captureScreen(const sp<IBinder>& display,
212 const sp<IGraphicBufferProducer>& producer,
213 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
214 uint32_t minLayerZ, uint32_t maxLayerZ,
215 bool useIdentityTransform, ISurfaceComposer::Rotation rotation);
216 virtual status_t getDisplayStats(const sp<IBinder>& display,
217 DisplayStatInfo* stats);
218 virtual status_t getDisplayConfigs(const sp<IBinder>& display,
219 Vector<DisplayInfo>* configs);
220 virtual int getActiveConfig(const sp<IBinder>& display);
221 virtual void setPowerMode(const sp<IBinder>& display, int mode);
222 virtual status_t setActiveConfig(const sp<IBinder>& display, int id);
223 virtual status_t clearAnimationFrameStats();
224 virtual status_t getAnimationFrameStats(FrameStats* outStats) const;
225 virtual status_t getHdrCapabilities(const sp<IBinder>& display,
226 HdrCapabilities* outCapabilities) const;
228 /* ------------------------------------------------------------------------
229 * DeathRecipient interface
231 virtual void binderDied(const wp<IBinder>& who);
233 /* ------------------------------------------------------------------------
236 virtual void onFirstRef();
238 /* ------------------------------------------------------------------------
239 * HWComposer::EventHandler interface
241 virtual void onVSyncReceived(int type, nsecs_t timestamp);
242 virtual void onHotplugReceived(int disp, bool connected);
244 /* ------------------------------------------------------------------------
248 void signalTransaction();
249 void signalLayerUpdate();
250 void signalRefresh();
252 // called on the main thread in response to initializeDisplays()
253 void onInitializeDisplays();
254 // called on the main thread in response to setActiveConfig()
255 void setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode);
256 // called on the main thread in response to setPowerMode()
257 void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode);
259 // Returns whether the transaction actually modified any state
260 bool handleMessageTransaction();
262 // Returns whether a new buffer has been latched (see handlePageFlip())
263 bool handleMessageInvalidate();
265 void handleMessageRefresh();
267 void handleTransaction(uint32_t transactionFlags);
268 void handleTransactionLocked(uint32_t transactionFlags);
270 void updateCursorAsync();
272 /* handlePageFlip - latch a new buffer if available and compute the dirty
273 * region. Returns whether a new buffer has been latched, i.e., whether it
274 * is necessary to perform a refresh during this vsync.
276 bool handlePageFlip();
278 /* ------------------------------------------------------------------------
281 uint32_t getTransactionFlags(uint32_t flags);
282 uint32_t peekTransactionFlags(uint32_t flags);
283 uint32_t setTransactionFlags(uint32_t flags);
284 void commitTransaction();
285 uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s);
286 uint32_t setDisplayStateLocked(const DisplayState& s);
288 /* ------------------------------------------------------------------------
291 status_t createLayer(const String8& name, const sp<Client>& client,
292 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
293 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp);
295 status_t createNormalLayer(const sp<Client>& client, const String8& name,
296 uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
297 sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp,
298 sp<Layer>* outLayer);
300 status_t createDimLayer(const sp<Client>& client, const String8& name,
301 uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
302 sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
304 // called in response to the window-manager calling
305 // ISurfaceComposerClient::destroySurface()
306 status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
308 // called when all clients have released all their references to
309 // this layer meaning it is entirely safe to destroy all
310 // resources associated to this layer.
311 status_t onLayerDestroyed(const wp<Layer>& layer);
313 // remove a layer from SurfaceFlinger immediately
314 status_t removeLayer(const sp<Layer>& layer);
316 // add a layer to SurfaceFlinger
317 status_t addClientLayer(const sp<Client>& client,
318 const sp<IBinder>& handle,
319 const sp<IGraphicBufferProducer>& gbc,
320 const sp<Layer>& lbc);
322 /* ------------------------------------------------------------------------
323 * Boot animation, on/off animations and screen capture
326 void startBootAnim();
328 void renderScreenImplLocked(
329 const sp<const DisplayDevice>& hw,
330 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
331 uint32_t minLayerZ, uint32_t maxLayerZ,
332 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation);
334 status_t captureScreenImplLocked(
335 const sp<const DisplayDevice>& hw,
336 const sp<IGraphicBufferProducer>& producer,
337 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
338 uint32_t minLayerZ, uint32_t maxLayerZ,
339 bool useIdentityTransform, Transform::orientation_flags rotation,
340 bool isLocalScreenshot);
342 /* ------------------------------------------------------------------------
345 size_t getMaxTextureSize() const;
346 size_t getMaxViewportDims() const;
348 /* ------------------------------------------------------------------------
349 * Display and layer stack management
351 // called when starting, or restarting after system_server death
352 void initializeDisplays();
354 // Create an IBinder for a builtin display and add it to current state
355 void createBuiltinDisplayLocked(DisplayDevice::DisplayType type);
357 // NOTE: can only be called from the main thread or with mStateLock held
358 sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
359 return mDisplays.valueFor(dpy);
362 // NOTE: can only be called from the main thread or with mStateLock held
363 sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
364 return mDisplays.valueFor(dpy);
367 // mark a region of a layer stack dirty. this updates the dirty
368 // region of all screens presenting this layer stack.
369 void invalidateLayerStack(uint32_t layerStack, const Region& dirty);
372 int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type);
375 /* ------------------------------------------------------------------------
379 HWComposer& getHwComposer() const { return *mHwc; }
381 /* ------------------------------------------------------------------------
384 void invalidateHwcGeometry();
385 static void computeVisibleRegions(
386 const LayerVector& currentLayers, uint32_t layerStack,
387 Region& dirtyRegion, Region& opaqueRegion);
389 void preComposition();
390 void postComposition(nsecs_t refreshStartTime);
391 void rebuildLayerStacks();
392 void setUpHWComposer();
393 void doComposition();
394 void doDebugFlashRegions();
395 void doDisplayComposition(const sp<const DisplayDevice>& hw, const Region& dirtyRegion);
397 // compose surfaces for display hw. this fails if using GL and the surface
398 // has been destroyed and is no longer valid.
399 bool doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty);
401 void postFramebuffer();
402 void drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const;
404 /* ------------------------------------------------------------------------
408 /* ------------------------------------------------------------------------
411 void enableHardwareVsync();
412 void disableHardwareVsync(bool makeUnavailable);
413 void resyncToHardwareVsync(bool makeAvailable);
415 /* ------------------------------------------------------------------------
416 * Debugging & dumpsys
418 void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
419 void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
420 void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
421 void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
422 bool startDdmConnection();
423 static void appendSfConfigString(String8& result);
424 void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
425 const sp<const DisplayDevice>& hw,
426 uint32_t minLayerZ, uint32_t maxLayerZ);
428 void logFrameStats();
430 void dumpStaticScreenStats(String8& result) const;
432 /* ------------------------------------------------------------------------
436 // access must be protected by mStateLock
437 mutable Mutex mStateLock;
439 volatile int32_t mTransactionFlags;
440 Condition mTransactionCV;
441 bool mTransactionPending;
442 bool mAnimTransactionPending;
443 Vector< sp<Layer> > mLayersPendingRemoval;
444 SortedVector< wp<IBinder> > mGraphicBufferProducerList;
446 // protected by mStateLock (but we could use another lock)
449 // access must be protected by mInvalidateLock
450 volatile int32_t mRepaintEverything;
452 // constant members (no synchronization needed for access)
454 RenderEngine* mRenderEngine;
456 bool mGpuToCpuSupported;
457 bool mDropMissedFrames;
458 sp<EventThread> mEventThread;
459 sp<EventThread> mSFEventThread;
460 sp<EventControlThread> mEventControlThread;
461 EGLContext mEGLContext;
462 EGLDisplay mEGLDisplay;
463 sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES];
465 // Can only accessed from the main thread, these members
466 // don't need synchronization
468 bool mVisibleRegionsDirty;
470 bool mHwWorkListDirty;
472 bool mGeometryInvalid;
474 bool mAnimCompositionPending;
476 std::vector<sp<Layer>> mLayersWithQueuedFrames;
479 // this may only be written from the main thread with mStateLock held
480 // it may be read from other threads with mStateLock held
481 DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
483 // don't use a lock for these, we don't care
486 int mDebugDisableHWC;
487 int mDebugDisableTransformHint;
488 volatile nsecs_t mDebugInSwapBuffers;
489 nsecs_t mLastSwapBufferTime;
490 volatile nsecs_t mDebugInTransaction;
491 nsecs_t mLastTransactionTime;
493 bool mForceFullDamage;
494 FenceTracker mFenceTracker;
496 // these are thread safe
497 mutable MessageQueue mEventQueue;
498 FrameTracker mAnimFrameTracker;
499 DispSync mPrimaryDispSync;
501 // protected by mDestroyedLayerLock;
502 mutable Mutex mDestroyedLayerLock;
503 Vector<Layer const *> mDestroyedLayers;
505 // protected by mHWVsyncLock
507 bool mPrimaryHWVsyncEnabled;
508 bool mHWVsyncAvailable;
510 /* ------------------------------------------------------------------------
511 * Feature prototyping
514 Daltonizer mDaltonizer;
518 bool mHasColorMatrix;
520 // Static screen stats
522 static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
523 nsecs_t mFrameBuckets[NUM_BUCKETS];
525 nsecs_t mLastSwapTime;
528 }; // namespace android
530 #endif // ANDROID_SURFACE_FLINGER_H