blob: 40c67156cabb2b748454b80d38a1581bece2fa17 [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
811 *outDisplayRequests = mChanges->getDisplayRequests();
812 uint32_t numWritten = 0;
813 for (const auto& request : mChanges->getLayerRequests()) {
814 if (numWritten == *outNumElements) {
815 break;
816 }
817 outLayers[numWritten] = request.first;
818 outLayerRequests[numWritten] = static_cast<int32_t>(request.second);
819 ++numWritten;
820 }
821
822 return Error::None;
823}
824
825Error HWC2On1Adapter::Display::getType(int32_t* outType)
826{
827 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
828
829 *outType = static_cast<int32_t>(mType);
830 return Error::None;
831}
832
833Error HWC2On1Adapter::Display::present(int32_t* outRetireFence)
834{
835 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
836
837 if (mChanges) {
838 Error error = mDevice.setAllDisplays();
839 if (error != Error::None) {
840 ALOGE("[%" PRIu64 "] present: setAllDisplaysFailed (%s)", mId,
841 to_string(error).c_str());
842 return error;
843 }
844 }
845
846 *outRetireFence = mRetireFence.get()->dup();
847 ALOGV("[%" PRIu64 "] present returning retire fence %d", mId,
848 *outRetireFence);
849
850 return Error::None;
851}
852
853Error HWC2On1Adapter::Display::setActiveConfig(hwc2_config_t configId)
854{
855 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
856
857 auto config = getConfig(configId);
858 if (!config) {
859 return Error::BadConfig;
860 }
Dan Stoza076ac672016-03-14 10:47:53 -0700861 if (config == mActiveConfig) {
862 return Error::None;
Dan Stozac6998d22015-09-24 17:03:36 -0700863 }
Dan Stoza076ac672016-03-14 10:47:53 -0700864
865 if (mDevice.mHwc1MinorVersion >= 4) {
866 uint32_t hwc1Id = 0;
867 auto error = config->getHwc1IdForColorMode(mActiveColorMode, &hwc1Id);
868 if (error != Error::None) {
869 return error;
870 }
871
872 int intError = mDevice.mHwc1Device->setActiveConfig(mDevice.mHwc1Device,
873 mHwc1Id, static_cast<int>(hwc1Id));
874 if (intError != 0) {
875 ALOGE("setActiveConfig: Failed to set active config on HWC1 (%d)",
876 intError);
877 return Error::BadConfig;
878 }
879 mActiveConfig = config;
880 }
881
Dan Stozac6998d22015-09-24 17:03:36 -0700882 return Error::None;
883}
884
885Error HWC2On1Adapter::Display::setClientTarget(buffer_handle_t target,
Dan Stoza5cf424b2016-05-20 14:02:39 -0700886 int32_t acquireFence, int32_t /*dataspace*/, hwc_region_t /*damage*/)
Dan Stozac6998d22015-09-24 17:03:36 -0700887{
888 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
889
890 ALOGV("[%" PRIu64 "] setClientTarget(%p, %d)", mId, target, acquireFence);
891 mClientTarget.setBuffer(target);
892 mClientTarget.setFence(acquireFence);
Dan Stoza5cf424b2016-05-20 14:02:39 -0700893 // dataspace and damage can't be used by HWC1, so ignore them
Dan Stozac6998d22015-09-24 17:03:36 -0700894 return Error::None;
895}
896
Michael Wright28f24d02016-07-12 13:30:53 -0700897Error HWC2On1Adapter::Display::setColorMode(android_color_mode_t mode)
Dan Stoza076ac672016-03-14 10:47:53 -0700898{
899 std::unique_lock<std::recursive_mutex> lock (mStateMutex);
900
901 ALOGV("[%" PRIu64 "] setColorMode(%d)", mId, mode);
902
903 if (mode == mActiveColorMode) {
904 return Error::None;
905 }
906 if (mColorModes.count(mode) == 0) {
907 ALOGE("[%" PRIu64 "] Mode %d not found in mColorModes", mId, mode);
908 return Error::Unsupported;
909 }
910
911 uint32_t hwc1Config = 0;
912 auto error = mActiveConfig->getHwc1IdForColorMode(mode, &hwc1Config);
913 if (error != Error::None) {
914 return error;
915 }
916
917 ALOGV("[%" PRIu64 "] Setting HWC1 config %u", mId, hwc1Config);
918 int intError = mDevice.mHwc1Device->setActiveConfig(mDevice.mHwc1Device,
919 mHwc1Id, hwc1Config);
920 if (intError != 0) {
921 ALOGE("[%" PRIu64 "] Failed to set HWC1 config (%d)", mId, intError);
922 return Error::Unsupported;
923 }
924
925 mActiveColorMode = mode;
926 return Error::None;
927}
928
Dan Stoza5df2a862016-03-24 16:19:37 -0700929Error HWC2On1Adapter::Display::setColorTransform(android_color_transform_t hint)
930{
931 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
932
933 ALOGV("%" PRIu64 "] setColorTransform(%d)", mId,
934 static_cast<int32_t>(hint));
935 mHasColorTransform = (hint != HAL_COLOR_TRANSFORM_IDENTITY);
936 return Error::None;
937}
938
Dan Stozac6998d22015-09-24 17:03:36 -0700939Error HWC2On1Adapter::Display::setOutputBuffer(buffer_handle_t buffer,
940 int32_t releaseFence)
941{
942 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
943
944 ALOGV("[%" PRIu64 "] setOutputBuffer(%p, %d)", mId, buffer, releaseFence);
945 mOutputBuffer.setBuffer(buffer);
946 mOutputBuffer.setFence(releaseFence);
947 return Error::None;
948}
949
950static bool isValid(PowerMode mode)
951{
952 switch (mode) {
953 case PowerMode::Off: // Fall-through
954 case PowerMode::DozeSuspend: // Fall-through
955 case PowerMode::Doze: // Fall-through
956 case PowerMode::On: return true;
957 default: return false;
958 }
959}
960
961static int getHwc1PowerMode(PowerMode mode)
962{
963 switch (mode) {
964 case PowerMode::Off: return HWC_POWER_MODE_OFF;
965 case PowerMode::DozeSuspend: return HWC_POWER_MODE_DOZE_SUSPEND;
966 case PowerMode::Doze: return HWC_POWER_MODE_DOZE;
967 case PowerMode::On: return HWC_POWER_MODE_NORMAL;
968 default: return HWC_POWER_MODE_OFF;
969 }
970}
971
972Error HWC2On1Adapter::Display::setPowerMode(PowerMode mode)
973{
974 if (!isValid(mode)) {
975 return Error::BadParameter;
976 }
977 if (mode == mPowerMode) {
978 return Error::None;
979 }
980
981 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
982
983 int error = 0;
984 if (mDevice.mHwc1MinorVersion < 4) {
985 error = mDevice.mHwc1Device->blank(mDevice.mHwc1Device, mHwc1Id,
986 mode == PowerMode::Off);
987 } else {
988 error = mDevice.mHwc1Device->setPowerMode(mDevice.mHwc1Device,
989 mHwc1Id, getHwc1PowerMode(mode));
990 }
991 ALOGE_IF(error != 0, "setPowerMode: Failed to set power mode on HWC1 (%d)",
992 error);
993
994 ALOGV("[%" PRIu64 "] setPowerMode(%s)", mId, to_string(mode).c_str());
995 mPowerMode = mode;
996 return Error::None;
997}
998
999static bool isValid(Vsync enable) {
1000 switch (enable) {
1001 case Vsync::Enable: // Fall-through
1002 case Vsync::Disable: return true;
1003 default: return false;
1004 }
1005}
1006
1007Error HWC2On1Adapter::Display::setVsyncEnabled(Vsync enable)
1008{
1009 if (!isValid(enable)) {
1010 return Error::BadParameter;
1011 }
1012 if (enable == mVsyncEnabled) {
1013 return Error::None;
1014 }
1015
1016 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1017
1018 int error = mDevice.mHwc1Device->eventControl(mDevice.mHwc1Device,
1019 mHwc1Id, HWC_EVENT_VSYNC, enable == Vsync::Enable);
1020 ALOGE_IF(error != 0, "setVsyncEnabled: Failed to set vsync on HWC1 (%d)",
1021 error);
1022
1023 mVsyncEnabled = enable;
1024 return Error::None;
1025}
1026
1027Error HWC2On1Adapter::Display::validate(uint32_t* outNumTypes,
1028 uint32_t* outNumRequests)
1029{
1030 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1031
1032 ALOGV("[%" PRIu64 "] Entering validate", mId);
1033
1034 if (!mChanges) {
1035 if (!mDevice.prepareAllDisplays()) {
1036 return Error::BadDisplay;
1037 }
1038 }
1039
1040 *outNumTypes = mChanges->getNumTypes();
1041 *outNumRequests = mChanges->getNumLayerRequests();
1042 ALOGV("[%" PRIu64 "] validate --> %u types, %u requests", mId, *outNumTypes,
1043 *outNumRequests);
1044 for (auto request : mChanges->getTypeChanges()) {
1045 ALOGV("Layer %" PRIu64 " --> %s", request.first,
1046 to_string(request.second).c_str());
1047 }
1048 return *outNumTypes > 0 ? Error::HasChanges : Error::None;
1049}
1050
1051// Display helpers
1052
1053Error HWC2On1Adapter::Display::updateLayerZ(hwc2_layer_t layerId, uint32_t z)
1054{
1055 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1056
1057 const auto mapLayer = mDevice.mLayers.find(layerId);
1058 if (mapLayer == mDevice.mLayers.end()) {
1059 ALOGE("[%" PRIu64 "] updateLayerZ failed to find layer", mId);
1060 return Error::BadLayer;
1061 }
1062
1063 const auto layer = mapLayer->second;
1064 const auto zRange = mLayers.equal_range(layer);
1065 bool layerOnDisplay = false;
1066 for (auto current = zRange.first; current != zRange.second; ++current) {
1067 if (**current == *layer) {
1068 if ((*current)->getZ() == z) {
1069 // Don't change anything if the Z hasn't changed
1070 return Error::None;
1071 }
1072 current = mLayers.erase(current);
1073 layerOnDisplay = true;
1074 break;
1075 }
1076 }
1077
1078 if (!layerOnDisplay) {
1079 ALOGE("[%" PRIu64 "] updateLayerZ failed to find layer on display",
1080 mId);
1081 return Error::BadLayer;
1082 }
1083
1084 layer->setZ(z);
1085 mLayers.emplace(std::move(layer));
1086 mZIsDirty = true;
1087
1088 return Error::None;
1089}
1090
Dan Stoza076ac672016-03-14 10:47:53 -07001091static constexpr uint32_t ATTRIBUTES_WITH_COLOR[] = {
1092 HWC_DISPLAY_VSYNC_PERIOD,
1093 HWC_DISPLAY_WIDTH,
1094 HWC_DISPLAY_HEIGHT,
1095 HWC_DISPLAY_DPI_X,
1096 HWC_DISPLAY_DPI_Y,
1097 HWC_DISPLAY_COLOR_TRANSFORM,
1098 HWC_DISPLAY_NO_ATTRIBUTE,
1099};
1100
1101static constexpr uint32_t ATTRIBUTES_WITHOUT_COLOR[] = {
Dan Stozac6998d22015-09-24 17:03:36 -07001102 HWC_DISPLAY_VSYNC_PERIOD,
1103 HWC_DISPLAY_WIDTH,
1104 HWC_DISPLAY_HEIGHT,
1105 HWC_DISPLAY_DPI_X,
1106 HWC_DISPLAY_DPI_Y,
1107 HWC_DISPLAY_NO_ATTRIBUTE,
1108};
Dan Stozac6998d22015-09-24 17:03:36 -07001109
Dan Stoza076ac672016-03-14 10:47:53 -07001110static constexpr size_t NUM_ATTRIBUTES_WITH_COLOR =
1111 sizeof(ATTRIBUTES_WITH_COLOR) / sizeof(uint32_t);
1112static_assert(sizeof(ATTRIBUTES_WITH_COLOR) > sizeof(ATTRIBUTES_WITHOUT_COLOR),
1113 "Attribute tables have unexpected sizes");
1114
1115static constexpr uint32_t ATTRIBUTE_MAP_WITH_COLOR[] = {
1116 6, // HWC_DISPLAY_NO_ATTRIBUTE = 0
1117 0, // HWC_DISPLAY_VSYNC_PERIOD = 1,
1118 1, // HWC_DISPLAY_WIDTH = 2,
1119 2, // HWC_DISPLAY_HEIGHT = 3,
1120 3, // HWC_DISPLAY_DPI_X = 4,
1121 4, // HWC_DISPLAY_DPI_Y = 5,
1122 5, // HWC_DISPLAY_COLOR_TRANSFORM = 6,
1123};
1124
1125static constexpr uint32_t ATTRIBUTE_MAP_WITHOUT_COLOR[] = {
Dan Stozac6998d22015-09-24 17:03:36 -07001126 5, // HWC_DISPLAY_NO_ATTRIBUTE = 0
1127 0, // HWC_DISPLAY_VSYNC_PERIOD = 1,
1128 1, // HWC_DISPLAY_WIDTH = 2,
1129 2, // HWC_DISPLAY_HEIGHT = 3,
1130 3, // HWC_DISPLAY_DPI_X = 4,
1131 4, // HWC_DISPLAY_DPI_Y = 5,
1132};
1133
1134template <uint32_t attribute>
1135static constexpr bool attributesMatch()
1136{
Dan Stoza076ac672016-03-14 10:47:53 -07001137 bool match = (attribute ==
1138 ATTRIBUTES_WITH_COLOR[ATTRIBUTE_MAP_WITH_COLOR[attribute]]);
1139 if (attribute == HWC_DISPLAY_COLOR_TRANSFORM) {
1140 return match;
1141 }
1142
1143 return match && (attribute ==
1144 ATTRIBUTES_WITHOUT_COLOR[ATTRIBUTE_MAP_WITHOUT_COLOR[attribute]]);
Dan Stozac6998d22015-09-24 17:03:36 -07001145}
1146static_assert(attributesMatch<HWC_DISPLAY_VSYNC_PERIOD>(),
1147 "Tables out of sync");
1148static_assert(attributesMatch<HWC_DISPLAY_WIDTH>(), "Tables out of sync");
1149static_assert(attributesMatch<HWC_DISPLAY_HEIGHT>(), "Tables out of sync");
1150static_assert(attributesMatch<HWC_DISPLAY_DPI_X>(), "Tables out of sync");
1151static_assert(attributesMatch<HWC_DISPLAY_DPI_Y>(), "Tables out of sync");
Dan Stoza076ac672016-03-14 10:47:53 -07001152static_assert(attributesMatch<HWC_DISPLAY_COLOR_TRANSFORM>(),
1153 "Tables out of sync");
Dan Stozac6998d22015-09-24 17:03:36 -07001154
1155void HWC2On1Adapter::Display::populateConfigs()
1156{
1157 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1158
1159 ALOGV("[%" PRIu64 "] populateConfigs", mId);
1160
1161 if (mHwc1Id == -1) {
1162 ALOGE("populateConfigs: HWC1 ID not set");
1163 return;
1164 }
1165
1166 const size_t MAX_NUM_CONFIGS = 128;
1167 uint32_t configs[MAX_NUM_CONFIGS] = {};
1168 size_t numConfigs = MAX_NUM_CONFIGS;
1169 mDevice.mHwc1Device->getDisplayConfigs(mDevice.mHwc1Device, mHwc1Id,
1170 configs, &numConfigs);
1171
1172 for (size_t c = 0; c < numConfigs; ++c) {
1173 uint32_t hwc1ConfigId = configs[c];
Dan Stoza076ac672016-03-14 10:47:53 -07001174 auto newConfig = std::make_shared<Config>(*this);
Dan Stozac6998d22015-09-24 17:03:36 -07001175
Dan Stoza076ac672016-03-14 10:47:53 -07001176 int32_t values[NUM_ATTRIBUTES_WITH_COLOR] = {};
1177 bool hasColor = true;
1178 auto result = mDevice.mHwc1Device->getDisplayAttributes(
1179 mDevice.mHwc1Device, mHwc1Id, hwc1ConfigId,
1180 ATTRIBUTES_WITH_COLOR, values);
1181 if (result != 0) {
1182 mDevice.mHwc1Device->getDisplayAttributes(mDevice.mHwc1Device,
1183 mHwc1Id, hwc1ConfigId, ATTRIBUTES_WITHOUT_COLOR, values);
1184 hasColor = false;
Dan Stozac6998d22015-09-24 17:03:36 -07001185 }
Dan Stoza076ac672016-03-14 10:47:53 -07001186
1187 auto attributeMap = hasColor ?
1188 ATTRIBUTE_MAP_WITH_COLOR : ATTRIBUTE_MAP_WITHOUT_COLOR;
1189
1190 newConfig->setAttribute(Attribute::VsyncPeriod,
1191 values[attributeMap[HWC_DISPLAY_VSYNC_PERIOD]]);
1192 newConfig->setAttribute(Attribute::Width,
1193 values[attributeMap[HWC_DISPLAY_WIDTH]]);
1194 newConfig->setAttribute(Attribute::Height,
1195 values[attributeMap[HWC_DISPLAY_HEIGHT]]);
1196 newConfig->setAttribute(Attribute::DpiX,
1197 values[attributeMap[HWC_DISPLAY_DPI_X]]);
1198 newConfig->setAttribute(Attribute::DpiY,
1199 values[attributeMap[HWC_DISPLAY_DPI_Y]]);
1200 if (hasColor) {
Michael Wright28f24d02016-07-12 13:30:53 -07001201 // In HWC1, color modes are referred to as color transforms. To avoid confusion with
1202 // the HWC2 concept of color transforms, we internally refer to them as color modes for
1203 // both HWC1 and 2.
1204 newConfig->setAttribute(ColorMode,
Dan Stoza076ac672016-03-14 10:47:53 -07001205 values[attributeMap[HWC_DISPLAY_COLOR_TRANSFORM]]);
1206 }
1207
Michael Wright28f24d02016-07-12 13:30:53 -07001208 // We can only do this after attempting to read the color mode
Dan Stoza076ac672016-03-14 10:47:53 -07001209 newConfig->setHwc1Id(hwc1ConfigId);
1210
1211 for (auto& existingConfig : mConfigs) {
1212 if (existingConfig->merge(*newConfig)) {
1213 ALOGV("Merged config %d with existing config %u: %s",
1214 hwc1ConfigId, existingConfig->getId(),
1215 existingConfig->toString().c_str());
1216 newConfig.reset();
1217 break;
1218 }
1219 }
1220
1221 // If it wasn't merged with any existing config, add it to the end
1222 if (newConfig) {
1223 newConfig->setId(static_cast<hwc2_config_t>(mConfigs.size()));
1224 ALOGV("Found new config %u: %s", newConfig->getId(),
1225 newConfig->toString().c_str());
1226 mConfigs.emplace_back(std::move(newConfig));
1227 }
Dan Stozac6998d22015-09-24 17:03:36 -07001228 }
Dan Stoza076ac672016-03-14 10:47:53 -07001229
1230 initializeActiveConfig();
1231 populateColorModes();
Dan Stozac6998d22015-09-24 17:03:36 -07001232}
1233
1234void HWC2On1Adapter::Display::populateConfigs(uint32_t width, uint32_t height)
1235{
1236 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1237
Dan Stoza076ac672016-03-14 10:47:53 -07001238 mConfigs.emplace_back(std::make_shared<Config>(*this));
Dan Stozac6998d22015-09-24 17:03:36 -07001239 auto& config = mConfigs[0];
1240
1241 config->setAttribute(Attribute::Width, static_cast<int32_t>(width));
1242 config->setAttribute(Attribute::Height, static_cast<int32_t>(height));
Dan Stoza076ac672016-03-14 10:47:53 -07001243 config->setHwc1Id(0);
1244 config->setId(0);
Dan Stozac6998d22015-09-24 17:03:36 -07001245 mActiveConfig = config;
1246}
1247
1248bool HWC2On1Adapter::Display::prepare()
1249{
1250 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1251
1252 // Only prepare display contents for displays HWC1 knows about
1253 if (mHwc1Id == -1) {
1254 return true;
1255 }
1256
1257 // It doesn't make sense to prepare a display for which there is no active
1258 // config, so return early
1259 if (!mActiveConfig) {
1260 ALOGE("[%" PRIu64 "] Attempted to prepare, but no config active", mId);
1261 return false;
1262 }
1263
1264 ALOGV("[%" PRIu64 "] Entering prepare", mId);
1265
1266 auto currentCount = mHwc1RequestedContents ?
1267 mHwc1RequestedContents->numHwLayers : 0;
1268 auto requiredCount = mLayers.size() + 1;
1269 ALOGV("[%" PRIu64 "] Requires %zd layers, %zd allocated in %p", mId,
1270 requiredCount, currentCount, mHwc1RequestedContents.get());
1271
1272 bool layerCountChanged = (currentCount != requiredCount);
1273 if (layerCountChanged) {
1274 reallocateHwc1Contents();
1275 }
1276
1277 bool applyAllState = false;
1278 if (layerCountChanged || mZIsDirty) {
1279 assignHwc1LayerIds();
1280 mZIsDirty = false;
1281 applyAllState = true;
1282 }
1283
1284 mHwc1RequestedContents->retireFenceFd = -1;
1285 mHwc1RequestedContents->flags = 0;
1286 if (isDirty() || applyAllState) {
1287 mHwc1RequestedContents->flags |= HWC_GEOMETRY_CHANGED;
1288 }
1289
1290 for (auto& layer : mLayers) {
1291 auto& hwc1Layer = mHwc1RequestedContents->hwLayers[layer->getHwc1Id()];
1292 hwc1Layer.releaseFenceFd = -1;
1293 layer->applyState(hwc1Layer, applyAllState);
1294 }
1295
1296 mHwc1RequestedContents->outbuf = mOutputBuffer.getBuffer();
1297 mHwc1RequestedContents->outbufAcquireFenceFd = mOutputBuffer.getFence();
1298
1299 prepareFramebufferTarget();
1300
1301 return true;
1302}
1303
1304static void cloneHWCRegion(hwc_region_t& region)
1305{
1306 auto size = sizeof(hwc_rect_t) * region.numRects;
1307 auto newRects = static_cast<hwc_rect_t*>(std::malloc(size));
1308 std::copy_n(region.rects, region.numRects, newRects);
1309 region.rects = newRects;
1310}
1311
1312HWC2On1Adapter::Display::HWC1Contents
1313 HWC2On1Adapter::Display::cloneRequestedContents() const
1314{
1315 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1316
1317 size_t size = sizeof(hwc_display_contents_1_t) +
1318 sizeof(hwc_layer_1_t) * (mHwc1RequestedContents->numHwLayers);
1319 auto contents = static_cast<hwc_display_contents_1_t*>(std::malloc(size));
1320 std::memcpy(contents, mHwc1RequestedContents.get(), size);
1321 for (size_t layerId = 0; layerId < contents->numHwLayers; ++layerId) {
1322 auto& layer = contents->hwLayers[layerId];
1323 // Deep copy the regions to avoid double-frees
1324 cloneHWCRegion(layer.visibleRegionScreen);
1325 cloneHWCRegion(layer.surfaceDamage);
1326 }
1327 return HWC1Contents(contents);
1328}
1329
1330void HWC2On1Adapter::Display::setReceivedContents(HWC1Contents contents)
1331{
1332 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1333
1334 mHwc1ReceivedContents = std::move(contents);
1335
1336 mChanges.reset(new Changes);
1337
1338 size_t numLayers = mHwc1ReceivedContents->numHwLayers;
1339 for (size_t hwc1Id = 0; hwc1Id < numLayers; ++hwc1Id) {
1340 const auto& receivedLayer = mHwc1ReceivedContents->hwLayers[hwc1Id];
1341 if (mHwc1LayerMap.count(hwc1Id) == 0) {
1342 ALOGE_IF(receivedLayer.compositionType != HWC_FRAMEBUFFER_TARGET,
1343 "setReceivedContents: HWC1 layer %zd doesn't have a"
1344 " matching HWC2 layer, and isn't the framebuffer target",
1345 hwc1Id);
1346 continue;
1347 }
1348
1349 Layer& layer = *mHwc1LayerMap[hwc1Id];
1350 updateTypeChanges(receivedLayer, layer);
1351 updateLayerRequests(receivedLayer, layer);
1352 }
1353}
1354
1355bool HWC2On1Adapter::Display::hasChanges() const
1356{
1357 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1358 return mChanges != nullptr;
1359}
1360
1361Error HWC2On1Adapter::Display::set(hwc_display_contents_1& hwcContents)
1362{
1363 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1364
1365 if (!mChanges || (mChanges->getNumTypes() > 0)) {
1366 ALOGE("[%" PRIu64 "] set failed: not validated", mId);
1367 return Error::NotValidated;
1368 }
1369
1370 // Set up the client/framebuffer target
1371 auto numLayers = hwcContents.numHwLayers;
1372
1373 // Close acquire fences on FRAMEBUFFER layers, since they will not be used
1374 // by HWC
1375 for (size_t l = 0; l < numLayers - 1; ++l) {
1376 auto& layer = hwcContents.hwLayers[l];
1377 if (layer.compositionType == HWC_FRAMEBUFFER) {
1378 ALOGV("Closing fence %d for layer %zd", layer.acquireFenceFd, l);
1379 close(layer.acquireFenceFd);
1380 layer.acquireFenceFd = -1;
1381 }
1382 }
1383
1384 auto& clientTargetLayer = hwcContents.hwLayers[numLayers - 1];
1385 if (clientTargetLayer.compositionType == HWC_FRAMEBUFFER_TARGET) {
1386 clientTargetLayer.handle = mClientTarget.getBuffer();
1387 clientTargetLayer.acquireFenceFd = mClientTarget.getFence();
1388 } else {
1389 ALOGE("[%" PRIu64 "] set: last HWC layer wasn't FRAMEBUFFER_TARGET",
1390 mId);
1391 }
1392
1393 mChanges.reset();
1394
1395 return Error::None;
1396}
1397
1398void HWC2On1Adapter::Display::addRetireFence(int fenceFd)
1399{
1400 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1401 mRetireFence.add(fenceFd);
1402}
1403
1404void HWC2On1Adapter::Display::addReleaseFences(
1405 const hwc_display_contents_1_t& hwcContents)
1406{
1407 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1408
1409 size_t numLayers = hwcContents.numHwLayers;
1410 for (size_t hwc1Id = 0; hwc1Id < numLayers; ++hwc1Id) {
1411 const auto& receivedLayer = hwcContents.hwLayers[hwc1Id];
1412 if (mHwc1LayerMap.count(hwc1Id) == 0) {
1413 if (receivedLayer.compositionType != HWC_FRAMEBUFFER_TARGET) {
1414 ALOGE("addReleaseFences: HWC1 layer %zd doesn't have a"
1415 " matching HWC2 layer, and isn't the framebuffer"
1416 " target", hwc1Id);
1417 }
1418 // Close the framebuffer target release fence since we will use the
1419 // display retire fence instead
1420 if (receivedLayer.releaseFenceFd != -1) {
1421 close(receivedLayer.releaseFenceFd);
1422 }
1423 continue;
1424 }
1425
1426 Layer& layer = *mHwc1LayerMap[hwc1Id];
1427 ALOGV("Adding release fence %d to layer %" PRIu64,
1428 receivedLayer.releaseFenceFd, layer.getId());
1429 layer.addReleaseFence(receivedLayer.releaseFenceFd);
1430 }
1431}
1432
Dan Stoza5df2a862016-03-24 16:19:37 -07001433bool HWC2On1Adapter::Display::hasColorTransform() const
1434{
1435 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1436 return mHasColorTransform;
1437}
1438
Dan Stozac6998d22015-09-24 17:03:36 -07001439static std::string hwc1CompositionString(int32_t type)
1440{
1441 switch (type) {
1442 case HWC_FRAMEBUFFER: return "Framebuffer";
1443 case HWC_OVERLAY: return "Overlay";
1444 case HWC_BACKGROUND: return "Background";
1445 case HWC_FRAMEBUFFER_TARGET: return "FramebufferTarget";
1446 case HWC_SIDEBAND: return "Sideband";
1447 case HWC_CURSOR_OVERLAY: return "CursorOverlay";
1448 default:
1449 return std::string("Unknown (") + std::to_string(type) + ")";
1450 }
1451}
1452
1453static std::string hwc1TransformString(int32_t transform)
1454{
1455 switch (transform) {
1456 case 0: return "None";
1457 case HWC_TRANSFORM_FLIP_H: return "FlipH";
1458 case HWC_TRANSFORM_FLIP_V: return "FlipV";
1459 case HWC_TRANSFORM_ROT_90: return "Rotate90";
1460 case HWC_TRANSFORM_ROT_180: return "Rotate180";
1461 case HWC_TRANSFORM_ROT_270: return "Rotate270";
1462 case HWC_TRANSFORM_FLIP_H_ROT_90: return "FlipHRotate90";
1463 case HWC_TRANSFORM_FLIP_V_ROT_90: return "FlipVRotate90";
1464 default:
1465 return std::string("Unknown (") + std::to_string(transform) + ")";
1466 }
1467}
1468
1469static std::string hwc1BlendModeString(int32_t mode)
1470{
1471 switch (mode) {
1472 case HWC_BLENDING_NONE: return "None";
1473 case HWC_BLENDING_PREMULT: return "Premultiplied";
1474 case HWC_BLENDING_COVERAGE: return "Coverage";
1475 default:
1476 return std::string("Unknown (") + std::to_string(mode) + ")";
1477 }
1478}
1479
1480static std::string rectString(hwc_rect_t rect)
1481{
1482 std::stringstream output;
1483 output << "[" << rect.left << ", " << rect.top << ", ";
1484 output << rect.right << ", " << rect.bottom << "]";
1485 return output.str();
1486}
1487
1488static std::string approximateFloatString(float f)
1489{
1490 if (static_cast<int32_t>(f) == f) {
1491 return std::to_string(static_cast<int32_t>(f));
1492 }
1493 int32_t truncated = static_cast<int32_t>(f * 10);
1494 bool approximate = (static_cast<float>(truncated) != f * 10);
1495 const size_t BUFFER_SIZE = 32;
1496 char buffer[BUFFER_SIZE] = {};
1497 auto bytesWritten = snprintf(buffer, BUFFER_SIZE,
1498 "%s%.1f", approximate ? "~" : "", f);
1499 return std::string(buffer, bytesWritten);
1500}
1501
1502static std::string frectString(hwc_frect_t frect)
1503{
1504 std::stringstream output;
1505 output << "[" << approximateFloatString(frect.left) << ", ";
1506 output << approximateFloatString(frect.top) << ", ";
1507 output << approximateFloatString(frect.right) << ", ";
1508 output << approximateFloatString(frect.bottom) << "]";
1509 return output.str();
1510}
1511
1512static std::string colorString(hwc_color_t color)
1513{
1514 std::stringstream output;
1515 output << "RGBA [";
1516 output << static_cast<int32_t>(color.r) << ", ";
1517 output << static_cast<int32_t>(color.g) << ", ";
1518 output << static_cast<int32_t>(color.b) << ", ";
1519 output << static_cast<int32_t>(color.a) << "]";
1520 return output.str();
1521}
1522
1523static std::string alphaString(float f)
1524{
1525 const size_t BUFFER_SIZE = 8;
1526 char buffer[BUFFER_SIZE] = {};
1527 auto bytesWritten = snprintf(buffer, BUFFER_SIZE, "%.3f", f);
1528 return std::string(buffer, bytesWritten);
1529}
1530
1531static std::string to_string(const hwc_layer_1_t& hwcLayer,
1532 int32_t hwc1MinorVersion)
1533{
1534 const char* fill = " ";
1535
1536 std::stringstream output;
1537
1538 output << " Composition: " <<
1539 hwc1CompositionString(hwcLayer.compositionType);
1540
1541 if (hwcLayer.compositionType == HWC_BACKGROUND) {
1542 output << " Color: " << colorString(hwcLayer.backgroundColor) << '\n';
1543 } else if (hwcLayer.compositionType == HWC_SIDEBAND) {
1544 output << " Stream: " << hwcLayer.sidebandStream << '\n';
1545 } else {
1546 output << " Buffer: " << hwcLayer.handle << "/" <<
1547 hwcLayer.acquireFenceFd << '\n';
1548 }
1549
1550 output << fill << "Display frame: " << rectString(hwcLayer.displayFrame) <<
1551 '\n';
1552
1553 output << fill << "Source crop: ";
1554 if (hwc1MinorVersion >= 3) {
1555 output << frectString(hwcLayer.sourceCropf) << '\n';
1556 } else {
1557 output << rectString(hwcLayer.sourceCropi) << '\n';
1558 }
1559
1560 output << fill << "Transform: " << hwc1TransformString(hwcLayer.transform);
1561 output << " Blend mode: " << hwc1BlendModeString(hwcLayer.blending);
1562 if (hwcLayer.planeAlpha != 0xFF) {
1563 output << " Alpha: " << alphaString(hwcLayer.planeAlpha / 255.0f);
1564 }
1565 output << '\n';
1566
1567 if (hwcLayer.hints != 0) {
1568 output << fill << "Hints:";
1569 if ((hwcLayer.hints & HWC_HINT_TRIPLE_BUFFER) != 0) {
1570 output << " TripleBuffer";
1571 }
1572 if ((hwcLayer.hints & HWC_HINT_CLEAR_FB) != 0) {
1573 output << " ClearFB";
1574 }
1575 output << '\n';
1576 }
1577
1578 if (hwcLayer.flags != 0) {
1579 output << fill << "Flags:";
1580 if ((hwcLayer.flags & HWC_SKIP_LAYER) != 0) {
1581 output << " SkipLayer";
1582 }
1583 if ((hwcLayer.flags & HWC_IS_CURSOR_LAYER) != 0) {
1584 output << " IsCursorLayer";
1585 }
1586 output << '\n';
1587 }
1588
1589 return output.str();
1590}
1591
1592static std::string to_string(const hwc_display_contents_1_t& hwcContents,
1593 int32_t hwc1MinorVersion)
1594{
1595 const char* fill = " ";
1596
1597 std::stringstream output;
1598 output << fill << "Geometry changed: " <<
1599 ((hwcContents.flags & HWC_GEOMETRY_CHANGED) != 0 ? "Y\n" : "N\n");
1600
1601 output << fill << hwcContents.numHwLayers << " Layer" <<
1602 ((hwcContents.numHwLayers == 1) ? "\n" : "s\n");
1603 for (size_t layer = 0; layer < hwcContents.numHwLayers; ++layer) {
1604 output << fill << " Layer " << layer;
1605 output << to_string(hwcContents.hwLayers[layer], hwc1MinorVersion);
1606 }
1607
1608 if (hwcContents.outbuf != nullptr) {
1609 output << fill << "Output buffer: " << hwcContents.outbuf << "/" <<
1610 hwcContents.outbufAcquireFenceFd << '\n';
1611 }
1612
1613 return output.str();
1614}
1615
1616std::string HWC2On1Adapter::Display::dump() const
1617{
1618 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1619
1620 std::stringstream output;
1621
1622 output << " Display " << mId << ": ";
1623 output << to_string(mType) << " ";
1624 output << "HWC1 ID: " << mHwc1Id << " ";
1625 output << "Power mode: " << to_string(mPowerMode) << " ";
1626 output << "Vsync: " << to_string(mVsyncEnabled) << '\n';
1627
Dan Stoza076ac672016-03-14 10:47:53 -07001628 output << " Color modes [active]:";
1629 for (const auto& mode : mColorModes) {
1630 if (mode == mActiveColorMode) {
1631 output << " [" << mode << ']';
Dan Stozac6998d22015-09-24 17:03:36 -07001632 } else {
Dan Stoza076ac672016-03-14 10:47:53 -07001633 output << " " << mode;
Dan Stozac6998d22015-09-24 17:03:36 -07001634 }
1635 }
1636 output << '\n';
1637
Dan Stoza076ac672016-03-14 10:47:53 -07001638 output << " " << mConfigs.size() << " Config" <<
1639 (mConfigs.size() == 1 ? "" : "s") << " (* active)\n";
1640 for (const auto& config : mConfigs) {
1641 output << (config == mActiveConfig ? " * " : " ");
1642 output << config->toString(true) << '\n';
1643 }
1644
Dan Stozac6998d22015-09-24 17:03:36 -07001645 output << " " << mLayers.size() << " Layer" <<
1646 (mLayers.size() == 1 ? "" : "s") << '\n';
1647 for (const auto& layer : mLayers) {
1648 output << layer->dump();
1649 }
1650
1651 output << " Client target: " << mClientTarget.getBuffer() << '\n';
1652
1653 if (mOutputBuffer.getBuffer() != nullptr) {
1654 output << " Output buffer: " << mOutputBuffer.getBuffer() << '\n';
1655 }
1656
1657 if (mHwc1ReceivedContents) {
1658 output << " Last received HWC1 state\n";
1659 output << to_string(*mHwc1ReceivedContents, mDevice.mHwc1MinorVersion);
1660 } else if (mHwc1RequestedContents) {
1661 output << " Last requested HWC1 state\n";
1662 output << to_string(*mHwc1RequestedContents, mDevice.mHwc1MinorVersion);
1663 }
1664
1665 return output.str();
1666}
1667
1668void HWC2On1Adapter::Display::Config::setAttribute(HWC2::Attribute attribute,
1669 int32_t value)
1670{
1671 mAttributes[attribute] = value;
1672}
1673
1674int32_t HWC2On1Adapter::Display::Config::getAttribute(Attribute attribute) const
1675{
1676 if (mAttributes.count(attribute) == 0) {
1677 return -1;
1678 }
1679 return mAttributes.at(attribute);
1680}
1681
Dan Stoza076ac672016-03-14 10:47:53 -07001682void HWC2On1Adapter::Display::Config::setHwc1Id(uint32_t id)
1683{
Michael Wright28f24d02016-07-12 13:30:53 -07001684 android_color_mode_t colorMode = static_cast<android_color_mode_t>(getAttribute(ColorMode));
1685 mHwc1Ids.emplace(colorMode, id);
Dan Stoza076ac672016-03-14 10:47:53 -07001686}
1687
1688bool HWC2On1Adapter::Display::Config::hasHwc1Id(uint32_t id) const
1689{
1690 for (const auto& idPair : mHwc1Ids) {
1691 if (id == idPair.second) {
1692 return true;
1693 }
1694 }
1695 return false;
1696}
1697
Michael Wright28f24d02016-07-12 13:30:53 -07001698Error HWC2On1Adapter::Display::Config::getColorModeForHwc1Id(
1699 uint32_t id, android_color_mode_t* outMode) const
Dan Stoza076ac672016-03-14 10:47:53 -07001700{
1701 for (const auto& idPair : mHwc1Ids) {
1702 if (id == idPair.second) {
Michael Wright28f24d02016-07-12 13:30:53 -07001703 *outMode = idPair.first;
1704 return Error::None;
Dan Stoza076ac672016-03-14 10:47:53 -07001705 }
1706 }
Michael Wright28f24d02016-07-12 13:30:53 -07001707 ALOGE("Unable to find color mode for HWC ID %" PRIu32 " on config %u", id, mId);
1708 return Error::BadParameter;
Dan Stoza076ac672016-03-14 10:47:53 -07001709}
1710
Michael Wright28f24d02016-07-12 13:30:53 -07001711Error HWC2On1Adapter::Display::Config::getHwc1IdForColorMode(android_color_mode_t mode,
Dan Stoza076ac672016-03-14 10:47:53 -07001712 uint32_t* outId) const
1713{
1714 for (const auto& idPair : mHwc1Ids) {
1715 if (mode == idPair.first) {
1716 *outId = idPair.second;
1717 return Error::None;
1718 }
1719 }
1720 ALOGE("Unable to find HWC1 ID for color mode %d on config %u", mode, mId);
1721 return Error::BadParameter;
1722}
1723
1724bool HWC2On1Adapter::Display::Config::merge(const Config& other)
1725{
1726 auto attributes = {HWC2::Attribute::Width, HWC2::Attribute::Height,
1727 HWC2::Attribute::VsyncPeriod, HWC2::Attribute::DpiX,
1728 HWC2::Attribute::DpiY};
1729 for (auto attribute : attributes) {
1730 if (getAttribute(attribute) != other.getAttribute(attribute)) {
1731 return false;
1732 }
1733 }
Michael Wright28f24d02016-07-12 13:30:53 -07001734 android_color_mode_t otherColorMode =
1735 static_cast<android_color_mode_t>(other.getAttribute(ColorMode));
1736 if (mHwc1Ids.count(otherColorMode) != 0) {
Dan Stoza076ac672016-03-14 10:47:53 -07001737 ALOGE("Attempted to merge two configs (%u and %u) which appear to be "
Michael Wright28f24d02016-07-12 13:30:53 -07001738 "identical", mHwc1Ids.at(otherColorMode),
1739 other.mHwc1Ids.at(otherColorMode));
Dan Stoza076ac672016-03-14 10:47:53 -07001740 return false;
1741 }
Michael Wright28f24d02016-07-12 13:30:53 -07001742 mHwc1Ids.emplace(otherColorMode,
1743 other.mHwc1Ids.at(otherColorMode));
Dan Stoza076ac672016-03-14 10:47:53 -07001744 return true;
1745}
1746
Michael Wright28f24d02016-07-12 13:30:53 -07001747std::set<android_color_mode_t> HWC2On1Adapter::Display::Config::getColorModes() const
Dan Stoza076ac672016-03-14 10:47:53 -07001748{
Michael Wright28f24d02016-07-12 13:30:53 -07001749 std::set<android_color_mode_t> colorModes;
Dan Stoza076ac672016-03-14 10:47:53 -07001750 for (const auto& idPair : mHwc1Ids) {
Michael Wright28f24d02016-07-12 13:30:53 -07001751 colorModes.emplace(idPair.first);
Dan Stoza076ac672016-03-14 10:47:53 -07001752 }
Michael Wright28f24d02016-07-12 13:30:53 -07001753 return colorModes;
Dan Stoza076ac672016-03-14 10:47:53 -07001754}
1755
1756std::string HWC2On1Adapter::Display::Config::toString(bool splitLine) const
Dan Stozac6998d22015-09-24 17:03:36 -07001757{
1758 std::string output;
1759
1760 const size_t BUFFER_SIZE = 100;
1761 char buffer[BUFFER_SIZE] = {};
1762 auto writtenBytes = snprintf(buffer, BUFFER_SIZE,
Dan Stoza076ac672016-03-14 10:47:53 -07001763 "%u x %u", mAttributes.at(HWC2::Attribute::Width),
Dan Stozac6998d22015-09-24 17:03:36 -07001764 mAttributes.at(HWC2::Attribute::Height));
1765 output.append(buffer, writtenBytes);
1766
1767 if (mAttributes.count(HWC2::Attribute::VsyncPeriod) != 0) {
1768 std::memset(buffer, 0, BUFFER_SIZE);
1769 writtenBytes = snprintf(buffer, BUFFER_SIZE, " @ %.1f Hz",
1770 1e9 / mAttributes.at(HWC2::Attribute::VsyncPeriod));
1771 output.append(buffer, writtenBytes);
1772 }
1773
1774 if (mAttributes.count(HWC2::Attribute::DpiX) != 0 &&
1775 mAttributes.at(HWC2::Attribute::DpiX) != -1) {
1776 std::memset(buffer, 0, BUFFER_SIZE);
1777 writtenBytes = snprintf(buffer, BUFFER_SIZE,
1778 ", DPI: %.1f x %.1f",
1779 mAttributes.at(HWC2::Attribute::DpiX) / 1000.0f,
1780 mAttributes.at(HWC2::Attribute::DpiY) / 1000.0f);
1781 output.append(buffer, writtenBytes);
1782 }
1783
Dan Stoza076ac672016-03-14 10:47:53 -07001784 std::memset(buffer, 0, BUFFER_SIZE);
1785 if (splitLine) {
1786 writtenBytes = snprintf(buffer, BUFFER_SIZE,
1787 "\n HWC1 ID/Color transform:");
1788 } else {
1789 writtenBytes = snprintf(buffer, BUFFER_SIZE,
1790 ", HWC1 ID/Color transform:");
1791 }
1792 output.append(buffer, writtenBytes);
1793
1794
1795 for (const auto& id : mHwc1Ids) {
Michael Wright28f24d02016-07-12 13:30:53 -07001796 android_color_mode_t colorMode = id.first;
Dan Stoza076ac672016-03-14 10:47:53 -07001797 uint32_t hwc1Id = id.second;
1798 std::memset(buffer, 0, BUFFER_SIZE);
Michael Wright28f24d02016-07-12 13:30:53 -07001799 if (colorMode == mDisplay.mActiveColorMode) {
Dan Stoza076ac672016-03-14 10:47:53 -07001800 writtenBytes = snprintf(buffer, BUFFER_SIZE, " [%u/%d]", hwc1Id,
Michael Wright28f24d02016-07-12 13:30:53 -07001801 colorMode);
Dan Stoza076ac672016-03-14 10:47:53 -07001802 } else {
1803 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 }
1806 output.append(buffer, writtenBytes);
1807 }
1808
Dan Stozac6998d22015-09-24 17:03:36 -07001809 return output;
1810}
1811
1812std::shared_ptr<const HWC2On1Adapter::Display::Config>
1813 HWC2On1Adapter::Display::getConfig(hwc2_config_t configId) const
1814{
1815 if (configId > mConfigs.size() || !mConfigs[configId]->isOnDisplay(*this)) {
1816 return nullptr;
1817 }
1818 return mConfigs[configId];
1819}
1820
Dan Stoza076ac672016-03-14 10:47:53 -07001821void HWC2On1Adapter::Display::populateColorModes()
1822{
Michael Wright28f24d02016-07-12 13:30:53 -07001823 mColorModes = mConfigs[0]->getColorModes();
Dan Stoza076ac672016-03-14 10:47:53 -07001824 for (const auto& config : mConfigs) {
Michael Wright28f24d02016-07-12 13:30:53 -07001825 std::set<android_color_mode_t> intersection;
1826 auto configModes = config->getColorModes();
Dan Stoza076ac672016-03-14 10:47:53 -07001827 std::set_intersection(mColorModes.cbegin(), mColorModes.cend(),
1828 configModes.cbegin(), configModes.cend(),
1829 std::inserter(intersection, intersection.begin()));
1830 std::swap(intersection, mColorModes);
1831 }
1832}
1833
1834void HWC2On1Adapter::Display::initializeActiveConfig()
1835{
1836 if (mDevice.mHwc1Device->getActiveConfig == nullptr) {
1837 ALOGV("getActiveConfig is null, choosing config 0");
1838 mActiveConfig = mConfigs[0];
Michael Wright28f24d02016-07-12 13:30:53 -07001839 mActiveColorMode = HAL_COLOR_MODE_NATIVE;
Dan Stoza076ac672016-03-14 10:47:53 -07001840 return;
1841 }
1842
1843 auto activeConfig = mDevice.mHwc1Device->getActiveConfig(
1844 mDevice.mHwc1Device, mHwc1Id);
Fabien Sanglardb7432cc2016-11-11 09:40:27 -08001845
1846 // Some devices startup without an activeConfig:
1847 // We need to set one ourselves.
1848 if (activeConfig == HWC_ERROR) {
1849 ALOGV("There is no active configuration: Picking the first one: 0.");
1850 const int defaultIndex = 0;
1851 mDevice.mHwc1Device->setActiveConfig(mDevice.mHwc1Device, mHwc1Id, defaultIndex);
1852 activeConfig = defaultIndex;
1853 }
1854
1855 for (const auto& config : mConfigs) {
1856 if (config->hasHwc1Id(activeConfig)) {
1857 ALOGE("Setting active config to %d for HWC1 config %u", config->getId(), activeConfig);
1858 mActiveConfig = config;
1859 if (config->getColorModeForHwc1Id(activeConfig, &mActiveColorMode) != Error::None) {
1860 // This should never happen since we checked for the config's presence before
1861 // setting it as active.
1862 ALOGE("Unable to find color mode for active HWC1 config %d", config->getId());
1863 mActiveColorMode = HAL_COLOR_MODE_NATIVE;
Dan Stoza076ac672016-03-14 10:47:53 -07001864 }
Fabien Sanglardb7432cc2016-11-11 09:40:27 -08001865 break;
Dan Stoza076ac672016-03-14 10:47:53 -07001866 }
1867 }
Fabien Sanglardb7432cc2016-11-11 09:40:27 -08001868 if (!mActiveConfig) {
1869 ALOGV("Unable to find active HWC1 config %u, defaulting to "
1870 "config 0", activeConfig);
1871 mActiveConfig = mConfigs[0];
1872 mActiveColorMode = HAL_COLOR_MODE_NATIVE;
1873 }
1874
1875
1876
1877
Dan Stoza076ac672016-03-14 10:47:53 -07001878}
1879
Dan Stozac6998d22015-09-24 17:03:36 -07001880void HWC2On1Adapter::Display::reallocateHwc1Contents()
1881{
1882 // Allocate an additional layer for the framebuffer target
1883 auto numLayers = mLayers.size() + 1;
1884 size_t size = sizeof(hwc_display_contents_1_t) +
1885 sizeof(hwc_layer_1_t) * numLayers;
1886 ALOGV("[%" PRIu64 "] reallocateHwc1Contents creating %zd layer%s", mId,
1887 numLayers, numLayers != 1 ? "s" : "");
1888 auto contents =
1889 static_cast<hwc_display_contents_1_t*>(std::calloc(size, 1));
1890 contents->numHwLayers = numLayers;
1891 mHwc1RequestedContents.reset(contents);
1892}
1893
1894void HWC2On1Adapter::Display::assignHwc1LayerIds()
1895{
1896 mHwc1LayerMap.clear();
1897 size_t nextHwc1Id = 0;
1898 for (auto& layer : mLayers) {
1899 mHwc1LayerMap[nextHwc1Id] = layer;
1900 layer->setHwc1Id(nextHwc1Id++);
1901 }
1902}
1903
1904void HWC2On1Adapter::Display::updateTypeChanges(const hwc_layer_1_t& hwc1Layer,
1905 const Layer& layer)
1906{
1907 auto layerId = layer.getId();
1908 switch (hwc1Layer.compositionType) {
1909 case HWC_FRAMEBUFFER:
1910 if (layer.getCompositionType() != Composition::Client) {
1911 mChanges->addTypeChange(layerId, Composition::Client);
1912 }
1913 break;
1914 case HWC_OVERLAY:
1915 if (layer.getCompositionType() != Composition::Device) {
1916 mChanges->addTypeChange(layerId, Composition::Device);
1917 }
1918 break;
1919 case HWC_BACKGROUND:
1920 ALOGE_IF(layer.getCompositionType() != Composition::SolidColor,
1921 "updateTypeChanges: HWC1 requested BACKGROUND, but HWC2"
1922 " wasn't expecting SolidColor");
1923 break;
1924 case HWC_FRAMEBUFFER_TARGET:
1925 // Do nothing, since it shouldn't be modified by HWC1
1926 break;
1927 case HWC_SIDEBAND:
1928 ALOGE_IF(layer.getCompositionType() != Composition::Sideband,
1929 "updateTypeChanges: HWC1 requested SIDEBAND, but HWC2"
1930 " wasn't expecting Sideband");
1931 break;
1932 case HWC_CURSOR_OVERLAY:
1933 ALOGE_IF(layer.getCompositionType() != Composition::Cursor,
1934 "updateTypeChanges: HWC1 requested CURSOR_OVERLAY, but"
1935 " HWC2 wasn't expecting Cursor");
1936 break;
1937 }
1938}
1939
1940void HWC2On1Adapter::Display::updateLayerRequests(
1941 const hwc_layer_1_t& hwc1Layer, const Layer& layer)
1942{
1943 if ((hwc1Layer.hints & HWC_HINT_CLEAR_FB) != 0) {
1944 mChanges->addLayerRequest(layer.getId(),
1945 LayerRequest::ClearClientTarget);
1946 }
1947}
1948
1949void HWC2On1Adapter::Display::prepareFramebufferTarget()
1950{
1951 // We check that mActiveConfig is valid in Display::prepare
1952 int32_t width = mActiveConfig->getAttribute(Attribute::Width);
1953 int32_t height = mActiveConfig->getAttribute(Attribute::Height);
1954
1955 auto& hwc1Target = mHwc1RequestedContents->hwLayers[mLayers.size()];
1956 hwc1Target.compositionType = HWC_FRAMEBUFFER_TARGET;
1957 hwc1Target.releaseFenceFd = -1;
1958 hwc1Target.hints = 0;
1959 hwc1Target.flags = 0;
1960 hwc1Target.transform = 0;
1961 hwc1Target.blending = HWC_BLENDING_PREMULT;
1962 if (mDevice.getHwc1MinorVersion() < 3) {
1963 hwc1Target.sourceCropi = {0, 0, width, height};
1964 } else {
1965 hwc1Target.sourceCropf = {0.0f, 0.0f, static_cast<float>(width),
1966 static_cast<float>(height)};
1967 }
1968 hwc1Target.displayFrame = {0, 0, width, height};
1969 hwc1Target.planeAlpha = 255;
1970 hwc1Target.visibleRegionScreen.numRects = 1;
1971 auto rects = static_cast<hwc_rect_t*>(std::malloc(sizeof(hwc_rect_t)));
1972 rects[0].left = 0;
1973 rects[0].top = 0;
1974 rects[0].right = width;
1975 rects[0].bottom = height;
1976 hwc1Target.visibleRegionScreen.rects = rects;
1977
1978 // We will set this to the correct value in set
1979 hwc1Target.acquireFenceFd = -1;
1980}
1981
1982// Layer functions
1983
1984std::atomic<hwc2_layer_t> HWC2On1Adapter::Layer::sNextId(1);
1985
1986HWC2On1Adapter::Layer::Layer(Display& display)
1987 : mId(sNextId++),
1988 mDisplay(display),
Dan Stozafc4e2022016-02-23 11:43:19 -08001989 mDirtyCount(0),
1990 mBuffer(),
1991 mSurfaceDamage(),
Dan Stozac6998d22015-09-24 17:03:36 -07001992 mBlendMode(*this, BlendMode::None),
1993 mColor(*this, {0, 0, 0, 0}),
1994 mCompositionType(*this, Composition::Invalid),
1995 mDisplayFrame(*this, {0, 0, -1, -1}),
1996 mPlaneAlpha(*this, 0.0f),
1997 mSidebandStream(*this, nullptr),
1998 mSourceCrop(*this, {0.0f, 0.0f, -1.0f, -1.0f}),
1999 mTransform(*this, Transform::None),
2000 mVisibleRegion(*this, std::vector<hwc_rect_t>()),
2001 mZ(0),
Dan Stozafc4e2022016-02-23 11:43:19 -08002002 mReleaseFence(),
Dan Stozac6998d22015-09-24 17:03:36 -07002003 mHwc1Id(0),
Dan Stoza5df2a862016-03-24 16:19:37 -07002004 mHasUnsupportedDataspace(false),
Dan Stozac6998d22015-09-24 17:03:36 -07002005 mHasUnsupportedPlaneAlpha(false) {}
2006
2007bool HWC2On1Adapter::SortLayersByZ::operator()(
2008 const std::shared_ptr<Layer>& lhs, const std::shared_ptr<Layer>& rhs)
2009{
2010 return lhs->getZ() < rhs->getZ();
2011}
2012
2013Error HWC2On1Adapter::Layer::setBuffer(buffer_handle_t buffer,
2014 int32_t acquireFence)
2015{
2016 ALOGV("Setting acquireFence to %d for layer %" PRIu64, acquireFence, mId);
2017 mBuffer.setBuffer(buffer);
2018 mBuffer.setFence(acquireFence);
2019 return Error::None;
2020}
2021
2022Error HWC2On1Adapter::Layer::setCursorPosition(int32_t x, int32_t y)
2023{
2024 if (mCompositionType.getValue() != Composition::Cursor) {
2025 return Error::BadLayer;
2026 }
2027
2028 if (mDisplay.hasChanges()) {
2029 return Error::NotValidated;
2030 }
2031
2032 auto displayId = mDisplay.getHwc1Id();
2033 auto hwc1Device = mDisplay.getDevice().getHwc1Device();
2034 hwc1Device->setCursorPositionAsync(hwc1Device, displayId, x, y);
2035 return Error::None;
2036}
2037
2038Error HWC2On1Adapter::Layer::setSurfaceDamage(hwc_region_t damage)
2039{
2040 mSurfaceDamage.resize(damage.numRects);
2041 std::copy_n(damage.rects, damage.numRects, mSurfaceDamage.begin());
2042 return Error::None;
2043}
2044
2045// Layer state functions
2046
2047Error HWC2On1Adapter::Layer::setBlendMode(BlendMode mode)
2048{
2049 mBlendMode.setPending(mode);
2050 return Error::None;
2051}
2052
2053Error HWC2On1Adapter::Layer::setColor(hwc_color_t color)
2054{
2055 mColor.setPending(color);
2056 return Error::None;
2057}
2058
2059Error HWC2On1Adapter::Layer::setCompositionType(Composition type)
2060{
2061 mCompositionType.setPending(type);
2062 return Error::None;
2063}
2064
Dan Stoza5df2a862016-03-24 16:19:37 -07002065Error HWC2On1Adapter::Layer::setDataspace(android_dataspace_t dataspace)
2066{
2067 mHasUnsupportedDataspace = (dataspace != HAL_DATASPACE_UNKNOWN);
2068 return Error::None;
2069}
2070
Dan Stozac6998d22015-09-24 17:03:36 -07002071Error HWC2On1Adapter::Layer::setDisplayFrame(hwc_rect_t frame)
2072{
2073 mDisplayFrame.setPending(frame);
2074 return Error::None;
2075}
2076
2077Error HWC2On1Adapter::Layer::setPlaneAlpha(float alpha)
2078{
2079 mPlaneAlpha.setPending(alpha);
2080 return Error::None;
2081}
2082
2083Error HWC2On1Adapter::Layer::setSidebandStream(const native_handle_t* stream)
2084{
2085 mSidebandStream.setPending(stream);
2086 return Error::None;
2087}
2088
2089Error HWC2On1Adapter::Layer::setSourceCrop(hwc_frect_t crop)
2090{
2091 mSourceCrop.setPending(crop);
2092 return Error::None;
2093}
2094
2095Error HWC2On1Adapter::Layer::setTransform(Transform transform)
2096{
2097 mTransform.setPending(transform);
2098 return Error::None;
2099}
2100
2101Error HWC2On1Adapter::Layer::setVisibleRegion(hwc_region_t rawVisible)
2102{
2103 std::vector<hwc_rect_t> visible(rawVisible.rects,
2104 rawVisible.rects + rawVisible.numRects);
2105 mVisibleRegion.setPending(std::move(visible));
2106 return Error::None;
2107}
2108
2109Error HWC2On1Adapter::Layer::setZ(uint32_t z)
2110{
2111 mZ = z;
2112 return Error::None;
2113}
2114
2115void HWC2On1Adapter::Layer::addReleaseFence(int fenceFd)
2116{
2117 ALOGV("addReleaseFence %d to layer %" PRIu64, fenceFd, mId);
2118 mReleaseFence.add(fenceFd);
2119}
2120
2121const sp<Fence>& HWC2On1Adapter::Layer::getReleaseFence() const
2122{
2123 return mReleaseFence.get();
2124}
2125
2126void HWC2On1Adapter::Layer::applyState(hwc_layer_1_t& hwc1Layer,
2127 bool applyAllState)
2128{
2129 applyCommonState(hwc1Layer, applyAllState);
2130 auto compositionType = mCompositionType.getPendingValue();
2131 if (compositionType == Composition::SolidColor) {
2132 applySolidColorState(hwc1Layer, applyAllState);
2133 } else if (compositionType == Composition::Sideband) {
2134 applySidebandState(hwc1Layer, applyAllState);
2135 } else {
2136 applyBufferState(hwc1Layer);
2137 }
2138 applyCompositionType(hwc1Layer, applyAllState);
2139}
2140
2141// Layer dump helpers
2142
2143static std::string regionStrings(const std::vector<hwc_rect_t>& visibleRegion,
2144 const std::vector<hwc_rect_t>& surfaceDamage)
2145{
2146 std::string regions;
2147 regions += " Visible Region";
2148 regions.resize(40, ' ');
2149 regions += "Surface Damage\n";
2150
2151 size_t numPrinted = 0;
2152 size_t maxSize = std::max(visibleRegion.size(), surfaceDamage.size());
2153 while (numPrinted < maxSize) {
2154 std::string line(" ");
2155 if (visibleRegion.empty() && numPrinted == 0) {
2156 line += "None";
2157 } else if (numPrinted < visibleRegion.size()) {
2158 line += rectString(visibleRegion[numPrinted]);
2159 }
2160 line.resize(40, ' ');
2161 if (surfaceDamage.empty() && numPrinted == 0) {
2162 line += "None";
2163 } else if (numPrinted < surfaceDamage.size()) {
2164 line += rectString(surfaceDamage[numPrinted]);
2165 }
2166 line += '\n';
2167 regions += line;
2168 ++numPrinted;
2169 }
2170 return regions;
2171}
2172
2173std::string HWC2On1Adapter::Layer::dump() const
2174{
2175 std::stringstream output;
2176 const char* fill = " ";
2177
2178 output << fill << to_string(mCompositionType.getPendingValue());
2179 output << " Layer HWC2/1: " << mId << "/" << mHwc1Id << " ";
2180 output << "Z: " << mZ;
2181 if (mCompositionType.getValue() == HWC2::Composition::SolidColor) {
2182 output << " " << colorString(mColor.getValue());
2183 } else if (mCompositionType.getValue() == HWC2::Composition::Sideband) {
2184 output << " Handle: " << mSidebandStream.getValue() << '\n';
2185 } else {
2186 output << " Buffer: " << mBuffer.getBuffer() << "/" <<
2187 mBuffer.getFence() << '\n';
2188 output << fill << " Display frame [LTRB]: " <<
2189 rectString(mDisplayFrame.getValue()) << '\n';
2190 output << fill << " Source crop: " <<
2191 frectString(mSourceCrop.getValue()) << '\n';
2192 output << fill << " Transform: " << to_string(mTransform.getValue());
2193 output << " Blend mode: " << to_string(mBlendMode.getValue());
2194 if (mPlaneAlpha.getValue() != 1.0f) {
2195 output << " Alpha: " <<
2196 alphaString(mPlaneAlpha.getValue()) << '\n';
2197 } else {
2198 output << '\n';
2199 }
2200 output << regionStrings(mVisibleRegion.getValue(), mSurfaceDamage);
2201 }
2202 return output.str();
2203}
2204
2205static int getHwc1Blending(HWC2::BlendMode blendMode)
2206{
2207 switch (blendMode) {
2208 case BlendMode::Coverage: return HWC_BLENDING_COVERAGE;
2209 case BlendMode::Premultiplied: return HWC_BLENDING_PREMULT;
2210 default: return HWC_BLENDING_NONE;
2211 }
2212}
2213
2214void HWC2On1Adapter::Layer::applyCommonState(hwc_layer_1_t& hwc1Layer,
2215 bool applyAllState)
2216{
2217 auto minorVersion = mDisplay.getDevice().getHwc1MinorVersion();
2218 if (applyAllState || mBlendMode.isDirty()) {
2219 hwc1Layer.blending = getHwc1Blending(mBlendMode.getPendingValue());
2220 mBlendMode.latch();
2221 }
2222 if (applyAllState || mDisplayFrame.isDirty()) {
2223 hwc1Layer.displayFrame = mDisplayFrame.getPendingValue();
2224 mDisplayFrame.latch();
2225 }
2226 if (applyAllState || mPlaneAlpha.isDirty()) {
2227 auto pendingAlpha = mPlaneAlpha.getPendingValue();
2228 if (minorVersion < 2) {
2229 mHasUnsupportedPlaneAlpha = pendingAlpha < 1.0f;
2230 } else {
2231 hwc1Layer.planeAlpha =
2232 static_cast<uint8_t>(255.0f * pendingAlpha + 0.5f);
2233 }
2234 mPlaneAlpha.latch();
2235 }
2236 if (applyAllState || mSourceCrop.isDirty()) {
2237 if (minorVersion < 3) {
2238 auto pending = mSourceCrop.getPendingValue();
2239 hwc1Layer.sourceCropi.left =
2240 static_cast<int32_t>(std::ceil(pending.left));
2241 hwc1Layer.sourceCropi.top =
2242 static_cast<int32_t>(std::ceil(pending.top));
2243 hwc1Layer.sourceCropi.right =
2244 static_cast<int32_t>(std::floor(pending.right));
2245 hwc1Layer.sourceCropi.bottom =
2246 static_cast<int32_t>(std::floor(pending.bottom));
2247 } else {
2248 hwc1Layer.sourceCropf = mSourceCrop.getPendingValue();
2249 }
2250 mSourceCrop.latch();
2251 }
2252 if (applyAllState || mTransform.isDirty()) {
2253 hwc1Layer.transform =
2254 static_cast<uint32_t>(mTransform.getPendingValue());
2255 mTransform.latch();
2256 }
2257 if (applyAllState || mVisibleRegion.isDirty()) {
2258 auto& hwc1VisibleRegion = hwc1Layer.visibleRegionScreen;
2259
2260 std::free(const_cast<hwc_rect_t*>(hwc1VisibleRegion.rects));
2261
2262 auto pending = mVisibleRegion.getPendingValue();
2263 hwc_rect_t* newRects = static_cast<hwc_rect_t*>(
2264 std::malloc(sizeof(hwc_rect_t) * pending.size()));
2265 std::copy(pending.begin(), pending.end(), newRects);
2266 hwc1VisibleRegion.rects = const_cast<const hwc_rect_t*>(newRects);
2267 hwc1VisibleRegion.numRects = pending.size();
2268 mVisibleRegion.latch();
2269 }
2270}
2271
2272void HWC2On1Adapter::Layer::applySolidColorState(hwc_layer_1_t& hwc1Layer,
2273 bool applyAllState)
2274{
2275 if (applyAllState || mColor.isDirty()) {
Fabien Sanglardeb3db612016-11-18 16:12:31 -08002276 // If the device does not support background color it is likely to make
2277 // assumption regarding backgroundColor and handle (both fields occupy
2278 // the same location in hwc_layer_1_t union).
2279 // To not confuse these devices we don't set background color and we
2280 // make sure handle is a null pointer.
2281 if (mDisplay.getDevice().supportsBackgroundColor()) {
2282 hwc1Layer.backgroundColor = mColor.getPendingValue();
2283 mHasUnsupportedBackgroundColor = false;
2284 } else {
2285 hwc1Layer.handle = nullptr;
2286 mHasUnsupportedBackgroundColor = true;
2287 }
Dan Stozac6998d22015-09-24 17:03:36 -07002288 mColor.latch();
2289 }
2290}
2291
2292void HWC2On1Adapter::Layer::applySidebandState(hwc_layer_1_t& hwc1Layer,
2293 bool applyAllState)
2294{
2295 if (applyAllState || mSidebandStream.isDirty()) {
2296 hwc1Layer.sidebandStream = mSidebandStream.getPendingValue();
2297 mSidebandStream.latch();
2298 }
2299}
2300
2301void HWC2On1Adapter::Layer::applyBufferState(hwc_layer_1_t& hwc1Layer)
2302{
2303 hwc1Layer.handle = mBuffer.getBuffer();
2304 hwc1Layer.acquireFenceFd = mBuffer.getFence();
2305}
2306
2307void HWC2On1Adapter::Layer::applyCompositionType(hwc_layer_1_t& hwc1Layer,
2308 bool applyAllState)
2309{
Dan Stoza5df2a862016-03-24 16:19:37 -07002310 // HWC1 never supports color transforms or dataspaces and only sometimes
2311 // supports plane alpha (depending on the version). These require us to drop
2312 // some or all layers to client composition.
2313 if (mHasUnsupportedDataspace || mHasUnsupportedPlaneAlpha ||
Fabien Sanglardeb3db612016-11-18 16:12:31 -08002314 mDisplay.hasColorTransform() || mHasUnsupportedBackgroundColor) {
Dan Stozac6998d22015-09-24 17:03:36 -07002315 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2316 hwc1Layer.flags = HWC_SKIP_LAYER;
2317 return;
2318 }
2319
2320 if (applyAllState || mCompositionType.isDirty()) {
2321 hwc1Layer.flags = 0;
2322 switch (mCompositionType.getPendingValue()) {
2323 case Composition::Client:
2324 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2325 hwc1Layer.flags |= HWC_SKIP_LAYER;
2326 break;
2327 case Composition::Device:
2328 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2329 break;
2330 case Composition::SolidColor:
Dan Stoza5df47cb2016-09-15 16:38:42 -07002331 // In theory the following line should work, but since the HWC1
2332 // version of SurfaceFlinger never used HWC_BACKGROUND, HWC1
2333 // devices may not work correctly. To be on the safe side, we
2334 // fall back to client composition.
2335 //
2336 // hwc1Layer.compositionType = HWC_BACKGROUND;
2337 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2338 hwc1Layer.flags |= HWC_SKIP_LAYER;
Dan Stozac6998d22015-09-24 17:03:36 -07002339 break;
2340 case Composition::Cursor:
2341 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2342 if (mDisplay.getDevice().getHwc1MinorVersion() >= 4) {
2343 hwc1Layer.hints |= HWC_IS_CURSOR_LAYER;
2344 }
2345 break;
2346 case Composition::Sideband:
2347 if (mDisplay.getDevice().getHwc1MinorVersion() < 4) {
2348 hwc1Layer.compositionType = HWC_SIDEBAND;
2349 } else {
2350 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2351 hwc1Layer.flags |= HWC_SKIP_LAYER;
2352 }
2353 break;
2354 default:
2355 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2356 hwc1Layer.flags |= HWC_SKIP_LAYER;
2357 break;
2358 }
2359 ALOGV("Layer %" PRIu64 " %s set to %d", mId,
2360 to_string(mCompositionType.getPendingValue()).c_str(),
2361 hwc1Layer.compositionType);
2362 ALOGV_IF(hwc1Layer.flags & HWC_SKIP_LAYER, " and skipping");
2363 mCompositionType.latch();
2364 }
2365}
2366
2367// Adapter helpers
2368
2369void HWC2On1Adapter::populateCapabilities()
2370{
2371 ALOGV("populateCapabilities");
2372 if (mHwc1MinorVersion >= 3U) {
2373 int supportedTypes = 0;
2374 auto result = mHwc1Device->query(mHwc1Device,
2375 HWC_DISPLAY_TYPES_SUPPORTED, &supportedTypes);
Fred Fettingerc50c01e2016-06-14 17:53:10 -05002376 if ((result == 0) && ((supportedTypes & HWC_DISPLAY_VIRTUAL_BIT) != 0)) {
Dan Stozac6998d22015-09-24 17:03:36 -07002377 ALOGI("Found support for HWC virtual displays");
2378 mHwc1SupportsVirtualDisplays = true;
2379 }
2380 }
2381 if (mHwc1MinorVersion >= 4U) {
2382 mCapabilities.insert(Capability::SidebandStream);
2383 }
Fabien Sanglardeb3db612016-11-18 16:12:31 -08002384
2385 // Check for HWC background color layer support.
2386 if (mHwc1MinorVersion >= 1U) {
2387 int backgroundColorSupported = 0;
2388 auto result = mHwc1Device->query(mHwc1Device,
2389 HWC_BACKGROUND_LAYER_SUPPORTED,
2390 &backgroundColorSupported);
2391 if ((result == 0) && (backgroundColorSupported == 1)) {
2392 ALOGV("Found support for HWC background color");
2393 mHwc1SupportsBackgroundColor = true;
2394 }
2395 }
Dan Stozac6998d22015-09-24 17:03:36 -07002396}
2397
2398HWC2On1Adapter::Display* HWC2On1Adapter::getDisplay(hwc2_display_t id)
2399{
Dan Stozafc4e2022016-02-23 11:43:19 -08002400 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002401
2402 auto display = mDisplays.find(id);
2403 if (display == mDisplays.end()) {
2404 return nullptr;
2405 }
2406
2407 return display->second.get();
2408}
2409
2410std::tuple<HWC2On1Adapter::Layer*, Error> HWC2On1Adapter::getLayer(
2411 hwc2_display_t displayId, hwc2_layer_t layerId)
2412{
2413 auto display = getDisplay(displayId);
2414 if (!display) {
2415 return std::make_tuple(static_cast<Layer*>(nullptr), Error::BadDisplay);
2416 }
2417
2418 auto layerEntry = mLayers.find(layerId);
2419 if (layerEntry == mLayers.end()) {
2420 return std::make_tuple(static_cast<Layer*>(nullptr), Error::BadLayer);
2421 }
2422
2423 auto layer = layerEntry->second;
2424 if (layer->getDisplay().getId() != displayId) {
2425 return std::make_tuple(static_cast<Layer*>(nullptr), Error::BadLayer);
2426 }
2427 return std::make_tuple(layer.get(), Error::None);
2428}
2429
2430void HWC2On1Adapter::populatePrimary()
2431{
2432 ALOGV("populatePrimary");
2433
Dan Stozafc4e2022016-02-23 11:43:19 -08002434 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002435
2436 auto display =
2437 std::make_shared<Display>(*this, HWC2::DisplayType::Physical);
2438 mHwc1DisplayMap[HWC_DISPLAY_PRIMARY] = display->getId();
2439 display->setHwc1Id(HWC_DISPLAY_PRIMARY);
2440 display->populateConfigs();
2441 mDisplays.emplace(display->getId(), std::move(display));
2442}
2443
2444bool HWC2On1Adapter::prepareAllDisplays()
2445{
2446 ATRACE_CALL();
2447
Dan Stozafc4e2022016-02-23 11:43:19 -08002448 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002449
2450 for (const auto& displayPair : mDisplays) {
2451 auto& display = displayPair.second;
2452 if (!display->prepare()) {
2453 return false;
2454 }
2455 }
2456
2457 if (mHwc1DisplayMap.count(0) == 0) {
2458 ALOGE("prepareAllDisplays: Unable to find primary HWC1 display");
2459 return false;
2460 }
2461
2462 // Always push the primary display
2463 std::vector<HWC2On1Adapter::Display::HWC1Contents> requestedContents;
2464 auto primaryDisplayId = mHwc1DisplayMap[HWC_DISPLAY_PRIMARY];
2465 auto& primaryDisplay = mDisplays[primaryDisplayId];
2466 auto primaryDisplayContents = primaryDisplay->cloneRequestedContents();
2467 requestedContents.push_back(std::move(primaryDisplayContents));
2468
2469 // Push the external display, if present
2470 if (mHwc1DisplayMap.count(HWC_DISPLAY_EXTERNAL) != 0) {
2471 auto externalDisplayId = mHwc1DisplayMap[HWC_DISPLAY_EXTERNAL];
2472 auto& externalDisplay = mDisplays[externalDisplayId];
2473 auto externalDisplayContents =
2474 externalDisplay->cloneRequestedContents();
2475 requestedContents.push_back(std::move(externalDisplayContents));
2476 } else {
2477 // Even if an external display isn't present, we still need to send
2478 // at least two displays down to HWC1
2479 requestedContents.push_back(nullptr);
2480 }
2481
2482 // Push the hardware virtual display, if supported and present
2483 if (mHwc1MinorVersion >= 3) {
2484 if (mHwc1DisplayMap.count(HWC_DISPLAY_VIRTUAL) != 0) {
2485 auto virtualDisplayId = mHwc1DisplayMap[HWC_DISPLAY_VIRTUAL];
2486 auto& virtualDisplay = mDisplays[virtualDisplayId];
2487 auto virtualDisplayContents =
2488 virtualDisplay->cloneRequestedContents();
2489 requestedContents.push_back(std::move(virtualDisplayContents));
2490 } else {
2491 requestedContents.push_back(nullptr);
2492 }
2493 }
2494
2495 mHwc1Contents.clear();
2496 for (auto& displayContents : requestedContents) {
2497 mHwc1Contents.push_back(displayContents.get());
2498 if (!displayContents) {
2499 continue;
2500 }
2501
2502 ALOGV("Display %zd layers:", mHwc1Contents.size() - 1);
2503 for (size_t l = 0; l < displayContents->numHwLayers; ++l) {
2504 auto& layer = displayContents->hwLayers[l];
2505 ALOGV(" %zd: %d", l, layer.compositionType);
2506 }
2507 }
2508
2509 ALOGV("Calling HWC1 prepare");
2510 {
2511 ATRACE_NAME("HWC1 prepare");
2512 mHwc1Device->prepare(mHwc1Device, mHwc1Contents.size(),
2513 mHwc1Contents.data());
2514 }
2515
2516 for (size_t c = 0; c < mHwc1Contents.size(); ++c) {
2517 auto& contents = mHwc1Contents[c];
2518 if (!contents) {
2519 continue;
2520 }
2521 ALOGV("Display %zd layers:", c);
2522 for (size_t l = 0; l < contents->numHwLayers; ++l) {
2523 ALOGV(" %zd: %d", l, contents->hwLayers[l].compositionType);
2524 }
2525 }
2526
2527 // Return the received contents to their respective displays
2528 for (size_t hwc1Id = 0; hwc1Id < mHwc1Contents.size(); ++hwc1Id) {
2529 if (mHwc1Contents[hwc1Id] == nullptr) {
2530 continue;
2531 }
2532
2533 auto displayId = mHwc1DisplayMap[hwc1Id];
2534 auto& display = mDisplays[displayId];
2535 display->setReceivedContents(std::move(requestedContents[hwc1Id]));
2536 }
2537
2538 return true;
2539}
2540
2541Error HWC2On1Adapter::setAllDisplays()
2542{
2543 ATRACE_CALL();
2544
Dan Stozafc4e2022016-02-23 11:43:19 -08002545 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002546
2547 // Make sure we're ready to validate
2548 for (size_t hwc1Id = 0; hwc1Id < mHwc1Contents.size(); ++hwc1Id) {
2549 if (mHwc1Contents[hwc1Id] == nullptr) {
2550 continue;
2551 }
2552
2553 auto displayId = mHwc1DisplayMap[hwc1Id];
2554 auto& display = mDisplays[displayId];
2555 Error error = display->set(*mHwc1Contents[hwc1Id]);
2556 if (error != Error::None) {
2557 ALOGE("setAllDisplays: Failed to set display %zd: %s", hwc1Id,
2558 to_string(error).c_str());
2559 return error;
2560 }
2561 }
2562
2563 ALOGV("Calling HWC1 set");
2564 {
2565 ATRACE_NAME("HWC1 set");
2566 mHwc1Device->set(mHwc1Device, mHwc1Contents.size(),
2567 mHwc1Contents.data());
2568 }
2569
2570 // Add retire and release fences
2571 for (size_t hwc1Id = 0; hwc1Id < mHwc1Contents.size(); ++hwc1Id) {
2572 if (mHwc1Contents[hwc1Id] == nullptr) {
2573 continue;
2574 }
2575
2576 auto displayId = mHwc1DisplayMap[hwc1Id];
2577 auto& display = mDisplays[displayId];
2578 auto retireFenceFd = mHwc1Contents[hwc1Id]->retireFenceFd;
2579 ALOGV("setAllDisplays: Adding retire fence %d to display %zd",
2580 retireFenceFd, hwc1Id);
2581 display->addRetireFence(mHwc1Contents[hwc1Id]->retireFenceFd);
2582 display->addReleaseFences(*mHwc1Contents[hwc1Id]);
2583 }
2584
2585 return Error::None;
2586}
2587
2588void HWC2On1Adapter::hwc1Invalidate()
2589{
2590 ALOGV("Received hwc1Invalidate");
2591
Dan Stozafc4e2022016-02-23 11:43:19 -08002592 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002593
2594 // If the HWC2-side callback hasn't been registered yet, buffer this until
2595 // it is registered
2596 if (mCallbacks.count(Callback::Refresh) == 0) {
2597 mHasPendingInvalidate = true;
2598 return;
2599 }
2600
2601 const auto& callbackInfo = mCallbacks[Callback::Refresh];
2602 std::vector<hwc2_display_t> displays;
2603 for (const auto& displayPair : mDisplays) {
2604 displays.emplace_back(displayPair.first);
2605 }
2606
2607 // Call back without the state lock held
2608 lock.unlock();
2609
2610 auto refresh = reinterpret_cast<HWC2_PFN_REFRESH>(callbackInfo.pointer);
2611 for (auto display : displays) {
2612 refresh(callbackInfo.data, display);
2613 }
2614}
2615
2616void HWC2On1Adapter::hwc1Vsync(int hwc1DisplayId, int64_t timestamp)
2617{
2618 ALOGV("Received hwc1Vsync(%d, %" PRId64 ")", hwc1DisplayId, timestamp);
2619
Dan Stozafc4e2022016-02-23 11:43:19 -08002620 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002621
2622 // If the HWC2-side callback hasn't been registered yet, buffer this until
2623 // it is registered
2624 if (mCallbacks.count(Callback::Vsync) == 0) {
2625 mPendingVsyncs.emplace_back(hwc1DisplayId, timestamp);
2626 return;
2627 }
2628
2629 if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) {
2630 ALOGE("hwc1Vsync: Couldn't find display for HWC1 id %d", hwc1DisplayId);
2631 return;
2632 }
2633
2634 const auto& callbackInfo = mCallbacks[Callback::Vsync];
2635 auto displayId = mHwc1DisplayMap[hwc1DisplayId];
2636
2637 // Call back without the state lock held
2638 lock.unlock();
2639
2640 auto vsync = reinterpret_cast<HWC2_PFN_VSYNC>(callbackInfo.pointer);
2641 vsync(callbackInfo.data, displayId, timestamp);
2642}
2643
2644void HWC2On1Adapter::hwc1Hotplug(int hwc1DisplayId, int connected)
2645{
2646 ALOGV("Received hwc1Hotplug(%d, %d)", hwc1DisplayId, connected);
2647
2648 if (hwc1DisplayId != HWC_DISPLAY_EXTERNAL) {
2649 ALOGE("hwc1Hotplug: Received hotplug for non-external display");
2650 return;
2651 }
2652
Dan Stozafc4e2022016-02-23 11:43:19 -08002653 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002654
2655 // If the HWC2-side callback hasn't been registered yet, buffer this until
2656 // it is registered
2657 if (mCallbacks.count(Callback::Hotplug) == 0) {
2658 mPendingHotplugs.emplace_back(hwc1DisplayId, connected);
2659 return;
2660 }
2661
2662 hwc2_display_t displayId = UINT64_MAX;
2663 if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) {
2664 if (connected == 0) {
2665 ALOGW("hwc1Hotplug: Received disconnect for unconnected display");
2666 return;
2667 }
2668
2669 // Create a new display on connect
2670 auto display = std::make_shared<HWC2On1Adapter::Display>(*this,
2671 HWC2::DisplayType::Physical);
2672 display->setHwc1Id(HWC_DISPLAY_EXTERNAL);
2673 display->populateConfigs();
2674 displayId = display->getId();
2675 mHwc1DisplayMap[HWC_DISPLAY_EXTERNAL] = displayId;
2676 mDisplays.emplace(displayId, std::move(display));
2677 } else {
2678 if (connected != 0) {
2679 ALOGW("hwc1Hotplug: Received connect for previously connected "
2680 "display");
2681 return;
2682 }
2683
2684 // Disconnect an existing display
2685 displayId = mHwc1DisplayMap[hwc1DisplayId];
2686 mHwc1DisplayMap.erase(HWC_DISPLAY_EXTERNAL);
2687 mDisplays.erase(displayId);
2688 }
2689
2690 const auto& callbackInfo = mCallbacks[Callback::Hotplug];
2691
2692 // Call back without the state lock held
2693 lock.unlock();
2694
2695 auto hotplug = reinterpret_cast<HWC2_PFN_HOTPLUG>(callbackInfo.pointer);
2696 auto hwc2Connected = (connected == 0) ?
2697 HWC2::Connection::Disconnected : HWC2::Connection::Connected;
2698 hotplug(callbackInfo.data, displayId, static_cast<int32_t>(hwc2Connected));
2699}
2700
2701} // namespace android