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