blob: 5b4964553cfd4489dde5de4af19e4e8f197a2b42 [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 kDvrPerformanceProperty[] = "sys.dvr.performance";
Corey Tabaka451256f2017-08-22 11:59:15 -070049const char kDvrStandaloneProperty[] = "ro.boot.vr";
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080050
Luke Song4b788322017-03-24 14:17:31 -070051const char kRightEyeOffsetProperty[] = "dvr.right_eye_offset_ns";
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080052
Steven Thomasaf336272018-01-04 17:36:47 -080053// How long to wait after boot finishes before we turn the display off.
54constexpr int kBootFinishedDisplayOffTimeoutSec = 10;
55
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 Thomas7f8761e2018-01-18 18:49:59 -0800191
192 std::unique_lock<std::mutex> lock(post_thread_mutex_);
193 post_thread_ready_.wait(lock, [this] {
194 return !post_thread_resumed_;
195 });
Steven Thomas050b2c82017-03-06 11:45:16 -0800196}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800197
Steven Thomasaf336272018-01-04 17:36:47 -0800198void HardwareComposer::OnBootFinished() {
199 std::lock_guard<std::mutex> lock(post_thread_mutex_);
200 if (boot_finished_)
201 return;
202 boot_finished_ = true;
203 post_thread_wait_.notify_one();
204 if (is_standalone_device_)
205 request_display_callback_(true);
206}
207
Corey Tabaka2251d822017-04-20 16:04:07 -0700208// Update the post thread quiescent state based on idle and suspended inputs.
209void HardwareComposer::UpdatePostThreadState(PostThreadStateType state,
210 bool suspend) {
211 std::unique_lock<std::mutex> lock(post_thread_mutex_);
212
213 // Update the votes in the state variable before evaluating the effective
214 // quiescent state. Any bits set in post_thread_state_ indicate that the post
215 // thread should be suspended.
216 if (suspend) {
217 post_thread_state_ |= state;
218 } else {
219 post_thread_state_ &= ~state;
220 }
221
222 const bool quit = post_thread_state_ & PostThreadState::Quit;
223 const bool effective_suspend = post_thread_state_ != PostThreadState::Active;
224 if (quit) {
225 post_thread_quiescent_ = true;
226 eventfd_write(post_thread_event_fd_.Get(), 1);
227 post_thread_wait_.notify_one();
228 } else if (effective_suspend && !post_thread_quiescent_) {
229 post_thread_quiescent_ = true;
230 eventfd_write(post_thread_event_fd_.Get(), 1);
231 } else if (!effective_suspend && post_thread_quiescent_) {
232 post_thread_quiescent_ = false;
233 eventfd_t value;
234 eventfd_read(post_thread_event_fd_.Get(), &value);
235 post_thread_wait_.notify_one();
236 }
Steven Thomas050b2c82017-03-06 11:45:16 -0800237}
Steven Thomas282a5ed2017-02-07 18:07:01 -0800238
Steven Thomas050b2c82017-03-06 11:45:16 -0800239void HardwareComposer::OnPostThreadResumed() {
Corey Tabaka451256f2017-08-22 11:59:15 -0700240 // Phones create a new composer client on resume and destroy it on pause.
241 // Standalones only create the composer client once and then use SetPowerMode
242 // to control the screen on pause/resume.
243 if (!is_standalone_device_ || !composer_) {
Lloyd Piquea822d522017-12-20 16:42:57 -0800244 composer_.reset(new Hwc2::impl::Composer("default"));
Corey Tabaka451256f2017-08-22 11:59:15 -0700245 composer_callback_ = new ComposerCallback;
246 composer_->registerCallback(composer_callback_);
Steven Thomas6e8f7062017-11-22 14:15:29 -0800247 LOG_ALWAYS_FATAL_IF(!composer_callback_->HasDisplayId(),
248 "Registered composer callback but didn't get primary display");
Corey Tabaka451256f2017-08-22 11:59:15 -0700249 Layer::SetComposer(composer_.get());
Steven Thomas6e8f7062017-11-22 14:15:29 -0800250 Layer::SetDisplayId(composer_callback_->GetDisplayId());
Corey Tabaka451256f2017-08-22 11:59:15 -0700251 } else {
252 SetPowerMode(true);
253 }
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700254
Steven Thomas050b2c82017-03-06 11:45:16 -0800255 EnableVsync(true);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800256
Steven Thomas050b2c82017-03-06 11:45:16 -0800257 // Trigger target-specific performance mode change.
258 property_set(kDvrPerformanceProperty, "performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800259}
260
Steven Thomas050b2c82017-03-06 11:45:16 -0800261void HardwareComposer::OnPostThreadPaused() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700262 retire_fence_fds_.clear();
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700263 layers_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800264
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700265 if (composer_) {
Steven Thomasb02664d2017-07-26 18:48:28 -0700266 EnableVsync(false);
267 }
Steven Thomas050b2c82017-03-06 11:45:16 -0800268
Corey Tabaka451256f2017-08-22 11:59:15 -0700269 if (!is_standalone_device_) {
270 composer_callback_ = nullptr;
271 composer_.reset(nullptr);
272 Layer::SetComposer(nullptr);
Steven Thomas6e8f7062017-11-22 14:15:29 -0800273 Layer::SetDisplayId(0);
Corey Tabaka451256f2017-08-22 11:59:15 -0700274 } else {
275 SetPowerMode(false);
276 }
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700277
Steven Thomas050b2c82017-03-06 11:45:16 -0800278 // Trigger target-specific performance mode change.
279 property_set(kDvrPerformanceProperty, "idle");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800280}
281
Steven Thomasaf336272018-01-04 17:36:47 -0800282bool HardwareComposer::PostThreadCondWait(std::unique_lock<std::mutex>& lock,
283 int timeout_sec,
284 const std::function<bool()>& pred) {
285 auto pred_with_quit = [&] {
286 return pred() || (post_thread_state_ & PostThreadState::Quit);
287 };
288 if (timeout_sec >= 0) {
289 post_thread_wait_.wait_for(lock, std::chrono::seconds(timeout_sec),
290 pred_with_quit);
291 } else {
292 post_thread_wait_.wait(lock, pred_with_quit);
293 }
294 if (post_thread_state_ & PostThreadState::Quit) {
295 ALOGI("HardwareComposer::PostThread: Quitting.");
296 return true;
297 }
298 return false;
299}
300
Corey Tabaka2251d822017-04-20 16:04:07 -0700301HWC::Error HardwareComposer::Validate(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800302 uint32_t num_types;
303 uint32_t num_requests;
Corey Tabaka2251d822017-04-20 16:04:07 -0700304 HWC::Error error =
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700305 composer_->validateDisplay(display, &num_types, &num_requests);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800306
307 if (error == HWC2_ERROR_HAS_CHANGES) {
308 // TODO(skiazyk): We might need to inspect the requested changes first, but
309 // so far it seems like we shouldn't ever hit a bad state.
310 // error = hwc2_funcs_.accept_display_changes_fn_(hardware_composer_device_,
311 // display);
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700312 error = composer_->acceptDisplayChanges(display);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800313 }
314
315 return error;
316}
317
Steven Thomasb02664d2017-07-26 18:48:28 -0700318HWC::Error HardwareComposer::EnableVsync(bool enabled) {
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700319 return composer_->setVsyncEnabled(
Steven Thomas6e8f7062017-11-22 14:15:29 -0800320 composer_callback_->GetDisplayId(),
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800321 (Hwc2::IComposerClient::Vsync)(enabled ? HWC2_VSYNC_ENABLE
322 : HWC2_VSYNC_DISABLE));
323}
324
Corey Tabaka451256f2017-08-22 11:59:15 -0700325HWC::Error HardwareComposer::SetPowerMode(bool active) {
326 HWC::PowerMode power_mode = active ? HWC::PowerMode::On : HWC::PowerMode::Off;
327 return composer_->setPowerMode(
Steven Thomas6e8f7062017-11-22 14:15:29 -0800328 composer_callback_->GetDisplayId(),
329 power_mode.cast<Hwc2::IComposerClient::PowerMode>());
Corey Tabaka451256f2017-08-22 11:59:15 -0700330}
331
Corey Tabaka2251d822017-04-20 16:04:07 -0700332HWC::Error HardwareComposer::Present(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800333 int32_t present_fence;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700334 HWC::Error error = composer_->presentDisplay(display, &present_fence);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800335
336 // According to the documentation, this fence is signaled at the time of
337 // vsync/DMA for physical displays.
Corey Tabaka2251d822017-04-20 16:04:07 -0700338 if (error == HWC::Error::None) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800339 ATRACE_INT("HardwareComposer: VsyncFence", present_fence);
340 retire_fence_fds_.emplace_back(present_fence);
341 } else {
342 ATRACE_INT("HardwareComposer: PresentResult", error);
343 }
344
345 return error;
346}
347
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700348HWC::Error HardwareComposer::GetDisplayAttribute(Hwc2::Composer* composer,
Steven Thomasb02664d2017-07-26 18:48:28 -0700349 hwc2_display_t display,
Corey Tabaka2251d822017-04-20 16:04:07 -0700350 hwc2_config_t config,
351 hwc2_attribute_t attribute,
352 int32_t* out_value) const {
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700353 return composer->getDisplayAttribute(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800354 display, config, (Hwc2::IComposerClient::Attribute)attribute, out_value);
355}
356
Corey Tabaka2251d822017-04-20 16:04:07 -0700357HWC::Error HardwareComposer::GetDisplayMetrics(
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700358 Hwc2::Composer* composer, hwc2_display_t display, hwc2_config_t config,
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800359 HWCDisplayMetrics* out_metrics) const {
Corey Tabaka2251d822017-04-20 16:04:07 -0700360 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800361
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700362 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_WIDTH,
Corey Tabaka2251d822017-04-20 16:04:07 -0700363 &out_metrics->width);
364 if (error != HWC::Error::None) {
365 ALOGE(
366 "HardwareComposer::GetDisplayMetrics: Failed to get display width: %s",
367 error.to_string().c_str());
368 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800369 }
370
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700371 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_HEIGHT,
Corey Tabaka2251d822017-04-20 16:04:07 -0700372 &out_metrics->height);
373 if (error != HWC::Error::None) {
374 ALOGE(
375 "HardwareComposer::GetDisplayMetrics: Failed to get display height: %s",
376 error.to_string().c_str());
377 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800378 }
379
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700380 error = GetDisplayAttribute(composer, display, config,
Steven Thomasb02664d2017-07-26 18:48:28 -0700381 HWC2_ATTRIBUTE_VSYNC_PERIOD,
Corey Tabaka2251d822017-04-20 16:04:07 -0700382 &out_metrics->vsync_period_ns);
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, HWC2_ATTRIBUTE_DPI_X,
Corey Tabaka2251d822017-04-20 16:04:07 -0700391 &out_metrics->dpi.x);
392 if (error != HWC::Error::None) {
393 ALOGE(
394 "HardwareComposer::GetDisplayMetrics: Failed to get display DPI X: %s",
395 error.to_string().c_str());
396 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800397 }
398
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700399 error = GetDisplayAttribute(composer, display, config, HWC2_ATTRIBUTE_DPI_Y,
Corey Tabaka2251d822017-04-20 16:04:07 -0700400 &out_metrics->dpi.y);
401 if (error != HWC::Error::None) {
402 ALOGE(
403 "HardwareComposer::GetDisplayMetrics: Failed to get display DPI Y: %s",
404 error.to_string().c_str());
405 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800406 }
407
Corey Tabaka2251d822017-04-20 16:04:07 -0700408 return HWC::Error::None;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800409}
410
Corey Tabaka0b485c92017-05-19 12:02:58 -0700411std::string HardwareComposer::Dump() {
412 std::unique_lock<std::mutex> lock(post_thread_mutex_);
413 std::ostringstream stream;
414
415 stream << "Display metrics: " << display_metrics_.width << "x"
416 << display_metrics_.height << " " << (display_metrics_.dpi.x / 1000.0)
417 << "x" << (display_metrics_.dpi.y / 1000.0) << " dpi @ "
418 << (1000000000.0 / display_metrics_.vsync_period_ns) << " Hz"
419 << std::endl;
420
421 stream << "Post thread resumed: " << post_thread_resumed_ << std::endl;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700422 stream << "Active layers: " << layers_.size() << std::endl;
Corey Tabaka0b485c92017-05-19 12:02:58 -0700423 stream << std::endl;
424
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700425 for (size_t i = 0; i < layers_.size(); i++) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700426 stream << "Layer " << i << ":";
427 stream << " type=" << layers_[i].GetCompositionType().to_string();
428 stream << " surface_id=" << layers_[i].GetSurfaceId();
429 stream << " buffer_id=" << layers_[i].GetBufferId();
430 stream << std::endl;
431 }
432 stream << std::endl;
433
434 if (post_thread_resumed_) {
435 stream << "Hardware Composer Debug Info:" << std::endl;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700436 stream << composer_->dumpDebugInfo();
Corey Tabaka0b485c92017-05-19 12:02:58 -0700437 }
438
439 return stream.str();
440}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800441
Corey Tabaka2251d822017-04-20 16:04:07 -0700442void HardwareComposer::PostLayers() {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800443 ATRACE_NAME("HardwareComposer::PostLayers");
444
445 // Setup the hardware composer layers with current buffers.
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700446 for (auto& layer : layers_) {
447 layer.Prepare();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800448 }
449
450 // Now that we have taken in a frame from the application, we have a chance
451 // to drop the frame before passing the frame along to HWC.
452 // If the display driver has become backed up, we detect it here and then
453 // react by skipping this frame to catch up latency.
454 while (!retire_fence_fds_.empty() &&
455 (!retire_fence_fds_.front() ||
456 sync_wait(retire_fence_fds_.front().Get(), 0) == 0)) {
457 // There are only 2 fences in here, no performance problem to shift the
458 // array of ints.
459 retire_fence_fds_.erase(retire_fence_fds_.begin());
460 }
461
George Burgess IV353a6f62017-06-26 17:13:09 -0700462 const bool is_fence_pending = static_cast<int32_t>(retire_fence_fds_.size()) >
John Bates954796e2017-05-11 11:00:31 -0700463 post_thread_config_.allowed_pending_fence_count;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800464
Corey Tabakab3732f02017-09-16 00:58:54 -0700465 if (is_fence_pending) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800466 ATRACE_INT("frame_skip_count", ++frame_skip_count_);
467
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800468 ALOGW_IF(is_fence_pending,
469 "Warning: dropping a frame to catch up with HWC (pending = %zd)",
470 retire_fence_fds_.size());
471
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700472 for (auto& layer : layers_) {
473 layer.Drop();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800474 }
475 return;
476 } else {
477 // Make the transition more obvious in systrace when the frame skip happens
478 // above.
479 ATRACE_INT("frame_skip_count", 0);
480 }
481
Corey Tabaka89bbefc2017-06-06 16:14:21 -0700482#if TRACE > 1
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700483 for (size_t i = 0; i < layers_.size(); i++) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700484 ALOGI("HardwareComposer::PostLayers: layer=%zu buffer_id=%d composition=%s",
485 i, layers_[i].GetBufferId(),
Corey Tabaka2251d822017-04-20 16:04:07 -0700486 layers_[i].GetCompositionType().to_string().c_str());
Corey Tabaka0b485c92017-05-19 12:02:58 -0700487 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800488#endif
489
John Bates46684842017-12-13 15:26:50 -0800490 HWC::Error error = Validate(composer_callback_->GetDisplayId());
491 if (error != HWC::Error::None) {
492 ALOGE("HardwareComposer::PostLayers: Validate failed: %s",
493 error.to_string().c_str());
494 return;
495 }
496
Steven Thomas6e8f7062017-11-22 14:15:29 -0800497 error = Present(composer_callback_->GetDisplayId());
Corey Tabaka2251d822017-04-20 16:04:07 -0700498 if (error != HWC::Error::None) {
499 ALOGE("HardwareComposer::PostLayers: Present failed: %s",
500 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800501 return;
502 }
503
504 std::vector<Hwc2::Layer> out_layers;
505 std::vector<int> out_fences;
Steven Thomas6e8f7062017-11-22 14:15:29 -0800506 error = composer_->getReleaseFences(composer_callback_->GetDisplayId(),
507 &out_layers, &out_fences);
Corey Tabaka2251d822017-04-20 16:04:07 -0700508 ALOGE_IF(error != HWC::Error::None,
509 "HardwareComposer::PostLayers: Failed to get release fences: %s",
510 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800511
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700512 // Perform post-frame bookkeeping.
Corey Tabaka2251d822017-04-20 16:04:07 -0700513 uint32_t num_elements = out_layers.size();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800514 for (size_t i = 0; i < num_elements; ++i) {
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700515 for (auto& layer : layers_) {
516 if (layer.GetLayerHandle() == out_layers[i]) {
517 layer.Finish(out_fences[i]);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800518 }
519 }
520 }
521}
522
Steven Thomas050b2c82017-03-06 11:45:16 -0800523void HardwareComposer::SetDisplaySurfaces(
Corey Tabaka2251d822017-04-20 16:04:07 -0700524 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces) {
Jin Qian7480c062017-03-21 00:04:15 +0000525 ALOGI("HardwareComposer::SetDisplaySurfaces: surface count=%zd",
526 surfaces.size());
Corey Tabaka2251d822017-04-20 16:04:07 -0700527 const bool display_idle = surfaces.size() == 0;
528 {
529 std::unique_lock<std::mutex> lock(post_thread_mutex_);
530 pending_surfaces_ = std::move(surfaces);
531 }
532
Steven Thomasaf336272018-01-04 17:36:47 -0800533 if (request_display_callback_ && !is_standalone_device_)
Steven Thomas2ddf5672017-06-15 11:38:40 -0700534 request_display_callback_(!display_idle);
535
Corey Tabaka2251d822017-04-20 16:04:07 -0700536 // Set idle state based on whether there are any surfaces to handle.
537 UpdatePostThreadState(PostThreadState::Idle, display_idle);
Steven Thomas050b2c82017-03-06 11:45:16 -0800538}
Jin Qian7480c062017-03-21 00:04:15 +0000539
John Bates954796e2017-05-11 11:00:31 -0700540int HardwareComposer::OnNewGlobalBuffer(DvrGlobalBufferKey key,
541 IonBuffer& ion_buffer) {
Okan Arikan822b7102017-05-08 13:31:34 -0700542 if (key == DvrGlobalBuffers::kVsyncBuffer) {
543 vsync_ring_ = std::make_unique<CPUMappedBroadcastRing<DvrVsyncRing>>(
544 &ion_buffer, CPUUsageMode::WRITE_OFTEN);
545
546 if (vsync_ring_->IsMapped() == false) {
547 return -EPERM;
548 }
549 }
550
551 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700552 return MapConfigBuffer(ion_buffer);
553 }
554
555 return 0;
556}
557
558void HardwareComposer::OnDeletedGlobalBuffer(DvrGlobalBufferKey key) {
Okan Arikan822b7102017-05-08 13:31:34 -0700559 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700560 ConfigBufferDeleted();
561 }
562}
563
564int HardwareComposer::MapConfigBuffer(IonBuffer& ion_buffer) {
565 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700566 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700567
Okan Arikan6f468c62017-05-31 14:48:30 -0700568 if (ion_buffer.width() < DvrConfigRing::MemorySize()) {
John Bates954796e2017-05-11 11:00:31 -0700569 ALOGE("HardwareComposer::MapConfigBuffer: invalid buffer size.");
570 return -EINVAL;
571 }
572
573 void* buffer_base = 0;
574 int result = ion_buffer.Lock(ion_buffer.usage(), 0, 0, ion_buffer.width(),
575 ion_buffer.height(), &buffer_base);
576 if (result != 0) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700577 ALOGE(
578 "HardwareComposer::MapConfigBuffer: Failed to map vrflinger config "
579 "buffer.");
John Bates954796e2017-05-11 11:00:31 -0700580 return -EPERM;
581 }
582
Okan Arikan6f468c62017-05-31 14:48:30 -0700583 shared_config_ring_ = DvrConfigRing::Create(buffer_base, ion_buffer.width());
John Bates954796e2017-05-11 11:00:31 -0700584 ion_buffer.Unlock();
585
586 return 0;
587}
588
589void HardwareComposer::ConfigBufferDeleted() {
590 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700591 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700592}
593
594void HardwareComposer::UpdateConfigBuffer() {
595 std::lock_guard<std::mutex> lock(shared_config_mutex_);
596 if (!shared_config_ring_.is_valid())
597 return;
598 // Copy from latest record in shared_config_ring_ to local copy.
Okan Arikan6f468c62017-05-31 14:48:30 -0700599 DvrConfig record;
John Bates954796e2017-05-11 11:00:31 -0700600 if (shared_config_ring_.GetNewest(&shared_config_ring_sequence_, &record)) {
John Batescc65c3c2017-09-28 14:43:19 -0700601 ALOGI("DvrConfig updated: sequence %u, post offset %d",
602 shared_config_ring_sequence_, record.frame_post_offset_ns);
603 ++shared_config_ring_sequence_;
John Bates954796e2017-05-11 11:00:31 -0700604 post_thread_config_ = record;
605 }
606}
607
Corey Tabaka2251d822017-04-20 16:04:07 -0700608int HardwareComposer::PostThreadPollInterruptible(
Steven Thomasb02664d2017-07-26 18:48:28 -0700609 const pdx::LocalHandle& event_fd, int requested_events, int timeout_ms) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800610 pollfd pfd[2] = {
611 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700612 .fd = event_fd.Get(),
Steven Thomas66747c12017-03-22 18:45:31 -0700613 .events = static_cast<short>(requested_events),
614 .revents = 0,
Steven Thomas050b2c82017-03-06 11:45:16 -0800615 },
616 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700617 .fd = post_thread_event_fd_.Get(),
Steven Thomas050b2c82017-03-06 11:45:16 -0800618 .events = POLLPRI | POLLIN,
619 .revents = 0,
620 },
621 };
622 int ret, error;
623 do {
Steven Thomasb02664d2017-07-26 18:48:28 -0700624 ret = poll(pfd, 2, timeout_ms);
Steven Thomas050b2c82017-03-06 11:45:16 -0800625 error = errno;
626 ALOGW_IF(ret < 0,
627 "HardwareComposer::PostThreadPollInterruptible: Error during "
628 "poll(): %s (%d)",
629 strerror(error), error);
630 } while (ret < 0 && error == EINTR);
631
632 if (ret < 0) {
633 return -error;
Steven Thomasb02664d2017-07-26 18:48:28 -0700634 } else if (ret == 0) {
635 return -ETIMEDOUT;
Steven Thomas050b2c82017-03-06 11:45:16 -0800636 } else if (pfd[0].revents != 0) {
637 return 0;
638 } else if (pfd[1].revents != 0) {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -0700639 ALOGI("VrHwcPost thread interrupted: revents=%x", pfd[1].revents);
Steven Thomas050b2c82017-03-06 11:45:16 -0800640 return kPostThreadInterrupted;
641 } else {
642 return 0;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800643 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800644}
645
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800646// Waits for the next vsync and returns the timestamp of the vsync event. If
647// vsync already passed since the last call, returns the latest vsync timestamp
Steven Thomasb02664d2017-07-26 18:48:28 -0700648// instead of blocking.
Corey Tabakab3732f02017-09-16 00:58:54 -0700649Status<int64_t> HardwareComposer::WaitForVSync() {
650 const int64_t predicted_vsync_time =
651 last_vsync_timestamp_ +
652 display_metrics_.vsync_period_ns * vsync_prediction_interval_;
653 const int error = SleepUntil(predicted_vsync_time);
654 if (error < 0) {
655 ALOGE("HardwareComposer::WaifForVSync:: Failed to sleep: %s",
656 strerror(-error));
Steven Thomasb02664d2017-07-26 18:48:28 -0700657 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800658 }
Corey Tabakab3732f02017-09-16 00:58:54 -0700659 return {predicted_vsync_time};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800660}
661
662int HardwareComposer::SleepUntil(int64_t wakeup_timestamp) {
663 const int timer_fd = vsync_sleep_timer_fd_.Get();
664 const itimerspec wakeup_itimerspec = {
665 .it_interval = {.tv_sec = 0, .tv_nsec = 0},
666 .it_value = NsToTimespec(wakeup_timestamp),
667 };
668 int ret =
669 timerfd_settime(timer_fd, TFD_TIMER_ABSTIME, &wakeup_itimerspec, nullptr);
670 int error = errno;
671 if (ret < 0) {
672 ALOGE("HardwareComposer::SleepUntil: Failed to set timerfd: %s",
673 strerror(error));
674 return -error;
675 }
676
Corey Tabaka451256f2017-08-22 11:59:15 -0700677 return PostThreadPollInterruptible(vsync_sleep_timer_fd_, POLLIN,
678 /*timeout_ms*/ -1);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800679}
680
681void HardwareComposer::PostThread() {
682 // NOLINTNEXTLINE(runtime/int)
Steven Thomas050b2c82017-03-06 11:45:16 -0800683 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>("VrHwcPost"), 0, 0, 0);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800684
Corey Tabaka2251d822017-04-20 16:04:07 -0700685 // Set the scheduler to SCHED_FIFO with high priority. If this fails here
686 // there may have been a startup timing issue between this thread and
687 // performanced. Try again later when this thread becomes active.
688 bool thread_policy_setup =
689 SetThreadPolicy("graphics:high", "/system/performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800690
Steven Thomas050b2c82017-03-06 11:45:16 -0800691 // Create a timerfd based on CLOCK_MONOTINIC.
692 vsync_sleep_timer_fd_.Reset(timerfd_create(CLOCK_MONOTONIC, 0));
693 LOG_ALWAYS_FATAL_IF(
694 !vsync_sleep_timer_fd_,
695 "HardwareComposer: Failed to create vsync sleep timerfd: %s",
696 strerror(errno));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800697
698 const int64_t ns_per_frame = display_metrics_.vsync_period_ns;
699 const int64_t photon_offset_ns = GetPosePredictionTimeOffset(ns_per_frame);
700
701 // TODO(jbates) Query vblank time from device, when such an API is available.
702 // This value (6.3%) was measured on A00 in low persistence mode.
703 int64_t vblank_ns = ns_per_frame * 63 / 1000;
704 int64_t right_eye_photon_offset_ns = (ns_per_frame - vblank_ns) / 2;
705
706 // Check property for overriding right eye offset value.
707 right_eye_photon_offset_ns =
708 property_get_int64(kRightEyeOffsetProperty, right_eye_photon_offset_ns);
709
Steven Thomas050b2c82017-03-06 11:45:16 -0800710 bool was_running = false;
711
Steven Thomasaf336272018-01-04 17:36:47 -0800712 if (is_standalone_device_) {
713 // First, wait until boot finishes.
714 std::unique_lock<std::mutex> lock(post_thread_mutex_);
715 if (PostThreadCondWait(lock, -1, [this] { return boot_finished_; })) {
716 return;
717 }
718
719 // Then, wait until we're either leaving the quiescent state, or the boot
720 // finished display off timeout expires.
721 if (PostThreadCondWait(lock, kBootFinishedDisplayOffTimeoutSec,
722 [this] { return !post_thread_quiescent_; })) {
723 return;
724 }
725
726 LOG_ALWAYS_FATAL_IF(post_thread_state_ & PostThreadState::Suspended,
727 "Vr flinger should own the display by now.");
728 post_thread_resumed_ = true;
729 post_thread_ready_.notify_all();
730 OnPostThreadResumed();
731 was_running = true;
732 }
733
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800734 while (1) {
735 ATRACE_NAME("HardwareComposer::PostThread");
736
John Bates954796e2017-05-11 11:00:31 -0700737 // Check for updated config once per vsync.
738 UpdateConfigBuffer();
739
Corey Tabaka2251d822017-04-20 16:04:07 -0700740 while (post_thread_quiescent_) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800741 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Corey Tabaka2251d822017-04-20 16:04:07 -0700742 ALOGI("HardwareComposer::PostThread: Entering quiescent state.");
743
Corey Tabakadf0b9162017-08-03 17:14:08 -0700744 // Tear down resources if necessary.
745 if (was_running)
746 OnPostThreadPaused();
Corey Tabaka2251d822017-04-20 16:04:07 -0700747
748 was_running = false;
749 post_thread_resumed_ = false;
750 post_thread_ready_.notify_all();
751
Steven Thomasaf336272018-01-04 17:36:47 -0800752 if (PostThreadCondWait(lock, -1,
753 [this] { return !post_thread_quiescent_; })) {
754 // A true return value means we've been asked to quit.
Corey Tabaka2251d822017-04-20 16:04:07 -0700755 return;
Steven Thomas282a5ed2017-02-07 18:07:01 -0800756 }
Corey Tabaka2251d822017-04-20 16:04:07 -0700757
Corey Tabaka2251d822017-04-20 16:04:07 -0700758 post_thread_resumed_ = true;
759 post_thread_ready_.notify_all();
760
761 ALOGI("HardwareComposer::PostThread: Exiting quiescent state.");
Steven Thomas050b2c82017-03-06 11:45:16 -0800762 }
763
764 if (!was_running) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700765 // Setup resources.
Steven Thomas050b2c82017-03-06 11:45:16 -0800766 OnPostThreadResumed();
767 was_running = true;
Corey Tabaka2251d822017-04-20 16:04:07 -0700768
769 // Try to setup the scheduler policy if it failed during startup. Only
770 // attempt to do this on transitions from inactive to active to avoid
771 // spamming the system with RPCs and log messages.
772 if (!thread_policy_setup) {
773 thread_policy_setup =
774 SetThreadPolicy("graphics:high", "/system/performance");
775 }
Corey Tabakab3732f02017-09-16 00:58:54 -0700776
777 // Initialize the last vsync timestamp with the current time. The
778 // predictor below uses this time + the vsync interval in absolute time
779 // units for the initial delay. Once the driver starts reporting vsync the
780 // predictor will sync up with the real vsync.
781 last_vsync_timestamp_ = GetSystemClockNs();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800782 }
783
784 int64_t vsync_timestamp = 0;
785 {
Corey Tabakab3732f02017-09-16 00:58:54 -0700786 TRACE_FORMAT("wait_vsync|vsync=%u;last_timestamp=%" PRId64
787 ";prediction_interval=%d|",
788 vsync_count_ + 1, last_vsync_timestamp_,
789 vsync_prediction_interval_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800790
Corey Tabakab3732f02017-09-16 00:58:54 -0700791 auto status = WaitForVSync();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800792 ALOGE_IF(
Corey Tabakab3732f02017-09-16 00:58:54 -0700793 !status,
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800794 "HardwareComposer::PostThread: Failed to wait for vsync event: %s",
Corey Tabakab3732f02017-09-16 00:58:54 -0700795 status.GetErrorMessage().c_str());
796
797 // If there was an error either sleeping was interrupted due to pausing or
798 // there was an error getting the latest timestamp.
799 if (!status)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800800 continue;
Corey Tabakab3732f02017-09-16 00:58:54 -0700801
802 // Predicted vsync timestamp for this interval. This is stable because we
803 // use absolute time for the wakeup timer.
804 vsync_timestamp = status.get();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800805 }
806
Corey Tabakab3732f02017-09-16 00:58:54 -0700807 // Advance the vsync counter only if the system is keeping up with hardware
808 // vsync to give clients an indication of the delays.
809 if (vsync_prediction_interval_ == 1)
810 ++vsync_count_;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800811
Corey Tabaka2251d822017-04-20 16:04:07 -0700812 const bool layer_config_changed = UpdateLayerConfig();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800813
Okan Arikan822b7102017-05-08 13:31:34 -0700814 // Publish the vsync event.
815 if (vsync_ring_) {
816 DvrVsync vsync;
817 vsync.vsync_count = vsync_count_;
818 vsync.vsync_timestamp_ns = vsync_timestamp;
819 vsync.vsync_left_eye_offset_ns = photon_offset_ns;
820 vsync.vsync_right_eye_offset_ns = right_eye_photon_offset_ns;
821 vsync.vsync_period_ns = ns_per_frame;
822
823 vsync_ring_->Publish(vsync);
824 }
825
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800826 // Signal all of the vsync clients. Because absolute time is used for the
827 // wakeup time below, this can take a little time if necessary.
828 if (vsync_callback_)
Steven Thomas6e8f7062017-11-22 14:15:29 -0800829 vsync_callback_(vsync_timestamp, /*frame_time_estimate*/ 0, vsync_count_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800830
831 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700832 // Sleep until shortly before vsync.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800833 ATRACE_NAME("sleep");
834
Corey Tabaka2251d822017-04-20 16:04:07 -0700835 const int64_t display_time_est_ns = vsync_timestamp + ns_per_frame;
836 const int64_t now_ns = GetSystemClockNs();
John Bates954796e2017-05-11 11:00:31 -0700837 const int64_t sleep_time_ns = display_time_est_ns - now_ns -
838 post_thread_config_.frame_post_offset_ns;
839 const int64_t wakeup_time_ns =
840 display_time_est_ns - post_thread_config_.frame_post_offset_ns;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800841
842 ATRACE_INT64("sleep_time_ns", sleep_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800843 if (sleep_time_ns > 0) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700844 int error = SleepUntil(wakeup_time_ns);
John Bates46684842017-12-13 15:26:50 -0800845 ALOGE_IF(error < 0 && error != kPostThreadInterrupted,
846 "HardwareComposer::PostThread: Failed to sleep: %s",
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800847 strerror(-error));
John Bates46684842017-12-13 15:26:50 -0800848 // If the sleep was interrupted (error == kPostThreadInterrupted),
849 // we still go through and present this frame because we may have set
850 // layers earlier and we want to flush the Composer's internal command
851 // buffer by continuing through to validate and present.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800852 }
853 }
854
Corey Tabakab3732f02017-09-16 00:58:54 -0700855 {
Steven Thomas6e8f7062017-11-22 14:15:29 -0800856 auto status = composer_callback_->GetVsyncTime();
Corey Tabakab3732f02017-09-16 00:58:54 -0700857 if (!status) {
858 ALOGE("HardwareComposer::PostThread: Failed to get VSYNC time: %s",
859 status.GetErrorMessage().c_str());
860 }
861
862 // If we failed to read vsync there might be a problem with the driver.
863 // Since there's nothing we can do just behave as though we didn't get an
864 // updated vsync time and let the prediction continue.
865 const int64_t current_vsync_timestamp =
866 status ? status.get() : last_vsync_timestamp_;
867
868 const bool vsync_delayed =
869 last_vsync_timestamp_ == current_vsync_timestamp;
870 ATRACE_INT("vsync_delayed", vsync_delayed);
871
872 // If vsync was delayed advance the prediction interval and allow the
873 // fence logic in PostLayers() to skip the frame.
874 if (vsync_delayed) {
875 ALOGW(
876 "HardwareComposer::PostThread: VSYNC timestamp did not advance "
877 "since last frame: timestamp=%" PRId64 " prediction_interval=%d",
878 current_vsync_timestamp, vsync_prediction_interval_);
879 vsync_prediction_interval_++;
880 } else {
881 // We have an updated vsync timestamp, reset the prediction interval.
882 last_vsync_timestamp_ = current_vsync_timestamp;
883 vsync_prediction_interval_ = 1;
884 }
885 }
886
Corey Tabaka2251d822017-04-20 16:04:07 -0700887 PostLayers();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800888 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800889}
890
Corey Tabaka2251d822017-04-20 16:04:07 -0700891// Checks for changes in the surface stack and updates the layer config to
892// accomodate the new stack.
Steven Thomas050b2c82017-03-06 11:45:16 -0800893bool HardwareComposer::UpdateLayerConfig() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700894 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces;
Steven Thomas050b2c82017-03-06 11:45:16 -0800895 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700896 std::unique_lock<std::mutex> lock(post_thread_mutex_);
897 if (pending_surfaces_.empty())
Steven Thomas050b2c82017-03-06 11:45:16 -0800898 return false;
Corey Tabaka2251d822017-04-20 16:04:07 -0700899
900 surfaces = std::move(pending_surfaces_);
Steven Thomas050b2c82017-03-06 11:45:16 -0800901 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800902
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800903 ATRACE_NAME("UpdateLayerConfig_HwLayers");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800904
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700905 // Sort the new direct surface list by z-order to determine the relative order
906 // of the surfaces. This relative order is used for the HWC z-order value to
907 // insulate VrFlinger and HWC z-order semantics from each other.
908 std::sort(surfaces.begin(), surfaces.end(), [](const auto& a, const auto& b) {
909 return a->z_order() < b->z_order();
910 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800911
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700912 // Prepare a new layer stack, pulling in layers from the previous
913 // layer stack that are still active and updating their attributes.
914 std::vector<Layer> layers;
915 size_t layer_index = 0;
916 for (const auto& surface : surfaces) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700917 // The bottom layer is opaque, other layers blend.
918 HWC::BlendMode blending =
919 layer_index == 0 ? HWC::BlendMode::None : HWC::BlendMode::Coverage;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700920
921 // Try to find a layer for this surface in the set of active layers.
922 auto search =
923 std::lower_bound(layers_.begin(), layers_.end(), surface->surface_id());
924 const bool found = search != layers_.end() &&
925 search->GetSurfaceId() == surface->surface_id();
926 if (found) {
927 // Update the attributes of the layer that may have changed.
928 search->SetBlending(blending);
929 search->SetZOrder(layer_index); // Relative z-order.
930
931 // Move the existing layer to the new layer set and remove the empty layer
932 // object from the current set.
933 layers.push_back(std::move(*search));
934 layers_.erase(search);
935 } else {
936 // Insert a layer for the new surface.
937 layers.emplace_back(surface, blending, display_transform_,
938 HWC::Composition::Device, layer_index);
939 }
940
941 ALOGI_IF(
942 TRACE,
943 "HardwareComposer::UpdateLayerConfig: layer_index=%zu surface_id=%d",
944 layer_index, layers[layer_index].GetSurfaceId());
945
946 layer_index++;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800947 }
948
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700949 // Sort the new layer stack by ascending surface id.
950 std::sort(layers.begin(), layers.end());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800951
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700952 // Replace the previous layer set with the new layer set. The destructor of
953 // the previous set will clean up the remaining Layers that are not moved to
954 // the new layer set.
955 layers_ = std::move(layers);
956
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800957 ALOGD_IF(TRACE, "HardwareComposer::UpdateLayerConfig: %zd active layers",
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700958 layers_.size());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800959 return true;
960}
961
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800962void HardwareComposer::SetVSyncCallback(VSyncCallback callback) {
963 vsync_callback_ = callback;
964}
965
Steven Thomasb02664d2017-07-26 18:48:28 -0700966Return<void> HardwareComposer::ComposerCallback::onHotplug(
Steven Thomas6e8f7062017-11-22 14:15:29 -0800967 Hwc2::Display display, IComposerCallback::Connection conn) {
968 // Our first onHotplug callback is always for the primary display.
969 //
970 // Ignore any other hotplug callbacks since the primary display is never
971 // disconnected and we don't care about other displays.
972 if (!has_display_id_) {
973 LOG_ALWAYS_FATAL_IF(conn != IComposerCallback::Connection::CONNECTED,
974 "Initial onHotplug callback should be primary display connected");
975 has_display_id_ = true;
976 display_id_ = display;
977
Corey Tabakab3732f02017-09-16 00:58:54 -0700978 std::array<char, 1024> buffer;
979 snprintf(buffer.data(), buffer.size(),
980 "/sys/class/graphics/fb%" PRIu64 "/vsync_event", display);
981 if (LocalHandle handle{buffer.data(), O_RDONLY}) {
982 ALOGI(
983 "HardwareComposer::ComposerCallback::onHotplug: Driver supports "
984 "vsync_event node for display %" PRIu64,
985 display);
Steven Thomas6e8f7062017-11-22 14:15:29 -0800986 driver_vsync_event_fd_ = std::move(handle);
Corey Tabakab3732f02017-09-16 00:58:54 -0700987 } else {
988 ALOGI(
989 "HardwareComposer::ComposerCallback::onHotplug: Driver does not "
990 "support vsync_event node for display %" PRIu64,
991 display);
992 }
993 }
994
Steven Thomasb02664d2017-07-26 18:48:28 -0700995 return Void();
996}
997
998Return<void> HardwareComposer::ComposerCallback::onRefresh(
999 Hwc2::Display /*display*/) {
1000 return hardware::Void();
1001}
1002
Corey Tabaka451256f2017-08-22 11:59:15 -07001003Return<void> HardwareComposer::ComposerCallback::onVsync(Hwc2::Display display,
1004 int64_t timestamp) {
Steven Thomas6e8f7062017-11-22 14:15:29 -08001005 // Ignore any onVsync callbacks for the non-primary display.
1006 if (has_display_id_ && display == display_id_) {
1007 TRACE_FORMAT("vsync_callback|display=%" PRIu64 ";timestamp=%" PRId64 "|",
1008 display, timestamp);
1009 callback_vsync_timestamp_ = timestamp;
Steven Thomasb02664d2017-07-26 18:48:28 -07001010 }
1011 return Void();
1012}
1013
Steven Thomas6e8f7062017-11-22 14:15:29 -08001014Status<int64_t> HardwareComposer::ComposerCallback::GetVsyncTime() {
Corey Tabakab3732f02017-09-16 00:58:54 -07001015 // See if the driver supports direct vsync events.
Steven Thomas6e8f7062017-11-22 14:15:29 -08001016 LocalHandle& event_fd = driver_vsync_event_fd_;
Corey Tabakab3732f02017-09-16 00:58:54 -07001017 if (!event_fd) {
1018 // Fall back to returning the last timestamp returned by the vsync
1019 // callback.
1020 std::lock_guard<std::mutex> autolock(vsync_mutex_);
Steven Thomas6e8f7062017-11-22 14:15:29 -08001021 return callback_vsync_timestamp_;
Corey Tabakab3732f02017-09-16 00:58:54 -07001022 }
1023
1024 // When the driver supports the vsync_event sysfs node we can use it to
1025 // determine the latest vsync timestamp, even if the HWC callback has been
1026 // delayed.
1027
1028 // The driver returns data in the form "VSYNC=<timestamp ns>".
1029 std::array<char, 32> data;
1030 data.fill('\0');
1031
1032 // Seek back to the beginning of the event file.
1033 int ret = lseek(event_fd.Get(), 0, SEEK_SET);
1034 if (ret < 0) {
1035 const int error = errno;
1036 ALOGE(
1037 "HardwareComposer::ComposerCallback::GetVsyncTime: Failed to seek "
1038 "vsync event fd: %s",
1039 strerror(error));
1040 return ErrorStatus(error);
1041 }
1042
1043 // Read the vsync event timestamp.
1044 ret = read(event_fd.Get(), data.data(), data.size());
1045 if (ret < 0) {
1046 const int error = errno;
1047 ALOGE_IF(error != EAGAIN,
1048 "HardwareComposer::ComposerCallback::GetVsyncTime: Error "
1049 "while reading timestamp: %s",
1050 strerror(error));
1051 return ErrorStatus(error);
1052 }
1053
1054 int64_t timestamp;
1055 ret = sscanf(data.data(), "VSYNC=%" PRIu64,
1056 reinterpret_cast<uint64_t*>(&timestamp));
1057 if (ret < 0) {
1058 const int error = errno;
1059 ALOGE(
1060 "HardwareComposer::ComposerCallback::GetVsyncTime: Error while "
1061 "parsing timestamp: %s",
1062 strerror(error));
1063 return ErrorStatus(error);
1064 }
1065
1066 return {timestamp};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001067}
1068
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001069Hwc2::Composer* Layer::composer_{nullptr};
1070HWCDisplayMetrics Layer::display_metrics_{0, 0, {0, 0}, 0};
Steven Thomas6e8f7062017-11-22 14:15:29 -08001071hwc2_display_t Layer::display_id_{0};
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001072
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001073void Layer::Reset() {
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001074 if (hardware_composer_layer_) {
Steven Thomas6e8f7062017-11-22 14:15:29 -08001075 composer_->destroyLayer(display_id_, hardware_composer_layer_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001076 hardware_composer_layer_ = 0;
1077 }
1078
Corey Tabaka2251d822017-04-20 16:04:07 -07001079 z_order_ = 0;
1080 blending_ = HWC::BlendMode::None;
1081 transform_ = HWC::Transform::None;
1082 composition_type_ = HWC::Composition::Invalid;
1083 target_composition_type_ = composition_type_;
1084 source_ = EmptyVariant{};
1085 acquire_fence_.Close();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001086 surface_rect_functions_applied_ = false;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001087 pending_visibility_settings_ = true;
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001088 cached_buffer_map_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001089}
1090
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001091Layer::Layer(const std::shared_ptr<DirectDisplaySurface>& surface,
1092 HWC::BlendMode blending, HWC::Transform transform,
1093 HWC::Composition composition_type, size_t z_order)
1094 : z_order_{z_order},
1095 blending_{blending},
1096 transform_{transform},
1097 target_composition_type_{composition_type},
1098 source_{SourceSurface{surface}} {
1099 CommonLayerSetup();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001100}
1101
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001102Layer::Layer(const std::shared_ptr<IonBuffer>& buffer, HWC::BlendMode blending,
1103 HWC::Transform transform, HWC::Composition composition_type,
1104 size_t z_order)
1105 : z_order_{z_order},
1106 blending_{blending},
1107 transform_{transform},
1108 target_composition_type_{composition_type},
1109 source_{SourceBuffer{buffer}} {
1110 CommonLayerSetup();
1111}
1112
1113Layer::~Layer() { Reset(); }
1114
1115Layer::Layer(Layer&& other) { *this = std::move(other); }
1116
1117Layer& Layer::operator=(Layer&& other) {
1118 if (this != &other) {
1119 Reset();
1120 using std::swap;
1121 swap(hardware_composer_layer_, other.hardware_composer_layer_);
1122 swap(z_order_, other.z_order_);
1123 swap(blending_, other.blending_);
1124 swap(transform_, other.transform_);
1125 swap(composition_type_, other.composition_type_);
1126 swap(target_composition_type_, other.target_composition_type_);
1127 swap(source_, other.source_);
1128 swap(acquire_fence_, other.acquire_fence_);
1129 swap(surface_rect_functions_applied_,
1130 other.surface_rect_functions_applied_);
1131 swap(pending_visibility_settings_, other.pending_visibility_settings_);
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001132 swap(cached_buffer_map_, other.cached_buffer_map_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001133 }
1134 return *this;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001135}
1136
Corey Tabaka2251d822017-04-20 16:04:07 -07001137void Layer::UpdateBuffer(const std::shared_ptr<IonBuffer>& buffer) {
1138 if (source_.is<SourceBuffer>())
1139 std::get<SourceBuffer>(source_) = {buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001140}
1141
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001142void Layer::SetBlending(HWC::BlendMode blending) {
1143 if (blending_ != blending) {
1144 blending_ = blending;
1145 pending_visibility_settings_ = true;
1146 }
1147}
1148
1149void Layer::SetZOrder(size_t z_order) {
1150 if (z_order_ != z_order) {
1151 z_order_ = z_order;
1152 pending_visibility_settings_ = true;
1153 }
1154}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001155
1156IonBuffer* Layer::GetBuffer() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001157 struct Visitor {
1158 IonBuffer* operator()(SourceSurface& source) { return source.GetBuffer(); }
1159 IonBuffer* operator()(SourceBuffer& source) { return source.GetBuffer(); }
1160 IonBuffer* operator()(EmptyVariant) { return nullptr; }
1161 };
1162 return source_.Visit(Visitor{});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001163}
1164
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001165void Layer::UpdateVisibilitySettings() {
1166 if (pending_visibility_settings_) {
1167 pending_visibility_settings_ = false;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001168
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001169 HWC::Error error;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001170
1171 error = composer_->setLayerBlendMode(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001172 display_id_, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001173 blending_.cast<Hwc2::IComposerClient::BlendMode>());
1174 ALOGE_IF(error != HWC::Error::None,
1175 "Layer::UpdateLayerSettings: Error setting layer blend mode: %s",
1176 error.to_string().c_str());
1177
Steven Thomas6e8f7062017-11-22 14:15:29 -08001178 error = composer_->setLayerZOrder(display_id_, hardware_composer_layer_,
1179 z_order_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001180 ALOGE_IF(error != HWC::Error::None,
1181 "Layer::UpdateLayerSettings: Error setting z_ order: %s",
1182 error.to_string().c_str());
1183 }
1184}
1185
1186void Layer::UpdateLayerSettings() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001187 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001188
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001189 UpdateVisibilitySettings();
1190
Corey Tabaka2251d822017-04-20 16:04:07 -07001191 // TODO(eieio): Use surface attributes or some other mechanism to control
1192 // the layer display frame.
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001193 error = composer_->setLayerDisplayFrame(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001194 display_id_, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001195 {0, 0, display_metrics_.width, display_metrics_.height});
Corey Tabaka2251d822017-04-20 16:04:07 -07001196 ALOGE_IF(error != HWC::Error::None,
1197 "Layer::UpdateLayerSettings: Error setting layer display frame: %s",
1198 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001199
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001200 error = composer_->setLayerVisibleRegion(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001201 display_id_, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001202 {{0, 0, display_metrics_.width, display_metrics_.height}});
Corey Tabaka2251d822017-04-20 16:04:07 -07001203 ALOGE_IF(error != HWC::Error::None,
1204 "Layer::UpdateLayerSettings: Error setting layer visible region: %s",
1205 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001206
Steven Thomas6e8f7062017-11-22 14:15:29 -08001207 error = composer_->setLayerPlaneAlpha(display_id_, hardware_composer_layer_,
1208 1.0f);
Corey Tabaka2251d822017-04-20 16:04:07 -07001209 ALOGE_IF(error != HWC::Error::None,
1210 "Layer::UpdateLayerSettings: Error setting layer plane alpha: %s",
1211 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001212}
1213
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001214void Layer::CommonLayerSetup() {
Steven Thomas6e8f7062017-11-22 14:15:29 -08001215 HWC::Error error = composer_->createLayer(display_id_,
1216 &hardware_composer_layer_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001217 ALOGE_IF(error != HWC::Error::None,
1218 "Layer::CommonLayerSetup: Failed to create layer on primary "
1219 "display: %s",
1220 error.to_string().c_str());
1221 UpdateLayerSettings();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001222}
1223
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001224bool Layer::CheckAndUpdateCachedBuffer(std::size_t slot, int buffer_id) {
1225 auto search = cached_buffer_map_.find(slot);
1226 if (search != cached_buffer_map_.end() && search->second == buffer_id)
1227 return true;
1228
1229 // Assign or update the buffer slot.
1230 if (buffer_id >= 0)
1231 cached_buffer_map_[slot] = buffer_id;
1232 return false;
1233}
1234
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001235void Layer::Prepare() {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001236 int right, bottom, id;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -04001237 sp<GraphicBuffer> handle;
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001238 std::size_t slot;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001239
Corey Tabaka2251d822017-04-20 16:04:07 -07001240 // Acquire the next buffer according to the type of source.
1241 IfAnyOf<SourceSurface, SourceBuffer>::Call(&source_, [&](auto& source) {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001242 std::tie(right, bottom, id, handle, acquire_fence_, slot) =
1243 source.Acquire();
Corey Tabaka2251d822017-04-20 16:04:07 -07001244 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001245
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001246 TRACE_FORMAT("Layer::Prepare|buffer_id=%d;slot=%zu|", id, slot);
1247
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001248 // Update any visibility (blending, z-order) changes that occurred since
1249 // last prepare.
1250 UpdateVisibilitySettings();
1251
1252 // When a layer is first setup there may be some time before the first
1253 // buffer arrives. Setup the HWC layer as a solid color to stall for time
1254 // until the first buffer arrives. Once the first buffer arrives there will
1255 // always be a buffer for the frame even if it is old.
Corey Tabaka2251d822017-04-20 16:04:07 -07001256 if (!handle.get()) {
1257 if (composition_type_ == HWC::Composition::Invalid) {
1258 composition_type_ = HWC::Composition::SolidColor;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001259 composer_->setLayerCompositionType(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001260 display_id_, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001261 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1262 Hwc2::IComposerClient::Color layer_color = {0, 0, 0, 0};
Steven Thomas6e8f7062017-11-22 14:15:29 -08001263 composer_->setLayerColor(display_id_, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001264 layer_color);
Corey Tabaka2251d822017-04-20 16:04:07 -07001265 } else {
1266 // The composition type is already set. Nothing else to do until a
1267 // buffer arrives.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001268 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001269 } else {
Corey Tabaka2251d822017-04-20 16:04:07 -07001270 if (composition_type_ != target_composition_type_) {
1271 composition_type_ = target_composition_type_;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001272 composer_->setLayerCompositionType(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001273 display_id_, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001274 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1275 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001276
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001277 // See if the HWC cache already has this buffer.
1278 const bool cached = CheckAndUpdateCachedBuffer(slot, id);
1279 if (cached)
1280 handle = nullptr;
1281
Corey Tabaka2251d822017-04-20 16:04:07 -07001282 HWC::Error error{HWC::Error::None};
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001283 error =
Steven Thomas6e8f7062017-11-22 14:15:29 -08001284 composer_->setLayerBuffer(display_id_, hardware_composer_layer_,
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001285 slot, handle, acquire_fence_.Get());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001286
Corey Tabaka2251d822017-04-20 16:04:07 -07001287 ALOGE_IF(error != HWC::Error::None,
1288 "Layer::Prepare: Error setting layer buffer: %s",
1289 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001290
Corey Tabaka2251d822017-04-20 16:04:07 -07001291 if (!surface_rect_functions_applied_) {
1292 const float float_right = right;
1293 const float float_bottom = bottom;
Steven Thomas6e8f7062017-11-22 14:15:29 -08001294 error = composer_->setLayerSourceCrop(display_id_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001295 hardware_composer_layer_,
1296 {0, 0, float_right, float_bottom});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001297
Corey Tabaka2251d822017-04-20 16:04:07 -07001298 ALOGE_IF(error != HWC::Error::None,
1299 "Layer::Prepare: Error setting layer source crop: %s",
1300 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001301
Corey Tabaka2251d822017-04-20 16:04:07 -07001302 surface_rect_functions_applied_ = true;
1303 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001304 }
1305}
1306
1307void Layer::Finish(int release_fence_fd) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001308 IfAnyOf<SourceSurface, SourceBuffer>::Call(
1309 &source_, [release_fence_fd](auto& source) {
1310 source.Finish(LocalHandle(release_fence_fd));
1311 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001312}
1313
Corey Tabaka2251d822017-04-20 16:04:07 -07001314void Layer::Drop() { acquire_fence_.Close(); }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001315
1316} // namespace dvr
1317} // namespace android