blob: 5d796dc31e40f67b8df57d7e040c9b1f8773cb60 [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>
Corey Tabakab3732f02017-09-16 00:58:54 -07008#include <stdint.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08009#include <sync/sync.h>
10#include <sys/eventfd.h>
11#include <sys/prctl.h>
12#include <sys/resource.h>
13#include <sys/system_properties.h>
14#include <sys/timerfd.h>
Corey Tabakab3732f02017-09-16 00:58:54 -070015#include <sys/types.h>
Corey Tabaka2251d822017-04-20 16:04:07 -070016#include <time.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080017#include <unistd.h>
18#include <utils/Trace.h>
19
20#include <algorithm>
Corey Tabaka2251d822017-04-20 16:04:07 -070021#include <chrono>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080022#include <functional>
23#include <map>
Corey Tabaka0b485c92017-05-19 12:02:58 -070024#include <sstream>
25#include <string>
John Bates954796e2017-05-11 11:00:31 -070026#include <tuple>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080027
Corey Tabaka2251d822017-04-20 16:04:07 -070028#include <dvr/dvr_display_types.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080029#include <dvr/performance_client_api.h>
30#include <private/dvr/clock_ns.h>
Corey Tabaka2251d822017-04-20 16:04:07 -070031#include <private/dvr/ion_buffer.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080032
Steven Thomasb02664d2017-07-26 18:48:28 -070033using android::hardware::Return;
34using android::hardware::Void;
Corey Tabakab3732f02017-09-16 00:58:54 -070035using android::pdx::ErrorStatus;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080036using android::pdx::LocalHandle;
Corey Tabakab3732f02017-09-16 00:58:54 -070037using android::pdx::Status;
Corey Tabaka2251d822017-04-20 16:04:07 -070038using android::pdx::rpc::EmptyVariant;
39using android::pdx::rpc::IfAnyOf;
40
41using namespace std::chrono_literals;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080042
43namespace android {
44namespace dvr {
45
46namespace {
47
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080048const char kBacklightBrightnessSysFile[] =
49 "/sys/class/leds/lcd-backlight/brightness";
50
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080051const char kDvrPerformanceProperty[] = "sys.dvr.performance";
Corey Tabaka451256f2017-08-22 11:59:15 -070052const char kDvrStandaloneProperty[] = "ro.boot.vr";
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080053
Luke Song4b788322017-03-24 14:17:31 -070054const char kRightEyeOffsetProperty[] = "dvr.right_eye_offset_ns";
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080055
Steven Thomasaf336272018-01-04 17:36:47 -080056// How long to wait after boot finishes before we turn the display off.
57constexpr int kBootFinishedDisplayOffTimeoutSec = 10;
58
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080059// Get time offset from a vsync to when the pose for that vsync should be
60// predicted out to. For example, if scanout gets halfway through the frame
61// at the halfway point between vsyncs, then this could be half the period.
62// With global shutter displays, this should be changed to the offset to when
63// illumination begins. Low persistence adds a frame of latency, so we predict
64// to the center of the next frame.
65inline int64_t GetPosePredictionTimeOffset(int64_t vsync_period_ns) {
66 return (vsync_period_ns * 150) / 100;
67}
68
Corey Tabaka2251d822017-04-20 16:04:07 -070069// Attempts to set the scheduler class and partiton for the current thread.
70// Returns true on success or false on failure.
71bool SetThreadPolicy(const std::string& scheduler_class,
72 const std::string& partition) {
73 int error = dvrSetSchedulerClass(0, scheduler_class.c_str());
74 if (error < 0) {
75 ALOGE(
76 "SetThreadPolicy: Failed to set scheduler class \"%s\" for "
77 "thread_id=%d: %s",
78 scheduler_class.c_str(), gettid(), strerror(-error));
79 return false;
80 }
81 error = dvrSetCpuPartition(0, partition.c_str());
82 if (error < 0) {
83 ALOGE(
84 "SetThreadPolicy: Failed to set cpu partiton \"%s\" for thread_id=%d: "
85 "%s",
86 partition.c_str(), gettid(), strerror(-error));
87 return false;
88 }
89 return true;
90}
91
Corey Tabakab3732f02017-09-16 00:58:54 -070092// Utility to generate scoped tracers with arguments.
93// TODO(eieio): Move/merge this into utils/Trace.h?
94class TraceArgs {
95 public:
96 template <typename... Args>
97 TraceArgs(const char* format, Args&&... args) {
98 std::array<char, 1024> buffer;
99 snprintf(buffer.data(), buffer.size(), format, std::forward<Args>(args)...);
100 atrace_begin(ATRACE_TAG, buffer.data());
101 }
102
103 ~TraceArgs() { atrace_end(ATRACE_TAG); }
104
105 private:
106 TraceArgs(const TraceArgs&) = delete;
107 void operator=(const TraceArgs&) = delete;
108};
109
110// Macro to define a scoped tracer with arguments. Uses PASTE(x, y) macro
111// defined in utils/Trace.h.
112#define TRACE_FORMAT(format, ...) \
113 TraceArgs PASTE(__tracer, __LINE__) { format, ##__VA_ARGS__ }
114
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800115} // anonymous namespace
116
Corey Tabaka2251d822017-04-20 16:04:07 -0700117HardwareComposer::HardwareComposer()
Steven Thomasb02664d2017-07-26 18:48:28 -0700118 : initialized_(false), request_display_callback_(nullptr) {}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800119
120HardwareComposer::~HardwareComposer(void) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700121 UpdatePostThreadState(PostThreadState::Quit, true);
122 if (post_thread_.joinable())
Steven Thomas050b2c82017-03-06 11:45:16 -0800123 post_thread_.join();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800124}
125
Steven Thomasb02664d2017-07-26 18:48:28 -0700126bool HardwareComposer::Initialize(
Steven Thomas6e8f7062017-11-22 14:15:29 -0800127 Hwc2::Composer* composer, hwc2_display_t primary_display_id,
128 RequestDisplayCallback request_display_callback) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800129 if (initialized_) {
130 ALOGE("HardwareComposer::Initialize: already initialized.");
131 return false;
132 }
133
Corey Tabaka451256f2017-08-22 11:59:15 -0700134 is_standalone_device_ = property_get_bool(kDvrStandaloneProperty, false);
135
Steven Thomasb02664d2017-07-26 18:48:28 -0700136 request_display_callback_ = request_display_callback;
137
Corey Tabaka2251d822017-04-20 16:04:07 -0700138 HWC::Error error = HWC::Error::None;
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800139
140 Hwc2::Config config;
Steven Thomas6e8f7062017-11-22 14:15:29 -0800141 error = composer->getActiveConfig(primary_display_id, &config);
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800142
Corey Tabaka2251d822017-04-20 16:04:07 -0700143 if (error != HWC::Error::None) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800144 ALOGE("HardwareComposer: Failed to get current display config : %d",
145 config);
146 return false;
147 }
148
Steven Thomas6e8f7062017-11-22 14:15:29 -0800149 error = GetDisplayMetrics(composer, primary_display_id, config,
Steven Thomasb02664d2017-07-26 18:48:28 -0700150 &native_display_metrics_);
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800151
Corey Tabaka2251d822017-04-20 16:04:07 -0700152 if (error != HWC::Error::None) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800153 ALOGE(
154 "HardwareComposer: Failed to get display attributes for current "
155 "configuration : %d",
Corey Tabaka2251d822017-04-20 16:04:07 -0700156 error.value);
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800157 return false;
158 }
159
160 ALOGI(
161 "HardwareComposer: primary display attributes: width=%d height=%d "
162 "vsync_period_ns=%d DPI=%dx%d",
163 native_display_metrics_.width, native_display_metrics_.height,
164 native_display_metrics_.vsync_period_ns, native_display_metrics_.dpi.x,
165 native_display_metrics_.dpi.y);
166
167 // Set the display metrics but never use rotation to avoid the long latency of
168 // rotation processing in hwc.
169 display_transform_ = HWC_TRANSFORM_NONE;
170 display_metrics_ = native_display_metrics_;
171
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700172 // Setup the display metrics used by all Layer instances.
173 Layer::SetDisplayMetrics(native_display_metrics_);
174
Corey Tabaka2251d822017-04-20 16:04:07 -0700175 post_thread_event_fd_.Reset(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
Steven Thomas050b2c82017-03-06 11:45:16 -0800176 LOG_ALWAYS_FATAL_IF(
Corey Tabaka2251d822017-04-20 16:04:07 -0700177 !post_thread_event_fd_,
Steven Thomas050b2c82017-03-06 11:45:16 -0800178 "HardwareComposer: Failed to create interrupt event fd : %s",
179 strerror(errno));
180
181 post_thread_ = std::thread(&HardwareComposer::PostThread, this);
182
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800183 initialized_ = true;
184
185 return initialized_;
186}
187
Steven Thomas050b2c82017-03-06 11:45:16 -0800188void HardwareComposer::Enable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700189 UpdatePostThreadState(PostThreadState::Suspended, false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800190}
191
192void HardwareComposer::Disable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700193 UpdatePostThreadState(PostThreadState::Suspended, true);
Steven Thomas050b2c82017-03-06 11:45:16 -0800194}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800195
Steven Thomasaf336272018-01-04 17:36:47 -0800196void HardwareComposer::OnBootFinished() {
197 std::lock_guard<std::mutex> lock(post_thread_mutex_);
198 if (boot_finished_)
199 return;
200 boot_finished_ = true;
201 post_thread_wait_.notify_one();
202 if (is_standalone_device_)
203 request_display_callback_(true);
204}
205
Corey Tabaka2251d822017-04-20 16:04:07 -0700206// Update the post thread quiescent state based on idle and suspended inputs.
207void HardwareComposer::UpdatePostThreadState(PostThreadStateType state,
208 bool suspend) {
209 std::unique_lock<std::mutex> lock(post_thread_mutex_);
210
211 // Update the votes in the state variable before evaluating the effective
212 // quiescent state. Any bits set in post_thread_state_ indicate that the post
213 // thread should be suspended.
214 if (suspend) {
215 post_thread_state_ |= state;
216 } else {
217 post_thread_state_ &= ~state;
218 }
219
220 const bool quit = post_thread_state_ & PostThreadState::Quit;
221 const bool effective_suspend = post_thread_state_ != PostThreadState::Active;
222 if (quit) {
223 post_thread_quiescent_ = true;
224 eventfd_write(post_thread_event_fd_.Get(), 1);
225 post_thread_wait_.notify_one();
226 } else if (effective_suspend && !post_thread_quiescent_) {
227 post_thread_quiescent_ = true;
228 eventfd_write(post_thread_event_fd_.Get(), 1);
229 } else if (!effective_suspend && post_thread_quiescent_) {
230 post_thread_quiescent_ = false;
231 eventfd_t value;
232 eventfd_read(post_thread_event_fd_.Get(), &value);
233 post_thread_wait_.notify_one();
234 }
235
236 // Wait until the post thread is in the requested state.
237 post_thread_ready_.wait(lock, [this, effective_suspend] {
238 return effective_suspend != post_thread_resumed_;
239 });
Steven Thomas050b2c82017-03-06 11:45:16 -0800240}
Steven Thomas282a5ed2017-02-07 18:07:01 -0800241
Steven Thomas050b2c82017-03-06 11:45:16 -0800242void HardwareComposer::OnPostThreadResumed() {
Corey Tabaka451256f2017-08-22 11:59:15 -0700243 // Phones create a new composer client on resume and destroy it on pause.
244 // Standalones only create the composer client once and then use SetPowerMode
245 // to control the screen on pause/resume.
246 if (!is_standalone_device_ || !composer_) {
247 composer_.reset(new Hwc2::Composer("default"));
248 composer_callback_ = new ComposerCallback;
249 composer_->registerCallback(composer_callback_);
Steven Thomas6e8f7062017-11-22 14:15:29 -0800250 LOG_ALWAYS_FATAL_IF(!composer_callback_->HasDisplayId(),
251 "Registered composer callback but didn't get primary display");
Corey Tabaka451256f2017-08-22 11:59:15 -0700252 Layer::SetComposer(composer_.get());
Steven Thomas6e8f7062017-11-22 14:15:29 -0800253 Layer::SetDisplayId(composer_callback_->GetDisplayId());
Corey Tabaka451256f2017-08-22 11:59:15 -0700254 } else {
255 SetPowerMode(true);
256 }
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700257
Steven Thomas050b2c82017-03-06 11:45:16 -0800258 EnableVsync(true);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800259
Steven Thomas050b2c82017-03-06 11:45:16 -0800260 // TODO(skiazyk): We need to do something about accessing this directly,
261 // supposedly there is a backlight service on the way.
262 // TODO(steventhomas): When we change the backlight setting, will surface
263 // flinger (or something else) set it back to its original value once we give
264 // control of the display back to surface flinger?
265 SetBacklightBrightness(255);
Steven Thomas282a5ed2017-02-07 18:07:01 -0800266
Steven Thomas050b2c82017-03-06 11:45:16 -0800267 // Trigger target-specific performance mode change.
268 property_set(kDvrPerformanceProperty, "performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800269}
270
Steven Thomas050b2c82017-03-06 11:45:16 -0800271void HardwareComposer::OnPostThreadPaused() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700272 retire_fence_fds_.clear();
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700273 layers_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800274
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700275 if (composer_) {
Steven Thomasb02664d2017-07-26 18:48:28 -0700276 EnableVsync(false);
277 }
Steven Thomas050b2c82017-03-06 11:45:16 -0800278
Corey Tabaka451256f2017-08-22 11:59:15 -0700279 if (!is_standalone_device_) {
280 composer_callback_ = nullptr;
281 composer_.reset(nullptr);
282 Layer::SetComposer(nullptr);
Steven Thomas6e8f7062017-11-22 14:15:29 -0800283 Layer::SetDisplayId(0);
Corey Tabaka451256f2017-08-22 11:59:15 -0700284 } else {
285 SetPowerMode(false);
286 }
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700287
Steven Thomas050b2c82017-03-06 11:45:16 -0800288 // Trigger target-specific performance mode change.
289 property_set(kDvrPerformanceProperty, "idle");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800290}
291
Steven Thomasaf336272018-01-04 17:36:47 -0800292bool HardwareComposer::PostThreadCondWait(std::unique_lock<std::mutex>& lock,
293 int timeout_sec,
294 const std::function<bool()>& pred) {
295 auto pred_with_quit = [&] {
296 return pred() || (post_thread_state_ & PostThreadState::Quit);
297 };
298 if (timeout_sec >= 0) {
299 post_thread_wait_.wait_for(lock, std::chrono::seconds(timeout_sec),
300 pred_with_quit);
301 } else {
302 post_thread_wait_.wait(lock, pred_with_quit);
303 }
304 if (post_thread_state_ & PostThreadState::Quit) {
305 ALOGI("HardwareComposer::PostThread: Quitting.");
306 return true;
307 }
308 return false;
309}
310
Corey Tabaka2251d822017-04-20 16:04:07 -0700311HWC::Error HardwareComposer::Validate(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800312 uint32_t num_types;
313 uint32_t num_requests;
Corey Tabaka2251d822017-04-20 16:04:07 -0700314 HWC::Error error =
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700315 composer_->validateDisplay(display, &num_types, &num_requests);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800316
317 if (error == HWC2_ERROR_HAS_CHANGES) {
318 // TODO(skiazyk): We might need to inspect the requested changes first, but
319 // so far it seems like we shouldn't ever hit a bad state.
320 // error = hwc2_funcs_.accept_display_changes_fn_(hardware_composer_device_,
321 // display);
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700322 error = composer_->acceptDisplayChanges(display);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800323 }
324
325 return error;
326}
327
Steven Thomasb02664d2017-07-26 18:48:28 -0700328HWC::Error HardwareComposer::EnableVsync(bool enabled) {
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700329 return composer_->setVsyncEnabled(
Steven Thomas6e8f7062017-11-22 14:15:29 -0800330 composer_callback_->GetDisplayId(),
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800331 (Hwc2::IComposerClient::Vsync)(enabled ? HWC2_VSYNC_ENABLE
332 : HWC2_VSYNC_DISABLE));
333}
334
Corey Tabaka451256f2017-08-22 11:59:15 -0700335HWC::Error HardwareComposer::SetPowerMode(bool active) {
336 HWC::PowerMode power_mode = active ? HWC::PowerMode::On : HWC::PowerMode::Off;
337 return composer_->setPowerMode(
Steven Thomas6e8f7062017-11-22 14:15:29 -0800338 composer_callback_->GetDisplayId(),
339 power_mode.cast<Hwc2::IComposerClient::PowerMode>());
Corey Tabaka451256f2017-08-22 11:59:15 -0700340}
341
Corey Tabaka2251d822017-04-20 16:04:07 -0700342HWC::Error HardwareComposer::Present(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800343 int32_t present_fence;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700344 HWC::Error error = composer_->presentDisplay(display, &present_fence);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800345
346 // According to the documentation, this fence is signaled at the time of
347 // vsync/DMA for physical displays.
Corey Tabaka2251d822017-04-20 16:04:07 -0700348 if (error == HWC::Error::None) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800349 ATRACE_INT("HardwareComposer: VsyncFence", present_fence);
350 retire_fence_fds_.emplace_back(present_fence);
351 } else {
352 ATRACE_INT("HardwareComposer: PresentResult", error);
353 }
354
355 return error;
356}
357
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700358HWC::Error HardwareComposer::GetDisplayAttribute(Hwc2::Composer* composer,
Steven Thomasb02664d2017-07-26 18:48:28 -0700359 hwc2_display_t display,
Corey Tabaka2251d822017-04-20 16:04:07 -0700360 hwc2_config_t config,
361 hwc2_attribute_t attribute,
362 int32_t* out_value) const {
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700363 return composer->getDisplayAttribute(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800364 display, config, (Hwc2::IComposerClient::Attribute)attribute, out_value);
365}
366
Corey Tabaka2251d822017-04-20 16:04:07 -0700367HWC::Error HardwareComposer::GetDisplayMetrics(
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700368 Hwc2::Composer* composer, hwc2_display_t display, hwc2_config_t config,
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800369 HWCDisplayMetrics* out_metrics) const {
Corey Tabaka2251d822017-04-20 16:04:07 -0700370 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800371
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700372 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_WIDTH,
Corey Tabaka2251d822017-04-20 16:04:07 -0700373 &out_metrics->width);
374 if (error != HWC::Error::None) {
375 ALOGE(
376 "HardwareComposer::GetDisplayMetrics: Failed to get display width: %s",
377 error.to_string().c_str());
378 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800379 }
380
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700381 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_HEIGHT,
Corey Tabaka2251d822017-04-20 16:04:07 -0700382 &out_metrics->height);
383 if (error != HWC::Error::None) {
384 ALOGE(
385 "HardwareComposer::GetDisplayMetrics: Failed to get display height: %s",
386 error.to_string().c_str());
387 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800388 }
389
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700390 error = GetDisplayAttribute(composer, display, config,
Steven Thomasb02664d2017-07-26 18:48:28 -0700391 HWC2_ATTRIBUTE_VSYNC_PERIOD,
Corey Tabaka2251d822017-04-20 16:04:07 -0700392 &out_metrics->vsync_period_ns);
393 if (error != HWC::Error::None) {
394 ALOGE(
395 "HardwareComposer::GetDisplayMetrics: Failed to get display height: %s",
396 error.to_string().c_str());
397 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800398 }
399
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700400 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_DPI_X,
Corey Tabaka2251d822017-04-20 16:04:07 -0700401 &out_metrics->dpi.x);
402 if (error != HWC::Error::None) {
403 ALOGE(
404 "HardwareComposer::GetDisplayMetrics: Failed to get display DPI X: %s",
405 error.to_string().c_str());
406 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800407 }
408
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700409 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_DPI_Y,
Corey Tabaka2251d822017-04-20 16:04:07 -0700410 &out_metrics->dpi.y);
411 if (error != HWC::Error::None) {
412 ALOGE(
413 "HardwareComposer::GetDisplayMetrics: Failed to get display DPI Y: %s",
414 error.to_string().c_str());
415 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800416 }
417
Corey Tabaka2251d822017-04-20 16:04:07 -0700418 return HWC::Error::None;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800419}
420
Corey Tabaka0b485c92017-05-19 12:02:58 -0700421std::string HardwareComposer::Dump() {
422 std::unique_lock<std::mutex> lock(post_thread_mutex_);
423 std::ostringstream stream;
424
425 stream << "Display metrics: " << display_metrics_.width << "x"
426 << display_metrics_.height << " " << (display_metrics_.dpi.x / 1000.0)
427 << "x" << (display_metrics_.dpi.y / 1000.0) << " dpi @ "
428 << (1000000000.0 / display_metrics_.vsync_period_ns) << " Hz"
429 << std::endl;
430
431 stream << "Post thread resumed: " << post_thread_resumed_ << std::endl;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700432 stream << "Active layers: " << layers_.size() << std::endl;
Corey Tabaka0b485c92017-05-19 12:02:58 -0700433 stream << std::endl;
434
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700435 for (size_t i = 0; i < layers_.size(); i++) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700436 stream << "Layer " << i << ":";
437 stream << " type=" << layers_[i].GetCompositionType().to_string();
438 stream << " surface_id=" << layers_[i].GetSurfaceId();
439 stream << " buffer_id=" << layers_[i].GetBufferId();
440 stream << std::endl;
441 }
442 stream << std::endl;
443
444 if (post_thread_resumed_) {
445 stream << "Hardware Composer Debug Info:" << std::endl;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700446 stream << composer_->dumpDebugInfo();
Corey Tabaka0b485c92017-05-19 12:02:58 -0700447 }
448
449 return stream.str();
450}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800451
Corey Tabaka2251d822017-04-20 16:04:07 -0700452void HardwareComposer::PostLayers() {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800453 ATRACE_NAME("HardwareComposer::PostLayers");
454
455 // Setup the hardware composer layers with current buffers.
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700456 for (auto& layer : layers_) {
457 layer.Prepare();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800458 }
459
Steven Thomas6e8f7062017-11-22 14:15:29 -0800460 HWC::Error error = Validate(composer_callback_->GetDisplayId());
Corey Tabaka2251d822017-04-20 16:04:07 -0700461 if (error != HWC::Error::None) {
462 ALOGE("HardwareComposer::PostLayers: Validate failed: %s",
463 error.to_string().c_str());
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700464 return;
465 }
466
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800467 // Now that we have taken in a frame from the application, we have a chance
468 // to drop the frame before passing the frame along to HWC.
469 // If the display driver has become backed up, we detect it here and then
470 // react by skipping this frame to catch up latency.
471 while (!retire_fence_fds_.empty() &&
472 (!retire_fence_fds_.front() ||
473 sync_wait(retire_fence_fds_.front().Get(), 0) == 0)) {
474 // There are only 2 fences in here, no performance problem to shift the
475 // array of ints.
476 retire_fence_fds_.erase(retire_fence_fds_.begin());
477 }
478
George Burgess IV353a6f62017-06-26 17:13:09 -0700479 const bool is_fence_pending = static_cast<int32_t>(retire_fence_fds_.size()) >
John Bates954796e2017-05-11 11:00:31 -0700480 post_thread_config_.allowed_pending_fence_count;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800481
Corey Tabakab3732f02017-09-16 00:58:54 -0700482 if (is_fence_pending) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800483 ATRACE_INT("frame_skip_count", ++frame_skip_count_);
484
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800485 ALOGW_IF(is_fence_pending,
486 "Warning: dropping a frame to catch up with HWC (pending = %zd)",
487 retire_fence_fds_.size());
488
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700489 for (auto& layer : layers_) {
490 layer.Drop();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800491 }
492 return;
493 } else {
494 // Make the transition more obvious in systrace when the frame skip happens
495 // above.
496 ATRACE_INT("frame_skip_count", 0);
497 }
498
Corey Tabaka89bbefc2017-06-06 16:14:21 -0700499#if TRACE > 1
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700500 for (size_t i = 0; i < layers_.size(); i++) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700501 ALOGI("HardwareComposer::PostLayers: layer=%zu buffer_id=%d composition=%s",
502 i, layers_[i].GetBufferId(),
Corey Tabaka2251d822017-04-20 16:04:07 -0700503 layers_[i].GetCompositionType().to_string().c_str());
Corey Tabaka0b485c92017-05-19 12:02:58 -0700504 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800505#endif
506
Steven Thomas6e8f7062017-11-22 14:15:29 -0800507 error = Present(composer_callback_->GetDisplayId());
Corey Tabaka2251d822017-04-20 16:04:07 -0700508 if (error != HWC::Error::None) {
509 ALOGE("HardwareComposer::PostLayers: Present failed: %s",
510 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800511 return;
512 }
513
514 std::vector<Hwc2::Layer> out_layers;
515 std::vector<int> out_fences;
Steven Thomas6e8f7062017-11-22 14:15:29 -0800516 error = composer_->getReleaseFences(composer_callback_->GetDisplayId(),
517 &out_layers, &out_fences);
Corey Tabaka2251d822017-04-20 16:04:07 -0700518 ALOGE_IF(error != HWC::Error::None,
519 "HardwareComposer::PostLayers: Failed to get release fences: %s",
520 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800521
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700522 // Perform post-frame bookkeeping.
Corey Tabaka2251d822017-04-20 16:04:07 -0700523 uint32_t num_elements = out_layers.size();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800524 for (size_t i = 0; i < num_elements; ++i) {
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700525 for (auto& layer : layers_) {
526 if (layer.GetLayerHandle() == out_layers[i]) {
527 layer.Finish(out_fences[i]);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800528 }
529 }
530 }
531}
532
Steven Thomas050b2c82017-03-06 11:45:16 -0800533void HardwareComposer::SetDisplaySurfaces(
Corey Tabaka2251d822017-04-20 16:04:07 -0700534 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces) {
Jin Qian7480c062017-03-21 00:04:15 +0000535 ALOGI("HardwareComposer::SetDisplaySurfaces: surface count=%zd",
536 surfaces.size());
Corey Tabaka2251d822017-04-20 16:04:07 -0700537 const bool display_idle = surfaces.size() == 0;
538 {
539 std::unique_lock<std::mutex> lock(post_thread_mutex_);
540 pending_surfaces_ = std::move(surfaces);
541 }
542
Steven Thomasaf336272018-01-04 17:36:47 -0800543 if (request_display_callback_ && !is_standalone_device_)
Steven Thomas2ddf5672017-06-15 11:38:40 -0700544 request_display_callback_(!display_idle);
545
Corey Tabaka2251d822017-04-20 16:04:07 -0700546 // Set idle state based on whether there are any surfaces to handle.
547 UpdatePostThreadState(PostThreadState::Idle, display_idle);
Steven Thomas050b2c82017-03-06 11:45:16 -0800548}
Jin Qian7480c062017-03-21 00:04:15 +0000549
John Bates954796e2017-05-11 11:00:31 -0700550int HardwareComposer::OnNewGlobalBuffer(DvrGlobalBufferKey key,
551 IonBuffer& ion_buffer) {
Okan Arikan822b7102017-05-08 13:31:34 -0700552 if (key == DvrGlobalBuffers::kVsyncBuffer) {
553 vsync_ring_ = std::make_unique<CPUMappedBroadcastRing<DvrVsyncRing>>(
554 &ion_buffer, CPUUsageMode::WRITE_OFTEN);
555
556 if (vsync_ring_->IsMapped() == false) {
557 return -EPERM;
558 }
559 }
560
561 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700562 return MapConfigBuffer(ion_buffer);
563 }
564
565 return 0;
566}
567
568void HardwareComposer::OnDeletedGlobalBuffer(DvrGlobalBufferKey key) {
Okan Arikan822b7102017-05-08 13:31:34 -0700569 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700570 ConfigBufferDeleted();
571 }
572}
573
574int HardwareComposer::MapConfigBuffer(IonBuffer& ion_buffer) {
575 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700576 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700577
Okan Arikan6f468c62017-05-31 14:48:30 -0700578 if (ion_buffer.width() < DvrConfigRing::MemorySize()) {
John Bates954796e2017-05-11 11:00:31 -0700579 ALOGE("HardwareComposer::MapConfigBuffer: invalid buffer size.");
580 return -EINVAL;
581 }
582
583 void* buffer_base = 0;
584 int result = ion_buffer.Lock(ion_buffer.usage(), 0, 0, ion_buffer.width(),
585 ion_buffer.height(), &buffer_base);
586 if (result != 0) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700587 ALOGE(
588 "HardwareComposer::MapConfigBuffer: Failed to map vrflinger config "
589 "buffer.");
John Bates954796e2017-05-11 11:00:31 -0700590 return -EPERM;
591 }
592
Okan Arikan6f468c62017-05-31 14:48:30 -0700593 shared_config_ring_ = DvrConfigRing::Create(buffer_base, ion_buffer.width());
John Bates954796e2017-05-11 11:00:31 -0700594 ion_buffer.Unlock();
595
596 return 0;
597}
598
599void HardwareComposer::ConfigBufferDeleted() {
600 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700601 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700602}
603
604void HardwareComposer::UpdateConfigBuffer() {
605 std::lock_guard<std::mutex> lock(shared_config_mutex_);
606 if (!shared_config_ring_.is_valid())
607 return;
608 // Copy from latest record in shared_config_ring_ to local copy.
Okan Arikan6f468c62017-05-31 14:48:30 -0700609 DvrConfig record;
John Bates954796e2017-05-11 11:00:31 -0700610 if (shared_config_ring_.GetNewest(&shared_config_ring_sequence_, &record)) {
John Batescc65c3c2017-09-28 14:43:19 -0700611 ALOGI("DvrConfig updated: sequence %u, post offset %d",
612 shared_config_ring_sequence_, record.frame_post_offset_ns);
613 ++shared_config_ring_sequence_;
John Bates954796e2017-05-11 11:00:31 -0700614 post_thread_config_ = record;
615 }
616}
617
Corey Tabaka2251d822017-04-20 16:04:07 -0700618int HardwareComposer::PostThreadPollInterruptible(
Steven Thomasb02664d2017-07-26 18:48:28 -0700619 const pdx::LocalHandle& event_fd, int requested_events, int timeout_ms) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800620 pollfd pfd[2] = {
621 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700622 .fd = event_fd.Get(),
Steven Thomas66747c12017-03-22 18:45:31 -0700623 .events = static_cast<short>(requested_events),
624 .revents = 0,
Steven Thomas050b2c82017-03-06 11:45:16 -0800625 },
626 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700627 .fd = post_thread_event_fd_.Get(),
Steven Thomas050b2c82017-03-06 11:45:16 -0800628 .events = POLLPRI | POLLIN,
629 .revents = 0,
630 },
631 };
632 int ret, error;
633 do {
Steven Thomasb02664d2017-07-26 18:48:28 -0700634 ret = poll(pfd, 2, timeout_ms);
Steven Thomas050b2c82017-03-06 11:45:16 -0800635 error = errno;
636 ALOGW_IF(ret < 0,
637 "HardwareComposer::PostThreadPollInterruptible: Error during "
638 "poll(): %s (%d)",
639 strerror(error), error);
640 } while (ret < 0 && error == EINTR);
641
642 if (ret < 0) {
643 return -error;
Steven Thomasb02664d2017-07-26 18:48:28 -0700644 } else if (ret == 0) {
645 return -ETIMEDOUT;
Steven Thomas050b2c82017-03-06 11:45:16 -0800646 } else if (pfd[0].revents != 0) {
647 return 0;
648 } else if (pfd[1].revents != 0) {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -0700649 ALOGI("VrHwcPost thread interrupted: revents=%x", pfd[1].revents);
Steven Thomas050b2c82017-03-06 11:45:16 -0800650 return kPostThreadInterrupted;
651 } else {
652 return 0;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800653 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800654}
655
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800656// Waits for the next vsync and returns the timestamp of the vsync event. If
657// vsync already passed since the last call, returns the latest vsync timestamp
Steven Thomasb02664d2017-07-26 18:48:28 -0700658// instead of blocking.
Corey Tabakab3732f02017-09-16 00:58:54 -0700659Status<int64_t> HardwareComposer::WaitForVSync() {
660 const int64_t predicted_vsync_time =
661 last_vsync_timestamp_ +
662 display_metrics_.vsync_period_ns * vsync_prediction_interval_;
663 const int error = SleepUntil(predicted_vsync_time);
664 if (error < 0) {
665 ALOGE("HardwareComposer::WaifForVSync:: Failed to sleep: %s",
666 strerror(-error));
Steven Thomasb02664d2017-07-26 18:48:28 -0700667 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800668 }
Corey Tabakab3732f02017-09-16 00:58:54 -0700669 return {predicted_vsync_time};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800670}
671
672int HardwareComposer::SleepUntil(int64_t wakeup_timestamp) {
673 const int timer_fd = vsync_sleep_timer_fd_.Get();
674 const itimerspec wakeup_itimerspec = {
675 .it_interval = {.tv_sec = 0, .tv_nsec = 0},
676 .it_value = NsToTimespec(wakeup_timestamp),
677 };
678 int ret =
679 timerfd_settime(timer_fd, TFD_TIMER_ABSTIME, &wakeup_itimerspec, nullptr);
680 int error = errno;
681 if (ret < 0) {
682 ALOGE("HardwareComposer::SleepUntil: Failed to set timerfd: %s",
683 strerror(error));
684 return -error;
685 }
686
Corey Tabaka451256f2017-08-22 11:59:15 -0700687 return PostThreadPollInterruptible(vsync_sleep_timer_fd_, POLLIN,
688 /*timeout_ms*/ -1);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800689}
690
691void HardwareComposer::PostThread() {
692 // NOLINTNEXTLINE(runtime/int)
Steven Thomas050b2c82017-03-06 11:45:16 -0800693 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>("VrHwcPost"), 0, 0, 0);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800694
Corey Tabaka2251d822017-04-20 16:04:07 -0700695 // Set the scheduler to SCHED_FIFO with high priority. If this fails here
696 // there may have been a startup timing issue between this thread and
697 // performanced. Try again later when this thread becomes active.
698 bool thread_policy_setup =
699 SetThreadPolicy("graphics:high", "/system/performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800700
Steven Thomas050b2c82017-03-06 11:45:16 -0800701#if ENABLE_BACKLIGHT_BRIGHTNESS
702 // TODO(hendrikw): This isn't required at the moment. It's possible that there
703 // is another method to access this when needed.
704 // Open the backlight brightness control sysfs node.
705 backlight_brightness_fd_ = LocalHandle(kBacklightBrightnessSysFile, O_RDWR);
706 ALOGW_IF(!backlight_brightness_fd_,
707 "HardwareComposer: Failed to open backlight brightness control: %s",
708 strerror(errno));
Corey Tabaka2251d822017-04-20 16:04:07 -0700709#endif // ENABLE_BACKLIGHT_BRIGHTNESS
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800710
Steven Thomas050b2c82017-03-06 11:45:16 -0800711 // Create a timerfd based on CLOCK_MONOTINIC.
712 vsync_sleep_timer_fd_.Reset(timerfd_create(CLOCK_MONOTONIC, 0));
713 LOG_ALWAYS_FATAL_IF(
714 !vsync_sleep_timer_fd_,
715 "HardwareComposer: Failed to create vsync sleep timerfd: %s",
716 strerror(errno));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800717
718 const int64_t ns_per_frame = display_metrics_.vsync_period_ns;
719 const int64_t photon_offset_ns = GetPosePredictionTimeOffset(ns_per_frame);
720
721 // TODO(jbates) Query vblank time from device, when such an API is available.
722 // This value (6.3%) was measured on A00 in low persistence mode.
723 int64_t vblank_ns = ns_per_frame * 63 / 1000;
724 int64_t right_eye_photon_offset_ns = (ns_per_frame - vblank_ns) / 2;
725
726 // Check property for overriding right eye offset value.
727 right_eye_photon_offset_ns =
728 property_get_int64(kRightEyeOffsetProperty, right_eye_photon_offset_ns);
729
Steven Thomas050b2c82017-03-06 11:45:16 -0800730 bool was_running = false;
731
Steven Thomasaf336272018-01-04 17:36:47 -0800732 if (is_standalone_device_) {
733 // First, wait until boot finishes.
734 std::unique_lock<std::mutex> lock(post_thread_mutex_);
735 if (PostThreadCondWait(lock, -1, [this] { return boot_finished_; })) {
736 return;
737 }
738
739 // Then, wait until we're either leaving the quiescent state, or the boot
740 // finished display off timeout expires.
741 if (PostThreadCondWait(lock, kBootFinishedDisplayOffTimeoutSec,
742 [this] { return !post_thread_quiescent_; })) {
743 return;
744 }
745
746 LOG_ALWAYS_FATAL_IF(post_thread_state_ & PostThreadState::Suspended,
747 "Vr flinger should own the display by now.");
748 post_thread_resumed_ = true;
749 post_thread_ready_.notify_all();
750 OnPostThreadResumed();
751 was_running = true;
752 }
753
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800754 while (1) {
755 ATRACE_NAME("HardwareComposer::PostThread");
756
John Bates954796e2017-05-11 11:00:31 -0700757 // Check for updated config once per vsync.
758 UpdateConfigBuffer();
759
Corey Tabaka2251d822017-04-20 16:04:07 -0700760 while (post_thread_quiescent_) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800761 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Corey Tabaka2251d822017-04-20 16:04:07 -0700762 ALOGI("HardwareComposer::PostThread: Entering quiescent state.");
763
Corey Tabakadf0b9162017-08-03 17:14:08 -0700764 // Tear down resources if necessary.
765 if (was_running)
766 OnPostThreadPaused();
Corey Tabaka2251d822017-04-20 16:04:07 -0700767
768 was_running = false;
769 post_thread_resumed_ = false;
770 post_thread_ready_.notify_all();
771
Steven Thomasaf336272018-01-04 17:36:47 -0800772 if (PostThreadCondWait(lock, -1,
773 [this] { return !post_thread_quiescent_; })) {
774 // A true return value means we've been asked to quit.
Corey Tabaka2251d822017-04-20 16:04:07 -0700775 return;
Steven Thomas282a5ed2017-02-07 18:07:01 -0800776 }
Corey Tabaka2251d822017-04-20 16:04:07 -0700777
Corey Tabaka2251d822017-04-20 16:04:07 -0700778 post_thread_resumed_ = true;
779 post_thread_ready_.notify_all();
780
781 ALOGI("HardwareComposer::PostThread: Exiting quiescent state.");
Steven Thomas050b2c82017-03-06 11:45:16 -0800782 }
783
784 if (!was_running) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700785 // Setup resources.
Steven Thomas050b2c82017-03-06 11:45:16 -0800786 OnPostThreadResumed();
787 was_running = true;
Corey Tabaka2251d822017-04-20 16:04:07 -0700788
789 // Try to setup the scheduler policy if it failed during startup. Only
790 // attempt to do this on transitions from inactive to active to avoid
791 // spamming the system with RPCs and log messages.
792 if (!thread_policy_setup) {
793 thread_policy_setup =
794 SetThreadPolicy("graphics:high", "/system/performance");
795 }
Corey Tabakab3732f02017-09-16 00:58:54 -0700796
797 // Initialize the last vsync timestamp with the current time. The
798 // predictor below uses this time + the vsync interval in absolute time
799 // units for the initial delay. Once the driver starts reporting vsync the
800 // predictor will sync up with the real vsync.
801 last_vsync_timestamp_ = GetSystemClockNs();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800802 }
803
804 int64_t vsync_timestamp = 0;
805 {
Corey Tabakab3732f02017-09-16 00:58:54 -0700806 TRACE_FORMAT("wait_vsync|vsync=%u;last_timestamp=%" PRId64
807 ";prediction_interval=%d|",
808 vsync_count_ + 1, last_vsync_timestamp_,
809 vsync_prediction_interval_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800810
Corey Tabakab3732f02017-09-16 00:58:54 -0700811 auto status = WaitForVSync();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800812 ALOGE_IF(
Corey Tabakab3732f02017-09-16 00:58:54 -0700813 !status,
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800814 "HardwareComposer::PostThread: Failed to wait for vsync event: %s",
Corey Tabakab3732f02017-09-16 00:58:54 -0700815 status.GetErrorMessage().c_str());
816
817 // If there was an error either sleeping was interrupted due to pausing or
818 // there was an error getting the latest timestamp.
819 if (!status)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800820 continue;
Corey Tabakab3732f02017-09-16 00:58:54 -0700821
822 // Predicted vsync timestamp for this interval. This is stable because we
823 // use absolute time for the wakeup timer.
824 vsync_timestamp = status.get();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800825 }
826
Corey Tabakab3732f02017-09-16 00:58:54 -0700827 // Advance the vsync counter only if the system is keeping up with hardware
828 // vsync to give clients an indication of the delays.
829 if (vsync_prediction_interval_ == 1)
830 ++vsync_count_;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800831
Corey Tabaka2251d822017-04-20 16:04:07 -0700832 const bool layer_config_changed = UpdateLayerConfig();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800833
Okan Arikan822b7102017-05-08 13:31:34 -0700834 // Publish the vsync event.
835 if (vsync_ring_) {
836 DvrVsync vsync;
837 vsync.vsync_count = vsync_count_;
838 vsync.vsync_timestamp_ns = vsync_timestamp;
839 vsync.vsync_left_eye_offset_ns = photon_offset_ns;
840 vsync.vsync_right_eye_offset_ns = right_eye_photon_offset_ns;
841 vsync.vsync_period_ns = ns_per_frame;
842
843 vsync_ring_->Publish(vsync);
844 }
845
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800846 // Signal all of the vsync clients. Because absolute time is used for the
847 // wakeup time below, this can take a little time if necessary.
848 if (vsync_callback_)
Steven Thomas6e8f7062017-11-22 14:15:29 -0800849 vsync_callback_(vsync_timestamp, /*frame_time_estimate*/ 0, vsync_count_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800850
851 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700852 // Sleep until shortly before vsync.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800853 ATRACE_NAME("sleep");
854
Corey Tabaka2251d822017-04-20 16:04:07 -0700855 const int64_t display_time_est_ns = vsync_timestamp + ns_per_frame;
856 const int64_t now_ns = GetSystemClockNs();
John Bates954796e2017-05-11 11:00:31 -0700857 const int64_t sleep_time_ns = display_time_est_ns - now_ns -
858 post_thread_config_.frame_post_offset_ns;
859 const int64_t wakeup_time_ns =
860 display_time_est_ns - post_thread_config_.frame_post_offset_ns;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800861
862 ATRACE_INT64("sleep_time_ns", sleep_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800863 if (sleep_time_ns > 0) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700864 int error = SleepUntil(wakeup_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800865 ALOGE_IF(error < 0, "HardwareComposer::PostThread: Failed to sleep: %s",
866 strerror(-error));
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700867 if (error == kPostThreadInterrupted) {
868 if (layer_config_changed) {
869 // If the layer config changed we need to validateDisplay() even if
870 // we're going to drop the frame, to flush the Composer object's
871 // internal command buffer and apply our layer changes.
Steven Thomas6e8f7062017-11-22 14:15:29 -0800872 Validate(composer_callback_->GetDisplayId());
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700873 }
Steven Thomas050b2c82017-03-06 11:45:16 -0800874 continue;
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700875 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800876 }
877 }
878
Corey Tabakab3732f02017-09-16 00:58:54 -0700879 {
Steven Thomas6e8f7062017-11-22 14:15:29 -0800880 auto status = composer_callback_->GetVsyncTime();
Corey Tabakab3732f02017-09-16 00:58:54 -0700881 if (!status) {
882 ALOGE("HardwareComposer::PostThread: Failed to get VSYNC time: %s",
883 status.GetErrorMessage().c_str());
884 }
885
886 // If we failed to read vsync there might be a problem with the driver.
887 // Since there's nothing we can do just behave as though we didn't get an
888 // updated vsync time and let the prediction continue.
889 const int64_t current_vsync_timestamp =
890 status ? status.get() : last_vsync_timestamp_;
891
892 const bool vsync_delayed =
893 last_vsync_timestamp_ == current_vsync_timestamp;
894 ATRACE_INT("vsync_delayed", vsync_delayed);
895
896 // If vsync was delayed advance the prediction interval and allow the
897 // fence logic in PostLayers() to skip the frame.
898 if (vsync_delayed) {
899 ALOGW(
900 "HardwareComposer::PostThread: VSYNC timestamp did not advance "
901 "since last frame: timestamp=%" PRId64 " prediction_interval=%d",
902 current_vsync_timestamp, vsync_prediction_interval_);
903 vsync_prediction_interval_++;
904 } else {
905 // We have an updated vsync timestamp, reset the prediction interval.
906 last_vsync_timestamp_ = current_vsync_timestamp;
907 vsync_prediction_interval_ = 1;
908 }
909 }
910
Corey Tabaka2251d822017-04-20 16:04:07 -0700911 PostLayers();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800912 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800913}
914
Corey Tabaka2251d822017-04-20 16:04:07 -0700915// Checks for changes in the surface stack and updates the layer config to
916// accomodate the new stack.
Steven Thomas050b2c82017-03-06 11:45:16 -0800917bool HardwareComposer::UpdateLayerConfig() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700918 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces;
Steven Thomas050b2c82017-03-06 11:45:16 -0800919 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700920 std::unique_lock<std::mutex> lock(post_thread_mutex_);
921 if (pending_surfaces_.empty())
Steven Thomas050b2c82017-03-06 11:45:16 -0800922 return false;
Corey Tabaka2251d822017-04-20 16:04:07 -0700923
924 surfaces = std::move(pending_surfaces_);
Steven Thomas050b2c82017-03-06 11:45:16 -0800925 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800926
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800927 ATRACE_NAME("UpdateLayerConfig_HwLayers");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800928
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700929 // Sort the new direct surface list by z-order to determine the relative order
930 // of the surfaces. This relative order is used for the HWC z-order value to
931 // insulate VrFlinger and HWC z-order semantics from each other.
932 std::sort(surfaces.begin(), surfaces.end(), [](const auto& a, const auto& b) {
933 return a->z_order() < b->z_order();
934 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800935
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700936 // Prepare a new layer stack, pulling in layers from the previous
937 // layer stack that are still active and updating their attributes.
938 std::vector<Layer> layers;
939 size_t layer_index = 0;
940 for (const auto& surface : surfaces) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700941 // The bottom layer is opaque, other layers blend.
942 HWC::BlendMode blending =
943 layer_index == 0 ? HWC::BlendMode::None : HWC::BlendMode::Coverage;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700944
945 // Try to find a layer for this surface in the set of active layers.
946 auto search =
947 std::lower_bound(layers_.begin(), layers_.end(), surface->surface_id());
948 const bool found = search != layers_.end() &&
949 search->GetSurfaceId() == surface->surface_id();
950 if (found) {
951 // Update the attributes of the layer that may have changed.
952 search->SetBlending(blending);
953 search->SetZOrder(layer_index); // Relative z-order.
954
955 // Move the existing layer to the new layer set and remove the empty layer
956 // object from the current set.
957 layers.push_back(std::move(*search));
958 layers_.erase(search);
959 } else {
960 // Insert a layer for the new surface.
961 layers.emplace_back(surface, blending, display_transform_,
962 HWC::Composition::Device, layer_index);
963 }
964
965 ALOGI_IF(
966 TRACE,
967 "HardwareComposer::UpdateLayerConfig: layer_index=%zu surface_id=%d",
968 layer_index, layers[layer_index].GetSurfaceId());
969
970 layer_index++;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800971 }
972
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700973 // Sort the new layer stack by ascending surface id.
974 std::sort(layers.begin(), layers.end());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800975
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700976 // Replace the previous layer set with the new layer set. The destructor of
977 // the previous set will clean up the remaining Layers that are not moved to
978 // the new layer set.
979 layers_ = std::move(layers);
980
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800981 ALOGD_IF(TRACE, "HardwareComposer::UpdateLayerConfig: %zd active layers",
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700982 layers_.size());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800983 return true;
984}
985
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800986void HardwareComposer::SetVSyncCallback(VSyncCallback callback) {
987 vsync_callback_ = callback;
988}
989
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800990void HardwareComposer::SetBacklightBrightness(int brightness) {
991 if (backlight_brightness_fd_) {
992 std::array<char, 32> text;
993 const int length = snprintf(text.data(), text.size(), "%d", brightness);
994 write(backlight_brightness_fd_.Get(), text.data(), length);
995 }
996}
997
Steven Thomasb02664d2017-07-26 18:48:28 -0700998Return<void> HardwareComposer::ComposerCallback::onHotplug(
Steven Thomas6e8f7062017-11-22 14:15:29 -0800999 Hwc2::Display display, IComposerCallback::Connection conn) {
1000 // Our first onHotplug callback is always for the primary display.
1001 //
1002 // Ignore any other hotplug callbacks since the primary display is never
1003 // disconnected and we don't care about other displays.
1004 if (!has_display_id_) {
1005 LOG_ALWAYS_FATAL_IF(conn != IComposerCallback::Connection::CONNECTED,
1006 "Initial onHotplug callback should be primary display connected");
1007 has_display_id_ = true;
1008 display_id_ = display;
1009
Corey Tabakab3732f02017-09-16 00:58:54 -07001010 std::array<char, 1024> buffer;
1011 snprintf(buffer.data(), buffer.size(),
1012 "/sys/class/graphics/fb%" PRIu64 "/vsync_event", display);
1013 if (LocalHandle handle{buffer.data(), O_RDONLY}) {
1014 ALOGI(
1015 "HardwareComposer::ComposerCallback::onHotplug: Driver supports "
1016 "vsync_event node for display %" PRIu64,
1017 display);
Steven Thomas6e8f7062017-11-22 14:15:29 -08001018 driver_vsync_event_fd_ = std::move(handle);
Corey Tabakab3732f02017-09-16 00:58:54 -07001019 } else {
1020 ALOGI(
1021 "HardwareComposer::ComposerCallback::onHotplug: Driver does not "
1022 "support vsync_event node for display %" PRIu64,
1023 display);
1024 }
1025 }
1026
Steven Thomasb02664d2017-07-26 18:48:28 -07001027 return Void();
1028}
1029
1030Return<void> HardwareComposer::ComposerCallback::onRefresh(
1031 Hwc2::Display /*display*/) {
1032 return hardware::Void();
1033}
1034
Corey Tabaka451256f2017-08-22 11:59:15 -07001035Return<void> HardwareComposer::ComposerCallback::onVsync(Hwc2::Display display,
1036 int64_t timestamp) {
Steven Thomas6e8f7062017-11-22 14:15:29 -08001037 // Ignore any onVsync callbacks for the non-primary display.
1038 if (has_display_id_ && display == display_id_) {
1039 TRACE_FORMAT("vsync_callback|display=%" PRIu64 ";timestamp=%" PRId64 "|",
1040 display, timestamp);
1041 callback_vsync_timestamp_ = timestamp;
Steven Thomasb02664d2017-07-26 18:48:28 -07001042 }
1043 return Void();
1044}
1045
Steven Thomas6e8f7062017-11-22 14:15:29 -08001046Status<int64_t> HardwareComposer::ComposerCallback::GetVsyncTime() {
Corey Tabakab3732f02017-09-16 00:58:54 -07001047 // See if the driver supports direct vsync events.
Steven Thomas6e8f7062017-11-22 14:15:29 -08001048 LocalHandle& event_fd = driver_vsync_event_fd_;
Corey Tabakab3732f02017-09-16 00:58:54 -07001049 if (!event_fd) {
1050 // Fall back to returning the last timestamp returned by the vsync
1051 // callback.
1052 std::lock_guard<std::mutex> autolock(vsync_mutex_);
Steven Thomas6e8f7062017-11-22 14:15:29 -08001053 return callback_vsync_timestamp_;
Corey Tabakab3732f02017-09-16 00:58:54 -07001054 }
1055
1056 // When the driver supports the vsync_event sysfs node we can use it to
1057 // determine the latest vsync timestamp, even if the HWC callback has been
1058 // delayed.
1059
1060 // The driver returns data in the form "VSYNC=<timestamp ns>".
1061 std::array<char, 32> data;
1062 data.fill('\0');
1063
1064 // Seek back to the beginning of the event file.
1065 int ret = lseek(event_fd.Get(), 0, SEEK_SET);
1066 if (ret < 0) {
1067 const int error = errno;
1068 ALOGE(
1069 "HardwareComposer::ComposerCallback::GetVsyncTime: Failed to seek "
1070 "vsync event fd: %s",
1071 strerror(error));
1072 return ErrorStatus(error);
1073 }
1074
1075 // Read the vsync event timestamp.
1076 ret = read(event_fd.Get(), data.data(), data.size());
1077 if (ret < 0) {
1078 const int error = errno;
1079 ALOGE_IF(error != EAGAIN,
1080 "HardwareComposer::ComposerCallback::GetVsyncTime: Error "
1081 "while reading timestamp: %s",
1082 strerror(error));
1083 return ErrorStatus(error);
1084 }
1085
1086 int64_t timestamp;
1087 ret = sscanf(data.data(), "VSYNC=%" PRIu64,
1088 reinterpret_cast<uint64_t*>(&timestamp));
1089 if (ret < 0) {
1090 const int error = errno;
1091 ALOGE(
1092 "HardwareComposer::ComposerCallback::GetVsyncTime: Error while "
1093 "parsing timestamp: %s",
1094 strerror(error));
1095 return ErrorStatus(error);
1096 }
1097
1098 return {timestamp};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001099}
1100
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001101Hwc2::Composer* Layer::composer_{nullptr};
1102HWCDisplayMetrics Layer::display_metrics_{0, 0, {0, 0}, 0};
Steven Thomas6e8f7062017-11-22 14:15:29 -08001103hwc2_display_t Layer::display_id_{0};
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001104
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001105void Layer::Reset() {
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001106 if (hardware_composer_layer_) {
Steven Thomas6e8f7062017-11-22 14:15:29 -08001107 composer_->destroyLayer(display_id_, hardware_composer_layer_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001108 hardware_composer_layer_ = 0;
1109 }
1110
Corey Tabaka2251d822017-04-20 16:04:07 -07001111 z_order_ = 0;
1112 blending_ = HWC::BlendMode::None;
1113 transform_ = HWC::Transform::None;
1114 composition_type_ = HWC::Composition::Invalid;
1115 target_composition_type_ = composition_type_;
1116 source_ = EmptyVariant{};
1117 acquire_fence_.Close();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001118 surface_rect_functions_applied_ = false;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001119 pending_visibility_settings_ = true;
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001120 cached_buffer_map_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001121}
1122
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001123Layer::Layer(const std::shared_ptr<DirectDisplaySurface>& surface,
1124 HWC::BlendMode blending, HWC::Transform transform,
1125 HWC::Composition composition_type, size_t z_order)
1126 : z_order_{z_order},
1127 blending_{blending},
1128 transform_{transform},
1129 target_composition_type_{composition_type},
1130 source_{SourceSurface{surface}} {
1131 CommonLayerSetup();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001132}
1133
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001134Layer::Layer(const std::shared_ptr<IonBuffer>& buffer, HWC::BlendMode blending,
1135 HWC::Transform transform, HWC::Composition composition_type,
1136 size_t z_order)
1137 : z_order_{z_order},
1138 blending_{blending},
1139 transform_{transform},
1140 target_composition_type_{composition_type},
1141 source_{SourceBuffer{buffer}} {
1142 CommonLayerSetup();
1143}
1144
1145Layer::~Layer() { Reset(); }
1146
1147Layer::Layer(Layer&& other) { *this = std::move(other); }
1148
1149Layer& Layer::operator=(Layer&& other) {
1150 if (this != &other) {
1151 Reset();
1152 using std::swap;
1153 swap(hardware_composer_layer_, other.hardware_composer_layer_);
1154 swap(z_order_, other.z_order_);
1155 swap(blending_, other.blending_);
1156 swap(transform_, other.transform_);
1157 swap(composition_type_, other.composition_type_);
1158 swap(target_composition_type_, other.target_composition_type_);
1159 swap(source_, other.source_);
1160 swap(acquire_fence_, other.acquire_fence_);
1161 swap(surface_rect_functions_applied_,
1162 other.surface_rect_functions_applied_);
1163 swap(pending_visibility_settings_, other.pending_visibility_settings_);
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001164 swap(cached_buffer_map_, other.cached_buffer_map_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001165 }
1166 return *this;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001167}
1168
Corey Tabaka2251d822017-04-20 16:04:07 -07001169void Layer::UpdateBuffer(const std::shared_ptr<IonBuffer>& buffer) {
1170 if (source_.is<SourceBuffer>())
1171 std::get<SourceBuffer>(source_) = {buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001172}
1173
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001174void Layer::SetBlending(HWC::BlendMode blending) {
1175 if (blending_ != blending) {
1176 blending_ = blending;
1177 pending_visibility_settings_ = true;
1178 }
1179}
1180
1181void Layer::SetZOrder(size_t z_order) {
1182 if (z_order_ != z_order) {
1183 z_order_ = z_order;
1184 pending_visibility_settings_ = true;
1185 }
1186}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001187
1188IonBuffer* Layer::GetBuffer() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001189 struct Visitor {
1190 IonBuffer* operator()(SourceSurface& source) { return source.GetBuffer(); }
1191 IonBuffer* operator()(SourceBuffer& source) { return source.GetBuffer(); }
1192 IonBuffer* operator()(EmptyVariant) { return nullptr; }
1193 };
1194 return source_.Visit(Visitor{});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001195}
1196
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001197void Layer::UpdateVisibilitySettings() {
1198 if (pending_visibility_settings_) {
1199 pending_visibility_settings_ = false;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001200
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001201 HWC::Error error;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001202
1203 error = composer_->setLayerBlendMode(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001204 display_id_, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001205 blending_.cast<Hwc2::IComposerClient::BlendMode>());
1206 ALOGE_IF(error != HWC::Error::None,
1207 "Layer::UpdateLayerSettings: Error setting layer blend mode: %s",
1208 error.to_string().c_str());
1209
Steven Thomas6e8f7062017-11-22 14:15:29 -08001210 error = composer_->setLayerZOrder(display_id_, hardware_composer_layer_,
1211 z_order_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001212 ALOGE_IF(error != HWC::Error::None,
1213 "Layer::UpdateLayerSettings: Error setting z_ order: %s",
1214 error.to_string().c_str());
1215 }
1216}
1217
1218void Layer::UpdateLayerSettings() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001219 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001220
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001221 UpdateVisibilitySettings();
1222
Corey Tabaka2251d822017-04-20 16:04:07 -07001223 // TODO(eieio): Use surface attributes or some other mechanism to control
1224 // the layer display frame.
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001225 error = composer_->setLayerDisplayFrame(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001226 display_id_, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001227 {0, 0, display_metrics_.width, display_metrics_.height});
Corey Tabaka2251d822017-04-20 16:04:07 -07001228 ALOGE_IF(error != HWC::Error::None,
1229 "Layer::UpdateLayerSettings: Error setting layer display frame: %s",
1230 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001231
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001232 error = composer_->setLayerVisibleRegion(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001233 display_id_, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001234 {{0, 0, display_metrics_.width, display_metrics_.height}});
Corey Tabaka2251d822017-04-20 16:04:07 -07001235 ALOGE_IF(error != HWC::Error::None,
1236 "Layer::UpdateLayerSettings: Error setting layer visible region: %s",
1237 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001238
Steven Thomas6e8f7062017-11-22 14:15:29 -08001239 error = composer_->setLayerPlaneAlpha(display_id_, hardware_composer_layer_,
1240 1.0f);
Corey Tabaka2251d822017-04-20 16:04:07 -07001241 ALOGE_IF(error != HWC::Error::None,
1242 "Layer::UpdateLayerSettings: Error setting layer plane alpha: %s",
1243 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001244}
1245
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001246void Layer::CommonLayerSetup() {
Steven Thomas6e8f7062017-11-22 14:15:29 -08001247 HWC::Error error = composer_->createLayer(display_id_,
1248 &hardware_composer_layer_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001249 ALOGE_IF(error != HWC::Error::None,
1250 "Layer::CommonLayerSetup: Failed to create layer on primary "
1251 "display: %s",
1252 error.to_string().c_str());
1253 UpdateLayerSettings();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001254}
1255
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001256bool Layer::CheckAndUpdateCachedBuffer(std::size_t slot, int buffer_id) {
1257 auto search = cached_buffer_map_.find(slot);
1258 if (search != cached_buffer_map_.end() && search->second == buffer_id)
1259 return true;
1260
1261 // Assign or update the buffer slot.
1262 if (buffer_id >= 0)
1263 cached_buffer_map_[slot] = buffer_id;
1264 return false;
1265}
1266
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001267void Layer::Prepare() {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001268 int right, bottom, id;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -04001269 sp<GraphicBuffer> handle;
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001270 std::size_t slot;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001271
Corey Tabaka2251d822017-04-20 16:04:07 -07001272 // Acquire the next buffer according to the type of source.
1273 IfAnyOf<SourceSurface, SourceBuffer>::Call(&source_, [&](auto& source) {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001274 std::tie(right, bottom, id, handle, acquire_fence_, slot) =
1275 source.Acquire();
Corey Tabaka2251d822017-04-20 16:04:07 -07001276 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001277
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001278 TRACE_FORMAT("Layer::Prepare|buffer_id=%d;slot=%zu|", id, slot);
1279
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001280 // Update any visibility (blending, z-order) changes that occurred since
1281 // last prepare.
1282 UpdateVisibilitySettings();
1283
1284 // When a layer is first setup there may be some time before the first
1285 // buffer arrives. Setup the HWC layer as a solid color to stall for time
1286 // until the first buffer arrives. Once the first buffer arrives there will
1287 // always be a buffer for the frame even if it is old.
Corey Tabaka2251d822017-04-20 16:04:07 -07001288 if (!handle.get()) {
1289 if (composition_type_ == HWC::Composition::Invalid) {
1290 composition_type_ = HWC::Composition::SolidColor;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001291 composer_->setLayerCompositionType(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001292 display_id_, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001293 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1294 Hwc2::IComposerClient::Color layer_color = {0, 0, 0, 0};
Steven Thomas6e8f7062017-11-22 14:15:29 -08001295 composer_->setLayerColor(display_id_, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001296 layer_color);
Corey Tabaka2251d822017-04-20 16:04:07 -07001297 } else {
1298 // The composition type is already set. Nothing else to do until a
1299 // buffer arrives.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001300 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001301 } else {
Corey Tabaka2251d822017-04-20 16:04:07 -07001302 if (composition_type_ != target_composition_type_) {
1303 composition_type_ = target_composition_type_;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001304 composer_->setLayerCompositionType(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001305 display_id_, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001306 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1307 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001308
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001309 // See if the HWC cache already has this buffer.
1310 const bool cached = CheckAndUpdateCachedBuffer(slot, id);
1311 if (cached)
1312 handle = nullptr;
1313
Corey Tabaka2251d822017-04-20 16:04:07 -07001314 HWC::Error error{HWC::Error::None};
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001315 error =
Steven Thomas6e8f7062017-11-22 14:15:29 -08001316 composer_->setLayerBuffer(display_id_, hardware_composer_layer_,
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001317 slot, handle, acquire_fence_.Get());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001318
Corey Tabaka2251d822017-04-20 16:04:07 -07001319 ALOGE_IF(error != HWC::Error::None,
1320 "Layer::Prepare: Error setting layer buffer: %s",
1321 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001322
Corey Tabaka2251d822017-04-20 16:04:07 -07001323 if (!surface_rect_functions_applied_) {
1324 const float float_right = right;
1325 const float float_bottom = bottom;
Steven Thomas6e8f7062017-11-22 14:15:29 -08001326 error = composer_->setLayerSourceCrop(display_id_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001327 hardware_composer_layer_,
1328 {0, 0, float_right, float_bottom});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001329
Corey Tabaka2251d822017-04-20 16:04:07 -07001330 ALOGE_IF(error != HWC::Error::None,
1331 "Layer::Prepare: Error setting layer source crop: %s",
1332 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001333
Corey Tabaka2251d822017-04-20 16:04:07 -07001334 surface_rect_functions_applied_ = true;
1335 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001336 }
1337}
1338
1339void Layer::Finish(int release_fence_fd) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001340 IfAnyOf<SourceSurface, SourceBuffer>::Call(
1341 &source_, [release_fence_fd](auto& source) {
1342 source.Finish(LocalHandle(release_fence_fd));
1343 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001344}
1345
Corey Tabaka2251d822017-04-20 16:04:07 -07001346void Layer::Drop() { acquire_fence_.Close(); }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001347
1348} // namespace dvr
1349} // namespace android