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