blob: 560f2102b5247c92cba728b7618dac2261d32507 [file] [log] [blame]
John Reck0ff95c92022-12-08 11:45:29 -05001/*
2 * Copyright (C) 2022 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_TAG "Gralloc5"
18#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
20#include <ui/Gralloc5.h>
21
John Reckd727e9c2023-12-08 11:30:37 -050022#include <aidl/android/hardware/graphics/allocator/AllocationError.h>
John Reck0ff95c92022-12-08 11:45:29 -050023#include <aidlcommonsupport/NativeHandle.h>
24#include <android/binder_manager.h>
25#include <android/hardware/graphics/mapper/utils/IMapperMetadataTypes.h>
26#include <binder/IPCThreadState.h>
27#include <dlfcn.h>
28#include <ui/FatVector.h>
29#include <vndksupport/linker.h>
30
31using namespace aidl::android::hardware::graphics::allocator;
32using namespace aidl::android::hardware::graphics::common;
33using namespace ::android::hardware::graphics::mapper;
34
John Reckedcd8852023-07-25 16:03:44 -040035using ADataspace = aidl::android::hardware::graphics::common::Dataspace;
36using APixelFormat = aidl::android::hardware::graphics::common::PixelFormat;
37
John Reck0ff95c92022-12-08 11:45:29 -050038namespace android {
39
40static const auto kIAllocatorServiceName = IAllocator::descriptor + std::string("/default");
41static const auto kIAllocatorMinimumVersion = 2;
John Reckedcd8852023-07-25 16:03:44 -040042constexpr const char* kStandardMetadataName =
43 "android.hardware.graphics.common.StandardMetadataType";
John Reck0ff95c92022-12-08 11:45:29 -050044
45// TODO(b/72323293, b/72703005): Remove these invalid bits from callers
46static constexpr uint64_t kRemovedUsageBits = static_cast<uint64_t>((1 << 10) | (1 << 13));
47
48typedef AIMapper_Error (*AIMapper_loadIMapperFn)(AIMapper *_Nullable *_Nonnull outImplementation);
49
50struct Gralloc5 {
51 std::shared_ptr<IAllocator> allocator;
52 AIMapper *mapper = nullptr;
53};
54
55static std::shared_ptr<IAllocator> waitForAllocator() {
56 if (__builtin_available(android 31, *)) {
57 if (!AServiceManager_isDeclared(kIAllocatorServiceName.c_str())) {
58 return nullptr;
59 }
60 auto allocator = IAllocator::fromBinder(
61 ndk::SpAIBinder(AServiceManager_waitForService(kIAllocatorServiceName.c_str())));
62 if (!allocator) {
63 ALOGE("AIDL IAllocator declared but failed to get service");
64 return nullptr;
65 }
66
67 int32_t version = 0;
68 if (!allocator->getInterfaceVersion(&version).isOk()) {
69 ALOGE("Failed to query interface version");
70 return nullptr;
71 }
72 if (version < kIAllocatorMinimumVersion) {
73 return nullptr;
74 }
75 return allocator;
76 } else {
77 // TODO: LOG_ALWAYS_FATAL("libui is not backwards compatible");
78 return nullptr;
79 }
80}
81
82static void *loadIMapperLibrary() {
83 static void *imapperLibrary = []() -> void * {
84 auto allocator = waitForAllocator();
85 std::string mapperSuffix;
86 auto status = allocator->getIMapperLibrarySuffix(&mapperSuffix);
87 if (!status.isOk()) {
88 ALOGE("Failed to get IMapper library suffix");
89 return nullptr;
90 }
91
92 std::string lib_name = "mapper." + mapperSuffix + ".so";
93 void *so = android_load_sphal_library(lib_name.c_str(), RTLD_LOCAL | RTLD_NOW);
94 if (!so) {
95 ALOGE("Failed to load %s", lib_name.c_str());
96 }
97 return so;
98 }();
99 return imapperLibrary;
100}
101
102static const Gralloc5 &getInstance() {
103 static Gralloc5 instance = []() {
104 auto allocator = waitForAllocator();
105 if (!allocator) {
106 return Gralloc5{};
107 }
108 void *so = loadIMapperLibrary();
109 if (!so) {
110 return Gralloc5{};
111 }
112 auto loadIMapper = (AIMapper_loadIMapperFn)dlsym(so, "AIMapper_loadIMapper");
113 AIMapper *mapper = nullptr;
114 AIMapper_Error error = loadIMapper(&mapper);
115 if (error != AIMAPPER_ERROR_NONE) {
116 ALOGE("AIMapper_loadIMapper failed %d", error);
117 return Gralloc5{};
118 }
119 return Gralloc5{std::move(allocator), mapper};
120 }();
121 return instance;
122}
123
124template <StandardMetadataType T>
125static auto getStandardMetadata(AIMapper *mapper, buffer_handle_t bufferHandle)
126 -> decltype(StandardMetadata<T>::value::decode(nullptr, 0)) {
127 using Value = typename StandardMetadata<T>::value;
128 // TODO: Tune for common-case better
129 FatVector<uint8_t, 128> buffer;
130 int32_t sizeRequired = mapper->v5.getStandardMetadata(bufferHandle, static_cast<int64_t>(T),
131 buffer.data(), buffer.size());
132 if (sizeRequired < 0) {
133 ALOGW_IF(-AIMAPPER_ERROR_UNSUPPORTED != sizeRequired,
134 "Unexpected error %d from valid getStandardMetadata call", -sizeRequired);
135 return std::nullopt;
136 }
137 if ((size_t)sizeRequired > buffer.size()) {
138 buffer.resize(sizeRequired);
139 sizeRequired = mapper->v5.getStandardMetadata(bufferHandle, static_cast<int64_t>(T),
140 buffer.data(), buffer.size());
141 }
142 if (sizeRequired < 0 || (size_t)sizeRequired > buffer.size()) {
143 ALOGW("getStandardMetadata failed, received %d with buffer size %zd", sizeRequired,
144 buffer.size());
145 // Generate a fail type
146 return std::nullopt;
147 }
148 return Value::decode(buffer.data(), sizeRequired);
149}
150
151template <StandardMetadataType T>
152static AIMapper_Error setStandardMetadata(AIMapper *mapper, buffer_handle_t bufferHandle,
153 const typename StandardMetadata<T>::value_type &value) {
154 using Value = typename StandardMetadata<T>::value;
155 int32_t sizeRequired = Value::encode(value, nullptr, 0);
156 if (sizeRequired < 0) {
157 ALOGW("Failed to calculate required size");
158 return static_cast<AIMapper_Error>(-sizeRequired);
159 }
160 FatVector<uint8_t, 128> buffer;
161 buffer.resize(sizeRequired);
162 sizeRequired = Value::encode(value, buffer.data(), buffer.size());
163 if (sizeRequired < 0 || (size_t)sizeRequired > buffer.size()) {
164 ALOGW("Failed to encode with calculated size %d; buffer size %zd", sizeRequired,
165 buffer.size());
166 return static_cast<AIMapper_Error>(-sizeRequired);
167 }
168 return mapper->v5.setStandardMetadata(bufferHandle, static_cast<int64_t>(T), buffer.data(),
169 sizeRequired);
170}
171
172Gralloc5Allocator::Gralloc5Allocator(const Gralloc5Mapper &mapper) : mMapper(mapper) {
173 mAllocator = getInstance().allocator;
174}
175
176bool Gralloc5Allocator::isLoaded() const {
177 return mAllocator != nullptr;
178}
179
180static uint64_t getValidUsageBits() {
181 static const uint64_t validUsageBits = []() -> uint64_t {
182 uint64_t bits = 0;
183 for (const auto bit : ndk::enum_range<BufferUsage>{}) {
184 bits |= static_cast<int64_t>(bit);
185 }
186 return bits;
187 }();
188 return validUsageBits | kRemovedUsageBits;
189}
190
191static std::optional<BufferDescriptorInfo> makeDescriptor(std::string requestorName, uint32_t width,
192 uint32_t height, PixelFormat format,
193 uint32_t layerCount, uint64_t usage) {
194 uint64_t validUsageBits = getValidUsageBits();
195 if (usage & ~validUsageBits) {
196 ALOGE("buffer descriptor contains invalid usage bits 0x%" PRIx64, usage & ~validUsageBits);
197 return std::nullopt;
198 }
199
200 BufferDescriptorInfo descriptorInfo{
201 .width = static_cast<int32_t>(width),
202 .height = static_cast<int32_t>(height),
203 .layerCount = static_cast<int32_t>(layerCount),
204 .format = static_cast<::aidl::android::hardware::graphics::common::PixelFormat>(format),
205 .usage = static_cast<BufferUsage>(usage),
206 };
207 auto nameLength = std::min(requestorName.length(), descriptorInfo.name.size() - 1);
208 memcpy(descriptorInfo.name.data(), requestorName.data(), nameLength);
209 requestorName.data()[nameLength] = 0;
210 return descriptorInfo;
211}
212
213std::string Gralloc5Allocator::dumpDebugInfo(bool less) const {
214 return mMapper.dumpBuffers(less);
215}
216
217status_t Gralloc5Allocator::allocate(std::string requestorName, uint32_t width, uint32_t height,
218 android::PixelFormat format, uint32_t layerCount,
John Reckd727e9c2023-12-08 11:30:37 -0500219 uint64_t usage, uint32_t* outStride,
220 buffer_handle_t* outBufferHandles, bool importBuffers) const {
221 auto result = allocate(GraphicBufferAllocator::AllocationRequest{
222 .importBuffer = importBuffers,
223 .width = width,
224 .height = height,
225 .format = format,
226 .layerCount = layerCount,
227 .usage = usage,
228 .requestorName = requestorName,
229 });
230
231 *outStride = result.stride;
232 outBufferHandles[0] = result.handle;
233 return result.status;
234}
235
236GraphicBufferAllocator::AllocationResult Gralloc5Allocator::allocate(
237 const GraphicBufferAllocator::AllocationRequest& request) const {
238 auto descriptorInfo = makeDescriptor(request.requestorName, request.width, request.height,
239 request.format, request.layerCount, request.usage);
John Reck0ff95c92022-12-08 11:45:29 -0500240 if (!descriptorInfo) {
John Reckd727e9c2023-12-08 11:30:37 -0500241 return GraphicBufferAllocator::AllocationResult{BAD_VALUE};
242 }
243
244 descriptorInfo->additionalOptions.reserve(request.extras.size());
245 for (const auto& option : request.extras) {
246 ExtendableType type;
247 type.name = option.name;
248 type.value = option.value;
249 descriptorInfo->additionalOptions.push_back(std::move(type));
John Reck0ff95c92022-12-08 11:45:29 -0500250 }
251
252 AllocationResult result;
John Reckd727e9c2023-12-08 11:30:37 -0500253 auto status = mAllocator->allocate2(*descriptorInfo, 1, &result);
John Reck0ff95c92022-12-08 11:45:29 -0500254 if (!status.isOk()) {
255 auto error = status.getExceptionCode();
256 if (error == EX_SERVICE_SPECIFIC) {
John Reckd727e9c2023-12-08 11:30:37 -0500257 switch (static_cast<AllocationError>(status.getServiceSpecificError())) {
258 case AllocationError::BAD_DESCRIPTOR:
259 error = BAD_VALUE;
260 break;
261 case AllocationError::NO_RESOURCES:
262 error = NO_MEMORY;
263 break;
264 default:
265 error = UNKNOWN_ERROR;
266 break;
267 }
John Reck0ff95c92022-12-08 11:45:29 -0500268 }
John Reckd727e9c2023-12-08 11:30:37 -0500269 return GraphicBufferAllocator::AllocationResult{error};
John Reck0ff95c92022-12-08 11:45:29 -0500270 }
271
John Reckd727e9c2023-12-08 11:30:37 -0500272 GraphicBufferAllocator::AllocationResult ret{OK};
273 if (request.importBuffer) {
274 auto handle = makeFromAidl(result.buffers[0]);
275 auto error = mMapper.importBuffer(handle, &ret.handle);
276 native_handle_delete(handle);
277 if (error != NO_ERROR) {
278 return GraphicBufferAllocator::AllocationResult{error};
John Reck0ff95c92022-12-08 11:45:29 -0500279 }
280 } else {
John Reckd727e9c2023-12-08 11:30:37 -0500281 ret.handle = dupFromAidl(result.buffers[0]);
282 if (!ret.handle) {
283 return GraphicBufferAllocator::AllocationResult{NO_MEMORY};
John Reck0ff95c92022-12-08 11:45:29 -0500284 }
285 }
286
John Reckd727e9c2023-12-08 11:30:37 -0500287 ret.stride = result.stride;
John Reck0ff95c92022-12-08 11:45:29 -0500288
289 // Release all the resources held by AllocationResult (specifically any remaining FDs)
290 result = {};
291 // make sure the kernel driver sees BC_FREE_BUFFER and closes the fds now
292 // TODO: Re-enable this at some point if it's necessary. We can't do it now because libui
293 // is marked apex_available (b/214400477) and libbinder isn't (which of course is correct)
294 // IPCThreadState::self()->flushCommands();
295
John Reckd727e9c2023-12-08 11:30:37 -0500296 return ret;
John Reck0ff95c92022-12-08 11:45:29 -0500297}
298
299void Gralloc5Mapper::preload() {
300 // TODO(b/261858155): Implement. We can't bounce off of IAllocator for this because zygote can't
301 // use binder. So when an alternate strategy of retrieving the library prefix is available,
302 // use that here.
303}
304
305Gralloc5Mapper::Gralloc5Mapper() {
306 mMapper = getInstance().mapper;
307}
308
309bool Gralloc5Mapper::isLoaded() const {
310 return mMapper != nullptr && mMapper->version >= AIMAPPER_VERSION_5;
311}
312
John Reckedcd8852023-07-25 16:03:44 -0400313static bool isStandardMetadata(AIMapper_MetadataType metadataType) {
314 return strcmp(kStandardMetadataName, metadataType.name) == 0;
315}
316
317struct DumpBufferResult {
318 uint64_t bufferId;
319 std::string name;
320 uint64_t width;
321 uint64_t height;
322 uint64_t layerCount;
323 APixelFormat pixelFormatRequested;
324 uint32_t pixelFormatFourCC;
325 uint64_t pixelFormatModifier;
326 BufferUsage usage;
327 ADataspace dataspace;
328 uint64_t allocationSize;
329 uint64_t protectedContent;
330 ExtendableType compression;
331 ExtendableType interlaced;
332 ExtendableType chromaSiting;
333 std::vector<ui::PlaneLayout> planeLayouts;
334};
335
336#define DECODE_TO(name, output) \
337 case StandardMetadataType::name: \
338 output = StandardMetadata<StandardMetadataType::name>::value ::decode(value, valueSize) \
339 .value(); \
340 break
341
342static void dumpBufferCommon(DumpBufferResult* outResult, AIMapper_MetadataType metadataType,
343 const void* value, size_t valueSize) {
344 if (!isStandardMetadata(metadataType)) {
345 return;
346 }
347 StandardMetadataType type = (StandardMetadataType)metadataType.value;
348 switch (type) {
349 DECODE_TO(BUFFER_ID, outResult->bufferId);
350 DECODE_TO(NAME, outResult->name);
351 DECODE_TO(WIDTH, outResult->width);
352 DECODE_TO(HEIGHT, outResult->height);
353 DECODE_TO(LAYER_COUNT, outResult->layerCount);
354 DECODE_TO(PIXEL_FORMAT_REQUESTED, outResult->pixelFormatRequested);
355 DECODE_TO(PIXEL_FORMAT_FOURCC, outResult->pixelFormatFourCC);
356 DECODE_TO(PIXEL_FORMAT_MODIFIER, outResult->pixelFormatModifier);
357 DECODE_TO(USAGE, outResult->usage);
358 DECODE_TO(DATASPACE, outResult->dataspace);
359 DECODE_TO(ALLOCATION_SIZE, outResult->allocationSize);
360 DECODE_TO(PROTECTED_CONTENT, outResult->protectedContent);
361 DECODE_TO(COMPRESSION, outResult->compression);
362 DECODE_TO(INTERLACED, outResult->interlaced);
363 DECODE_TO(CHROMA_SITING, outResult->chromaSiting);
364 DECODE_TO(PLANE_LAYOUTS, outResult->planeLayouts);
365 default:
366 break;
367 }
368}
369
370#undef DECODE_TO
371
372template <typename EnumT, typename = std::enable_if_t<std::is_enum<EnumT>{}>>
373constexpr std::underlying_type_t<EnumT> to_underlying(EnumT e) noexcept {
374 return static_cast<std::underlying_type_t<EnumT>>(e);
375}
376
377static void writeDumpToStream(const DumpBufferResult& bufferDump, std::ostream& outDump,
378 bool less) {
379 double allocationSizeKiB = static_cast<double>(bufferDump.allocationSize) / 1024;
380
381 outDump << "+ name:" << bufferDump.name << ", id:" << bufferDump.bufferId
382 << ", size:" << std::fixed << allocationSizeKiB << "KiB, w/h:" << bufferDump.width
383 << "x" << bufferDump.height << ", usage: 0x" << std::hex
384 << to_underlying(bufferDump.usage) << std::dec
385 << ", req fmt:" << to_underlying(bufferDump.pixelFormatRequested)
386 << ", fourcc/mod:" << bufferDump.pixelFormatFourCC << "/"
387 << bufferDump.pixelFormatModifier << ", dataspace: 0x" << std::hex
388 << to_underlying(bufferDump.dataspace) << std::dec << ", compressed: ";
389
390 if (less) {
391 bool isCompressed = !gralloc4::isStandardCompression(bufferDump.compression) ||
392 (gralloc4::getStandardCompressionValue(bufferDump.compression) !=
393 ui::Compression::NONE);
394 outDump << std::boolalpha << isCompressed << "\n";
395 } else {
396 outDump << gralloc4::getCompressionName(bufferDump.compression) << "\n";
397 }
398
399 if (!less) {
400 bool firstPlane = true;
401 for (const auto& planeLayout : bufferDump.planeLayouts) {
402 if (firstPlane) {
403 firstPlane = false;
404 outDump << "\tplanes: ";
405 } else {
406 outDump << "\t ";
407 }
408
409 for (size_t i = 0; i < planeLayout.components.size(); i++) {
410 const auto& planeLayoutComponent = planeLayout.components[i];
411 outDump << gralloc4::getPlaneLayoutComponentTypeName(planeLayoutComponent.type);
412 if (i < planeLayout.components.size() - 1) {
413 outDump << "/";
414 } else {
415 outDump << ":\t";
416 }
417 }
418 outDump << " w/h:" << planeLayout.widthInSamples << "x" << planeLayout.heightInSamples
419 << ", stride:" << planeLayout.strideInBytes
420 << " bytes, size:" << planeLayout.totalSizeInBytes;
421 outDump << ", inc:" << planeLayout.sampleIncrementInBits
422 << " bits, subsampling w/h:" << planeLayout.horizontalSubsampling << "x"
423 << planeLayout.verticalSubsampling;
424 outDump << "\n";
425 }
426
427 outDump << "\tlayer cnt: " << bufferDump.layerCount
428 << ", protected content: " << bufferDump.protectedContent
429 << ", interlaced: " << gralloc4::getInterlacedName(bufferDump.interlaced)
430 << ", chroma siting:" << gralloc4::getChromaSitingName(bufferDump.chromaSiting)
431 << "\n";
432 }
433}
434
John Reck0ff95c92022-12-08 11:45:29 -0500435std::string Gralloc5Mapper::dumpBuffer(buffer_handle_t bufferHandle, bool less) const {
John Reckedcd8852023-07-25 16:03:44 -0400436 DumpBufferResult bufferInfo;
437 AIMapper_DumpBufferCallback dumpBuffer = [](void* contextPtr,
438 AIMapper_MetadataType metadataType,
439 const void* _Nonnull value, size_t valueSize) {
440 DumpBufferResult* context = reinterpret_cast<DumpBufferResult*>(contextPtr);
441 dumpBufferCommon(context, metadataType, value, valueSize);
442 };
443 AIMapper_Error error = mMapper->v5.dumpBuffer(bufferHandle, dumpBuffer, &bufferInfo);
444 if (error != AIMAPPER_ERROR_NONE) {
445 ALOGE("Error dumping buffer: %d", error);
446 return std::string{};
447 }
448 std::ostringstream stream;
449 stream.precision(2);
450 writeDumpToStream(bufferInfo, stream, less);
451 return stream.str();
John Reck0ff95c92022-12-08 11:45:29 -0500452}
453
454std::string Gralloc5Mapper::dumpBuffers(bool less) const {
John Reckedcd8852023-07-25 16:03:44 -0400455 class DumpAllBuffersContext {
456 private:
457 bool mHasPending = false;
458 DumpBufferResult mPending;
459 std::vector<DumpBufferResult> mResults;
460
461 public:
462 DumpAllBuffersContext() { mResults.reserve(10); }
463
464 void commit() {
465 if (mHasPending) {
466 mResults.push_back(mPending);
467 mHasPending = false;
468 }
469 }
470
471 DumpBufferResult* write() {
472 mHasPending = true;
473 return &mPending;
474 }
475
476 const std::vector<DumpBufferResult>& results() {
477 commit();
478 return mResults;
479 }
480 } context;
481
482 AIMapper_BeginDumpBufferCallback beginCallback = [](void* contextPtr) {
483 DumpAllBuffersContext* context = reinterpret_cast<DumpAllBuffersContext*>(contextPtr);
484 context->commit();
485 };
486
487 AIMapper_DumpBufferCallback dumpBuffer = [](void* contextPtr,
488 AIMapper_MetadataType metadataType,
489 const void* _Nonnull value, size_t valueSize) {
490 DumpAllBuffersContext* context = reinterpret_cast<DumpAllBuffersContext*>(contextPtr);
491 dumpBufferCommon(context->write(), metadataType, value, valueSize);
492 };
493
494 AIMapper_Error error = mMapper->v5.dumpAllBuffers(beginCallback, dumpBuffer, &context);
495 if (error != AIMAPPER_ERROR_NONE) {
496 ALOGE("Error dumping buffers: %d", error);
497 return std::string{};
498 }
499 uint64_t totalAllocationSize = 0;
500 std::ostringstream stream;
501 stream.precision(2);
502 stream << "Imported gralloc buffers:\n";
503
504 for (const auto& bufferDump : context.results()) {
505 writeDumpToStream(bufferDump, stream, less);
506 totalAllocationSize += bufferDump.allocationSize;
507 }
508
509 double totalAllocationSizeKiB = static_cast<double>(totalAllocationSize) / 1024;
510 stream << "Total imported by gralloc: " << totalAllocationSizeKiB << "KiB\n";
511 return stream.str();
John Reck0ff95c92022-12-08 11:45:29 -0500512}
513
514status_t Gralloc5Mapper::importBuffer(const native_handle_t *rawHandle,
515 buffer_handle_t *outBufferHandle) const {
516 return mMapper->v5.importBuffer(rawHandle, outBufferHandle);
517}
518
519void Gralloc5Mapper::freeBuffer(buffer_handle_t bufferHandle) const {
520 mMapper->v5.freeBuffer(bufferHandle);
521}
522
523status_t Gralloc5Mapper::validateBufferSize(buffer_handle_t bufferHandle, uint32_t width,
524 uint32_t height, PixelFormat format,
525 uint32_t layerCount, uint64_t usage,
526 uint32_t stride) const {
527 {
528 auto value = getStandardMetadata<StandardMetadataType::WIDTH>(mMapper, bufferHandle);
529 if (width != value) {
530 ALOGW("Width didn't match, expected %d got %" PRId64, width, value.value_or(-1));
531 return BAD_VALUE;
532 }
533 }
534 {
535 auto value = getStandardMetadata<StandardMetadataType::HEIGHT>(mMapper, bufferHandle);
536 if (height != value) {
537 ALOGW("Height didn't match, expected %d got %" PRId64, height, value.value_or(-1));
538 return BAD_VALUE;
539 }
540 }
541 {
John Reck54a98142023-11-21 11:13:40 -0500542 auto expected = static_cast<APixelFormat>(format);
543 if (expected != APixelFormat::IMPLEMENTATION_DEFINED) {
544 auto value =
545 getStandardMetadata<StandardMetadataType::PIXEL_FORMAT_REQUESTED>(mMapper,
546 bufferHandle);
547 if (expected != value) {
548 ALOGW("Format didn't match, expected %d got %s", format,
549 value.has_value() ? toString(*value).c_str() : "<null>");
550 return BAD_VALUE;
551 }
John Reck0ff95c92022-12-08 11:45:29 -0500552 }
553 }
554 {
555 auto value = getStandardMetadata<StandardMetadataType::LAYER_COUNT>(mMapper, bufferHandle);
556 if (layerCount != value) {
557 ALOGW("Layer count didn't match, expected %d got %" PRId64, layerCount,
558 value.value_or(-1));
559 return BAD_VALUE;
560 }
561 }
John Reck47390ec2023-05-24 13:46:37 -0400562 // TODO: This can false-positive fail if the allocator adjusted the USAGE bits internally
563 // Investigate further & re-enable or remove, but for now ignoring usage should be OK
564 (void)usage;
565 // {
566 // auto value = getStandardMetadata<StandardMetadataType::USAGE>(mMapper, bufferHandle);
567 // if (static_cast<BufferUsage>(usage) != value) {
568 // ALOGW("Usage didn't match, expected %" PRIu64 " got %" PRId64, usage,
569 // static_cast<int64_t>(value.value_or(BufferUsage::CPU_READ_NEVER)));
570 // return BAD_VALUE;
571 // }
572 // }
John Reck0ff95c92022-12-08 11:45:29 -0500573 {
John Recke225b282023-03-24 16:15:17 -0400574 auto value = getStandardMetadata<StandardMetadataType::STRIDE>(mMapper, bufferHandle);
575 if (stride != value) {
576 ALOGW("Stride didn't match, expected %" PRIu32 " got %" PRId32, stride,
577 value.value_or(-1));
578 return BAD_VALUE;
579 }
John Reck0ff95c92022-12-08 11:45:29 -0500580 }
581 return OK;
582}
583
584void Gralloc5Mapper::getTransportSize(buffer_handle_t bufferHandle, uint32_t *outNumFds,
585 uint32_t *outNumInts) const {
586 mMapper->v5.getTransportSize(bufferHandle, outNumFds, outNumInts);
587}
588
589status_t Gralloc5Mapper::lock(buffer_handle_t bufferHandle, uint64_t usage, const Rect &bounds,
590 int acquireFence, void **outData, int32_t *outBytesPerPixel,
591 int32_t *outBytesPerStride) const {
John Reck434bc982023-12-19 17:04:07 -0500592 if (outBytesPerPixel) *outBytesPerPixel = -1;
593 if (outBytesPerStride) *outBytesPerStride = -1;
John Reck0ff95c92022-12-08 11:45:29 -0500594
595 auto status = mMapper->v5.lock(bufferHandle, usage, bounds, acquireFence, outData);
596
597 ALOGW_IF(status != AIMAPPER_ERROR_NONE, "lock(%p, ...) failed: %d", bufferHandle, status);
598 return static_cast<status_t>(status);
599}
600
601status_t Gralloc5Mapper::lock(buffer_handle_t bufferHandle, uint64_t usage, const Rect &bounds,
602 int acquireFence, android_ycbcr *outYcbcr) const {
603 if (!outYcbcr) {
604 return BAD_VALUE;
605 }
606
607 // TODO(b/262279301): Change the return type of ::unlock to unique_fd instead of int so that
608 // ignoring the return value "just works" instead
609 auto unlock = [this](buffer_handle_t bufferHandle) {
610 int fence = this->unlock(bufferHandle);
611 if (fence != -1) {
612 ::close(fence);
613 }
614 };
615
616 std::vector<ui::PlaneLayout> planeLayouts;
617 status_t error = getPlaneLayouts(bufferHandle, &planeLayouts);
618 if (error != NO_ERROR) {
619 return error;
620 }
621
622 void *data = nullptr;
623 error = lock(bufferHandle, usage, bounds, acquireFence, &data, nullptr, nullptr);
624 if (error != NO_ERROR) {
625 return error;
626 }
627
628 android_ycbcr ycbcr;
629
630 ycbcr.y = nullptr;
631 ycbcr.cb = nullptr;
632 ycbcr.cr = nullptr;
633 ycbcr.ystride = 0;
634 ycbcr.cstride = 0;
635 ycbcr.chroma_step = 0;
636
637 for (const auto &planeLayout : planeLayouts) {
638 for (const auto &planeLayoutComponent : planeLayout.components) {
639 if (!gralloc4::isStandardPlaneLayoutComponentType(planeLayoutComponent.type)) {
640 continue;
641 }
642
643 uint8_t *tmpData = static_cast<uint8_t *>(data) + planeLayout.offsetInBytes;
644
645 // Note that `offsetInBits` may not be a multiple of 8 for packed formats (e.g. P010)
646 // but we still want to point to the start of the first byte.
647 tmpData += (planeLayoutComponent.offsetInBits / 8);
648
649 uint64_t sampleIncrementInBytes;
650
651 auto type = static_cast<PlaneLayoutComponentType>(planeLayoutComponent.type.value);
652 switch (type) {
653 case PlaneLayoutComponentType::Y:
654 if ((ycbcr.y != nullptr) || (planeLayout.sampleIncrementInBits % 8 != 0)) {
655 unlock(bufferHandle);
656 return BAD_VALUE;
657 }
658 ycbcr.y = tmpData;
659 ycbcr.ystride = planeLayout.strideInBytes;
660 break;
661
662 case PlaneLayoutComponentType::CB:
663 case PlaneLayoutComponentType::CR:
664 if (planeLayout.sampleIncrementInBits % 8 != 0) {
665 unlock(bufferHandle);
666 return BAD_VALUE;
667 }
668
669 sampleIncrementInBytes = planeLayout.sampleIncrementInBits / 8;
670 if ((sampleIncrementInBytes != 1) && (sampleIncrementInBytes != 2) &&
671 (sampleIncrementInBytes != 4)) {
672 unlock(bufferHandle);
673 return BAD_VALUE;
674 }
675
676 if (ycbcr.cstride == 0 && ycbcr.chroma_step == 0) {
677 ycbcr.cstride = planeLayout.strideInBytes;
678 ycbcr.chroma_step = sampleIncrementInBytes;
679 } else {
680 if ((static_cast<int64_t>(ycbcr.cstride) != planeLayout.strideInBytes) ||
681 (ycbcr.chroma_step != sampleIncrementInBytes)) {
682 unlock(bufferHandle);
683 return BAD_VALUE;
684 }
685 }
686
687 if (type == PlaneLayoutComponentType::CB) {
688 if (ycbcr.cb != nullptr) {
689 unlock(bufferHandle);
690 return BAD_VALUE;
691 }
692 ycbcr.cb = tmpData;
693 } else {
694 if (ycbcr.cr != nullptr) {
695 unlock(bufferHandle);
696 return BAD_VALUE;
697 }
698 ycbcr.cr = tmpData;
699 }
700 break;
701 default:
702 break;
703 };
704 }
705 }
706
707 *outYcbcr = ycbcr;
708 return OK;
709}
710
711int Gralloc5Mapper::unlock(buffer_handle_t bufferHandle) const {
712 int fence = -1;
713 AIMapper_Error error = mMapper->v5.unlock(bufferHandle, &fence);
714 if (error != AIMAPPER_ERROR_NONE) {
715 ALOGW("unlock failed with error %d", error);
716 }
717 return fence;
718}
719
720status_t Gralloc5Mapper::isSupported(uint32_t width, uint32_t height, PixelFormat format,
721 uint32_t layerCount, uint64_t usage,
722 bool *outSupported) const {
723 auto descriptorInfo = makeDescriptor("", width, height, format, layerCount, usage);
724 if (!descriptorInfo) {
725 *outSupported = false;
726 return OK;
727 }
728 auto status = getInstance().allocator->isSupported(*descriptorInfo, outSupported);
729 if (!status.isOk()) {
730 ALOGW("IAllocator::isSupported error %d (%s)", status.getStatus(), status.getMessage());
731 *outSupported = false;
732 }
733 return OK;
734}
735
736status_t Gralloc5Mapper::getBufferId(buffer_handle_t bufferHandle, uint64_t *outBufferId) const {
737 auto value = getStandardMetadata<StandardMetadataType::BUFFER_ID>(mMapper, bufferHandle);
738 if (value.has_value()) {
739 *outBufferId = *value;
740 return OK;
741 }
742 return UNKNOWN_TRANSACTION;
743}
744
745status_t Gralloc5Mapper::getName(buffer_handle_t bufferHandle, std::string *outName) const {
746 auto value = getStandardMetadata<StandardMetadataType::NAME>(mMapper, bufferHandle);
747 if (value.has_value()) {
748 *outName = *value;
749 return OK;
750 }
751 return UNKNOWN_TRANSACTION;
752}
753
754status_t Gralloc5Mapper::getWidth(buffer_handle_t bufferHandle, uint64_t *outWidth) const {
755 auto value = getStandardMetadata<StandardMetadataType::WIDTH>(mMapper, bufferHandle);
756 if (value.has_value()) {
757 *outWidth = *value;
758 return OK;
759 }
760 return UNKNOWN_TRANSACTION;
761}
762
763status_t Gralloc5Mapper::getHeight(buffer_handle_t bufferHandle, uint64_t *outHeight) const {
764 auto value = getStandardMetadata<StandardMetadataType::HEIGHT>(mMapper, bufferHandle);
765 if (value.has_value()) {
766 *outHeight = *value;
767 return OK;
768 }
769 return UNKNOWN_TRANSACTION;
770}
771
772status_t Gralloc5Mapper::getLayerCount(buffer_handle_t bufferHandle,
773 uint64_t *outLayerCount) const {
774 auto value = getStandardMetadata<StandardMetadataType::LAYER_COUNT>(mMapper, bufferHandle);
775 if (value.has_value()) {
776 *outLayerCount = *value;
777 return OK;
778 }
779 return UNKNOWN_TRANSACTION;
780}
781
782status_t Gralloc5Mapper::getPixelFormatRequested(buffer_handle_t bufferHandle,
783 ui::PixelFormat *outPixelFormatRequested) const {
784 auto value = getStandardMetadata<StandardMetadataType::PIXEL_FORMAT_REQUESTED>(mMapper,
785 bufferHandle);
786 if (value.has_value()) {
787 *outPixelFormatRequested = static_cast<ui::PixelFormat>(*value);
788 return OK;
789 }
790 return UNKNOWN_TRANSACTION;
791}
792
793status_t Gralloc5Mapper::getPixelFormatFourCC(buffer_handle_t bufferHandle,
794 uint32_t *outPixelFormatFourCC) const {
795 auto value =
796 getStandardMetadata<StandardMetadataType::PIXEL_FORMAT_FOURCC>(mMapper, bufferHandle);
797 if (value.has_value()) {
798 *outPixelFormatFourCC = *value;
799 return OK;
800 }
801 return UNKNOWN_TRANSACTION;
802}
803
804status_t Gralloc5Mapper::getPixelFormatModifier(buffer_handle_t bufferHandle,
805 uint64_t *outPixelFormatModifier) const {
806 auto value =
807 getStandardMetadata<StandardMetadataType::PIXEL_FORMAT_MODIFIER>(mMapper, bufferHandle);
808 if (value.has_value()) {
809 *outPixelFormatModifier = *value;
810 return OK;
811 }
812 return UNKNOWN_TRANSACTION;
813}
814
815status_t Gralloc5Mapper::getUsage(buffer_handle_t bufferHandle, uint64_t *outUsage) const {
816 auto value = getStandardMetadata<StandardMetadataType::USAGE>(mMapper, bufferHandle);
817 if (value.has_value()) {
818 *outUsage = static_cast<uint64_t>(*value);
819 return OK;
820 }
821 return UNKNOWN_TRANSACTION;
822}
823
824status_t Gralloc5Mapper::getAllocationSize(buffer_handle_t bufferHandle,
825 uint64_t *outAllocationSize) const {
826 auto value = getStandardMetadata<StandardMetadataType::ALLOCATION_SIZE>(mMapper, bufferHandle);
827 if (value.has_value()) {
828 *outAllocationSize = *value;
829 return OK;
830 }
831 return UNKNOWN_TRANSACTION;
832}
833
834status_t Gralloc5Mapper::getProtectedContent(buffer_handle_t bufferHandle,
835 uint64_t *outProtectedContent) const {
836 auto value =
837 getStandardMetadata<StandardMetadataType::PROTECTED_CONTENT>(mMapper, bufferHandle);
838 if (value.has_value()) {
839 *outProtectedContent = *value;
840 return OK;
841 }
842 return UNKNOWN_TRANSACTION;
843}
844
845status_t Gralloc5Mapper::getCompression(
846 buffer_handle_t bufferHandle,
847 aidl::android::hardware::graphics::common::ExtendableType *outCompression) const {
848 auto value = getStandardMetadata<StandardMetadataType::COMPRESSION>(mMapper, bufferHandle);
849 if (value.has_value()) {
850 *outCompression = *value;
851 return OK;
852 }
853 return UNKNOWN_TRANSACTION;
854}
855
856status_t Gralloc5Mapper::getCompression(buffer_handle_t bufferHandle,
857 ui::Compression *outCompression) const {
858 auto value = getStandardMetadata<StandardMetadataType::COMPRESSION>(mMapper, bufferHandle);
859 if (!value.has_value()) {
860 return UNKNOWN_TRANSACTION;
861 }
862 if (!gralloc4::isStandardCompression(*value)) {
863 return BAD_TYPE;
864 }
865 *outCompression = gralloc4::getStandardCompressionValue(*value);
866 return OK;
867}
868
869status_t Gralloc5Mapper::getInterlaced(
870 buffer_handle_t bufferHandle,
871 aidl::android::hardware::graphics::common::ExtendableType *outInterlaced) const {
872 auto value = getStandardMetadata<StandardMetadataType::INTERLACED>(mMapper, bufferHandle);
873 if (value.has_value()) {
874 *outInterlaced = *value;
875 return OK;
876 }
877 return UNKNOWN_TRANSACTION;
878}
879
880status_t Gralloc5Mapper::getInterlaced(buffer_handle_t bufferHandle,
881 ui::Interlaced *outInterlaced) const {
882 if (!outInterlaced) {
883 return BAD_VALUE;
884 }
885 ExtendableType interlaced;
886 status_t error = getInterlaced(bufferHandle, &interlaced);
887 if (error) {
888 return error;
889 }
890 if (!gralloc4::isStandardInterlaced(interlaced)) {
891 return BAD_TYPE;
892 }
893 *outInterlaced = gralloc4::getStandardInterlacedValue(interlaced);
894 return NO_ERROR;
895}
896
897status_t Gralloc5Mapper::getChromaSiting(
898 buffer_handle_t bufferHandle,
899 aidl::android::hardware::graphics::common::ExtendableType *outChromaSiting) const {
900 auto value = getStandardMetadata<StandardMetadataType::CHROMA_SITING>(mMapper, bufferHandle);
901 if (value.has_value()) {
902 *outChromaSiting = *value;
903 return OK;
904 }
905 return UNKNOWN_TRANSACTION;
906}
907
908status_t Gralloc5Mapper::getChromaSiting(buffer_handle_t bufferHandle,
909 ui::ChromaSiting *outChromaSiting) const {
910 if (!outChromaSiting) {
911 return BAD_VALUE;
912 }
913 ExtendableType chromaSiting;
914 status_t error = getChromaSiting(bufferHandle, &chromaSiting);
915 if (error) {
916 return error;
917 }
918 if (!gralloc4::isStandardChromaSiting(chromaSiting)) {
919 return BAD_TYPE;
920 }
921 *outChromaSiting = gralloc4::getStandardChromaSitingValue(chromaSiting);
922 return NO_ERROR;
923}
924
925status_t Gralloc5Mapper::getPlaneLayouts(buffer_handle_t bufferHandle,
926 std::vector<ui::PlaneLayout> *outPlaneLayouts) const {
927 auto value = getStandardMetadata<StandardMetadataType::PLANE_LAYOUTS>(mMapper, bufferHandle);
928 if (value.has_value()) {
929 *outPlaneLayouts = *value;
930 return OK;
931 }
932 return UNKNOWN_TRANSACTION;
933}
934
935status_t Gralloc5Mapper::getDataspace(buffer_handle_t bufferHandle,
936 ui::Dataspace *outDataspace) const {
937 auto value = getStandardMetadata<StandardMetadataType::DATASPACE>(mMapper, bufferHandle);
938 if (value.has_value()) {
939 *outDataspace = static_cast<ui::Dataspace>(*value);
940 return OK;
941 }
942 return UNKNOWN_TRANSACTION;
943}
944
945status_t Gralloc5Mapper::setDataspace(buffer_handle_t bufferHandle, ui::Dataspace dataspace) const {
946 return setStandardMetadata<StandardMetadataType::DATASPACE>(mMapper, bufferHandle,
947 static_cast<Dataspace>(dataspace));
948}
949
950status_t Gralloc5Mapper::getBlendMode(buffer_handle_t bufferHandle,
951 ui::BlendMode *outBlendMode) const {
952 auto value = getStandardMetadata<StandardMetadataType::BLEND_MODE>(mMapper, bufferHandle);
953 if (value.has_value()) {
954 *outBlendMode = static_cast<ui::BlendMode>(*value);
955 return OK;
956 }
957 return UNKNOWN_TRANSACTION;
958}
959
960status_t Gralloc5Mapper::getSmpte2086(buffer_handle_t bufferHandle,
961 std::optional<ui::Smpte2086> *outSmpte2086) const {
962 auto value = getStandardMetadata<StandardMetadataType::SMPTE2086>(mMapper, bufferHandle);
963 if (value.has_value()) {
964 *outSmpte2086 = *value;
965 return OK;
966 }
967 return UNKNOWN_TRANSACTION;
968}
969
970status_t Gralloc5Mapper::setSmpte2086(buffer_handle_t bufferHandle,
971 std::optional<ui::Smpte2086> smpte2086) const {
972 return setStandardMetadata<StandardMetadataType::SMPTE2086>(mMapper, bufferHandle, smpte2086);
973}
974
975status_t Gralloc5Mapper::getCta861_3(buffer_handle_t bufferHandle,
976 std::optional<ui::Cta861_3> *outCta861_3) const {
977 auto value = getStandardMetadata<StandardMetadataType::CTA861_3>(mMapper, bufferHandle);
978 if (value.has_value()) {
979 *outCta861_3 = *value;
980 return OK;
981 }
982 return UNKNOWN_TRANSACTION;
983}
984
985status_t Gralloc5Mapper::setCta861_3(buffer_handle_t bufferHandle,
986 std::optional<ui::Cta861_3> cta861_3) const {
987 return setStandardMetadata<StandardMetadataType::CTA861_3>(mMapper, bufferHandle, cta861_3);
988}
989
990status_t Gralloc5Mapper::getSmpte2094_40(
991 buffer_handle_t bufferHandle, std::optional<std::vector<uint8_t>> *outSmpte2094_40) const {
992 auto value = getStandardMetadata<StandardMetadataType::SMPTE2094_40>(mMapper, bufferHandle);
993 if (value.has_value()) {
994 *outSmpte2094_40 = std::move(*value);
995 return OK;
996 }
997 return UNKNOWN_TRANSACTION;
998}
999
1000status_t Gralloc5Mapper::setSmpte2094_40(buffer_handle_t bufferHandle,
1001 std::optional<std::vector<uint8_t>> smpte2094_40) const {
1002 return setStandardMetadata<StandardMetadataType::SMPTE2094_40>(mMapper, bufferHandle,
1003 smpte2094_40);
1004}
1005
1006status_t Gralloc5Mapper::getSmpte2094_10(
1007 buffer_handle_t bufferHandle, std::optional<std::vector<uint8_t>> *outSmpte2094_10) const {
1008 auto value = getStandardMetadata<StandardMetadataType::SMPTE2094_10>(mMapper, bufferHandle);
1009 if (value.has_value()) {
1010 *outSmpte2094_10 = std::move(*value);
1011 return OK;
1012 }
1013 return UNKNOWN_TRANSACTION;
1014}
1015
1016status_t Gralloc5Mapper::setSmpte2094_10(buffer_handle_t bufferHandle,
1017 std::optional<std::vector<uint8_t>> smpte2094_10) const {
1018 return setStandardMetadata<StandardMetadataType::SMPTE2094_10>(mMapper, bufferHandle,
1019 smpte2094_10);
1020}
1021
John Reck0ff95c92022-12-08 11:45:29 -05001022} // namespace android