1 /* 2 * Copyright 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 //#define LOG_NDEBUG 0 18 19 #undef LOG_TAG 20 #define LOG_TAG "HWC2On1Adapter" 21 #define ATRACE_TAG ATRACE_TAG_GRAPHICS 22 23 #include "HWC2On1Adapter.h" 24 25 #include <hardware/hwcomposer.h> 26 #include <log/log.h> 27 #include <utils/Trace.h> 28 29 #include <cstdlib> 30 #include <chrono> 31 #include <inttypes.h> 32 #include <sstream> 33 34 using namespace std::chrono_literals; 35 36 static bool operator==(const hwc_color_t& lhs, const hwc_color_t& rhs) { 37 return lhs.r == rhs.r && 38 lhs.g == rhs.g && 39 lhs.b == rhs.b && 40 lhs.a == rhs.a; 41 } 42 43 static bool operator==(const hwc_rect_t& lhs, const hwc_rect_t& rhs) { 44 return lhs.left == rhs.left && 45 lhs.top == rhs.top && 46 lhs.right == rhs.right && 47 lhs.bottom == rhs.bottom; 48 } 49 50 static bool operator==(const hwc_frect_t& lhs, const hwc_frect_t& rhs) { 51 return lhs.left == rhs.left && 52 lhs.top == rhs.top && 53 lhs.right == rhs.right && 54 lhs.bottom == rhs.bottom; 55 } 56 57 template <typename T> 58 static inline bool operator!=(const T& lhs, const T& rhs) 59 { 60 return !(lhs == rhs); 61 } 62 63 static uint8_t getMinorVersion(struct hwc_composer_device_1* device) 64 { 65 auto version = device->common.version & HARDWARE_API_VERSION_2_MAJ_MIN_MASK; 66 return (version >> 16) & 0xF; 67 } 68 69 template <typename PFN, typename T> 70 static hwc2_function_pointer_t asFP(T function) 71 { 72 static_assert(std::is_same<PFN, T>::value, "Incompatible function pointer"); 73 return reinterpret_cast<hwc2_function_pointer_t>(function); 74 } 75 76 using namespace HWC2; 77 78 static constexpr Attribute ColorTransform = static_cast<Attribute>(6); 79 80 namespace android { 81 82 void HWC2On1Adapter::DisplayContentsDeleter::operator()( 83 hwc_display_contents_1_t* contents) 84 { 85 if (contents != nullptr) { 86 for (size_t l = 0; l < contents->numHwLayers; ++l) { 87 auto& layer = contents->hwLayers[l]; 88 std::free(const_cast<hwc_rect_t*>(layer.visibleRegionScreen.rects)); 89 } 90 } 91 std::free(contents); 92 } 93 94 class HWC2On1Adapter::Callbacks : public hwc_procs_t { 95 public: 96 Callbacks(HWC2On1Adapter& adapter) : mAdapter(adapter) { 97 invalidate = &invalidateHook; 98 vsync = &vsyncHook; 99 hotplug = &hotplugHook; 100 } 101 102 static void invalidateHook(const hwc_procs_t* procs) { 103 auto callbacks = static_cast<const Callbacks*>(procs); 104 callbacks->mAdapter.hwc1Invalidate(); 105 } 106 107 static void vsyncHook(const hwc_procs_t* procs, int display, 108 int64_t timestamp) { 109 auto callbacks = static_cast<const Callbacks*>(procs); 110 callbacks->mAdapter.hwc1Vsync(display, timestamp); 111 } 112 113 static void hotplugHook(const hwc_procs_t* procs, int display, 114 int connected) { 115 auto callbacks = static_cast<const Callbacks*>(procs); 116 callbacks->mAdapter.hwc1Hotplug(display, connected); 117 } 118 119 private: 120 HWC2On1Adapter& mAdapter; 121 }; 122 123 static int closeHook(hw_device_t* /*device*/) 124 { 125 // Do nothing, since the real work is done in the class destructor, but we 126 // need to provide a valid function pointer for hwc2_close to call 127 return 0; 128 } 129 130 HWC2On1Adapter::HWC2On1Adapter(hwc_composer_device_1_t* hwc1Device) 131 : mDumpString(), 132 mHwc1Device(hwc1Device), 133 mHwc1MinorVersion(getMinorVersion(hwc1Device)), 134 mHwc1SupportsVirtualDisplays(false), 135 mHwc1Callbacks(std::make_unique<Callbacks>(*this)), 136 mCapabilities(), 137 mLayers(), 138 mHwc1VirtualDisplay(), 139 mStateMutex(), 140 mCallbacks(), 141 mHasPendingInvalidate(false), 142 mPendingVsyncs(), 143 mPendingHotplugs(), 144 mDisplays(), 145 mHwc1DisplayMap() 146 { 147 common.close = closeHook; 148 getCapabilities = getCapabilitiesHook; 149 getFunction = getFunctionHook; 150 populateCapabilities(); 151 populatePrimary(); 152 mHwc1Device->registerProcs(mHwc1Device, 153 static_cast<const hwc_procs_t*>(mHwc1Callbacks.get())); 154 } 155 156 HWC2On1Adapter::~HWC2On1Adapter() { 157 hwc_close_1(mHwc1Device); 158 } 159 160 void HWC2On1Adapter::doGetCapabilities(uint32_t* outCount, 161 int32_t* outCapabilities) 162 { 163 if (outCapabilities == nullptr) { 164 *outCount = mCapabilities.size(); 165 return; 166 } 167 168 auto capabilityIter = mCapabilities.cbegin(); 169 for (size_t written = 0; written < *outCount; ++written) { 170 if (capabilityIter == mCapabilities.cend()) { 171 return; 172 } 173 outCapabilities[written] = static_cast<int32_t>(*capabilityIter); 174 ++capabilityIter; 175 } 176 } 177 178 hwc2_function_pointer_t HWC2On1Adapter::doGetFunction( 179 FunctionDescriptor descriptor) 180 { 181 switch (descriptor) { 182 // Device functions 183 case FunctionDescriptor::CreateVirtualDisplay: 184 return asFP<HWC2_PFN_CREATE_VIRTUAL_DISPLAY>( 185 createVirtualDisplayHook); 186 case FunctionDescriptor::DestroyVirtualDisplay: 187 return asFP<HWC2_PFN_DESTROY_VIRTUAL_DISPLAY>( 188 destroyVirtualDisplayHook); 189 case FunctionDescriptor::Dump: 190 return asFP<HWC2_PFN_DUMP>(dumpHook); 191 case FunctionDescriptor::GetMaxVirtualDisplayCount: 192 return asFP<HWC2_PFN_GET_MAX_VIRTUAL_DISPLAY_COUNT>( 193 getMaxVirtualDisplayCountHook); 194 case FunctionDescriptor::RegisterCallback: 195 return asFP<HWC2_PFN_REGISTER_CALLBACK>(registerCallbackHook); 196 197 // Display functions 198 case FunctionDescriptor::AcceptDisplayChanges: 199 return asFP<HWC2_PFN_ACCEPT_DISPLAY_CHANGES>( 200 displayHook<decltype(&Display::acceptChanges), 201 &Display::acceptChanges>); 202 case FunctionDescriptor::CreateLayer: 203 return asFP<HWC2_PFN_CREATE_LAYER>( 204 displayHook<decltype(&Display::createLayer), 205 &Display::createLayer, hwc2_layer_t*>); 206 case FunctionDescriptor::DestroyLayer: 207 return asFP<HWC2_PFN_DESTROY_LAYER>( 208 displayHook<decltype(&Display::destroyLayer), 209 &Display::destroyLayer, hwc2_layer_t>); 210 case FunctionDescriptor::GetActiveConfig: 211 return asFP<HWC2_PFN_GET_ACTIVE_CONFIG>( 212 displayHook<decltype(&Display::getActiveConfig), 213 &Display::getActiveConfig, hwc2_config_t*>); 214 case FunctionDescriptor::GetChangedCompositionTypes: 215 return asFP<HWC2_PFN_GET_CHANGED_COMPOSITION_TYPES>( 216 displayHook<decltype(&Display::getChangedCompositionTypes), 217 &Display::getChangedCompositionTypes, uint32_t*, 218 hwc2_layer_t*, int32_t*>); 219 case FunctionDescriptor::GetColorModes: 220 return asFP<HWC2_PFN_GET_COLOR_MODES>( 221 displayHook<decltype(&Display::getColorModes), 222 &Display::getColorModes, uint32_t*, int32_t*>); 223 case FunctionDescriptor::GetDisplayAttribute: 224 return asFP<HWC2_PFN_GET_DISPLAY_ATTRIBUTE>( 225 getDisplayAttributeHook); 226 case FunctionDescriptor::GetDisplayConfigs: 227 return asFP<HWC2_PFN_GET_DISPLAY_CONFIGS>( 228 displayHook<decltype(&Display::getConfigs), 229 &Display::getConfigs, uint32_t*, hwc2_config_t*>); 230 case FunctionDescriptor::GetDisplayName: 231 return asFP<HWC2_PFN_GET_DISPLAY_NAME>( 232 displayHook<decltype(&Display::getName), 233 &Display::getName, uint32_t*, char*>); 234 case FunctionDescriptor::GetDisplayRequests: 235 return asFP<HWC2_PFN_GET_DISPLAY_REQUESTS>( 236 displayHook<decltype(&Display::getRequests), 237 &Display::getRequests, int32_t*, uint32_t*, hwc2_layer_t*, 238 int32_t*>); 239 case FunctionDescriptor::GetDisplayType: 240 return asFP<HWC2_PFN_GET_DISPLAY_TYPE>( 241 displayHook<decltype(&Display::getType), 242 &Display::getType, int32_t*>); 243 case FunctionDescriptor::GetDozeSupport: 244 return asFP<HWC2_PFN_GET_DOZE_SUPPORT>( 245 displayHook<decltype(&Display::getDozeSupport), 246 &Display::getDozeSupport, int32_t*>); 247 case FunctionDescriptor::GetHdrCapabilities: 248 return asFP<HWC2_PFN_GET_HDR_CAPABILITIES>( 249 displayHook<decltype(&Display::getHdrCapabilities), 250 &Display::getHdrCapabilities, uint32_t*, int32_t*, float*, 251 float*, float*>); 252 case FunctionDescriptor::GetReleaseFences: 253 return asFP<HWC2_PFN_GET_RELEASE_FENCES>( 254 displayHook<decltype(&Display::getReleaseFences), 255 &Display::getReleaseFences, uint32_t*, hwc2_layer_t*, 256 int32_t*>); 257 case FunctionDescriptor::PresentDisplay: 258 return asFP<HWC2_PFN_PRESENT_DISPLAY>( 259 displayHook<decltype(&Display::present), 260 &Display::present, int32_t*>); 261 case FunctionDescriptor::SetActiveConfig: 262 return asFP<HWC2_PFN_SET_ACTIVE_CONFIG>( 263 displayHook<decltype(&Display::setActiveConfig), 264 &Display::setActiveConfig, hwc2_config_t>); 265 case FunctionDescriptor::SetClientTarget: 266 return asFP<HWC2_PFN_SET_CLIENT_TARGET>( 267 displayHook<decltype(&Display::setClientTarget), 268 &Display::setClientTarget, buffer_handle_t, int32_t, 269 int32_t, hwc_region_t>); 270 case FunctionDescriptor::SetColorMode: 271 return asFP<HWC2_PFN_SET_COLOR_MODE>( 272 displayHook<decltype(&Display::setColorMode), 273 &Display::setColorMode, int32_t>); 274 case FunctionDescriptor::SetColorTransform: 275 return asFP<HWC2_PFN_SET_COLOR_TRANSFORM>(setColorTransformHook); 276 case FunctionDescriptor::SetOutputBuffer: 277 return asFP<HWC2_PFN_SET_OUTPUT_BUFFER>( 278 displayHook<decltype(&Display::setOutputBuffer), 279 &Display::setOutputBuffer, buffer_handle_t, int32_t>); 280 case FunctionDescriptor::SetPowerMode: 281 return asFP<HWC2_PFN_SET_POWER_MODE>(setPowerModeHook); 282 case FunctionDescriptor::SetVsyncEnabled: 283 return asFP<HWC2_PFN_SET_VSYNC_ENABLED>(setVsyncEnabledHook); 284 case FunctionDescriptor::ValidateDisplay: 285 return asFP<HWC2_PFN_VALIDATE_DISPLAY>( 286 displayHook<decltype(&Display::validate), 287 &Display::validate, uint32_t*, uint32_t*>); 288 289 // Layer functions 290 case FunctionDescriptor::SetCursorPosition: 291 return asFP<HWC2_PFN_SET_CURSOR_POSITION>( 292 layerHook<decltype(&Layer::setCursorPosition), 293 &Layer::setCursorPosition, int32_t, int32_t>); 294 case FunctionDescriptor::SetLayerBuffer: 295 return asFP<HWC2_PFN_SET_LAYER_BUFFER>( 296 layerHook<decltype(&Layer::setBuffer), &Layer::setBuffer, 297 buffer_handle_t, int32_t>); 298 case FunctionDescriptor::SetLayerSurfaceDamage: 299 return asFP<HWC2_PFN_SET_LAYER_SURFACE_DAMAGE>( 300 layerHook<decltype(&Layer::setSurfaceDamage), 301 &Layer::setSurfaceDamage, hwc_region_t>); 302 303 // Layer state functions 304 case FunctionDescriptor::SetLayerBlendMode: 305 return asFP<HWC2_PFN_SET_LAYER_BLEND_MODE>( 306 setLayerBlendModeHook); 307 case FunctionDescriptor::SetLayerColor: 308 return asFP<HWC2_PFN_SET_LAYER_COLOR>( 309 layerHook<decltype(&Layer::setColor), &Layer::setColor, 310 hwc_color_t>); 311 case FunctionDescriptor::SetLayerCompositionType: 312 return asFP<HWC2_PFN_SET_LAYER_COMPOSITION_TYPE>( 313 setLayerCompositionTypeHook); 314 case FunctionDescriptor::SetLayerDataspace: 315 return asFP<HWC2_PFN_SET_LAYER_DATASPACE>(setLayerDataspaceHook); 316 case FunctionDescriptor::SetLayerDisplayFrame: 317 return asFP<HWC2_PFN_SET_LAYER_DISPLAY_FRAME>( 318 layerHook<decltype(&Layer::setDisplayFrame), 319 &Layer::setDisplayFrame, hwc_rect_t>); 320 case FunctionDescriptor::SetLayerPlaneAlpha: 321 return asFP<HWC2_PFN_SET_LAYER_PLANE_ALPHA>( 322 layerHook<decltype(&Layer::setPlaneAlpha), 323 &Layer::setPlaneAlpha, float>); 324 case FunctionDescriptor::SetLayerSidebandStream: 325 return asFP<HWC2_PFN_SET_LAYER_SIDEBAND_STREAM>( 326 layerHook<decltype(&Layer::setSidebandStream), 327 &Layer::setSidebandStream, const native_handle_t*>); 328 case FunctionDescriptor::SetLayerSourceCrop: 329 return asFP<HWC2_PFN_SET_LAYER_SOURCE_CROP>( 330 layerHook<decltype(&Layer::setSourceCrop), 331 &Layer::setSourceCrop, hwc_frect_t>); 332 case FunctionDescriptor::SetLayerTransform: 333 return asFP<HWC2_PFN_SET_LAYER_TRANSFORM>(setLayerTransformHook); 334 case FunctionDescriptor::SetLayerVisibleRegion: 335 return asFP<HWC2_PFN_SET_LAYER_VISIBLE_REGION>( 336 layerHook<decltype(&Layer::setVisibleRegion), 337 &Layer::setVisibleRegion, hwc_region_t>); 338 case FunctionDescriptor::SetLayerZOrder: 339 return asFP<HWC2_PFN_SET_LAYER_Z_ORDER>(setLayerZOrderHook); 340 341 default: 342 ALOGE("doGetFunction: Unknown function descriptor: %d (%s)", 343 static_cast<int32_t>(descriptor), 344 to_string(descriptor).c_str()); 345 return nullptr; 346 } 347 } 348 349 // Device functions 350 351 Error HWC2On1Adapter::createVirtualDisplay(uint32_t width, 352 uint32_t height, hwc2_display_t* outDisplay) 353 { 354 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex); 355 356 if (mHwc1VirtualDisplay) { 357 // We have already allocated our only HWC1 virtual display 358 ALOGE("createVirtualDisplay: HWC1 virtual display already allocated"); 359 return Error::NoResources; 360 } 361 362 if (MAX_VIRTUAL_DISPLAY_DIMENSION != 0 && 363 (width > MAX_VIRTUAL_DISPLAY_DIMENSION || 364 height > MAX_VIRTUAL_DISPLAY_DIMENSION)) { 365 ALOGE("createVirtualDisplay: Can't create a virtual display with" 366 " a dimension > %u (tried %u x %u)", 367 MAX_VIRTUAL_DISPLAY_DIMENSION, width, height); 368 return Error::NoResources; 369 } 370 371 mHwc1VirtualDisplay = std::make_shared<HWC2On1Adapter::Display>(*this, 372 HWC2::DisplayType::Virtual); 373 mHwc1VirtualDisplay->populateConfigs(width, height); 374 const auto displayId = mHwc1VirtualDisplay->getId(); 375 mHwc1DisplayMap[HWC_DISPLAY_VIRTUAL] = displayId; 376 mHwc1VirtualDisplay->setHwc1Id(HWC_DISPLAY_VIRTUAL); 377 mDisplays.emplace(displayId, mHwc1VirtualDisplay); 378 *outDisplay = displayId; 379 380 return Error::None; 381 } 382 383 Error HWC2On1Adapter::destroyVirtualDisplay(hwc2_display_t displayId) 384 { 385 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex); 386 387 if (!mHwc1VirtualDisplay || (mHwc1VirtualDisplay->getId() != displayId)) { 388 return Error::BadDisplay; 389 } 390 391 mHwc1VirtualDisplay.reset(); 392 mHwc1DisplayMap.erase(HWC_DISPLAY_VIRTUAL); 393 mDisplays.erase(displayId); 394 395 return Error::None; 396 } 397 398 void HWC2On1Adapter::dump(uint32_t* outSize, char* outBuffer) 399 { 400 if (outBuffer != nullptr) { 401 auto copiedBytes = mDumpString.copy(outBuffer, *outSize); 402 *outSize = static_cast<uint32_t>(copiedBytes); 403 return; 404 } 405 406 std::stringstream output; 407 408 output << "-- HWC2On1Adapter --\n"; 409 410 output << "Adapting to a HWC 1." << static_cast<int>(mHwc1MinorVersion) << 411 " device\n"; 412 413 // Attempt to acquire the lock for 1 second, but proceed without the lock 414 // after that, so we can still get some information if we're deadlocked 415 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex, 416 std::defer_lock); 417 lock.try_lock_for(1s); 418 419 if (mCapabilities.empty()) { 420 output << "Capabilities: None\n"; 421 } else { 422 output << "Capabilities:\n"; 423 for (auto capability : mCapabilities) { 424 output << " " << to_string(capability) << '\n'; 425 } 426 } 427 428 output << "Displays:\n"; 429 for (const auto& element : mDisplays) { 430 const auto& display = element.second; 431 output << display->dump(); 432 } 433 output << '\n'; 434 435 // Release the lock before calling into HWC1, and since we no longer require 436 // mutual exclusion to access mCapabilities or mDisplays 437 lock.unlock(); 438 439 if (mHwc1Device->dump) { 440 output << "HWC1 dump:\n"; 441 std::vector<char> hwc1Dump(4096); 442 // Call with size - 1 to preserve a null character at the end 443 mHwc1Device->dump(mHwc1Device, hwc1Dump.data(), 444 static_cast<int>(hwc1Dump.size() - 1)); 445 output << hwc1Dump.data(); 446 } 447 448 mDumpString = output.str(); 449 *outSize = static_cast<uint32_t>(mDumpString.size()); 450 } 451 452 uint32_t HWC2On1Adapter::getMaxVirtualDisplayCount() 453 { 454 return mHwc1SupportsVirtualDisplays ? 1 : 0; 455 } 456 457 static bool isValid(Callback descriptor) { 458 switch (descriptor) { 459 case Callback::Hotplug: // Fall-through 460 case Callback::Refresh: // Fall-through 461 case Callback::Vsync: return true; 462 default: return false; 463 } 464 } 465 466 Error HWC2On1Adapter::registerCallback(Callback descriptor, 467 hwc2_callback_data_t callbackData, hwc2_function_pointer_t pointer) 468 { 469 if (!isValid(descriptor)) { 470 return Error::BadParameter; 471 } 472 473 ALOGV("registerCallback(%s, %p, %p)", to_string(descriptor).c_str(), 474 callbackData, pointer); 475 476 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex); 477 478 mCallbacks[descriptor] = {callbackData, pointer}; 479 480 bool hasPendingInvalidate = false; 481 std::vector<hwc2_display_t> displayIds; 482 std::vector<std::pair<hwc2_display_t, int64_t>> pendingVsyncs; 483 std::vector<std::pair<hwc2_display_t, int>> pendingHotplugs; 484 485 if (descriptor == Callback::Refresh) { 486 hasPendingInvalidate = mHasPendingInvalidate; 487 if (hasPendingInvalidate) { 488 for (auto& displayPair : mDisplays) { 489 displayIds.emplace_back(displayPair.first); 490 } 491 } 492 mHasPendingInvalidate = false; 493 } else if (descriptor == Callback::Vsync) { 494 for (auto pending : mPendingVsyncs) { 495 auto hwc1DisplayId = pending.first; 496 if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) { 497 ALOGE("hwc1Vsync: Couldn't find display for HWC1 id %d", 498 hwc1DisplayId); 499 continue; 500 } 501 auto displayId = mHwc1DisplayMap[hwc1DisplayId]; 502 auto timestamp = pending.second; 503 pendingVsyncs.emplace_back(displayId, timestamp); 504 } 505 mPendingVsyncs.clear(); 506 } else if (descriptor == Callback::Hotplug) { 507 // Hotplug the primary display 508 pendingHotplugs.emplace_back(mHwc1DisplayMap[HWC_DISPLAY_PRIMARY], 509 static_cast<int32_t>(Connection::Connected)); 510 511 for (auto pending : mPendingHotplugs) { 512 auto hwc1DisplayId = pending.first; 513 if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) { 514 ALOGE("hwc1Hotplug: Couldn't find display for HWC1 id %d", 515 hwc1DisplayId); 516 continue; 517 } 518 auto displayId = mHwc1DisplayMap[hwc1DisplayId]; 519 auto connected = pending.second; 520 pendingHotplugs.emplace_back(displayId, connected); 521 } 522 } 523 524 // Call pending callbacks without the state lock held 525 lock.unlock(); 526 527 if (hasPendingInvalidate) { 528 auto refresh = reinterpret_cast<HWC2_PFN_REFRESH>(pointer); 529 for (auto displayId : displayIds) { 530 refresh(callbackData, displayId); 531 } 532 } 533 if (!pendingVsyncs.empty()) { 534 auto vsync = reinterpret_cast<HWC2_PFN_VSYNC>(pointer); 535 for (auto& pendingVsync : pendingVsyncs) { 536 vsync(callbackData, pendingVsync.first, pendingVsync.second); 537 } 538 } 539 if (!pendingHotplugs.empty()) { 540 auto hotplug = reinterpret_cast<HWC2_PFN_HOTPLUG>(pointer); 541 for (auto& pendingHotplug : pendingHotplugs) { 542 hotplug(callbackData, pendingHotplug.first, pendingHotplug.second); 543 } 544 } 545 return Error::None; 546 } 547 548 // Display functions 549 550 std::atomic<hwc2_display_t> HWC2On1Adapter::Display::sNextId(1); 551 552 HWC2On1Adapter::Display::Display(HWC2On1Adapter& device, HWC2::DisplayType type) 553 : mId(sNextId++), 554 mDevice(device), 555 mDirtyCount(0), 556 mStateMutex(), 557 mZIsDirty(false), 558 mHwc1RequestedContents(nullptr), 559 mHwc1ReceivedContents(nullptr), 560 mRetireFence(), 561 mChanges(), 562 mHwc1Id(-1), 563 mConfigs(), 564 mActiveConfig(nullptr), 565 mName(), 566 mType(type), 567 mPowerMode(PowerMode::Off), 568 mVsyncEnabled(Vsync::Invalid), 569 mClientTarget(), 570 mOutputBuffer(), 571 mHasColorTransform(false), 572 mLayers(), 573 mHwc1LayerMap() {} 574 575 Error HWC2On1Adapter::Display::acceptChanges() 576 { 577 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 578 579 if (!mChanges) { 580 ALOGV("[%" PRIu64 "] acceptChanges failed, not validated", mId); 581 return Error::NotValidated; 582 } 583 584 ALOGV("[%" PRIu64 "] acceptChanges", mId); 585 586 for (auto& change : mChanges->getTypeChanges()) { 587 auto layerId = change.first; 588 auto type = change.second; 589 auto layer = mDevice.mLayers[layerId]; 590 layer->setCompositionType(type); 591 } 592 593 mChanges->clearTypeChanges(); 594 595 mHwc1RequestedContents = std::move(mHwc1ReceivedContents); 596 597 return Error::None; 598 } 599 600 Error HWC2On1Adapter::Display::createLayer(hwc2_layer_t* outLayerId) 601 { 602 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 603 604 auto layer = *mLayers.emplace(std::make_shared<Layer>(*this)); 605 mDevice.mLayers.emplace(std::make_pair(layer->getId(), layer)); 606 *outLayerId = layer->getId(); 607 ALOGV("[%" PRIu64 "] created layer %" PRIu64, mId, *outLayerId); 608 return Error::None; 609 } 610 611 Error HWC2On1Adapter::Display::destroyLayer(hwc2_layer_t layerId) 612 { 613 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 614 615 const auto mapLayer = mDevice.mLayers.find(layerId); 616 if (mapLayer == mDevice.mLayers.end()) { 617 ALOGV("[%" PRIu64 "] destroyLayer(%" PRIu64 ") failed: no such layer", 618 mId, layerId); 619 return Error::BadLayer; 620 } 621 const auto layer = mapLayer->second; 622 mDevice.mLayers.erase(mapLayer); 623 const auto zRange = mLayers.equal_range(layer); 624 for (auto current = zRange.first; current != zRange.second; ++current) { 625 if (**current == *layer) { 626 current = mLayers.erase(current); 627 break; 628 } 629 } 630 ALOGV("[%" PRIu64 "] destroyed layer %" PRIu64, mId, layerId); 631 return Error::None; 632 } 633 634 Error HWC2On1Adapter::Display::getActiveConfig(hwc2_config_t* outConfig) 635 { 636 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 637 638 if (!mActiveConfig) { 639 ALOGV("[%" PRIu64 "] getActiveConfig --> %s", mId, 640 to_string(Error::BadConfig).c_str()); 641 return Error::BadConfig; 642 } 643 auto configId = mActiveConfig->getId(); 644 ALOGV("[%" PRIu64 "] getActiveConfig --> %u", mId, configId); 645 *outConfig = configId; 646 return Error::None; 647 } 648 649 Error HWC2On1Adapter::Display::getAttribute(hwc2_config_t configId, 650 Attribute attribute, int32_t* outValue) 651 { 652 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 653 654 if (configId > mConfigs.size() || !mConfigs[configId]->isOnDisplay(*this)) { 655 ALOGV("[%" PRIu64 "] getAttribute failed: bad config (%u)", mId, 656 configId); 657 return Error::BadConfig; 658 } 659 *outValue = mConfigs[configId]->getAttribute(attribute); 660 ALOGV("[%" PRIu64 "] getAttribute(%u, %s) --> %d", mId, configId, 661 to_string(attribute).c_str(), *outValue); 662 return Error::None; 663 } 664 665 Error HWC2On1Adapter::Display::getChangedCompositionTypes( 666 uint32_t* outNumElements, hwc2_layer_t* outLayers, int32_t* outTypes) 667 { 668 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 669 670 if (!mChanges) { 671 ALOGE("[%" PRIu64 "] getChangedCompositionTypes failed: not validated", 672 mId); 673 return Error::NotValidated; 674 } 675 676 if ((outLayers == nullptr) || (outTypes == nullptr)) { 677 *outNumElements = mChanges->getTypeChanges().size(); 678 return Error::None; 679 } 680 681 uint32_t numWritten = 0; 682 for (const auto& element : mChanges->getTypeChanges()) { 683 if (numWritten == *outNumElements) { 684 break; 685 } 686 auto layerId = element.first; 687 auto intType = static_cast<int32_t>(element.second); 688 ALOGV("Adding %" PRIu64 " %s", layerId, 689 to_string(element.second).c_str()); 690 outLayers[numWritten] = layerId; 691 outTypes[numWritten] = intType; 692 ++numWritten; 693 } 694 *outNumElements = numWritten; 695 696 return Error::None; 697 } 698 699 Error HWC2On1Adapter::Display::getColorModes(uint32_t* outNumModes, 700 int32_t* outModes) 701 { 702 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 703 704 if (!outModes) { 705 *outNumModes = mColorModes.size(); 706 return Error::None; 707 } 708 uint32_t numModes = std::min(*outNumModes, 709 static_cast<uint32_t>(mColorModes.size())); 710 std::copy_n(mColorModes.cbegin(), numModes, outModes); 711 *outNumModes = numModes; 712 return Error::None; 713 } 714 715 Error HWC2On1Adapter::Display::getConfigs(uint32_t* outNumConfigs, 716 hwc2_config_t* outConfigs) 717 { 718 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 719 720 if (!outConfigs) { 721 *outNumConfigs = mConfigs.size(); 722 return Error::None; 723 } 724 uint32_t numWritten = 0; 725 for (const auto& config : mConfigs) { 726 if (numWritten == *outNumConfigs) { 727 break; 728 } 729 outConfigs[numWritten] = config->getId(); 730 ++numWritten; 731 } 732 *outNumConfigs = numWritten; 733 return Error::None; 734 } 735 736 Error HWC2On1Adapter::Display::getDozeSupport(int32_t* outSupport) 737 { 738 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 739 740 if (mDevice.mHwc1MinorVersion < 4 || mHwc1Id != 0) { 741 *outSupport = 0; 742 } else { 743 *outSupport = 1; 744 } 745 return Error::None; 746 } 747 748 Error HWC2On1Adapter::Display::getHdrCapabilities(uint32_t* outNumTypes, 749 int32_t* /*outTypes*/, float* /*outMaxLuminance*/, 750 float* /*outMaxAverageLuminance*/, float* /*outMinLuminance*/) 751 { 752 // This isn't supported on HWC1, so per the HWC2 header, return numTypes = 0 753 *outNumTypes = 0; 754 return Error::None; 755 } 756 757 Error HWC2On1Adapter::Display::getName(uint32_t* outSize, char* outName) 758 { 759 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 760 761 if (!outName) { 762 *outSize = mName.size(); 763 return Error::None; 764 } 765 auto numCopied = mName.copy(outName, *outSize); 766 *outSize = numCopied; 767 return Error::None; 768 } 769 770 Error HWC2On1Adapter::Display::getReleaseFences(uint32_t* outNumElements, 771 hwc2_layer_t* outLayers, int32_t* outFences) 772 { 773 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 774 775 uint32_t numWritten = 0; 776 bool outputsNonNull = (outLayers != nullptr) && (outFences != nullptr); 777 for (const auto& layer : mLayers) { 778 if (outputsNonNull && (numWritten == *outNumElements)) { 779 break; 780 } 781 782 auto releaseFence = layer->getReleaseFence(); 783 if (releaseFence != Fence::NO_FENCE) { 784 if (outputsNonNull) { 785 outLayers[numWritten] = layer->getId(); 786 outFences[numWritten] = releaseFence->dup(); 787 } 788 ++numWritten; 789 } 790 } 791 *outNumElements = numWritten; 792 793 return Error::None; 794 } 795 796 Error HWC2On1Adapter::Display::getRequests(int32_t* outDisplayRequests, 797 uint32_t* outNumElements, hwc2_layer_t* outLayers, 798 int32_t* outLayerRequests) 799 { 800 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 801 802 if (!mChanges) { 803 return Error::NotValidated; 804 } 805 806 if (outLayers == nullptr || outLayerRequests == nullptr) { 807 *outNumElements = mChanges->getNumLayerRequests(); 808 return Error::None; 809 } 810 811 *outDisplayRequests = mChanges->getDisplayRequests(); 812 uint32_t numWritten = 0; 813 for (const auto& request : mChanges->getLayerRequests()) { 814 if (numWritten == *outNumElements) { 815 break; 816 } 817 outLayers[numWritten] = request.first; 818 outLayerRequests[numWritten] = static_cast<int32_t>(request.second); 819 ++numWritten; 820 } 821 822 return Error::None; 823 } 824 825 Error HWC2On1Adapter::Display::getType(int32_t* outType) 826 { 827 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 828 829 *outType = static_cast<int32_t>(mType); 830 return Error::None; 831 } 832 833 Error HWC2On1Adapter::Display::present(int32_t* outRetireFence) 834 { 835 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 836 837 if (mChanges) { 838 Error error = mDevice.setAllDisplays(); 839 if (error != Error::None) { 840 ALOGE("[%" PRIu64 "] present: setAllDisplaysFailed (%s)", mId, 841 to_string(error).c_str()); 842 return error; 843 } 844 } 845 846 *outRetireFence = mRetireFence.get()->dup(); 847 ALOGV("[%" PRIu64 "] present returning retire fence %d", mId, 848 *outRetireFence); 849 850 return Error::None; 851 } 852 853 Error HWC2On1Adapter::Display::setActiveConfig(hwc2_config_t configId) 854 { 855 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 856 857 auto config = getConfig(configId); 858 if (!config) { 859 return Error::BadConfig; 860 } 861 if (config == mActiveConfig) { 862 return Error::None; 863 } 864 865 if (mDevice.mHwc1MinorVersion >= 4) { 866 uint32_t hwc1Id = 0; 867 auto error = config->getHwc1IdForColorMode(mActiveColorMode, &hwc1Id); 868 if (error != Error::None) { 869 return error; 870 } 871 872 int intError = mDevice.mHwc1Device->setActiveConfig(mDevice.mHwc1Device, 873 mHwc1Id, static_cast<int>(hwc1Id)); 874 if (intError != 0) { 875 ALOGE("setActiveConfig: Failed to set active config on HWC1 (%d)", 876 intError); 877 return Error::BadConfig; 878 } 879 mActiveConfig = config; 880 } 881 882 return Error::None; 883 } 884 885 Error HWC2On1Adapter::Display::setClientTarget(buffer_handle_t target, 886 int32_t acquireFence, int32_t /*dataspace*/, hwc_region_t /*damage*/) 887 { 888 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 889 890 ALOGV("[%" PRIu64 "] setClientTarget(%p, %d)", mId, target, acquireFence); 891 mClientTarget.setBuffer(target); 892 mClientTarget.setFence(acquireFence); 893 // dataspace and damage can't be used by HWC1, so ignore them 894 return Error::None; 895 } 896 897 Error HWC2On1Adapter::Display::setColorMode(int32_t mode) 898 { 899 std::unique_lock<std::recursive_mutex> lock (mStateMutex); 900 901 ALOGV("[%" PRIu64 "] setColorMode(%d)", mId, mode); 902 903 if (mode == mActiveColorMode) { 904 return Error::None; 905 } 906 if (mColorModes.count(mode) == 0) { 907 ALOGE("[%" PRIu64 "] Mode %d not found in mColorModes", mId, mode); 908 return Error::Unsupported; 909 } 910 911 uint32_t hwc1Config = 0; 912 auto error = mActiveConfig->getHwc1IdForColorMode(mode, &hwc1Config); 913 if (error != Error::None) { 914 return error; 915 } 916 917 ALOGV("[%" PRIu64 "] Setting HWC1 config %u", mId, hwc1Config); 918 int intError = mDevice.mHwc1Device->setActiveConfig(mDevice.mHwc1Device, 919 mHwc1Id, hwc1Config); 920 if (intError != 0) { 921 ALOGE("[%" PRIu64 "] Failed to set HWC1 config (%d)", mId, intError); 922 return Error::Unsupported; 923 } 924 925 mActiveColorMode = mode; 926 return Error::None; 927 } 928 929 Error HWC2On1Adapter::Display::setColorTransform(android_color_transform_t hint) 930 { 931 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 932 933 ALOGV("%" PRIu64 "] setColorTransform(%d)", mId, 934 static_cast<int32_t>(hint)); 935 mHasColorTransform = (hint != HAL_COLOR_TRANSFORM_IDENTITY); 936 return Error::None; 937 } 938 939 Error HWC2On1Adapter::Display::setOutputBuffer(buffer_handle_t buffer, 940 int32_t releaseFence) 941 { 942 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 943 944 ALOGV("[%" PRIu64 "] setOutputBuffer(%p, %d)", mId, buffer, releaseFence); 945 mOutputBuffer.setBuffer(buffer); 946 mOutputBuffer.setFence(releaseFence); 947 return Error::None; 948 } 949 950 static bool isValid(PowerMode mode) 951 { 952 switch (mode) { 953 case PowerMode::Off: // Fall-through 954 case PowerMode::DozeSuspend: // Fall-through 955 case PowerMode::Doze: // Fall-through 956 case PowerMode::On: return true; 957 default: return false; 958 } 959 } 960 961 static int getHwc1PowerMode(PowerMode mode) 962 { 963 switch (mode) { 964 case PowerMode::Off: return HWC_POWER_MODE_OFF; 965 case PowerMode::DozeSuspend: return HWC_POWER_MODE_DOZE_SUSPEND; 966 case PowerMode::Doze: return HWC_POWER_MODE_DOZE; 967 case PowerMode::On: return HWC_POWER_MODE_NORMAL; 968 default: return HWC_POWER_MODE_OFF; 969 } 970 } 971 972 Error HWC2On1Adapter::Display::setPowerMode(PowerMode mode) 973 { 974 if (!isValid(mode)) { 975 return Error::BadParameter; 976 } 977 if (mode == mPowerMode) { 978 return Error::None; 979 } 980 981 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 982 983 int error = 0; 984 if (mDevice.mHwc1MinorVersion < 4) { 985 error = mDevice.mHwc1Device->blank(mDevice.mHwc1Device, mHwc1Id, 986 mode == PowerMode::Off); 987 } else { 988 error = mDevice.mHwc1Device->setPowerMode(mDevice.mHwc1Device, 989 mHwc1Id, getHwc1PowerMode(mode)); 990 } 991 ALOGE_IF(error != 0, "setPowerMode: Failed to set power mode on HWC1 (%d)", 992 error); 993 994 ALOGV("[%" PRIu64 "] setPowerMode(%s)", mId, to_string(mode).c_str()); 995 mPowerMode = mode; 996 return Error::None; 997 } 998 999 static bool isValid(Vsync enable) { 1000 switch (enable) { 1001 case Vsync::Enable: // Fall-through 1002 case Vsync::Disable: return true; 1003 default: return false; 1004 } 1005 } 1006 1007 Error HWC2On1Adapter::Display::setVsyncEnabled(Vsync enable) 1008 { 1009 if (!isValid(enable)) { 1010 return Error::BadParameter; 1011 } 1012 if (enable == mVsyncEnabled) { 1013 return Error::None; 1014 } 1015 1016 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 1017 1018 int error = mDevice.mHwc1Device->eventControl(mDevice.mHwc1Device, 1019 mHwc1Id, HWC_EVENT_VSYNC, enable == Vsync::Enable); 1020 ALOGE_IF(error != 0, "setVsyncEnabled: Failed to set vsync on HWC1 (%d)", 1021 error); 1022 1023 mVsyncEnabled = enable; 1024 return Error::None; 1025 } 1026 1027 Error HWC2On1Adapter::Display::validate(uint32_t* outNumTypes, 1028 uint32_t* outNumRequests) 1029 { 1030 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 1031 1032 ALOGV("[%" PRIu64 "] Entering validate", mId); 1033 1034 if (!mChanges) { 1035 if (!mDevice.prepareAllDisplays()) { 1036 return Error::BadDisplay; 1037 } 1038 } 1039 1040 *outNumTypes = mChanges->getNumTypes(); 1041 *outNumRequests = mChanges->getNumLayerRequests(); 1042 ALOGV("[%" PRIu64 "] validate --> %u types, %u requests", mId, *outNumTypes, 1043 *outNumRequests); 1044 for (auto request : mChanges->getTypeChanges()) { 1045 ALOGV("Layer %" PRIu64 " --> %s", request.first, 1046 to_string(request.second).c_str()); 1047 } 1048 return *outNumTypes > 0 ? Error::HasChanges : Error::None; 1049 } 1050 1051 // Display helpers 1052 1053 Error HWC2On1Adapter::Display::updateLayerZ(hwc2_layer_t layerId, uint32_t z) 1054 { 1055 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 1056 1057 const auto mapLayer = mDevice.mLayers.find(layerId); 1058 if (mapLayer == mDevice.mLayers.end()) { 1059 ALOGE("[%" PRIu64 "] updateLayerZ failed to find layer", mId); 1060 return Error::BadLayer; 1061 } 1062 1063 const auto layer = mapLayer->second; 1064 const auto zRange = mLayers.equal_range(layer); 1065 bool layerOnDisplay = false; 1066 for (auto current = zRange.first; current != zRange.second; ++current) { 1067 if (**current == *layer) { 1068 if ((*current)->getZ() == z) { 1069 // Don't change anything if the Z hasn't changed 1070 return Error::None; 1071 } 1072 current = mLayers.erase(current); 1073 layerOnDisplay = true; 1074 break; 1075 } 1076 } 1077 1078 if (!layerOnDisplay) { 1079 ALOGE("[%" PRIu64 "] updateLayerZ failed to find layer on display", 1080 mId); 1081 return Error::BadLayer; 1082 } 1083 1084 layer->setZ(z); 1085 mLayers.emplace(std::move(layer)); 1086 mZIsDirty = true; 1087 1088 return Error::None; 1089 } 1090 1091 static constexpr uint32_t ATTRIBUTES_WITH_COLOR[] = { 1092 HWC_DISPLAY_VSYNC_PERIOD, 1093 HWC_DISPLAY_WIDTH, 1094 HWC_DISPLAY_HEIGHT, 1095 HWC_DISPLAY_DPI_X, 1096 HWC_DISPLAY_DPI_Y, 1097 HWC_DISPLAY_COLOR_TRANSFORM, 1098 HWC_DISPLAY_NO_ATTRIBUTE, 1099 }; 1100 1101 static constexpr uint32_t ATTRIBUTES_WITHOUT_COLOR[] = { 1102 HWC_DISPLAY_VSYNC_PERIOD, 1103 HWC_DISPLAY_WIDTH, 1104 HWC_DISPLAY_HEIGHT, 1105 HWC_DISPLAY_DPI_X, 1106 HWC_DISPLAY_DPI_Y, 1107 HWC_DISPLAY_NO_ATTRIBUTE, 1108 }; 1109 1110 static constexpr size_t NUM_ATTRIBUTES_WITH_COLOR = 1111 sizeof(ATTRIBUTES_WITH_COLOR) / sizeof(uint32_t); 1112 static_assert(sizeof(ATTRIBUTES_WITH_COLOR) > sizeof(ATTRIBUTES_WITHOUT_COLOR), 1113 "Attribute tables have unexpected sizes"); 1114 1115 static constexpr uint32_t ATTRIBUTE_MAP_WITH_COLOR[] = { 1116 6, // HWC_DISPLAY_NO_ATTRIBUTE = 0 1117 0, // HWC_DISPLAY_VSYNC_PERIOD = 1, 1118 1, // HWC_DISPLAY_WIDTH = 2, 1119 2, // HWC_DISPLAY_HEIGHT = 3, 1120 3, // HWC_DISPLAY_DPI_X = 4, 1121 4, // HWC_DISPLAY_DPI_Y = 5, 1122 5, // HWC_DISPLAY_COLOR_TRANSFORM = 6, 1123 }; 1124 1125 static constexpr uint32_t ATTRIBUTE_MAP_WITHOUT_COLOR[] = { 1126 5, // HWC_DISPLAY_NO_ATTRIBUTE = 0 1127 0, // HWC_DISPLAY_VSYNC_PERIOD = 1, 1128 1, // HWC_DISPLAY_WIDTH = 2, 1129 2, // HWC_DISPLAY_HEIGHT = 3, 1130 3, // HWC_DISPLAY_DPI_X = 4, 1131 4, // HWC_DISPLAY_DPI_Y = 5, 1132 }; 1133 1134 template <uint32_t attribute> 1135 static constexpr bool attributesMatch() 1136 { 1137 bool match = (attribute == 1138 ATTRIBUTES_WITH_COLOR[ATTRIBUTE_MAP_WITH_COLOR[attribute]]); 1139 if (attribute == HWC_DISPLAY_COLOR_TRANSFORM) { 1140 return match; 1141 } 1142 1143 return match && (attribute == 1144 ATTRIBUTES_WITHOUT_COLOR[ATTRIBUTE_MAP_WITHOUT_COLOR[attribute]]); 1145 } 1146 static_assert(attributesMatch<HWC_DISPLAY_VSYNC_PERIOD>(), 1147 "Tables out of sync"); 1148 static_assert(attributesMatch<HWC_DISPLAY_WIDTH>(), "Tables out of sync"); 1149 static_assert(attributesMatch<HWC_DISPLAY_HEIGHT>(), "Tables out of sync"); 1150 static_assert(attributesMatch<HWC_DISPLAY_DPI_X>(), "Tables out of sync"); 1151 static_assert(attributesMatch<HWC_DISPLAY_DPI_Y>(), "Tables out of sync"); 1152 static_assert(attributesMatch<HWC_DISPLAY_COLOR_TRANSFORM>(), 1153 "Tables out of sync"); 1154 1155 void HWC2On1Adapter::Display::populateConfigs() 1156 { 1157 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 1158 1159 ALOGV("[%" PRIu64 "] populateConfigs", mId); 1160 1161 if (mHwc1Id == -1) { 1162 ALOGE("populateConfigs: HWC1 ID not set"); 1163 return; 1164 } 1165 1166 const size_t MAX_NUM_CONFIGS = 128; 1167 uint32_t configs[MAX_NUM_CONFIGS] = {}; 1168 size_t numConfigs = MAX_NUM_CONFIGS; 1169 mDevice.mHwc1Device->getDisplayConfigs(mDevice.mHwc1Device, mHwc1Id, 1170 configs, &numConfigs); 1171 1172 for (size_t c = 0; c < numConfigs; ++c) { 1173 uint32_t hwc1ConfigId = configs[c]; 1174 auto newConfig = std::make_shared<Config>(*this); 1175 1176 int32_t values[NUM_ATTRIBUTES_WITH_COLOR] = {}; 1177 bool hasColor = true; 1178 auto result = mDevice.mHwc1Device->getDisplayAttributes( 1179 mDevice.mHwc1Device, mHwc1Id, hwc1ConfigId, 1180 ATTRIBUTES_WITH_COLOR, values); 1181 if (result != 0) { 1182 mDevice.mHwc1Device->getDisplayAttributes(mDevice.mHwc1Device, 1183 mHwc1Id, hwc1ConfigId, ATTRIBUTES_WITHOUT_COLOR, values); 1184 hasColor = false; 1185 } 1186 1187 auto attributeMap = hasColor ? 1188 ATTRIBUTE_MAP_WITH_COLOR : ATTRIBUTE_MAP_WITHOUT_COLOR; 1189 1190 newConfig->setAttribute(Attribute::VsyncPeriod, 1191 values[attributeMap[HWC_DISPLAY_VSYNC_PERIOD]]); 1192 newConfig->setAttribute(Attribute::Width, 1193 values[attributeMap[HWC_DISPLAY_WIDTH]]); 1194 newConfig->setAttribute(Attribute::Height, 1195 values[attributeMap[HWC_DISPLAY_HEIGHT]]); 1196 newConfig->setAttribute(Attribute::DpiX, 1197 values[attributeMap[HWC_DISPLAY_DPI_X]]); 1198 newConfig->setAttribute(Attribute::DpiY, 1199 values[attributeMap[HWC_DISPLAY_DPI_Y]]); 1200 if (hasColor) { 1201 newConfig->setAttribute(ColorTransform, 1202 values[attributeMap[HWC_DISPLAY_COLOR_TRANSFORM]]); 1203 } 1204 1205 // We can only do this after attempting to read the color transform 1206 newConfig->setHwc1Id(hwc1ConfigId); 1207 1208 for (auto& existingConfig : mConfigs) { 1209 if (existingConfig->merge(*newConfig)) { 1210 ALOGV("Merged config %d with existing config %u: %s", 1211 hwc1ConfigId, existingConfig->getId(), 1212 existingConfig->toString().c_str()); 1213 newConfig.reset(); 1214 break; 1215 } 1216 } 1217 1218 // If it wasn't merged with any existing config, add it to the end 1219 if (newConfig) { 1220 newConfig->setId(static_cast<hwc2_config_t>(mConfigs.size())); 1221 ALOGV("Found new config %u: %s", newConfig->getId(), 1222 newConfig->toString().c_str()); 1223 mConfigs.emplace_back(std::move(newConfig)); 1224 } 1225 } 1226 1227 initializeActiveConfig(); 1228 populateColorModes(); 1229 } 1230 1231 void HWC2On1Adapter::Display::populateConfigs(uint32_t width, uint32_t height) 1232 { 1233 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 1234 1235 mConfigs.emplace_back(std::make_shared<Config>(*this)); 1236 auto& config = mConfigs[0]; 1237 1238 config->setAttribute(Attribute::Width, static_cast<int32_t>(width)); 1239 config->setAttribute(Attribute::Height, static_cast<int32_t>(height)); 1240 config->setHwc1Id(0); 1241 config->setId(0); 1242 mActiveConfig = config; 1243 } 1244 1245 bool HWC2On1Adapter::Display::prepare() 1246 { 1247 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 1248 1249 // Only prepare display contents for displays HWC1 knows about 1250 if (mHwc1Id == -1) { 1251 return true; 1252 } 1253 1254 // It doesn't make sense to prepare a display for which there is no active 1255 // config, so return early 1256 if (!mActiveConfig) { 1257 ALOGE("[%" PRIu64 "] Attempted to prepare, but no config active", mId); 1258 return false; 1259 } 1260 1261 ALOGV("[%" PRIu64 "] Entering prepare", mId); 1262 1263 auto currentCount = mHwc1RequestedContents ? 1264 mHwc1RequestedContents->numHwLayers : 0; 1265 auto requiredCount = mLayers.size() + 1; 1266 ALOGV("[%" PRIu64 "] Requires %zd layers, %zd allocated in %p", mId, 1267 requiredCount, currentCount, mHwc1RequestedContents.get()); 1268 1269 bool layerCountChanged = (currentCount != requiredCount); 1270 if (layerCountChanged) { 1271 reallocateHwc1Contents(); 1272 } 1273 1274 bool applyAllState = false; 1275 if (layerCountChanged || mZIsDirty) { 1276 assignHwc1LayerIds(); 1277 mZIsDirty = false; 1278 applyAllState = true; 1279 } 1280 1281 mHwc1RequestedContents->retireFenceFd = -1; 1282 mHwc1RequestedContents->flags = 0; 1283 if (isDirty() || applyAllState) { 1284 mHwc1RequestedContents->flags |= HWC_GEOMETRY_CHANGED; 1285 } 1286 1287 for (auto& layer : mLayers) { 1288 auto& hwc1Layer = mHwc1RequestedContents->hwLayers[layer->getHwc1Id()]; 1289 hwc1Layer.releaseFenceFd = -1; 1290 layer->applyState(hwc1Layer, applyAllState); 1291 } 1292 1293 mHwc1RequestedContents->outbuf = mOutputBuffer.getBuffer(); 1294 mHwc1RequestedContents->outbufAcquireFenceFd = mOutputBuffer.getFence(); 1295 1296 prepareFramebufferTarget(); 1297 1298 return true; 1299 } 1300 1301 static void cloneHWCRegion(hwc_region_t& region) 1302 { 1303 auto size = sizeof(hwc_rect_t) * region.numRects; 1304 auto newRects = static_cast<hwc_rect_t*>(std::malloc(size)); 1305 std::copy_n(region.rects, region.numRects, newRects); 1306 region.rects = newRects; 1307 } 1308 1309 HWC2On1Adapter::Display::HWC1Contents 1310 HWC2On1Adapter::Display::cloneRequestedContents() const 1311 { 1312 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 1313 1314 size_t size = sizeof(hwc_display_contents_1_t) + 1315 sizeof(hwc_layer_1_t) * (mHwc1RequestedContents->numHwLayers); 1316 auto contents = static_cast<hwc_display_contents_1_t*>(std::malloc(size)); 1317 std::memcpy(contents, mHwc1RequestedContents.get(), size); 1318 for (size_t layerId = 0; layerId < contents->numHwLayers; ++layerId) { 1319 auto& layer = contents->hwLayers[layerId]; 1320 // Deep copy the regions to avoid double-frees 1321 cloneHWCRegion(layer.visibleRegionScreen); 1322 cloneHWCRegion(layer.surfaceDamage); 1323 } 1324 return HWC1Contents(contents); 1325 } 1326 1327 void HWC2On1Adapter::Display::setReceivedContents(HWC1Contents contents) 1328 { 1329 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 1330 1331 mHwc1ReceivedContents = std::move(contents); 1332 1333 mChanges.reset(new Changes); 1334 1335 size_t numLayers = mHwc1ReceivedContents->numHwLayers; 1336 for (size_t hwc1Id = 0; hwc1Id < numLayers; ++hwc1Id) { 1337 const auto& receivedLayer = mHwc1ReceivedContents->hwLayers[hwc1Id]; 1338 if (mHwc1LayerMap.count(hwc1Id) == 0) { 1339 ALOGE_IF(receivedLayer.compositionType != HWC_FRAMEBUFFER_TARGET, 1340 "setReceivedContents: HWC1 layer %zd doesn't have a" 1341 " matching HWC2 layer, and isn't the framebuffer target", 1342 hwc1Id); 1343 continue; 1344 } 1345 1346 Layer& layer = *mHwc1LayerMap[hwc1Id]; 1347 updateTypeChanges(receivedLayer, layer); 1348 updateLayerRequests(receivedLayer, layer); 1349 } 1350 } 1351 1352 bool HWC2On1Adapter::Display::hasChanges() const 1353 { 1354 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 1355 return mChanges != nullptr; 1356 } 1357 1358 Error HWC2On1Adapter::Display::set(hwc_display_contents_1& hwcContents) 1359 { 1360 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 1361 1362 if (!mChanges || (mChanges->getNumTypes() > 0)) { 1363 ALOGE("[%" PRIu64 "] set failed: not validated", mId); 1364 return Error::NotValidated; 1365 } 1366 1367 // Set up the client/framebuffer target 1368 auto numLayers = hwcContents.numHwLayers; 1369 1370 // Close acquire fences on FRAMEBUFFER layers, since they will not be used 1371 // by HWC 1372 for (size_t l = 0; l < numLayers - 1; ++l) { 1373 auto& layer = hwcContents.hwLayers[l]; 1374 if (layer.compositionType == HWC_FRAMEBUFFER) { 1375 ALOGV("Closing fence %d for layer %zd", layer.acquireFenceFd, l); 1376 close(layer.acquireFenceFd); 1377 layer.acquireFenceFd = -1; 1378 } 1379 } 1380 1381 auto& clientTargetLayer = hwcContents.hwLayers[numLayers - 1]; 1382 if (clientTargetLayer.compositionType == HWC_FRAMEBUFFER_TARGET) { 1383 clientTargetLayer.handle = mClientTarget.getBuffer(); 1384 clientTargetLayer.acquireFenceFd = mClientTarget.getFence(); 1385 } else { 1386 ALOGE("[%" PRIu64 "] set: last HWC layer wasn't FRAMEBUFFER_TARGET", 1387 mId); 1388 } 1389 1390 mChanges.reset(); 1391 1392 return Error::None; 1393 } 1394 1395 void HWC2On1Adapter::Display::addRetireFence(int fenceFd) 1396 { 1397 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 1398 mRetireFence.add(fenceFd); 1399 } 1400 1401 void HWC2On1Adapter::Display::addReleaseFences( 1402 const hwc_display_contents_1_t& hwcContents) 1403 { 1404 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 1405 1406 size_t numLayers = hwcContents.numHwLayers; 1407 for (size_t hwc1Id = 0; hwc1Id < numLayers; ++hwc1Id) { 1408 const auto& receivedLayer = hwcContents.hwLayers[hwc1Id]; 1409 if (mHwc1LayerMap.count(hwc1Id) == 0) { 1410 if (receivedLayer.compositionType != HWC_FRAMEBUFFER_TARGET) { 1411 ALOGE("addReleaseFences: HWC1 layer %zd doesn't have a" 1412 " matching HWC2 layer, and isn't the framebuffer" 1413 " target", hwc1Id); 1414 } 1415 // Close the framebuffer target release fence since we will use the 1416 // display retire fence instead 1417 if (receivedLayer.releaseFenceFd != -1) { 1418 close(receivedLayer.releaseFenceFd); 1419 } 1420 continue; 1421 } 1422 1423 Layer& layer = *mHwc1LayerMap[hwc1Id]; 1424 ALOGV("Adding release fence %d to layer %" PRIu64, 1425 receivedLayer.releaseFenceFd, layer.getId()); 1426 layer.addReleaseFence(receivedLayer.releaseFenceFd); 1427 } 1428 } 1429 1430 bool HWC2On1Adapter::Display::hasColorTransform() const 1431 { 1432 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 1433 return mHasColorTransform; 1434 } 1435 1436 static std::string hwc1CompositionString(int32_t type) 1437 { 1438 switch (type) { 1439 case HWC_FRAMEBUFFER: return "Framebuffer"; 1440 case HWC_OVERLAY: return "Overlay"; 1441 case HWC_BACKGROUND: return "Background"; 1442 case HWC_FRAMEBUFFER_TARGET: return "FramebufferTarget"; 1443 case HWC_SIDEBAND: return "Sideband"; 1444 case HWC_CURSOR_OVERLAY: return "CursorOverlay"; 1445 default: 1446 return std::string("Unknown (") + std::to_string(type) + ")"; 1447 } 1448 } 1449 1450 static std::string hwc1TransformString(int32_t transform) 1451 { 1452 switch (transform) { 1453 case 0: return "None"; 1454 case HWC_TRANSFORM_FLIP_H: return "FlipH"; 1455 case HWC_TRANSFORM_FLIP_V: return "FlipV"; 1456 case HWC_TRANSFORM_ROT_90: return "Rotate90"; 1457 case HWC_TRANSFORM_ROT_180: return "Rotate180"; 1458 case HWC_TRANSFORM_ROT_270: return "Rotate270"; 1459 case HWC_TRANSFORM_FLIP_H_ROT_90: return "FlipHRotate90"; 1460 case HWC_TRANSFORM_FLIP_V_ROT_90: return "FlipVRotate90"; 1461 default: 1462 return std::string("Unknown (") + std::to_string(transform) + ")"; 1463 } 1464 } 1465 1466 static std::string hwc1BlendModeString(int32_t mode) 1467 { 1468 switch (mode) { 1469 case HWC_BLENDING_NONE: return "None"; 1470 case HWC_BLENDING_PREMULT: return "Premultiplied"; 1471 case HWC_BLENDING_COVERAGE: return "Coverage"; 1472 default: 1473 return std::string("Unknown (") + std::to_string(mode) + ")"; 1474 } 1475 } 1476 1477 static std::string rectString(hwc_rect_t rect) 1478 { 1479 std::stringstream output; 1480 output << "[" << rect.left << ", " << rect.top << ", "; 1481 output << rect.right << ", " << rect.bottom << "]"; 1482 return output.str(); 1483 } 1484 1485 static std::string approximateFloatString(float f) 1486 { 1487 if (static_cast<int32_t>(f) == f) { 1488 return std::to_string(static_cast<int32_t>(f)); 1489 } 1490 int32_t truncated = static_cast<int32_t>(f * 10); 1491 bool approximate = (static_cast<float>(truncated) != f * 10); 1492 const size_t BUFFER_SIZE = 32; 1493 char buffer[BUFFER_SIZE] = {}; 1494 auto bytesWritten = snprintf(buffer, BUFFER_SIZE, 1495 "%s%.1f", approximate ? "~" : "", f); 1496 return std::string(buffer, bytesWritten); 1497 } 1498 1499 static std::string frectString(hwc_frect_t frect) 1500 { 1501 std::stringstream output; 1502 output << "[" << approximateFloatString(frect.left) << ", "; 1503 output << approximateFloatString(frect.top) << ", "; 1504 output << approximateFloatString(frect.right) << ", "; 1505 output << approximateFloatString(frect.bottom) << "]"; 1506 return output.str(); 1507 } 1508 1509 static std::string colorString(hwc_color_t color) 1510 { 1511 std::stringstream output; 1512 output << "RGBA ["; 1513 output << static_cast<int32_t>(color.r) << ", "; 1514 output << static_cast<int32_t>(color.g) << ", "; 1515 output << static_cast<int32_t>(color.b) << ", "; 1516 output << static_cast<int32_t>(color.a) << "]"; 1517 return output.str(); 1518 } 1519 1520 static std::string alphaString(float f) 1521 { 1522 const size_t BUFFER_SIZE = 8; 1523 char buffer[BUFFER_SIZE] = {}; 1524 auto bytesWritten = snprintf(buffer, BUFFER_SIZE, "%.3f", f); 1525 return std::string(buffer, bytesWritten); 1526 } 1527 1528 static std::string to_string(const hwc_layer_1_t& hwcLayer, 1529 int32_t hwc1MinorVersion) 1530 { 1531 const char* fill = " "; 1532 1533 std::stringstream output; 1534 1535 output << " Composition: " << 1536 hwc1CompositionString(hwcLayer.compositionType); 1537 1538 if (hwcLayer.compositionType == HWC_BACKGROUND) { 1539 output << " Color: " << colorString(hwcLayer.backgroundColor) << '\n'; 1540 } else if (hwcLayer.compositionType == HWC_SIDEBAND) { 1541 output << " Stream: " << hwcLayer.sidebandStream << '\n'; 1542 } else { 1543 output << " Buffer: " << hwcLayer.handle << "/" << 1544 hwcLayer.acquireFenceFd << '\n'; 1545 } 1546 1547 output << fill << "Display frame: " << rectString(hwcLayer.displayFrame) << 1548 '\n'; 1549 1550 output << fill << "Source crop: "; 1551 if (hwc1MinorVersion >= 3) { 1552 output << frectString(hwcLayer.sourceCropf) << '\n'; 1553 } else { 1554 output << rectString(hwcLayer.sourceCropi) << '\n'; 1555 } 1556 1557 output << fill << "Transform: " << hwc1TransformString(hwcLayer.transform); 1558 output << " Blend mode: " << hwc1BlendModeString(hwcLayer.blending); 1559 if (hwcLayer.planeAlpha != 0xFF) { 1560 output << " Alpha: " << alphaString(hwcLayer.planeAlpha / 255.0f); 1561 } 1562 output << '\n'; 1563 1564 if (hwcLayer.hints != 0) { 1565 output << fill << "Hints:"; 1566 if ((hwcLayer.hints & HWC_HINT_TRIPLE_BUFFER) != 0) { 1567 output << " TripleBuffer"; 1568 } 1569 if ((hwcLayer.hints & HWC_HINT_CLEAR_FB) != 0) { 1570 output << " ClearFB"; 1571 } 1572 output << '\n'; 1573 } 1574 1575 if (hwcLayer.flags != 0) { 1576 output << fill << "Flags:"; 1577 if ((hwcLayer.flags & HWC_SKIP_LAYER) != 0) { 1578 output << " SkipLayer"; 1579 } 1580 if ((hwcLayer.flags & HWC_IS_CURSOR_LAYER) != 0) { 1581 output << " IsCursorLayer"; 1582 } 1583 output << '\n'; 1584 } 1585 1586 return output.str(); 1587 } 1588 1589 static std::string to_string(const hwc_display_contents_1_t& hwcContents, 1590 int32_t hwc1MinorVersion) 1591 { 1592 const char* fill = " "; 1593 1594 std::stringstream output; 1595 output << fill << "Geometry changed: " << 1596 ((hwcContents.flags & HWC_GEOMETRY_CHANGED) != 0 ? "Y\n" : "N\n"); 1597 1598 output << fill << hwcContents.numHwLayers << " Layer" << 1599 ((hwcContents.numHwLayers == 1) ? "\n" : "s\n"); 1600 for (size_t layer = 0; layer < hwcContents.numHwLayers; ++layer) { 1601 output << fill << " Layer " << layer; 1602 output << to_string(hwcContents.hwLayers[layer], hwc1MinorVersion); 1603 } 1604 1605 if (hwcContents.outbuf != nullptr) { 1606 output << fill << "Output buffer: " << hwcContents.outbuf << "/" << 1607 hwcContents.outbufAcquireFenceFd << '\n'; 1608 } 1609 1610 return output.str(); 1611 } 1612 1613 std::string HWC2On1Adapter::Display::dump() const 1614 { 1615 std::unique_lock<std::recursive_mutex> lock(mStateMutex); 1616 1617 std::stringstream output; 1618 1619 output << " Display " << mId << ": "; 1620 output << to_string(mType) << " "; 1621 output << "HWC1 ID: " << mHwc1Id << " "; 1622 output << "Power mode: " << to_string(mPowerMode) << " "; 1623 output << "Vsync: " << to_string(mVsyncEnabled) << '\n'; 1624 1625 output << " Color modes [active]:"; 1626 for (const auto& mode : mColorModes) { 1627 if (mode == mActiveColorMode) { 1628 output << " [" << mode << ']'; 1629 } else { 1630 output << " " << mode; 1631 } 1632 } 1633 output << '\n'; 1634 1635 output << " " << mConfigs.size() << " Config" << 1636 (mConfigs.size() == 1 ? "" : "s") << " (* active)\n"; 1637 for (const auto& config : mConfigs) { 1638 output << (config == mActiveConfig ? " * " : " "); 1639 output << config->toString(true) << '\n'; 1640 } 1641 1642 output << " " << mLayers.size() << " Layer" << 1643 (mLayers.size() == 1 ? "" : "s") << '\n'; 1644 for (const auto& layer : mLayers) { 1645 output << layer->dump(); 1646 } 1647 1648 output << " Client target: " << mClientTarget.getBuffer() << '\n'; 1649 1650 if (mOutputBuffer.getBuffer() != nullptr) { 1651 output << " Output buffer: " << mOutputBuffer.getBuffer() << '\n'; 1652 } 1653 1654 if (mHwc1ReceivedContents) { 1655 output << " Last received HWC1 state\n"; 1656 output << to_string(*mHwc1ReceivedContents, mDevice.mHwc1MinorVersion); 1657 } else if (mHwc1RequestedContents) { 1658 output << " Last requested HWC1 state\n"; 1659 output << to_string(*mHwc1RequestedContents, mDevice.mHwc1MinorVersion); 1660 } 1661 1662 return output.str(); 1663 } 1664 1665 void HWC2On1Adapter::Display::Config::setAttribute(HWC2::Attribute attribute, 1666 int32_t value) 1667 { 1668 mAttributes[attribute] = value; 1669 } 1670 1671 int32_t HWC2On1Adapter::Display::Config::getAttribute(Attribute attribute) const 1672 { 1673 if (mAttributes.count(attribute) == 0) { 1674 return -1; 1675 } 1676 return mAttributes.at(attribute); 1677 } 1678 1679 void HWC2On1Adapter::Display::Config::setHwc1Id(uint32_t id) 1680 { 1681 int32_t colorTransform = getAttribute(ColorTransform); 1682 mHwc1Ids.emplace(colorTransform, id); 1683 } 1684 1685 bool HWC2On1Adapter::Display::Config::hasHwc1Id(uint32_t id) const 1686 { 1687 for (const auto& idPair : mHwc1Ids) { 1688 if (id == idPair.second) { 1689 return true; 1690 } 1691 } 1692 return false; 1693 } 1694 1695 int32_t HWC2On1Adapter::Display::Config::getColorModeForHwc1Id( 1696 uint32_t id) const 1697 { 1698 for (const auto& idPair : mHwc1Ids) { 1699 if (id == idPair.second) { 1700 return idPair.first; 1701 } 1702 } 1703 return -1; 1704 } 1705 1706 Error HWC2On1Adapter::Display::Config::getHwc1IdForColorMode(int32_t mode, 1707 uint32_t* outId) const 1708 { 1709 for (const auto& idPair : mHwc1Ids) { 1710 if (mode == idPair.first) { 1711 *outId = idPair.second; 1712 return Error::None; 1713 } 1714 } 1715 ALOGE("Unable to find HWC1 ID for color mode %d on config %u", mode, mId); 1716 return Error::BadParameter; 1717 } 1718 1719 bool HWC2On1Adapter::Display::Config::merge(const Config& other) 1720 { 1721 auto attributes = {HWC2::Attribute::Width, HWC2::Attribute::Height, 1722 HWC2::Attribute::VsyncPeriod, HWC2::Attribute::DpiX, 1723 HWC2::Attribute::DpiY}; 1724 for (auto attribute : attributes) { 1725 if (getAttribute(attribute) != other.getAttribute(attribute)) { 1726 return false; 1727 } 1728 } 1729 int32_t otherColorTransform = other.getAttribute(ColorTransform); 1730 if (mHwc1Ids.count(otherColorTransform) != 0) { 1731 ALOGE("Attempted to merge two configs (%u and %u) which appear to be " 1732 "identical", mHwc1Ids.at(otherColorTransform), 1733 other.mHwc1Ids.at(otherColorTransform)); 1734 return false; 1735 } 1736 mHwc1Ids.emplace(otherColorTransform, 1737 other.mHwc1Ids.at(otherColorTransform)); 1738 return true; 1739 } 1740 1741 std::set<int32_t> HWC2On1Adapter::Display::Config::getColorTransforms() const 1742 { 1743 std::set<int32_t> colorTransforms; 1744 for (const auto& idPair : mHwc1Ids) { 1745 colorTransforms.emplace(idPair.first); 1746 } 1747 return colorTransforms; 1748 } 1749 1750 std::string HWC2On1Adapter::Display::Config::toString(bool splitLine) const 1751 { 1752 std::string output; 1753 1754 const size_t BUFFER_SIZE = 100; 1755 char buffer[BUFFER_SIZE] = {}; 1756 auto writtenBytes = snprintf(buffer, BUFFER_SIZE, 1757 "%u x %u", mAttributes.at(HWC2::Attribute::Width), 1758 mAttributes.at(HWC2::Attribute::Height)); 1759 output.append(buffer, writtenBytes); 1760 1761 if (mAttributes.count(HWC2::Attribute::VsyncPeriod) != 0) { 1762 std::memset(buffer, 0, BUFFER_SIZE); 1763 writtenBytes = snprintf(buffer, BUFFER_SIZE, " @ %.1f Hz", 1764 1e9 / mAttributes.at(HWC2::Attribute::VsyncPeriod)); 1765 output.append(buffer, writtenBytes); 1766 } 1767 1768 if (mAttributes.count(HWC2::Attribute::DpiX) != 0 && 1769 mAttributes.at(HWC2::Attribute::DpiX) != -1) { 1770 std::memset(buffer, 0, BUFFER_SIZE); 1771 writtenBytes = snprintf(buffer, BUFFER_SIZE, 1772 ", DPI: %.1f x %.1f", 1773 mAttributes.at(HWC2::Attribute::DpiX) / 1000.0f, 1774 mAttributes.at(HWC2::Attribute::DpiY) / 1000.0f); 1775 output.append(buffer, writtenBytes); 1776 } 1777 1778 std::memset(buffer, 0, BUFFER_SIZE); 1779 if (splitLine) { 1780 writtenBytes = snprintf(buffer, BUFFER_SIZE, 1781 "\n HWC1 ID/Color transform:"); 1782 } else { 1783 writtenBytes = snprintf(buffer, BUFFER_SIZE, 1784 ", HWC1 ID/Color transform:"); 1785 } 1786 output.append(buffer, writtenBytes); 1787 1788 1789 for (const auto& id : mHwc1Ids) { 1790 int32_t colorTransform = id.first; 1791 uint32_t hwc1Id = id.second; 1792 std::memset(buffer, 0, BUFFER_SIZE); 1793 if (colorTransform == mDisplay.mActiveColorMode) { 1794 writtenBytes = snprintf(buffer, BUFFER_SIZE, " [%u/%d]", hwc1Id, 1795 colorTransform); 1796 } else { 1797 writtenBytes = snprintf(buffer, BUFFER_SIZE, " %u/%d", hwc1Id, 1798 colorTransform); 1799 } 1800 output.append(buffer, writtenBytes); 1801 } 1802 1803 return output; 1804 } 1805 1806 std::shared_ptr<const HWC2On1Adapter::Display::Config> 1807 HWC2On1Adapter::Display::getConfig(hwc2_config_t configId) const 1808 { 1809 if (configId > mConfigs.size() || !mConfigs[configId]->isOnDisplay(*this)) { 1810 return nullptr; 1811 } 1812 return mConfigs[configId]; 1813 } 1814 1815 void HWC2On1Adapter::Display::populateColorModes() 1816 { 1817 mColorModes = mConfigs[0]->getColorTransforms(); 1818 for (const auto& config : mConfigs) { 1819 std::set<int32_t> intersection; 1820 auto configModes = config->getColorTransforms(); 1821 std::set_intersection(mColorModes.cbegin(), mColorModes.cend(), 1822 configModes.cbegin(), configModes.cend(), 1823 std::inserter(intersection, intersection.begin())); 1824 std::swap(intersection, mColorModes); 1825 } 1826 } 1827 1828 void HWC2On1Adapter::Display::initializeActiveConfig() 1829 { 1830 if (mDevice.mHwc1Device->getActiveConfig == nullptr) { 1831 ALOGV("getActiveConfig is null, choosing config 0"); 1832 mActiveConfig = mConfigs[0]; 1833 mActiveColorMode = -1; 1834 return; 1835 } 1836 1837 auto activeConfig = mDevice.mHwc1Device->getActiveConfig( 1838 mDevice.mHwc1Device, mHwc1Id); 1839 if (activeConfig >= 0) { 1840 for (const auto& config : mConfigs) { 1841 if (config->hasHwc1Id(activeConfig)) { 1842 ALOGV("Setting active config to %d for HWC1 config %u", 1843 config->getId(), activeConfig); 1844 mActiveConfig = config; 1845 mActiveColorMode = config->getColorModeForHwc1Id(activeConfig); 1846 break; 1847 } 1848 } 1849 if (!mActiveConfig) { 1850 ALOGV("Unable to find active HWC1 config %u, defaulting to " 1851 "config 0", activeConfig); 1852 mActiveConfig = mConfigs[0]; 1853 mActiveColorMode = -1; 1854 } 1855 } 1856 } 1857 1858 void HWC2On1Adapter::Display::reallocateHwc1Contents() 1859 { 1860 // Allocate an additional layer for the framebuffer target 1861 auto numLayers = mLayers.size() + 1; 1862 size_t size = sizeof(hwc_display_contents_1_t) + 1863 sizeof(hwc_layer_1_t) * numLayers; 1864 ALOGV("[%" PRIu64 "] reallocateHwc1Contents creating %zd layer%s", mId, 1865 numLayers, numLayers != 1 ? "s" : ""); 1866 auto contents = 1867 static_cast<hwc_display_contents_1_t*>(std::calloc(size, 1)); 1868 contents->numHwLayers = numLayers; 1869 mHwc1RequestedContents.reset(contents); 1870 } 1871 1872 void HWC2On1Adapter::Display::assignHwc1LayerIds() 1873 { 1874 mHwc1LayerMap.clear(); 1875 size_t nextHwc1Id = 0; 1876 for (auto& layer : mLayers) { 1877 mHwc1LayerMap[nextHwc1Id] = layer; 1878 layer->setHwc1Id(nextHwc1Id++); 1879 } 1880 } 1881 1882 void HWC2On1Adapter::Display::updateTypeChanges(const hwc_layer_1_t& hwc1Layer, 1883 const Layer& layer) 1884 { 1885 auto layerId = layer.getId(); 1886 switch (hwc1Layer.compositionType) { 1887 case HWC_FRAMEBUFFER: 1888 if (layer.getCompositionType() != Composition::Client) { 1889 mChanges->addTypeChange(layerId, Composition::Client); 1890 } 1891 break; 1892 case HWC_OVERLAY: 1893 if (layer.getCompositionType() != Composition::Device) { 1894 mChanges->addTypeChange(layerId, Composition::Device); 1895 } 1896 break; 1897 case HWC_BACKGROUND: 1898 ALOGE_IF(layer.getCompositionType() != Composition::SolidColor, 1899 "updateTypeChanges: HWC1 requested BACKGROUND, but HWC2" 1900 " wasn't expecting SolidColor"); 1901 break; 1902 case HWC_FRAMEBUFFER_TARGET: 1903 // Do nothing, since it shouldn't be modified by HWC1 1904 break; 1905 case HWC_SIDEBAND: 1906 ALOGE_IF(layer.getCompositionType() != Composition::Sideband, 1907 "updateTypeChanges: HWC1 requested SIDEBAND, but HWC2" 1908 " wasn't expecting Sideband"); 1909 break; 1910 case HWC_CURSOR_OVERLAY: 1911 ALOGE_IF(layer.getCompositionType() != Composition::Cursor, 1912 "updateTypeChanges: HWC1 requested CURSOR_OVERLAY, but" 1913 " HWC2 wasn't expecting Cursor"); 1914 break; 1915 } 1916 } 1917 1918 void HWC2On1Adapter::Display::updateLayerRequests( 1919 const hwc_layer_1_t& hwc1Layer, const Layer& layer) 1920 { 1921 if ((hwc1Layer.hints & HWC_HINT_CLEAR_FB) != 0) { 1922 mChanges->addLayerRequest(layer.getId(), 1923 LayerRequest::ClearClientTarget); 1924 } 1925 } 1926 1927 void HWC2On1Adapter::Display::prepareFramebufferTarget() 1928 { 1929 // We check that mActiveConfig is valid in Display::prepare 1930 int32_t width = mActiveConfig->getAttribute(Attribute::Width); 1931 int32_t height = mActiveConfig->getAttribute(Attribute::Height); 1932 1933 auto& hwc1Target = mHwc1RequestedContents->hwLayers[mLayers.size()]; 1934 hwc1Target.compositionType = HWC_FRAMEBUFFER_TARGET; 1935 hwc1Target.releaseFenceFd = -1; 1936 hwc1Target.hints = 0; 1937 hwc1Target.flags = 0; 1938 hwc1Target.transform = 0; 1939 hwc1Target.blending = HWC_BLENDING_PREMULT; 1940 if (mDevice.getHwc1MinorVersion() < 3) { 1941 hwc1Target.sourceCropi = {0, 0, width, height}; 1942 } else { 1943 hwc1Target.sourceCropf = {0.0f, 0.0f, static_cast<float>(width), 1944 static_cast<float>(height)}; 1945 } 1946 hwc1Target.displayFrame = {0, 0, width, height}; 1947 hwc1Target.planeAlpha = 255; 1948 hwc1Target.visibleRegionScreen.numRects = 1; 1949 auto rects = static_cast<hwc_rect_t*>(std::malloc(sizeof(hwc_rect_t))); 1950 rects[0].left = 0; 1951 rects[0].top = 0; 1952 rects[0].right = width; 1953 rects[0].bottom = height; 1954 hwc1Target.visibleRegionScreen.rects = rects; 1955 1956 // We will set this to the correct value in set 1957 hwc1Target.acquireFenceFd = -1; 1958 } 1959 1960 // Layer functions 1961 1962 std::atomic<hwc2_layer_t> HWC2On1Adapter::Layer::sNextId(1); 1963 1964 HWC2On1Adapter::Layer::Layer(Display& display) 1965 : mId(sNextId++), 1966 mDisplay(display), 1967 mDirtyCount(0), 1968 mBuffer(), 1969 mSurfaceDamage(), 1970 mBlendMode(*this, BlendMode::None), 1971 mColor(*this, {0, 0, 0, 0}), 1972 mCompositionType(*this, Composition::Invalid), 1973 mDisplayFrame(*this, {0, 0, -1, -1}), 1974 mPlaneAlpha(*this, 0.0f), 1975 mSidebandStream(*this, nullptr), 1976 mSourceCrop(*this, {0.0f, 0.0f, -1.0f, -1.0f}), 1977 mTransform(*this, Transform::None), 1978 mVisibleRegion(*this, std::vector<hwc_rect_t>()), 1979 mZ(0), 1980 mReleaseFence(), 1981 mHwc1Id(0), 1982 mHasUnsupportedDataspace(false), 1983 mHasUnsupportedPlaneAlpha(false) {} 1984 1985 bool HWC2On1Adapter::SortLayersByZ::operator()( 1986 const std::shared_ptr<Layer>& lhs, const std::shared_ptr<Layer>& rhs) 1987 { 1988 return lhs->getZ() < rhs->getZ(); 1989 } 1990 1991 Error HWC2On1Adapter::Layer::setBuffer(buffer_handle_t buffer, 1992 int32_t acquireFence) 1993 { 1994 ALOGV("Setting acquireFence to %d for layer %" PRIu64, acquireFence, mId); 1995 mBuffer.setBuffer(buffer); 1996 mBuffer.setFence(acquireFence); 1997 return Error::None; 1998 } 1999 2000 Error HWC2On1Adapter::Layer::setCursorPosition(int32_t x, int32_t y) 2001 { 2002 if (mCompositionType.getValue() != Composition::Cursor) { 2003 return Error::BadLayer; 2004 } 2005 2006 if (mDisplay.hasChanges()) { 2007 return Error::NotValidated; 2008 } 2009 2010 auto displayId = mDisplay.getHwc1Id(); 2011 auto hwc1Device = mDisplay.getDevice().getHwc1Device(); 2012 hwc1Device->setCursorPositionAsync(hwc1Device, displayId, x, y); 2013 return Error::None; 2014 } 2015 2016 Error HWC2On1Adapter::Layer::setSurfaceDamage(hwc_region_t damage) 2017 { 2018 mSurfaceDamage.resize(damage.numRects); 2019 std::copy_n(damage.rects, damage.numRects, mSurfaceDamage.begin()); 2020 return Error::None; 2021 } 2022 2023 // Layer state functions 2024 2025 Error HWC2On1Adapter::Layer::setBlendMode(BlendMode mode) 2026 { 2027 mBlendMode.setPending(mode); 2028 return Error::None; 2029 } 2030 2031 Error HWC2On1Adapter::Layer::setColor(hwc_color_t color) 2032 { 2033 mColor.setPending(color); 2034 return Error::None; 2035 } 2036 2037 Error HWC2On1Adapter::Layer::setCompositionType(Composition type) 2038 { 2039 mCompositionType.setPending(type); 2040 return Error::None; 2041 } 2042 2043 Error HWC2On1Adapter::Layer::setDataspace(android_dataspace_t dataspace) 2044 { 2045 mHasUnsupportedDataspace = (dataspace != HAL_DATASPACE_UNKNOWN); 2046 return Error::None; 2047 } 2048 2049 Error HWC2On1Adapter::Layer::setDisplayFrame(hwc_rect_t frame) 2050 { 2051 mDisplayFrame.setPending(frame); 2052 return Error::None; 2053 } 2054 2055 Error HWC2On1Adapter::Layer::setPlaneAlpha(float alpha) 2056 { 2057 mPlaneAlpha.setPending(alpha); 2058 return Error::None; 2059 } 2060 2061 Error HWC2On1Adapter::Layer::setSidebandStream(const native_handle_t* stream) 2062 { 2063 mSidebandStream.setPending(stream); 2064 return Error::None; 2065 } 2066 2067 Error HWC2On1Adapter::Layer::setSourceCrop(hwc_frect_t crop) 2068 { 2069 mSourceCrop.setPending(crop); 2070 return Error::None; 2071 } 2072 2073 Error HWC2On1Adapter::Layer::setTransform(Transform transform) 2074 { 2075 mTransform.setPending(transform); 2076 return Error::None; 2077 } 2078 2079 Error HWC2On1Adapter::Layer::setVisibleRegion(hwc_region_t rawVisible) 2080 { 2081 std::vector<hwc_rect_t> visible(rawVisible.rects, 2082 rawVisible.rects + rawVisible.numRects); 2083 mVisibleRegion.setPending(std::move(visible)); 2084 return Error::None; 2085 } 2086 2087 Error HWC2On1Adapter::Layer::setZ(uint32_t z) 2088 { 2089 mZ = z; 2090 return Error::None; 2091 } 2092 2093 void HWC2On1Adapter::Layer::addReleaseFence(int fenceFd) 2094 { 2095 ALOGV("addReleaseFence %d to layer %" PRIu64, fenceFd, mId); 2096 mReleaseFence.add(fenceFd); 2097 } 2098 2099 const sp<Fence>& HWC2On1Adapter::Layer::getReleaseFence() const 2100 { 2101 return mReleaseFence.get(); 2102 } 2103 2104 void HWC2On1Adapter::Layer::applyState(hwc_layer_1_t& hwc1Layer, 2105 bool applyAllState) 2106 { 2107 applyCommonState(hwc1Layer, applyAllState); 2108 auto compositionType = mCompositionType.getPendingValue(); 2109 if (compositionType == Composition::SolidColor) { 2110 applySolidColorState(hwc1Layer, applyAllState); 2111 } else if (compositionType == Composition::Sideband) { 2112 applySidebandState(hwc1Layer, applyAllState); 2113 } else { 2114 applyBufferState(hwc1Layer); 2115 } 2116 applyCompositionType(hwc1Layer, applyAllState); 2117 } 2118 2119 // Layer dump helpers 2120 2121 static std::string regionStrings(const std::vector<hwc_rect_t>& visibleRegion, 2122 const std::vector<hwc_rect_t>& surfaceDamage) 2123 { 2124 std::string regions; 2125 regions += " Visible Region"; 2126 regions.resize(40, ' '); 2127 regions += "Surface Damage\n"; 2128 2129 size_t numPrinted = 0; 2130 size_t maxSize = std::max(visibleRegion.size(), surfaceDamage.size()); 2131 while (numPrinted < maxSize) { 2132 std::string line(" "); 2133 if (visibleRegion.empty() && numPrinted == 0) { 2134 line += "None"; 2135 } else if (numPrinted < visibleRegion.size()) { 2136 line += rectString(visibleRegion[numPrinted]); 2137 } 2138 line.resize(40, ' '); 2139 if (surfaceDamage.empty() && numPrinted == 0) { 2140 line += "None"; 2141 } else if (numPrinted < surfaceDamage.size()) { 2142 line += rectString(surfaceDamage[numPrinted]); 2143 } 2144 line += '\n'; 2145 regions += line; 2146 ++numPrinted; 2147 } 2148 return regions; 2149 } 2150 2151 std::string HWC2On1Adapter::Layer::dump() const 2152 { 2153 std::stringstream output; 2154 const char* fill = " "; 2155 2156 output << fill << to_string(mCompositionType.getPendingValue()); 2157 output << " Layer HWC2/1: " << mId << "/" << mHwc1Id << " "; 2158 output << "Z: " << mZ; 2159 if (mCompositionType.getValue() == HWC2::Composition::SolidColor) { 2160 output << " " << colorString(mColor.getValue()); 2161 } else if (mCompositionType.getValue() == HWC2::Composition::Sideband) { 2162 output << " Handle: " << mSidebandStream.getValue() << '\n'; 2163 } else { 2164 output << " Buffer: " << mBuffer.getBuffer() << "/" << 2165 mBuffer.getFence() << '\n'; 2166 output << fill << " Display frame [LTRB]: " << 2167 rectString(mDisplayFrame.getValue()) << '\n'; 2168 output << fill << " Source crop: " << 2169 frectString(mSourceCrop.getValue()) << '\n'; 2170 output << fill << " Transform: " << to_string(mTransform.getValue()); 2171 output << " Blend mode: " << to_string(mBlendMode.getValue()); 2172 if (mPlaneAlpha.getValue() != 1.0f) { 2173 output << " Alpha: " << 2174 alphaString(mPlaneAlpha.getValue()) << '\n'; 2175 } else { 2176 output << '\n'; 2177 } 2178 output << regionStrings(mVisibleRegion.getValue(), mSurfaceDamage); 2179 } 2180 return output.str(); 2181 } 2182 2183 static int getHwc1Blending(HWC2::BlendMode blendMode) 2184 { 2185 switch (blendMode) { 2186 case BlendMode::Coverage: return HWC_BLENDING_COVERAGE; 2187 case BlendMode::Premultiplied: return HWC_BLENDING_PREMULT; 2188 default: return HWC_BLENDING_NONE; 2189 } 2190 } 2191 2192 void HWC2On1Adapter::Layer::applyCommonState(hwc_layer_1_t& hwc1Layer, 2193 bool applyAllState) 2194 { 2195 auto minorVersion = mDisplay.getDevice().getHwc1MinorVersion(); 2196 if (applyAllState || mBlendMode.isDirty()) { 2197 hwc1Layer.blending = getHwc1Blending(mBlendMode.getPendingValue()); 2198 mBlendMode.latch(); 2199 } 2200 if (applyAllState || mDisplayFrame.isDirty()) { 2201 hwc1Layer.displayFrame = mDisplayFrame.getPendingValue(); 2202 mDisplayFrame.latch(); 2203 } 2204 if (applyAllState || mPlaneAlpha.isDirty()) { 2205 auto pendingAlpha = mPlaneAlpha.getPendingValue(); 2206 if (minorVersion < 2) { 2207 mHasUnsupportedPlaneAlpha = pendingAlpha < 1.0f; 2208 } else { 2209 hwc1Layer.planeAlpha = 2210 static_cast<uint8_t>(255.0f * pendingAlpha + 0.5f); 2211 } 2212 mPlaneAlpha.latch(); 2213 } 2214 if (applyAllState || mSourceCrop.isDirty()) { 2215 if (minorVersion < 3) { 2216 auto pending = mSourceCrop.getPendingValue(); 2217 hwc1Layer.sourceCropi.left = 2218 static_cast<int32_t>(std::ceil(pending.left)); 2219 hwc1Layer.sourceCropi.top = 2220 static_cast<int32_t>(std::ceil(pending.top)); 2221 hwc1Layer.sourceCropi.right = 2222 static_cast<int32_t>(std::floor(pending.right)); 2223 hwc1Layer.sourceCropi.bottom = 2224 static_cast<int32_t>(std::floor(pending.bottom)); 2225 } else { 2226 hwc1Layer.sourceCropf = mSourceCrop.getPendingValue(); 2227 } 2228 mSourceCrop.latch(); 2229 } 2230 if (applyAllState || mTransform.isDirty()) { 2231 hwc1Layer.transform = 2232 static_cast<uint32_t>(mTransform.getPendingValue()); 2233 mTransform.latch(); 2234 } 2235 if (applyAllState || mVisibleRegion.isDirty()) { 2236 auto& hwc1VisibleRegion = hwc1Layer.visibleRegionScreen; 2237 2238 std::free(const_cast<hwc_rect_t*>(hwc1VisibleRegion.rects)); 2239 2240 auto pending = mVisibleRegion.getPendingValue(); 2241 hwc_rect_t* newRects = static_cast<hwc_rect_t*>( 2242 std::malloc(sizeof(hwc_rect_t) * pending.size())); 2243 std::copy(pending.begin(), pending.end(), newRects); 2244 hwc1VisibleRegion.rects = const_cast<const hwc_rect_t*>(newRects); 2245 hwc1VisibleRegion.numRects = pending.size(); 2246 mVisibleRegion.latch(); 2247 } 2248 } 2249 2250 void HWC2On1Adapter::Layer::applySolidColorState(hwc_layer_1_t& hwc1Layer, 2251 bool applyAllState) 2252 { 2253 if (applyAllState || mColor.isDirty()) { 2254 hwc1Layer.backgroundColor = mColor.getPendingValue(); 2255 mColor.latch(); 2256 } 2257 } 2258 2259 void HWC2On1Adapter::Layer::applySidebandState(hwc_layer_1_t& hwc1Layer, 2260 bool applyAllState) 2261 { 2262 if (applyAllState || mSidebandStream.isDirty()) { 2263 hwc1Layer.sidebandStream = mSidebandStream.getPendingValue(); 2264 mSidebandStream.latch(); 2265 } 2266 } 2267 2268 void HWC2On1Adapter::Layer::applyBufferState(hwc_layer_1_t& hwc1Layer) 2269 { 2270 hwc1Layer.handle = mBuffer.getBuffer(); 2271 hwc1Layer.acquireFenceFd = mBuffer.getFence(); 2272 } 2273 2274 void HWC2On1Adapter::Layer::applyCompositionType(hwc_layer_1_t& hwc1Layer, 2275 bool applyAllState) 2276 { 2277 // HWC1 never supports color transforms or dataspaces and only sometimes 2278 // supports plane alpha (depending on the version). These require us to drop 2279 // some or all layers to client composition. 2280 if (mHasUnsupportedDataspace || mHasUnsupportedPlaneAlpha || 2281 mDisplay.hasColorTransform()) { 2282 hwc1Layer.compositionType = HWC_FRAMEBUFFER; 2283 hwc1Layer.flags = HWC_SKIP_LAYER; 2284 return; 2285 } 2286 2287 if (applyAllState || mCompositionType.isDirty()) { 2288 hwc1Layer.flags = 0; 2289 switch (mCompositionType.getPendingValue()) { 2290 case Composition::Client: 2291 hwc1Layer.compositionType = HWC_FRAMEBUFFER; 2292 hwc1Layer.flags |= HWC_SKIP_LAYER; 2293 break; 2294 case Composition::Device: 2295 hwc1Layer.compositionType = HWC_FRAMEBUFFER; 2296 break; 2297 case Composition::SolidColor: 2298 hwc1Layer.compositionType = HWC_BACKGROUND; 2299 break; 2300 case Composition::Cursor: 2301 hwc1Layer.compositionType = HWC_FRAMEBUFFER; 2302 if (mDisplay.getDevice().getHwc1MinorVersion() >= 4) { 2303 hwc1Layer.hints |= HWC_IS_CURSOR_LAYER; 2304 } 2305 break; 2306 case Composition::Sideband: 2307 if (mDisplay.getDevice().getHwc1MinorVersion() < 4) { 2308 hwc1Layer.compositionType = HWC_SIDEBAND; 2309 } else { 2310 hwc1Layer.compositionType = HWC_FRAMEBUFFER; 2311 hwc1Layer.flags |= HWC_SKIP_LAYER; 2312 } 2313 break; 2314 default: 2315 hwc1Layer.compositionType = HWC_FRAMEBUFFER; 2316 hwc1Layer.flags |= HWC_SKIP_LAYER; 2317 break; 2318 } 2319 ALOGV("Layer %" PRIu64 " %s set to %d", mId, 2320 to_string(mCompositionType.getPendingValue()).c_str(), 2321 hwc1Layer.compositionType); 2322 ALOGV_IF(hwc1Layer.flags & HWC_SKIP_LAYER, " and skipping"); 2323 mCompositionType.latch(); 2324 } 2325 } 2326 2327 // Adapter helpers 2328 2329 void HWC2On1Adapter::populateCapabilities() 2330 { 2331 ALOGV("populateCapabilities"); 2332 if (mHwc1MinorVersion >= 3U) { 2333 int supportedTypes = 0; 2334 auto result = mHwc1Device->query(mHwc1Device, 2335 HWC_DISPLAY_TYPES_SUPPORTED, &supportedTypes); 2336 if ((result == 0) && ((supportedTypes & HWC_DISPLAY_VIRTUAL) != 0)) { 2337 ALOGI("Found support for HWC virtual displays"); 2338 mHwc1SupportsVirtualDisplays = true; 2339 } 2340 } 2341 if (mHwc1MinorVersion >= 4U) { 2342 mCapabilities.insert(Capability::SidebandStream); 2343 } 2344 } 2345 2346 HWC2On1Adapter::Display* HWC2On1Adapter::getDisplay(hwc2_display_t id) 2347 { 2348 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex); 2349 2350 auto display = mDisplays.find(id); 2351 if (display == mDisplays.end()) { 2352 return nullptr; 2353 } 2354 2355 return display->second.get(); 2356 } 2357 2358 std::tuple<HWC2On1Adapter::Layer*, Error> HWC2On1Adapter::getLayer( 2359 hwc2_display_t displayId, hwc2_layer_t layerId) 2360 { 2361 auto display = getDisplay(displayId); 2362 if (!display) { 2363 return std::make_tuple(static_cast<Layer*>(nullptr), Error::BadDisplay); 2364 } 2365 2366 auto layerEntry = mLayers.find(layerId); 2367 if (layerEntry == mLayers.end()) { 2368 return std::make_tuple(static_cast<Layer*>(nullptr), Error::BadLayer); 2369 } 2370 2371 auto layer = layerEntry->second; 2372 if (layer->getDisplay().getId() != displayId) { 2373 return std::make_tuple(static_cast<Layer*>(nullptr), Error::BadLayer); 2374 } 2375 return std::make_tuple(layer.get(), Error::None); 2376 } 2377 2378 void HWC2On1Adapter::populatePrimary() 2379 { 2380 ALOGV("populatePrimary"); 2381 2382 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex); 2383 2384 auto display = 2385 std::make_shared<Display>(*this, HWC2::DisplayType::Physical); 2386 mHwc1DisplayMap[HWC_DISPLAY_PRIMARY] = display->getId(); 2387 display->setHwc1Id(HWC_DISPLAY_PRIMARY); 2388 display->populateConfigs(); 2389 mDisplays.emplace(display->getId(), std::move(display)); 2390 } 2391 2392 bool HWC2On1Adapter::prepareAllDisplays() 2393 { 2394 ATRACE_CALL(); 2395 2396 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex); 2397 2398 for (const auto& displayPair : mDisplays) { 2399 auto& display = displayPair.second; 2400 if (!display->prepare()) { 2401 return false; 2402 } 2403 } 2404 2405 if (mHwc1DisplayMap.count(0) == 0) { 2406 ALOGE("prepareAllDisplays: Unable to find primary HWC1 display"); 2407 return false; 2408 } 2409 2410 // Always push the primary display 2411 std::vector<HWC2On1Adapter::Display::HWC1Contents> requestedContents; 2412 auto primaryDisplayId = mHwc1DisplayMap[HWC_DISPLAY_PRIMARY]; 2413 auto& primaryDisplay = mDisplays[primaryDisplayId]; 2414 auto primaryDisplayContents = primaryDisplay->cloneRequestedContents(); 2415 requestedContents.push_back(std::move(primaryDisplayContents)); 2416 2417 // Push the external display, if present 2418 if (mHwc1DisplayMap.count(HWC_DISPLAY_EXTERNAL) != 0) { 2419 auto externalDisplayId = mHwc1DisplayMap[HWC_DISPLAY_EXTERNAL]; 2420 auto& externalDisplay = mDisplays[externalDisplayId]; 2421 auto externalDisplayContents = 2422 externalDisplay->cloneRequestedContents(); 2423 requestedContents.push_back(std::move(externalDisplayContents)); 2424 } else { 2425 // Even if an external display isn't present, we still need to send 2426 // at least two displays down to HWC1 2427 requestedContents.push_back(nullptr); 2428 } 2429 2430 // Push the hardware virtual display, if supported and present 2431 if (mHwc1MinorVersion >= 3) { 2432 if (mHwc1DisplayMap.count(HWC_DISPLAY_VIRTUAL) != 0) { 2433 auto virtualDisplayId = mHwc1DisplayMap[HWC_DISPLAY_VIRTUAL]; 2434 auto& virtualDisplay = mDisplays[virtualDisplayId]; 2435 auto virtualDisplayContents = 2436 virtualDisplay->cloneRequestedContents(); 2437 requestedContents.push_back(std::move(virtualDisplayContents)); 2438 } else { 2439 requestedContents.push_back(nullptr); 2440 } 2441 } 2442 2443 mHwc1Contents.clear(); 2444 for (auto& displayContents : requestedContents) { 2445 mHwc1Contents.push_back(displayContents.get()); 2446 if (!displayContents) { 2447 continue; 2448 } 2449 2450 ALOGV("Display %zd layers:", mHwc1Contents.size() - 1); 2451 for (size_t l = 0; l < displayContents->numHwLayers; ++l) { 2452 auto& layer = displayContents->hwLayers[l]; 2453 ALOGV(" %zd: %d", l, layer.compositionType); 2454 } 2455 } 2456 2457 ALOGV("Calling HWC1 prepare"); 2458 { 2459 ATRACE_NAME("HWC1 prepare"); 2460 mHwc1Device->prepare(mHwc1Device, mHwc1Contents.size(), 2461 mHwc1Contents.data()); 2462 } 2463 2464 for (size_t c = 0; c < mHwc1Contents.size(); ++c) { 2465 auto& contents = mHwc1Contents[c]; 2466 if (!contents) { 2467 continue; 2468 } 2469 ALOGV("Display %zd layers:", c); 2470 for (size_t l = 0; l < contents->numHwLayers; ++l) { 2471 ALOGV(" %zd: %d", l, contents->hwLayers[l].compositionType); 2472 } 2473 } 2474 2475 // Return the received contents to their respective displays 2476 for (size_t hwc1Id = 0; hwc1Id < mHwc1Contents.size(); ++hwc1Id) { 2477 if (mHwc1Contents[hwc1Id] == nullptr) { 2478 continue; 2479 } 2480 2481 auto displayId = mHwc1DisplayMap[hwc1Id]; 2482 auto& display = mDisplays[displayId]; 2483 display->setReceivedContents(std::move(requestedContents[hwc1Id])); 2484 } 2485 2486 return true; 2487 } 2488 2489 Error HWC2On1Adapter::setAllDisplays() 2490 { 2491 ATRACE_CALL(); 2492 2493 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex); 2494 2495 // Make sure we're ready to validate 2496 for (size_t hwc1Id = 0; hwc1Id < mHwc1Contents.size(); ++hwc1Id) { 2497 if (mHwc1Contents[hwc1Id] == nullptr) { 2498 continue; 2499 } 2500 2501 auto displayId = mHwc1DisplayMap[hwc1Id]; 2502 auto& display = mDisplays[displayId]; 2503 Error error = display->set(*mHwc1Contents[hwc1Id]); 2504 if (error != Error::None) { 2505 ALOGE("setAllDisplays: Failed to set display %zd: %s", hwc1Id, 2506 to_string(error).c_str()); 2507 return error; 2508 } 2509 } 2510 2511 ALOGV("Calling HWC1 set"); 2512 { 2513 ATRACE_NAME("HWC1 set"); 2514 mHwc1Device->set(mHwc1Device, mHwc1Contents.size(), 2515 mHwc1Contents.data()); 2516 } 2517 2518 // Add retire and release fences 2519 for (size_t hwc1Id = 0; hwc1Id < mHwc1Contents.size(); ++hwc1Id) { 2520 if (mHwc1Contents[hwc1Id] == nullptr) { 2521 continue; 2522 } 2523 2524 auto displayId = mHwc1DisplayMap[hwc1Id]; 2525 auto& display = mDisplays[displayId]; 2526 auto retireFenceFd = mHwc1Contents[hwc1Id]->retireFenceFd; 2527 ALOGV("setAllDisplays: Adding retire fence %d to display %zd", 2528 retireFenceFd, hwc1Id); 2529 display->addRetireFence(mHwc1Contents[hwc1Id]->retireFenceFd); 2530 display->addReleaseFences(*mHwc1Contents[hwc1Id]); 2531 } 2532 2533 return Error::None; 2534 } 2535 2536 void HWC2On1Adapter::hwc1Invalidate() 2537 { 2538 ALOGV("Received hwc1Invalidate"); 2539 2540 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex); 2541 2542 // If the HWC2-side callback hasn't been registered yet, buffer this until 2543 // it is registered 2544 if (mCallbacks.count(Callback::Refresh) == 0) { 2545 mHasPendingInvalidate = true; 2546 return; 2547 } 2548 2549 const auto& callbackInfo = mCallbacks[Callback::Refresh]; 2550 std::vector<hwc2_display_t> displays; 2551 for (const auto& displayPair : mDisplays) { 2552 displays.emplace_back(displayPair.first); 2553 } 2554 2555 // Call back without the state lock held 2556 lock.unlock(); 2557 2558 auto refresh = reinterpret_cast<HWC2_PFN_REFRESH>(callbackInfo.pointer); 2559 for (auto display : displays) { 2560 refresh(callbackInfo.data, display); 2561 } 2562 } 2563 2564 void HWC2On1Adapter::hwc1Vsync(int hwc1DisplayId, int64_t timestamp) 2565 { 2566 ALOGV("Received hwc1Vsync(%d, %" PRId64 ")", hwc1DisplayId, timestamp); 2567 2568 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex); 2569 2570 // If the HWC2-side callback hasn't been registered yet, buffer this until 2571 // it is registered 2572 if (mCallbacks.count(Callback::Vsync) == 0) { 2573 mPendingVsyncs.emplace_back(hwc1DisplayId, timestamp); 2574 return; 2575 } 2576 2577 if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) { 2578 ALOGE("hwc1Vsync: Couldn't find display for HWC1 id %d", hwc1DisplayId); 2579 return; 2580 } 2581 2582 const auto& callbackInfo = mCallbacks[Callback::Vsync]; 2583 auto displayId = mHwc1DisplayMap[hwc1DisplayId]; 2584 2585 // Call back without the state lock held 2586 lock.unlock(); 2587 2588 auto vsync = reinterpret_cast<HWC2_PFN_VSYNC>(callbackInfo.pointer); 2589 vsync(callbackInfo.data, displayId, timestamp); 2590 } 2591 2592 void HWC2On1Adapter::hwc1Hotplug(int hwc1DisplayId, int connected) 2593 { 2594 ALOGV("Received hwc1Hotplug(%d, %d)", hwc1DisplayId, connected); 2595 2596 if (hwc1DisplayId != HWC_DISPLAY_EXTERNAL) { 2597 ALOGE("hwc1Hotplug: Received hotplug for non-external display"); 2598 return; 2599 } 2600 2601 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex); 2602 2603 // If the HWC2-side callback hasn't been registered yet, buffer this until 2604 // it is registered 2605 if (mCallbacks.count(Callback::Hotplug) == 0) { 2606 mPendingHotplugs.emplace_back(hwc1DisplayId, connected); 2607 return; 2608 } 2609 2610 hwc2_display_t displayId = UINT64_MAX; 2611 if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) { 2612 if (connected == 0) { 2613 ALOGW("hwc1Hotplug: Received disconnect for unconnected display"); 2614 return; 2615 } 2616 2617 // Create a new display on connect 2618 auto display = std::make_shared<HWC2On1Adapter::Display>(*this, 2619 HWC2::DisplayType::Physical); 2620 display->setHwc1Id(HWC_DISPLAY_EXTERNAL); 2621 display->populateConfigs(); 2622 displayId = display->getId(); 2623 mHwc1DisplayMap[HWC_DISPLAY_EXTERNAL] = displayId; 2624 mDisplays.emplace(displayId, std::move(display)); 2625 } else { 2626 if (connected != 0) { 2627 ALOGW("hwc1Hotplug: Received connect for previously connected " 2628 "display"); 2629 return; 2630 } 2631 2632 // Disconnect an existing display 2633 displayId = mHwc1DisplayMap[hwc1DisplayId]; 2634 mHwc1DisplayMap.erase(HWC_DISPLAY_EXTERNAL); 2635 mDisplays.erase(displayId); 2636 } 2637 2638 const auto& callbackInfo = mCallbacks[Callback::Hotplug]; 2639 2640 // Call back without the state lock held 2641 lock.unlock(); 2642 2643 auto hotplug = reinterpret_cast<HWC2_PFN_HOTPLUG>(callbackInfo.pointer); 2644 auto hwc2Connected = (connected == 0) ? 2645 HWC2::Connection::Disconnected : HWC2::Connection::Connected; 2646 hotplug(callbackInfo.data, displayId, static_cast<int32_t>(hwc2Connected)); 2647 } 2648 2649 } // namespace android 2650