hardware_composer.cpp revision a8a92784bc5f6a50ce00311c6161fbcfc0898c5a
1#include "hardware_composer.h" 2 3#include <log/log.h> 4#include <cutils/properties.h> 5#include <cutils/sched_policy.h> 6#include <fcntl.h> 7#include <poll.h> 8#include <sync/sync.h> 9#include <sys/eventfd.h> 10#include <sys/prctl.h> 11#include <sys/resource.h> 12#include <sys/system_properties.h> 13#include <sys/timerfd.h> 14#include <unistd.h> 15#include <utils/Trace.h> 16 17#include <algorithm> 18#include <functional> 19#include <map> 20 21#include <dvr/performance_client_api.h> 22#include <private/dvr/clock_ns.h> 23#include <private/dvr/display_types.h> 24#include <private/dvr/pose_client_internal.h> 25#include <private/dvr/sync_util.h> 26 27#include "debug_hud_data.h" 28#include "screenshot_service.h" 29 30using android::pdx::LocalHandle; 31 32namespace android { 33namespace dvr { 34 35namespace { 36 37// If the number of pending fences goes over this count at the point when we 38// are about to submit a new frame to HWC, we will drop the frame. This should 39// be a signal that the display driver has begun queuing frames. Note that with 40// smart displays (with RAM), the fence is signaled earlier than the next vsync, 41// at the point when the DMA to the display completes. Currently we use a smart 42// display and the EDS timing coincides with zero pending fences, so this is 0. 43constexpr int kAllowedPendingFenceCount = 0; 44 45// If we think we're going to miss vsync by more than this amount, skip the 46// frame. 47constexpr int64_t kFrameSkipThresholdNs = 4000000; // 4ms 48 49// Counter PostLayers() deficiency by requiring apps to produce a frame at least 50// 2.5ms before vsync. See b/28881672. 51constexpr int64_t kFrameTimeEstimateMin = 2500000; // 2.5ms 52 53constexpr size_t kDefaultDisplayConfigCount = 32; 54 55constexpr float kMetersPerInch = 0.0254f; 56 57const char kBacklightBrightnessSysFile[] = 58 "/sys/class/leds/lcd-backlight/brightness"; 59 60const char kPrimaryDisplayVSyncEventFile[] = 61 "/sys/class/graphics/fb0/vsync_event"; 62 63const char kPrimaryDisplayWaitPPEventFile[] = "/sys/class/graphics/fb0/wait_pp"; 64 65const char kDvrPerformanceProperty[] = "sys.dvr.performance"; 66 67const char kRightEyeOffsetProperty[] = "dreamos.right_eye_offset_ns"; 68 69// Returns our best guess for the time the compositor will spend rendering the 70// next frame. 71int64_t GuessFrameTime(int compositor_visible_layer_count) { 72 // The cost of asynchronous EDS and lens warp is currently measured at 2.5ms 73 // for one layer and 7ms for two layers, but guess a higher frame time to 74 // account for CPU overhead. This guess is only used before we've measured the 75 // actual time to render a frame for the current compositor configuration. 76 switch (compositor_visible_layer_count) { 77 case 0: 78 return 500000; // .5ms 79 case 1: 80 return 5000000; // 5ms 81 default: 82 return 10500000; // 10.5ms 83 } 84} 85 86// Get time offset from a vsync to when the pose for that vsync should be 87// predicted out to. For example, if scanout gets halfway through the frame 88// at the halfway point between vsyncs, then this could be half the period. 89// With global shutter displays, this should be changed to the offset to when 90// illumination begins. Low persistence adds a frame of latency, so we predict 91// to the center of the next frame. 92inline int64_t GetPosePredictionTimeOffset(int64_t vsync_period_ns) { 93 return (vsync_period_ns * 150) / 100; 94} 95 96} // anonymous namespace 97 98HardwareComposer::HardwareComposer() 99 : HardwareComposer(nullptr) { 100} 101 102HardwareComposer::HardwareComposer(Hwc2::Composer* hwc2_hidl) 103 : hwc2_hidl_(hwc2_hidl), 104 display_transform_(HWC_TRANSFORM_NONE), 105 display_surfaces_updated_(false), 106 hardware_layers_need_update_(false), 107 display_on_(false), 108 active_layer_count_(0), 109 gpu_layer_(nullptr), 110 terminate_post_thread_event_fd_(-1), 111 pause_post_thread_(true), 112 backlight_brightness_fd_(-1), 113 primary_display_vsync_event_fd_(-1), 114 primary_display_wait_pp_fd_(-1), 115 vsync_sleep_timer_fd_(-1), 116 last_vsync_timestamp_(0), 117 vsync_count_(0), 118 frame_skip_count_(0), 119 pose_client_(nullptr) { 120 std::transform(layer_storage_.begin(), layer_storage_.end(), layers_.begin(), 121 [](auto& layer) { return &layer; }); 122 123 callbacks_ = new ComposerCallback; 124} 125 126HardwareComposer::~HardwareComposer(void) { 127 if (!IsSuspended()) { 128 Suspend(); 129 } 130} 131 132bool HardwareComposer::Resume() { 133 std::lock_guard<std::mutex> autolock(layer_mutex_); 134 135 if (!IsSuspended()) { 136 ALOGE("HardwareComposer::Resume: HardwareComposer is already running."); 137 return false; 138 } 139 140 int32_t ret = HWC2_ERROR_NONE; 141 142 static const uint32_t attributes[] = { 143 HWC_DISPLAY_WIDTH, HWC_DISPLAY_HEIGHT, HWC_DISPLAY_VSYNC_PERIOD, 144 HWC_DISPLAY_DPI_X, HWC_DISPLAY_DPI_Y, HWC_DISPLAY_NO_ATTRIBUTE, 145 }; 146 147 std::vector<Hwc2::Config> configs; 148 ret = (int32_t)hwc2_hidl_->getDisplayConfigs(HWC_DISPLAY_PRIMARY, &configs); 149 150 if (ret != HWC2_ERROR_NONE) { 151 ALOGE("HardwareComposer: Failed to get display configs"); 152 return false; 153 } 154 155 uint32_t num_configs = configs.size(); 156 157 for (size_t i = 0; i < num_configs; i++) { 158 ALOGI("HardwareComposer: cfg[%zd/%zd] = 0x%08x", i, num_configs, 159 configs[i]); 160 161 ret = GetDisplayMetrics(HWC_DISPLAY_PRIMARY, configs[i], 162 &native_display_metrics_); 163 164 if (ret != HWC2_ERROR_NONE) { 165 ALOGE("HardwareComposer: Failed to get display attributes %d", ret); 166 continue; 167 } else { 168 ret = 169 (int32_t)hwc2_hidl_->setActiveConfig(HWC_DISPLAY_PRIMARY, configs[i]); 170 171 if (ret != HWC2_ERROR_NONE) { 172 ALOGE("HardwareComposer: Failed to set display configuration; ret=%d", 173 ret); 174 continue; 175 } 176 177 break; 178 } 179 } 180 181 if (ret != HWC2_ERROR_NONE) { 182 ALOGE("HardwareComposer: Could not set a valid display configuration."); 183 return false; 184 } 185 186 // Set the display metrics but never use rotation to avoid the long latency of 187 // rotation processing in hwc. 188 display_transform_ = HWC_TRANSFORM_NONE; 189 display_metrics_ = native_display_metrics_; 190 191 ALOGI( 192 "HardwareComposer: primary display attributes: width=%d height=%d " 193 "vsync_period_ns=%d DPI=%dx%d", 194 native_display_metrics_.width, native_display_metrics_.height, 195 native_display_metrics_.vsync_period_ns, native_display_metrics_.dpi.x, 196 native_display_metrics_.dpi.y); 197 198 // Always turn off vsync when we start. 199 EnableVsync(false); 200 201 constexpr int format = HAL_PIXEL_FORMAT_RGBA_8888; 202 constexpr int usage = 203 GRALLOC_USAGE_HW_FB | GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER; 204 205 framebuffer_target_ = std::make_shared<IonBuffer>( 206 native_display_metrics_.width, native_display_metrics_.height, format, 207 usage); 208 209 // Associate each Layer instance with a hardware composer layer. 210 for (auto layer : layers_) { 211 layer->Initialize(hwc2_hidl_.get(), &native_display_metrics_); 212 } 213 214 // Open the backlight brightness control sysfs node. 215 backlight_brightness_fd_ = LocalHandle(kBacklightBrightnessSysFile, O_RDWR); 216 ALOGW_IF(!backlight_brightness_fd_, 217 "HardwareComposer: Failed to open backlight brightness control: %s", 218 strerror(errno)); 219 220 // Open the vsync event node for the primary display. 221 // TODO(eieio): Move this into a platform-specific class. 222 primary_display_vsync_event_fd_ = 223 LocalHandle(kPrimaryDisplayVSyncEventFile, O_RDONLY); 224 ALOGE_IF(!primary_display_vsync_event_fd_, 225 "HardwareComposer: Failed to open vsync event node for primary " 226 "display: %s", 227 strerror(errno)); 228 229 // Open the wait pingpong status node for the primary display. 230 // TODO(eieio): Move this into a platform-specific class. 231 primary_display_wait_pp_fd_ = 232 LocalHandle(kPrimaryDisplayWaitPPEventFile, O_RDONLY); 233 ALOGE_IF( 234 !primary_display_wait_pp_fd_, 235 "HardwareComposer: Failed to open wait_pp node for primary display: %s", 236 strerror(errno)); 237 238 // Create a timerfd based on CLOCK_MONOTINIC. 239 vsync_sleep_timer_fd_.Reset(timerfd_create(CLOCK_MONOTONIC, 0)); 240 LOG_ALWAYS_FATAL_IF( 241 !vsync_sleep_timer_fd_, 242 "HardwareComposer: Failed to create vsync sleep timerfd: %s", 243 strerror(errno)); 244 245 // Connect to pose service. 246 pose_client_ = dvrPoseCreate(); 247 ALOGE_IF(!pose_client_, "HardwareComposer: Failed to create pose client"); 248 249 // Variables used to control the post thread state 250 pause_post_thread_ = false; 251 terminate_post_thread_event_fd_.Reset(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK)); 252 253 LOG_ALWAYS_FATAL_IF( 254 !terminate_post_thread_event_fd_, 255 "HardwareComposer: Failed to create terminate PostThread event fd : %s", 256 strerror(errno)); 257 258 // If get_id() is the default thread::id object, it has not been created yet 259 if (post_thread_.get_id() == std::thread::id()) { 260 post_thread_ = std::thread(&HardwareComposer::PostThread, this); 261 } else { 262 UpdateDisplayState(); 263 thread_pause_semaphore_.notify_one(); 264 } 265 266 return true; 267} 268 269bool HardwareComposer::Suspend() { 270 // Wait for any pending layer operations to finish 271 std::unique_lock<std::mutex> layer_lock(layer_mutex_); 272 273 if (IsSuspended()) { 274 ALOGE("HardwareComposer::Suspend: HardwareComposer is already suspended."); 275 return false; 276 } 277 278 PausePostThread(); 279 280 EnableVsync(false); 281 SetPowerMode(HWC_DISPLAY_PRIMARY, HWC2_POWER_MODE_OFF); 282 283 backlight_brightness_fd_.Close(); 284 primary_display_vsync_event_fd_.Close(); 285 primary_display_wait_pp_fd_.Close(); 286 vsync_sleep_timer_fd_.Close(); 287 retire_fence_fds_.clear(); 288 gpu_layer_ = nullptr; 289 290 // We have to destroy the layers before we close the hwc device 291 for (size_t i = 0; i < kMaxHardwareLayers; ++i) { 292 layers_[i]->Reset(); 293 } 294 295 active_layer_count_ = 0; 296 297 framebuffer_target_.reset(); 298 299 //hwc2_hidl_.reset(); 300 301 if (pose_client_) 302 dvrPoseDestroy(pose_client_); 303 304 return true; 305} 306 307void HardwareComposer::PausePostThread() { 308 pause_post_thread_ = true; 309 310 int error = eventfd_write(terminate_post_thread_event_fd_.Get(), 1); 311 ALOGE_IF(error, 312 "HardwareComposer::PausePostThread: could not write post " 313 "thread termination event fd : %d", 314 error); 315 316 std::unique_lock<std::mutex> wait_for_thread(thread_pause_mutex_); 317 terminate_post_thread_event_fd_.Close(); 318} 319 320DisplayMetrics HardwareComposer::GetHmdDisplayMetrics() const { 321 vec2i screen_size(display_metrics_.width, display_metrics_.height); 322 DisplayOrientation orientation = 323 (display_metrics_.width > display_metrics_.height 324 ? DisplayOrientation::kLandscape 325 : DisplayOrientation::kPortrait); 326 float dpi_x = static_cast<float>(display_metrics_.dpi.x) / 1000.0f; 327 float dpi_y = static_cast<float>(display_metrics_.dpi.y) / 1000.0f; 328 float meters_per_pixel_x = kMetersPerInch / dpi_x; 329 float meters_per_pixel_y = kMetersPerInch / dpi_y; 330 vec2 meters_per_pixel(meters_per_pixel_x, meters_per_pixel_y); 331 double frame_duration_s = 332 static_cast<double>(display_metrics_.vsync_period_ns) / 1000000000.0; 333 // TODO(hendrikw): Hard coding to 3mm. The Pixel is actually 4mm, but it 334 // seems that their tray to lens distance is wrong too, which 335 // offsets this, at least for the pixel. 336 float border_size = 0.003f; 337 return DisplayMetrics(screen_size, meters_per_pixel, border_size, 338 static_cast<float>(frame_duration_s), orientation); 339} 340 341int32_t HardwareComposer::Validate(hwc2_display_t display) { 342 uint32_t num_types; 343 uint32_t num_requests; 344 int32_t error = 345 (int32_t)hwc2_hidl_->validateDisplay(display, &num_types, &num_requests); 346 347 if (error == HWC2_ERROR_HAS_CHANGES) { 348 // TODO(skiazyk): We might need to inspect the requested changes first, but 349 // so far it seems like we shouldn't ever hit a bad state. 350 // error = hwc2_funcs_.accept_display_changes_fn_(hardware_composer_device_, 351 // display); 352 error = (int32_t)hwc2_hidl_->acceptDisplayChanges(display); 353 } 354 355 return error; 356} 357 358int32_t HardwareComposer::EnableVsync(bool enabled) { 359 return (int32_t)hwc2_hidl_->setVsyncEnabled( 360 HWC_DISPLAY_PRIMARY, 361 (Hwc2::IComposerClient::Vsync)(enabled ? HWC2_VSYNC_ENABLE 362 : HWC2_VSYNC_DISABLE)); 363} 364 365int32_t HardwareComposer::Present(hwc2_display_t display) { 366 int32_t present_fence; 367 int32_t error = (int32_t)hwc2_hidl_->presentDisplay(display, &present_fence); 368 369 // According to the documentation, this fence is signaled at the time of 370 // vsync/DMA for physical displays. 371 if (error == HWC2_ERROR_NONE) { 372 ATRACE_INT("HardwareComposer: VsyncFence", present_fence); 373 retire_fence_fds_.emplace_back(present_fence); 374 } else { 375 ATRACE_INT("HardwareComposer: PresentResult", error); 376 } 377 378 return error; 379} 380 381int32_t HardwareComposer::SetPowerMode(hwc2_display_t display, 382 hwc2_power_mode_t mode) { 383 if (mode == HWC2_POWER_MODE_OFF) { 384 EnableVsync(false); 385 } 386 387 display_on_ = mode != HWC2_POWER_MODE_OFF; 388 389 return (int32_t)hwc2_hidl_->setPowerMode( 390 display, (Hwc2::IComposerClient::PowerMode)mode); 391} 392 393int32_t HardwareComposer::GetDisplayAttribute(hwc2_display_t display, 394 hwc2_config_t config, 395 hwc2_attribute_t attribute, 396 int32_t* out_value) const { 397 return (int32_t)hwc2_hidl_->getDisplayAttribute( 398 display, config, (Hwc2::IComposerClient::Attribute)attribute, out_value); 399} 400 401int32_t HardwareComposer::GetDisplayMetrics( 402 hwc2_display_t display, hwc2_config_t config, 403 HWCDisplayMetrics* out_metrics) const { 404 int32_t ret = HWC2_ERROR_NONE; 405 406 ret = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_WIDTH, 407 &out_metrics->width); 408 if (ret != HWC2_ERROR_NONE) { 409 ALOGE("HardwareComposer: Failed to get display width"); 410 return ret; 411 } 412 413 ret = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_HEIGHT, 414 &out_metrics->height); 415 if (ret != HWC2_ERROR_NONE) { 416 ALOGE("HardwareComposer: Failed to get display height"); 417 return ret; 418 } 419 420 ret = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_VSYNC_PERIOD, 421 &out_metrics->vsync_period_ns); 422 if (ret != HWC2_ERROR_NONE) { 423 ALOGE("HardwareComposer: Failed to get display height"); 424 return ret; 425 } 426 427 ret = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_DPI_X, 428 &out_metrics->dpi.x); 429 if (ret != HWC2_ERROR_NONE) { 430 ALOGE("HardwareComposer: Failed to get display DPI X"); 431 return ret; 432 } 433 434 ret = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_DPI_Y, 435 &out_metrics->dpi.y); 436 if (ret != HWC2_ERROR_NONE) { 437 ALOGE("HardwareComposer: Failed to get display DPI Y"); 438 return ret; 439 } 440 441 return HWC2_ERROR_NONE; 442} 443 444void HardwareComposer::Dump(char* buffer, uint32_t* out_size) { 445 std::string debug_str = hwc2_hidl_->dumpDebugInfo(); 446 ALOGI("%s", debug_str.c_str()); 447 448 if (buffer == nullptr) { 449 *out_size = debug_str.size(); 450 } else { 451 std::copy(debug_str.begin(), debug_str.begin() + *out_size, buffer); 452 } 453} 454 455// TODO(skiazyk): Figure out what to do with `is_geometry_changed`. There does 456// not seem to be any equivalent in the HWC2 API, but that doesn't mean its not 457// there. 458void HardwareComposer::PostLayers(bool /*is_geometry_changed*/) { 459 ATRACE_NAME("HardwareComposer::PostLayers"); 460 461 // Setup the hardware composer layers with current buffers. 462 for (size_t i = 0; i < active_layer_count_; i++) { 463 layers_[i]->Prepare(); 464 } 465 466 // Now that we have taken in a frame from the application, we have a chance 467 // to drop the frame before passing the frame along to HWC. 468 // If the display driver has become backed up, we detect it here and then 469 // react by skipping this frame to catch up latency. 470 while (!retire_fence_fds_.empty() && 471 (!retire_fence_fds_.front() || 472 sync_wait(retire_fence_fds_.front().Get(), 0) == 0)) { 473 // There are only 2 fences in here, no performance problem to shift the 474 // array of ints. 475 retire_fence_fds_.erase(retire_fence_fds_.begin()); 476 } 477 478 const bool is_frame_pending = IsFramePendingInDriver(); 479 const bool is_fence_pending = 480 retire_fence_fds_.size() > kAllowedPendingFenceCount; 481 482 if (is_fence_pending || is_frame_pending) { 483 ATRACE_INT("frame_skip_count", ++frame_skip_count_); 484 485 ALOGW_IF(is_frame_pending, "Warning: frame already queued, dropping frame"); 486 ALOGW_IF(is_fence_pending, 487 "Warning: dropping a frame to catch up with HWC (pending = %zd)", 488 retire_fence_fds_.size()); 489 490 for (size_t i = 0; i < active_layer_count_; i++) { 491 layers_[i]->Drop(); 492 } 493 return; 494 } else { 495 // Make the transition more obvious in systrace when the frame skip happens 496 // above. 497 ATRACE_INT("frame_skip_count", 0); 498 } 499 500#if TRACE 501 for (size_t i = 0; i < active_layer_count_; i++) 502 ALOGI("HardwareComposer::PostLayers: dl[%zu] ctype=0x%08x", i, 503 layers_[i]->GetCompositionType()); 504#endif 505 506 int32_t ret = HWC2_ERROR_NONE; 507 508 std::vector<Hwc2::IComposerClient::Rect> full_region(1); 509 full_region[0].left = 0; 510 full_region[0].top = 0; 511 full_region[0].right = framebuffer_target_->width(); 512 full_region[0].bottom = framebuffer_target_->height(); 513 514 ALOGE_IF(ret, "Error setting client target : %d", ret); 515 516 ret = Validate(HWC_DISPLAY_PRIMARY); 517 if (ret) { 518 ALOGE("HardwareComposer::Validate failed; ret=%d", ret); 519 return; 520 } 521 522 ret = Present(HWC_DISPLAY_PRIMARY); 523 if (ret) { 524 ALOGE("HardwareComposer::Present failed; ret=%d", ret); 525 return; 526 } 527 528 std::vector<Hwc2::Layer> out_layers; 529 std::vector<int> out_fences; 530 ret = (int32_t)hwc2_hidl_->getReleaseFences(HWC_DISPLAY_PRIMARY, &out_layers, 531 &out_fences); 532 uint32_t num_elements = out_layers.size(); 533 534 ALOGE_IF(ret, "HardwareComposer: GetReleaseFences failed; ret=%d", ret); 535 536 // Perform post-frame bookkeeping. Unused layers are a no-op. 537 for (size_t i = 0; i < num_elements; ++i) { 538 for (size_t j = 0; j < active_layer_count_; ++j) { 539 if (layers_[j]->GetLayerHandle() == out_layers[i]) { 540 layers_[j]->Finish(out_fences[i]); 541 } 542 } 543 } 544} 545 546// TODO(skiazyk): This is a work-around for the fact that we currently do not 547// handle the case when new surfaces are introduced when displayd is not 548// in an active state. A proper-solution will require re-structuring 549// displayd a little, but hopefully this is sufficient for now. 550// For example, could this be handled in |UpdateLayerSettings| instead? 551void HardwareComposer::UpdateDisplayState() { 552 const bool has_display_surfaces = display_surfaces_.size() > 0; 553 554 if (has_display_surfaces) { 555 int32_t ret = SetPowerMode(HWC_DISPLAY_PRIMARY, HWC2_POWER_MODE_ON); 556 557 ALOGE_IF(ret, "HardwareComposer: Could not set power mode; ret=%d", ret); 558 559 EnableVsync(true); 560 } 561 // TODO(skiazyk): We need to do something about accessing this directly, 562 // supposedly there is a backlight service on the way. 563 SetBacklightBrightness(255); 564 565 if (!display_on_ && has_display_surfaces) { 566 const int error = ReadVSyncTimestamp(&last_vsync_timestamp_); 567 ALOGE_IF(error < 0, 568 "HardwareComposer::SetDisplaySurfaces: Failed to read vsync " 569 "timestamp: %s", 570 strerror(-error)); 571 } 572 573 // Trigger target-specific performance mode change. 574 property_set(kDvrPerformanceProperty, display_on_ ? "performance" : "idle"); 575} 576 577int HardwareComposer::SetDisplaySurfaces( 578 std::vector<std::shared_ptr<DisplaySurface>> surfaces) { 579 std::lock_guard<std::mutex> autolock(layer_mutex_); 580 581 ALOGI("HardwareComposer::SetDisplaySurfaces: surface count=%zd", 582 surfaces.size()); 583 584 // Figure out whether we need to update hardware layers. If this surface 585 // change does not add or remove hardware layers we can avoid display hiccups 586 // by gracefully updating only the GPU compositor layers. 587 // hardware_layers_need_update_ is reset to false by the Post thread. 588 int old_gpu_layer_count = 0; 589 int new_gpu_layer_count = 0; 590 // Look for new hardware layers and count new GPU layers. 591 for (const auto& surface : surfaces) { 592 if (!(surface->flags() & 593 DVR_DISPLAY_SURFACE_FLAGS_DISABLE_SYSTEM_DISTORTION)) 594 ++new_gpu_layer_count; 595 else if (std::find(display_surfaces_.begin(), display_surfaces_.end(), 596 surface) == display_surfaces_.end()) 597 // This is a new hardware layer, we need to update. 598 hardware_layers_need_update_ = true; 599 } 600 // Look for deleted hardware layers or compositor layers. 601 for (const auto& surface : display_surfaces_) { 602 if (!(surface->flags() & 603 DVR_DISPLAY_SURFACE_FLAGS_DISABLE_SYSTEM_DISTORTION)) 604 ++old_gpu_layer_count; 605 else if (std::find(surfaces.begin(), surfaces.end(), surface) == 606 surfaces.end()) 607 // This is a deleted hardware layer, we need to update. 608 hardware_layers_need_update_ = true; 609 } 610 // Check for compositor hardware layer transition. 611 if ((!old_gpu_layer_count && new_gpu_layer_count) || 612 (old_gpu_layer_count && !new_gpu_layer_count)) 613 hardware_layers_need_update_ = true; 614 615 display_surfaces_ = std::move(surfaces); 616 display_surfaces_updated_ = true; 617 618 // Set the chosen layer order for all surfaces. 619 for (size_t i = 0; i < display_surfaces_.size(); ++i) { 620 display_surfaces_[i]->SetLayerOrder(static_cast<int>(i)); 621 } 622 623 // TODO(skiazyk): fix this so that it is handled seamlessly with dormant/non- 624 // dormant state. 625 if (!IsSuspended()) { 626 UpdateDisplayState(); 627 } 628 629 return 0; 630} 631 632// Reads the value of the display driver wait_pingpong state. Returns 0 or 1 633// (the value of the state) on success or a negative error otherwise. 634// TODO(eieio): This is pretty driver specific, this should be moved to a 635// separate class eventually. 636int HardwareComposer::ReadWaitPPState() { 637 // Gracefully handle when the kernel does not support this feature. 638 if (!primary_display_wait_pp_fd_) 639 return 0; 640 641 const int wait_pp_fd = primary_display_wait_pp_fd_.Get(); 642 int ret, error; 643 644 ret = lseek(wait_pp_fd, 0, SEEK_SET); 645 if (ret < 0) { 646 error = errno; 647 ALOGE("HardwareComposer::ReadWaitPPState: Failed to seek wait_pp fd: %s", 648 strerror(error)); 649 return -error; 650 } 651 652 char data = -1; 653 ret = read(wait_pp_fd, &data, sizeof(data)); 654 if (ret < 0) { 655 error = errno; 656 ALOGE("HardwareComposer::ReadWaitPPState: Failed to read wait_pp state: %s", 657 strerror(error)); 658 return -error; 659 } 660 661 switch (data) { 662 case '0': 663 return 0; 664 case '1': 665 return 1; 666 default: 667 ALOGE( 668 "HardwareComposer::ReadWaitPPState: Unexpected value for wait_pp: %d", 669 data); 670 return -EINVAL; 671 } 672} 673 674// Reads the timestamp of the last vsync from the display driver. 675// TODO(eieio): This is pretty driver specific, this should be moved to a 676// separate class eventually. 677int HardwareComposer::ReadVSyncTimestamp(int64_t* timestamp) { 678 const int event_fd = primary_display_vsync_event_fd_.Get(); 679 int ret, error; 680 681 // The driver returns data in the form "VSYNC=<timestamp ns>". 682 std::array<char, 32> data; 683 data.fill('\0'); 684 685 // Seek back to the beginning of the event file. 686 ret = lseek(event_fd, 0, SEEK_SET); 687 if (ret < 0) { 688 error = errno; 689 ALOGE( 690 "HardwareComposer::ReadVSyncTimestamp: Failed to seek vsync event fd: " 691 "%s", 692 strerror(error)); 693 return -error; 694 } 695 696 // Read the vsync event timestamp. 697 ret = read(event_fd, data.data(), data.size()); 698 if (ret < 0) { 699 error = errno; 700 ALOGE_IF( 701 error != EAGAIN, 702 "HardwareComposer::ReadVSyncTimestamp: Error while reading timestamp: " 703 "%s", 704 strerror(error)); 705 return -error; 706 } 707 708 ret = sscanf(data.data(), "VSYNC=%" PRIu64, 709 reinterpret_cast<uint64_t*>(timestamp)); 710 if (ret < 0) { 711 error = errno; 712 ALOGE( 713 "HardwareComposer::ReadVSyncTimestamp: Error while parsing timestamp: " 714 "%s", 715 strerror(error)); 716 return -error; 717 } 718 719 return 0; 720} 721 722// Blocks until the next vsync event is signaled by the display driver. 723// TODO(eieio): This is pretty driver specific, this should be moved to a 724// separate class eventually. 725int HardwareComposer::BlockUntilVSync() { 726 const int event_fd = primary_display_vsync_event_fd_.Get(); 727 pollfd pfd[2] = { 728 { 729 .fd = event_fd, .events = POLLPRI, .revents = 0, 730 }, 731 // This extra event fd is to ensure that we can break out of this loop to 732 // pause the thread even when vsync is disabled, and thus no events on the 733 // vsync fd are being generated. 734 { 735 .fd = terminate_post_thread_event_fd_.Get(), 736 .events = POLLPRI | POLLIN, 737 .revents = 0, 738 }, 739 }; 740 int ret, error; 741 do { 742 ret = poll(pfd, 2, -1); 743 error = errno; 744 ALOGW_IF(ret < 0, 745 "HardwareComposer::BlockUntilVSync: Error while waiting for vsync " 746 "event: %s (%d)", 747 strerror(error), error); 748 } while (ret < 0 && error == EINTR); 749 750 return ret < 0 ? -error : 0; 751} 752 753// Waits for the next vsync and returns the timestamp of the vsync event. If 754// vsync already passed since the last call, returns the latest vsync timestamp 755// instead of blocking. This method updates the last_vsync_timeout_ in the 756// process. 757// 758// TODO(eieio): This is pretty driver specific, this should be moved to a 759// separate class eventually. 760int HardwareComposer::WaitForVSync(int64_t* timestamp) { 761 int error; 762 763 // Get the current timestamp and decide what to do. 764 while (true) { 765 int64_t current_vsync_timestamp; 766 error = ReadVSyncTimestamp(¤t_vsync_timestamp); 767 if (error < 0 && error != -EAGAIN) 768 return error; 769 770 if (error == -EAGAIN) { 771 // Vsync was turned off, wait for the next vsync event. 772 error = BlockUntilVSync(); 773 if (error < 0) 774 return error; 775 776 // If a request to pause the post thread was given, exit immediately 777 if (IsSuspended()) { 778 return 0; 779 } 780 781 // Try again to get the timestamp for this new vsync interval. 782 continue; 783 } 784 785 // Check that we advanced to a later vsync interval. 786 if (TimestampGT(current_vsync_timestamp, last_vsync_timestamp_)) { 787 *timestamp = last_vsync_timestamp_ = current_vsync_timestamp; 788 return 0; 789 } 790 791 // See how close we are to the next expected vsync. If we're within 1ms, 792 // sleep for 1ms and try again. 793 const int64_t ns_per_frame = display_metrics_.vsync_period_ns; 794 const int64_t threshold_ns = 1000000; 795 796 const int64_t next_vsync_est = last_vsync_timestamp_ + ns_per_frame; 797 const int64_t distance_to_vsync_est = next_vsync_est - GetSystemClockNs(); 798 799 if (distance_to_vsync_est > threshold_ns) { 800 // Wait for vsync event notification. 801 error = BlockUntilVSync(); 802 if (error < 0) 803 return error; 804 805 // Again, exit immediately if the thread was requested to pause 806 if (IsSuspended()) { 807 return 0; 808 } 809 } else { 810 // Sleep for a short time before retrying. 811 std::this_thread::sleep_for(std::chrono::milliseconds(1)); 812 } 813 } 814} 815 816int HardwareComposer::SleepUntil(int64_t wakeup_timestamp) { 817 const int timer_fd = vsync_sleep_timer_fd_.Get(); 818 const itimerspec wakeup_itimerspec = { 819 .it_interval = {.tv_sec = 0, .tv_nsec = 0}, 820 .it_value = NsToTimespec(wakeup_timestamp), 821 }; 822 int ret = 823 timerfd_settime(timer_fd, TFD_TIMER_ABSTIME, &wakeup_itimerspec, nullptr); 824 int error = errno; 825 if (ret < 0) { 826 ALOGE("HardwareComposer::SleepUntil: Failed to set timerfd: %s", 827 strerror(error)); 828 return -error; 829 } 830 831 // Wait for the timer by reading the expiration count. 832 uint64_t expiration_count; 833 ret = read(timer_fd, &expiration_count, sizeof(expiration_count)); 834 if (ret < 0) { 835 ALOGE("HardwareComposer::SleepUntil: Failed to wait for timerfd: %s", 836 strerror(error)); 837 return -error; 838 } 839 840 return 0; 841} 842 843void HardwareComposer::PostThread() { 844 // NOLINTNEXTLINE(runtime/int) 845 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>("PostThread"), 0, 0, 0); 846 847 std::unique_lock<std::mutex> thread_lock(thread_pause_mutex_); 848 849 // Set the scheduler to SCHED_FIFO with high priority. 850 int error = dvrSetSchedulerClass(0, "graphics:high"); 851 LOG_ALWAYS_FATAL_IF( 852 error < 0, 853 "HardwareComposer::PostThread: Failed to set scheduler class: %s", 854 strerror(-error)); 855 error = dvrSetCpuPartition(0, "/system/performance"); 856 LOG_ALWAYS_FATAL_IF( 857 error < 0, 858 "HardwareComposer::PostThread: Failed to set cpu partition: %s", 859 strerror(-error)); 860 861 // Force the layers to be setup at least once. 862 display_surfaces_updated_ = true; 863 864 // Initialize the GPU compositor. 865 LOG_ALWAYS_FATAL_IF(!compositor_.Initialize(GetHmdDisplayMetrics()), 866 "Failed to initialize the compositor"); 867 868 const int64_t ns_per_frame = display_metrics_.vsync_period_ns; 869 const int64_t photon_offset_ns = GetPosePredictionTimeOffset(ns_per_frame); 870 871 // TODO(jbates) Query vblank time from device, when such an API is available. 872 // This value (6.3%) was measured on A00 in low persistence mode. 873 int64_t vblank_ns = ns_per_frame * 63 / 1000; 874 int64_t right_eye_photon_offset_ns = (ns_per_frame - vblank_ns) / 2; 875 876 // Check property for overriding right eye offset value. 877 right_eye_photon_offset_ns = 878 property_get_int64(kRightEyeOffsetProperty, right_eye_photon_offset_ns); 879 880 // The list of surfaces the compositor should attempt to render. This is set 881 // at the start of each frame. 882 std::vector<std::shared_ptr<DisplaySurface>> compositor_surfaces; 883 compositor_surfaces.reserve(2); 884 885 // Our history of frame times. This is used to get a better estimate of how 886 // long the next frame will take, to set a schedule for EDS. 887 FrameTimeHistory frame_time_history; 888 889 // The backlog is used to allow us to start rendering the next frame before 890 // the previous frame has finished, and still get an accurate measurement of 891 // frame duration. 892 std::vector<FrameTimeMeasurementRecord> frame_time_backlog; 893 constexpr int kFrameTimeBacklogMax = 2; 894 frame_time_backlog.reserve(kFrameTimeBacklogMax); 895 896 // Storage for retrieving fence info. 897 FenceInfoBuffer fence_info_buffer; 898 899 while (1) { 900 ATRACE_NAME("HardwareComposer::PostThread"); 901 902 while (IsSuspended()) { 903 ALOGI("HardwareComposer::PostThread: Post thread pause requested."); 904 thread_pause_semaphore_.wait(thread_lock); 905 // The layers will need to be updated since they were deleted previously 906 display_surfaces_updated_ = true; 907 hardware_layers_need_update_ = true; 908 } 909 910 int64_t vsync_timestamp = 0; 911 { 912 std::array<char, 128> buf; 913 snprintf(buf.data(), buf.size(), "wait_vsync|vsync=%d|", 914 vsync_count_ + 1); 915 ATRACE_NAME(buf.data()); 916 917 error = WaitForVSync(&vsync_timestamp); 918 ALOGE_IF( 919 error < 0, 920 "HardwareComposer::PostThread: Failed to wait for vsync event: %s", 921 strerror(-error)); 922 923 // Don't bother processing this frame if a pause was requested 924 if (IsSuspended()) { 925 continue; 926 } 927 } 928 929 ++vsync_count_; 930 931 static double last_print_time = -1; 932 double current_time = GetSystemClockSec(); 933 if (last_print_time < 0 || current_time - last_print_time > 3) { 934 last_print_time = current_time; 935 } 936 937 if (pose_client_) { 938 // Signal the pose service with vsync info. 939 // Display timestamp is in the middle of scanout. 940 privateDvrPoseNotifyVsync(pose_client_, vsync_count_, 941 vsync_timestamp + photon_offset_ns, 942 ns_per_frame, right_eye_photon_offset_ns); 943 } 944 945 bool layer_config_changed = UpdateLayerConfig(&compositor_surfaces); 946 947 if (layer_config_changed) { 948 frame_time_history.ResetWithSeed( 949 GuessFrameTime(compositor_surfaces.size())); 950 frame_time_backlog.clear(); 951 } else { 952 UpdateFrameTimeHistory(&frame_time_backlog, kFrameTimeBacklogMax, 953 &fence_info_buffer, &frame_time_history); 954 } 955 956 // Get our current best estimate at how long the next frame will take to 957 // render, based on how long previous frames took to render. Use this 958 // estimate to decide when to wake up for EDS. 959 int64_t frame_time_estimate = 960 frame_time_history.GetSampleCount() == 0 961 ? GuessFrameTime(compositor_surfaces.size()) 962 : frame_time_history.GetAverage(); 963 frame_time_estimate = std::max(frame_time_estimate, kFrameTimeEstimateMin); 964 DebugHudData::data.hwc_latency = frame_time_estimate; 965 966 // Signal all of the vsync clients. Because absolute time is used for the 967 // wakeup time below, this can take a little time if necessary. 968 if (vsync_callback_) 969 vsync_callback_(HWC_DISPLAY_PRIMARY, vsync_timestamp, frame_time_estimate, 970 vsync_count_); 971 972 { 973 // Sleep until async EDS wakeup time. 974 ATRACE_NAME("sleep"); 975 976 int64_t display_time_est = vsync_timestamp + ns_per_frame; 977 int64_t now = GetSystemClockNs(); 978 int64_t frame_finish_time_est = now + frame_time_estimate; 979 int64_t sleep_time_ns = display_time_est - now - frame_time_estimate; 980 981 ATRACE_INT64("sleep_time_ns", sleep_time_ns); 982 if (frame_finish_time_est - display_time_est >= kFrameSkipThresholdNs) { 983 ATRACE_INT("frame_skip_count", ++frame_skip_count_); 984 ALOGE( 985 "HardwareComposer::PostThread: Missed frame schedule, drop " 986 "frame. Expected frame miss: %.1fms", 987 static_cast<double>(frame_finish_time_est - display_time_est) / 988 1000000); 989 990 // There are several reasons we might skip a frame, but one possibility 991 // is we mispredicted the frame time. Clear out the frame time history. 992 frame_time_history.ResetWithSeed( 993 GuessFrameTime(compositor_surfaces.size())); 994 frame_time_backlog.clear(); 995 DebugHudData::data.hwc_frame_stats.SkipFrame(); 996 997 continue; 998 } else { 999 // Make the transition more obvious in systrace when the frame skip 1000 // happens above. 1001 ATRACE_INT("frame_skip_count", 0); 1002 } 1003 1004 if (sleep_time_ns > 0) { 1005 error = SleepUntil(display_time_est - frame_time_estimate); 1006 ALOGE_IF(error < 0, "HardwareComposer::PostThread: Failed to sleep: %s", 1007 strerror(-error)); 1008 } 1009 } 1010 1011 DebugHudData::data.hwc_frame_stats.AddFrame(); 1012 1013 int64_t frame_start_time = GetSystemClockNs(); 1014 1015 // Setup the output buffer for the compositor. This needs to happen before 1016 // you draw with the compositor. 1017 if (gpu_layer_ != nullptr) { 1018 gpu_layer_->UpdateDirectBuffer(compositor_.GetBuffer()); 1019 } 1020 1021 // Call PostLayers now before performing the GL code for the compositor to 1022 // avoid missing the deadline that can cause the lower-level hwc to get 1023 // permanently backed up. 1024 PostLayers(layer_config_changed); 1025 1026 PostCompositorBuffers(compositor_surfaces); 1027 1028 if (gpu_layer_ != nullptr) { 1029 // Note, with scanline racing, this draw is timed along with the post 1030 // layers to finish just in time. 1031 LocalHandle frame_fence_fd; 1032 compositor_.DrawFrame(vsync_count_ + 1, &frame_fence_fd); 1033 if (frame_fence_fd) { 1034 LOG_ALWAYS_FATAL_IF(frame_time_backlog.size() >= kFrameTimeBacklogMax, 1035 "Frame time backlog exceeds capacity"); 1036 frame_time_backlog.push_back( 1037 {frame_start_time, std::move(frame_fence_fd)}); 1038 } 1039 } else if (!layer_config_changed) { 1040 frame_time_history.AddSample(GetSystemClockNs() - frame_start_time); 1041 } 1042 1043 HandlePendingScreenshots(); 1044 } 1045 1046 // TODO(skiazyk): Currently the compositor is not fully releasing its EGL 1047 // context, which seems to prevent the thread from exiting properly. 1048 // This shouldn't be too hard to address, I just don't have time right now. 1049 compositor_.Shutdown(); 1050} 1051 1052bool HardwareComposer::UpdateLayerConfig( 1053 std::vector<std::shared_ptr<DisplaySurface>>* compositor_surfaces) { 1054 std::lock_guard<std::mutex> autolock(layer_mutex_); 1055 1056 if (!display_surfaces_updated_) 1057 return false; 1058 1059 display_surfaces_updated_ = false; 1060 DebugHudData::data.ResetLayers(); 1061 1062 // Update compositor layers. 1063 { 1064 ATRACE_NAME("UpdateLayerConfig_GpuLayers"); 1065 compositor_.UpdateSurfaces(display_surfaces_); 1066 compositor_surfaces->clear(); 1067 for (size_t i = 0; i < display_surfaces_.size(); ++i) { 1068 const auto& surface = display_surfaces_[i]; 1069 if (!(surface->flags() & 1070 DVR_DISPLAY_SURFACE_FLAGS_DISABLE_SYSTEM_DISTORTION)) { 1071 compositor_surfaces->push_back(surface); 1072 } 1073 } 1074 } 1075 1076 if (!hardware_layers_need_update_) 1077 return true; 1078 1079 // Update hardware layers. 1080 1081 ATRACE_NAME("UpdateLayerConfig_HwLayers"); 1082 hardware_layers_need_update_ = false; 1083 1084 // Update the display layers in a non-destructive fashion. 1085 1086 // Create a map from surface id to hardware layer 1087 std::map<int, Layer*> display_surface_layers; 1088 1089 for (size_t i = 0; i < active_layer_count_; ++i) { 1090 auto layer = layers_[i]; 1091 int surface_id = layer->GetSurfaceId(); 1092 1093 auto found = 1094 std::find_if(display_surfaces_.begin(), display_surfaces_.end(), 1095 [surface_id](const auto& surface) { 1096 return surface->surface_id() == surface_id; 1097 }); 1098 1099 if (found != display_surfaces_.end()) { 1100 display_surface_layers[surface_id] = layer; 1101 } 1102 } 1103 1104 bool has_gpu_layer = std::any_of( 1105 display_surfaces_.begin(), display_surfaces_.end(), 1106 [](const auto& surface) { 1107 return !(surface->flags() & 1108 DVR_DISPLAY_SURFACE_FLAGS_DISABLE_SYSTEM_DISTORTION); 1109 }); 1110 1111 if (!has_gpu_layer) { 1112 gpu_layer_ = nullptr; 1113 } 1114 1115 auto is_layer_active = [&display_surface_layers, has_gpu_layer](auto layer) { 1116 int surface_id = layer->GetSurfaceId(); 1117 if (surface_id >= 0) { 1118 return display_surface_layers.count(surface_id) > 0; 1119 } else { 1120 return has_gpu_layer; 1121 } 1122 }; 1123 1124 // Compress the in-use layers to the top of the list 1125 auto part = std::partition( 1126 layers_.begin(), layers_.begin() + active_layer_count_, is_layer_active); 1127 1128 size_t new_active_layer_count = part - layers_.begin(); 1129 1130 // Clear any unused layers 1131 for (size_t i = new_active_layer_count; i < active_layer_count_; ++i) { 1132 layers_[i]->Reset(); 1133 } 1134 1135 active_layer_count_ = new_active_layer_count; 1136 1137 bool gpu_layer_applied = false; 1138 1139 // Create/update all of the hardware layers 1140 for (size_t i = 0; i < display_surfaces_.size(); ++i) { 1141 const auto& surface = display_surfaces_[i]; 1142 bool is_hw_surface = 1143 surface->flags() & DVR_DISPLAY_SURFACE_FLAGS_DISABLE_SYSTEM_DISTORTION; 1144 hwc2_blend_mode_t blending = 1145 i == 0 ? HWC2_BLEND_MODE_NONE : HWC2_BLEND_MODE_COVERAGE; 1146 1147 DebugHudData::data.SetLayerInfo( 1148 i, surface->width(), surface->height(), 1149 !!(surface->flags() & DVR_DISPLAY_SURFACE_FLAGS_GEOMETRY_SEPARATE_2)); 1150 1151 if (!is_hw_surface && gpu_layer_applied) { 1152 continue; 1153 } 1154 1155 Layer* target_layer; 1156 bool existing_layer = false; 1157 1158 if (is_hw_surface) { 1159 auto it = display_surface_layers.find(surface->surface_id()); 1160 1161 if (it != display_surface_layers.end()) { 1162 target_layer = it->second; 1163 existing_layer = true; 1164 } 1165 } else if (gpu_layer_ != nullptr) { 1166 target_layer = gpu_layer_; 1167 existing_layer = true; 1168 } 1169 1170 if (!existing_layer) { 1171 if (active_layer_count_ >= kMaxHardwareLayers) { 1172 ALOGI("HardwareComposer: More than %d hardware layers requested.", 1173 kMaxHardwareLayers); 1174 break; 1175 } else { 1176 target_layer = layers_[active_layer_count_]; 1177 ++active_layer_count_; 1178 } 1179 1180 ALOGD_IF(TRACE, 1181 "HardwareComposer::UpdateLayerConfig: (new) surface_id=%d -> " 1182 "layer=%zd", 1183 surface->surface_id(), i); 1184 1185 if (is_hw_surface) { 1186 target_layer->Setup(surface, blending, display_transform_, 1187 HWC2_COMPOSITION_DEVICE, i); 1188 } else { 1189 gpu_layer_ = target_layer; 1190 target_layer->Setup(compositor_.GetBuffer(), blending, 1191 display_transform_, HWC2_COMPOSITION_DEVICE, i); 1192 } 1193 } else { 1194 ALOGD_IF(TRACE, 1195 "HardwareComposer::UpdateLayerConfig: (retained) surface_id=%d " 1196 "-> layer=%zd", 1197 surface->surface_id(), i); 1198 1199 target_layer->SetBlending(blending); 1200 target_layer->SetZOrderIndex(i); 1201 target_layer->UpdateLayerSettings(); 1202 } 1203 1204 gpu_layer_applied = !is_hw_surface; 1205 } 1206 1207 ALOGD_IF(TRACE, "HardwareComposer::UpdateLayerConfig: %zd active layers", 1208 active_layer_count_); 1209 1210 return true; 1211} 1212 1213void HardwareComposer::PostCompositorBuffers( 1214 const std::vector<std::shared_ptr<DisplaySurface>>& compositor_surfaces) { 1215 ATRACE_NAME("PostCompositorBuffers"); 1216 for (const auto& surface : compositor_surfaces) { 1217 compositor_.PostBuffer(surface); 1218 } 1219} 1220 1221void HardwareComposer::UpdateFrameTimeHistory( 1222 std::vector<FrameTimeMeasurementRecord>* backlog, int backlog_max, 1223 FenceInfoBuffer* fence_info_buffer, FrameTimeHistory* history) { 1224 while (!backlog->empty()) { 1225 const auto& frame_time_record = backlog->front(); 1226 int64_t end_time = 0; 1227 bool frame_finished = CheckFrameFinished(frame_time_record.fence.Get(), 1228 fence_info_buffer, &end_time); 1229 if (frame_finished) { 1230 int64_t frame_duration = end_time - frame_time_record.start_time; 1231 history->AddSample(frame_duration); 1232 // Our backlog is tiny (2 elements), so erasing from the front is ok 1233 backlog->erase(backlog->begin()); 1234 } else { 1235 break; 1236 } 1237 } 1238 1239 if (backlog->size() == static_cast<size_t>(backlog_max)) { 1240 // Yikes, something must've gone wrong if our oldest frame hasn't finished 1241 // yet. Give up on waiting for it. 1242 const auto& stale_frame_time_record = backlog->front(); 1243 int64_t frame_duration = 1244 GetSystemClockNs() - stale_frame_time_record.start_time; 1245 backlog->erase(backlog->begin()); 1246 history->AddSample(frame_duration); 1247 ALOGW("Frame didn't finish after %.1fms", 1248 static_cast<double>(frame_duration) / 1000000); 1249 } 1250} 1251 1252bool HardwareComposer::CheckFrameFinished(int frame_fence_fd, 1253 FenceInfoBuffer* fence_info_buffer, 1254 int64_t* timestamp) { 1255 int result = -1; 1256 int sync_result = sync_wait(frame_fence_fd, 0); 1257 if (sync_result == 0) { 1258 result = 1259 GetFenceSignaledTimestamp(frame_fence_fd, fence_info_buffer, timestamp); 1260 if (result < 0) { 1261 ALOGE("Failed getting signaled timestamp from fence"); 1262 } 1263 } else if (errno != ETIME) { 1264 ALOGE("sync_wait on frame fence failed"); 1265 } 1266 return result >= 0; 1267} 1268 1269void HardwareComposer::HandlePendingScreenshots() { 1270 // Take a screenshot of the requested layer, if available. 1271 // TODO(eieio): Look into using virtual displays to composite the layer stack 1272 // into a single output buffer that can be returned to the screenshot clients. 1273 if (active_layer_count_ > 0) { 1274 if (auto screenshot_service = ScreenshotService::GetInstance()) { 1275 if (screenshot_service->IsScreenshotRequestPending()) { 1276 ATRACE_NAME("screenshot"); 1277 screenshot_service->TakeIfNeeded(layers_, compositor_); 1278 } 1279 } else { 1280 ALOGW( 1281 "HardwareComposer::HandlePendingScreenshots: Failed to get " 1282 "screenshot service!"); 1283 } 1284 } 1285} 1286 1287void HardwareComposer::SetVSyncCallback(VSyncCallback callback) { 1288 vsync_callback_ = callback; 1289} 1290 1291void HardwareComposer::HwcRefresh(hwc2_callback_data_t /*data*/, 1292 hwc2_display_t /*display*/) { 1293 // TODO(eieio): implement invalidate callbacks. 1294} 1295 1296void HardwareComposer::HwcVSync(hwc2_callback_data_t /*data*/, 1297 hwc2_display_t /*display*/, 1298 int64_t /*timestamp*/) { 1299 ATRACE_NAME(__PRETTY_FUNCTION__); 1300 // Intentionally empty. HWC may require a callback to be set to enable vsync 1301 // signals. We bypass this callback thread by monitoring the vsync event 1302 // directly, but signals still need to be enabled. 1303} 1304 1305void HardwareComposer::HwcHotplug(hwc2_callback_data_t /*callbackData*/, 1306 hwc2_display_t /*display*/, 1307 hwc2_connection_t /*connected*/) { 1308 // TODO(eieio): implement display hotplug callbacks. 1309} 1310 1311void HardwareComposer::SetBacklightBrightness(int brightness) { 1312 if (backlight_brightness_fd_) { 1313 std::array<char, 32> text; 1314 const int length = snprintf(text.data(), text.size(), "%d", brightness); 1315 write(backlight_brightness_fd_.Get(), text.data(), length); 1316 } 1317} 1318 1319Layer::Layer() 1320 : hwc2_hidl_(nullptr), 1321 surface_index_(-1), 1322 hardware_composer_layer_(0), 1323 display_metrics_(nullptr), 1324 blending_(HWC2_BLEND_MODE_NONE), 1325 transform_(HWC_TRANSFORM_NONE), 1326 composition_type_(HWC2_COMPOSITION_DEVICE), 1327 surface_rect_functions_applied_(false) {} 1328 1329void Layer::Initialize(Hwc2::Composer* hwc2_hidl, HWCDisplayMetrics* metrics) { 1330 hwc2_hidl_ = hwc2_hidl; 1331 display_metrics_ = metrics; 1332} 1333 1334void Layer::Reset() { 1335 const int ret = acquired_buffer_.Release(std::move(release_fence_)); 1336 ALOGE_IF(ret < 0, "Layer::Reset: failed to release buffer: %s", 1337 strerror(-ret)); 1338 1339 if (hwc2_hidl_ != nullptr && hardware_composer_layer_) { 1340 hwc2_hidl_->destroyLayer(HWC_DISPLAY_PRIMARY, hardware_composer_layer_); 1341 hardware_composer_layer_ = 0; 1342 } 1343 1344 surface_index_ = static_cast<size_t>(-1); 1345 blending_ = HWC2_BLEND_MODE_NONE; 1346 transform_ = HWC_TRANSFORM_NONE; 1347 composition_type_ = HWC2_COMPOSITION_DEVICE; 1348 direct_buffer_ = nullptr; 1349 surface_ = nullptr; 1350 acquire_fence_fd_.Close(); 1351 surface_rect_functions_applied_ = false; 1352} 1353 1354void Layer::Setup(const std::shared_ptr<DisplaySurface>& surface, 1355 hwc2_blend_mode_t blending, hwc_transform_t transform, 1356 hwc2_composition_t composition_type, size_t index) { 1357 Reset(); 1358 surface_index_ = index; 1359 surface_ = surface; 1360 blending_ = blending; 1361 transform_ = transform; 1362 composition_type_ = composition_type; 1363 CommonLayerSetup(); 1364} 1365 1366void Layer::Setup(const std::shared_ptr<IonBuffer>& buffer, 1367 hwc2_blend_mode_t blending, hwc_transform_t transform, 1368 hwc2_composition_t composition_type, size_t z_order) { 1369 Reset(); 1370 surface_index_ = z_order; 1371 direct_buffer_ = buffer; 1372 blending_ = blending; 1373 transform_ = transform; 1374 composition_type_ = composition_type; 1375 CommonLayerSetup(); 1376} 1377 1378void Layer::UpdateDirectBuffer(const std::shared_ptr<IonBuffer>& buffer) { 1379 direct_buffer_ = buffer; 1380} 1381 1382void Layer::SetBlending(hwc2_blend_mode_t blending) { blending_ = blending; } 1383 1384void Layer::SetZOrderIndex(int z_index) { surface_index_ = z_index; } 1385 1386IonBuffer* Layer::GetBuffer() { 1387 if (direct_buffer_) 1388 return direct_buffer_.get(); 1389 else if (acquired_buffer_.IsAvailable()) 1390 return acquired_buffer_.buffer()->buffer(); 1391 else 1392 return nullptr; 1393} 1394 1395void Layer::UpdateLayerSettings() { 1396 if (!IsLayerSetup()) { 1397 ALOGE("HardwareComposer: Trying to update layers data on an unused layer."); 1398 return; 1399 } 1400 1401 int32_t ret = HWC2_ERROR_NONE; 1402 1403 hwc2_display_t display = HWC_DISPLAY_PRIMARY; 1404 1405 ret = (int32_t)hwc2_hidl_->setLayerCompositionType( 1406 display, hardware_composer_layer_, 1407 (Hwc2::IComposerClient::Composition)composition_type_); 1408 ALOGE_IF(ret, "HardwareComposer: Error setting layer composition type : %d", 1409 ret); 1410 // ret = (int32_t) hwc2_hidl_->setLayerTransform(display, 1411 // hardware_composer_layer_, 1412 // (Hwc2::IComposerClient::Transform) 1413 // transform_); 1414 // ALOGE_IF(ret, "HardwareComposer: Error setting layer transform : %d", ret); 1415 1416 // ret = hwc2_funcs_->set_layer_blend_mode_fn_( 1417 // hardware_composer_device_, display, hardware_composer_layer_, 1418 // blending_); 1419 ret = (int32_t)hwc2_hidl_->setLayerBlendMode( 1420 display, hardware_composer_layer_, 1421 (Hwc2::IComposerClient::BlendMode)blending_); 1422 ALOGE_IF(ret, "HardwareComposer: Error setting layer blend mode : %d", ret); 1423 1424 Hwc2::IComposerClient::Rect display_frame; 1425 display_frame.left = 0; 1426 display_frame.top = 0; 1427 display_frame.right = display_metrics_->width; 1428 display_frame.bottom = display_metrics_->height; 1429 ret = (int32_t)hwc2_hidl_->setLayerDisplayFrame( 1430 display, hardware_composer_layer_, display_frame); 1431 ALOGE_IF(ret, "HardwareComposer: Error setting layer display frame : %d", 1432 ret); 1433 1434 std::vector<Hwc2::IComposerClient::Rect> visible_region(1); 1435 visible_region[0] = display_frame; 1436 ret = (int32_t)hwc2_hidl_->setLayerVisibleRegion( 1437 display, hardware_composer_layer_, visible_region); 1438 ALOGE_IF(ret, "HardwareComposer: Error setting layer visible region : %d", 1439 ret); 1440 1441 ret = (int32_t)hwc2_hidl_->setLayerPlaneAlpha(display, 1442 hardware_composer_layer_, 1.0f); 1443 ALOGE_IF(ret, "HardwareComposer: Error setting layer plane alpha : %d", ret); 1444 1445 ret = (int32_t)hwc2_hidl_->setLayerZOrder(display, hardware_composer_layer_, 1446 surface_index_); 1447 ALOGE_IF(ret, "HardwareComposer: Error, setting z order index : %d", ret); 1448} 1449 1450void Layer::CommonLayerSetup() { 1451 int32_t ret = (int32_t)hwc2_hidl_->createLayer(HWC_DISPLAY_PRIMARY, 1452 &hardware_composer_layer_); 1453 1454 ALOGE_IF(ret, 1455 "HardwareComposer: Failed to create layer on primary display : %d", 1456 ret); 1457 1458 UpdateLayerSettings(); 1459} 1460 1461void Layer::Prepare() { 1462 int right, bottom; 1463 buffer_handle_t handle; 1464 1465 if (surface_) { 1466 // Only update the acquired buffer when one is either available or this is 1467 // the first time through. 1468 if (surface_->IsBufferAvailable()) { 1469 // If we previously set this to a solid color layer to stall for time, 1470 // revert it to a device layer. 1471 if (acquired_buffer_.IsEmpty() && 1472 composition_type_ != HWC2_COMPOSITION_DEVICE) { 1473 composition_type_ = HWC2_COMPOSITION_DEVICE; 1474 hwc2_hidl_->setLayerCompositionType( 1475 HWC_DISPLAY_PRIMARY, hardware_composer_layer_, 1476 (Hwc2::IComposerClient::Composition)HWC2_COMPOSITION_DEVICE); 1477 } 1478 1479 DebugHudData::data.AddLayerFrame(surface_index_); 1480 acquired_buffer_.Release(std::move(release_fence_)); 1481 acquired_buffer_ = surface_->AcquireCurrentBuffer(); 1482 1483 // Basic latency stopgap for when the application misses a frame: 1484 // If the application recovers on the 2nd or 3rd (etc) frame after 1485 // missing, this code will skip a frame to catch up by checking if 1486 // the next frame is also available. 1487 if (surface_->IsBufferAvailable()) { 1488 DebugHudData::data.SkipLayerFrame(surface_index_); 1489 ATRACE_NAME("DropToCatchUp"); 1490 ATRACE_ASYNC_END("BufferPost", acquired_buffer_.buffer()->id()); 1491 acquired_buffer_ = surface_->AcquireCurrentBuffer(); 1492 } 1493 ATRACE_ASYNC_END("BufferPost", acquired_buffer_.buffer()->id()); 1494 } else if (acquired_buffer_.IsEmpty()) { 1495 // While we are waiting for a buffer, set this to be an empty layer 1496 if (composition_type_ != HWC2_COMPOSITION_SOLID_COLOR) { 1497 composition_type_ = HWC2_COMPOSITION_SOLID_COLOR; 1498 hwc2_hidl_->setLayerCompositionType( 1499 HWC_DISPLAY_PRIMARY, hardware_composer_layer_, 1500 (Hwc2::IComposerClient::Composition)HWC2_COMPOSITION_SOLID_COLOR); 1501 1502 Hwc2::IComposerClient::Color layer_color = { 1503 0, 0, 0, 0, 1504 }; 1505 hwc2_hidl_->setLayerColor(HWC_DISPLAY_PRIMARY, hardware_composer_layer_, 1506 layer_color); 1507 } 1508 return; 1509 } 1510 right = acquired_buffer_.buffer()->width(); 1511 bottom = acquired_buffer_.buffer()->height(); 1512 handle = acquired_buffer_.buffer()->native_handle(); 1513 acquire_fence_fd_.Reset(acquired_buffer_.ClaimAcquireFence().Release()); 1514 } else { 1515 right = direct_buffer_->width(); 1516 bottom = direct_buffer_->height(); 1517 handle = direct_buffer_->handle(); 1518 acquire_fence_fd_.Close(); 1519 } 1520 1521 int32_t ret = HWC2_ERROR_NONE; 1522 1523 if (composition_type_ == HWC2_COMPOSITION_DEVICE) { 1524 ret = (int32_t)hwc2_hidl_->setLayerBuffer(HWC_DISPLAY_PRIMARY, 1525 hardware_composer_layer_, handle, 1526 acquire_fence_fd_.Get()); 1527 1528 ALOGE_IF(ret, "HardwareComposer: Error setting layer buffer : %d", ret); 1529 } 1530 1531 if (!surface_rect_functions_applied_) { 1532 Hwc2::IComposerClient::FRect crop_rect = { 1533 0, 0, static_cast<float>(right), static_cast<float>(bottom), 1534 }; 1535 hwc2_hidl_->setLayerSourceCrop(HWC_DISPLAY_PRIMARY, 1536 hardware_composer_layer_, crop_rect); 1537 1538 ALOGE_IF(ret, "HardwareComposer: Error setting layer source crop : %d", 1539 ret); 1540 1541// TODO(skiazyk): why is this ifdef'd out. Is if a driver-specific issue where 1542// it must/cannot be called? 1543#ifdef QCOM_BSP 1544 hwc_rect_t damage_rect = { 1545 0, 0, right, bottom, 1546 }; 1547 hwc_region_t damage = { 1548 1, &damage_rect, 1549 }; 1550 // ret = hwc2_funcs_->set_layer_surface_damage( 1551 // hardware_composer_device_, HWC_DISPLAY_PRIMARY, 1552 // hardware_composer_layer_, damage); 1553 // uses a std::vector as the listing 1554 // hwc2_hidl_->setLayerSurfaceDamage(HWC_DISPLAY_PRIMARY, 1555 // hardware_composer_layer_, vector here); 1556 1557 ALOGE_IF(ret, "HardwareComposer: Error settings layer surface damage : %d", 1558 ret); 1559#endif 1560 1561 surface_rect_functions_applied_ = true; 1562 } 1563} 1564 1565void Layer::Finish(int release_fence_fd) { 1566 release_fence_.Reset(release_fence_fd); 1567} 1568 1569void Layer::Drop() { acquire_fence_fd_.Close(); } 1570 1571} // namespace dvr 1572} // namespace android 1573