OSDN Git Service

29e999eea490de4ca51a2ebc8a21c076937f6227
[android-x86/frameworks-native.git] / services / surfaceflinger / SurfaceFlinger.h
1 /*
2  * Copyright (C) 2007 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #ifndef ANDROID_SURFACE_FLINGER_H
18 #define ANDROID_SURFACE_FLINGER_H
19
20 #include <stdint.h>
21 #include <sys/types.h>
22
23 #include <EGL/egl.h>
24
25 /*
26  * NOTE: Make sure this file doesn't include  anything from <gl/ > or <gl2/ >
27  */
28
29 #include <cutils/compiler.h>
30
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>
37
38 #include <binder/IMemory.h>
39
40 #include <ui/PixelFormat.h>
41 #include <ui/mat4.h>
42
43 #include <gui/ISurfaceComposer.h>
44 #include <gui/ISurfaceComposerClient.h>
45
46 #include <hardware/hwcomposer_defs.h>
47
48 #include <private/gui/LayerState.h>
49
50 #include "Barrier.h"
51 #include "DisplayDevice.h"
52 #include "DispSync.h"
53 #include "FenceTracker.h"
54 #include "FrameTracker.h"
55 #include "MessageQueue.h"
56
57 #include "DisplayHardware/HWComposer.h"
58 #include "Effects/Daltonizer.h"
59
60 #include "FrameRateHelper.h"
61
62 namespace android {
63
64 // ---------------------------------------------------------------------------
65
66 class Client;
67 class DisplayEventConnection;
68 class EventThread;
69 class IGraphicBufferAlloc;
70 class Layer;
71 class LayerDim;
72 class LayerBlur;
73 class Surface;
74 class RenderEngine;
75 class EventControlThread;
76
77 // ---------------------------------------------------------------------------
78
79 enum {
80     eTransactionNeeded        = 0x01,
81     eTraversalNeeded          = 0x02,
82     eDisplayTransactionNeeded = 0x04,
83     eTransactionMask          = 0x07
84 };
85
86 class SurfaceFlinger : public BnSurfaceComposer,
87                        private IBinder::DeathRecipient,
88                        private HWComposer::EventHandler
89 {
90 public:
91     friend class ExSurfaceFlinger;
92
93     static char const* getServiceName() ANDROID_API {
94         return "SurfaceFlinger";
95     }
96
97     SurfaceFlinger() ANDROID_API;
98
99     // must be called before clients can connect
100     void init() ANDROID_API;
101
102     // starts SurfaceFlinger main loop in the current thread
103     void run() ANDROID_API;
104
105     enum {
106         EVENT_VSYNC = HWC_EVENT_VSYNC
107     };
108
109     // post an asynchronous message to the main thread
110     status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
111
112     // post a synchronous message to the main thread
113     status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
114
115     // force full composition on all displays
116     void repaintEverything();
117
118     // returns the default Display
119     sp<const DisplayDevice> getDefaultDisplayDevice() const {
120         return getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]);
121     }
122
123     // utility function to delete a texture on the main thread
124     void deleteTextureAsync(uint32_t texture);
125
126     // enable/disable h/w composer event
127     // TODO: this should be made accessible only to EventThread
128 #ifdef USE_HWC2
129     void setVsyncEnabled(int disp, int enabled);
130 #else
131     void eventControl(int disp, int event, int enabled);
132 #endif
133
134     // called on the main thread by MessageQueue when an internal message
135     // is received
136     // TODO: this should be made accessible only to MessageQueue
137     void onMessageReceived(int32_t what);
138
139     // for debugging only
140     // TODO: this should be made accessible only to HWComposer
141     const Vector< sp<Layer> >& getLayerSortedByZForHwcDisplay(int id);
142
143     RenderEngine& getRenderEngine() const {
144         return *mRenderEngine;
145     }
146
147 private:
148     friend class Client;
149     friend class DisplayEventConnection;
150     friend class Layer;
151     friend class LayerDim;
152     friend class MonitoredProducer;
153     friend class LayerBlur;
154
155     // This value is specified in number of frames.  Log frame stats at most
156     // every half hour.
157     enum { LOG_FRAME_STATS_PERIOD =  30*60*60 };
158
159     static const size_t MAX_LAYERS = 4096;
160
161     // We're reference counted, never destroy SurfaceFlinger directly
162     virtual ~SurfaceFlinger();
163
164     /* ------------------------------------------------------------------------
165      * Internal data structures
166      */
167
168     class LayerVector : public SortedVector< sp<Layer> > {
169     public:
170         LayerVector();
171         LayerVector(const LayerVector& rhs);
172         virtual int do_compare(const void* lhs, const void* rhs) const;
173     };
174
175     struct DisplayDeviceState {
176         DisplayDeviceState();
177         DisplayDeviceState(DisplayDevice::DisplayType type, bool isSecure);
178         bool isValid() const { return type >= 0; }
179         bool isMainDisplay() const { return type == DisplayDevice::DISPLAY_PRIMARY; }
180         bool isVirtualDisplay() const { return type >= DisplayDevice::DISPLAY_VIRTUAL; }
181         DisplayDevice::DisplayType type;
182         sp<IGraphicBufferProducer> surface;
183         uint32_t layerStack;
184         Rect viewport;
185         Rect frame;
186         uint8_t orientation;
187         uint32_t width, height;
188         String8 displayName;
189         bool isSecure;
190     };
191
192     struct State {
193         LayerVector layersSortedByZ;
194         DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
195     };
196
197     /* ------------------------------------------------------------------------
198      * IBinder interface
199      */
200     virtual status_t onTransact(uint32_t code, const Parcel& data,
201         Parcel* reply, uint32_t flags);
202     virtual status_t dump(int fd, const Vector<String16>& args);
203
204     /* ------------------------------------------------------------------------
205      * ISurfaceComposer interface
206      */
207     virtual sp<ISurfaceComposerClient> createConnection();
208     virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc();
209     virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
210     virtual void destroyDisplay(const sp<IBinder>& display);
211     virtual sp<IBinder> getBuiltInDisplay(int32_t id);
212     virtual void setTransactionState(const Vector<ComposerState>& state,
213             const Vector<DisplayState>& displays, uint32_t flags);
214     virtual void bootFinished();
215     virtual bool authenticateSurfaceTexture(
216         const sp<IGraphicBufferProducer>& bufferProducer) const;
217     virtual sp<IDisplayEventConnection> createDisplayEventConnection();
218     virtual status_t captureScreen(const sp<IBinder>& display,
219             const sp<IGraphicBufferProducer>& producer,
220             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
221             uint32_t minLayerZ, uint32_t maxLayerZ,
222             bool useIdentityTransform, ISurfaceComposer::Rotation rotation);
223     virtual status_t getDisplayStats(const sp<IBinder>& display,
224             DisplayStatInfo* stats);
225     virtual status_t getDisplayConfigs(const sp<IBinder>& display,
226             Vector<DisplayInfo>* configs);
227     virtual int getActiveConfig(const sp<IBinder>& display);
228     virtual void setPowerMode(const sp<IBinder>& display, int mode);
229     virtual status_t setActiveConfig(const sp<IBinder>& display, int id);
230     virtual status_t clearAnimationFrameStats();
231     virtual status_t getAnimationFrameStats(FrameStats* outStats) const;
232     virtual status_t getHdrCapabilities(const sp<IBinder>& display,
233             HdrCapabilities* outCapabilities) const;
234
235     /* ------------------------------------------------------------------------
236      * DeathRecipient interface
237      */
238     virtual void binderDied(const wp<IBinder>& who);
239
240     /* ------------------------------------------------------------------------
241      * RefBase interface
242      */
243     virtual void onFirstRef();
244
245     /* ------------------------------------------------------------------------
246      * HWComposer::EventHandler interface
247      */
248     virtual void onVSyncReceived(int type, nsecs_t timestamp);
249     virtual void onHotplugReceived(int disp, bool connected);
250
251     /* ------------------------------------------------------------------------
252      * Extensions
253      */
254     virtual void updateExtendedMode() { }
255
256     virtual void getIndexLOI(size_t /*dpy*/,
257                      const LayerVector& /*currentLayers*/,
258                      bool& /*bIgnoreLayers*/,
259                      int& /*indexLOI*/) { }
260
261     virtual bool updateLayerVisibleNonTransparentRegion(
262                      const int& dpy, const sp<Layer>& layer,
263                      bool& bIgnoreLayers, int& indexLOI,
264                      uint32_t layerStack, const int& i);
265
266     virtual void delayDPTransactionIfNeeded(
267                      const Vector<DisplayState>& /*displays*/) { }
268
269     virtual bool canDrawLayerinScreenShot(
270                      const sp<const DisplayDevice>& hw,
271                      const sp<Layer>& layer);
272
273     virtual void isfreezeSurfacePresent(
274                      bool& freezeSurfacePresent,
275                      const sp<const DisplayDevice>& /*hw*/,
276                      const int32_t& /*id*/) { freezeSurfacePresent = false; }
277
278     virtual void setOrientationEventControl(
279                      bool& /*freezeSurfacePresent*/,
280                      const int32_t& /*id*/) { }
281
282     virtual void updateVisibleRegionsDirty() { }
283     virtual void  drawWormHoleIfRequired(HWComposer::LayerListIterator &cur,
284         const HWComposer::LayerListIterator &end,
285         const sp<const DisplayDevice>& hw,
286         const Region& region);
287     /* ------------------------------------------------------------------------
288      * Message handling
289      */
290     void waitForEvent();
291     void signalTransaction();
292     void signalLayerUpdate();
293     void signalRefresh();
294
295     // called on the main thread in response to initializeDisplays()
296     void onInitializeDisplays();
297     // called on the main thread in response to setActiveConfig()
298     void setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode);
299     // called on the main thread in response to setPowerMode()
300     void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode);
301
302     // Returns whether the transaction actually modified any state
303     bool handleMessageTransaction();
304
305     // Returns whether a new buffer has been latched (see handlePageFlip())
306     bool handleMessageInvalidate();
307
308     void handleMessageRefresh();
309
310     void handleTransaction(uint32_t transactionFlags);
311     void handleTransactionLocked(uint32_t transactionFlags);
312
313     void updateCursorAsync();
314
315     /* handlePageFlip - latch a new buffer if available and compute the dirty
316      * region. Returns whether a new buffer has been latched, i.e., whether it
317      * is necessary to perform a refresh during this vsync.
318      */
319     bool handlePageFlip();
320
321     /* ------------------------------------------------------------------------
322      * Transactions
323      */
324     uint32_t getTransactionFlags(uint32_t flags);
325     uint32_t peekTransactionFlags(uint32_t flags);
326     uint32_t setTransactionFlags(uint32_t flags);
327     void commitTransaction();
328     uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s);
329     uint32_t setDisplayStateLocked(const DisplayState& s);
330
331     /* ------------------------------------------------------------------------
332      * Layer management
333      */
334     status_t createLayer(const String8& name, const sp<Client>& client,
335             uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
336             sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp);
337
338     status_t createNormalLayer(const sp<Client>& client, const String8& name,
339             uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
340             sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp,
341             sp<Layer>* outLayer);
342
343     status_t createDimLayer(const sp<Client>& client, const String8& name,
344             uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
345             sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
346
347     status_t createBlurLayer(const sp<Client>& client, const String8& name,
348             uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
349             sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
350
351     // called in response to the window-manager calling
352     // ISurfaceComposerClient::destroySurface()
353     status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
354
355     // called when all clients have released all their references to
356     // this layer meaning it is entirely safe to destroy all
357     // resources associated to this layer.
358     status_t onLayerDestroyed(const wp<Layer>& layer);
359
360     // remove a layer from SurfaceFlinger immediately
361     status_t removeLayer(const sp<Layer>& layer);
362
363     // add a layer to SurfaceFlinger
364     status_t addClientLayer(const sp<Client>& client,
365             const sp<IBinder>& handle,
366             const sp<IGraphicBufferProducer>& gbc,
367             const sp<Layer>& lbc);
368
369     /* ------------------------------------------------------------------------
370      * Boot animation, on/off animations and screen capture
371      */
372
373     void startBootAnim();
374
375     void renderScreenImplLocked(
376             const sp<const DisplayDevice>& hw,
377             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
378             uint32_t minLayerZ, uint32_t maxLayerZ,
379             bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation);
380
381     status_t captureScreenImplLocked(
382             const sp<const DisplayDevice>& hw,
383             const sp<IGraphicBufferProducer>& producer,
384             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
385             uint32_t minLayerZ, uint32_t maxLayerZ,
386             bool useIdentityTransform, Transform::orientation_flags rotation,
387             bool isLocalScreenshot);
388
389     /* ------------------------------------------------------------------------
390      * EGL
391      */
392     size_t getMaxTextureSize() const;
393     size_t getMaxViewportDims() const;
394
395     /* ------------------------------------------------------------------------
396      * Display and layer stack management
397      */
398     // called when starting, or restarting after system_server death
399     void initializeDisplays();
400
401     // Create an IBinder for a builtin display and add it to current state
402     void createBuiltinDisplayLocked(DisplayDevice::DisplayType type);
403
404     // NOTE: can only be called from the main thread or with mStateLock held
405     sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
406         return mDisplays.valueFor(dpy);
407     }
408
409     // NOTE: can only be called from the main thread or with mStateLock held
410     sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
411         return mDisplays.valueFor(dpy);
412     }
413
414     // mark a region of a layer stack dirty. this updates the dirty
415     // region of all screens presenting this layer stack.
416     void invalidateLayerStack(uint32_t layerStack, const Region& dirty);
417
418 #ifndef USE_HWC2
419     int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type);
420 #endif
421
422     /* ------------------------------------------------------------------------
423      * H/W composer
424      */
425
426     HWComposer& getHwComposer() const { return *mHwc; }
427
428     /* ------------------------------------------------------------------------
429      * Compositing
430      */
431     void invalidateHwcGeometry();
432     void computeVisibleRegions(size_t dpy,
433             const LayerVector& currentLayers, uint32_t layerStack,
434             Region& dirtyRegion, Region& opaqueRegion);
435
436     void preComposition();
437     void postComposition(nsecs_t refreshStartTime);
438     void rebuildLayerStacks();
439     void setUpHWComposer();
440     void doComposition();
441     void doDebugFlashRegions();
442     void doDisplayComposition(const sp<const DisplayDevice>& hw, const Region& dirtyRegion);
443
444     // compose surfaces for display hw. this fails if using GL and the surface
445     // has been destroyed and is no longer valid.
446     bool doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty);
447
448     void postFramebuffer();
449     void drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const;
450
451     /* ------------------------------------------------------------------------
452      * Display management
453      */
454
455     /* ------------------------------------------------------------------------
456      * VSync
457      */
458      void enableHardwareVsync();
459      void resyncToHardwareVsync(bool makeAvailable);
460      void disableHardwareVsync(bool makeUnavailable);
461 public:
462      void resyncWithRateLimit();
463 private:
464
465     /* ------------------------------------------------------------------------
466      * Debugging & dumpsys
467      */
468     void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
469     void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
470     void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
471     void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
472     bool startDdmConnection();
473     static void appendSfConfigString(String8& result);
474     void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
475             const sp<const DisplayDevice>& hw,
476             uint32_t minLayerZ, uint32_t maxLayerZ);
477
478     void logFrameStats();
479
480     void dumpStaticScreenStats(String8& result) const;
481     virtual void dumpDrawCycle(bool /* prePrepare */ ) { }
482
483     /* ------------------------------------------------------------------------
484      * Attributes
485      */
486
487     // access must be protected by mStateLock
488     mutable Mutex mStateLock;
489     State mCurrentState;
490     volatile int32_t mTransactionFlags;
491     Condition mTransactionCV;
492     bool mTransactionPending;
493     bool mAnimTransactionPending;
494     Vector< sp<Layer> > mLayersPendingRemoval;
495     SortedVector< wp<IBinder> > mGraphicBufferProducerList;
496
497     // protected by mStateLock (but we could use another lock)
498     bool mLayersRemoved;
499
500     // access must be protected by mInvalidateLock
501     volatile int32_t mRepaintEverything;
502
503     // constant members (no synchronization needed for access)
504     HWComposer* mHwc;
505     RenderEngine* mRenderEngine;
506     nsecs_t mBootTime;
507     bool mGpuToCpuSupported;
508     bool mDropMissedFrames;
509     sp<EventThread> mEventThread;
510     sp<EventThread> mSFEventThread;
511     sp<EventControlThread> mEventControlThread;
512     EGLContext mEGLContext;
513     EGLDisplay mEGLDisplay;
514     sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES];
515
516     // Can only accessed from the main thread, these members
517     // don't need synchronization
518     State mDrawingState;
519     bool mVisibleRegionsDirty;
520 #ifndef USE_HWC2
521     bool mHwWorkListDirty;
522 #else
523     bool mGeometryInvalid;
524 #endif
525     bool mAnimCompositionPending;
526 #ifdef USE_HWC2
527     std::vector<sp<Layer>> mLayersWithQueuedFrames;
528 #endif
529
530     // this may only be written from the main thread with mStateLock held
531     // it may be read from other threads with mStateLock held
532     DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
533
534     // don't use a lock for these, we don't care
535     int mDebugRegion;
536     int mDebugDDMS;
537     int mDebugDisableHWC;
538     int mDebugDisableTransformHint;
539     volatile nsecs_t mDebugInSwapBuffers;
540     nsecs_t mLastSwapBufferTime;
541     volatile nsecs_t mDebugInTransaction;
542     nsecs_t mLastTransactionTime;
543     bool mBootFinished;
544     bool mForceFullDamage;
545     FenceTracker mFenceTracker;
546
547     // these are thread safe
548     mutable MessageQueue mEventQueue;
549     FrameTracker mAnimFrameTracker;
550     DispSync mPrimaryDispSync;
551
552     // protected by mDestroyedLayerLock;
553     mutable Mutex mDestroyedLayerLock;
554     Vector<Layer const *> mDestroyedLayers;
555
556     // protected by mHWVsyncLock
557     Mutex mHWVsyncLock;
558     bool mPrimaryHWVsyncEnabled;
559     bool mHWVsyncAvailable;
560
561     /* ------------------------------------------------------------------------
562      * Feature prototyping
563      */
564
565     Daltonizer mDaltonizer;
566     bool mDaltonize;
567
568     mat4 mColorMatrix;
569     bool mHasColorMatrix;
570
571     mat4 mSecondaryColorMatrix;
572     bool mHasSecondaryColorMatrix;
573
574     // Static screen stats
575     bool mHasPoweredOff;
576     static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
577     nsecs_t mFrameBuckets[NUM_BUCKETS];
578     nsecs_t mTotalTime;
579     std::atomic<nsecs_t> mLastSwapTime;
580
581     FrameRateHelper mFrameRateHelper;
582
583     /*
584      * A number that increases on every new frame composition and screen capture.
585      * LayerBlur can speed up it's drawing by caching texture using this variable
586      * if multiple LayerBlur objects draw in one frame composition.
587      * In case of display mirroring, this variable should be increased on every display.
588      */
589     uint32_t mActiveFrameSequence;
590
591 };
592
593 }; // namespace android
594
595 #endif // ANDROID_SURFACE_FLINGER_H