blob: e2a8b90adb11abd2ca67af7498a9cd241a0c595e [file] [log] [blame]
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001#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
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800192 bool Initialize();
193
194 bool IsInitialized() const { return initialized_; }
195
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800196 bool Suspend();
197 bool Resume();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800198
199 // Get the HMD display metrics for the current display.
200 DisplayMetrics GetHmdDisplayMetrics() const;
201
202 int32_t GetDisplayAttribute(hwc2_display_t display, hwc2_config_t config,
203 hwc2_attribute_t attributes,
204 int32_t* out_value) const;
205 int32_t GetDisplayMetrics(hwc2_display_t display, hwc2_config_t config,
206 HWCDisplayMetrics* out_metrics) const;
207 void Dump(char* buffer, uint32_t* out_size);
208
209 void SetVSyncCallback(VSyncCallback callback);
210
211 // Metrics of the logical display, which is always landscape.
212 int DisplayWidth() const { return display_metrics_.width; }
213 int DisplayHeight() const { return display_metrics_.height; }
214 HWCDisplayMetrics display_metrics() const { return display_metrics_; }
215
216 // Metrics of the native display, which depends on the specific hardware
217 // implementation of the display.
218 HWCDisplayMetrics native_display_metrics() const {
219 return native_display_metrics_;
220 }
221
222 std::shared_ptr<IonBuffer> framebuffer_target() const {
223 return framebuffer_target_;
224 }
225
226 // Set the display surface stack to compose to the display each frame.
227 int SetDisplaySurfaces(std::vector<std::shared_ptr<DisplaySurface>> surfaces);
228
229 Compositor* GetCompositor() { return &compositor_; }
230
Steven Thomas3cfac282017-02-06 12:29:30 -0800231 void OnHardwareComposerRefresh();
232
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800233 private:
234 int32_t EnableVsync(bool enabled);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800235
236 class ComposerCallback : public Hwc2::IComposerCallback {
237 public:
238 ComposerCallback() {}
239
240 hardware::Return<void> onHotplug(Hwc2::Display /*display*/,
241 Connection /*connected*/) override {
242 // TODO(skiazyk): depending on how the server is implemented, we might
243 // have to set it up to synchronize with receiving this event, as it can
244 // potentially be a critical event for setting up state within the
245 // hwc2 module. That is, we (technically) should not call any other hwc
246 // methods until this method has been called after registering the
247 // callbacks.
248 return hardware::Void();
249 }
250
251 hardware::Return<void> onRefresh(Hwc2::Display /*display*/) override {
252 return hardware::Void();
253 }
254
255 hardware::Return<void> onVsync(Hwc2::Display /*display*/,
256 int64_t /*timestamp*/) override {
257 return hardware::Void();
258 }
259 };
260
261 int32_t Validate(hwc2_display_t display);
262 int32_t Present(hwc2_display_t display);
263
264 void SetBacklightBrightness(int brightness);
265
266 void PostLayers(bool is_geometry_changed);
267 void PostThread();
268
269 int ReadWaitPPState();
Steven Thomas282a5ed2017-02-07 18:07:01 -0800270 int BlockUntilVSync(/*out*/ bool* suspend_requested);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800271 int ReadVSyncTimestamp(int64_t* timestamp);
272 int WaitForVSync(int64_t* timestamp);
273 int SleepUntil(int64_t wakeup_timestamp);
274
275 bool IsFramePendingInDriver() { return ReadWaitPPState() == 1; }
276
277 // Returns true if the layer config changed, false otherwise
278 bool UpdateLayerConfig(
279 std::vector<std::shared_ptr<DisplaySurface>>* compositor_surfaces);
280 void PostCompositorBuffers(
281 const std::vector<std::shared_ptr<DisplaySurface>>& compositor_surfaces);
282
283 void UpdateDisplayState();
284
285 struct FrameTimeMeasurementRecord {
286 int64_t start_time;
287 pdx::LocalHandle fence;
288
289 FrameTimeMeasurementRecord(FrameTimeMeasurementRecord&&) = default;
290 FrameTimeMeasurementRecord& operator=(FrameTimeMeasurementRecord&&) =
291 default;
292 FrameTimeMeasurementRecord(const FrameTimeMeasurementRecord&) = delete;
293 FrameTimeMeasurementRecord& operator=(const FrameTimeMeasurementRecord&) =
294 delete;
295 };
296
297 void UpdateFrameTimeHistory(std::vector<FrameTimeMeasurementRecord>* backlog,
298 int backlog_max,
299 FenceInfoBuffer* fence_info_buffer,
300 FrameTimeHistory* history);
301
302 // Returns true if the frame finished rendering, false otherwise. If the frame
303 // finished the frame end time is stored in timestamp. Doesn't block.
304 bool CheckFrameFinished(int frame_fence_fd,
305 FenceInfoBuffer* fence_info_buffer,
306 int64_t* timestamp);
307
308 void HandlePendingScreenshots();
309
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800310 bool initialized_;
311
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800312 // Hardware composer HAL device.
313 std::unique_ptr<Hwc2::Composer> hwc2_hidl_;
314 sp<ComposerCallback> callbacks_;
315
316 // Display metrics of the physical display.
317 HWCDisplayMetrics native_display_metrics_;
318 // Display metrics of the logical display, adjusted so that orientation is
319 // landscape.
320 HWCDisplayMetrics display_metrics_;
321 // Transform required to get from native to logical display orientation.
322 hwc_transform_t display_transform_;
323
324 // Buffer for the background layer required by hardware composer.
325 std::shared_ptr<IonBuffer> framebuffer_target_;
326
327 // Protects access to the display surfaces and logical layers.
328 std::mutex layer_mutex_;
329
330 // Active display surfaces configured by the display manager.
331 std::vector<std::shared_ptr<DisplaySurface>> display_surfaces_;
332 std::vector<std::shared_ptr<DisplaySurface>> added_display_surfaces_;
333 bool display_surfaces_updated_;
334 bool hardware_layers_need_update_;
335
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800336 // Layer array for handling buffer flow into hardware composer layers.
337 // Note that the first array is the actual storage for the layer objects,
338 // and the latter is an array of pointers, which can be freely re-arranged
339 // without messing up the underlying objects.
340 std::array<Layer, kMaxHardwareLayers> layer_storage_;
341 std::array<Layer*, kMaxHardwareLayers> layers_;
342 size_t active_layer_count_;
343
344 // Set by the Post thread to the index of the GPU compositing output
345 // buffer in the layers_ array.
346 Layer* gpu_layer_;
347
348 // Handler to hook vsync events outside of this class.
349 VSyncCallback vsync_callback_;
350
Steven Thomas282a5ed2017-02-07 18:07:01 -0800351 // The layer posting thread. This thread wakes up a short time before vsync to
352 // hand buffers to post processing and the results to hardware composer.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800353 std::thread post_thread_;
354
Steven Thomas282a5ed2017-02-07 18:07:01 -0800355 enum class PostThreadState {
356 // post_thread_state_ starts off paused. When suspending, the control thread
357 // will block until post_thread_state_ == kPaused, indicating the post
358 // thread has completed the transition to paused (most importantly: no more
359 // hardware composer calls).
360 kPaused,
361 // post_thread_state_ is set to kRunning by the control thread (either
362 // surface flinger's main thread or the vr flinger dispatcher thread). The
363 // post thread blocks until post_thread_state_ == kRunning.
364 kRunning,
365 // Set by the control thread to indicate the post thread should pause. The
366 // post thread will change post_thread_state_ from kPauseRequested to
367 // kPaused when it stops.
368 kPauseRequested
369 };
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800370 // Control variables to control the state of the post thread
Steven Thomas282a5ed2017-02-07 18:07:01 -0800371 PostThreadState post_thread_state_;
372 // Used to wake the post thread up while it's waiting for vsync, for faster
373 // transition to the paused state.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800374 pdx::LocalHandle terminate_post_thread_event_fd_;
Steven Thomas282a5ed2017-02-07 18:07:01 -0800375 // post_thread_state_mutex_ should be held before checking or modifying
376 // post_thread_state_.
377 std::mutex post_thread_state_mutex_;
378 // Used to communicate between the control thread and the post thread.
379 std::condition_variable post_thread_state_cond_var_;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800380
381 // Backlight LED brightness sysfs node.
382 pdx::LocalHandle backlight_brightness_fd_;
383
384 // Primary display vsync event sysfs node.
385 pdx::LocalHandle primary_display_vsync_event_fd_;
386
387 // Primary display wait_pingpong state sysfs node.
388 pdx::LocalHandle primary_display_wait_pp_fd_;
389
390 // VSync sleep timerfd.
391 pdx::LocalHandle vsync_sleep_timer_fd_;
392
393 // The timestamp of the last vsync.
394 int64_t last_vsync_timestamp_;
395
396 // Vsync count since display on.
397 uint32_t vsync_count_;
398
399 // Counter tracking the number of skipped frames.
400 int frame_skip_count_;
401
402 // After construction, only accessed on post_thread_.
403 Compositor compositor_;
404
405 // Fd array for tracking retire fences that are returned by hwc. This allows
406 // us to detect when the display driver begins queuing frames.
407 std::vector<pdx::LocalHandle> retire_fence_fds_;
408
409 // Pose client for frame count notifications. Pose client predicts poses
410 // out to display frame boundaries, so we need to tell it about vsyncs.
411 DvrPose* pose_client_;
412
413 static void HwcRefresh(hwc2_callback_data_t data, hwc2_display_t display);
414 static void HwcVSync(hwc2_callback_data_t data, hwc2_display_t display,
415 int64_t timestamp);
416 static void HwcHotplug(hwc2_callback_data_t callbackData,
417 hwc2_display_t display, hwc2_connection_t connected);
418
419 HardwareComposer(const HardwareComposer&) = delete;
420 void operator=(const HardwareComposer&) = delete;
421};
422
423} // namespace dvr
424} // namespace android
425
426#endif // ANDROID_DVR_SERVICES_DISPLAYD_HARDWARE_COMPOSER_H_