blob: 00172a1d84a6a35e6624f901af80fa28a417f9e1 [file] [log] [blame]
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001#include "hardware_composer.h"
2
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08003#include <cutils/properties.h>
4#include <cutils/sched_policy.h>
5#include <fcntl.h>
Corey Tabaka2251d822017-04-20 16:04:07 -07006#include <log/log.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08007#include <poll.h>
8#include <sync/sync.h>
9#include <sys/eventfd.h>
10#include <sys/prctl.h>
11#include <sys/resource.h>
12#include <sys/system_properties.h>
13#include <sys/timerfd.h>
Corey Tabaka2251d822017-04-20 16:04:07 -070014#include <time.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080015#include <unistd.h>
16#include <utils/Trace.h>
17
18#include <algorithm>
Corey Tabaka2251d822017-04-20 16:04:07 -070019#include <chrono>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080020#include <functional>
21#include <map>
Corey Tabaka0b485c92017-05-19 12:02:58 -070022#include <sstream>
23#include <string>
John Bates954796e2017-05-11 11:00:31 -070024#include <tuple>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080025
Corey Tabaka2251d822017-04-20 16:04:07 -070026#include <dvr/dvr_display_types.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080027#include <dvr/performance_client_api.h>
28#include <private/dvr/clock_ns.h>
Corey Tabaka2251d822017-04-20 16:04:07 -070029#include <private/dvr/ion_buffer.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080030
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080031using android::pdx::LocalHandle;
Corey Tabaka2251d822017-04-20 16:04:07 -070032using android::pdx::rpc::EmptyVariant;
33using android::pdx::rpc::IfAnyOf;
34
35using namespace std::chrono_literals;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080036
37namespace android {
38namespace dvr {
39
40namespace {
41
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080042const char kBacklightBrightnessSysFile[] =
43 "/sys/class/leds/lcd-backlight/brightness";
44
45const char kPrimaryDisplayVSyncEventFile[] =
46 "/sys/class/graphics/fb0/vsync_event";
47
48const char kPrimaryDisplayWaitPPEventFile[] = "/sys/class/graphics/fb0/wait_pp";
49
50const char kDvrPerformanceProperty[] = "sys.dvr.performance";
51
Luke Song4b788322017-03-24 14:17:31 -070052const char kRightEyeOffsetProperty[] = "dvr.right_eye_offset_ns";
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080053
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080054// Get time offset from a vsync to when the pose for that vsync should be
55// predicted out to. For example, if scanout gets halfway through the frame
56// at the halfway point between vsyncs, then this could be half the period.
57// With global shutter displays, this should be changed to the offset to when
58// illumination begins. Low persistence adds a frame of latency, so we predict
59// to the center of the next frame.
60inline int64_t GetPosePredictionTimeOffset(int64_t vsync_period_ns) {
61 return (vsync_period_ns * 150) / 100;
62}
63
Corey Tabaka2251d822017-04-20 16:04:07 -070064// Attempts to set the scheduler class and partiton for the current thread.
65// Returns true on success or false on failure.
66bool SetThreadPolicy(const std::string& scheduler_class,
67 const std::string& partition) {
68 int error = dvrSetSchedulerClass(0, scheduler_class.c_str());
69 if (error < 0) {
70 ALOGE(
71 "SetThreadPolicy: Failed to set scheduler class \"%s\" for "
72 "thread_id=%d: %s",
73 scheduler_class.c_str(), gettid(), strerror(-error));
74 return false;
75 }
76 error = dvrSetCpuPartition(0, partition.c_str());
77 if (error < 0) {
78 ALOGE(
79 "SetThreadPolicy: Failed to set cpu partiton \"%s\" for thread_id=%d: "
80 "%s",
81 partition.c_str(), gettid(), strerror(-error));
82 return false;
83 }
84 return true;
85}
86
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080087} // anonymous namespace
88
Corey Tabaka2251d822017-04-20 16:04:07 -070089// Layer static data.
90Hwc2::Composer* Layer::hwc2_hidl_;
91const HWCDisplayMetrics* Layer::display_metrics_;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080092
Corey Tabaka2251d822017-04-20 16:04:07 -070093// HardwareComposer static data;
94constexpr size_t HardwareComposer::kMaxHardwareLayers;
95
96HardwareComposer::HardwareComposer()
97 : HardwareComposer(nullptr, RequestDisplayCallback()) {}
98
99HardwareComposer::HardwareComposer(
100 Hwc2::Composer* hwc2_hidl, RequestDisplayCallback request_display_callback)
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800101 : initialized_(false),
102 hwc2_hidl_(hwc2_hidl),
Corey Tabaka2251d822017-04-20 16:04:07 -0700103 request_display_callback_(request_display_callback),
104 callbacks_(new ComposerCallback) {}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800105
106HardwareComposer::~HardwareComposer(void) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700107 UpdatePostThreadState(PostThreadState::Quit, true);
108 if (post_thread_.joinable())
Steven Thomas050b2c82017-03-06 11:45:16 -0800109 post_thread_.join();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800110}
111
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800112bool HardwareComposer::Initialize() {
113 if (initialized_) {
114 ALOGE("HardwareComposer::Initialize: already initialized.");
115 return false;
116 }
117
Corey Tabaka2251d822017-04-20 16:04:07 -0700118 HWC::Error error = HWC::Error::None;
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800119
120 Hwc2::Config config;
Corey Tabaka2251d822017-04-20 16:04:07 -0700121 error = hwc2_hidl_->getActiveConfig(HWC_DISPLAY_PRIMARY, &config);
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800122
Corey Tabaka2251d822017-04-20 16:04:07 -0700123 if (error != HWC::Error::None) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800124 ALOGE("HardwareComposer: Failed to get current display config : %d",
125 config);
126 return false;
127 }
128
Corey Tabaka2251d822017-04-20 16:04:07 -0700129 error =
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800130 GetDisplayMetrics(HWC_DISPLAY_PRIMARY, config, &native_display_metrics_);
131
Corey Tabaka2251d822017-04-20 16:04:07 -0700132 if (error != HWC::Error::None) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800133 ALOGE(
134 "HardwareComposer: Failed to get display attributes for current "
135 "configuration : %d",
Corey Tabaka2251d822017-04-20 16:04:07 -0700136 error.value);
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800137 return false;
138 }
139
140 ALOGI(
141 "HardwareComposer: primary display attributes: width=%d height=%d "
142 "vsync_period_ns=%d DPI=%dx%d",
143 native_display_metrics_.width, native_display_metrics_.height,
144 native_display_metrics_.vsync_period_ns, native_display_metrics_.dpi.x,
145 native_display_metrics_.dpi.y);
146
147 // Set the display metrics but never use rotation to avoid the long latency of
148 // rotation processing in hwc.
149 display_transform_ = HWC_TRANSFORM_NONE;
150 display_metrics_ = native_display_metrics_;
151
Corey Tabaka2251d822017-04-20 16:04:07 -0700152 // Pass hwc instance and metrics to setup globals for Layer.
153 Layer::InitializeGlobals(hwc2_hidl_, &native_display_metrics_);
154
155 post_thread_event_fd_.Reset(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
Steven Thomas050b2c82017-03-06 11:45:16 -0800156 LOG_ALWAYS_FATAL_IF(
Corey Tabaka2251d822017-04-20 16:04:07 -0700157 !post_thread_event_fd_,
Steven Thomas050b2c82017-03-06 11:45:16 -0800158 "HardwareComposer: Failed to create interrupt event fd : %s",
159 strerror(errno));
160
161 post_thread_ = std::thread(&HardwareComposer::PostThread, this);
162
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800163 initialized_ = true;
164
165 return initialized_;
166}
167
Steven Thomas050b2c82017-03-06 11:45:16 -0800168void HardwareComposer::Enable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700169 UpdatePostThreadState(PostThreadState::Suspended, false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800170}
171
172void HardwareComposer::Disable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700173 UpdatePostThreadState(PostThreadState::Suspended, true);
Steven Thomas050b2c82017-03-06 11:45:16 -0800174}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800175
Corey Tabaka2251d822017-04-20 16:04:07 -0700176// Update the post thread quiescent state based on idle and suspended inputs.
177void HardwareComposer::UpdatePostThreadState(PostThreadStateType state,
178 bool suspend) {
179 std::unique_lock<std::mutex> lock(post_thread_mutex_);
180
181 // Update the votes in the state variable before evaluating the effective
182 // quiescent state. Any bits set in post_thread_state_ indicate that the post
183 // thread should be suspended.
184 if (suspend) {
185 post_thread_state_ |= state;
186 } else {
187 post_thread_state_ &= ~state;
188 }
189
190 const bool quit = post_thread_state_ & PostThreadState::Quit;
191 const bool effective_suspend = post_thread_state_ != PostThreadState::Active;
192 if (quit) {
193 post_thread_quiescent_ = true;
194 eventfd_write(post_thread_event_fd_.Get(), 1);
195 post_thread_wait_.notify_one();
196 } else if (effective_suspend && !post_thread_quiescent_) {
197 post_thread_quiescent_ = true;
198 eventfd_write(post_thread_event_fd_.Get(), 1);
199 } else if (!effective_suspend && post_thread_quiescent_) {
200 post_thread_quiescent_ = false;
201 eventfd_t value;
202 eventfd_read(post_thread_event_fd_.Get(), &value);
203 post_thread_wait_.notify_one();
204 }
205
206 // Wait until the post thread is in the requested state.
207 post_thread_ready_.wait(lock, [this, effective_suspend] {
208 return effective_suspend != post_thread_resumed_;
209 });
Steven Thomas050b2c82017-03-06 11:45:16 -0800210}
Steven Thomas282a5ed2017-02-07 18:07:01 -0800211
Steven Thomas050b2c82017-03-06 11:45:16 -0800212void HardwareComposer::OnPostThreadResumed() {
Corey Tabaka69a59732017-06-06 16:33:31 -0700213 if (request_display_callback_)
214 request_display_callback_(true);
215
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700216 hwc2_hidl_->resetCommands();
217
Corey Tabaka2251d822017-04-20 16:04:07 -0700218 // HIDL HWC seems to have an internal race condition. If we submit a frame too
219 // soon after turning on VSync we don't get any VSync signals. Give poor HWC
220 // implementations a chance to enable VSync before we continue.
221 EnableVsync(false);
222 std::this_thread::sleep_for(100ms);
Steven Thomas050b2c82017-03-06 11:45:16 -0800223 EnableVsync(true);
Corey Tabaka2251d822017-04-20 16:04:07 -0700224 std::this_thread::sleep_for(100ms);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800225
Steven Thomas050b2c82017-03-06 11:45:16 -0800226 // TODO(skiazyk): We need to do something about accessing this directly,
227 // supposedly there is a backlight service on the way.
228 // TODO(steventhomas): When we change the backlight setting, will surface
229 // flinger (or something else) set it back to its original value once we give
230 // control of the display back to surface flinger?
231 SetBacklightBrightness(255);
Steven Thomas282a5ed2017-02-07 18:07:01 -0800232
Steven Thomas050b2c82017-03-06 11:45:16 -0800233 // Trigger target-specific performance mode change.
234 property_set(kDvrPerformanceProperty, "performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800235}
236
Steven Thomas050b2c82017-03-06 11:45:16 -0800237void HardwareComposer::OnPostThreadPaused() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700238 retire_fence_fds_.clear();
Steven Thomas050b2c82017-03-06 11:45:16 -0800239 display_surfaces_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800240
Corey Tabaka2251d822017-04-20 16:04:07 -0700241 for (size_t i = 0; i < kMaxHardwareLayers; ++i) {
242 layers_[i].Reset();
243 }
244 active_layer_count_ = 0;
Steven Thomas050b2c82017-03-06 11:45:16 -0800245
Steven Thomas050b2c82017-03-06 11:45:16 -0800246 EnableVsync(false);
247
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700248 hwc2_hidl_->resetCommands();
249
Steven Thomas050b2c82017-03-06 11:45:16 -0800250 // Trigger target-specific performance mode change.
251 property_set(kDvrPerformanceProperty, "idle");
Corey Tabaka69a59732017-06-06 16:33:31 -0700252
253 if (request_display_callback_)
254 request_display_callback_(false);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800255}
256
Corey Tabaka2251d822017-04-20 16:04:07 -0700257HWC::Error HardwareComposer::Validate(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800258 uint32_t num_types;
259 uint32_t num_requests;
Corey Tabaka2251d822017-04-20 16:04:07 -0700260 HWC::Error error =
261 hwc2_hidl_->validateDisplay(display, &num_types, &num_requests);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800262
263 if (error == HWC2_ERROR_HAS_CHANGES) {
264 // TODO(skiazyk): We might need to inspect the requested changes first, but
265 // so far it seems like we shouldn't ever hit a bad state.
266 // error = hwc2_funcs_.accept_display_changes_fn_(hardware_composer_device_,
267 // display);
Corey Tabaka2251d822017-04-20 16:04:07 -0700268 error = hwc2_hidl_->acceptDisplayChanges(display);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800269 }
270
271 return error;
272}
273
274int32_t HardwareComposer::EnableVsync(bool enabled) {
275 return (int32_t)hwc2_hidl_->setVsyncEnabled(
276 HWC_DISPLAY_PRIMARY,
277 (Hwc2::IComposerClient::Vsync)(enabled ? HWC2_VSYNC_ENABLE
278 : HWC2_VSYNC_DISABLE));
279}
280
Corey Tabaka2251d822017-04-20 16:04:07 -0700281HWC::Error HardwareComposer::Present(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800282 int32_t present_fence;
Corey Tabaka2251d822017-04-20 16:04:07 -0700283 HWC::Error error = hwc2_hidl_->presentDisplay(display, &present_fence);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800284
285 // According to the documentation, this fence is signaled at the time of
286 // vsync/DMA for physical displays.
Corey Tabaka2251d822017-04-20 16:04:07 -0700287 if (error == HWC::Error::None) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800288 ATRACE_INT("HardwareComposer: VsyncFence", present_fence);
289 retire_fence_fds_.emplace_back(present_fence);
290 } else {
291 ATRACE_INT("HardwareComposer: PresentResult", error);
292 }
293
294 return error;
295}
296
Corey Tabaka2251d822017-04-20 16:04:07 -0700297HWC::Error HardwareComposer::GetDisplayAttribute(hwc2_display_t display,
298 hwc2_config_t config,
299 hwc2_attribute_t attribute,
300 int32_t* out_value) const {
301 return hwc2_hidl_->getDisplayAttribute(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800302 display, config, (Hwc2::IComposerClient::Attribute)attribute, out_value);
303}
304
Corey Tabaka2251d822017-04-20 16:04:07 -0700305HWC::Error HardwareComposer::GetDisplayMetrics(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800306 hwc2_display_t display, hwc2_config_t config,
307 HWCDisplayMetrics* out_metrics) const {
Corey Tabaka2251d822017-04-20 16:04:07 -0700308 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800309
Corey Tabaka2251d822017-04-20 16:04:07 -0700310 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_WIDTH,
311 &out_metrics->width);
312 if (error != HWC::Error::None) {
313 ALOGE(
314 "HardwareComposer::GetDisplayMetrics: Failed to get display width: %s",
315 error.to_string().c_str());
316 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800317 }
318
Corey Tabaka2251d822017-04-20 16:04:07 -0700319 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_HEIGHT,
320 &out_metrics->height);
321 if (error != HWC::Error::None) {
322 ALOGE(
323 "HardwareComposer::GetDisplayMetrics: Failed to get display height: %s",
324 error.to_string().c_str());
325 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800326 }
327
Corey Tabaka2251d822017-04-20 16:04:07 -0700328 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_VSYNC_PERIOD,
329 &out_metrics->vsync_period_ns);
330 if (error != HWC::Error::None) {
331 ALOGE(
332 "HardwareComposer::GetDisplayMetrics: Failed to get display height: %s",
333 error.to_string().c_str());
334 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800335 }
336
Corey Tabaka2251d822017-04-20 16:04:07 -0700337 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_DPI_X,
338 &out_metrics->dpi.x);
339 if (error != HWC::Error::None) {
340 ALOGE(
341 "HardwareComposer::GetDisplayMetrics: Failed to get display DPI X: %s",
342 error.to_string().c_str());
343 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800344 }
345
Corey Tabaka2251d822017-04-20 16:04:07 -0700346 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_DPI_Y,
347 &out_metrics->dpi.y);
348 if (error != HWC::Error::None) {
349 ALOGE(
350 "HardwareComposer::GetDisplayMetrics: Failed to get display DPI Y: %s",
351 error.to_string().c_str());
352 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800353 }
354
Corey Tabaka2251d822017-04-20 16:04:07 -0700355 return HWC::Error::None;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800356}
357
Corey Tabaka0b485c92017-05-19 12:02:58 -0700358std::string HardwareComposer::Dump() {
359 std::unique_lock<std::mutex> lock(post_thread_mutex_);
360 std::ostringstream stream;
361
362 stream << "Display metrics: " << display_metrics_.width << "x"
363 << display_metrics_.height << " " << (display_metrics_.dpi.x / 1000.0)
364 << "x" << (display_metrics_.dpi.y / 1000.0) << " dpi @ "
365 << (1000000000.0 / display_metrics_.vsync_period_ns) << " Hz"
366 << std::endl;
367
368 stream << "Post thread resumed: " << post_thread_resumed_ << std::endl;
369 stream << "Active layers: " << active_layer_count_ << std::endl;
370 stream << std::endl;
371
372 for (size_t i = 0; i < active_layer_count_; i++) {
373 stream << "Layer " << i << ":";
374 stream << " type=" << layers_[i].GetCompositionType().to_string();
375 stream << " surface_id=" << layers_[i].GetSurfaceId();
376 stream << " buffer_id=" << layers_[i].GetBufferId();
377 stream << std::endl;
378 }
379 stream << std::endl;
380
381 if (post_thread_resumed_) {
382 stream << "Hardware Composer Debug Info:" << std::endl;
383 stream << hwc2_hidl_->dumpDebugInfo();
384 }
385
386 return stream.str();
387}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800388
Corey Tabaka2251d822017-04-20 16:04:07 -0700389void HardwareComposer::PostLayers() {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800390 ATRACE_NAME("HardwareComposer::PostLayers");
391
392 // Setup the hardware composer layers with current buffers.
393 for (size_t i = 0; i < active_layer_count_; i++) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700394 layers_[i].Prepare();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800395 }
396
Corey Tabaka2251d822017-04-20 16:04:07 -0700397 HWC::Error error = Validate(HWC_DISPLAY_PRIMARY);
398 if (error != HWC::Error::None) {
399 ALOGE("HardwareComposer::PostLayers: Validate failed: %s",
400 error.to_string().c_str());
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700401 return;
402 }
403
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800404 // Now that we have taken in a frame from the application, we have a chance
405 // to drop the frame before passing the frame along to HWC.
406 // If the display driver has become backed up, we detect it here and then
407 // react by skipping this frame to catch up latency.
408 while (!retire_fence_fds_.empty() &&
409 (!retire_fence_fds_.front() ||
410 sync_wait(retire_fence_fds_.front().Get(), 0) == 0)) {
411 // There are only 2 fences in here, no performance problem to shift the
412 // array of ints.
413 retire_fence_fds_.erase(retire_fence_fds_.begin());
414 }
415
416 const bool is_frame_pending = IsFramePendingInDriver();
John Bates954796e2017-05-11 11:00:31 -0700417 const bool is_fence_pending = retire_fence_fds_.size() >
418 post_thread_config_.allowed_pending_fence_count;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800419
420 if (is_fence_pending || is_frame_pending) {
421 ATRACE_INT("frame_skip_count", ++frame_skip_count_);
422
423 ALOGW_IF(is_frame_pending, "Warning: frame already queued, dropping frame");
424 ALOGW_IF(is_fence_pending,
425 "Warning: dropping a frame to catch up with HWC (pending = %zd)",
426 retire_fence_fds_.size());
427
428 for (size_t i = 0; i < active_layer_count_; i++) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700429 layers_[i].Drop();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800430 }
431 return;
432 } else {
433 // Make the transition more obvious in systrace when the frame skip happens
434 // above.
435 ATRACE_INT("frame_skip_count", 0);
436 }
437
Corey Tabaka89bbefc2017-06-06 16:14:21 -0700438#if TRACE > 1
Corey Tabaka0b485c92017-05-19 12:02:58 -0700439 for (size_t i = 0; i < active_layer_count_; i++) {
440 ALOGI("HardwareComposer::PostLayers: layer=%zu buffer_id=%d composition=%s",
441 i, layers_[i].GetBufferId(),
Corey Tabaka2251d822017-04-20 16:04:07 -0700442 layers_[i].GetCompositionType().to_string().c_str());
Corey Tabaka0b485c92017-05-19 12:02:58 -0700443 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800444#endif
445
Corey Tabaka2251d822017-04-20 16:04:07 -0700446 error = Present(HWC_DISPLAY_PRIMARY);
447 if (error != HWC::Error::None) {
448 ALOGE("HardwareComposer::PostLayers: Present failed: %s",
449 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800450 return;
451 }
452
453 std::vector<Hwc2::Layer> out_layers;
454 std::vector<int> out_fences;
Corey Tabaka2251d822017-04-20 16:04:07 -0700455 error = hwc2_hidl_->getReleaseFences(HWC_DISPLAY_PRIMARY, &out_layers,
456 &out_fences);
457 ALOGE_IF(error != HWC::Error::None,
458 "HardwareComposer::PostLayers: Failed to get release fences: %s",
459 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800460
461 // Perform post-frame bookkeeping. Unused layers are a no-op.
Corey Tabaka2251d822017-04-20 16:04:07 -0700462 uint32_t num_elements = out_layers.size();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800463 for (size_t i = 0; i < num_elements; ++i) {
464 for (size_t j = 0; j < active_layer_count_; ++j) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700465 if (layers_[j].GetLayerHandle() == out_layers[i]) {
466 layers_[j].Finish(out_fences[i]);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800467 }
468 }
469 }
470}
471
Steven Thomas050b2c82017-03-06 11:45:16 -0800472void HardwareComposer::SetDisplaySurfaces(
Corey Tabaka2251d822017-04-20 16:04:07 -0700473 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces) {
Jin Qian7480c062017-03-21 00:04:15 +0000474 ALOGI("HardwareComposer::SetDisplaySurfaces: surface count=%zd",
475 surfaces.size());
Corey Tabaka2251d822017-04-20 16:04:07 -0700476 const bool display_idle = surfaces.size() == 0;
477 {
478 std::unique_lock<std::mutex> lock(post_thread_mutex_);
479 pending_surfaces_ = std::move(surfaces);
480 }
481
482 // Set idle state based on whether there are any surfaces to handle.
483 UpdatePostThreadState(PostThreadState::Idle, display_idle);
Steven Thomas050b2c82017-03-06 11:45:16 -0800484}
Jin Qian7480c062017-03-21 00:04:15 +0000485
John Bates954796e2017-05-11 11:00:31 -0700486int HardwareComposer::OnNewGlobalBuffer(DvrGlobalBufferKey key,
487 IonBuffer& ion_buffer) {
Okan Arikan822b7102017-05-08 13:31:34 -0700488 if (key == DvrGlobalBuffers::kVsyncBuffer) {
489 vsync_ring_ = std::make_unique<CPUMappedBroadcastRing<DvrVsyncRing>>(
490 &ion_buffer, CPUUsageMode::WRITE_OFTEN);
491
492 if (vsync_ring_->IsMapped() == false) {
493 return -EPERM;
494 }
495 }
496
497 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700498 return MapConfigBuffer(ion_buffer);
499 }
500
501 return 0;
502}
503
504void HardwareComposer::OnDeletedGlobalBuffer(DvrGlobalBufferKey key) {
Okan Arikan822b7102017-05-08 13:31:34 -0700505 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700506 ConfigBufferDeleted();
507 }
508}
509
510int HardwareComposer::MapConfigBuffer(IonBuffer& ion_buffer) {
511 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700512 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700513
Okan Arikan6f468c62017-05-31 14:48:30 -0700514 if (ion_buffer.width() < DvrConfigRing::MemorySize()) {
John Bates954796e2017-05-11 11:00:31 -0700515 ALOGE("HardwareComposer::MapConfigBuffer: invalid buffer size.");
516 return -EINVAL;
517 }
518
519 void* buffer_base = 0;
520 int result = ion_buffer.Lock(ion_buffer.usage(), 0, 0, ion_buffer.width(),
521 ion_buffer.height(), &buffer_base);
522 if (result != 0) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700523 ALOGE(
524 "HardwareComposer::MapConfigBuffer: Failed to map vrflinger config "
525 "buffer.");
John Bates954796e2017-05-11 11:00:31 -0700526 return -EPERM;
527 }
528
Okan Arikan6f468c62017-05-31 14:48:30 -0700529 shared_config_ring_ = DvrConfigRing::Create(buffer_base, ion_buffer.width());
John Bates954796e2017-05-11 11:00:31 -0700530 ion_buffer.Unlock();
531
532 return 0;
533}
534
535void HardwareComposer::ConfigBufferDeleted() {
536 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700537 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700538}
539
540void HardwareComposer::UpdateConfigBuffer() {
541 std::lock_guard<std::mutex> lock(shared_config_mutex_);
542 if (!shared_config_ring_.is_valid())
543 return;
544 // Copy from latest record in shared_config_ring_ to local copy.
Okan Arikan6f468c62017-05-31 14:48:30 -0700545 DvrConfig record;
John Bates954796e2017-05-11 11:00:31 -0700546 if (shared_config_ring_.GetNewest(&shared_config_ring_sequence_, &record)) {
547 post_thread_config_ = record;
548 }
549}
550
Corey Tabaka2251d822017-04-20 16:04:07 -0700551int HardwareComposer::PostThreadPollInterruptible(
552 const pdx::LocalHandle& event_fd, int requested_events) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800553 pollfd pfd[2] = {
554 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700555 .fd = event_fd.Get(),
Steven Thomas66747c12017-03-22 18:45:31 -0700556 .events = static_cast<short>(requested_events),
557 .revents = 0,
Steven Thomas050b2c82017-03-06 11:45:16 -0800558 },
559 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700560 .fd = post_thread_event_fd_.Get(),
Steven Thomas050b2c82017-03-06 11:45:16 -0800561 .events = POLLPRI | POLLIN,
562 .revents = 0,
563 },
564 };
565 int ret, error;
566 do {
567 ret = poll(pfd, 2, -1);
568 error = errno;
569 ALOGW_IF(ret < 0,
570 "HardwareComposer::PostThreadPollInterruptible: Error during "
571 "poll(): %s (%d)",
572 strerror(error), error);
573 } while (ret < 0 && error == EINTR);
574
575 if (ret < 0) {
576 return -error;
577 } else if (pfd[0].revents != 0) {
578 return 0;
579 } else if (pfd[1].revents != 0) {
580 ALOGI("VrHwcPost thread interrupted");
581 return kPostThreadInterrupted;
582 } else {
583 return 0;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800584 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800585}
586
587// Reads the value of the display driver wait_pingpong state. Returns 0 or 1
588// (the value of the state) on success or a negative error otherwise.
589// TODO(eieio): This is pretty driver specific, this should be moved to a
590// separate class eventually.
591int HardwareComposer::ReadWaitPPState() {
592 // Gracefully handle when the kernel does not support this feature.
593 if (!primary_display_wait_pp_fd_)
594 return 0;
595
596 const int wait_pp_fd = primary_display_wait_pp_fd_.Get();
597 int ret, error;
598
599 ret = lseek(wait_pp_fd, 0, SEEK_SET);
600 if (ret < 0) {
601 error = errno;
602 ALOGE("HardwareComposer::ReadWaitPPState: Failed to seek wait_pp fd: %s",
603 strerror(error));
604 return -error;
605 }
606
607 char data = -1;
608 ret = read(wait_pp_fd, &data, sizeof(data));
609 if (ret < 0) {
610 error = errno;
611 ALOGE("HardwareComposer::ReadWaitPPState: Failed to read wait_pp state: %s",
612 strerror(error));
613 return -error;
614 }
615
616 switch (data) {
617 case '0':
618 return 0;
619 case '1':
620 return 1;
621 default:
622 ALOGE(
623 "HardwareComposer::ReadWaitPPState: Unexpected value for wait_pp: %d",
624 data);
625 return -EINVAL;
626 }
627}
628
629// Reads the timestamp of the last vsync from the display driver.
630// TODO(eieio): This is pretty driver specific, this should be moved to a
631// separate class eventually.
632int HardwareComposer::ReadVSyncTimestamp(int64_t* timestamp) {
633 const int event_fd = primary_display_vsync_event_fd_.Get();
634 int ret, error;
635
636 // The driver returns data in the form "VSYNC=<timestamp ns>".
637 std::array<char, 32> data;
638 data.fill('\0');
639
640 // Seek back to the beginning of the event file.
641 ret = lseek(event_fd, 0, SEEK_SET);
642 if (ret < 0) {
643 error = errno;
644 ALOGE(
645 "HardwareComposer::ReadVSyncTimestamp: Failed to seek vsync event fd: "
646 "%s",
647 strerror(error));
648 return -error;
649 }
650
651 // Read the vsync event timestamp.
652 ret = read(event_fd, data.data(), data.size());
653 if (ret < 0) {
654 error = errno;
655 ALOGE_IF(
656 error != EAGAIN,
657 "HardwareComposer::ReadVSyncTimestamp: Error while reading timestamp: "
658 "%s",
659 strerror(error));
660 return -error;
661 }
662
663 ret = sscanf(data.data(), "VSYNC=%" PRIu64,
664 reinterpret_cast<uint64_t*>(timestamp));
665 if (ret < 0) {
666 error = errno;
667 ALOGE(
668 "HardwareComposer::ReadVSyncTimestamp: Error while parsing timestamp: "
669 "%s",
670 strerror(error));
671 return -error;
672 }
673
674 return 0;
675}
676
677// Blocks until the next vsync event is signaled by the display driver.
678// TODO(eieio): This is pretty driver specific, this should be moved to a
679// separate class eventually.
Steven Thomas050b2c82017-03-06 11:45:16 -0800680int HardwareComposer::BlockUntilVSync() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700681 // Vsync is signaled by POLLPRI on the fb vsync node.
682 return PostThreadPollInterruptible(primary_display_vsync_event_fd_, POLLPRI);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800683}
684
685// Waits for the next vsync and returns the timestamp of the vsync event. If
686// vsync already passed since the last call, returns the latest vsync timestamp
687// instead of blocking. This method updates the last_vsync_timeout_ in the
688// process.
689//
690// TODO(eieio): This is pretty driver specific, this should be moved to a
691// separate class eventually.
692int HardwareComposer::WaitForVSync(int64_t* timestamp) {
693 int error;
694
695 // Get the current timestamp and decide what to do.
696 while (true) {
697 int64_t current_vsync_timestamp;
698 error = ReadVSyncTimestamp(&current_vsync_timestamp);
699 if (error < 0 && error != -EAGAIN)
700 return error;
701
702 if (error == -EAGAIN) {
703 // Vsync was turned off, wait for the next vsync event.
Steven Thomas050b2c82017-03-06 11:45:16 -0800704 error = BlockUntilVSync();
705 if (error < 0 || error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800706 return error;
707
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800708 // Try again to get the timestamp for this new vsync interval.
709 continue;
710 }
711
712 // Check that we advanced to a later vsync interval.
713 if (TimestampGT(current_vsync_timestamp, last_vsync_timestamp_)) {
714 *timestamp = last_vsync_timestamp_ = current_vsync_timestamp;
715 return 0;
716 }
717
718 // See how close we are to the next expected vsync. If we're within 1ms,
719 // sleep for 1ms and try again.
720 const int64_t ns_per_frame = display_metrics_.vsync_period_ns;
Corey Tabaka2251d822017-04-20 16:04:07 -0700721 const int64_t threshold_ns = 1000000; // 1ms
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800722
723 const int64_t next_vsync_est = last_vsync_timestamp_ + ns_per_frame;
724 const int64_t distance_to_vsync_est = next_vsync_est - GetSystemClockNs();
725
726 if (distance_to_vsync_est > threshold_ns) {
727 // Wait for vsync event notification.
Steven Thomas050b2c82017-03-06 11:45:16 -0800728 error = BlockUntilVSync();
729 if (error < 0 || error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800730 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800731 } else {
Steven Thomas050b2c82017-03-06 11:45:16 -0800732 // Sleep for a short time (1 millisecond) before retrying.
Corey Tabaka2251d822017-04-20 16:04:07 -0700733 error = SleepUntil(GetSystemClockNs() + threshold_ns);
Steven Thomas050b2c82017-03-06 11:45:16 -0800734 if (error < 0 || error == kPostThreadInterrupted)
735 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800736 }
737 }
738}
739
740int HardwareComposer::SleepUntil(int64_t wakeup_timestamp) {
741 const int timer_fd = vsync_sleep_timer_fd_.Get();
742 const itimerspec wakeup_itimerspec = {
743 .it_interval = {.tv_sec = 0, .tv_nsec = 0},
744 .it_value = NsToTimespec(wakeup_timestamp),
745 };
746 int ret =
747 timerfd_settime(timer_fd, TFD_TIMER_ABSTIME, &wakeup_itimerspec, nullptr);
748 int error = errno;
749 if (ret < 0) {
750 ALOGE("HardwareComposer::SleepUntil: Failed to set timerfd: %s",
751 strerror(error));
752 return -error;
753 }
754
Corey Tabaka2251d822017-04-20 16:04:07 -0700755 return PostThreadPollInterruptible(vsync_sleep_timer_fd_, POLLIN);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800756}
757
758void HardwareComposer::PostThread() {
759 // NOLINTNEXTLINE(runtime/int)
Steven Thomas050b2c82017-03-06 11:45:16 -0800760 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>("VrHwcPost"), 0, 0, 0);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800761
Corey Tabaka2251d822017-04-20 16:04:07 -0700762 // Set the scheduler to SCHED_FIFO with high priority. If this fails here
763 // there may have been a startup timing issue between this thread and
764 // performanced. Try again later when this thread becomes active.
765 bool thread_policy_setup =
766 SetThreadPolicy("graphics:high", "/system/performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800767
Steven Thomas050b2c82017-03-06 11:45:16 -0800768#if ENABLE_BACKLIGHT_BRIGHTNESS
769 // TODO(hendrikw): This isn't required at the moment. It's possible that there
770 // is another method to access this when needed.
771 // Open the backlight brightness control sysfs node.
772 backlight_brightness_fd_ = LocalHandle(kBacklightBrightnessSysFile, O_RDWR);
773 ALOGW_IF(!backlight_brightness_fd_,
774 "HardwareComposer: Failed to open backlight brightness control: %s",
775 strerror(errno));
Corey Tabaka2251d822017-04-20 16:04:07 -0700776#endif // ENABLE_BACKLIGHT_BRIGHTNESS
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800777
Steven Thomas050b2c82017-03-06 11:45:16 -0800778 // Open the vsync event node for the primary display.
779 // TODO(eieio): Move this into a platform-specific class.
780 primary_display_vsync_event_fd_ =
781 LocalHandle(kPrimaryDisplayVSyncEventFile, O_RDONLY);
782 ALOGE_IF(!primary_display_vsync_event_fd_,
783 "HardwareComposer: Failed to open vsync event node for primary "
784 "display: %s",
785 strerror(errno));
786
787 // Open the wait pingpong status node for the primary display.
788 // TODO(eieio): Move this into a platform-specific class.
789 primary_display_wait_pp_fd_ =
790 LocalHandle(kPrimaryDisplayWaitPPEventFile, O_RDONLY);
791 ALOGW_IF(
792 !primary_display_wait_pp_fd_,
793 "HardwareComposer: Failed to open wait_pp node for primary display: %s",
794 strerror(errno));
795
796 // Create a timerfd based on CLOCK_MONOTINIC.
797 vsync_sleep_timer_fd_.Reset(timerfd_create(CLOCK_MONOTONIC, 0));
798 LOG_ALWAYS_FATAL_IF(
799 !vsync_sleep_timer_fd_,
800 "HardwareComposer: Failed to create vsync sleep timerfd: %s",
801 strerror(errno));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800802
803 const int64_t ns_per_frame = display_metrics_.vsync_period_ns;
804 const int64_t photon_offset_ns = GetPosePredictionTimeOffset(ns_per_frame);
805
806 // TODO(jbates) Query vblank time from device, when such an API is available.
807 // This value (6.3%) was measured on A00 in low persistence mode.
808 int64_t vblank_ns = ns_per_frame * 63 / 1000;
809 int64_t right_eye_photon_offset_ns = (ns_per_frame - vblank_ns) / 2;
810
811 // Check property for overriding right eye offset value.
812 right_eye_photon_offset_ns =
813 property_get_int64(kRightEyeOffsetProperty, right_eye_photon_offset_ns);
814
Steven Thomas050b2c82017-03-06 11:45:16 -0800815 bool was_running = false;
816
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800817 while (1) {
818 ATRACE_NAME("HardwareComposer::PostThread");
819
John Bates954796e2017-05-11 11:00:31 -0700820 // Check for updated config once per vsync.
821 UpdateConfigBuffer();
822
Corey Tabaka2251d822017-04-20 16:04:07 -0700823 while (post_thread_quiescent_) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800824 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Corey Tabaka2251d822017-04-20 16:04:07 -0700825 ALOGI("HardwareComposer::PostThread: Entering quiescent state.");
826
827 // Tear down resources.
828 OnPostThreadPaused();
829
830 was_running = false;
831 post_thread_resumed_ = false;
832 post_thread_ready_.notify_all();
833
834 if (post_thread_state_ & PostThreadState::Quit) {
835 ALOGI("HardwareComposer::PostThread: Quitting.");
836 return;
Steven Thomas282a5ed2017-02-07 18:07:01 -0800837 }
Corey Tabaka2251d822017-04-20 16:04:07 -0700838
839 post_thread_wait_.wait(lock, [this] { return !post_thread_quiescent_; });
840
841 post_thread_resumed_ = true;
842 post_thread_ready_.notify_all();
843
844 ALOGI("HardwareComposer::PostThread: Exiting quiescent state.");
Steven Thomas050b2c82017-03-06 11:45:16 -0800845 }
846
847 if (!was_running) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700848 // Setup resources.
Steven Thomas050b2c82017-03-06 11:45:16 -0800849 OnPostThreadResumed();
850 was_running = true;
Corey Tabaka2251d822017-04-20 16:04:07 -0700851
852 // Try to setup the scheduler policy if it failed during startup. Only
853 // attempt to do this on transitions from inactive to active to avoid
854 // spamming the system with RPCs and log messages.
855 if (!thread_policy_setup) {
856 thread_policy_setup =
857 SetThreadPolicy("graphics:high", "/system/performance");
858 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800859 }
860
861 int64_t vsync_timestamp = 0;
862 {
863 std::array<char, 128> buf;
864 snprintf(buf.data(), buf.size(), "wait_vsync|vsync=%d|",
865 vsync_count_ + 1);
866 ATRACE_NAME(buf.data());
867
Corey Tabaka2251d822017-04-20 16:04:07 -0700868 const int error = WaitForVSync(&vsync_timestamp);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800869 ALOGE_IF(
870 error < 0,
871 "HardwareComposer::PostThread: Failed to wait for vsync event: %s",
872 strerror(-error));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800873 // Don't bother processing this frame if a pause was requested
Steven Thomas050b2c82017-03-06 11:45:16 -0800874 if (error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800875 continue;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800876 }
877
878 ++vsync_count_;
879
Corey Tabaka2251d822017-04-20 16:04:07 -0700880 const bool layer_config_changed = UpdateLayerConfig();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800881
Okan Arikan822b7102017-05-08 13:31:34 -0700882 // Publish the vsync event.
883 if (vsync_ring_) {
884 DvrVsync vsync;
885 vsync.vsync_count = vsync_count_;
886 vsync.vsync_timestamp_ns = vsync_timestamp;
887 vsync.vsync_left_eye_offset_ns = photon_offset_ns;
888 vsync.vsync_right_eye_offset_ns = right_eye_photon_offset_ns;
889 vsync.vsync_period_ns = ns_per_frame;
890
891 vsync_ring_->Publish(vsync);
892 }
893
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800894 // Signal all of the vsync clients. Because absolute time is used for the
895 // wakeup time below, this can take a little time if necessary.
896 if (vsync_callback_)
Corey Tabaka2251d822017-04-20 16:04:07 -0700897 vsync_callback_(HWC_DISPLAY_PRIMARY, vsync_timestamp,
898 /*frame_time_estimate*/ 0, vsync_count_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800899
900 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700901 // Sleep until shortly before vsync.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800902 ATRACE_NAME("sleep");
903
Corey Tabaka2251d822017-04-20 16:04:07 -0700904 const int64_t display_time_est_ns = vsync_timestamp + ns_per_frame;
905 const int64_t now_ns = GetSystemClockNs();
John Bates954796e2017-05-11 11:00:31 -0700906 const int64_t sleep_time_ns = display_time_est_ns - now_ns -
907 post_thread_config_.frame_post_offset_ns;
908 const int64_t wakeup_time_ns =
909 display_time_est_ns - post_thread_config_.frame_post_offset_ns;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800910
911 ATRACE_INT64("sleep_time_ns", sleep_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800912 if (sleep_time_ns > 0) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700913 int error = SleepUntil(wakeup_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800914 ALOGE_IF(error < 0, "HardwareComposer::PostThread: Failed to sleep: %s",
915 strerror(-error));
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700916 if (error == kPostThreadInterrupted) {
917 if (layer_config_changed) {
918 // If the layer config changed we need to validateDisplay() even if
919 // we're going to drop the frame, to flush the Composer object's
920 // internal command buffer and apply our layer changes.
921 Validate(HWC_DISPLAY_PRIMARY);
922 }
Steven Thomas050b2c82017-03-06 11:45:16 -0800923 continue;
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700924 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800925 }
926 }
927
Corey Tabaka2251d822017-04-20 16:04:07 -0700928 PostLayers();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800929 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800930}
931
Corey Tabaka2251d822017-04-20 16:04:07 -0700932// Checks for changes in the surface stack and updates the layer config to
933// accomodate the new stack.
Steven Thomas050b2c82017-03-06 11:45:16 -0800934bool HardwareComposer::UpdateLayerConfig() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700935 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces;
Steven Thomas050b2c82017-03-06 11:45:16 -0800936 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700937 std::unique_lock<std::mutex> lock(post_thread_mutex_);
938 if (pending_surfaces_.empty())
Steven Thomas050b2c82017-03-06 11:45:16 -0800939 return false;
Corey Tabaka2251d822017-04-20 16:04:07 -0700940
941 surfaces = std::move(pending_surfaces_);
Steven Thomas050b2c82017-03-06 11:45:16 -0800942 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800943
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800944 ATRACE_NAME("UpdateLayerConfig_HwLayers");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800945
Corey Tabaka2251d822017-04-20 16:04:07 -0700946 display_surfaces_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800947
Corey Tabaka2251d822017-04-20 16:04:07 -0700948 Layer* target_layer;
949 size_t layer_index;
950 for (layer_index = 0;
951 layer_index < std::min(surfaces.size(), kMaxHardwareLayers);
952 layer_index++) {
953 // The bottom layer is opaque, other layers blend.
954 HWC::BlendMode blending =
955 layer_index == 0 ? HWC::BlendMode::None : HWC::BlendMode::Coverage;
956 layers_[layer_index].Setup(surfaces[layer_index], blending,
957 display_transform_, HWC::Composition::Device,
958 layer_index);
959 display_surfaces_.push_back(surfaces[layer_index]);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800960 }
961
Corey Tabaka2251d822017-04-20 16:04:07 -0700962 // Clear unused layers.
963 for (size_t i = layer_index; i < kMaxHardwareLayers; i++)
964 layers_[i].Reset();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800965
Corey Tabaka2251d822017-04-20 16:04:07 -0700966 active_layer_count_ = layer_index;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800967 ALOGD_IF(TRACE, "HardwareComposer::UpdateLayerConfig: %zd active layers",
968 active_layer_count_);
969
Corey Tabaka2251d822017-04-20 16:04:07 -0700970 // Any surfaces left over could not be assigned a hardware layer and will
971 // not be displayed.
972 ALOGW_IF(surfaces.size() != display_surfaces_.size(),
973 "HardwareComposer::UpdateLayerConfig: More surfaces than layers: "
974 "pending_surfaces=%zu display_surfaces=%zu",
975 surfaces.size(), display_surfaces_.size());
976
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800977 return true;
978}
979
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800980void HardwareComposer::SetVSyncCallback(VSyncCallback callback) {
981 vsync_callback_ = callback;
982}
983
984void HardwareComposer::HwcRefresh(hwc2_callback_data_t /*data*/,
985 hwc2_display_t /*display*/) {
986 // TODO(eieio): implement invalidate callbacks.
987}
988
989void HardwareComposer::HwcVSync(hwc2_callback_data_t /*data*/,
990 hwc2_display_t /*display*/,
991 int64_t /*timestamp*/) {
992 ATRACE_NAME(__PRETTY_FUNCTION__);
993 // Intentionally empty. HWC may require a callback to be set to enable vsync
994 // signals. We bypass this callback thread by monitoring the vsync event
995 // directly, but signals still need to be enabled.
996}
997
998void HardwareComposer::HwcHotplug(hwc2_callback_data_t /*callbackData*/,
999 hwc2_display_t /*display*/,
1000 hwc2_connection_t /*connected*/) {
1001 // TODO(eieio): implement display hotplug callbacks.
1002}
1003
Steven Thomas3cfac282017-02-06 12:29:30 -08001004void HardwareComposer::OnHardwareComposerRefresh() {
1005 // TODO(steventhomas): Handle refresh.
1006}
1007
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001008void HardwareComposer::SetBacklightBrightness(int brightness) {
1009 if (backlight_brightness_fd_) {
1010 std::array<char, 32> text;
1011 const int length = snprintf(text.data(), text.size(), "%d", brightness);
1012 write(backlight_brightness_fd_.Get(), text.data(), length);
1013 }
1014}
1015
Corey Tabaka2251d822017-04-20 16:04:07 -07001016void Layer::InitializeGlobals(Hwc2::Composer* hwc2_hidl,
1017 const HWCDisplayMetrics* metrics) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001018 hwc2_hidl_ = hwc2_hidl;
1019 display_metrics_ = metrics;
1020}
1021
1022void Layer::Reset() {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001023 if (hwc2_hidl_ != nullptr && hardware_composer_layer_) {
1024 hwc2_hidl_->destroyLayer(HWC_DISPLAY_PRIMARY, hardware_composer_layer_);
1025 hardware_composer_layer_ = 0;
1026 }
1027
Corey Tabaka2251d822017-04-20 16:04:07 -07001028 z_order_ = 0;
1029 blending_ = HWC::BlendMode::None;
1030 transform_ = HWC::Transform::None;
1031 composition_type_ = HWC::Composition::Invalid;
1032 target_composition_type_ = composition_type_;
1033 source_ = EmptyVariant{};
1034 acquire_fence_.Close();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001035 surface_rect_functions_applied_ = false;
1036}
1037
Corey Tabaka2251d822017-04-20 16:04:07 -07001038void Layer::Setup(const std::shared_ptr<DirectDisplaySurface>& surface,
1039 HWC::BlendMode blending, HWC::Transform transform,
1040 HWC::Composition composition_type, size_t z_order) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001041 Reset();
Corey Tabaka2251d822017-04-20 16:04:07 -07001042 z_order_ = z_order;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001043 blending_ = blending;
1044 transform_ = transform;
Corey Tabaka2251d822017-04-20 16:04:07 -07001045 composition_type_ = HWC::Composition::Invalid;
1046 target_composition_type_ = composition_type;
1047 source_ = SourceSurface{surface};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001048 CommonLayerSetup();
1049}
1050
1051void Layer::Setup(const std::shared_ptr<IonBuffer>& buffer,
Corey Tabaka2251d822017-04-20 16:04:07 -07001052 HWC::BlendMode blending, HWC::Transform transform,
1053 HWC::Composition composition_type, size_t z_order) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001054 Reset();
Corey Tabaka2251d822017-04-20 16:04:07 -07001055 z_order_ = z_order;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001056 blending_ = blending;
1057 transform_ = transform;
Corey Tabaka2251d822017-04-20 16:04:07 -07001058 composition_type_ = HWC::Composition::Invalid;
1059 target_composition_type_ = composition_type;
1060 source_ = SourceBuffer{buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001061 CommonLayerSetup();
1062}
1063
Corey Tabaka2251d822017-04-20 16:04:07 -07001064void Layer::UpdateBuffer(const std::shared_ptr<IonBuffer>& buffer) {
1065 if (source_.is<SourceBuffer>())
1066 std::get<SourceBuffer>(source_) = {buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001067}
1068
Corey Tabaka2251d822017-04-20 16:04:07 -07001069void Layer::SetBlending(HWC::BlendMode blending) { blending_ = blending; }
1070void Layer::SetZOrder(size_t z_order) { z_order_ = z_order; }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001071
1072IonBuffer* Layer::GetBuffer() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001073 struct Visitor {
1074 IonBuffer* operator()(SourceSurface& source) { return source.GetBuffer(); }
1075 IonBuffer* operator()(SourceBuffer& source) { return source.GetBuffer(); }
1076 IonBuffer* operator()(EmptyVariant) { return nullptr; }
1077 };
1078 return source_.Visit(Visitor{});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001079}
1080
1081void Layer::UpdateLayerSettings() {
1082 if (!IsLayerSetup()) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001083 ALOGE(
1084 "HardwareComposer::Layer::UpdateLayerSettings: Attempt to update "
1085 "unused Layer!");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001086 return;
1087 }
1088
Corey Tabaka2251d822017-04-20 16:04:07 -07001089 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001090 hwc2_display_t display = HWC_DISPLAY_PRIMARY;
1091
Corey Tabaka2251d822017-04-20 16:04:07 -07001092 error = hwc2_hidl_->setLayerCompositionType(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001093 display, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001094 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1095 ALOGE_IF(
1096 error != HWC::Error::None,
1097 "Layer::UpdateLayerSettings: Error setting layer composition type: %s",
1098 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001099
Corey Tabaka2251d822017-04-20 16:04:07 -07001100 error = hwc2_hidl_->setLayerBlendMode(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001101 display, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001102 blending_.cast<Hwc2::IComposerClient::BlendMode>());
1103 ALOGE_IF(error != HWC::Error::None,
1104 "Layer::UpdateLayerSettings: Error setting layer blend mode: %s",
1105 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001106
Corey Tabaka2251d822017-04-20 16:04:07 -07001107 // TODO(eieio): Use surface attributes or some other mechanism to control
1108 // the layer display frame.
1109 error = hwc2_hidl_->setLayerDisplayFrame(
1110 display, hardware_composer_layer_,
1111 {0, 0, display_metrics_->width, display_metrics_->height});
1112 ALOGE_IF(error != HWC::Error::None,
1113 "Layer::UpdateLayerSettings: Error setting layer display frame: %s",
1114 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001115
Corey Tabaka2251d822017-04-20 16:04:07 -07001116 error = hwc2_hidl_->setLayerVisibleRegion(
1117 display, hardware_composer_layer_,
1118 {{0, 0, display_metrics_->width, display_metrics_->height}});
1119 ALOGE_IF(error != HWC::Error::None,
1120 "Layer::UpdateLayerSettings: Error setting layer visible region: %s",
1121 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001122
Corey Tabaka2251d822017-04-20 16:04:07 -07001123 error =
1124 hwc2_hidl_->setLayerPlaneAlpha(display, hardware_composer_layer_, 1.0f);
1125 ALOGE_IF(error != HWC::Error::None,
1126 "Layer::UpdateLayerSettings: Error setting layer plane alpha: %s",
1127 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001128
Corey Tabaka2251d822017-04-20 16:04:07 -07001129 error =
1130 hwc2_hidl_->setLayerZOrder(display, hardware_composer_layer_, z_order_);
1131 ALOGE_IF(error != HWC::Error::None,
1132 "Layer::UpdateLayerSettings: Error setting z_ order: %s",
1133 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001134}
1135
1136void Layer::CommonLayerSetup() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001137 HWC::Error error =
1138 hwc2_hidl_->createLayer(HWC_DISPLAY_PRIMARY, &hardware_composer_layer_);
1139 ALOGE_IF(
1140 error != HWC::Error::None,
1141 "Layer::CommonLayerSetup: Failed to create layer on primary display: %s",
1142 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001143 UpdateLayerSettings();
1144}
1145
1146void Layer::Prepare() {
1147 int right, bottom;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -04001148 sp<GraphicBuffer> handle;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001149
Corey Tabaka2251d822017-04-20 16:04:07 -07001150 // Acquire the next buffer according to the type of source.
1151 IfAnyOf<SourceSurface, SourceBuffer>::Call(&source_, [&](auto& source) {
1152 std::tie(right, bottom, handle, acquire_fence_) = source.Acquire();
1153 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001154
Corey Tabaka2251d822017-04-20 16:04:07 -07001155 // When a layer is first setup there may be some time before the first buffer
1156 // arrives. Setup the HWC layer as a solid color to stall for time until the
1157 // first buffer arrives. Once the first buffer arrives there will always be a
1158 // buffer for the frame even if it is old.
1159 if (!handle.get()) {
1160 if (composition_type_ == HWC::Composition::Invalid) {
1161 composition_type_ = HWC::Composition::SolidColor;
1162 hwc2_hidl_->setLayerCompositionType(
1163 HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1164 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1165 Hwc2::IComposerClient::Color layer_color = {0, 0, 0, 0};
1166 hwc2_hidl_->setLayerColor(HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1167 layer_color);
1168 } else {
1169 // The composition type is already set. Nothing else to do until a
1170 // buffer arrives.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001171 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001172 } else {
Corey Tabaka2251d822017-04-20 16:04:07 -07001173 if (composition_type_ != target_composition_type_) {
1174 composition_type_ = target_composition_type_;
1175 hwc2_hidl_->setLayerCompositionType(
1176 HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1177 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1178 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001179
Corey Tabaka2251d822017-04-20 16:04:07 -07001180 HWC::Error error{HWC::Error::None};
1181 error = hwc2_hidl_->setLayerBuffer(HWC_DISPLAY_PRIMARY,
1182 hardware_composer_layer_, 0, handle,
1183 acquire_fence_.Get());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001184
Corey Tabaka2251d822017-04-20 16:04:07 -07001185 ALOGE_IF(error != HWC::Error::None,
1186 "Layer::Prepare: Error setting layer buffer: %s",
1187 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001188
Corey Tabaka2251d822017-04-20 16:04:07 -07001189 if (!surface_rect_functions_applied_) {
1190 const float float_right = right;
1191 const float float_bottom = bottom;
1192 error = hwc2_hidl_->setLayerSourceCrop(HWC_DISPLAY_PRIMARY,
1193 hardware_composer_layer_,
1194 {0, 0, float_right, float_bottom});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001195
Corey Tabaka2251d822017-04-20 16:04:07 -07001196 ALOGE_IF(error != HWC::Error::None,
1197 "Layer::Prepare: Error setting layer source crop: %s",
1198 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001199
Corey Tabaka2251d822017-04-20 16:04:07 -07001200 surface_rect_functions_applied_ = true;
1201 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001202 }
1203}
1204
1205void Layer::Finish(int release_fence_fd) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001206 IfAnyOf<SourceSurface, SourceBuffer>::Call(
1207 &source_, [release_fence_fd](auto& source) {
1208 source.Finish(LocalHandle(release_fence_fd));
1209 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001210}
1211
Corey Tabaka2251d822017-04-20 16:04:07 -07001212void Layer::Drop() { acquire_fence_.Close(); }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001213
1214} // namespace dvr
1215} // namespace android