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_DISPLAY_DEVICE_H
18 #define ANDROID_DISPLAY_DEVICE_H
19 
20 #include "Transform.h"
21 
22 #include <stdlib.h>
23 #include <unordered_map>
24 
25 #include <math/mat4.h>
26 
27 #include <binder/IBinder.h>
28 #include <gui/ISurfaceComposer.h>
29 #include <hardware/hwcomposer_defs.h>
30 #include <ui/GraphicTypes.h>
31 #include <ui/HdrCapabilities.h>
32 #include <ui/Region.h>
33 #include <utils/RefBase.h>
34 #include <utils/Mutex.h>
35 #include <utils/String8.h>
36 #include <utils/Timers.h>
37 
38 #include "RenderArea.h"
39 #include "RenderEngine/Surface.h"
40 
41 #include <memory>
42 
43 struct ANativeWindow;
44 
45 namespace android {
46 
47 struct DisplayInfo;
48 class DisplaySurface;
49 class Fence;
50 class IGraphicBufferProducer;
51 class Layer;
52 class SurfaceFlinger;
53 class HWComposer;
54 
55 class DisplayDevice : public LightRefBase<DisplayDevice>
56 {
57 public:
58     constexpr static float sDefaultMinLumiance = 0.0;
59     constexpr static float sDefaultMaxLumiance = 500.0;
60 
61     // region in layer-stack space
62     mutable Region dirtyRegion;
63     // region in screen space
64     Region undefinedRegion;
65     bool lastCompositionHadVisibleLayers;
66 
67     enum DisplayType {
68         DISPLAY_ID_INVALID = -1,
69         DISPLAY_PRIMARY     = HWC_DISPLAY_PRIMARY,
70         DISPLAY_EXTERNAL    = HWC_DISPLAY_EXTERNAL,
71         DISPLAY_VIRTUAL     = HWC_DISPLAY_VIRTUAL,
72         NUM_BUILTIN_DISPLAY_TYPES = HWC_NUM_PHYSICAL_DISPLAY_TYPES,
73     };
74 
75     enum {
76         NO_LAYER_STACK = 0xFFFFFFFF,
77     };
78 
79     // clang-format off
80     DisplayDevice(
81             const sp<SurfaceFlinger>& flinger,
82             DisplayType type,
83             int32_t hwcId,
84             bool isSecure,
85             const wp<IBinder>& displayToken,
86             const sp<ANativeWindow>& nativeWindow,
87             const sp<DisplaySurface>& displaySurface,
88             std::unique_ptr<RE::Surface> renderSurface,
89             int displayWidth,
90             int displayHeight,
91             bool hasWideColorGamut,
92             const HdrCapabilities& hdrCapabilities,
93             const int32_t supportedPerFrameMetadata,
94             const std::unordered_map<ui::ColorMode, std::vector<ui::RenderIntent>>& hwcColorModes,
95             int initialPowerMode);
96     // clang-format on
97 
98     ~DisplayDevice();
99 
100     // whether this is a valid object. An invalid DisplayDevice is returned
101     // when an non existing id is requested
102     bool isValid() const;
103 
104     // isSecure indicates whether this display can be trusted to display
105     // secure surfaces.
isSecure()106     bool isSecure() const { return mIsSecure; }
107 
108     // Flip the front and back buffers if the back buffer is "dirty".  Might
109     // be instantaneous, might involve copying the frame buffer around.
110     void flip() const;
111 
112     int         getWidth() const;
113     int         getHeight() const;
114 
115     void                    setVisibleLayersSortedByZ(const Vector< sp<Layer> >& layers);
116     const Vector< sp<Layer> >& getVisibleLayersSortedByZ() const;
117     void                    setLayersNeedingFences(const Vector< sp<Layer> >& layers);
118     const Vector< sp<Layer> >& getLayersNeedingFences() const;
119     Region                  getDirtyRegion(bool repaintEverything) const;
120 
121     void                    setLayerStack(uint32_t stack);
122     void                    setDisplaySize(const int newWidth, const int newHeight);
123     void                    setProjection(int orientation, const Rect& viewport, const Rect& frame);
124 
getOrientation()125     int                     getOrientation() const { return mOrientation; }
126     uint32_t                getOrientationTransform() const;
127     static uint32_t         getPrimaryDisplayOrientationTransform();
getTransform()128     const Transform&        getTransform() const { return mGlobalTransform; }
getViewport()129     const Rect              getViewport() const { return mViewport; }
getFrame()130     const Rect              getFrame() const { return mFrame; }
getScissor()131     const Rect&             getScissor() const { return mScissor; }
needsFiltering()132     bool                    needsFiltering() const { return mNeedsFiltering; }
133 
getLayerStack()134     uint32_t                getLayerStack() const { return mLayerStack; }
getDisplayType()135     int32_t                 getDisplayType() const { return mType; }
isPrimary()136     bool                    isPrimary() const { return mType == DISPLAY_PRIMARY; }
getHwcDisplayId()137     int32_t                 getHwcDisplayId() const { return mHwcDisplayId; }
getDisplayToken()138     const wp<IBinder>&      getDisplayToken() const { return mDisplayToken; }
139 
getSupportedPerFrameMetadata()140     int32_t getSupportedPerFrameMetadata() const { return mSupportedPerFrameMetadata; }
141 
142     // We pass in mustRecompose so we can keep VirtualDisplaySurface's state
143     // machine happy without actually queueing a buffer if nothing has changed
144     status_t beginFrame(bool mustRecompose) const;
145     status_t prepareFrame(HWComposer& hwc);
146 
hasWideColorGamut()147     bool hasWideColorGamut() const { return mHasWideColorGamut; }
148     // Whether h/w composer has native support for specific HDR type.
hasHDR10Support()149     bool hasHDR10Support() const { return mHasHdr10; }
hasHLGSupport()150     bool hasHLGSupport() const { return mHasHLG; }
hasDolbyVisionSupport()151     bool hasDolbyVisionSupport() const { return mHasDolbyVision; }
152 
153     // Return true if the HDR dataspace is supported but
154     // there is no corresponding color mode.
155     bool hasLegacyHdrSupport(ui::Dataspace dataspace) const;
156 
157     // The returned HdrCapabilities is the combination of HDR capabilities from
158     // hardware composer and RenderEngine. When the DisplayDevice supports wide
159     // color gamut, RenderEngine is able to simulate HDR support in Display P3
160     // color space for both PQ and HLG HDR contents. The minimum and maximum
161     // luminance will be set to sDefaultMinLumiance and sDefaultMaxLumiance
162     // respectively if hardware composer doesn't return meaningful values.
getHdrCapabilities()163     const HdrCapabilities& getHdrCapabilities() const { return mHdrCapabilities; }
164 
165     // Return true if intent is supported by the display.
166     bool hasRenderIntent(ui::RenderIntent intent) const;
167 
168     void getBestColorMode(ui::Dataspace dataspace, ui::RenderIntent intent,
169                           ui::Dataspace* outDataspace, ui::ColorMode* outMode,
170                           ui::RenderIntent* outIntent) const;
171 
172     void swapBuffers(HWComposer& hwc) const;
173 
174     // called after h/w composer has completed its set() call
175     void onSwapBuffersCompleted() const;
176 
getBounds()177     Rect getBounds() const {
178         return Rect(mDisplayWidth, mDisplayHeight);
179     }
bounds()180     inline Rect bounds() const { return getBounds(); }
181 
182     void setDisplayName(const String8& displayName);
getDisplayName()183     const String8& getDisplayName() const { return mDisplayName; }
184 
185     bool makeCurrent() const;
186     void setViewportAndProjection() const;
187 
188     const sp<Fence>& getClientTargetAcquireFence() const;
189 
190     /* ------------------------------------------------------------------------
191      * Display power mode management.
192      */
193     int getPowerMode() const;
194     void setPowerMode(int mode);
195     bool isDisplayOn() const;
196 
197     ui::ColorMode getActiveColorMode() const;
198     void setActiveColorMode(ui::ColorMode mode);
199     ui::RenderIntent getActiveRenderIntent() const;
200     void setActiveRenderIntent(ui::RenderIntent renderIntent);
201     android_color_transform_t getColorTransform() const;
202     void setColorTransform(const mat4& transform);
203     void setCompositionDataSpace(ui::Dataspace dataspace);
204     ui::Dataspace getCompositionDataSpace() const;
205 
206     /* ------------------------------------------------------------------------
207      * Display active config management.
208      */
209     int getActiveConfig() const;
210     void setActiveConfig(int mode);
211 
212     // release HWC resources (if any) for removable displays
213     void disconnect(HWComposer& hwc);
214 
215     /* ------------------------------------------------------------------------
216      * Debugging
217      */
218     uint32_t getPageFlipCount() const;
219     void dump(String8& result) const;
220 
221 private:
222     /*
223      *  Constants, set during initialization
224      */
225     sp<SurfaceFlinger> mFlinger;
226     DisplayType mType;
227     int32_t mHwcDisplayId;
228     wp<IBinder> mDisplayToken;
229 
230     // ANativeWindow this display is rendering into
231     sp<ANativeWindow> mNativeWindow;
232     sp<DisplaySurface> mDisplaySurface;
233 
234     std::unique_ptr<RE::Surface> mSurface;
235     int             mDisplayWidth;
236     int             mDisplayHeight;
237     mutable uint32_t mPageFlipCount;
238     String8         mDisplayName;
239     bool            mIsSecure;
240 
241     /*
242      * Can only accessed from the main thread, these members
243      * don't need synchronization.
244      */
245 
246     // list of visible layers on that display
247     Vector< sp<Layer> > mVisibleLayersSortedByZ;
248     // list of layers needing fences
249     Vector< sp<Layer> > mLayersNeedingFences;
250 
251     /*
252      * Transaction state
253      */
254     static status_t orientationToTransfrom(int orientation,
255             int w, int h, Transform* tr);
256 
257     // The identifier of the active layer stack for this display. Several displays
258     // can use the same layer stack: A z-ordered group of layers (sometimes called
259     // "surfaces"). Any given layer can only be on a single layer stack.
260     uint32_t mLayerStack;
261 
262     int mOrientation;
263     static uint32_t sPrimaryDisplayOrientation;
264     // user-provided visible area of the layer stack
265     Rect mViewport;
266     // user-provided rectangle where mViewport gets mapped to
267     Rect mFrame;
268     // pre-computed scissor to apply to the display
269     Rect mScissor;
270     Transform mGlobalTransform;
271     bool mNeedsFiltering;
272     // Current power mode
273     int mPowerMode;
274     // Current active config
275     int mActiveConfig;
276     // current active color mode
277     ui::ColorMode mActiveColorMode = ui::ColorMode::NATIVE;
278     // Current active render intent.
279     ui::RenderIntent mActiveRenderIntent = ui::RenderIntent::COLORIMETRIC;
280     ui::Dataspace mCompositionDataSpace = ui::Dataspace::UNKNOWN;
281     // Current color transform
282     android_color_transform_t mColorTransform;
283 
284     // Need to know if display is wide-color capable or not.
285     // Initialized by SurfaceFlinger when the DisplayDevice is created.
286     // Fed to RenderEngine during composition.
287     bool mHasWideColorGamut;
288     bool mHasHdr10;
289     bool mHasHLG;
290     bool mHasDolbyVision;
291     HdrCapabilities mHdrCapabilities;
292     const int32_t mSupportedPerFrameMetadata;
293 
294     // Mappings from desired Dataspace/RenderIntent to the supported
295     // Dataspace/ColorMode/RenderIntent.
296     using ColorModeKey = uint64_t;
297     struct ColorModeValue {
298         ui::Dataspace dataspace;
299         ui::ColorMode colorMode;
300         ui::RenderIntent renderIntent;
301     };
302 
getColorModeKey(ui::Dataspace dataspace,ui::RenderIntent intent)303     static ColorModeKey getColorModeKey(ui::Dataspace dataspace, ui::RenderIntent intent) {
304         return (static_cast<uint64_t>(dataspace) << 32) | static_cast<uint32_t>(intent);
305     }
306     void populateColorModes(
307             const std::unordered_map<ui::ColorMode, std::vector<ui::RenderIntent>>& hwcColorModes);
308     void addColorMode(
309             const std::unordered_map<ui::ColorMode, std::vector<ui::RenderIntent>>& hwcColorModes,
310             const ui::ColorMode mode, const ui::RenderIntent intent);
311 
312     std::unordered_map<ColorModeKey, ColorModeValue> mColorModes;
313 };
314 
315 struct DisplayDeviceState {
316     DisplayDeviceState() = default;
317     DisplayDeviceState(DisplayDevice::DisplayType type, bool isSecure);
318 
isValidDisplayDeviceState319     bool isValid() const { return type >= 0; }
isMainDisplayDisplayDeviceState320     bool isMainDisplay() const { return type == DisplayDevice::DISPLAY_PRIMARY; }
isVirtualDisplayDisplayDeviceState321     bool isVirtualDisplay() const { return type >= DisplayDevice::DISPLAY_VIRTUAL; }
322 
323     static std::atomic<int32_t> nextDisplayId;
324     int32_t displayId = nextDisplayId++;
325     DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_ID_INVALID;
326     sp<IGraphicBufferProducer> surface;
327     uint32_t layerStack = DisplayDevice::NO_LAYER_STACK;
328     Rect viewport;
329     Rect frame;
330     uint8_t orientation = 0;
331     uint32_t width = 0;
332     uint32_t height = 0;
333     String8 displayName;
334     bool isSecure = false;
335 };
336 
337 class DisplayRenderArea : public RenderArea {
338 public:
339     DisplayRenderArea(const sp<const DisplayDevice> device,
340                       ISurfaceComposer::Rotation rotation = ISurfaceComposer::eRotateNone)
341           : DisplayRenderArea(device, device->getBounds(), device->getHeight(), device->getWidth(),
342                               rotation) {}
DisplayRenderArea(const sp<const DisplayDevice> device,Rect sourceCrop,uint32_t reqHeight,uint32_t reqWidth,ISurfaceComposer::Rotation rotation)343     DisplayRenderArea(const sp<const DisplayDevice> device, Rect sourceCrop, uint32_t reqHeight,
344                       uint32_t reqWidth, ISurfaceComposer::Rotation rotation)
345           : RenderArea(reqHeight, reqWidth, CaptureFill::OPAQUE, rotation), mDevice(device),
346                               mSourceCrop(sourceCrop) {}
347 
getTransform()348     const Transform& getTransform() const override { return mDevice->getTransform(); }
getBounds()349     Rect getBounds() const override { return mDevice->getBounds(); }
getHeight()350     int getHeight() const override { return mDevice->getHeight(); }
getWidth()351     int getWidth() const override { return mDevice->getWidth(); }
isSecure()352     bool isSecure() const override { return mDevice->isSecure(); }
needsFiltering()353     bool needsFiltering() const override { return mDevice->needsFiltering(); }
getSourceCrop()354     Rect getSourceCrop() const override { return mSourceCrop; }
355 
356 private:
357     const sp<const DisplayDevice> mDevice;
358     const Rect mSourceCrop;
359 };
360 
361 }; // namespace android
362 
363 #endif // ANDROID_DISPLAY_DEVICE_H
364