blob: 7a78d1f88a29db756900172fae963a84ae0cd1b0 [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_);
484 shared_config_ring_ = DvrVrFlingerConfigRing();
485
486 if (ion_buffer.width() < DvrVrFlingerConfigRing::MemorySize()) {
487 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
500 shared_config_ring_ =
501 DvrVrFlingerConfigRing::Create(buffer_base, ion_buffer.width());
502 ion_buffer.Unlock();
503
504 return 0;
505}
506
507void HardwareComposer::ConfigBufferDeleted() {
508 std::lock_guard<std::mutex> lock(shared_config_mutex_);
509 shared_config_ring_ = DvrVrFlingerConfigRing();
510}
511
512void HardwareComposer::UpdateConfigBuffer() {
513 std::lock_guard<std::mutex> lock(shared_config_mutex_);
514 if (!shared_config_ring_.is_valid())
515 return;
516 // Copy from latest record in shared_config_ring_ to local copy.
Okan Arikan822b7102017-05-08 13:31:34 -0700517 DvrVrFlingerConfig record;
John Bates954796e2017-05-11 11:00:31 -0700518 if (shared_config_ring_.GetNewest(&shared_config_ring_sequence_, &record)) {
519 post_thread_config_ = record;
520 }
521}
522
Corey Tabaka2251d822017-04-20 16:04:07 -0700523int HardwareComposer::PostThreadPollInterruptible(
524 const pdx::LocalHandle& event_fd, int requested_events) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800525 pollfd pfd[2] = {
526 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700527 .fd = event_fd.Get(),
Steven Thomas66747c12017-03-22 18:45:31 -0700528 .events = static_cast<short>(requested_events),
529 .revents = 0,
Steven Thomas050b2c82017-03-06 11:45:16 -0800530 },
531 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700532 .fd = post_thread_event_fd_.Get(),
Steven Thomas050b2c82017-03-06 11:45:16 -0800533 .events = POLLPRI | POLLIN,
534 .revents = 0,
535 },
536 };
537 int ret, error;
538 do {
539 ret = poll(pfd, 2, -1);
540 error = errno;
541 ALOGW_IF(ret < 0,
542 "HardwareComposer::PostThreadPollInterruptible: Error during "
543 "poll(): %s (%d)",
544 strerror(error), error);
545 } while (ret < 0 && error == EINTR);
546
547 if (ret < 0) {
548 return -error;
549 } else if (pfd[0].revents != 0) {
550 return 0;
551 } else if (pfd[1].revents != 0) {
552 ALOGI("VrHwcPost thread interrupted");
553 return kPostThreadInterrupted;
554 } else {
555 return 0;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800556 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800557}
558
559// Reads the value of the display driver wait_pingpong state. Returns 0 or 1
560// (the value of the state) on success or a negative error otherwise.
561// TODO(eieio): This is pretty driver specific, this should be moved to a
562// separate class eventually.
563int HardwareComposer::ReadWaitPPState() {
564 // Gracefully handle when the kernel does not support this feature.
565 if (!primary_display_wait_pp_fd_)
566 return 0;
567
568 const int wait_pp_fd = primary_display_wait_pp_fd_.Get();
569 int ret, error;
570
571 ret = lseek(wait_pp_fd, 0, SEEK_SET);
572 if (ret < 0) {
573 error = errno;
574 ALOGE("HardwareComposer::ReadWaitPPState: Failed to seek wait_pp fd: %s",
575 strerror(error));
576 return -error;
577 }
578
579 char data = -1;
580 ret = read(wait_pp_fd, &data, sizeof(data));
581 if (ret < 0) {
582 error = errno;
583 ALOGE("HardwareComposer::ReadWaitPPState: Failed to read wait_pp state: %s",
584 strerror(error));
585 return -error;
586 }
587
588 switch (data) {
589 case '0':
590 return 0;
591 case '1':
592 return 1;
593 default:
594 ALOGE(
595 "HardwareComposer::ReadWaitPPState: Unexpected value for wait_pp: %d",
596 data);
597 return -EINVAL;
598 }
599}
600
601// Reads the timestamp of the last vsync from the display driver.
602// TODO(eieio): This is pretty driver specific, this should be moved to a
603// separate class eventually.
604int HardwareComposer::ReadVSyncTimestamp(int64_t* timestamp) {
605 const int event_fd = primary_display_vsync_event_fd_.Get();
606 int ret, error;
607
608 // The driver returns data in the form "VSYNC=<timestamp ns>".
609 std::array<char, 32> data;
610 data.fill('\0');
611
612 // Seek back to the beginning of the event file.
613 ret = lseek(event_fd, 0, SEEK_SET);
614 if (ret < 0) {
615 error = errno;
616 ALOGE(
617 "HardwareComposer::ReadVSyncTimestamp: Failed to seek vsync event fd: "
618 "%s",
619 strerror(error));
620 return -error;
621 }
622
623 // Read the vsync event timestamp.
624 ret = read(event_fd, data.data(), data.size());
625 if (ret < 0) {
626 error = errno;
627 ALOGE_IF(
628 error != EAGAIN,
629 "HardwareComposer::ReadVSyncTimestamp: Error while reading timestamp: "
630 "%s",
631 strerror(error));
632 return -error;
633 }
634
635 ret = sscanf(data.data(), "VSYNC=%" PRIu64,
636 reinterpret_cast<uint64_t*>(timestamp));
637 if (ret < 0) {
638 error = errno;
639 ALOGE(
640 "HardwareComposer::ReadVSyncTimestamp: Error while parsing timestamp: "
641 "%s",
642 strerror(error));
643 return -error;
644 }
645
646 return 0;
647}
648
649// Blocks until the next vsync event is signaled by the display driver.
650// TODO(eieio): This is pretty driver specific, this should be moved to a
651// separate class eventually.
Steven Thomas050b2c82017-03-06 11:45:16 -0800652int HardwareComposer::BlockUntilVSync() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700653 // Vsync is signaled by POLLPRI on the fb vsync node.
654 return PostThreadPollInterruptible(primary_display_vsync_event_fd_, POLLPRI);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800655}
656
657// Waits for the next vsync and returns the timestamp of the vsync event. If
658// vsync already passed since the last call, returns the latest vsync timestamp
659// instead of blocking. This method updates the last_vsync_timeout_ in the
660// process.
661//
662// TODO(eieio): This is pretty driver specific, this should be moved to a
663// separate class eventually.
664int HardwareComposer::WaitForVSync(int64_t* timestamp) {
665 int error;
666
667 // Get the current timestamp and decide what to do.
668 while (true) {
669 int64_t current_vsync_timestamp;
670 error = ReadVSyncTimestamp(&current_vsync_timestamp);
671 if (error < 0 && error != -EAGAIN)
672 return error;
673
674 if (error == -EAGAIN) {
675 // Vsync was turned off, wait for the next vsync event.
Steven Thomas050b2c82017-03-06 11:45:16 -0800676 error = BlockUntilVSync();
677 if (error < 0 || error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800678 return error;
679
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800680 // Try again to get the timestamp for this new vsync interval.
681 continue;
682 }
683
684 // Check that we advanced to a later vsync interval.
685 if (TimestampGT(current_vsync_timestamp, last_vsync_timestamp_)) {
686 *timestamp = last_vsync_timestamp_ = current_vsync_timestamp;
687 return 0;
688 }
689
690 // See how close we are to the next expected vsync. If we're within 1ms,
691 // sleep for 1ms and try again.
692 const int64_t ns_per_frame = display_metrics_.vsync_period_ns;
Corey Tabaka2251d822017-04-20 16:04:07 -0700693 const int64_t threshold_ns = 1000000; // 1ms
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800694
695 const int64_t next_vsync_est = last_vsync_timestamp_ + ns_per_frame;
696 const int64_t distance_to_vsync_est = next_vsync_est - GetSystemClockNs();
697
698 if (distance_to_vsync_est > threshold_ns) {
699 // Wait for vsync event notification.
Steven Thomas050b2c82017-03-06 11:45:16 -0800700 error = BlockUntilVSync();
701 if (error < 0 || error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800702 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800703 } else {
Steven Thomas050b2c82017-03-06 11:45:16 -0800704 // Sleep for a short time (1 millisecond) before retrying.
Corey Tabaka2251d822017-04-20 16:04:07 -0700705 error = SleepUntil(GetSystemClockNs() + threshold_ns);
Steven Thomas050b2c82017-03-06 11:45:16 -0800706 if (error < 0 || error == kPostThreadInterrupted)
707 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800708 }
709 }
710}
711
712int HardwareComposer::SleepUntil(int64_t wakeup_timestamp) {
713 const int timer_fd = vsync_sleep_timer_fd_.Get();
714 const itimerspec wakeup_itimerspec = {
715 .it_interval = {.tv_sec = 0, .tv_nsec = 0},
716 .it_value = NsToTimespec(wakeup_timestamp),
717 };
718 int ret =
719 timerfd_settime(timer_fd, TFD_TIMER_ABSTIME, &wakeup_itimerspec, nullptr);
720 int error = errno;
721 if (ret < 0) {
722 ALOGE("HardwareComposer::SleepUntil: Failed to set timerfd: %s",
723 strerror(error));
724 return -error;
725 }
726
Corey Tabaka2251d822017-04-20 16:04:07 -0700727 return PostThreadPollInterruptible(vsync_sleep_timer_fd_, POLLIN);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800728}
729
730void HardwareComposer::PostThread() {
731 // NOLINTNEXTLINE(runtime/int)
Steven Thomas050b2c82017-03-06 11:45:16 -0800732 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>("VrHwcPost"), 0, 0, 0);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800733
Corey Tabaka2251d822017-04-20 16:04:07 -0700734 // Set the scheduler to SCHED_FIFO with high priority. If this fails here
735 // there may have been a startup timing issue between this thread and
736 // performanced. Try again later when this thread becomes active.
737 bool thread_policy_setup =
738 SetThreadPolicy("graphics:high", "/system/performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800739
Steven Thomas050b2c82017-03-06 11:45:16 -0800740#if ENABLE_BACKLIGHT_BRIGHTNESS
741 // TODO(hendrikw): This isn't required at the moment. It's possible that there
742 // is another method to access this when needed.
743 // Open the backlight brightness control sysfs node.
744 backlight_brightness_fd_ = LocalHandle(kBacklightBrightnessSysFile, O_RDWR);
745 ALOGW_IF(!backlight_brightness_fd_,
746 "HardwareComposer: Failed to open backlight brightness control: %s",
747 strerror(errno));
Corey Tabaka2251d822017-04-20 16:04:07 -0700748#endif // ENABLE_BACKLIGHT_BRIGHTNESS
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800749
Steven Thomas050b2c82017-03-06 11:45:16 -0800750 // Open the vsync event node for the primary display.
751 // TODO(eieio): Move this into a platform-specific class.
752 primary_display_vsync_event_fd_ =
753 LocalHandle(kPrimaryDisplayVSyncEventFile, O_RDONLY);
754 ALOGE_IF(!primary_display_vsync_event_fd_,
755 "HardwareComposer: Failed to open vsync event node for primary "
756 "display: %s",
757 strerror(errno));
758
759 // Open the wait pingpong status node for the primary display.
760 // TODO(eieio): Move this into a platform-specific class.
761 primary_display_wait_pp_fd_ =
762 LocalHandle(kPrimaryDisplayWaitPPEventFile, O_RDONLY);
763 ALOGW_IF(
764 !primary_display_wait_pp_fd_,
765 "HardwareComposer: Failed to open wait_pp node for primary display: %s",
766 strerror(errno));
767
768 // Create a timerfd based on CLOCK_MONOTINIC.
769 vsync_sleep_timer_fd_.Reset(timerfd_create(CLOCK_MONOTONIC, 0));
770 LOG_ALWAYS_FATAL_IF(
771 !vsync_sleep_timer_fd_,
772 "HardwareComposer: Failed to create vsync sleep timerfd: %s",
773 strerror(errno));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800774
775 const int64_t ns_per_frame = display_metrics_.vsync_period_ns;
776 const int64_t photon_offset_ns = GetPosePredictionTimeOffset(ns_per_frame);
777
778 // TODO(jbates) Query vblank time from device, when such an API is available.
779 // This value (6.3%) was measured on A00 in low persistence mode.
780 int64_t vblank_ns = ns_per_frame * 63 / 1000;
781 int64_t right_eye_photon_offset_ns = (ns_per_frame - vblank_ns) / 2;
782
783 // Check property for overriding right eye offset value.
784 right_eye_photon_offset_ns =
785 property_get_int64(kRightEyeOffsetProperty, right_eye_photon_offset_ns);
786
Steven Thomas050b2c82017-03-06 11:45:16 -0800787 bool was_running = false;
788
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800789 while (1) {
790 ATRACE_NAME("HardwareComposer::PostThread");
791
John Bates954796e2017-05-11 11:00:31 -0700792 // Check for updated config once per vsync.
793 UpdateConfigBuffer();
794
Corey Tabaka2251d822017-04-20 16:04:07 -0700795 while (post_thread_quiescent_) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800796 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Corey Tabaka2251d822017-04-20 16:04:07 -0700797 ALOGI("HardwareComposer::PostThread: Entering quiescent state.");
798
799 // Tear down resources.
800 OnPostThreadPaused();
801
802 was_running = false;
803 post_thread_resumed_ = false;
804 post_thread_ready_.notify_all();
805
806 if (post_thread_state_ & PostThreadState::Quit) {
807 ALOGI("HardwareComposer::PostThread: Quitting.");
808 return;
Steven Thomas282a5ed2017-02-07 18:07:01 -0800809 }
Corey Tabaka2251d822017-04-20 16:04:07 -0700810
811 post_thread_wait_.wait(lock, [this] { return !post_thread_quiescent_; });
812
813 post_thread_resumed_ = true;
814 post_thread_ready_.notify_all();
815
816 ALOGI("HardwareComposer::PostThread: Exiting quiescent state.");
Steven Thomas050b2c82017-03-06 11:45:16 -0800817 }
818
819 if (!was_running) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700820 // Setup resources.
Steven Thomas050b2c82017-03-06 11:45:16 -0800821 OnPostThreadResumed();
822 was_running = true;
Corey Tabaka2251d822017-04-20 16:04:07 -0700823
824 // Try to setup the scheduler policy if it failed during startup. Only
825 // attempt to do this on transitions from inactive to active to avoid
826 // spamming the system with RPCs and log messages.
827 if (!thread_policy_setup) {
828 thread_policy_setup =
829 SetThreadPolicy("graphics:high", "/system/performance");
830 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800831 }
832
833 int64_t vsync_timestamp = 0;
834 {
835 std::array<char, 128> buf;
836 snprintf(buf.data(), buf.size(), "wait_vsync|vsync=%d|",
837 vsync_count_ + 1);
838 ATRACE_NAME(buf.data());
839
Corey Tabaka2251d822017-04-20 16:04:07 -0700840 const int error = WaitForVSync(&vsync_timestamp);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800841 ALOGE_IF(
842 error < 0,
843 "HardwareComposer::PostThread: Failed to wait for vsync event: %s",
844 strerror(-error));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800845 // Don't bother processing this frame if a pause was requested
Steven Thomas050b2c82017-03-06 11:45:16 -0800846 if (error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800847 continue;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800848 }
849
850 ++vsync_count_;
851
Corey Tabaka2251d822017-04-20 16:04:07 -0700852 const bool layer_config_changed = UpdateLayerConfig();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800853
Okan Arikan822b7102017-05-08 13:31:34 -0700854 // Publish the vsync event.
855 if (vsync_ring_) {
856 DvrVsync vsync;
857 vsync.vsync_count = vsync_count_;
858 vsync.vsync_timestamp_ns = vsync_timestamp;
859 vsync.vsync_left_eye_offset_ns = photon_offset_ns;
860 vsync.vsync_right_eye_offset_ns = right_eye_photon_offset_ns;
861 vsync.vsync_period_ns = ns_per_frame;
862
863 vsync_ring_->Publish(vsync);
864 }
865
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800866 // Signal all of the vsync clients. Because absolute time is used for the
867 // wakeup time below, this can take a little time if necessary.
868 if (vsync_callback_)
Corey Tabaka2251d822017-04-20 16:04:07 -0700869 vsync_callback_(HWC_DISPLAY_PRIMARY, vsync_timestamp,
870 /*frame_time_estimate*/ 0, vsync_count_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800871
872 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700873 // Sleep until shortly before vsync.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800874 ATRACE_NAME("sleep");
875
Corey Tabaka2251d822017-04-20 16:04:07 -0700876 const int64_t display_time_est_ns = vsync_timestamp + ns_per_frame;
877 const int64_t now_ns = GetSystemClockNs();
John Bates954796e2017-05-11 11:00:31 -0700878 const int64_t sleep_time_ns = display_time_est_ns - now_ns -
879 post_thread_config_.frame_post_offset_ns;
880 const int64_t wakeup_time_ns =
881 display_time_est_ns - post_thread_config_.frame_post_offset_ns;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800882
883 ATRACE_INT64("sleep_time_ns", sleep_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800884 if (sleep_time_ns > 0) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700885 int error = SleepUntil(wakeup_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800886 ALOGE_IF(error < 0, "HardwareComposer::PostThread: Failed to sleep: %s",
887 strerror(-error));
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700888 if (error == kPostThreadInterrupted) {
889 if (layer_config_changed) {
890 // If the layer config changed we need to validateDisplay() even if
891 // we're going to drop the frame, to flush the Composer object's
892 // internal command buffer and apply our layer changes.
893 Validate(HWC_DISPLAY_PRIMARY);
894 }
Steven Thomas050b2c82017-03-06 11:45:16 -0800895 continue;
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700896 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800897 }
898 }
899
Corey Tabaka2251d822017-04-20 16:04:07 -0700900 PostLayers();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800901 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800902}
903
Corey Tabaka2251d822017-04-20 16:04:07 -0700904// Checks for changes in the surface stack and updates the layer config to
905// accomodate the new stack.
Steven Thomas050b2c82017-03-06 11:45:16 -0800906bool HardwareComposer::UpdateLayerConfig() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700907 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces;
Steven Thomas050b2c82017-03-06 11:45:16 -0800908 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700909 std::unique_lock<std::mutex> lock(post_thread_mutex_);
910 if (pending_surfaces_.empty())
Steven Thomas050b2c82017-03-06 11:45:16 -0800911 return false;
Corey Tabaka2251d822017-04-20 16:04:07 -0700912
913 surfaces = std::move(pending_surfaces_);
Steven Thomas050b2c82017-03-06 11:45:16 -0800914 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800915
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800916 ATRACE_NAME("UpdateLayerConfig_HwLayers");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800917
Corey Tabaka2251d822017-04-20 16:04:07 -0700918 display_surfaces_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800919
Corey Tabaka2251d822017-04-20 16:04:07 -0700920 Layer* target_layer;
921 size_t layer_index;
922 for (layer_index = 0;
923 layer_index < std::min(surfaces.size(), kMaxHardwareLayers);
924 layer_index++) {
925 // The bottom layer is opaque, other layers blend.
926 HWC::BlendMode blending =
927 layer_index == 0 ? HWC::BlendMode::None : HWC::BlendMode::Coverage;
928 layers_[layer_index].Setup(surfaces[layer_index], blending,
929 display_transform_, HWC::Composition::Device,
930 layer_index);
931 display_surfaces_.push_back(surfaces[layer_index]);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800932 }
933
Corey Tabaka2251d822017-04-20 16:04:07 -0700934 // Clear unused layers.
935 for (size_t i = layer_index; i < kMaxHardwareLayers; i++)
936 layers_[i].Reset();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800937
Corey Tabaka2251d822017-04-20 16:04:07 -0700938 active_layer_count_ = layer_index;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800939 ALOGD_IF(TRACE, "HardwareComposer::UpdateLayerConfig: %zd active layers",
940 active_layer_count_);
941
Corey Tabaka2251d822017-04-20 16:04:07 -0700942 // Any surfaces left over could not be assigned a hardware layer and will
943 // not be displayed.
944 ALOGW_IF(surfaces.size() != display_surfaces_.size(),
945 "HardwareComposer::UpdateLayerConfig: More surfaces than layers: "
946 "pending_surfaces=%zu display_surfaces=%zu",
947 surfaces.size(), display_surfaces_.size());
948
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800949 return true;
950}
951
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800952void HardwareComposer::SetVSyncCallback(VSyncCallback callback) {
953 vsync_callback_ = callback;
954}
955
956void HardwareComposer::HwcRefresh(hwc2_callback_data_t /*data*/,
957 hwc2_display_t /*display*/) {
958 // TODO(eieio): implement invalidate callbacks.
959}
960
961void HardwareComposer::HwcVSync(hwc2_callback_data_t /*data*/,
962 hwc2_display_t /*display*/,
963 int64_t /*timestamp*/) {
964 ATRACE_NAME(__PRETTY_FUNCTION__);
965 // Intentionally empty. HWC may require a callback to be set to enable vsync
966 // signals. We bypass this callback thread by monitoring the vsync event
967 // directly, but signals still need to be enabled.
968}
969
970void HardwareComposer::HwcHotplug(hwc2_callback_data_t /*callbackData*/,
971 hwc2_display_t /*display*/,
972 hwc2_connection_t /*connected*/) {
973 // TODO(eieio): implement display hotplug callbacks.
974}
975
Steven Thomas3cfac282017-02-06 12:29:30 -0800976void HardwareComposer::OnHardwareComposerRefresh() {
977 // TODO(steventhomas): Handle refresh.
978}
979
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800980void HardwareComposer::SetBacklightBrightness(int brightness) {
981 if (backlight_brightness_fd_) {
982 std::array<char, 32> text;
983 const int length = snprintf(text.data(), text.size(), "%d", brightness);
984 write(backlight_brightness_fd_.Get(), text.data(), length);
985 }
986}
987
Corey Tabaka2251d822017-04-20 16:04:07 -0700988void Layer::InitializeGlobals(Hwc2::Composer* hwc2_hidl,
989 const HWCDisplayMetrics* metrics) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800990 hwc2_hidl_ = hwc2_hidl;
991 display_metrics_ = metrics;
992}
993
994void Layer::Reset() {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800995 if (hwc2_hidl_ != nullptr && hardware_composer_layer_) {
996 hwc2_hidl_->destroyLayer(HWC_DISPLAY_PRIMARY, hardware_composer_layer_);
997 hardware_composer_layer_ = 0;
998 }
999
Corey Tabaka2251d822017-04-20 16:04:07 -07001000 z_order_ = 0;
1001 blending_ = HWC::BlendMode::None;
1002 transform_ = HWC::Transform::None;
1003 composition_type_ = HWC::Composition::Invalid;
1004 target_composition_type_ = composition_type_;
1005 source_ = EmptyVariant{};
1006 acquire_fence_.Close();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001007 surface_rect_functions_applied_ = false;
1008}
1009
Corey Tabaka2251d822017-04-20 16:04:07 -07001010void Layer::Setup(const std::shared_ptr<DirectDisplaySurface>& surface,
1011 HWC::BlendMode blending, HWC::Transform transform,
1012 HWC::Composition composition_type, size_t z_order) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001013 Reset();
Corey Tabaka2251d822017-04-20 16:04:07 -07001014 z_order_ = z_order;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001015 blending_ = blending;
1016 transform_ = transform;
Corey Tabaka2251d822017-04-20 16:04:07 -07001017 composition_type_ = HWC::Composition::Invalid;
1018 target_composition_type_ = composition_type;
1019 source_ = SourceSurface{surface};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001020 CommonLayerSetup();
1021}
1022
1023void Layer::Setup(const std::shared_ptr<IonBuffer>& buffer,
Corey Tabaka2251d822017-04-20 16:04:07 -07001024 HWC::BlendMode blending, HWC::Transform transform,
1025 HWC::Composition composition_type, size_t z_order) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001026 Reset();
Corey Tabaka2251d822017-04-20 16:04:07 -07001027 z_order_ = z_order;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001028 blending_ = blending;
1029 transform_ = transform;
Corey Tabaka2251d822017-04-20 16:04:07 -07001030 composition_type_ = HWC::Composition::Invalid;
1031 target_composition_type_ = composition_type;
1032 source_ = SourceBuffer{buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001033 CommonLayerSetup();
1034}
1035
Corey Tabaka2251d822017-04-20 16:04:07 -07001036void Layer::UpdateBuffer(const std::shared_ptr<IonBuffer>& buffer) {
1037 if (source_.is<SourceBuffer>())
1038 std::get<SourceBuffer>(source_) = {buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001039}
1040
Corey Tabaka2251d822017-04-20 16:04:07 -07001041void Layer::SetBlending(HWC::BlendMode blending) { blending_ = blending; }
1042void Layer::SetZOrder(size_t z_order) { z_order_ = z_order; }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001043
1044IonBuffer* Layer::GetBuffer() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001045 struct Visitor {
1046 IonBuffer* operator()(SourceSurface& source) { return source.GetBuffer(); }
1047 IonBuffer* operator()(SourceBuffer& source) { return source.GetBuffer(); }
1048 IonBuffer* operator()(EmptyVariant) { return nullptr; }
1049 };
1050 return source_.Visit(Visitor{});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001051}
1052
1053void Layer::UpdateLayerSettings() {
1054 if (!IsLayerSetup()) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001055 ALOGE(
1056 "HardwareComposer::Layer::UpdateLayerSettings: Attempt to update "
1057 "unused Layer!");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001058 return;
1059 }
1060
Corey Tabaka2251d822017-04-20 16:04:07 -07001061 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001062 hwc2_display_t display = HWC_DISPLAY_PRIMARY;
1063
Corey Tabaka2251d822017-04-20 16:04:07 -07001064 error = hwc2_hidl_->setLayerCompositionType(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001065 display, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001066 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1067 ALOGE_IF(
1068 error != HWC::Error::None,
1069 "Layer::UpdateLayerSettings: Error setting layer composition type: %s",
1070 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001071
Corey Tabaka2251d822017-04-20 16:04:07 -07001072 error = hwc2_hidl_->setLayerBlendMode(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001073 display, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001074 blending_.cast<Hwc2::IComposerClient::BlendMode>());
1075 ALOGE_IF(error != HWC::Error::None,
1076 "Layer::UpdateLayerSettings: Error setting layer blend mode: %s",
1077 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001078
Corey Tabaka2251d822017-04-20 16:04:07 -07001079 // TODO(eieio): Use surface attributes or some other mechanism to control
1080 // the layer display frame.
1081 error = hwc2_hidl_->setLayerDisplayFrame(
1082 display, hardware_composer_layer_,
1083 {0, 0, display_metrics_->width, display_metrics_->height});
1084 ALOGE_IF(error != HWC::Error::None,
1085 "Layer::UpdateLayerSettings: Error setting layer display frame: %s",
1086 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001087
Corey Tabaka2251d822017-04-20 16:04:07 -07001088 error = hwc2_hidl_->setLayerVisibleRegion(
1089 display, hardware_composer_layer_,
1090 {{0, 0, display_metrics_->width, display_metrics_->height}});
1091 ALOGE_IF(error != HWC::Error::None,
1092 "Layer::UpdateLayerSettings: Error setting layer visible region: %s",
1093 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001094
Corey Tabaka2251d822017-04-20 16:04:07 -07001095 error =
1096 hwc2_hidl_->setLayerPlaneAlpha(display, hardware_composer_layer_, 1.0f);
1097 ALOGE_IF(error != HWC::Error::None,
1098 "Layer::UpdateLayerSettings: Error setting layer plane alpha: %s",
1099 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001100
Corey Tabaka2251d822017-04-20 16:04:07 -07001101 error =
1102 hwc2_hidl_->setLayerZOrder(display, hardware_composer_layer_, z_order_);
1103 ALOGE_IF(error != HWC::Error::None,
1104 "Layer::UpdateLayerSettings: Error setting z_ order: %s",
1105 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001106}
1107
1108void Layer::CommonLayerSetup() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001109 HWC::Error error =
1110 hwc2_hidl_->createLayer(HWC_DISPLAY_PRIMARY, &hardware_composer_layer_);
1111 ALOGE_IF(
1112 error != HWC::Error::None,
1113 "Layer::CommonLayerSetup: Failed to create layer on primary display: %s",
1114 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001115 UpdateLayerSettings();
1116}
1117
1118void Layer::Prepare() {
1119 int right, bottom;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -04001120 sp<GraphicBuffer> handle;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001121
Corey Tabaka2251d822017-04-20 16:04:07 -07001122 // Acquire the next buffer according to the type of source.
1123 IfAnyOf<SourceSurface, SourceBuffer>::Call(&source_, [&](auto& source) {
1124 std::tie(right, bottom, handle, acquire_fence_) = source.Acquire();
1125 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001126
Corey Tabaka2251d822017-04-20 16:04:07 -07001127 // When a layer is first setup there may be some time before the first buffer
1128 // arrives. Setup the HWC layer as a solid color to stall for time until the
1129 // first buffer arrives. Once the first buffer arrives there will always be a
1130 // buffer for the frame even if it is old.
1131 if (!handle.get()) {
1132 if (composition_type_ == HWC::Composition::Invalid) {
1133 composition_type_ = HWC::Composition::SolidColor;
1134 hwc2_hidl_->setLayerCompositionType(
1135 HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1136 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1137 Hwc2::IComposerClient::Color layer_color = {0, 0, 0, 0};
1138 hwc2_hidl_->setLayerColor(HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1139 layer_color);
1140 } else {
1141 // The composition type is already set. Nothing else to do until a
1142 // buffer arrives.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001143 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001144 } else {
Corey Tabaka2251d822017-04-20 16:04:07 -07001145 if (composition_type_ != target_composition_type_) {
1146 composition_type_ = target_composition_type_;
1147 hwc2_hidl_->setLayerCompositionType(
1148 HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1149 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1150 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001151
Corey Tabaka2251d822017-04-20 16:04:07 -07001152 HWC::Error error{HWC::Error::None};
1153 error = hwc2_hidl_->setLayerBuffer(HWC_DISPLAY_PRIMARY,
1154 hardware_composer_layer_, 0, handle,
1155 acquire_fence_.Get());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001156
Corey Tabaka2251d822017-04-20 16:04:07 -07001157 ALOGE_IF(error != HWC::Error::None,
1158 "Layer::Prepare: Error setting layer buffer: %s",
1159 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001160
Corey Tabaka2251d822017-04-20 16:04:07 -07001161 if (!surface_rect_functions_applied_) {
1162 const float float_right = right;
1163 const float float_bottom = bottom;
1164 error = hwc2_hidl_->setLayerSourceCrop(HWC_DISPLAY_PRIMARY,
1165 hardware_composer_layer_,
1166 {0, 0, float_right, float_bottom});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001167
Corey Tabaka2251d822017-04-20 16:04:07 -07001168 ALOGE_IF(error != HWC::Error::None,
1169 "Layer::Prepare: Error setting layer source crop: %s",
1170 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001171
Corey Tabaka2251d822017-04-20 16:04:07 -07001172 surface_rect_functions_applied_ = true;
1173 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001174 }
1175}
1176
1177void Layer::Finish(int release_fence_fd) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001178 IfAnyOf<SourceSurface, SourceBuffer>::Call(
1179 &source_, [release_fence_fd](auto& source) {
1180 source.Finish(LocalHandle(release_fence_fd));
1181 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001182}
1183
Corey Tabaka2251d822017-04-20 16:04:07 -07001184void Layer::Drop() { acquire_fence_.Close(); }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001185
1186} // namespace dvr
1187} // namespace android