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