blob: 9072d89d7668e4db19075beaf1273099e0ec3837 [file] [log] [blame]
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001#include "hardware_composer.h"
2
Steven Thomasdfde8fa2018-04-19 16:00:58 -07003#include <binder/IServiceManager.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08004#include <cutils/properties.h>
5#include <cutils/sched_policy.h>
6#include <fcntl.h>
Corey Tabaka2251d822017-04-20 16:04:07 -07007#include <log/log.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08008#include <poll.h>
Corey Tabakab3732f02017-09-16 00:58:54 -07009#include <stdint.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080010#include <sync/sync.h>
11#include <sys/eventfd.h>
12#include <sys/prctl.h>
13#include <sys/resource.h>
14#include <sys/system_properties.h>
15#include <sys/timerfd.h>
Corey Tabakab3732f02017-09-16 00:58:54 -070016#include <sys/types.h>
Corey Tabaka2251d822017-04-20 16:04:07 -070017#include <time.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080018#include <unistd.h>
19#include <utils/Trace.h>
20
21#include <algorithm>
Corey Tabaka2251d822017-04-20 16:04:07 -070022#include <chrono>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080023#include <functional>
24#include <map>
Corey Tabaka0b485c92017-05-19 12:02:58 -070025#include <sstream>
26#include <string>
John Bates954796e2017-05-11 11:00:31 -070027#include <tuple>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080028
Corey Tabaka2251d822017-04-20 16:04:07 -070029#include <dvr/dvr_display_types.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080030#include <dvr/performance_client_api.h>
31#include <private/dvr/clock_ns.h>
Corey Tabaka2251d822017-04-20 16:04:07 -070032#include <private/dvr/ion_buffer.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080033
Steven Thomasb02664d2017-07-26 18:48:28 -070034using android::hardware::Return;
35using android::hardware::Void;
Corey Tabakab3732f02017-09-16 00:58:54 -070036using android::pdx::ErrorStatus;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080037using android::pdx::LocalHandle;
Corey Tabakab3732f02017-09-16 00:58:54 -070038using android::pdx::Status;
Corey Tabaka2251d822017-04-20 16:04:07 -070039using android::pdx::rpc::EmptyVariant;
40using android::pdx::rpc::IfAnyOf;
41
42using namespace std::chrono_literals;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080043
44namespace android {
45namespace dvr {
46
47namespace {
48
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080049const char kDvrPerformanceProperty[] = "sys.dvr.performance";
Corey Tabaka451256f2017-08-22 11:59:15 -070050const char kDvrStandaloneProperty[] = "ro.boot.vr";
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080051
Luke Song4b788322017-03-24 14:17:31 -070052const char kRightEyeOffsetProperty[] = "dvr.right_eye_offset_ns";
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080053
Steven Thomasdfde8fa2018-04-19 16:00:58 -070054// Surface flinger uses "VSYNC-sf" and "VSYNC-app" for its version of these
55// events. Name ours similarly.
56const char kVsyncTraceEventName[] = "VSYNC-vrflinger";
57
Steven Thomasaf336272018-01-04 17:36:47 -080058// How long to wait after boot finishes before we turn the display off.
59constexpr int kBootFinishedDisplayOffTimeoutSec = 10;
60
Steven Thomasbfe46a02018-02-16 14:27:35 -080061constexpr int kDefaultDisplayWidth = 1920;
62constexpr int kDefaultDisplayHeight = 1080;
63constexpr int64_t kDefaultVsyncPeriodNs = 16666667;
64// Hardware composer reports dpi as dots per thousand inches (dpi * 1000).
65constexpr int kDefaultDpi = 400000;
66
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080067// Get time offset from a vsync to when the pose for that vsync should be
68// predicted out to. For example, if scanout gets halfway through the frame
69// at the halfway point between vsyncs, then this could be half the period.
70// With global shutter displays, this should be changed to the offset to when
71// illumination begins. Low persistence adds a frame of latency, so we predict
72// to the center of the next frame.
73inline int64_t GetPosePredictionTimeOffset(int64_t vsync_period_ns) {
74 return (vsync_period_ns * 150) / 100;
75}
76
Corey Tabaka2251d822017-04-20 16:04:07 -070077// Attempts to set the scheduler class and partiton for the current thread.
78// Returns true on success or false on failure.
79bool SetThreadPolicy(const std::string& scheduler_class,
80 const std::string& partition) {
81 int error = dvrSetSchedulerClass(0, scheduler_class.c_str());
82 if (error < 0) {
83 ALOGE(
84 "SetThreadPolicy: Failed to set scheduler class \"%s\" for "
85 "thread_id=%d: %s",
86 scheduler_class.c_str(), gettid(), strerror(-error));
87 return false;
88 }
89 error = dvrSetCpuPartition(0, partition.c_str());
90 if (error < 0) {
91 ALOGE(
92 "SetThreadPolicy: Failed to set cpu partiton \"%s\" for thread_id=%d: "
93 "%s",
94 partition.c_str(), gettid(), strerror(-error));
95 return false;
96 }
97 return true;
98}
99
Corey Tabakab3732f02017-09-16 00:58:54 -0700100// Utility to generate scoped tracers with arguments.
101// TODO(eieio): Move/merge this into utils/Trace.h?
102class TraceArgs {
103 public:
104 template <typename... Args>
Chih-Hung Hsieh79e7f1b2018-12-20 15:53:43 -0800105 explicit TraceArgs(const char* format, Args&&... args) {
Corey Tabakab3732f02017-09-16 00:58:54 -0700106 std::array<char, 1024> buffer;
107 snprintf(buffer.data(), buffer.size(), format, std::forward<Args>(args)...);
108 atrace_begin(ATRACE_TAG, buffer.data());
109 }
110
111 ~TraceArgs() { atrace_end(ATRACE_TAG); }
112
113 private:
114 TraceArgs(const TraceArgs&) = delete;
115 void operator=(const TraceArgs&) = delete;
116};
117
118// Macro to define a scoped tracer with arguments. Uses PASTE(x, y) macro
119// defined in utils/Trace.h.
120#define TRACE_FORMAT(format, ...) \
121 TraceArgs PASTE(__tracer, __LINE__) { format, ##__VA_ARGS__ }
122
Steven Thomasbfe46a02018-02-16 14:27:35 -0800123// Returns "primary" or "external". Useful for writing more readable logs.
124const char* GetDisplayName(bool is_primary) {
125 return is_primary ? "primary" : "external";
126}
127
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800128} // anonymous namespace
129
Corey Tabaka2251d822017-04-20 16:04:07 -0700130HardwareComposer::HardwareComposer()
Steven Thomasb02664d2017-07-26 18:48:28 -0700131 : initialized_(false), request_display_callback_(nullptr) {}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800132
133HardwareComposer::~HardwareComposer(void) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700134 UpdatePostThreadState(PostThreadState::Quit, true);
135 if (post_thread_.joinable())
Steven Thomas050b2c82017-03-06 11:45:16 -0800136 post_thread_.join();
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700137 composer_callback_->SetVsyncService(nullptr);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800138}
139
Steven Thomasb02664d2017-07-26 18:48:28 -0700140bool HardwareComposer::Initialize(
Steven Thomas6e8f7062017-11-22 14:15:29 -0800141 Hwc2::Composer* composer, hwc2_display_t primary_display_id,
142 RequestDisplayCallback request_display_callback) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800143 if (initialized_) {
144 ALOGE("HardwareComposer::Initialize: already initialized.");
145 return false;
146 }
147
Corey Tabaka451256f2017-08-22 11:59:15 -0700148 is_standalone_device_ = property_get_bool(kDvrStandaloneProperty, false);
149
Steven Thomasb02664d2017-07-26 18:48:28 -0700150 request_display_callback_ = request_display_callback;
151
Steven Thomasbfe46a02018-02-16 14:27:35 -0800152 primary_display_ = GetDisplayParams(composer, primary_display_id, true);
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700153
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700154 vsync_service_ = new VsyncService;
155 sp<IServiceManager> sm(defaultServiceManager());
156 auto result = sm->addService(String16(VsyncService::GetServiceName()),
157 vsync_service_, false);
158 LOG_ALWAYS_FATAL_IF(result != android::OK,
159 "addService(%s) failed", VsyncService::GetServiceName());
160
Corey Tabaka2251d822017-04-20 16:04:07 -0700161 post_thread_event_fd_.Reset(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
Steven Thomas050b2c82017-03-06 11:45:16 -0800162 LOG_ALWAYS_FATAL_IF(
Corey Tabaka2251d822017-04-20 16:04:07 -0700163 !post_thread_event_fd_,
Steven Thomas050b2c82017-03-06 11:45:16 -0800164 "HardwareComposer: Failed to create interrupt event fd : %s",
165 strerror(errno));
166
167 post_thread_ = std::thread(&HardwareComposer::PostThread, this);
168
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800169 initialized_ = true;
170
171 return initialized_;
172}
173
Steven Thomas050b2c82017-03-06 11:45:16 -0800174void HardwareComposer::Enable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700175 UpdatePostThreadState(PostThreadState::Suspended, false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800176}
177
178void HardwareComposer::Disable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700179 UpdatePostThreadState(PostThreadState::Suspended, true);
Steven Thomas7f8761e2018-01-18 18:49:59 -0800180
181 std::unique_lock<std::mutex> lock(post_thread_mutex_);
182 post_thread_ready_.wait(lock, [this] {
183 return !post_thread_resumed_;
184 });
Steven Thomas050b2c82017-03-06 11:45:16 -0800185}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800186
Steven Thomasaf336272018-01-04 17:36:47 -0800187void HardwareComposer::OnBootFinished() {
188 std::lock_guard<std::mutex> lock(post_thread_mutex_);
189 if (boot_finished_)
190 return;
191 boot_finished_ = true;
192 post_thread_wait_.notify_one();
193 if (is_standalone_device_)
194 request_display_callback_(true);
195}
196
Corey Tabaka2251d822017-04-20 16:04:07 -0700197// Update the post thread quiescent state based on idle and suspended inputs.
198void HardwareComposer::UpdatePostThreadState(PostThreadStateType state,
199 bool suspend) {
200 std::unique_lock<std::mutex> lock(post_thread_mutex_);
201
202 // Update the votes in the state variable before evaluating the effective
203 // quiescent state. Any bits set in post_thread_state_ indicate that the post
204 // thread should be suspended.
205 if (suspend) {
206 post_thread_state_ |= state;
207 } else {
208 post_thread_state_ &= ~state;
209 }
210
211 const bool quit = post_thread_state_ & PostThreadState::Quit;
212 const bool effective_suspend = post_thread_state_ != PostThreadState::Active;
213 if (quit) {
214 post_thread_quiescent_ = true;
215 eventfd_write(post_thread_event_fd_.Get(), 1);
216 post_thread_wait_.notify_one();
217 } else if (effective_suspend && !post_thread_quiescent_) {
218 post_thread_quiescent_ = true;
219 eventfd_write(post_thread_event_fd_.Get(), 1);
220 } else if (!effective_suspend && post_thread_quiescent_) {
221 post_thread_quiescent_ = false;
222 eventfd_t value;
223 eventfd_read(post_thread_event_fd_.Get(), &value);
224 post_thread_wait_.notify_one();
225 }
Steven Thomas050b2c82017-03-06 11:45:16 -0800226}
Steven Thomas282a5ed2017-02-07 18:07:01 -0800227
Steven Thomasbfe46a02018-02-16 14:27:35 -0800228void HardwareComposer::CreateComposer() {
229 if (composer_)
230 return;
231 composer_.reset(new Hwc2::impl::Composer("default"));
232 composer_callback_ = new ComposerCallback;
233 composer_->registerCallback(composer_callback_);
234 LOG_ALWAYS_FATAL_IF(!composer_callback_->GotFirstHotplug(),
235 "Registered composer callback but didn't get hotplug for primary"
236 " display");
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700237 composer_callback_->SetVsyncService(vsync_service_);
Steven Thomasbfe46a02018-02-16 14:27:35 -0800238}
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700239
Steven Thomasbfe46a02018-02-16 14:27:35 -0800240void HardwareComposer::OnPostThreadResumed() {
241 ALOGI("OnPostThreadResumed");
242 EnableDisplay(*target_display_, true);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800243
Steven Thomas050b2c82017-03-06 11:45:16 -0800244 // Trigger target-specific performance mode change.
245 property_set(kDvrPerformanceProperty, "performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800246}
247
Steven Thomas050b2c82017-03-06 11:45:16 -0800248void HardwareComposer::OnPostThreadPaused() {
Steven Thomasbfe46a02018-02-16 14:27:35 -0800249 ALOGI("OnPostThreadPaused");
Corey Tabaka2251d822017-04-20 16:04:07 -0700250 retire_fence_fds_.clear();
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700251 layers_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800252
Steven Thomasbfe46a02018-02-16 14:27:35 -0800253 // Phones create a new composer client on resume and destroy it on pause.
254 // Standalones only create the composer client once and then use SetPowerMode
255 // to control the screen on pause/resume.
Corey Tabaka451256f2017-08-22 11:59:15 -0700256 if (!is_standalone_device_) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700257 if (composer_callback_ != nullptr) {
258 composer_callback_->SetVsyncService(nullptr);
259 composer_callback_ = nullptr;
260 }
Corey Tabaka451256f2017-08-22 11:59:15 -0700261 composer_.reset(nullptr);
Corey Tabaka451256f2017-08-22 11:59:15 -0700262 } else {
Steven Thomasbfe46a02018-02-16 14:27:35 -0800263 EnableDisplay(*target_display_, false);
Corey Tabaka451256f2017-08-22 11:59:15 -0700264 }
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700265
Steven Thomas050b2c82017-03-06 11:45:16 -0800266 // Trigger target-specific performance mode change.
267 property_set(kDvrPerformanceProperty, "idle");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800268}
269
Steven Thomasaf336272018-01-04 17:36:47 -0800270bool HardwareComposer::PostThreadCondWait(std::unique_lock<std::mutex>& lock,
271 int timeout_sec,
272 const std::function<bool()>& pred) {
273 auto pred_with_quit = [&] {
274 return pred() || (post_thread_state_ & PostThreadState::Quit);
275 };
276 if (timeout_sec >= 0) {
277 post_thread_wait_.wait_for(lock, std::chrono::seconds(timeout_sec),
278 pred_with_quit);
279 } else {
280 post_thread_wait_.wait(lock, pred_with_quit);
281 }
282 if (post_thread_state_ & PostThreadState::Quit) {
283 ALOGI("HardwareComposer::PostThread: Quitting.");
284 return true;
285 }
286 return false;
287}
288
Corey Tabaka2251d822017-04-20 16:04:07 -0700289HWC::Error HardwareComposer::Validate(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800290 uint32_t num_types;
291 uint32_t num_requests;
Corey Tabaka2251d822017-04-20 16:04:07 -0700292 HWC::Error error =
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700293 composer_->validateDisplay(display, &num_types, &num_requests);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800294
295 if (error == HWC2_ERROR_HAS_CHANGES) {
Steven Thomasbfe46a02018-02-16 14:27:35 -0800296 ALOGE("Hardware composer has requested composition changes, "
297 "which we don't support.");
298 // Accept the changes anyway and see if we can get something on the screen.
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700299 error = composer_->acceptDisplayChanges(display);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800300 }
301
302 return error;
303}
304
Steven Thomasbfe46a02018-02-16 14:27:35 -0800305bool HardwareComposer::EnableVsync(const DisplayParams& display, bool enabled) {
306 HWC::Error error = composer_->setVsyncEnabled(display.id,
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800307 (Hwc2::IComposerClient::Vsync)(enabled ? HWC2_VSYNC_ENABLE
308 : HWC2_VSYNC_DISABLE));
Steven Thomasbfe46a02018-02-16 14:27:35 -0800309 if (error != HWC::Error::None) {
310 ALOGE("Error attempting to %s vsync on %s display: %s",
311 enabled ? "enable" : "disable", GetDisplayName(display.is_primary),
312 error.to_string().c_str());
313 }
314 return error == HWC::Error::None;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800315}
316
Steven Thomasbfe46a02018-02-16 14:27:35 -0800317bool HardwareComposer::SetPowerMode(const DisplayParams& display, bool active) {
318 ALOGI("Turning %s display %s", GetDisplayName(display.is_primary),
319 active ? "on" : "off");
Corey Tabaka451256f2017-08-22 11:59:15 -0700320 HWC::PowerMode power_mode = active ? HWC::PowerMode::On : HWC::PowerMode::Off;
Steven Thomasbfe46a02018-02-16 14:27:35 -0800321 HWC::Error error = composer_->setPowerMode(display.id,
Steven Thomas6e8f7062017-11-22 14:15:29 -0800322 power_mode.cast<Hwc2::IComposerClient::PowerMode>());
Steven Thomasbfe46a02018-02-16 14:27:35 -0800323 if (error != HWC::Error::None) {
324 ALOGE("Error attempting to turn %s display %s: %s",
325 GetDisplayName(display.is_primary), active ? "on" : "off",
326 error.to_string().c_str());
327 }
328 return error == HWC::Error::None;
329}
330
331bool HardwareComposer::EnableDisplay(const DisplayParams& display,
332 bool enabled) {
333 bool power_result;
334 bool vsync_result;
335 // When turning a display on, we set the power state then set vsync. When
336 // turning a display off we do it in the opposite order.
337 if (enabled) {
338 power_result = SetPowerMode(display, enabled);
339 vsync_result = EnableVsync(display, enabled);
340 } else {
341 vsync_result = EnableVsync(display, enabled);
342 power_result = SetPowerMode(display, enabled);
343 }
344 return power_result && vsync_result;
Corey Tabaka451256f2017-08-22 11:59:15 -0700345}
346
Corey Tabaka2251d822017-04-20 16:04:07 -0700347HWC::Error HardwareComposer::Present(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800348 int32_t present_fence;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700349 HWC::Error error = composer_->presentDisplay(display, &present_fence);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800350
351 // According to the documentation, this fence is signaled at the time of
352 // vsync/DMA for physical displays.
Corey Tabaka2251d822017-04-20 16:04:07 -0700353 if (error == HWC::Error::None) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800354 retire_fence_fds_.emplace_back(present_fence);
355 } else {
356 ATRACE_INT("HardwareComposer: PresentResult", error);
357 }
358
359 return error;
360}
361
Steven Thomasbfe46a02018-02-16 14:27:35 -0800362DisplayParams HardwareComposer::GetDisplayParams(
363 Hwc2::Composer* composer, hwc2_display_t display, bool is_primary) {
364 DisplayParams params;
365 params.id = display;
366 params.is_primary = is_primary;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800367
Steven Thomasbfe46a02018-02-16 14:27:35 -0800368 Hwc2::Config config;
369 HWC::Error error = composer->getActiveConfig(display, &config);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800370
Steven Thomasbfe46a02018-02-16 14:27:35 -0800371 if (error == HWC::Error::None) {
372 auto get_attr = [&](hwc2_attribute_t attr, const char* attr_name)
373 -> std::optional<int32_t> {
374 int32_t val;
375 HWC::Error error = composer->getDisplayAttribute(
376 display, config, (Hwc2::IComposerClient::Attribute)attr, &val);
377 if (error != HWC::Error::None) {
378 ALOGE("Failed to get %s display attr %s: %s",
379 GetDisplayName(is_primary), attr_name,
380 error.to_string().c_str());
381 return std::nullopt;
382 }
383 return val;
384 };
385
386 auto width = get_attr(HWC2_ATTRIBUTE_WIDTH, "width");
387 auto height = get_attr(HWC2_ATTRIBUTE_HEIGHT, "height");
388
389 if (width && height) {
390 params.width = *width;
391 params.height = *height;
392 } else {
393 ALOGI("Failed to get width and/or height for %s display. Using default"
394 " size %dx%d.", GetDisplayName(is_primary), kDefaultDisplayWidth,
395 kDefaultDisplayHeight);
396 params.width = kDefaultDisplayWidth;
397 params.height = kDefaultDisplayHeight;
398 }
399
400 auto vsync_period = get_attr(HWC2_ATTRIBUTE_VSYNC_PERIOD, "vsync period");
401 if (vsync_period) {
402 params.vsync_period_ns = *vsync_period;
403 } else {
404 ALOGI("Failed to get vsync period for %s display. Using default vsync"
405 " period %.2fms", GetDisplayName(is_primary),
406 static_cast<float>(kDefaultVsyncPeriodNs) / 1000000);
407 params.vsync_period_ns = kDefaultVsyncPeriodNs;
408 }
409
410 auto dpi_x = get_attr(HWC2_ATTRIBUTE_DPI_X, "DPI X");
411 auto dpi_y = get_attr(HWC2_ATTRIBUTE_DPI_Y, "DPI Y");
412 if (dpi_x && dpi_y) {
413 params.dpi.x = *dpi_x;
414 params.dpi.y = *dpi_y;
415 } else {
416 ALOGI("Failed to get dpi_x and/or dpi_y for %s display. Using default"
417 " dpi %d.", GetDisplayName(is_primary), kDefaultDpi);
418 params.dpi.x = kDefaultDpi;
419 params.dpi.y = kDefaultDpi;
420 }
421 } else {
422 ALOGE("HardwareComposer: Failed to get current %s display config: %d."
423 " Using default display values.",
424 GetDisplayName(is_primary), error.value);
425 params.width = kDefaultDisplayWidth;
426 params.height = kDefaultDisplayHeight;
427 params.dpi.x = kDefaultDpi;
428 params.dpi.y = kDefaultDpi;
429 params.vsync_period_ns = kDefaultVsyncPeriodNs;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800430 }
431
Steven Thomasbfe46a02018-02-16 14:27:35 -0800432 ALOGI(
433 "HardwareComposer: %s display attributes: width=%d height=%d "
434 "vsync_period_ns=%d DPI=%dx%d",
435 GetDisplayName(is_primary),
436 params.width,
437 params.height,
438 params.vsync_period_ns,
439 params.dpi.x,
440 params.dpi.y);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800441
Steven Thomasbfe46a02018-02-16 14:27:35 -0800442 return params;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800443}
444
Corey Tabaka0b485c92017-05-19 12:02:58 -0700445std::string HardwareComposer::Dump() {
446 std::unique_lock<std::mutex> lock(post_thread_mutex_);
447 std::ostringstream stream;
448
Steven Thomasbfe46a02018-02-16 14:27:35 -0800449 auto print_display_metrics = [&](const DisplayParams& params) {
450 stream << GetDisplayName(params.is_primary)
451 << " display metrics: " << params.width << "x"
452 << params.height << " " << (params.dpi.x / 1000.0)
453 << "x" << (params.dpi.y / 1000.0) << " dpi @ "
454 << (1000000000.0 / params.vsync_period_ns) << " Hz"
455 << std::endl;
456 };
457
458 print_display_metrics(primary_display_);
459 if (external_display_)
460 print_display_metrics(*external_display_);
Corey Tabaka0b485c92017-05-19 12:02:58 -0700461
462 stream << "Post thread resumed: " << post_thread_resumed_ << std::endl;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700463 stream << "Active layers: " << layers_.size() << std::endl;
Corey Tabaka0b485c92017-05-19 12:02:58 -0700464 stream << std::endl;
465
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700466 for (size_t i = 0; i < layers_.size(); i++) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700467 stream << "Layer " << i << ":";
468 stream << " type=" << layers_[i].GetCompositionType().to_string();
469 stream << " surface_id=" << layers_[i].GetSurfaceId();
470 stream << " buffer_id=" << layers_[i].GetBufferId();
471 stream << std::endl;
472 }
473 stream << std::endl;
474
475 if (post_thread_resumed_) {
476 stream << "Hardware Composer Debug Info:" << std::endl;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700477 stream << composer_->dumpDebugInfo();
Corey Tabaka0b485c92017-05-19 12:02:58 -0700478 }
479
480 return stream.str();
481}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800482
Steven Thomasbfe46a02018-02-16 14:27:35 -0800483void HardwareComposer::PostLayers(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800484 ATRACE_NAME("HardwareComposer::PostLayers");
485
486 // Setup the hardware composer layers with current buffers.
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700487 for (auto& layer : layers_) {
488 layer.Prepare();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800489 }
490
491 // Now that we have taken in a frame from the application, we have a chance
492 // to drop the frame before passing the frame along to HWC.
493 // If the display driver has become backed up, we detect it here and then
494 // react by skipping this frame to catch up latency.
495 while (!retire_fence_fds_.empty() &&
496 (!retire_fence_fds_.front() ||
497 sync_wait(retire_fence_fds_.front().Get(), 0) == 0)) {
498 // There are only 2 fences in here, no performance problem to shift the
499 // array of ints.
500 retire_fence_fds_.erase(retire_fence_fds_.begin());
501 }
502
George Burgess IV353a6f62017-06-26 17:13:09 -0700503 const bool is_fence_pending = static_cast<int32_t>(retire_fence_fds_.size()) >
John Bates954796e2017-05-11 11:00:31 -0700504 post_thread_config_.allowed_pending_fence_count;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800505
Corey Tabakab3732f02017-09-16 00:58:54 -0700506 if (is_fence_pending) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800507 ATRACE_INT("frame_skip_count", ++frame_skip_count_);
508
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800509 ALOGW_IF(is_fence_pending,
510 "Warning: dropping a frame to catch up with HWC (pending = %zd)",
511 retire_fence_fds_.size());
512
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700513 for (auto& layer : layers_) {
514 layer.Drop();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800515 }
516 return;
517 } else {
518 // Make the transition more obvious in systrace when the frame skip happens
519 // above.
520 ATRACE_INT("frame_skip_count", 0);
521 }
522
Corey Tabaka89bbefc2017-06-06 16:14:21 -0700523#if TRACE > 1
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700524 for (size_t i = 0; i < layers_.size(); i++) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700525 ALOGI("HardwareComposer::PostLayers: layer=%zu buffer_id=%d composition=%s",
526 i, layers_[i].GetBufferId(),
Corey Tabaka2251d822017-04-20 16:04:07 -0700527 layers_[i].GetCompositionType().to_string().c_str());
Corey Tabaka0b485c92017-05-19 12:02:58 -0700528 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800529#endif
530
Steven Thomasbfe46a02018-02-16 14:27:35 -0800531 HWC::Error error = Validate(display);
John Bates46684842017-12-13 15:26:50 -0800532 if (error != HWC::Error::None) {
Steven Thomasbfe46a02018-02-16 14:27:35 -0800533 ALOGE("HardwareComposer::PostLayers: Validate failed: %s display=%" PRIu64,
534 error.to_string().c_str(), display);
John Bates46684842017-12-13 15:26:50 -0800535 return;
536 }
537
Steven Thomasbfe46a02018-02-16 14:27:35 -0800538 error = Present(display);
Corey Tabaka2251d822017-04-20 16:04:07 -0700539 if (error != HWC::Error::None) {
540 ALOGE("HardwareComposer::PostLayers: Present failed: %s",
541 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800542 return;
543 }
544
545 std::vector<Hwc2::Layer> out_layers;
546 std::vector<int> out_fences;
Steven Thomasbfe46a02018-02-16 14:27:35 -0800547 error = composer_->getReleaseFences(display,
Steven Thomas6e8f7062017-11-22 14:15:29 -0800548 &out_layers, &out_fences);
Corey Tabaka2251d822017-04-20 16:04:07 -0700549 ALOGE_IF(error != HWC::Error::None,
550 "HardwareComposer::PostLayers: Failed to get release fences: %s",
551 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800552
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700553 // Perform post-frame bookkeeping.
Corey Tabaka2251d822017-04-20 16:04:07 -0700554 uint32_t num_elements = out_layers.size();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800555 for (size_t i = 0; i < num_elements; ++i) {
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700556 for (auto& layer : layers_) {
557 if (layer.GetLayerHandle() == out_layers[i]) {
558 layer.Finish(out_fences[i]);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800559 }
560 }
561 }
562}
563
Steven Thomas050b2c82017-03-06 11:45:16 -0800564void HardwareComposer::SetDisplaySurfaces(
Corey Tabaka2251d822017-04-20 16:04:07 -0700565 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces) {
Jin Qian7480c062017-03-21 00:04:15 +0000566 ALOGI("HardwareComposer::SetDisplaySurfaces: surface count=%zd",
567 surfaces.size());
Corey Tabaka2251d822017-04-20 16:04:07 -0700568 const bool display_idle = surfaces.size() == 0;
569 {
570 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Steven Thomasbfe46a02018-02-16 14:27:35 -0800571 surfaces_ = std::move(surfaces);
572 surfaces_changed_ = true;
Corey Tabaka2251d822017-04-20 16:04:07 -0700573 }
574
Steven Thomasaf336272018-01-04 17:36:47 -0800575 if (request_display_callback_ && !is_standalone_device_)
Steven Thomas2ddf5672017-06-15 11:38:40 -0700576 request_display_callback_(!display_idle);
577
Corey Tabaka2251d822017-04-20 16:04:07 -0700578 // Set idle state based on whether there are any surfaces to handle.
579 UpdatePostThreadState(PostThreadState::Idle, display_idle);
Steven Thomas050b2c82017-03-06 11:45:16 -0800580}
Jin Qian7480c062017-03-21 00:04:15 +0000581
John Bates954796e2017-05-11 11:00:31 -0700582int HardwareComposer::OnNewGlobalBuffer(DvrGlobalBufferKey key,
583 IonBuffer& ion_buffer) {
Okan Arikan822b7102017-05-08 13:31:34 -0700584 if (key == DvrGlobalBuffers::kVsyncBuffer) {
585 vsync_ring_ = std::make_unique<CPUMappedBroadcastRing<DvrVsyncRing>>(
586 &ion_buffer, CPUUsageMode::WRITE_OFTEN);
587
588 if (vsync_ring_->IsMapped() == false) {
589 return -EPERM;
590 }
591 }
592
593 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700594 return MapConfigBuffer(ion_buffer);
595 }
596
597 return 0;
598}
599
600void HardwareComposer::OnDeletedGlobalBuffer(DvrGlobalBufferKey key) {
Okan Arikan822b7102017-05-08 13:31:34 -0700601 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700602 ConfigBufferDeleted();
603 }
604}
605
606int HardwareComposer::MapConfigBuffer(IonBuffer& ion_buffer) {
607 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700608 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700609
Okan Arikan6f468c62017-05-31 14:48:30 -0700610 if (ion_buffer.width() < DvrConfigRing::MemorySize()) {
John Bates954796e2017-05-11 11:00:31 -0700611 ALOGE("HardwareComposer::MapConfigBuffer: invalid buffer size.");
612 return -EINVAL;
613 }
614
615 void* buffer_base = 0;
616 int result = ion_buffer.Lock(ion_buffer.usage(), 0, 0, ion_buffer.width(),
617 ion_buffer.height(), &buffer_base);
618 if (result != 0) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700619 ALOGE(
620 "HardwareComposer::MapConfigBuffer: Failed to map vrflinger config "
621 "buffer.");
John Bates954796e2017-05-11 11:00:31 -0700622 return -EPERM;
623 }
624
Okan Arikan6f468c62017-05-31 14:48:30 -0700625 shared_config_ring_ = DvrConfigRing::Create(buffer_base, ion_buffer.width());
John Bates954796e2017-05-11 11:00:31 -0700626 ion_buffer.Unlock();
627
628 return 0;
629}
630
631void HardwareComposer::ConfigBufferDeleted() {
632 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700633 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700634}
635
636void HardwareComposer::UpdateConfigBuffer() {
637 std::lock_guard<std::mutex> lock(shared_config_mutex_);
638 if (!shared_config_ring_.is_valid())
639 return;
640 // Copy from latest record in shared_config_ring_ to local copy.
Okan Arikan6f468c62017-05-31 14:48:30 -0700641 DvrConfig record;
John Bates954796e2017-05-11 11:00:31 -0700642 if (shared_config_ring_.GetNewest(&shared_config_ring_sequence_, &record)) {
John Batescc65c3c2017-09-28 14:43:19 -0700643 ALOGI("DvrConfig updated: sequence %u, post offset %d",
644 shared_config_ring_sequence_, record.frame_post_offset_ns);
645 ++shared_config_ring_sequence_;
John Bates954796e2017-05-11 11:00:31 -0700646 post_thread_config_ = record;
647 }
648}
649
Corey Tabaka2251d822017-04-20 16:04:07 -0700650int HardwareComposer::PostThreadPollInterruptible(
Steven Thomasb02664d2017-07-26 18:48:28 -0700651 const pdx::LocalHandle& event_fd, int requested_events, int timeout_ms) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800652 pollfd pfd[2] = {
653 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700654 .fd = event_fd.Get(),
Steven Thomas66747c12017-03-22 18:45:31 -0700655 .events = static_cast<short>(requested_events),
656 .revents = 0,
Steven Thomas050b2c82017-03-06 11:45:16 -0800657 },
658 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700659 .fd = post_thread_event_fd_.Get(),
Steven Thomas050b2c82017-03-06 11:45:16 -0800660 .events = POLLPRI | POLLIN,
661 .revents = 0,
662 },
663 };
664 int ret, error;
665 do {
Steven Thomasb02664d2017-07-26 18:48:28 -0700666 ret = poll(pfd, 2, timeout_ms);
Steven Thomas050b2c82017-03-06 11:45:16 -0800667 error = errno;
668 ALOGW_IF(ret < 0,
669 "HardwareComposer::PostThreadPollInterruptible: Error during "
670 "poll(): %s (%d)",
671 strerror(error), error);
672 } while (ret < 0 && error == EINTR);
673
674 if (ret < 0) {
675 return -error;
Steven Thomasb02664d2017-07-26 18:48:28 -0700676 } else if (ret == 0) {
677 return -ETIMEDOUT;
Steven Thomas050b2c82017-03-06 11:45:16 -0800678 } else if (pfd[0].revents != 0) {
679 return 0;
680 } else if (pfd[1].revents != 0) {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -0700681 ALOGI("VrHwcPost thread interrupted: revents=%x", pfd[1].revents);
Steven Thomas050b2c82017-03-06 11:45:16 -0800682 return kPostThreadInterrupted;
683 } else {
684 return 0;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800685 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800686}
687
Steven Thomasbfe46a02018-02-16 14:27:35 -0800688// Sleep until the next predicted vsync, returning the predicted vsync
689// timestamp.
690Status<int64_t> HardwareComposer::WaitForPredictedVSync() {
691 const int64_t predicted_vsync_time = last_vsync_timestamp_ +
692 (target_display_->vsync_period_ns * vsync_prediction_interval_);
Corey Tabakab3732f02017-09-16 00:58:54 -0700693 const int error = SleepUntil(predicted_vsync_time);
694 if (error < 0) {
695 ALOGE("HardwareComposer::WaifForVSync:: Failed to sleep: %s",
696 strerror(-error));
Steven Thomasb02664d2017-07-26 18:48:28 -0700697 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800698 }
Corey Tabakab3732f02017-09-16 00:58:54 -0700699 return {predicted_vsync_time};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800700}
701
702int HardwareComposer::SleepUntil(int64_t wakeup_timestamp) {
703 const int timer_fd = vsync_sleep_timer_fd_.Get();
704 const itimerspec wakeup_itimerspec = {
705 .it_interval = {.tv_sec = 0, .tv_nsec = 0},
706 .it_value = NsToTimespec(wakeup_timestamp),
707 };
708 int ret =
709 timerfd_settime(timer_fd, TFD_TIMER_ABSTIME, &wakeup_itimerspec, nullptr);
710 int error = errno;
711 if (ret < 0) {
712 ALOGE("HardwareComposer::SleepUntil: Failed to set timerfd: %s",
713 strerror(error));
714 return -error;
715 }
716
Corey Tabaka451256f2017-08-22 11:59:15 -0700717 return PostThreadPollInterruptible(vsync_sleep_timer_fd_, POLLIN,
718 /*timeout_ms*/ -1);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800719}
720
721void HardwareComposer::PostThread() {
722 // NOLINTNEXTLINE(runtime/int)
Steven Thomas050b2c82017-03-06 11:45:16 -0800723 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>("VrHwcPost"), 0, 0, 0);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800724
Corey Tabaka2251d822017-04-20 16:04:07 -0700725 // Set the scheduler to SCHED_FIFO with high priority. If this fails here
726 // there may have been a startup timing issue between this thread and
727 // performanced. Try again later when this thread becomes active.
728 bool thread_policy_setup =
729 SetThreadPolicy("graphics:high", "/system/performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800730
Steven Thomas050b2c82017-03-06 11:45:16 -0800731 // Create a timerfd based on CLOCK_MONOTINIC.
732 vsync_sleep_timer_fd_.Reset(timerfd_create(CLOCK_MONOTONIC, 0));
733 LOG_ALWAYS_FATAL_IF(
734 !vsync_sleep_timer_fd_,
735 "HardwareComposer: Failed to create vsync sleep timerfd: %s",
736 strerror(errno));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800737
Steven Thomasbfe46a02018-02-16 14:27:35 -0800738 struct VsyncEyeOffsets { int64_t left_ns, right_ns; };
Steven Thomas050b2c82017-03-06 11:45:16 -0800739 bool was_running = false;
740
Steven Thomasbfe46a02018-02-16 14:27:35 -0800741 auto get_vsync_eye_offsets = [this]() -> VsyncEyeOffsets {
742 VsyncEyeOffsets offsets;
743 offsets.left_ns =
744 GetPosePredictionTimeOffset(target_display_->vsync_period_ns);
745
746 // TODO(jbates) Query vblank time from device, when such an API is
747 // available. This value (6.3%) was measured on A00 in low persistence mode.
748 int64_t vblank_ns = target_display_->vsync_period_ns * 63 / 1000;
749 offsets.right_ns = (target_display_->vsync_period_ns - vblank_ns) / 2;
750
751 // Check property for overriding right eye offset value.
752 offsets.right_ns =
753 property_get_int64(kRightEyeOffsetProperty, offsets.right_ns);
754
755 return offsets;
756 };
757
758 VsyncEyeOffsets vsync_eye_offsets = get_vsync_eye_offsets();
759
Steven Thomasaf336272018-01-04 17:36:47 -0800760 if (is_standalone_device_) {
761 // First, wait until boot finishes.
762 std::unique_lock<std::mutex> lock(post_thread_mutex_);
763 if (PostThreadCondWait(lock, -1, [this] { return boot_finished_; })) {
764 return;
765 }
766
767 // Then, wait until we're either leaving the quiescent state, or the boot
768 // finished display off timeout expires.
769 if (PostThreadCondWait(lock, kBootFinishedDisplayOffTimeoutSec,
770 [this] { return !post_thread_quiescent_; })) {
771 return;
772 }
773
774 LOG_ALWAYS_FATAL_IF(post_thread_state_ & PostThreadState::Suspended,
775 "Vr flinger should own the display by now.");
776 post_thread_resumed_ = true;
777 post_thread_ready_.notify_all();
Steven Thomasbfe46a02018-02-16 14:27:35 -0800778 if (!composer_)
779 CreateComposer();
Steven Thomasaf336272018-01-04 17:36:47 -0800780 }
781
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800782 while (1) {
783 ATRACE_NAME("HardwareComposer::PostThread");
784
John Bates954796e2017-05-11 11:00:31 -0700785 // Check for updated config once per vsync.
786 UpdateConfigBuffer();
787
Corey Tabaka2251d822017-04-20 16:04:07 -0700788 while (post_thread_quiescent_) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800789 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Corey Tabaka2251d822017-04-20 16:04:07 -0700790 ALOGI("HardwareComposer::PostThread: Entering quiescent state.");
791
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700792 if (was_running) {
793 vsync_trace_parity_ = false;
794 ATRACE_INT(kVsyncTraceEventName, 0);
795 }
796
Steven Thomasbfe46a02018-02-16 14:27:35 -0800797 // Tear down resources.
798 OnPostThreadPaused();
Corey Tabaka2251d822017-04-20 16:04:07 -0700799 was_running = false;
800 post_thread_resumed_ = false;
801 post_thread_ready_.notify_all();
802
Steven Thomasaf336272018-01-04 17:36:47 -0800803 if (PostThreadCondWait(lock, -1,
804 [this] { return !post_thread_quiescent_; })) {
805 // A true return value means we've been asked to quit.
Corey Tabaka2251d822017-04-20 16:04:07 -0700806 return;
Steven Thomas282a5ed2017-02-07 18:07:01 -0800807 }
Corey Tabaka2251d822017-04-20 16:04:07 -0700808
Corey Tabaka2251d822017-04-20 16:04:07 -0700809 post_thread_resumed_ = true;
810 post_thread_ready_.notify_all();
811
812 ALOGI("HardwareComposer::PostThread: Exiting quiescent state.");
Steven Thomas050b2c82017-03-06 11:45:16 -0800813 }
814
Steven Thomasbfe46a02018-02-16 14:27:35 -0800815 if (!composer_)
816 CreateComposer();
817
818 bool target_display_changed = UpdateTargetDisplay();
819 bool just_resumed_running = !was_running;
820 was_running = true;
821
822 if (target_display_changed)
823 vsync_eye_offsets = get_vsync_eye_offsets();
824
825 if (just_resumed_running) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800826 OnPostThreadResumed();
Corey Tabaka2251d822017-04-20 16:04:07 -0700827
828 // Try to setup the scheduler policy if it failed during startup. Only
829 // attempt to do this on transitions from inactive to active to avoid
830 // spamming the system with RPCs and log messages.
831 if (!thread_policy_setup) {
832 thread_policy_setup =
833 SetThreadPolicy("graphics:high", "/system/performance");
834 }
Steven Thomasbfe46a02018-02-16 14:27:35 -0800835 }
Corey Tabakab3732f02017-09-16 00:58:54 -0700836
Steven Thomasbfe46a02018-02-16 14:27:35 -0800837 if (target_display_changed || just_resumed_running) {
Corey Tabakab3732f02017-09-16 00:58:54 -0700838 // Initialize the last vsync timestamp with the current time. The
839 // predictor below uses this time + the vsync interval in absolute time
840 // units for the initial delay. Once the driver starts reporting vsync the
841 // predictor will sync up with the real vsync.
842 last_vsync_timestamp_ = GetSystemClockNs();
Steven Thomasbfe46a02018-02-16 14:27:35 -0800843 vsync_prediction_interval_ = 1;
844 retire_fence_fds_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800845 }
846
847 int64_t vsync_timestamp = 0;
848 {
Corey Tabakab3732f02017-09-16 00:58:54 -0700849 TRACE_FORMAT("wait_vsync|vsync=%u;last_timestamp=%" PRId64
850 ";prediction_interval=%d|",
851 vsync_count_ + 1, last_vsync_timestamp_,
852 vsync_prediction_interval_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800853
Steven Thomasbfe46a02018-02-16 14:27:35 -0800854 auto status = WaitForPredictedVSync();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800855 ALOGE_IF(
Corey Tabakab3732f02017-09-16 00:58:54 -0700856 !status,
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800857 "HardwareComposer::PostThread: Failed to wait for vsync event: %s",
Corey Tabakab3732f02017-09-16 00:58:54 -0700858 status.GetErrorMessage().c_str());
859
860 // If there was an error either sleeping was interrupted due to pausing or
861 // there was an error getting the latest timestamp.
862 if (!status)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800863 continue;
Corey Tabakab3732f02017-09-16 00:58:54 -0700864
865 // Predicted vsync timestamp for this interval. This is stable because we
866 // use absolute time for the wakeup timer.
867 vsync_timestamp = status.get();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800868 }
869
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700870 vsync_trace_parity_ = !vsync_trace_parity_;
871 ATRACE_INT(kVsyncTraceEventName, vsync_trace_parity_ ? 1 : 0);
872
Corey Tabakab3732f02017-09-16 00:58:54 -0700873 // Advance the vsync counter only if the system is keeping up with hardware
874 // vsync to give clients an indication of the delays.
875 if (vsync_prediction_interval_ == 1)
876 ++vsync_count_;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800877
Steven Thomasbfe46a02018-02-16 14:27:35 -0800878 UpdateLayerConfig();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800879
Okan Arikan822b7102017-05-08 13:31:34 -0700880 // Publish the vsync event.
881 if (vsync_ring_) {
882 DvrVsync vsync;
883 vsync.vsync_count = vsync_count_;
884 vsync.vsync_timestamp_ns = vsync_timestamp;
Steven Thomasbfe46a02018-02-16 14:27:35 -0800885 vsync.vsync_left_eye_offset_ns = vsync_eye_offsets.left_ns;
886 vsync.vsync_right_eye_offset_ns = vsync_eye_offsets.right_ns;
887 vsync.vsync_period_ns = target_display_->vsync_period_ns;
Okan Arikan822b7102017-05-08 13:31:34 -0700888
889 vsync_ring_->Publish(vsync);
890 }
891
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800892 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700893 // Sleep until shortly before vsync.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800894 ATRACE_NAME("sleep");
895
Steven Thomasbfe46a02018-02-16 14:27:35 -0800896 const int64_t display_time_est_ns =
897 vsync_timestamp + target_display_->vsync_period_ns;
Corey Tabaka2251d822017-04-20 16:04:07 -0700898 const int64_t now_ns = GetSystemClockNs();
John Bates954796e2017-05-11 11:00:31 -0700899 const int64_t sleep_time_ns = display_time_est_ns - now_ns -
900 post_thread_config_.frame_post_offset_ns;
901 const int64_t wakeup_time_ns =
902 display_time_est_ns - post_thread_config_.frame_post_offset_ns;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800903
904 ATRACE_INT64("sleep_time_ns", sleep_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800905 if (sleep_time_ns > 0) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700906 int error = SleepUntil(wakeup_time_ns);
John Bates46684842017-12-13 15:26:50 -0800907 ALOGE_IF(error < 0 && error != kPostThreadInterrupted,
908 "HardwareComposer::PostThread: Failed to sleep: %s",
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800909 strerror(-error));
John Bates46684842017-12-13 15:26:50 -0800910 // If the sleep was interrupted (error == kPostThreadInterrupted),
911 // we still go through and present this frame because we may have set
912 // layers earlier and we want to flush the Composer's internal command
913 // buffer by continuing through to validate and present.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800914 }
915 }
916
Corey Tabakab3732f02017-09-16 00:58:54 -0700917 {
Steven Thomasbfe46a02018-02-16 14:27:35 -0800918 auto status = composer_callback_->GetVsyncTime(target_display_->id);
Corey Tabakab3732f02017-09-16 00:58:54 -0700919
920 // If we failed to read vsync there might be a problem with the driver.
921 // Since there's nothing we can do just behave as though we didn't get an
922 // updated vsync time and let the prediction continue.
923 const int64_t current_vsync_timestamp =
924 status ? status.get() : last_vsync_timestamp_;
925
926 const bool vsync_delayed =
927 last_vsync_timestamp_ == current_vsync_timestamp;
928 ATRACE_INT("vsync_delayed", vsync_delayed);
929
930 // If vsync was delayed advance the prediction interval and allow the
931 // fence logic in PostLayers() to skip the frame.
932 if (vsync_delayed) {
933 ALOGW(
934 "HardwareComposer::PostThread: VSYNC timestamp did not advance "
935 "since last frame: timestamp=%" PRId64 " prediction_interval=%d",
936 current_vsync_timestamp, vsync_prediction_interval_);
937 vsync_prediction_interval_++;
938 } else {
939 // We have an updated vsync timestamp, reset the prediction interval.
940 last_vsync_timestamp_ = current_vsync_timestamp;
941 vsync_prediction_interval_ = 1;
942 }
943 }
944
Steven Thomasbfe46a02018-02-16 14:27:35 -0800945 PostLayers(target_display_->id);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800946 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800947}
948
Steven Thomasbfe46a02018-02-16 14:27:35 -0800949bool HardwareComposer::UpdateTargetDisplay() {
950 bool target_display_changed = false;
951 auto displays = composer_callback_->GetDisplays();
952 if (displays.external_display_was_hotplugged) {
953 bool was_using_external_display = !target_display_->is_primary;
954 if (was_using_external_display) {
955 // The external display was hotplugged, so make sure to ignore any bad
956 // display errors as we destroy the layers.
957 for (auto& layer: layers_)
958 layer.IgnoreBadDisplayErrorsOnDestroy(true);
959 }
960
961 if (displays.external_display) {
962 // External display was connected
963 external_display_ = GetDisplayParams(composer_.get(),
964 *displays.external_display, /*is_primary*/ false);
965
mamika4f14de2019-08-30 07:27:14 -0700966 ALOGI("External display connected. Switching to external display.");
967 target_display_ = &(*external_display_);
968 target_display_changed = true;
Steven Thomasbfe46a02018-02-16 14:27:35 -0800969 } else {
970 // External display was disconnected
971 external_display_ = std::nullopt;
972 if (was_using_external_display) {
973 ALOGI("External display disconnected. Switching to primary display.");
974 target_display_ = &primary_display_;
975 target_display_changed = true;
976 }
977 }
978 }
979
980 if (target_display_changed) {
981 // If we're switching to the external display, turn the primary display off.
982 if (!target_display_->is_primary) {
983 EnableDisplay(primary_display_, false);
984 }
985 // If we're switching to the primary display, and the external display is
986 // still connected, turn the external display off.
987 else if (target_display_->is_primary && external_display_) {
988 EnableDisplay(*external_display_, false);
989 }
990
991 // Turn the new target display on.
992 EnableDisplay(*target_display_, true);
993
994 // When we switch displays we need to recreate all the layers, so clear the
995 // current list, which will trigger layer recreation.
996 layers_.clear();
997 }
998
999 return target_display_changed;
1000}
1001
Corey Tabaka2251d822017-04-20 16:04:07 -07001002// Checks for changes in the surface stack and updates the layer config to
1003// accomodate the new stack.
Steven Thomasbfe46a02018-02-16 14:27:35 -08001004void HardwareComposer::UpdateLayerConfig() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001005 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces;
Steven Thomas050b2c82017-03-06 11:45:16 -08001006 {
Corey Tabaka2251d822017-04-20 16:04:07 -07001007 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Corey Tabaka2251d822017-04-20 16:04:07 -07001008
Steven Thomasbfe46a02018-02-16 14:27:35 -08001009 if (!surfaces_changed_ && (!layers_.empty() || surfaces_.empty()))
1010 return;
1011
1012 surfaces = surfaces_;
1013 surfaces_changed_ = false;
Steven Thomas050b2c82017-03-06 11:45:16 -08001014 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001015
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001016 ATRACE_NAME("UpdateLayerConfig_HwLayers");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001017
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001018 // Sort the new direct surface list by z-order to determine the relative order
1019 // of the surfaces. This relative order is used for the HWC z-order value to
1020 // insulate VrFlinger and HWC z-order semantics from each other.
1021 std::sort(surfaces.begin(), surfaces.end(), [](const auto& a, const auto& b) {
1022 return a->z_order() < b->z_order();
1023 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001024
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001025 // Prepare a new layer stack, pulling in layers from the previous
1026 // layer stack that are still active and updating their attributes.
1027 std::vector<Layer> layers;
1028 size_t layer_index = 0;
1029 for (const auto& surface : surfaces) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001030 // The bottom layer is opaque, other layers blend.
1031 HWC::BlendMode blending =
1032 layer_index == 0 ? HWC::BlendMode::None : HWC::BlendMode::Coverage;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001033
1034 // Try to find a layer for this surface in the set of active layers.
1035 auto search =
1036 std::lower_bound(layers_.begin(), layers_.end(), surface->surface_id());
1037 const bool found = search != layers_.end() &&
1038 search->GetSurfaceId() == surface->surface_id();
1039 if (found) {
1040 // Update the attributes of the layer that may have changed.
1041 search->SetBlending(blending);
1042 search->SetZOrder(layer_index); // Relative z-order.
1043
1044 // Move the existing layer to the new layer set and remove the empty layer
1045 // object from the current set.
1046 layers.push_back(std::move(*search));
1047 layers_.erase(search);
1048 } else {
1049 // Insert a layer for the new surface.
Steven Thomasbfe46a02018-02-16 14:27:35 -08001050 layers.emplace_back(composer_.get(), *target_display_, surface, blending,
1051 HWC::Composition::Device, layer_index);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001052 }
1053
1054 ALOGI_IF(
1055 TRACE,
1056 "HardwareComposer::UpdateLayerConfig: layer_index=%zu surface_id=%d",
1057 layer_index, layers[layer_index].GetSurfaceId());
1058
1059 layer_index++;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001060 }
1061
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001062 // Sort the new layer stack by ascending surface id.
1063 std::sort(layers.begin(), layers.end());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001064
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001065 // Replace the previous layer set with the new layer set. The destructor of
1066 // the previous set will clean up the remaining Layers that are not moved to
1067 // the new layer set.
1068 layers_ = std::move(layers);
1069
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001070 ALOGD_IF(TRACE, "HardwareComposer::UpdateLayerConfig: %zd active layers",
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001071 layers_.size());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001072}
1073
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001074std::vector<sp<IVsyncCallback>>::const_iterator
1075HardwareComposer::VsyncService::FindCallback(
1076 const sp<IVsyncCallback>& callback) const {
1077 sp<IBinder> binder = IInterface::asBinder(callback);
1078 return std::find_if(callbacks_.cbegin(), callbacks_.cend(),
1079 [&](const sp<IVsyncCallback>& callback) {
1080 return IInterface::asBinder(callback) == binder;
1081 });
1082}
1083
1084status_t HardwareComposer::VsyncService::registerCallback(
1085 const sp<IVsyncCallback> callback) {
1086 std::lock_guard<std::mutex> autolock(mutex_);
1087 if (FindCallback(callback) == callbacks_.cend()) {
1088 callbacks_.push_back(callback);
1089 }
Tianyu Jiang932fb4f2018-11-15 11:09:58 -08001090 return OK;
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001091}
1092
1093status_t HardwareComposer::VsyncService::unregisterCallback(
1094 const sp<IVsyncCallback> callback) {
1095 std::lock_guard<std::mutex> autolock(mutex_);
1096 auto iter = FindCallback(callback);
1097 if (iter != callbacks_.cend()) {
1098 callbacks_.erase(iter);
1099 }
Tianyu Jiang932fb4f2018-11-15 11:09:58 -08001100 return OK;
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001101}
1102
1103void HardwareComposer::VsyncService::OnVsync(int64_t vsync_timestamp) {
1104 ATRACE_NAME("VsyncService::OnVsync");
1105 std::lock_guard<std::mutex> autolock(mutex_);
1106 for (auto iter = callbacks_.begin(); iter != callbacks_.end();) {
1107 if ((*iter)->onVsync(vsync_timestamp) == android::DEAD_OBJECT) {
1108 iter = callbacks_.erase(iter);
1109 } else {
1110 ++iter;
1111 }
1112 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001113}
1114
Steven Thomasb02664d2017-07-26 18:48:28 -07001115Return<void> HardwareComposer::ComposerCallback::onHotplug(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001116 Hwc2::Display display, IComposerCallback::Connection conn) {
Steven Thomasbfe46a02018-02-16 14:27:35 -08001117 std::lock_guard<std::mutex> lock(mutex_);
1118 ALOGI("onHotplug display=%" PRIu64 " conn=%d", display, conn);
1119
1120 bool is_primary = !got_first_hotplug_ || display == primary_display_.id;
1121
Steven Thomas6e8f7062017-11-22 14:15:29 -08001122 // Our first onHotplug callback is always for the primary display.
Steven Thomasbfe46a02018-02-16 14:27:35 -08001123 if (!got_first_hotplug_) {
Steven Thomas6e8f7062017-11-22 14:15:29 -08001124 LOG_ALWAYS_FATAL_IF(conn != IComposerCallback::Connection::CONNECTED,
1125 "Initial onHotplug callback should be primary display connected");
Steven Thomasbfe46a02018-02-16 14:27:35 -08001126 got_first_hotplug_ = true;
1127 } else if (is_primary) {
1128 ALOGE("Ignoring unexpected onHotplug() call for primary display");
1129 return Void();
1130 }
1131
1132 if (conn == IComposerCallback::Connection::CONNECTED) {
1133 if (!is_primary)
1134 external_display_ = DisplayInfo();
1135 DisplayInfo& display_info = is_primary ?
1136 primary_display_ : *external_display_;
1137 display_info.id = display;
Steven Thomas6e8f7062017-11-22 14:15:29 -08001138
Corey Tabakab3732f02017-09-16 00:58:54 -07001139 std::array<char, 1024> buffer;
1140 snprintf(buffer.data(), buffer.size(),
1141 "/sys/class/graphics/fb%" PRIu64 "/vsync_event", display);
1142 if (LocalHandle handle{buffer.data(), O_RDONLY}) {
1143 ALOGI(
1144 "HardwareComposer::ComposerCallback::onHotplug: Driver supports "
1145 "vsync_event node for display %" PRIu64,
1146 display);
Steven Thomasbfe46a02018-02-16 14:27:35 -08001147 display_info.driver_vsync_event_fd = std::move(handle);
Corey Tabakab3732f02017-09-16 00:58:54 -07001148 } else {
1149 ALOGI(
1150 "HardwareComposer::ComposerCallback::onHotplug: Driver does not "
1151 "support vsync_event node for display %" PRIu64,
1152 display);
1153 }
Steven Thomasbfe46a02018-02-16 14:27:35 -08001154 } else if (conn == IComposerCallback::Connection::DISCONNECTED) {
1155 external_display_ = std::nullopt;
Corey Tabakab3732f02017-09-16 00:58:54 -07001156 }
1157
Steven Thomasbfe46a02018-02-16 14:27:35 -08001158 if (!is_primary)
1159 external_display_was_hotplugged_ = true;
1160
Steven Thomasb02664d2017-07-26 18:48:28 -07001161 return Void();
1162}
1163
1164Return<void> HardwareComposer::ComposerCallback::onRefresh(
1165 Hwc2::Display /*display*/) {
1166 return hardware::Void();
1167}
1168
Corey Tabaka451256f2017-08-22 11:59:15 -07001169Return<void> HardwareComposer::ComposerCallback::onVsync(Hwc2::Display display,
1170 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001171 TRACE_FORMAT("vsync_callback|display=%" PRIu64 ";timestamp=%" PRId64 "|",
1172 display, timestamp);
1173 std::lock_guard<std::mutex> lock(mutex_);
Steven Thomasbfe46a02018-02-16 14:27:35 -08001174 DisplayInfo* display_info = GetDisplayInfo(display);
1175 if (display_info) {
Steven Thomasbfe46a02018-02-16 14:27:35 -08001176 display_info->callback_vsync_timestamp = timestamp;
Steven Thomasb02664d2017-07-26 18:48:28 -07001177 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001178 if (primary_display_.id == display && vsync_service_ != nullptr) {
1179 vsync_service_->OnVsync(timestamp);
1180 }
Steven Thomasbfe46a02018-02-16 14:27:35 -08001181
Steven Thomasb02664d2017-07-26 18:48:28 -07001182 return Void();
1183}
1184
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001185void HardwareComposer::ComposerCallback::SetVsyncService(
1186 const sp<VsyncService>& vsync_service) {
1187 std::lock_guard<std::mutex> lock(mutex_);
1188 vsync_service_ = vsync_service;
1189}
1190
Steven Thomasbfe46a02018-02-16 14:27:35 -08001191HardwareComposer::ComposerCallback::Displays
1192HardwareComposer::ComposerCallback::GetDisplays() {
1193 std::lock_guard<std::mutex> lock(mutex_);
1194 Displays displays;
1195 displays.primary_display = primary_display_.id;
1196 if (external_display_)
1197 displays.external_display = external_display_->id;
1198 if (external_display_was_hotplugged_) {
1199 external_display_was_hotplugged_ = false;
1200 displays.external_display_was_hotplugged = true;
1201 }
1202 return displays;
1203}
1204
1205Status<int64_t> HardwareComposer::ComposerCallback::GetVsyncTime(
1206 hwc2_display_t display) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001207 std::lock_guard<std::mutex> autolock(mutex_);
Steven Thomasbfe46a02018-02-16 14:27:35 -08001208 DisplayInfo* display_info = GetDisplayInfo(display);
1209 if (!display_info) {
1210 ALOGW("Attempt to get vsync time for unknown display %" PRIu64, display);
1211 return ErrorStatus(EINVAL);
1212 }
1213
Corey Tabakab3732f02017-09-16 00:58:54 -07001214 // See if the driver supports direct vsync events.
Steven Thomasbfe46a02018-02-16 14:27:35 -08001215 LocalHandle& event_fd = display_info->driver_vsync_event_fd;
Corey Tabakab3732f02017-09-16 00:58:54 -07001216 if (!event_fd) {
1217 // Fall back to returning the last timestamp returned by the vsync
1218 // callback.
Steven Thomasbfe46a02018-02-16 14:27:35 -08001219 return display_info->callback_vsync_timestamp;
Corey Tabakab3732f02017-09-16 00:58:54 -07001220 }
1221
1222 // When the driver supports the vsync_event sysfs node we can use it to
1223 // determine the latest vsync timestamp, even if the HWC callback has been
1224 // delayed.
1225
1226 // The driver returns data in the form "VSYNC=<timestamp ns>".
1227 std::array<char, 32> data;
1228 data.fill('\0');
1229
1230 // Seek back to the beginning of the event file.
1231 int ret = lseek(event_fd.Get(), 0, SEEK_SET);
1232 if (ret < 0) {
1233 const int error = errno;
1234 ALOGE(
1235 "HardwareComposer::ComposerCallback::GetVsyncTime: Failed to seek "
1236 "vsync event fd: %s",
1237 strerror(error));
1238 return ErrorStatus(error);
1239 }
1240
1241 // Read the vsync event timestamp.
1242 ret = read(event_fd.Get(), data.data(), data.size());
1243 if (ret < 0) {
1244 const int error = errno;
1245 ALOGE_IF(error != EAGAIN,
1246 "HardwareComposer::ComposerCallback::GetVsyncTime: Error "
1247 "while reading timestamp: %s",
1248 strerror(error));
1249 return ErrorStatus(error);
1250 }
1251
1252 int64_t timestamp;
1253 ret = sscanf(data.data(), "VSYNC=%" PRIu64,
1254 reinterpret_cast<uint64_t*>(&timestamp));
1255 if (ret < 0) {
1256 const int error = errno;
1257 ALOGE(
1258 "HardwareComposer::ComposerCallback::GetVsyncTime: Error while "
1259 "parsing timestamp: %s",
1260 strerror(error));
1261 return ErrorStatus(error);
1262 }
1263
1264 return {timestamp};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001265}
1266
Steven Thomasbfe46a02018-02-16 14:27:35 -08001267HardwareComposer::ComposerCallback::DisplayInfo*
1268HardwareComposer::ComposerCallback::GetDisplayInfo(hwc2_display_t display) {
1269 if (display == primary_display_.id) {
1270 return &primary_display_;
1271 } else if (external_display_ && display == external_display_->id) {
1272 return &(*external_display_);
1273 }
1274 return nullptr;
1275}
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001276
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001277void Layer::Reset() {
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001278 if (hardware_composer_layer_) {
Steven Thomasbfe46a02018-02-16 14:27:35 -08001279 HWC::Error error =
1280 composer_->destroyLayer(display_params_.id, hardware_composer_layer_);
1281 if (error != HWC::Error::None &&
1282 (!ignore_bad_display_errors_on_destroy_ ||
1283 error != HWC::Error::BadDisplay)) {
1284 ALOGE("destroyLayer() failed for display %" PRIu64 ", layer %" PRIu64
1285 ". error: %s", display_params_.id, hardware_composer_layer_,
1286 error.to_string().c_str());
1287 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001288 hardware_composer_layer_ = 0;
1289 }
1290
Corey Tabaka2251d822017-04-20 16:04:07 -07001291 z_order_ = 0;
1292 blending_ = HWC::BlendMode::None;
Corey Tabaka2251d822017-04-20 16:04:07 -07001293 composition_type_ = HWC::Composition::Invalid;
1294 target_composition_type_ = composition_type_;
1295 source_ = EmptyVariant{};
1296 acquire_fence_.Close();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001297 surface_rect_functions_applied_ = false;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001298 pending_visibility_settings_ = true;
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001299 cached_buffer_map_.clear();
Steven Thomasbfe46a02018-02-16 14:27:35 -08001300 ignore_bad_display_errors_on_destroy_ = false;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001301}
1302
Steven Thomasbfe46a02018-02-16 14:27:35 -08001303Layer::Layer(Hwc2::Composer* composer, const DisplayParams& display_params,
1304 const std::shared_ptr<DirectDisplaySurface>& surface,
1305 HWC::BlendMode blending, HWC::Composition composition_type,
1306 size_t z_order)
1307 : composer_(composer),
1308 display_params_(display_params),
1309 z_order_{z_order},
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001310 blending_{blending},
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001311 target_composition_type_{composition_type},
1312 source_{SourceSurface{surface}} {
1313 CommonLayerSetup();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001314}
1315
Steven Thomasbfe46a02018-02-16 14:27:35 -08001316Layer::Layer(Hwc2::Composer* composer, const DisplayParams& display_params,
1317 const std::shared_ptr<IonBuffer>& buffer, HWC::BlendMode blending,
1318 HWC::Composition composition_type, size_t z_order)
1319 : composer_(composer),
1320 display_params_(display_params),
1321 z_order_{z_order},
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001322 blending_{blending},
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001323 target_composition_type_{composition_type},
1324 source_{SourceBuffer{buffer}} {
1325 CommonLayerSetup();
1326}
1327
1328Layer::~Layer() { Reset(); }
1329
Chih-Hung Hsieh5bc849f2018-09-25 14:21:50 -07001330Layer::Layer(Layer&& other) noexcept { *this = std::move(other); }
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001331
Chih-Hung Hsieh5bc849f2018-09-25 14:21:50 -07001332Layer& Layer::operator=(Layer&& other) noexcept {
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001333 if (this != &other) {
1334 Reset();
1335 using std::swap;
Steven Thomasbfe46a02018-02-16 14:27:35 -08001336 swap(composer_, other.composer_);
1337 swap(display_params_, other.display_params_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001338 swap(hardware_composer_layer_, other.hardware_composer_layer_);
1339 swap(z_order_, other.z_order_);
1340 swap(blending_, other.blending_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001341 swap(composition_type_, other.composition_type_);
1342 swap(target_composition_type_, other.target_composition_type_);
1343 swap(source_, other.source_);
1344 swap(acquire_fence_, other.acquire_fence_);
1345 swap(surface_rect_functions_applied_,
1346 other.surface_rect_functions_applied_);
1347 swap(pending_visibility_settings_, other.pending_visibility_settings_);
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001348 swap(cached_buffer_map_, other.cached_buffer_map_);
Steven Thomasbfe46a02018-02-16 14:27:35 -08001349 swap(ignore_bad_display_errors_on_destroy_,
1350 other.ignore_bad_display_errors_on_destroy_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001351 }
1352 return *this;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001353}
1354
Corey Tabaka2251d822017-04-20 16:04:07 -07001355void Layer::UpdateBuffer(const std::shared_ptr<IonBuffer>& buffer) {
1356 if (source_.is<SourceBuffer>())
1357 std::get<SourceBuffer>(source_) = {buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001358}
1359
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001360void Layer::SetBlending(HWC::BlendMode blending) {
1361 if (blending_ != blending) {
1362 blending_ = blending;
1363 pending_visibility_settings_ = true;
1364 }
1365}
1366
1367void Layer::SetZOrder(size_t z_order) {
1368 if (z_order_ != z_order) {
1369 z_order_ = z_order;
1370 pending_visibility_settings_ = true;
1371 }
1372}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001373
1374IonBuffer* Layer::GetBuffer() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001375 struct Visitor {
1376 IonBuffer* operator()(SourceSurface& source) { return source.GetBuffer(); }
1377 IonBuffer* operator()(SourceBuffer& source) { return source.GetBuffer(); }
1378 IonBuffer* operator()(EmptyVariant) { return nullptr; }
1379 };
1380 return source_.Visit(Visitor{});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001381}
1382
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001383void Layer::UpdateVisibilitySettings() {
1384 if (pending_visibility_settings_) {
1385 pending_visibility_settings_ = false;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001386
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001387 HWC::Error error;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001388
1389 error = composer_->setLayerBlendMode(
Steven Thomasbfe46a02018-02-16 14:27:35 -08001390 display_params_.id, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001391 blending_.cast<Hwc2::IComposerClient::BlendMode>());
1392 ALOGE_IF(error != HWC::Error::None,
1393 "Layer::UpdateLayerSettings: Error setting layer blend mode: %s",
1394 error.to_string().c_str());
1395
Steven Thomasbfe46a02018-02-16 14:27:35 -08001396 error = composer_->setLayerZOrder(display_params_.id,
1397 hardware_composer_layer_, z_order_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001398 ALOGE_IF(error != HWC::Error::None,
1399 "Layer::UpdateLayerSettings: Error setting z_ order: %s",
1400 error.to_string().c_str());
1401 }
1402}
1403
1404void Layer::UpdateLayerSettings() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001405 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001406
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001407 UpdateVisibilitySettings();
1408
Corey Tabaka2251d822017-04-20 16:04:07 -07001409 // TODO(eieio): Use surface attributes or some other mechanism to control
1410 // the layer display frame.
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001411 error = composer_->setLayerDisplayFrame(
Steven Thomasbfe46a02018-02-16 14:27:35 -08001412 display_params_.id, hardware_composer_layer_,
1413 {0, 0, display_params_.width, display_params_.height});
Corey Tabaka2251d822017-04-20 16:04:07 -07001414 ALOGE_IF(error != HWC::Error::None,
1415 "Layer::UpdateLayerSettings: Error setting layer display frame: %s",
1416 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001417
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001418 error = composer_->setLayerVisibleRegion(
Steven Thomasbfe46a02018-02-16 14:27:35 -08001419 display_params_.id, hardware_composer_layer_,
1420 {{0, 0, display_params_.width, display_params_.height}});
Corey Tabaka2251d822017-04-20 16:04:07 -07001421 ALOGE_IF(error != HWC::Error::None,
1422 "Layer::UpdateLayerSettings: Error setting layer visible region: %s",
1423 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001424
Steven Thomasbfe46a02018-02-16 14:27:35 -08001425 error = composer_->setLayerPlaneAlpha(display_params_.id,
1426 hardware_composer_layer_, 1.0f);
Corey Tabaka2251d822017-04-20 16:04:07 -07001427 ALOGE_IF(error != HWC::Error::None,
1428 "Layer::UpdateLayerSettings: Error setting layer plane alpha: %s",
1429 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001430}
1431
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001432void Layer::CommonLayerSetup() {
Steven Thomasbfe46a02018-02-16 14:27:35 -08001433 HWC::Error error = composer_->createLayer(display_params_.id,
Steven Thomas6e8f7062017-11-22 14:15:29 -08001434 &hardware_composer_layer_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001435 ALOGE_IF(error != HWC::Error::None,
1436 "Layer::CommonLayerSetup: Failed to create layer on primary "
1437 "display: %s",
1438 error.to_string().c_str());
1439 UpdateLayerSettings();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001440}
1441
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001442bool Layer::CheckAndUpdateCachedBuffer(std::size_t slot, int buffer_id) {
1443 auto search = cached_buffer_map_.find(slot);
1444 if (search != cached_buffer_map_.end() && search->second == buffer_id)
1445 return true;
1446
1447 // Assign or update the buffer slot.
1448 if (buffer_id >= 0)
1449 cached_buffer_map_[slot] = buffer_id;
1450 return false;
1451}
1452
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001453void Layer::Prepare() {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001454 int right, bottom, id;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -04001455 sp<GraphicBuffer> handle;
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001456 std::size_t slot;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001457
Corey Tabaka2251d822017-04-20 16:04:07 -07001458 // Acquire the next buffer according to the type of source.
1459 IfAnyOf<SourceSurface, SourceBuffer>::Call(&source_, [&](auto& source) {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001460 std::tie(right, bottom, id, handle, acquire_fence_, slot) =
1461 source.Acquire();
Corey Tabaka2251d822017-04-20 16:04:07 -07001462 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001463
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001464 TRACE_FORMAT("Layer::Prepare|buffer_id=%d;slot=%zu|", id, slot);
1465
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001466 // Update any visibility (blending, z-order) changes that occurred since
1467 // last prepare.
1468 UpdateVisibilitySettings();
1469
1470 // When a layer is first setup there may be some time before the first
1471 // buffer arrives. Setup the HWC layer as a solid color to stall for time
1472 // until the first buffer arrives. Once the first buffer arrives there will
1473 // always be a buffer for the frame even if it is old.
Corey Tabaka2251d822017-04-20 16:04:07 -07001474 if (!handle.get()) {
1475 if (composition_type_ == HWC::Composition::Invalid) {
1476 composition_type_ = HWC::Composition::SolidColor;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001477 composer_->setLayerCompositionType(
Steven Thomasbfe46a02018-02-16 14:27:35 -08001478 display_params_.id, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001479 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1480 Hwc2::IComposerClient::Color layer_color = {0, 0, 0, 0};
Steven Thomasbfe46a02018-02-16 14:27:35 -08001481 composer_->setLayerColor(display_params_.id, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001482 layer_color);
Corey Tabaka2251d822017-04-20 16:04:07 -07001483 } else {
1484 // The composition type is already set. Nothing else to do until a
1485 // buffer arrives.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001486 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001487 } else {
Corey Tabaka2251d822017-04-20 16:04:07 -07001488 if (composition_type_ != target_composition_type_) {
1489 composition_type_ = target_composition_type_;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001490 composer_->setLayerCompositionType(
Steven Thomasbfe46a02018-02-16 14:27:35 -08001491 display_params_.id, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001492 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1493 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001494
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001495 // See if the HWC cache already has this buffer.
1496 const bool cached = CheckAndUpdateCachedBuffer(slot, id);
1497 if (cached)
1498 handle = nullptr;
1499
Corey Tabaka2251d822017-04-20 16:04:07 -07001500 HWC::Error error{HWC::Error::None};
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001501 error =
Steven Thomasbfe46a02018-02-16 14:27:35 -08001502 composer_->setLayerBuffer(display_params_.id, hardware_composer_layer_,
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001503 slot, handle, acquire_fence_.Get());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001504
Corey Tabaka2251d822017-04-20 16:04:07 -07001505 ALOGE_IF(error != HWC::Error::None,
1506 "Layer::Prepare: Error setting layer buffer: %s",
1507 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001508
Corey Tabaka2251d822017-04-20 16:04:07 -07001509 if (!surface_rect_functions_applied_) {
1510 const float float_right = right;
1511 const float float_bottom = bottom;
Steven Thomasbfe46a02018-02-16 14:27:35 -08001512 error = composer_->setLayerSourceCrop(display_params_.id,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001513 hardware_composer_layer_,
1514 {0, 0, float_right, float_bottom});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001515
Corey Tabaka2251d822017-04-20 16:04:07 -07001516 ALOGE_IF(error != HWC::Error::None,
1517 "Layer::Prepare: Error setting layer source crop: %s",
1518 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001519
Corey Tabaka2251d822017-04-20 16:04:07 -07001520 surface_rect_functions_applied_ = true;
1521 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001522 }
1523}
1524
1525void Layer::Finish(int release_fence_fd) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001526 IfAnyOf<SourceSurface, SourceBuffer>::Call(
1527 &source_, [release_fence_fd](auto& source) {
1528 source.Finish(LocalHandle(release_fence_fd));
1529 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001530}
1531
Corey Tabaka2251d822017-04-20 16:04:07 -07001532void Layer::Drop() { acquire_fence_.Close(); }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001533
1534} // namespace dvr
1535} // namespace android