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