blob: c18ae82c8f107943b0689b5473609fe0f4361e0e [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
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080029using android::pdx::LocalHandle;
Corey Tabaka2251d822017-04-20 16:04:07 -070030using android::pdx::rpc::EmptyVariant;
31using android::pdx::rpc::IfAnyOf;
32
33using namespace std::chrono_literals;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080034
35namespace android {
36namespace dvr {
37
38namespace {
39
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080040const char kBacklightBrightnessSysFile[] =
41 "/sys/class/leds/lcd-backlight/brightness";
42
43const char kPrimaryDisplayVSyncEventFile[] =
44 "/sys/class/graphics/fb0/vsync_event";
45
46const char kPrimaryDisplayWaitPPEventFile[] = "/sys/class/graphics/fb0/wait_pp";
47
48const char kDvrPerformanceProperty[] = "sys.dvr.performance";
49
Luke Song4b788322017-03-24 14:17:31 -070050const char kRightEyeOffsetProperty[] = "dvr.right_eye_offset_ns";
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080051
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080052// Get time offset from a vsync to when the pose for that vsync should be
53// predicted out to. For example, if scanout gets halfway through the frame
54// at the halfway point between vsyncs, then this could be half the period.
55// With global shutter displays, this should be changed to the offset to when
56// illumination begins. Low persistence adds a frame of latency, so we predict
57// to the center of the next frame.
58inline int64_t GetPosePredictionTimeOffset(int64_t vsync_period_ns) {
59 return (vsync_period_ns * 150) / 100;
60}
61
Corey Tabaka2251d822017-04-20 16:04:07 -070062// Attempts to set the scheduler class and partiton for the current thread.
63// Returns true on success or false on failure.
64bool SetThreadPolicy(const std::string& scheduler_class,
65 const std::string& partition) {
66 int error = dvrSetSchedulerClass(0, scheduler_class.c_str());
67 if (error < 0) {
68 ALOGE(
69 "SetThreadPolicy: Failed to set scheduler class \"%s\" for "
70 "thread_id=%d: %s",
71 scheduler_class.c_str(), gettid(), strerror(-error));
72 return false;
73 }
74 error = dvrSetCpuPartition(0, partition.c_str());
75 if (error < 0) {
76 ALOGE(
77 "SetThreadPolicy: Failed to set cpu partiton \"%s\" for thread_id=%d: "
78 "%s",
79 partition.c_str(), gettid(), strerror(-error));
80 return false;
81 }
82 return true;
83}
84
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080085} // anonymous namespace
86
Corey Tabaka2251d822017-04-20 16:04:07 -070087// Layer static data.
88Hwc2::Composer* Layer::hwc2_hidl_;
89const HWCDisplayMetrics* Layer::display_metrics_;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080090
Corey Tabaka2251d822017-04-20 16:04:07 -070091// HardwareComposer static data;
92constexpr size_t HardwareComposer::kMaxHardwareLayers;
93
94HardwareComposer::HardwareComposer()
95 : HardwareComposer(nullptr, RequestDisplayCallback()) {}
96
97HardwareComposer::HardwareComposer(
98 Hwc2::Composer* hwc2_hidl, RequestDisplayCallback request_display_callback)
Stephen Kiazyk016e5e32017-02-21 17:09:22 -080099 : initialized_(false),
100 hwc2_hidl_(hwc2_hidl),
Corey Tabaka2251d822017-04-20 16:04:07 -0700101 request_display_callback_(request_display_callback),
102 callbacks_(new ComposerCallback) {}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800103
104HardwareComposer::~HardwareComposer(void) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700105 UpdatePostThreadState(PostThreadState::Quit, true);
106 if (post_thread_.joinable())
Steven Thomas050b2c82017-03-06 11:45:16 -0800107 post_thread_.join();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800108}
109
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800110bool HardwareComposer::Initialize() {
111 if (initialized_) {
112 ALOGE("HardwareComposer::Initialize: already initialized.");
113 return false;
114 }
115
Corey Tabaka2251d822017-04-20 16:04:07 -0700116 HWC::Error error = HWC::Error::None;
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800117
118 Hwc2::Config config;
Corey Tabaka2251d822017-04-20 16:04:07 -0700119 error = hwc2_hidl_->getActiveConfig(HWC_DISPLAY_PRIMARY, &config);
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800120
Corey Tabaka2251d822017-04-20 16:04:07 -0700121 if (error != HWC::Error::None) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800122 ALOGE("HardwareComposer: Failed to get current display config : %d",
123 config);
124 return false;
125 }
126
Corey Tabaka2251d822017-04-20 16:04:07 -0700127 error =
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800128 GetDisplayMetrics(HWC_DISPLAY_PRIMARY, config, &native_display_metrics_);
129
Corey Tabaka2251d822017-04-20 16:04:07 -0700130 if (error != HWC::Error::None) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800131 ALOGE(
132 "HardwareComposer: Failed to get display attributes for current "
133 "configuration : %d",
Corey Tabaka2251d822017-04-20 16:04:07 -0700134 error.value);
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800135 return false;
136 }
137
138 ALOGI(
139 "HardwareComposer: primary display attributes: width=%d height=%d "
140 "vsync_period_ns=%d DPI=%dx%d",
141 native_display_metrics_.width, native_display_metrics_.height,
142 native_display_metrics_.vsync_period_ns, native_display_metrics_.dpi.x,
143 native_display_metrics_.dpi.y);
144
145 // Set the display metrics but never use rotation to avoid the long latency of
146 // rotation processing in hwc.
147 display_transform_ = HWC_TRANSFORM_NONE;
148 display_metrics_ = native_display_metrics_;
149
Corey Tabaka2251d822017-04-20 16:04:07 -0700150 // Pass hwc instance and metrics to setup globals for Layer.
151 Layer::InitializeGlobals(hwc2_hidl_, &native_display_metrics_);
152
153 post_thread_event_fd_.Reset(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
Steven Thomas050b2c82017-03-06 11:45:16 -0800154 LOG_ALWAYS_FATAL_IF(
Corey Tabaka2251d822017-04-20 16:04:07 -0700155 !post_thread_event_fd_,
Steven Thomas050b2c82017-03-06 11:45:16 -0800156 "HardwareComposer: Failed to create interrupt event fd : %s",
157 strerror(errno));
158
159 post_thread_ = std::thread(&HardwareComposer::PostThread, this);
160
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800161 initialized_ = true;
162
163 return initialized_;
164}
165
Steven Thomas050b2c82017-03-06 11:45:16 -0800166void HardwareComposer::Enable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700167 UpdatePostThreadState(PostThreadState::Suspended, false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800168}
169
170void HardwareComposer::Disable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700171 UpdatePostThreadState(PostThreadState::Suspended, true);
Steven Thomas050b2c82017-03-06 11:45:16 -0800172}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800173
Corey Tabaka2251d822017-04-20 16:04:07 -0700174// Update the post thread quiescent state based on idle and suspended inputs.
175void HardwareComposer::UpdatePostThreadState(PostThreadStateType state,
176 bool suspend) {
177 std::unique_lock<std::mutex> lock(post_thread_mutex_);
178
179 // Update the votes in the state variable before evaluating the effective
180 // quiescent state. Any bits set in post_thread_state_ indicate that the post
181 // thread should be suspended.
182 if (suspend) {
183 post_thread_state_ |= state;
184 } else {
185 post_thread_state_ &= ~state;
186 }
187
188 const bool quit = post_thread_state_ & PostThreadState::Quit;
189 const bool effective_suspend = post_thread_state_ != PostThreadState::Active;
190 if (quit) {
191 post_thread_quiescent_ = true;
192 eventfd_write(post_thread_event_fd_.Get(), 1);
193 post_thread_wait_.notify_one();
194 } else if (effective_suspend && !post_thread_quiescent_) {
195 post_thread_quiescent_ = true;
196 eventfd_write(post_thread_event_fd_.Get(), 1);
197 } else if (!effective_suspend && post_thread_quiescent_) {
198 post_thread_quiescent_ = false;
199 eventfd_t value;
200 eventfd_read(post_thread_event_fd_.Get(), &value);
201 post_thread_wait_.notify_one();
202 }
203
204 // Wait until the post thread is in the requested state.
205 post_thread_ready_.wait(lock, [this, effective_suspend] {
206 return effective_suspend != post_thread_resumed_;
207 });
Steven Thomas050b2c82017-03-06 11:45:16 -0800208}
Steven Thomas282a5ed2017-02-07 18:07:01 -0800209
Steven Thomas050b2c82017-03-06 11:45:16 -0800210void HardwareComposer::OnPostThreadResumed() {
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700211 hwc2_hidl_->resetCommands();
212
Corey Tabaka2251d822017-04-20 16:04:07 -0700213 // HIDL HWC seems to have an internal race condition. If we submit a frame too
214 // soon after turning on VSync we don't get any VSync signals. Give poor HWC
215 // implementations a chance to enable VSync before we continue.
216 EnableVsync(false);
217 std::this_thread::sleep_for(100ms);
Steven Thomas050b2c82017-03-06 11:45:16 -0800218 EnableVsync(true);
Corey Tabaka2251d822017-04-20 16:04:07 -0700219 std::this_thread::sleep_for(100ms);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800220
Steven Thomas050b2c82017-03-06 11:45:16 -0800221 // TODO(skiazyk): We need to do something about accessing this directly,
222 // supposedly there is a backlight service on the way.
223 // TODO(steventhomas): When we change the backlight setting, will surface
224 // flinger (or something else) set it back to its original value once we give
225 // control of the display back to surface flinger?
226 SetBacklightBrightness(255);
Steven Thomas282a5ed2017-02-07 18:07:01 -0800227
Steven Thomas050b2c82017-03-06 11:45:16 -0800228 // Trigger target-specific performance mode change.
229 property_set(kDvrPerformanceProperty, "performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800230}
231
Steven Thomas050b2c82017-03-06 11:45:16 -0800232void HardwareComposer::OnPostThreadPaused() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700233 retire_fence_fds_.clear();
Steven Thomas050b2c82017-03-06 11:45:16 -0800234 display_surfaces_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800235
Corey Tabaka2251d822017-04-20 16:04:07 -0700236 for (size_t i = 0; i < kMaxHardwareLayers; ++i) {
237 layers_[i].Reset();
238 }
239 active_layer_count_ = 0;
Steven Thomas050b2c82017-03-06 11:45:16 -0800240
Steven Thomas050b2c82017-03-06 11:45:16 -0800241 EnableVsync(false);
242
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700243 hwc2_hidl_->resetCommands();
244
Steven Thomas050b2c82017-03-06 11:45:16 -0800245 // Trigger target-specific performance mode change.
246 property_set(kDvrPerformanceProperty, "idle");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800247}
248
Corey Tabaka2251d822017-04-20 16:04:07 -0700249HWC::Error HardwareComposer::Validate(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800250 uint32_t num_types;
251 uint32_t num_requests;
Corey Tabaka2251d822017-04-20 16:04:07 -0700252 HWC::Error error =
253 hwc2_hidl_->validateDisplay(display, &num_types, &num_requests);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800254
255 if (error == HWC2_ERROR_HAS_CHANGES) {
256 // TODO(skiazyk): We might need to inspect the requested changes first, but
257 // so far it seems like we shouldn't ever hit a bad state.
258 // error = hwc2_funcs_.accept_display_changes_fn_(hardware_composer_device_,
259 // display);
Corey Tabaka2251d822017-04-20 16:04:07 -0700260 error = hwc2_hidl_->acceptDisplayChanges(display);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800261 }
262
263 return error;
264}
265
266int32_t HardwareComposer::EnableVsync(bool enabled) {
267 return (int32_t)hwc2_hidl_->setVsyncEnabled(
268 HWC_DISPLAY_PRIMARY,
269 (Hwc2::IComposerClient::Vsync)(enabled ? HWC2_VSYNC_ENABLE
270 : HWC2_VSYNC_DISABLE));
271}
272
Corey Tabaka2251d822017-04-20 16:04:07 -0700273HWC::Error HardwareComposer::Present(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800274 int32_t present_fence;
Corey Tabaka2251d822017-04-20 16:04:07 -0700275 HWC::Error error = hwc2_hidl_->presentDisplay(display, &present_fence);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800276
277 // According to the documentation, this fence is signaled at the time of
278 // vsync/DMA for physical displays.
Corey Tabaka2251d822017-04-20 16:04:07 -0700279 if (error == HWC::Error::None) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800280 ATRACE_INT("HardwareComposer: VsyncFence", present_fence);
281 retire_fence_fds_.emplace_back(present_fence);
282 } else {
283 ATRACE_INT("HardwareComposer: PresentResult", error);
284 }
285
286 return error;
287}
288
Corey Tabaka2251d822017-04-20 16:04:07 -0700289HWC::Error HardwareComposer::GetDisplayAttribute(hwc2_display_t display,
290 hwc2_config_t config,
291 hwc2_attribute_t attribute,
292 int32_t* out_value) const {
293 return hwc2_hidl_->getDisplayAttribute(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800294 display, config, (Hwc2::IComposerClient::Attribute)attribute, out_value);
295}
296
Corey Tabaka2251d822017-04-20 16:04:07 -0700297HWC::Error HardwareComposer::GetDisplayMetrics(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800298 hwc2_display_t display, hwc2_config_t config,
299 HWCDisplayMetrics* out_metrics) const {
Corey Tabaka2251d822017-04-20 16:04:07 -0700300 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800301
Corey Tabaka2251d822017-04-20 16:04:07 -0700302 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_WIDTH,
303 &out_metrics->width);
304 if (error != HWC::Error::None) {
305 ALOGE(
306 "HardwareComposer::GetDisplayMetrics: Failed to get display width: %s",
307 error.to_string().c_str());
308 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800309 }
310
Corey Tabaka2251d822017-04-20 16:04:07 -0700311 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_HEIGHT,
312 &out_metrics->height);
313 if (error != HWC::Error::None) {
314 ALOGE(
315 "HardwareComposer::GetDisplayMetrics: Failed to get display height: %s",
316 error.to_string().c_str());
317 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800318 }
319
Corey Tabaka2251d822017-04-20 16:04:07 -0700320 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_VSYNC_PERIOD,
321 &out_metrics->vsync_period_ns);
322 if (error != HWC::Error::None) {
323 ALOGE(
324 "HardwareComposer::GetDisplayMetrics: Failed to get display height: %s",
325 error.to_string().c_str());
326 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800327 }
328
Corey Tabaka2251d822017-04-20 16:04:07 -0700329 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_DPI_X,
330 &out_metrics->dpi.x);
331 if (error != HWC::Error::None) {
332 ALOGE(
333 "HardwareComposer::GetDisplayMetrics: Failed to get display DPI X: %s",
334 error.to_string().c_str());
335 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800336 }
337
Corey Tabaka2251d822017-04-20 16:04:07 -0700338 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_DPI_Y,
339 &out_metrics->dpi.y);
340 if (error != HWC::Error::None) {
341 ALOGE(
342 "HardwareComposer::GetDisplayMetrics: Failed to get display DPI Y: %s",
343 error.to_string().c_str());
344 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800345 }
346
Corey Tabaka2251d822017-04-20 16:04:07 -0700347 return HWC::Error::None;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800348}
349
Corey Tabaka2251d822017-04-20 16:04:07 -0700350std::string HardwareComposer::Dump() { return hwc2_hidl_->dumpDebugInfo(); }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800351
Corey Tabaka2251d822017-04-20 16:04:07 -0700352void HardwareComposer::PostLayers() {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800353 ATRACE_NAME("HardwareComposer::PostLayers");
354
355 // Setup the hardware composer layers with current buffers.
356 for (size_t i = 0; i < active_layer_count_; i++) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700357 layers_[i].Prepare();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800358 }
359
Corey Tabaka2251d822017-04-20 16:04:07 -0700360 HWC::Error error = Validate(HWC_DISPLAY_PRIMARY);
361 if (error != HWC::Error::None) {
362 ALOGE("HardwareComposer::PostLayers: Validate failed: %s",
363 error.to_string().c_str());
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700364 return;
365 }
366
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800367 // Now that we have taken in a frame from the application, we have a chance
368 // to drop the frame before passing the frame along to HWC.
369 // If the display driver has become backed up, we detect it here and then
370 // react by skipping this frame to catch up latency.
371 while (!retire_fence_fds_.empty() &&
372 (!retire_fence_fds_.front() ||
373 sync_wait(retire_fence_fds_.front().Get(), 0) == 0)) {
374 // There are only 2 fences in here, no performance problem to shift the
375 // array of ints.
376 retire_fence_fds_.erase(retire_fence_fds_.begin());
377 }
378
379 const bool is_frame_pending = IsFramePendingInDriver();
John Bates954796e2017-05-11 11:00:31 -0700380 const bool is_fence_pending = retire_fence_fds_.size() >
381 post_thread_config_.allowed_pending_fence_count;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800382
383 if (is_fence_pending || is_frame_pending) {
384 ATRACE_INT("frame_skip_count", ++frame_skip_count_);
385
386 ALOGW_IF(is_frame_pending, "Warning: frame already queued, dropping frame");
387 ALOGW_IF(is_fence_pending,
388 "Warning: dropping a frame to catch up with HWC (pending = %zd)",
389 retire_fence_fds_.size());
390
391 for (size_t i = 0; i < active_layer_count_; i++) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700392 layers_[i].Drop();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800393 }
394 return;
395 } else {
396 // Make the transition more obvious in systrace when the frame skip happens
397 // above.
398 ATRACE_INT("frame_skip_count", 0);
399 }
400
401#if TRACE
402 for (size_t i = 0; i < active_layer_count_; i++)
Corey Tabaka2251d822017-04-20 16:04:07 -0700403 ALOGI("HardwareComposer::PostLayers: layer=%zu composition=%s", i,
404 layers_[i].GetCompositionType().to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800405#endif
406
Corey Tabaka2251d822017-04-20 16:04:07 -0700407 error = Present(HWC_DISPLAY_PRIMARY);
408 if (error != HWC::Error::None) {
409 ALOGE("HardwareComposer::PostLayers: Present failed: %s",
410 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800411 return;
412 }
413
414 std::vector<Hwc2::Layer> out_layers;
415 std::vector<int> out_fences;
Corey Tabaka2251d822017-04-20 16:04:07 -0700416 error = hwc2_hidl_->getReleaseFences(HWC_DISPLAY_PRIMARY, &out_layers,
417 &out_fences);
418 ALOGE_IF(error != HWC::Error::None,
419 "HardwareComposer::PostLayers: Failed to get release fences: %s",
420 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800421
422 // Perform post-frame bookkeeping. Unused layers are a no-op.
Corey Tabaka2251d822017-04-20 16:04:07 -0700423 uint32_t num_elements = out_layers.size();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800424 for (size_t i = 0; i < num_elements; ++i) {
425 for (size_t j = 0; j < active_layer_count_; ++j) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700426 if (layers_[j].GetLayerHandle() == out_layers[i]) {
427 layers_[j].Finish(out_fences[i]);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800428 }
429 }
430 }
431}
432
Steven Thomas050b2c82017-03-06 11:45:16 -0800433void HardwareComposer::SetDisplaySurfaces(
Corey Tabaka2251d822017-04-20 16:04:07 -0700434 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces) {
Jin Qian7480c062017-03-21 00:04:15 +0000435 ALOGI("HardwareComposer::SetDisplaySurfaces: surface count=%zd",
436 surfaces.size());
Corey Tabaka2251d822017-04-20 16:04:07 -0700437 const bool display_idle = surfaces.size() == 0;
438 {
439 std::unique_lock<std::mutex> lock(post_thread_mutex_);
440 pending_surfaces_ = std::move(surfaces);
441 }
442
443 // Set idle state based on whether there are any surfaces to handle.
444 UpdatePostThreadState(PostThreadState::Idle, display_idle);
445
446 // XXX: TEMPORARY
447 // Request control of the display based on whether there are any surfaces to
448 // handle. This callback sets the post thread active state once the transition
449 // is complete in SurfaceFlinger.
450 // TODO(eieio): Unify the control signal used to move SurfaceFlinger into VR
451 // mode. Currently this is hooked up to persistent VR mode, but perhaps this
452 // makes more sense to control it from VrCore, which could in turn base its
453 // decision on persistent VR mode.
454 if (request_display_callback_)
455 request_display_callback_(!display_idle);
Steven Thomas050b2c82017-03-06 11:45:16 -0800456}
Jin Qian7480c062017-03-21 00:04:15 +0000457
John Bates954796e2017-05-11 11:00:31 -0700458int HardwareComposer::OnNewGlobalBuffer(DvrGlobalBufferKey key,
459 IonBuffer& ion_buffer) {
Okan Arikan822b7102017-05-08 13:31:34 -0700460 if (key == DvrGlobalBuffers::kVsyncBuffer) {
461 vsync_ring_ = std::make_unique<CPUMappedBroadcastRing<DvrVsyncRing>>(
462 &ion_buffer, CPUUsageMode::WRITE_OFTEN);
463
464 if (vsync_ring_->IsMapped() == false) {
465 return -EPERM;
466 }
467 }
468
469 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700470 return MapConfigBuffer(ion_buffer);
471 }
472
473 return 0;
474}
475
476void HardwareComposer::OnDeletedGlobalBuffer(DvrGlobalBufferKey key) {
Okan Arikan822b7102017-05-08 13:31:34 -0700477 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700478 ConfigBufferDeleted();
479 }
480}
481
482int HardwareComposer::MapConfigBuffer(IonBuffer& ion_buffer) {
483 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700484 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700485
Okan Arikan6f468c62017-05-31 14:48:30 -0700486 if (ion_buffer.width() < DvrConfigRing::MemorySize()) {
John Bates954796e2017-05-11 11:00:31 -0700487 ALOGE("HardwareComposer::MapConfigBuffer: invalid buffer size.");
488 return -EINVAL;
489 }
490
491 void* buffer_base = 0;
492 int result = ion_buffer.Lock(ion_buffer.usage(), 0, 0, ion_buffer.width(),
493 ion_buffer.height(), &buffer_base);
494 if (result != 0) {
495 ALOGE("HardwareComposer::MapConfigBuffer: Failed to map vrflinger config "
496 "buffer.");
497 return -EPERM;
498 }
499
Okan Arikan6f468c62017-05-31 14:48:30 -0700500 shared_config_ring_ = DvrConfigRing::Create(buffer_base, ion_buffer.width());
John Bates954796e2017-05-11 11:00:31 -0700501 ion_buffer.Unlock();
502
503 return 0;
504}
505
506void HardwareComposer::ConfigBufferDeleted() {
507 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700508 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700509}
510
511void HardwareComposer::UpdateConfigBuffer() {
512 std::lock_guard<std::mutex> lock(shared_config_mutex_);
513 if (!shared_config_ring_.is_valid())
514 return;
515 // Copy from latest record in shared_config_ring_ to local copy.
Okan Arikan6f468c62017-05-31 14:48:30 -0700516 DvrConfig record;
John Bates954796e2017-05-11 11:00:31 -0700517 if (shared_config_ring_.GetNewest(&shared_config_ring_sequence_, &record)) {
518 post_thread_config_ = record;
519 }
520}
521
Corey Tabaka2251d822017-04-20 16:04:07 -0700522int HardwareComposer::PostThreadPollInterruptible(
523 const pdx::LocalHandle& event_fd, int requested_events) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800524 pollfd pfd[2] = {
525 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700526 .fd = event_fd.Get(),
Steven Thomas66747c12017-03-22 18:45:31 -0700527 .events = static_cast<short>(requested_events),
528 .revents = 0,
Steven Thomas050b2c82017-03-06 11:45:16 -0800529 },
530 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700531 .fd = post_thread_event_fd_.Get(),
Steven Thomas050b2c82017-03-06 11:45:16 -0800532 .events = POLLPRI | POLLIN,
533 .revents = 0,
534 },
535 };
536 int ret, error;
537 do {
538 ret = poll(pfd, 2, -1);
539 error = errno;
540 ALOGW_IF(ret < 0,
541 "HardwareComposer::PostThreadPollInterruptible: Error during "
542 "poll(): %s (%d)",
543 strerror(error), error);
544 } while (ret < 0 && error == EINTR);
545
546 if (ret < 0) {
547 return -error;
548 } else if (pfd[0].revents != 0) {
549 return 0;
550 } else if (pfd[1].revents != 0) {
551 ALOGI("VrHwcPost thread interrupted");
552 return kPostThreadInterrupted;
553 } else {
554 return 0;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800555 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800556}
557
558// Reads the value of the display driver wait_pingpong state. Returns 0 or 1
559// (the value of the state) on success or a negative error otherwise.
560// TODO(eieio): This is pretty driver specific, this should be moved to a
561// separate class eventually.
562int HardwareComposer::ReadWaitPPState() {
563 // Gracefully handle when the kernel does not support this feature.
564 if (!primary_display_wait_pp_fd_)
565 return 0;
566
567 const int wait_pp_fd = primary_display_wait_pp_fd_.Get();
568 int ret, error;
569
570 ret = lseek(wait_pp_fd, 0, SEEK_SET);
571 if (ret < 0) {
572 error = errno;
573 ALOGE("HardwareComposer::ReadWaitPPState: Failed to seek wait_pp fd: %s",
574 strerror(error));
575 return -error;
576 }
577
578 char data = -1;
579 ret = read(wait_pp_fd, &data, sizeof(data));
580 if (ret < 0) {
581 error = errno;
582 ALOGE("HardwareComposer::ReadWaitPPState: Failed to read wait_pp state: %s",
583 strerror(error));
584 return -error;
585 }
586
587 switch (data) {
588 case '0':
589 return 0;
590 case '1':
591 return 1;
592 default:
593 ALOGE(
594 "HardwareComposer::ReadWaitPPState: Unexpected value for wait_pp: %d",
595 data);
596 return -EINVAL;
597 }
598}
599
600// Reads the timestamp of the last vsync from the display driver.
601// TODO(eieio): This is pretty driver specific, this should be moved to a
602// separate class eventually.
603int HardwareComposer::ReadVSyncTimestamp(int64_t* timestamp) {
604 const int event_fd = primary_display_vsync_event_fd_.Get();
605 int ret, error;
606
607 // The driver returns data in the form "VSYNC=<timestamp ns>".
608 std::array<char, 32> data;
609 data.fill('\0');
610
611 // Seek back to the beginning of the event file.
612 ret = lseek(event_fd, 0, SEEK_SET);
613 if (ret < 0) {
614 error = errno;
615 ALOGE(
616 "HardwareComposer::ReadVSyncTimestamp: Failed to seek vsync event fd: "
617 "%s",
618 strerror(error));
619 return -error;
620 }
621
622 // Read the vsync event timestamp.
623 ret = read(event_fd, data.data(), data.size());
624 if (ret < 0) {
625 error = errno;
626 ALOGE_IF(
627 error != EAGAIN,
628 "HardwareComposer::ReadVSyncTimestamp: Error while reading timestamp: "
629 "%s",
630 strerror(error));
631 return -error;
632 }
633
634 ret = sscanf(data.data(), "VSYNC=%" PRIu64,
635 reinterpret_cast<uint64_t*>(timestamp));
636 if (ret < 0) {
637 error = errno;
638 ALOGE(
639 "HardwareComposer::ReadVSyncTimestamp: Error while parsing timestamp: "
640 "%s",
641 strerror(error));
642 return -error;
643 }
644
645 return 0;
646}
647
648// Blocks until the next vsync event is signaled by the display driver.
649// TODO(eieio): This is pretty driver specific, this should be moved to a
650// separate class eventually.
Steven Thomas050b2c82017-03-06 11:45:16 -0800651int HardwareComposer::BlockUntilVSync() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700652 // Vsync is signaled by POLLPRI on the fb vsync node.
653 return PostThreadPollInterruptible(primary_display_vsync_event_fd_, POLLPRI);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800654}
655
656// Waits for the next vsync and returns the timestamp of the vsync event. If
657// vsync already passed since the last call, returns the latest vsync timestamp
658// instead of blocking. This method updates the last_vsync_timeout_ in the
659// process.
660//
661// TODO(eieio): This is pretty driver specific, this should be moved to a
662// separate class eventually.
663int HardwareComposer::WaitForVSync(int64_t* timestamp) {
664 int error;
665
666 // Get the current timestamp and decide what to do.
667 while (true) {
668 int64_t current_vsync_timestamp;
669 error = ReadVSyncTimestamp(&current_vsync_timestamp);
670 if (error < 0 && error != -EAGAIN)
671 return error;
672
673 if (error == -EAGAIN) {
674 // Vsync was turned off, wait for the next vsync event.
Steven Thomas050b2c82017-03-06 11:45:16 -0800675 error = BlockUntilVSync();
676 if (error < 0 || error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800677 return error;
678
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800679 // Try again to get the timestamp for this new vsync interval.
680 continue;
681 }
682
683 // Check that we advanced to a later vsync interval.
684 if (TimestampGT(current_vsync_timestamp, last_vsync_timestamp_)) {
685 *timestamp = last_vsync_timestamp_ = current_vsync_timestamp;
686 return 0;
687 }
688
689 // See how close we are to the next expected vsync. If we're within 1ms,
690 // sleep for 1ms and try again.
691 const int64_t ns_per_frame = display_metrics_.vsync_period_ns;
Corey Tabaka2251d822017-04-20 16:04:07 -0700692 const int64_t threshold_ns = 1000000; // 1ms
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800693
694 const int64_t next_vsync_est = last_vsync_timestamp_ + ns_per_frame;
695 const int64_t distance_to_vsync_est = next_vsync_est - GetSystemClockNs();
696
697 if (distance_to_vsync_est > threshold_ns) {
698 // Wait for vsync event notification.
Steven Thomas050b2c82017-03-06 11:45:16 -0800699 error = BlockUntilVSync();
700 if (error < 0 || error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800701 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800702 } else {
Steven Thomas050b2c82017-03-06 11:45:16 -0800703 // Sleep for a short time (1 millisecond) before retrying.
Corey Tabaka2251d822017-04-20 16:04:07 -0700704 error = SleepUntil(GetSystemClockNs() + threshold_ns);
Steven Thomas050b2c82017-03-06 11:45:16 -0800705 if (error < 0 || error == kPostThreadInterrupted)
706 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800707 }
708 }
709}
710
711int HardwareComposer::SleepUntil(int64_t wakeup_timestamp) {
712 const int timer_fd = vsync_sleep_timer_fd_.Get();
713 const itimerspec wakeup_itimerspec = {
714 .it_interval = {.tv_sec = 0, .tv_nsec = 0},
715 .it_value = NsToTimespec(wakeup_timestamp),
716 };
717 int ret =
718 timerfd_settime(timer_fd, TFD_TIMER_ABSTIME, &wakeup_itimerspec, nullptr);
719 int error = errno;
720 if (ret < 0) {
721 ALOGE("HardwareComposer::SleepUntil: Failed to set timerfd: %s",
722 strerror(error));
723 return -error;
724 }
725
Corey Tabaka2251d822017-04-20 16:04:07 -0700726 return PostThreadPollInterruptible(vsync_sleep_timer_fd_, POLLIN);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800727}
728
729void HardwareComposer::PostThread() {
730 // NOLINTNEXTLINE(runtime/int)
Steven Thomas050b2c82017-03-06 11:45:16 -0800731 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>("VrHwcPost"), 0, 0, 0);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800732
Corey Tabaka2251d822017-04-20 16:04:07 -0700733 // Set the scheduler to SCHED_FIFO with high priority. If this fails here
734 // there may have been a startup timing issue between this thread and
735 // performanced. Try again later when this thread becomes active.
736 bool thread_policy_setup =
737 SetThreadPolicy("graphics:high", "/system/performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800738
Steven Thomas050b2c82017-03-06 11:45:16 -0800739#if ENABLE_BACKLIGHT_BRIGHTNESS
740 // TODO(hendrikw): This isn't required at the moment. It's possible that there
741 // is another method to access this when needed.
742 // Open the backlight brightness control sysfs node.
743 backlight_brightness_fd_ = LocalHandle(kBacklightBrightnessSysFile, O_RDWR);
744 ALOGW_IF(!backlight_brightness_fd_,
745 "HardwareComposer: Failed to open backlight brightness control: %s",
746 strerror(errno));
Corey Tabaka2251d822017-04-20 16:04:07 -0700747#endif // ENABLE_BACKLIGHT_BRIGHTNESS
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800748
Steven Thomas050b2c82017-03-06 11:45:16 -0800749 // Open the vsync event node for the primary display.
750 // TODO(eieio): Move this into a platform-specific class.
751 primary_display_vsync_event_fd_ =
752 LocalHandle(kPrimaryDisplayVSyncEventFile, O_RDONLY);
753 ALOGE_IF(!primary_display_vsync_event_fd_,
754 "HardwareComposer: Failed to open vsync event node for primary "
755 "display: %s",
756 strerror(errno));
757
758 // Open the wait pingpong status node for the primary display.
759 // TODO(eieio): Move this into a platform-specific class.
760 primary_display_wait_pp_fd_ =
761 LocalHandle(kPrimaryDisplayWaitPPEventFile, O_RDONLY);
762 ALOGW_IF(
763 !primary_display_wait_pp_fd_,
764 "HardwareComposer: Failed to open wait_pp node for primary display: %s",
765 strerror(errno));
766
767 // Create a timerfd based on CLOCK_MONOTINIC.
768 vsync_sleep_timer_fd_.Reset(timerfd_create(CLOCK_MONOTONIC, 0));
769 LOG_ALWAYS_FATAL_IF(
770 !vsync_sleep_timer_fd_,
771 "HardwareComposer: Failed to create vsync sleep timerfd: %s",
772 strerror(errno));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800773
774 const int64_t ns_per_frame = display_metrics_.vsync_period_ns;
775 const int64_t photon_offset_ns = GetPosePredictionTimeOffset(ns_per_frame);
776
777 // TODO(jbates) Query vblank time from device, when such an API is available.
778 // This value (6.3%) was measured on A00 in low persistence mode.
779 int64_t vblank_ns = ns_per_frame * 63 / 1000;
780 int64_t right_eye_photon_offset_ns = (ns_per_frame - vblank_ns) / 2;
781
782 // Check property for overriding right eye offset value.
783 right_eye_photon_offset_ns =
784 property_get_int64(kRightEyeOffsetProperty, right_eye_photon_offset_ns);
785
Steven Thomas050b2c82017-03-06 11:45:16 -0800786 bool was_running = false;
787
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800788 while (1) {
789 ATRACE_NAME("HardwareComposer::PostThread");
790
John Bates954796e2017-05-11 11:00:31 -0700791 // Check for updated config once per vsync.
792 UpdateConfigBuffer();
793
Corey Tabaka2251d822017-04-20 16:04:07 -0700794 while (post_thread_quiescent_) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800795 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Corey Tabaka2251d822017-04-20 16:04:07 -0700796 ALOGI("HardwareComposer::PostThread: Entering quiescent state.");
797
798 // Tear down resources.
799 OnPostThreadPaused();
800
801 was_running = false;
802 post_thread_resumed_ = false;
803 post_thread_ready_.notify_all();
804
805 if (post_thread_state_ & PostThreadState::Quit) {
806 ALOGI("HardwareComposer::PostThread: Quitting.");
807 return;
Steven Thomas282a5ed2017-02-07 18:07:01 -0800808 }
Corey Tabaka2251d822017-04-20 16:04:07 -0700809
810 post_thread_wait_.wait(lock, [this] { return !post_thread_quiescent_; });
811
812 post_thread_resumed_ = true;
813 post_thread_ready_.notify_all();
814
815 ALOGI("HardwareComposer::PostThread: Exiting quiescent state.");
Steven Thomas050b2c82017-03-06 11:45:16 -0800816 }
817
818 if (!was_running) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700819 // Setup resources.
Steven Thomas050b2c82017-03-06 11:45:16 -0800820 OnPostThreadResumed();
821 was_running = true;
Corey Tabaka2251d822017-04-20 16:04:07 -0700822
823 // Try to setup the scheduler policy if it failed during startup. Only
824 // attempt to do this on transitions from inactive to active to avoid
825 // spamming the system with RPCs and log messages.
826 if (!thread_policy_setup) {
827 thread_policy_setup =
828 SetThreadPolicy("graphics:high", "/system/performance");
829 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800830 }
831
832 int64_t vsync_timestamp = 0;
833 {
834 std::array<char, 128> buf;
835 snprintf(buf.data(), buf.size(), "wait_vsync|vsync=%d|",
836 vsync_count_ + 1);
837 ATRACE_NAME(buf.data());
838
Corey Tabaka2251d822017-04-20 16:04:07 -0700839 const int error = WaitForVSync(&vsync_timestamp);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800840 ALOGE_IF(
841 error < 0,
842 "HardwareComposer::PostThread: Failed to wait for vsync event: %s",
843 strerror(-error));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800844 // Don't bother processing this frame if a pause was requested
Steven Thomas050b2c82017-03-06 11:45:16 -0800845 if (error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800846 continue;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800847 }
848
849 ++vsync_count_;
850
Corey Tabaka2251d822017-04-20 16:04:07 -0700851 const bool layer_config_changed = UpdateLayerConfig();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800852
Okan Arikan822b7102017-05-08 13:31:34 -0700853 // Publish the vsync event.
854 if (vsync_ring_) {
855 DvrVsync vsync;
856 vsync.vsync_count = vsync_count_;
857 vsync.vsync_timestamp_ns = vsync_timestamp;
858 vsync.vsync_left_eye_offset_ns = photon_offset_ns;
859 vsync.vsync_right_eye_offset_ns = right_eye_photon_offset_ns;
860 vsync.vsync_period_ns = ns_per_frame;
861
862 vsync_ring_->Publish(vsync);
863 }
864
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800865 // Signal all of the vsync clients. Because absolute time is used for the
866 // wakeup time below, this can take a little time if necessary.
867 if (vsync_callback_)
Corey Tabaka2251d822017-04-20 16:04:07 -0700868 vsync_callback_(HWC_DISPLAY_PRIMARY, vsync_timestamp,
869 /*frame_time_estimate*/ 0, vsync_count_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800870
871 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700872 // Sleep until shortly before vsync.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800873 ATRACE_NAME("sleep");
874
Corey Tabaka2251d822017-04-20 16:04:07 -0700875 const int64_t display_time_est_ns = vsync_timestamp + ns_per_frame;
876 const int64_t now_ns = GetSystemClockNs();
John Bates954796e2017-05-11 11:00:31 -0700877 const int64_t sleep_time_ns = display_time_est_ns - now_ns -
878 post_thread_config_.frame_post_offset_ns;
879 const int64_t wakeup_time_ns =
880 display_time_est_ns - post_thread_config_.frame_post_offset_ns;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800881
882 ATRACE_INT64("sleep_time_ns", sleep_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800883 if (sleep_time_ns > 0) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700884 int error = SleepUntil(wakeup_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800885 ALOGE_IF(error < 0, "HardwareComposer::PostThread: Failed to sleep: %s",
886 strerror(-error));
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700887 if (error == kPostThreadInterrupted) {
888 if (layer_config_changed) {
889 // If the layer config changed we need to validateDisplay() even if
890 // we're going to drop the frame, to flush the Composer object's
891 // internal command buffer and apply our layer changes.
892 Validate(HWC_DISPLAY_PRIMARY);
893 }
Steven Thomas050b2c82017-03-06 11:45:16 -0800894 continue;
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700895 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800896 }
897 }
898
Corey Tabaka2251d822017-04-20 16:04:07 -0700899 PostLayers();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800900 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800901}
902
Corey Tabaka2251d822017-04-20 16:04:07 -0700903// Checks for changes in the surface stack and updates the layer config to
904// accomodate the new stack.
Steven Thomas050b2c82017-03-06 11:45:16 -0800905bool HardwareComposer::UpdateLayerConfig() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700906 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces;
Steven Thomas050b2c82017-03-06 11:45:16 -0800907 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700908 std::unique_lock<std::mutex> lock(post_thread_mutex_);
909 if (pending_surfaces_.empty())
Steven Thomas050b2c82017-03-06 11:45:16 -0800910 return false;
Corey Tabaka2251d822017-04-20 16:04:07 -0700911
912 surfaces = std::move(pending_surfaces_);
Steven Thomas050b2c82017-03-06 11:45:16 -0800913 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800914
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800915 ATRACE_NAME("UpdateLayerConfig_HwLayers");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800916
Corey Tabaka2251d822017-04-20 16:04:07 -0700917 display_surfaces_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800918
Corey Tabaka2251d822017-04-20 16:04:07 -0700919 Layer* target_layer;
920 size_t layer_index;
921 for (layer_index = 0;
922 layer_index < std::min(surfaces.size(), kMaxHardwareLayers);
923 layer_index++) {
924 // The bottom layer is opaque, other layers blend.
925 HWC::BlendMode blending =
926 layer_index == 0 ? HWC::BlendMode::None : HWC::BlendMode::Coverage;
927 layers_[layer_index].Setup(surfaces[layer_index], blending,
928 display_transform_, HWC::Composition::Device,
929 layer_index);
930 display_surfaces_.push_back(surfaces[layer_index]);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800931 }
932
Corey Tabaka2251d822017-04-20 16:04:07 -0700933 // Clear unused layers.
934 for (size_t i = layer_index; i < kMaxHardwareLayers; i++)
935 layers_[i].Reset();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800936
Corey Tabaka2251d822017-04-20 16:04:07 -0700937 active_layer_count_ = layer_index;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800938 ALOGD_IF(TRACE, "HardwareComposer::UpdateLayerConfig: %zd active layers",
939 active_layer_count_);
940
Corey Tabaka2251d822017-04-20 16:04:07 -0700941 // Any surfaces left over could not be assigned a hardware layer and will
942 // not be displayed.
943 ALOGW_IF(surfaces.size() != display_surfaces_.size(),
944 "HardwareComposer::UpdateLayerConfig: More surfaces than layers: "
945 "pending_surfaces=%zu display_surfaces=%zu",
946 surfaces.size(), display_surfaces_.size());
947
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800948 return true;
949}
950
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800951void HardwareComposer::SetVSyncCallback(VSyncCallback callback) {
952 vsync_callback_ = callback;
953}
954
955void HardwareComposer::HwcRefresh(hwc2_callback_data_t /*data*/,
956 hwc2_display_t /*display*/) {
957 // TODO(eieio): implement invalidate callbacks.
958}
959
960void HardwareComposer::HwcVSync(hwc2_callback_data_t /*data*/,
961 hwc2_display_t /*display*/,
962 int64_t /*timestamp*/) {
963 ATRACE_NAME(__PRETTY_FUNCTION__);
964 // Intentionally empty. HWC may require a callback to be set to enable vsync
965 // signals. We bypass this callback thread by monitoring the vsync event
966 // directly, but signals still need to be enabled.
967}
968
969void HardwareComposer::HwcHotplug(hwc2_callback_data_t /*callbackData*/,
970 hwc2_display_t /*display*/,
971 hwc2_connection_t /*connected*/) {
972 // TODO(eieio): implement display hotplug callbacks.
973}
974
Steven Thomas3cfac282017-02-06 12:29:30 -0800975void HardwareComposer::OnHardwareComposerRefresh() {
976 // TODO(steventhomas): Handle refresh.
977}
978
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800979void HardwareComposer::SetBacklightBrightness(int brightness) {
980 if (backlight_brightness_fd_) {
981 std::array<char, 32> text;
982 const int length = snprintf(text.data(), text.size(), "%d", brightness);
983 write(backlight_brightness_fd_.Get(), text.data(), length);
984 }
985}
986
Corey Tabaka2251d822017-04-20 16:04:07 -0700987void Layer::InitializeGlobals(Hwc2::Composer* hwc2_hidl,
988 const HWCDisplayMetrics* metrics) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800989 hwc2_hidl_ = hwc2_hidl;
990 display_metrics_ = metrics;
991}
992
993void Layer::Reset() {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800994 if (hwc2_hidl_ != nullptr && hardware_composer_layer_) {
995 hwc2_hidl_->destroyLayer(HWC_DISPLAY_PRIMARY, hardware_composer_layer_);
996 hardware_composer_layer_ = 0;
997 }
998
Corey Tabaka2251d822017-04-20 16:04:07 -0700999 z_order_ = 0;
1000 blending_ = HWC::BlendMode::None;
1001 transform_ = HWC::Transform::None;
1002 composition_type_ = HWC::Composition::Invalid;
1003 target_composition_type_ = composition_type_;
1004 source_ = EmptyVariant{};
1005 acquire_fence_.Close();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001006 surface_rect_functions_applied_ = false;
1007}
1008
Corey Tabaka2251d822017-04-20 16:04:07 -07001009void Layer::Setup(const std::shared_ptr<DirectDisplaySurface>& surface,
1010 HWC::BlendMode blending, HWC::Transform transform,
1011 HWC::Composition composition_type, size_t z_order) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001012 Reset();
Corey Tabaka2251d822017-04-20 16:04:07 -07001013 z_order_ = z_order;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001014 blending_ = blending;
1015 transform_ = transform;
Corey Tabaka2251d822017-04-20 16:04:07 -07001016 composition_type_ = HWC::Composition::Invalid;
1017 target_composition_type_ = composition_type;
1018 source_ = SourceSurface{surface};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001019 CommonLayerSetup();
1020}
1021
1022void Layer::Setup(const std::shared_ptr<IonBuffer>& buffer,
Corey Tabaka2251d822017-04-20 16:04:07 -07001023 HWC::BlendMode blending, HWC::Transform transform,
1024 HWC::Composition composition_type, size_t z_order) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001025 Reset();
Corey Tabaka2251d822017-04-20 16:04:07 -07001026 z_order_ = z_order;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001027 blending_ = blending;
1028 transform_ = transform;
Corey Tabaka2251d822017-04-20 16:04:07 -07001029 composition_type_ = HWC::Composition::Invalid;
1030 target_composition_type_ = composition_type;
1031 source_ = SourceBuffer{buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001032 CommonLayerSetup();
1033}
1034
Corey Tabaka2251d822017-04-20 16:04:07 -07001035void Layer::UpdateBuffer(const std::shared_ptr<IonBuffer>& buffer) {
1036 if (source_.is<SourceBuffer>())
1037 std::get<SourceBuffer>(source_) = {buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001038}
1039
Corey Tabaka2251d822017-04-20 16:04:07 -07001040void Layer::SetBlending(HWC::BlendMode blending) { blending_ = blending; }
1041void Layer::SetZOrder(size_t z_order) { z_order_ = z_order; }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001042
1043IonBuffer* Layer::GetBuffer() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001044 struct Visitor {
1045 IonBuffer* operator()(SourceSurface& source) { return source.GetBuffer(); }
1046 IonBuffer* operator()(SourceBuffer& source) { return source.GetBuffer(); }
1047 IonBuffer* operator()(EmptyVariant) { return nullptr; }
1048 };
1049 return source_.Visit(Visitor{});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001050}
1051
1052void Layer::UpdateLayerSettings() {
1053 if (!IsLayerSetup()) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001054 ALOGE(
1055 "HardwareComposer::Layer::UpdateLayerSettings: Attempt to update "
1056 "unused Layer!");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001057 return;
1058 }
1059
Corey Tabaka2251d822017-04-20 16:04:07 -07001060 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001061 hwc2_display_t display = HWC_DISPLAY_PRIMARY;
1062
Corey Tabaka2251d822017-04-20 16:04:07 -07001063 error = hwc2_hidl_->setLayerCompositionType(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001064 display, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001065 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1066 ALOGE_IF(
1067 error != HWC::Error::None,
1068 "Layer::UpdateLayerSettings: Error setting layer composition type: %s",
1069 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001070
Corey Tabaka2251d822017-04-20 16:04:07 -07001071 error = hwc2_hidl_->setLayerBlendMode(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001072 display, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001073 blending_.cast<Hwc2::IComposerClient::BlendMode>());
1074 ALOGE_IF(error != HWC::Error::None,
1075 "Layer::UpdateLayerSettings: Error setting layer blend mode: %s",
1076 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001077
Corey Tabaka2251d822017-04-20 16:04:07 -07001078 // TODO(eieio): Use surface attributes or some other mechanism to control
1079 // the layer display frame.
1080 error = hwc2_hidl_->setLayerDisplayFrame(
1081 display, hardware_composer_layer_,
1082 {0, 0, display_metrics_->width, display_metrics_->height});
1083 ALOGE_IF(error != HWC::Error::None,
1084 "Layer::UpdateLayerSettings: Error setting layer display frame: %s",
1085 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001086
Corey Tabaka2251d822017-04-20 16:04:07 -07001087 error = hwc2_hidl_->setLayerVisibleRegion(
1088 display, hardware_composer_layer_,
1089 {{0, 0, display_metrics_->width, display_metrics_->height}});
1090 ALOGE_IF(error != HWC::Error::None,
1091 "Layer::UpdateLayerSettings: Error setting layer visible region: %s",
1092 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001093
Corey Tabaka2251d822017-04-20 16:04:07 -07001094 error =
1095 hwc2_hidl_->setLayerPlaneAlpha(display, hardware_composer_layer_, 1.0f);
1096 ALOGE_IF(error != HWC::Error::None,
1097 "Layer::UpdateLayerSettings: Error setting layer plane alpha: %s",
1098 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001099
Corey Tabaka2251d822017-04-20 16:04:07 -07001100 error =
1101 hwc2_hidl_->setLayerZOrder(display, hardware_composer_layer_, z_order_);
1102 ALOGE_IF(error != HWC::Error::None,
1103 "Layer::UpdateLayerSettings: Error setting z_ order: %s",
1104 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001105}
1106
1107void Layer::CommonLayerSetup() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001108 HWC::Error error =
1109 hwc2_hidl_->createLayer(HWC_DISPLAY_PRIMARY, &hardware_composer_layer_);
1110 ALOGE_IF(
1111 error != HWC::Error::None,
1112 "Layer::CommonLayerSetup: Failed to create layer on primary display: %s",
1113 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001114 UpdateLayerSettings();
1115}
1116
1117void Layer::Prepare() {
1118 int right, bottom;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -04001119 sp<GraphicBuffer> handle;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001120
Corey Tabaka2251d822017-04-20 16:04:07 -07001121 // Acquire the next buffer according to the type of source.
1122 IfAnyOf<SourceSurface, SourceBuffer>::Call(&source_, [&](auto& source) {
1123 std::tie(right, bottom, handle, acquire_fence_) = source.Acquire();
1124 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001125
Corey Tabaka2251d822017-04-20 16:04:07 -07001126 // When a layer is first setup there may be some time before the first buffer
1127 // arrives. Setup the HWC layer as a solid color to stall for time until the
1128 // first buffer arrives. Once the first buffer arrives there will always be a
1129 // buffer for the frame even if it is old.
1130 if (!handle.get()) {
1131 if (composition_type_ == HWC::Composition::Invalid) {
1132 composition_type_ = HWC::Composition::SolidColor;
1133 hwc2_hidl_->setLayerCompositionType(
1134 HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1135 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1136 Hwc2::IComposerClient::Color layer_color = {0, 0, 0, 0};
1137 hwc2_hidl_->setLayerColor(HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1138 layer_color);
1139 } else {
1140 // The composition type is already set. Nothing else to do until a
1141 // buffer arrives.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001142 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001143 } else {
Corey Tabaka2251d822017-04-20 16:04:07 -07001144 if (composition_type_ != target_composition_type_) {
1145 composition_type_ = target_composition_type_;
1146 hwc2_hidl_->setLayerCompositionType(
1147 HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1148 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1149 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001150
Corey Tabaka2251d822017-04-20 16:04:07 -07001151 HWC::Error error{HWC::Error::None};
1152 error = hwc2_hidl_->setLayerBuffer(HWC_DISPLAY_PRIMARY,
1153 hardware_composer_layer_, 0, handle,
1154 acquire_fence_.Get());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001155
Corey Tabaka2251d822017-04-20 16:04:07 -07001156 ALOGE_IF(error != HWC::Error::None,
1157 "Layer::Prepare: Error setting layer buffer: %s",
1158 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001159
Corey Tabaka2251d822017-04-20 16:04:07 -07001160 if (!surface_rect_functions_applied_) {
1161 const float float_right = right;
1162 const float float_bottom = bottom;
1163 error = hwc2_hidl_->setLayerSourceCrop(HWC_DISPLAY_PRIMARY,
1164 hardware_composer_layer_,
1165 {0, 0, float_right, float_bottom});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001166
Corey Tabaka2251d822017-04-20 16:04:07 -07001167 ALOGE_IF(error != HWC::Error::None,
1168 "Layer::Prepare: Error setting layer source crop: %s",
1169 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001170
Corey Tabaka2251d822017-04-20 16:04:07 -07001171 surface_rect_functions_applied_ = true;
1172 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001173 }
1174}
1175
1176void Layer::Finish(int release_fence_fd) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001177 IfAnyOf<SourceSurface, SourceBuffer>::Call(
1178 &source_, [release_fence_fd](auto& source) {
1179 source.Finish(LocalHandle(release_fence_fd));
1180 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001181}
1182
Corey Tabaka2251d822017-04-20 16:04:07 -07001183void Layer::Drop() { acquire_fence_.Close(); }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001184
1185} // namespace dvr
1186} // namespace android