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