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