OSDN Git Service

drm_hwcomposer: Rework display modes handling
[android-x86/external-drm_hwcomposer.git] / DrmHwcTwo.h
1 /*
2  * Copyright (C) 2016 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_DRM_HWC_TWO_H_
18 #define ANDROID_DRM_HWC_TWO_H_
19
20 #include <hardware/hwcomposer2.h>
21 #include <math.h>
22
23 #include <array>
24 #include <map>
25
26 #include "compositor/DrmDisplayCompositor.h"
27 #include "compositor/Planner.h"
28 #include "drm/ResourceManager.h"
29 #include "drm/VSyncWorker.h"
30 #include "drmhwcomposer.h"
31
32 namespace android {
33
34 class Backend;
35
36 class DrmHwcTwo : public hwc2_device_t {
37  public:
38   static int HookDevOpen(const struct hw_module_t *module, const char *name,
39                          struct hw_device_t **dev);
40
41   DrmHwcTwo();
42
43   HWC2::Error Init();
44
45   std::pair<HWC2_PFN_HOTPLUG, hwc2_callback_data_t> hotplug_callback_{};
46   std::pair<HWC2_PFN_VSYNC, hwc2_callback_data_t> vsync_callback_{};
47 #if PLATFORM_SDK_VERSION > 29
48   std::pair<HWC2_PFN_VSYNC_2_4, hwc2_callback_data_t> vsync_2_4_callback_{};
49 #endif
50   std::pair<HWC2_PFN_REFRESH, hwc2_callback_data_t> refresh_callback_{};
51
52   std::mutex callback_lock_;
53
54   class HwcLayer {
55    public:
56     HWC2::Composition sf_type() const {
57       return sf_type_;
58     }
59     HWC2::Composition validated_type() const {
60       return validated_type_;
61     }
62     void accept_type_change() {
63       sf_type_ = validated_type_;
64     }
65     void set_validated_type(HWC2::Composition type) {
66       validated_type_ = type;
67     }
68     bool type_changed() const {
69       return sf_type_ != validated_type_;
70     }
71
72     uint32_t z_order() const {
73       return z_order_;
74     }
75
76     buffer_handle_t buffer() {
77       return buffer_;
78     }
79     void set_buffer(buffer_handle_t buffer) {
80       buffer_ = buffer;
81     }
82
83     hwc_rect_t display_frame() {
84       return display_frame_;
85     }
86
87     void PopulateDrmLayer(DrmHwcLayer *layer);
88
89     bool RequireScalingOrPhasing() {
90       float src_width = source_crop_.right - source_crop_.left;
91       float src_height = source_crop_.bottom - source_crop_.top;
92
93       float dest_width = display_frame_.right - display_frame_.left;
94       float dest_height = display_frame_.bottom - display_frame_.top;
95
96       bool scaling = src_width != dest_width || src_height != dest_height;
97       bool phasing = (source_crop_.left - floor(source_crop_.left) != 0) ||
98                      (source_crop_.top - floor(source_crop_.top) != 0);
99       return scaling || phasing;
100     }
101
102     // Layer hooks
103     HWC2::Error SetCursorPosition(int32_t /*x*/, int32_t /*y*/);
104     HWC2::Error SetLayerBlendMode(int32_t mode);
105     HWC2::Error SetLayerBuffer(buffer_handle_t buffer, int32_t acquire_fence);
106     HWC2::Error SetLayerColor(hwc_color_t /*color*/);
107     HWC2::Error SetLayerCompositionType(int32_t type);
108     HWC2::Error SetLayerDataspace(int32_t dataspace);
109     HWC2::Error SetLayerDisplayFrame(hwc_rect_t frame);
110     HWC2::Error SetLayerPlaneAlpha(float alpha);
111     HWC2::Error SetLayerSidebandStream(const native_handle_t *stream);
112     HWC2::Error SetLayerSourceCrop(hwc_frect_t crop);
113     HWC2::Error SetLayerSurfaceDamage(hwc_region_t damage);
114     HWC2::Error SetLayerTransform(int32_t transform);
115     HWC2::Error SetLayerVisibleRegion(hwc_region_t visible);
116     HWC2::Error SetLayerZOrder(uint32_t order);
117
118     UniqueFd acquire_fence_;
119
120     /*
121      * Release fence is not used.
122      * There is no release fence support available in the DRM/KMS. In case no
123      * release fence provided application will use this buffer for writing when
124      * the next frame present fence is signaled.
125      */
126     UniqueFd release_fence_;
127
128    private:
129     // sf_type_ stores the initial type given to us by surfaceflinger,
130     // validated_type_ stores the type after running ValidateDisplay
131     HWC2::Composition sf_type_ = HWC2::Composition::Invalid;
132     HWC2::Composition validated_type_ = HWC2::Composition::Invalid;
133
134     buffer_handle_t buffer_ = NULL;
135     hwc_rect_t display_frame_;
136     float alpha_ = 1.0f;
137     hwc_frect_t source_crop_;
138     DrmHwcTransform transform_ = DrmHwcTransform::kIdentity;
139     uint32_t z_order_ = 0;
140     DrmHwcBlending blending_ = DrmHwcBlending::kNone;
141     DrmHwcColorSpace color_space_ = DrmHwcColorSpace::kUndefined;
142     DrmHwcSampleRange sample_range_ = DrmHwcSampleRange::kUndefined;
143   };
144
145   class HwcDisplay {
146    public:
147     HwcDisplay(ResourceManager *resource_manager, DrmDevice *drm,
148                hwc2_display_t handle, HWC2::DisplayType type, DrmHwcTwo *hwc2);
149     HwcDisplay(const HwcDisplay &) = delete;
150     HWC2::Error Init(std::vector<DrmPlane *> *planes);
151
152     HWC2::Error CreateComposition(AtomicCommitArgs &a_args);
153     std::vector<DrmHwcTwo::HwcLayer *> GetOrderLayersByZPos();
154
155     void ClearDisplay();
156
157     std::string Dump();
158
159     // HWC Hooks
160     HWC2::Error AcceptDisplayChanges();
161     HWC2::Error CreateLayer(hwc2_layer_t *layer);
162     HWC2::Error DestroyLayer(hwc2_layer_t layer);
163     HWC2::Error GetActiveConfig(hwc2_config_t *config) const;
164     HWC2::Error GetChangedCompositionTypes(uint32_t *num_elements,
165                                            hwc2_layer_t *layers,
166                                            int32_t *types);
167     HWC2::Error GetClientTargetSupport(uint32_t width, uint32_t height,
168                                        int32_t format, int32_t dataspace);
169     HWC2::Error GetColorModes(uint32_t *num_modes, int32_t *modes);
170     HWC2::Error GetDisplayAttribute(hwc2_config_t config, int32_t attribute,
171                                     int32_t *value);
172     HWC2::Error GetDisplayConfigs(uint32_t *num_configs,
173                                   hwc2_config_t *configs);
174     HWC2::Error GetDisplayName(uint32_t *size, char *name);
175     HWC2::Error GetDisplayRequests(int32_t *display_requests,
176                                    uint32_t *num_elements, hwc2_layer_t *layers,
177                                    int32_t *layer_requests);
178     HWC2::Error GetDisplayType(int32_t *type);
179 #if PLATFORM_SDK_VERSION > 27
180     HWC2::Error GetRenderIntents(int32_t mode, uint32_t *outNumIntents,
181                                  int32_t *outIntents);
182     HWC2::Error SetColorModeWithIntent(int32_t mode, int32_t intent);
183 #endif
184 #if PLATFORM_SDK_VERSION > 28
185     HWC2::Error GetDisplayIdentificationData(uint8_t *outPort,
186                                              uint32_t *outDataSize,
187                                              uint8_t *outData);
188     HWC2::Error GetDisplayCapabilities(uint32_t *outNumCapabilities,
189                                        uint32_t *outCapabilities);
190     HWC2::Error GetDisplayBrightnessSupport(bool *supported);
191     HWC2::Error SetDisplayBrightness(float);
192 #endif
193 #if PLATFORM_SDK_VERSION > 29
194     HWC2::Error GetDisplayConnectionType(uint32_t *outType);
195     HWC2::Error GetDisplayVsyncPeriod(hwc2_vsync_period_t *outVsyncPeriod);
196
197     HWC2::Error SetActiveConfigWithConstraints(
198         hwc2_config_t config,
199         hwc_vsync_period_change_constraints_t *vsyncPeriodChangeConstraints,
200         hwc_vsync_period_change_timeline_t *outTimeline);
201     HWC2::Error SetAutoLowLatencyMode(bool on);
202     HWC2::Error GetSupportedContentTypes(
203         uint32_t *outNumSupportedContentTypes,
204         const uint32_t *outSupportedContentTypes);
205
206     HWC2::Error SetContentType(int32_t contentType);
207 #endif
208
209     HWC2::Error GetDozeSupport(int32_t *support);
210     HWC2::Error GetHdrCapabilities(uint32_t *num_types, int32_t *types,
211                                    float *max_luminance,
212                                    float *max_average_luminance,
213                                    float *min_luminance);
214     HWC2::Error GetReleaseFences(uint32_t *num_elements, hwc2_layer_t *layers,
215                                  int32_t *fences);
216     HWC2::Error PresentDisplay(int32_t *present_fence);
217     HWC2::Error SetActiveConfig(hwc2_config_t config);
218     HWC2::Error ChosePreferredConfig();
219     HWC2::Error SetClientTarget(buffer_handle_t target, int32_t acquire_fence,
220                                 int32_t dataspace, hwc_region_t damage);
221     HWC2::Error SetColorMode(int32_t mode);
222     HWC2::Error SetColorTransform(const float *matrix, int32_t hint);
223     HWC2::Error SetOutputBuffer(buffer_handle_t buffer, int32_t release_fence);
224     HWC2::Error SetPowerMode(int32_t mode);
225     HWC2::Error SetVsyncEnabled(int32_t enabled);
226     HWC2::Error ValidateDisplay(uint32_t *num_types, uint32_t *num_requests);
227     HwcLayer *get_layer(hwc2_layer_t layer) {
228       auto it = layers_.find(layer);
229       if (it == layers_.end())
230         return nullptr;
231       return &it->second;
232     }
233
234     /* Statistics */
235     struct Stats {
236       Stats minus(Stats b) {
237         return {total_frames_ - b.total_frames_,
238                 total_pixops_ - b.total_pixops_,
239                 gpu_pixops_ - b.gpu_pixops_,
240                 failed_kms_validate_ - b.failed_kms_validate_,
241                 failed_kms_present_ - b.failed_kms_present_,
242                 frames_flattened_ - b.frames_flattened_};
243       }
244
245       uint32_t total_frames_ = 0;
246       uint64_t total_pixops_ = 0;
247       uint64_t gpu_pixops_ = 0;
248       uint32_t failed_kms_validate_ = 0;
249       uint32_t failed_kms_present_ = 0;
250       uint32_t frames_flattened_ = 0;
251     };
252
253     struct HwcDisplayConfig {
254       int id{};
255       int group_id{};
256       DrmMode mode;
257       bool disabled{};
258
259       bool IsInterlaced() {
260         return (mode.flags() & DRM_MODE_FLAG_INTERLACE) != 0;
261       }
262     };
263
264     std::map<int /*config_id*/, struct HwcDisplayConfig> hwc_configs_;
265
266     int active_config_id_ = 0;
267     int preferred_config_id_ = 0;
268
269     const Backend *backend() const {
270       return backend_.get();
271     }
272     void set_backend(std::unique_ptr<Backend> backend) {
273       backend_ = std::move(backend);
274     }
275
276     const std::vector<DrmPlane *> &primary_planes() const {
277       return primary_planes_;
278     }
279
280     const std::vector<DrmPlane *> &overlay_planes() const {
281       return overlay_planes_;
282     }
283
284     std::map<hwc2_layer_t, HwcLayer> &layers() {
285       return layers_;
286     }
287
288     const DrmDisplayCompositor &compositor() const {
289       return compositor_;
290     }
291
292     const DrmDevice *drm() const {
293       return drm_;
294     }
295
296     const DrmConnector *connector() const {
297       return connector_;
298     }
299
300     ResourceManager *resource_manager() const {
301       return resource_manager_;
302     }
303
304     android_color_transform_t &color_transform_hint() {
305       return color_transform_hint_;
306     }
307
308     Stats &total_stats() {
309       return total_stats_;
310     }
311
312     /* returns true if composition should be sent to client */
313     bool ProcessClientFlatteningState(bool skip) {
314       int flattenning_state = flattenning_state_;
315       if (flattenning_state == ClientFlattenningState::Disabled) {
316         return false;
317       }
318
319       if (skip) {
320         flattenning_state_ = ClientFlattenningState::NotRequired;
321         return false;
322       }
323
324       if (flattenning_state == ClientFlattenningState::ClientRefreshRequested) {
325         flattenning_state_ = ClientFlattenningState::Flattened;
326         return true;
327       }
328
329       flattening_vsync_worker_.VSyncControl(true);
330       flattenning_state_ = ClientFlattenningState::VsyncCountdownMax;
331       return false;
332     }
333
334    private:
335     enum ClientFlattenningState : int32_t {
336       Disabled = -3,
337       NotRequired = -2,
338       Flattened = -1,
339       ClientRefreshRequested = 0,
340       VsyncCountdownMax = 60, /* 1 sec @ 60FPS */
341     };
342
343     std::atomic_int flattenning_state_{ClientFlattenningState::NotRequired};
344     VSyncWorker flattening_vsync_worker_;
345
346     constexpr static size_t MATRIX_SIZE = 16;
347
348     DrmHwcTwo *hwc2_;
349
350     ResourceManager *resource_manager_;
351     DrmDevice *drm_;
352     DrmDisplayCompositor compositor_;
353     std::unique_ptr<Planner> planner_;
354
355     std::vector<DrmPlane *> primary_planes_;
356     std::vector<DrmPlane *> overlay_planes_;
357
358     std::unique_ptr<Backend> backend_;
359
360     VSyncWorker vsync_worker_;
361     DrmConnector *connector_ = NULL;
362     DrmCrtc *crtc_ = NULL;
363     hwc2_display_t handle_;
364     HWC2::DisplayType type_;
365     uint32_t layer_idx_ = 0;
366     std::map<hwc2_layer_t, HwcLayer> layers_;
367     HwcLayer client_layer_;
368     int32_t color_mode_{};
369     std::array<float, MATRIX_SIZE> color_transform_matrix_{};
370     android_color_transform_t color_transform_hint_;
371
372     uint32_t frame_no_ = 0;
373     Stats total_stats_;
374     Stats prev_stats_;
375     std::string DumpDelta(DrmHwcTwo::HwcDisplay::Stats delta);
376   };
377
378  private:
379   static DrmHwcTwo *toDrmHwcTwo(hwc2_device_t *dev) {
380     return static_cast<DrmHwcTwo *>(dev);
381   }
382
383   template <typename PFN, typename T>
384   static hwc2_function_pointer_t ToHook(T function) {
385     static_assert(std::is_same<PFN, T>::value, "Incompatible fn pointer");
386     return reinterpret_cast<hwc2_function_pointer_t>(function);
387   }
388
389   template <typename T, typename HookType, HookType func, typename... Args>
390   static T DeviceHook(hwc2_device_t *dev, Args... args) {
391     DrmHwcTwo *hwc = toDrmHwcTwo(dev);
392     return static_cast<T>(((*hwc).*func)(std::forward<Args>(args)...));
393   }
394
395   static HwcDisplay *GetDisplay(DrmHwcTwo *hwc, hwc2_display_t display_handle) {
396     auto it = hwc->displays_.find(display_handle);
397     if (it == hwc->displays_.end())
398       return nullptr;
399
400     return &it->second;
401   }
402
403   template <typename HookType, HookType func, typename... Args>
404   static int32_t DisplayHook(hwc2_device_t *dev, hwc2_display_t display_handle,
405                              Args... args) {
406     HwcDisplay *display = GetDisplay(toDrmHwcTwo(dev), display_handle);
407     if (!display)
408       return static_cast<int32_t>(HWC2::Error::BadDisplay);
409
410     return static_cast<int32_t>((display->*func)(std::forward<Args>(args)...));
411   }
412
413   template <typename HookType, HookType func, typename... Args>
414   static int32_t LayerHook(hwc2_device_t *dev, hwc2_display_t display_handle,
415                            hwc2_layer_t layer_handle, Args... args) {
416     HwcDisplay *display = GetDisplay(toDrmHwcTwo(dev), display_handle);
417     if (!display)
418       return static_cast<int32_t>(HWC2::Error::BadDisplay);
419
420     HwcLayer *layer = display->get_layer(layer_handle);
421     if (!layer)
422       return static_cast<int32_t>(HWC2::Error::BadLayer);
423
424     return static_cast<int32_t>((layer->*func)(std::forward<Args>(args)...));
425   }
426
427   // hwc2_device_t hooks
428   static int HookDevClose(hw_device_t *dev);
429   static void HookDevGetCapabilities(hwc2_device_t *dev, uint32_t *out_count,
430                                      int32_t *out_capabilities);
431   static hwc2_function_pointer_t HookDevGetFunction(struct hwc2_device *device,
432                                                     int32_t descriptor);
433
434   // Device functions
435   HWC2::Error CreateVirtualDisplay(uint32_t width, uint32_t height,
436                                    int32_t *format, hwc2_display_t *display);
437   HWC2::Error DestroyVirtualDisplay(hwc2_display_t display);
438   void Dump(uint32_t *outSize, char *outBuffer);
439   uint32_t GetMaxVirtualDisplayCount();
440   HWC2::Error RegisterCallback(int32_t descriptor, hwc2_callback_data_t data,
441                                hwc2_function_pointer_t function);
442   HWC2::Error CreateDisplay(hwc2_display_t displ, HWC2::DisplayType type);
443   void HandleDisplayHotplug(hwc2_display_t displayid, int state);
444   void HandleInitialHotplugState(DrmDevice *drmDevice);
445
446   void HandleHotplugUEvent();
447
448   ResourceManager resource_manager_;
449   std::map<hwc2_display_t, HwcDisplay> displays_;
450
451   std::string mDumpString;
452 };
453 }  // namespace android
454
455 #endif