1/*
2 * Copyright 2015 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_SF_HWC2_H
18#define ANDROID_SF_HWC2_H
19
20#define HWC2_INCLUDE_STRINGIFICATION
21#define HWC2_USE_CPP11
22#include <hardware/hwcomposer2.h>
23#undef HWC2_INCLUDE_STRINGIFICATION
24#undef HWC2_USE_CPP11
25
26#include <gui/HdrMetadata.h>
27#include <math/mat4.h>
28#include <ui/GraphicTypes.h>
29#include <ui/HdrCapabilities.h>
30#include <utils/Log.h>
31#include <utils/StrongPointer.h>
32#include <utils/Timers.h>
33
34#include <functional>
35#include <string>
36#include <unordered_map>
37#include <unordered_set>
38#include <vector>
39
40namespace android {
41    class Fence;
42    class FloatRect;
43    class GraphicBuffer;
44    class Rect;
45    class Region;
46    namespace Hwc2 {
47        class Composer;
48    }
49
50    class TestableSurfaceFlinger;
51}
52
53namespace HWC2 {
54
55class Display;
56class Layer;
57
58// Implement this interface to receive hardware composer events.
59//
60// These callback functions will generally be called on a hwbinder thread, but
61// when first registering the callback the onHotplugReceived() function will
62// immediately be called on the thread calling registerCallback().
63//
64// All calls receive a sequenceId, which will be the value that was supplied to
65// HWC2::Device::registerCallback(). It's used to help differentiate callbacks
66// from different hardware composer instances.
67class ComposerCallback {
68 public:
69    virtual void onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
70                                   Connection connection) = 0;
71    virtual void onRefreshReceived(int32_t sequenceId,
72                                   hwc2_display_t display) = 0;
73    virtual void onVsyncReceived(int32_t sequenceId, hwc2_display_t display,
74                                 int64_t timestamp) = 0;
75    virtual ~ComposerCallback() = default;
76};
77
78// C++ Wrapper around hwc2_device_t. Load all functions pointers
79// and handle callback registration.
80class Device
81{
82public:
83    explicit Device(std::unique_ptr<android::Hwc2::Composer> composer);
84
85    void registerCallback(ComposerCallback* callback, int32_t sequenceId);
86
87    // Required by HWC2
88
89    std::string dump() const;
90
91    const std::unordered_set<Capability>& getCapabilities() const {
92        return mCapabilities;
93    };
94
95    uint32_t getMaxVirtualDisplayCount() const;
96    Error createVirtualDisplay(uint32_t width, uint32_t height,
97            android::ui::PixelFormat* format, Display** outDisplay);
98    void destroyDisplay(hwc2_display_t displayId);
99
100    void onHotplug(hwc2_display_t displayId, Connection connection);
101
102    // Other Device methods
103
104    Display* getDisplayById(hwc2_display_t id);
105
106    android::Hwc2::Composer* getComposer() { return mComposer.get(); }
107
108    // We buffer most state changes and flush them implicitly with
109    // Display::validate, Display::present, and Display::presentOrValidate.
110    // This method provides an explicit way to flush state changes to HWC.
111    Error flushCommands();
112
113private:
114    // Initialization methods
115
116    void loadCapabilities();
117
118    // Member variables
119    std::unique_ptr<android::Hwc2::Composer> mComposer;
120    std::unordered_set<Capability> mCapabilities;
121    std::unordered_map<hwc2_display_t, std::unique_ptr<Display>> mDisplays;
122    bool mRegisteredCallback = false;
123};
124
125// Convenience C++ class to access hwc2_device_t Display functions directly.
126class Display
127{
128public:
129    Display(android::Hwc2::Composer& composer, const std::unordered_set<Capability>& capabilities,
130            hwc2_display_t id, DisplayType type);
131    ~Display();
132
133    class Config
134    {
135    public:
136        class Builder
137        {
138        public:
139            Builder(Display& display, hwc2_config_t id);
140
141            std::shared_ptr<const Config> build() {
142                return std::const_pointer_cast<const Config>(
143                        std::move(mConfig));
144            }
145
146            Builder& setWidth(int32_t width) {
147                mConfig->mWidth = width;
148                return *this;
149            }
150            Builder& setHeight(int32_t height) {
151                mConfig->mHeight = height;
152                return *this;
153            }
154            Builder& setVsyncPeriod(int32_t vsyncPeriod) {
155                mConfig->mVsyncPeriod = vsyncPeriod;
156                return *this;
157            }
158            Builder& setDpiX(int32_t dpiX) {
159                if (dpiX == -1) {
160                    mConfig->mDpiX = getDefaultDensity();
161                } else {
162                    mConfig->mDpiX = dpiX / 1000.0f;
163                }
164                return *this;
165            }
166            Builder& setDpiY(int32_t dpiY) {
167                if (dpiY == -1) {
168                    mConfig->mDpiY = getDefaultDensity();
169                } else {
170                    mConfig->mDpiY = dpiY / 1000.0f;
171                }
172                return *this;
173            }
174
175        private:
176            float getDefaultDensity();
177            std::shared_ptr<Config> mConfig;
178        };
179
180        hwc2_display_t getDisplayId() const { return mDisplay.getId(); }
181        hwc2_config_t getId() const { return mId; }
182
183        int32_t getWidth() const { return mWidth; }
184        int32_t getHeight() const { return mHeight; }
185        nsecs_t getVsyncPeriod() const { return mVsyncPeriod; }
186        float getDpiX() const { return mDpiX; }
187        float getDpiY() const { return mDpiY; }
188
189    private:
190        Config(Display& display, hwc2_config_t id);
191
192        Display& mDisplay;
193        hwc2_config_t mId;
194
195        int32_t mWidth;
196        int32_t mHeight;
197        nsecs_t mVsyncPeriod;
198        float mDpiX;
199        float mDpiY;
200    };
201
202    // Required by HWC2
203
204    [[clang::warn_unused_result]] Error acceptChanges();
205    [[clang::warn_unused_result]] Error createLayer(Layer** outLayer);
206    [[clang::warn_unused_result]] Error destroyLayer(Layer* layer);
207    [[clang::warn_unused_result]] Error getActiveConfig(
208            std::shared_ptr<const Config>* outConfig) const;
209    [[clang::warn_unused_result]] Error getActiveConfigIndex(int* outIndex) const;
210    [[clang::warn_unused_result]] Error getChangedCompositionTypes(
211            std::unordered_map<Layer*, Composition>* outTypes);
212    [[clang::warn_unused_result]] Error getColorModes(
213            std::vector<android::ui::ColorMode>* outModes) const;
214    // outSupportedPerFrameMetadata is an opaque bitmask to the callers
215    // but contains HdrMetadata::Type::*.
216    [[clang::warn_unused_result]] Error getSupportedPerFrameMetadata(
217            int32_t* outSupportedPerFrameMetadata) const;
218    [[clang::warn_unused_result]] Error getRenderIntents(
219            android::ui::ColorMode colorMode,
220            std::vector<android::ui::RenderIntent>* outRenderIntents) const;
221    [[clang::warn_unused_result]] Error getDataspaceSaturationMatrix(
222            android::ui::Dataspace dataspace, android::mat4* outMatrix);
223
224    // Doesn't call into the HWC2 device, so no errors are possible
225    std::vector<std::shared_ptr<const Config>> getConfigs() const;
226
227    [[clang::warn_unused_result]] Error getName(std::string* outName) const;
228    [[clang::warn_unused_result]] Error getRequests(
229            DisplayRequest* outDisplayRequests,
230            std::unordered_map<Layer*, LayerRequest>* outLayerRequests);
231    [[clang::warn_unused_result]] Error getType(DisplayType* outType) const;
232    [[clang::warn_unused_result]] Error supportsDoze(bool* outSupport) const;
233    [[clang::warn_unused_result]] Error getHdrCapabilities(
234            android::HdrCapabilities* outCapabilities) const;
235    [[clang::warn_unused_result]] Error getReleaseFences(
236            std::unordered_map<Layer*,
237                    android::sp<android::Fence>>* outFences) const;
238    [[clang::warn_unused_result]] Error present(
239            android::sp<android::Fence>* outPresentFence);
240    [[clang::warn_unused_result]] Error setActiveConfig(
241            const std::shared_ptr<const Config>& config);
242    [[clang::warn_unused_result]] Error setClientTarget(
243            uint32_t slot, const android::sp<android::GraphicBuffer>& target,
244            const android::sp<android::Fence>& acquireFence,
245            android::ui::Dataspace dataspace);
246    [[clang::warn_unused_result]] Error setColorMode(
247            android::ui::ColorMode mode,
248            android::ui::RenderIntent renderIntent);
249    [[clang::warn_unused_result]] Error setColorTransform(
250            const android::mat4& matrix, android_color_transform_t hint);
251    [[clang::warn_unused_result]] Error setOutputBuffer(
252            const android::sp<android::GraphicBuffer>& buffer,
253            const android::sp<android::Fence>& releaseFence);
254    [[clang::warn_unused_result]] Error setPowerMode(PowerMode mode);
255    [[clang::warn_unused_result]] Error setVsyncEnabled(Vsync enabled);
256    [[clang::warn_unused_result]] Error validate(uint32_t* outNumTypes,
257            uint32_t* outNumRequests);
258    [[clang::warn_unused_result]] Error presentOrValidate(uint32_t* outNumTypes,
259            uint32_t* outNumRequests,
260            android::sp<android::Fence>* outPresentFence, uint32_t* state);
261
262    // Other Display methods
263
264    hwc2_display_t getId() const { return mId; }
265    bool isConnected() const { return mIsConnected; }
266    void setConnected(bool connected);  // For use by Device only
267
268private:
269    int32_t getAttribute(hwc2_config_t configId, Attribute attribute);
270    void loadConfig(hwc2_config_t configId);
271    void loadConfigs();
272
273    // This may fail (and return a null pointer) if no layer with this ID exists
274    // on this display
275    Layer* getLayerById(hwc2_layer_t id) const;
276
277    friend android::TestableSurfaceFlinger;
278
279    // Member variables
280
281    // These are references to data owned by HWC2::Device, which will outlive
282    // this HWC2::Display, so these references are guaranteed to be valid for
283    // the lifetime of this object.
284    android::Hwc2::Composer& mComposer;
285    const std::unordered_set<Capability>& mCapabilities;
286
287    hwc2_display_t mId;
288    bool mIsConnected;
289    DisplayType mType;
290    std::unordered_map<hwc2_layer_t, std::unique_ptr<Layer>> mLayers;
291    std::unordered_map<hwc2_config_t, std::shared_ptr<const Config>> mConfigs;
292};
293
294// Convenience C++ class to access hwc2_device_t Layer functions directly.
295class Layer
296{
297public:
298    Layer(android::Hwc2::Composer& composer,
299          const std::unordered_set<Capability>& capabilities,
300          hwc2_display_t displayId, hwc2_layer_t layerId);
301    ~Layer();
302
303    hwc2_layer_t getId() const { return mId; }
304
305    // Register a listener to be notified when the layer is destroyed. When the
306    // listener function is called, the Layer will be in the process of being
307    // destroyed, so it's not safe to call methods on it.
308    void setLayerDestroyedListener(std::function<void(Layer*)> listener);
309
310    [[clang::warn_unused_result]] Error setCursorPosition(int32_t x, int32_t y);
311    [[clang::warn_unused_result]] Error setBuffer(uint32_t slot,
312            const android::sp<android::GraphicBuffer>& buffer,
313            const android::sp<android::Fence>& acquireFence);
314    [[clang::warn_unused_result]] Error setSurfaceDamage(
315            const android::Region& damage);
316
317    [[clang::warn_unused_result]] Error setBlendMode(BlendMode mode);
318    [[clang::warn_unused_result]] Error setColor(hwc_color_t color);
319    [[clang::warn_unused_result]] Error setCompositionType(Composition type);
320    [[clang::warn_unused_result]] Error setDataspace(
321            android::ui::Dataspace dataspace);
322    [[clang::warn_unused_result]] Error setPerFrameMetadata(
323            const int32_t supportedPerFrameMetadata,
324            const android::HdrMetadata& metadata);
325    [[clang::warn_unused_result]] Error setDisplayFrame(
326            const android::Rect& frame);
327    [[clang::warn_unused_result]] Error setPlaneAlpha(float alpha);
328    [[clang::warn_unused_result]] Error setSidebandStream(
329            const native_handle_t* stream);
330    [[clang::warn_unused_result]] Error setSourceCrop(
331            const android::FloatRect& crop);
332    [[clang::warn_unused_result]] Error setTransform(Transform transform);
333    [[clang::warn_unused_result]] Error setVisibleRegion(
334            const android::Region& region);
335    [[clang::warn_unused_result]] Error setZOrder(uint32_t z);
336    [[clang::warn_unused_result]] Error setInfo(uint32_t type, uint32_t appId);
337
338private:
339    // These are references to data owned by HWC2::Device, which will outlive
340    // this HWC2::Layer, so these references are guaranteed to be valid for
341    // the lifetime of this object.
342    android::Hwc2::Composer& mComposer;
343    const std::unordered_set<Capability>& mCapabilities;
344
345    hwc2_display_t mDisplayId;
346    hwc2_layer_t mId;
347    android::ui::Dataspace mDataSpace = android::ui::Dataspace::UNKNOWN;
348    android::HdrMetadata mHdrMetadata;
349    std::function<void(Layer*)> mLayerDestroyedListener;
350};
351
352} // namespace HWC2
353
354#endif // ANDROID_SF_HWC2_H
355