blob: be17ecfa82d6722881de79176d7a0f2d8c5a65ba [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
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080056// Get time offset from a vsync to when the pose for that vsync should be
57// predicted out to. For example, if scanout gets halfway through the frame
58// at the halfway point between vsyncs, then this could be half the period.
59// With global shutter displays, this should be changed to the offset to when
60// illumination begins. Low persistence adds a frame of latency, so we predict
61// to the center of the next frame.
62inline int64_t GetPosePredictionTimeOffset(int64_t vsync_period_ns) {
63 return (vsync_period_ns * 150) / 100;
64}
65
Corey Tabaka2251d822017-04-20 16:04:07 -070066// Attempts to set the scheduler class and partiton for the current thread.
67// Returns true on success or false on failure.
68bool SetThreadPolicy(const std::string& scheduler_class,
69 const std::string& partition) {
70 int error = dvrSetSchedulerClass(0, scheduler_class.c_str());
71 if (error < 0) {
72 ALOGE(
73 "SetThreadPolicy: Failed to set scheduler class \"%s\" for "
74 "thread_id=%d: %s",
75 scheduler_class.c_str(), gettid(), strerror(-error));
76 return false;
77 }
78 error = dvrSetCpuPartition(0, partition.c_str());
79 if (error < 0) {
80 ALOGE(
81 "SetThreadPolicy: Failed to set cpu partiton \"%s\" for thread_id=%d: "
82 "%s",
83 partition.c_str(), gettid(), strerror(-error));
84 return false;
85 }
86 return true;
87}
88
Corey Tabakab3732f02017-09-16 00:58:54 -070089// Utility to generate scoped tracers with arguments.
90// TODO(eieio): Move/merge this into utils/Trace.h?
91class TraceArgs {
92 public:
93 template <typename... Args>
94 TraceArgs(const char* format, Args&&... args) {
95 std::array<char, 1024> buffer;
96 snprintf(buffer.data(), buffer.size(), format, std::forward<Args>(args)...);
97 atrace_begin(ATRACE_TAG, buffer.data());
98 }
99
100 ~TraceArgs() { atrace_end(ATRACE_TAG); }
101
102 private:
103 TraceArgs(const TraceArgs&) = delete;
104 void operator=(const TraceArgs&) = delete;
105};
106
107// Macro to define a scoped tracer with arguments. Uses PASTE(x, y) macro
108// defined in utils/Trace.h.
109#define TRACE_FORMAT(format, ...) \
110 TraceArgs PASTE(__tracer, __LINE__) { format, ##__VA_ARGS__ }
111
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800112} // anonymous namespace
113
Corey Tabaka2251d822017-04-20 16:04:07 -0700114HardwareComposer::HardwareComposer()
Steven Thomasb02664d2017-07-26 18:48:28 -0700115 : initialized_(false), request_display_callback_(nullptr) {}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800116
117HardwareComposer::~HardwareComposer(void) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700118 UpdatePostThreadState(PostThreadState::Quit, true);
119 if (post_thread_.joinable())
Steven Thomas050b2c82017-03-06 11:45:16 -0800120 post_thread_.join();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800121}
122
Steven Thomasb02664d2017-07-26 18:48:28 -0700123bool HardwareComposer::Initialize(
Steven Thomas6e8f7062017-11-22 14:15:29 -0800124 Hwc2::Composer* composer, hwc2_display_t primary_display_id,
125 RequestDisplayCallback request_display_callback) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800126 if (initialized_) {
127 ALOGE("HardwareComposer::Initialize: already initialized.");
128 return false;
129 }
130
Corey Tabaka451256f2017-08-22 11:59:15 -0700131 is_standalone_device_ = property_get_bool(kDvrStandaloneProperty, false);
132
Steven Thomasb02664d2017-07-26 18:48:28 -0700133 request_display_callback_ = request_display_callback;
134
Corey Tabaka2251d822017-04-20 16:04:07 -0700135 HWC::Error error = HWC::Error::None;
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800136
137 Hwc2::Config config;
Steven Thomas6e8f7062017-11-22 14:15:29 -0800138 error = composer->getActiveConfig(primary_display_id, &config);
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800139
Corey Tabaka2251d822017-04-20 16:04:07 -0700140 if (error != HWC::Error::None) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800141 ALOGE("HardwareComposer: Failed to get current display config : %d",
142 config);
143 return false;
144 }
145
Steven Thomas6e8f7062017-11-22 14:15:29 -0800146 error = GetDisplayMetrics(composer, primary_display_id, config,
Steven Thomasb02664d2017-07-26 18:48:28 -0700147 &native_display_metrics_);
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800148
Corey Tabaka2251d822017-04-20 16:04:07 -0700149 if (error != HWC::Error::None) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800150 ALOGE(
151 "HardwareComposer: Failed to get display attributes for current "
152 "configuration : %d",
Corey Tabaka2251d822017-04-20 16:04:07 -0700153 error.value);
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800154 return false;
155 }
156
157 ALOGI(
158 "HardwareComposer: primary display attributes: width=%d height=%d "
159 "vsync_period_ns=%d DPI=%dx%d",
160 native_display_metrics_.width, native_display_metrics_.height,
161 native_display_metrics_.vsync_period_ns, native_display_metrics_.dpi.x,
162 native_display_metrics_.dpi.y);
163
164 // Set the display metrics but never use rotation to avoid the long latency of
165 // rotation processing in hwc.
166 display_transform_ = HWC_TRANSFORM_NONE;
167 display_metrics_ = native_display_metrics_;
168
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700169 // Setup the display metrics used by all Layer instances.
170 Layer::SetDisplayMetrics(native_display_metrics_);
171
Corey Tabaka2251d822017-04-20 16:04:07 -0700172 post_thread_event_fd_.Reset(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
Steven Thomas050b2c82017-03-06 11:45:16 -0800173 LOG_ALWAYS_FATAL_IF(
Corey Tabaka2251d822017-04-20 16:04:07 -0700174 !post_thread_event_fd_,
Steven Thomas050b2c82017-03-06 11:45:16 -0800175 "HardwareComposer: Failed to create interrupt event fd : %s",
176 strerror(errno));
177
178 post_thread_ = std::thread(&HardwareComposer::PostThread, this);
179
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800180 initialized_ = true;
181
182 return initialized_;
183}
184
Steven Thomas050b2c82017-03-06 11:45:16 -0800185void HardwareComposer::Enable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700186 UpdatePostThreadState(PostThreadState::Suspended, false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800187}
188
189void HardwareComposer::Disable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700190 UpdatePostThreadState(PostThreadState::Suspended, true);
Steven Thomas050b2c82017-03-06 11:45:16 -0800191}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800192
Corey Tabaka2251d822017-04-20 16:04:07 -0700193// Update the post thread quiescent state based on idle and suspended inputs.
194void HardwareComposer::UpdatePostThreadState(PostThreadStateType state,
195 bool suspend) {
196 std::unique_lock<std::mutex> lock(post_thread_mutex_);
197
198 // Update the votes in the state variable before evaluating the effective
199 // quiescent state. Any bits set in post_thread_state_ indicate that the post
200 // thread should be suspended.
201 if (suspend) {
202 post_thread_state_ |= state;
203 } else {
204 post_thread_state_ &= ~state;
205 }
206
207 const bool quit = post_thread_state_ & PostThreadState::Quit;
208 const bool effective_suspend = post_thread_state_ != PostThreadState::Active;
209 if (quit) {
210 post_thread_quiescent_ = true;
211 eventfd_write(post_thread_event_fd_.Get(), 1);
212 post_thread_wait_.notify_one();
213 } else if (effective_suspend && !post_thread_quiescent_) {
214 post_thread_quiescent_ = true;
215 eventfd_write(post_thread_event_fd_.Get(), 1);
216 } else if (!effective_suspend && post_thread_quiescent_) {
217 post_thread_quiescent_ = false;
218 eventfd_t value;
219 eventfd_read(post_thread_event_fd_.Get(), &value);
220 post_thread_wait_.notify_one();
221 }
222
223 // Wait until the post thread is in the requested state.
224 post_thread_ready_.wait(lock, [this, effective_suspend] {
225 return effective_suspend != post_thread_resumed_;
226 });
Steven Thomas050b2c82017-03-06 11:45:16 -0800227}
Steven Thomas282a5ed2017-02-07 18:07:01 -0800228
Steven Thomas050b2c82017-03-06 11:45:16 -0800229void HardwareComposer::OnPostThreadResumed() {
Corey Tabaka451256f2017-08-22 11:59:15 -0700230 // Phones create a new composer client on resume and destroy it on pause.
231 // Standalones only create the composer client once and then use SetPowerMode
232 // to control the screen on pause/resume.
233 if (!is_standalone_device_ || !composer_) {
234 composer_.reset(new Hwc2::Composer("default"));
235 composer_callback_ = new ComposerCallback;
236 composer_->registerCallback(composer_callback_);
Steven Thomas6e8f7062017-11-22 14:15:29 -0800237 LOG_ALWAYS_FATAL_IF(!composer_callback_->HasDisplayId(),
238 "Registered composer callback but didn't get primary display");
Corey Tabaka451256f2017-08-22 11:59:15 -0700239 Layer::SetComposer(composer_.get());
Steven Thomas6e8f7062017-11-22 14:15:29 -0800240 Layer::SetDisplayId(composer_callback_->GetDisplayId());
Corey Tabaka451256f2017-08-22 11:59:15 -0700241 } else {
242 SetPowerMode(true);
243 }
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700244
Steven Thomas050b2c82017-03-06 11:45:16 -0800245 EnableVsync(true);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800246
Steven Thomas050b2c82017-03-06 11:45:16 -0800247 // TODO(skiazyk): We need to do something about accessing this directly,
248 // supposedly there is a backlight service on the way.
249 // TODO(steventhomas): When we change the backlight setting, will surface
250 // flinger (or something else) set it back to its original value once we give
251 // control of the display back to surface flinger?
252 SetBacklightBrightness(255);
Steven Thomas282a5ed2017-02-07 18:07:01 -0800253
Steven Thomas050b2c82017-03-06 11:45:16 -0800254 // Trigger target-specific performance mode change.
255 property_set(kDvrPerformanceProperty, "performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800256}
257
Steven Thomas050b2c82017-03-06 11:45:16 -0800258void HardwareComposer::OnPostThreadPaused() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700259 retire_fence_fds_.clear();
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700260 layers_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800261
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700262 if (composer_) {
Steven Thomasb02664d2017-07-26 18:48:28 -0700263 EnableVsync(false);
264 }
Steven Thomas050b2c82017-03-06 11:45:16 -0800265
Corey Tabaka451256f2017-08-22 11:59:15 -0700266 if (!is_standalone_device_) {
267 composer_callback_ = nullptr;
268 composer_.reset(nullptr);
269 Layer::SetComposer(nullptr);
Steven Thomas6e8f7062017-11-22 14:15:29 -0800270 Layer::SetDisplayId(0);
Corey Tabaka451256f2017-08-22 11:59:15 -0700271 } else {
272 SetPowerMode(false);
273 }
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700274
Steven Thomas050b2c82017-03-06 11:45:16 -0800275 // Trigger target-specific performance mode change.
276 property_set(kDvrPerformanceProperty, "idle");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800277}
278
Corey Tabaka2251d822017-04-20 16:04:07 -0700279HWC::Error HardwareComposer::Validate(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800280 uint32_t num_types;
281 uint32_t num_requests;
Corey Tabaka2251d822017-04-20 16:04:07 -0700282 HWC::Error error =
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700283 composer_->validateDisplay(display, &num_types, &num_requests);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800284
285 if (error == HWC2_ERROR_HAS_CHANGES) {
286 // TODO(skiazyk): We might need to inspect the requested changes first, but
287 // so far it seems like we shouldn't ever hit a bad state.
288 // error = hwc2_funcs_.accept_display_changes_fn_(hardware_composer_device_,
289 // display);
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700290 error = composer_->acceptDisplayChanges(display);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800291 }
292
293 return error;
294}
295
Steven Thomasb02664d2017-07-26 18:48:28 -0700296HWC::Error HardwareComposer::EnableVsync(bool enabled) {
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700297 return composer_->setVsyncEnabled(
Steven Thomas6e8f7062017-11-22 14:15:29 -0800298 composer_callback_->GetDisplayId(),
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800299 (Hwc2::IComposerClient::Vsync)(enabled ? HWC2_VSYNC_ENABLE
300 : HWC2_VSYNC_DISABLE));
301}
302
Corey Tabaka451256f2017-08-22 11:59:15 -0700303HWC::Error HardwareComposer::SetPowerMode(bool active) {
304 HWC::PowerMode power_mode = active ? HWC::PowerMode::On : HWC::PowerMode::Off;
305 return composer_->setPowerMode(
Steven Thomas6e8f7062017-11-22 14:15:29 -0800306 composer_callback_->GetDisplayId(),
307 power_mode.cast<Hwc2::IComposerClient::PowerMode>());
Corey Tabaka451256f2017-08-22 11:59:15 -0700308}
309
Corey Tabaka2251d822017-04-20 16:04:07 -0700310HWC::Error HardwareComposer::Present(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800311 int32_t present_fence;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700312 HWC::Error error = composer_->presentDisplay(display, &present_fence);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800313
314 // According to the documentation, this fence is signaled at the time of
315 // vsync/DMA for physical displays.
Corey Tabaka2251d822017-04-20 16:04:07 -0700316 if (error == HWC::Error::None) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800317 ATRACE_INT("HardwareComposer: VsyncFence", present_fence);
318 retire_fence_fds_.emplace_back(present_fence);
319 } else {
320 ATRACE_INT("HardwareComposer: PresentResult", error);
321 }
322
323 return error;
324}
325
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700326HWC::Error HardwareComposer::GetDisplayAttribute(Hwc2::Composer* composer,
Steven Thomasb02664d2017-07-26 18:48:28 -0700327 hwc2_display_t display,
Corey Tabaka2251d822017-04-20 16:04:07 -0700328 hwc2_config_t config,
329 hwc2_attribute_t attribute,
330 int32_t* out_value) const {
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700331 return composer->getDisplayAttribute(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800332 display, config, (Hwc2::IComposerClient::Attribute)attribute, out_value);
333}
334
Corey Tabaka2251d822017-04-20 16:04:07 -0700335HWC::Error HardwareComposer::GetDisplayMetrics(
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700336 Hwc2::Composer* composer, hwc2_display_t display, hwc2_config_t config,
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800337 HWCDisplayMetrics* out_metrics) const {
Corey Tabaka2251d822017-04-20 16:04:07 -0700338 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800339
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700340 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_WIDTH,
Corey Tabaka2251d822017-04-20 16:04:07 -0700341 &out_metrics->width);
342 if (error != HWC::Error::None) {
343 ALOGE(
344 "HardwareComposer::GetDisplayMetrics: Failed to get display width: %s",
345 error.to_string().c_str());
346 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800347 }
348
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700349 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_HEIGHT,
Corey Tabaka2251d822017-04-20 16:04:07 -0700350 &out_metrics->height);
351 if (error != HWC::Error::None) {
352 ALOGE(
353 "HardwareComposer::GetDisplayMetrics: Failed to get display height: %s",
354 error.to_string().c_str());
355 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800356 }
357
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700358 error = GetDisplayAttribute(composer, display, config,
Steven Thomasb02664d2017-07-26 18:48:28 -0700359 HWC2_ATTRIBUTE_VSYNC_PERIOD,
Corey Tabaka2251d822017-04-20 16:04:07 -0700360 &out_metrics->vsync_period_ns);
361 if (error != HWC::Error::None) {
362 ALOGE(
363 "HardwareComposer::GetDisplayMetrics: Failed to get display height: %s",
364 error.to_string().c_str());
365 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800366 }
367
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700368 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_DPI_X,
Corey Tabaka2251d822017-04-20 16:04:07 -0700369 &out_metrics->dpi.x);
370 if (error != HWC::Error::None) {
371 ALOGE(
372 "HardwareComposer::GetDisplayMetrics: Failed to get display DPI X: %s",
373 error.to_string().c_str());
374 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800375 }
376
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700377 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_DPI_Y,
Corey Tabaka2251d822017-04-20 16:04:07 -0700378 &out_metrics->dpi.y);
379 if (error != HWC::Error::None) {
380 ALOGE(
381 "HardwareComposer::GetDisplayMetrics: Failed to get display DPI Y: %s",
382 error.to_string().c_str());
383 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800384 }
385
Corey Tabaka2251d822017-04-20 16:04:07 -0700386 return HWC::Error::None;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800387}
388
Corey Tabaka0b485c92017-05-19 12:02:58 -0700389std::string HardwareComposer::Dump() {
390 std::unique_lock<std::mutex> lock(post_thread_mutex_);
391 std::ostringstream stream;
392
393 stream << "Display metrics: " << display_metrics_.width << "x"
394 << display_metrics_.height << " " << (display_metrics_.dpi.x / 1000.0)
395 << "x" << (display_metrics_.dpi.y / 1000.0) << " dpi @ "
396 << (1000000000.0 / display_metrics_.vsync_period_ns) << " Hz"
397 << std::endl;
398
399 stream << "Post thread resumed: " << post_thread_resumed_ << std::endl;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700400 stream << "Active layers: " << layers_.size() << std::endl;
Corey Tabaka0b485c92017-05-19 12:02:58 -0700401 stream << std::endl;
402
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700403 for (size_t i = 0; i < layers_.size(); i++) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700404 stream << "Layer " << i << ":";
405 stream << " type=" << layers_[i].GetCompositionType().to_string();
406 stream << " surface_id=" << layers_[i].GetSurfaceId();
407 stream << " buffer_id=" << layers_[i].GetBufferId();
408 stream << std::endl;
409 }
410 stream << std::endl;
411
412 if (post_thread_resumed_) {
413 stream << "Hardware Composer Debug Info:" << std::endl;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700414 stream << composer_->dumpDebugInfo();
Corey Tabaka0b485c92017-05-19 12:02:58 -0700415 }
416
417 return stream.str();
418}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800419
Corey Tabaka2251d822017-04-20 16:04:07 -0700420void HardwareComposer::PostLayers() {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800421 ATRACE_NAME("HardwareComposer::PostLayers");
422
423 // Setup the hardware composer layers with current buffers.
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700424 for (auto& layer : layers_) {
425 layer.Prepare();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800426 }
427
Steven Thomas6e8f7062017-11-22 14:15:29 -0800428 HWC::Error error = Validate(composer_callback_->GetDisplayId());
Corey Tabaka2251d822017-04-20 16:04:07 -0700429 if (error != HWC::Error::None) {
430 ALOGE("HardwareComposer::PostLayers: Validate failed: %s",
431 error.to_string().c_str());
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700432 return;
433 }
434
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800435 // Now that we have taken in a frame from the application, we have a chance
436 // to drop the frame before passing the frame along to HWC.
437 // If the display driver has become backed up, we detect it here and then
438 // react by skipping this frame to catch up latency.
439 while (!retire_fence_fds_.empty() &&
440 (!retire_fence_fds_.front() ||
441 sync_wait(retire_fence_fds_.front().Get(), 0) == 0)) {
442 // There are only 2 fences in here, no performance problem to shift the
443 // array of ints.
444 retire_fence_fds_.erase(retire_fence_fds_.begin());
445 }
446
George Burgess IV353a6f62017-06-26 17:13:09 -0700447 const bool is_fence_pending = static_cast<int32_t>(retire_fence_fds_.size()) >
John Bates954796e2017-05-11 11:00:31 -0700448 post_thread_config_.allowed_pending_fence_count;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800449
Corey Tabakab3732f02017-09-16 00:58:54 -0700450 if (is_fence_pending) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800451 ATRACE_INT("frame_skip_count", ++frame_skip_count_);
452
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800453 ALOGW_IF(is_fence_pending,
454 "Warning: dropping a frame to catch up with HWC (pending = %zd)",
455 retire_fence_fds_.size());
456
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700457 for (auto& layer : layers_) {
458 layer.Drop();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800459 }
460 return;
461 } else {
462 // Make the transition more obvious in systrace when the frame skip happens
463 // above.
464 ATRACE_INT("frame_skip_count", 0);
465 }
466
Corey Tabaka89bbefc2017-06-06 16:14:21 -0700467#if TRACE > 1
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700468 for (size_t i = 0; i < layers_.size(); i++) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700469 ALOGI("HardwareComposer::PostLayers: layer=%zu buffer_id=%d composition=%s",
470 i, layers_[i].GetBufferId(),
Corey Tabaka2251d822017-04-20 16:04:07 -0700471 layers_[i].GetCompositionType().to_string().c_str());
Corey Tabaka0b485c92017-05-19 12:02:58 -0700472 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800473#endif
474
Steven Thomas6e8f7062017-11-22 14:15:29 -0800475 error = Present(composer_callback_->GetDisplayId());
Corey Tabaka2251d822017-04-20 16:04:07 -0700476 if (error != HWC::Error::None) {
477 ALOGE("HardwareComposer::PostLayers: Present failed: %s",
478 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800479 return;
480 }
481
482 std::vector<Hwc2::Layer> out_layers;
483 std::vector<int> out_fences;
Steven Thomas6e8f7062017-11-22 14:15:29 -0800484 error = composer_->getReleaseFences(composer_callback_->GetDisplayId(),
485 &out_layers, &out_fences);
Corey Tabaka2251d822017-04-20 16:04:07 -0700486 ALOGE_IF(error != HWC::Error::None,
487 "HardwareComposer::PostLayers: Failed to get release fences: %s",
488 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800489
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700490 // Perform post-frame bookkeeping.
Corey Tabaka2251d822017-04-20 16:04:07 -0700491 uint32_t num_elements = out_layers.size();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800492 for (size_t i = 0; i < num_elements; ++i) {
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700493 for (auto& layer : layers_) {
494 if (layer.GetLayerHandle() == out_layers[i]) {
495 layer.Finish(out_fences[i]);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800496 }
497 }
498 }
499}
500
Steven Thomas050b2c82017-03-06 11:45:16 -0800501void HardwareComposer::SetDisplaySurfaces(
Corey Tabaka2251d822017-04-20 16:04:07 -0700502 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces) {
Jin Qian7480c062017-03-21 00:04:15 +0000503 ALOGI("HardwareComposer::SetDisplaySurfaces: surface count=%zd",
504 surfaces.size());
Corey Tabaka2251d822017-04-20 16:04:07 -0700505 const bool display_idle = surfaces.size() == 0;
506 {
507 std::unique_lock<std::mutex> lock(post_thread_mutex_);
508 pending_surfaces_ = std::move(surfaces);
509 }
510
Corey Tabaka451256f2017-08-22 11:59:15 -0700511 if (request_display_callback_ && (!is_standalone_device_ || !composer_))
Steven Thomas2ddf5672017-06-15 11:38:40 -0700512 request_display_callback_(!display_idle);
513
Corey Tabaka2251d822017-04-20 16:04:07 -0700514 // Set idle state based on whether there are any surfaces to handle.
515 UpdatePostThreadState(PostThreadState::Idle, display_idle);
Steven Thomas050b2c82017-03-06 11:45:16 -0800516}
Jin Qian7480c062017-03-21 00:04:15 +0000517
John Bates954796e2017-05-11 11:00:31 -0700518int HardwareComposer::OnNewGlobalBuffer(DvrGlobalBufferKey key,
519 IonBuffer& ion_buffer) {
Okan Arikan822b7102017-05-08 13:31:34 -0700520 if (key == DvrGlobalBuffers::kVsyncBuffer) {
521 vsync_ring_ = std::make_unique<CPUMappedBroadcastRing<DvrVsyncRing>>(
522 &ion_buffer, CPUUsageMode::WRITE_OFTEN);
523
524 if (vsync_ring_->IsMapped() == false) {
525 return -EPERM;
526 }
527 }
528
529 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700530 return MapConfigBuffer(ion_buffer);
531 }
532
533 return 0;
534}
535
536void HardwareComposer::OnDeletedGlobalBuffer(DvrGlobalBufferKey key) {
Okan Arikan822b7102017-05-08 13:31:34 -0700537 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700538 ConfigBufferDeleted();
539 }
540}
541
542int HardwareComposer::MapConfigBuffer(IonBuffer& ion_buffer) {
543 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700544 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700545
Okan Arikan6f468c62017-05-31 14:48:30 -0700546 if (ion_buffer.width() < DvrConfigRing::MemorySize()) {
John Bates954796e2017-05-11 11:00:31 -0700547 ALOGE("HardwareComposer::MapConfigBuffer: invalid buffer size.");
548 return -EINVAL;
549 }
550
551 void* buffer_base = 0;
552 int result = ion_buffer.Lock(ion_buffer.usage(), 0, 0, ion_buffer.width(),
553 ion_buffer.height(), &buffer_base);
554 if (result != 0) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700555 ALOGE(
556 "HardwareComposer::MapConfigBuffer: Failed to map vrflinger config "
557 "buffer.");
John Bates954796e2017-05-11 11:00:31 -0700558 return -EPERM;
559 }
560
Okan Arikan6f468c62017-05-31 14:48:30 -0700561 shared_config_ring_ = DvrConfigRing::Create(buffer_base, ion_buffer.width());
John Bates954796e2017-05-11 11:00:31 -0700562 ion_buffer.Unlock();
563
564 return 0;
565}
566
567void HardwareComposer::ConfigBufferDeleted() {
568 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700569 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700570}
571
572void HardwareComposer::UpdateConfigBuffer() {
573 std::lock_guard<std::mutex> lock(shared_config_mutex_);
574 if (!shared_config_ring_.is_valid())
575 return;
576 // Copy from latest record in shared_config_ring_ to local copy.
Okan Arikan6f468c62017-05-31 14:48:30 -0700577 DvrConfig record;
John Bates954796e2017-05-11 11:00:31 -0700578 if (shared_config_ring_.GetNewest(&shared_config_ring_sequence_, &record)) {
John Batescc65c3c2017-09-28 14:43:19 -0700579 ALOGI("DvrConfig updated: sequence %u, post offset %d",
580 shared_config_ring_sequence_, record.frame_post_offset_ns);
581 ++shared_config_ring_sequence_;
John Bates954796e2017-05-11 11:00:31 -0700582 post_thread_config_ = record;
583 }
584}
585
Corey Tabaka2251d822017-04-20 16:04:07 -0700586int HardwareComposer::PostThreadPollInterruptible(
Steven Thomasb02664d2017-07-26 18:48:28 -0700587 const pdx::LocalHandle& event_fd, int requested_events, int timeout_ms) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800588 pollfd pfd[2] = {
589 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700590 .fd = event_fd.Get(),
Steven Thomas66747c12017-03-22 18:45:31 -0700591 .events = static_cast<short>(requested_events),
592 .revents = 0,
Steven Thomas050b2c82017-03-06 11:45:16 -0800593 },
594 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700595 .fd = post_thread_event_fd_.Get(),
Steven Thomas050b2c82017-03-06 11:45:16 -0800596 .events = POLLPRI | POLLIN,
597 .revents = 0,
598 },
599 };
600 int ret, error;
601 do {
Steven Thomasb02664d2017-07-26 18:48:28 -0700602 ret = poll(pfd, 2, timeout_ms);
Steven Thomas050b2c82017-03-06 11:45:16 -0800603 error = errno;
604 ALOGW_IF(ret < 0,
605 "HardwareComposer::PostThreadPollInterruptible: Error during "
606 "poll(): %s (%d)",
607 strerror(error), error);
608 } while (ret < 0 && error == EINTR);
609
610 if (ret < 0) {
611 return -error;
Steven Thomasb02664d2017-07-26 18:48:28 -0700612 } else if (ret == 0) {
613 return -ETIMEDOUT;
Steven Thomas050b2c82017-03-06 11:45:16 -0800614 } else if (pfd[0].revents != 0) {
615 return 0;
616 } else if (pfd[1].revents != 0) {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -0700617 ALOGI("VrHwcPost thread interrupted: revents=%x", pfd[1].revents);
Steven Thomas050b2c82017-03-06 11:45:16 -0800618 return kPostThreadInterrupted;
619 } else {
620 return 0;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800621 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800622}
623
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800624// Waits for the next vsync and returns the timestamp of the vsync event. If
625// vsync already passed since the last call, returns the latest vsync timestamp
Steven Thomasb02664d2017-07-26 18:48:28 -0700626// instead of blocking.
Corey Tabakab3732f02017-09-16 00:58:54 -0700627Status<int64_t> HardwareComposer::WaitForVSync() {
628 const int64_t predicted_vsync_time =
629 last_vsync_timestamp_ +
630 display_metrics_.vsync_period_ns * vsync_prediction_interval_;
631 const int error = SleepUntil(predicted_vsync_time);
632 if (error < 0) {
633 ALOGE("HardwareComposer::WaifForVSync:: Failed to sleep: %s",
634 strerror(-error));
Steven Thomasb02664d2017-07-26 18:48:28 -0700635 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800636 }
Corey Tabakab3732f02017-09-16 00:58:54 -0700637 return {predicted_vsync_time};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800638}
639
640int HardwareComposer::SleepUntil(int64_t wakeup_timestamp) {
641 const int timer_fd = vsync_sleep_timer_fd_.Get();
642 const itimerspec wakeup_itimerspec = {
643 .it_interval = {.tv_sec = 0, .tv_nsec = 0},
644 .it_value = NsToTimespec(wakeup_timestamp),
645 };
646 int ret =
647 timerfd_settime(timer_fd, TFD_TIMER_ABSTIME, &wakeup_itimerspec, nullptr);
648 int error = errno;
649 if (ret < 0) {
650 ALOGE("HardwareComposer::SleepUntil: Failed to set timerfd: %s",
651 strerror(error));
652 return -error;
653 }
654
Corey Tabaka451256f2017-08-22 11:59:15 -0700655 return PostThreadPollInterruptible(vsync_sleep_timer_fd_, POLLIN,
656 /*timeout_ms*/ -1);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800657}
658
659void HardwareComposer::PostThread() {
660 // NOLINTNEXTLINE(runtime/int)
Steven Thomas050b2c82017-03-06 11:45:16 -0800661 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>("VrHwcPost"), 0, 0, 0);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800662
Corey Tabaka2251d822017-04-20 16:04:07 -0700663 // Set the scheduler to SCHED_FIFO with high priority. If this fails here
664 // there may have been a startup timing issue between this thread and
665 // performanced. Try again later when this thread becomes active.
666 bool thread_policy_setup =
667 SetThreadPolicy("graphics:high", "/system/performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800668
Steven Thomas050b2c82017-03-06 11:45:16 -0800669#if ENABLE_BACKLIGHT_BRIGHTNESS
670 // TODO(hendrikw): This isn't required at the moment. It's possible that there
671 // is another method to access this when needed.
672 // Open the backlight brightness control sysfs node.
673 backlight_brightness_fd_ = LocalHandle(kBacklightBrightnessSysFile, O_RDWR);
674 ALOGW_IF(!backlight_brightness_fd_,
675 "HardwareComposer: Failed to open backlight brightness control: %s",
676 strerror(errno));
Corey Tabaka2251d822017-04-20 16:04:07 -0700677#endif // ENABLE_BACKLIGHT_BRIGHTNESS
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800678
Steven Thomas050b2c82017-03-06 11:45:16 -0800679 // Create a timerfd based on CLOCK_MONOTINIC.
680 vsync_sleep_timer_fd_.Reset(timerfd_create(CLOCK_MONOTONIC, 0));
681 LOG_ALWAYS_FATAL_IF(
682 !vsync_sleep_timer_fd_,
683 "HardwareComposer: Failed to create vsync sleep timerfd: %s",
684 strerror(errno));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800685
686 const int64_t ns_per_frame = display_metrics_.vsync_period_ns;
687 const int64_t photon_offset_ns = GetPosePredictionTimeOffset(ns_per_frame);
688
689 // TODO(jbates) Query vblank time from device, when such an API is available.
690 // This value (6.3%) was measured on A00 in low persistence mode.
691 int64_t vblank_ns = ns_per_frame * 63 / 1000;
692 int64_t right_eye_photon_offset_ns = (ns_per_frame - vblank_ns) / 2;
693
694 // Check property for overriding right eye offset value.
695 right_eye_photon_offset_ns =
696 property_get_int64(kRightEyeOffsetProperty, right_eye_photon_offset_ns);
697
Steven Thomas050b2c82017-03-06 11:45:16 -0800698 bool was_running = false;
699
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800700 while (1) {
701 ATRACE_NAME("HardwareComposer::PostThread");
702
John Bates954796e2017-05-11 11:00:31 -0700703 // Check for updated config once per vsync.
704 UpdateConfigBuffer();
705
Corey Tabaka2251d822017-04-20 16:04:07 -0700706 while (post_thread_quiescent_) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800707 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Corey Tabaka2251d822017-04-20 16:04:07 -0700708 ALOGI("HardwareComposer::PostThread: Entering quiescent state.");
709
Corey Tabakadf0b9162017-08-03 17:14:08 -0700710 // Tear down resources if necessary.
711 if (was_running)
712 OnPostThreadPaused();
Corey Tabaka2251d822017-04-20 16:04:07 -0700713
714 was_running = false;
715 post_thread_resumed_ = false;
716 post_thread_ready_.notify_all();
717
718 if (post_thread_state_ & PostThreadState::Quit) {
719 ALOGI("HardwareComposer::PostThread: Quitting.");
720 return;
Steven Thomas282a5ed2017-02-07 18:07:01 -0800721 }
Corey Tabaka2251d822017-04-20 16:04:07 -0700722
723 post_thread_wait_.wait(lock, [this] { return !post_thread_quiescent_; });
724
725 post_thread_resumed_ = true;
726 post_thread_ready_.notify_all();
727
728 ALOGI("HardwareComposer::PostThread: Exiting quiescent state.");
Steven Thomas050b2c82017-03-06 11:45:16 -0800729 }
730
731 if (!was_running) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700732 // Setup resources.
Steven Thomas050b2c82017-03-06 11:45:16 -0800733 OnPostThreadResumed();
734 was_running = true;
Corey Tabaka2251d822017-04-20 16:04:07 -0700735
736 // Try to setup the scheduler policy if it failed during startup. Only
737 // attempt to do this on transitions from inactive to active to avoid
738 // spamming the system with RPCs and log messages.
739 if (!thread_policy_setup) {
740 thread_policy_setup =
741 SetThreadPolicy("graphics:high", "/system/performance");
742 }
Corey Tabakab3732f02017-09-16 00:58:54 -0700743
744 // Initialize the last vsync timestamp with the current time. The
745 // predictor below uses this time + the vsync interval in absolute time
746 // units for the initial delay. Once the driver starts reporting vsync the
747 // predictor will sync up with the real vsync.
748 last_vsync_timestamp_ = GetSystemClockNs();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800749 }
750
751 int64_t vsync_timestamp = 0;
752 {
Corey Tabakab3732f02017-09-16 00:58:54 -0700753 TRACE_FORMAT("wait_vsync|vsync=%u;last_timestamp=%" PRId64
754 ";prediction_interval=%d|",
755 vsync_count_ + 1, last_vsync_timestamp_,
756 vsync_prediction_interval_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800757
Corey Tabakab3732f02017-09-16 00:58:54 -0700758 auto status = WaitForVSync();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800759 ALOGE_IF(
Corey Tabakab3732f02017-09-16 00:58:54 -0700760 !status,
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800761 "HardwareComposer::PostThread: Failed to wait for vsync event: %s",
Corey Tabakab3732f02017-09-16 00:58:54 -0700762 status.GetErrorMessage().c_str());
763
764 // If there was an error either sleeping was interrupted due to pausing or
765 // there was an error getting the latest timestamp.
766 if (!status)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800767 continue;
Corey Tabakab3732f02017-09-16 00:58:54 -0700768
769 // Predicted vsync timestamp for this interval. This is stable because we
770 // use absolute time for the wakeup timer.
771 vsync_timestamp = status.get();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800772 }
773
Corey Tabakab3732f02017-09-16 00:58:54 -0700774 // Advance the vsync counter only if the system is keeping up with hardware
775 // vsync to give clients an indication of the delays.
776 if (vsync_prediction_interval_ == 1)
777 ++vsync_count_;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800778
Corey Tabaka2251d822017-04-20 16:04:07 -0700779 const bool layer_config_changed = UpdateLayerConfig();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800780
Okan Arikan822b7102017-05-08 13:31:34 -0700781 // Publish the vsync event.
782 if (vsync_ring_) {
783 DvrVsync vsync;
784 vsync.vsync_count = vsync_count_;
785 vsync.vsync_timestamp_ns = vsync_timestamp;
786 vsync.vsync_left_eye_offset_ns = photon_offset_ns;
787 vsync.vsync_right_eye_offset_ns = right_eye_photon_offset_ns;
788 vsync.vsync_period_ns = ns_per_frame;
789
790 vsync_ring_->Publish(vsync);
791 }
792
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800793 // Signal all of the vsync clients. Because absolute time is used for the
794 // wakeup time below, this can take a little time if necessary.
795 if (vsync_callback_)
Steven Thomas6e8f7062017-11-22 14:15:29 -0800796 vsync_callback_(vsync_timestamp, /*frame_time_estimate*/ 0, vsync_count_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800797
798 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700799 // Sleep until shortly before vsync.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800800 ATRACE_NAME("sleep");
801
Corey Tabaka2251d822017-04-20 16:04:07 -0700802 const int64_t display_time_est_ns = vsync_timestamp + ns_per_frame;
803 const int64_t now_ns = GetSystemClockNs();
John Bates954796e2017-05-11 11:00:31 -0700804 const int64_t sleep_time_ns = display_time_est_ns - now_ns -
805 post_thread_config_.frame_post_offset_ns;
806 const int64_t wakeup_time_ns =
807 display_time_est_ns - post_thread_config_.frame_post_offset_ns;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800808
809 ATRACE_INT64("sleep_time_ns", sleep_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800810 if (sleep_time_ns > 0) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700811 int error = SleepUntil(wakeup_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800812 ALOGE_IF(error < 0, "HardwareComposer::PostThread: Failed to sleep: %s",
813 strerror(-error));
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700814 if (error == kPostThreadInterrupted) {
815 if (layer_config_changed) {
816 // If the layer config changed we need to validateDisplay() even if
817 // we're going to drop the frame, to flush the Composer object's
818 // internal command buffer and apply our layer changes.
Steven Thomas6e8f7062017-11-22 14:15:29 -0800819 Validate(composer_callback_->GetDisplayId());
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700820 }
Steven Thomas050b2c82017-03-06 11:45:16 -0800821 continue;
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700822 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800823 }
824 }
825
Corey Tabakab3732f02017-09-16 00:58:54 -0700826 {
Steven Thomas6e8f7062017-11-22 14:15:29 -0800827 auto status = composer_callback_->GetVsyncTime();
Corey Tabakab3732f02017-09-16 00:58:54 -0700828 if (!status) {
829 ALOGE("HardwareComposer::PostThread: Failed to get VSYNC time: %s",
830 status.GetErrorMessage().c_str());
831 }
832
833 // If we failed to read vsync there might be a problem with the driver.
834 // Since there's nothing we can do just behave as though we didn't get an
835 // updated vsync time and let the prediction continue.
836 const int64_t current_vsync_timestamp =
837 status ? status.get() : last_vsync_timestamp_;
838
839 const bool vsync_delayed =
840 last_vsync_timestamp_ == current_vsync_timestamp;
841 ATRACE_INT("vsync_delayed", vsync_delayed);
842
843 // If vsync was delayed advance the prediction interval and allow the
844 // fence logic in PostLayers() to skip the frame.
845 if (vsync_delayed) {
846 ALOGW(
847 "HardwareComposer::PostThread: VSYNC timestamp did not advance "
848 "since last frame: timestamp=%" PRId64 " prediction_interval=%d",
849 current_vsync_timestamp, vsync_prediction_interval_);
850 vsync_prediction_interval_++;
851 } else {
852 // We have an updated vsync timestamp, reset the prediction interval.
853 last_vsync_timestamp_ = current_vsync_timestamp;
854 vsync_prediction_interval_ = 1;
855 }
856 }
857
Corey Tabaka2251d822017-04-20 16:04:07 -0700858 PostLayers();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800859 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800860}
861
Corey Tabaka2251d822017-04-20 16:04:07 -0700862// Checks for changes in the surface stack and updates the layer config to
863// accomodate the new stack.
Steven Thomas050b2c82017-03-06 11:45:16 -0800864bool HardwareComposer::UpdateLayerConfig() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700865 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces;
Steven Thomas050b2c82017-03-06 11:45:16 -0800866 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700867 std::unique_lock<std::mutex> lock(post_thread_mutex_);
868 if (pending_surfaces_.empty())
Steven Thomas050b2c82017-03-06 11:45:16 -0800869 return false;
Corey Tabaka2251d822017-04-20 16:04:07 -0700870
871 surfaces = std::move(pending_surfaces_);
Steven Thomas050b2c82017-03-06 11:45:16 -0800872 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800873
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800874 ATRACE_NAME("UpdateLayerConfig_HwLayers");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800875
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700876 // Sort the new direct surface list by z-order to determine the relative order
877 // of the surfaces. This relative order is used for the HWC z-order value to
878 // insulate VrFlinger and HWC z-order semantics from each other.
879 std::sort(surfaces.begin(), surfaces.end(), [](const auto& a, const auto& b) {
880 return a->z_order() < b->z_order();
881 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800882
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700883 // Prepare a new layer stack, pulling in layers from the previous
884 // layer stack that are still active and updating their attributes.
885 std::vector<Layer> layers;
886 size_t layer_index = 0;
887 for (const auto& surface : surfaces) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700888 // The bottom layer is opaque, other layers blend.
889 HWC::BlendMode blending =
890 layer_index == 0 ? HWC::BlendMode::None : HWC::BlendMode::Coverage;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700891
892 // Try to find a layer for this surface in the set of active layers.
893 auto search =
894 std::lower_bound(layers_.begin(), layers_.end(), surface->surface_id());
895 const bool found = search != layers_.end() &&
896 search->GetSurfaceId() == surface->surface_id();
897 if (found) {
898 // Update the attributes of the layer that may have changed.
899 search->SetBlending(blending);
900 search->SetZOrder(layer_index); // Relative z-order.
901
902 // Move the existing layer to the new layer set and remove the empty layer
903 // object from the current set.
904 layers.push_back(std::move(*search));
905 layers_.erase(search);
906 } else {
907 // Insert a layer for the new surface.
908 layers.emplace_back(surface, blending, display_transform_,
909 HWC::Composition::Device, layer_index);
910 }
911
912 ALOGI_IF(
913 TRACE,
914 "HardwareComposer::UpdateLayerConfig: layer_index=%zu surface_id=%d",
915 layer_index, layers[layer_index].GetSurfaceId());
916
917 layer_index++;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800918 }
919
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700920 // Sort the new layer stack by ascending surface id.
921 std::sort(layers.begin(), layers.end());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800922
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700923 // Replace the previous layer set with the new layer set. The destructor of
924 // the previous set will clean up the remaining Layers that are not moved to
925 // the new layer set.
926 layers_ = std::move(layers);
927
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800928 ALOGD_IF(TRACE, "HardwareComposer::UpdateLayerConfig: %zd active layers",
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700929 layers_.size());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800930 return true;
931}
932
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800933void HardwareComposer::SetVSyncCallback(VSyncCallback callback) {
934 vsync_callback_ = callback;
935}
936
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800937void HardwareComposer::SetBacklightBrightness(int brightness) {
938 if (backlight_brightness_fd_) {
939 std::array<char, 32> text;
940 const int length = snprintf(text.data(), text.size(), "%d", brightness);
941 write(backlight_brightness_fd_.Get(), text.data(), length);
942 }
943}
944
Steven Thomasb02664d2017-07-26 18:48:28 -0700945Return<void> HardwareComposer::ComposerCallback::onHotplug(
Steven Thomas6e8f7062017-11-22 14:15:29 -0800946 Hwc2::Display display, IComposerCallback::Connection conn) {
947 // Our first onHotplug callback is always for the primary display.
948 //
949 // Ignore any other hotplug callbacks since the primary display is never
950 // disconnected and we don't care about other displays.
951 if (!has_display_id_) {
952 LOG_ALWAYS_FATAL_IF(conn != IComposerCallback::Connection::CONNECTED,
953 "Initial onHotplug callback should be primary display connected");
954 has_display_id_ = true;
955 display_id_ = display;
956
Corey Tabakab3732f02017-09-16 00:58:54 -0700957 std::array<char, 1024> buffer;
958 snprintf(buffer.data(), buffer.size(),
959 "/sys/class/graphics/fb%" PRIu64 "/vsync_event", display);
960 if (LocalHandle handle{buffer.data(), O_RDONLY}) {
961 ALOGI(
962 "HardwareComposer::ComposerCallback::onHotplug: Driver supports "
963 "vsync_event node for display %" PRIu64,
964 display);
Steven Thomas6e8f7062017-11-22 14:15:29 -0800965 driver_vsync_event_fd_ = std::move(handle);
Corey Tabakab3732f02017-09-16 00:58:54 -0700966 } else {
967 ALOGI(
968 "HardwareComposer::ComposerCallback::onHotplug: Driver does not "
969 "support vsync_event node for display %" PRIu64,
970 display);
971 }
972 }
973
Steven Thomasb02664d2017-07-26 18:48:28 -0700974 return Void();
975}
976
977Return<void> HardwareComposer::ComposerCallback::onRefresh(
978 Hwc2::Display /*display*/) {
979 return hardware::Void();
980}
981
Corey Tabaka451256f2017-08-22 11:59:15 -0700982Return<void> HardwareComposer::ComposerCallback::onVsync(Hwc2::Display display,
983 int64_t timestamp) {
Steven Thomas6e8f7062017-11-22 14:15:29 -0800984 // Ignore any onVsync callbacks for the non-primary display.
985 if (has_display_id_ && display == display_id_) {
986 TRACE_FORMAT("vsync_callback|display=%" PRIu64 ";timestamp=%" PRId64 "|",
987 display, timestamp);
988 callback_vsync_timestamp_ = timestamp;
Steven Thomasb02664d2017-07-26 18:48:28 -0700989 }
990 return Void();
991}
992
Steven Thomas6e8f7062017-11-22 14:15:29 -0800993Status<int64_t> HardwareComposer::ComposerCallback::GetVsyncTime() {
Corey Tabakab3732f02017-09-16 00:58:54 -0700994 // See if the driver supports direct vsync events.
Steven Thomas6e8f7062017-11-22 14:15:29 -0800995 LocalHandle& event_fd = driver_vsync_event_fd_;
Corey Tabakab3732f02017-09-16 00:58:54 -0700996 if (!event_fd) {
997 // Fall back to returning the last timestamp returned by the vsync
998 // callback.
999 std::lock_guard<std::mutex> autolock(vsync_mutex_);
Steven Thomas6e8f7062017-11-22 14:15:29 -08001000 return callback_vsync_timestamp_;
Corey Tabakab3732f02017-09-16 00:58:54 -07001001 }
1002
1003 // When the driver supports the vsync_event sysfs node we can use it to
1004 // determine the latest vsync timestamp, even if the HWC callback has been
1005 // delayed.
1006
1007 // The driver returns data in the form "VSYNC=<timestamp ns>".
1008 std::array<char, 32> data;
1009 data.fill('\0');
1010
1011 // Seek back to the beginning of the event file.
1012 int ret = lseek(event_fd.Get(), 0, SEEK_SET);
1013 if (ret < 0) {
1014 const int error = errno;
1015 ALOGE(
1016 "HardwareComposer::ComposerCallback::GetVsyncTime: Failed to seek "
1017 "vsync event fd: %s",
1018 strerror(error));
1019 return ErrorStatus(error);
1020 }
1021
1022 // Read the vsync event timestamp.
1023 ret = read(event_fd.Get(), data.data(), data.size());
1024 if (ret < 0) {
1025 const int error = errno;
1026 ALOGE_IF(error != EAGAIN,
1027 "HardwareComposer::ComposerCallback::GetVsyncTime: Error "
1028 "while reading timestamp: %s",
1029 strerror(error));
1030 return ErrorStatus(error);
1031 }
1032
1033 int64_t timestamp;
1034 ret = sscanf(data.data(), "VSYNC=%" PRIu64,
1035 reinterpret_cast<uint64_t*>(&timestamp));
1036 if (ret < 0) {
1037 const int error = errno;
1038 ALOGE(
1039 "HardwareComposer::ComposerCallback::GetVsyncTime: Error while "
1040 "parsing timestamp: %s",
1041 strerror(error));
1042 return ErrorStatus(error);
1043 }
1044
1045 return {timestamp};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001046}
1047
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001048Hwc2::Composer* Layer::composer_{nullptr};
1049HWCDisplayMetrics Layer::display_metrics_{0, 0, {0, 0}, 0};
Steven Thomas6e8f7062017-11-22 14:15:29 -08001050hwc2_display_t Layer::display_id_{0};
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001051
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001052void Layer::Reset() {
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001053 if (hardware_composer_layer_) {
Steven Thomas6e8f7062017-11-22 14:15:29 -08001054 composer_->destroyLayer(display_id_, hardware_composer_layer_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001055 hardware_composer_layer_ = 0;
1056 }
1057
Corey Tabaka2251d822017-04-20 16:04:07 -07001058 z_order_ = 0;
1059 blending_ = HWC::BlendMode::None;
1060 transform_ = HWC::Transform::None;
1061 composition_type_ = HWC::Composition::Invalid;
1062 target_composition_type_ = composition_type_;
1063 source_ = EmptyVariant{};
1064 acquire_fence_.Close();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001065 surface_rect_functions_applied_ = false;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001066 pending_visibility_settings_ = true;
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001067 cached_buffer_map_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001068}
1069
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001070Layer::Layer(const std::shared_ptr<DirectDisplaySurface>& surface,
1071 HWC::BlendMode blending, HWC::Transform transform,
1072 HWC::Composition composition_type, size_t z_order)
1073 : z_order_{z_order},
1074 blending_{blending},
1075 transform_{transform},
1076 target_composition_type_{composition_type},
1077 source_{SourceSurface{surface}} {
1078 CommonLayerSetup();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001079}
1080
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001081Layer::Layer(const std::shared_ptr<IonBuffer>& buffer, HWC::BlendMode blending,
1082 HWC::Transform transform, HWC::Composition composition_type,
1083 size_t z_order)
1084 : z_order_{z_order},
1085 blending_{blending},
1086 transform_{transform},
1087 target_composition_type_{composition_type},
1088 source_{SourceBuffer{buffer}} {
1089 CommonLayerSetup();
1090}
1091
1092Layer::~Layer() { Reset(); }
1093
1094Layer::Layer(Layer&& other) { *this = std::move(other); }
1095
1096Layer& Layer::operator=(Layer&& other) {
1097 if (this != &other) {
1098 Reset();
1099 using std::swap;
1100 swap(hardware_composer_layer_, other.hardware_composer_layer_);
1101 swap(z_order_, other.z_order_);
1102 swap(blending_, other.blending_);
1103 swap(transform_, other.transform_);
1104 swap(composition_type_, other.composition_type_);
1105 swap(target_composition_type_, other.target_composition_type_);
1106 swap(source_, other.source_);
1107 swap(acquire_fence_, other.acquire_fence_);
1108 swap(surface_rect_functions_applied_,
1109 other.surface_rect_functions_applied_);
1110 swap(pending_visibility_settings_, other.pending_visibility_settings_);
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001111 swap(cached_buffer_map_, other.cached_buffer_map_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001112 }
1113 return *this;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001114}
1115
Corey Tabaka2251d822017-04-20 16:04:07 -07001116void Layer::UpdateBuffer(const std::shared_ptr<IonBuffer>& buffer) {
1117 if (source_.is<SourceBuffer>())
1118 std::get<SourceBuffer>(source_) = {buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001119}
1120
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001121void Layer::SetBlending(HWC::BlendMode blending) {
1122 if (blending_ != blending) {
1123 blending_ = blending;
1124 pending_visibility_settings_ = true;
1125 }
1126}
1127
1128void Layer::SetZOrder(size_t z_order) {
1129 if (z_order_ != z_order) {
1130 z_order_ = z_order;
1131 pending_visibility_settings_ = true;
1132 }
1133}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001134
1135IonBuffer* Layer::GetBuffer() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001136 struct Visitor {
1137 IonBuffer* operator()(SourceSurface& source) { return source.GetBuffer(); }
1138 IonBuffer* operator()(SourceBuffer& source) { return source.GetBuffer(); }
1139 IonBuffer* operator()(EmptyVariant) { return nullptr; }
1140 };
1141 return source_.Visit(Visitor{});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001142}
1143
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001144void Layer::UpdateVisibilitySettings() {
1145 if (pending_visibility_settings_) {
1146 pending_visibility_settings_ = false;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001147
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001148 HWC::Error error;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001149
1150 error = composer_->setLayerBlendMode(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001151 display_id_, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001152 blending_.cast<Hwc2::IComposerClient::BlendMode>());
1153 ALOGE_IF(error != HWC::Error::None,
1154 "Layer::UpdateLayerSettings: Error setting layer blend mode: %s",
1155 error.to_string().c_str());
1156
Steven Thomas6e8f7062017-11-22 14:15:29 -08001157 error = composer_->setLayerZOrder(display_id_, hardware_composer_layer_,
1158 z_order_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001159 ALOGE_IF(error != HWC::Error::None,
1160 "Layer::UpdateLayerSettings: Error setting z_ order: %s",
1161 error.to_string().c_str());
1162 }
1163}
1164
1165void Layer::UpdateLayerSettings() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001166 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001167
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001168 UpdateVisibilitySettings();
1169
Corey Tabaka2251d822017-04-20 16:04:07 -07001170 // TODO(eieio): Use surface attributes or some other mechanism to control
1171 // the layer display frame.
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001172 error = composer_->setLayerDisplayFrame(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001173 display_id_, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001174 {0, 0, display_metrics_.width, display_metrics_.height});
Corey Tabaka2251d822017-04-20 16:04:07 -07001175 ALOGE_IF(error != HWC::Error::None,
1176 "Layer::UpdateLayerSettings: Error setting layer display frame: %s",
1177 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001178
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001179 error = composer_->setLayerVisibleRegion(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001180 display_id_, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001181 {{0, 0, display_metrics_.width, display_metrics_.height}});
Corey Tabaka2251d822017-04-20 16:04:07 -07001182 ALOGE_IF(error != HWC::Error::None,
1183 "Layer::UpdateLayerSettings: Error setting layer visible region: %s",
1184 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001185
Steven Thomas6e8f7062017-11-22 14:15:29 -08001186 error = composer_->setLayerPlaneAlpha(display_id_, hardware_composer_layer_,
1187 1.0f);
Corey Tabaka2251d822017-04-20 16:04:07 -07001188 ALOGE_IF(error != HWC::Error::None,
1189 "Layer::UpdateLayerSettings: Error setting layer plane alpha: %s",
1190 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001191}
1192
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001193void Layer::CommonLayerSetup() {
Steven Thomas6e8f7062017-11-22 14:15:29 -08001194 HWC::Error error = composer_->createLayer(display_id_,
1195 &hardware_composer_layer_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001196 ALOGE_IF(error != HWC::Error::None,
1197 "Layer::CommonLayerSetup: Failed to create layer on primary "
1198 "display: %s",
1199 error.to_string().c_str());
1200 UpdateLayerSettings();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001201}
1202
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001203bool Layer::CheckAndUpdateCachedBuffer(std::size_t slot, int buffer_id) {
1204 auto search = cached_buffer_map_.find(slot);
1205 if (search != cached_buffer_map_.end() && search->second == buffer_id)
1206 return true;
1207
1208 // Assign or update the buffer slot.
1209 if (buffer_id >= 0)
1210 cached_buffer_map_[slot] = buffer_id;
1211 return false;
1212}
1213
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001214void Layer::Prepare() {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001215 int right, bottom, id;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -04001216 sp<GraphicBuffer> handle;
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001217 std::size_t slot;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001218
Corey Tabaka2251d822017-04-20 16:04:07 -07001219 // Acquire the next buffer according to the type of source.
1220 IfAnyOf<SourceSurface, SourceBuffer>::Call(&source_, [&](auto& source) {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001221 std::tie(right, bottom, id, handle, acquire_fence_, slot) =
1222 source.Acquire();
Corey Tabaka2251d822017-04-20 16:04:07 -07001223 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001224
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001225 TRACE_FORMAT("Layer::Prepare|buffer_id=%d;slot=%zu|", id, slot);
1226
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001227 // Update any visibility (blending, z-order) changes that occurred since
1228 // last prepare.
1229 UpdateVisibilitySettings();
1230
1231 // When a layer is first setup there may be some time before the first
1232 // buffer arrives. Setup the HWC layer as a solid color to stall for time
1233 // until the first buffer arrives. Once the first buffer arrives there will
1234 // always be a buffer for the frame even if it is old.
Corey Tabaka2251d822017-04-20 16:04:07 -07001235 if (!handle.get()) {
1236 if (composition_type_ == HWC::Composition::Invalid) {
1237 composition_type_ = HWC::Composition::SolidColor;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001238 composer_->setLayerCompositionType(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001239 display_id_, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001240 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1241 Hwc2::IComposerClient::Color layer_color = {0, 0, 0, 0};
Steven Thomas6e8f7062017-11-22 14:15:29 -08001242 composer_->setLayerColor(display_id_, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001243 layer_color);
Corey Tabaka2251d822017-04-20 16:04:07 -07001244 } else {
1245 // The composition type is already set. Nothing else to do until a
1246 // buffer arrives.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001247 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001248 } else {
Corey Tabaka2251d822017-04-20 16:04:07 -07001249 if (composition_type_ != target_composition_type_) {
1250 composition_type_ = target_composition_type_;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001251 composer_->setLayerCompositionType(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001252 display_id_, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001253 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1254 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001255
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001256 // See if the HWC cache already has this buffer.
1257 const bool cached = CheckAndUpdateCachedBuffer(slot, id);
1258 if (cached)
1259 handle = nullptr;
1260
Corey Tabaka2251d822017-04-20 16:04:07 -07001261 HWC::Error error{HWC::Error::None};
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001262 error =
Steven Thomas6e8f7062017-11-22 14:15:29 -08001263 composer_->setLayerBuffer(display_id_, hardware_composer_layer_,
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001264 slot, handle, acquire_fence_.Get());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001265
Corey Tabaka2251d822017-04-20 16:04:07 -07001266 ALOGE_IF(error != HWC::Error::None,
1267 "Layer::Prepare: Error setting layer buffer: %s",
1268 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001269
Corey Tabaka2251d822017-04-20 16:04:07 -07001270 if (!surface_rect_functions_applied_) {
1271 const float float_right = right;
1272 const float float_bottom = bottom;
Steven Thomas6e8f7062017-11-22 14:15:29 -08001273 error = composer_->setLayerSourceCrop(display_id_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001274 hardware_composer_layer_,
1275 {0, 0, float_right, float_bottom});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001276
Corey Tabaka2251d822017-04-20 16:04:07 -07001277 ALOGE_IF(error != HWC::Error::None,
1278 "Layer::Prepare: Error setting layer source crop: %s",
1279 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001280
Corey Tabaka2251d822017-04-20 16:04:07 -07001281 surface_rect_functions_applied_ = true;
1282 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001283 }
1284}
1285
1286void Layer::Finish(int release_fence_fd) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001287 IfAnyOf<SourceSurface, SourceBuffer>::Call(
1288 &source_, [release_fence_fd](auto& source) {
1289 source.Finish(LocalHandle(release_fence_fd));
1290 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001291}
1292
Corey Tabaka2251d822017-04-20 16:04:07 -07001293void Layer::Drop() { acquire_fence_.Close(); }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001294
1295} // namespace dvr
1296} // namespace android