blob: 57a77cffd40c53f6b2101d201294b673f2c8e571 [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";
50
Luke Song4b788322017-03-24 14:17:31 -070051const char kRightEyeOffsetProperty[] = "dvr.right_eye_offset_ns";
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080052
Steven Thomasbfe46a02018-02-16 14:27:35 -080053const char kUseExternalDisplayProperty[] = "persist.vr.use_external_display";
54
Steven Thomasdfde8fa2018-04-19 16:00:58 -070055// Surface flinger uses "VSYNC-sf" and "VSYNC-app" for its version of these
56// events. Name ours similarly.
57const char kVsyncTraceEventName[] = "VSYNC-vrflinger";
58
Steven Thomasaf336272018-01-04 17:36:47 -080059// How long to wait after boot finishes before we turn the display off.
60constexpr int kBootFinishedDisplayOffTimeoutSec = 10;
61
Steven Thomasbfe46a02018-02-16 14:27:35 -080062constexpr int kDefaultDisplayWidth = 1920;
63constexpr int kDefaultDisplayHeight = 1080;
64constexpr int64_t kDefaultVsyncPeriodNs = 16666667;
65// Hardware composer reports dpi as dots per thousand inches (dpi * 1000).
66constexpr int kDefaultDpi = 400000;
67
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080068// Get time offset from a vsync to when the pose for that vsync should be
69// predicted out to. For example, if scanout gets halfway through the frame
70// at the halfway point between vsyncs, then this could be half the period.
71// With global shutter displays, this should be changed to the offset to when
72// illumination begins. Low persistence adds a frame of latency, so we predict
73// to the center of the next frame.
74inline int64_t GetPosePredictionTimeOffset(int64_t vsync_period_ns) {
75 return (vsync_period_ns * 150) / 100;
76}
77
Corey Tabaka2251d822017-04-20 16:04:07 -070078// Attempts to set the scheduler class and partiton for the current thread.
79// Returns true on success or false on failure.
80bool SetThreadPolicy(const std::string& scheduler_class,
81 const std::string& partition) {
82 int error = dvrSetSchedulerClass(0, scheduler_class.c_str());
83 if (error < 0) {
84 ALOGE(
85 "SetThreadPolicy: Failed to set scheduler class \"%s\" for "
86 "thread_id=%d: %s",
87 scheduler_class.c_str(), gettid(), strerror(-error));
88 return false;
89 }
90 error = dvrSetCpuPartition(0, partition.c_str());
91 if (error < 0) {
92 ALOGE(
93 "SetThreadPolicy: Failed to set cpu partiton \"%s\" for thread_id=%d: "
94 "%s",
95 partition.c_str(), gettid(), strerror(-error));
96 return false;
97 }
98 return true;
99}
100
Corey Tabakab3732f02017-09-16 00:58:54 -0700101// Utility to generate scoped tracers with arguments.
102// TODO(eieio): Move/merge this into utils/Trace.h?
103class TraceArgs {
104 public:
105 template <typename... Args>
Chih-Hung Hsieh79e7f1b2018-12-20 15:53:43 -0800106 explicit TraceArgs(const char* format, Args&&... args) {
Corey Tabakab3732f02017-09-16 00:58:54 -0700107 std::array<char, 1024> buffer;
108 snprintf(buffer.data(), buffer.size(), format, std::forward<Args>(args)...);
109 atrace_begin(ATRACE_TAG, buffer.data());
110 }
111
112 ~TraceArgs() { atrace_end(ATRACE_TAG); }
113
114 private:
115 TraceArgs(const TraceArgs&) = delete;
116 void operator=(const TraceArgs&) = delete;
117};
118
119// Macro to define a scoped tracer with arguments. Uses PASTE(x, y) macro
120// defined in utils/Trace.h.
121#define TRACE_FORMAT(format, ...) \
122 TraceArgs PASTE(__tracer, __LINE__) { format, ##__VA_ARGS__ }
123
Steven Thomasbfe46a02018-02-16 14:27:35 -0800124// Returns "primary" or "external". Useful for writing more readable logs.
125const char* GetDisplayName(bool is_primary) {
126 return is_primary ? "primary" : "external";
127}
128
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800129} // anonymous namespace
130
Corey Tabaka2251d822017-04-20 16:04:07 -0700131HardwareComposer::HardwareComposer()
Steven Thomasb02664d2017-07-26 18:48:28 -0700132 : initialized_(false), request_display_callback_(nullptr) {}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800133
134HardwareComposer::~HardwareComposer(void) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700135 UpdatePostThreadState(PostThreadState::Quit, true);
136 if (post_thread_.joinable())
Steven Thomas050b2c82017-03-06 11:45:16 -0800137 post_thread_.join();
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700138 composer_callback_->SetVsyncService(nullptr);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800139}
140
Steven Thomasb02664d2017-07-26 18:48:28 -0700141bool HardwareComposer::Initialize(
Steven Thomas6e8f7062017-11-22 14:15:29 -0800142 Hwc2::Composer* composer, hwc2_display_t primary_display_id,
143 RequestDisplayCallback request_display_callback) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800144 if (initialized_) {
145 ALOGE("HardwareComposer::Initialize: already initialized.");
146 return false;
147 }
148
Steven Thomasb02664d2017-07-26 18:48:28 -0700149 request_display_callback_ = request_display_callback;
150
Steven Thomasbfe46a02018-02-16 14:27:35 -0800151 primary_display_ = GetDisplayParams(composer, primary_display_id, true);
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700152
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700153 vsync_service_ = new VsyncService;
154 sp<IServiceManager> sm(defaultServiceManager());
155 auto result = sm->addService(String16(VsyncService::GetServiceName()),
156 vsync_service_, false);
157 LOG_ALWAYS_FATAL_IF(result != android::OK,
158 "addService(%s) failed", VsyncService::GetServiceName());
159
Corey Tabaka2251d822017-04-20 16:04:07 -0700160 post_thread_event_fd_.Reset(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
Steven Thomas050b2c82017-03-06 11:45:16 -0800161 LOG_ALWAYS_FATAL_IF(
Corey Tabaka2251d822017-04-20 16:04:07 -0700162 !post_thread_event_fd_,
Steven Thomas050b2c82017-03-06 11:45:16 -0800163 "HardwareComposer: Failed to create interrupt event fd : %s",
164 strerror(errno));
165
166 post_thread_ = std::thread(&HardwareComposer::PostThread, this);
167
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800168 initialized_ = true;
169
170 return initialized_;
171}
172
Steven Thomas050b2c82017-03-06 11:45:16 -0800173void HardwareComposer::Enable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700174 UpdatePostThreadState(PostThreadState::Suspended, false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800175}
176
177void HardwareComposer::Disable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700178 UpdatePostThreadState(PostThreadState::Suspended, true);
Steven Thomas7f8761e2018-01-18 18:49:59 -0800179
180 std::unique_lock<std::mutex> lock(post_thread_mutex_);
181 post_thread_ready_.wait(lock, [this] {
182 return !post_thread_resumed_;
183 });
Steven Thomas050b2c82017-03-06 11:45:16 -0800184}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800185
Steven Thomasaf336272018-01-04 17:36:47 -0800186void HardwareComposer::OnBootFinished() {
187 std::lock_guard<std::mutex> lock(post_thread_mutex_);
188 if (boot_finished_)
189 return;
190 boot_finished_ = true;
191 post_thread_wait_.notify_one();
Steven Thomasaf336272018-01-04 17:36:47 -0800192}
193
Corey Tabaka2251d822017-04-20 16:04:07 -0700194// Update the post thread quiescent state based on idle and suspended inputs.
195void HardwareComposer::UpdatePostThreadState(PostThreadStateType state,
196 bool suspend) {
197 std::unique_lock<std::mutex> lock(post_thread_mutex_);
198
199 // Update the votes in the state variable before evaluating the effective
200 // quiescent state. Any bits set in post_thread_state_ indicate that the post
201 // thread should be suspended.
202 if (suspend) {
203 post_thread_state_ |= state;
204 } else {
205 post_thread_state_ &= ~state;
206 }
207
208 const bool quit = post_thread_state_ & PostThreadState::Quit;
209 const bool effective_suspend = post_thread_state_ != PostThreadState::Active;
210 if (quit) {
211 post_thread_quiescent_ = true;
212 eventfd_write(post_thread_event_fd_.Get(), 1);
213 post_thread_wait_.notify_one();
214 } else if (effective_suspend && !post_thread_quiescent_) {
215 post_thread_quiescent_ = true;
216 eventfd_write(post_thread_event_fd_.Get(), 1);
217 } else if (!effective_suspend && post_thread_quiescent_) {
218 post_thread_quiescent_ = false;
219 eventfd_t value;
220 eventfd_read(post_thread_event_fd_.Get(), &value);
221 post_thread_wait_.notify_one();
222 }
Steven Thomas050b2c82017-03-06 11:45:16 -0800223}
Steven Thomas282a5ed2017-02-07 18:07:01 -0800224
Steven Thomasbfe46a02018-02-16 14:27:35 -0800225void HardwareComposer::CreateComposer() {
226 if (composer_)
227 return;
228 composer_.reset(new Hwc2::impl::Composer("default"));
229 composer_callback_ = new ComposerCallback;
230 composer_->registerCallback(composer_callback_);
231 LOG_ALWAYS_FATAL_IF(!composer_callback_->GotFirstHotplug(),
232 "Registered composer callback but didn't get hotplug for primary"
233 " display");
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700234 composer_callback_->SetVsyncService(vsync_service_);
Steven Thomasbfe46a02018-02-16 14:27:35 -0800235}
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700236
Steven Thomasbfe46a02018-02-16 14:27:35 -0800237void HardwareComposer::OnPostThreadResumed() {
238 ALOGI("OnPostThreadResumed");
239 EnableDisplay(*target_display_, true);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800240
Steven Thomas050b2c82017-03-06 11:45:16 -0800241 // Trigger target-specific performance mode change.
242 property_set(kDvrPerformanceProperty, "performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800243}
244
Steven Thomas050b2c82017-03-06 11:45:16 -0800245void HardwareComposer::OnPostThreadPaused() {
Steven Thomasbfe46a02018-02-16 14:27:35 -0800246 ALOGI("OnPostThreadPaused");
Corey Tabaka2251d822017-04-20 16:04:07 -0700247 retire_fence_fds_.clear();
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700248 layers_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800249
Steven Thomasbfe46a02018-02-16 14:27:35 -0800250 // Phones create a new composer client on resume and destroy it on pause.
Inseob Kim15791ea2020-07-31 19:29:32 +0900251 if (composer_callback_ != nullptr) {
252 composer_callback_->SetVsyncService(nullptr);
253 composer_callback_ = nullptr;
Corey Tabaka451256f2017-08-22 11:59:15 -0700254 }
Inseob Kim15791ea2020-07-31 19:29:32 +0900255 composer_.reset(nullptr);
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700256
Steven Thomas050b2c82017-03-06 11:45:16 -0800257 // Trigger target-specific performance mode change.
258 property_set(kDvrPerformanceProperty, "idle");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800259}
260
Steven Thomasaf336272018-01-04 17:36:47 -0800261bool HardwareComposer::PostThreadCondWait(std::unique_lock<std::mutex>& lock,
262 int timeout_sec,
263 const std::function<bool()>& pred) {
264 auto pred_with_quit = [&] {
265 return pred() || (post_thread_state_ & PostThreadState::Quit);
266 };
267 if (timeout_sec >= 0) {
268 post_thread_wait_.wait_for(lock, std::chrono::seconds(timeout_sec),
269 pred_with_quit);
270 } else {
271 post_thread_wait_.wait(lock, pred_with_quit);
272 }
273 if (post_thread_state_ & PostThreadState::Quit) {
274 ALOGI("HardwareComposer::PostThread: Quitting.");
275 return true;
276 }
277 return false;
278}
279
Corey Tabaka2251d822017-04-20 16:04:07 -0700280HWC::Error HardwareComposer::Validate(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800281 uint32_t num_types;
282 uint32_t num_requests;
Corey Tabaka2251d822017-04-20 16:04:07 -0700283 HWC::Error error =
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700284 composer_->validateDisplay(display, &num_types, &num_requests);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800285
286 if (error == HWC2_ERROR_HAS_CHANGES) {
Steven Thomasbfe46a02018-02-16 14:27:35 -0800287 ALOGE("Hardware composer has requested composition changes, "
288 "which we don't support.");
289 // Accept the changes anyway and see if we can get something on the screen.
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700290 error = composer_->acceptDisplayChanges(display);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800291 }
292
293 return error;
294}
295
Steven Thomasbfe46a02018-02-16 14:27:35 -0800296bool HardwareComposer::EnableVsync(const DisplayParams& display, bool enabled) {
297 HWC::Error error = composer_->setVsyncEnabled(display.id,
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800298 (Hwc2::IComposerClient::Vsync)(enabled ? HWC2_VSYNC_ENABLE
299 : HWC2_VSYNC_DISABLE));
Steven Thomasbfe46a02018-02-16 14:27:35 -0800300 if (error != HWC::Error::None) {
301 ALOGE("Error attempting to %s vsync on %s display: %s",
302 enabled ? "enable" : "disable", GetDisplayName(display.is_primary),
303 error.to_string().c_str());
304 }
305 return error == HWC::Error::None;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800306}
307
Steven Thomasbfe46a02018-02-16 14:27:35 -0800308bool HardwareComposer::SetPowerMode(const DisplayParams& display, bool active) {
309 ALOGI("Turning %s display %s", GetDisplayName(display.is_primary),
310 active ? "on" : "off");
Corey Tabaka451256f2017-08-22 11:59:15 -0700311 HWC::PowerMode power_mode = active ? HWC::PowerMode::On : HWC::PowerMode::Off;
Steven Thomasbfe46a02018-02-16 14:27:35 -0800312 HWC::Error error = composer_->setPowerMode(display.id,
Steven Thomas6e8f7062017-11-22 14:15:29 -0800313 power_mode.cast<Hwc2::IComposerClient::PowerMode>());
Steven Thomasbfe46a02018-02-16 14:27:35 -0800314 if (error != HWC::Error::None) {
315 ALOGE("Error attempting to turn %s display %s: %s",
316 GetDisplayName(display.is_primary), active ? "on" : "off",
317 error.to_string().c_str());
318 }
319 return error == HWC::Error::None;
320}
321
322bool HardwareComposer::EnableDisplay(const DisplayParams& display,
323 bool enabled) {
324 bool power_result;
325 bool vsync_result;
326 // When turning a display on, we set the power state then set vsync. When
327 // turning a display off we do it in the opposite order.
328 if (enabled) {
329 power_result = SetPowerMode(display, enabled);
330 vsync_result = EnableVsync(display, enabled);
331 } else {
332 vsync_result = EnableVsync(display, enabled);
333 power_result = SetPowerMode(display, enabled);
334 }
335 return power_result && vsync_result;
Corey Tabaka451256f2017-08-22 11:59:15 -0700336}
337
Corey Tabaka2251d822017-04-20 16:04:07 -0700338HWC::Error HardwareComposer::Present(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800339 int32_t present_fence;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700340 HWC::Error error = composer_->presentDisplay(display, &present_fence);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800341
342 // According to the documentation, this fence is signaled at the time of
343 // vsync/DMA for physical displays.
Corey Tabaka2251d822017-04-20 16:04:07 -0700344 if (error == HWC::Error::None) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800345 retire_fence_fds_.emplace_back(present_fence);
346 } else {
347 ATRACE_INT("HardwareComposer: PresentResult", error);
348 }
349
350 return error;
351}
352
Steven Thomasbfe46a02018-02-16 14:27:35 -0800353DisplayParams HardwareComposer::GetDisplayParams(
354 Hwc2::Composer* composer, hwc2_display_t display, bool is_primary) {
355 DisplayParams params;
356 params.id = display;
357 params.is_primary = is_primary;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800358
Steven Thomasbfe46a02018-02-16 14:27:35 -0800359 Hwc2::Config config;
360 HWC::Error error = composer->getActiveConfig(display, &config);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800361
Steven Thomasbfe46a02018-02-16 14:27:35 -0800362 if (error == HWC::Error::None) {
363 auto get_attr = [&](hwc2_attribute_t attr, const char* attr_name)
364 -> std::optional<int32_t> {
365 int32_t val;
366 HWC::Error error = composer->getDisplayAttribute(
367 display, config, (Hwc2::IComposerClient::Attribute)attr, &val);
368 if (error != HWC::Error::None) {
369 ALOGE("Failed to get %s display attr %s: %s",
370 GetDisplayName(is_primary), attr_name,
371 error.to_string().c_str());
372 return std::nullopt;
373 }
374 return val;
375 };
376
377 auto width = get_attr(HWC2_ATTRIBUTE_WIDTH, "width");
378 auto height = get_attr(HWC2_ATTRIBUTE_HEIGHT, "height");
379
380 if (width && height) {
381 params.width = *width;
382 params.height = *height;
383 } else {
384 ALOGI("Failed to get width and/or height for %s display. Using default"
385 " size %dx%d.", GetDisplayName(is_primary), kDefaultDisplayWidth,
386 kDefaultDisplayHeight);
387 params.width = kDefaultDisplayWidth;
388 params.height = kDefaultDisplayHeight;
389 }
390
391 auto vsync_period = get_attr(HWC2_ATTRIBUTE_VSYNC_PERIOD, "vsync period");
392 if (vsync_period) {
393 params.vsync_period_ns = *vsync_period;
394 } else {
395 ALOGI("Failed to get vsync period for %s display. Using default vsync"
396 " period %.2fms", GetDisplayName(is_primary),
397 static_cast<float>(kDefaultVsyncPeriodNs) / 1000000);
398 params.vsync_period_ns = kDefaultVsyncPeriodNs;
399 }
400
401 auto dpi_x = get_attr(HWC2_ATTRIBUTE_DPI_X, "DPI X");
402 auto dpi_y = get_attr(HWC2_ATTRIBUTE_DPI_Y, "DPI Y");
403 if (dpi_x && dpi_y) {
404 params.dpi.x = *dpi_x;
405 params.dpi.y = *dpi_y;
406 } else {
407 ALOGI("Failed to get dpi_x and/or dpi_y for %s display. Using default"
408 " dpi %d.", GetDisplayName(is_primary), kDefaultDpi);
409 params.dpi.x = kDefaultDpi;
410 params.dpi.y = kDefaultDpi;
411 }
412 } else {
413 ALOGE("HardwareComposer: Failed to get current %s display config: %d."
414 " Using default display values.",
415 GetDisplayName(is_primary), error.value);
416 params.width = kDefaultDisplayWidth;
417 params.height = kDefaultDisplayHeight;
418 params.dpi.x = kDefaultDpi;
419 params.dpi.y = kDefaultDpi;
420 params.vsync_period_ns = kDefaultVsyncPeriodNs;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800421 }
422
Steven Thomasbfe46a02018-02-16 14:27:35 -0800423 ALOGI(
424 "HardwareComposer: %s display attributes: width=%d height=%d "
425 "vsync_period_ns=%d DPI=%dx%d",
426 GetDisplayName(is_primary),
427 params.width,
428 params.height,
429 params.vsync_period_ns,
430 params.dpi.x,
431 params.dpi.y);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800432
Steven Thomasbfe46a02018-02-16 14:27:35 -0800433 return params;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800434}
435
Corey Tabaka0b485c92017-05-19 12:02:58 -0700436std::string HardwareComposer::Dump() {
437 std::unique_lock<std::mutex> lock(post_thread_mutex_);
438 std::ostringstream stream;
439
Steven Thomasbfe46a02018-02-16 14:27:35 -0800440 auto print_display_metrics = [&](const DisplayParams& params) {
441 stream << GetDisplayName(params.is_primary)
442 << " display metrics: " << params.width << "x"
443 << params.height << " " << (params.dpi.x / 1000.0)
444 << "x" << (params.dpi.y / 1000.0) << " dpi @ "
445 << (1000000000.0 / params.vsync_period_ns) << " Hz"
446 << std::endl;
447 };
448
449 print_display_metrics(primary_display_);
450 if (external_display_)
451 print_display_metrics(*external_display_);
Corey Tabaka0b485c92017-05-19 12:02:58 -0700452
453 stream << "Post thread resumed: " << post_thread_resumed_ << std::endl;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700454 stream << "Active layers: " << layers_.size() << std::endl;
Corey Tabaka0b485c92017-05-19 12:02:58 -0700455 stream << std::endl;
456
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700457 for (size_t i = 0; i < layers_.size(); i++) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700458 stream << "Layer " << i << ":";
459 stream << " type=" << layers_[i].GetCompositionType().to_string();
460 stream << " surface_id=" << layers_[i].GetSurfaceId();
461 stream << " buffer_id=" << layers_[i].GetBufferId();
462 stream << std::endl;
463 }
464 stream << std::endl;
465
466 if (post_thread_resumed_) {
467 stream << "Hardware Composer Debug Info:" << std::endl;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700468 stream << composer_->dumpDebugInfo();
Corey Tabaka0b485c92017-05-19 12:02:58 -0700469 }
470
471 return stream.str();
472}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800473
Steven Thomasbfe46a02018-02-16 14:27:35 -0800474void HardwareComposer::PostLayers(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800475 ATRACE_NAME("HardwareComposer::PostLayers");
476
477 // Setup the hardware composer layers with current buffers.
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700478 for (auto& layer : layers_) {
479 layer.Prepare();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800480 }
481
482 // Now that we have taken in a frame from the application, we have a chance
483 // to drop the frame before passing the frame along to HWC.
484 // If the display driver has become backed up, we detect it here and then
485 // react by skipping this frame to catch up latency.
486 while (!retire_fence_fds_.empty() &&
487 (!retire_fence_fds_.front() ||
488 sync_wait(retire_fence_fds_.front().Get(), 0) == 0)) {
489 // There are only 2 fences in here, no performance problem to shift the
490 // array of ints.
491 retire_fence_fds_.erase(retire_fence_fds_.begin());
492 }
493
George Burgess IV353a6f62017-06-26 17:13:09 -0700494 const bool is_fence_pending = static_cast<int32_t>(retire_fence_fds_.size()) >
John Bates954796e2017-05-11 11:00:31 -0700495 post_thread_config_.allowed_pending_fence_count;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800496
Corey Tabakab3732f02017-09-16 00:58:54 -0700497 if (is_fence_pending) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800498 ATRACE_INT("frame_skip_count", ++frame_skip_count_);
499
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800500 ALOGW_IF(is_fence_pending,
501 "Warning: dropping a frame to catch up with HWC (pending = %zd)",
502 retire_fence_fds_.size());
503
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700504 for (auto& layer : layers_) {
505 layer.Drop();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800506 }
507 return;
508 } else {
509 // Make the transition more obvious in systrace when the frame skip happens
510 // above.
511 ATRACE_INT("frame_skip_count", 0);
512 }
513
Corey Tabaka89bbefc2017-06-06 16:14:21 -0700514#if TRACE > 1
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700515 for (size_t i = 0; i < layers_.size(); i++) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700516 ALOGI("HardwareComposer::PostLayers: layer=%zu buffer_id=%d composition=%s",
517 i, layers_[i].GetBufferId(),
Corey Tabaka2251d822017-04-20 16:04:07 -0700518 layers_[i].GetCompositionType().to_string().c_str());
Corey Tabaka0b485c92017-05-19 12:02:58 -0700519 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800520#endif
521
Steven Thomasbfe46a02018-02-16 14:27:35 -0800522 HWC::Error error = Validate(display);
John Bates46684842017-12-13 15:26:50 -0800523 if (error != HWC::Error::None) {
Steven Thomasbfe46a02018-02-16 14:27:35 -0800524 ALOGE("HardwareComposer::PostLayers: Validate failed: %s display=%" PRIu64,
525 error.to_string().c_str(), display);
John Bates46684842017-12-13 15:26:50 -0800526 return;
527 }
528
Steven Thomasbfe46a02018-02-16 14:27:35 -0800529 error = Present(display);
Corey Tabaka2251d822017-04-20 16:04:07 -0700530 if (error != HWC::Error::None) {
531 ALOGE("HardwareComposer::PostLayers: Present failed: %s",
532 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800533 return;
534 }
535
536 std::vector<Hwc2::Layer> out_layers;
537 std::vector<int> out_fences;
Steven Thomasbfe46a02018-02-16 14:27:35 -0800538 error = composer_->getReleaseFences(display,
Steven Thomas6e8f7062017-11-22 14:15:29 -0800539 &out_layers, &out_fences);
Corey Tabaka2251d822017-04-20 16:04:07 -0700540 ALOGE_IF(error != HWC::Error::None,
541 "HardwareComposer::PostLayers: Failed to get release fences: %s",
542 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800543
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700544 // Perform post-frame bookkeeping.
Corey Tabaka2251d822017-04-20 16:04:07 -0700545 uint32_t num_elements = out_layers.size();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800546 for (size_t i = 0; i < num_elements; ++i) {
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700547 for (auto& layer : layers_) {
548 if (layer.GetLayerHandle() == out_layers[i]) {
549 layer.Finish(out_fences[i]);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800550 }
551 }
552 }
553}
554
Steven Thomas050b2c82017-03-06 11:45:16 -0800555void HardwareComposer::SetDisplaySurfaces(
Corey Tabaka2251d822017-04-20 16:04:07 -0700556 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces) {
Jin Qian7480c062017-03-21 00:04:15 +0000557 ALOGI("HardwareComposer::SetDisplaySurfaces: surface count=%zd",
558 surfaces.size());
Corey Tabaka2251d822017-04-20 16:04:07 -0700559 const bool display_idle = surfaces.size() == 0;
560 {
561 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Steven Thomasbfe46a02018-02-16 14:27:35 -0800562 surfaces_ = std::move(surfaces);
563 surfaces_changed_ = true;
Corey Tabaka2251d822017-04-20 16:04:07 -0700564 }
565
Inseob Kim15791ea2020-07-31 19:29:32 +0900566 if (request_display_callback_)
Steven Thomas2ddf5672017-06-15 11:38:40 -0700567 request_display_callback_(!display_idle);
568
Corey Tabaka2251d822017-04-20 16:04:07 -0700569 // Set idle state based on whether there are any surfaces to handle.
570 UpdatePostThreadState(PostThreadState::Idle, display_idle);
Steven Thomas050b2c82017-03-06 11:45:16 -0800571}
Jin Qian7480c062017-03-21 00:04:15 +0000572
John Bates954796e2017-05-11 11:00:31 -0700573int HardwareComposer::OnNewGlobalBuffer(DvrGlobalBufferKey key,
574 IonBuffer& ion_buffer) {
Okan Arikan822b7102017-05-08 13:31:34 -0700575 if (key == DvrGlobalBuffers::kVsyncBuffer) {
576 vsync_ring_ = std::make_unique<CPUMappedBroadcastRing<DvrVsyncRing>>(
577 &ion_buffer, CPUUsageMode::WRITE_OFTEN);
578
579 if (vsync_ring_->IsMapped() == false) {
580 return -EPERM;
581 }
582 }
583
584 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700585 return MapConfigBuffer(ion_buffer);
586 }
587
588 return 0;
589}
590
591void HardwareComposer::OnDeletedGlobalBuffer(DvrGlobalBufferKey key) {
Okan Arikan822b7102017-05-08 13:31:34 -0700592 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700593 ConfigBufferDeleted();
594 }
595}
596
597int HardwareComposer::MapConfigBuffer(IonBuffer& ion_buffer) {
598 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700599 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700600
Okan Arikan6f468c62017-05-31 14:48:30 -0700601 if (ion_buffer.width() < DvrConfigRing::MemorySize()) {
John Bates954796e2017-05-11 11:00:31 -0700602 ALOGE("HardwareComposer::MapConfigBuffer: invalid buffer size.");
603 return -EINVAL;
604 }
605
606 void* buffer_base = 0;
607 int result = ion_buffer.Lock(ion_buffer.usage(), 0, 0, ion_buffer.width(),
608 ion_buffer.height(), &buffer_base);
609 if (result != 0) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700610 ALOGE(
611 "HardwareComposer::MapConfigBuffer: Failed to map vrflinger config "
612 "buffer.");
John Bates954796e2017-05-11 11:00:31 -0700613 return -EPERM;
614 }
615
Okan Arikan6f468c62017-05-31 14:48:30 -0700616 shared_config_ring_ = DvrConfigRing::Create(buffer_base, ion_buffer.width());
John Bates954796e2017-05-11 11:00:31 -0700617 ion_buffer.Unlock();
618
619 return 0;
620}
621
622void HardwareComposer::ConfigBufferDeleted() {
623 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700624 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700625}
626
627void HardwareComposer::UpdateConfigBuffer() {
628 std::lock_guard<std::mutex> lock(shared_config_mutex_);
629 if (!shared_config_ring_.is_valid())
630 return;
631 // Copy from latest record in shared_config_ring_ to local copy.
Okan Arikan6f468c62017-05-31 14:48:30 -0700632 DvrConfig record;
John Bates954796e2017-05-11 11:00:31 -0700633 if (shared_config_ring_.GetNewest(&shared_config_ring_sequence_, &record)) {
John Batescc65c3c2017-09-28 14:43:19 -0700634 ALOGI("DvrConfig updated: sequence %u, post offset %d",
635 shared_config_ring_sequence_, record.frame_post_offset_ns);
636 ++shared_config_ring_sequence_;
John Bates954796e2017-05-11 11:00:31 -0700637 post_thread_config_ = record;
638 }
639}
640
Corey Tabaka2251d822017-04-20 16:04:07 -0700641int HardwareComposer::PostThreadPollInterruptible(
Steven Thomasb02664d2017-07-26 18:48:28 -0700642 const pdx::LocalHandle& event_fd, int requested_events, int timeout_ms) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800643 pollfd pfd[2] = {
644 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700645 .fd = event_fd.Get(),
Steven Thomas66747c12017-03-22 18:45:31 -0700646 .events = static_cast<short>(requested_events),
647 .revents = 0,
Steven Thomas050b2c82017-03-06 11:45:16 -0800648 },
649 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700650 .fd = post_thread_event_fd_.Get(),
Steven Thomas050b2c82017-03-06 11:45:16 -0800651 .events = POLLPRI | POLLIN,
652 .revents = 0,
653 },
654 };
655 int ret, error;
656 do {
Steven Thomasb02664d2017-07-26 18:48:28 -0700657 ret = poll(pfd, 2, timeout_ms);
Steven Thomas050b2c82017-03-06 11:45:16 -0800658 error = errno;
659 ALOGW_IF(ret < 0,
660 "HardwareComposer::PostThreadPollInterruptible: Error during "
661 "poll(): %s (%d)",
662 strerror(error), error);
663 } while (ret < 0 && error == EINTR);
664
665 if (ret < 0) {
666 return -error;
Steven Thomasb02664d2017-07-26 18:48:28 -0700667 } else if (ret == 0) {
668 return -ETIMEDOUT;
Steven Thomas050b2c82017-03-06 11:45:16 -0800669 } else if (pfd[0].revents != 0) {
670 return 0;
671 } else if (pfd[1].revents != 0) {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -0700672 ALOGI("VrHwcPost thread interrupted: revents=%x", pfd[1].revents);
Steven Thomas050b2c82017-03-06 11:45:16 -0800673 return kPostThreadInterrupted;
674 } else {
675 return 0;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800676 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800677}
678
Steven Thomasbfe46a02018-02-16 14:27:35 -0800679// Sleep until the next predicted vsync, returning the predicted vsync
680// timestamp.
681Status<int64_t> HardwareComposer::WaitForPredictedVSync() {
682 const int64_t predicted_vsync_time = last_vsync_timestamp_ +
683 (target_display_->vsync_period_ns * vsync_prediction_interval_);
Corey Tabakab3732f02017-09-16 00:58:54 -0700684 const int error = SleepUntil(predicted_vsync_time);
685 if (error < 0) {
686 ALOGE("HardwareComposer::WaifForVSync:: Failed to sleep: %s",
687 strerror(-error));
Steven Thomasb02664d2017-07-26 18:48:28 -0700688 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800689 }
Corey Tabakab3732f02017-09-16 00:58:54 -0700690 return {predicted_vsync_time};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800691}
692
693int HardwareComposer::SleepUntil(int64_t wakeup_timestamp) {
694 const int timer_fd = vsync_sleep_timer_fd_.Get();
695 const itimerspec wakeup_itimerspec = {
696 .it_interval = {.tv_sec = 0, .tv_nsec = 0},
697 .it_value = NsToTimespec(wakeup_timestamp),
698 };
699 int ret =
700 timerfd_settime(timer_fd, TFD_TIMER_ABSTIME, &wakeup_itimerspec, nullptr);
701 int error = errno;
702 if (ret < 0) {
703 ALOGE("HardwareComposer::SleepUntil: Failed to set timerfd: %s",
704 strerror(error));
705 return -error;
706 }
707
Corey Tabaka451256f2017-08-22 11:59:15 -0700708 return PostThreadPollInterruptible(vsync_sleep_timer_fd_, POLLIN,
709 /*timeout_ms*/ -1);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800710}
711
712void HardwareComposer::PostThread() {
713 // NOLINTNEXTLINE(runtime/int)
Steven Thomas050b2c82017-03-06 11:45:16 -0800714 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>("VrHwcPost"), 0, 0, 0);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800715
Corey Tabaka2251d822017-04-20 16:04:07 -0700716 // Set the scheduler to SCHED_FIFO with high priority. If this fails here
717 // there may have been a startup timing issue between this thread and
718 // performanced. Try again later when this thread becomes active.
719 bool thread_policy_setup =
720 SetThreadPolicy("graphics:high", "/system/performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800721
Steven Thomas050b2c82017-03-06 11:45:16 -0800722 // Create a timerfd based on CLOCK_MONOTINIC.
723 vsync_sleep_timer_fd_.Reset(timerfd_create(CLOCK_MONOTONIC, 0));
724 LOG_ALWAYS_FATAL_IF(
725 !vsync_sleep_timer_fd_,
726 "HardwareComposer: Failed to create vsync sleep timerfd: %s",
727 strerror(errno));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800728
Steven Thomasbfe46a02018-02-16 14:27:35 -0800729 struct VsyncEyeOffsets { int64_t left_ns, right_ns; };
Steven Thomas050b2c82017-03-06 11:45:16 -0800730 bool was_running = false;
731
Steven Thomasbfe46a02018-02-16 14:27:35 -0800732 auto get_vsync_eye_offsets = [this]() -> VsyncEyeOffsets {
733 VsyncEyeOffsets offsets;
734 offsets.left_ns =
735 GetPosePredictionTimeOffset(target_display_->vsync_period_ns);
736
737 // TODO(jbates) Query vblank time from device, when such an API is
738 // available. This value (6.3%) was measured on A00 in low persistence mode.
739 int64_t vblank_ns = target_display_->vsync_period_ns * 63 / 1000;
740 offsets.right_ns = (target_display_->vsync_period_ns - vblank_ns) / 2;
741
742 // Check property for overriding right eye offset value.
743 offsets.right_ns =
744 property_get_int64(kRightEyeOffsetProperty, offsets.right_ns);
745
746 return offsets;
747 };
748
749 VsyncEyeOffsets vsync_eye_offsets = get_vsync_eye_offsets();
750
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800751 while (1) {
752 ATRACE_NAME("HardwareComposer::PostThread");
753
John Bates954796e2017-05-11 11:00:31 -0700754 // Check for updated config once per vsync.
755 UpdateConfigBuffer();
756
Corey Tabaka2251d822017-04-20 16:04:07 -0700757 while (post_thread_quiescent_) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800758 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Corey Tabaka2251d822017-04-20 16:04:07 -0700759 ALOGI("HardwareComposer::PostThread: Entering quiescent state.");
760
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700761 if (was_running) {
762 vsync_trace_parity_ = false;
763 ATRACE_INT(kVsyncTraceEventName, 0);
764 }
765
Steven Thomasbfe46a02018-02-16 14:27:35 -0800766 // Tear down resources.
767 OnPostThreadPaused();
Corey Tabaka2251d822017-04-20 16:04:07 -0700768 was_running = false;
769 post_thread_resumed_ = false;
770 post_thread_ready_.notify_all();
771
Steven Thomasaf336272018-01-04 17:36:47 -0800772 if (PostThreadCondWait(lock, -1,
773 [this] { return !post_thread_quiescent_; })) {
774 // A true return value means we've been asked to quit.
Corey Tabaka2251d822017-04-20 16:04:07 -0700775 return;
Steven Thomas282a5ed2017-02-07 18:07:01 -0800776 }
Corey Tabaka2251d822017-04-20 16:04:07 -0700777
Corey Tabaka2251d822017-04-20 16:04:07 -0700778 post_thread_resumed_ = true;
779 post_thread_ready_.notify_all();
780
781 ALOGI("HardwareComposer::PostThread: Exiting quiescent state.");
Steven Thomas050b2c82017-03-06 11:45:16 -0800782 }
783
Steven Thomasbfe46a02018-02-16 14:27:35 -0800784 if (!composer_)
785 CreateComposer();
786
787 bool target_display_changed = UpdateTargetDisplay();
788 bool just_resumed_running = !was_running;
789 was_running = true;
790
791 if (target_display_changed)
792 vsync_eye_offsets = get_vsync_eye_offsets();
793
794 if (just_resumed_running) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800795 OnPostThreadResumed();
Corey Tabaka2251d822017-04-20 16:04:07 -0700796
797 // Try to setup the scheduler policy if it failed during startup. Only
798 // attempt to do this on transitions from inactive to active to avoid
799 // spamming the system with RPCs and log messages.
800 if (!thread_policy_setup) {
801 thread_policy_setup =
802 SetThreadPolicy("graphics:high", "/system/performance");
803 }
Steven Thomasbfe46a02018-02-16 14:27:35 -0800804 }
Corey Tabakab3732f02017-09-16 00:58:54 -0700805
Steven Thomasbfe46a02018-02-16 14:27:35 -0800806 if (target_display_changed || just_resumed_running) {
Corey Tabakab3732f02017-09-16 00:58:54 -0700807 // Initialize the last vsync timestamp with the current time. The
808 // predictor below uses this time + the vsync interval in absolute time
809 // units for the initial delay. Once the driver starts reporting vsync the
810 // predictor will sync up with the real vsync.
811 last_vsync_timestamp_ = GetSystemClockNs();
Steven Thomasbfe46a02018-02-16 14:27:35 -0800812 vsync_prediction_interval_ = 1;
813 retire_fence_fds_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800814 }
815
816 int64_t vsync_timestamp = 0;
817 {
Corey Tabakab3732f02017-09-16 00:58:54 -0700818 TRACE_FORMAT("wait_vsync|vsync=%u;last_timestamp=%" PRId64
819 ";prediction_interval=%d|",
820 vsync_count_ + 1, last_vsync_timestamp_,
821 vsync_prediction_interval_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800822
Steven Thomasbfe46a02018-02-16 14:27:35 -0800823 auto status = WaitForPredictedVSync();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800824 ALOGE_IF(
Corey Tabakab3732f02017-09-16 00:58:54 -0700825 !status,
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800826 "HardwareComposer::PostThread: Failed to wait for vsync event: %s",
Corey Tabakab3732f02017-09-16 00:58:54 -0700827 status.GetErrorMessage().c_str());
828
829 // If there was an error either sleeping was interrupted due to pausing or
830 // there was an error getting the latest timestamp.
831 if (!status)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800832 continue;
Corey Tabakab3732f02017-09-16 00:58:54 -0700833
834 // Predicted vsync timestamp for this interval. This is stable because we
835 // use absolute time for the wakeup timer.
836 vsync_timestamp = status.get();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800837 }
838
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700839 vsync_trace_parity_ = !vsync_trace_parity_;
840 ATRACE_INT(kVsyncTraceEventName, vsync_trace_parity_ ? 1 : 0);
841
Corey Tabakab3732f02017-09-16 00:58:54 -0700842 // Advance the vsync counter only if the system is keeping up with hardware
843 // vsync to give clients an indication of the delays.
844 if (vsync_prediction_interval_ == 1)
845 ++vsync_count_;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800846
Steven Thomasbfe46a02018-02-16 14:27:35 -0800847 UpdateLayerConfig();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800848
Okan Arikan822b7102017-05-08 13:31:34 -0700849 // Publish the vsync event.
850 if (vsync_ring_) {
851 DvrVsync vsync;
852 vsync.vsync_count = vsync_count_;
853 vsync.vsync_timestamp_ns = vsync_timestamp;
Steven Thomasbfe46a02018-02-16 14:27:35 -0800854 vsync.vsync_left_eye_offset_ns = vsync_eye_offsets.left_ns;
855 vsync.vsync_right_eye_offset_ns = vsync_eye_offsets.right_ns;
856 vsync.vsync_period_ns = target_display_->vsync_period_ns;
Okan Arikan822b7102017-05-08 13:31:34 -0700857
858 vsync_ring_->Publish(vsync);
859 }
860
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800861 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700862 // Sleep until shortly before vsync.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800863 ATRACE_NAME("sleep");
864
Steven Thomasbfe46a02018-02-16 14:27:35 -0800865 const int64_t display_time_est_ns =
866 vsync_timestamp + target_display_->vsync_period_ns;
Corey Tabaka2251d822017-04-20 16:04:07 -0700867 const int64_t now_ns = GetSystemClockNs();
John Bates954796e2017-05-11 11:00:31 -0700868 const int64_t sleep_time_ns = display_time_est_ns - now_ns -
869 post_thread_config_.frame_post_offset_ns;
870 const int64_t wakeup_time_ns =
871 display_time_est_ns - post_thread_config_.frame_post_offset_ns;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800872
873 ATRACE_INT64("sleep_time_ns", sleep_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800874 if (sleep_time_ns > 0) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700875 int error = SleepUntil(wakeup_time_ns);
John Bates46684842017-12-13 15:26:50 -0800876 ALOGE_IF(error < 0 && error != kPostThreadInterrupted,
877 "HardwareComposer::PostThread: Failed to sleep: %s",
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800878 strerror(-error));
John Bates46684842017-12-13 15:26:50 -0800879 // If the sleep was interrupted (error == kPostThreadInterrupted),
880 // we still go through and present this frame because we may have set
881 // layers earlier and we want to flush the Composer's internal command
882 // buffer by continuing through to validate and present.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800883 }
884 }
885
Corey Tabakab3732f02017-09-16 00:58:54 -0700886 {
Steven Thomasbfe46a02018-02-16 14:27:35 -0800887 auto status = composer_callback_->GetVsyncTime(target_display_->id);
Corey Tabakab3732f02017-09-16 00:58:54 -0700888
889 // If we failed to read vsync there might be a problem with the driver.
890 // Since there's nothing we can do just behave as though we didn't get an
891 // updated vsync time and let the prediction continue.
892 const int64_t current_vsync_timestamp =
893 status ? status.get() : last_vsync_timestamp_;
894
895 const bool vsync_delayed =
896 last_vsync_timestamp_ == current_vsync_timestamp;
897 ATRACE_INT("vsync_delayed", vsync_delayed);
898
899 // If vsync was delayed advance the prediction interval and allow the
900 // fence logic in PostLayers() to skip the frame.
901 if (vsync_delayed) {
902 ALOGW(
903 "HardwareComposer::PostThread: VSYNC timestamp did not advance "
904 "since last frame: timestamp=%" PRId64 " prediction_interval=%d",
905 current_vsync_timestamp, vsync_prediction_interval_);
906 vsync_prediction_interval_++;
907 } else {
908 // We have an updated vsync timestamp, reset the prediction interval.
909 last_vsync_timestamp_ = current_vsync_timestamp;
910 vsync_prediction_interval_ = 1;
911 }
912 }
913
Steven Thomasbfe46a02018-02-16 14:27:35 -0800914 PostLayers(target_display_->id);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800915 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800916}
917
Steven Thomasbfe46a02018-02-16 14:27:35 -0800918bool HardwareComposer::UpdateTargetDisplay() {
919 bool target_display_changed = false;
920 auto displays = composer_callback_->GetDisplays();
921 if (displays.external_display_was_hotplugged) {
922 bool was_using_external_display = !target_display_->is_primary;
923 if (was_using_external_display) {
924 // The external display was hotplugged, so make sure to ignore any bad
925 // display errors as we destroy the layers.
926 for (auto& layer: layers_)
927 layer.IgnoreBadDisplayErrorsOnDestroy(true);
928 }
929
930 if (displays.external_display) {
931 // External display was connected
932 external_display_ = GetDisplayParams(composer_.get(),
933 *displays.external_display, /*is_primary*/ false);
934
935 if (property_get_bool(kUseExternalDisplayProperty, false)) {
936 ALOGI("External display connected. Switching to external display.");
937 target_display_ = &(*external_display_);
938 target_display_changed = true;
939 } else {
940 ALOGI("External display connected, but sysprop %s is unset, so"
941 " using primary display.", kUseExternalDisplayProperty);
942 if (was_using_external_display) {
943 target_display_ = &primary_display_;
944 target_display_changed = true;
945 }
946 }
947 } else {
948 // External display was disconnected
949 external_display_ = std::nullopt;
950 if (was_using_external_display) {
951 ALOGI("External display disconnected. Switching to primary display.");
952 target_display_ = &primary_display_;
953 target_display_changed = true;
954 }
955 }
956 }
957
958 if (target_display_changed) {
959 // If we're switching to the external display, turn the primary display off.
960 if (!target_display_->is_primary) {
961 EnableDisplay(primary_display_, false);
962 }
963 // If we're switching to the primary display, and the external display is
964 // still connected, turn the external display off.
965 else if (target_display_->is_primary && external_display_) {
966 EnableDisplay(*external_display_, false);
967 }
968
969 // Turn the new target display on.
970 EnableDisplay(*target_display_, true);
971
972 // When we switch displays we need to recreate all the layers, so clear the
973 // current list, which will trigger layer recreation.
974 layers_.clear();
975 }
976
977 return target_display_changed;
978}
979
Corey Tabaka2251d822017-04-20 16:04:07 -0700980// Checks for changes in the surface stack and updates the layer config to
981// accomodate the new stack.
Steven Thomasbfe46a02018-02-16 14:27:35 -0800982void HardwareComposer::UpdateLayerConfig() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700983 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces;
Steven Thomas050b2c82017-03-06 11:45:16 -0800984 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700985 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Corey Tabaka2251d822017-04-20 16:04:07 -0700986
Steven Thomasbfe46a02018-02-16 14:27:35 -0800987 if (!surfaces_changed_ && (!layers_.empty() || surfaces_.empty()))
988 return;
989
990 surfaces = surfaces_;
991 surfaces_changed_ = false;
Steven Thomas050b2c82017-03-06 11:45:16 -0800992 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800993
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800994 ATRACE_NAME("UpdateLayerConfig_HwLayers");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800995
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700996 // Sort the new direct surface list by z-order to determine the relative order
997 // of the surfaces. This relative order is used for the HWC z-order value to
998 // insulate VrFlinger and HWC z-order semantics from each other.
999 std::sort(surfaces.begin(), surfaces.end(), [](const auto& a, const auto& b) {
1000 return a->z_order() < b->z_order();
1001 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001002
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001003 // Prepare a new layer stack, pulling in layers from the previous
1004 // layer stack that are still active and updating their attributes.
1005 std::vector<Layer> layers;
1006 size_t layer_index = 0;
1007 for (const auto& surface : surfaces) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001008 // The bottom layer is opaque, other layers blend.
1009 HWC::BlendMode blending =
1010 layer_index == 0 ? HWC::BlendMode::None : HWC::BlendMode::Coverage;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001011
1012 // Try to find a layer for this surface in the set of active layers.
1013 auto search =
1014 std::lower_bound(layers_.begin(), layers_.end(), surface->surface_id());
1015 const bool found = search != layers_.end() &&
1016 search->GetSurfaceId() == surface->surface_id();
1017 if (found) {
1018 // Update the attributes of the layer that may have changed.
1019 search->SetBlending(blending);
1020 search->SetZOrder(layer_index); // Relative z-order.
1021
1022 // Move the existing layer to the new layer set and remove the empty layer
1023 // object from the current set.
1024 layers.push_back(std::move(*search));
1025 layers_.erase(search);
1026 } else {
1027 // Insert a layer for the new surface.
Steven Thomasbfe46a02018-02-16 14:27:35 -08001028 layers.emplace_back(composer_.get(), *target_display_, surface, blending,
1029 HWC::Composition::Device, layer_index);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001030 }
1031
1032 ALOGI_IF(
1033 TRACE,
1034 "HardwareComposer::UpdateLayerConfig: layer_index=%zu surface_id=%d",
1035 layer_index, layers[layer_index].GetSurfaceId());
1036
1037 layer_index++;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001038 }
1039
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001040 // Sort the new layer stack by ascending surface id.
1041 std::sort(layers.begin(), layers.end());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001042
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001043 // Replace the previous layer set with the new layer set. The destructor of
1044 // the previous set will clean up the remaining Layers that are not moved to
1045 // the new layer set.
1046 layers_ = std::move(layers);
1047
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001048 ALOGD_IF(TRACE, "HardwareComposer::UpdateLayerConfig: %zd active layers",
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001049 layers_.size());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001050}
1051
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001052std::vector<sp<IVsyncCallback>>::const_iterator
1053HardwareComposer::VsyncService::FindCallback(
1054 const sp<IVsyncCallback>& callback) const {
1055 sp<IBinder> binder = IInterface::asBinder(callback);
1056 return std::find_if(callbacks_.cbegin(), callbacks_.cend(),
1057 [&](const sp<IVsyncCallback>& callback) {
1058 return IInterface::asBinder(callback) == binder;
1059 });
1060}
1061
1062status_t HardwareComposer::VsyncService::registerCallback(
1063 const sp<IVsyncCallback> callback) {
1064 std::lock_guard<std::mutex> autolock(mutex_);
1065 if (FindCallback(callback) == callbacks_.cend()) {
1066 callbacks_.push_back(callback);
1067 }
Tianyu Jiang932fb4f2018-11-15 11:09:58 -08001068 return OK;
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001069}
1070
1071status_t HardwareComposer::VsyncService::unregisterCallback(
1072 const sp<IVsyncCallback> callback) {
1073 std::lock_guard<std::mutex> autolock(mutex_);
1074 auto iter = FindCallback(callback);
1075 if (iter != callbacks_.cend()) {
1076 callbacks_.erase(iter);
1077 }
Tianyu Jiang932fb4f2018-11-15 11:09:58 -08001078 return OK;
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001079}
1080
1081void HardwareComposer::VsyncService::OnVsync(int64_t vsync_timestamp) {
1082 ATRACE_NAME("VsyncService::OnVsync");
1083 std::lock_guard<std::mutex> autolock(mutex_);
1084 for (auto iter = callbacks_.begin(); iter != callbacks_.end();) {
1085 if ((*iter)->onVsync(vsync_timestamp) == android::DEAD_OBJECT) {
1086 iter = callbacks_.erase(iter);
1087 } else {
1088 ++iter;
1089 }
1090 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001091}
1092
Steven Thomasb02664d2017-07-26 18:48:28 -07001093Return<void> HardwareComposer::ComposerCallback::onHotplug(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001094 Hwc2::Display display, IComposerCallback::Connection conn) {
Steven Thomasbfe46a02018-02-16 14:27:35 -08001095 std::lock_guard<std::mutex> lock(mutex_);
1096 ALOGI("onHotplug display=%" PRIu64 " conn=%d", display, conn);
1097
1098 bool is_primary = !got_first_hotplug_ || display == primary_display_.id;
1099
Steven Thomas6e8f7062017-11-22 14:15:29 -08001100 // Our first onHotplug callback is always for the primary display.
Steven Thomasbfe46a02018-02-16 14:27:35 -08001101 if (!got_first_hotplug_) {
Steven Thomas6e8f7062017-11-22 14:15:29 -08001102 LOG_ALWAYS_FATAL_IF(conn != IComposerCallback::Connection::CONNECTED,
1103 "Initial onHotplug callback should be primary display connected");
Steven Thomasbfe46a02018-02-16 14:27:35 -08001104 got_first_hotplug_ = true;
1105 } else if (is_primary) {
1106 ALOGE("Ignoring unexpected onHotplug() call for primary display");
1107 return Void();
1108 }
1109
1110 if (conn == IComposerCallback::Connection::CONNECTED) {
1111 if (!is_primary)
1112 external_display_ = DisplayInfo();
1113 DisplayInfo& display_info = is_primary ?
1114 primary_display_ : *external_display_;
1115 display_info.id = display;
Steven Thomas6e8f7062017-11-22 14:15:29 -08001116
Corey Tabakab3732f02017-09-16 00:58:54 -07001117 std::array<char, 1024> buffer;
1118 snprintf(buffer.data(), buffer.size(),
1119 "/sys/class/graphics/fb%" PRIu64 "/vsync_event", display);
1120 if (LocalHandle handle{buffer.data(), O_RDONLY}) {
1121 ALOGI(
1122 "HardwareComposer::ComposerCallback::onHotplug: Driver supports "
1123 "vsync_event node for display %" PRIu64,
1124 display);
Steven Thomasbfe46a02018-02-16 14:27:35 -08001125 display_info.driver_vsync_event_fd = std::move(handle);
Corey Tabakab3732f02017-09-16 00:58:54 -07001126 } else {
1127 ALOGI(
1128 "HardwareComposer::ComposerCallback::onHotplug: Driver does not "
1129 "support vsync_event node for display %" PRIu64,
1130 display);
1131 }
Steven Thomasbfe46a02018-02-16 14:27:35 -08001132 } else if (conn == IComposerCallback::Connection::DISCONNECTED) {
1133 external_display_ = std::nullopt;
Corey Tabakab3732f02017-09-16 00:58:54 -07001134 }
1135
Steven Thomasbfe46a02018-02-16 14:27:35 -08001136 if (!is_primary)
1137 external_display_was_hotplugged_ = true;
1138
Steven Thomasb02664d2017-07-26 18:48:28 -07001139 return Void();
1140}
1141
1142Return<void> HardwareComposer::ComposerCallback::onRefresh(
1143 Hwc2::Display /*display*/) {
1144 return hardware::Void();
1145}
1146
Corey Tabaka451256f2017-08-22 11:59:15 -07001147Return<void> HardwareComposer::ComposerCallback::onVsync(Hwc2::Display display,
1148 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001149 TRACE_FORMAT("vsync_callback|display=%" PRIu64 ";timestamp=%" PRId64 "|",
1150 display, timestamp);
1151 std::lock_guard<std::mutex> lock(mutex_);
Steven Thomasbfe46a02018-02-16 14:27:35 -08001152 DisplayInfo* display_info = GetDisplayInfo(display);
1153 if (display_info) {
Steven Thomasbfe46a02018-02-16 14:27:35 -08001154 display_info->callback_vsync_timestamp = timestamp;
Steven Thomasb02664d2017-07-26 18:48:28 -07001155 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001156 if (primary_display_.id == display && vsync_service_ != nullptr) {
1157 vsync_service_->OnVsync(timestamp);
1158 }
Steven Thomasbfe46a02018-02-16 14:27:35 -08001159
Steven Thomasb02664d2017-07-26 18:48:28 -07001160 return Void();
1161}
1162
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001163void HardwareComposer::ComposerCallback::SetVsyncService(
1164 const sp<VsyncService>& vsync_service) {
1165 std::lock_guard<std::mutex> lock(mutex_);
1166 vsync_service_ = vsync_service;
1167}
1168
Steven Thomasbfe46a02018-02-16 14:27:35 -08001169HardwareComposer::ComposerCallback::Displays
1170HardwareComposer::ComposerCallback::GetDisplays() {
1171 std::lock_guard<std::mutex> lock(mutex_);
1172 Displays displays;
1173 displays.primary_display = primary_display_.id;
1174 if (external_display_)
1175 displays.external_display = external_display_->id;
1176 if (external_display_was_hotplugged_) {
1177 external_display_was_hotplugged_ = false;
1178 displays.external_display_was_hotplugged = true;
1179 }
1180 return displays;
1181}
1182
1183Status<int64_t> HardwareComposer::ComposerCallback::GetVsyncTime(
1184 hwc2_display_t display) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001185 std::lock_guard<std::mutex> autolock(mutex_);
Steven Thomasbfe46a02018-02-16 14:27:35 -08001186 DisplayInfo* display_info = GetDisplayInfo(display);
1187 if (!display_info) {
1188 ALOGW("Attempt to get vsync time for unknown display %" PRIu64, display);
1189 return ErrorStatus(EINVAL);
1190 }
1191
Corey Tabakab3732f02017-09-16 00:58:54 -07001192 // See if the driver supports direct vsync events.
Steven Thomasbfe46a02018-02-16 14:27:35 -08001193 LocalHandle& event_fd = display_info->driver_vsync_event_fd;
Corey Tabakab3732f02017-09-16 00:58:54 -07001194 if (!event_fd) {
1195 // Fall back to returning the last timestamp returned by the vsync
1196 // callback.
Steven Thomasbfe46a02018-02-16 14:27:35 -08001197 return display_info->callback_vsync_timestamp;
Corey Tabakab3732f02017-09-16 00:58:54 -07001198 }
1199
1200 // When the driver supports the vsync_event sysfs node we can use it to
1201 // determine the latest vsync timestamp, even if the HWC callback has been
1202 // delayed.
1203
1204 // The driver returns data in the form "VSYNC=<timestamp ns>".
1205 std::array<char, 32> data;
1206 data.fill('\0');
1207
1208 // Seek back to the beginning of the event file.
1209 int ret = lseek(event_fd.Get(), 0, SEEK_SET);
1210 if (ret < 0) {
1211 const int error = errno;
1212 ALOGE(
1213 "HardwareComposer::ComposerCallback::GetVsyncTime: Failed to seek "
1214 "vsync event fd: %s",
1215 strerror(error));
1216 return ErrorStatus(error);
1217 }
1218
1219 // Read the vsync event timestamp.
1220 ret = read(event_fd.Get(), data.data(), data.size());
1221 if (ret < 0) {
1222 const int error = errno;
1223 ALOGE_IF(error != EAGAIN,
1224 "HardwareComposer::ComposerCallback::GetVsyncTime: Error "
1225 "while reading timestamp: %s",
1226 strerror(error));
1227 return ErrorStatus(error);
1228 }
1229
1230 int64_t timestamp;
1231 ret = sscanf(data.data(), "VSYNC=%" PRIu64,
1232 reinterpret_cast<uint64_t*>(&timestamp));
1233 if (ret < 0) {
1234 const int error = errno;
1235 ALOGE(
1236 "HardwareComposer::ComposerCallback::GetVsyncTime: Error while "
1237 "parsing timestamp: %s",
1238 strerror(error));
1239 return ErrorStatus(error);
1240 }
1241
1242 return {timestamp};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001243}
1244
Steven Thomasbfe46a02018-02-16 14:27:35 -08001245HardwareComposer::ComposerCallback::DisplayInfo*
1246HardwareComposer::ComposerCallback::GetDisplayInfo(hwc2_display_t display) {
1247 if (display == primary_display_.id) {
1248 return &primary_display_;
1249 } else if (external_display_ && display == external_display_->id) {
1250 return &(*external_display_);
1251 }
1252 return nullptr;
1253}
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001254
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001255void Layer::Reset() {
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001256 if (hardware_composer_layer_) {
Steven Thomasbfe46a02018-02-16 14:27:35 -08001257 HWC::Error error =
1258 composer_->destroyLayer(display_params_.id, hardware_composer_layer_);
1259 if (error != HWC::Error::None &&
1260 (!ignore_bad_display_errors_on_destroy_ ||
1261 error != HWC::Error::BadDisplay)) {
1262 ALOGE("destroyLayer() failed for display %" PRIu64 ", layer %" PRIu64
1263 ". error: %s", display_params_.id, hardware_composer_layer_,
1264 error.to_string().c_str());
1265 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001266 hardware_composer_layer_ = 0;
1267 }
1268
Corey Tabaka2251d822017-04-20 16:04:07 -07001269 z_order_ = 0;
1270 blending_ = HWC::BlendMode::None;
Corey Tabaka2251d822017-04-20 16:04:07 -07001271 composition_type_ = HWC::Composition::Invalid;
1272 target_composition_type_ = composition_type_;
1273 source_ = EmptyVariant{};
1274 acquire_fence_.Close();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001275 surface_rect_functions_applied_ = false;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001276 pending_visibility_settings_ = true;
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001277 cached_buffer_map_.clear();
Steven Thomasbfe46a02018-02-16 14:27:35 -08001278 ignore_bad_display_errors_on_destroy_ = false;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001279}
1280
Steven Thomasbfe46a02018-02-16 14:27:35 -08001281Layer::Layer(Hwc2::Composer* composer, const DisplayParams& display_params,
1282 const std::shared_ptr<DirectDisplaySurface>& surface,
1283 HWC::BlendMode blending, HWC::Composition composition_type,
1284 size_t z_order)
1285 : composer_(composer),
1286 display_params_(display_params),
1287 z_order_{z_order},
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001288 blending_{blending},
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001289 target_composition_type_{composition_type},
1290 source_{SourceSurface{surface}} {
1291 CommonLayerSetup();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001292}
1293
Steven Thomasbfe46a02018-02-16 14:27:35 -08001294Layer::Layer(Hwc2::Composer* composer, const DisplayParams& display_params,
1295 const std::shared_ptr<IonBuffer>& buffer, HWC::BlendMode blending,
1296 HWC::Composition composition_type, size_t z_order)
1297 : composer_(composer),
1298 display_params_(display_params),
1299 z_order_{z_order},
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001300 blending_{blending},
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001301 target_composition_type_{composition_type},
1302 source_{SourceBuffer{buffer}} {
1303 CommonLayerSetup();
1304}
1305
1306Layer::~Layer() { Reset(); }
1307
Chih-Hung Hsieh5bc849f2018-09-25 14:21:50 -07001308Layer::Layer(Layer&& other) noexcept { *this = std::move(other); }
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001309
Chih-Hung Hsieh5bc849f2018-09-25 14:21:50 -07001310Layer& Layer::operator=(Layer&& other) noexcept {
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001311 if (this != &other) {
1312 Reset();
1313 using std::swap;
Steven Thomasbfe46a02018-02-16 14:27:35 -08001314 swap(composer_, other.composer_);
1315 swap(display_params_, other.display_params_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001316 swap(hardware_composer_layer_, other.hardware_composer_layer_);
1317 swap(z_order_, other.z_order_);
1318 swap(blending_, other.blending_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001319 swap(composition_type_, other.composition_type_);
1320 swap(target_composition_type_, other.target_composition_type_);
1321 swap(source_, other.source_);
1322 swap(acquire_fence_, other.acquire_fence_);
1323 swap(surface_rect_functions_applied_,
1324 other.surface_rect_functions_applied_);
1325 swap(pending_visibility_settings_, other.pending_visibility_settings_);
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001326 swap(cached_buffer_map_, other.cached_buffer_map_);
Steven Thomasbfe46a02018-02-16 14:27:35 -08001327 swap(ignore_bad_display_errors_on_destroy_,
1328 other.ignore_bad_display_errors_on_destroy_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001329 }
1330 return *this;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001331}
1332
Corey Tabaka2251d822017-04-20 16:04:07 -07001333void Layer::UpdateBuffer(const std::shared_ptr<IonBuffer>& buffer) {
1334 if (source_.is<SourceBuffer>())
1335 std::get<SourceBuffer>(source_) = {buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001336}
1337
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001338void Layer::SetBlending(HWC::BlendMode blending) {
1339 if (blending_ != blending) {
1340 blending_ = blending;
1341 pending_visibility_settings_ = true;
1342 }
1343}
1344
1345void Layer::SetZOrder(size_t z_order) {
1346 if (z_order_ != z_order) {
1347 z_order_ = z_order;
1348 pending_visibility_settings_ = true;
1349 }
1350}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001351
1352IonBuffer* Layer::GetBuffer() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001353 struct Visitor {
1354 IonBuffer* operator()(SourceSurface& source) { return source.GetBuffer(); }
1355 IonBuffer* operator()(SourceBuffer& source) { return source.GetBuffer(); }
1356 IonBuffer* operator()(EmptyVariant) { return nullptr; }
1357 };
1358 return source_.Visit(Visitor{});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001359}
1360
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001361void Layer::UpdateVisibilitySettings() {
1362 if (pending_visibility_settings_) {
1363 pending_visibility_settings_ = false;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001364
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001365 HWC::Error error;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001366
1367 error = composer_->setLayerBlendMode(
Steven Thomasbfe46a02018-02-16 14:27:35 -08001368 display_params_.id, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001369 blending_.cast<Hwc2::IComposerClient::BlendMode>());
1370 ALOGE_IF(error != HWC::Error::None,
1371 "Layer::UpdateLayerSettings: Error setting layer blend mode: %s",
1372 error.to_string().c_str());
1373
Steven Thomasbfe46a02018-02-16 14:27:35 -08001374 error = composer_->setLayerZOrder(display_params_.id,
1375 hardware_composer_layer_, z_order_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001376 ALOGE_IF(error != HWC::Error::None,
1377 "Layer::UpdateLayerSettings: Error setting z_ order: %s",
1378 error.to_string().c_str());
1379 }
1380}
1381
1382void Layer::UpdateLayerSettings() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001383 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001384
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001385 UpdateVisibilitySettings();
1386
Corey Tabaka2251d822017-04-20 16:04:07 -07001387 // TODO(eieio): Use surface attributes or some other mechanism to control
1388 // the layer display frame.
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001389 error = composer_->setLayerDisplayFrame(
Steven Thomasbfe46a02018-02-16 14:27:35 -08001390 display_params_.id, hardware_composer_layer_,
1391 {0, 0, display_params_.width, display_params_.height});
Corey Tabaka2251d822017-04-20 16:04:07 -07001392 ALOGE_IF(error != HWC::Error::None,
1393 "Layer::UpdateLayerSettings: Error setting layer display frame: %s",
1394 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001395
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001396 error = composer_->setLayerVisibleRegion(
Steven Thomasbfe46a02018-02-16 14:27:35 -08001397 display_params_.id, hardware_composer_layer_,
1398 {{0, 0, display_params_.width, display_params_.height}});
Corey Tabaka2251d822017-04-20 16:04:07 -07001399 ALOGE_IF(error != HWC::Error::None,
1400 "Layer::UpdateLayerSettings: Error setting layer visible region: %s",
1401 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001402
Steven Thomasbfe46a02018-02-16 14:27:35 -08001403 error = composer_->setLayerPlaneAlpha(display_params_.id,
1404 hardware_composer_layer_, 1.0f);
Corey Tabaka2251d822017-04-20 16:04:07 -07001405 ALOGE_IF(error != HWC::Error::None,
1406 "Layer::UpdateLayerSettings: Error setting layer plane alpha: %s",
1407 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001408}
1409
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001410void Layer::CommonLayerSetup() {
Steven Thomasbfe46a02018-02-16 14:27:35 -08001411 HWC::Error error = composer_->createLayer(display_params_.id,
Steven Thomas6e8f7062017-11-22 14:15:29 -08001412 &hardware_composer_layer_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001413 ALOGE_IF(error != HWC::Error::None,
1414 "Layer::CommonLayerSetup: Failed to create layer on primary "
1415 "display: %s",
1416 error.to_string().c_str());
1417 UpdateLayerSettings();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001418}
1419
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001420bool Layer::CheckAndUpdateCachedBuffer(std::size_t slot, int buffer_id) {
1421 auto search = cached_buffer_map_.find(slot);
1422 if (search != cached_buffer_map_.end() && search->second == buffer_id)
1423 return true;
1424
1425 // Assign or update the buffer slot.
1426 if (buffer_id >= 0)
1427 cached_buffer_map_[slot] = buffer_id;
1428 return false;
1429}
1430
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001431void Layer::Prepare() {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001432 int right, bottom, id;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -04001433 sp<GraphicBuffer> handle;
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001434 std::size_t slot;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001435
Corey Tabaka2251d822017-04-20 16:04:07 -07001436 // Acquire the next buffer according to the type of source.
1437 IfAnyOf<SourceSurface, SourceBuffer>::Call(&source_, [&](auto& source) {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001438 std::tie(right, bottom, id, handle, acquire_fence_, slot) =
1439 source.Acquire();
Corey Tabaka2251d822017-04-20 16:04:07 -07001440 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001441
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001442 TRACE_FORMAT("Layer::Prepare|buffer_id=%d;slot=%zu|", id, slot);
1443
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001444 // Update any visibility (blending, z-order) changes that occurred since
1445 // last prepare.
1446 UpdateVisibilitySettings();
1447
1448 // When a layer is first setup there may be some time before the first
1449 // buffer arrives. Setup the HWC layer as a solid color to stall for time
1450 // until the first buffer arrives. Once the first buffer arrives there will
1451 // always be a buffer for the frame even if it is old.
Corey Tabaka2251d822017-04-20 16:04:07 -07001452 if (!handle.get()) {
1453 if (composition_type_ == HWC::Composition::Invalid) {
1454 composition_type_ = HWC::Composition::SolidColor;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001455 composer_->setLayerCompositionType(
Steven Thomasbfe46a02018-02-16 14:27:35 -08001456 display_params_.id, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001457 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1458 Hwc2::IComposerClient::Color layer_color = {0, 0, 0, 0};
Steven Thomasbfe46a02018-02-16 14:27:35 -08001459 composer_->setLayerColor(display_params_.id, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001460 layer_color);
Corey Tabaka2251d822017-04-20 16:04:07 -07001461 } else {
1462 // The composition type is already set. Nothing else to do until a
1463 // buffer arrives.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001464 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001465 } else {
Corey Tabaka2251d822017-04-20 16:04:07 -07001466 if (composition_type_ != target_composition_type_) {
1467 composition_type_ = target_composition_type_;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001468 composer_->setLayerCompositionType(
Steven Thomasbfe46a02018-02-16 14:27:35 -08001469 display_params_.id, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001470 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1471 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001472
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001473 // See if the HWC cache already has this buffer.
1474 const bool cached = CheckAndUpdateCachedBuffer(slot, id);
1475 if (cached)
1476 handle = nullptr;
1477
Corey Tabaka2251d822017-04-20 16:04:07 -07001478 HWC::Error error{HWC::Error::None};
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001479 error =
Steven Thomasbfe46a02018-02-16 14:27:35 -08001480 composer_->setLayerBuffer(display_params_.id, hardware_composer_layer_,
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001481 slot, handle, acquire_fence_.Get());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001482
Corey Tabaka2251d822017-04-20 16:04:07 -07001483 ALOGE_IF(error != HWC::Error::None,
1484 "Layer::Prepare: Error setting layer buffer: %s",
1485 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001486
Corey Tabaka2251d822017-04-20 16:04:07 -07001487 if (!surface_rect_functions_applied_) {
1488 const float float_right = right;
1489 const float float_bottom = bottom;
Steven Thomasbfe46a02018-02-16 14:27:35 -08001490 error = composer_->setLayerSourceCrop(display_params_.id,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001491 hardware_composer_layer_,
1492 {0, 0, float_right, float_bottom});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001493
Corey Tabaka2251d822017-04-20 16:04:07 -07001494 ALOGE_IF(error != HWC::Error::None,
1495 "Layer::Prepare: Error setting layer source crop: %s",
1496 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001497
Corey Tabaka2251d822017-04-20 16:04:07 -07001498 surface_rect_functions_applied_ = true;
1499 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001500 }
1501}
1502
1503void Layer::Finish(int release_fence_fd) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001504 IfAnyOf<SourceSurface, SourceBuffer>::Call(
1505 &source_, [release_fence_fd](auto& source) {
1506 source.Finish(LocalHandle(release_fence_fd));
1507 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001508}
1509
Corey Tabaka2251d822017-04-20 16:04:07 -07001510void Layer::Drop() { acquire_fence_.Close(); }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001511
1512} // namespace dvr
1513} // namespace android