blob: 9c4278cbea8596d5e73e3d8bde1ac1e2c1d58aa4 [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>
Corey Tabaka0b485c92017-05-19 12:02:58 -070022#include <sstream>
23#include <string>
John Bates954796e2017-05-11 11:00:31 -070024#include <tuple>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080025
Corey Tabaka2251d822017-04-20 16:04:07 -070026#include <dvr/dvr_display_types.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080027#include <dvr/performance_client_api.h>
28#include <private/dvr/clock_ns.h>
Corey Tabaka2251d822017-04-20 16:04:07 -070029#include <private/dvr/ion_buffer.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080030
Steven Thomasb02664d2017-07-26 18:48:28 -070031using android::hardware::Return;
32using android::hardware::Void;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080033using android::pdx::LocalHandle;
Corey Tabaka2251d822017-04-20 16:04:07 -070034using android::pdx::rpc::EmptyVariant;
35using android::pdx::rpc::IfAnyOf;
36
37using namespace std::chrono_literals;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080038
39namespace android {
40namespace dvr {
41
42namespace {
43
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080044const char kBacklightBrightnessSysFile[] =
45 "/sys/class/leds/lcd-backlight/brightness";
46
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080047const char kDvrPerformanceProperty[] = "sys.dvr.performance";
Corey Tabaka451256f2017-08-22 11:59:15 -070048const char kDvrStandaloneProperty[] = "ro.boot.vr";
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080049
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 -070087HardwareComposer::HardwareComposer()
Steven Thomasb02664d2017-07-26 18:48:28 -070088 : initialized_(false), request_display_callback_(nullptr) {}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080089
90HardwareComposer::~HardwareComposer(void) {
Corey Tabaka2251d822017-04-20 16:04:07 -070091 UpdatePostThreadState(PostThreadState::Quit, true);
92 if (post_thread_.joinable())
Steven Thomas050b2c82017-03-06 11:45:16 -080093 post_thread_.join();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080094}
95
Steven Thomasb02664d2017-07-26 18:48:28 -070096bool HardwareComposer::Initialize(
Corey Tabaka2c4aea32017-08-31 20:01:15 -070097 Hwc2::Composer* composer, RequestDisplayCallback request_display_callback) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -080098 if (initialized_) {
99 ALOGE("HardwareComposer::Initialize: already initialized.");
100 return false;
101 }
102
Corey Tabaka451256f2017-08-22 11:59:15 -0700103 is_standalone_device_ = property_get_bool(kDvrStandaloneProperty, false);
104
Steven Thomasb02664d2017-07-26 18:48:28 -0700105 request_display_callback_ = request_display_callback;
106
Corey Tabaka2251d822017-04-20 16:04:07 -0700107 HWC::Error error = HWC::Error::None;
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800108
109 Hwc2::Config config;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700110 error = composer->getActiveConfig(HWC_DISPLAY_PRIMARY, &config);
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800111
Corey Tabaka2251d822017-04-20 16:04:07 -0700112 if (error != HWC::Error::None) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800113 ALOGE("HardwareComposer: Failed to get current display config : %d",
114 config);
115 return false;
116 }
117
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700118 error = GetDisplayMetrics(composer, HWC_DISPLAY_PRIMARY, config,
Steven Thomasb02664d2017-07-26 18:48:28 -0700119 &native_display_metrics_);
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(
123 "HardwareComposer: Failed to get display attributes for current "
124 "configuration : %d",
Corey Tabaka2251d822017-04-20 16:04:07 -0700125 error.value);
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800126 return false;
127 }
128
129 ALOGI(
130 "HardwareComposer: primary display attributes: width=%d height=%d "
131 "vsync_period_ns=%d DPI=%dx%d",
132 native_display_metrics_.width, native_display_metrics_.height,
133 native_display_metrics_.vsync_period_ns, native_display_metrics_.dpi.x,
134 native_display_metrics_.dpi.y);
135
136 // Set the display metrics but never use rotation to avoid the long latency of
137 // rotation processing in hwc.
138 display_transform_ = HWC_TRANSFORM_NONE;
139 display_metrics_ = native_display_metrics_;
140
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700141 // Setup the display metrics used by all Layer instances.
142 Layer::SetDisplayMetrics(native_display_metrics_);
143
Corey Tabaka2251d822017-04-20 16:04:07 -0700144 post_thread_event_fd_.Reset(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
Steven Thomas050b2c82017-03-06 11:45:16 -0800145 LOG_ALWAYS_FATAL_IF(
Corey Tabaka2251d822017-04-20 16:04:07 -0700146 !post_thread_event_fd_,
Steven Thomas050b2c82017-03-06 11:45:16 -0800147 "HardwareComposer: Failed to create interrupt event fd : %s",
148 strerror(errno));
149
150 post_thread_ = std::thread(&HardwareComposer::PostThread, this);
151
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800152 initialized_ = true;
153
154 return initialized_;
155}
156
Steven Thomas050b2c82017-03-06 11:45:16 -0800157void HardwareComposer::Enable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700158 UpdatePostThreadState(PostThreadState::Suspended, false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800159}
160
161void HardwareComposer::Disable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700162 UpdatePostThreadState(PostThreadState::Suspended, true);
Steven Thomas050b2c82017-03-06 11:45:16 -0800163}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800164
Corey Tabaka2251d822017-04-20 16:04:07 -0700165// Update the post thread quiescent state based on idle and suspended inputs.
166void HardwareComposer::UpdatePostThreadState(PostThreadStateType state,
167 bool suspend) {
168 std::unique_lock<std::mutex> lock(post_thread_mutex_);
169
170 // Update the votes in the state variable before evaluating the effective
171 // quiescent state. Any bits set in post_thread_state_ indicate that the post
172 // thread should be suspended.
173 if (suspend) {
174 post_thread_state_ |= state;
175 } else {
176 post_thread_state_ &= ~state;
177 }
178
179 const bool quit = post_thread_state_ & PostThreadState::Quit;
180 const bool effective_suspend = post_thread_state_ != PostThreadState::Active;
181 if (quit) {
182 post_thread_quiescent_ = true;
183 eventfd_write(post_thread_event_fd_.Get(), 1);
184 post_thread_wait_.notify_one();
185 } else if (effective_suspend && !post_thread_quiescent_) {
186 post_thread_quiescent_ = true;
187 eventfd_write(post_thread_event_fd_.Get(), 1);
188 } else if (!effective_suspend && post_thread_quiescent_) {
189 post_thread_quiescent_ = false;
190 eventfd_t value;
191 eventfd_read(post_thread_event_fd_.Get(), &value);
192 post_thread_wait_.notify_one();
193 }
194
195 // Wait until the post thread is in the requested state.
196 post_thread_ready_.wait(lock, [this, effective_suspend] {
197 return effective_suspend != post_thread_resumed_;
198 });
Steven Thomas050b2c82017-03-06 11:45:16 -0800199}
Steven Thomas282a5ed2017-02-07 18:07:01 -0800200
Steven Thomas050b2c82017-03-06 11:45:16 -0800201void HardwareComposer::OnPostThreadResumed() {
Corey Tabaka451256f2017-08-22 11:59:15 -0700202 // Phones create a new composer client on resume and destroy it on pause.
203 // Standalones only create the composer client once and then use SetPowerMode
204 // to control the screen on pause/resume.
205 if (!is_standalone_device_ || !composer_) {
206 composer_.reset(new Hwc2::Composer("default"));
207 composer_callback_ = new ComposerCallback;
208 composer_->registerCallback(composer_callback_);
209 Layer::SetComposer(composer_.get());
210 } else {
211 SetPowerMode(true);
212 }
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700213
Steven Thomas050b2c82017-03-06 11:45:16 -0800214 EnableVsync(true);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800215
Steven Thomas050b2c82017-03-06 11:45:16 -0800216 // TODO(skiazyk): We need to do something about accessing this directly,
217 // supposedly there is a backlight service on the way.
218 // TODO(steventhomas): When we change the backlight setting, will surface
219 // flinger (or something else) set it back to its original value once we give
220 // control of the display back to surface flinger?
221 SetBacklightBrightness(255);
Steven Thomas282a5ed2017-02-07 18:07:01 -0800222
Steven Thomas050b2c82017-03-06 11:45:16 -0800223 // Trigger target-specific performance mode change.
224 property_set(kDvrPerformanceProperty, "performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800225}
226
Steven Thomas050b2c82017-03-06 11:45:16 -0800227void HardwareComposer::OnPostThreadPaused() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700228 retire_fence_fds_.clear();
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700229 layers_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800230
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700231 if (composer_) {
Steven Thomasb02664d2017-07-26 18:48:28 -0700232 EnableVsync(false);
233 }
Steven Thomas050b2c82017-03-06 11:45:16 -0800234
Corey Tabaka451256f2017-08-22 11:59:15 -0700235 if (!is_standalone_device_) {
236 composer_callback_ = nullptr;
237 composer_.reset(nullptr);
238 Layer::SetComposer(nullptr);
239 } else {
240 SetPowerMode(false);
241 }
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700242
Steven Thomas050b2c82017-03-06 11:45:16 -0800243 // Trigger target-specific performance mode change.
244 property_set(kDvrPerformanceProperty, "idle");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800245}
246
Corey Tabaka2251d822017-04-20 16:04:07 -0700247HWC::Error HardwareComposer::Validate(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800248 uint32_t num_types;
249 uint32_t num_requests;
Corey Tabaka2251d822017-04-20 16:04:07 -0700250 HWC::Error error =
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700251 composer_->validateDisplay(display, &num_types, &num_requests);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800252
253 if (error == HWC2_ERROR_HAS_CHANGES) {
254 // TODO(skiazyk): We might need to inspect the requested changes first, but
255 // so far it seems like we shouldn't ever hit a bad state.
256 // error = hwc2_funcs_.accept_display_changes_fn_(hardware_composer_device_,
257 // display);
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700258 error = composer_->acceptDisplayChanges(display);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800259 }
260
261 return error;
262}
263
Steven Thomasb02664d2017-07-26 18:48:28 -0700264HWC::Error HardwareComposer::EnableVsync(bool enabled) {
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700265 return composer_->setVsyncEnabled(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800266 HWC_DISPLAY_PRIMARY,
267 (Hwc2::IComposerClient::Vsync)(enabled ? HWC2_VSYNC_ENABLE
268 : HWC2_VSYNC_DISABLE));
269}
270
Corey Tabaka451256f2017-08-22 11:59:15 -0700271HWC::Error HardwareComposer::SetPowerMode(bool active) {
272 HWC::PowerMode power_mode = active ? HWC::PowerMode::On : HWC::PowerMode::Off;
273 return composer_->setPowerMode(
274 HWC_DISPLAY_PRIMARY, power_mode.cast<Hwc2::IComposerClient::PowerMode>());
275}
276
Corey Tabaka2251d822017-04-20 16:04:07 -0700277HWC::Error HardwareComposer::Present(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800278 int32_t present_fence;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700279 HWC::Error error = composer_->presentDisplay(display, &present_fence);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800280
281 // According to the documentation, this fence is signaled at the time of
282 // vsync/DMA for physical displays.
Corey Tabaka2251d822017-04-20 16:04:07 -0700283 if (error == HWC::Error::None) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800284 ATRACE_INT("HardwareComposer: VsyncFence", present_fence);
285 retire_fence_fds_.emplace_back(present_fence);
286 } else {
287 ATRACE_INT("HardwareComposer: PresentResult", error);
288 }
289
290 return error;
291}
292
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700293HWC::Error HardwareComposer::GetDisplayAttribute(Hwc2::Composer* composer,
Steven Thomasb02664d2017-07-26 18:48:28 -0700294 hwc2_display_t display,
Corey Tabaka2251d822017-04-20 16:04:07 -0700295 hwc2_config_t config,
296 hwc2_attribute_t attribute,
297 int32_t* out_value) const {
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700298 return composer->getDisplayAttribute(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800299 display, config, (Hwc2::IComposerClient::Attribute)attribute, out_value);
300}
301
Corey Tabaka2251d822017-04-20 16:04:07 -0700302HWC::Error HardwareComposer::GetDisplayMetrics(
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700303 Hwc2::Composer* composer, hwc2_display_t display, hwc2_config_t config,
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800304 HWCDisplayMetrics* out_metrics) const {
Corey Tabaka2251d822017-04-20 16:04:07 -0700305 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800306
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700307 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_WIDTH,
Corey Tabaka2251d822017-04-20 16:04:07 -0700308 &out_metrics->width);
309 if (error != HWC::Error::None) {
310 ALOGE(
311 "HardwareComposer::GetDisplayMetrics: Failed to get display width: %s",
312 error.to_string().c_str());
313 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800314 }
315
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700316 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_HEIGHT,
Corey Tabaka2251d822017-04-20 16:04:07 -0700317 &out_metrics->height);
318 if (error != HWC::Error::None) {
319 ALOGE(
320 "HardwareComposer::GetDisplayMetrics: Failed to get display height: %s",
321 error.to_string().c_str());
322 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800323 }
324
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700325 error = GetDisplayAttribute(composer, display, config,
Steven Thomasb02664d2017-07-26 18:48:28 -0700326 HWC2_ATTRIBUTE_VSYNC_PERIOD,
Corey Tabaka2251d822017-04-20 16:04:07 -0700327 &out_metrics->vsync_period_ns);
328 if (error != HWC::Error::None) {
329 ALOGE(
330 "HardwareComposer::GetDisplayMetrics: Failed to get display height: %s",
331 error.to_string().c_str());
332 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800333 }
334
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700335 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_DPI_X,
Corey Tabaka2251d822017-04-20 16:04:07 -0700336 &out_metrics->dpi.x);
337 if (error != HWC::Error::None) {
338 ALOGE(
339 "HardwareComposer::GetDisplayMetrics: Failed to get display DPI X: %s",
340 error.to_string().c_str());
341 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800342 }
343
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700344 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_DPI_Y,
Corey Tabaka2251d822017-04-20 16:04:07 -0700345 &out_metrics->dpi.y);
346 if (error != HWC::Error::None) {
347 ALOGE(
348 "HardwareComposer::GetDisplayMetrics: Failed to get display DPI Y: %s",
349 error.to_string().c_str());
350 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800351 }
352
Corey Tabaka2251d822017-04-20 16:04:07 -0700353 return HWC::Error::None;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800354}
355
Corey Tabaka0b485c92017-05-19 12:02:58 -0700356std::string HardwareComposer::Dump() {
357 std::unique_lock<std::mutex> lock(post_thread_mutex_);
358 std::ostringstream stream;
359
360 stream << "Display metrics: " << display_metrics_.width << "x"
361 << display_metrics_.height << " " << (display_metrics_.dpi.x / 1000.0)
362 << "x" << (display_metrics_.dpi.y / 1000.0) << " dpi @ "
363 << (1000000000.0 / display_metrics_.vsync_period_ns) << " Hz"
364 << std::endl;
365
366 stream << "Post thread resumed: " << post_thread_resumed_ << std::endl;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700367 stream << "Active layers: " << layers_.size() << std::endl;
Corey Tabaka0b485c92017-05-19 12:02:58 -0700368 stream << std::endl;
369
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700370 for (size_t i = 0; i < layers_.size(); i++) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700371 stream << "Layer " << i << ":";
372 stream << " type=" << layers_[i].GetCompositionType().to_string();
373 stream << " surface_id=" << layers_[i].GetSurfaceId();
374 stream << " buffer_id=" << layers_[i].GetBufferId();
375 stream << std::endl;
376 }
377 stream << std::endl;
378
379 if (post_thread_resumed_) {
380 stream << "Hardware Composer Debug Info:" << std::endl;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700381 stream << composer_->dumpDebugInfo();
Corey Tabaka0b485c92017-05-19 12:02:58 -0700382 }
383
384 return stream.str();
385}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800386
Corey Tabaka2251d822017-04-20 16:04:07 -0700387void HardwareComposer::PostLayers() {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800388 ATRACE_NAME("HardwareComposer::PostLayers");
389
390 // Setup the hardware composer layers with current buffers.
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700391 for (auto& layer : layers_) {
392 layer.Prepare();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800393 }
394
Corey Tabaka2251d822017-04-20 16:04:07 -0700395 HWC::Error error = Validate(HWC_DISPLAY_PRIMARY);
396 if (error != HWC::Error::None) {
397 ALOGE("HardwareComposer::PostLayers: Validate failed: %s",
398 error.to_string().c_str());
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700399 return;
400 }
401
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800402 // Now that we have taken in a frame from the application, we have a chance
403 // to drop the frame before passing the frame along to HWC.
404 // If the display driver has become backed up, we detect it here and then
405 // react by skipping this frame to catch up latency.
406 while (!retire_fence_fds_.empty() &&
407 (!retire_fence_fds_.front() ||
408 sync_wait(retire_fence_fds_.front().Get(), 0) == 0)) {
409 // There are only 2 fences in here, no performance problem to shift the
410 // array of ints.
411 retire_fence_fds_.erase(retire_fence_fds_.begin());
412 }
413
414 const bool is_frame_pending = IsFramePendingInDriver();
George Burgess IV353a6f62017-06-26 17:13:09 -0700415 const bool is_fence_pending = static_cast<int32_t>(retire_fence_fds_.size()) >
John Bates954796e2017-05-11 11:00:31 -0700416 post_thread_config_.allowed_pending_fence_count;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800417
418 if (is_fence_pending || is_frame_pending) {
419 ATRACE_INT("frame_skip_count", ++frame_skip_count_);
420
421 ALOGW_IF(is_frame_pending, "Warning: frame already queued, dropping frame");
422 ALOGW_IF(is_fence_pending,
423 "Warning: dropping a frame to catch up with HWC (pending = %zd)",
424 retire_fence_fds_.size());
425
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700426 for (auto& layer : layers_) {
427 layer.Drop();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800428 }
429 return;
430 } else {
431 // Make the transition more obvious in systrace when the frame skip happens
432 // above.
433 ATRACE_INT("frame_skip_count", 0);
434 }
435
Corey Tabaka89bbefc2017-06-06 16:14:21 -0700436#if TRACE > 1
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700437 for (size_t i = 0; i < layers_.size(); i++) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700438 ALOGI("HardwareComposer::PostLayers: layer=%zu buffer_id=%d composition=%s",
439 i, layers_[i].GetBufferId(),
Corey Tabaka2251d822017-04-20 16:04:07 -0700440 layers_[i].GetCompositionType().to_string().c_str());
Corey Tabaka0b485c92017-05-19 12:02:58 -0700441 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800442#endif
443
Corey Tabaka2251d822017-04-20 16:04:07 -0700444 error = Present(HWC_DISPLAY_PRIMARY);
445 if (error != HWC::Error::None) {
446 ALOGE("HardwareComposer::PostLayers: Present failed: %s",
447 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800448 return;
449 }
450
451 std::vector<Hwc2::Layer> out_layers;
452 std::vector<int> out_fences;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700453 error = composer_->getReleaseFences(HWC_DISPLAY_PRIMARY, &out_layers,
454 &out_fences);
Corey Tabaka2251d822017-04-20 16:04:07 -0700455 ALOGE_IF(error != HWC::Error::None,
456 "HardwareComposer::PostLayers: Failed to get release fences: %s",
457 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800458
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700459 // Perform post-frame bookkeeping.
Corey Tabaka2251d822017-04-20 16:04:07 -0700460 uint32_t num_elements = out_layers.size();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800461 for (size_t i = 0; i < num_elements; ++i) {
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700462 for (auto& layer : layers_) {
463 if (layer.GetLayerHandle() == out_layers[i]) {
464 layer.Finish(out_fences[i]);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800465 }
466 }
467 }
468}
469
Steven Thomas050b2c82017-03-06 11:45:16 -0800470void HardwareComposer::SetDisplaySurfaces(
Corey Tabaka2251d822017-04-20 16:04:07 -0700471 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces) {
Jin Qian7480c062017-03-21 00:04:15 +0000472 ALOGI("HardwareComposer::SetDisplaySurfaces: surface count=%zd",
473 surfaces.size());
Corey Tabaka2251d822017-04-20 16:04:07 -0700474 const bool display_idle = surfaces.size() == 0;
475 {
476 std::unique_lock<std::mutex> lock(post_thread_mutex_);
477 pending_surfaces_ = std::move(surfaces);
478 }
479
Corey Tabaka451256f2017-08-22 11:59:15 -0700480 if (request_display_callback_ && (!is_standalone_device_ || !composer_))
Steven Thomas2ddf5672017-06-15 11:38:40 -0700481 request_display_callback_(!display_idle);
482
Corey Tabaka2251d822017-04-20 16:04:07 -0700483 // Set idle state based on whether there are any surfaces to handle.
484 UpdatePostThreadState(PostThreadState::Idle, display_idle);
Steven Thomas050b2c82017-03-06 11:45:16 -0800485}
Jin Qian7480c062017-03-21 00:04:15 +0000486
John Bates954796e2017-05-11 11:00:31 -0700487int HardwareComposer::OnNewGlobalBuffer(DvrGlobalBufferKey key,
488 IonBuffer& ion_buffer) {
Okan Arikan822b7102017-05-08 13:31:34 -0700489 if (key == DvrGlobalBuffers::kVsyncBuffer) {
490 vsync_ring_ = std::make_unique<CPUMappedBroadcastRing<DvrVsyncRing>>(
491 &ion_buffer, CPUUsageMode::WRITE_OFTEN);
492
493 if (vsync_ring_->IsMapped() == false) {
494 return -EPERM;
495 }
496 }
497
498 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700499 return MapConfigBuffer(ion_buffer);
500 }
501
502 return 0;
503}
504
505void HardwareComposer::OnDeletedGlobalBuffer(DvrGlobalBufferKey key) {
Okan Arikan822b7102017-05-08 13:31:34 -0700506 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700507 ConfigBufferDeleted();
508 }
509}
510
511int HardwareComposer::MapConfigBuffer(IonBuffer& ion_buffer) {
512 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700513 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700514
Okan Arikan6f468c62017-05-31 14:48:30 -0700515 if (ion_buffer.width() < DvrConfigRing::MemorySize()) {
John Bates954796e2017-05-11 11:00:31 -0700516 ALOGE("HardwareComposer::MapConfigBuffer: invalid buffer size.");
517 return -EINVAL;
518 }
519
520 void* buffer_base = 0;
521 int result = ion_buffer.Lock(ion_buffer.usage(), 0, 0, ion_buffer.width(),
522 ion_buffer.height(), &buffer_base);
523 if (result != 0) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700524 ALOGE(
525 "HardwareComposer::MapConfigBuffer: Failed to map vrflinger config "
526 "buffer.");
John Bates954796e2017-05-11 11:00:31 -0700527 return -EPERM;
528 }
529
Okan Arikan6f468c62017-05-31 14:48:30 -0700530 shared_config_ring_ = DvrConfigRing::Create(buffer_base, ion_buffer.width());
John Bates954796e2017-05-11 11:00:31 -0700531 ion_buffer.Unlock();
532
533 return 0;
534}
535
536void HardwareComposer::ConfigBufferDeleted() {
537 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700538 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700539}
540
541void HardwareComposer::UpdateConfigBuffer() {
542 std::lock_guard<std::mutex> lock(shared_config_mutex_);
543 if (!shared_config_ring_.is_valid())
544 return;
545 // Copy from latest record in shared_config_ring_ to local copy.
Okan Arikan6f468c62017-05-31 14:48:30 -0700546 DvrConfig record;
John Bates954796e2017-05-11 11:00:31 -0700547 if (shared_config_ring_.GetNewest(&shared_config_ring_sequence_, &record)) {
548 post_thread_config_ = record;
549 }
550}
551
Corey Tabaka2251d822017-04-20 16:04:07 -0700552int HardwareComposer::PostThreadPollInterruptible(
Steven Thomasb02664d2017-07-26 18:48:28 -0700553 const pdx::LocalHandle& event_fd, int requested_events, int timeout_ms) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800554 pollfd pfd[2] = {
555 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700556 .fd = event_fd.Get(),
Steven Thomas66747c12017-03-22 18:45:31 -0700557 .events = static_cast<short>(requested_events),
558 .revents = 0,
Steven Thomas050b2c82017-03-06 11:45:16 -0800559 },
560 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700561 .fd = post_thread_event_fd_.Get(),
Steven Thomas050b2c82017-03-06 11:45:16 -0800562 .events = POLLPRI | POLLIN,
563 .revents = 0,
564 },
565 };
566 int ret, error;
567 do {
Steven Thomasb02664d2017-07-26 18:48:28 -0700568 ret = poll(pfd, 2, timeout_ms);
Steven Thomas050b2c82017-03-06 11:45:16 -0800569 error = errno;
570 ALOGW_IF(ret < 0,
571 "HardwareComposer::PostThreadPollInterruptible: Error during "
572 "poll(): %s (%d)",
573 strerror(error), error);
574 } while (ret < 0 && error == EINTR);
575
576 if (ret < 0) {
577 return -error;
Steven Thomasb02664d2017-07-26 18:48:28 -0700578 } else if (ret == 0) {
579 return -ETIMEDOUT;
Steven Thomas050b2c82017-03-06 11:45:16 -0800580 } else if (pfd[0].revents != 0) {
581 return 0;
582 } else if (pfd[1].revents != 0) {
583 ALOGI("VrHwcPost thread interrupted");
584 return kPostThreadInterrupted;
585 } else {
586 return 0;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800587 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800588}
589
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800590// Waits for the next vsync and returns the timestamp of the vsync event. If
591// vsync already passed since the last call, returns the latest vsync timestamp
Steven Thomasb02664d2017-07-26 18:48:28 -0700592// instead of blocking.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800593int HardwareComposer::WaitForVSync(int64_t* timestamp) {
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700594 int error = PostThreadPollInterruptible(composer_callback_->GetVsyncEventFd(),
595 POLLIN, /*timeout_ms*/ 1000);
Steven Thomasb02664d2017-07-26 18:48:28 -0700596 if (error == kPostThreadInterrupted || error < 0) {
597 return error;
598 } else {
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700599 *timestamp = composer_callback_->GetVsyncTime();
Steven Thomasb02664d2017-07-26 18:48:28 -0700600 return 0;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800601 }
602}
603
604int HardwareComposer::SleepUntil(int64_t wakeup_timestamp) {
605 const int timer_fd = vsync_sleep_timer_fd_.Get();
606 const itimerspec wakeup_itimerspec = {
607 .it_interval = {.tv_sec = 0, .tv_nsec = 0},
608 .it_value = NsToTimespec(wakeup_timestamp),
609 };
610 int ret =
611 timerfd_settime(timer_fd, TFD_TIMER_ABSTIME, &wakeup_itimerspec, nullptr);
612 int error = errno;
613 if (ret < 0) {
614 ALOGE("HardwareComposer::SleepUntil: Failed to set timerfd: %s",
615 strerror(error));
616 return -error;
617 }
618
Corey Tabaka451256f2017-08-22 11:59:15 -0700619 return PostThreadPollInterruptible(vsync_sleep_timer_fd_, POLLIN,
620 /*timeout_ms*/ -1);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800621}
622
623void HardwareComposer::PostThread() {
624 // NOLINTNEXTLINE(runtime/int)
Steven Thomas050b2c82017-03-06 11:45:16 -0800625 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>("VrHwcPost"), 0, 0, 0);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800626
Corey Tabaka2251d822017-04-20 16:04:07 -0700627 // Set the scheduler to SCHED_FIFO with high priority. If this fails here
628 // there may have been a startup timing issue between this thread and
629 // performanced. Try again later when this thread becomes active.
630 bool thread_policy_setup =
631 SetThreadPolicy("graphics:high", "/system/performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800632
Steven Thomas050b2c82017-03-06 11:45:16 -0800633#if ENABLE_BACKLIGHT_BRIGHTNESS
634 // TODO(hendrikw): This isn't required at the moment. It's possible that there
635 // is another method to access this when needed.
636 // Open the backlight brightness control sysfs node.
637 backlight_brightness_fd_ = LocalHandle(kBacklightBrightnessSysFile, O_RDWR);
638 ALOGW_IF(!backlight_brightness_fd_,
639 "HardwareComposer: Failed to open backlight brightness control: %s",
640 strerror(errno));
Corey Tabaka2251d822017-04-20 16:04:07 -0700641#endif // ENABLE_BACKLIGHT_BRIGHTNESS
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800642
Steven Thomas050b2c82017-03-06 11:45:16 -0800643 // Create a timerfd based on CLOCK_MONOTINIC.
644 vsync_sleep_timer_fd_.Reset(timerfd_create(CLOCK_MONOTONIC, 0));
645 LOG_ALWAYS_FATAL_IF(
646 !vsync_sleep_timer_fd_,
647 "HardwareComposer: Failed to create vsync sleep timerfd: %s",
648 strerror(errno));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800649
650 const int64_t ns_per_frame = display_metrics_.vsync_period_ns;
651 const int64_t photon_offset_ns = GetPosePredictionTimeOffset(ns_per_frame);
652
653 // TODO(jbates) Query vblank time from device, when such an API is available.
654 // This value (6.3%) was measured on A00 in low persistence mode.
655 int64_t vblank_ns = ns_per_frame * 63 / 1000;
656 int64_t right_eye_photon_offset_ns = (ns_per_frame - vblank_ns) / 2;
657
658 // Check property for overriding right eye offset value.
659 right_eye_photon_offset_ns =
660 property_get_int64(kRightEyeOffsetProperty, right_eye_photon_offset_ns);
661
Steven Thomas050b2c82017-03-06 11:45:16 -0800662 bool was_running = false;
663
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800664 while (1) {
665 ATRACE_NAME("HardwareComposer::PostThread");
666
John Bates954796e2017-05-11 11:00:31 -0700667 // Check for updated config once per vsync.
668 UpdateConfigBuffer();
669
Corey Tabaka2251d822017-04-20 16:04:07 -0700670 while (post_thread_quiescent_) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800671 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Corey Tabaka2251d822017-04-20 16:04:07 -0700672 ALOGI("HardwareComposer::PostThread: Entering quiescent state.");
673
Corey Tabakadf0b9162017-08-03 17:14:08 -0700674 // Tear down resources if necessary.
675 if (was_running)
676 OnPostThreadPaused();
Corey Tabaka2251d822017-04-20 16:04:07 -0700677
678 was_running = false;
679 post_thread_resumed_ = false;
680 post_thread_ready_.notify_all();
681
682 if (post_thread_state_ & PostThreadState::Quit) {
683 ALOGI("HardwareComposer::PostThread: Quitting.");
684 return;
Steven Thomas282a5ed2017-02-07 18:07:01 -0800685 }
Corey Tabaka2251d822017-04-20 16:04:07 -0700686
687 post_thread_wait_.wait(lock, [this] { return !post_thread_quiescent_; });
688
689 post_thread_resumed_ = true;
690 post_thread_ready_.notify_all();
691
692 ALOGI("HardwareComposer::PostThread: Exiting quiescent state.");
Steven Thomas050b2c82017-03-06 11:45:16 -0800693 }
694
695 if (!was_running) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700696 // Setup resources.
Steven Thomas050b2c82017-03-06 11:45:16 -0800697 OnPostThreadResumed();
698 was_running = true;
Corey Tabaka2251d822017-04-20 16:04:07 -0700699
700 // Try to setup the scheduler policy if it failed during startup. Only
701 // attempt to do this on transitions from inactive to active to avoid
702 // spamming the system with RPCs and log messages.
703 if (!thread_policy_setup) {
704 thread_policy_setup =
705 SetThreadPolicy("graphics:high", "/system/performance");
706 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800707 }
708
709 int64_t vsync_timestamp = 0;
710 {
711 std::array<char, 128> buf;
712 snprintf(buf.data(), buf.size(), "wait_vsync|vsync=%d|",
713 vsync_count_ + 1);
714 ATRACE_NAME(buf.data());
715
Corey Tabaka2251d822017-04-20 16:04:07 -0700716 const int error = WaitForVSync(&vsync_timestamp);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800717 ALOGE_IF(
718 error < 0,
719 "HardwareComposer::PostThread: Failed to wait for vsync event: %s",
720 strerror(-error));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800721 // Don't bother processing this frame if a pause was requested
Steven Thomas050b2c82017-03-06 11:45:16 -0800722 if (error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800723 continue;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800724 }
725
726 ++vsync_count_;
727
Corey Tabaka2251d822017-04-20 16:04:07 -0700728 const bool layer_config_changed = UpdateLayerConfig();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800729
Okan Arikan822b7102017-05-08 13:31:34 -0700730 // Publish the vsync event.
731 if (vsync_ring_) {
732 DvrVsync vsync;
733 vsync.vsync_count = vsync_count_;
734 vsync.vsync_timestamp_ns = vsync_timestamp;
735 vsync.vsync_left_eye_offset_ns = photon_offset_ns;
736 vsync.vsync_right_eye_offset_ns = right_eye_photon_offset_ns;
737 vsync.vsync_period_ns = ns_per_frame;
738
739 vsync_ring_->Publish(vsync);
740 }
741
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800742 // Signal all of the vsync clients. Because absolute time is used for the
743 // wakeup time below, this can take a little time if necessary.
744 if (vsync_callback_)
Corey Tabaka2251d822017-04-20 16:04:07 -0700745 vsync_callback_(HWC_DISPLAY_PRIMARY, vsync_timestamp,
746 /*frame_time_estimate*/ 0, vsync_count_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800747
748 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700749 // Sleep until shortly before vsync.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800750 ATRACE_NAME("sleep");
751
Corey Tabaka2251d822017-04-20 16:04:07 -0700752 const int64_t display_time_est_ns = vsync_timestamp + ns_per_frame;
753 const int64_t now_ns = GetSystemClockNs();
John Bates954796e2017-05-11 11:00:31 -0700754 const int64_t sleep_time_ns = display_time_est_ns - now_ns -
755 post_thread_config_.frame_post_offset_ns;
756 const int64_t wakeup_time_ns =
757 display_time_est_ns - post_thread_config_.frame_post_offset_ns;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800758
759 ATRACE_INT64("sleep_time_ns", sleep_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800760 if (sleep_time_ns > 0) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700761 int error = SleepUntil(wakeup_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800762 ALOGE_IF(error < 0, "HardwareComposer::PostThread: Failed to sleep: %s",
763 strerror(-error));
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700764 if (error == kPostThreadInterrupted) {
765 if (layer_config_changed) {
766 // If the layer config changed we need to validateDisplay() even if
767 // we're going to drop the frame, to flush the Composer object's
768 // internal command buffer and apply our layer changes.
769 Validate(HWC_DISPLAY_PRIMARY);
770 }
Steven Thomas050b2c82017-03-06 11:45:16 -0800771 continue;
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700772 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800773 }
774 }
775
Corey Tabaka2251d822017-04-20 16:04:07 -0700776 PostLayers();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800777 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800778}
779
Corey Tabaka2251d822017-04-20 16:04:07 -0700780// Checks for changes in the surface stack and updates the layer config to
781// accomodate the new stack.
Steven Thomas050b2c82017-03-06 11:45:16 -0800782bool HardwareComposer::UpdateLayerConfig() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700783 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces;
Steven Thomas050b2c82017-03-06 11:45:16 -0800784 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700785 std::unique_lock<std::mutex> lock(post_thread_mutex_);
786 if (pending_surfaces_.empty())
Steven Thomas050b2c82017-03-06 11:45:16 -0800787 return false;
Corey Tabaka2251d822017-04-20 16:04:07 -0700788
789 surfaces = std::move(pending_surfaces_);
Steven Thomas050b2c82017-03-06 11:45:16 -0800790 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800791
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800792 ATRACE_NAME("UpdateLayerConfig_HwLayers");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800793
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700794 // Sort the new direct surface list by z-order to determine the relative order
795 // of the surfaces. This relative order is used for the HWC z-order value to
796 // insulate VrFlinger and HWC z-order semantics from each other.
797 std::sort(surfaces.begin(), surfaces.end(), [](const auto& a, const auto& b) {
798 return a->z_order() < b->z_order();
799 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800800
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700801 // Prepare a new layer stack, pulling in layers from the previous
802 // layer stack that are still active and updating their attributes.
803 std::vector<Layer> layers;
804 size_t layer_index = 0;
805 for (const auto& surface : surfaces) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700806 // The bottom layer is opaque, other layers blend.
807 HWC::BlendMode blending =
808 layer_index == 0 ? HWC::BlendMode::None : HWC::BlendMode::Coverage;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700809
810 // Try to find a layer for this surface in the set of active layers.
811 auto search =
812 std::lower_bound(layers_.begin(), layers_.end(), surface->surface_id());
813 const bool found = search != layers_.end() &&
814 search->GetSurfaceId() == surface->surface_id();
815 if (found) {
816 // Update the attributes of the layer that may have changed.
817 search->SetBlending(blending);
818 search->SetZOrder(layer_index); // Relative z-order.
819
820 // Move the existing layer to the new layer set and remove the empty layer
821 // object from the current set.
822 layers.push_back(std::move(*search));
823 layers_.erase(search);
824 } else {
825 // Insert a layer for the new surface.
826 layers.emplace_back(surface, blending, display_transform_,
827 HWC::Composition::Device, layer_index);
828 }
829
830 ALOGI_IF(
831 TRACE,
832 "HardwareComposer::UpdateLayerConfig: layer_index=%zu surface_id=%d",
833 layer_index, layers[layer_index].GetSurfaceId());
834
835 layer_index++;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800836 }
837
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700838 // Sort the new layer stack by ascending surface id.
839 std::sort(layers.begin(), layers.end());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800840
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700841 // Replace the previous layer set with the new layer set. The destructor of
842 // the previous set will clean up the remaining Layers that are not moved to
843 // the new layer set.
844 layers_ = std::move(layers);
845
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800846 ALOGD_IF(TRACE, "HardwareComposer::UpdateLayerConfig: %zd active layers",
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700847 layers_.size());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800848 return true;
849}
850
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800851void HardwareComposer::SetVSyncCallback(VSyncCallback callback) {
852 vsync_callback_ = callback;
853}
854
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800855void HardwareComposer::SetBacklightBrightness(int brightness) {
856 if (backlight_brightness_fd_) {
857 std::array<char, 32> text;
858 const int length = snprintf(text.data(), text.size(), "%d", brightness);
859 write(backlight_brightness_fd_.Get(), text.data(), length);
860 }
861}
862
Steven Thomasb02664d2017-07-26 18:48:28 -0700863HardwareComposer::ComposerCallback::ComposerCallback() {
864 vsync_event_fd_.Reset(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
Corey Tabaka451256f2017-08-22 11:59:15 -0700865 LOG_ALWAYS_FATAL_IF(!vsync_event_fd_, "Failed to create vsync event fd : %s",
866 strerror(errno));
Steven Thomasb02664d2017-07-26 18:48:28 -0700867}
868
869Return<void> HardwareComposer::ComposerCallback::onHotplug(
Corey Tabaka451256f2017-08-22 11:59:15 -0700870 Hwc2::Display /*display*/, IComposerCallback::Connection /*conn*/) {
Steven Thomasb02664d2017-07-26 18:48:28 -0700871 return Void();
872}
873
874Return<void> HardwareComposer::ComposerCallback::onRefresh(
875 Hwc2::Display /*display*/) {
876 return hardware::Void();
877}
878
Corey Tabaka451256f2017-08-22 11:59:15 -0700879Return<void> HardwareComposer::ComposerCallback::onVsync(Hwc2::Display display,
880 int64_t timestamp) {
Steven Thomasb02664d2017-07-26 18:48:28 -0700881 if (display == HWC_DISPLAY_PRIMARY) {
882 std::lock_guard<std::mutex> lock(vsync_mutex_);
883 vsync_time_ = timestamp;
884 int error = eventfd_write(vsync_event_fd_.Get(), 1);
885 LOG_ALWAYS_FATAL_IF(error != 0, "Failed writing to vsync event fd");
886 }
887 return Void();
888}
889
Corey Tabaka451256f2017-08-22 11:59:15 -0700890const pdx::LocalHandle& HardwareComposer::ComposerCallback::GetVsyncEventFd()
891 const {
Steven Thomasb02664d2017-07-26 18:48:28 -0700892 return vsync_event_fd_;
893}
894
895int64_t HardwareComposer::ComposerCallback::GetVsyncTime() {
896 std::lock_guard<std::mutex> lock(vsync_mutex_);
897 eventfd_t event;
898 eventfd_read(vsync_event_fd_.Get(), &event);
899 LOG_ALWAYS_FATAL_IF(vsync_time_ < 0,
900 "Attempt to read vsync time before vsync event");
901 int64_t return_val = vsync_time_;
902 vsync_time_ = -1;
903 return return_val;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800904}
905
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700906Hwc2::Composer* Layer::composer_{nullptr};
907HWCDisplayMetrics Layer::display_metrics_{0, 0, {0, 0}, 0};
908
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800909void Layer::Reset() {
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700910 if (hardware_composer_layer_) {
911 composer_->destroyLayer(HWC_DISPLAY_PRIMARY, hardware_composer_layer_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800912 hardware_composer_layer_ = 0;
913 }
914
Corey Tabaka2251d822017-04-20 16:04:07 -0700915 z_order_ = 0;
916 blending_ = HWC::BlendMode::None;
917 transform_ = HWC::Transform::None;
918 composition_type_ = HWC::Composition::Invalid;
919 target_composition_type_ = composition_type_;
920 source_ = EmptyVariant{};
921 acquire_fence_.Close();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800922 surface_rect_functions_applied_ = false;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700923 pending_visibility_settings_ = true;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800924}
925
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700926Layer::Layer(const std::shared_ptr<DirectDisplaySurface>& surface,
927 HWC::BlendMode blending, HWC::Transform transform,
928 HWC::Composition composition_type, size_t z_order)
929 : z_order_{z_order},
930 blending_{blending},
931 transform_{transform},
932 target_composition_type_{composition_type},
933 source_{SourceSurface{surface}} {
934 CommonLayerSetup();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800935}
936
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700937Layer::Layer(const std::shared_ptr<IonBuffer>& buffer, HWC::BlendMode blending,
938 HWC::Transform transform, HWC::Composition composition_type,
939 size_t z_order)
940 : z_order_{z_order},
941 blending_{blending},
942 transform_{transform},
943 target_composition_type_{composition_type},
944 source_{SourceBuffer{buffer}} {
945 CommonLayerSetup();
946}
947
948Layer::~Layer() { Reset(); }
949
950Layer::Layer(Layer&& other) { *this = std::move(other); }
951
952Layer& Layer::operator=(Layer&& other) {
953 if (this != &other) {
954 Reset();
955 using std::swap;
956 swap(hardware_composer_layer_, other.hardware_composer_layer_);
957 swap(z_order_, other.z_order_);
958 swap(blending_, other.blending_);
959 swap(transform_, other.transform_);
960 swap(composition_type_, other.composition_type_);
961 swap(target_composition_type_, other.target_composition_type_);
962 swap(source_, other.source_);
963 swap(acquire_fence_, other.acquire_fence_);
964 swap(surface_rect_functions_applied_,
965 other.surface_rect_functions_applied_);
966 swap(pending_visibility_settings_, other.pending_visibility_settings_);
967 }
968 return *this;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800969}
970
Corey Tabaka2251d822017-04-20 16:04:07 -0700971void Layer::UpdateBuffer(const std::shared_ptr<IonBuffer>& buffer) {
972 if (source_.is<SourceBuffer>())
973 std::get<SourceBuffer>(source_) = {buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800974}
975
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700976void Layer::SetBlending(HWC::BlendMode blending) {
977 if (blending_ != blending) {
978 blending_ = blending;
979 pending_visibility_settings_ = true;
980 }
981}
982
983void Layer::SetZOrder(size_t z_order) {
984 if (z_order_ != z_order) {
985 z_order_ = z_order;
986 pending_visibility_settings_ = true;
987 }
988}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800989
990IonBuffer* Layer::GetBuffer() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700991 struct Visitor {
992 IonBuffer* operator()(SourceSurface& source) { return source.GetBuffer(); }
993 IonBuffer* operator()(SourceBuffer& source) { return source.GetBuffer(); }
994 IonBuffer* operator()(EmptyVariant) { return nullptr; }
995 };
996 return source_.Visit(Visitor{});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800997}
998
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700999void Layer::UpdateVisibilitySettings() {
1000 if (pending_visibility_settings_) {
1001 pending_visibility_settings_ = false;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001002
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001003 HWC::Error error;
1004 hwc2_display_t display = HWC_DISPLAY_PRIMARY;
1005
1006 error = composer_->setLayerBlendMode(
1007 display, hardware_composer_layer_,
1008 blending_.cast<Hwc2::IComposerClient::BlendMode>());
1009 ALOGE_IF(error != HWC::Error::None,
1010 "Layer::UpdateLayerSettings: Error setting layer blend mode: %s",
1011 error.to_string().c_str());
1012
1013 error =
1014 composer_->setLayerZOrder(display, hardware_composer_layer_, z_order_);
1015 ALOGE_IF(error != HWC::Error::None,
1016 "Layer::UpdateLayerSettings: Error setting z_ order: %s",
1017 error.to_string().c_str());
1018 }
1019}
1020
1021void Layer::UpdateLayerSettings() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001022 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001023 hwc2_display_t display = HWC_DISPLAY_PRIMARY;
1024
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001025 UpdateVisibilitySettings();
1026
Corey Tabaka2251d822017-04-20 16:04:07 -07001027 // TODO(eieio): Use surface attributes or some other mechanism to control
1028 // the layer display frame.
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001029 error = composer_->setLayerDisplayFrame(
Corey Tabaka2251d822017-04-20 16:04:07 -07001030 display, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001031 {0, 0, display_metrics_.width, display_metrics_.height});
Corey Tabaka2251d822017-04-20 16:04:07 -07001032 ALOGE_IF(error != HWC::Error::None,
1033 "Layer::UpdateLayerSettings: Error setting layer display frame: %s",
1034 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001035
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001036 error = composer_->setLayerVisibleRegion(
Corey Tabaka2251d822017-04-20 16:04:07 -07001037 display, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001038 {{0, 0, display_metrics_.width, display_metrics_.height}});
Corey Tabaka2251d822017-04-20 16:04:07 -07001039 ALOGE_IF(error != HWC::Error::None,
1040 "Layer::UpdateLayerSettings: Error setting layer visible region: %s",
1041 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001042
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001043 error =
1044 composer_->setLayerPlaneAlpha(display, hardware_composer_layer_, 1.0f);
Corey Tabaka2251d822017-04-20 16:04:07 -07001045 ALOGE_IF(error != HWC::Error::None,
1046 "Layer::UpdateLayerSettings: Error setting layer plane alpha: %s",
1047 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001048}
1049
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001050void Layer::CommonLayerSetup() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001051 HWC::Error error =
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001052 composer_->createLayer(HWC_DISPLAY_PRIMARY, &hardware_composer_layer_);
1053 ALOGE_IF(error != HWC::Error::None,
1054 "Layer::CommonLayerSetup: Failed to create layer on primary "
1055 "display: %s",
1056 error.to_string().c_str());
1057 UpdateLayerSettings();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001058}
1059
1060void Layer::Prepare() {
1061 int right, bottom;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -04001062 sp<GraphicBuffer> handle;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001063
Corey Tabaka2251d822017-04-20 16:04:07 -07001064 // Acquire the next buffer according to the type of source.
1065 IfAnyOf<SourceSurface, SourceBuffer>::Call(&source_, [&](auto& source) {
1066 std::tie(right, bottom, handle, acquire_fence_) = source.Acquire();
1067 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001068
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001069 // Update any visibility (blending, z-order) changes that occurred since
1070 // last prepare.
1071 UpdateVisibilitySettings();
1072
1073 // When a layer is first setup there may be some time before the first
1074 // buffer arrives. Setup the HWC layer as a solid color to stall for time
1075 // until the first buffer arrives. Once the first buffer arrives there will
1076 // always be a buffer for the frame even if it is old.
Corey Tabaka2251d822017-04-20 16:04:07 -07001077 if (!handle.get()) {
1078 if (composition_type_ == HWC::Composition::Invalid) {
1079 composition_type_ = HWC::Composition::SolidColor;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001080 composer_->setLayerCompositionType(
Corey Tabaka2251d822017-04-20 16:04:07 -07001081 HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1082 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1083 Hwc2::IComposerClient::Color layer_color = {0, 0, 0, 0};
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001084 composer_->setLayerColor(HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1085 layer_color);
Corey Tabaka2251d822017-04-20 16:04:07 -07001086 } else {
1087 // The composition type is already set. Nothing else to do until a
1088 // buffer arrives.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001089 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001090 } else {
Corey Tabaka2251d822017-04-20 16:04:07 -07001091 if (composition_type_ != target_composition_type_) {
1092 composition_type_ = target_composition_type_;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001093 composer_->setLayerCompositionType(
Corey Tabaka2251d822017-04-20 16:04:07 -07001094 HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1095 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1096 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001097
Corey Tabaka2251d822017-04-20 16:04:07 -07001098 HWC::Error error{HWC::Error::None};
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001099 error =
1100 composer_->setLayerBuffer(HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1101 0, handle, acquire_fence_.Get());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001102
Corey Tabaka2251d822017-04-20 16:04:07 -07001103 ALOGE_IF(error != HWC::Error::None,
1104 "Layer::Prepare: Error setting layer buffer: %s",
1105 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001106
Corey Tabaka2251d822017-04-20 16:04:07 -07001107 if (!surface_rect_functions_applied_) {
1108 const float float_right = right;
1109 const float float_bottom = bottom;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001110 error = composer_->setLayerSourceCrop(HWC_DISPLAY_PRIMARY,
1111 hardware_composer_layer_,
1112 {0, 0, float_right, float_bottom});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001113
Corey Tabaka2251d822017-04-20 16:04:07 -07001114 ALOGE_IF(error != HWC::Error::None,
1115 "Layer::Prepare: Error setting layer source crop: %s",
1116 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001117
Corey Tabaka2251d822017-04-20 16:04:07 -07001118 surface_rect_functions_applied_ = true;
1119 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001120 }
1121}
1122
1123void Layer::Finish(int release_fence_fd) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001124 IfAnyOf<SourceSurface, SourceBuffer>::Call(
1125 &source_, [release_fence_fd](auto& source) {
1126 source.Finish(LocalHandle(release_fence_fd));
1127 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001128}
1129
Corey Tabaka2251d822017-04-20 16:04:07 -07001130void Layer::Drop() { acquire_fence_.Close(); }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001131
1132} // namespace dvr
1133} // namespace android