blob: dabc77fb097d78a72fadde60c805e6e2be9d216b [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
78namespace android {
79
80void HWC2On1Adapter::DisplayContentsDeleter::operator()(
81 hwc_display_contents_1_t* contents)
82{
83 if (contents != nullptr) {
84 for (size_t l = 0; l < contents->numHwLayers; ++l) {
85 auto& layer = contents->hwLayers[l];
86 std::free(const_cast<hwc_rect_t*>(layer.visibleRegionScreen.rects));
87 }
88 }
89 std::free(contents);
90}
91
92class HWC2On1Adapter::Callbacks : public hwc_procs_t {
93 public:
94 Callbacks(HWC2On1Adapter& adapter) : mAdapter(adapter) {
95 invalidate = &invalidateHook;
96 vsync = &vsyncHook;
97 hotplug = &hotplugHook;
98 }
99
100 static void invalidateHook(const hwc_procs_t* procs) {
101 auto callbacks = static_cast<const Callbacks*>(procs);
102 callbacks->mAdapter.hwc1Invalidate();
103 }
104
105 static void vsyncHook(const hwc_procs_t* procs, int display,
106 int64_t timestamp) {
107 auto callbacks = static_cast<const Callbacks*>(procs);
108 callbacks->mAdapter.hwc1Vsync(display, timestamp);
109 }
110
111 static void hotplugHook(const hwc_procs_t* procs, int display,
112 int connected) {
113 auto callbacks = static_cast<const Callbacks*>(procs);
114 callbacks->mAdapter.hwc1Hotplug(display, connected);
115 }
116
117 private:
118 HWC2On1Adapter& mAdapter;
119};
120
121static int closeHook(hw_device_t* /*device*/)
122{
123 // Do nothing, since the real work is done in the class destructor, but we
124 // need to provide a valid function pointer for hwc2_close to call
125 return 0;
126}
127
128HWC2On1Adapter::HWC2On1Adapter(hwc_composer_device_1_t* hwc1Device)
129 : mDumpString(),
130 mHwc1Device(hwc1Device),
131 mHwc1MinorVersion(getMinorVersion(hwc1Device)),
132 mHwc1SupportsVirtualDisplays(false),
133 mHwc1Callbacks(std::make_unique<Callbacks>(*this)),
134 mCapabilities(),
135 mLayers(),
136 mHwc1VirtualDisplay(),
137 mStateMutex(),
138 mCallbacks(),
139 mHasPendingInvalidate(false),
140 mPendingVsyncs(),
141 mPendingHotplugs(),
142 mDisplays(),
143 mHwc1DisplayMap()
144{
145 common.close = closeHook;
146 getCapabilities = getCapabilitiesHook;
147 getFunction = getFunctionHook;
148 populateCapabilities();
149 populatePrimary();
150 mHwc1Device->registerProcs(mHwc1Device,
151 static_cast<const hwc_procs_t*>(mHwc1Callbacks.get()));
152}
153
154HWC2On1Adapter::~HWC2On1Adapter() {
155 hwc_close_1(mHwc1Device);
156}
157
158void HWC2On1Adapter::doGetCapabilities(uint32_t* outCount,
159 int32_t* outCapabilities)
160{
161 if (outCapabilities == nullptr) {
162 *outCount = mCapabilities.size();
163 return;
164 }
165
166 auto capabilityIter = mCapabilities.cbegin();
167 for (size_t written = 0; written < *outCount; ++written) {
168 if (capabilityIter == mCapabilities.cend()) {
169 return;
170 }
171 outCapabilities[written] = static_cast<int32_t>(*capabilityIter);
172 ++capabilityIter;
173 }
174}
175
176hwc2_function_pointer_t HWC2On1Adapter::doGetFunction(
177 FunctionDescriptor descriptor)
178{
179 switch (descriptor) {
180 // Device functions
181 case FunctionDescriptor::CreateVirtualDisplay:
182 return asFP<HWC2_PFN_CREATE_VIRTUAL_DISPLAY>(
183 createVirtualDisplayHook);
184 case FunctionDescriptor::DestroyVirtualDisplay:
185 return asFP<HWC2_PFN_DESTROY_VIRTUAL_DISPLAY>(
186 destroyVirtualDisplayHook);
187 case FunctionDescriptor::Dump:
188 return asFP<HWC2_PFN_DUMP>(dumpHook);
189 case FunctionDescriptor::GetMaxVirtualDisplayCount:
190 return asFP<HWC2_PFN_GET_MAX_VIRTUAL_DISPLAY_COUNT>(
191 getMaxVirtualDisplayCountHook);
192 case FunctionDescriptor::RegisterCallback:
193 return asFP<HWC2_PFN_REGISTER_CALLBACK>(registerCallbackHook);
194
195 // Display functions
196 case FunctionDescriptor::AcceptDisplayChanges:
197 return asFP<HWC2_PFN_ACCEPT_DISPLAY_CHANGES>(
198 displayHook<decltype(&Display::acceptChanges),
199 &Display::acceptChanges>);
200 case FunctionDescriptor::CreateLayer:
201 return asFP<HWC2_PFN_CREATE_LAYER>(
202 displayHook<decltype(&Display::createLayer),
203 &Display::createLayer, hwc2_layer_t*>);
204 case FunctionDescriptor::DestroyLayer:
205 return asFP<HWC2_PFN_DESTROY_LAYER>(
206 displayHook<decltype(&Display::destroyLayer),
207 &Display::destroyLayer, hwc2_layer_t>);
208 case FunctionDescriptor::GetActiveConfig:
209 return asFP<HWC2_PFN_GET_ACTIVE_CONFIG>(
210 displayHook<decltype(&Display::getActiveConfig),
211 &Display::getActiveConfig, hwc2_config_t*>);
212 case FunctionDescriptor::GetChangedCompositionTypes:
213 return asFP<HWC2_PFN_GET_CHANGED_COMPOSITION_TYPES>(
214 displayHook<decltype(&Display::getChangedCompositionTypes),
215 &Display::getChangedCompositionTypes, uint32_t*,
216 hwc2_layer_t*, int32_t*>);
217 case FunctionDescriptor::GetDisplayAttribute:
218 return asFP<HWC2_PFN_GET_DISPLAY_ATTRIBUTE>(
219 getDisplayAttributeHook);
220 case FunctionDescriptor::GetDisplayConfigs:
221 return asFP<HWC2_PFN_GET_DISPLAY_CONFIGS>(
222 displayHook<decltype(&Display::getConfigs),
223 &Display::getConfigs, uint32_t*, hwc2_config_t*>);
224 case FunctionDescriptor::GetDisplayName:
225 return asFP<HWC2_PFN_GET_DISPLAY_NAME>(
226 displayHook<decltype(&Display::getName),
227 &Display::getName, uint32_t*, char*>);
228 case FunctionDescriptor::GetDisplayRequests:
229 return asFP<HWC2_PFN_GET_DISPLAY_REQUESTS>(
230 displayHook<decltype(&Display::getRequests),
231 &Display::getRequests, int32_t*, uint32_t*, hwc2_layer_t*,
232 int32_t*>);
233 case FunctionDescriptor::GetDisplayType:
234 return asFP<HWC2_PFN_GET_DISPLAY_TYPE>(
235 displayHook<decltype(&Display::getType),
236 &Display::getType, int32_t*>);
237 case FunctionDescriptor::GetDozeSupport:
238 return asFP<HWC2_PFN_GET_DOZE_SUPPORT>(
239 displayHook<decltype(&Display::getDozeSupport),
240 &Display::getDozeSupport, int32_t*>);
241 case FunctionDescriptor::GetReleaseFences:
242 return asFP<HWC2_PFN_GET_RELEASE_FENCES>(
243 displayHook<decltype(&Display::getReleaseFences),
244 &Display::getReleaseFences, uint32_t*, hwc2_layer_t*,
245 int32_t*>);
246 case FunctionDescriptor::PresentDisplay:
247 return asFP<HWC2_PFN_PRESENT_DISPLAY>(
248 displayHook<decltype(&Display::present),
249 &Display::present, int32_t*>);
250 case FunctionDescriptor::SetActiveConfig:
251 return asFP<HWC2_PFN_SET_ACTIVE_CONFIG>(
252 displayHook<decltype(&Display::setActiveConfig),
253 &Display::setActiveConfig, hwc2_config_t>);
254 case FunctionDescriptor::SetClientTarget:
255 return asFP<HWC2_PFN_SET_CLIENT_TARGET>(
256 displayHook<decltype(&Display::setClientTarget),
257 &Display::setClientTarget, buffer_handle_t, int32_t,
258 int32_t>);
259 case FunctionDescriptor::SetOutputBuffer:
260 return asFP<HWC2_PFN_SET_OUTPUT_BUFFER>(
261 displayHook<decltype(&Display::setOutputBuffer),
262 &Display::setOutputBuffer, buffer_handle_t, int32_t>);
263 case FunctionDescriptor::SetPowerMode:
264 return asFP<HWC2_PFN_SET_POWER_MODE>(setPowerModeHook);
265 case FunctionDescriptor::SetVsyncEnabled:
266 return asFP<HWC2_PFN_SET_VSYNC_ENABLED>(setVsyncEnabledHook);
267 case FunctionDescriptor::ValidateDisplay:
268 return asFP<HWC2_PFN_VALIDATE_DISPLAY>(
269 displayHook<decltype(&Display::validate),
270 &Display::validate, uint32_t*, uint32_t*>);
271
272 // Layer functions
273 case FunctionDescriptor::SetCursorPosition:
274 return asFP<HWC2_PFN_SET_CURSOR_POSITION>(
275 layerHook<decltype(&Layer::setCursorPosition),
276 &Layer::setCursorPosition, int32_t, int32_t>);
277 case FunctionDescriptor::SetLayerBuffer:
278 return asFP<HWC2_PFN_SET_LAYER_BUFFER>(
279 layerHook<decltype(&Layer::setBuffer), &Layer::setBuffer,
280 buffer_handle_t, int32_t>);
281 case FunctionDescriptor::SetLayerSurfaceDamage:
282 return asFP<HWC2_PFN_SET_LAYER_SURFACE_DAMAGE>(
283 layerHook<decltype(&Layer::setSurfaceDamage),
284 &Layer::setSurfaceDamage, hwc_region_t>);
285
286 // Layer state functions
287 case FunctionDescriptor::SetLayerBlendMode:
288 return asFP<HWC2_PFN_SET_LAYER_BLEND_MODE>(
289 setLayerBlendModeHook);
290 case FunctionDescriptor::SetLayerColor:
291 return asFP<HWC2_PFN_SET_LAYER_COLOR>(
292 layerHook<decltype(&Layer::setColor), &Layer::setColor,
293 hwc_color_t>);
294 case FunctionDescriptor::SetLayerCompositionType:
295 return asFP<HWC2_PFN_SET_LAYER_COMPOSITION_TYPE>(
296 setLayerCompositionTypeHook);
297 case FunctionDescriptor::SetLayerDisplayFrame:
298 return asFP<HWC2_PFN_SET_LAYER_DISPLAY_FRAME>(
299 layerHook<decltype(&Layer::setDisplayFrame),
300 &Layer::setDisplayFrame, hwc_rect_t>);
301 case FunctionDescriptor::SetLayerPlaneAlpha:
302 return asFP<HWC2_PFN_SET_LAYER_PLANE_ALPHA>(
303 layerHook<decltype(&Layer::setPlaneAlpha),
304 &Layer::setPlaneAlpha, float>);
305 case FunctionDescriptor::SetLayerSidebandStream:
306 return asFP<HWC2_PFN_SET_LAYER_SIDEBAND_STREAM>(
307 layerHook<decltype(&Layer::setSidebandStream),
308 &Layer::setSidebandStream, const native_handle_t*>);
309 case FunctionDescriptor::SetLayerSourceCrop:
310 return asFP<HWC2_PFN_SET_LAYER_SOURCE_CROP>(
311 layerHook<decltype(&Layer::setSourceCrop),
312 &Layer::setSourceCrop, hwc_frect_t>);
313 case FunctionDescriptor::SetLayerTransform:
314 return asFP<HWC2_PFN_SET_LAYER_TRANSFORM>(setLayerTransformHook);
315 case FunctionDescriptor::SetLayerVisibleRegion:
316 return asFP<HWC2_PFN_SET_LAYER_VISIBLE_REGION>(
317 layerHook<decltype(&Layer::setVisibleRegion),
318 &Layer::setVisibleRegion, hwc_region_t>);
319 case FunctionDescriptor::SetLayerZOrder:
320 return asFP<HWC2_PFN_SET_LAYER_Z_ORDER>(setLayerZOrderHook);
321
322 default:
323 ALOGE("doGetFunction: Unknown function descriptor: %d (%s)",
324 static_cast<int32_t>(descriptor),
325 to_string(descriptor).c_str());
326 return nullptr;
327 }
328}
329
330// Device functions
331
332Error HWC2On1Adapter::createVirtualDisplay(uint32_t width,
333 uint32_t height, hwc2_display_t* outDisplay)
334{
Dan Stozafc4e2022016-02-23 11:43:19 -0800335 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -0700336
337 if (mHwc1VirtualDisplay) {
338 // We have already allocated our only HWC1 virtual display
339 ALOGE("createVirtualDisplay: HWC1 virtual display already allocated");
340 return Error::NoResources;
341 }
342
343 if (MAX_VIRTUAL_DISPLAY_DIMENSION != 0 &&
344 (width > MAX_VIRTUAL_DISPLAY_DIMENSION ||
345 height > MAX_VIRTUAL_DISPLAY_DIMENSION)) {
346 ALOGE("createVirtualDisplay: Can't create a virtual display with"
347 " a dimension > %u (tried %u x %u)",
348 MAX_VIRTUAL_DISPLAY_DIMENSION, width, height);
349 return Error::NoResources;
350 }
351
352 mHwc1VirtualDisplay = std::make_shared<HWC2On1Adapter::Display>(*this,
353 HWC2::DisplayType::Virtual);
354 mHwc1VirtualDisplay->populateConfigs(width, height);
355 const auto displayId = mHwc1VirtualDisplay->getId();
356 mHwc1DisplayMap[HWC_DISPLAY_VIRTUAL] = displayId;
357 mHwc1VirtualDisplay->setHwc1Id(HWC_DISPLAY_VIRTUAL);
358 mDisplays.emplace(displayId, mHwc1VirtualDisplay);
359 *outDisplay = displayId;
360
361 return Error::None;
362}
363
364Error HWC2On1Adapter::destroyVirtualDisplay(hwc2_display_t displayId)
365{
Dan Stozafc4e2022016-02-23 11:43:19 -0800366 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -0700367
368 if (!mHwc1VirtualDisplay || (mHwc1VirtualDisplay->getId() != displayId)) {
369 return Error::BadDisplay;
370 }
371
372 mHwc1VirtualDisplay.reset();
373 mHwc1DisplayMap.erase(HWC_DISPLAY_VIRTUAL);
374 mDisplays.erase(displayId);
375
376 return Error::None;
377}
378
379void HWC2On1Adapter::dump(uint32_t* outSize, char* outBuffer)
380{
381 if (outBuffer != nullptr) {
382 auto copiedBytes = mDumpString.copy(outBuffer, *outSize);
383 *outSize = static_cast<uint32_t>(copiedBytes);
384 return;
385 }
386
387 std::stringstream output;
388
389 output << "-- HWC2On1Adapter --\n";
390
391 output << "Adapting to a HWC 1." << static_cast<int>(mHwc1MinorVersion) <<
392 " device\n";
393
394 // Attempt to acquire the lock for 1 second, but proceed without the lock
395 // after that, so we can still get some information if we're deadlocked
Dan Stozafc4e2022016-02-23 11:43:19 -0800396 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex,
397 std::defer_lock);
Dan Stozac6998d22015-09-24 17:03:36 -0700398 lock.try_lock_for(1s);
399
400 if (mCapabilities.empty()) {
401 output << "Capabilities: None\n";
402 } else {
403 output << "Capabilities:\n";
404 for (auto capability : mCapabilities) {
405 output << " " << to_string(capability) << '\n';
406 }
407 }
408
409 output << "Displays:\n";
410 for (const auto& element : mDisplays) {
411 const auto& display = element.second;
412 output << display->dump();
413 }
414 output << '\n';
415
Dan Stozafc4e2022016-02-23 11:43:19 -0800416 // Release the lock before calling into HWC1, and since we no longer require
417 // mutual exclusion to access mCapabilities or mDisplays
418 lock.unlock();
419
Dan Stozac6998d22015-09-24 17:03:36 -0700420 if (mHwc1Device->dump) {
421 output << "HWC1 dump:\n";
422 std::vector<char> hwc1Dump(4096);
423 // Call with size - 1 to preserve a null character at the end
424 mHwc1Device->dump(mHwc1Device, hwc1Dump.data(),
425 static_cast<int>(hwc1Dump.size() - 1));
426 output << hwc1Dump.data();
427 }
428
429 mDumpString = output.str();
430 *outSize = static_cast<uint32_t>(mDumpString.size());
431}
432
433uint32_t HWC2On1Adapter::getMaxVirtualDisplayCount()
434{
435 return mHwc1SupportsVirtualDisplays ? 1 : 0;
436}
437
438static bool isValid(Callback descriptor) {
439 switch (descriptor) {
440 case Callback::Hotplug: // Fall-through
441 case Callback::Refresh: // Fall-through
442 case Callback::Vsync: return true;
443 default: return false;
444 }
445}
446
447Error HWC2On1Adapter::registerCallback(Callback descriptor,
448 hwc2_callback_data_t callbackData, hwc2_function_pointer_t pointer)
449{
450 if (!isValid(descriptor)) {
451 return Error::BadParameter;
452 }
453
454 ALOGV("registerCallback(%s, %p, %p)", to_string(descriptor).c_str(),
455 callbackData, pointer);
456
Dan Stozafc4e2022016-02-23 11:43:19 -0800457 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -0700458
459 mCallbacks[descriptor] = {callbackData, pointer};
460
461 bool hasPendingInvalidate = false;
462 std::vector<hwc2_display_t> displayIds;
463 std::vector<std::pair<hwc2_display_t, int64_t>> pendingVsyncs;
464 std::vector<std::pair<hwc2_display_t, int>> pendingHotplugs;
465
466 if (descriptor == Callback::Refresh) {
467 hasPendingInvalidate = mHasPendingInvalidate;
468 if (hasPendingInvalidate) {
469 for (auto& displayPair : mDisplays) {
470 displayIds.emplace_back(displayPair.first);
471 }
472 }
473 mHasPendingInvalidate = false;
474 } else if (descriptor == Callback::Vsync) {
475 for (auto pending : mPendingVsyncs) {
476 auto hwc1DisplayId = pending.first;
477 if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) {
478 ALOGE("hwc1Vsync: Couldn't find display for HWC1 id %d",
479 hwc1DisplayId);
480 continue;
481 }
482 auto displayId = mHwc1DisplayMap[hwc1DisplayId];
483 auto timestamp = pending.second;
484 pendingVsyncs.emplace_back(displayId, timestamp);
485 }
486 mPendingVsyncs.clear();
487 } else if (descriptor == Callback::Hotplug) {
488 // Hotplug the primary display
489 pendingHotplugs.emplace_back(mHwc1DisplayMap[HWC_DISPLAY_PRIMARY],
490 static_cast<int32_t>(Connection::Connected));
491
492 for (auto pending : mPendingHotplugs) {
493 auto hwc1DisplayId = pending.first;
494 if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) {
495 ALOGE("hwc1Hotplug: Couldn't find display for HWC1 id %d",
496 hwc1DisplayId);
497 continue;
498 }
499 auto displayId = mHwc1DisplayMap[hwc1DisplayId];
500 auto connected = pending.second;
501 pendingHotplugs.emplace_back(displayId, connected);
502 }
503 }
504
505 // Call pending callbacks without the state lock held
506 lock.unlock();
507
508 if (hasPendingInvalidate) {
509 auto refresh = reinterpret_cast<HWC2_PFN_REFRESH>(pointer);
510 for (auto displayId : displayIds) {
511 refresh(callbackData, displayId);
512 }
513 }
514 if (!pendingVsyncs.empty()) {
515 auto vsync = reinterpret_cast<HWC2_PFN_VSYNC>(pointer);
516 for (auto& pendingVsync : pendingVsyncs) {
517 vsync(callbackData, pendingVsync.first, pendingVsync.second);
518 }
519 }
520 if (!pendingHotplugs.empty()) {
521 auto hotplug = reinterpret_cast<HWC2_PFN_HOTPLUG>(pointer);
522 for (auto& pendingHotplug : pendingHotplugs) {
523 hotplug(callbackData, pendingHotplug.first, pendingHotplug.second);
524 }
525 }
526 return Error::None;
527}
528
529// Display functions
530
531std::atomic<hwc2_display_t> HWC2On1Adapter::Display::sNextId(1);
532
533HWC2On1Adapter::Display::Display(HWC2On1Adapter& device, HWC2::DisplayType type)
534 : mId(sNextId++),
535 mDevice(device),
536 mDirtyCount(0),
537 mStateMutex(),
538 mZIsDirty(false),
539 mHwc1RequestedContents(nullptr),
540 mHwc1ReceivedContents(nullptr),
541 mRetireFence(),
542 mChanges(),
543 mHwc1Id(-1),
544 mConfigs(),
545 mActiveConfig(nullptr),
546 mName(),
547 mType(type),
548 mPowerMode(PowerMode::Off),
549 mVsyncEnabled(Vsync::Invalid),
550 mClientTarget(),
551 mOutputBuffer(),
Dan Stozafc4e2022016-02-23 11:43:19 -0800552 mLayers(),
553 mHwc1LayerMap() {}
Dan Stozac6998d22015-09-24 17:03:36 -0700554
555Error HWC2On1Adapter::Display::acceptChanges()
556{
557 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
558
559 if (!mChanges) {
560 ALOGV("[%" PRIu64 "] acceptChanges failed, not validated", mId);
561 return Error::NotValidated;
562 }
563
564 ALOGV("[%" PRIu64 "] acceptChanges", mId);
565
566 for (auto& change : mChanges->getTypeChanges()) {
567 auto layerId = change.first;
568 auto type = change.second;
569 auto layer = mDevice.mLayers[layerId];
570 layer->setCompositionType(type);
571 }
572
573 mChanges->clearTypeChanges();
574
575 mHwc1RequestedContents = std::move(mHwc1ReceivedContents);
576
577 return Error::None;
578}
579
580Error HWC2On1Adapter::Display::createLayer(hwc2_layer_t* outLayerId)
581{
582 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
583
584 auto layer = *mLayers.emplace(std::make_shared<Layer>(*this));
585 mDevice.mLayers.emplace(std::make_pair(layer->getId(), layer));
586 *outLayerId = layer->getId();
587 ALOGV("[%" PRIu64 "] created layer %" PRIu64, mId, *outLayerId);
588 return Error::None;
589}
590
591Error HWC2On1Adapter::Display::destroyLayer(hwc2_layer_t layerId)
592{
593 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
594
595 const auto mapLayer = mDevice.mLayers.find(layerId);
596 if (mapLayer == mDevice.mLayers.end()) {
597 ALOGV("[%" PRIu64 "] destroyLayer(%" PRIu64 ") failed: no such layer",
598 mId, layerId);
599 return Error::BadLayer;
600 }
601 const auto layer = mapLayer->second;
602 mDevice.mLayers.erase(mapLayer);
603 const auto zRange = mLayers.equal_range(layer);
604 for (auto current = zRange.first; current != zRange.second; ++current) {
605 if (**current == *layer) {
606 current = mLayers.erase(current);
607 break;
608 }
609 }
610 ALOGV("[%" PRIu64 "] destroyed layer %" PRIu64, mId, layerId);
611 return Error::None;
612}
613
614Error HWC2On1Adapter::Display::getActiveConfig(hwc2_config_t* outConfig)
615{
616 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
617
618 if (!mActiveConfig) {
619 ALOGV("[%" PRIu64 "] getActiveConfig --> %s", mId,
620 to_string(Error::BadConfig).c_str());
621 return Error::BadConfig;
622 }
623 auto configId = mActiveConfig->getId();
624 ALOGV("[%" PRIu64 "] getActiveConfig --> %u", mId, configId);
625 *outConfig = configId;
626 return Error::None;
627}
628
629Error HWC2On1Adapter::Display::getAttribute(hwc2_config_t configId,
630 Attribute attribute, int32_t* outValue)
631{
632 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
633
634 if (configId > mConfigs.size() || !mConfigs[configId]->isOnDisplay(*this)) {
635 ALOGV("[%" PRIu64 "] getAttribute failed: bad config (%u)", mId,
636 configId);
637 return Error::BadConfig;
638 }
639 *outValue = mConfigs[configId]->getAttribute(attribute);
640 ALOGV("[%" PRIu64 "] getAttribute(%u, %s) --> %d", mId, configId,
641 to_string(attribute).c_str(), *outValue);
642 return Error::None;
643}
644
645Error HWC2On1Adapter::Display::getChangedCompositionTypes(
646 uint32_t* outNumElements, hwc2_layer_t* outLayers, int32_t* outTypes)
647{
648 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
649
650 if (!mChanges) {
651 ALOGE("[%" PRIu64 "] getChangedCompositionTypes failed: not validated",
652 mId);
653 return Error::NotValidated;
654 }
655
656 if ((outLayers == nullptr) || (outTypes == nullptr)) {
657 *outNumElements = mChanges->getTypeChanges().size();
658 return Error::None;
659 }
660
661 uint32_t numWritten = 0;
662 for (const auto& element : mChanges->getTypeChanges()) {
663 if (numWritten == *outNumElements) {
664 break;
665 }
666 auto layerId = element.first;
667 auto intType = static_cast<int32_t>(element.second);
668 ALOGV("Adding %" PRIu64 " %s", layerId,
669 to_string(element.second).c_str());
670 outLayers[numWritten] = layerId;
671 outTypes[numWritten] = intType;
672 ++numWritten;
673 }
674 *outNumElements = numWritten;
675
676 return Error::None;
677}
678
679Error HWC2On1Adapter::Display::getConfigs(uint32_t* outNumConfigs,
680 hwc2_config_t* outConfigs)
681{
682 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
683
684 if (!outConfigs) {
685 *outNumConfigs = mConfigs.size();
686 return Error::None;
687 }
688 uint32_t numWritten = 0;
689 for (const auto& config : mConfigs) {
690 if (numWritten == *outNumConfigs) {
691 break;
692 }
693 outConfigs[numWritten] = config->getId();
694 ++numWritten;
695 }
696 *outNumConfigs = numWritten;
697 return Error::None;
698}
699
700Error HWC2On1Adapter::Display::getDozeSupport(int32_t* outSupport)
701{
702 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
703
704 if (mDevice.mHwc1MinorVersion < 4 || mHwc1Id != 0) {
705 *outSupport = 0;
706 } else {
707 *outSupport = 1;
708 }
709 return Error::None;
710}
711
712Error HWC2On1Adapter::Display::getName(uint32_t* outSize, char* outName)
713{
714 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
715
716 if (!outName) {
717 *outSize = mName.size();
718 return Error::None;
719 }
720 auto numCopied = mName.copy(outName, *outSize);
721 *outSize = numCopied;
722 return Error::None;
723}
724
725Error HWC2On1Adapter::Display::getReleaseFences(uint32_t* outNumElements,
726 hwc2_layer_t* outLayers, int32_t* outFences)
727{
728 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
729
730 uint32_t numWritten = 0;
731 bool outputsNonNull = (outLayers != nullptr) && (outFences != nullptr);
732 for (const auto& layer : mLayers) {
733 if (outputsNonNull && (numWritten == *outNumElements)) {
734 break;
735 }
736
737 auto releaseFence = layer->getReleaseFence();
738 if (releaseFence != Fence::NO_FENCE) {
739 if (outputsNonNull) {
740 outLayers[numWritten] = layer->getId();
741 outFences[numWritten] = releaseFence->dup();
742 }
743 ++numWritten;
744 }
745 }
746 *outNumElements = numWritten;
747
748 return Error::None;
749}
750
751Error HWC2On1Adapter::Display::getRequests(int32_t* outDisplayRequests,
752 uint32_t* outNumElements, hwc2_layer_t* outLayers,
753 int32_t* outLayerRequests)
754{
755 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
756
757 if (!mChanges) {
758 return Error::NotValidated;
759 }
760
761 if (outLayers == nullptr || outLayerRequests == nullptr) {
762 *outNumElements = mChanges->getNumLayerRequests();
763 return Error::None;
764 }
765
766 *outDisplayRequests = mChanges->getDisplayRequests();
767 uint32_t numWritten = 0;
768 for (const auto& request : mChanges->getLayerRequests()) {
769 if (numWritten == *outNumElements) {
770 break;
771 }
772 outLayers[numWritten] = request.first;
773 outLayerRequests[numWritten] = static_cast<int32_t>(request.second);
774 ++numWritten;
775 }
776
777 return Error::None;
778}
779
780Error HWC2On1Adapter::Display::getType(int32_t* outType)
781{
782 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
783
784 *outType = static_cast<int32_t>(mType);
785 return Error::None;
786}
787
788Error HWC2On1Adapter::Display::present(int32_t* outRetireFence)
789{
790 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
791
792 if (mChanges) {
793 Error error = mDevice.setAllDisplays();
794 if (error != Error::None) {
795 ALOGE("[%" PRIu64 "] present: setAllDisplaysFailed (%s)", mId,
796 to_string(error).c_str());
797 return error;
798 }
799 }
800
801 *outRetireFence = mRetireFence.get()->dup();
802 ALOGV("[%" PRIu64 "] present returning retire fence %d", mId,
803 *outRetireFence);
804
805 return Error::None;
806}
807
808Error HWC2On1Adapter::Display::setActiveConfig(hwc2_config_t configId)
809{
810 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
811
812 auto config = getConfig(configId);
813 if (!config) {
814 return Error::BadConfig;
815 }
816 mActiveConfig = config;
817 if (mDevice.mHwc1MinorVersion >= 4) {
818 int error = mDevice.mHwc1Device->setActiveConfig(mDevice.mHwc1Device,
819 mHwc1Id, static_cast<int>(configId));
820 ALOGE_IF(error != 0,
821 "setActiveConfig: Failed to set active config on HWC1 (%d)",
822 error);
823 }
824 return Error::None;
825}
826
827Error HWC2On1Adapter::Display::setClientTarget(buffer_handle_t target,
828 int32_t acquireFence, int32_t /*dataspace*/)
829{
830 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
831
832 ALOGV("[%" PRIu64 "] setClientTarget(%p, %d)", mId, target, acquireFence);
833 mClientTarget.setBuffer(target);
834 mClientTarget.setFence(acquireFence);
835 // dataspace can't be used by HWC1, so ignore it
836 return Error::None;
837}
838
839Error HWC2On1Adapter::Display::setOutputBuffer(buffer_handle_t buffer,
840 int32_t releaseFence)
841{
842 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
843
844 ALOGV("[%" PRIu64 "] setOutputBuffer(%p, %d)", mId, buffer, releaseFence);
845 mOutputBuffer.setBuffer(buffer);
846 mOutputBuffer.setFence(releaseFence);
847 return Error::None;
848}
849
850static bool isValid(PowerMode mode)
851{
852 switch (mode) {
853 case PowerMode::Off: // Fall-through
854 case PowerMode::DozeSuspend: // Fall-through
855 case PowerMode::Doze: // Fall-through
856 case PowerMode::On: return true;
857 default: return false;
858 }
859}
860
861static int getHwc1PowerMode(PowerMode mode)
862{
863 switch (mode) {
864 case PowerMode::Off: return HWC_POWER_MODE_OFF;
865 case PowerMode::DozeSuspend: return HWC_POWER_MODE_DOZE_SUSPEND;
866 case PowerMode::Doze: return HWC_POWER_MODE_DOZE;
867 case PowerMode::On: return HWC_POWER_MODE_NORMAL;
868 default: return HWC_POWER_MODE_OFF;
869 }
870}
871
872Error HWC2On1Adapter::Display::setPowerMode(PowerMode mode)
873{
874 if (!isValid(mode)) {
875 return Error::BadParameter;
876 }
877 if (mode == mPowerMode) {
878 return Error::None;
879 }
880
881 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
882
883 int error = 0;
884 if (mDevice.mHwc1MinorVersion < 4) {
885 error = mDevice.mHwc1Device->blank(mDevice.mHwc1Device, mHwc1Id,
886 mode == PowerMode::Off);
887 } else {
888 error = mDevice.mHwc1Device->setPowerMode(mDevice.mHwc1Device,
889 mHwc1Id, getHwc1PowerMode(mode));
890 }
891 ALOGE_IF(error != 0, "setPowerMode: Failed to set power mode on HWC1 (%d)",
892 error);
893
894 ALOGV("[%" PRIu64 "] setPowerMode(%s)", mId, to_string(mode).c_str());
895 mPowerMode = mode;
896 return Error::None;
897}
898
899static bool isValid(Vsync enable) {
900 switch (enable) {
901 case Vsync::Enable: // Fall-through
902 case Vsync::Disable: return true;
903 default: return false;
904 }
905}
906
907Error HWC2On1Adapter::Display::setVsyncEnabled(Vsync enable)
908{
909 if (!isValid(enable)) {
910 return Error::BadParameter;
911 }
912 if (enable == mVsyncEnabled) {
913 return Error::None;
914 }
915
916 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
917
918 int error = mDevice.mHwc1Device->eventControl(mDevice.mHwc1Device,
919 mHwc1Id, HWC_EVENT_VSYNC, enable == Vsync::Enable);
920 ALOGE_IF(error != 0, "setVsyncEnabled: Failed to set vsync on HWC1 (%d)",
921 error);
922
923 mVsyncEnabled = enable;
924 return Error::None;
925}
926
927Error HWC2On1Adapter::Display::validate(uint32_t* outNumTypes,
928 uint32_t* outNumRequests)
929{
930 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
931
932 ALOGV("[%" PRIu64 "] Entering validate", mId);
933
934 if (!mChanges) {
935 if (!mDevice.prepareAllDisplays()) {
936 return Error::BadDisplay;
937 }
938 }
939
940 *outNumTypes = mChanges->getNumTypes();
941 *outNumRequests = mChanges->getNumLayerRequests();
942 ALOGV("[%" PRIu64 "] validate --> %u types, %u requests", mId, *outNumTypes,
943 *outNumRequests);
944 for (auto request : mChanges->getTypeChanges()) {
945 ALOGV("Layer %" PRIu64 " --> %s", request.first,
946 to_string(request.second).c_str());
947 }
948 return *outNumTypes > 0 ? Error::HasChanges : Error::None;
949}
950
951// Display helpers
952
953Error HWC2On1Adapter::Display::updateLayerZ(hwc2_layer_t layerId, uint32_t z)
954{
955 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
956
957 const auto mapLayer = mDevice.mLayers.find(layerId);
958 if (mapLayer == mDevice.mLayers.end()) {
959 ALOGE("[%" PRIu64 "] updateLayerZ failed to find layer", mId);
960 return Error::BadLayer;
961 }
962
963 const auto layer = mapLayer->second;
964 const auto zRange = mLayers.equal_range(layer);
965 bool layerOnDisplay = false;
966 for (auto current = zRange.first; current != zRange.second; ++current) {
967 if (**current == *layer) {
968 if ((*current)->getZ() == z) {
969 // Don't change anything if the Z hasn't changed
970 return Error::None;
971 }
972 current = mLayers.erase(current);
973 layerOnDisplay = true;
974 break;
975 }
976 }
977
978 if (!layerOnDisplay) {
979 ALOGE("[%" PRIu64 "] updateLayerZ failed to find layer on display",
980 mId);
981 return Error::BadLayer;
982 }
983
984 layer->setZ(z);
985 mLayers.emplace(std::move(layer));
986 mZIsDirty = true;
987
988 return Error::None;
989}
990
991static constexpr uint32_t ATTRIBUTES[] = {
992 HWC_DISPLAY_VSYNC_PERIOD,
993 HWC_DISPLAY_WIDTH,
994 HWC_DISPLAY_HEIGHT,
995 HWC_DISPLAY_DPI_X,
996 HWC_DISPLAY_DPI_Y,
997 HWC_DISPLAY_NO_ATTRIBUTE,
998};
999static constexpr size_t NUM_ATTRIBUTES = sizeof(ATTRIBUTES) / sizeof(uint32_t);
1000
1001static constexpr uint32_t ATTRIBUTE_MAP[] = {
1002 5, // HWC_DISPLAY_NO_ATTRIBUTE = 0
1003 0, // HWC_DISPLAY_VSYNC_PERIOD = 1,
1004 1, // HWC_DISPLAY_WIDTH = 2,
1005 2, // HWC_DISPLAY_HEIGHT = 3,
1006 3, // HWC_DISPLAY_DPI_X = 4,
1007 4, // HWC_DISPLAY_DPI_Y = 5,
1008};
1009
1010template <uint32_t attribute>
1011static constexpr bool attributesMatch()
1012{
1013 return ATTRIBUTES[ATTRIBUTE_MAP[attribute]] == attribute;
1014}
1015static_assert(attributesMatch<HWC_DISPLAY_VSYNC_PERIOD>(),
1016 "Tables out of sync");
1017static_assert(attributesMatch<HWC_DISPLAY_WIDTH>(), "Tables out of sync");
1018static_assert(attributesMatch<HWC_DISPLAY_HEIGHT>(), "Tables out of sync");
1019static_assert(attributesMatch<HWC_DISPLAY_DPI_X>(), "Tables out of sync");
1020static_assert(attributesMatch<HWC_DISPLAY_DPI_Y>(), "Tables out of sync");
1021
1022void HWC2On1Adapter::Display::populateConfigs()
1023{
1024 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1025
1026 ALOGV("[%" PRIu64 "] populateConfigs", mId);
1027
1028 if (mHwc1Id == -1) {
1029 ALOGE("populateConfigs: HWC1 ID not set");
1030 return;
1031 }
1032
1033 const size_t MAX_NUM_CONFIGS = 128;
1034 uint32_t configs[MAX_NUM_CONFIGS] = {};
1035 size_t numConfigs = MAX_NUM_CONFIGS;
1036 mDevice.mHwc1Device->getDisplayConfigs(mDevice.mHwc1Device, mHwc1Id,
1037 configs, &numConfigs);
1038
1039 for (size_t c = 0; c < numConfigs; ++c) {
1040 uint32_t hwc1ConfigId = configs[c];
1041 hwc2_config_t id = static_cast<hwc2_config_t>(mConfigs.size());
1042 mConfigs.emplace_back(
1043 std::make_shared<Config>(*this, id, hwc1ConfigId));
1044 auto& config = mConfigs[id];
1045
1046 int32_t values[NUM_ATTRIBUTES] = {};
1047 mDevice.mHwc1Device->getDisplayAttributes(mDevice.mHwc1Device, mHwc1Id,
1048 hwc1ConfigId, ATTRIBUTES, values);
1049
1050 config->setAttribute(Attribute::VsyncPeriod,
1051 values[ATTRIBUTE_MAP[HWC_DISPLAY_VSYNC_PERIOD]]);
1052 config->setAttribute(Attribute::Width,
1053 values[ATTRIBUTE_MAP[HWC_DISPLAY_WIDTH]]);
1054 config->setAttribute(Attribute::Height,
1055 values[ATTRIBUTE_MAP[HWC_DISPLAY_HEIGHT]]);
1056 config->setAttribute(Attribute::DpiX,
1057 values[ATTRIBUTE_MAP[HWC_DISPLAY_DPI_X]]);
1058 config->setAttribute(Attribute::DpiY,
1059 values[ATTRIBUTE_MAP[HWC_DISPLAY_DPI_Y]]);
1060
1061 ALOGV("Found config: %s", config->toString().c_str());
1062 }
1063
1064 ALOGV("Getting active config");
1065 if (mDevice.mHwc1Device->getActiveConfig != nullptr) {
1066 auto activeConfig = mDevice.mHwc1Device->getActiveConfig(
1067 mDevice.mHwc1Device, mHwc1Id);
1068 if (activeConfig >= 0) {
1069 ALOGV("Setting active config to %d", activeConfig);
1070 mActiveConfig = mConfigs[activeConfig];
1071 }
1072 } else {
1073 ALOGV("getActiveConfig is null, choosing config 0");
1074 mActiveConfig = mConfigs[0];
1075 }
1076}
1077
1078void HWC2On1Adapter::Display::populateConfigs(uint32_t width, uint32_t height)
1079{
1080 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1081
1082 mConfigs.emplace_back(std::make_shared<Config>(*this, 0, 0));
1083 auto& config = mConfigs[0];
1084
1085 config->setAttribute(Attribute::Width, static_cast<int32_t>(width));
1086 config->setAttribute(Attribute::Height, static_cast<int32_t>(height));
1087 mActiveConfig = config;
1088}
1089
1090bool HWC2On1Adapter::Display::prepare()
1091{
1092 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1093
1094 // Only prepare display contents for displays HWC1 knows about
1095 if (mHwc1Id == -1) {
1096 return true;
1097 }
1098
1099 // It doesn't make sense to prepare a display for which there is no active
1100 // config, so return early
1101 if (!mActiveConfig) {
1102 ALOGE("[%" PRIu64 "] Attempted to prepare, but no config active", mId);
1103 return false;
1104 }
1105
1106 ALOGV("[%" PRIu64 "] Entering prepare", mId);
1107
1108 auto currentCount = mHwc1RequestedContents ?
1109 mHwc1RequestedContents->numHwLayers : 0;
1110 auto requiredCount = mLayers.size() + 1;
1111 ALOGV("[%" PRIu64 "] Requires %zd layers, %zd allocated in %p", mId,
1112 requiredCount, currentCount, mHwc1RequestedContents.get());
1113
1114 bool layerCountChanged = (currentCount != requiredCount);
1115 if (layerCountChanged) {
1116 reallocateHwc1Contents();
1117 }
1118
1119 bool applyAllState = false;
1120 if (layerCountChanged || mZIsDirty) {
1121 assignHwc1LayerIds();
1122 mZIsDirty = false;
1123 applyAllState = true;
1124 }
1125
1126 mHwc1RequestedContents->retireFenceFd = -1;
1127 mHwc1RequestedContents->flags = 0;
1128 if (isDirty() || applyAllState) {
1129 mHwc1RequestedContents->flags |= HWC_GEOMETRY_CHANGED;
1130 }
1131
1132 for (auto& layer : mLayers) {
1133 auto& hwc1Layer = mHwc1RequestedContents->hwLayers[layer->getHwc1Id()];
1134 hwc1Layer.releaseFenceFd = -1;
1135 layer->applyState(hwc1Layer, applyAllState);
1136 }
1137
1138 mHwc1RequestedContents->outbuf = mOutputBuffer.getBuffer();
1139 mHwc1RequestedContents->outbufAcquireFenceFd = mOutputBuffer.getFence();
1140
1141 prepareFramebufferTarget();
1142
1143 return true;
1144}
1145
1146static void cloneHWCRegion(hwc_region_t& region)
1147{
1148 auto size = sizeof(hwc_rect_t) * region.numRects;
1149 auto newRects = static_cast<hwc_rect_t*>(std::malloc(size));
1150 std::copy_n(region.rects, region.numRects, newRects);
1151 region.rects = newRects;
1152}
1153
1154HWC2On1Adapter::Display::HWC1Contents
1155 HWC2On1Adapter::Display::cloneRequestedContents() const
1156{
1157 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1158
1159 size_t size = sizeof(hwc_display_contents_1_t) +
1160 sizeof(hwc_layer_1_t) * (mHwc1RequestedContents->numHwLayers);
1161 auto contents = static_cast<hwc_display_contents_1_t*>(std::malloc(size));
1162 std::memcpy(contents, mHwc1RequestedContents.get(), size);
1163 for (size_t layerId = 0; layerId < contents->numHwLayers; ++layerId) {
1164 auto& layer = contents->hwLayers[layerId];
1165 // Deep copy the regions to avoid double-frees
1166 cloneHWCRegion(layer.visibleRegionScreen);
1167 cloneHWCRegion(layer.surfaceDamage);
1168 }
1169 return HWC1Contents(contents);
1170}
1171
1172void HWC2On1Adapter::Display::setReceivedContents(HWC1Contents contents)
1173{
1174 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1175
1176 mHwc1ReceivedContents = std::move(contents);
1177
1178 mChanges.reset(new Changes);
1179
1180 size_t numLayers = mHwc1ReceivedContents->numHwLayers;
1181 for (size_t hwc1Id = 0; hwc1Id < numLayers; ++hwc1Id) {
1182 const auto& receivedLayer = mHwc1ReceivedContents->hwLayers[hwc1Id];
1183 if (mHwc1LayerMap.count(hwc1Id) == 0) {
1184 ALOGE_IF(receivedLayer.compositionType != HWC_FRAMEBUFFER_TARGET,
1185 "setReceivedContents: HWC1 layer %zd doesn't have a"
1186 " matching HWC2 layer, and isn't the framebuffer target",
1187 hwc1Id);
1188 continue;
1189 }
1190
1191 Layer& layer = *mHwc1LayerMap[hwc1Id];
1192 updateTypeChanges(receivedLayer, layer);
1193 updateLayerRequests(receivedLayer, layer);
1194 }
1195}
1196
1197bool HWC2On1Adapter::Display::hasChanges() const
1198{
1199 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1200 return mChanges != nullptr;
1201}
1202
1203Error HWC2On1Adapter::Display::set(hwc_display_contents_1& hwcContents)
1204{
1205 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1206
1207 if (!mChanges || (mChanges->getNumTypes() > 0)) {
1208 ALOGE("[%" PRIu64 "] set failed: not validated", mId);
1209 return Error::NotValidated;
1210 }
1211
1212 // Set up the client/framebuffer target
1213 auto numLayers = hwcContents.numHwLayers;
1214
1215 // Close acquire fences on FRAMEBUFFER layers, since they will not be used
1216 // by HWC
1217 for (size_t l = 0; l < numLayers - 1; ++l) {
1218 auto& layer = hwcContents.hwLayers[l];
1219 if (layer.compositionType == HWC_FRAMEBUFFER) {
1220 ALOGV("Closing fence %d for layer %zd", layer.acquireFenceFd, l);
1221 close(layer.acquireFenceFd);
1222 layer.acquireFenceFd = -1;
1223 }
1224 }
1225
1226 auto& clientTargetLayer = hwcContents.hwLayers[numLayers - 1];
1227 if (clientTargetLayer.compositionType == HWC_FRAMEBUFFER_TARGET) {
1228 clientTargetLayer.handle = mClientTarget.getBuffer();
1229 clientTargetLayer.acquireFenceFd = mClientTarget.getFence();
1230 } else {
1231 ALOGE("[%" PRIu64 "] set: last HWC layer wasn't FRAMEBUFFER_TARGET",
1232 mId);
1233 }
1234
1235 mChanges.reset();
1236
1237 return Error::None;
1238}
1239
1240void HWC2On1Adapter::Display::addRetireFence(int fenceFd)
1241{
1242 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1243 mRetireFence.add(fenceFd);
1244}
1245
1246void HWC2On1Adapter::Display::addReleaseFences(
1247 const hwc_display_contents_1_t& hwcContents)
1248{
1249 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1250
1251 size_t numLayers = hwcContents.numHwLayers;
1252 for (size_t hwc1Id = 0; hwc1Id < numLayers; ++hwc1Id) {
1253 const auto& receivedLayer = hwcContents.hwLayers[hwc1Id];
1254 if (mHwc1LayerMap.count(hwc1Id) == 0) {
1255 if (receivedLayer.compositionType != HWC_FRAMEBUFFER_TARGET) {
1256 ALOGE("addReleaseFences: HWC1 layer %zd doesn't have a"
1257 " matching HWC2 layer, and isn't the framebuffer"
1258 " target", hwc1Id);
1259 }
1260 // Close the framebuffer target release fence since we will use the
1261 // display retire fence instead
1262 if (receivedLayer.releaseFenceFd != -1) {
1263 close(receivedLayer.releaseFenceFd);
1264 }
1265 continue;
1266 }
1267
1268 Layer& layer = *mHwc1LayerMap[hwc1Id];
1269 ALOGV("Adding release fence %d to layer %" PRIu64,
1270 receivedLayer.releaseFenceFd, layer.getId());
1271 layer.addReleaseFence(receivedLayer.releaseFenceFd);
1272 }
1273}
1274
1275static std::string hwc1CompositionString(int32_t type)
1276{
1277 switch (type) {
1278 case HWC_FRAMEBUFFER: return "Framebuffer";
1279 case HWC_OVERLAY: return "Overlay";
1280 case HWC_BACKGROUND: return "Background";
1281 case HWC_FRAMEBUFFER_TARGET: return "FramebufferTarget";
1282 case HWC_SIDEBAND: return "Sideband";
1283 case HWC_CURSOR_OVERLAY: return "CursorOverlay";
1284 default:
1285 return std::string("Unknown (") + std::to_string(type) + ")";
1286 }
1287}
1288
1289static std::string hwc1TransformString(int32_t transform)
1290{
1291 switch (transform) {
1292 case 0: return "None";
1293 case HWC_TRANSFORM_FLIP_H: return "FlipH";
1294 case HWC_TRANSFORM_FLIP_V: return "FlipV";
1295 case HWC_TRANSFORM_ROT_90: return "Rotate90";
1296 case HWC_TRANSFORM_ROT_180: return "Rotate180";
1297 case HWC_TRANSFORM_ROT_270: return "Rotate270";
1298 case HWC_TRANSFORM_FLIP_H_ROT_90: return "FlipHRotate90";
1299 case HWC_TRANSFORM_FLIP_V_ROT_90: return "FlipVRotate90";
1300 default:
1301 return std::string("Unknown (") + std::to_string(transform) + ")";
1302 }
1303}
1304
1305static std::string hwc1BlendModeString(int32_t mode)
1306{
1307 switch (mode) {
1308 case HWC_BLENDING_NONE: return "None";
1309 case HWC_BLENDING_PREMULT: return "Premultiplied";
1310 case HWC_BLENDING_COVERAGE: return "Coverage";
1311 default:
1312 return std::string("Unknown (") + std::to_string(mode) + ")";
1313 }
1314}
1315
1316static std::string rectString(hwc_rect_t rect)
1317{
1318 std::stringstream output;
1319 output << "[" << rect.left << ", " << rect.top << ", ";
1320 output << rect.right << ", " << rect.bottom << "]";
1321 return output.str();
1322}
1323
1324static std::string approximateFloatString(float f)
1325{
1326 if (static_cast<int32_t>(f) == f) {
1327 return std::to_string(static_cast<int32_t>(f));
1328 }
1329 int32_t truncated = static_cast<int32_t>(f * 10);
1330 bool approximate = (static_cast<float>(truncated) != f * 10);
1331 const size_t BUFFER_SIZE = 32;
1332 char buffer[BUFFER_SIZE] = {};
1333 auto bytesWritten = snprintf(buffer, BUFFER_SIZE,
1334 "%s%.1f", approximate ? "~" : "", f);
1335 return std::string(buffer, bytesWritten);
1336}
1337
1338static std::string frectString(hwc_frect_t frect)
1339{
1340 std::stringstream output;
1341 output << "[" << approximateFloatString(frect.left) << ", ";
1342 output << approximateFloatString(frect.top) << ", ";
1343 output << approximateFloatString(frect.right) << ", ";
1344 output << approximateFloatString(frect.bottom) << "]";
1345 return output.str();
1346}
1347
1348static std::string colorString(hwc_color_t color)
1349{
1350 std::stringstream output;
1351 output << "RGBA [";
1352 output << static_cast<int32_t>(color.r) << ", ";
1353 output << static_cast<int32_t>(color.g) << ", ";
1354 output << static_cast<int32_t>(color.b) << ", ";
1355 output << static_cast<int32_t>(color.a) << "]";
1356 return output.str();
1357}
1358
1359static std::string alphaString(float f)
1360{
1361 const size_t BUFFER_SIZE = 8;
1362 char buffer[BUFFER_SIZE] = {};
1363 auto bytesWritten = snprintf(buffer, BUFFER_SIZE, "%.3f", f);
1364 return std::string(buffer, bytesWritten);
1365}
1366
1367static std::string to_string(const hwc_layer_1_t& hwcLayer,
1368 int32_t hwc1MinorVersion)
1369{
1370 const char* fill = " ";
1371
1372 std::stringstream output;
1373
1374 output << " Composition: " <<
1375 hwc1CompositionString(hwcLayer.compositionType);
1376
1377 if (hwcLayer.compositionType == HWC_BACKGROUND) {
1378 output << " Color: " << colorString(hwcLayer.backgroundColor) << '\n';
1379 } else if (hwcLayer.compositionType == HWC_SIDEBAND) {
1380 output << " Stream: " << hwcLayer.sidebandStream << '\n';
1381 } else {
1382 output << " Buffer: " << hwcLayer.handle << "/" <<
1383 hwcLayer.acquireFenceFd << '\n';
1384 }
1385
1386 output << fill << "Display frame: " << rectString(hwcLayer.displayFrame) <<
1387 '\n';
1388
1389 output << fill << "Source crop: ";
1390 if (hwc1MinorVersion >= 3) {
1391 output << frectString(hwcLayer.sourceCropf) << '\n';
1392 } else {
1393 output << rectString(hwcLayer.sourceCropi) << '\n';
1394 }
1395
1396 output << fill << "Transform: " << hwc1TransformString(hwcLayer.transform);
1397 output << " Blend mode: " << hwc1BlendModeString(hwcLayer.blending);
1398 if (hwcLayer.planeAlpha != 0xFF) {
1399 output << " Alpha: " << alphaString(hwcLayer.planeAlpha / 255.0f);
1400 }
1401 output << '\n';
1402
1403 if (hwcLayer.hints != 0) {
1404 output << fill << "Hints:";
1405 if ((hwcLayer.hints & HWC_HINT_TRIPLE_BUFFER) != 0) {
1406 output << " TripleBuffer";
1407 }
1408 if ((hwcLayer.hints & HWC_HINT_CLEAR_FB) != 0) {
1409 output << " ClearFB";
1410 }
1411 output << '\n';
1412 }
1413
1414 if (hwcLayer.flags != 0) {
1415 output << fill << "Flags:";
1416 if ((hwcLayer.flags & HWC_SKIP_LAYER) != 0) {
1417 output << " SkipLayer";
1418 }
1419 if ((hwcLayer.flags & HWC_IS_CURSOR_LAYER) != 0) {
1420 output << " IsCursorLayer";
1421 }
1422 output << '\n';
1423 }
1424
1425 return output.str();
1426}
1427
1428static std::string to_string(const hwc_display_contents_1_t& hwcContents,
1429 int32_t hwc1MinorVersion)
1430{
1431 const char* fill = " ";
1432
1433 std::stringstream output;
1434 output << fill << "Geometry changed: " <<
1435 ((hwcContents.flags & HWC_GEOMETRY_CHANGED) != 0 ? "Y\n" : "N\n");
1436
1437 output << fill << hwcContents.numHwLayers << " Layer" <<
1438 ((hwcContents.numHwLayers == 1) ? "\n" : "s\n");
1439 for (size_t layer = 0; layer < hwcContents.numHwLayers; ++layer) {
1440 output << fill << " Layer " << layer;
1441 output << to_string(hwcContents.hwLayers[layer], hwc1MinorVersion);
1442 }
1443
1444 if (hwcContents.outbuf != nullptr) {
1445 output << fill << "Output buffer: " << hwcContents.outbuf << "/" <<
1446 hwcContents.outbufAcquireFenceFd << '\n';
1447 }
1448
1449 return output.str();
1450}
1451
1452std::string HWC2On1Adapter::Display::dump() const
1453{
1454 std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1455
1456 std::stringstream output;
1457
1458 output << " Display " << mId << ": ";
1459 output << to_string(mType) << " ";
1460 output << "HWC1 ID: " << mHwc1Id << " ";
1461 output << "Power mode: " << to_string(mPowerMode) << " ";
1462 output << "Vsync: " << to_string(mVsyncEnabled) << '\n';
1463
1464 output << " " << mConfigs.size() << " Config" <<
1465 (mConfigs.size() == 1 ? "" : "s") << " (* Active)\n";
1466 for (const auto& config : mConfigs) {
1467 if (config == mActiveConfig) {
1468 output << " * " << config->toString();
1469 } else {
1470 output << " " << config->toString();
1471 }
1472 }
1473 output << '\n';
1474
1475 output << " " << mLayers.size() << " Layer" <<
1476 (mLayers.size() == 1 ? "" : "s") << '\n';
1477 for (const auto& layer : mLayers) {
1478 output << layer->dump();
1479 }
1480
1481 output << " Client target: " << mClientTarget.getBuffer() << '\n';
1482
1483 if (mOutputBuffer.getBuffer() != nullptr) {
1484 output << " Output buffer: " << mOutputBuffer.getBuffer() << '\n';
1485 }
1486
1487 if (mHwc1ReceivedContents) {
1488 output << " Last received HWC1 state\n";
1489 output << to_string(*mHwc1ReceivedContents, mDevice.mHwc1MinorVersion);
1490 } else if (mHwc1RequestedContents) {
1491 output << " Last requested HWC1 state\n";
1492 output << to_string(*mHwc1RequestedContents, mDevice.mHwc1MinorVersion);
1493 }
1494
1495 return output.str();
1496}
1497
1498void HWC2On1Adapter::Display::Config::setAttribute(HWC2::Attribute attribute,
1499 int32_t value)
1500{
1501 mAttributes[attribute] = value;
1502}
1503
1504int32_t HWC2On1Adapter::Display::Config::getAttribute(Attribute attribute) const
1505{
1506 if (mAttributes.count(attribute) == 0) {
1507 return -1;
1508 }
1509 return mAttributes.at(attribute);
1510}
1511
1512std::string HWC2On1Adapter::Display::Config::toString() const
1513{
1514 std::string output;
1515
1516 const size_t BUFFER_SIZE = 100;
1517 char buffer[BUFFER_SIZE] = {};
1518 auto writtenBytes = snprintf(buffer, BUFFER_SIZE,
1519 "[%u] %u x %u", mHwcId,
1520 mAttributes.at(HWC2::Attribute::Width),
1521 mAttributes.at(HWC2::Attribute::Height));
1522 output.append(buffer, writtenBytes);
1523
1524 if (mAttributes.count(HWC2::Attribute::VsyncPeriod) != 0) {
1525 std::memset(buffer, 0, BUFFER_SIZE);
1526 writtenBytes = snprintf(buffer, BUFFER_SIZE, " @ %.1f Hz",
1527 1e9 / mAttributes.at(HWC2::Attribute::VsyncPeriod));
1528 output.append(buffer, writtenBytes);
1529 }
1530
1531 if (mAttributes.count(HWC2::Attribute::DpiX) != 0 &&
1532 mAttributes.at(HWC2::Attribute::DpiX) != -1) {
1533 std::memset(buffer, 0, BUFFER_SIZE);
1534 writtenBytes = snprintf(buffer, BUFFER_SIZE,
1535 ", DPI: %.1f x %.1f",
1536 mAttributes.at(HWC2::Attribute::DpiX) / 1000.0f,
1537 mAttributes.at(HWC2::Attribute::DpiY) / 1000.0f);
1538 output.append(buffer, writtenBytes);
1539 }
1540
1541 return output;
1542}
1543
1544std::shared_ptr<const HWC2On1Adapter::Display::Config>
1545 HWC2On1Adapter::Display::getConfig(hwc2_config_t configId) const
1546{
1547 if (configId > mConfigs.size() || !mConfigs[configId]->isOnDisplay(*this)) {
1548 return nullptr;
1549 }
1550 return mConfigs[configId];
1551}
1552
1553void HWC2On1Adapter::Display::reallocateHwc1Contents()
1554{
1555 // Allocate an additional layer for the framebuffer target
1556 auto numLayers = mLayers.size() + 1;
1557 size_t size = sizeof(hwc_display_contents_1_t) +
1558 sizeof(hwc_layer_1_t) * numLayers;
1559 ALOGV("[%" PRIu64 "] reallocateHwc1Contents creating %zd layer%s", mId,
1560 numLayers, numLayers != 1 ? "s" : "");
1561 auto contents =
1562 static_cast<hwc_display_contents_1_t*>(std::calloc(size, 1));
1563 contents->numHwLayers = numLayers;
1564 mHwc1RequestedContents.reset(contents);
1565}
1566
1567void HWC2On1Adapter::Display::assignHwc1LayerIds()
1568{
1569 mHwc1LayerMap.clear();
1570 size_t nextHwc1Id = 0;
1571 for (auto& layer : mLayers) {
1572 mHwc1LayerMap[nextHwc1Id] = layer;
1573 layer->setHwc1Id(nextHwc1Id++);
1574 }
1575}
1576
1577void HWC2On1Adapter::Display::updateTypeChanges(const hwc_layer_1_t& hwc1Layer,
1578 const Layer& layer)
1579{
1580 auto layerId = layer.getId();
1581 switch (hwc1Layer.compositionType) {
1582 case HWC_FRAMEBUFFER:
1583 if (layer.getCompositionType() != Composition::Client) {
1584 mChanges->addTypeChange(layerId, Composition::Client);
1585 }
1586 break;
1587 case HWC_OVERLAY:
1588 if (layer.getCompositionType() != Composition::Device) {
1589 mChanges->addTypeChange(layerId, Composition::Device);
1590 }
1591 break;
1592 case HWC_BACKGROUND:
1593 ALOGE_IF(layer.getCompositionType() != Composition::SolidColor,
1594 "updateTypeChanges: HWC1 requested BACKGROUND, but HWC2"
1595 " wasn't expecting SolidColor");
1596 break;
1597 case HWC_FRAMEBUFFER_TARGET:
1598 // Do nothing, since it shouldn't be modified by HWC1
1599 break;
1600 case HWC_SIDEBAND:
1601 ALOGE_IF(layer.getCompositionType() != Composition::Sideband,
1602 "updateTypeChanges: HWC1 requested SIDEBAND, but HWC2"
1603 " wasn't expecting Sideband");
1604 break;
1605 case HWC_CURSOR_OVERLAY:
1606 ALOGE_IF(layer.getCompositionType() != Composition::Cursor,
1607 "updateTypeChanges: HWC1 requested CURSOR_OVERLAY, but"
1608 " HWC2 wasn't expecting Cursor");
1609 break;
1610 }
1611}
1612
1613void HWC2On1Adapter::Display::updateLayerRequests(
1614 const hwc_layer_1_t& hwc1Layer, const Layer& layer)
1615{
1616 if ((hwc1Layer.hints & HWC_HINT_CLEAR_FB) != 0) {
1617 mChanges->addLayerRequest(layer.getId(),
1618 LayerRequest::ClearClientTarget);
1619 }
1620}
1621
1622void HWC2On1Adapter::Display::prepareFramebufferTarget()
1623{
1624 // We check that mActiveConfig is valid in Display::prepare
1625 int32_t width = mActiveConfig->getAttribute(Attribute::Width);
1626 int32_t height = mActiveConfig->getAttribute(Attribute::Height);
1627
1628 auto& hwc1Target = mHwc1RequestedContents->hwLayers[mLayers.size()];
1629 hwc1Target.compositionType = HWC_FRAMEBUFFER_TARGET;
1630 hwc1Target.releaseFenceFd = -1;
1631 hwc1Target.hints = 0;
1632 hwc1Target.flags = 0;
1633 hwc1Target.transform = 0;
1634 hwc1Target.blending = HWC_BLENDING_PREMULT;
1635 if (mDevice.getHwc1MinorVersion() < 3) {
1636 hwc1Target.sourceCropi = {0, 0, width, height};
1637 } else {
1638 hwc1Target.sourceCropf = {0.0f, 0.0f, static_cast<float>(width),
1639 static_cast<float>(height)};
1640 }
1641 hwc1Target.displayFrame = {0, 0, width, height};
1642 hwc1Target.planeAlpha = 255;
1643 hwc1Target.visibleRegionScreen.numRects = 1;
1644 auto rects = static_cast<hwc_rect_t*>(std::malloc(sizeof(hwc_rect_t)));
1645 rects[0].left = 0;
1646 rects[0].top = 0;
1647 rects[0].right = width;
1648 rects[0].bottom = height;
1649 hwc1Target.visibleRegionScreen.rects = rects;
1650
1651 // We will set this to the correct value in set
1652 hwc1Target.acquireFenceFd = -1;
1653}
1654
1655// Layer functions
1656
1657std::atomic<hwc2_layer_t> HWC2On1Adapter::Layer::sNextId(1);
1658
1659HWC2On1Adapter::Layer::Layer(Display& display)
1660 : mId(sNextId++),
1661 mDisplay(display),
Dan Stozafc4e2022016-02-23 11:43:19 -08001662 mDirtyCount(0),
1663 mBuffer(),
1664 mSurfaceDamage(),
Dan Stozac6998d22015-09-24 17:03:36 -07001665 mBlendMode(*this, BlendMode::None),
1666 mColor(*this, {0, 0, 0, 0}),
1667 mCompositionType(*this, Composition::Invalid),
1668 mDisplayFrame(*this, {0, 0, -1, -1}),
1669 mPlaneAlpha(*this, 0.0f),
1670 mSidebandStream(*this, nullptr),
1671 mSourceCrop(*this, {0.0f, 0.0f, -1.0f, -1.0f}),
1672 mTransform(*this, Transform::None),
1673 mVisibleRegion(*this, std::vector<hwc_rect_t>()),
1674 mZ(0),
Dan Stozafc4e2022016-02-23 11:43:19 -08001675 mReleaseFence(),
Dan Stozac6998d22015-09-24 17:03:36 -07001676 mHwc1Id(0),
1677 mHasUnsupportedPlaneAlpha(false) {}
1678
1679bool HWC2On1Adapter::SortLayersByZ::operator()(
1680 const std::shared_ptr<Layer>& lhs, const std::shared_ptr<Layer>& rhs)
1681{
1682 return lhs->getZ() < rhs->getZ();
1683}
1684
1685Error HWC2On1Adapter::Layer::setBuffer(buffer_handle_t buffer,
1686 int32_t acquireFence)
1687{
1688 ALOGV("Setting acquireFence to %d for layer %" PRIu64, acquireFence, mId);
1689 mBuffer.setBuffer(buffer);
1690 mBuffer.setFence(acquireFence);
1691 return Error::None;
1692}
1693
1694Error HWC2On1Adapter::Layer::setCursorPosition(int32_t x, int32_t y)
1695{
1696 if (mCompositionType.getValue() != Composition::Cursor) {
1697 return Error::BadLayer;
1698 }
1699
1700 if (mDisplay.hasChanges()) {
1701 return Error::NotValidated;
1702 }
1703
1704 auto displayId = mDisplay.getHwc1Id();
1705 auto hwc1Device = mDisplay.getDevice().getHwc1Device();
1706 hwc1Device->setCursorPositionAsync(hwc1Device, displayId, x, y);
1707 return Error::None;
1708}
1709
1710Error HWC2On1Adapter::Layer::setSurfaceDamage(hwc_region_t damage)
1711{
1712 mSurfaceDamage.resize(damage.numRects);
1713 std::copy_n(damage.rects, damage.numRects, mSurfaceDamage.begin());
1714 return Error::None;
1715}
1716
1717// Layer state functions
1718
1719Error HWC2On1Adapter::Layer::setBlendMode(BlendMode mode)
1720{
1721 mBlendMode.setPending(mode);
1722 return Error::None;
1723}
1724
1725Error HWC2On1Adapter::Layer::setColor(hwc_color_t color)
1726{
1727 mColor.setPending(color);
1728 return Error::None;
1729}
1730
1731Error HWC2On1Adapter::Layer::setCompositionType(Composition type)
1732{
1733 mCompositionType.setPending(type);
1734 return Error::None;
1735}
1736
1737Error HWC2On1Adapter::Layer::setDisplayFrame(hwc_rect_t frame)
1738{
1739 mDisplayFrame.setPending(frame);
1740 return Error::None;
1741}
1742
1743Error HWC2On1Adapter::Layer::setPlaneAlpha(float alpha)
1744{
1745 mPlaneAlpha.setPending(alpha);
1746 return Error::None;
1747}
1748
1749Error HWC2On1Adapter::Layer::setSidebandStream(const native_handle_t* stream)
1750{
1751 mSidebandStream.setPending(stream);
1752 return Error::None;
1753}
1754
1755Error HWC2On1Adapter::Layer::setSourceCrop(hwc_frect_t crop)
1756{
1757 mSourceCrop.setPending(crop);
1758 return Error::None;
1759}
1760
1761Error HWC2On1Adapter::Layer::setTransform(Transform transform)
1762{
1763 mTransform.setPending(transform);
1764 return Error::None;
1765}
1766
1767Error HWC2On1Adapter::Layer::setVisibleRegion(hwc_region_t rawVisible)
1768{
1769 std::vector<hwc_rect_t> visible(rawVisible.rects,
1770 rawVisible.rects + rawVisible.numRects);
1771 mVisibleRegion.setPending(std::move(visible));
1772 return Error::None;
1773}
1774
1775Error HWC2On1Adapter::Layer::setZ(uint32_t z)
1776{
1777 mZ = z;
1778 return Error::None;
1779}
1780
1781void HWC2On1Adapter::Layer::addReleaseFence(int fenceFd)
1782{
1783 ALOGV("addReleaseFence %d to layer %" PRIu64, fenceFd, mId);
1784 mReleaseFence.add(fenceFd);
1785}
1786
1787const sp<Fence>& HWC2On1Adapter::Layer::getReleaseFence() const
1788{
1789 return mReleaseFence.get();
1790}
1791
1792void HWC2On1Adapter::Layer::applyState(hwc_layer_1_t& hwc1Layer,
1793 bool applyAllState)
1794{
1795 applyCommonState(hwc1Layer, applyAllState);
1796 auto compositionType = mCompositionType.getPendingValue();
1797 if (compositionType == Composition::SolidColor) {
1798 applySolidColorState(hwc1Layer, applyAllState);
1799 } else if (compositionType == Composition::Sideband) {
1800 applySidebandState(hwc1Layer, applyAllState);
1801 } else {
1802 applyBufferState(hwc1Layer);
1803 }
1804 applyCompositionType(hwc1Layer, applyAllState);
1805}
1806
1807// Layer dump helpers
1808
1809static std::string regionStrings(const std::vector<hwc_rect_t>& visibleRegion,
1810 const std::vector<hwc_rect_t>& surfaceDamage)
1811{
1812 std::string regions;
1813 regions += " Visible Region";
1814 regions.resize(40, ' ');
1815 regions += "Surface Damage\n";
1816
1817 size_t numPrinted = 0;
1818 size_t maxSize = std::max(visibleRegion.size(), surfaceDamage.size());
1819 while (numPrinted < maxSize) {
1820 std::string line(" ");
1821 if (visibleRegion.empty() && numPrinted == 0) {
1822 line += "None";
1823 } else if (numPrinted < visibleRegion.size()) {
1824 line += rectString(visibleRegion[numPrinted]);
1825 }
1826 line.resize(40, ' ');
1827 if (surfaceDamage.empty() && numPrinted == 0) {
1828 line += "None";
1829 } else if (numPrinted < surfaceDamage.size()) {
1830 line += rectString(surfaceDamage[numPrinted]);
1831 }
1832 line += '\n';
1833 regions += line;
1834 ++numPrinted;
1835 }
1836 return regions;
1837}
1838
1839std::string HWC2On1Adapter::Layer::dump() const
1840{
1841 std::stringstream output;
1842 const char* fill = " ";
1843
1844 output << fill << to_string(mCompositionType.getPendingValue());
1845 output << " Layer HWC2/1: " << mId << "/" << mHwc1Id << " ";
1846 output << "Z: " << mZ;
1847 if (mCompositionType.getValue() == HWC2::Composition::SolidColor) {
1848 output << " " << colorString(mColor.getValue());
1849 } else if (mCompositionType.getValue() == HWC2::Composition::Sideband) {
1850 output << " Handle: " << mSidebandStream.getValue() << '\n';
1851 } else {
1852 output << " Buffer: " << mBuffer.getBuffer() << "/" <<
1853 mBuffer.getFence() << '\n';
1854 output << fill << " Display frame [LTRB]: " <<
1855 rectString(mDisplayFrame.getValue()) << '\n';
1856 output << fill << " Source crop: " <<
1857 frectString(mSourceCrop.getValue()) << '\n';
1858 output << fill << " Transform: " << to_string(mTransform.getValue());
1859 output << " Blend mode: " << to_string(mBlendMode.getValue());
1860 if (mPlaneAlpha.getValue() != 1.0f) {
1861 output << " Alpha: " <<
1862 alphaString(mPlaneAlpha.getValue()) << '\n';
1863 } else {
1864 output << '\n';
1865 }
1866 output << regionStrings(mVisibleRegion.getValue(), mSurfaceDamage);
1867 }
1868 return output.str();
1869}
1870
1871static int getHwc1Blending(HWC2::BlendMode blendMode)
1872{
1873 switch (blendMode) {
1874 case BlendMode::Coverage: return HWC_BLENDING_COVERAGE;
1875 case BlendMode::Premultiplied: return HWC_BLENDING_PREMULT;
1876 default: return HWC_BLENDING_NONE;
1877 }
1878}
1879
1880void HWC2On1Adapter::Layer::applyCommonState(hwc_layer_1_t& hwc1Layer,
1881 bool applyAllState)
1882{
1883 auto minorVersion = mDisplay.getDevice().getHwc1MinorVersion();
1884 if (applyAllState || mBlendMode.isDirty()) {
1885 hwc1Layer.blending = getHwc1Blending(mBlendMode.getPendingValue());
1886 mBlendMode.latch();
1887 }
1888 if (applyAllState || mDisplayFrame.isDirty()) {
1889 hwc1Layer.displayFrame = mDisplayFrame.getPendingValue();
1890 mDisplayFrame.latch();
1891 }
1892 if (applyAllState || mPlaneAlpha.isDirty()) {
1893 auto pendingAlpha = mPlaneAlpha.getPendingValue();
1894 if (minorVersion < 2) {
1895 mHasUnsupportedPlaneAlpha = pendingAlpha < 1.0f;
1896 } else {
1897 hwc1Layer.planeAlpha =
1898 static_cast<uint8_t>(255.0f * pendingAlpha + 0.5f);
1899 }
1900 mPlaneAlpha.latch();
1901 }
1902 if (applyAllState || mSourceCrop.isDirty()) {
1903 if (minorVersion < 3) {
1904 auto pending = mSourceCrop.getPendingValue();
1905 hwc1Layer.sourceCropi.left =
1906 static_cast<int32_t>(std::ceil(pending.left));
1907 hwc1Layer.sourceCropi.top =
1908 static_cast<int32_t>(std::ceil(pending.top));
1909 hwc1Layer.sourceCropi.right =
1910 static_cast<int32_t>(std::floor(pending.right));
1911 hwc1Layer.sourceCropi.bottom =
1912 static_cast<int32_t>(std::floor(pending.bottom));
1913 } else {
1914 hwc1Layer.sourceCropf = mSourceCrop.getPendingValue();
1915 }
1916 mSourceCrop.latch();
1917 }
1918 if (applyAllState || mTransform.isDirty()) {
1919 hwc1Layer.transform =
1920 static_cast<uint32_t>(mTransform.getPendingValue());
1921 mTransform.latch();
1922 }
1923 if (applyAllState || mVisibleRegion.isDirty()) {
1924 auto& hwc1VisibleRegion = hwc1Layer.visibleRegionScreen;
1925
1926 std::free(const_cast<hwc_rect_t*>(hwc1VisibleRegion.rects));
1927
1928 auto pending = mVisibleRegion.getPendingValue();
1929 hwc_rect_t* newRects = static_cast<hwc_rect_t*>(
1930 std::malloc(sizeof(hwc_rect_t) * pending.size()));
1931 std::copy(pending.begin(), pending.end(), newRects);
1932 hwc1VisibleRegion.rects = const_cast<const hwc_rect_t*>(newRects);
1933 hwc1VisibleRegion.numRects = pending.size();
1934 mVisibleRegion.latch();
1935 }
1936}
1937
1938void HWC2On1Adapter::Layer::applySolidColorState(hwc_layer_1_t& hwc1Layer,
1939 bool applyAllState)
1940{
1941 if (applyAllState || mColor.isDirty()) {
1942 hwc1Layer.backgroundColor = mColor.getPendingValue();
1943 mColor.latch();
1944 }
1945}
1946
1947void HWC2On1Adapter::Layer::applySidebandState(hwc_layer_1_t& hwc1Layer,
1948 bool applyAllState)
1949{
1950 if (applyAllState || mSidebandStream.isDirty()) {
1951 hwc1Layer.sidebandStream = mSidebandStream.getPendingValue();
1952 mSidebandStream.latch();
1953 }
1954}
1955
1956void HWC2On1Adapter::Layer::applyBufferState(hwc_layer_1_t& hwc1Layer)
1957{
1958 hwc1Layer.handle = mBuffer.getBuffer();
1959 hwc1Layer.acquireFenceFd = mBuffer.getFence();
1960}
1961
1962void HWC2On1Adapter::Layer::applyCompositionType(hwc_layer_1_t& hwc1Layer,
1963 bool applyAllState)
1964{
1965 if (mHasUnsupportedPlaneAlpha) {
1966 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
1967 hwc1Layer.flags = HWC_SKIP_LAYER;
1968 return;
1969 }
1970
1971 if (applyAllState || mCompositionType.isDirty()) {
1972 hwc1Layer.flags = 0;
1973 switch (mCompositionType.getPendingValue()) {
1974 case Composition::Client:
1975 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
1976 hwc1Layer.flags |= HWC_SKIP_LAYER;
1977 break;
1978 case Composition::Device:
1979 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
1980 break;
1981 case Composition::SolidColor:
1982 hwc1Layer.compositionType = HWC_BACKGROUND;
1983 break;
1984 case Composition::Cursor:
1985 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
1986 if (mDisplay.getDevice().getHwc1MinorVersion() >= 4) {
1987 hwc1Layer.hints |= HWC_IS_CURSOR_LAYER;
1988 }
1989 break;
1990 case Composition::Sideband:
1991 if (mDisplay.getDevice().getHwc1MinorVersion() < 4) {
1992 hwc1Layer.compositionType = HWC_SIDEBAND;
1993 } else {
1994 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
1995 hwc1Layer.flags |= HWC_SKIP_LAYER;
1996 }
1997 break;
1998 default:
1999 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2000 hwc1Layer.flags |= HWC_SKIP_LAYER;
2001 break;
2002 }
2003 ALOGV("Layer %" PRIu64 " %s set to %d", mId,
2004 to_string(mCompositionType.getPendingValue()).c_str(),
2005 hwc1Layer.compositionType);
2006 ALOGV_IF(hwc1Layer.flags & HWC_SKIP_LAYER, " and skipping");
2007 mCompositionType.latch();
2008 }
2009}
2010
2011// Adapter helpers
2012
2013void HWC2On1Adapter::populateCapabilities()
2014{
2015 ALOGV("populateCapabilities");
2016 if (mHwc1MinorVersion >= 3U) {
2017 int supportedTypes = 0;
2018 auto result = mHwc1Device->query(mHwc1Device,
2019 HWC_DISPLAY_TYPES_SUPPORTED, &supportedTypes);
2020 if ((result == 0) && ((supportedTypes & HWC_DISPLAY_VIRTUAL) != 0)) {
2021 ALOGI("Found support for HWC virtual displays");
2022 mHwc1SupportsVirtualDisplays = true;
2023 }
2024 }
2025 if (mHwc1MinorVersion >= 4U) {
2026 mCapabilities.insert(Capability::SidebandStream);
2027 }
2028}
2029
2030HWC2On1Adapter::Display* HWC2On1Adapter::getDisplay(hwc2_display_t id)
2031{
Dan Stozafc4e2022016-02-23 11:43:19 -08002032 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002033
2034 auto display = mDisplays.find(id);
2035 if (display == mDisplays.end()) {
2036 return nullptr;
2037 }
2038
2039 return display->second.get();
2040}
2041
2042std::tuple<HWC2On1Adapter::Layer*, Error> HWC2On1Adapter::getLayer(
2043 hwc2_display_t displayId, hwc2_layer_t layerId)
2044{
2045 auto display = getDisplay(displayId);
2046 if (!display) {
2047 return std::make_tuple(static_cast<Layer*>(nullptr), Error::BadDisplay);
2048 }
2049
2050 auto layerEntry = mLayers.find(layerId);
2051 if (layerEntry == mLayers.end()) {
2052 return std::make_tuple(static_cast<Layer*>(nullptr), Error::BadLayer);
2053 }
2054
2055 auto layer = layerEntry->second;
2056 if (layer->getDisplay().getId() != displayId) {
2057 return std::make_tuple(static_cast<Layer*>(nullptr), Error::BadLayer);
2058 }
2059 return std::make_tuple(layer.get(), Error::None);
2060}
2061
2062void HWC2On1Adapter::populatePrimary()
2063{
2064 ALOGV("populatePrimary");
2065
Dan Stozafc4e2022016-02-23 11:43:19 -08002066 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002067
2068 auto display =
2069 std::make_shared<Display>(*this, HWC2::DisplayType::Physical);
2070 mHwc1DisplayMap[HWC_DISPLAY_PRIMARY] = display->getId();
2071 display->setHwc1Id(HWC_DISPLAY_PRIMARY);
2072 display->populateConfigs();
2073 mDisplays.emplace(display->getId(), std::move(display));
2074}
2075
2076bool HWC2On1Adapter::prepareAllDisplays()
2077{
2078 ATRACE_CALL();
2079
Dan Stozafc4e2022016-02-23 11:43:19 -08002080 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002081
2082 for (const auto& displayPair : mDisplays) {
2083 auto& display = displayPair.second;
2084 if (!display->prepare()) {
2085 return false;
2086 }
2087 }
2088
2089 if (mHwc1DisplayMap.count(0) == 0) {
2090 ALOGE("prepareAllDisplays: Unable to find primary HWC1 display");
2091 return false;
2092 }
2093
2094 // Always push the primary display
2095 std::vector<HWC2On1Adapter::Display::HWC1Contents> requestedContents;
2096 auto primaryDisplayId = mHwc1DisplayMap[HWC_DISPLAY_PRIMARY];
2097 auto& primaryDisplay = mDisplays[primaryDisplayId];
2098 auto primaryDisplayContents = primaryDisplay->cloneRequestedContents();
2099 requestedContents.push_back(std::move(primaryDisplayContents));
2100
2101 // Push the external display, if present
2102 if (mHwc1DisplayMap.count(HWC_DISPLAY_EXTERNAL) != 0) {
2103 auto externalDisplayId = mHwc1DisplayMap[HWC_DISPLAY_EXTERNAL];
2104 auto& externalDisplay = mDisplays[externalDisplayId];
2105 auto externalDisplayContents =
2106 externalDisplay->cloneRequestedContents();
2107 requestedContents.push_back(std::move(externalDisplayContents));
2108 } else {
2109 // Even if an external display isn't present, we still need to send
2110 // at least two displays down to HWC1
2111 requestedContents.push_back(nullptr);
2112 }
2113
2114 // Push the hardware virtual display, if supported and present
2115 if (mHwc1MinorVersion >= 3) {
2116 if (mHwc1DisplayMap.count(HWC_DISPLAY_VIRTUAL) != 0) {
2117 auto virtualDisplayId = mHwc1DisplayMap[HWC_DISPLAY_VIRTUAL];
2118 auto& virtualDisplay = mDisplays[virtualDisplayId];
2119 auto virtualDisplayContents =
2120 virtualDisplay->cloneRequestedContents();
2121 requestedContents.push_back(std::move(virtualDisplayContents));
2122 } else {
2123 requestedContents.push_back(nullptr);
2124 }
2125 }
2126
2127 mHwc1Contents.clear();
2128 for (auto& displayContents : requestedContents) {
2129 mHwc1Contents.push_back(displayContents.get());
2130 if (!displayContents) {
2131 continue;
2132 }
2133
2134 ALOGV("Display %zd layers:", mHwc1Contents.size() - 1);
2135 for (size_t l = 0; l < displayContents->numHwLayers; ++l) {
2136 auto& layer = displayContents->hwLayers[l];
2137 ALOGV(" %zd: %d", l, layer.compositionType);
2138 }
2139 }
2140
2141 ALOGV("Calling HWC1 prepare");
2142 {
2143 ATRACE_NAME("HWC1 prepare");
2144 mHwc1Device->prepare(mHwc1Device, mHwc1Contents.size(),
2145 mHwc1Contents.data());
2146 }
2147
2148 for (size_t c = 0; c < mHwc1Contents.size(); ++c) {
2149 auto& contents = mHwc1Contents[c];
2150 if (!contents) {
2151 continue;
2152 }
2153 ALOGV("Display %zd layers:", c);
2154 for (size_t l = 0; l < contents->numHwLayers; ++l) {
2155 ALOGV(" %zd: %d", l, contents->hwLayers[l].compositionType);
2156 }
2157 }
2158
2159 // Return the received contents to their respective displays
2160 for (size_t hwc1Id = 0; hwc1Id < mHwc1Contents.size(); ++hwc1Id) {
2161 if (mHwc1Contents[hwc1Id] == nullptr) {
2162 continue;
2163 }
2164
2165 auto displayId = mHwc1DisplayMap[hwc1Id];
2166 auto& display = mDisplays[displayId];
2167 display->setReceivedContents(std::move(requestedContents[hwc1Id]));
2168 }
2169
2170 return true;
2171}
2172
2173Error HWC2On1Adapter::setAllDisplays()
2174{
2175 ATRACE_CALL();
2176
Dan Stozafc4e2022016-02-23 11:43:19 -08002177 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002178
2179 // Make sure we're ready to validate
2180 for (size_t hwc1Id = 0; hwc1Id < mHwc1Contents.size(); ++hwc1Id) {
2181 if (mHwc1Contents[hwc1Id] == nullptr) {
2182 continue;
2183 }
2184
2185 auto displayId = mHwc1DisplayMap[hwc1Id];
2186 auto& display = mDisplays[displayId];
2187 Error error = display->set(*mHwc1Contents[hwc1Id]);
2188 if (error != Error::None) {
2189 ALOGE("setAllDisplays: Failed to set display %zd: %s", hwc1Id,
2190 to_string(error).c_str());
2191 return error;
2192 }
2193 }
2194
2195 ALOGV("Calling HWC1 set");
2196 {
2197 ATRACE_NAME("HWC1 set");
2198 mHwc1Device->set(mHwc1Device, mHwc1Contents.size(),
2199 mHwc1Contents.data());
2200 }
2201
2202 // Add retire and release fences
2203 for (size_t hwc1Id = 0; hwc1Id < mHwc1Contents.size(); ++hwc1Id) {
2204 if (mHwc1Contents[hwc1Id] == nullptr) {
2205 continue;
2206 }
2207
2208 auto displayId = mHwc1DisplayMap[hwc1Id];
2209 auto& display = mDisplays[displayId];
2210 auto retireFenceFd = mHwc1Contents[hwc1Id]->retireFenceFd;
2211 ALOGV("setAllDisplays: Adding retire fence %d to display %zd",
2212 retireFenceFd, hwc1Id);
2213 display->addRetireFence(mHwc1Contents[hwc1Id]->retireFenceFd);
2214 display->addReleaseFences(*mHwc1Contents[hwc1Id]);
2215 }
2216
2217 return Error::None;
2218}
2219
2220void HWC2On1Adapter::hwc1Invalidate()
2221{
2222 ALOGV("Received hwc1Invalidate");
2223
Dan Stozafc4e2022016-02-23 11:43:19 -08002224 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002225
2226 // If the HWC2-side callback hasn't been registered yet, buffer this until
2227 // it is registered
2228 if (mCallbacks.count(Callback::Refresh) == 0) {
2229 mHasPendingInvalidate = true;
2230 return;
2231 }
2232
2233 const auto& callbackInfo = mCallbacks[Callback::Refresh];
2234 std::vector<hwc2_display_t> displays;
2235 for (const auto& displayPair : mDisplays) {
2236 displays.emplace_back(displayPair.first);
2237 }
2238
2239 // Call back without the state lock held
2240 lock.unlock();
2241
2242 auto refresh = reinterpret_cast<HWC2_PFN_REFRESH>(callbackInfo.pointer);
2243 for (auto display : displays) {
2244 refresh(callbackInfo.data, display);
2245 }
2246}
2247
2248void HWC2On1Adapter::hwc1Vsync(int hwc1DisplayId, int64_t timestamp)
2249{
2250 ALOGV("Received hwc1Vsync(%d, %" PRId64 ")", hwc1DisplayId, timestamp);
2251
Dan Stozafc4e2022016-02-23 11:43:19 -08002252 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002253
2254 // If the HWC2-side callback hasn't been registered yet, buffer this until
2255 // it is registered
2256 if (mCallbacks.count(Callback::Vsync) == 0) {
2257 mPendingVsyncs.emplace_back(hwc1DisplayId, timestamp);
2258 return;
2259 }
2260
2261 if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) {
2262 ALOGE("hwc1Vsync: Couldn't find display for HWC1 id %d", hwc1DisplayId);
2263 return;
2264 }
2265
2266 const auto& callbackInfo = mCallbacks[Callback::Vsync];
2267 auto displayId = mHwc1DisplayMap[hwc1DisplayId];
2268
2269 // Call back without the state lock held
2270 lock.unlock();
2271
2272 auto vsync = reinterpret_cast<HWC2_PFN_VSYNC>(callbackInfo.pointer);
2273 vsync(callbackInfo.data, displayId, timestamp);
2274}
2275
2276void HWC2On1Adapter::hwc1Hotplug(int hwc1DisplayId, int connected)
2277{
2278 ALOGV("Received hwc1Hotplug(%d, %d)", hwc1DisplayId, connected);
2279
2280 if (hwc1DisplayId != HWC_DISPLAY_EXTERNAL) {
2281 ALOGE("hwc1Hotplug: Received hotplug for non-external display");
2282 return;
2283 }
2284
Dan Stozafc4e2022016-02-23 11:43:19 -08002285 std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
Dan Stozac6998d22015-09-24 17:03:36 -07002286
2287 // If the HWC2-side callback hasn't been registered yet, buffer this until
2288 // it is registered
2289 if (mCallbacks.count(Callback::Hotplug) == 0) {
2290 mPendingHotplugs.emplace_back(hwc1DisplayId, connected);
2291 return;
2292 }
2293
2294 hwc2_display_t displayId = UINT64_MAX;
2295 if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) {
2296 if (connected == 0) {
2297 ALOGW("hwc1Hotplug: Received disconnect for unconnected display");
2298 return;
2299 }
2300
2301 // Create a new display on connect
2302 auto display = std::make_shared<HWC2On1Adapter::Display>(*this,
2303 HWC2::DisplayType::Physical);
2304 display->setHwc1Id(HWC_DISPLAY_EXTERNAL);
2305 display->populateConfigs();
2306 displayId = display->getId();
2307 mHwc1DisplayMap[HWC_DISPLAY_EXTERNAL] = displayId;
2308 mDisplays.emplace(displayId, std::move(display));
2309 } else {
2310 if (connected != 0) {
2311 ALOGW("hwc1Hotplug: Received connect for previously connected "
2312 "display");
2313 return;
2314 }
2315
2316 // Disconnect an existing display
2317 displayId = mHwc1DisplayMap[hwc1DisplayId];
2318 mHwc1DisplayMap.erase(HWC_DISPLAY_EXTERNAL);
2319 mDisplays.erase(displayId);
2320 }
2321
2322 const auto& callbackInfo = mCallbacks[Callback::Hotplug];
2323
2324 // Call back without the state lock held
2325 lock.unlock();
2326
2327 auto hotplug = reinterpret_cast<HWC2_PFN_HOTPLUG>(callbackInfo.pointer);
2328 auto hwc2Connected = (connected == 0) ?
2329 HWC2::Connection::Disconnected : HWC2::Connection::Connected;
2330 hotplug(callbackInfo.data, displayId, static_cast<int32_t>(hwc2Connected));
2331}
2332
2333} // namespace android