blob: 4f5d5489b9ff59da8b49225d555a7b93c7500c3f [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
460 // Now that we have taken in a frame from the application, we have a chance
461 // to drop the frame before passing the frame along to HWC.
462 // If the display driver has become backed up, we detect it here and then
463 // react by skipping this frame to catch up latency.
464 while (!retire_fence_fds_.empty() &&
465 (!retire_fence_fds_.front() ||
466 sync_wait(retire_fence_fds_.front().Get(), 0) == 0)) {
467 // There are only 2 fences in here, no performance problem to shift the
468 // array of ints.
469 retire_fence_fds_.erase(retire_fence_fds_.begin());
470 }
471
George Burgess IV353a6f62017-06-26 17:13:09 -0700472 const bool is_fence_pending = static_cast<int32_t>(retire_fence_fds_.size()) >
John Bates954796e2017-05-11 11:00:31 -0700473 post_thread_config_.allowed_pending_fence_count;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800474
Corey Tabakab3732f02017-09-16 00:58:54 -0700475 if (is_fence_pending) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800476 ATRACE_INT("frame_skip_count", ++frame_skip_count_);
477
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800478 ALOGW_IF(is_fence_pending,
479 "Warning: dropping a frame to catch up with HWC (pending = %zd)",
480 retire_fence_fds_.size());
481
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700482 for (auto& layer : layers_) {
483 layer.Drop();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800484 }
485 return;
486 } else {
487 // Make the transition more obvious in systrace when the frame skip happens
488 // above.
489 ATRACE_INT("frame_skip_count", 0);
490 }
491
Corey Tabaka89bbefc2017-06-06 16:14:21 -0700492#if TRACE > 1
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700493 for (size_t i = 0; i < layers_.size(); i++) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700494 ALOGI("HardwareComposer::PostLayers: layer=%zu buffer_id=%d composition=%s",
495 i, layers_[i].GetBufferId(),
Corey Tabaka2251d822017-04-20 16:04:07 -0700496 layers_[i].GetCompositionType().to_string().c_str());
Corey Tabaka0b485c92017-05-19 12:02:58 -0700497 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800498#endif
499
John Bates46684842017-12-13 15:26:50 -0800500 HWC::Error error = Validate(composer_callback_->GetDisplayId());
501 if (error != HWC::Error::None) {
502 ALOGE("HardwareComposer::PostLayers: Validate failed: %s",
503 error.to_string().c_str());
504 return;
505 }
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);
John Bates46684842017-12-13 15:26:50 -0800865 ALOGE_IF(error < 0 && error != kPostThreadInterrupted,
866 "HardwareComposer::PostThread: Failed to sleep: %s",
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800867 strerror(-error));
John Bates46684842017-12-13 15:26:50 -0800868 // If the sleep was interrupted (error == kPostThreadInterrupted),
869 // we still go through and present this frame because we may have set
870 // layers earlier and we want to flush the Composer's internal command
871 // buffer by continuing through to validate and present.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800872 }
873 }
874
Corey Tabakab3732f02017-09-16 00:58:54 -0700875 {
Steven Thomas6e8f7062017-11-22 14:15:29 -0800876 auto status = composer_callback_->GetVsyncTime();
Corey Tabakab3732f02017-09-16 00:58:54 -0700877 if (!status) {
878 ALOGE("HardwareComposer::PostThread: Failed to get VSYNC time: %s",
879 status.GetErrorMessage().c_str());
880 }
881
882 // If we failed to read vsync there might be a problem with the driver.
883 // Since there's nothing we can do just behave as though we didn't get an
884 // updated vsync time and let the prediction continue.
885 const int64_t current_vsync_timestamp =
886 status ? status.get() : last_vsync_timestamp_;
887
888 const bool vsync_delayed =
889 last_vsync_timestamp_ == current_vsync_timestamp;
890 ATRACE_INT("vsync_delayed", vsync_delayed);
891
892 // If vsync was delayed advance the prediction interval and allow the
893 // fence logic in PostLayers() to skip the frame.
894 if (vsync_delayed) {
895 ALOGW(
896 "HardwareComposer::PostThread: VSYNC timestamp did not advance "
897 "since last frame: timestamp=%" PRId64 " prediction_interval=%d",
898 current_vsync_timestamp, vsync_prediction_interval_);
899 vsync_prediction_interval_++;
900 } else {
901 // We have an updated vsync timestamp, reset the prediction interval.
902 last_vsync_timestamp_ = current_vsync_timestamp;
903 vsync_prediction_interval_ = 1;
904 }
905 }
906
Corey Tabaka2251d822017-04-20 16:04:07 -0700907 PostLayers();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800908 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800909}
910
Corey Tabaka2251d822017-04-20 16:04:07 -0700911// Checks for changes in the surface stack and updates the layer config to
912// accomodate the new stack.
Steven Thomas050b2c82017-03-06 11:45:16 -0800913bool HardwareComposer::UpdateLayerConfig() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700914 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces;
Steven Thomas050b2c82017-03-06 11:45:16 -0800915 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700916 std::unique_lock<std::mutex> lock(post_thread_mutex_);
917 if (pending_surfaces_.empty())
Steven Thomas050b2c82017-03-06 11:45:16 -0800918 return false;
Corey Tabaka2251d822017-04-20 16:04:07 -0700919
920 surfaces = std::move(pending_surfaces_);
Steven Thomas050b2c82017-03-06 11:45:16 -0800921 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800922
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800923 ATRACE_NAME("UpdateLayerConfig_HwLayers");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800924
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700925 // Sort the new direct surface list by z-order to determine the relative order
926 // of the surfaces. This relative order is used for the HWC z-order value to
927 // insulate VrFlinger and HWC z-order semantics from each other.
928 std::sort(surfaces.begin(), surfaces.end(), [](const auto& a, const auto& b) {
929 return a->z_order() < b->z_order();
930 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800931
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700932 // Prepare a new layer stack, pulling in layers from the previous
933 // layer stack that are still active and updating their attributes.
934 std::vector<Layer> layers;
935 size_t layer_index = 0;
936 for (const auto& surface : surfaces) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700937 // The bottom layer is opaque, other layers blend.
938 HWC::BlendMode blending =
939 layer_index == 0 ? HWC::BlendMode::None : HWC::BlendMode::Coverage;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700940
941 // Try to find a layer for this surface in the set of active layers.
942 auto search =
943 std::lower_bound(layers_.begin(), layers_.end(), surface->surface_id());
944 const bool found = search != layers_.end() &&
945 search->GetSurfaceId() == surface->surface_id();
946 if (found) {
947 // Update the attributes of the layer that may have changed.
948 search->SetBlending(blending);
949 search->SetZOrder(layer_index); // Relative z-order.
950
951 // Move the existing layer to the new layer set and remove the empty layer
952 // object from the current set.
953 layers.push_back(std::move(*search));
954 layers_.erase(search);
955 } else {
956 // Insert a layer for the new surface.
957 layers.emplace_back(surface, blending, display_transform_,
958 HWC::Composition::Device, layer_index);
959 }
960
961 ALOGI_IF(
962 TRACE,
963 "HardwareComposer::UpdateLayerConfig: layer_index=%zu surface_id=%d",
964 layer_index, layers[layer_index].GetSurfaceId());
965
966 layer_index++;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800967 }
968
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700969 // Sort the new layer stack by ascending surface id.
970 std::sort(layers.begin(), layers.end());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800971
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700972 // Replace the previous layer set with the new layer set. The destructor of
973 // the previous set will clean up the remaining Layers that are not moved to
974 // the new layer set.
975 layers_ = std::move(layers);
976
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800977 ALOGD_IF(TRACE, "HardwareComposer::UpdateLayerConfig: %zd active layers",
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700978 layers_.size());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800979 return true;
980}
981
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800982void HardwareComposer::SetVSyncCallback(VSyncCallback callback) {
983 vsync_callback_ = callback;
984}
985
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800986void HardwareComposer::SetBacklightBrightness(int brightness) {
987 if (backlight_brightness_fd_) {
988 std::array<char, 32> text;
989 const int length = snprintf(text.data(), text.size(), "%d", brightness);
990 write(backlight_brightness_fd_.Get(), text.data(), length);
991 }
992}
993
Steven Thomasb02664d2017-07-26 18:48:28 -0700994Return<void> HardwareComposer::ComposerCallback::onHotplug(
Steven Thomas6e8f7062017-11-22 14:15:29 -0800995 Hwc2::Display display, IComposerCallback::Connection conn) {
996 // Our first onHotplug callback is always for the primary display.
997 //
998 // Ignore any other hotplug callbacks since the primary display is never
999 // disconnected and we don't care about other displays.
1000 if (!has_display_id_) {
1001 LOG_ALWAYS_FATAL_IF(conn != IComposerCallback::Connection::CONNECTED,
1002 "Initial onHotplug callback should be primary display connected");
1003 has_display_id_ = true;
1004 display_id_ = display;
1005
Corey Tabakab3732f02017-09-16 00:58:54 -07001006 std::array<char, 1024> buffer;
1007 snprintf(buffer.data(), buffer.size(),
1008 "/sys/class/graphics/fb%" PRIu64 "/vsync_event", display);
1009 if (LocalHandle handle{buffer.data(), O_RDONLY}) {
1010 ALOGI(
1011 "HardwareComposer::ComposerCallback::onHotplug: Driver supports "
1012 "vsync_event node for display %" PRIu64,
1013 display);
Steven Thomas6e8f7062017-11-22 14:15:29 -08001014 driver_vsync_event_fd_ = std::move(handle);
Corey Tabakab3732f02017-09-16 00:58:54 -07001015 } else {
1016 ALOGI(
1017 "HardwareComposer::ComposerCallback::onHotplug: Driver does not "
1018 "support vsync_event node for display %" PRIu64,
1019 display);
1020 }
1021 }
1022
Steven Thomasb02664d2017-07-26 18:48:28 -07001023 return Void();
1024}
1025
1026Return<void> HardwareComposer::ComposerCallback::onRefresh(
1027 Hwc2::Display /*display*/) {
1028 return hardware::Void();
1029}
1030
Corey Tabaka451256f2017-08-22 11:59:15 -07001031Return<void> HardwareComposer::ComposerCallback::onVsync(Hwc2::Display display,
1032 int64_t timestamp) {
Steven Thomas6e8f7062017-11-22 14:15:29 -08001033 // Ignore any onVsync callbacks for the non-primary display.
1034 if (has_display_id_ && display == display_id_) {
1035 TRACE_FORMAT("vsync_callback|display=%" PRIu64 ";timestamp=%" PRId64 "|",
1036 display, timestamp);
1037 callback_vsync_timestamp_ = timestamp;
Steven Thomasb02664d2017-07-26 18:48:28 -07001038 }
1039 return Void();
1040}
1041
Steven Thomas6e8f7062017-11-22 14:15:29 -08001042Status<int64_t> HardwareComposer::ComposerCallback::GetVsyncTime() {
Corey Tabakab3732f02017-09-16 00:58:54 -07001043 // See if the driver supports direct vsync events.
Steven Thomas6e8f7062017-11-22 14:15:29 -08001044 LocalHandle& event_fd = driver_vsync_event_fd_;
Corey Tabakab3732f02017-09-16 00:58:54 -07001045 if (!event_fd) {
1046 // Fall back to returning the last timestamp returned by the vsync
1047 // callback.
1048 std::lock_guard<std::mutex> autolock(vsync_mutex_);
Steven Thomas6e8f7062017-11-22 14:15:29 -08001049 return callback_vsync_timestamp_;
Corey Tabakab3732f02017-09-16 00:58:54 -07001050 }
1051
1052 // When the driver supports the vsync_event sysfs node we can use it to
1053 // determine the latest vsync timestamp, even if the HWC callback has been
1054 // delayed.
1055
1056 // The driver returns data in the form "VSYNC=<timestamp ns>".
1057 std::array<char, 32> data;
1058 data.fill('\0');
1059
1060 // Seek back to the beginning of the event file.
1061 int ret = lseek(event_fd.Get(), 0, SEEK_SET);
1062 if (ret < 0) {
1063 const int error = errno;
1064 ALOGE(
1065 "HardwareComposer::ComposerCallback::GetVsyncTime: Failed to seek "
1066 "vsync event fd: %s",
1067 strerror(error));
1068 return ErrorStatus(error);
1069 }
1070
1071 // Read the vsync event timestamp.
1072 ret = read(event_fd.Get(), data.data(), data.size());
1073 if (ret < 0) {
1074 const int error = errno;
1075 ALOGE_IF(error != EAGAIN,
1076 "HardwareComposer::ComposerCallback::GetVsyncTime: Error "
1077 "while reading timestamp: %s",
1078 strerror(error));
1079 return ErrorStatus(error);
1080 }
1081
1082 int64_t timestamp;
1083 ret = sscanf(data.data(), "VSYNC=%" PRIu64,
1084 reinterpret_cast<uint64_t*>(&timestamp));
1085 if (ret < 0) {
1086 const int error = errno;
1087 ALOGE(
1088 "HardwareComposer::ComposerCallback::GetVsyncTime: Error while "
1089 "parsing timestamp: %s",
1090 strerror(error));
1091 return ErrorStatus(error);
1092 }
1093
1094 return {timestamp};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001095}
1096
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001097Hwc2::Composer* Layer::composer_{nullptr};
1098HWCDisplayMetrics Layer::display_metrics_{0, 0, {0, 0}, 0};
Steven Thomas6e8f7062017-11-22 14:15:29 -08001099hwc2_display_t Layer::display_id_{0};
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001100
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001101void Layer::Reset() {
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001102 if (hardware_composer_layer_) {
Steven Thomas6e8f7062017-11-22 14:15:29 -08001103 composer_->destroyLayer(display_id_, hardware_composer_layer_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001104 hardware_composer_layer_ = 0;
1105 }
1106
Corey Tabaka2251d822017-04-20 16:04:07 -07001107 z_order_ = 0;
1108 blending_ = HWC::BlendMode::None;
1109 transform_ = HWC::Transform::None;
1110 composition_type_ = HWC::Composition::Invalid;
1111 target_composition_type_ = composition_type_;
1112 source_ = EmptyVariant{};
1113 acquire_fence_.Close();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001114 surface_rect_functions_applied_ = false;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001115 pending_visibility_settings_ = true;
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001116 cached_buffer_map_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001117}
1118
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001119Layer::Layer(const std::shared_ptr<DirectDisplaySurface>& surface,
1120 HWC::BlendMode blending, HWC::Transform transform,
1121 HWC::Composition composition_type, size_t z_order)
1122 : z_order_{z_order},
1123 blending_{blending},
1124 transform_{transform},
1125 target_composition_type_{composition_type},
1126 source_{SourceSurface{surface}} {
1127 CommonLayerSetup();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001128}
1129
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001130Layer::Layer(const std::shared_ptr<IonBuffer>& buffer, HWC::BlendMode blending,
1131 HWC::Transform transform, HWC::Composition composition_type,
1132 size_t z_order)
1133 : z_order_{z_order},
1134 blending_{blending},
1135 transform_{transform},
1136 target_composition_type_{composition_type},
1137 source_{SourceBuffer{buffer}} {
1138 CommonLayerSetup();
1139}
1140
1141Layer::~Layer() { Reset(); }
1142
1143Layer::Layer(Layer&& other) { *this = std::move(other); }
1144
1145Layer& Layer::operator=(Layer&& other) {
1146 if (this != &other) {
1147 Reset();
1148 using std::swap;
1149 swap(hardware_composer_layer_, other.hardware_composer_layer_);
1150 swap(z_order_, other.z_order_);
1151 swap(blending_, other.blending_);
1152 swap(transform_, other.transform_);
1153 swap(composition_type_, other.composition_type_);
1154 swap(target_composition_type_, other.target_composition_type_);
1155 swap(source_, other.source_);
1156 swap(acquire_fence_, other.acquire_fence_);
1157 swap(surface_rect_functions_applied_,
1158 other.surface_rect_functions_applied_);
1159 swap(pending_visibility_settings_, other.pending_visibility_settings_);
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001160 swap(cached_buffer_map_, other.cached_buffer_map_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001161 }
1162 return *this;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001163}
1164
Corey Tabaka2251d822017-04-20 16:04:07 -07001165void Layer::UpdateBuffer(const std::shared_ptr<IonBuffer>& buffer) {
1166 if (source_.is<SourceBuffer>())
1167 std::get<SourceBuffer>(source_) = {buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001168}
1169
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001170void Layer::SetBlending(HWC::BlendMode blending) {
1171 if (blending_ != blending) {
1172 blending_ = blending;
1173 pending_visibility_settings_ = true;
1174 }
1175}
1176
1177void Layer::SetZOrder(size_t z_order) {
1178 if (z_order_ != z_order) {
1179 z_order_ = z_order;
1180 pending_visibility_settings_ = true;
1181 }
1182}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001183
1184IonBuffer* Layer::GetBuffer() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001185 struct Visitor {
1186 IonBuffer* operator()(SourceSurface& source) { return source.GetBuffer(); }
1187 IonBuffer* operator()(SourceBuffer& source) { return source.GetBuffer(); }
1188 IonBuffer* operator()(EmptyVariant) { return nullptr; }
1189 };
1190 return source_.Visit(Visitor{});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001191}
1192
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001193void Layer::UpdateVisibilitySettings() {
1194 if (pending_visibility_settings_) {
1195 pending_visibility_settings_ = false;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001196
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001197 HWC::Error error;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001198
1199 error = composer_->setLayerBlendMode(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001200 display_id_, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001201 blending_.cast<Hwc2::IComposerClient::BlendMode>());
1202 ALOGE_IF(error != HWC::Error::None,
1203 "Layer::UpdateLayerSettings: Error setting layer blend mode: %s",
1204 error.to_string().c_str());
1205
Steven Thomas6e8f7062017-11-22 14:15:29 -08001206 error = composer_->setLayerZOrder(display_id_, hardware_composer_layer_,
1207 z_order_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001208 ALOGE_IF(error != HWC::Error::None,
1209 "Layer::UpdateLayerSettings: Error setting z_ order: %s",
1210 error.to_string().c_str());
1211 }
1212}
1213
1214void Layer::UpdateLayerSettings() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001215 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001216
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001217 UpdateVisibilitySettings();
1218
Corey Tabaka2251d822017-04-20 16:04:07 -07001219 // TODO(eieio): Use surface attributes or some other mechanism to control
1220 // the layer display frame.
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001221 error = composer_->setLayerDisplayFrame(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001222 display_id_, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001223 {0, 0, display_metrics_.width, display_metrics_.height});
Corey Tabaka2251d822017-04-20 16:04:07 -07001224 ALOGE_IF(error != HWC::Error::None,
1225 "Layer::UpdateLayerSettings: Error setting layer display frame: %s",
1226 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001227
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001228 error = composer_->setLayerVisibleRegion(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001229 display_id_, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001230 {{0, 0, display_metrics_.width, display_metrics_.height}});
Corey Tabaka2251d822017-04-20 16:04:07 -07001231 ALOGE_IF(error != HWC::Error::None,
1232 "Layer::UpdateLayerSettings: Error setting layer visible region: %s",
1233 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001234
Steven Thomas6e8f7062017-11-22 14:15:29 -08001235 error = composer_->setLayerPlaneAlpha(display_id_, hardware_composer_layer_,
1236 1.0f);
Corey Tabaka2251d822017-04-20 16:04:07 -07001237 ALOGE_IF(error != HWC::Error::None,
1238 "Layer::UpdateLayerSettings: Error setting layer plane alpha: %s",
1239 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001240}
1241
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001242void Layer::CommonLayerSetup() {
Steven Thomas6e8f7062017-11-22 14:15:29 -08001243 HWC::Error error = composer_->createLayer(display_id_,
1244 &hardware_composer_layer_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001245 ALOGE_IF(error != HWC::Error::None,
1246 "Layer::CommonLayerSetup: Failed to create layer on primary "
1247 "display: %s",
1248 error.to_string().c_str());
1249 UpdateLayerSettings();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001250}
1251
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001252bool Layer::CheckAndUpdateCachedBuffer(std::size_t slot, int buffer_id) {
1253 auto search = cached_buffer_map_.find(slot);
1254 if (search != cached_buffer_map_.end() && search->second == buffer_id)
1255 return true;
1256
1257 // Assign or update the buffer slot.
1258 if (buffer_id >= 0)
1259 cached_buffer_map_[slot] = buffer_id;
1260 return false;
1261}
1262
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001263void Layer::Prepare() {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001264 int right, bottom, id;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -04001265 sp<GraphicBuffer> handle;
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001266 std::size_t slot;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001267
Corey Tabaka2251d822017-04-20 16:04:07 -07001268 // Acquire the next buffer according to the type of source.
1269 IfAnyOf<SourceSurface, SourceBuffer>::Call(&source_, [&](auto& source) {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001270 std::tie(right, bottom, id, handle, acquire_fence_, slot) =
1271 source.Acquire();
Corey Tabaka2251d822017-04-20 16:04:07 -07001272 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001273
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001274 TRACE_FORMAT("Layer::Prepare|buffer_id=%d;slot=%zu|", id, slot);
1275
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001276 // Update any visibility (blending, z-order) changes that occurred since
1277 // last prepare.
1278 UpdateVisibilitySettings();
1279
1280 // When a layer is first setup there may be some time before the first
1281 // buffer arrives. Setup the HWC layer as a solid color to stall for time
1282 // until the first buffer arrives. Once the first buffer arrives there will
1283 // always be a buffer for the frame even if it is old.
Corey Tabaka2251d822017-04-20 16:04:07 -07001284 if (!handle.get()) {
1285 if (composition_type_ == HWC::Composition::Invalid) {
1286 composition_type_ = HWC::Composition::SolidColor;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001287 composer_->setLayerCompositionType(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001288 display_id_, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001289 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1290 Hwc2::IComposerClient::Color layer_color = {0, 0, 0, 0};
Steven Thomas6e8f7062017-11-22 14:15:29 -08001291 composer_->setLayerColor(display_id_, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001292 layer_color);
Corey Tabaka2251d822017-04-20 16:04:07 -07001293 } else {
1294 // The composition type is already set. Nothing else to do until a
1295 // buffer arrives.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001296 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001297 } else {
Corey Tabaka2251d822017-04-20 16:04:07 -07001298 if (composition_type_ != target_composition_type_) {
1299 composition_type_ = target_composition_type_;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001300 composer_->setLayerCompositionType(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001301 display_id_, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001302 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1303 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001304
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001305 // See if the HWC cache already has this buffer.
1306 const bool cached = CheckAndUpdateCachedBuffer(slot, id);
1307 if (cached)
1308 handle = nullptr;
1309
Corey Tabaka2251d822017-04-20 16:04:07 -07001310 HWC::Error error{HWC::Error::None};
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001311 error =
Steven Thomas6e8f7062017-11-22 14:15:29 -08001312 composer_->setLayerBuffer(display_id_, hardware_composer_layer_,
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001313 slot, handle, acquire_fence_.Get());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001314
Corey Tabaka2251d822017-04-20 16:04:07 -07001315 ALOGE_IF(error != HWC::Error::None,
1316 "Layer::Prepare: Error setting layer buffer: %s",
1317 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001318
Corey Tabaka2251d822017-04-20 16:04:07 -07001319 if (!surface_rect_functions_applied_) {
1320 const float float_right = right;
1321 const float float_bottom = bottom;
Steven Thomas6e8f7062017-11-22 14:15:29 -08001322 error = composer_->setLayerSourceCrop(display_id_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001323 hardware_composer_layer_,
1324 {0, 0, float_right, float_bottom});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001325
Corey Tabaka2251d822017-04-20 16:04:07 -07001326 ALOGE_IF(error != HWC::Error::None,
1327 "Layer::Prepare: Error setting layer source crop: %s",
1328 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001329
Corey Tabaka2251d822017-04-20 16:04:07 -07001330 surface_rect_functions_applied_ = true;
1331 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001332 }
1333}
1334
1335void Layer::Finish(int release_fence_fd) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001336 IfAnyOf<SourceSurface, SourceBuffer>::Call(
1337 &source_, [release_fence_fd](auto& source) {
1338 source.Finish(LocalHandle(release_fence_fd));
1339 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001340}
1341
Corey Tabaka2251d822017-04-20 16:04:07 -07001342void Layer::Drop() { acquire_fence_.Close(); }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001343
1344} // namespace dvr
1345} // namespace android