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
123 void setVsyncEnabled(int disp, int enabled);
125 void eventControl(int disp, int event, int enabled);
128 // called on the main thread by MessageQueue when an internal message
130 // TODO: this should be made accessible only to MessageQueue
131 void onMessageReceived(int32_t what);
133 // for debugging only
134 // TODO: this should be made accessible only to HWComposer
135 const Vector< sp<Layer> >& getLayerSortedByZForHwcDisplay(int id);
137 RenderEngine& getRenderEngine() const {
138 return *mRenderEngine;
143 friend class DisplayEventConnection;
145 friend class MonitoredProducer;
147 // This value is specified in number of frames. Log frame stats at most
149 enum { LOG_FRAME_STATS_PERIOD = 30*60*60 };
151 static const size_t MAX_LAYERS = 4096;
153 // We're reference counted, never destroy SurfaceFlinger directly
154 virtual ~SurfaceFlinger();
156 /* ------------------------------------------------------------------------
157 * Internal data structures
160 class LayerVector : public SortedVector< sp<Layer> > {
163 LayerVector(const LayerVector& rhs);
164 virtual int do_compare(const void* lhs, const void* rhs) const;
167 struct DisplayDeviceState {
168 DisplayDeviceState();
169 DisplayDeviceState(DisplayDevice::DisplayType type, bool isSecure);
170 bool isValid() const { return type >= 0; }
171 bool isMainDisplay() const { return type == DisplayDevice::DISPLAY_PRIMARY; }
172 bool isVirtualDisplay() const { return type >= DisplayDevice::DISPLAY_VIRTUAL; }
173 DisplayDevice::DisplayType type;
174 sp<IGraphicBufferProducer> surface;
179 uint32_t width, height;
185 LayerVector layersSortedByZ;
186 DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
189 /* ------------------------------------------------------------------------
192 virtual status_t onTransact(uint32_t code, const Parcel& data,
193 Parcel* reply, uint32_t flags);
194 virtual status_t dump(int fd, const Vector<String16>& args);
196 /* ------------------------------------------------------------------------
197 * ISurfaceComposer interface
199 virtual sp<ISurfaceComposerClient> createConnection();
200 virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc();
201 virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
202 virtual void destroyDisplay(const sp<IBinder>& display);
203 virtual sp<IBinder> getBuiltInDisplay(int32_t id);
204 virtual void setTransactionState(const Vector<ComposerState>& state,
205 const Vector<DisplayState>& displays, uint32_t flags);
206 virtual void bootFinished();
207 virtual bool authenticateSurfaceTexture(
208 const sp<IGraphicBufferProducer>& bufferProducer) const;
209 virtual sp<IDisplayEventConnection> createDisplayEventConnection();
210 virtual status_t captureScreen(const sp<IBinder>& display,
211 const sp<IGraphicBufferProducer>& producer,
212 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
213 uint32_t minLayerZ, uint32_t maxLayerZ,
214 bool useIdentityTransform, ISurfaceComposer::Rotation rotation);
215 virtual status_t getDisplayStats(const sp<IBinder>& display,
216 DisplayStatInfo* stats);
217 virtual status_t getDisplayConfigs(const sp<IBinder>& display,
218 Vector<DisplayInfo>* configs);
219 virtual int getActiveConfig(const sp<IBinder>& display);
220 virtual void setPowerMode(const sp<IBinder>& display, int mode);
221 virtual status_t setActiveConfig(const sp<IBinder>& display, int id);
222 virtual status_t clearAnimationFrameStats();
223 virtual status_t getAnimationFrameStats(FrameStats* outStats) const;
225 /* ------------------------------------------------------------------------
226 * DeathRecipient interface
228 virtual void binderDied(const wp<IBinder>& who);
230 /* ------------------------------------------------------------------------
233 virtual void onFirstRef();
235 /* ------------------------------------------------------------------------
236 * HWComposer::EventHandler interface
238 virtual void onVSyncReceived(int type, nsecs_t timestamp);
239 virtual void onHotplugReceived(int disp, bool connected);
241 /* ------------------------------------------------------------------------
245 void signalTransaction();
246 void signalLayerUpdate();
247 void signalRefresh();
249 // called on the main thread in response to initializeDisplays()
250 void onInitializeDisplays();
251 // called on the main thread in response to setActiveConfig()
252 void setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode);
253 // called on the main thread in response to setPowerMode()
254 void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode);
256 // Returns whether the transaction actually modified any state
257 bool handleMessageTransaction();
259 // Returns whether a new buffer has been latched (see handlePageFlip())
260 bool handleMessageInvalidate();
262 void handleMessageRefresh();
264 void handleTransaction(uint32_t transactionFlags);
265 void handleTransactionLocked(uint32_t transactionFlags);
267 void updateCursorAsync();
269 /* handlePageFlip - latch a new buffer if available and compute the dirty
270 * region. Returns whether a new buffer has been latched, i.e., whether it
271 * is necessary to perform a refresh during this vsync.
273 bool handlePageFlip();
275 /* ------------------------------------------------------------------------
278 uint32_t getTransactionFlags(uint32_t flags);
279 uint32_t peekTransactionFlags(uint32_t flags);
280 uint32_t setTransactionFlags(uint32_t flags);
281 void commitTransaction();
282 uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s);
283 uint32_t setDisplayStateLocked(const DisplayState& s);
285 /* ------------------------------------------------------------------------
288 status_t createLayer(const String8& name, const sp<Client>& client,
289 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
290 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp);
292 status_t createNormalLayer(const sp<Client>& client, const String8& name,
293 uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
294 sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp,
295 sp<Layer>* outLayer);
297 status_t createDimLayer(const sp<Client>& client, const String8& name,
298 uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
299 sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
301 // called in response to the window-manager calling
302 // ISurfaceComposerClient::destroySurface()
303 status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
305 // called when all clients have released all their references to
306 // this layer meaning it is entirely safe to destroy all
307 // resources associated to this layer.
308 status_t onLayerDestroyed(const wp<Layer>& layer);
310 // remove a layer from SurfaceFlinger immediately
311 status_t removeLayer(const sp<Layer>& layer);
313 // add a layer to SurfaceFlinger
314 status_t addClientLayer(const sp<Client>& client,
315 const sp<IBinder>& handle,
316 const sp<IGraphicBufferProducer>& gbc,
317 const sp<Layer>& lbc);
319 /* ------------------------------------------------------------------------
320 * Boot animation, on/off animations and screen capture
323 void startBootAnim();
325 void renderScreenImplLocked(
326 const sp<const DisplayDevice>& hw,
327 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
328 uint32_t minLayerZ, uint32_t maxLayerZ,
329 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation);
331 status_t captureScreenImplLocked(
332 const sp<const DisplayDevice>& hw,
333 const sp<IGraphicBufferProducer>& producer,
334 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
335 uint32_t minLayerZ, uint32_t maxLayerZ,
336 bool useIdentityTransform, Transform::orientation_flags rotation,
337 bool isLocalScreenshot);
339 /* ------------------------------------------------------------------------
342 size_t getMaxTextureSize() const;
343 size_t getMaxViewportDims() const;
345 /* ------------------------------------------------------------------------
346 * Display and layer stack management
348 // called when starting, or restarting after system_server death
349 void initializeDisplays();
351 // Create an IBinder for a builtin display and add it to current state
352 void createBuiltinDisplayLocked(DisplayDevice::DisplayType type);
354 // NOTE: can only be called from the main thread or with mStateLock held
355 sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
356 return mDisplays.valueFor(dpy);
359 // NOTE: can only be called from the main thread or with mStateLock held
360 sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
361 return mDisplays.valueFor(dpy);
364 // mark a region of a layer stack dirty. this updates the dirty
365 // region of all screens presenting this layer stack.
366 void invalidateLayerStack(uint32_t layerStack, const Region& dirty);
369 int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type);
372 /* ------------------------------------------------------------------------
376 HWComposer& getHwComposer() const { return *mHwc; }
378 /* ------------------------------------------------------------------------
381 void invalidateHwcGeometry();
382 static void computeVisibleRegions(
383 const LayerVector& currentLayers, uint32_t layerStack,
384 Region& dirtyRegion, Region& opaqueRegion);
386 void preComposition();
387 void postComposition();
388 void rebuildLayerStacks();
389 void setUpHWComposer();
390 void doComposition();
391 void doDebugFlashRegions();
392 void doDisplayComposition(const sp<const DisplayDevice>& hw, const Region& dirtyRegion);
394 // compose surfaces for display hw. this fails if using GL and the surface
395 // has been destroyed and is no longer valid.
396 bool doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty);
398 void postFramebuffer();
399 void drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const;
401 /* ------------------------------------------------------------------------
405 /* ------------------------------------------------------------------------
408 void enableHardwareVsync();
409 void disableHardwareVsync(bool makeUnavailable);
410 void resyncToHardwareVsync(bool makeAvailable);
412 /* ------------------------------------------------------------------------
413 * Debugging & dumpsys
415 void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
416 void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
417 void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
418 void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
419 bool startDdmConnection();
420 static void appendSfConfigString(String8& result);
421 void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
422 const sp<const DisplayDevice>& hw,
423 uint32_t minLayerZ, uint32_t maxLayerZ);
425 void logFrameStats();
427 void dumpStaticScreenStats(String8& result) const;
429 /* ------------------------------------------------------------------------
433 // access must be protected by mStateLock
434 mutable Mutex mStateLock;
436 volatile int32_t mTransactionFlags;
437 Condition mTransactionCV;
438 bool mTransactionPending;
439 bool mAnimTransactionPending;
440 Vector< sp<Layer> > mLayersPendingRemoval;
441 SortedVector< wp<IBinder> > mGraphicBufferProducerList;
443 // protected by mStateLock (but we could use another lock)
446 // access must be protected by mInvalidateLock
447 volatile int32_t mRepaintEverything;
449 // constant members (no synchronization needed for access)
451 RenderEngine* mRenderEngine;
453 bool mGpuToCpuSupported;
454 bool mDropMissedFrames;
455 sp<EventThread> mEventThread;
456 sp<EventThread> mSFEventThread;
457 sp<EventControlThread> mEventControlThread;
458 EGLContext mEGLContext;
459 EGLDisplay mEGLDisplay;
460 sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES];
462 // Can only accessed from the main thread, these members
463 // don't need synchronization
465 bool mVisibleRegionsDirty;
467 bool mHwWorkListDirty;
469 bool mGeometryInvalid;
471 bool mAnimCompositionPending;
473 std::vector<sp<Layer>> mLayersWithQueuedFrames;
476 // this may only be written from the main thread with mStateLock held
477 // it may be read from other threads with mStateLock held
478 DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
480 // don't use a lock for these, we don't care
483 int mDebugDisableHWC;
484 int mDebugDisableTransformHint;
485 volatile nsecs_t mDebugInSwapBuffers;
486 nsecs_t mLastSwapBufferTime;
487 volatile nsecs_t mDebugInTransaction;
488 nsecs_t mLastTransactionTime;
490 bool mForceFullDamage;
492 // these are thread safe
493 mutable MessageQueue mEventQueue;
494 FrameTracker mAnimFrameTracker;
495 DispSync mPrimaryDispSync;
497 // protected by mDestroyedLayerLock;
498 mutable Mutex mDestroyedLayerLock;
499 Vector<Layer const *> mDestroyedLayers;
501 // protected by mHWVsyncLock
503 bool mPrimaryHWVsyncEnabled;
504 bool mHWVsyncAvailable;
506 /* ------------------------------------------------------------------------
507 * Feature prototyping
510 Daltonizer mDaltonizer;
514 bool mHasColorMatrix;
516 // Static screen stats
518 static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
519 nsecs_t mFrameBuckets[NUM_BUCKETS];
521 nsecs_t mLastSwapTime;
524 }; // namespace android
526 #endif // ANDROID_SURFACE_FLINGER_H