diff options
author | Android Build Coastguard Worker <android-build-coastguard-worker@google.com> | 2022-05-11 05:03:31 +0000 |
---|---|---|
committer | Android Build Coastguard Worker <android-build-coastguard-worker@google.com> | 2022-05-11 05:03:31 +0000 |
commit | fe7340ee96d09c967787a04a41c25c71fab9c291 (patch) | |
tree | 8e2c640be06a05fdc28ced0de956702c43663f1d | |
parent | 2427e6be40ba0c178da80cf73c2ec6a514a6d6fa (diff) | |
parent | 42f13403a20257cfa97dd490a67681117a6da1b2 (diff) | |
download | drm_hwcomposer-android13-mainline-media-swcodec-release.tar.gz |
Snap for 8570526 from 42f13403a20257cfa97dd490a67681117a6da1b2 to mainline-media-swcodec-releaseaml_swc_331911000aml_swc_331712000aml_swc_331612000aml_swc_331511000aml_swc_331410000aml_swc_331318000aml_swc_331116000aml_swc_331012020android13-mainline-media-swcodec-release
Change-Id: Ic258c74812bbf6328fa6567c58d272384692016a
118 files changed, 13422 insertions, 6513 deletions
diff --git a/.gitlab-ci-checkcommit.sh b/.ci/.gitlab-ci-checkcommit.sh index c1c524d..c9c2e49 100755 --- a/.gitlab-ci-checkcommit.sh +++ b/.ci/.gitlab-ci-checkcommit.sh @@ -50,9 +50,15 @@ git log --pretty='%h' FETCH_HEAD..HEAD | while read h; do exit 1 fi - git show "$h" -- | clang-format-diff-5.0 -p 1 -style=file > format-fixup.patch - if [ -s format-fixup.patch ]; then - cat format-fixup.patch >&2 + git show "$h" -- | clang-format-diff-13 -p 1 -style=file > /tmp/format-fixup.patch + if [ -s /tmp/format-fixup.patch ]; then + cat /tmp/format-fixup.patch >&2 + exit 1 + fi + + find -name "*.bp" -exec bpfmt -d -s {} \; > /tmp/bpfmt.patch + if [ -s /tmp/bpfmt.patch ]; then + cat /tmp/bpfmt.patch >&2 exit 1 fi done diff --git a/.ci/Makefile b/.ci/Makefile new file mode 100644 index 0000000..a0e4b73 --- /dev/null +++ b/.ci/Makefile @@ -0,0 +1,158 @@ + +INCLUDE_DIRS := . ../libdrm/include/drm include ./.ci/android_headers ./tests/test_include +SYSTEM_INCLUDE_DIRS := /usr/include/libdrm + +CLANG := clang++-13 +CLANG_TIDY := clang-tidy-13 +OUT_DIR := /tmp/drm_hwcomposer/build +SRC_DIR := . + +CXXFLAGS := -fPIC -Wall -Wextra -Werror -DPLATFORM_SDK_VERSION=31 -D__ANDROID_API__=31 +CXXFLAGS += -D_LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS +CXXFLAGS += -fvisibility-inlines-hidden -std=gnu++17 -DHWC2_USE_CPP11 -DHWC2_INCLUDE_STRINGIFICATION -fno-rtti + +SKIP_FILES := \ + bufferinfo/BufferInfoMapperMetadata.cpp + +TIDY_FILES_OVERRIDE := \ + bufferinfo/legacy/BufferInfoImagination.cpp:COARSE \ + bufferinfo/legacy/BufferInfoLibdrm.cpp:COARSE \ + bufferinfo/legacy/BufferInfoMaliHisi.cpp:COARSE \ + bufferinfo/legacy/BufferInfoMaliMediatek.cpp:COARSE \ + bufferinfo/legacy/BufferInfoMaliMeson.cpp:COARSE \ + bufferinfo/legacy/BufferInfoMinigbm.cpp:COARSE \ + drm/DrmFbImporter.h:FINE \ + drm/DrmMode.h:COARSE \ + drm/DrmProperty.h:COARSE \ + drm/DrmUnique.h:FINE \ + drm/DrmProperty.cpp:COARSE \ + drm/VSyncWorker.cpp:COARSE \ + hwc2_device/DrmHwcTwo.cpp:COARSE \ + hwc2_device/DrmHwcTwo.h:COARSE \ + hwc2_device/HwcDisplay.cpp:COARSE \ + hwc2_device/HwcDisplay.h:COARSE \ + tests/worker_test.cpp:COARSE \ + utils/Worker.h:COARSE \ + utils/UniqueFd.h:FINE \ + utils/log.h:FINE \ + utils/properties.h:FINE \ + +TIDY_CHECKS_FINE := * \ + -llvmlibc* -fuchsia-* -altera-* \ + -llvm-header-guard \ + -cppcoreguidelines-pro-type-vararg \ + -hicpp-vararg \ + -hicpp-signed-bitwise \ + +TIDY_CHECKS_NORMAL := \ + $(TIDY_CHECKS_FINE) \ + -hicpp* \ + -bugprone-easily-swappable-parameters \ + -cppcoreguidelines-special-member-functions \ + -cppcoreguidelines-avoid-c-arrays \ + -cppcoreguidelines-pro-bounds-array-to-pointer-decay \ + -cppcoreguidelines-pro-bounds-constant-array-index \ + -cppcoreguidelines-avoid-magic-numbers \ + -google-readability-braces-around-statements \ + -google-readability-casting \ + -misc-non-private-member-variables-in-classes \ + -modernize-avoid-c-arrays \ + -modernize-use-nodiscard \ + -modernize-use-trailing-return-type \ + -readability-braces-around-statements \ + +TIDY_CHECKS_COARSE := \ + $(TIDY_CHECKS_NORMAL) \ + -cppcoreguidelines-non-private-member-variables-in-classes \ + -cppcoreguidelines-pro-bounds-pointer-arithmetic \ + -cppcoreguidelines-pro-type-cstyle-cast \ + -cppcoreguidelines-pro-type-reinterpret-cast \ + -cppcoreguidelines-pro-type-static-cast-downcast \ + -cppcoreguidelines-pro-type-union-access \ + -cppcoreguidelines-macro-usage \ + -readability-convert-member-functions-to-static \ + -readability-implicit-bool-conversion \ + -readability-identifier-naming \ + -readability-magic-numbers \ + +.PHONY: all build tidy clean + +all: build tidy + +clean: + rm -rf $(OUT_DIR)/ + +# Build + +BUILD_FILES_AUTO := $(shell find -L $(SRC_DIR) -not -path '*/\.*' -not -path '*/tests/test_include/*' -path '*.cpp') +SKIP_FILES_path := $(foreach file,$(SKIP_FILES),$(SRC_DIR)/$(file)) + +BUILD_FILES := $(subst ./,,$(filter-out $(SKIP_FILES_path),$(BUILD_FILES_AUTO))) + +_OBJ := $(BUILD_FILES:.cpp=.o) +OBJ := $(patsubst %,$(OUT_DIR)/%,$(_OBJ)) + +DEPS := $(patsubst %.cpp,$(OUT_DIR)/%.d,$(BUILD_FILES)) + +build: $(OBJ) + +CXXARGS := $(foreach dir,$(INCLUDE_DIRS),-I$(SRC_DIR)/$(dir)) $(foreach dir,$(SYSTEM_INCLUDE_DIRS),-I$(dir)) $(CXXFLAGS) + +$(OUT_DIR)/%.o: $(SRC_DIR)/%.cpp + mkdir -p $(dir $@) + $(CLANG) $< $(CXXARGS) -c -o $@ + +$(OUT_DIR)/%.d: $(SRC_DIR)/%.cpp + mkdir -p $(dir $@) + $(CLANG) $(CXXARGS) $< -MM -MT $(OUT_DIR)/$(patsubst %.cpp,%.o,$<) -o $@ + +# TIDY +TIDY_FILES_AUTO := $(shell find -L $(SRC_DIR) -not -path '*/\.*' -not -path '*/tests/test_include/*' \( -path '*.cpp' -o -path '*.h' \)) + +TIDY_FILES_AUTO_filtered := $(filter-out $(SKIP_FILES_path),$(TIDY_FILES_AUTO)) + +TIDY_FILES_OVERRIDE_path := $(foreach pair,$(TIDY_FILES_OVERRIDE),$(SRC_DIR)/$(pair)) + +TIDY_FILES_OVERRIDE_name_only := $(foreach pair,$(TIDY_FILES_OVERRIDE_path),$(word 1, $(subst :, ,$(pair)))) + +TIDY_FILES := $(sort $(TIDY_FILES_AUTO_filtered) $(TIDY_FILES_OVERRIDE_name_only)) + +space := $(subst ,, ) +comma := , + +TIDY_ARGS_NONE := --checks="-*,llvm-include-order" +TIDY_ARGS_ := --checks="-*,llvm-include-order" +TIDY_ARGS_FINE := --checks="$(subst $(space),$(comma),$(strip $(TIDY_CHECKS_FINE)))" +TIDY_ARGS_NORMAL := --checks="$(subst $(space),$(comma),$(strip $(TIDY_CHECKS_NORMAL)))" +TIDY_ARGS_COARSE := --checks="$(subst $(space),$(comma),$(strip $(TIDY_CHECKS_COARSE)))" + +define process-tidy + +_TARG := $(OUT_DIR)/$1.tidy.ts +_DEP := $(SRC_DIR)/$1 + +TIDY_DEPS += $(_TARG) + +TIDY_LEVEL_1 := $$(strip $$(foreach pair,$$(TIDY_FILES_OVERRIDE_path),$$(if $$(filter $$(word 1, $$(subst :, ,$$(pair))),$1),$$(word 2, $$(subst :, ,$$(pair))),))) + +TIDY_LEVEL_2 := $$(if $$(TIDY_LEVEL_1),$$(TIDY_LEVEL_1),NORMAL) + +TIDY_ARGS := $$(TIDY_ARGS_$$(TIDY_LEVEL_2)) + +$$(_TARG): _DEP := $$(_DEP) +$$(_TARG): _TARG := $$(_TARG) +$$(_TARG): TIDY_ARGS := $$(TIDY_ARGS) +$$(_TARG): $$(_DEP) + mkdir -p $$(dir $$(_TARG)) + $$(CLANG_TIDY) $$(_DEP) $$(TIDY_ARGS) -- -x c++ $$(CXXARGS) -Wno-pragma-once-outside-header + touch $$(_TARG) + +endef + +$(foreach file,$(TIDY_FILES),$(eval $(call process-tidy,$(file)))) + +tidy: $(TIDY_DEPS) + +ifneq ($(MAKECMDGOALS), clean) +-include $(DEPS) +endif diff --git a/.ci/android_headers/cutils/compiler.h b/.ci/android_headers/cutils/compiler.h new file mode 100644 index 0000000..5754666 --- /dev/null +++ b/.ci/android_headers/cutils/compiler.h @@ -0,0 +1,45 @@ +// clang-format off +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_CUTILS_COMPILER_H +#define ANDROID_CUTILS_COMPILER_H + +/* + * helps the compiler's optimizer predicting branches + */ + +#ifdef __cplusplus +# define CC_LIKELY( exp ) (__builtin_expect( !!(exp), true )) +# define CC_UNLIKELY( exp ) (__builtin_expect( !!(exp), false )) +#else +# define CC_LIKELY( exp ) (__builtin_expect( !!(exp), 1 )) +# define CC_UNLIKELY( exp ) (__builtin_expect( !!(exp), 0 )) +#endif + +/** + * exports marked symbols + * + * if used on a C++ class declaration, this macro must be inserted + * after the "class" keyword. For instance: + * + * template <typename TYPE> + * class ANDROID_API Singleton { } + */ + +#define ANDROID_API __attribute__((visibility("default"))) + +#endif // ANDROID_CUTILS_COMPILER_H diff --git a/.ci/android_headers/cutils/native_handle.h b/.ci/android_headers/cutils/native_handle.h new file mode 100644 index 0000000..4f500f6 --- /dev/null +++ b/.ci/android_headers/cutils/native_handle.h @@ -0,0 +1,107 @@ +// clang-format off +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_HANDLE_H_ +#define NATIVE_HANDLE_H_ + +#include <stdalign.h> + +#ifdef __cplusplus +extern "C" { +#endif + +#define NATIVE_HANDLE_MAX_FDS 1024 +#define NATIVE_HANDLE_MAX_INTS 1024 + +/* Declare a char array for use with native_handle_init */ +#define NATIVE_HANDLE_DECLARE_STORAGE(name, maxFds, maxInts) \ + alignas(native_handle_t) char (name)[ \ + sizeof(native_handle_t) + sizeof(int) * ((maxFds) + (maxInts))] + +typedef struct native_handle +{ + int version; /* sizeof(native_handle_t) */ + int numFds; /* number of file-descriptors at &data[0] */ + int numInts; /* number of ints at &data[numFds] */ +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wzero-length-array" +#endif + int data[0]; /* numFds + numInts ints */ +#if defined(__clang__) +#pragma clang diagnostic pop +#endif +} native_handle_t; + +typedef const native_handle_t* buffer_handle_t; + +/* + * native_handle_close + * + * closes the file descriptors contained in this native_handle_t + * + * return 0 on success, or a negative error code on failure + * + */ +int native_handle_close(const native_handle_t* h); + +/* + * native_handle_init + * + * Initializes a native_handle_t from storage. storage must be declared with + * NATIVE_HANDLE_DECLARE_STORAGE. numFds and numInts must not respectively + * exceed maxFds and maxInts used to declare the storage. + */ +native_handle_t* native_handle_init(char* storage, int numFds, int numInts); + +/* + * native_handle_create + * + * creates a native_handle_t and initializes it. must be destroyed with + * native_handle_delete(). Note that numFds must be <= NATIVE_HANDLE_MAX_FDS, + * numInts must be <= NATIVE_HANDLE_MAX_INTS, and both must be >= 0. + * + */ +native_handle_t* native_handle_create(int numFds, int numInts); + +/* + * native_handle_clone + * + * creates a native_handle_t and initializes it from another native_handle_t. + * Must be destroyed with native_handle_delete(). + * + */ +native_handle_t* native_handle_clone(const native_handle_t* handle); + +/* + * native_handle_delete + * + * frees a native_handle_t allocated with native_handle_create(). + * This ONLY frees the memory allocated for the native_handle_t, but doesn't + * close the file descriptors; which can be achieved with native_handle_close(). + * + * return 0 on success, or a negative error code on failure + * + */ +int native_handle_delete(native_handle_t* h); + + +#ifdef __cplusplus +} +#endif + +#endif /* NATIVE_HANDLE_H_ */ diff --git a/.ci/android_headers/cutils/trace.h b/.ci/android_headers/cutils/trace.h new file mode 100644 index 0000000..54265a7 --- /dev/null +++ b/.ci/android_headers/cutils/trace.h @@ -0,0 +1,247 @@ +// clang-format off +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _LIBS_CUTILS_TRACE_H +#define _LIBS_CUTILS_TRACE_H + +#include <inttypes.h> +#include <stdatomic.h> +#include <stdbool.h> +#include <stdint.h> +#include <stdio.h> +#include <sys/cdefs.h> +#include <sys/types.h> +#include <unistd.h> +#include <cutils/compiler.h> + +__BEGIN_DECLS + +/** + * The ATRACE_TAG macro can be defined before including this header to trace + * using one of the tags defined below. It must be defined to one of the + * following ATRACE_TAG_* macros. The trace tag is used to filter tracing in + * userland to avoid some of the runtime cost of tracing when it is not desired. + * + * Defining ATRACE_TAG to be ATRACE_TAG_ALWAYS will result in the tracing always + * being enabled - this should ONLY be done for debug code, as userland tracing + * has a performance cost even when the trace is not being recorded. Defining + * ATRACE_TAG to be ATRACE_TAG_NEVER or leaving ATRACE_TAG undefined will result + * in the tracing always being disabled. + * + * ATRACE_TAG_HAL should be bitwise ORed with the relevant tags for tracing + * within a hardware module. For example a camera hardware module would set: + * #define ATRACE_TAG (ATRACE_TAG_CAMERA | ATRACE_TAG_HAL) + * + * Keep these in sync with frameworks/base/core/java/android/os/Trace.java. + */ +#define ATRACE_TAG_NEVER 0 // This tag is never enabled. +#define ATRACE_TAG_ALWAYS (1<<0) // This tag is always enabled. +#define ATRACE_TAG_GRAPHICS (1<<1) +#define ATRACE_TAG_INPUT (1<<2) +#define ATRACE_TAG_VIEW (1<<3) +#define ATRACE_TAG_WEBVIEW (1<<4) +#define ATRACE_TAG_WINDOW_MANAGER (1<<5) +#define ATRACE_TAG_ACTIVITY_MANAGER (1<<6) +#define ATRACE_TAG_SYNC_MANAGER (1<<7) +#define ATRACE_TAG_AUDIO (1<<8) +#define ATRACE_TAG_VIDEO (1<<9) +#define ATRACE_TAG_CAMERA (1<<10) +#define ATRACE_TAG_HAL (1<<11) +#define ATRACE_TAG_APP (1<<12) +#define ATRACE_TAG_RESOURCES (1<<13) +#define ATRACE_TAG_DALVIK (1<<14) +#define ATRACE_TAG_RS (1<<15) +#define ATRACE_TAG_BIONIC (1<<16) +#define ATRACE_TAG_POWER (1<<17) +#define ATRACE_TAG_PACKAGE_MANAGER (1<<18) +#define ATRACE_TAG_SYSTEM_SERVER (1<<19) +#define ATRACE_TAG_DATABASE (1<<20) +#define ATRACE_TAG_NETWORK (1<<21) +#define ATRACE_TAG_ADB (1<<22) +#define ATRACE_TAG_VIBRATOR (1<<23) +#define ATRACE_TAG_AIDL (1<<24) +#define ATRACE_TAG_NNAPI (1<<25) +#define ATRACE_TAG_RRO (1<<26) +#define ATRACE_TAG_LAST ATRACE_TAG_RRO + +// Reserved for initialization. +#define ATRACE_TAG_NOT_READY (1ULL<<63) + +#define ATRACE_TAG_VALID_MASK ((ATRACE_TAG_LAST - 1) | ATRACE_TAG_LAST) + +#ifndef ATRACE_TAG +#define ATRACE_TAG ATRACE_TAG_NEVER +#elif ATRACE_TAG > ATRACE_TAG_VALID_MASK +#error ATRACE_TAG must be defined to be one of the tags defined in cutils/trace.h +#endif + +/** + * Opens the trace file for writing and reads the property for initial tags. + * The atrace.tags.enableflags property sets the tags to trace. + * This function should not be explicitly called, the first call to any normal + * trace function will cause it to be run safely. + */ +void atrace_setup(); + +/** + * If tracing is ready, set atrace_enabled_tags to the system property + * debug.atrace.tags.enableflags. Can be used as a sysprop change callback. + */ +void atrace_update_tags(); + +/** + * Set whether the process is debuggable. By default the process is not + * considered debuggable. If the process is not debuggable then application- + * level tracing is not allowed unless the ro.debuggable system property is + * set to '1'. + */ +void atrace_set_debuggable(bool debuggable); + +/** + * Set whether tracing is enabled for the current process. This is used to + * prevent tracing within the Zygote process. + */ +void atrace_set_tracing_enabled(bool enabled); + +/** + * This is always set to false. This forces code that uses an old version + * of this header to always call into atrace_setup, in which we call + * atrace_init unconditionally. + */ +extern atomic_bool atrace_is_ready; + +/** + * Set of ATRACE_TAG flags to trace for, initialized to ATRACE_TAG_NOT_READY. + * A value of zero indicates setup has failed. + * Any other nonzero value indicates setup has succeeded, and tracing is on. + */ +extern uint64_t atrace_enabled_tags; + +/** + * Handle to the kernel's trace buffer, initialized to -1. + * Any other value indicates setup has succeeded, and is a valid fd for tracing. + */ +extern int atrace_marker_fd; + +/** + * atrace_init readies the process for tracing by opening the trace_marker file. + * Calling any trace function causes this to be run, so calling it is optional. + * This can be explicitly run to avoid setup delay on first trace function. + */ +#define ATRACE_INIT() atrace_init() +#define ATRACE_GET_ENABLED_TAGS() atrace_get_enabled_tags() + +void atrace_init(); +uint64_t atrace_get_enabled_tags(); + +/** + * Test if a given tag is currently enabled. + * Returns nonzero if the tag is enabled, otherwise zero. + * It can be used as a guard condition around more expensive trace calculations. + */ +#define ATRACE_ENABLED() atrace_is_tag_enabled(ATRACE_TAG) +static inline uint64_t atrace_is_tag_enabled(uint64_t tag) +{ + return atrace_get_enabled_tags() & tag; +} + +/** + * Trace the beginning of a context. name is used to identify the context. + * This is often used to time function execution. + */ +#define ATRACE_BEGIN(name) atrace_begin(ATRACE_TAG, name) +static inline void atrace_begin(uint64_t tag, const char* name) +{ + if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) { + void atrace_begin_body(const char*); + atrace_begin_body(name); + } +} + +/** + * Trace the end of a context. + * This should match up (and occur after) a corresponding ATRACE_BEGIN. + */ +#define ATRACE_END() atrace_end(ATRACE_TAG) +static inline void atrace_end(uint64_t tag) +{ + if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) { + void atrace_end_body(); + atrace_end_body(); + } +} + +/** + * Trace the beginning of an asynchronous event. Unlike ATRACE_BEGIN/ATRACE_END + * contexts, asynchronous events do not need to be nested. The name describes + * the event, and the cookie provides a unique identifier for distinguishing + * simultaneous events. The name and cookie used to begin an event must be + * used to end it. + */ +#define ATRACE_ASYNC_BEGIN(name, cookie) \ + atrace_async_begin(ATRACE_TAG, name, cookie) +static inline void atrace_async_begin(uint64_t tag, const char* name, + int32_t cookie) +{ + if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) { + void atrace_async_begin_body(const char*, int32_t); + atrace_async_begin_body(name, cookie); + } +} + +/** + * Trace the end of an asynchronous event. + * This should have a corresponding ATRACE_ASYNC_BEGIN. + */ +#define ATRACE_ASYNC_END(name, cookie) atrace_async_end(ATRACE_TAG, name, cookie) +static inline void atrace_async_end(uint64_t tag, const char* name, int32_t cookie) +{ + if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) { + void atrace_async_end_body(const char*, int32_t); + atrace_async_end_body(name, cookie); + } +} + +/** + * Traces an integer counter value. name is used to identify the counter. + * This can be used to track how a value changes over time. + */ +#define ATRACE_INT(name, value) atrace_int(ATRACE_TAG, name, value) +static inline void atrace_int(uint64_t tag, const char* name, int32_t value) +{ + if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) { + void atrace_int_body(const char*, int32_t); + atrace_int_body(name, value); + } +} + +/** + * Traces a 64-bit integer counter value. name is used to identify the + * counter. This can be used to track how a value changes over time. + */ +#define ATRACE_INT64(name, value) atrace_int64(ATRACE_TAG, name, value) +static inline void atrace_int64(uint64_t tag, const char* name, int64_t value) +{ + if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) { + void atrace_int64_body(const char*, int64_t); + atrace_int64_body(name, value); + } +} + +__END_DECLS + +#endif // _LIBS_CUTILS_TRACE_H diff --git a/.ci/android_headers/gralloc_handle.h b/.ci/android_headers/gralloc_handle.h new file mode 100644 index 0000000..4a7c9dd --- /dev/null +++ b/.ci/android_headers/gralloc_handle.h @@ -0,0 +1,112 @@ +// clang-format off +/* + * Copyright (C) 2010-2011 Chia-I Wu <olvaffe@gmail.com> + * Copyright (C) 2010-2011 LunarG Inc. + * Copyright (C) 2016 Linaro, Ltd., Rob Herring <robh@kernel.org> + * Copyright (C) 2018 Collabora, Robert Foss <robert.foss@collabora.com> + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#ifndef __ANDROID_GRALLOC_HANDLE_H__ +#define __ANDROID_GRALLOC_HANDLE_H__ + +#include <cutils/native_handle.h> +#include <stdint.h> + +/* support users of drm_gralloc/gbm_gralloc */ +#define gralloc_gbm_handle_t gralloc_handle_t +#define gralloc_drm_handle_t gralloc_handle_t + +struct gralloc_handle_t { + native_handle_t base; + + /* dma-buf file descriptor + * Must be located first since, native_handle_t is allocated + * using native_handle_create(), which allocates space for + * sizeof(native_handle_t) + sizeof(int) * (numFds + numInts) + * numFds = GRALLOC_HANDLE_NUM_FDS + * numInts = GRALLOC_HANDLE_NUM_INTS + * Where numFds represents the number of FDs and + * numInts represents the space needed for the + * remainder of this struct. + * And the FDs are expected to be found first following + * native_handle_t. + */ + int prime_fd; + + /* api variables */ + uint32_t magic; /* differentiate between allocator impls */ + uint32_t version; /* api version */ + + uint32_t width; /* width of buffer in pixels */ + uint32_t height; /* height of buffer in pixels */ + uint32_t format; /* pixel format (Android) */ + uint32_t usage; /* android libhardware usage flags */ + + uint32_t stride; /* the stride in bytes */ + int data_owner; /* owner of data (for validation) */ + uint64_t modifier __attribute__((aligned(8))); /* buffer modifiers */ + + union { + void *data; /* pointer to struct gralloc_gbm_bo_t */ + uint64_t reserved; + } __attribute__((aligned(8))); +}; + +#define GRALLOC_HANDLE_VERSION 4 +#define GRALLOC_HANDLE_MAGIC 0x60585350 +#define GRALLOC_HANDLE_NUM_FDS 1 +#define GRALLOC_HANDLE_NUM_INTS ( \ + ((sizeof(struct gralloc_handle_t) - sizeof(native_handle_t))/sizeof(int)) \ + - GRALLOC_HANDLE_NUM_FDS) + +static inline struct gralloc_handle_t *gralloc_handle(buffer_handle_t handle) +{ + return (struct gralloc_handle_t *)handle; +} + +/** + * Create a buffer handle. + */ +static inline native_handle_t *gralloc_handle_create(int32_t width, + int32_t height, + int32_t hal_format, + int32_t usage) +{ + struct gralloc_handle_t *handle; + native_handle_t *nhandle = native_handle_create(GRALLOC_HANDLE_NUM_FDS, + GRALLOC_HANDLE_NUM_INTS); + + if (!nhandle) + return NULL; + + handle = gralloc_handle(nhandle); + handle->magic = GRALLOC_HANDLE_MAGIC; + handle->version = GRALLOC_HANDLE_VERSION; + handle->width = width; + handle->height = height; + handle->format = hal_format; + handle->usage = usage; + handle->prime_fd = -1; + + return nhandle; +} + +#endif diff --git a/.ci/android_headers/hardware/gralloc.h b/.ci/android_headers/hardware/gralloc.h new file mode 100644 index 0000000..260140e --- /dev/null +++ b/.ci/android_headers/hardware/gralloc.h @@ -0,0 +1,451 @@ +// clang-format off +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef ANDROID_GRALLOC_INTERFACE_H +#define ANDROID_GRALLOC_INTERFACE_H + +#include <system/graphics.h> +#include <hardware/hardware.h> + +#include <stdint.h> +#include <sys/cdefs.h> +#include <sys/types.h> + +#include <cutils/native_handle.h> + +#include <hardware/hardware.h> +#if 0 /* Header below is not used by drm_hwcomposer */ +#include <hardware/fb.h> +#endif + +__BEGIN_DECLS + +/** + * Module versioning information for the Gralloc hardware module, based on + * gralloc_module_t.common.module_api_version. + * + * Version History: + * + * GRALLOC_MODULE_API_VERSION_0_1: + * Initial Gralloc hardware module API. + * + * GRALLOC_MODULE_API_VERSION_0_2: + * Add support for flexible YCbCr format with (*lock_ycbcr)() method. + * + * GRALLOC_MODULE_API_VERSION_0_3: + * Add support for fence passing to/from lock/unlock. + */ + +#define GRALLOC_MODULE_API_VERSION_0_1 HARDWARE_MODULE_API_VERSION(0, 1) +#define GRALLOC_MODULE_API_VERSION_0_2 HARDWARE_MODULE_API_VERSION(0, 2) +#define GRALLOC_MODULE_API_VERSION_0_3 HARDWARE_MODULE_API_VERSION(0, 3) + +#define GRALLOC_DEVICE_API_VERSION_0_1 HARDWARE_DEVICE_API_VERSION(0, 1) + +/** + * The id of this module + */ +#define GRALLOC_HARDWARE_MODULE_ID "gralloc" + +/** + * Name of the graphics device to open + */ + +#define GRALLOC_HARDWARE_GPU0 "gpu0" + +enum { + /* buffer is never read in software */ + GRALLOC_USAGE_SW_READ_NEVER = 0x00000000U, + /* buffer is rarely read in software */ + GRALLOC_USAGE_SW_READ_RARELY = 0x00000002U, + /* buffer is often read in software */ + GRALLOC_USAGE_SW_READ_OFTEN = 0x00000003U, + /* mask for the software read values */ + GRALLOC_USAGE_SW_READ_MASK = 0x0000000FU, + + /* buffer is never written in software */ + GRALLOC_USAGE_SW_WRITE_NEVER = 0x00000000U, + /* buffer is rarely written in software */ + GRALLOC_USAGE_SW_WRITE_RARELY = 0x00000020U, + /* buffer is often written in software */ + GRALLOC_USAGE_SW_WRITE_OFTEN = 0x00000030U, + /* mask for the software write values */ + GRALLOC_USAGE_SW_WRITE_MASK = 0x000000F0U, + + /* buffer will be used as an OpenGL ES texture */ + GRALLOC_USAGE_HW_TEXTURE = 0x00000100U, + /* buffer will be used as an OpenGL ES render target */ + GRALLOC_USAGE_HW_RENDER = 0x00000200U, + /* buffer will be used by the 2D hardware blitter */ + GRALLOC_USAGE_HW_2D = 0x00000400U, + /* buffer will be used by the HWComposer HAL module */ + GRALLOC_USAGE_HW_COMPOSER = 0x00000800U, + /* buffer will be used with the framebuffer device */ + GRALLOC_USAGE_HW_FB = 0x00001000U, + + /* buffer should be displayed full-screen on an external display when + * possible */ + GRALLOC_USAGE_EXTERNAL_DISP = 0x00002000U, + + /* Must have a hardware-protected path to external display sink for + * this buffer. If a hardware-protected path is not available, then + * either don't composite only this buffer (preferred) to the + * external sink, or (less desirable) do not route the entire + * composition to the external sink. */ + GRALLOC_USAGE_PROTECTED = 0x00004000U, + + /* buffer may be used as a cursor */ + GRALLOC_USAGE_CURSOR = 0x00008000U, + + /* buffer will be used with the HW video encoder */ + GRALLOC_USAGE_HW_VIDEO_ENCODER = 0x00010000U, + /* buffer will be written by the HW camera pipeline */ + GRALLOC_USAGE_HW_CAMERA_WRITE = 0x00020000U, + /* buffer will be read by the HW camera pipeline */ + GRALLOC_USAGE_HW_CAMERA_READ = 0x00040000U, + /* buffer will be used as part of zero-shutter-lag queue */ + GRALLOC_USAGE_HW_CAMERA_ZSL = 0x00060000U, + /* mask for the camera access values */ + GRALLOC_USAGE_HW_CAMERA_MASK = 0x00060000U, + /* mask for the software usage bit-mask */ + GRALLOC_USAGE_HW_MASK = 0x00071F00U, + + /* buffer will be used as a RenderScript Allocation */ + GRALLOC_USAGE_RENDERSCRIPT = 0x00100000U, + + /* Set by the consumer to indicate to the producer that they may attach a + * buffer that they did not detach from the BufferQueue. Will be filtered + * out by GRALLOC_USAGE_ALLOC_MASK, so gralloc modules will not need to + * handle this flag. */ + GRALLOC_USAGE_FOREIGN_BUFFERS = 0x00200000U, + + /* buffer will be used as input to HW HEIC image encoder */ + GRALLOC_USAGE_HW_IMAGE_ENCODER = 0x08000000U, + + /* Mask of all flags which could be passed to a gralloc module for buffer + * allocation. Any flags not in this mask do not need to be handled by + * gralloc modules. */ + GRALLOC_USAGE_ALLOC_MASK = ~(GRALLOC_USAGE_FOREIGN_BUFFERS), + + /* implementation-specific private usage flags */ + GRALLOC_USAGE_PRIVATE_0 = 0x10000000U, + GRALLOC_USAGE_PRIVATE_1 = 0x20000000U, + GRALLOC_USAGE_PRIVATE_2 = 0x40000000U, + GRALLOC_USAGE_PRIVATE_3 = 0x80000000U, + GRALLOC_USAGE_PRIVATE_MASK = 0xF0000000U, +}; + +/*****************************************************************************/ + +/** + * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM + * and the fields of this data structure must begin with hw_module_t + * followed by module specific information. + */ +typedef struct gralloc_module_t { + struct hw_module_t common; + + /* + * (*registerBuffer)() must be called before a buffer_handle_t that has not + * been created with (*alloc_device_t::alloc)() can be used. + * + * This is intended to be used with buffer_handle_t's that have been + * received in this process through IPC. + * + * This function checks that the handle is indeed a valid one and prepares + * it for use with (*lock)() and (*unlock)(). + * + * It is not necessary to call (*registerBuffer)() on a handle created + * with (*alloc_device_t::alloc)(). + * + * returns an error if this buffer_handle_t is not valid. + */ + int (*registerBuffer)(struct gralloc_module_t const* module, + buffer_handle_t handle); + + /* + * (*unregisterBuffer)() is called once this handle is no longer needed in + * this process. After this call, it is an error to call (*lock)(), + * (*unlock)(), or (*registerBuffer)(). + * + * This function doesn't close or free the handle itself; this is done + * by other means, usually through libcutils's native_handle_close() and + * native_handle_free(). + * + * It is an error to call (*unregisterBuffer)() on a buffer that wasn't + * explicitly registered first. + */ + int (*unregisterBuffer)(struct gralloc_module_t const* module, + buffer_handle_t handle); + + /* + * The (*lock)() method is called before a buffer is accessed for the + * specified usage. This call may block, for instance if the h/w needs + * to finish rendering or if CPU caches need to be synchronized. + * + * The caller promises to modify only pixels in the area specified + * by (l,t,w,h). + * + * The content of the buffer outside of the specified area is NOT modified + * by this call. + * + * If usage specifies GRALLOC_USAGE_SW_*, vaddr is filled with the address + * of the buffer in virtual memory. + * + * Note calling (*lock)() on HAL_PIXEL_FORMAT_YCbCr_*_888 buffers will fail + * and return -EINVAL. These buffers must be locked with (*lock_ycbcr)() + * instead. + * + * THREADING CONSIDERATIONS: + * + * It is legal for several different threads to lock a buffer from + * read access, none of the threads are blocked. + * + * However, locking a buffer simultaneously for write or read/write is + * undefined, but: + * - shall not result in termination of the process + * - shall not block the caller + * It is acceptable to return an error or to leave the buffer's content + * into an indeterminate state. + * + * If the buffer was created with a usage mask incompatible with the + * requested usage flags here, -EINVAL is returned. + * + */ + + int (*lock)(struct gralloc_module_t const* module, + buffer_handle_t handle, int usage, + int l, int t, int w, int h, + void** vaddr); + + + /* + * The (*unlock)() method must be called after all changes to the buffer + * are completed. + */ + + int (*unlock)(struct gralloc_module_t const* module, + buffer_handle_t handle); + + + /* reserved for future use */ + int (*perform)(struct gralloc_module_t const* module, + int operation, ... ); + + /* + * The (*lock_ycbcr)() method is like the (*lock)() method, with the + * difference that it fills a struct ycbcr with a description of the buffer + * layout, and zeroes out the reserved fields. + * + * If the buffer format is not compatible with a flexible YUV format (e.g. + * the buffer layout cannot be represented with the ycbcr struct), it + * will return -EINVAL. + * + * This method must work on buffers with HAL_PIXEL_FORMAT_YCbCr_*_888 + * if supported by the device, as well as with any other format that is + * requested by the multimedia codecs when they are configured with a + * flexible-YUV-compatible color-format with android native buffers. + * + * Note that this method may also be called on buffers of other formats, + * including non-YUV formats. + * + * Added in GRALLOC_MODULE_API_VERSION_0_2. + */ + + int (*lock_ycbcr)(struct gralloc_module_t const* module, + buffer_handle_t handle, int usage, + int l, int t, int w, int h, + struct android_ycbcr *ycbcr); + + /* + * The (*lockAsync)() method is like the (*lock)() method except + * that the buffer's sync fence object is passed into the lock + * call instead of requiring the caller to wait for completion. + * + * The gralloc implementation takes ownership of the fenceFd and + * is responsible for closing it when no longer needed. + * + * Added in GRALLOC_MODULE_API_VERSION_0_3. + */ + int (*lockAsync)(struct gralloc_module_t const* module, + buffer_handle_t handle, int usage, + int l, int t, int w, int h, + void** vaddr, int fenceFd); + + /* + * The (*unlockAsync)() method is like the (*unlock)() method + * except that a buffer sync fence object is returned from the + * lock call, representing the completion of any pending work + * performed by the gralloc implementation. + * + * The caller takes ownership of the fenceFd and is responsible + * for closing it when no longer needed. + * + * Added in GRALLOC_MODULE_API_VERSION_0_3. + */ + int (*unlockAsync)(struct gralloc_module_t const* module, + buffer_handle_t handle, int* fenceFd); + + /* + * The (*lockAsync_ycbcr)() method is like the (*lock_ycbcr)() + * method except that the buffer's sync fence object is passed + * into the lock call instead of requiring the caller to wait for + * completion. + * + * The gralloc implementation takes ownership of the fenceFd and + * is responsible for closing it when no longer needed. + * + * Added in GRALLOC_MODULE_API_VERSION_0_3. + */ + int (*lockAsync_ycbcr)(struct gralloc_module_t const* module, + buffer_handle_t handle, int usage, + int l, int t, int w, int h, + struct android_ycbcr *ycbcr, int fenceFd); + + /* getTransportSize(..., outNumFds, outNumInts) + * This function is mandatory on devices running IMapper2.1 or higher. + * + * Get the transport size of a buffer. An imported buffer handle is a raw + * buffer handle with the process-local runtime data appended. This + * function, for example, allows a caller to omit the process-local + * runtime data at the tail when serializing the imported buffer handle. + * + * Note that a client might or might not omit the process-local runtime + * data when sending an imported buffer handle. The mapper must support + * both cases on the receiving end. + */ + int32_t (*getTransportSize)( + struct gralloc_module_t const* module, buffer_handle_t handle, uint32_t *outNumFds, + uint32_t *outNumInts); + + /* validateBufferSize(..., w, h, format, usage, stride) + * This function is mandatory on devices running IMapper2.1 or higher. + * + * Validate that the buffer can be safely accessed by a caller who assumes + * the specified width, height, format, usage, and stride. This must at least validate + * that the buffer size is large enough. Validating the buffer against + * individual buffer attributes is optional. + */ + int32_t (*validateBufferSize)( + struct gralloc_module_t const* device, buffer_handle_t handle, + uint32_t w, uint32_t h, int32_t format, int usage, + uint32_t stride); + + /* reserved for future use */ + void* reserved_proc[1]; + +} gralloc_module_t; + +/*****************************************************************************/ + +/** + * Every device data structure must begin with hw_device_t + * followed by module specific public methods and attributes. + */ + +typedef struct alloc_device_t { + struct hw_device_t common; + + /* + * (*alloc)() Allocates a buffer in graphic memory with the requested + * parameters and returns a buffer_handle_t and the stride in pixels to + * allow the implementation to satisfy hardware constraints on the width + * of a pixmap (eg: it may have to be multiple of 8 pixels). + * The CALLER TAKES OWNERSHIP of the buffer_handle_t. + * + * If format is HAL_PIXEL_FORMAT_YCbCr_420_888, the returned stride must be + * 0, since the actual strides are available from the android_ycbcr + * structure. + * + * Returns 0 on success or -errno on error. + */ + + int (*alloc)(struct alloc_device_t* dev, + int w, int h, int format, int usage, + buffer_handle_t* handle, int* stride); + + /* + * (*free)() Frees a previously allocated buffer. + * Behavior is undefined if the buffer is still mapped in any process, + * but shall not result in termination of the program or security breaches + * (allowing a process to get access to another process' buffers). + * THIS FUNCTION TAKES OWNERSHIP of the buffer_handle_t which becomes + * invalid after the call. + * + * Returns 0 on success or -errno on error. + */ + int (*free)(struct alloc_device_t* dev, + buffer_handle_t handle); + + /* This hook is OPTIONAL. + * + * If non NULL it will be caused by SurfaceFlinger on dumpsys + */ + void (*dump)(struct alloc_device_t *dev, char *buff, int buff_len); + + void* reserved_proc[7]; +} alloc_device_t; + + +/** convenience API for opening and closing a supported device */ + +static inline int gralloc_open(const struct hw_module_t* module, + struct alloc_device_t** device) { + return module->methods->open(module, + GRALLOC_HARDWARE_GPU0, TO_HW_DEVICE_T_OPEN(device)); +} + +static inline int gralloc_close(struct alloc_device_t* device) { + return device->common.close(&device->common); +} + +/** + * map_usage_to_memtrack should be called after allocating a gralloc buffer. + * + * @param usage - it is the flag used when alloc function is called. + * + * This function maps the gralloc usage flags to appropriate memtrack bucket. + * GrallocHAL implementers and users should make an additional ION_IOCTL_TAG + * call using the memtrack tag returned by this function. This will help the + * in-kernel memtack to categorize the memory allocated by different processes + * according to their usage. + * + */ +static inline const char* map_usage_to_memtrack(uint32_t usage) { + usage &= GRALLOC_USAGE_ALLOC_MASK; + + if ((usage & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) { + return "camera"; + } else if ((usage & GRALLOC_USAGE_HW_VIDEO_ENCODER) != 0 || + (usage & GRALLOC_USAGE_EXTERNAL_DISP) != 0) { + return "video"; + } else if ((usage & GRALLOC_USAGE_HW_RENDER) != 0 || + (usage & GRALLOC_USAGE_HW_TEXTURE) != 0) { + return "gl"; + } else if ((usage & GRALLOC_USAGE_HW_CAMERA_READ) != 0) { + return "camera"; + } else if ((usage & GRALLOC_USAGE_SW_READ_MASK) != 0 || + (usage & GRALLOC_USAGE_SW_WRITE_MASK) != 0) { + return "cpu"; + } + return "graphics"; +} + +__END_DECLS + +#endif // ANDROID_GRALLOC_INTERFACE_H diff --git a/.ci/android_headers/hardware/hardware.h b/.ci/android_headers/hardware/hardware.h new file mode 100644 index 0000000..a6d9ad9 --- /dev/null +++ b/.ci/android_headers/hardware/hardware.h @@ -0,0 +1,245 @@ +// clang-format off +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_INCLUDE_HARDWARE_HARDWARE_H +#define ANDROID_INCLUDE_HARDWARE_HARDWARE_H + +#include <stdint.h> +#include <sys/cdefs.h> + +#include <cutils/native_handle.h> +#include <system/graphics.h> + +__BEGIN_DECLS + +/* + * Value for the hw_module_t.tag field + */ + +#define MAKE_TAG_CONSTANT(A,B,C,D) (((A) << 24) | ((B) << 16) | ((C) << 8) | (D)) + +#define HARDWARE_MODULE_TAG MAKE_TAG_CONSTANT('H', 'W', 'M', 'T') +#define HARDWARE_DEVICE_TAG MAKE_TAG_CONSTANT('H', 'W', 'D', 'T') + +#define HARDWARE_MAKE_API_VERSION(maj,min) \ + ((((maj) & 0xff) << 8) | ((min) & 0xff)) + +#define HARDWARE_MAKE_API_VERSION_2(maj,min,hdr) \ + ((((maj) & 0xff) << 24) | (((min) & 0xff) << 16) | ((hdr) & 0xffff)) +#define HARDWARE_API_VERSION_2_MAJ_MIN_MASK 0xffff0000 +#define HARDWARE_API_VERSION_2_HEADER_MASK 0x0000ffff + + +/* + * The current HAL API version. + * + * All module implementations must set the hw_module_t.hal_api_version field + * to this value when declaring the module with HAL_MODULE_INFO_SYM. + * + * Note that previous implementations have always set this field to 0. + * Therefore, libhardware HAL API will always consider versions 0.0 and 1.0 + * to be 100% binary compatible. + * + */ +#define HARDWARE_HAL_API_VERSION HARDWARE_MAKE_API_VERSION(1, 0) + +/* + * Helper macros for module implementors. + * + * The derived modules should provide convenience macros for supported + * versions so that implementations can explicitly specify module/device + * versions at definition time. + * + * Use this macro to set the hw_module_t.module_api_version field. + */ +#define HARDWARE_MODULE_API_VERSION(maj,min) HARDWARE_MAKE_API_VERSION(maj,min) +#define HARDWARE_MODULE_API_VERSION_2(maj,min,hdr) HARDWARE_MAKE_API_VERSION_2(maj,min,hdr) + +/* + * Use this macro to set the hw_device_t.version field + */ +#define HARDWARE_DEVICE_API_VERSION(maj,min) HARDWARE_MAKE_API_VERSION(maj,min) +#define HARDWARE_DEVICE_API_VERSION_2(maj,min,hdr) HARDWARE_MAKE_API_VERSION_2(maj,min,hdr) + +struct hw_module_t; +struct hw_module_methods_t; +struct hw_device_t; + +/** + * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM + * and the fields of this data structure must begin with hw_module_t + * followed by module specific information. + */ +typedef struct hw_module_t { + /** tag must be initialized to HARDWARE_MODULE_TAG */ + uint32_t tag; + + /** + * The API version of the implemented module. The module owner is + * responsible for updating the version when a module interface has + * changed. + * + * The derived modules such as gralloc and audio own and manage this field. + * The module user must interpret the version field to decide whether or + * not to inter-operate with the supplied module implementation. + * For example, SurfaceFlinger is responsible for making sure that + * it knows how to manage different versions of the gralloc-module API, + * and AudioFlinger must know how to do the same for audio-module API. + * + * The module API version should include a major and a minor component. + * For example, version 1.0 could be represented as 0x0100. This format + * implies that versions 0x0100-0x01ff are all API-compatible. + * + * In the future, libhardware will expose a hw_get_module_version() + * (or equivalent) function that will take minimum/maximum supported + * versions as arguments and would be able to reject modules with + * versions outside of the supplied range. + */ + uint16_t module_api_version; +#define version_major module_api_version + /** + * version_major/version_minor defines are supplied here for temporary + * source code compatibility. They will be removed in the next version. + * ALL clients must convert to the new version format. + */ + + /** + * The API version of the HAL module interface. This is meant to + * version the hw_module_t, hw_module_methods_t, and hw_device_t + * structures and definitions. + * + * The HAL interface owns this field. Module users/implementations + * must NOT rely on this value for version information. + * + * Presently, 0 is the only valid value. + */ + uint16_t hal_api_version; +#define version_minor hal_api_version + + /** Identifier of module */ + const char *id; + + /** Name of this module */ + const char *name; + + /** Author/owner/implementor of the module */ + const char *author; + + /** Modules methods */ + struct hw_module_methods_t* methods; + + /** module's dso */ + void* dso; + +#ifdef __LP64__ + uint64_t reserved[32-7]; +#else + /** padding to 128 bytes, reserved for future use */ + uint32_t reserved[32-7]; +#endif + +} hw_module_t; + +typedef struct hw_module_methods_t { + /** Open a specific device */ + int (*open)(const struct hw_module_t* module, const char* id, + struct hw_device_t** device); + +} hw_module_methods_t; + +/** + * Every device data structure must begin with hw_device_t + * followed by module specific public methods and attributes. + */ +typedef struct hw_device_t { + /** tag must be initialized to HARDWARE_DEVICE_TAG */ + uint32_t tag; + + /** + * Version of the module-specific device API. This value is used by + * the derived-module user to manage different device implementations. + * + * The module user is responsible for checking the module_api_version + * and device version fields to ensure that the user is capable of + * communicating with the specific module implementation. + * + * One module can support multiple devices with different versions. This + * can be useful when a device interface changes in an incompatible way + * but it is still necessary to support older implementations at the same + * time. One such example is the Camera 2.0 API. + * + * This field is interpreted by the module user and is ignored by the + * HAL interface itself. + */ + uint32_t version; + + /** reference to the module this device belongs to */ + struct hw_module_t* module; + + /** padding reserved for future use */ +#ifdef __LP64__ + uint64_t reserved[12]; +#else + uint32_t reserved[12]; +#endif + + /** Close this device */ + int (*close)(struct hw_device_t* device); + +} hw_device_t; + +#ifdef __cplusplus +#define TO_HW_DEVICE_T_OPEN(x) reinterpret_cast<struct hw_device_t**>(x) +#else +#define TO_HW_DEVICE_T_OPEN(x) (struct hw_device_t**)(x) +#endif + +/** + * Name of the hal_module_info + */ +#define HAL_MODULE_INFO_SYM HMI + +/** + * Name of the hal_module_info as a string + */ +#define HAL_MODULE_INFO_SYM_AS_STR "HMI" + +/** + * Get the module info associated with a module by id. + * + * @return: 0 == success, <0 == error and *module == NULL + */ +int hw_get_module(const char *id, const struct hw_module_t **module); + +/** + * Get the module info associated with a module instance by class 'class_id' + * and instance 'inst'. + * + * Some modules types necessitate multiple instances. For example audio supports + * multiple concurrent interfaces and thus 'audio' is the module class + * and 'primary' or 'a2dp' are module interfaces. This implies that the files + * providing these modules would be named audio.primary.<variant>.so and + * audio.a2dp.<variant>.so + * + * @return: 0 == success, <0 == error and *module == NULL + */ +int hw_get_module_by_class(const char *class_id, const char *inst, + const struct hw_module_t **module); + +__END_DECLS + +#endif /* ANDROID_INCLUDE_HARDWARE_HARDWARE_H */ diff --git a/.ci/android_headers/hardware/hwcomposer.h b/.ci/android_headers/hardware/hwcomposer.h new file mode 100644 index 0000000..fd083d9 --- /dev/null +++ b/.ci/android_headers/hardware/hwcomposer.h @@ -0,0 +1,799 @@ +// clang-format off +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_INCLUDE_HARDWARE_HWCOMPOSER_H +#define ANDROID_INCLUDE_HARDWARE_HWCOMPOSER_H + +#include <stdint.h> +#include <sys/cdefs.h> + +#include <hardware/gralloc.h> +#include <hardware/hardware.h> +#include <cutils/native_handle.h> + +#include <hardware/hwcomposer_defs.h> + +__BEGIN_DECLS + +/*****************************************************************************/ + +/* for compatibility */ +#define HWC_MODULE_API_VERSION HWC_MODULE_API_VERSION_0_1 +#define HWC_DEVICE_API_VERSION HWC_DEVICE_API_VERSION_0_1 +#define HWC_API_VERSION HWC_DEVICE_API_VERSION + +/*****************************************************************************/ + +typedef struct hwc_layer_1 { + /* + * compositionType is used to specify this layer's type and is set by either + * the hardware composer implementation, or by the caller (see below). + * + * This field is always reset to HWC_BACKGROUND or HWC_FRAMEBUFFER + * before (*prepare)() is called when the HWC_GEOMETRY_CHANGED flag is + * also set, otherwise, this field is preserved between (*prepare)() + * calls. + * + * HWC_BACKGROUND + * Always set by the caller before calling (*prepare)(), this value + * indicates this is a special "background" layer. The only valid field + * is backgroundColor. + * The HWC can toggle this value to HWC_FRAMEBUFFER to indicate it CANNOT + * handle the background color. + * + * + * HWC_FRAMEBUFFER_TARGET + * Always set by the caller before calling (*prepare)(), this value + * indicates this layer is the framebuffer surface used as the target of + * OpenGL ES composition. If the HWC sets all other layers to HWC_OVERLAY + * or HWC_BACKGROUND, then no OpenGL ES composition will be done, and + * this layer should be ignored during set(). + * + * This flag (and the framebuffer surface layer) will only be used if the + * HWC version is HWC_DEVICE_API_VERSION_1_1 or higher. In older versions, + * the OpenGL ES target surface is communicated by the (dpy, sur) fields + * in hwc_compositor_device_1_t. + * + * This value cannot be set by the HWC implementation. + * + * + * HWC_FRAMEBUFFER + * Set by the caller before calling (*prepare)() ONLY when the + * HWC_GEOMETRY_CHANGED flag is also set. + * + * Set by the HWC implementation during (*prepare)(), this indicates + * that the layer will be drawn into the framebuffer using OpenGL ES. + * The HWC can toggle this value to HWC_OVERLAY to indicate it will + * handle the layer. + * + * + * HWC_OVERLAY + * Set by the HWC implementation during (*prepare)(), this indicates + * that the layer will be handled by the HWC (ie: it must not be + * composited with OpenGL ES). + * + * + * HWC_SIDEBAND + * Set by the caller before calling (*prepare)(), this value indicates + * the contents of this layer come from a sideband video stream. + * + * The h/w composer is responsible for receiving new image buffers from + * the stream at the appropriate time (e.g. synchronized to a separate + * audio stream), compositing them with the current contents of other + * layers, and displaying the resulting image. This happens + * independently of the normal prepare/set cycle. The prepare/set calls + * only happen when other layers change, or when properties of the + * sideband layer such as position or size change. + * + * If the h/w composer can't handle the layer as a sideband stream for + * some reason (e.g. unsupported scaling/blending/rotation, or too many + * sideband layers) it can set compositionType to HWC_FRAMEBUFFER in + * (*prepare)(). However, doing so will result in the layer being shown + * as a solid color since the platform is not currently able to composite + * sideband layers with the GPU. This may be improved in future + * versions of the platform. + * + * + * HWC_CURSOR_OVERLAY + * Set by the HWC implementation during (*prepare)(), this value + * indicates the layer's composition will now be handled by the HWC. + * Additionally, the client can now asynchronously update the on-screen + * position of this layer using the setCursorPositionAsync() api. + */ + int32_t compositionType; + + /* + * hints is bit mask set by the HWC implementation during (*prepare)(). + * It is preserved between (*prepare)() calls, unless the + * HWC_GEOMETRY_CHANGED flag is set, in which case it is reset to 0. + * + * see hwc_layer_t::hints + */ + uint32_t hints; + + /* see hwc_layer_t::flags */ + uint32_t flags; + + union { + /* color of the background. hwc_color_t.a is ignored */ + hwc_color_t backgroundColor; + + struct { + union { + /* When compositionType is HWC_FRAMEBUFFER, HWC_OVERLAY, + * HWC_FRAMEBUFFER_TARGET, this is the handle of the buffer to + * compose. This handle is guaranteed to have been allocated + * from gralloc using the GRALLOC_USAGE_HW_COMPOSER usage flag. + * If the layer's handle is unchanged across two consecutive + * prepare calls and the HWC_GEOMETRY_CHANGED flag is not set + * for the second call then the HWComposer implementation may + * assume that the contents of the buffer have not changed. */ + buffer_handle_t handle; + + /* When compositionType is HWC_SIDEBAND, this is the handle + * of the sideband video stream to compose. */ + const native_handle_t* sidebandStream; + }; + + /* transformation to apply to the buffer during composition */ + uint32_t transform; + + /* blending to apply during composition */ + int32_t blending; + + /* area of the source to consider, the origin is the top-left corner of + * the buffer. As of HWC_DEVICE_API_VERSION_1_3, sourceRect uses floats. + * If the h/w can't support a non-integer source crop rectangle, it should + * punt to OpenGL ES composition. + */ + union { + // crop rectangle in integer (pre HWC_DEVICE_API_VERSION_1_3) + hwc_rect_t sourceCropi; + hwc_rect_t sourceCrop; // just for source compatibility + // crop rectangle in floats (as of HWC_DEVICE_API_VERSION_1_3) + hwc_frect_t sourceCropf; + }; + + /* where to composite the sourceCrop onto the display. The sourceCrop + * is scaled using linear filtering to the displayFrame. The origin is the + * top-left corner of the screen. + */ + hwc_rect_t displayFrame; + + /* visible region in screen space. The origin is the + * top-left corner of the screen. + * The visible region INCLUDES areas overlapped by a translucent layer. + */ + hwc_region_t visibleRegionScreen; + + /* Sync fence object that will be signaled when the buffer's + * contents are available. May be -1 if the contents are already + * available. This field is only valid during set(), and should be + * ignored during prepare(). The set() call must not wait for the + * fence to be signaled before returning, but the HWC must wait for + * all buffers to be signaled before reading from them. + * + * HWC_FRAMEBUFFER layers will never have an acquire fence, since + * reads from them are complete before the framebuffer is ready for + * display. + * + * HWC_SIDEBAND layers will never have an acquire fence, since + * synchronization is handled through implementation-defined + * sideband mechanisms. + * + * The HWC takes ownership of the acquireFenceFd and is responsible + * for closing it when no longer needed. + */ + int acquireFenceFd; + + /* During set() the HWC must set this field to a file descriptor for + * a sync fence object that will signal after the HWC has finished + * reading from the buffer. The field is ignored by prepare(). Each + * layer should have a unique file descriptor, even if more than one + * refer to the same underlying fence object; this allows each to be + * closed independently. + * + * If buffer reads can complete at significantly different times, + * then using independent fences is preferred. For example, if the + * HWC handles some layers with a blit engine and others with + * overlays, then the blit layers can be reused immediately after + * the blit completes, but the overlay layers can't be reused until + * a subsequent frame has been displayed. + * + * Since HWC doesn't read from HWC_FRAMEBUFFER layers, it shouldn't + * produce a release fence for them. The releaseFenceFd will be -1 + * for these layers when set() is called. + * + * Since HWC_SIDEBAND buffers don't pass through the HWC client, + * the HWC shouldn't produce a release fence for them. The + * releaseFenceFd will be -1 for these layers when set() is called. + * + * The HWC client taks ownership of the releaseFenceFd and is + * responsible for closing it when no longer needed. + */ + int releaseFenceFd; + + /* + * Availability: HWC_DEVICE_API_VERSION_1_2 + * + * Alpha value applied to the whole layer. The effective + * value of each pixel is computed as: + * + * if (blending == HWC_BLENDING_PREMULT) + * pixel.rgb = pixel.rgb * planeAlpha / 255 + * pixel.a = pixel.a * planeAlpha / 255 + * + * Then blending proceeds as usual according to the "blending" + * field above. + * + * NOTE: planeAlpha applies to YUV layers as well: + * + * pixel.rgb = yuv_to_rgb(pixel.yuv) + * if (blending == HWC_BLENDING_PREMULT) + * pixel.rgb = pixel.rgb * planeAlpha / 255 + * pixel.a = planeAlpha + * + * + * IMPLEMENTATION NOTE: + * + * If the source image doesn't have an alpha channel, then + * the h/w can use the HWC_BLENDING_COVERAGE equations instead of + * HWC_BLENDING_PREMULT and simply set the alpha channel to + * planeAlpha. + * + * e.g.: + * + * if (blending == HWC_BLENDING_PREMULT) + * blending = HWC_BLENDING_COVERAGE; + * pixel.a = planeAlpha; + * + */ + uint8_t planeAlpha; + + /* Pad to 32 bits */ + uint8_t _pad[3]; + + /* + * Availability: HWC_DEVICE_API_VERSION_1_5 + * + * This defines the region of the source buffer that has been + * modified since the last frame. + * + * If surfaceDamage.numRects > 0, then it may be assumed that any + * portion of the source buffer not covered by one of the rects has + * not been modified this frame. If surfaceDamage.numRects == 0, + * then the whole source buffer must be treated as if it had been + * modified. + * + * If the layer's contents are not modified relative to the prior + * prepare/set cycle, surfaceDamage will contain exactly one empty + * rect ([0, 0, 0, 0]). + * + * The damage rects are relative to the pre-transformed buffer, and + * their origin is the top-left corner. + */ + hwc_region_t surfaceDamage; + }; + }; + +#ifdef __LP64__ + /* + * For 64-bit mode, this struct is 120 bytes (and 8-byte aligned), and needs + * to be padded as such to maintain binary compatibility. + */ + uint8_t reserved[120 - 112]; +#else + /* + * For 32-bit mode, this struct is 96 bytes, and needs to be padded as such + * to maintain binary compatibility. + */ + uint8_t reserved[96 - 84]; +#endif + +} hwc_layer_1_t; + +/* This represents a display, typically an EGLDisplay object */ +typedef void* hwc_display_t; + +/* This represents a surface, typically an EGLSurface object */ +typedef void* hwc_surface_t; + +/* + * hwc_display_contents_1_t::flags values + */ +enum { + /* + * HWC_GEOMETRY_CHANGED is set by SurfaceFlinger to indicate that the list + * passed to (*prepare)() has changed by more than just the buffer handles + * and acquire fences. + */ + HWC_GEOMETRY_CHANGED = 0x00000001, +}; + +/* + * Description of the contents to output on a display. + * + * This is the top-level structure passed to the prepare and set calls to + * negotiate and commit the composition of a display image. + */ +typedef struct hwc_display_contents_1 { + /* File descriptor referring to a Sync HAL fence object which will signal + * when this composition is retired. For a physical display, a composition + * is retired when it has been replaced on-screen by a subsequent set. For + * a virtual display, the composition is retired when the writes to + * outputBuffer are complete and can be read. The fence object is created + * and returned by the set call; this field will be -1 on entry to prepare + * and set. SurfaceFlinger will close the returned file descriptor. + */ + int retireFenceFd; + + union { + /* Fields only relevant for HWC_DEVICE_VERSION_1_0. */ + struct { + /* (dpy, sur) is the target of SurfaceFlinger's OpenGL ES + * composition for HWC_DEVICE_VERSION_1_0. They aren't relevant to + * prepare. The set call should commit this surface atomically to + * the display along with any overlay layers. + */ + hwc_display_t dpy; + hwc_surface_t sur; + }; + + /* These fields are used for virtual displays when the h/w composer + * version is at least HWC_DEVICE_VERSION_1_3. */ + struct { + /* outbuf is the buffer that receives the composed image for + * virtual displays. Writes to the outbuf must wait until + * outbufAcquireFenceFd signals. A fence that will signal when + * writes to outbuf are complete should be returned in + * retireFenceFd. + * + * This field is set before prepare(), so properties of the buffer + * can be used to decide which layers can be handled by h/w + * composer. + * + * If prepare() sets all layers to FRAMEBUFFER, then GLES + * composition will happen directly to the output buffer. In this + * case, both outbuf and the FRAMEBUFFER_TARGET layer's buffer will + * be the same, and set() has no work to do besides managing fences. + * + * If the TARGET_FORCE_HWC_FOR_VIRTUAL_DISPLAYS board config + * variable is defined (not the default), then this behavior is + * changed: if all layers are marked for FRAMEBUFFER, GLES + * composition will take place to a scratch framebuffer, and + * h/w composer must copy it to the output buffer. This allows the + * h/w composer to do format conversion if there are cases where + * that is more desirable than doing it in the GLES driver or at the + * virtual display consumer. + * + * If some or all layers are marked OVERLAY, then the framebuffer + * and output buffer will be different. As with physical displays, + * the framebuffer handle will not change between frames if all + * layers are marked for OVERLAY. + */ + buffer_handle_t outbuf; + + /* File descriptor for a fence that will signal when outbuf is + * ready to be written. The h/w composer is responsible for closing + * this when no longer needed. + * + * Will be -1 whenever outbuf is NULL, or when the outbuf can be + * written immediately. + */ + int outbufAcquireFenceFd; + }; + }; + + /* List of layers that will be composed on the display. The buffer handles + * in the list will be unique. If numHwLayers is 0, all composition will be + * performed by SurfaceFlinger. + */ + uint32_t flags; + size_t numHwLayers; + hwc_layer_1_t hwLayers[0]; + +} hwc_display_contents_1_t; + +/* see hwc_composer_device::registerProcs() + * All of the callbacks are required and non-NULL unless otherwise noted. + */ +typedef struct hwc_procs { + /* + * (*invalidate)() triggers a screen refresh, in particular prepare and set + * will be called shortly after this call is made. Note that there is + * NO GUARANTEE that the screen refresh will happen after invalidate() + * returns (in particular, it could happen before). + * invalidate() is GUARANTEED TO NOT CALL BACK into the h/w composer HAL and + * it is safe to call invalidate() from any of hwc_composer_device + * hooks, unless noted otherwise. + */ + void (*invalidate)(const struct hwc_procs* procs); + + /* + * (*vsync)() is called by the h/w composer HAL when a vsync event is + * received and HWC_EVENT_VSYNC is enabled on a display + * (see: hwc_event_control). + * + * the "disp" parameter indicates which display the vsync event is for. + * the "timestamp" parameter is the system monotonic clock timestamp in + * nanosecond of when the vsync event happened. + * + * vsync() is GUARANTEED TO NOT CALL BACK into the h/w composer HAL. + * + * It is expected that vsync() is called from a thread of at least + * HAL_PRIORITY_URGENT_DISPLAY with as little latency as possible, + * typically less than 0.5 ms. + * + * It is a (silent) error to have HWC_EVENT_VSYNC enabled when calling + * hwc_composer_device.set(..., 0, 0, 0) (screen off). The implementation + * can either stop or continue to process VSYNC events, but must not + * crash or cause other problems. + */ + void (*vsync)(const struct hwc_procs* procs, int disp, int64_t timestamp); + + /* + * (*hotplug)() is called by the h/w composer HAL when a display is + * connected or disconnected. The PRIMARY display is always connected and + * the hotplug callback should not be called for it. + * + * The disp parameter indicates which display type this event is for. + * The connected parameter indicates whether the display has just been + * connected (1) or disconnected (0). + * + * The hotplug() callback may call back into the h/w composer on the same + * thread to query refresh rate and dpi for the display. Additionally, + * other threads may be calling into the h/w composer while the callback + * is in progress. + * + * The h/w composer must serialize calls to the hotplug callback; only + * one thread may call it at a time. + * + * This callback will be NULL if the h/w composer is using + * HWC_DEVICE_API_VERSION_1_0. + */ + void (*hotplug)(const struct hwc_procs* procs, int disp, int connected); + +} hwc_procs_t; + + +/*****************************************************************************/ + +typedef struct hwc_module { + /** + * Common methods of the hardware composer module. This *must* be the first member of + * hwc_module as users of this structure will cast a hw_module_t to + * hwc_module pointer in contexts where it's known the hw_module_t references a + * hwc_module. + */ + struct hw_module_t common; +} hwc_module_t; + +#define HWC_ERROR (-1) +typedef struct hwc_composer_device_1 { + /** + * Common methods of the hardware composer device. This *must* be the first member of + * hwc_composer_device_1 as users of this structure will cast a hw_device_t to + * hwc_composer_device_1 pointer in contexts where it's known the hw_device_t references a + * hwc_composer_device_1. + */ + struct hw_device_t common; + + /* + * (*prepare)() is called for each frame before composition and is used by + * SurfaceFlinger to determine what composition steps the HWC can handle. + * + * (*prepare)() can be called more than once, the last call prevails. + * + * The HWC responds by setting the compositionType field in each layer to + * either HWC_FRAMEBUFFER, HWC_OVERLAY, or HWC_CURSOR_OVERLAY. For the + * HWC_FRAMEBUFFER type, composition for the layer is handled by + * SurfaceFlinger with OpenGL ES. For the latter two overlay types, + * the HWC will have to handle the layer's composition. compositionType + * and hints are preserved between (*prepare)() calles unless the + * HWC_GEOMETRY_CHANGED flag is set. + * + * (*prepare)() is called with HWC_GEOMETRY_CHANGED to indicate that the + * list's geometry has changed, that is, when more than just the buffer's + * handles have been updated. Typically this happens (but is not limited to) + * when a window is added, removed, resized or moved. In this case + * compositionType and hints are reset to their default value. + * + * For HWC 1.0, numDisplays will always be one, and displays[0] will be + * non-NULL. + * + * For HWC 1.1, numDisplays will always be HWC_NUM_PHYSICAL_DISPLAY_TYPES. + * Entries for unsupported or disabled/disconnected display types will be + * NULL. + * + * In HWC 1.3, numDisplays may be up to HWC_NUM_DISPLAY_TYPES. The extra + * entries correspond to enabled virtual displays, and will be non-NULL. + * + * returns: 0 on success. An negative error code on error. If an error is + * returned, SurfaceFlinger will assume that none of the layer will be + * handled by the HWC. + */ + int (*prepare)(struct hwc_composer_device_1 *dev, + size_t numDisplays, hwc_display_contents_1_t** displays); + + /* + * (*set)() is used in place of eglSwapBuffers(), and assumes the same + * functionality, except it also commits the work list atomically with + * the actual eglSwapBuffers(). + * + * The layer lists are guaranteed to be the same as the ones returned from + * the last call to (*prepare)(). + * + * When this call returns the caller assumes that the displays will be + * updated in the near future with the content of their work lists, without + * artifacts during the transition from the previous frame. + * + * A display with zero layers indicates that the entire composition has + * been handled by SurfaceFlinger with OpenGL ES. In this case, (*set)() + * behaves just like eglSwapBuffers(). + * + * For HWC 1.0, numDisplays will always be one, and displays[0] will be + * non-NULL. + * + * For HWC 1.1, numDisplays will always be HWC_NUM_PHYSICAL_DISPLAY_TYPES. + * Entries for unsupported or disabled/disconnected display types will be + * NULL. + * + * In HWC 1.3, numDisplays may be up to HWC_NUM_DISPLAY_TYPES. The extra + * entries correspond to enabled virtual displays, and will be non-NULL. + * + * IMPORTANT NOTE: There is an implicit layer containing opaque black + * pixels behind all the layers in the list. It is the responsibility of + * the hwcomposer module to make sure black pixels are output (or blended + * from). + * + * IMPORTANT NOTE: In the event of an error this call *MUST* still cause + * any fences returned in the previous call to set to eventually become + * signaled. The caller may have already issued wait commands on these + * fences, and having set return without causing those fences to signal + * will likely result in a deadlock. + * + * returns: 0 on success. A negative error code on error: + * HWC_EGL_ERROR: eglGetError() will provide the proper error code (only + * allowed prior to HWComposer 1.1) + * Another code for non EGL errors. + */ + int (*set)(struct hwc_composer_device_1 *dev, + size_t numDisplays, hwc_display_contents_1_t** displays); + + /* + * eventControl(..., event, enabled) + * Enables or disables h/w composer events for a display. + * + * eventControl can be called from any thread and takes effect + * immediately. + * + * Supported events are: + * HWC_EVENT_VSYNC + * + * returns -EINVAL if the "event" parameter is not one of the value above + * or if the "enabled" parameter is not 0 or 1. + */ + int (*eventControl)(struct hwc_composer_device_1* dev, int disp, + int event, int enabled); + + union { + /* + * For HWC 1.3 and earlier, the blank() interface is used. + * + * blank(..., blank) + * Blanks or unblanks a display's screen. + * + * Turns the screen off when blank is nonzero, on when blank is zero. + * Multiple sequential calls with the same blank value must be + * supported. + * The screen state transition must be be complete when the function + * returns. + * + * returns 0 on success, negative on error. + */ + int (*blank)(struct hwc_composer_device_1* dev, int disp, int blank); + + /* + * For HWC 1.4 and above, setPowerMode() will be used in place of + * blank(). + * + * setPowerMode(..., mode) + * Sets the display screen's power state. + * + * Refer to the documentation of the HWC_POWER_MODE_* constants + * for information about each power mode. + * + * The functionality is similar to the blank() command in previous + * versions of HWC, but with support for more power states. + * + * The display driver is expected to retain and restore the low power + * state of the display while entering and exiting from suspend. + * + * Multiple sequential calls with the same mode value must be supported. + * + * The screen state transition must be be complete when the function + * returns. + * + * returns 0 on success, negative on error. + */ + int (*setPowerMode)(struct hwc_composer_device_1* dev, int disp, + int mode); + }; + + /* + * Used to retrieve information about the h/w composer + * + * Returns 0 on success or -errno on error. + */ + int (*query)(struct hwc_composer_device_1* dev, int what, int* value); + + /* + * (*registerProcs)() registers callbacks that the h/w composer HAL can + * later use. It will be called immediately after the composer device is + * opened with non-NULL procs. It is FORBIDDEN to call any of the callbacks + * from within registerProcs(). registerProcs() must save the hwc_procs_t + * pointer which is needed when calling a registered callback. + */ + void (*registerProcs)(struct hwc_composer_device_1* dev, + hwc_procs_t const* procs); + + /* + * This field is OPTIONAL and can be NULL. + * + * If non NULL it will be called by SurfaceFlinger on dumpsys + */ + void (*dump)(struct hwc_composer_device_1* dev, char *buff, int buff_len); + + /* + * (*getDisplayConfigs)() returns handles for the configurations available + * on the connected display. These handles must remain valid as long as the + * display is connected. + * + * Configuration handles are written to configs. The number of entries + * allocated by the caller is passed in *numConfigs; getDisplayConfigs must + * not try to write more than this number of config handles. On return, the + * total number of configurations available for the display is returned in + * *numConfigs. If *numConfigs is zero on entry, then configs may be NULL. + * + * Hardware composers implementing HWC_DEVICE_API_VERSION_1_3 or prior + * shall choose one configuration to activate and report it as the first + * entry in the returned list. Reporting the inactive configurations is not + * required. + * + * HWC_DEVICE_API_VERSION_1_4 and later provide configuration management + * through SurfaceFlinger, and hardware composers implementing these APIs + * must also provide getActiveConfig and setActiveConfig. Hardware composers + * implementing these API versions may choose not to activate any + * configuration, leaving configuration selection to higher levels of the + * framework. + * + * Returns 0 on success or a negative error code on error. If disp is a + * hotpluggable display type and no display is connected, an error shall be + * returned. + * + * This field is REQUIRED for HWC_DEVICE_API_VERSION_1_1 and later. + * It shall be NULL for previous versions. + */ + int (*getDisplayConfigs)(struct hwc_composer_device_1* dev, int disp, + uint32_t* configs, size_t* numConfigs); + + /* + * (*getDisplayAttributes)() returns attributes for a specific config of a + * connected display. The config parameter is one of the config handles + * returned by getDisplayConfigs. + * + * The list of attributes to return is provided in the attributes + * parameter, terminated by HWC_DISPLAY_NO_ATTRIBUTE. The value for each + * requested attribute is written in order to the values array. The + * HWC_DISPLAY_NO_ATTRIBUTE attribute does not have a value, so the values + * array will have one less value than the attributes array. + * + * This field is REQUIRED for HWC_DEVICE_API_VERSION_1_1 and later. + * It shall be NULL for previous versions. + * + * If disp is a hotpluggable display type and no display is connected, + * or if config is not a valid configuration for the display, a negative + * error code shall be returned. + */ + int (*getDisplayAttributes)(struct hwc_composer_device_1* dev, int disp, + uint32_t config, const uint32_t* attributes, int32_t* values); + + /* + * (*getActiveConfig)() returns the index of the configuration that is + * currently active on the connected display. The index is relative to + * the list of configuration handles returned by getDisplayConfigs. If there + * is no active configuration, HWC_ERROR shall be returned. + * + * Returns the configuration index on success or HWC_ERROR on error. + * + * This field is REQUIRED for HWC_DEVICE_API_VERSION_1_4 and later. + * It shall be NULL for previous versions. + */ + int (*getActiveConfig)(struct hwc_composer_device_1* dev, int disp); + + /* + * (*setActiveConfig)() instructs the hardware composer to switch to the + * display configuration at the given index in the list of configuration + * handles returned by getDisplayConfigs. + * + * If this function returns without error, any subsequent calls to + * getActiveConfig shall return the index set by this function until one + * of the following occurs: + * 1) Another successful call of this function + * 2) The display is disconnected + * + * Returns 0 on success or a negative error code on error. If disp is a + * hotpluggable display type and no display is connected, or if index is + * outside of the range of hardware configurations returned by + * getDisplayConfigs, an error shall be returned. + * + * This field is REQUIRED for HWC_DEVICE_API_VERSION_1_4 and later. + * It shall be NULL for previous versions. + */ + int (*setActiveConfig)(struct hwc_composer_device_1* dev, int disp, + int index); + /* + * Asynchronously update the location of the cursor layer. + * + * Within the standard prepare()/set() composition loop, the client + * (surfaceflinger) can request that a given layer uses dedicated cursor + * composition hardware by specifiying the HWC_IS_CURSOR_LAYER flag. Only + * one layer per display can have this flag set. If the layer is suitable + * for the platform's cursor hardware, hwcomposer will return from prepare() + * a composition type of HWC_CURSOR_OVERLAY for that layer. This indicates + * not only that the client is not responsible for compositing that layer, + * but also that the client can continue to update the position of that layer + * after a call to set(). This can reduce the visible latency of mouse + * movement to visible, on-screen cursor updates. Calls to + * setCursorPositionAsync() may be made from a different thread doing the + * prepare()/set() composition loop, but care must be taken to not interleave + * calls of setCursorPositionAsync() between calls of set()/prepare(). + * + * Notes: + * - Only one layer per display can be specified as a cursor layer with + * HWC_IS_CURSOR_LAYER. + * - hwcomposer will only return one layer per display as HWC_CURSOR_OVERLAY + * - This returns 0 on success or -errno on error. + * - This field is optional for HWC_DEVICE_API_VERSION_1_4 and later. It + * should be null for previous versions. + */ + int (*setCursorPositionAsync)(struct hwc_composer_device_1 *dev, int disp, int x_pos, int y_pos); + + /* + * Reserved for future use. Must be NULL. + */ + void* reserved_proc[1]; + +} hwc_composer_device_1_t; + +/** convenience API for opening and closing a device */ + +static inline int hwc_open_1(const struct hw_module_t* module, + hwc_composer_device_1_t** device) { + return module->methods->open(module, + HWC_HARDWARE_COMPOSER, TO_HW_DEVICE_T_OPEN(device)); +} + +static inline int hwc_close_1(hwc_composer_device_1_t* device) { + return device->common.close(&device->common); +} + +/*****************************************************************************/ + +__END_DECLS + +#endif /* ANDROID_INCLUDE_HARDWARE_HWCOMPOSER_H */ diff --git a/.ci/android_headers/hardware/hwcomposer2.h b/.ci/android_headers/hardware/hwcomposer2.h new file mode 100644 index 0000000..df5670f --- /dev/null +++ b/.ci/android_headers/hardware/hwcomposer2.h @@ -0,0 +1,3183 @@ +// clang-format off +/* + * Copyright 2015 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_HARDWARE_HWCOMPOSER2_H +#define ANDROID_HARDWARE_HWCOMPOSER2_H + +#include <sys/cdefs.h> + +#include <hardware/hardware.h> + +#include "hwcomposer_defs.h" + +/* Missing in glibc, pull from BIONIC */ +#if defined(__cplusplus) +#define __BIONIC_CAST(_k,_t,_v) (_k<_t>(_v)) +#else +#define __BIONIC_CAST(_k,_t,_v) ((_t) (_v)) +#endif + +__BEGIN_DECLS + +/* + * Enums + * + * For most of these enums, there is an invalid value defined to be 0. This is + * an attempt to catch uninitialized fields, and these values should not be + * used. + */ + +/* Display attributes queryable through getDisplayAttribute */ +typedef enum { + HWC2_ATTRIBUTE_INVALID = 0, + + /* Dimensions in pixels */ + HWC2_ATTRIBUTE_WIDTH = 1, + HWC2_ATTRIBUTE_HEIGHT = 2, + + /* Vsync period in nanoseconds */ + HWC2_ATTRIBUTE_VSYNC_PERIOD = 3, + + /* Dots per thousand inches (DPI * 1000). Scaling by 1000 allows these + * numbers to be stored in an int32_t without losing too much precision. If + * the DPI for a configuration is unavailable or is considered unreliable, + * the device may return -1 instead */ + HWC2_ATTRIBUTE_DPI_X = 4, + HWC2_ATTRIBUTE_DPI_Y = 5, + + /* The configuration group this config is associated to. + * Switching between configurations within the same group may be done seamlessly + * in some conditions via setActiveConfigWithConstraints. */ + HWC2_ATTRIBUTE_CONFIG_GROUP = 7, +} hwc2_attribute_t; + +/* Blend modes, settable per layer */ +typedef enum { + HWC2_BLEND_MODE_INVALID = 0, + + /* colorOut = colorSrc */ + HWC2_BLEND_MODE_NONE = 1, + + /* colorOut = colorSrc + colorDst * (1 - alphaSrc) */ + HWC2_BLEND_MODE_PREMULTIPLIED = 2, + + /* colorOut = colorSrc * alphaSrc + colorDst * (1 - alphaSrc) */ + HWC2_BLEND_MODE_COVERAGE = 3, +} hwc2_blend_mode_t; + +/* See the 'Callbacks' section for more detailed descriptions of what these + * functions do */ +typedef enum { + HWC2_CALLBACK_INVALID = 0, + HWC2_CALLBACK_HOTPLUG = 1, + HWC2_CALLBACK_REFRESH = 2, + HWC2_CALLBACK_VSYNC = 3, + HWC2_CALLBACK_VSYNC_2_4 = 4, + HWC2_CALLBACK_VSYNC_PERIOD_TIMING_CHANGED = 5, + HWC2_CALLBACK_SEAMLESS_POSSIBLE = 6, +} hwc2_callback_descriptor_t; + +/* Optional capabilities which may be supported by some devices. The particular + * set of supported capabilities for a given device may be retrieved using + * getCapabilities. */ +typedef enum { + HWC2_CAPABILITY_INVALID = 0, + + /* Specifies that the device supports sideband stream layers, for which + * buffer content updates and other synchronization will not be provided + * through the usual validate/present cycle and must be handled by an + * external implementation-defined mechanism. Only changes to layer state + * (such as position, size, etc.) need to be performed through the + * validate/present cycle. */ + HWC2_CAPABILITY_SIDEBAND_STREAM = 1, + + /* Specifies that the device will apply a color transform even when either + * the client or the device has chosen that all layers should be composed by + * the client. This will prevent the client from applying the color + * transform during its composition step. */ + HWC2_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM = 2, + + /* Specifies that the present fence must not be used as an accurate + * representation of the actual present time of a frame. + * This capability must never be set by HWC2 devices. + * This capability may be set for HWC1 devices that use the + * HWC2On1Adapter where emulation of the present fence using the retire + * fence is not feasible. + * In the future, CTS tests will require present time to be reliable. + */ + HWC2_CAPABILITY_PRESENT_FENCE_IS_NOT_RELIABLE = 3, + + /* Specifies that a device is able to skip the validateDisplay call before + * receiving a call to presentDisplay. The client will always skip + * validateDisplay and try to call presentDisplay regardless of the changes + * in the properties of the layers. If the device returns anything else than + * HWC2_ERROR_NONE, it will call validateDisplay then presentDisplay again. + * For this capability to be worthwhile the device implementation of + * presentDisplay should fail as fast as possible in the case a + * validateDisplay step is needed. + */ + HWC2_CAPABILITY_SKIP_VALIDATE = 4, +} hwc2_capability_t; + +/* Possible composition types for a given layer */ +typedef enum { + HWC2_COMPOSITION_INVALID = 0, + + /* The client will composite this layer into the client target buffer + * (provided to the device through setClientTarget). + * + * The device must not request any composition type changes for layers of + * this type. */ + HWC2_COMPOSITION_CLIENT = 1, + + /* The device will handle the composition of this layer through a hardware + * overlay or other similar means. + * + * Upon validateDisplay, the device may request a change from this type to + * HWC2_COMPOSITION_CLIENT. */ + HWC2_COMPOSITION_DEVICE = 2, + + /* The device will render this layer using the color set through + * setLayerColor. If this functionality is not supported on a layer that the + * client sets to HWC2_COMPOSITION_SOLID_COLOR, the device must request that + * the composition type of that layer is changed to HWC2_COMPOSITION_CLIENT + * upon the next call to validateDisplay. + * + * Upon validateDisplay, the device may request a change from this type to + * HWC2_COMPOSITION_CLIENT. */ + HWC2_COMPOSITION_SOLID_COLOR = 3, + + /* Similar to DEVICE, but the position of this layer may also be set + * asynchronously through setCursorPosition. If this functionality is not + * supported on a layer that the client sets to HWC2_COMPOSITION_CURSOR, the + * device must request that the composition type of that layer is changed to + * HWC2_COMPOSITION_CLIENT upon the next call to validateDisplay. + * + * Upon validateDisplay, the device may request a change from this type to + * either HWC2_COMPOSITION_DEVICE or HWC2_COMPOSITION_CLIENT. Changing to + * HWC2_COMPOSITION_DEVICE will prevent the use of setCursorPosition but + * still permit the device to composite the layer. */ + HWC2_COMPOSITION_CURSOR = 4, + + /* The device will handle the composition of this layer, as well as its + * buffer updates and content synchronization. Only supported on devices + * which provide HWC2_CAPABILITY_SIDEBAND_STREAM. + * + * Upon validateDisplay, the device may request a change from this type to + * either HWC2_COMPOSITION_DEVICE or HWC2_COMPOSITION_CLIENT, but it is + * unlikely that content will display correctly in these cases. */ + HWC2_COMPOSITION_SIDEBAND = 5, +} hwc2_composition_t; + +/* Possible connection options from the hotplug callback */ +typedef enum { + HWC2_CONNECTION_INVALID = 0, + + /* The display has been connected */ + HWC2_CONNECTION_CONNECTED = 1, + + /* The display has been disconnected */ + HWC2_CONNECTION_DISCONNECTED = 2, +} hwc2_connection_t; + +/* Display requests returned by getDisplayRequests */ +typedef enum { + /* Instructs the client to provide a new client target buffer, even if no + * layers are marked for client composition. */ + HWC2_DISPLAY_REQUEST_FLIP_CLIENT_TARGET = 1 << 0, + + /* Instructs the client to write the result of client composition directly + * into the virtual display output buffer. If any of the layers are not + * marked as HWC2_COMPOSITION_CLIENT or the given display is not a virtual + * display, this request has no effect. */ + HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT = 1 << 1, +} hwc2_display_request_t; + +/* Display types returned by getDisplayType */ +typedef enum { + HWC2_DISPLAY_TYPE_INVALID = 0, + + /* All physical displays, including both internal displays and hotpluggable + * external displays */ + HWC2_DISPLAY_TYPE_PHYSICAL = 1, + + /* Virtual displays created by createVirtualDisplay */ + HWC2_DISPLAY_TYPE_VIRTUAL = 2, +} hwc2_display_type_t; + +/* Physical display types returned by getDisplayConnectionType */ +typedef enum { + HWC2_DISPLAY_CONNECTION_TYPE_INTERNAL = 0, + HWC2_DISPLAY_CONNECTION_TYPE_EXTERNAL = 1, +} hwc2_display_connection_type_t; + +/* Return codes from all functions */ +typedef enum { + HWC2_ERROR_NONE = 0, + HWC2_ERROR_BAD_CONFIG, + HWC2_ERROR_BAD_DISPLAY, + HWC2_ERROR_BAD_LAYER, + HWC2_ERROR_BAD_PARAMETER, + HWC2_ERROR_HAS_CHANGES, + HWC2_ERROR_NO_RESOURCES, + HWC2_ERROR_NOT_VALIDATED, + HWC2_ERROR_UNSUPPORTED, + HWC2_ERROR_SEAMLESS_NOT_ALLOWED, + HWC2_ERROR_SEAMLESS_NOT_POSSIBLE, +} hwc2_error_t; + +/* Function descriptors for use with getFunction */ +typedef enum { + HWC2_FUNCTION_INVALID = 0, + HWC2_FUNCTION_ACCEPT_DISPLAY_CHANGES, + HWC2_FUNCTION_CREATE_LAYER, + HWC2_FUNCTION_CREATE_VIRTUAL_DISPLAY, + HWC2_FUNCTION_DESTROY_LAYER, + HWC2_FUNCTION_DESTROY_VIRTUAL_DISPLAY, + HWC2_FUNCTION_DUMP, + HWC2_FUNCTION_GET_ACTIVE_CONFIG, + HWC2_FUNCTION_GET_CHANGED_COMPOSITION_TYPES, + HWC2_FUNCTION_GET_CLIENT_TARGET_SUPPORT, + HWC2_FUNCTION_GET_COLOR_MODES, + HWC2_FUNCTION_GET_DISPLAY_ATTRIBUTE, + HWC2_FUNCTION_GET_DISPLAY_CONFIGS, + HWC2_FUNCTION_GET_DISPLAY_NAME, + HWC2_FUNCTION_GET_DISPLAY_REQUESTS, + HWC2_FUNCTION_GET_DISPLAY_TYPE, + HWC2_FUNCTION_GET_DOZE_SUPPORT, + HWC2_FUNCTION_GET_HDR_CAPABILITIES, + HWC2_FUNCTION_GET_MAX_VIRTUAL_DISPLAY_COUNT, + HWC2_FUNCTION_GET_RELEASE_FENCES, + HWC2_FUNCTION_PRESENT_DISPLAY, + HWC2_FUNCTION_REGISTER_CALLBACK, + HWC2_FUNCTION_SET_ACTIVE_CONFIG, + HWC2_FUNCTION_SET_CLIENT_TARGET, + HWC2_FUNCTION_SET_COLOR_MODE, + HWC2_FUNCTION_SET_COLOR_TRANSFORM, + HWC2_FUNCTION_SET_CURSOR_POSITION, + HWC2_FUNCTION_SET_LAYER_BLEND_MODE, + HWC2_FUNCTION_SET_LAYER_BUFFER, + HWC2_FUNCTION_SET_LAYER_COLOR, + HWC2_FUNCTION_SET_LAYER_COMPOSITION_TYPE, + HWC2_FUNCTION_SET_LAYER_DATASPACE, + HWC2_FUNCTION_SET_LAYER_DISPLAY_FRAME, + HWC2_FUNCTION_SET_LAYER_PLANE_ALPHA, + HWC2_FUNCTION_SET_LAYER_SIDEBAND_STREAM, + HWC2_FUNCTION_SET_LAYER_SOURCE_CROP, + HWC2_FUNCTION_SET_LAYER_SURFACE_DAMAGE, + HWC2_FUNCTION_SET_LAYER_TRANSFORM, + HWC2_FUNCTION_SET_LAYER_VISIBLE_REGION, + HWC2_FUNCTION_SET_LAYER_Z_ORDER, + HWC2_FUNCTION_SET_OUTPUT_BUFFER, + HWC2_FUNCTION_SET_POWER_MODE, + HWC2_FUNCTION_SET_VSYNC_ENABLED, + HWC2_FUNCTION_VALIDATE_DISPLAY, + HWC2_FUNCTION_SET_LAYER_FLOAT_COLOR, + HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA, + HWC2_FUNCTION_GET_PER_FRAME_METADATA_KEYS, + HWC2_FUNCTION_SET_READBACK_BUFFER, + HWC2_FUNCTION_GET_READBACK_BUFFER_ATTRIBUTES, + HWC2_FUNCTION_GET_READBACK_BUFFER_FENCE, + HWC2_FUNCTION_GET_RENDER_INTENTS, + HWC2_FUNCTION_SET_COLOR_MODE_WITH_RENDER_INTENT, + HWC2_FUNCTION_GET_DATASPACE_SATURATION_MATRIX, + + // composer 2.3 + HWC2_FUNCTION_GET_DISPLAY_IDENTIFICATION_DATA, + HWC2_FUNCTION_GET_DISPLAY_CAPABILITIES, + HWC2_FUNCTION_SET_LAYER_COLOR_TRANSFORM, + HWC2_FUNCTION_GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES, + HWC2_FUNCTION_SET_DISPLAYED_CONTENT_SAMPLING_ENABLED, + HWC2_FUNCTION_GET_DISPLAYED_CONTENT_SAMPLE, + HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA_BLOBS, + HWC2_FUNCTION_GET_DISPLAY_BRIGHTNESS_SUPPORT, + HWC2_FUNCTION_SET_DISPLAY_BRIGHTNESS, + + // composer 2.4 + HWC2_FUNCTION_GET_DISPLAY_CONNECTION_TYPE, + HWC2_FUNCTION_GET_DISPLAY_VSYNC_PERIOD, + HWC2_FUNCTION_SET_ACTIVE_CONFIG_WITH_CONSTRAINTS, + HWC2_FUNCTION_SET_AUTO_LOW_LATENCY_MODE, + HWC2_FUNCTION_GET_SUPPORTED_CONTENT_TYPES, + HWC2_FUNCTION_SET_CONTENT_TYPE, + HWC2_FUNCTION_GET_CLIENT_TARGET_PROPERTY, + HWC2_FUNCTION_SET_LAYER_GENERIC_METADATA, + HWC2_FUNCTION_GET_LAYER_GENERIC_METADATA_KEY, +} hwc2_function_descriptor_t; + +/* Layer requests returned from getDisplayRequests */ +typedef enum { + /* The client should clear its target with transparent pixels where this + * layer would be. The client may ignore this request if the layer must be + * blended. */ + HWC2_LAYER_REQUEST_CLEAR_CLIENT_TARGET = 1 << 0, +} hwc2_layer_request_t; + +/* Power modes for use with setPowerMode */ +typedef enum { + /* The display is fully off (blanked) */ + HWC2_POWER_MODE_OFF = 0, + + /* These are optional low power modes. getDozeSupport may be called to + * determine whether a given display supports these modes. */ + + /* The display is turned on and configured in a low power state that is + * suitable for presenting ambient information to the user, possibly with + * lower fidelity than HWC2_POWER_MODE_ON, but with greater efficiency. */ + HWC2_POWER_MODE_DOZE = 1, + + /* The display is configured as in HWC2_POWER_MODE_DOZE but may stop + * applying display updates from the client. This is effectively a hint to + * the device that drawing to the display has been suspended and that the + * the device should remain on in a low power state and continue displaying + * its current contents indefinitely until the power mode changes. + * + * This mode may also be used as a signal to enable hardware-based doze + * functionality. In this case, the device is free to take over the display + * and manage it autonomously to implement a low power always-on display. */ + HWC2_POWER_MODE_DOZE_SUSPEND = 3, + + /* The display is fully on */ + HWC2_POWER_MODE_ON = 2, +} hwc2_power_mode_t; + +typedef enum { + HWC2_CONTENT_TYPE_NONE = 0, + HWC2_CONTENT_TYPE_GRAPHICS = 1, + HWC2_CONTENT_TYPE_PHOTO = 2, + HWC2_CONTENT_TYPE_CINEMA = 3, + HWC2_CONTENT_TYPE_GAME = 4, +} hwc2_content_type_t; + +/* Vsync values passed to setVsyncEnabled */ +typedef enum { + HWC2_VSYNC_INVALID = 0, + + /* Enable vsync */ + HWC2_VSYNC_ENABLE = 1, + + /* Disable vsync */ + HWC2_VSYNC_DISABLE = 2, +} hwc2_vsync_t; + +/* MUST match HIDL's V2_2::IComposerClient::PerFrameMetadataKey */ +typedef enum { + /* SMPTE ST 2084:2014. + * Coordinates defined in CIE 1931 xy chromaticity space + */ + HWC2_DISPLAY_RED_PRIMARY_X = 0, + HWC2_DISPLAY_RED_PRIMARY_Y = 1, + HWC2_DISPLAY_GREEN_PRIMARY_X = 2, + HWC2_DISPLAY_GREEN_PRIMARY_Y = 3, + HWC2_DISPLAY_BLUE_PRIMARY_X = 4, + HWC2_DISPLAY_BLUE_PRIMARY_Y = 5, + HWC2_WHITE_POINT_X = 6, + HWC2_WHITE_POINT_Y = 7, + /* SMPTE ST 2084:2014. + * Units: nits + * max as defined by ST 2048: 10,000 nits + */ + HWC2_MAX_LUMINANCE = 8, + HWC2_MIN_LUMINANCE = 9, + + /* CTA 861.3 + * Units: nits + */ + HWC2_MAX_CONTENT_LIGHT_LEVEL = 10, + HWC2_MAX_FRAME_AVERAGE_LIGHT_LEVEL = 11, +} hwc2_per_frame_metadata_key_t; + +/* SetDisplayedContentSampling values passed to setDisplayedContentSamplingEnabled */ +typedef enum { + HWC2_DISPLAYED_CONTENT_SAMPLING_INVALID = 0, + + /* Enable displayed content sampling */ + HWC2_DISPLAYED_CONTENT_SAMPLING_ENABLE = 1, + + /* Disable displayed content sampling */ + HWC2_DISPLAYED_CONTENT_SAMPLING_DISABLE = 2, +} hwc2_displayed_content_sampling_t; + +typedef enum { + HWC2_FORMAT_COMPONENT_0 = 1 << 0, /* The first component (eg, for RGBA_8888, this is R) */ + HWC2_FORMAT_COMPONENT_1 = 1 << 1, /* The second component (eg, for RGBA_8888, this is G) */ + HWC2_FORMAT_COMPONENT_2 = 1 << 2, /* The third component (eg, for RGBA_8888, this is B) */ + HWC2_FORMAT_COMPONENT_3 = 1 << 3, /* The fourth component (eg, for RGBA_8888, this is A) */ +} hwc2_format_color_component_t; + +/* Optional display capabilities which may be supported by some displays. + * The particular set of supported capabilities for a given display may be + * retrieved using getDisplayCapabilities. */ +typedef enum { + HWC2_DISPLAY_CAPABILITY_INVALID = 0, + + /** + * Specifies that the display must apply a color transform even when either + * the client or the device has chosen that all layers should be composed by + * the client. This prevents the client from applying the color transform + * during its composition step. + * If getDisplayCapabilities is supported, the global capability + * HWC2_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM is ignored. + * If getDisplayCapabilities is not supported, and the global capability + * HWC2_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM is returned by getCapabilities, + * then all displays must be treated as having + * HWC2_DISPLAY_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM. + */ + HWC2_DISPLAY_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM = 1, + + /** + * Specifies that the display supports PowerMode::DOZE and + * PowerMode::DOZE_SUSPEND. DOZE_SUSPEND may not provide any benefit + * over DOZE (see the definition of PowerMode for more information), + * but if both DOZE and DOZE_SUSPEND are no different from + * PowerMode::ON, the device must not claim support. + * HWC2_DISPLAY_CAPABILITY_DOZE must be returned by getDisplayCapabilities + * when getDozeSupport indicates the display supports PowerMode::DOZE and + * PowerMode::DOZE_SUSPEND. + */ + HWC2_DISPLAY_CAPABILITY_DOZE = 2, + + /** + * Specified that the display supports brightness operations. + */ + HWC2_DISPLAY_CAPABILITY_BRIGHTNESS = 3, + + /** + * Specifies that the display supports a low latency mode. If the connection + * to the display is via HDMI, this specifies whether Auto Low Latency Mode + * is supported. If, instead, there is an internal connection to the display, + * then this specifies that the display has some other custom low latency + * mode. + */ + HWC2_DISPLAY_CAPABILITY_AUTO_LOW_LATENCY_MODE = 5, +} hwc2_display_capability_t; + +/* + * Stringification Functions + */ + +#ifdef HWC2_INCLUDE_STRINGIFICATION + +static inline const char* getAttributeName(hwc2_attribute_t attribute) { + switch (attribute) { + case HWC2_ATTRIBUTE_INVALID: return "Invalid"; + case HWC2_ATTRIBUTE_WIDTH: return "Width"; + case HWC2_ATTRIBUTE_HEIGHT: return "Height"; + case HWC2_ATTRIBUTE_VSYNC_PERIOD: return "VsyncPeriod"; + case HWC2_ATTRIBUTE_DPI_X: return "DpiX"; + case HWC2_ATTRIBUTE_DPI_Y: return "DpiY"; + case HWC2_ATTRIBUTE_CONFIG_GROUP: return "ConfigGroup"; + default: return "Unknown"; + } +} + +static inline const char* getBlendModeName(hwc2_blend_mode_t mode) { + switch (mode) { + case HWC2_BLEND_MODE_INVALID: return "Invalid"; + case HWC2_BLEND_MODE_NONE: return "None"; + case HWC2_BLEND_MODE_PREMULTIPLIED: return "Premultiplied"; + case HWC2_BLEND_MODE_COVERAGE: return "Coverage"; + default: return "Unknown"; + } +} + +static inline const char* getCallbackDescriptorName( + hwc2_callback_descriptor_t desc) { + switch (desc) { + case HWC2_CALLBACK_INVALID: return "Invalid"; + case HWC2_CALLBACK_HOTPLUG: return "Hotplug"; + case HWC2_CALLBACK_REFRESH: return "Refresh"; + case HWC2_CALLBACK_VSYNC: return "Vsync"; + case HWC2_CALLBACK_VSYNC_2_4: return "Vsync2.4"; + case HWC2_CALLBACK_VSYNC_PERIOD_TIMING_CHANGED: return "VsyncPeriodTimingChanged"; + case HWC2_CALLBACK_SEAMLESS_POSSIBLE: return "SeamlessPossible"; + default: return "Unknown"; + } +} + +static inline const char* getCapabilityName(hwc2_capability_t capability) { + switch (capability) { + case HWC2_CAPABILITY_INVALID: return "Invalid"; + case HWC2_CAPABILITY_SIDEBAND_STREAM: return "SidebandStream"; + case HWC2_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM: + return "SkipClientColorTransform"; + case HWC2_CAPABILITY_PRESENT_FENCE_IS_NOT_RELIABLE: + return "PresentFenceIsNotReliable"; + default: return "Unknown"; + } +} + +static inline const char* getCompositionName(hwc2_composition_t composition) { + switch (composition) { + case HWC2_COMPOSITION_INVALID: return "Invalid"; + case HWC2_COMPOSITION_CLIENT: return "Client"; + case HWC2_COMPOSITION_DEVICE: return "Device"; + case HWC2_COMPOSITION_SOLID_COLOR: return "SolidColor"; + case HWC2_COMPOSITION_CURSOR: return "Cursor"; + case HWC2_COMPOSITION_SIDEBAND: return "Sideband"; + default: return "Unknown"; + } +} + +static inline const char* getConnectionName(hwc2_connection_t connection) { + switch (connection) { + case HWC2_CONNECTION_INVALID: return "Invalid"; + case HWC2_CONNECTION_CONNECTED: return "Connected"; + case HWC2_CONNECTION_DISCONNECTED: return "Disconnected"; + default: return "Unknown"; + } +} + +static inline const char* getDisplayRequestName( + hwc2_display_request_t request) { + switch (__BIONIC_CAST(static_cast, int, request)) { + case 0: return "None"; + case HWC2_DISPLAY_REQUEST_FLIP_CLIENT_TARGET: return "FlipClientTarget"; + case HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT: + return "WriteClientTargetToOutput"; + case HWC2_DISPLAY_REQUEST_FLIP_CLIENT_TARGET | + HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT: + return "FlipClientTarget|WriteClientTargetToOutput"; + default: return "Unknown"; + } +} + +static inline const char* getDisplayTypeName(hwc2_display_type_t type) { + switch (type) { + case HWC2_DISPLAY_TYPE_INVALID: return "Invalid"; + case HWC2_DISPLAY_TYPE_PHYSICAL: return "Physical"; + case HWC2_DISPLAY_TYPE_VIRTUAL: return "Virtual"; + default: return "Unknown"; + } +} + +static inline const char* getDisplayConnectionTypeName(hwc2_display_connection_type_t type) { + switch (type) { + case HWC2_DISPLAY_CONNECTION_TYPE_INTERNAL: return "Internal"; + case HWC2_DISPLAY_CONNECTION_TYPE_EXTERNAL: return "External"; + default: return "Unknown"; + } +} + +static inline const char* getErrorName(hwc2_error_t error) { + switch (error) { + case HWC2_ERROR_NONE: return "None"; + case HWC2_ERROR_BAD_CONFIG: return "BadConfig"; + case HWC2_ERROR_BAD_DISPLAY: return "BadDisplay"; + case HWC2_ERROR_BAD_LAYER: return "BadLayer"; + case HWC2_ERROR_BAD_PARAMETER: return "BadParameter"; + case HWC2_ERROR_HAS_CHANGES: return "HasChanges"; + case HWC2_ERROR_NO_RESOURCES: return "NoResources"; + case HWC2_ERROR_NOT_VALIDATED: return "NotValidated"; + case HWC2_ERROR_UNSUPPORTED: return "Unsupported"; + case HWC2_ERROR_SEAMLESS_NOT_ALLOWED: return "SeamlessNotAllowed"; + case HWC2_ERROR_SEAMLESS_NOT_POSSIBLE: return "SeamlessNotPossible"; + default: return "Unknown"; + } +} + +static inline const char* getFunctionDescriptorName( + hwc2_function_descriptor_t desc) { + switch (desc) { + case HWC2_FUNCTION_INVALID: return "Invalid"; + case HWC2_FUNCTION_ACCEPT_DISPLAY_CHANGES: + return "AcceptDisplayChanges"; + case HWC2_FUNCTION_CREATE_LAYER: return "CreateLayer"; + case HWC2_FUNCTION_CREATE_VIRTUAL_DISPLAY: + return "CreateVirtualDisplay"; + case HWC2_FUNCTION_DESTROY_LAYER: return "DestroyLayer"; + case HWC2_FUNCTION_DESTROY_VIRTUAL_DISPLAY: + return "DestroyVirtualDisplay"; + case HWC2_FUNCTION_DUMP: return "Dump"; + case HWC2_FUNCTION_GET_ACTIVE_CONFIG: return "GetActiveConfig"; + case HWC2_FUNCTION_GET_CHANGED_COMPOSITION_TYPES: + return "GetChangedCompositionTypes"; + case HWC2_FUNCTION_GET_CLIENT_TARGET_SUPPORT: + return "GetClientTargetSupport"; + case HWC2_FUNCTION_GET_COLOR_MODES: return "GetColorModes"; + case HWC2_FUNCTION_GET_DISPLAY_ATTRIBUTE: return "GetDisplayAttribute"; + case HWC2_FUNCTION_GET_DISPLAY_CONFIGS: return "GetDisplayConfigs"; + case HWC2_FUNCTION_GET_DISPLAY_NAME: return "GetDisplayName"; + case HWC2_FUNCTION_GET_DISPLAY_REQUESTS: return "GetDisplayRequests"; + case HWC2_FUNCTION_GET_DISPLAY_TYPE: return "GetDisplayType"; + case HWC2_FUNCTION_GET_DOZE_SUPPORT: return "GetDozeSupport"; + case HWC2_FUNCTION_GET_HDR_CAPABILITIES: return "GetHdrCapabilities"; + case HWC2_FUNCTION_GET_MAX_VIRTUAL_DISPLAY_COUNT: + return "GetMaxVirtualDisplayCount"; + case HWC2_FUNCTION_GET_RELEASE_FENCES: return "GetReleaseFences"; + case HWC2_FUNCTION_PRESENT_DISPLAY: return "PresentDisplay"; + case HWC2_FUNCTION_REGISTER_CALLBACK: return "RegisterCallback"; + case HWC2_FUNCTION_SET_ACTIVE_CONFIG: return "SetActiveConfig"; + case HWC2_FUNCTION_SET_CLIENT_TARGET: return "SetClientTarget"; + case HWC2_FUNCTION_SET_COLOR_MODE: return "SetColorMode"; + case HWC2_FUNCTION_SET_COLOR_TRANSFORM: return "SetColorTransform"; + case HWC2_FUNCTION_SET_CURSOR_POSITION: return "SetCursorPosition"; + case HWC2_FUNCTION_SET_LAYER_BLEND_MODE: return "SetLayerBlendMode"; + case HWC2_FUNCTION_SET_LAYER_BUFFER: return "SetLayerBuffer"; + case HWC2_FUNCTION_SET_LAYER_COLOR: return "SetLayerColor"; + case HWC2_FUNCTION_SET_LAYER_COMPOSITION_TYPE: + return "SetLayerCompositionType"; + case HWC2_FUNCTION_SET_LAYER_DATASPACE: return "SetLayerDataspace"; + case HWC2_FUNCTION_SET_LAYER_DISPLAY_FRAME: + return "SetLayerDisplayFrame"; + case HWC2_FUNCTION_SET_LAYER_PLANE_ALPHA: return "SetLayerPlaneAlpha"; + case HWC2_FUNCTION_SET_LAYER_SIDEBAND_STREAM: + return "SetLayerSidebandStream"; + case HWC2_FUNCTION_SET_LAYER_SOURCE_CROP: return "SetLayerSourceCrop"; + case HWC2_FUNCTION_SET_LAYER_SURFACE_DAMAGE: + return "SetLayerSurfaceDamage"; + case HWC2_FUNCTION_SET_LAYER_TRANSFORM: return "SetLayerTransform"; + case HWC2_FUNCTION_SET_LAYER_VISIBLE_REGION: + return "SetLayerVisibleRegion"; + case HWC2_FUNCTION_SET_LAYER_Z_ORDER: return "SetLayerZOrder"; + case HWC2_FUNCTION_SET_OUTPUT_BUFFER: return "SetOutputBuffer"; + case HWC2_FUNCTION_SET_POWER_MODE: return "SetPowerMode"; + case HWC2_FUNCTION_SET_VSYNC_ENABLED: return "SetVsyncEnabled"; + case HWC2_FUNCTION_VALIDATE_DISPLAY: return "ValidateDisplay"; + case HWC2_FUNCTION_SET_LAYER_FLOAT_COLOR: return "SetLayerFloatColor"; + case HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA: return "SetLayerPerFrameMetadata"; + case HWC2_FUNCTION_GET_PER_FRAME_METADATA_KEYS: return "GetPerFrameMetadataKeys"; + case HWC2_FUNCTION_SET_READBACK_BUFFER: return "SetReadbackBuffer"; + case HWC2_FUNCTION_GET_READBACK_BUFFER_ATTRIBUTES: return "GetReadbackBufferAttributes"; + case HWC2_FUNCTION_GET_READBACK_BUFFER_FENCE: return "GetReadbackBufferFence"; + case HWC2_FUNCTION_GET_RENDER_INTENTS: return "GetRenderIntents"; + case HWC2_FUNCTION_SET_COLOR_MODE_WITH_RENDER_INTENT: return "SetColorModeWithRenderIntent"; + case HWC2_FUNCTION_GET_DATASPACE_SATURATION_MATRIX: return "GetDataspaceSaturationMatrix"; + + // composer 2.3 + case HWC2_FUNCTION_GET_DISPLAY_IDENTIFICATION_DATA: return "GetDisplayIdentificationData"; + case HWC2_FUNCTION_GET_DISPLAY_CAPABILITIES: return "GetDisplayCapabilities"; + case HWC2_FUNCTION_SET_LAYER_COLOR_TRANSFORM: return "SetLayerColorTransform"; + case HWC2_FUNCTION_GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES: return "GetDisplayedContentSamplingAttributes"; + case HWC2_FUNCTION_SET_DISPLAYED_CONTENT_SAMPLING_ENABLED: return "SetDisplayedContentSamplingEnabled"; + case HWC2_FUNCTION_GET_DISPLAYED_CONTENT_SAMPLE: return "GetDisplayedContentSample"; + case HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA_BLOBS: return "SetLayerPerFrameMetadataBlobs"; + case HWC2_FUNCTION_GET_DISPLAY_BRIGHTNESS_SUPPORT: return "GetDisplayBrightnessSupport"; + case HWC2_FUNCTION_SET_DISPLAY_BRIGHTNESS: return "SetDisplayBrightness"; + + // composer 2.4 + case HWC2_FUNCTION_GET_DISPLAY_CONNECTION_TYPE: return "GetDisplayConnectionType"; + case HWC2_FUNCTION_GET_DISPLAY_VSYNC_PERIOD: return "GetDisplayVsyncPeriod"; + case HWC2_FUNCTION_SET_ACTIVE_CONFIG_WITH_CONSTRAINTS: return "SetActiveConfigWithConstraints"; + case HWC2_FUNCTION_SET_AUTO_LOW_LATENCY_MODE: return "SetAutoLowLatencyMode"; + case HWC2_FUNCTION_GET_SUPPORTED_CONTENT_TYPES: return "GetSupportedContentTypes"; + case HWC2_FUNCTION_SET_CONTENT_TYPE: return "SetContentType"; + case HWC2_FUNCTION_GET_CLIENT_TARGET_PROPERTY: return "GetClientTargetProperty"; + case HWC2_FUNCTION_SET_LAYER_GENERIC_METADATA: return "SetLayerGenericMetadata"; + case HWC2_FUNCTION_GET_LAYER_GENERIC_METADATA_KEY: return "GetLayerGenericMetadataKey"; + + default: return "Unknown"; + } +} + +static inline const char* getLayerRequestName(hwc2_layer_request_t request) { + switch (__BIONIC_CAST(static_cast, int, request)) { + case 0: return "None"; + case HWC2_LAYER_REQUEST_CLEAR_CLIENT_TARGET: return "ClearClientTarget"; + default: return "Unknown"; + } +} + +static inline const char* getPowerModeName(hwc2_power_mode_t mode) { + switch (mode) { + case HWC2_POWER_MODE_OFF: return "Off"; + case HWC2_POWER_MODE_DOZE_SUSPEND: return "DozeSuspend"; + case HWC2_POWER_MODE_DOZE: return "Doze"; + case HWC2_POWER_MODE_ON: return "On"; + default: return "Unknown"; + } +} + +static inline const char* getContentTypeName(hwc2_content_type_t contentType) { + switch(contentType) { + case HWC2_CONTENT_TYPE_NONE: return "None"; + case HWC2_CONTENT_TYPE_GRAPHICS: return "Graphics"; + case HWC2_CONTENT_TYPE_PHOTO: return "Photo"; + case HWC2_CONTENT_TYPE_CINEMA: return "Cinema"; + case HWC2_CONTENT_TYPE_GAME: return "Game"; + default: return "Unknown"; + } +} + +static inline const char* getTransformName(hwc_transform_t transform) { + switch (__BIONIC_CAST(static_cast, int, transform)) { + case 0: return "None"; + case HWC_TRANSFORM_FLIP_H: return "FlipH"; + case HWC_TRANSFORM_FLIP_V: return "FlipV"; + case HWC_TRANSFORM_ROT_90: return "Rotate90"; + case HWC_TRANSFORM_ROT_180: return "Rotate180"; + case HWC_TRANSFORM_ROT_270: return "Rotate270"; + case HWC_TRANSFORM_FLIP_H_ROT_90: return "FlipHRotate90"; + case HWC_TRANSFORM_FLIP_V_ROT_90: return "FlipVRotate90"; + default: return "Unknown"; + } +} + +static inline const char* getVsyncName(hwc2_vsync_t vsync) { + switch (vsync) { + case HWC2_VSYNC_INVALID: return "Invalid"; + case HWC2_VSYNC_ENABLE: return "Enable"; + case HWC2_VSYNC_DISABLE: return "Disable"; + default: return "Unknown"; + } +} + +static inline const char* getDisplayedContentSamplingName( + hwc2_displayed_content_sampling_t sampling) { + switch (sampling) { + case HWC2_DISPLAYED_CONTENT_SAMPLING_INVALID: return "Invalid"; + case HWC2_DISPLAYED_CONTENT_SAMPLING_ENABLE: return "Enable"; + case HWC2_DISPLAYED_CONTENT_SAMPLING_DISABLE: return "Disable"; + default: return "Unknown"; + } +} + +static inline const char* getFormatColorComponentName(hwc2_format_color_component_t component) { + switch (component) { + case HWC2_FORMAT_COMPONENT_0: return "FirstComponent"; + case HWC2_FORMAT_COMPONENT_1: return "SecondComponent"; + case HWC2_FORMAT_COMPONENT_2: return "ThirdComponent"; + case HWC2_FORMAT_COMPONENT_3: return "FourthComponent"; + default: return "Unknown"; + } +} + +static inline const char* getDisplayCapabilityName(hwc2_display_capability_t capability) { + switch (capability) { + case HWC2_DISPLAY_CAPABILITY_INVALID: return "Invalid"; + case HWC2_DISPLAY_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM: + return "SkipClientColorTransform"; + case HWC2_DISPLAY_CAPABILITY_DOZE: + return "Doze"; + case HWC2_DISPLAY_CAPABILITY_BRIGHTNESS: + return "Brightness"; + case HWC2_DISPLAY_CAPABILITY_AUTO_LOW_LATENCY_MODE: + return "AutoLowLatencyMode"; + default: + return "Unknown"; + } +} + +#define TO_STRING(E, T, printer) \ + inline std::string to_string(E value) { return printer(value); } \ + inline std::string to_string(T value) { return to_string(static_cast<E>(value)); } +#else // !HWC2_INCLUDE_STRINGIFICATION +#define TO_STRING(name, printer) +#endif // HWC2_INCLUDE_STRINGIFICATION + +/* + * C++11 features + */ + +#ifdef HWC2_USE_CPP11 +__END_DECLS + +#ifdef HWC2_INCLUDE_STRINGIFICATION +#include <string> +#endif + +namespace HWC2 { + +enum class Attribute : int32_t { + Invalid = HWC2_ATTRIBUTE_INVALID, + Width = HWC2_ATTRIBUTE_WIDTH, + Height = HWC2_ATTRIBUTE_HEIGHT, + VsyncPeriod = HWC2_ATTRIBUTE_VSYNC_PERIOD, + DpiX = HWC2_ATTRIBUTE_DPI_X, + DpiY = HWC2_ATTRIBUTE_DPI_Y, + ConfigGroup = HWC2_ATTRIBUTE_CONFIG_GROUP, +}; +TO_STRING(hwc2_attribute_t, Attribute, getAttributeName) + +enum class BlendMode : int32_t { + Invalid = HWC2_BLEND_MODE_INVALID, + None = HWC2_BLEND_MODE_NONE, + Premultiplied = HWC2_BLEND_MODE_PREMULTIPLIED, + Coverage = HWC2_BLEND_MODE_COVERAGE, +}; +TO_STRING(hwc2_blend_mode_t, BlendMode, getBlendModeName) + +enum class Callback : int32_t { + Invalid = HWC2_CALLBACK_INVALID, + Hotplug = HWC2_CALLBACK_HOTPLUG, + Refresh = HWC2_CALLBACK_REFRESH, + Vsync = HWC2_CALLBACK_VSYNC, + Vsync_2_4 = HWC2_CALLBACK_VSYNC_2_4, + VsyncPeriodTimingChanged = HWC2_CALLBACK_VSYNC_PERIOD_TIMING_CHANGED, + SeamlessPossible = HWC2_CALLBACK_SEAMLESS_POSSIBLE, +}; +TO_STRING(hwc2_callback_descriptor_t, Callback, getCallbackDescriptorName) + +enum class Capability : int32_t { + Invalid = HWC2_CAPABILITY_INVALID, + SidebandStream = HWC2_CAPABILITY_SIDEBAND_STREAM, + SkipClientColorTransform = HWC2_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM, + PresentFenceIsNotReliable = HWC2_CAPABILITY_PRESENT_FENCE_IS_NOT_RELIABLE, + SkipValidate = HWC2_CAPABILITY_SKIP_VALIDATE, +}; +TO_STRING(hwc2_capability_t, Capability, getCapabilityName) + +enum class Composition : int32_t { + Invalid = HWC2_COMPOSITION_INVALID, + Client = HWC2_COMPOSITION_CLIENT, + Device = HWC2_COMPOSITION_DEVICE, + SolidColor = HWC2_COMPOSITION_SOLID_COLOR, + Cursor = HWC2_COMPOSITION_CURSOR, + Sideband = HWC2_COMPOSITION_SIDEBAND, +}; +TO_STRING(hwc2_composition_t, Composition, getCompositionName) + +enum class Connection : int32_t { + Invalid = HWC2_CONNECTION_INVALID, + Connected = HWC2_CONNECTION_CONNECTED, + Disconnected = HWC2_CONNECTION_DISCONNECTED, +}; +TO_STRING(hwc2_connection_t, Connection, getConnectionName) + +enum class DisplayRequest : int32_t { + FlipClientTarget = HWC2_DISPLAY_REQUEST_FLIP_CLIENT_TARGET, + WriteClientTargetToOutput = + HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT, +}; +TO_STRING(hwc2_display_request_t, DisplayRequest, getDisplayRequestName) + +enum class DisplayType : int32_t { + Invalid = HWC2_DISPLAY_TYPE_INVALID, + Physical = HWC2_DISPLAY_TYPE_PHYSICAL, + Virtual = HWC2_DISPLAY_TYPE_VIRTUAL, +}; +TO_STRING(hwc2_display_type_t, DisplayType, getDisplayTypeName) + +enum class DisplayConnectionType : uint32_t { + Internal = HWC2_DISPLAY_CONNECTION_TYPE_INTERNAL, + External = HWC2_DISPLAY_CONNECTION_TYPE_EXTERNAL, +}; +TO_STRING(hwc2_display_connection_type_t, DisplayConnectionType, getDisplayConnectionTypeName) + +enum class Error : int32_t { + None = HWC2_ERROR_NONE, + BadConfig = HWC2_ERROR_BAD_CONFIG, + BadDisplay = HWC2_ERROR_BAD_DISPLAY, + BadLayer = HWC2_ERROR_BAD_LAYER, + BadParameter = HWC2_ERROR_BAD_PARAMETER, + HasChanges = HWC2_ERROR_HAS_CHANGES, + NoResources = HWC2_ERROR_NO_RESOURCES, + NotValidated = HWC2_ERROR_NOT_VALIDATED, + Unsupported = HWC2_ERROR_UNSUPPORTED, + SeamlessNotAllowed = HWC2_ERROR_SEAMLESS_NOT_ALLOWED, + SeamlessNotPossible = HWC2_ERROR_SEAMLESS_NOT_POSSIBLE, +}; +TO_STRING(hwc2_error_t, Error, getErrorName) + +enum class FunctionDescriptor : int32_t { + Invalid = HWC2_FUNCTION_INVALID, + AcceptDisplayChanges = HWC2_FUNCTION_ACCEPT_DISPLAY_CHANGES, + CreateLayer = HWC2_FUNCTION_CREATE_LAYER, + CreateVirtualDisplay = HWC2_FUNCTION_CREATE_VIRTUAL_DISPLAY, + DestroyLayer = HWC2_FUNCTION_DESTROY_LAYER, + DestroyVirtualDisplay = HWC2_FUNCTION_DESTROY_VIRTUAL_DISPLAY, + Dump = HWC2_FUNCTION_DUMP, + GetActiveConfig = HWC2_FUNCTION_GET_ACTIVE_CONFIG, + GetChangedCompositionTypes = HWC2_FUNCTION_GET_CHANGED_COMPOSITION_TYPES, + GetClientTargetSupport = HWC2_FUNCTION_GET_CLIENT_TARGET_SUPPORT, + GetColorModes = HWC2_FUNCTION_GET_COLOR_MODES, + GetDisplayAttribute = HWC2_FUNCTION_GET_DISPLAY_ATTRIBUTE, + GetDisplayConfigs = HWC2_FUNCTION_GET_DISPLAY_CONFIGS, + GetDisplayName = HWC2_FUNCTION_GET_DISPLAY_NAME, + GetDisplayRequests = HWC2_FUNCTION_GET_DISPLAY_REQUESTS, + GetDisplayType = HWC2_FUNCTION_GET_DISPLAY_TYPE, + GetDozeSupport = HWC2_FUNCTION_GET_DOZE_SUPPORT, + GetHdrCapabilities = HWC2_FUNCTION_GET_HDR_CAPABILITIES, + GetMaxVirtualDisplayCount = HWC2_FUNCTION_GET_MAX_VIRTUAL_DISPLAY_COUNT, + GetReleaseFences = HWC2_FUNCTION_GET_RELEASE_FENCES, + PresentDisplay = HWC2_FUNCTION_PRESENT_DISPLAY, + RegisterCallback = HWC2_FUNCTION_REGISTER_CALLBACK, + SetActiveConfig = HWC2_FUNCTION_SET_ACTIVE_CONFIG, + SetClientTarget = HWC2_FUNCTION_SET_CLIENT_TARGET, + SetColorMode = HWC2_FUNCTION_SET_COLOR_MODE, + SetColorTransform = HWC2_FUNCTION_SET_COLOR_TRANSFORM, + SetCursorPosition = HWC2_FUNCTION_SET_CURSOR_POSITION, + SetLayerBlendMode = HWC2_FUNCTION_SET_LAYER_BLEND_MODE, + SetLayerBuffer = HWC2_FUNCTION_SET_LAYER_BUFFER, + SetLayerColor = HWC2_FUNCTION_SET_LAYER_COLOR, + SetLayerCompositionType = HWC2_FUNCTION_SET_LAYER_COMPOSITION_TYPE, + SetLayerDataspace = HWC2_FUNCTION_SET_LAYER_DATASPACE, + SetLayerDisplayFrame = HWC2_FUNCTION_SET_LAYER_DISPLAY_FRAME, + SetLayerPlaneAlpha = HWC2_FUNCTION_SET_LAYER_PLANE_ALPHA, + SetLayerSidebandStream = HWC2_FUNCTION_SET_LAYER_SIDEBAND_STREAM, + SetLayerSourceCrop = HWC2_FUNCTION_SET_LAYER_SOURCE_CROP, + SetLayerSurfaceDamage = HWC2_FUNCTION_SET_LAYER_SURFACE_DAMAGE, + SetLayerTransform = HWC2_FUNCTION_SET_LAYER_TRANSFORM, + SetLayerVisibleRegion = HWC2_FUNCTION_SET_LAYER_VISIBLE_REGION, + SetLayerZOrder = HWC2_FUNCTION_SET_LAYER_Z_ORDER, + SetOutputBuffer = HWC2_FUNCTION_SET_OUTPUT_BUFFER, + SetPowerMode = HWC2_FUNCTION_SET_POWER_MODE, + SetVsyncEnabled = HWC2_FUNCTION_SET_VSYNC_ENABLED, + ValidateDisplay = HWC2_FUNCTION_VALIDATE_DISPLAY, + SetLayerFloatColor = HWC2_FUNCTION_SET_LAYER_FLOAT_COLOR, + SetLayerPerFrameMetadata = HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA, + GetPerFrameMetadataKeys = HWC2_FUNCTION_GET_PER_FRAME_METADATA_KEYS, + SetReadbackBuffer = HWC2_FUNCTION_SET_READBACK_BUFFER, + GetReadbackBufferAttributes = HWC2_FUNCTION_GET_READBACK_BUFFER_ATTRIBUTES, + GetReadbackBufferFence = HWC2_FUNCTION_GET_READBACK_BUFFER_FENCE, + GetRenderIntents = HWC2_FUNCTION_GET_RENDER_INTENTS, + SetColorModeWithRenderIntent = HWC2_FUNCTION_SET_COLOR_MODE_WITH_RENDER_INTENT, + GetDataspaceSaturationMatrix = HWC2_FUNCTION_GET_DATASPACE_SATURATION_MATRIX, + + // composer 2.3 + GetDisplayIdentificationData = HWC2_FUNCTION_GET_DISPLAY_IDENTIFICATION_DATA, + GetDisplayCapabilities = HWC2_FUNCTION_GET_DISPLAY_CAPABILITIES, + SetLayerColorTransform = HWC2_FUNCTION_SET_LAYER_COLOR_TRANSFORM, + GetDisplayedContentSamplingAttributes = HWC2_FUNCTION_GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES, + SetDisplayedContentSamplingEnabled = HWC2_FUNCTION_SET_DISPLAYED_CONTENT_SAMPLING_ENABLED, + GetDisplayedContentSample = HWC2_FUNCTION_GET_DISPLAYED_CONTENT_SAMPLE, + SetLayerPerFrameMetadataBlobs = HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA_BLOBS, + GetDisplayBrightnessSupport = HWC2_FUNCTION_GET_DISPLAY_BRIGHTNESS_SUPPORT, + SetDisplayBrightness = HWC2_FUNCTION_SET_DISPLAY_BRIGHTNESS, + + // composer 2.4 + GetDisplayConnectionType = HWC2_FUNCTION_GET_DISPLAY_CONNECTION_TYPE, + GetDisplayVsyncPeriod = HWC2_FUNCTION_GET_DISPLAY_VSYNC_PERIOD, + SetActiveConfigWithConstraints = HWC2_FUNCTION_SET_ACTIVE_CONFIG_WITH_CONSTRAINTS, + SetAutoLowLatencyMode = HWC2_FUNCTION_SET_AUTO_LOW_LATENCY_MODE, + GetSupportedContentTypes = HWC2_FUNCTION_GET_SUPPORTED_CONTENT_TYPES, + SetContentType = HWC2_FUNCTION_SET_CONTENT_TYPE, + GetClientTargetProperty = HWC2_FUNCTION_GET_CLIENT_TARGET_PROPERTY, + SetLayerGenericMetadata = HWC2_FUNCTION_SET_LAYER_GENERIC_METADATA, + GetLayerGenericMetadataKey = HWC2_FUNCTION_GET_LAYER_GENERIC_METADATA_KEY, +}; +TO_STRING(hwc2_function_descriptor_t, FunctionDescriptor, + getFunctionDescriptorName) + +enum class LayerRequest : int32_t { + ClearClientTarget = HWC2_LAYER_REQUEST_CLEAR_CLIENT_TARGET, +}; +TO_STRING(hwc2_layer_request_t, LayerRequest, getLayerRequestName) + +enum class PowerMode : int32_t { + Off = HWC2_POWER_MODE_OFF, + DozeSuspend = HWC2_POWER_MODE_DOZE_SUSPEND, + Doze = HWC2_POWER_MODE_DOZE, + On = HWC2_POWER_MODE_ON, +}; +TO_STRING(hwc2_power_mode_t, PowerMode, getPowerModeName) + +enum class ContentType : int32_t { + None = HWC2_CONTENT_TYPE_NONE, + Graphics = HWC2_CONTENT_TYPE_GRAPHICS, + Photo = HWC2_CONTENT_TYPE_PHOTO, + Cinema = HWC2_CONTENT_TYPE_CINEMA, + Game = HWC2_CONTENT_TYPE_GAME, +}; +TO_STRING(hwc2_content_type_t, ContentType, getContentTypeName) + +enum class Transform : int32_t { + None = 0, + FlipH = HWC_TRANSFORM_FLIP_H, + FlipV = HWC_TRANSFORM_FLIP_V, + Rotate90 = HWC_TRANSFORM_ROT_90, + Rotate180 = HWC_TRANSFORM_ROT_180, + Rotate270 = HWC_TRANSFORM_ROT_270, + FlipHRotate90 = HWC_TRANSFORM_FLIP_H_ROT_90, + FlipVRotate90 = HWC_TRANSFORM_FLIP_V_ROT_90, +}; +TO_STRING(hwc_transform_t, Transform, getTransformName) + +enum class Vsync : int32_t { + Invalid = HWC2_VSYNC_INVALID, + Enable = HWC2_VSYNC_ENABLE, + Disable = HWC2_VSYNC_DISABLE, +}; +TO_STRING(hwc2_vsync_t, Vsync, getVsyncName) + +enum class DisplayCapability : int32_t { + Invalid = HWC2_DISPLAY_CAPABILITY_INVALID, + SkipClientColorTransform = HWC2_DISPLAY_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM, + Doze = HWC2_DISPLAY_CAPABILITY_DOZE, + Brightness = HWC2_DISPLAY_CAPABILITY_BRIGHTNESS, + AutoLowLatencyMode = HWC2_DISPLAY_CAPABILITY_AUTO_LOW_LATENCY_MODE, +}; +TO_STRING(hwc2_display_capability_t, DisplayCapability, getDisplayCapabilityName) + +} // namespace HWC2 + +__BEGIN_DECLS +#endif // HWC2_USE_CPP11 + +/* + * Typedefs + */ + +typedef void (*hwc2_function_pointer_t)(); + +typedef void* hwc2_callback_data_t; +typedef uint32_t hwc2_config_t; +typedef uint64_t hwc2_display_t; +typedef uint64_t hwc2_layer_t; +typedef uint32_t hwc2_vsync_period_t; + +/* + * Device Struct + */ + +typedef struct hwc2_device { + /* Must be the first member of this struct, since a pointer to this struct + * will be generated by casting from a hw_device_t* */ + struct hw_device_t common; + + /* getCapabilities(..., outCount, outCapabilities) + * + * Provides a list of capabilities (described in the definition of + * hwc2_capability_t above) supported by this device. This list must + * not change after the device has been loaded. + * + * Parameters: + * outCount - if outCapabilities was NULL, the number of capabilities + * which would have been returned; if outCapabilities was not NULL, + * the number of capabilities returned, which must not exceed the + * value stored in outCount prior to the call + * outCapabilities - a list of capabilities supported by this device; may + * be NULL, in which case this function must write into outCount the + * number of capabilities which would have been written into + * outCapabilities + */ + void (*getCapabilities)(struct hwc2_device* device, uint32_t* outCount, + int32_t* /*hwc2_capability_t*/ outCapabilities); + + /* getFunction(..., descriptor) + * + * Returns a function pointer which implements the requested description. + * + * Parameters: + * descriptor - the function to return + * + * Returns either a function pointer implementing the requested descriptor + * or NULL if the described function is not supported by this device. + */ + hwc2_function_pointer_t (*getFunction)(struct hwc2_device* device, + int32_t /*hwc2_function_descriptor_t*/ descriptor); +} hwc2_device_t; + +static inline int hwc2_open(const struct hw_module_t* module, + hwc2_device_t** device) { + return module->methods->open(module, HWC_HARDWARE_COMPOSER, + TO_HW_DEVICE_T_OPEN(device)); +} + +static inline int hwc2_close(hwc2_device_t* device) { + return device->common.close(&device->common); +} + +/* + * Callbacks + * + * All of these callbacks take as their first parameter the callbackData which + * was provided at the time of callback registration, so this parameter is + * omitted from the described parameter lists. + */ + +/* hotplug(..., display, connected) + * Descriptor: HWC2_CALLBACK_HOTPLUG + * Will be provided to all HWC2 devices + * + * Notifies the client that the given display has either been connected or + * disconnected. Every active display (even a built-in physical display) must + * trigger at least one hotplug notification, even if it only occurs immediately + * after callback registration. + * + * The client may call back into the device on the same thread to query display + * properties (such as width, height, and vsync period), and other threads may + * call into the device while the callback is in progress. The device must + * serialize calls to this callback such that only one thread is calling it at a + * time. + * + * Displays which have been connected are assumed to be in HWC2_POWER_MODE_OFF, + * and the vsync callback should not be called for a display until vsync has + * been enabled with setVsyncEnabled. + * + * Parameters: + * display - the display which has been hotplugged + * connected - whether the display has been connected or disconnected + */ +typedef void (*HWC2_PFN_HOTPLUG)(hwc2_callback_data_t callbackData, + hwc2_display_t display, int32_t /*hwc2_connection_t*/ connected); + +/* refresh(..., display) + * Descriptor: HWC2_CALLBACK_REFRESH + * Will be provided to all HWC2 devices + * + * Notifies the client to trigger a screen refresh. This forces all layer state + * for this display to be resent, and the display to be validated and presented, + * even if there have been no changes. + * + * This refresh will occur some time after the callback is initiated, but not + * necessarily before it returns. This thread, however, is guaranteed not to + * call back into the device, thus it is safe to trigger this callback from + * other functions which call into the device. + * + * Parameters: + * display - the display to refresh + */ +typedef void (*HWC2_PFN_REFRESH)(hwc2_callback_data_t callbackData, + hwc2_display_t display); + +/* vsync(..., display, timestamp) + * Descriptor: HWC2_CALLBACK_VSYNC + * Will be provided to all HWC2 devices + * + * Notifies the client that a vsync event has occurred. This callback must + * only be triggered when vsync is enabled for this display (through + * setVsyncEnabled). + * + * This callback should be triggered from a thread of at least + * HAL_PRIORITY_URGENT_DISPLAY with as little latency as possible, typically + * less than 0.5 ms. This thread is guaranteed not to call back into the device. + * + * Parameters: + * display - the display which has received a vsync event + * timestamp - the CLOCK_MONOTONIC time at which the vsync event occurred, in + * nanoseconds + */ +typedef void (*HWC2_PFN_VSYNC)(hwc2_callback_data_t callbackData, + hwc2_display_t display, int64_t timestamp); + +/* vsync_2_4(..., display, timestamp, vsyncPeriodNanos) + * Descriptor: HWC2_CALLBACK_VSYNC_2_4 + * Required for HWC2 devices for composer 2.4 + * + * Notifies the client that a vsync event has occurred. This callback must + * only be triggered when vsync is enabled for this display (through + * setVsyncEnabled). + * + * This callback should be triggered from a thread of at least + * HAL_PRIORITY_URGENT_DISPLAY with as little latency as possible, typically + * less than 0.5 ms. This thread is guaranteed not to call back into the device. + * + * Parameters: + * display - the display which has received a vsync event + * timestamp - the CLOCK_MONOTONIC time at which the vsync event occurred, in + * nanoseconds + * vsyncPeriodNanos - the display vsync period in nanoseconds i.e. the next onVsync2_4 is + * expected to be called vsyncPeriod nanoseconds after this call. + */ +typedef void (*HWC2_PFN_VSYNC_2_4)(hwc2_callback_data_t callbackData, + hwc2_display_t display, int64_t timestamp, hwc2_vsync_period_t vsyncPeriodNanos); + +/* vsyncPeriodTimingChanged(..., display, updated_timeline) + * Descriptor: HWC2_CALLBACK_VSYNC_PERIOD_TIMING_CHANGED + * Optional for HWC2 devices for composer 2.4 + * + * Notifies the client that the previously reported timing for vsync period change has been + * updated. This may occur if the composer missed the deadline for changing the vsync period + * or the client submitted a refresh frame too late. + * + * This callback should be triggered from a thread of at least + * HAL_PRIORITY_URGENT_DISPLAY with as little latency as possible, typically + * less than 0.5 ms. This thread is guaranteed not to call back into the device. + * + * Parameters: + * display - the display which has received a vsync event + * updated_timeline - new timeline for the vsync period change + */ +typedef void (*HWC2_PFN_VSYNC_PERIOD_TIMING_CHANGED)(hwc2_callback_data_t callbackData, + hwc2_display_t display, hwc_vsync_period_change_timeline_t* updated_timeline); + +/* SeamlessPossible(..., display) + * Descriptor: HWC2_CALLBACK_SEAMLESS_POSSIBLE + * Optional for HWC2 devices for composer 2.4 + * + * Notifies the client that the conditions which previously led to returning SEAMLESS_NOT_POSSIBLE + * from setActiveConfigWithConstraints have changed and now seamless may be possible. Client should + * retry calling setActiveConfigWithConstraints. + * + * + * Parameters: + * display - a display setActiveConfigWithConstraints previously failed with + * SEAMLESS_NOT_POSSIBLE. + */ +typedef void (*HWC2_PFN_SEAMLESS_POSSIBLE)(hwc2_callback_data_t callbackData, + hwc2_display_t display); + +/* + * Device Functions + * + * All of these functions take as their first parameter a device pointer, so + * this parameter is omitted from the described parameter lists. + */ + +/* createVirtualDisplay(..., width, height, format, outDisplay) + * Descriptor: HWC2_FUNCTION_CREATE_VIRTUAL_DISPLAY + * Must be provided by all HWC2 devices + * + * Creates a new virtual display with the given width and height. The format + * passed into this function is the default format requested by the consumer of + * the virtual display output buffers. If a different format will be returned by + * the device, it should be returned in this parameter so it can be set properly + * when handing the buffers to the consumer. + * + * The display will be assumed to be on from the time the first frame is + * presented until the display is destroyed. + * + * Parameters: + * width - width in pixels + * height - height in pixels + * format - prior to the call, the default output buffer format selected by + * the consumer; after the call, the format the device will produce + * outDisplay - the newly-created virtual display; pointer will be non-NULL + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_UNSUPPORTED - the width or height is too large for the device to + * be able to create a virtual display + * HWC2_ERROR_NO_RESOURCES - the device is unable to create a new virtual + * display at this time + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_CREATE_VIRTUAL_DISPLAY)( + hwc2_device_t* device, uint32_t width, uint32_t height, + int32_t* /*android_pixel_format_t*/ format, hwc2_display_t* outDisplay); + +/* destroyVirtualDisplay(..., display) + * Descriptor: HWC2_FUNCTION_DESTROY_VIRTUAL_DISPLAY + * Must be provided by all HWC2 devices + * + * Destroys a virtual display. After this call all resources consumed by this + * display may be freed by the device and any operations performed on this + * display should fail. + * + * Parameters: + * display - the virtual display to destroy + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_PARAMETER - the display handle which was passed in does not + * refer to a virtual display + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_DESTROY_VIRTUAL_DISPLAY)( + hwc2_device_t* device, hwc2_display_t display); + +/* dump(..., outSize, outBuffer) + * Descriptor: HWC2_FUNCTION_DUMP + * Must be provided by all HWC2 devices + * + * Retrieves implementation-defined debug information, which will be displayed + * during, for example, `dumpsys SurfaceFlinger`. + * + * If called with outBuffer == NULL, the device should store a copy of the + * desired output and return its length in bytes in outSize. If the device + * already has a stored copy, that copy should be purged and replaced with a + * fresh copy. + * + * If called with outBuffer != NULL, the device should copy its stored version + * of the output into outBuffer and store how many bytes of data it copied into + * outSize. Prior to this call, the client will have populated outSize with the + * maximum number of bytes outBuffer can hold. The device must not write more + * than this amount into outBuffer. If the device does not currently have a + * stored copy, then it should return 0 in outSize. + * + * Any data written into outBuffer need not be null-terminated. + * + * Parameters: + * outSize - if outBuffer was NULL, the number of bytes needed to copy the + * device's stored output; if outBuffer was not NULL, the number of bytes + * written into it, which must not exceed the value stored in outSize + * prior to the call; pointer will be non-NULL + * outBuffer - the buffer to write the dump output into; may be NULL as + * described above; data written into this buffer need not be + * null-terminated + */ +typedef void (*HWC2_PFN_DUMP)(hwc2_device_t* device, uint32_t* outSize, + char* outBuffer); + +/* getMaxVirtualDisplayCount(...) + * Descriptor: HWC2_FUNCTION_GET_MAX_VIRTUAL_DISPLAY_COUNT + * Must be provided by all HWC2 devices + * + * Returns the maximum number of virtual displays supported by this device + * (which may be 0). The client will not attempt to create more than this many + * virtual displays on this device. This number must not change for the lifetime + * of the device. + */ +typedef uint32_t (*HWC2_PFN_GET_MAX_VIRTUAL_DISPLAY_COUNT)( + hwc2_device_t* device); + +/* registerCallback(..., descriptor, callbackData, pointer) + * Descriptor: HWC2_FUNCTION_REGISTER_CALLBACK + * Must be provided by all HWC2 devices + * + * Provides a callback for the device to call. All callbacks take a callbackData + * item as the first parameter, so this value should be stored with the callback + * for later use. The callbackData may differ from one callback to another. If + * this function is called multiple times with the same descriptor, later + * callbacks replace earlier ones. + * + * Parameters: + * descriptor - which callback should be set + * callBackdata - opaque data which must be passed back through the callback + * pointer - a non-NULL function pointer corresponding to the descriptor + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_PARAMETER - descriptor was invalid + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_REGISTER_CALLBACK)( + hwc2_device_t* device, + int32_t /*hwc2_callback_descriptor_t*/ descriptor, + hwc2_callback_data_t callbackData, hwc2_function_pointer_t pointer); + +/* getDataspaceSaturationMatrix(..., dataspace, outMatrix) + * Descriptor: HWC2_FUNCTION_GET_DATASPACE_SATURATION_MATRIX + * Provided by HWC2 devices which don't return nullptr function pointer. + * + * Get the saturation matrix of the specified dataspace. The saturation matrix + * can be used to approximate the dataspace saturation operation performed by + * the HWC2 device when non-colorimetric mapping is allowed. It is to be + * applied on linear pixel values. + * + * Parameters: + * dataspace - the dataspace to query for + * outMatrix - a column-major 4x4 matrix (16 floats). It must be an identity + * matrix unless dataspace is HAL_DATASPACE_SRGB_LINEAR. + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_PARAMETER - dataspace was invalid + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DATASPACE_SATURATION_MATRIX)( + hwc2_device_t* device, int32_t /*android_dataspace_t*/ dataspace, + float* outMatrix); + +/* + * Display Functions + * + * All of these functions take as their first two parameters a device pointer + * and a display handle, so these parameters are omitted from the described + * parameter lists. + */ + +/* acceptDisplayChanges(...) + * Descriptor: HWC2_FUNCTION_ACCEPT_DISPLAY_CHANGES + * Must be provided by all HWC2 devices + * + * Accepts the changes required by the device from the previous validateDisplay + * call (which may be queried using getChangedCompositionTypes) and revalidates + * the display. This function is equivalent to requesting the changed types from + * getChangedCompositionTypes, setting those types on the corresponding layers, + * and then calling validateDisplay again. + * + * After this call it must be valid to present this display. Calling this after + * validateDisplay returns 0 changes must succeed with HWC2_ERROR_NONE, but + * should have no other effect. + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_NOT_VALIDATED - validateDisplay has not been called + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_ACCEPT_DISPLAY_CHANGES)( + hwc2_device_t* device, hwc2_display_t display); + +/* createLayer(..., outLayer) + * Descriptor: HWC2_FUNCTION_CREATE_LAYER + * Must be provided by all HWC2 devices + * + * Creates a new layer on the given display. + * + * Parameters: + * outLayer - the handle of the new layer; pointer will be non-NULL + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_NO_RESOURCES - the device was unable to create this layer + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_CREATE_LAYER)(hwc2_device_t* device, + hwc2_display_t display, hwc2_layer_t* outLayer); + +/* destroyLayer(..., layer) + * Descriptor: HWC2_FUNCTION_DESTROY_LAYER + * Must be provided by all HWC2 devices + * + * Destroys the given layer. + * + * Parameters: + * layer - the handle of the layer to destroy + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_DESTROY_LAYER)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer); + +/* getActiveConfig(..., outConfig) + * Descriptor: HWC2_FUNCTION_GET_ACTIVE_CONFIG + * Must be provided by all HWC2 devices + * + * Retrieves which display configuration is currently active. + * + * If no display configuration is currently active, this function must return + * HWC2_ERROR_BAD_CONFIG and place no configuration handle in outConfig. It is + * the responsibility of the client to call setActiveConfig with a valid + * configuration before attempting to present anything on the display. + * + * Parameters: + * outConfig - the currently active display configuration; pointer will be + * non-NULL + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_CONFIG - no configuration is currently active + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_ACTIVE_CONFIG)( + hwc2_device_t* device, hwc2_display_t display, + hwc2_config_t* outConfig); + +/* getChangedCompositionTypes(..., outNumElements, outLayers, outTypes) + * Descriptor: HWC2_FUNCTION_GET_CHANGED_COMPOSITION_TYPES + * Must be provided by all HWC2 devices + * + * Retrieves the layers for which the device requires a different composition + * type than had been set prior to the last call to validateDisplay. The client + * will either update its state with these types and call acceptDisplayChanges, + * or will set new types and attempt to validate the display again. + * + * outLayers and outTypes may be NULL to retrieve the number of elements which + * will be returned. The number of elements returned must be the same as the + * value returned in outNumTypes from the last call to validateDisplay. + * + * Parameters: + * outNumElements - if outLayers or outTypes were NULL, the number of layers + * and types which would have been returned; if both were non-NULL, the + * number of elements returned in outLayers and outTypes, which must not + * exceed the value stored in outNumElements prior to the call; pointer + * will be non-NULL + * outLayers - an array of layer handles + * outTypes - an array of composition types, each corresponding to an element + * of outLayers + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_NOT_VALIDATED - validateDisplay has not been called for this + * display + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_CHANGED_COMPOSITION_TYPES)( + hwc2_device_t* device, hwc2_display_t display, + uint32_t* outNumElements, hwc2_layer_t* outLayers, + int32_t* /*hwc2_composition_t*/ outTypes); + +/* getClientTargetSupport(..., width, height, format, dataspace) + * Descriptor: HWC2_FUNCTION_GET_CLIENT_TARGET_SUPPORT + * Must be provided by all HWC2 devices + * + * Returns whether a client target with the given properties can be handled by + * the device. + * + * The valid formats can be found in android_pixel_format_t in + * <system/graphics.h>. + * + * For more about dataspaces, see setLayerDataspace. + * + * This function must return true for a client target with width and height + * equal to the active display configuration dimensions, + * HAL_PIXEL_FORMAT_RGBA_8888, and HAL_DATASPACE_UNKNOWN. It is not required to + * return true for any other configuration. + * + * Parameters: + * width - client target width in pixels + * height - client target height in pixels + * format - client target format + * dataspace - client target dataspace, as described in setLayerDataspace + * + * Returns HWC2_ERROR_NONE if the given configuration is supported or one of the + * following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_UNSUPPORTED - the given configuration is not supported + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_CLIENT_TARGET_SUPPORT)( + hwc2_device_t* device, hwc2_display_t display, uint32_t width, + uint32_t height, int32_t /*android_pixel_format_t*/ format, + int32_t /*android_dataspace_t*/ dataspace); + +/* getColorModes(..., outNumModes, outModes) + * Descriptor: HWC2_FUNCTION_GET_COLOR_MODES + * Must be provided by all HWC2 devices + * + * Returns the color modes supported on this display. + * + * The valid color modes can be found in android_color_mode_t in + * <system/graphics.h>. All HWC2 devices must support at least + * HAL_COLOR_MODE_NATIVE. + * + * outNumModes may be NULL to retrieve the number of modes which will be + * returned. + * + * Parameters: + * outNumModes - if outModes was NULL, the number of modes which would have + * been returned; if outModes was not NULL, the number of modes returned, + * which must not exceed the value stored in outNumModes prior to the + * call; pointer will be non-NULL + * outModes - an array of color modes + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_COLOR_MODES)( + hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumModes, + int32_t* /*android_color_mode_t*/ outModes); + +/* getRenderIntents(..., mode, outNumIntents, outIntents) + * Descriptor: HWC2_FUNCTION_GET_RENDER_INTENTS + * Provided by HWC2 devices which don't return nullptr function pointer. + * + * Returns the render intents supported on this display. + * + * The valid render intents can be found in android_render_intent_v1_1_t in + * <system/graphics.h>. All HWC2 devices must support at least + * HAL_RENDER_INTENT_COLORIMETRIC. + * + * outNumIntents may be NULL to retrieve the number of intents which will be + * returned. + * + * Parameters: + * mode - the color mode to query the render intents for + * outNumIntents - if outIntents was NULL, the number of intents which would + * have been returned; if outIntents was not NULL, the number of intents + * returned, which must not exceed the value stored in outNumIntents + * prior to the call; pointer will be non-NULL + * outIntents - an array of render intents + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_RENDER_INTENTS)( + hwc2_device_t* device, hwc2_display_t display, int32_t mode, + uint32_t* outNumIntents, + int32_t* /*android_render_intent_v1_1_t*/ outIntents); + +/* getDisplayAttribute(..., config, attribute, outValue) + * Descriptor: HWC2_FUNCTION_GET_DISPLAY_ATTRIBUTE + * Must be provided by all HWC2 devices + * + * Returns a display attribute value for a particular display configuration. + * + * Any attribute which is not supported or for which the value is unknown by the + * device must return a value of -1. + * + * Parameters: + * config - the display configuration for which to return attribute values + * attribute - the attribute to query + * outValue - the value of the attribute; the pointer will be non-NULL + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_CONFIG - config does not name a valid configuration for this + * display + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_ATTRIBUTE)( + hwc2_device_t* device, hwc2_display_t display, hwc2_config_t config, + int32_t /*hwc2_attribute_t*/ attribute, int32_t* outValue); + +/* getDisplayConfigs(..., outNumConfigs, outConfigs) + * Descriptor: HWC2_FUNCTION_GET_DISPLAY_CONFIGS + * Must be provided by all HWC2 devices + * + * Returns handles for all of the valid display configurations on this display. + * + * outConfigs may be NULL to retrieve the number of elements which will be + * returned. + * + * Parameters: + * outNumConfigs - if outConfigs was NULL, the number of configurations which + * would have been returned; if outConfigs was not NULL, the number of + * configurations returned, which must not exceed the value stored in + * outNumConfigs prior to the call; pointer will be non-NULL + * outConfigs - an array of configuration handles + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_CONFIGS)( + hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumConfigs, + hwc2_config_t* outConfigs); + +/* getDisplayName(..., outSize, outName) + * Descriptor: HWC2_FUNCTION_GET_DISPLAY_NAME + * Must be provided by all HWC2 devices + * + * Returns a human-readable version of the display's name. + * + * outName may be NULL to retrieve the length of the name. + * + * Parameters: + * outSize - if outName was NULL, the number of bytes needed to return the + * name if outName was not NULL, the number of bytes written into it, + * which must not exceed the value stored in outSize prior to the call; + * pointer will be non-NULL + * outName - the display's name + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_NAME)( + hwc2_device_t* device, hwc2_display_t display, uint32_t* outSize, + char* outName); + +/* getDisplayRequests(..., outDisplayRequests, outNumElements, outLayers, + * outLayerRequests) + * Descriptor: HWC2_FUNCTION_GET_DISPLAY_REQUESTS + * Must be provided by all HWC2 devices + * + * Returns the display requests and the layer requests required for the last + * validated configuration. + * + * Display requests provide information about how the client should handle the + * client target. Layer requests provide information about how the client + * should handle an individual layer. + * + * If outLayers or outLayerRequests is NULL, the required number of layers and + * requests must be returned in outNumElements, but this number may also be + * obtained from validateDisplay as outNumRequests (outNumElements must be equal + * to the value returned in outNumRequests from the last call to + * validateDisplay). + * + * Parameters: + * outDisplayRequests - the display requests for the current validated state + * outNumElements - if outLayers or outLayerRequests were NULL, the number of + * elements which would have been returned, which must be equal to the + * value returned in outNumRequests from the last validateDisplay call on + * this display; if both were not NULL, the number of elements in + * outLayers and outLayerRequests, which must not exceed the value stored + * in outNumElements prior to the call; pointer will be non-NULL + * outLayers - an array of layers which all have at least one request + * outLayerRequests - the requests corresponding to each element of outLayers + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_NOT_VALIDATED - validateDisplay has not been called for this + * display + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_REQUESTS)( + hwc2_device_t* device, hwc2_display_t display, + int32_t* /*hwc2_display_request_t*/ outDisplayRequests, + uint32_t* outNumElements, hwc2_layer_t* outLayers, + int32_t* /*hwc2_layer_request_t*/ outLayerRequests); + +/* getDisplayType(..., outType) + * Descriptor: HWC2_FUNCTION_GET_DISPLAY_TYPE + * Must be provided by all HWC2 devices + * + * Returns whether the given display is a physical or virtual display. + * + * Parameters: + * outType - the type of the display; pointer will be non-NULL + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_TYPE)( + hwc2_device_t* device, hwc2_display_t display, + int32_t* /*hwc2_display_type_t*/ outType); + +/* getDisplayIdentificationData(..., outPort, outDataSize, outData) + * Descriptor: HWC2_FUNCTION_GET_DISPLAY_IDENTIFICATION_DATA + * Optional for HWC2 devices + * + * If supported, getDisplayIdentificationData returns the port and data that + * describe a physical display. The port is a unique number that identifies a + * physical connector (e.g. eDP, HDMI) for display output. The data blob is + * parsed to determine its format, typically EDID 1.3 as specified in VESA + * E-EDID Standard Release A Revision 1. + * + * Devices for which display identification is unsupported must return null when + * getFunction is called with HWC2_FUNCTION_GET_DISPLAY_IDENTIFICATION_DATA. + * + * Parameters: + * outPort - the connector to which the display is connected; + * pointer will be non-NULL + * outDataSize - if outData is NULL, the size in bytes of the data which would + * have been returned; if outData is not NULL, the size of outData, which + * must not exceed the value stored in outDataSize prior to the call; + * pointer will be non-NULL + * outData - the EDID 1.3 blob identifying the display + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_IDENTIFICATION_DATA)( + hwc2_device_t* device, hwc2_display_t display, uint8_t* outPort, + uint32_t* outDataSize, uint8_t* outData); + +/* getDozeSupport(..., outSupport) + * Descriptor: HWC2_FUNCTION_GET_DOZE_SUPPORT + * Must be provided by all HWC2 devices + * + * Returns whether the given display supports HWC2_POWER_MODE_DOZE and + * HWC2_POWER_MODE_DOZE_SUSPEND. DOZE_SUSPEND may not provide any benefit over + * DOZE (see the definition of hwc2_power_mode_t for more information), but if + * both DOZE and DOZE_SUSPEND are no different from HWC2_POWER_MODE_ON, the + * device should not claim support. + * + * Parameters: + * outSupport - whether the display supports doze modes (1 for yes, 0 for no); + * pointer will be non-NULL + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DOZE_SUPPORT)( + hwc2_device_t* device, hwc2_display_t display, int32_t* outSupport); + +/* getHdrCapabilities(..., outNumTypes, outTypes, outMaxLuminance, + * outMaxAverageLuminance, outMinLuminance) + * Descriptor: HWC2_FUNCTION_GET_HDR_CAPABILITIES + * Must be provided by all HWC2 devices + * + * Returns the high dynamic range (HDR) capabilities of the given display, which + * are invariant with regard to the active configuration. + * + * Displays which are not HDR-capable must return no types in outTypes and set + * outNumTypes to 0. + * + * If outTypes is NULL, the required number of HDR types must be returned in + * outNumTypes. + * + * Parameters: + * outNumTypes - if outTypes was NULL, the number of types which would have + * been returned; if it was not NULL, the number of types stored in + * outTypes, which must not exceed the value stored in outNumTypes prior + * to the call; pointer will be non-NULL + * outTypes - an array of HDR types, may have 0 elements if the display is not + * HDR-capable + * outMaxLuminance - the desired content maximum luminance for this display in + * cd/m^2; pointer will be non-NULL + * outMaxAverageLuminance - the desired content maximum frame-average + * luminance for this display in cd/m^2; pointer will be non-NULL + * outMinLuminance - the desired content minimum luminance for this display in + * cd/m^2; pointer will be non-NULL + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_HDR_CAPABILITIES)( + hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumTypes, + int32_t* /*android_hdr_t*/ outTypes, float* outMaxLuminance, + float* outMaxAverageLuminance, float* outMinLuminance); + +/* getReleaseFences(..., outNumElements, outLayers, outFences) + * Descriptor: HWC2_FUNCTION_GET_RELEASE_FENCES + * Must be provided by all HWC2 devices + * + * Retrieves the release fences for device layers on this display which will + * receive new buffer contents this frame. + * + * A release fence is a file descriptor referring to a sync fence object which + * will be signaled after the device has finished reading from the buffer + * presented in the prior frame. This indicates that it is safe to start writing + * to the buffer again. If a given layer's fence is not returned from this + * function, it will be assumed that the buffer presented on the previous frame + * is ready to be written. + * + * The fences returned by this function should be unique for each layer (even if + * they point to the same underlying sync object), and ownership of the fences + * is transferred to the client, which is responsible for closing them. + * + * If outLayers or outFences is NULL, the required number of layers and fences + * must be returned in outNumElements. + * + * Parameters: + * outNumElements - if outLayers or outFences were NULL, the number of + * elements which would have been returned; if both were not NULL, the + * number of elements in outLayers and outFences, which must not exceed + * the value stored in outNumElements prior to the call; pointer will be + * non-NULL + * outLayers - an array of layer handles + * outFences - an array of sync fence file descriptors as described above, + * each corresponding to an element of outLayers + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_RELEASE_FENCES)( + hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumElements, + hwc2_layer_t* outLayers, int32_t* outFences); + +/* presentDisplay(..., outPresentFence) + * Descriptor: HWC2_FUNCTION_PRESENT_DISPLAY + * Must be provided by all HWC2 devices + * + * Presents the current display contents on the screen (or in the case of + * virtual displays, into the output buffer). + * + * Prior to calling this function, the display must be successfully validated + * with validateDisplay. Note that setLayerBuffer and setLayerSurfaceDamage + * specifically do not count as layer state, so if there are no other changes + * to the layer state (or to the buffer's properties as described in + * setLayerBuffer), then it is safe to call this function without first + * validating the display. + * + * If this call succeeds, outPresentFence will be populated with a file + * descriptor referring to a present sync fence object. For physical displays, + * this fence will be signaled at the vsync when the result of composition of + * this frame starts to appear (for video-mode panels) or starts to transfer to + * panel memory (for command-mode panels). For virtual displays, this fence will + * be signaled when writes to the output buffer have completed and it is safe to + * read from it. + * + * Parameters: + * outPresentFence - a sync fence file descriptor as described above; pointer + * will be non-NULL + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_NO_RESOURCES - no valid output buffer has been set for a virtual + * display + * HWC2_ERROR_NOT_VALIDATED - validateDisplay has not successfully been called + * for this display + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_PRESENT_DISPLAY)( + hwc2_device_t* device, hwc2_display_t display, + int32_t* outPresentFence); + +/* setActiveConfig(..., config) + * Descriptor: HWC2_FUNCTION_SET_ACTIVE_CONFIG + * Must be provided by all HWC2 devices + * + * Sets the active configuration for this display. Upon returning, the given + * display configuration should be active and remain so until either this + * function is called again or the display is disconnected. + * + * Parameters: + * config - the new display configuration + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_CONFIG - the configuration handle passed in is not valid for + * this display + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_ACTIVE_CONFIG)( + hwc2_device_t* device, hwc2_display_t display, hwc2_config_t config); + +/* setClientTarget(..., target, acquireFence, dataspace, damage) + * Descriptor: HWC2_FUNCTION_SET_CLIENT_TARGET + * Must be provided by all HWC2 devices + * + * Sets the buffer handle which will receive the output of client composition. + * Layers marked as HWC2_COMPOSITION_CLIENT will be composited into this buffer + * prior to the call to presentDisplay, and layers not marked as + * HWC2_COMPOSITION_CLIENT should be composited with this buffer by the device. + * + * The buffer handle provided may be null if no layers are being composited by + * the client. This must not result in an error (unless an invalid display + * handle is also provided). + * + * Also provides a file descriptor referring to an acquire sync fence object, + * which will be signaled when it is safe to read from the client target buffer. + * If it is already safe to read from this buffer, -1 may be passed instead. + * The device must ensure that it is safe for the client to close this file + * descriptor at any point after this function is called. + * + * For more about dataspaces, see setLayerDataspace. + * + * The damage parameter describes a surface damage region as defined in the + * description of setLayerSurfaceDamage. + * + * Will be called before presentDisplay if any of the layers are marked as + * HWC2_COMPOSITION_CLIENT. If no layers are so marked, then it is not + * necessary to call this function. It is not necessary to call validateDisplay + * after changing the target through this function. + * + * Parameters: + * target - the new target buffer + * acquireFence - a sync fence file descriptor as described above + * dataspace - the dataspace of the buffer, as described in setLayerDataspace + * damage - the surface damage region + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_PARAMETER - the new target handle was invalid + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_CLIENT_TARGET)( + hwc2_device_t* device, hwc2_display_t display, buffer_handle_t target, + int32_t acquireFence, int32_t /*android_dataspace_t*/ dataspace, + hwc_region_t damage); + +/* setColorMode(..., mode) + * Descriptor: HWC2_FUNCTION_SET_COLOR_MODE + * Must be provided by all HWC2 devices + * + * Sets the color mode of the given display. + * + * This must be called outside of validateDisplay/presentDisplay, and it takes + * effect on next presentDisplay. + * + * The valid color modes can be found in android_color_mode_t in + * <system/graphics.h>. All HWC2 devices must support at least + * HAL_COLOR_MODE_NATIVE, and displays are assumed to be in this mode upon + * hotplug. + * + * Parameters: + * mode - the mode to set + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_PARAMETER - mode is not a valid color mode + * HWC2_ERROR_UNSUPPORTED - mode is not supported on this display + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_COLOR_MODE)( + hwc2_device_t* device, hwc2_display_t display, + int32_t /*android_color_mode_t*/ mode); + +/* setColorModeWithIntent(..., mode, intent) + * Descriptor: HWC2_FUNCTION_SET_COLOR_MODE_WITH_RENDER_INTENT + * Provided by HWC2 devices which don't return nullptr function pointer. + * + * This must be called outside of validateDisplay/presentDisplay, and it takes + * effect on next presentDisplay. + * + * The valid color modes and render intents can be found in + * android_color_mode_t and android_render_intent_v1_1_t in + * <system/graphics.h>. All HWC2 devices must support at least + * HAL_COLOR_MODE_NATIVE and HAL_RENDER_INTENT_COLORIMETRIC, and displays are + * assumed to be in this mode and intent upon hotplug. + * + * Parameters: + * mode - the mode to set + * intent - the intent to set + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_PARAMETER - mode/intent is not a valid color mode or + * render intent + * HWC2_ERROR_UNSUPPORTED - mode or intent is not supported on this display + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_COLOR_MODE_WITH_RENDER_INTENT)( + hwc2_device_t* device, hwc2_display_t display, + int32_t /*android_color_mode_t*/ mode, + int32_t /*android_render_intent_v1_1_t */ intent); + +/* setColorTransform(..., matrix, hint) + * Descriptor: HWC2_FUNCTION_SET_COLOR_TRANSFORM + * Must be provided by all HWC2 devices + * + * Sets a color transform which will be applied after composition. + * + * If hint is not HAL_COLOR_TRANSFORM_ARBITRARY, then the device may use the + * hint to apply the desired color transform instead of using the color matrix + * directly. + * + * If the device is not capable of either using the hint or the matrix to apply + * the desired color transform, it should force all layers to client composition + * during validateDisplay. + * + * If HWC2_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM is present, then the client + * will never apply the color transform during client composition, even if all + * layers are being composed by the client. + * + * The matrix provided is an affine color transformation of the following form: + * + * |r.r r.g r.b 0| + * |g.r g.g g.b 0| + * |b.r b.g b.b 0| + * |Tr Tg Tb 1| + * + * This matrix will be provided in row-major form: {r.r, r.g, r.b, 0, g.r, ...}. + * + * Given a matrix of this form and an input color [R_in, G_in, B_in], the output + * color [R_out, G_out, B_out] will be: + * + * R_out = R_in * r.r + G_in * g.r + B_in * b.r + Tr + * G_out = R_in * r.g + G_in * g.g + B_in * b.g + Tg + * B_out = R_in * r.b + G_in * g.b + B_in * b.b + Tb + * + * Parameters: + * matrix - a 4x4 transform matrix (16 floats) as described above + * hint - a hint value which may be used instead of the given matrix unless it + * is HAL_COLOR_TRANSFORM_ARBITRARY + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_PARAMETER - hint is not a valid color transform hint + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_COLOR_TRANSFORM)( + hwc2_device_t* device, hwc2_display_t display, const float* matrix, + int32_t /*android_color_transform_t*/ hint); + +/* getPerFrameMetadataKeys(..., outKeys) + * Descriptor: HWC2_FUNCTION_GET_PER_FRAME_METADATA_KEYS + * Optional for HWC2 devices + * + * If supported (getFunction(HWC2_FUNCTION_GET_PER_FRAME_METADATA_KEYS) is non-null), + * getPerFrameMetadataKeys returns the list of supported PerFrameMetadataKeys + * which are invariant with regard to the active configuration. + * + * Devices which are not HDR-capable, must return null when getFunction is called + * with HWC2_FUNCTION_GET_PER_FRAME_METADATA_KEYS. + * + * If outKeys is NULL, the required number of PerFrameMetadataKey keys + * must be returned in outNumKeys. + * + * Parameters: + * outNumKeys - if outKeys is NULL, the number of keys which would have + * been returned; if outKeys is not NULL, the number of keys stored in + * outKeys, which must not exceed the value stored in outNumKeys prior + * to the call; pointer will be non-NULL + * outKeys - an array of hwc2_per_frame_metadata_key_t keys + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_PER_FRAME_METADATA_KEYS)( + hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumKeys, + int32_t* /*hwc2_per_frame_metadata_key_t*/ outKeys); + +/* setOutputBuffer(..., buffer, releaseFence) + * Descriptor: HWC2_FUNCTION_SET_OUTPUT_BUFFER + * Must be provided by all HWC2 devices + * + * Sets the output buffer for a virtual display. That is, the buffer to which + * the composition result will be written. + * + * Also provides a file descriptor referring to a release sync fence object, + * which will be signaled when it is safe to write to the output buffer. If it + * is already safe to write to the output buffer, -1 may be passed instead. The + * device must ensure that it is safe for the client to close this file + * descriptor at any point after this function is called. + * + * Must be called at least once before presentDisplay, but does not have any + * interaction with layer state or display validation. + * + * Parameters: + * buffer - the new output buffer + * releaseFence - a sync fence file descriptor as described above + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_PARAMETER - the new output buffer handle was invalid + * HWC2_ERROR_UNSUPPORTED - display does not refer to a virtual display + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_OUTPUT_BUFFER)( + hwc2_device_t* device, hwc2_display_t display, buffer_handle_t buffer, + int32_t releaseFence); + +/* setPowerMode(..., mode) + * Descriptor: HWC2_FUNCTION_SET_POWER_MODE + * Must be provided by all HWC2 devices + * + * Sets the power mode of the given display. The transition must be complete + * when this function returns. It is valid to call this function multiple times + * with the same power mode. + * + * All displays must support HWC2_POWER_MODE_ON and HWC2_POWER_MODE_OFF. Whether + * a display supports HWC2_POWER_MODE_DOZE or HWC2_POWER_MODE_DOZE_SUSPEND may + * be queried using getDozeSupport. + * + * Parameters: + * mode - the new power mode + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_PARAMETER - mode was not a valid power mode + * HWC2_ERROR_UNSUPPORTED - mode was a valid power mode, but is not supported + * on this display + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_POWER_MODE)( + hwc2_device_t* device, hwc2_display_t display, + int32_t /*hwc2_power_mode_t*/ mode); + +/* getReadbackBufferAttributes(..., outFormat, outDataspace) + * Optional for HWC2 devices + * + * Returns the format which should be used when allocating a buffer for use by + * device readback as well as the dataspace in which its contents should be + * interpreted. + * + * If readback is not supported by this HWC implementation, this call will also + * be able to return HWC2_ERROR_UNSUPPORTED so we can fall back to another method. + * Returning NULL to a getFunction request for this function will also indicate + * that readback is not supported. + * + * The width and height of this buffer will be those of the currently-active + * display configuration, and the usage flags will consist of the following: + * BufferUsage::CPU_READ | BufferUsage::GPU_TEXTURE | + * BufferUsage::COMPOSER_OUTPUT + * + * The format and dataspace provided must be sufficient such that if a + * correctly-configured buffer is passed into setReadbackBuffer, filled by + * the device, and then displayed by the client as a full-screen buffer, the + * output of the display remains the same (subject to the note about protected + * content in the description of setReadbackBuffer). + * + * If the active configuration or color mode of this display has changed since + * the previous call to this function, it will be called again prior to setting + * a readback buffer such that the returned format and dataspace can be updated + * accordingly. + * + * Parameters: + * outFormat - the format the client should use when allocating a device + * readback buffer; pointer will be non-NULL + * outDataspace - the dataspace the client will use when interpreting the + * contents of a device readback buffer; pointer will be non-NULL + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * + * See also: + * setReadbackBuffer + * getReadbackBufferFence + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_READBACK_BUFFER_ATTRIBUTES)( + hwc2_device_t* device, hwc2_display_t display, + int32_t* /*android_pixel_format_t*/ outFormat, + int32_t* /*android_dataspace_t*/ outDataspace); + +/* getReadbackBufferFence(..., outFence) + * Optional for HWC2 devices + * + * Returns an acquire sync fence file descriptor which will signal when the + * buffer provided to setReadbackBuffer has been filled by the device and is + * safe for the client to read. + * + * If it is already safe to read from this buffer, -1 may be returned instead. + * The client takes ownership of this file descriptor and is responsible for + * closing it when it is no longer needed. + * + * This function will be called immediately after the composition cycle being + * captured into the readback buffer. The complete ordering of a readback buffer + * capture is as follows: + * + * getReadbackBufferAttributes + * // Readback buffer is allocated + * // Many frames may pass + * + * setReadbackBuffer + * validateDisplay + * presentDisplay + * getReadbackBufferFence + * // Implicitly wait on the acquire fence before accessing the buffer + * + * Parameters: + * outFence - a sync fence file descriptor as described above; pointer + * will be non-NULL + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_NO_RESOURCES - the readback operation was successful, but + * resulted in a different validate result than would have occurred + * without readback + * HWC2_ERROR_UNSUPPORTED - the readback operation was unsuccessful because + * of resource constraints, the presence of protected content, or other + * reasons; -1 must be returned in outFence + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_READBACK_BUFFER_FENCE)( + hwc2_device_t* device, hwc2_display_t display, + int32_t* outFence); + +/* setReadbackBuffer(..., buffer, releaseFence) + * Optional for HWC2 devices + * + * Sets the readback buffer to be filled with the contents of the next + * composition performed for this display (i.e., the contents present at the + * time of the next validateDisplay/presentDisplay cycle). + * + * This buffer will have been allocated as described in + * getReadbackBufferAttributes and will be interpreted as being in the dataspace + * provided by the same. + * + * If there is hardware protected content on the display at the time of the next + * composition, the area of the readback buffer covered by such content must be + * completely black. Any areas of the buffer not covered by such content may + * optionally be black as well. + * + * The release fence file descriptor provided works identically to the one + * described for setOutputBuffer. + * + * This function will not be called between any call to validateDisplay and a + * subsequent call to presentDisplay. + * + * Parameters: + * buffer - the new readback buffer + * releaseFence - a sync fence file descriptor as described in setOutputBuffer + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_PARAMETER - the new readback buffer handle was invalid + * + * See also: + * getReadbackBufferAttributes + * getReadbackBufferFence + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_READBACK_BUFFER)( + hwc2_device_t* device, hwc2_display_t display, + buffer_handle_t buffer, int32_t releaseFence); + +/* setVsyncEnabled(..., enabled) + * Descriptor: HWC2_FUNCTION_SET_VSYNC_ENABLED + * Must be provided by all HWC2 devices + * + * Enables or disables the vsync signal for the given display. Virtual displays + * never generate vsync callbacks, and any attempt to enable vsync for a virtual + * display though this function must return HWC2_ERROR_NONE and have no other + * effect. + * + * Parameters: + * enabled - whether to enable or disable vsync + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_PARAMETER - enabled was an invalid value + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_VSYNC_ENABLED)( + hwc2_device_t* device, hwc2_display_t display, + int32_t /*hwc2_vsync_t*/ enabled); + +/* validateDisplay(..., outNumTypes, outNumRequests) + * Descriptor: HWC2_FUNCTION_VALIDATE_DISPLAY + * Must be provided by all HWC2 devices + * + * Instructs the device to inspect all of the layer state and determine if + * there are any composition type changes necessary before presenting the + * display. Permitted changes are described in the definition of + * hwc2_composition_t above. + * + * Also returns the number of layer requests required + * by the given layer configuration. + * + * Parameters: + * outNumTypes - the number of composition type changes required by the + * device; if greater than 0, the client must either set and validate new + * types, or call acceptDisplayChanges to accept the changes returned by + * getChangedCompositionTypes; must be the same as the number of changes + * returned by getChangedCompositionTypes (see the declaration of that + * function for more information); pointer will be non-NULL + * outNumRequests - the number of layer requests required by this layer + * configuration; must be equal to the number of layer requests returned + * by getDisplayRequests (see the declaration of that function for + * more information); pointer will be non-NULL + * + * Returns HWC2_ERROR_NONE if no changes are necessary and it is safe to present + * the display using the current layer state. Otherwise returns one of the + * following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_HAS_CHANGES - outNumTypes was greater than 0 (see parameter list + * for more information) + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_VALIDATE_DISPLAY)( + hwc2_device_t* device, hwc2_display_t display, + uint32_t* outNumTypes, uint32_t* outNumRequests); + +/* + * Layer Functions + * + * These are functions which operate on layers, but which do not modify state + * that must be validated before use. See also 'Layer State Functions' below. + * + * All of these functions take as their first three parameters a device pointer, + * a display handle for the display which contains the layer, and a layer + * handle, so these parameters are omitted from the described parameter lists. + */ + +/* setCursorPosition(..., x, y) + * Descriptor: HWC2_FUNCTION_SET_CURSOR_POSITION + * Must be provided by all HWC2 devices + * + * Asynchonously sets the position of a cursor layer. + * + * Prior to validateDisplay, a layer may be marked as HWC2_COMPOSITION_CURSOR. + * If validation succeeds (i.e., the device does not request a composition + * change for that layer), then once a buffer has been set for the layer and it + * has been presented, its position may be set by this function at any time + * between presentDisplay and any subsequent validateDisplay calls for this + * display. + * + * Once validateDisplay is called, this function will not be called again until + * the validate/present sequence is completed. + * + * May be called from any thread so long as it is not interleaved with the + * validate/present sequence as described above. + * + * Parameters: + * x - the new x coordinate (in pixels from the left of the screen) + * y - the new y coordinate (in pixels from the top of the screen) + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_LAYER - the layer is invalid or is not currently marked as + * HWC2_COMPOSITION_CURSOR + * HWC2_ERROR_NOT_VALIDATED - the device is currently in the middle of the + * validate/present sequence + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_CURSOR_POSITION)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer, + int32_t x, int32_t y); + +/* setLayerBuffer(..., buffer, acquireFence) + * Descriptor: HWC2_FUNCTION_SET_LAYER_BUFFER + * Must be provided by all HWC2 devices + * + * Sets the buffer handle to be displayed for this layer. If the buffer + * properties set at allocation time (width, height, format, and usage) have not + * changed since the previous frame, it is not necessary to call validateDisplay + * before calling presentDisplay unless new state needs to be validated in the + * interim. + * + * Also provides a file descriptor referring to an acquire sync fence object, + * which will be signaled when it is safe to read from the given buffer. If it + * is already safe to read from the buffer, -1 may be passed instead. The + * device must ensure that it is safe for the client to close this file + * descriptor at any point after this function is called. + * + * This function must return HWC2_ERROR_NONE and have no other effect if called + * for a layer with a composition type of HWC2_COMPOSITION_SOLID_COLOR (because + * it has no buffer) or HWC2_COMPOSITION_SIDEBAND or HWC2_COMPOSITION_CLIENT + * (because synchronization and buffer updates for these layers are handled + * elsewhere). + * + * Parameters: + * buffer - the buffer handle to set + * acquireFence - a sync fence file descriptor as described above + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in + * HWC2_ERROR_BAD_PARAMETER - the buffer handle passed in was invalid + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_BUFFER)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer, + buffer_handle_t buffer, int32_t acquireFence); + +/* setLayerSurfaceDamage(..., damage) + * Descriptor: HWC2_FUNCTION_SET_LAYER_SURFACE_DAMAGE + * Must be provided by all HWC2 devices + * + * Provides the region of the source buffer which has been modified since the + * last frame. This region does not need to be validated before calling + * presentDisplay. + * + * Once set through this function, the damage region remains the same until a + * subsequent call to this function. + * + * If damage.numRects > 0, then it may be assumed that any portion of the source + * buffer not covered by one of the rects has not been modified this frame. If + * damage.numRects == 0, then the whole source buffer must be treated as if it + * has been modified. + * + * If the layer's contents are not modified relative to the prior frame, damage + * will contain exactly one empty rect([0, 0, 0, 0]). + * + * The damage rects are relative to the pre-transformed buffer, and their origin + * is the top-left corner. They will not exceed the dimensions of the latched + * buffer. + * + * Parameters: + * damage - the new surface damage region + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_SURFACE_DAMAGE)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer, + hwc_region_t damage); + +/* setLayerPerFrameMetadata(..., numMetadata, metadata) + * Descriptor: HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA + * Optional for HWC2 devices + * + * If supported (getFunction(HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA) is + * non-null), sets the metadata for the given display for all following + * frames. + * + * Upon returning from this function, the metadata change must have + * fully taken effect. + * + * This function will only be called if getPerFrameMetadataKeys is non-NULL + * and returns at least one key. + * + * Parameters: + * numElements is the number of elements in each of the keys and metadata arrays + * keys is a pointer to the array of keys. + * outMetadata is a pointer to the corresponding array of metadata. + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_PARAMETER - metadata is not valid + * HWC2_ERROR_UNSUPPORTED - metadata is not supported on this display + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_PER_FRAME_METADATA)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer, + uint32_t numElements, const int32_t* /*hw2_per_frame_metadata_key_t*/ keys, + const float* metadata); + +/* setLayerPerFrameMetadataBlobs(...,numElements, keys, sizes, blobs) + * Descriptor: HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA_BLOBS + * Optional for HWC2 devices + * + * If supported, (getFunction(HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA_BLOBS) + * is non-null), sets the metadata for the given display and layer. + * + * Upon returning from this function, the metadata change must have fully taken + * effect. + * + * This function must only be called if getPerFrameMetadataKeys is non-NULL + * and returns at least one key that corresponds to a blob type. + * + * Current valid blob type keys are: HDR10_PLUS_SEI + * + * Parameters: + * numElements is the number of elements in each of the keys, sizes, and + * metadata arrays + * keys is a pointer to an array of keys. Current valid keys are those listed + * above as valid blob type keys. + * sizes is a pointer to an array of unsigned ints specifying the sizes of + * each metadata blob + * metadata is a pointer to a blob of data holding all blobs contiguously in + * memory + * + * Returns HWC2_ERROR_NONE or one of the following erros: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_PARAMETER - sizes of keys and metadata parameters does + * not match numElements, numElements < 0, or keys contains a + * non-valid key (see above for current valid blob type keys). + * HWC2_ERROR_UNSUPPORTED - metadata is not supported on this display + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_PER_FRAME_METADATA_BLOBS)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer, + uint32_t numElements, const int32_t* keys, const uint32_t* sizes, + const uint8_t* metadata); +/* + * Layer State Functions + * + * These functions modify the state of a given layer. They do not take effect + * until the display configuration is successfully validated with + * validateDisplay and the display contents are presented with presentDisplay. + * + * All of these functions take as their first three parameters a device pointer, + * a display handle for the display which contains the layer, and a layer + * handle, so these parameters are omitted from the described parameter lists. + */ + +/* setLayerBlendMode(..., mode) + * Descriptor: HWC2_FUNCTION_SET_LAYER_BLEND_MODE + * Must be provided by all HWC2 devices + * + * Sets the blend mode of the given layer. + * + * Parameters: + * mode - the new blend mode + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in + * HWC2_ERROR_BAD_PARAMETER - an invalid blend mode was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_BLEND_MODE)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer, + int32_t /*hwc2_blend_mode_t*/ mode); + +/* setLayerColor(..., color) + * Descriptor: HWC2_FUNCTION_SET_LAYER_COLOR + * Must be provided by all HWC2 devices + * + * Sets the color of the given layer. If the composition type of the layer is + * not HWC2_COMPOSITION_SOLID_COLOR, this call must return HWC2_ERROR_NONE and + * have no other effect. + * + * Parameters: + * color - the new color + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_COLOR)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer, + hwc_color_t color); + +/* setLayerFloatColor(..., color) + * Descriptor: HWC2_FUNCTION_SET_LAYER_FLOAT_COLOR + * Provided by HWC2 devices which don't return nullptr function pointer. + * + * Sets the color of the given layer. If the composition type of the layer is + * not HWC2_COMPOSITION_SOLID_COLOR, this call must return HWC2_ERROR_NONE and + * have no other effect. + * + * Parameters: + * color - the new color in float type, rage is [0.0, 1.0], the colorspace is + * defined by the dataspace that gets set by calling setLayerDataspace. + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_FLOAT_COLOR)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer, + hwc_float_color_t color); + +/* setLayerCompositionType(..., type) + * Descriptor: HWC2_FUNCTION_SET_LAYER_COMPOSITION_TYPE + * Must be provided by all HWC2 devices + * + * Sets the desired composition type of the given layer. During validateDisplay, + * the device may request changes to the composition types of any of the layers + * as described in the definition of hwc2_composition_t above. + * + * Parameters: + * type - the new composition type + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in + * HWC2_ERROR_BAD_PARAMETER - an invalid composition type was passed in + * HWC2_ERROR_UNSUPPORTED - a valid composition type was passed in, but it is + * not supported by this device + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_COMPOSITION_TYPE)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer, + int32_t /*hwc2_composition_t*/ type); + +/* setLayerDataspace(..., dataspace) + * Descriptor: HWC2_FUNCTION_SET_LAYER_DATASPACE + * Must be provided by all HWC2 devices + * + * Sets the dataspace that the current buffer on this layer is in. + * + * The dataspace provides more information about how to interpret the buffer + * contents, such as the encoding standard and color transform. + * + * See the values of android_dataspace_t in <system/graphics.h> for more + * information. + * + * Parameters: + * dataspace - the new dataspace + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_DATASPACE)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer, + int32_t /*android_dataspace_t*/ dataspace); + +/* setLayerDisplayFrame(..., frame) + * Descriptor: HWC2_FUNCTION_SET_LAYER_DISPLAY_FRAME + * Must be provided by all HWC2 devices + * + * Sets the display frame (the portion of the display covered by a layer) of the + * given layer. This frame will not exceed the display dimensions. + * + * Parameters: + * frame - the new display frame + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_DISPLAY_FRAME)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer, + hwc_rect_t frame); + +/* setLayerPlaneAlpha(..., alpha) + * Descriptor: HWC2_FUNCTION_SET_LAYER_PLANE_ALPHA + * Must be provided by all HWC2 devices + * + * Sets an alpha value (a floating point value in the range [0.0, 1.0]) which + * will be applied to the whole layer. It can be conceptualized as a + * preprocessing step which applies the following function: + * if (blendMode == HWC2_BLEND_MODE_PREMULTIPLIED) + * out.rgb = in.rgb * planeAlpha + * out.a = in.a * planeAlpha + * + * If the device does not support this operation on a layer which is marked + * HWC2_COMPOSITION_DEVICE, it must request a composition type change to + * HWC2_COMPOSITION_CLIENT upon the next validateDisplay call. + * + * Parameters: + * alpha - the plane alpha value to apply + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_PLANE_ALPHA)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer, + float alpha); + +/* setLayerSidebandStream(..., stream) + * Descriptor: HWC2_FUNCTION_SET_LAYER_SIDEBAND_STREAM + * Provided by HWC2 devices which support HWC2_CAPABILITY_SIDEBAND_STREAM + * + * Sets the sideband stream for this layer. If the composition type of the given + * layer is not HWC2_COMPOSITION_SIDEBAND, this call must return HWC2_ERROR_NONE + * and have no other effect. + * + * Parameters: + * stream - the new sideband stream + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in + * HWC2_ERROR_BAD_PARAMETER - an invalid sideband stream was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_SIDEBAND_STREAM)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer, + const native_handle_t* stream); + +/* setLayerSourceCrop(..., crop) + * Descriptor: HWC2_FUNCTION_SET_LAYER_SOURCE_CROP + * Must be provided by all HWC2 devices + * + * Sets the source crop (the portion of the source buffer which will fill the + * display frame) of the given layer. This crop rectangle will not exceed the + * dimensions of the latched buffer. + * + * If the device is not capable of supporting a true float source crop (i.e., it + * will truncate or round the floats to integers), it should set this layer to + * HWC2_COMPOSITION_CLIENT when crop is non-integral for the most accurate + * rendering. + * + * If the device cannot support float source crops, but still wants to handle + * the layer, it should use the following code (or similar) to convert to + * an integer crop: + * intCrop.left = (int) ceilf(crop.left); + * intCrop.top = (int) ceilf(crop.top); + * intCrop.right = (int) floorf(crop.right); + * intCrop.bottom = (int) floorf(crop.bottom); + * + * Parameters: + * crop - the new source crop + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_SOURCE_CROP)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer, + hwc_frect_t crop); + +/* setLayerTransform(..., transform) + * Descriptor: HWC2_FUNCTION_SET_LAYER_TRANSFORM + * Must be provided by all HWC2 devices + * + * Sets the transform (rotation/flip) of the given layer. + * + * Parameters: + * transform - the new transform + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in + * HWC2_ERROR_BAD_PARAMETER - an invalid transform was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_TRANSFORM)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer, + int32_t /*hwc_transform_t*/ transform); + +/* setLayerVisibleRegion(..., visible) + * Descriptor: HWC2_FUNCTION_SET_LAYER_VISIBLE_REGION + * Must be provided by all HWC2 devices + * + * Specifies the portion of the layer that is visible, including portions under + * translucent areas of other layers. The region is in screen space, and will + * not exceed the dimensions of the screen. + * + * Parameters: + * visible - the new visible region, in screen space + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_VISIBLE_REGION)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer, + hwc_region_t visible); + +/* setLayerZOrder(..., z) + * Descriptor: HWC2_FUNCTION_SET_LAYER_Z_ORDER + * Must be provided by all HWC2 devices + * + * Sets the desired Z order (height) of the given layer. A layer with a greater + * Z value occludes a layer with a lesser Z value. + * + * Parameters: + * z - the new Z order + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_Z_ORDER)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer, + uint32_t z); + +/* setLayerColorTransform(..., matrix) + * Descriptor: HWC2_FUNCTION_SET_LAYER_COLOR_TRANSFORM + * Optional by all HWC2 devices + * + * Sets a matrix for color transform which will be applied on this layer + * before composition. + * + * If the device is not capable of apply the matrix on this layer, it must force + * this layer to client composition during VALIDATE_DISPLAY. + * + * The matrix provided is an affine color transformation of the following form: + * + * |r.r r.g r.b 0| + * |g.r g.g g.b 0| + * |b.r b.g b.b 0| + * |Tr Tg Tb 1| + * + * This matrix must be provided in row-major form: + * + * {r.r, r.g, r.b, 0, g.r, ...}. + * + * Given a matrix of this form and an input color [R_in, G_in, B_in], + * the input color must first be converted to linear space + * [R_linear, G_linear, B_linear], then the output linear color + * [R_out_linear, G_out_linear, B_out_linear] will be: + * + * R_out_linear = R_linear * r.r + G_linear * g.r + B_linear * b.r + Tr + * G_out_linear = R_linear * r.g + G_linear * g.g + B_linear * b.g + Tg + * B_out_linear = R_linear * r.b + G_linear * g.b + B_linear * b.b + Tb + * + * [R_out_linear, G_out_linear, B_out_linear] must then be converted to + * gamma space: [R_out, G_out, B_out] before blending. + * + * Parameters: + * matrix - a 4x4 transform matrix (16 floats) as described above + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_COLOR_TRANSFORM)( + hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer, + const float* matrix); + +/* getDisplayedContentSamplingAttributes(..., + * format, dataspace, supported_components, max_frames) + * Descriptor: HWC2_FUNCTION_GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES + * Optional by all HWC2 devices + * + * Query for what types of color sampling the hardware supports. + * + * Parameters: + * format - The format of the sampled pixels; pointer will be non-NULL + * dataspace - The dataspace of the sampled pixels; pointer will be non-NULL + * supported_components - The mask of which components can be sampled; pointer + * will be non-NULL + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY when an invalid display was passed in, or + * HWC2_ERROR_UNSUPPORTED when there is no efficient way to sample. + */ +typedef int32_t (*HWC2_PFN_GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES)( + hwc2_device_t* device, hwc2_display_t display, + int32_t* /* android_pixel_format_t */ format, + int32_t* /* android_dataspace_t */ dataspace, + uint8_t* /* mask of android_component_t */ supported_components); + +/* setDisplayedContentSamplingEnabled(..., enabled) + * Descriptor: HWC2_FUNCTION_SET_DISPLAYED_CONTENT_SAMPLING_ENABLED + * Optional by all HWC2 devices + * + * Enables or disables the collection of color content statistics + * on this display. + * + * Sampling occurs on the contents of the final composition on this display + * (i.e., the contents presented on screen). + * + * Sampling support is optional, and is set to DISABLE by default. + * On each call to ENABLE, all collected statistics will be reset. + * + * Sample data can be queried via getDisplayedContentSample(). + * + * Parameters: + * enabled - indicates whether to enable or disable sampling. + * component_mask - The mask of which components should be sampled. + * If zero, all supported components are to be enabled. + * max_frames - is the maximum number of frames that should be stored before + * discard. The sample represents the most-recently posted frames. + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY when an invalid display handle was passed in, + * HWC2_ERROR_BAD_PARAMETER when enabled was an invalid value, or + * HWC2_ERROR_NO_RESOURCES when the requested ringbuffer size via max_frames + * was not available. + * HWC2_ERROR_UNSUPPORTED when there is no efficient way to sample. + */ +typedef int32_t (*HWC2_PFN_SET_DISPLAYED_CONTENT_SAMPLING_ENABLED)( + hwc2_device_t* device, hwc2_display_t display, + int32_t /*hwc2_displayed_content_sampling_t*/ enabled, + uint8_t /* mask of android_component_t */ component_mask, + uint64_t max_frames); + +/* getDisplayedContentSample(..., component, max_frames, timestamp, + * samples_size, samples, frame_count) + * Descriptor: HWC2_FUNCTION_GET_DISPLAYED_CONTENT_SAMPLE + * Optional by all HWC2 devices + * + * Collects the results of display content color sampling for display. + * + * Collection of data can occur whether the sampling is in ENABLE or + * DISABLE state. + * + * Parameters: + * max_frames - is the maximum number of frames that should be represented in + * the sample. The sample represents the most-recently posted frames. + * If max_frames is 0, all frames are to be represented by the sample. + * timestamp - is the timestamp after which any frames were posted that should + * be included in the sample. Timestamp is CLOCK_MONOTONIC. + * If timestamp is 0, do not filter from the sample by time. + * frame_count - The number of frames represented by this sample; pointer will + * be non-NULL. + * samples_size - The sizes of the color histogram representing the color + * sampling. Sample_sizes are indexed in the same order as + * HWC2_FORMAT_COMPONENT_. + * samples - The arrays of data corresponding to the sampling data. Samples are + * indexed in the same order as HWC2_FORMAT_COMPONENT_. + * The size of each sample is the samples_size for the same index. + * Each components sample is an array that is to be filled with the + * evenly-weighted buckets of a histogram counting how many times a pixel + * of the given component was displayed onscreen. Caller owns the data and + * pointer may be NULL to query samples_size. + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY when an invalid display was passed in, or + * HWC2_ERROR_UNSUPPORTED when there is no efficient way to sample, or + * HWC2_ERROR_BAD_PARAMETER when the component is not supported by the hardware. + */ +typedef int32_t (*HWC2_PFN_GET_DISPLAYED_CONTENT_SAMPLE)( + hwc2_device_t* device, hwc2_display_t display, + uint64_t max_frames, uint64_t timestamp, + uint64_t* frame_count, int32_t samples_size[4], uint64_t* samples[4]); + +/* getDisplayCapabilities(..., outCapabilities) + * Descriptor: HWC2_FUNCTION_GET_DISPLAY_CAPABILITIES + * Required for HWC2 devices for composer 2.3 + * Optional for HWC2 devices for composer 2.1 and 2.2 + * + * getDisplayCapabilities returns a list of supported capabilities + * (as described in the definition of Capability above). + * This list must not change after initialization. + * + * Parameters: + * outNumCapabilities - if outCapabilities was nullptr, returns the number of capabilities + * if outCapabilities was not nullptr, returns the number of capabilities stored in + * outCapabilities, which must not exceed the value stored in outNumCapabilities prior + * to the call; pointer will be non-NULL + * outCapabilities - a list of supported capabilities. + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_CAPABILITIES)( + hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumCapabilities, + uint32_t* outCapabilities); + +/* Use getDisplayCapabilities instead. If brightness is supported, must return + * DisplayCapability::BRIGHTNESS as one of the display capabilities via getDisplayCapabilities. + * Only use getDisplayCapabilities as the source of truth to query brightness support. + * + * getDisplayBrightnessSupport(displayToken) + * Descriptor: HWC2_FUNCTION_GET_DISPLAY_BRIGHTNESS_SUPPORT + * Required for HWC2 devices for composer 2.3 + * Optional for HWC2 devices for composer 2.1 and 2.2 + * + * getDisplayBrightnessSupport returns whether brightness operations are supported on a display. + * + * Parameters: + * outSupport - whether the display supports operations. + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY when the display is invalid. + */ +typedef int32_t /*hwc_error_t*/ (*HWC2_PFN_GET_DISPLAY_BRIGHTNESS_SUPPORT)(hwc2_device_t* device, + hwc2_display_t display, bool* outSupport); + +/* setDisplayBrightness(displayToken, brightnesss) + * Descriptor: HWC2_FUNCTION_SET_DISPLAY_BRIGHTNESS + * Required for HWC2 devices for composer 2.3 + * Optional for HWC2 devices for composer 2.1 and 2.2 + * + * setDisplayBrightness sets the brightness of a display. + * + * Parameters: + * brightness - a number between 0.0f (minimum brightness) and 1.0f (maximum brightness), or + * -1.0f to turn the backlight off. + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY when the display is invalid, or + * HWC2_ERROR_UNSUPPORTED when brightness operations are not supported, or + * HWC2_ERROR_BAD_PARAMETER when the brightness is invalid, or + * HWC2_ERROR_NO_RESOURCES when the brightness cannot be applied. + */ +typedef int32_t /*hwc_error_t*/ (*HWC2_PFN_SET_DISPLAY_BRIGHTNESS)(hwc2_device_t* device, + hwc2_display_t display, float brightness); + +/* Composer 2.4 additions */ + +/* getDisplayConnectionType(..., outType) + * Descriptor: HWC2_FUNCTION_GET_DISPLAY_CONNECTION_TYPE + * Optional for all HWC2 devices + * + * Returns whether the given physical display is internal or external. + * + * Parameters: + * outType - the connection type of the display; pointer will be non-NULL + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY when the display is invalid or virtual. + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_CONNECTION_TYPE)( + hwc2_device_t* device, hwc2_display_t display, + uint32_t* /*hwc2_display_connection_type_t*/ outType); + +/* getDisplayVsyncPeriod(..., outVsyncPeriods) + * Descriptor: HWC2_FUNCTION_GET_DISPLAY_VSYNC_PERIOD + * Required for HWC2 devices for composer 2.4 + * + * Retrieves which vsync period the display is currently using. + * + * If no display configuration is currently active, this function must + * return BAD_CONFIG. If a vsync period is about to change due to a + * setActiveConfigWithConstraints call, this function must return the current vsync period + * until the change has taken place. + * + * Parameters: + * outVsyncPeriod - the current vsync period of the display. + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_CONFIG - no configuration is currently active + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_VSYNC_PERIOD)( + hwc2_device_t* device, hwc2_display_t display, hwc2_vsync_period_t* outVsyncPeriod); + +/* setActiveConfigWithConstraints(..., + * config, + * vsyncPeriodChangeConstraints, + * outTimeline) + * Descriptor: HWC2_FUNCTION_SET_ACTIVE_CONFIG_WITH_CONSTRAINTS + * Required for HWC2 devices for composer 2.4 + * + * Sets the active configuration and the refresh rate for this display. + * If the new config shares the same config group as the current config, + * only the vsync period shall change. + * Upon returning, the given display configuration, except vsync period, must be active and + * remain so until either this function is called again or the display is disconnected. + * When the display starts to refresh at the new vsync period, onVsync_2_4 callback must be + * called with the new vsync period. + * + * Parameters: + * config - the new display configuration. + * vsyncPeriodChangeConstraints - constraints required for changing vsync period: + * desiredTimeNanos - the time in CLOCK_MONOTONIC after + * which the vsync period may change + * (i.e., the vsync period must not change + * before this time). + * seamlessRequired - if true, requires that the vsync period + * change must happen seamlessly without + * a noticeable visual artifact. + * When the conditions change and it may be + * possible to change the vsync period + * seamlessly, HWC2_CALLBACK_SEAMLESS_POSSIBLE + * callback must be called to indicate that + * caller should retry. + * outTimeline - the timeline for the vsync period change. + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in. + * HWC2_ERROR_BAD_CONFIG - an invalid configuration handle passed in. + * HWC2_ERROR_SEAMLESS_NOT_ALLOWED - when seamlessRequired was true but config provided doesn't + * share the same config group as the current config. + * HWC2_ERROR_SEAMLESS_NOT_POSSIBLE - when seamlessRequired was true but the display cannot + * achieve the vsync period change without a noticeable + * visual artifact. + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_ACTIVE_CONFIG_WITH_CONSTRAINTS)( + hwc2_device_t* device, hwc2_display_t display, hwc2_config_t config, + hwc_vsync_period_change_constraints_t* vsyncPeriodChangeConstraints, + hwc_vsync_period_change_timeline_t* outTimeline); + +/* setAutoLowLatencyMode(displayToken, on) + * Descriptor: HWC2_FUNCTION_SET_AUTO_LOW_LATENCY_MODE + * Optional for HWC2 devices + * + * setAutoLowLatencyMode requests that the display goes into low latency mode. If the display + * is connected via HDMI 2.1, then Auto Low Latency Mode should be triggered. If the display is + * internally connected, then a custom low latency mode should be triggered (if available). + * + * Parameters: + * on - indicates whether to turn low latency mode on (=true) or off (=false) + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - when the display is invalid, or + * HWC2_ERROR_UNSUPPORTED - when the display does not support any low latency mode + */ +typedef int32_t /*hwc_error_t*/ (*HWC2_PFN_SET_AUTO_LOW_LATENCY_MODE)(hwc2_device_t* device, + hwc2_display_t display, bool on); + +/* getSupportedContentTypes(..., outSupportedContentTypes) + * Descriptor: HWC2_FUNCTION_GET_SUPPORTED_CONTENT_TYPES + * Optional for HWC2 devices + * + * getSupportedContentTypes returns a list of supported content types + * (as described in the definition of ContentType above). + * This list must not change after initialization. + * + * Parameters: + * outNumSupportedContentTypes - if outSupportedContentTypes was nullptr, returns the number + * of supported content types; if outSupportedContentTypes was not nullptr, returns the + * number of capabilities stored in outSupportedContentTypes, which must not exceed the + * value stored in outNumSupportedContentTypes prior to the call; pointer will be non-NULL + * outSupportedContentTypes - a list of supported content types. + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + */ +typedef int32_t /*hwc_error_t*/ (*HWC2_PFN_GET_SUPPORTED_CONTENT_TYPES)(hwc2_device_t* device, + hwc2_display_t display, uint32_t* outNumSupportedContentTypes, uint32_t* outSupportedContentTypes); + +/* setContentType(displayToken, contentType) + * Descriptor: HWC2_FUNCTION_SET_CONTENT_TYPE + * Optional for HWC2 devices + * + * setContentType instructs the display that the content being shown is of the given contentType + * (one of GRAPHICS, PHOTO, CINEMA, GAME). + * + * According to the HDMI 1.4 specification, supporting all content types is optional. Whether + * the display supports a given content type is reported by getSupportedContentTypes. + * + * Parameters: + * contentType - the type of content that is currently being shown on the display + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - when the display is invalid, or + * HWC2_ERROR_UNSUPPORTED - when the given content type is a valid content type, but is not + * supported on this display, or + * HWC2_ERROR_BAD_PARAMETER - when the given content type is invalid + */ +typedef int32_t /*hwc_error_t*/ (*HWC2_PFN_SET_CONTENT_TYPE)(hwc2_device_t* device, + hwc2_display_t display, int32_t /* hwc2_content_type_t */ contentType); + +/* getClientTargetProperty(..., outClientTargetProperty) + * Descriptor: HWC2_FUNCTION_GET_CLIENT_TARGET_PROPERTY + * Optional for HWC2 devices + * + * Retrieves the client target properties for which the hardware composer + * requests after the last call to validateDisplay. The client must set the + * properties of the client target to match the returned values. + * When this API is implemented, if client composition is needed, the hardware + * composer must return meaningful client target property with dataspace not + * setting to UNKNOWN. + * When the returned dataspace is set to UNKNOWN, it means hardware composer + * requests nothing, the client must ignore the returned client target property + * structrue. + * + * Parameters: + * outClientTargetProperty - the client target properties that hardware + * composer requests. If dataspace field is set to UNKNOWN, it means + * the hardware composer requests nothing, the client must ignore the + * returned client target property structure. + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_NOT_VALIDATED - validateDisplay has not been called for this + * display + */ +typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_CLIENT_TARGET_PROPERTY)( + hwc2_device_t* device, hwc2_display_t display, + hwc_client_target_property_t* outClientTargetProperty); + +/* setLayerGenericMetadata(..., keyLength, key, mandatory, valueLength, value) + * Descriptor: HWC2_FUNCTION_SET_LAYER_GENERIC_METADATA + * Optional for HWC2 devices for composer 2.4+ + * + * setLayerGenericMetadata sets a piece of generic metadata for the given layer. + * If this function is called twice with the same key but different values, the + * newer value must override the older one. Calling this function with + * valueLength == 0 must reset that key's metadata as if it had not been set. + * + * A given piece of metadata may either be mandatory or a hint (non-mandatory) + * as indicated by the `mandatory` parameter. Mandatory metadata may affect the + * composition result, which is to say that it may cause a visible change in the + * final image. By contrast, hints may only affect the composition strategy, + * such as which layers are composited by the client, but must not cause a + * visible change in the final image. + * + * This implies that if the device does not understand a given key: + * - If the key is marked as mandatory, it must mark this layer for client + * composition in order to ensure the correct composition result + * - If the key is a hint, the metadata provided may be ignored + * + * Parameters: + * keyLength - the length of the key parameter + * key - the metadata key + * mandatory - indicates whether this particular key represents mandatory + * metadata or a hint, as described above + * valueLength - the length of the value parameter + * value - the metadata value + * + * Returns HWC2_ERROR_NONE or one of the following errors: + * HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in + * HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in + * HWC2_ERROR_BAD_PARAMETER - an unsupported key was passed in, or the value + * does not conform to the expected format for the key + */ +typedef int32_t /*hwc_error_t*/ (*HWC2_PFN_SET_LAYER_GENERIC_METADATA)(hwc2_device_t* device, + hwc2_display_t display, hwc2_layer_t layer, uint32_t keyLength, const char* key, + bool mandatory, uint32_t valueLength, const uint8_t* value); + +/* getLayerGenericMetadataKey(..., keyIndex, outKeyLength, outKey, outMandatory) + * Descriptor: HWC2_FUNCTION_GET_LAYER_GENERIC_METADATA_KEY + * Optional for HWC2 devices for composer 2.4+ + * + * getLayerGenericMetadataKey allows the client to query which metadata keys are + * supported by the composer implementation. Only keys in this list will be + * passed into setLayerGenericMetadata. Additionally, the key names in this list + * must meet the following requirements: + * - Must be specified in reverse domain name notation + * - Must not start with 'com.android' or 'android' + * - Must be unique within the returned list of keys + * - Must correspond to a matching HIDL struct type, which defines the structure + * of its values. For example, the key 'com.example.V1-3.Foo' should + * correspond to a value of type com.example@1.3::Foo, which is defined in a + * vendor HAL extension + * + * Client code which calls this function will look similar to this: + * + * struct Key { + * std::string name; + * bool mandatory; + * } + * + * std::vector<Key> keys; + * uint32_t index = 0; + * uint32_t keyLength = 0; + * while (true) { + * getLayerGenericMetadataKey(device, index, &keyLength, nullptr, nullptr); + * if (keyLength == 0) break; + * + * Key key; + * key.name.resize(keyLength); + * getLayerGenericMetadataKey(device, index, &keyLength, key.name.data(), &key.mandatory); + * keys.push_back(key); + * + * ++index; + * } + * + * Parameters: + * keyIndex - the index of the key to retrieve. For values beyond the end of + * the list of supported keys, outKeyLength should return 0, and the + * client may assume that if the length is 0 for keyIndex N, then it is + * also 0 for all keyIndex values > N. + * outKeyLength - if outKey was nullptr, returns the length of the key to + * allow the client to allocate an appropriately-sized buffer; if outKey + * was not nullptr, returns the length of the returned key, which must not + * exceed the value stored in outKeyLength prior to the call; pointer will + * be non-null + * outKey - the key at the given index, or nullptr to query the key's length + * outMandatory - whether the given metadata is mandatory or not (see + * setLayerGenericMetadata for more information), may be nullptr + */ +typedef void (*HWC2_PFN_GET_LAYER_GENERIC_METADATA_KEY)(hwc2_device_t* device, uint32_t keyIndex, + uint32_t* outKeyLength, char* outKey, bool* outMandatory); + +__END_DECLS + +#endif diff --git a/.ci/android_headers/hardware/hwcomposer_defs.h b/.ci/android_headers/hardware/hwcomposer_defs.h new file mode 100644 index 0000000..f466a36 --- /dev/null +++ b/.ci/android_headers/hardware/hwcomposer_defs.h @@ -0,0 +1,345 @@ +// clang-format off +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_INCLUDE_HARDWARE_HWCOMPOSER_DEFS_H +#define ANDROID_INCLUDE_HARDWARE_HWCOMPOSER_DEFS_H + +#include <stdint.h> +#include <sys/cdefs.h> + +#include <hardware/gralloc.h> +#include <hardware/hardware.h> +#include <cutils/native_handle.h> + +__BEGIN_DECLS + +/* Shared by HWC1 and HWC2 */ + +#define HWC_HEADER_VERSION 1 + +#define HWC_MODULE_API_VERSION_0_1 HARDWARE_MODULE_API_VERSION(0, 1) + +#define HWC_DEVICE_API_VERSION_1_0 HARDWARE_DEVICE_API_VERSION_2(1, 0, HWC_HEADER_VERSION) +#define HWC_DEVICE_API_VERSION_1_1 HARDWARE_DEVICE_API_VERSION_2(1, 1, HWC_HEADER_VERSION) +#define HWC_DEVICE_API_VERSION_1_2 HARDWARE_DEVICE_API_VERSION_2(1, 2, HWC_HEADER_VERSION) +#define HWC_DEVICE_API_VERSION_1_3 HARDWARE_DEVICE_API_VERSION_2(1, 3, HWC_HEADER_VERSION) +#define HWC_DEVICE_API_VERSION_1_4 HARDWARE_DEVICE_API_VERSION_2(1, 4, HWC_HEADER_VERSION) +#define HWC_DEVICE_API_VERSION_1_5 HARDWARE_DEVICE_API_VERSION_2(1, 5, HWC_HEADER_VERSION) + +#define HWC_DEVICE_API_VERSION_2_0 HARDWARE_DEVICE_API_VERSION_2(2, 0, HWC_HEADER_VERSION) + +/** + * The id of this module + */ +#define HWC_HARDWARE_MODULE_ID "hwcomposer" + +/** + * Name of the sensors device to open + */ +#define HWC_HARDWARE_COMPOSER "composer" + +typedef struct hwc_color { + uint8_t r; + uint8_t g; + uint8_t b; + uint8_t a; +} hwc_color_t; + +typedef struct hwc_float_color { + float r; + float g; + float b; + float a; +} hwc_float_color_t; + +typedef struct hwc_frect { + float left; + float top; + float right; + float bottom; +} hwc_frect_t; + +typedef struct hwc_rect { + int left; + int top; + int right; + int bottom; +} hwc_rect_t; + +typedef struct hwc_region { + size_t numRects; + hwc_rect_t const* rects; +} hwc_region_t; + +/* + * hwc_layer_t::transform values + */ +typedef enum { + /* flip source image horizontally */ + HWC_TRANSFORM_FLIP_H = HAL_TRANSFORM_FLIP_H, + /* flip source image vertically */ + HWC_TRANSFORM_FLIP_V = HAL_TRANSFORM_FLIP_V, + /* rotate source image 90 degrees clock-wise */ + HWC_TRANSFORM_ROT_90 = HAL_TRANSFORM_ROT_90, + /* rotate source image 180 degrees */ + HWC_TRANSFORM_ROT_180 = HAL_TRANSFORM_ROT_180, + /* rotate source image 270 degrees clock-wise */ + HWC_TRANSFORM_ROT_270 = HAL_TRANSFORM_ROT_270, + /* flip source image horizontally, the rotate 90 degrees clock-wise */ + HWC_TRANSFORM_FLIP_H_ROT_90 = HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90, + /* flip source image vertically, the rotate 90 degrees clock-wise */ + HWC_TRANSFORM_FLIP_V_ROT_90 = HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90, +} hwc_transform_t; + +/* Constraints for changing vsync period */ +typedef struct hwc_vsync_period_change_constraints { + /* Time in CLOCK_MONOTONIC after which the vsync period may change + * (i.e., the vsync period must not change before this time). */ + int64_t desiredTimeNanos; + /* + * If true, requires that the vsync period change must happen seamlessly without + * a noticeable visual artifact. */ + uint8_t seamlessRequired; +} hwc_vsync_period_change_constraints_t; + +/* Timing for a vsync period change. */ +typedef struct hwc_vsync_period_change_timeline { + /* The time in CLOCK_MONOTONIC when the new display will start to refresh at + * the new vsync period. */ + int64_t newVsyncAppliedTimeNanos; + + /* Set to true if the client is required to sent a frame to be displayed before + * the change can take place. */ + uint8_t refreshRequired; + + /* The time in CLOCK_MONOTONIC when the client is expected to send the new frame. + * Should be ignored if refreshRequired is false. */ + int64_t refreshTimeNanos; +} hwc_vsync_period_change_timeline_t; + +typedef struct hwc_client_target_property { + // The pixel format of client target requested by hardware composer. + int32_t pixelFormat; + // The dataspace of the client target requested by hardware composer. + int32_t dataspace; +} hwc_client_target_property_t; + +/******************************************************************************* + * Beyond this point are things only used by HWC1, which should be ignored when + * implementing a HWC2 device + ******************************************************************************/ + +enum { + /* hwc_composer_device_t::set failed in EGL */ + HWC_EGL_ERROR = -1 +}; + +/* + * hwc_layer_t::hints values + * Hints are set by the HAL and read by SurfaceFlinger + */ +enum { + /* + * HWC can set the HWC_HINT_TRIPLE_BUFFER hint to indicate to SurfaceFlinger + * that it should triple buffer this layer. Typically HWC does this when + * the layer will be unavailable for use for an extended period of time, + * e.g. if the display will be fetching data directly from the layer and + * the layer can not be modified until after the next set(). + */ + HWC_HINT_TRIPLE_BUFFER = 0x00000001, + + /* + * HWC sets HWC_HINT_CLEAR_FB to tell SurfaceFlinger that it should clear the + * framebuffer with transparent pixels where this layer would be. + * SurfaceFlinger will only honor this flag when the layer has no blending + * + */ + HWC_HINT_CLEAR_FB = 0x00000002 +}; + +/* + * hwc_layer_t::flags values + * Flags are set by SurfaceFlinger and read by the HAL + */ +enum { + /* + * HWC_SKIP_LAYER is set by SurfaceFlinger to indicate that the HAL + * shall not consider this layer for composition as it will be handled + * by SurfaceFlinger (just as if compositionType was set to HWC_FRAMEBUFFER). + */ + HWC_SKIP_LAYER = 0x00000001, + + /* + * HWC_IS_CURSOR_LAYER is set by surfaceflinger to indicate that this + * layer is being used as a cursor on this particular display, and that + * surfaceflinger can potentially perform asynchronous position updates for + * this layer. If a call to prepare() returns HWC_CURSOR_OVERLAY for the + * composition type of this layer, then the hwcomposer will allow async + * position updates to this layer via setCursorPositionAsync(). + */ + HWC_IS_CURSOR_LAYER = 0x00000002 +}; + +/* + * hwc_layer_t::compositionType values + */ +enum { + /* this layer is to be drawn into the framebuffer by SurfaceFlinger */ + HWC_FRAMEBUFFER = 0, + + /* this layer will be handled in the HWC */ + HWC_OVERLAY = 1, + + /* this is the background layer. it's used to set the background color. + * there is only a single background layer */ + HWC_BACKGROUND = 2, + + /* this layer holds the result of compositing the HWC_FRAMEBUFFER layers. + * Added in HWC_DEVICE_API_VERSION_1_1. */ + HWC_FRAMEBUFFER_TARGET = 3, + + /* this layer's contents are taken from a sideband buffer stream. + * Added in HWC_DEVICE_API_VERSION_1_4. */ + HWC_SIDEBAND = 4, + + /* this layer's composition will be handled by hwcomposer by dedicated + cursor overlay hardware. hwcomposer will also all async position updates + of this layer outside of the normal prepare()/set() loop. Added in + HWC_DEVICE_API_VERSION_1_4. */ + HWC_CURSOR_OVERLAY = 5 + }; +/* + * hwc_layer_t::blending values + */ +enum { + /* no blending */ + HWC_BLENDING_NONE = 0x0100, + + /* ONE / ONE_MINUS_SRC_ALPHA */ + HWC_BLENDING_PREMULT = 0x0105, + + /* SRC_ALPHA / ONE_MINUS_SRC_ALPHA */ + HWC_BLENDING_COVERAGE = 0x0405 +}; + +/* attributes queriable with query() */ +enum { + /* + * Must return 1 if the background layer is supported, 0 otherwise. + */ + HWC_BACKGROUND_LAYER_SUPPORTED = 0, + + /* + * Returns the vsync period in nanoseconds. + * + * This query is not used for HWC_DEVICE_API_VERSION_1_1 and later. + * Instead, the per-display attribute HWC_DISPLAY_VSYNC_PERIOD is used. + */ + HWC_VSYNC_PERIOD = 1, + + /* + * Availability: HWC_DEVICE_API_VERSION_1_1 + * Returns a mask of supported display types. + */ + HWC_DISPLAY_TYPES_SUPPORTED = 2, +}; + +/* display attributes returned by getDisplayAttributes() */ +enum { + /* Indicates the end of an attribute list */ + HWC_DISPLAY_NO_ATTRIBUTE = 0, + + /* The vsync period in nanoseconds */ + HWC_DISPLAY_VSYNC_PERIOD = 1, + + /* The number of pixels in the horizontal and vertical directions. */ + HWC_DISPLAY_WIDTH = 2, + HWC_DISPLAY_HEIGHT = 3, + + /* The number of pixels per thousand inches of this configuration. + * + * Scaling DPI by 1000 allows it to be stored in an int without losing + * too much precision. + * + * If the DPI for a configuration is unavailable or the HWC implementation + * considers it unreliable, it should set these attributes to zero. + */ + HWC_DISPLAY_DPI_X = 4, + HWC_DISPLAY_DPI_Y = 5, + + /* Indicates which of the vendor-defined color transforms is provided by + * this configuration. */ + HWC_DISPLAY_COLOR_TRANSFORM = 6, + + /* The configuration group this config is associated to. The groups are defined + * to mark certain configs as similar and changing configs within a certain group + * may be done seamlessly in some conditions. setActiveConfigWithConstraints. */ + HWC_DISPLAY_CONFIG_GROUP = 7, +}; + +/* Allowed events for hwc_methods::eventControl() */ +enum { + HWC_EVENT_VSYNC = 0 +}; + +/* Display types and associated mask bits. */ +enum { + HWC_DISPLAY_PRIMARY = 0, + HWC_DISPLAY_EXTERNAL = 1, // HDMI, DP, etc. + HWC_DISPLAY_VIRTUAL = 2, + + HWC_NUM_PHYSICAL_DISPLAY_TYPES = 2, + HWC_NUM_DISPLAY_TYPES = 3, +}; + +enum { + HWC_DISPLAY_PRIMARY_BIT = 1 << HWC_DISPLAY_PRIMARY, + HWC_DISPLAY_EXTERNAL_BIT = 1 << HWC_DISPLAY_EXTERNAL, + HWC_DISPLAY_VIRTUAL_BIT = 1 << HWC_DISPLAY_VIRTUAL, +}; + +/* Display power modes */ +enum { + /* The display is turned off (blanked). */ + HWC_POWER_MODE_OFF = 0, + /* The display is turned on and configured in a low power state + * that is suitable for presenting ambient information to the user, + * possibly with lower fidelity than normal but greater efficiency. */ + HWC_POWER_MODE_DOZE = 1, + /* The display is turned on normally. */ + HWC_POWER_MODE_NORMAL = 2, + /* The display is configured as in HWC_POWER_MODE_DOZE but may + * stop applying frame buffer updates from the graphics subsystem. + * This power mode is effectively a hint from the doze dream to + * tell the hardware that it is done drawing to the display for the + * time being and that the display should remain on in a low power + * state and continue showing its current contents indefinitely + * until the mode changes. + * + * This mode may also be used as a signal to enable hardware-based doze + * functionality. In this case, the doze dream is effectively + * indicating that the hardware is free to take over the display + * and manage it autonomously to implement low power always-on display + * functionality. */ + HWC_POWER_MODE_DOZE_SUSPEND = 3, +}; + +/*****************************************************************************/ + +__END_DECLS + +#endif /* ANDROID_INCLUDE_HARDWARE_HWCOMPOSER_DEFS_H */ diff --git a/.ci/android_headers/ndk/sync.h b/.ci/android_headers/ndk/sync.h new file mode 100644 index 0000000..2ca389b --- /dev/null +++ b/.ci/android_headers/ndk/sync.h @@ -0,0 +1,111 @@ +// clang-format off +/* + * Copyright 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @addtogroup Sync + * @{ + */ + +/** + * @file sync.h + */ + +#ifndef ANDROID_SYNC_H +#define ANDROID_SYNC_H + +#include <stdint.h> +#include <sys/cdefs.h> + +#include <linux/sync_file.h> + +__BEGIN_DECLS + +#if __ANDROID_API__ >= 26 + +/* Fences indicate the status of an asynchronous task. They are initially + * in unsignaled state (0), and make a one-time transition to either signaled + * (1) or error (< 0) state. A sync file is a collection of one or more fences; + * the sync file's status is error if any of its fences are in error state, + * signaled if all of the child fences are signaled, or unsignaled otherwise. + * + * Sync files are created by various device APIs in response to submitting + * tasks to the device. Standard file descriptor lifetime syscalls like dup() + * and close() are used to manage sync file lifetime. + * + * The poll(), ppoll(), or select() syscalls can be used to wait for the sync + * file to change status, or (with a timeout of zero) to check its status. + * + * The functions below provide a few additional sync-specific operations. + */ + +/** + * Merge two sync files. + * + * This produces a new sync file with the given name which has the union of the + * two original sync file's fences; redundant fences may be removed. + * + * If one of the input sync files is signaled or invalid, then this function + * may behave like dup(): the new file descriptor refers to the valid/unsignaled + * sync file with its original name, rather than a new sync file. + * + * The original fences remain valid, and the caller is responsible for closing + * them. + * + * Available since API level 26. + */ +int32_t sync_merge(const char* name, int32_t fd1, int32_t fd2) /* __INTRODUCED_IN(26) */; + +/** + * Retrieve detailed information about a sync file and its fences. + * + * The returned sync_file_info must be freed by calling sync_file_info_free(). + * + * Available since API level 26. + */ +struct sync_file_info* sync_file_info(int32_t fd) /* __INTRODUCED_IN(26) */; + +/** + * Get the array of fence infos from the sync file's info. + * + * The returned array is owned by the parent sync file info, and has + * info->num_fences entries. + * + * Available since API level 26. + */ +static inline struct sync_fence_info* sync_get_fence_info(const struct sync_file_info* info) { +// This header should compile in C, but some C++ projects enable +// warnings-as-error for C-style casts. +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wold-style-cast" + return (struct sync_fence_info *)(uintptr_t)(info->sync_fence_info); +#pragma GCC diagnostic pop +} + +/** + * Free a struct sync_file_info structure + * + * Available since API level 26. + */ +void sync_file_info_free(struct sync_file_info* info) /* __INTRODUCED_IN(26) */; + +#endif /* __ANDROID_API__ >= 26 */ + +__END_DECLS + +#endif /* ANDROID_SYNC_H */ + +/** @} */ diff --git a/.ci/android_headers/sync/sync.h b/.ci/android_headers/sync/sync.h new file mode 100644 index 0000000..4ec6d4c --- /dev/null +++ b/.ci/android_headers/sync/sync.h @@ -0,0 +1,50 @@ +// clang-format off +/* + * sync.h + * + * Copyright 2012 Google, Inc + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __SYS_CORE_SYNC_H +#define __SYS_CORE_SYNC_H + +/* This file contains the legacy sync interface used by Android platform and + * device code. The direct contents will be removed over time as code + * transitions to using the updated interface in ndk/sync.h. When this file is + * empty other than the ndk/sync.h include, that file will be renamed to + * replace this one. + * + * New code should continue to include this file (#include <android/sync.h>) + * instead of ndk/sync.h so the eventual rename is seamless, but should only + * use the things declared in ndk/sync.h. + * + * This file used to be called sync/sync.h, but we renamed to that both the + * platform and NDK call it android/sync.h. A symlink from the old name to this + * one exists temporarily to avoid having to change all sync clients + * simultaneously. It will be removed when they've been updated, and probably + * after this change has been delivered to AOSP so that integrations don't + * break builds. + */ + +#include "../ndk/sync.h" + +__BEGIN_DECLS + +/* timeout in msecs */ +int sync_wait(int fd, int timeout); + +__END_DECLS + +#endif /* __SYS_CORE_SYNC_H */ diff --git a/.ci/android_headers/system/graphics-base-v1.0.h b/.ci/android_headers/system/graphics-base-v1.0.h new file mode 100644 index 0000000..20a80ed --- /dev/null +++ b/.ci/android_headers/system/graphics-base-v1.0.h @@ -0,0 +1,141 @@ +// clang-format off +// This file is autogenerated by hidl-gen. Do not edit manually. +// Source: android.hardware.graphics.common@1.0 +// Location: hardware/interfaces/graphics/common/1.0/ + +#ifndef HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_0_EXPORTED_CONSTANTS_H_ +#define HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_0_EXPORTED_CONSTANTS_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + HAL_PIXEL_FORMAT_RGBA_8888 = 1, + HAL_PIXEL_FORMAT_RGBX_8888 = 2, + HAL_PIXEL_FORMAT_RGB_888 = 3, + HAL_PIXEL_FORMAT_RGB_565 = 4, + HAL_PIXEL_FORMAT_BGRA_8888 = 5, + HAL_PIXEL_FORMAT_YCBCR_422_SP = 16, + HAL_PIXEL_FORMAT_YCRCB_420_SP = 17, + HAL_PIXEL_FORMAT_YCBCR_422_I = 20, + HAL_PIXEL_FORMAT_RGBA_FP16 = 22, + HAL_PIXEL_FORMAT_RAW16 = 32, + HAL_PIXEL_FORMAT_BLOB = 33, + HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED = 34, + HAL_PIXEL_FORMAT_YCBCR_420_888 = 35, + HAL_PIXEL_FORMAT_RAW_OPAQUE = 36, + HAL_PIXEL_FORMAT_RAW10 = 37, + HAL_PIXEL_FORMAT_RAW12 = 38, + HAL_PIXEL_FORMAT_RGBA_1010102 = 43, + HAL_PIXEL_FORMAT_Y8 = 538982489, + HAL_PIXEL_FORMAT_Y16 = 540422489, + HAL_PIXEL_FORMAT_YV12 = 842094169, +} android_pixel_format_t; + +typedef enum { + HAL_TRANSFORM_FLIP_H = 1, // (1 << 0) + HAL_TRANSFORM_FLIP_V = 2, // (1 << 1) + HAL_TRANSFORM_ROT_90 = 4, // (1 << 2) + HAL_TRANSFORM_ROT_180 = 3, // (FLIP_H | FLIP_V) + HAL_TRANSFORM_ROT_270 = 7, // ((FLIP_H | FLIP_V) | ROT_90) +} android_transform_t; + +typedef enum { + HAL_DATASPACE_UNKNOWN = 0, + HAL_DATASPACE_ARBITRARY = 1, + HAL_DATASPACE_STANDARD_SHIFT = 16, + HAL_DATASPACE_STANDARD_MASK = 4128768, // (63 << STANDARD_SHIFT) + HAL_DATASPACE_STANDARD_UNSPECIFIED = 0, // (0 << STANDARD_SHIFT) + HAL_DATASPACE_STANDARD_BT709 = 65536, // (1 << STANDARD_SHIFT) + HAL_DATASPACE_STANDARD_BT601_625 = 131072, // (2 << STANDARD_SHIFT) + HAL_DATASPACE_STANDARD_BT601_625_UNADJUSTED = 196608, // (3 << STANDARD_SHIFT) + HAL_DATASPACE_STANDARD_BT601_525 = 262144, // (4 << STANDARD_SHIFT) + HAL_DATASPACE_STANDARD_BT601_525_UNADJUSTED = 327680, // (5 << STANDARD_SHIFT) + HAL_DATASPACE_STANDARD_BT2020 = 393216, // (6 << STANDARD_SHIFT) + HAL_DATASPACE_STANDARD_BT2020_CONSTANT_LUMINANCE = 458752, // (7 << STANDARD_SHIFT) + HAL_DATASPACE_STANDARD_BT470M = 524288, // (8 << STANDARD_SHIFT) + HAL_DATASPACE_STANDARD_FILM = 589824, // (9 << STANDARD_SHIFT) + HAL_DATASPACE_STANDARD_DCI_P3 = 655360, // (10 << STANDARD_SHIFT) + HAL_DATASPACE_STANDARD_ADOBE_RGB = 720896, // (11 << STANDARD_SHIFT) + HAL_DATASPACE_TRANSFER_SHIFT = 22, + HAL_DATASPACE_TRANSFER_MASK = 130023424, // (31 << TRANSFER_SHIFT) + HAL_DATASPACE_TRANSFER_UNSPECIFIED = 0, // (0 << TRANSFER_SHIFT) + HAL_DATASPACE_TRANSFER_LINEAR = 4194304, // (1 << TRANSFER_SHIFT) + HAL_DATASPACE_TRANSFER_SRGB = 8388608, // (2 << TRANSFER_SHIFT) + HAL_DATASPACE_TRANSFER_SMPTE_170M = 12582912, // (3 << TRANSFER_SHIFT) + HAL_DATASPACE_TRANSFER_GAMMA2_2 = 16777216, // (4 << TRANSFER_SHIFT) + HAL_DATASPACE_TRANSFER_GAMMA2_6 = 20971520, // (5 << TRANSFER_SHIFT) + HAL_DATASPACE_TRANSFER_GAMMA2_8 = 25165824, // (6 << TRANSFER_SHIFT) + HAL_DATASPACE_TRANSFER_ST2084 = 29360128, // (7 << TRANSFER_SHIFT) + HAL_DATASPACE_TRANSFER_HLG = 33554432, // (8 << TRANSFER_SHIFT) + HAL_DATASPACE_RANGE_SHIFT = 27, + HAL_DATASPACE_RANGE_MASK = 939524096, // (7 << RANGE_SHIFT) + HAL_DATASPACE_RANGE_UNSPECIFIED = 0, // (0 << RANGE_SHIFT) + HAL_DATASPACE_RANGE_FULL = 134217728, // (1 << RANGE_SHIFT) + HAL_DATASPACE_RANGE_LIMITED = 268435456, // (2 << RANGE_SHIFT) + HAL_DATASPACE_RANGE_EXTENDED = 402653184, // (3 << RANGE_SHIFT) + HAL_DATASPACE_SRGB_LINEAR = 512, + HAL_DATASPACE_V0_SRGB_LINEAR = 138477568, // ((STANDARD_BT709 | TRANSFER_LINEAR) | RANGE_FULL) + HAL_DATASPACE_V0_SCRGB_LINEAR = + 406913024, // ((STANDARD_BT709 | TRANSFER_LINEAR) | RANGE_EXTENDED) + HAL_DATASPACE_SRGB = 513, + HAL_DATASPACE_V0_SRGB = 142671872, // ((STANDARD_BT709 | TRANSFER_SRGB) | RANGE_FULL) + HAL_DATASPACE_V0_SCRGB = 411107328, // ((STANDARD_BT709 | TRANSFER_SRGB) | RANGE_EXTENDED) + HAL_DATASPACE_JFIF = 257, + HAL_DATASPACE_V0_JFIF = 146931712, // ((STANDARD_BT601_625 | TRANSFER_SMPTE_170M) | RANGE_FULL) + HAL_DATASPACE_BT601_625 = 258, + HAL_DATASPACE_V0_BT601_625 = + 281149440, // ((STANDARD_BT601_625 | TRANSFER_SMPTE_170M) | RANGE_LIMITED) + HAL_DATASPACE_BT601_525 = 259, + HAL_DATASPACE_V0_BT601_525 = + 281280512, // ((STANDARD_BT601_525 | TRANSFER_SMPTE_170M) | RANGE_LIMITED) + HAL_DATASPACE_BT709 = 260, + HAL_DATASPACE_V0_BT709 = 281083904, // ((STANDARD_BT709 | TRANSFER_SMPTE_170M) | RANGE_LIMITED) + HAL_DATASPACE_DCI_P3_LINEAR = 139067392, // ((STANDARD_DCI_P3 | TRANSFER_LINEAR) | RANGE_FULL) + HAL_DATASPACE_DCI_P3 = 155844608, // ((STANDARD_DCI_P3 | TRANSFER_GAMMA2_6) | RANGE_FULL) + HAL_DATASPACE_DISPLAY_P3_LINEAR = + 139067392, // ((STANDARD_DCI_P3 | TRANSFER_LINEAR) | RANGE_FULL) + HAL_DATASPACE_DISPLAY_P3 = 143261696, // ((STANDARD_DCI_P3 | TRANSFER_SRGB) | RANGE_FULL) + HAL_DATASPACE_ADOBE_RGB = 151715840, // ((STANDARD_ADOBE_RGB | TRANSFER_GAMMA2_2) | RANGE_FULL) + HAL_DATASPACE_BT2020_LINEAR = 138805248, // ((STANDARD_BT2020 | TRANSFER_LINEAR) | RANGE_FULL) + HAL_DATASPACE_BT2020 = 147193856, // ((STANDARD_BT2020 | TRANSFER_SMPTE_170M) | RANGE_FULL) + HAL_DATASPACE_BT2020_PQ = 163971072, // ((STANDARD_BT2020 | TRANSFER_ST2084) | RANGE_FULL) + HAL_DATASPACE_DEPTH = 4096, + HAL_DATASPACE_SENSOR = 4097, +} android_dataspace_t; + +typedef enum { + HAL_COLOR_MODE_NATIVE = 0, + HAL_COLOR_MODE_STANDARD_BT601_625 = 1, + HAL_COLOR_MODE_STANDARD_BT601_625_UNADJUSTED = 2, + HAL_COLOR_MODE_STANDARD_BT601_525 = 3, + HAL_COLOR_MODE_STANDARD_BT601_525_UNADJUSTED = 4, + HAL_COLOR_MODE_STANDARD_BT709 = 5, + HAL_COLOR_MODE_DCI_P3 = 6, + HAL_COLOR_MODE_SRGB = 7, + HAL_COLOR_MODE_ADOBE_RGB = 8, + HAL_COLOR_MODE_DISPLAY_P3 = 9, +} android_color_mode_t; + +typedef enum { + HAL_COLOR_TRANSFORM_IDENTITY = 0, + HAL_COLOR_TRANSFORM_ARBITRARY_MATRIX = 1, + HAL_COLOR_TRANSFORM_VALUE_INVERSE = 2, + HAL_COLOR_TRANSFORM_GRAYSCALE = 3, + HAL_COLOR_TRANSFORM_CORRECT_PROTANOPIA = 4, + HAL_COLOR_TRANSFORM_CORRECT_DEUTERANOPIA = 5, + HAL_COLOR_TRANSFORM_CORRECT_TRITANOPIA = 6, +} android_color_transform_t; + +typedef enum { + HAL_HDR_DOLBY_VISION = 1, + HAL_HDR_HDR10 = 2, + HAL_HDR_HLG = 3, +} android_hdr_t; + +#ifdef __cplusplus +} +#endif + +#endif // HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_0_EXPORTED_CONSTANTS_H_ diff --git a/.ci/android_headers/system/graphics-base-v1.1.h b/.ci/android_headers/system/graphics-base-v1.1.h new file mode 100644 index 0000000..a90da62 --- /dev/null +++ b/.ci/android_headers/system/graphics-base-v1.1.h @@ -0,0 +1,49 @@ +// clang-format off +// This file is autogenerated by hidl-gen. Do not edit manually. +// Source: android.hardware.graphics.common@1.1 +// Location: hardware/interfaces/graphics/common/1.1/ + +#ifndef HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_1_EXPORTED_CONSTANTS_H_ +#define HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_1_EXPORTED_CONSTANTS_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + HAL_PIXEL_FORMAT_DEPTH_16 = 48, + HAL_PIXEL_FORMAT_DEPTH_24 = 49, + HAL_PIXEL_FORMAT_DEPTH_24_STENCIL_8 = 50, + HAL_PIXEL_FORMAT_DEPTH_32F = 51, + HAL_PIXEL_FORMAT_DEPTH_32F_STENCIL_8 = 52, + HAL_PIXEL_FORMAT_STENCIL_8 = 53, + HAL_PIXEL_FORMAT_YCBCR_P010 = 54, +} android_pixel_format_v1_1_t; + +typedef enum { + HAL_DATASPACE_BT2020_ITU = + 281411584, // ((STANDARD_BT2020 | TRANSFER_SMPTE_170M) | RANGE_LIMITED) + HAL_DATASPACE_BT2020_ITU_PQ = + 298188800, // ((STANDARD_BT2020 | TRANSFER_ST2084) | RANGE_LIMITED) + HAL_DATASPACE_BT2020_ITU_HLG = 302383104, // ((STANDARD_BT2020 | TRANSFER_HLG) | RANGE_LIMITED) + HAL_DATASPACE_BT2020_HLG = 168165376, // ((STANDARD_BT2020 | TRANSFER_HLG) | RANGE_FULL) +} android_dataspace_v1_1_t; + +typedef enum { + HAL_COLOR_MODE_BT2020 = 10, + HAL_COLOR_MODE_BT2100_PQ = 11, + HAL_COLOR_MODE_BT2100_HLG = 12, +} android_color_mode_v1_1_t; + +typedef enum { + HAL_RENDER_INTENT_COLORIMETRIC = 0, + HAL_RENDER_INTENT_ENHANCE = 1, + HAL_RENDER_INTENT_TONE_MAP_COLORIMETRIC = 2, + HAL_RENDER_INTENT_TONE_MAP_ENHANCE = 3, +} android_render_intent_v1_1_t; + +#ifdef __cplusplus +} +#endif + +#endif // HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_1_EXPORTED_CONSTANTS_H_ diff --git a/.ci/android_headers/system/graphics-base-v1.2.h b/.ci/android_headers/system/graphics-base-v1.2.h new file mode 100644 index 0000000..baddf79 --- /dev/null +++ b/.ci/android_headers/system/graphics-base-v1.2.h @@ -0,0 +1,32 @@ +// clang-format off +// This file is autogenerated by hidl-gen. Do not edit manually. +// Source: android.hardware.graphics.common@1.2 +// Location: hardware/interfaces/graphics/common/1.2/ + +#ifndef HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_2_EXPORTED_CONSTANTS_H_ +#define HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_2_EXPORTED_CONSTANTS_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + HAL_HDR_HDR10_PLUS = 4, +} android_hdr_v1_2_t; + +typedef enum { + HAL_DATASPACE_DISPLAY_BT2020 = 142999552 /* ((STANDARD_BT2020 | TRANSFER_SRGB) | RANGE_FULL) */, + HAL_DATASPACE_DYNAMIC_DEPTH = 4098 /* 0x1002 */, + HAL_DATASPACE_JPEG_APP_SEGMENTS = 4099 /* 0x1003 */, + HAL_DATASPACE_HEIF = 4100 /* 0x1004 */, +} android_dataspace_v1_2_t; + +typedef enum { + HAL_PIXEL_FORMAT_HSV_888 = 55 /* 0x37 */, +} android_pixel_format_v1_2_t; + +#ifdef __cplusplus +} +#endif + +#endif // HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_2_EXPORTED_CONSTANTS_H_ diff --git a/.ci/android_headers/system/graphics-base.h b/.ci/android_headers/system/graphics-base.h new file mode 100644 index 0000000..073b985 --- /dev/null +++ b/.ci/android_headers/system/graphics-base.h @@ -0,0 +1,9 @@ +// clang-format off +#ifndef SYSTEM_CORE_GRAPHICS_BASE_H_ +#define SYSTEM_CORE_GRAPHICS_BASE_H_ + +#include "graphics-base-v1.0.h" +#include "graphics-base-v1.1.h" +#include "graphics-base-v1.2.h" + +#endif // SYSTEM_CORE_GRAPHICS_BASE_H_ diff --git a/.ci/android_headers/system/graphics-sw.h b/.ci/android_headers/system/graphics-sw.h new file mode 100644 index 0000000..dd29e63 --- /dev/null +++ b/.ci/android_headers/system/graphics-sw.h @@ -0,0 +1,17 @@ +// clang-format off +#ifndef SYSTEM_CORE_GRAPHICS_SW_H_ +#define SYSTEM_CORE_GRAPHICS_SW_H_ + +/* Software formats not in the HAL definitions. */ +typedef enum { + HAL_PIXEL_FORMAT_YCBCR_422_888 = 39, // 0x27 + HAL_PIXEL_FORMAT_YCBCR_444_888 = 40, // 0x28 + HAL_PIXEL_FORMAT_FLEX_RGB_888 = 41, // 0x29 + HAL_PIXEL_FORMAT_FLEX_RGBA_8888 = 42, // 0x2A +} android_pixel_format_sw_t; + +/* for compatibility */ +#define HAL_PIXEL_FORMAT_YCbCr_422_888 HAL_PIXEL_FORMAT_YCBCR_422_888 +#define HAL_PIXEL_FORMAT_YCbCr_444_888 HAL_PIXEL_FORMAT_YCBCR_444_888 + +#endif // SYSTEM_CORE_GRAPHICS_SW_H_ diff --git a/.ci/android_headers/system/graphics.h b/.ci/android_headers/system/graphics.h new file mode 100644 index 0000000..8693587 --- /dev/null +++ b/.ci/android_headers/system/graphics.h @@ -0,0 +1,269 @@ +// clang-format off +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SYSTEM_CORE_INCLUDE_ANDROID_GRAPHICS_H +#define SYSTEM_CORE_INCLUDE_ANDROID_GRAPHICS_H + +#include <stddef.h> +#include <stdint.h> + +/* + * Some of the enums are now defined in HIDL in hardware/interfaces and are + * generated. + */ +#include "graphics-base.h" +#include "graphics-sw.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* for compatibility */ +#define HAL_PIXEL_FORMAT_YCbCr_420_888 HAL_PIXEL_FORMAT_YCBCR_420_888 +#define HAL_PIXEL_FORMAT_YCbCr_422_SP HAL_PIXEL_FORMAT_YCBCR_422_SP +#define HAL_PIXEL_FORMAT_YCrCb_420_SP HAL_PIXEL_FORMAT_YCRCB_420_SP +#define HAL_PIXEL_FORMAT_YCbCr_422_I HAL_PIXEL_FORMAT_YCBCR_422_I +typedef android_pixel_format_t android_pixel_format; +typedef android_transform_t android_transform; +typedef android_dataspace_t android_dataspace; +typedef android_color_mode_t android_color_mode; +typedef android_color_transform_t android_color_transform; +typedef android_hdr_t android_hdr; + +/* + * If the HAL needs to create service threads to handle graphics related + * tasks, these threads need to run at HAL_PRIORITY_URGENT_DISPLAY priority + * if they can block the main rendering thread in any way. + * + * the priority of the current thread can be set with: + * + * #include <sys/resource.h> + * setpriority(PRIO_PROCESS, 0, HAL_PRIORITY_URGENT_DISPLAY); + * + */ + +#define HAL_PRIORITY_URGENT_DISPLAY (-8) + +/* + * Structure for describing YCbCr formats for consumption by applications. + * This is used with HAL_PIXEL_FORMAT_YCbCr_*_888. + * + * Buffer chroma subsampling is defined in the format. + * e.g. HAL_PIXEL_FORMAT_YCbCr_420_888 has subsampling 4:2:0. + * + * Buffers must have a 8 bit depth. + * + * y, cb, and cr point to the first byte of their respective planes. + * + * Stride describes the distance in bytes from the first value of one row of + * the image to the first value of the next row. It includes the width of the + * image plus padding. + * ystride is the stride of the luma plane. + * cstride is the stride of the chroma planes. + * + * chroma_step is the distance in bytes from one chroma pixel value to the + * next. This is 2 bytes for semiplanar (because chroma values are interleaved + * and each chroma value is one byte) and 1 for planar. + */ + +struct android_ycbcr { + void *y; + void *cb; + void *cr; + size_t ystride; + size_t cstride; + size_t chroma_step; + + /** reserved for future use, set to 0 by gralloc's (*lock_ycbcr)() */ + uint32_t reserved[8]; +}; + +/* + * Structures for describing flexible YUVA/RGBA formats for consumption by + * applications. Such flexible formats contain a plane for each component (e.g. + * red, green, blue), where each plane is laid out in a grid-like pattern + * occupying unique byte addresses and with consistent byte offsets between + * neighboring pixels. + * + * The android_flex_layout structure is used with any pixel format that can be + * represented by it, such as: + * - HAL_PIXEL_FORMAT_YCbCr_*_888 + * - HAL_PIXEL_FORMAT_FLEX_RGB*_888 + * - HAL_PIXEL_FORMAT_RGB[AX]_888[8],BGRA_8888,RGB_888 + * - HAL_PIXEL_FORMAT_YV12,Y8,Y16,YCbCr_422_SP/I,YCrCb_420_SP + * - even implementation defined formats that can be represented by + * the structures + * + * Vertical increment (aka. row increment or stride) describes the distance in + * bytes from the first pixel of one row to the first pixel of the next row + * (below) for the component plane. This can be negative. + * + * Horizontal increment (aka. column or pixel increment) describes the distance + * in bytes from one pixel to the next pixel (to the right) on the same row for + * the component plane. This can be negative. + * + * Each plane can be subsampled either vertically or horizontally by + * a power-of-two factor. + * + * The bit-depth of each component can be arbitrary, as long as the pixels are + * laid out on whole bytes, in native byte-order, using the most significant + * bits of each unit. + */ + +typedef enum android_flex_component { + /* luma */ + FLEX_COMPONENT_Y = 1 << 0, + /* chroma blue */ + FLEX_COMPONENT_Cb = 1 << 1, + /* chroma red */ + FLEX_COMPONENT_Cr = 1 << 2, + + /* red */ + FLEX_COMPONENT_R = 1 << 10, + /* green */ + FLEX_COMPONENT_G = 1 << 11, + /* blue */ + FLEX_COMPONENT_B = 1 << 12, + + /* alpha */ + FLEX_COMPONENT_A = 1 << 30, +} android_flex_component_t; + +typedef struct android_flex_plane { + /* pointer to the first byte of the top-left pixel of the plane. */ + uint8_t *top_left; + + android_flex_component_t component; + + /* bits allocated for the component in each pixel. Must be a positive + multiple of 8. */ + int32_t bits_per_component; + /* number of the most significant bits used in the format for this + component. Must be between 1 and bits_per_component, inclusive. */ + int32_t bits_used; + + /* horizontal increment */ + int32_t h_increment; + /* vertical increment */ + int32_t v_increment; + /* horizontal subsampling. Must be a positive power of 2. */ + int32_t h_subsampling; + /* vertical subsampling. Must be a positive power of 2. */ + int32_t v_subsampling; +} android_flex_plane_t; + +typedef enum android_flex_format { + /* not a flexible format */ + FLEX_FORMAT_INVALID = 0x0, + FLEX_FORMAT_Y = FLEX_COMPONENT_Y, + FLEX_FORMAT_YCbCr = FLEX_COMPONENT_Y | FLEX_COMPONENT_Cb | FLEX_COMPONENT_Cr, + FLEX_FORMAT_YCbCrA = FLEX_FORMAT_YCbCr | FLEX_COMPONENT_A, + FLEX_FORMAT_RGB = FLEX_COMPONENT_R | FLEX_COMPONENT_G | FLEX_COMPONENT_B, + FLEX_FORMAT_RGBA = FLEX_FORMAT_RGB | FLEX_COMPONENT_A, +} android_flex_format_t; + +typedef struct android_flex_layout { + /* the kind of flexible format */ + android_flex_format_t format; + + /* number of planes; 0 for FLEX_FORMAT_INVALID */ + uint32_t num_planes; + /* a plane for each component; ordered in increasing component value order. + E.g. FLEX_FORMAT_RGBA maps 0 -> R, 1 -> G, etc. + Can be NULL for FLEX_FORMAT_INVALID */ + android_flex_plane_t *planes; +} android_flex_layout_t; + +/** + * Structure used to define depth point clouds for format HAL_PIXEL_FORMAT_BLOB + * with dataSpace value of HAL_DATASPACE_DEPTH. + * When locking a native buffer of the above format and dataSpace value, + * the vaddr pointer can be cast to this structure. + * + * A variable-length list of (x,y,z, confidence) 3D points, as floats. (x, y, + * z) represents a measured point's position, with the coordinate system defined + * by the data source. Confidence represents the estimated likelihood that this + * measurement is correct. It is between 0.f and 1.f, inclusive, with 1.f == + * 100% confidence. + * + * num_points is the number of points in the list + * + * xyz_points is the flexible array of floating-point values. + * It contains (num_points) * 4 floats. + * + * For example: + * android_depth_points d = get_depth_buffer(); + * struct { + * float x; float y; float z; float confidence; + * } firstPoint, lastPoint; + * + * firstPoint.x = d.xyzc_points[0]; + * firstPoint.y = d.xyzc_points[1]; + * firstPoint.z = d.xyzc_points[2]; + * firstPoint.confidence = d.xyzc_points[3]; + * lastPoint.x = d.xyzc_points[(d.num_points - 1) * 4 + 0]; + * lastPoint.y = d.xyzc_points[(d.num_points - 1) * 4 + 1]; + * lastPoint.z = d.xyzc_points[(d.num_points - 1) * 4 + 2]; + * lastPoint.confidence = d.xyzc_points[(d.num_points - 1) * 4 + 3]; + */ + +struct android_depth_points { + uint32_t num_points; + + /** reserved for future use, set to 0 by gralloc's (*lock)() */ + uint32_t reserved[8]; + +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wc99-extensions" +#endif + float xyzc_points[]; +#if defined(__clang__) +#pragma clang diagnostic pop +#endif +}; + +/** + * These structures are used to define the reference display's + * capabilities for HDR content. Display engine can use this + * to better tone map content to user's display. + * Color is defined in CIE XYZ coordinates + */ +struct android_xy_color { + float x; + float y; +}; + +struct android_smpte2086_metadata { + struct android_xy_color displayPrimaryRed; + struct android_xy_color displayPrimaryGreen; + struct android_xy_color displayPrimaryBlue; + struct android_xy_color whitePoint; + float maxLuminance; + float minLuminance; +}; + +struct android_cta861_3_metadata { + float maxContentLightLevel; + float maxFrameAverageLightLevel; +}; + +#ifdef __cplusplus +} +#endif + +#endif /* SYSTEM_CORE_INCLUDE_ANDROID_GRAPHICS_H */ diff --git a/.ci/android_headers/ui/GraphicBuffer.h b/.ci/android_headers/ui/GraphicBuffer.h new file mode 100644 index 0000000..701340c --- /dev/null +++ b/.ci/android_headers/ui/GraphicBuffer.h @@ -0,0 +1,286 @@ +// clang-format off +/* + * Copyright (C) 2007 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_GRAPHIC_BUFFER_H +#define ANDROID_GRAPHIC_BUFFER_H + +#include <stdint.h> +#include <sys/types.h> + +#include <string> +#include <utility> +#include <vector> + +#include <android/hardware_buffer.h> +#include <ui/ANativeObjectBase.h> +#include <ui/GraphicBufferMapper.h> +#include <ui/PixelFormat.h> +#include <ui/Rect.h> +#include <utils/Flattenable.h> +#include <utils/RefBase.h> + +#include <nativebase/nativebase.h> + +#include <hardware/gralloc.h> + +namespace android { + +class GraphicBufferMapper; + +using GraphicBufferDeathCallback = std::function<void(void* /*context*/, uint64_t bufferId)>; + +// =========================================================================== +// GraphicBuffer +// =========================================================================== + +class GraphicBuffer + : public ANativeObjectBase<ANativeWindowBuffer, GraphicBuffer, RefBase>, + public Flattenable<GraphicBuffer> +{ + friend class Flattenable<GraphicBuffer>; +public: + + enum { + USAGE_SW_READ_NEVER = GRALLOC_USAGE_SW_READ_NEVER, + USAGE_SW_READ_RARELY = GRALLOC_USAGE_SW_READ_RARELY, + USAGE_SW_READ_OFTEN = GRALLOC_USAGE_SW_READ_OFTEN, + USAGE_SW_READ_MASK = GRALLOC_USAGE_SW_READ_MASK, + + USAGE_SW_WRITE_NEVER = GRALLOC_USAGE_SW_WRITE_NEVER, + USAGE_SW_WRITE_RARELY = GRALLOC_USAGE_SW_WRITE_RARELY, + USAGE_SW_WRITE_OFTEN = GRALLOC_USAGE_SW_WRITE_OFTEN, + USAGE_SW_WRITE_MASK = GRALLOC_USAGE_SW_WRITE_MASK, + + USAGE_SOFTWARE_MASK = USAGE_SW_READ_MASK|USAGE_SW_WRITE_MASK, + + USAGE_PROTECTED = GRALLOC_USAGE_PROTECTED, + + USAGE_HW_TEXTURE = GRALLOC_USAGE_HW_TEXTURE, + USAGE_HW_RENDER = GRALLOC_USAGE_HW_RENDER, + USAGE_HW_2D = GRALLOC_USAGE_HW_2D, + USAGE_HW_COMPOSER = GRALLOC_USAGE_HW_COMPOSER, + USAGE_HW_VIDEO_ENCODER = GRALLOC_USAGE_HW_VIDEO_ENCODER, + USAGE_HW_MASK = GRALLOC_USAGE_HW_MASK, + + USAGE_CURSOR = GRALLOC_USAGE_CURSOR, + }; + + static sp<GraphicBuffer> from(ANativeWindowBuffer *); + + static GraphicBuffer* fromAHardwareBuffer(AHardwareBuffer*); + static GraphicBuffer const* fromAHardwareBuffer(AHardwareBuffer const*); + AHardwareBuffer* toAHardwareBuffer(); + AHardwareBuffer const* toAHardwareBuffer() const; + + // Create a GraphicBuffer to be unflatten'ed into or be reallocated. + GraphicBuffer(); + + // Create a GraphicBuffer by allocating and managing a buffer internally. + // This function is privileged. See reallocate for details. + GraphicBuffer(uint32_t inWidth, uint32_t inHeight, PixelFormat inFormat, + uint32_t inLayerCount, uint64_t inUsage, + std::string requestorName = "<Unknown>"); + + // Create a GraphicBuffer from an existing handle. + enum HandleWrapMethod : uint8_t { + // Wrap and use the handle directly. It assumes the handle has been + // registered and never fails. The handle must have a longer lifetime + // than this wrapping GraphicBuffer. + // + // This can be used when, for example, you want to wrap a handle that + // is already managed by another GraphicBuffer. + WRAP_HANDLE, + + // Take ownership of the handle and use it directly. It assumes the + // handle has been registered and never fails. + // + // This can be used to manage an already registered handle with + // GraphicBuffer. + TAKE_HANDLE, + + // Take onwership of an unregistered handle and use it directly. It + // can fail when the buffer does not register. There is no ownership + // transfer on failures. + // + // This can be used to, for example, create a GraphicBuffer from a + // handle returned by Parcel::readNativeHandle. + TAKE_UNREGISTERED_HANDLE, + + // Make a clone of the handle and use the cloned handle. It can fail + // when cloning fails or when the buffer does not register. There is + // never ownership transfer. + // + // This can be used to create a GraphicBuffer from a handle that + // cannot be used directly, such as one from hidl_handle. + CLONE_HANDLE, + }; + GraphicBuffer(const native_handle_t* inHandle, HandleWrapMethod method, uint32_t inWidth, + uint32_t inHeight, PixelFormat inFormat, uint32_t inLayerCount, uint64_t inUsage, + uint32_t inStride); + + // These functions are deprecated because they only take 32 bits of usage + GraphicBuffer(const native_handle_t* inHandle, HandleWrapMethod method, uint32_t inWidth, + uint32_t inHeight, PixelFormat inFormat, uint32_t inLayerCount, uint32_t inUsage, + uint32_t inStride) + : GraphicBuffer(inHandle, method, inWidth, inHeight, inFormat, inLayerCount, + static_cast<uint64_t>(inUsage), inStride) {} + GraphicBuffer(uint32_t inWidth, uint32_t inHeight, PixelFormat inFormat, + uint32_t inLayerCount, uint32_t inUsage, uint32_t inStride, + native_handle_t* inHandle, bool keepOwnership); + GraphicBuffer(uint32_t inWidth, uint32_t inHeight, PixelFormat inFormat, + uint32_t inUsage, std::string requestorName = "<Unknown>"); + + // return status + status_t initCheck() const; + + uint32_t getWidth() const { return static_cast<uint32_t>(width); } + uint32_t getHeight() const { return static_cast<uint32_t>(height); } + uint32_t getStride() const { return static_cast<uint32_t>(stride); } + uint64_t getUsage() const { return usage; } + PixelFormat getPixelFormat() const { return format; } + uint32_t getLayerCount() const { return static_cast<uint32_t>(layerCount); } + Rect getBounds() const { return Rect(width, height); } + uint64_t getId() const { return mId; } + + uint32_t getGenerationNumber() const { return mGenerationNumber; } + void setGenerationNumber(uint32_t generation) { + mGenerationNumber = generation; + } + + // This function is privileged. It requires access to the allocator + // device or service, which usually involves adding suitable selinux + // rules. + status_t reallocate(uint32_t inWidth, uint32_t inHeight, + PixelFormat inFormat, uint32_t inLayerCount, uint64_t inUsage); + + bool needsReallocation(uint32_t inWidth, uint32_t inHeight, + PixelFormat inFormat, uint32_t inLayerCount, uint64_t inUsage); + + // For the following two lock functions, if bytesPerStride or bytesPerPixel + // are unknown or variable, -1 will be returned + status_t lock(uint32_t inUsage, void** vaddr, int32_t* outBytesPerPixel = nullptr, + int32_t* outBytesPerStride = nullptr); + status_t lock(uint32_t inUsage, const Rect& rect, void** vaddr, + int32_t* outBytesPerPixel = nullptr, int32_t* outBytesPerStride = nullptr); + // For HAL_PIXEL_FORMAT_YCbCr_420_888 + status_t lockYCbCr(uint32_t inUsage, android_ycbcr *ycbcr); + status_t lockYCbCr(uint32_t inUsage, const Rect& rect, + android_ycbcr *ycbcr); + status_t unlock(); + // For the following three lockAsync functions, if bytesPerStride or bytesPerPixel + // are unknown or variable, -1 will be returned + status_t lockAsync(uint32_t inUsage, void** vaddr, int fenceFd, + int32_t* outBytesPerPixel = nullptr, int32_t* outBytesPerStride = nullptr); + status_t lockAsync(uint32_t inUsage, const Rect& rect, void** vaddr, int fenceFd, + int32_t* outBytesPerPixel = nullptr, int32_t* outBytesPerStride = nullptr); + status_t lockAsync(uint64_t inProducerUsage, uint64_t inConsumerUsage, const Rect& rect, + void** vaddr, int fenceFd, int32_t* outBytesPerPixel = nullptr, + int32_t* outBytesPerStride = nullptr); + status_t lockAsyncYCbCr(uint32_t inUsage, android_ycbcr *ycbcr, + int fenceFd); + status_t lockAsyncYCbCr(uint32_t inUsage, const Rect& rect, + android_ycbcr *ycbcr, int fenceFd); + status_t unlockAsync(int *fenceFd); + + status_t isSupported(uint32_t inWidth, uint32_t inHeight, PixelFormat inFormat, + uint32_t inLayerCount, uint64_t inUsage, bool* outSupported) const; + + ANativeWindowBuffer* getNativeBuffer() const; + + // for debugging + static void dumpAllocationsToSystemLog(); + + // Flattenable protocol + size_t getFlattenedSize() const; + size_t getFdCount() const; + status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const; + status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count); + + GraphicBufferMapper::Version getBufferMapperVersion() const { + return mBufferMapper.getMapperVersion(); + } + + void addDeathCallback(GraphicBufferDeathCallback deathCallback, void* context); + +private: + ~GraphicBuffer(); + + enum { + ownNone = 0, + ownHandle = 1, + ownData = 2, + }; + + inline const GraphicBufferMapper& getBufferMapper() const { + return mBufferMapper; + } + inline GraphicBufferMapper& getBufferMapper() { + return mBufferMapper; + } + uint8_t mOwner; + +private: + friend class Surface; + friend class BpSurface; + friend class BnSurface; + friend class LightRefBase<GraphicBuffer>; + GraphicBuffer(const GraphicBuffer& rhs); + GraphicBuffer& operator = (const GraphicBuffer& rhs); + const GraphicBuffer& operator = (const GraphicBuffer& rhs) const; + + status_t initWithSize(uint32_t inWidth, uint32_t inHeight, + PixelFormat inFormat, uint32_t inLayerCount, + uint64_t inUsage, std::string requestorName); + + status_t initWithHandle(const native_handle_t* inHandle, HandleWrapMethod method, + uint32_t inWidth, uint32_t inHeight, PixelFormat inFormat, + uint32_t inLayerCount, uint64_t inUsage, uint32_t inStride); + + void free_handle(); + + GraphicBufferMapper& mBufferMapper; + ssize_t mInitCheck; + + // numbers of fds/ints in native_handle_t to flatten + uint32_t mTransportNumFds; + uint32_t mTransportNumInts; + + uint64_t mId; + + // Stores the generation number of this buffer. If this number does not + // match the BufferQueue's internal generation number (set through + // IGBP::setGenerationNumber), attempts to attach the buffer will fail. + uint32_t mGenerationNumber; + + // Send a callback when a GraphicBuffer dies. + // + // This is used for BufferStateLayer caching. GraphicBuffers are refcounted per process. When + // A GraphicBuffer doesn't have any more sp<> in a process, it is destroyed. This causes + // problems when trying to implicitcly cache across process boundaries. Ideally, both sides + // of the cache would hold onto wp<> references. When an app dropped its sp<>, the GraphicBuffer + // would be destroyed. Unfortunately, when SurfaceFlinger has only a wp<> reference to the + // GraphicBuffer, it immediately goes out of scope in the SurfaceFlinger process. SurfaceFlinger + // must hold onto a sp<> to the buffer. When the GraphicBuffer goes out of scope in the app's + // process, the client side cache will get this callback. It erases the buffer from its cache + // and informs SurfaceFlinger that it should drop its strong pointer reference to the buffer. + std::vector<std::pair<GraphicBufferDeathCallback, void* /*mDeathCallbackContext*/>> + mDeathCallbacks; +}; + +}; // namespace android + +#endif // ANDROID_GRAPHIC_BUFFER_H diff --git a/.ci/android_headers/utils/Trace.h b/.ci/android_headers/utils/Trace.h new file mode 100644 index 0000000..88c4db5 --- /dev/null +++ b/.ci/android_headers/utils/Trace.h @@ -0,0 +1,62 @@ +// clang-format off +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_TRACE_H +#define ANDROID_TRACE_H + +#if defined(_WIN32) + +#define ATRACE_NAME(...) +#define ATRACE_CALL() + +#else // !_WIN32 + +#include <stdint.h> + +#include <cutils/trace.h> + +// See <cutils/trace.h> for more ATRACE_* macros. + +// ATRACE_NAME traces from its location until the end of its enclosing scope. +#define _PASTE(x, y) x ## y +#define PASTE(x, y) _PASTE(x,y) +#define ATRACE_NAME(name) ::android::ScopedTrace PASTE(___tracer, __LINE__)(ATRACE_TAG, name) + +// ATRACE_CALL is an ATRACE_NAME that uses the current function name. +#define ATRACE_CALL() ATRACE_NAME(__FUNCTION__) + +namespace android { + +class ScopedTrace { +public: + inline ScopedTrace(uint64_t tag, const char* name) : mTag(tag) { + atrace_begin(mTag, name); + } + + inline ~ScopedTrace() { + atrace_end(mTag); + } + +private: + uint64_t mTag; +}; + +} // namespace android + +#endif // _WIN32 + +#endif // ANDROID_TRACE_H diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000..3731a29 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,60 @@ +# Turn all the warnings from the checks above into errors. +WarningsAsErrors: "*" + +#HeaderFilterRegex: "^.*external/drm_hwcomposer/.*.h$" + +FormatStyle: google + +CheckOptions: + - key: readability-identifier-naming.ClassCase + value: CamelCase + - key: readability-identifier-naming.ClassMemberCase + value: lower_case + - key: readability-identifier-naming.ConstexprVariableCase + value: CamelCase + - key: readability-identifier-naming.ConstexprVariablePrefix + value: k + - key: readability-identifier-naming.EnumCase + value: CamelCase + - key: readability-identifier-naming.EnumConstantCase + value: CamelCase + - key: readability-identifier-naming.EnumConstantPrefix + value: k + - key: readability-identifier-naming.FunctionCase + value: CamelCase + - key: readability-identifier-naming.GlobalConstantCase + value: CamelCase + - key: readability-identifier-naming.GlobalConstantPrefix + value: k + - key: readability-identifier-naming.StaticConstantCase + value: CamelCase + - key: readability-identifier-naming.StaticConstantPrefix + value: k + - key: readability-identifier-naming.StaticVariableCase + value: lower_case + - key: readability-identifier-naming.MacroDefinitionCase + value: UPPER_CASE + - key: readability-identifier-naming.MacroDefinitionIgnoredRegexp + value: '^[A-Z]+(_[A-Z]+)*_$' + - key: readability-identifier-naming.MemberCase + value: lower_case + - key: readability-identifier-naming.PrivateMemberSuffix + value: _ + - key: readability-identifier-naming.PublicMemberSuffix + value: '' + - key: readability-identifier-naming.NamespaceCase + value: lower_case + - key: readability-identifier-naming.ParameterCase + value: lower_case + - key: readability-identifier-naming.TypeAliasCase + value: CamelCase + - key: readability-identifier-naming.TypedefCase + value: CamelCase + - key: readability-identifier-naming.VariableCase + value: lower_case + - key: readability-identifier-naming.IgnoreMainLikeFunctions + value: 1 + - key: cppcoreguidelines-macro-usage.AllowedRegexp + value: "LOG_TAG|ATRACE_TAG" + - key: readability-magic-numbers.IgnoredFloatingPointValues + value: '1000.0' diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index c97f4ff..89ac1b8 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,15 +1,27 @@ -image: ubuntu:16.04 +image: ubuntu:21.10 + +variables: + DEBIAN_FRONTEND: noninteractive before_script: - apt-get --quiet update --yes >/dev/null - - apt-get --quiet install --yes clang-format-5.0 git >/dev/null + - apt-get --quiet install --yes clang-13 clang-tidy-13 clang-format-13 git libdrm-dev blueprint-tools libgtest-dev make >/dev/null stages: + - build - style +build: + stage: build + script: + - make -f .ci/Makefile + artifacts: + when: on_failure + untracked: true + checkstyle: stage: style - script: "./.gitlab-ci-checkcommit.sh" + script: "./.ci/.gitlab-ci-checkcommit.sh" artifacts: when: on_failure untracked: true @@ -38,8 +38,8 @@ cc_library_static { srcs: ["utils/Worker.cpp"], include_dirs: [ - "external/drm_hwcomposer/include", "external/drm_hwcomposer", + "external/drm_hwcomposer/include", ], cflags: [ @@ -69,8 +69,8 @@ cc_defaults { ], include_dirs: [ - "external/drm_hwcomposer/include", "external/drm_hwcomposer", + "external/drm_hwcomposer/include", ], static_libs: ["libdrmhwc_utils"], @@ -81,8 +81,9 @@ cc_defaults { ], cppflags: [ - "-DHWC2_USE_CPP11", "-DHWC2_INCLUDE_STRINGIFICATION", + "-DHWC2_USE_CPP11", + "-std=c++17", ], product_variables: { @@ -94,54 +95,67 @@ cc_defaults { relative_install_path: "hw", vendor: true, } -cc_library_static { - name: "drm_hwcomposer", - defaults: ["hwcomposer.drm_defaults"], - srcs: [ - "DrmHwcTwo.cpp", +filegroup { + name: "drm_hwcomposer_common", + srcs: [ "bufferinfo/BufferInfoGetter.cpp", "bufferinfo/BufferInfoMapperMetadata.cpp", - "compositor/DrmDisplayComposition.cpp", - "compositor/DrmDisplayCompositor.cpp", - "compositor/Planner.cpp", + "compositor/DrmKmsPlan.cpp", + "drm/DrmAtomicStateManager.cpp", "drm/DrmConnector.cpp", "drm/DrmCrtc.cpp", "drm/DrmDevice.cpp", + "drm/DrmDisplayPipeline.cpp", "drm/DrmEncoder.cpp", - "drm/DrmEventListener.cpp", - "drm/DrmGenericImporter.cpp", + "drm/DrmFbImporter.cpp", "drm/DrmMode.cpp", "drm/DrmPlane.cpp", "drm/DrmProperty.cpp", "drm/ResourceManager.cpp", + "drm/UEventListener.cpp", "drm/VSyncWorker.cpp", - "utils/autolock.cpp", "utils/hwcutils.cpp", - "backend/BackendManager.cpp", "backend/Backend.cpp", "backend/BackendClient.cpp", - "backend/BackendRCarDu.cpp", + "backend/BackendManager.cpp", + + "hwc2_device/DrmHwcTwo.cpp", + "hwc2_device/HwcDisplay.cpp", + "hwc2_device/HwcDisplayConfigs.cpp", + "hwc2_device/HwcLayer.cpp", + "hwc2_device/hwc2_device.cpp", ], } +// Kept only for compatibility with older Android version. Please do not use! +cc_library_static { + name: "drm_hwcomposer", + defaults: ["hwcomposer.drm_defaults"], + srcs: [":drm_hwcomposer_common"], +} + cc_library_shared { name: "hwcomposer.drm", defaults: ["hwcomposer.drm_defaults"], - whole_static_libs: ["drm_hwcomposer"], - srcs: ["bufferinfo/legacy/BufferInfoLibdrm.cpp"], + srcs: [ + ":drm_hwcomposer_common", + "bufferinfo/legacy/BufferInfoLibdrm.cpp", + ], + cflags: ["-DUSE_IMAPPER4_METADATA_API"], } cc_library_shared { name: "hwcomposer.drm_minigbm", defaults: ["hwcomposer.drm_defaults"], - whole_static_libs: ["drm_hwcomposer"], - srcs: ["bufferinfo/legacy/BufferInfoMinigbm.cpp"], - include_dirs: ["external/minigbm/cros_gralloc"], + srcs: [ + ":drm_hwcomposer_common", + "bufferinfo/legacy/BufferInfoMinigbm.cpp", + ], } // Used by hwcomposer.drm_imagination diff --git a/DrmHwcTwo.cpp b/DrmHwcTwo.cpp deleted file mode 100644 index 93b6fa7..0000000 --- a/DrmHwcTwo.cpp +++ /dev/null @@ -1,1434 +0,0 @@ -/* - * Copyright (C) 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define ATRACE_TAG ATRACE_TAG_GRAPHICS -#define LOG_TAG "hwc-drm-two" - -#include "DrmHwcTwo.h" - -#include <cutils/properties.h> -#include <hardware/hardware.h> -#include <hardware/hwcomposer2.h> -#include <inttypes.h> -#include <log/log.h> - -#include <string> - -#include "backend/BackendManager.h" -#include "bufferinfo/BufferInfoGetter.h" -#include "compositor/DrmDisplayComposition.h" - -namespace android { - -DrmHwcTwo::DrmHwcTwo() { - common.tag = HARDWARE_DEVICE_TAG; - common.version = HWC_DEVICE_API_VERSION_2_0; - common.close = HookDevClose; - getCapabilities = HookDevGetCapabilities; - getFunction = HookDevGetFunction; -} - -HWC2::Error DrmHwcTwo::CreateDisplay(hwc2_display_t displ, - HWC2::DisplayType type) { - DrmDevice *drm = resource_manager_.GetDrmDevice(displ); - std::shared_ptr<Importer> importer = resource_manager_.GetImporter(displ); - if (!drm || !importer) { - ALOGE("Failed to get a valid drmresource and importer"); - return HWC2::Error::NoResources; - } - displays_.emplace(std::piecewise_construct, std::forward_as_tuple(displ), - std::forward_as_tuple(&resource_manager_, drm, importer, - displ, type)); - - DrmCrtc *crtc = drm->GetCrtcForDisplay(static_cast<int>(displ)); - if (!crtc) { - ALOGE("Failed to get crtc for display %d", static_cast<int>(displ)); - return HWC2::Error::BadDisplay; - } - std::vector<DrmPlane *> display_planes; - for (auto &plane : drm->planes()) { - if (plane->GetCrtcSupported(*crtc)) - display_planes.push_back(plane.get()); - } - displays_.at(displ).Init(&display_planes); - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::Init() { - int rv = resource_manager_.Init(); - if (rv) { - ALOGE("Can't initialize the resource manager %d", rv); - return HWC2::Error::NoResources; - } - - HWC2::Error ret = HWC2::Error::None; - for (int i = 0; i < resource_manager_.getDisplayCount(); i++) { - ret = CreateDisplay(i, HWC2::DisplayType::Physical); - if (ret != HWC2::Error::None) { - ALOGE("Failed to create display %d with error %d", i, ret); - return ret; - } - } - - auto &drmDevices = resource_manager_.getDrmDevices(); - for (auto &device : drmDevices) { - device->RegisterHotplugHandler(new DrmHotplugHandler(this, device.get())); - } - return ret; -} - -template <typename... Args> -static inline HWC2::Error unsupported(char const *func, Args... /*args*/) { - ALOGV("Unsupported function: %s", func); - return HWC2::Error::Unsupported; -} - -static inline void supported(char const *func) { - ALOGV("Supported function: %s", func); -} - -HWC2::Error DrmHwcTwo::CreateVirtualDisplay(uint32_t width, uint32_t height, - int32_t *format, - hwc2_display_t *display) { - // TODO: Implement virtual display - return unsupported(__func__, width, height, format, display); -} - -HWC2::Error DrmHwcTwo::DestroyVirtualDisplay(hwc2_display_t display) { - // TODO: Implement virtual display - return unsupported(__func__, display); -} - -std::string DrmHwcTwo::HwcDisplay::DumpDelta( - DrmHwcTwo::HwcDisplay::Stats delta) { - if (delta.total_pixops_ == 0) - return "No stats yet"; - double Ratio = 1.0 - double(delta.gpu_pixops_) / double(delta.total_pixops_); - - return (std::stringstream() - << " Total frames count: " << delta.total_frames_ << "\n" - << " Failed to test commit frames: " << delta.failed_kms_validate_ - << "\n" - << " Failed to commit frames: " << delta.failed_kms_present_ << "\n" - << ((delta.failed_kms_present_ > 0) - ? " !!! Internal failure, FIX it please\n" - : "") - << " Flattened frames: " << delta.frames_flattened_ << "\n" - << " Pixel operations (free units)" - << " : [TOTAL: " << delta.total_pixops_ - << " / GPU: " << delta.gpu_pixops_ << "]\n" - << " Composition efficiency: " << Ratio) - .str(); -} - -std::string DrmHwcTwo::HwcDisplay::Dump() { - auto out = (std::stringstream() - << "- Display on: " << connector_->name() << "\n" - << " Flattening state: " << compositor_.GetFlatteningState() - << "\n" - << "Statistics since system boot:\n" - << DumpDelta(total_stats_) << "\n\n" - << "Statistics since last dumpsys request:\n" - << DumpDelta(total_stats_.minus(prev_stats_)) << "\n\n") - .str(); - - memcpy(&prev_stats_, &total_stats_, sizeof(Stats)); - return out; -} - -void DrmHwcTwo::Dump(uint32_t *outSize, char *outBuffer) { - supported(__func__); - - if (outBuffer != nullptr) { - auto copiedBytes = mDumpString.copy(outBuffer, *outSize); - *outSize = static_cast<uint32_t>(copiedBytes); - return; - } - - std::stringstream output; - - output << "-- drm_hwcomposer --\n\n"; - - for (std::pair<const hwc2_display_t, DrmHwcTwo::HwcDisplay> &dp : displays_) - output << dp.second.Dump(); - - mDumpString = output.str(); - *outSize = static_cast<uint32_t>(mDumpString.size()); -} - -uint32_t DrmHwcTwo::GetMaxVirtualDisplayCount() { - // TODO: Implement virtual display - unsupported(__func__); - return 0; -} - -HWC2::Error DrmHwcTwo::RegisterCallback(int32_t descriptor, - hwc2_callback_data_t data, - hwc2_function_pointer_t function) { - supported(__func__); - - switch (static_cast<HWC2::Callback>(descriptor)) { - case HWC2::Callback::Hotplug: { - SetHotplugCallback(data, function); - auto &drmDevices = resource_manager_.getDrmDevices(); - for (auto &device : drmDevices) - HandleInitialHotplugState(device.get()); - break; - } - case HWC2::Callback::Refresh: { - for (std::pair<const hwc2_display_t, DrmHwcTwo::HwcDisplay> &d : - displays_) - d.second.RegisterRefreshCallback(data, function); - break; - } - case HWC2::Callback::Vsync: { - for (std::pair<const hwc2_display_t, DrmHwcTwo::HwcDisplay> &d : - displays_) - d.second.RegisterVsyncCallback(data, function); - break; - } - default: - break; - } - return HWC2::Error::None; -} - -DrmHwcTwo::HwcDisplay::HwcDisplay(ResourceManager *resource_manager, - DrmDevice *drm, - std::shared_ptr<Importer> importer, - hwc2_display_t handle, HWC2::DisplayType type) - : resource_manager_(resource_manager), - drm_(drm), - importer_(importer), - handle_(handle), - type_(type), - color_transform_hint_(HAL_COLOR_TRANSFORM_IDENTITY) { - supported(__func__); - - // clang-format off - color_transform_matrix_ = {1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0}; - // clang-format on -} - -void DrmHwcTwo::HwcDisplay::ClearDisplay() { - compositor_.ClearDisplay(); -} - -HWC2::Error DrmHwcTwo::HwcDisplay::Init(std::vector<DrmPlane *> *planes) { - supported(__func__); - planner_ = Planner::CreateInstance(drm_); - if (!planner_) { - ALOGE("Failed to create planner instance for composition"); - return HWC2::Error::NoResources; - } - - int display = static_cast<int>(handle_); - int ret = compositor_.Init(resource_manager_, display); - if (ret) { - ALOGE("Failed display compositor init for display %d (%d)", display, ret); - return HWC2::Error::NoResources; - } - - // Split up the given display planes into primary and overlay to properly - // interface with the composition - char use_overlay_planes_prop[PROPERTY_VALUE_MAX]; - property_get("vendor.hwc.drm.use_overlay_planes", use_overlay_planes_prop, - "1"); - bool use_overlay_planes = atoi(use_overlay_planes_prop); - for (auto &plane : *planes) { - if (plane->type() == DRM_PLANE_TYPE_PRIMARY) - primary_planes_.push_back(plane); - else if (use_overlay_planes && (plane)->type() == DRM_PLANE_TYPE_OVERLAY) - overlay_planes_.push_back(plane); - } - - crtc_ = drm_->GetCrtcForDisplay(display); - if (!crtc_) { - ALOGE("Failed to get crtc for display %d", display); - return HWC2::Error::BadDisplay; - } - - connector_ = drm_->GetConnectorForDisplay(display); - if (!connector_) { - ALOGE("Failed to get connector for display %d", display); - return HWC2::Error::BadDisplay; - } - - ret = vsync_worker_.Init(drm_, display); - if (ret) { - ALOGE("Failed to create event worker for d=%d %d\n", display, ret); - return HWC2::Error::BadDisplay; - } - - ret = BackendManager::GetInstance().SetBackendForDisplay(this); - if (ret) { - ALOGE("Failed to set backend for d=%d %d\n", display, ret); - return HWC2::Error::BadDisplay; - } - - return ChosePreferredConfig(); -} - -HWC2::Error DrmHwcTwo::HwcDisplay::ChosePreferredConfig() { - // Fetch the number of modes from the display - uint32_t num_configs; - HWC2::Error err = GetDisplayConfigs(&num_configs, NULL); - if (err != HWC2::Error::None || !num_configs) - return err; - - return SetActiveConfig(connector_->get_preferred_mode_id()); -} - -void DrmHwcTwo::HwcDisplay::RegisterVsyncCallback( - hwc2_callback_data_t data, hwc2_function_pointer_t func) { - supported(__func__); - vsync_worker_.RegisterClientCallback(data, func); -} - -void DrmHwcTwo::HwcDisplay::RegisterRefreshCallback( - hwc2_callback_data_t data, hwc2_function_pointer_t func) { - supported(__func__); - compositor_.SetRefreshCallback(data, func); -} - -HWC2::Error DrmHwcTwo::HwcDisplay::AcceptDisplayChanges() { - supported(__func__); - for (std::pair<const hwc2_layer_t, DrmHwcTwo::HwcLayer> &l : layers_) - l.second.accept_type_change(); - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::CreateLayer(hwc2_layer_t *layer) { - supported(__func__); - layers_.emplace(static_cast<hwc2_layer_t>(layer_idx_), HwcLayer()); - *layer = static_cast<hwc2_layer_t>(layer_idx_); - ++layer_idx_; - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::DestroyLayer(hwc2_layer_t layer) { - supported(__func__); - if (!get_layer(layer)) - return HWC2::Error::BadLayer; - - layers_.erase(layer); - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::GetActiveConfig(hwc2_config_t *config) { - supported(__func__); - DrmMode const &mode = connector_->active_mode(); - if (mode.id() == 0) - return HWC2::Error::BadConfig; - - *config = mode.id(); - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::GetChangedCompositionTypes( - uint32_t *num_elements, hwc2_layer_t *layers, int32_t *types) { - supported(__func__); - uint32_t num_changes = 0; - for (std::pair<const hwc2_layer_t, DrmHwcTwo::HwcLayer> &l : layers_) { - if (l.second.type_changed()) { - if (layers && num_changes < *num_elements) - layers[num_changes] = l.first; - if (types && num_changes < *num_elements) - types[num_changes] = static_cast<int32_t>(l.second.validated_type()); - ++num_changes; - } - } - if (!layers && !types) - *num_elements = num_changes; - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::GetClientTargetSupport(uint32_t width, - uint32_t height, - int32_t /*format*/, - int32_t dataspace) { - supported(__func__); - std::pair<uint32_t, uint32_t> min = drm_->min_resolution(); - std::pair<uint32_t, uint32_t> max = drm_->max_resolution(); - - if (width < min.first || height < min.second) - return HWC2::Error::Unsupported; - - if (width > max.first || height > max.second) - return HWC2::Error::Unsupported; - - if (dataspace != HAL_DATASPACE_UNKNOWN && - dataspace != HAL_DATASPACE_STANDARD_UNSPECIFIED) - return HWC2::Error::Unsupported; - - // TODO: Validate format can be handled by either GL or planes - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::GetColorModes(uint32_t *num_modes, - int32_t *modes) { - supported(__func__); - if (!modes) - *num_modes = 1; - - if (modes) - *modes = HAL_COLOR_MODE_NATIVE; - - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayAttribute(hwc2_config_t config, - int32_t attribute_in, - int32_t *value) { - supported(__func__); - auto mode = std::find_if(connector_->modes().begin(), - connector_->modes().end(), - [config](DrmMode const &m) { - return m.id() == config; - }); - if (mode == connector_->modes().end()) { - ALOGE("Could not find active mode for %d", config); - return HWC2::Error::BadConfig; - } - - static const int32_t kUmPerInch = 25400; - uint32_t mm_width = connector_->mm_width(); - uint32_t mm_height = connector_->mm_height(); - auto attribute = static_cast<HWC2::Attribute>(attribute_in); - switch (attribute) { - case HWC2::Attribute::Width: - *value = mode->h_display(); - break; - case HWC2::Attribute::Height: - *value = mode->v_display(); - break; - case HWC2::Attribute::VsyncPeriod: - // in nanoseconds - *value = 1000 * 1000 * 1000 / mode->v_refresh(); - break; - case HWC2::Attribute::DpiX: - // Dots per 1000 inches - *value = mm_width ? (mode->h_display() * kUmPerInch) / mm_width : -1; - break; - case HWC2::Attribute::DpiY: - // Dots per 1000 inches - *value = mm_height ? (mode->v_display() * kUmPerInch) / mm_height : -1; - break; - default: - *value = -1; - return HWC2::Error::BadConfig; - } - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayConfigs(uint32_t *num_configs, - hwc2_config_t *configs) { - supported(__func__); - // Since this callback is normally invoked twice (once to get the count, and - // once to populate configs), we don't really want to read the edid - // redundantly. Instead, only update the modes on the first invocation. While - // it's possible this will result in stale modes, it'll all come out in the - // wash when we try to set the active config later. - if (!configs) { - int ret = connector_->UpdateModes(); - if (ret) { - ALOGE("Failed to update display modes %d", ret); - return HWC2::Error::BadDisplay; - } - } - - // Since the upper layers only look at vactive/hactive/refresh, height and - // width, it doesn't differentiate interlaced from progressive and other - // similar modes. Depending on the order of modes we return to SF, it could - // end up choosing a suboptimal configuration and dropping the preferred - // mode. To workaround this, don't offer interlaced modes to SF if there is - // at least one non-interlaced alternative and only offer a single WxH@R - // mode with at least the prefered mode from in DrmConnector::UpdateModes() - - // TODO: Remove the following block of code until AOSP handles all modes - std::vector<DrmMode> sel_modes; - - // Add the preferred mode first to be sure it's not dropped - auto mode = std::find_if(connector_->modes().begin(), - connector_->modes().end(), [&](DrmMode const &m) { - return m.id() == - connector_->get_preferred_mode_id(); - }); - if (mode != connector_->modes().end()) - sel_modes.push_back(*mode); - - // Add the active mode if different from preferred mode - if (connector_->active_mode().id() != connector_->get_preferred_mode_id()) - sel_modes.push_back(connector_->active_mode()); - - // Cycle over the modes and filter out "similar" modes, keeping only the - // first ones in the order given by DRM (from CEA ids and timings order) - for (const DrmMode &mode : connector_->modes()) { - // TODO: Remove this when 3D Attributes are in AOSP - if (mode.flags() & DRM_MODE_FLAG_3D_MASK) - continue; - - // TODO: Remove this when the Interlaced attribute is in AOSP - if (mode.flags() & DRM_MODE_FLAG_INTERLACE) { - auto m = std::find_if(connector_->modes().begin(), - connector_->modes().end(), - [&mode](DrmMode const &m) { - return !(m.flags() & DRM_MODE_FLAG_INTERLACE) && - m.h_display() == mode.h_display() && - m.v_display() == mode.v_display(); - }); - if (m == connector_->modes().end()) - sel_modes.push_back(mode); - - continue; - } - - // Search for a similar WxH@R mode in the filtered list and drop it if - // another mode with the same WxH@R has already been selected - // TODO: Remove this when AOSP handles duplicates modes - auto m = std::find_if(sel_modes.begin(), sel_modes.end(), - [&mode](DrmMode const &m) { - return m.h_display() == mode.h_display() && - m.v_display() == mode.v_display() && - m.v_refresh() == mode.v_refresh(); - }); - if (m == sel_modes.end()) - sel_modes.push_back(mode); - } - - auto num_modes = static_cast<uint32_t>(sel_modes.size()); - if (!configs) { - *num_configs = num_modes; - return HWC2::Error::None; - } - - uint32_t idx = 0; - for (const DrmMode &mode : sel_modes) { - if (idx >= *num_configs) - break; - configs[idx++] = mode.id(); - } - *num_configs = idx; - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayName(uint32_t *size, char *name) { - supported(__func__); - std::ostringstream stream; - stream << "display-" << connector_->id(); - std::string string = stream.str(); - size_t length = string.length(); - if (!name) { - *size = length; - return HWC2::Error::None; - } - - *size = std::min<uint32_t>(static_cast<uint32_t>(length - 1), *size); - strncpy(name, string.c_str(), *size); - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayRequests(int32_t *display_requests, - uint32_t *num_elements, - hwc2_layer_t *layers, - int32_t *layer_requests) { - supported(__func__); - // TODO: I think virtual display should request - // HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT here - unsupported(__func__, display_requests, num_elements, layers, layer_requests); - *num_elements = 0; - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayType(int32_t *type) { - supported(__func__); - *type = static_cast<int32_t>(type_); - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::GetDozeSupport(int32_t *support) { - supported(__func__); - *support = 0; - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::GetHdrCapabilities( - uint32_t *num_types, int32_t * /*types*/, float * /*max_luminance*/, - float * /*max_average_luminance*/, float * /*min_luminance*/) { - supported(__func__); - *num_types = 0; - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::GetReleaseFences(uint32_t *num_elements, - hwc2_layer_t *layers, - int32_t *fences) { - supported(__func__); - uint32_t num_layers = 0; - - for (std::pair<const hwc2_layer_t, DrmHwcTwo::HwcLayer> &l : layers_) { - ++num_layers; - if (layers == NULL || fences == NULL) { - continue; - } else if (num_layers > *num_elements) { - ALOGW("Overflow num_elements %d/%d", num_layers, *num_elements); - return HWC2::Error::None; - } - - layers[num_layers - 1] = l.first; - fences[num_layers - 1] = l.second.take_release_fence(); - } - *num_elements = num_layers; - return HWC2::Error::None; -} - -void DrmHwcTwo::HwcDisplay::AddFenceToPresentFence(int fd) { - if (fd < 0) - return; - - if (present_fence_.get() >= 0) { - int old_fence = present_fence_.get(); - present_fence_.Set(sync_merge("dc_present", old_fence, fd)); - close(fd); - } else { - present_fence_.Set(fd); - } -} - -bool DrmHwcTwo::HwcDisplay::HardwareSupportsLayerType( - HWC2::Composition comp_type) { - return comp_type == HWC2::Composition::Device || - comp_type == HWC2::Composition::Cursor; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::CreateComposition(bool test) { - std::vector<DrmCompositionDisplayLayersMap> layers_map; - layers_map.emplace_back(); - DrmCompositionDisplayLayersMap &map = layers_map.back(); - - map.display = static_cast<int>(handle_); - map.geometry_changed = true; // TODO: Fix this - - // order the layers by z-order - bool use_client_layer = false; - uint32_t client_z_order = UINT32_MAX; - std::map<uint32_t, DrmHwcTwo::HwcLayer *> z_map; - for (std::pair<const hwc2_layer_t, DrmHwcTwo::HwcLayer> &l : layers_) { - switch (l.second.validated_type()) { - case HWC2::Composition::Device: - z_map.emplace(std::make_pair(l.second.z_order(), &l.second)); - break; - case HWC2::Composition::Client: - // Place it at the z_order of the lowest client layer - use_client_layer = true; - client_z_order = std::min(client_z_order, l.second.z_order()); - break; - default: - continue; - } - } - if (use_client_layer) - z_map.emplace(std::make_pair(client_z_order, &client_layer_)); - - if (z_map.empty()) - return HWC2::Error::BadLayer; - - // now that they're ordered by z, add them to the composition - for (std::pair<const uint32_t, DrmHwcTwo::HwcLayer *> &l : z_map) { - DrmHwcLayer layer; - l.second->PopulateDrmLayer(&layer); - int ret = layer.ImportBuffer(importer_.get()); - if (ret) { - ALOGE("Failed to import layer, ret=%d", ret); - return HWC2::Error::NoResources; - } - map.layers.emplace_back(std::move(layer)); - } - - std::unique_ptr<DrmDisplayComposition> composition = compositor_ - .CreateComposition(); - composition->Init(drm_, crtc_, importer_.get(), planner_.get(), frame_no_); - - // TODO: Don't always assume geometry changed - int ret = composition->SetLayers(map.layers.data(), map.layers.size(), true); - if (ret) { - ALOGE("Failed to set layers in the composition ret=%d", ret); - return HWC2::Error::BadLayer; - } - - std::vector<DrmPlane *> primary_planes(primary_planes_); - std::vector<DrmPlane *> overlay_planes(overlay_planes_); - ret = composition->Plan(&primary_planes, &overlay_planes); - if (ret) { - ALOGE("Failed to plan the composition ret=%d", ret); - return HWC2::Error::BadConfig; - } - - // Disable the planes we're not using - for (auto i = primary_planes.begin(); i != primary_planes.end();) { - composition->AddPlaneDisable(*i); - i = primary_planes.erase(i); - } - for (auto i = overlay_planes.begin(); i != overlay_planes.end();) { - composition->AddPlaneDisable(*i); - i = overlay_planes.erase(i); - } - - if (test) { - ret = compositor_.TestComposition(composition.get()); - } else { - ret = compositor_.ApplyComposition(std::move(composition)); - AddFenceToPresentFence(compositor_.TakeOutFence()); - } - if (ret) { - if (!test) - ALOGE("Failed to apply the frame composition ret=%d", ret); - return HWC2::Error::BadParameter; - } - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::PresentDisplay(int32_t *present_fence) { - supported(__func__); - HWC2::Error ret; - - ++total_stats_.total_frames_; - - ret = CreateComposition(false); - if (ret != HWC2::Error::None) - ++total_stats_.failed_kms_present_; - - if (ret == HWC2::Error::BadLayer) { - // Can we really have no client or device layers? - *present_fence = -1; - return HWC2::Error::None; - } - if (ret != HWC2::Error::None) - return ret; - - *present_fence = present_fence_.Release(); - - ++frame_no_; - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::SetActiveConfig(hwc2_config_t config) { - supported(__func__); - auto mode = std::find_if(connector_->modes().begin(), - connector_->modes().end(), - [config](DrmMode const &m) { - return m.id() == config; - }); - if (mode == connector_->modes().end()) { - ALOGE("Could not find active mode for %d", config); - return HWC2::Error::BadConfig; - } - - std::unique_ptr<DrmDisplayComposition> composition = compositor_ - .CreateComposition(); - composition->Init(drm_, crtc_, importer_.get(), planner_.get(), frame_no_); - int ret = composition->SetDisplayMode(*mode); - ret = compositor_.ApplyComposition(std::move(composition)); - if (ret) { - ALOGE("Failed to queue dpms composition on %d", ret); - return HWC2::Error::BadConfig; - } - - connector_->set_active_mode(*mode); - - // Setup the client layer's dimensions - hwc_rect_t display_frame = {.left = 0, - .top = 0, - .right = static_cast<int>(mode->h_display()), - .bottom = static_cast<int>(mode->v_display())}; - client_layer_.SetLayerDisplayFrame(display_frame); - - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::SetClientTarget(buffer_handle_t target, - int32_t acquire_fence, - int32_t dataspace, - hwc_region_t /*damage*/) { - supported(__func__); - UniqueFd uf(acquire_fence); - - client_layer_.set_buffer(target); - client_layer_.set_acquire_fence(uf.get()); - client_layer_.SetLayerDataspace(dataspace); - - /* TODO: Do not update source_crop every call. - * It makes sense to do it once after every hotplug event. */ - hwc_drm_bo bo{}; - BufferInfoGetter::GetInstance()->ConvertBoInfo(target, &bo); - - hwc_frect_t source_crop = {.left = 0.0f, - .top = 0.0f, - .right = bo.width + 0.0f, - .bottom = bo.height + 0.0f}; - client_layer_.SetLayerSourceCrop(source_crop); - - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::SetColorMode(int32_t mode) { - supported(__func__); - - if (mode < HAL_COLOR_MODE_NATIVE || mode > HAL_COLOR_MODE_BT2100_HLG) - return HWC2::Error::BadParameter; - - if (mode != HAL_COLOR_MODE_NATIVE) - return HWC2::Error::Unsupported; - - color_mode_ = mode; - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::SetColorTransform(const float *matrix, - int32_t hint) { - supported(__func__); - if (hint < HAL_COLOR_TRANSFORM_IDENTITY || - hint > HAL_COLOR_TRANSFORM_CORRECT_TRITANOPIA) - return HWC2::Error::BadParameter; - - if (!matrix && hint == HAL_COLOR_TRANSFORM_ARBITRARY_MATRIX) - return HWC2::Error::BadParameter; - - color_transform_hint_ = static_cast<android_color_transform_t>(hint); - if (color_transform_hint_ == HAL_COLOR_TRANSFORM_ARBITRARY_MATRIX) - std::copy(matrix, matrix + MATRIX_SIZE, color_transform_matrix_.begin()); - - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::SetOutputBuffer(buffer_handle_t buffer, - int32_t release_fence) { - supported(__func__); - // TODO: Need virtual display support - return unsupported(__func__, buffer, release_fence); -} - -HWC2::Error DrmHwcTwo::HwcDisplay::SetPowerMode(int32_t mode_in) { - supported(__func__); - uint64_t dpms_value = 0; - auto mode = static_cast<HWC2::PowerMode>(mode_in); - switch (mode) { - case HWC2::PowerMode::Off: - dpms_value = DRM_MODE_DPMS_OFF; - break; - case HWC2::PowerMode::On: - dpms_value = DRM_MODE_DPMS_ON; - break; - case HWC2::PowerMode::Doze: - case HWC2::PowerMode::DozeSuspend: - return HWC2::Error::Unsupported; - default: - ALOGI("Power mode %d is unsupported\n", mode); - return HWC2::Error::BadParameter; - }; - - std::unique_ptr<DrmDisplayComposition> composition = compositor_ - .CreateComposition(); - composition->Init(drm_, crtc_, importer_.get(), planner_.get(), frame_no_); - composition->SetDpmsMode(dpms_value); - int ret = compositor_.ApplyComposition(std::move(composition)); - if (ret) { - ALOGE("Failed to apply the dpms composition ret=%d", ret); - return HWC2::Error::BadParameter; - } - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::SetVsyncEnabled(int32_t enabled) { - supported(__func__); - vsync_worker_.VSyncControl(HWC2_VSYNC_ENABLE == enabled); - return HWC2::Error::None; -} - -uint32_t DrmHwcTwo::HwcDisplay::CalcPixOps( - std::map<uint32_t, DrmHwcTwo::HwcLayer *> &z_map, size_t first_z, - size_t size) { - uint32_t pixops = 0; - for (std::pair<const uint32_t, DrmHwcTwo::HwcLayer *> &l : z_map) { - if (l.first >= first_z && l.first < first_z + size) { - hwc_rect_t df = l.second->display_frame(); - pixops += (df.right - df.left) * (df.bottom - df.top); - } - } - return pixops; -} - -void DrmHwcTwo::HwcDisplay::MarkValidated( - std::map<uint32_t, DrmHwcTwo::HwcLayer *> &z_map, size_t client_first_z, - size_t client_size) { - for (std::pair<const uint32_t, DrmHwcTwo::HwcLayer *> &l : z_map) { - if (l.first >= client_first_z && l.first < client_first_z + client_size) - l.second->set_validated_type(HWC2::Composition::Client); - else - l.second->set_validated_type(HWC2::Composition::Device); - } -} - -HWC2::Error DrmHwcTwo::HwcDisplay::ValidateDisplay(uint32_t *num_types, - uint32_t *num_requests) { - supported(__func__); - - return backend_->ValidateDisplay(this, num_types, num_requests); -} - -#if PLATFORM_SDK_VERSION > 28 -HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayIdentificationData( - uint8_t *outPort, uint32_t *outDataSize, uint8_t *outData) { - supported(__func__); - - drmModePropertyBlobPtr blob; - - if (connector_->GetEdidBlob(blob)) { - ALOGE("Failed to get edid property value."); - return HWC2::Error::Unsupported; - } - - if (outData) { - *outDataSize = std::min(*outDataSize, blob->length); - memcpy(outData, blob->data, *outDataSize); - } else { - *outDataSize = blob->length; - } - *outPort = connector_->id(); - - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayCapabilities( - uint32_t *outNumCapabilities, uint32_t *outCapabilities) { - unsupported(__func__, outCapabilities); - - if (outNumCapabilities == NULL) { - return HWC2::Error::BadParameter; - } - - *outNumCapabilities = 0; - - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayBrightnessSupport( - bool *supported) { - *supported = false; - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::SetDisplayBrightness( - float /* brightness */) { - return HWC2::Error::Unsupported; -} - -#endif /* PLATFORM_SDK_VERSION > 28 */ - -#if PLATFORM_SDK_VERSION > 27 - -HWC2::Error DrmHwcTwo::HwcDisplay::GetRenderIntents( - int32_t mode, uint32_t *outNumIntents, - int32_t * /*android_render_intent_v1_1_t*/ outIntents) { - if (mode != HAL_COLOR_MODE_NATIVE) { - return HWC2::Error::BadParameter; - } - - if (outIntents == nullptr) { - *outNumIntents = 1; - return HWC2::Error::None; - } - *outNumIntents = 1; - outIntents[0] = HAL_RENDER_INTENT_COLORIMETRIC; - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcDisplay::SetColorModeWithIntent(int32_t mode, - int32_t intent) { - if (intent < HAL_RENDER_INTENT_COLORIMETRIC || - intent > HAL_RENDER_INTENT_TONE_MAP_ENHANCE) - return HWC2::Error::BadParameter; - - if (mode < HAL_COLOR_MODE_NATIVE || mode > HAL_COLOR_MODE_BT2100_HLG) - return HWC2::Error::BadParameter; - - if (mode != HAL_COLOR_MODE_NATIVE) - return HWC2::Error::Unsupported; - - if (intent != HAL_RENDER_INTENT_COLORIMETRIC) - return HWC2::Error::Unsupported; - - color_mode_ = mode; - return HWC2::Error::None; -} - -#endif /* PLATFORM_SDK_VERSION > 27 */ - -HWC2::Error DrmHwcTwo::HwcLayer::SetCursorPosition(int32_t x, int32_t y) { - supported(__func__); - cursor_x_ = x; - cursor_y_ = y; - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcLayer::SetLayerBlendMode(int32_t mode) { - supported(__func__); - blending_ = static_cast<HWC2::BlendMode>(mode); - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcLayer::SetLayerBuffer(buffer_handle_t buffer, - int32_t acquire_fence) { - supported(__func__); - UniqueFd uf(acquire_fence); - - set_buffer(buffer); - set_acquire_fence(uf.get()); - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcLayer::SetLayerColor(hwc_color_t color) { - // TODO: Put to client composition here? - supported(__func__); - layer_color_ = color; - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcLayer::SetLayerCompositionType(int32_t type) { - sf_type_ = static_cast<HWC2::Composition>(type); - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcLayer::SetLayerDataspace(int32_t dataspace) { - supported(__func__); - dataspace_ = static_cast<android_dataspace_t>(dataspace); - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcLayer::SetLayerDisplayFrame(hwc_rect_t frame) { - supported(__func__); - display_frame_ = frame; - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcLayer::SetLayerPlaneAlpha(float alpha) { - supported(__func__); - alpha_ = alpha; - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcLayer::SetLayerSidebandStream( - const native_handle_t *stream) { - supported(__func__); - // TODO: We don't support sideband - return unsupported(__func__, stream); -} - -HWC2::Error DrmHwcTwo::HwcLayer::SetLayerSourceCrop(hwc_frect_t crop) { - supported(__func__); - source_crop_ = crop; - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcLayer::SetLayerSurfaceDamage(hwc_region_t damage) { - supported(__func__); - // TODO: We don't use surface damage, marking as unsupported - unsupported(__func__, damage); - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcLayer::SetLayerTransform(int32_t transform) { - supported(__func__); - transform_ = static_cast<HWC2::Transform>(transform); - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcLayer::SetLayerVisibleRegion(hwc_region_t visible) { - supported(__func__); - // TODO: We don't use this information, marking as unsupported - unsupported(__func__, visible); - return HWC2::Error::None; -} - -HWC2::Error DrmHwcTwo::HwcLayer::SetLayerZOrder(uint32_t order) { - supported(__func__); - z_order_ = order; - return HWC2::Error::None; -} - -void DrmHwcTwo::HwcLayer::PopulateDrmLayer(DrmHwcLayer *layer) { - supported(__func__); - switch (blending_) { - case HWC2::BlendMode::None: - layer->blending = DrmHwcBlending::kNone; - break; - case HWC2::BlendMode::Premultiplied: - layer->blending = DrmHwcBlending::kPreMult; - break; - case HWC2::BlendMode::Coverage: - layer->blending = DrmHwcBlending::kCoverage; - break; - default: - ALOGE("Unknown blending mode b=%d", blending_); - layer->blending = DrmHwcBlending::kNone; - break; - } - - OutputFd release_fence = release_fence_output(); - - layer->sf_handle = buffer_; - layer->acquire_fence = acquire_fence_.Release(); - layer->release_fence = std::move(release_fence); - layer->SetDisplayFrame(display_frame_); - layer->alpha = static_cast<uint16_t>(65535.0f * alpha_ + 0.5f); - layer->SetSourceCrop(source_crop_); - layer->SetTransform(static_cast<int32_t>(transform_)); -} - -void DrmHwcTwo::HandleDisplayHotplug(hwc2_display_t displayid, int state) { - const std::lock_guard<std::mutex> lock(hotplug_callback_lock); - - if (hotplug_callback_hook_ && hotplug_callback_data_) - hotplug_callback_hook_(hotplug_callback_data_, displayid, - state == DRM_MODE_CONNECTED - ? HWC2_CONNECTION_CONNECTED - : HWC2_CONNECTION_DISCONNECTED); -} - -void DrmHwcTwo::HandleInitialHotplugState(DrmDevice *drmDevice) { - for (auto &conn : drmDevice->connectors()) { - if (conn->state() != DRM_MODE_CONNECTED) - continue; - HandleDisplayHotplug(conn->display(), conn->state()); - } -} - -void DrmHwcTwo::DrmHotplugHandler::HandleEvent(uint64_t timestamp_us) { - for (auto &conn : drm_->connectors()) { - drmModeConnection old_state = conn->state(); - drmModeConnection cur_state = conn->UpdateModes() - ? DRM_MODE_UNKNOWNCONNECTION - : conn->state(); - - if (cur_state == old_state) - continue; - - ALOGI("%s event @%" PRIu64 " for connector %u on display %d", - cur_state == DRM_MODE_CONNECTED ? "Plug" : "Unplug", timestamp_us, - conn->id(), conn->display()); - - int display_id = conn->display(); - if (cur_state == DRM_MODE_CONNECTED) { - auto &display = hwc2_->displays_.at(display_id); - display.ChosePreferredConfig(); - } else { - auto &display = hwc2_->displays_.at(display_id); - display.ClearDisplay(); - } - - hwc2_->HandleDisplayHotplug(display_id, cur_state); - } -} - -// static -int DrmHwcTwo::HookDevClose(hw_device_t * /*dev*/) { - unsupported(__func__); - return 0; -} - -// static -void DrmHwcTwo::HookDevGetCapabilities(hwc2_device_t * /*dev*/, - uint32_t *out_count, - int32_t * /*out_capabilities*/) { - supported(__func__); - *out_count = 0; -} - -// static -hwc2_function_pointer_t DrmHwcTwo::HookDevGetFunction( - struct hwc2_device * /*dev*/, int32_t descriptor) { - supported(__func__); - auto func = static_cast<HWC2::FunctionDescriptor>(descriptor); - switch (func) { - // Device functions - case HWC2::FunctionDescriptor::CreateVirtualDisplay: - return ToHook<HWC2_PFN_CREATE_VIRTUAL_DISPLAY>( - DeviceHook<int32_t, decltype(&DrmHwcTwo::CreateVirtualDisplay), - &DrmHwcTwo::CreateVirtualDisplay, uint32_t, uint32_t, - int32_t *, hwc2_display_t *>); - case HWC2::FunctionDescriptor::DestroyVirtualDisplay: - return ToHook<HWC2_PFN_DESTROY_VIRTUAL_DISPLAY>( - DeviceHook<int32_t, decltype(&DrmHwcTwo::DestroyVirtualDisplay), - &DrmHwcTwo::DestroyVirtualDisplay, hwc2_display_t>); - case HWC2::FunctionDescriptor::Dump: - return ToHook<HWC2_PFN_DUMP>( - DeviceHook<void, decltype(&DrmHwcTwo::Dump), &DrmHwcTwo::Dump, - uint32_t *, char *>); - case HWC2::FunctionDescriptor::GetMaxVirtualDisplayCount: - return ToHook<HWC2_PFN_GET_MAX_VIRTUAL_DISPLAY_COUNT>( - DeviceHook<uint32_t, decltype(&DrmHwcTwo::GetMaxVirtualDisplayCount), - &DrmHwcTwo::GetMaxVirtualDisplayCount>); - case HWC2::FunctionDescriptor::RegisterCallback: - return ToHook<HWC2_PFN_REGISTER_CALLBACK>( - DeviceHook<int32_t, decltype(&DrmHwcTwo::RegisterCallback), - &DrmHwcTwo::RegisterCallback, int32_t, - hwc2_callback_data_t, hwc2_function_pointer_t>); - - // Display functions - case HWC2::FunctionDescriptor::AcceptDisplayChanges: - return ToHook<HWC2_PFN_ACCEPT_DISPLAY_CHANGES>( - DisplayHook<decltype(&HwcDisplay::AcceptDisplayChanges), - &HwcDisplay::AcceptDisplayChanges>); - case HWC2::FunctionDescriptor::CreateLayer: - return ToHook<HWC2_PFN_CREATE_LAYER>( - DisplayHook<decltype(&HwcDisplay::CreateLayer), - &HwcDisplay::CreateLayer, hwc2_layer_t *>); - case HWC2::FunctionDescriptor::DestroyLayer: - return ToHook<HWC2_PFN_DESTROY_LAYER>( - DisplayHook<decltype(&HwcDisplay::DestroyLayer), - &HwcDisplay::DestroyLayer, hwc2_layer_t>); - case HWC2::FunctionDescriptor::GetActiveConfig: - return ToHook<HWC2_PFN_GET_ACTIVE_CONFIG>( - DisplayHook<decltype(&HwcDisplay::GetActiveConfig), - &HwcDisplay::GetActiveConfig, hwc2_config_t *>); - case HWC2::FunctionDescriptor::GetChangedCompositionTypes: - return ToHook<HWC2_PFN_GET_CHANGED_COMPOSITION_TYPES>( - DisplayHook<decltype(&HwcDisplay::GetChangedCompositionTypes), - &HwcDisplay::GetChangedCompositionTypes, uint32_t *, - hwc2_layer_t *, int32_t *>); - case HWC2::FunctionDescriptor::GetClientTargetSupport: - return ToHook<HWC2_PFN_GET_CLIENT_TARGET_SUPPORT>( - DisplayHook<decltype(&HwcDisplay::GetClientTargetSupport), - &HwcDisplay::GetClientTargetSupport, uint32_t, uint32_t, - int32_t, int32_t>); - case HWC2::FunctionDescriptor::GetColorModes: - return ToHook<HWC2_PFN_GET_COLOR_MODES>( - DisplayHook<decltype(&HwcDisplay::GetColorModes), - &HwcDisplay::GetColorModes, uint32_t *, int32_t *>); - case HWC2::FunctionDescriptor::GetDisplayAttribute: - return ToHook<HWC2_PFN_GET_DISPLAY_ATTRIBUTE>( - DisplayHook<decltype(&HwcDisplay::GetDisplayAttribute), - &HwcDisplay::GetDisplayAttribute, hwc2_config_t, int32_t, - int32_t *>); - case HWC2::FunctionDescriptor::GetDisplayConfigs: - return ToHook<HWC2_PFN_GET_DISPLAY_CONFIGS>( - DisplayHook<decltype(&HwcDisplay::GetDisplayConfigs), - &HwcDisplay::GetDisplayConfigs, uint32_t *, - hwc2_config_t *>); - case HWC2::FunctionDescriptor::GetDisplayName: - return ToHook<HWC2_PFN_GET_DISPLAY_NAME>( - DisplayHook<decltype(&HwcDisplay::GetDisplayName), - &HwcDisplay::GetDisplayName, uint32_t *, char *>); - case HWC2::FunctionDescriptor::GetDisplayRequests: - return ToHook<HWC2_PFN_GET_DISPLAY_REQUESTS>( - DisplayHook<decltype(&HwcDisplay::GetDisplayRequests), - &HwcDisplay::GetDisplayRequests, int32_t *, uint32_t *, - hwc2_layer_t *, int32_t *>); - case HWC2::FunctionDescriptor::GetDisplayType: - return ToHook<HWC2_PFN_GET_DISPLAY_TYPE>( - DisplayHook<decltype(&HwcDisplay::GetDisplayType), - &HwcDisplay::GetDisplayType, int32_t *>); - case HWC2::FunctionDescriptor::GetDozeSupport: - return ToHook<HWC2_PFN_GET_DOZE_SUPPORT>( - DisplayHook<decltype(&HwcDisplay::GetDozeSupport), - &HwcDisplay::GetDozeSupport, int32_t *>); - case HWC2::FunctionDescriptor::GetHdrCapabilities: - return ToHook<HWC2_PFN_GET_HDR_CAPABILITIES>( - DisplayHook<decltype(&HwcDisplay::GetHdrCapabilities), - &HwcDisplay::GetHdrCapabilities, uint32_t *, int32_t *, - float *, float *, float *>); - case HWC2::FunctionDescriptor::GetReleaseFences: - return ToHook<HWC2_PFN_GET_RELEASE_FENCES>( - DisplayHook<decltype(&HwcDisplay::GetReleaseFences), - &HwcDisplay::GetReleaseFences, uint32_t *, hwc2_layer_t *, - int32_t *>); - case HWC2::FunctionDescriptor::PresentDisplay: - return ToHook<HWC2_PFN_PRESENT_DISPLAY>( - DisplayHook<decltype(&HwcDisplay::PresentDisplay), - &HwcDisplay::PresentDisplay, int32_t *>); - case HWC2::FunctionDescriptor::SetActiveConfig: - return ToHook<HWC2_PFN_SET_ACTIVE_CONFIG>( - DisplayHook<decltype(&HwcDisplay::SetActiveConfig), - &HwcDisplay::SetActiveConfig, hwc2_config_t>); - case HWC2::FunctionDescriptor::SetClientTarget: - return ToHook<HWC2_PFN_SET_CLIENT_TARGET>( - DisplayHook<decltype(&HwcDisplay::SetClientTarget), - &HwcDisplay::SetClientTarget, buffer_handle_t, int32_t, - int32_t, hwc_region_t>); - case HWC2::FunctionDescriptor::SetColorMode: - return ToHook<HWC2_PFN_SET_COLOR_MODE>( - DisplayHook<decltype(&HwcDisplay::SetColorMode), - &HwcDisplay::SetColorMode, int32_t>); - case HWC2::FunctionDescriptor::SetColorTransform: - return ToHook<HWC2_PFN_SET_COLOR_TRANSFORM>( - DisplayHook<decltype(&HwcDisplay::SetColorTransform), - &HwcDisplay::SetColorTransform, const float *, int32_t>); - case HWC2::FunctionDescriptor::SetOutputBuffer: - return ToHook<HWC2_PFN_SET_OUTPUT_BUFFER>( - DisplayHook<decltype(&HwcDisplay::SetOutputBuffer), - &HwcDisplay::SetOutputBuffer, buffer_handle_t, int32_t>); - case HWC2::FunctionDescriptor::SetPowerMode: - return ToHook<HWC2_PFN_SET_POWER_MODE>( - DisplayHook<decltype(&HwcDisplay::SetPowerMode), - &HwcDisplay::SetPowerMode, int32_t>); - case HWC2::FunctionDescriptor::SetVsyncEnabled: - return ToHook<HWC2_PFN_SET_VSYNC_ENABLED>( - DisplayHook<decltype(&HwcDisplay::SetVsyncEnabled), - &HwcDisplay::SetVsyncEnabled, int32_t>); - case HWC2::FunctionDescriptor::ValidateDisplay: - return ToHook<HWC2_PFN_VALIDATE_DISPLAY>( - DisplayHook<decltype(&HwcDisplay::ValidateDisplay), - &HwcDisplay::ValidateDisplay, uint32_t *, uint32_t *>); -#if PLATFORM_SDK_VERSION > 27 - case HWC2::FunctionDescriptor::GetRenderIntents: - return ToHook<HWC2_PFN_GET_RENDER_INTENTS>( - DisplayHook<decltype(&HwcDisplay::GetRenderIntents), - &HwcDisplay::GetRenderIntents, int32_t, uint32_t *, - int32_t *>); - case HWC2::FunctionDescriptor::SetColorModeWithRenderIntent: - return ToHook<HWC2_PFN_SET_COLOR_MODE_WITH_RENDER_INTENT>( - DisplayHook<decltype(&HwcDisplay::SetColorModeWithIntent), - &HwcDisplay::SetColorModeWithIntent, int32_t, int32_t>); -#endif -#if PLATFORM_SDK_VERSION > 28 - case HWC2::FunctionDescriptor::GetDisplayIdentificationData: - return ToHook<HWC2_PFN_GET_DISPLAY_IDENTIFICATION_DATA>( - DisplayHook<decltype(&HwcDisplay::GetDisplayIdentificationData), - &HwcDisplay::GetDisplayIdentificationData, uint8_t *, - uint32_t *, uint8_t *>); - case HWC2::FunctionDescriptor::GetDisplayCapabilities: - return ToHook<HWC2_PFN_GET_DISPLAY_CAPABILITIES>( - DisplayHook<decltype(&HwcDisplay::GetDisplayCapabilities), - &HwcDisplay::GetDisplayCapabilities, uint32_t *, - uint32_t *>); - case HWC2::FunctionDescriptor::GetDisplayBrightnessSupport: - return ToHook<HWC2_PFN_GET_DISPLAY_BRIGHTNESS_SUPPORT>( - DisplayHook<decltype(&HwcDisplay::GetDisplayBrightnessSupport), - &HwcDisplay::GetDisplayBrightnessSupport, bool *>); - case HWC2::FunctionDescriptor::SetDisplayBrightness: - return ToHook<HWC2_PFN_SET_DISPLAY_BRIGHTNESS>( - DisplayHook<decltype(&HwcDisplay::SetDisplayBrightness), - &HwcDisplay::SetDisplayBrightness, float>); -#endif /* PLATFORM_SDK_VERSION > 28 */ - // Layer functions - case HWC2::FunctionDescriptor::SetCursorPosition: - return ToHook<HWC2_PFN_SET_CURSOR_POSITION>( - LayerHook<decltype(&HwcLayer::SetCursorPosition), - &HwcLayer::SetCursorPosition, int32_t, int32_t>); - case HWC2::FunctionDescriptor::SetLayerBlendMode: - return ToHook<HWC2_PFN_SET_LAYER_BLEND_MODE>( - LayerHook<decltype(&HwcLayer::SetLayerBlendMode), - &HwcLayer::SetLayerBlendMode, int32_t>); - case HWC2::FunctionDescriptor::SetLayerBuffer: - return ToHook<HWC2_PFN_SET_LAYER_BUFFER>( - LayerHook<decltype(&HwcLayer::SetLayerBuffer), - &HwcLayer::SetLayerBuffer, buffer_handle_t, int32_t>); - case HWC2::FunctionDescriptor::SetLayerColor: - return ToHook<HWC2_PFN_SET_LAYER_COLOR>( - LayerHook<decltype(&HwcLayer::SetLayerColor), - &HwcLayer::SetLayerColor, hwc_color_t>); - case HWC2::FunctionDescriptor::SetLayerCompositionType: - return ToHook<HWC2_PFN_SET_LAYER_COMPOSITION_TYPE>( - LayerHook<decltype(&HwcLayer::SetLayerCompositionType), - &HwcLayer::SetLayerCompositionType, int32_t>); - case HWC2::FunctionDescriptor::SetLayerDataspace: - return ToHook<HWC2_PFN_SET_LAYER_DATASPACE>( - LayerHook<decltype(&HwcLayer::SetLayerDataspace), - &HwcLayer::SetLayerDataspace, int32_t>); - case HWC2::FunctionDescriptor::SetLayerDisplayFrame: - return ToHook<HWC2_PFN_SET_LAYER_DISPLAY_FRAME>( - LayerHook<decltype(&HwcLayer::SetLayerDisplayFrame), - &HwcLayer::SetLayerDisplayFrame, hwc_rect_t>); - case HWC2::FunctionDescriptor::SetLayerPlaneAlpha: - return ToHook<HWC2_PFN_SET_LAYER_PLANE_ALPHA>( - LayerHook<decltype(&HwcLayer::SetLayerPlaneAlpha), - &HwcLayer::SetLayerPlaneAlpha, float>); - case HWC2::FunctionDescriptor::SetLayerSidebandStream: - return ToHook<HWC2_PFN_SET_LAYER_SIDEBAND_STREAM>( - LayerHook<decltype(&HwcLayer::SetLayerSidebandStream), - &HwcLayer::SetLayerSidebandStream, - const native_handle_t *>); - case HWC2::FunctionDescriptor::SetLayerSourceCrop: - return ToHook<HWC2_PFN_SET_LAYER_SOURCE_CROP>( - LayerHook<decltype(&HwcLayer::SetLayerSourceCrop), - &HwcLayer::SetLayerSourceCrop, hwc_frect_t>); - case HWC2::FunctionDescriptor::SetLayerSurfaceDamage: - return ToHook<HWC2_PFN_SET_LAYER_SURFACE_DAMAGE>( - LayerHook<decltype(&HwcLayer::SetLayerSurfaceDamage), - &HwcLayer::SetLayerSurfaceDamage, hwc_region_t>); - case HWC2::FunctionDescriptor::SetLayerTransform: - return ToHook<HWC2_PFN_SET_LAYER_TRANSFORM>( - LayerHook<decltype(&HwcLayer::SetLayerTransform), - &HwcLayer::SetLayerTransform, int32_t>); - case HWC2::FunctionDescriptor::SetLayerVisibleRegion: - return ToHook<HWC2_PFN_SET_LAYER_VISIBLE_REGION>( - LayerHook<decltype(&HwcLayer::SetLayerVisibleRegion), - &HwcLayer::SetLayerVisibleRegion, hwc_region_t>); - case HWC2::FunctionDescriptor::SetLayerZOrder: - return ToHook<HWC2_PFN_SET_LAYER_Z_ORDER>( - LayerHook<decltype(&HwcLayer::SetLayerZOrder), - &HwcLayer::SetLayerZOrder, uint32_t>); - case HWC2::FunctionDescriptor::Invalid: - default: - return NULL; - } -} - -// static -int DrmHwcTwo::HookDevOpen(const struct hw_module_t *module, const char *name, - struct hw_device_t **dev) { - supported(__func__); - if (strcmp(name, HWC_HARDWARE_COMPOSER)) { - ALOGE("Invalid module name- %s", name); - return -EINVAL; - } - - std::unique_ptr<DrmHwcTwo> ctx(new DrmHwcTwo()); - if (!ctx) { - ALOGE("Failed to allocate DrmHwcTwo"); - return -ENOMEM; - } - - HWC2::Error err = ctx->Init(); - if (err != HWC2::Error::None) { - ALOGE("Failed to initialize DrmHwcTwo err=%d\n", err); - return -EINVAL; - } - - ctx->common.module = const_cast<hw_module_t *>(module); - *dev = &ctx->common; - ctx.release(); - return 0; -} -} // namespace android - -static struct hw_module_methods_t hwc2_module_methods = { - .open = android::DrmHwcTwo::HookDevOpen, -}; - -hw_module_t HAL_MODULE_INFO_SYM = { - .tag = HARDWARE_MODULE_TAG, - .module_api_version = HARDWARE_MODULE_API_VERSION(2, 0), - .id = HWC_HARDWARE_MODULE_ID, - .name = "DrmHwcTwo module", - .author = "The Android Open Source Project", - .methods = &hwc2_module_methods, - .dso = NULL, - .reserved = {0}, -}; diff --git a/DrmHwcTwo.h b/DrmHwcTwo.h deleted file mode 100644 index d489113..0000000 --- a/DrmHwcTwo.h +++ /dev/null @@ -1,434 +0,0 @@ -/* - * Copyright (C) 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ANDROID_DRM_HWC_TWO_H_ -#define ANDROID_DRM_HWC_TWO_H_ - -#include <hardware/hwcomposer2.h> -#include <math.h> - -#include <array> -#include <map> - -#include "compositor/DrmDisplayCompositor.h" -#include "compositor/Planner.h" -#include "drm/DrmGenericImporter.h" -#include "drm/ResourceManager.h" -#include "drm/VSyncWorker.h" -#include "drmhwcomposer.h" - -namespace android { - -class Backend; - -class DrmHwcTwo : public hwc2_device_t { - public: - static int HookDevOpen(const struct hw_module_t *module, const char *name, - struct hw_device_t **dev); - - DrmHwcTwo(); - - HWC2::Error Init(); - - hwc2_callback_data_t hotplug_callback_data_ = NULL; - HWC2_PFN_HOTPLUG hotplug_callback_hook_ = NULL; - std::mutex hotplug_callback_lock; - - void SetHotplugCallback(hwc2_callback_data_t data, - hwc2_function_pointer_t hook) { - const std::lock_guard<std::mutex> lock(hotplug_callback_lock); - hotplug_callback_data_ = data; - hotplug_callback_hook_ = reinterpret_cast<HWC2_PFN_HOTPLUG>(hook); - } - - class HwcLayer { - public: - HWC2::Composition sf_type() const { - return sf_type_; - } - HWC2::Composition validated_type() const { - return validated_type_; - } - void accept_type_change() { - sf_type_ = validated_type_; - } - void set_validated_type(HWC2::Composition type) { - validated_type_ = type; - } - bool type_changed() const { - return sf_type_ != validated_type_; - } - - uint32_t z_order() const { - return z_order_; - } - - buffer_handle_t buffer() { - return buffer_; - } - void set_buffer(buffer_handle_t buffer) { - buffer_ = buffer; - } - - int take_acquire_fence() { - return acquire_fence_.Release(); - } - void set_acquire_fence(int acquire_fence) { - acquire_fence_.Set(dup(acquire_fence)); - } - - int release_fence() { - return release_fence_.get(); - } - int take_release_fence() { - return release_fence_.Release(); - } - void manage_release_fence() { - release_fence_.Set(release_fence_raw_); - release_fence_raw_ = -1; - } - OutputFd release_fence_output() { - return OutputFd(&release_fence_raw_); - } - - hwc_rect_t display_frame() { - return display_frame_; - } - - void PopulateDrmLayer(DrmHwcLayer *layer); - - bool RequireScalingOrPhasing() { - float src_width = source_crop_.right - source_crop_.left; - float src_height = source_crop_.bottom - source_crop_.top; - - float dest_width = display_frame_.right - display_frame_.left; - float dest_height = display_frame_.bottom - display_frame_.top; - - bool scaling = src_width != dest_width || src_height != dest_height; - bool phasing = (source_crop_.left - floor(source_crop_.left) != 0) || - (source_crop_.top - floor(source_crop_.top) != 0); - return scaling || phasing; - } - - // Layer hooks - HWC2::Error SetCursorPosition(int32_t x, int32_t y); - HWC2::Error SetLayerBlendMode(int32_t mode); - HWC2::Error SetLayerBuffer(buffer_handle_t buffer, int32_t acquire_fence); - HWC2::Error SetLayerColor(hwc_color_t color); - HWC2::Error SetLayerCompositionType(int32_t type); - HWC2::Error SetLayerDataspace(int32_t dataspace); - HWC2::Error SetLayerDisplayFrame(hwc_rect_t frame); - HWC2::Error SetLayerPlaneAlpha(float alpha); - HWC2::Error SetLayerSidebandStream(const native_handle_t *stream); - HWC2::Error SetLayerSourceCrop(hwc_frect_t crop); - HWC2::Error SetLayerSurfaceDamage(hwc_region_t damage); - HWC2::Error SetLayerTransform(int32_t transform); - HWC2::Error SetLayerVisibleRegion(hwc_region_t visible); - HWC2::Error SetLayerZOrder(uint32_t z); - - private: - // sf_type_ stores the initial type given to us by surfaceflinger, - // validated_type_ stores the type after running ValidateDisplay - HWC2::Composition sf_type_ = HWC2::Composition::Invalid; - HWC2::Composition validated_type_ = HWC2::Composition::Invalid; - - HWC2::BlendMode blending_ = HWC2::BlendMode::None; - buffer_handle_t buffer_ = NULL; - UniqueFd acquire_fence_; - int release_fence_raw_ = -1; - UniqueFd release_fence_; - hwc_rect_t display_frame_; - float alpha_ = 1.0f; - hwc_frect_t source_crop_; - int32_t cursor_x_; - int32_t cursor_y_; - hwc_color_t layer_color_; - HWC2::Transform transform_ = HWC2::Transform::None; - uint32_t z_order_ = 0; - android_dataspace_t dataspace_ = HAL_DATASPACE_UNKNOWN; - }; - - class HwcDisplay { - public: - HwcDisplay(ResourceManager *resource_manager, DrmDevice *drm, - std::shared_ptr<Importer> importer, hwc2_display_t handle, - HWC2::DisplayType type); - HwcDisplay(const HwcDisplay &) = delete; - HWC2::Error Init(std::vector<DrmPlane *> *planes); - - void RegisterVsyncCallback(hwc2_callback_data_t data, - hwc2_function_pointer_t func); - void RegisterRefreshCallback(hwc2_callback_data_t data, - hwc2_function_pointer_t func); - HWC2::Error CreateComposition(bool test); - bool HardwareSupportsLayerType(HWC2::Composition comp_type); - uint32_t CalcPixOps(std::map<uint32_t, DrmHwcTwo::HwcLayer *> &z_map, - size_t first_z, size_t size); - void MarkValidated(std::map<uint32_t, DrmHwcTwo::HwcLayer *> &z_map, - size_t client_first_z, size_t client_size); - - void ClearDisplay(); - - std::string Dump(); - - // HWC Hooks - HWC2::Error AcceptDisplayChanges(); - HWC2::Error CreateLayer(hwc2_layer_t *layer); - HWC2::Error DestroyLayer(hwc2_layer_t layer); - HWC2::Error GetActiveConfig(hwc2_config_t *config); - HWC2::Error GetChangedCompositionTypes(uint32_t *num_elements, - hwc2_layer_t *layers, - int32_t *types); - HWC2::Error GetClientTargetSupport(uint32_t width, uint32_t height, - int32_t format, int32_t dataspace); - HWC2::Error GetColorModes(uint32_t *num_modes, int32_t *modes); - HWC2::Error GetDisplayAttribute(hwc2_config_t config, int32_t attribute, - int32_t *value); - HWC2::Error GetDisplayConfigs(uint32_t *num_configs, - hwc2_config_t *configs); - HWC2::Error GetDisplayName(uint32_t *size, char *name); - HWC2::Error GetDisplayRequests(int32_t *display_requests, - uint32_t *num_elements, hwc2_layer_t *layers, - int32_t *layer_requests); - HWC2::Error GetDisplayType(int32_t *type); -#if PLATFORM_SDK_VERSION > 27 - HWC2::Error GetRenderIntents(int32_t mode, uint32_t *outNumIntents, - int32_t *outIntents); - HWC2::Error SetColorModeWithIntent(int32_t mode, int32_t intent); -#endif -#if PLATFORM_SDK_VERSION > 28 - HWC2::Error GetDisplayIdentificationData(uint8_t *outPort, - uint32_t *outDataSize, - uint8_t *outData); - HWC2::Error GetDisplayCapabilities(uint32_t *outNumCapabilities, - uint32_t *outCapabilities); - HWC2::Error GetDisplayBrightnessSupport(bool *supported); - HWC2::Error SetDisplayBrightness(float); -#endif - HWC2::Error GetDozeSupport(int32_t *support); - HWC2::Error GetHdrCapabilities(uint32_t *num_types, int32_t *types, - float *max_luminance, - float *max_average_luminance, - float *min_luminance); - HWC2::Error GetReleaseFences(uint32_t *num_elements, hwc2_layer_t *layers, - int32_t *fences); - HWC2::Error PresentDisplay(int32_t *present_fence); - HWC2::Error SetActiveConfig(hwc2_config_t config); - HWC2::Error ChosePreferredConfig(); - HWC2::Error SetClientTarget(buffer_handle_t target, int32_t acquire_fence, - int32_t dataspace, hwc_region_t damage); - HWC2::Error SetColorMode(int32_t mode); - HWC2::Error SetColorTransform(const float *matrix, int32_t hint); - HWC2::Error SetOutputBuffer(buffer_handle_t buffer, int32_t release_fence); - HWC2::Error SetPowerMode(int32_t mode); - HWC2::Error SetVsyncEnabled(int32_t enabled); - HWC2::Error ValidateDisplay(uint32_t *num_types, uint32_t *num_requests); - HwcLayer *get_layer(hwc2_layer_t layer) { - auto it = layers_.find(layer); - if (it == layers_.end()) - return nullptr; - return &it->second; - } - - /* Statistics */ - struct Stats { - Stats minus(Stats b) { - return {total_frames_ - b.total_frames_, - total_pixops_ - b.total_pixops_, - gpu_pixops_ - b.gpu_pixops_, - failed_kms_validate_ - b.failed_kms_validate_, - failed_kms_present_ - b.failed_kms_present_, - frames_flattened_ - b.frames_flattened_}; - } - - uint32_t total_frames_ = 0; - uint64_t total_pixops_ = 0; - uint64_t gpu_pixops_ = 0; - uint32_t failed_kms_validate_ = 0; - uint32_t failed_kms_present_ = 0; - uint32_t frames_flattened_ = 0; - }; - - const Backend *backend() const { - return backend_.get(); - } - void set_backend(std::unique_ptr<Backend> backend) { - backend_ = std::move(backend); - } - - const std::vector<DrmPlane *> &primary_planes() const { - return primary_planes_; - } - - const std::vector<DrmPlane *> &overlay_planes() const { - return overlay_planes_; - } - - std::map<hwc2_layer_t, HwcLayer> &layers() { - return layers_; - } - - const DrmDisplayCompositor &compositor() const { - return compositor_; - } - - const DrmDevice *drm() const { - return drm_; - } - - const DrmConnector *connector() const { - return connector_; - } - - const std::shared_ptr<Importer> &importer() const { - return importer_; - } - - ResourceManager *resource_manager() const { - return resource_manager_; - } - - android_color_transform_t &color_transform_hint() { - return color_transform_hint_; - } - - Stats &total_stats() { - return total_stats_; - } - - private: - void AddFenceToPresentFence(int fd); - - constexpr static size_t MATRIX_SIZE = 16; - - ResourceManager *resource_manager_; - DrmDevice *drm_; - DrmDisplayCompositor compositor_; - std::shared_ptr<Importer> importer_; - std::unique_ptr<Planner> planner_; - - std::vector<DrmPlane *> primary_planes_; - std::vector<DrmPlane *> overlay_planes_; - - std::unique_ptr<Backend> backend_; - - VSyncWorker vsync_worker_; - DrmConnector *connector_ = NULL; - DrmCrtc *crtc_ = NULL; - hwc2_display_t handle_; - HWC2::DisplayType type_; - uint32_t layer_idx_ = 0; - std::map<hwc2_layer_t, HwcLayer> layers_; - HwcLayer client_layer_; - UniqueFd present_fence_; - int32_t color_mode_; - std::array<float, MATRIX_SIZE> color_transform_matrix_; - android_color_transform_t color_transform_hint_; - - uint32_t frame_no_ = 0; - Stats total_stats_; - Stats prev_stats_; - std::string DumpDelta(DrmHwcTwo::HwcDisplay::Stats delta); - }; - - class DrmHotplugHandler : public DrmEventHandler { - public: - DrmHotplugHandler(DrmHwcTwo *hwc2, DrmDevice *drm) - : hwc2_(hwc2), drm_(drm) { - } - void HandleEvent(uint64_t timestamp_us); - - private: - DrmHwcTwo *hwc2_; - DrmDevice *drm_; - }; - - private: - static DrmHwcTwo *toDrmHwcTwo(hwc2_device_t *dev) { - return static_cast<DrmHwcTwo *>(dev); - } - - template <typename PFN, typename T> - static hwc2_function_pointer_t ToHook(T function) { - static_assert(std::is_same<PFN, T>::value, "Incompatible fn pointer"); - return reinterpret_cast<hwc2_function_pointer_t>(function); - } - - template <typename T, typename HookType, HookType func, typename... Args> - static T DeviceHook(hwc2_device_t *dev, Args... args) { - DrmHwcTwo *hwc = toDrmHwcTwo(dev); - return static_cast<T>(((*hwc).*func)(std::forward<Args>(args)...)); - } - - static HwcDisplay *GetDisplay(DrmHwcTwo *hwc, hwc2_display_t display_handle) { - auto it = hwc->displays_.find(display_handle); - if (it == hwc->displays_.end()) - return nullptr; - - return &it->second; - } - - template <typename HookType, HookType func, typename... Args> - static int32_t DisplayHook(hwc2_device_t *dev, hwc2_display_t display_handle, - Args... args) { - HwcDisplay *display = GetDisplay(toDrmHwcTwo(dev), display_handle); - if (!display) - return static_cast<int32_t>(HWC2::Error::BadDisplay); - - return static_cast<int32_t>((display->*func)(std::forward<Args>(args)...)); - } - - template <typename HookType, HookType func, typename... Args> - static int32_t LayerHook(hwc2_device_t *dev, hwc2_display_t display_handle, - hwc2_layer_t layer_handle, Args... args) { - HwcDisplay *display = GetDisplay(toDrmHwcTwo(dev), display_handle); - if (!display) - return static_cast<int32_t>(HWC2::Error::BadDisplay); - - HwcLayer *layer = display->get_layer(layer_handle); - if (!layer) - return static_cast<int32_t>(HWC2::Error::BadLayer); - - return static_cast<int32_t>((layer->*func)(std::forward<Args>(args)...)); - } - - // hwc2_device_t hooks - static int HookDevClose(hw_device_t *dev); - static void HookDevGetCapabilities(hwc2_device_t *dev, uint32_t *out_count, - int32_t *out_capabilities); - static hwc2_function_pointer_t HookDevGetFunction(struct hwc2_device *device, - int32_t descriptor); - - // Device functions - HWC2::Error CreateVirtualDisplay(uint32_t width, uint32_t height, - int32_t *format, hwc2_display_t *display); - HWC2::Error DestroyVirtualDisplay(hwc2_display_t display); - void Dump(uint32_t *outSize, char *outBuffer); - uint32_t GetMaxVirtualDisplayCount(); - HWC2::Error RegisterCallback(int32_t descriptor, hwc2_callback_data_t data, - hwc2_function_pointer_t function); - HWC2::Error CreateDisplay(hwc2_display_t displ, HWC2::DisplayType type); - void HandleDisplayHotplug(hwc2_display_t displayid, int state); - void HandleInitialHotplugState(DrmDevice *drmDevice); - - ResourceManager resource_manager_; - std::map<hwc2_display_t, HwcDisplay> displays_; - - std::string mDumpString; -}; -} // namespace android - -#endif @@ -1,5 +1,5 @@ adelva@google.com +dimitrysh@google.com john.stultz@linaro.org marcheu@google.com seanpaul@google.com -zachr@google.com @@ -1,19 +1,29 @@ -drm_hwcomposer +drm\_hwcomposer ====== -Patches to drm_hwcomposer are very much welcome, we really want this to be the -universal HW composer implementation for Android and similar platforms -So please bring on porting patches, bugfixes, improvements for documentation -and new features. +Patches to drm\_hwcomposer are very much welcome, we really want this to be the +universal HW composer implementation for Android and similar platforms. So +please bring on porting patches, bugfixes, improvements for documentation and +new features. A short list of contribution guidelines: -* Submit changes via gitlab merge requests on gitlab.freedesktop.org -* drm_hwcomposer is Apache 2.0 Licensed and we require contributions to follow the developer's certificate of origin: http://developercertificate.org/ -* When submitting new code please follow the naming conventions documented in the generated documentation. Also please make full use of all the helpers and convenience macros provided by drm_hwcomposer. The below command can help you with formatting of your patches: - - `git diff | clang-format-diff-5.0 -p 1 -style=file` -* Hardware specific changes should be tested on relevant platforms before committing. +* Submit changes via gitlab merge requests on gitlab.freedesktop.org. +* drm\_hwcomposer is Apache 2.0 Licensed and we require contributions to follow + the developer's certificate of origin: http://developercertificate.org/. +* When submitting new code please follow the naming conventions documented in + the generated documentation. Also please make full use of all the helpers and + convenience macros provided by drm\_hwcomposer. The below command can help + you with formatting of your patches: -If you need inspiration, please checkout our [TODO issues](https://gitlab.freedesktop.org/drm-hwcomposer/drm-hwcomposer/issues?label_name%5B%5D=TODO) + ``` + git diff | clang-format-diff-13 -p 1 -style=file + ``` + +* Hardware specific changes should be tested on relevant platforms before + committing. + +If you need inspiration, please checkout our [TODO issues][1]. Happy hacking! + +[1]: https://gitlab.freedesktop.org/drm-hwcomposer/drm-hwcomposer/issues?label_name%5B%5D=TODO diff --git a/backend/Backend.cpp b/backend/Backend.cpp index 887eb0e..f6d9c18 100644 --- a/backend/Backend.cpp +++ b/backend/Backend.cpp @@ -16,122 +16,154 @@ #include "Backend.h" +#include <climits> + #include "BackendManager.h" #include "bufferinfo/BufferInfoGetter.h" namespace android { -HWC2::Error Backend::ValidateDisplay(DrmHwcTwo::HwcDisplay *display, - uint32_t *num_types, +HWC2::Error Backend::ValidateDisplay(HwcDisplay *display, uint32_t *num_types, uint32_t *num_requests) { *num_types = 0; *num_requests = 0; - size_t avail_planes = display->primary_planes().size() + - display->overlay_planes().size(); - - /* - * If more layers then planes, save one plane - * for client composited layers - */ - if (avail_planes < display->layers().size()) - avail_planes--; - std::map<uint32_t, DrmHwcTwo::HwcLayer *> z_map, z_map_tmp; - uint32_t z_index = 0; - // First create a map of layers and z_order values - for (std::pair<const hwc2_layer_t, DrmHwcTwo::HwcLayer> &l : - display->layers()) - z_map_tmp.emplace(std::make_pair(l.second.z_order(), &l.second)); - // normalise the map so that the lowest z_order layer has key 0 - for (std::pair<const uint32_t, DrmHwcTwo::HwcLayer *> &l : z_map_tmp) - z_map.emplace(std::make_pair(z_index++, l.second)); + auto layers = display->GetOrderLayersByZPos(); - uint32_t total_pixops = display->CalcPixOps(z_map, 0, z_map.size()); - uint32_t gpu_pixops = 0; + int client_start = -1; + size_t client_size = 0; - int client_start = -1, client_size = 0; - - if (display->compositor().ShouldFlattenOnClient()) { + if (display->ProcessClientFlatteningState(layers.size() <= 1)) { + display->total_stats().frames_flattened_++; client_start = 0; - client_size = z_map.size(); - display->MarkValidated(z_map, client_start, client_size); + client_size = layers.size(); + MarkValidated(layers, client_start, client_size); } else { - std::tie(client_start, client_size) = GetClientLayers(display, z_map); - - int extra_client = (z_map.size() - client_size) - avail_planes; - if (extra_client > 0) { - int start = 0, steps; - if (client_size != 0) { - int prepend = std::min(client_start, extra_client); - int append = std::min(int(z_map.size() - (client_start + client_size)), - extra_client); - start = client_start - prepend; - client_size += extra_client; - steps = 1 + std::min(std::min(append, prepend), - int(z_map.size()) - (start + client_size)); - } else { - client_size = extra_client; - steps = 1 + z_map.size() - extra_client; - } + std::tie(client_start, client_size) = GetClientLayers(display, layers); - gpu_pixops = INT_MAX; - for (int i = 0; i < steps; i++) { - uint32_t po = display->CalcPixOps(z_map, start + i, client_size); - if (po < gpu_pixops) { - gpu_pixops = po; - client_start = start + i; - } - } - } + MarkValidated(layers, client_start, client_size); - display->MarkValidated(z_map, client_start, client_size); + bool testing_needed = !(client_start == 0 && client_size == layers.size()); - bool testing_needed = !(client_start == 0 && client_size == z_map.size()); + AtomicCommitArgs a_args = {.test_only = true}; if (testing_needed && - display->CreateComposition(true) != HWC2::Error::None) { + display->CreateComposition(a_args) != HWC2::Error::None) { ++display->total_stats().failed_kms_validate_; - gpu_pixops = total_pixops; - client_size = z_map.size(); - display->MarkValidated(z_map, 0, client_size); + client_start = 0; + client_size = layers.size(); + MarkValidated(layers, 0, client_size); } } *num_types = client_size; - display->total_stats().frames_flattened_ = display->compositor() - .GetFlattenedFramesCount(); - display->total_stats().gpu_pixops_ += gpu_pixops; - display->total_stats().total_pixops_ += total_pixops; + display->total_stats().gpu_pixops_ += CalcPixOps(layers, client_start, + client_size); + display->total_stats().total_pixops_ += CalcPixOps(layers, 0, layers.size()); - return *num_types ? HWC2::Error::HasChanges : HWC2::Error::None; + return *num_types != 0 ? HWC2::Error::HasChanges : HWC2::Error::None; } -std::tuple<int, int> Backend::GetClientLayers( - DrmHwcTwo::HwcDisplay *display, - const std::map<uint32_t, DrmHwcTwo::HwcLayer *> &z_map) { - int client_start = -1, client_size = 0; +std::tuple<int, size_t> Backend::GetClientLayers( + HwcDisplay *display, const std::vector<HwcLayer *> &layers) { + int client_start = -1; + size_t client_size = 0; - for (auto & [ z_order, layer ] : z_map) { - if (IsClientLayer(display, layer)) { + for (size_t z_order = 0; z_order < layers.size(); ++z_order) { + if (IsClientLayer(display, layers[z_order])) { if (client_start < 0) - client_start = z_order; + client_start = (int)z_order; client_size = (z_order - client_start) + 1; } } - return std::make_tuple(client_start, client_size); + return GetExtraClientRange(display, layers, client_start, client_size); } -bool Backend::IsClientLayer(DrmHwcTwo::HwcDisplay *display, - DrmHwcTwo::HwcLayer *layer) { - return !display->HardwareSupportsLayerType(layer->sf_type()) || - !BufferInfoGetter::GetInstance()->IsHandleUsable(layer->buffer()) || +bool Backend::IsClientLayer(HwcDisplay *display, HwcLayer *layer) { + return !HardwareSupportsLayerType(layer->GetSfType()) || + !BufferInfoGetter::GetInstance()->IsHandleUsable(layer->GetBuffer()) || display->color_transform_hint() != HAL_COLOR_TRANSFORM_IDENTITY || (layer->RequireScalingOrPhasing() && - display->resource_manager()->ForcedScalingWithGpu()); + display->GetHwc2()->GetResMan().ForcedScalingWithGpu()); +} + +bool Backend::HardwareSupportsLayerType(HWC2::Composition comp_type) { + return comp_type == HWC2::Composition::Device || + comp_type == HWC2::Composition::Cursor; +} + +uint32_t Backend::CalcPixOps(const std::vector<HwcLayer *> &layers, + size_t first_z, size_t size) { + uint32_t pixops = 0; + for (size_t z_order = 0; z_order < layers.size(); ++z_order) { + if (z_order >= first_z && z_order < first_z + size) { + hwc_rect_t df = layers[z_order]->GetDisplayFrame(); + pixops += (df.right - df.left) * (df.bottom - df.top); + } + } + return pixops; +} + +void Backend::MarkValidated(std::vector<HwcLayer *> &layers, + size_t client_first_z, size_t client_size) { + for (size_t z_order = 0; z_order < layers.size(); ++z_order) { + if (z_order >= client_first_z && z_order < client_first_z + client_size) + layers[z_order]->SetValidatedType(HWC2::Composition::Client); + else + layers[z_order]->SetValidatedType(HWC2::Composition::Device); + } +} + +std::tuple<int, int> Backend::GetExtraClientRange( + HwcDisplay *display, const std::vector<HwcLayer *> &layers, + int client_start, size_t client_size) { + auto planes = display->GetPipe().GetUsablePlanes(); + size_t avail_planes = planes.size(); + + /* + * If more layers then planes, save one plane + * for client composited layers + */ + if (avail_planes < display->layers().size()) + avail_planes--; + + int extra_client = int(layers.size() - client_size) - int(avail_planes); + + if (extra_client > 0) { + int start = 0; + size_t steps = 0; + if (client_size != 0) { + int prepend = std::min(client_start, extra_client); + int append = std::min(int(layers.size()) - + int(client_start + client_size), + extra_client); + start = client_start - (int)prepend; + client_size += extra_client; + steps = 1 + std::min(std::min(append, prepend), + int(layers.size()) - int(start + client_size)); + } else { + client_size = extra_client; + steps = 1 + layers.size() - extra_client; + } + + uint32_t gpu_pixops = UINT32_MAX; + for (size_t i = 0; i < steps; i++) { + uint32_t po = CalcPixOps(layers, start + i, client_size); + if (po < gpu_pixops) { + gpu_pixops = po; + client_start = start + int(i); + } + } + } + + return std::make_tuple(client_start, client_size); } +// clang-format off +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables, cert-err58-cpp) REGISTER_BACKEND("generic", Backend); +// clang-format on } // namespace android diff --git a/backend/Backend.h b/backend/Backend.h index 898fece..82b8fca 100644 --- a/backend/Backend.h +++ b/backend/Backend.h @@ -17,21 +17,28 @@ #ifndef ANDROID_BACKEND_H #define ANDROID_BACKEND_H -#include "DrmHwcTwo.h" +#include "hwc2_device/DrmHwcTwo.h" namespace android { class Backend { public: virtual ~Backend() = default; - virtual HWC2::Error ValidateDisplay(DrmHwcTwo::HwcDisplay *display, - uint32_t *num_types, + virtual HWC2::Error ValidateDisplay(HwcDisplay *display, uint32_t *num_types, uint32_t *num_requests); - virtual std::tuple<int, int> GetClientLayers( - DrmHwcTwo::HwcDisplay *display, - const std::map<uint32_t, DrmHwcTwo::HwcLayer *> &z_map); - virtual bool IsClientLayer(DrmHwcTwo::HwcDisplay *display, - DrmHwcTwo::HwcLayer *layer); + virtual std::tuple<int, size_t> GetClientLayers( + HwcDisplay *display, const std::vector<HwcLayer *> &layers); + virtual bool IsClientLayer(HwcDisplay *display, HwcLayer *layer); + + protected: + static bool HardwareSupportsLayerType(HWC2::Composition comp_type); + static uint32_t CalcPixOps(const std::vector<HwcLayer *> &layers, + size_t first_z, size_t size); + static void MarkValidated(std::vector<HwcLayer *> &layers, + size_t client_first_z, size_t client_size); + static std::tuple<int, int> GetExtraClientRange( + HwcDisplay *display, const std::vector<HwcLayer *> &layers, + int client_start, size_t client_size); }; } // namespace android diff --git a/backend/BackendClient.cpp b/backend/BackendClient.cpp index 033a35c..606dca2 100644 --- a/backend/BackendClient.cpp +++ b/backend/BackendClient.cpp @@ -20,16 +20,19 @@ namespace android { -HWC2::Error BackendClient::ValidateDisplay(DrmHwcTwo::HwcDisplay *display, +HWC2::Error BackendClient::ValidateDisplay(HwcDisplay *display, uint32_t *num_types, uint32_t * /*num_requests*/) { - for (auto & [ layer_handle, layer ] : display->layers()) { - layer.set_validated_type(HWC2::Composition::Client); + for (auto &[layer_handle, layer] : display->layers()) { + layer.SetValidatedType(HWC2::Composition::Client); ++*num_types; } return HWC2::Error::HasChanges; } +// clang-format off +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables, cert-err58-cpp) REGISTER_BACKEND("client", BackendClient); +// clang-format on } // namespace android diff --git a/backend/BackendClient.h b/backend/BackendClient.h index 13543f1..95abb0f 100644 --- a/backend/BackendClient.h +++ b/backend/BackendClient.h @@ -23,8 +23,7 @@ namespace android { class BackendClient : public Backend { public: - HWC2::Error ValidateDisplay(DrmHwcTwo::HwcDisplay *display, - uint32_t *num_types, + HWC2::Error ValidateDisplay(HwcDisplay *display, uint32_t *num_types, uint32_t *num_requests) override; }; } // namespace android diff --git a/backend/BackendManager.cpp b/backend/BackendManager.cpp index 0bacdcd..9bf6324 100644 --- a/backend/BackendManager.cpp +++ b/backend/BackendManager.cpp @@ -18,12 +18,13 @@ #include "BackendManager.h" -#include <cutils/properties.h> -#include <log/log.h> +#include "utils/log.h" +#include "utils/properties.h" namespace android { -const std::vector<std::string> BackendManager::client_devices_ = { +// NOLINTNEXTLINE(cert-err58-cpp) +const std::vector<std::string> BackendManager::kClientDevices = { "kirin", "mediatek-drm", }; @@ -35,43 +36,45 @@ BackendManager &BackendManager::GetInstance() { } int BackendManager::RegisterBackend(const std::string &name, - backend_constructor_t backend_constructor) { + BackendConstructorT backend_constructor) { available_backends_[name] = std::move(backend_constructor); return 0; } -int BackendManager::SetBackendForDisplay(DrmHwcTwo::HwcDisplay *display) { - std::string driver_name(display->drm()->GetName()); +int BackendManager::SetBackendForDisplay(HwcDisplay *display) { + std::string driver_name(display->GetPipe().device->GetName()); char backend_override[PROPERTY_VALUE_MAX]; property_get("vendor.hwc.backend_override", backend_override, driver_name.c_str()); - std::string backend_name(std::move(backend_override)); + std::string backend_name(backend_override); display->set_backend(GetBackendByName(backend_name)); - if (!display->backend()) { + if (display->backend() == nullptr) { ALOGE("Failed to set backend '%s' for '%s' and driver '%s'", - backend_name.c_str(), display->connector()->name().c_str(), + backend_name.c_str(), + display->GetPipe().connector->Get()->GetName().c_str(), driver_name.c_str()); return -EINVAL; } ALOGI("Backend '%s' for '%s' and driver '%s' was successfully set", - backend_name.c_str(), display->connector()->name().c_str(), + backend_name.c_str(), + display->GetPipe().connector->Get()->GetName().c_str(), driver_name.c_str()); return 0; } std::unique_ptr<Backend> BackendManager::GetBackendByName(std::string &name) { - if (!available_backends_.size()) { + if (available_backends_.empty()) { ALOGE("No backends are specified"); return nullptr; } auto it = available_backends_.find(name); if (it == available_backends_.end()) { - auto it = std::find(client_devices_.begin(), client_devices_.end(), name); - name = it == client_devices_.end() ? "generic" : "client"; + auto it = std::find(kClientDevices.begin(), kClientDevices.end(), name); + name = it == kClientDevices.end() ? "generic" : "client"; } return available_backends_[name](); diff --git a/backend/BackendManager.h b/backend/BackendManager.h index e86c098..751cb78 100644 --- a/backend/BackendManager.h +++ b/backend/BackendManager.h @@ -24,6 +24,7 @@ #include "Backend.h" +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define REGISTER_BACKEND(name_str_, backend_) \ static int \ backend = BackendManager::GetInstance() \ @@ -36,21 +37,21 @@ namespace android { class BackendManager { public: - using backend_constructor_t = std::function<std::unique_ptr<Backend>()>; + using BackendConstructorT = std::function<std::unique_ptr<Backend>()>; static BackendManager &GetInstance(); int RegisterBackend(const std::string &name, - backend_constructor_t backend_constructor); - int SetBackendForDisplay(DrmHwcTwo::HwcDisplay *display); + BackendConstructorT backend_constructor); + int SetBackendForDisplay(HwcDisplay *display); std::unique_ptr<Backend> GetBackendByName(std::string &name); - HWC2::Error ValidateDisplay(DrmHwcTwo::HwcDisplay *display, - uint32_t *num_types, uint32_t *num_requests); + HWC2::Error ValidateDisplay(HwcDisplay *display, uint32_t *num_types, + uint32_t *num_requests); private: BackendManager() = default; - static const std::vector<std::string> client_devices_; + static const std::vector<std::string> kClientDevices; - std::map<std::string, backend_constructor_t> available_backends_; + std::map<std::string, BackendConstructorT> available_backends_; }; } // namespace android diff --git a/backend/BackendRCarDu.cpp b/backend/BackendRCarDu.cpp deleted file mode 100644 index e85fa71..0000000 --- a/backend/BackendRCarDu.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "BackendRCarDu.h" - -#include "BackendManager.h" -#include "bufferinfo/BufferInfoGetter.h" -#include "drm_fourcc.h" - -namespace android { - -bool BackendRCarDu::IsClientLayer(DrmHwcTwo::HwcDisplay *display, - DrmHwcTwo::HwcLayer *layer) { - hwc_drm_bo_t bo; - - int ret = BufferInfoGetter::GetInstance()->ConvertBoInfo(layer->buffer(), - &bo); - if (ret) - return true; - - if (bo.format == DRM_FORMAT_ABGR8888) - return true; - - if (layer->RequireScalingOrPhasing()) - return true; - - return Backend::IsClientLayer(display, layer); -} - -REGISTER_BACKEND("rcar-du", BackendRCarDu); - -} // namespace android
\ No newline at end of file diff --git a/bufferinfo/BufferInfoGetter.cpp b/bufferinfo/BufferInfoGetter.cpp index afdc50e..0cfd7e5 100644 --- a/bufferinfo/BufferInfoGetter.cpp +++ b/bufferinfo/BufferInfoGetter.cpp @@ -22,28 +22,27 @@ #include "BufferInfoMapperMetadata.h" #endif -#include <cutils/properties.h> -#include <gralloc_handle.h> -#include <hardware/gralloc.h> -#include <log/log.h> #include <xf86drm.h> #include <xf86drmMode.h> +#include "utils/log.h" +#include "utils/properties.h" + namespace android { BufferInfoGetter *BufferInfoGetter::GetInstance() { static std::unique_ptr<BufferInfoGetter> inst; - if (inst == nullptr) { -#if PLATFORM_SDK_VERSION >= 30 + if (!inst) { +#if PLATFORM_SDK_VERSION >= 30 && defined(USE_IMAPPER4_METADATA_API) inst.reset(BufferInfoMapperMetadata::CreateInstance()); - if (inst == nullptr) { + if (!inst) { ALOGW( "Generic buffer getter is not available. Falling back to legacy..."); -#endif - inst.reset(LegacyBufferInfoGetter::CreateInstance()); -#if PLATFORM_SDK_VERSION >= 30 } #endif + if (!inst) { + inst = LegacyBufferInfoGetter::CreateInstance(); + } } return inst.get(); @@ -53,19 +52,21 @@ bool BufferInfoGetter::IsHandleUsable(buffer_handle_t handle) { hwc_drm_bo_t bo; memset(&bo, 0, sizeof(hwc_drm_bo_t)); - if (ConvertBoInfo(handle, &bo) != 0) + if (ConvertBoInfo(handle, &bo) != 0) { return false; - - if (bo.prime_fds[0] == 0) + } + if (bo.prime_fds[0] == 0) { return false; - + } return true; } int LegacyBufferInfoGetter::Init() { - int ret = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, - (const hw_module_t **)&gralloc_); - if (ret) { + int ret = hw_get_module( + GRALLOC_HARDWARE_MODULE_ID, + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + reinterpret_cast<const hw_module_t **>(&gralloc_)); + if (ret != 0) { ALOGE("Failed to open gralloc module"); return ret; } @@ -90,6 +91,8 @@ uint32_t LegacyBufferInfoGetter::ConvertHalFormatToDrm(uint32_t hal_format) { return DRM_FORMAT_BGR565; case HAL_PIXEL_FORMAT_YV12: return DRM_FORMAT_YVU420; + case HAL_PIXEL_FORMAT_RGBA_1010102: + return DRM_FORMAT_ABGR2101010; default: ALOGE("Cannot convert hal format to drm format %u", hal_format); return DRM_FORMAT_INVALID; @@ -103,13 +106,14 @@ bool BufferInfoGetter::IsDrmFormatRgb(uint32_t drm_format) { case DRM_FORMAT_ABGR8888: case DRM_FORMAT_BGR888: case DRM_FORMAT_BGR565: + case DRM_FORMAT_ABGR2101010: return true; default: return false; } } -__attribute__((weak)) LegacyBufferInfoGetter * +__attribute__((weak)) std::unique_ptr<LegacyBufferInfoGetter> LegacyBufferInfoGetter::CreateInstance() { ALOGE("No legacy buffer info getters available"); return nullptr; diff --git a/bufferinfo/BufferInfoGetter.h b/bufferinfo/BufferInfoGetter.h index fad3d16..59184a4 100644 --- a/bufferinfo/BufferInfoGetter.h +++ b/bufferinfo/BufferInfoGetter.h @@ -31,8 +31,7 @@ namespace android { class BufferInfoGetter { public: - virtual ~BufferInfoGetter() { - } + virtual ~BufferInfoGetter() = default; virtual int ConvertBoInfo(buffer_handle_t handle, hwc_drm_bo_t *bo) = 0; @@ -49,28 +48,40 @@ class LegacyBufferInfoGetter : public BufferInfoGetter { int Init(); - int ConvertBoInfo(buffer_handle_t handle, hwc_drm_bo_t *bo) override = 0; + virtual int ValidateGralloc() { + return 0; + } - static LegacyBufferInfoGetter *CreateInstance(); + static std::unique_ptr<LegacyBufferInfoGetter> CreateInstance(); static uint32_t ConvertHalFormatToDrm(uint32_t hal_format); + + // NOLINTNEXTLINE:(readability-identifier-naming) const gralloc_module_t *gralloc_; }; -#define LEGACY_BUFFER_INFO_GETTER(getter_) \ - LegacyBufferInfoGetter *LegacyBufferInfoGetter::CreateInstance() { \ - auto *instance = new getter_(); \ - if (!instance) \ - return NULL; \ - \ - int ret = instance->Init(); \ - if (ret) { \ - ALOGE("Failed to initialize the " #getter_ " getter %d", ret); \ - delete instance; \ - return NULL; \ - } \ - return instance; \ +#ifdef DISABLE_LEGACY_GETTERS +#define LEGACY_BUFFER_INFO_GETTER(getter_) +#else +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define LEGACY_BUFFER_INFO_GETTER(getter_) \ + std::unique_ptr<LegacyBufferInfoGetter> \ + LegacyBufferInfoGetter::CreateInstance() { \ + auto instance = std::make_unique<getter_>(); \ + if (instance) { \ + int err = instance->Init(); \ + if (err) { \ + ALOGE("Failed to initialize the " #getter_ " getter %d", err); \ + instance.reset(); \ + } \ + err = instance->ValidateGralloc(); \ + if (err) { \ + instance.reset(); \ + } \ + } \ + return std::move(instance); \ } +#endif } // namespace android #endif diff --git a/bufferinfo/BufferInfoMapperMetadata.cpp b/bufferinfo/BufferInfoMapperMetadata.cpp index 3aabeb5..2f08a76 100644 --- a/bufferinfo/BufferInfoMapperMetadata.cpp +++ b/bufferinfo/BufferInfoMapperMetadata.cpp @@ -21,13 +21,13 @@ #include "BufferInfoMapperMetadata.h" #include <drm/drm_fourcc.h> -#include <inttypes.h> -#include <log/log.h> #include <ui/GraphicBufferMapper.h> #include <xf86drm.h> #include <xf86drmMode.h> -using android::hardware::graphics::common::V1_1::BufferUsage; +#include <cinttypes> + +#include "utils/log.h" namespace android { @@ -47,42 +47,54 @@ BufferInfoGetter *BufferInfoMapperMetadata::CreateInstance() { */ int __attribute__((weak)) BufferInfoMapperMetadata::GetFds(buffer_handle_t handle, hwc_drm_bo_t *bo) { - int num_fds = handle->numFds; + int fd_index = 0; - if (num_fds >= 1 && num_fds <= 2) { - if (IsDrmFormatRgb(bo->format)) { - bo->prime_fds[0] = handle->data[0]; - } else { - bo->prime_fds[0] = bo->prime_fds[1] = bo->prime_fds[2] = handle->data[0]; - } - if (bo->prime_fds[0] <= 0) { - ALOGE("Encountered invalid fd %d", bo->prime_fds[0]); - return android::BAD_VALUE; + if (handle->numFds <= 0) { + ALOGE("Handle has no fds"); + return android::BAD_VALUE; + } + + for (int i = 0; i < kHwcDrmBoMaxPlanes; i++) { + /* If no size, we're out of usable planes */ + if (bo->sizes[i] <= 0) { + if (i == 0) { + ALOGE("Bad handle metadata"); + return android::BAD_VALUE; + } + break; } - } else if (num_fds >= 3) { - bo->prime_fds[0] = handle->data[0]; - bo->prime_fds[1] = handle->data[1]; - bo->prime_fds[2] = handle->data[2]; - for (int i = 0; i < 3; i++) { - if (bo->prime_fds[i] <= 0) { - ALOGE("Encountered invalid fd %d", bo->prime_fds[i]); + /* + * If the offset is zero, its multi-buffer + * so move to the next fd + */ + if (i != 0 && bo->offsets[i] == 0) { + fd_index++; + if (fd_index >= handle->numFds) { + ALOGE("Handle has no more fds"); return android::BAD_VALUE; } } + + bo->prime_fds[i] = handle->data[fd_index]; + if (bo->prime_fds[i] <= 0) { + ALOGE("Invalid prime fd"); + return android::BAD_VALUE; + } } + return 0; } int BufferInfoMapperMetadata::ConvertBoInfo(buffer_handle_t handle, hwc_drm_bo_t *bo) { GraphicBufferMapper &mapper = GraphicBufferMapper::getInstance(); - if (!handle) + if (handle == nullptr) return -EINVAL; uint64_t usage = 0; int err = mapper.getUsage(handle, &usage); - if (err) { + if (err != 0) { ALOGE("Failed to get usage err=%d", err); return err; } @@ -90,28 +102,27 @@ int BufferInfoMapperMetadata::ConvertBoInfo(buffer_handle_t handle, ui::PixelFormat hal_format; err = mapper.getPixelFormatRequested(handle, &hal_format); - if (err) { + if (err != 0) { ALOGE("Failed to get HAL Pixel Format err=%d", err); return err; } bo->hal_format = static_cast<uint32_t>(hal_format); err = mapper.getPixelFormatFourCC(handle, &bo->format); - if (err) { + if (err != 0) { ALOGE("Failed to get FourCC format err=%d", err); return err; } err = mapper.getPixelFormatModifier(handle, &bo->modifiers[0]); - if (err) { + if (err != 0) { ALOGE("Failed to get DRM Modifier err=%d", err); return err; } - bo->with_modifiers = true; uint64_t width = 0; err = mapper.getWidth(handle, &width); - if (err) { + if (err != 0) { ALOGE("Failed to get Width err=%d", err); return err; } @@ -119,7 +130,7 @@ int BufferInfoMapperMetadata::ConvertBoInfo(buffer_handle_t handle, uint64_t height = 0; err = mapper.getHeight(handle, &height); - if (err) { + if (err != 0) { ALOGE("Failed to get Height err=%d", err); return err; } @@ -127,7 +138,7 @@ int BufferInfoMapperMetadata::ConvertBoInfo(buffer_handle_t handle, std::vector<ui::PlaneLayout> layouts; err = mapper.getPlaneLayouts(handle, &layouts); - if (err) { + if (err != 0) { ALOGE("Failed to get Plane Layouts err=%d", err); return err; } @@ -136,6 +147,7 @@ int BufferInfoMapperMetadata::ConvertBoInfo(buffer_handle_t handle, bo->modifiers[i] = bo->modifiers[0]; bo->pitches[i] = layouts[i].strideInBytes; bo->offsets[i] = layouts[i].offsetInBytes; + bo->sizes[i] = layouts[i].totalSizeInBytes; } return GetFds(handle, bo); diff --git a/bufferinfo/legacy/BufferInfoImagination.cpp b/bufferinfo/legacy/BufferInfoImagination.cpp index 84c177e..691dd14 100644 --- a/bufferinfo/legacy/BufferInfoImagination.cpp +++ b/bufferinfo/legacy/BufferInfoImagination.cpp @@ -18,10 +18,12 @@ #include "BufferInfoImagination.h" -#include <log/log.h> #include <xf86drm.h> +#include <cerrno> + #include "img_gralloc1_public.h" +#include "utils/log.h" namespace android { @@ -29,7 +31,7 @@ LEGACY_BUFFER_INFO_GETTER(BufferInfoImagination); int BufferInfoImagination::ConvertBoInfo(buffer_handle_t handle, hwc_drm_bo_t *bo) { - IMG_native_handle_t *hnd = (IMG_native_handle_t *)handle; + auto *hnd = (IMG_native_handle_t *)handle; if (!hnd) return -EINVAL; diff --git a/bufferinfo/legacy/BufferInfoLibdrm.cpp b/bufferinfo/legacy/BufferInfoLibdrm.cpp index 3f6a6fd..6baf6bb 100644 --- a/bufferinfo/legacy/BufferInfoLibdrm.cpp +++ b/bufferinfo/legacy/BufferInfoLibdrm.cpp @@ -18,65 +18,74 @@ #include "BufferInfoLibdrm.h" -#include <cutils/properties.h> #include <gralloc_handle.h> #include <hardware/gralloc.h> -#include <log/log.h> #include <xf86drm.h> #include <xf86drmMode.h> +#include <mutex> + +#include "utils/log.h" +#include "utils/properties.h" + namespace android { LEGACY_BUFFER_INFO_GETTER(BufferInfoLibdrm); enum chroma_order { - YCbCr, - YCrCb, + kYCbCr, + kYCrCb, }; -struct droid_yuv_format { +struct DroidYuvFormat { /* Lookup keys */ - int native; /* HAL_PIXEL_FORMAT_ */ + uint32_t native; /* HAL_PIXEL_FORMAT_ */ enum chroma_order chroma_order; /* chroma order is {Cb, Cr} or {Cr, Cb} */ - int chroma_step; /* Distance in bytes between subsequent chroma pixels. */ + size_t chroma_step; /* Distance in bytes between subsequent chroma pixels. */ /* Result */ int fourcc; /* DRM_FORMAT_ */ }; +#ifndef DRM_FORMAT_XYUV8888 +#define DRM_FORMAT_XYUV8888 \ + fourcc_code('X', 'Y', 'U', 'V') /* [31:0] X:Y:Cb:Cr 8:8:8:8 little endian */ +#endif + /* The following table is used to look up a DRI image FourCC based * on native format and information contained in android_ycbcr struct. */ -static const struct droid_yuv_format droid_yuv_formats[] = { +static const struct DroidYuvFormat kDroidYuvFormats[] = { /* Native format, YCrCb, Chroma step, DRI image FourCC */ - {HAL_PIXEL_FORMAT_YCbCr_420_888, YCbCr, 2, DRM_FORMAT_NV12}, - {HAL_PIXEL_FORMAT_YCbCr_420_888, YCbCr, 1, DRM_FORMAT_YUV420}, - {HAL_PIXEL_FORMAT_YCbCr_420_888, YCrCb, 1, DRM_FORMAT_YVU420}, - {HAL_PIXEL_FORMAT_YV12, YCrCb, 1, DRM_FORMAT_YVU420}, + {HAL_PIXEL_FORMAT_YCbCr_420_888, kYCbCr, 2, DRM_FORMAT_NV12}, + {HAL_PIXEL_FORMAT_YCbCr_420_888, kYCbCr, 1, DRM_FORMAT_YUV420}, + {HAL_PIXEL_FORMAT_YCbCr_420_888, kYCrCb, 1, DRM_FORMAT_YVU420}, + {HAL_PIXEL_FORMAT_YV12, kYCrCb, 1, DRM_FORMAT_YVU420}, /* HACK: See droid_create_image_from_prime_fds() and * https://issuetracker.google.com/32077885. */ - {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, YCbCr, 2, DRM_FORMAT_NV12}, - {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, YCbCr, 1, DRM_FORMAT_YUV420}, - {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, YCrCb, 1, DRM_FORMAT_YVU420}, - {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, YCrCb, 1, DRM_FORMAT_AYUV}, - {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, YCrCb, 1, DRM_FORMAT_XYUV8888}, + {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, kYCbCr, 2, DRM_FORMAT_NV12}, + {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, kYCbCr, 1, DRM_FORMAT_YUV420}, + {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, kYCrCb, 1, DRM_FORMAT_YVU420}, + {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, kYCrCb, 1, DRM_FORMAT_AYUV}, + {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, kYCrCb, 1, DRM_FORMAT_XYUV8888}, }; #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) -static int get_fourcc_yuv(int native, enum chroma_order chroma_order, - int chroma_step) { - for (int i = 0; i < ARRAY_SIZE(droid_yuv_formats); ++i) - if (droid_yuv_formats[i].native == native && - droid_yuv_formats[i].chroma_order == chroma_order && - droid_yuv_formats[i].chroma_step == chroma_step) - return droid_yuv_formats[i].fourcc; +static uint32_t get_fourcc_yuv(uint32_t native, enum chroma_order chroma_order, + size_t chroma_step) { + for (auto droid_yuv_format : kDroidYuvFormats) + if (droid_yuv_format.native == native && + droid_yuv_format.chroma_order == chroma_order && + droid_yuv_format.chroma_step == chroma_step) + return droid_yuv_format.fourcc; - return -1; + return UINT32_MAX; } -static bool is_yuv(int native) { - for (int i = 0; i < ARRAY_SIZE(droid_yuv_formats); ++i) - if (droid_yuv_formats[i].native == native) +static bool is_yuv(uint32_t native) { + // NOLINTNEXTLINE(readability-use-anyofallof) + for (auto droid_yuv_format : kDroidYuvFormats) + if (droid_yuv_format.native == native) return true; return false; @@ -84,9 +93,9 @@ static bool is_yuv(int native) { bool BufferInfoLibdrm::GetYuvPlaneInfo(int num_fds, buffer_handle_t handle, hwc_drm_bo_t *bo) { - struct android_ycbcr ycbcr; - enum chroma_order chroma_order; - int ret; + struct android_ycbcr ycbcr {}; + enum chroma_order chroma_order {}; + int ret = 0; if (!gralloc_->lock_ycbcr) { static std::once_flag once; @@ -109,11 +118,11 @@ bool BufferInfoLibdrm::GetYuvPlaneInfo(int num_fds, buffer_handle_t handle, bo->offsets[0] = (size_t)ycbcr.y; /* We assume here that all the planes are located in one DMA-buf. */ if ((size_t)ycbcr.cr < (size_t)ycbcr.cb) { - chroma_order = YCrCb; + chroma_order = kYCrCb; bo->offsets[1] = (size_t)ycbcr.cr; bo->offsets[2] = (size_t)ycbcr.cb; } else { - chroma_order = YCbCr; + chroma_order = kYCbCr; bo->offsets[1] = (size_t)ycbcr.cb; bo->offsets[2] = (size_t)ycbcr.cr; } @@ -128,11 +137,11 @@ bool BufferInfoLibdrm::GetYuvPlaneInfo(int num_fds, buffer_handle_t handle, /* .chroma_step is the byte distance between the same chroma channel * values of subsequent pixels, assumed to be the same for Cb and Cr. */ bo->format = get_fourcc_yuv(bo->hal_format, chroma_order, ycbcr.chroma_step); - if (bo->format == -1) { + if (bo->format == UINT32_MAX) { ALOGW( "unsupported YUV format, native = %x, chroma_order = %s, chroma_step = " "%d", - bo->hal_format, chroma_order == YCbCr ? "YCbCr" : "YCrCb", + bo->hal_format, chroma_order == kYCbCr ? "YCbCr" : "YCrCb", (int)ycbcr.chroma_step); return false; } @@ -171,8 +180,6 @@ int BufferInfoLibdrm::ConvertBoInfo(buffer_handle_t handle, hwc_drm_bo_t *bo) { #endif #if GRALLOC_HANDLE_VERSION == 4 bo->modifiers[0] = gr_handle->modifier; - bo->with_modifiers = gr_handle->modifier != DRM_FORMAT_MOD_NONE && - gr_handle->modifier != DRM_FORMAT_MOD_INVALID; #endif bo->usage = gr_handle->usage; @@ -184,7 +191,18 @@ int BufferInfoLibdrm::ConvertBoInfo(buffer_handle_t handle, hwc_drm_bo_t *bo) { } else { bo->pitches[0] = gr_handle->stride; bo->offsets[0] = 0; - bo->format = ConvertHalFormatToDrm(gr_handle->format); + + /* FOSS graphic components (gbm_gralloc, mesa3d) are translating + * HAL_PIXEL_FORMAT_RGB_565 to DRM_FORMAT_RGB565 without swapping + * the R and B components. Same must be done here. */ + switch (bo->hal_format) { + case HAL_PIXEL_FORMAT_RGB_565: + bo->format = DRM_FORMAT_RGB565; + break; + default: + bo->format = ConvertHalFormatToDrm(gr_handle->format); + } + if (bo->format == DRM_FORMAT_INVALID) return -EINVAL; } @@ -192,4 +210,20 @@ int BufferInfoLibdrm::ConvertBoInfo(buffer_handle_t handle, hwc_drm_bo_t *bo) { return 0; } +constexpr char gbm_gralloc_module_name[] = "GBM Memory Allocator"; +constexpr char drm_gralloc_module_name[] = "DRM Memory Allocator"; + +int BufferInfoLibdrm::ValidateGralloc() { + if (strcmp(gralloc_->common.name, drm_gralloc_module_name) != 0 && + strcmp(gralloc_->common.name, gbm_gralloc_module_name) != 0) { + ALOGE( + "Gralloc name isn't valid: Expected: \"%s\" or \"%s\", Actual: \"%s\"", + gbm_gralloc_module_name, drm_gralloc_module_name, + gralloc_->common.name); + return -EINVAL; + } + + return 0; +} + } // namespace android diff --git a/bufferinfo/legacy/BufferInfoLibdrm.h b/bufferinfo/legacy/BufferInfoLibdrm.h index 4d37d00..cad8add 100644 --- a/bufferinfo/legacy/BufferInfoLibdrm.h +++ b/bufferinfo/legacy/BufferInfoLibdrm.h @@ -27,6 +27,7 @@ class BufferInfoLibdrm : public LegacyBufferInfoGetter { public: using LegacyBufferInfoGetter::LegacyBufferInfoGetter; int ConvertBoInfo(buffer_handle_t handle, hwc_drm_bo_t *bo) override; + int ValidateGralloc() override; private: bool GetYuvPlaneInfo(int num_fds, buffer_handle_t handle, hwc_drm_bo_t *bo); diff --git a/bufferinfo/legacy/BufferInfoMaliHisi.cpp b/bufferinfo/legacy/BufferInfoMaliHisi.cpp index ab5579c..5fc413a 100644 --- a/bufferinfo/legacy/BufferInfoMaliHisi.cpp +++ b/bufferinfo/legacy/BufferInfoMaliHisi.cpp @@ -18,13 +18,13 @@ #include "BufferInfoMaliHisi.h" -#include <log/log.h> #include <xf86drm.h> #include <xf86drmMode.h> #include <cinttypes> #include "gralloc_priv.h" +#include "utils/log.h" #define MALI_ALIGN(value, base) (((value) + ((base)-1)) & ~((base)-1)) @@ -68,10 +68,9 @@ uint64_t BufferInfoMaliHisi::ConvertGrallocFormatToDrmModifiers( int BufferInfoMaliHisi::ConvertBoInfo(buffer_handle_t handle, hwc_drm_bo_t *bo) { - bool is_rgb; + bool is_rgb = false; - private_handle_t const *hnd = reinterpret_cast<private_handle_t const *>( - handle); + const auto *hnd = (private_handle_t const *)handle; if (!hnd) return -EINVAL; @@ -120,8 +119,6 @@ int BufferInfoMaliHisi::ConvertBoInfo(buffer_handle_t handle, break; } - bo->with_modifiers = true; - return 0; } diff --git a/bufferinfo/legacy/BufferInfoMaliMediatek.cpp b/bufferinfo/legacy/BufferInfoMaliMediatek.cpp index ce47343..7e6f3a8 100644 --- a/bufferinfo/legacy/BufferInfoMaliMediatek.cpp +++ b/bufferinfo/legacy/BufferInfoMaliMediatek.cpp @@ -19,7 +19,6 @@ #include "BufferInfoMaliMediatek.h" #include <hardware/gralloc.h> -#include <log/log.h> #include <stdatomic.h> #include <xf86drm.h> #include <xf86drmMode.h> @@ -27,6 +26,7 @@ #include <cinttypes> #include "gralloc_priv.h" +#include "utils/log.h" namespace android { @@ -34,8 +34,7 @@ LEGACY_BUFFER_INFO_GETTER(BufferInfoMaliMediatek); int BufferInfoMaliMediatek::ConvertBoInfo(buffer_handle_t handle, hwc_drm_bo_t *bo) { - private_handle_t const *hnd = reinterpret_cast<private_handle_t const *>( - handle); + const auto *hnd = (private_handle_t const *)handle; if (!hnd) return -EINVAL; diff --git a/bufferinfo/legacy/BufferInfoMaliMeson.cpp b/bufferinfo/legacy/BufferInfoMaliMeson.cpp index b6896e1..9daf542 100644 --- a/bufferinfo/legacy/BufferInfoMaliMeson.cpp +++ b/bufferinfo/legacy/BufferInfoMaliMeson.cpp @@ -18,13 +18,13 @@ #include "BufferInfoMaliMeson.h" -#include <log/log.h> #include <xf86drm.h> #include <xf86drmMode.h> #include <cinttypes> #include "gralloc_priv.h" +#include "utils/log.h" namespace android { @@ -63,8 +63,7 @@ uint64_t BufferInfoMaliMeson::ConvertGrallocFormatToDrmModifiers( int BufferInfoMaliMeson::ConvertBoInfo(buffer_handle_t handle, hwc_drm_bo_t *bo) { - private_handle_t const *hnd = reinterpret_cast<private_handle_t const *>( - handle); + const auto *hnd = (private_handle_t const *)handle; if (!hnd) return -EINVAL; @@ -87,8 +86,6 @@ int BufferInfoMaliMeson::ConvertBoInfo(buffer_handle_t handle, bo->pitches[0] = hnd->byte_stride; bo->offsets[0] = 0; - bo->with_modifiers = true; - return 0; } diff --git a/bufferinfo/legacy/BufferInfoMinigbm.cpp b/bufferinfo/legacy/BufferInfoMinigbm.cpp index 860de08..777c2b7 100644 --- a/bufferinfo/legacy/BufferInfoMinigbm.cpp +++ b/bufferinfo/legacy/BufferInfoMinigbm.cpp @@ -18,29 +18,106 @@ #include "BufferInfoMinigbm.h" -#include <log/log.h> #include <xf86drm.h> #include <xf86drmMode.h> -#include "cros_gralloc_handle.h" +#include <cerrno> +#include <cstring> +#include "utils/log.h" namespace android { LEGACY_BUFFER_INFO_GETTER(BufferInfoMinigbm); +constexpr int CROS_GRALLOC_DRM_GET_FORMAT = 1; +constexpr int CROS_GRALLOC_DRM_GET_DIMENSIONS = 2; +constexpr int CROS_GRALLOC_DRM_GET_BUFFER_INFO = 4; +constexpr int CROS_GRALLOC_DRM_GET_USAGE = 5; + +struct cros_gralloc0_buffer_info { + uint32_t drm_fourcc; + int num_fds; + int fds[4]; + uint64_t modifier; + int offset[4]; + int stride[4]; +}; + int BufferInfoMinigbm::ConvertBoInfo(buffer_handle_t handle, hwc_drm_bo_t *bo) { - cros_gralloc_handle *gr_handle = (cros_gralloc_handle *)handle; - if (!gr_handle) + if (handle == nullptr) { + return -EINVAL; + } + + uint32_t width{}; + uint32_t height{}; + if (gralloc_->perform(gralloc_, CROS_GRALLOC_DRM_GET_DIMENSIONS, handle, + &width, &height) != 0) { + ALOGE( + "CROS_GRALLOC_DRM_GET_DIMENSIONS operation has failed. " + "Please ensure you are using the latest minigbm."); + return -EINVAL; + } + + int32_t droid_format{}; + if (gralloc_->perform(gralloc_, CROS_GRALLOC_DRM_GET_FORMAT, handle, + &droid_format) != 0) { + ALOGE( + "CROS_GRALLOC_DRM_GET_FORMAT operation has failed. " + "Please ensure you are using the latest minigbm."); return -EINVAL; + } + + uint32_t usage{}; + if (gralloc_->perform(gralloc_, CROS_GRALLOC_DRM_GET_USAGE, handle, &usage) != + 0) { + ALOGE( + "CROS_GRALLOC_DRM_GET_USAGE operation has failed. " + "Please ensure you are using the latest minigbm."); + return -EINVAL; + } + + struct cros_gralloc0_buffer_info info {}; + if (gralloc_->perform(gralloc_, CROS_GRALLOC_DRM_GET_BUFFER_INFO, handle, + &info) != 0) { + ALOGE( + "CROS_GRALLOC_DRM_GET_BUFFER_INFO operation has failed. " + "Please ensure you are using the latest minigbm."); + return -EINVAL; + } + + bo->width = width; + bo->height = height; - bo->width = gr_handle->width; - bo->height = gr_handle->height; - bo->hal_format = gr_handle->droid_format; - bo->format = gr_handle->format; - bo->usage = gr_handle->usage; - bo->prime_fds[0] = gr_handle->fds[0]; - bo->pitches[0] = gr_handle->strides[0]; - bo->offsets[0] = gr_handle->offsets[0]; + bo->hal_format = droid_format; + + bo->format = info.drm_fourcc; + bo->usage = usage; + + for (int i = 0; i < info.num_fds; i++) { + bo->modifiers[i] = info.modifier; + bo->prime_fds[i] = info.fds[i]; + bo->pitches[i] = info.stride[i]; + bo->offsets[i] = info.offset[i]; + } + + return 0; +} + +constexpr char cros_gralloc_module_name[] = "CrOS Gralloc"; + +int BufferInfoMinigbm::ValidateGralloc() { + if (strcmp(gralloc_->common.name, cros_gralloc_module_name) != 0) { + ALOGE("Gralloc name isn't valid: Expected: \"%s\", Actual: \"%s\"", + cros_gralloc_module_name, gralloc_->common.name); + return -EINVAL; + } + + if (gralloc_->perform == nullptr) { + ALOGE( + "CrOS gralloc has no perform call implemented. Please upgrade your " + "minigbm."); + return -EINVAL; + } return 0; } diff --git a/bufferinfo/legacy/BufferInfoMinigbm.h b/bufferinfo/legacy/BufferInfoMinigbm.h index bff9d74..04cc2ae 100644 --- a/bufferinfo/legacy/BufferInfoMinigbm.h +++ b/bufferinfo/legacy/BufferInfoMinigbm.h @@ -27,6 +27,7 @@ class BufferInfoMinigbm : public LegacyBufferInfoGetter { public: using LegacyBufferInfoGetter::LegacyBufferInfoGetter; int ConvertBoInfo(buffer_handle_t handle, hwc_drm_bo_t *bo) override; + int ValidateGralloc() override; }; } // namespace android diff --git a/build_deploy.sh b/build_deploy.sh new file mode 100755 index 0000000..ef25e5c --- /dev/null +++ b/build_deploy.sh @@ -0,0 +1,26 @@ +#!/bin/bash -e + +# To see logs after deploy run: $ HWCLOG=1 TESTDEV=<DEV> ./build_deploy.sh + +[ -z "$TESTDEV" ] && echo "Run $ TESTDEV=<Your lunch target> ./build_deploy.sh" && false + +cd ../.. +. build/envsetup.sh +lunch $TESTDEV +cd - + +mm + +adb root && adb remount && adb sync vendor + +adb shell stop +adb shell stop vendor.hwcomposer-2-1 && adb shell start vendor.hwcomposer-2-1 || true +adb shell stop vendor.hwcomposer-2-2 && adb shell start vendor.hwcomposer-2-2 || true +adb shell stop vendor.hwcomposer-2-3 && adb shell start vendor.hwcomposer-2-3 || true +adb shell stop vendor.hwcomposer-2-4 && adb shell start vendor.hwcomposer-2-4 || true + +[ $HWCLOG -eq "1" ] && adb logcat -c + +adb shell start + +[ $HWCLOG -eq "1" ] && adb logcat | grep -i hwc diff --git a/compositor/DrmDisplayComposition.cpp b/compositor/DrmDisplayComposition.cpp deleted file mode 100644 index 4d2e19a..0000000 --- a/compositor/DrmDisplayComposition.cpp +++ /dev/null @@ -1,297 +0,0 @@ -/* - * Copyright (C) 2015 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "hwc-drm-display-composition" - -#include "DrmDisplayComposition.h" - -#include <log/log.h> -#include <stdlib.h> -#include <sync/sync.h> -#include <xf86drmMode.h> - -#include <algorithm> -#include <unordered_set> - -#include "DrmDisplayCompositor.h" -#include "Planner.h" -#include "drm/DrmDevice.h" - -namespace android { - -DrmDisplayComposition::~DrmDisplayComposition() { -} - -int DrmDisplayComposition::Init(DrmDevice *drm, DrmCrtc *crtc, - Importer *importer, Planner *planner, - uint64_t frame_no) { - drm_ = drm; - crtc_ = crtc; // Can be NULL if we haven't modeset yet - importer_ = importer; - planner_ = planner; - frame_no_ = frame_no; - - return 0; -} - -bool DrmDisplayComposition::validate_composition_type(DrmCompositionType des) { - return type_ == DRM_COMPOSITION_TYPE_EMPTY || type_ == des; -} - -int DrmDisplayComposition::SetLayers(DrmHwcLayer *layers, size_t num_layers, - bool geometry_changed) { - if (!validate_composition_type(DRM_COMPOSITION_TYPE_FRAME)) - return -EINVAL; - - geometry_changed_ = geometry_changed; - - for (size_t layer_index = 0; layer_index < num_layers; layer_index++) { - layers_.emplace_back(std::move(layers[layer_index])); - } - - type_ = DRM_COMPOSITION_TYPE_FRAME; - return 0; -} - -int DrmDisplayComposition::SetDpmsMode(uint32_t dpms_mode) { - if (!validate_composition_type(DRM_COMPOSITION_TYPE_DPMS)) - return -EINVAL; - dpms_mode_ = dpms_mode; - type_ = DRM_COMPOSITION_TYPE_DPMS; - return 0; -} - -int DrmDisplayComposition::SetDisplayMode(const DrmMode &display_mode) { - if (!validate_composition_type(DRM_COMPOSITION_TYPE_MODESET)) - return -EINVAL; - display_mode_ = display_mode; - dpms_mode_ = DRM_MODE_DPMS_ON; - type_ = DRM_COMPOSITION_TYPE_MODESET; - return 0; -} - -int DrmDisplayComposition::AddPlaneDisable(DrmPlane *plane) { - composition_planes_.emplace_back(DrmCompositionPlane::Type::kDisable, plane, - crtc_); - return 0; -} - -int DrmDisplayComposition::AddPlaneComposition(DrmCompositionPlane plane) { - composition_planes_.emplace_back(std::move(plane)); - return 0; -} - -int DrmDisplayComposition::Plan(std::vector<DrmPlane *> *primary_planes, - std::vector<DrmPlane *> *overlay_planes) { - if (type_ != DRM_COMPOSITION_TYPE_FRAME) - return 0; - - std::map<size_t, DrmHwcLayer *> to_composite; - - for (size_t i = 0; i < layers_.size(); ++i) - to_composite.emplace(std::make_pair(i, &layers_[i])); - - int ret; - std::tie(ret, - composition_planes_) = planner_->ProvisionPlanes(to_composite, crtc_, - primary_planes, - overlay_planes); - if (ret) { - ALOGE("Planner failed provisioning planes ret=%d", ret); - return ret; - } - - // Remove the planes we used from the pool before returning. This ensures they - // won't be reused by another display in the composition. - for (auto &i : composition_planes_) { - if (!i.plane()) - continue; - - // make sure that source layers are ordered based on zorder - std::sort(i.source_layers().begin(), i.source_layers().end()); - - std::vector<DrmPlane *> *container; - if (i.plane()->type() == DRM_PLANE_TYPE_PRIMARY) - container = primary_planes; - else - container = overlay_planes; - for (auto j = container->begin(); j != container->end(); ++j) { - if (*j == i.plane()) { - container->erase(j); - break; - } - } - } - - return 0; -} - -static const char *DrmCompositionTypeToString(DrmCompositionType type) { - switch (type) { - case DRM_COMPOSITION_TYPE_EMPTY: - return "EMPTY"; - case DRM_COMPOSITION_TYPE_FRAME: - return "FRAME"; - case DRM_COMPOSITION_TYPE_DPMS: - return "DPMS"; - case DRM_COMPOSITION_TYPE_MODESET: - return "MODESET"; - default: - return "<invalid>"; - } -} - -static const char *DPMSModeToString(int dpms_mode) { - switch (dpms_mode) { - case DRM_MODE_DPMS_ON: - return "ON"; - case DRM_MODE_DPMS_OFF: - return "OFF"; - default: - return "<invalid>"; - } -} - -static void DumpBuffer(const DrmHwcBuffer &buffer, std::ostringstream *out) { - if (!buffer) { - *out << "buffer=<invalid>"; - return; - } - - *out << "buffer[w/h/format]="; - *out << buffer->width << "/" << buffer->height << "/" << buffer->format; -} - -static void DumpTransform(uint32_t transform, std::ostringstream *out) { - *out << "["; - - if (transform == 0) - *out << "IDENTITY"; - - bool separator = false; - if (transform & DrmHwcTransform::kFlipH) { - *out << "FLIPH"; - separator = true; - } - if (transform & DrmHwcTransform::kFlipV) { - if (separator) - *out << "|"; - *out << "FLIPV"; - separator = true; - } - if (transform & DrmHwcTransform::kRotate90) { - if (separator) - *out << "|"; - *out << "ROTATE90"; - separator = true; - } - if (transform & DrmHwcTransform::kRotate180) { - if (separator) - *out << "|"; - *out << "ROTATE180"; - separator = true; - } - if (transform & DrmHwcTransform::kRotate270) { - if (separator) - *out << "|"; - *out << "ROTATE270"; - separator = true; - } - - uint32_t valid_bits = DrmHwcTransform::kFlipH | DrmHwcTransform::kFlipH | - DrmHwcTransform::kRotate90 | - DrmHwcTransform::kRotate180 | - DrmHwcTransform::kRotate270; - if (transform & ~valid_bits) { - if (separator) - *out << "|"; - *out << "INVALID"; - } - *out << "]"; -} - -static const char *BlendingToString(DrmHwcBlending blending) { - switch (blending) { - case DrmHwcBlending::kNone: - return "NONE"; - case DrmHwcBlending::kPreMult: - return "PREMULT"; - case DrmHwcBlending::kCoverage: - return "COVERAGE"; - default: - return "<invalid>"; - } -} - -void DrmDisplayComposition::Dump(std::ostringstream *out) const { - *out << "----DrmDisplayComposition" - << " crtc=" << (crtc_ ? crtc_->id() : -1) - << " type=" << DrmCompositionTypeToString(type_); - - switch (type_) { - case DRM_COMPOSITION_TYPE_DPMS: - *out << " dpms_mode=" << DPMSModeToString(dpms_mode_); - break; - case DRM_COMPOSITION_TYPE_MODESET: - *out << " display_mode=" << display_mode_.h_display() << "x" - << display_mode_.v_display(); - break; - default: - break; - } - - *out << " Layers: count=" << layers_.size() << "\n"; - for (size_t i = 0; i < layers_.size(); i++) { - const DrmHwcLayer &layer = layers_[i]; - *out << " [" << i << "] "; - - DumpBuffer(layer.buffer, out); - - if (layer.protected_usage()) - *out << " protected"; - - *out << " transform="; - DumpTransform(layer.transform, out); - *out << " blending[a=" << (int)layer.alpha - << "]=" << BlendingToString(layer.blending) << "\n"; - } - - *out << " Planes: count=" << composition_planes_.size() << "\n"; - for (size_t i = 0; i < composition_planes_.size(); i++) { - const DrmCompositionPlane &comp_plane = composition_planes_[i]; - *out << " [" << i << "]" - << " plane=" << (comp_plane.plane() ? comp_plane.plane()->id() : -1) - << " type="; - switch (comp_plane.type()) { - case DrmCompositionPlane::Type::kDisable: - *out << "DISABLE"; - break; - case DrmCompositionPlane::Type::kLayer: - *out << "LAYER"; - break; - default: - *out << "<invalid>"; - break; - } - - *out << " source_layer="; - for (auto i : comp_plane.source_layers()) { - *out << i << " "; - } - *out << "\n"; - } -} -} // namespace android diff --git a/compositor/DrmDisplayComposition.h b/compositor/DrmDisplayComposition.h deleted file mode 100644 index 73a9024..0000000 --- a/compositor/DrmDisplayComposition.h +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (C) 2015 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ANDROID_DRM_DISPLAY_COMPOSITION_H_ -#define ANDROID_DRM_DISPLAY_COMPOSITION_H_ - -#include <hardware/hardware.h> -#include <hardware/hwcomposer.h> - -#include <sstream> -#include <vector> - -#include "drm/DrmCrtc.h" -#include "drm/DrmPlane.h" -#include "drmhwcomposer.h" - -namespace android { - -class Importer; -class Planner; -class SquashState; - -enum DrmCompositionType { - DRM_COMPOSITION_TYPE_EMPTY, - DRM_COMPOSITION_TYPE_FRAME, - DRM_COMPOSITION_TYPE_DPMS, - DRM_COMPOSITION_TYPE_MODESET, -}; - -struct DrmCompositionDisplayLayersMap { - int display; - bool geometry_changed = true; - std::vector<DrmHwcLayer> layers; - - DrmCompositionDisplayLayersMap() = default; - DrmCompositionDisplayLayersMap(DrmCompositionDisplayLayersMap &&rhs) = - default; -}; - -struct DrmCompositionRegion { - std::vector<size_t> source_layers; -}; - -class DrmCompositionPlane { - public: - enum class Type : int32_t { - kDisable, - kLayer, - }; - - DrmCompositionPlane() = default; - DrmCompositionPlane(DrmCompositionPlane &&rhs) = default; - DrmCompositionPlane &operator=(DrmCompositionPlane &&other) = default; - DrmCompositionPlane(Type type, DrmPlane *plane, DrmCrtc *crtc) - : type_(type), plane_(plane), crtc_(crtc) { - } - DrmCompositionPlane(Type type, DrmPlane *plane, DrmCrtc *crtc, - size_t source_layer) - : type_(type), - plane_(plane), - crtc_(crtc), - source_layers_(1, source_layer) { - } - - Type type() const { - return type_; - } - - DrmPlane *plane() const { - return plane_; - } - void set_plane(DrmPlane *plane) { - plane_ = plane; - } - - DrmCrtc *crtc() const { - return crtc_; - } - - std::vector<size_t> &source_layers() { - return source_layers_; - } - - const std::vector<size_t> &source_layers() const { - return source_layers_; - } - - private: - Type type_ = Type::kDisable; - DrmPlane *plane_ = NULL; - DrmCrtc *crtc_ = NULL; - std::vector<size_t> source_layers_; -}; - -class DrmDisplayComposition { - public: - DrmDisplayComposition() = default; - DrmDisplayComposition(const DrmDisplayComposition &) = delete; - ~DrmDisplayComposition(); - - int Init(DrmDevice *drm, DrmCrtc *crtc, Importer *importer, Planner *planner, - uint64_t frame_no); - - int SetLayers(DrmHwcLayer *layers, size_t num_layers, bool geometry_changed); - int AddPlaneComposition(DrmCompositionPlane plane); - int AddPlaneDisable(DrmPlane *plane); - int SetDpmsMode(uint32_t dpms_mode); - int SetDisplayMode(const DrmMode &display_mode); - - int Plan(std::vector<DrmPlane *> *primary_planes, - std::vector<DrmPlane *> *overlay_planes); - - std::vector<DrmHwcLayer> &layers() { - return layers_; - } - - std::vector<DrmCompositionPlane> &composition_planes() { - return composition_planes_; - } - - bool geometry_changed() const { - return geometry_changed_; - } - - uint64_t frame_no() const { - return frame_no_; - } - - DrmCompositionType type() const { - return type_; - } - - uint32_t dpms_mode() const { - return dpms_mode_; - } - - const DrmMode &display_mode() const { - return display_mode_; - } - - DrmCrtc *crtc() const { - return crtc_; - } - - Importer *importer() const { - return importer_; - } - - Planner *planner() const { - return planner_; - } - - int take_out_fence() { - return out_fence_.Release(); - } - - void set_out_fence(int out_fence) { - out_fence_.Set(out_fence); - } - - void Dump(std::ostringstream *out) const; - - private: - bool validate_composition_type(DrmCompositionType desired); - - DrmDevice *drm_ = NULL; - DrmCrtc *crtc_ = NULL; - Importer *importer_ = NULL; - Planner *planner_ = NULL; - - DrmCompositionType type_ = DRM_COMPOSITION_TYPE_EMPTY; - uint32_t dpms_mode_ = DRM_MODE_DPMS_ON; - DrmMode display_mode_; - - UniqueFd out_fence_ = -1; - - bool geometry_changed_; - std::vector<DrmHwcLayer> layers_; - std::vector<DrmCompositionPlane> composition_planes_; - - uint64_t frame_no_ = 0; -}; -} // namespace android - -#endif // ANDROID_DRM_DISPLAY_COMPOSITION_H_ diff --git a/compositor/DrmDisplayCompositor.cpp b/compositor/DrmDisplayCompositor.cpp deleted file mode 100644 index ba0d56b..0000000 --- a/compositor/DrmDisplayCompositor.cpp +++ /dev/null @@ -1,1099 +0,0 @@ -/* - * Copyright (C) 2015 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define ATRACE_TAG ATRACE_TAG_GRAPHICS -#define LOG_TAG "hwc-drm-display-compositor" - -#include "DrmDisplayCompositor.h" - -#include <drm/drm_mode.h> -#include <log/log.h> -#include <pthread.h> -#include <sched.h> -#include <stdlib.h> -#include <sync/sync.h> -#include <time.h> -#include <utils/Trace.h> - -#include <array> -#include <sstream> -#include <vector> - -#include "drm/DrmCrtc.h" -#include "drm/DrmDevice.h" -#include "drm/DrmPlane.h" -#include "utils/autolock.h" - -static const uint32_t kWaitWritebackFence = 100; // ms - -namespace android { - -std::ostream &operator<<(std::ostream &str, FlatteningState state) { - std::array<const char *, 6> flattenting_state_str = { - "None", "Not needed", "SF Requested", "Squashed by GPU", - "Serial", "Concurrent", - }; - - return str << flattenting_state_str[static_cast<int>(state)]; -} - -class CompositorVsyncCallback : public VsyncCallback { - public: - CompositorVsyncCallback(DrmDisplayCompositor *compositor) - : compositor_(compositor) { - } - - void Callback(int display, int64_t timestamp) { - compositor_->Vsync(display, timestamp); - } - - private: - DrmDisplayCompositor *compositor_; -}; - -DrmDisplayCompositor::DrmDisplayCompositor() - : resource_manager_(NULL), - display_(-1), - initialized_(false), - active_(false), - use_hw_overlays_(true), - dump_frames_composited_(0), - dump_last_timestamp_ns_(0), - flatten_countdown_(FLATTEN_COUNTDOWN_INIT), - writeback_fence_(-1), - flattening_state_(FlatteningState::kNone), - frames_flattened_(0) { - struct timespec ts; - if (clock_gettime(CLOCK_MONOTONIC, &ts)) - return; - dump_last_timestamp_ns_ = ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec; -} - -DrmDisplayCompositor::~DrmDisplayCompositor() { - if (!initialized_) - return; - - vsync_worker_.Exit(); - int ret = pthread_mutex_lock(&lock_); - if (ret) - ALOGE("Failed to acquire compositor lock %d", ret); - DrmDevice *drm = resource_manager_->GetDrmDevice(display_); - if (mode_.blob_id) - drm->DestroyPropertyBlob(mode_.blob_id); - if (mode_.old_blob_id) - drm->DestroyPropertyBlob(mode_.old_blob_id); - - active_composition_.reset(); - - ret = pthread_mutex_unlock(&lock_); - if (ret) - ALOGE("Failed to acquire compositor lock %d", ret); - - pthread_mutex_destroy(&lock_); -} - -int DrmDisplayCompositor::Init(ResourceManager *resource_manager, int display) { - resource_manager_ = resource_manager; - display_ = display; - DrmDevice *drm = resource_manager_->GetDrmDevice(display); - if (!drm) { - ALOGE("Could not find drmdevice for display"); - return -EINVAL; - } - int ret = pthread_mutex_init(&lock_, NULL); - if (ret) { - ALOGE("Failed to initialize drm compositor lock %d\n", ret); - return ret; - } - planner_ = Planner::CreateInstance(drm); - - vsync_worker_.Init(drm, display_); - auto callback = std::make_shared<CompositorVsyncCallback>(this); - vsync_worker_.RegisterCallback(callback); - - initialized_ = true; - return 0; -} - -std::unique_ptr<DrmDisplayComposition> DrmDisplayCompositor::CreateComposition() - const { - return std::unique_ptr<DrmDisplayComposition>(new DrmDisplayComposition()); -} - -std::unique_ptr<DrmDisplayComposition> -DrmDisplayCompositor::CreateInitializedComposition() const { - DrmDevice *drm = resource_manager_->GetDrmDevice(display_); - DrmCrtc *crtc = drm->GetCrtcForDisplay(display_); - if (!crtc) { - ALOGE("Failed to find crtc for display = %d", display_); - return std::unique_ptr<DrmDisplayComposition>(); - } - std::unique_ptr<DrmDisplayComposition> comp = CreateComposition(); - std::shared_ptr<Importer> importer = resource_manager_->GetImporter(display_); - if (!importer) { - ALOGE("Failed to find resources for display = %d", display_); - return std::unique_ptr<DrmDisplayComposition>(); - } - int ret = comp->Init(drm, crtc, importer.get(), planner_.get(), 0); - if (ret) { - ALOGE("Failed to init composition for display = %d", display_); - return std::unique_ptr<DrmDisplayComposition>(); - } - return comp; -} - -FlatteningState DrmDisplayCompositor::GetFlatteningState() const { - return flattening_state_; -} - -uint32_t DrmDisplayCompositor::GetFlattenedFramesCount() const { - return frames_flattened_; -} - -bool DrmDisplayCompositor::ShouldFlattenOnClient() const { - return flattening_state_ == FlatteningState::kClientRequested || - flattening_state_ == FlatteningState::kClientDone; -} - -std::tuple<uint32_t, uint32_t, int> -DrmDisplayCompositor::GetActiveModeResolution() { - DrmDevice *drm = resource_manager_->GetDrmDevice(display_); - DrmConnector *connector = drm->GetConnectorForDisplay(display_); - if (connector == NULL) { - ALOGE("Failed to determine display mode: no connector for display %d", - display_); - return std::make_tuple(0, 0, -ENODEV); - } - - const DrmMode &mode = connector->active_mode(); - return std::make_tuple(mode.h_display(), mode.v_display(), 0); -} - -int DrmDisplayCompositor::DisablePlanes(DrmDisplayComposition *display_comp) { - drmModeAtomicReqPtr pset = drmModeAtomicAlloc(); - if (!pset) { - ALOGE("Failed to allocate property set"); - return -ENOMEM; - } - - int ret; - std::vector<DrmCompositionPlane> &comp_planes = display_comp - ->composition_planes(); - for (DrmCompositionPlane &comp_plane : comp_planes) { - DrmPlane *plane = comp_plane.plane(); - ret = drmModeAtomicAddProperty(pset, plane->id(), - plane->crtc_property().id(), 0) < 0 || - drmModeAtomicAddProperty(pset, plane->id(), plane->fb_property().id(), - 0) < 0; - if (ret) { - ALOGE("Failed to add plane %d disable to pset", plane->id()); - drmModeAtomicFree(pset); - return ret; - } - } - DrmDevice *drm = resource_manager_->GetDrmDevice(display_); - ret = drmModeAtomicCommit(drm->fd(), pset, 0, drm); - if (ret) { - ALOGE("Failed to commit pset ret=%d\n", ret); - drmModeAtomicFree(pset); - return ret; - } - - drmModeAtomicFree(pset); - return 0; -} - -int DrmDisplayCompositor::SetupWritebackCommit(drmModeAtomicReqPtr pset, - uint32_t crtc_id, - DrmConnector *writeback_conn, - DrmHwcBuffer *writeback_buffer) { - int ret = 0; - if (writeback_conn->writeback_fb_id().id() == 0 || - writeback_conn->writeback_out_fence().id() == 0) { - ALOGE("Writeback properties don't exit"); - return -EINVAL; - } - if ((*writeback_buffer)->fb_id == 0) { - ALOGE("Invalid writeback buffer"); - return -EINVAL; - } - ret = drmModeAtomicAddProperty(pset, writeback_conn->id(), - writeback_conn->writeback_fb_id().id(), - (*writeback_buffer)->fb_id); - if (ret < 0) { - ALOGE("Failed to add writeback_fb_id"); - return ret; - } - ret = drmModeAtomicAddProperty(pset, writeback_conn->id(), - writeback_conn->writeback_out_fence().id(), - (uint64_t)&writeback_fence_); - if (ret < 0) { - ALOGE("Failed to add writeback_out_fence"); - return ret; - } - - ret = drmModeAtomicAddProperty(pset, writeback_conn->id(), - writeback_conn->crtc_id_property().id(), - crtc_id); - if (ret < 0) { - ALOGE("Failed to attach writeback"); - return ret; - } - return 0; -} - -int DrmDisplayCompositor::CommitFrame(DrmDisplayComposition *display_comp, - bool test_only, - DrmConnector *writeback_conn, - DrmHwcBuffer *writeback_buffer) { - ATRACE_CALL(); - - int ret = 0; - - std::vector<DrmHwcLayer> &layers = display_comp->layers(); - std::vector<DrmCompositionPlane> &comp_planes = display_comp - ->composition_planes(); - DrmDevice *drm = resource_manager_->GetDrmDevice(display_); - uint64_t out_fences[drm->crtcs().size()]; - - DrmConnector *connector = drm->GetConnectorForDisplay(display_); - if (!connector) { - ALOGE("Could not locate connector for display %d", display_); - return -ENODEV; - } - DrmCrtc *crtc = drm->GetCrtcForDisplay(display_); - if (!crtc) { - ALOGE("Could not locate crtc for display %d", display_); - return -ENODEV; - } - - drmModeAtomicReqPtr pset = drmModeAtomicAlloc(); - if (!pset) { - ALOGE("Failed to allocate property set"); - return -ENOMEM; - } - - if (writeback_buffer != NULL) { - if (writeback_conn == NULL) { - ALOGE("Invalid arguments requested writeback without writeback conn"); - return -EINVAL; - } - ret = SetupWritebackCommit(pset, crtc->id(), writeback_conn, - writeback_buffer); - if (ret < 0) { - ALOGE("Failed to Setup Writeback Commit ret = %d", ret); - return ret; - } - } - if (crtc->out_fence_ptr_property().id() != 0) { - ret = drmModeAtomicAddProperty(pset, crtc->id(), - crtc->out_fence_ptr_property().id(), - (uint64_t)&out_fences[crtc->pipe()]); - if (ret < 0) { - ALOGE("Failed to add OUT_FENCE_PTR property to pset: %d", ret); - drmModeAtomicFree(pset); - return ret; - } - } - - if (mode_.needs_modeset) { - ret = drmModeAtomicAddProperty(pset, crtc->id(), - crtc->active_property().id(), 1); - if (ret < 0) { - ALOGE("Failed to add crtc active to pset\n"); - drmModeAtomicFree(pset); - return ret; - } - - ret = drmModeAtomicAddProperty(pset, crtc->id(), crtc->mode_property().id(), - mode_.blob_id) < 0 || - drmModeAtomicAddProperty(pset, connector->id(), - connector->crtc_id_property().id(), - crtc->id()) < 0; - if (ret) { - ALOGE("Failed to add blob %d to pset", mode_.blob_id); - drmModeAtomicFree(pset); - return ret; - } - } - - for (DrmCompositionPlane &comp_plane : comp_planes) { - DrmPlane *plane = comp_plane.plane(); - DrmCrtc *crtc = comp_plane.crtc(); - std::vector<size_t> &source_layers = comp_plane.source_layers(); - - int fb_id = -1; - int fence_fd = -1; - hwc_rect_t display_frame; - hwc_frect_t source_crop; - uint64_t rotation = 0; - uint64_t alpha = 0xFFFF; - uint64_t blend; - - if (comp_plane.type() != DrmCompositionPlane::Type::kDisable) { - if (source_layers.size() > 1) { - ALOGE("Can't handle more than one source layer sz=%zu type=%d", - source_layers.size(), comp_plane.type()); - continue; - } - - if (source_layers.empty() || source_layers.front() >= layers.size()) { - ALOGE("Source layer index %zu out of bounds %zu type=%d", - source_layers.front(), layers.size(), comp_plane.type()); - break; - } - DrmHwcLayer &layer = layers[source_layers.front()]; - if (!layer.buffer) { - ALOGE("Expected a valid framebuffer for pset"); - break; - } - fb_id = layer.buffer->fb_id; - fence_fd = layer.acquire_fence.get(); - display_frame = layer.display_frame; - source_crop = layer.source_crop; - alpha = layer.alpha; - - if (plane->blend_property().id()) { - switch (layer.blending) { - case DrmHwcBlending::kPreMult: - std::tie(blend, ret) = plane->blend_property().GetEnumValueWithName( - "Pre-multiplied"); - break; - case DrmHwcBlending::kCoverage: - std::tie(blend, ret) = plane->blend_property().GetEnumValueWithName( - "Coverage"); - break; - case DrmHwcBlending::kNone: - default: - std::tie(blend, ret) = plane->blend_property().GetEnumValueWithName( - "None"); - break; - } - } - - if (plane->zpos_property().id() && - !plane->zpos_property().is_immutable()) { - uint64_t min_zpos = 0; - - // Ignore ret and use min_zpos as 0 by default - std::tie(std::ignore, min_zpos) = plane->zpos_property().range_min(); - - ret = drmModeAtomicAddProperty(pset, plane->id(), - plane->zpos_property().id(), - source_layers.front() + min_zpos) < 0; - if (ret) { - ALOGE("Failed to add zpos property %d to plane %d", - plane->zpos_property().id(), plane->id()); - break; - } - } - - rotation = 0; - if (layer.transform & DrmHwcTransform::kFlipH) - rotation |= DRM_MODE_REFLECT_X; - if (layer.transform & DrmHwcTransform::kFlipV) - rotation |= DRM_MODE_REFLECT_Y; - if (layer.transform & DrmHwcTransform::kRotate90) - rotation |= DRM_MODE_ROTATE_90; - else if (layer.transform & DrmHwcTransform::kRotate180) - rotation |= DRM_MODE_ROTATE_180; - else if (layer.transform & DrmHwcTransform::kRotate270) - rotation |= DRM_MODE_ROTATE_270; - else - rotation |= DRM_MODE_ROTATE_0; - - if (fence_fd >= 0) { - int prop_id = plane->in_fence_fd_property().id(); - if (prop_id == 0) { - ALOGE("Failed to get IN_FENCE_FD property id"); - break; - } - ret = drmModeAtomicAddProperty(pset, plane->id(), prop_id, fence_fd); - if (ret < 0) { - ALOGE("Failed to add IN_FENCE_FD property to pset: %d", ret); - break; - } - } - } - - // Disable the plane if there's no framebuffer - if (fb_id < 0) { - ret = drmModeAtomicAddProperty(pset, plane->id(), - plane->crtc_property().id(), 0) < 0 || - drmModeAtomicAddProperty(pset, plane->id(), - plane->fb_property().id(), 0) < 0; - if (ret) { - ALOGE("Failed to add plane %d disable to pset", plane->id()); - break; - } - continue; - } - - ret = drmModeAtomicAddProperty(pset, plane->id(), - plane->crtc_property().id(), crtc->id()) < 0; - ret |= drmModeAtomicAddProperty(pset, plane->id(), - plane->fb_property().id(), fb_id) < 0; - ret |= drmModeAtomicAddProperty(pset, plane->id(), - plane->crtc_x_property().id(), - display_frame.left) < 0; - ret |= drmModeAtomicAddProperty(pset, plane->id(), - plane->crtc_y_property().id(), - display_frame.top) < 0; - ret |= drmModeAtomicAddProperty(pset, plane->id(), - plane->crtc_w_property().id(), - display_frame.right - display_frame.left) < - 0; - ret |= drmModeAtomicAddProperty(pset, plane->id(), - plane->crtc_h_property().id(), - display_frame.bottom - display_frame.top) < - 0; - ret |= drmModeAtomicAddProperty(pset, plane->id(), - plane->src_x_property().id(), - (int)(source_crop.left) << 16) < 0; - ret |= drmModeAtomicAddProperty(pset, plane->id(), - plane->src_y_property().id(), - (int)(source_crop.top) << 16) < 0; - ret |= drmModeAtomicAddProperty(pset, plane->id(), - plane->src_w_property().id(), - (int)(source_crop.right - source_crop.left) - << 16) < 0; - ret |= drmModeAtomicAddProperty(pset, plane->id(), - plane->src_h_property().id(), - (int)(source_crop.bottom - source_crop.top) - << 16) < 0; - if (ret) { - ALOGE("Failed to add plane %d to set", plane->id()); - break; - } - - if (plane->rotation_property().id()) { - ret = drmModeAtomicAddProperty(pset, plane->id(), - plane->rotation_property().id(), - rotation) < 0; - if (ret) { - ALOGE("Failed to add rotation property %d to plane %d", - plane->rotation_property().id(), plane->id()); - break; - } - } - - if (plane->alpha_property().id()) { - ret = drmModeAtomicAddProperty(pset, plane->id(), - plane->alpha_property().id(), alpha) < 0; - if (ret) { - ALOGE("Failed to add alpha property %d to plane %d", - plane->alpha_property().id(), plane->id()); - break; - } - } - - if (plane->blend_property().id()) { - ret = drmModeAtomicAddProperty(pset, plane->id(), - plane->blend_property().id(), blend) < 0; - if (ret) { - ALOGE("Failed to add pixel blend mode property %d to plane %d", - plane->blend_property().id(), plane->id()); - break; - } - } - } - - if (!ret) { - uint32_t flags = DRM_MODE_ATOMIC_ALLOW_MODESET; - if (test_only) - flags |= DRM_MODE_ATOMIC_TEST_ONLY; - - ret = drmModeAtomicCommit(drm->fd(), pset, flags, drm); - if (ret) { - if (!test_only) - ALOGE("Failed to commit pset ret=%d\n", ret); - drmModeAtomicFree(pset); - return ret; - } - } - if (pset) - drmModeAtomicFree(pset); - - if (!test_only && mode_.needs_modeset) { - ret = drm->DestroyPropertyBlob(mode_.old_blob_id); - if (ret) { - ALOGE("Failed to destroy old mode property blob %" PRIu32 "/%d", - mode_.old_blob_id, ret); - return ret; - } - - /* TODO: Add dpms to the pset when the kernel supports it */ - ret = ApplyDpms(display_comp); - if (ret) { - ALOGE("Failed to apply DPMS after modeset %d\n", ret); - return ret; - } - - connector->set_active_mode(mode_.mode); - mode_.old_blob_id = mode_.blob_id; - mode_.blob_id = 0; - mode_.needs_modeset = false; - } - - if (crtc->out_fence_ptr_property().id()) { - display_comp->set_out_fence((int)out_fences[crtc->pipe()]); - } - - return ret; -} - -int DrmDisplayCompositor::ApplyDpms(DrmDisplayComposition *display_comp) { - DrmDevice *drm = resource_manager_->GetDrmDevice(display_); - DrmConnector *conn = drm->GetConnectorForDisplay(display_); - if (!conn) { - ALOGE("Failed to get DrmConnector for display %d", display_); - return -ENODEV; - } - - const DrmProperty &prop = conn->dpms_property(); - int ret = drmModeConnectorSetProperty(drm->fd(), conn->id(), prop.id(), - display_comp->dpms_mode()); - if (ret) { - ALOGE("Failed to set DPMS property for connector %d", conn->id()); - return ret; - } - return 0; -} - -std::tuple<int, uint32_t> DrmDisplayCompositor::CreateModeBlob( - const DrmMode &mode) { - struct drm_mode_modeinfo drm_mode; - memset(&drm_mode, 0, sizeof(drm_mode)); - mode.ToDrmModeModeInfo(&drm_mode); - - uint32_t id = 0; - DrmDevice *drm = resource_manager_->GetDrmDevice(display_); - int ret = drm->CreatePropertyBlob(&drm_mode, sizeof(struct drm_mode_modeinfo), - &id); - if (ret) { - ALOGE("Failed to create mode property blob %d", ret); - return std::make_tuple(ret, 0); - } - ALOGE("Create blob_id %" PRIu32 "\n", id); - return std::make_tuple(ret, id); -} - -void DrmDisplayCompositor::ClearDisplay() { - if (!active_composition_) - return; - - if (DisablePlanes(active_composition_.get())) - return; - - active_composition_.reset(NULL); - vsync_worker_.VSyncControl(false); -} - -void DrmDisplayCompositor::ApplyFrame( - std::unique_ptr<DrmDisplayComposition> composition, int status, - bool writeback) { - AutoLock lock(&lock_, __func__); - if (lock.Lock()) - return; - int ret = status; - - if (!ret) { - if (writeback && !CountdownExpired()) { - ALOGE("Abort playing back scene"); - return; - } - ret = CommitFrame(composition.get(), false); - } - - if (ret) { - ALOGE("Composite failed for display %d", display_); - // Disable the hw used by the last active composition. This allows us to - // signal the release fences from that composition to avoid hanging. - ClearDisplay(); - return; - } - ++dump_frames_composited_; - - active_composition_.swap(composition); - - flatten_countdown_ = FLATTEN_COUNTDOWN_INIT; - if (flattening_state_ != FlatteningState::kClientRequested) { - SetFlattening(FlatteningState::kNone); - } else { - SetFlattening(FlatteningState::kClientDone); - } - vsync_worker_.VSyncControl(!writeback); -} - -int DrmDisplayCompositor::ApplyComposition( - std::unique_ptr<DrmDisplayComposition> composition) { - int ret = 0; - switch (composition->type()) { - case DRM_COMPOSITION_TYPE_FRAME: - if (composition->geometry_changed()) { - // Send the composition to the kernel to ensure we can commit it. This - // is just a test, it won't actually commit the frame. - ret = CommitFrame(composition.get(), true); - if (ret) { - ALOGE("Commit test failed for display %d, FIXME", display_); - return ret; - } - } - - ApplyFrame(std::move(composition), ret); - break; - case DRM_COMPOSITION_TYPE_DPMS: - active_ = (composition->dpms_mode() == DRM_MODE_DPMS_ON); - ret = ApplyDpms(composition.get()); - if (ret) - ALOGE("Failed to apply dpms for display %d", display_); - return ret; - case DRM_COMPOSITION_TYPE_MODESET: - mode_.mode = composition->display_mode(); - if (mode_.blob_id) - resource_manager_->GetDrmDevice(display_)->DestroyPropertyBlob( - mode_.blob_id); - std::tie(ret, mode_.blob_id) = CreateModeBlob(mode_.mode); - if (ret) { - ALOGE("Failed to create mode blob for display %d", display_); - return ret; - } - mode_.needs_modeset = true; - return 0; - default: - ALOGE("Unknown composition type %d", composition->type()); - return -EINVAL; - } - - return ret; -} - -int DrmDisplayCompositor::TestComposition(DrmDisplayComposition *composition) { - return CommitFrame(composition, true); -} - -// Flatten a scene on the display by using a writeback connector -// and returns the composition result as a DrmHwcLayer. -int DrmDisplayCompositor::FlattenOnDisplay( - std::unique_ptr<DrmDisplayComposition> &src, DrmConnector *writeback_conn, - DrmMode &src_mode, DrmHwcLayer *writeback_layer) { - int ret = 0; - DrmDevice *drm = resource_manager_->GetDrmDevice(display_); - ret = writeback_conn->UpdateModes(); - if (ret) { - ALOGE("Failed to update modes %d", ret); - return ret; - } - for (const DrmMode &mode : writeback_conn->modes()) { - if (mode.h_display() == src_mode.h_display() && - mode.v_display() == src_mode.v_display()) { - mode_.mode = mode; - if (mode_.blob_id) - drm->DestroyPropertyBlob(mode_.blob_id); - std::tie(ret, mode_.blob_id) = CreateModeBlob(mode_.mode); - if (ret) { - ALOGE("Failed to create mode blob for display %d", display_); - return ret; - } - mode_.needs_modeset = true; - break; - } - } - if (mode_.blob_id <= 0) { - ALOGE("Failed to find similar mode"); - return -EINVAL; - } - - DrmCrtc *crtc = drm->GetCrtcForDisplay(display_); - if (!crtc) { - ALOGE("Failed to find crtc for display %d", display_); - return -EINVAL; - } - // TODO what happens if planes could go to both CRTCs, I don't think it's - // handled anywhere - std::vector<DrmPlane *> primary_planes; - std::vector<DrmPlane *> overlay_planes; - for (auto &plane : drm->planes()) { - if (!plane->GetCrtcSupported(*crtc)) - continue; - if (plane->type() == DRM_PLANE_TYPE_PRIMARY) - primary_planes.push_back(plane.get()); - else if (plane->type() == DRM_PLANE_TYPE_OVERLAY) - overlay_planes.push_back(plane.get()); - } - - ret = src->Plan(&primary_planes, &overlay_planes); - if (ret) { - ALOGE("Failed to plan the composition ret = %d", ret); - return ret; - } - - // Disable the planes we're not using - for (auto i = primary_planes.begin(); i != primary_planes.end();) { - src->AddPlaneDisable(*i); - i = primary_planes.erase(i); - } - for (auto i = overlay_planes.begin(); i != overlay_planes.end();) { - src->AddPlaneDisable(*i); - i = overlay_planes.erase(i); - } - - AutoLock lock(&lock_, __func__); - ret = lock.Lock(); - if (ret) - return ret; - DrmFramebuffer *writeback_fb = &framebuffers_[framebuffer_index_]; - framebuffer_index_ = (framebuffer_index_ + 1) % DRM_DISPLAY_BUFFERS; - if (!writeback_fb->Allocate(mode_.mode.h_display(), mode_.mode.v_display())) { - ALOGE("Failed to allocate writeback buffer"); - return -ENOMEM; - } - DrmHwcBuffer *writeback_buffer = &writeback_layer->buffer; - writeback_layer->sf_handle = writeback_fb->buffer()->handle; - ret = writeback_layer->ImportBuffer( - resource_manager_->GetImporter(display_).get()); - if (ret) { - ALOGE("Failed to import writeback buffer"); - return ret; - } - - ret = CommitFrame(src.get(), true, writeback_conn, writeback_buffer); - if (ret) { - ALOGE("Atomic check failed"); - return ret; - } - ret = CommitFrame(src.get(), false, writeback_conn, writeback_buffer); - if (ret) { - ALOGE("Atomic commit failed"); - return ret; - } - - ret = sync_wait(writeback_fence_, kWaitWritebackFence); - writeback_layer->acquire_fence.Set(writeback_fence_); - writeback_fence_ = -1; - if (ret) { - ALOGE("Failed to wait on writeback fence"); - return ret; - } - return 0; -} - -void DrmDisplayCompositor::SetFlattening(FlatteningState new_state) { - if (flattening_state_ != new_state) { - switch (flattening_state_) { - case FlatteningState::kClientDone: - case FlatteningState::kConcurrent: - case FlatteningState::kSerial: - ++frames_flattened_; - break; - case FlatteningState::kClientRequested: - case FlatteningState::kNone: - case FlatteningState::kNotNeeded: - break; - } - } - flattening_state_ = new_state; -} - -bool DrmDisplayCompositor::IsFlatteningNeeded() const { - return CountdownExpired() && active_composition_->layers().size() >= 2; -} - -int DrmDisplayCompositor::FlattenOnClient() { - const std::lock_guard<std::mutex> lock(refresh_callback_lock); - - if (refresh_callback_hook_ && refresh_callback_data_) { - { - AutoLock lock(&lock_, __func__); - if (!IsFlatteningNeeded()) { - if (flattening_state_ != FlatteningState::kClientDone) { - ALOGV("Flattening is not needed"); - SetFlattening(FlatteningState::kNotNeeded); - } - return -EALREADY; - } - } - - ALOGV( - "No writeback connector available, " - "falling back to client composition"); - SetFlattening(FlatteningState::kClientRequested); - refresh_callback_hook_(refresh_callback_data_, display_); - return 0; - } else { - ALOGV("No writeback connector available"); - return -EINVAL; - } -} - -// Flatten a scene by enabling the writeback connector attached -// to the same CRTC as the one driving the display. -int DrmDisplayCompositor::FlattenSerial(DrmConnector *writeback_conn) { - ALOGV("FlattenSerial by enabling writeback connector to the same crtc"); - // Flattened composition with only one layer that is obtained - // using the writeback connector - std::unique_ptr<DrmDisplayComposition> - writeback_comp = CreateInitializedComposition(); - if (!writeback_comp) - return -EINVAL; - - AutoLock lock(&lock_, __func__); - int ret = lock.Lock(); - if (ret) - return ret; - if (!IsFlatteningNeeded()) { - ALOGV("Flattening is not needed"); - SetFlattening(FlatteningState::kNotNeeded); - return -EALREADY; - } - - DrmFramebuffer *writeback_fb = &framebuffers_[framebuffer_index_]; - framebuffer_index_ = (framebuffer_index_ + 1) % DRM_DISPLAY_BUFFERS; - lock.Unlock(); - - if (!writeback_fb->Allocate(mode_.mode.h_display(), mode_.mode.v_display())) { - ALOGE("Failed to allocate writeback buffer"); - return -ENOMEM; - } - writeback_comp->layers().emplace_back(); - - DrmHwcLayer &writeback_layer = writeback_comp->layers().back(); - writeback_layer.sf_handle = writeback_fb->buffer()->handle; - writeback_layer.source_crop = {0, 0, (float)mode_.mode.h_display(), - (float)mode_.mode.v_display()}; - writeback_layer.display_frame = {0, 0, (int)mode_.mode.h_display(), - (int)mode_.mode.v_display()}; - ret = writeback_layer.ImportBuffer( - resource_manager_->GetImporter(display_).get()); - if (ret || writeback_comp->layers().size() != 1) { - ALOGE("Failed to import writeback buffer"); - return ret; - } - - drmModeAtomicReqPtr pset = drmModeAtomicAlloc(); - if (!pset) { - ALOGE("Failed to allocate property set"); - return -ENOMEM; - } - DrmDevice *drm = resource_manager_->GetDrmDevice(display_); - DrmCrtc *crtc = drm->GetCrtcForDisplay(display_); - if (!crtc) { - ALOGE("Failed to find crtc for display %d", display_); - return -EINVAL; - } - ret = SetupWritebackCommit(pset, crtc->id(), writeback_conn, - &writeback_layer.buffer); - if (ret < 0) { - ALOGE("Failed to Setup Writeback Commit"); - return ret; - } - ret = drmModeAtomicCommit(drm->fd(), pset, 0, drm); - if (ret) { - ALOGE("Failed to enable writeback %d", ret); - return ret; - } - ret = sync_wait(writeback_fence_, kWaitWritebackFence); - writeback_layer.acquire_fence.Set(writeback_fence_); - writeback_fence_ = -1; - if (ret) { - ALOGE("Failed to wait on writeback fence"); - return ret; - } - - DrmCompositionPlane squashed_comp(DrmCompositionPlane::Type::kLayer, NULL, - crtc); - for (auto &drmplane : drm->planes()) { - if (!drmplane->GetCrtcSupported(*crtc)) - continue; - if (!squashed_comp.plane() && drmplane->type() == DRM_PLANE_TYPE_PRIMARY) - squashed_comp.set_plane(drmplane.get()); - else - writeback_comp->AddPlaneDisable(drmplane.get()); - } - squashed_comp.source_layers().push_back(0); - ret = writeback_comp->AddPlaneComposition(std::move(squashed_comp)); - if (ret) { - ALOGE("Failed to add flatten scene"); - return ret; - } - - ApplyFrame(std::move(writeback_comp), 0, true); - return 0; -} - -// Flatten a scene by using a crtc which works concurrent with -// the one driving the display. -int DrmDisplayCompositor::FlattenConcurrent(DrmConnector *writeback_conn) { - ALOGV("FlattenConcurrent by using an unused crtc/display"); - int ret = 0; - DrmDisplayCompositor drmdisplaycompositor; - ret = drmdisplaycompositor.Init(resource_manager_, writeback_conn->display()); - if (ret) { - ALOGE("Failed to init drmdisplaycompositor = %d", ret); - return ret; - } - // Copy of the active_composition, needed because of two things: - // 1) Not to hold the lock for the whole time we are accessing - // active_composition - // 2) It will be committed on a crtc that might not be on the same - // dri node, so buffers need to be imported on the right node. - std::unique_ptr<DrmDisplayComposition> - copy_comp = drmdisplaycompositor.CreateInitializedComposition(); - - // Writeback composition that will be committed to the display. - std::unique_ptr<DrmDisplayComposition> - writeback_comp = CreateInitializedComposition(); - - if (!copy_comp || !writeback_comp) - return -EINVAL; - AutoLock lock(&lock_, __func__); - ret = lock.Lock(); - if (ret) - return ret; - if (!IsFlatteningNeeded()) { - ALOGV("Flattening is not needed"); - SetFlattening(FlatteningState::kNotNeeded); - return -EALREADY; - } - DrmCrtc *crtc = active_composition_->crtc(); - - std::vector<DrmHwcLayer> copy_layers; - for (DrmHwcLayer &src_layer : active_composition_->layers()) { - DrmHwcLayer copy; - ret = copy.InitFromDrmHwcLayer(&src_layer, - resource_manager_ - ->GetImporter(writeback_conn->display()) - .get()); - if (ret) { - ALOGE("Failed to import buffer ret = %d", ret); - return -EINVAL; - } - copy_layers.emplace_back(std::move(copy)); - } - ret = copy_comp->SetLayers(copy_layers.data(), copy_layers.size(), true); - if (ret) { - ALOGE("Failed to set copy_comp layers"); - return ret; - } - - lock.Unlock(); - DrmHwcLayer writeback_layer; - ret = drmdisplaycompositor.FlattenOnDisplay(copy_comp, writeback_conn, - mode_.mode, &writeback_layer); - if (ret) { - ALOGE("Failed to flatten on display ret = %d", ret); - return ret; - } - - DrmCompositionPlane squashed_comp(DrmCompositionPlane::Type::kLayer, NULL, - crtc); - for (auto &drmplane : resource_manager_->GetDrmDevice(display_)->planes()) { - if (!drmplane->GetCrtcSupported(*crtc)) - continue; - if (drmplane->type() == DRM_PLANE_TYPE_PRIMARY) - squashed_comp.set_plane(drmplane.get()); - else - writeback_comp->AddPlaneDisable(drmplane.get()); - } - writeback_comp->layers().emplace_back(); - DrmHwcLayer &next_layer = writeback_comp->layers().back(); - next_layer.sf_handle = writeback_layer.get_usable_handle(); - next_layer.blending = DrmHwcBlending::kPreMult; - next_layer.source_crop = {0, 0, (float)mode_.mode.h_display(), - (float)mode_.mode.v_display()}; - next_layer.display_frame = {0, 0, (int)mode_.mode.h_display(), - (int)mode_.mode.v_display()}; - ret = next_layer.ImportBuffer(resource_manager_->GetImporter(display_).get()); - if (ret) { - ALOGE("Failed to import framebuffer for display %d", ret); - return ret; - } - squashed_comp.source_layers().push_back(0); - ret = writeback_comp->AddPlaneComposition(std::move(squashed_comp)); - if (ret) { - ALOGE("Failed to add plane composition %d", ret); - return ret; - } - ApplyFrame(std::move(writeback_comp), 0, true); - return ret; -} - -int DrmDisplayCompositor::FlattenActiveComposition() { - DrmConnector *writeback_conn = resource_manager_->AvailableWritebackConnector( - display_); - if (!active_composition_ || !writeback_conn) { - // Try to fallback to GPU composition on client, since it is more - // power-efficient than composition on device side - return FlattenOnClient(); - } - - if (writeback_conn->display() != display_) { - SetFlattening(FlatteningState::kConcurrent); - return FlattenConcurrent(writeback_conn); - } else { - SetFlattening(FlatteningState::kSerial); - return FlattenSerial(writeback_conn); - } - - return 0; -} - -bool DrmDisplayCompositor::CountdownExpired() const { - return flatten_countdown_ <= 0; -} - -void DrmDisplayCompositor::Vsync(int display, int64_t timestamp) { - AutoLock lock(&lock_, __func__); - if (lock.Lock()) - return; - flatten_countdown_--; - if (!CountdownExpired()) - return; - lock.Unlock(); - int ret = FlattenActiveComposition(); - ALOGV("scene flattening triggered for display %d at timestamp %" PRIu64 - " result = %d \n", - display, timestamp, ret); -} - -void DrmDisplayCompositor::Dump(std::ostringstream *out) const { - int ret = pthread_mutex_lock(&lock_); - if (ret) - return; - - uint64_t num_frames = dump_frames_composited_; - dump_frames_composited_ = 0; - - struct timespec ts; - ret = clock_gettime(CLOCK_MONOTONIC, &ts); - if (ret) { - pthread_mutex_unlock(&lock_); - return; - } - - uint64_t cur_ts = ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec; - uint64_t num_ms = (cur_ts - dump_last_timestamp_ns_) / (1000 * 1000); - float fps = num_ms ? (num_frames * 1000.0f) / (num_ms) : 0.0f; - - *out << "--DrmDisplayCompositor[" << display_ - << "]: num_frames=" << num_frames << " num_ms=" << num_ms - << " fps=" << fps << "\n"; - - dump_last_timestamp_ns_ = cur_ts; - - pthread_mutex_unlock(&lock_); -} -} // namespace android diff --git a/compositor/DrmDisplayCompositor.h b/compositor/DrmDisplayCompositor.h deleted file mode 100644 index ab3f867..0000000 --- a/compositor/DrmDisplayCompositor.h +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (C) 2015 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ANDROID_DRM_DISPLAY_COMPOSITOR_H_ -#define ANDROID_DRM_DISPLAY_COMPOSITOR_H_ - -#include <hardware/hardware.h> -#include <hardware/hwcomposer.h> -#include <pthread.h> - -#include <memory> -#include <sstream> -#include <tuple> - -#include "DrmDisplayComposition.h" -#include "DrmFramebuffer.h" -#include "Planner.h" -#include "drm/ResourceManager.h" -#include "drm/VSyncWorker.h" -#include "drmhwcomposer.h" - -// One for the front, one for the back, and one for cases where we need to -// squash a frame that the hw can't display with hw overlays. -#define DRM_DISPLAY_BUFFERS 3 - -// If a scene is still for this number of vblanks flatten it to reduce power -// consumption. -#define FLATTEN_COUNTDOWN_INIT 60 - -namespace android { - -enum class FlatteningState { - kNone, - kNotNeeded, - kClientRequested, - kClientDone, - kSerial, - kConcurrent -}; - -std::ostream &operator<<(std::ostream &str, FlatteningState state); - -class DrmDisplayCompositor { - public: - DrmDisplayCompositor(); - ~DrmDisplayCompositor(); - - int Init(ResourceManager *resource_manager, int display); - - hwc2_callback_data_t refresh_callback_data_ = NULL; - HWC2_PFN_REFRESH refresh_callback_hook_ = NULL; - std::mutex refresh_callback_lock; - - void SetRefreshCallback(hwc2_callback_data_t data, - hwc2_function_pointer_t hook) { - const std::lock_guard<std::mutex> lock(refresh_callback_lock); - refresh_callback_data_ = data; - refresh_callback_hook_ = reinterpret_cast<HWC2_PFN_REFRESH>(hook); - } - - std::unique_ptr<DrmDisplayComposition> CreateComposition() const; - std::unique_ptr<DrmDisplayComposition> CreateInitializedComposition() const; - int ApplyComposition(std::unique_ptr<DrmDisplayComposition> composition); - int TestComposition(DrmDisplayComposition *composition); - int Composite(); - void Dump(std::ostringstream *out) const; - void Vsync(int display, int64_t timestamp); - void ClearDisplay(); - int TakeOutFence() { - if (!active_composition_) - return -1; - return active_composition_->take_out_fence(); - } - - FlatteningState GetFlatteningState() const; - uint32_t GetFlattenedFramesCount() const; - bool ShouldFlattenOnClient() const; - - std::tuple<uint32_t, uint32_t, int> GetActiveModeResolution(); - - private: - struct ModeState { - bool needs_modeset = false; - DrmMode mode; - uint32_t blob_id = 0; - uint32_t old_blob_id = 0; - }; - - DrmDisplayCompositor(const DrmDisplayCompositor &) = delete; - - // We'll wait for acquire fences to fire for kAcquireWaitTimeoutMs, - // kAcquireWaitTries times, logging a warning in between. - static const int kAcquireWaitTries = 5; - static const int kAcquireWaitTimeoutMs = 100; - - int CommitFrame(DrmDisplayComposition *display_comp, bool test_only, - DrmConnector *writeback_conn = NULL, - DrmHwcBuffer *writeback_buffer = NULL); - int SetupWritebackCommit(drmModeAtomicReqPtr pset, uint32_t crtc_id, - DrmConnector *writeback_conn, - DrmHwcBuffer *writeback_buffer); - int ApplyDpms(DrmDisplayComposition *display_comp); - int DisablePlanes(DrmDisplayComposition *display_comp); - - void ApplyFrame(std::unique_ptr<DrmDisplayComposition> composition, - int status, bool writeback = false); - - void SetFlattening(FlatteningState new_state); - bool IsFlatteningNeeded() const; - int FlattenActiveComposition(); - int FlattenOnClient(); - int FlattenSerial(DrmConnector *writeback_conn); - int FlattenConcurrent(DrmConnector *writeback_conn); - int FlattenOnDisplay(std::unique_ptr<DrmDisplayComposition> &src, - DrmConnector *writeback_conn, DrmMode &src_mode, - DrmHwcLayer *writeback_layer); - - bool CountdownExpired() const; - - std::tuple<int, uint32_t> CreateModeBlob(const DrmMode &mode); - - ResourceManager *resource_manager_; - int display_; - - std::unique_ptr<DrmDisplayComposition> active_composition_; - - bool initialized_; - bool active_; - bool use_hw_overlays_; - - ModeState mode_; - - int framebuffer_index_; - DrmFramebuffer framebuffers_[DRM_DISPLAY_BUFFERS]; - - // mutable since we need to acquire in Dump() - mutable pthread_mutex_t lock_; - - // State tracking progress since our last Dump(). These are mutable since - // we need to reset them on every Dump() call. - mutable uint64_t dump_frames_composited_; - mutable uint64_t dump_last_timestamp_ns_; - VSyncWorker vsync_worker_; - int64_t flatten_countdown_; - std::unique_ptr<Planner> planner_; - int writeback_fence_; - - FlatteningState flattening_state_; - uint32_t frames_flattened_; - - std::function<void(int)> refresh_display_cb_; -}; -} // namespace android - -#endif // ANDROID_DRM_DISPLAY_COMPOSITOR_H_ diff --git a/compositor/DrmKmsPlan.cpp b/compositor/DrmKmsPlan.cpp new file mode 100644 index 0000000..966bd4e --- /dev/null +++ b/compositor/DrmKmsPlan.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "hwc-composition-drm-kms-plan" + +#include "DrmKmsPlan.h" + +#include "drm/DrmDevice.h" +#include "drm/DrmPlane.h" +#include "utils/log.h" + +namespace android { +auto DrmKmsPlan::CreateDrmKmsPlan(DrmDisplayPipeline &pipe, + std::vector<DrmHwcLayer> composition) + -> std::unique_ptr<DrmKmsPlan> { + auto plan = std::make_unique<DrmKmsPlan>(); + + auto avail_planes = pipe.GetUsablePlanes(); + + int z_pos = 0; + for (auto &dhl : composition) { + std::shared_ptr<BindingOwner<DrmPlane>> plane; + + /* Skip unsupported planes */ + do { + if (avail_planes.empty()) { + return {}; + } + + plane = *avail_planes.begin(); + avail_planes.erase(avail_planes.begin()); + } while (!plane->Get()->IsValidForLayer(&dhl)); + + LayerToPlaneJoining joining = { + .layer = std::move(dhl), + .plane = plane, + .z_pos = z_pos++, + }; + + plan->plan.emplace_back(std::move(joining)); + } + + return plan; +} + +} // namespace android diff --git a/backend/BackendRCarDu.h b/compositor/DrmKmsPlan.h index 8a1011a..35e66e9 100644 --- a/backend/BackendRCarDu.h +++ b/compositor/DrmKmsPlan.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020 The Android Open Source Project + * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,18 +14,31 @@ * limitations under the License. */ -#ifndef HWC_DISPLAY_BACKEND_RCAR_DU_H -#define HWC_DISPLAY_BACKEND_RCAR_DU_H +#ifndef ANDROID_DRM_KMS_PLAN_H_ +#define ANDROID_DRM_KMS_PLAN_H_ -#include "Backend.h" +#include <memory> +#include <vector> + +#include "drmhwcomposer.h" namespace android { -class BackendRCarDu : public Backend { - public: - bool IsClientLayer(DrmHwcTwo::HwcDisplay *display, - DrmHwcTwo::HwcLayer *layer) override; +class DrmDevice; + +struct DrmKmsPlan { + struct LayerToPlaneJoining { + DrmHwcLayer layer; + std::shared_ptr<BindingOwner<DrmPlane>> plane; + int z_pos; + }; + + std::vector<LayerToPlaneJoining> plan; + + static auto CreateDrmKmsPlan(DrmDisplayPipeline &pipe, + std::vector<DrmHwcLayer> composition) + -> std::unique_ptr<DrmKmsPlan>; }; -} // namespace android +} // namespace android #endif diff --git a/compositor/Planner.cpp b/compositor/Planner.cpp deleted file mode 100644 index f4b5c51..0000000 --- a/compositor/Planner.cpp +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (C) 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "hwc-platform" - -#include "Planner.h" - -#include <log/log.h> - -#include "drm/DrmDevice.h" - -namespace android { - -std::unique_ptr<Planner> Planner::CreateInstance(DrmDevice *) { - std::unique_ptr<Planner> planner(new Planner); - planner->AddStage<PlanStageGreedy>(); - return planner; -} - -std::vector<DrmPlane *> Planner::GetUsablePlanes( - DrmCrtc *crtc, std::vector<DrmPlane *> *primary_planes, - std::vector<DrmPlane *> *overlay_planes) { - std::vector<DrmPlane *> usable_planes; - std::copy_if(primary_planes->begin(), primary_planes->end(), - std::back_inserter(usable_planes), - [=](DrmPlane *plane) { return plane->GetCrtcSupported(*crtc); }); - std::copy_if(overlay_planes->begin(), overlay_planes->end(), - std::back_inserter(usable_planes), - [=](DrmPlane *plane) { return plane->GetCrtcSupported(*crtc); }); - return usable_planes; -} - -int Planner::PlanStage::ValidatePlane(DrmPlane *plane, DrmHwcLayer *layer) { - int ret = 0; - uint64_t blend; - - if ((plane->rotation_property().id() == 0) && - layer->transform != DrmHwcTransform::kIdentity) { - ALOGE("Rotation is not supported on plane %d", plane->id()); - return -EINVAL; - } - - if (plane->alpha_property().id() == 0 && layer->alpha != 0xffff) { - ALOGE("Alpha is not supported on plane %d", plane->id()); - return -EINVAL; - } - - if (plane->blend_property().id() == 0) { - if ((layer->blending != DrmHwcBlending::kNone) && - (layer->blending != DrmHwcBlending::kPreMult)) { - ALOGE("Blending is not supported on plane %d", plane->id()); - return -EINVAL; - } - } else { - switch (layer->blending) { - case DrmHwcBlending::kPreMult: - std::tie(blend, ret) = plane->blend_property().GetEnumValueWithName( - "Pre-multiplied"); - break; - case DrmHwcBlending::kCoverage: - std::tie(blend, ret) = plane->blend_property().GetEnumValueWithName( - "Coverage"); - break; - case DrmHwcBlending::kNone: - default: - std::tie(blend, - ret) = plane->blend_property().GetEnumValueWithName("None"); - break; - } - if (ret) - ALOGE("Expected a valid blend mode on plane %d", plane->id()); - } - - uint32_t format = layer->buffer->format; - if (!plane->IsFormatSupported(format)) { - ALOGE("Plane %d does not supports %c%c%c%c format", plane->id(), format, - format >> 8, format >> 16, format >> 24); - return -EINVAL; - } - - return ret; -} - -std::tuple<int, std::vector<DrmCompositionPlane>> Planner::ProvisionPlanes( - std::map<size_t, DrmHwcLayer *> &layers, DrmCrtc *crtc, - std::vector<DrmPlane *> *primary_planes, - std::vector<DrmPlane *> *overlay_planes) { - std::vector<DrmCompositionPlane> composition; - std::vector<DrmPlane *> planes = GetUsablePlanes(crtc, primary_planes, - overlay_planes); - if (planes.empty()) { - ALOGE("Display %d has no usable planes", crtc->display()); - return std::make_tuple(-ENODEV, std::vector<DrmCompositionPlane>()); - } - - // Go through the provisioning stages and provision planes - for (auto &i : stages_) { - int ret = i->ProvisionPlanes(&composition, layers, crtc, &planes); - if (ret) { - ALOGE("Failed provision stage with ret %d", ret); - return std::make_tuple(ret, std::vector<DrmCompositionPlane>()); - } - } - - return std::make_tuple(0, std::move(composition)); -} - -int PlanStageProtected::ProvisionPlanes( - std::vector<DrmCompositionPlane> *composition, - std::map<size_t, DrmHwcLayer *> &layers, DrmCrtc *crtc, - std::vector<DrmPlane *> *planes) { - int ret; - int protected_zorder = -1; - for (auto i = layers.begin(); i != layers.end();) { - if (!i->second->protected_usage()) { - ++i; - continue; - } - - ret = Emplace(composition, planes, DrmCompositionPlane::Type::kLayer, crtc, - std::make_pair(i->first, i->second)); - if (ret) { - ALOGE("Failed to dedicate protected layer! Dropping it."); - return ret; - } - - protected_zorder = i->first; - i = layers.erase(i); - } - - return 0; -} - -int PlanStageGreedy::ProvisionPlanes( - std::vector<DrmCompositionPlane> *composition, - std::map<size_t, DrmHwcLayer *> &layers, DrmCrtc *crtc, - std::vector<DrmPlane *> *planes) { - // Fill up the remaining planes - for (auto i = layers.begin(); i != layers.end(); i = layers.erase(i)) { - int ret = Emplace(composition, planes, DrmCompositionPlane::Type::kLayer, - crtc, std::make_pair(i->first, i->second)); - // We don't have any planes left - if (ret == -ENOENT) - break; - else if (ret) { - ALOGE("Failed to emplace layer %zu, dropping it", i->first); - return ret; - } - } - - return 0; -} -} // namespace android diff --git a/compositor/Planner.h b/compositor/Planner.h deleted file mode 100644 index 09034ff..0000000 --- a/compositor/Planner.h +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (C) 2015 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ANDROID_DRM_PLATFORM_H_ -#define ANDROID_DRM_PLATFORM_H_ - -#include <hardware/hardware.h> -#include <hardware/hwcomposer.h> - -#include <map> -#include <vector> - -#include "compositor/DrmDisplayComposition.h" -#include "drmhwcomposer.h" - -namespace android { - -class DrmDevice; - -class Planner { - public: - class PlanStage { - public: - virtual ~PlanStage() { - } - - virtual int ProvisionPlanes(std::vector<DrmCompositionPlane> *composition, - std::map<size_t, DrmHwcLayer *> &layers, - DrmCrtc *crtc, - std::vector<DrmPlane *> *planes) = 0; - - protected: - // Removes and returns the next available plane from planes - static DrmPlane *PopPlane(std::vector<DrmPlane *> *planes) { - if (planes->empty()) - return NULL; - DrmPlane *plane = planes->front(); - planes->erase(planes->begin()); - return plane; - } - - static int ValidatePlane(DrmPlane *plane, DrmHwcLayer *layer); - - // Inserts the given layer:plane in the composition at the back - static int Emplace(std::vector<DrmCompositionPlane> *composition, - std::vector<DrmPlane *> *planes, - DrmCompositionPlane::Type type, DrmCrtc *crtc, - std::pair<size_t, DrmHwcLayer *> layer) { - DrmPlane *plane = PopPlane(planes); - std::vector<DrmPlane *> unused_planes; - int ret = -ENOENT; - while (plane) { - ret = ValidatePlane(plane, layer.second); - if (!ret) - break; - if (!plane->zpos_property().is_immutable()) - unused_planes.push_back(plane); - plane = PopPlane(planes); - } - - if (!ret) { - composition->emplace_back(type, plane, crtc, layer.first); - planes->insert(planes->begin(), unused_planes.begin(), - unused_planes.end()); - } - - return ret; - } - }; - - // Creates a planner instance with platform-specific planning stages - static std::unique_ptr<Planner> CreateInstance(DrmDevice *drm); - - // Takes a stack of layers and provisions hardware planes for them. If the - // entire stack can't fit in hardware, FIXME - // - // @layers: a map of index:layer of layers to composite - // @primary_planes: a vector of primary planes available for this frame - // @overlay_planes: a vector of overlay planes available for this frame - // - // Returns: A tuple with the status of the operation (0 for success) and - // a vector of the resulting plan (ie: layer->plane mapping). - std::tuple<int, std::vector<DrmCompositionPlane>> ProvisionPlanes( - std::map<size_t, DrmHwcLayer *> &layers, DrmCrtc *crtc, - std::vector<DrmPlane *> *primary_planes, - std::vector<DrmPlane *> *overlay_planes); - - template <typename T, typename... A> - void AddStage(A &&... args) { - stages_.emplace_back( - std::unique_ptr<PlanStage>(new T(std::forward(args)...))); - } - - private: - std::vector<DrmPlane *> GetUsablePlanes( - DrmCrtc *crtc, std::vector<DrmPlane *> *primary_planes, - std::vector<DrmPlane *> *overlay_planes); - - std::vector<std::unique_ptr<PlanStage>> stages_; -}; - -// This plan stage extracts all protected layers and places them on dedicated -// planes. -class PlanStageProtected : public Planner::PlanStage { - public: - int ProvisionPlanes(std::vector<DrmCompositionPlane> *composition, - std::map<size_t, DrmHwcLayer *> &layers, DrmCrtc *crtc, - std::vector<DrmPlane *> *planes); -}; - -// This plan stage places as many layers on dedicated planes as possible (first -// come first serve), and then sticks the rest in a precomposition plane (if -// needed). -class PlanStageGreedy : public Planner::PlanStage { - public: - int ProvisionPlanes(std::vector<DrmCompositionPlane> *composition, - std::map<size_t, DrmHwcLayer *> &layers, DrmCrtc *crtc, - std::vector<DrmPlane *> *planes); -}; -} // namespace android -#endif diff --git a/drm/DrmAtomicStateManager.cpp b/drm/DrmAtomicStateManager.cpp new file mode 100644 index 0000000..65fb19e --- /dev/null +++ b/drm/DrmAtomicStateManager.cpp @@ -0,0 +1,191 @@ +/* + * Copyright (C) 2015 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define ATRACE_TAG ATRACE_TAG_GRAPHICS +#define LOG_TAG "hwc-drm-atomic-state-manager" + +#include "DrmAtomicStateManager.h" + +#include <drm/drm_mode.h> +#include <pthread.h> +#include <sched.h> +#include <sync/sync.h> +#include <utils/Trace.h> + +#include <array> +#include <cstdlib> +#include <ctime> +#include <sstream> +#include <vector> + +#include "drm/DrmCrtc.h" +#include "drm/DrmDevice.h" +#include "drm/DrmPlane.h" +#include "drm/DrmUnique.h" +#include "utils/log.h" + +namespace android { + +// NOLINTNEXTLINE (readability-function-cognitive-complexity): Fixme +auto DrmAtomicStateManager::CommitFrame(AtomicCommitArgs &args) -> int { + ATRACE_CALL(); + + if (args.active && *args.active == active_frame_state_.crtc_active_state) { + /* Don't set the same state twice */ + args.active.reset(); + } + + if (!args.HasInputs()) { + /* nothing to do */ + return 0; + } + + if (!active_frame_state_.crtc_active_state) { + /* Force activate display */ + args.active = true; + } + + auto new_frame_state = NewFrameState(); + + auto *drm = pipe_->device; + auto *connector = pipe_->connector->Get(); + auto *crtc = pipe_->crtc->Get(); + + auto pset = MakeDrmModeAtomicReqUnique(); + if (!pset) { + ALOGE("Failed to allocate property set"); + return -ENOMEM; + } + + int64_t out_fence = -1; + if (crtc->GetOutFencePtrProperty() && + !crtc->GetOutFencePtrProperty().AtomicSet(*pset, uint64_t(&out_fence))) { + return -EINVAL; + } + + if (args.active) { + new_frame_state.crtc_active_state = *args.active; + if (!crtc->GetActiveProperty().AtomicSet(*pset, *args.active ? 1 : 0) || + !connector->GetCrtcIdProperty().AtomicSet(*pset, crtc->GetId())) { + return -EINVAL; + } + } + + if (args.display_mode) { + new_frame_state.mode_blob = args.display_mode.value().CreateModeBlob(*drm); + + if (!new_frame_state.mode_blob) { + ALOGE("Failed to create mode_blob"); + return -EINVAL; + } + + if (!crtc->GetModeProperty().AtomicSet(*pset, *new_frame_state.mode_blob)) { + return -EINVAL; + } + } + + auto unused_planes = new_frame_state.used_planes; + + if (args.composition) { + new_frame_state.used_framebuffers.clear(); + new_frame_state.used_planes.clear(); + + for (auto &joining : args.composition->plan) { + DrmPlane *plane = joining.plane->Get(); + DrmHwcLayer &layer = joining.layer; + + new_frame_state.used_framebuffers.emplace_back(layer.fb_id_handle); + new_frame_state.used_planes.emplace_back(joining.plane); + + /* Remove from 'unused' list, since plane is re-used */ + auto &v = unused_planes; + v.erase(std::remove(v.begin(), v.end(), joining.plane), v.end()); + + if (plane->AtomicSetState(*pset, layer, joining.z_pos, crtc->GetId()) != + 0) { + return -EINVAL; + } + } + } + + if (args.composition) { + for (auto &plane : unused_planes) { + if (plane->Get()->AtomicDisablePlane(*pset) != 0) { + return -EINVAL; + } + } + } + + uint32_t flags = DRM_MODE_ATOMIC_ALLOW_MODESET; + if (args.test_only) + flags |= DRM_MODE_ATOMIC_TEST_ONLY; + + int err = drmModeAtomicCommit(drm->GetFd(), pset.get(), flags, drm); + if (err != 0) { + if (!args.test_only) + ALOGE("Failed to commit pset ret=%d\n", err); + return err; + } + + if (!args.test_only) { + if (args.display_mode) { + /* TODO(nobody): we still need this for synthetic vsync, remove after + * vsync reworked */ + connector->SetActiveMode(*args.display_mode); + } + + active_frame_state_ = std::move(new_frame_state); + + if (crtc->GetOutFencePtrProperty()) { + args.out_fence = UniqueFd((int)out_fence); + } + } + + return 0; +} + +auto DrmAtomicStateManager::ExecuteAtomicCommit(AtomicCommitArgs &args) -> int { + int err = CommitFrame(args); + + if (!args.test_only) { + if (err != 0) { + ALOGE("Composite failed for pipeline %s", + pipe_->connector->Get()->GetName().c_str()); + // Disable the hw used by the last active composition. This allows us to + // signal the release fences from that composition to avoid hanging. + AtomicCommitArgs cl_args{}; + cl_args.composition = std::make_shared<DrmKmsPlan>(); + if (CommitFrame(cl_args) != 0) { + ALOGE("Failed to clean-up active composition for pipeline %s", + pipe_->connector->Get()->GetName().c_str()); + } + return err; + } + } + + return err; +} // namespace android + +auto DrmAtomicStateManager::ActivateDisplayUsingDPMS() -> int { + return drmModeConnectorSetProperty(pipe_->device->GetFd(), + pipe_->connector->Get()->GetId(), + pipe_->connector->Get() + ->GetDpmsProperty() + .id(), + DRM_MODE_DPMS_ON); +} + +} // namespace android diff --git a/drm/DrmAtomicStateManager.h b/drm/DrmAtomicStateManager.h new file mode 100644 index 0000000..08a1c13 --- /dev/null +++ b/drm/DrmAtomicStateManager.h @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2015 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_DRM_ATOMIC_STATE_MANAGER_H_ +#define ANDROID_DRM_ATOMIC_STATE_MANAGER_H_ + +#include <pthread.h> + +#include <functional> +#include <memory> +#include <optional> +#include <sstream> +#include <tuple> + +#include "compositor/DrmKmsPlan.h" +#include "drm/DrmPlane.h" +#include "drm/ResourceManager.h" +#include "drm/VSyncWorker.h" +#include "drmhwcomposer.h" + +namespace android { + +struct AtomicCommitArgs { + /* inputs. All fields are optional, but at least one has to be specified */ + bool test_only = false; + std::optional<DrmMode> display_mode; + std::optional<bool> active; + std::shared_ptr<DrmKmsPlan> composition; + + /* out */ + UniqueFd out_fence; + + /* helpers */ + auto HasInputs() -> bool { + return display_mode || active || composition; + } +}; + +class DrmAtomicStateManager { + public: + explicit DrmAtomicStateManager(DrmDisplayPipeline *pipe) : pipe_(pipe){}; + DrmAtomicStateManager(const DrmAtomicStateManager &) = delete; + ~DrmAtomicStateManager() = default; + + auto ExecuteAtomicCommit(AtomicCommitArgs &args) -> int; + auto ActivateDisplayUsingDPMS() -> int; + + private: + auto CommitFrame(AtomicCommitArgs &args) -> int; + + struct KmsState { + /* Required to cleanup unused planes */ + std::vector<std::shared_ptr<BindingOwner<DrmPlane>>> used_planes; + /* We have to hold a reference to framebuffer while displaying it , + * otherwise picture will blink */ + std::vector<std::shared_ptr<DrmFbIdHandle>> used_framebuffers; + + DrmModeUserPropertyBlobUnique mode_blob; + + /* To avoid setting the inactive state twice, which will fail the commit */ + bool crtc_active_state{}; + } active_frame_state_; + + auto NewFrameState() -> KmsState { + return (KmsState){ + .used_planes = active_frame_state_.used_planes, + .used_framebuffers = active_frame_state_.used_framebuffers, + .crtc_active_state = active_frame_state_.crtc_active_state, + }; + } + + DrmDisplayPipeline *const pipe_; +}; +} // namespace android + +#endif // ANDROID_DRM_DISPLAY_COMPOSITOR_H_ diff --git a/drm/DrmConnector.cpp b/drm/DrmConnector.cpp index f1b6c1b..4737316 100644 --- a/drm/DrmConnector.cpp +++ b/drm/DrmConnector.cpp @@ -18,237 +18,174 @@ #include "DrmConnector.h" -#include <errno.h> -#include <log/log.h> -#include <stdint.h> #include <xf86drmMode.h> #include <array> +#include <cerrno> +#include <cstdint> #include <sstream> #include "DrmDevice.h" +#include "utils/log.h" + +#ifndef DRM_MODE_CONNECTOR_SPI +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define DRM_MODE_CONNECTOR_SPI 19 +#endif + +#ifndef DRM_MODE_CONNECTOR_USB +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define DRM_MODE_CONNECTOR_USB 20 +#endif namespace android { -constexpr size_t TYPES_COUNT = 17; - -DrmConnector::DrmConnector(DrmDevice *drm, drmModeConnectorPtr c, - DrmEncoder *current_encoder, - std::vector<DrmEncoder *> &possible_encoders) - : drm_(drm), - id_(c->connector_id), - encoder_(current_encoder), - display_(-1), - type_(c->connector_type), - type_id_(c->connector_type_id), - state_(c->connection), - mm_width_(c->mmWidth), - mm_height_(c->mmHeight), - possible_encoders_(possible_encoders) { +constexpr size_t kTypesCount = 21; + +static bool GetOptionalConnectorProperty(const DrmDevice &dev, + const DrmConnector &connector, + const char *prop_name, + DrmProperty *property) { + return dev.GetProperty(connector.GetId(), DRM_MODE_OBJECT_CONNECTOR, + prop_name, property) == 0; } -int DrmConnector::Init() { - int ret = drm_->GetConnectorProperty(*this, "DPMS", &dpms_property_); - if (ret) { - ALOGE("Could not get DPMS property\n"); - return ret; - } - ret = drm_->GetConnectorProperty(*this, "CRTC_ID", &crtc_id_property_); - if (ret) { - ALOGE("Could not get CRTC_ID property\n"); - return ret; +static bool GetConnectorProperty(const DrmDevice &dev, + const DrmConnector &connector, + const char *prop_name, DrmProperty *property) { + if (!GetOptionalConnectorProperty(dev, connector, prop_name, property)) { + ALOGE("Could not get %s property\n", prop_name); + return false; } - ret = UpdateEdidProperty(); - if (writeback()) { - ret = drm_->GetConnectorProperty(*this, "WRITEBACK_PIXEL_FORMATS", - &writeback_pixel_formats_); - if (ret) { - ALOGE("Could not get WRITEBACK_PIXEL_FORMATS connector_id = %d\n", id_); - return ret; - } - ret = drm_->GetConnectorProperty(*this, "WRITEBACK_FB_ID", - &writeback_fb_id_); - if (ret) { - ALOGE("Could not get WRITEBACK_FB_ID connector_id = %d\n", id_); - return ret; - } - ret = drm_->GetConnectorProperty(*this, "WRITEBACK_OUT_FENCE_PTR", - &writeback_out_fence_); - if (ret) { - ALOGE("Could not get WRITEBACK_OUT_FENCE_PTR connector_id = %d\n", id_); - return ret; - } - } - return 0; + return true; } -int DrmConnector::UpdateEdidProperty() { - int ret = drm_->GetConnectorProperty(*this, "EDID", &edid_property_); - if (ret) { - ALOGW("Could not get EDID property\n"); +auto DrmConnector::CreateInstance(DrmDevice &dev, uint32_t connector_id, + uint32_t index) + -> std::unique_ptr<DrmConnector> { + auto conn = MakeDrmModeConnectorUnique(dev.GetFd(), connector_id); + if (!conn) { + ALOGE("Failed to get connector %d", connector_id); + return {}; } - return ret; -} -int DrmConnector::GetEdidBlob(drmModePropertyBlobPtr &blob) { - uint64_t blob_id; - int ret = UpdateEdidProperty(); - if (ret) { - return ret; + auto c = std::unique_ptr<DrmConnector>( + new DrmConnector(std::move(conn), &dev, index)); + + if (!GetConnectorProperty(dev, *c, "DPMS", &c->dpms_property_) || + !GetConnectorProperty(dev, *c, "CRTC_ID", &c->crtc_id_property_)) { + return {}; } - std::tie(ret, blob_id) = edid_property().value(); - if (ret) { - return ret; + c->UpdateEdidProperty(); + + if (c->IsWriteback() && + (!GetConnectorProperty(dev, *c, "WRITEBACK_PIXEL_FORMATS", + &c->writeback_pixel_formats_) || + !GetConnectorProperty(dev, *c, "WRITEBACK_FB_ID", + &c->writeback_fb_id_) || + !GetConnectorProperty(dev, *c, "WRITEBACK_OUT_FENCE_PTR", + &c->writeback_out_fence_))) { + return {}; } - blob = drmModeGetPropertyBlob(drm_->fd(), blob_id); - return !blob; + return c; } -uint32_t DrmConnector::id() const { - return id_; +int DrmConnector::UpdateEdidProperty() { + return GetOptionalConnectorProperty(*drm_, *this, "EDID", &edid_property_) + ? 0 + : -EINVAL; } -int DrmConnector::display() const { - return display_; -} +auto DrmConnector::GetEdidBlob() -> DrmModePropertyBlobUnique { + uint64_t blob_id = 0; + int ret = UpdateEdidProperty(); + if (ret != 0) { + return {}; + } -void DrmConnector::set_display(int display) { - display_ = display; + std::tie(ret, blob_id) = GetEdidProperty().value(); + if (ret != 0) { + return {}; + } + + return MakeDrmModePropertyBlobUnique(drm_->GetFd(), blob_id); } -bool DrmConnector::internal() const { - return type_ == DRM_MODE_CONNECTOR_LVDS || type_ == DRM_MODE_CONNECTOR_eDP || - type_ == DRM_MODE_CONNECTOR_DSI || - type_ == DRM_MODE_CONNECTOR_VIRTUAL || type_ == DRM_MODE_CONNECTOR_DPI; +bool DrmConnector::IsInternal() const { + auto type = connector_->connector_type; + return type == DRM_MODE_CONNECTOR_LVDS || type == DRM_MODE_CONNECTOR_eDP || + type == DRM_MODE_CONNECTOR_DSI || type == DRM_MODE_CONNECTOR_VIRTUAL || + type == DRM_MODE_CONNECTOR_DPI || type == DRM_MODE_CONNECTOR_SPI; } -bool DrmConnector::external() const { - return type_ == DRM_MODE_CONNECTOR_HDMIA || - type_ == DRM_MODE_CONNECTOR_DisplayPort || - type_ == DRM_MODE_CONNECTOR_DVID || type_ == DRM_MODE_CONNECTOR_DVII || - type_ == DRM_MODE_CONNECTOR_VGA; +bool DrmConnector::IsExternal() const { + auto type = connector_->connector_type; + return type == DRM_MODE_CONNECTOR_HDMIA || + type == DRM_MODE_CONNECTOR_DisplayPort || + type == DRM_MODE_CONNECTOR_DVID || type == DRM_MODE_CONNECTOR_DVII || + type == DRM_MODE_CONNECTOR_VGA || type == DRM_MODE_CONNECTOR_USB; } -bool DrmConnector::writeback() const { +bool DrmConnector::IsWriteback() const { #ifdef DRM_MODE_CONNECTOR_WRITEBACK - return type_ == DRM_MODE_CONNECTOR_WRITEBACK; + return connector_->connector_type == DRM_MODE_CONNECTOR_WRITEBACK; #else return false; #endif } -bool DrmConnector::valid_type() const { - return internal() || external() || writeback(); +bool DrmConnector::IsValid() const { + return IsInternal() || IsExternal() || IsWriteback(); } -std::string DrmConnector::name() const { - constexpr std::array<const char *, TYPES_COUNT> names = - {"None", "VGA", "DVI-I", "DVI-D", "DVI-A", "Composite", - "SVIDEO", "LVDS", "Component", "DIN", "DP", "HDMI-A", - "HDMI-B", "TV", "eDP", "Virtual", "DSI"}; +std::string DrmConnector::GetName() const { + constexpr std::array<const char *, kTypesCount> kNames = + {"None", "VGA", "DVI-I", "DVI-D", "DVI-A", "Composite", + "SVIDEO", "LVDS", "Component", "DIN", "DP", "HDMI-A", + "HDMI-B", "TV", "eDP", "Virtual", "DSI", "DPI", + "Writeback", "SPI", "USB"}; - if (type_ < TYPES_COUNT) { + if (connector_->connector_type < kTypesCount) { std::ostringstream name_buf; - name_buf << names[type_] << "-" << type_id_; + name_buf << kNames[connector_->connector_type] << "-" + << connector_->connector_type_id; return name_buf.str(); - } else { - ALOGE("Unknown type in connector %d, could not make his name", id_); - return "None"; } + + ALOGE("Unknown type in connector %d, could not make his name", GetId()); + return "None"; } int DrmConnector::UpdateModes() { - int fd = drm_->fd(); - - drmModeConnectorPtr c = drmModeGetConnector(fd, id_); - if (!c) { - ALOGE("Failed to get connector %d", id_); + auto conn = MakeDrmModeConnectorUnique(drm_->GetFd(), GetId()); + if (!conn) { + ALOGE("Failed to get connector %d", GetId()); return -ENODEV; } + connector_ = std::move(conn); - state_ = c->connection; - - bool preferred_mode_found = false; - std::vector<DrmMode> new_modes; - for (int i = 0; i < c->count_modes; ++i) { + modes_.clear(); + for (int i = 0; i < connector_->count_modes; ++i) { bool exists = false; for (const DrmMode &mode : modes_) { - if (mode == c->modes[i]) { - new_modes.push_back(mode); + if (mode == connector_->modes[i]) { exists = true; break; } } + if (!exists) { - DrmMode m(&c->modes[i]); - m.set_id(drm_->next_mode_id()); - new_modes.push_back(m); + modes_.emplace_back(DrmMode(&connector_->modes[i])); } - // Use only the first DRM_MODE_TYPE_PREFERRED mode found - if (!preferred_mode_found && - (new_modes.back().type() & DRM_MODE_TYPE_PREFERRED)) { - preferred_mode_id_ = new_modes.back().id(); - preferred_mode_found = true; - } - } - modes_.swap(new_modes); - if (!preferred_mode_found && modes_.size() != 0) { - preferred_mode_id_ = modes_[0].id(); } - return 0; -} -const DrmMode &DrmConnector::active_mode() const { - return active_mode_; + return 0; } -void DrmConnector::set_active_mode(const DrmMode &mode) { +void DrmConnector::SetActiveMode(DrmMode &mode) { active_mode_ = mode; } -const DrmProperty &DrmConnector::dpms_property() const { - return dpms_property_; -} - -const DrmProperty &DrmConnector::crtc_id_property() const { - return crtc_id_property_; -} - -const DrmProperty &DrmConnector::edid_property() const { - return edid_property_; -} - -const DrmProperty &DrmConnector::writeback_pixel_formats() const { - return writeback_pixel_formats_; -} - -const DrmProperty &DrmConnector::writeback_fb_id() const { - return writeback_fb_id_; -} - -const DrmProperty &DrmConnector::writeback_out_fence() const { - return writeback_out_fence_; -} - -DrmEncoder *DrmConnector::encoder() const { - return encoder_; -} - -void DrmConnector::set_encoder(DrmEncoder *encoder) { - encoder_ = encoder; -} - -drmModeConnection DrmConnector::state() const { - return state_; -} - -uint32_t DrmConnector::mm_width() const { - return mm_width_; -} - -uint32_t DrmConnector::mm_height() const { - return mm_height_; -} } // namespace android diff --git a/drm/DrmConnector.h b/drm/DrmConnector.h index 8533af8..629b3cc 100644 --- a/drm/DrmConnector.h +++ b/drm/DrmConnector.h @@ -17,87 +17,112 @@ #ifndef ANDROID_DRM_CONNECTOR_H_ #define ANDROID_DRM_CONNECTOR_H_ -#include <stdint.h> #include <xf86drmMode.h> +#include <cstdint> #include <string> #include <vector> #include "DrmEncoder.h" #include "DrmMode.h" #include "DrmProperty.h" +#include "DrmUnique.h" namespace android { class DrmDevice; -class DrmConnector { +class DrmConnector : public PipelineBindable<DrmConnector> { public: - DrmConnector(DrmDevice *drm, drmModeConnectorPtr c, - DrmEncoder *current_encoder, - std::vector<DrmEncoder *> &possible_encoders); + static auto CreateInstance(DrmDevice &dev, uint32_t connector_id, + uint32_t index) -> std::unique_ptr<DrmConnector>; + DrmConnector(const DrmProperty &) = delete; DrmConnector &operator=(const DrmProperty &) = delete; - int Init(); int UpdateEdidProperty(); - int GetEdidBlob(drmModePropertyBlobPtr &blob); + auto GetEdidBlob() -> DrmModePropertyBlobUnique; + + auto GetDev() const -> DrmDevice & { + return *drm_; + } - uint32_t id() const; + auto GetId() const { + return connector_->connector_id; + } - int display() const; - void set_display(int display); + auto GetIndexInResArray() const { + return index_in_res_array_; + } - bool internal() const; - bool external() const; - bool writeback() const; - bool valid_type() const; + auto GetCurrentEncoderId() const { + return connector_->encoder_id; + } - std::string name() const; + auto SupportsEncoder(DrmEncoder &enc) const { + for (int i = 0; i < connector_->count_encoders; i++) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) + if (connector_->encoders[i] == enc.GetId()) { + return true; + } + } + + return false; + } + + bool IsInternal() const; + bool IsExternal() const; + bool IsWriteback() const; + bool IsValid() const; + + std::string GetName() const; int UpdateModes(); - const std::vector<DrmMode> &modes() const { + auto &GetModes() const { return modes_; } - const DrmMode &active_mode() const; - void set_active_mode(const DrmMode &mode); - - const DrmProperty &dpms_property() const; - const DrmProperty &crtc_id_property() const; - const DrmProperty &edid_property() const; - const DrmProperty &writeback_pixel_formats() const; - const DrmProperty &writeback_fb_id() const; - const DrmProperty &writeback_out_fence() const; - - const std::vector<DrmEncoder *> &possible_encoders() const { - return possible_encoders_; + + auto &GetActiveMode() const { + return active_mode_; + } + + void SetActiveMode(DrmMode &mode); + + auto &GetDpmsProperty() const { + return dpms_property_; } - DrmEncoder *encoder() const; - void set_encoder(DrmEncoder *encoder); - drmModeConnection state() const; + auto &GetCrtcIdProperty() const { + return crtc_id_property_; + } - uint32_t mm_width() const; - uint32_t mm_height() const; + auto &GetEdidProperty() const { + return edid_property_; + } - uint32_t get_preferred_mode_id() const { - return preferred_mode_id_; + auto IsConnected() const { + return connector_->connection == DRM_MODE_CONNECTED; } - private: - DrmDevice *drm_; + auto GetMmWidth() const { + return connector_->mmWidth; + } + + auto GetMmHeight() const { + return connector_->mmHeight; + }; - uint32_t id_; - DrmEncoder *encoder_; - int display_; + private: + DrmConnector(DrmModeConnectorUnique connector, DrmDevice *drm, uint32_t index) + : connector_(std::move(connector)), + drm_(drm), + index_in_res_array_(index){}; - uint32_t type_; - uint32_t type_id_; - drmModeConnection state_; + DrmModeConnectorUnique connector_; + DrmDevice *const drm_; - uint32_t mm_width_; - uint32_t mm_height_; + const uint32_t index_in_res_array_; DrmMode active_mode_; std::vector<DrmMode> modes_; @@ -108,10 +133,6 @@ class DrmConnector { DrmProperty writeback_pixel_formats_; DrmProperty writeback_fb_id_; DrmProperty writeback_out_fence_; - - std::vector<DrmEncoder *> possible_encoders_; - - uint32_t preferred_mode_id_; }; } // namespace android diff --git a/drm/DrmCrtc.cpp b/drm/DrmCrtc.cpp index 4ce8cfc..b54f14b 100644 --- a/drm/DrmCrtc.cpp +++ b/drm/DrmCrtc.cpp @@ -18,68 +18,50 @@ #include "DrmCrtc.h" -#include <log/log.h> -#include <stdint.h> +#include <utils/log.h> #include <xf86drmMode.h> +#include <cstdint> + #include "DrmDevice.h" namespace android { -DrmCrtc::DrmCrtc(DrmDevice *drm, drmModeCrtcPtr c, unsigned pipe) - : drm_(drm), id_(c->crtc_id), pipe_(pipe), display_(-1), mode_(&c->mode) { +static int GetCrtcProperty(const DrmDevice &dev, const DrmCrtc &crtc, + const char *prop_name, DrmProperty *property) { + return dev.GetProperty(crtc.GetId(), DRM_MODE_OBJECT_CRTC, prop_name, + property); } -int DrmCrtc::Init() { - int ret = drm_->GetCrtcProperty(*this, "ACTIVE", &active_property_); - if (ret) { +auto DrmCrtc::CreateInstance(DrmDevice &dev, uint32_t crtc_id, uint32_t index) + -> std::unique_ptr<DrmCrtc> { + auto crtc = MakeDrmModeCrtcUnique(dev.GetFd(), crtc_id); + if (!crtc) { + ALOGE("Failed to get CRTC %d", crtc_id); + return {}; + } + + auto c = std::unique_ptr<DrmCrtc>(new DrmCrtc(std::move(crtc), index)); + + int ret = GetCrtcProperty(dev, *c, "ACTIVE", &c->active_property_); + if (ret != 0) { ALOGE("Failed to get ACTIVE property"); - return ret; + return {}; } - ret = drm_->GetCrtcProperty(*this, "MODE_ID", &mode_property_); - if (ret) { + ret = GetCrtcProperty(dev, *c, "MODE_ID", &c->mode_property_); + if (ret != 0) { ALOGE("Failed to get MODE_ID property"); - return ret; + return {}; } - ret = drm_->GetCrtcProperty(*this, "OUT_FENCE_PTR", &out_fence_ptr_property_); - if (ret) { + ret = GetCrtcProperty(dev, *c, "OUT_FENCE_PTR", &c->out_fence_ptr_property_); + if (ret != 0) { ALOGE("Failed to get OUT_FENCE_PTR property"); - return ret; + return {}; } - return 0; -} - -uint32_t DrmCrtc::id() const { - return id_; -} - -unsigned DrmCrtc::pipe() const { - return pipe_; -} -int DrmCrtc::display() const { - return display_; + return c; } -void DrmCrtc::set_display(int display) { - display_ = display; -} - -bool DrmCrtc::can_bind(int display) const { - return display_ == -1 || display_ == display; -} - -const DrmProperty &DrmCrtc::active_property() const { - return active_property_; -} - -const DrmProperty &DrmCrtc::mode_property() const { - return mode_property_; -} - -const DrmProperty &DrmCrtc::out_fence_ptr_property() const { - return out_fence_ptr_property_; -} } // namespace android diff --git a/drm/DrmCrtc.h b/drm/DrmCrtc.h index 7972bef..ebf0a97 100644 --- a/drm/DrmCrtc.h +++ b/drm/DrmCrtc.h @@ -17,44 +17,55 @@ #ifndef ANDROID_DRM_CRTC_H_ #define ANDROID_DRM_CRTC_H_ -#include <stdint.h> #include <xf86drmMode.h> +#include <cstdint> + +#include "DrmDisplayPipeline.h" #include "DrmMode.h" #include "DrmProperty.h" +#include "DrmUnique.h" namespace android { class DrmDevice; -class DrmCrtc { +class DrmCrtc : public PipelineBindable<DrmCrtc> { public: - DrmCrtc(DrmDevice *drm, drmModeCrtcPtr c, unsigned pipe); + static auto CreateInstance(DrmDevice &dev, uint32_t crtc_id, uint32_t index) + -> std::unique_ptr<DrmCrtc>; + + DrmCrtc() = delete; DrmCrtc(const DrmCrtc &) = delete; DrmCrtc &operator=(const DrmCrtc &) = delete; - int Init(); + auto GetId() const { + return crtc_->crtc_id; + } - uint32_t id() const; - unsigned pipe() const; + auto GetIndexInResArray() const { + return index_in_res_array_; + } - int display() const; - void set_display(int display); + auto &GetActiveProperty() const { + return active_property_; + } - bool can_bind(int display) const; + auto &GetModeProperty() const { + return mode_property_; + } - const DrmProperty &active_property() const; - const DrmProperty &mode_property() const; - const DrmProperty &out_fence_ptr_property() const; + auto &GetOutFencePtrProperty() const { + return out_fence_ptr_property_; + } private: - DrmDevice *drm_; + DrmCrtc(DrmModeCrtcUnique crtc, uint32_t index) + : crtc_(std::move(crtc)), index_in_res_array_(index){}; - uint32_t id_; - unsigned pipe_; - int display_; + DrmModeCrtcUnique crtc_; - DrmMode mode_; + const uint32_t index_in_res_array_; DrmProperty active_property_; DrmProperty mode_property_; diff --git a/drm/DrmDevice.cpp b/drm/DrmDevice.cpp index bf1a5e2..fd4589e 100644 --- a/drm/DrmDevice.cpp +++ b/drm/DrmDevice.cpp @@ -18,137 +18,70 @@ #include "DrmDevice.h" -#include <cutils/properties.h> -#include <errno.h> #include <fcntl.h> -#include <log/log.h> -#include <stdint.h> #include <xf86drm.h> #include <xf86drmMode.h> -#include <algorithm> -#include <array> #include <cinttypes> -#include <sstream> +#include <cstdint> #include <string> -static void trim_left(std::string &str) { - str.erase(std::begin(str), - std::find_if(std::begin(str), std::end(str), - [](int ch) { return !std::isspace(ch); })); -} - -static void trim_right(std::string &str) { - str.erase(std::find_if(std::rbegin(str), std::rend(str), - [](int ch) { return !std::isspace(ch); }) - .base(), - std::end(str)); -} - -static void trim(std::string &str) { - trim_left(str); - trim_right(str); -} +#include "drm/DrmAtomicStateManager.h" +#include "drm/DrmPlane.h" +#include "utils/log.h" +#include "utils/properties.h" namespace android { -static std::vector<std::string> read_primary_display_order_prop() { - std::array<char, PROPERTY_VALUE_MAX> display_order_buf; - property_get("vendor.hwc.drm.primary_display_order", display_order_buf.data(), - "..."); - - std::vector<std::string> display_order; - std::istringstream str(display_order_buf.data()); - for (std::string conn_name = ""; std::getline(str, conn_name, ',');) { - trim(conn_name); - display_order.push_back(std::move(conn_name)); - } - return display_order; -} - -static std::vector<DrmConnector *> make_primary_display_candidates( - std::vector<std::unique_ptr<DrmConnector>> &connectors) { - std::vector<DrmConnector *> primary_candidates; - std::transform(std::begin(connectors), std::end(connectors), - std::back_inserter(primary_candidates), - [](std::unique_ptr<DrmConnector> &conn) { - return conn.get(); - }); - primary_candidates.erase(std::remove_if(std::begin(primary_candidates), - std::end(primary_candidates), - [](const DrmConnector *conn) { - return conn->state() != - DRM_MODE_CONNECTED; - }), - std::end(primary_candidates)); - - std::vector<std::string> display_order = read_primary_display_order_prop(); - bool use_other = display_order.back() == "..."; - - // putting connectors from primary_display_order first - auto curr_connector = std::begin(primary_candidates); - for (const std::string &display_name : display_order) { - auto it = std::find_if(std::begin(primary_candidates), - std::end(primary_candidates), - [&display_name](const DrmConnector *conn) { - return conn->name() == display_name; - }); - if (it != std::end(primary_candidates)) { - std::iter_swap(it, curr_connector); - ++curr_connector; - } - } - - if (use_other) { - // then putting internal connectors second, everything else afterwards - std::partition(curr_connector, std::end(primary_candidates), - [](const DrmConnector *conn) { return conn->internal(); }); - } else { - primary_candidates.erase(curr_connector, std::end(primary_candidates)); - } - - return primary_candidates; -} - -DrmDevice::DrmDevice() : event_listener_(this) { -} - -DrmDevice::~DrmDevice() { - event_listener_.Exit(); +DrmDevice::DrmDevice() { + drm_fb_importer_ = std::make_unique<DrmFbImporter>(*this); } -std::tuple<int, int> DrmDevice::Init(const char *path, int num_displays) { +auto DrmDevice::Init(const char *path) -> int { /* TODO: Use drmOpenControl here instead */ - fd_.Set(open(path, O_RDWR)); - if (fd() < 0) { + fd_ = UniqueFd(open(path, O_RDWR | O_CLOEXEC)); + if (!fd_) { + // NOLINTNEXTLINE(concurrency-mt-unsafe): Fixme ALOGE("Failed to open dri %s: %s", path, strerror(errno)); - return std::make_tuple(-ENODEV, 0); + return -ENODEV; } - int ret = drmSetClientCap(fd(), DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1); - if (ret) { + int ret = drmSetClientCap(GetFd(), DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1); + if (ret != 0) { ALOGE("Failed to set universal plane cap %d", ret); - return std::make_tuple(ret, 0); + return ret; } - ret = drmSetClientCap(fd(), DRM_CLIENT_CAP_ATOMIC, 1); - if (ret) { + ret = drmSetClientCap(GetFd(), DRM_CLIENT_CAP_ATOMIC, 1); + if (ret != 0) { ALOGE("Failed to set atomic cap %d", ret); - return std::make_tuple(ret, 0); + return ret; } #ifdef DRM_CLIENT_CAP_WRITEBACK_CONNECTORS - ret = drmSetClientCap(fd(), DRM_CLIENT_CAP_WRITEBACK_CONNECTORS, 1); - if (ret) { + ret = drmSetClientCap(GetFd(), DRM_CLIENT_CAP_WRITEBACK_CONNECTORS, 1); + if (ret != 0) { ALOGI("Failed to set writeback cap %d", ret); - ret = 0; } #endif - drmModeResPtr res = drmModeGetResources(fd()); + uint64_t cap_value = 0; + if (drmGetCap(GetFd(), DRM_CAP_ADDFB2_MODIFIERS, &cap_value) != 0) { + ALOGW("drmGetCap failed. Fallback to no modifier support."); + cap_value = 0; + } + HasAddFb2ModifiersSupport_ = cap_value != 0; + + drmSetMaster(GetFd()); + if (drmIsMaster(GetFd()) == 0) { + ALOGE("DRM/KMS master access required"); + return -EACCES; + } + + auto res = MakeDrmModeResUnique(GetFd()); if (!res) { ALOGE("Failed to get DrmDevice resources"); - return std::make_tuple(-ENODEV, 0); + return -ENODEV; } min_resolution_ = std::pair<uint32_t, uint32_t>(res->min_width, @@ -156,390 +89,100 @@ std::tuple<int, int> DrmDevice::Init(const char *path, int num_displays) { max_resolution_ = std::pair<uint32_t, uint32_t>(res->max_width, res->max_height); - // Assumes that the primary display will always be in the first - // drm_device opened. - bool found_primary = num_displays != 0; - - for (int i = 0; !ret && i < res->count_crtcs; ++i) { - drmModeCrtcPtr c = drmModeGetCrtc(fd(), res->crtcs[i]); - if (!c) { - ALOGE("Failed to get crtc %d", res->crtcs[i]); - ret = -ENODEV; - break; + for (int i = 0; i < res->count_crtcs; ++i) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) + auto crtc = DrmCrtc::CreateInstance(*this, res->crtcs[i], i); + if (crtc) { + crtcs_.emplace_back(std::move(crtc)); } - - std::unique_ptr<DrmCrtc> crtc(new DrmCrtc(this, c, i)); - drmModeFreeCrtc(c); - - ret = crtc->Init(); - if (ret) { - ALOGE("Failed to initialize crtc %d", res->crtcs[i]); - break; - } - crtcs_.emplace_back(std::move(crtc)); } - std::vector<int> possible_clones; - for (int i = 0; !ret && i < res->count_encoders; ++i) { - drmModeEncoderPtr e = drmModeGetEncoder(fd(), res->encoders[i]); - if (!e) { - ALOGE("Failed to get encoder %d", res->encoders[i]); - ret = -ENODEV; - break; - } - - std::vector<DrmCrtc *> possible_crtcs; - DrmCrtc *current_crtc = NULL; - for (auto &crtc : crtcs_) { - if ((1 << crtc->pipe()) & e->possible_crtcs) - possible_crtcs.push_back(crtc.get()); - - if (crtc->id() == e->crtc_id) - current_crtc = crtc.get(); + for (int i = 0; i < res->count_encoders; ++i) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) + auto enc = DrmEncoder::CreateInstance(*this, res->encoders[i], i); + if (enc) { + encoders_.emplace_back(std::move(enc)); } - - std::unique_ptr<DrmEncoder> enc( - new DrmEncoder(e, current_crtc, possible_crtcs)); - possible_clones.push_back(e->possible_clones); - drmModeFreeEncoder(e); - - encoders_.emplace_back(std::move(enc)); } - for (unsigned int i = 0; i < encoders_.size(); i++) { - for (unsigned int j = 0; j < encoders_.size(); j++) - if (possible_clones[i] & (1 << j)) - encoders_[i]->AddPossibleClone(encoders_[j].get()); - } - - for (int i = 0; !ret && i < res->count_connectors; ++i) { - drmModeConnectorPtr c = drmModeGetConnector(fd(), res->connectors[i]); - if (!c) { - ALOGE("Failed to get connector %d", res->connectors[i]); - ret = -ENODEV; - break; - } - - std::vector<DrmEncoder *> possible_encoders; - DrmEncoder *current_encoder = NULL; - for (int j = 0; j < c->count_encoders; ++j) { - for (auto &encoder : encoders_) { - if (encoder->id() == c->encoders[j]) - possible_encoders.push_back(encoder.get()); - if (encoder->id() == c->encoder_id) - current_encoder = encoder.get(); - } - } + for (int i = 0; i < res->count_connectors; ++i) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) + auto conn = DrmConnector::CreateInstance(*this, res->connectors[i], i); - std::unique_ptr<DrmConnector> conn( - new DrmConnector(this, c, current_encoder, possible_encoders)); - - drmModeFreeConnector(c); - - ret = conn->Init(); - if (ret) { - ALOGE("Init connector %d failed", res->connectors[i]); - break; + if (!conn) { + continue; } - if (conn->writeback()) + if (conn->IsWriteback()) { writeback_connectors_.emplace_back(std::move(conn)); - else + } else { connectors_.emplace_back(std::move(conn)); - } - - // Primary display priority: - // 1) vendor.hwc.drm.primary_display_order property - // 2) internal connectors - // 3) anything else - std::vector<DrmConnector *> - primary_candidates = make_primary_display_candidates(connectors_); - if (!primary_candidates.empty() && !found_primary) { - DrmConnector &conn = **std::begin(primary_candidates); - conn.set_display(num_displays); - displays_[num_displays] = num_displays; - ++num_displays; - found_primary = true; - } else { - ALOGE( - "Failed to find primary display from " - "\"vendor.hwc.drm.primary_display_order\" property"); - } - - // If no priority display were found then pick first available as primary and - // for the others assign consecutive display_numbers. - for (auto &conn : connectors_) { - if (conn->external() || conn->internal()) { - if (!found_primary) { - conn->set_display(num_displays); - displays_[num_displays] = num_displays; - found_primary = true; - ++num_displays; - } else if (conn->display() < 0) { - conn->set_display(num_displays); - displays_[num_displays] = num_displays; - ++num_displays; - } } } - if (res) - drmModeFreeResources(res); - - // Catch-all for the above loops - if (ret) - return std::make_tuple(ret, 0); - - drmModePlaneResPtr plane_res = drmModeGetPlaneResources(fd()); + auto plane_res = MakeDrmModePlaneResUnique(GetFd()); if (!plane_res) { ALOGE("Failed to get plane resources"); - return std::make_tuple(-ENOENT, 0); + return -ENOENT; } for (uint32_t i = 0; i < plane_res->count_planes; ++i) { - drmModePlanePtr p = drmModeGetPlane(fd(), plane_res->planes[i]); - if (!p) { - ALOGE("Failed to get plane %d", plane_res->planes[i]); - ret = -ENODEV; - break; - } - - std::unique_ptr<DrmPlane> plane(new DrmPlane(this, p)); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) + auto plane = DrmPlane::CreateInstance(*this, plane_res->planes[i]); - drmModeFreePlane(p); - - ret = plane->Init(); - if (ret) { - ALOGE("Init plane %d failed", plane_res->planes[i]); - break; + if (plane) { + planes_.emplace_back(std::move(plane)); } - - planes_.emplace_back(std::move(plane)); - } - drmModeFreePlaneResources(plane_res); - if (ret) - return std::make_tuple(ret, 0); - - ret = event_listener_.Init(); - if (ret) { - ALOGE("Can't initialize event listener %d", ret); - return std::make_tuple(ret, 0); } - for (auto &conn : connectors_) { - ret = CreateDisplayPipe(conn.get()); - if (ret) { - ALOGE("Failed CreateDisplayPipe %d with %d", conn->id(), ret); - return std::make_tuple(ret, 0); - } - if (!AttachWriteback(conn.get())) { - ALOGI("Display %d has writeback attach to it", conn->display()); - } - } - return std::make_tuple(ret, displays_.size()); -} - -bool DrmDevice::HandlesDisplay(int display) const { - return displays_.find(display) != displays_.end(); -} - -DrmConnector *DrmDevice::GetConnectorForDisplay(int display) const { - for (auto &conn : connectors_) { - if (conn->display() == display) - return conn.get(); - } - return NULL; -} - -DrmConnector *DrmDevice::GetWritebackConnectorForDisplay(int display) const { - for (auto &conn : writeback_connectors_) { - if (conn->display() == display) - return conn.get(); - } - return NULL; -} - -// TODO what happens when hotplugging -DrmConnector *DrmDevice::AvailableWritebackConnector(int display) const { - DrmConnector *writeback_conn = GetWritebackConnectorForDisplay(display); - DrmConnector *display_conn = GetConnectorForDisplay(display); - // If we have a writeback already attached to the same CRTC just use that, - // if possible. - if (display_conn && writeback_conn && - writeback_conn->encoder()->CanClone(display_conn->encoder())) - return writeback_conn; - - // Use another CRTC if available and doesn't have any connector - for (auto &crtc : crtcs_) { - if (crtc->display() == display) - continue; - display_conn = GetConnectorForDisplay(crtc->display()); - // If we have a display connected don't use it for writeback - if (display_conn && display_conn->state() == DRM_MODE_CONNECTED) - continue; - writeback_conn = GetWritebackConnectorForDisplay(crtc->display()); - if (writeback_conn) - return writeback_conn; - } - return NULL; -} - -DrmCrtc *DrmDevice::GetCrtcForDisplay(int display) const { - for (auto &crtc : crtcs_) { - if (crtc->display() == display) - return crtc.get(); - } - return NULL; -} - -DrmPlane *DrmDevice::GetPlane(uint32_t id) const { - for (auto &plane : planes_) { - if (plane->id() == id) - return plane.get(); - } - return NULL; -} - -const std::vector<std::unique_ptr<DrmCrtc>> &DrmDevice::crtcs() const { - return crtcs_; -} - -uint32_t DrmDevice::next_mode_id() { - return ++mode_id_; -} - -int DrmDevice::TryEncoderForDisplay(int display, DrmEncoder *enc) { - /* First try to use the currently-bound crtc */ - DrmCrtc *crtc = enc->crtc(); - if (crtc && crtc->can_bind(display)) { - crtc->set_display(display); - enc->set_crtc(crtc); - return 0; - } - - /* Try to find a possible crtc which will work */ - for (DrmCrtc *crtc : enc->possible_crtcs()) { - /* We've already tried this earlier */ - if (crtc == enc->crtc()) - continue; - - if (crtc->can_bind(display)) { - crtc->set_display(display); - enc->set_crtc(crtc); - return 0; - } - } - - /* We can't use the encoder, but nothing went wrong, try another one */ - return -EAGAIN; -} - -int DrmDevice::CreateDisplayPipe(DrmConnector *connector) { - int display = connector->display(); - /* Try to use current setup first */ - if (connector->encoder()) { - int ret = TryEncoderForDisplay(display, connector->encoder()); - if (!ret) { - return 0; - } else if (ret != -EAGAIN) { - ALOGE("Could not set mode %d/%d", display, ret); - return ret; - } - } - - for (DrmEncoder *enc : connector->possible_encoders()) { - int ret = TryEncoderForDisplay(display, enc); - if (!ret) { - connector->set_encoder(enc); - return 0; - } else if (ret != -EAGAIN) { - ALOGE("Could not set mode %d/%d", display, ret); - return ret; - } - } - ALOGE("Could not find a suitable encoder/crtc for display %d", - connector->display()); - return -ENODEV; -} - -// Attach writeback connector to the CRTC linked to the display_conn -int DrmDevice::AttachWriteback(DrmConnector *display_conn) { - DrmCrtc *display_crtc = display_conn->encoder()->crtc(); - if (GetWritebackConnectorForDisplay(display_crtc->display()) != NULL) { - ALOGE("Display already has writeback attach to it"); - return -EINVAL; - } - for (auto &writeback_conn : writeback_connectors_) { - if (writeback_conn->display() >= 0) - continue; - for (DrmEncoder *writeback_enc : writeback_conn->possible_encoders()) { - for (DrmCrtc *possible_crtc : writeback_enc->possible_crtcs()) { - if (possible_crtc != display_crtc) - continue; - // Use just encoders which had not been bound already - if (writeback_enc->can_bind(display_crtc->display())) { - writeback_enc->set_crtc(display_crtc); - writeback_conn->set_encoder(writeback_enc); - writeback_conn->set_display(display_crtc->display()); - writeback_conn->UpdateModes(); - return 0; - } - } - } - } - return -EINVAL; + return 0; } -int DrmDevice::CreatePropertyBlob(void *data, size_t length, - uint32_t *blob_id) { - struct drm_mode_create_blob create_blob; - memset(&create_blob, 0, sizeof(create_blob)); +auto DrmDevice::RegisterUserPropertyBlob(void *data, size_t length) const + -> DrmModeUserPropertyBlobUnique { + struct drm_mode_create_blob create_blob {}; create_blob.length = length; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) create_blob.data = (__u64)data; - int ret = drmIoctl(fd(), DRM_IOCTL_MODE_CREATEPROPBLOB, &create_blob); - if (ret) { + int ret = drmIoctl(GetFd(), DRM_IOCTL_MODE_CREATEPROPBLOB, &create_blob); + if (ret != 0) { ALOGE("Failed to create mode property blob %d", ret); - return ret; - } - *blob_id = create_blob.blob_id; - return 0; -} - -int DrmDevice::DestroyPropertyBlob(uint32_t blob_id) { - if (!blob_id) - return 0; - - struct drm_mode_destroy_blob destroy_blob; - memset(&destroy_blob, 0, sizeof(destroy_blob)); - destroy_blob.blob_id = (__u32)blob_id; - int ret = drmIoctl(fd(), DRM_IOCTL_MODE_DESTROYPROPBLOB, &destroy_blob); - if (ret) { - ALOGE("Failed to destroy mode property blob %" PRIu32 "/%d", blob_id, ret); - return ret; - } - return 0; -} - -DrmEventListener *DrmDevice::event_listener() { - return &event_listener_; + return {}; + } + + return DrmModeUserPropertyBlobUnique( + new uint32_t(create_blob.blob_id), [this](const uint32_t *it) { + struct drm_mode_destroy_blob destroy_blob {}; + destroy_blob.blob_id = (__u32)*it; + int err = drmIoctl(GetFd(), DRM_IOCTL_MODE_DESTROYPROPBLOB, + &destroy_blob); + if (err != 0) { + ALOGE("Failed to destroy mode property blob %" PRIu32 "/%d", *it, + err); + } + // NOLINTNEXTLINE(cppcoreguidelines-owning-memory) + delete it; + }); } int DrmDevice::GetProperty(uint32_t obj_id, uint32_t obj_type, - const char *prop_name, DrmProperty *property) { - drmModeObjectPropertiesPtr props; + const char *prop_name, DrmProperty *property) const { + drmModeObjectPropertiesPtr props = nullptr; - props = drmModeObjectGetProperties(fd(), obj_id, obj_type); - if (!props) { + props = drmModeObjectGetProperties(GetFd(), obj_id, obj_type); + if (props == nullptr) { ALOGE("Failed to get properties for %d/%x", obj_id, obj_type); return -ENODEV; } bool found = false; for (int i = 0; !found && (size_t)i < props->count_props; ++i) { - drmModePropertyPtr p = drmModeGetProperty(fd(), props->props[i]); - if (!strcmp(p->name, prop_name)) { - property->Init(p, props->prop_values[i]); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) + drmModePropertyPtr p = drmModeGetProperty(GetFd(), props->props[i]); + if (strcmp(p->name, prop_name) == 0) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) + property->Init(obj_id, p, props->prop_values[i]); found = true; } drmModeFreeProperty(p); @@ -549,32 +192,51 @@ int DrmDevice::GetProperty(uint32_t obj_id, uint32_t obj_type, return found ? 0 : -ENOENT; } -int DrmDevice::GetPlaneProperty(const DrmPlane &plane, const char *prop_name, - DrmProperty *property) { - return GetProperty(plane.id(), DRM_MODE_OBJECT_PLANE, prop_name, property); +std::string DrmDevice::GetName() const { + auto *ver = drmGetVersion(GetFd()); + if (ver == nullptr) { + ALOGW("Failed to get drm version for fd=%d", GetFd()); + return "generic"; + } + + std::string name(ver->name); + drmFreeVersion(ver); + return name; +} + +auto DrmDevice::IsKMSDev(const char *path) -> bool { + auto fd = UniqueFd(open(path, O_RDWR | O_CLOEXEC)); + if (!fd) { + return false; + } + + auto res = MakeDrmModeResUnique(fd.Get()); + if (!res) { + return false; + } + + bool is_kms = res->count_crtcs > 0 && res->count_connectors > 0 && + res->count_encoders > 0; + + return is_kms; } -int DrmDevice::GetCrtcProperty(const DrmCrtc &crtc, const char *prop_name, - DrmProperty *property) { - return GetProperty(crtc.id(), DRM_MODE_OBJECT_CRTC, prop_name, property); +auto DrmDevice::GetConnectors() + -> const std::vector<std::unique_ptr<DrmConnector>> & { + return connectors_; } -int DrmDevice::GetConnectorProperty(const DrmConnector &connector, - const char *prop_name, - DrmProperty *property) { - return GetProperty(connector.id(), DRM_MODE_OBJECT_CONNECTOR, prop_name, - property); +auto DrmDevice::GetPlanes() -> const std::vector<std::unique_ptr<DrmPlane>> & { + return planes_; } -const std::string DrmDevice::GetName() const { - auto ver = drmGetVersion(fd_.get()); - if (!ver) { - ALOGW("Failed to get drm version for fd=%d", fd_.get()); - return "generic"; - } +auto DrmDevice::GetCrtcs() -> const std::vector<std::unique_ptr<DrmCrtc>> & { + return crtcs_; +} - std::string name(ver->name); - drmFreeVersion(ver); - return name; +auto DrmDevice::GetEncoders() + -> const std::vector<std::unique_ptr<DrmEncoder>> & { + return encoders_; } + } // namespace android diff --git a/drm/DrmDevice.h b/drm/DrmDevice.h index be68aa6..f2530ee 100644 --- a/drm/DrmDevice.h +++ b/drm/DrmDevice.h @@ -17,93 +17,98 @@ #ifndef ANDROID_DRM_H_ #define ANDROID_DRM_H_ -#include <stdint.h> - +#include <cstdint> #include <map> #include <tuple> #include "DrmConnector.h" #include "DrmCrtc.h" #include "DrmEncoder.h" -#include "DrmEventListener.h" -#include "DrmPlane.h" +#include "DrmFbImporter.h" +#include "utils/UniqueFd.h" namespace android { +class DrmFbImporter; +class DrmPlane; + class DrmDevice { public: DrmDevice(); - ~DrmDevice(); + ~DrmDevice() = default; - std::tuple<int, int> Init(const char *path, int num_displays); + auto Init(const char *path) -> int; - int fd() const { - return fd_.get(); + auto GetFd() const { + return fd_.Get(); } - const std::vector<std::unique_ptr<DrmConnector>> &connectors() const { - return connectors_; + auto GetConnectors() -> const std::vector<std::unique_ptr<DrmConnector>> &; + auto GetPlanes() -> const std::vector<std::unique_ptr<DrmPlane>> &; + auto GetCrtcs() -> const std::vector<std::unique_ptr<DrmCrtc>> &; + auto GetEncoders() -> const std::vector<std::unique_ptr<DrmEncoder>> &; + + auto GetMinResolution() const { + return min_resolution_; } - const std::vector<std::unique_ptr<DrmPlane>> &planes() const { - return planes_; + auto GetMaxResolution() const { + return max_resolution_; } - std::pair<uint32_t, uint32_t> min_resolution() const { - return min_resolution_; + std::string GetName() const; + + auto RegisterUserPropertyBlob(void *data, size_t length) const + -> DrmModeUserPropertyBlobUnique; + + auto HasAddFb2ModifiersSupport() const { + return HasAddFb2ModifiersSupport_; } - std::pair<uint32_t, uint32_t> max_resolution() const { - return max_resolution_; + auto &GetDrmFbImporter() { + return *drm_fb_importer_; } - DrmConnector *GetConnectorForDisplay(int display) const; - DrmConnector *GetWritebackConnectorForDisplay(int display) const; - DrmConnector *AvailableWritebackConnector(int display) const; - DrmCrtc *GetCrtcForDisplay(int display) const; - DrmPlane *GetPlane(uint32_t id) const; - DrmEventListener *event_listener(); - - int GetPlaneProperty(const DrmPlane &plane, const char *prop_name, - DrmProperty *property); - int GetCrtcProperty(const DrmCrtc &crtc, const char *prop_name, - DrmProperty *property); - int GetConnectorProperty(const DrmConnector &connector, const char *prop_name, - DrmProperty *property); - - const std::string GetName() const; - - const std::vector<std::unique_ptr<DrmCrtc>> &crtcs() const; - uint32_t next_mode_id(); - - int CreatePropertyBlob(void *data, size_t length, uint32_t *blob_id); - int DestroyPropertyBlob(uint32_t blob_id); - bool HandlesDisplay(int display) const; - void RegisterHotplugHandler(DrmEventHandler *handler) { - event_listener_.RegisterHotplugHandler(handler); + static auto IsKMSDev(const char *path) -> bool; + + auto FindCrtcById(uint32_t id) const -> DrmCrtc * { + for (const auto &crtc : crtcs_) { + if (crtc->GetId() == id) { + return crtc.get(); + } + }; + + return nullptr; } - private: - int TryEncoderForDisplay(int display, DrmEncoder *enc); - int GetProperty(uint32_t obj_id, uint32_t obj_type, const char *prop_name, - DrmProperty *property); + auto FindEncoderById(uint32_t id) const -> DrmEncoder * { + for (const auto &enc : encoders_) { + if (enc->GetId() == id) { + return enc.get(); + } + }; - int CreateDisplayPipe(DrmConnector *connector); - int AttachWriteback(DrmConnector *display_conn); + return nullptr; + } + int GetProperty(uint32_t obj_id, uint32_t obj_type, const char *prop_name, + DrmProperty *property) const; + + private: UniqueFd fd_; - uint32_t mode_id_ = 0; std::vector<std::unique_ptr<DrmConnector>> connectors_; std::vector<std::unique_ptr<DrmConnector>> writeback_connectors_; std::vector<std::unique_ptr<DrmEncoder>> encoders_; std::vector<std::unique_ptr<DrmCrtc>> crtcs_; std::vector<std::unique_ptr<DrmPlane>> planes_; - DrmEventListener event_listener_; std::pair<uint32_t, uint32_t> min_resolution_; std::pair<uint32_t, uint32_t> max_resolution_; - std::map<int, int> displays_; + + bool HasAddFb2ModifiersSupport_{}; + + std::unique_ptr<DrmFbImporter> drm_fb_importer_; }; } // namespace android diff --git a/drm/DrmDisplayPipeline.cpp b/drm/DrmDisplayPipeline.cpp new file mode 100644 index 0000000..f993d28 --- /dev/null +++ b/drm/DrmDisplayPipeline.cpp @@ -0,0 +1,192 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "hwc-drm-display-pipeline" + +#include "DrmDisplayPipeline.h" + +#include "DrmAtomicStateManager.h" +#include "DrmConnector.h" +#include "DrmCrtc.h" +#include "DrmDevice.h" +#include "DrmEncoder.h" +#include "DrmPlane.h" +#include "utils/log.h" +#include "utils/properties.h" + +namespace android { + +template <class O> +auto PipelineBindable<O>::BindPipeline(DrmDisplayPipeline *pipeline, + bool return_object_if_bound) + -> std::shared_ptr<BindingOwner<O>> { + auto owner_object = owner_object_.lock(); + if (owner_object) { + if (bound_pipeline_ == pipeline && return_object_if_bound) { + return owner_object; + } + + return {}; + } + owner_object = std::make_shared<BindingOwner<O>>(static_cast<O *>(this)); + + owner_object_ = owner_object; + bound_pipeline_ = pipeline; + return owner_object; +} + +static auto TryCreatePipeline(DrmDevice &dev, DrmConnector &connector, + DrmEncoder &enc, DrmCrtc &crtc) + -> std::unique_ptr<DrmDisplayPipeline> { + /* Check if resources are available */ + + auto pipe = std::make_unique<DrmDisplayPipeline>(); + pipe->device = &dev; + + pipe->connector = connector.BindPipeline(pipe.get()); + pipe->encoder = enc.BindPipeline(pipe.get()); + pipe->crtc = crtc.BindPipeline(pipe.get()); + + if (!pipe->connector || !pipe->encoder || !pipe->crtc) { + return {}; + } + + std::vector<DrmPlane *> primary_planes; + std::vector<DrmPlane *> overlay_planes; + + /* Attach necessary resources */ + auto display_planes = std::vector<DrmPlane *>(); + for (const auto &plane : dev.GetPlanes()) { + if (plane->IsCrtcSupported(crtc)) { + if (plane->GetType() == DRM_PLANE_TYPE_PRIMARY) { + primary_planes.emplace_back(plane.get()); + } else if (plane->GetType() == DRM_PLANE_TYPE_OVERLAY) { + overlay_planes.emplace_back(plane.get()); + } else { + ALOGI("Ignoring cursor plane %d", plane->GetId()); + } + } + } + + if (primary_planes.empty()) { + ALOGE("Primary plane for CRTC %d not found", crtc.GetId()); + return {}; + } + + if (primary_planes.size() > 1) { + ALOGE("Found more than 1 primary plane for CRTC %d", crtc.GetId()); + return {}; + } + + pipe->primary_plane = primary_planes[0]->BindPipeline(pipe.get()); + if (!pipe->primary_plane) { + ALOGE("Primary plane %d is already owned. Internal error.", + primary_planes[0]->GetId()); + return {}; + } + + pipe->atomic_state_manager = std::make_unique<DrmAtomicStateManager>( + pipe.get()); + + return pipe; +} + +static auto TryCreatePipelineUsingEncoder(DrmDevice &dev, DrmConnector &conn, + DrmEncoder &enc) + -> std::unique_ptr<DrmDisplayPipeline> { + /* First try to use the currently-bound crtc */ + auto *crtc = dev.FindCrtcById(enc.GetCurrentCrtcId()); + if (crtc != nullptr) { + auto pipeline = TryCreatePipeline(dev, conn, enc, *crtc); + if (pipeline) { + return pipeline; + } + } + + /* Try to find a possible crtc which will work */ + for (const auto &crtc : dev.GetCrtcs()) { + if (enc.SupportsCrtc(*crtc)) { + auto pipeline = TryCreatePipeline(dev, conn, enc, *crtc); + if (pipeline) { + return pipeline; + } + } + } + + /* We can't use this encoder, but nothing went wrong, try another one */ + return {}; +} + +auto DrmDisplayPipeline::CreatePipeline(DrmConnector &connector) + -> std::unique_ptr<DrmDisplayPipeline> { + auto &dev = connector.GetDev(); + /* Try to use current setup first */ + auto *encoder = dev.FindEncoderById(connector.GetCurrentEncoderId()); + + if (encoder != nullptr) { + auto pipeline = TryCreatePipelineUsingEncoder(dev, connector, *encoder); + if (pipeline) { + return pipeline; + } + } + + for (const auto &enc : dev.GetEncoders()) { + if (connector.SupportsEncoder(*enc)) { + auto pipeline = TryCreatePipelineUsingEncoder(dev, connector, *enc); + if (pipeline) { + return pipeline; + } + } + } + + ALOGE("Could not find a suitable encoder/crtc for connector %s", + connector.GetName().c_str()); + + return {}; +} + +static bool ReadUseOverlayProperty() { + char use_overlay_planes_prop[PROPERTY_VALUE_MAX]; + property_get("vendor.hwc.drm.use_overlay_planes", use_overlay_planes_prop, + "1"); + constexpr int kStrtolBase = 10; + return strtol(use_overlay_planes_prop, nullptr, kStrtolBase) != 0; +} + +auto DrmDisplayPipeline::GetUsablePlanes() + -> std::vector<std::shared_ptr<BindingOwner<DrmPlane>>> { + std::vector<std::shared_ptr<BindingOwner<DrmPlane>>> planes; + planes.emplace_back(primary_plane); + + static bool use_overlay_planes = ReadUseOverlayProperty(); + + if (use_overlay_planes) { + for (const auto &plane : device->GetPlanes()) { + if (plane->IsCrtcSupported(*crtc->Get())) { + if (plane->GetType() == DRM_PLANE_TYPE_OVERLAY) { + auto op = plane->BindPipeline(this, true); + if (op) { + planes.emplace_back(op); + } + } + } + } + } + + return planes; +} + +} // namespace android diff --git a/drm/DrmDisplayPipeline.h b/drm/DrmDisplayPipeline.h new file mode 100644 index 0000000..7ec619e --- /dev/null +++ b/drm/DrmDisplayPipeline.h @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_DRMDISPLAYPIPELINE_H_ +#define ANDROID_DRMDISPLAYPIPELINE_H_ + +#include <memory> +#include <vector> + +namespace android { + +class DrmConnector; +class DrmDevice; +class DrmPlane; +class DrmCrtc; +class DrmEncoder; +class DrmAtomicStateManager; + +struct DrmDisplayPipeline; + +template <class O> +class BindingOwner; + +template <class O> +class PipelineBindable { + friend class BindingOwner<O>; + + public: + auto *GetPipeline() { + return bound_pipeline_; + } + + auto BindPipeline(DrmDisplayPipeline *pipeline, + bool return_object_if_bound = false) + -> std::shared_ptr<BindingOwner<O>>; + + private: + DrmDisplayPipeline *bound_pipeline_; + std::weak_ptr<BindingOwner<O>> owner_object_; +}; + +template <class B> +class BindingOwner { + public: + explicit BindingOwner(B *pb) : bindable_(pb){}; + ~BindingOwner() { + bindable_->bound_pipeline_ = nullptr; + } + + B *Get() { + return bindable_; + } + + private: + B *const bindable_; +}; + +struct DrmDisplayPipeline { + static auto CreatePipeline(DrmConnector &connector) + -> std::unique_ptr<DrmDisplayPipeline>; + + auto GetUsablePlanes() + -> std::vector<std::shared_ptr<BindingOwner<DrmPlane>>>; + + DrmDevice *device; + + std::shared_ptr<BindingOwner<DrmConnector>> connector; + std::shared_ptr<BindingOwner<DrmEncoder>> encoder; + std::shared_ptr<BindingOwner<DrmCrtc>> crtc; + std::shared_ptr<BindingOwner<DrmPlane>> primary_plane; + + std::unique_ptr<DrmAtomicStateManager> atomic_state_manager; +}; + +} // namespace android + +#endif diff --git a/drm/DrmEncoder.cpp b/drm/DrmEncoder.cpp index bcf0926..eed5b5f 100644 --- a/drm/DrmEncoder.cpp +++ b/drm/DrmEncoder.cpp @@ -14,49 +14,28 @@ * limitations under the License. */ +#define LOG_TAG "hwc-drm-encoder" + #include "DrmEncoder.h" -#include <stdint.h> #include <xf86drmMode.h> +#include <cstdint> + #include "DrmDevice.h" +#include "utils/log.h" namespace android { -DrmEncoder::DrmEncoder(drmModeEncoderPtr e, DrmCrtc *current_crtc, - const std::vector<DrmCrtc *> &possible_crtcs) - : id_(e->encoder_id), - crtc_(current_crtc), - display_(-1), - possible_crtcs_(possible_crtcs) { -} - -uint32_t DrmEncoder::id() const { - return id_; -} - -DrmCrtc *DrmEncoder::crtc() const { - return crtc_; -} - -bool DrmEncoder::CanClone(DrmEncoder *possible_clone) { - return possible_clones_.find(possible_clone) != possible_clones_.end(); -} - -void DrmEncoder::AddPossibleClone(DrmEncoder *possible_clone) { - possible_clones_.insert(possible_clone); -} +auto DrmEncoder::CreateInstance(DrmDevice &dev, uint32_t encoder_id, + uint32_t index) -> std::unique_ptr<DrmEncoder> { + auto e = MakeDrmModeEncoderUnique(dev.GetFd(), encoder_id); + if (!e) { + ALOGE("Failed to get encoder %d", encoder_id); + return {}; + } -void DrmEncoder::set_crtc(DrmCrtc *crtc) { - crtc_ = crtc; - display_ = crtc->display(); + return std::unique_ptr<DrmEncoder>(new DrmEncoder(std::move(e), index)); } -int DrmEncoder::display() const { - return display_; -} - -bool DrmEncoder::can_bind(int display) const { - return display_ == -1 || display_ == display; -} } // namespace android diff --git a/drm/DrmEncoder.h b/drm/DrmEncoder.h index f4464d0..39a695c 100644 --- a/drm/DrmEncoder.h +++ b/drm/DrmEncoder.h @@ -17,43 +17,52 @@ #ifndef ANDROID_DRM_ENCODER_H_ #define ANDROID_DRM_ENCODER_H_ -#include <stdint.h> #include <xf86drmMode.h> +#include <cstdint> #include <set> #include <vector> #include "DrmCrtc.h" +#include "DrmDisplayPipeline.h" namespace android { -class DrmEncoder { +class DrmEncoder : public PipelineBindable<DrmEncoder> { public: - DrmEncoder(drmModeEncoderPtr e, DrmCrtc *current_crtc, - const std::vector<DrmCrtc *> &possible_crtcs); + static auto CreateInstance(DrmDevice &dev, uint32_t encoder_id, + uint32_t index) -> std::unique_ptr<DrmEncoder>; + DrmEncoder(const DrmEncoder &) = delete; DrmEncoder &operator=(const DrmEncoder &) = delete; - uint32_t id() const; + auto GetId() const { + return enc_->encoder_id; + }; + + auto GetIndexInResArray() const { + return index_in_res_array_; + } - DrmCrtc *crtc() const; - void set_crtc(DrmCrtc *crtc); - bool can_bind(int display) const; - int display() const; + auto CanClone(DrmEncoder &encoder) { + return (enc_->possible_clones & (1 << encoder.GetIndexInResArray())) != 0; + } - const std::vector<DrmCrtc *> &possible_crtcs() const { - return possible_crtcs_; + auto SupportsCrtc(DrmCrtc &crtc) { + return (enc_->possible_crtcs & (1 << crtc.GetIndexInResArray())) != 0; + } + + auto GetCurrentCrtcId() { + return enc_->crtc_id; } - bool CanClone(DrmEncoder *encoder); - void AddPossibleClone(DrmEncoder *possible_clone); private: - uint32_t id_; - DrmCrtc *crtc_; - int display_; + DrmEncoder(DrmModeEncoderUnique enc, uint32_t index) + : enc_(std::move(enc)), index_in_res_array_(index){}; + + DrmModeEncoderUnique enc_; - std::vector<DrmCrtc *> possible_crtcs_; - std::set<DrmEncoder *> possible_clones_; + const uint32_t index_in_res_array_; }; } // namespace android diff --git a/drm/DrmEventListener.cpp b/drm/DrmEventListener.cpp deleted file mode 100644 index 3d95e28..0000000 --- a/drm/DrmEventListener.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (C) 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "hwc-drm-event-listener" - -#include "DrmEventListener.h" - -#include <assert.h> -#include <errno.h> -#include <hardware/hardware.h> -#include <hardware/hwcomposer.h> -#include <linux/netlink.h> -#include <log/log.h> -#include <sys/socket.h> -#include <xf86drm.h> - -#include "DrmDevice.h" - -namespace android { - -DrmEventListener::DrmEventListener(DrmDevice *drm) - : Worker("drm-event-listener", HAL_PRIORITY_URGENT_DISPLAY), drm_(drm) { -} - -int DrmEventListener::Init() { - uevent_fd_.Set(socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT)); - if (uevent_fd_.get() < 0) { - ALOGE("Failed to open uevent socket: %s", strerror(errno)); - return uevent_fd_.get(); - } - - struct sockaddr_nl addr; - memset(&addr, 0, sizeof(addr)); - addr.nl_family = AF_NETLINK; - addr.nl_pid = 0; - addr.nl_groups = 0xFFFFFFFF; - - int ret = bind(uevent_fd_.get(), (struct sockaddr *)&addr, sizeof(addr)); - if (ret) { - ALOGE("Failed to bind uevent socket: %s", strerror(errno)); - return -errno; - } - - FD_ZERO(&fds_); - FD_SET(drm_->fd(), &fds_); - FD_SET(uevent_fd_.get(), &fds_); - max_fd_ = std::max(drm_->fd(), uevent_fd_.get()); - - return InitWorker(); -} - -void DrmEventListener::RegisterHotplugHandler(DrmEventHandler *handler) { - assert(!hotplug_handler_); - hotplug_handler_.reset(handler); -} - -void DrmEventListener::FlipHandler(int /* fd */, unsigned int /* sequence */, - unsigned int tv_sec, unsigned int tv_usec, - void *user_data) { - DrmEventHandler *handler = (DrmEventHandler *)user_data; - if (!handler) - return; - - handler->HandleEvent((uint64_t)tv_sec * 1000 * 1000 + tv_usec); - delete handler; -} - -void DrmEventListener::UEventHandler() { - char buffer[1024]; - int ret; - - struct timespec ts; - uint64_t timestamp = 0; - ret = clock_gettime(CLOCK_MONOTONIC, &ts); - if (!ret) - timestamp = ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec; - else - ALOGE("Failed to get monotonic clock on hotplug %d", ret); - - while (true) { - ret = read(uevent_fd_.get(), &buffer, sizeof(buffer)); - if (ret == 0) { - return; - } else if (ret < 0) { - ALOGE("Got error reading uevent %d", ret); - return; - } - - if (!hotplug_handler_) - continue; - - bool drm_event = false, hotplug_event = false; - for (int i = 0; i < ret;) { - char *event = buffer + i; - if (strcmp(event, "DEVTYPE=drm_minor")) - drm_event = true; - else if (strcmp(event, "HOTPLUG=1")) - hotplug_event = true; - - i += strlen(event) + 1; - } - - if (drm_event && hotplug_event) - hotplug_handler_->HandleEvent(timestamp); - } -} - -void DrmEventListener::Routine() { - int ret; - do { - ret = select(max_fd_ + 1, &fds_, NULL, NULL, NULL); - } while (ret == -1 && errno == EINTR); - - if (FD_ISSET(drm_->fd(), &fds_)) { - drmEventContext event_context = - {.version = 2, - .vblank_handler = NULL, - .page_flip_handler = DrmEventListener::FlipHandler}; - drmHandleEvent(drm_->fd(), &event_context); - } - - if (FD_ISSET(uevent_fd_.get(), &fds_)) - UEventHandler(); -} -} // namespace android diff --git a/drm/DrmEventListener.h b/drm/DrmEventListener.h deleted file mode 100644 index 9f9a4ba..0000000 --- a/drm/DrmEventListener.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ANDROID_DRM_EVENT_LISTENER_H_ -#define ANDROID_DRM_EVENT_LISTENER_H_ - -#include "autofd.h" -#include "utils/Worker.h" - -namespace android { - -class DrmDevice; - -class DrmEventHandler { - public: - DrmEventHandler() { - } - virtual ~DrmEventHandler() { - } - - virtual void HandleEvent(uint64_t timestamp_us) = 0; -}; - -class DrmEventListener : public Worker { - public: - DrmEventListener(DrmDevice *drm); - virtual ~DrmEventListener() { - } - - int Init(); - - void RegisterHotplugHandler(DrmEventHandler *handler); - - static void FlipHandler(int fd, unsigned int sequence, unsigned int tv_sec, - unsigned int tv_usec, void *user_data); - - protected: - virtual void Routine(); - - private: - void UEventHandler(); - - fd_set fds_; - UniqueFd uevent_fd_; - int max_fd_ = -1; - - DrmDevice *drm_; - std::unique_ptr<DrmEventHandler> hotplug_handler_; -}; -} // namespace android - -#endif diff --git a/drm/DrmFbImporter.cpp b/drm/DrmFbImporter.cpp new file mode 100644 index 0000000..eeab076 --- /dev/null +++ b/drm/DrmFbImporter.cpp @@ -0,0 +1,155 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define LOG_TAG "hwc-platform-drm-generic" + +#include "DrmFbImporter.h" + +#include <hardware/gralloc.h> +#include <xf86drm.h> +#include <xf86drmMode.h> + +#include <cinttypes> +#include <system_error> + +#include "utils/log.h" +#include "utils/properties.h" + +namespace android { + +auto DrmFbIdHandle::CreateInstance(hwc_drm_bo_t *bo, GemHandle first_gem_handle, + DrmDevice &drm) + -> std::shared_ptr<DrmFbIdHandle> { + // NOLINTNEXTLINE(cppcoreguidelines-owning-memory): priv. constructor usage + std::shared_ptr<DrmFbIdHandle> local(new DrmFbIdHandle(drm)); + + local->gem_handles_[0] = first_gem_handle; + int32_t err = 0; + + /* Framebuffer object creation require gem handle for every used plane */ + for (size_t i = 1; i < local->gem_handles_.size(); i++) { + if (bo->prime_fds[i] > 0) { + if (bo->prime_fds[i] != bo->prime_fds[0]) { + err = drmPrimeFDToHandle(drm.GetFd(), bo->prime_fds[i], + &local->gem_handles_.at(i)); + if (err != 0) { + ALOGE("failed to import prime fd %d errno=%d", bo->prime_fds[i], + errno); + } + } else { + local->gem_handles_.at(i) = local->gem_handles_[0]; + } + } + } + + bool has_modifiers = bo->modifiers[0] != DRM_FORMAT_MOD_NONE && + bo->modifiers[0] != DRM_FORMAT_MOD_INVALID; + + if (!drm.HasAddFb2ModifiersSupport() && has_modifiers) { + ALOGE("No ADDFB2 with modifier support. Can't import modifier %" PRIu64, + bo->modifiers[0]); + local.reset(); + return local; + } + + /* Create framebuffer object */ + if (!has_modifiers) { + err = drmModeAddFB2(drm.GetFd(), bo->width, bo->height, bo->format, + &local->gem_handles_[0], &bo->pitches[0], + &bo->offsets[0], &local->fb_id_, 0); + } else { + err = drmModeAddFB2WithModifiers(drm.GetFd(), bo->width, bo->height, + bo->format, &local->gem_handles_[0], + &bo->pitches[0], &bo->offsets[0], + &bo->modifiers[0], &local->fb_id_, + DRM_MODE_FB_MODIFIERS); + } + if (err != 0) { + ALOGE("could not create drm fb %d", err); + local.reset(); + } + + return local; +} + +DrmFbIdHandle::~DrmFbIdHandle() { + /* Destroy framebuffer object */ + if (drmModeRmFB(drm_->GetFd(), fb_id_) != 0) { + ALOGE("Failed to rm fb"); + } + + /* Close GEM handles. + * + * WARNING: TODO(nobody): + * From Linux side libweston relies on libgbm to get KMS handle and never + * closes it (handle is closed by libgbm on buffer destruction) + * Probably we should offer similar approach to users (at least on user + * request via system properties) + */ + struct drm_gem_close gem_close {}; + for (size_t i = 0; i < gem_handles_.size(); i++) { + /* Don't close invalid handle. Close handle only once in cases + * where several YUV planes located in the single buffer. */ + if (gem_handles_[i] == 0 || + (i != 0 && gem_handles_[i] == gem_handles_[0])) { + continue; + } + gem_close.handle = gem_handles_[i]; + int32_t err = drmIoctl(drm_->GetFd(), DRM_IOCTL_GEM_CLOSE, &gem_close); + if (err != 0) { + ALOGE("Failed to close gem handle %d, errno: %d", gem_handles_[i], errno); + } + } +} + +auto DrmFbImporter::GetOrCreateFbId(hwc_drm_bo_t *bo) + -> std::shared_ptr<DrmFbIdHandle> { + /* Lookup DrmFbIdHandle in cache first. First handle serves as a cache key. */ + GemHandle first_handle = 0; + int32_t err = drmPrimeFDToHandle(drm_->GetFd(), bo->prime_fds[0], + &first_handle); + + if (err != 0) { + ALOGE("Failed to import prime fd %d ret=%d", bo->prime_fds[0], err); + return {}; + } + + auto drm_fb_id_cached = drm_fb_id_handle_cache_.find(first_handle); + + if (drm_fb_id_cached != drm_fb_id_handle_cache_.end()) { + if (auto drm_fb_id_handle_shared = drm_fb_id_cached->second.lock()) { + return drm_fb_id_handle_shared; + } + drm_fb_id_handle_cache_.erase(drm_fb_id_cached); + } + + /* Cleanup cached empty weak pointers */ + const int minimal_cleanup_size = 128; + if (drm_fb_id_handle_cache_.size() > minimal_cleanup_size) { + CleanupEmptyCacheElements(); + } + + /* No DrmFbIdHandle found in cache, create framebuffer object */ + auto fb_id_handle = DrmFbIdHandle::CreateInstance(bo, first_handle, *drm_); + if (fb_id_handle) { + drm_fb_id_handle_cache_[first_handle] = fb_id_handle; + } + + return fb_id_handle; +} + +} // namespace android diff --git a/drm/DrmFbImporter.h b/drm/DrmFbImporter.h new file mode 100644 index 0000000..7f17bbe --- /dev/null +++ b/drm/DrmFbImporter.h @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DRM_DRMFBIMPORTER_H_ +#define DRM_DRMFBIMPORTER_H_ + +#include <drm/drm_fourcc.h> +#include <hardware/gralloc.h> + +#include <array> +#include <map> + +#include "drm/DrmDevice.h" +#include "drmhwcgralloc.h" + +#ifndef DRM_FORMAT_INVALID +#define DRM_FORMAT_INVALID 0 +#endif + +using GemHandle = uint32_t; + +namespace android { + +class DrmFbIdHandle { + public: + static auto CreateInstance(hwc_drm_bo_t *bo, GemHandle first_gem_handle, + DrmDevice &drm) -> std::shared_ptr<DrmFbIdHandle>; + + ~DrmFbIdHandle(); + DrmFbIdHandle(DrmFbIdHandle &&) = delete; + DrmFbIdHandle(const DrmFbIdHandle &) = delete; + auto operator=(const DrmFbIdHandle &) = delete; + auto operator=(DrmFbIdHandle &&) = delete; + + auto GetFbId [[nodiscard]] () const -> uint32_t { + return fb_id_; + } + + private: + explicit DrmFbIdHandle(DrmDevice &drm) : drm_(&drm){}; + + DrmDevice *const drm_; + + uint32_t fb_id_{}; + std::array<GemHandle, kHwcDrmBoMaxPlanes> gem_handles_{}; +}; + +class DrmFbImporter { + public: + explicit DrmFbImporter(DrmDevice &drm) : drm_(&drm){}; + ~DrmFbImporter() = default; + DrmFbImporter(const DrmFbImporter &) = delete; + DrmFbImporter(DrmFbImporter &&) = delete; + auto operator=(const DrmFbImporter &) = delete; + auto operator=(DrmFbImporter &&) = delete; + + auto GetOrCreateFbId(hwc_drm_bo_t *bo) -> std::shared_ptr<DrmFbIdHandle>; + + private: + void CleanupEmptyCacheElements() { + for (auto it = drm_fb_id_handle_cache_.begin(); + it != drm_fb_id_handle_cache_.end();) { + if (it->second.expired()) { + it = drm_fb_id_handle_cache_.erase(it); + } else { + ++it; + } + } + } + + DrmDevice *const drm_; + + std::map<GemHandle, std::weak_ptr<DrmFbIdHandle>> drm_fb_id_handle_cache_; +}; + +} // namespace android + +#endif diff --git a/drm/DrmGenericImporter.cpp b/drm/DrmGenericImporter.cpp deleted file mode 100644 index 8ab4fe5..0000000 --- a/drm/DrmGenericImporter.cpp +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "hwc-platform-drm-generic" - -#include "DrmGenericImporter.h" - -#include <cutils/properties.h> -#include <gralloc_handle.h> -#include <hardware/gralloc.h> -#include <inttypes.h> -#include <log/log.h> -#include <xf86drm.h> -#include <xf86drmMode.h> - -namespace android { - -DrmGenericImporter::DrmGenericImporter(DrmDevice *drm) : drm_(drm) { - uint64_t cap_value = 0; - if (drmGetCap(drm_->fd(), DRM_CAP_ADDFB2_MODIFIERS, &cap_value)) { - ALOGE("drmGetCap failed. Fallback to no modifier support."); - cap_value = 0; - } - has_modifier_support_ = cap_value; -} - -DrmGenericImporter::~DrmGenericImporter() { -} - -int DrmGenericImporter::ImportBuffer(hwc_drm_bo_t *bo) { - int ret = drmPrimeFDToHandle(drm_->fd(), bo->prime_fds[0], - &bo->gem_handles[0]); - if (ret) { - ALOGE("failed to import prime fd %d ret=%d", bo->prime_fds[0], ret); - return ret; - } - - for (int i = 1; i < HWC_DRM_BO_MAX_PLANES; i++) { - int fd = bo->prime_fds[i]; - if (fd != 0) { - if (fd != bo->prime_fds[0]) { - ALOGE("Multiplanar FBs are not supported by this version of composer"); - return -ENOTSUP; - } - bo->gem_handles[i] = bo->gem_handles[0]; - } - } - - if (!has_modifier_support_ && bo->modifiers[0]) { - ALOGE("No ADDFB2 with modifier support. Can't import modifier %" PRIu64, - bo->modifiers[0]); - return -EINVAL; - } - - if (!bo->with_modifiers) - ret = drmModeAddFB2(drm_->fd(), bo->width, bo->height, bo->format, - bo->gem_handles, bo->pitches, bo->offsets, &bo->fb_id, - 0); - else - ret = drmModeAddFB2WithModifiers(drm_->fd(), bo->width, bo->height, - bo->format, bo->gem_handles, bo->pitches, - bo->offsets, bo->modifiers, &bo->fb_id, - bo->modifiers[0] ? DRM_MODE_FB_MODIFIERS - : 0); - - if (ret) { - ALOGE("could not create drm fb %d", ret); - return ret; - } - - ImportHandle(bo->gem_handles[0]); - - return ret; -} - -int DrmGenericImporter::ReleaseBuffer(hwc_drm_bo_t *bo) { - if (bo->fb_id) - if (drmModeRmFB(drm_->fd(), bo->fb_id)) - ALOGE("Failed to rm fb"); - - for (int i = 0; i < HWC_DRM_BO_MAX_PLANES; i++) { - if (!bo->gem_handles[i]) - continue; - - if (ReleaseHandle(bo->gem_handles[i])) { - ALOGE("Failed to release gem handle %d", bo->gem_handles[i]); - } else { - for (int j = i + 1; j < HWC_DRM_BO_MAX_PLANES; j++) - if (bo->gem_handles[j] == bo->gem_handles[i]) - bo->gem_handles[j] = 0; - bo->gem_handles[i] = 0; - } - } - return 0; -} - -int DrmGenericImporter::ImportHandle(uint32_t gem_handle) { - gem_refcount_[gem_handle]++; - - return 0; -} - -int DrmGenericImporter::ReleaseHandle(uint32_t gem_handle) { - if (--gem_refcount_[gem_handle]) - return 0; - - gem_refcount_.erase(gem_handle); - - return CloseHandle(gem_handle); -} - -int DrmGenericImporter::CloseHandle(uint32_t gem_handle) { - struct drm_gem_close gem_close; - - memset(&gem_close, 0, sizeof(gem_close)); - - gem_close.handle = gem_handle; - int ret = drmIoctl(drm_->fd(), DRM_IOCTL_GEM_CLOSE, &gem_close); - if (ret) - ALOGE("Failed to close gem handle %d %d", gem_handle, ret); - - return ret; -} -} // namespace android diff --git a/drm/DrmGenericImporter.h b/drm/DrmGenericImporter.h deleted file mode 100644 index ca53762..0000000 --- a/drm/DrmGenericImporter.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ANDROID_PLATFORM_DRM_GENERIC_H_ -#define ANDROID_PLATFORM_DRM_GENERIC_H_ - -#include <drm/drm_fourcc.h> -#include <hardware/gralloc.h> - -#include <map> - -#include "drm/DrmDevice.h" -#include "drmhwcgralloc.h" - -#ifndef DRM_FORMAT_INVALID -#define DRM_FORMAT_INVALID 0 -#endif - -namespace android { - -class Importer { - public: - virtual ~Importer() { - } - - // Imports the buffer referred to by handle into bo. - // - // Note: This can be called from a different thread than ReleaseBuffer. The - // implementation is responsible for ensuring thread safety. - virtual int ImportBuffer(hwc_drm_bo_t *bo) = 0; - - // Releases the buffer object (ie: does the inverse of ImportBuffer) - // - // Note: This can be called from a different thread than ImportBuffer. The - // implementation is responsible for ensuring thread safety. - virtual int ReleaseBuffer(hwc_drm_bo_t *bo) = 0; -}; - -class DrmGenericImporter : public Importer { - public: - DrmGenericImporter(DrmDevice *drm); - ~DrmGenericImporter() override; - - int ImportBuffer(hwc_drm_bo_t *bo) override; - int ReleaseBuffer(hwc_drm_bo_t *bo) override; - int ImportHandle(uint32_t gem_handle); - int ReleaseHandle(uint32_t gem_handle); - - protected: - DrmDevice *drm_; - - private: - int CloseHandle(uint32_t gem_handle); - std::map<uint32_t, int> gem_refcount_; - bool has_modifier_support_; -}; - -} // namespace android - -#endif diff --git a/drm/DrmMode.cpp b/drm/DrmMode.cpp index 6de671a..010ea1b 100644 --- a/drm/DrmMode.cpp +++ b/drm/DrmMode.cpp @@ -16,13 +16,14 @@ #include "DrmMode.h" +#include <cstring> + #include "DrmDevice.h" namespace android { DrmMode::DrmMode(drmModeModeInfoPtr m) - : id_(0), - clock_(m->clock), + : clock_(m->clock), h_display_(m->hdisplay), h_sync_start_(m->hsync_start), h_sync_end_(m->hsync_end), @@ -48,79 +49,56 @@ bool DrmMode::operator==(const drmModeModeInfo &m) const { v_scan_ == m.vscan && flags_ == m.flags && type_ == m.type; } -void DrmMode::ToDrmModeModeInfo(drm_mode_modeinfo *m) const { - m->clock = clock_; - m->hdisplay = h_display_; - m->hsync_start = h_sync_start_; - m->hsync_end = h_sync_end_; - m->htotal = h_total_; - m->hskew = h_skew_; - m->vdisplay = v_display_; - m->vsync_start = v_sync_start_; - m->vsync_end = v_sync_end_; - m->vtotal = v_total_; - m->vscan = v_scan_; - m->vrefresh = v_refresh_; - m->flags = flags_; - m->type = type_; - strncpy(m->name, name_.c_str(), DRM_DISPLAY_MODE_LEN); -} - -uint32_t DrmMode::id() const { - return id_; -} - -void DrmMode::set_id(uint32_t id) { - id_ = id; -} - uint32_t DrmMode::clock() const { return clock_; } -uint32_t DrmMode::h_display() const { +uint16_t DrmMode::h_display() const { return h_display_; } -uint32_t DrmMode::h_sync_start() const { +uint16_t DrmMode::h_sync_start() const { return h_sync_start_; } -uint32_t DrmMode::h_sync_end() const { +uint16_t DrmMode::h_sync_end() const { return h_sync_end_; } -uint32_t DrmMode::h_total() const { +uint16_t DrmMode::h_total() const { return h_total_; } -uint32_t DrmMode::h_skew() const { +uint16_t DrmMode::h_skew() const { return h_skew_; } -uint32_t DrmMode::v_display() const { +uint16_t DrmMode::v_display() const { return v_display_; } -uint32_t DrmMode::v_sync_start() const { +uint16_t DrmMode::v_sync_start() const { return v_sync_start_; } -uint32_t DrmMode::v_sync_end() const { +uint16_t DrmMode::v_sync_end() const { return v_sync_end_; } -uint32_t DrmMode::v_total() const { +uint16_t DrmMode::v_total() const { return v_total_; } -uint32_t DrmMode::v_scan() const { +uint16_t DrmMode::v_scan() const { return v_scan_; } float DrmMode::v_refresh() const { + if (clock_ == 0) { + return v_refresh_; + } // Always recalculate refresh to report correct float rate - return clock_ / (float)(v_total_ * h_total_) * 1000.0f; + return static_cast<float>(clock_) / (float)(v_total_ * h_total_) * 1000.0F; } uint32_t DrmMode::flags() const { @@ -132,6 +110,31 @@ uint32_t DrmMode::type() const { } std::string DrmMode::name() const { - return name_; + return name_ + "@" + std::to_string(v_refresh()); +} + +auto DrmMode::CreateModeBlob(const DrmDevice &drm) + -> DrmModeUserPropertyBlobUnique { + struct drm_mode_modeinfo drm_mode = { + .clock = clock_, + .hdisplay = h_display_, + .hsync_start = h_sync_start_, + .hsync_end = h_sync_end_, + .htotal = h_total_, + .hskew = h_skew_, + .vdisplay = v_display_, + .vsync_start = v_sync_start_, + .vsync_end = v_sync_end_, + .vtotal = v_total_, + .vscan = v_scan_, + .vrefresh = v_refresh_, + .flags = flags_, + .type = type_, + }; + strncpy(drm_mode.name, name_.c_str(), DRM_DISPLAY_MODE_LEN); + + return drm.RegisterUserPropertyBlob(&drm_mode, + sizeof(struct drm_mode_modeinfo)); } + } // namespace android diff --git a/drm/DrmMode.h b/drm/DrmMode.h index 313a8ea..20515f9 100644 --- a/drm/DrmMode.h +++ b/drm/DrmMode.h @@ -17,37 +17,38 @@ #ifndef ANDROID_DRM_MODE_H_ #define ANDROID_DRM_MODE_H_ -#include <stdint.h> #include <xf86drmMode.h> +#include <cstdint> +#include <cstdio> #include <string> +#include "DrmUnique.h" + namespace android { +class DrmDevice; + class DrmMode { public: DrmMode() = default; - DrmMode(drmModeModeInfoPtr m); + explicit DrmMode(drmModeModeInfoPtr m); bool operator==(const drmModeModeInfo &m) const; - void ToDrmModeModeInfo(drm_mode_modeinfo *m) const; - - uint32_t id() const; - void set_id(uint32_t id); uint32_t clock() const; - uint32_t h_display() const; - uint32_t h_sync_start() const; - uint32_t h_sync_end() const; - uint32_t h_total() const; - uint32_t h_skew() const; - - uint32_t v_display() const; - uint32_t v_sync_start() const; - uint32_t v_sync_end() const; - uint32_t v_total() const; - uint32_t v_scan() const; + uint16_t h_display() const; + uint16_t h_sync_start() const; + uint16_t h_sync_end() const; + uint16_t h_total() const; + uint16_t h_skew() const; + + uint16_t v_display() const; + uint16_t v_sync_start() const; + uint16_t v_sync_end() const; + uint16_t v_total() const; + uint16_t v_scan() const; float v_refresh() const; uint32_t flags() const; @@ -55,23 +56,23 @@ class DrmMode { std::string name() const; - private: - uint32_t id_ = 0; + auto CreateModeBlob(const DrmDevice &drm) -> DrmModeUserPropertyBlobUnique; + private: uint32_t clock_ = 0; - uint32_t h_display_ = 0; - uint32_t h_sync_start_ = 0; - uint32_t h_sync_end_ = 0; - uint32_t h_total_ = 0; - uint32_t h_skew_ = 0; - - uint32_t v_display_ = 0; - uint32_t v_sync_start_ = 0; - uint32_t v_sync_end_ = 0; - uint32_t v_total_ = 0; - uint32_t v_scan_ = 0; - uint32_t v_refresh_ = 0; + uint16_t h_display_ = 0; + uint16_t h_sync_start_ = 0; + uint16_t h_sync_end_ = 0; + uint16_t h_total_ = 0; + uint16_t h_skew_ = 0; + + uint16_t v_display_ = 0; + uint16_t v_sync_start_ = 0; + uint16_t v_sync_end_ = 0; + uint16_t v_total_ = 0; + uint16_t v_scan_ = 0; + uint16_t v_refresh_ = 0; uint32_t flags_ = 0; uint32_t type_ = 0; diff --git a/drm/DrmPlane.cpp b/drm/DrmPlane.cpp index f994252..28f48f3 100644 --- a/drm/DrmPlane.cpp +++ b/drm/DrmPlane.cpp @@ -18,35 +18,49 @@ #include "DrmPlane.h" -#include <errno.h> -#include <log/log.h> -#include <stdint.h> - +#include <algorithm> +#include <cerrno> #include <cinttypes> +#include <cstdint> #include "DrmDevice.h" +#include "bufferinfo/BufferInfoGetter.h" +#include "utils/log.h" namespace android { -DrmPlane::DrmPlane(DrmDevice *drm, drmModePlanePtr p) - : drm_(drm), - id_(p->plane_id), - possible_crtc_mask_(p->possible_crtcs), - formats_(p->formats, p->formats + p->count_formats) { +auto DrmPlane::CreateInstance(DrmDevice &dev, uint32_t plane_id) + -> std::unique_ptr<DrmPlane> { + auto p = MakeDrmModePlaneUnique(dev.GetFd(), plane_id); + if (!p) { + ALOGE("Failed to get plane %d", plane_id); + return {}; + } + + auto plane = std::unique_ptr<DrmPlane>(new DrmPlane(dev, std::move(p))); + + if (plane->Init() != 0) { + ALOGE("Failed to init plane %d", plane_id); + return {}; + } + + return plane; } int DrmPlane::Init() { + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) + formats_ = {plane_->formats, plane_->formats + plane_->count_formats}; + DrmProperty p; - int ret = drm_->GetPlaneProperty(*this, "type", &p); - if (ret) { - ALOGE("Could not get plane type property"); - return ret; + if (!GetPlaneProperty("type", p)) { + return -ENOTSUP; } - uint64_t type; + int ret = 0; + uint64_t type = 0; std::tie(ret, type) = p.value(); - if (ret) { + if (ret != 0) { ALOGE("Failed to get plane type property value"); return ret; } @@ -61,99 +75,115 @@ int DrmPlane::Init() { return -EINVAL; } - ret = drm_->GetPlaneProperty(*this, "CRTC_ID", &crtc_property_); - if (ret) { - ALOGE("Could not get CRTC_ID property"); - return ret; + if (!GetPlaneProperty("CRTC_ID", crtc_property_) || + !GetPlaneProperty("FB_ID", fb_property_) || + !GetPlaneProperty("CRTC_X", crtc_x_property_) || + !GetPlaneProperty("CRTC_Y", crtc_y_property_) || + !GetPlaneProperty("CRTC_W", crtc_w_property_) || + !GetPlaneProperty("CRTC_H", crtc_h_property_) || + !GetPlaneProperty("SRC_X", src_x_property_) || + !GetPlaneProperty("SRC_Y", src_y_property_) || + !GetPlaneProperty("SRC_W", src_w_property_) || + !GetPlaneProperty("SRC_H", src_h_property_)) { + return -ENOTSUP; } - ret = drm_->GetPlaneProperty(*this, "FB_ID", &fb_property_); - if (ret) { - ALOGE("Could not get FB_ID property"); - return ret; + GetPlaneProperty("zpos", zpos_property_, Presence::kOptional); + + if (GetPlaneProperty("rotation", rotation_property_, Presence::kOptional)) { + rotation_property_.AddEnumToMap("rotate-0", DrmHwcTransform::kIdentity, + transform_enum_map_); + rotation_property_.AddEnumToMap("rotate-90", DrmHwcTransform::kRotate90, + transform_enum_map_); + rotation_property_.AddEnumToMap("rotate-180", DrmHwcTransform::kRotate180, + transform_enum_map_); + rotation_property_.AddEnumToMap("rotate-270", DrmHwcTransform::kRotate270, + transform_enum_map_); + rotation_property_.AddEnumToMap("reflect-x", DrmHwcTransform::kFlipH, + transform_enum_map_); + rotation_property_.AddEnumToMap("reflect-y", DrmHwcTransform::kFlipV, + transform_enum_map_); } - ret = drm_->GetPlaneProperty(*this, "CRTC_X", &crtc_x_property_); - if (ret) { - ALOGE("Could not get CRTC_X property"); - return ret; - } + GetPlaneProperty("alpha", alpha_property_, Presence::kOptional); - ret = drm_->GetPlaneProperty(*this, "CRTC_Y", &crtc_y_property_); - if (ret) { - ALOGE("Could not get CRTC_Y property"); - return ret; + if (GetPlaneProperty("pixel blend mode", blend_property_, + Presence::kOptional)) { + blend_property_.AddEnumToMap("Pre-multiplied", DrmHwcBlending::kPreMult, + blending_enum_map_); + blend_property_.AddEnumToMap("Coverage", DrmHwcBlending::kCoverage, + blending_enum_map_); + blend_property_.AddEnumToMap("None", DrmHwcBlending::kNone, + blending_enum_map_); } - ret = drm_->GetPlaneProperty(*this, "CRTC_W", &crtc_w_property_); - if (ret) { - ALOGE("Could not get CRTC_W property"); - return ret; + GetPlaneProperty("IN_FENCE_FD", in_fence_fd_property_, Presence::kOptional); + + if (HasNonRgbFormat()) { + if (GetPlaneProperty("COLOR_ENCODING", color_encoding_propery_, + Presence::kOptional)) { + color_encoding_propery_.AddEnumToMap("ITU-R BT.709 YCbCr", + DrmHwcColorSpace::kItuRec709, + color_encoding_enum_map_); + color_encoding_propery_.AddEnumToMap("ITU-R BT.601 YCbCr", + DrmHwcColorSpace::kItuRec601, + color_encoding_enum_map_); + color_encoding_propery_.AddEnumToMap("ITU-R BT.2020 YCbCr", + DrmHwcColorSpace::kItuRec2020, + color_encoding_enum_map_); + } + + if (GetPlaneProperty("COLOR_RANGE", color_range_property_, + Presence::kOptional)) { + color_range_property_.AddEnumToMap("YCbCr full range", + DrmHwcSampleRange::kFullRange, + color_range_enum_map_); + color_range_property_.AddEnumToMap("YCbCr limited range", + DrmHwcSampleRange::kLimitedRange, + color_range_enum_map_); + } } - ret = drm_->GetPlaneProperty(*this, "CRTC_H", &crtc_h_property_); - if (ret) { - ALOGE("Could not get CRTC_H property"); - return ret; - } + return 0; +} - ret = drm_->GetPlaneProperty(*this, "SRC_X", &src_x_property_); - if (ret) { - ALOGE("Could not get SRC_X property"); - return ret; - } +bool DrmPlane::IsCrtcSupported(const DrmCrtc &crtc) const { + return ((1 << crtc.GetIndexInResArray()) & plane_->possible_crtcs) != 0; +} - ret = drm_->GetPlaneProperty(*this, "SRC_Y", &src_y_property_); - if (ret) { - ALOGE("Could not get SRC_Y property"); - return ret; +bool DrmPlane::IsValidForLayer(DrmHwcLayer *layer) { + if (!rotation_property_) { + if (layer->transform != DrmHwcTransform::kIdentity) { + ALOGV("No rotation property on plane %d", GetId()); + return false; + } + } else { + if (transform_enum_map_.count(layer->transform) == 0) { + ALOGV("Transform is not supported on plane %d", GetId()); + return false; + } } - ret = drm_->GetPlaneProperty(*this, "SRC_W", &src_w_property_); - if (ret) { - ALOGE("Could not get SRC_W property"); - return ret; + if (alpha_property_.id() == 0 && layer->alpha != UINT16_MAX) { + ALOGV("Alpha is not supported on plane %d", GetId()); + return false; } - ret = drm_->GetPlaneProperty(*this, "SRC_H", &src_h_property_); - if (ret) { - ALOGE("Could not get SRC_H property"); - return ret; + if (blending_enum_map_.count(layer->blending) == 0 && + layer->blending != DrmHwcBlending::kNone && + layer->blending != DrmHwcBlending::kPreMult) { + ALOGV("Blending is not supported on plane %d", GetId()); + return false; } - ret = drm_->GetPlaneProperty(*this, "zpos", &zpos_property_); - if (ret) - ALOGE("Could not get zpos property for plane %u", id()); - - ret = drm_->GetPlaneProperty(*this, "rotation", &rotation_property_); - if (ret) - ALOGE("Could not get rotation property"); - - ret = drm_->GetPlaneProperty(*this, "alpha", &alpha_property_); - if (ret) - ALOGI("Could not get alpha property"); - - ret = drm_->GetPlaneProperty(*this, "pixel blend mode", &blend_property_); - if (ret) - ALOGI("Could not get pixel blend mode property"); - - ret = drm_->GetPlaneProperty(*this, "IN_FENCE_FD", &in_fence_fd_property_); - if (ret) - ALOGI("Could not get IN_FENCE_FD property"); - - return 0; -} - -uint32_t DrmPlane::id() const { - return id_; -} - -bool DrmPlane::GetCrtcSupported(const DrmCrtc &crtc) const { - return !!((1 << crtc.pipe()) & possible_crtc_mask_); -} + uint32_t format = layer->buffer_info.format; + if (!IsFormatSupported(format)) { + ALOGV("Plane %d does not supports %c%c%c%c format", GetId(), format, + format >> 8, format >> 16, format >> 24); + return false; + } -uint32_t DrmPlane::type() const { - return type_; + return true; } bool DrmPlane::IsFormatSupported(uint32_t format) const { @@ -161,63 +191,130 @@ bool DrmPlane::IsFormatSupported(uint32_t format) const { std::end(formats_); } -const DrmProperty &DrmPlane::crtc_property() const { - return crtc_property_; +bool DrmPlane::HasNonRgbFormat() const { + return std::find_if_not(std::begin(formats_), std::end(formats_), + [](uint32_t format) { + return BufferInfoGetter::IsDrmFormatRgb(format); + }) != std::end(formats_); } -const DrmProperty &DrmPlane::fb_property() const { - return fb_property_; +static uint64_t ToDrmRotation(DrmHwcTransform transform) { + uint64_t rotation = 0; + if ((transform & DrmHwcTransform::kFlipH) != 0) + rotation |= DRM_MODE_REFLECT_X; + if ((transform & DrmHwcTransform::kFlipV) != 0) + rotation |= DRM_MODE_REFLECT_Y; + if ((transform & DrmHwcTransform::kRotate90) != 0) + rotation |= DRM_MODE_ROTATE_90; + else if ((transform & DrmHwcTransform::kRotate180) != 0) + rotation |= DRM_MODE_ROTATE_180; + else if ((transform & DrmHwcTransform::kRotate270) != 0) + rotation |= DRM_MODE_ROTATE_270; + else + rotation |= DRM_MODE_ROTATE_0; + + return rotation; } -const DrmProperty &DrmPlane::crtc_x_property() const { - return crtc_x_property_; +/* Convert float to 16.16 fixed point */ +static int To1616FixPt(float in) { + constexpr int kBitShift = 16; + return int(in * (1 << kBitShift)); } -const DrmProperty &DrmPlane::crtc_y_property() const { - return crtc_y_property_; -} +auto DrmPlane::AtomicSetState(drmModeAtomicReq &pset, DrmHwcLayer &layer, + uint32_t zpos, uint32_t crtc_id) -> int { + if (!layer.fb_id_handle) { + ALOGE("Expected a valid framebuffer for pset"); + return -EINVAL; + } -const DrmProperty &DrmPlane::crtc_w_property() const { - return crtc_w_property_; -} + if (zpos_property_ && !zpos_property_.is_immutable()) { + uint64_t min_zpos = 0; -const DrmProperty &DrmPlane::crtc_h_property() const { - return crtc_h_property_; -} + // Ignore ret and use min_zpos as 0 by default + std::tie(std::ignore, min_zpos) = zpos_property_.range_min(); -const DrmProperty &DrmPlane::src_x_property() const { - return src_x_property_; -} + if (!zpos_property_.AtomicSet(pset, zpos + min_zpos)) { + return -EINVAL; + } + } -const DrmProperty &DrmPlane::src_y_property() const { - return src_y_property_; -} + if (layer.acquire_fence && + !in_fence_fd_property_.AtomicSet(pset, layer.acquire_fence.Get())) { + return -EINVAL; + } -const DrmProperty &DrmPlane::src_w_property() const { - return src_w_property_; -} + if (!crtc_property_.AtomicSet(pset, crtc_id) || + !fb_property_.AtomicSet(pset, layer.fb_id_handle->GetFbId()) || + !crtc_x_property_.AtomicSet(pset, layer.display_frame.left) || + !crtc_y_property_.AtomicSet(pset, layer.display_frame.top) || + !crtc_w_property_.AtomicSet(pset, layer.display_frame.right - + layer.display_frame.left) || + !crtc_h_property_.AtomicSet(pset, layer.display_frame.bottom - + layer.display_frame.top) || + !src_x_property_.AtomicSet(pset, To1616FixPt(layer.source_crop.left)) || + !src_y_property_.AtomicSet(pset, To1616FixPt(layer.source_crop.top)) || + !src_w_property_.AtomicSet(pset, To1616FixPt(layer.source_crop.right - + layer.source_crop.left)) || + !src_h_property_.AtomicSet(pset, To1616FixPt(layer.source_crop.bottom - + layer.source_crop.top))) { + return -EINVAL; + } -const DrmProperty &DrmPlane::src_h_property() const { - return src_h_property_; -} + if (rotation_property_ && + !rotation_property_.AtomicSet(pset, ToDrmRotation(layer.transform))) { + return -EINVAL; + } -const DrmProperty &DrmPlane::zpos_property() const { - return zpos_property_; -} + if (alpha_property_ && !alpha_property_.AtomicSet(pset, layer.alpha)) { + return -EINVAL; + } -const DrmProperty &DrmPlane::rotation_property() const { - return rotation_property_; -} + if (blending_enum_map_.count(layer.blending) != 0 && + !blend_property_.AtomicSet(pset, blending_enum_map_[layer.blending])) { + return -EINVAL; + } + + if (color_encoding_enum_map_.count(layer.color_space) != 0 && + !color_encoding_propery_ + .AtomicSet(pset, color_encoding_enum_map_[layer.color_space])) { + return -EINVAL; + } + + if (color_range_enum_map_.count(layer.sample_range) != 0 && + !color_range_property_ + .AtomicSet(pset, color_range_enum_map_[layer.sample_range])) { + return -EINVAL; + } -const DrmProperty &DrmPlane::alpha_property() const { - return alpha_property_; + return 0; } -const DrmProperty &DrmPlane::blend_property() const { - return blend_property_; +auto DrmPlane::AtomicDisablePlane(drmModeAtomicReq &pset) -> int { + if (!crtc_property_.AtomicSet(pset, 0) || !fb_property_.AtomicSet(pset, 0)) { + return -EINVAL; + } + + return 0; } -const DrmProperty &DrmPlane::in_fence_fd_property() const { - return in_fence_fd_property_; +auto DrmPlane::GetPlaneProperty(const char *prop_name, DrmProperty &property, + Presence presence) -> bool { + int err = drm_->GetProperty(GetId(), DRM_MODE_OBJECT_PLANE, prop_name, + &property); + if (err != 0) { + if (presence == Presence::kMandatory) { + ALOGE("Could not get mandatory property \"%s\" from plane %d", prop_name, + GetId()); + } else { + ALOGV("Could not get optional property \"%s\" from plane %d", prop_name, + GetId()); + } + return false; + } + + return true; } + } // namespace android diff --git a/drm/DrmPlane.h b/drm/DrmPlane.h index 16731a8..65f458f 100644 --- a/drm/DrmPlane.h +++ b/drm/DrmPlane.h @@ -17,57 +17,62 @@ #ifndef ANDROID_DRM_PLANE_H_ #define ANDROID_DRM_PLANE_H_ -#include <stdint.h> #include <xf86drmMode.h> +#include <cstdint> #include <vector> #include "DrmCrtc.h" #include "DrmProperty.h" +#include "drmhwcomposer.h" namespace android { class DrmDevice; +struct DrmHwcLayer; -class DrmPlane { +class DrmPlane : public PipelineBindable<DrmPlane> { public: - DrmPlane(DrmDevice *drm, drmModePlanePtr p); DrmPlane(const DrmPlane &) = delete; DrmPlane &operator=(const DrmPlane &) = delete; - int Init(); + static auto CreateInstance(DrmDevice &dev, uint32_t plane_id) + -> std::unique_ptr<DrmPlane>; - uint32_t id() const; + bool IsCrtcSupported(const DrmCrtc &crtc) const; + bool IsValidForLayer(DrmHwcLayer *layer); - bool GetCrtcSupported(const DrmCrtc &crtc) const; - - uint32_t type() const; + auto GetType() const { + return type_; + } bool IsFormatSupported(uint32_t format) const; + bool HasNonRgbFormat() const; + + auto AtomicSetState(drmModeAtomicReq &pset, DrmHwcLayer &layer, uint32_t zpos, + uint32_t crtc_id) -> int; + auto AtomicDisablePlane(drmModeAtomicReq &pset) -> int; + auto &GetZPosProperty() const { + return zpos_property_; + } - const DrmProperty &crtc_property() const; - const DrmProperty &fb_property() const; - const DrmProperty &crtc_x_property() const; - const DrmProperty &crtc_y_property() const; - const DrmProperty &crtc_w_property() const; - const DrmProperty &crtc_h_property() const; - const DrmProperty &src_x_property() const; - const DrmProperty &src_y_property() const; - const DrmProperty &src_w_property() const; - const DrmProperty &src_h_property() const; - const DrmProperty &zpos_property() const; - const DrmProperty &rotation_property() const; - const DrmProperty &alpha_property() const; - const DrmProperty &blend_property() const; - const DrmProperty &in_fence_fd_property() const; + auto GetId() const { + return plane_->plane_id; + } private: - DrmDevice *drm_; - uint32_t id_; + DrmPlane(DrmDevice &dev, DrmModePlaneUnique plane) + : drm_(&dev), plane_(std::move(plane)){}; + DrmDevice *const drm_; + DrmModePlaneUnique plane_; - uint32_t possible_crtc_mask_; + enum class Presence { kOptional, kMandatory }; - uint32_t type_; + auto Init() -> int; + auto GetPlaneProperty(const char *prop_name, DrmProperty &property, + Presence presence = Presence::kMandatory) -> bool; + + uint32_t type_{}; std::vector<uint32_t> formats_; @@ -86,6 +91,13 @@ class DrmPlane { DrmProperty alpha_property_; DrmProperty blend_property_; DrmProperty in_fence_fd_property_; + DrmProperty color_encoding_propery_; + DrmProperty color_range_property_; + + std::map<DrmHwcBlending, uint64_t> blending_enum_map_; + std::map<DrmHwcColorSpace, uint64_t> color_encoding_enum_map_; + std::map<DrmHwcSampleRange, uint64_t> color_range_enum_map_; + std::map<DrmHwcTransform, uint64_t> transform_enum_map_; }; } // namespace android diff --git a/drm/DrmProperty.cpp b/drm/DrmProperty.cpp index b60a76e..32f1c62 100644 --- a/drm/DrmProperty.cpp +++ b/drm/DrmProperty.cpp @@ -14,15 +14,19 @@ * limitations under the License. */ +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define LOG_TAG "hwc-drm-property" + #include "DrmProperty.h" -#include <errno.h> -#include <stdint.h> #include <xf86drmMode.h> +#include <cerrno> +#include <cstdint> #include <string> #include "DrmDevice.h" +#include "utils/log.h" namespace android { @@ -30,28 +34,26 @@ DrmProperty::DrmPropertyEnum::DrmPropertyEnum(drm_mode_property_enum *e) : value_(e->value), name_(e->name) { } -DrmProperty::DrmPropertyEnum::~DrmPropertyEnum() { -} - -DrmProperty::DrmProperty(drmModePropertyPtr p, uint64_t value) - : id_(0), type_(DRM_PROPERTY_TYPE_INVALID), flags_(0), name_("") { - Init(p, value); +DrmProperty::DrmProperty(uint32_t obj_id, drmModePropertyPtr p, + uint64_t value) { + Init(obj_id, p, value); } -void DrmProperty::Init(drmModePropertyPtr p, uint64_t value) { +void DrmProperty::Init(uint32_t obj_id, drmModePropertyPtr p, uint64_t value) { + obj_id_ = obj_id; id_ = p->prop_id; flags_ = p->flags; name_ = p->name; value_ = value; for (int i = 0; i < p->count_values; ++i) - values_.push_back(p->values[i]); + values_.emplace_back(p->values[i]); for (int i = 0; i < p->count_enums; ++i) - enums_.push_back(DrmPropertyEnum(&p->enums[i])); + enums_.emplace_back(DrmPropertyEnum(&p->enums[i])); for (int i = 0; i < p->count_blobs; ++i) - blob_ids_.push_back(p->blob_ids[i]); + blob_ids_.emplace_back(p->blob_ids[i]); if (flags_ & DRM_MODE_PROP_RANGE) type_ = DRM_PROPERTY_TYPE_INT; @@ -61,6 +63,8 @@ void DrmProperty::Init(drmModePropertyPtr p, uint64_t value) { type_ = DRM_PROPERTY_TYPE_OBJECT; else if (flags_ & DRM_MODE_PROP_BLOB) type_ = DRM_PROPERTY_TYPE_BLOB; + else if (flags_ & DRM_MODE_PROP_BITMASK) + type_ = DRM_PROPERTY_TYPE_BITMASK; } uint32_t DrmProperty::id() const { @@ -75,7 +79,7 @@ std::tuple<int, uint64_t> DrmProperty::value() const { if (type_ == DRM_PROPERTY_TYPE_BLOB) return std::make_tuple(0, value_); - if (values_.size() == 0) + if (values_.empty()) return std::make_tuple(-ENOENT, 0); switch (type_) { @@ -91,6 +95,7 @@ std::tuple<int, uint64_t> DrmProperty::value() const { case DRM_PROPERTY_TYPE_OBJECT: return std::make_tuple(0, value_); + case DRM_PROPERTY_TYPE_BITMASK: default: return std::make_tuple(-EINVAL, 0); } @@ -107,7 +112,7 @@ bool DrmProperty::is_range() const { std::tuple<int, uint64_t> DrmProperty::range_min() const { if (!is_range()) return std::make_tuple(-EINVAL, 0); - if (values_.size() < 1) + if (values_.empty()) return std::make_tuple(-ENOENT, 0); return std::make_tuple(0, values_[0]); @@ -123,13 +128,28 @@ std::tuple<int, uint64_t> DrmProperty::range_max() const { } std::tuple<uint64_t, int> DrmProperty::GetEnumValueWithName( - std::string name) const { - for (auto it : enums_) { - if (it.name_.compare(name) == 0) { + const std::string &name) const { + for (const auto &it : enums_) { + if (it.name_ == name) { return std::make_tuple(it.value_, 0); } } return std::make_tuple(UINT64_MAX, -EINVAL); } + +auto DrmProperty::AtomicSet(drmModeAtomicReq &pset, uint64_t value) const + -> bool { + if (id_ == 0) { + ALOGE("AtomicSet() is called on non-initialized property!"); + return false; + } + if (drmModeAtomicAddProperty(&pset, obj_id_, id_, value) < 0) { + ALOGE("Failed to add obj_id: %u, prop_id: %u (%s) to pset", obj_id_, id_, + name_.c_str()); + return false; + } + return true; +} + } // namespace android diff --git a/drm/DrmProperty.h b/drm/DrmProperty.h index d293da3..26a7c38 100644 --- a/drm/DrmProperty.h +++ b/drm/DrmProperty.h @@ -17,9 +17,10 @@ #ifndef ANDROID_DRM_PROPERTY_H_ #define ANDROID_DRM_PROPERTY_H_ -#include <stdint.h> #include <xf86drmMode.h> +#include <cstdint> +#include <map> #include <string> #include <vector> @@ -30,18 +31,19 @@ enum DrmPropertyType { DRM_PROPERTY_TYPE_ENUM, DRM_PROPERTY_TYPE_OBJECT, DRM_PROPERTY_TYPE_BLOB, + DRM_PROPERTY_TYPE_BITMASK, DRM_PROPERTY_TYPE_INVALID, }; class DrmProperty { public: DrmProperty() = default; - DrmProperty(drmModePropertyPtr p, uint64_t value); + DrmProperty(uint32_t obj_id, drmModePropertyPtr p, uint64_t value); DrmProperty(const DrmProperty &) = delete; DrmProperty &operator=(const DrmProperty &) = delete; - void Init(drmModePropertyPtr p, uint64_t value); - std::tuple<uint64_t, int> GetEnumValueWithName(std::string name) const; + auto Init(uint32_t obj_id, drmModePropertyPtr p, uint64_t value) -> void; + std::tuple<uint64_t, int> GetEnumValueWithName(const std::string &name) const; uint32_t id() const; std::string name() const; @@ -53,16 +55,28 @@ class DrmProperty { std::tuple<int, uint64_t> range_min() const; std::tuple<int, uint64_t> range_max() const; + [[nodiscard]] auto AtomicSet(drmModeAtomicReq &pset, uint64_t value) const + -> bool; + + template <class E> + auto AddEnumToMap(const std::string &name, E key, std::map<E, uint64_t> &map) + -> bool; + + explicit operator bool() const { + return id_ != 0; + } + private: class DrmPropertyEnum { public: - DrmPropertyEnum(drm_mode_property_enum *e); - ~DrmPropertyEnum(); + explicit DrmPropertyEnum(drm_mode_property_enum *e); + ~DrmPropertyEnum() = default; uint64_t value_; std::string name_; }; + uint32_t obj_id_ = 0; uint32_t id_ = 0; DrmPropertyType type_ = DRM_PROPERTY_TYPE_INVALID; @@ -74,6 +88,21 @@ class DrmProperty { std::vector<DrmPropertyEnum> enums_; std::vector<uint32_t> blob_ids_; }; + +template <class E> +auto DrmProperty::AddEnumToMap(const std::string &name, E key, + std::map<E, uint64_t> &map) -> bool { + uint64_t enum_value = UINT64_MAX; + int err = 0; + std::tie(enum_value, err) = GetEnumValueWithName(name); + if (err == 0) { + map[key] = enum_value; + return true; + } + + return false; +} + } // namespace android #endif // ANDROID_DRM_PROPERTY_H_ diff --git a/drm/DrmUnique.h b/drm/DrmUnique.h new file mode 100644 index 0000000..282528b --- /dev/null +++ b/drm/DrmUnique.h @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DRM_UNIQUE_H_ +#define DRM_UNIQUE_H_ + +#include <xf86drmMode.h> + +#include <functional> +#include <memory> + +template <typename T> +using DUniquePtr = std::unique_ptr<T, std::function<void(T *)>>; + +using DrmModeAtomicReqUnique = DUniquePtr<drmModeAtomicReq>; +auto inline MakeDrmModeAtomicReqUnique() { + return DrmModeAtomicReqUnique(drmModeAtomicAlloc(), [](drmModeAtomicReq *it) { + drmModeAtomicFree(it); + }); +}; + +using DrmModeConnectorUnique = DUniquePtr<drmModeConnector>; +auto inline MakeDrmModeConnectorUnique(int fd, uint32_t connector_id) { + return DrmModeConnectorUnique(drmModeGetConnector(fd, connector_id), + [](drmModeConnector *it) { + drmModeFreeConnector(it); + }); +} + +using DrmModeCrtcUnique = DUniquePtr<drmModeCrtc>; +auto inline MakeDrmModeCrtcUnique(int fd, uint32_t crtc_id) { + return DrmModeCrtcUnique(drmModeGetCrtc(fd, crtc_id), + [](drmModeCrtc *it) { drmModeFreeCrtc(it); }); +} + +using DrmModeEncoderUnique = DUniquePtr<drmModeEncoder>; +auto inline MakeDrmModeEncoderUnique(int fd, uint32_t encoder_id) { + return DrmModeEncoderUnique(drmModeGetEncoder(fd, encoder_id), + [](drmModeEncoder *it) { + drmModeFreeEncoder(it); + }); +} + +using DrmModePlaneUnique = DUniquePtr<drmModePlane>; +auto inline MakeDrmModePlaneUnique(int fd, uint32_t plane_id) { + return DrmModePlaneUnique(drmModeGetPlane(fd, plane_id), + [](drmModePlane *it) { drmModeFreePlane(it); }); +} + +using DrmModePlaneResUnique = DUniquePtr<drmModePlaneRes>; +auto inline MakeDrmModePlaneResUnique(int fd) { + return DrmModePlaneResUnique(drmModeGetPlaneResources(fd), + [](drmModePlaneRes *it) { + drmModeFreePlaneResources(it); + }); +} + +using DrmModeUserPropertyBlobUnique = DUniquePtr<uint32_t /*id*/>; + +using DrmModePropertyBlobUnique = DUniquePtr<drmModePropertyBlobRes>; +auto inline MakeDrmModePropertyBlobUnique(int fd, uint32_t blob_id) { + return DrmModePropertyBlobUnique(drmModeGetPropertyBlob(fd, blob_id), + [](drmModePropertyBlobRes *it) { + drmModeFreePropertyBlob(it); + }); +} + +using DrmModeResUnique = DUniquePtr<drmModeRes>; +auto inline MakeDrmModeResUnique(int fd) { + return DrmModeResUnique(drmModeGetResources(fd), + [](drmModeRes *it) { drmModeFreeResources(it); }); +} + +#endif diff --git a/drm/ResourceManager.cpp b/drm/ResourceManager.cpp index fc24aea..c8235e9 100644 --- a/drm/ResourceManager.cpp +++ b/drm/ResourceManager.cpp @@ -18,134 +18,167 @@ #include "ResourceManager.h" -#include <cutils/properties.h> -#include <log/log.h> +#include <fcntl.h> #include <sys/stat.h> +#include <ctime> #include <sstream> #include "bufferinfo/BufferInfoGetter.h" +#include "drm/DrmAtomicStateManager.h" +#include "drm/DrmDevice.h" +#include "drm/DrmDisplayPipeline.h" +#include "drm/DrmPlane.h" +#include "utils/log.h" +#include "utils/properties.h" namespace android { -ResourceManager::ResourceManager() : num_displays_(0), gralloc_(NULL) { +ResourceManager::ResourceManager( + PipelineToFrontendBindingInterface *p2f_bind_interface) + : frontend_interface_(p2f_bind_interface) { + if (uevent_listener_.Init() != 0) { + ALOGE("Can't initialize event listener"); + } +} + +ResourceManager::~ResourceManager() { + uevent_listener_.Exit(); } -int ResourceManager::Init() { +void ResourceManager::Init() { + if (initialized_) { + ALOGE("Already initialized"); + return; + } + char path_pattern[PROPERTY_VALUE_MAX]; // Could be a valid path or it can have at the end of it the wildcard % // which means that it will try open all devices until an error is met. int path_len = property_get("vendor.hwc.drm.device", path_pattern, "/dev/dri/card%"); - int ret = 0; if (path_pattern[path_len - 1] != '%') { - ret = AddDrmDevice(std::string(path_pattern)); + AddDrmDevice(std::string(path_pattern)); } else { path_pattern[path_len - 1] = '\0'; - for (int idx = 0; !ret; ++idx) { + for (int idx = 0;; ++idx) { std::ostringstream path; path << path_pattern << idx; - struct stat buf; - if (stat(path.str().c_str(), &buf)) { + struct stat buf {}; + if (stat(path.str().c_str(), &buf) != 0) break; - } else if (IsKMSDev(path.str().c_str())) { - ret = AddDrmDevice(path.str()); + + if (DrmDevice::IsKMSDev(path.str().c_str())) { + AddDrmDevice(path.str()); } } } - if (!num_displays_) { - ALOGE("Failed to initialize any displays"); - return ret ? -EINVAL : ret; - } - char scale_with_gpu[PROPERTY_VALUE_MAX]; property_get("vendor.hwc.drm.scale_with_gpu", scale_with_gpu, "0"); scale_with_gpu_ = bool(strncmp(scale_with_gpu, "0", 1)); - if (!BufferInfoGetter::GetInstance()) { + if (BufferInfoGetter::GetInstance() == nullptr) { ALOGE("Failed to initialize BufferInfoGetter"); - return -EINVAL; + return; } - return hw_get_module(GRALLOC_HARDWARE_MODULE_ID, - (const hw_module_t **)&gralloc_); + uevent_listener_.RegisterHotplugHandler([this] { + const std::lock_guard<std::mutex> lock(GetMainLock()); + UpdateFrontendDisplays(); + }); + + UpdateFrontendDisplays(); + + initialized_ = true; } -int ResourceManager::AddDrmDevice(std::string path) { - std::unique_ptr<DrmDevice> drm = std::make_unique<DrmDevice>(); - int displays_added, ret; - std::tie(ret, displays_added) = drm->Init(path.c_str(), num_displays_); - if (ret) - return ret; - std::shared_ptr<Importer> importer; - importer.reset(new DrmGenericImporter(drm.get())); - if (!importer) { - ALOGE("Failed to create importer instance"); - return -ENODEV; +void ResourceManager::DeInit() { + if (!initialized_) { + ALOGE("Not initialized"); + return; } - importers_.push_back(importer); + + uevent_listener_.RegisterHotplugHandler([] {}); + + DetachAllFrontendDisplays(); + drms_.clear(); + + initialized_ = false; +} + +int ResourceManager::AddDrmDevice(const std::string &path) { + auto drm = std::make_unique<DrmDevice>(); + int ret = drm->Init(path.c_str()); drms_.push_back(std::move(drm)); - num_displays_ += displays_added; return ret; } -DrmConnector *ResourceManager::AvailableWritebackConnector(int display) { - DrmDevice *drm_device = GetDrmDevice(display); - DrmConnector *writeback_conn = NULL; - if (drm_device) { - writeback_conn = drm_device->AvailableWritebackConnector(display); - if (writeback_conn) - return writeback_conn; - } - for (auto &drm : drms_) { - if (drm.get() == drm_device) - continue; - writeback_conn = drm->AvailableWritebackConnector(display); - if (writeback_conn) - return writeback_conn; - } - return writeback_conn; +auto ResourceManager::GetTimeMonotonicNs() -> int64_t { + struct timespec ts {}; + clock_gettime(CLOCK_MONOTONIC, &ts); + constexpr int64_t kNsInSec = 1000000000LL; + return int64_t(ts.tv_sec) * kNsInSec + int64_t(ts.tv_nsec); } -bool ResourceManager::IsKMSDev(const char *path) { - int fd = open(path, O_RDWR | O_CLOEXEC); - if (fd < 0) - return false; - - auto res = drmModeGetResources(fd); - if (!res) { - close(fd); - return false; +void ResourceManager::UpdateFrontendDisplays() { + auto ordered_connectors = GetOrderedConnectors(); + + for (auto *conn : ordered_connectors) { + conn->UpdateModes(); + bool connected = conn->IsConnected(); + bool attached = attached_pipelines_.count(conn) != 0; + + if (connected != attached) { + ALOGI("%s connector %s", connected ? "Attaching" : "Detaching", + conn->GetName().c_str()); + + if (connected) { + auto pipeline = DrmDisplayPipeline::CreatePipeline(*conn); + frontend_interface_->BindDisplay(pipeline.get()); + attached_pipelines_[conn] = std::move(pipeline); + } else { + auto &pipeline = attached_pipelines_[conn]; + frontend_interface_->UnbindDisplay(pipeline.get()); + attached_pipelines_.erase(conn); + } + } } + frontend_interface_->FinalizeDisplayBinding(); +} - bool is_kms = res->count_crtcs > 0 && res->count_connectors > 0 && - res->count_encoders > 0; +void ResourceManager::DetachAllFrontendDisplays() { + for (auto &p : attached_pipelines_) { + frontend_interface_->UnbindDisplay(p.second.get()); + } + attached_pipelines_.clear(); + frontend_interface_->FinalizeDisplayBinding(); +} - drmModeFreeResources(res); - close(fd); +auto ResourceManager::GetOrderedConnectors() -> std::vector<DrmConnector *> { + /* Put internal displays first then external to + * ensure Internal will take Primary slot + */ - return is_kms; -} + std::vector<DrmConnector *> ordered_connectors; -DrmDevice *ResourceManager::GetDrmDevice(int display) { for (auto &drm : drms_) { - if (drm->HandlesDisplay(display)) - return drm.get(); + for (const auto &conn : drm->GetConnectors()) { + if (conn->IsInternal()) { + ordered_connectors.emplace_back(conn.get()); + } + } } - return NULL; -} -std::shared_ptr<Importer> ResourceManager::GetImporter(int display) { - for (unsigned int i = 0; i < drms_.size(); i++) { - if (drms_[i]->HandlesDisplay(display)) - return importers_[i]; + for (auto &drm : drms_) { + for (const auto &conn : drm->GetConnectors()) { + if (conn->IsExternal()) { + ordered_connectors.emplace_back(conn.get()); + } + } } - return NULL; -} -const gralloc_module_t *ResourceManager::gralloc() { - return gralloc_; + return ordered_connectors; } } // namespace android diff --git a/drm/ResourceManager.h b/drm/ResourceManager.h index 7102cea..88ba878 100644 --- a/drm/ResourceManager.h +++ b/drm/ResourceManager.h @@ -17,43 +17,67 @@ #ifndef RESOURCEMANAGER_H #define RESOURCEMANAGER_H -#include <string.h> +#include <cstring> #include "DrmDevice.h" -#include "DrmGenericImporter.h" +#include "DrmDisplayPipeline.h" +#include "DrmFbImporter.h" +#include "UEventListener.h" namespace android { +class PipelineToFrontendBindingInterface { + public: + virtual ~PipelineToFrontendBindingInterface() = default; + virtual bool BindDisplay(DrmDisplayPipeline *); + virtual bool UnbindDisplay(DrmDisplayPipeline *); + virtual void FinalizeDisplayBinding(); +}; + class ResourceManager { public: - ResourceManager(); + explicit ResourceManager( + PipelineToFrontendBindingInterface *p2f_bind_interface); ResourceManager(const ResourceManager &) = delete; ResourceManager &operator=(const ResourceManager &) = delete; - int Init(); - DrmDevice *GetDrmDevice(int display); - std::shared_ptr<Importer> GetImporter(int display); - const gralloc_module_t *gralloc(); - DrmConnector *AvailableWritebackConnector(int display); - const std::vector<std::unique_ptr<DrmDevice>> &getDrmDevices() const { - return drms_; - } - int getDisplayCount() const { - return num_displays_; - } - bool ForcedScalingWithGpu() { + ResourceManager(const ResourceManager &&) = delete; + ResourceManager &&operator=(const ResourceManager &&) = delete; + ~ResourceManager(); + + void Init(); + + void DeInit(); + + bool ForcedScalingWithGpu() const { return scale_with_gpu_; } + auto &GetMainLock() { + return main_lock_; + } + + static auto GetTimeMonotonicNs() -> int64_t; + private: - int AddDrmDevice(std::string path); - static bool IsKMSDev(const char *path); + auto AddDrmDevice(std::string const &path) -> int; + auto GetOrderedConnectors() -> std::vector<DrmConnector *>; + void UpdateFrontendDisplays(); + void DetachAllFrontendDisplays(); - int num_displays_; std::vector<std::unique_ptr<DrmDevice>> drms_; - std::vector<std::shared_ptr<Importer>> importers_; - const gralloc_module_t *gralloc_; - bool scale_with_gpu_; + bool scale_with_gpu_{}; + + UEventListener uevent_listener_; + + std::mutex main_lock_; + + std::map<DrmConnector *, std::unique_ptr<DrmDisplayPipeline>> + attached_pipelines_; + + PipelineToFrontendBindingInterface *const frontend_interface_; + + bool initialized_{}; }; } // namespace android diff --git a/drm/UEventListener.cpp b/drm/UEventListener.cpp new file mode 100644 index 0000000..b56b8e1 --- /dev/null +++ b/drm/UEventListener.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2016 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "hwc-uevent-listener" + +#include "UEventListener.h" + +#include <cerrno> + +#include "utils/log.h" + +/* Originally defined in system/core/libsystem/include/system/graphics.h as + * #define HAL_PRIORITY_URGENT_DISPLAY (-8)*/ +constexpr int kHalPriorityUrgentDisplay = -8; + +namespace android { + +UEventListener::UEventListener() + : Worker("uevent-listener", kHalPriorityUrgentDisplay){}; + +int UEventListener::Init() { + uevent_ = UEvent::CreateInstance(); + if (!uevent_) { + return -ENODEV; + } + + return InitWorker(); +} + +void UEventListener::Routine() { + while (true) { + auto uevent_str = uevent_->ReadNext(); + + if (!hotplug_handler_ || !uevent_str) + continue; + + bool drm_event = uevent_str->find("DEVTYPE=drm_minor") != std::string::npos; + bool hotplug_event = uevent_str->find("HOTPLUG=1") != std::string::npos; + + if (drm_event && hotplug_event) { + constexpr useconds_t kDelayAfterUeventUs = 200000; + /* We need some delay to ensure DrmConnector::UpdateModes() will query + * correct modes list, otherwise at least RPI4 board may report 0 modes */ + usleep(kDelayAfterUeventUs); + hotplug_handler_(); + } + } +} +} // namespace android diff --git a/utils/autolock.h b/drm/UEventListener.h index 006406a..c8b8582 100644 --- a/utils/autolock.h +++ b/drm/UEventListener.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,29 +14,35 @@ * limitations under the License. */ -#include <pthread.h> +#ifndef ANDROID_UEVENT_LISTENER_H_ +#define ANDROID_UEVENT_LISTENER_H_ + +#include <functional> + +#include "utils/UEvent.h" +#include "utils/Worker.h" namespace android { -class AutoLock { +class UEventListener : public Worker { public: - AutoLock(pthread_mutex_t *mutex, const char *const name) - : mutex_(mutex), name_(name) { - } - ~AutoLock() { - if (locked_) - Unlock(); - } + UEventListener(); + ~UEventListener() override = default; - AutoLock(const AutoLock &rhs) = delete; - AutoLock &operator=(const AutoLock &rhs) = delete; + int Init(); - int Lock(); - int Unlock(); + void RegisterHotplugHandler(std::function<void()> hotplug_handler) { + hotplug_handler_ = std::move(hotplug_handler); + } + + protected: + void Routine() override; private: - pthread_mutex_t *const mutex_; - bool locked_ = false; - const char *const name_; + std::unique_ptr<UEvent> uevent_; + + std::function<void()> hotplug_handler_; }; } // namespace android + +#endif diff --git a/drm/VSyncWorker.cpp b/drm/VSyncWorker.cpp index b2f7e5f..ed41189 100644 --- a/drm/VSyncWorker.cpp +++ b/drm/VSyncWorker.cpp @@ -18,44 +18,26 @@ #include "VSyncWorker.h" -#include <log/log.h> -#include <stdlib.h> -#include <time.h> #include <xf86drm.h> #include <xf86drmMode.h> -namespace android { - -VSyncWorker::VSyncWorker() - : Worker("vsync", HAL_PRIORITY_URGENT_DISPLAY), - drm_(NULL), - display_(-1), - enabled_(false), - last_timestamp_(-1) { -} +#include <cstdlib> +#include <cstring> +#include <ctime> -VSyncWorker::~VSyncWorker() { -} +#include "utils/log.h" -int VSyncWorker::Init(DrmDevice *drm, int display) { - drm_ = drm; - display_ = display; +namespace android { - return InitWorker(); -} +VSyncWorker::VSyncWorker() : Worker("vsync", HAL_PRIORITY_URGENT_DISPLAY){}; -void VSyncWorker::RegisterCallback(std::shared_ptr<VsyncCallback> callback) { - Lock(); - callback_ = callback; - Unlock(); -} +auto VSyncWorker::Init(DrmDisplayPipeline *pipe, + std::function<void(uint64_t /*timestamp*/)> callback) + -> int { + pipe_ = pipe; + callback_ = std::move(callback); -void VSyncWorker::RegisterClientCallback(hwc2_callback_data_t data, - hwc2_function_pointer_t hook) { - Lock(); - vsync_callback_data_ = data; - vsync_callback_hook_ = reinterpret_cast<HWC2_PFN_VSYNC>(hook); - Unlock(); + return InitWorker(); } void VSyncWorker::VSyncControl(bool enabled) { @@ -80,7 +62,7 @@ void VSyncWorker::VSyncControl(bool enabled) { * Thus, we must sleep until timestamp 687 to maintain phase with the last * timestamp. */ -int64_t VSyncWorker::GetPhasedVSync(int64_t frame_ns, int64_t current) { +int64_t VSyncWorker::GetPhasedVSync(int64_t frame_ns, int64_t current) const { if (last_timestamp_ < 0) return current + frame_ns; @@ -88,28 +70,29 @@ int64_t VSyncWorker::GetPhasedVSync(int64_t frame_ns, int64_t current) { last_timestamp_; } -static const int64_t kOneSecondNs = 1 * 1000 * 1000 * 1000; +static const int64_t kOneSecondNs = 1LL * 1000 * 1000 * 1000; int VSyncWorker::SyntheticWaitVBlank(int64_t *timestamp) { - struct timespec vsync; + struct timespec vsync {}; int ret = clock_gettime(CLOCK_MONOTONIC, &vsync); + if (ret) + return ret; - float refresh = 60.0f; // Default to 60Hz refresh rate - DrmConnector *conn = drm_->GetConnectorForDisplay(display_); - if (conn && conn->active_mode().v_refresh() != 0.0f) - refresh = conn->active_mode().v_refresh(); - else - ALOGW("Vsync worker active with conn=%p refresh=%f\n", conn, - conn ? conn->active_mode().v_refresh() : 0.0f); + float refresh = 60.0F; // Default to 60Hz refresh rate + if (pipe_ != nullptr && + pipe_->connector->Get()->GetActiveMode().v_refresh() != 0.0F) { + refresh = pipe_->connector->Get()->GetActiveMode().v_refresh(); + } - int64_t phased_timestamp = GetPhasedVSync(kOneSecondNs / refresh, + int64_t phased_timestamp = GetPhasedVSync(kOneSecondNs / + static_cast<int>(refresh), vsync.tv_sec * kOneSecondNs + vsync.tv_nsec); vsync.tv_sec = phased_timestamp / kOneSecondNs; - vsync.tv_nsec = phased_timestamp - (vsync.tv_sec * kOneSecondNs); + vsync.tv_nsec = int(phased_timestamp - (vsync.tv_sec * kOneSecondNs)); do { - ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &vsync, NULL); - } while (ret == -1 && errno == EINTR); + ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &vsync, nullptr); + } while (ret == EINTR); if (ret) return ret; @@ -118,7 +101,7 @@ int VSyncWorker::SyntheticWaitVBlank(int64_t *timestamp) { } void VSyncWorker::Routine() { - int ret; + int ret = 0; Lock(); if (!enabled_) { @@ -129,28 +112,28 @@ void VSyncWorker::Routine() { } } - int display = display_; - std::shared_ptr<VsyncCallback> callback(callback_); + auto *pipe = pipe_; Unlock(); - DrmCrtc *crtc = drm_->GetCrtcForDisplay(display); - if (!crtc) { - ALOGE("Failed to get crtc for display"); - return; - } - uint32_t high_crtc = (crtc->pipe() << DRM_VBLANK_HIGH_CRTC_SHIFT); + ret = -EAGAIN; + int64_t timestamp = 0; + drmVBlank vblank{}; - drmVBlank vblank; - memset(&vblank, 0, sizeof(vblank)); - vblank.request.type = (drmVBlankSeqType)( - DRM_VBLANK_RELATIVE | (high_crtc & DRM_VBLANK_HIGH_CRTC_MASK)); - vblank.request.sequence = 1; + if (pipe != nullptr) { + uint32_t high_crtc = (pipe->crtc->Get()->GetIndexInResArray() + << DRM_VBLANK_HIGH_CRTC_SHIFT); - int64_t timestamp; - ret = drmWaitVBlank(drm_->fd(), &vblank); - if (ret == -EINTR) { - return; - } else if (ret) { + vblank.request.type = (drmVBlankSeqType)(DRM_VBLANK_RELATIVE | + (high_crtc & + DRM_VBLANK_HIGH_CRTC_MASK)); + vblank.request.sequence = 1; + + ret = drmWaitVBlank(pipe->device->GetFd(), &vblank); + if (ret == -EINTR) + return; + } + + if (ret) { ret = SyntheticWaitVBlank(×tamp); if (ret) return; @@ -162,13 +145,9 @@ void VSyncWorker::Routine() { if (!enabled_) return; - if (callback) - callback->Callback(display, timestamp); - - Lock(); - if (enabled_ && vsync_callback_hook_ && vsync_callback_data_) - vsync_callback_hook_(vsync_callback_data_, display, timestamp); - Unlock(); + if (callback_) { + callback_(timestamp); + } last_timestamp_ = timestamp; } diff --git a/drm/VSyncWorker.h b/drm/VSyncWorker.h index 7454b51..1e6d39f 100644 --- a/drm/VSyncWorker.h +++ b/drm/VSyncWorker.h @@ -20,8 +20,10 @@ #include <hardware/hardware.h> #include <hardware/hwcomposer.h> #include <hardware/hwcomposer2.h> -#include <stdint.h> +#include <atomic> +#include <cstdint> +#include <functional> #include <map> #include "DrmDevice.h" @@ -29,22 +31,13 @@ namespace android { -class VsyncCallback { - public: - virtual ~VsyncCallback() { - } - virtual void Callback(int display, int64_t timestamp) = 0; -}; - class VSyncWorker : public Worker { public: VSyncWorker(); - ~VSyncWorker() override; + ~VSyncWorker() override = default; - int Init(DrmDevice *drm, int display); - void RegisterCallback(std::shared_ptr<VsyncCallback> callback); - void RegisterClientCallback(hwc2_callback_data_t data, - hwc2_function_pointer_t hook); + auto Init(DrmDisplayPipeline *pipe, + std::function<void(uint64_t /*timestamp*/)> callback) -> int; void VSyncControl(bool enabled); @@ -52,22 +45,14 @@ class VSyncWorker : public Worker { void Routine() override; private: - int64_t GetPhasedVSync(int64_t frame_ns, int64_t current); + int64_t GetPhasedVSync(int64_t frame_ns, int64_t current) const; int SyntheticWaitVBlank(int64_t *timestamp); - DrmDevice *drm_; - - // shared_ptr since we need to use this outside of the thread lock (to - // actually call the hook) and we don't want the memory freed until we're - // done - std::shared_ptr<VsyncCallback> callback_ = NULL; - - int display_; - std::atomic_bool enabled_; - int64_t last_timestamp_; + std::function<void(uint64_t /*timestamp*/)> callback_; - hwc2_callback_data_t vsync_callback_data_ = NULL; - HWC2_PFN_VSYNC vsync_callback_hook_ = NULL; + DrmDisplayPipeline *pipe_ = nullptr; + std::atomic_bool enabled_ = false; + int64_t last_timestamp_ = -1; }; } // namespace android diff --git a/hwc2_device/DrmHwcTwo.cpp b/hwc2_device/DrmHwcTwo.cpp new file mode 100644 index 0000000..e689419 --- /dev/null +++ b/hwc2_device/DrmHwcTwo.cpp @@ -0,0 +1,266 @@ +/* + * Copyright (C) 2016 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "hwc-drm-two" + +#include "DrmHwcTwo.h" + +#include <cinttypes> + +#include "backend/Backend.h" +#include "utils/log.h" + +namespace android { + +DrmHwcTwo::DrmHwcTwo() : resource_manager_(this){}; + +/* Must be called after every display attach/detach cycle */ +void DrmHwcTwo::FinalizeDisplayBinding() { + if (displays_.count(kPrimaryDisplay) == 0) { + /* Primary display MUST always exist */ + ALOGI("No pipelines available. Creating null-display for headless mode"); + displays_[kPrimaryDisplay] = std::make_unique< + HwcDisplay>(kPrimaryDisplay, HWC2::DisplayType::Physical, this); + /* Initializes null-display */ + displays_[kPrimaryDisplay]->SetPipeline(nullptr); + } + + if (displays_[kPrimaryDisplay]->IsInHeadlessMode() && + !display_handles_.empty()) { + /* Reattach first secondary display to take place of the primary */ + auto *pipe = display_handles_.begin()->first; + ALOGI("Primary display was disconnected, reattaching '%s' as new primary", + pipe->connector->Get()->GetName().c_str()); + UnbindDisplay(pipe); + BindDisplay(pipe); + } + + // Finally, send hotplug events to the client + for (auto &dhe : deferred_hotplug_events_) { + SendHotplugEventToClient(dhe.first, dhe.second); + } + deferred_hotplug_events_.clear(); + + /* Wait 0.2s before removing the displays to flush pending HWC2 transactions + */ + auto &mutex = GetResMan().GetMainLock(); + mutex.unlock(); + const int kTimeForSFToDisposeDisplayUs = 200000; + usleep(kTimeForSFToDisposeDisplayUs); + mutex.lock(); + std::vector<std::unique_ptr<HwcDisplay>> for_disposal; + for (auto handle : displays_for_removal_list_) { + for_disposal.emplace_back( + std::unique_ptr<HwcDisplay>(displays_[handle].release())); + displays_.erase(handle); + } + /* Destroy HwcDisplays while unlocked to avoid vsyncworker deadlocks */ + mutex.unlock(); + for_disposal.clear(); + mutex.lock(); +} + +bool DrmHwcTwo::BindDisplay(DrmDisplayPipeline *pipeline) { + if (display_handles_.count(pipeline) != 0) { + ALOGE("%s, pipeline is already used by another display, FIXME!!!: %p", + __func__, pipeline); + return false; + } + + uint32_t disp_handle = kPrimaryDisplay; + + if (displays_.count(kPrimaryDisplay) != 0 && + !displays_[kPrimaryDisplay]->IsInHeadlessMode()) { + disp_handle = ++last_display_handle_; + } + + if (displays_.count(disp_handle) == 0) { + auto disp = std::make_unique<HwcDisplay>(disp_handle, + HWC2::DisplayType::Physical, this); + displays_[disp_handle] = std::move(disp); + } + + ALOGI("Attaching pipeline '%s' to the display #%d%s", + pipeline->connector->Get()->GetName().c_str(), (int)disp_handle, + disp_handle == kPrimaryDisplay ? " (Primary)" : ""); + + displays_[disp_handle]->SetPipeline(pipeline); + display_handles_[pipeline] = disp_handle; + + return true; +} + +bool DrmHwcTwo::UnbindDisplay(DrmDisplayPipeline *pipeline) { + if (display_handles_.count(pipeline) == 0) { + ALOGE("%s, can't find the display, pipeline: %p", __func__, pipeline); + return false; + } + auto handle = display_handles_[pipeline]; + display_handles_.erase(pipeline); + + ALOGI("Detaching the pipeline '%s' from the display #%i%s", + pipeline->connector->Get()->GetName().c_str(), (int)handle, + handle == kPrimaryDisplay ? " (Primary)" : ""); + + if (displays_.count(handle) == 0) { + ALOGE("%s, can't find the display, handle: %" PRIu64, __func__, handle); + return false; + } + displays_[handle]->SetPipeline(nullptr); + + /* We must defer display disposal and removal, since it may still have pending + * HWC_API calls scheduled and waiting until ueventlistener thread releases + * main lock, otherwise transaction may fail and SF may crash + */ + if (handle != kPrimaryDisplay) { + displays_for_removal_list_.emplace_back(handle); + } + return true; +} + +HWC2::Error DrmHwcTwo::CreateVirtualDisplay(uint32_t /*width*/, + uint32_t /*height*/, + int32_t * /*format*/, + hwc2_display_t * /*display*/) { + // TODO(nobody): Implement virtual display + return HWC2::Error::Unsupported; +} + +HWC2::Error DrmHwcTwo::DestroyVirtualDisplay(hwc2_display_t /*display*/) { + // TODO(nobody): Implement virtual display + return HWC2::Error::Unsupported; +} + +void DrmHwcTwo::Dump(uint32_t *outSize, char *outBuffer) { + if (outBuffer != nullptr) { + auto copied_bytes = mDumpString.copy(outBuffer, *outSize); + *outSize = static_cast<uint32_t>(copied_bytes); + return; + } + + std::stringstream output; + + output << "-- drm_hwcomposer --\n\n"; + + for (auto &disp : displays_) + output << disp.second->Dump(); + + mDumpString = output.str(); + *outSize = static_cast<uint32_t>(mDumpString.size()); +} + +uint32_t DrmHwcTwo::GetMaxVirtualDisplayCount() { + // TODO(nobody): Implement virtual display + return 0; +} + +HWC2::Error DrmHwcTwo::RegisterCallback(int32_t descriptor, + hwc2_callback_data_t data, + hwc2_function_pointer_t function) { + switch (static_cast<HWC2::Callback>(descriptor)) { + case HWC2::Callback::Hotplug: { + hotplug_callback_ = std::make_pair(HWC2_PFN_HOTPLUG(function), data); + if (function != nullptr) { + resource_manager_.Init(); + } else { + resource_manager_.DeInit(); + /* Headless display may still be here, remove it */ + displays_.erase(kPrimaryDisplay); + } + break; + } + case HWC2::Callback::Refresh: { + refresh_callback_ = std::make_pair(HWC2_PFN_REFRESH(function), data); + break; + } + case HWC2::Callback::Vsync: { + vsync_callback_ = std::make_pair(HWC2_PFN_VSYNC(function), data); + break; + } +#if PLATFORM_SDK_VERSION > 29 + case HWC2::Callback::Vsync_2_4: { + vsync_2_4_callback_ = std::make_pair(HWC2_PFN_VSYNC_2_4(function), data); + break; + } + case HWC2::Callback::VsyncPeriodTimingChanged: { + period_timing_changed_callback_ = std:: + make_pair(HWC2_PFN_VSYNC_PERIOD_TIMING_CHANGED(function), data); + break; + } +#endif + default: + break; + } + return HWC2::Error::None; +} + +void DrmHwcTwo::SendHotplugEventToClient(hwc2_display_t displayid, + bool connected) { + auto &mutex = GetResMan().GetMainLock(); + if (mutex.try_lock()) { + ALOGE("FIXME!!!: Main mutex must be locked in %s", __func__); + mutex.unlock(); + return; + } + + auto hc = hotplug_callback_; + if (hc.first != nullptr && hc.second != nullptr) { + /* For some reason CLIENT will call HWC2 API in hotplug callback handler, + * which will cause deadlock . Unlock main mutex to prevent this. + */ + mutex.unlock(); + hc.first(hc.second, displayid, + connected == DRM_MODE_CONNECTED ? HWC2_CONNECTION_CONNECTED + : HWC2_CONNECTION_DISCONNECTED); + mutex.lock(); + } +} + +void DrmHwcTwo::SendVsyncEventToClient( + hwc2_display_t displayid, int64_t timestamp, + [[maybe_unused]] uint32_t vsync_period) const { + /* vsync callback */ +#if PLATFORM_SDK_VERSION > 29 + if (vsync_2_4_callback_.first != nullptr && + vsync_2_4_callback_.second != nullptr) { + vsync_2_4_callback_.first(vsync_2_4_callback_.second, displayid, timestamp, + vsync_period); + } else +#endif + if (vsync_callback_.first != nullptr && + vsync_callback_.second != nullptr) { + vsync_callback_.first(vsync_callback_.second, displayid, timestamp); + } +} + +void DrmHwcTwo::SendVsyncPeriodTimingChangedEventToClient( + [[maybe_unused]] hwc2_display_t displayid, + [[maybe_unused]] int64_t timestamp) const { +#if PLATFORM_SDK_VERSION > 29 + hwc_vsync_period_change_timeline_t timeline = { + .newVsyncAppliedTimeNanos = timestamp, + .refreshRequired = false, + .refreshTimeNanos = 0, + }; + if (period_timing_changed_callback_.first != nullptr && + period_timing_changed_callback_.second != nullptr) { + period_timing_changed_callback_ + .first(period_timing_changed_callback_.second, displayid, &timeline); + } +#endif +} + +} // namespace android diff --git a/hwc2_device/DrmHwcTwo.h b/hwc2_device/DrmHwcTwo.h new file mode 100644 index 0000000..2b8a74f --- /dev/null +++ b/hwc2_device/DrmHwcTwo.h @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2016 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_DRM_HWC_TWO_H_ +#define ANDROID_DRM_HWC_TWO_H_ + +#include <hardware/hwcomposer2.h> + +#include "drm/ResourceManager.h" +#include "hwc2_device/HwcDisplay.h" + +namespace android { + +class DrmHwcTwo : public PipelineToFrontendBindingInterface { + public: + DrmHwcTwo(); + ~DrmHwcTwo() override = default; + + std::pair<HWC2_PFN_HOTPLUG, hwc2_callback_data_t> hotplug_callback_{}; + std::pair<HWC2_PFN_VSYNC, hwc2_callback_data_t> vsync_callback_{}; +#if PLATFORM_SDK_VERSION > 29 + std::pair<HWC2_PFN_VSYNC_2_4, hwc2_callback_data_t> vsync_2_4_callback_{}; + std::pair<HWC2_PFN_VSYNC_PERIOD_TIMING_CHANGED, hwc2_callback_data_t> + period_timing_changed_callback_{}; +#endif + std::pair<HWC2_PFN_REFRESH, hwc2_callback_data_t> refresh_callback_{}; + + // Device functions + HWC2::Error CreateVirtualDisplay(uint32_t width, uint32_t height, + int32_t *format, hwc2_display_t *display); + HWC2::Error DestroyVirtualDisplay(hwc2_display_t display); + void Dump(uint32_t *outSize, char *outBuffer); + uint32_t GetMaxVirtualDisplayCount(); + HWC2::Error RegisterCallback(int32_t descriptor, hwc2_callback_data_t data, + hwc2_function_pointer_t function); + + auto GetDisplay(hwc2_display_t display_handle) { + return displays_.count(display_handle) != 0 + ? displays_[display_handle].get() + : nullptr; + } + + auto &GetResMan() { + return resource_manager_; + } + + void ScheduleHotplugEvent(hwc2_display_t displayid, bool connected) { + deferred_hotplug_events_[displayid] = connected; + } + + // PipelineToFrontendBindingInterface + bool BindDisplay(DrmDisplayPipeline *pipeline) override; + bool UnbindDisplay(DrmDisplayPipeline *pipeline) override; + void FinalizeDisplayBinding() override; + + void SendVsyncEventToClient(hwc2_display_t displayid, int64_t timestamp, + uint32_t vsync_period) const; + void SendVsyncPeriodTimingChangedEventToClient(hwc2_display_t displayid, + int64_t timestamp) const; + + private: + void SendHotplugEventToClient(hwc2_display_t displayid, bool connected); + + ResourceManager resource_manager_; + std::map<hwc2_display_t, std::unique_ptr<HwcDisplay>> displays_; + std::map<DrmDisplayPipeline *, hwc2_display_t> display_handles_; + + std::string mDumpString; + + std::map<hwc2_display_t, bool> deferred_hotplug_events_; + std::vector<hwc2_display_t> displays_for_removal_list_; + + uint32_t last_display_handle_ = kPrimaryDisplay; +}; +} // namespace android + +#endif diff --git a/hwc2_device/HwcDisplay.cpp b/hwc2_device/HwcDisplay.cpp new file mode 100644 index 0000000..cedac19 --- /dev/null +++ b/hwc2_device/HwcDisplay.cpp @@ -0,0 +1,909 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "hwc-display" +#define ATRACE_TAG ATRACE_TAG_GRAPHICS + +#include "HwcDisplay.h" + +#include "DrmHwcTwo.h" +#include "backend/Backend.h" +#include "backend/BackendManager.h" +#include "bufferinfo/BufferInfoGetter.h" +#include "utils/log.h" +#include "utils/properties.h" + +namespace android { + +std::string HwcDisplay::DumpDelta(HwcDisplay::Stats delta) { + if (delta.total_pixops_ == 0) + return "No stats yet"; + double ratio = 1.0 - double(delta.gpu_pixops_) / double(delta.total_pixops_); + + std::stringstream ss; + ss << " Total frames count: " << delta.total_frames_ << "\n" + << " Failed to test commit frames: " << delta.failed_kms_validate_ << "\n" + << " Failed to commit frames: " << delta.failed_kms_present_ << "\n" + << ((delta.failed_kms_present_ > 0) + ? " !!! Internal failure, FIX it please\n" + : "") + << " Flattened frames: " << delta.frames_flattened_ << "\n" + << " Pixel operations (free units)" + << " : [TOTAL: " << delta.total_pixops_ << " / GPU: " << delta.gpu_pixops_ + << "]\n" + << " Composition efficiency: " << ratio; + + return ss.str(); +} + +std::string HwcDisplay::Dump() { + std::string flattening_state_str; + switch (flattenning_state_) { + case ClientFlattenningState::Disabled: + flattening_state_str = "Disabled"; + break; + case ClientFlattenningState::NotRequired: + flattening_state_str = "Not needed"; + break; + case ClientFlattenningState::Flattened: + flattening_state_str = "Active"; + break; + case ClientFlattenningState::ClientRefreshRequested: + flattening_state_str = "Refresh requested"; + break; + default: + flattening_state_str = std::to_string(flattenning_state_) + + " VSync remains"; + } + + std::string connector_name = IsInHeadlessMode() + ? "NULL-DISPLAY" + : GetPipe().connector->Get()->GetName(); + + std::stringstream ss; + ss << "- Display on: " << connector_name << "\n" + << " Flattening state: " << flattening_state_str << "\n" + << "Statistics since system boot:\n" + << DumpDelta(total_stats_) << "\n\n" + << "Statistics since last dumpsys request:\n" + << DumpDelta(total_stats_.minus(prev_stats_)) << "\n\n"; + + memcpy(&prev_stats_, &total_stats_, sizeof(Stats)); + return ss.str(); +} + +HwcDisplay::HwcDisplay(hwc2_display_t handle, HWC2::DisplayType type, + DrmHwcTwo *hwc2) + : hwc2_(hwc2), + handle_(handle), + type_(type), + color_transform_hint_(HAL_COLOR_TRANSFORM_IDENTITY) { + // clang-format off + color_transform_matrix_ = {1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0}; + // clang-format on +} + +HwcDisplay::~HwcDisplay() = default; + +void HwcDisplay::SetPipeline(DrmDisplayPipeline *pipeline) { + pipeline_ = pipeline; + + if (pipeline != nullptr) { + ChosePreferredConfig(); + Init(); + + hwc2_->ScheduleHotplugEvent(handle_, /*connected = */ true); + } else { + backend_.reset(); + vsync_worker_.Init(nullptr, [](int64_t) {}); + SetClientTarget(nullptr, -1, 0, {}); + if (handle_ != kPrimaryDisplay) { + hwc2_->ScheduleHotplugEvent(handle_, /*connected = */ false); + } + } +} + +HWC2::Error HwcDisplay::Init() { + int ret = vsync_worker_.Init(pipeline_, [this](int64_t timestamp) { + const std::lock_guard<std::mutex> lock(hwc2_->GetResMan().GetMainLock()); + if (vsync_event_en_) { + uint32_t period_ns{}; + GetDisplayVsyncPeriod(&period_ns); + hwc2_->SendVsyncEventToClient(handle_, timestamp, period_ns); + } + if (vsync_flattening_en_) { + ProcessFlatenningVsyncInternal(); + } + if (vsync_tracking_en_) { + last_vsync_ts_ = timestamp; + } + if (!vsync_event_en_ && !vsync_flattening_en_ && !vsync_tracking_en_) { + vsync_worker_.VSyncControl(false); + } + }); + if (ret && ret != -EALREADY) { + ALOGE("Failed to create event worker for d=%d %d\n", int(handle_), ret); + return HWC2::Error::BadDisplay; + } + + if (!IsInHeadlessMode()) { + ret = BackendManager::GetInstance().SetBackendForDisplay(this); + if (ret) { + ALOGE("Failed to set backend for d=%d %d\n", int(handle_), ret); + return HWC2::Error::BadDisplay; + } + } + + client_layer_.SetLayerBlendMode(HWC2_BLEND_MODE_PREMULTIPLIED); + + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::ChosePreferredConfig() { + HWC2::Error err{}; + if (!IsInHeadlessMode()) { + err = configs_.Update(*pipeline_->connector->Get()); + } else { + configs_.FillHeadless(); + } + if (!IsInHeadlessMode() && err != HWC2::Error::None) { + return HWC2::Error::BadDisplay; + } + + return SetActiveConfig(configs_.preferred_config_id); +} + +HWC2::Error HwcDisplay::AcceptDisplayChanges() { + for (std::pair<const hwc2_layer_t, HwcLayer> &l : layers_) + l.second.AcceptTypeChange(); + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::CreateLayer(hwc2_layer_t *layer) { + layers_.emplace(static_cast<hwc2_layer_t>(layer_idx_), HwcLayer()); + *layer = static_cast<hwc2_layer_t>(layer_idx_); + ++layer_idx_; + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::DestroyLayer(hwc2_layer_t layer) { + if (!get_layer(layer)) { + return HWC2::Error::BadLayer; + } + + layers_.erase(layer); + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::GetActiveConfig(hwc2_config_t *config) const { + if (configs_.hwc_configs.count(staged_mode_config_id_) == 0) + return HWC2::Error::BadConfig; + + *config = staged_mode_config_id_; + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::GetChangedCompositionTypes(uint32_t *num_elements, + hwc2_layer_t *layers, + int32_t *types) { + if (IsInHeadlessMode()) { + *num_elements = 0; + return HWC2::Error::None; + } + + uint32_t num_changes = 0; + for (std::pair<const hwc2_layer_t, HwcLayer> &l : layers_) { + if (l.second.IsTypeChanged()) { + if (layers && num_changes < *num_elements) + layers[num_changes] = l.first; + if (types && num_changes < *num_elements) + types[num_changes] = static_cast<int32_t>(l.second.GetValidatedType()); + ++num_changes; + } + } + if (!layers && !types) + *num_elements = num_changes; + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::GetClientTargetSupport(uint32_t width, uint32_t height, + int32_t /*format*/, + int32_t dataspace) { + if (IsInHeadlessMode()) { + return HWC2::Error::None; + } + + std::pair<uint32_t, uint32_t> min = pipeline_->device->GetMinResolution(); + std::pair<uint32_t, uint32_t> max = pipeline_->device->GetMaxResolution(); + + if (width < min.first || height < min.second) + return HWC2::Error::Unsupported; + + if (width > max.first || height > max.second) + return HWC2::Error::Unsupported; + + if (dataspace != HAL_DATASPACE_UNKNOWN) + return HWC2::Error::Unsupported; + + // TODO(nobody): Validate format can be handled by either GL or planes + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::GetColorModes(uint32_t *num_modes, int32_t *modes) { + if (!modes) + *num_modes = 1; + + if (modes) + *modes = HAL_COLOR_MODE_NATIVE; + + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::GetDisplayAttribute(hwc2_config_t config, + int32_t attribute_in, + int32_t *value) { + int conf = static_cast<int>(config); + + if (configs_.hwc_configs.count(conf) == 0) { + ALOGE("Could not find mode #%d", conf); + return HWC2::Error::BadConfig; + } + + auto &hwc_config = configs_.hwc_configs[conf]; + + static const int32_t kUmPerInch = 25400; + uint32_t mm_width = configs_.mm_width; + uint32_t mm_height = configs_.mm_height; + auto attribute = static_cast<HWC2::Attribute>(attribute_in); + switch (attribute) { + case HWC2::Attribute::Width: + *value = static_cast<int>(hwc_config.mode.h_display()); + break; + case HWC2::Attribute::Height: + *value = static_cast<int>(hwc_config.mode.v_display()); + break; + case HWC2::Attribute::VsyncPeriod: + // in nanoseconds + *value = static_cast<int>(1E9 / hwc_config.mode.v_refresh()); + break; + case HWC2::Attribute::DpiX: + // Dots per 1000 inches + *value = mm_width ? static_cast<int>(hwc_config.mode.h_display() * + kUmPerInch / mm_width) + : -1; + break; + case HWC2::Attribute::DpiY: + // Dots per 1000 inches + *value = mm_height ? static_cast<int>(hwc_config.mode.v_display() * + kUmPerInch / mm_height) + : -1; + break; +#if PLATFORM_SDK_VERSION > 29 + case HWC2::Attribute::ConfigGroup: + /* Dispite ConfigGroup is a part of HWC2.4 API, framework + * able to request it even if service @2.1 is used */ + *value = int(hwc_config.group_id); + break; +#endif + default: + *value = -1; + return HWC2::Error::BadConfig; + } + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::GetDisplayConfigs(uint32_t *num_configs, + hwc2_config_t *configs) { + uint32_t idx = 0; + for (auto &hwc_config : configs_.hwc_configs) { + if (hwc_config.second.disabled) { + continue; + } + + if (configs != nullptr) { + if (idx >= *num_configs) { + break; + } + configs[idx] = hwc_config.second.id; + } + + idx++; + } + *num_configs = idx; + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::GetDisplayName(uint32_t *size, char *name) { + std::ostringstream stream; + if (IsInHeadlessMode()) { + stream << "null-display"; + } else { + stream << "display-" << GetPipe().connector->Get()->GetId(); + } + std::string string = stream.str(); + size_t length = string.length(); + if (!name) { + *size = length; + return HWC2::Error::None; + } + + *size = std::min<uint32_t>(static_cast<uint32_t>(length - 1), *size); + strncpy(name, string.c_str(), *size); + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::GetDisplayRequests(int32_t * /*display_requests*/, + uint32_t *num_elements, + hwc2_layer_t * /*layers*/, + int32_t * /*layer_requests*/) { + // TODO(nobody): I think virtual display should request + // HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT here + *num_elements = 0; + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::GetDisplayType(int32_t *type) { + *type = static_cast<int32_t>(type_); + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::GetDozeSupport(int32_t *support) { + *support = 0; + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::GetHdrCapabilities(uint32_t *num_types, + int32_t * /*types*/, + float * /*max_luminance*/, + float * /*max_average_luminance*/, + float * /*min_luminance*/) { + *num_types = 0; + return HWC2::Error::None; +} + +/* Find API details at: + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r3:hardware/libhardware/include/hardware/hwcomposer2.h;l=1767 + */ +HWC2::Error HwcDisplay::GetReleaseFences(uint32_t *num_elements, + hwc2_layer_t *layers, + int32_t *fences) { + if (IsInHeadlessMode()) { + *num_elements = 0; + return HWC2::Error::None; + } + + uint32_t num_layers = 0; + + for (std::pair<const hwc2_layer_t, HwcLayer> &l : layers_) { + ++num_layers; + if (layers == nullptr || fences == nullptr) + continue; + + if (num_layers > *num_elements) { + ALOGW("Overflow num_elements %d/%d", num_layers, *num_elements); + return HWC2::Error::None; + } + + layers[num_layers - 1] = l.first; + fences[num_layers - 1] = l.second.GetReleaseFence().Release(); + } + *num_elements = num_layers; + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::CreateComposition(AtomicCommitArgs &a_args) { + if (IsInHeadlessMode()) { + ALOGE("%s: Display is in headless mode, should never reach here", __func__); + return HWC2::Error::None; + } + + int PrevModeVsyncPeriodNs = static_cast<int>( + 1E9 / GetPipe().connector->Get()->GetActiveMode().v_refresh()); + + auto mode_update_commited_ = false; + if (staged_mode_ && + staged_mode_change_time_ <= ResourceManager::GetTimeMonotonicNs()) { + client_layer_.SetLayerDisplayFrame( + (hwc_rect_t){.left = 0, + .top = 0, + .right = static_cast<int>(staged_mode_->h_display()), + .bottom = static_cast<int>(staged_mode_->v_display())}); + + configs_.active_config_id = staged_mode_config_id_; + + a_args.display_mode = *staged_mode_; + if (!a_args.test_only) { + mode_update_commited_ = true; + } + } + + // order the layers by z-order + bool use_client_layer = false; + uint32_t client_z_order = UINT32_MAX; + std::map<uint32_t, HwcLayer *> z_map; + for (std::pair<const hwc2_layer_t, HwcLayer> &l : layers_) { + switch (l.second.GetValidatedType()) { + case HWC2::Composition::Device: + z_map.emplace(std::make_pair(l.second.GetZOrder(), &l.second)); + break; + case HWC2::Composition::Client: + // Place it at the z_order of the lowest client layer + use_client_layer = true; + client_z_order = std::min(client_z_order, l.second.GetZOrder()); + break; + default: + continue; + } + } + if (use_client_layer) + z_map.emplace(std::make_pair(client_z_order, &client_layer_)); + + if (z_map.empty()) + return HWC2::Error::BadLayer; + + std::vector<DrmHwcLayer> composition_layers; + + // now that they're ordered by z, add them to the composition + for (std::pair<const uint32_t, HwcLayer *> &l : z_map) { + DrmHwcLayer layer; + l.second->PopulateDrmLayer(&layer); + int ret = layer.ImportBuffer(GetPipe().device); + if (ret) { + ALOGE("Failed to import layer, ret=%d", ret); + return HWC2::Error::NoResources; + } + composition_layers.emplace_back(std::move(layer)); + } + + /* Store plan to ensure shared planes won't be stolen by other display + * in between of ValidateDisplay() and PresentDisplay() calls + */ + current_plan_ = DrmKmsPlan::CreateDrmKmsPlan(GetPipe(), + std::move(composition_layers)); + if (!current_plan_) { + if (!a_args.test_only) { + ALOGE("Failed to create DrmKmsPlan"); + } + return HWC2::Error::BadConfig; + } + + a_args.composition = current_plan_; + + int ret = GetPipe().atomic_state_manager->ExecuteAtomicCommit(a_args); + + if (ret) { + if (!a_args.test_only) + ALOGE("Failed to apply the frame composition ret=%d", ret); + return HWC2::Error::BadParameter; + } + + if (mode_update_commited_) { + staged_mode_.reset(); + vsync_tracking_en_ = false; + if (last_vsync_ts_ != 0) { + hwc2_->SendVsyncPeriodTimingChangedEventToClient( + handle_, last_vsync_ts_ + PrevModeVsyncPeriodNs); + } + } + + return HWC2::Error::None; +} + +/* Find API details at: + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r3:hardware/libhardware/include/hardware/hwcomposer2.h;l=1805 + */ +HWC2::Error HwcDisplay::PresentDisplay(int32_t *present_fence) { + if (IsInHeadlessMode()) { + *present_fence = -1; + return HWC2::Error::None; + } + HWC2::Error ret{}; + + ++total_stats_.total_frames_; + + AtomicCommitArgs a_args{}; + ret = CreateComposition(a_args); + + if (ret != HWC2::Error::None) + ++total_stats_.failed_kms_present_; + + if (ret == HWC2::Error::BadLayer) { + // Can we really have no client or device layers? + *present_fence = -1; + return HWC2::Error::None; + } + if (ret != HWC2::Error::None) + return ret; + + *present_fence = a_args.out_fence.Release(); + + ++frame_no_; + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::SetActiveConfigInternal(uint32_t config, + int64_t change_time) { + if (configs_.hwc_configs.count(config) == 0) { + ALOGE("Could not find active mode for %u", config); + return HWC2::Error::BadConfig; + } + + staged_mode_ = configs_.hwc_configs[config].mode; + staged_mode_change_time_ = change_time; + staged_mode_config_id_ = config; + + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::SetActiveConfig(hwc2_config_t config) { + return SetActiveConfigInternal(config, ResourceManager::GetTimeMonotonicNs()); +} + +/* Find API details at: + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r3:hardware/libhardware/include/hardware/hwcomposer2.h;l=1861 + */ +HWC2::Error HwcDisplay::SetClientTarget(buffer_handle_t target, + int32_t acquire_fence, + int32_t dataspace, + hwc_region_t /*damage*/) { + client_layer_.SetLayerBuffer(target, acquire_fence); + client_layer_.SetLayerDataspace(dataspace); + + /* + * target can be nullptr, this does mean the Composer Service is calling + * cleanDisplayResources() on after receiving HOTPLUG event. See more at: + * https://cs.android.com/android/platform/superproject/+/master:hardware/interfaces/graphics/composer/2.1/utils/hal/include/composer-hal/2.1/ComposerClient.h;l=350;drc=944b68180b008456ed2eb4d4d329e33b19bd5166 + */ + if (target == nullptr) { + return HWC2::Error::None; + } + + /* TODO: Do not update source_crop every call. + * It makes sense to do it once after every hotplug event. */ + HwcDrmBo bo{}; + BufferInfoGetter::GetInstance()->ConvertBoInfo(target, &bo); + + hwc_frect_t source_crop = {.left = 0.0F, + .top = 0.0F, + .right = static_cast<float>(bo.width), + .bottom = static_cast<float>(bo.height)}; + client_layer_.SetLayerSourceCrop(source_crop); + + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::SetColorMode(int32_t mode) { + if (mode < HAL_COLOR_MODE_NATIVE || mode > HAL_COLOR_MODE_BT2100_HLG) + return HWC2::Error::BadParameter; + + if (mode != HAL_COLOR_MODE_NATIVE) + return HWC2::Error::Unsupported; + + color_mode_ = mode; + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::SetColorTransform(const float *matrix, int32_t hint) { + if (hint < HAL_COLOR_TRANSFORM_IDENTITY || + hint > HAL_COLOR_TRANSFORM_CORRECT_TRITANOPIA) + return HWC2::Error::BadParameter; + + if (!matrix && hint == HAL_COLOR_TRANSFORM_ARBITRARY_MATRIX) + return HWC2::Error::BadParameter; + + color_transform_hint_ = static_cast<android_color_transform_t>(hint); + if (color_transform_hint_ == HAL_COLOR_TRANSFORM_ARBITRARY_MATRIX) + std::copy(matrix, matrix + MATRIX_SIZE, color_transform_matrix_.begin()); + + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::SetOutputBuffer(buffer_handle_t /*buffer*/, + int32_t /*release_fence*/) { + // TODO(nobody): Need virtual display support + return HWC2::Error::Unsupported; +} + +HWC2::Error HwcDisplay::SetPowerMode(int32_t mode_in) { + if (IsInHeadlessMode()) { + return HWC2::Error::None; + } + + auto mode = static_cast<HWC2::PowerMode>(mode_in); + AtomicCommitArgs a_args{}; + + switch (mode) { + case HWC2::PowerMode::Off: + a_args.active = false; + break; + case HWC2::PowerMode::On: + /* + * Setting the display to active before we have a composition + * can break some drivers, so skip setting a_args.active to + * true, as the next composition frame will implicitly activate + * the display + */ + return GetPipe().atomic_state_manager->ActivateDisplayUsingDPMS() == 0 + ? HWC2::Error::None + : HWC2::Error::BadParameter; + break; + case HWC2::PowerMode::Doze: + case HWC2::PowerMode::DozeSuspend: + return HWC2::Error::Unsupported; + default: + ALOGI("Power mode %d is unsupported\n", mode); + return HWC2::Error::BadParameter; + }; + + int err = GetPipe().atomic_state_manager->ExecuteAtomicCommit(a_args); + if (err) { + ALOGE("Failed to apply the dpms composition err=%d", err); + return HWC2::Error::BadParameter; + } + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::SetVsyncEnabled(int32_t enabled) { + vsync_event_en_ = HWC2_VSYNC_ENABLE == enabled; + if (vsync_event_en_) { + vsync_worker_.VSyncControl(true); + } + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::ValidateDisplay(uint32_t *num_types, + uint32_t *num_requests) { + if (IsInHeadlessMode()) { + *num_types = *num_requests = 0; + return HWC2::Error::None; + } + return backend_->ValidateDisplay(this, num_types, num_requests); +} + +std::vector<HwcLayer *> HwcDisplay::GetOrderLayersByZPos() { + std::vector<HwcLayer *> ordered_layers; + ordered_layers.reserve(layers_.size()); + + for (auto &[handle, layer] : layers_) { + ordered_layers.emplace_back(&layer); + } + + std::sort(std::begin(ordered_layers), std::end(ordered_layers), + [](const HwcLayer *lhs, const HwcLayer *rhs) { + return lhs->GetZOrder() < rhs->GetZOrder(); + }); + + return ordered_layers; +} + +HWC2::Error HwcDisplay::GetDisplayVsyncPeriod( + uint32_t *outVsyncPeriod /* ns */) { + return GetDisplayAttribute(configs_.active_config_id, + HWC2_ATTRIBUTE_VSYNC_PERIOD, + (int32_t *)(outVsyncPeriod)); +} + +#if PLATFORM_SDK_VERSION > 29 +HWC2::Error HwcDisplay::GetDisplayConnectionType(uint32_t *outType) { + if (IsInHeadlessMode()) { + *outType = static_cast<uint32_t>(HWC2::DisplayConnectionType::Internal); + return HWC2::Error::None; + } + /* Primary display should be always internal, + * otherwise SF will be unhappy and will crash + */ + if (GetPipe().connector->Get()->IsInternal() || handle_ == kPrimaryDisplay) + *outType = static_cast<uint32_t>(HWC2::DisplayConnectionType::Internal); + else if (GetPipe().connector->Get()->IsExternal()) + *outType = static_cast<uint32_t>(HWC2::DisplayConnectionType::External); + else + return HWC2::Error::BadConfig; + + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::SetActiveConfigWithConstraints( + hwc2_config_t config, + hwc_vsync_period_change_constraints_t *vsyncPeriodChangeConstraints, + hwc_vsync_period_change_timeline_t *outTimeline) { + if (vsyncPeriodChangeConstraints == nullptr || outTimeline == nullptr) { + return HWC2::Error::BadParameter; + } + + uint32_t current_vsync_period{}; + GetDisplayVsyncPeriod(¤t_vsync_period); + + if (vsyncPeriodChangeConstraints->seamlessRequired) { + return HWC2::Error::SeamlessNotAllowed; + } + + outTimeline->refreshTimeNanos = vsyncPeriodChangeConstraints + ->desiredTimeNanos - + current_vsync_period; + auto ret = SetActiveConfigInternal(config, outTimeline->refreshTimeNanos); + if (ret != HWC2::Error::None) { + return ret; + } + + outTimeline->refreshRequired = true; + outTimeline->newVsyncAppliedTimeNanos = vsyncPeriodChangeConstraints + ->desiredTimeNanos; + + last_vsync_ts_ = 0; + vsync_tracking_en_ = true; + vsync_worker_.VSyncControl(true); + + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::SetAutoLowLatencyMode(bool /*on*/) { + return HWC2::Error::Unsupported; +} + +HWC2::Error HwcDisplay::GetSupportedContentTypes( + uint32_t *outNumSupportedContentTypes, + const uint32_t *outSupportedContentTypes) { + if (outSupportedContentTypes == nullptr) + *outNumSupportedContentTypes = 0; + + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::SetContentType(int32_t contentType) { + if (contentType != HWC2_CONTENT_TYPE_NONE) + return HWC2::Error::Unsupported; + + /* TODO: Map to the DRM Connector property: + * https://elixir.bootlin.com/linux/v5.4-rc5/source/drivers/gpu/drm/drm_connector.c#L809 + */ + + return HWC2::Error::None; +} +#endif + +#if PLATFORM_SDK_VERSION > 28 +HWC2::Error HwcDisplay::GetDisplayIdentificationData(uint8_t *outPort, + uint32_t *outDataSize, + uint8_t *outData) { + if (IsInHeadlessMode()) { + return HWC2::Error::None; + } + auto blob = GetPipe().connector->Get()->GetEdidBlob(); + + *outPort = handle_ - 1; + + if (!blob) { + if (outData == nullptr) { + *outDataSize = 0; + } + return HWC2::Error::None; + } + + if (outData) { + *outDataSize = std::min(*outDataSize, blob->length); + memcpy(outData, blob->data, *outDataSize); + } else { + *outDataSize = blob->length; + } + + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::GetDisplayCapabilities(uint32_t *outNumCapabilities, + uint32_t * /*outCapabilities*/) { + if (outNumCapabilities == nullptr) { + return HWC2::Error::BadParameter; + } + + *outNumCapabilities = 0; + + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::GetDisplayBrightnessSupport(bool *supported) { + *supported = false; + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::SetDisplayBrightness(float /* brightness */) { + return HWC2::Error::Unsupported; +} + +#endif /* PLATFORM_SDK_VERSION > 28 */ + +#if PLATFORM_SDK_VERSION > 27 + +HWC2::Error HwcDisplay::GetRenderIntents( + int32_t mode, uint32_t *outNumIntents, + int32_t * /*android_render_intent_v1_1_t*/ outIntents) { + if (mode != HAL_COLOR_MODE_NATIVE) { + return HWC2::Error::BadParameter; + } + + if (outIntents == nullptr) { + *outNumIntents = 1; + return HWC2::Error::None; + } + *outNumIntents = 1; + outIntents[0] = HAL_RENDER_INTENT_COLORIMETRIC; + return HWC2::Error::None; +} + +HWC2::Error HwcDisplay::SetColorModeWithIntent(int32_t mode, int32_t intent) { + if (intent < HAL_RENDER_INTENT_COLORIMETRIC || + intent > HAL_RENDER_INTENT_TONE_MAP_ENHANCE) + return HWC2::Error::BadParameter; + + if (mode < HAL_COLOR_MODE_NATIVE || mode > HAL_COLOR_MODE_BT2100_HLG) + return HWC2::Error::BadParameter; + + if (mode != HAL_COLOR_MODE_NATIVE) + return HWC2::Error::Unsupported; + + if (intent != HAL_RENDER_INTENT_COLORIMETRIC) + return HWC2::Error::Unsupported; + + color_mode_ = mode; + return HWC2::Error::None; +} + +#endif /* PLATFORM_SDK_VERSION > 27 */ + +const Backend *HwcDisplay::backend() const { + return backend_.get(); +} + +void HwcDisplay::set_backend(std::unique_ptr<Backend> backend) { + backend_ = std::move(backend); +} + +/* returns true if composition should be sent to client */ +bool HwcDisplay::ProcessClientFlatteningState(bool skip) { + int flattenning_state = flattenning_state_; + if (flattenning_state == ClientFlattenningState::Disabled) { + return false; + } + + if (skip) { + flattenning_state_ = ClientFlattenningState::NotRequired; + return false; + } + + if (flattenning_state == ClientFlattenningState::ClientRefreshRequested) { + flattenning_state_ = ClientFlattenningState::Flattened; + return true; + } + + vsync_flattening_en_ = true; + vsync_worker_.VSyncControl(true); + flattenning_state_ = ClientFlattenningState::VsyncCountdownMax; + return false; +} + +void HwcDisplay::ProcessFlatenningVsyncInternal() { + if (flattenning_state_ > ClientFlattenningState::ClientRefreshRequested && + --flattenning_state_ == ClientFlattenningState::ClientRefreshRequested && + hwc2_->refresh_callback_.first != nullptr && + hwc2_->refresh_callback_.second != nullptr) { + hwc2_->refresh_callback_.first(hwc2_->refresh_callback_.second, handle_); + vsync_flattening_en_ = false; + } +} + +} // namespace android diff --git a/hwc2_device/HwcDisplay.h b/hwc2_device/HwcDisplay.h new file mode 100644 index 0000000..98d8e9b --- /dev/null +++ b/hwc2_device/HwcDisplay.h @@ -0,0 +1,239 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_HWC2_DEVICE_HWC_DISPLAY_H +#define ANDROID_HWC2_DEVICE_HWC_DISPLAY_H + +#include <hardware/hwcomposer2.h> + +#include <optional> + +#include "HwcDisplayConfigs.h" +#include "drm/DrmAtomicStateManager.h" +#include "drm/ResourceManager.h" +#include "drm/VSyncWorker.h" +#include "drmhwcomposer.h" +#include "hwc2_device/HwcLayer.h" + +namespace android { + +class Backend; +class DrmHwcTwo; + +inline constexpr uint32_t kPrimaryDisplay = 0; + +class HwcDisplay { + public: + HwcDisplay(hwc2_display_t handle, HWC2::DisplayType type, DrmHwcTwo *hwc2); + HwcDisplay(const HwcDisplay &) = delete; + ~HwcDisplay(); + + /* SetPipeline should be carefully used only by DrmHwcTwo hotplug handlers */ + void SetPipeline(DrmDisplayPipeline *pipeline); + + HWC2::Error CreateComposition(AtomicCommitArgs &a_args); + std::vector<HwcLayer *> GetOrderLayersByZPos(); + + void ClearDisplay(); + + std::string Dump(); + + // HWC Hooks + HWC2::Error AcceptDisplayChanges(); + HWC2::Error CreateLayer(hwc2_layer_t *layer); + HWC2::Error DestroyLayer(hwc2_layer_t layer); + HWC2::Error GetActiveConfig(hwc2_config_t *config) const; + HWC2::Error GetChangedCompositionTypes(uint32_t *num_elements, + hwc2_layer_t *layers, int32_t *types); + HWC2::Error GetClientTargetSupport(uint32_t width, uint32_t height, + int32_t format, int32_t dataspace); + HWC2::Error GetColorModes(uint32_t *num_modes, int32_t *modes); + HWC2::Error GetDisplayAttribute(hwc2_config_t config, int32_t attribute, + int32_t *value); + HWC2::Error GetDisplayConfigs(uint32_t *num_configs, hwc2_config_t *configs); + HWC2::Error GetDisplayName(uint32_t *size, char *name); + HWC2::Error GetDisplayRequests(int32_t *display_requests, + uint32_t *num_elements, hwc2_layer_t *layers, + int32_t *layer_requests); + HWC2::Error GetDisplayType(int32_t *type); +#if PLATFORM_SDK_VERSION > 27 + HWC2::Error GetRenderIntents(int32_t mode, uint32_t *outNumIntents, + int32_t *outIntents); + HWC2::Error SetColorModeWithIntent(int32_t mode, int32_t intent); +#endif +#if PLATFORM_SDK_VERSION > 28 + HWC2::Error GetDisplayIdentificationData(uint8_t *outPort, + uint32_t *outDataSize, + uint8_t *outData); + HWC2::Error GetDisplayCapabilities(uint32_t *outNumCapabilities, + uint32_t *outCapabilities); + HWC2::Error GetDisplayBrightnessSupport(bool *supported); + HWC2::Error SetDisplayBrightness(float); +#endif +#if PLATFORM_SDK_VERSION > 29 + HWC2::Error GetDisplayConnectionType(uint32_t *outType); + + HWC2::Error SetActiveConfigWithConstraints( + hwc2_config_t config, + hwc_vsync_period_change_constraints_t *vsyncPeriodChangeConstraints, + hwc_vsync_period_change_timeline_t *outTimeline); + HWC2::Error SetAutoLowLatencyMode(bool on); + HWC2::Error GetSupportedContentTypes( + uint32_t *outNumSupportedContentTypes, + const uint32_t *outSupportedContentTypes); + + HWC2::Error SetContentType(int32_t contentType); +#endif + HWC2::Error GetDisplayVsyncPeriod(uint32_t *outVsyncPeriod); + + HWC2::Error GetDozeSupport(int32_t *support); + HWC2::Error GetHdrCapabilities(uint32_t *num_types, int32_t *types, + float *max_luminance, + float *max_average_luminance, + float *min_luminance); + HWC2::Error GetReleaseFences(uint32_t *num_elements, hwc2_layer_t *layers, + int32_t *fences); + HWC2::Error PresentDisplay(int32_t *present_fence); + HWC2::Error SetActiveConfig(hwc2_config_t config); + HWC2::Error ChosePreferredConfig(); + HWC2::Error SetClientTarget(buffer_handle_t target, int32_t acquire_fence, + int32_t dataspace, hwc_region_t damage); + HWC2::Error SetColorMode(int32_t mode); + HWC2::Error SetColorTransform(const float *matrix, int32_t hint); + HWC2::Error SetOutputBuffer(buffer_handle_t buffer, int32_t release_fence); + HWC2::Error SetPowerMode(int32_t mode); + HWC2::Error SetVsyncEnabled(int32_t enabled); + HWC2::Error ValidateDisplay(uint32_t *num_types, uint32_t *num_requests); + HwcLayer *get_layer(hwc2_layer_t layer) { + auto it = layers_.find(layer); + if (it == layers_.end()) + return nullptr; + return &it->second; + } + + /* Statistics */ + struct Stats { + Stats minus(Stats b) const { + return {total_frames_ - b.total_frames_, + total_pixops_ - b.total_pixops_, + gpu_pixops_ - b.gpu_pixops_, + failed_kms_validate_ - b.failed_kms_validate_, + failed_kms_present_ - b.failed_kms_present_, + frames_flattened_ - b.frames_flattened_}; + } + + uint32_t total_frames_ = 0; + uint64_t total_pixops_ = 0; + uint64_t gpu_pixops_ = 0; + uint32_t failed_kms_validate_ = 0; + uint32_t failed_kms_present_ = 0; + uint32_t frames_flattened_ = 0; + }; + + const Backend *backend() const; + void set_backend(std::unique_ptr<Backend> backend); + + auto GetHwc2() { + return hwc2_; + } + + std::map<hwc2_layer_t, HwcLayer> &layers() { + return layers_; + } + + auto &GetPipe() { + return *pipeline_; + } + + android_color_transform_t &color_transform_hint() { + return color_transform_hint_; + } + + Stats &total_stats() { + return total_stats_; + } + + /* returns true if composition should be sent to client */ + bool ProcessClientFlatteningState(bool skip); + void ProcessFlatenningVsyncInternal(); + + /* Headless mode required to keep SurfaceFlinger alive when all display are + * disconnected, Without headless mode Android will continuously crash. + * Only single internal (primary) display is required to be in HEADLESS mode + * to prevent the crash. See: + * https://source.android.com/devices/graphics/hotplug#handling-common-scenarios + */ + bool IsInHeadlessMode() { + return !pipeline_; + } + + private: + enum ClientFlattenningState : int32_t { + Disabled = -3, + NotRequired = -2, + Flattened = -1, + ClientRefreshRequested = 0, + VsyncCountdownMax = 60, /* 1 sec @ 60FPS */ + }; + + std::atomic_int flattenning_state_{ClientFlattenningState::NotRequired}; + + constexpr static size_t MATRIX_SIZE = 16; + + HwcDisplayConfigs configs_; + + DrmHwcTwo *const hwc2_; + + std::optional<DrmMode> staged_mode_; + int64_t staged_mode_change_time_{}; + uint32_t staged_mode_config_id_{}; + + DrmDisplayPipeline *pipeline_{}; + + std::unique_ptr<Backend> backend_; + + VSyncWorker vsync_worker_; + bool vsync_event_en_{}; + bool vsync_flattening_en_{}; + bool vsync_tracking_en_{}; + int64_t last_vsync_ts_{}; + + const hwc2_display_t handle_; + HWC2::DisplayType type_; + + uint32_t layer_idx_{}; + + std::map<hwc2_layer_t, HwcLayer> layers_; + HwcLayer client_layer_; + int32_t color_mode_{}; + std::array<float, MATRIX_SIZE> color_transform_matrix_{}; + android_color_transform_t color_transform_hint_; + + std::shared_ptr<DrmKmsPlan> current_plan_; + + uint32_t frame_no_ = 0; + Stats total_stats_; + Stats prev_stats_; + std::string DumpDelta(HwcDisplay::Stats delta); + + HWC2::Error Init(); + + HWC2::Error SetActiveConfigInternal(uint32_t config, int64_t change_time); +}; + +} // namespace android + +#endif diff --git a/hwc2_device/HwcDisplayConfigs.cpp b/hwc2_device/HwcDisplayConfigs.cpp new file mode 100644 index 0000000..6a3ed5a --- /dev/null +++ b/hwc2_device/HwcDisplayConfigs.cpp @@ -0,0 +1,202 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "hwc-display-configs" + +#include "HwcDisplayConfigs.h" + +#include <cmath> + +#include "drm/DrmConnector.h" +#include "utils/log.h" + +constexpr uint32_t kHeadlessModeDisplayWidthMm = 163; +constexpr uint32_t kHeadlessModeDisplayHeightMm = 122; +constexpr uint32_t kHeadlessModeDisplayWidthPx = 1024; +constexpr uint32_t kHeadlessModeDisplayHeightPx = 768; +constexpr uint32_t kHeadlessModeDisplayVRefresh = 60; + +namespace android { + +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +uint32_t HwcDisplayConfigs::last_config_id = 1; + +void HwcDisplayConfigs::FillHeadless() { + hwc_configs.clear(); + + last_config_id++; + preferred_config_id = active_config_id = last_config_id; + auto headless_drm_mode_info = (drmModeModeInfo){ + .hdisplay = kHeadlessModeDisplayWidthPx, + .vdisplay = kHeadlessModeDisplayHeightPx, + .vrefresh = kHeadlessModeDisplayVRefresh, + .name = "HEADLESS-MODE", + }; + hwc_configs[active_config_id] = (HwcDisplayConfig){ + .id = active_config_id, + .group_id = 1, + .mode = DrmMode(&headless_drm_mode_info), + }; + + mm_width = kHeadlessModeDisplayWidthMm; + mm_height = kHeadlessModeDisplayHeightMm; +} + +// NOLINTNEXTLINE (readability-function-cognitive-complexity): Fixme +HWC2::Error HwcDisplayConfigs::Update(DrmConnector &connector) { + /* In case UpdateModes will fail we will still have one mode for headless + * mode*/ + FillHeadless(); + /* Read real configs */ + int ret = connector.UpdateModes(); + if (ret != 0) { + ALOGE("Failed to update display modes %d", ret); + return HWC2::Error::BadDisplay; + } + + if (connector.GetModes().empty()) { + ALOGE("No modes reported by KMS"); + return HWC2::Error::BadDisplay; + } + + hwc_configs.clear(); + mm_width = connector.GetMmWidth(); + mm_height = connector.GetMmHeight(); + + preferred_config_id = 0; + uint32_t preferred_config_group_id = 0; + + uint32_t first_config_id = last_config_id; + uint32_t last_group_id = 1; + + /* Group modes */ + for (const auto &mode : connector.GetModes()) { + /* Find group for the new mode or create new group */ + uint32_t group_found = 0; + for (auto &hwc_config : hwc_configs) { + if (mode.h_display() == hwc_config.second.mode.h_display() && + mode.v_display() == hwc_config.second.mode.v_display()) { + group_found = hwc_config.second.group_id; + } + } + if (group_found == 0) { + group_found = last_group_id++; + } + + bool disabled = false; + if ((mode.flags() & DRM_MODE_FLAG_3D_MASK) != 0) { + ALOGI("Disabling display mode %s (Modes with 3D flag aren't supported)", + mode.name().c_str()); + disabled = true; + } + + /* Add config */ + hwc_configs[last_config_id] = { + .id = last_config_id, + .group_id = group_found, + .mode = mode, + .disabled = disabled, + }; + + /* Chwck if the mode is preferred */ + if ((mode.type() & DRM_MODE_TYPE_PREFERRED) != 0 && + preferred_config_id == 0) { + preferred_config_id = last_config_id; + preferred_config_group_id = group_found; + } + + last_config_id++; + } + + /* We must have preferred mode. Set first mode as preferred + * in case KMS haven't reported anything. */ + if (preferred_config_id == 0) { + preferred_config_id = first_config_id; + preferred_config_group_id = 1; + } + + for (uint32_t group = 1; group < last_group_id; group++) { + bool has_interlaced = false; + bool has_progressive = false; + for (auto &hwc_config : hwc_configs) { + if (hwc_config.second.group_id != group || hwc_config.second.disabled) { + continue; + } + + if (hwc_config.second.IsInterlaced()) { + has_interlaced = true; + } else { + has_progressive = true; + } + } + + bool has_both = has_interlaced && has_progressive; + if (!has_both) { + continue; + } + + bool group_contains_preferred_interlaced = false; + if (group == preferred_config_group_id && + hwc_configs[preferred_config_id].IsInterlaced()) { + group_contains_preferred_interlaced = true; + } + + for (auto &hwc_config : hwc_configs) { + if (hwc_config.second.group_id != group || hwc_config.second.disabled) { + continue; + } + + bool disable = group_contains_preferred_interlaced + ? !hwc_config.second.IsInterlaced() + : hwc_config.second.IsInterlaced(); + + if (disable) { + ALOGI( + "Group %i: Disabling display mode %s (This group should consist " + "of %s modes)", + group, hwc_config.second.mode.name().c_str(), + group_contains_preferred_interlaced ? "interlaced" : "progressive"); + + hwc_config.second.disabled = true; + } + } + } + + /* Group should not contain 2 modes with FPS delta less than ~1HZ + * otherwise android.graphics.cts.SetFrameRateTest CTS will fail + */ + constexpr float kMinFpsDelta = 1.0; // FPS + for (uint32_t m1 = first_config_id; m1 < last_config_id; m1++) { + for (uint32_t m2 = first_config_id; m2 < last_config_id; m2++) { + if (m1 != m2 && hwc_configs[m1].group_id == hwc_configs[m2].group_id && + !hwc_configs[m1].disabled && !hwc_configs[m2].disabled && + fabsf(hwc_configs[m1].mode.v_refresh() - + hwc_configs[m2].mode.v_refresh()) < kMinFpsDelta) { + ALOGI( + "Group %i: Disabling display mode %s (Refresh rate value is " + "too close to existing mode %s)", + hwc_configs[m2].group_id, hwc_configs[m2].mode.name().c_str(), + hwc_configs[m1].mode.name().c_str()); + + hwc_configs[m2].disabled = true; + } + } + } + + return HWC2::Error::None; +} + +} // namespace android diff --git a/hwc2_device/HwcDisplayConfigs.h b/hwc2_device/HwcDisplayConfigs.h new file mode 100644 index 0000000..7c173d6 --- /dev/null +++ b/hwc2_device/HwcDisplayConfigs.h @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_HWC2_DEVICE_HWC_DISPLAY_CONFIGS_H +#define ANDROID_HWC2_DEVICE_HWC_DISPLAY_CONFIGS_H + +#include <hardware/hwcomposer2.h> + +#include <map> + +#include "drm/DrmMode.h" + +namespace android { + +class DrmConnector; + +struct HwcDisplayConfig { + uint32_t id{}; + uint32_t group_id{}; + DrmMode mode; + bool disabled{}; + + bool IsInterlaced() const { + return (mode.flags() & DRM_MODE_FLAG_INTERLACE) != 0; + } +}; + +struct HwcDisplayConfigs { + HWC2::Error Update(DrmConnector &conn); + void FillHeadless(); + + std::map<uint32_t /*config_id*/, struct HwcDisplayConfig> hwc_configs; + + uint32_t active_config_id = 0; + uint32_t preferred_config_id = 0; + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) + static uint32_t last_config_id; + + uint32_t mm_width = 0; + uint32_t mm_height = 0; +}; + +} // namespace android + +#endif diff --git a/hwc2_device/HwcLayer.cpp b/hwc2_device/HwcLayer.cpp new file mode 100644 index 0000000..66babda --- /dev/null +++ b/hwc2_device/HwcLayer.cpp @@ -0,0 +1,180 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "hwc-layer" + +#include "HwcLayer.h" + +#include <fcntl.h> + +#include "utils/log.h" + +namespace android { + +// NOLINTNEXTLINE(readability-convert-member-functions-to-static) +HWC2::Error HwcLayer::SetCursorPosition(int32_t /*x*/, int32_t /*y*/) { + return HWC2::Error::None; +} + +HWC2::Error HwcLayer::SetLayerBlendMode(int32_t mode) { + switch (static_cast<HWC2::BlendMode>(mode)) { + case HWC2::BlendMode::None: + blending_ = DrmHwcBlending::kNone; + break; + case HWC2::BlendMode::Premultiplied: + blending_ = DrmHwcBlending::kPreMult; + break; + case HWC2::BlendMode::Coverage: + blending_ = DrmHwcBlending::kCoverage; + break; + default: + ALOGE("Unknown blending mode b=%d", blending_); + blending_ = DrmHwcBlending::kNone; + break; + } + return HWC2::Error::None; +} + +/* Find API details at: + * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r3:hardware/libhardware/include/hardware/hwcomposer2.h;l=2314 + */ +HWC2::Error HwcLayer::SetLayerBuffer(buffer_handle_t buffer, + int32_t acquire_fence) { + buffer_ = buffer; + acquire_fence_ = UniqueFd(acquire_fence); + return HWC2::Error::None; +} + +// NOLINTNEXTLINE(readability-convert-member-functions-to-static) +HWC2::Error HwcLayer::SetLayerColor(hwc_color_t /*color*/) { + // TODO(nobody): Put to client composition here? + return HWC2::Error::None; +} + +HWC2::Error HwcLayer::SetLayerCompositionType(int32_t type) { + sf_type_ = static_cast<HWC2::Composition>(type); + return HWC2::Error::None; +} + +HWC2::Error HwcLayer::SetLayerDataspace(int32_t dataspace) { + switch (dataspace & HAL_DATASPACE_STANDARD_MASK) { + case HAL_DATASPACE_STANDARD_BT709: + color_space_ = DrmHwcColorSpace::kItuRec709; + break; + case HAL_DATASPACE_STANDARD_BT601_625: + case HAL_DATASPACE_STANDARD_BT601_625_UNADJUSTED: + case HAL_DATASPACE_STANDARD_BT601_525: + case HAL_DATASPACE_STANDARD_BT601_525_UNADJUSTED: + color_space_ = DrmHwcColorSpace::kItuRec601; + break; + case HAL_DATASPACE_STANDARD_BT2020: + case HAL_DATASPACE_STANDARD_BT2020_CONSTANT_LUMINANCE: + color_space_ = DrmHwcColorSpace::kItuRec2020; + break; + default: + color_space_ = DrmHwcColorSpace::kUndefined; + } + + switch (dataspace & HAL_DATASPACE_RANGE_MASK) { + case HAL_DATASPACE_RANGE_FULL: + sample_range_ = DrmHwcSampleRange::kFullRange; + break; + case HAL_DATASPACE_RANGE_LIMITED: + sample_range_ = DrmHwcSampleRange::kLimitedRange; + break; + default: + sample_range_ = DrmHwcSampleRange::kUndefined; + } + return HWC2::Error::None; +} + +HWC2::Error HwcLayer::SetLayerDisplayFrame(hwc_rect_t frame) { + display_frame_ = frame; + return HWC2::Error::None; +} + +HWC2::Error HwcLayer::SetLayerPlaneAlpha(float alpha) { + alpha_ = alpha; + return HWC2::Error::None; +} + +// NOLINTNEXTLINE(readability-convert-member-functions-to-static) +HWC2::Error HwcLayer::SetLayerSidebandStream( + const native_handle_t * /*stream*/) { + // TODO(nobody): We don't support sideband + return HWC2::Error::Unsupported; +} + +HWC2::Error HwcLayer::SetLayerSourceCrop(hwc_frect_t crop) { + source_crop_ = crop; + return HWC2::Error::None; +} + +// NOLINTNEXTLINE(readability-convert-member-functions-to-static) +HWC2::Error HwcLayer::SetLayerSurfaceDamage(hwc_region_t /*damage*/) { + // TODO(nobody): We don't use surface damage, marking as unsupported + return HWC2::Error::None; +} + +HWC2::Error HwcLayer::SetLayerTransform(int32_t transform) { + uint32_t l_transform = 0; + + // 270* and 180* cannot be combined with flips. More specifically, they + // already contain both horizontal and vertical flips, so those fields are + // redundant in this case. 90* rotation can be combined with either horizontal + // flip or vertical flip, so treat it differently + if (transform == HWC_TRANSFORM_ROT_270) { + l_transform = DrmHwcTransform::kRotate270; + } else if (transform == HWC_TRANSFORM_ROT_180) { + l_transform = DrmHwcTransform::kRotate180; + } else { + if ((transform & HWC_TRANSFORM_FLIP_H) != 0) + l_transform |= DrmHwcTransform::kFlipH; + if ((transform & HWC_TRANSFORM_FLIP_V) != 0) + l_transform |= DrmHwcTransform::kFlipV; + if ((transform & HWC_TRANSFORM_ROT_90) != 0) + l_transform |= DrmHwcTransform::kRotate90; + } + + transform_ = static_cast<DrmHwcTransform>(l_transform); + return HWC2::Error::None; +} + +// NOLINTNEXTLINE(readability-convert-member-functions-to-static) +HWC2::Error HwcLayer::SetLayerVisibleRegion(hwc_region_t /*visible*/) { + // TODO(nobody): We don't use this information, marking as unsupported + return HWC2::Error::None; +} + +HWC2::Error HwcLayer::SetLayerZOrder(uint32_t order) { + z_order_ = order; + return HWC2::Error::None; +} + +void HwcLayer::PopulateDrmLayer(DrmHwcLayer *layer) { + layer->sf_handle = buffer_; + // TODO(rsglobal): Avoid extra fd duplication + layer->acquire_fence = UniqueFd(fcntl(acquire_fence_.Get(), F_DUPFD_CLOEXEC)); + layer->display_frame = display_frame_; + layer->alpha = std::lround(alpha_ * UINT16_MAX); + layer->blending = blending_; + layer->source_crop = source_crop_; + layer->transform = transform_; + layer->color_space = color_space_; + layer->sample_range = sample_range_; +} + +} // namespace android
\ No newline at end of file diff --git a/hwc2_device/HwcLayer.h b/hwc2_device/HwcLayer.h new file mode 100644 index 0000000..df4ce6d --- /dev/null +++ b/hwc2_device/HwcLayer.h @@ -0,0 +1,123 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_HWC2_DEVICE_HWC_LAYER_H +#define ANDROID_HWC2_DEVICE_HWC_LAYER_H + +#include <hardware/hwcomposer2.h> + +#include <cmath> + +#include "drmhwcomposer.h" + +namespace android { + +class HwcLayer { + public: + HWC2::Composition GetSfType() const { + return sf_type_; + } + HWC2::Composition GetValidatedType() const { + return validated_type_; + } + void AcceptTypeChange() { + sf_type_ = validated_type_; + } + void SetValidatedType(HWC2::Composition type) { + validated_type_ = type; + } + bool IsTypeChanged() const { + return sf_type_ != validated_type_; + } + + uint32_t GetZOrder() const { + return z_order_; + } + + buffer_handle_t GetBuffer() { + return buffer_; + } + + hwc_rect_t GetDisplayFrame() { + return display_frame_; + } + + UniqueFd GetReleaseFence() { + return std::move(release_fence_); + } + + void PopulateDrmLayer(DrmHwcLayer *layer); + + bool RequireScalingOrPhasing() const { + float src_width = source_crop_.right - source_crop_.left; + float src_height = source_crop_.bottom - source_crop_.top; + + auto dest_width = float(display_frame_.right - display_frame_.left); + auto dest_height = float(display_frame_.bottom - display_frame_.top); + + bool scaling = src_width != dest_width || src_height != dest_height; + bool phasing = (source_crop_.left - std::floor(source_crop_.left) != 0) || + (source_crop_.top - std::floor(source_crop_.top) != 0); + return scaling || phasing; + } + + // Layer hooks + HWC2::Error SetCursorPosition(int32_t /*x*/, int32_t /*y*/); + HWC2::Error SetLayerBlendMode(int32_t mode); + HWC2::Error SetLayerBuffer(buffer_handle_t buffer, int32_t acquire_fence); + HWC2::Error SetLayerColor(hwc_color_t /*color*/); + HWC2::Error SetLayerCompositionType(int32_t type); + HWC2::Error SetLayerDataspace(int32_t dataspace); + HWC2::Error SetLayerDisplayFrame(hwc_rect_t frame); + HWC2::Error SetLayerPlaneAlpha(float alpha); + HWC2::Error SetLayerSidebandStream(const native_handle_t *stream); + HWC2::Error SetLayerSourceCrop(hwc_frect_t crop); + HWC2::Error SetLayerSurfaceDamage(hwc_region_t damage); + HWC2::Error SetLayerTransform(int32_t transform); + HWC2::Error SetLayerVisibleRegion(hwc_region_t visible); + HWC2::Error SetLayerZOrder(uint32_t order); + + private: + // sf_type_ stores the initial type given to us by surfaceflinger, + // validated_type_ stores the type after running ValidateDisplay + HWC2::Composition sf_type_ = HWC2::Composition::Invalid; + HWC2::Composition validated_type_ = HWC2::Composition::Invalid; + + buffer_handle_t buffer_ = nullptr; + hwc_rect_t display_frame_; + static constexpr float kOpaqueFloat = 1.0F; + float alpha_ = kOpaqueFloat; + hwc_frect_t source_crop_; + DrmHwcTransform transform_ = DrmHwcTransform::kIdentity; + uint32_t z_order_ = 0; + DrmHwcBlending blending_ = DrmHwcBlending::kNone; + DrmHwcColorSpace color_space_ = DrmHwcColorSpace::kUndefined; + DrmHwcSampleRange sample_range_ = DrmHwcSampleRange::kUndefined; + + UniqueFd acquire_fence_; + + /* + * Release fence is not used. + * There is no release fence support available in the DRM/KMS. In case no + * release fence provided application will use this buffer for writing when + * the next frame present fence is signaled. + */ + UniqueFd release_fence_; +}; + +} // namespace android + +#endif diff --git a/hwc2_device/hwc2_device.cpp b/hwc2_device/hwc2_device.cpp new file mode 100644 index 0000000..a6dedb4 --- /dev/null +++ b/hwc2_device/hwc2_device.cpp @@ -0,0 +1,415 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +// #define LOG_NDEBUG 0 // Uncomment to see HWC2 API calls in logcat + +#define LOG_TAG "hwc2-device" + +#include <cinttypes> + +#include "DrmHwcTwo.h" +#include "backend/Backend.h" +#include "utils/log.h" + +namespace android { + +/* Converts long __PRETTY_FUNCTION__ result, e.g.: + * "int32_t android::LayerHook(hwc2_device_t *, hwc2_display_t, hwc2_layer_t," + * "Args...) [HookType = HWC2::Error (android::HwcLayer::*)(const native_handle" + * "*,int), func = &android::HwcLayer::SetLayerBuffer, Args = <const + * "native_handle, int>" + * to the short "android::HwcLayer::SetLayerBuffer" for better logs readability + */ +static std::string GetFuncName(const char *pretty_function) { + std::string str(pretty_function); + const char *start = "func = &"; + size_t p1 = str.find(start); + p1 += strlen(start); + size_t p2 = str.find(',', p1); + return str.substr(p1, p2 - p1); +} + +struct Drmhwc2Device : hwc2_device { + DrmHwcTwo drmhwctwo; +}; + +static DrmHwcTwo *ToDrmHwcTwo(hwc2_device_t *dev) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast): + return &static_cast<Drmhwc2Device *>(dev)->drmhwctwo; +} + +template <typename PFN, typename T> +static hwc2_function_pointer_t ToHook(T function) { + static_assert(std::is_same<PFN, T>::value, "Incompatible fn pointer"); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): + return reinterpret_cast<hwc2_function_pointer_t>(function); +} + +template <typename T, typename HookType, HookType func, typename... Args> +static T DeviceHook(hwc2_device_t *dev, Args... args) { + ALOGV("Device hook: %s", GetFuncName(__PRETTY_FUNCTION__).c_str()); + DrmHwcTwo *hwc = ToDrmHwcTwo(dev); + const std::lock_guard<std::mutex> lock(hwc->GetResMan().GetMainLock()); + return static_cast<T>(((*hwc).*func)(std::forward<Args>(args)...)); +} + +template <typename HookType, HookType func, typename... Args> +static int32_t DisplayHook(hwc2_device_t *dev, hwc2_display_t display_handle, + Args... args) { + ALOGV("Display #%" PRIu64 " hook: %s", display_handle, + GetFuncName(__PRETTY_FUNCTION__).c_str()); + DrmHwcTwo *hwc = ToDrmHwcTwo(dev); + const std::lock_guard<std::mutex> lock(hwc->GetResMan().GetMainLock()); + auto *display = hwc->GetDisplay(display_handle); + if (display == nullptr) + return static_cast<int32_t>(HWC2::Error::BadDisplay); + + return static_cast<int32_t>((display->*func)(std::forward<Args>(args)...)); +} + +template <typename HookType, HookType func, typename... Args> +static int32_t LayerHook(hwc2_device_t *dev, hwc2_display_t display_handle, + hwc2_layer_t layer_handle, Args... args) { + ALOGV("Display #%" PRIu64 " Layer: #%" PRIu64 " hook: %s", display_handle, + layer_handle, GetFuncName(__PRETTY_FUNCTION__).c_str()); + DrmHwcTwo *hwc = ToDrmHwcTwo(dev); + const std::lock_guard<std::mutex> lock(hwc->GetResMan().GetMainLock()); + auto *display = hwc->GetDisplay(display_handle); + if (display == nullptr) + return static_cast<int32_t>(HWC2::Error::BadDisplay); + + HwcLayer *layer = display->get_layer(layer_handle); + if (!layer) + return static_cast<int32_t>(HWC2::Error::BadLayer); + + return static_cast<int32_t>((layer->*func)(std::forward<Args>(args)...)); +} + +static int HookDevClose(hw_device_t *dev) { + // NOLINTNEXTLINE (cppcoreguidelines-pro-type-reinterpret-cast): Safe + auto *hwc2_dev = reinterpret_cast<hwc2_device_t *>(dev); + std::unique_ptr<DrmHwcTwo> ctx(ToDrmHwcTwo(hwc2_dev)); + return 0; +} + +static void HookDevGetCapabilities(hwc2_device_t * /*dev*/, uint32_t *out_count, + int32_t * /*out_capabilities*/) { + *out_count = 0; +} + +static hwc2_function_pointer_t HookDevGetFunction(struct hwc2_device * /*dev*/, + int32_t descriptor) { + auto func = static_cast<HWC2::FunctionDescriptor>(descriptor); + switch (func) { + // Device functions + case HWC2::FunctionDescriptor::CreateVirtualDisplay: + return ToHook<HWC2_PFN_CREATE_VIRTUAL_DISPLAY>( + DeviceHook<int32_t, decltype(&DrmHwcTwo::CreateVirtualDisplay), + &DrmHwcTwo::CreateVirtualDisplay, uint32_t, uint32_t, + int32_t *, hwc2_display_t *>); + case HWC2::FunctionDescriptor::DestroyVirtualDisplay: + return ToHook<HWC2_PFN_DESTROY_VIRTUAL_DISPLAY>( + DeviceHook<int32_t, decltype(&DrmHwcTwo::DestroyVirtualDisplay), + &DrmHwcTwo::DestroyVirtualDisplay, hwc2_display_t>); + case HWC2::FunctionDescriptor::Dump: + return ToHook<HWC2_PFN_DUMP>( + DeviceHook<void, decltype(&DrmHwcTwo::Dump), &DrmHwcTwo::Dump, + uint32_t *, char *>); + case HWC2::FunctionDescriptor::GetMaxVirtualDisplayCount: + return ToHook<HWC2_PFN_GET_MAX_VIRTUAL_DISPLAY_COUNT>( + DeviceHook<uint32_t, decltype(&DrmHwcTwo::GetMaxVirtualDisplayCount), + &DrmHwcTwo::GetMaxVirtualDisplayCount>); + case HWC2::FunctionDescriptor::RegisterCallback: + return ToHook<HWC2_PFN_REGISTER_CALLBACK>( + DeviceHook<int32_t, decltype(&DrmHwcTwo::RegisterCallback), + &DrmHwcTwo::RegisterCallback, int32_t, + hwc2_callback_data_t, hwc2_function_pointer_t>); + + // Display functions + case HWC2::FunctionDescriptor::AcceptDisplayChanges: + return ToHook<HWC2_PFN_ACCEPT_DISPLAY_CHANGES>( + DisplayHook<decltype(&HwcDisplay::AcceptDisplayChanges), + &HwcDisplay::AcceptDisplayChanges>); + case HWC2::FunctionDescriptor::CreateLayer: + return ToHook<HWC2_PFN_CREATE_LAYER>( + DisplayHook<decltype(&HwcDisplay::CreateLayer), + &HwcDisplay::CreateLayer, hwc2_layer_t *>); + case HWC2::FunctionDescriptor::DestroyLayer: + return ToHook<HWC2_PFN_DESTROY_LAYER>( + DisplayHook<decltype(&HwcDisplay::DestroyLayer), + &HwcDisplay::DestroyLayer, hwc2_layer_t>); + case HWC2::FunctionDescriptor::GetActiveConfig: + return ToHook<HWC2_PFN_GET_ACTIVE_CONFIG>( + DisplayHook<decltype(&HwcDisplay::GetActiveConfig), + &HwcDisplay::GetActiveConfig, hwc2_config_t *>); + case HWC2::FunctionDescriptor::GetChangedCompositionTypes: + return ToHook<HWC2_PFN_GET_CHANGED_COMPOSITION_TYPES>( + DisplayHook<decltype(&HwcDisplay::GetChangedCompositionTypes), + &HwcDisplay::GetChangedCompositionTypes, uint32_t *, + hwc2_layer_t *, int32_t *>); + case HWC2::FunctionDescriptor::GetClientTargetSupport: + return ToHook<HWC2_PFN_GET_CLIENT_TARGET_SUPPORT>( + DisplayHook<decltype(&HwcDisplay::GetClientTargetSupport), + &HwcDisplay::GetClientTargetSupport, uint32_t, uint32_t, + int32_t, int32_t>); + case HWC2::FunctionDescriptor::GetColorModes: + return ToHook<HWC2_PFN_GET_COLOR_MODES>( + DisplayHook<decltype(&HwcDisplay::GetColorModes), + &HwcDisplay::GetColorModes, uint32_t *, int32_t *>); + case HWC2::FunctionDescriptor::GetDisplayAttribute: + return ToHook<HWC2_PFN_GET_DISPLAY_ATTRIBUTE>( + DisplayHook<decltype(&HwcDisplay::GetDisplayAttribute), + &HwcDisplay::GetDisplayAttribute, hwc2_config_t, int32_t, + int32_t *>); + case HWC2::FunctionDescriptor::GetDisplayConfigs: + return ToHook<HWC2_PFN_GET_DISPLAY_CONFIGS>( + DisplayHook<decltype(&HwcDisplay::GetDisplayConfigs), + &HwcDisplay::GetDisplayConfigs, uint32_t *, + hwc2_config_t *>); + case HWC2::FunctionDescriptor::GetDisplayName: + return ToHook<HWC2_PFN_GET_DISPLAY_NAME>( + DisplayHook<decltype(&HwcDisplay::GetDisplayName), + &HwcDisplay::GetDisplayName, uint32_t *, char *>); + case HWC2::FunctionDescriptor::GetDisplayRequests: + return ToHook<HWC2_PFN_GET_DISPLAY_REQUESTS>( + DisplayHook<decltype(&HwcDisplay::GetDisplayRequests), + &HwcDisplay::GetDisplayRequests, int32_t *, uint32_t *, + hwc2_layer_t *, int32_t *>); + case HWC2::FunctionDescriptor::GetDisplayType: + return ToHook<HWC2_PFN_GET_DISPLAY_TYPE>( + DisplayHook<decltype(&HwcDisplay::GetDisplayType), + &HwcDisplay::GetDisplayType, int32_t *>); + case HWC2::FunctionDescriptor::GetDozeSupport: + return ToHook<HWC2_PFN_GET_DOZE_SUPPORT>( + DisplayHook<decltype(&HwcDisplay::GetDozeSupport), + &HwcDisplay::GetDozeSupport, int32_t *>); + case HWC2::FunctionDescriptor::GetHdrCapabilities: + return ToHook<HWC2_PFN_GET_HDR_CAPABILITIES>( + DisplayHook<decltype(&HwcDisplay::GetHdrCapabilities), + &HwcDisplay::GetHdrCapabilities, uint32_t *, int32_t *, + float *, float *, float *>); + case HWC2::FunctionDescriptor::GetReleaseFences: + return ToHook<HWC2_PFN_GET_RELEASE_FENCES>( + DisplayHook<decltype(&HwcDisplay::GetReleaseFences), + &HwcDisplay::GetReleaseFences, uint32_t *, hwc2_layer_t *, + int32_t *>); + case HWC2::FunctionDescriptor::PresentDisplay: + return ToHook<HWC2_PFN_PRESENT_DISPLAY>( + DisplayHook<decltype(&HwcDisplay::PresentDisplay), + &HwcDisplay::PresentDisplay, int32_t *>); + case HWC2::FunctionDescriptor::SetActiveConfig: + return ToHook<HWC2_PFN_SET_ACTIVE_CONFIG>( + DisplayHook<decltype(&HwcDisplay::SetActiveConfig), + &HwcDisplay::SetActiveConfig, hwc2_config_t>); + case HWC2::FunctionDescriptor::SetClientTarget: + return ToHook<HWC2_PFN_SET_CLIENT_TARGET>( + DisplayHook<decltype(&HwcDisplay::SetClientTarget), + &HwcDisplay::SetClientTarget, buffer_handle_t, int32_t, + int32_t, hwc_region_t>); + case HWC2::FunctionDescriptor::SetColorMode: + return ToHook<HWC2_PFN_SET_COLOR_MODE>( + DisplayHook<decltype(&HwcDisplay::SetColorMode), + &HwcDisplay::SetColorMode, int32_t>); + case HWC2::FunctionDescriptor::SetColorTransform: + return ToHook<HWC2_PFN_SET_COLOR_TRANSFORM>( + DisplayHook<decltype(&HwcDisplay::SetColorTransform), + &HwcDisplay::SetColorTransform, const float *, int32_t>); + case HWC2::FunctionDescriptor::SetOutputBuffer: + return ToHook<HWC2_PFN_SET_OUTPUT_BUFFER>( + DisplayHook<decltype(&HwcDisplay::SetOutputBuffer), + &HwcDisplay::SetOutputBuffer, buffer_handle_t, int32_t>); + case HWC2::FunctionDescriptor::SetPowerMode: + return ToHook<HWC2_PFN_SET_POWER_MODE>( + DisplayHook<decltype(&HwcDisplay::SetPowerMode), + &HwcDisplay::SetPowerMode, int32_t>); + case HWC2::FunctionDescriptor::SetVsyncEnabled: + return ToHook<HWC2_PFN_SET_VSYNC_ENABLED>( + DisplayHook<decltype(&HwcDisplay::SetVsyncEnabled), + &HwcDisplay::SetVsyncEnabled, int32_t>); + case HWC2::FunctionDescriptor::ValidateDisplay: + return ToHook<HWC2_PFN_VALIDATE_DISPLAY>( + DisplayHook<decltype(&HwcDisplay::ValidateDisplay), + &HwcDisplay::ValidateDisplay, uint32_t *, uint32_t *>); +#if PLATFORM_SDK_VERSION > 27 + case HWC2::FunctionDescriptor::GetRenderIntents: + return ToHook<HWC2_PFN_GET_RENDER_INTENTS>( + DisplayHook<decltype(&HwcDisplay::GetRenderIntents), + &HwcDisplay::GetRenderIntents, int32_t, uint32_t *, + int32_t *>); + case HWC2::FunctionDescriptor::SetColorModeWithRenderIntent: + return ToHook<HWC2_PFN_SET_COLOR_MODE_WITH_RENDER_INTENT>( + DisplayHook<decltype(&HwcDisplay::SetColorModeWithIntent), + &HwcDisplay::SetColorModeWithIntent, int32_t, int32_t>); +#endif +#if PLATFORM_SDK_VERSION > 28 + case HWC2::FunctionDescriptor::GetDisplayIdentificationData: + return ToHook<HWC2_PFN_GET_DISPLAY_IDENTIFICATION_DATA>( + DisplayHook<decltype(&HwcDisplay::GetDisplayIdentificationData), + &HwcDisplay::GetDisplayIdentificationData, uint8_t *, + uint32_t *, uint8_t *>); + case HWC2::FunctionDescriptor::GetDisplayCapabilities: + return ToHook<HWC2_PFN_GET_DISPLAY_CAPABILITIES>( + DisplayHook<decltype(&HwcDisplay::GetDisplayCapabilities), + &HwcDisplay::GetDisplayCapabilities, uint32_t *, + uint32_t *>); + case HWC2::FunctionDescriptor::GetDisplayBrightnessSupport: + return ToHook<HWC2_PFN_GET_DISPLAY_BRIGHTNESS_SUPPORT>( + DisplayHook<decltype(&HwcDisplay::GetDisplayBrightnessSupport), + &HwcDisplay::GetDisplayBrightnessSupport, bool *>); + case HWC2::FunctionDescriptor::SetDisplayBrightness: + return ToHook<HWC2_PFN_SET_DISPLAY_BRIGHTNESS>( + DisplayHook<decltype(&HwcDisplay::SetDisplayBrightness), + &HwcDisplay::SetDisplayBrightness, float>); +#endif /* PLATFORM_SDK_VERSION > 28 */ +#if PLATFORM_SDK_VERSION > 29 + case HWC2::FunctionDescriptor::GetDisplayConnectionType: + return ToHook<HWC2_PFN_GET_DISPLAY_CONNECTION_TYPE>( + DisplayHook<decltype(&HwcDisplay::GetDisplayConnectionType), + &HwcDisplay::GetDisplayConnectionType, uint32_t *>); + case HWC2::FunctionDescriptor::GetDisplayVsyncPeriod: + return ToHook<HWC2_PFN_GET_DISPLAY_VSYNC_PERIOD>( + DisplayHook<decltype(&HwcDisplay::GetDisplayVsyncPeriod), + &HwcDisplay::GetDisplayVsyncPeriod, + hwc2_vsync_period_t *>); + case HWC2::FunctionDescriptor::SetActiveConfigWithConstraints: + return ToHook<HWC2_PFN_SET_ACTIVE_CONFIG_WITH_CONSTRAINTS>( + DisplayHook<decltype(&HwcDisplay::SetActiveConfigWithConstraints), + &HwcDisplay::SetActiveConfigWithConstraints, + hwc2_config_t, hwc_vsync_period_change_constraints_t *, + hwc_vsync_period_change_timeline_t *>); + case HWC2::FunctionDescriptor::SetAutoLowLatencyMode: + return ToHook<HWC2_PFN_SET_AUTO_LOW_LATENCY_MODE>( + DisplayHook<decltype(&HwcDisplay::SetAutoLowLatencyMode), + &HwcDisplay::SetAutoLowLatencyMode, bool>); + case HWC2::FunctionDescriptor::GetSupportedContentTypes: + return ToHook<HWC2_PFN_GET_SUPPORTED_CONTENT_TYPES>( + DisplayHook<decltype(&HwcDisplay::GetSupportedContentTypes), + &HwcDisplay::GetSupportedContentTypes, uint32_t *, + uint32_t *>); + case HWC2::FunctionDescriptor::SetContentType: + return ToHook<HWC2_PFN_SET_CONTENT_TYPE>( + DisplayHook<decltype(&HwcDisplay::SetContentType), + &HwcDisplay::SetContentType, int32_t>); +#endif + // Layer functions + case HWC2::FunctionDescriptor::SetCursorPosition: + return ToHook<HWC2_PFN_SET_CURSOR_POSITION>( + LayerHook<decltype(&HwcLayer::SetCursorPosition), + &HwcLayer::SetCursorPosition, int32_t, int32_t>); + case HWC2::FunctionDescriptor::SetLayerBlendMode: + return ToHook<HWC2_PFN_SET_LAYER_BLEND_MODE>( + LayerHook<decltype(&HwcLayer::SetLayerBlendMode), + &HwcLayer::SetLayerBlendMode, int32_t>); + case HWC2::FunctionDescriptor::SetLayerBuffer: + return ToHook<HWC2_PFN_SET_LAYER_BUFFER>( + LayerHook<decltype(&HwcLayer::SetLayerBuffer), + &HwcLayer::SetLayerBuffer, buffer_handle_t, int32_t>); + case HWC2::FunctionDescriptor::SetLayerColor: + return ToHook<HWC2_PFN_SET_LAYER_COLOR>( + LayerHook<decltype(&HwcLayer::SetLayerColor), + &HwcLayer::SetLayerColor, hwc_color_t>); + case HWC2::FunctionDescriptor::SetLayerCompositionType: + return ToHook<HWC2_PFN_SET_LAYER_COMPOSITION_TYPE>( + LayerHook<decltype(&HwcLayer::SetLayerCompositionType), + &HwcLayer::SetLayerCompositionType, int32_t>); + case HWC2::FunctionDescriptor::SetLayerDataspace: + return ToHook<HWC2_PFN_SET_LAYER_DATASPACE>( + LayerHook<decltype(&HwcLayer::SetLayerDataspace), + &HwcLayer::SetLayerDataspace, int32_t>); + case HWC2::FunctionDescriptor::SetLayerDisplayFrame: + return ToHook<HWC2_PFN_SET_LAYER_DISPLAY_FRAME>( + LayerHook<decltype(&HwcLayer::SetLayerDisplayFrame), + &HwcLayer::SetLayerDisplayFrame, hwc_rect_t>); + case HWC2::FunctionDescriptor::SetLayerPlaneAlpha: + return ToHook<HWC2_PFN_SET_LAYER_PLANE_ALPHA>( + LayerHook<decltype(&HwcLayer::SetLayerPlaneAlpha), + &HwcLayer::SetLayerPlaneAlpha, float>); + case HWC2::FunctionDescriptor::SetLayerSidebandStream: + return ToHook<HWC2_PFN_SET_LAYER_SIDEBAND_STREAM>( + LayerHook<decltype(&HwcLayer::SetLayerSidebandStream), + &HwcLayer::SetLayerSidebandStream, + const native_handle_t *>); + case HWC2::FunctionDescriptor::SetLayerSourceCrop: + return ToHook<HWC2_PFN_SET_LAYER_SOURCE_CROP>( + LayerHook<decltype(&HwcLayer::SetLayerSourceCrop), + &HwcLayer::SetLayerSourceCrop, hwc_frect_t>); + case HWC2::FunctionDescriptor::SetLayerSurfaceDamage: + return ToHook<HWC2_PFN_SET_LAYER_SURFACE_DAMAGE>( + LayerHook<decltype(&HwcLayer::SetLayerSurfaceDamage), + &HwcLayer::SetLayerSurfaceDamage, hwc_region_t>); + case HWC2::FunctionDescriptor::SetLayerTransform: + return ToHook<HWC2_PFN_SET_LAYER_TRANSFORM>( + LayerHook<decltype(&HwcLayer::SetLayerTransform), + &HwcLayer::SetLayerTransform, int32_t>); + case HWC2::FunctionDescriptor::SetLayerVisibleRegion: + return ToHook<HWC2_PFN_SET_LAYER_VISIBLE_REGION>( + LayerHook<decltype(&HwcLayer::SetLayerVisibleRegion), + &HwcLayer::SetLayerVisibleRegion, hwc_region_t>); + case HWC2::FunctionDescriptor::SetLayerZOrder: + return ToHook<HWC2_PFN_SET_LAYER_Z_ORDER>( + LayerHook<decltype(&HwcLayer::SetLayerZOrder), + &HwcLayer::SetLayerZOrder, uint32_t>); + case HWC2::FunctionDescriptor::Invalid: + default: + return nullptr; + } +} + +static int HookDevOpen(const struct hw_module_t *module, const char *name, + struct hw_device_t **dev) { + if (strcmp(name, HWC_HARDWARE_COMPOSER) != 0) { + ALOGE("Invalid module name- %s", name); + return -EINVAL; + } + + auto ctx = std::make_unique<Drmhwc2Device>(); + if (!ctx) { + ALOGE("Failed to allocate DrmHwcTwo"); + return -ENOMEM; + } + + ctx->common.tag = HARDWARE_DEVICE_TAG; + ctx->common.version = HWC_DEVICE_API_VERSION_2_0; + ctx->common.close = HookDevClose; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) + ctx->common.module = (hw_module_t *)module; + ctx->getCapabilities = HookDevGetCapabilities; + ctx->getFunction = HookDevGetFunction; + + *dev = &ctx.release()->common; + + return 0; +} + +} // namespace android + +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +static struct hw_module_methods_t hwc2_module_methods = { + .open = android::HookDevOpen, +}; + +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +hw_module_t HAL_MODULE_INFO_SYM = { + .tag = HARDWARE_MODULE_TAG, + .module_api_version = HARDWARE_MODULE_API_VERSION(2, 0), + .id = HWC_HARDWARE_MODULE_ID, + .name = "DrmHwcTwo module", + .author = "The Android Open Source Project", + .methods = &hwc2_module_methods, + .dso = nullptr, + .reserved = {0}, +}; diff --git a/include/DrmFramebuffer.h b/include/DrmFramebuffer.h deleted file mode 100644 index 33ca0db..0000000 --- a/include/DrmFramebuffer.h +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (C) 2015 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ANDROID_DRM_FRAMEBUFFER_ -#define ANDROID_DRM_FRAMEBUFFER_ - -#include <stdint.h> -#include <sync/sync.h> -#include <ui/GraphicBuffer.h> - -namespace android { - -struct DrmFramebuffer { - DrmFramebuffer() : release_fence_fd_(-1) { - } - - ~DrmFramebuffer() { - if (release_fence_fd() >= 0) - close(release_fence_fd()); - } - - bool is_valid() { - return buffer_ != NULL; - } - - sp<GraphicBuffer> buffer() { - return buffer_; - } - - int release_fence_fd() { - return release_fence_fd_; - } - - void set_release_fence_fd(int fd) { - if (release_fence_fd_ >= 0) - close(release_fence_fd_); - release_fence_fd_ = fd; - } - - bool Allocate(uint32_t w, uint32_t h) { - if (is_valid()) { - if (buffer_->getWidth() == w && buffer_->getHeight() == h) - return true; - - if (release_fence_fd_ >= 0) { - if (sync_wait(release_fence_fd_, kReleaseWaitTimeoutMs) != 0) { - ALOGE("Wait for release fence failed\n"); - return false; - } - } - Clear(); - } - buffer_ = new GraphicBuffer(w, h, PIXEL_FORMAT_RGB_888, - GRALLOC_USAGE_HW_FB | GRALLOC_USAGE_HW_RENDER | - GRALLOC_USAGE_HW_COMPOSER); - release_fence_fd_ = -1; - return is_valid(); - } - - void Clear() { - if (!is_valid()) - return; - - if (release_fence_fd_ >= 0) { - close(release_fence_fd_); - release_fence_fd_ = -1; - } - - buffer_.clear(); - } - - int WaitReleased(int timeout_milliseconds) { - if (!is_valid()) - return 0; - if (release_fence_fd_ < 0) - return 0; - - int ret = sync_wait(release_fence_fd_, timeout_milliseconds); - return ret; - } - - // Somewhat arbitrarily chosen, but wanted to stay below 3000ms, which is the - // system timeout - static const int kReleaseWaitTimeoutMs = 1500; - - private: - sp<GraphicBuffer> buffer_; - int release_fence_fd_; -}; -} // namespace android - -#endif // ANDROID_DRM_FRAMEBUFFER_ diff --git a/include/autofd.h b/include/autofd.h deleted file mode 100644 index 9af6c22..0000000 --- a/include/autofd.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2015 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ANDROID_AUTO_FD_H_ -#define ANDROID_AUTO_FD_H_ - -#include <unistd.h> - -namespace android { - -class UniqueFd { - public: - UniqueFd() = default; - UniqueFd(int fd) : fd_(fd) { - } - UniqueFd(UniqueFd &&rhs) { - fd_ = rhs.fd_; - rhs.fd_ = -1; - } - - UniqueFd &operator=(UniqueFd &&rhs) { - Set(rhs.Release()); - return *this; - } - - ~UniqueFd() { - if (fd_ >= 0) - close(fd_); - } - - int Release() { - int old_fd = fd_; - fd_ = -1; - return old_fd; - } - - int Set(int fd) { - if (fd_ >= 0) - close(fd_); - fd_ = fd; - return fd_; - } - - void Close() { - if (fd_ >= 0) - close(fd_); - fd_ = -1; - } - - int get() const { - return fd_; - } - - private: - int fd_ = -1; -}; - -struct OutputFd { - OutputFd() = default; - OutputFd(int *fd) : fd_(fd) { - } - OutputFd(OutputFd &&rhs) { - fd_ = rhs.fd_; - rhs.fd_ = NULL; - } - - OutputFd &operator=(OutputFd &&rhs) { - fd_ = rhs.fd_; - rhs.fd_ = NULL; - return *this; - } - - int Set(int fd) { - if (*fd_ >= 0) - close(*fd_); - *fd_ = fd; - return fd; - } - - int get() { - return *fd_; - } - - operator bool() const { - return fd_ != NULL; - } - - private: - int *fd_ = NULL; -}; -} // namespace android - -#endif diff --git a/include/drmhwcgralloc.h b/include/drmhwcgralloc.h index fc0af64..949912d 100644 --- a/include/drmhwcgralloc.h +++ b/include/drmhwcgralloc.h @@ -17,24 +17,26 @@ #ifndef ANDROID_DRMHWCGRALLOC_H_ #define ANDROID_DRMHWCGRALLOC_H_ -#include <stdint.h> +#include <cstdint> -#define HWC_DRM_BO_MAX_PLANES 4 -typedef struct hwc_drm_bo { +constexpr int kHwcDrmBoMaxPlanes = 4; + +struct HwcDrmBo { uint32_t width; uint32_t height; uint32_t format; /* DRM_FORMAT_* from drm_fourcc.h */ uint32_t hal_format; /* HAL_PIXEL_FORMAT_* */ uint32_t usage; - uint32_t pitches[HWC_DRM_BO_MAX_PLANES]; - uint32_t offsets[HWC_DRM_BO_MAX_PLANES]; - uint32_t prime_fds[HWC_DRM_BO_MAX_PLANES]; - uint32_t gem_handles[HWC_DRM_BO_MAX_PLANES]; - uint64_t modifiers[HWC_DRM_BO_MAX_PLANES]; - uint32_t fb_id; - bool with_modifiers; + uint32_t pitches[kHwcDrmBoMaxPlanes]; + uint32_t offsets[kHwcDrmBoMaxPlanes]; + /* sizes[] is used only by mapper@4 metadata getter for internal purposes */ + uint32_t sizes[kHwcDrmBoMaxPlanes]; + int prime_fds[kHwcDrmBoMaxPlanes]; + uint64_t modifiers[kHwcDrmBoMaxPlanes]; int acquire_fence_fd; - void *priv; -} hwc_drm_bo_t; +}; + +// NOLINTNEXTLINE(readability-identifier-naming) +using hwc_drm_bo_t = HwcDrmBo; #endif // ANDROID_DRMHWCGRALLOC_H_ diff --git a/include/drmhwcomposer.h b/include/drmhwcomposer.h index 0706ae5..4fb0efd 100644 --- a/include/drmhwcomposer.h +++ b/include/drmhwcomposer.h @@ -17,101 +17,35 @@ #ifndef ANDROID_DRM_HWCOMPOSER_H_ #define ANDROID_DRM_HWCOMPOSER_H_ -#include <stdbool.h> -#include <stdint.h> - -#include <vector> - #include <hardware/hardware.h> #include <hardware/hwcomposer.h> -#include "autofd.h" -#include "drmhwcgralloc.h" - -struct hwc_import_context; -int hwc_import_init(struct hwc_import_context **ctx); -int hwc_import_destroy(struct hwc_import_context *ctx); +#include <cstdbool> +#include <cstdint> +#include <vector> -int hwc_import_bo_create(int fd, struct hwc_import_context *ctx, - buffer_handle_t buf, struct hwc_drm_bo *bo); -bool hwc_import_bo_release(int fd, struct hwc_import_context *ctx, - struct hwc_drm_bo *bo); +#include "drm/DrmFbImporter.h" +#include "drmhwcgralloc.h" +#include "utils/UniqueFd.h" namespace android { -class Importer; - -class DrmHwcBuffer { - public: - DrmHwcBuffer() = default; - DrmHwcBuffer(const hwc_drm_bo &bo, Importer *importer) - : bo_(bo), importer_(importer) { - } - DrmHwcBuffer(DrmHwcBuffer &&rhs) : bo_(rhs.bo_), importer_(rhs.importer_) { - rhs.importer_ = NULL; - } - - ~DrmHwcBuffer() { - Clear(); - } - - DrmHwcBuffer &operator=(DrmHwcBuffer &&rhs) { - Clear(); - importer_ = rhs.importer_; - rhs.importer_ = NULL; - bo_ = rhs.bo_; - return *this; - } - - operator bool() const { - return importer_ != NULL; - } - - const hwc_drm_bo *operator->() const; - - void Clear(); +class DrmFbIdHandle; - int ImportBuffer(buffer_handle_t handle, Importer *importer); - - private: - hwc_drm_bo bo_; - Importer *importer_ = NULL; +enum class DrmHwcColorSpace : int32_t { + kUndefined, + kItuRec601, + kItuRec709, + kItuRec2020, }; -class DrmHwcNativeHandle { - public: - DrmHwcNativeHandle() = default; - - DrmHwcNativeHandle(native_handle_t *handle) : handle_(handle) { - } - - DrmHwcNativeHandle(DrmHwcNativeHandle &&rhs) { - handle_ = rhs.handle_; - rhs.handle_ = NULL; - } - - ~DrmHwcNativeHandle(); - - DrmHwcNativeHandle &operator=(DrmHwcNativeHandle &&rhs) { - Clear(); - handle_ = rhs.handle_; - rhs.handle_ = NULL; - return *this; - } - - int CopyBufferHandle(buffer_handle_t handle); - - void Clear(); - - buffer_handle_t get() const { - return handle_; - } - - private: - native_handle_t *handle_ = NULL; +enum class DrmHwcSampleRange : int32_t { + kUndefined, + kFullRange, + kLimitedRange, }; -enum DrmHwcTransform { +enum DrmHwcTransform : uint32_t { kIdentity = 0, kFlipH = 1 << 0, kFlipV = 1 << 1, @@ -121,37 +55,30 @@ enum DrmHwcTransform { }; enum class DrmHwcBlending : int32_t { - kNone = HWC_BLENDING_NONE, - kPreMult = HWC_BLENDING_PREMULT, - kCoverage = HWC_BLENDING_COVERAGE, + kNone, + kPreMult, + kCoverage, }; struct DrmHwcLayer { - buffer_handle_t sf_handle = NULL; + buffer_handle_t sf_handle = nullptr; + hwc_drm_bo_t buffer_info{}; + std::shared_ptr<DrmFbIdHandle> fb_id_handle; + int gralloc_buffer_usage = 0; - DrmHwcBuffer buffer; - DrmHwcNativeHandle handle; - uint32_t transform; + DrmHwcTransform transform{}; DrmHwcBlending blending = DrmHwcBlending::kNone; - uint16_t alpha = 0xffff; + uint16_t alpha = UINT16_MAX; hwc_frect_t source_crop; hwc_rect_t display_frame; + DrmHwcColorSpace color_space; + DrmHwcSampleRange sample_range; UniqueFd acquire_fence; - OutputFd release_fence; - - int ImportBuffer(Importer *importer); - int InitFromDrmHwcLayer(DrmHwcLayer *layer, Importer *importer); - void SetTransform(int32_t sf_transform); - void SetSourceCrop(hwc_frect_t const &crop); - void SetDisplayFrame(hwc_rect_t const &frame); - - buffer_handle_t get_usable_handle() const { - return handle.get() != NULL ? handle.get() : sf_handle; - } + int ImportBuffer(DrmDevice *drm_device); - bool protected_usage() const { + bool IsProtected() const { return (gralloc_buffer_usage & GRALLOC_USAGE_PROTECTED) == GRALLOC_USAGE_PROTECTED; } diff --git a/presubmit.sh b/presubmit.sh new file mode 100755 index 0000000..a551398 --- /dev/null +++ b/presubmit.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +set -e + +echo "Run native build:" + +make -f .ci/Makefile -j12 + +echo "Run style check:" + +./.ci/.gitlab-ci-checkcommit.sh + +echo -e "\n\e[32m --- SUCCESS ---" diff --git a/tests/Android.bp b/tests/Android.bp index 6ffb364..b25342e 100644 --- a/tests/Android.bp +++ b/tests/Android.bp @@ -1,4 +1,23 @@ +cc_library_shared { + name: "hwcomposer.filegroups_build_test", + defaults: ["hwcomposer.drm_defaults"], + srcs: [ + ":drm_hwcomposer_common", + ":drm_hwcomposer_platformhisi", + ":drm_hwcomposer_platformimagination", + ":drm_hwcomposer_platformmediatek", + ":drm_hwcomposer_platformmeson", + ], + + local_include_dirs: [ + "test_include", + ], + + cppflags: [ + "-DDISABLE_LEGACY_GETTERS", + ], +} package { // See: http://go/android-license-faq @@ -19,7 +38,21 @@ cc_test { static_libs: ["libdrmhwc_utils"], shared_libs: ["hwcomposer.drm"], include_dirs: [ + "external/drm_hwcomposer", "external/drm_hwcomposer/include", + ], +} + +// Tool for listening and dumping uevents +cc_test { + name: "hwc-drm-uevent-print", + + srcs: ["uevent_print.cpp"], + + vendor: true, + header_libs: ["libhardware_headers"], + shared_libs: ["liblog"], + include_dirs: [ "external/drm_hwcomposer", ], } diff --git a/tests/test_include/gralloc_helper.h b/tests/test_include/gralloc_helper.h new file mode 100644 index 0000000..b6cd24d --- /dev/null +++ b/tests/test_include/gralloc_helper.h @@ -0,0 +1,54 @@ +// clang-format off +/* + * Copyright (C) 2010-2017 ARM Limited. All rights reserved. + * + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GRALLOC_HELPER_H_ +#define GRALLOC_HELPER_H_ + +#include <sys/mman.h> +#include <sys/user.h> +#include "utils/log.h" + +#ifndef AWAR +#define AWAR(fmt, args...) \ + __android_log_print(ANDROID_LOG_WARN, "[Gralloc-Warning]", "%s:%d " fmt, __func__, __LINE__, ##args) +#endif +#ifndef AINF +#define AINF(fmt, args...) __android_log_print(ANDROID_LOG_INFO, "[Gralloc]", fmt, ##args) +#endif +#ifndef AERR +#define AERR(fmt, args...) \ + __android_log_print(ANDROID_LOG_ERROR, "[Gralloc-ERROR]", "%s:%d " fmt, __func__, __LINE__, ##args) +#endif +#ifndef AERR_IF +#define AERR_IF(eq, fmt, args...) \ + if ((eq)) \ + AERR(fmt, args) +#endif + +#define GRALLOC_ALIGN(value, base) (((value) + ((base)-1)) & ~((base)-1)) + +#define GRALLOC_UNUSED(x) ((void)x) + +static inline size_t round_up_to_page_size(size_t x) +{ + return (x + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1); +} + +#endif /* GRALLOC_HELPER_H_ */ +// clang-format on diff --git a/tests/test_include/gralloc_priv.h b/tests/test_include/gralloc_priv.h new file mode 100644 index 0000000..e771a69 --- /dev/null +++ b/tests/test_include/gralloc_priv.h @@ -0,0 +1,69 @@ +// clang-format off +/* + * Copyright (C) 2017 ARM Limited. All rights reserved. + * + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GRALLOC_PRIV_H_ +#define GRALLOC_PRIV_H_ + +#include <stdint.h> +#include <pthread.h> +#include <errno.h> +#include <linux/fb.h> +#include <sys/types.h> +#include <unistd.h> +#include <sys/mman.h> +#include <cutils/native_handle.h> +#include "utils/log.h" + +#if GRALLOC_USE_GRALLOC1_API +#include <hardware/gralloc1.h> +#else +#include <hardware/gralloc.h> +#endif +/** + * mali_gralloc_formats.h needs the define for GRALLOC_MODULE_API_VERSION_0_3 and + * GRALLOC_MODULE_API_VERSION_1_0, so include <gralloc1.h> or <gralloc.h> before + * including mali_gralloc_formats.h + **/ +#include "mali_gralloc_formats.h" +#include "mali_gralloc_usages.h" +#include "gralloc_helper.h" + +#if defined(GRALLOC_MODULE_API_VERSION_0_3) || \ + (defined(GRALLOC_MODULE_API_VERSION_1_0) && !defined(GRALLOC_DISABLE_PRIVATE_BUFFER_DEF)) + +/* + * This header file contains the private buffer definition. For gralloc 0.3 it will + * always be exposed, but for gralloc 1.0 it will be removed at some point in the future. + * + * GRALLOC_DISABLE_PRIVATE_BUFFER_DEF is intended for DDKs to test while implementing + * the new private API. + */ +#include "mali_gralloc_buffer.h" +#endif + +#if defined(GRALLOC_MODULE_API_VERSION_1_0) + +/* gralloc 1.0 supports the new private interface that abstracts + * the private buffer definition to a set of defined APIs. + */ +#include "mali_gralloc_private_interface.h" +#endif + +#endif /* GRALLOC_PRIV_H_ */ +// clang-format on diff --git a/tests/test_include/img_gralloc1_public.h b/tests/test_include/img_gralloc1_public.h new file mode 100644 index 0000000..aef435f --- /dev/null +++ b/tests/test_include/img_gralloc1_public.h @@ -0,0 +1,253 @@ +// clang-format off +/* Copyright (c) Imagination Technologies Ltd. + * + * The contents of this file are subject to the MIT license as set out below. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef HAL_PUBLIC_H +#define HAL_PUBLIC_H + +/* Authors of third party hardware composer (HWC) modules will need to include + * this header to access functionality in the gralloc and framebuffer HALs. + */ + +#include <hardware/gralloc.h> +#if 0 /* Header below is not used by drm_hwcomposer */ +#include <hardware/memtrack.h> +#endif + +#define ALIGN(x,a) (((x) + (a) - 1L) & ~((a) - 1L)) +#define HW_ALIGN 16 + +/* This can be tuned down as appropriate for the SOC. + * + * IMG formats are usually a single sub-alloc. + * Some OEM video formats are two sub-allocs (Y, UV planes). + * Future OEM video formats might be three sub-allocs (Y, U, V planes). + */ +#define MAX_SUB_ALLOCS 3 + +/* Format is not YCbCr (e.g. a RGB format) - bIsYUVFormat should be false */ +#define YUV_CHROMA_ORDER_NONE 0 +/* Cb follows Y */ +#define YUV_CHROMA_ORDER_CBCR_UV 1 +/* Cr follows Y */ +#define YUV_CHROMA_ORDER_CRCB_VU 2 + +typedef struct +{ + native_handle_t base; + + /* These fields can be sent cross process. They are also valid + * to duplicate within the same process. + * + * A table is stored within psPrivateData on gralloc_module_t (this + * is obviously per-process) which maps stamps to a mapped + * PVRSRV_CLIENT_MEM_INFO in that process. Each map entry has a lock + * count associated with it, satisfying the requirements of the + * Android API. This also prevents us from leaking maps/allocations. + * + * This table has entries inserted either by alloc() + * (alloc_device_t) or map() (gralloc_module_t). Entries are removed + * by free() (alloc_device_t) and unmap() (gralloc_module_t). + * + * As a special case for framebuffer_device_t, framebuffer_open() + * will add and framebuffer_close() will remove from this table. + */ + +#define IMG_NATIVE_HANDLE_NUMFDS MAX_SUB_ALLOCS + /* The `fd' field is used to "export" a meminfo to another process. + * Therefore, it is allocated by alloc_device_t, and consumed by + * gralloc_module_t. The framebuffer_device_t does not need a handle, + * and the special value IMG_FRAMEBUFFER_FD is used instead. + */ + int fd[MAX_SUB_ALLOCS]; + +#define IMG_NATIVE_HANDLE_NUMINTS \ + ((sizeof(unsigned long long) / sizeof(int)) + 5 + MAX_SUB_ALLOCS + 1 + MAX_SUB_ALLOCS + MAX_SUB_ALLOCS) + /* A KERNEL unique identifier for any exported kernel meminfo. Each + * exported kernel meminfo will have a unique stamp, but note that in + * userspace, several meminfos across multiple processes could have + * the same stamp. As the native_handle can be dup(2)'d, there could be + * multiple handles with the same stamp but different file descriptors. + */ + unsigned long long ui64Stamp; + + /* This is used for buffer usage validation when locking a buffer, + * and also in WSEGL (for the composition bypass feature). + */ + int usage; + + /* In order to do efficient cache flushes we need the buffer dimensions + * and format. These are available on the ANativeWindowBuffer, + * but the platform doesn't pass them down to the graphics HAL. + */ + int iWidth; + int iHeight; + int iFormat; + unsigned int uiBpp; + + /* The ion allocation path doesn't allow for the allocation size and + * mapping flags to be communicated cross-process automatically. + * Cache these here so we can map buffers in client processes. + */ + unsigned int uiAllocSize[MAX_SUB_ALLOCS]; + unsigned int uiFlags; + /* For multi-planar allocations, there will be multiple hstrides */ + int aiStride[MAX_SUB_ALLOCS]; + + /* For multi-planar allocations, there will be multiple vstrides */ + int aiVStride[MAX_SUB_ALLOCS]; + +} +__attribute__((aligned(sizeof(int)),packed)) IMG_native_handle_t; + +typedef struct +{ + int l, t, w, h; +} +IMG_write_lock_rect_t; + +typedef int (*IMG_buffer_format_compute_params_pfn)( + unsigned int uiPlane, int *piWidth, int *piHeight, + int *piStride, int *piVStride, unsigned long *pulPlaneOffset); + +typedef struct IMG_buffer_format_public_t +{ + /* Buffer formats are returned as a linked list */ + struct IMG_buffer_format_public_t *psNext; + + /* HAL_PIXEL_FORMAT_... enumerant */ + int iHalPixelFormat; + + /* WSEGL_PIXELFORMAT_... enumerant */ + int iWSEGLPixelFormat; + + /* Friendly name for format */ + const char *const szName; + + /* Bits (not bytes) per pixel */ + unsigned int uiBpp; + + /* Supported HW usage bits. If this is GRALLOC_USAGE_HW_MASK, all usages + * are supported. Used for HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED. + */ + int iSupportedUsage; + + /* YUV output format */ + int bIsYUVFormat; + + /* YCBCR_ORDERING_* defined the order of the Cb/Cr values */ + int eYUVChromaOrder; + + /* Utility function for adjusting YUV per-plane parameters */ + IMG_buffer_format_compute_params_pfn pfnComputeParams; +} +IMG_buffer_format_public_t; + +#if 0 /* Not used by drm_hwcomposer but require additional dependencies */ + +typedef struct +{ + /* Base memtrack record, copied to caller */ + struct memtrack_record base; + + /* Record type, for filtering cached records */ + enum memtrack_type eType; + + /* Process ID, for filtering cached records */ + pid_t pid; +} +IMG_memtrack_record_public_t; + +typedef struct IMG_gralloc_module_public_t +{ + gralloc_module_t base; + + /* This function is deprecated and might be NULL. Do not use it. */ + int (*GetPhyAddrs)(gralloc_module_t const* module, + buffer_handle_t handle, void **ppvPhyAddr); + + /* Obtain HAL's registered format list */ + const IMG_buffer_format_public_t *(*GetBufferFormats)(void); + + int (*GetImplementationFormat) (struct IMG_gralloc_module_public_t const *psGrallocModule, int usage); + + int (*GetMemTrackRecords)(struct IMG_gralloc_module_public_t const *module, + IMG_memtrack_record_public_t **ppsRecords, + size_t *puNumRecords); + + /* Custom-blit components in lieu of overlay hardware */ + int (*Blit)(struct IMG_gralloc_module_public_t const *module, + buffer_handle_t src, + void *dest[MAX_SUB_ALLOCS], int format); + + int (*Blit2)(struct IMG_gralloc_module_public_t const *module, + buffer_handle_t src, buffer_handle_t dest, + int w, int h, int x, int y); + + int (*Blit3)(struct IMG_gralloc_module_public_t const *module, + unsigned long long ui64SrcStamp, int iSrcWidth, + int iSrcHeight, int iSrcFormat, int eSrcRotation, + buffer_handle_t dest, int eDestRotation); +} +IMG_gralloc_module_public_t; + +#endif + +/** + * pixel format definitions + */ + +enum { + /* + * 0x100 = 0x1FF + * + * This range is reserved for pixel formats that are specific to the HAL + * implementation. Implementations can use any value in this range to + * communicate video pixel formats between their HAL modules. These + * formats must not have an alpha channel. Additionally, an EGLimage + * created from a gralloc buffer of one of these formats must be + * supported for use with the GL_OES_EGL_image_external OpenGL ES + * extension. + */ + + /* + * These are vendor specific pixel format, by (informal) convention + * IMGTec formats start from the top of the range, TI formats start from + * the bottom + */ + HAL_PIXEL_FORMAT_TI_NV12 = 0x100, + HAL_PIXEL_FORMAT_TI_UNUSED = 0x101, + HAL_PIXEL_FORMAT_TI_NV12_1D = 0x102, + HAL_PIXEL_FORMAT_TI_Y8 = 0x103, + HAL_PIXEL_FORMAT_TI_Y16 = 0x104, + HAL_PIXEL_FORMAT_TI_UYVY = 0x105, + HAL_PIXEL_FORMAT_BGRX_8888 = 0x1FF, + + /* generic format missing from Android list, not specific to vendor + * implementation + */ + HAL_PIXEL_FORMAT_NV12 = 0x3231564E, // FourCC for NV12 +}; + +#endif /* HAL_PUBLIC_H */ +// clang-format on diff --git a/tests/test_include/mali_gralloc_buffer.h b/tests/test_include/mali_gralloc_buffer.h new file mode 100644 index 0000000..83f77c2 --- /dev/null +++ b/tests/test_include/mali_gralloc_buffer.h @@ -0,0 +1,271 @@ +// clang-format off +/* + * Copyright (C) 2017 ARM Limited. All rights reserved. + * + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef MALI_GRALLOC_BUFFER_H_ +#define MALI_GRALLOC_BUFFER_H_ + +#include <errno.h> +#include <sys/types.h> +#include <unistd.h> +#include <sys/mman.h> + +#include "mali_gralloc_private_interface_types.h" + +/* NOTE: + * If your framebuffer device driver is integrated with dma_buf, you will have to + * change this IOCTL definition to reflect your integration with the framebuffer + * device. + * Expected return value is a structure filled with a file descriptor + * backing your framebuffer device memory. + */ +struct fb_dmabuf_export +{ + __u32 fd; + __u32 flags; +}; +#define FBIOGET_DMABUF _IOR('F', 0x21, struct fb_dmabuf_export) + +/* the max string size of GRALLOC_HARDWARE_GPU0 & GRALLOC_HARDWARE_FB0 + * 8 is big enough for "gpu0" & "fb0" currently + */ +#define MALI_GRALLOC_HARDWARE_MAX_STR_LEN 8 +#define NUM_FB_BUFFERS 2 + +/* Define number of shared file descriptors */ +#define GRALLOC_ARM_NUM_FDS 2 + +#define NUM_INTS_IN_PRIVATE_HANDLE ((sizeof(struct private_handle_t) - sizeof(native_handle)) / sizeof(int) - sNumFds) + +#define SZ_4K 0x00001000 +#define SZ_2M 0x00200000 + +struct private_handle_t; + +#ifndef __cplusplus +/* C99 with pedantic don't allow anonymous unions which is used in below struct + * Disable pedantic for C for this struct only. + */ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpedantic" +#endif + +#ifdef __cplusplus +struct private_handle_t : public native_handle +{ +#else +struct private_handle_t +{ + struct native_handle nativeHandle; +#endif + +#ifdef __cplusplus + /* Never intended to be used from C code */ + enum + { + PRIV_FLAGS_FRAMEBUFFER = 0x00000001, + PRIV_FLAGS_USES_ION_COMPOUND_HEAP = 0x00000002, + PRIV_FLAGS_USES_ION = 0x00000004, + PRIV_FLAGS_USES_ION_DMA_HEAP = 0x00000008 + }; + + enum + { + LOCK_STATE_WRITE = 1 << 31, + LOCK_STATE_MAPPED = 1 << 30, + LOCK_STATE_READ_MASK = 0x3FFFFFFF + }; +#endif + + /* + * Shared file descriptor for dma_buf sharing. This must be the first element in the + * structure so that binder knows where it is and can properly share it between + * processes. + * DO NOT MOVE THIS ELEMENT! + */ + int share_fd; + int share_attr_fd; + + // ints + int magic; + int req_format; + uint64_t internal_format; + int byte_stride; + int flags; + int size; + int width; + int height; + int internalWidth; + int internalHeight; + int stride; + union + { + void *base; + uint64_t padding; + }; + union { + uint64_t consumer_usage; + uint64_t usage; + }; + uint64_t producer_usage; + uint64_t backing_store_id; + int backing_store_size; + int writeOwner; + int allocating_pid; + int remote_pid; + int ref_count; + // locally mapped shared attribute area + union + { + void *attr_base; + uint64_t padding3; + }; + + mali_gralloc_yuv_info yuv_info; + + // Following members is for framebuffer only + int fd; + union + { + off_t offset; + uint64_t padding4; + }; + + /* + * min_pgsz denotes minimum phys_page size used by this buffer. + * if buffer memory is physical contiguous set min_pgsz to buff->size + * if not sure buff's real phys_page size, you can use SZ_4K for safe. + */ + int min_pgsz; +#ifdef __cplusplus + /* + * We track the number of integers in the structure. There are 16 unconditional + * integers (magic - pid, yuv_info, fd and offset). Note that the fd element is + * considered an int not an fd because it is not intended to be used outside the + * surface flinger process. The GRALLOC_ARM_NUM_INTS variable is used to track the + * number of integers that are conditionally included. Similar considerations apply + * to the number of fds. + */ + static const int sNumFds = GRALLOC_ARM_NUM_FDS; + static const int sMagic = 0x3141592; + + private_handle_t(int _flags, int _size, void *_base, uint64_t _consumer_usage, uint64_t _producer_usage, + int fb_file, off_t fb_offset) + : share_fd(-1) + , share_attr_fd(-1) + , magic(sMagic) + , flags(_flags) + , size(_size) + , width(0) + , height(0) + , stride(0) + , base(_base) + , consumer_usage(_consumer_usage) + , producer_usage(_producer_usage) + , backing_store_id(0x0) + , backing_store_size(0) + , writeOwner(0) + , allocating_pid(getpid()) + , remote_pid(-1) + , ref_count(1) + , attr_base(MAP_FAILED) + , yuv_info(MALI_YUV_NO_INFO) + , fd(fb_file) + , offset(fb_offset) + { + version = sizeof(native_handle); + numFds = sNumFds; + numInts = NUM_INTS_IN_PRIVATE_HANDLE; + } + + private_handle_t(int _flags, int _size, int _min_pgsz, uint64_t _consumer_usage, uint64_t _producer_usage, + int _shared_fd, int _req_format, uint64_t _internal_format, int _byte_stride, int _width, + int _height, int _stride, int _internalWidth, int _internalHeight, int _backing_store_size) + : share_fd(_shared_fd) + , share_attr_fd(-1) + , magic(sMagic) + , req_format(_req_format) + , internal_format(_internal_format) + , byte_stride(_byte_stride) + , flags(_flags) + , size(_size) + , width(_width) + , height(_height) + , internalWidth(_internalWidth) + , internalHeight(_internalHeight) + , stride(_stride) + , base(NULL) + , consumer_usage(_consumer_usage) + , producer_usage(_producer_usage) + , backing_store_id(0x0) + , backing_store_size(_backing_store_size) + , writeOwner(0) + , allocating_pid(getpid()) + , remote_pid(-1) + , ref_count(1) + , attr_base(MAP_FAILED) + , yuv_info(MALI_YUV_NO_INFO) + , fd(-1) + , offset(0) + , min_pgsz(_min_pgsz) + { + version = sizeof(native_handle); + numFds = sNumFds; + numInts = NUM_INTS_IN_PRIVATE_HANDLE; + } + + ~private_handle_t() + { + magic = 0; + } + + bool usesPhysicallyContiguousMemory() + { + return (flags & PRIV_FLAGS_FRAMEBUFFER) ? true : false; + } + + static int validate(const native_handle *h) + { + const private_handle_t *hnd = (const private_handle_t *)h; + + if (!h || h->version != sizeof(native_handle) || h->numInts != NUM_INTS_IN_PRIVATE_HANDLE || + h->numFds != sNumFds || hnd->magic != sMagic) + { + return -EINVAL; + } + + return 0; + } + + static private_handle_t *dynamicCast(const native_handle *in) + { + if (validate(in) == 0) + { + return (private_handle_t *)in; + } + + return NULL; + } +#endif +}; +#ifndef __cplusplus +/* Restore previous diagnostic for pedantic */ +#pragma GCC diagnostic pop +#endif + +#endif /* MALI_GRALLOC_BUFFER_H_ */ +// clang-format on diff --git a/tests/test_include/mali_gralloc_formats.h b/tests/test_include/mali_gralloc_formats.h new file mode 100644 index 0000000..e62ce5e --- /dev/null +++ b/tests/test_include/mali_gralloc_formats.h @@ -0,0 +1,270 @@ +// clang-format off +/* + * Copyright (C) 2016-2017 ARM Limited. All rights reserved. + * + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MALI_GRALLOC_FORMATS_H_ +#define MALI_GRALLOC_FORMATS_H_ + +#include <system/graphics.h> + +/* Internal formats are represented in gralloc as a 64bit identifier + * where the 32 lower bits are a base format and the 32 upper bits are modifiers. + * + * Modifier bits are divided into mutually exclusive ones and those that are not. + */ +/* Internal format type */ +typedef uint64_t mali_gralloc_internal_format; + +/* Internal format masks */ +#define MALI_GRALLOC_INTFMT_FMT_MASK 0x00000000ffffffffULL +#define MALI_GRALLOC_INTFMT_EXT_MASK 0xffffffff00000000ULL +#define MALI_GRALLOC_INTFMT_ME_EXT_MASK 0x0000ffff00000000ULL +#define MALI_GRALLOC_INTFMT_REG_EXT_MASK 0xffff000000000000ULL + +/* Internal base formats */ + +/* Base formats that do not have an identical HAL match + * are defined starting at the Android private range + */ +#define MALI_GRALLOC_FORMAT_INTERNAL_RANGE_BASE 0x100 + +typedef enum +{ + MALI_GRALLOC_FORMAT_TYPE_USAGE, + MALI_GRALLOC_FORMAT_TYPE_INTERNAL, +} mali_gralloc_format_type; + +typedef enum +{ + /* Internal definitions for HAL formats. */ + MALI_GRALLOC_FORMAT_INTERNAL_RGBA_8888 = HAL_PIXEL_FORMAT_RGBA_8888, + MALI_GRALLOC_FORMAT_INTERNAL_RGBX_8888 = HAL_PIXEL_FORMAT_RGBX_8888, + MALI_GRALLOC_FORMAT_INTERNAL_RGB_888 = HAL_PIXEL_FORMAT_RGB_888, + MALI_GRALLOC_FORMAT_INTERNAL_RGB_565 = HAL_PIXEL_FORMAT_RGB_565, + MALI_GRALLOC_FORMAT_INTERNAL_BGRA_8888 = HAL_PIXEL_FORMAT_BGRA_8888, + MALI_GRALLOC_FORMAT_INTERNAL_YV12 = HAL_PIXEL_FORMAT_YV12, + MALI_GRALLOC_FORMAT_INTERNAL_Y8 = HAL_PIXEL_FORMAT_Y8, + MALI_GRALLOC_FORMAT_INTERNAL_Y16 = HAL_PIXEL_FORMAT_Y16, + MALI_GRALLOC_FORMAT_INTERNAL_YUV420_888 = HAL_PIXEL_FORMAT_YCbCr_420_888, + + /* Camera specific HAL formats */ + MALI_GRALLOC_FORMAT_INTERNAL_RAW16 = HAL_PIXEL_FORMAT_RAW16, + MALI_GRALLOC_FORMAT_INTERNAL_RAW12 = HAL_PIXEL_FORMAT_RAW12, + MALI_GRALLOC_FORMAT_INTERNAL_RAW10 = HAL_PIXEL_FORMAT_RAW10, + MALI_GRALLOC_FORMAT_INTERNAL_BLOB = HAL_PIXEL_FORMAT_BLOB, + + /* Flexible YUV formats would be parsed but not have any representation as + * internal format itself but one of the ones below + */ + + /* The internal private formats that have no HAL equivivalent are defined + * afterwards starting at a specific base range */ + MALI_GRALLOC_FORMAT_INTERNAL_NV12 = MALI_GRALLOC_FORMAT_INTERNAL_RANGE_BASE, + MALI_GRALLOC_FORMAT_INTERNAL_NV21, + MALI_GRALLOC_FORMAT_INTERNAL_YUV422_8BIT, + + /* Extended YUV formats + * + * NOTE: P010, P210, and Y410 are only supported uncompressed. + */ + MALI_GRALLOC_FORMAT_INTERNAL_Y0L2, + MALI_GRALLOC_FORMAT_INTERNAL_P010, + MALI_GRALLOC_FORMAT_INTERNAL_P210, + MALI_GRALLOC_FORMAT_INTERNAL_Y210, + MALI_GRALLOC_FORMAT_INTERNAL_Y410, + + /* Add more internal formats here. Make sure decode_internal_format() is updated. */ + + /* These are legacy 0.3 gralloc formats used only by the wrap/unwrap macros. */ + MALI_GRALLOC_FORMAT_INTERNAL_YV12_WRAP, + MALI_GRALLOC_FORMAT_INTERNAL_Y8_WRAP, + MALI_GRALLOC_FORMAT_INTERNAL_Y16_WRAP, + + MALI_GRALLOC_FORMAT_INTERNAL_RANGE_LAST, +} mali_gralloc_pixel_format; + +/* Format Modifier Bits Locations */ +#define MALI_GRALLOC_INTFMT_ME_EXTENSION_BIT_START 32 +#define MALI_GRALLOC_INTFMT_EXTENSION_BIT_START (MALI_GRALLOC_INTFMT_ME_EXTENSION_BIT_START + 16) + +/* Mutually Exclusive Modifier Bits */ + +/* This format will use AFBC */ +#define MALI_GRALLOC_INTFMT_AFBC_BASIC (1ULL << (MALI_GRALLOC_INTFMT_ME_EXTENSION_BIT_START + 0)) + +/* This format uses AFBC split block mode */ +#define MALI_GRALLOC_INTFMT_AFBC_SPLITBLK (1ULL << (MALI_GRALLOC_INTFMT_ME_EXTENSION_BIT_START + 1)) + +#define MALI_GRALLOC_INTFMT_UNUSED (1ULL << (MALI_GRALLOC_INTFMT_ME_EXTENSION_BIT_START + 2)) + +/* This format uses AFBC wide block mode */ +#define MALI_GRALLOC_INTFMT_AFBC_WIDEBLK (1ULL << (MALI_GRALLOC_INTFMT_ME_EXTENSION_BIT_START + 3)) + +/* Regular Modifier Bits */ +#define MALI_GRALLOC_INTFMT_AFBC_TILED_HEADERS (1ULL << (MALI_GRALLOC_INTFMT_EXTENSION_BIT_START + 0)) + +/* This mask should be used to check or clear support for AFBC for an internal format + * These bits are mutually exclusive so this mask should not be used to enable support + */ +#define MALI_GRALLOC_INTFMT_AFBCENABLE_MASK \ + ((uint64_t)(MALI_GRALLOC_INTFMT_AFBC_BASIC | MALI_GRALLOC_INTFMT_AFBC_SPLITBLK | MALI_GRALLOC_INTFMT_AFBC_WIDEBLK)) + +/* These are legacy Gralloc 0.3 support macros for passing private formats through the 0.3 alloc interface. + * It packs modifier bits together with base format into a 32 bit format identifier. + * Gralloc 1.0 interface should use private functions to set private buffer format in the buffer descriptor. + * + * Packing: + * + * Bits 15-0: mali_gralloc_pixel_format format + * Bits 23-16: mutually exclusive modifier bits + * Bits 31-24: regular modifier bits + */ +static inline int mali_gralloc_format_wrapper(int format, int modifiers) +{ + /* Internal formats that are identical to HAL formats + * have the same definition. This is convenient for + * client parsing code to not have to parse them separately. + * + * For 3 of the HAL YUV formats that have very large definitions + * this causes problems for packing in modifier bits. + * Because of this reason we redefine these three formats + * while packing/unpacking them. + */ + if (format == MALI_GRALLOC_FORMAT_INTERNAL_YV12) + { + format = MALI_GRALLOC_FORMAT_INTERNAL_YV12_WRAP; + } + else if (format == MALI_GRALLOC_FORMAT_INTERNAL_Y8) + { + format = MALI_GRALLOC_FORMAT_INTERNAL_Y8_WRAP; + } + else if (format == MALI_GRALLOC_FORMAT_INTERNAL_Y16) + { + format = MALI_GRALLOC_FORMAT_INTERNAL_Y16_WRAP; + } + + return (modifiers | format); +} + +static inline uint64_t mali_gralloc_format_unwrap(int x) +{ + uint64_t internal_format = (uint64_t)(((((uint64_t)(x)) & 0xff000000) << 24) | // Regular modifier bits + ((((uint64_t)(x)) & 0x00ff0000) << 16) | // Mutually exclusive modifier bits + (((uint64_t)(x)) & 0x0000ffff)); // Private format + + uint64_t base_format = internal_format & MALI_GRALLOC_INTFMT_FMT_MASK; + uint64_t modifiers = internal_format & MALI_GRALLOC_INTFMT_EXT_MASK; + + if (base_format == MALI_GRALLOC_FORMAT_INTERNAL_YV12_WRAP) + { + base_format = MALI_GRALLOC_FORMAT_INTERNAL_YV12; + } + else if (base_format == MALI_GRALLOC_FORMAT_INTERNAL_Y8_WRAP) + { + base_format = MALI_GRALLOC_FORMAT_INTERNAL_Y8; + } + else if (base_format == MALI_GRALLOC_FORMAT_INTERNAL_Y16_WRAP) + { + base_format = MALI_GRALLOC_FORMAT_INTERNAL_Y16; + } + + return (modifiers | base_format); +} + +#define GRALLOC_PRIVATE_FORMAT_WRAPPER(x) (mali_gralloc_format_wrapper(x, 0)) +#define GRALLOC_PRIVATE_FORMAT_WRAPPER_AFBC(x) (mali_gralloc_format_wrapper(x, (MALI_GRALLOC_INTFMT_AFBC_BASIC >> 16))) +#define GRALLOC_PRIVATE_FORMAT_WRAPPER_AFBC_SPLITBLK(x) \ + (mali_gralloc_format_wrapper(x, (MALI_GRALLOC_INTFMT_AFBC_SPLITBLK >> 16))) +#define GRALLOC_PRIVATE_FORMAT_WRAPPER_AFBC_WIDEBLK(x) \ + (mali_gralloc_format_wrapper(x, (MALI_GRALLOC_INTFMT_AFBC_WIDEBLK >> 16))) +#define GRALLOC_PRIVATE_FORMAT_WRAPPER_AFBC_TILED_HEADERS_BASIC(x) \ + (mali_gralloc_format_wrapper(x, (MALI_GRALLOC_INTFMT_AFBC_TILED_HEADERS >> 24) | \ + (MALI_GRALLOC_INTFMT_AFBC_BASIC >> 16))) +#define GRALLOC_PRIVATE_FORMAT_WRAPPER_AFBC_TILED_HEADERS_WIDE(x) \ + (mali_gralloc_format_wrapper(x, (MALI_GRALLOC_INTFMT_AFBC_TILED_HEADERS >> 24) | \ + (MALI_GRALLOC_INTFMT_AFBC_WIDEBLK >> 16))) +#define GRALLOC_PRIVATE_FORMAT_UNWRAP(x) mali_gralloc_format_unwrap(x) + +/* IP block capability masks */ +#define MALI_GRALLOC_FORMAT_CAPABILITY_OPTIONS_PRESENT ((uint64_t)(1 << 0)) +#define MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_BASIC ((uint64_t)(1 << 1)) +#define MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_SPLITBLK ((uint64_t)(1 << 2)) +#define MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_WIDEBLK ((uint64_t)(1 << 3)) +#define MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_WIDEBLK_YUV_DISABLE ((uint64_t)(1 << 4)) +#define MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_YUV_NOREAD ((uint64_t)(1 << 5)) +#define MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_YUV_NOWRITE ((uint64_t)(1 << 6)) +#define MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_TILED_HEADERS ((uint64_t)(1 << 7)) + +#define MALI_GRALLOC_FORMAT_CAPABILITY_AFBCENABLE_MASK \ + ((uint64_t)(MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_BASIC | MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_SPLITBLK | \ + MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_WIDEBLK | MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_TILED_HEADERS)) + +struct mali_gralloc_format_caps +{ + uint64_t caps_mask; +}; +typedef struct mali_gralloc_format_caps mali_gralloc_format_caps; + +#define MALI_GRALLOC_FORMATCAPS_SYM_NAME mali_gralloc_format_capabilities +#define MALI_GRALLOC_FORMATCAPS_SYM_NAME_STR "mali_gralloc_format_capabilities" + +/* Producer and Consumer definitions */ +typedef enum +{ + MALI_GRALLOC_PRODUCER_VIDEO_DECODER, + MALI_GRALLOC_PRODUCER_GPU, + MALI_GRALLOC_PRODUCER_CAMERA, +} mali_gralloc_producer_type; + +typedef enum +{ + + /* For surface composition in SurfaceFlinger a producer + * will not know what consumer will process a buffer. + * + * MALI_GRALLOC_CONSUMER_GPU_OR_DISPLAY means the GPU + * MUST support the given format but it should be allocated + * with preference to the DPU. + */ + MALI_GRALLOC_CONSUMER_GPU_OR_DISPLAY, + MALI_GRALLOC_CONSUMER_VIDEO_ENCODER, + + /* This is used when no known "premium" dpu is configured. + * For example, HDLCD/CLCD would be such a dpu. + */ + MALI_GRALLOC_CONSUMER_GPU_EXCL, +} mali_gralloc_consumer_type; + +/* Internal prototypes */ +#if defined(GRALLOC_LIBRARY_BUILD) +uint64_t mali_gralloc_select_format(uint64_t req_format, mali_gralloc_format_type type, uint64_t usage, + int buffer_size); +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +void mali_gralloc_get_gpu_caps(struct mali_gralloc_format_caps *gpu_caps); + +#ifdef __cplusplus +} +#endif + +#endif /* MALI_GRALLOC_FORMATS_H_ */ +// clang-format on diff --git a/tests/test_include/mali_gralloc_private_interface_types.h b/tests/test_include/mali_gralloc_private_interface_types.h new file mode 100644 index 0000000..26b7744 --- /dev/null +++ b/tests/test_include/mali_gralloc_private_interface_types.h @@ -0,0 +1,88 @@ +// clang-format off +/* + * Copyright (C) 2017 ARM Limited. All rights reserved. + * + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MALI_GRALLOC_PRIVATE_INTERFACE_TYPES_H_ +#define MALI_GRALLOC_PRIVATE_INTERFACE_TYPES_H_ + +#define GRALLOC_ARM_BUFFER_ATTR_HDR_INFO_SUPPORT + +typedef enum +{ + MALI_HDR_NO_INFO, + MALI_HDR_ST2084, + MALI_HDR_HLG, + MALI_HDR_LAST +} mali_transfer_function; + +typedef struct +{ + //values are in units of 0.00002 + uint16_t x; + uint16_t y; +} primaries; + +typedef struct +{ + primaries r; + primaries g; + primaries b; + primaries w; + uint16_t minDisplayLuminance; // in cd/m^2 + uint16_t maxDisplayLuminance; // in 0.0001 cd/m^2 + uint16_t maxContentLightLevel; // in cd/m^2 + uint16_t maxFrameAverageLightLevel; // in cd/m^2 + mali_transfer_function eotf; +} mali_hdr_info; + +enum +{ + /* CROP_RECT and YUV_TRANS are intended to be + * written by producers and read by consumers. + * A producer should write these parameters before + * it queues a buffer to the consumer. + */ + + /* CROP RECT, defined as an int array of top, left, height, width. Origin in top-left corner */ + GRALLOC_ARM_BUFFER_ATTR_CROP_RECT = 1, + + /* Set if the AFBC format used a YUV transform before compressing */ + GRALLOC_ARM_BUFFER_ATTR_AFBC_YUV_TRANS = 2, + + /* Set if the AFBC format uses sparse allocation */ + GRALLOC_ARM_BUFFER_ATTR_AFBC_SPARSE_ALLOC = 3, + + /* HDR Informations*/ + GRALLOC_ARM_BUFFER_ATTR_HDR_INFO = 4, + + GRALLOC_ARM_BUFFER_ATTR_LAST +}; + +typedef uint32_t buf_attr; + +typedef enum +{ + MALI_YUV_NO_INFO, + MALI_YUV_BT601_NARROW, + MALI_YUV_BT601_WIDE, + MALI_YUV_BT709_NARROW, + MALI_YUV_BT709_WIDE +} mali_gralloc_yuv_info; + +#endif /* MALI_GRALLOC_PRIVATE_INTERFACE_TYPES_H_ */ +// clang-format on diff --git a/tests/test_include/mali_gralloc_usages.h b/tests/test_include/mali_gralloc_usages.h new file mode 100644 index 0000000..55de5a0 --- /dev/null +++ b/tests/test_include/mali_gralloc_usages.h @@ -0,0 +1,94 @@ +// clang-format off +/* + * (C) COPYRIGHT 2017 ARM Limited. All rights reserved. + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MALI_GRALLOC_USAGES_H_ +#define MALI_GRALLOC_USAGES_H_ + +/* + * Below usage types overlap, this is intentional. + * The reason is that for Gralloc 0.3 there are very + * few usage flags we have at our disposal. + * + * The overlapping is handled by processing the definitions + * in a specific order. + * + * MALI_GRALLOC_USAGE_PRIVATE_FORMAT and MALI_GRALLOC_USAGE_NO_AFBC + * don't overlap and are processed first. + * + * MALI_GRALLOC_USAGE_YUV_CONF are only for YUV formats and clients + * using MALI_GRALLOC_USAGE_NO_AFBC must never allocate YUV formats. + * The latter is strictly enforced and allocations will fail. + * + * MALI_GRALLOC_USAGE_AFBC_PADDING is only valid if MALI_GRALLOC_USAGE_NO_AFBC + * is not present. + */ + +/* + * Gralloc private usage 0-3 are the same in 0.3 and 1.0. + * We defined based our usages based on what is available. + */ +#if defined(GRALLOC_MODULE_API_VERSION_1_0) +typedef enum +{ + /* The client has specified a private format in the format parameter */ + MALI_GRALLOC_USAGE_PRIVATE_FORMAT = (int)GRALLOC1_PRODUCER_USAGE_PRIVATE_3, + + /* Buffer won't be allocated as AFBC */ + MALI_GRALLOC_USAGE_NO_AFBC = (int)(GRALLOC1_PRODUCER_USAGE_PRIVATE_1 | GRALLOC1_PRODUCER_USAGE_PRIVATE_2), + + /* Valid only for YUV allocations */ + MALI_GRALLOC_USAGE_YUV_CONF_0 = 0, + MALI_GRALLOC_USAGE_YUV_CONF_1 = (int)GRALLOC1_PRODUCER_USAGE_PRIVATE_1, + MALI_GRALLOC_USAGE_YUV_CONF_2 = (int)GRALLOC1_PRODUCER_USAGE_PRIVATE_0, + MALI_GRALLOC_USAGE_YUV_CONF_3 = (int)(GRALLOC1_PRODUCER_USAGE_PRIVATE_0 | GRALLOC1_PRODUCER_USAGE_PRIVATE_1), + MALI_GRALLOC_USAGE_YUV_CONF_MASK = MALI_GRALLOC_USAGE_YUV_CONF_3, + + /* A very specific alignment is requested on some buffers */ + MALI_GRALLOC_USAGE_AFBC_PADDING = (int)GRALLOC1_PRODUCER_USAGE_PRIVATE_2, + +} mali_gralloc_usage_type; +#elif defined(GRALLOC_MODULE_API_VERSION_0_3) +typedef enum +{ + /* The client has specified a private format in the format parameter */ + MALI_GRALLOC_USAGE_PRIVATE_FORMAT = (int)GRALLOC_USAGE_PRIVATE_3, + + /* Buffer won't be allocated as AFBC */ + MALI_GRALLOC_USAGE_NO_AFBC = (int)(GRALLOC_USAGE_PRIVATE_1 | GRALLOC_USAGE_PRIVATE_2), + + /* Valid only for YUV allocations */ + MALI_GRALLOC_USAGE_YUV_CONF_0 = 0, + MALI_GRALLOC_USAGE_YUV_CONF_1 = (int)GRALLOC_USAGE_PRIVATE_1, + MALI_GRALLOC_USAGE_YUV_CONF_2 = (int)GRALLOC_USAGE_PRIVATE_0, + MALI_GRALLOC_USAGE_YUV_CONF_3 = (int)(GRALLOC_USAGE_PRIVATE_0 | GRALLOC_USAGE_PRIVATE_1), + MALI_GRALLOC_USAGE_YUV_CONF_MASK = MALI_GRALLOC_USAGE_YUV_CONF_3, + + /* A very specific alignment is requested on some buffers */ + MALI_GRALLOC_USAGE_AFBC_PADDING = GRALLOC_USAGE_PRIVATE_2, + +} mali_gralloc_usage_type; +#else +#if defined(GRALLOC_LIBRARY_BUILD) +#error "Please include mali_gralloc_module.h before including other gralloc headers when building gralloc itself" +#else +#error "Please include either gralloc.h or gralloc1.h header before including gralloc_priv.h" +#endif +#endif + +#endif /*MALI_GRALLOC_USAGES_H_*/ +// clang-format on diff --git a/tests/uevent_print.cpp b/tests/uevent_print.cpp new file mode 100644 index 0000000..6ffbbfb --- /dev/null +++ b/tests/uevent_print.cpp @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include <iostream> + +#include "utils/UEvent.h" + +int main() { + auto uevent = android::UEvent::CreateInstance(); + if (!uevent) { + std::cout << "Can't initialize UEvent class" << std::endl; + return -ENODEV; + } + + int number = 0; + for (;;) { + auto msg = uevent->ReadNext(); + if (!msg) { + continue; + } + + std::cout << "New event #" << number++ << std::endl + << *msg << std::endl + << std::endl; + } +} diff --git a/tests/worker_test.cpp b/tests/worker_test.cpp index cb6275e..d1eb2b3 100644 --- a/tests/worker_test.cpp +++ b/tests/worker_test.cpp @@ -8,17 +8,13 @@ using android::Worker; struct TestWorker : public Worker { - TestWorker() - : Worker("test-worker", HAL_PRIORITY_URGENT_DISPLAY), - value(0), - enabled_(false) { - } + TestWorker() : Worker("test-worker", HAL_PRIORITY_URGENT_DISPLAY){}; int Init() { return InitWorker(); } - void Routine() { + void Routine() override { Lock(); if (!enabled_) { int ret = WaitForSignalOrExitLocked(); @@ -47,16 +43,17 @@ struct TestWorker : public Worker { Signal(); } - int value; + // NOLINTNEXTLINE: should not be public + int value{}; private: - bool enabled_; + bool enabled_{}; }; struct WorkerTest : public testing::Test { TestWorker worker; - virtual void SetUp() { + void SetUp() override { worker.Init(); } @@ -65,7 +62,8 @@ struct WorkerTest : public testing::Test { } }; -TEST_F(WorkerTest, test_worker) { +// NOLINTNEXTLINE: required by gtest macros +TEST_F(WorkerTest, TestWorker) { // already isInitialized so should succeed ASSERT_TRUE(worker.initialized()); @@ -102,7 +100,8 @@ TEST_F(WorkerTest, test_worker) { ASSERT_FALSE(worker.initialized()); } -TEST_F(WorkerTest, exit_while_running) { +// NOLINTNEXTLINE: required by gtest macros +TEST_F(WorkerTest, ExitWhileRunning) { worker.Control(true); std::this_thread::sleep_for(std::chrono::milliseconds(50)); diff --git a/utils/UEvent.h b/utils/UEvent.h new file mode 100644 index 0000000..17b3cab --- /dev/null +++ b/utils/UEvent.h @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include <linux/netlink.h> +#include <sys/socket.h> + +#include <cerrno> +#include <memory> +#include <optional> +#include <string> + +#include "UniqueFd.h" +#include "log.h" + +namespace android { + +class UEvent { + public: + static auto CreateInstance() -> std::unique_ptr<UEvent> { + auto fd = UniqueFd( + socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT)); + + if (!fd) { + ALOGE("Failed to open uevent socket: errno=%i", errno); + return {}; + } + + struct sockaddr_nl addr {}; + addr.nl_family = AF_NETLINK; + addr.nl_pid = 0; + addr.nl_groups = UINT32_MAX; + + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) + int ret = bind(fd.Get(), (struct sockaddr *)&addr, sizeof(addr)); + if (ret != 0) { + ALOGE("Failed to bind uevent socket: errno=%i", errno); + return {}; + } + + return std::unique_ptr<UEvent>(new UEvent(fd)); + } + + auto ReadNext() -> std::optional<std::string> { + constexpr int kUEventBufferSize = 1024; + char buffer[kUEventBufferSize]; + ssize_t ret = 0; + ret = read(fd_.Get(), &buffer, sizeof(buffer)); + if (ret == 0) + return {}; + + if (ret < 0) { + ALOGE("Got error reading uevent %zd", ret); + return {}; + } + + for (int i = 0; i < ret - 1; i++) { + if (buffer[i] == '\0') { + buffer[i] = '\n'; + } + } + + return std::string(buffer); + } + + private: + explicit UEvent(UniqueFd &fd) : fd_(std::move(fd)){}; + UniqueFd fd_; +}; + +} // namespace android diff --git a/utils/UniqueFd.h b/utils/UniqueFd.h new file mode 100644 index 0000000..1a390ba --- /dev/null +++ b/utils/UniqueFd.h @@ -0,0 +1,111 @@ +/* + * Copyright (C) 2015, 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UNIQUEFD_H_ +#define UNIQUEFD_H_ + +#include <unistd.h> + +#include <memory> + +namespace android { + +/* + * Using UniqueFd: + * 1. Create UniqueFd object: + * auto fd_obj = UniqueFd(open("SomeFile", xxx)); + * + * 2. Check whether the fd_obj is empty: + * if (!fd_obj) { return -errno; } + * + * 3. Accessing the file descriptor: + * int ret = read(fd_obj.Get(), buf, buf_size); + * + * 4. Closing the file: + * FD will be closed once execution leaves fd_obj scope (on any return, + * exception, destruction of class/struct where object is member, etc.). + * User can also force closing the fd_obj by calling: + * fd_obj = UniqueFd(); + * // fd is closed and fd_obj is empty now. + * + * 5. File descriptor may be transferred to the code, which will close it after + * using. This can be done in 2 ways: + * a. Duplicate the fd, in this case both fds should be closed separately: + * int out_fd = dup(fd_obj.Get(); + * ... + * close(out_fd); + * b. Transfer ownership, use this method if you do not need the fd anymore. + * int out_fd = fd_obj.Release(); + * // fd_obj is empty now. + * ... + * close(out_fd); + * + * 6. Transferring fd into another UniqueFD object: + * UniqueFd fd_obj_2 = std::move(fd_obj); + * // fd_obj empty now + */ + +constexpr int kEmptyFd = -1; + +class UniqueFd { + public: + UniqueFd() = default; + explicit UniqueFd(int fd) : fd_(fd){}; + + auto Release [[nodiscard]] () -> int { + return std::exchange(fd_, kEmptyFd); + } + + auto Get [[nodiscard]] () const -> int { + return fd_; + } + + explicit operator bool() const { + return fd_ != kEmptyFd; + } + + ~UniqueFd() { + Set(kEmptyFd); + } + + /* Allow move semantics */ + UniqueFd(UniqueFd &&rhs) noexcept { + Set(rhs.Release()); + } + + auto operator=(UniqueFd &&rhs) noexcept -> UniqueFd & { + Set(rhs.Release()); + return *this; + } + + /* Disable copy semantics */ + UniqueFd(const UniqueFd &) = delete; + auto operator=(const UniqueFd &) = delete; + + private: + void Set(int new_fd) { + if (fd_ != kEmptyFd) { + close(fd_); + } + fd_ = new_fd; + } + + int fd_ = kEmptyFd; +}; + +} // namespace android + +#endif diff --git a/utils/Worker.cpp b/utils/Worker.cpp index 1f30588..d2b60c8 100644 --- a/utils/Worker.cpp +++ b/utils/Worker.cpp @@ -34,8 +34,7 @@ int Worker::InitWorker() { if (initialized()) return -EALREADY; - thread_ = std::unique_ptr<std::thread>( - new std::thread(&Worker::InternalRoutine, this)); + thread_ = std::make_unique<std::thread>(&Worker::InternalRoutine, this); initialized_ = true; exit_ = false; diff --git a/utils/Worker.h b/utils/Worker.h index 73a80da..ab01d5f 100644 --- a/utils/Worker.h +++ b/utils/Worker.h @@ -17,10 +17,9 @@ #ifndef ANDROID_WORKER_H_ #define ANDROID_WORKER_H_ -#include <stdint.h> -#include <stdlib.h> - #include <condition_variable> +#include <cstdint> +#include <cstdlib> #include <mutex> #include <string> #include <thread> diff --git a/utils/autolock.cpp b/utils/autolock.cpp deleted file mode 100644 index 4e9552a..0000000 --- a/utils/autolock.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2015 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define ATRACE_TAG ATRACE_TAG_GRAPHICS -#define LOG_TAG "hwc-drm-auto-lock" - -#include "autolock.h" - -#include <errno.h> -#include <pthread.h> - -#include <log/log.h> - -namespace android { - -int AutoLock::Lock() { - if (locked_) { - ALOGE("Invalid attempt to double lock AutoLock %s", name_); - return -EINVAL; - } - int ret = pthread_mutex_lock(mutex_); - if (ret) { - ALOGE("Failed to acquire %s lock %d", name_, ret); - return ret; - } - locked_ = true; - return 0; -} - -int AutoLock::Unlock() { - if (!locked_) { - ALOGE("Invalid attempt to unlock unlocked AutoLock %s", name_); - return -EINVAL; - } - int ret = pthread_mutex_unlock(mutex_); - if (ret) { - ALOGE("Failed to release %s lock %d", name_, ret); - return ret; - } - locked_ = false; - return 0; -} -} // namespace android diff --git a/utils/hwcutils.cpp b/utils/hwcutils.cpp index 322efce..c537b99 100644 --- a/utils/hwcutils.cpp +++ b/utils/hwcutils.cpp @@ -17,149 +17,33 @@ #define ATRACE_TAG ATRACE_TAG_GRAPHICS #define LOG_TAG "hwc-drm-utils" -#include <log/log.h> -#include <ui/Gralloc.h> -#include <ui/GraphicBufferMapper.h> +#include <utils/log.h> + +#include <cerrno> #include "bufferinfo/BufferInfoGetter.h" -#include "drm/DrmGenericImporter.h" +#include "drm/DrmFbImporter.h" #include "drmhwcomposer.h" -#define UNUSED(x) (void)(x) - namespace android { -const hwc_drm_bo *DrmHwcBuffer::operator->() const { - if (importer_ == NULL) { - ALOGE("Access of non-existent BO"); - exit(1); - return NULL; - } - return &bo_; -} - -void DrmHwcBuffer::Clear() { - if (importer_ != NULL) { - importer_->ReleaseBuffer(&bo_); - importer_ = NULL; - } -} - -int DrmHwcBuffer::ImportBuffer(buffer_handle_t handle, Importer *importer) { - hwc_drm_bo tmp_bo{}; +int DrmHwcLayer::ImportBuffer(DrmDevice *drm_device) { + buffer_info = hwc_drm_bo_t{}; - int ret = BufferInfoGetter::GetInstance()->ConvertBoInfo(handle, &tmp_bo); - if (ret) { + int ret = BufferInfoGetter::GetInstance()->ConvertBoInfo(sf_handle, + &buffer_info); + if (ret != 0) { ALOGE("Failed to convert buffer info %d", ret); return ret; } - ret = importer->ImportBuffer(&tmp_bo); - if (ret) { - ALOGE("Failed to import buffer %d", ret); - return ret; - } - - if (importer_ != NULL) { - importer_->ReleaseBuffer(&bo_); + fb_id_handle = drm_device->GetDrmFbImporter().GetOrCreateFbId(&buffer_info); + if (!fb_id_handle) { + ALOGE("Failed to import buffer"); + return -EINVAL; } - importer_ = importer; - - bo_ = tmp_bo; - - return 0; -} - -int DrmHwcNativeHandle::CopyBufferHandle(buffer_handle_t handle) { - native_handle_t *handle_copy; - GraphicBufferMapper &gm(GraphicBufferMapper::get()); - int ret; - - ret = gm.getGrallocMapper().importBuffer(handle, - const_cast<buffer_handle_t *>( - &handle_copy)); - - if (ret) { - ALOGE("Failed to import buffer handle %d", ret); - return ret; - } - - Clear(); - - handle_ = handle_copy; - return 0; } -DrmHwcNativeHandle::~DrmHwcNativeHandle() { - Clear(); -} - -void DrmHwcNativeHandle::Clear() { - if (handle_ != NULL) { - GraphicBufferMapper &gm(GraphicBufferMapper::get()); - int ret = gm.freeBuffer(handle_); - if (ret) { - ALOGE("Failed to free buffer handle %d", ret); - } - handle_ = NULL; - } -} - -int DrmHwcLayer::ImportBuffer(Importer *importer) { - int ret = buffer.ImportBuffer(sf_handle, importer); - if (ret) - return ret; - - const hwc_drm_bo *bo = buffer.operator->(); - - ret = handle.CopyBufferHandle(sf_handle); - if (ret) - return ret; - - gralloc_buffer_usage = bo->usage; - - return 0; -} - -int DrmHwcLayer::InitFromDrmHwcLayer(DrmHwcLayer *src_layer, - Importer *importer) { - blending = src_layer->blending; - sf_handle = src_layer->sf_handle; - acquire_fence = -1; - display_frame = src_layer->display_frame; - alpha = src_layer->alpha; - source_crop = src_layer->source_crop; - transform = src_layer->transform; - return ImportBuffer(importer); -} - -void DrmHwcLayer::SetSourceCrop(hwc_frect_t const &crop) { - source_crop = crop; -} - -void DrmHwcLayer::SetDisplayFrame(hwc_rect_t const &frame) { - display_frame = frame; -} - -void DrmHwcLayer::SetTransform(int32_t sf_transform) { - transform = 0; - // 270* and 180* cannot be combined with flips. More specifically, they - // already contain both horizontal and vertical flips, so those fields are - // redundant in this case. 90* rotation can be combined with either horizontal - // flip or vertical flip, so treat it differently - if (sf_transform == HWC_TRANSFORM_ROT_270) { - transform = DrmHwcTransform::kRotate270; - } else if (sf_transform == HWC_TRANSFORM_ROT_180) { - transform = DrmHwcTransform::kRotate180; - } else { - if (sf_transform & HWC_TRANSFORM_FLIP_H) - transform |= DrmHwcTransform::kFlipH; - if (sf_transform & HWC_TRANSFORM_FLIP_V) - transform |= DrmHwcTransform::kFlipV; - if (sf_transform & HWC_TRANSFORM_ROT_90) - transform |= DrmHwcTransform::kRotate90; - } -} } // namespace android diff --git a/utils/log.h b/utils/log.h new file mode 100644 index 0000000..a48d2e7 --- /dev/null +++ b/utils/log.h @@ -0,0 +1,26 @@ +#ifndef UTILS_LOG_H_ +#define UTILS_LOG_H_ + +#ifdef ANDROID + +#include <log/log.h> + +#else + +#include <cinttypes> +#include <cstdio> + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define ALOGE(args...) printf("ERR: " args) +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define ALOGW(args...) printf("WARN: " args) +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define ALOGI(args...) printf("INFO: " args) +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define ALOGD(args...) printf("DBG:" args) +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define ALOGV(args...) printf("VERBOSE: " args) + +#endif + +#endif
\ No newline at end of file diff --git a/utils/properties.h b/utils/properties.h new file mode 100644 index 0000000..0b49c61 --- /dev/null +++ b/utils/properties.h @@ -0,0 +1,29 @@ +#ifndef UTILS_PROPERTIES_H_ +#define UTILS_PROPERTIES_H_ + +#ifdef ANDROID + +#include <cutils/properties.h> + +#else + +#include <cstdio> +#include <cstdlib> +#include <cstring> + +// NOLINTNEXTLINE(readability-identifier-naming) +constexpr int PROPERTY_VALUE_MAX = 92; + +// NOLINTNEXTLINE(readability-identifier-naming) +auto inline property_get(const char *name, char *value, + const char *default_value) -> int { + // NOLINTNEXTLINE (concurrency-mt-unsafe) + char *prop = std::getenv(name); + snprintf(value, PROPERTY_VALUE_MAX, "%s", + (prop == nullptr) ? default_value : prop); + return static_cast<int>(strlen(value)); +} + +#endif + +#endif
\ No newline at end of file |