blob: cc0dfb0945a5762378e1391d3cbf8c0c4dfbf401 [file] [log] [blame]
Dan Stozac6998d22015-09-24 17:03:36 -07001/*
2 * Copyright 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18
19#undef LOG_TAG
20#define LOG_TAG "HWC2On1Adapter"
21#define ATRACE_TAG ATRACE_TAG_GRAPHICS
22
23#include "HWC2On1Adapter.h"
24
25#include <hardware/hwcomposer.h>
26#include <log/log.h>
27#include <utils/Trace.h>
28
29#include <cstdlib>
30#include <chrono>
31#include <inttypes.h>
32#include <sstream>
33
34using namespace std::chrono_literals;
35
36static bool operator==(const hwc_color_t& lhs, const hwc_color_t& rhs) {
37 return lhs.r == rhs.r &&
38 lhs.g == rhs.g &&
39 lhs.b == rhs.b &&
40 lhs.a == rhs.a;
41}
42
43static bool operator==(const hwc_rect_t& lhs, const hwc_rect_t& rhs) {
44 return lhs.left == rhs.left &&
45 lhs.top == rhs.top &&
46 lhs.right == rhs.right &&
47 lhs.bottom == rhs.bottom;
48}
49
50static bool operator==(const hwc_frect_t& lhs, const hwc_frect_t& rhs) {
51 return lhs.left == rhs.left &&
52 lhs.top == rhs.top &&
53 lhs.right == rhs.right &&
54 lhs.bottom == rhs.bottom;
55}
56
57template <typename T>
58static inline bool operator!=(const T& lhs, const T& rhs)
59{
60 return !(lhs == rhs);
61}
62
63static uint8_t getMinorVersion(struct hwc_composer_device_1* device)
64{
65 auto version = device->common.version & HARDWARE_API_VERSION_2_MAJ_MIN_MASK;
66 return (version >> 16) & 0xF;
67}
68
69template <typename PFN, typename T>
70static hwc2_function_pointer_t asFP(T function)
71{
72 static_assert(std::is_same<PFN, T>::value, "Incompatible function pointer");
73 return reinterpret_cast<hwc2_function_pointer_t>(function);
74}
75
76using namespace HWC2;
77
Michael Wright28f24d02016-07-12 13:30:53 -070078static constexpr Attribute ColorMode = static_cast<Attribute>(6);
Dan Stoza076ac672016-03-14 10:47:53 -070079
Dan Stozac6998d22015-09-24 17:03:36 -070080namespace android {
81
82void 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
94class HWC2On1Adapter::Callbacks : public hwc_procs_t {
95 public:
96 Callbacks(HWC2On1Adapter& adapter) : mAdapter(adapter) {
97 invalidate = &invalidateHook;
98 vsync = &vsyncHook;
99 hotplug = &hotplugHook;
100 }
101
102 static void invalidateHook(const hwc_procs_t* procs) {
103 auto callbacks = static_cast<const Callbacks*>(procs);
104 callbacks->mAdapter.hwc1Invalidate();
105 }
106
107 static void vsyncHook(const hwc_procs_t* procs, int display,
108 int64_t timestamp) {
109 auto callbacks = static_cast<const Callbacks*>(procs);
110 callbacks->mAdapter.hwc1Vsync(display, timestamp);
111 }
112
113 static void hotplugHook(const hwc_procs_t* procs, int display,
114 int connected) {
115 auto callbacks = static_cast<const Callbacks*>(procs);
116 callbacks->mAdapter.hwc1Hotplug(display, connected);
117 }
118
119 private:
120 HWC2On1Adapter& mAdapter;
121};
122
123static 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
130HWC2On1Adapter::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
156HWC2On1Adapter::~HWC2On1Adapter() {
157 hwc_close_1(mHwc1Device);
158}
159
160void 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
178hwc2_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*>);
Dan Stoza076ac672016-03-14 10:47:53 -0700219 case FunctionDescriptor::GetColorModes:
220 return asFP<HWC2_PFN_GET_COLOR_MODES>(
221 displayHook<decltype(&Display::getColorModes),
222 &Display::getColorModes, uint32_t*, int32_t*>);
Dan Stozac6998d22015-09-24 17:03:36 -0700223 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*>);
Dan Stozaed40eba2016-03-16 12:33:52 -0700247 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*>);
Dan Stozac6998d22015-09-24 17:03:36 -0700252 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,
Dan Stoza5cf424b2016-05-20 14:02:39 -0700269 int32_t, hwc_region_t>);
Dan Stoza076ac672016-03-14 10:47:53 -0700270 case FunctionDescriptor::SetColorMode:
Michael Wright28f24d02016-07-12 13:30:53 -0700271 return asFP<HWC2_PFN_SET_COLOR_MODE>(setColorModeHook);
Dan Stoza5df2a862016-03-24 16:19:37 -0700272 case FunctionDescriptor::SetColorTransform:
273 return asFP<HWC2_PFN_SET_COLOR_TRANSFORM>(setColorTransformHook);
Dan Stozac6998d22015-09-24 17:03:36 -0700274 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);
Dan Stoza5df2a862016-03-24 16:19:37 -0700312 case FunctionDescriptor::SetLayerDataspace:
313 return asFP<HWC2_PFN_SET_LAYER_DATASPACE>(setLayerDataspaceHook);
Dan Stozac6998d22015-09-24 17:03:36 -0700314 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
349Error HWC2On1Adapter::createVirtualDisplay(uint32_t width,
350 uint32_t height, hwc2_display_t* outDisplay)
351{
Dan Stozafc4e2022016-02-23 11:43:19 -0800352 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -0700353
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
381Error HWC2On1Adapter::destroyVirtualDisplay(hwc2_display_t displayId)
382{
Dan Stozafc4e2022016-02-23 11:43:19 -0800383 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -0700384
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
396void 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
Dan Stozafc4e2022016-02-23 11:43:19 -0800413 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex,
414 std::defer_lock);
Dan Stozac6998d22015-09-24 17:03:36 -0700415 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
Dan Stozafc4e2022016-02-23 11:43:19 -0800433 // 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
Dan Stozac6998d22015-09-24 17:03:36 -0700437 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
450uint32_t HWC2On1Adapter::getMaxVirtualDisplayCount()
451{
452 return mHwc1SupportsVirtualDisplays ? 1 : 0;
453}
454
455static 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
464Error 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
Dan Stozafc4e2022016-02-23 11:43:19 -0800474 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -0700475
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
548std::atomic<hwc2_display_t> HWC2On1Adapter::Display::sNextId(1);
549
550HWC2On1Adapter::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 mName(),
564 mType(type),
565 mPowerMode(PowerMode::Off),
566 mVsyncEnabled(Vsync::Invalid),
567 mClientTarget(),
568 mOutputBuffer(),
Dan Stoza5df2a862016-03-24 16:19:37 -0700569 mHasColorTransform(false),
Dan Stozafc4e2022016-02-23 11:43:19 -0800570 mLayers(),
571 mHwc1LayerMap() {}
Dan Stozac6998d22015-09-24 17:03:36 -0700572
573Error HWC2On1Adapter::Display::acceptChanges()
574{
575 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
576
577 if (!mChanges) {
578 ALOGV("[%" PRIu64 "] acceptChanges failed, not validated", mId);
579 return Error::NotValidated;
580 }
581
582 ALOGV("[%" PRIu64 "] acceptChanges", mId);
583
584 for (auto& change : mChanges->getTypeChanges()) {
585 auto layerId = change.first;
586 auto type = change.second;
587 auto layer = mDevice.mLayers[layerId];
588 layer->setCompositionType(type);
589 }
590
591 mChanges->clearTypeChanges();
592
593 mHwc1RequestedContents = std::move(mHwc1ReceivedContents);
594
595 return Error::None;
596}
597
598Error HWC2On1Adapter::Display::createLayer(hwc2_layer_t* outLayerId)
599{
600 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
601
602 auto layer = *mLayers.emplace(std::make_shared<Layer>(*this));
603 mDevice.mLayers.emplace(std::make_pair(layer->getId(), layer));
604 *outLayerId = layer->getId();
605 ALOGV("[%" PRIu64 "] created layer %" PRIu64, mId, *outLayerId);
606 return Error::None;
607}
608
609Error HWC2On1Adapter::Display::destroyLayer(hwc2_layer_t layerId)
610{
611 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
612
613 const auto mapLayer = mDevice.mLayers.find(layerId);
614 if (mapLayer == mDevice.mLayers.end()) {
615 ALOGV("[%" PRIu64 "] destroyLayer(%" PRIu64 ") failed: no such layer",
616 mId, layerId);
617 return Error::BadLayer;
618 }
619 const auto layer = mapLayer->second;
620 mDevice.mLayers.erase(mapLayer);
621 const auto zRange = mLayers.equal_range(layer);
622 for (auto current = zRange.first; current != zRange.second; ++current) {
623 if (**current == *layer) {
624 current = mLayers.erase(current);
625 break;
626 }
627 }
628 ALOGV("[%" PRIu64 "] destroyed layer %" PRIu64, mId, layerId);
629 return Error::None;
630}
631
632Error HWC2On1Adapter::Display::getActiveConfig(hwc2_config_t* outConfig)
633{
634 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
635
636 if (!mActiveConfig) {
637 ALOGV("[%" PRIu64 "] getActiveConfig --> %s", mId,
638 to_string(Error::BadConfig).c_str());
639 return Error::BadConfig;
640 }
641 auto configId = mActiveConfig->getId();
642 ALOGV("[%" PRIu64 "] getActiveConfig --> %u", mId, configId);
643 *outConfig = configId;
644 return Error::None;
645}
646
647Error HWC2On1Adapter::Display::getAttribute(hwc2_config_t configId,
648 Attribute attribute, int32_t* outValue)
649{
650 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
651
652 if (configId > mConfigs.size() || !mConfigs[configId]->isOnDisplay(*this)) {
653 ALOGV("[%" PRIu64 "] getAttribute failed: bad config (%u)", mId,
654 configId);
655 return Error::BadConfig;
656 }
657 *outValue = mConfigs[configId]->getAttribute(attribute);
658 ALOGV("[%" PRIu64 "] getAttribute(%u, %s) --> %d", mId, configId,
659 to_string(attribute).c_str(), *outValue);
660 return Error::None;
661}
662
663Error HWC2On1Adapter::Display::getChangedCompositionTypes(
664 uint32_t* outNumElements, hwc2_layer_t* outLayers, int32_t* outTypes)
665{
666 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
667
668 if (!mChanges) {
669 ALOGE("[%" PRIu64 "] getChangedCompositionTypes failed: not validated",
670 mId);
671 return Error::NotValidated;
672 }
673
674 if ((outLayers == nullptr) || (outTypes == nullptr)) {
675 *outNumElements = mChanges->getTypeChanges().size();
676 return Error::None;
677 }
678
679 uint32_t numWritten = 0;
680 for (const auto& element : mChanges->getTypeChanges()) {
681 if (numWritten == *outNumElements) {
682 break;
683 }
684 auto layerId = element.first;
685 auto intType = static_cast<int32_t>(element.second);
686 ALOGV("Adding %" PRIu64 " %s", layerId,
687 to_string(element.second).c_str());
688 outLayers[numWritten] = layerId;
689 outTypes[numWritten] = intType;
690 ++numWritten;
691 }
692 *outNumElements = numWritten;
693
694 return Error::None;
695}
696
Dan Stoza076ac672016-03-14 10:47:53 -0700697Error HWC2On1Adapter::Display::getColorModes(uint32_t* outNumModes,
698 int32_t* outModes)
699{
700 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
701
702 if (!outModes) {
703 *outNumModes = mColorModes.size();
704 return Error::None;
705 }
706 uint32_t numModes = std::min(*outNumModes,
707 static_cast<uint32_t>(mColorModes.size()));
708 std::copy_n(mColorModes.cbegin(), numModes, outModes);
709 *outNumModes = numModes;
710 return Error::None;
711}
712
Dan Stozac6998d22015-09-24 17:03:36 -0700713Error HWC2On1Adapter::Display::getConfigs(uint32_t* outNumConfigs,
714 hwc2_config_t* outConfigs)
715{
716 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
717
718 if (!outConfigs) {
719 *outNumConfigs = mConfigs.size();
720 return Error::None;
721 }
722 uint32_t numWritten = 0;
723 for (const auto& config : mConfigs) {
724 if (numWritten == *outNumConfigs) {
725 break;
726 }
727 outConfigs[numWritten] = config->getId();
728 ++numWritten;
729 }
730 *outNumConfigs = numWritten;
731 return Error::None;
732}
733
734Error HWC2On1Adapter::Display::getDozeSupport(int32_t* outSupport)
735{
736 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
737
738 if (mDevice.mHwc1MinorVersion < 4 || mHwc1Id != 0) {
739 *outSupport = 0;
740 } else {
741 *outSupport = 1;
742 }
743 return Error::None;
744}
745
Dan Stozaed40eba2016-03-16 12:33:52 -0700746Error HWC2On1Adapter::Display::getHdrCapabilities(uint32_t* outNumTypes,
747 int32_t* /*outTypes*/, float* /*outMaxLuminance*/,
748 float* /*outMaxAverageLuminance*/, float* /*outMinLuminance*/)
749{
750 // This isn't supported on HWC1, so per the HWC2 header, return numTypes = 0
751 *outNumTypes = 0;
752 return Error::None;
753}
754
Dan Stozac6998d22015-09-24 17:03:36 -0700755Error HWC2On1Adapter::Display::getName(uint32_t* outSize, char* outName)
756{
757 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
758
759 if (!outName) {
760 *outSize = mName.size();
761 return Error::None;
762 }
763 auto numCopied = mName.copy(outName, *outSize);
764 *outSize = numCopied;
765 return Error::None;
766}
767
768Error HWC2On1Adapter::Display::getReleaseFences(uint32_t* outNumElements,
769 hwc2_layer_t* outLayers, int32_t* outFences)
770{
771 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
772
773 uint32_t numWritten = 0;
774 bool outputsNonNull = (outLayers != nullptr) && (outFences != nullptr);
775 for (const auto& layer : mLayers) {
776 if (outputsNonNull && (numWritten == *outNumElements)) {
777 break;
778 }
779
780 auto releaseFence = layer->getReleaseFence();
781 if (releaseFence != Fence::NO_FENCE) {
782 if (outputsNonNull) {
783 outLayers[numWritten] = layer->getId();
784 outFences[numWritten] = releaseFence->dup();
785 }
786 ++numWritten;
787 }
788 }
789 *outNumElements = numWritten;
790
791 return Error::None;
792}
793
794Error HWC2On1Adapter::Display::getRequests(int32_t* outDisplayRequests,
795 uint32_t* outNumElements, hwc2_layer_t* outLayers,
796 int32_t* outLayerRequests)
797{
798 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
799
800 if (!mChanges) {
801 return Error::NotValidated;
802 }
803
804 if (outLayers == nullptr || outLayerRequests == nullptr) {
805 *outNumElements = mChanges->getNumLayerRequests();
806 return Error::None;
807 }
808
809 *outDisplayRequests = mChanges->getDisplayRequests();
810 uint32_t numWritten = 0;
811 for (const auto& request : mChanges->getLayerRequests()) {
812 if (numWritten == *outNumElements) {
813 break;
814 }
815 outLayers[numWritten] = request.first;
816 outLayerRequests[numWritten] = static_cast<int32_t>(request.second);
817 ++numWritten;
818 }
819
820 return Error::None;
821}
822
823Error HWC2On1Adapter::Display::getType(int32_t* outType)
824{
825 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
826
827 *outType = static_cast<int32_t>(mType);
828 return Error::None;
829}
830
831Error HWC2On1Adapter::Display::present(int32_t* outRetireFence)
832{
833 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
834
835 if (mChanges) {
836 Error error = mDevice.setAllDisplays();
837 if (error != Error::None) {
838 ALOGE("[%" PRIu64 "] present: setAllDisplaysFailed (%s)", mId,
839 to_string(error).c_str());
840 return error;
841 }
842 }
843
844 *outRetireFence = mRetireFence.get()->dup();
845 ALOGV("[%" PRIu64 "] present returning retire fence %d", mId,
846 *outRetireFence);
847
848 return Error::None;
849}
850
851Error HWC2On1Adapter::Display::setActiveConfig(hwc2_config_t configId)
852{
853 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
854
855 auto config = getConfig(configId);
856 if (!config) {
857 return Error::BadConfig;
858 }
Dan Stoza076ac672016-03-14 10:47:53 -0700859 if (config == mActiveConfig) {
860 return Error::None;
Dan Stozac6998d22015-09-24 17:03:36 -0700861 }
Dan Stoza076ac672016-03-14 10:47:53 -0700862
863 if (mDevice.mHwc1MinorVersion >= 4) {
864 uint32_t hwc1Id = 0;
865 auto error = config->getHwc1IdForColorMode(mActiveColorMode, &hwc1Id);
866 if (error != Error::None) {
867 return error;
868 }
869
870 int intError = mDevice.mHwc1Device->setActiveConfig(mDevice.mHwc1Device,
871 mHwc1Id, static_cast<int>(hwc1Id));
872 if (intError != 0) {
873 ALOGE("setActiveConfig: Failed to set active config on HWC1 (%d)",
874 intError);
875 return Error::BadConfig;
876 }
877 mActiveConfig = config;
878 }
879
Dan Stozac6998d22015-09-24 17:03:36 -0700880 return Error::None;
881}
882
883Error HWC2On1Adapter::Display::setClientTarget(buffer_handle_t target,
Dan Stoza5cf424b2016-05-20 14:02:39 -0700884 int32_t acquireFence, int32_t /*dataspace*/, hwc_region_t /*damage*/)
Dan Stozac6998d22015-09-24 17:03:36 -0700885{
886 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
887
888 ALOGV("[%" PRIu64 "] setClientTarget(%p, %d)", mId, target, acquireFence);
889 mClientTarget.setBuffer(target);
890 mClientTarget.setFence(acquireFence);
Dan Stoza5cf424b2016-05-20 14:02:39 -0700891 // dataspace and damage can't be used by HWC1, so ignore them
Dan Stozac6998d22015-09-24 17:03:36 -0700892 return Error::None;
893}
894
Michael Wright28f24d02016-07-12 13:30:53 -0700895Error HWC2On1Adapter::Display::setColorMode(android_color_mode_t mode)
Dan Stoza076ac672016-03-14 10:47:53 -0700896{
897 std::unique_lock<std::recursive_mutex> lock (mStateMutex);
898
899 ALOGV("[%" PRIu64 "] setColorMode(%d)", mId, mode);
900
901 if (mode == mActiveColorMode) {
902 return Error::None;
903 }
904 if (mColorModes.count(mode) == 0) {
905 ALOGE("[%" PRIu64 "] Mode %d not found in mColorModes", mId, mode);
906 return Error::Unsupported;
907 }
908
909 uint32_t hwc1Config = 0;
910 auto error = mActiveConfig->getHwc1IdForColorMode(mode, &hwc1Config);
911 if (error != Error::None) {
912 return error;
913 }
914
915 ALOGV("[%" PRIu64 "] Setting HWC1 config %u", mId, hwc1Config);
916 int intError = mDevice.mHwc1Device->setActiveConfig(mDevice.mHwc1Device,
917 mHwc1Id, hwc1Config);
918 if (intError != 0) {
919 ALOGE("[%" PRIu64 "] Failed to set HWC1 config (%d)", mId, intError);
920 return Error::Unsupported;
921 }
922
923 mActiveColorMode = mode;
924 return Error::None;
925}
926
Dan Stoza5df2a862016-03-24 16:19:37 -0700927Error HWC2On1Adapter::Display::setColorTransform(android_color_transform_t hint)
928{
929 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
930
931 ALOGV("%" PRIu64 "] setColorTransform(%d)", mId,
932 static_cast<int32_t>(hint));
933 mHasColorTransform = (hint != HAL_COLOR_TRANSFORM_IDENTITY);
934 return Error::None;
935}
936
Dan Stozac6998d22015-09-24 17:03:36 -0700937Error HWC2On1Adapter::Display::setOutputBuffer(buffer_handle_t buffer,
938 int32_t releaseFence)
939{
940 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
941
942 ALOGV("[%" PRIu64 "] setOutputBuffer(%p, %d)", mId, buffer, releaseFence);
943 mOutputBuffer.setBuffer(buffer);
944 mOutputBuffer.setFence(releaseFence);
945 return Error::None;
946}
947
948static bool isValid(PowerMode mode)
949{
950 switch (mode) {
951 case PowerMode::Off: // Fall-through
952 case PowerMode::DozeSuspend: // Fall-through
953 case PowerMode::Doze: // Fall-through
954 case PowerMode::On: return true;
955 default: return false;
956 }
957}
958
959static int getHwc1PowerMode(PowerMode mode)
960{
961 switch (mode) {
962 case PowerMode::Off: return HWC_POWER_MODE_OFF;
963 case PowerMode::DozeSuspend: return HWC_POWER_MODE_DOZE_SUSPEND;
964 case PowerMode::Doze: return HWC_POWER_MODE_DOZE;
965 case PowerMode::On: return HWC_POWER_MODE_NORMAL;
966 default: return HWC_POWER_MODE_OFF;
967 }
968}
969
970Error HWC2On1Adapter::Display::setPowerMode(PowerMode mode)
971{
972 if (!isValid(mode)) {
973 return Error::BadParameter;
974 }
975 if (mode == mPowerMode) {
976 return Error::None;
977 }
978
979 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
980
981 int error = 0;
982 if (mDevice.mHwc1MinorVersion < 4) {
983 error = mDevice.mHwc1Device->blank(mDevice.mHwc1Device, mHwc1Id,
984 mode == PowerMode::Off);
985 } else {
986 error = mDevice.mHwc1Device->setPowerMode(mDevice.mHwc1Device,
987 mHwc1Id, getHwc1PowerMode(mode));
988 }
989 ALOGE_IF(error != 0, "setPowerMode: Failed to set power mode on HWC1 (%d)",
990 error);
991
992 ALOGV("[%" PRIu64 "] setPowerMode(%s)", mId, to_string(mode).c_str());
993 mPowerMode = mode;
994 return Error::None;
995}
996
997static bool isValid(Vsync enable) {
998 switch (enable) {
999 case Vsync::Enable: // Fall-through
1000 case Vsync::Disable: return true;
1001 default: return false;
1002 }
1003}
1004
1005Error HWC2On1Adapter::Display::setVsyncEnabled(Vsync enable)
1006{
1007 if (!isValid(enable)) {
1008 return Error::BadParameter;
1009 }
1010 if (enable == mVsyncEnabled) {
1011 return Error::None;
1012 }
1013
1014 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1015
1016 int error = mDevice.mHwc1Device->eventControl(mDevice.mHwc1Device,
1017 mHwc1Id, HWC_EVENT_VSYNC, enable == Vsync::Enable);
1018 ALOGE_IF(error != 0, "setVsyncEnabled: Failed to set vsync on HWC1 (%d)",
1019 error);
1020
1021 mVsyncEnabled = enable;
1022 return Error::None;
1023}
1024
1025Error HWC2On1Adapter::Display::validate(uint32_t* outNumTypes,
1026 uint32_t* outNumRequests)
1027{
1028 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1029
1030 ALOGV("[%" PRIu64 "] Entering validate", mId);
1031
1032 if (!mChanges) {
1033 if (!mDevice.prepareAllDisplays()) {
1034 return Error::BadDisplay;
1035 }
1036 }
1037
1038 *outNumTypes = mChanges->getNumTypes();
1039 *outNumRequests = mChanges->getNumLayerRequests();
1040 ALOGV("[%" PRIu64 "] validate --> %u types, %u requests", mId, *outNumTypes,
1041 *outNumRequests);
1042 for (auto request : mChanges->getTypeChanges()) {
1043 ALOGV("Layer %" PRIu64 " --> %s", request.first,
1044 to_string(request.second).c_str());
1045 }
1046 return *outNumTypes > 0 ? Error::HasChanges : Error::None;
1047}
1048
1049// Display helpers
1050
1051Error HWC2On1Adapter::Display::updateLayerZ(hwc2_layer_t layerId, uint32_t z)
1052{
1053 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1054
1055 const auto mapLayer = mDevice.mLayers.find(layerId);
1056 if (mapLayer == mDevice.mLayers.end()) {
1057 ALOGE("[%" PRIu64 "] updateLayerZ failed to find layer", mId);
1058 return Error::BadLayer;
1059 }
1060
1061 const auto layer = mapLayer->second;
1062 const auto zRange = mLayers.equal_range(layer);
1063 bool layerOnDisplay = false;
1064 for (auto current = zRange.first; current != zRange.second; ++current) {
1065 if (**current == *layer) {
1066 if ((*current)->getZ() == z) {
1067 // Don't change anything if the Z hasn't changed
1068 return Error::None;
1069 }
1070 current = mLayers.erase(current);
1071 layerOnDisplay = true;
1072 break;
1073 }
1074 }
1075
1076 if (!layerOnDisplay) {
1077 ALOGE("[%" PRIu64 "] updateLayerZ failed to find layer on display",
1078 mId);
1079 return Error::BadLayer;
1080 }
1081
1082 layer->setZ(z);
1083 mLayers.emplace(std::move(layer));
1084 mZIsDirty = true;
1085
1086 return Error::None;
1087}
1088
Dan Stoza076ac672016-03-14 10:47:53 -07001089static constexpr uint32_t ATTRIBUTES_WITH_COLOR[] = {
1090 HWC_DISPLAY_VSYNC_PERIOD,
1091 HWC_DISPLAY_WIDTH,
1092 HWC_DISPLAY_HEIGHT,
1093 HWC_DISPLAY_DPI_X,
1094 HWC_DISPLAY_DPI_Y,
1095 HWC_DISPLAY_COLOR_TRANSFORM,
1096 HWC_DISPLAY_NO_ATTRIBUTE,
1097};
1098
1099static constexpr uint32_t ATTRIBUTES_WITHOUT_COLOR[] = {
Dan Stozac6998d22015-09-24 17:03:36 -07001100 HWC_DISPLAY_VSYNC_PERIOD,
1101 HWC_DISPLAY_WIDTH,
1102 HWC_DISPLAY_HEIGHT,
1103 HWC_DISPLAY_DPI_X,
1104 HWC_DISPLAY_DPI_Y,
1105 HWC_DISPLAY_NO_ATTRIBUTE,
1106};
Dan Stozac6998d22015-09-24 17:03:36 -07001107
Dan Stoza076ac672016-03-14 10:47:53 -07001108static constexpr size_t NUM_ATTRIBUTES_WITH_COLOR =
1109 sizeof(ATTRIBUTES_WITH_COLOR) / sizeof(uint32_t);
1110static_assert(sizeof(ATTRIBUTES_WITH_COLOR) > sizeof(ATTRIBUTES_WITHOUT_COLOR),
1111 "Attribute tables have unexpected sizes");
1112
1113static constexpr uint32_t ATTRIBUTE_MAP_WITH_COLOR[] = {
1114 6, // HWC_DISPLAY_NO_ATTRIBUTE = 0
1115 0, // HWC_DISPLAY_VSYNC_PERIOD = 1,
1116 1, // HWC_DISPLAY_WIDTH = 2,
1117 2, // HWC_DISPLAY_HEIGHT = 3,
1118 3, // HWC_DISPLAY_DPI_X = 4,
1119 4, // HWC_DISPLAY_DPI_Y = 5,
1120 5, // HWC_DISPLAY_COLOR_TRANSFORM = 6,
1121};
1122
1123static constexpr uint32_t ATTRIBUTE_MAP_WITHOUT_COLOR[] = {
Dan Stozac6998d22015-09-24 17:03:36 -07001124 5, // HWC_DISPLAY_NO_ATTRIBUTE = 0
1125 0, // HWC_DISPLAY_VSYNC_PERIOD = 1,
1126 1, // HWC_DISPLAY_WIDTH = 2,
1127 2, // HWC_DISPLAY_HEIGHT = 3,
1128 3, // HWC_DISPLAY_DPI_X = 4,
1129 4, // HWC_DISPLAY_DPI_Y = 5,
1130};
1131
1132template <uint32_t attribute>
1133static constexpr bool attributesMatch()
1134{
Dan Stoza076ac672016-03-14 10:47:53 -07001135 bool match = (attribute ==
1136 ATTRIBUTES_WITH_COLOR[ATTRIBUTE_MAP_WITH_COLOR[attribute]]);
1137 if (attribute == HWC_DISPLAY_COLOR_TRANSFORM) {
1138 return match;
1139 }
1140
1141 return match && (attribute ==
1142 ATTRIBUTES_WITHOUT_COLOR[ATTRIBUTE_MAP_WITHOUT_COLOR[attribute]]);
Dan Stozac6998d22015-09-24 17:03:36 -07001143}
1144static_assert(attributesMatch<HWC_DISPLAY_VSYNC_PERIOD>(),
1145 "Tables out of sync");
1146static_assert(attributesMatch<HWC_DISPLAY_WIDTH>(), "Tables out of sync");
1147static_assert(attributesMatch<HWC_DISPLAY_HEIGHT>(), "Tables out of sync");
1148static_assert(attributesMatch<HWC_DISPLAY_DPI_X>(), "Tables out of sync");
1149static_assert(attributesMatch<HWC_DISPLAY_DPI_Y>(), "Tables out of sync");
Dan Stoza076ac672016-03-14 10:47:53 -07001150static_assert(attributesMatch<HWC_DISPLAY_COLOR_TRANSFORM>(),
1151 "Tables out of sync");
Dan Stozac6998d22015-09-24 17:03:36 -07001152
1153void HWC2On1Adapter::Display::populateConfigs()
1154{
1155 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1156
1157 ALOGV("[%" PRIu64 "] populateConfigs", mId);
1158
1159 if (mHwc1Id == -1) {
1160 ALOGE("populateConfigs: HWC1 ID not set");
1161 return;
1162 }
1163
1164 const size_t MAX_NUM_CONFIGS = 128;
1165 uint32_t configs[MAX_NUM_CONFIGS] = {};
1166 size_t numConfigs = MAX_NUM_CONFIGS;
1167 mDevice.mHwc1Device->getDisplayConfigs(mDevice.mHwc1Device, mHwc1Id,
1168 configs, &numConfigs);
1169
1170 for (size_t c = 0; c < numConfigs; ++c) {
1171 uint32_t hwc1ConfigId = configs[c];
Dan Stoza076ac672016-03-14 10:47:53 -07001172 auto newConfig = std::make_shared<Config>(*this);
Dan Stozac6998d22015-09-24 17:03:36 -07001173
Dan Stoza076ac672016-03-14 10:47:53 -07001174 int32_t values[NUM_ATTRIBUTES_WITH_COLOR] = {};
1175 bool hasColor = true;
1176 auto result = mDevice.mHwc1Device->getDisplayAttributes(
1177 mDevice.mHwc1Device, mHwc1Id, hwc1ConfigId,
1178 ATTRIBUTES_WITH_COLOR, values);
1179 if (result != 0) {
1180 mDevice.mHwc1Device->getDisplayAttributes(mDevice.mHwc1Device,
1181 mHwc1Id, hwc1ConfigId, ATTRIBUTES_WITHOUT_COLOR, values);
1182 hasColor = false;
Dan Stozac6998d22015-09-24 17:03:36 -07001183 }
Dan Stoza076ac672016-03-14 10:47:53 -07001184
1185 auto attributeMap = hasColor ?
1186 ATTRIBUTE_MAP_WITH_COLOR : ATTRIBUTE_MAP_WITHOUT_COLOR;
1187
1188 newConfig->setAttribute(Attribute::VsyncPeriod,
1189 values[attributeMap[HWC_DISPLAY_VSYNC_PERIOD]]);
1190 newConfig->setAttribute(Attribute::Width,
1191 values[attributeMap[HWC_DISPLAY_WIDTH]]);
1192 newConfig->setAttribute(Attribute::Height,
1193 values[attributeMap[HWC_DISPLAY_HEIGHT]]);
1194 newConfig->setAttribute(Attribute::DpiX,
1195 values[attributeMap[HWC_DISPLAY_DPI_X]]);
1196 newConfig->setAttribute(Attribute::DpiY,
1197 values[attributeMap[HWC_DISPLAY_DPI_Y]]);
1198 if (hasColor) {
Michael Wright28f24d02016-07-12 13:30:53 -07001199 // In HWC1, color modes are referred to as color transforms. To avoid confusion with
1200 // the HWC2 concept of color transforms, we internally refer to them as color modes for
1201 // both HWC1 and 2.
1202 newConfig->setAttribute(ColorMode,
Dan Stoza076ac672016-03-14 10:47:53 -07001203 values[attributeMap[HWC_DISPLAY_COLOR_TRANSFORM]]);
1204 }
1205
Michael Wright28f24d02016-07-12 13:30:53 -07001206 // We can only do this after attempting to read the color mode
Dan Stoza076ac672016-03-14 10:47:53 -07001207 newConfig->setHwc1Id(hwc1ConfigId);
1208
1209 for (auto& existingConfig : mConfigs) {
1210 if (existingConfig->merge(*newConfig)) {
1211 ALOGV("Merged config %d with existing config %u: %s",
1212 hwc1ConfigId, existingConfig->getId(),
1213 existingConfig->toString().c_str());
1214 newConfig.reset();
1215 break;
1216 }
1217 }
1218
1219 // If it wasn't merged with any existing config, add it to the end
1220 if (newConfig) {
1221 newConfig->setId(static_cast<hwc2_config_t>(mConfigs.size()));
1222 ALOGV("Found new config %u: %s", newConfig->getId(),
1223 newConfig->toString().c_str());
1224 mConfigs.emplace_back(std::move(newConfig));
1225 }
Dan Stozac6998d22015-09-24 17:03:36 -07001226 }
Dan Stoza076ac672016-03-14 10:47:53 -07001227
1228 initializeActiveConfig();
1229 populateColorModes();
Dan Stozac6998d22015-09-24 17:03:36 -07001230}
1231
1232void HWC2On1Adapter::Display::populateConfigs(uint32_t width, uint32_t height)
1233{
1234 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1235
Dan Stoza076ac672016-03-14 10:47:53 -07001236 mConfigs.emplace_back(std::make_shared<Config>(*this));
Dan Stozac6998d22015-09-24 17:03:36 -07001237 auto& config = mConfigs[0];
1238
1239 config->setAttribute(Attribute::Width, static_cast<int32_t>(width));
1240 config->setAttribute(Attribute::Height, static_cast<int32_t>(height));
Dan Stoza076ac672016-03-14 10:47:53 -07001241 config->setHwc1Id(0);
1242 config->setId(0);
Dan Stozac6998d22015-09-24 17:03:36 -07001243 mActiveConfig = config;
1244}
1245
1246bool HWC2On1Adapter::Display::prepare()
1247{
1248 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1249
1250 // Only prepare display contents for displays HWC1 knows about
1251 if (mHwc1Id == -1) {
1252 return true;
1253 }
1254
1255 // It doesn't make sense to prepare a display for which there is no active
1256 // config, so return early
1257 if (!mActiveConfig) {
1258 ALOGE("[%" PRIu64 "] Attempted to prepare, but no config active", mId);
1259 return false;
1260 }
1261
1262 ALOGV("[%" PRIu64 "] Entering prepare", mId);
1263
1264 auto currentCount = mHwc1RequestedContents ?
1265 mHwc1RequestedContents->numHwLayers : 0;
1266 auto requiredCount = mLayers.size() + 1;
1267 ALOGV("[%" PRIu64 "] Requires %zd layers, %zd allocated in %p", mId,
1268 requiredCount, currentCount, mHwc1RequestedContents.get());
1269
1270 bool layerCountChanged = (currentCount != requiredCount);
1271 if (layerCountChanged) {
1272 reallocateHwc1Contents();
1273 }
1274
1275 bool applyAllState = false;
1276 if (layerCountChanged || mZIsDirty) {
1277 assignHwc1LayerIds();
1278 mZIsDirty = false;
1279 applyAllState = true;
1280 }
1281
1282 mHwc1RequestedContents->retireFenceFd = -1;
1283 mHwc1RequestedContents->flags = 0;
1284 if (isDirty() || applyAllState) {
1285 mHwc1RequestedContents->flags |= HWC_GEOMETRY_CHANGED;
1286 }
1287
1288 for (auto& layer : mLayers) {
1289 auto& hwc1Layer = mHwc1RequestedContents->hwLayers[layer->getHwc1Id()];
1290 hwc1Layer.releaseFenceFd = -1;
1291 layer->applyState(hwc1Layer, applyAllState);
1292 }
1293
1294 mHwc1RequestedContents->outbuf = mOutputBuffer.getBuffer();
1295 mHwc1RequestedContents->outbufAcquireFenceFd = mOutputBuffer.getFence();
1296
1297 prepareFramebufferTarget();
1298
1299 return true;
1300}
1301
1302static void cloneHWCRegion(hwc_region_t& region)
1303{
1304 auto size = sizeof(hwc_rect_t) * region.numRects;
1305 auto newRects = static_cast<hwc_rect_t*>(std::malloc(size));
1306 std::copy_n(region.rects, region.numRects, newRects);
1307 region.rects = newRects;
1308}
1309
1310HWC2On1Adapter::Display::HWC1Contents
1311 HWC2On1Adapter::Display::cloneRequestedContents() const
1312{
1313 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1314
1315 size_t size = sizeof(hwc_display_contents_1_t) +
1316 sizeof(hwc_layer_1_t) * (mHwc1RequestedContents->numHwLayers);
1317 auto contents = static_cast<hwc_display_contents_1_t*>(std::malloc(size));
1318 std::memcpy(contents, mHwc1RequestedContents.get(), size);
1319 for (size_t layerId = 0; layerId < contents->numHwLayers; ++layerId) {
1320 auto& layer = contents->hwLayers[layerId];
1321 // Deep copy the regions to avoid double-frees
1322 cloneHWCRegion(layer.visibleRegionScreen);
1323 cloneHWCRegion(layer.surfaceDamage);
1324 }
1325 return HWC1Contents(contents);
1326}
1327
1328void HWC2On1Adapter::Display::setReceivedContents(HWC1Contents contents)
1329{
1330 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1331
1332 mHwc1ReceivedContents = std::move(contents);
1333
1334 mChanges.reset(new Changes);
1335
1336 size_t numLayers = mHwc1ReceivedContents->numHwLayers;
1337 for (size_t hwc1Id = 0; hwc1Id < numLayers; ++hwc1Id) {
1338 const auto& receivedLayer = mHwc1ReceivedContents->hwLayers[hwc1Id];
1339 if (mHwc1LayerMap.count(hwc1Id) == 0) {
1340 ALOGE_IF(receivedLayer.compositionType != HWC_FRAMEBUFFER_TARGET,
1341 "setReceivedContents: HWC1 layer %zd doesn't have a"
1342 " matching HWC2 layer, and isn't the framebuffer target",
1343 hwc1Id);
1344 continue;
1345 }
1346
1347 Layer& layer = *mHwc1LayerMap[hwc1Id];
1348 updateTypeChanges(receivedLayer, layer);
1349 updateLayerRequests(receivedLayer, layer);
1350 }
1351}
1352
1353bool HWC2On1Adapter::Display::hasChanges() const
1354{
1355 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1356 return mChanges != nullptr;
1357}
1358
1359Error HWC2On1Adapter::Display::set(hwc_display_contents_1& hwcContents)
1360{
1361 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1362
1363 if (!mChanges || (mChanges->getNumTypes() > 0)) {
1364 ALOGE("[%" PRIu64 "] set failed: not validated", mId);
1365 return Error::NotValidated;
1366 }
1367
1368 // Set up the client/framebuffer target
1369 auto numLayers = hwcContents.numHwLayers;
1370
1371 // Close acquire fences on FRAMEBUFFER layers, since they will not be used
1372 // by HWC
1373 for (size_t l = 0; l < numLayers - 1; ++l) {
1374 auto& layer = hwcContents.hwLayers[l];
1375 if (layer.compositionType == HWC_FRAMEBUFFER) {
1376 ALOGV("Closing fence %d for layer %zd", layer.acquireFenceFd, l);
1377 close(layer.acquireFenceFd);
1378 layer.acquireFenceFd = -1;
1379 }
1380 }
1381
1382 auto& clientTargetLayer = hwcContents.hwLayers[numLayers - 1];
1383 if (clientTargetLayer.compositionType == HWC_FRAMEBUFFER_TARGET) {
1384 clientTargetLayer.handle = mClientTarget.getBuffer();
1385 clientTargetLayer.acquireFenceFd = mClientTarget.getFence();
1386 } else {
1387 ALOGE("[%" PRIu64 "] set: last HWC layer wasn't FRAMEBUFFER_TARGET",
1388 mId);
1389 }
1390
1391 mChanges.reset();
1392
1393 return Error::None;
1394}
1395
1396void HWC2On1Adapter::Display::addRetireFence(int fenceFd)
1397{
1398 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1399 mRetireFence.add(fenceFd);
1400}
1401
1402void HWC2On1Adapter::Display::addReleaseFences(
1403 const hwc_display_contents_1_t& hwcContents)
1404{
1405 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1406
1407 size_t numLayers = hwcContents.numHwLayers;
1408 for (size_t hwc1Id = 0; hwc1Id < numLayers; ++hwc1Id) {
1409 const auto& receivedLayer = hwcContents.hwLayers[hwc1Id];
1410 if (mHwc1LayerMap.count(hwc1Id) == 0) {
1411 if (receivedLayer.compositionType != HWC_FRAMEBUFFER_TARGET) {
1412 ALOGE("addReleaseFences: HWC1 layer %zd doesn't have a"
1413 " matching HWC2 layer, and isn't the framebuffer"
1414 " target", hwc1Id);
1415 }
1416 // Close the framebuffer target release fence since we will use the
1417 // display retire fence instead
1418 if (receivedLayer.releaseFenceFd != -1) {
1419 close(receivedLayer.releaseFenceFd);
1420 }
1421 continue;
1422 }
1423
1424 Layer& layer = *mHwc1LayerMap[hwc1Id];
1425 ALOGV("Adding release fence %d to layer %" PRIu64,
1426 receivedLayer.releaseFenceFd, layer.getId());
1427 layer.addReleaseFence(receivedLayer.releaseFenceFd);
1428 }
1429}
1430
Dan Stoza5df2a862016-03-24 16:19:37 -07001431bool HWC2On1Adapter::Display::hasColorTransform() const
1432{
1433 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1434 return mHasColorTransform;
1435}
1436
Dan Stozac6998d22015-09-24 17:03:36 -07001437static std::string hwc1CompositionString(int32_t type)
1438{
1439 switch (type) {
1440 case HWC_FRAMEBUFFER: return "Framebuffer";
1441 case HWC_OVERLAY: return "Overlay";
1442 case HWC_BACKGROUND: return "Background";
1443 case HWC_FRAMEBUFFER_TARGET: return "FramebufferTarget";
1444 case HWC_SIDEBAND: return "Sideband";
1445 case HWC_CURSOR_OVERLAY: return "CursorOverlay";
1446 default:
1447 return std::string("Unknown (") + std::to_string(type) + ")";
1448 }
1449}
1450
1451static std::string hwc1TransformString(int32_t transform)
1452{
1453 switch (transform) {
1454 case 0: return "None";
1455 case HWC_TRANSFORM_FLIP_H: return "FlipH";
1456 case HWC_TRANSFORM_FLIP_V: return "FlipV";
1457 case HWC_TRANSFORM_ROT_90: return "Rotate90";
1458 case HWC_TRANSFORM_ROT_180: return "Rotate180";
1459 case HWC_TRANSFORM_ROT_270: return "Rotate270";
1460 case HWC_TRANSFORM_FLIP_H_ROT_90: return "FlipHRotate90";
1461 case HWC_TRANSFORM_FLIP_V_ROT_90: return "FlipVRotate90";
1462 default:
1463 return std::string("Unknown (") + std::to_string(transform) + ")";
1464 }
1465}
1466
1467static std::string hwc1BlendModeString(int32_t mode)
1468{
1469 switch (mode) {
1470 case HWC_BLENDING_NONE: return "None";
1471 case HWC_BLENDING_PREMULT: return "Premultiplied";
1472 case HWC_BLENDING_COVERAGE: return "Coverage";
1473 default:
1474 return std::string("Unknown (") + std::to_string(mode) + ")";
1475 }
1476}
1477
1478static std::string rectString(hwc_rect_t rect)
1479{
1480 std::stringstream output;
1481 output << "[" << rect.left << ", " << rect.top << ", ";
1482 output << rect.right << ", " << rect.bottom << "]";
1483 return output.str();
1484}
1485
1486static std::string approximateFloatString(float f)
1487{
1488 if (static_cast<int32_t>(f) == f) {
1489 return std::to_string(static_cast<int32_t>(f));
1490 }
1491 int32_t truncated = static_cast<int32_t>(f * 10);
1492 bool approximate = (static_cast<float>(truncated) != f * 10);
1493 const size_t BUFFER_SIZE = 32;
1494 char buffer[BUFFER_SIZE] = {};
1495 auto bytesWritten = snprintf(buffer, BUFFER_SIZE,
1496 "%s%.1f", approximate ? "~" : "", f);
1497 return std::string(buffer, bytesWritten);
1498}
1499
1500static std::string frectString(hwc_frect_t frect)
1501{
1502 std::stringstream output;
1503 output << "[" << approximateFloatString(frect.left) << ", ";
1504 output << approximateFloatString(frect.top) << ", ";
1505 output << approximateFloatString(frect.right) << ", ";
1506 output << approximateFloatString(frect.bottom) << "]";
1507 return output.str();
1508}
1509
1510static std::string colorString(hwc_color_t color)
1511{
1512 std::stringstream output;
1513 output << "RGBA [";
1514 output << static_cast<int32_t>(color.r) << ", ";
1515 output << static_cast<int32_t>(color.g) << ", ";
1516 output << static_cast<int32_t>(color.b) << ", ";
1517 output << static_cast<int32_t>(color.a) << "]";
1518 return output.str();
1519}
1520
1521static std::string alphaString(float f)
1522{
1523 const size_t BUFFER_SIZE = 8;
1524 char buffer[BUFFER_SIZE] = {};
1525 auto bytesWritten = snprintf(buffer, BUFFER_SIZE, "%.3f", f);
1526 return std::string(buffer, bytesWritten);
1527}
1528
1529static std::string to_string(const hwc_layer_1_t& hwcLayer,
1530 int32_t hwc1MinorVersion)
1531{
1532 const char* fill = " ";
1533
1534 std::stringstream output;
1535
1536 output << " Composition: " <<
1537 hwc1CompositionString(hwcLayer.compositionType);
1538
1539 if (hwcLayer.compositionType == HWC_BACKGROUND) {
1540 output << " Color: " << colorString(hwcLayer.backgroundColor) << '\n';
1541 } else if (hwcLayer.compositionType == HWC_SIDEBAND) {
1542 output << " Stream: " << hwcLayer.sidebandStream << '\n';
1543 } else {
1544 output << " Buffer: " << hwcLayer.handle << "/" <<
1545 hwcLayer.acquireFenceFd << '\n';
1546 }
1547
1548 output << fill << "Display frame: " << rectString(hwcLayer.displayFrame) <<
1549 '\n';
1550
1551 output << fill << "Source crop: ";
1552 if (hwc1MinorVersion >= 3) {
1553 output << frectString(hwcLayer.sourceCropf) << '\n';
1554 } else {
1555 output << rectString(hwcLayer.sourceCropi) << '\n';
1556 }
1557
1558 output << fill << "Transform: " << hwc1TransformString(hwcLayer.transform);
1559 output << " Blend mode: " << hwc1BlendModeString(hwcLayer.blending);
1560 if (hwcLayer.planeAlpha != 0xFF) {
1561 output << " Alpha: " << alphaString(hwcLayer.planeAlpha / 255.0f);
1562 }
1563 output << '\n';
1564
1565 if (hwcLayer.hints != 0) {
1566 output << fill << "Hints:";
1567 if ((hwcLayer.hints & HWC_HINT_TRIPLE_BUFFER) != 0) {
1568 output << " TripleBuffer";
1569 }
1570 if ((hwcLayer.hints & HWC_HINT_CLEAR_FB) != 0) {
1571 output << " ClearFB";
1572 }
1573 output << '\n';
1574 }
1575
1576 if (hwcLayer.flags != 0) {
1577 output << fill << "Flags:";
1578 if ((hwcLayer.flags & HWC_SKIP_LAYER) != 0) {
1579 output << " SkipLayer";
1580 }
1581 if ((hwcLayer.flags & HWC_IS_CURSOR_LAYER) != 0) {
1582 output << " IsCursorLayer";
1583 }
1584 output << '\n';
1585 }
1586
1587 return output.str();
1588}
1589
1590static std::string to_string(const hwc_display_contents_1_t& hwcContents,
1591 int32_t hwc1MinorVersion)
1592{
1593 const char* fill = " ";
1594
1595 std::stringstream output;
1596 output << fill << "Geometry changed: " <<
1597 ((hwcContents.flags & HWC_GEOMETRY_CHANGED) != 0 ? "Y\n" : "N\n");
1598
1599 output << fill << hwcContents.numHwLayers << " Layer" <<
1600 ((hwcContents.numHwLayers == 1) ? "\n" : "s\n");
1601 for (size_t layer = 0; layer < hwcContents.numHwLayers; ++layer) {
1602 output << fill << " Layer " << layer;
1603 output << to_string(hwcContents.hwLayers[layer], hwc1MinorVersion);
1604 }
1605
1606 if (hwcContents.outbuf != nullptr) {
1607 output << fill << "Output buffer: " << hwcContents.outbuf << "/" <<
1608 hwcContents.outbufAcquireFenceFd << '\n';
1609 }
1610
1611 return output.str();
1612}
1613
1614std::string HWC2On1Adapter::Display::dump() const
1615{
1616 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1617
1618 std::stringstream output;
1619
1620 output << " Display " << mId << ": ";
1621 output << to_string(mType) << " ";
1622 output << "HWC1 ID: " << mHwc1Id << " ";
1623 output << "Power mode: " << to_string(mPowerMode) << " ";
1624 output << "Vsync: " << to_string(mVsyncEnabled) << '\n';
1625
Dan Stoza076ac672016-03-14 10:47:53 -07001626 output << " Color modes [active]:";
1627 for (const auto& mode : mColorModes) {
1628 if (mode == mActiveColorMode) {
1629 output << " [" << mode << ']';
Dan Stozac6998d22015-09-24 17:03:36 -07001630 } else {
Dan Stoza076ac672016-03-14 10:47:53 -07001631 output << " " << mode;
Dan Stozac6998d22015-09-24 17:03:36 -07001632 }
1633 }
1634 output << '\n';
1635
Dan Stoza076ac672016-03-14 10:47:53 -07001636 output << " " << mConfigs.size() << " Config" <<
1637 (mConfigs.size() == 1 ? "" : "s") << " (* active)\n";
1638 for (const auto& config : mConfigs) {
1639 output << (config == mActiveConfig ? " * " : " ");
1640 output << config->toString(true) << '\n';
1641 }
1642
Dan Stozac6998d22015-09-24 17:03:36 -07001643 output << " " << mLayers.size() << " Layer" <<
1644 (mLayers.size() == 1 ? "" : "s") << '\n';
1645 for (const auto& layer : mLayers) {
1646 output << layer->dump();
1647 }
1648
1649 output << " Client target: " << mClientTarget.getBuffer() << '\n';
1650
1651 if (mOutputBuffer.getBuffer() != nullptr) {
1652 output << " Output buffer: " << mOutputBuffer.getBuffer() << '\n';
1653 }
1654
1655 if (mHwc1ReceivedContents) {
1656 output << " Last received HWC1 state\n";
1657 output << to_string(*mHwc1ReceivedContents, mDevice.mHwc1MinorVersion);
1658 } else if (mHwc1RequestedContents) {
1659 output << " Last requested HWC1 state\n";
1660 output << to_string(*mHwc1RequestedContents, mDevice.mHwc1MinorVersion);
1661 }
1662
1663 return output.str();
1664}
1665
1666void HWC2On1Adapter::Display::Config::setAttribute(HWC2::Attribute attribute,
1667 int32_t value)
1668{
1669 mAttributes[attribute] = value;
1670}
1671
1672int32_t HWC2On1Adapter::Display::Config::getAttribute(Attribute attribute) const
1673{
1674 if (mAttributes.count(attribute) == 0) {
1675 return -1;
1676 }
1677 return mAttributes.at(attribute);
1678}
1679
Dan Stoza076ac672016-03-14 10:47:53 -07001680void HWC2On1Adapter::Display::Config::setHwc1Id(uint32_t id)
1681{
Michael Wright28f24d02016-07-12 13:30:53 -07001682 android_color_mode_t colorMode = static_cast<android_color_mode_t>(getAttribute(ColorMode));
1683 mHwc1Ids.emplace(colorMode, id);
Dan Stoza076ac672016-03-14 10:47:53 -07001684}
1685
1686bool HWC2On1Adapter::Display::Config::hasHwc1Id(uint32_t id) const
1687{
1688 for (const auto& idPair : mHwc1Ids) {
1689 if (id == idPair.second) {
1690 return true;
1691 }
1692 }
1693 return false;
1694}
1695
Michael Wright28f24d02016-07-12 13:30:53 -07001696Error HWC2On1Adapter::Display::Config::getColorModeForHwc1Id(
1697 uint32_t id, android_color_mode_t* outMode) const
Dan Stoza076ac672016-03-14 10:47:53 -07001698{
1699 for (const auto& idPair : mHwc1Ids) {
1700 if (id == idPair.second) {
Michael Wright28f24d02016-07-12 13:30:53 -07001701 *outMode = idPair.first;
1702 return Error::None;
Dan Stoza076ac672016-03-14 10:47:53 -07001703 }
1704 }
Michael Wright28f24d02016-07-12 13:30:53 -07001705 ALOGE("Unable to find color mode for HWC ID %" PRIu32 " on config %u", id, mId);
1706 return Error::BadParameter;
Dan Stoza076ac672016-03-14 10:47:53 -07001707}
1708
Michael Wright28f24d02016-07-12 13:30:53 -07001709Error HWC2On1Adapter::Display::Config::getHwc1IdForColorMode(android_color_mode_t mode,
Dan Stoza076ac672016-03-14 10:47:53 -07001710 uint32_t* outId) const
1711{
1712 for (const auto& idPair : mHwc1Ids) {
1713 if (mode == idPair.first) {
1714 *outId = idPair.second;
1715 return Error::None;
1716 }
1717 }
1718 ALOGE("Unable to find HWC1 ID for color mode %d on config %u", mode, mId);
1719 return Error::BadParameter;
1720}
1721
1722bool HWC2On1Adapter::Display::Config::merge(const Config& other)
1723{
1724 auto attributes = {HWC2::Attribute::Width, HWC2::Attribute::Height,
1725 HWC2::Attribute::VsyncPeriod, HWC2::Attribute::DpiX,
1726 HWC2::Attribute::DpiY};
1727 for (auto attribute : attributes) {
1728 if (getAttribute(attribute) != other.getAttribute(attribute)) {
1729 return false;
1730 }
1731 }
Michael Wright28f24d02016-07-12 13:30:53 -07001732 android_color_mode_t otherColorMode =
1733 static_cast<android_color_mode_t>(other.getAttribute(ColorMode));
1734 if (mHwc1Ids.count(otherColorMode) != 0) {
Dan Stoza076ac672016-03-14 10:47:53 -07001735 ALOGE("Attempted to merge two configs (%u and %u) which appear to be "
Michael Wright28f24d02016-07-12 13:30:53 -07001736 "identical", mHwc1Ids.at(otherColorMode),
1737 other.mHwc1Ids.at(otherColorMode));
Dan Stoza076ac672016-03-14 10:47:53 -07001738 return false;
1739 }
Michael Wright28f24d02016-07-12 13:30:53 -07001740 mHwc1Ids.emplace(otherColorMode,
1741 other.mHwc1Ids.at(otherColorMode));
Dan Stoza076ac672016-03-14 10:47:53 -07001742 return true;
1743}
1744
Michael Wright28f24d02016-07-12 13:30:53 -07001745std::set<android_color_mode_t> HWC2On1Adapter::Display::Config::getColorModes() const
Dan Stoza076ac672016-03-14 10:47:53 -07001746{
Michael Wright28f24d02016-07-12 13:30:53 -07001747 std::set<android_color_mode_t> colorModes;
Dan Stoza076ac672016-03-14 10:47:53 -07001748 for (const auto& idPair : mHwc1Ids) {
Michael Wright28f24d02016-07-12 13:30:53 -07001749 colorModes.emplace(idPair.first);
Dan Stoza076ac672016-03-14 10:47:53 -07001750 }
Michael Wright28f24d02016-07-12 13:30:53 -07001751 return colorModes;
Dan Stoza076ac672016-03-14 10:47:53 -07001752}
1753
1754std::string HWC2On1Adapter::Display::Config::toString(bool splitLine) const
Dan Stozac6998d22015-09-24 17:03:36 -07001755{
1756 std::string output;
1757
1758 const size_t BUFFER_SIZE = 100;
1759 char buffer[BUFFER_SIZE] = {};
1760 auto writtenBytes = snprintf(buffer, BUFFER_SIZE,
Dan Stoza076ac672016-03-14 10:47:53 -07001761 "%u x %u", mAttributes.at(HWC2::Attribute::Width),
Dan Stozac6998d22015-09-24 17:03:36 -07001762 mAttributes.at(HWC2::Attribute::Height));
1763 output.append(buffer, writtenBytes);
1764
1765 if (mAttributes.count(HWC2::Attribute::VsyncPeriod) != 0) {
1766 std::memset(buffer, 0, BUFFER_SIZE);
1767 writtenBytes = snprintf(buffer, BUFFER_SIZE, " @ %.1f Hz",
1768 1e9 / mAttributes.at(HWC2::Attribute::VsyncPeriod));
1769 output.append(buffer, writtenBytes);
1770 }
1771
1772 if (mAttributes.count(HWC2::Attribute::DpiX) != 0 &&
1773 mAttributes.at(HWC2::Attribute::DpiX) != -1) {
1774 std::memset(buffer, 0, BUFFER_SIZE);
1775 writtenBytes = snprintf(buffer, BUFFER_SIZE,
1776 ", DPI: %.1f x %.1f",
1777 mAttributes.at(HWC2::Attribute::DpiX) / 1000.0f,
1778 mAttributes.at(HWC2::Attribute::DpiY) / 1000.0f);
1779 output.append(buffer, writtenBytes);
1780 }
1781
Dan Stoza076ac672016-03-14 10:47:53 -07001782 std::memset(buffer, 0, BUFFER_SIZE);
1783 if (splitLine) {
1784 writtenBytes = snprintf(buffer, BUFFER_SIZE,
1785 "\n HWC1 ID/Color transform:");
1786 } else {
1787 writtenBytes = snprintf(buffer, BUFFER_SIZE,
1788 ", HWC1 ID/Color transform:");
1789 }
1790 output.append(buffer, writtenBytes);
1791
1792
1793 for (const auto& id : mHwc1Ids) {
Michael Wright28f24d02016-07-12 13:30:53 -07001794 android_color_mode_t colorMode = id.first;
Dan Stoza076ac672016-03-14 10:47:53 -07001795 uint32_t hwc1Id = id.second;
1796 std::memset(buffer, 0, BUFFER_SIZE);
Michael Wright28f24d02016-07-12 13:30:53 -07001797 if (colorMode == mDisplay.mActiveColorMode) {
Dan Stoza076ac672016-03-14 10:47:53 -07001798 writtenBytes = snprintf(buffer, BUFFER_SIZE, " [%u/%d]", hwc1Id,
Michael Wright28f24d02016-07-12 13:30:53 -07001799 colorMode);
Dan Stoza076ac672016-03-14 10:47:53 -07001800 } else {
1801 writtenBytes = snprintf(buffer, BUFFER_SIZE, " %u/%d", hwc1Id,
Michael Wright28f24d02016-07-12 13:30:53 -07001802 colorMode);
Dan Stoza076ac672016-03-14 10:47:53 -07001803 }
1804 output.append(buffer, writtenBytes);
1805 }
1806
Dan Stozac6998d22015-09-24 17:03:36 -07001807 return output;
1808}
1809
1810std::shared_ptr<const HWC2On1Adapter::Display::Config>
1811 HWC2On1Adapter::Display::getConfig(hwc2_config_t configId) const
1812{
1813 if (configId > mConfigs.size() || !mConfigs[configId]->isOnDisplay(*this)) {
1814 return nullptr;
1815 }
1816 return mConfigs[configId];
1817}
1818
Dan Stoza076ac672016-03-14 10:47:53 -07001819void HWC2On1Adapter::Display::populateColorModes()
1820{
Michael Wright28f24d02016-07-12 13:30:53 -07001821 mColorModes = mConfigs[0]->getColorModes();
Dan Stoza076ac672016-03-14 10:47:53 -07001822 for (const auto& config : mConfigs) {
Michael Wright28f24d02016-07-12 13:30:53 -07001823 std::set<android_color_mode_t> intersection;
1824 auto configModes = config->getColorModes();
Dan Stoza076ac672016-03-14 10:47:53 -07001825 std::set_intersection(mColorModes.cbegin(), mColorModes.cend(),
1826 configModes.cbegin(), configModes.cend(),
1827 std::inserter(intersection, intersection.begin()));
1828 std::swap(intersection, mColorModes);
1829 }
1830}
1831
1832void HWC2On1Adapter::Display::initializeActiveConfig()
1833{
1834 if (mDevice.mHwc1Device->getActiveConfig == nullptr) {
1835 ALOGV("getActiveConfig is null, choosing config 0");
1836 mActiveConfig = mConfigs[0];
Michael Wright28f24d02016-07-12 13:30:53 -07001837 mActiveColorMode = HAL_COLOR_MODE_NATIVE;
Dan Stoza076ac672016-03-14 10:47:53 -07001838 return;
1839 }
1840
1841 auto activeConfig = mDevice.mHwc1Device->getActiveConfig(
1842 mDevice.mHwc1Device, mHwc1Id);
1843 if (activeConfig >= 0) {
1844 for (const auto& config : mConfigs) {
1845 if (config->hasHwc1Id(activeConfig)) {
1846 ALOGV("Setting active config to %d for HWC1 config %u",
1847 config->getId(), activeConfig);
1848 mActiveConfig = config;
Michael Wright28f24d02016-07-12 13:30:53 -07001849 if (config->getColorModeForHwc1Id(activeConfig, &mActiveColorMode) != Error::None) {
1850 // This should never happen since we checked for the config's presence before
1851 // setting it as active.
1852 ALOGE("Unable to find color mode for active HWC1 config %d",
1853 config->getId());
1854 mActiveColorMode = HAL_COLOR_MODE_NATIVE;
1855 }
Dan Stoza076ac672016-03-14 10:47:53 -07001856 break;
1857 }
1858 }
1859 if (!mActiveConfig) {
1860 ALOGV("Unable to find active HWC1 config %u, defaulting to "
1861 "config 0", activeConfig);
1862 mActiveConfig = mConfigs[0];
Michael Wright28f24d02016-07-12 13:30:53 -07001863 mActiveColorMode = HAL_COLOR_MODE_NATIVE;
Dan Stoza076ac672016-03-14 10:47:53 -07001864 }
1865 }
1866}
1867
Dan Stozac6998d22015-09-24 17:03:36 -07001868void HWC2On1Adapter::Display::reallocateHwc1Contents()
1869{
1870 // Allocate an additional layer for the framebuffer target
1871 auto numLayers = mLayers.size() + 1;
1872 size_t size = sizeof(hwc_display_contents_1_t) +
1873 sizeof(hwc_layer_1_t) * numLayers;
1874 ALOGV("[%" PRIu64 "] reallocateHwc1Contents creating %zd layer%s", mId,
1875 numLayers, numLayers != 1 ? "s" : "");
1876 auto contents =
1877 static_cast<hwc_display_contents_1_t*>(std::calloc(size, 1));
1878 contents->numHwLayers = numLayers;
1879 mHwc1RequestedContents.reset(contents);
1880}
1881
1882void HWC2On1Adapter::Display::assignHwc1LayerIds()
1883{
1884 mHwc1LayerMap.clear();
1885 size_t nextHwc1Id = 0;
1886 for (auto& layer : mLayers) {
1887 mHwc1LayerMap[nextHwc1Id] = layer;
1888 layer->setHwc1Id(nextHwc1Id++);
1889 }
1890}
1891
1892void HWC2On1Adapter::Display::updateTypeChanges(const hwc_layer_1_t& hwc1Layer,
1893 const Layer& layer)
1894{
1895 auto layerId = layer.getId();
1896 switch (hwc1Layer.compositionType) {
1897 case HWC_FRAMEBUFFER:
1898 if (layer.getCompositionType() != Composition::Client) {
1899 mChanges->addTypeChange(layerId, Composition::Client);
1900 }
1901 break;
1902 case HWC_OVERLAY:
1903 if (layer.getCompositionType() != Composition::Device) {
1904 mChanges->addTypeChange(layerId, Composition::Device);
1905 }
1906 break;
1907 case HWC_BACKGROUND:
1908 ALOGE_IF(layer.getCompositionType() != Composition::SolidColor,
1909 "updateTypeChanges: HWC1 requested BACKGROUND, but HWC2"
1910 " wasn't expecting SolidColor");
1911 break;
1912 case HWC_FRAMEBUFFER_TARGET:
1913 // Do nothing, since it shouldn't be modified by HWC1
1914 break;
1915 case HWC_SIDEBAND:
1916 ALOGE_IF(layer.getCompositionType() != Composition::Sideband,
1917 "updateTypeChanges: HWC1 requested SIDEBAND, but HWC2"
1918 " wasn't expecting Sideband");
1919 break;
1920 case HWC_CURSOR_OVERLAY:
1921 ALOGE_IF(layer.getCompositionType() != Composition::Cursor,
1922 "updateTypeChanges: HWC1 requested CURSOR_OVERLAY, but"
1923 " HWC2 wasn't expecting Cursor");
1924 break;
1925 }
1926}
1927
1928void HWC2On1Adapter::Display::updateLayerRequests(
1929 const hwc_layer_1_t& hwc1Layer, const Layer& layer)
1930{
1931 if ((hwc1Layer.hints & HWC_HINT_CLEAR_FB) != 0) {
1932 mChanges->addLayerRequest(layer.getId(),
1933 LayerRequest::ClearClientTarget);
1934 }
1935}
1936
1937void HWC2On1Adapter::Display::prepareFramebufferTarget()
1938{
1939 // We check that mActiveConfig is valid in Display::prepare
1940 int32_t width = mActiveConfig->getAttribute(Attribute::Width);
1941 int32_t height = mActiveConfig->getAttribute(Attribute::Height);
1942
1943 auto& hwc1Target = mHwc1RequestedContents->hwLayers[mLayers.size()];
1944 hwc1Target.compositionType = HWC_FRAMEBUFFER_TARGET;
1945 hwc1Target.releaseFenceFd = -1;
1946 hwc1Target.hints = 0;
1947 hwc1Target.flags = 0;
1948 hwc1Target.transform = 0;
1949 hwc1Target.blending = HWC_BLENDING_PREMULT;
1950 if (mDevice.getHwc1MinorVersion() < 3) {
1951 hwc1Target.sourceCropi = {0, 0, width, height};
1952 } else {
1953 hwc1Target.sourceCropf = {0.0f, 0.0f, static_cast<float>(width),
1954 static_cast<float>(height)};
1955 }
1956 hwc1Target.displayFrame = {0, 0, width, height};
1957 hwc1Target.planeAlpha = 255;
1958 hwc1Target.visibleRegionScreen.numRects = 1;
1959 auto rects = static_cast<hwc_rect_t*>(std::malloc(sizeof(hwc_rect_t)));
1960 rects[0].left = 0;
1961 rects[0].top = 0;
1962 rects[0].right = width;
1963 rects[0].bottom = height;
1964 hwc1Target.visibleRegionScreen.rects = rects;
1965
1966 // We will set this to the correct value in set
1967 hwc1Target.acquireFenceFd = -1;
1968}
1969
1970// Layer functions
1971
1972std::atomic<hwc2_layer_t> HWC2On1Adapter::Layer::sNextId(1);
1973
1974HWC2On1Adapter::Layer::Layer(Display& display)
1975 : mId(sNextId++),
1976 mDisplay(display),
Dan Stozafc4e2022016-02-23 11:43:19 -08001977 mDirtyCount(0),
1978 mBuffer(),
1979 mSurfaceDamage(),
Dan Stozac6998d22015-09-24 17:03:36 -07001980 mBlendMode(*this, BlendMode::None),
1981 mColor(*this, {0, 0, 0, 0}),
1982 mCompositionType(*this, Composition::Invalid),
1983 mDisplayFrame(*this, {0, 0, -1, -1}),
1984 mPlaneAlpha(*this, 0.0f),
1985 mSidebandStream(*this, nullptr),
1986 mSourceCrop(*this, {0.0f, 0.0f, -1.0f, -1.0f}),
1987 mTransform(*this, Transform::None),
1988 mVisibleRegion(*this, std::vector<hwc_rect_t>()),
1989 mZ(0),
Dan Stozafc4e2022016-02-23 11:43:19 -08001990 mReleaseFence(),
Dan Stozac6998d22015-09-24 17:03:36 -07001991 mHwc1Id(0),
Dan Stoza5df2a862016-03-24 16:19:37 -07001992 mHasUnsupportedDataspace(false),
Dan Stozac6998d22015-09-24 17:03:36 -07001993 mHasUnsupportedPlaneAlpha(false) {}
1994
1995bool HWC2On1Adapter::SortLayersByZ::operator()(
1996 const std::shared_ptr<Layer>& lhs, const std::shared_ptr<Layer>& rhs)
1997{
1998 return lhs->getZ() < rhs->getZ();
1999}
2000
2001Error HWC2On1Adapter::Layer::setBuffer(buffer_handle_t buffer,
2002 int32_t acquireFence)
2003{
2004 ALOGV("Setting acquireFence to %d for layer %" PRIu64, acquireFence, mId);
2005 mBuffer.setBuffer(buffer);
2006 mBuffer.setFence(acquireFence);
2007 return Error::None;
2008}
2009
2010Error HWC2On1Adapter::Layer::setCursorPosition(int32_t x, int32_t y)
2011{
2012 if (mCompositionType.getValue() != Composition::Cursor) {
2013 return Error::BadLayer;
2014 }
2015
2016 if (mDisplay.hasChanges()) {
2017 return Error::NotValidated;
2018 }
2019
2020 auto displayId = mDisplay.getHwc1Id();
2021 auto hwc1Device = mDisplay.getDevice().getHwc1Device();
2022 hwc1Device->setCursorPositionAsync(hwc1Device, displayId, x, y);
2023 return Error::None;
2024}
2025
2026Error HWC2On1Adapter::Layer::setSurfaceDamage(hwc_region_t damage)
2027{
2028 mSurfaceDamage.resize(damage.numRects);
2029 std::copy_n(damage.rects, damage.numRects, mSurfaceDamage.begin());
2030 return Error::None;
2031}
2032
2033// Layer state functions
2034
2035Error HWC2On1Adapter::Layer::setBlendMode(BlendMode mode)
2036{
2037 mBlendMode.setPending(mode);
2038 return Error::None;
2039}
2040
2041Error HWC2On1Adapter::Layer::setColor(hwc_color_t color)
2042{
2043 mColor.setPending(color);
2044 return Error::None;
2045}
2046
2047Error HWC2On1Adapter::Layer::setCompositionType(Composition type)
2048{
2049 mCompositionType.setPending(type);
2050 return Error::None;
2051}
2052
Dan Stoza5df2a862016-03-24 16:19:37 -07002053Error HWC2On1Adapter::Layer::setDataspace(android_dataspace_t dataspace)
2054{
2055 mHasUnsupportedDataspace = (dataspace != HAL_DATASPACE_UNKNOWN);
2056 return Error::None;
2057}
2058
Dan Stozac6998d22015-09-24 17:03:36 -07002059Error HWC2On1Adapter::Layer::setDisplayFrame(hwc_rect_t frame)
2060{
2061 mDisplayFrame.setPending(frame);
2062 return Error::None;
2063}
2064
2065Error HWC2On1Adapter::Layer::setPlaneAlpha(float alpha)
2066{
2067 mPlaneAlpha.setPending(alpha);
2068 return Error::None;
2069}
2070
2071Error HWC2On1Adapter::Layer::setSidebandStream(const native_handle_t* stream)
2072{
2073 mSidebandStream.setPending(stream);
2074 return Error::None;
2075}
2076
2077Error HWC2On1Adapter::Layer::setSourceCrop(hwc_frect_t crop)
2078{
2079 mSourceCrop.setPending(crop);
2080 return Error::None;
2081}
2082
2083Error HWC2On1Adapter::Layer::setTransform(Transform transform)
2084{
2085 mTransform.setPending(transform);
2086 return Error::None;
2087}
2088
2089Error HWC2On1Adapter::Layer::setVisibleRegion(hwc_region_t rawVisible)
2090{
2091 std::vector<hwc_rect_t> visible(rawVisible.rects,
2092 rawVisible.rects + rawVisible.numRects);
2093 mVisibleRegion.setPending(std::move(visible));
2094 return Error::None;
2095}
2096
2097Error HWC2On1Adapter::Layer::setZ(uint32_t z)
2098{
2099 mZ = z;
2100 return Error::None;
2101}
2102
2103void HWC2On1Adapter::Layer::addReleaseFence(int fenceFd)
2104{
2105 ALOGV("addReleaseFence %d to layer %" PRIu64, fenceFd, mId);
2106 mReleaseFence.add(fenceFd);
2107}
2108
2109const sp<Fence>& HWC2On1Adapter::Layer::getReleaseFence() const
2110{
2111 return mReleaseFence.get();
2112}
2113
2114void HWC2On1Adapter::Layer::applyState(hwc_layer_1_t& hwc1Layer,
2115 bool applyAllState)
2116{
2117 applyCommonState(hwc1Layer, applyAllState);
2118 auto compositionType = mCompositionType.getPendingValue();
2119 if (compositionType == Composition::SolidColor) {
2120 applySolidColorState(hwc1Layer, applyAllState);
2121 } else if (compositionType == Composition::Sideband) {
2122 applySidebandState(hwc1Layer, applyAllState);
2123 } else {
2124 applyBufferState(hwc1Layer);
2125 }
2126 applyCompositionType(hwc1Layer, applyAllState);
2127}
2128
2129// Layer dump helpers
2130
2131static std::string regionStrings(const std::vector<hwc_rect_t>& visibleRegion,
2132 const std::vector<hwc_rect_t>& surfaceDamage)
2133{
2134 std::string regions;
2135 regions += " Visible Region";
2136 regions.resize(40, ' ');
2137 regions += "Surface Damage\n";
2138
2139 size_t numPrinted = 0;
2140 size_t maxSize = std::max(visibleRegion.size(), surfaceDamage.size());
2141 while (numPrinted < maxSize) {
2142 std::string line(" ");
2143 if (visibleRegion.empty() && numPrinted == 0) {
2144 line += "None";
2145 } else if (numPrinted < visibleRegion.size()) {
2146 line += rectString(visibleRegion[numPrinted]);
2147 }
2148 line.resize(40, ' ');
2149 if (surfaceDamage.empty() && numPrinted == 0) {
2150 line += "None";
2151 } else if (numPrinted < surfaceDamage.size()) {
2152 line += rectString(surfaceDamage[numPrinted]);
2153 }
2154 line += '\n';
2155 regions += line;
2156 ++numPrinted;
2157 }
2158 return regions;
2159}
2160
2161std::string HWC2On1Adapter::Layer::dump() const
2162{
2163 std::stringstream output;
2164 const char* fill = " ";
2165
2166 output << fill << to_string(mCompositionType.getPendingValue());
2167 output << " Layer HWC2/1: " << mId << "/" << mHwc1Id << " ";
2168 output << "Z: " << mZ;
2169 if (mCompositionType.getValue() == HWC2::Composition::SolidColor) {
2170 output << " " << colorString(mColor.getValue());
2171 } else if (mCompositionType.getValue() == HWC2::Composition::Sideband) {
2172 output << " Handle: " << mSidebandStream.getValue() << '\n';
2173 } else {
2174 output << " Buffer: " << mBuffer.getBuffer() << "/" <<
2175 mBuffer.getFence() << '\n';
2176 output << fill << " Display frame [LTRB]: " <<
2177 rectString(mDisplayFrame.getValue()) << '\n';
2178 output << fill << " Source crop: " <<
2179 frectString(mSourceCrop.getValue()) << '\n';
2180 output << fill << " Transform: " << to_string(mTransform.getValue());
2181 output << " Blend mode: " << to_string(mBlendMode.getValue());
2182 if (mPlaneAlpha.getValue() != 1.0f) {
2183 output << " Alpha: " <<
2184 alphaString(mPlaneAlpha.getValue()) << '\n';
2185 } else {
2186 output << '\n';
2187 }
2188 output << regionStrings(mVisibleRegion.getValue(), mSurfaceDamage);
2189 }
2190 return output.str();
2191}
2192
2193static int getHwc1Blending(HWC2::BlendMode blendMode)
2194{
2195 switch (blendMode) {
2196 case BlendMode::Coverage: return HWC_BLENDING_COVERAGE;
2197 case BlendMode::Premultiplied: return HWC_BLENDING_PREMULT;
2198 default: return HWC_BLENDING_NONE;
2199 }
2200}
2201
2202void HWC2On1Adapter::Layer::applyCommonState(hwc_layer_1_t& hwc1Layer,
2203 bool applyAllState)
2204{
2205 auto minorVersion = mDisplay.getDevice().getHwc1MinorVersion();
2206 if (applyAllState || mBlendMode.isDirty()) {
2207 hwc1Layer.blending = getHwc1Blending(mBlendMode.getPendingValue());
2208 mBlendMode.latch();
2209 }
2210 if (applyAllState || mDisplayFrame.isDirty()) {
2211 hwc1Layer.displayFrame = mDisplayFrame.getPendingValue();
2212 mDisplayFrame.latch();
2213 }
2214 if (applyAllState || mPlaneAlpha.isDirty()) {
2215 auto pendingAlpha = mPlaneAlpha.getPendingValue();
2216 if (minorVersion < 2) {
2217 mHasUnsupportedPlaneAlpha = pendingAlpha < 1.0f;
2218 } else {
2219 hwc1Layer.planeAlpha =
2220 static_cast<uint8_t>(255.0f * pendingAlpha + 0.5f);
2221 }
2222 mPlaneAlpha.latch();
2223 }
2224 if (applyAllState || mSourceCrop.isDirty()) {
2225 if (minorVersion < 3) {
2226 auto pending = mSourceCrop.getPendingValue();
2227 hwc1Layer.sourceCropi.left =
2228 static_cast<int32_t>(std::ceil(pending.left));
2229 hwc1Layer.sourceCropi.top =
2230 static_cast<int32_t>(std::ceil(pending.top));
2231 hwc1Layer.sourceCropi.right =
2232 static_cast<int32_t>(std::floor(pending.right));
2233 hwc1Layer.sourceCropi.bottom =
2234 static_cast<int32_t>(std::floor(pending.bottom));
2235 } else {
2236 hwc1Layer.sourceCropf = mSourceCrop.getPendingValue();
2237 }
2238 mSourceCrop.latch();
2239 }
2240 if (applyAllState || mTransform.isDirty()) {
2241 hwc1Layer.transform =
2242 static_cast<uint32_t>(mTransform.getPendingValue());
2243 mTransform.latch();
2244 }
2245 if (applyAllState || mVisibleRegion.isDirty()) {
2246 auto& hwc1VisibleRegion = hwc1Layer.visibleRegionScreen;
2247
2248 std::free(const_cast<hwc_rect_t*>(hwc1VisibleRegion.rects));
2249
2250 auto pending = mVisibleRegion.getPendingValue();
2251 hwc_rect_t* newRects = static_cast<hwc_rect_t*>(
2252 std::malloc(sizeof(hwc_rect_t) * pending.size()));
2253 std::copy(pending.begin(), pending.end(), newRects);
2254 hwc1VisibleRegion.rects = const_cast<const hwc_rect_t*>(newRects);
2255 hwc1VisibleRegion.numRects = pending.size();
2256 mVisibleRegion.latch();
2257 }
2258}
2259
2260void HWC2On1Adapter::Layer::applySolidColorState(hwc_layer_1_t& hwc1Layer,
2261 bool applyAllState)
2262{
2263 if (applyAllState || mColor.isDirty()) {
2264 hwc1Layer.backgroundColor = mColor.getPendingValue();
2265 mColor.latch();
2266 }
2267}
2268
2269void HWC2On1Adapter::Layer::applySidebandState(hwc_layer_1_t& hwc1Layer,
2270 bool applyAllState)
2271{
2272 if (applyAllState || mSidebandStream.isDirty()) {
2273 hwc1Layer.sidebandStream = mSidebandStream.getPendingValue();
2274 mSidebandStream.latch();
2275 }
2276}
2277
2278void HWC2On1Adapter::Layer::applyBufferState(hwc_layer_1_t& hwc1Layer)
2279{
2280 hwc1Layer.handle = mBuffer.getBuffer();
2281 hwc1Layer.acquireFenceFd = mBuffer.getFence();
2282}
2283
2284void HWC2On1Adapter::Layer::applyCompositionType(hwc_layer_1_t& hwc1Layer,
2285 bool applyAllState)
2286{
Dan Stoza5df2a862016-03-24 16:19:37 -07002287 // HWC1 never supports color transforms or dataspaces and only sometimes
2288 // supports plane alpha (depending on the version). These require us to drop
2289 // some or all layers to client composition.
2290 if (mHasUnsupportedDataspace || mHasUnsupportedPlaneAlpha ||
2291 mDisplay.hasColorTransform()) {
Dan Stozac6998d22015-09-24 17:03:36 -07002292 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2293 hwc1Layer.flags = HWC_SKIP_LAYER;
2294 return;
2295 }
2296
2297 if (applyAllState || mCompositionType.isDirty()) {
2298 hwc1Layer.flags = 0;
2299 switch (mCompositionType.getPendingValue()) {
2300 case Composition::Client:
2301 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2302 hwc1Layer.flags |= HWC_SKIP_LAYER;
2303 break;
2304 case Composition::Device:
2305 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2306 break;
2307 case Composition::SolidColor:
Dan Stoza5df47cb2016-09-15 16:38:42 -07002308 // In theory the following line should work, but since the HWC1
2309 // version of SurfaceFlinger never used HWC_BACKGROUND, HWC1
2310 // devices may not work correctly. To be on the safe side, we
2311 // fall back to client composition.
2312 //
2313 // hwc1Layer.compositionType = HWC_BACKGROUND;
2314 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2315 hwc1Layer.flags |= HWC_SKIP_LAYER;
Dan Stozac6998d22015-09-24 17:03:36 -07002316 break;
2317 case Composition::Cursor:
2318 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2319 if (mDisplay.getDevice().getHwc1MinorVersion() >= 4) {
2320 hwc1Layer.hints |= HWC_IS_CURSOR_LAYER;
2321 }
2322 break;
2323 case Composition::Sideband:
2324 if (mDisplay.getDevice().getHwc1MinorVersion() < 4) {
2325 hwc1Layer.compositionType = HWC_SIDEBAND;
2326 } else {
2327 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2328 hwc1Layer.flags |= HWC_SKIP_LAYER;
2329 }
2330 break;
2331 default:
2332 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2333 hwc1Layer.flags |= HWC_SKIP_LAYER;
2334 break;
2335 }
2336 ALOGV("Layer %" PRIu64 " %s set to %d", mId,
2337 to_string(mCompositionType.getPendingValue()).c_str(),
2338 hwc1Layer.compositionType);
2339 ALOGV_IF(hwc1Layer.flags & HWC_SKIP_LAYER, " and skipping");
2340 mCompositionType.latch();
2341 }
2342}
2343
2344// Adapter helpers
2345
2346void HWC2On1Adapter::populateCapabilities()
2347{
2348 ALOGV("populateCapabilities");
2349 if (mHwc1MinorVersion >= 3U) {
2350 int supportedTypes = 0;
2351 auto result = mHwc1Device->query(mHwc1Device,
2352 HWC_DISPLAY_TYPES_SUPPORTED, &supportedTypes);
Fred Fettingerc50c01e2016-06-14 17:53:10 -05002353 if ((result == 0) && ((supportedTypes & HWC_DISPLAY_VIRTUAL_BIT) != 0)) {
Dan Stozac6998d22015-09-24 17:03:36 -07002354 ALOGI("Found support for HWC virtual displays");
2355 mHwc1SupportsVirtualDisplays = true;
2356 }
2357 }
2358 if (mHwc1MinorVersion >= 4U) {
2359 mCapabilities.insert(Capability::SidebandStream);
2360 }
2361}
2362
2363HWC2On1Adapter::Display* HWC2On1Adapter::getDisplay(hwc2_display_t id)
2364{
Dan Stozafc4e2022016-02-23 11:43:19 -08002365 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002366
2367 auto display = mDisplays.find(id);
2368 if (display == mDisplays.end()) {
2369 return nullptr;
2370 }
2371
2372 return display->second.get();
2373}
2374
2375std::tuple<HWC2On1Adapter::Layer*, Error> HWC2On1Adapter::getLayer(
2376 hwc2_display_t displayId, hwc2_layer_t layerId)
2377{
2378 auto display = getDisplay(displayId);
2379 if (!display) {
2380 return std::make_tuple(static_cast<Layer*>(nullptr), Error::BadDisplay);
2381 }
2382
2383 auto layerEntry = mLayers.find(layerId);
2384 if (layerEntry == mLayers.end()) {
2385 return std::make_tuple(static_cast<Layer*>(nullptr), Error::BadLayer);
2386 }
2387
2388 auto layer = layerEntry->second;
2389 if (layer->getDisplay().getId() != displayId) {
2390 return std::make_tuple(static_cast<Layer*>(nullptr), Error::BadLayer);
2391 }
2392 return std::make_tuple(layer.get(), Error::None);
2393}
2394
2395void HWC2On1Adapter::populatePrimary()
2396{
2397 ALOGV("populatePrimary");
2398
Dan Stozafc4e2022016-02-23 11:43:19 -08002399 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002400
2401 auto display =
2402 std::make_shared<Display>(*this, HWC2::DisplayType::Physical);
2403 mHwc1DisplayMap[HWC_DISPLAY_PRIMARY] = display->getId();
2404 display->setHwc1Id(HWC_DISPLAY_PRIMARY);
2405 display->populateConfigs();
2406 mDisplays.emplace(display->getId(), std::move(display));
2407}
2408
2409bool HWC2On1Adapter::prepareAllDisplays()
2410{
2411 ATRACE_CALL();
2412
Dan Stozafc4e2022016-02-23 11:43:19 -08002413 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002414
2415 for (const auto& displayPair : mDisplays) {
2416 auto& display = displayPair.second;
2417 if (!display->prepare()) {
2418 return false;
2419 }
2420 }
2421
2422 if (mHwc1DisplayMap.count(0) == 0) {
2423 ALOGE("prepareAllDisplays: Unable to find primary HWC1 display");
2424 return false;
2425 }
2426
2427 // Always push the primary display
2428 std::vector<HWC2On1Adapter::Display::HWC1Contents> requestedContents;
2429 auto primaryDisplayId = mHwc1DisplayMap[HWC_DISPLAY_PRIMARY];
2430 auto& primaryDisplay = mDisplays[primaryDisplayId];
2431 auto primaryDisplayContents = primaryDisplay->cloneRequestedContents();
2432 requestedContents.push_back(std::move(primaryDisplayContents));
2433
2434 // Push the external display, if present
2435 if (mHwc1DisplayMap.count(HWC_DISPLAY_EXTERNAL) != 0) {
2436 auto externalDisplayId = mHwc1DisplayMap[HWC_DISPLAY_EXTERNAL];
2437 auto& externalDisplay = mDisplays[externalDisplayId];
2438 auto externalDisplayContents =
2439 externalDisplay->cloneRequestedContents();
2440 requestedContents.push_back(std::move(externalDisplayContents));
2441 } else {
2442 // Even if an external display isn't present, we still need to send
2443 // at least two displays down to HWC1
2444 requestedContents.push_back(nullptr);
2445 }
2446
2447 // Push the hardware virtual display, if supported and present
2448 if (mHwc1MinorVersion >= 3) {
2449 if (mHwc1DisplayMap.count(HWC_DISPLAY_VIRTUAL) != 0) {
2450 auto virtualDisplayId = mHwc1DisplayMap[HWC_DISPLAY_VIRTUAL];
2451 auto& virtualDisplay = mDisplays[virtualDisplayId];
2452 auto virtualDisplayContents =
2453 virtualDisplay->cloneRequestedContents();
2454 requestedContents.push_back(std::move(virtualDisplayContents));
2455 } else {
2456 requestedContents.push_back(nullptr);
2457 }
2458 }
2459
2460 mHwc1Contents.clear();
2461 for (auto& displayContents : requestedContents) {
2462 mHwc1Contents.push_back(displayContents.get());
2463 if (!displayContents) {
2464 continue;
2465 }
2466
2467 ALOGV("Display %zd layers:", mHwc1Contents.size() - 1);
2468 for (size_t l = 0; l < displayContents->numHwLayers; ++l) {
2469 auto& layer = displayContents->hwLayers[l];
2470 ALOGV(" %zd: %d", l, layer.compositionType);
2471 }
2472 }
2473
2474 ALOGV("Calling HWC1 prepare");
2475 {
2476 ATRACE_NAME("HWC1 prepare");
2477 mHwc1Device->prepare(mHwc1Device, mHwc1Contents.size(),
2478 mHwc1Contents.data());
2479 }
2480
2481 for (size_t c = 0; c < mHwc1Contents.size(); ++c) {
2482 auto& contents = mHwc1Contents[c];
2483 if (!contents) {
2484 continue;
2485 }
2486 ALOGV("Display %zd layers:", c);
2487 for (size_t l = 0; l < contents->numHwLayers; ++l) {
2488 ALOGV(" %zd: %d", l, contents->hwLayers[l].compositionType);
2489 }
2490 }
2491
2492 // Return the received contents to their respective displays
2493 for (size_t hwc1Id = 0; hwc1Id < mHwc1Contents.size(); ++hwc1Id) {
2494 if (mHwc1Contents[hwc1Id] == nullptr) {
2495 continue;
2496 }
2497
2498 auto displayId = mHwc1DisplayMap[hwc1Id];
2499 auto& display = mDisplays[displayId];
2500 display->setReceivedContents(std::move(requestedContents[hwc1Id]));
2501 }
2502
2503 return true;
2504}
2505
2506Error HWC2On1Adapter::setAllDisplays()
2507{
2508 ATRACE_CALL();
2509
Dan Stozafc4e2022016-02-23 11:43:19 -08002510 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002511
2512 // Make sure we're ready to validate
2513 for (size_t hwc1Id = 0; hwc1Id < mHwc1Contents.size(); ++hwc1Id) {
2514 if (mHwc1Contents[hwc1Id] == nullptr) {
2515 continue;
2516 }
2517
2518 auto displayId = mHwc1DisplayMap[hwc1Id];
2519 auto& display = mDisplays[displayId];
2520 Error error = display->set(*mHwc1Contents[hwc1Id]);
2521 if (error != Error::None) {
2522 ALOGE("setAllDisplays: Failed to set display %zd: %s", hwc1Id,
2523 to_string(error).c_str());
2524 return error;
2525 }
2526 }
2527
2528 ALOGV("Calling HWC1 set");
2529 {
2530 ATRACE_NAME("HWC1 set");
2531 mHwc1Device->set(mHwc1Device, mHwc1Contents.size(),
2532 mHwc1Contents.data());
2533 }
2534
2535 // Add retire and release fences
2536 for (size_t hwc1Id = 0; hwc1Id < mHwc1Contents.size(); ++hwc1Id) {
2537 if (mHwc1Contents[hwc1Id] == nullptr) {
2538 continue;
2539 }
2540
2541 auto displayId = mHwc1DisplayMap[hwc1Id];
2542 auto& display = mDisplays[displayId];
2543 auto retireFenceFd = mHwc1Contents[hwc1Id]->retireFenceFd;
2544 ALOGV("setAllDisplays: Adding retire fence %d to display %zd",
2545 retireFenceFd, hwc1Id);
2546 display->addRetireFence(mHwc1Contents[hwc1Id]->retireFenceFd);
2547 display->addReleaseFences(*mHwc1Contents[hwc1Id]);
2548 }
2549
2550 return Error::None;
2551}
2552
2553void HWC2On1Adapter::hwc1Invalidate()
2554{
2555 ALOGV("Received hwc1Invalidate");
2556
Dan Stozafc4e2022016-02-23 11:43:19 -08002557 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002558
2559 // If the HWC2-side callback hasn't been registered yet, buffer this until
2560 // it is registered
2561 if (mCallbacks.count(Callback::Refresh) == 0) {
2562 mHasPendingInvalidate = true;
2563 return;
2564 }
2565
2566 const auto& callbackInfo = mCallbacks[Callback::Refresh];
2567 std::vector<hwc2_display_t> displays;
2568 for (const auto& displayPair : mDisplays) {
2569 displays.emplace_back(displayPair.first);
2570 }
2571
2572 // Call back without the state lock held
2573 lock.unlock();
2574
2575 auto refresh = reinterpret_cast<HWC2_PFN_REFRESH>(callbackInfo.pointer);
2576 for (auto display : displays) {
2577 refresh(callbackInfo.data, display);
2578 }
2579}
2580
2581void HWC2On1Adapter::hwc1Vsync(int hwc1DisplayId, int64_t timestamp)
2582{
2583 ALOGV("Received hwc1Vsync(%d, %" PRId64 ")", hwc1DisplayId, timestamp);
2584
Dan Stozafc4e2022016-02-23 11:43:19 -08002585 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002586
2587 // If the HWC2-side callback hasn't been registered yet, buffer this until
2588 // it is registered
2589 if (mCallbacks.count(Callback::Vsync) == 0) {
2590 mPendingVsyncs.emplace_back(hwc1DisplayId, timestamp);
2591 return;
2592 }
2593
2594 if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) {
2595 ALOGE("hwc1Vsync: Couldn't find display for HWC1 id %d", hwc1DisplayId);
2596 return;
2597 }
2598
2599 const auto& callbackInfo = mCallbacks[Callback::Vsync];
2600 auto displayId = mHwc1DisplayMap[hwc1DisplayId];
2601
2602 // Call back without the state lock held
2603 lock.unlock();
2604
2605 auto vsync = reinterpret_cast<HWC2_PFN_VSYNC>(callbackInfo.pointer);
2606 vsync(callbackInfo.data, displayId, timestamp);
2607}
2608
2609void HWC2On1Adapter::hwc1Hotplug(int hwc1DisplayId, int connected)
2610{
2611 ALOGV("Received hwc1Hotplug(%d, %d)", hwc1DisplayId, connected);
2612
2613 if (hwc1DisplayId != HWC_DISPLAY_EXTERNAL) {
2614 ALOGE("hwc1Hotplug: Received hotplug for non-external display");
2615 return;
2616 }
2617
Dan Stozafc4e2022016-02-23 11:43:19 -08002618 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002619
2620 // If the HWC2-side callback hasn't been registered yet, buffer this until
2621 // it is registered
2622 if (mCallbacks.count(Callback::Hotplug) == 0) {
2623 mPendingHotplugs.emplace_back(hwc1DisplayId, connected);
2624 return;
2625 }
2626
2627 hwc2_display_t displayId = UINT64_MAX;
2628 if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) {
2629 if (connected == 0) {
2630 ALOGW("hwc1Hotplug: Received disconnect for unconnected display");
2631 return;
2632 }
2633
2634 // Create a new display on connect
2635 auto display = std::make_shared<HWC2On1Adapter::Display>(*this,
2636 HWC2::DisplayType::Physical);
2637 display->setHwc1Id(HWC_DISPLAY_EXTERNAL);
2638 display->populateConfigs();
2639 displayId = display->getId();
2640 mHwc1DisplayMap[HWC_DISPLAY_EXTERNAL] = displayId;
2641 mDisplays.emplace(displayId, std::move(display));
2642 } else {
2643 if (connected != 0) {
2644 ALOGW("hwc1Hotplug: Received connect for previously connected "
2645 "display");
2646 return;
2647 }
2648
2649 // Disconnect an existing display
2650 displayId = mHwc1DisplayMap[hwc1DisplayId];
2651 mHwc1DisplayMap.erase(HWC_DISPLAY_EXTERNAL);
2652 mDisplays.erase(displayId);
2653 }
2654
2655 const auto& callbackInfo = mCallbacks[Callback::Hotplug];
2656
2657 // Call back without the state lock held
2658 lock.unlock();
2659
2660 auto hotplug = reinterpret_cast<HWC2_PFN_HOTPLUG>(callbackInfo.pointer);
2661 auto hwc2Connected = (connected == 0) ?
2662 HWC2::Connection::Disconnected : HWC2::Connection::Connected;
2663 hotplug(callbackInfo.data, displayId, static_cast<int32_t>(hwc2Connected));
2664}
2665
2666} // namespace android