blob: 88173cac3e9ec7d96946c89873023e64fe8df3bd [file] [log] [blame]
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001#include "hardware_composer.h"
2
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08003#include <cutils/properties.h>
4#include <cutils/sched_policy.h>
5#include <fcntl.h>
Corey Tabaka2251d822017-04-20 16:04:07 -07006#include <log/log.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08007#include <poll.h>
8#include <sync/sync.h>
9#include <sys/eventfd.h>
10#include <sys/prctl.h>
11#include <sys/resource.h>
12#include <sys/system_properties.h>
13#include <sys/timerfd.h>
Corey Tabaka2251d822017-04-20 16:04:07 -070014#include <time.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080015#include <unistd.h>
16#include <utils/Trace.h>
17
18#include <algorithm>
Corey Tabaka2251d822017-04-20 16:04:07 -070019#include <chrono>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080020#include <functional>
21#include <map>
John Bates954796e2017-05-11 11:00:31 -070022#include <tuple>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080023
Corey Tabaka2251d822017-04-20 16:04:07 -070024#include <dvr/dvr_display_types.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080025#include <dvr/performance_client_api.h>
26#include <private/dvr/clock_ns.h>
Corey Tabaka2251d822017-04-20 16:04:07 -070027#include <private/dvr/ion_buffer.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080028#include <private/dvr/pose_client_internal.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080029
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080030using android::pdx::LocalHandle;
Corey Tabaka2251d822017-04-20 16:04:07 -070031using android::pdx::rpc::EmptyVariant;
32using android::pdx::rpc::IfAnyOf;
33
34using namespace std::chrono_literals;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080035
36namespace android {
37namespace dvr {
38
39namespace {
40
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080041const char kBacklightBrightnessSysFile[] =
42 "/sys/class/leds/lcd-backlight/brightness";
43
44const char kPrimaryDisplayVSyncEventFile[] =
45 "/sys/class/graphics/fb0/vsync_event";
46
47const char kPrimaryDisplayWaitPPEventFile[] = "/sys/class/graphics/fb0/wait_pp";
48
49const char kDvrPerformanceProperty[] = "sys.dvr.performance";
50
Luke Song4b788322017-03-24 14:17:31 -070051const char kRightEyeOffsetProperty[] = "dvr.right_eye_offset_ns";
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080052
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080053// Get time offset from a vsync to when the pose for that vsync should be
54// predicted out to. For example, if scanout gets halfway through the frame
55// at the halfway point between vsyncs, then this could be half the period.
56// With global shutter displays, this should be changed to the offset to when
57// illumination begins. Low persistence adds a frame of latency, so we predict
58// to the center of the next frame.
59inline int64_t GetPosePredictionTimeOffset(int64_t vsync_period_ns) {
60 return (vsync_period_ns * 150) / 100;
61}
62
Corey Tabaka2251d822017-04-20 16:04:07 -070063// Attempts to set the scheduler class and partiton for the current thread.
64// Returns true on success or false on failure.
65bool SetThreadPolicy(const std::string& scheduler_class,
66 const std::string& partition) {
67 int error = dvrSetSchedulerClass(0, scheduler_class.c_str());
68 if (error < 0) {
69 ALOGE(
70 "SetThreadPolicy: Failed to set scheduler class \"%s\" for "
71 "thread_id=%d: %s",
72 scheduler_class.c_str(), gettid(), strerror(-error));
73 return false;
74 }
75 error = dvrSetCpuPartition(0, partition.c_str());
76 if (error < 0) {
77 ALOGE(
78 "SetThreadPolicy: Failed to set cpu partiton \"%s\" for thread_id=%d: "
79 "%s",
80 partition.c_str(), gettid(), strerror(-error));
81 return false;
82 }
83 return true;
84}
85
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080086} // anonymous namespace
87
Corey Tabaka2251d822017-04-20 16:04:07 -070088// Layer static data.
89Hwc2::Composer* Layer::hwc2_hidl_;
90const HWCDisplayMetrics* Layer::display_metrics_;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080091
Corey Tabaka2251d822017-04-20 16:04:07 -070092// HardwareComposer static data;
93constexpr size_t HardwareComposer::kMaxHardwareLayers;
94
95HardwareComposer::HardwareComposer()
96 : HardwareComposer(nullptr, RequestDisplayCallback()) {}
97
98HardwareComposer::HardwareComposer(
99 Hwc2::Composer* hwc2_hidl, RequestDisplayCallback request_display_callback)
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800100 : initialized_(false),
101 hwc2_hidl_(hwc2_hidl),
Corey Tabaka2251d822017-04-20 16:04:07 -0700102 request_display_callback_(request_display_callback),
103 callbacks_(new ComposerCallback) {}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800104
105HardwareComposer::~HardwareComposer(void) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700106 UpdatePostThreadState(PostThreadState::Quit, true);
107 if (post_thread_.joinable())
Steven Thomas050b2c82017-03-06 11:45:16 -0800108 post_thread_.join();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800109}
110
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800111bool HardwareComposer::Initialize() {
112 if (initialized_) {
113 ALOGE("HardwareComposer::Initialize: already initialized.");
114 return false;
115 }
116
Corey Tabaka2251d822017-04-20 16:04:07 -0700117 HWC::Error error = HWC::Error::None;
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800118
119 Hwc2::Config config;
Corey Tabaka2251d822017-04-20 16:04:07 -0700120 error = hwc2_hidl_->getActiveConfig(HWC_DISPLAY_PRIMARY, &config);
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800121
Corey Tabaka2251d822017-04-20 16:04:07 -0700122 if (error != HWC::Error::None) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800123 ALOGE("HardwareComposer: Failed to get current display config : %d",
124 config);
125 return false;
126 }
127
Corey Tabaka2251d822017-04-20 16:04:07 -0700128 error =
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800129 GetDisplayMetrics(HWC_DISPLAY_PRIMARY, config, &native_display_metrics_);
130
Corey Tabaka2251d822017-04-20 16:04:07 -0700131 if (error != HWC::Error::None) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800132 ALOGE(
133 "HardwareComposer: Failed to get display attributes for current "
134 "configuration : %d",
Corey Tabaka2251d822017-04-20 16:04:07 -0700135 error.value);
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800136 return false;
137 }
138
139 ALOGI(
140 "HardwareComposer: primary display attributes: width=%d height=%d "
141 "vsync_period_ns=%d DPI=%dx%d",
142 native_display_metrics_.width, native_display_metrics_.height,
143 native_display_metrics_.vsync_period_ns, native_display_metrics_.dpi.x,
144 native_display_metrics_.dpi.y);
145
146 // Set the display metrics but never use rotation to avoid the long latency of
147 // rotation processing in hwc.
148 display_transform_ = HWC_TRANSFORM_NONE;
149 display_metrics_ = native_display_metrics_;
150
Corey Tabaka2251d822017-04-20 16:04:07 -0700151 // Pass hwc instance and metrics to setup globals for Layer.
152 Layer::InitializeGlobals(hwc2_hidl_, &native_display_metrics_);
153
154 post_thread_event_fd_.Reset(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
Steven Thomas050b2c82017-03-06 11:45:16 -0800155 LOG_ALWAYS_FATAL_IF(
Corey Tabaka2251d822017-04-20 16:04:07 -0700156 !post_thread_event_fd_,
Steven Thomas050b2c82017-03-06 11:45:16 -0800157 "HardwareComposer: Failed to create interrupt event fd : %s",
158 strerror(errno));
159
160 post_thread_ = std::thread(&HardwareComposer::PostThread, this);
161
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800162 initialized_ = true;
163
164 return initialized_;
165}
166
Steven Thomas050b2c82017-03-06 11:45:16 -0800167void HardwareComposer::Enable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700168 UpdatePostThreadState(PostThreadState::Suspended, false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800169}
170
171void HardwareComposer::Disable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700172 UpdatePostThreadState(PostThreadState::Suspended, true);
Steven Thomas050b2c82017-03-06 11:45:16 -0800173}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800174
Corey Tabaka2251d822017-04-20 16:04:07 -0700175// Update the post thread quiescent state based on idle and suspended inputs.
176void HardwareComposer::UpdatePostThreadState(PostThreadStateType state,
177 bool suspend) {
178 std::unique_lock<std::mutex> lock(post_thread_mutex_);
179
180 // Update the votes in the state variable before evaluating the effective
181 // quiescent state. Any bits set in post_thread_state_ indicate that the post
182 // thread should be suspended.
183 if (suspend) {
184 post_thread_state_ |= state;
185 } else {
186 post_thread_state_ &= ~state;
187 }
188
189 const bool quit = post_thread_state_ & PostThreadState::Quit;
190 const bool effective_suspend = post_thread_state_ != PostThreadState::Active;
191 if (quit) {
192 post_thread_quiescent_ = true;
193 eventfd_write(post_thread_event_fd_.Get(), 1);
194 post_thread_wait_.notify_one();
195 } else if (effective_suspend && !post_thread_quiescent_) {
196 post_thread_quiescent_ = true;
197 eventfd_write(post_thread_event_fd_.Get(), 1);
198 } else if (!effective_suspend && post_thread_quiescent_) {
199 post_thread_quiescent_ = false;
200 eventfd_t value;
201 eventfd_read(post_thread_event_fd_.Get(), &value);
202 post_thread_wait_.notify_one();
203 }
204
205 // Wait until the post thread is in the requested state.
206 post_thread_ready_.wait(lock, [this, effective_suspend] {
207 return effective_suspend != post_thread_resumed_;
208 });
Steven Thomas050b2c82017-03-06 11:45:16 -0800209}
Steven Thomas282a5ed2017-02-07 18:07:01 -0800210
Steven Thomas050b2c82017-03-06 11:45:16 -0800211void HardwareComposer::OnPostThreadResumed() {
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700212 hwc2_hidl_->resetCommands();
213
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800214 // Connect to pose service.
215 pose_client_ = dvrPoseCreate();
216 ALOGE_IF(!pose_client_, "HardwareComposer: Failed to create pose client");
217
Corey Tabaka2251d822017-04-20 16:04:07 -0700218 // HIDL HWC seems to have an internal race condition. If we submit a frame too
219 // soon after turning on VSync we don't get any VSync signals. Give poor HWC
220 // implementations a chance to enable VSync before we continue.
221 EnableVsync(false);
222 std::this_thread::sleep_for(100ms);
Steven Thomas050b2c82017-03-06 11:45:16 -0800223 EnableVsync(true);
Corey Tabaka2251d822017-04-20 16:04:07 -0700224 std::this_thread::sleep_for(100ms);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800225
Steven Thomas050b2c82017-03-06 11:45:16 -0800226 // TODO(skiazyk): We need to do something about accessing this directly,
227 // supposedly there is a backlight service on the way.
228 // TODO(steventhomas): When we change the backlight setting, will surface
229 // flinger (or something else) set it back to its original value once we give
230 // control of the display back to surface flinger?
231 SetBacklightBrightness(255);
Steven Thomas282a5ed2017-02-07 18:07:01 -0800232
Steven Thomas050b2c82017-03-06 11:45:16 -0800233 // Trigger target-specific performance mode change.
234 property_set(kDvrPerformanceProperty, "performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800235}
236
Steven Thomas050b2c82017-03-06 11:45:16 -0800237void HardwareComposer::OnPostThreadPaused() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700238 retire_fence_fds_.clear();
Steven Thomas050b2c82017-03-06 11:45:16 -0800239 display_surfaces_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800240
Corey Tabaka2251d822017-04-20 16:04:07 -0700241 for (size_t i = 0; i < kMaxHardwareLayers; ++i) {
242 layers_[i].Reset();
243 }
244 active_layer_count_ = 0;
Steven Thomas050b2c82017-03-06 11:45:16 -0800245
246 if (pose_client_) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800247 dvrPoseDestroy(pose_client_);
Steven Thomas050b2c82017-03-06 11:45:16 -0800248 pose_client_ = nullptr;
249 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800250
Steven Thomas050b2c82017-03-06 11:45:16 -0800251 EnableVsync(false);
252
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700253 hwc2_hidl_->resetCommands();
254
Steven Thomas050b2c82017-03-06 11:45:16 -0800255 // Trigger target-specific performance mode change.
256 property_set(kDvrPerformanceProperty, "idle");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800257}
258
Corey Tabaka2251d822017-04-20 16:04:07 -0700259HWC::Error HardwareComposer::Validate(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800260 uint32_t num_types;
261 uint32_t num_requests;
Corey Tabaka2251d822017-04-20 16:04:07 -0700262 HWC::Error error =
263 hwc2_hidl_->validateDisplay(display, &num_types, &num_requests);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800264
265 if (error == HWC2_ERROR_HAS_CHANGES) {
266 // TODO(skiazyk): We might need to inspect the requested changes first, but
267 // so far it seems like we shouldn't ever hit a bad state.
268 // error = hwc2_funcs_.accept_display_changes_fn_(hardware_composer_device_,
269 // display);
Corey Tabaka2251d822017-04-20 16:04:07 -0700270 error = hwc2_hidl_->acceptDisplayChanges(display);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800271 }
272
273 return error;
274}
275
276int32_t HardwareComposer::EnableVsync(bool enabled) {
277 return (int32_t)hwc2_hidl_->setVsyncEnabled(
278 HWC_DISPLAY_PRIMARY,
279 (Hwc2::IComposerClient::Vsync)(enabled ? HWC2_VSYNC_ENABLE
280 : HWC2_VSYNC_DISABLE));
281}
282
Corey Tabaka2251d822017-04-20 16:04:07 -0700283HWC::Error HardwareComposer::Present(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800284 int32_t present_fence;
Corey Tabaka2251d822017-04-20 16:04:07 -0700285 HWC::Error error = hwc2_hidl_->presentDisplay(display, &present_fence);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800286
287 // According to the documentation, this fence is signaled at the time of
288 // vsync/DMA for physical displays.
Corey Tabaka2251d822017-04-20 16:04:07 -0700289 if (error == HWC::Error::None) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800290 ATRACE_INT("HardwareComposer: VsyncFence", present_fence);
291 retire_fence_fds_.emplace_back(present_fence);
292 } else {
293 ATRACE_INT("HardwareComposer: PresentResult", error);
294 }
295
296 return error;
297}
298
Corey Tabaka2251d822017-04-20 16:04:07 -0700299HWC::Error HardwareComposer::GetDisplayAttribute(hwc2_display_t display,
300 hwc2_config_t config,
301 hwc2_attribute_t attribute,
302 int32_t* out_value) const {
303 return hwc2_hidl_->getDisplayAttribute(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800304 display, config, (Hwc2::IComposerClient::Attribute)attribute, out_value);
305}
306
Corey Tabaka2251d822017-04-20 16:04:07 -0700307HWC::Error HardwareComposer::GetDisplayMetrics(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800308 hwc2_display_t display, hwc2_config_t config,
309 HWCDisplayMetrics* out_metrics) const {
Corey Tabaka2251d822017-04-20 16:04:07 -0700310 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800311
Corey Tabaka2251d822017-04-20 16:04:07 -0700312 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_WIDTH,
313 &out_metrics->width);
314 if (error != HWC::Error::None) {
315 ALOGE(
316 "HardwareComposer::GetDisplayMetrics: Failed to get display width: %s",
317 error.to_string().c_str());
318 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800319 }
320
Corey Tabaka2251d822017-04-20 16:04:07 -0700321 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_HEIGHT,
322 &out_metrics->height);
323 if (error != HWC::Error::None) {
324 ALOGE(
325 "HardwareComposer::GetDisplayMetrics: Failed to get display height: %s",
326 error.to_string().c_str());
327 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800328 }
329
Corey Tabaka2251d822017-04-20 16:04:07 -0700330 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_VSYNC_PERIOD,
331 &out_metrics->vsync_period_ns);
332 if (error != HWC::Error::None) {
333 ALOGE(
334 "HardwareComposer::GetDisplayMetrics: Failed to get display height: %s",
335 error.to_string().c_str());
336 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800337 }
338
Corey Tabaka2251d822017-04-20 16:04:07 -0700339 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_DPI_X,
340 &out_metrics->dpi.x);
341 if (error != HWC::Error::None) {
342 ALOGE(
343 "HardwareComposer::GetDisplayMetrics: Failed to get display DPI X: %s",
344 error.to_string().c_str());
345 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800346 }
347
Corey Tabaka2251d822017-04-20 16:04:07 -0700348 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_DPI_Y,
349 &out_metrics->dpi.y);
350 if (error != HWC::Error::None) {
351 ALOGE(
352 "HardwareComposer::GetDisplayMetrics: Failed to get display DPI Y: %s",
353 error.to_string().c_str());
354 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800355 }
356
Corey Tabaka2251d822017-04-20 16:04:07 -0700357 return HWC::Error::None;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800358}
359
Corey Tabaka2251d822017-04-20 16:04:07 -0700360std::string HardwareComposer::Dump() { return hwc2_hidl_->dumpDebugInfo(); }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800361
Corey Tabaka2251d822017-04-20 16:04:07 -0700362void HardwareComposer::PostLayers() {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800363 ATRACE_NAME("HardwareComposer::PostLayers");
364
365 // Setup the hardware composer layers with current buffers.
366 for (size_t i = 0; i < active_layer_count_; i++) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700367 layers_[i].Prepare();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800368 }
369
Corey Tabaka2251d822017-04-20 16:04:07 -0700370 HWC::Error error = Validate(HWC_DISPLAY_PRIMARY);
371 if (error != HWC::Error::None) {
372 ALOGE("HardwareComposer::PostLayers: Validate failed: %s",
373 error.to_string().c_str());
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700374 return;
375 }
376
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800377 // Now that we have taken in a frame from the application, we have a chance
378 // to drop the frame before passing the frame along to HWC.
379 // If the display driver has become backed up, we detect it here and then
380 // react by skipping this frame to catch up latency.
381 while (!retire_fence_fds_.empty() &&
382 (!retire_fence_fds_.front() ||
383 sync_wait(retire_fence_fds_.front().Get(), 0) == 0)) {
384 // There are only 2 fences in here, no performance problem to shift the
385 // array of ints.
386 retire_fence_fds_.erase(retire_fence_fds_.begin());
387 }
388
389 const bool is_frame_pending = IsFramePendingInDriver();
John Bates954796e2017-05-11 11:00:31 -0700390 const bool is_fence_pending = retire_fence_fds_.size() >
391 post_thread_config_.allowed_pending_fence_count;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800392
393 if (is_fence_pending || is_frame_pending) {
394 ATRACE_INT("frame_skip_count", ++frame_skip_count_);
395
396 ALOGW_IF(is_frame_pending, "Warning: frame already queued, dropping frame");
397 ALOGW_IF(is_fence_pending,
398 "Warning: dropping a frame to catch up with HWC (pending = %zd)",
399 retire_fence_fds_.size());
400
401 for (size_t i = 0; i < active_layer_count_; i++) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700402 layers_[i].Drop();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800403 }
404 return;
405 } else {
406 // Make the transition more obvious in systrace when the frame skip happens
407 // above.
408 ATRACE_INT("frame_skip_count", 0);
409 }
410
411#if TRACE
412 for (size_t i = 0; i < active_layer_count_; i++)
Corey Tabaka2251d822017-04-20 16:04:07 -0700413 ALOGI("HardwareComposer::PostLayers: layer=%zu composition=%s", i,
414 layers_[i].GetCompositionType().to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800415#endif
416
Corey Tabaka2251d822017-04-20 16:04:07 -0700417 error = Present(HWC_DISPLAY_PRIMARY);
418 if (error != HWC::Error::None) {
419 ALOGE("HardwareComposer::PostLayers: Present failed: %s",
420 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800421 return;
422 }
423
424 std::vector<Hwc2::Layer> out_layers;
425 std::vector<int> out_fences;
Corey Tabaka2251d822017-04-20 16:04:07 -0700426 error = hwc2_hidl_->getReleaseFences(HWC_DISPLAY_PRIMARY, &out_layers,
427 &out_fences);
428 ALOGE_IF(error != HWC::Error::None,
429 "HardwareComposer::PostLayers: Failed to get release fences: %s",
430 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800431
432 // Perform post-frame bookkeeping. Unused layers are a no-op.
Corey Tabaka2251d822017-04-20 16:04:07 -0700433 uint32_t num_elements = out_layers.size();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800434 for (size_t i = 0; i < num_elements; ++i) {
435 for (size_t j = 0; j < active_layer_count_; ++j) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700436 if (layers_[j].GetLayerHandle() == out_layers[i]) {
437 layers_[j].Finish(out_fences[i]);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800438 }
439 }
440 }
441}
442
Steven Thomas050b2c82017-03-06 11:45:16 -0800443void HardwareComposer::SetDisplaySurfaces(
Corey Tabaka2251d822017-04-20 16:04:07 -0700444 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces) {
Jin Qian7480c062017-03-21 00:04:15 +0000445 ALOGI("HardwareComposer::SetDisplaySurfaces: surface count=%zd",
446 surfaces.size());
Corey Tabaka2251d822017-04-20 16:04:07 -0700447 const bool display_idle = surfaces.size() == 0;
448 {
449 std::unique_lock<std::mutex> lock(post_thread_mutex_);
450 pending_surfaces_ = std::move(surfaces);
451 }
452
453 // Set idle state based on whether there are any surfaces to handle.
454 UpdatePostThreadState(PostThreadState::Idle, display_idle);
455
456 // XXX: TEMPORARY
457 // Request control of the display based on whether there are any surfaces to
458 // handle. This callback sets the post thread active state once the transition
459 // is complete in SurfaceFlinger.
460 // TODO(eieio): Unify the control signal used to move SurfaceFlinger into VR
461 // mode. Currently this is hooked up to persistent VR mode, but perhaps this
462 // makes more sense to control it from VrCore, which could in turn base its
463 // decision on persistent VR mode.
464 if (request_display_callback_)
465 request_display_callback_(!display_idle);
Steven Thomas050b2c82017-03-06 11:45:16 -0800466}
Jin Qian7480c062017-03-21 00:04:15 +0000467
John Bates954796e2017-05-11 11:00:31 -0700468int HardwareComposer::OnNewGlobalBuffer(DvrGlobalBufferKey key,
469 IonBuffer& ion_buffer) {
470 if (key == kVrFlingerConfigBufferKey) {
471 return MapConfigBuffer(ion_buffer);
472 }
473
474 return 0;
475}
476
477void HardwareComposer::OnDeletedGlobalBuffer(DvrGlobalBufferKey key) {
478 if (key == kVrFlingerConfigBufferKey) {
479 ConfigBufferDeleted();
480 }
481}
482
483int HardwareComposer::MapConfigBuffer(IonBuffer& ion_buffer) {
484 std::lock_guard<std::mutex> lock(shared_config_mutex_);
485 shared_config_ring_ = DvrVrFlingerConfigRing();
486
487 if (ion_buffer.width() < DvrVrFlingerConfigRing::MemorySize()) {
488 ALOGE("HardwareComposer::MapConfigBuffer: invalid buffer size.");
489 return -EINVAL;
490 }
491
492 void* buffer_base = 0;
493 int result = ion_buffer.Lock(ion_buffer.usage(), 0, 0, ion_buffer.width(),
494 ion_buffer.height(), &buffer_base);
495 if (result != 0) {
496 ALOGE("HardwareComposer::MapConfigBuffer: Failed to map vrflinger config "
497 "buffer.");
498 return -EPERM;
499 }
500
501 shared_config_ring_ =
502 DvrVrFlingerConfigRing::Create(buffer_base, ion_buffer.width());
503 ion_buffer.Unlock();
504
505 return 0;
506}
507
508void HardwareComposer::ConfigBufferDeleted() {
509 std::lock_guard<std::mutex> lock(shared_config_mutex_);
510 shared_config_ring_ = DvrVrFlingerConfigRing();
511}
512
513void HardwareComposer::UpdateConfigBuffer() {
514 std::lock_guard<std::mutex> lock(shared_config_mutex_);
515 if (!shared_config_ring_.is_valid())
516 return;
517 // Copy from latest record in shared_config_ring_ to local copy.
518 DvrVrFlingerConfigBuffer record;
519 if (shared_config_ring_.GetNewest(&shared_config_ring_sequence_, &record)) {
520 post_thread_config_ = record;
521 }
522}
523
Corey Tabaka2251d822017-04-20 16:04:07 -0700524int HardwareComposer::PostThreadPollInterruptible(
525 const pdx::LocalHandle& event_fd, int requested_events) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800526 pollfd pfd[2] = {
527 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700528 .fd = event_fd.Get(),
Steven Thomas66747c12017-03-22 18:45:31 -0700529 .events = static_cast<short>(requested_events),
530 .revents = 0,
Steven Thomas050b2c82017-03-06 11:45:16 -0800531 },
532 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700533 .fd = post_thread_event_fd_.Get(),
Steven Thomas050b2c82017-03-06 11:45:16 -0800534 .events = POLLPRI | POLLIN,
535 .revents = 0,
536 },
537 };
538 int ret, error;
539 do {
540 ret = poll(pfd, 2, -1);
541 error = errno;
542 ALOGW_IF(ret < 0,
543 "HardwareComposer::PostThreadPollInterruptible: Error during "
544 "poll(): %s (%d)",
545 strerror(error), error);
546 } while (ret < 0 && error == EINTR);
547
548 if (ret < 0) {
549 return -error;
550 } else if (pfd[0].revents != 0) {
551 return 0;
552 } else if (pfd[1].revents != 0) {
553 ALOGI("VrHwcPost thread interrupted");
554 return kPostThreadInterrupted;
555 } else {
556 return 0;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800557 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800558}
559
560// Reads the value of the display driver wait_pingpong state. Returns 0 or 1
561// (the value of the state) on success or a negative error otherwise.
562// TODO(eieio): This is pretty driver specific, this should be moved to a
563// separate class eventually.
564int HardwareComposer::ReadWaitPPState() {
565 // Gracefully handle when the kernel does not support this feature.
566 if (!primary_display_wait_pp_fd_)
567 return 0;
568
569 const int wait_pp_fd = primary_display_wait_pp_fd_.Get();
570 int ret, error;
571
572 ret = lseek(wait_pp_fd, 0, SEEK_SET);
573 if (ret < 0) {
574 error = errno;
575 ALOGE("HardwareComposer::ReadWaitPPState: Failed to seek wait_pp fd: %s",
576 strerror(error));
577 return -error;
578 }
579
580 char data = -1;
581 ret = read(wait_pp_fd, &data, sizeof(data));
582 if (ret < 0) {
583 error = errno;
584 ALOGE("HardwareComposer::ReadWaitPPState: Failed to read wait_pp state: %s",
585 strerror(error));
586 return -error;
587 }
588
589 switch (data) {
590 case '0':
591 return 0;
592 case '1':
593 return 1;
594 default:
595 ALOGE(
596 "HardwareComposer::ReadWaitPPState: Unexpected value for wait_pp: %d",
597 data);
598 return -EINVAL;
599 }
600}
601
602// Reads the timestamp of the last vsync from the display driver.
603// TODO(eieio): This is pretty driver specific, this should be moved to a
604// separate class eventually.
605int HardwareComposer::ReadVSyncTimestamp(int64_t* timestamp) {
606 const int event_fd = primary_display_vsync_event_fd_.Get();
607 int ret, error;
608
609 // The driver returns data in the form "VSYNC=<timestamp ns>".
610 std::array<char, 32> data;
611 data.fill('\0');
612
613 // Seek back to the beginning of the event file.
614 ret = lseek(event_fd, 0, SEEK_SET);
615 if (ret < 0) {
616 error = errno;
617 ALOGE(
618 "HardwareComposer::ReadVSyncTimestamp: Failed to seek vsync event fd: "
619 "%s",
620 strerror(error));
621 return -error;
622 }
623
624 // Read the vsync event timestamp.
625 ret = read(event_fd, data.data(), data.size());
626 if (ret < 0) {
627 error = errno;
628 ALOGE_IF(
629 error != EAGAIN,
630 "HardwareComposer::ReadVSyncTimestamp: Error while reading timestamp: "
631 "%s",
632 strerror(error));
633 return -error;
634 }
635
636 ret = sscanf(data.data(), "VSYNC=%" PRIu64,
637 reinterpret_cast<uint64_t*>(timestamp));
638 if (ret < 0) {
639 error = errno;
640 ALOGE(
641 "HardwareComposer::ReadVSyncTimestamp: Error while parsing timestamp: "
642 "%s",
643 strerror(error));
644 return -error;
645 }
646
647 return 0;
648}
649
650// Blocks until the next vsync event is signaled by the display driver.
651// TODO(eieio): This is pretty driver specific, this should be moved to a
652// separate class eventually.
Steven Thomas050b2c82017-03-06 11:45:16 -0800653int HardwareComposer::BlockUntilVSync() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700654 // Vsync is signaled by POLLPRI on the fb vsync node.
655 return PostThreadPollInterruptible(primary_display_vsync_event_fd_, POLLPRI);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800656}
657
658// Waits for the next vsync and returns the timestamp of the vsync event. If
659// vsync already passed since the last call, returns the latest vsync timestamp
660// instead of blocking. This method updates the last_vsync_timeout_ in the
661// process.
662//
663// TODO(eieio): This is pretty driver specific, this should be moved to a
664// separate class eventually.
665int HardwareComposer::WaitForVSync(int64_t* timestamp) {
666 int error;
667
668 // Get the current timestamp and decide what to do.
669 while (true) {
670 int64_t current_vsync_timestamp;
671 error = ReadVSyncTimestamp(&current_vsync_timestamp);
672 if (error < 0 && error != -EAGAIN)
673 return error;
674
675 if (error == -EAGAIN) {
676 // Vsync was turned off, wait for the next vsync event.
Steven Thomas050b2c82017-03-06 11:45:16 -0800677 error = BlockUntilVSync();
678 if (error < 0 || error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800679 return error;
680
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800681 // Try again to get the timestamp for this new vsync interval.
682 continue;
683 }
684
685 // Check that we advanced to a later vsync interval.
686 if (TimestampGT(current_vsync_timestamp, last_vsync_timestamp_)) {
687 *timestamp = last_vsync_timestamp_ = current_vsync_timestamp;
688 return 0;
689 }
690
691 // See how close we are to the next expected vsync. If we're within 1ms,
692 // sleep for 1ms and try again.
693 const int64_t ns_per_frame = display_metrics_.vsync_period_ns;
Corey Tabaka2251d822017-04-20 16:04:07 -0700694 const int64_t threshold_ns = 1000000; // 1ms
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800695
696 const int64_t next_vsync_est = last_vsync_timestamp_ + ns_per_frame;
697 const int64_t distance_to_vsync_est = next_vsync_est - GetSystemClockNs();
698
699 if (distance_to_vsync_est > threshold_ns) {
700 // Wait for vsync event notification.
Steven Thomas050b2c82017-03-06 11:45:16 -0800701 error = BlockUntilVSync();
702 if (error < 0 || error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800703 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800704 } else {
Steven Thomas050b2c82017-03-06 11:45:16 -0800705 // Sleep for a short time (1 millisecond) before retrying.
Corey Tabaka2251d822017-04-20 16:04:07 -0700706 error = SleepUntil(GetSystemClockNs() + threshold_ns);
Steven Thomas050b2c82017-03-06 11:45:16 -0800707 if (error < 0 || error == kPostThreadInterrupted)
708 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800709 }
710 }
711}
712
713int HardwareComposer::SleepUntil(int64_t wakeup_timestamp) {
714 const int timer_fd = vsync_sleep_timer_fd_.Get();
715 const itimerspec wakeup_itimerspec = {
716 .it_interval = {.tv_sec = 0, .tv_nsec = 0},
717 .it_value = NsToTimespec(wakeup_timestamp),
718 };
719 int ret =
720 timerfd_settime(timer_fd, TFD_TIMER_ABSTIME, &wakeup_itimerspec, nullptr);
721 int error = errno;
722 if (ret < 0) {
723 ALOGE("HardwareComposer::SleepUntil: Failed to set timerfd: %s",
724 strerror(error));
725 return -error;
726 }
727
Corey Tabaka2251d822017-04-20 16:04:07 -0700728 return PostThreadPollInterruptible(vsync_sleep_timer_fd_, POLLIN);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800729}
730
731void HardwareComposer::PostThread() {
732 // NOLINTNEXTLINE(runtime/int)
Steven Thomas050b2c82017-03-06 11:45:16 -0800733 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>("VrHwcPost"), 0, 0, 0);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800734
Corey Tabaka2251d822017-04-20 16:04:07 -0700735 // Set the scheduler to SCHED_FIFO with high priority. If this fails here
736 // there may have been a startup timing issue between this thread and
737 // performanced. Try again later when this thread becomes active.
738 bool thread_policy_setup =
739 SetThreadPolicy("graphics:high", "/system/performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800740
Steven Thomas050b2c82017-03-06 11:45:16 -0800741#if ENABLE_BACKLIGHT_BRIGHTNESS
742 // TODO(hendrikw): This isn't required at the moment. It's possible that there
743 // is another method to access this when needed.
744 // Open the backlight brightness control sysfs node.
745 backlight_brightness_fd_ = LocalHandle(kBacklightBrightnessSysFile, O_RDWR);
746 ALOGW_IF(!backlight_brightness_fd_,
747 "HardwareComposer: Failed to open backlight brightness control: %s",
748 strerror(errno));
Corey Tabaka2251d822017-04-20 16:04:07 -0700749#endif // ENABLE_BACKLIGHT_BRIGHTNESS
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800750
Steven Thomas050b2c82017-03-06 11:45:16 -0800751 // Open the vsync event node for the primary display.
752 // TODO(eieio): Move this into a platform-specific class.
753 primary_display_vsync_event_fd_ =
754 LocalHandle(kPrimaryDisplayVSyncEventFile, O_RDONLY);
755 ALOGE_IF(!primary_display_vsync_event_fd_,
756 "HardwareComposer: Failed to open vsync event node for primary "
757 "display: %s",
758 strerror(errno));
759
760 // Open the wait pingpong status node for the primary display.
761 // TODO(eieio): Move this into a platform-specific class.
762 primary_display_wait_pp_fd_ =
763 LocalHandle(kPrimaryDisplayWaitPPEventFile, O_RDONLY);
764 ALOGW_IF(
765 !primary_display_wait_pp_fd_,
766 "HardwareComposer: Failed to open wait_pp node for primary display: %s",
767 strerror(errno));
768
769 // Create a timerfd based on CLOCK_MONOTINIC.
770 vsync_sleep_timer_fd_.Reset(timerfd_create(CLOCK_MONOTONIC, 0));
771 LOG_ALWAYS_FATAL_IF(
772 !vsync_sleep_timer_fd_,
773 "HardwareComposer: Failed to create vsync sleep timerfd: %s",
774 strerror(errno));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800775
776 const int64_t ns_per_frame = display_metrics_.vsync_period_ns;
777 const int64_t photon_offset_ns = GetPosePredictionTimeOffset(ns_per_frame);
778
779 // TODO(jbates) Query vblank time from device, when such an API is available.
780 // This value (6.3%) was measured on A00 in low persistence mode.
781 int64_t vblank_ns = ns_per_frame * 63 / 1000;
782 int64_t right_eye_photon_offset_ns = (ns_per_frame - vblank_ns) / 2;
783
784 // Check property for overriding right eye offset value.
785 right_eye_photon_offset_ns =
786 property_get_int64(kRightEyeOffsetProperty, right_eye_photon_offset_ns);
787
Steven Thomas050b2c82017-03-06 11:45:16 -0800788 bool was_running = false;
789
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800790 while (1) {
791 ATRACE_NAME("HardwareComposer::PostThread");
792
John Bates954796e2017-05-11 11:00:31 -0700793 // Check for updated config once per vsync.
794 UpdateConfigBuffer();
795
Corey Tabaka2251d822017-04-20 16:04:07 -0700796 while (post_thread_quiescent_) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800797 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Corey Tabaka2251d822017-04-20 16:04:07 -0700798 ALOGI("HardwareComposer::PostThread: Entering quiescent state.");
799
800 // Tear down resources.
801 OnPostThreadPaused();
802
803 was_running = false;
804 post_thread_resumed_ = false;
805 post_thread_ready_.notify_all();
806
807 if (post_thread_state_ & PostThreadState::Quit) {
808 ALOGI("HardwareComposer::PostThread: Quitting.");
809 return;
Steven Thomas282a5ed2017-02-07 18:07:01 -0800810 }
Corey Tabaka2251d822017-04-20 16:04:07 -0700811
812 post_thread_wait_.wait(lock, [this] { return !post_thread_quiescent_; });
813
814 post_thread_resumed_ = true;
815 post_thread_ready_.notify_all();
816
817 ALOGI("HardwareComposer::PostThread: Exiting quiescent state.");
Steven Thomas050b2c82017-03-06 11:45:16 -0800818 }
819
820 if (!was_running) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700821 // Setup resources.
Steven Thomas050b2c82017-03-06 11:45:16 -0800822 OnPostThreadResumed();
823 was_running = true;
Corey Tabaka2251d822017-04-20 16:04:07 -0700824
825 // Try to setup the scheduler policy if it failed during startup. Only
826 // attempt to do this on transitions from inactive to active to avoid
827 // spamming the system with RPCs and log messages.
828 if (!thread_policy_setup) {
829 thread_policy_setup =
830 SetThreadPolicy("graphics:high", "/system/performance");
831 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800832 }
833
834 int64_t vsync_timestamp = 0;
835 {
836 std::array<char, 128> buf;
837 snprintf(buf.data(), buf.size(), "wait_vsync|vsync=%d|",
838 vsync_count_ + 1);
839 ATRACE_NAME(buf.data());
840
Corey Tabaka2251d822017-04-20 16:04:07 -0700841 const int error = WaitForVSync(&vsync_timestamp);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800842 ALOGE_IF(
843 error < 0,
844 "HardwareComposer::PostThread: Failed to wait for vsync event: %s",
845 strerror(-error));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800846 // Don't bother processing this frame if a pause was requested
Steven Thomas050b2c82017-03-06 11:45:16 -0800847 if (error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800848 continue;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800849 }
850
851 ++vsync_count_;
852
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800853 if (pose_client_) {
854 // Signal the pose service with vsync info.
855 // Display timestamp is in the middle of scanout.
856 privateDvrPoseNotifyVsync(pose_client_, vsync_count_,
857 vsync_timestamp + photon_offset_ns,
858 ns_per_frame, right_eye_photon_offset_ns);
859 }
860
Corey Tabaka2251d822017-04-20 16:04:07 -0700861 const bool layer_config_changed = UpdateLayerConfig();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800862
863 // Signal all of the vsync clients. Because absolute time is used for the
864 // wakeup time below, this can take a little time if necessary.
865 if (vsync_callback_)
Corey Tabaka2251d822017-04-20 16:04:07 -0700866 vsync_callback_(HWC_DISPLAY_PRIMARY, vsync_timestamp,
867 /*frame_time_estimate*/ 0, vsync_count_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800868
869 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700870 // Sleep until shortly before vsync.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800871 ATRACE_NAME("sleep");
872
Corey Tabaka2251d822017-04-20 16:04:07 -0700873 const int64_t display_time_est_ns = vsync_timestamp + ns_per_frame;
874 const int64_t now_ns = GetSystemClockNs();
John Bates954796e2017-05-11 11:00:31 -0700875 const int64_t sleep_time_ns = display_time_est_ns - now_ns -
876 post_thread_config_.frame_post_offset_ns;
877 const int64_t wakeup_time_ns =
878 display_time_est_ns - post_thread_config_.frame_post_offset_ns;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800879
880 ATRACE_INT64("sleep_time_ns", sleep_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800881 if (sleep_time_ns > 0) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700882 int error = SleepUntil(wakeup_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800883 ALOGE_IF(error < 0, "HardwareComposer::PostThread: Failed to sleep: %s",
884 strerror(-error));
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700885 if (error == kPostThreadInterrupted) {
886 if (layer_config_changed) {
887 // If the layer config changed we need to validateDisplay() even if
888 // we're going to drop the frame, to flush the Composer object's
889 // internal command buffer and apply our layer changes.
890 Validate(HWC_DISPLAY_PRIMARY);
891 }
Steven Thomas050b2c82017-03-06 11:45:16 -0800892 continue;
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700893 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800894 }
895 }
896
Corey Tabaka2251d822017-04-20 16:04:07 -0700897 PostLayers();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800898 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800899}
900
Corey Tabaka2251d822017-04-20 16:04:07 -0700901// Checks for changes in the surface stack and updates the layer config to
902// accomodate the new stack.
Steven Thomas050b2c82017-03-06 11:45:16 -0800903bool HardwareComposer::UpdateLayerConfig() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700904 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces;
Steven Thomas050b2c82017-03-06 11:45:16 -0800905 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700906 std::unique_lock<std::mutex> lock(post_thread_mutex_);
907 if (pending_surfaces_.empty())
Steven Thomas050b2c82017-03-06 11:45:16 -0800908 return false;
Corey Tabaka2251d822017-04-20 16:04:07 -0700909
910 surfaces = std::move(pending_surfaces_);
Steven Thomas050b2c82017-03-06 11:45:16 -0800911 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800912
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800913 ATRACE_NAME("UpdateLayerConfig_HwLayers");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800914
Corey Tabaka2251d822017-04-20 16:04:07 -0700915 display_surfaces_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800916
Corey Tabaka2251d822017-04-20 16:04:07 -0700917 Layer* target_layer;
918 size_t layer_index;
919 for (layer_index = 0;
920 layer_index < std::min(surfaces.size(), kMaxHardwareLayers);
921 layer_index++) {
922 // The bottom layer is opaque, other layers blend.
923 HWC::BlendMode blending =
924 layer_index == 0 ? HWC::BlendMode::None : HWC::BlendMode::Coverage;
925 layers_[layer_index].Setup(surfaces[layer_index], blending,
926 display_transform_, HWC::Composition::Device,
927 layer_index);
928 display_surfaces_.push_back(surfaces[layer_index]);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800929 }
930
Corey Tabaka2251d822017-04-20 16:04:07 -0700931 // Clear unused layers.
932 for (size_t i = layer_index; i < kMaxHardwareLayers; i++)
933 layers_[i].Reset();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800934
Corey Tabaka2251d822017-04-20 16:04:07 -0700935 active_layer_count_ = layer_index;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800936 ALOGD_IF(TRACE, "HardwareComposer::UpdateLayerConfig: %zd active layers",
937 active_layer_count_);
938
Corey Tabaka2251d822017-04-20 16:04:07 -0700939 // Any surfaces left over could not be assigned a hardware layer and will
940 // not be displayed.
941 ALOGW_IF(surfaces.size() != display_surfaces_.size(),
942 "HardwareComposer::UpdateLayerConfig: More surfaces than layers: "
943 "pending_surfaces=%zu display_surfaces=%zu",
944 surfaces.size(), display_surfaces_.size());
945
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800946 return true;
947}
948
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800949void HardwareComposer::SetVSyncCallback(VSyncCallback callback) {
950 vsync_callback_ = callback;
951}
952
953void HardwareComposer::HwcRefresh(hwc2_callback_data_t /*data*/,
954 hwc2_display_t /*display*/) {
955 // TODO(eieio): implement invalidate callbacks.
956}
957
958void HardwareComposer::HwcVSync(hwc2_callback_data_t /*data*/,
959 hwc2_display_t /*display*/,
960 int64_t /*timestamp*/) {
961 ATRACE_NAME(__PRETTY_FUNCTION__);
962 // Intentionally empty. HWC may require a callback to be set to enable vsync
963 // signals. We bypass this callback thread by monitoring the vsync event
964 // directly, but signals still need to be enabled.
965}
966
967void HardwareComposer::HwcHotplug(hwc2_callback_data_t /*callbackData*/,
968 hwc2_display_t /*display*/,
969 hwc2_connection_t /*connected*/) {
970 // TODO(eieio): implement display hotplug callbacks.
971}
972
Steven Thomas3cfac282017-02-06 12:29:30 -0800973void HardwareComposer::OnHardwareComposerRefresh() {
974 // TODO(steventhomas): Handle refresh.
975}
976
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800977void HardwareComposer::SetBacklightBrightness(int brightness) {
978 if (backlight_brightness_fd_) {
979 std::array<char, 32> text;
980 const int length = snprintf(text.data(), text.size(), "%d", brightness);
981 write(backlight_brightness_fd_.Get(), text.data(), length);
982 }
983}
984
Corey Tabaka2251d822017-04-20 16:04:07 -0700985void Layer::InitializeGlobals(Hwc2::Composer* hwc2_hidl,
986 const HWCDisplayMetrics* metrics) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800987 hwc2_hidl_ = hwc2_hidl;
988 display_metrics_ = metrics;
989}
990
991void Layer::Reset() {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800992 if (hwc2_hidl_ != nullptr && hardware_composer_layer_) {
993 hwc2_hidl_->destroyLayer(HWC_DISPLAY_PRIMARY, hardware_composer_layer_);
994 hardware_composer_layer_ = 0;
995 }
996
Corey Tabaka2251d822017-04-20 16:04:07 -0700997 z_order_ = 0;
998 blending_ = HWC::BlendMode::None;
999 transform_ = HWC::Transform::None;
1000 composition_type_ = HWC::Composition::Invalid;
1001 target_composition_type_ = composition_type_;
1002 source_ = EmptyVariant{};
1003 acquire_fence_.Close();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001004 surface_rect_functions_applied_ = false;
1005}
1006
Corey Tabaka2251d822017-04-20 16:04:07 -07001007void Layer::Setup(const std::shared_ptr<DirectDisplaySurface>& surface,
1008 HWC::BlendMode blending, HWC::Transform transform,
1009 HWC::Composition composition_type, size_t z_order) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001010 Reset();
Corey Tabaka2251d822017-04-20 16:04:07 -07001011 z_order_ = z_order;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001012 blending_ = blending;
1013 transform_ = transform;
Corey Tabaka2251d822017-04-20 16:04:07 -07001014 composition_type_ = HWC::Composition::Invalid;
1015 target_composition_type_ = composition_type;
1016 source_ = SourceSurface{surface};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001017 CommonLayerSetup();
1018}
1019
1020void Layer::Setup(const std::shared_ptr<IonBuffer>& buffer,
Corey Tabaka2251d822017-04-20 16:04:07 -07001021 HWC::BlendMode blending, HWC::Transform transform,
1022 HWC::Composition composition_type, size_t z_order) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001023 Reset();
Corey Tabaka2251d822017-04-20 16:04:07 -07001024 z_order_ = z_order;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001025 blending_ = blending;
1026 transform_ = transform;
Corey Tabaka2251d822017-04-20 16:04:07 -07001027 composition_type_ = HWC::Composition::Invalid;
1028 target_composition_type_ = composition_type;
1029 source_ = SourceBuffer{buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001030 CommonLayerSetup();
1031}
1032
Corey Tabaka2251d822017-04-20 16:04:07 -07001033void Layer::UpdateBuffer(const std::shared_ptr<IonBuffer>& buffer) {
1034 if (source_.is<SourceBuffer>())
1035 std::get<SourceBuffer>(source_) = {buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001036}
1037
Corey Tabaka2251d822017-04-20 16:04:07 -07001038void Layer::SetBlending(HWC::BlendMode blending) { blending_ = blending; }
1039void Layer::SetZOrder(size_t z_order) { z_order_ = z_order; }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001040
1041IonBuffer* Layer::GetBuffer() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001042 struct Visitor {
1043 IonBuffer* operator()(SourceSurface& source) { return source.GetBuffer(); }
1044 IonBuffer* operator()(SourceBuffer& source) { return source.GetBuffer(); }
1045 IonBuffer* operator()(EmptyVariant) { return nullptr; }
1046 };
1047 return source_.Visit(Visitor{});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001048}
1049
1050void Layer::UpdateLayerSettings() {
1051 if (!IsLayerSetup()) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001052 ALOGE(
1053 "HardwareComposer::Layer::UpdateLayerSettings: Attempt to update "
1054 "unused Layer!");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001055 return;
1056 }
1057
Corey Tabaka2251d822017-04-20 16:04:07 -07001058 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001059 hwc2_display_t display = HWC_DISPLAY_PRIMARY;
1060
Corey Tabaka2251d822017-04-20 16:04:07 -07001061 error = hwc2_hidl_->setLayerCompositionType(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001062 display, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001063 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1064 ALOGE_IF(
1065 error != HWC::Error::None,
1066 "Layer::UpdateLayerSettings: Error setting layer composition type: %s",
1067 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001068
Corey Tabaka2251d822017-04-20 16:04:07 -07001069 error = hwc2_hidl_->setLayerBlendMode(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001070 display, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001071 blending_.cast<Hwc2::IComposerClient::BlendMode>());
1072 ALOGE_IF(error != HWC::Error::None,
1073 "Layer::UpdateLayerSettings: Error setting layer blend mode: %s",
1074 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001075
Corey Tabaka2251d822017-04-20 16:04:07 -07001076 // TODO(eieio): Use surface attributes or some other mechanism to control
1077 // the layer display frame.
1078 error = hwc2_hidl_->setLayerDisplayFrame(
1079 display, hardware_composer_layer_,
1080 {0, 0, display_metrics_->width, display_metrics_->height});
1081 ALOGE_IF(error != HWC::Error::None,
1082 "Layer::UpdateLayerSettings: Error setting layer display frame: %s",
1083 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001084
Corey Tabaka2251d822017-04-20 16:04:07 -07001085 error = hwc2_hidl_->setLayerVisibleRegion(
1086 display, hardware_composer_layer_,
1087 {{0, 0, display_metrics_->width, display_metrics_->height}});
1088 ALOGE_IF(error != HWC::Error::None,
1089 "Layer::UpdateLayerSettings: Error setting layer visible region: %s",
1090 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001091
Corey Tabaka2251d822017-04-20 16:04:07 -07001092 error =
1093 hwc2_hidl_->setLayerPlaneAlpha(display, hardware_composer_layer_, 1.0f);
1094 ALOGE_IF(error != HWC::Error::None,
1095 "Layer::UpdateLayerSettings: Error setting layer plane alpha: %s",
1096 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001097
Corey Tabaka2251d822017-04-20 16:04:07 -07001098 error =
1099 hwc2_hidl_->setLayerZOrder(display, hardware_composer_layer_, z_order_);
1100 ALOGE_IF(error != HWC::Error::None,
1101 "Layer::UpdateLayerSettings: Error setting z_ order: %s",
1102 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001103}
1104
1105void Layer::CommonLayerSetup() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001106 HWC::Error error =
1107 hwc2_hidl_->createLayer(HWC_DISPLAY_PRIMARY, &hardware_composer_layer_);
1108 ALOGE_IF(
1109 error != HWC::Error::None,
1110 "Layer::CommonLayerSetup: Failed to create layer on primary display: %s",
1111 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001112 UpdateLayerSettings();
1113}
1114
1115void Layer::Prepare() {
1116 int right, bottom;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -04001117 sp<GraphicBuffer> handle;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001118
Corey Tabaka2251d822017-04-20 16:04:07 -07001119 // Acquire the next buffer according to the type of source.
1120 IfAnyOf<SourceSurface, SourceBuffer>::Call(&source_, [&](auto& source) {
1121 std::tie(right, bottom, handle, acquire_fence_) = source.Acquire();
1122 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001123
Corey Tabaka2251d822017-04-20 16:04:07 -07001124 // When a layer is first setup there may be some time before the first buffer
1125 // arrives. Setup the HWC layer as a solid color to stall for time until the
1126 // first buffer arrives. Once the first buffer arrives there will always be a
1127 // buffer for the frame even if it is old.
1128 if (!handle.get()) {
1129 if (composition_type_ == HWC::Composition::Invalid) {
1130 composition_type_ = HWC::Composition::SolidColor;
1131 hwc2_hidl_->setLayerCompositionType(
1132 HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1133 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1134 Hwc2::IComposerClient::Color layer_color = {0, 0, 0, 0};
1135 hwc2_hidl_->setLayerColor(HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1136 layer_color);
1137 } else {
1138 // The composition type is already set. Nothing else to do until a
1139 // buffer arrives.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001140 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001141 } else {
Corey Tabaka2251d822017-04-20 16:04:07 -07001142 if (composition_type_ != target_composition_type_) {
1143 composition_type_ = target_composition_type_;
1144 hwc2_hidl_->setLayerCompositionType(
1145 HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1146 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1147 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001148
Corey Tabaka2251d822017-04-20 16:04:07 -07001149 HWC::Error error{HWC::Error::None};
1150 error = hwc2_hidl_->setLayerBuffer(HWC_DISPLAY_PRIMARY,
1151 hardware_composer_layer_, 0, handle,
1152 acquire_fence_.Get());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001153
Corey Tabaka2251d822017-04-20 16:04:07 -07001154 ALOGE_IF(error != HWC::Error::None,
1155 "Layer::Prepare: Error setting layer buffer: %s",
1156 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001157
Corey Tabaka2251d822017-04-20 16:04:07 -07001158 if (!surface_rect_functions_applied_) {
1159 const float float_right = right;
1160 const float float_bottom = bottom;
1161 error = hwc2_hidl_->setLayerSourceCrop(HWC_DISPLAY_PRIMARY,
1162 hardware_composer_layer_,
1163 {0, 0, float_right, float_bottom});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001164
Corey Tabaka2251d822017-04-20 16:04:07 -07001165 ALOGE_IF(error != HWC::Error::None,
1166 "Layer::Prepare: Error setting layer source crop: %s",
1167 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001168
Corey Tabaka2251d822017-04-20 16:04:07 -07001169 surface_rect_functions_applied_ = true;
1170 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001171 }
1172}
1173
1174void Layer::Finish(int release_fence_fd) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001175 IfAnyOf<SourceSurface, SourceBuffer>::Call(
1176 &source_, [release_fence_fd](auto& source) {
1177 source.Finish(LocalHandle(release_fence_fd));
1178 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001179}
1180
Corey Tabaka2251d822017-04-20 16:04:07 -07001181void Layer::Drop() { acquire_fence_.Close(); }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001182
1183} // namespace dvr
1184} // namespace android