hardware_composer.h revision 105036fa54ad282611d355ecea00c470abbfa4a0
1#ifndef ANDROID_DVR_SERVICES_DISPLAYD_HARDWARE_COMPOSER_H_
2#define ANDROID_DVR_SERVICES_DISPLAYD_HARDWARE_COMPOSER_H_
3
4#include <log/log.h>
5#include <hardware/gralloc.h>
6#include <hardware/hardware.h>
7#include <hardware/hwcomposer2.h>
8
9#include <private/dvr/buffer_hub_client.h>
10#include <private/dvr/sync_util.h>
11
12#include <array>
13#include <condition_variable>
14#include <memory>
15#include <mutex>
16#include <thread>
17#include <tuple>
18#include <vector>
19
20#include <pdx/file_handle.h>
21#include <private/dvr/buffer_hub_client.h>
22#include <private/dvr/frame_time_history.h>
23#include <private/dvr/sync_util.h>
24
25#include "acquired_buffer.h"
26#include "compositor.h"
27#include "display_surface.h"
28
29#include "DisplayHardware/ComposerHal.h"
30
31// Hardware composer HAL doesn't define HWC_TRANSFORM_NONE as of this writing.
32#ifndef HWC_TRANSFORM_NONE
33#define HWC_TRANSFORM_NONE static_cast<hwc_transform_t>(0)
34#endif
35
36namespace android {
37namespace dvr {
38
39// Basic display metrics for physical displays. Dimensions and densities are
40// relative to the physical display orientation, which may be different from the
41// logical display orientation exposed to applications.
42struct HWCDisplayMetrics {
43  int width;
44  int height;
45  struct {
46    int x;
47    int y;
48  } dpi;
49  int vsync_period_ns;
50};
51
52// Layer represents the connection between a hardware composer layer and the
53// source supplying buffers for the layer's contents.
54class Layer {
55 public:
56  Layer();
57
58  // Sets the hardware composer layer and display metrics that this Layer should
59  // use each Prepare cycle. This class does not own either of these pointers,
60  // which MUST remain valid for its lifetime. This method MUST be called once
61  // in the life of the instance before any other method is valid to call.
62  void Initialize(Hwc2::Composer* hwc2_hidl, HWCDisplayMetrics* metrics);
63
64  // Releases any shared pointers and fence handles held by this instance.
65  void Reset();
66
67  // Sets up the layer to use a display surface as its content source. The Layer
68  // will automatically handle ACQUIRE/RELEASE phases for the surface's buffer
69  // train every frame.
70  //
71  // |blending| receives HWC_BLENDING_* values.
72  // |transform| receives HWC_TRANSFORM_* values.
73  // |composition_type| receives either HWC_FRAMEBUFFER for most layers or
74  // HWC_FRAMEBUFFER_TARGET (unless you know what you are doing).
75  // |index| is the index of this surface in the DisplaySurface array.
76  void Setup(const std::shared_ptr<DisplaySurface>& surface,
77             hwc2_blend_mode_t blending, hwc_transform_t transform,
78             hwc2_composition_t composition_type, size_t index);
79
80  // Sets up the layer to use a direct buffer as its content source. No special
81  // handling of the buffer is performed; responsibility for updating or
82  // changing the buffer each frame is on the caller.
83  //
84  // |blending| receives HWC_BLENDING_* values.
85  // |transform| receives HWC_TRANSFORM_* values.
86  // |composition_type| receives either HWC_FRAMEBUFFER for most layers or
87  // HWC_FRAMEBUFFER_TARGET (unless you know what you are doing).
88  void Setup(const std::shared_ptr<IonBuffer>& buffer,
89             hwc2_blend_mode_t blending, hwc_transform_t transform,
90             hwc2_composition_t composition_type, size_t z_order);
91
92  // Layers that use a direct IonBuffer should call this each frame to update
93  // which buffer will be used for the next PostLayers.
94  void UpdateDirectBuffer(const std::shared_ptr<IonBuffer>& buffer);
95
96  // Sets up the hardware composer layer for the next frame. When the layer is
97  // associated with a display surface, this method automatically ACQUIRES a new
98  // buffer if one is available.
99  void Prepare();
100
101  // After calling prepare, if this frame is to be dropped instead of passing
102  // along to the HWC, call Drop to close the contained fence(s).
103  void Drop();
104
105  // Performs fence bookkeeping after the frame has been posted to hardware
106  // composer.
107  void Finish(int release_fence_fd);
108
109  // Sets the blending for the layer. |blending| receives HWC_BLENDING_* values.
110  void SetBlending(hwc2_blend_mode_t blending);
111
112  // Sets the Z-order of this layer
113  void SetZOrderIndex(int surface_index);
114
115  // Gets the current IonBuffer associated with this layer. Ownership of the
116  // buffer DOES NOT pass to the caller and the pointer is not guaranteed to
117  // remain valid across calls to Layer::Setup(), Layer::Prepare(), or
118  // Layer::Reset(). YOU HAVE BEEN WARNED.
119  IonBuffer* GetBuffer();
120
121  hwc2_composition_t GetCompositionType() const { return composition_type_; }
122
123  hwc2_layer_t GetLayerHandle() const { return hardware_composer_layer_; }
124
125  bool UsesDirectBuffer() const { return direct_buffer_ != nullptr; }
126
127  bool IsLayerSetup() const {
128    return direct_buffer_ != nullptr || surface_ != nullptr;
129  }
130
131  // Applies all of the settings to this layer using the hwc functions
132  void UpdateLayerSettings();
133
134  int GetSurfaceId() const {
135    if (surface_ != nullptr) {
136      return surface_->surface_id();
137    } else {
138      return -1;
139    }
140  }
141
142 private:
143  void CommonLayerSetup();
144
145  Hwc2::Composer* hwc2_hidl_;
146
147  // Original display surface array index for tracking purposes.
148  size_t surface_index_;
149
150  // The hardware composer layer and metrics to use during the prepare cycle.
151  hwc2_layer_t hardware_composer_layer_;
152  HWCDisplayMetrics* display_metrics_;
153
154  // Layer properties used to setup the hardware composer layer during the
155  // Prepare phase.
156  hwc2_blend_mode_t blending_;
157  hwc_transform_t transform_;
158  hwc2_composition_t composition_type_;
159
160  // These two members are mutually exclusive. When direct_buffer_ is set the
161  // Layer gets its contents directly from that buffer; when surface_ is set the
162  // Layer gets it contents from the surface's buffer train.
163  std::shared_ptr<IonBuffer> direct_buffer_;
164  std::shared_ptr<DisplaySurface> surface_;
165
166  // State when associated with a display surface.
167  AcquiredBuffer acquired_buffer_;
168  pdx::LocalHandle release_fence_;
169
170  pdx::LocalHandle acquire_fence_fd_;
171  bool surface_rect_functions_applied_;
172
173  Layer(const Layer&) = delete;
174  void operator=(const Layer&) = delete;
175};
176
177// HardwareComposer encapsulates the hardware composer HAL, exposing a
178// simplified API to post buffers to the display.
179class HardwareComposer {
180 public:
181  // Type for vsync callback.
182  using VSyncCallback = std::function<void(int, int64_t, int64_t, uint32_t)>;
183
184  // Since there is no universal way to query the number of hardware layers,
185  // just set it to 4 for now.
186  static constexpr int kMaxHardwareLayers = 4;
187
188  HardwareComposer();
189  HardwareComposer(Hwc2::Composer* hidl);
190  ~HardwareComposer();
191
192  bool Suspend();
193  bool Resume();
194  bool IsSuspended() const { return pause_post_thread_; }
195
196  // Get the HMD display metrics for the current display.
197  DisplayMetrics GetHmdDisplayMetrics() const;
198
199  int32_t GetDisplayAttribute(hwc2_display_t display, hwc2_config_t config,
200                              hwc2_attribute_t attributes,
201                              int32_t* out_value) const;
202  int32_t GetDisplayMetrics(hwc2_display_t display, hwc2_config_t config,
203                            HWCDisplayMetrics* out_metrics) const;
204  void Dump(char* buffer, uint32_t* out_size);
205
206  void SetVSyncCallback(VSyncCallback callback);
207
208  // Metrics of the logical display, which is always landscape.
209  int DisplayWidth() const { return display_metrics_.width; }
210  int DisplayHeight() const { return display_metrics_.height; }
211  HWCDisplayMetrics display_metrics() const { return display_metrics_; }
212
213  // Metrics of the native display, which depends on the specific hardware
214  // implementation of the display.
215  HWCDisplayMetrics native_display_metrics() const {
216    return native_display_metrics_;
217  }
218
219  std::shared_ptr<IonBuffer> framebuffer_target() const {
220    return framebuffer_target_;
221  }
222
223  // Set the display surface stack to compose to the display each frame.
224  int SetDisplaySurfaces(std::vector<std::shared_ptr<DisplaySurface>> surfaces);
225
226  Compositor* GetCompositor() { return &compositor_; }
227
228 private:
229  int32_t EnableVsync(bool enabled);
230
231  class ComposerCallback : public Hwc2::IComposerCallback {
232   public:
233    ComposerCallback() {}
234
235    hardware::Return<void> onHotplug(Hwc2::Display /*display*/,
236                                     Connection /*connected*/) override {
237      // TODO(skiazyk): depending on how the server is implemented, we might
238      // have to set it up to synchronize with receiving this event, as it can
239      // potentially be a critical event for setting up state within the
240      // hwc2 module. That is, we (technically) should not call any other hwc
241      // methods until this method has been called after registering the
242      // callbacks.
243      return hardware::Void();
244    }
245
246    hardware::Return<void> onRefresh(Hwc2::Display /*display*/) override {
247      return hardware::Void();
248    }
249
250    hardware::Return<void> onVsync(Hwc2::Display /*display*/,
251                                   int64_t /*timestamp*/) override {
252      return hardware::Void();
253    }
254  };
255
256  int32_t Validate(hwc2_display_t display);
257  int32_t Present(hwc2_display_t display);
258
259  void SetBacklightBrightness(int brightness);
260
261  void PostLayers(bool is_geometry_changed);
262  void PostThread();
263
264  int ReadWaitPPState();
265  int BlockUntilVSync();
266  int ReadVSyncTimestamp(int64_t* timestamp);
267  int WaitForVSync(int64_t* timestamp);
268  int SleepUntil(int64_t wakeup_timestamp);
269
270  bool IsFramePendingInDriver() { return ReadWaitPPState() == 1; }
271
272  // Returns true if the layer config changed, false otherwise
273  bool UpdateLayerConfig(
274      std::vector<std::shared_ptr<DisplaySurface>>* compositor_surfaces);
275  void PostCompositorBuffers(
276      const std::vector<std::shared_ptr<DisplaySurface>>& compositor_surfaces);
277
278  void UpdateDisplayState();
279
280  struct FrameTimeMeasurementRecord {
281    int64_t start_time;
282    pdx::LocalHandle fence;
283
284    FrameTimeMeasurementRecord(FrameTimeMeasurementRecord&&) = default;
285    FrameTimeMeasurementRecord& operator=(FrameTimeMeasurementRecord&&) =
286        default;
287    FrameTimeMeasurementRecord(const FrameTimeMeasurementRecord&) = delete;
288    FrameTimeMeasurementRecord& operator=(const FrameTimeMeasurementRecord&) =
289        delete;
290  };
291
292  void UpdateFrameTimeHistory(std::vector<FrameTimeMeasurementRecord>* backlog,
293                              int backlog_max,
294                              FenceInfoBuffer* fence_info_buffer,
295                              FrameTimeHistory* history);
296
297  // Returns true if the frame finished rendering, false otherwise. If the frame
298  // finished the frame end time is stored in timestamp. Doesn't block.
299  bool CheckFrameFinished(int frame_fence_fd,
300                          FenceInfoBuffer* fence_info_buffer,
301                          int64_t* timestamp);
302
303  void HandlePendingScreenshots();
304
305  void PausePostThread();
306
307  // Hardware composer HAL device.
308  std::unique_ptr<Hwc2::Composer> hwc2_hidl_;
309  sp<ComposerCallback> callbacks_;
310
311  // Display metrics of the physical display.
312  HWCDisplayMetrics native_display_metrics_;
313  // Display metrics of the logical display, adjusted so that orientation is
314  // landscape.
315  HWCDisplayMetrics display_metrics_;
316  // Transform required to get from native to logical display orientation.
317  hwc_transform_t display_transform_;
318
319  // Buffer for the background layer required by hardware composer.
320  std::shared_ptr<IonBuffer> framebuffer_target_;
321
322  // Protects access to the display surfaces and logical layers.
323  std::mutex layer_mutex_;
324
325  // Active display surfaces configured by the display manager.
326  std::vector<std::shared_ptr<DisplaySurface>> display_surfaces_;
327  std::vector<std::shared_ptr<DisplaySurface>> added_display_surfaces_;
328  bool display_surfaces_updated_;
329  bool hardware_layers_need_update_;
330
331  // Layer array for handling buffer flow into hardware composer layers.
332  // Note that the first array is the actual storage for the layer objects,
333  // and the latter is an array of pointers, which can be freely re-arranged
334  // without messing up the underlying objects.
335  std::array<Layer, kMaxHardwareLayers> layer_storage_;
336  std::array<Layer*, kMaxHardwareLayers> layers_;
337  size_t active_layer_count_;
338
339  // Set by the Post thread to the index of the GPU compositing output
340  // buffer in the layers_ array.
341  Layer* gpu_layer_;
342
343  // Handler to hook vsync events outside of this class.
344  VSyncCallback vsync_callback_;
345
346  // Thread and condition for managing the layer posting thread. This thread
347  // wakes up a short time before vsync to hand buffers to post processing and
348  // the results to hardware composer.
349  std::thread post_thread_;
350
351  // Control variables to control the state of the post thread
352  pdx::LocalHandle terminate_post_thread_event_fd_;
353  bool pause_post_thread_;
354  std::mutex thread_pause_mutex_;
355  std::condition_variable thread_pause_semaphore_;
356
357  // Backlight LED brightness sysfs node.
358  pdx::LocalHandle backlight_brightness_fd_;
359
360  // Primary display vsync event sysfs node.
361  pdx::LocalHandle primary_display_vsync_event_fd_;
362
363  // Primary display wait_pingpong state sysfs node.
364  pdx::LocalHandle primary_display_wait_pp_fd_;
365
366  // VSync sleep timerfd.
367  pdx::LocalHandle vsync_sleep_timer_fd_;
368
369  // The timestamp of the last vsync.
370  int64_t last_vsync_timestamp_;
371
372  // Vsync count since display on.
373  uint32_t vsync_count_;
374
375  // Counter tracking the number of skipped frames.
376  int frame_skip_count_;
377
378  // After construction, only accessed on post_thread_.
379  Compositor compositor_;
380
381  // Fd array for tracking retire fences that are returned by hwc. This allows
382  // us to detect when the display driver begins queuing frames.
383  std::vector<pdx::LocalHandle> retire_fence_fds_;
384
385  // Pose client for frame count notifications. Pose client predicts poses
386  // out to display frame boundaries, so we need to tell it about vsyncs.
387  DvrPose* pose_client_;
388
389  static void HwcRefresh(hwc2_callback_data_t data, hwc2_display_t display);
390  static void HwcVSync(hwc2_callback_data_t data, hwc2_display_t display,
391                       int64_t timestamp);
392  static void HwcHotplug(hwc2_callback_data_t callbackData,
393                         hwc2_display_t display, hwc2_connection_t connected);
394
395  HardwareComposer(const HardwareComposer&) = delete;
396  void operator=(const HardwareComposer&) = delete;
397};
398
399}  // namespace dvr
400}  // namespace android
401
402#endif  // ANDROID_DVR_SERVICES_DISPLAYD_HARDWARE_COMPOSER_H_
403