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